From 4080bfb45b86d5d03950809ac1759f90486e633e Mon Sep 17 00:00:00 2001 From: Wu-Hui Date: Thu, 6 Jun 2024 10:28:05 -0400 Subject: [PATCH 01/60] introduce pipeline proto changes --- dev/protos/firestore_v1_proto_api.d.ts | 404 ++++- dev/protos/firestore_v1_proto_api.js | 1343 ++++++++++++++--- dev/protos/google/firestore/v1/document.proto | 114 ++ .../google/firestore/v1/firestore.proto | 86 ++ dev/protos/google/firestore/v1/pipeline.proto | 41 + dev/protos/v1.json | 152 +- 6 files changed, 1958 insertions(+), 182 deletions(-) create mode 100644 dev/protos/google/firestore/v1/pipeline.proto diff --git a/dev/protos/firestore_v1_proto_api.d.ts b/dev/protos/firestore_v1_proto_api.d.ts index ac9a6bc1a..0d428b9ef 100644 --- a/dev/protos/firestore_v1_proto_api.d.ts +++ b/dev/protos/firestore_v1_proto_api.d.ts @@ -3921,6 +3921,15 @@ export namespace google { /** Value mapValue */ mapValue?: (google.firestore.v1.IMapValue|null); + + /** Value fieldReferenceValue */ + fieldReferenceValue?: (string|null); + + /** Value functionValue */ + functionValue?: (google.firestore.v1.IFunction|null); + + /** Value pipelineValue */ + pipelineValue?: (google.firestore.v1.IPipeline|null); } /** Represents a Value. */ @@ -3965,8 +3974,17 @@ export namespace google { /** Value mapValue. */ public mapValue?: (google.firestore.v1.IMapValue|null); + /** Value fieldReferenceValue. */ + public fieldReferenceValue?: (string|null); + + /** Value functionValue. */ + public functionValue?: (google.firestore.v1.IFunction|null); + + /** Value pipelineValue. */ + public pipelineValue?: (google.firestore.v1.IPipeline|null); + /** Value valueType. */ - public valueType?: ("nullValue"|"booleanValue"|"integerValue"|"doubleValue"|"timestampValue"|"stringValue"|"bytesValue"|"referenceValue"|"geoPointValue"|"arrayValue"|"mapValue"); + public valueType?: ("nullValue"|"booleanValue"|"integerValue"|"doubleValue"|"timestampValue"|"stringValue"|"bytesValue"|"referenceValue"|"geoPointValue"|"arrayValue"|"mapValue"|"fieldReferenceValue"|"functionValue"|"pipelineValue"); /** * Creates a Value message from a plain object. Also converts values to their respective internal types. @@ -4093,6 +4111,177 @@ export namespace google { public static getTypeUrl(typeUrlPrefix?: string): string; } + /** Properties of a Function. */ + interface IFunction { + + /** Function name */ + name?: (string|null); + + /** Function args */ + args?: (google.firestore.v1.IValue[]|null); + + /** Function options */ + options?: ({ [k: string]: google.firestore.v1.IValue }|null); + } + + /** Represents a Function. */ + class Function implements IFunction { + + /** + * Constructs a new Function. + * @param [properties] Properties to set + */ + constructor(properties?: google.firestore.v1.IFunction); + + /** Function name. */ + public name: string; + + /** Function args. */ + public args: google.firestore.v1.IValue[]; + + /** Function options. */ + public options: { [k: string]: google.firestore.v1.IValue }; + + /** + * Creates a Function message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns Function + */ + public static fromObject(object: { [k: string]: any }): google.firestore.v1.Function; + + /** + * Creates a plain object from a Function message. Also converts values to other types if specified. + * @param message Function + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.firestore.v1.Function, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this Function to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for Function + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a Pipeline. */ + interface IPipeline { + + /** Pipeline stages */ + stages?: (google.firestore.v1.Pipeline.IStage[]|null); + } + + /** Represents a Pipeline. */ + class Pipeline implements IPipeline { + + /** + * Constructs a new Pipeline. + * @param [properties] Properties to set + */ + constructor(properties?: google.firestore.v1.IPipeline); + + /** Pipeline stages. */ + public stages: google.firestore.v1.Pipeline.IStage[]; + + /** + * Creates a Pipeline message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns Pipeline + */ + public static fromObject(object: { [k: string]: any }): google.firestore.v1.Pipeline; + + /** + * Creates a plain object from a Pipeline message. Also converts values to other types if specified. + * @param message Pipeline + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.firestore.v1.Pipeline, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this Pipeline to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for Pipeline + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + namespace Pipeline { + + /** Properties of a Stage. */ + interface IStage { + + /** Stage name */ + name?: (string|null); + + /** Stage args */ + args?: (google.firestore.v1.IValue[]|null); + + /** Stage options */ + options?: ({ [k: string]: google.firestore.v1.IValue }|null); + } + + /** Represents a Stage. */ + class Stage implements IStage { + + /** + * Constructs a new Stage. + * @param [properties] Properties to set + */ + constructor(properties?: google.firestore.v1.Pipeline.IStage); + + /** Stage name. */ + public name: string; + + /** Stage args. */ + public args: google.firestore.v1.IValue[]; + + /** Stage options. */ + public options: { [k: string]: google.firestore.v1.IValue }; + + /** + * Creates a Stage message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns Stage + */ + public static fromObject(object: { [k: string]: any }): google.firestore.v1.Pipeline.Stage; + + /** + * Creates a plain object from a Stage message. Also converts values to other types if specified. + * @param message Stage + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.firestore.v1.Pipeline.Stage, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this Stage to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for Stage + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + } + /** Properties of a BitSequence. */ interface IBitSequence { @@ -4602,6 +4791,20 @@ export namespace google { */ public runQuery(request: google.firestore.v1.IRunQueryRequest): Promise; + /** + * Calls ExecutePipeline. + * @param request ExecutePipelineRequest message or plain object + * @param callback Node-style callback called with the error, if any, and ExecutePipelineResponse + */ + public executePipeline(request: google.firestore.v1.IExecutePipelineRequest, callback: google.firestore.v1.Firestore.ExecutePipelineCallback): void; + + /** + * Calls ExecutePipeline. + * @param request ExecutePipelineRequest message or plain object + * @returns Promise + */ + public executePipeline(request: google.firestore.v1.IExecutePipelineRequest): Promise; + /** * Calls RunAggregationQuery. * @param request RunAggregationQueryRequest message or plain object @@ -4766,6 +4969,13 @@ export namespace google { */ type RunQueryCallback = (error: (Error|null), response?: google.firestore.v1.RunQueryResponse) => void; + /** + * Callback as used by {@link google.firestore.v1.Firestore#executePipeline}. + * @param error Error, if any + * @param [response] ExecutePipelineResponse + */ + type ExecutePipelineCallback = (error: (Error|null), response?: google.firestore.v1.ExecutePipelineResponse) => void; + /** * Callback as used by {@link google.firestore.v1.Firestore#runAggregationQuery}. * @param error Error, if any @@ -5815,6 +6025,144 @@ export namespace google { public static getTypeUrl(typeUrlPrefix?: string): string; } + /** Properties of an ExecutePipelineRequest. */ + interface IExecutePipelineRequest { + + /** ExecutePipelineRequest database */ + database?: (string|null); + + /** ExecutePipelineRequest structuredPipeline */ + structuredPipeline?: (google.firestore.v1.IStructuredPipeline|null); + + /** ExecutePipelineRequest transaction */ + transaction?: (Uint8Array|null); + + /** ExecutePipelineRequest newTransaction */ + newTransaction?: (google.firestore.v1.ITransactionOptions|null); + + /** ExecutePipelineRequest readTime */ + readTime?: (google.protobuf.ITimestamp|null); + } + + /** Represents an ExecutePipelineRequest. */ + class ExecutePipelineRequest implements IExecutePipelineRequest { + + /** + * Constructs a new ExecutePipelineRequest. + * @param [properties] Properties to set + */ + constructor(properties?: google.firestore.v1.IExecutePipelineRequest); + + /** ExecutePipelineRequest database. */ + public database: string; + + /** ExecutePipelineRequest structuredPipeline. */ + public structuredPipeline?: (google.firestore.v1.IStructuredPipeline|null); + + /** ExecutePipelineRequest transaction. */ + public transaction?: (Uint8Array|null); + + /** ExecutePipelineRequest newTransaction. */ + public newTransaction?: (google.firestore.v1.ITransactionOptions|null); + + /** ExecutePipelineRequest readTime. */ + public readTime?: (google.protobuf.ITimestamp|null); + + /** ExecutePipelineRequest pipelineType. */ + public pipelineType?: "structuredPipeline"; + + /** ExecutePipelineRequest consistencySelector. */ + public consistencySelector?: ("transaction"|"newTransaction"|"readTime"); + + /** + * Creates an ExecutePipelineRequest message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns ExecutePipelineRequest + */ + public static fromObject(object: { [k: string]: any }): google.firestore.v1.ExecutePipelineRequest; + + /** + * Creates a plain object from an ExecutePipelineRequest message. Also converts values to other types if specified. + * @param message ExecutePipelineRequest + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.firestore.v1.ExecutePipelineRequest, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this ExecutePipelineRequest to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for ExecutePipelineRequest + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of an ExecutePipelineResponse. */ + interface IExecutePipelineResponse { + + /** ExecutePipelineResponse transaction */ + transaction?: (Uint8Array|null); + + /** ExecutePipelineResponse results */ + results?: (google.firestore.v1.IDocument[]|null); + + /** ExecutePipelineResponse executionTime */ + executionTime?: (google.protobuf.ITimestamp|null); + } + + /** Represents an ExecutePipelineResponse. */ + class ExecutePipelineResponse implements IExecutePipelineResponse { + + /** + * Constructs a new ExecutePipelineResponse. + * @param [properties] Properties to set + */ + constructor(properties?: google.firestore.v1.IExecutePipelineResponse); + + /** ExecutePipelineResponse transaction. */ + public transaction: Uint8Array; + + /** ExecutePipelineResponse results. */ + public results: google.firestore.v1.IDocument[]; + + /** ExecutePipelineResponse executionTime. */ + public executionTime?: (google.protobuf.ITimestamp|null); + + /** + * Creates an ExecutePipelineResponse message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns ExecutePipelineResponse + */ + public static fromObject(object: { [k: string]: any }): google.firestore.v1.ExecutePipelineResponse; + + /** + * Creates a plain object from an ExecutePipelineResponse message. Also converts values to other types if specified. + * @param message ExecutePipelineResponse + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.firestore.v1.ExecutePipelineResponse, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this ExecutePipelineResponse to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for ExecutePipelineResponse + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + /** Properties of a RunAggregationQueryRequest. */ interface IRunAggregationQueryRequest { @@ -6899,6 +7247,60 @@ export namespace google { public static getTypeUrl(typeUrlPrefix?: string): string; } + /** Properties of a StructuredPipeline. */ + interface IStructuredPipeline { + + /** StructuredPipeline pipeline */ + pipeline?: (google.firestore.v1.IPipeline|null); + + /** StructuredPipeline options */ + options?: ({ [k: string]: google.firestore.v1.IValue }|null); + } + + /** Represents a StructuredPipeline. */ + class StructuredPipeline implements IStructuredPipeline { + + /** + * Constructs a new StructuredPipeline. + * @param [properties] Properties to set + */ + constructor(properties?: google.firestore.v1.IStructuredPipeline); + + /** StructuredPipeline pipeline. */ + public pipeline?: (google.firestore.v1.IPipeline|null); + + /** StructuredPipeline options. */ + public options: { [k: string]: google.firestore.v1.IValue }; + + /** + * Creates a StructuredPipeline message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns StructuredPipeline + */ + public static fromObject(object: { [k: string]: any }): google.firestore.v1.StructuredPipeline; + + /** + * Creates a plain object from a StructuredPipeline message. Also converts values to other types if specified. + * @param message StructuredPipeline + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.firestore.v1.StructuredPipeline, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this StructuredPipeline to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for StructuredPipeline + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + /** Properties of a StructuredQuery. */ interface IStructuredQuery { diff --git a/dev/protos/firestore_v1_proto_api.js b/dev/protos/firestore_v1_proto_api.js index c4a08c1f1..a123ad6d9 100644 --- a/dev/protos/firestore_v1_proto_api.js +++ b/dev/protos/firestore_v1_proto_api.js @@ -10212,6 +10212,9 @@ * @property {google.type.ILatLng|null} [geoPointValue] Value geoPointValue * @property {google.firestore.v1.IArrayValue|null} [arrayValue] Value arrayValue * @property {google.firestore.v1.IMapValue|null} [mapValue] Value mapValue + * @property {string|null} [fieldReferenceValue] Value fieldReferenceValue + * @property {google.firestore.v1.IFunction|null} [functionValue] Value functionValue + * @property {google.firestore.v1.IPipeline|null} [pipelineValue] Value pipelineValue */ /** @@ -10317,17 +10320,41 @@ */ Value.prototype.mapValue = null; + /** + * Value fieldReferenceValue. + * @member {string|null|undefined} fieldReferenceValue + * @memberof google.firestore.v1.Value + * @instance + */ + Value.prototype.fieldReferenceValue = null; + + /** + * Value functionValue. + * @member {google.firestore.v1.IFunction|null|undefined} functionValue + * @memberof google.firestore.v1.Value + * @instance + */ + Value.prototype.functionValue = null; + + /** + * Value pipelineValue. + * @member {google.firestore.v1.IPipeline|null|undefined} pipelineValue + * @memberof google.firestore.v1.Value + * @instance + */ + Value.prototype.pipelineValue = null; + // OneOf field names bound to virtual getters and setters var $oneOfFields; /** * Value valueType. - * @member {"nullValue"|"booleanValue"|"integerValue"|"doubleValue"|"timestampValue"|"stringValue"|"bytesValue"|"referenceValue"|"geoPointValue"|"arrayValue"|"mapValue"|undefined} valueType + * @member {"nullValue"|"booleanValue"|"integerValue"|"doubleValue"|"timestampValue"|"stringValue"|"bytesValue"|"referenceValue"|"geoPointValue"|"arrayValue"|"mapValue"|"fieldReferenceValue"|"functionValue"|"pipelineValue"|undefined} valueType * @memberof google.firestore.v1.Value * @instance */ Object.defineProperty(Value.prototype, "valueType", { - get: $util.oneOfGetter($oneOfFields = ["nullValue", "booleanValue", "integerValue", "doubleValue", "timestampValue", "stringValue", "bytesValue", "referenceValue", "geoPointValue", "arrayValue", "mapValue"]), + get: $util.oneOfGetter($oneOfFields = ["nullValue", "booleanValue", "integerValue", "doubleValue", "timestampValue", "stringValue", "bytesValue", "referenceValue", "geoPointValue", "arrayValue", "mapValue", "fieldReferenceValue", "functionValue", "pipelineValue"]), set: $util.oneOfSetter($oneOfFields) }); @@ -10397,6 +10424,18 @@ throw TypeError(".google.firestore.v1.Value.mapValue: object expected"); message.mapValue = $root.google.firestore.v1.MapValue.fromObject(object.mapValue); } + if (object.fieldReferenceValue != null) + message.fieldReferenceValue = String(object.fieldReferenceValue); + if (object.functionValue != null) { + if (typeof object.functionValue !== "object") + throw TypeError(".google.firestore.v1.Value.functionValue: object expected"); + message.functionValue = $root.google.firestore.v1.Function.fromObject(object.functionValue); + } + if (object.pipelineValue != null) { + if (typeof object.pipelineValue !== "object") + throw TypeError(".google.firestore.v1.Value.pipelineValue: object expected"); + message.pipelineValue = $root.google.firestore.v1.Pipeline.fromObject(object.pipelineValue); + } return message; }; @@ -10471,6 +10510,21 @@ if (options.oneofs) object.valueType = "bytesValue"; } + if (message.fieldReferenceValue != null && message.hasOwnProperty("fieldReferenceValue")) { + object.fieldReferenceValue = message.fieldReferenceValue; + if (options.oneofs) + object.valueType = "fieldReferenceValue"; + } + if (message.functionValue != null && message.hasOwnProperty("functionValue")) { + object.functionValue = $root.google.firestore.v1.Function.toObject(message.functionValue, options); + if (options.oneofs) + object.valueType = "functionValue"; + } + if (message.pipelineValue != null && message.hasOwnProperty("pipelineValue")) { + object.pipelineValue = $root.google.firestore.v1.Pipeline.toObject(message.pipelineValue, options); + if (options.oneofs) + object.valueType = "pipelineValue"; + } return object; }; @@ -10724,6 +10778,422 @@ return MapValue; })(); + v1.Function = (function() { + + /** + * Properties of a Function. + * @memberof google.firestore.v1 + * @interface IFunction + * @property {string|null} [name] Function name + * @property {Array.|null} [args] Function args + * @property {Object.|null} [options] Function options + */ + + /** + * Constructs a new Function. + * @memberof google.firestore.v1 + * @classdesc Represents a Function. + * @implements IFunction + * @constructor + * @param {google.firestore.v1.IFunction=} [properties] Properties to set + */ + function Function(properties) { + this.args = []; + this.options = {}; + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } + + /** + * Function name. + * @member {string} name + * @memberof google.firestore.v1.Function + * @instance + */ + Function.prototype.name = ""; + + /** + * Function args. + * @member {Array.} args + * @memberof google.firestore.v1.Function + * @instance + */ + Function.prototype.args = $util.emptyArray; + + /** + * Function options. + * @member {Object.} options + * @memberof google.firestore.v1.Function + * @instance + */ + Function.prototype.options = $util.emptyObject; + + /** + * Creates a Function message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.firestore.v1.Function + * @static + * @param {Object.} object Plain object + * @returns {google.firestore.v1.Function} Function + */ + Function.fromObject = function fromObject(object) { + if (object instanceof $root.google.firestore.v1.Function) + return object; + var message = new $root.google.firestore.v1.Function(); + if (object.name != null) + message.name = String(object.name); + if (object.args) { + if (!Array.isArray(object.args)) + throw TypeError(".google.firestore.v1.Function.args: array expected"); + message.args = []; + for (var i = 0; i < object.args.length; ++i) { + if (typeof object.args[i] !== "object") + throw TypeError(".google.firestore.v1.Function.args: object expected"); + message.args[i] = $root.google.firestore.v1.Value.fromObject(object.args[i]); + } + } + if (object.options) { + if (typeof object.options !== "object") + throw TypeError(".google.firestore.v1.Function.options: object expected"); + message.options = {}; + for (var keys = Object.keys(object.options), i = 0; i < keys.length; ++i) { + if (typeof object.options[keys[i]] !== "object") + throw TypeError(".google.firestore.v1.Function.options: object expected"); + message.options[keys[i]] = $root.google.firestore.v1.Value.fromObject(object.options[keys[i]]); + } + } + return message; + }; + + /** + * Creates a plain object from a Function message. Also converts values to other types if specified. + * @function toObject + * @memberof google.firestore.v1.Function + * @static + * @param {google.firestore.v1.Function} message Function + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + Function.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.arrays || options.defaults) + object.args = []; + if (options.objects || options.defaults) + object.options = {}; + if (options.defaults) + object.name = ""; + if (message.name != null && message.hasOwnProperty("name")) + object.name = message.name; + if (message.args && message.args.length) { + object.args = []; + for (var j = 0; j < message.args.length; ++j) + object.args[j] = $root.google.firestore.v1.Value.toObject(message.args[j], options); + } + var keys2; + if (message.options && (keys2 = Object.keys(message.options)).length) { + object.options = {}; + for (var j = 0; j < keys2.length; ++j) + object.options[keys2[j]] = $root.google.firestore.v1.Value.toObject(message.options[keys2[j]], options); + } + return object; + }; + + /** + * Converts this Function to JSON. + * @function toJSON + * @memberof google.firestore.v1.Function + * @instance + * @returns {Object.} JSON object + */ + Function.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + + /** + * Gets the default type url for Function + * @function getTypeUrl + * @memberof google.firestore.v1.Function + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + Function.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.firestore.v1.Function"; + }; + + return Function; + })(); + + v1.Pipeline = (function() { + + /** + * Properties of a Pipeline. + * @memberof google.firestore.v1 + * @interface IPipeline + * @property {Array.|null} [stages] Pipeline stages + */ + + /** + * Constructs a new Pipeline. + * @memberof google.firestore.v1 + * @classdesc Represents a Pipeline. + * @implements IPipeline + * @constructor + * @param {google.firestore.v1.IPipeline=} [properties] Properties to set + */ + function Pipeline(properties) { + this.stages = []; + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } + + /** + * Pipeline stages. + * @member {Array.} stages + * @memberof google.firestore.v1.Pipeline + * @instance + */ + Pipeline.prototype.stages = $util.emptyArray; + + /** + * Creates a Pipeline message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.firestore.v1.Pipeline + * @static + * @param {Object.} object Plain object + * @returns {google.firestore.v1.Pipeline} Pipeline + */ + Pipeline.fromObject = function fromObject(object) { + if (object instanceof $root.google.firestore.v1.Pipeline) + return object; + var message = new $root.google.firestore.v1.Pipeline(); + if (object.stages) { + if (!Array.isArray(object.stages)) + throw TypeError(".google.firestore.v1.Pipeline.stages: array expected"); + message.stages = []; + for (var i = 0; i < object.stages.length; ++i) { + if (typeof object.stages[i] !== "object") + throw TypeError(".google.firestore.v1.Pipeline.stages: object expected"); + message.stages[i] = $root.google.firestore.v1.Pipeline.Stage.fromObject(object.stages[i]); + } + } + return message; + }; + + /** + * Creates a plain object from a Pipeline message. Also converts values to other types if specified. + * @function toObject + * @memberof google.firestore.v1.Pipeline + * @static + * @param {google.firestore.v1.Pipeline} message Pipeline + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + Pipeline.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.arrays || options.defaults) + object.stages = []; + if (message.stages && message.stages.length) { + object.stages = []; + for (var j = 0; j < message.stages.length; ++j) + object.stages[j] = $root.google.firestore.v1.Pipeline.Stage.toObject(message.stages[j], options); + } + return object; + }; + + /** + * Converts this Pipeline to JSON. + * @function toJSON + * @memberof google.firestore.v1.Pipeline + * @instance + * @returns {Object.} JSON object + */ + Pipeline.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + + /** + * Gets the default type url for Pipeline + * @function getTypeUrl + * @memberof google.firestore.v1.Pipeline + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + Pipeline.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.firestore.v1.Pipeline"; + }; + + Pipeline.Stage = (function() { + + /** + * Properties of a Stage. + * @memberof google.firestore.v1.Pipeline + * @interface IStage + * @property {string|null} [name] Stage name + * @property {Array.|null} [args] Stage args + * @property {Object.|null} [options] Stage options + */ + + /** + * Constructs a new Stage. + * @memberof google.firestore.v1.Pipeline + * @classdesc Represents a Stage. + * @implements IStage + * @constructor + * @param {google.firestore.v1.Pipeline.IStage=} [properties] Properties to set + */ + function Stage(properties) { + this.args = []; + this.options = {}; + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } + + /** + * Stage name. + * @member {string} name + * @memberof google.firestore.v1.Pipeline.Stage + * @instance + */ + Stage.prototype.name = ""; + + /** + * Stage args. + * @member {Array.} args + * @memberof google.firestore.v1.Pipeline.Stage + * @instance + */ + Stage.prototype.args = $util.emptyArray; + + /** + * Stage options. + * @member {Object.} options + * @memberof google.firestore.v1.Pipeline.Stage + * @instance + */ + Stage.prototype.options = $util.emptyObject; + + /** + * Creates a Stage message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.firestore.v1.Pipeline.Stage + * @static + * @param {Object.} object Plain object + * @returns {google.firestore.v1.Pipeline.Stage} Stage + */ + Stage.fromObject = function fromObject(object) { + if (object instanceof $root.google.firestore.v1.Pipeline.Stage) + return object; + var message = new $root.google.firestore.v1.Pipeline.Stage(); + if (object.name != null) + message.name = String(object.name); + if (object.args) { + if (!Array.isArray(object.args)) + throw TypeError(".google.firestore.v1.Pipeline.Stage.args: array expected"); + message.args = []; + for (var i = 0; i < object.args.length; ++i) { + if (typeof object.args[i] !== "object") + throw TypeError(".google.firestore.v1.Pipeline.Stage.args: object expected"); + message.args[i] = $root.google.firestore.v1.Value.fromObject(object.args[i]); + } + } + if (object.options) { + if (typeof object.options !== "object") + throw TypeError(".google.firestore.v1.Pipeline.Stage.options: object expected"); + message.options = {}; + for (var keys = Object.keys(object.options), i = 0; i < keys.length; ++i) { + if (typeof object.options[keys[i]] !== "object") + throw TypeError(".google.firestore.v1.Pipeline.Stage.options: object expected"); + message.options[keys[i]] = $root.google.firestore.v1.Value.fromObject(object.options[keys[i]]); + } + } + return message; + }; + + /** + * Creates a plain object from a Stage message. Also converts values to other types if specified. + * @function toObject + * @memberof google.firestore.v1.Pipeline.Stage + * @static + * @param {google.firestore.v1.Pipeline.Stage} message Stage + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + Stage.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.arrays || options.defaults) + object.args = []; + if (options.objects || options.defaults) + object.options = {}; + if (options.defaults) + object.name = ""; + if (message.name != null && message.hasOwnProperty("name")) + object.name = message.name; + if (message.args && message.args.length) { + object.args = []; + for (var j = 0; j < message.args.length; ++j) + object.args[j] = $root.google.firestore.v1.Value.toObject(message.args[j], options); + } + var keys2; + if (message.options && (keys2 = Object.keys(message.options)).length) { + object.options = {}; + for (var j = 0; j < keys2.length; ++j) + object.options[keys2[j]] = $root.google.firestore.v1.Value.toObject(message.options[keys2[j]], options); + } + return object; + }; + + /** + * Converts this Stage to JSON. + * @function toJSON + * @memberof google.firestore.v1.Pipeline.Stage + * @instance + * @returns {Object.} JSON object + */ + Stage.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + + /** + * Gets the default type url for Stage + * @function getTypeUrl + * @memberof google.firestore.v1.Pipeline.Stage + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + Stage.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.firestore.v1.Pipeline.Stage"; + }; + + return Stage; + })(); + + return Pipeline; + })(); + v1.BitSequence = (function() { /** @@ -11875,20 +12345,53 @@ */ /** - * Callback as used by {@link google.firestore.v1.Firestore#runAggregationQuery}. + * Callback as used by {@link google.firestore.v1.Firestore#executePipeline}. * @memberof google.firestore.v1.Firestore - * @typedef RunAggregationQueryCallback + * @typedef ExecutePipelineCallback * @type {function} * @param {Error|null} error Error, if any - * @param {google.firestore.v1.RunAggregationQueryResponse} [response] RunAggregationQueryResponse + * @param {google.firestore.v1.ExecutePipelineResponse} [response] ExecutePipelineResponse */ /** - * Calls RunAggregationQuery. - * @function runAggregationQuery + * Calls ExecutePipeline. + * @function executePipeline * @memberof google.firestore.v1.Firestore * @instance - * @param {google.firestore.v1.IRunAggregationQueryRequest} request RunAggregationQueryRequest message or plain object + * @param {google.firestore.v1.IExecutePipelineRequest} request ExecutePipelineRequest message or plain object + * @param {google.firestore.v1.Firestore.ExecutePipelineCallback} callback Node-style callback called with the error, if any, and ExecutePipelineResponse + * @returns {undefined} + * @variation 1 + */ + Object.defineProperty(Firestore.prototype.executePipeline = function executePipeline(request, callback) { + return this.rpcCall(executePipeline, $root.google.firestore.v1.ExecutePipelineRequest, $root.google.firestore.v1.ExecutePipelineResponse, request, callback); + }, "name", { value: "ExecutePipeline" }); + + /** + * Calls ExecutePipeline. + * @function executePipeline + * @memberof google.firestore.v1.Firestore + * @instance + * @param {google.firestore.v1.IExecutePipelineRequest} request ExecutePipelineRequest message or plain object + * @returns {Promise} Promise + * @variation 2 + */ + + /** + * Callback as used by {@link google.firestore.v1.Firestore#runAggregationQuery}. + * @memberof google.firestore.v1.Firestore + * @typedef RunAggregationQueryCallback + * @type {function} + * @param {Error|null} error Error, if any + * @param {google.firestore.v1.RunAggregationQueryResponse} [response] RunAggregationQueryResponse + */ + + /** + * Calls RunAggregationQuery. + * @function runAggregationQuery + * @memberof google.firestore.v1.Firestore + * @instance + * @param {google.firestore.v1.IRunAggregationQueryRequest} request RunAggregationQueryRequest message or plain object * @param {google.firestore.v1.Firestore.RunAggregationQueryCallback} callback Node-style callback called with the error, if any, and RunAggregationQueryResponse * @returns {undefined} * @variation 1 @@ -14138,64 +14641,475 @@ RunQueryRequest.prototype.newTransaction = null; /** - * RunQueryRequest readTime. - * @member {google.protobuf.ITimestamp|null|undefined} readTime - * @memberof google.firestore.v1.RunQueryRequest + * RunQueryRequest readTime. + * @member {google.protobuf.ITimestamp|null|undefined} readTime + * @memberof google.firestore.v1.RunQueryRequest + * @instance + */ + RunQueryRequest.prototype.readTime = null; + + /** + * RunQueryRequest explainOptions. + * @member {google.firestore.v1.IExplainOptions|null|undefined} explainOptions + * @memberof google.firestore.v1.RunQueryRequest + * @instance + */ + RunQueryRequest.prototype.explainOptions = null; + + // OneOf field names bound to virtual getters and setters + var $oneOfFields; + + /** + * RunQueryRequest queryType. + * @member {"structuredQuery"|undefined} queryType + * @memberof google.firestore.v1.RunQueryRequest + * @instance + */ + Object.defineProperty(RunQueryRequest.prototype, "queryType", { + get: $util.oneOfGetter($oneOfFields = ["structuredQuery"]), + set: $util.oneOfSetter($oneOfFields) + }); + + /** + * RunQueryRequest consistencySelector. + * @member {"transaction"|"newTransaction"|"readTime"|undefined} consistencySelector + * @memberof google.firestore.v1.RunQueryRequest + * @instance + */ + Object.defineProperty(RunQueryRequest.prototype, "consistencySelector", { + get: $util.oneOfGetter($oneOfFields = ["transaction", "newTransaction", "readTime"]), + set: $util.oneOfSetter($oneOfFields) + }); + + /** + * Creates a RunQueryRequest message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.firestore.v1.RunQueryRequest + * @static + * @param {Object.} object Plain object + * @returns {google.firestore.v1.RunQueryRequest} RunQueryRequest + */ + RunQueryRequest.fromObject = function fromObject(object) { + if (object instanceof $root.google.firestore.v1.RunQueryRequest) + return object; + var message = new $root.google.firestore.v1.RunQueryRequest(); + if (object.parent != null) + message.parent = String(object.parent); + if (object.structuredQuery != null) { + if (typeof object.structuredQuery !== "object") + throw TypeError(".google.firestore.v1.RunQueryRequest.structuredQuery: object expected"); + message.structuredQuery = $root.google.firestore.v1.StructuredQuery.fromObject(object.structuredQuery); + } + if (object.transaction != null) + if (typeof object.transaction === "string") + $util.base64.decode(object.transaction, message.transaction = $util.newBuffer($util.base64.length(object.transaction)), 0); + else if (object.transaction.length >= 0) + message.transaction = object.transaction; + if (object.newTransaction != null) { + if (typeof object.newTransaction !== "object") + throw TypeError(".google.firestore.v1.RunQueryRequest.newTransaction: object expected"); + message.newTransaction = $root.google.firestore.v1.TransactionOptions.fromObject(object.newTransaction); + } + if (object.readTime != null) { + if (typeof object.readTime !== "object") + throw TypeError(".google.firestore.v1.RunQueryRequest.readTime: object expected"); + message.readTime = $root.google.protobuf.Timestamp.fromObject(object.readTime); + } + if (object.explainOptions != null) { + if (typeof object.explainOptions !== "object") + throw TypeError(".google.firestore.v1.RunQueryRequest.explainOptions: object expected"); + message.explainOptions = $root.google.firestore.v1.ExplainOptions.fromObject(object.explainOptions); + } + return message; + }; + + /** + * Creates a plain object from a RunQueryRequest message. Also converts values to other types if specified. + * @function toObject + * @memberof google.firestore.v1.RunQueryRequest + * @static + * @param {google.firestore.v1.RunQueryRequest} message RunQueryRequest + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + RunQueryRequest.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.defaults) { + object.parent = ""; + object.explainOptions = null; + } + if (message.parent != null && message.hasOwnProperty("parent")) + object.parent = message.parent; + if (message.structuredQuery != null && message.hasOwnProperty("structuredQuery")) { + object.structuredQuery = $root.google.firestore.v1.StructuredQuery.toObject(message.structuredQuery, options); + if (options.oneofs) + object.queryType = "structuredQuery"; + } + if (message.transaction != null && message.hasOwnProperty("transaction")) { + object.transaction = options.bytes === String ? $util.base64.encode(message.transaction, 0, message.transaction.length) : options.bytes === Array ? Array.prototype.slice.call(message.transaction) : message.transaction; + if (options.oneofs) + object.consistencySelector = "transaction"; + } + if (message.newTransaction != null && message.hasOwnProperty("newTransaction")) { + object.newTransaction = $root.google.firestore.v1.TransactionOptions.toObject(message.newTransaction, options); + if (options.oneofs) + object.consistencySelector = "newTransaction"; + } + if (message.readTime != null && message.hasOwnProperty("readTime")) { + object.readTime = $root.google.protobuf.Timestamp.toObject(message.readTime, options); + if (options.oneofs) + object.consistencySelector = "readTime"; + } + if (message.explainOptions != null && message.hasOwnProperty("explainOptions")) + object.explainOptions = $root.google.firestore.v1.ExplainOptions.toObject(message.explainOptions, options); + return object; + }; + + /** + * Converts this RunQueryRequest to JSON. + * @function toJSON + * @memberof google.firestore.v1.RunQueryRequest + * @instance + * @returns {Object.} JSON object + */ + RunQueryRequest.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + + /** + * Gets the default type url for RunQueryRequest + * @function getTypeUrl + * @memberof google.firestore.v1.RunQueryRequest + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + RunQueryRequest.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.firestore.v1.RunQueryRequest"; + }; + + return RunQueryRequest; + })(); + + v1.RunQueryResponse = (function() { + + /** + * Properties of a RunQueryResponse. + * @memberof google.firestore.v1 + * @interface IRunQueryResponse + * @property {Uint8Array|null} [transaction] RunQueryResponse transaction + * @property {google.firestore.v1.IDocument|null} [document] RunQueryResponse document + * @property {google.protobuf.ITimestamp|null} [readTime] RunQueryResponse readTime + * @property {number|null} [skippedResults] RunQueryResponse skippedResults + * @property {boolean|null} [done] RunQueryResponse done + * @property {google.firestore.v1.IExplainMetrics|null} [explainMetrics] RunQueryResponse explainMetrics + */ + + /** + * Constructs a new RunQueryResponse. + * @memberof google.firestore.v1 + * @classdesc Represents a RunQueryResponse. + * @implements IRunQueryResponse + * @constructor + * @param {google.firestore.v1.IRunQueryResponse=} [properties] Properties to set + */ + function RunQueryResponse(properties) { + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } + + /** + * RunQueryResponse transaction. + * @member {Uint8Array} transaction + * @memberof google.firestore.v1.RunQueryResponse + * @instance + */ + RunQueryResponse.prototype.transaction = $util.newBuffer([]); + + /** + * RunQueryResponse document. + * @member {google.firestore.v1.IDocument|null|undefined} document + * @memberof google.firestore.v1.RunQueryResponse + * @instance + */ + RunQueryResponse.prototype.document = null; + + /** + * RunQueryResponse readTime. + * @member {google.protobuf.ITimestamp|null|undefined} readTime + * @memberof google.firestore.v1.RunQueryResponse + * @instance + */ + RunQueryResponse.prototype.readTime = null; + + /** + * RunQueryResponse skippedResults. + * @member {number} skippedResults + * @memberof google.firestore.v1.RunQueryResponse + * @instance + */ + RunQueryResponse.prototype.skippedResults = 0; + + /** + * RunQueryResponse done. + * @member {boolean|null|undefined} done + * @memberof google.firestore.v1.RunQueryResponse + * @instance + */ + RunQueryResponse.prototype.done = null; + + /** + * RunQueryResponse explainMetrics. + * @member {google.firestore.v1.IExplainMetrics|null|undefined} explainMetrics + * @memberof google.firestore.v1.RunQueryResponse + * @instance + */ + RunQueryResponse.prototype.explainMetrics = null; + + // OneOf field names bound to virtual getters and setters + var $oneOfFields; + + /** + * RunQueryResponse continuationSelector. + * @member {"done"|undefined} continuationSelector + * @memberof google.firestore.v1.RunQueryResponse + * @instance + */ + Object.defineProperty(RunQueryResponse.prototype, "continuationSelector", { + get: $util.oneOfGetter($oneOfFields = ["done"]), + set: $util.oneOfSetter($oneOfFields) + }); + + /** + * Creates a RunQueryResponse message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.firestore.v1.RunQueryResponse + * @static + * @param {Object.} object Plain object + * @returns {google.firestore.v1.RunQueryResponse} RunQueryResponse + */ + RunQueryResponse.fromObject = function fromObject(object) { + if (object instanceof $root.google.firestore.v1.RunQueryResponse) + return object; + var message = new $root.google.firestore.v1.RunQueryResponse(); + if (object.transaction != null) + if (typeof object.transaction === "string") + $util.base64.decode(object.transaction, message.transaction = $util.newBuffer($util.base64.length(object.transaction)), 0); + else if (object.transaction.length >= 0) + message.transaction = object.transaction; + if (object.document != null) { + if (typeof object.document !== "object") + throw TypeError(".google.firestore.v1.RunQueryResponse.document: object expected"); + message.document = $root.google.firestore.v1.Document.fromObject(object.document); + } + if (object.readTime != null) { + if (typeof object.readTime !== "object") + throw TypeError(".google.firestore.v1.RunQueryResponse.readTime: object expected"); + message.readTime = $root.google.protobuf.Timestamp.fromObject(object.readTime); + } + if (object.skippedResults != null) + message.skippedResults = object.skippedResults | 0; + if (object.done != null) + message.done = Boolean(object.done); + if (object.explainMetrics != null) { + if (typeof object.explainMetrics !== "object") + throw TypeError(".google.firestore.v1.RunQueryResponse.explainMetrics: object expected"); + message.explainMetrics = $root.google.firestore.v1.ExplainMetrics.fromObject(object.explainMetrics); + } + return message; + }; + + /** + * Creates a plain object from a RunQueryResponse message. Also converts values to other types if specified. + * @function toObject + * @memberof google.firestore.v1.RunQueryResponse + * @static + * @param {google.firestore.v1.RunQueryResponse} message RunQueryResponse + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + RunQueryResponse.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.defaults) { + object.document = null; + if (options.bytes === String) + object.transaction = ""; + else { + object.transaction = []; + if (options.bytes !== Array) + object.transaction = $util.newBuffer(object.transaction); + } + object.readTime = null; + object.skippedResults = 0; + object.explainMetrics = null; + } + if (message.document != null && message.hasOwnProperty("document")) + object.document = $root.google.firestore.v1.Document.toObject(message.document, options); + if (message.transaction != null && message.hasOwnProperty("transaction")) + object.transaction = options.bytes === String ? $util.base64.encode(message.transaction, 0, message.transaction.length) : options.bytes === Array ? Array.prototype.slice.call(message.transaction) : message.transaction; + if (message.readTime != null && message.hasOwnProperty("readTime")) + object.readTime = $root.google.protobuf.Timestamp.toObject(message.readTime, options); + if (message.skippedResults != null && message.hasOwnProperty("skippedResults")) + object.skippedResults = message.skippedResults; + if (message.done != null && message.hasOwnProperty("done")) { + object.done = message.done; + if (options.oneofs) + object.continuationSelector = "done"; + } + if (message.explainMetrics != null && message.hasOwnProperty("explainMetrics")) + object.explainMetrics = $root.google.firestore.v1.ExplainMetrics.toObject(message.explainMetrics, options); + return object; + }; + + /** + * Converts this RunQueryResponse to JSON. + * @function toJSON + * @memberof google.firestore.v1.RunQueryResponse + * @instance + * @returns {Object.} JSON object + */ + RunQueryResponse.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + + /** + * Gets the default type url for RunQueryResponse + * @function getTypeUrl + * @memberof google.firestore.v1.RunQueryResponse + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + RunQueryResponse.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.firestore.v1.RunQueryResponse"; + }; + + return RunQueryResponse; + })(); + + v1.ExecutePipelineRequest = (function() { + + /** + * Properties of an ExecutePipelineRequest. + * @memberof google.firestore.v1 + * @interface IExecutePipelineRequest + * @property {string|null} [database] ExecutePipelineRequest database + * @property {google.firestore.v1.IStructuredPipeline|null} [structuredPipeline] ExecutePipelineRequest structuredPipeline + * @property {Uint8Array|null} [transaction] ExecutePipelineRequest transaction + * @property {google.firestore.v1.ITransactionOptions|null} [newTransaction] ExecutePipelineRequest newTransaction + * @property {google.protobuf.ITimestamp|null} [readTime] ExecutePipelineRequest readTime + */ + + /** + * Constructs a new ExecutePipelineRequest. + * @memberof google.firestore.v1 + * @classdesc Represents an ExecutePipelineRequest. + * @implements IExecutePipelineRequest + * @constructor + * @param {google.firestore.v1.IExecutePipelineRequest=} [properties] Properties to set + */ + function ExecutePipelineRequest(properties) { + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } + + /** + * ExecutePipelineRequest database. + * @member {string} database + * @memberof google.firestore.v1.ExecutePipelineRequest + * @instance + */ + ExecutePipelineRequest.prototype.database = ""; + + /** + * ExecutePipelineRequest structuredPipeline. + * @member {google.firestore.v1.IStructuredPipeline|null|undefined} structuredPipeline + * @memberof google.firestore.v1.ExecutePipelineRequest + * @instance + */ + ExecutePipelineRequest.prototype.structuredPipeline = null; + + /** + * ExecutePipelineRequest transaction. + * @member {Uint8Array|null|undefined} transaction + * @memberof google.firestore.v1.ExecutePipelineRequest + * @instance + */ + ExecutePipelineRequest.prototype.transaction = null; + + /** + * ExecutePipelineRequest newTransaction. + * @member {google.firestore.v1.ITransactionOptions|null|undefined} newTransaction + * @memberof google.firestore.v1.ExecutePipelineRequest * @instance */ - RunQueryRequest.prototype.readTime = null; + ExecutePipelineRequest.prototype.newTransaction = null; /** - * RunQueryRequest explainOptions. - * @member {google.firestore.v1.IExplainOptions|null|undefined} explainOptions - * @memberof google.firestore.v1.RunQueryRequest + * ExecutePipelineRequest readTime. + * @member {google.protobuf.ITimestamp|null|undefined} readTime + * @memberof google.firestore.v1.ExecutePipelineRequest * @instance */ - RunQueryRequest.prototype.explainOptions = null; + ExecutePipelineRequest.prototype.readTime = null; // OneOf field names bound to virtual getters and setters var $oneOfFields; /** - * RunQueryRequest queryType. - * @member {"structuredQuery"|undefined} queryType - * @memberof google.firestore.v1.RunQueryRequest + * ExecutePipelineRequest pipelineType. + * @member {"structuredPipeline"|undefined} pipelineType + * @memberof google.firestore.v1.ExecutePipelineRequest * @instance */ - Object.defineProperty(RunQueryRequest.prototype, "queryType", { - get: $util.oneOfGetter($oneOfFields = ["structuredQuery"]), + Object.defineProperty(ExecutePipelineRequest.prototype, "pipelineType", { + get: $util.oneOfGetter($oneOfFields = ["structuredPipeline"]), set: $util.oneOfSetter($oneOfFields) }); /** - * RunQueryRequest consistencySelector. + * ExecutePipelineRequest consistencySelector. * @member {"transaction"|"newTransaction"|"readTime"|undefined} consistencySelector - * @memberof google.firestore.v1.RunQueryRequest + * @memberof google.firestore.v1.ExecutePipelineRequest * @instance */ - Object.defineProperty(RunQueryRequest.prototype, "consistencySelector", { + Object.defineProperty(ExecutePipelineRequest.prototype, "consistencySelector", { get: $util.oneOfGetter($oneOfFields = ["transaction", "newTransaction", "readTime"]), set: $util.oneOfSetter($oneOfFields) }); /** - * Creates a RunQueryRequest message from a plain object. Also converts values to their respective internal types. + * Creates an ExecutePipelineRequest message from a plain object. Also converts values to their respective internal types. * @function fromObject - * @memberof google.firestore.v1.RunQueryRequest + * @memberof google.firestore.v1.ExecutePipelineRequest * @static * @param {Object.} object Plain object - * @returns {google.firestore.v1.RunQueryRequest} RunQueryRequest + * @returns {google.firestore.v1.ExecutePipelineRequest} ExecutePipelineRequest */ - RunQueryRequest.fromObject = function fromObject(object) { - if (object instanceof $root.google.firestore.v1.RunQueryRequest) + ExecutePipelineRequest.fromObject = function fromObject(object) { + if (object instanceof $root.google.firestore.v1.ExecutePipelineRequest) return object; - var message = new $root.google.firestore.v1.RunQueryRequest(); - if (object.parent != null) - message.parent = String(object.parent); - if (object.structuredQuery != null) { - if (typeof object.structuredQuery !== "object") - throw TypeError(".google.firestore.v1.RunQueryRequest.structuredQuery: object expected"); - message.structuredQuery = $root.google.firestore.v1.StructuredQuery.fromObject(object.structuredQuery); + var message = new $root.google.firestore.v1.ExecutePipelineRequest(); + if (object.database != null) + message.database = String(object.database); + if (object.structuredPipeline != null) { + if (typeof object.structuredPipeline !== "object") + throw TypeError(".google.firestore.v1.ExecutePipelineRequest.structuredPipeline: object expected"); + message.structuredPipeline = $root.google.firestore.v1.StructuredPipeline.fromObject(object.structuredPipeline); } if (object.transaction != null) if (typeof object.transaction === "string") @@ -14204,45 +15118,38 @@ message.transaction = object.transaction; if (object.newTransaction != null) { if (typeof object.newTransaction !== "object") - throw TypeError(".google.firestore.v1.RunQueryRequest.newTransaction: object expected"); + throw TypeError(".google.firestore.v1.ExecutePipelineRequest.newTransaction: object expected"); message.newTransaction = $root.google.firestore.v1.TransactionOptions.fromObject(object.newTransaction); } if (object.readTime != null) { if (typeof object.readTime !== "object") - throw TypeError(".google.firestore.v1.RunQueryRequest.readTime: object expected"); + throw TypeError(".google.firestore.v1.ExecutePipelineRequest.readTime: object expected"); message.readTime = $root.google.protobuf.Timestamp.fromObject(object.readTime); } - if (object.explainOptions != null) { - if (typeof object.explainOptions !== "object") - throw TypeError(".google.firestore.v1.RunQueryRequest.explainOptions: object expected"); - message.explainOptions = $root.google.firestore.v1.ExplainOptions.fromObject(object.explainOptions); - } return message; }; /** - * Creates a plain object from a RunQueryRequest message. Also converts values to other types if specified. + * Creates a plain object from an ExecutePipelineRequest message. Also converts values to other types if specified. * @function toObject - * @memberof google.firestore.v1.RunQueryRequest + * @memberof google.firestore.v1.ExecutePipelineRequest * @static - * @param {google.firestore.v1.RunQueryRequest} message RunQueryRequest + * @param {google.firestore.v1.ExecutePipelineRequest} message ExecutePipelineRequest * @param {$protobuf.IConversionOptions} [options] Conversion options * @returns {Object.} Plain object */ - RunQueryRequest.toObject = function toObject(message, options) { + ExecutePipelineRequest.toObject = function toObject(message, options) { if (!options) options = {}; var object = {}; - if (options.defaults) { - object.parent = ""; - object.explainOptions = null; - } - if (message.parent != null && message.hasOwnProperty("parent")) - object.parent = message.parent; - if (message.structuredQuery != null && message.hasOwnProperty("structuredQuery")) { - object.structuredQuery = $root.google.firestore.v1.StructuredQuery.toObject(message.structuredQuery, options); + if (options.defaults) + object.database = ""; + if (message.database != null && message.hasOwnProperty("database")) + object.database = message.database; + if (message.structuredPipeline != null && message.hasOwnProperty("structuredPipeline")) { + object.structuredPipeline = $root.google.firestore.v1.StructuredPipeline.toObject(message.structuredPipeline, options); if (options.oneofs) - object.queryType = "structuredQuery"; + object.pipelineType = "structuredPipeline"; } if (message.transaction != null && message.hasOwnProperty("transaction")) { object.transaction = options.bytes === String ? $util.base64.encode(message.transaction, 0, message.transaction.length) : options.bytes === Array ? Array.prototype.slice.call(message.transaction) : message.transaction; @@ -14259,63 +15166,59 @@ if (options.oneofs) object.consistencySelector = "readTime"; } - if (message.explainOptions != null && message.hasOwnProperty("explainOptions")) - object.explainOptions = $root.google.firestore.v1.ExplainOptions.toObject(message.explainOptions, options); return object; }; /** - * Converts this RunQueryRequest to JSON. + * Converts this ExecutePipelineRequest to JSON. * @function toJSON - * @memberof google.firestore.v1.RunQueryRequest + * @memberof google.firestore.v1.ExecutePipelineRequest * @instance * @returns {Object.} JSON object */ - RunQueryRequest.prototype.toJSON = function toJSON() { + ExecutePipelineRequest.prototype.toJSON = function toJSON() { return this.constructor.toObject(this, $protobuf.util.toJSONOptions); }; /** - * Gets the default type url for RunQueryRequest + * Gets the default type url for ExecutePipelineRequest * @function getTypeUrl - * @memberof google.firestore.v1.RunQueryRequest + * @memberof google.firestore.v1.ExecutePipelineRequest * @static * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") * @returns {string} The default type url */ - RunQueryRequest.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + ExecutePipelineRequest.getTypeUrl = function getTypeUrl(typeUrlPrefix) { if (typeUrlPrefix === undefined) { typeUrlPrefix = "type.googleapis.com"; } - return typeUrlPrefix + "/google.firestore.v1.RunQueryRequest"; + return typeUrlPrefix + "/google.firestore.v1.ExecutePipelineRequest"; }; - return RunQueryRequest; + return ExecutePipelineRequest; })(); - v1.RunQueryResponse = (function() { + v1.ExecutePipelineResponse = (function() { /** - * Properties of a RunQueryResponse. + * Properties of an ExecutePipelineResponse. * @memberof google.firestore.v1 - * @interface IRunQueryResponse - * @property {Uint8Array|null} [transaction] RunQueryResponse transaction - * @property {google.firestore.v1.IDocument|null} [document] RunQueryResponse document - * @property {google.protobuf.ITimestamp|null} [readTime] RunQueryResponse readTime - * @property {number|null} [skippedResults] RunQueryResponse skippedResults - * @property {boolean|null} [done] RunQueryResponse done - * @property {google.firestore.v1.IExplainMetrics|null} [explainMetrics] RunQueryResponse explainMetrics + * @interface IExecutePipelineResponse + * @property {Uint8Array|null} [transaction] ExecutePipelineResponse transaction + * @property {Array.|null} [results] ExecutePipelineResponse results + * @property {google.protobuf.ITimestamp|null} [executionTime] ExecutePipelineResponse executionTime */ /** - * Constructs a new RunQueryResponse. + * Constructs a new ExecutePipelineResponse. * @memberof google.firestore.v1 - * @classdesc Represents a RunQueryResponse. - * @implements IRunQueryResponse + * @classdesc Represents an ExecutePipelineResponse. + * @implements IExecutePipelineResponse * @constructor - * @param {google.firestore.v1.IRunQueryResponse=} [properties] Properties to set + * @param {google.firestore.v1.IExecutePipelineResponse=} [properties] Properties to set */ - function RunQueryResponse(properties) { + function ExecutePipelineResponse(properties) { + this.results = []; if (properties) for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) if (properties[keys[i]] != null) @@ -14323,121 +15226,80 @@ } /** - * RunQueryResponse transaction. + * ExecutePipelineResponse transaction. * @member {Uint8Array} transaction - * @memberof google.firestore.v1.RunQueryResponse - * @instance - */ - RunQueryResponse.prototype.transaction = $util.newBuffer([]); - - /** - * RunQueryResponse document. - * @member {google.firestore.v1.IDocument|null|undefined} document - * @memberof google.firestore.v1.RunQueryResponse - * @instance - */ - RunQueryResponse.prototype.document = null; - - /** - * RunQueryResponse readTime. - * @member {google.protobuf.ITimestamp|null|undefined} readTime - * @memberof google.firestore.v1.RunQueryResponse - * @instance - */ - RunQueryResponse.prototype.readTime = null; - - /** - * RunQueryResponse skippedResults. - * @member {number} skippedResults - * @memberof google.firestore.v1.RunQueryResponse - * @instance - */ - RunQueryResponse.prototype.skippedResults = 0; - - /** - * RunQueryResponse done. - * @member {boolean|null|undefined} done - * @memberof google.firestore.v1.RunQueryResponse + * @memberof google.firestore.v1.ExecutePipelineResponse * @instance */ - RunQueryResponse.prototype.done = null; + ExecutePipelineResponse.prototype.transaction = $util.newBuffer([]); /** - * RunQueryResponse explainMetrics. - * @member {google.firestore.v1.IExplainMetrics|null|undefined} explainMetrics - * @memberof google.firestore.v1.RunQueryResponse + * ExecutePipelineResponse results. + * @member {Array.} results + * @memberof google.firestore.v1.ExecutePipelineResponse * @instance */ - RunQueryResponse.prototype.explainMetrics = null; - - // OneOf field names bound to virtual getters and setters - var $oneOfFields; + ExecutePipelineResponse.prototype.results = $util.emptyArray; /** - * RunQueryResponse continuationSelector. - * @member {"done"|undefined} continuationSelector - * @memberof google.firestore.v1.RunQueryResponse + * ExecutePipelineResponse executionTime. + * @member {google.protobuf.ITimestamp|null|undefined} executionTime + * @memberof google.firestore.v1.ExecutePipelineResponse * @instance */ - Object.defineProperty(RunQueryResponse.prototype, "continuationSelector", { - get: $util.oneOfGetter($oneOfFields = ["done"]), - set: $util.oneOfSetter($oneOfFields) - }); + ExecutePipelineResponse.prototype.executionTime = null; /** - * Creates a RunQueryResponse message from a plain object. Also converts values to their respective internal types. + * Creates an ExecutePipelineResponse message from a plain object. Also converts values to their respective internal types. * @function fromObject - * @memberof google.firestore.v1.RunQueryResponse + * @memberof google.firestore.v1.ExecutePipelineResponse * @static * @param {Object.} object Plain object - * @returns {google.firestore.v1.RunQueryResponse} RunQueryResponse + * @returns {google.firestore.v1.ExecutePipelineResponse} ExecutePipelineResponse */ - RunQueryResponse.fromObject = function fromObject(object) { - if (object instanceof $root.google.firestore.v1.RunQueryResponse) + ExecutePipelineResponse.fromObject = function fromObject(object) { + if (object instanceof $root.google.firestore.v1.ExecutePipelineResponse) return object; - var message = new $root.google.firestore.v1.RunQueryResponse(); + var message = new $root.google.firestore.v1.ExecutePipelineResponse(); if (object.transaction != null) if (typeof object.transaction === "string") $util.base64.decode(object.transaction, message.transaction = $util.newBuffer($util.base64.length(object.transaction)), 0); else if (object.transaction.length >= 0) message.transaction = object.transaction; - if (object.document != null) { - if (typeof object.document !== "object") - throw TypeError(".google.firestore.v1.RunQueryResponse.document: object expected"); - message.document = $root.google.firestore.v1.Document.fromObject(object.document); - } - if (object.readTime != null) { - if (typeof object.readTime !== "object") - throw TypeError(".google.firestore.v1.RunQueryResponse.readTime: object expected"); - message.readTime = $root.google.protobuf.Timestamp.fromObject(object.readTime); + if (object.results) { + if (!Array.isArray(object.results)) + throw TypeError(".google.firestore.v1.ExecutePipelineResponse.results: array expected"); + message.results = []; + for (var i = 0; i < object.results.length; ++i) { + if (typeof object.results[i] !== "object") + throw TypeError(".google.firestore.v1.ExecutePipelineResponse.results: object expected"); + message.results[i] = $root.google.firestore.v1.Document.fromObject(object.results[i]); + } } - if (object.skippedResults != null) - message.skippedResults = object.skippedResults | 0; - if (object.done != null) - message.done = Boolean(object.done); - if (object.explainMetrics != null) { - if (typeof object.explainMetrics !== "object") - throw TypeError(".google.firestore.v1.RunQueryResponse.explainMetrics: object expected"); - message.explainMetrics = $root.google.firestore.v1.ExplainMetrics.fromObject(object.explainMetrics); + if (object.executionTime != null) { + if (typeof object.executionTime !== "object") + throw TypeError(".google.firestore.v1.ExecutePipelineResponse.executionTime: object expected"); + message.executionTime = $root.google.protobuf.Timestamp.fromObject(object.executionTime); } return message; }; /** - * Creates a plain object from a RunQueryResponse message. Also converts values to other types if specified. + * Creates a plain object from an ExecutePipelineResponse message. Also converts values to other types if specified. * @function toObject - * @memberof google.firestore.v1.RunQueryResponse + * @memberof google.firestore.v1.ExecutePipelineResponse * @static - * @param {google.firestore.v1.RunQueryResponse} message RunQueryResponse + * @param {google.firestore.v1.ExecutePipelineResponse} message ExecutePipelineResponse * @param {$protobuf.IConversionOptions} [options] Conversion options * @returns {Object.} Plain object */ - RunQueryResponse.toObject = function toObject(message, options) { + ExecutePipelineResponse.toObject = function toObject(message, options) { if (!options) options = {}; var object = {}; + if (options.arrays || options.defaults) + object.results = []; if (options.defaults) { - object.document = null; if (options.bytes === String) object.transaction = ""; else { @@ -14445,55 +15307,47 @@ if (options.bytes !== Array) object.transaction = $util.newBuffer(object.transaction); } - object.readTime = null; - object.skippedResults = 0; - object.explainMetrics = null; + object.executionTime = null; } - if (message.document != null && message.hasOwnProperty("document")) - object.document = $root.google.firestore.v1.Document.toObject(message.document, options); if (message.transaction != null && message.hasOwnProperty("transaction")) object.transaction = options.bytes === String ? $util.base64.encode(message.transaction, 0, message.transaction.length) : options.bytes === Array ? Array.prototype.slice.call(message.transaction) : message.transaction; - if (message.readTime != null && message.hasOwnProperty("readTime")) - object.readTime = $root.google.protobuf.Timestamp.toObject(message.readTime, options); - if (message.skippedResults != null && message.hasOwnProperty("skippedResults")) - object.skippedResults = message.skippedResults; - if (message.done != null && message.hasOwnProperty("done")) { - object.done = message.done; - if (options.oneofs) - object.continuationSelector = "done"; + if (message.results && message.results.length) { + object.results = []; + for (var j = 0; j < message.results.length; ++j) + object.results[j] = $root.google.firestore.v1.Document.toObject(message.results[j], options); } - if (message.explainMetrics != null && message.hasOwnProperty("explainMetrics")) - object.explainMetrics = $root.google.firestore.v1.ExplainMetrics.toObject(message.explainMetrics, options); + if (message.executionTime != null && message.hasOwnProperty("executionTime")) + object.executionTime = $root.google.protobuf.Timestamp.toObject(message.executionTime, options); return object; }; /** - * Converts this RunQueryResponse to JSON. + * Converts this ExecutePipelineResponse to JSON. * @function toJSON - * @memberof google.firestore.v1.RunQueryResponse + * @memberof google.firestore.v1.ExecutePipelineResponse * @instance * @returns {Object.} JSON object */ - RunQueryResponse.prototype.toJSON = function toJSON() { + ExecutePipelineResponse.prototype.toJSON = function toJSON() { return this.constructor.toObject(this, $protobuf.util.toJSONOptions); }; /** - * Gets the default type url for RunQueryResponse + * Gets the default type url for ExecutePipelineResponse * @function getTypeUrl - * @memberof google.firestore.v1.RunQueryResponse + * @memberof google.firestore.v1.ExecutePipelineResponse * @static * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") * @returns {string} The default type url */ - RunQueryResponse.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + ExecutePipelineResponse.getTypeUrl = function getTypeUrl(typeUrlPrefix) { if (typeUrlPrefix === undefined) { typeUrlPrefix = "type.googleapis.com"; } - return typeUrlPrefix + "/google.firestore.v1.RunQueryResponse"; + return typeUrlPrefix + "/google.firestore.v1.ExecutePipelineResponse"; }; - return RunQueryResponse; + return ExecutePipelineResponse; })(); v1.RunAggregationQueryRequest = (function() { @@ -17197,6 +18051,135 @@ return BatchWriteResponse; })(); + v1.StructuredPipeline = (function() { + + /** + * Properties of a StructuredPipeline. + * @memberof google.firestore.v1 + * @interface IStructuredPipeline + * @property {google.firestore.v1.IPipeline|null} [pipeline] StructuredPipeline pipeline + * @property {Object.|null} [options] StructuredPipeline options + */ + + /** + * Constructs a new StructuredPipeline. + * @memberof google.firestore.v1 + * @classdesc Represents a StructuredPipeline. + * @implements IStructuredPipeline + * @constructor + * @param {google.firestore.v1.IStructuredPipeline=} [properties] Properties to set + */ + function StructuredPipeline(properties) { + this.options = {}; + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } + + /** + * StructuredPipeline pipeline. + * @member {google.firestore.v1.IPipeline|null|undefined} pipeline + * @memberof google.firestore.v1.StructuredPipeline + * @instance + */ + StructuredPipeline.prototype.pipeline = null; + + /** + * StructuredPipeline options. + * @member {Object.} options + * @memberof google.firestore.v1.StructuredPipeline + * @instance + */ + StructuredPipeline.prototype.options = $util.emptyObject; + + /** + * Creates a StructuredPipeline message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.firestore.v1.StructuredPipeline + * @static + * @param {Object.} object Plain object + * @returns {google.firestore.v1.StructuredPipeline} StructuredPipeline + */ + StructuredPipeline.fromObject = function fromObject(object) { + if (object instanceof $root.google.firestore.v1.StructuredPipeline) + return object; + var message = new $root.google.firestore.v1.StructuredPipeline(); + if (object.pipeline != null) { + if (typeof object.pipeline !== "object") + throw TypeError(".google.firestore.v1.StructuredPipeline.pipeline: object expected"); + message.pipeline = $root.google.firestore.v1.Pipeline.fromObject(object.pipeline); + } + if (object.options) { + if (typeof object.options !== "object") + throw TypeError(".google.firestore.v1.StructuredPipeline.options: object expected"); + message.options = {}; + for (var keys = Object.keys(object.options), i = 0; i < keys.length; ++i) { + if (typeof object.options[keys[i]] !== "object") + throw TypeError(".google.firestore.v1.StructuredPipeline.options: object expected"); + message.options[keys[i]] = $root.google.firestore.v1.Value.fromObject(object.options[keys[i]]); + } + } + return message; + }; + + /** + * Creates a plain object from a StructuredPipeline message. Also converts values to other types if specified. + * @function toObject + * @memberof google.firestore.v1.StructuredPipeline + * @static + * @param {google.firestore.v1.StructuredPipeline} message StructuredPipeline + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + StructuredPipeline.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.objects || options.defaults) + object.options = {}; + if (options.defaults) + object.pipeline = null; + if (message.pipeline != null && message.hasOwnProperty("pipeline")) + object.pipeline = $root.google.firestore.v1.Pipeline.toObject(message.pipeline, options); + var keys2; + if (message.options && (keys2 = Object.keys(message.options)).length) { + object.options = {}; + for (var j = 0; j < keys2.length; ++j) + object.options[keys2[j]] = $root.google.firestore.v1.Value.toObject(message.options[keys2[j]], options); + } + return object; + }; + + /** + * Converts this StructuredPipeline to JSON. + * @function toJSON + * @memberof google.firestore.v1.StructuredPipeline + * @instance + * @returns {Object.} JSON object + */ + StructuredPipeline.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + + /** + * Gets the default type url for StructuredPipeline + * @function getTypeUrl + * @memberof google.firestore.v1.StructuredPipeline + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + StructuredPipeline.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.firestore.v1.StructuredPipeline"; + }; + + return StructuredPipeline; + })(); + v1.StructuredQuery = (function() { /** diff --git a/dev/protos/google/firestore/v1/document.proto b/dev/protos/google/firestore/v1/document.proto index 5ad6752aa..5348fe643 100644 --- a/dev/protos/google/firestore/v1/document.proto +++ b/dev/protos/google/firestore/v1/document.proto @@ -128,6 +128,50 @@ message Value { // A map value. MapValue map_value = 6; + + + // Value which references a field. + // + // This is considered relative (vs absolute) since it only refers to a field + // and not a field within a particular document. + // + // **Requires:** + // + // * Must follow [field reference][FieldReference.field_path] limitations. + // + // * Not allowed to be used when writing documents. + // + // (-- NOTE(batchik): long term, there is no reason this type should not be + // allowed to be used on the write path. --) + string field_reference_value = 19; + + // A value that represents an unevaluated expression. + // + // **Requires:** + // + // * Not allowed to be used when writing documents. + // + // (-- NOTE(batchik): similar to above, there is no reason to not allow + // storing expressions into the database, just no plan to support in + // the near term. + // + // This would actually be an interesting way to represent user-defined + // functions or more expressive rules-based systems. --) + Function function_value = 20; + + // A value that represents an unevaluated pipeline. + // + // **Requires:** + // + // * Not allowed to be used when writing documents. + // + // (-- NOTE(batchik): similar to above, there is no reason to not allow + // storing expressions into the database, just no plan to support in + // the near term. + // + // This would actually be an interesting way to represent user-defined + // functions or more expressive rules-based systems. --) + Pipeline pipeline_value = 21; } } @@ -147,3 +191,73 @@ message MapValue { // not exceed 1,500 bytes and cannot be empty. map fields = 1; } + +// Represents an unevaluated scalar expression. +// +// For example, the expression `like(user_name, "%alice%")` is represented as: +// +// ``` +// name: "like" +// args { field_reference: "user_name" } +// args { string_value: "%alice%" } +// ``` +// +// (-- api-linter: core::0123::resource-annotation=disabled +// aip.dev/not-precedent: this is not a One Platform API resource. --) +message Function { + // The name of the function to evaluate. + // + // **Requires:** + // + // * must be in snake case (lower case with underscore separator). + // + string name = 1; + + // Ordered list of arguments the given function expects. + repeated Value args = 2; + + // Optional named arguments that certain functions may support. + map options = 3; +} + +// A Firestore query represented as an ordered list of operations / stages. +message Pipeline { + // A single operation within a pipeline. + // + // A stage is made up of a unique name, and a list of arguments. The exact + // number of arguments & types is dependent on the stage type. + // + // To give an example, the stage `filter(state = "MD")` would be encoded as: + // + // ``` + // name: "filter" + // args { + // function_value { + // name: "eq" + // args { field_reference_value: "state" } + // args { string_value: "MD" } + // } + // } + // ``` + // + // See public documentation for the full list. + message Stage { + // The name of the stage to evaluate. + // + // **Requires:** + // + // * must be in snake case (lower case with underscore separator). + // + string name = 1; + + // Ordered list of arguments the given stage expects. + repeated Value args = 2; + + // Optional named arguments that certain functions may support. + map options = 3; + } + + // Ordered list of stages to evaluate. + repeated Stage stages = 1; +} + diff --git a/dev/protos/google/firestore/v1/firestore.proto b/dev/protos/google/firestore/v1/firestore.proto index 2ed6bf070..f8718bb67 100644 --- a/dev/protos/google/firestore/v1/firestore.proto +++ b/dev/protos/google/firestore/v1/firestore.proto @@ -22,6 +22,7 @@ import "google/api/field_behavior.proto"; import "google/firestore/v1/aggregation_result.proto"; import "google/firestore/v1/common.proto"; import "google/firestore/v1/document.proto"; +import "google/firestore/v1/pipeline.proto"; import "google/firestore/v1/query.proto"; import "google/firestore/v1/query_profile.proto"; import "google/firestore/v1/write.proto"; @@ -140,6 +141,15 @@ service Firestore { }; } + // Executes a pipeline query. + rpc ExecutePipeline(ExecutePipelineRequest) + returns (stream ExecutePipelineResponse) { + option (google.api.http) = { + post: "/v1beta1/{database=projects/*/databases/*}:executePipeline" + body: "*" + }; + } + // Runs an aggregation query. // // Rather than producing [Document][google.firestore.v1.Document] results like @@ -624,6 +634,82 @@ message RunQueryResponse { ExplainMetrics explain_metrics = 11; } +// The request for [Firestore.ExecutePipeline][]. +message ExecutePipelineRequest { + // Database identifier, in the form `projects/{project}/databases/{database}`. + string database = 1 [ + (google.api.field_behavior) = REQUIRED + ]; + + oneof pipeline_type { + // A pipelined operation. + StructuredPipeline structured_pipeline = 2; + } + + // Optional consistency arguments, defaults to strong consistency. + oneof consistency_selector { + // Run the query within an already active transaction. + // + // The value here is the opaque transaction ID to execute the query in. + bytes transaction = 5; + + // Execute the pipeline in a new transaction. + // + // The identifier of the newly created transaction will be returned in the + // first response on the stream. This defaults to a read-only transaction. + TransactionOptions new_transaction = 6; + + // Execute the pipeline in a snapshot transaction at the given time. + // + // This must be a microsecond precision timestamp within the past one hour, + // or if Point-in-Time Recovery is enabled, can additionally be a whole + // minute timestamp within the past 7 days. + google.protobuf.Timestamp read_time = 7; + } + + // Explain / analyze options for the pipeline. + // ExplainOptions explain_options = 8 [(google.api.field_behavior) = OPTIONAL]; +} + +// The response for [Firestore.Execute][]. +message ExecutePipelineResponse { + // Newly created transaction identifier. + // + // This field is only specified on the first response from the server when + // the request specified [ExecuteRequest.new_transaction][]. + bytes transaction = 1; + + // An ordered batch of results returned executing a pipeline. + // + // The batch size is variable, and can even be zero for when only a partial + // progress message is returned. + // + // The fields present in the returned documents are only those that were + // explicitly requested in the pipeline, this include those like + // [`__name__`][Document.name] & [`__update_time__`][Document.update_time]. + // This is explicitly a divergence from `Firestore.RunQuery` / + // `Firestore.GetDocument` RPCs which always return such fields even when they + // are not specified in the [`mask`][DocumentMask]. + repeated Document results = 2; + + // The time at which the document(s) were read. + // + // This may be monotonically increasing; in this case, the previous documents + // in the result stream are guaranteed not to have changed between their + // `execution_time` and this one. + // + // If the query returns no results, a response with `execution_time` and no + // `results` will be sent, and this represents the time at which the operation + // was run. + google.protobuf.Timestamp execution_time = 3; + + // Query explain metrics. + // + // Set on the last response when [ExecutePipelineRequest.explain_options][] + // was specified on the request. + // ExplainMetrics explain_metrics = 4; +} + // The request for // [Firestore.RunAggregationQuery][google.firestore.v1.Firestore.RunAggregationQuery]. message RunAggregationQueryRequest { diff --git a/dev/protos/google/firestore/v1/pipeline.proto b/dev/protos/google/firestore/v1/pipeline.proto new file mode 100644 index 000000000..ea5b23093 --- /dev/null +++ b/dev/protos/google/firestore/v1/pipeline.proto @@ -0,0 +1,41 @@ +/*! + * 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. + */ + +syntax = "proto3"; +package google.firestore.v1; +import "google/firestore/v1/document.proto"; +option csharp_namespace = "Google.Cloud.Firestore.V1"; +option php_namespace = "Google\\Cloud\\Firestore\\V1"; +option ruby_package = "Google::Cloud::Firestore::V1"; +option java_multiple_files = true; +option java_package = "com.google.firestore.v1"; +option java_outer_classname = "PipelineProto"; +option objc_class_prefix = "GCFS"; +// A Firestore query represented as an ordered list of operations / stages. +// +// This is considered the top-level function which plans & executes a query. +// It is logically equivalent to `query(stages, options)`, but prevents the +// client from having to build a function wrapper. +message StructuredPipeline { + // The pipeline query to execute. + Pipeline pipeline = 1; + // Optional query-level arguments. + // + // (-- Think query statement hints. --) + // + // (-- TODO(batchik): define the api contract of using an unsupported hint --) + map options = 2; +} diff --git a/dev/protos/v1.json b/dev/protos/v1.json index 19be0044b..7d3336323 100644 --- a/dev/protos/v1.json +++ b/dev/protos/v1.json @@ -1555,7 +1555,10 @@ "referenceValue", "geoPointValue", "arrayValue", - "mapValue" + "mapValue", + "fieldReferenceValue", + "functionValue", + "pipelineValue" ] } }, @@ -1603,6 +1606,18 @@ "mapValue": { "type": "MapValue", "id": 6 + }, + "fieldReferenceValue": { + "type": "string", + "id": 19 + }, + "functionValue": { + "type": "Function", + "id": 20 + }, + "pipelineValue": { + "type": "Pipeline", + "id": 21 } } }, @@ -1624,6 +1639,53 @@ } } }, + "Function": { + "fields": { + "name": { + "type": "string", + "id": 1 + }, + "args": { + "rule": "repeated", + "type": "Value", + "id": 2 + }, + "options": { + "keyType": "string", + "type": "Value", + "id": 3 + } + } + }, + "Pipeline": { + "fields": { + "stages": { + "rule": "repeated", + "type": "Stage", + "id": 1 + } + }, + "nested": { + "Stage": { + "fields": { + "name": { + "type": "string", + "id": 1 + }, + "args": { + "rule": "repeated", + "type": "Value", + "id": 2 + }, + "options": { + "keyType": "string", + "type": "Value", + "id": 3 + } + } + } + } + }, "BitSequence": { "fields": { "bitmap": { @@ -1898,6 +1960,23 @@ } ] }, + "ExecutePipeline": { + "requestType": "ExecutePipelineRequest", + "responseType": "ExecutePipelineResponse", + "responseStream": true, + "options": { + "(google.api.http).post": "/v1beta1/{database=projects/*/databases/*}:executePipeline", + "(google.api.http).body": "*" + }, + "parsedOptions": [ + { + "(google.api.http)": { + "post": "/v1beta1/{database=projects/*/databases/*}:executePipeline", + "body": "*" + } + } + ] + }, "RunAggregationQuery": { "requestType": "RunAggregationQueryRequest", "responseType": "RunAggregationQueryResponse", @@ -2446,6 +2525,64 @@ } } }, + "ExecutePipelineRequest": { + "oneofs": { + "pipelineType": { + "oneof": [ + "structuredPipeline" + ] + }, + "consistencySelector": { + "oneof": [ + "transaction", + "newTransaction", + "readTime" + ] + } + }, + "fields": { + "database": { + "type": "string", + "id": 1, + "options": { + "(google.api.field_behavior)": "REQUIRED" + } + }, + "structuredPipeline": { + "type": "StructuredPipeline", + "id": 2 + }, + "transaction": { + "type": "bytes", + "id": 5 + }, + "newTransaction": { + "type": "TransactionOptions", + "id": 6 + }, + "readTime": { + "type": "google.protobuf.Timestamp", + "id": 7 + } + } + }, + "ExecutePipelineResponse": { + "fields": { + "transaction": { + "type": "bytes", + "id": 1 + }, + "results": { + "rule": "repeated", + "type": "Document", + "id": 2 + }, + "executionTime": { + "type": "google.protobuf.Timestamp", + "id": 3 + } + } + }, "RunAggregationQueryRequest": { "oneofs": { "queryType": { @@ -2877,6 +3014,19 @@ } } }, + "StructuredPipeline": { + "fields": { + "pipeline": { + "type": "Pipeline", + "id": 1 + }, + "options": { + "keyType": "string", + "type": "Value", + "id": 2 + } + } + }, "StructuredQuery": { "fields": { "select": { From 608a75e246a141a0a0b2e595cfd910f95b44b7bb Mon Sep 17 00:00:00 2001 From: Wu-Hui Date: Wed, 12 Jun 2024 14:52:13 -0400 Subject: [PATCH 02/60] Add expressions, stages, and pipeline --- dev/src/expression.ts | 803 ++++++++++++++++++ dev/src/pipeline-util.ts | 440 ++++++++++ dev/src/pipeline.ts | 318 +++++++ dev/src/reference/aggregate-query.ts | 21 + .../reference/composite-filter-internal.ts | 8 + dev/src/reference/field-filter-internal.ts | 44 +- dev/src/reference/query.ts | 142 +++- dev/src/reference/types.ts | 11 + dev/src/reference/vector-query.ts | 13 + dev/src/serializer.ts | 7 + dev/src/stage.ts | 228 +++++ dev/src/types.ts | 5 + types/firestore.d.ts | 12 +- 13 files changed, 2010 insertions(+), 42 deletions(-) create mode 100644 dev/src/expression.ts create mode 100644 dev/src/pipeline-util.ts create mode 100644 dev/src/pipeline.ts create mode 100644 dev/src/stage.ts diff --git a/dev/src/expression.ts b/dev/src/expression.ts new file mode 100644 index 000000000..0387699d3 --- /dev/null +++ b/dev/src/expression.ts @@ -0,0 +1,803 @@ +import * as protos from '../protos/firestore_v1_proto_api'; +import api = protos.google.firestore.v1; + +import {VectorValue} from './field-value'; +import {GeoPoint} from './geo-point'; +import {FieldPath} from './path'; +import {Pipeline} from './pipeline'; +import {isFirestoreValue} from './pipeline-util'; +import {DocumentReference} from './reference/document-reference'; +import {Serializer} from './serializer'; +import {Timestamp} from './timestamp'; + +export interface Selectable { + selectable: true; +} + +export interface FilterCondition { + filterable: true; +} + +export interface Accumulator { + toField(fieldName: string): AggregateTarget; +} + +export class AggregateTarget implements Selectable { + constructor( + public field: Field, + public accumulator: Accumulator & Expr + ) {} + + selectable = true as const; +} + +export type FilterExpr = Expr & FilterCondition; + +export type SelectableExpr = Expr & Selectable; + +export type ExprType = 'Field' | 'Constant' | 'Function' | 'ListOfExprs'; + +export abstract class Expr { + equal(other: Expr): Equal; + equal(other: any): Equal; + equal(other: any): Equal { + if (other instanceof Expr) { + return new Equal(this, other); + } + return new Equal(this, Constant.of(other)); + } + + notEqual(other: Expr): NotEqual; + notEqual(other: any): NotEqual; + notEqual(other: any): NotEqual { + if (other instanceof Expr) { + return new NotEqual(this, other); + } + return new NotEqual(this, Constant.of(other)); + } + + lessThan(other: Expr): LessThan; + lessThan(other: any): LessThan; + lessThan(other: any): LessThan { + if (other instanceof Expr) { + return new LessThan(this, other); + } + return new LessThan(this, Constant.of(other)); + } + + lessThanOrEqual(other: Expr): LessThanOrEqual; + lessThanOrEqual(other: any): LessThanOrEqual; + lessThanOrEqual(other: any): LessThanOrEqual { + if (other instanceof Expr) { + return new LessThanOrEqual(this, other); + } + return new LessThanOrEqual(this, Constant.of(other)); + } + + greaterThan(other: Expr): GreaterThan; + greaterThan(other: any): GreaterThan; + greaterThan(other: any): GreaterThan { + if (other instanceof Expr) { + return new GreaterThan(this, other); + } + return new GreaterThan(this, Constant.of(other)); + } + + greaterThanOrEqual(other: Expr): GreaterThanOrEqual; + greaterThanOrEqual(other: any): GreaterThanOrEqual; + greaterThanOrEqual(other: any): GreaterThanOrEqual { + if (other instanceof Expr) { + return new GreaterThanOrEqual(this, other); + } + return new GreaterThanOrEqual(this, Constant.of(other)); + } + + arrayContains(element: Expr): ArrayContains; + arrayContains(element: any): ArrayContains; + arrayContains(element: any): ArrayContains { + if (element instanceof Expr) { + return new ArrayContains(this, element); + } + return new ArrayContains(this, Constant.of(element)); + } + + arrayContainsAny(values: Expr[]): ArrayContainsAny; + arrayContainsAny(values: any[]): ArrayContainsAny; + arrayContainsAny(values: any[]): ArrayContainsAny { + const exprValues = values.map(value => + value instanceof Expr ? value : Constant.of(value) + ); + return new ArrayContainsAny(this, exprValues); + } + + in(...others: Expr[]): In; + in(...others: any[]): In; + in(...others: any[]): In { + const exprOthers = others.map(other => + other instanceof Expr ? other : Constant.of(other) + ); + return new In(this, exprOthers); + } + + isNaN(): IsNan { + return new IsNan(this); + } + + isNull(): IsNull { + return new IsNull(this); + } + + count(): Count { + return new Count(this, false); + } + + sum(): Sum { + return new Sum(this, false); + } + + avg(): Avg { + return new Avg(this, false); + } + + min(): Min { + return new Min(this, false); + } + + max(): Max { + return new Max(this, false); + } + + cosineDistance(other: Expr): CosineDistance; + cosineDistance(other: VectorValue): CosineDistance; + cosineDistance(other: number[]): CosineDistance; + cosineDistance(other: Expr | VectorValue | number[]): CosineDistance { + if (other instanceof Expr) { + return new CosineDistance(this, other); + } else { + return new CosineDistance(this, Constant.ofVector(other)); + } + } + + dotProductDistance(other: Expr): DotProductDistance; + dotProductDistance(other: VectorValue): DotProductDistance; + dotProductDistance(other: number[]): DotProductDistance; + dotProductDistance(other: Expr | VectorValue | number[]): DotProductDistance { + if (other instanceof Expr) { + return new DotProductDistance(this, other); + } else { + return new DotProductDistance(this, Constant.ofVector(other)); + } + } + + euclideanDistance(other: Expr): EuclideanDistance; + euclideanDistance(other: VectorValue): EuclideanDistance; + euclideanDistance(other: number[]): EuclideanDistance; + euclideanDistance(other: Expr | VectorValue | number[]): EuclideanDistance { + if (other instanceof Expr) { + return new EuclideanDistance(this, other); + } else { + return new EuclideanDistance(this, Constant.ofVector(other)); + } + } + + abstract _toProto(serializer: Serializer): api.IValue; +} + +class ListOfExprs extends Expr { + exprType: ExprType = 'ListOfExprs'; + constructor(private exprs: Expr[]) { + super(); + } + + _toProto(serializer: Serializer): api.IValue { + return { + arrayValue: { + values: this.exprs.map(p => serializer.encodeValue(p)!), + }, + }; + } +} + +export class Field extends Expr implements Selectable { + exprType: ExprType = 'Field'; + selectable = true as const; + + private constructor( + private fieldPath: FirebaseFirestore.FieldPath, + private pipeline: Pipeline | null = null + ) { + super(); + } + + static of(name: string): Field; + static of(path: FirebaseFirestore.FieldPath): Field; + static of(nameOrPath: string | FirebaseFirestore.FieldPath): Field; + static of(pipeline: Pipeline, name: string): Field; + static of( + pipelineOrName: Pipeline | string | FirebaseFirestore.FieldPath, + name?: string + ): Field { + if (typeof pipelineOrName === 'string') { + return new Field(FieldPath.fromArgument(pipelineOrName)); + } else if (pipelineOrName instanceof FirebaseFirestore.FieldPath) { + return new Field(pipelineOrName); + } else { + return new Field(FieldPath.fromArgument(name!), pipelineOrName); + } + } + + fieldName(): string { + return (this.fieldPath as FieldPath).formattedName; + } + + _toProto(serializer: Serializer): api.IValue { + return { + fieldReferenceValue: (this.fieldPath as FieldPath).formattedName, + }; + } +} + +export class Fields extends Expr implements Selectable { + exprType: ExprType = 'Field'; + selectable = true as const; + + private constructor(private fields: Field[]) { + super(); + } + + static of(name: string, ...others: string[]): Fields { + return new Fields([Field.of(name), ...others.map(Field.of)]); + } + + static ofAll(): Fields { + return new Fields([]); + } + + fieldList(): Field[] { + return this.fields.map(f => f); + } + + _toProto(serializer: Serializer): api.IValue { + return { + arrayValue: { + values: this.fields.map(f => f._toProto(serializer)), + }, + }; + } +} + +export class Constant extends Expr { + exprType: ExprType = 'Constant'; + + private constructor(private value: any) { + super(); + } + + static of(value: number): Constant; + static of(value: string): Constant; + static of(value: boolean): Constant; + static of(value: null): Constant; + static of(value: undefined): Constant; + static of(value: GeoPoint): Constant; + static of(value: Timestamp): Constant; + static of(value: Date): Constant; + static of(value: Uint8Array): Constant; + static of(value: DocumentReference): Constant; + static of(value: api.IValue): Constant; + static of(value: Array): Constant; + static of(value: Map): Constant; + static of(value: VectorValue): Constant; + static of(value: api.IValue): Constant; + static of(value: any): Constant { + return new Constant(value); + } + + static ofVector(value: Array | VectorValue): Constant { + if (value instanceof VectorValue) { + return new Constant(value); + } else { + return new Constant(new VectorValue(value)); + } + } + + _toProto(serializer: Serializer): api.IValue { + if (isFirestoreValue(this.value)) { + return this.value; + } + + return serializer.encodeValue(this.value)!; + } +} + +export class Function extends Expr { + exprType: ExprType = 'Function'; + constructor( + private name: string, + private params: Expr[] + ) { + super(); + } + + _toProto(serializer: Serializer): api.IValue { + return { + functionValue: { + name: this.name, + args: this.params.map(p => serializer.encodeValue(p)!), + }, + }; + } +} + +export class Equal extends Function implements FilterCondition { + constructor( + private left: Expr, + private right: Expr + ) { + super('eq', [left, right]); + } + filterable = true as const; +} + +class NotEqual extends Function implements FilterCondition { + constructor( + private left: Expr, + private right: Expr + ) { + super('neq', [left, right]); + } + filterable = true as const; +} + +class LessThan extends Function implements FilterCondition { + constructor( + private left: Expr, + private right: Expr + ) { + super('lt', [left, right]); + } + filterable = true as const; +} + +class LessThanOrEqual extends Function implements FilterCondition { + constructor( + private left: Expr, + private right: Expr + ) { + super('lte', [left, right]); + } + filterable = true as const; +} + +class GreaterThan extends Function implements FilterCondition { + constructor( + private left: Expr, + private right: Expr + ) { + super('gt', [left, right]); + } + filterable = true as const; +} + +class GreaterThanOrEqual extends Function implements FilterCondition { + constructor( + private left: Expr, + private right: Expr + ) { + super('gte', [left, right]); + } + filterable = true as const; +} + +class ArrayContains extends Function implements FilterCondition { + constructor( + private array: Expr, + private element: Expr + ) { + super('array_contains', [array, element]); + } + filterable = true as const; +} + +class ArrayContainsAny extends Function implements FilterCondition { + constructor( + private array: Expr, + private values: Expr[] + ) { + super('array_contains_any', [array, new ListOfExprs(values)]); + } + filterable = true as const; +} + +class In extends Function implements FilterCondition { + constructor( + private left: Expr, + private others: Expr[] + ) { + super('in', [left, new ListOfExprs(others)]); + } + filterable = true as const; +} + +class IsNan extends Function implements FilterCondition { + constructor(private expr: Expr) { + super('is_nan', [expr]); + } + filterable = true as const; +} +class IsNull extends Function implements FilterCondition { + constructor(private expr: Expr) { + super('is_null', [expr]); + } + filterable = true as const; +} + +class Not extends Function implements FilterCondition { + constructor(private expr: Expr) { + super('not', [expr]); + } + filterable = true as const; +} + +class And extends Function implements FilterCondition { + constructor(private conditions: FilterExpr[]) { + super('and', conditions); + } + + filterable = true as const; +} + +class Or extends Function implements FilterCondition { + constructor(private conditions: FilterExpr[]) { + super('or', conditions); + } + filterable = true as const; +} + +class Count extends Function implements Accumulator { + constructor( + private value: Expr | undefined, + private distinct: boolean + ) { + super('count', value === undefined ? [] : [value]); + } + + toField(fieldName: string): AggregateTarget { + return new AggregateTarget(Field.of(fieldName), this); + } +} + +class Sum extends Function implements Accumulator { + constructor( + private value: Expr, + private distinct: boolean + ) { + super('sum', [value]); + } + toField(fieldName: string): AggregateTarget { + return new AggregateTarget(Field.of(fieldName), this); + } +} + +class Avg extends Function implements Accumulator { + constructor( + private value: Expr, + private distinct: boolean + ) { + super('avg', [value]); + } + toField(fieldName: string): AggregateTarget { + return new AggregateTarget(Field.of(fieldName), this); + } +} + +class Min extends Function implements Accumulator { + constructor( + private value: Expr, + private distinct: boolean + ) { + super('min', [value]); + } + toField(fieldName: string): AggregateTarget { + return new AggregateTarget(Field.of(fieldName), this); + } +} + +class Max extends Function implements Accumulator { + constructor( + private value: Expr, + private distinct: boolean + ) { + super('max', [value]); + } + toField(fieldName: string): AggregateTarget { + return new AggregateTarget(Field.of(fieldName), this); + } +} + +class CosineDistance extends Function { + constructor( + private vector1: Expr, + private vector2: Expr + ) { + super('cosine_distance', [vector1, vector2]); + } +} + +class DotProductDistance extends Function { + constructor( + private vector1: Expr, + private vector2: Expr + ) { + super('dot_product', [vector1, vector2]); + } +} + +class EuclideanDistance extends Function { + constructor( + private vector1: Expr, + private vector2: Expr + ) { + super('euclidean_distance', [vector1, vector2]); + } +} + +function equal(left: Expr, right: Expr): Equal; +function equal(left: Expr, right: any): Equal; +function equal(left: string, right: Expr): Equal; +function equal(left: string, right: any): Equal; +function equal(left: Expr | string, right: any): Equal { + const leftExpr = left instanceof Expr ? left : Field.of(left); + const rightExpr = right instanceof Expr ? right : Constant.of(right); + return new Equal(leftExpr, rightExpr); +} + +// notEqual +function notEqual(left: Expr, right: Expr): NotEqual; +function notEqual(left: Expr, right: any): NotEqual; +function notEqual(left: string, right: Expr): NotEqual; +function notEqual(left: string, right: any): NotEqual; +function notEqual(left: Expr | string, right: any): NotEqual { + const leftExpr = left instanceof Expr ? left : Field.of(left); + const rightExpr = right instanceof Expr ? right : Constant.of(right); + return new NotEqual(leftExpr, rightExpr); +} + +function lessThan(left: Expr, right: Expr): LessThan; +function lessThan(left: Expr, right: any): LessThan; +function lessThan(left: string, right: Expr): LessThan; +function lessThan(left: string, right: any): LessThan; +function lessThan(left: Expr | string, right: any): LessThan { + const leftExpr = left instanceof Expr ? left : Field.of(left); + const rightExpr = right instanceof Expr ? right : Constant.of(right); + return new LessThan(leftExpr, rightExpr); +} + +function lessThanOrEqual(left: Expr, right: Expr): LessThanOrEqual; +function lessThanOrEqual(left: Expr, right: any): LessThanOrEqual; +function lessThanOrEqual(left: string, right: Expr): LessThanOrEqual; +function lessThanOrEqual(left: string, right: any): LessThanOrEqual; +function lessThanOrEqual(left: Expr | string, right: any): LessThanOrEqual { + const leftExpr = left instanceof Expr ? left : Field.of(left); + const rightExpr = right instanceof Expr ? right : Constant.of(right); + return new LessThanOrEqual(leftExpr, rightExpr); +} + +function greaterThan(left: Expr, right: Expr): GreaterThan; +function greaterThan(left: Expr, right: any): GreaterThan; +function greaterThan(left: string, right: Expr): GreaterThan; +function greaterThan(left: string, right: any): GreaterThan; +function greaterThan(left: Expr | string, right: any): GreaterThan { + const leftExpr = left instanceof Expr ? left : Field.of(left); + const rightExpr = right instanceof Expr ? right : Constant.of(right); + return new GreaterThan(leftExpr, rightExpr); +} + +function greaterThanOrEqual(left: Expr, right: Expr): GreaterThanOrEqual; +function greaterThanOrEqual(left: Expr, right: any): GreaterThanOrEqual; +function greaterThanOrEqual(left: string, right: Expr): GreaterThanOrEqual; +function greaterThanOrEqual(left: string, right: any): GreaterThanOrEqual; +function greaterThanOrEqual( + left: Expr | string, + right: any +): GreaterThanOrEqual { + const leftExpr = left instanceof Expr ? left : Field.of(left); + const rightExpr = right instanceof Expr ? right : Constant.of(right); + return new GreaterThanOrEqual(leftExpr, rightExpr); +} + +function arrayContains(array: Expr, element: Expr): ArrayContains; +function arrayContains(array: Expr, element: any): ArrayContains; +function arrayContains(array: string, element: Expr): ArrayContains; +function arrayContains(array: string, element: any): ArrayContains; +function arrayContains(array: Expr | string, element: any): ArrayContains { + const arrayExpr = array instanceof Expr ? array : Field.of(array); + const elementExpr = element instanceof Expr ? element : Constant.of(element); + return new ArrayContains(arrayExpr, elementExpr); +} + +function arrayContainsAny(array: Expr, values: Expr[]): ArrayContainsAny; +function arrayContainsAny(array: Expr, values: any[]): ArrayContainsAny; +function arrayContainsAny(array: string, values: Expr[]): ArrayContainsAny; +function arrayContainsAny(array: string, values: any[]): ArrayContainsAny; +function arrayContainsAny( + array: Expr | string, + values: any[] +): ArrayContainsAny { + const arrayExpr = array instanceof Expr ? array : Field.of(array); + const exprValues = values.map(value => + value instanceof Expr ? value : Constant.of(value) + ); + return new ArrayContainsAny(arrayExpr, exprValues); +} + +function inAny(element: Expr, others: Expr[]): In; +function inAny(element: Expr, others: any[]): In; +function inAny(element: string, others: Expr[]): In; // Added overload +function inAny(element: string, others: any[]): In; // Added overload +function inAny(element: Expr | string, others: any[]): In { + const elementExpr = element instanceof Expr ? element : Field.of(element); + const exprOthers = others.map(other => + other instanceof Expr ? other : Constant.of(other) + ); + return new In(elementExpr, exprOthers); +} + +function notInAny(element: Expr, others: Expr[]): Not; +function notInAny(element: Expr, others: any[]): Not; +function notInAny(element: string, others: Expr[]): Not; // Added overload +function notInAny(element: string, others: any[]): Not; // Added overload +function notInAny(element: Expr | string, others: any[]): Not { + const elementExpr = element instanceof Expr ? element : Field.of(element); + const exprOthers = others.map(other => + other instanceof Expr ? other : Constant.of(other) + ); + return new Not(new In(elementExpr, exprOthers)); +} + +export function and(left: FilterExpr, ...right: FilterExpr[]): And { + return new And([left, ...right]); +} + +export function or(left: FilterExpr, ...right: FilterExpr[]): Or { + return new Or([left, ...right]); +} + +export function not(filter: FilterExpr): Not { + return new Not(filter); +} + +export function isNull(value: Expr): IsNull; +export function isNull(value: string): IsNull; +export function isNull(value: Expr | string): IsNull { + const valueExpr = value instanceof Expr ? value : Field.of(value); + return new IsNull(valueExpr); +} + +export function isNan(value: Expr): IsNan; +export function isNan(value: string): IsNan; +export function isNan(value: Expr | string): IsNan { + const valueExpr = value instanceof Expr ? value : Field.of(value); + return new IsNan(valueExpr); +} + +export function countAll(): Count { + return new Count(undefined, false); +} + +export function count(value: Expr): Count; +export function count(value: string): Count; +export function count(value: Expr | string): Count { + const exprValue = value instanceof Expr ? value : Field.of(value); + return new Count(exprValue, false); +} + +export function sum(value: Expr): Sum; +export function sum(value: string): Sum; +export function sum(value: Expr | string): Sum { + const exprValue = value instanceof Expr ? value : Field.of(value); + return new Sum(exprValue, false); +} + +export function avg(value: Expr): Avg; +export function avg(value: string): Avg; +export function avg(value: Expr | string): Avg { + const exprValue = value instanceof Expr ? value : Field.of(value); + return new Avg(exprValue, false); +} + +function min(value: Expr): Min; +function min(value: string): Min; +function min(value: Expr | string): Min { + const exprValue = value instanceof Expr ? value : Field.of(value); + return new Min(exprValue, false); +} + +function max(value: Expr): Max; +function max(value: string): Max; +function max(value: Expr | string): Max { + const exprValue = value instanceof Expr ? value : Field.of(value); + return new Max(exprValue, false); +} + +function cosineDistance(expr: Expr, other: Expr): CosineDistance; +function cosineDistance(expr: Expr, other: number[]): CosineDistance; +function cosineDistance(expr: Expr, other: VectorValue): CosineDistance; +function cosineDistance(expr: string, other: Expr): CosineDistance; +function cosineDistance(expr: string, other: number[]): CosineDistance; +function cosineDistance(expr: string, other: VectorValue): CosineDistance; +function cosineDistance( + expr: Expr | string, + other: Expr | number[] | VectorValue +): CosineDistance { + const expr1 = expr instanceof Expr ? expr : Field.of(expr); + const expr2 = other instanceof Expr ? other : Constant.ofVector(other); + return new CosineDistance(expr1, expr2); +} + +function dotProductDistance(expr: Expr, other: Expr): DotProductDistance; // Fixed return type +function dotProductDistance(expr: Expr, other: number[]): DotProductDistance; +function dotProductDistance(expr: Expr, other: VectorValue): DotProductDistance; +function dotProductDistance(expr: string, other: Expr): DotProductDistance; +function dotProductDistance(expr: string, other: number[]): DotProductDistance; +function dotProductDistance( + expr: string, + other: VectorValue +): DotProductDistance; +function dotProductDistance( + expr: Expr | string, + other: Expr | number[] | VectorValue +): DotProductDistance { + const expr1 = expr instanceof Expr ? expr : Field.of(expr); + const expr2 = other instanceof Expr ? other : Constant.ofVector(other); + return new DotProductDistance(expr1, expr2); +} + +function euclideanDistance(expr: Expr, other: Expr): EuclideanDistance; +function euclideanDistance(expr: Expr, other: number[]): EuclideanDistance; +function euclideanDistance(expr: Expr, other: VectorValue): EuclideanDistance; +function euclideanDistance(expr: string, other: Expr): EuclideanDistance; +function euclideanDistance(expr: string, other: number[]): EuclideanDistance; +function euclideanDistance(expr: string, other: VectorValue): EuclideanDistance; +function euclideanDistance( + expr: Expr | string, + other: Expr | number[] | VectorValue +): EuclideanDistance { + const expr1 = expr instanceof Expr ? expr : Field.of(expr); + const expr2 = other instanceof Expr ? other : Constant.ofVector(other); + return new EuclideanDistance(expr1, expr2); +} + +function genericFunction(name: string, params: Expr[]): Function { + return new Function(name, params); +} + +export class Ordering { + constructor( + private expr: Expr, + private direction: 'asc' | 'desc' + ) {} + + static of( + expr: Expr, + direction: 'asc' | 'desc' | undefined = undefined + ): Ordering { + return new Ordering(expr, direction || 'asc'); + } + static ascending(expr: Expr): Ordering { + return new Ordering(expr, 'asc'); + } + static descending(expr: Expr): Ordering { + return new Ordering(expr, 'desc'); + } + + _toProto(serializer: Serializer): api.IValue { + return { + mapValue: { + fields: { + direction: serializer.encodeValue(this.direction)!, + expression: serializer.encodeValue(this.expr)!, + }, + }, + }; + } +} diff --git a/dev/src/pipeline-util.ts b/dev/src/pipeline-util.ts new file mode 100644 index 000000000..ef42b9138 --- /dev/null +++ b/dev/src/pipeline-util.ts @@ -0,0 +1,440 @@ +import * as firestore from '@google-cloud/firestore'; +import {GoogleError, serializer} from 'google-gax'; +import {Duplex, Transform} from 'stream'; +import {google} from '../protos/firestore_v1_proto_api'; + +import * as protos from '../protos/firestore_v1_proto_api'; +import { + Expr, + FilterCondition, + and, + or, + isNan, + Field, + not, + Constant, +} from './expression'; +import Firestore, {DocumentReference, Timestamp} from './index'; +import {logger} from './logger'; +import {QualifiedResourcePath} from './path'; +import {Pipeline, PipelineResult} from './pipeline'; +import {CompositeFilterInternal} from './reference/composite-filter-internal'; +import {NOOP_MESSAGE} from './reference/constants'; +import {FieldFilterInternal} from './reference/field-filter-internal'; +import {FilterInternal} from './reference/filter-internal'; +import {PipelineStreamElement, QueryResponse} from './reference/types'; +import {Serializer} from './serializer'; +import { + Deferred, + getTotalTimeout, + isObject, + isPermanentRpcError, + requestTag, + wrapError, +} from './util'; +import api = protos.google.firestore.v1; + +/** + * Returns a builder for DocumentSnapshot and QueryDocumentSnapshot instances. + * Invoke `.build()' to assemble the final snapshot. + * + * @private + * @internal + */ +export class ExecutionUtil< + AppModelType, + DbModelType extends firestore.DocumentData, +> { + constructor( + /** @private */ + readonly _firestore: Firestore, + /** @private */ + readonly _serializer: Serializer + ) {} + + _getResponse( + pipeline: Pipeline, + transactionOrReadTime?: Uint8Array | Timestamp | api.ITransactionOptions, + explainOptions?: firestore.ExplainOptions + ): Promise> | undefined> { + // Capture the error stack to preserve stack tracing across async calls. + const stack = Error().stack!; + + return new Promise((resolve, reject) => { + const results: Array> = []; + const output: Omit, 'result'> & { + executionTime?: Timestamp; + } = {}; + + this._stream(pipeline, transactionOrReadTime, explainOptions) + .on('error', err => { + reject(wrapError(err, stack)); + }) + .on( + 'data', + (data: PipelineStreamElement) => { + if (data.transaction) { + output.transaction = data.transaction; + } + if (data.executionTime) { + output.executionTime = data.executionTime; + } + if (data.explainMetrics) { + output.explainMetrics = data.explainMetrics; + } + if (data.result) { + results.push(data.result); + } + } + ) + .on('end', () => { + // Only return a snapshot when we have a readTime + // explain queries with analyze !== true will return no documents and no read time + const result = output.executionTime ? results : undefined; + + resolve(result); + }); + }); + } + + // This method exists solely to enable unit tests to mock it. + _isPermanentRpcError(err: GoogleError, methodName: string): boolean { + return isPermanentRpcError(err, methodName); + } + + _hasRetryTimedOut(methodName: string, startTime: number): boolean { + const totalTimeout = getTotalTimeout(methodName); + if (totalTimeout === 0) { + return false; + } + + return Date.now() - startTime >= totalTimeout; + } + + stream(pipeline: Pipeline): NodeJS.ReadableStream { + const responseStream = this._stream(pipeline); + const transform = new Transform({ + objectMode: true, + transform(chunk, encoding, callback) { + callback(undefined, chunk.result); + }, + }); + + responseStream.pipe(transform); + responseStream.on('error', e => transform.destroy(e)); + return transform; + } + + _stream( + pipeline: Pipeline, + transactionOrReadTime?: Uint8Array | Timestamp | api.ITransactionOptions, + explainOptions?: firestore.ExplainOptions + ): NodeJS.ReadableStream { + const tag = requestTag(); + const startTime = Date.now(); + const isExplain = explainOptions !== undefined; + + let backendStream: Duplex; + const stream = new Transform({ + objectMode: true, + transform: ( + proto: api.ExecutePipelineResponse | typeof NOOP_MESSAGE, + enc, + callback + ) => { + if (proto === NOOP_MESSAGE) { + callback(undefined); + return; + } + + if (proto.results) { + for (const r of proto.results) { + const output: PipelineStreamElement = {}; + + // Proto comes with zero-length buffer by default + if (proto.transaction?.length) { + output.transaction = proto.transaction; + } + + if (proto.executionTime) { + output.executionTime = Timestamp.fromProto(proto.executionTime); + } + + const ref = r.name + ? new DocumentReference( + this._firestore, + QualifiedResourcePath.fromSlashSeparatedString(r.name) + ) + : undefined; + output.result = new PipelineResult( + this._serializer, + ref, + r.fields, + Timestamp.fromProto(proto.executionTime!), + r.createTime ? Timestamp.fromProto(r.createTime!) : undefined, + r.updateTime ? Timestamp.fromProto(r.updateTime!) : undefined + ); + + callback(undefined, output); + } + } + }, + }); + + this._firestore + .initializeIfNeeded(tag) + .then(async () => { + // `toProto()` might throw an exception. We rely on the behavior of an + // async function to convert this exception into the rejected Promise we + // catch below. + const request = pipeline._toProto( + this._firestore, + transactionOrReadTime, + explainOptions + ); + + let streamActive: Deferred; + do { + streamActive = new Deferred(); + const methodName = 'executePipeline'; + backendStream = await this._firestore.requestStream( + methodName, + /* bidirectional= */ false, + request, + tag + ); + backendStream.on('error', err => { + backendStream.unpipe(stream); + + logger( + 'QueryUtil._stream', + tag, + 'Query failed with stream error:', + err + ); + stream.destroy(err); + streamActive.resolve(/* active= */ false); + }); + backendStream.on('end', () => { + streamActive.resolve(/* active= */ false); + }); + backendStream.resume(); + backendStream.pipe(stream); + } while (await streamActive.promise); + }) + .catch(e => stream.destroy(e)); + + return stream; + } +} + +function isITimestamp(obj: any): obj is google.protobuf.ITimestamp { + if (typeof obj !== 'object' || obj === null) { + return false; // Must be a non-null object + } + if ( + ('seconds' in obj && + !( + obj.seconds === null || + typeof obj.seconds === 'number' || + typeof obj.seconds === 'string' + )) || + ('nanos' in obj && !(obj.nanos === null || typeof obj.nanos === 'number')) + ) { + return false; // Invalid property type + } + + return true; // All checks passed +} +function isILatLng(obj: any): obj is google.type.ILatLng { + if (typeof obj !== 'object' || obj === null) { + return false; // Must be a non-null object + } + if ( + ('latitude' in obj && + !(obj.latitude === null || typeof obj.latitude === 'number')) || + ('longitude' in obj && + !(obj.longitude === null || typeof obj.longitude === 'number')) + ) { + return false; // Invalid property type + } + + return true; // All checks passed +} +function isIArrayValue(obj: any): obj is api.IArrayValue { + if (typeof obj !== 'object' || obj === null) { + return false; // Must be a non-null object + } + if ('values' in obj && !(obj.values === null || Array.isArray(obj.values))) { + return false; // Invalid property type + } + + return true; // All checks passed +} +function isIMapValue(obj: any): obj is api.IMapValue { + if (typeof obj !== 'object' || obj === null) { + return false; // Must be a non-null object + } + if ('fields' in obj && !(obj.fields === null || isObject(obj.fields))) { + return false; // Invalid property type + } + + return true; // All checks passed +} +function isIFunction(obj: any): obj is api.IFunction { + if (typeof obj !== 'object' || obj === null) { + return false; // Must be a non-null object + } + if ( + ('name' in obj && !(obj.name === null || typeof obj.name === 'string')) || + ('args' in obj && !(obj.args === null || Array.isArray(obj.args))) + ) { + return false; // Invalid property type + } + + return true; // All checks passed +} + +function isIPipeline(obj: any): obj is api.IPipeline { + if (typeof obj !== 'object' || obj === null) { + return false; // Must be a non-null object + } + if ('stages' in obj && !(obj.stages === null || Array.isArray(obj.stages))) { + return false; // Invalid property type + } + + return true; // All checks passed +} + +export function isFirestoreValue(obj: any): obj is api.IValue { + if (typeof obj !== 'object' || obj === null) { + return false; // Must be a non-null object + } + + // Check optional properties and their types + if ( + ('nullValue' in obj && + !( + obj.nullValue === null || + obj.nullValue instanceof google.protobuf.BoolValue + )) || + ('booleanValue' in obj && + !(obj.booleanValue === null || typeof obj.booleanValue === 'boolean')) || + ('integerValue' in obj && + !( + obj.integerValue === null || + typeof obj.integerValue === 'number' || + typeof obj.integerValue === 'string' + )) || + ('doubleValue' in obj && + !(obj.doubleValue === null || typeof obj.doubleValue === 'number')) || + ('timestampValue' in obj && + !(obj.timestampValue === null || isITimestamp(obj.timestampValue))) || + ('stringValue' in obj && + !(obj.stringValue === null || typeof obj.stringValue === 'string')) || + ('bytesValue' in obj && + !(obj.bytesValue === null || obj.bytesValue instanceof Uint8Array)) || + ('referenceValue' in obj && + !( + obj.referenceValue === null || typeof obj.referenceValue === 'string' + )) || + ('geoPointValue' in obj && + !(obj.geoPointValue === null || isILatLng(obj.geoPointValue))) || + ('arrayValue' in obj && + !(obj.arrayValue === null || isIArrayValue(obj.arrayValue))) || + ('mapValue' in obj && + !(obj.mapValue === null || isIMapValue(obj.mapValue))) || + ('fieldReferenceValue' in obj && + !( + obj.fieldReferenceValue === null || + typeof obj.fieldReferenceValue === 'string' + )) || + ('functionValue' in obj && + !(obj.functionValue === null || isIFunction(obj.functionValue))) || + ('pipelineValue' in obj && + !(obj.pipelineValue === null || isIPipeline(obj.pipelineValue))) + ) { + return false; // Invalid property type + } + + return true; // All checks passed +} + +export function toPipelineFilterCondition( + f: FilterInternal, + serializer: Serializer +): FilterCondition & Expr { + if (f instanceof FieldFilterInternal) { + if (f.isNanChecking()) { + if (f.nanOp() === 'IS_NAN') { + return Field.of(f.field).isNaN(); + } else { + return not(Field.of(f.field).isNaN()); + } + } else if (f.isNullChecking()) { + if (f.nullOp() === 'IS_NULL') { + return Field.of(f.field).isNull(); + } else { + return not(Field.of(f.field).isNull()); + } + } else { + // Comparison filters + const value = isFirestoreValue(f.value) + ? f.value + : serializer.encodeValue(f.value); + switch (f.op) { + case 'LESS_THAN': + return Field.of(f.field).lessThan(value); + case 'LESS_THAN_OR_EQUAL': + return Field.of(f.field).lessThanOrEqual(value); + case 'GREATER_THAN': + return Field.of(f.field).greaterThan(value); + case 'GREATER_THAN_OR_EQUAL': + return Field.of(f.field).greaterThanOrEqual(value); + case 'EQUAL': + return Field.of(f.field).equal(value); + case 'NOT_EQUAL': + return Field.of(f.field).notEqual(value); + case 'ARRAY_CONTAINS': + return Field.of(f.field).arrayContains(value); + case 'IN': { + const values = value?.arrayValue?.values?.map(val => + Constant.of(value) + ); + return Field.of(f.field).in(...values!); + } + case 'ARRAY_CONTAINS_ANY': { + const values = value?.arrayValue?.values?.map(val => + Constant.of(value) + ); + return Field.of(f.field).arrayContainsAny(values!); + } + case 'NOT_IN': { + const values = value?.arrayValue?.values?.map(val => + Constant.of(value) + ); + return not(Field.of(f.field).in(...values!)); + } + } + } + } else if (f instanceof CompositeFilterInternal) { + switch (f._getOperator()) { + case 'AND': { + const conditions = f + .getFilters() + .map(f => toPipelineFilterCondition(f, serializer)); + return and(conditions[0], ...conditions.slice(1)); + } + case 'OR': { + const conditions = f + .getFilters() + .map(f => toPipelineFilterCondition(f, serializer)); + return or(conditions[0], ...conditions.slice(1)); + } + } + } + + throw new Error( + `Failed to convert filter to pipeline conditions: ${f.toProto()}` + ); +} diff --git a/dev/src/pipeline.ts b/dev/src/pipeline.ts new file mode 100644 index 000000000..eb0cf038e --- /dev/null +++ b/dev/src/pipeline.ts @@ -0,0 +1,318 @@ +import * as firestore from '@google-cloud/firestore'; +import {google} from '../protos/firestore_v1_proto_api'; +import { + Accumulator, + AggregateTarget, + Expr, + Field, + Fields, + FilterCondition, + Ordering, + Selectable, +} from './expression'; +import {VectorValue} from './field-value'; +import Firestore, {Timestamp} from './index'; +import {ExecutionUtil} from './pipeline-util'; +import {DocumentReference} from './reference/document-reference'; +import {Serializer} from './serializer'; +import { + AddField, + Aggregate, + Collection, + CollectionGroup, + Database, + Documents, + Filter, + FindNearest, + FindNearestOptions, + GenerateStage, + Limit, + Offset, + Select, + Sort, + Stage, +} from './stage'; +import {ApiMapValue} from './types'; +import * as protos from '../protos/firestore_v1_proto_api'; +import api = protos.google.firestore.v1; +import IStructuredPipeline = google.firestore.v1.IStructuredPipeline; +import IStage = google.firestore.v1.Pipeline.IStage; +import {QueryCursor} from './reference/types'; + +export class Pipeline< + AppModelType = firestore.DocumentData, + DbModelType extends firestore.DocumentData = firestore.DocumentData, +> { + private constructor(private stages: Stage[]) {} + + static fromCollection(collectionPath: string): Pipeline { + return new Pipeline([new Collection(collectionPath)]); + } + + static fromCollectionGroup(collectionId: string): Pipeline { + return new Pipeline([new CollectionGroup(collectionId)]); + } + + static fromDatabase(): Pipeline { + return new Pipeline([new Database()]); + } + + static fromDocuments(docs: DocumentReference[]): Pipeline { + return new Pipeline([Documents.of(docs)]); + } + + addFields(...fields: Selectable[]): Pipeline { + const copy = this.stages.map(s => s); + copy.push(new AddField(this.selectablesToMap(fields))); + return new Pipeline(copy); + } + + select(...fields: string[]): Pipeline; + select(...fields: Selectable[]): Pipeline; + select(...fields: (Selectable | string)[]): Pipeline { + const copy = this.stages.map(s => s); + copy.push(new Select(this.selectablesToMap(fields))); + return new Pipeline(copy); + } + + private selectablesToMap( + selectables: (Selectable | string)[] + ): Map { + const result = new Map(); + for (const selectable of selectables) { + if (typeof selectable === 'string') { + result.set(selectable as string, Field.of(selectable)); + } else if (selectable instanceof Field) { + result.set((selectable as Field).fieldName(), selectable); + } else if (selectable instanceof AggregateTarget) { + const target = selectable as AggregateTarget; + result.set(target.field.fieldName(), target.accumulator); + } else if (selectable instanceof Fields) { + const fields = selectable as Fields; + for (const field of fields.fieldList()) { + result.set(field.fieldName(), field); + } + } + } + return result; + } + + filter(condition: FilterCondition & Expr): Pipeline { + const copy = this.stages.map(s => s); + copy.push(new Filter(condition)); + return new Pipeline(copy); + } + + offset(offset: number): Pipeline { + const copy = this.stages.map(s => s); + copy.push(new Offset(offset)); + return new Pipeline(copy); + } + + limit(limit: number): Pipeline { + const copy = this.stages.map(s => s); + copy.push(new Limit(limit)); + return new Pipeline(copy); + } + + aggregate(...targets: AggregateTarget[]): Pipeline { + const copy = this.stages.map(s => s); + copy.push( + new Aggregate( + new Map(), + new Map( + targets.map(target => [target.field.fieldName(), target.accumulator]) + ) + ) + ); + return new Pipeline(copy); + } + + findNearest( + field: string, + vector: number[], + options: FindNearestOptions + ): Pipeline; + findNearest( + field: Field, + vector: FirebaseFirestore.VectorValue, + options: FindNearestOptions + ): Pipeline; + findNearest( + field: string | Field, + vector: FirebaseFirestore.VectorValue | number[], + options: FindNearestOptions + ): Pipeline; + findNearest( + field: string | Field, + vector: number[] | FirebaseFirestore.VectorValue, + options: FindNearestOptions + ): Pipeline { + const copy = this.stages.map(s => s); + const fieldExpr = typeof field === 'string' ? Field.of(field) : field; + copy.push(new FindNearest(fieldExpr, vector, options)); + return new Pipeline(copy); + } + + sort(orderings: Ordering[]): Pipeline; + sort( + orderings: Ordering[], + density?: 'unspecified' | 'required', + truncation?: 'unspecified' | 'disabled' + ): Pipeline; + sort( + orderings: Ordering[], + density?: 'unspecified' | 'required', + truncation?: 'unspecified' | 'disabled' + ): Pipeline { + const copy = this.stages.map(s => s); + copy.push( + new Sort(orderings, density ?? 'unspecified', truncation ?? 'unspecified') + ); + return new Pipeline(copy); + } + + paginate(pageSize: number, orderings?: Ordering[]): PaginatingPipeline { + const copy = this.stages.map(s => s); + return new PaginatingPipeline(new Pipeline(copy), pageSize, orderings); + } + + genericStage(name: string, params: any[]): Pipeline { + const copy = this.stages.map(s => s); + copy.push(new GenerateStage(name, params)); + return new Pipeline(copy); + } + + execute( + db: Firestore + ): Promise>> { + const util = new ExecutionUtil( + db, + db._serializer! + ); + return util._getResponse(this).then(result => result!); + } + + stream(db: Firestore): NodeJS.ReadableStream { + const util = new ExecutionUtil( + db, + db._serializer! + ); + return util.stream(this); + } + + _toProto( + db: Firestore, + transactionOrReadTime?: Uint8Array | Timestamp | api.ITransactionOptions, + explainOptions?: FirebaseFirestore.ExplainOptions + ): api.IExecutePipelineRequest { + const stages: IStage[] = this.stages.map(stage => + stage._toProto(db._serializer!) + ); + const structuredPipeline: IStructuredPipeline = {pipeline: {stages}}; + return { + database: db.formattedName, + structuredPipeline, + }; + } +} + +class PaginatingPipeline { + constructor( + private pipeline: Pipeline, + private pageSize: number, + private orderings?: Ordering[] + ) {} + + firstPage(): Pipeline { + return this.pipeline; + } + + lastPage(): Pipeline { + return this.pipeline; + } + + offset(): PaginatingPipeline { + return this; + } + + limit(): PaginatingPipeline { + return this; + } + + startAt(result: PipelineResult): PaginatingPipeline { + return this; + } + + startAfter(result: PipelineResult): PaginatingPipeline { + return this; + } + + endAt(result: PipelineResult): PaginatingPipeline { + return this; + } + + endBefore(result: PipelineResult): PaginatingPipeline { + return this; + } + + /** + * @internal + * @private + */ + withEndCursor(arg0: QueryCursor): PaginatingPipeline { + throw new Error('Method not implemented.'); + } + /** + * @internal + * @private + */ + withStartCursor(arg0: QueryCursor): PaginatingPipeline { + throw new Error('Method not implemented.'); + } +} + +export class PipelineResult< + AppModelType = firestore.DocumentData, + DbModelType extends firestore.DocumentData = firestore.DocumentData, +> { + private _ref: DocumentReference | undefined; + private _serializer: Serializer; + private _readTime: Timestamp | undefined; + private _createTime: Timestamp | undefined; + private _updateTime: Timestamp | undefined; + + /** + * @private + * @internal + * + * @param serializer The serializer used to encode/decode protobuf. + * @param ref The reference to the document. + * @param _fieldsProto The fields of the Firestore `Document` Protobuf backing + * this document (or undefined if the document does not exist). + * @param readTime The time when this snapshot was read (or undefined if + * the document exists only locally). + * @param createTime The time when the document was created (or undefined if + * the document does not exist). + * @param updateTime The time when the document was last updated (or undefined + * if the document does not exist). + */ + constructor( + serializer: Serializer, + ref?: DocumentReference, + /** + * @internal + * @private + **/ + readonly _fieldsProto?: ApiMapValue | null, + readTime?: Timestamp, + createTime?: Timestamp, + updateTime?: Timestamp + ) { + this._ref = ref; + this._serializer = serializer; + this._readTime = readTime; + this._createTime = createTime; + this._updateTime = updateTime; + } +} diff --git a/dev/src/reference/aggregate-query.ts b/dev/src/reference/aggregate-query.ts index 6171c34b4..a4c497571 100644 --- a/dev/src/reference/aggregate-query.ts +++ b/dev/src/reference/aggregate-query.ts @@ -22,6 +22,8 @@ import * as deepEqual from 'fast-deep-equal'; import * as firestore from '@google-cloud/firestore'; import {Aggregate, AggregateSpec} from '../aggregate'; +import {AggregateTarget, avg, count, countAll, Field, sum} from '../expression'; +import {Pipeline} from '../pipeline'; import {Timestamp} from '../timestamp'; import {mapToArray, requestTag, wrapError} from '../util'; import {ExplainMetrics, ExplainResults} from '../query-profile'; @@ -331,6 +333,25 @@ export class AggregateQuery< return runQueryRequest; } + toPipeline(): Pipeline { + const aggregates = mapToArray( + this._aggregates, + (aggregate, clientAlias) => { + if (aggregate.aggregateType === 'count') { + if (aggregate._field === undefined) { + return countAll().toField(clientAlias); + } + return count(Field.of(aggregate._field)).toField(clientAlias); + } else if (aggregate.aggregateType === 'avg') { + return avg(Field.of(aggregate._field!)).toField(clientAlias); + } else { + return sum(Field.of(aggregate._field!)).toField(clientAlias); + } + } + ); + return this._query.toPipeline().aggregate(...aggregates); + } + /** * Compares this object with the given object for equality. * diff --git a/dev/src/reference/composite-filter-internal.ts b/dev/src/reference/composite-filter-internal.ts index aa41d8c8d..204f4b87f 100644 --- a/dev/src/reference/composite-filter-internal.ts +++ b/dev/src/reference/composite-filter-internal.ts @@ -40,6 +40,14 @@ export class CompositeFilterInternal extends FilterInternal { return this.operator === 'AND'; } + /** + * @private + * @internal + */ + public _getOperator(): api.StructuredQuery.CompositeFilter.Operator { + return this.operator; + } + public getFlattenedFilters(): FieldFilterInternal[] { if (this.memoizedFlattenedFilters !== null) { return this.memoizedFlattenedFilters; diff --git a/dev/src/reference/field-filter-internal.ts b/dev/src/reference/field-filter-internal.ts index 70ef12725..4728511b5 100644 --- a/dev/src/reference/field-filter-internal.ts +++ b/dev/src/reference/field-filter-internal.ts @@ -48,8 +48,8 @@ export class FieldFilterInternal extends FilterInternal { constructor( private readonly serializer: Serializer, readonly field: FieldPath, - private readonly op: api.StructuredQuery.FieldFilter.Operator, - private readonly value: unknown + readonly op: api.StructuredQuery.FieldFilter.Operator, + readonly value: unknown ) { super(); } @@ -74,6 +74,38 @@ export class FieldFilterInternal extends FilterInternal { } } + /** + * @private + * @internal + */ + isNanChecking(): boolean { + return typeof this.value === 'number' && isNaN(this.value); + } + + /** + * @private + * @internal + */ + nanOp(): 'IS_NAN' | 'IS_NOT_NAN' { + return this.op === 'EQUAL' ? 'IS_NAN' : 'IS_NOT_NAN'; + } + + /** + * @private + * @internal + */ + isNullChecking(): boolean { + return this.value === null; + } + + /** + * @private + * @internal + */ + nullOp(): 'IS_NULL' | 'IS_NOT_NULL' { + return this.op === 'EQUAL' ? 'IS_NULL' : 'IS_NOT_NULL'; + } + /** * Generates the proto representation for this field filter. * @@ -81,24 +113,24 @@ export class FieldFilterInternal extends FilterInternal { * @internal */ toProto(): api.StructuredQuery.IFilter { - if (typeof this.value === 'number' && isNaN(this.value)) { + if (this.isNanChecking()) { return { unaryFilter: { field: { fieldPath: this.field.formattedName, }, - op: this.op === 'EQUAL' ? 'IS_NAN' : 'IS_NOT_NAN', + op: this.nanOp(), }, }; } - if (this.value === null) { + if (this.isNullChecking()) { return { unaryFilter: { field: { fieldPath: this.field.formattedName, }, - op: this.op === 'EQUAL' ? 'IS_NULL' : 'IS_NOT_NULL', + op: this.nullOp(), }, }; } diff --git a/dev/src/reference/query.ts b/dev/src/reference/query.ts index f7664b4d5..ab516e642 100644 --- a/dev/src/reference/query.ts +++ b/dev/src/reference/query.ts @@ -14,48 +14,54 @@ * limitations under the License. */ -import * as protos from '../../protos/firestore_v1_proto_api'; -import api = protos.google.firestore.v1; import * as firestore from '@google-cloud/firestore'; import {GoogleError} from 'google-gax'; import {Transform} from 'stream'; +import * as protos from '../../protos/firestore_v1_proto_api'; +import {Field, Ordering} from '../expression'; -import {QueryUtil} from './query-util'; +import {CompositeFilter, UnaryFilter} from '../filter'; import { - Firestore, AggregateField, DocumentChange, DocumentSnapshot, FieldPath, Filter, + Firestore, QueryDocumentSnapshot, Timestamp, } from '../index'; -import {QueryOptions} from './query-options'; -import {FieldOrder} from './field-order'; -import {FilterInternal} from './filter-internal'; -import {FieldFilterInternal} from './field-filter-internal'; +import {compare} from '../order'; +import {validateFieldPath} from '../path'; +import {Pipeline} from '../pipeline'; +import {toPipelineFilterCondition} from '../pipeline-util'; +import {ExplainResults} from '../query-profile'; +import {Serializer} from '../serializer'; +import {Limit} from '../stage'; +import {defaultConverter} from '../types'; +import { + invalidArgumentMessage, + validateFunction, + validateInteger, + validateMinNumberOfArguments, +} from '../validate'; +import {QueryWatch} from '../watch'; +import {AggregateQuery} from './aggregate-query'; import {CompositeFilterInternal} from './composite-filter-internal'; import {comparisonOperators, directionOperators} from './constants'; -import {VectorQueryOptions} from './vector-query-options'; import {DocumentReference} from './document-reference'; -import {QuerySnapshot} from './query-snapshot'; -import {Serializer} from '../serializer'; -import {ExplainResults} from '../query-profile'; - -import {CompositeFilter, UnaryFilter} from '../filter'; -import {validateFieldPath} from '../path'; +import {FieldFilterInternal} from './field-filter-internal'; +import {FieldOrder} from './field-order'; +import {FilterInternal} from './filter-internal'; import { validateQueryOperator, validateQueryOrder, validateQueryValue, } from './helpers'; -import { - invalidArgumentMessage, - validateFunction, - validateInteger, - validateMinNumberOfArguments, -} from '../validate'; +import {QueryOptions} from './query-options'; +import {QuerySnapshot} from './query-snapshot'; + +import {QueryUtil} from './query-util'; import { LimitType, QueryCursor, @@ -63,11 +69,9 @@ import { QuerySnapshotResponse, QueryStreamElement, } from './types'; -import {AggregateQuery} from './aggregate-query'; import {VectorQuery} from './vector-query'; -import {QueryWatch} from '../watch'; -import {compare} from '../order'; -import {defaultConverter} from '../types'; +import {VectorQueryOptions} from './vector-query-options'; +import api = protos.google.firestore.v1; /** * A Query refers to a query which you can read or stream from. You can also @@ -662,6 +666,80 @@ export class Query< ); } + toPipeline(): Pipeline { + let pipeline; + if (this._queryOptions.allDescendants) { + pipeline = Pipeline.fromCollectionGroup(this._queryOptions.collectionId); + } else { + pipeline = Pipeline.fromCollection( + this._queryOptions.parentPath.append(this._queryOptions.collectionId) + .relativeName + ); + } + + // filters + for (const f of this._queryOptions.filters) { + pipeline = pipeline.filter( + toPipelineFilterCondition(f, this._serializer) + ); + } + + // projections + const projections = this._queryOptions.projection?.fields || []; + if (projections.length > 0) { + pipeline = pipeline.select( + ...projections.map(p => Field.of(p.fieldPath!)) + ); + } + + // orderbys + const orderings = this.createImplicitOrderBy().map(fieldOrder => { + let dir: 'asc' | 'desc' | undefined = undefined; + switch (fieldOrder.direction) { + case 'ASCENDING': { + dir = 'asc'; + break; + } + case 'DESCENDING': { + dir = 'desc'; + break; + } + } + return Ordering.of(Field.of(fieldOrder.field), dir); + }); + if (orderings.length > 0) { + pipeline = pipeline.sort(orderings, 'required', 'unspecified'); + } + + // Cursors, Limit and Offset + if ( + !this._queryOptions.startAt || + !this._queryOptions.endAt || + this._queryOptions.limitType === LimitType.Last + ) { + let paginating = pipeline.paginate(this._queryOptions.limit || 10); + if (this._queryOptions.startAt) { + paginating = paginating.withStartCursor(this._queryOptions.startAt!); + } + if (this._queryOptions.endAt) { + paginating = paginating.withEndCursor(this._queryOptions.endAt!); + } + if (this._queryOptions.limit === LimitType.Last) { + return paginating.lastPage(); + } else { + return paginating.firstPage(); + } + } else { + if (this._queryOptions.offset) { + pipeline = pipeline.offset(this._queryOptions.offset); + } + if (this._queryOptions.limit) { + pipeline = pipeline.offset(this._queryOptions.limit); + } + } + return pipeline; + } + /** * Returns true if this `Query` is equal to the provided value. * @@ -706,7 +784,7 @@ export class Query< * set of field values to use as the boundary. * @returns The implicit ordering semantics. */ - private createImplicitOrderBy( + private createImplicitOrderByForCursor( cursorValuesOrDocumentSnapshot: Array< DocumentSnapshot | unknown > @@ -719,6 +797,10 @@ export class Query< return this._queryOptions.fieldOrders; } + return this.createImplicitOrderBy(); + } + + private createImplicitOrderBy(): FieldOrder[] { const fieldOrders = this._queryOptions.fieldOrders.slice(); const fieldsNormalized = new Set([ ...fieldOrders.map(item => item.field.toString()), @@ -914,7 +996,7 @@ export class Query< 1 ); - const fieldOrders = this.createImplicitOrderBy( + const fieldOrders = this.createImplicitOrderByForCursor( fieldValuesOrDocumentSnapshot ); const startAt = this.createCursor( @@ -958,7 +1040,7 @@ export class Query< 1 ); - const fieldOrders = this.createImplicitOrderBy( + const fieldOrders = this.createImplicitOrderByForCursor( fieldValuesOrDocumentSnapshot ); const startAt = this.createCursor( @@ -1001,7 +1083,7 @@ export class Query< 1 ); - const fieldOrders = this.createImplicitOrderBy( + const fieldOrders = this.createImplicitOrderByForCursor( fieldValuesOrDocumentSnapshot ); const endAt = this.createCursor( @@ -1044,7 +1126,7 @@ export class Query< 1 ); - const fieldOrders = this.createImplicitOrderBy( + const fieldOrders = this.createImplicitOrderByForCursor( fieldValuesOrDocumentSnapshot ); const endAt = this.createCursor( diff --git a/dev/src/reference/types.ts b/dev/src/reference/types.ts index 844233e24..96aa7098e 100644 --- a/dev/src/reference/types.ts +++ b/dev/src/reference/types.ts @@ -15,6 +15,7 @@ */ import * as protos from '../../protos/firestore_v1_proto_api'; +import {PipelineResult} from '../pipeline'; import api = protos.google.firestore.v1; import {Timestamp} from '../timestamp'; @@ -59,6 +60,16 @@ export enum LimitType { Last, } +export interface PipelineStreamElement< + AppModelType = firestore.DocumentData, + DbModelType extends firestore.DocumentData = firestore.DocumentData, +> { + transaction?: Uint8Array; + executionTime?: Timestamp; + explainMetrics?: ExplainMetrics; + result?: PipelineResult; +} + /** * onSnapshot() callback that receives a QuerySnapshot. * diff --git a/dev/src/reference/vector-query.ts b/dev/src/reference/vector-query.ts index 4df93e60f..4f0a8c349 100644 --- a/dev/src/reference/vector-query.ts +++ b/dev/src/reference/vector-query.ts @@ -17,6 +17,9 @@ import * as protos from '../../protos/firestore_v1_proto_api'; import api = protos.google.firestore.v1; import * as firestore from '@google-cloud/firestore'; +import {Field} from '../expression'; +import {Pipeline} from '../pipeline'; +import {FindNearestOptions} from '../stage'; import {Timestamp} from '../timestamp'; import {VectorValue} from '../field-value'; @@ -128,6 +131,16 @@ export class VectorQuery< return result; } + toPipeline(): Pipeline { + const options = { + limit: this.options.limit, + distanceMeasure: this.options.distanceMeasure.toLowerCase(), + } as FindNearestOptions; + return this.query + .toPipeline() + .findNearest(Field.of(this.vectorField), this.queryVector, options); + } + _getResponse( explainOptions?: firestore.ExplainOptions ): Promise>> { diff --git a/dev/src/serializer.ts b/dev/src/serializer.ts index ace53ce4c..8ec31dd6a 100644 --- a/dev/src/serializer.ts +++ b/dev/src/serializer.ts @@ -184,6 +184,13 @@ export class Serializer { } } + if (isObject(val)) { + const _toProto = val['_toProto']; + if (typeof _toProto === 'function') { + return _toProto.bind(val)(this); + } + } + if (Array.isArray(val)) { const array: api.IValue = { arrayValue: {}, diff --git a/dev/src/stage.ts b/dev/src/stage.ts new file mode 100644 index 000000000..0f31aa311 --- /dev/null +++ b/dev/src/stage.ts @@ -0,0 +1,228 @@ +import * as protos from '../protos/firestore_v1_proto_api'; +import api = protos.google.firestore.v1; + +import { + Accumulator, + Expr, + Field, + FilterCondition, + Ordering, +} from './expression'; +import {VectorValue} from './field-value'; +import {DocumentReference} from './reference/document-reference'; +import {Serializer} from './serializer'; + +export interface Stage { + name: string; + _toProto(serializer: Serializer): api.Pipeline.IStage; +} + +export class AddField implements Stage { + name = 'add_field'; + + constructor(private fields: Map) {} + + _toProto(serializer: Serializer): api.Pipeline.IStage { + return { + name: this.name, + args: [serializer.encodeValue(this.fields)!], + }; + } +} + +export class Aggregate implements Stage { + name = 'aggregate'; + + constructor( + private groups: Map, + private accumulators: Map + ) {} + + _toProto(serializer: Serializer): api.Pipeline.IStage { + return { + name: this.name, + args: [ + serializer.encodeValue(this.groups)!, + serializer.encodeValue(this.accumulators)!, + ], + }; + } +} + +export class Collection implements Stage { + name = 'collection'; + + constructor(private collectionPath: string) {} + + _toProto(serializer: Serializer): api.Pipeline.IStage { + return { + name: this.name, + args: [{referenceValue: this.collectionPath}], + }; + } +} + +export class CollectionGroup implements Stage { + name = 'collection_group'; + + constructor(private collectionId: string) {} + + _toProto(serializer: Serializer): api.Pipeline.IStage { + return { + name: this.name, + args: [{referenceValue: ''}, serializer.encodeValue(this.collectionId)!], + }; + } +} + +export class Database implements Stage { + name = 'database'; + + _toProto(serializer: Serializer): api.Pipeline.IStage { + return { + name: this.name, + }; + } +} + +export class Documents implements Stage { + name = 'documents'; + + constructor(private docPaths: string[]) {} + + static of(refs: DocumentReference[]): Documents { + return new Documents(refs.map(ref => '/' + ref.path)); + } + + _toProto(serializer: Serializer): api.Pipeline.IStage { + return { + name: this.name, + args: this.docPaths.map(p => { + return {referenceValue: p}; + }), + }; + } +} + +export class Filter implements Stage { + name = 'filter'; + + constructor(private condition: FilterCondition & Expr) {} + + _toProto(serializer: Serializer): api.Pipeline.IStage { + return { + name: this.name, + args: [this.condition._toProto(serializer)], + }; + } +} + +export interface FindNearestOptions { + limit: number; + distanceMeasure: 'euclidean' | 'cosine' | 'dot_product'; + distanceField?: string; +} + +export class FindNearest implements Stage { + name = 'find_nearest'; + + constructor( + private property: Field, + private vector: FirebaseFirestore.VectorValue | number[], + private options: FindNearestOptions + ) {} + + _toProto(serializer: Serializer): api.Pipeline.IStage { + const options: {[k: string]: api.IValue} = { + limit: serializer.encodeValue(this.options.limit)!, + }; + if (this.options.distanceField) { + options.distance_field = Field.of(this.options.distanceField)._toProto( + serializer + ); + } + + return { + name: this.name, + args: [ + this.property._toProto(serializer), + this.vector instanceof FirebaseFirestore.VectorValue + ? serializer.encodeValue(this.vector)! + : serializer.encodeVector(this.vector), + serializer.encodeValue(this.options.distanceMeasure)!, + ], + options, + }; + } +} + +export class Limit implements Stage { + name = 'limit'; + + constructor(private limit: number) {} + + _toProto(serializer: Serializer): api.Pipeline.IStage { + return { + name: this.name, + args: [serializer.encodeValue(this.limit)!], + }; + } +} + +export class Offset implements Stage { + name = 'offset'; + + constructor(private offset: number) {} + + _toProto(serializer: Serializer): api.Pipeline.IStage { + return { + name: this.name, + args: [serializer.encodeValue(this.offset)!], + }; + } +} + +export class Select implements Stage { + name = 'select'; + + constructor(private projections: Map) {} + + _toProto(serializer: Serializer): api.Pipeline.IStage { + return { + name: this.name, + args: [serializer.encodeValue(this.projections)!], + }; + } +} + +export class Sort implements Stage { + name = 'filter'; + + constructor( + private orders: Ordering[], + private density: 'unspecified' | 'required', + private truncation: 'unspecified' | 'disabled' + ) {} + + _toProto(serializer: Serializer): api.Pipeline.IStage { + return { + name: this.name, + args: this.orders.map(o => o._toProto(serializer)), + options: { + density: serializer.encodeValue(this.density)!, + truncation: serializer.encodeValue(this.truncation)!, + }, + }; + } +} + +export class GenerateStage implements Stage { + constructor( + public name: string, + params: any[] + ) {} + + _toProto(serializer: Serializer): api.Pipeline.Stage { + return new api.Pipeline.Stage(); + } +} diff --git a/dev/src/types.ts b/dev/src/types.ts index ac7a62d22..45d926818 100644 --- a/dev/src/types.ts +++ b/dev/src/types.ts @@ -64,6 +64,10 @@ export interface GapicClient { request?: api.IBatchGetDocumentsRequest, options?: CallOptions ): Duplex; + executePipeline( + request?: api.IExecutePipelineRequest, + options?: CallOptions + ): Duplex; runQuery(request?: api.IRunQueryRequest, options?: CallOptions): Duplex; runAggregationQuery( request?: api.IRunAggregationQueryRequest, @@ -96,6 +100,7 @@ export type FirestoreUnaryMethod = /** Streaming methods used in the Firestore SDK. */ export type FirestoreStreamingMethod = + | 'executePipeline' | 'listen' | 'partitionQueryStream' | 'runQuery' diff --git a/types/firestore.d.ts b/types/firestore.d.ts index 702e5ee84..76cf5e10f 100644 --- a/types/firestore.d.ts +++ b/types/firestore.d.ts @@ -39,8 +39,8 @@ declare namespace FirebaseFirestore { | (T extends Primitive ? T : T extends {} - ? {[K in keyof T]?: PartialWithFieldValue | FieldValue} - : never); + ? {[K in keyof T]?: PartialWithFieldValue | FieldValue} + : never); /** * Allows FieldValues to be passed in as a property value while maintaining @@ -51,8 +51,8 @@ declare namespace FirebaseFirestore { | (T extends Primitive ? T : T extends {} - ? {[K in keyof T]: WithFieldValue | FieldValue} - : never); + ? {[K in keyof T]: WithFieldValue | FieldValue} + : never); /** * Update data (for use with [update]{@link DocumentReference#update}) @@ -71,8 +71,8 @@ declare namespace FirebaseFirestore { export type UpdateData = T extends Primitive ? T : T extends {} - ? {[K in keyof T]?: UpdateData | FieldValue} & NestedUpdateFields - : Partial; + ? {[K in keyof T]?: UpdateData | FieldValue} & NestedUpdateFields + : Partial; /** Primitive types. */ export type Primitive = string | number | boolean | undefined | null; From 25ee91a40da7cededc03302369704e12c340af66 Mon Sep 17 00:00:00 2001 From: Wu-Hui Date: Thu, 25 Jul 2024 14:53:09 -0400 Subject: [PATCH 03/60] can run pipelines --- dev/src/expression.ts | 54 +- dev/src/index.ts | 5 + dev/src/pipeline-util.ts | 255 +-- dev/src/pipeline.ts | 89 +- dev/src/reference/query.ts | 42 +- dev/src/reference/vector-query.ts | 1 + dev/src/serializer.ts | 15 + dev/src/stage.ts | 16 +- dev/src/v1/firestore_client.ts | 22 + dev/src/v1/firestore_client_config.json | 5 + dev/system-test/firestore.ts | 2118 +-------------------- dev/system-test/pipeline.ts | 99 + dev/system-test/query.ts | 2234 +++++++++++++++++++++++ 13 files changed, 2668 insertions(+), 2287 deletions(-) create mode 100644 dev/system-test/pipeline.ts create mode 100644 dev/system-test/query.ts diff --git a/dev/src/expression.ts b/dev/src/expression.ts index 0387699d3..e2642407b 100644 --- a/dev/src/expression.ts +++ b/dev/src/expression.ts @@ -1,6 +1,8 @@ import * as protos from '../protos/firestore_v1_proto_api'; import api = protos.google.firestore.v1; +import * as firestore from '@google-cloud/firestore'; + import {VectorValue} from './field-value'; import {GeoPoint} from './geo-point'; import {FieldPath} from './path'; @@ -127,6 +129,10 @@ export abstract class Expr { return new IsNull(this); } + exists(): Exists { + return new Exists(this); + } + count(): Count { return new Count(this, false); } @@ -203,26 +209,36 @@ export class Field extends Expr implements Selectable { selectable = true as const; private constructor( - private fieldPath: FirebaseFirestore.FieldPath, + private fieldPath: firestore.FieldPath, private pipeline: Pipeline | null = null ) { super(); } static of(name: string): Field; - static of(path: FirebaseFirestore.FieldPath): Field; - static of(nameOrPath: string | FirebaseFirestore.FieldPath): Field; + static of(path: firestore.FieldPath): Field; + static of(nameOrPath: string | firestore.FieldPath): Field; static of(pipeline: Pipeline, name: string): Field; static of( - pipelineOrName: Pipeline | string | FirebaseFirestore.FieldPath, + pipelineOrName: Pipeline | string | firestore.FieldPath, name?: string ): Field { if (typeof pipelineOrName === 'string') { + if (FieldPath.documentId().formattedName === pipelineOrName) { + return new Field(new FieldPath('__path__')); + } + return new Field(FieldPath.fromArgument(pipelineOrName)); - } else if (pipelineOrName instanceof FirebaseFirestore.FieldPath) { + } else if (pipelineOrName instanceof FieldPath) { + if (FieldPath.documentId().isEqual(pipelineOrName)) { + return new Field(new FieldPath('__path__')); + } return new Field(pipelineOrName); } else { - return new Field(FieldPath.fromArgument(name!), pipelineOrName); + return new Field( + FieldPath.fromArgument(name!), + pipelineOrName as Pipeline + ); } } @@ -424,6 +440,14 @@ class IsNan extends Function implements FilterCondition { } filterable = true as const; } + +class Exists extends Function implements FilterCondition { + constructor(private expr: Expr) { + super('exists', [expr]); + } + filterable = true as const; +} + class IsNull extends Function implements FilterCondition { constructor(private expr: Expr) { super('is_null', [expr]); @@ -666,6 +690,14 @@ export function not(filter: FilterExpr): Not { return new Not(filter); } +export function exists(value: Expr): Exists; +export function exists(field: string): Exists; +export function exists(valueOrField: Expr | string): Exists { + const valueExpr = + valueOrField instanceof Expr ? valueOrField : Field.of(valueOrField); + return new Exists(valueExpr); +} + export function isNull(value: Expr): IsNull; export function isNull(value: string): IsNull; export function isNull(value: Expr | string): IsNull { @@ -774,20 +806,20 @@ function genericFunction(name: string, params: Expr[]): Function { export class Ordering { constructor( private expr: Expr, - private direction: 'asc' | 'desc' + private direction: 'ascending' | 'descending' ) {} static of( expr: Expr, - direction: 'asc' | 'desc' | undefined = undefined + direction: 'ascending' | 'descending' | undefined = undefined ): Ordering { - return new Ordering(expr, direction || 'asc'); + return new Ordering(expr, direction || 'ascending'); } static ascending(expr: Expr): Ordering { - return new Ordering(expr, 'asc'); + return new Ordering(expr, 'ascending'); } static descending(expr: Expr): Ordering { - return new Ordering(expr, 'desc'); + return new Ordering(expr, 'descending'); } _toProto(serializer: Serializer): api.IValue { diff --git a/dev/src/index.ts b/dev/src/index.ts index 8d470c29e..61982a432 100644 --- a/dev/src/index.ts +++ b/dev/src/index.ts @@ -41,6 +41,7 @@ import { ResourcePath, validateResourcePath, } from './path'; +import {PipelineSource} from './pipeline'; import {ClientPool} from './pool'; import {CollectionReference} from './reference/collection-reference'; import {DocumentReference} from './reference/document-reference'; @@ -898,6 +899,10 @@ export class Firestore implements firestore.Firestore { return new CollectionGroup(this, collectionId, /* converter= */ undefined); } + pipeline(): PipelineSource { + return new PipelineSource(this); + } + /** * Creates a [WriteBatch]{@link WriteBatch}, used for performing * multiple writes as a single atomic operation. diff --git a/dev/src/pipeline-util.ts b/dev/src/pipeline-util.ts index ef42b9138..8b814e0a6 100644 --- a/dev/src/pipeline-util.ts +++ b/dev/src/pipeline-util.ts @@ -72,18 +72,20 @@ export class ExecutionUtil< }) .on( 'data', - (data: PipelineStreamElement) => { - if (data.transaction) { - output.transaction = data.transaction; - } - if (data.executionTime) { - output.executionTime = data.executionTime; - } - if (data.explainMetrics) { - output.explainMetrics = data.explainMetrics; - } - if (data.result) { - results.push(data.result); + (data: PipelineStreamElement[]) => { + for (const element of data) { + if (element.transaction) { + output.transaction = element.transaction; + } + if (element.executionTime) { + output.executionTime = element.executionTime; + } + if (element.explainMetrics) { + output.explainMetrics = element.explainMetrics; + } + if (element.result) { + results.push(element.result); + } } } ) @@ -142,41 +144,55 @@ export class ExecutionUtil< enc, callback ) => { + console.log(`Pipeline response: ${JSON.stringify(proto, null, 2)}`); if (proto === NOOP_MESSAGE) { callback(undefined); return; } - if (proto.results) { - for (const r of proto.results) { - const output: PipelineStreamElement = {}; - - // Proto comes with zero-length buffer by default - if (proto.transaction?.length) { - output.transaction = proto.transaction; - } - - if (proto.executionTime) { - output.executionTime = Timestamp.fromProto(proto.executionTime); - } - - const ref = r.name - ? new DocumentReference( - this._firestore, - QualifiedResourcePath.fromSlashSeparatedString(r.name) - ) - : undefined; - output.result = new PipelineResult( - this._serializer, - ref, - r.fields, - Timestamp.fromProto(proto.executionTime!), - r.createTime ? Timestamp.fromProto(r.createTime!) : undefined, - r.updateTime ? Timestamp.fromProto(r.updateTime!) : undefined - ); - - callback(undefined, output); + if (proto.results && proto.results.length === 0) { + const output: PipelineStreamElement = {}; + if (proto.transaction?.length) { + output.transaction = proto.transaction; } + if (proto.executionTime) { + output.executionTime = Timestamp.fromProto(proto.executionTime); + } + callback(undefined, [output]); + } else { + callback( + undefined, + proto.results.map(result => { + const output: PipelineStreamElement = + {}; + if (proto.transaction?.length) { + output.transaction = proto.transaction; + } + if (proto.executionTime) { + output.executionTime = Timestamp.fromProto(proto.executionTime); + } + + const ref = result.name + ? new DocumentReference( + this._firestore, + QualifiedResourcePath.fromSlashSeparatedString(result.name) + ) + : undefined; + output.result = new PipelineResult( + this._serializer, + ref, + result.fields, + Timestamp.fromProto(proto.executionTime!), + result.createTime + ? Timestamp.fromProto(result.createTime!) + : undefined, + result.updateTime + ? Timestamp.fromProto(result.updateTime!) + : undefined + ); + return output; + }) + ); } }, }); @@ -188,11 +204,14 @@ export class ExecutionUtil< // async function to convert this exception into the rejected Promise we // catch below. const request = pipeline._toProto( - this._firestore, transactionOrReadTime, explainOptions ); + console.log( + `Executing pipeline: \n ${JSON.stringify(request, null, 2)}` + ); + let streamActive: Deferred; do { streamActive = new Deferred(); @@ -207,9 +226,9 @@ export class ExecutionUtil< backendStream.unpipe(stream); logger( - 'QueryUtil._stream', + 'PipelineUtil._stream', tag, - 'Query failed with stream error:', + 'Pipeline failed with stream error:', err ); stream.destroy(err); @@ -222,7 +241,15 @@ export class ExecutionUtil< backendStream.pipe(stream); } while (await streamActive.promise); }) - .catch(e => stream.destroy(e)); + .catch(e => { + logger( + 'PipelineUtil._stream', + tag, + 'Pipeline failed with stream error:', + e + ); + stream.destroy(e); + }); return stream; } @@ -233,77 +260,78 @@ function isITimestamp(obj: any): obj is google.protobuf.ITimestamp { return false; // Must be a non-null object } if ( - ('seconds' in obj && - !( - obj.seconds === null || - typeof obj.seconds === 'number' || - typeof obj.seconds === 'string' - )) || - ('nanos' in obj && !(obj.nanos === null || typeof obj.nanos === 'number')) + 'seconds' in obj && + (obj.seconds === null || + typeof obj.seconds === 'number' || + typeof obj.seconds === 'string') && + 'nanos' in obj && + (obj.nanos === null || typeof obj.nanos === 'number') ) { - return false; // Invalid property type + return true; } - return true; // All checks passed + return false; } function isILatLng(obj: any): obj is google.type.ILatLng { if (typeof obj !== 'object' || obj === null) { return false; // Must be a non-null object } if ( - ('latitude' in obj && - !(obj.latitude === null || typeof obj.latitude === 'number')) || - ('longitude' in obj && - !(obj.longitude === null || typeof obj.longitude === 'number')) + 'latitude' in obj && + (obj.latitude === null || typeof obj.latitude === 'number') && + 'longitude' in obj && + (obj.longitude === null || typeof obj.longitude === 'number') ) { - return false; // Invalid property type + return true; } - return true; // All checks passed + return false; } function isIArrayValue(obj: any): obj is api.IArrayValue { if (typeof obj !== 'object' || obj === null) { return false; // Must be a non-null object } - if ('values' in obj && !(obj.values === null || Array.isArray(obj.values))) { - return false; // Invalid property type + if ('values' in obj && (obj.values === null || Array.isArray(obj.values))) { + return true; } - return true; // All checks passed + return false; } function isIMapValue(obj: any): obj is api.IMapValue { if (typeof obj !== 'object' || obj === null) { return false; // Must be a non-null object } - if ('fields' in obj && !(obj.fields === null || isObject(obj.fields))) { - return false; // Invalid property type + if ('fields' in obj && (obj.fields === null || isObject(obj.fields))) { + return true; } - return true; // All checks passed + return false; } function isIFunction(obj: any): obj is api.IFunction { if (typeof obj !== 'object' || obj === null) { return false; // Must be a non-null object } if ( - ('name' in obj && !(obj.name === null || typeof obj.name === 'string')) || - ('args' in obj && !(obj.args === null || Array.isArray(obj.args))) + 'name' in obj && + (obj.name === null || typeof obj.name === 'string') && + 'args' in obj && + (obj.args === null || Array.isArray(obj.args)) ) { - return false; // Invalid property type + return true; } - return true; // All checks passed + return false; } function isIPipeline(obj: any): obj is api.IPipeline { if (typeof obj !== 'object' || obj === null) { return false; // Must be a non-null object } - if ('stages' in obj && !(obj.stages === null || Array.isArray(obj.stages))) { - return false; // Invalid property type + if ('stages' in obj && (obj.stages === null || Array.isArray(obj.stages))) { + return true; } - return true; // All checks passed + return false; } export function isFirestoreValue(obj: any): obj is api.IValue { @@ -314,50 +342,42 @@ export function isFirestoreValue(obj: any): obj is api.IValue { // Check optional properties and their types if ( ('nullValue' in obj && - !( - obj.nullValue === null || - obj.nullValue instanceof google.protobuf.BoolValue - )) || + (obj.nullValue === null || obj.nullValue === 'NULL_VALUE')) || ('booleanValue' in obj && - !(obj.booleanValue === null || typeof obj.booleanValue === 'boolean')) || + (obj.booleanValue === null || typeof obj.booleanValue === 'boolean')) || ('integerValue' in obj && - !( - obj.integerValue === null || + (obj.integerValue === null || typeof obj.integerValue === 'number' || - typeof obj.integerValue === 'string' - )) || + typeof obj.integerValue === 'string')) || ('doubleValue' in obj && - !(obj.doubleValue === null || typeof obj.doubleValue === 'number')) || + (obj.doubleValue === null || typeof obj.doubleValue === 'number')) || ('timestampValue' in obj && - !(obj.timestampValue === null || isITimestamp(obj.timestampValue))) || + (obj.timestampValue === null || isITimestamp(obj.timestampValue))) || ('stringValue' in obj && - !(obj.stringValue === null || typeof obj.stringValue === 'string')) || + (obj.stringValue === null || typeof obj.stringValue === 'string')) || ('bytesValue' in obj && - !(obj.bytesValue === null || obj.bytesValue instanceof Uint8Array)) || + (obj.bytesValue === null || obj.bytesValue instanceof Uint8Array)) || ('referenceValue' in obj && - !( - obj.referenceValue === null || typeof obj.referenceValue === 'string' - )) || + (obj.referenceValue === null || + typeof obj.referenceValue === 'string')) || ('geoPointValue' in obj && - !(obj.geoPointValue === null || isILatLng(obj.geoPointValue))) || + (obj.geoPointValue === null || isILatLng(obj.geoPointValue))) || ('arrayValue' in obj && - !(obj.arrayValue === null || isIArrayValue(obj.arrayValue))) || + (obj.arrayValue === null || isIArrayValue(obj.arrayValue))) || ('mapValue' in obj && - !(obj.mapValue === null || isIMapValue(obj.mapValue))) || + (obj.mapValue === null || isIMapValue(obj.mapValue))) || ('fieldReferenceValue' in obj && - !( - obj.fieldReferenceValue === null || - typeof obj.fieldReferenceValue === 'string' - )) || + (obj.fieldReferenceValue === null || + typeof obj.fieldReferenceValue === 'string')) || ('functionValue' in obj && - !(obj.functionValue === null || isIFunction(obj.functionValue))) || + (obj.functionValue === null || isIFunction(obj.functionValue))) || ('pipelineValue' in obj && - !(obj.pipelineValue === null || isIPipeline(obj.pipelineValue))) + (obj.pipelineValue === null || isIPipeline(obj.pipelineValue))) ) { - return false; // Invalid property type + return true; } - return true; // All checks passed + return false; } export function toPipelineFilterCondition( @@ -365,17 +385,18 @@ export function toPipelineFilterCondition( serializer: Serializer ): FilterCondition & Expr { if (f instanceof FieldFilterInternal) { + const field = Field.of(f.field); if (f.isNanChecking()) { if (f.nanOp() === 'IS_NAN') { - return Field.of(f.field).isNaN(); + return and(field.exists(), field.isNaN()); } else { - return not(Field.of(f.field).isNaN()); + return and(field.exists(), not(field.isNaN())); } } else if (f.isNullChecking()) { if (f.nullOp() === 'IS_NULL') { - return Field.of(f.field).isNull(); + return and(field.exists(), field.isNull()); } else { - return not(Field.of(f.field).isNull()); + return and(field.exists(), not(field.isNull())); } } else { // Comparison filters @@ -384,36 +405,36 @@ export function toPipelineFilterCondition( : serializer.encodeValue(f.value); switch (f.op) { case 'LESS_THAN': - return Field.of(f.field).lessThan(value); + return and(field.exists(), field.lessThan(value)); case 'LESS_THAN_OR_EQUAL': - return Field.of(f.field).lessThanOrEqual(value); + return and(field.exists(), field.lessThanOrEqual(value)); case 'GREATER_THAN': - return Field.of(f.field).greaterThan(value); + return and(field.exists(), field.greaterThan(value)); case 'GREATER_THAN_OR_EQUAL': - return Field.of(f.field).greaterThanOrEqual(value); + return and(field.exists(), field.greaterThanOrEqual(value)); case 'EQUAL': - return Field.of(f.field).equal(value); + return and(field.exists(), field.equal(value)); case 'NOT_EQUAL': - return Field.of(f.field).notEqual(value); + return and(field.exists(), field.notEqual(value)); case 'ARRAY_CONTAINS': - return Field.of(f.field).arrayContains(value); + return and(field.exists(), field.arrayContains(value)); case 'IN': { const values = value?.arrayValue?.values?.map(val => - Constant.of(value) + Constant.of(val) ); - return Field.of(f.field).in(...values!); + return and(field.exists(), field.in(...values!)); } case 'ARRAY_CONTAINS_ANY': { const values = value?.arrayValue?.values?.map(val => - Constant.of(value) + Constant.of(val) ); - return Field.of(f.field).arrayContainsAny(values!); + return and(field.exists(), field.arrayContainsAny(values!)); } case 'NOT_IN': { const values = value?.arrayValue?.values?.map(val => - Constant.of(value) + Constant.of(val) ); - return not(Field.of(f.field).in(...values!)); + return and(field.exists(), not(field.in(...values!))); } } } diff --git a/dev/src/pipeline.ts b/dev/src/pipeline.ts index eb0cf038e..7ab677218 100644 --- a/dev/src/pipeline.ts +++ b/dev/src/pipeline.ts @@ -10,7 +10,6 @@ import { Ordering, Selectable, } from './expression'; -import {VectorValue} from './field-value'; import Firestore, {Timestamp} from './index'; import {ExecutionUtil} from './pipeline-util'; import {DocumentReference} from './reference/document-reference'; @@ -22,7 +21,7 @@ import { CollectionGroup, Database, Documents, - Filter, + Where, FindNearest, FindNearestOptions, GenerateStage, @@ -39,32 +38,39 @@ import IStructuredPipeline = google.firestore.v1.IStructuredPipeline; import IStage = google.firestore.v1.Pipeline.IStage; import {QueryCursor} from './reference/types'; -export class Pipeline< - AppModelType = firestore.DocumentData, - DbModelType extends firestore.DocumentData = firestore.DocumentData, -> { - private constructor(private stages: Stage[]) {} +export class PipelineSource { + constructor(private db: Firestore) {} - static fromCollection(collectionPath: string): Pipeline { - return new Pipeline([new Collection(collectionPath)]); + collection(collectionPath: string): Pipeline { + return new Pipeline(this.db, [new Collection(collectionPath)]); } - static fromCollectionGroup(collectionId: string): Pipeline { - return new Pipeline([new CollectionGroup(collectionId)]); + collectionGroup(collectionId: string): Pipeline { + return new Pipeline(this.db, [new CollectionGroup(collectionId)]); } - static fromDatabase(): Pipeline { - return new Pipeline([new Database()]); + database(): Pipeline { + return new Pipeline(this.db, [new Database()]); } - static fromDocuments(docs: DocumentReference[]): Pipeline { - return new Pipeline([Documents.of(docs)]); + documents(docs: DocumentReference[]): Pipeline { + return new Pipeline(this.db, [Documents.of(docs)]); } +} + +export class Pipeline< + AppModelType = firestore.DocumentData, + DbModelType extends firestore.DocumentData = firestore.DocumentData, +> { + constructor( + private db: Firestore, + private stages: Stage[] + ) {} addFields(...fields: Selectable[]): Pipeline { const copy = this.stages.map(s => s); copy.push(new AddField(this.selectablesToMap(fields))); - return new Pipeline(copy); + return new Pipeline(this.db, copy); } select(...fields: string[]): Pipeline; @@ -72,7 +78,7 @@ export class Pipeline< select(...fields: (Selectable | string)[]): Pipeline { const copy = this.stages.map(s => s); copy.push(new Select(this.selectablesToMap(fields))); - return new Pipeline(copy); + return new Pipeline(this.db, copy); } private selectablesToMap( @@ -97,22 +103,22 @@ export class Pipeline< return result; } - filter(condition: FilterCondition & Expr): Pipeline { + where(condition: FilterCondition & Expr): Pipeline { const copy = this.stages.map(s => s); - copy.push(new Filter(condition)); - return new Pipeline(copy); + copy.push(new Where(condition)); + return new Pipeline(this.db, copy); } offset(offset: number): Pipeline { const copy = this.stages.map(s => s); copy.push(new Offset(offset)); - return new Pipeline(copy); + return new Pipeline(this.db, copy); } limit(limit: number): Pipeline { const copy = this.stages.map(s => s); copy.push(new Limit(limit)); - return new Pipeline(copy); + return new Pipeline(this.db, copy); } aggregate(...targets: AggregateTarget[]): Pipeline { @@ -125,7 +131,7 @@ export class Pipeline< ) ) ); - return new Pipeline(copy); + return new Pipeline(this.db, copy); } findNearest( @@ -151,7 +157,7 @@ export class Pipeline< const copy = this.stages.map(s => s); const fieldExpr = typeof field === 'string' ? Field.of(field) : field; copy.push(new FindNearest(fieldExpr, vector, options)); - return new Pipeline(copy); + return new Pipeline(this.db, copy); } sort(orderings: Ordering[]): Pipeline; @@ -169,49 +175,50 @@ export class Pipeline< copy.push( new Sort(orderings, density ?? 'unspecified', truncation ?? 'unspecified') ); - return new Pipeline(copy); + return new Pipeline(this.db, copy); } paginate(pageSize: number, orderings?: Ordering[]): PaginatingPipeline { const copy = this.stages.map(s => s); - return new PaginatingPipeline(new Pipeline(copy), pageSize, orderings); + return new PaginatingPipeline( + new Pipeline(this.db, copy), + pageSize, + orderings + ); } genericStage(name: string, params: any[]): Pipeline { const copy = this.stages.map(s => s); copy.push(new GenerateStage(name, params)); - return new Pipeline(copy); + return new Pipeline(this.db, copy); } - execute( - db: Firestore - ): Promise>> { + execute(): Promise>> { const util = new ExecutionUtil( - db, - db._serializer! + this.db, + this.db._serializer! ); return util._getResponse(this).then(result => result!); } - stream(db: Firestore): NodeJS.ReadableStream { + stream(): NodeJS.ReadableStream { const util = new ExecutionUtil( - db, - db._serializer! + this.db, + this.db._serializer! ); return util.stream(this); } _toProto( - db: Firestore, transactionOrReadTime?: Uint8Array | Timestamp | api.ITransactionOptions, explainOptions?: FirebaseFirestore.ExplainOptions ): api.IExecutePipelineRequest { const stages: IStage[] = this.stages.map(stage => - stage._toProto(db._serializer!) + stage._toProto(this.db._serializer!) ); const structuredPipeline: IStructuredPipeline = {pipeline: {stages}}; return { - database: db.formattedName, + database: this.db.formattedName, structuredPipeline, }; } @@ -278,9 +285,9 @@ export class PipelineResult< > { private _ref: DocumentReference | undefined; private _serializer: Serializer; - private _readTime: Timestamp | undefined; - private _createTime: Timestamp | undefined; - private _updateTime: Timestamp | undefined; + public readonly _readTime: Timestamp | undefined; + public readonly _createTime: Timestamp | undefined; + public readonly _updateTime: Timestamp | undefined; /** * @private diff --git a/dev/src/reference/query.ts b/dev/src/reference/query.ts index ab516e642..75f6706b8 100644 --- a/dev/src/reference/query.ts +++ b/dev/src/reference/query.ts @@ -18,7 +18,7 @@ import * as firestore from '@google-cloud/firestore'; import {GoogleError} from 'google-gax'; import {Transform} from 'stream'; import * as protos from '../../protos/firestore_v1_proto_api'; -import {Field, Ordering} from '../expression'; +import {and, Field, Ordering} from '../expression'; import {CompositeFilter, UnaryFilter} from '../filter'; import { @@ -669,19 +669,21 @@ export class Query< toPipeline(): Pipeline { let pipeline; if (this._queryOptions.allDescendants) { - pipeline = Pipeline.fromCollectionGroup(this._queryOptions.collectionId); + pipeline = this.firestore + .pipeline() + .collectionGroup(this._queryOptions.collectionId); } else { - pipeline = Pipeline.fromCollection( - this._queryOptions.parentPath.append(this._queryOptions.collectionId) - .relativeName - ); + pipeline = this.firestore + .pipeline() + .collection( + this._queryOptions.parentPath.append(this._queryOptions.collectionId) + .relativeName + ); } // filters for (const f of this._queryOptions.filters) { - pipeline = pipeline.filter( - toPipelineFilterCondition(f, this._serializer) - ); + pipeline = pipeline.where(toPipelineFilterCondition(f, this._serializer)); } // projections @@ -693,15 +695,25 @@ export class Query< } // orderbys + const exists = this.createImplicitOrderBy().map(fieldOrder => { + return Field.of(fieldOrder.field).exists(); + }); + if (exists.length > 1) { + const [first, ...rest] = exists; + pipeline = pipeline.where(and(first, ...rest)); + } else if (exists.length == 1) { + pipeline = pipeline.where(exists[0]); + } + const orderings = this.createImplicitOrderBy().map(fieldOrder => { - let dir: 'asc' | 'desc' | undefined = undefined; + let dir: 'ascending' | 'descending' | undefined = undefined; switch (fieldOrder.direction) { case 'ASCENDING': { - dir = 'asc'; + dir = 'ascending'; break; } case 'DESCENDING': { - dir = 'desc'; + dir = 'descending'; break; } } @@ -713,8 +725,8 @@ export class Query< // Cursors, Limit and Offset if ( - !this._queryOptions.startAt || - !this._queryOptions.endAt || + !!this._queryOptions.startAt || + !!this._queryOptions.endAt || this._queryOptions.limitType === LimitType.Last ) { let paginating = pipeline.paginate(this._queryOptions.limit || 10); @@ -734,7 +746,7 @@ export class Query< pipeline = pipeline.offset(this._queryOptions.offset); } if (this._queryOptions.limit) { - pipeline = pipeline.offset(this._queryOptions.limit); + pipeline = pipeline.limit(this._queryOptions.limit); } } return pipeline; diff --git a/dev/src/reference/vector-query.ts b/dev/src/reference/vector-query.ts index 4f0a8c349..ad853c73b 100644 --- a/dev/src/reference/vector-query.ts +++ b/dev/src/reference/vector-query.ts @@ -138,6 +138,7 @@ export class VectorQuery< } as FindNearestOptions; return this.query .toPipeline() + .where(Field.of(this.vectorField).exists()) .findNearest(Field.of(this.vectorField), this.queryVector, options); } diff --git a/dev/src/serializer.ts b/dev/src/serializer.ts index 8ec31dd6a..a66bba1b4 100644 --- a/dev/src/serializer.ts +++ b/dev/src/serializer.ts @@ -209,6 +209,21 @@ export class Serializer { return array; } + if (val instanceof Map) { + const map: api.IMapValue = {fields: {}}; + for (const [key, value] of val.entries()) { + if (typeof key !== 'string') { + throw new Error(`Cannot encode map with non-string key: ${key}`); + } + + map.fields![key] = this.encodeValue(value)!; + } + + return { + mapValue: map, + }; + } + if (typeof val === 'object' && isPlainObject(val)) { const map: api.IValue = { mapValue: {}, diff --git a/dev/src/stage.ts b/dev/src/stage.ts index 0f31aa311..ca8d5f39b 100644 --- a/dev/src/stage.ts +++ b/dev/src/stage.ts @@ -52,7 +52,11 @@ export class Aggregate implements Stage { export class Collection implements Stage { name = 'collection'; - constructor(private collectionPath: string) {} + constructor(private collectionPath: string) { + if (!this.collectionPath.startsWith('/')) { + this.collectionPath = '/' + this.collectionPath; + } + } _toProto(serializer: Serializer): api.Pipeline.IStage { return { @@ -104,8 +108,8 @@ export class Documents implements Stage { } } -export class Filter implements Stage { - name = 'filter'; +export class Where implements Stage { + name = 'where'; constructor(private condition: FilterCondition & Expr) {} @@ -146,9 +150,9 @@ export class FindNearest implements Stage { name: this.name, args: [ this.property._toProto(serializer), - this.vector instanceof FirebaseFirestore.VectorValue + this.vector instanceof VectorValue ? serializer.encodeValue(this.vector)! - : serializer.encodeVector(this.vector), + : serializer.encodeVector(this.vector as number[]), serializer.encodeValue(this.options.distanceMeasure)!, ], options, @@ -196,7 +200,7 @@ export class Select implements Stage { } export class Sort implements Stage { - name = 'filter'; + name = 'sort'; constructor( private orders: Ordering[], diff --git a/dev/src/v1/firestore_client.ts b/dev/src/v1/firestore_client.ts index e1f4b242d..9affa770c 100644 --- a/dev/src/v1/firestore_client.ts +++ b/dev/src/v1/firestore_client.ts @@ -242,6 +242,11 @@ export class FirestoreClient { !!opts.fallback, !!opts.gaxServerStreamingRetries ), + executePipeline: new this._gaxModule.StreamDescriptor( + this._gaxModule.StreamType.SERVER_STREAMING, + !!opts.fallback, + !!opts.gaxServerStreamingRetries + ), runAggregationQuery: new this._gaxModule.StreamDescriptor( this._gaxModule.StreamType.SERVER_STREAMING, !!opts.fallback, @@ -317,6 +322,7 @@ export class FirestoreClient { 'beginTransaction', 'commit', 'rollback', + 'executePipeline', 'runQuery', 'runAggregationQuery', 'partitionQuery', @@ -1316,6 +1322,22 @@ export class FirestoreClient { return this.innerApiCalls.runQuery(request, options); } + executePipeline( + request?: protos.google.firestore.v1.IExecutePipelineRequest, + options?: CallOptions + ): gax.CancellableStream { + request = request || {}; + options = options || {}; + options.otherArgs = options.otherArgs || {}; + options.otherArgs.headers = options.otherArgs.headers || {}; + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + parent: '', + }); + this.initialize(); + return this.innerApiCalls.executePipeline(request, options); + } + /** * Runs an aggregation query. * diff --git a/dev/src/v1/firestore_client_config.json b/dev/src/v1/firestore_client_config.json index 75487fc9b..47cbabb90 100644 --- a/dev/src/v1/firestore_client_config.json +++ b/dev/src/v1/firestore_client_config.json @@ -80,6 +80,11 @@ "retry_codes_name": "deadline_exceeded_resource_exhausted_internal_unavailable", "retry_params_name": "default" }, + "ExecutePipeline": { + "timeout_millis": 300000, + "retry_codes_name": "deadline_exceeded_resource_exhausted_internal_unavailable", + "retry_params_name": "default" + }, "RunAggregationQuery": { "timeout_millis": 300000, "retry_codes_name": "deadline_exceeded_resource_exhausted_internal_unavailable", diff --git a/dev/system-test/firestore.ts b/dev/system-test/firestore.ts index 5f7d683d7..cf040220b 100644 --- a/dev/system-test/firestore.ts +++ b/dev/system-test/firestore.ts @@ -65,7 +65,7 @@ use(chaiAsPromised); const version = require('../../package.json').version; -class DeferredPromise { +export class DeferredPromise { resolve: Function; reject: Function; promise: Promise | null; @@ -101,12 +101,31 @@ if (process.env.NODE_ENV === 'DEBUG') { setLogFunction(console.log); } -function getTestRoot(settings: Settings = {}): CollectionReference { +export function getTestRoot(settings: Settings = {}): CollectionReference { const internalSettings: Settings = {}; if (process.env.FIRESTORE_NAMED_DATABASE) { internalSettings.databaseId = process.env.FIRESTORE_NAMED_DATABASE; } + if (process.env.FIRESTORE_TARGET_BACKEND) { + switch (process.env.FIRESTORE_TARGET_BACKEND.toUpperCase()) { + case 'PROD': { + break; + } + case 'QA': { + internalSettings.host = 'staging-firestore.sandbox.googleapis.com'; + break; + } + case 'NIGHTLY': { + internalSettings.host = 'test-firestore.sandbox.googleapis.com'; + break; + } + default: { + break; + } + } + } + const firestore = new Firestore({ ...internalSettings, ...settings, // caller settings take precedent over internal settings @@ -1813,2101 +1832,6 @@ describe('runs query on a large collection', () => { }); }); -describe('Query class', () => { - interface PaginatedResults { - pages: number; - docs: QueryDocumentSnapshot[]; - } - - let firestore: Firestore; - let randomCol: CollectionReference; - - const paginateResults = ( - query: Query, - startAfter?: unknown - ): Promise => { - return (startAfter ? query.startAfter(startAfter) : query) - .get() - .then(snapshot => { - if (snapshot.empty) { - return {pages: 0, docs: []}; - } else { - const docs = snapshot.docs; - return paginateResults(query, docs[docs.length - 1]).then( - nextPage => { - return { - pages: nextPage.pages + 1, - docs: docs.concat(nextPage.docs), - }; - } - ); - } - }); - }; - - async function addDocs( - ...docs: DocumentData[] - ): Promise { - let id = 0; // Guarantees consistent ordering for the first documents - const refs: DocumentReference[] = []; - for (const doc of docs) { - const ref = randomCol.doc('doc' + id++); - await ref.set(doc); - refs.push(ref); - } - return refs; - } - - async function testCollectionWithDocs(docs: { - [id: string]: DocumentData; - }): Promise> { - for (const id in docs) { - const ref = randomCol.doc(id); - await ref.set(docs[id]); - } - return randomCol; - } - - function expectDocs(result: QuerySnapshot, ...docs: string[]): void; - function expectDocs(result: QuerySnapshot, ...data: DocumentData[]): void; - - function expectDocs( - result: QuerySnapshot, - ...data: DocumentData[] | string[] - ): void { - expect(result.size).to.equal(data.length); - - if (data.length > 0) { - if (typeof data[0] === 'string') { - const actualIds = result.docs.map(docSnapshot => docSnapshot.id); - expect(actualIds).to.deep.equal(data); - } else { - result.forEach(doc => { - expect(doc.data()).to.deep.equal(data.shift()); - }); - } - } - } - - beforeEach(() => { - randomCol = getTestRoot(); - firestore = randomCol.firestore; - }); - - afterEach(() => verifyInstance(firestore)); - - it('has firestore property', () => { - const ref = randomCol.limit(0); - expect(ref.firestore).to.be.an.instanceOf(Firestore); - }); - - it('has select() method', () => { - const ref = randomCol.doc('doc'); - return ref - .set({foo: 'bar', bar: 'foo'}) - .then(() => { - return randomCol.select('foo').get(); - }) - .then(res => { - expect(res.docs[0].data()).to.deep.equal({foo: 'bar'}); - }); - }); - - it('select() supports empty fields', () => { - const ref = randomCol.doc('doc'); - return ref - .set({foo: 'bar', bar: 'foo'}) - .then(() => { - return randomCol.select().get(); - }) - .then(res => { - expect(res.docs[0].ref.id).to.deep.equal('doc'); - expect(res.docs[0].data()).to.deep.equal({}); - }); - }); - - it('has where() method', () => { - const ref = randomCol.doc('doc'); - return ref - .set({foo: 'bar'}) - .then(() => { - return randomCol.where('foo', '==', 'bar').get(); - }) - .then(res => { - expect(res.docs[0].data()).to.deep.equal({foo: 'bar'}); - }); - }); - - it('supports NaN and Null', () => { - const ref = randomCol.doc('doc'); - return ref - .set({foo: NaN, bar: null}) - .then(() => { - return randomCol.where('foo', '==', NaN).where('bar', '==', null).get(); - }) - .then(res => { - expect( - typeof res.docs[0].get('foo') === 'number' && - isNaN(res.docs[0].get('foo')) - ); - expect(res.docs[0].get('bar')).to.equal(null); - }); - }); - - it('supports array-contains', () => { - return Promise.all([ - randomCol.add({foo: ['bar']}), - randomCol.add({foo: []}), - ]) - .then(() => randomCol.where('foo', 'array-contains', 'bar').get()) - .then(res => { - expect(res.size).to.equal(1); - expect(res.docs[0].get('foo')).to.deep.equal(['bar']); - }); - }); - - it('supports findNearest by EUCLIDEAN distance', async () => { - const indexTestHelper = new IndexTestHelper(firestore); - - const collectionReference = await indexTestHelper.createTestDocs([ - {foo: 'bar'}, - {foo: 'xxx', embedding: FieldValue.vector([10, 10])}, - {foo: 'bar', embedding: FieldValue.vector([1, 1])}, - {foo: 'bar', embedding: FieldValue.vector([10, 0])}, - {foo: 'bar', embedding: FieldValue.vector([20, 0])}, - {foo: 'bar', embedding: FieldValue.vector([100, 100])}, - ]); - - const vectorQuery = indexTestHelper - .query(collectionReference) - .where('foo', '==', 'bar') - .findNearest('embedding', [10, 10], { - limit: 3, - distanceMeasure: 'EUCLIDEAN', - }); - - const res = await vectorQuery.get(); - expect(res.size).to.equal(3); - expect(res.docs[0].get('embedding').isEqual(FieldValue.vector([10, 0]))).to - .be.true; - expect(res.docs[1].get('embedding').isEqual(FieldValue.vector([1, 1]))).to - .be.true; - expect(res.docs[2].get('embedding').isEqual(FieldValue.vector([20, 0]))).to - .be.true; - }); - - it('supports findNearest by COSINE distance', async () => { - const indexTestHelper = new IndexTestHelper(firestore); - - const collectionReference = await indexTestHelper.setTestDocs({ - '1': {foo: 'bar'}, - '2': {foo: 'xxx', embedding: FieldValue.vector([10, 10])}, - '3': {foo: 'bar', embedding: FieldValue.vector([1, 1])}, - '4': {foo: 'bar', embedding: FieldValue.vector([20, 0])}, - '5': {foo: 'bar', embedding: FieldValue.vector([10, 0])}, - '6': {foo: 'bar', embedding: FieldValue.vector([100, 100])}, - }); - - const vectorQuery = indexTestHelper - .query(collectionReference) - .where('foo', '==', 'bar') - .findNearest('embedding', [10, 10], { - limit: 3, - distanceMeasure: 'COSINE', - }); - - const res = await vectorQuery.get(); - - expect(res.size).to.equal(3); - - if (res.docs[0].get('embedding').isEqual(FieldValue.vector([1, 1]))) { - expect( - res.docs[1].get('embedding').isEqual(FieldValue.vector([100, 100])) - ).to.be.true; - } else { - expect( - res.docs[0].get('embedding').isEqual(FieldValue.vector([100, 100])) - ).to.be.true; - expect(res.docs[1].get('embedding').isEqual(FieldValue.vector([1, 1]))).to - .be.true; - } - - expect( - res.docs[2].get('embedding').isEqual(FieldValue.vector([20, 0])) || - res.docs[2].get('embedding').isEqual(FieldValue.vector([20, 0])) - ).to.be.true; - }); - - it('supports findNearest by DOT_PRODUCT distance', async () => { - const indexTestHelper = new IndexTestHelper(firestore); - - const collectionReference = await indexTestHelper.createTestDocs([ - {foo: 'bar'}, - {foo: 'xxx', embedding: FieldValue.vector([10, 10])}, - {foo: 'bar', embedding: FieldValue.vector([1, 1])}, - {foo: 'bar', embedding: FieldValue.vector([10, 0])}, - {foo: 'bar', embedding: FieldValue.vector([20, 0])}, - {foo: 'bar', embedding: FieldValue.vector([100, 100])}, - ]); - - const vectorQuery = indexTestHelper - .query(collectionReference) - .where('foo', '==', 'bar') - .findNearest('embedding', [10, 10], { - limit: 3, - distanceMeasure: 'DOT_PRODUCT', - }); - - const res = await vectorQuery.get(); - expect(res.size).to.equal(3); - expect(res.docs[0].get('embedding').isEqual(FieldValue.vector([100, 100]))) - .to.be.true; - expect(res.docs[1].get('embedding').isEqual(FieldValue.vector([20, 0]))).to - .be.true; - expect(res.docs[2].get('embedding').isEqual(FieldValue.vector([10, 0]))).to - .be.true; - }); - - it('findNearest works with converters', async () => { - const indexTestHelper = new IndexTestHelper(firestore); - - class FooDistance { - constructor( - readonly foo: string, - readonly embedding: Array - ) {} - } - - const fooConverter = { - toFirestore(d: FooDistance): DocumentData { - return {title: d.foo, embedding: FieldValue.vector(d.embedding)}; - }, - fromFirestore(snapshot: QueryDocumentSnapshot): FooDistance { - const data = snapshot.data(); - return new FooDistance(data.foo, data.embedding.toArray()); - }, - }; - - const collectionRef = await indexTestHelper.createTestDocs([ - {foo: 'bar', embedding: FieldValue.vector([5, 5])}, - ]); - - const vectorQuery = indexTestHelper - .query(collectionRef) - .withConverter(fooConverter) - .where('foo', '==', 'bar') - .findNearest('embedding', [10, 10], { - limit: 3, - distanceMeasure: 'EUCLIDEAN', - }); - - const res = await vectorQuery.get(); - - expect(res.size).to.equal(1); - expect(res.docs[0].data().foo).to.equal('bar'); - expect(res.docs[0].data().embedding).to.deep.equal([5, 5]); - }); - - it('supports findNearest skipping fields of wrong types', async () => { - const indexTestHelper = new IndexTestHelper(firestore); - - const collectionRef = await indexTestHelper.createTestDocs([ - {foo: 'bar'}, - - // These documents are skipped because it is not really a vector value - {foo: 'bar', embedding: [10, 10]}, - {foo: 'bar', embedding: 'not actually a vector'}, - {foo: 'bar', embedding: null}, - - // Actual vector values - {foo: 'bar', embedding: FieldValue.vector([9, 9])}, - {foo: 'bar', embedding: FieldValue.vector([50, 50])}, - {foo: 'bar', embedding: FieldValue.vector([100, 100])}, - ]); - - const vectorQuery = indexTestHelper - .query(collectionRef) - .where('foo', '==', 'bar') - .findNearest('embedding', [10, 10], { - limit: 100, // Intentionally large to get all matches. - distanceMeasure: 'EUCLIDEAN', - }); - - const res = await vectorQuery.get(); - expect(res.size).to.equal(3); - expect(res.docs[0].get('embedding').isEqual(FieldValue.vector([9, 9]))).to - .be.true; - expect(res.docs[1].get('embedding').isEqual(FieldValue.vector([50, 50]))).to - .be.true; - expect(res.docs[2].get('embedding').isEqual(FieldValue.vector([100, 100]))) - .to.be.true; - }); - - it('findNearest ignores mismatching dimensions', async () => { - const indexTestHelper = new IndexTestHelper(firestore); - - const collectionRef = await indexTestHelper.createTestDocs([ - {foo: 'bar'}, - - // Vectors with dimension mismatch - {foo: 'bar', embedding: FieldValue.vector([10])}, - - // Vectors with dimension match - {foo: 'bar', embedding: FieldValue.vector([9, 9])}, - {foo: 'bar', embedding: FieldValue.vector([50, 50])}, - ]); - - const vectorQuery = indexTestHelper - .query(collectionRef) - .where('foo', '==', 'bar') - .findNearest('embedding', [10, 10], { - limit: 3, - distanceMeasure: 'EUCLIDEAN', - }); - - const res = await vectorQuery.get(); - expect(res.size).to.equal(2); - expect(res.docs[0].get('embedding').isEqual(FieldValue.vector([9, 9]))).to - .be.true; - expect(res.docs[1].get('embedding').isEqual(FieldValue.vector([50, 50]))).to - .be.true; - }); - - it('supports findNearest on non-existent field', async () => { - const indexTestHelper = new IndexTestHelper(firestore); - - const collectionRef = await indexTestHelper.createTestDocs([ - {foo: 'bar'}, - {foo: 'bar', otherField: [10, 10]}, - {foo: 'bar', otherField: 'not actually a vector'}, - {foo: 'bar', otherField: null}, - ]); - - const vectorQuery = indexTestHelper - .query(collectionRef) - .where('foo', '==', 'bar') - .findNearest('embedding', [10, 10], { - limit: 3, - distanceMeasure: 'EUCLIDEAN', - }); - - const res = await vectorQuery.get(); - - expect(res.size).to.equal(0); - }); - - it('supports findNearest on vector nested in a map', async () => { - const indexTestHelper = new IndexTestHelper(firestore); - - const collectionReference = await indexTestHelper.createTestDocs([ - {nested: {foo: 'bar'}}, - {nested: {foo: 'xxx', embedding: FieldValue.vector([10, 10])}}, - {nested: {foo: 'bar', embedding: FieldValue.vector([1, 1])}}, - {nested: {foo: 'bar', embedding: FieldValue.vector([10, 0])}}, - {nested: {foo: 'bar', embedding: FieldValue.vector([20, 0])}}, - {nested: {foo: 'bar', embedding: FieldValue.vector([100, 100])}}, - ]); - - const vectorQuery = indexTestHelper - .query(collectionReference) - .findNearest('nested.embedding', [10, 10], { - limit: 3, - distanceMeasure: 'EUCLIDEAN', - }); - - const res = await vectorQuery.get(); - expect(res.size).to.equal(3); - expect( - res.docs[0].get('nested.embedding').isEqual(FieldValue.vector([10, 10])) - ).to.be.true; - expect( - res.docs[1].get('nested.embedding').isEqual(FieldValue.vector([10, 0])) - ).to.be.true; - expect( - res.docs[2].get('nested.embedding').isEqual(FieldValue.vector([1, 1])) - ).to.be.true; - }); - - it('supports findNearest with select to exclude vector data in response', async () => { - const indexTestHelper = new IndexTestHelper(firestore); - - const collectionReference = await indexTestHelper.createTestDocs([ - {foo: 1}, - {foo: 2, embedding: FieldValue.vector([10, 10])}, - {foo: 3, embedding: FieldValue.vector([1, 1])}, - {foo: 4, embedding: FieldValue.vector([10, 0])}, - {foo: 5, embedding: FieldValue.vector([20, 0])}, - {foo: 6, embedding: FieldValue.vector([100, 100])}, - ]); - - const vectorQuery = indexTestHelper - .query(collectionReference) - .where('foo', 'in', [1, 2, 3, 4, 5, 6]) - .select('foo') - .findNearest('embedding', [10, 10], { - limit: 10, - distanceMeasure: 'EUCLIDEAN', - }); - - const res = await vectorQuery.get(); - expect(res.size).to.equal(5); - expect(res.docs[0].get('foo')).to.equal(2); - expect(res.docs[1].get('foo')).to.equal(4); - expect(res.docs[2].get('foo')).to.equal(3); - expect(res.docs[3].get('foo')).to.equal(5); - expect(res.docs[4].get('foo')).to.equal(6); - - res.docs.forEach(ds => expect(ds.get('embedding')).to.be.undefined); - }); - - it('supports findNearest limits', async () => { - const indexTestHelper = new IndexTestHelper(firestore); - - const embeddingVector = []; - const queryVector = []; - for (let i = 0; i < 2048; i++) { - embeddingVector.push(i + 1); - queryVector.push(i - 1); - } - - const collectionReference = await indexTestHelper.createTestDocs([ - {embedding: FieldValue.vector(embeddingVector)}, - ]); - - const vectorQuery = indexTestHelper - .query(collectionReference) - .findNearest('embedding', queryVector, { - limit: 1000, - distanceMeasure: 'EUCLIDEAN', - }); - - const res = await vectorQuery.get(); - expect(res.size).to.equal(1); - expect( - (res.docs[0].get('embedding') as VectorValue).toArray() - ).to.deep.equal(embeddingVector); - }); - - it('supports !=', async () => { - await addDocs( - {zip: NaN}, - {zip: 91102}, - {zip: 98101}, - {zip: 98103}, - {zip: [98101]}, - {zip: ['98101', {zip: 98101}]}, - {zip: {zip: 98101}}, - {zip: null} - ); - - let res = await randomCol.where('zip', '!=', 98101).get(); - expectDocs( - res, - {zip: NaN}, - {zip: 91102}, - {zip: 98103}, - {zip: [98101]}, - {zip: ['98101', {zip: 98101}]}, - {zip: {zip: 98101}} - ); - - res = await randomCol.where('zip', '!=', NaN).get(); - expectDocs( - res, - {zip: 91102}, - {zip: 98101}, - {zip: 98103}, - {zip: [98101]}, - {zip: ['98101', {zip: 98101}]}, - {zip: {zip: 98101}} - ); - - res = await randomCol.where('zip', '!=', null).get(); - expectDocs( - res, - {zip: NaN}, - {zip: 91102}, - {zip: 98101}, - {zip: 98103}, - {zip: [98101]}, - {zip: ['98101', {zip: 98101}]}, - {zip: {zip: 98101}} - ); - }); - - it('supports != with document ID', async () => { - const refs = await addDocs({count: 1}, {count: 2}, {count: 3}); - const res = await randomCol - .where(FieldPath.documentId(), '!=', refs[0].id) - .get(); - expectDocs(res, {count: 2}, {count: 3}); - }); - - it('supports not-in', async () => { - await addDocs( - {zip: 98101}, - {zip: 91102}, - {zip: 98103}, - {zip: [98101]}, - {zip: ['98101', {zip: 98101}]}, - {zip: {zip: 98101}} - ); - let res = await randomCol.where('zip', 'not-in', [98101, 98103]).get(); - expectDocs( - res, - {zip: 91102}, - {zip: [98101]}, - {zip: ['98101', {zip: 98101}]}, - {zip: {zip: 98101}} - ); - - res = await randomCol.where('zip', 'not-in', [NaN]).get(); - expectDocs( - res, - {zip: 91102}, - {zip: 98101}, - {zip: 98103}, - {zip: [98101]}, - {zip: ['98101', {zip: 98101}]}, - {zip: {zip: 98101}} - ); - - res = await randomCol.where('zip', 'not-in', [null]).get(); - expect(res.size).to.equal(0); - }); - - it('supports not-in with document ID array', async () => { - const refs = await addDocs({count: 1}, {count: 2}, {count: 3}); - const res = await randomCol - .where(FieldPath.documentId(), 'not-in', [refs[0].id, refs[1]]) - .get(); - expectDocs(res, {count: 3}); - }); - - it('supports "in"', async () => { - await addDocs( - {zip: 98101}, - {zip: 91102}, - {zip: 98103}, - {zip: [98101]}, - {zip: ['98101', {zip: 98101}]}, - {zip: {zip: 98101}} - ); - const res = await randomCol.where('zip', 'in', [98101, 98103]).get(); - expectDocs(res, {zip: 98101}, {zip: 98103}); - }); - - it('supports "in" with document ID array', async () => { - const refs = await addDocs({count: 1}, {count: 2}, {count: 3}); - const res = await randomCol - .where(FieldPath.documentId(), 'in', [refs[0].id, refs[1]]) - .get(); - expectDocs(res, {count: 1}, {count: 2}); - }); - - it('supports array-contains-any', async () => { - await addDocs( - {array: [42]}, - {array: ['a', 42, 'c']}, - {array: [41.999, '42', {a: [42]}]}, - {array: [42], array2: ['sigh']}, - {array: [43]}, - {array: [{a: 42}]}, - {array: 42} - ); - - const res = await randomCol - .where('array', 'array-contains-any', [42, 43]) - .get(); - - expectDocs( - res, - {array: [42]}, - {array: ['a', 42, 'c']}, - { - array: [42], - array2: ['sigh'], - }, - {array: [43]} - ); - }); - - it('can query by FieldPath.documentId()', () => { - const ref = randomCol.doc('foo'); - - return ref - .set({}) - .then(() => { - return randomCol.where(FieldPath.documentId(), '>=', 'bar').get(); - }) - .then(res => { - expect(res.docs.length).to.equal(1); - }); - }); - - it('has orderBy() method', async () => { - await addDocs({foo: 'a'}, {foo: 'b'}); - - let res = await randomCol.orderBy('foo').get(); - expectDocs(res, {foo: 'a'}, {foo: 'b'}); - - res = await randomCol.orderBy('foo', 'desc').get(); - expectDocs(res, {foo: 'b'}, {foo: 'a'}); - }); - - it('can order by FieldPath.documentId()', () => { - const ref1 = randomCol.doc('doc1'); - const ref2 = randomCol.doc('doc2'); - - return Promise.all([ref1.set({foo: 'a'}), ref2.set({foo: 'b'})]) - .then(() => { - return randomCol.orderBy(FieldPath.documentId()).get(); - }) - .then(res => { - expect(res.docs[0].data()).to.deep.equal({foo: 'a'}); - expect(res.docs[1].data()).to.deep.equal({foo: 'b'}); - }); - }); - - it('can run get() on empty collection', async () => { - return randomCol.get().then(res => { - return expect(res.empty); - }); - }); - - it('can run stream() on empty collection', async () => { - let received = 0; - const stream = randomCol.stream(); - - for await (const doc of stream) { - expect(doc).to.be.an.instanceOf(QueryDocumentSnapshot); - ++received; - } - - expect(received).to.equal(0); - }); - - it('has limit() method on get()', async () => { - await addDocs({foo: 'a'}, {foo: 'b'}); - const res = await randomCol.orderBy('foo').limit(1).get(); - expectDocs(res, {foo: 'a'}); - }); - - it('has limit() method on stream()', async () => { - let received = 0; - await addDocs({foo: 'a'}, {foo: 'b'}); - - const stream = randomCol.orderBy('foo').limit(1).stream(); - for await (const doc of stream) { - expect(doc).to.be.an.instanceOf(QueryDocumentSnapshot); - ++received; - } - - expect(received).to.equal(1); - }); - - it('can run limit(num), where num is larger than the collection size on get()', async () => { - await addDocs({foo: 'a'}, {foo: 'b'}); - const res = await randomCol.orderBy('foo').limit(3).get(); - expectDocs(res, {foo: 'a'}, {foo: 'b'}); - }); - - it('can run limit(num), where num is larger than the collection size on stream()', async () => { - let received = 0; - await addDocs({foo: 'a'}, {foo: 'b'}); - - const stream = randomCol.orderBy('foo').limit(3).stream(); - for await (const doc of stream) { - expect(doc).to.be.an.instanceOf(QueryDocumentSnapshot); - ++received; - } - - expect(received).to.equal(2); - }); - - it('has limitToLast() method', async () => { - await addDocs({doc: 1}, {doc: 2}, {doc: 3}); - const res = await randomCol.orderBy('doc').limitToLast(2).get(); - expectDocs(res, {doc: 2}, {doc: 3}); - }); - - it('limitToLast() supports Query cursors', async () => { - await addDocs({doc: 1}, {doc: 2}, {doc: 3}, {doc: 4}, {doc: 5}); - const res = await randomCol - .orderBy('doc') - .startAt(2) - .endAt(4) - .limitToLast(5) - .get(); - expectDocs(res, {doc: 2}, {doc: 3}, {doc: 4}); - }); - - it('can use offset() method with get()', async () => { - await addDocs({foo: 'a'}, {foo: 'b'}); - const res = await randomCol.orderBy('foo').offset(1).get(); - expectDocs(res, {foo: 'b'}); - }); - - it('can use offset() method with stream()', async () => { - let received = 0; - await addDocs({foo: 'a'}, {foo: 'b'}); - - const stream = randomCol.orderBy('foo').offset(1).stream(); - for await (const doc of stream) { - expect(doc).to.be.an.instanceOf(QueryDocumentSnapshot); - ++received; - } - - expect(received).to.equal(1); - }); - - it('can run offset(num), where num is larger than the collection size on get()', async () => { - await addDocs({foo: 'a'}, {foo: 'b'}); - const res = await randomCol.orderBy('foo').offset(3).get(); - expect(res.empty); - }); - - it('can run offset(num), where num is larger than the collection size on stream()', async () => { - let received = 0; - await addDocs({foo: 'a'}, {foo: 'b'}); - const stream = randomCol.orderBy('foo').offset(3).stream(); - for await (const doc of stream) { - expect(doc).to.be.an.instanceOf(QueryDocumentSnapshot); - ++received; - } - expect(received).to.equal(0); - }); - - it('supports Unicode in document names', async () => { - const collRef = randomCol.doc('доброеутро').collection('coll'); - await collRef.add({}); - const snapshot = await collRef.get(); - expect(snapshot.size).to.equal(1); - }); - - it('supports pagination', () => { - const batch = firestore.batch(); - - for (let i = 0; i < 10; ++i) { - batch.set(randomCol.doc('doc' + i), {val: i}); - } - - const query = randomCol.orderBy('val').limit(3); - - return batch - .commit() - .then(() => paginateResults(query)) - .then(results => { - expect(results.pages).to.equal(4); - expect(results.docs).to.have.length(10); - }); - }); - - it('supports pagination with where() clauses', () => { - const batch = firestore.batch(); - - for (let i = 0; i < 10; ++i) { - batch.set(randomCol.doc('doc' + i), {val: i}); - } - - const query = randomCol.where('val', '>=', 1).limit(3); - - return batch - .commit() - .then(() => paginateResults(query)) - .then(results => { - expect(results.pages).to.equal(3); - expect(results.docs).to.have.length(9); - }); - }); - - it('supports pagination with array-contains filter', () => { - const batch = firestore.batch(); - - for (let i = 0; i < 10; ++i) { - batch.set(randomCol.doc('doc' + i), {array: ['foo']}); - } - - const query = randomCol.where('array', 'array-contains', 'foo').limit(3); - - return batch - .commit() - .then(() => paginateResults(query)) - .then(results => { - expect(results.pages).to.equal(4); - expect(results.docs).to.have.length(10); - }); - }); - - it('has startAt() method', async () => { - await addDocs({foo: 'a'}, {foo: 'b'}); - const res = await randomCol.orderBy('foo').startAt('b').get(); - expectDocs(res, {foo: 'b'}); - }); - - it('startAt() adds implicit order by for DocumentSnapshot', async () => { - const references = await addDocs({foo: 'a'}, {foo: 'b'}); - const docSnap = await references[1].get(); - const res = await randomCol.startAt(docSnap).get(); - expectDocs(res, {foo: 'b'}); - }); - - it('has startAfter() method', async () => { - await addDocs({foo: 'a'}, {foo: 'b'}); - const res = await randomCol.orderBy('foo').startAfter('a').get(); - expectDocs(res, {foo: 'b'}); - }); - - it('has endAt() method', async () => { - await addDocs({foo: 'a'}, {foo: 'b'}); - const res = await randomCol.orderBy('foo').endAt('b').get(); - expectDocs(res, {foo: 'a'}, {foo: 'b'}); - }); - - it('has endBefore() method', async () => { - await addDocs({foo: 'a'}, {foo: 'b'}); - const res = await randomCol.orderBy('foo').endBefore('b').get(); - expectDocs(res, {foo: 'a'}); - }); - - it('has stream() method', done => { - let received = 0; - const ref1 = randomCol.doc('doc1'); - const ref2 = randomCol.doc('doc2'); - - Promise.all([ref1.set({foo: 'a'}), ref2.set({foo: 'b'})]).then(() => { - return randomCol - .stream() - .on('data', d => { - expect(d).to.be.an.instanceOf(DocumentSnapshot); - ++received; - }) - .on('end', () => { - expect(received).to.equal(2); - done(); - }); - }); - }); - - it('stream() supports readable[Symbol.asyncIterator]()', async () => { - let received = 0; - await randomCol.doc().set({foo: 'bar'}); - await randomCol.doc().set({foo: 'bar'}); - - const stream = randomCol.stream(); - for await (const doc of stream) { - expect(doc).to.be.an.instanceOf(QueryDocumentSnapshot); - ++received; - } - - expect(received).to.equal(2); - }); - - it('can query collection groups', async () => { - // Use `randomCol` to get a random collection group name to use but ensure - // it starts with 'b' for predictable ordering. - const collectionGroup = 'b' + randomCol.id; - - const docPaths = [ - `abc/123/${collectionGroup}/cg-doc1`, - `abc/123/${collectionGroup}/cg-doc2`, - `${collectionGroup}/cg-doc3`, - `${collectionGroup}/cg-doc4`, - `def/456/${collectionGroup}/cg-doc5`, - `${collectionGroup}/virtual-doc/nested-coll/not-cg-doc`, - `x${collectionGroup}/not-cg-doc`, - `${collectionGroup}x/not-cg-doc`, - `abc/123/${collectionGroup}x/not-cg-doc`, - `abc/123/x${collectionGroup}/not-cg-doc`, - `abc/${collectionGroup}`, - ]; - const batch = firestore.batch(); - for (const docPath of docPaths) { - batch.set(firestore.doc(docPath), {x: 1}); - } - await batch.commit(); - - const querySnapshot = await firestore - .collectionGroup(collectionGroup) - .get(); - expect(querySnapshot.docs.map(d => d.id)).to.deep.equal([ - 'cg-doc1', - 'cg-doc2', - 'cg-doc3', - 'cg-doc4', - 'cg-doc5', - ]); - }); - - it('can query collection groups with startAt / endAt by arbitrary documentId', async () => { - // Use `randomCol` to get a random collection group name to use but - // ensure it starts with 'b' for predictable ordering. - const collectionGroup = 'b' + randomCol.id; - - const docPaths = [ - `a/a/${collectionGroup}/cg-doc1`, - `a/b/a/b/${collectionGroup}/cg-doc2`, - `a/b/${collectionGroup}/cg-doc3`, - `a/b/c/d/${collectionGroup}/cg-doc4`, - `a/c/${collectionGroup}/cg-doc5`, - `${collectionGroup}/cg-doc6`, - 'a/b/nope/nope', - ]; - const batch = firestore.batch(); - for (const docPath of docPaths) { - batch.set(firestore.doc(docPath), {x: 1}); - } - await batch.commit(); - - let querySnapshot = await firestore - .collectionGroup(collectionGroup) - .orderBy(FieldPath.documentId()) - .startAt('a/b') - .endAt('a/b0') - .get(); - expect(querySnapshot.docs.map(d => d.id)).to.deep.equal([ - 'cg-doc2', - 'cg-doc3', - 'cg-doc4', - ]); - - querySnapshot = await firestore - .collectionGroup(collectionGroup) - .orderBy(FieldPath.documentId()) - .startAfter('a/b') - .endBefore(`a/b/${collectionGroup}/cg-doc3`) - .get(); - expect(querySnapshot.docs.map(d => d.id)).to.deep.equal(['cg-doc2']); - }); - - it('can query collection groups with where filters on arbitrary documentId', async () => { - // Use `randomCol` to get a random collection group name to use but - // ensure it starts with 'b' for predictable ordering. - const collectionGroup = 'b' + randomCol.id; - - const docPaths = [ - `a/a/${collectionGroup}/cg-doc1`, - `a/b/a/b/${collectionGroup}/cg-doc2`, - `a/b/${collectionGroup}/cg-doc3`, - `a/b/c/d/${collectionGroup}/cg-doc4`, - `a/c/${collectionGroup}/cg-doc5`, - `${collectionGroup}/cg-doc6`, - 'a/b/nope/nope', - ]; - const batch = firestore.batch(); - for (const docPath of docPaths) { - batch.set(firestore.doc(docPath), {x: 1}); - } - await batch.commit(); - - let querySnapshot = await firestore - .collectionGroup(collectionGroup) - .where(FieldPath.documentId(), '>=', 'a/b') - .where(FieldPath.documentId(), '<=', 'a/b0') - .get(); - expect(querySnapshot.docs.map(d => d.id)).to.deep.equal([ - 'cg-doc2', - 'cg-doc3', - 'cg-doc4', - ]); - - querySnapshot = await firestore - .collectionGroup(collectionGroup) - .where(FieldPath.documentId(), '>', 'a/b') - .where(FieldPath.documentId(), '<', `a/b/${collectionGroup}/cg-doc3`) - .get(); - expect(querySnapshot.docs.map(d => d.id)).to.deep.equal(['cg-doc2']); - }); - - it('can query large collections', async () => { - // @grpc/grpc-js v0.4.1 failed to deliver the full set of query results for - // larger collections (https://github.com/grpc/grpc-node/issues/895); - const batch = firestore.batch(); - for (let i = 0; i < 100; ++i) { - batch.create(randomCol.doc(), {}); - } - await batch.commit(); - - const snapshot = await randomCol.get(); - expect(snapshot.size).to.equal(100); - }); - - it('supports OR queries', async () => { - const collection = await testCollectionWithDocs({ - doc1: {a: 1, b: 0}, - doc2: {a: 2, b: 1}, - doc3: {a: 3, b: 2}, - doc4: {a: 1, b: 3}, - doc5: {a: 1, b: 1}, - }); - - // Two equalities: a==1 || b==1. - expectDocs( - await collection - .where( - Filter.or(Filter.where('a', '==', 1), Filter.where('b', '==', 1)) - ) - .get(), - 'doc1', - 'doc2', - 'doc4', - 'doc5' - ); - - // (a==1 && b==0) || (a==3 && b==2) - expectDocs( - await collection - .where( - Filter.or( - Filter.and(Filter.where('a', '==', 1), Filter.where('b', '==', 0)), - Filter.and(Filter.where('a', '==', 3), Filter.where('b', '==', 2)) - ) - ) - .get(), - 'doc1', - 'doc3' - ); - - // a==1 && (b==0 || b==3). - expectDocs( - await collection - .where( - Filter.and( - Filter.where('a', '==', 1), - Filter.or(Filter.where('b', '==', 0), Filter.where('b', '==', 3)) - ) - ) - .get(), - 'doc1', - 'doc4' - ); - - // (a==2 || b==2) && (a==3 || b==3) - expectDocs( - await collection - .where( - Filter.and( - Filter.or(Filter.where('a', '==', 2), Filter.where('b', '==', 2)), - Filter.or(Filter.where('a', '==', 3), Filter.where('b', '==', 3)) - ) - ) - .get(), - 'doc3' - ); - - // Test with limits without orderBy (the __name__ ordering is the tie breaker). - expectDocs( - await collection - .where( - Filter.or(Filter.where('a', '==', 2), Filter.where('b', '==', 1)) - ) - .limit(1) - .get(), - 'doc2' - ); - }); - - // Skip this test if running against production because it results in a 'missing index' error. - // The Firestore Emulator, however, does serve these queries. - (process.env.FIRESTORE_EMULATOR_HOST === undefined ? it.skip : it)( - 'supports OR queries with composite indexes', - async () => { - const collection = await testCollectionWithDocs({ - doc1: {a: 1, b: 0}, - doc2: {a: 2, b: 1}, - doc3: {a: 3, b: 2}, - doc4: {a: 1, b: 3}, - doc5: {a: 1, b: 1}, - }); - - // with one inequality: a>2 || b==1. - expectDocs( - await collection - .where( - Filter.or(Filter.where('a', '>', 2), Filter.where('b', '==', 1)) - ) - .get(), - 'doc5', - 'doc2', - 'doc3' - ); - - // Test with limits (implicit order by ASC): (a==1) || (b > 0) LIMIT 2 - expectDocs( - await collection - .where( - Filter.or(Filter.where('a', '==', 1), Filter.where('b', '>', 0)) - ) - .limit(2) - .get(), - 'doc1', - 'doc2' - ); - - // Test with limits (explicit order by): (a==1) || (b > 0) LIMIT_TO_LAST 2 - // Note: The public query API does not allow implicit ordering when limitToLast is used. - expectDocs( - await collection - .where( - Filter.or(Filter.where('a', '==', 1), Filter.where('b', '>', 0)) - ) - .limitToLast(2) - .orderBy('b') - .get(), - 'doc3', - 'doc4' - ); - - // Test with limits (explicit order by ASC): (a==2) || (b == 1) ORDER BY a LIMIT 1 - expectDocs( - await collection - .where( - Filter.or(Filter.where('a', '==', 2), Filter.where('b', '==', 1)) - ) - .limit(1) - .orderBy('a') - .get(), - 'doc5' - ); - - // Test with limits (explicit order by DESC): (a==2) || (b == 1) ORDER BY a LIMIT 1 - expectDocs( - await collection - .where( - Filter.or(Filter.where('a', '==', 2), Filter.where('b', '==', 1)) - ) - .limit(1) - .orderBy('a', 'desc') - .get(), - 'doc2' - ); - } - ); - - it('supports OR queries on documents with missing fields', async () => { - const collection = await testCollectionWithDocs({ - doc1: {a: 1, b: 0}, - doc2: {b: 1}, - doc3: {a: 3, b: 2}, - doc4: {a: 1, b: 3}, - doc5: {a: 1}, - doc6: {a: 2}, - }); - - // Query: a==1 || b==1 - // There's no explicit nor implicit orderBy. Documents with missing 'a' or missing 'b' should be - // allowed if the document matches at least one disjunction term. - expectDocs( - await collection - .where( - Filter.or(Filter.where('a', '==', 1), Filter.where('b', '==', 1)) - ) - .get(), - 'doc1', - 'doc2', - 'doc4', - 'doc5' - ); - }); - - // Skip this test if running against production because it results in a 'missing index' error. - // The Firestore Emulator, however, does serve these queries. - (process.env.FIRESTORE_EMULATOR_HOST === undefined ? it.skip : it)( - 'supports OR queries on documents with missing fields', - async () => { - const collection = await testCollectionWithDocs({ - doc1: {a: 1, b: 0}, - doc2: {b: 1}, - doc3: {a: 3, b: 2}, - doc4: {a: 1, b: 3}, - doc5: {a: 1}, - doc6: {a: 2}, - }); - - // Query: a==1 || b==1 order by a. - // doc2 should not be included because it's missing the field 'a', and we have "orderBy a". - expectDocs( - await collection - .where( - Filter.or(Filter.where('a', '==', 1), Filter.where('b', '==', 1)) - ) - .orderBy('a') - .get(), - 'doc1', - 'doc4', - 'doc5' - ); - - // Query: a==1 || b==1 order by b. - // doc5 should not be included because it's missing the field 'b', and we have "orderBy b". - expectDocs( - await collection - .where( - Filter.or(Filter.where('a', '==', 1), Filter.where('b', '==', 1)) - ) - .orderBy('b') - .get(), - 'doc1', - 'doc2', - 'doc4' - ); - - // Query: a>2 || b==1. - // This query has an implicit 'order by a'. - // doc2 should not be included because it's missing the field 'a'. - expectDocs( - await collection - .where( - Filter.or(Filter.where('a', '>', 2), Filter.where('b', '==', 1)) - ) - .get(), - 'doc3' - ); - - // Query: a>1 || b==1 order by a order by b. - // doc6 should not be included because it's missing the field 'b'. - // doc2 should not be included because it's missing the field 'a'. - expectDocs( - await collection - .where( - Filter.or(Filter.where('a', '>', 1), Filter.where('b', '==', 1)) - ) - .orderBy('a') - .orderBy('b') - .get(), - 'doc3' - ); - } - ); - - it('supports OR queries with in', async () => { - const collection = await testCollectionWithDocs({ - doc1: {a: 1, b: 0}, - doc2: {b: 1}, - doc3: {a: 3, b: 2}, - doc4: {a: 1, b: 3}, - doc5: {a: 1}, - doc6: {a: 2}, - }); - - // Query: a==2 || b in [2, 3] - expectDocs( - await collection - .where( - Filter.or(Filter.where('a', '==', 2), Filter.where('b', 'in', [2, 3])) - ) - .get(), - 'doc3', - 'doc4', - 'doc6' - ); - }); - - // Skip this test if running against production because it results in a 'missing index' error. - // The Firestore Emulator, however, does serve these queries. - (process.env.FIRESTORE_EMULATOR_HOST === undefined ? it.skip : it)( - 'supports OR queries with not-in', - async () => { - const collection = await testCollectionWithDocs({ - doc1: {a: 1, b: 0}, - doc2: {b: 1}, - doc3: {a: 3, b: 2}, - doc4: {a: 1, b: 3}, - doc5: {a: 1}, - doc6: {a: 2}, - }); - - // a==2 || (b != 2 && b != 3) - // Has implicit "orderBy b" - expectDocs( - await collection - .where( - Filter.or( - Filter.where('a', '==', 2), - Filter.where('b', 'not-in', [2, 3]) - ) - ) - .get(), - 'doc1', - 'doc2' - ); - } - ); - - it('supports OR queries with array membership', async () => { - const collection = await testCollectionWithDocs({ - doc1: {a: 1, b: [0]}, - doc2: {b: [1]}, - doc3: {a: 3, b: [2, 7]}, - doc4: {a: 1, b: [3, 7]}, - doc5: {a: 1}, - doc6: {a: 2}, - }); - - // Query: a==2 || b array-contains 7 - expectDocs( - await collection - .where( - Filter.or( - Filter.where('a', '==', 2), - Filter.where('b', 'array-contains', 7) - ) - ) - .get(), - 'doc3', - 'doc4', - 'doc6' - ); - - // a==2 || b array-contains-any [0, 3] - // Has implicit "orderBy b" - expectDocs( - await collection - .where( - Filter.or( - Filter.where('a', '==', 2), - Filter.where('b', 'array-contains-any', [0, 3]) - ) - ) - .get(), - 'doc1', - 'doc4', - 'doc6' - ); - }); - - describe('watch', () => { - interface ExpectedChange { - type: string; - doc: DocumentSnapshot; - } - - const currentDeferred = new DeferredPromise(); - - const snapshot = (id: string, data: DocumentData) => { - const ref = randomCol.doc(id); - const fields = ref.firestore._serializer!.encodeFields(data); - return randomCol.firestore.snapshot_( - { - name: - 'projects/ignored/databases/(default)/documents/' + - ref._path.relativeName, - fields, - createTime: {seconds: 0, nanos: 0}, - updateTime: {seconds: 0, nanos: 0}, - }, - {seconds: 0, nanos: 0} - ); - }; - - const docChange = ( - type: string, - id: string, - data: DocumentData - ): ExpectedChange => { - return { - type, - doc: snapshot(id, data), - }; - }; - - const added = (id: string, data: DocumentData) => - docChange('added', id, data); - const modified = (id: string, data: DocumentData) => - docChange('modified', id, data); - const removed = (id: string, data: DocumentData) => - docChange('removed', id, data); - - function resetPromise() { - currentDeferred.promise = new Promise((resolve, reject) => { - currentDeferred.resolve = resolve; - currentDeferred.reject = reject; - }); - } - - function waitForSnapshot(): Promise { - return currentDeferred.promise!.then(snapshot => { - resetPromise(); - return snapshot; - }); - } - - function snapshotsEqual( - actual: QuerySnapshot, - expected: {docs: DocumentSnapshot[]; docChanges: ExpectedChange[]} - ) { - let i; - expect(actual.size).to.equal(expected.docs.length); - for (i = 0; i < expected.docs.length && i < actual.size; i++) { - expect(actual.docs[i].ref.id).to.equal(expected.docs[i].ref.id); - expect(actual.docs[i].data()).to.deep.equal(expected.docs[i].data()); - } - const actualDocChanges = actual.docChanges(); - expect(actualDocChanges.length).to.equal(expected.docChanges.length); - for (i = 0; i < expected.docChanges.length; i++) { - expect(actualDocChanges[i].type).to.equal(expected.docChanges[i].type); - expect(actualDocChanges[i].doc.ref.id).to.equal( - expected.docChanges[i].doc.ref.id - ); - expect(actualDocChanges[i].doc.data()).to.deep.equal( - expected.docChanges[i].doc.data() - ); - expect(actualDocChanges[i].doc.readTime).to.exist; - expect(actualDocChanges[i].doc.createTime).to.exist; - expect(actualDocChanges[i].doc.updateTime).to.exist; - } - expect(actual.readTime).to.exist; - } - - beforeEach(() => resetPromise()); - - it('handles changing a doc', () => { - const ref1 = randomCol.doc('doc1'); - const ref2 = randomCol.doc('doc2'); - - const unsubscribe = randomCol.onSnapshot( - snapshot => { - currentDeferred.resolve(snapshot); - }, - err => { - currentDeferred.reject!(err); - } - ); - - return waitForSnapshot() - .then(results => { - snapshotsEqual(results, {docs: [], docChanges: []}); - // Add a result. - return ref1.set({foo: 'a'}); - }) - .then(() => { - return waitForSnapshot(); - }) - .then(results => { - snapshotsEqual(results, { - docs: [snapshot('doc1', {foo: 'a'})], - docChanges: [added('doc1', {foo: 'a'})], - }); - // Add another result. - return ref2.set({foo: 'b'}); - }) - .then(() => { - return waitForSnapshot(); - }) - .then(results => { - snapshotsEqual(results, { - docs: [snapshot('doc1', {foo: 'a'}), snapshot('doc2', {foo: 'b'})], - docChanges: [added('doc2', {foo: 'b'})], - }); - // Change a result. - return ref2.set({bar: 'c'}); - }) - .then(() => { - return waitForSnapshot(); - }) - .then(results => { - snapshotsEqual(results, { - docs: [snapshot('doc1', {foo: 'a'}), snapshot('doc2', {bar: 'c'})], - docChanges: [modified('doc2', {bar: 'c'})], - }); - unsubscribe(); - }); - }); - - it("handles changing a doc so it doesn't match", () => { - const ref1 = randomCol.doc('doc1'); - const ref2 = randomCol.doc('doc2'); - - const query = randomCol.where('included', '==', 'yes'); - const unsubscribe = query.onSnapshot( - snapshot => { - currentDeferred.resolve(snapshot); - }, - err => { - currentDeferred.reject(err); - } - ); - - return waitForSnapshot() - .then(results => { - snapshotsEqual(results, {docs: [], docChanges: []}); - // Add a result. - return ref1.set({included: 'yes'}); - }) - .then(() => { - return waitForSnapshot(); - }) - .then(results => { - snapshotsEqual(results, { - docs: [snapshot('doc1', {included: 'yes'})], - docChanges: [added('doc1', {included: 'yes'})], - }); - // Add another result. - return ref2.set({included: 'yes'}); - }) - .then(() => { - return waitForSnapshot(); - }) - .then(results => { - snapshotsEqual(results, { - docs: [ - snapshot('doc1', {included: 'yes'}), - snapshot('doc2', {included: 'yes'}), - ], - docChanges: [added('doc2', {included: 'yes'})], - }); - // Change a result. - return ref2.set({included: 'no'}); - }) - .then(() => { - return waitForSnapshot(); - }) - .then(results => { - snapshotsEqual(results, { - docs: [snapshot('doc1', {included: 'yes'})], - docChanges: [removed('doc2', {included: 'yes'})], - }); - unsubscribe(); - }); - }); - - it('handles deleting a doc', () => { - const ref1 = randomCol.doc('doc1'); - const ref2 = randomCol.doc('doc2'); - - const unsubscribe = randomCol.onSnapshot( - snapshot => { - currentDeferred.resolve(snapshot); - }, - err => { - currentDeferred.reject(err); - } - ); - - return waitForSnapshot() - .then(results => { - snapshotsEqual(results, {docs: [], docChanges: []}); - // Add a result. - return ref1.set({included: 'yes'}); - }) - .then(() => { - return waitForSnapshot(); - }) - .then(results => { - snapshotsEqual(results, { - docs: [snapshot('doc1', {included: 'yes'})], - docChanges: [added('doc1', {included: 'yes'})], - }); - // Add another result. - return ref2.set({included: 'yes'}); - }) - .then(() => { - return waitForSnapshot(); - }) - .then(results => { - snapshotsEqual(results, { - docs: [ - snapshot('doc1', {included: 'yes'}), - snapshot('doc2', {included: 'yes'}), - ], - docChanges: [added('doc2', {included: 'yes'})], - }); - // Delete a result. - return ref2.delete(); - }) - .then(() => { - return waitForSnapshot(); - }) - .then(results => { - snapshotsEqual(results, { - docs: [snapshot('doc1', {included: 'yes'})], - docChanges: [removed('doc2', {included: 'yes'})], - }); - unsubscribe(); - }); - }); - - it('orders limitToLast() correctly', async () => { - const ref1 = randomCol.doc('doc1'); - const ref2 = randomCol.doc('doc2'); - const ref3 = randomCol.doc('doc3'); - - await ref1.set({doc: 1}); - await ref2.set({doc: 2}); - await ref3.set({doc: 3}); - - const unsubscribe = randomCol - .orderBy('doc') - .limitToLast(2) - .onSnapshot(snapshot => currentDeferred.resolve(snapshot)); - - const results = await waitForSnapshot(); - snapshotsEqual(results, { - docs: [snapshot('doc2', {doc: 2}), snapshot('doc3', {doc: 3})], - docChanges: [added('doc2', {doc: 2}), added('doc3', {doc: 3})], - }); - - unsubscribe(); - }); - - it('SDK orders vector field same way as backend', async () => { - // We validate that the SDK orders the vector field the same way as the backend - // by comparing the sort order of vector fields from a Query.get() and - // Query.onSnapshot(). Query.onSnapshot() will return sort order of the SDK, - // and Query.get() will return sort order of the backend. - - // Test data in the order that we expect the backend to sort it. - const docsInOrder = [ - {embedding: [1, 2, 3, 4, 5, 6]}, - {embedding: [100]}, - {embedding: FieldValue.vector([Number.NEGATIVE_INFINITY])}, - {embedding: FieldValue.vector([-100])}, - {embedding: FieldValue.vector([100])}, - {embedding: FieldValue.vector([Number.POSITIVE_INFINITY])}, - {embedding: FieldValue.vector([1, 2])}, - {embedding: FieldValue.vector([2, 2])}, - {embedding: FieldValue.vector([1, 2, 3])}, - {embedding: FieldValue.vector([1, 2, 3, 4])}, - {embedding: FieldValue.vector([1, 2, 3, 4, 5])}, - {embedding: FieldValue.vector([1, 2, 100, 4, 4])}, - {embedding: FieldValue.vector([100, 2, 3, 4, 5])}, - {embedding: {HELLO: 'WORLD'}}, - {embedding: {hello: 'world'}}, - ]; - - const expectedSnapshots = []; - const expectedChanges = []; - - for (let i = 0; i < docsInOrder.length; i++) { - const dr = await randomCol.add(docsInOrder[i]); - expectedSnapshots.push(snapshot(dr.id, docsInOrder[i])); - expectedChanges.push(added(dr.id, docsInOrder[i])); - } - - const orderedQuery = randomCol.orderBy('embedding'); - - const unsubscribe = orderedQuery.onSnapshot( - snapshot => { - currentDeferred.resolve(snapshot); - }, - err => { - currentDeferred.reject!(err); - } - ); - - const watchSnapshot = await waitForSnapshot(); - unsubscribe(); - - const getSnapshot = await orderedQuery.get(); - - // Compare the snapshot (including sort order) of a snapshot - // from Query.onSnapshot() to an actual snapshot from Query.get() - snapshotsEqual(watchSnapshot, { - docs: getSnapshot.docs, - docChanges: getSnapshot.docChanges(), - }); - - // Compare the snapshot (including sort order) of a snapshot - // from Query.onSnapshot() to the expected sort order from - // the backend. - snapshotsEqual(watchSnapshot, { - docs: expectedSnapshots, - docChanges: expectedChanges, - }); - }); - }); - - (process.env.FIRESTORE_EMULATOR_HOST === undefined - ? describe.skip - : describe)('multiple inequality', () => { - it('supports multiple inequality queries', async () => { - const collection = await testCollectionWithDocs({ - doc1: {key: 'a', sort: 0, v: 0}, - doc2: {key: 'b', sort: 3, v: 1}, - doc3: {key: 'c', sort: 1, v: 3}, - doc4: {key: 'd', sort: 2, v: 2}, - }); - - // Multiple inequality fields - let results = await collection - .where('key', '!=', 'a') - .where('sort', '<=', 2) - .where('v', '>', 2) - .get(); - expectDocs(results, 'doc3'); - - // Duplicate inequality fields - results = await collection - .where('key', '!=', 'a') - .where('sort', '<=', 2) - .where('sort', '>', 1) - .get(); - expectDocs(results, 'doc4'); - - // With multiple IN - results = await collection - .where('key', '>=', 'a') - .where('sort', '<=', 2) - .where('v', 'in', [2, 3, 4]) - .where('sort', 'in', [2, 3]) - .get(); - expectDocs(results, 'doc4'); - - // With NOT-IN - results = await collection - .where('key', '>=', 'a') - .where('sort', '<=', 2) - .where('v', 'not-in', [2, 4, 5]) - .get(); - expectDocs(results, 'doc1', 'doc3'); - - // With orderby - results = await collection - .where('key', '>=', 'a') - .where('sort', '<=', 2) - .orderBy('v', 'desc') - .get(); - expectDocs(results, 'doc3', 'doc4', 'doc1'); - - // With limit - results = await collection - .where('key', '>=', 'a') - .where('sort', '<=', 2) - .orderBy('v', 'desc') - .limit(2) - .get(); - expectDocs(results, 'doc3', 'doc4'); - - // With limitToLast - results = await collection - .where('key', '>=', 'a') - .where('sort', '<=', 2) - .orderBy('v', 'desc') - .limitToLast(2) - .get(); - expectDocs(results, 'doc4', 'doc1'); - }); - - it('can use on special values', async () => { - const collection = await testCollectionWithDocs({ - doc1: {key: 'a', sort: 0, v: 0}, - doc2: {key: 'b', sort: NaN, v: 1}, - doc3: {key: 'c', sort: null, v: 3}, - doc4: {key: 'd', v: 0}, - doc5: {key: 'e', sort: 1}, - doc6: {key: 'f', sort: 1, v: 1}, - }); - - let results = await collection - .where('key', '!=', 'a') - .where('sort', '<=', 2) - .get(); - expectDocs(results, 'doc5', 'doc6'); - - results = await collection - .where('key', '!=', 'a') - .where('sort', '<=', 2) - .where('v', '<=', 1) - .get(); - expectDocs(results, 'doc6'); - }); - - it('can use with array membership', async () => { - const collection = await testCollectionWithDocs({ - doc1: {key: 'a', sort: 0, v: [0]}, - doc2: {key: 'b', sort: 1, v: [0, 1, 3]}, - doc3: {key: 'c', sort: 1, v: []}, - doc4: {key: 'd', sort: 2, v: [1]}, - doc5: {key: 'e', sort: 3, v: [2, 4]}, - doc6: {key: 'f', sort: 4, v: [NaN]}, - doc7: {key: 'g', sort: 4, v: [null]}, - }); - - let results = await collection - .where('key', '!=', 'a') - .where('sort', '>=', 1) - .where('v', 'array-contains', 0) - .get(); - expectDocs(results, 'doc2'); - - results = await collection - .where('key', '!=', 'a') - .where('sort', '>=', 1) - .where('v', 'array-contains-any', [0, 1]) - .get(); - expectDocs(results, 'doc2', 'doc4'); - }); - - // Use cursor in following test cases to add implicit order by fields in the sdk and compare the - // result with the query fields normalized in the server. - it('can use with nested field', async () => { - // eslint-disable-next-line @typescript-eslint/no-explicit-any - const testData = (n?: number): any => { - n = n || 1; - return { - name: 'room ' + n, - metadata: { - createdAt: n, - }, - field: 'field ' + n, - 'field.dot': n, - 'field\\slash': n, - }; - }; - - const collection = await testCollectionWithDocs({ - doc1: testData(400), - doc2: testData(200), - doc3: testData(100), - doc4: testData(300), - }); - - // ordered by: name asc, metadata.createdAt asc, __name__ asc - let query = collection - .where('metadata.createdAt', '<=', 500) - .where('metadata.createdAt', '>', 100) - .where('name', '!=', 'room 200') - .orderBy('name'); - let docSnap = await collection.doc('doc4').get(); - let queryWithCursor = query.startAt(docSnap); - expectDocs(await query.get(), 'doc4', 'doc1'); - expectDocs(await queryWithCursor.get(), 'doc4', 'doc1'); - - // ordered by: name desc, field desc, field.dot desc, field\\slash desc, __name__ desc - query = collection - .where('field', '>=', 'field 100') - .where(new FieldPath('field.dot'), '!=', 300) - .where('field\\slash', '<', 400) - .orderBy('name', 'desc'); - docSnap = await collection.doc('doc2').get(); - queryWithCursor = query.startAt(docSnap); - expectDocs(await query.get(), 'doc2', 'doc3'); - expectDocs(await queryWithCursor.get(), 'doc2', 'doc3'); - }); - - it('can use with nested composite filters', async () => { - const collection = await testCollectionWithDocs({ - doc1: {key: 'a', sort: 0, v: 5}, - doc2: {key: 'aa', sort: 4, v: 4}, - doc3: {key: 'c', sort: 3, v: 3}, - doc4: {key: 'b', sort: 2, v: 2}, - doc5: {key: 'b', sort: 2, v: 1}, - doc6: {key: 'b', sort: 0, v: 0}, - }); - - // Implicitly ordered by: 'key' asc, 'sort' asc, 'v' asc, __name__ asc - let query = collection.where( - Filter.or( - Filter.and( - Filter.where('key', '==', 'b'), - Filter.where('sort', '<=', 2) - ), - Filter.and(Filter.where('key', '!=', 'b'), Filter.where('v', '>', 4)) - ) - ); - let docSnap = await collection.doc('doc1').get(); - let queryWithCursor = query.startAt(docSnap); - expectDocs(await query.get(), 'doc1', 'doc6', 'doc5', 'doc4'); - expectDocs(await queryWithCursor.get(), 'doc1', 'doc6', 'doc5', 'doc4'); - - // Ordered by: 'sort' desc, 'key' asc, 'v' asc, __name__ asc - query = collection - .where( - Filter.or( - Filter.and( - Filter.where('key', '==', 'b'), - Filter.where('sort', '<=', 2) - ), - Filter.and( - Filter.where('key', '!=', 'b'), - Filter.where('v', '>', 4) - ) - ) - ) - .orderBy('sort', 'desc') - .orderBy('key'); - docSnap = await collection.doc('doc5').get(); - queryWithCursor = query.startAt(docSnap); - expectDocs(await query.get(), 'doc5', 'doc4', 'doc1', 'doc6'); - expectDocs(await queryWithCursor.get(), 'doc5', 'doc4', 'doc1', 'doc6'); - - // Implicitly ordered by: 'key' asc, 'sort' asc, 'v' asc, __name__ asc - query = collection.where( - Filter.and( - Filter.or( - Filter.and( - Filter.where('key', '==', 'b'), - Filter.where('sort', '<=', 4) - ), - Filter.and( - Filter.where('key', '!=', 'b'), - Filter.where('v', '>=', 4) - ) - ), - Filter.or( - Filter.and( - Filter.where('key', '>', 'b'), - Filter.where('sort', '>=', 1) - ), - Filter.and(Filter.where('key', '<', 'b'), Filter.where('v', '>', 0)) - ) - ) - ); - docSnap = await collection.doc('doc1').get(); - queryWithCursor = query.startAt(docSnap); - expectDocs(await query.get(), 'doc1', 'doc2'); - expectDocs(await queryWithCursor.get(), 'doc1', 'doc2'); - }); - - it('inequality fields will be implicitly ordered lexicographically by the server', async () => { - const collection = await testCollectionWithDocs({ - doc1: {key: 'a', sort: 0, v: 5}, - doc2: {key: 'aa', sort: 4, v: 4}, - doc3: {key: 'b', sort: 3, v: 3}, - doc4: {key: 'b', sort: 2, v: 2}, - doc5: {key: 'b', sort: 2, v: 1}, - doc6: {key: 'b', sort: 0, v: 0}, - }); - - const docSnap = await collection.doc('doc2').get(); - - // Implicitly ordered by: 'key' asc, 'sort' asc, __name__ asc - let query = collection - .where('key', '!=', 'a') - .where('sort', '>', 1) - .where('v', 'in', [1, 2, 3, 4]); - let queryWithCursor = query.startAt(docSnap); - expectDocs(await query.get(), 'doc2', 'doc4', 'doc5', 'doc3'); - expectDocs(await queryWithCursor.get(), 'doc2', 'doc4', 'doc5', 'doc3'); - - // Changing filters order will not effect implicit order. - // Implicitly ordered by: 'key' asc, 'sort' asc, __name__ asc - query = collection - .where('sort', '>', 1) - .where('key', '!=', 'a') - .where('v', 'in', [1, 2, 3, 4]); - queryWithCursor = query.startAt(docSnap); - expectDocs(await query.get(), 'doc2', 'doc4', 'doc5', 'doc3'); - expectDocs(await queryWithCursor.get(), 'doc2', 'doc4', 'doc5', 'doc3'); - }); - - it('can use multiple explicit order by field', async () => { - const collection = await testCollectionWithDocs({ - doc1: {key: 'a', sort: 5, v: 0}, - doc2: {key: 'aa', sort: 4, v: 0}, - doc3: {key: 'b', sort: 3, v: 1}, - doc4: {key: 'b', sort: 2, v: 1}, - doc5: {key: 'bb', sort: 1, v: 1}, - doc6: {key: 'c', sort: 0, v: 2}, - }); - - let docSnap = await collection.doc('doc2').get(); - - // Ordered by: 'v' asc, 'key' asc, 'sort' asc, __name__ asc - let query = collection - .where('key', '>', 'a') - .where('sort', '>=', 1) - .orderBy('v'); - let queryWithCursor = query.startAt(docSnap); - expectDocs(await query.get(), 'doc2', 'doc4', 'doc3', 'doc5'); - expectDocs(await queryWithCursor.get(), 'doc2', 'doc4', 'doc3', 'doc5'); - - // Ordered by: 'v asc, 'sort' asc, 'key' asc, __name__ asc - query = collection - .where('key', '>', 'a') - .where('sort', '>=', 1) - .orderBy('v') - .orderBy('sort'); - queryWithCursor = query.startAt(docSnap); - expectDocs(await query.get(), 'doc2', 'doc5', 'doc4', 'doc3'); - expectDocs(await queryWithCursor.get(), 'doc2', 'doc5', 'doc4', 'doc3'); - - docSnap = await collection.doc('doc5').get(); - - // Implicit order by matches the direction of last explicit order by. - // Ordered by: 'v' desc, 'key' desc, 'sort' desc, __name__ desc - query = collection - .where('key', '>', 'a') - .where('sort', '>=', 1) - .orderBy('v', 'desc'); - queryWithCursor = query.startAt(docSnap); - expectDocs(await query.get(), 'doc5', 'doc3', 'doc4', 'doc2'); - expectDocs(await queryWithCursor.get(), 'doc5', 'doc3', 'doc4', 'doc2'); - - // Ordered by: 'v desc, 'sort' asc, 'key' asc, __name__ asc - query = collection - .where('key', '>', 'a') - .where('sort', '>=', 1) - .orderBy('v', 'desc') - .orderBy('sort'); - queryWithCursor = query.startAt(docSnap); - expectDocs(await query.get(), 'doc5', 'doc4', 'doc3', 'doc2'); - expectDocs(await queryWithCursor.get(), 'doc5', 'doc4', 'doc3', 'doc2'); - }); - - it('can use in aggregate query', async () => { - const collection = await testCollectionWithDocs({ - doc1: {key: 'a', sort: 5, v: 0}, - doc2: {key: 'aa', sort: 4, v: 0}, - doc3: {key: 'b', sort: 3, v: 1}, - doc4: {key: 'b', sort: 2, v: 1}, - doc5: {key: 'bb', sort: 1, v: 1}, - }); - - const results = await collection - .where('key', '>', 'a') - .where('sort', '>=', 1) - .orderBy('v') - .count() - .get(); - expect(results.data().count).to.be.equal(4); - //TODO(MIEQ): Add sum and average when they are public. - }); - - it('can use document ID im multiple inequality query', async () => { - const collection = await testCollectionWithDocs({ - doc1: {key: 'a', sort: 5}, - doc2: {key: 'aa', sort: 4}, - doc3: {key: 'b', sort: 3}, - doc4: {key: 'b', sort: 2}, - doc5: {key: 'bb', sort: 1}, - }); - - const docSnap = await collection.doc('doc2').get(); - - // Document Key in inequality field will implicitly ordered to the last. - // Implicitly ordered by: 'key' asc, 'sort' asc, __name__ asc - let query = collection - .where('sort', '>=', 1) - .where('key', '!=', 'a') - .where(FieldPath.documentId(), '<', 'doc5'); - let queryWithCursor = query.startAt(docSnap); - expectDocs(await query.get(), 'doc2', 'doc4', 'doc3'); - expectDocs(await queryWithCursor.get(), 'doc2', 'doc4', 'doc3'); - - // Changing filters order will not effect implicit order. - // Implicitly ordered by: 'key' asc, 'sort' asc, __name__ asc - query = collection - .where(FieldPath.documentId(), '<', 'doc5') - .where('sort', '>=', 1) - .where('key', '!=', 'a'); - queryWithCursor = query.startAt(docSnap); - expectDocs(await query.get(), 'doc2', 'doc4', 'doc3'); - expectDocs(await queryWithCursor.get(), 'doc2', 'doc4', 'doc3'); - - // Ordered by: 'sort' desc,'key' desc, __name__ desc - query = collection - .where(FieldPath.documentId(), '<', 'doc5') - .where('sort', '>=', 1) - .where('key', '!=', 'a') - .orderBy('sort', 'desc'); - queryWithCursor = query.startAt(docSnap); - expectDocs(await query.get(), 'doc2', 'doc3', 'doc4'); - expectDocs(await queryWithCursor.get(), 'doc2', 'doc3', 'doc4'); - }); - }); -}); - describe('count queries', () => { let firestore: Firestore; let randomCol: CollectionReference; diff --git a/dev/system-test/pipeline.ts b/dev/system-test/pipeline.ts new file mode 100644 index 000000000..8dcfe7006 --- /dev/null +++ b/dev/system-test/pipeline.ts @@ -0,0 +1,99 @@ +import { + AggregateQuery, + DocumentData, + QuerySnapshot, + VectorValue, +} from '@google-cloud/firestore'; + +import {expect} from 'chai'; +import {afterEach, beforeEach, describe, it} from 'mocha'; +import { + CollectionReference, + DocumentReference, + DocumentSnapshot, + FieldPath, + FieldValue, + Filter, + Firestore, + Query, + QueryDocumentSnapshot, +} from '../src'; +import {verifyInstance} from '../test/util/helpers'; +import {DeferredPromise, getTestRoot} from './firestore'; +import {IndexTestHelper} from './index_test_helper'; + +describe('Pipeline class', () => { + let firestore: Firestore; + let randomCol: CollectionReference; + + async function addDocs( + ...docs: DocumentData[] + ): Promise { + let id = 0; // Guarantees consistent ordering for the first documents + const refs: DocumentReference[] = []; + for (const doc of docs) { + const ref = randomCol.doc('doc' + id++); + await ref.set(doc); + refs.push(ref); + } + return refs; + } + + async function testCollectionWithDocs(docs: { + [id: string]: DocumentData; + }): Promise> { + for (const id in docs) { + const ref = randomCol.doc(id); + await ref.set(docs[id]); + } + return randomCol; + } + + function expectDocs(result: QuerySnapshot, ...docs: string[]): void; + function expectDocs(result: QuerySnapshot, ...data: DocumentData[]): void; + + function expectDocs( + result: QuerySnapshot, + ...data: DocumentData[] | string[] + ): void { + expect(result.size).to.equal(data.length); + + if (data.length > 0) { + if (typeof data[0] === 'string') { + const actualIds = result.docs.map(docSnapshot => docSnapshot.id); + expect(actualIds).to.deep.equal(data); + } else { + result.forEach(doc => { + expect(doc.data()).to.deep.equal(data.shift()); + }); + } + } + } + + async function compareQueryAndPipeline(query: Query): Promise { + const queryResults = await query.get(); + const pipeline = query.toPipeline(); + const pipelineResults = await pipeline.execute(); + + expect(queryResults.docs.map(s => s._fieldsProto)).to.deep.equal( + pipelineResults.map(r => r._fieldsProto) + ); + return queryResults; + } + + beforeEach(() => { + randomCol = getTestRoot(); + firestore = randomCol.firestore; + }); + + afterEach(() => verifyInstance(firestore)); + + it('basic collection', async () => { + const result = await firestore + .pipeline() + .collection(randomCol.path) + .limit(0) + .execute(); + expect(result).to.be.empty; + }); +}); diff --git a/dev/system-test/query.ts b/dev/system-test/query.ts new file mode 100644 index 000000000..efc42be03 --- /dev/null +++ b/dev/system-test/query.ts @@ -0,0 +1,2234 @@ +import { + DocumentData, + QuerySnapshot, + VectorValue, +} from '@google-cloud/firestore'; + +import {expect} from 'chai'; +import {afterEach, beforeEach, describe, it} from 'mocha'; +import { + CollectionReference, + DocumentReference, + DocumentSnapshot, + FieldPath, + FieldValue, + Filter, + Firestore, + Query, + QueryDocumentSnapshot, + VectorQuery, + VectorQuerySnapshot, +} from '../src'; +import {verifyInstance} from '../test/util/helpers'; +import {DeferredPromise, getTestRoot} from './firestore'; +import {IndexTestHelper} from './index_test_helper'; + +describe.only('Query class', () => { + interface PaginatedResults { + pages: number; + docs: QueryDocumentSnapshot[]; + } + + let firestore: Firestore; + let randomCol: CollectionReference; + + const paginateResults = ( + query: Query, + startAfter?: unknown + ): Promise => { + return (startAfter ? query.startAfter(startAfter) : query) + .get() + .then(snapshot => { + if (snapshot.empty) { + return {pages: 0, docs: []}; + } else { + const docs = snapshot.docs; + return paginateResults(query, docs[docs.length - 1]).then( + nextPage => { + return { + pages: nextPage.pages + 1, + docs: docs.concat(nextPage.docs), + }; + } + ); + } + }); + }; + + async function addDocs( + ...docs: DocumentData[] + ): Promise { + let id = 0; // Guarantees consistent ordering for the first documents + const refs: DocumentReference[] = []; + for (const doc of docs) { + const ref = randomCol.doc('doc' + id++); + await ref.set(doc); + refs.push(ref); + } + return refs; + } + + async function testCollectionWithDocs(docs: { + [id: string]: DocumentData; + }): Promise> { + for (const id in docs) { + const ref = randomCol.doc(id); + await ref.set(docs[id]); + } + return randomCol; + } + + function expectDocs(result: QuerySnapshot, ...docs: string[]): void; + function expectDocs(result: QuerySnapshot, ...data: DocumentData[]): void; + + function expectDocs( + result: QuerySnapshot, + ...data: DocumentData[] | string[] + ): void { + expect(result.size).to.equal(data.length); + + if (data.length > 0) { + if (typeof data[0] === 'string') { + const actualIds = result.docs.map(docSnapshot => docSnapshot.id); + expect(actualIds).to.deep.equal(data); + } else { + result.forEach(doc => { + expect(doc.data()).to.deep.equal(data.shift()); + }); + } + } + } + + async function compareQueryAndPipeline(query: Query): Promise { + const queryResults = await query.get(); + const pipeline = query.toPipeline(); + const pipelineResults = await pipeline.execute(); + + expect(pipelineResults.map(r => r._fieldsProto)).to.deep.equal( + queryResults.docs.map(s => s._fieldsProto) + ); + return queryResults; + } + + async function compareVectorQueryAndPipeline( + query: VectorQuery + ): Promise { + const queryResults = await query.get(); + const pipeline = query.toPipeline(); + const pipelineResults = await pipeline.execute(); + + expect(pipelineResults.map(r => r._fieldsProto)).to.deep.equal( + queryResults.docs.map(s => s._fieldsProto) + ); + return queryResults; + } + + beforeEach(() => { + randomCol = getTestRoot(); + firestore = randomCol.firestore; + }); + + afterEach(() => verifyInstance(firestore)); + + it('has firestore property', () => { + const ref = randomCol.limit(0); + expect(ref.firestore).to.be.an.instanceOf(Firestore); + }); + + it('has select() method', () => { + const ref = randomCol.doc('doc'); + return ref + .set({foo: 'bar', bar: 'foo'}) + .then(() => { + return randomCol.select('foo').get(); + }) + .then(res => { + expect(res.docs[0].data()).to.deep.equal({foo: 'bar'}); + }); + }); + + it('select() supports empty fields', () => { + const ref = randomCol.doc('doc'); + return ref + .set({foo: 'bar', bar: 'foo'}) + .then(() => { + return randomCol.select().get(); + }) + .then(res => { + expect(res.docs[0].ref.id).to.deep.equal('doc'); + expect(res.docs[0].data()).to.deep.equal({}); + }); + }); + + it('has where() method', () => { + const ref = randomCol.doc('doc'); + return ref + .set({foo: 'bar'}) + .then(() => { + return compareQueryAndPipeline(randomCol.where('foo', '==', 'bar')); + }) + .then(res => { + expect(res.docs[0].data()).to.deep.equal({foo: 'bar'}); + }); + }); + + it('supports NaN and Null', () => { + const ref = randomCol.doc('doc'); + return ref + .set({foo: NaN, bar: null}) + .then(() => { + return compareQueryAndPipeline( + randomCol.where('foo', '==', NaN).where('bar', '==', null) + ); + }) + .then(res => { + expect( + typeof res.docs[0].get('foo') === 'number' && + isNaN(res.docs[0].get('foo')) + ); + expect(res.docs[0].get('bar')).to.equal(null); + }); + }); + + it('supports array-contains', () => { + return Promise.all([ + randomCol.add({foo: ['bar']}), + randomCol.add({foo: []}), + ]) + .then(() => + compareQueryAndPipeline(randomCol.where('foo', 'array-contains', 'bar')) + ) + .then(res => { + expect(res.size).to.equal(1); + expect(res.docs[0].get('foo')).to.deep.equal(['bar']); + }); + }); + + it.skip('supports findNearest by EUCLIDEAN distance', async () => { + const indexTestHelper = new IndexTestHelper(firestore); + + const collectionReference = await indexTestHelper.createTestDocs([ + {foo: 'bar'}, + {foo: 'xxx', embedding: FieldValue.vector([10, 10])}, + {foo: 'bar', embedding: FieldValue.vector([1, 1])}, + {foo: 'bar', embedding: FieldValue.vector([10, 0])}, + {foo: 'bar', embedding: FieldValue.vector([20, 0])}, + {foo: 'bar', embedding: FieldValue.vector([100, 100])}, + ]); + + const vectorQuery = indexTestHelper + .query(collectionReference) + .where('foo', '==', 'bar') + .findNearest('embedding', [10, 10], { + limit: 3, + distanceMeasure: 'EUCLIDEAN', + }); + + const res = await compareVectorQueryAndPipeline(vectorQuery); + expect(res.size).to.equal(3); + expect(res.docs[0].get('embedding').isEqual(FieldValue.vector([10, 0]))).to + .be.true; + expect(res.docs[1].get('embedding').isEqual(FieldValue.vector([1, 1]))).to + .be.true; + expect(res.docs[2].get('embedding').isEqual(FieldValue.vector([20, 0]))).to + .be.true; + }); + + it.skip('supports findNearest by COSINE distance', async () => { + const indexTestHelper = new IndexTestHelper(firestore); + + const collectionReference = await indexTestHelper.setTestDocs({ + '1': {foo: 'bar'}, + '2': {foo: 'xxx', embedding: FieldValue.vector([10, 10])}, + '3': {foo: 'bar', embedding: FieldValue.vector([1, 1])}, + '4': {foo: 'bar', embedding: FieldValue.vector([20, 0])}, + '5': {foo: 'bar', embedding: FieldValue.vector([10, 0])}, + '6': {foo: 'bar', embedding: FieldValue.vector([100, 100])}, + }); + + const vectorQuery = indexTestHelper + .query(collectionReference) + .where('foo', '==', 'bar') + .findNearest('embedding', [10, 10], { + limit: 3, + distanceMeasure: 'COSINE', + }); + + const res = await compareVectorQueryAndPipeline(vectorQuery); + + expect(res.size).to.equal(3); + + if (res.docs[0].get('embedding').isEqual(FieldValue.vector([1, 1]))) { + expect( + res.docs[1].get('embedding').isEqual(FieldValue.vector([100, 100])) + ).to.be.true; + } else { + expect( + res.docs[0].get('embedding').isEqual(FieldValue.vector([100, 100])) + ).to.be.true; + expect(res.docs[1].get('embedding').isEqual(FieldValue.vector([1, 1]))).to + .be.true; + } + + expect( + res.docs[2].get('embedding').isEqual(FieldValue.vector([20, 0])) || + res.docs[2].get('embedding').isEqual(FieldValue.vector([20, 0])) + ).to.be.true; + }); + + it.skip('supports findNearest by DOT_PRODUCT distance', async () => { + const indexTestHelper = new IndexTestHelper(firestore); + + const collectionReference = await indexTestHelper.createTestDocs([ + {foo: 'bar'}, + {foo: 'xxx', embedding: FieldValue.vector([10, 10])}, + {foo: 'bar', embedding: FieldValue.vector([1, 1])}, + {foo: 'bar', embedding: FieldValue.vector([10, 0])}, + {foo: 'bar', embedding: FieldValue.vector([20, 0])}, + {foo: 'bar', embedding: FieldValue.vector([100, 100])}, + ]); + + const vectorQuery = indexTestHelper + .query(collectionReference) + .where('foo', '==', 'bar') + .findNearest('embedding', [10, 10], { + limit: 3, + distanceMeasure: 'DOT_PRODUCT', + }); + + const res = await compareVectorQueryAndPipeline(vectorQuery); + expect(res.size).to.equal(3); + expect(res.docs[0].get('embedding').isEqual(FieldValue.vector([100, 100]))) + .to.be.true; + expect(res.docs[1].get('embedding').isEqual(FieldValue.vector([20, 0]))).to + .be.true; + expect(res.docs[2].get('embedding').isEqual(FieldValue.vector([10, 0]))).to + .be.true; + }); + + it.skip('findNearest works with converters', async () => { + const indexTestHelper = new IndexTestHelper(firestore); + + class FooDistance { + constructor( + readonly foo: string, + readonly embedding: Array + ) {} + } + + const fooConverter = { + toFirestore(d: FooDistance): DocumentData { + return {title: d.foo, embedding: FieldValue.vector(d.embedding)}; + }, + fromFirestore(snapshot: QueryDocumentSnapshot): FooDistance { + const data = snapshot.data(); + return new FooDistance(data.foo, data.embedding.toArray()); + }, + }; + + const collectionRef = await indexTestHelper.createTestDocs([ + {foo: 'bar', embedding: FieldValue.vector([5, 5])}, + ]); + + const vectorQuery = indexTestHelper + .query(collectionRef) + .withConverter(fooConverter) + .where('foo', '==', 'bar') + .findNearest('embedding', [10, 10], { + limit: 3, + distanceMeasure: 'EUCLIDEAN', + }); + + const res = await compareVectorQueryAndPipeline(vectorQuery); + + expect(res.size).to.equal(1); + expect(res.docs[0].data().foo).to.equal('bar'); + expect(res.docs[0].data().embedding).to.deep.equal([5, 5]); + }); + + it.skip('supports findNearest skipping fields of wrong types', async () => { + const indexTestHelper = new IndexTestHelper(firestore); + + const collectionRef = await indexTestHelper.createTestDocs([ + {foo: 'bar'}, + + // These documents are skipped because it is not really a vector value + {foo: 'bar', embedding: [10, 10]}, + {foo: 'bar', embedding: 'not actually a vector'}, + {foo: 'bar', embedding: null}, + + // Actual vector values + {foo: 'bar', embedding: FieldValue.vector([9, 9])}, + {foo: 'bar', embedding: FieldValue.vector([50, 50])}, + {foo: 'bar', embedding: FieldValue.vector([100, 100])}, + ]); + + const vectorQuery = indexTestHelper + .query(collectionRef) + .where('foo', '==', 'bar') + .findNearest('embedding', [10, 10], { + limit: 100, // Intentionally large to get all matches. + distanceMeasure: 'EUCLIDEAN', + }); + + const res = await compareVectorQueryAndPipeline(vectorQuery); + expect(res.size).to.equal(3); + expect(res.docs[0].get('embedding').isEqual(FieldValue.vector([9, 9]))).to + .be.true; + expect(res.docs[1].get('embedding').isEqual(FieldValue.vector([50, 50]))).to + .be.true; + expect(res.docs[2].get('embedding').isEqual(FieldValue.vector([100, 100]))) + .to.be.true; + }); + + it.skip('findNearest ignores mismatching dimensions', async () => { + const indexTestHelper = new IndexTestHelper(firestore); + + const collectionRef = await indexTestHelper.createTestDocs([ + {foo: 'bar'}, + + // Vectors with dimension mismatch + {foo: 'bar', embedding: FieldValue.vector([10])}, + + // Vectors with dimension match + {foo: 'bar', embedding: FieldValue.vector([9, 9])}, + {foo: 'bar', embedding: FieldValue.vector([50, 50])}, + ]); + + const vectorQuery = indexTestHelper + .query(collectionRef) + .where('foo', '==', 'bar') + .findNearest('embedding', [10, 10], { + limit: 3, + distanceMeasure: 'EUCLIDEAN', + }); + + const res = await compareVectorQueryAndPipeline(vectorQuery); + expect(res.size).to.equal(2); + expect(res.docs[0].get('embedding').isEqual(FieldValue.vector([9, 9]))).to + .be.true; + expect(res.docs[1].get('embedding').isEqual(FieldValue.vector([50, 50]))).to + .be.true; + }); + + it.skip('supports findNearest on non-existent field', async () => { + const indexTestHelper = new IndexTestHelper(firestore); + + const collectionRef = await indexTestHelper.createTestDocs([ + {foo: 'bar'}, + {foo: 'bar', otherField: [10, 10]}, + {foo: 'bar', otherField: 'not actually a vector'}, + {foo: 'bar', otherField: null}, + ]); + + const vectorQuery = indexTestHelper + .query(collectionRef) + .where('foo', '==', 'bar') + .findNearest('embedding', [10, 10], { + limit: 3, + distanceMeasure: 'EUCLIDEAN', + }); + + const res = await compareVectorQueryAndPipeline(vectorQuery); + + expect(res.size).to.equal(0); + }); + + it.skip('supports findNearest on vector nested in a map', async () => { + const indexTestHelper = new IndexTestHelper(firestore); + + const collectionReference = await indexTestHelper.createTestDocs([ + {nested: {foo: 'bar'}}, + {nested: {foo: 'xxx', embedding: FieldValue.vector([10, 10])}}, + {nested: {foo: 'bar', embedding: FieldValue.vector([1, 1])}}, + {nested: {foo: 'bar', embedding: FieldValue.vector([10, 0])}}, + {nested: {foo: 'bar', embedding: FieldValue.vector([20, 0])}}, + {nested: {foo: 'bar', embedding: FieldValue.vector([100, 100])}}, + ]); + + const vectorQuery = indexTestHelper + .query(collectionReference) + .findNearest('nested.embedding', [10, 10], { + limit: 3, + distanceMeasure: 'EUCLIDEAN', + }); + + const res = await compareVectorQueryAndPipeline(vectorQuery); + expect(res.size).to.equal(3); + expect( + res.docs[0].get('nested.embedding').isEqual(FieldValue.vector([10, 10])) + ).to.be.true; + expect( + res.docs[1].get('nested.embedding').isEqual(FieldValue.vector([10, 0])) + ).to.be.true; + expect( + res.docs[2].get('nested.embedding').isEqual(FieldValue.vector([1, 1])) + ).to.be.true; + }); + + it('supports findNearest with select to exclude vector data in response', async () => { + const indexTestHelper = new IndexTestHelper(firestore); + + const collectionReference = await indexTestHelper.createTestDocs([ + {foo: 1}, + {foo: 2, embedding: FieldValue.vector([10, 10])}, + {foo: 3, embedding: FieldValue.vector([1, 1])}, + {foo: 4, embedding: FieldValue.vector([10, 0])}, + {foo: 5, embedding: FieldValue.vector([20, 0])}, + {foo: 6, embedding: FieldValue.vector([100, 100])}, + ]); + + const vectorQuery = indexTestHelper + .query(collectionReference) + .where('foo', 'in', [1, 2, 3, 4, 5, 6]) + .select('foo') + .findNearest('embedding', [10, 10], { + limit: 10, + distanceMeasure: 'EUCLIDEAN', + }); + + const res = await vectorQuery.get(); + expect(res.size).to.equal(5); + expect(res.docs[0].get('foo')).to.equal(2); + expect(res.docs[1].get('foo')).to.equal(4); + expect(res.docs[2].get('foo')).to.equal(3); + expect(res.docs[3].get('foo')).to.equal(5); + expect(res.docs[4].get('foo')).to.equal(6); + + res.docs.forEach(ds => expect(ds.get('embedding')).to.be.undefined); + }); + + it.skip('supports findNearest limits', async () => { + const indexTestHelper = new IndexTestHelper(firestore); + + const embeddingVector = []; + const queryVector = []; + for (let i = 0; i < 2048; i++) { + embeddingVector.push(i + 1); + queryVector.push(i - 1); + } + + const collectionReference = await indexTestHelper.createTestDocs([ + {embedding: FieldValue.vector(embeddingVector)}, + ]); + + const vectorQuery = indexTestHelper + .query(collectionReference) + .findNearest('embedding', queryVector, { + limit: 1000, + distanceMeasure: 'EUCLIDEAN', + }); + + const res = await compareVectorQueryAndPipeline(vectorQuery); + expect(res.size).to.equal(1); + expect( + (res.docs[0].get('embedding') as VectorValue).toArray() + ).to.deep.equal(embeddingVector); + }); + + it('supports !=', async () => { + await addDocs( + {zip: NaN}, + {zip: 91102}, + {zip: 98101}, + {zip: 98103}, + {zip: [98101]}, + {zip: ['98101', {zip: 98101}]}, + {zip: {zip: 98101}}, + {zip: null} + ); + + let res = await compareQueryAndPipeline( + randomCol.where('zip', '!=', 98101) + ); + expectDocs( + res, + {zip: NaN}, + {zip: 91102}, + {zip: 98103}, + {zip: [98101]}, + {zip: ['98101', {zip: 98101}]}, + {zip: {zip: 98101}} + ); + + res = await compareQueryAndPipeline(randomCol.where('zip', '!=', NaN)); + expectDocs( + res, + {zip: 91102}, + {zip: 98101}, + {zip: 98103}, + {zip: [98101]}, + {zip: ['98101', {zip: 98101}]}, + {zip: {zip: 98101}} + ); + + res = await compareQueryAndPipeline(randomCol.where('zip', '!=', null)); + expectDocs( + res, + {zip: NaN}, + {zip: 91102}, + {zip: 98101}, + {zip: 98103}, + {zip: [98101]}, + {zip: ['98101', {zip: 98101}]}, + {zip: {zip: 98101}} + ); + }); + + it('supports != with document ID', async () => { + const refs = await addDocs({count: 1}, {count: 2}, {count: 3}); + const res = await compareQueryAndPipeline( + randomCol.where(FieldPath.documentId(), '!=', refs[0].id) + ); + expectDocs(res, {count: 2}, {count: 3}); + }); + + it.skip('supports not-in', async () => { + await addDocs( + {zip: 98101}, + {zip: 91102}, + {zip: 98103}, + {zip: [98101]}, + {zip: ['98101', {zip: 98101}]}, + {zip: {zip: 98101}} + ); + let res = await compareQueryAndPipeline( + randomCol.where('zip', 'not-in', [98101, 98103]) + ); + expectDocs( + res, + {zip: 91102}, + {zip: [98101]}, + {zip: ['98101', {zip: 98101}]}, + {zip: {zip: 98101}} + ); + + res = await compareQueryAndPipeline( + randomCol.where('zip', 'not-in', [NaN]) + ); + expectDocs( + res, + {zip: 91102}, + {zip: 98101}, + {zip: 98103}, + {zip: [98101]}, + {zip: ['98101', {zip: 98101}]}, + {zip: {zip: 98101}} + ); + + res = await compareQueryAndPipeline( + randomCol.where('zip', 'not-in', [null]) + ); + expect(res.size).to.equal(0); + }); + + it('supports not-in with document ID array', async () => { + const refs = await addDocs({count: 1}, {count: 2}, {count: 3}); + const res = await compareQueryAndPipeline( + randomCol.where(FieldPath.documentId(), 'not-in', [refs[0].id, refs[1]]) + ); + expectDocs(res, {count: 3}); + }); + + it('supports "in"', async () => { + await addDocs( + {zip: 98101}, + {zip: 91102}, + {zip: 98103}, + {zip: [98101]}, + {zip: ['98101', {zip: 98101}]}, + {zip: {zip: 98101}} + ); + const res = await compareQueryAndPipeline( + randomCol.where('zip', 'in', [98101, 98103]) + ); + expectDocs(res, {zip: 98101}, {zip: 98103}); + }); + + it.only('supports "in" with document ID array', async () => { + const refs = await addDocs({count: 1}, {count: 2}, {count: 3}); + const res = await compareQueryAndPipeline( + randomCol.where(FieldPath.documentId(), 'in', [refs[0].id, refs[1]]) + ); + expectDocs(res, {count: 1}, {count: 2}); + }); + + it('supports array-contains-any', async () => { + await addDocs( + {array: [42]}, + {array: ['a', 42, 'c']}, + {array: [41.999, '42', {a: [42]}]}, + {array: [42], array2: ['sigh']}, + {array: [43]}, + {array: [{a: 42}]}, + {array: 42} + ); + + const res = await compareQueryAndPipeline( + randomCol.where('array', 'array-contains-any', [42, 43]) + ); + + expectDocs( + res, + {array: [42]}, + {array: ['a', 42, 'c']}, + { + array: [42], + array2: ['sigh'], + }, + {array: [43]} + ); + }); + + it.skip('can query by FieldPath.documentId()', () => { + const ref = randomCol.doc('foo'); + + return ref + .set({}) + .then(() => { + return compareQueryAndPipeline( + randomCol.where(FieldPath.documentId(), '>=', 'bar') + ); + }) + .then(res => { + expect(res.docs.length).to.equal(1); + }); + }); + + it.skip('has orderBy() method', async () => { + await addDocs({foo: 'a'}, {foo: 'b'}); + + let res = await compareQueryAndPipeline(randomCol.orderBy('foo')); + expectDocs(res, {foo: 'a'}, {foo: 'b'}); + + res = await compareQueryAndPipeline(randomCol.orderBy('foo', 'desc')); + expectDocs(res, {foo: 'b'}, {foo: 'a'}); + }); + + it('can order by FieldPath.documentId()', () => { + const ref1 = randomCol.doc('doc1'); + const ref2 = randomCol.doc('doc2'); + + return Promise.all([ref1.set({foo: 'a'}), ref2.set({foo: 'b'})]) + .then(() => { + return compareQueryAndPipeline( + randomCol.orderBy(FieldPath.documentId()) + ); + }) + .then(res => { + expect(res.docs[0].data()).to.deep.equal({foo: 'a'}); + expect(res.docs[1].data()).to.deep.equal({foo: 'b'}); + }); + }); + + it('can run get() on empty collection', async () => { + return compareQueryAndPipeline(randomCol).then(res => { + return expect(res.empty); + }); + }); + + it('can run stream() on empty collection', async () => { + let received = 0; + const stream = randomCol.stream(); + + for await (const doc of stream) { + expect(doc).to.be.an.instanceOf(QueryDocumentSnapshot); + ++received; + } + + expect(received).to.equal(0); + }); + + it.skip('has limit() method on get()', async () => { + await addDocs({foo: 'a'}, {foo: 'b'}); + const res = await compareQueryAndPipeline( + randomCol.orderBy('foo').limit(1) + ); + expectDocs(res, {foo: 'a'}); + }); + + it('has limit() method on stream()', async () => { + let received = 0; + await addDocs({foo: 'a'}, {foo: 'b'}); + + const stream = randomCol.orderBy('foo').limit(1).stream(); + for await (const doc of stream) { + expect(doc).to.be.an.instanceOf(QueryDocumentSnapshot); + ++received; + } + + expect(received).to.equal(1); + }); + + it.skip('can run limit(num), where num is larger than the collection size on get()', async () => { + await addDocs({foo: 'a'}, {foo: 'b'}); + const res = await compareQueryAndPipeline( + randomCol.orderBy('foo').limit(3) + ); + expectDocs(res, {foo: 'a'}, {foo: 'b'}); + }); + + it('can run limit(num), where num is larger than the collection size on stream()', async () => { + let received = 0; + await addDocs({foo: 'a'}, {foo: 'b'}); + + const stream = randomCol.orderBy('foo').limit(3).stream(); + for await (const doc of stream) { + expect(doc).to.be.an.instanceOf(QueryDocumentSnapshot); + ++received; + } + + expect(received).to.equal(2); + }); + + it.skip('has limitToLast() method', async () => { + await addDocs({doc: 1}, {doc: 2}, {doc: 3}); + // const res = await compareQueryAndPipeline(randomCol.orderBy('doc').limitToLast(2)); + const res = await randomCol.orderBy('doc').limitToLast(2).get(); + expectDocs(res, {doc: 2}, {doc: 3}); + }); + + it('limitToLast() supports Query cursors', async () => { + await addDocs({doc: 1}, {doc: 2}, {doc: 3}, {doc: 4}, {doc: 5}); + const res = await compareQueryAndPipeline( + randomCol.orderBy('doc').startAt(2).endAt(4).limitToLast(5) + ); + expectDocs(res, {doc: 2}, {doc: 3}, {doc: 4}); + }); + + it.skip('can use offset() method with get()', async () => { + await addDocs({foo: 'a'}, {foo: 'b'}); + const res = await compareQueryAndPipeline( + randomCol.orderBy('foo').offset(1) + ); + expectDocs(res, {foo: 'b'}); + }); + + it('can use offset() method with stream()', async () => { + let received = 0; + await addDocs({foo: 'a'}, {foo: 'b'}); + + const stream = randomCol.orderBy('foo').offset(1).stream(); + for await (const doc of stream) { + expect(doc).to.be.an.instanceOf(QueryDocumentSnapshot); + ++received; + } + + expect(received).to.equal(1); + }); + + it.skip('can run offset(num), where num is larger than the collection size on get()', async () => { + await addDocs({foo: 'a'}, {foo: 'b'}); + const res = await compareQueryAndPipeline( + randomCol.orderBy('foo').offset(3) + ); + expect(res.empty); + }); + + it('can run offset(num), where num is larger than the collection size on stream()', async () => { + let received = 0; + await addDocs({foo: 'a'}, {foo: 'b'}); + const stream = randomCol.orderBy('foo').offset(3).stream(); + for await (const doc of stream) { + expect(doc).to.be.an.instanceOf(QueryDocumentSnapshot); + ++received; + } + expect(received).to.equal(0); + }); + + it('supports Unicode in document names', async () => { + const collRef = randomCol.doc('доброеутро').collection('coll'); + await collRef.add({}); + const snapshot = await compareQueryAndPipeline(collRef); + expect(snapshot.size).to.equal(1); + }); + + it('supports pagination', () => { + const batch = firestore.batch(); + + for (let i = 0; i < 10; ++i) { + batch.set(randomCol.doc('doc' + i), {val: i}); + } + + const query = randomCol.orderBy('val').limit(3); + + return batch + .commit() + .then(() => paginateResults(query)) + .then(results => { + expect(results.pages).to.equal(4); + expect(results.docs).to.have.length(10); + }); + }); + + it('supports pagination with where() clauses', () => { + const batch = firestore.batch(); + + for (let i = 0; i < 10; ++i) { + batch.set(randomCol.doc('doc' + i), {val: i}); + } + + const query = randomCol.where('val', '>=', 1).limit(3); + + return batch + .commit() + .then(() => paginateResults(query)) + .then(results => { + expect(results.pages).to.equal(3); + expect(results.docs).to.have.length(9); + }); + }); + + it('supports pagination with array-contains filter', () => { + const batch = firestore.batch(); + + for (let i = 0; i < 10; ++i) { + batch.set(randomCol.doc('doc' + i), {array: ['foo']}); + } + + const query = randomCol.where('array', 'array-contains', 'foo').limit(3); + + return batch + .commit() + .then(() => paginateResults(query)) + .then(results => { + expect(results.pages).to.equal(4); + expect(results.docs).to.have.length(10); + }); + }); + + it('has startAt() method', async () => { + await addDocs({foo: 'a'}, {foo: 'b'}); + const res = await randomCol.orderBy('foo').startAt('b').get(); + expectDocs(res, {foo: 'b'}); + }); + + it('startAt() adds implicit order by for DocumentSnapshot', async () => { + const references = await addDocs({foo: 'a'}, {foo: 'b'}); + const docSnap = await references[1].get(); + const res = await randomCol.startAt(docSnap).get(); + expectDocs(res, {foo: 'b'}); + }); + + it('has startAfter() method', async () => { + await addDocs({foo: 'a'}, {foo: 'b'}); + const res = await randomCol.orderBy('foo').startAfter('a').get(); + expectDocs(res, {foo: 'b'}); + }); + + it('has endAt() method', async () => { + await addDocs({foo: 'a'}, {foo: 'b'}); + const res = await randomCol.orderBy('foo').endAt('b').get(); + expectDocs(res, {foo: 'a'}, {foo: 'b'}); + }); + + it('has endBefore() method', async () => { + await addDocs({foo: 'a'}, {foo: 'b'}); + const res = await randomCol.orderBy('foo').endBefore('b').get(); + expectDocs(res, {foo: 'a'}); + }); + + it('has stream() method', done => { + let received = 0; + const ref1 = randomCol.doc('doc1'); + const ref2 = randomCol.doc('doc2'); + + Promise.all([ref1.set({foo: 'a'}), ref2.set({foo: 'b'})]).then(() => { + return randomCol + .stream() + .on('data', d => { + expect(d).to.be.an.instanceOf(DocumentSnapshot); + ++received; + }) + .on('end', () => { + expect(received).to.equal(2); + done(); + }); + }); + }); + + it('stream() supports readable[Symbol.asyncIterator]()', async () => { + let received = 0; + await randomCol.doc().set({foo: 'bar'}); + await randomCol.doc().set({foo: 'bar'}); + + const stream = randomCol.stream(); + for await (const doc of stream) { + expect(doc).to.be.an.instanceOf(QueryDocumentSnapshot); + ++received; + } + + expect(received).to.equal(2); + }); + + it.skip('can query collection groups', async () => { + // Use `randomCol` to get a random collection group name to use but ensure + // it starts with 'b' for predictable ordering. + const collectionGroup = 'b' + randomCol.id; + + const docPaths = [ + `abc/123/${collectionGroup}/cg-doc1`, + `abc/123/${collectionGroup}/cg-doc2`, + `${collectionGroup}/cg-doc3`, + `${collectionGroup}/cg-doc4`, + `def/456/${collectionGroup}/cg-doc5`, + `${collectionGroup}/virtual-doc/nested-coll/not-cg-doc`, + `x${collectionGroup}/not-cg-doc`, + `${collectionGroup}x/not-cg-doc`, + `abc/123/${collectionGroup}x/not-cg-doc`, + `abc/123/x${collectionGroup}/not-cg-doc`, + `abc/${collectionGroup}`, + ]; + const batch = firestore.batch(); + for (const docPath of docPaths) { + batch.set(firestore.doc(docPath), {x: 1}); + } + await batch.commit(); + + const querySnapshot = await compareQueryAndPipeline( + firestore.collectionGroup(collectionGroup) + ); + expect(querySnapshot.docs.map(d => d.id)).to.deep.equal([ + 'cg-doc1', + 'cg-doc2', + 'cg-doc3', + 'cg-doc4', + 'cg-doc5', + ]); + }); + + it('can query collection groups with startAt / endAt by arbitrary documentId', async () => { + // Use `randomCol` to get a random collection group name to use but + // ensure it starts with 'b' for predictable ordering. + const collectionGroup = 'b' + randomCol.id; + + const docPaths = [ + `a/a/${collectionGroup}/cg-doc1`, + `a/b/a/b/${collectionGroup}/cg-doc2`, + `a/b/${collectionGroup}/cg-doc3`, + `a/b/c/d/${collectionGroup}/cg-doc4`, + `a/c/${collectionGroup}/cg-doc5`, + `${collectionGroup}/cg-doc6`, + 'a/b/nope/nope', + ]; + const batch = firestore.batch(); + for (const docPath of docPaths) { + batch.set(firestore.doc(docPath), {x: 1}); + } + await batch.commit(); + + let querySnapshot = await firestore + .collectionGroup(collectionGroup) + .orderBy(FieldPath.documentId()) + .startAt('a/b') + .endAt('a/b0') + .get(); + expect(querySnapshot.docs.map(d => d.id)).to.deep.equal([ + 'cg-doc2', + 'cg-doc3', + 'cg-doc4', + ]); + + querySnapshot = await firestore + .collectionGroup(collectionGroup) + .orderBy(FieldPath.documentId()) + .startAfter('a/b') + .endBefore(`a/b/${collectionGroup}/cg-doc3`) + .get(); + expect(querySnapshot.docs.map(d => d.id)).to.deep.equal(['cg-doc2']); + }); + + it('can query collection groups with where filters on arbitrary documentId', async () => { + // Use `randomCol` to get a random collection group name to use but + // ensure it starts with 'b' for predictable ordering. + const collectionGroup = 'b' + randomCol.id; + + const docPaths = [ + `a/a/${collectionGroup}/cg-doc1`, + `a/b/a/b/${collectionGroup}/cg-doc2`, + `a/b/${collectionGroup}/cg-doc3`, + `a/b/c/d/${collectionGroup}/cg-doc4`, + `a/c/${collectionGroup}/cg-doc5`, + `${collectionGroup}/cg-doc6`, + 'a/b/nope/nope', + ]; + const batch = firestore.batch(); + for (const docPath of docPaths) { + batch.set(firestore.doc(docPath), {x: 1}); + } + await batch.commit(); + + let querySnapshot = await compareQueryAndPipeline( + firestore + .collectionGroup(collectionGroup) + .where(FieldPath.documentId(), '>=', 'a/b') + .where(FieldPath.documentId(), '<=', 'a/b0') + ); + expect(querySnapshot.docs.map(d => d.id)).to.deep.equal([ + 'cg-doc2', + 'cg-doc3', + 'cg-doc4', + ]); + + querySnapshot = await compareQueryAndPipeline( + firestore + .collectionGroup(collectionGroup) + .where(FieldPath.documentId(), '>', 'a/b') + .where(FieldPath.documentId(), '<', `a/b/${collectionGroup}/cg-doc3`) + ); + expect(querySnapshot.docs.map(d => d.id)).to.deep.equal(['cg-doc2']); + }); + + it('can query large collections', async () => { + // @grpc/grpc-js v0.4.1 failed to deliver the full set of query results for + // larger collections (https://github.com/grpc/grpc-node/issues/895); + const batch = firestore.batch(); + for (let i = 0; i < 100; ++i) { + batch.create(randomCol.doc(), {}); + } + await batch.commit(); + + const snapshot = await compareQueryAndPipeline(randomCol); + expect(snapshot.size).to.equal(100); + }); + + it('supports OR queries', async () => { + const collection = await testCollectionWithDocs({ + doc1: {a: 1, b: 0}, + doc2: {a: 2, b: 1}, + doc3: {a: 3, b: 2}, + doc4: {a: 1, b: 3}, + doc5: {a: 1, b: 1}, + }); + + // Two equalities: a==1 || b==1. + expectDocs( + await compareQueryAndPipeline( + collection.where( + Filter.or(Filter.where('a', '==', 1), Filter.where('b', '==', 1)) + ) + ), + 'doc1', + 'doc2', + 'doc4', + 'doc5' + ); + + // (a==1 && b==0) || (a==3 && b==2) + expectDocs( + await compareQueryAndPipeline( + collection.where( + Filter.or( + Filter.and(Filter.where('a', '==', 1), Filter.where('b', '==', 0)), + Filter.and(Filter.where('a', '==', 3), Filter.where('b', '==', 2)) + ) + ) + ), + 'doc1', + 'doc3' + ); + + // a==1 && (b==0 || b==3). + expectDocs( + await compareQueryAndPipeline( + collection.where( + Filter.and( + Filter.where('a', '==', 1), + Filter.or(Filter.where('b', '==', 0), Filter.where('b', '==', 3)) + ) + ) + ), + 'doc1', + 'doc4' + ); + + // (a==2 || b==2) && (a==3 || b==3) + expectDocs( + await compareQueryAndPipeline( + collection.where( + Filter.and( + Filter.or(Filter.where('a', '==', 2), Filter.where('b', '==', 2)), + Filter.or(Filter.where('a', '==', 3), Filter.where('b', '==', 3)) + ) + ) + ), + 'doc3' + ); + + // Test with limits without orderBy (the __name__ ordering is the tie breaker). + expectDocs( + await compareQueryAndPipeline( + collection + .where( + Filter.or(Filter.where('a', '==', 2), Filter.where('b', '==', 1)) + ) + .limit(1) + ), + 'doc2' + ); + }); + + // Skip this test if running against production because it results in a 'missing index' error. + // The Firestore Emulator, however, does serve these queries. + (process.env.FIRESTORE_EMULATOR_HOST === undefined ? it.skip : it)( + 'supports OR queries with composite indexes', + async () => { + const collection = await testCollectionWithDocs({ + doc1: {a: 1, b: 0}, + doc2: {a: 2, b: 1}, + doc3: {a: 3, b: 2}, + doc4: {a: 1, b: 3}, + doc5: {a: 1, b: 1}, + }); + + // with one inequality: a>2 || b==1. + expectDocs( + await compareQueryAndPipeline( + collection.where( + Filter.or(Filter.where('a', '>', 2), Filter.where('b', '==', 1)) + ) + ), + 'doc5', + 'doc2', + 'doc3' + ); + + // Test with limits (implicit order by ASC): (a==1) || (b > 0) LIMIT 2 + expectDocs( + await compareQueryAndPipeline( + collection + .where( + Filter.or(Filter.where('a', '==', 1), Filter.where('b', '>', 0)) + ) + .limit(2) + ), + 'doc1', + 'doc2' + ); + + // Test with limits (explicit order by): (a==1) || (b > 0) LIMIT_TO_LAST 2 + // Note: The public query API does not allow implicit ordering when limitToLast is used. + expectDocs( + await compareQueryAndPipeline( + collection + .where( + Filter.or(Filter.where('a', '==', 1), Filter.where('b', '>', 0)) + ) + .limitToLast(2) + .orderBy('b') + ), + 'doc3', + 'doc4' + ); + + // Test with limits (explicit order by ASC): (a==2) || (b == 1) ORDER BY a LIMIT 1 + expectDocs( + await compareQueryAndPipeline( + collection + .where( + Filter.or(Filter.where('a', '==', 2), Filter.where('b', '==', 1)) + ) + .limit(1) + .orderBy('a') + ), + 'doc5' + ); + + // Test with limits (explicit order by DESC): (a==2) || (b == 1) ORDER BY a LIMIT 1 + expectDocs( + await compareQueryAndPipeline( + collection + .where( + Filter.or(Filter.where('a', '==', 2), Filter.where('b', '==', 1)) + ) + .limit(1) + .orderBy('a', 'desc') + ), + 'doc2' + ); + } + ); + + it('supports OR queries on documents with missing fields', async () => { + const collection = await testCollectionWithDocs({ + doc1: {a: 1, b: 0}, + doc2: {b: 1}, + doc3: {a: 3, b: 2}, + doc4: {a: 1, b: 3}, + doc5: {a: 1}, + doc6: {a: 2}, + }); + + // Query: a==1 || b==1 + // There's no explicit nor implicit orderBy. Documents with missing 'a' or missing 'b' should be + // allowed if the document matches at least one disjunction term. + expectDocs( + await compareQueryAndPipeline( + collection.where( + Filter.or(Filter.where('a', '==', 1), Filter.where('b', '==', 1)) + ) + ), + 'doc1', + 'doc2', + 'doc4', + 'doc5' + ); + }); + + // Skip this test if running against production because it results in a 'missing index' error. + // The Firestore Emulator, however, does serve these queries. + (process.env.FIRESTORE_EMULATOR_HOST === undefined ? it.skip : it)( + 'supports OR queries on documents with missing fields', + async () => { + const collection = await testCollectionWithDocs({ + doc1: {a: 1, b: 0}, + doc2: {b: 1}, + doc3: {a: 3, b: 2}, + doc4: {a: 1, b: 3}, + doc5: {a: 1}, + doc6: {a: 2}, + }); + + // Query: a==1 || b==1 order by a. + // doc2 should not be included because it's missing the field 'a', and we have "orderBy a". + expectDocs( + await compareQueryAndPipeline( + collection + .where( + Filter.or(Filter.where('a', '==', 1), Filter.where('b', '==', 1)) + ) + .orderBy('a') + ), + 'doc1', + 'doc4', + 'doc5' + ); + + // Query: a==1 || b==1 order by b. + // doc5 should not be included because it's missing the field 'b', and we have "orderBy b". + expectDocs( + await compareQueryAndPipeline( + collection + .where( + Filter.or(Filter.where('a', '==', 1), Filter.where('b', '==', 1)) + ) + .orderBy('b') + ), + 'doc1', + 'doc2', + 'doc4' + ); + + // Query: a>2 || b==1. + // This query has an implicit 'order by a'. + // doc2 should not be included because it's missing the field 'a'. + expectDocs( + await compareQueryAndPipeline( + collection.where( + Filter.or(Filter.where('a', '>', 2), Filter.where('b', '==', 1)) + ) + ), + 'doc3' + ); + + // Query: a>1 || b==1 order by a order by b. + // doc6 should not be included because it's missing the field 'b'. + // doc2 should not be included because it's missing the field 'a'. + expectDocs( + await compareQueryAndPipeline( + collection + .where( + Filter.or(Filter.where('a', '>', 1), Filter.where('b', '==', 1)) + ) + .orderBy('a') + .orderBy('b') + ), + 'doc3' + ); + } + ); + + it('supports OR queries with in', async () => { + const collection = await testCollectionWithDocs({ + doc1: {a: 1, b: 0}, + doc2: {b: 1}, + doc3: {a: 3, b: 2}, + doc4: {a: 1, b: 3}, + doc5: {a: 1}, + doc6: {a: 2}, + }); + + // Query: a==2 || b in [2, 3] + expectDocs( + await compareQueryAndPipeline( + collection.where( + Filter.or(Filter.where('a', '==', 2), Filter.where('b', 'in', [2, 3])) + ) + ), + 'doc3', + 'doc4', + 'doc6' + ); + }); + + // Skip this test if running against production because it results in a 'missing index' error. + // The Firestore Emulator, however, does serve these queries. + (process.env.FIRESTORE_EMULATOR_HOST === undefined ? it.skip : it)( + 'supports OR queries with not-in', + async () => { + const collection = await testCollectionWithDocs({ + doc1: {a: 1, b: 0}, + doc2: {b: 1}, + doc3: {a: 3, b: 2}, + doc4: {a: 1, b: 3}, + doc5: {a: 1}, + doc6: {a: 2}, + }); + + // a==2 || (b != 2 && b != 3) + // Has implicit "orderBy b" + expectDocs( + await compareQueryAndPipeline( + collection.where( + Filter.or( + Filter.where('a', '==', 2), + Filter.where('b', 'not-in', [2, 3]) + ) + ) + ), + 'doc1', + 'doc2' + ); + } + ); + + it('supports OR queries with array membership', async () => { + const collection = await testCollectionWithDocs({ + doc1: {a: 1, b: [0]}, + doc2: {b: [1]}, + doc3: {a: 3, b: [2, 7]}, + doc4: {a: 1, b: [3, 7]}, + doc5: {a: 1}, + doc6: {a: 2}, + }); + + // Query: a==2 || b array-contains 7 + expectDocs( + await compareQueryAndPipeline( + collection.where( + Filter.or( + Filter.where('a', '==', 2), + Filter.where('b', 'array-contains', 7) + ) + ) + ), + 'doc3', + 'doc4', + 'doc6' + ); + + // a==2 || b array-contains-any [0, 3] + // Has implicit "orderBy b" + expectDocs( + await compareQueryAndPipeline( + collection.where( + Filter.or( + Filter.where('a', '==', 2), + Filter.where('b', 'array-contains-any', [0, 3]) + ) + ) + ), + 'doc1', + 'doc4', + 'doc6' + ); + }); + + describe('watch', () => { + interface ExpectedChange { + type: string; + doc: DocumentSnapshot; + } + + const currentDeferred = new DeferredPromise(); + + const snapshot = (id: string, data: DocumentData) => { + const ref = randomCol.doc(id); + const fields = ref.firestore._serializer!.encodeFields(data); + return randomCol.firestore.snapshot_( + { + name: + 'projects/ignored/databases/(default)/documents/' + + ref._path.relativeName, + fields, + createTime: {seconds: 0, nanos: 0}, + updateTime: {seconds: 0, nanos: 0}, + }, + {seconds: 0, nanos: 0} + ); + }; + + const docChange = ( + type: string, + id: string, + data: DocumentData + ): ExpectedChange => { + return { + type, + doc: snapshot(id, data), + }; + }; + + const added = (id: string, data: DocumentData) => + docChange('added', id, data); + const modified = (id: string, data: DocumentData) => + docChange('modified', id, data); + const removed = (id: string, data: DocumentData) => + docChange('removed', id, data); + + function resetPromise() { + currentDeferred.promise = new Promise((resolve, reject) => { + currentDeferred.resolve = resolve; + currentDeferred.reject = reject; + }); + } + + function waitForSnapshot(): Promise { + return currentDeferred.promise!.then(snapshot => { + resetPromise(); + return snapshot; + }); + } + + function snapshotsEqual( + actual: QuerySnapshot, + expected: {docs: DocumentSnapshot[]; docChanges: ExpectedChange[]} + ) { + let i; + expect(actual.size).to.equal(expected.docs.length); + for (i = 0; i < expected.docs.length && i < actual.size; i++) { + expect(actual.docs[i].ref.id).to.equal(expected.docs[i].ref.id); + expect(actual.docs[i].data()).to.deep.equal(expected.docs[i].data()); + } + const actualDocChanges = actual.docChanges(); + expect(actualDocChanges.length).to.equal(expected.docChanges.length); + for (i = 0; i < expected.docChanges.length; i++) { + expect(actualDocChanges[i].type).to.equal(expected.docChanges[i].type); + expect(actualDocChanges[i].doc.ref.id).to.equal( + expected.docChanges[i].doc.ref.id + ); + expect(actualDocChanges[i].doc.data()).to.deep.equal( + expected.docChanges[i].doc.data() + ); + expect(actualDocChanges[i].doc.readTime).to.exist; + expect(actualDocChanges[i].doc.createTime).to.exist; + expect(actualDocChanges[i].doc.updateTime).to.exist; + } + expect(actual.readTime).to.exist; + } + + beforeEach(() => resetPromise()); + + it('handles changing a doc', () => { + const ref1 = randomCol.doc('doc1'); + const ref2 = randomCol.doc('doc2'); + + const unsubscribe = randomCol.onSnapshot( + snapshot => { + currentDeferred.resolve(snapshot); + }, + err => { + currentDeferred.reject!(err); + } + ); + + return waitForSnapshot() + .then(results => { + snapshotsEqual(results, {docs: [], docChanges: []}); + // Add a result. + return ref1.set({foo: 'a'}); + }) + .then(() => { + return waitForSnapshot(); + }) + .then(results => { + snapshotsEqual(results, { + docs: [snapshot('doc1', {foo: 'a'})], + docChanges: [added('doc1', {foo: 'a'})], + }); + // Add another result. + return ref2.set({foo: 'b'}); + }) + .then(() => { + return waitForSnapshot(); + }) + .then(results => { + snapshotsEqual(results, { + docs: [snapshot('doc1', {foo: 'a'}), snapshot('doc2', {foo: 'b'})], + docChanges: [added('doc2', {foo: 'b'})], + }); + // Change a result. + return ref2.set({bar: 'c'}); + }) + .then(() => { + return waitForSnapshot(); + }) + .then(results => { + snapshotsEqual(results, { + docs: [snapshot('doc1', {foo: 'a'}), snapshot('doc2', {bar: 'c'})], + docChanges: [modified('doc2', {bar: 'c'})], + }); + unsubscribe(); + }); + }); + + it("handles changing a doc so it doesn't match", () => { + const ref1 = randomCol.doc('doc1'); + const ref2 = randomCol.doc('doc2'); + + const query = randomCol.where('included', '==', 'yes'); + const unsubscribe = query.onSnapshot( + snapshot => { + currentDeferred.resolve(snapshot); + }, + err => { + currentDeferred.reject(err); + } + ); + + return waitForSnapshot() + .then(results => { + snapshotsEqual(results, {docs: [], docChanges: []}); + // Add a result. + return ref1.set({included: 'yes'}); + }) + .then(() => { + return waitForSnapshot(); + }) + .then(results => { + snapshotsEqual(results, { + docs: [snapshot('doc1', {included: 'yes'})], + docChanges: [added('doc1', {included: 'yes'})], + }); + // Add another result. + return ref2.set({included: 'yes'}); + }) + .then(() => { + return waitForSnapshot(); + }) + .then(results => { + snapshotsEqual(results, { + docs: [ + snapshot('doc1', {included: 'yes'}), + snapshot('doc2', {included: 'yes'}), + ], + docChanges: [added('doc2', {included: 'yes'})], + }); + // Change a result. + return ref2.set({included: 'no'}); + }) + .then(() => { + return waitForSnapshot(); + }) + .then(results => { + snapshotsEqual(results, { + docs: [snapshot('doc1', {included: 'yes'})], + docChanges: [removed('doc2', {included: 'yes'})], + }); + unsubscribe(); + }); + }); + + it('handles deleting a doc', () => { + const ref1 = randomCol.doc('doc1'); + const ref2 = randomCol.doc('doc2'); + + const unsubscribe = randomCol.onSnapshot( + snapshot => { + currentDeferred.resolve(snapshot); + }, + err => { + currentDeferred.reject(err); + } + ); + + return waitForSnapshot() + .then(results => { + snapshotsEqual(results, {docs: [], docChanges: []}); + // Add a result. + return ref1.set({included: 'yes'}); + }) + .then(() => { + return waitForSnapshot(); + }) + .then(results => { + snapshotsEqual(results, { + docs: [snapshot('doc1', {included: 'yes'})], + docChanges: [added('doc1', {included: 'yes'})], + }); + // Add another result. + return ref2.set({included: 'yes'}); + }) + .then(() => { + return waitForSnapshot(); + }) + .then(results => { + snapshotsEqual(results, { + docs: [ + snapshot('doc1', {included: 'yes'}), + snapshot('doc2', {included: 'yes'}), + ], + docChanges: [added('doc2', {included: 'yes'})], + }); + // Delete a result. + return ref2.delete(); + }) + .then(() => { + return waitForSnapshot(); + }) + .then(results => { + snapshotsEqual(results, { + docs: [snapshot('doc1', {included: 'yes'})], + docChanges: [removed('doc2', {included: 'yes'})], + }); + unsubscribe(); + }); + }); + + it('orders limitToLast() correctly', async () => { + const ref1 = randomCol.doc('doc1'); + const ref2 = randomCol.doc('doc2'); + const ref3 = randomCol.doc('doc3'); + + await ref1.set({doc: 1}); + await ref2.set({doc: 2}); + await ref3.set({doc: 3}); + + const unsubscribe = randomCol + .orderBy('doc') + .limitToLast(2) + .onSnapshot(snapshot => currentDeferred.resolve(snapshot)); + + const results = await waitForSnapshot(); + snapshotsEqual(results, { + docs: [snapshot('doc2', {doc: 2}), snapshot('doc3', {doc: 3})], + docChanges: [added('doc2', {doc: 2}), added('doc3', {doc: 3})], + }); + + unsubscribe(); + }); + + it('SDK orders vector field same way as backend', async () => { + // We validate that the SDK orders the vector field the same way as the backend + // by comparing the sort order of vector fields from a Query.get() and + // Query.onSnapshot(). Query.onSnapshot() will return sort order of the SDK, + // and Query.get() will return sort order of the backend. + + // Test data in the order that we expect the backend to sort it. + const docsInOrder = [ + {embedding: [1, 2, 3, 4, 5, 6]}, + {embedding: [100]}, + {embedding: FieldValue.vector([Number.NEGATIVE_INFINITY])}, + {embedding: FieldValue.vector([-100])}, + {embedding: FieldValue.vector([100])}, + {embedding: FieldValue.vector([Number.POSITIVE_INFINITY])}, + {embedding: FieldValue.vector([1, 2])}, + {embedding: FieldValue.vector([2, 2])}, + {embedding: FieldValue.vector([1, 2, 3])}, + {embedding: FieldValue.vector([1, 2, 3, 4])}, + {embedding: FieldValue.vector([1, 2, 3, 4, 5])}, + {embedding: FieldValue.vector([1, 2, 100, 4, 4])}, + {embedding: FieldValue.vector([100, 2, 3, 4, 5])}, + {embedding: {HELLO: 'WORLD'}}, + {embedding: {hello: 'world'}}, + ]; + + const expectedSnapshots = []; + const expectedChanges = []; + + for (let i = 0; i < docsInOrder.length; i++) { + const dr = await randomCol.add(docsInOrder[i]); + expectedSnapshots.push(snapshot(dr.id, docsInOrder[i])); + expectedChanges.push(added(dr.id, docsInOrder[i])); + } + + const orderedQuery = randomCol.orderBy('embedding'); + + const unsubscribe = orderedQuery.onSnapshot( + snapshot => { + currentDeferred.resolve(snapshot); + }, + err => { + currentDeferred.reject!(err); + } + ); + + const watchSnapshot = await waitForSnapshot(); + unsubscribe(); + + const getSnapshot = await orderedQuery.get(); + + // Compare the snapshot (including sort order) of a snapshot + // from Query.onSnapshot() to an actual snapshot from Query.get() + snapshotsEqual(watchSnapshot, { + docs: getSnapshot.docs, + docChanges: getSnapshot.docChanges(), + }); + + // Compare the snapshot (including sort order) of a snapshot + // from Query.onSnapshot() to the expected sort order from + // the backend. + snapshotsEqual(watchSnapshot, { + docs: expectedSnapshots, + docChanges: expectedChanges, + }); + }); + }); + + (process.env.FIRESTORE_EMULATOR_HOST === undefined + ? describe.skip + : describe.only)('multiple inequality', () => { + it('supports multiple inequality queries', async () => { + const collection = await testCollectionWithDocs({ + doc1: {key: 'a', sort: 0, v: 0}, + doc2: {key: 'b', sort: 3, v: 1}, + doc3: {key: 'c', sort: 1, v: 3}, + doc4: {key: 'd', sort: 2, v: 2}, + }); + + // Multiple inequality fields + let results = await compareQueryAndPipeline( + collection + .where('key', '!=', 'a') + .where('sort', '<=', 2) + .where('v', '>', 2) + ); + expectDocs(results, 'doc3'); + + // Duplicate inequality fields + results = await compareQueryAndPipeline( + collection + .where('key', '!=', 'a') + .where('sort', '<=', 2) + .where('sort', '>', 1) + ); + expectDocs(results, 'doc4'); + + // With multiple IN + results = await compareQueryAndPipeline( + collection + .where('key', '>=', 'a') + .where('sort', '<=', 2) + .where('v', 'in', [2, 3, 4]) + .where('sort', 'in', [2, 3]) + ); + expectDocs(results, 'doc4'); + + // With NOT-IN + results = await compareQueryAndPipeline( + collection + .where('key', '>=', 'a') + .where('sort', '<=', 2) + .where('v', 'not-in', [2, 4, 5]) + ); + expectDocs(results, 'doc1', 'doc3'); + + // With orderby + results = await compareQueryAndPipeline( + collection + .where('key', '>=', 'a') + .where('sort', '<=', 2) + .orderBy('v', 'desc') + ); + expectDocs(results, 'doc3', 'doc4', 'doc1'); + + // With limit + results = await compareQueryAndPipeline( + collection + .where('key', '>=', 'a') + .where('sort', '<=', 2) + .orderBy('v', 'desc') + .limit(2) + ); + expectDocs(results, 'doc3', 'doc4'); + + // With limitToLast + results = await compareQueryAndPipeline( + collection + .where('key', '>=', 'a') + .where('sort', '<=', 2) + .orderBy('v', 'desc') + .limitToLast(2) + ); + expectDocs(results, 'doc4', 'doc1'); + }); + + it('can use on special values', async () => { + const collection = await testCollectionWithDocs({ + doc1: {key: 'a', sort: 0, v: 0}, + doc2: {key: 'b', sort: NaN, v: 1}, + doc3: {key: 'c', sort: null, v: 3}, + doc4: {key: 'd', v: 0}, + doc5: {key: 'e', sort: 1}, + doc6: {key: 'f', sort: 1, v: 1}, + }); + + let results = await compareQueryAndPipeline( + collection.where('key', '!=', 'a').where('sort', '<=', 2) + ); + expectDocs(results, 'doc5', 'doc6'); + + results = await compareQueryAndPipeline( + collection + .where('key', '!=', 'a') + .where('sort', '<=', 2) + .where('v', '<=', 1) + ); + expectDocs(results, 'doc6'); + }); + + it('can use with array membership', async () => { + const collection = await testCollectionWithDocs({ + doc1: {key: 'a', sort: 0, v: [0]}, + doc2: {key: 'b', sort: 1, v: [0, 1, 3]}, + doc3: {key: 'c', sort: 1, v: []}, + doc4: {key: 'd', sort: 2, v: [1]}, + doc5: {key: 'e', sort: 3, v: [2, 4]}, + doc6: {key: 'f', sort: 4, v: [NaN]}, + doc7: {key: 'g', sort: 4, v: [null]}, + }); + + let results = await compareQueryAndPipeline( + collection + .where('key', '!=', 'a') + .where('sort', '>=', 1) + .where('v', 'array-contains', 0) + ); + expectDocs(results, 'doc2'); + + results = await compareQueryAndPipeline( + collection + .where('key', '!=', 'a') + .where('sort', '>=', 1) + .where('v', 'array-contains-any', [0, 1]) + ); + expectDocs(results, 'doc2', 'doc4'); + }); + + // Use cursor in following test cases to add implicit order by fields in the sdk and compare the + // result with the query fields normalized in the server. + it('can use with nested field', async () => { + // eslint-disable-next-line @typescript-eslint/no-explicit-any + const testData = (n?: number): any => { + n = n || 1; + return { + name: 'room ' + n, + metadata: { + createdAt: n, + }, + field: 'field ' + n, + 'field.dot': n, + 'field\\slash': n, + }; + }; + + const collection = await testCollectionWithDocs({ + doc1: testData(400), + doc2: testData(200), + doc3: testData(100), + doc4: testData(300), + }); + + // ordered by: name asc, metadata.createdAt asc, __name__ asc + let query = collection + .where('metadata.createdAt', '<=', 500) + .where('metadata.createdAt', '>', 100) + .where('name', '!=', 'room 200') + .orderBy('name'); + let docSnap = await collection.doc('doc4').get(); + let queryWithCursor = query.startAt(docSnap); + expectDocs(await compareQueryAndPipeline(query), 'doc4', 'doc1'); + expectDocs(await queryWithCursor.get(), 'doc4', 'doc1'); + + // ordered by: name desc, field desc, field.dot desc, field\\slash desc, __name__ desc + query = collection + .where('field', '>=', 'field 100') + .where(new FieldPath('field.dot'), '!=', 300) + .where('field\\slash', '<', 400) + .orderBy('name', 'desc'); + docSnap = await collection.doc('doc2').get(); + queryWithCursor = query.startAt(docSnap); + expectDocs(await compareQueryAndPipeline(query), 'doc2', 'doc3'); + expectDocs(await queryWithCursor.get(), 'doc2', 'doc3'); + }); + + it('can use with nested composite filters', async () => { + const collection = await testCollectionWithDocs({ + doc1: {key: 'a', sort: 0, v: 5}, + doc2: {key: 'aa', sort: 4, v: 4}, + doc3: {key: 'c', sort: 3, v: 3}, + doc4: {key: 'b', sort: 2, v: 2}, + doc5: {key: 'b', sort: 2, v: 1}, + doc6: {key: 'b', sort: 0, v: 0}, + }); + + // Implicitly ordered by: 'key' asc, 'sort' asc, 'v' asc, __name__ asc + let query = collection.where( + Filter.or( + Filter.and( + Filter.where('key', '==', 'b'), + Filter.where('sort', '<=', 2) + ), + Filter.and(Filter.where('key', '!=', 'b'), Filter.where('v', '>', 4)) + ) + ); + let docSnap = await collection.doc('doc1').get(); + let queryWithCursor = query.startAt(docSnap); + expectDocs( + await compareQueryAndPipeline(query), + 'doc1', + 'doc6', + 'doc5', + 'doc4' + ); + expectDocs(await queryWithCursor.get(), 'doc1', 'doc6', 'doc5', 'doc4'); + + // Ordered by: 'sort' desc, 'key' asc, 'v' asc, __name__ asc + query = collection + .where( + Filter.or( + Filter.and( + Filter.where('key', '==', 'b'), + Filter.where('sort', '<=', 2) + ), + Filter.and( + Filter.where('key', '!=', 'b'), + Filter.where('v', '>', 4) + ) + ) + ) + .orderBy('sort', 'desc') + .orderBy('key'); + docSnap = await collection.doc('doc5').get(); + queryWithCursor = query.startAt(docSnap); + expectDocs( + await compareQueryAndPipeline(query), + 'doc5', + 'doc4', + 'doc1', + 'doc6' + ); + expectDocs(await queryWithCursor.get(), 'doc5', 'doc4', 'doc1', 'doc6'); + + // Implicitly ordered by: 'key' asc, 'sort' asc, 'v' asc, __name__ asc + query = collection.where( + Filter.and( + Filter.or( + Filter.and( + Filter.where('key', '==', 'b'), + Filter.where('sort', '<=', 4) + ), + Filter.and( + Filter.where('key', '!=', 'b'), + Filter.where('v', '>=', 4) + ) + ), + Filter.or( + Filter.and( + Filter.where('key', '>', 'b'), + Filter.where('sort', '>=', 1) + ), + Filter.and(Filter.where('key', '<', 'b'), Filter.where('v', '>', 0)) + ) + ) + ); + docSnap = await collection.doc('doc1').get(); + queryWithCursor = query.startAt(docSnap); + expectDocs(await compareQueryAndPipeline(query), 'doc1', 'doc2'); + expectDocs(await queryWithCursor.get(), 'doc1', 'doc2'); + }); + + it('inequality fields will be implicitly ordered lexicographically by the server', async () => { + const collection = await testCollectionWithDocs({ + doc1: {key: 'a', sort: 0, v: 5}, + doc2: {key: 'aa', sort: 4, v: 4}, + doc3: {key: 'b', sort: 3, v: 3}, + doc4: {key: 'b', sort: 2, v: 2}, + doc5: {key: 'b', sort: 2, v: 1}, + doc6: {key: 'b', sort: 0, v: 0}, + }); + + const docSnap = await collection.doc('doc2').get(); + + // Implicitly ordered by: 'key' asc, 'sort' asc, __name__ asc + let query = collection + .where('key', '!=', 'a') + .where('sort', '>', 1) + .where('v', 'in', [1, 2, 3, 4]); + let queryWithCursor = query.startAt(docSnap); + expectDocs( + await compareQueryAndPipeline(query), + 'doc2', + 'doc4', + 'doc5', + 'doc3' + ); + expectDocs(await queryWithCursor.get(), 'doc2', 'doc4', 'doc5', 'doc3'); + + // Changing filters order will not effect implicit order. + // Implicitly ordered by: 'key' asc, 'sort' asc, __name__ asc + query = collection + .where('sort', '>', 1) + .where('key', '!=', 'a') + .where('v', 'in', [1, 2, 3, 4]); + queryWithCursor = query.startAt(docSnap); + expectDocs( + await compareQueryAndPipeline(query), + 'doc2', + 'doc4', + 'doc5', + 'doc3' + ); + expectDocs(await queryWithCursor.get(), 'doc2', 'doc4', 'doc5', 'doc3'); + }); + + it('can use multiple explicit order by field', async () => { + const collection = await testCollectionWithDocs({ + doc1: {key: 'a', sort: 5, v: 0}, + doc2: {key: 'aa', sort: 4, v: 0}, + doc3: {key: 'b', sort: 3, v: 1}, + doc4: {key: 'b', sort: 2, v: 1}, + doc5: {key: 'bb', sort: 1, v: 1}, + doc6: {key: 'c', sort: 0, v: 2}, + }); + + let docSnap = await collection.doc('doc2').get(); + + // Ordered by: 'v' asc, 'key' asc, 'sort' asc, __name__ asc + let query = collection + .where('key', '>', 'a') + .where('sort', '>=', 1) + .orderBy('v'); + let queryWithCursor = query.startAt(docSnap); + expectDocs( + await compareQueryAndPipeline(query), + 'doc2', + 'doc4', + 'doc3', + 'doc5' + ); + expectDocs(await queryWithCursor.get(), 'doc2', 'doc4', 'doc3', 'doc5'); + + // Ordered by: 'v asc, 'sort' asc, 'key' asc, __name__ asc + query = collection + .where('key', '>', 'a') + .where('sort', '>=', 1) + .orderBy('v') + .orderBy('sort'); + queryWithCursor = query.startAt(docSnap); + expectDocs( + await compareQueryAndPipeline(query), + 'doc2', + 'doc5', + 'doc4', + 'doc3' + ); + expectDocs(await queryWithCursor.get(), 'doc2', 'doc5', 'doc4', 'doc3'); + + docSnap = await collection.doc('doc5').get(); + + // Implicit order by matches the direction of last explicit order by. + // Ordered by: 'v' desc, 'key' desc, 'sort' desc, __name__ desc + query = collection + .where('key', '>', 'a') + .where('sort', '>=', 1) + .orderBy('v', 'desc'); + queryWithCursor = query.startAt(docSnap); + expectDocs( + await compareQueryAndPipeline(query), + 'doc5', + 'doc3', + 'doc4', + 'doc2' + ); + expectDocs(await queryWithCursor.get(), 'doc5', 'doc3', 'doc4', 'doc2'); + + // Ordered by: 'v desc, 'sort' asc, 'key' asc, __name__ asc + query = collection + .where('key', '>', 'a') + .where('sort', '>=', 1) + .orderBy('v', 'desc') + .orderBy('sort'); + queryWithCursor = query.startAt(docSnap); + expectDocs( + await compareQueryAndPipeline(query), + 'doc5', + 'doc4', + 'doc3', + 'doc2' + ); + expectDocs(await queryWithCursor.get(), 'doc5', 'doc4', 'doc3', 'doc2'); + }); + + it('can use in aggregate query', async () => { + const collection = await testCollectionWithDocs({ + doc1: {key: 'a', sort: 5, v: 0}, + doc2: {key: 'aa', sort: 4, v: 0}, + doc3: {key: 'b', sort: 3, v: 1}, + doc4: {key: 'b', sort: 2, v: 1}, + doc5: {key: 'bb', sort: 1, v: 1}, + }); + + const results = await collection + .where('key', '>', 'a') + .where('sort', '>=', 1) + .orderBy('v') + .count() + .get(); + expect(results.data().count).to.be.equal(4); + //TODO(MIEQ): Add sum and average when they are public. + }); + + it('can use document ID im multiple inequality query', async () => { + const collection = await testCollectionWithDocs({ + doc1: {key: 'a', sort: 5}, + doc2: {key: 'aa', sort: 4}, + doc3: {key: 'b', sort: 3}, + doc4: {key: 'b', sort: 2}, + doc5: {key: 'bb', sort: 1}, + }); + + const docSnap = await collection.doc('doc2').get(); + + // Document Key in inequality field will implicitly ordered to the last. + // Implicitly ordered by: 'key' asc, 'sort' asc, __name__ asc + let query = collection + .where('sort', '>=', 1) + .where('key', '!=', 'a') + .where(FieldPath.documentId(), '<', 'doc5'); + let queryWithCursor = query.startAt(docSnap); + expectDocs(await compareQueryAndPipeline(query), 'doc2', 'doc4', 'doc3'); + expectDocs(await queryWithCursor.get(), 'doc2', 'doc4', 'doc3'); + + // Changing filters order will not effect implicit order. + // Implicitly ordered by: 'key' asc, 'sort' asc, __name__ asc + query = collection + .where(FieldPath.documentId(), '<', 'doc5') + .where('sort', '>=', 1) + .where('key', '!=', 'a'); + queryWithCursor = query.startAt(docSnap); + expectDocs(await compareQueryAndPipeline(query), 'doc2', 'doc4', 'doc3'); + expectDocs(await queryWithCursor.get(), 'doc2', 'doc4', 'doc3'); + + // Ordered by: 'sort' desc,'key' desc, __name__ desc + query = collection + .where(FieldPath.documentId(), '<', 'doc5') + .where('sort', '>=', 1) + .where('key', '!=', 'a') + .orderBy('sort', 'desc'); + queryWithCursor = query.startAt(docSnap); + expectDocs(await compareQueryAndPipeline(query), 'doc2', 'doc3', 'doc4'); + expectDocs(await queryWithCursor.get(), 'doc2', 'doc3', 'doc4'); + }); + }); +}); From 9ad261455a4b53d7dd5ab997ed8ce9baa8776afd Mon Sep 17 00:00:00 2001 From: Wu-Hui Date: Tue, 30 Jul 2024 11:47:22 -0400 Subject: [PATCH 04/60] pipeline impl --- dev/src/expression.ts | 898 ++++++++++++++++++++++----- dev/src/pipeline-util.ts | 20 +- dev/src/pipeline.ts | 343 +++++++++- dev/src/reference/aggregate-query.ts | 19 +- dev/src/reference/query.ts | 25 +- dev/src/reference/vector-query.ts | 2 +- dev/src/stage.ts | 19 +- dev/src/util.ts | 24 + dev/system-test/pipeline.ts | 660 +++++++++++++++++++- dev/system-test/query.ts | 59 +- 10 files changed, 1809 insertions(+), 260 deletions(-) diff --git a/dev/src/expression.ts b/dev/src/expression.ts index e2642407b..32ab6f6f1 100644 --- a/dev/src/expression.ts +++ b/dev/src/expression.ts @@ -21,77 +21,119 @@ export interface FilterCondition { } export interface Accumulator { - toField(fieldName: string): AggregateTarget; -} - -export class AggregateTarget implements Selectable { - constructor( - public field: Field, - public accumulator: Accumulator & Expr - ) {} - - selectable = true as const; + accumulator: true; } +export type AccumulatorTarget = ExprWithAlias; export type FilterExpr = Expr & FilterCondition; export type SelectableExpr = Expr & Selectable; -export type ExprType = 'Field' | 'Constant' | 'Function' | 'ListOfExprs'; +export type ExprType = + | 'Field' + | 'Constant' + | 'Function' + | 'ListOfExprs' + | 'ExprWithAlias'; export abstract class Expr { - equal(other: Expr): Equal; - equal(other: any): Equal; - equal(other: any): Equal { + add(other: Expr): Add; + add(other: any): Add; + add(other: any): Add { + if (other instanceof Expr) { + return new Add(this, other); + } + return new Add(this, Constant.of(other)); + } + + subtract(other: Expr): Subtract; + subtract(other: any): Subtract; + subtract(other: any): Subtract { + if (other instanceof Expr) { + return new Subtract(this, other); + } + return new Subtract(this, Constant.of(other)); + } + + multiply(other: Expr): Multiply; + multiply(other: any): Multiply; + multiply(other: any): Multiply { + if (other instanceof Expr) { + return new Multiply(this, other); + } + return new Multiply(this, Constant.of(other)); + } + + divide(other: Expr): Divide; + divide(other: any): Divide; + divide(other: any): Divide { + if (other instanceof Expr) { + return new Divide(this, other); + } + return new Divide(this, Constant.of(other)); + } + + eq(other: Expr): Eq; + eq(other: any): Eq; + eq(other: any): Eq { if (other instanceof Expr) { - return new Equal(this, other); + return new Eq(this, other); } - return new Equal(this, Constant.of(other)); + return new Eq(this, Constant.of(other)); } - notEqual(other: Expr): NotEqual; - notEqual(other: any): NotEqual; - notEqual(other: any): NotEqual { + neq(other: Expr): Neq; + neq(other: any): Neq; + neq(other: any): Neq { if (other instanceof Expr) { - return new NotEqual(this, other); + return new Neq(this, other); } - return new NotEqual(this, Constant.of(other)); + return new Neq(this, Constant.of(other)); } - lessThan(other: Expr): LessThan; - lessThan(other: any): LessThan; - lessThan(other: any): LessThan { + lt(other: Expr): Lt; + lt(other: any): Lt; + lt(other: any): Lt { if (other instanceof Expr) { - return new LessThan(this, other); + return new Lt(this, other); } - return new LessThan(this, Constant.of(other)); + return new Lt(this, Constant.of(other)); } - lessThanOrEqual(other: Expr): LessThanOrEqual; - lessThanOrEqual(other: any): LessThanOrEqual; - lessThanOrEqual(other: any): LessThanOrEqual { + lte(other: Expr): Lte; + lte(other: any): Lte; + lte(other: any): Lte { if (other instanceof Expr) { - return new LessThanOrEqual(this, other); + return new Lte(this, other); } - return new LessThanOrEqual(this, Constant.of(other)); + return new Lte(this, Constant.of(other)); } - greaterThan(other: Expr): GreaterThan; - greaterThan(other: any): GreaterThan; - greaterThan(other: any): GreaterThan { + gt(other: Expr): Gt; + gt(other: any): Gt; + gt(other: any): Gt { if (other instanceof Expr) { - return new GreaterThan(this, other); + return new Gt(this, other); } - return new GreaterThan(this, Constant.of(other)); + return new Gt(this, Constant.of(other)); } - greaterThanOrEqual(other: Expr): GreaterThanOrEqual; - greaterThanOrEqual(other: any): GreaterThanOrEqual; - greaterThanOrEqual(other: any): GreaterThanOrEqual { + gte(other: Expr): Gte; + gte(other: any): Gte; + gte(other: any): Gte { if (other instanceof Expr) { - return new GreaterThanOrEqual(this, other); + return new Gte(this, other); } - return new GreaterThanOrEqual(this, Constant.of(other)); + return new Gte(this, Constant.of(other)); + } + + arrayConcat(...values: Expr[]): ArrayConcat; + arrayConcat(...values: any[]): ArrayConcat; + arrayConcat(...values: any[]): ArrayConcat { + const exprValues = values.map(value => + value instanceof Expr ? value : Constant.of(value) + ); + return new ArrayConcat(this, exprValues); } arrayContains(element: Expr): ArrayContains; @@ -103,15 +145,36 @@ export abstract class Expr { return new ArrayContains(this, Constant.of(element)); } - arrayContainsAny(values: Expr[]): ArrayContainsAny; - arrayContainsAny(values: any[]): ArrayContainsAny; - arrayContainsAny(values: any[]): ArrayContainsAny { + arrayContainsAll(...values: Expr[]): ArrayContainsAll; + arrayContainsAll(...values: any[]): ArrayContainsAll; + arrayContainsAll(...values: any[]): ArrayContainsAll { + const exprValues = values.map(value => + value instanceof Expr ? value : Constant.of(value) + ); + return new ArrayContainsAll(this, exprValues); + } + + arrayContainsAny(...values: Expr[]): ArrayContainsAny; + arrayContainsAny(...values: any[]): ArrayContainsAny; + arrayContainsAny(...values: any[]): ArrayContainsAny { const exprValues = values.map(value => value instanceof Expr ? value : Constant.of(value) ); return new ArrayContainsAny(this, exprValues); } + arrayFilter(filter: FilterExpr): ArrayFilter { + return new ArrayFilter(this, filter); + } + + arrayLength(): ArrayLength { + return new ArrayLength(this); + } + + arrayTransform(transform: Function): ArrayTransform { + return new ArrayTransform(this, transform); + } + in(...others: Expr[]): In; in(...others: any[]): In; in(...others: any[]): In { @@ -133,6 +196,76 @@ export abstract class Expr { return new Exists(this); } + length(): Length { + return new Length(this); + } + + like(pattern: string): Like; + like(pattern: Expr): Like; + like(stringOrExpr: string | Expr): Like { + if (stringOrExpr instanceof Expr) { + return new Like(this, stringOrExpr); + } + return new Like(this, Constant.of(stringOrExpr)); + } + + regexContains(pattern: string): RegexContains; + regexContains(pattern: Expr): RegexContains; + regexContains(stringOrExpr: string | Expr): RegexContains { + if (stringOrExpr instanceof Expr) { + return new RegexContains(this, stringOrExpr); + } + return new RegexContains(this, Constant.of(stringOrExpr)); + } + + regexMatch(pattern: string): RegexMatch; + regexMatch(pattern: Expr): RegexMatch; + regexMatch(stringOrExpr: string | Expr): RegexMatch { + if (stringOrExpr instanceof Expr) { + return new RegexMatch(this, stringOrExpr); + } + return new RegexMatch(this, Constant.of(stringOrExpr)); + } + + startsWith(prefix: string): StartsWith; + startsWith(prefix: Expr): StartsWith; + startsWith(stringOrExpr: string | Expr): StartsWith { + if (stringOrExpr instanceof Expr) { + return new StartsWith(this, stringOrExpr); + } + return new StartsWith(this, Constant.of(stringOrExpr)); + } + + endsWith(suffix: string): EndsWith; + endsWith(suffix: Expr): EndsWith; + endsWith(stringOrExpr: string | Expr): EndsWith { + if (stringOrExpr instanceof Expr) { + return new EndsWith(this, stringOrExpr); + } + return new EndsWith(this, Constant.of(stringOrExpr)); + } + + toLowercase(): ToLowercase { + return new ToLowercase(this); + } + + toUppercase(): ToUppercase { + return new ToUppercase(this); + } + + trim(): Trim { + return new Trim(this); + } + + strConcat(...elements: (string | Expr)[]): StrConcat { + const exprs = elements.map(e => (e instanceof Expr ? e : Constant.of(e))); + return new StrConcat(this, exprs); + } + + mapGet(subfield: string): MapGet { + return new MapGet(this, subfield); + } + count(): Count { return new Count(this, false); } @@ -186,9 +319,37 @@ export abstract class Expr { } } + ascending(): Ordering { + return Ordering.ascending(this); + } + + descending(): Ordering { + return Ordering.descending(this); + } + + as(name: string): ExprWithAlias { + return new ExprWithAlias(this, name); + } + abstract _toProto(serializer: Serializer): api.IValue; } +export class ExprWithAlias extends Expr implements Selectable { + exprType: ExprType = 'ExprWithAlias'; + selectable = true as const; + + constructor( + public expr: T, + public alias: string + ) { + super(); + } + + _toProto(serializer: Serializer): api.IValue { + throw new Error('ExprWithAlias should not be serialized directly.'); + } +} + class ListOfExprs extends Expr { exprType: ExprType = 'ListOfExprs'; constructor(private exprs: Expr[]) { @@ -344,7 +505,43 @@ export class Function extends Expr { } } -export class Equal extends Function implements FilterCondition { +export class Add extends Function { + constructor( + private left: Expr, + private right: Expr + ) { + super('add', [left, right]); + } +} + +export class Subtract extends Function { + constructor( + private left: Expr, + private right: Expr + ) { + super('subtract', [left, right]); + } +} + +export class Multiply extends Function { + constructor( + private left: Expr, + private right: Expr + ) { + super('multiply', [left, right]); + } +} + +export class Divide extends Function { + constructor( + private left: Expr, + private right: Expr + ) { + super('divide', [left, right]); + } +} + +export class Eq extends Function implements FilterCondition { constructor( private left: Expr, private right: Expr @@ -354,7 +551,7 @@ export class Equal extends Function implements FilterCondition { filterable = true as const; } -class NotEqual extends Function implements FilterCondition { +class Neq extends Function implements FilterCondition { constructor( private left: Expr, private right: Expr @@ -364,7 +561,7 @@ class NotEqual extends Function implements FilterCondition { filterable = true as const; } -class LessThan extends Function implements FilterCondition { +class Lt extends Function implements FilterCondition { constructor( private left: Expr, private right: Expr @@ -374,7 +571,7 @@ class LessThan extends Function implements FilterCondition { filterable = true as const; } -class LessThanOrEqual extends Function implements FilterCondition { +class Lte extends Function implements FilterCondition { constructor( private left: Expr, private right: Expr @@ -384,7 +581,7 @@ class LessThanOrEqual extends Function implements FilterCondition { filterable = true as const; } -class GreaterThan extends Function implements FilterCondition { +class Gt extends Function implements FilterCondition { constructor( private left: Expr, private right: Expr @@ -394,7 +591,7 @@ class GreaterThan extends Function implements FilterCondition { filterable = true as const; } -class GreaterThanOrEqual extends Function implements FilterCondition { +class Gte extends Function implements FilterCondition { constructor( private left: Expr, private right: Expr @@ -404,6 +601,15 @@ class GreaterThanOrEqual extends Function implements FilterCondition { filterable = true as const; } +class ArrayConcat extends Function { + constructor( + private array: Expr, + private elements: Expr[] + ) { + super('array_concat', [array, ...elements]); + } +} + class ArrayContains extends Function implements FilterCondition { constructor( private array: Expr, @@ -414,6 +620,16 @@ class ArrayContains extends Function implements FilterCondition { filterable = true as const; } +class ArrayContainsAll extends Function implements FilterCondition { + constructor( + private array: Expr, + private values: Expr[] + ) { + super('array_contains_all', [array, new ListOfExprs(values)]); + } + filterable = true as const; +} + class ArrayContainsAny extends Function implements FilterCondition { constructor( private array: Expr, @@ -424,6 +640,36 @@ class ArrayContainsAny extends Function implements FilterCondition { filterable = true as const; } +class ArrayFilter extends Function { + constructor( + private array: Expr, + private filter: FilterExpr + ) { + super('array_filter', [array, filter]); + } +} + +class ArrayLength extends Function { + constructor(private array: Expr) { + super('array_length', [array]); + } +} + +class ArrayTransform extends Function { + constructor( + private array: Expr, + private transform: Function + ) { + super('array_transform', [array, transform]); + } +} + +class ArrayElement extends Function { + constructor() { + super('array_element', []); + } +} + class In extends Function implements FilterCondition { constructor( private left: Expr, @@ -477,65 +723,161 @@ class Or extends Function implements FilterCondition { filterable = true as const; } +class Xor extends Function implements FilterCondition { + constructor(private conditions: FilterExpr[]) { + super('xor', conditions); + } + filterable = true as const; +} + +class If extends Function implements FilterCondition { + constructor( + private condition: FilterExpr, + private thenExpr: Expr, + private elseExpr: Expr + ) { + super('if', [condition, thenExpr, elseExpr]); + } + filterable = true as const; +} + +class Length extends Function { + constructor(private expr: Expr) { + super('length', [expr]); + } +} + +class Like extends Function implements FilterCondition { + constructor( + private expr: Expr, + private pattern: Expr + ) { + super('like', [expr, pattern]); + } + filterable = true as const; +} + +class RegexContains extends Function implements FilterCondition { + constructor( + private expr: Expr, + private pattern: Expr + ) { + super('regex_contains', [expr, pattern]); + } + filterable = true as const; +} + +class RegexMatch extends Function implements FilterCondition { + constructor( + private expr: Expr, + private pattern: Expr + ) { + super('regex_match', [expr, pattern]); + } + filterable = true as const; +} + +class StartsWith extends Function implements FilterCondition { + constructor( + private expr: Expr, + private prefix: Expr + ) { + super('starts_with', [expr, prefix]); + } + filterable = true as const; +} + +class EndsWith extends Function implements FilterCondition { + constructor( + private expr: Expr, + private suffix: Expr + ) { + super('ends_with', [expr, suffix]); + } + filterable = true as const; +} + +class ToLowercase extends Function { + constructor(private expr: Expr) { + super('to_lowercase', [expr]); + } +} + +class ToUppercase extends Function { + constructor(private expr: Expr) { + super('to_uppercase', [expr]); + } +} + +class Trim extends Function { + constructor(private expr: Expr) { + super('trim', [expr]); + } +} + +class StrConcat extends Function { + constructor( + private first: Expr, + private rest: Expr[] + ) { + super('str_concat', [first, ...rest]); + } +} + +class MapGet extends Function { + constructor(map: Expr, name: string) { + super('map_get', [map, Constant.of(name)]); + } +} + class Count extends Function implements Accumulator { + accumulator = true as const; constructor( private value: Expr | undefined, private distinct: boolean ) { super('count', value === undefined ? [] : [value]); } - - toField(fieldName: string): AggregateTarget { - return new AggregateTarget(Field.of(fieldName), this); - } } class Sum extends Function implements Accumulator { + accumulator = true as const; constructor( private value: Expr, private distinct: boolean ) { super('sum', [value]); } - toField(fieldName: string): AggregateTarget { - return new AggregateTarget(Field.of(fieldName), this); - } } class Avg extends Function implements Accumulator { + accumulator = true as const; constructor( private value: Expr, private distinct: boolean ) { super('avg', [value]); } - toField(fieldName: string): AggregateTarget { - return new AggregateTarget(Field.of(fieldName), this); - } } class Min extends Function implements Accumulator { + accumulator = true as const; constructor( private value: Expr, private distinct: boolean ) { super('min', [value]); } - toField(fieldName: string): AggregateTarget { - return new AggregateTarget(Field.of(fieldName), this); - } } class Max extends Function implements Accumulator { + accumulator = true as const; constructor( private value: Expr, private distinct: boolean ) { super('max', [value]); } - toField(fieldName: string): AggregateTarget { - return new AggregateTarget(Field.of(fieldName), this); - } } class CosineDistance extends Function { @@ -565,85 +907,145 @@ class EuclideanDistance extends Function { } } -function equal(left: Expr, right: Expr): Equal; -function equal(left: Expr, right: any): Equal; -function equal(left: string, right: Expr): Equal; -function equal(left: string, right: any): Equal; -function equal(left: Expr | string, right: any): Equal { +export function add(left: Expr, right: Expr): Add; +export function add(left: Expr, right: any): Add; +export function add(left: string, right: Expr): Add; +export function add(left: string, right: any): Add; +export function add(left: Expr | string, right: Expr | any): Add { + const normalizedLeft = typeof left === 'string' ? Field.of(left) : left; + const normalizedRight = right instanceof Expr ? right : Constant.of(right); + return new Add(normalizedLeft, normalizedRight); +} + +export function subtract(left: Expr, right: Expr): Subtract; +export function subtract(left: Expr, right: any): Subtract; +export function subtract(left: string, right: Expr): Subtract; +export function subtract(left: string, right: any): Subtract; +export function subtract(left: Expr | string, right: Expr | any): Subtract { + const normalizedLeft = typeof left === 'string' ? Field.of(left) : left; + const normalizedRight = right instanceof Expr ? right : Constant.of(right); + return new Subtract(normalizedLeft, normalizedRight); +} + +export function multiply(left: Expr, right: Expr): Multiply; +export function multiply(left: Expr, right: any): Multiply; +export function multiply(left: string, right: Expr): Multiply; +export function multiply(left: string, right: any): Multiply; +export function multiply(left: Expr | string, right: Expr | any): Multiply { + const normalizedLeft = typeof left === 'string' ? Field.of(left) : left; + const normalizedRight = right instanceof Expr ? right : Constant.of(right); + return new Multiply(normalizedLeft, normalizedRight); +} + +export function divide(left: Expr, right: Expr): Divide; +export function divide(left: Expr, right: any): Divide; +export function divide(left: string, right: Expr): Divide; +export function divide(left: string, right: any): Divide; +export function divide(left: Expr | string, right: Expr | any): Divide { + const normalizedLeft = typeof left === 'string' ? Field.of(left) : left; + const normalizedRight = right instanceof Expr ? right : Constant.of(right); + return new Divide(normalizedLeft, normalizedRight); +} + +export function eq(left: Expr, right: Expr): Eq; +export function eq(left: Expr, right: any): Eq; +export function eq(left: string, right: Expr): Eq; +export function eq(left: string, right: any): Eq; +export function eq(left: Expr | string, right: any): Eq { const leftExpr = left instanceof Expr ? left : Field.of(left); const rightExpr = right instanceof Expr ? right : Constant.of(right); - return new Equal(leftExpr, rightExpr); + return new Eq(leftExpr, rightExpr); } -// notEqual -function notEqual(left: Expr, right: Expr): NotEqual; -function notEqual(left: Expr, right: any): NotEqual; -function notEqual(left: string, right: Expr): NotEqual; -function notEqual(left: string, right: any): NotEqual; -function notEqual(left: Expr | string, right: any): NotEqual { +export function neq(left: Expr, right: Expr): Neq; +export function neq(left: Expr, right: any): Neq; +export function neq(left: string, right: Expr): Neq; +export function neq(left: string, right: any): Neq; +export function neq(left: Expr | string, right: any): Neq { const leftExpr = left instanceof Expr ? left : Field.of(left); const rightExpr = right instanceof Expr ? right : Constant.of(right); - return new NotEqual(leftExpr, rightExpr); + return new Neq(leftExpr, rightExpr); } -function lessThan(left: Expr, right: Expr): LessThan; -function lessThan(left: Expr, right: any): LessThan; -function lessThan(left: string, right: Expr): LessThan; -function lessThan(left: string, right: any): LessThan; -function lessThan(left: Expr | string, right: any): LessThan { +export function lt(left: Expr, right: Expr): Lt; +export function lt(left: Expr, right: any): Lt; +export function lt(left: string, right: Expr): Lt; +export function lt(left: string, right: any): Lt; +export function lt(left: Expr | string, right: any): Lt { const leftExpr = left instanceof Expr ? left : Field.of(left); const rightExpr = right instanceof Expr ? right : Constant.of(right); - return new LessThan(leftExpr, rightExpr); + return new Lt(leftExpr, rightExpr); } -function lessThanOrEqual(left: Expr, right: Expr): LessThanOrEqual; -function lessThanOrEqual(left: Expr, right: any): LessThanOrEqual; -function lessThanOrEqual(left: string, right: Expr): LessThanOrEqual; -function lessThanOrEqual(left: string, right: any): LessThanOrEqual; -function lessThanOrEqual(left: Expr | string, right: any): LessThanOrEqual { +export function lte(left: Expr, right: Expr): Lte; +export function lte(left: Expr, right: any): Lte; +export function lte(left: string, right: Expr): Lte; +export function lte(left: string, right: any): Lte; +export function lte(left: Expr | string, right: any): Lte { const leftExpr = left instanceof Expr ? left : Field.of(left); const rightExpr = right instanceof Expr ? right : Constant.of(right); - return new LessThanOrEqual(leftExpr, rightExpr); + return new Lte(leftExpr, rightExpr); } -function greaterThan(left: Expr, right: Expr): GreaterThan; -function greaterThan(left: Expr, right: any): GreaterThan; -function greaterThan(left: string, right: Expr): GreaterThan; -function greaterThan(left: string, right: any): GreaterThan; -function greaterThan(left: Expr | string, right: any): GreaterThan { +export function gt(left: Expr, right: Expr): Gt; +export function gt(left: Expr, right: any): Gt; +export function gt(left: string, right: Expr): Gt; +export function gt(left: string, right: any): Gt; +export function gt(left: Expr | string, right: any): Gt { const leftExpr = left instanceof Expr ? left : Field.of(left); const rightExpr = right instanceof Expr ? right : Constant.of(right); - return new GreaterThan(leftExpr, rightExpr); + return new Gt(leftExpr, rightExpr); } -function greaterThanOrEqual(left: Expr, right: Expr): GreaterThanOrEqual; -function greaterThanOrEqual(left: Expr, right: any): GreaterThanOrEqual; -function greaterThanOrEqual(left: string, right: Expr): GreaterThanOrEqual; -function greaterThanOrEqual(left: string, right: any): GreaterThanOrEqual; -function greaterThanOrEqual( - left: Expr | string, - right: any -): GreaterThanOrEqual { +export function gte(left: Expr, right: Expr): Gte; +export function gte(left: Expr, right: any): Gte; +export function gte(left: string, right: Expr): Gte; +export function gte(left: string, right: any): Gte; +export function gte(left: Expr | string, right: any): Gte { const leftExpr = left instanceof Expr ? left : Field.of(left); const rightExpr = right instanceof Expr ? right : Constant.of(right); - return new GreaterThanOrEqual(leftExpr, rightExpr); + return new Gte(leftExpr, rightExpr); +} + +export function arrayConcat(array: Expr, elements: Expr[]): ArrayConcat; +export function arrayConcat(array: Expr, elements: any[]): ArrayConcat; +export function arrayConcat(array: string, elements: Expr[]): ArrayConcat; +export function arrayConcat(array: string, elements: any[]): ArrayConcat; +export function arrayConcat( + array: Expr | string, + elements: any[] +): ArrayConcat { + const arrayExpr = array instanceof Expr ? array : Field.of(array); + const exprValues = elements.map(element => + element instanceof Expr ? element : Constant.of(element) + ); + return new ArrayConcat(arrayExpr, exprValues); } -function arrayContains(array: Expr, element: Expr): ArrayContains; -function arrayContains(array: Expr, element: any): ArrayContains; -function arrayContains(array: string, element: Expr): ArrayContains; -function arrayContains(array: string, element: any): ArrayContains; -function arrayContains(array: Expr | string, element: any): ArrayContains { +export function arrayContains(array: Expr, element: Expr): ArrayContains; +export function arrayContains(array: Expr, element: any): ArrayContains; +export function arrayContains(array: string, element: Expr): ArrayContains; +export function arrayContains(array: string, element: any): ArrayContains; +export function arrayContains( + array: Expr | string, + element: any +): ArrayContains { const arrayExpr = array instanceof Expr ? array : Field.of(array); const elementExpr = element instanceof Expr ? element : Constant.of(element); return new ArrayContains(arrayExpr, elementExpr); } -function arrayContainsAny(array: Expr, values: Expr[]): ArrayContainsAny; -function arrayContainsAny(array: Expr, values: any[]): ArrayContainsAny; -function arrayContainsAny(array: string, values: Expr[]): ArrayContainsAny; -function arrayContainsAny(array: string, values: any[]): ArrayContainsAny; -function arrayContainsAny( +export function arrayContainsAny(array: Expr, values: Expr[]): ArrayContainsAny; +export function arrayContainsAny(array: Expr, values: any[]): ArrayContainsAny; +export function arrayContainsAny( + array: string, + values: Expr[] +): ArrayContainsAny; +export function arrayContainsAny( + array: string, + values: any[] +): ArrayContainsAny; +export function arrayContainsAny( array: Expr | string, values: any[] ): ArrayContainsAny { @@ -654,11 +1056,51 @@ function arrayContainsAny( return new ArrayContainsAny(arrayExpr, exprValues); } -function inAny(element: Expr, others: Expr[]): In; -function inAny(element: Expr, others: any[]): In; -function inAny(element: string, others: Expr[]): In; // Added overload -function inAny(element: string, others: any[]): In; // Added overload -function inAny(element: Expr | string, others: any[]): In { +export function arrayContainsAll(array: Expr, values: Expr[]): ArrayContainsAll; +export function arrayContainsAll(array: Expr, values: any[]): ArrayContainsAll; +export function arrayContainsAll( + array: string, + values: Expr[] +): ArrayContainsAll; +export function arrayContainsAll( + array: string, + values: any[] +): ArrayContainsAll; +export function arrayContainsAll( + array: Expr | string, + values: any[] +): ArrayContainsAll { + const arrayExpr = array instanceof Expr ? array : Field.of(array); + const exprValues = values.map(value => + value instanceof Expr ? value : Constant.of(value) + ); + return new ArrayContainsAll(arrayExpr, exprValues); +} + +export function arrayFilter(array: Expr, filter: FilterExpr): ArrayFilter { + return new ArrayFilter(array, filter); +} + +export function arrayLength(array: Expr): ArrayLength { + return new ArrayLength(array); +} + +export function arrayTransform( + array: Expr, + transform: Function +): ArrayTransform { + return new ArrayTransform(array, transform); +} + +export function arrayElement(): ArrayElement { + return new ArrayElement(); +} + +export function inAny(element: Expr, others: Expr[]): In; +export function inAny(element: Expr, others: any[]): In; +export function inAny(element: string, others: Expr[]): In; // Added overload +export function inAny(element: string, others: any[]): In; // Added overload +export function inAny(element: Expr | string, others: any[]): In { const elementExpr = element instanceof Expr ? element : Field.of(element); const exprOthers = others.map(other => other instanceof Expr ? other : Constant.of(other) @@ -666,11 +1108,11 @@ function inAny(element: Expr | string, others: any[]): In { return new In(elementExpr, exprOthers); } -function notInAny(element: Expr, others: Expr[]): Not; -function notInAny(element: Expr, others: any[]): Not; -function notInAny(element: string, others: Expr[]): Not; // Added overload -function notInAny(element: string, others: any[]): Not; // Added overload -function notInAny(element: Expr | string, others: any[]): Not { +export function notInAny(element: Expr, others: Expr[]): Not; +export function notInAny(element: Expr, others: any[]): Not; +export function notInAny(element: string, others: Expr[]): Not; // Added overload +export function notInAny(element: string, others: any[]): Not; // Added overload +export function notInAny(element: Expr | string, others: any[]): Not { const elementExpr = element instanceof Expr ? element : Field.of(element); const exprOthers = others.map(other => other instanceof Expr ? other : Constant.of(other) @@ -686,6 +1128,18 @@ export function or(left: FilterExpr, ...right: FilterExpr[]): Or { return new Or([left, ...right]); } +export function xor(left: FilterExpr, ...right: FilterExpr[]): Xor { + return new Xor([left, ...right]); +} + +export function ifFunction( + condition: FilterExpr, + thenExpr: Expr, + elseExpr: Expr +): If { + return new If(condition, thenExpr, elseExpr); +} + export function not(filter: FilterExpr): Not { return new Not(filter); } @@ -712,6 +1166,115 @@ export function isNan(value: Expr | string): IsNan { return new IsNan(valueExpr); } +export function length(field: string): Length; +export function length(expr: Expr): Length; +export function length(value: Expr | string): Length { + const valueExpr = value instanceof Expr ? value : Field.of(value); + return new Length(valueExpr); +} + +export function like(left: Expr, pattern: Expr): Like; +export function like(left: Expr, pattern: string): Like; +export function like(left: string, pattern: Expr): Like; +export function like(left: string, pattern: string): Like; +export function like(left: Expr | string, pattern: Expr | string): Like { + const leftExpr = left instanceof Expr ? left : Field.of(left); + const patternExpr = pattern instanceof Expr ? pattern : Constant.of(pattern); + return new Like(leftExpr, patternExpr); +} + +export function regexContains(left: Expr, pattern: Expr): RegexContains; +export function regexContains(left: Expr, pattern: string): RegexContains; +export function regexContains(left: string, pattern: Expr): RegexContains; +export function regexContains(left: string, pattern: string): RegexContains; +export function regexContains( + left: Expr | string, + pattern: Expr | string +): RegexContains { + const leftExpr = left instanceof Expr ? left : Field.of(left); + const patternExpr = pattern instanceof Expr ? pattern : Constant.of(pattern); + return new RegexContains(leftExpr, patternExpr); +} + +export function regexMatch(left: Expr, pattern: Expr): RegexMatch; +export function regexMatch(left: Expr, pattern: string): RegexMatch; +export function regexMatch(left: string, pattern: Expr): RegexMatch; +export function regexMatch(left: string, pattern: string): RegexMatch; +export function regexMatch( + left: Expr | string, + pattern: Expr | string +): RegexMatch { + const leftExpr = left instanceof Expr ? left : Field.of(left); + const patternExpr = pattern instanceof Expr ? pattern : Constant.of(pattern); + return new RegexMatch(leftExpr, patternExpr); +} + +export function startsWith(expr: Expr, prefix: Expr): StartsWith; +export function startsWith(expr: Expr, prefix: string): StartsWith; +export function startsWith(expr: string, prefix: Expr): StartsWith; +export function startsWith(expr: string, prefix: string): StartsWith; +export function startsWith( + expr: Expr | string, + prefix: Expr | string +): StartsWith { + const exprLeft = expr instanceof Expr ? expr : Field.of(expr); + const prefixExpr = prefix instanceof Expr ? prefix : Constant.of(prefix); + return new StartsWith(exprLeft, prefixExpr); +} + +export function endsWith(expr: Expr, suffix: Expr): EndsWith; +export function endsWith(expr: Expr, suffix: string): EndsWith; +export function endsWith(expr: string, suffix: Expr): EndsWith; +export function endsWith(expr: string, suffix: string): EndsWith; +export function endsWith(expr: Expr | string, suffix: Expr | string): EndsWith { + const exprLeft = expr instanceof Expr ? expr : Field.of(expr); + const suffixExpr = suffix instanceof Expr ? suffix : Constant.of(suffix); + return new EndsWith(exprLeft, suffixExpr); +} + +export function toLowercase(expr: Expr): ToLowercase; +export function toLowercase(expr: string): ToLowercase; +export function toLowercase(expr: Expr | string): ToLowercase { + return new ToLowercase(expr instanceof Expr ? expr : Field.of(expr)); +} + +export function toUppercase(expr: Expr): ToUppercase; +export function toUppercase(expr: string): ToUppercase; +export function toUppercase(expr: Expr | string): ToUppercase { + return new ToUppercase(expr instanceof Expr ? expr : Field.of(expr)); +} + +export function trim(expr: Expr): Trim; +export function trim(expr: string): Trim; +export function trim(expr: Expr | string): Trim { + return new Trim(expr instanceof Expr ? expr : Field.of(expr)); +} + +export function strConcat( + first: string, + ...elements: (Expr | string)[] +): StrConcat; +export function strConcat( + first: Expr, + ...elements: (Expr | string)[] +): StrConcat; +export function strConcat( + first: string | Expr, + ...elements: (string | Expr)[] +): StrConcat { + const exprs = elements.map(e => (e instanceof Expr ? e : Constant.of(e))); + return new StrConcat(first instanceof Expr ? first : Field.of(first), exprs); +} + +export function mapGet(mapField: string, subField: string): MapGet; +export function mapGet(mapExpr: Expr, subField: string): MapGet; +export function mapGet(fieldOrExpr: string | Expr, subField: string): MapGet { + return new MapGet( + typeof fieldOrExpr === 'string' ? Field.of(fieldOrExpr) : fieldOrExpr, + subField + ); +} + export function countAll(): Count { return new Count(undefined, false); } @@ -737,27 +1300,30 @@ export function avg(value: Expr | string): Avg { return new Avg(exprValue, false); } -function min(value: Expr): Min; -function min(value: string): Min; -function min(value: Expr | string): Min { +export function min(value: Expr): Min; +export function min(value: string): Min; +export function min(value: Expr | string): Min { const exprValue = value instanceof Expr ? value : Field.of(value); return new Min(exprValue, false); } -function max(value: Expr): Max; -function max(value: string): Max; -function max(value: Expr | string): Max { +export function max(value: Expr): Max; +export function max(value: string): Max; +export function max(value: Expr | string): Max { const exprValue = value instanceof Expr ? value : Field.of(value); return new Max(exprValue, false); } -function cosineDistance(expr: Expr, other: Expr): CosineDistance; -function cosineDistance(expr: Expr, other: number[]): CosineDistance; -function cosineDistance(expr: Expr, other: VectorValue): CosineDistance; -function cosineDistance(expr: string, other: Expr): CosineDistance; -function cosineDistance(expr: string, other: number[]): CosineDistance; -function cosineDistance(expr: string, other: VectorValue): CosineDistance; -function cosineDistance( +export function cosineDistance(expr: Expr, other: Expr): CosineDistance; +export function cosineDistance(expr: Expr, other: number[]): CosineDistance; +export function cosineDistance(expr: Expr, other: VectorValue): CosineDistance; +export function cosineDistance(expr: string, other: Expr): CosineDistance; +export function cosineDistance(expr: string, other: number[]): CosineDistance; +export function cosineDistance( + expr: string, + other: VectorValue +): CosineDistance; +export function cosineDistance( expr: Expr | string, other: Expr | number[] | VectorValue ): CosineDistance { @@ -766,16 +1332,28 @@ function cosineDistance( return new CosineDistance(expr1, expr2); } -function dotProductDistance(expr: Expr, other: Expr): DotProductDistance; // Fixed return type -function dotProductDistance(expr: Expr, other: number[]): DotProductDistance; -function dotProductDistance(expr: Expr, other: VectorValue): DotProductDistance; -function dotProductDistance(expr: string, other: Expr): DotProductDistance; -function dotProductDistance(expr: string, other: number[]): DotProductDistance; -function dotProductDistance( +export function dotProductDistance(expr: Expr, other: Expr): DotProductDistance; // Fixed return type +export function dotProductDistance( + expr: Expr, + other: number[] +): DotProductDistance; +export function dotProductDistance( + expr: Expr, + other: VectorValue +): DotProductDistance; +export function dotProductDistance( + expr: string, + other: Expr +): DotProductDistance; +export function dotProductDistance( + expr: string, + other: number[] +): DotProductDistance; +export function dotProductDistance( expr: string, other: VectorValue ): DotProductDistance; -function dotProductDistance( +export function dotProductDistance( expr: Expr | string, other: Expr | number[] | VectorValue ): DotProductDistance { @@ -784,13 +1362,25 @@ function dotProductDistance( return new DotProductDistance(expr1, expr2); } -function euclideanDistance(expr: Expr, other: Expr): EuclideanDistance; -function euclideanDistance(expr: Expr, other: number[]): EuclideanDistance; -function euclideanDistance(expr: Expr, other: VectorValue): EuclideanDistance; -function euclideanDistance(expr: string, other: Expr): EuclideanDistance; -function euclideanDistance(expr: string, other: number[]): EuclideanDistance; -function euclideanDistance(expr: string, other: VectorValue): EuclideanDistance; -function euclideanDistance( +export function euclideanDistance(expr: Expr, other: Expr): EuclideanDistance; +export function euclideanDistance( + expr: Expr, + other: number[] +): EuclideanDistance; +export function euclideanDistance( + expr: Expr, + other: VectorValue +): EuclideanDistance; +export function euclideanDistance(expr: string, other: Expr): EuclideanDistance; +export function euclideanDistance( + expr: string, + other: number[] +): EuclideanDistance; +export function euclideanDistance( + expr: string, + other: VectorValue +): EuclideanDistance; +export function euclideanDistance( expr: Expr | string, other: Expr | number[] | VectorValue ): EuclideanDistance { @@ -799,7 +1389,7 @@ function euclideanDistance( return new EuclideanDistance(expr1, expr2); } -function genericFunction(name: string, params: Expr[]): Function { +export function genericFunction(name: string, params: Expr[]): Function { return new Function(name, params); } diff --git a/dev/src/pipeline-util.ts b/dev/src/pipeline-util.ts index 8b814e0a6..21ba1e77d 100644 --- a/dev/src/pipeline-util.ts +++ b/dev/src/pipeline-util.ts @@ -90,11 +90,7 @@ export class ExecutionUtil< } ) .on('end', () => { - // Only return a snapshot when we have a readTime - // explain queries with analyze !== true will return no documents and no read time - const result = output.executionTime ? results : undefined; - - resolve(result); + resolve(results); }); }); } @@ -181,7 +177,7 @@ export class ExecutionUtil< output.result = new PipelineResult( this._serializer, ref, - result.fields, + result.fields || undefined, Timestamp.fromProto(proto.executionTime!), result.createTime ? Timestamp.fromProto(result.createTime!) @@ -405,17 +401,17 @@ export function toPipelineFilterCondition( : serializer.encodeValue(f.value); switch (f.op) { case 'LESS_THAN': - return and(field.exists(), field.lessThan(value)); + return and(field.exists(), field.lt(value)); case 'LESS_THAN_OR_EQUAL': - return and(field.exists(), field.lessThanOrEqual(value)); + return and(field.exists(), field.lte(value)); case 'GREATER_THAN': - return and(field.exists(), field.greaterThan(value)); + return and(field.exists(), field.gt(value)); case 'GREATER_THAN_OR_EQUAL': - return and(field.exists(), field.greaterThanOrEqual(value)); + return and(field.exists(), field.gte(value)); case 'EQUAL': - return and(field.exists(), field.equal(value)); + return and(field.exists(), field.eq(value)); case 'NOT_EQUAL': - return and(field.exists(), field.notEqual(value)); + return and(field.exists(), field.neq(value)); case 'ARRAY_CONTAINS': return and(field.exists(), field.arrayContains(value)); case 'IN': { diff --git a/dev/src/pipeline.ts b/dev/src/pipeline.ts index 7ab677218..2976a8272 100644 --- a/dev/src/pipeline.ts +++ b/dev/src/pipeline.ts @@ -1,16 +1,19 @@ import * as firestore from '@google-cloud/firestore'; +import * as deepEqual from 'fast-deep-equal'; import {google} from '../protos/firestore_v1_proto_api'; import { Accumulator, - AggregateTarget, + AccumulatorTarget, Expr, + ExprWithAlias, Field, Fields, FilterCondition, Ordering, Selectable, } from './expression'; -import Firestore, {Timestamp} from './index'; +import Firestore, {FieldPath, QueryDocumentSnapshot, Timestamp} from './index'; +import {validateFieldPath} from './path'; import {ExecutionUtil} from './pipeline-util'; import {DocumentReference} from './reference/document-reference'; import {Serializer} from './serializer'; @@ -30,13 +33,15 @@ import { Select, Sort, Stage, + Distinct, } from './stage'; -import {ApiMapValue} from './types'; +import {ApiMapValue, defaultConverter} from './types'; import * as protos from '../protos/firestore_v1_proto_api'; import api = protos.google.firestore.v1; import IStructuredPipeline = google.firestore.v1.IStructuredPipeline; import IStage = google.firestore.v1.Pipeline.IStage; import {QueryCursor} from './reference/types'; +import {isOptionalEqual} from './util'; export class PipelineSource { constructor(private db: Firestore) {} @@ -90,14 +95,14 @@ export class Pipeline< result.set(selectable as string, Field.of(selectable)); } else if (selectable instanceof Field) { result.set((selectable as Field).fieldName(), selectable); - } else if (selectable instanceof AggregateTarget) { - const target = selectable as AggregateTarget; - result.set(target.field.fieldName(), target.accumulator); } else if (selectable instanceof Fields) { const fields = selectable as Fields; for (const field of fields.fieldList()) { result.set(field.fieldName(), field); } + } else if (selectable instanceof ExprWithAlias) { + const expr = selectable as ExprWithAlias; + result.set(expr.alias, expr.expr); } } return result; @@ -121,16 +126,49 @@ export class Pipeline< return new Pipeline(this.db, copy); } - aggregate(...targets: AggregateTarget[]): Pipeline { + distinct(...groups: (string | Selectable)[]): Pipeline { const copy = this.stages.map(s => s); - copy.push( - new Aggregate( - new Map(), - new Map( - targets.map(target => [target.field.fieldName(), target.accumulator]) + copy.push(new Distinct(this.selectablesToMap(groups || []))); + return new Pipeline(this.db, copy); + } + + aggregate(...accumulators: AccumulatorTarget[]): Pipeline; + aggregate(options: { + accumulators: AccumulatorTarget[]; + groups?: (string | Selectable)[]; + }): Pipeline; + aggregate( + optionsOrTarget: + | AccumulatorTarget + | {accumulators: AccumulatorTarget[]; groups?: (string | Selectable)[]}, + ...rest: AccumulatorTarget[] + ): Pipeline { + const copy = this.stages.map(s => s); + if ('accumulators' in optionsOrTarget) { + copy.push( + new Aggregate( + new Map( + optionsOrTarget.accumulators.map((target: AccumulatorTarget) => [ + target.alias, + target.expr, + ]) + ), + this.selectablesToMap(optionsOrTarget.groups || []) ) - ) - ); + ); + } else { + copy.push( + new Aggregate( + new Map( + [optionsOrTarget, ...rest].map(target => [ + target.alias, + target.expr, + ]) + ), + new Map() + ) + ); + } return new Pipeline(this.db, copy); } @@ -160,21 +198,39 @@ export class Pipeline< return new Pipeline(this.db, copy); } - sort(orderings: Ordering[]): Pipeline; - sort( - orderings: Ordering[], - density?: 'unspecified' | 'required', - truncation?: 'unspecified' | 'disabled' - ): Pipeline; + sort(...orderings: Ordering[]): Pipeline; + sort(options: { + orderings: Ordering[]; + density?: 'unspecified' | 'required'; + truncation?: 'unspecified' | 'disabled'; + }): Pipeline; sort( - orderings: Ordering[], - density?: 'unspecified' | 'required', - truncation?: 'unspecified' | 'disabled' + optionsOrOrderings: + | Ordering + | { + orderings: Ordering[]; + density?: 'unspecified' | 'required'; + truncation?: 'unspecified' | 'disabled'; + }, + ...rest: Ordering[] ): Pipeline { const copy = this.stages.map(s => s); - copy.push( - new Sort(orderings, density ?? 'unspecified', truncation ?? 'unspecified') - ); + // Option object + if ('orderings' in optionsOrOrderings) { + copy.push( + new Sort( + optionsOrOrderings.orderings, + optionsOrOrderings.density ?? 'unspecified', + optionsOrOrderings.truncation ?? 'unspecified' + ) + ); + } else { + // Ordering object + copy.push( + new Sort([optionsOrOrderings, ...rest], 'unspecified', 'unspecified') + ); + } + return new Pipeline(this.db, copy); } @@ -283,7 +339,9 @@ export class PipelineResult< AppModelType = firestore.DocumentData, DbModelType extends firestore.DocumentData = firestore.DocumentData, > { - private _ref: DocumentReference | undefined; + private readonly _ref: + | DocumentReference + | undefined; private _serializer: Serializer; public readonly _readTime: Timestamp | undefined; public readonly _createTime: Timestamp | undefined; @@ -311,7 +369,7 @@ export class PipelineResult< * @internal * @private **/ - readonly _fieldsProto?: ApiMapValue | null, + readonly _fieldsProto?: ApiMapValue, readTime?: Timestamp, createTime?: Timestamp, updateTime?: Timestamp @@ -322,4 +380,233 @@ export class PipelineResult< this._createTime = createTime; this._updateTime = updateTime; } + + get ref(): DocumentReference | undefined { + return this._ref; + } + + /** + * The ID of the document for which this DocumentSnapshot contains data. + * + * @type {string} + * @name DocumentSnapshot#id + * @readonly + * + * @example + * ``` + * let documentRef = firestore.doc('col/doc'); + * + * documentRef.get().then((documentSnapshot) => { + * if (documentSnapshot.exists) { + * console.log(`Document found with name '${documentSnapshot.id}'`); + * } + * }); + * ``` + */ + get id(): string | undefined { + return this._ref?.id; + } + + /** + * The time the document was created. Undefined for documents that don't + * exist. + * + * @type {Timestamp|undefined} + * @name DocumentSnapshot#createTime + * @readonly + * + * @example + * ``` + * let documentRef = firestore.doc('col/doc'); + * + * documentRef.get().then(documentSnapshot => { + * if (documentSnapshot.exists) { + * let createTime = documentSnapshot.createTime; + * console.log(`Document created at '${createTime.toDate()}'`); + * } + * }); + * ``` + */ + get createTime(): Timestamp | undefined { + return this._createTime; + } + + /** + * The time the document was last updated (at the time the snapshot was + * generated). Undefined for documents that don't exist. + * + * @type {Timestamp|undefined} + * @name DocumentSnapshot#updateTime + * @readonly + * + * @example + * ``` + * let documentRef = firestore.doc('col/doc'); + * + * documentRef.get().then(documentSnapshot => { + * if (documentSnapshot.exists) { + * let updateTime = documentSnapshot.updateTime; + * console.log(`Document updated at '${updateTime.toDate()}'`); + * } + * }); + * ``` + */ + get updateTime(): Timestamp | undefined { + return this._updateTime; + } + + /** + * The time this snapshot was read. + * + * @type {Timestamp} + * @name DocumentSnapshot#readTime + * @readonly + * + * @example + * ``` + * let documentRef = firestore.doc('col/doc'); + * + * documentRef.get().then(documentSnapshot => { + * let readTime = documentSnapshot.readTime; + * console.log(`Document read at '${readTime.toDate()}'`); + * }); + * ``` + */ + get readTime(): Timestamp { + if (this._readTime === undefined) { + throw new Error("Called 'readTime' on a local document"); + } + return this._readTime; + } + + /** + * Retrieves all fields in the document as an object. Returns 'undefined' if + * the document doesn't exist. + * + * @returns {T|undefined} An object containing all fields in the document or + * 'undefined' if the document doesn't exist. + * + * @example + * ``` + * let documentRef = firestore.doc('col/doc'); + * + * documentRef.get().then(documentSnapshot => { + * let data = documentSnapshot.data(); + * console.log(`Retrieved data: ${JSON.stringify(data)}`); + * }); + * ``` + */ + data(): AppModelType | undefined { + const fields = this._fieldsProto; + + if (fields === undefined) { + return undefined; + } + + // We only want to use the converter and create a new QueryDocumentSnapshot + // if a converter has been provided. + if (!!this.ref && this.ref._converter !== defaultConverter()) { + const untypedReference = new DocumentReference( + this.ref.firestore, + this.ref._path + ); + return this.ref._converter.fromFirestore( + new QueryDocumentSnapshot( + untypedReference, + this._fieldsProto!, + this.readTime, + this.createTime!, + this.updateTime! + ) + ); + } else { + const obj: firestore.DocumentData = {}; + for (const prop of Object.keys(fields)) { + obj[prop] = this._serializer.decodeValue(fields[prop]); + } + return obj as AppModelType; + } + } + + /** + * Retrieves the field specified by `field`. + * + * @param {string|FieldPath} field The field path + * (e.g. 'foo' or 'foo.bar') to a specific field. + * @returns {*} The data at the specified field location or undefined if no + * such field exists. + * + * @example + * ``` + * let documentRef = firestore.doc('col/doc'); + * + * documentRef.set({ a: { b: 'c' }}).then(() => { + * return documentRef.get(); + * }).then(documentSnapshot => { + * let field = documentSnapshot.get('a.b'); + * console.log(`Retrieved field value: ${field}`); + * }); + * ``` + */ + // We deliberately use `any` in the external API to not impose type-checking + // on end users. + // eslint-disable-next-line @typescript-eslint/no-explicit-any + get(field: string | FieldPath): any { + validateFieldPath('field', field); + + const protoField = this.protoField(field); + + if (protoField === undefined) { + return undefined; + } + + return this._serializer.decodeValue(protoField); + } + + /** + * Retrieves the field specified by 'fieldPath' in its Protobuf JS + * representation. + * + * @private + * @internal + * @param field The path (e.g. 'foo' or 'foo.bar') to a specific field. + * @returns The Protobuf-encoded data at the specified field location or + * undefined if no such field exists. + */ + protoField(field: string | FieldPath): api.IValue | undefined { + let fields: ApiMapValue | api.IValue | undefined = this._fieldsProto; + + if (fields === undefined) { + return undefined; + } + + const components = FieldPath.fromArgument(field).toArray(); + while (components.length > 1) { + fields = (fields as ApiMapValue)[components.shift()!]; + + if (!fields || !fields.mapValue) { + return undefined; + } + + fields = fields.mapValue.fields!; + } + + return (fields as ApiMapValue)[components[0]]; + } + + /** + * Returns true if the document's data and path in this `DocumentSnapshot` is + * equal to the provided value. + * + * @param {*} other The value to compare against. + * @return {boolean} true if this `DocumentSnapshot` is equal to the provided + * value. + */ + isEqual(other: PipelineResult): boolean { + return ( + this === other || + (isOptionalEqual(this._ref, other._ref) && + deepEqual(this._fieldsProto, other._fieldsProto)) + ); + } } diff --git a/dev/src/reference/aggregate-query.ts b/dev/src/reference/aggregate-query.ts index a4c497571..f614e0d4e 100644 --- a/dev/src/reference/aggregate-query.ts +++ b/dev/src/reference/aggregate-query.ts @@ -22,7 +22,14 @@ import * as deepEqual from 'fast-deep-equal'; import * as firestore from '@google-cloud/firestore'; import {Aggregate, AggregateSpec} from '../aggregate'; -import {AggregateTarget, avg, count, countAll, Field, sum} from '../expression'; +import { + AccumulatorTarget, + avg, + count, + countAll, + Field, + sum, +} from '../expression'; import {Pipeline} from '../pipeline'; import {Timestamp} from '../timestamp'; import {mapToArray, requestTag, wrapError} from '../util'; @@ -339,17 +346,17 @@ export class AggregateQuery< (aggregate, clientAlias) => { if (aggregate.aggregateType === 'count') { if (aggregate._field === undefined) { - return countAll().toField(clientAlias); + return countAll().as(clientAlias); } - return count(Field.of(aggregate._field)).toField(clientAlias); + return count(Field.of(aggregate._field)).as(clientAlias); } else if (aggregate.aggregateType === 'avg') { - return avg(Field.of(aggregate._field!)).toField(clientAlias); + return avg(Field.of(aggregate._field!)).as(clientAlias); } else { - return sum(Field.of(aggregate._field!)).toField(clientAlias); + return sum(Field.of(aggregate._field!)).as(clientAlias); } } ); - return this._query.toPipeline().aggregate(...aggregates); + return this._query.pipeline().aggregate(...aggregates); } /** diff --git a/dev/src/reference/query.ts b/dev/src/reference/query.ts index 75f6706b8..e335ae2d1 100644 --- a/dev/src/reference/query.ts +++ b/dev/src/reference/query.ts @@ -666,7 +666,7 @@ export class Query< ); } - toPipeline(): Pipeline { + pipeline(): Pipeline { let pipeline; if (this._queryOptions.allDescendants) { pipeline = this.firestore @@ -701,7 +701,7 @@ export class Query< if (exists.length > 1) { const [first, ...rest] = exists; pipeline = pipeline.where(and(first, ...rest)); - } else if (exists.length == 1) { + } else if (exists.length === 1) { pipeline = pipeline.where(exists[0]); } @@ -720,7 +720,11 @@ export class Query< return Ordering.of(Field.of(fieldOrder.field), dir); }); if (orderings.length > 0) { - pipeline = pipeline.sort(orderings, 'required', 'unspecified'); + pipeline = pipeline.sort({ + orderings: orderings, + density: 'required', + truncation: 'unspecified', + }); } // Cursors, Limit and Offset @@ -729,18 +733,9 @@ export class Query< !!this._queryOptions.endAt || this._queryOptions.limitType === LimitType.Last ) { - let paginating = pipeline.paginate(this._queryOptions.limit || 10); - if (this._queryOptions.startAt) { - paginating = paginating.withStartCursor(this._queryOptions.startAt!); - } - if (this._queryOptions.endAt) { - paginating = paginating.withEndCursor(this._queryOptions.endAt!); - } - if (this._queryOptions.limit === LimitType.Last) { - return paginating.lastPage(); - } else { - return paginating.firstPage(); - } + throw new Error( + 'Query to Pipeline conversion: cursors and limitToLast is not supported yet.' + ); } else { if (this._queryOptions.offset) { pipeline = pipeline.offset(this._queryOptions.offset); diff --git a/dev/src/reference/vector-query.ts b/dev/src/reference/vector-query.ts index ad853c73b..39bcc7c82 100644 --- a/dev/src/reference/vector-query.ts +++ b/dev/src/reference/vector-query.ts @@ -137,7 +137,7 @@ export class VectorQuery< distanceMeasure: this.options.distanceMeasure.toLowerCase(), } as FindNearestOptions; return this.query - .toPipeline() + .pipeline() .where(Field.of(this.vectorField).exists()) .findNearest(Field.of(this.vectorField), this.queryVector, options); } diff --git a/dev/src/stage.ts b/dev/src/stage.ts index ca8d5f39b..842b09cca 100644 --- a/dev/src/stage.ts +++ b/dev/src/stage.ts @@ -34,21 +34,34 @@ export class Aggregate implements Stage { name = 'aggregate'; constructor( - private groups: Map, - private accumulators: Map + private accumulators: Map, + private groups: Map ) {} _toProto(serializer: Serializer): api.Pipeline.IStage { return { name: this.name, args: [ - serializer.encodeValue(this.groups)!, serializer.encodeValue(this.accumulators)!, + serializer.encodeValue(this.groups)!, ], }; } } +export class Distinct implements Stage { + name = 'distinct'; + + constructor(private groups: Map) {} + + _toProto(serializer: Serializer): api.Pipeline.IStage { + return { + name: this.name, + args: [serializer.encodeValue(this.groups)!], + }; + } +} + export class Collection implements Stage { name = 'collection'; diff --git a/dev/src/util.ts b/dev/src/util.ts index c4b4754c1..c5a0de214 100644 --- a/dev/src/util.ts +++ b/dev/src/util.ts @@ -316,6 +316,30 @@ export function isArrayEqual boolean}>( return true; } +/** + * Verifies equality for an optional type using the `isEqual` interface. + * + * @private + * @internal + * @param left Optional object supporting `isEqual`. + * @param right Optional object supporting `isEqual`. + * @return True if equal. + */ +export function isOptionalEqual boolean}>( + left: T | undefined, + right: T | undefined +): boolean { + if (left === undefined && right === undefined) { + return true; + } + + if (left === undefined || right === undefined) { + return false; + } + + return left.isEqual(right); +} + /** * Verifies equality for an array of primitives. * diff --git a/dev/system-test/pipeline.ts b/dev/system-test/pipeline.ts index 8dcfe7006..97d46eb38 100644 --- a/dev/system-test/pipeline.ts +++ b/dev/system-test/pipeline.ts @@ -18,11 +18,41 @@ import { Query, QueryDocumentSnapshot, } from '../src'; +import { + add, + and, + arrayContains, + arrayContainsAny, + arrayElement, + arrayFilter, + arrayTransform, + avg, + countAll, + endsWith, + eq, + Field, + gt, + like, + lt, + neq, + not, + isNull, + or, + regexContains, + regexMatch, + startsWith, + strConcat, + subtract, + cosineDistance, + dotProductDistance, + euclideanDistance, + Constant, +} from '../src/expression'; +import {PipelineResult} from '../src/pipeline'; import {verifyInstance} from '../test/util/helpers'; import {DeferredPromise, getTestRoot} from './firestore'; -import {IndexTestHelper} from './index_test_helper'; -describe('Pipeline class', () => { +describe.only('Pipeline class', () => { let firestore: Firestore; let randomCol: CollectionReference; @@ -49,22 +79,25 @@ describe('Pipeline class', () => { return randomCol; } - function expectDocs(result: QuerySnapshot, ...docs: string[]): void; - function expectDocs(result: QuerySnapshot, ...data: DocumentData[]): void; + function expectResults(result: PipelineResult[], ...docs: string[]): void; + function expectResults( + result: PipelineResult[], + ...data: DocumentData[] + ): void; - function expectDocs( - result: QuerySnapshot, + function expectResults( + result: PipelineResult[], ...data: DocumentData[] | string[] ): void { - expect(result.size).to.equal(data.length); + expect(result.length).to.equal(data.length); if (data.length > 0) { if (typeof data[0] === 'string') { - const actualIds = result.docs.map(docSnapshot => docSnapshot.id); + const actualIds = result.map(result => result.ref?.id); expect(actualIds).to.deep.equal(data); } else { - result.forEach(doc => { - expect(doc.data()).to.deep.equal(data.shift()); + result.forEach(r => { + expect(r.data()).to.deep.equal(data.shift()); }); } } @@ -72,7 +105,7 @@ describe('Pipeline class', () => { async function compareQueryAndPipeline(query: Query): Promise { const queryResults = await query.get(); - const pipeline = query.toPipeline(); + const pipeline = query.pipeline(); const pipelineResults = await pipeline.execute(); expect(queryResults.docs.map(s => s._fieldsProto)).to.deep.equal( @@ -81,14 +114,111 @@ describe('Pipeline class', () => { return queryResults; } - beforeEach(() => { + async function setupBookDocs(): Promise> { + const bookDocs: {[id: string]: DocumentData} = { + book1: { + title: "The Hitchhiker's Guide to the Galaxy", + author: 'Douglas Adams', + genre: 'Science Fiction', + published: 1979, + rating: 4.2, + tags: ['comedy', 'space', 'adventure'], + awards: {hugo: true, nebula: false}, + }, + book2: { + title: 'Pride and Prejudice', + author: 'Jane Austen', + genre: 'Romance', + published: 1813, + rating: 4.5, + tags: ['classic', 'social commentary', 'love'], + awards: {none: true}, + }, + book3: { + title: 'One Hundred Years of Solitude', + author: 'Gabriel García Márquez', + genre: 'Magical Realism', + published: 1967, + rating: 4.3, + tags: ['family', 'history', 'fantasy'], + awards: {nobel: true, nebula: false}, + }, + book4: { + title: 'The Lord of the Rings', + author: 'J.R.R. Tolkien', + genre: 'Fantasy', + published: 1954, + rating: 4.7, + tags: ['adventure', 'magic', 'epic'], + awards: {hugo: false, nebula: false}, + }, + book5: { + title: "The Handmaid's Tale", + author: 'Margaret Atwood', + genre: 'Dystopian', + published: 1985, + rating: 4.1, + tags: ['feminism', 'totalitarianism', 'resistance'], + awards: {'arthur c. clarke': true, 'booker prize': false}, + }, + book6: { + title: 'Crime and Punishment', + author: 'Fyodor Dostoevsky', + genre: 'Psychological Thriller', + published: 1866, + rating: 4.3, + tags: ['philosophy', 'crime', 'redemption'], + awards: {none: true}, + }, + book7: { + title: 'To Kill a Mockingbird', + author: 'Harper Lee', + genre: 'Southern Gothic', + published: 1960, + rating: 4.2, + tags: ['racism', 'injustice', 'coming-of-age'], + awards: {pulitzer: true}, + }, + book8: { + title: '1984', + author: 'George Orwell', + genre: 'Dystopian', + published: 1949, + rating: 4.2, + tags: ['surveillance', 'totalitarianism', 'propaganda'], + awards: {prometheus: true}, + }, + book9: { + title: 'The Great Gatsby', + author: 'F. Scott Fitzgerald', + genre: 'Modernist', + published: 1925, + rating: 4.0, + tags: ['wealth', 'american dream', 'love'], + awards: {none: true}, + }, + book10: { + title: 'Dune', + author: 'Frank Herbert', + genre: 'Science Fiction', + published: 1965, + rating: 4.6, + tags: ['politics', 'desert', 'ecology'], + awards: {hugo: true, nebula: true}, + }, + }; + return testCollectionWithDocs(bookDocs); + } + + before(async () => { randomCol = getTestRoot(); + await setupBookDocs(); firestore = randomCol.firestore; }); afterEach(() => verifyInstance(firestore)); - it('basic collection', async () => { + it('empty results as expected', async () => { const result = await firestore .pipeline() .collection(randomCol.path) @@ -96,4 +226,508 @@ describe('Pipeline class', () => { .execute(); expect(result).to.be.empty; }); + + it('returns aggregate results as expected', async () => { + let result = await firestore + .pipeline() + .collection(randomCol.path) + .aggregate(countAll().as('count')) + .execute(); + expectResults(result, {count: 10}); + + result = await randomCol + .pipeline() + .where(eq('genre', 'Science Fiction')) + .aggregate( + countAll().as('count'), + avg('rating').as('avg_rating'), + Field.of('rating').max().as('max_rating') + ) + .execute(); + expectResults(result, {count: 2, avg_rating: 4.4, max_rating: 4.6}); + }); + + it('rejects groups without accumulators', async () => { + await expect( + randomCol + .pipeline() + .where(lt('published', 1900)) + .aggregate({ + accumulators: [], + groups: ['genre'], + }) + .execute() + ).to.be.rejected; + }); + + it('returns distinct values as expected', async () => { + const results = await randomCol + .pipeline() + .where(lt('published', 1900)) + .distinct(Field.of('genre').toLowercase().as('lower_genre')) + .execute(); + expectResults( + results, + {lower_genre: 'romance'}, + {lower_genre: 'psychological thriller'} + ); + }); + + it('returns group and accumulate results', async () => { + const results = await randomCol + .pipeline() + .where(lt('published', 1984)) + .aggregate({ + accumulators: [avg('rating').as('avg_rating')], + groups: ['genre'], + }) + .where(gt('avg_rating', 4.3)) + .execute(); + expectResults( + results, + {avg_rating: 4.7, genre: 'Fantasy'}, + {avg_rating: 4.5, genre: 'Romance'}, + {avg_rating: 4.4, genre: 'Science Fiction'} + ); + }); + + it('returns min and max accumulations', async () => { + const results = await randomCol + .pipeline() + .aggregate( + countAll().as('count'), + Field.of('rating').max().as('max_rating'), + Field.of('published').min().as('min_published') + ) + .execute(); + expectResults(results, { + count: 10, + max_rating: 4.7, + min_published: 1813, + }); + }); + + it('can select fields', async () => { + const results = await randomCol + .pipeline() + .select('title', 'author') + .sort(Field.of('author').ascending()) + .execute(); + expectResults( + results, + {title: "The Hitchhiker's Guide to the Galaxy", author: 'Douglas Adams'}, + {title: 'The Great Gatsby', author: 'F. Scott Fitzgerald'}, + {title: 'Dune', author: 'Frank Herbert'}, + {title: 'Crime and Punishment', author: 'Fyodor Dostoevsky'}, + { + title: 'One Hundred Years of Solitude', + author: 'Gabriel García Márquez', + }, + {title: '1984', author: 'George Orwell'}, + {title: 'To Kill a Mockingbird', author: 'Harper Lee'}, + {title: 'The Lord of the Rings', author: 'J.R.R. Tolkien'}, + {title: 'Pride and Prejudice', author: 'Jane Austen'}, + {title: "The Handmaid's Tale", author: 'Margaret Atwood'} + ); + }); + + it('where with and', async () => { + const results = await randomCol + .pipeline() + .where(and(gt('rating', 4.5), eq('genre', 'Science Fiction'))) + .execute(); + expectResults(results, 'book10'); + }); + + it('where with or', async () => { + const results = await randomCol + .pipeline() + .where(or(eq('genre', 'Romance'), eq('genre', 'Dystopian'))) + .select('title') + .execute(); + expectResults( + results, + {title: 'Pride and Prejudice'}, + {title: "The Handmaid's Tale"}, + {title: '1984'} + ); + }); + + it('offset and limits', async () => { + const results = await randomCol + .pipeline() + .sort(Field.of('author').ascending()) + .offset(5) + .limit(3) + .select('title', 'author') + .execute(); + expectResults( + results, + {title: '1984', author: 'George Orwell'}, + {title: 'To Kill a Mockingbird', author: 'Harper Lee'}, + {title: 'The Lord of the Rings', author: 'J.R.R. Tolkien'} + ); + }); + + it('arrayContains works', async () => { + const results = await randomCol + .pipeline() + .where(arrayContains('tags', 'comedy')) + .select('title') + .execute(); + expectResults(results, {title: "The Hitchhiker's Guide to the Galaxy"}); + }); + + it('arrayContainsAny works', async () => { + const results = await randomCol + .pipeline() + .where(arrayContainsAny('tags', ['comedy', 'classic'])) + .select('title') + .execute(); + expectResults( + results, + {title: "The Hitchhiker's Guide to the Galaxy"}, + {title: 'Pride and Prejudice'} + ); + }); + + it('arrayContainsAll works', async () => { + const results = await randomCol + .pipeline() + .where(Field.of('tags').arrayContainsAll('adventure', 'magic')) + .select('title') + .execute(); + expectResults(results, {title: 'The Lord of the Rings'}); + }); + + it('arrayLength works', async () => { + const results = await randomCol + .pipeline() + .select(Field.of('tags').arrayLength().as('tagsCount')) + .where(eq('tagsCount', 3)) + .execute(); + expect(results.length).to.equal(10); + }); + + it('arrayConcat works', async () => { + const results = await randomCol + .pipeline() + .select( + Field.of('tags').arrayConcat('newTag1', 'newTag2').as('modifiedTags') + ) + .limit(1) + .execute(); + expectResults(results, { + modifiedTags: ['comedy', 'space', 'adventure', 'newTag1', 'newTag2'], + }); + }); + + it('arrayFilter works', async () => { + const results = await randomCol + .pipeline() + .select( + arrayFilter(Field.of('tags'), arrayElement().eq('comedy')).as( + 'filteredTags' + ) + ) + .limit(1) + .execute(); + + expectResults(results, { + filteredTags: ['comedy'], + }); + }); + + it('arrayTransform works', async () => { + const results = await randomCol + .pipeline() + .select( + arrayTransform( + Field.of('tags'), + arrayElement().strConcat('transformed') + ).as('transformedTags') + ) + .limit(1) + .execute(); + expectResults(results, { + transformedTags: [ + 'comedytransformed', + 'spacetransformed', + 'adventuretransformed', + ], + }); + }); + + it('testStrConcat', async () => { + const results = await randomCol + .pipeline() + .select( + Field.of('author').strConcat(' - ', Field.of('title')).as('bookInfo') + ) + .limit(1) + .execute(); + expectResults(results, { + bookInfo: "Douglas Adams - The Hitchhiker's Guide to the Galaxy", + }); + }); + + it('testStartsWith', async () => { + const results = await randomCol + .pipeline() + .where(startsWith('title', 'The')) + .select('title') + .sort(Field.of('title').ascending()) + .execute(); + expectResults( + results, + {title: 'The Great Gatsby'}, + {title: "The Handmaid's Tale"}, + {title: "The Hitchhiker's Guide to the Galaxy"}, + {title: 'The Lord of the Rings'} + ); + }); + + it('testEndsWith', async () => { + const results = await randomCol + .pipeline() + .where(endsWith('title', 'y')) + .select('title') + .sort(Field.of('title').descending()) + .execute(); + expectResults( + results, + {title: "The Hitchhiker's Guide to the Galaxy"}, + {title: 'The Great Gatsby'} + ); + }); + + it('testLength', async () => { + const results = await randomCol + .pipeline() + .select(Field.of('title').length().as('titleLength'), Field.of('title')) + .where(gt('titleLength', 20)) + .execute(); + expectResults( + results, + {titleLength: 32, title: "The Hitchhiker's Guide to the Galaxy"}, + { + titleLength: 27, + title: 'One Hundred Years of Solitude', + } + ); + }); + + it('testToLowercase', async () => { + const results = await randomCol + .pipeline() + .select(Field.of('title').toLowercase().as('lowercaseTitle')) + .limit(1) + .execute(); + expectResults(results, { + lowercaseTitle: "the hitchhiker's guide to the galaxy", + }); + }); + + it('testToUppercase', async () => { + const results = await randomCol + .pipeline() + .select(Field.of('author').toUppercase().as('uppercaseAuthor')) + .limit(1) + .execute(); + expectResults(results, {uppercaseAuthor: 'DOUGLAS ADAMS'}); + }); + + it('testTrim', async () => { + const results = await randomCol + .pipeline() + .addFields(strConcat(' ', Field.of('title'), ' ').as('spacedTitle')) + .select( + Field.of('spacedTitle').trim().as('trimmedTitle'), + Field.of('spacedTitle') + ) + .limit(1) + .execute(); + expectResults(results, { + spacedTitle: " The Hitchhiker's Guide to the Galaxy ", + trimmedTitle: "The Hitchhiker's Guide to the Galaxy", + }); + }); + + it('testLike', async () => { + const results = await randomCol + .pipeline() + .where(like('title', '%Guide%')) + .select('title') + .execute(); + expectResults(results, {title: "The Hitchhiker's Guide to the Galaxy"}); + }); + + it('testRegexContains', async () => { + const results = await randomCol + .pipeline() + .where(regexContains('title', '(?i)(the|of)')) + .execute(); + expect(results.length).to.equal(5); + }); + + it('testRegexMatches', async () => { + const results = await randomCol + .pipeline() + .where(regexMatch('title', '.*(?i)(the|of).*')) + .execute(); + expect(results.length).to.equal(5); + }); + + it('testArithmeticOperations', async () => { + const results = await randomCol + .pipeline() + .select( + add(Field.of('rating'), 1).as('ratingPlusOne'), + subtract(Field.of('published'), 1900).as('yearsSince1900'), + Field.of('rating').multiply(10).as('ratingTimesTen'), + Field.of('rating').divide(2).as('ratingDividedByTwo') + ) + .limit(1) + .execute(); + expectResults(results, { + ratingPlusOne: 5.2, + yearsSince1900: 79, + ratingTimesTen: 42, + ratingDividedByTwo: 2.1, + }); + }); + + it('testComparisonOperators', async () => { + const results = await randomCol + .pipeline() + .where( + and( + gt('rating', 4.2), + lt(Field.of('rating'), 4.5), + neq('genre', 'Science Fiction') + ) + ) + .select('rating', 'title') + .sort(Field.of('title').ascending()) + .execute(); + expectResults( + results, + {rating: 4.3, title: 'Crime and Punishment'}, + { + rating: 4.3, + title: 'One Hundred Years of Solitude', + }, + {rating: 4.5, title: 'Pride and Prejudice'} + ); + }); + + it('testLogicalOperators', async () => { + const results = await randomCol + .pipeline() + .where( + or( + and(gt('rating', 4.5), eq('genre', 'Science Fiction')), + lt('published', 1900) + ) + ) + .select('title') + .sort(Field.of('title').ascending()) + .execute(); + expectResults( + results, + {title: 'Crime and Punishment'}, + {title: 'Dune'}, + {title: 'Pride and Prejudice'} + ); + }); + + it('testChecks', async () => { + const results = await randomCol + .pipeline() + .where(not(Field.of('rating').isNaN())) + .select( + isNull('rating').as('ratingIsNull'), + not(Field.of('rating').isNaN()).as('ratingIsNotNaN') + ) + .limit(1) + .execute(); + expectResults(results, {ratingIsNull: false, ratingIsNotNaN: true}); + }); + + it('testMapGet', async () => { + const results = await randomCol + .pipeline() + .select( + Field.of('awards').mapGet('hugo').as('hugoAward'), + Field.of('title') + ) + .where(eq('hugoAward', true)) + .execute(); + expectResults( + results, + {hugoAward: true, title: "The Hitchhiker's Guide to the Galaxy"}, + {hugoAward: true, title: 'Dune'} + ); + }); + + // it('testParent', async () => { + // const results = await randomCol + // .pipeline() + // .select( + // parent(randomCol.doc('chile').collection('subCollection').path).as( + // 'parent' + // ) + // ) + // .limit(1) + // .execute(); + // expect(results[0].data().parent.endsWith('/books')).to.be.true; + // }); + // + // it('testCollectionId', async () => { + // const results = await randomCol + // .pipeline() + // .select(collectionId(randomCol.doc('chile')).as('collectionId')) + // .limit(1) + // .execute(); + // expectResults(results, {collectionId: 'books'}); + // }); + + it('testDistanceFunctions', async () => { + const sourceVector = [0.1, 0.1]; + const targetVector = [0.5, 0.8]; + const results = await randomCol + .pipeline() + .select( + cosineDistance(Constant.ofVector(sourceVector), targetVector).as( + 'cosineDistance' + ), + dotProductDistance(Constant.ofVector(sourceVector), targetVector).as( + 'dotProductDistance' + ), + euclideanDistance(Constant.ofVector(sourceVector), targetVector).as( + 'euclideanDistance' + ) + ) + .limit(1) + .execute(); + + expectResults(results, { + cosineDistance: 0.02560880430538015, + dotProductDistance: 0.13, + euclideanDistance: 0.806225774829855, + }); + }); + + it('testNestedFields', async () => { + const results = await randomCol + .pipeline() + .where(eq('awards.hugo', true)) + .select('title', 'awards.hugo') + .execute(); + expectResults( + results, + {title: "The Hitchhiker's Guide to the Galaxy", 'awards.hugo': true}, + {title: 'Dune', 'awards.hugo': true} + ); + }); }); diff --git a/dev/system-test/query.ts b/dev/system-test/query.ts index efc42be03..cc0b877d2 100644 --- a/dev/system-test/query.ts +++ b/dev/system-test/query.ts @@ -23,7 +23,7 @@ import {verifyInstance} from '../test/util/helpers'; import {DeferredPromise, getTestRoot} from './firestore'; import {IndexTestHelper} from './index_test_helper'; -describe.only('Query class', () => { +describe('Query class', () => { interface PaginatedResults { pages: number; docs: QueryDocumentSnapshot[]; @@ -101,7 +101,7 @@ describe.only('Query class', () => { async function compareQueryAndPipeline(query: Query): Promise { const queryResults = await query.get(); - const pipeline = query.toPipeline(); + const pipeline = query.pipeline(); const pipelineResults = await pipeline.execute(); expect(pipelineResults.map(r => r._fieldsProto)).to.deep.equal( @@ -204,7 +204,7 @@ describe.only('Query class', () => { }); }); - it.skip('supports findNearest by EUCLIDEAN distance', async () => { + it('supports findNearest by EUCLIDEAN distance', async () => { const indexTestHelper = new IndexTestHelper(firestore); const collectionReference = await indexTestHelper.createTestDocs([ @@ -234,7 +234,7 @@ describe.only('Query class', () => { .be.true; }); - it.skip('supports findNearest by COSINE distance', async () => { + it('supports findNearest by COSINE distance', async () => { const indexTestHelper = new IndexTestHelper(firestore); const collectionReference = await indexTestHelper.setTestDocs({ @@ -276,7 +276,7 @@ describe.only('Query class', () => { ).to.be.true; }); - it.skip('supports findNearest by DOT_PRODUCT distance', async () => { + it('supports findNearest by DOT_PRODUCT distance', async () => { const indexTestHelper = new IndexTestHelper(firestore); const collectionReference = await indexTestHelper.createTestDocs([ @@ -306,7 +306,7 @@ describe.only('Query class', () => { .be.true; }); - it.skip('findNearest works with converters', async () => { + it('findNearest works with converters', async () => { const indexTestHelper = new IndexTestHelper(firestore); class FooDistance { @@ -346,7 +346,7 @@ describe.only('Query class', () => { expect(res.docs[0].data().embedding).to.deep.equal([5, 5]); }); - it.skip('supports findNearest skipping fields of wrong types', async () => { + it('supports findNearest skipping fields of wrong types', async () => { const indexTestHelper = new IndexTestHelper(firestore); const collectionRef = await indexTestHelper.createTestDocs([ @@ -381,7 +381,7 @@ describe.only('Query class', () => { .to.be.true; }); - it.skip('findNearest ignores mismatching dimensions', async () => { + it('findNearest ignores mismatching dimensions', async () => { const indexTestHelper = new IndexTestHelper(firestore); const collectionRef = await indexTestHelper.createTestDocs([ @@ -411,7 +411,7 @@ describe.only('Query class', () => { .be.true; }); - it.skip('supports findNearest on non-existent field', async () => { + it('supports findNearest on non-existent field', async () => { const indexTestHelper = new IndexTestHelper(firestore); const collectionRef = await indexTestHelper.createTestDocs([ @@ -434,7 +434,7 @@ describe.only('Query class', () => { expect(res.size).to.equal(0); }); - it.skip('supports findNearest on vector nested in a map', async () => { + it('supports findNearest on vector nested in a map', async () => { const indexTestHelper = new IndexTestHelper(firestore); const collectionReference = await indexTestHelper.createTestDocs([ @@ -498,7 +498,7 @@ describe.only('Query class', () => { res.docs.forEach(ds => expect(ds.get('embedding')).to.be.undefined); }); - it.skip('supports findNearest limits', async () => { + it('supports findNearest limits', async () => { const indexTestHelper = new IndexTestHelper(firestore); const embeddingVector = []; @@ -583,7 +583,7 @@ describe.only('Query class', () => { expectDocs(res, {count: 2}, {count: 3}); }); - it.skip('supports not-in', async () => { + it('supports not-in', async () => { await addDocs( {zip: 98101}, {zip: 91102}, @@ -645,7 +645,7 @@ describe.only('Query class', () => { expectDocs(res, {zip: 98101}, {zip: 98103}); }); - it.only('supports "in" with document ID array', async () => { + it('supports "in" with document ID array', async () => { const refs = await addDocs({count: 1}, {count: 2}, {count: 3}); const res = await compareQueryAndPipeline( randomCol.where(FieldPath.documentId(), 'in', [refs[0].id, refs[1]]) @@ -680,7 +680,7 @@ describe.only('Query class', () => { ); }); - it.skip('can query by FieldPath.documentId()', () => { + it('can query by FieldPath.documentId()', () => { const ref = randomCol.doc('foo'); return ref @@ -695,7 +695,7 @@ describe.only('Query class', () => { }); }); - it.skip('has orderBy() method', async () => { + it('has orderBy() method', async () => { await addDocs({foo: 'a'}, {foo: 'b'}); let res = await compareQueryAndPipeline(randomCol.orderBy('foo')); @@ -739,7 +739,7 @@ describe.only('Query class', () => { expect(received).to.equal(0); }); - it.skip('has limit() method on get()', async () => { + it('has limit() method on get()', async () => { await addDocs({foo: 'a'}, {foo: 'b'}); const res = await compareQueryAndPipeline( randomCol.orderBy('foo').limit(1) @@ -760,7 +760,7 @@ describe.only('Query class', () => { expect(received).to.equal(1); }); - it.skip('can run limit(num), where num is larger than the collection size on get()', async () => { + it('can run limit(num), where num is larger than the collection size on get()', async () => { await addDocs({foo: 'a'}, {foo: 'b'}); const res = await compareQueryAndPipeline( randomCol.orderBy('foo').limit(3) @@ -781,7 +781,7 @@ describe.only('Query class', () => { expect(received).to.equal(2); }); - it.skip('has limitToLast() method', async () => { + it('has limitToLast() method', async () => { await addDocs({doc: 1}, {doc: 2}, {doc: 3}); // const res = await compareQueryAndPipeline(randomCol.orderBy('doc').limitToLast(2)); const res = await randomCol.orderBy('doc').limitToLast(2).get(); @@ -790,13 +790,16 @@ describe.only('Query class', () => { it('limitToLast() supports Query cursors', async () => { await addDocs({doc: 1}, {doc: 2}, {doc: 3}, {doc: 4}, {doc: 5}); - const res = await compareQueryAndPipeline( - randomCol.orderBy('doc').startAt(2).endAt(4).limitToLast(5) - ); + const res = await randomCol + .orderBy('doc') + .startAt(2) + .endAt(4) + .limitToLast(5) + .get(); expectDocs(res, {doc: 2}, {doc: 3}, {doc: 4}); }); - it.skip('can use offset() method with get()', async () => { + it('can use offset() method with get()', async () => { await addDocs({foo: 'a'}, {foo: 'b'}); const res = await compareQueryAndPipeline( randomCol.orderBy('foo').offset(1) @@ -817,7 +820,7 @@ describe.only('Query class', () => { expect(received).to.equal(1); }); - it.skip('can run offset(num), where num is larger than the collection size on get()', async () => { + it('can run offset(num), where num is larger than the collection size on get()', async () => { await addDocs({foo: 'a'}, {foo: 'b'}); const res = await compareQueryAndPipeline( randomCol.orderBy('foo').offset(3) @@ -961,7 +964,7 @@ describe.only('Query class', () => { expect(received).to.equal(2); }); - it.skip('can query collection groups', async () => { + it('can query collection groups', async () => { // Use `randomCol` to get a random collection group name to use but ensure // it starts with 'b' for predictable ordering. const collectionGroup = 'b' + randomCol.id; @@ -1170,7 +1173,7 @@ describe.only('Query class', () => { // Skip this test if running against production because it results in a 'missing index' error. // The Firestore Emulator, however, does serve these queries. - (process.env.FIRESTORE_EMULATOR_HOST === undefined ? it.skip : it)( + (process.env.FIRESTORE_EMULATOR_HOST === undefined ? it : it)( 'supports OR queries with composite indexes', async () => { const collection = await testCollectionWithDocs({ @@ -1277,7 +1280,7 @@ describe.only('Query class', () => { // Skip this test if running against production because it results in a 'missing index' error. // The Firestore Emulator, however, does serve these queries. - (process.env.FIRESTORE_EMULATOR_HOST === undefined ? it.skip : it)( + (process.env.FIRESTORE_EMULATOR_HOST === undefined ? it : it)( 'supports OR queries on documents with missing fields', async () => { const collection = await testCollectionWithDocs({ @@ -1373,7 +1376,7 @@ describe.only('Query class', () => { // Skip this test if running against production because it results in a 'missing index' error. // The Firestore Emulator, however, does serve these queries. - (process.env.FIRESTORE_EMULATOR_HOST === undefined ? it.skip : it)( + (process.env.FIRESTORE_EMULATOR_HOST === undefined ? it : it)( 'supports OR queries with not-in', async () => { const collection = await testCollectionWithDocs({ @@ -1786,7 +1789,7 @@ describe.only('Query class', () => { }); (process.env.FIRESTORE_EMULATOR_HOST === undefined - ? describe.skip + ? describe : describe.only)('multiple inequality', () => { it('supports multiple inequality queries', async () => { const collection = await testCollectionWithDocs({ From a514c652197ee8ed730a9658bad3cd6de7181dae Mon Sep 17 00:00:00 2001 From: Wu-Hui Date: Thu, 22 Aug 2024 10:37:31 -0400 Subject: [PATCH 05/60] Fix routing headers --- dev/src/expression.ts | 2917 +++++++++++++++++++++++++++++++- dev/src/pipeline-util.ts | 4 +- dev/src/pipeline.ts | 567 +++++-- dev/src/reference/query.ts | 2 +- dev/src/stage.ts | 10 +- dev/src/v1/firestore_client.ts | 2 +- dev/system-test/pipeline.ts | 3 +- 7 files changed, 3273 insertions(+), 232 deletions(-) diff --git a/dev/src/expression.ts b/dev/src/expression.ts index 32ab6f6f1..3fde72f9d 100644 --- a/dev/src/expression.ts +++ b/dev/src/expression.ts @@ -12,23 +12,45 @@ import {DocumentReference} from './reference/document-reference'; import {Serializer} from './serializer'; import {Timestamp} from './timestamp'; +/** + * An interface that represents a selectable expression. + */ export interface Selectable { selectable: true; } +/** + * An interface that represents a filter condition. + */ export interface FilterCondition { filterable: true; } +/** + * An interface that represents an accumulator. + */ export interface Accumulator { accumulator: true; } + +/** + * An accumulator target, which is an expression with an alias that also implements the Accumulator interface. + */ export type AccumulatorTarget = ExprWithAlias; +/** + * A filter expression, which is an expression that also implements the FilterCondition interface. + */ export type FilterExpr = Expr & FilterCondition; +/** + * A selectable expression, which is an expression that also implements the Selectable interface. + */ export type SelectableExpr = Expr & Selectable; +/** + * An enumeration of the different types of expressions. + */ export type ExprType = | 'Field' | 'Constant' @@ -36,8 +58,46 @@ export type ExprType = | 'ListOfExprs' | 'ExprWithAlias'; +/** + * Represents an expression that can be evaluated to a value within the execution of a {@link + * 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. + * - **Aggregations:** Calculate aggregate values (e.g., sum, average) over a set of documents. + * + * The `Expr` class provides a fluent API for building expressions. You can chain together + * method calls to create complex expressions. + */ export abstract class Expr { + /** + * Creates an expression that adds this expression to another expression. + * + * ```typescript + * // Add the value of the 'quantity' field and the 'reserve' field. + * Field.of("quantity").add(Field.of("reserve")); + * ``` + * + * @param other The expression to add to this expression. + * @return A new `Expr` representing the addition operation. + */ add(other: Expr): Add; + + /** + * Creates an expression that adds this expression to a constant value. + * + * ```typescript + * // Add 5 to the value of the 'age' field + * Field.of("age").add(5); + * ``` + * + * @param other The constant value to add. + * @return A new `Expr` representing the addition operation. + */ add(other: any): Add; add(other: any): Add { if (other instanceof Expr) { @@ -46,7 +106,30 @@ export abstract class Expr { return new Add(this, Constant.of(other)); } + /** + * Creates an expression that subtracts another expression from this expression. + * + * ```typescript + * // Subtract the 'discount' field from the 'price' field + * Field.of("price").subtract(Field.of("discount")); + * ``` + * + * @param other The expression to subtract from this expression. + * @return A new `Expr` representing the subtraction operation. + */ subtract(other: Expr): Subtract; + + /** + * Creates an expression that subtracts a constant value from this expression. + * + * ```typescript + * // Subtract 20 from the value of the 'total' field + * Field.of("total").subtract(20); + * ``` + * + * @param other The constant value to subtract. + * @return A new `Expr` representing the subtraction operation. + */ subtract(other: any): Subtract; subtract(other: any): Subtract { if (other instanceof Expr) { @@ -55,7 +138,30 @@ export abstract class Expr { return new Subtract(this, Constant.of(other)); } + /** + * Creates an expression that multiplies this expression by another expression. + * + * ```typescript + * // Multiply the 'quantity' field by the 'price' field + * Field.of("quantity").multiply(Field.of("price")); + * ``` + * + * @param other The expression to multiply by. + * @return A new `Expr` representing the multiplication operation. + */ multiply(other: Expr): Multiply; + + /** + * Creates an expression that multiplies this expression by a constant value. + * + * ```typescript + * // Multiply the 'value' field by 2 + * Field.of("value").multiply(2); + * ``` + * + * @param other The constant value to multiply by. + * @return A new `Expr` representing the multiplication operation. + */ multiply(other: any): Multiply; multiply(other: any): Multiply { if (other instanceof Expr) { @@ -64,7 +170,30 @@ export abstract class Expr { return new Multiply(this, Constant.of(other)); } + /** + * Creates an expression that divides this expression by another expression. + * + * ```typescript + * // Divide the 'total' field by the 'count' field + * Field.of("total").divide(Field.of("count")); + * ``` + * + * @param other The expression to divide by. + * @return A new `Expr` representing the division operation. + */ divide(other: Expr): Divide; + + /** + * Creates an expression that divides this expression by a constant value. + * + * ```typescript + * // Divide the 'value' field by 10 + * Field.of("value").divide(10); + * ``` + * + * @param other The constant value to divide by. + * @return A new `Expr` representing the division operation. + */ divide(other: any): Divide; divide(other: any): Divide { if (other instanceof Expr) { @@ -73,7 +202,30 @@ export abstract class Expr { return new Divide(this, Constant.of(other)); } + /** + * Creates an expression that checks if this expression is equal to another expression. + * + * ```typescript + * // Check if the 'age' field is equal to 21 + * Field.of("age").eq(21); + * ``` + * + * @param other The expression to compare for equality. + * @return A new `Expr` representing the equality comparison. + */ eq(other: Expr): Eq; + + /** + * Creates an expression that checks if this expression is equal to a constant value. + * + * ```typescript + * // Check if the 'city' field is equal to "London" + * Field.of("city").eq("London"); + * ``` + * + * @param other The constant value to compare for equality. + * @return A new `Expr` representing the equality comparison. + */ eq(other: any): Eq; eq(other: any): Eq { if (other instanceof Expr) { @@ -82,7 +234,30 @@ export abstract class Expr { return new Eq(this, Constant.of(other)); } + /** + * Creates an expression that checks if this expression is not equal to another expression. + * + * ```typescript + * // Check if the 'status' field is not equal to "completed" + * Field.of("status").neq("completed"); + * ``` + * + * @param other The expression to compare for inequality. + * @return A new `Expr` representing the inequality comparison. + */ neq(other: Expr): Neq; + + /** + * Creates an expression that checks if this expression is not equal to a constant value. + * + * ```typescript + * // Check if the 'country' field is not equal to "USA" + * Field.of("country").neq("USA"); + * ``` + * + * @param other The constant value to compare for inequality. + * @return A new `Expr` representing the inequality comparison. + */ neq(other: any): Neq; neq(other: any): Neq { if (other instanceof Expr) { @@ -91,7 +266,30 @@ export abstract class Expr { return new Neq(this, Constant.of(other)); } + /** + * Creates an expression that checks if this expression is less than another expression. + * + * ```typescript + * // Check if the 'age' field is less than 'limit' + * Field.of("age").lt(Field.of('limit')); + * ``` + * + * @param other The expression to compare for less than. + * @return A new `Expr` representing the less than comparison. + */ lt(other: Expr): Lt; + + /** + * Creates an expression that checks if this expression is less than a constant value. + * + * ```typescript + * // Check if the 'price' field is less than 50 + * Field.of("price").lt(50); + * ``` + * + * @param other The constant value to compare for less than. + * @return A new `Expr` representing the less than comparison. + */ lt(other: any): Lt; lt(other: any): Lt { if (other instanceof Expr) { @@ -100,7 +298,31 @@ export abstract class Expr { return new Lt(this, Constant.of(other)); } + /** + * Creates an expression that checks if this expression is less than or equal to another + * expression. + * + * ```typescript + * // Check if the 'quantity' field is less than or equal to 20 + * Field.of("quantity").lte(Constant.of(20)); + * ``` + * + * @param other The expression to compare for less than or equal to. + * @return A new `Expr` representing the less than or equal to comparison. + */ lte(other: Expr): Lte; + + /** + * Creates an expression that checks if this expression is less than or equal to a constant value. + * + * ```typescript + * // Check if the 'score' field is less than or equal to 70 + * Field.of("score").lte(70); + * ``` + * + * @param other The constant value to compare for less than or equal to. + * @return A new `Expr` representing the less than or equal to comparison. + */ lte(other: any): Lte; lte(other: any): Lte { if (other instanceof Expr) { @@ -109,7 +331,30 @@ export abstract class Expr { return new Lte(this, Constant.of(other)); } + /** + * Creates an expression that checks if this expression is greater than another expression. + * + * ```typescript + * // Check if the 'age' field is greater than the 'limit' field + * Field.of("age").gt(Field.of("limit")); + * ``` + * + * @param other The expression to compare for greater than. + * @return A new `Expr` representing the greater than comparison. + */ gt(other: Expr): Gt; + + /** + * Creates an expression that checks if this expression is greater than a constant value. + * + * ```typescript + * // Check if the 'price' field is greater than 100 + * Field.of("price").gt(100); + * ``` + * + * @param other The constant value to compare for greater than. + * @return A new `Expr` representing the greater than comparison. + */ gt(other: any): Gt; gt(other: any): Gt { if (other instanceof Expr) { @@ -118,7 +363,32 @@ export abstract class Expr { return new Gt(this, Constant.of(other)); } + /** + * Creates an expression that checks if this expression is greater than or equal to another + * expression. + * + * ```typescript + * // Check if the 'quantity' field is greater than or equal to field 'requirement' plus 1 + * Field.of("quantity").gte(Field.of('requirement').add(1)); + * ``` + * + * @param other The expression to compare for greater than or equal to. + * @return A new `Expr` representing the greater than or equal to comparison. + */ gte(other: Expr): Gte; + + /** + * Creates an expression that checks if this expression is greater than or equal to a constant + * value. + * + * ```typescript + * // Check if the 'score' field is greater than or equal to 80 + * Field.of("score").gte(80); + * ``` + * + * @param other The constant value to compare for greater than or equal to. + * @return A new `Expr` representing the greater than or equal to comparison. + */ gte(other: any): Gte; gte(other: any): Gte { if (other instanceof Expr) { @@ -127,7 +397,30 @@ export abstract class Expr { return new Gte(this, Constant.of(other)); } + /** + * Creates an expression that concatenates an array expression with one or more other arrays. + * + * ```typescript + * // Combine the 'items' array with another array field. + * Field.of("items").arrayConcat(Field.of("otherItems")); + * ``` + * + * @param values The array expressions to concatenate. + * @return A new `Expr` representing the concatenated array. + */ arrayConcat(...values: Expr[]): ArrayConcat; + + /** + * Creates an expression that concatenates an array expression with one or more other arrays. + * + * ```typescript + * // Combine the 'tags' array with a new array and an array field + * Field.of("tags").arrayConcat(Arrays.asList("newTag1", "newTag2"), Field.of("otherTag")); + * ``` + * + * @param values The array expressions or values to concatenate. + * @return A new `Expr` representing the concatenated array. + */ arrayConcat(...values: any[]): ArrayConcat; arrayConcat(...values: any[]): ArrayConcat { const exprValues = values.map(value => @@ -136,7 +429,30 @@ export abstract class Expr { return new ArrayConcat(this, exprValues); } + /** + * Creates an expression that checks if an array contains a specific element. + * + * ```typescript + * // Check if the 'sizes' array contains the value from the 'selectedSize' field + * Field.of("sizes").arrayContains(Field.of("selectedSize")); + * ``` + * + * @param element The element to search for in the array. + * @return A new `Expr` representing the 'array_contains' comparison. + */ arrayContains(element: Expr): ArrayContains; + + /** + * Creates an expression that checks if an array contains a specific value. + * + * ```typescript + * // Check if the 'colors' array contains "red" + * Field.of("colors").arrayContains("red"); + * ``` + * + * @param element The element to search for in the array. + * @return A new `Expr` representing the 'array_contains' comparison. + */ arrayContains(element: any): ArrayContains; arrayContains(element: any): ArrayContains { if (element instanceof Expr) { @@ -145,7 +461,30 @@ export abstract class Expr { return new ArrayContains(this, Constant.of(element)); } + /** + * Creates an expression that checks if an array contains all the specified elements. + * + * ```typescript + * // Check if the 'tags' array contains both "news" and "sports" + * Field.of("tags").arrayContainsAll(Field.of("tag1"), Field.of("tag2")); + * ``` + * + * @param values The elements to check for in the array. + * @return A new `Expr` representing the 'array_contains_all' comparison. + */ arrayContainsAll(...values: Expr[]): ArrayContainsAll; + + /** + * Creates an expression that checks if an array contains all the specified elements. + * + * ```typescript + * // Check if the 'tags' array contains both of the values from field 'tag1' and "tag2" + * Field.of("tags").arrayContainsAll(Field.of("tag1"), Field.of("tag2")); + * ``` + * + * @param values The elements to check for in the array. + * @return A new `Expr` representing the 'array_contains_all' comparison. + */ arrayContainsAll(...values: any[]): ArrayContainsAll; arrayContainsAll(...values: any[]): ArrayContainsAll { const exprValues = values.map(value => @@ -154,7 +493,31 @@ export abstract class Expr { return new ArrayContainsAll(this, exprValues); } + /** + * Creates an expression that checks if an array contains any of the specified elements. + * + * ```typescript + * // Check if the 'categories' array contains either values from field "cate1" or "cate2" + * Field.of("categories").arrayContainsAny(Field.of("cate1"), Field.of("cate2")); + * ``` + * + * @param values The elements to check for in the array. + * @return A new `Expr` representing the 'array_contains_any' comparison. + */ arrayContainsAny(...values: Expr[]): ArrayContainsAny; + + /** + * Creates an expression that checks if an array contains any of the specified elements. + * + * ```typescript + * // Check if the 'groups' array contains either the value from the 'userGroup' field + * // or the value "guest" + * Field.of("groups").arrayContainsAny(Field.of("userGroup"), "guest"); + * ``` + * + * @param values The elements to check for in the array. + * @return A new `Expr` representing the 'array_contains_any' comparison. + */ arrayContainsAny(...values: any[]): ArrayContainsAny; arrayContainsAny(...values: any[]): ArrayContainsAny { const exprValues = values.map(value => @@ -163,19 +526,80 @@ export abstract class Expr { return new ArrayContainsAny(this, exprValues); } + /** + * Creates an expression that filters elements from an array using the given {@link + * FilterCondition} and returns the filtered elements as a new array. + * + * ```typescript + * // Get items from the 'inventoryPrices' array where the array item is greater than 0 + * // Note we use {@link Function#arrayElement} to represent array elements to construct a + * // filtering condition. + * Field.of("inventoryPrices").arrayFilter(arrayElement().gt(0)); + * ``` + * + * @param filter The {@link FilterCondition} to apply to the array elements. + * @return A new `Expr` representing the filtered array. + */ arrayFilter(filter: FilterExpr): ArrayFilter { return new ArrayFilter(this, filter); } + /** + * Creates an expression that calculates the length of an array. + * + * ```typescript + * // Get the number of items in the 'cart' array + * Field.of("cart").arrayLength(); + * ``` + * + * @return A new `Expr` representing the length of the array. + */ arrayLength(): ArrayLength { return new ArrayLength(this); } + /** + * Creates an expression that applies a transformation function to each element in an array and + * returns the new array as the result of the evaluation. + * + * ```typescript + * // Convert all strings in the 'names' array to uppercase + * Field.of("names").arrayTransform(arrayElement().toUppercase()); + * ``` + * + * @param transform The {@link Function} to apply to each array element. + * @return A new `Expr` representing the transformed array. + */ arrayTransform(transform: Function): ArrayTransform { return new ArrayTransform(this, transform); } + /** + * Creates an expression that checks if this expression is equal to any of the provided values or + * expressions. + * + * ```typescript + * // Check if the 'category' field is either "Electronics" or value of field 'primaryType' + * Field.of("category").in("Electronics", Field.of("primaryType")); + * ``` + * + * @param others The values or expressions to check against. + * @return A new `Expr` representing the 'IN' comparison. + */ in(...others: Expr[]): In; + + /** + * Creates an expression that checks if this expression is equal to any of the provided values or + * expressions. + * + * ```typescript + * // Check if the 'category' field is either "Electronics" or value of field 'primaryType' + * Field.of("category").in("Electronics", Field.of("primaryType")); + * ``` + * + * @param others The values or expressions to check against. + * @return A new `Expr` representing the 'IN' comparison. + */ in(...others: any[]): In; in(...others: any[]): In { const exprOthers = others.map(other => @@ -184,23 +608,72 @@ export abstract class Expr { return new In(this, exprOthers); } + /** + * Creates an expression that checks if this expression evaluates to 'NaN' (Not a Number). + * + * ```typescript + * // Check if the result of a calculation is NaN + * Field.of("value").divide(0).isNaN(); + * ``` + * + * @return A new `Expr` representing the 'isNaN' check. + */ isNaN(): IsNan { return new IsNan(this); } - isNull(): IsNull { - return new IsNull(this); - } - + /** + * Creates an expression that checks if a field exists in the document. + * + * ```typescript + * // Check if the document has a field named "phoneNumber" + * Field.of("phoneNumber").exists(); + * ``` + * + * @return A new `Expr` representing the 'exists' check. + */ exists(): Exists { return new Exists(this); } + /** + * Creates an expression that calculates the length of a string. + * + * ```typescript + * // Get the length of the 'name' field + * Field.of("name").length(); + * ``` + * + * @return A new `Expr` representing the length of the string. + */ length(): Length { return new Length(this); } + /** + * Creates an expression that performs a case-sensitive string comparison. + * + * ```typescript + * // Check if the 'title' field contains the word "guide" (case-sensitive) + * Field.of("title").like("%guide%"); + * ``` + * + * @param pattern The pattern to search for. You can use "%" as a wildcard character. + * @return A new `Expr` representing the 'like' comparison. + */ like(pattern: string): Like; + + /** + * Creates an expression that performs a case-sensitive string comparison. + * + * ```typescript + * // Check if the 'title' field contains the word "guide" (case-sensitive) + * Field.of("title").like("%guide%"); + * ``` + * + * @param pattern The pattern to search for. You can use "%" as a wildcard character. + * @return A new `Expr` representing the 'like' comparison. + */ like(pattern: Expr): Like; like(stringOrExpr: string | Expr): Like { if (stringOrExpr instanceof Expr) { @@ -209,7 +682,32 @@ export abstract class Expr { return new Like(this, Constant.of(stringOrExpr)); } + /** + * Creates an expression that checks if a string contains a specified regular expression as a + * substring. + * + * ```typescript + * // Check if the 'description' field contains "example" (case-insensitive) + * Field.of("description").regexContains("(?i)example"); + * ``` + * + * @param pattern The regular expression to use for the search. + * @return A new `Expr` representing the 'contains' comparison. + */ regexContains(pattern: string): RegexContains; + + /** + * Creates an expression that checks if a string contains a specified regular expression as a + * substring. + * + * ```typescript + * // Check if the 'description' field contains the regular expression stored in field 'regex' + * Field.of("description").regexContains(Field.of("regex")); + * ``` + * + * @param pattern The regular expression to use for the search. + * @return A new `Expr` representing the 'contains' comparison. + */ regexContains(pattern: Expr): RegexContains; regexContains(stringOrExpr: string | Expr): RegexContains { if (stringOrExpr instanceof Expr) { @@ -218,7 +716,30 @@ export abstract class Expr { return new RegexContains(this, Constant.of(stringOrExpr)); } + /** + * Creates an expression that checks if a string matches a specified regular expression. + * + * ```typescript + * // Check if the 'email' field matches a valid email pattern + * Field.of("email").regexMatch("[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,}"); + * ``` + * + * @param pattern The regular expression to use for the match. + * @return A new `Expr` representing the regular expression match. + */ regexMatch(pattern: string): RegexMatch; + + /** + * Creates an expression that checks if a string matches a specified regular expression. + * + * ```typescript + * // Check if the 'email' field matches a regular expression stored in field 'regex' + * Field.of("email").regexMatch(Field.of("regex")); + * ``` + * + * @param pattern The regular expression to use for the match. + * @return A new `Expr` representing the regular expression match. + */ regexMatch(pattern: Expr): RegexMatch; regexMatch(stringOrExpr: string | Expr): RegexMatch { if (stringOrExpr instanceof Expr) { @@ -227,7 +748,31 @@ export abstract class Expr { return new RegexMatch(this, Constant.of(stringOrExpr)); } + /** + * Creates an expression that checks if a string starts with a given prefix. + * + * ```typescript + * // Check if the 'name' field starts with "Mr." + * Field.of("name").startsWith("Mr."); + * ``` + * + * @param prefix The prefix to check for. + * @return A new `Expr` representing the 'starts with' comparison. + */ startsWith(prefix: string): StartsWith; + + /** + * Creates an expression that checks if a string starts with a given prefix (represented as an + * expression). + * + * ```typescript + * // Check if the 'fullName' field starts with the value of the 'firstName' field + * Field.of("fullName").startsWith(Field.of("firstName")); + * ``` + * + * @param prefix The prefix expression to check for. + * @return A new `Expr` representing the 'starts with' comparison. + */ startsWith(prefix: Expr): StartsWith; startsWith(stringOrExpr: string | Expr): StartsWith { if (stringOrExpr instanceof Expr) { @@ -236,7 +781,31 @@ export abstract class Expr { return new StartsWith(this, Constant.of(stringOrExpr)); } + /** + * Creates an expression that checks if a string ends with a given postfix. + * + * ```typescript + * // Check if the 'filename' field ends with ".txt" + * Field.of("filename").endsWith(".txt"); + * ``` + * + * @param suffix The postfix to check for. + * @return A new `Expr` representing the 'ends with' comparison. + */ endsWith(suffix: string): EndsWith; + + /** + * Creates an expression that checks if a string ends with a given postfix (represented as an + * expression). + * + * ```typescript + * // Check if the 'url' field ends with the value of the 'extension' field + * Field.of("url").endsWith(Field.of("extension")); + * ``` + * + * @param suffix The postfix expression to check for. + * @return A new `Expr` representing the 'ends with' comparison. + */ endsWith(suffix: Expr): EndsWith; endsWith(stringOrExpr: string | Expr): EndsWith { if (stringOrExpr instanceof Expr) { @@ -245,49 +814,186 @@ export abstract class Expr { return new EndsWith(this, Constant.of(stringOrExpr)); } + /** + * Creates an expression that converts a string to lowercase. + * + * ```typescript + * // Convert the 'name' field to lowercase + * Field.of("name").toLowerCase(); + * ``` + * + * @return A new `Expr` representing the lowercase string. + */ toLowercase(): ToLowercase { return new ToLowercase(this); } + /** + * Creates an expression that converts a string to uppercase. + * + * ```typescript + * // Convert the 'title' field to uppercase + * Field.of("title").toUpperCase(); + * ``` + * + * @return A new `Expr` representing the uppercase string. + */ toUppercase(): ToUppercase { return new ToUppercase(this); } + /** + * Creates an expression that removes leading and trailing whitespace from a string. + * + * ```typescript + * // Trim whitespace from the 'userInput' field + * Field.of("userInput").trim(); + * ``` + * + * @return A new `Expr` representing the trimmed string. + */ trim(): Trim { return new Trim(this); } + /** + * Creates an expression that concatenates string expressions together. + * + * ```typescript + * // Combine the 'firstName', " ", and 'lastName' fields into a single string + * Field.of("firstName").strConcat(Constant.of(" "), Field.of("lastName")); + * ``` + * + * @param elements The expressions (typically strings) to concatenate. + * @return A new `Expr` representing the concatenated string. + */ strConcat(...elements: (string | Expr)[]): StrConcat { const exprs = elements.map(e => (e instanceof Expr ? e : Constant.of(e))); return new StrConcat(this, exprs); } + /** + * Accesses a value from a map (object) field using the provided key. + * + * ```typescript + * // Get the 'city' value from the 'address' map field + * Field.of("address").mapGet("city"); + * ``` + * + * @param subfield The key to access in the map. + * @return A new `Expr` representing the value associated with the given key in the map. + */ mapGet(subfield: string): MapGet { return new MapGet(this, subfield); } + /** + * Creates an aggregation that counts the number of stage inputs with valid evaluations of the + * expression or field. + * + * ```typescript + * // Count the total number of products + * Field.of("productId").count().as("totalProducts"); + * ``` + * + * @return A new `Accumulator` representing the 'count' aggregation. + */ count(): Count { return new Count(this, false); } + /** + * Creates an aggregation that calculates the sum of a numeric field across multiple stage inputs. + * + * ```typescript + * // Calculate the total revenue from a set of orders + * Field.of("orderAmount").sum().as("totalRevenue"); + * ``` + * + * @return A new `Accumulator` representing the 'sum' aggregation. + */ sum(): Sum { return new Sum(this, false); } + /** + * Creates an aggregation that calculates the average (mean) of a numeric field across multiple + * stage inputs. + * + * ```typescript + * // Calculate the average age of users + * Field.of("age").avg().as("averageAge"); + * ``` + * + * @return A new `Accumulator` representing the 'avg' aggregation. + */ avg(): Avg { return new Avg(this, false); } + /** + * Creates an aggregation that finds the minimum value of a field across multiple stage inputs. + * + * ```typescript + * // Find the lowest price of all products + * Field.of("price").min().as("lowestPrice"); + * ``` + * + * @return A new `Accumulator` representing the 'min' aggregation. + */ min(): Min { return new Min(this, false); } + /** + * Creates an aggregation that finds the maximum value of a field across multiple stage inputs. + * + * ```typescript + * // Find the highest score in a leaderboard + * Field.of("score").max().as("highestScore"); + * ``` + * + * @return A new `Accumulator` representing the 'max' aggregation. + */ max(): Max { return new Max(this, false); } + /** + * Calculates the cosine distance between two vectors. + * + * ```typescript + * // Calculate the cosine distance between the 'userVector' field and the 'itemVector' field + * Field.of("userVector").cosineDistance(Field.of("itemVector")); + * ``` + * + * @param other The other vector (represented as an Expr) to compare against. + * @return A new `Expr` representing the cosine distance between the two vectors. + */ cosineDistance(other: Expr): CosineDistance; + /** + * Calculates the Cosine distance between two vectors. + * + * ```typescript + * // Calculate the Cosine distance between the 'location' field and a target location + * Field.of("location").cosineDistance(new VectorValue([37.7749, -122.4194])); + * ``` + * + * @param other The other vector (as a VectorValue) to compare against. + * @return A new `Expr` representing the Cosine* distance between the two vectors. + */ cosineDistance(other: VectorValue): CosineDistance; + /** + * Calculates the Cosine distance between two vectors. + * + * ```typescript + * // Calculate the Cosine distance between the 'location' field and a target location + * Field.of("location").cosineDistance([37.7749, -122.4194]); + * ``` + * + * @param other The other vector (as an array of numbers) to compare against. + * @return A new `Expr` representing the Cosine distance between the two vectors. + */ cosineDistance(other: number[]): CosineDistance; cosineDistance(other: Expr | VectorValue | number[]): CosineDistance { if (other instanceof Expr) { @@ -297,8 +1003,43 @@ export abstract class Expr { } } + /** + * Calculates the dot product distance between two vectors. + * + * ```typescript + * // Calculate the dot product distance between a feature vector and a target vector + * Field.of("features").dotProductDistance([0.5, 0.8, 0.2]); + * ``` + * + * @param other The other vector (as an array of numbers) to compare against. + * @return A new `Expr` representing the dot product distance between the two vectors. + */ dotProductDistance(other: Expr): DotProductDistance; + + /** + * Calculates the dot product distance between two vectors. + * + * ```typescript + * // Calculate the dot product distance between a feature vector and a target vector + * Field.of("features").dotProductDistance(new VectorValue([0.5, 0.8, 0.2])); + * ``` + * + * @param other The other vector (as a VectorValue) to compare against. + * @return A new `Expr` representing the dot product distance between the two vectors. + */ dotProductDistance(other: VectorValue): DotProductDistance; + + /** + * Calculates the dot product distance between two vectors. + * + * ```typescript + * // Calculate the dot product distance between a feature vector and a target vector + * Field.of("features").dotProductDistance([0.5, 0.8, 0.2]); + * ``` + * + * @param other The other vector (as an array of numbers) to compare against. + * @return A new `Expr` representing the dot product distance between the two vectors. + */ dotProductDistance(other: number[]): DotProductDistance; dotProductDistance(other: Expr | VectorValue | number[]): DotProductDistance { if (other instanceof Expr) { @@ -308,8 +1049,43 @@ export abstract class Expr { } } + /** + * Calculates the Euclidean distance between two vectors. + * + * ```typescript + * // Calculate the Euclidean distance between the 'location' field and a target location + * Field.of("location").euclideanDistance([37.7749, -122.4194]); + * ``` + * + * @param other The other vector (as an array of numbers) to compare against. + * @return A new `Expr` representing the Euclidean distance between the two vectors. + */ euclideanDistance(other: Expr): EuclideanDistance; + + /** + * Calculates the Euclidean distance between two vectors. + * + * ```typescript + * // Calculate the Euclidean distance between the 'location' field and a target location + * Field.of("location").euclideanDistance(new VectorValue([37.7749, -122.4194])); + * ``` + * + * @param other The other vector (as a VectorValue) to compare against. + * @return A new `Expr` representing the Euclidean distance between the two vectors. + */ euclideanDistance(other: VectorValue): EuclideanDistance; + + /** + * Calculates the Euclidean distance between two vectors. + * + * ```typescript + * // Calculate the Euclidean distance between the 'location' field and a target location + * Field.of("location").euclideanDistance([37.7749, -122.4194]); + * ``` + * + * @param other The other vector (as an array of numbers) to compare against. + * @return A new `Expr` representing the Euclidean distance between the two vectors. + */ euclideanDistance(other: number[]): EuclideanDistance; euclideanDistance(other: Expr | VectorValue | number[]): EuclideanDistance { if (other instanceof Expr) { @@ -319,14 +1095,52 @@ export abstract class Expr { } } + /** + * Creates an {@link Ordering} that sorts documents in ascending order based on this expression. + * + * ```typescript + * // Sort documents by the 'name' field in ascending order + * firestore.pipeline().collection("users") + * .sort(Field.of("name").ascending()); + * ``` + * + * @return A new `Ordering` for ascending sorting. + */ ascending(): Ordering { - return Ordering.ascending(this); + return ascending(this); } + /** + * Creates an {@link Ordering} that sorts documents in descending order based on this expression. + * + * ```typescript + * // Sort documents by the 'createdAt' field in descending order + * firestore.pipeline().collection("users") + * .sort(Field.of("createdAt").descending()); + * ``` + * + * @return A new `Ordering` for descending sorting. + */ descending(): Ordering { - return Ordering.descending(this); + return descending(this); } + /** + * 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. + * + * ```typescript + * // Calculate the total price and assign it the alias "totalPrice" and add it to the output. + * firestore.pipeline().collection("items") + * .addFields(Field.of("price").multiply(Field.of("quantity")).as("totalPrice")); + * ``` + * + * @param name The alias to assign to this expression. + * @return A new {@link ExprWithAlias} that wraps this + * expression and associates it with the provided alias. + */ as(name: string): ExprWithAlias { return new ExprWithAlias(this, name); } @@ -365,6 +1179,22 @@ class ListOfExprs extends Expr { } } +/** + * Represents a reference to a field in a Firestore document, or outputs of a {@link Pipeline} stage. + * + *

Field references are used to access document field values in expressions and to specify fields + * for sorting, filtering, and projecting data in Firestore pipelines. + * + *

You can create a `Field` instance using the static {@link #of} method: + * + * ```typescript + * // Create a Field instance for the 'name' field + * const nameField = Field.of("name"); + * + * // Create a Field instance for a nested field 'address.city' + * const cityField = Field.of("address.city"); + * ``` + */ export class Field extends Expr implements Selectable { exprType: ExprType = 'Field'; selectable = true as const; @@ -376,6 +1206,23 @@ export class Field extends Expr implements Selectable { super(); } + /** + * Creates a {@code Field} instance representing the field at the given path. + * + * The path can be a simple field name (e.g., "name") or a dot-separated path to a nested field + * (e.g., "address.city"). + * + * ```typescript + * // Create a Field instance for the 'title' field + * const titleField = Field.of("title"); + * + * // Create a Field instance for a nested field 'author.firstName' + * const authorFirstNameField = Field.of("author.firstName"); + * ``` + * + * @param name The path to the field. + * @return A new {@code Field} instance representing the specified field. + */ static of(name: string): Field; static of(path: firestore.FieldPath): Field; static of(nameOrPath: string | firestore.FieldPath): Field; @@ -443,6 +1290,19 @@ export class Fields extends Expr implements Selectable { } } +/** + * Represents a constant value that can be used in a Firestore pipeline expression. + * + * You can create a `Constant` instance using the static {@link #of} method: + * + * ```typescript + * // Create a Constant instance for the number 10 + * const ten = Constant.of(10); + * + * // Create a Constant instance for the string "hello" + * const hello = Constant.of("hello"); + * ``` + */ export class Constant extends Expr { exprType: ExprType = 'Constant'; @@ -450,25 +1310,140 @@ export class Constant extends Expr { super(); } + /** + * Creates a `Constant` instance for a number value. + * + * @param value The number value. + * @return A new `Constant` instance. + */ static of(value: number): Constant; + + /** + * Creates a `Constant` instance for a string value. + * + * @param value The string value. + * @return A new `Constant` instance. + */ static of(value: string): Constant; + + /** + * Creates a `Constant` instance for a boolean value. + * + * @param value The boolean value. + * @return A new `Constant` instance. + */ static of(value: boolean): Constant; + + /** + * Creates a `Constant` instance for a null value. + * + * @param value The null value. + * @return A new `Constant` instance. + */ static of(value: null): Constant; + + /** + * Creates a `Constant` instance for an undefined value. + * + * @param value The undefined value. + * @return A new `Constant` instance. + */ static of(value: undefined): Constant; + + /** + * Creates a `Constant` instance for a GeoPoint value. + * + * @param value The GeoPoint value. + * @return A new `Constant` instance. + */ static of(value: GeoPoint): Constant; + + /** + * Creates a `Constant` instance for a Timestamp value. + * + * @param value The Timestamp value. + * @return A new `Constant` instance. + */ static of(value: Timestamp): Constant; + + /** + * Creates a `Constant` instance for a Date value. + * + * @param value The Date value. + * @return A new `Constant` instance. + */ static of(value: Date): Constant; + + /** + * Creates a `Constant` instance for a Uint8Array value. + * + * @param value The Uint8Array value. + * @return A new `Constant` instance. + */ static of(value: Uint8Array): Constant; + + /** + * Creates a `Constant` instance for a DocumentReference value. + * + * @param value The DocumentReference value. + * @return A new `Constant` instance. + */ static of(value: DocumentReference): Constant; + + /** + * Creates a `Constant` instance for a Firestore proto value. + * + * @param value The Firestore proto value. + * @return A new `Constant` instance. + */ static of(value: api.IValue): Constant; + + /** + * Creates a `Constant` instance for an array value. + * + * @param value The array value. + * @return A new `Constant` instance. + */ static of(value: Array): Constant; + + /** + * Creates a `Constant` instance for a map value. + * + * @param value The map value. + * @return A new `Constant` instance. + */ static of(value: Map): Constant; + + /** + * Creates a `Constant` instance for a VectorValue value. + * + * @param value The VectorValue value. + * @return A new `Constant` instance. + */ static of(value: VectorValue): Constant; + + /** + * Creates a `Constant` instance for a Firestore proto value. + * + * @param value The Firestore proto value. + * @return A new `Constant` instance. + */ static of(value: api.IValue): Constant; static of(value: any): Constant { return new Constant(value); } + /** + * Creates a `Constant` instance for a VectorValue value. + * + * ```typescript + * // Create a Constant instance for a vector value + * const vectorConstant = Constant.ofVector([1, 2, 3]); + * ``` + * + * @param value The VectorValue value. + * @return A new `Constant` instance. + */ static ofVector(value: Array | VectorValue): Constant { if (value instanceof VectorValue) { return new Constant(value); @@ -486,6 +1461,13 @@ export class Constant extends Expr { } } +/** + * This class defines the base class for Firestore {@link 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 and}, {@link eq}, + * or the methods on {@link Expr} ({@link Expr#eq}, {@link Expr#lt}, etc) to construct new Function instances. + */ export class Function extends Expr { exprType: ExprType = 'Function'; constructor( @@ -694,13 +1676,6 @@ class Exists extends Function implements FilterCondition { filterable = true as const; } -class IsNull extends Function implements FilterCondition { - constructor(private expr: Expr) { - super('is_null', [expr]); - } - filterable = true as const; -} - class Not extends Function implements FilterCondition { constructor(private expr: Expr) { super('not', [expr]); @@ -907,9 +1882,60 @@ class EuclideanDistance extends Function { } } +/** + * Creates an expression that adds two expressions together. + * + * ```typescript + * // Add the value of the 'quantity' field and the 'reserve' field. + * add(Field.of("quantity"), Field.of("reserve")); + * ``` + * + * @param left The first expression to add. + * @param right The second expression to add. + * @return A new {@code Expr} representing the addition operation. + */ export function add(left: Expr, right: Expr): Add; + +/** + * Creates an expression that adds an expression to a constant value. + * + * ```typescript + * // Add 5 to the value of the 'age' field + * add(Field.of("age"), 5); + * ``` + * + * @param left The expression to add to. + * @param right The constant value to add. + * @return A new {@code Expr} representing the addition operation. + */ export function add(left: Expr, right: any): Add; + +/** + * Creates an expression that adds a field's value to an expression. + * + * ```typescript + * // Add the value of the 'quantity' field and the 'reserve' field. + * add("quantity", Field.of("reserve")); + * ``` + * + * @param left The field name to add to. + * @param right The expression to add. + * @return A new {@code Expr} representing the addition operation. + */ export function add(left: string, right: Expr): Add; + +/** + * Creates an expression that adds a field's value to a constant value. + * + * ```typescript + * // Add 5 to the value of the 'age' field + * add("age", 5); + * ``` + * + * @param left The field name to add to. + * @param right The constant value to add. + * @return A new {@code Expr} representing the addition operation. + */ export function add(left: string, right: any): Add; export function add(left: Expr | string, right: Expr | any): Add { const normalizedLeft = typeof left === 'string' ? Field.of(left) : left; @@ -917,9 +1943,60 @@ export function add(left: Expr | string, right: Expr | any): Add { return new Add(normalizedLeft, normalizedRight); } +/** + * Creates an expression that subtracts two expressions. + * + * ```typescript + * // Subtract the 'discount' field from the 'price' field + * subtract(Field.of("price"), Field.of("discount")); + * ``` + * + * @param left The expression to subtract from. + * @param right The expression to subtract. + * @return A new {@code Expr} representing the subtraction operation. + */ export function subtract(left: Expr, right: Expr): Subtract; + +/** + * Creates an expression that subtracts a constant value from an expression. + * + * ```typescript + * // Subtract the constant value 2 from the 'value' field + * subtract(Field.of("value"), 2); + * ``` + * + * @param left The expression to subtract from. + * @param right The constant value to subtract. + * @return A new {@code Expr} representing the subtraction operation. + */ export function subtract(left: Expr, right: any): Subtract; + +/** + * Creates an expression that subtracts an expression from a field's value. + * + * ```typescript + * // Subtract the 'discount' field from the 'price' field + * subtract("price", Field.of("discount")); + * ``` + * + * @param left The field name to subtract from. + * @param right The expression to subtract. + * @return A new {@code Expr} representing the subtraction operation. + */ export function subtract(left: string, right: Expr): Subtract; + +/** + * Creates an expression that subtracts a constant value from a field's value. + * + * ```typescript + * // Subtract 20 from the value of the 'total' field + * subtract("total", 20); + * ``` + * + * @param left The field name to subtract from. + * @param right The constant value to subtract. + * @return A new {@code Expr} representing the subtraction operation. + */ export function subtract(left: string, right: any): Subtract; export function subtract(left: Expr | string, right: Expr | any): Subtract { const normalizedLeft = typeof left === 'string' ? Field.of(left) : left; @@ -927,9 +2004,60 @@ export function subtract(left: Expr | string, right: Expr | any): Subtract { return new Subtract(normalizedLeft, normalizedRight); } +/** + * Creates an expression that multiplies two expressions together. + * + * ```typescript + * // Multiply the 'quantity' field by the 'price' field + * multiply(Field.of("quantity"), Field.of("price")); + * ``` + * + * @param left The first expression to multiply. + * @param right The second expression to multiply. + * @return A new {@code Expr} representing the multiplication operation. + */ export function multiply(left: Expr, right: Expr): Multiply; + +/** + * Creates an expression that multiplies an expression by a constant value. + * + * ```typescript + * // Multiply the value of the 'price' field by 2 + * multiply(Field.of("price"), 2); + * ``` + * + * @param left The expression to multiply. + * @param right The constant value to multiply by. + * @return A new {@code Expr} representing the multiplication operation. + */ export function multiply(left: Expr, right: any): Multiply; + +/** + * Creates an expression that multiplies a field's value by an expression. + * + * ```typescript + * // Multiply the 'quantity' field by the 'price' field + * multiply("quantity", Field.of("price")); + * ``` + * + * @param left The field name to multiply. + * @param right The expression to multiply by. + * @return A new {@code Expr} representing the multiplication operation. + */ export function multiply(left: string, right: Expr): Multiply; + +/** + * Creates an expression that multiplies a field's value by a constant value. + * + * ```typescript + * // Multiply the 'value' field by 2 + * multiply("value", 2); + * ``` + * + * @param left The field name to multiply. + * @param right The constant value to multiply by. + * @return A new {@code Expr} representing the multiplication operation. + */ export function multiply(left: string, right: any): Multiply; export function multiply(left: Expr | string, right: Expr | any): Multiply { const normalizedLeft = typeof left === 'string' ? Field.of(left) : left; @@ -937,9 +2065,60 @@ export function multiply(left: Expr | string, right: Expr | any): Multiply { return new Multiply(normalizedLeft, normalizedRight); } +/** + * Creates an expression that divides two expressions. + * + * ```typescript + * // Divide the 'total' field by the 'count' field + * divide(Field.of("total"), Field.of("count")); + * ``` + * + * @param left The expression to be divided. + * @param right The expression to divide by. + * @return A new {@code Expr} representing the division operation. + */ export function divide(left: Expr, right: Expr): Divide; + +/** + * Creates an expression that divides an expression by a constant value. + * + * ```typescript + * // Divide the 'value' field by 10 + * divide(Field.of("value"), 10); + * ``` + * + * @param left The expression to be divided. + * @param right The constant value to divide by. + * @return A new {@code Expr} representing the division operation. + */ export function divide(left: Expr, right: any): Divide; + +/** + * Creates an expression that divides a field's value by an expression. + * + * ```typescript + * // Divide the 'total' field by the 'count' field + * divide("total", Field.of("count")); + * ``` + * + * @param left The field name to be divided. + * @param right The expression to divide by. + * @return A new {@code Expr} representing the division operation. + */ export function divide(left: string, right: Expr): Divide; + +/** + * Creates an expression that divides a field's value by a constant value. + * + * ```typescript + * // Divide the 'value' field by 10 + * divide("value", 10); + * ``` + * + * @param left The field name to be divided. + * @param right The constant value to divide by. + * @return A new {@code Expr} representing the division operation. + */ export function divide(left: string, right: any): Divide; export function divide(left: Expr | string, right: Expr | any): Divide { const normalizedLeft = typeof left === 'string' ? Field.of(left) : left; @@ -947,9 +2126,60 @@ export function divide(left: Expr | string, right: Expr | any): Divide { return new Divide(normalizedLeft, normalizedRight); } +/** + * Creates an expression that checks if two expressions are equal. + * + * ```typescript + * // Check if the 'age' field is equal to an expression + * eq(Field.of("age"), Field.of("minAge").add(10)); + * ``` + * + * @param left The first expression to compare. + * @param right The second expression to compare. + * @return A new `Expr` representing the equality comparison. + */ export function eq(left: Expr, right: Expr): Eq; + +/** + * Creates an expression that checks if an expression is equal to a constant value. + * + * ```typescript + * // Check if the 'age' field is equal to 21 + * eq(Field.of("age"), 21); + * ``` + * + * @param left The expression to compare. + * @param right The constant value to compare to. + * @return A new `Expr` representing the equality comparison. + */ export function eq(left: Expr, right: any): Eq; + +/** + * Creates an expression that checks if a field's value is equal to an expression. + * + * ```typescript + * // Check if the 'age' field is equal to the 'limit' field + * eq("age", Field.of("limit")); + * ``` + * + * @param left The field name to compare. + * @param right The expression to compare to. + * @return A new `Expr` representing the equality comparison. + */ export function eq(left: string, right: Expr): Eq; + +/** + * Creates an expression that checks if a field's value is equal to a constant value. + * + * ```typescript + * // Check if the 'city' field is equal to string constant "London" + * eq("city", "London"); + * ``` + * + * @param left The field name to compare. + * @param right The constant value to compare to. + * @return A new `Expr` representing the equality comparison. + */ export function eq(left: string, right: any): Eq; export function eq(left: Expr | string, right: any): Eq { const leftExpr = left instanceof Expr ? left : Field.of(left); @@ -957,9 +2187,60 @@ export function eq(left: Expr | string, right: any): Eq { return new Eq(leftExpr, rightExpr); } +/** + * Creates an expression that checks if two expressions are not equal. + * + * ```typescript + * // Check if the 'status' field is not equal to field 'finalState' + * neq(Field.of("status"), Field.of("finalState")); + * ``` + * + * @param left The first expression to compare. + * @param right The second expression to compare. + * @return A new `Expr` representing the inequality comparison. + */ export function neq(left: Expr, right: Expr): Neq; + +/** + * Creates an expression that checks if an expression is not equal to a constant value. + * + * ```typescript + * // Check if the 'status' field is not equal to "completed" + * neq(Field.of("status"), "completed"); + * ``` + * + * @param left The expression to compare. + * @param right The constant value to compare to. + * @return A new `Expr` representing the inequality comparison. + */ export function neq(left: Expr, right: any): Neq; + +/** + * Creates an expression that checks if a field's value is not equal to an expression. + * + * ```typescript + * // Check if the 'status' field is not equal to the value of 'expectedStatus' + * neq("status", Field.of("expectedStatus")); + * ``` + * + * @param left The field name to compare. + * @param right The expression to compare to. + * @return A new `Expr` representing the inequality comparison. + */ export function neq(left: string, right: Expr): Neq; + +/** + * Creates an expression that checks if a field's value is not equal to a constant value. + * + * ```typescript + * // Check if the 'country' field is not equal to "USA" + * neq("country", "USA"); + * ``` + * + * @param left The field name to compare. + * @param right The constant value to compare to. + * @return A new `Expr` representing the inequality comparison. + */ export function neq(left: string, right: any): Neq; export function neq(left: Expr | string, right: any): Neq { const leftExpr = left instanceof Expr ? left : Field.of(left); @@ -967,9 +2248,60 @@ export function neq(left: Expr | string, right: any): Neq { return new Neq(leftExpr, rightExpr); } +/** + * Creates an expression that checks if the first expression is less than the second expression. + * + * ```typescript + * // Check if the 'age' field is less than 30 + * lt(Field.of("age"), Field.of("limit")); + * ``` + * + * @param left The first expression to compare. + * @param right The second expression to compare. + * @return A new `Expr` representing the less than comparison. + */ export function lt(left: Expr, right: Expr): Lt; + +/** + * Creates an expression that checks if an expression is less than a constant value. + * + * ```typescript + * // Check if the 'age' field is less than 30 + * lt(Field.of("age"), 30); + * ``` + * + * @param left The expression to compare. + * @param right The constant value to compare to. + * @return A new `Expr` representing the less than comparison. + */ export function lt(left: Expr, right: any): Lt; + +/** + * Creates an expression that checks if a field's value is less than an expression. + * + * ```typescript + * // Check if the 'age' field is less than the 'limit' field + * lt("age", Field.of("limit")); + * ``` + * + * @param left The field name to compare. + * @param right The expression to compare to. + * @return A new `Expr` representing the less than comparison. + */ export function lt(left: string, right: Expr): Lt; + +/** + * Creates an expression that checks if a field's value is less than a constant value. + * + * ```typescript + * // Check if the 'price' field is less than 50 + * lt("price", 50); + * ``` + * + * @param left The field name to compare. + * @param right The constant value to compare to. + * @return A new `Expr` representing the less than comparison. + */ export function lt(left: string, right: any): Lt; export function lt(left: Expr | string, right: any): Lt { const leftExpr = left instanceof Expr ? left : Field.of(left); @@ -977,9 +2309,61 @@ export function lt(left: Expr | string, right: any): Lt { return new Lt(leftExpr, rightExpr); } +/** + * Creates an expression that checks if the first expression is less than or equal to the second + * expression. + * + * ```typescript + * // Check if the 'quantity' field is less than or equal to 20 + * lte(Field.of("quantity"), Field.of("limit")); + * ``` + * + * @param left The first expression to compare. + * @param right The second expression to compare. + * @return A new `Expr` representing the less than or equal to comparison. + */ export function lte(left: Expr, right: Expr): Lte; + +/** + * Creates an expression that checks if an expression is less than or equal to a constant value. + * + * ```typescript + * // Check if the 'quantity' field is less than or equal to 20 + * lte(Field.of("quantity"), 20); + * ``` + * + * @param left The expression to compare. + * @param right The constant value to compare to. + * @return A new `Expr` representing the less than or equal to comparison. + */ export function lte(left: Expr, right: any): Lte; + +/** + * Creates an expression that checks if a field's value is less than or equal to an expression. + * + * ```typescript + * // Check if the 'quantity' field is less than or equal to the 'limit' field + * lte("quantity", Field.of("limit")); + * ``` + * + * @param left The field name to compare. + * @param right The expression to compare to. + * @return A new `Expr` representing the less than or equal to comparison. + */ export function lte(left: string, right: Expr): Lte; + +/** + * Creates an expression that checks if a field's value is less than or equal to a constant value. + * + * ```typescript + * // Check if the 'score' field is less than or equal to 70 + * lte("score", 70); + * ``` + * + * @param left The field name to compare. + * @param right The constant value to compare to. + * @return A new `Expr` representing the less than or equal to comparison. + */ export function lte(left: string, right: any): Lte; export function lte(left: Expr | string, right: any): Lte { const leftExpr = left instanceof Expr ? left : Field.of(left); @@ -987,9 +2371,61 @@ export function lte(left: Expr | string, right: any): Lte { return new Lte(leftExpr, rightExpr); } +/** + * Creates an expression that checks if the first expression is greater than the second + * expression. + * + * ```typescript + * // Check if the 'age' field is greater than 18 + * gt(Field.of("age"), Constant(9).add(9)); + * ``` + * + * @param left The first expression to compare. + * @param right The second expression to compare. + * @return A new `Expr` representing the greater than comparison. + */ export function gt(left: Expr, right: Expr): Gt; + +/** + * Creates an expression that checks if an expression is greater than a constant value. + * + * ```typescript + * // Check if the 'age' field is greater than 18 + * gt(Field.of("age"), 18); + * ``` + * + * @param left The expression to compare. + * @param right The constant value to compare to. + * @return A new `Expr` representing the greater than comparison. + */ export function gt(left: Expr, right: any): Gt; + +/** + * Creates an expression that checks if a field's value is greater than an expression. + * + * ```typescript + * // Check if the value of field 'age' is greater than the value of field 'limit' + * gt("age", Field.of("limit")); + * ``` + * + * @param left The field name to compare. + * @param right The expression to compare to. + * @return A new `Expr` representing the greater than comparison. + */ export function gt(left: string, right: Expr): Gt; + +/** + * Creates an expression that checks if a field's value is greater than a constant value. + * + * ```typescript + * // Check if the 'price' field is greater than 100 + * gt("price", 100); + * ``` + * + * @param left The field name to compare. + * @param right The constant value to compare to. + * @return A new `Expr` representing the greater than comparison. + */ export function gt(left: string, right: any): Gt; export function gt(left: Expr | string, right: any): Gt { const leftExpr = left instanceof Expr ? left : Field.of(left); @@ -997,9 +2433,63 @@ export function gt(left: Expr | string, right: any): Gt { return new Gt(leftExpr, rightExpr); } +/** + * Creates an expression that checks if the first expression is greater than or equal to the + * second expression. + * + * ```typescript + * // Check if the 'quantity' field is greater than or equal to the field "threshold" + * gte(Field.of("quantity"), Field.of("threshold")); + * ``` + * + * @param left The first expression to compare. + * @param right The second expression to compare. + * @return A new `Expr` representing the greater than or equal to comparison. + */ export function gte(left: Expr, right: Expr): Gte; + +/** + * Creates an expression that checks if an expression is greater than or equal to a constant + * value. + * + * ```typescript + * // Check if the 'quantity' field is greater than or equal to 10 + * gte(Field.of("quantity"), 10); + * ``` + * + * @param left The expression to compare. + * @param right The constant value to compare to. + * @return A new `Expr` representing the greater than or equal to comparison. + */ export function gte(left: Expr, right: any): Gte; + +/** + * Creates an expression that checks if a field's value is greater than or equal to an expression. + * + * ```typescript + * // Check if the value of field 'age' is greater than or equal to the value of field 'limit' + * gte("age", Field.of("limit")); + * ``` + * + * @param left The field name to compare. + * @param right The expression to compare to. + * @return A new `Expr` representing the greater than or equal to comparison. + */ export function gte(left: string, right: Expr): Gte; + +/** + * Creates an expression that checks if a field's value is greater than or equal to a constant + * value. + * + * ```typescript + * // Check if the 'score' field is greater than or equal to 80 + * gte("score", 80); + * ``` + * + * @param left The field name to compare. + * @param right The constant value to compare to. + * @return A new `Expr` representing the greater than or equal to comparison. + */ export function gte(left: string, right: any): Gte; export function gte(left: Expr | string, right: any): Gte { const leftExpr = left instanceof Expr ? left : Field.of(left); @@ -1007,9 +2497,60 @@ export function gte(left: Expr | string, right: any): Gte { return new Gte(leftExpr, rightExpr); } +/** + * Creates an expression that concatenates an array expression with other arrays. + * + * ```typescript + * // Combine the 'items' array with two new item arrays + * arrayConcat(Field.of("items"), [Field.of("newItems"), Field.of("otherItems")]); + * ``` + * + * @param array The array expression to concatenate to. + * @param elements The array expressions to concatenate. + * @return A new {@code Expr} representing the concatenated array. + */ export function arrayConcat(array: Expr, elements: Expr[]): ArrayConcat; + +/** + * Creates an expression that concatenates an array expression with other arrays and/or values. + * + * ```typescript + * // Combine the 'tags' array with a new array + * arrayConcat(Field.of("tags"), ["newTag1", "newTag2"]); + * ``` + * + * @param array The array expression to concatenate to. + * @param elements The array expressions or single values to concatenate. + * @return A new {@code Expr} representing the concatenated array. + */ export function arrayConcat(array: Expr, elements: any[]): ArrayConcat; + +/** + * Creates an expression that concatenates a field's array value with other arrays. + * + * ```typescript + * // Combine the 'items' array with two new item arrays + * arrayConcat("items", [Field.of("newItems"), Field.of("otherItems")]); + * ``` + * + * @param array The field name containing array values. + * @param elements The array expressions to concatenate. + * @return A new {@code Expr} representing the concatenated array. + */ export function arrayConcat(array: string, elements: Expr[]): ArrayConcat; + +/** + * Creates an expression that concatenates a field's array value with other arrays and/or values. + * + * ```typescript + * // Combine the 'tags' array with a new array + * arrayConcat("tags", ["newTag1", "newTag2"]); + * ``` + * + * @param array The field name containing array values. + * @param elements The array expressions or single values to concatenate. + * @return A new {@code Expr} representing the concatenated array. + */ export function arrayConcat(array: string, elements: any[]): ArrayConcat; export function arrayConcat( array: Expr | string, @@ -1022,9 +2563,60 @@ export function arrayConcat( return new ArrayConcat(arrayExpr, exprValues); } +/** + * Creates an expression that checks if an array expression contains a specific element. + * + * ```typescript + * // Check if the 'colors' array contains the value of field 'selectedColor' + * arrayContains(Field.of("colors"), Field.of("selectedColor")); + * ``` + * + * @param array The array expression to check. + * @param element The element to search for in the array. + * @return A new {@code Expr} representing the 'array_contains' comparison. + */ export function arrayContains(array: Expr, element: Expr): ArrayContains; + +/** + * Creates an expression that checks if an array expression contains a specific element. + * + * ```typescript + * // Check if the 'colors' array contains "red" + * arrayContains(Field.of("colors"), "red"); + * ``` + * + * @param array The array expression to check. + * @param element The element to search for in the array. + * @return A new {@code Expr} representing the 'array_contains' comparison. + */ export function arrayContains(array: Expr, element: any): ArrayContains; + +/** + * Creates an expression that checks if a field's array value contains a specific element. + * + * ```typescript + * // Check if the 'colors' array contains the value of field 'selectedColor' + * arrayContains("colors", Field.of("selectedColor")); + * ``` + * + * @param array The field name to check. + * @param element The element to search for in the array. + * @return A new {@code Expr} representing the 'array_contains' comparison. + */ export function arrayContains(array: string, element: Expr): ArrayContains; + +/** + * Creates an expression that checks if a field's array value contains a specific value. + * + * ```typescript + * // Check if the 'colors' array contains "red" + * arrayContains("colors", "red"); + * ``` + * + * @param array The field name to check. + * @param element The element to search for in the array. + * @return A new {@code Expr} representing the 'array_contains' comparison. + */ export function arrayContains(array: string, element: any): ArrayContains; export function arrayContains( array: Expr | string, @@ -1035,12 +2627,69 @@ export function arrayContains( return new ArrayContains(arrayExpr, elementExpr); } +/** + * Creates an expression that checks if an array expression contains any of the specified + * elements. + * + * ```typescript + * // Check if the 'categories' array contains either values from field "cate1" or "Science" + * arrayContainsAny(Field.of("categories"), [Field.of("cate1"), "Science"]); + * ``` + * + * @param array The array expression to check. + * @param values The elements to check for in the array. + * @return A new {@code Expr} representing the 'array_contains_any' comparison. + */ export function arrayContainsAny(array: Expr, values: Expr[]): ArrayContainsAny; + +/** + * Creates an expression that checks if an array expression contains any of the specified + * elements. + * + * ```typescript + * // Check if the 'categories' array contains either values from field "cate1" or "Science" + * arrayContainsAny(Field.of("categories"), [Field.of("cate1"), "Science"]); + * ``` + * + * @param array The array expression to check. + * @param values The elements to check for in the array. + * @return A new {@code Expr} representing the 'array_contains_any' comparison. + */ export function arrayContainsAny(array: Expr, values: any[]): ArrayContainsAny; + +/** + * Creates an expression that checks if a field's array value contains any of the specified + * elements. + * + * ```typescript + * // Check if the 'groups' array contains either the value from the 'userGroup' field + * // or the value "guest" + * arrayContainsAny("categories", [Field.of("cate1"), "Science"]); + * ``` + * + * @param array The field name to check. + * @param values The elements to check for in the array. + * @return A new {@code Expr} representing the 'array_contains_any' comparison. + */ export function arrayContainsAny( array: string, values: Expr[] ): ArrayContainsAny; + +/** + * Creates an expression that checks if a field's array value contains any of the specified + * elements. + * + * ```typescript + * // Check if the 'groups' array contains either the value from the 'userGroup' field + * // or the value "guest" + * arrayContainsAny("categories", [Field.of("cate1"), "Science"]); + * ``` + * + * @param array The field name to check. + * @param values The elements to check for in the array. + * @return A new {@code Expr} representing the 'array_contains_any' comparison. + */ export function arrayContainsAny( array: string, values: any[] @@ -1056,12 +2705,65 @@ export function arrayContainsAny( return new ArrayContainsAny(arrayExpr, exprValues); } +/** + * Creates an expression that checks if an array expression contains all the specified elements. + * + * ```typescript + * // Check if the 'tags' array contains both of the values from field 'tag1', 'tag2' and "tag3" + * arrayContainsAll(Field.of("tags"), [Field.of("tag1"), "SciFi", "Adventure"]); + * ``` + * + * @param array The array expression to check. + * @param values The elements to check for in the array. + * @return A new {@code Expr} representing the 'array_contains_all' comparison. + */ export function arrayContainsAll(array: Expr, values: Expr[]): ArrayContainsAll; + +/** + * Creates an expression that checks if an array expression contains all the specified elements. + * + * ```typescript + * // Check if the 'tags' array contains both of the values from field 'tag1', 'tag2' and "tag3" + * arrayContainsAll(Field.of("tags"), [Field.of("tag1"), "SciFi", "Adventure"]); + * ``` + * + * @param array The array expression to check. + * @param values The elements to check for in the array. + * @return A new {@code Expr} representing the 'array_contains_all' comparison. + */ export function arrayContainsAll(array: Expr, values: any[]): ArrayContainsAll; + +/** + * Creates an expression that checks if a field's array value contains all the specified values or + * expressions. + * + * ```typescript + * // Check if the 'tags' array contains both of the values from field 'tag1' and "tag2" + * arrayContainsAll("tags", [Field.of("tag1"), "SciFi", "Adventure"]); + * ``` + * + * @param array The field name to check. + * @param values The elements to check for in the array. + * @return A new {@code Expr} representing the 'array_contains_all' comparison. + */ export function arrayContainsAll( array: string, values: Expr[] ): ArrayContainsAll; + +/** + * Creates an expression that checks if a field's array value contains all the specified values or + * expressions. + * + * ```typescript + * // Check if the 'tags' array contains both of the values from field 'tag1' and "tag2" + * arrayContainsAll("tags", [Field.of("tag1"), "SciFi", "Adventure"]); + * ``` + * + * @param array The field name to check. + * @param values The elements to check for in the array. + * @return A new {@code Expr} representing the 'array_contains_all' comparison. + */ export function arrayContainsAll( array: string, values: any[] @@ -1077,14 +2779,55 @@ export function arrayContainsAll( return new ArrayContainsAll(arrayExpr, exprValues); } +/** + * Creates an expression that filters elements from an array expression using the given {@link + * FilterExpr} and returns the filtered elements as a new array. + * + * ```typescript + * // Get items from the 'inventoryPrices' array where the array item is greater than 0 + * // Note we use {@link arrayElement} to represent array elements to construct a + * // filtering condition. + * arrayFilter(Field.of("inventoryPrices"), arrayElement().gt(0)); + * ``` + * + * @param array The array expression to filter. + * @param filter The {@link FilterExpr} to apply to the array elements. + * @return A new {@code Expr} representing the filtered array. + */ export function arrayFilter(array: Expr, filter: FilterExpr): ArrayFilter { return new ArrayFilter(array, filter); } +/** + * Creates an expression that calculates the length of an array expression. + * + * ```typescript + * // Get the number of items in the 'cart' array + * arrayLength(Field.of("cart")); + * ``` + * + * @param array The array expression to calculate the length of. + * @return A new {@code Expr} representing the length of the array. + */ export function arrayLength(array: Expr): ArrayLength { return new ArrayLength(array); } +/** + * Creates an expression that applies a transformation function to each element in an array + * expression and returns the new array as the result of the evaluation. + * + * ```typescript + * // Convert all strings in the 'names' array to uppercase + * // Note we use {@link arrayElement} to represent array elements to construct a + * // transforming function. + * arrayTransform(Field.of("names"), arrayElement().toUppercase()); + * ``` + * + * @param array The array expression to transform. + * @param transform The {@link Function} to apply to each array element. + * @return A new {@code Expr} representing the transformed array. + */ export function arrayTransform( array: Expr, transform: Function @@ -1092,14 +2835,80 @@ export function arrayTransform( return new ArrayTransform(array, transform); } +/** + * Returns an expression that represents an array element within an {@link ArrayFilter} or {@link + * ArrayTransform} expression. + * + * ```typescript + * // Get items from the 'inventoryPrices' array where the array item is greater than 0 + * arrayFilter(Field.of("inventoryPrices"), arrayElement().gt(0)); + * ``` + * + * @return A new {@code Expr} representing an array element. + */ export function arrayElement(): ArrayElement { return new ArrayElement(); } +/** + * Creates an expression that checks if an expression is equal to any of the provided values or + * expressions. + * + * ```typescript + * // Check if the 'category' field is either "Electronics" or value of field 'primaryType' + * inAny(Field.of("category"), [Constant.of("Electronics"), Field.of("primaryType")]); + * ``` + * + * @param element The expression to compare. + * @param others The values to check against. + * @return A new {@code Expr} representing the 'IN' comparison. + */ export function inAny(element: Expr, others: Expr[]): In; + +/** + * Creates an expression that checks if an expression is equal to any of the provided values or + * expressions. + * + * ```typescript + * // Check if the 'category' field is either "Electronics" or value of field 'primaryType' + * inAny(Field.of("category"), ["Electronics", Field.of("primaryType")]); + * ``` + * + * @param element The expression to compare. + * @param others The values to check against. + * @return A new {@code Expr} representing the 'IN' comparison. + */ export function inAny(element: Expr, others: any[]): In; -export function inAny(element: string, others: Expr[]): In; // Added overload -export function inAny(element: string, others: any[]): In; // Added overload + +/** + * Creates an expression that checks if a field's value is equal to any of the provided values or + * expressions. + * + * ```typescript + * // Check if the 'category' field is either "Electronics" or value of field 'primaryType' + * inAny("category", [Constant.of("Electronics"), Field.of("primaryType")]); + * ``` + * + * @param element The field to compare. + * @param others The values to check against. + * @return A new {@code Expr} representing the 'IN' comparison. + */ +export function inAny(element: string, others: Expr[]): In; + +/** + * Creates an expression that checks if a field's value is equal to any of the provided values or + * expressions. + * + * ```typescript + * // Check if the 'category' field is either "Electronics" or value of field 'primaryType' + * inAny("category", ["Electronics", Field.of("primaryType")]); + * ``` + * + * @param element The field to compare. + * @param others The values to check against. + * @return A new {@code Expr} representing the 'IN' comparison. + */ +export function inAny(element: string, others: any[]): In; export function inAny(element: Expr | string, others: any[]): In { const elementExpr = element instanceof Expr ? element : Field.of(element); const exprOthers = others.map(other => @@ -1108,10 +2917,65 @@ export function inAny(element: Expr | string, others: any[]): In { return new In(elementExpr, exprOthers); } +/** + * Creates an expression that checks if an expression is not equal to any of the provided values + * or expressions. + * + * ```typescript + * // Check if the 'status' field is neither "pending" nor the value of 'rejectedStatus' + * notInAny(Field.of("status"), [Constant.of("pending"), Field.of("rejectedStatus")]); + * ``` + * + * @param element The expression to compare. + * @param others The values to check against. + * @return A new {@code Expr} representing the 'NOT IN' comparison. + */ export function notInAny(element: Expr, others: Expr[]): Not; + +/** + * Creates an expression that checks if an expression is not equal to any of the provided values + * or expressions. + * + * ```typescript + * // Check if the 'status' field is neither "pending" nor the value of 'rejectedStatus' + * notInAny(Field.of("status"), ["pending", Field.of("rejectedStatus")]); + * ``` + * + * @param element The expression to compare. + * @param others The values to check against. + * @return A new {@code Expr} representing the 'NOT IN' comparison. + */ export function notInAny(element: Expr, others: any[]): Not; -export function notInAny(element: string, others: Expr[]): Not; // Added overload -export function notInAny(element: string, others: any[]): Not; // Added overload + +/** + * Creates an expression that checks if a field's value is not equal to any of the provided values + * or expressions. + * + * ```typescript + * // Check if the 'status' field is neither "pending" nor the value of 'rejectedStatus' + * notInAny("status", [Constant.of("pending"), Field.of("rejectedStatus")]); + * ``` + * + * @param element The field name to compare. + * @param others The values to check against. + * @return A new {@code Expr} representing the 'NOT IN' comparison. + */ +export function notInAny(element: string, others: Expr[]): Not; + +/** + * Creates an expression that checks if a field's value is not equal to any of the provided values + * or expressions. + * + * ```typescript + * // Check if the 'status' field is neither "pending" nor the value of 'rejectedStatus' + * notInAny("status", ["pending", Field.of("rejectedStatus")]); + * ``` + * + * @param element The field name to compare. + * @param others The values to check against. + * @return A new {@code Expr} representing the 'NOT IN' comparison. + */ +export function notInAny(element: string, others: any[]): Not; export function notInAny(element: Expr | string, others: any[]): Not { const elementExpr = element instanceof Expr ? element : Field.of(element); const exprOthers = others.map(other => @@ -1120,18 +2984,76 @@ export function notInAny(element: Expr | string, others: any[]): Not { return new Not(new In(elementExpr, exprOthers)); } +/** + * Creates an expression that performs a logical 'AND' operation on multiple filter conditions. + * + * ```typescript + * // Check if the 'age' field is greater than 18 AND the 'city' field is "London" AND + * // the 'status' field is "active" + * const condition = and(gt("age", 18), eq("city", "London"), eq("status", "active")); + * ``` + * + * @param left The first filter condition. + * @param right Additional filter conditions to 'AND' together. + * @return A new {@code Expr} representing the logical 'AND' operation. + */ export function and(left: FilterExpr, ...right: FilterExpr[]): And { return new And([left, ...right]); } +/** + * Creates an expression that performs a logical 'OR' operation on multiple filter conditions. + * + * ```typescript + * // Check if the 'age' field is greater than 18 OR the 'city' field is "London" OR + * // the 'status' field is "active" + * const condition = or(gt("age", 18), eq("city", "London"), eq("status", "active")); + * ``` + * + * @param left The first filter condition. + * @param right Additional filter conditions to 'OR' together. + * @return A new {@code Expr} representing the logical 'OR' operation. + */ export function or(left: FilterExpr, ...right: FilterExpr[]): Or { return new Or([left, ...right]); } +/** + * Creates an expression that performs a logical 'XOR' (exclusive OR) operation on multiple filter + * conditions. + * + * ```typescript + * // Check if only one of the conditions is true: 'age' greater than 18, 'city' is "London", + * // or 'status' is "active". + * const condition = xor( + * gt("age", 18), + * eq("city", "London"), + * eq("status", "active")); + * ``` + * + * @param left The first filter condition. + * @param right Additional filter conditions to 'XOR' together. + * @return A new {@code Expr} representing the logical 'XOR' operation. + */ export function xor(left: FilterExpr, ...right: FilterExpr[]): Xor { return new Xor([left, ...right]); } +/** + * Creates a conditional expression that evaluates to a 'then' expression if a condition is true + * and an 'else' expression if the condition is false. + * + * ```typescript + * // If 'age' is greater than 18, return "Adult"; otherwise, return "Minor". + * ifFunction( + * gt("age", 18), Constant.of("Adult"), Constant.of("Minor")); + * ``` + * + * @param condition The condition to evaluate. + * @param thenExpr The expression to evaluate if the condition is true. + * @param elseExpr The expression to evaluate if the condition is false. + * @return A new {@code Expr} representing the conditional expression. + */ export function ifFunction( condition: FilterExpr, thenExpr: Expr, @@ -1140,11 +3062,45 @@ export function ifFunction( return new If(condition, thenExpr, elseExpr); } +/** + * Creates an expression that negates a filter condition. + * + * ```typescript + * // Find documents where the 'completed' field is NOT true + * not(eq("completed", true)); + * ``` + * + * @param filter The filter condition to negate. + * @return A new {@code Expr} representing the negated filter condition. + */ export function not(filter: FilterExpr): Not { return new Not(filter); } +/** + * Creates an expression that checks if a field exists. + * + * ```typescript + * // Check if the document has a field named "phoneNumber" + * exists(Field.of("phoneNumber")); + * ``` + * + * @param value An expression evaluates to the name of the field to check. + * @return A new {@code Expr} representing the 'exists' check. + */ export function exists(value: Expr): Exists; + +/** + * Creates an expression that checks if a field exists. + * + * ```typescript + * // Check if the document has a field named "phoneNumber" + * exists("phoneNumber"); + * ``` + * + * @param field The field name to check. + * @return A new {@code Expr} representing the 'exists' check. + */ export function exists(field: string): Exists; export function exists(valueOrField: Expr | string): Exists { const valueExpr = @@ -1152,41 +3108,188 @@ export function exists(valueOrField: Expr | string): Exists { return new Exists(valueExpr); } -export function isNull(value: Expr): IsNull; -export function isNull(value: string): IsNull; -export function isNull(value: Expr | string): IsNull { - const valueExpr = value instanceof Expr ? value : Field.of(value); - return new IsNull(valueExpr); -} - +/** + * Creates an expression that checks if an expression evaluates to 'NaN' (Not a Number). + * + * ```typescript + * // Check if the result of a calculation is NaN + * isNaN(Field.of("value").divide(0)); + * ``` + * + * @param value The expression to check. + * @return A new {@code Expr} representing the 'isNaN' check. + */ export function isNan(value: Expr): IsNan; + +/** + * Creates an expression that checks if a field's value evaluates to 'NaN' (Not a Number). + * + * ```typescript + * // Check if the result of a calculation is NaN + * isNaN("value"); + * ``` + * + * @param value The name of the field to check. + * @return A new {@code Expr} representing the 'isNaN' check. + */ export function isNan(value: string): IsNan; export function isNan(value: Expr | string): IsNan { const valueExpr = value instanceof Expr ? value : Field.of(value); return new IsNan(valueExpr); } +/** + * Creates an expression that calculates the length of a string field. + * + * ```typescript + * // Get the length of the 'name' field + * length("name"); + * ``` + * + * @param field The name of the field containing the string. + * @return A new {@code Expr} representing the length of the string. + */ export function length(field: string): Length; + +/** + * Creates an expression that calculates the length of a string expression. + * + * ```typescript + * // Get the length of the 'name' field + * length(Field.of("name")); + * ``` + * + * @param expr The expression representing the string to calculate the length of. + * @return A new {@code Expr} representing the length of the string. + */ export function length(expr: Expr): Length; export function length(value: Expr | string): Length { const valueExpr = value instanceof Expr ? value : Field.of(value); return new Length(valueExpr); } -export function like(left: Expr, pattern: Expr): Like; -export function like(left: Expr, pattern: string): Like; -export function like(left: string, pattern: Expr): Like; +/** + * Creates an expression that performs a case-sensitive wildcard string comparison against a + * field. + * + * ```typescript + * // Check if the 'title' field contains the string "guide" + * like("title", "%guide%"); + * ``` + * + * @param left The name of the field containing the string. + * @param pattern The pattern to search for. You can use "%" as a wildcard character. + * @return A new {@code Expr} representing the 'like' comparison. + */ export function like(left: string, pattern: string): Like; + +/** + * Creates an expression that performs a case-sensitive wildcard string comparison against a + * field. + * + * ```typescript + * // Check if the 'title' field contains the string "guide" + * like("title", Field.of("pattern")); + * ``` + * + * @param left The name of the field containing the string. + * @param pattern The pattern to search for. You can use "%" as a wildcard character. + * @return A new {@code Expr} representing the 'like' comparison. + */ +export function like(left: string, pattern: Expr): Like; + +/** + * Creates an expression that performs a case-sensitive wildcard string comparison. + * + * ```typescript + * // Check if the 'title' field contains the string "guide" + * like(Field.of("title"), "%guide%"); + * ``` + * + * @param left The expression representing the string to perform the comparison on. + * @param pattern The pattern to search for. You can use "%" as a wildcard character. + * @return A new {@code Expr} representing the 'like' comparison. + */ +export function like(left: Expr, pattern: string): Like; + +/** + * Creates an expression that performs a case-sensitive wildcard string comparison. + * + * ```typescript + * // Check if the 'title' field contains the string "guide" + * like(Field.of("title"), Field.of("pattern")); + * ``` + * + * @param left The expression representing the string to perform the comparison on. + * @param pattern The pattern to search for. You can use "%" as a wildcard character. + * @return A new {@code Expr} representing the 'like' comparison. + */ +export function like(left: Expr, pattern: Expr): Like; export function like(left: Expr | string, pattern: Expr | string): Like { const leftExpr = left instanceof Expr ? left : Field.of(left); const patternExpr = pattern instanceof Expr ? pattern : Constant.of(pattern); return new Like(leftExpr, patternExpr); } -export function regexContains(left: Expr, pattern: Expr): RegexContains; -export function regexContains(left: Expr, pattern: string): RegexContains; -export function regexContains(left: string, pattern: Expr): RegexContains; +/** + * Creates an expression that checks if a string field contains a specified regular expression as + * a substring. + * + * ```typescript + * // Check if the 'description' field contains "example" (case-insensitive) + * regexContains("description", "(?i)example"); + * ``` + * + * @param left The name of the field containing the string. + * @param pattern The regular expression to use for the search. + * @return A new {@code Expr} representing the 'contains' comparison. + */ export function regexContains(left: string, pattern: string): RegexContains; + +/** + * Creates an expression that checks if a string field contains a specified regular expression as + * a substring. + * + * ```typescript + * // Check if the 'description' field contains "example" (case-insensitive) + * regexContains("description", Field.of("pattern")); + * ``` + * + * @param left The name of the field containing the string. + * @param pattern The regular expression to use for the search. + * @return A new {@code Expr} representing the 'contains' comparison. + */ +export function regexContains(left: string, pattern: Expr): RegexContains; + +/** + * Creates an expression that checks if a string expression contains a specified regular + * expression as a substring. + * + * ```typescript + * // Check if the 'description' field contains "example" (case-insensitive) + * regexContains(Field.of("description"), "(?i)example"); + * ``` + * + * @param left The expression representing the string to perform the comparison on. + * @param pattern The regular expression to use for the search. + * @return A new {@code Expr} representing the 'contains' comparison. + */ +export function regexContains(left: Expr, pattern: string): RegexContains; + +/** + * Creates an expression that checks if a string expression contains a specified regular + * expression as a substring. + * + * ```typescript + * // Check if the 'description' field contains "example" (case-insensitive) + * regexContains(Field.of("description"), Field.of("pattern")); + * ``` + * + * @param left The expression representing the string to perform the comparison on. + * @param pattern The regular expression to use for the search. + * @return A new {@code Expr} representing the 'contains' comparison. + */ +export function regexContains(left: Expr, pattern: Expr): RegexContains; export function regexContains( left: Expr | string, pattern: Expr | string @@ -1196,10 +3299,63 @@ export function regexContains( return new RegexContains(leftExpr, patternExpr); } -export function regexMatch(left: Expr, pattern: Expr): RegexMatch; -export function regexMatch(left: Expr, pattern: string): RegexMatch; -export function regexMatch(left: string, pattern: Expr): RegexMatch; +/** + * Creates an expression that checks if a string field matches a specified regular expression. + * + * ```typescript + * // Check if the 'email' field matches a valid email pattern + * regexMatch("email", "[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,}"); + * ``` + * + * @param left The name of the field containing the string. + * @param pattern The regular expression to use for the match. + * @return A new {@code Expr} representing the regular expression match. + */ export function regexMatch(left: string, pattern: string): RegexMatch; + +/** + * Creates an expression that checks if a string field matches a specified regular expression. + * + * ```typescript + * // Check if the 'email' field matches a valid email pattern + * regexMatch("email", Field.of("pattern")); + * ``` + * + * @param left The name of the field containing the string. + * @param pattern The regular expression to use for the match. + * @return A new {@code Expr} representing the regular expression match. + */ +export function regexMatch(left: string, pattern: Expr): RegexMatch; + +/** + * Creates an expression that checks if a string expression matches a specified regular + * expression. + * + * ```typescript + * // Check if the 'email' field matches a valid email pattern + * regexMatch(Field.of("email"), "[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,}"); + * ``` + * + * @param left The expression representing the string to match against. + * @param pattern The regular expression to use for the match. + * @return A new {@code Expr} representing the regular expression match. + */ +export function regexMatch(left: Expr, pattern: string): RegexMatch; + +/** + * Creates an expression that checks if a string expression matches a specified regular + * expression. + * + * ```typescript + * // Check if the 'email' field matches a valid email pattern + * regexMatch(Field.of("email"), Field.of("pattern")); + * ``` + * + * @param left The expression representing the string to match against. + * @param pattern The regular expression to use for the match. + * @return A new {@code Expr} representing the regular expression match. + */ +export function regexMatch(left: Expr, pattern: Expr): RegexMatch; export function regexMatch( left: Expr | string, pattern: Expr | string @@ -1209,10 +3365,61 @@ export function regexMatch( return new RegexMatch(leftExpr, patternExpr); } -export function startsWith(expr: Expr, prefix: Expr): StartsWith; -export function startsWith(expr: Expr, prefix: string): StartsWith; -export function startsWith(expr: string, prefix: Expr): StartsWith; +/** + * Creates an expression that checks if a field's value starts with a given prefix. + * + * ```typescript + * // Check if the 'name' field starts with "Mr." + * startsWith("name", "Mr."); + * ``` + * + * @param expr The field name to check. + * @param prefix The prefix to check for. + * @return A new {@code Expr} representing the 'starts with' comparison. + */ export function startsWith(expr: string, prefix: string): StartsWith; + +/** + * Creates an expression that checks if a field's value starts with a given prefix. + * + * ```typescript + * // Check if the 'fullName' field starts with the value of the 'firstName' field + * startsWith("fullName", Field.of("firstName")); + * ``` + * + * @param expr The field name to check. + * @param prefix The expression representing the prefix. + * @return A new {@code Expr} representing the 'starts with' comparison. + */ +export function startsWith(expr: string, prefix: Expr): StartsWith; + +/** + * Creates an expression that checks if a string expression starts with a given prefix. + * + * ```typescript + * // Check if the result of concatenating 'firstName' and 'lastName' fields starts with "Mr." + * startsWith(Field.of("fullName"), "Mr."); + * ``` + * + * @param expr The expression to check. + * @param prefix The prefix to check for. + * @return A new {@code Expr} representing the 'starts with' comparison. + */ +export function startsWith(expr: Expr, prefix: string): StartsWith; + +/** + * Creates an expression that checks if a string expression starts with a given prefix. + * + * ```typescript + * // Check if the result of concatenating 'firstName' and 'lastName' fields starts with "Mr." + * startsWith(Field.of("fullName"), Field.of("prefix")); + * ``` + * + * @param expr The expression to check. + * @param prefix The prefix to check for. + * @return A new {@code Expr} representing the 'starts with' comparison. + */ +export function startsWith(expr: Expr, prefix: Expr): StartsWith; export function startsWith( expr: Expr | string, prefix: Expr | string @@ -1222,38 +3429,183 @@ export function startsWith( return new StartsWith(exprLeft, prefixExpr); } -export function endsWith(expr: Expr, suffix: Expr): EndsWith; -export function endsWith(expr: Expr, suffix: string): EndsWith; -export function endsWith(expr: string, suffix: Expr): EndsWith; +/** + * Creates an expression that checks if a field's value ends with a given postfix. + * + * ```typescript + * // Check if the 'filename' field ends with ".txt" + * endsWith("filename", ".txt"); + * ``` + * + * @param expr The field name to check. + * @param suffix The postfix to check for. + * @return A new {@code Expr} representing the 'ends with' comparison. + */ export function endsWith(expr: string, suffix: string): EndsWith; + +/** + * Creates an expression that checks if a field's value ends with a given postfix. + * + * ```typescript + * // Check if the 'url' field ends with the value of the 'extension' field + * endsWith("url", Field.of("extension")); + * ``` + * + * @param expr The field name to check. + * @param suffix The expression representing the postfix. + * @return A new {@code Expr} representing the 'ends with' comparison. + */ +export function endsWith(expr: string, suffix: Expr): EndsWith; + +/** + * Creates an expression that checks if a string expression ends with a given postfix. + * + * ```typescript + * // Check if the result of concatenating 'firstName' and 'lastName' fields ends with "Jr." + * endsWith(Field.of("fullName"), "Jr."); + * ``` + * + * @param expr The expression to check. + * @param suffix The postfix to check for. + * @return A new {@code Expr} representing the 'ends with' comparison. + */ +export function endsWith(expr: Expr, suffix: string): EndsWith; + +/** + * Creates an expression that checks if a string expression ends with a given postfix. + * + * ```typescript + * // Check if the result of concatenating 'firstName' and 'lastName' fields ends with "Jr." + * endsWith(Field.of("fullName"), Constant.of("Jr.")); + * ``` + * + * @param expr The expression to check. + * @param suffix The postfix to check for. + * @return A new {@code Expr} representing the 'ends with' comparison. + */ +export function endsWith(expr: Expr, suffix: Expr): EndsWith; export function endsWith(expr: Expr | string, suffix: Expr | string): EndsWith { const exprLeft = expr instanceof Expr ? expr : Field.of(expr); const suffixExpr = suffix instanceof Expr ? suffix : Constant.of(suffix); return new EndsWith(exprLeft, suffixExpr); } -export function toLowercase(expr: Expr): ToLowercase; +/** + * Creates an expression that converts a string field to lowercase. + * + * ```typescript + * // Convert the 'name' field to lowercase + * toLowercase("name"); + * ``` + * + * @param expr The name of the field containing the string. + * @return A new {@code Expr} representing the lowercase string. + */ export function toLowercase(expr: string): ToLowercase; + +/** + * Creates an expression that converts a string expression to lowercase. + * + * ```typescript + * // Convert the 'name' field to lowercase + * toLowercase(Field.of("name")); + * ``` + * + * @param expr The expression representing the string to convert to lowercase. + * @return A new {@code Expr} representing the lowercase string. + */ +export function toLowercase(expr: Expr): ToLowercase; export function toLowercase(expr: Expr | string): ToLowercase { return new ToLowercase(expr instanceof Expr ? expr : Field.of(expr)); } -export function toUppercase(expr: Expr): ToUppercase; +/** + * Creates an expression that converts a string field to uppercase. + * + * ```typescript + * // Convert the 'title' field to uppercase + * toUppercase("title"); + * ``` + * + * @param expr The name of the field containing the string. + * @return A new {@code Expr} representing the uppercase string. + */ export function toUppercase(expr: string): ToUppercase; + +/** + * Creates an expression that converts a string expression to uppercase. + * + * ```typescript + * // Convert the 'title' field to uppercase + * toUppercase(Field.of("title")); + * ``` + * + * @param expr The expression representing the string to convert to uppercase. + * @return A new {@code Expr} representing the uppercase string. + */ +export function toUppercase(expr: Expr): ToUppercase; export function toUppercase(expr: Expr | string): ToUppercase { return new ToUppercase(expr instanceof Expr ? expr : Field.of(expr)); } -export function trim(expr: Expr): Trim; +/** + * Creates an expression that removes leading and trailing whitespace from a string field. + * + * ```typescript + * // Trim whitespace from the 'userInput' field + * trim("userInput"); + * ``` + * + * @param expr The name of the field containing the string. + * @return A new {@code Expr} representing the trimmed string. + */ export function trim(expr: string): Trim; + +/** + * Creates an expression that removes leading and trailing whitespace from a string expression. + * + * ```typescript + * // Trim whitespace from the 'userInput' field + * trim(Field.of("userInput")); + * ``` + * + * @param expr The expression representing the string to trim. + * @return A new {@code Expr} representing the trimmed string. + */ +export function trim(expr: Expr): Trim; export function trim(expr: Expr | string): Trim { return new Trim(expr instanceof Expr ? expr : Field.of(expr)); } +/** + * Creates an expression that concatenates string functions, fields or constants together. + * + * ```typescript + * // Combine the 'firstName', " ", and 'lastName' fields into a single string + * strConcat("firstName", " ", Field.of("lastName")); + * ``` + * + * @param first The field name containing the initial string value. + * @param elements The expressions (typically strings) to concatenate. + * @return A new {@code Expr} representing the concatenated string. + */ export function strConcat( first: string, ...elements: (Expr | string)[] ): StrConcat; + +/** + * Creates an expression that concatenates string expressions together. + * + * ```typescript + * // Combine the 'firstName', " ", and 'lastName' fields into a single string + * strConcat(Field.of("firstName"), " ", Field.of("lastName")); + * ``` + * + * @param first The initial string expression to concatenate to. + * @param elements The expressions (typically strings) to concatenate. + * @return A new {@code Expr} representing the concatenated string. + */ export function strConcat( first: Expr, ...elements: (Expr | string)[] @@ -1266,7 +3618,32 @@ export function strConcat( return new StrConcat(first instanceof Expr ? first : Field.of(first), exprs); } +/** + * Accesses a value from a map (object) field using the provided key. + * + * ```typescript + * // Get the 'city' value from the 'address' map field + * mapGet("address", "city"); + * ``` + * + * @param mapField The field name of the map field. + * @param subField The key to access in the map. + * @return A new {@code Expr} representing the value associated with the given key in the map. + */ export function mapGet(mapField: string, subField: string): MapGet; + +/** + * Accesses a value from a map (object) expression using the provided key. + * + * ```typescript + * // Get the 'city' value from the 'address' map field + * mapGet(Field.of("address"), "city"); + * ``` + * + * @param mapExpr The expression representing the map. + * @param subField The key to access in the map. + * @return A new {@code Expr} representing the value associated with the given key in the map. + */ export function mapGet(mapExpr: Expr, subField: string): MapGet; export function mapGet(fieldOrExpr: string | Expr, subField: string): MapGet { return new MapGet( @@ -1275,54 +3652,264 @@ export function mapGet(fieldOrExpr: string | Expr, subField: string): MapGet { ); } +/** + * Creates an aggregation that counts the total number of stage inputs. + * + * ```typescript + * // Count the total number of users + * countAll().as("totalUsers"); + * ``` + * + * @return A new {@code Accumulator} representing the 'countAll' aggregation. + */ export function countAll(): Count { return new Count(undefined, false); } +/** + * Creates an aggregation that counts the number of stage inputs with valid evaluations of the + * provided expression. + * + * ```typescript + * // Count the number of items where the price is greater than 10 + * count(Field.of("price").gt(10)).as("expensiveItemCount"); + * ``` + * + * @param value The expression to count. + * @return A new {@code Accumulator} representing the 'count' aggregation. + */ export function count(value: Expr): Count; + +/** + * Creates an aggregation that counts the number of stage inputs with valid evaluations of the + * provided field. + * + * ```typescript + * // Count the total number of products + * count("productId").as("totalProducts"); + * ``` + * + * @param value The name of the field to count. + * @return A new {@code Accumulator} representing the 'count' aggregation. + */ export function count(value: string): Count; export function count(value: Expr | string): Count { const exprValue = value instanceof Expr ? value : Field.of(value); return new Count(exprValue, false); } +/** + * Creates an aggregation that calculates the sum of values from an expression across multiple + * stage inputs. + * + * ```typescript + * // Calculate the total revenue from a set of orders + * sum(Field.of("orderAmount")).as("totalRevenue"); + * ``` + * + * @param value The expression to sum up. + * @return A new {@code Accumulator} representing the 'sum' aggregation. + */ export function sum(value: Expr): Sum; + +/** + * Creates an aggregation that calculates the sum of a field's values across multiple stage + * inputs. + * + * ```typescript + * // Calculate the total revenue from a set of orders + * sum("orderAmount").as("totalRevenue"); + * ``` + * + * @param value The name of the field containing numeric values to sum up. + * @return A new {@code Accumulator} representing the 'sum' aggregation. + */ export function sum(value: string): Sum; export function sum(value: Expr | string): Sum { const exprValue = value instanceof Expr ? value : Field.of(value); return new Sum(exprValue, false); } +/** + * Creates an aggregation that calculates the average (mean) of values from an expression across + * multiple stage inputs. + * + * ```typescript + * // Calculate the average age of users + * avg(Field.of("age")).as("averageAge"); + * ``` + * + * @param value The expression representing the values to average. + * @return A new {@code Accumulator} representing the 'avg' aggregation. + */ export function avg(value: Expr): Avg; + +/** + * Creates an aggregation that calculates the average (mean) of a field's values across multiple + * stage inputs. + * + * ```typescript + * // Calculate the average age of users + * avg("age").as("averageAge"); + * ``` + * + * @param value The name of the field containing numeric values to average. + * @return A new {@code Accumulator} representing the 'avg' aggregation. + */ export function avg(value: string): Avg; export function avg(value: Expr | string): Avg { const exprValue = value instanceof Expr ? value : Field.of(value); return new Avg(exprValue, false); } +/** + * Creates an aggregation that finds the minimum value of an expression across multiple stage + * inputs. + * + * ```typescript + * // Find the lowest price of all products + * min(Field.of("price")).as("lowestPrice"); + * ``` + * + * @param value The expression to find the minimum value of. + * @return A new {@code Accumulator} representing the 'min' aggregation. + */ export function min(value: Expr): Min; + +/** + * Creates an aggregation that finds the minimum value of a field across multiple stage inputs. + * + * ```typescript + * // Find the lowest price of all products + * min("price").as("lowestPrice"); + * ``` + * + * @param value The name of the field to find the minimum value of. + * @return A new {@code Accumulator} representing the 'min' aggregation. + */ export function min(value: string): Min; export function min(value: Expr | string): Min { const exprValue = value instanceof Expr ? value : Field.of(value); return new Min(exprValue, false); } +/** + * Creates an aggregation that finds the maximum value of an expression across multiple stage + * inputs. + * + * ```typescript + * // Find the highest score in a leaderboard + * max(Field.of("score")).as("highestScore"); + * ``` + * + * @param value The expression to find the maximum value of. + * @return A new {@code Accumulator} representing the 'max' aggregation. + */ export function max(value: Expr): Max; + +/** + * Creates an aggregation that finds the maximum value of a field across multiple stage inputs. + * + * ```typescript + * // Find the highest score in a leaderboard + * max("score").as("highestScore"); + * ``` + * + * @param value The name of the field to find the maximum value of. + * @return A new {@code Accumulator} representing the 'max' aggregation. + */ export function max(value: string): Max; export function max(value: Expr | string): Max { const exprValue = value instanceof Expr ? value : Field.of(value); return new Max(exprValue, false); } -export function cosineDistance(expr: Expr, other: Expr): CosineDistance; -export function cosineDistance(expr: Expr, other: number[]): CosineDistance; -export function cosineDistance(expr: Expr, other: VectorValue): CosineDistance; -export function cosineDistance(expr: string, other: Expr): CosineDistance; +/** + * Calculates the Cosine distance between a field's vector value and a double array. + * + * ```typescript + * // Calculate the Cosine distance between the 'location' field and a target location + * cosineDistance("location", [37.7749, -122.4194]); + * ``` + * + * @param expr The name of the field containing the first vector. + * @param other The other vector (as an array of doubles) to compare against. + * @return A new {@code Expr} representing the Cosine distance between the two vectors. + */ export function cosineDistance(expr: string, other: number[]): CosineDistance; + +/** + * Calculates the Cosine distance between a field's vector value and a VectorValue. + * + * ```typescript + * // Calculate the Cosine distance between the 'location' field and a target location + * cosineDistance("location", new VectorValue([37.7749, -122.4194])); + * ``` + * + * @param expr The name of the field containing the first vector. + * @param other The other vector (as a VectorValue) to compare against. + * @return A new {@code Expr} representing the Cosine distance between the two vectors. + */ export function cosineDistance( expr: string, other: VectorValue ): CosineDistance; + +/** + * Calculates the Cosine distance between a field's vector value and a vector expression. + * + * ```typescript + * // Calculate the cosine distance between the 'userVector' field and the 'itemVector' field + * cosineDistance("userVector", Field.of("itemVector")); + * ``` + * + * @param expr The name of the field containing the first vector. + * @param other The other vector (represented as an Expr) to compare against. + * @return A new {@code Expr} representing the cosine distance between the two vectors. + */ +export function cosineDistance(expr: string, other: Expr): CosineDistance; + +/** + * Calculates the Cosine distance between a vector expression and a double array. + * + * ```typescript + * // Calculate the cosine distance between the 'location' field and a target location + * cosineDistance(Field.of("location"), [37.7749, -122.4194]); + * ``` + * + * @param expr The first vector (represented as an Expr) to compare against. + * @param other The other vector (as an array of doubles) to compare against. + * @return A new {@code Expr} representing the cosine distance between the two vectors. + */ +export function cosineDistance(expr: Expr, other: number[]): CosineDistance; + +/** + * Calculates the Cosine distance between a vector expression and a VectorValue. + * + * ```typescript + * // Calculate the cosine distance between the 'location' field and a target location + * cosineDistance(Field.of("location"), new VectorValue([37.7749, -122.4194])); + * ``` + * + * @param expr The first vector (represented as an Expr) to compare against. + * @param other The other vector (as a VectorValue) to compare against. + * @return A new {@code Expr} representing the cosine distance between the two vectors. + */ +export function cosineDistance(expr: Expr, other: VectorValue): CosineDistance; + +/** + * Calculates the Cosine distance between two vector expressions. + * + * ```typescript + * // Calculate the cosine distance between the 'userVector' field and the 'itemVector' field + * cosineDistance(Field.of("userVector"), Field.of("itemVector")); + * ``` + * + * @param expr The first vector (represented as an Expr) to compare against. + * @param other The other vector (represented as an Expr) to compare against. + * @return A new {@code Expr} representing the cosine distance between the two vectors. + */ +export function cosineDistance(expr: Expr, other: Expr): CosineDistance; export function cosineDistance( expr: Expr | string, other: Expr | number[] | VectorValue @@ -1332,27 +3919,104 @@ export function cosineDistance( return new CosineDistance(expr1, expr2); } -export function dotProductDistance(expr: Expr, other: Expr): DotProductDistance; // Fixed return type +/** + * Calculates the dot product distance between a field's vector value and a double array. + * + * ```typescript + * // Calculate the dot product distance between a feature vector and a target vector + * dotProductDistance("features", [0.5, 0.8, 0.2]); + * ``` + * + * @param expr The name of the field containing the first vector. + * @param other The other vector (as an array of doubles) to compare against. + * @return A new {@code Expr} representing the dot product distance between the two vectors. + */ export function dotProductDistance( - expr: Expr, + expr: string, other: number[] ): DotProductDistance; + +/** + * Calculates the dot product distance between a field's vector value and a VectorValue. + * + * ```typescript + * // Calculate the dot product distance between a feature vector and a target vector + * dotProductDistance("features", new VectorValue([0.5, 0.8, 0.2])); + * ``` + * + * @param expr The name of the field containing the first vector. + * @param other The other vector (as a VectorValue) to compare against. + * @return A new {@code Expr} representing the dot product distance between the two vectors. + */ export function dotProductDistance( - expr: Expr, + expr: string, other: VectorValue ): DotProductDistance; + +/** + * Calculates the dot product distance between a field's vector value and a vector expression. + * + * ```typescript + * // Calculate the dot product distance between two document vectors: 'docVector1' and 'docVector2' + * dotProductDistance("docVector1", Field.of("docVector2")); + * ``` + * + * @param expr The name of the field containing the first vector. + * @param other The other vector (represented as an Expr) to compare against. + * @return A new {@code Expr} representing the dot product distance between the two vectors. + */ export function dotProductDistance( expr: string, other: Expr ): DotProductDistance; + +/** + * Calculates the dot product distance between a vector expression and a double array. + * + * ```typescript + * // Calculate the dot product distance between a feature vector and a target vector + * dotProductDistance(Field.of("features"), [0.5, 0.8, 0.2]); + * ``` + * + * @param expr The first vector (represented as an Expr) to compare against. + * @param other The other vector (as an array of doubles) to compare against. + * @return A new {@code Expr} representing the dot product distance between the two vectors. + */ export function dotProductDistance( - expr: string, + expr: Expr, other: number[] ): DotProductDistance; + +/** + * Calculates the dot product distance between a vector expression and a VectorValue. + * + * ```typescript + * // Calculate the dot product distance between a feature vector and a target vector + * dotProductDistance(Field.of("features"), new VectorValue([0.5, 0.8, 0.2])); + * ``` + * + * @param expr The first vector (represented as an Expr) to compare against. + * @param other The other vector (as a VectorValue) to compare against. + * @return A new {@code Expr} representing the dot product distance between the two vectors. + */ export function dotProductDistance( - expr: string, + expr: Expr, other: VectorValue ): DotProductDistance; + +/** + * Calculates the dot product distance between two vector expressions. + * + * ```typescript + * // Calculate the dot product distance between two document vectors: 'docVector1' and 'docVector2' + * dotProductDistance(Field.of("docVector1"), Field.of("docVector2")); + * ``` + * + * @param expr The first vector (represented as an Expr) to compare against. + * @param other The other vector (represented as an Expr) to compare against. + * @return A new {@code Expr} representing the dot product distance between the two vectors. + */ +export function dotProductDistance(expr: Expr, other: Expr): DotProductDistance; export function dotProductDistance( expr: Expr | string, other: Expr | number[] | VectorValue @@ -1362,24 +4026,102 @@ export function dotProductDistance( return new DotProductDistance(expr1, expr2); } -export function euclideanDistance(expr: Expr, other: Expr): EuclideanDistance; +/** + * Calculates the Euclidean distance between a field's vector value and a double array. + * + * ```typescript + * // Calculate the Euclidean distance between the 'location' field and a target location + * euclideanDistance("location", [37.7749, -122.4194]); + * ``` + * + * @param expr The name of the field containing the first vector. + * @param other The other vector (as an array of doubles) to compare against. + * @return A new {@code Expr} representing the Euclidean distance between the two vectors. + */ export function euclideanDistance( - expr: Expr, + expr: string, other: number[] ): EuclideanDistance; + +/** + * Calculates the Euclidean distance between a field's vector value and a VectorValue. + * + * ```typescript + * // Calculate the Euclidean distance between the 'location' field and a target location + * euclideanDistance("location", new VectorValue([37.7749, -122.4194])); + * ``` + * + * @param expr The name of the field containing the first vector. + * @param other The other vector (as a VectorValue) to compare against. + * @return A new {@code Expr} representing the Euclidean distance between the two vectors. + */ export function euclideanDistance( - expr: Expr, + expr: string, other: VectorValue ): EuclideanDistance; + +/** + * Calculates the Euclidean distance between a field's vector value and a vector expression. + * + * ```typescript + * // Calculate the Euclidean distance between two vector fields: 'pointA' and 'pointB' + * euclideanDistance("pointA", Field.of("pointB")); + * ``` + * + * @param expr The name of the field containing the first vector. + * @param other The other vector (represented as an Expr) to compare against. + * @return A new {@code Expr} representing the Euclidean distance between the two vectors. + */ export function euclideanDistance(expr: string, other: Expr): EuclideanDistance; + +/** + * Calculates the Euclidean distance between a vector expression and a double array. + * + * ```typescript + * // Calculate the Euclidean distance between the 'location' field and a target location + * + * euclideanDistance(Field.of("location"), [37.7749, -122.4194]); + * ``` + * + * @param expr The first vector (represented as an Expr) to compare against. + * @param other The other vector (as an array of doubles) to compare against. + * @return A new {@code Expr} representing the Euclidean distance between the two vectors. + */ export function euclideanDistance( - expr: string, + expr: Expr, other: number[] ): EuclideanDistance; + +/** + * Calculates the Euclidean distance between a vector expression and a VectorValue. + * + * ```typescript + * // Calculate the Euclidean distance between the 'location' field and a target location + * euclideanDistance(Field.of("location"), new VectorValue([37.7749, -122.4194])); + * ``` + * + * @param expr The first vector (represented as an Expr) to compare against. + * @param other The other vector (as a VectorValue) to compare against. + * @return A new {@code Expr} representing the Euclidean distance between the two vectors. + */ export function euclideanDistance( - expr: string, + expr: Expr, other: VectorValue ): EuclideanDistance; + +/** + * Calculates the Euclidean distance between two vector expressions. + * + * ```typescript + * // Calculate the Euclidean distance between two vector fields: 'pointA' and 'pointB' + * euclideanDistance(Field.of("pointA"), Field.of("pointB")); + * ``` + * + * @param expr The first vector (represented as an Expr) to compare against. + * @param other The other vector (represented as an Expr) to compare against. + * @return A new {@code Expr} representing the Euclidean distance between the two vectors. + */ +export function euclideanDistance(expr: Expr, other: Expr): EuclideanDistance; export function euclideanDistance( expr: Expr | string, other: Expr | number[] | VectorValue @@ -1389,29 +4131,66 @@ export function euclideanDistance( return new EuclideanDistance(expr1, expr2); } +/** + * Creates functions that work on the backend but do not exist in the SDK yet. + * + * ```typescript + * // Call a user defined function named "myFunc" with the arguments 10 and 20 + * // This is the same of the 'sum(Field.of("price"))', if it did not exist + * genericFunction("sum", [Field.of("price")]); + * ``` + * + * @param name The name of the user defined function. + * @param params The arguments to pass to the function. + * @return A new {@code Function} representing the function call. + */ export function genericFunction(name: string, params: Expr[]): Function { return new Function(name, params); } +/** + * Creates an {@link Ordering} that sorts documents in ascending order based on this expression. + * + * ```typescript + * // Sort documents by the 'name' field in ascending order + * firestore.pipeline().collection("users") + * .sort(ascending(Field.of("name"))); + * ``` + * + * @param expr The expression to create an ascending ordering for. + * @return A new `Ordering` for ascending sorting. + */ +export function ascending(expr: Expr): Ordering { + return new Ordering(expr, 'ascending'); +} + +/** + * Creates an {@link Ordering} that sorts documents in descending order based on this expression. + * + * ```typescript + * // Sort documents by the 'createdAt' field in descending order + * firestore.pipeline().collection("users") + * .sort(descending(Field.of("createdAt"))); + * ``` + * + * @param expr The expression to create a descending ordering for. + * @return A new `Ordering` for descending sorting. + */ +export function descending(expr: Expr): Ordering { + return new Ordering(expr, 'descending'); +} + +/** + * Represents an ordering criterion for sorting documents in a Firestore pipeline. + * + * You create `Ordering` instances using the `ascending` and `descending` helper functions. + */ export class Ordering { constructor( private expr: Expr, private direction: 'ascending' | 'descending' ) {} - static of( - expr: Expr, - direction: 'ascending' | 'descending' | undefined = undefined - ): Ordering { - return new Ordering(expr, direction || 'ascending'); - } - static ascending(expr: Expr): Ordering { - return new Ordering(expr, 'ascending'); - } - static descending(expr: Expr): Ordering { - return new Ordering(expr, 'descending'); - } - _toProto(serializer: Serializer): api.IValue { return { mapValue: { diff --git a/dev/src/pipeline-util.ts b/dev/src/pipeline-util.ts index 21ba1e77d..f4fdd886f 100644 --- a/dev/src/pipeline-util.ts +++ b/dev/src/pipeline-util.ts @@ -390,9 +390,9 @@ export function toPipelineFilterCondition( } } else if (f.isNullChecking()) { if (f.nullOp() === 'IS_NULL') { - return and(field.exists(), field.isNull()); + return and(field.exists(), field.eq(null)); } else { - return and(field.exists(), not(field.isNull())); + return and(field.exists(), not(field.eq(null))); } } else { // Comparison filters diff --git a/dev/src/pipeline.ts b/dev/src/pipeline.ts index 2976a8272..d663267a1 100644 --- a/dev/src/pipeline.ts +++ b/dev/src/pipeline.ts @@ -9,6 +9,7 @@ import { Field, Fields, FilterCondition, + Function, Ordering, Selectable, } from './expression'; @@ -63,6 +64,46 @@ export class PipelineSource { } } +/** + * The Pipeline class provides a flexible and expressive framework for building complex data + * transformation and query pipelines for Firestore. + * + * A pipeline takes data sources, such as Firestore collections or collection groups, and applies + * a series of stages that are chained together. Each stage takes the output from the previous stage + * (or the data source) and produces an output for the next stage (or as the final output of the + * pipeline). + * + * Expressions can be used within each stage to filter and transform data through the stage. + * + * NOTE: The chained stages do not prescribe exactly how Firestore will execute the pipeline. + * Instead, Firestore only guarantees that the result is the same as if the chained stages were + * executed in order. + * + * Usage Examples: + * + * ```typescript + * const db: Firestore; // Assumes a valid firestore instance. + * + * // Example 1: Select specific fields and rename 'rating' to 'bookRating' + * const results1 = await db.pipeline() + * .collection("books") + * .select("title", "author", Field.of("rating").as("bookRating")) + * .execute(); + * + * // Example 2: Filter documents where 'genre' is "Science Fiction" and 'published' is after 1950 + * const results2 = await db.pipeline() + * .collection("books") + * .where(and(Field.of("genre").eq("Science Fiction"), Field.of("published").gt(1950))) + * .execute(); + * + * // Example 3: Calculate the average rating of books published after 1980 + * const results3 = await db.pipeline() + * .collection("books") + * .where(Field.of("published").gt(1980)) + * .aggregate(avg(Field.of("rating")).as("averageRating")) + * .execute(); + * ``` + */ export class Pipeline< AppModelType = firestore.DocumentData, DbModelType extends firestore.DocumentData = firestore.DocumentData, @@ -72,13 +113,89 @@ export class Pipeline< private stages: Stage[] ) {} + /** + * Adds new fields to outputs from previous stages. + * + * This stage allows you to compute values on-the-fly based on existing data from previous + * stages or constants. You can use this to create new fields or overwrite existing ones (if there + * is name overlaps). + * + * The added fields are defined using {@link Selectable}s, which can be: + * + * - {@link Field}: References an existing document field. + * - {@link Function}: Performs a calculation using functions like `add`, `multiply` with + * assigned aliases using {@link Expr#as}. + * + * Example: + * + * ```typescript + * firestore.pipeline().collection("books") + * .addFields( + * Field.of("rating").as("bookRating"), // Rename 'rating' to 'bookRating' + * add(5, Field.of("quantity")).as("totalCost") // Calculate 'totalCost' + * ); + * ``` + * + * @param fields The fields to add to the documents, specified as {@link Selectable}s. + * @return A new Pipeline object with this stage appended to the stage list. + */ addFields(...fields: Selectable[]): Pipeline { const copy = this.stages.map(s => s); copy.push(new AddField(this.selectablesToMap(fields))); return new Pipeline(this.db, copy); } + /** + * Selects a set of fields from the outputs of previous stages. + * + *

If no selections are provided, the output of this stage is empty. Use {@link + * com.google.cloud.firestore.Pipeline#addFields} instead if only additions are + * desired. + * + *

Example: + * + * ```typescript + * firestore.collection("books") + * .select("name", "address"); + * + * // The above is a shorthand of this: + * firestore.pipeline().collection("books") + * .select(Field.of("name"), Field.of("address")); + * ``` + * + * @param fields The name of the fields to include in the output documents. + * @return A new Pipeline object with this stage appended to the stage list. + */ select(...fields: string[]): Pipeline; + /** + * Selects or creates a set of fields from the outputs of previous stages. + * + *

The selected fields are defined using {@link Selectable} expressions, which can be: + * + *

    + *
  • {@link Field}: References an existing document field.
  • + *
  • {@link Function}: Represents the result of a function with an assigned alias name using + * {@link Expr#as}
  • + *
+ * + *

If no selections are provided, the output of this stage is empty. Use {@link + * com.google.cloud.firestore.Pipeline#addFields} instead if only additions are + * desired. + * + *

Example: + * + * ```typescript + * firestore.pipeline().collection("books") + * .select( + * Field.of("name"), + * Field.of("address").toUppercase().as("upperAddress"), + * ); + * ``` + * + * @param selections The fields to include in the output documents, specified as {@link + * Selectable} expressions. + * @return A new Pipeline object with this stage appended to the stage list. + */ select(...fields: Selectable[]): Pipeline; select(...fields: (Selectable | string)[]): Pipeline { const copy = this.stages.map(s => s); @@ -108,31 +225,208 @@ export class Pipeline< return result; } + /** + * Filters the documents from previous stages to only include those matching the specified {@link + * FilterCondition}. + * + *

This stage allows you to apply conditions to the data, similar to a "WHERE" clause in SQL. + * You can filter documents based on their field values, using implementations of {@link + * FilterCondition}, typically including but not limited to: + * + *

    + *
  • field comparators: {@link Function#eq}, {@link Function#lt} (less than), {@link + * Function#gt} (greater than), etc.
  • + *
  • logical operators: {@link Function#and}, {@link Function#or}, {@link Function#not}, etc.
  • + *
  • advanced functions: {@link Function#regexMatch}, {@link + * Function#arrayContains}, etc.
  • + *
+ * + *

Example: + * + * ```typescript + * firestore.pipeline().collection("books") + * .where( + * and( + * gt(Field.of("rating"), 4.0), // Filter for ratings greater than 4.0 + * Field.of("genre").eq("Science Fiction") // Equivalent to gt("genre", "Science Fiction") + * ) + * ); + * ``` + * + * @param condition The {@link FilterCondition} to apply. + * @return A new Pipeline object with this stage appended to the stage list. + */ where(condition: FilterCondition & Expr): Pipeline { const copy = this.stages.map(s => s); copy.push(new Where(condition)); return new Pipeline(this.db, copy); } + /** + * Skips the first `offset` number of documents from the results of previous stages. + * + *

This stage is useful for implementing pagination in your pipelines, allowing you to retrieve + * results in chunks. It is typically used in conjunction with {@link #limit} to control the + * size of each page. + * + *

Example: + * + * ```typescript + * // Retrieve the second page of 20 results + * firestore.pipeline().collection("books") + * .sort(Field.of("published").descending()) + * .offset(20) // Skip the first 20 results + * .limit(20); // Take the next 20 results + * ``` + * + * @param offset The number of documents to skip. + * @return A new Pipeline object with this stage appended to the stage list. + */ offset(offset: number): Pipeline { const copy = this.stages.map(s => s); copy.push(new Offset(offset)); return new Pipeline(this.db, copy); } + /** + * Limits the maximum number of documents returned by previous stages to `limit`. + * + *

This stage is particularly useful when you want to retrieve a controlled subset of data from + * a potentially large result set. It's often used for: + * + *

    + *
  • **Pagination:** In combination with {@link #offset} to retrieve specific pages of + * results.
  • + *
  • **Limiting Data Retrieval:** To prevent excessive data transfer and improve performance, + * especially when dealing with large collections.
  • + *
+ * + *

Example: + * + * ```typescript + * // Limit the results to the top 10 highest-rated books + * firestore.pipeline().collection("books") + * .sort(Field.of("rating").descending()) + * .limit(10); + * ``` + * + * @param limit The maximum number of documents to return. + * @return A new Pipeline object with this stage appended to the stage list. + */ limit(limit: number): Pipeline { const copy = this.stages.map(s => s); copy.push(new Limit(limit)); return new Pipeline(this.db, copy); } + /** + * Returns a set of distinct field values from the inputs to this stage. + * + *

This stage run through the results from previous stages to include only results with unique + * combinations of values for the specified fields and produce these fields as the output. + * + *

Example: + * + * ```typescript + * // Get a list of unique genres. + * firestore.pipeline().collection("books") + * .distinct("genre"); + * ``` + * + * @param fields The fields to consider when determining distinct values. + * @return A new {@code Pipeline} object with this stage appended to the stage list. + */ + distinct(...fields: string[]): Pipeline; + + /** + * Returns a set of distinct {@link Expr} values from the inputs to this stage. + * + *

This stage run through the results from previous stages to include only results with unique + * combinations of {@link Expr} values ({@link Field}, {@link Function}, etc). + * + *

The parameters to this stage are defined using {@link Selectable} expressions, which can be: + * + *

    + *
  • {@link Field}: References an existing document field.
  • + *
  • {@link Function}: Represents the result of a function with an assigned alias name using + * {@link Expr#as}
  • + *
+ * + *

Example: + * + * ```typescript + * // Get a list of unique author names in uppercase and genre combinations. + * firestore.pipeline().collection("books") + * .distinct(toUppercase(Field.of("author")).as("authorName"), Field.of("genre")) + * .select("authorName"); + * ``` + * + * @param selectables The {@link Selectable} expressions to consider when determining distinct + * value combinations. + * @return A new {@code Pipeline} object with this stage appended to the stage list. + */ + distinct(...selectables: Selectable[]): Pipeline; distinct(...groups: (string | Selectable)[]): Pipeline { const copy = this.stages.map(s => s); copy.push(new Distinct(this.selectablesToMap(groups || []))); return new Pipeline(this.db, copy); } + /** + * Performs aggregation operations on the documents from previous stages. + * + *

This stage allows you to calculate aggregate values over a set of documents. You define the + * aggregations to perform using {@link AccumulatorTarget} expressions which are typically results of + * calling {@link Expr#as} on {@link Accumulator} instances. + * + *

Example: + * + * ```typescript + * // Calculate the average rating and the total number of books + * firestore.pipeline().collection("books") + * .aggregate( + * Field.of("rating").avg().as("averageRating"), + * countAll().as("totalBooks") + * ); + * ``` + * + * @param accumulators The {@link AccumulatorTarget} expressions, each wrapping an {@link Accumulator} + * and provide a name for the accumulated results. + * @return A new Pipeline object with this stage appended to the stage list. + */ aggregate(...accumulators: AccumulatorTarget[]): Pipeline; + /** + * Performs optionally grouped aggregation operations on the documents from previous stages. + * + *

This stage allows you to calculate aggregate values over a set of documents, optionally + * grouped by one or more fields or functions. You can specify: + * + *

    + *
  • **Grouping Fields or Functions:** One or more fields or functions to group the documents + * by. For each distinct combination of values in these fields, a separate group is created. + * If no grouping fields are provided, a single group containing all documents is used. Not + * specifying groups is the same as putting the entire inputs into one group.
  • + *
  • **Accumulators:** One or more accumulation operations to perform within each group. These + * are defined using {@link AccumulatorTarget} expressions, which are typically created by + * calling {@link Expr#as} on {@link Accumulator} instances. Each aggregation + * calculates a value (e.g., sum, average, count) based on the documents within its group.
  • + *
+ * + *

Example: + * + * ```typescript + * // Calculate the average rating for each genre. + * firestore.pipeline().collection("books") + * .aggregate({ + * accumulators: [avg(Field.of("rating")).as("avg_rating")] + * groups: ["genre"] + * }); + * ``` + * + * @param aggregate An {@link Aggregate} object that specifies the grouping fields (if any) and + * the aggregation operations to perform. + * @return A new {@code Pipeline} object with this stage appended to the stage list. + */ aggregate(options: { accumulators: AccumulatorTarget[]; groups?: (string | Selectable)[]; @@ -198,6 +492,30 @@ export class Pipeline< return new Pipeline(this.db, copy); } + /** + * Sorts the documents from previous stages based on one or more {@link Ordering} criteria. + * + *

This stage allows you to order the results of your pipeline. You can specify multiple {@link + * Ordering} instances to sort by multiple fields in ascending or descending order. If documents + * have the same value for a field used for sorting, the next specified ordering will be used. If + * all orderings result in equal comparison, the documents are considered equal and the order is + * unspecified. + * + *

Example: + * + * ```typescript + * // Sort books by rating in descending order, and then by title in ascending order for books + * // with the same rating + * firestore.pipeline().collection("books") + * .sort( + * Ordering.of(Field.of("rating")).descending(), + * Ordering.of(Field.of("title")) // Ascending order is the default + * ); + * ``` + * + * @param orders One or more {@link Ordering} instances specifying the sorting criteria. + * @return A new {@code Pipeline} object with this stage appended to the stage list. + */ sort(...orderings: Ordering[]): Pipeline; sort(options: { orderings: Ordering[]; @@ -217,38 +535,72 @@ export class Pipeline< const copy = this.stages.map(s => s); // Option object if ('orderings' in optionsOrOrderings) { - copy.push( - new Sort( - optionsOrOrderings.orderings, - optionsOrOrderings.density ?? 'unspecified', - optionsOrOrderings.truncation ?? 'unspecified' - ) - ); + copy.push(new Sort(optionsOrOrderings.orderings)); } else { // Ordering object - copy.push( - new Sort([optionsOrOrderings, ...rest], 'unspecified', 'unspecified') - ); + copy.push(new Sort([optionsOrOrderings, ...rest])); } return new Pipeline(this.db, copy); } - paginate(pageSize: number, orderings?: Ordering[]): PaginatingPipeline { - const copy = this.stages.map(s => s); - return new PaginatingPipeline( - new Pipeline(this.db, copy), - pageSize, - orderings - ); - } - + /** + * Adds a generic stage to the pipeline. + * + *

This method provides a flexible way to extend the pipeline's functionality by adding custom + * stages. Each generic stage is defined by a unique `name` and a set of `params` that control its + * behavior. + * + *

Example (Assuming there is no "where" stage available in SDK): + * + * ```typescript + * // Assume we don't have a built-in "where" stage + * firestore.pipeline().collection("books") + * .genericStage("where", [Field.of("published").lt(1900)]) // Custom "where" stage + * .select("title", "author"); + * ``` + * + * @param name The unique name of the generic stage to add. + * @param params A list of parameters to configure the generic stage's behavior. + * @return A new {@code Pipeline} object with this stage appended to the stage list. + */ genericStage(name: string, params: any[]): Pipeline { const copy = this.stages.map(s => s); copy.push(new GenerateStage(name, params)); return new Pipeline(this.db, copy); } + /** + * Executes this pipeline and returns a Promise to represent the asynchronous operation. + * + *

The returned Promise can be used to track the progress of the pipeline execution + * and retrieve the results (or handle any errors) asynchronously. + * + *

The pipeline results are returned as a list of {@link PipelineResult} objects. Each {@link + * PipelineResult} typically represents a single key/value map that has passed through all the + * stages of the pipeline, however this might differ depending on the stages involved in the + * pipeline. For example: + * + *

    + *
  • If there are no stages or only transformation stages, each {@link PipelineResult} + * represents a single document.
  • + *
  • If there is an aggregation, only a single {@link PipelineResult} is returned, + * representing the aggregated results over the entire dataset .
  • + *
  • If there is an aggregation stage with grouping, each {@link PipelineResult} represents a + * distinct group and its associated aggregated values.
  • + *
+ * + *

Example: + * + * ```typescript + * const futureResults = await firestore.pipeline().collection("books") + * .where(gt(Field.of("rating"), 4.5)) + * .select("title", "author", "rating") + * .execute(); + * ``` + * + * @return A Promise representing the asynchronous pipeline execution. + */ execute(): Promise>> { const util = new ExecutionUtil( this.db, @@ -257,6 +609,22 @@ export class Pipeline< return util._getResponse(this).then(result => result!); } + /** + * Executes this pipeline and streams the results as {@link PipelineResult}s. + * + * @returns {Stream.} A stream of + * PipelineResult. + * + * @example + * ```typescript + * firestore.pipeline().collection("books") + * .where(gt(Field.of("rating"), 4.5)) + * .select("title", "author", "rating") + * .stream() + * .on('data', (pipelineResult) => {}) + * .on('end', () => {}); + * ``` + */ stream(): NodeJS.ReadableStream { const util = new ExecutionUtil( this.db, @@ -280,61 +648,13 @@ export class Pipeline< } } -class PaginatingPipeline { - constructor( - private pipeline: Pipeline, - private pageSize: number, - private orderings?: Ordering[] - ) {} - - firstPage(): Pipeline { - return this.pipeline; - } - - lastPage(): Pipeline { - return this.pipeline; - } - - offset(): PaginatingPipeline { - return this; - } - - limit(): PaginatingPipeline { - return this; - } - - startAt(result: PipelineResult): PaginatingPipeline { - return this; - } - - startAfter(result: PipelineResult): PaginatingPipeline { - return this; - } - - endAt(result: PipelineResult): PaginatingPipeline { - return this; - } - - endBefore(result: PipelineResult): PaginatingPipeline { - return this; - } - - /** - * @internal - * @private - */ - withEndCursor(arg0: QueryCursor): PaginatingPipeline { - throw new Error('Method not implemented.'); - } - /** - * @internal - * @private - */ - withStartCursor(arg0: QueryCursor): PaginatingPipeline { - throw new Error('Method not implemented.'); - } -} - +/** + * A PipelineResult contains data read from a Firestore Pipeline. The data can be extracted with the + * {@link #data()} or {@link #get(String)} methods. + * + *

If the PipelineResult represents a non-document result, `ref` will return a undefined + * value. + */ export class PipelineResult< AppModelType = firestore.DocumentData, DbModelType extends firestore.DocumentData = firestore.DocumentData, @@ -343,7 +663,7 @@ export class PipelineResult< | DocumentReference | undefined; private _serializer: Serializer; - public readonly _readTime: Timestamp | undefined; + public readonly _executionTime: Timestamp | undefined; public readonly _createTime: Timestamp | undefined; public readonly _updateTime: Timestamp | undefined; @@ -355,12 +675,10 @@ export class PipelineResult< * @param ref The reference to the document. * @param _fieldsProto The fields of the Firestore `Document` Protobuf backing * this document (or undefined if the document does not exist). - * @param readTime The time when this snapshot was read (or undefined if + * @param readTime The time when this result was read (or undefined if * the document exists only locally). - * @param createTime The time when the document was created (or undefined if - * the document does not exist). - * @param updateTime The time when the document was last updated (or undefined - * if the document does not exist). + * @param createTime The time when the document was created if the result is a document, undefined otherwise. + * @param updateTime The time when the document was last updated if the result is a document, undefined otherwise. */ constructor( serializer: Serializer, @@ -376,56 +694,34 @@ export class PipelineResult< ) { this._ref = ref; this._serializer = serializer; - this._readTime = readTime; + this._executionTime = readTime; this._createTime = createTime; this._updateTime = updateTime; } + /** + * The reference of the document, if it is a document; otherwise `undefined`. + */ get ref(): DocumentReference | undefined { return this._ref; } /** - * The ID of the document for which this DocumentSnapshot contains data. + * The ID of the document for which this PipelineResult contains data, if it is a document; otherwise `undefined`. * * @type {string} - * @name DocumentSnapshot#id * @readonly * - * @example - * ``` - * let documentRef = firestore.doc('col/doc'); - * - * documentRef.get().then((documentSnapshot) => { - * if (documentSnapshot.exists) { - * console.log(`Document found with name '${documentSnapshot.id}'`); - * } - * }); - * ``` */ get id(): string | undefined { return this._ref?.id; } /** - * The time the document was created. Undefined for documents that don't - * exist. + * The time the document was created. Undefined if this result is not a document. * * @type {Timestamp|undefined} - * @name DocumentSnapshot#createTime * @readonly - * - * @example - * ``` - * let documentRef = firestore.doc('col/doc'); - * - * documentRef.get().then(documentSnapshot => { - * if (documentSnapshot.exists) { - * let createTime = documentSnapshot.createTime; - * console.log(`Document created at '${createTime.toDate()}'`); - * } - * }); - * ``` */ get createTime(): Timestamp | undefined { return this._createTime; @@ -433,54 +729,31 @@ export class PipelineResult< /** * The time the document was last updated (at the time the snapshot was - * generated). Undefined for documents that don't exist. + * generated). Undefined if this result is not a document. * * @type {Timestamp|undefined} - * @name DocumentSnapshot#updateTime * @readonly - * - * @example - * ``` - * let documentRef = firestore.doc('col/doc'); - * - * documentRef.get().then(documentSnapshot => { - * if (documentSnapshot.exists) { - * let updateTime = documentSnapshot.updateTime; - * console.log(`Document updated at '${updateTime.toDate()}'`); - * } - * }); - * ``` */ get updateTime(): Timestamp | undefined { return this._updateTime; } /** - * The time this snapshot was read. + * The time at which the pipeline producing this result is executed. * * @type {Timestamp} - * @name DocumentSnapshot#readTime * @readonly * - * @example - * ``` - * let documentRef = firestore.doc('col/doc'); - * - * documentRef.get().then(documentSnapshot => { - * let readTime = documentSnapshot.readTime; - * console.log(`Document read at '${readTime.toDate()}'`); - * }); - * ``` */ - get readTime(): Timestamp { - if (this._readTime === undefined) { + get executionTime(): Timestamp { + if (this._executionTime === undefined) { throw new Error("Called 'readTime' on a local document"); } - return this._readTime; + return this._executionTime; } /** - * Retrieves all fields in the document as an object. Returns 'undefined' if + * Retrieves all fields in the result as an object. Returns 'undefined' if * the document doesn't exist. * * @returns {T|undefined} An object containing all fields in the document or @@ -488,10 +761,10 @@ export class PipelineResult< * * @example * ``` - * let documentRef = firestore.doc('col/doc'); + * let p = firestore.pipeline().collection('col'); * - * documentRef.get().then(documentSnapshot => { - * let data = documentSnapshot.data(); + * p.execute().then(results => { + * let data = results[0].data(); * console.log(`Retrieved data: ${JSON.stringify(data)}`); * }); * ``` @@ -514,7 +787,7 @@ export class PipelineResult< new QueryDocumentSnapshot( untypedReference, this._fieldsProto!, - this.readTime, + this.executionTime, this.createTime!, this.updateTime! ) @@ -538,12 +811,10 @@ export class PipelineResult< * * @example * ``` - * let documentRef = firestore.doc('col/doc'); + * let p = firestore.pipeline().collection('col'); * - * documentRef.set({ a: { b: 'c' }}).then(() => { - * return documentRef.get(); - * }).then(documentSnapshot => { - * let field = documentSnapshot.get('a.b'); + * p.execute().then(results => { + * let field = results[0].get('a.b'); * console.log(`Retrieved field value: ${field}`); * }); * ``` @@ -595,11 +866,11 @@ export class PipelineResult< } /** - * Returns true if the document's data and path in this `DocumentSnapshot` is + * Returns true if the document's data and path in this `PipelineResult` is * equal to the provided value. * * @param {*} other The value to compare against. - * @return {boolean} true if this `DocumentSnapshot` is equal to the provided + * @return {boolean} true if this `PipelineResult` is equal to the provided * value. */ isEqual(other: PipelineResult): boolean { diff --git a/dev/src/reference/query.ts b/dev/src/reference/query.ts index e335ae2d1..42fbb7be1 100644 --- a/dev/src/reference/query.ts +++ b/dev/src/reference/query.ts @@ -717,7 +717,7 @@ export class Query< break; } } - return Ordering.of(Field.of(fieldOrder.field), dir); + return new Ordering(Field.of(fieldOrder.field), dir || 'ascending'); }); if (orderings.length > 0) { pipeline = pipeline.sort({ diff --git a/dev/src/stage.ts b/dev/src/stage.ts index 842b09cca..f6cd4faeb 100644 --- a/dev/src/stage.ts +++ b/dev/src/stage.ts @@ -215,20 +215,12 @@ export class Select implements Stage { export class Sort implements Stage { name = 'sort'; - constructor( - private orders: Ordering[], - private density: 'unspecified' | 'required', - private truncation: 'unspecified' | 'disabled' - ) {} + constructor(private orders: Ordering[]) {} _toProto(serializer: Serializer): api.Pipeline.IStage { return { name: this.name, args: this.orders.map(o => o._toProto(serializer)), - options: { - density: serializer.encodeValue(this.density)!, - truncation: serializer.encodeValue(this.truncation)!, - }, }; } } diff --git a/dev/src/v1/firestore_client.ts b/dev/src/v1/firestore_client.ts index 9affa770c..09be77e4f 100644 --- a/dev/src/v1/firestore_client.ts +++ b/dev/src/v1/firestore_client.ts @@ -1332,7 +1332,7 @@ export class FirestoreClient { options.otherArgs.headers = options.otherArgs.headers || {}; options.otherArgs.headers['x-goog-request-params'] = this._gaxModule.routingHeader.fromParams({ - parent: '', + parent: request.database ? `${request.database}/documents` : '', }); this.initialize(); return this.innerApiCalls.executePipeline(request, options); diff --git a/dev/system-test/pipeline.ts b/dev/system-test/pipeline.ts index 97d46eb38..283b472e7 100644 --- a/dev/system-test/pipeline.ts +++ b/dev/system-test/pipeline.ts @@ -36,7 +36,6 @@ import { lt, neq, not, - isNull, or, regexContains, regexMatch, @@ -646,7 +645,7 @@ describe.only('Pipeline class', () => { .pipeline() .where(not(Field.of('rating').isNaN())) .select( - isNull('rating').as('ratingIsNull'), + Field.of('rating').eq(null).as('ratingIsNull'), not(Field.of('rating').isNaN()).as('ratingIsNotNaN') ) .limit(1) From e95701770a9510e21da32479925b4383ff68377c Mon Sep 17 00:00:00 2001 From: Wu-Hui Date: Thu, 22 Aug 2024 15:18:11 -0400 Subject: [PATCH 06/60] Basic initial converter support --- dev/src/pipeline-util.ts | 11 ++-- dev/src/pipeline.ts | 119 +++++++++++++++++++++++++++++------- dev/src/types.ts | 19 ++++++ dev/system-test/pipeline.ts | 47 ++++++++++++-- types/firestore.d.ts | 30 +++++++++ 5 files changed, 194 insertions(+), 32 deletions(-) diff --git a/dev/src/pipeline-util.ts b/dev/src/pipeline-util.ts index f4fdd886f..c3fff41d3 100644 --- a/dev/src/pipeline-util.ts +++ b/dev/src/pipeline-util.ts @@ -1,5 +1,6 @@ import * as firestore from '@google-cloud/firestore'; import {GoogleError, serializer} from 'google-gax'; +import {converter} from 'protobufjs'; import {Duplex, Transform} from 'stream'; import {google} from '../protos/firestore_v1_proto_api'; @@ -49,7 +50,8 @@ export class ExecutionUtil< /** @private */ readonly _firestore: Firestore, /** @private */ - readonly _serializer: Serializer + readonly _serializer: Serializer, + readonly _converter: firestore.FirestorePipelineConverter ) {} _getResponse( @@ -169,12 +171,12 @@ export class ExecutionUtil< } const ref = result.name - ? new DocumentReference( + ? new DocumentReference( this._firestore, QualifiedResourcePath.fromSlashSeparatedString(result.name) ) : undefined; - output.result = new PipelineResult( + output.result = new PipelineResult( this._serializer, ref, result.fields || undefined, @@ -184,7 +186,8 @@ export class ExecutionUtil< : undefined, result.updateTime ? Timestamp.fromProto(result.updateTime!) - : undefined + : undefined, + this._converter ); return output; }) diff --git a/dev/src/pipeline.ts b/dev/src/pipeline.ts index d663267a1..a832f4a72 100644 --- a/dev/src/pipeline.ts +++ b/dev/src/pipeline.ts @@ -1,3 +1,4 @@ +import {DocumentData} from '@google-cloud/firestore'; import * as firestore from '@google-cloud/firestore'; import * as deepEqual from 'fast-deep-equal'; import {google} from '../protos/firestore_v1_proto_api'; @@ -36,7 +37,7 @@ import { Stage, Distinct, } from './stage'; -import {ApiMapValue, defaultConverter} from './types'; +import {ApiMapValue, defaultConverter, defaultPipelineConverter} from './types'; import * as protos from '../protos/firestore_v1_proto_api'; import api = protos.google.firestore.v1; import IStructuredPipeline = google.firestore.v1.IStructuredPipeline; @@ -110,7 +111,8 @@ export class Pipeline< > { constructor( private db: Firestore, - private stages: Stage[] + private stages: Stage[], + private converter: firestore.FirestorePipelineConverter = defaultConverter() ) {} /** @@ -570,6 +572,77 @@ export class Pipeline< return new Pipeline(this.db, copy); } + withConverter(converter: null): Pipeline; + withConverter< + NewAppModelType, + NewDbModelType extends firestore.DocumentData = firestore.DocumentData, + >( + converter: firestore.FirestorePipelineConverter + ): Pipeline; + /** + * Applies a custom data converter to this Query, allowing you to use your + * own custom model objects with Firestore. When you call get() on the + * returned Query, the provided converter will convert between Firestore + * data of type `NewDbModelType` and your custom type `NewAppModelType`. + * + * Using the converter allows you to specify generic type arguments when + * storing and retrieving objects from Firestore. + * + * Passing in `null` as the converter parameter removes the current + * converter. + * + * @example + * ``` + * class Post { + * constructor(readonly title: string, readonly author: string) {} + * + * toString(): string { + * return this.title + ', by ' + this.author; + * } + * } + * + * const postConverter = { + * toFirestore(post: Post): FirebaseFirestore.DocumentData { + * return {title: post.title, author: post.author}; + * }, + * fromFirestore( + * snapshot: FirebaseFirestore.QueryDocumentSnapshot + * ): Post { + * const data = snapshot.data(); + * return new Post(data.title, data.author); + * } + * }; + * + * const postSnap = await Firestore() + * .collection('posts') + * .withConverter(postConverter) + * .doc().get(); + * const post = postSnap.data(); + * if (post !== undefined) { + * post.title; // string + * post.toString(); // Should be defined + * post.someNonExistentProperty; // TS error + * } + * + * ``` + * @param {FirestoreDataConverter | null} converter Converts objects to and + * from Firestore. Passing in `null` removes the current converter. + * @return A Query that uses the provided converter. + */ + withConverter< + NewAppModelType, + NewDbModelType extends firestore.DocumentData = firestore.DocumentData, + >( + converter: firestore.FirestorePipelineConverter | null + ): Pipeline { + const copy = this.stages.map(s => s); + return new Pipeline( + this.db, + copy, + converter ?? defaultPipelineConverter() + ); + } + /** * Executes this pipeline and returns a Promise to represent the asynchronous operation. * @@ -604,7 +677,8 @@ export class Pipeline< execute(): Promise>> { const util = new ExecutionUtil( this.db, - this.db._serializer! + this.db._serializer!, + this.converter ); return util._getResponse(this).then(result => result!); } @@ -628,7 +702,8 @@ export class Pipeline< stream(): NodeJS.ReadableStream { const util = new ExecutionUtil( this.db, - this.db._serializer! + this.db._serializer!, + this.converter ); return util.stream(this); } @@ -658,10 +733,9 @@ export class Pipeline< export class PipelineResult< AppModelType = firestore.DocumentData, DbModelType extends firestore.DocumentData = firestore.DocumentData, -> { - private readonly _ref: - | DocumentReference - | undefined; +> implements firestore.PipelineResult +{ + private readonly _ref: DocumentReference | undefined; private _serializer: Serializer; public readonly _executionTime: Timestamp | undefined; public readonly _createTime: Timestamp | undefined; @@ -682,7 +756,7 @@ export class PipelineResult< */ constructor( serializer: Serializer, - ref?: DocumentReference, + ref?: DocumentReference, /** * @internal * @private @@ -690,7 +764,8 @@ export class PipelineResult< readonly _fieldsProto?: ApiMapValue, readTime?: Timestamp, createTime?: Timestamp, - updateTime?: Timestamp + updateTime?: Timestamp, + readonly converter: firestore.FirestorePipelineConverter = defaultConverter() ) { this._ref = ref; this._serializer = serializer; @@ -702,7 +777,7 @@ export class PipelineResult< /** * The reference of the document, if it is a document; otherwise `undefined`. */ - get ref(): DocumentReference | undefined { + get ref(): DocumentReference | undefined { return this._ref; } @@ -778,18 +853,16 @@ export class PipelineResult< // We only want to use the converter and create a new QueryDocumentSnapshot // if a converter has been provided. - if (!!this.ref && this.ref._converter !== defaultConverter()) { - const untypedReference = new DocumentReference( - this.ref.firestore, - this.ref._path - ); - return this.ref._converter.fromFirestore( - new QueryDocumentSnapshot( - untypedReference, - this._fieldsProto!, - this.executionTime, - this.createTime!, - this.updateTime! + if (!!this.converter && this.converter !== defaultPipelineConverter()) { + return this.converter.fromFirestore( + new PipelineResult( + this._serializer, + this.ref, + this._fieldsProto, + this._executionTime, + this.createTime, + this.updateTime, + defaultPipelineConverter() ) ); } else { diff --git a/dev/src/types.ts b/dev/src/types.ts index 45d926818..26e8be080 100644 --- a/dev/src/types.ts +++ b/dev/src/types.ts @@ -19,6 +19,7 @@ import { QueryDocumentSnapshot, DocumentData, WithFieldValue, + FirestorePipelineConverter, } from '@google-cloud/firestore'; import {CallOptions} from 'google-gax'; @@ -26,6 +27,7 @@ import {Duplex} from 'stream'; import {google} from '../protos/firestore_v1_proto_api'; import {FieldPath} from './path'; +import {PipelineResult} from './pipeline'; import api = google.firestore.v1; @@ -151,6 +153,23 @@ export function defaultConverter< >; } +const defaultPipelineConverterObj: FirestorePipelineConverter = { + fromFirestore(snapshot: PipelineResult): DocumentData { + return snapshot.data()!; + }, +}; + +/** + * A default converter to use when none is provided. + * @private + * @internal + */ +export function defaultPipelineConverter< + AppModelType, +>(): FirestorePipelineConverter { + return defaultConverterObj as FirestoreDataConverter; +} + /** * Update data that has been resolved to a mapping of FieldPaths to values. */ diff --git a/dev/system-test/pipeline.ts b/dev/system-test/pipeline.ts index 283b472e7..a1b1d8f74 100644 --- a/dev/system-test/pipeline.ts +++ b/dev/system-test/pipeline.ts @@ -1,6 +1,7 @@ import { AggregateQuery, DocumentData, + FirestorePipelineConverter, QuerySnapshot, VectorValue, } from '@google-cloud/firestore'; @@ -78,14 +79,17 @@ describe.only('Pipeline class', () => { return randomCol; } - function expectResults(result: PipelineResult[], ...docs: string[]): void; - function expectResults( - result: PipelineResult[], + function expectResults( + result: PipelineResult[], + ...docs: string[] + ): void; + function expectResults( + result: PipelineResult[], ...data: DocumentData[] ): void; - function expectResults( - result: PipelineResult[], + function expectResults( + result: PipelineResult[], ...data: DocumentData[] | string[] ): void { expect(result.length).to.equal(data.length); @@ -729,4 +733,37 @@ describe.only('Pipeline class', () => { {title: 'Dune', 'awards.hugo': true} ); }); + + it('testPipelineConverters', async () => { + type AppModel = {myTitle: string; myAuthor: string; myPublished: number}; + const converter: FirestorePipelineConverter = { + fromFirestore(result: FirebaseFirestore.PipelineResult): AppModel { + return { + myTitle: result.data()!.title as string, + myAuthor: result.data()!.author as string, + myPublished: result.data()!.published as number, + }; + }, + }; + + const results = await firestore + .pipeline() + .collection(randomCol.path) + .sort(Field.of('published').ascending()) + .limit(2) + .withConverter(converter) + .execute(); + + const objs = results.map(r => r.data()); + expect(objs[0]).to.deep.equal({ + myAuthor: 'Jane Austen', + myPublished: 1813, + myTitle: 'Pride and Prejudice', + }); + expect(objs[1]).to.deep.equal({ + myAuthor: 'Fyodor Dostoevsky', + myPublished: 1866, + myTitle: 'Crime and Punishment', + }); + }); }); diff --git a/types/firestore.d.ts b/types/firestore.d.ts index 76cf5e10f..b10ce3c99 100644 --- a/types/firestore.d.ts +++ b/types/firestore.d.ts @@ -380,6 +380,10 @@ declare namespace FirebaseFirestore { fromFirestore(snapshot: QueryDocumentSnapshot): AppModelType; } + export interface FirestorePipelineConverter { + fromFirestore(result: PipelineResult): AppModelType; + } + /** * Settings used to directly configure a `Firestore` instance. */ @@ -1659,6 +1663,32 @@ declare namespace FirebaseFirestore { data(): AppModelType; } + export class PipelineResult< + AppModelType = DocumentData, + DbModelType extends DocumentData = DocumentData, + > { + private constructor(); + + /** + * The time the document was created. + */ + readonly createTime: Timestamp | undefined; + + /** + * The time the document was last updated (at the time the snapshot was + * generated). + */ + readonly updateTime: Timestamp | undefined; + + /** + * Retrieves all fields in the document as an Object. + * + * @override + * @return An Object containing all fields in the document. + */ + data(): AppModelType | undefined; + } + /** * The direction of a `Query.orderBy()` clause is specified as 'desc' or 'asc' * (descending or ascending). From 50f061bdc9ce850662beaf5fd7ad68f2b0bb96b6 Mon Sep 17 00:00:00 2001 From: Wu-Hui Date: Mon, 26 Aug 2024 09:49:19 -0400 Subject: [PATCH 07/60] Converter cleanup --- dev/src/pipeline-util.ts | 53 ++++++++++++++++--------------------- dev/src/pipeline.ts | 37 +++++++++----------------- dev/src/reference/types.ts | 2 +- dev/system-test/pipeline.ts | 2 +- types/firestore.d.ts | 5 +--- 5 files changed, 39 insertions(+), 60 deletions(-) diff --git a/dev/src/pipeline-util.ts b/dev/src/pipeline-util.ts index c3fff41d3..ce6677b9a 100644 --- a/dev/src/pipeline-util.ts +++ b/dev/src/pipeline-util.ts @@ -42,10 +42,7 @@ import api = protos.google.firestore.v1; * @private * @internal */ -export class ExecutionUtil< - AppModelType, - DbModelType extends firestore.DocumentData, -> { +export class ExecutionUtil { constructor( /** @private */ readonly _firestore: Firestore, @@ -55,15 +52,15 @@ export class ExecutionUtil< ) {} _getResponse( - pipeline: Pipeline, + pipeline: Pipeline, transactionOrReadTime?: Uint8Array | Timestamp | api.ITransactionOptions, explainOptions?: firestore.ExplainOptions - ): Promise> | undefined> { + ): Promise> | undefined> { // Capture the error stack to preserve stack tracing across async calls. const stack = Error().stack!; return new Promise((resolve, reject) => { - const results: Array> = []; + const results: Array> = []; const output: Omit, 'result'> & { executionTime?: Timestamp; } = {}; @@ -72,25 +69,22 @@ export class ExecutionUtil< .on('error', err => { reject(wrapError(err, stack)); }) - .on( - 'data', - (data: PipelineStreamElement[]) => { - for (const element of data) { - if (element.transaction) { - output.transaction = element.transaction; - } - if (element.executionTime) { - output.executionTime = element.executionTime; - } - if (element.explainMetrics) { - output.explainMetrics = element.explainMetrics; - } - if (element.result) { - results.push(element.result); - } + .on('data', (data: PipelineStreamElement[]) => { + for (const element of data) { + if (element.transaction) { + output.transaction = element.transaction; + } + if (element.executionTime) { + output.executionTime = element.executionTime; + } + if (element.explainMetrics) { + output.explainMetrics = element.explainMetrics; + } + if (element.result) { + results.push(element.result); } } - ) + }) .on('end', () => { resolve(results); }); @@ -111,7 +105,7 @@ export class ExecutionUtil< return Date.now() - startTime >= totalTimeout; } - stream(pipeline: Pipeline): NodeJS.ReadableStream { + stream(pipeline: Pipeline): NodeJS.ReadableStream { const responseStream = this._stream(pipeline); const transform = new Transform({ objectMode: true, @@ -126,7 +120,7 @@ export class ExecutionUtil< } _stream( - pipeline: Pipeline, + pipeline: Pipeline, transactionOrReadTime?: Uint8Array | Timestamp | api.ITransactionOptions, explainOptions?: firestore.ExplainOptions ): NodeJS.ReadableStream { @@ -149,7 +143,7 @@ export class ExecutionUtil< } if (proto.results && proto.results.length === 0) { - const output: PipelineStreamElement = {}; + const output: PipelineStreamElement = {}; if (proto.transaction?.length) { output.transaction = proto.transaction; } @@ -161,8 +155,7 @@ export class ExecutionUtil< callback( undefined, proto.results.map(result => { - const output: PipelineStreamElement = - {}; + const output: PipelineStreamElement = {}; if (proto.transaction?.length) { output.transaction = proto.transaction; } @@ -176,7 +169,7 @@ export class ExecutionUtil< QualifiedResourcePath.fromSlashSeparatedString(result.name) ) : undefined; - output.result = new PipelineResult( + output.result = new PipelineResult( this._serializer, ref, result.fields || undefined, diff --git a/dev/src/pipeline.ts b/dev/src/pipeline.ts index a832f4a72..dc5d14025 100644 --- a/dev/src/pipeline.ts +++ b/dev/src/pipeline.ts @@ -105,10 +105,7 @@ export class PipelineSource { * .execute(); * ``` */ -export class Pipeline< - AppModelType = firestore.DocumentData, - DbModelType extends firestore.DocumentData = firestore.DocumentData, -> { +export class Pipeline { constructor( private db: Firestore, private stages: Stage[], @@ -573,12 +570,9 @@ export class Pipeline< } withConverter(converter: null): Pipeline; - withConverter< - NewAppModelType, - NewDbModelType extends firestore.DocumentData = firestore.DocumentData, - >( + withConverter( converter: firestore.FirestorePipelineConverter - ): Pipeline; + ): Pipeline; /** * Applies a custom data converter to this Query, allowing you to use your * own custom model objects with Firestore. When you call get() on the @@ -629,14 +623,11 @@ export class Pipeline< * from Firestore. Passing in `null` removes the current converter. * @return A Query that uses the provided converter. */ - withConverter< - NewAppModelType, - NewDbModelType extends firestore.DocumentData = firestore.DocumentData, - >( + withConverter( converter: firestore.FirestorePipelineConverter | null - ): Pipeline { + ): Pipeline { const copy = this.stages.map(s => s); - return new Pipeline( + return new Pipeline( this.db, copy, converter ?? defaultPipelineConverter() @@ -674,8 +665,8 @@ export class Pipeline< * * @return A Promise representing the asynchronous pipeline execution. */ - execute(): Promise>> { - const util = new ExecutionUtil( + execute(): Promise>> { + const util = new ExecutionUtil( this.db, this.db._serializer!, this.converter @@ -700,7 +691,7 @@ export class Pipeline< * ``` */ stream(): NodeJS.ReadableStream { - const util = new ExecutionUtil( + const util = new ExecutionUtil( this.db, this.db._serializer!, this.converter @@ -730,10 +721,8 @@ export class Pipeline< *

If the PipelineResult represents a non-document result, `ref` will return a undefined * value. */ -export class PipelineResult< - AppModelType = firestore.DocumentData, - DbModelType extends firestore.DocumentData = firestore.DocumentData, -> implements firestore.PipelineResult +export class PipelineResult + implements firestore.PipelineResult { private readonly _ref: DocumentReference | undefined; private _serializer: Serializer; @@ -855,7 +844,7 @@ export class PipelineResult< // if a converter has been provided. if (!!this.converter && this.converter !== defaultPipelineConverter()) { return this.converter.fromFirestore( - new PipelineResult( + new PipelineResult( this._serializer, this.ref, this._fieldsProto, @@ -946,7 +935,7 @@ export class PipelineResult< * @return {boolean} true if this `PipelineResult` is equal to the provided * value. */ - isEqual(other: PipelineResult): boolean { + isEqual(other: PipelineResult): boolean { return ( this === other || (isOptionalEqual(this._ref, other._ref) && diff --git a/dev/src/reference/types.ts b/dev/src/reference/types.ts index 96aa7098e..036994ff6 100644 --- a/dev/src/reference/types.ts +++ b/dev/src/reference/types.ts @@ -67,7 +67,7 @@ export interface PipelineStreamElement< transaction?: Uint8Array; executionTime?: Timestamp; explainMetrics?: ExplainMetrics; - result?: PipelineResult; + result?: PipelineResult; } /** diff --git a/dev/system-test/pipeline.ts b/dev/system-test/pipeline.ts index a1b1d8f74..a5b262cbf 100644 --- a/dev/system-test/pipeline.ts +++ b/dev/system-test/pipeline.ts @@ -734,7 +734,7 @@ describe.only('Pipeline class', () => { ); }); - it('testPipelineConverters', async () => { + it('pipeline converter works', async () => { type AppModel = {myTitle: string; myAuthor: string; myPublished: number}; const converter: FirestorePipelineConverter = { fromFirestore(result: FirebaseFirestore.PipelineResult): AppModel { diff --git a/types/firestore.d.ts b/types/firestore.d.ts index b10ce3c99..0c4f0a93d 100644 --- a/types/firestore.d.ts +++ b/types/firestore.d.ts @@ -1663,10 +1663,7 @@ declare namespace FirebaseFirestore { data(): AppModelType; } - export class PipelineResult< - AppModelType = DocumentData, - DbModelType extends DocumentData = DocumentData, - > { + export class PipelineResult { private constructor(); /** From 5947337db17cb72ac760f3ae602ae8bd6de31a0e Mon Sep 17 00:00:00 2001 From: Wu-Hui Date: Mon, 26 Aug 2024 11:44:21 -0400 Subject: [PATCH 08/60] Address some feedbacks and add more nested field test. --- dev/src/expression.ts | 14 +-- dev/src/pipeline.ts | 124 +++++++++------------------ dev/src/reference/aggregate-query.ts | 6 +- dev/src/reference/query.ts | 6 +- dev/src/stage.ts | 2 +- dev/system-test/pipeline.ts | 53 +++++++++--- 6 files changed, 93 insertions(+), 112 deletions(-) diff --git a/dev/src/expression.ts b/dev/src/expression.ts index 3fde72f9d..32c46e063 100644 --- a/dev/src/expression.ts +++ b/dev/src/expression.ts @@ -999,7 +999,7 @@ export abstract class Expr { if (other instanceof Expr) { return new CosineDistance(this, other); } else { - return new CosineDistance(this, Constant.ofVector(other)); + return new CosineDistance(this, Constant.vector(other)); } } @@ -1045,7 +1045,7 @@ export abstract class Expr { if (other instanceof Expr) { return new DotProductDistance(this, other); } else { - return new DotProductDistance(this, Constant.ofVector(other)); + return new DotProductDistance(this, Constant.vector(other)); } } @@ -1091,7 +1091,7 @@ export abstract class Expr { if (other instanceof Expr) { return new EuclideanDistance(this, other); } else { - return new EuclideanDistance(this, Constant.ofVector(other)); + return new EuclideanDistance(this, Constant.vector(other)); } } @@ -1444,7 +1444,7 @@ export class Constant extends Expr { * @param value The VectorValue value. * @return A new `Constant` instance. */ - static ofVector(value: Array | VectorValue): Constant { + static vector(value: Array | VectorValue): Constant { if (value instanceof VectorValue) { return new Constant(value); } else { @@ -3915,7 +3915,7 @@ export function cosineDistance( other: Expr | number[] | VectorValue ): CosineDistance { const expr1 = expr instanceof Expr ? expr : Field.of(expr); - const expr2 = other instanceof Expr ? other : Constant.ofVector(other); + const expr2 = other instanceof Expr ? other : Constant.vector(other); return new CosineDistance(expr1, expr2); } @@ -4022,7 +4022,7 @@ export function dotProductDistance( other: Expr | number[] | VectorValue ): DotProductDistance { const expr1 = expr instanceof Expr ? expr : Field.of(expr); - const expr2 = other instanceof Expr ? other : Constant.ofVector(other); + const expr2 = other instanceof Expr ? other : Constant.vector(other); return new DotProductDistance(expr1, expr2); } @@ -4127,7 +4127,7 @@ export function euclideanDistance( other: Expr | number[] | VectorValue ): EuclideanDistance { const expr1 = expr instanceof Expr ? expr : Field.of(expr); - const expr2 = other instanceof Expr ? other : Constant.ofVector(other); + const expr2 = other instanceof Expr ? other : Constant.vector(other); return new EuclideanDistance(expr1, expr2); } diff --git a/dev/src/pipeline.ts b/dev/src/pipeline.ts index dc5d14025..7b0e7a285 100644 --- a/dev/src/pipeline.ts +++ b/dev/src/pipeline.ts @@ -29,7 +29,7 @@ import { Where, FindNearest, FindNearestOptions, - GenerateStage, + GenericStage, Limit, Offset, Select, @@ -138,41 +138,20 @@ export class Pipeline { * @param fields The fields to add to the documents, specified as {@link Selectable}s. * @return A new Pipeline object with this stage appended to the stage list. */ - addFields(...fields: Selectable[]): Pipeline { + addFields(...fields: Selectable[]): Pipeline { const copy = this.stages.map(s => s); copy.push(new AddField(this.selectablesToMap(fields))); - return new Pipeline(this.db, copy); + return new Pipeline(this.db, copy, this.converter); } - /** - * Selects a set of fields from the outputs of previous stages. - * - *

If no selections are provided, the output of this stage is empty. Use {@link - * com.google.cloud.firestore.Pipeline#addFields} instead if only additions are - * desired. - * - *

Example: - * - * ```typescript - * firestore.collection("books") - * .select("name", "address"); - * - * // The above is a shorthand of this: - * firestore.pipeline().collection("books") - * .select(Field.of("name"), Field.of("address")); - * ``` - * - * @param fields The name of the fields to include in the output documents. - * @return A new Pipeline object with this stage appended to the stage list. - */ - select(...fields: string[]): Pipeline; /** * Selects or creates a set of fields from the outputs of previous stages. * *

The selected fields are defined using {@link Selectable} expressions, which can be: * *

    - *
  • {@link Field}: References an existing document field.
  • + *
  • {@code string}: Name of an existing field
  • + *
  • {@link Field}: References an existing field.
  • *
  • {@link Function}: Represents the result of a function with an assigned alias name using * {@link Expr#as}
  • *
@@ -186,20 +165,20 @@ export class Pipeline { * ```typescript * firestore.pipeline().collection("books") * .select( - * Field.of("name"), + * "firstName", + * Field.of("lastName"), * Field.of("address").toUppercase().as("upperAddress"), * ); * ``` * * @param selections The fields to include in the output documents, specified as {@link - * Selectable} expressions. + * Selectable} expressions or {@code string} values representing field names. * @return A new Pipeline object with this stage appended to the stage list. */ - select(...fields: Selectable[]): Pipeline; - select(...fields: (Selectable | string)[]): Pipeline { + select(...fields: (Selectable | string)[]): Pipeline { const copy = this.stages.map(s => s); copy.push(new Select(this.selectablesToMap(fields))); - return new Pipeline(this.db, copy); + return new Pipeline(this.db, copy, this.converter); } private selectablesToMap( @@ -255,10 +234,10 @@ export class Pipeline { * @param condition The {@link FilterCondition} to apply. * @return A new Pipeline object with this stage appended to the stage list. */ - where(condition: FilterCondition & Expr): Pipeline { + where(condition: FilterCondition & Expr): Pipeline { const copy = this.stages.map(s => s); copy.push(new Where(condition)); - return new Pipeline(this.db, copy); + return new Pipeline(this.db, copy, this.converter); } /** @@ -281,10 +260,10 @@ export class Pipeline { * @param offset The number of documents to skip. * @return A new Pipeline object with this stage appended to the stage list. */ - offset(offset: number): Pipeline { + offset(offset: number): Pipeline { const copy = this.stages.map(s => s); copy.push(new Offset(offset)); - return new Pipeline(this.db, copy); + return new Pipeline(this.db, copy, this.converter); } /** @@ -312,40 +291,22 @@ export class Pipeline { * @param limit The maximum number of documents to return. * @return A new Pipeline object with this stage appended to the stage list. */ - limit(limit: number): Pipeline { + limit(limit: number): Pipeline { const copy = this.stages.map(s => s); copy.push(new Limit(limit)); - return new Pipeline(this.db, copy); + return new Pipeline(this.db, copy, this.converter); } - /** - * Returns a set of distinct field values from the inputs to this stage. - * - *

This stage run through the results from previous stages to include only results with unique - * combinations of values for the specified fields and produce these fields as the output. - * - *

Example: - * - * ```typescript - * // Get a list of unique genres. - * firestore.pipeline().collection("books") - * .distinct("genre"); - * ``` - * - * @param fields The fields to consider when determining distinct values. - * @return A new {@code Pipeline} object with this stage appended to the stage list. - */ - distinct(...fields: string[]): Pipeline; - /** * Returns a set of distinct {@link Expr} values from the inputs to this stage. * *

This stage run through the results from previous stages to include only results with unique * combinations of {@link Expr} values ({@link Field}, {@link Function}, etc). * - *

The parameters to this stage are defined using {@link Selectable} expressions, which can be: + *

The parameters to this stage are defined using {@link Selectable} expressions or {@code string}s: * *

    + *
  • {@code string}: Name of an existing field
  • *
  • {@link Field}: References an existing document field.
  • *
  • {@link Function}: Represents the result of a function with an assigned alias name using * {@link Expr#as}
  • @@ -356,19 +317,18 @@ export class Pipeline { * ```typescript * // Get a list of unique author names in uppercase and genre combinations. * firestore.pipeline().collection("books") - * .distinct(toUppercase(Field.of("author")).as("authorName"), Field.of("genre")) + * .distinct(toUppercase(Field.of("author")).as("authorName"), Field.of("genre"), "publishedAt") * .select("authorName"); * ``` * * @param selectables The {@link Selectable} expressions to consider when determining distinct - * value combinations. + * value combinations or {@code string}s representing field names. * @return A new {@code Pipeline} object with this stage appended to the stage list. */ - distinct(...selectables: Selectable[]): Pipeline; - distinct(...groups: (string | Selectable)[]): Pipeline { + distinct(...groups: (string | Selectable)[]): Pipeline { const copy = this.stages.map(s => s); copy.push(new Distinct(this.selectablesToMap(groups || []))); - return new Pipeline(this.db, copy); + return new Pipeline(this.db, copy, this.converter); } /** @@ -393,7 +353,7 @@ export class Pipeline { * and provide a name for the accumulated results. * @return A new Pipeline object with this stage appended to the stage list. */ - aggregate(...accumulators: AccumulatorTarget[]): Pipeline; + aggregate(...accumulators: AccumulatorTarget[]): Pipeline; /** * Performs optionally grouped aggregation operations on the documents from previous stages. * @@ -429,13 +389,13 @@ export class Pipeline { aggregate(options: { accumulators: AccumulatorTarget[]; groups?: (string | Selectable)[]; - }): Pipeline; + }): Pipeline; aggregate( optionsOrTarget: | AccumulatorTarget | {accumulators: AccumulatorTarget[]; groups?: (string | Selectable)[]}, ...rest: AccumulatorTarget[] - ): Pipeline { + ): Pipeline { const copy = this.stages.map(s => s); if ('accumulators' in optionsOrTarget) { copy.push( @@ -462,29 +422,29 @@ export class Pipeline { ) ); } - return new Pipeline(this.db, copy); + return new Pipeline(this.db, copy, this.converter); } findNearest( field: string, vector: number[], options: FindNearestOptions - ): Pipeline; + ): Pipeline; findNearest( field: Field, vector: FirebaseFirestore.VectorValue, options: FindNearestOptions - ): Pipeline; + ): Pipeline; findNearest( field: string | Field, vector: FirebaseFirestore.VectorValue | number[], options: FindNearestOptions - ): Pipeline; + ): Pipeline; findNearest( field: string | Field, vector: number[] | FirebaseFirestore.VectorValue, options: FindNearestOptions - ): Pipeline { + ): Pipeline { const copy = this.stages.map(s => s); const fieldExpr = typeof field === 'string' ? Field.of(field) : field; copy.push(new FindNearest(fieldExpr, vector, options)); @@ -515,22 +475,16 @@ export class Pipeline { * @param orders One or more {@link Ordering} instances specifying the sorting criteria. * @return A new {@code Pipeline} object with this stage appended to the stage list. */ - sort(...orderings: Ordering[]): Pipeline; - sort(options: { - orderings: Ordering[]; - density?: 'unspecified' | 'required'; - truncation?: 'unspecified' | 'disabled'; - }): Pipeline; + sort(...orderings: Ordering[]): Pipeline; + sort(options: {orderings: Ordering[]}): Pipeline; sort( optionsOrOrderings: | Ordering | { orderings: Ordering[]; - density?: 'unspecified' | 'required'; - truncation?: 'unspecified' | 'disabled'; }, ...rest: Ordering[] - ): Pipeline { + ): Pipeline { const copy = this.stages.map(s => s); // Option object if ('orderings' in optionsOrOrderings) { @@ -540,7 +494,7 @@ export class Pipeline { copy.push(new Sort([optionsOrOrderings, ...rest])); } - return new Pipeline(this.db, copy); + return new Pipeline(this.db, copy, this.converter); } /** @@ -563,10 +517,10 @@ export class Pipeline { * @param params A list of parameters to configure the generic stage's behavior. * @return A new {@code Pipeline} object with this stage appended to the stage list. */ - genericStage(name: string, params: any[]): Pipeline { + genericStage(name: string, params: any[]): Pipeline { const copy = this.stages.map(s => s); - copy.push(new GenerateStage(name, params)); - return new Pipeline(this.db, copy); + copy.push(new GenericStage(name, params)); + return new Pipeline(this.db, copy, this.converter); } withConverter(converter: null): Pipeline; @@ -811,7 +765,9 @@ export class PipelineResult */ get executionTime(): Timestamp { if (this._executionTime === undefined) { - throw new Error("Called 'readTime' on a local document"); + throw new Error( + "'executionTime' is expected to exist, but it is undefined" + ); } return this._executionTime; } diff --git a/dev/src/reference/aggregate-query.ts b/dev/src/reference/aggregate-query.ts index f614e0d4e..fa88567a2 100644 --- a/dev/src/reference/aggregate-query.ts +++ b/dev/src/reference/aggregate-query.ts @@ -340,7 +340,7 @@ export class AggregateQuery< return runQueryRequest; } - toPipeline(): Pipeline { + pipeline(): Pipeline { const aggregates = mapToArray( this._aggregates, (aggregate, clientAlias) => { @@ -351,8 +351,10 @@ export class AggregateQuery< return count(Field.of(aggregate._field)).as(clientAlias); } else if (aggregate.aggregateType === 'avg') { return avg(Field.of(aggregate._field!)).as(clientAlias); - } else { + } else if (aggregate.aggregateType === 'sum') { return sum(Field.of(aggregate._field!)).as(clientAlias); + } else { + throw new Error(`Unknown aggregate type ${aggregate.aggregateType}`); } } ); diff --git a/dev/src/reference/query.ts b/dev/src/reference/query.ts index 42fbb7be1..e6f1e8d4a 100644 --- a/dev/src/reference/query.ts +++ b/dev/src/reference/query.ts @@ -720,11 +720,7 @@ export class Query< return new Ordering(Field.of(fieldOrder.field), dir || 'ascending'); }); if (orderings.length > 0) { - pipeline = pipeline.sort({ - orderings: orderings, - density: 'required', - truncation: 'unspecified', - }); + pipeline = pipeline.sort({orderings: orderings}); } // Cursors, Limit and Offset diff --git a/dev/src/stage.ts b/dev/src/stage.ts index f6cd4faeb..de656fc03 100644 --- a/dev/src/stage.ts +++ b/dev/src/stage.ts @@ -225,7 +225,7 @@ export class Sort implements Stage { } } -export class GenerateStage implements Stage { +export class GenericStage implements Stage { constructor( public name: string, params: any[] diff --git a/dev/system-test/pipeline.ts b/dev/system-test/pipeline.ts index a5b262cbf..09c98f1a3 100644 --- a/dev/system-test/pipeline.ts +++ b/dev/system-test/pipeline.ts @@ -47,6 +47,7 @@ import { dotProductDistance, euclideanDistance, Constant, + mapGet, } from '../src/expression'; import {PipelineResult} from '../src/pipeline'; import {verifyInstance} from '../test/util/helpers'; @@ -126,7 +127,8 @@ describe.only('Pipeline class', () => { published: 1979, rating: 4.2, tags: ['comedy', 'space', 'adventure'], - awards: {hugo: true, nebula: false}, + awards: {hugo: true, nebula: false, others: {unknown: {year: 1980}}}, + nestedField: {'level.1': {'level.2': true}}, }, book2: { title: 'Pride and Prejudice', @@ -429,9 +431,9 @@ describe.only('Pipeline class', () => { const results = await randomCol .pipeline() .select( - arrayFilter(Field.of('tags'), arrayElement().eq('comedy')).as( - 'filteredTags' - ) + Field.of('tags') + .arrayFilter(arrayElement().eq('comedy')) + .as('filteredTags') ) .limit(1) .execute(); @@ -445,10 +447,9 @@ describe.only('Pipeline class', () => { const results = await randomCol .pipeline() .select( - arrayTransform( - Field.of('tags'), - arrayElement().strConcat('transformed') - ).as('transformedTags') + Field.of('tags') + .arrayTransform(arrayElement().strConcat('transformed')) + .as('transformedTags') ) .limit(1) .execute(); @@ -662,14 +663,19 @@ describe.only('Pipeline class', () => { .pipeline() .select( Field.of('awards').mapGet('hugo').as('hugoAward'), + Field.of('awards').mapGet('others').as('others'), Field.of('title') ) .where(eq('hugoAward', true)) .execute(); expectResults( results, - {hugoAward: true, title: "The Hitchhiker's Guide to the Galaxy"}, - {hugoAward: true, title: 'Dune'} + { + hugoAward: true, + title: "The Hitchhiker's Guide to the Galaxy", + others: {unknown: {year: 1980}}, + }, + {hugoAward: true, title: 'Dune', others: null} ); }); @@ -701,13 +707,13 @@ describe.only('Pipeline class', () => { const results = await randomCol .pipeline() .select( - cosineDistance(Constant.ofVector(sourceVector), targetVector).as( + cosineDistance(Constant.vector(sourceVector), targetVector).as( 'cosineDistance' ), - dotProductDistance(Constant.ofVector(sourceVector), targetVector).as( + dotProductDistance(Constant.vector(sourceVector), targetVector).as( 'dotProductDistance' ), - euclideanDistance(Constant.ofVector(sourceVector), targetVector).as( + euclideanDistance(Constant.vector(sourceVector), targetVector).as( 'euclideanDistance' ) ) @@ -734,6 +740,27 @@ describe.only('Pipeline class', () => { ); }); + it('test mapGet with field name including . notation', async () => { + const results = await randomCol + .pipeline() + .where(eq('awards.hugo', true)) + .select( + 'title', + Field.of('nestedField.level.1'), + mapGet('nestedField', 'level.1').mapGet('level.2').as('nested') + ) + .execute(); + expectResults( + results, + { + title: "The Hitchhiker's Guide to the Galaxy", + 'nestedField.level.`1`': null, + nested: true, + }, + {title: 'Dune', 'nestedField.level.`1`': null, nested: null} + ); + }); + it('pipeline converter works', async () => { type AppModel = {myTitle: string; myAuthor: string; myPublished: number}; const converter: FirestorePipelineConverter = { From 84e5eaba5e5c179de4498695f3a6b36b04178934 Mon Sep 17 00:00:00 2001 From: Wu-Hui Date: Mon, 26 Aug 2024 15:38:28 -0400 Subject: [PATCH 09/60] License header and tests fix --- dev/src/expression.ts | 14 ++++++++++++++ dev/src/pipeline-util.ts | 14 ++++++++++++++ dev/src/pipeline.ts | 14 ++++++++++++++ dev/src/stage.ts | 14 ++++++++++++++ dev/system-test/pipeline.ts | 23 ++++++++++++++++++++--- dev/system-test/query.ts | 14 ++++++++++++++ 6 files changed, 90 insertions(+), 3 deletions(-) diff --git a/dev/src/expression.ts b/dev/src/expression.ts index 32c46e063..410ae5886 100644 --- a/dev/src/expression.ts +++ b/dev/src/expression.ts @@ -1,3 +1,17 @@ +// 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. + import * as protos from '../protos/firestore_v1_proto_api'; import api = protos.google.firestore.v1; diff --git a/dev/src/pipeline-util.ts b/dev/src/pipeline-util.ts index ce6677b9a..866d90cc9 100644 --- a/dev/src/pipeline-util.ts +++ b/dev/src/pipeline-util.ts @@ -1,3 +1,17 @@ +// 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. + import * as firestore from '@google-cloud/firestore'; import {GoogleError, serializer} from 'google-gax'; import {converter} from 'protobufjs'; diff --git a/dev/src/pipeline.ts b/dev/src/pipeline.ts index 7b0e7a285..6f5d802f5 100644 --- a/dev/src/pipeline.ts +++ b/dev/src/pipeline.ts @@ -1,3 +1,17 @@ +// 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. + import {DocumentData} from '@google-cloud/firestore'; import * as firestore from '@google-cloud/firestore'; import * as deepEqual from 'fast-deep-equal'; diff --git a/dev/src/stage.ts b/dev/src/stage.ts index de656fc03..2dc941164 100644 --- a/dev/src/stage.ts +++ b/dev/src/stage.ts @@ -1,3 +1,17 @@ +// 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. + import * as protos from '../protos/firestore_v1_proto_api'; import api = protos.google.firestore.v1; diff --git a/dev/system-test/pipeline.ts b/dev/system-test/pipeline.ts index 09c98f1a3..0eca6211b 100644 --- a/dev/system-test/pipeline.ts +++ b/dev/system-test/pipeline.ts @@ -1,3 +1,17 @@ +// 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. + import { AggregateQuery, DocumentData, @@ -48,6 +62,7 @@ import { euclideanDistance, Constant, mapGet, + lte, } from '../src/expression'; import {PipelineResult} from '../src/pipeline'; import {verifyInstance} from '../test/util/helpers'; @@ -313,8 +328,9 @@ describe.only('Pipeline class', () => { }); it('can select fields', async () => { - const results = await randomCol + const results = await firestore .pipeline() + .collection(randomCol.path) .select('title', 'author') .sort(Field.of('author').ascending()) .execute(); @@ -359,8 +375,9 @@ describe.only('Pipeline class', () => { }); it('offset and limits', async () => { - const results = await randomCol + const results = await firestore .pipeline() + .collection(randomCol.path) .sort(Field.of('author').ascending()) .offset(5) .limit(3) @@ -607,7 +624,7 @@ describe.only('Pipeline class', () => { .where( and( gt('rating', 4.2), - lt(Field.of('rating'), 4.5), + lte(Field.of('rating'), 4.5), neq('genre', 'Science Fiction') ) ) diff --git a/dev/system-test/query.ts b/dev/system-test/query.ts index cc0b877d2..84853f79b 100644 --- a/dev/system-test/query.ts +++ b/dev/system-test/query.ts @@ -1,3 +1,17 @@ +// 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. + import { DocumentData, QuerySnapshot, From eff4589a610f5d2771a3b2012e7cf0b3cfc43d48 Mon Sep 17 00:00:00 2001 From: Wu-Hui Date: Mon, 26 Aug 2024 15:38:28 -0400 Subject: [PATCH 10/60] License header and tests fix --- dev/src/expression.ts | 459 ++++++++++++++++++++++++++++++++++++ dev/src/pipeline-util.ts | 14 ++ dev/src/pipeline.ts | 22 ++ dev/src/stage.ts | 14 ++ dev/system-test/pipeline.ts | 23 +- dev/system-test/query.ts | 14 ++ 6 files changed, 543 insertions(+), 3 deletions(-) diff --git a/dev/src/expression.ts b/dev/src/expression.ts index 32c46e063..edb7f8827 100644 --- a/dev/src/expression.ts +++ b/dev/src/expression.ts @@ -1,3 +1,17 @@ +// 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. + import * as protos from '../protos/firestore_v1_proto_api'; import api = protos.google.firestore.v1; @@ -13,6 +27,8 @@ import {Serializer} from './serializer'; import {Timestamp} from './timestamp'; /** + * @beta + * * An interface that represents a selectable expression. */ export interface Selectable { @@ -20,6 +36,8 @@ export interface Selectable { } /** + * @beta + * * An interface that represents a filter condition. */ export interface FilterCondition { @@ -27,6 +45,8 @@ export interface FilterCondition { } /** + * @beta + * * An interface that represents an accumulator. */ export interface Accumulator { @@ -34,21 +54,29 @@ export interface Accumulator { } /** + * @beta + * * An accumulator target, which is an expression with an alias that also implements the Accumulator interface. */ export type AccumulatorTarget = ExprWithAlias; /** + * @beta + * * A filter expression, which is an expression that also implements the FilterCondition interface. */ export type FilterExpr = Expr & FilterCondition; /** + * @beta + * * A selectable expression, which is an expression that also implements the Selectable interface. */ export type SelectableExpr = Expr & Selectable; /** + * @beta + * * An enumeration of the different types of expressions. */ export type ExprType = @@ -59,6 +87,8 @@ export type ExprType = | 'ExprWithAlias'; /** + * @beta + * * Represents an expression that can be evaluated to a value within the execution of a {@link * Pipeline}. * @@ -1148,6 +1178,9 @@ export abstract class Expr { abstract _toProto(serializer: Serializer): api.IValue; } +/** + * @beta + */ export class ExprWithAlias extends Expr implements Selectable { exprType: ExprType = 'ExprWithAlias'; selectable = true as const; @@ -1164,6 +1197,9 @@ export class ExprWithAlias extends Expr implements Selectable { } } +/** + * @internal + */ class ListOfExprs extends Expr { exprType: ExprType = 'ListOfExprs'; constructor(private exprs: Expr[]) { @@ -1180,6 +1216,8 @@ class ListOfExprs extends Expr { } /** + * @beta + * * Represents a reference to a field in a Firestore document, or outputs of a {@link Pipeline} stage. * *

    Field references are used to access document field values in expressions and to specify fields @@ -1261,6 +1299,9 @@ export class Field extends Expr implements Selectable { } } +/** + * @beta + */ export class Fields extends Expr implements Selectable { exprType: ExprType = 'Field'; selectable = true as const; @@ -1291,6 +1332,8 @@ export class Fields extends Expr implements Selectable { } /** + * @beta + * * Represents a constant value that can be used in a Firestore pipeline expression. * * You can create a `Constant` instance using the static {@link #of} method: @@ -1462,6 +1505,8 @@ export class Constant extends Expr { } /** + * @beta + * * This class defines the base class for Firestore {@link Pipeline} functions, which can be evaluated within pipeline * execution. * @@ -1487,6 +1532,9 @@ export class Function extends Expr { } } +/** + * @beta + */ export class Add extends Function { constructor( private left: Expr, @@ -1496,6 +1544,9 @@ export class Add extends Function { } } +/** + * @beta + */ export class Subtract extends Function { constructor( private left: Expr, @@ -1505,6 +1556,9 @@ export class Subtract extends Function { } } +/** + * @beta + */ export class Multiply extends Function { constructor( private left: Expr, @@ -1514,6 +1568,9 @@ export class Multiply extends Function { } } +/** + * @beta + */ export class Divide extends Function { constructor( private left: Expr, @@ -1523,6 +1580,9 @@ export class Divide extends Function { } } +/** + * @beta + */ export class Eq extends Function implements FilterCondition { constructor( private left: Expr, @@ -1533,6 +1593,9 @@ export class Eq extends Function implements FilterCondition { filterable = true as const; } +/** + * @beta + */ class Neq extends Function implements FilterCondition { constructor( private left: Expr, @@ -1543,6 +1606,9 @@ class Neq extends Function implements FilterCondition { filterable = true as const; } +/** + * @beta + */ class Lt extends Function implements FilterCondition { constructor( private left: Expr, @@ -1553,6 +1619,9 @@ class Lt extends Function implements FilterCondition { filterable = true as const; } +/** + * @beta + */ class Lte extends Function implements FilterCondition { constructor( private left: Expr, @@ -1563,6 +1632,9 @@ class Lte extends Function implements FilterCondition { filterable = true as const; } +/** + * @beta + */ class Gt extends Function implements FilterCondition { constructor( private left: Expr, @@ -1573,6 +1645,9 @@ class Gt extends Function implements FilterCondition { filterable = true as const; } +/** + * @beta + */ class Gte extends Function implements FilterCondition { constructor( private left: Expr, @@ -1583,6 +1658,9 @@ class Gte extends Function implements FilterCondition { filterable = true as const; } +/** + * @beta + */ class ArrayConcat extends Function { constructor( private array: Expr, @@ -1592,6 +1670,9 @@ class ArrayConcat extends Function { } } +/** + * @beta + */ class ArrayContains extends Function implements FilterCondition { constructor( private array: Expr, @@ -1602,6 +1683,9 @@ class ArrayContains extends Function implements FilterCondition { filterable = true as const; } +/** + * @beta + */ class ArrayContainsAll extends Function implements FilterCondition { constructor( private array: Expr, @@ -1612,6 +1696,9 @@ class ArrayContainsAll extends Function implements FilterCondition { filterable = true as const; } +/** + * @beta + */ class ArrayContainsAny extends Function implements FilterCondition { constructor( private array: Expr, @@ -1622,6 +1709,9 @@ class ArrayContainsAny extends Function implements FilterCondition { filterable = true as const; } +/** + * @beta + */ class ArrayFilter extends Function { constructor( private array: Expr, @@ -1631,12 +1721,18 @@ class ArrayFilter extends Function { } } +/** + * @beta + */ class ArrayLength extends Function { constructor(private array: Expr) { super('array_length', [array]); } } +/** + * @beta + */ class ArrayTransform extends Function { constructor( private array: Expr, @@ -1646,12 +1742,18 @@ class ArrayTransform extends Function { } } +/** + * @beta + */ class ArrayElement extends Function { constructor() { super('array_element', []); } } +/** + * @beta + */ class In extends Function implements FilterCondition { constructor( private left: Expr, @@ -1662,6 +1764,9 @@ class In extends Function implements FilterCondition { filterable = true as const; } +/** + * @beta + */ class IsNan extends Function implements FilterCondition { constructor(private expr: Expr) { super('is_nan', [expr]); @@ -1669,6 +1774,9 @@ class IsNan extends Function implements FilterCondition { filterable = true as const; } +/** + * @beta + */ class Exists extends Function implements FilterCondition { constructor(private expr: Expr) { super('exists', [expr]); @@ -1676,6 +1784,9 @@ class Exists extends Function implements FilterCondition { filterable = true as const; } +/** + * @beta + */ class Not extends Function implements FilterCondition { constructor(private expr: Expr) { super('not', [expr]); @@ -1683,6 +1794,9 @@ class Not extends Function implements FilterCondition { filterable = true as const; } +/** + * @beta + */ class And extends Function implements FilterCondition { constructor(private conditions: FilterExpr[]) { super('and', conditions); @@ -1691,6 +1805,9 @@ class And extends Function implements FilterCondition { filterable = true as const; } +/** + * @beta + */ class Or extends Function implements FilterCondition { constructor(private conditions: FilterExpr[]) { super('or', conditions); @@ -1698,6 +1815,9 @@ class Or extends Function implements FilterCondition { filterable = true as const; } +/** + * @beta + */ class Xor extends Function implements FilterCondition { constructor(private conditions: FilterExpr[]) { super('xor', conditions); @@ -1705,6 +1825,9 @@ class Xor extends Function implements FilterCondition { filterable = true as const; } +/** + * @beta + */ class If extends Function implements FilterCondition { constructor( private condition: FilterExpr, @@ -1716,12 +1839,18 @@ class If extends Function implements FilterCondition { filterable = true as const; } +/** + * @beta + */ class Length extends Function { constructor(private expr: Expr) { super('length', [expr]); } } +/** + * @beta + */ class Like extends Function implements FilterCondition { constructor( private expr: Expr, @@ -1732,6 +1861,9 @@ class Like extends Function implements FilterCondition { filterable = true as const; } +/** + * @beta + */ class RegexContains extends Function implements FilterCondition { constructor( private expr: Expr, @@ -1742,6 +1874,9 @@ class RegexContains extends Function implements FilterCondition { filterable = true as const; } +/** + * @beta + */ class RegexMatch extends Function implements FilterCondition { constructor( private expr: Expr, @@ -1752,6 +1887,9 @@ class RegexMatch extends Function implements FilterCondition { filterable = true as const; } +/** + * @beta + */ class StartsWith extends Function implements FilterCondition { constructor( private expr: Expr, @@ -1762,6 +1900,9 @@ class StartsWith extends Function implements FilterCondition { filterable = true as const; } +/** + * @beta + */ class EndsWith extends Function implements FilterCondition { constructor( private expr: Expr, @@ -1772,24 +1913,36 @@ class EndsWith extends Function implements FilterCondition { filterable = true as const; } +/** + * @beta + */ class ToLowercase extends Function { constructor(private expr: Expr) { super('to_lowercase', [expr]); } } +/** + * @beta + */ class ToUppercase extends Function { constructor(private expr: Expr) { super('to_uppercase', [expr]); } } +/** + * @beta + */ class Trim extends Function { constructor(private expr: Expr) { super('trim', [expr]); } } +/** + * @beta + */ class StrConcat extends Function { constructor( private first: Expr, @@ -1799,12 +1952,18 @@ class StrConcat extends Function { } } +/** + * @beta + */ class MapGet extends Function { constructor(map: Expr, name: string) { super('map_get', [map, Constant.of(name)]); } } +/** + * @beta + */ class Count extends Function implements Accumulator { accumulator = true as const; constructor( @@ -1815,6 +1974,9 @@ class Count extends Function implements Accumulator { } } +/** + * @beta + */ class Sum extends Function implements Accumulator { accumulator = true as const; constructor( @@ -1825,6 +1987,9 @@ class Sum extends Function implements Accumulator { } } +/** + * @beta + */ class Avg extends Function implements Accumulator { accumulator = true as const; constructor( @@ -1835,6 +2000,9 @@ class Avg extends Function implements Accumulator { } } +/** + * @beta + */ class Min extends Function implements Accumulator { accumulator = true as const; constructor( @@ -1845,6 +2013,9 @@ class Min extends Function implements Accumulator { } } +/** + * @beta + */ class Max extends Function implements Accumulator { accumulator = true as const; constructor( @@ -1855,6 +2026,9 @@ class Max extends Function implements Accumulator { } } +/** + * @beta + */ class CosineDistance extends Function { constructor( private vector1: Expr, @@ -1864,6 +2038,9 @@ class CosineDistance extends Function { } } +/** + * @beta + */ class DotProductDistance extends Function { constructor( private vector1: Expr, @@ -1873,6 +2050,9 @@ class DotProductDistance extends Function { } } +/** + * @beta + */ class EuclideanDistance extends Function { constructor( private vector1: Expr, @@ -1883,6 +2063,8 @@ class EuclideanDistance extends Function { } /** + * @beta + * * Creates an expression that adds two expressions together. * * ```typescript @@ -1897,6 +2079,8 @@ class EuclideanDistance extends Function { export function add(left: Expr, right: Expr): Add; /** + * @beta + * * Creates an expression that adds an expression to a constant value. * * ```typescript @@ -1911,6 +2095,8 @@ export function add(left: Expr, right: Expr): Add; export function add(left: Expr, right: any): Add; /** + * @beta + * * Creates an expression that adds a field's value to an expression. * * ```typescript @@ -1925,6 +2111,8 @@ export function add(left: Expr, right: any): Add; export function add(left: string, right: Expr): Add; /** + * @beta + * * Creates an expression that adds a field's value to a constant value. * * ```typescript @@ -1944,6 +2132,8 @@ export function add(left: Expr | string, right: Expr | any): Add { } /** + * @beta + * * Creates an expression that subtracts two expressions. * * ```typescript @@ -1958,6 +2148,8 @@ export function add(left: Expr | string, right: Expr | any): Add { export function subtract(left: Expr, right: Expr): Subtract; /** + * @beta + * * Creates an expression that subtracts a constant value from an expression. * * ```typescript @@ -1972,6 +2164,8 @@ export function subtract(left: Expr, right: Expr): Subtract; export function subtract(left: Expr, right: any): Subtract; /** + * @beta + * * Creates an expression that subtracts an expression from a field's value. * * ```typescript @@ -1986,6 +2180,8 @@ export function subtract(left: Expr, right: any): Subtract; export function subtract(left: string, right: Expr): Subtract; /** + * @beta + * * Creates an expression that subtracts a constant value from a field's value. * * ```typescript @@ -2005,6 +2201,8 @@ export function subtract(left: Expr | string, right: Expr | any): Subtract { } /** + * @beta + * * Creates an expression that multiplies two expressions together. * * ```typescript @@ -2019,6 +2217,8 @@ export function subtract(left: Expr | string, right: Expr | any): Subtract { export function multiply(left: Expr, right: Expr): Multiply; /** + * @beta + * * Creates an expression that multiplies an expression by a constant value. * * ```typescript @@ -2033,6 +2233,8 @@ export function multiply(left: Expr, right: Expr): Multiply; export function multiply(left: Expr, right: any): Multiply; /** + * @beta + * * Creates an expression that multiplies a field's value by an expression. * * ```typescript @@ -2047,6 +2249,8 @@ export function multiply(left: Expr, right: any): Multiply; export function multiply(left: string, right: Expr): Multiply; /** + * @beta + * * Creates an expression that multiplies a field's value by a constant value. * * ```typescript @@ -2066,6 +2270,8 @@ export function multiply(left: Expr | string, right: Expr | any): Multiply { } /** + * @beta + * * Creates an expression that divides two expressions. * * ```typescript @@ -2080,6 +2286,8 @@ export function multiply(left: Expr | string, right: Expr | any): Multiply { export function divide(left: Expr, right: Expr): Divide; /** + * @beta + * * Creates an expression that divides an expression by a constant value. * * ```typescript @@ -2094,6 +2302,8 @@ export function divide(left: Expr, right: Expr): Divide; export function divide(left: Expr, right: any): Divide; /** + * @beta + * * Creates an expression that divides a field's value by an expression. * * ```typescript @@ -2108,6 +2318,8 @@ export function divide(left: Expr, right: any): Divide; export function divide(left: string, right: Expr): Divide; /** + * @beta + * * Creates an expression that divides a field's value by a constant value. * * ```typescript @@ -2127,6 +2339,8 @@ export function divide(left: Expr | string, right: Expr | any): Divide { } /** + * @beta + * * Creates an expression that checks if two expressions are equal. * * ```typescript @@ -2141,6 +2355,8 @@ export function divide(left: Expr | string, right: Expr | any): Divide { export function eq(left: Expr, right: Expr): Eq; /** + * @beta + * * Creates an expression that checks if an expression is equal to a constant value. * * ```typescript @@ -2155,6 +2371,8 @@ export function eq(left: Expr, right: Expr): Eq; export function eq(left: Expr, right: any): Eq; /** + * @beta + * * Creates an expression that checks if a field's value is equal to an expression. * * ```typescript @@ -2169,6 +2387,8 @@ export function eq(left: Expr, right: any): Eq; export function eq(left: string, right: Expr): Eq; /** + * @beta + * * Creates an expression that checks if a field's value is equal to a constant value. * * ```typescript @@ -2188,6 +2408,8 @@ export function eq(left: Expr | string, right: any): Eq { } /** + * @beta + * * Creates an expression that checks if two expressions are not equal. * * ```typescript @@ -2202,6 +2424,8 @@ export function eq(left: Expr | string, right: any): Eq { export function neq(left: Expr, right: Expr): Neq; /** + * @beta + * * Creates an expression that checks if an expression is not equal to a constant value. * * ```typescript @@ -2216,6 +2440,8 @@ export function neq(left: Expr, right: Expr): Neq; export function neq(left: Expr, right: any): Neq; /** + * @beta + * * Creates an expression that checks if a field's value is not equal to an expression. * * ```typescript @@ -2230,6 +2456,8 @@ export function neq(left: Expr, right: any): Neq; export function neq(left: string, right: Expr): Neq; /** + * @beta + * * Creates an expression that checks if a field's value is not equal to a constant value. * * ```typescript @@ -2249,6 +2477,8 @@ export function neq(left: Expr | string, right: any): Neq { } /** + * @beta + * * Creates an expression that checks if the first expression is less than the second expression. * * ```typescript @@ -2263,6 +2493,8 @@ export function neq(left: Expr | string, right: any): Neq { export function lt(left: Expr, right: Expr): Lt; /** + * @beta + * * Creates an expression that checks if an expression is less than a constant value. * * ```typescript @@ -2277,6 +2509,8 @@ export function lt(left: Expr, right: Expr): Lt; export function lt(left: Expr, right: any): Lt; /** + * @beta + * * Creates an expression that checks if a field's value is less than an expression. * * ```typescript @@ -2291,6 +2525,8 @@ export function lt(left: Expr, right: any): Lt; export function lt(left: string, right: Expr): Lt; /** + * @beta + * * Creates an expression that checks if a field's value is less than a constant value. * * ```typescript @@ -2310,6 +2546,8 @@ export function lt(left: Expr | string, right: any): Lt { } /** + * @beta + * * Creates an expression that checks if the first expression is less than or equal to the second * expression. * @@ -2325,6 +2563,8 @@ export function lt(left: Expr | string, right: any): Lt { export function lte(left: Expr, right: Expr): Lte; /** + * @beta + * * Creates an expression that checks if an expression is less than or equal to a constant value. * * ```typescript @@ -2353,6 +2593,8 @@ export function lte(left: Expr, right: any): Lte; export function lte(left: string, right: Expr): Lte; /** + * @beta + * * Creates an expression that checks if a field's value is less than or equal to a constant value. * * ```typescript @@ -2372,6 +2614,8 @@ export function lte(left: Expr | string, right: any): Lte { } /** + * @beta + * * Creates an expression that checks if the first expression is greater than the second * expression. * @@ -2387,6 +2631,8 @@ export function lte(left: Expr | string, right: any): Lte { export function gt(left: Expr, right: Expr): Gt; /** + * @beta + * * Creates an expression that checks if an expression is greater than a constant value. * * ```typescript @@ -2401,6 +2647,8 @@ export function gt(left: Expr, right: Expr): Gt; export function gt(left: Expr, right: any): Gt; /** + * @beta + * * Creates an expression that checks if a field's value is greater than an expression. * * ```typescript @@ -2415,6 +2663,8 @@ export function gt(left: Expr, right: any): Gt; export function gt(left: string, right: Expr): Gt; /** + * @beta + * * Creates an expression that checks if a field's value is greater than a constant value. * * ```typescript @@ -2434,6 +2684,8 @@ export function gt(left: Expr | string, right: any): Gt { } /** + * @beta + * * Creates an expression that checks if the first expression is greater than or equal to the * second expression. * @@ -2449,6 +2701,8 @@ export function gt(left: Expr | string, right: any): Gt { export function gte(left: Expr, right: Expr): Gte; /** + * @beta + * * Creates an expression that checks if an expression is greater than or equal to a constant * value. * @@ -2464,6 +2718,8 @@ export function gte(left: Expr, right: Expr): Gte; export function gte(left: Expr, right: any): Gte; /** + * @beta + * * Creates an expression that checks if a field's value is greater than or equal to an expression. * * ```typescript @@ -2478,6 +2734,8 @@ export function gte(left: Expr, right: any): Gte; export function gte(left: string, right: Expr): Gte; /** + * @beta + * * Creates an expression that checks if a field's value is greater than or equal to a constant * value. * @@ -2498,6 +2756,8 @@ export function gte(left: Expr | string, right: any): Gte { } /** + * @beta + * * Creates an expression that concatenates an array expression with other arrays. * * ```typescript @@ -2512,6 +2772,8 @@ export function gte(left: Expr | string, right: any): Gte { export function arrayConcat(array: Expr, elements: Expr[]): ArrayConcat; /** + * @beta + * * Creates an expression that concatenates an array expression with other arrays and/or values. * * ```typescript @@ -2526,6 +2788,8 @@ export function arrayConcat(array: Expr, elements: Expr[]): ArrayConcat; export function arrayConcat(array: Expr, elements: any[]): ArrayConcat; /** + * @beta + * * Creates an expression that concatenates a field's array value with other arrays. * * ```typescript @@ -2540,6 +2804,8 @@ export function arrayConcat(array: Expr, elements: any[]): ArrayConcat; export function arrayConcat(array: string, elements: Expr[]): ArrayConcat; /** + * @beta + * * Creates an expression that concatenates a field's array value with other arrays and/or values. * * ```typescript @@ -2564,6 +2830,8 @@ export function arrayConcat( } /** + * @beta + * * Creates an expression that checks if an array expression contains a specific element. * * ```typescript @@ -2578,6 +2846,8 @@ export function arrayConcat( export function arrayContains(array: Expr, element: Expr): ArrayContains; /** + * @beta + * * Creates an expression that checks if an array expression contains a specific element. * * ```typescript @@ -2592,6 +2862,8 @@ export function arrayContains(array: Expr, element: Expr): ArrayContains; export function arrayContains(array: Expr, element: any): ArrayContains; /** + * @beta + * * Creates an expression that checks if a field's array value contains a specific element. * * ```typescript @@ -2606,6 +2878,8 @@ export function arrayContains(array: Expr, element: any): ArrayContains; export function arrayContains(array: string, element: Expr): ArrayContains; /** + * @beta + * * Creates an expression that checks if a field's array value contains a specific value. * * ```typescript @@ -2628,6 +2902,8 @@ export function arrayContains( } /** + * @beta + * * Creates an expression that checks if an array expression contains any of the specified * elements. * @@ -2643,6 +2919,8 @@ export function arrayContains( export function arrayContainsAny(array: Expr, values: Expr[]): ArrayContainsAny; /** + * @beta + * * Creates an expression that checks if an array expression contains any of the specified * elements. * @@ -2658,6 +2936,8 @@ export function arrayContainsAny(array: Expr, values: Expr[]): ArrayContainsAny; export function arrayContainsAny(array: Expr, values: any[]): ArrayContainsAny; /** + * @beta + * * Creates an expression that checks if a field's array value contains any of the specified * elements. * @@ -2677,6 +2957,8 @@ export function arrayContainsAny( ): ArrayContainsAny; /** + * @beta + * * Creates an expression that checks if a field's array value contains any of the specified * elements. * @@ -2706,6 +2988,8 @@ export function arrayContainsAny( } /** + * @beta + * * Creates an expression that checks if an array expression contains all the specified elements. * * ```typescript @@ -2720,6 +3004,8 @@ export function arrayContainsAny( export function arrayContainsAll(array: Expr, values: Expr[]): ArrayContainsAll; /** + * @beta + * * Creates an expression that checks if an array expression contains all the specified elements. * * ```typescript @@ -2734,6 +3020,8 @@ export function arrayContainsAll(array: Expr, values: Expr[]): ArrayContainsAll; export function arrayContainsAll(array: Expr, values: any[]): ArrayContainsAll; /** + * @beta + * * Creates an expression that checks if a field's array value contains all the specified values or * expressions. * @@ -2752,6 +3040,8 @@ export function arrayContainsAll( ): ArrayContainsAll; /** + * @beta + * * Creates an expression that checks if a field's array value contains all the specified values or * expressions. * @@ -2780,6 +3070,8 @@ export function arrayContainsAll( } /** + * @beta + * * Creates an expression that filters elements from an array expression using the given {@link * FilterExpr} and returns the filtered elements as a new array. * @@ -2799,6 +3091,8 @@ export function arrayFilter(array: Expr, filter: FilterExpr): ArrayFilter { } /** + * @beta + * * Creates an expression that calculates the length of an array expression. * * ```typescript @@ -2814,6 +3108,8 @@ export function arrayLength(array: Expr): ArrayLength { } /** + * @beta + * * Creates an expression that applies a transformation function to each element in an array * expression and returns the new array as the result of the evaluation. * @@ -2836,6 +3132,8 @@ export function arrayTransform( } /** + * @beta + * * Returns an expression that represents an array element within an {@link ArrayFilter} or {@link * ArrayTransform} expression. * @@ -2851,6 +3149,8 @@ export function arrayElement(): ArrayElement { } /** + * @beta + * * Creates an expression that checks if an expression is equal to any of the provided values or * expressions. * @@ -2866,6 +3166,8 @@ export function arrayElement(): ArrayElement { export function inAny(element: Expr, others: Expr[]): In; /** + * @beta + * * Creates an expression that checks if an expression is equal to any of the provided values or * expressions. * @@ -2881,6 +3183,8 @@ export function inAny(element: Expr, others: Expr[]): In; export function inAny(element: Expr, others: any[]): In; /** + * @beta + * * Creates an expression that checks if a field's value is equal to any of the provided values or * expressions. * @@ -2896,6 +3200,8 @@ export function inAny(element: Expr, others: any[]): In; export function inAny(element: string, others: Expr[]): In; /** + * @beta + * * Creates an expression that checks if a field's value is equal to any of the provided values or * expressions. * @@ -2918,6 +3224,8 @@ export function inAny(element: Expr | string, others: any[]): In { } /** + * @beta + * * Creates an expression that checks if an expression is not equal to any of the provided values * or expressions. * @@ -2933,6 +3241,8 @@ export function inAny(element: Expr | string, others: any[]): In { export function notInAny(element: Expr, others: Expr[]): Not; /** + * @beta + * * Creates an expression that checks if an expression is not equal to any of the provided values * or expressions. * @@ -2948,6 +3258,8 @@ export function notInAny(element: Expr, others: Expr[]): Not; export function notInAny(element: Expr, others: any[]): Not; /** + * @beta + * * Creates an expression that checks if a field's value is not equal to any of the provided values * or expressions. * @@ -2963,6 +3275,8 @@ export function notInAny(element: Expr, others: any[]): Not; export function notInAny(element: string, others: Expr[]): Not; /** + * @beta + * * Creates an expression that checks if a field's value is not equal to any of the provided values * or expressions. * @@ -2985,6 +3299,8 @@ export function notInAny(element: Expr | string, others: any[]): Not { } /** + * @beta + * * Creates an expression that performs a logical 'AND' operation on multiple filter conditions. * * ```typescript @@ -3002,6 +3318,8 @@ export function and(left: FilterExpr, ...right: FilterExpr[]): And { } /** + * @beta + * * Creates an expression that performs a logical 'OR' operation on multiple filter conditions. * * ```typescript @@ -3019,6 +3337,8 @@ export function or(left: FilterExpr, ...right: FilterExpr[]): Or { } /** + * @beta + * * Creates an expression that performs a logical 'XOR' (exclusive OR) operation on multiple filter * conditions. * @@ -3040,6 +3360,8 @@ export function xor(left: FilterExpr, ...right: FilterExpr[]): Xor { } /** + * @beta + * * Creates a conditional expression that evaluates to a 'then' expression if a condition is true * and an 'else' expression if the condition is false. * @@ -3063,6 +3385,8 @@ export function ifFunction( } /** + * @beta + * * Creates an expression that negates a filter condition. * * ```typescript @@ -3078,6 +3402,8 @@ export function not(filter: FilterExpr): Not { } /** + * @beta + * * Creates an expression that checks if a field exists. * * ```typescript @@ -3091,6 +3417,8 @@ export function not(filter: FilterExpr): Not { export function exists(value: Expr): Exists; /** + * @beta + * * Creates an expression that checks if a field exists. * * ```typescript @@ -3109,6 +3437,8 @@ export function exists(valueOrField: Expr | string): Exists { } /** + * @beta + * * Creates an expression that checks if an expression evaluates to 'NaN' (Not a Number). * * ```typescript @@ -3122,6 +3452,8 @@ export function exists(valueOrField: Expr | string): Exists { export function isNan(value: Expr): IsNan; /** + * @beta + * * Creates an expression that checks if a field's value evaluates to 'NaN' (Not a Number). * * ```typescript @@ -3139,6 +3471,8 @@ export function isNan(value: Expr | string): IsNan { } /** + * @beta + * * Creates an expression that calculates the length of a string field. * * ```typescript @@ -3152,6 +3486,8 @@ export function isNan(value: Expr | string): IsNan { export function length(field: string): Length; /** + * @beta + * * Creates an expression that calculates the length of a string expression. * * ```typescript @@ -3169,6 +3505,8 @@ export function length(value: Expr | string): Length { } /** + * @beta + * * Creates an expression that performs a case-sensitive wildcard string comparison against a * field. * @@ -3184,6 +3522,8 @@ export function length(value: Expr | string): Length { export function like(left: string, pattern: string): Like; /** + * @beta + * * Creates an expression that performs a case-sensitive wildcard string comparison against a * field. * @@ -3199,6 +3539,8 @@ export function like(left: string, pattern: string): Like; export function like(left: string, pattern: Expr): Like; /** + * @beta + * * Creates an expression that performs a case-sensitive wildcard string comparison. * * ```typescript @@ -3213,6 +3555,8 @@ export function like(left: string, pattern: Expr): Like; export function like(left: Expr, pattern: string): Like; /** + * @beta + * * Creates an expression that performs a case-sensitive wildcard string comparison. * * ```typescript @@ -3232,6 +3576,8 @@ export function like(left: Expr | string, pattern: Expr | string): Like { } /** + * @beta + * * Creates an expression that checks if a string field contains a specified regular expression as * a substring. * @@ -3247,6 +3593,8 @@ export function like(left: Expr | string, pattern: Expr | string): Like { export function regexContains(left: string, pattern: string): RegexContains; /** + * @beta + * * Creates an expression that checks if a string field contains a specified regular expression as * a substring. * @@ -3262,6 +3610,8 @@ export function regexContains(left: string, pattern: string): RegexContains; export function regexContains(left: string, pattern: Expr): RegexContains; /** + * @beta + * * Creates an expression that checks if a string expression contains a specified regular * expression as a substring. * @@ -3277,6 +3627,8 @@ export function regexContains(left: string, pattern: Expr): RegexContains; export function regexContains(left: Expr, pattern: string): RegexContains; /** + * @beta + * * Creates an expression that checks if a string expression contains a specified regular * expression as a substring. * @@ -3300,6 +3652,8 @@ export function regexContains( } /** + * @beta + * * Creates an expression that checks if a string field matches a specified regular expression. * * ```typescript @@ -3314,6 +3668,8 @@ export function regexContains( export function regexMatch(left: string, pattern: string): RegexMatch; /** + * @beta + * * Creates an expression that checks if a string field matches a specified regular expression. * * ```typescript @@ -3328,6 +3684,8 @@ export function regexMatch(left: string, pattern: string): RegexMatch; export function regexMatch(left: string, pattern: Expr): RegexMatch; /** + * @beta + * * Creates an expression that checks if a string expression matches a specified regular * expression. * @@ -3343,6 +3701,8 @@ export function regexMatch(left: string, pattern: Expr): RegexMatch; export function regexMatch(left: Expr, pattern: string): RegexMatch; /** + * @beta + * * Creates an expression that checks if a string expression matches a specified regular * expression. * @@ -3366,6 +3726,8 @@ export function regexMatch( } /** + * @beta + * * Creates an expression that checks if a field's value starts with a given prefix. * * ```typescript @@ -3380,6 +3742,8 @@ export function regexMatch( export function startsWith(expr: string, prefix: string): StartsWith; /** + * @beta + * * Creates an expression that checks if a field's value starts with a given prefix. * * ```typescript @@ -3394,6 +3758,8 @@ export function startsWith(expr: string, prefix: string): StartsWith; export function startsWith(expr: string, prefix: Expr): StartsWith; /** + * @beta + * * Creates an expression that checks if a string expression starts with a given prefix. * * ```typescript @@ -3408,6 +3774,8 @@ export function startsWith(expr: string, prefix: Expr): StartsWith; export function startsWith(expr: Expr, prefix: string): StartsWith; /** + * @beta + * * Creates an expression that checks if a string expression starts with a given prefix. * * ```typescript @@ -3430,6 +3798,8 @@ export function startsWith( } /** + * @beta + * * Creates an expression that checks if a field's value ends with a given postfix. * * ```typescript @@ -3444,6 +3814,8 @@ export function startsWith( export function endsWith(expr: string, suffix: string): EndsWith; /** + * @beta + * * Creates an expression that checks if a field's value ends with a given postfix. * * ```typescript @@ -3458,6 +3830,8 @@ export function endsWith(expr: string, suffix: string): EndsWith; export function endsWith(expr: string, suffix: Expr): EndsWith; /** + * @beta + * * Creates an expression that checks if a string expression ends with a given postfix. * * ```typescript @@ -3472,6 +3846,8 @@ export function endsWith(expr: string, suffix: Expr): EndsWith; export function endsWith(expr: Expr, suffix: string): EndsWith; /** + * @beta + * * Creates an expression that checks if a string expression ends with a given postfix. * * ```typescript @@ -3491,6 +3867,8 @@ export function endsWith(expr: Expr | string, suffix: Expr | string): EndsWith { } /** + * @beta + * * Creates an expression that converts a string field to lowercase. * * ```typescript @@ -3504,6 +3882,8 @@ export function endsWith(expr: Expr | string, suffix: Expr | string): EndsWith { export function toLowercase(expr: string): ToLowercase; /** + * @beta + * * Creates an expression that converts a string expression to lowercase. * * ```typescript @@ -3520,6 +3900,8 @@ export function toLowercase(expr: Expr | string): ToLowercase { } /** + * @beta + * * Creates an expression that converts a string field to uppercase. * * ```typescript @@ -3533,6 +3915,8 @@ export function toLowercase(expr: Expr | string): ToLowercase { export function toUppercase(expr: string): ToUppercase; /** + * @beta + * * Creates an expression that converts a string expression to uppercase. * * ```typescript @@ -3549,6 +3933,8 @@ export function toUppercase(expr: Expr | string): ToUppercase { } /** + * @beta + * * Creates an expression that removes leading and trailing whitespace from a string field. * * ```typescript @@ -3562,6 +3948,8 @@ export function toUppercase(expr: Expr | string): ToUppercase { export function trim(expr: string): Trim; /** + * @beta + * * Creates an expression that removes leading and trailing whitespace from a string expression. * * ```typescript @@ -3578,6 +3966,8 @@ export function trim(expr: Expr | string): Trim { } /** + * @beta + * * Creates an expression that concatenates string functions, fields or constants together. * * ```typescript @@ -3595,6 +3985,7 @@ export function strConcat( ): StrConcat; /** + * @beta * Creates an expression that concatenates string expressions together. * * ```typescript @@ -3619,6 +4010,8 @@ export function strConcat( } /** + * @beta + * * Accesses a value from a map (object) field using the provided key. * * ```typescript @@ -3633,6 +4026,8 @@ export function strConcat( export function mapGet(mapField: string, subField: string): MapGet; /** + * @beta + * * Accesses a value from a map (object) expression using the provided key. * * ```typescript @@ -3653,6 +4048,8 @@ export function mapGet(fieldOrExpr: string | Expr, subField: string): MapGet { } /** + * @beta + * * Creates an aggregation that counts the total number of stage inputs. * * ```typescript @@ -3667,6 +4064,8 @@ export function countAll(): Count { } /** + * @beta + * * Creates an aggregation that counts the number of stage inputs with valid evaluations of the * provided expression. * @@ -3699,6 +4098,8 @@ export function count(value: Expr | string): Count { } /** + * @beta + * * Creates an aggregation that calculates the sum of values from an expression across multiple * stage inputs. * @@ -3713,6 +4114,8 @@ export function count(value: Expr | string): Count { export function sum(value: Expr): Sum; /** + * @beta + * * Creates an aggregation that calculates the sum of a field's values across multiple stage * inputs. * @@ -3731,6 +4134,8 @@ export function sum(value: Expr | string): Sum { } /** + * @beta + * * Creates an aggregation that calculates the average (mean) of values from an expression across * multiple stage inputs. * @@ -3745,6 +4150,8 @@ export function sum(value: Expr | string): Sum { export function avg(value: Expr): Avg; /** + * @beta + * * Creates an aggregation that calculates the average (mean) of a field's values across multiple * stage inputs. * @@ -3763,6 +4170,8 @@ export function avg(value: Expr | string): Avg { } /** + * @beta + * * Creates an aggregation that finds the minimum value of an expression across multiple stage * inputs. * @@ -3777,6 +4186,8 @@ export function avg(value: Expr | string): Avg { export function min(value: Expr): Min; /** + * @beta + * * Creates an aggregation that finds the minimum value of a field across multiple stage inputs. * * ```typescript @@ -3794,6 +4205,8 @@ export function min(value: Expr | string): Min { } /** + * @beta + * * Creates an aggregation that finds the maximum value of an expression across multiple stage * inputs. * @@ -3808,6 +4221,8 @@ export function min(value: Expr | string): Min { export function max(value: Expr): Max; /** + * @beta + * * Creates an aggregation that finds the maximum value of a field across multiple stage inputs. * * ```typescript @@ -3825,6 +4240,8 @@ export function max(value: Expr | string): Max { } /** + * @beta + * * Calculates the Cosine distance between a field's vector value and a double array. * * ```typescript @@ -3839,6 +4256,8 @@ export function max(value: Expr | string): Max { export function cosineDistance(expr: string, other: number[]): CosineDistance; /** + * @beta + * * Calculates the Cosine distance between a field's vector value and a VectorValue. * * ```typescript @@ -3856,6 +4275,8 @@ export function cosineDistance( ): CosineDistance; /** + * @beta + * * Calculates the Cosine distance between a field's vector value and a vector expression. * * ```typescript @@ -3870,6 +4291,8 @@ export function cosineDistance( export function cosineDistance(expr: string, other: Expr): CosineDistance; /** + * @beta + * * Calculates the Cosine distance between a vector expression and a double array. * * ```typescript @@ -3884,6 +4307,8 @@ export function cosineDistance(expr: string, other: Expr): CosineDistance; export function cosineDistance(expr: Expr, other: number[]): CosineDistance; /** + * @beta + * * Calculates the Cosine distance between a vector expression and a VectorValue. * * ```typescript @@ -3898,6 +4323,8 @@ export function cosineDistance(expr: Expr, other: number[]): CosineDistance; export function cosineDistance(expr: Expr, other: VectorValue): CosineDistance; /** + * @beta + * * Calculates the Cosine distance between two vector expressions. * * ```typescript @@ -3920,6 +4347,8 @@ export function cosineDistance( } /** + * @beta + * * Calculates the dot product distance between a field's vector value and a double array. * * ```typescript @@ -3937,6 +4366,8 @@ export function dotProductDistance( ): DotProductDistance; /** + * @beta + * * Calculates the dot product distance between a field's vector value and a VectorValue. * * ```typescript @@ -3954,6 +4385,8 @@ export function dotProductDistance( ): DotProductDistance; /** + * @beta + * * Calculates the dot product distance between a field's vector value and a vector expression. * * ```typescript @@ -3971,6 +4404,8 @@ export function dotProductDistance( ): DotProductDistance; /** + * @beta + * * Calculates the dot product distance between a vector expression and a double array. * * ```typescript @@ -3988,6 +4423,8 @@ export function dotProductDistance( ): DotProductDistance; /** + * @beta + * * Calculates the dot product distance between a vector expression and a VectorValue. * * ```typescript @@ -4005,6 +4442,8 @@ export function dotProductDistance( ): DotProductDistance; /** + * @beta + * * Calculates the dot product distance between two vector expressions. * * ```typescript @@ -4027,6 +4466,8 @@ export function dotProductDistance( } /** + * @beta + * * Calculates the Euclidean distance between a field's vector value and a double array. * * ```typescript @@ -4044,6 +4485,8 @@ export function euclideanDistance( ): EuclideanDistance; /** + * @beta + * * Calculates the Euclidean distance between a field's vector value and a VectorValue. * * ```typescript @@ -4061,6 +4504,8 @@ export function euclideanDistance( ): EuclideanDistance; /** + * @beta + * * Calculates the Euclidean distance between a field's vector value and a vector expression. * * ```typescript @@ -4075,6 +4520,8 @@ export function euclideanDistance( export function euclideanDistance(expr: string, other: Expr): EuclideanDistance; /** + * @beta + * * Calculates the Euclidean distance between a vector expression and a double array. * * ```typescript @@ -4093,6 +4540,8 @@ export function euclideanDistance( ): EuclideanDistance; /** + * @beta + * * Calculates the Euclidean distance between a vector expression and a VectorValue. * * ```typescript @@ -4110,6 +4559,8 @@ export function euclideanDistance( ): EuclideanDistance; /** + * @beta + * * Calculates the Euclidean distance between two vector expressions. * * ```typescript @@ -4132,6 +4583,8 @@ export function euclideanDistance( } /** + * @beta + * * Creates functions that work on the backend but do not exist in the SDK yet. * * ```typescript @@ -4149,6 +4602,8 @@ export function genericFunction(name: string, params: Expr[]): Function { } /** + * @beta + * * Creates an {@link Ordering} that sorts documents in ascending order based on this expression. * * ```typescript @@ -4165,6 +4620,8 @@ export function ascending(expr: Expr): Ordering { } /** + * @beta + * * Creates an {@link Ordering} that sorts documents in descending order based on this expression. * * ```typescript @@ -4181,6 +4638,8 @@ export function descending(expr: Expr): Ordering { } /** + * @beta + * * Represents an ordering criterion for sorting documents in a Firestore pipeline. * * You create `Ordering` instances using the `ascending` and `descending` helper functions. diff --git a/dev/src/pipeline-util.ts b/dev/src/pipeline-util.ts index ce6677b9a..866d90cc9 100644 --- a/dev/src/pipeline-util.ts +++ b/dev/src/pipeline-util.ts @@ -1,3 +1,17 @@ +// 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. + import * as firestore from '@google-cloud/firestore'; import {GoogleError, serializer} from 'google-gax'; import {converter} from 'protobufjs'; diff --git a/dev/src/pipeline.ts b/dev/src/pipeline.ts index 7b0e7a285..5abdfed54 100644 --- a/dev/src/pipeline.ts +++ b/dev/src/pipeline.ts @@ -1,3 +1,17 @@ +// 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. + import {DocumentData} from '@google-cloud/firestore'; import * as firestore from '@google-cloud/firestore'; import * as deepEqual from 'fast-deep-equal'; @@ -45,6 +59,10 @@ import IStage = google.firestore.v1.Pipeline.IStage; import {QueryCursor} from './reference/types'; import {isOptionalEqual} from './util'; +/** + * Represents the source of a Firestore {@link Pipeline}. + * @beta + */ export class PipelineSource { constructor(private db: Firestore) {} @@ -66,6 +84,8 @@ export class PipelineSource { } /** + * @beta + * * The Pipeline class provides a flexible and expressive framework for building complex data * transformation and query pipelines for Firestore. * @@ -669,6 +689,8 @@ export class Pipeline { } /** + * @beta + * * A PipelineResult contains data read from a Firestore Pipeline. The data can be extracted with the * {@link #data()} or {@link #get(String)} methods. * diff --git a/dev/src/stage.ts b/dev/src/stage.ts index de656fc03..2dc941164 100644 --- a/dev/src/stage.ts +++ b/dev/src/stage.ts @@ -1,3 +1,17 @@ +// 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. + import * as protos from '../protos/firestore_v1_proto_api'; import api = protos.google.firestore.v1; diff --git a/dev/system-test/pipeline.ts b/dev/system-test/pipeline.ts index 09c98f1a3..0eca6211b 100644 --- a/dev/system-test/pipeline.ts +++ b/dev/system-test/pipeline.ts @@ -1,3 +1,17 @@ +// 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. + import { AggregateQuery, DocumentData, @@ -48,6 +62,7 @@ import { euclideanDistance, Constant, mapGet, + lte, } from '../src/expression'; import {PipelineResult} from '../src/pipeline'; import {verifyInstance} from '../test/util/helpers'; @@ -313,8 +328,9 @@ describe.only('Pipeline class', () => { }); it('can select fields', async () => { - const results = await randomCol + const results = await firestore .pipeline() + .collection(randomCol.path) .select('title', 'author') .sort(Field.of('author').ascending()) .execute(); @@ -359,8 +375,9 @@ describe.only('Pipeline class', () => { }); it('offset and limits', async () => { - const results = await randomCol + const results = await firestore .pipeline() + .collection(randomCol.path) .sort(Field.of('author').ascending()) .offset(5) .limit(3) @@ -607,7 +624,7 @@ describe.only('Pipeline class', () => { .where( and( gt('rating', 4.2), - lt(Field.of('rating'), 4.5), + lte(Field.of('rating'), 4.5), neq('genre', 'Science Fiction') ) ) diff --git a/dev/system-test/query.ts b/dev/system-test/query.ts index cc0b877d2..84853f79b 100644 --- a/dev/system-test/query.ts +++ b/dev/system-test/query.ts @@ -1,3 +1,17 @@ +// 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. + import { DocumentData, QuerySnapshot, From a3e62b5bd0bad7fdf2cb62bc55e7749b374cf755 Mon Sep 17 00:00:00 2001 From: Wu-Hui Date: Tue, 3 Sep 2024 10:07:33 -0400 Subject: [PATCH 11/60] Addressing comments. --- dev/src/expression.ts | 146 ++++++++++++++++++------------------ dev/src/pipeline.ts | 4 +- dev/src/stage.ts | 48 ++++++++++++ dev/system-test/pipeline.ts | 6 +- types/firestore.d.ts | 2 + 5 files changed, 128 insertions(+), 78 deletions(-) diff --git a/dev/src/expression.ts b/dev/src/expression.ts index edb7f8827..deec76988 100644 --- a/dev/src/expression.ts +++ b/dev/src/expression.ts @@ -435,10 +435,10 @@ export abstract class Expr { * Field.of("items").arrayConcat(Field.of("otherItems")); * ``` * - * @param values The array expressions to concatenate. + * @param arrays The array expressions to concatenate. * @return A new `Expr` representing the concatenated array. */ - arrayConcat(...values: Expr[]): ArrayConcat; + arrayConcat(arrays: Expr[]): ArrayConcat; /** * Creates an expression that concatenates an array expression with one or more other arrays. @@ -448,12 +448,12 @@ export abstract class Expr { * Field.of("tags").arrayConcat(Arrays.asList("newTag1", "newTag2"), Field.of("otherTag")); * ``` * - * @param values The array expressions or values to concatenate. + * @param arrays The array expressions or values to concatenate. * @return A new `Expr` representing the concatenated array. */ - arrayConcat(...values: any[]): ArrayConcat; - arrayConcat(...values: any[]): ArrayConcat { - const exprValues = values.map(value => + arrayConcat(arrays: any[]): ArrayConcat; + arrayConcat(arrays: any[]): ArrayConcat { + const exprValues = arrays.map(value => value instanceof Expr ? value : Constant.of(value) ); return new ArrayConcat(this, exprValues); @@ -1034,48 +1034,48 @@ export abstract class Expr { } /** - * Calculates the dot product distance between two vectors. + * Calculates the dot product between two vectors. * * ```typescript - * // Calculate the dot product distance between a feature vector and a target vector - * Field.of("features").dotProductDistance([0.5, 0.8, 0.2]); + * // Calculate the dot product between a feature vector and a target vector + * Field.of("features").dotProduct([0.5, 0.8, 0.2]); * ``` * - * @param other The other vector (as an array of numbers) to compare against. - * @return A new `Expr` representing the dot product distance between the two vectors. + * @param other The other vector (as an array of numbers) to calculate with. + * @return A new `Expr` representing the dot product between the two vectors. */ - dotProductDistance(other: Expr): DotProductDistance; + dotProduct(other: Expr): DotProduct; /** - * Calculates the dot product distance between two vectors. + * Calculates the dot product between two vectors. * * ```typescript - * // Calculate the dot product distance between a feature vector and a target vector - * Field.of("features").dotProductDistance(new VectorValue([0.5, 0.8, 0.2])); + * // Calculate the dot product between a feature vector and a target vector + * Field.of("features").dotProduct(new VectorValue([0.5, 0.8, 0.2])); * ``` * - * @param other The other vector (as a VectorValue) to compare against. - * @return A new `Expr` representing the dot product distance between the two vectors. + * @param other The other vector (as an array of numbers) to calculate with. + * @return A new `Expr` representing the dot product between the two vectors. */ - dotProductDistance(other: VectorValue): DotProductDistance; + dotProduct(other: VectorValue): DotProduct; /** - * Calculates the dot product distance between two vectors. + * Calculates the dot product between two vectors. * * ```typescript - * // Calculate the dot product distance between a feature vector and a target vector - * Field.of("features").dotProductDistance([0.5, 0.8, 0.2]); + * // Calculate the dot product between a feature vector and a target vector + * Field.of("features").dotProduct([0.5, 0.8, 0.2]); * ``` * - * @param other The other vector (as an array of numbers) to compare against. - * @return A new `Expr` representing the dot product distance between the two vectors. + * @param other The other vector (as an array of numbers) to calculate with. + * @return A new `Expr` representing the dot product between the two vectors. */ - dotProductDistance(other: number[]): DotProductDistance; - dotProductDistance(other: Expr | VectorValue | number[]): DotProductDistance { + dotProduct(other: number[]): DotProduct; + dotProduct(other: Expr | VectorValue | number[]): DotProduct { if (other instanceof Expr) { - return new DotProductDistance(this, other); + return new DotProduct(this, other); } else { - return new DotProductDistance(this, Constant.vector(other)); + return new DotProduct(this, Constant.vector(other)); } } @@ -1087,7 +1087,7 @@ export abstract class Expr { * Field.of("location").euclideanDistance([37.7749, -122.4194]); * ``` * - * @param other The other vector (as an array of numbers) to compare against. + * @param other The other vector (as an array of numbers) to calculate with. * @return A new `Expr` representing the Euclidean distance between the two vectors. */ euclideanDistance(other: Expr): EuclideanDistance; @@ -2041,7 +2041,7 @@ class CosineDistance extends Function { /** * @beta */ -class DotProductDistance extends Function { +class DotProduct extends Function { constructor( private vector1: Expr, private vector2: Expr @@ -4349,120 +4349,120 @@ export function cosineDistance( /** * @beta * - * Calculates the dot product distance between a field's vector value and a double array. + * Calculates the dot product between a field's vector value and a double array. * * ```typescript * // Calculate the dot product distance between a feature vector and a target vector - * dotProductDistance("features", [0.5, 0.8, 0.2]); + * dotProduct("features", [0.5, 0.8, 0.2]); * ``` * * @param expr The name of the field containing the first vector. - * @param other The other vector (as an array of doubles) to compare against. - * @return A new {@code Expr} representing the dot product distance between the two vectors. + * @param other The other vector (as an array of doubles) to calculate with. + * @return A new {@code Expr} representing the dot product between the two vectors. */ -export function dotProductDistance( +export function dotProduct( expr: string, other: number[] -): DotProductDistance; +): DotProduct; /** * @beta * - * Calculates the dot product distance between a field's vector value and a VectorValue. + * Calculates the dot product between a field's vector value and a VectorValue. * * ```typescript * // Calculate the dot product distance between a feature vector and a target vector - * dotProductDistance("features", new VectorValue([0.5, 0.8, 0.2])); + * dotProduct("features", new VectorValue([0.5, 0.8, 0.2])); * ``` * * @param expr The name of the field containing the first vector. - * @param other The other vector (as a VectorValue) to compare against. - * @return A new {@code Expr} representing the dot product distance between the two vectors. + * @param other The other vector (as a VectorValue) to calculate with. + * @return A new {@code Expr} representing the dot product between the two vectors. */ -export function dotProductDistance( +export function dotProduct( expr: string, other: VectorValue -): DotProductDistance; +): DotProduct; /** * @beta * - * Calculates the dot product distance between a field's vector value and a vector expression. + * Calculates the dot product between a field's vector value and a vector expression. * * ```typescript * // Calculate the dot product distance between two document vectors: 'docVector1' and 'docVector2' - * dotProductDistance("docVector1", Field.of("docVector2")); + * dotProduct("docVector1", Field.of("docVector2")); * ``` * * @param expr The name of the field containing the first vector. - * @param other The other vector (represented as an Expr) to compare against. - * @return A new {@code Expr} representing the dot product distance between the two vectors. + * @param other The other vector (represented as an Expr) to calculate with. + * @return A new {@code Expr} representing the dot product between the two vectors. */ -export function dotProductDistance( +export function dotProduct( expr: string, other: Expr -): DotProductDistance; +): DotProduct; /** * @beta * - * Calculates the dot product distance between a vector expression and a double array. + * Calculates the dot product between a vector expression and a double array. * * ```typescript - * // Calculate the dot product distance between a feature vector and a target vector - * dotProductDistance(Field.of("features"), [0.5, 0.8, 0.2]); + * // Calculate the dot product between a feature vector and a target vector + * dotProduct(Field.of("features"), [0.5, 0.8, 0.2]); * ``` * - * @param expr The first vector (represented as an Expr) to compare against. - * @param other The other vector (as an array of doubles) to compare against. - * @return A new {@code Expr} representing the dot product distance between the two vectors. + * @param expr The first vector (represented as an Expr) to calculate with. + * @param other The other vector (as an array of doubles) to calculate with. + * @return A new {@code Expr} representing the dot product between the two vectors. */ -export function dotProductDistance( +export function dotProduct( expr: Expr, other: number[] -): DotProductDistance; +): DotProduct; /** * @beta * - * Calculates the dot product distance between a vector expression and a VectorValue. + * Calculates the dot product between a vector expression and a VectorValue. * * ```typescript - * // Calculate the dot product distance between a feature vector and a target vector - * dotProductDistance(Field.of("features"), new VectorValue([0.5, 0.8, 0.2])); + * // Calculate the dot product between a feature vector and a target vector + * dotProduct(Field.of("features"), new VectorValue([0.5, 0.8, 0.2])); * ``` * - * @param expr The first vector (represented as an Expr) to compare against. - * @param other The other vector (as a VectorValue) to compare against. - * @return A new {@code Expr} representing the dot product distance between the two vectors. + * @param expr The first vector (represented as an Expr) to calculate with. + * @param other The other vector (as a VectorValue) to calculate with. + * @return A new {@code Expr} representing the dot product between the two vectors. */ -export function dotProductDistance( +export function dotProduct( expr: Expr, other: VectorValue -): DotProductDistance; +): DotProduct; /** * @beta * - * Calculates the dot product distance between two vector expressions. + * Calculates the dot product between two vector expressions. * * ```typescript - * // Calculate the dot product distance between two document vectors: 'docVector1' and 'docVector2' - * dotProductDistance(Field.of("docVector1"), Field.of("docVector2")); + * // Calculate the dot product between two document vectors: 'docVector1' and 'docVector2' + * dotProduct(Field.of("docVector1"), Field.of("docVector2")); * ``` * - * @param expr The first vector (represented as an Expr) to compare against. - * @param other The other vector (represented as an Expr) to compare against. - * @return A new {@code Expr} representing the dot product distance between the two vectors. + * @param expr The first vector (represented as an Expr) to calculate with. + * @param other The other vector (represented as an Expr) to calculate with. + * @return A new {@code Expr} representing the dot product between the two vectors. */ -export function dotProductDistance(expr: Expr, other: Expr): DotProductDistance; -export function dotProductDistance( +export function dotProduct(expr: Expr, other: Expr): DotProduct; +export function dotProduct( expr: Expr | string, other: Expr | number[] | VectorValue -): DotProductDistance { +): DotProduct { const expr1 = expr instanceof Expr ? expr : Field.of(expr); const expr2 = other instanceof Expr ? other : Constant.vector(other); - return new DotProductDistance(expr1, expr2); + return new DotProduct(expr1, expr2); } /** diff --git a/dev/src/pipeline.ts b/dev/src/pipeline.ts index 5abdfed54..5ac3f1592 100644 --- a/dev/src/pipeline.ts +++ b/dev/src/pipeline.ts @@ -129,7 +129,7 @@ export class Pipeline { constructor( private db: Firestore, private stages: Stage[], - private converter: firestore.FirestorePipelineConverter = defaultConverter() + private converter: firestore.FirestorePipelineConverter = defaultPipelineConverter() ) {} /** @@ -730,7 +730,7 @@ export class PipelineResult readTime?: Timestamp, createTime?: Timestamp, updateTime?: Timestamp, - readonly converter: firestore.FirestorePipelineConverter = defaultConverter() + readonly converter: firestore.FirestorePipelineConverter = defaultPipelineConverter() ) { this._ref = ref; this._serializer = serializer; diff --git a/dev/src/stage.ts b/dev/src/stage.ts index 2dc941164..7da7170d7 100644 --- a/dev/src/stage.ts +++ b/dev/src/stage.ts @@ -26,11 +26,17 @@ import {VectorValue} from './field-value'; import {DocumentReference} from './reference/document-reference'; import {Serializer} from './serializer'; +/** + * @beta + */ export interface Stage { name: string; _toProto(serializer: Serializer): api.Pipeline.IStage; } +/** + * @beta + */ export class AddField implements Stage { name = 'add_field'; @@ -44,6 +50,9 @@ export class AddField implements Stage { } } +/** + * @beta + */ export class Aggregate implements Stage { name = 'aggregate'; @@ -63,6 +72,9 @@ export class Aggregate implements Stage { } } +/** + * @beta + */ export class Distinct implements Stage { name = 'distinct'; @@ -76,6 +88,9 @@ export class Distinct implements Stage { } } +/** + * @beta + */ export class Collection implements Stage { name = 'collection'; @@ -93,6 +108,9 @@ export class Collection implements Stage { } } +/** + * @beta + */ export class CollectionGroup implements Stage { name = 'collection_group'; @@ -106,6 +124,9 @@ export class CollectionGroup implements Stage { } } +/** + * @beta + */ export class Database implements Stage { name = 'database'; @@ -116,6 +137,9 @@ export class Database implements Stage { } } +/** + * @beta + */ export class Documents implements Stage { name = 'documents'; @@ -135,6 +159,9 @@ export class Documents implements Stage { } } +/** + * @beta + */ export class Where implements Stage { name = 'where'; @@ -148,12 +175,18 @@ export class Where implements Stage { } } +/** + * @beta + */ export interface FindNearestOptions { limit: number; distanceMeasure: 'euclidean' | 'cosine' | 'dot_product'; distanceField?: string; } +/** + * @beta + */ export class FindNearest implements Stage { name = 'find_nearest'; @@ -187,6 +220,9 @@ export class FindNearest implements Stage { } } +/** + * @beta + */ export class Limit implements Stage { name = 'limit'; @@ -200,6 +236,9 @@ export class Limit implements Stage { } } +/** + * @beta + */ export class Offset implements Stage { name = 'offset'; @@ -213,6 +252,9 @@ export class Offset implements Stage { } } +/** + * @beta + */ export class Select implements Stage { name = 'select'; @@ -226,6 +268,9 @@ export class Select implements Stage { } } +/** + * @beta + */ export class Sort implements Stage { name = 'sort'; @@ -239,6 +284,9 @@ export class Sort implements Stage { } } +/** + * @beta + */ export class GenericStage implements Stage { constructor( public name: string, diff --git a/dev/system-test/pipeline.ts b/dev/system-test/pipeline.ts index 0eca6211b..4af42e931 100644 --- a/dev/system-test/pipeline.ts +++ b/dev/system-test/pipeline.ts @@ -58,7 +58,7 @@ import { strConcat, subtract, cosineDistance, - dotProductDistance, + dotProduct, euclideanDistance, Constant, mapGet, @@ -435,7 +435,7 @@ describe.only('Pipeline class', () => { const results = await randomCol .pipeline() .select( - Field.of('tags').arrayConcat('newTag1', 'newTag2').as('modifiedTags') + Field.of('tags').arrayConcat(['newTag1', 'newTag2']).as('modifiedTags') ) .limit(1) .execute(); @@ -727,7 +727,7 @@ describe.only('Pipeline class', () => { cosineDistance(Constant.vector(sourceVector), targetVector).as( 'cosineDistance' ), - dotProductDistance(Constant.vector(sourceVector), targetVector).as( + dotProduct(Constant.vector(sourceVector), targetVector).as( 'dotProductDistance' ), euclideanDistance(Constant.vector(sourceVector), targetVector).as( diff --git a/types/firestore.d.ts b/types/firestore.d.ts index 0c4f0a93d..828eb1c88 100644 --- a/types/firestore.d.ts +++ b/types/firestore.d.ts @@ -1677,6 +1677,8 @@ declare namespace FirebaseFirestore { */ readonly updateTime: Timestamp | undefined; + readonly executionTime: Timestamp | undefined; + /** * Retrieves all fields in the document as an Object. * From 997c6c5a3f6a98095f04b4844e8dd87490393ffc Mon Sep 17 00:00:00 2001 From: Wu-Hui Date: Tue, 3 Sep 2024 11:05:54 -0400 Subject: [PATCH 12/60] DTS + some other fixes. --- dev/src/expression.ts | 25 +- dev/src/pipeline.ts | 20 +- dev/src/stage.ts | 16 +- dev/src/types.ts | 2 +- types/firestore.d.ts | 4489 ++++++++++++++++++++++++++++++++++++++++- 5 files changed, 4488 insertions(+), 64 deletions(-) diff --git a/dev/src/expression.ts b/dev/src/expression.ts index deec76988..b9f3b57f5 100644 --- a/dev/src/expression.ts +++ b/dev/src/expression.ts @@ -4360,10 +4360,7 @@ export function cosineDistance( * @param other The other vector (as an array of doubles) to calculate with. * @return A new {@code Expr} representing the dot product between the two vectors. */ -export function dotProduct( - expr: string, - other: number[] -): DotProduct; +export function dotProduct(expr: string, other: number[]): DotProduct; /** * @beta @@ -4379,10 +4376,7 @@ export function dotProduct( * @param other The other vector (as a VectorValue) to calculate with. * @return A new {@code Expr} representing the dot product between the two vectors. */ -export function dotProduct( - expr: string, - other: VectorValue -): DotProduct; +export function dotProduct(expr: string, other: VectorValue): DotProduct; /** * @beta @@ -4398,10 +4392,7 @@ export function dotProduct( * @param other The other vector (represented as an Expr) to calculate with. * @return A new {@code Expr} representing the dot product between the two vectors. */ -export function dotProduct( - expr: string, - other: Expr -): DotProduct; +export function dotProduct(expr: string, other: Expr): DotProduct; /** * @beta @@ -4417,10 +4408,7 @@ export function dotProduct( * @param other The other vector (as an array of doubles) to calculate with. * @return A new {@code Expr} representing the dot product between the two vectors. */ -export function dotProduct( - expr: Expr, - other: number[] -): DotProduct; +export function dotProduct(expr: Expr, other: number[]): DotProduct; /** * @beta @@ -4436,10 +4424,7 @@ export function dotProduct( * @param other The other vector (as a VectorValue) to calculate with. * @return A new {@code Expr} representing the dot product between the two vectors. */ -export function dotProduct( - expr: Expr, - other: VectorValue -): DotProduct; +export function dotProduct(expr: Expr, other: VectorValue): DotProduct; /** * @beta diff --git a/dev/src/pipeline.ts b/dev/src/pipeline.ts index 5ac3f1592..c39680714 100644 --- a/dev/src/pipeline.ts +++ b/dev/src/pipeline.ts @@ -34,12 +34,12 @@ import {ExecutionUtil} from './pipeline-util'; import {DocumentReference} from './reference/document-reference'; import {Serializer} from './serializer'; import { - AddField, + AddFields, Aggregate, - Collection, - CollectionGroup, - Database, - Documents, + CollectionSource, + CollectionGroupSource, + DatabaseSource, + DocumentsSource, Where, FindNearest, FindNearestOptions, @@ -67,19 +67,19 @@ export class PipelineSource { constructor(private db: Firestore) {} collection(collectionPath: string): Pipeline { - return new Pipeline(this.db, [new Collection(collectionPath)]); + return new Pipeline(this.db, [new CollectionSource(collectionPath)]); } collectionGroup(collectionId: string): Pipeline { - return new Pipeline(this.db, [new CollectionGroup(collectionId)]); + return new Pipeline(this.db, [new CollectionGroupSource(collectionId)]); } database(): Pipeline { - return new Pipeline(this.db, [new Database()]); + return new Pipeline(this.db, [new DatabaseSource()]); } documents(docs: DocumentReference[]): Pipeline { - return new Pipeline(this.db, [Documents.of(docs)]); + return new Pipeline(this.db, [DocumentsSource.of(docs)]); } } @@ -160,7 +160,7 @@ export class Pipeline { */ addFields(...fields: Selectable[]): Pipeline { const copy = this.stages.map(s => s); - copy.push(new AddField(this.selectablesToMap(fields))); + copy.push(new AddFields(this.selectablesToMap(fields))); return new Pipeline(this.db, copy, this.converter); } diff --git a/dev/src/stage.ts b/dev/src/stage.ts index 7da7170d7..31aeb19cd 100644 --- a/dev/src/stage.ts +++ b/dev/src/stage.ts @@ -37,8 +37,8 @@ export interface Stage { /** * @beta */ -export class AddField implements Stage { - name = 'add_field'; +export class AddFields implements Stage { + name = 'add_fields'; constructor(private fields: Map) {} @@ -91,7 +91,7 @@ export class Distinct implements Stage { /** * @beta */ -export class Collection implements Stage { +export class CollectionSource implements Stage { name = 'collection'; constructor(private collectionPath: string) { @@ -111,7 +111,7 @@ export class Collection implements Stage { /** * @beta */ -export class CollectionGroup implements Stage { +export class CollectionGroupSource implements Stage { name = 'collection_group'; constructor(private collectionId: string) {} @@ -127,7 +127,7 @@ export class CollectionGroup implements Stage { /** * @beta */ -export class Database implements Stage { +export class DatabaseSource implements Stage { name = 'database'; _toProto(serializer: Serializer): api.Pipeline.IStage { @@ -140,13 +140,13 @@ export class Database implements Stage { /** * @beta */ -export class Documents implements Stage { +export class DocumentsSource implements Stage { name = 'documents'; constructor(private docPaths: string[]) {} - static of(refs: DocumentReference[]): Documents { - return new Documents(refs.map(ref => '/' + ref.path)); + static of(refs: DocumentReference[]): DocumentsSource { + return new DocumentsSource(refs.map(ref => '/' + ref.path)); } _toProto(serializer: Serializer): api.Pipeline.IStage { diff --git a/dev/src/types.ts b/dev/src/types.ts index 26e8be080..e52756272 100644 --- a/dev/src/types.ts +++ b/dev/src/types.ts @@ -167,7 +167,7 @@ const defaultPipelineConverterObj: FirestorePipelineConverter = { export function defaultPipelineConverter< AppModelType, >(): FirestorePipelineConverter { - return defaultConverterObj as FirestoreDataConverter; + return defaultPipelineConverterObj as FirestorePipelineConverter; } /** diff --git a/types/firestore.d.ts b/types/firestore.d.ts index 828eb1c88..dc35a6272 100644 --- a/types/firestore.d.ts +++ b/types/firestore.d.ts @@ -1663,31 +1663,6 @@ declare namespace FirebaseFirestore { data(): AppModelType; } - export class PipelineResult { - private constructor(); - - /** - * The time the document was created. - */ - readonly createTime: Timestamp | undefined; - - /** - * The time the document was last updated (at the time the snapshot was - * generated). - */ - readonly updateTime: Timestamp | undefined; - - readonly executionTime: Timestamp | undefined; - - /** - * Retrieves all fields in the document as an Object. - * - * @override - * @return An Object containing all fields in the document. - */ - data(): AppModelType | undefined; - } - /** * The direction of a `Query.orderBy()` clause is specified as 'desc' or 'asc' * (descending or ascending). @@ -3221,6 +3196,4470 @@ declare namespace FirebaseFirestore { */ readonly snapshot: T | null; } + + /** + * @beta + * + * An interface that represents a selectable expression. + */ + export interface Selectable { + selectable: true; + } + + /** + * @beta + * + * An interface that represents a filter condition. + */ + export interface FilterCondition { + filterable: true; + } + + /** + * @beta + * + * An interface that represents an accumulator. + */ + export interface Accumulator { + accumulator: true; + } + + /** + * @beta + * + * An accumulator target, which is an expression with an alias that also implements the Accumulator interface. + */ + export type AccumulatorTarget = ExprWithAlias; + + /** + * @beta + * + * A filter expression, which is an expression that also implements the FilterCondition interface. + */ + export type FilterExpr = Expr & FilterCondition; + + /** + * @beta + * + * A selectable expression, which is an expression that also implements the Selectable interface. + */ + export type SelectableExpr = Expr & Selectable; + + /** + * @beta + * + * An enumeration of the different types of expressions. + */ + export type ExprType = + | 'Field' + | 'Constant' + | 'Function' + | 'ListOfExprs' + | 'ExprWithAlias'; + + /** + * @beta + * + * Represents an expression that can be evaluated to a value within the execution of a {@link + * 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. + * - **Aggregations:** Calculate aggregate values (e.g., sum, average) over a set of documents. + * + * The `Expr` class provides a fluent API for building expressions. You can chain together + * method calls to create complex expressions. + */ + export abstract class Expr { + /** + * Creates an expression that adds this expression to another expression. + * + * ```typescript + * // Add the value of the 'quantity' field and the 'reserve' field. + * Field.of("quantity").add(Field.of("reserve")); + * ``` + * + * @param other The expression to add to this expression. + * @return A new `Expr` representing the addition operation. + */ + add(other: Expr): Add; + + /** + * Creates an expression that adds this expression to a constant value. + * + * ```typescript + * // Add 5 to the value of the 'age' field + * Field.of("age").add(5); + * ``` + * + * @param other The constant value to add. + * @return A new `Expr` representing the addition operation. + */ + add(other: any): Add; + + /** + * Creates an expression that subtracts another expression from this expression. + * + * ```typescript + * // Subtract the 'discount' field from the 'price' field + * Field.of("price").subtract(Field.of("discount")); + * ``` + * + * @param other The expression to subtract from this expression. + * @return A new `Expr` representing the subtraction operation. + */ + subtract(other: Expr): Subtract; + + /** + * Creates an expression that subtracts a constant value from this expression. + * + * ```typescript + * // Subtract 20 from the value of the 'total' field + * Field.of("total").subtract(20); + * ``` + * + * @param other The constant value to subtract. + * @return A new `Expr` representing the subtraction operation. + */ + subtract(other: any): Subtract; + + /** + * Creates an expression that multiplies this expression by another expression. + * + * ```typescript + * // Multiply the 'quantity' field by the 'price' field + * Field.of("quantity").multiply(Field.of("price")); + * ``` + * + * @param other The expression to multiply by. + * @return A new `Expr` representing the multiplication operation. + */ + multiply(other: Expr): Multiply; + + /** + * Creates an expression that multiplies this expression by a constant value. + * + * ```typescript + * // Multiply the 'value' field by 2 + * Field.of("value").multiply(2); + * ``` + * + * @param other The constant value to multiply by. + * @return A new `Expr` representing the multiplication operation. + */ + multiply(other: any): Multiply; + + /** + * Creates an expression that divides this expression by another expression. + * + * ```typescript + * // Divide the 'total' field by the 'count' field + * Field.of("total").divide(Field.of("count")); + * ``` + * + * @param other The expression to divide by. + * @return A new `Expr` representing the division operation. + */ + divide(other: Expr): Divide; + + /** + * Creates an expression that divides this expression by a constant value. + * + * ```typescript + * // Divide the 'value' field by 10 + * Field.of("value").divide(10); + * ``` + * + * @param other The constant value to divide by. + * @return A new `Expr` representing the division operation. + */ + divide(other: any): Divide; + + /** + * Creates an expression that checks if this expression is equal to another expression. + * + * ```typescript + * // Check if the 'age' field is equal to 21 + * Field.of("age").eq(21); + * ``` + * + * @param other The expression to compare for equality. + * @return A new `Expr` representing the equality comparison. + */ + eq(other: Expr): Eq; + + /** + * Creates an expression that checks if this expression is equal to a constant value. + * + * ```typescript + * // Check if the 'city' field is equal to "London" + * Field.of("city").eq("London"); + * ``` + * + * @param other The constant value to compare for equality. + * @return A new `Expr` representing the equality comparison. + */ + eq(other: any): Eq; + + /** + * Creates an expression that checks if this expression is not equal to another expression. + * + * ```typescript + * // Check if the 'status' field is not equal to "completed" + * Field.of("status").neq("completed"); + * ``` + * + * @param other The expression to compare for inequality. + * @return A new `Expr` representing the inequality comparison. + */ + neq(other: Expr): Neq; + + /** + * Creates an expression that checks if this expression is not equal to a constant value. + * + * ```typescript + * // Check if the 'country' field is not equal to "USA" + * Field.of("country").neq("USA"); + * ``` + * + * @param other The constant value to compare for inequality. + * @return A new `Expr` representing the inequality comparison. + */ + neq(other: any): Neq; + + /** + * Creates an expression that checks if this expression is less than another expression. + * + * ```typescript + * // Check if the 'age' field is less than 'limit' + * Field.of("age").lt(Field.of('limit')); + * ``` + * + * @param other The expression to compare for less than. + * @return A new `Expr` representing the less than comparison. + */ + lt(other: Expr): Lt; + + /** + * Creates an expression that checks if this expression is less than a constant value. + * + * ```typescript + * // Check if the 'price' field is less than 50 + * Field.of("price").lt(50); + * ``` + * + * @param other The constant value to compare for less than. + * @return A new `Expr` representing the less than comparison. + */ + lt(other: any): Lt; + + /** + * Creates an expression that checks if this expression is less than or equal to another + * expression. + * + * ```typescript + * // Check if the 'quantity' field is less than or equal to 20 + * Field.of("quantity").lte(Constant.of(20)); + * ``` + * + * @param other The expression to compare for less than or equal to. + * @return A new `Expr` representing the less than or equal to comparison. + */ + lte(other: Expr): Lte; + + /** + * Creates an expression that checks if this expression is less than or equal to a constant value. + * + * ```typescript + * // Check if the 'score' field is less than or equal to 70 + * Field.of("score").lte(70); + * ``` + * + * @param other The constant value to compare for less than or equal to. + * @return A new `Expr` representing the less than or equal to comparison. + */ + lte(other: any): Lte; + + /** + * Creates an expression that checks if this expression is greater than another expression. + * + * ```typescript + * // Check if the 'age' field is greater than the 'limit' field + * Field.of("age").gt(Field.of("limit")); + * ``` + * + * @param other The expression to compare for greater than. + * @return A new `Expr` representing the greater than comparison. + */ + gt(other: Expr): Gt; + + /** + * Creates an expression that checks if this expression is greater than a constant value. + * + * ```typescript + * // Check if the 'price' field is greater than 100 + * Field.of("price").gt(100); + * ``` + * + * @param other The constant value to compare for greater than. + * @return A new `Expr` representing the greater than comparison. + */ + gt(other: any): Gt; + + /** + * Creates an expression that checks if this expression is greater than or equal to another + * expression. + * + * ```typescript + * // Check if the 'quantity' field is greater than or equal to field 'requirement' plus 1 + * Field.of("quantity").gte(Field.of('requirement').add(1)); + * ``` + * + * @param other The expression to compare for greater than or equal to. + * @return A new `Expr` representing the greater than or equal to comparison. + */ + gte(other: Expr): Gte; + + /** + * Creates an expression that checks if this expression is greater than or equal to a constant + * value. + * + * ```typescript + * // Check if the 'score' field is greater than or equal to 80 + * Field.of("score").gte(80); + * ``` + * + * @param other The constant value to compare for greater than or equal to. + * @return A new `Expr` representing the greater than or equal to comparison. + */ + gte(other: any): Gte; + + /** + * Creates an expression that concatenates an array expression with one or more other arrays. + * + * ```typescript + * // Combine the 'items' array with another array field. + * Field.of("items").arrayConcat(Field.of("otherItems")); + * ``` + * + * @param arrays The array expressions to concatenate. + * @return A new `Expr` representing the concatenated array. + */ + arrayConcat(arrays: Expr[]): ArrayConcat; + + /** + * Creates an expression that concatenates an array expression with one or more other arrays. + * + * ```typescript + * // Combine the 'tags' array with a new array and an array field + * Field.of("tags").arrayConcat(Arrays.asList("newTag1", "newTag2"), Field.of("otherTag")); + * ``` + * + * @param arrays The array expressions or values to concatenate. + * @return A new `Expr` representing the concatenated array. + */ + arrayConcat(arrays: any[]): ArrayConcat; + + /** + * Creates an expression that checks if an array contains a specific element. + * + * ```typescript + * // Check if the 'sizes' array contains the value from the 'selectedSize' field + * Field.of("sizes").arrayContains(Field.of("selectedSize")); + * ``` + * + * @param element The element to search for in the array. + * @return A new `Expr` representing the 'array_contains' comparison. + */ + arrayContains(element: Expr): ArrayContains; + + /** + * Creates an expression that checks if an array contains a specific value. + * + * ```typescript + * // Check if the 'colors' array contains "red" + * Field.of("colors").arrayContains("red"); + * ``` + * + * @param element The element to search for in the array. + * @return A new `Expr` representing the 'array_contains' comparison. + */ + arrayContains(element: any): ArrayContains; + + /** + * Creates an expression that checks if an array contains all the specified elements. + * + * ```typescript + * // Check if the 'tags' array contains both "news" and "sports" + * Field.of("tags").arrayContainsAll(Field.of("tag1"), Field.of("tag2")); + * ``` + * + * @param values The elements to check for in the array. + * @return A new `Expr` representing the 'array_contains_all' comparison. + */ + arrayContainsAll(...values: Expr[]): ArrayContainsAll; + + /** + * Creates an expression that checks if an array contains all the specified elements. + * + * ```typescript + * // Check if the 'tags' array contains both of the values from field 'tag1' and "tag2" + * Field.of("tags").arrayContainsAll(Field.of("tag1"), Field.of("tag2")); + * ``` + * + * @param values The elements to check for in the array. + * @return A new `Expr` representing the 'array_contains_all' comparison. + */ + arrayContainsAll(...values: any[]): ArrayContainsAll; + + /** + * Creates an expression that checks if an array contains any of the specified elements. + * + * ```typescript + * // Check if the 'categories' array contains either values from field "cate1" or "cate2" + * Field.of("categories").arrayContainsAny(Field.of("cate1"), Field.of("cate2")); + * ``` + * + * @param values The elements to check for in the array. + * @return A new `Expr` representing the 'array_contains_any' comparison. + */ + arrayContainsAny(...values: Expr[]): ArrayContainsAny; + + /** + * Creates an expression that checks if an array contains any of the specified elements. + * + * ```typescript + * // Check if the 'groups' array contains either the value from the 'userGroup' field + * // or the value "guest" + * Field.of("groups").arrayContainsAny(Field.of("userGroup"), "guest"); + * ``` + * + * @param values The elements to check for in the array. + * @return A new `Expr` representing the 'array_contains_any' comparison. + */ + arrayContainsAny(...values: any[]): ArrayContainsAny; + + /** + * Creates an expression that filters elements from an array using the given {@link + * FilterCondition} and returns the filtered elements as a new array. + * + * ```typescript + * // Get items from the 'inventoryPrices' array where the array item is greater than 0 + * // Note we use {@link Function#arrayElement} to represent array elements to construct a + * // filtering condition. + * Field.of("inventoryPrices").arrayFilter(arrayElement().gt(0)); + * ``` + * + * @param filter The {@link FilterCondition} to apply to the array elements. + * @return A new `Expr` representing the filtered array. + */ + arrayFilter(filter: FilterExpr): ArrayFilter; + + /** + * Creates an expression that calculates the length of an array. + * + * ```typescript + * // Get the number of items in the 'cart' array + * Field.of("cart").arrayLength(); + * ``` + * + * @return A new `Expr` representing the length of the array. + */ + arrayLength(): ArrayLength; + + /** + * Creates an expression that applies a transformation function to each element in an array and + * returns the new array as the result of the evaluation. + * + * ```typescript + * // Convert all strings in the 'names' array to uppercase + * Field.of("names").arrayTransform(arrayElement().toUppercase()); + * ``` + * + * @param transform The {@link Function} to apply to each array element. + * @return A new `Expr` representing the transformed array. + */ + arrayTransform(transform: Function): ArrayTransform; + + /** + * Creates an expression that checks if this expression is equal to any of the provided values or + * expressions. + * + * ```typescript + * // Check if the 'category' field is either "Electronics" or value of field 'primaryType' + * Field.of("category").in("Electronics", Field.of("primaryType")); + * ``` + * + * @param others The values or expressions to check against. + * @return A new `Expr` representing the 'IN' comparison. + */ + in(...others: Expr[]): In; + + /** + * Creates an expression that checks if this expression is equal to any of the provided values or + * expressions. + * + * ```typescript + * // Check if the 'category' field is either "Electronics" or value of field 'primaryType' + * Field.of("category").in("Electronics", Field.of("primaryType")); + * ``` + * + * @param others The values or expressions to check against. + * @return A new `Expr` representing the 'IN' comparison. + */ + in(...others: any[]): In; + + /** + * Creates an expression that checks if this expression evaluates to 'NaN' (Not a Number). + * + * ```typescript + * // Check if the result of a calculation is NaN + * Field.of("value").divide(0).isNaN(); + * ``` + * + * @return A new `Expr` representing the 'isNaN' check. + */ + isNaN(): IsNan; + + /** + * Creates an expression that checks if a field exists in the document. + * + * ```typescript + * // Check if the document has a field named "phoneNumber" + * Field.of("phoneNumber").exists(); + * ``` + * + * @return A new `Expr` representing the 'exists' check. + */ + exists(): Exists; + + /** + * Creates an expression that calculates the length of a string. + * + * ```typescript + * // Get the length of the 'name' field + * Field.of("name").length(); + * ``` + * + * @return A new `Expr` representing the length of the string. + */ + length(): Length; + + /** + * Creates an expression that performs a case-sensitive string comparison. + * + * ```typescript + * // Check if the 'title' field contains the word "guide" (case-sensitive) + * Field.of("title").like("%guide%"); + * ``` + * + * @param pattern The pattern to search for. You can use "%" as a wildcard character. + * @return A new `Expr` representing the 'like' comparison. + */ + like(pattern: string): Like; + + /** + * Creates an expression that performs a case-sensitive string comparison. + * + * ```typescript + * // Check if the 'title' field contains the word "guide" (case-sensitive) + * Field.of("title").like("%guide%"); + * ``` + * + * @param pattern The pattern to search for. You can use "%" as a wildcard character. + * @return A new `Expr` representing the 'like' comparison. + */ + like(pattern: Expr): Like; + + /** + * Creates an expression that checks if a string contains a specified regular expression as a + * substring. + * + * ```typescript + * // Check if the 'description' field contains "example" (case-insensitive) + * Field.of("description").regexContains("(?i)example"); + * ``` + * + * @param pattern The regular expression to use for the search. + * @return A new `Expr` representing the 'contains' comparison. + */ + regexContains(pattern: string): RegexContains; + + /** + * Creates an expression that checks if a string contains a specified regular expression as a + * substring. + * + * ```typescript + * // Check if the 'description' field contains the regular expression stored in field 'regex' + * Field.of("description").regexContains(Field.of("regex")); + * ``` + * + * @param pattern The regular expression to use for the search. + * @return A new `Expr` representing the 'contains' comparison. + */ + regexContains(pattern: Expr): RegexContains; + + /** + * Creates an expression that checks if a string matches a specified regular expression. + * + * ```typescript + * // Check if the 'email' field matches a valid email pattern + * Field.of("email").regexMatch("[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,}"); + * ``` + * + * @param pattern The regular expression to use for the match. + * @return A new `Expr` representing the regular expression match. + */ + regexMatch(pattern: string): RegexMatch; + + /** + * Creates an expression that checks if a string matches a specified regular expression. + * + * ```typescript + * // Check if the 'email' field matches a regular expression stored in field 'regex' + * Field.of("email").regexMatch(Field.of("regex")); + * ``` + * + * @param pattern The regular expression to use for the match. + * @return A new `Expr` representing the regular expression match. + */ + regexMatch(pattern: Expr): RegexMatch; + + /** + * Creates an expression that checks if a string starts with a given prefix. + * + * ```typescript + * // Check if the 'name' field starts with "Mr." + * Field.of("name").startsWith("Mr."); + * ``` + * + * @param prefix The prefix to check for. + * @return A new `Expr` representing the 'starts with' comparison. + */ + startsWith(prefix: string): StartsWith; + + /** + * Creates an expression that checks if a string starts with a given prefix (represented as an + * expression). + * + * ```typescript + * // Check if the 'fullName' field starts with the value of the 'firstName' field + * Field.of("fullName").startsWith(Field.of("firstName")); + * ``` + * + * @param prefix The prefix expression to check for. + * @return A new `Expr` representing the 'starts with' comparison. + */ + startsWith(prefix: Expr): StartsWith; + + /** + * Creates an expression that checks if a string ends with a given postfix. + * + * ```typescript + * // Check if the 'filename' field ends with ".txt" + * Field.of("filename").endsWith(".txt"); + * ``` + * + * @param suffix The postfix to check for. + * @return A new `Expr` representing the 'ends with' comparison. + */ + endsWith(suffix: string): EndsWith; + + /** + * Creates an expression that checks if a string ends with a given postfix (represented as an + * expression). + * + * ```typescript + * // Check if the 'url' field ends with the value of the 'extension' field + * Field.of("url").endsWith(Field.of("extension")); + * ``` + * + * @param suffix The postfix expression to check for. + * @return A new `Expr` representing the 'ends with' comparison. + */ + endsWith(suffix: Expr): EndsWith; + + /** + * Creates an expression that converts a string to lowercase. + * + * ```typescript + * // Convert the 'name' field to lowercase + * Field.of("name").toLowerCase(); + * ``` + * + * @return A new `Expr` representing the lowercase string. + */ + toLowercase(): ToLowercase; + + /** + * Creates an expression that converts a string to uppercase. + * + * ```typescript + * // Convert the 'title' field to uppercase + * Field.of("title").toUpperCase(); + * ``` + * + * @return A new `Expr` representing the uppercase string. + */ + toUppercase(): ToUppercase; + + /** + * Creates an expression that removes leading and trailing whitespace from a string. + * + * ```typescript + * // Trim whitespace from the 'userInput' field + * Field.of("userInput").trim(); + * ``` + * + * @return A new `Expr` representing the trimmed string. + */ + trim(): Trim; + + /** + * Creates an expression that concatenates string expressions together. + * + * ```typescript + * // Combine the 'firstName', " ", and 'lastName' fields into a single string + * Field.of("firstName").strConcat(Constant.of(" "), Field.of("lastName")); + * ``` + * + * @param elements The expressions (typically strings) to concatenate. + * @return A new `Expr` representing the concatenated string. + */ + strConcat(...elements: (string | Expr)[]): StrConcat; + + /** + * Accesses a value from a map (object) field using the provided key. + * + * ```typescript + * // Get the 'city' value from the 'address' map field + * Field.of("address").mapGet("city"); + * ``` + * + * @param subfield The key to access in the map. + * @return A new `Expr` representing the value associated with the given key in the map. + */ + mapGet(subfield: string): MapGet; + + /** + * Creates an aggregation that counts the number of stage inputs with valid evaluations of the + * expression or field. + * + * ```typescript + * // Count the total number of products + * Field.of("productId").count().as("totalProducts"); + * ``` + * + * @return A new `Accumulator` representing the 'count' aggregation. + */ + count(): Count; + + /** + * Creates an aggregation that calculates the sum of a numeric field across multiple stage inputs. + * + * ```typescript + * // Calculate the total revenue from a set of orders + * Field.of("orderAmount").sum().as("totalRevenue"); + * ``` + * + * @return A new `Accumulator` representing the 'sum' aggregation. + */ + sum(): Sum; + + /** + * Creates an aggregation that calculates the average (mean) of a numeric field across multiple + * stage inputs. + * + * ```typescript + * // Calculate the average age of users + * Field.of("age").avg().as("averageAge"); + * ``` + * + * @return A new `Accumulator` representing the 'avg' aggregation. + */ + avg(): Avg; + + /** + * Creates an aggregation that finds the minimum value of a field across multiple stage inputs. + * + * ```typescript + * // Find the lowest price of all products + * Field.of("price").min().as("lowestPrice"); + * ``` + * + * @return A new `Accumulator` representing the 'min' aggregation. + */ + min(): Min; + + /** + * Creates an aggregation that finds the maximum value of a field across multiple stage inputs. + * + * ```typescript + * // Find the highest score in a leaderboard + * Field.of("score").max().as("highestScore"); + * ``` + * + * @return A new `Accumulator` representing the 'max' aggregation. + */ + max(): Max; + + /** + * Calculates the cosine distance between two vectors. + * + * ```typescript + * // Calculate the cosine distance between the 'userVector' field and the 'itemVector' field + * Field.of("userVector").cosineDistance(Field.of("itemVector")); + * ``` + * + * @param other The other vector (represented as an Expr) to compare against. + * @return A new `Expr` representing the cosine distance between the two vectors. + */ + cosineDistance(other: Expr): CosineDistance; + /** + * Calculates the Cosine distance between two vectors. + * + * ```typescript + * // Calculate the Cosine distance between the 'location' field and a target location + * Field.of("location").cosineDistance(new VectorValue([37.7749, -122.4194])); + * ``` + * + * @param other The other vector (as a VectorValue) to compare against. + * @return A new `Expr` representing the Cosine* distance between the two vectors. + */ + cosineDistance(other: VectorValue): CosineDistance; + /** + * Calculates the Cosine distance between two vectors. + * + * ```typescript + * // Calculate the Cosine distance between the 'location' field and a target location + * Field.of("location").cosineDistance([37.7749, -122.4194]); + * ``` + * + * @param other The other vector (as an array of numbers) to compare against. + * @return A new `Expr` representing the Cosine distance between the two vectors. + */ + cosineDistance(other: number[]): CosineDistance; + + /** + * Calculates the dot product between two vectors. + * + * ```typescript + * // Calculate the dot product between a feature vector and a target vector + * Field.of("features").dotProduct([0.5, 0.8, 0.2]); + * ``` + * + * @param other The other vector (as an array of numbers) to calculate with. + * @return A new `Expr` representing the dot product between the two vectors. + */ + dotProduct(other: Expr): DotProduct; + + /** + * Calculates the dot product between two vectors. + * + * ```typescript + * // Calculate the dot product between a feature vector and a target vector + * Field.of("features").dotProduct(new VectorValue([0.5, 0.8, 0.2])); + * ``` + * + * @param other The other vector (as an array of numbers) to calculate with. + * @return A new `Expr` representing the dot product between the two vectors. + */ + dotProduct(other: VectorValue): DotProduct; + + /** + * Calculates the dot product between two vectors. + * + * ```typescript + * // Calculate the dot product between a feature vector and a target vector + * Field.of("features").dotProduct([0.5, 0.8, 0.2]); + * ``` + * + * @param other The other vector (as an array of numbers) to calculate with. + * @return A new `Expr` representing the dot product between the two vectors. + */ + dotProduct(other: number[]): DotProduct; + + /** + * Calculates the Euclidean distance between two vectors. + * + * ```typescript + * // Calculate the Euclidean distance between the 'location' field and a target location + * Field.of("location").euclideanDistance([37.7749, -122.4194]); + * ``` + * + * @param other The other vector (as an array of numbers) to calculate with. + * @return A new `Expr` representing the Euclidean distance between the two vectors. + */ + euclideanDistance(other: Expr): EuclideanDistance; + + /** + * Calculates the Euclidean distance between two vectors. + * + * ```typescript + * // Calculate the Euclidean distance between the 'location' field and a target location + * Field.of("location").euclideanDistance(new VectorValue([37.7749, -122.4194])); + * ``` + * + * @param other The other vector (as a VectorValue) to compare against. + * @return A new `Expr` representing the Euclidean distance between the two vectors. + */ + euclideanDistance(other: VectorValue): EuclideanDistance; + + /** + * Calculates the Euclidean distance between two vectors. + * + * ```typescript + * // Calculate the Euclidean distance between the 'location' field and a target location + * Field.of("location").euclideanDistance([37.7749, -122.4194]); + * ``` + * + * @param other The other vector (as an array of numbers) to compare against. + * @return A new `Expr` representing the Euclidean distance between the two vectors. + */ + euclideanDistance(other: number[]): EuclideanDistance; + + /** + * Creates an {@link Ordering} that sorts documents in ascending order based on this expression. + * + * ```typescript + * // Sort documents by the 'name' field in ascending order + * firestore.pipeline().collection("users") + * .sort(Field.of("name").ascending()); + * ``` + * + * @return A new `Ordering` for ascending sorting. + */ + ascending(): Ordering; + + /** + * Creates an {@link Ordering} that sorts documents in descending order based on this expression. + * + * ```typescript + * // Sort documents by the 'createdAt' field in descending order + * firestore.pipeline().collection("users") + * .sort(Field.of("createdAt").descending()); + * ``` + * + * @return A new `Ordering` for descending sorting. + */ + descending(): Ordering; + + /** + * 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. + * + * ```typescript + * // Calculate the total price and assign it the alias "totalPrice" and add it to the output. + * firestore.pipeline().collection("items") + * .addFields(Field.of("price").multiply(Field.of("quantity")).as("totalPrice")); + * ``` + * + * @param name The alias to assign to this expression. + * @return A new {@link ExprWithAlias} that wraps this + * expression and associates it with the provided alias. + */ + as(name: string): ExprWithAlias; + } + + /** + * @beta + */ + export class ExprWithAlias + extends Expr + implements Selectable + { + exprType: ExprType; + selectable: true; + /** + * @param expr The expression to alias. + * @param alias The alias to assign to the expression. + */ + constructor(expr: T, alias: string); + } + + /** + * @beta + * + * Represents a reference to a field in a Firestore document, or outputs of a {@link Pipeline} stage. + * + *

    Field references are used to access document field values in expressions and to specify fields + * for sorting, filtering, and projecting data in Firestore pipelines. + * + *

    You can create a `Field` instance using the static {@link #of} method: + * + * ```typescript + * // Create a Field instance for the 'name' field + * const nameField = Field.of("name"); + * + * // Create a Field instance for a nested field 'address.city' + * const cityField = Field.of("address.city"); + * ``` + */ + export class Field extends Expr implements Selectable { + exprType: ExprType; + selectable: true; + + /** + * Creates a {@code Field} instance representing the field at the given path. + * + * The path can be a simple field name (e.g., "name") or a dot-separated path to a nested field + * (e.g., "address.city"). + * + * ```typescript + * // Create a Field instance for the 'title' field + * const titleField = Field.of("title"); + * + * // Create a Field instance for a nested field 'author.firstName' + * const authorFirstNameField = Field.of("author.firstName"); + * ``` + * + * @param name The path to the field. + * @return A new {@code Field} instance representing the specified field. + */ + static of(name: string): Field; + static of(path: FieldPath): Field; + static of(nameOrPath: string | FieldPath): Field; + static of(pipeline: Pipeline, name: string): Field; + /** + * Returns the field name. + * + * @return The field name. + */ + fieldName(): string; + } + + /** + * @beta + */ + export class Fields extends Expr implements Selectable { + exprType: ExprType; + selectable: true; + static of(name: string, ...others: string[]): Fields; + static ofAll(): Fields; + /** + * Returns the list of fields. + * + * @return The list of fields. + */ + fieldList(): Field[]; + } + + /** + * @beta + * + * Represents a constant value that can be used in a Firestore pipeline expression. + * + * You can create a `Constant` instance using the static {@link #of} method: + * + * ```typescript + * // Create a Constant instance for the number 10 + * const ten = Constant.of(10); + * + * // Create a Constant instance for the string "hello" + * const hello = Constant.of("hello"); + * ``` + */ + export class Constant extends Expr { + exprType: ExprType; + + /** + * Creates a `Constant` instance for a number value. + * + * @param value The number value. + * @return A new `Constant` instance. + */ + static of(value: number): Constant; + + /** + * Creates a `Constant` instance for a string value. + * + * @param value The string value. + * @return A new `Constant` instance. + */ + static of(value: string): Constant; + + /** + * Creates a `Constant` instance for a boolean value. + * + * @param value The boolean value. + * @return A new `Constant` instance. + */ + static of(value: boolean): Constant; + + /** + * Creates a `Constant` instance for a null value. + * + * @param value The null value. + * @return A new `Constant` instance. + */ + static of(value: null): Constant; + + /** + * Creates a `Constant` instance for an undefined value. + * + * @param value The undefined value. + * @return A new `Constant` instance. + */ + static of(value: undefined): Constant; + + /** + * Creates a `Constant` instance for a GeoPoint value. + * + * @param value The GeoPoint value. + * @return A new `Constant` instance. + */ + static of(value: GeoPoint): Constant; + + /** + * Creates a `Constant` instance for a Timestamp value. + * + * @param value The Timestamp value. + * @return A new `Constant` instance. + */ + static of(value: Timestamp): Constant; + + /** + * Creates a `Constant` instance for a Date value. + * + * @param value The Date value. + * @return A new `Constant` instance. + */ + static of(value: Date): Constant; + + /** + * Creates a `Constant` instance for a Uint8Array value. + * + * @param value The Uint8Array value. + * @return A new `Constant` instance. + */ + static of(value: Uint8Array): Constant; + + /** + * Creates a `Constant` instance for a DocumentReference value. + * + * @param value The DocumentReference value. + * @return A new `Constant` instance. + */ + static of(value: DocumentReference): Constant; + + /** + * Creates a `Constant` instance for an array value. + * + * @param value The array value. + * @return A new `Constant` instance. + */ + static of(value: Array): Constant; + + /** + * Creates a `Constant` instance for a map value. + * + * @param value The map value. + * @return A new `Constant` instance. + */ + static of(value: Map): Constant; + + /** + * Creates a `Constant` instance for a VectorValue value. + * + * @param value The VectorValue value. + * @return A new `Constant` instance. + */ + static of(value: VectorValue): Constant; + static of(value: any): Constant; + + /** + * Creates a `Constant` instance for a VectorValue value. + * + * ```typescript + * // Create a Constant instance for a vector value + * const vectorConstant = Constant.ofVector([1, 2, 3]); + * ``` + * + * @param value The VectorValue value. + * @return A new `Constant` instance. + */ + static vector(value: Array | VectorValue): Constant; + } + + /** + * @beta + * + * This class defines the base class for Firestore {@link 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 and}, {@link eq}, + * or the methods on {@link Expr} ({@link Expr#eq}, {@link Expr#lt}, etc) to construct new Function instances. + */ + export class Function extends Expr { + exprType: ExprType; + } + + /** + * @beta + */ + export class Add extends Function {} + + /** + * @beta + */ + export class Subtract extends Function {} + + /** + * @beta + */ + export class Multiply extends Function {} + + /** + * @beta + */ + export class Divide extends Function {} + + /** + * @beta + */ + export class Eq extends Function implements FilterCondition { + filterable: true; + } + + /** + * @beta + */ + export class Neq extends Function implements FilterCondition { + filterable: true; + } + + /** + * @beta + */ + export class Lt extends Function implements FilterCondition { + filterable: true; + } + + /** + * @beta + */ + export class Lte extends Function implements FilterCondition { + filterable: true; + } + + /** + * @beta + */ + export class Gt extends Function implements FilterCondition { + filterable: true; + } + + /** + * @beta + */ + export class Gte extends Function implements FilterCondition { + filterable: true; + } + + /** + * @beta + */ + export class ArrayConcat extends Function {} + + /** + * @beta + */ + export class ArrayContains extends Function implements FilterCondition { + filterable: true; + } + + /** + * @beta + */ + export class ArrayContainsAll extends Function implements FilterCondition { + filterable: true; + } + + /** + * @beta + */ + export class ArrayContainsAny extends Function implements FilterCondition { + filterable: true; + } + + /** + * @beta + */ + export class ArrayFilter extends Function {} + + /** + * @beta + */ + export class ArrayLength extends Function {} + + /** + * @beta + */ + export class ArrayTransform extends Function {} + + /** + * @beta + */ + export class ArrayElement extends Function {} + + /** + * @beta + */ + export class In extends Function implements FilterCondition { + filterable: true; + } + + /** + * @beta + */ + export class IsNan extends Function implements FilterCondition { + filterable: true; + } + + /** + * @beta + */ + export class Exists extends Function implements FilterCondition { + filterable: true; + } + + /** + * @beta + */ + export class Not extends Function implements FilterCondition { + filterable: true; + } + + /** + * @beta + */ + export class And extends Function implements FilterCondition { + filterable: true; + } + + /** + * @beta + */ + export class Or extends Function implements FilterCondition { + filterable: true; + } + + /** + * @beta + */ + export class Xor extends Function implements FilterCondition { + filterable: true; + } + + /** + * @beta + */ + export class If extends Function implements FilterCondition { + filterable: true; + } + + /** + * @beta + */ + export class Length extends Function {} + + /** + * @beta + */ + export class Like extends Function implements FilterCondition { + filterable: true; + } + + /** + * @beta + */ + export class RegexContains extends Function implements FilterCondition { + filterable: true; + } + + /** + * @beta + */ + export class RegexMatch extends Function implements FilterCondition { + filterable: true; + } + + /** + * @beta + */ + export class StartsWith extends Function implements FilterCondition { + filterable: true; + } + + /** + * @beta + */ + export class EndsWith extends Function implements FilterCondition { + filterable: true; + } + + /** + * @beta + */ + export class ToLowercase extends Function {} + + /** + * @beta + */ + export class ToUppercase extends Function {} + + /** + * @beta + */ + export class Trim extends Function {} + + /** + * @beta + */ + export class StrConcat extends Function {} + + /** + * @beta + */ + export class MapGet extends Function {} + + /** + * @beta + */ + export class Count extends Function implements Accumulator { + accumulator: true; + } + + /** + * @beta + */ + export class Sum extends Function implements Accumulator { + accumulator: true; + } + + /** + * @beta + */ + export class Avg extends Function implements Accumulator { + accumulator: true; + } + + /** + * @beta + */ + export class Min extends Function implements Accumulator { + accumulator: true; + } + + /** + * @beta + */ + export class Max extends Function implements Accumulator { + accumulator: true; + } + + /** + * @beta + */ + export class CosineDistance extends Function {} + + /** + * @beta + */ + export class DotProduct extends Function {} + + /** + * @beta + */ + export class EuclideanDistance extends Function {} + + /** + * @beta + * + * Creates an expression that adds two expressions together. + * + * ```typescript + * // Add the value of the 'quantity' field and the 'reserve' field. + * add(Field.of("quantity"), Field.of("reserve")); + * ``` + * + * @param left The first expression to add. + * @param right The second expression to add. + * @return A new {@code Expr} representing the addition operation. + */ + export function add(left: Expr, right: Expr): Add; + + /** + * @beta + * + * Creates an expression that adds an expression to a constant value. + * + * ```typescript + * // Add 5 to the value of the 'age' field + * add(Field.of("age"), 5); + * ``` + * + * @param left The expression to add to. + * @param right The constant value to add. + * @return A new {@code Expr} representing the addition operation. + */ + export function add(left: Expr, right: any): Add; + + /** + * @beta + * + * Creates an expression that adds a field's value to an expression. + * + * ```typescript + * // Add the value of the 'quantity' field and the 'reserve' field. + * add("quantity", Field.of("reserve")); + * ``` + * + * @param left The field name to add to. + * @param right The expression to add. + * @return A new {@code Expr} representing the addition operation. + */ + export function add(left: string, right: Expr): Add; + + /** + * @beta + * + * Creates an expression that adds a field's value to a constant value. + * + * ```typescript + * // Add 5 to the value of the 'age' field + * add("age", 5); + * ``` + * + * @param left The field name to add to. + * @param right The constant value to add. + * @return A new {@code Expr} representing the addition operation. + */ + export function add(left: string, right: any): Add; + + /** + * @beta + * + * Creates an expression that subtracts two expressions. + * + * ```typescript + * // Subtract the 'discount' field from the 'price' field + * subtract(Field.of("price"), Field.of("discount")); + * ``` + * + * @param left The expression to subtract from. + * @param right The expression to subtract. + * @return A new {@code Expr} representing the subtraction operation. + */ + export function subtract(left: Expr, right: Expr): Subtract; + + /** + * @beta + * + * Creates an expression that subtracts a constant value from an expression. + * + * ```typescript + * // Subtract the constant value 2 from the 'value' field + * subtract(Field.of("value"), 2); + * ``` + * + * @param left The expression to subtract from. + * @param right The constant value to subtract. + * @return A new {@code Expr} representing the subtraction operation. + */ + export function subtract(left: Expr, right: any): Subtract; + + /** + * @beta + * + * Creates an expression that subtracts an expression from a field's value. + * + * ```typescript + * // Subtract the 'discount' field from the 'price' field + * subtract("price", Field.of("discount")); + * ``` + * + * @param left The field name to subtract from. + * @param right The expression to subtract. + * @return A new {@code Expr} representing the subtraction operation. + */ + export function subtract(left: string, right: Expr): Subtract; + + /** + * @beta + * + * Creates an expression that subtracts a constant value from a field's value. + * + * ```typescript + * // Subtract 20 from the value of the 'total' field + * subtract("total", 20); + * ``` + * + * @param left The field name to subtract from. + * @param right The constant value to subtract. + * @return A new {@code Expr} representing the subtraction operation. + */ + export function subtract(left: string, right: any): Subtract; + + /** + * @beta + * + * Creates an expression that multiplies two expressions together. + * + * ```typescript + * // Multiply the 'quantity' field by the 'price' field + * multiply(Field.of("quantity"), Field.of("price")); + * ``` + * + * @param left The first expression to multiply. + * @param right The second expression to multiply. + * @return A new {@code Expr} representing the multiplication operation. + */ + export function multiply(left: Expr, right: Expr): Multiply; + + /** + * @beta + * + * Creates an expression that multiplies an expression by a constant value. + * + * ```typescript + * // Multiply the value of the 'price' field by 2 + * multiply(Field.of("price"), 2); + * ``` + * + * @param left The expression to multiply. + * @param right The constant value to multiply by. + * @return A new {@code Expr} representing the multiplication operation. + */ + export function multiply(left: Expr, right: any): Multiply; + + /** + * @beta + * + * Creates an expression that multiplies a field's value by an expression. + * + * ```typescript + * // Multiply the 'quantity' field by the 'price' field + * multiply("quantity", Field.of("price")); + * ``` + * + * @param left The field name to multiply. + * @param right The expression to multiply by. + * @return A new {@code Expr} representing the multiplication operation. + */ + export function multiply(left: string, right: Expr): Multiply; + + /** + * @beta + * + * Creates an expression that multiplies a field's value by a constant value. + * + * ```typescript + * // Multiply the 'value' field by 2 + * multiply("value", 2); + * ``` + * + * @param left The field name to multiply. + * @param right The constant value to multiply by. + * @return A new {@code Expr} representing the multiplication operation. + */ + export function multiply(left: string, right: any): Multiply; + + /** + * @beta + * + * Creates an expression that divides two expressions. + * + * ```typescript + * // Divide the 'total' field by the 'count' field + * divide(Field.of("total"), Field.of("count")); + * ``` + * + * @param left The expression to be divided. + * @param right The expression to divide by. + * @return A new {@code Expr} representing the division operation. + */ + export function divide(left: Expr, right: Expr): Divide; + + /** + * @beta + * + * Creates an expression that divides an expression by a constant value. + * + * ```typescript + * // Divide the 'value' field by 10 + * divide(Field.of("value"), 10); + * ``` + * + * @param left The expression to be divided. + * @param right The constant value to divide by. + * @return A new {@code Expr} representing the division operation. + */ + export function divide(left: Expr, right: any): Divide; + + /** + * @beta + * + * Creates an expression that divides a field's value by an expression. + * + * ```typescript + * // Divide the 'total' field by the 'count' field + * divide("total", Field.of("count")); + * ``` + * + * @param left The field name to be divided. + * @param right The expression to divide by. + * @return A new {@code Expr} representing the division operation. + */ + export function divide(left: string, right: Expr): Divide; + + /** + * @beta + * + * Creates an expression that divides a field's value by a constant value. + * + * ```typescript + * // Divide the 'value' field by 10 + * divide("value", 10); + * ``` + * + * @param left The field name to be divided. + * @param right The constant value to divide by. + * @return A new {@code Expr} representing the division operation. + */ + export function divide(left: string, right: any): Divide; + + /** + * @beta + * + * Creates an expression that checks if two expressions are equal. + * + * ```typescript + * // Check if the 'age' field is equal to an expression + * eq(Field.of("age"), Field.of("minAge").add(10)); + * ``` + * + * @param left The first expression to compare. + * @param right The second expression to compare. + * @return A new `Expr` representing the equality comparison. + */ + export function eq(left: Expr, right: Expr): Eq; + + /** + * @beta + * + * Creates an expression that checks if an expression is equal to a constant value. + * + * ```typescript + * // Check if the 'age' field is equal to 21 + * eq(Field.of("age"), 21); + * ``` + * + * @param left The expression to compare. + * @param right The constant value to compare to. + * @return A new `Expr` representing the equality comparison. + */ + export function eq(left: Expr, right: any): Eq; + + /** + * @beta + * + * Creates an expression that checks if a field's value is equal to an expression. + * + * ```typescript + * // Check if the 'age' field is equal to the 'limit' field + * eq("age", Field.of("limit")); + * ``` + * + * @param left The field name to compare. + * @param right The expression to compare to. + * @return A new `Expr` representing the equality comparison. + */ + export function eq(left: string, right: Expr): Eq; + + /** + * @beta + * + * Creates an expression that checks if a field's value is equal to a constant value. + * + * ```typescript + * // Check if the 'city' field is equal to string constant "London" + * eq("city", "London"); + * ``` + * + * @param left The field name to compare. + * @param right The constant value to compare to. + * @return A new `Expr` representing the equality comparison. + */ + export function eq(left: string, right: any): Eq; + + /** + * @beta + * + * Creates an expression that checks if two expressions are not equal. + * + * ```typescript + * // Check if the 'status' field is not equal to field 'finalState' + * neq(Field.of("status"), Field.of("finalState")); + * ``` + * + * @param left The first expression to compare. + * @param right The second expression to compare. + * @return A new `Expr` representing the inequality comparison. + */ + export function neq(left: Expr, right: Expr): Neq; + + /** + * @beta + * + * Creates an expression that checks if an expression is not equal to a constant value. + * + * ```typescript + * // Check if the 'status' field is not equal to "completed" + * neq(Field.of("status"), "completed"); + * ``` + * + * @param left The expression to compare. + * @param right The constant value to compare to. + * @return A new `Expr` representing the inequality comparison. + */ + export function neq(left: Expr, right: any): Neq; + + /** + * @beta + * + * Creates an expression that checks if a field's value is not equal to an expression. + * + * ```typescript + * // Check if the 'status' field is not equal to the value of 'expectedStatus' + * neq("status", Field.of("expectedStatus")); + * ``` + * + * @param left The field name to compare. + * @param right The expression to compare to. + * @return A new `Expr` representing the inequality comparison. + */ + export function neq(left: string, right: Expr): Neq; + + /** + * @beta + * + * Creates an expression that checks if a field's value is not equal to a constant value. + * + * ```typescript + * // Check if the 'country' field is not equal to "USA" + * neq("country", "USA"); + * ``` + * + * @param left The field name to compare. + * @param right The constant value to compare to. + * @return A new `Expr` representing the inequality comparison. + */ + export function neq(left: string, right: any): Neq; + + /** + * @beta + * + * Creates an expression that checks if the first expression is less than the second expression. + * + * ```typescript + * // Check if the 'age' field is less than 30 + * lt(Field.of("age"), Field.of("limit")); + * ``` + * + * @param left The first expression to compare. + * @param right The second expression to compare. + * @return A new `Expr` representing the less than comparison. + */ + export function lt(left: Expr, right: Expr): Lt; + + /** + * @beta + * + * Creates an expression that checks if an expression is less than a constant value. + * + * ```typescript + * // Check if the 'age' field is less than 30 + * lt(Field.of("age"), 30); + * ``` + * + * @param left The expression to compare. + * @param right The constant value to compare to. + * @return A new `Expr` representing the less than comparison. + */ + export function lt(left: Expr, right: any): Lt; + + /** + * @beta + * + * Creates an expression that checks if a field's value is less than an expression. + * + * ```typescript + * // Check if the 'age' field is less than the 'limit' field + * lt("age", Field.of("limit")); + * ``` + * + * @param left The field name to compare. + * @param right The expression to compare to. + * @return A new `Expr` representing the less than comparison. + */ + export function lt(left: string, right: Expr): Lt; + + /** + * @beta + * + * Creates an expression that checks if a field's value is less than a constant value. + * + * ```typescript + * // Check if the 'price' field is less than 50 + * lt("price", 50); + * ``` + * + * @param left The field name to compare. + * @param right The constant value to compare to. + * @return A new `Expr` representing the less than comparison. + */ + export function lt(left: string, right: any): Lt; + + /** + * @beta + * + * Creates an expression that checks if the first expression is less than or equal to the second + * expression. + * + * ```typescript + * // Check if the 'quantity' field is less than or equal to 20 + * lte(Field.of("quantity"), Field.of("limit")); + * ``` + * + * @param left The first expression to compare. + * @param right The second expression to compare. + * @return A new `Expr` representing the less than or equal to comparison. + */ + export function lte(left: Expr, right: Expr): Lte; + + /** + * @beta + * + * Creates an expression that checks if an expression is less than or equal to a constant value. + * + * ```typescript + * // Check if the 'quantity' field is less than or equal to 20 + * lte(Field.of("quantity"), 20); + * ``` + * + * @param left The expression to compare. + * @param right The constant value to compare to. + * @return A new `Expr` representing the less than or equal to comparison. + */ + export function lte(left: Expr, right: any): Lte; + + /** + * Creates an expression that checks if a field's value is less than or equal to an expression. + * + * ```typescript + * // Check if the 'quantity' field is less than or equal to the 'limit' field + * lte("quantity", Field.of("limit")); + * ``` + * + * @param left The field name to compare. + * @param right The expression to compare to. + * @return A new `Expr` representing the less than or equal to comparison. + */ + export function lte(left: string, right: Expr): Lte; + + /** + * @beta + * + * Creates an expression that checks if a field's value is less than or equal to a constant value. + * + * ```typescript + * // Check if the 'score' field is less than or equal to 70 + * lte("score", 70); + * ``` + * + * @param left The field name to compare. + * @param right The constant value to compare to. + * @return A new `Expr` representing the less than or equal to comparison. + */ + export function lte(left: string, right: any): Lte; + + /** + * @beta + * + * Creates an expression that checks if the first expression is greater than the second + * expression. + * + * ```typescript + * // Check if the 'age' field is greater than 18 + * gt(Field.of("age"), Constant(9).add(9)); + * ``` + * + * @param left The first expression to compare. + * @param right The second expression to compare. + * @return A new `Expr` representing the greater than comparison. + */ + export function gt(left: Expr, right: Expr): Gt; + + /** + * @beta + * + * Creates an expression that checks if an expression is greater than a constant value. + * + * ```typescript + * // Check if the 'age' field is greater than 18 + * gt(Field.of("age"), 18); + * ``` + * + * @param left The expression to compare. + * @param right The constant value to compare to. + * @return A new `Expr` representing the greater than comparison. + */ + export function gt(left: Expr, right: any): Gt; + + /** + * @beta + * + * Creates an expression that checks if a field's value is greater than an expression. + * + * ```typescript + * // Check if the value of field 'age' is greater than the value of field 'limit' + * gt("age", Field.of("limit")); + * ``` + * + * @param left The field name to compare. + * @param right The expression to compare to. + * @return A new `Expr` representing the greater than comparison. + */ + export function gt(left: string, right: Expr): Gt; + + /** + * @beta + * + * Creates an expression that checks if a field's value is greater than a constant value. + * + * ```typescript + * // Check if the 'price' field is greater than 100 + * gt("price", 100); + * ``` + * + * @param left The field name to compare. + * @param right The constant value to compare to. + * @return A new `Expr` representing the greater than comparison. + */ + export function gt(left: string, right: any): Gt; + + /** + * @beta + * + * Creates an expression that checks if the first expression is greater than or equal to the + * second expression. + * + * ```typescript + * // Check if the 'quantity' field is greater than or equal to the field "threshold" + * gte(Field.of("quantity"), Field.of("threshold")); + * ``` + * + * @param left The first expression to compare. + * @param right The second expression to compare. + * @return A new `Expr` representing the greater than or equal to comparison. + */ + export function gte(left: Expr, right: Expr): Gte; + + /** + * @beta + * + * Creates an expression that checks if an expression is greater than or equal to a constant + * value. + * + * ```typescript + * // Check if the 'quantity' field is greater than or equal to 10 + * gte(Field.of("quantity"), 10); + * ``` + * + * @param left The expression to compare. + * @param right The constant value to compare to. + * @return A new `Expr` representing the greater than or equal to comparison. + */ + export function gte(left: Expr, right: any): Gte; + + /** + * @beta + * + * Creates an expression that checks if a field's value is greater than or equal to an expression. + * + * ```typescript + * // Check if the value of field 'age' is greater than or equal to the value of field 'limit' + * gte("age", Field.of("limit")); + * ``` + * + * @param left The field name to compare. + * @param right The expression to compare to. + * @return A new `Expr` representing the greater than or equal to comparison. + */ + export function gte(left: string, right: Expr): Gte; + + /** + * @beta + * + * Creates an expression that checks if a field's value is greater than or equal to a constant + * value. + * + * ```typescript + * // Check if the 'score' field is greater than or equal to 80 + * gte("score", 80); + * ``` + * + * @param left The field name to compare. + * @param right The constant value to compare to. + * @return A new `Expr` representing the greater than or equal to comparison. + */ + export function gte(left: string, right: any): Gte; + + /** + * @beta + * + * Creates an expression that concatenates an array expression with other arrays. + * + * ```typescript + * // Combine the 'items' array with two new item arrays + * arrayConcat(Field.of("items"), [Field.of("newItems"), Field.of("otherItems")]); + * ``` + * + * @param array The array expression to concatenate to. + * @param elements The array expressions to concatenate. + * @return A new {@code Expr} representing the concatenated array. + */ + export function arrayConcat(array: Expr, elements: Expr[]): ArrayConcat; + + /** + * @beta + * + * Creates an expression that concatenates an array expression with other arrays and/or values. + * + * ```typescript + * // Combine the 'tags' array with a new array + * arrayConcat(Field.of("tags"), ["newTag1", "newTag2"]); + * ``` + * + * @param array The array expression to concatenate to. + * @param elements The array expressions or single values to concatenate. + * @return A new {@code Expr} representing the concatenated array. + */ + export function arrayConcat(array: Expr, elements: any[]): ArrayConcat; + + /** + * @beta + * + * Creates an expression that concatenates a field's array value with other arrays. + * + * ```typescript + * // Combine the 'items' array with two new item arrays + * arrayConcat("items", [Field.of("newItems"), Field.of("otherItems")]); + * ``` + * + * @param array The field name containing array values. + * @param elements The array expressions to concatenate. + * @return A new {@code Expr} representing the concatenated array. + */ + export function arrayConcat(array: string, elements: Expr[]): ArrayConcat; + + /** + * @beta + * + * Creates an expression that concatenates a field's array value with other arrays and/or values. + * + * ```typescript + * // Combine the 'tags' array with a new array + * arrayConcat("tags", ["newTag1", "newTag2"]); + * ``` + * + * @param array The field name containing array values. + * @param elements The array expressions or single values to concatenate. + * @return A new {@code Expr} representing the concatenated array. + */ + export function arrayConcat(array: string, elements: any[]): ArrayConcat; + + /** + * @beta + * + * Creates an expression that checks if an array expression contains a specific element. + * + * ```typescript + * // Check if the 'colors' array contains the value of field 'selectedColor' + * arrayContains(Field.of("colors"), Field.of("selectedColor")); + * ``` + * + * @param array The array expression to check. + * @param element The element to search for in the array. + * @return A new {@code Expr} representing the 'array_contains' comparison. + */ + export function arrayContains(array: Expr, element: Expr): ArrayContains; + + /** + * @beta + * + * Creates an expression that checks if an array expression contains a specific element. + * + * ```typescript + * // Check if the 'colors' array contains "red" + * arrayContains(Field.of("colors"), "red"); + * ``` + * + * @param array The array expression to check. + * @param element The element to search for in the array. + * @return A new {@code Expr} representing the 'array_contains' comparison. + */ + export function arrayContains(array: Expr, element: any): ArrayContains; + + /** + * @beta + * + * Creates an expression that checks if a field's array value contains a specific element. + * + * ```typescript + * // Check if the 'colors' array contains the value of field 'selectedColor' + * arrayContains("colors", Field.of("selectedColor")); + * ``` + * + * @param array The field name to check. + * @param element The element to search for in the array. + * @return A new {@code Expr} representing the 'array_contains' comparison. + */ + export function arrayContains(array: string, element: Expr): ArrayContains; + + /** + * @beta + * + * Creates an expression that checks if a field's array value contains a specific value. + * + * ```typescript + * // Check if the 'colors' array contains "red" + * arrayContains("colors", "red"); + * ``` + * + * @param array The field name to check. + * @param element The element to search for in the array. + * @return A new {@code Expr} representing the 'array_contains' comparison. + */ + export function arrayContains(array: string, element: any): ArrayContains; + + /** + * @beta + * + * Creates an expression that checks if an array expression contains any of the specified + * elements. + * + * ```typescript + * // Check if the 'categories' array contains either values from field "cate1" or "Science" + * arrayContainsAny(Field.of("categories"), [Field.of("cate1"), "Science"]); + * ``` + * + * @param array The array expression to check. + * @param values The elements to check for in the array. + * @return A new {@code Expr} representing the 'array_contains_any' comparison. + */ + export function arrayContainsAny( + array: Expr, + values: Expr[] + ): ArrayContainsAny; + + /** + * @beta + * + * Creates an expression that checks if an array expression contains any of the specified + * elements. + * + * ```typescript + * // Check if the 'categories' array contains either values from field "cate1" or "Science" + * arrayContainsAny(Field.of("categories"), [Field.of("cate1"), "Science"]); + * ``` + * + * @param array The array expression to check. + * @param values The elements to check for in the array. + * @return A new {@code Expr} representing the 'array_contains_any' comparison. + */ + export function arrayContainsAny( + array: Expr, + values: any[] + ): ArrayContainsAny; + + /** + * @beta + * + * Creates an expression that checks if a field's array value contains any of the specified + * elements. + * + * ```typescript + * // Check if the 'groups' array contains either the value from the 'userGroup' field + * // or the value "guest" + * arrayContainsAny("categories", [Field.of("cate1"), "Science"]); + * ``` + * + * @param array The field name to check. + * @param values The elements to check for in the array. + * @return A new {@code Expr} representing the 'array_contains_any' comparison. + */ + export function arrayContainsAny( + array: string, + values: Expr[] + ): ArrayContainsAny; + + /** + * @beta + * + * Creates an expression that checks if a field's array value contains any of the specified + * elements. + * + * ```typescript + * // Check if the 'groups' array contains either the value from the 'userGroup' field + * // or the value "guest" + * arrayContainsAny("categories", [Field.of("cate1"), "Science"]); + * ``` + * + * @param array The field name to check. + * @param values The elements to check for in the array. + * @return A new {@code Expr} representing the 'array_contains_any' comparison. + */ + export function arrayContainsAny( + array: string, + values: any[] + ): ArrayContainsAny; + + /** + * @beta + * + * Creates an expression that checks if an array expression contains all the specified elements. + * + * ```typescript + * // Check if the 'tags' array contains both of the values from field 'tag1', 'tag2' and "tag3" + * arrayContainsAll(Field.of("tags"), [Field.of("tag1"), "SciFi", "Adventure"]); + * ``` + * + * @param array The array expression to check. + * @param values The elements to check for in the array. + * @return A new {@code Expr} representing the 'array_contains_all' comparison. + */ + export function arrayContainsAll( + array: Expr, + values: Expr[] + ): ArrayContainsAll; + + /** + * @beta + * + * Creates an expression that checks if an array expression contains all the specified elements. + * + * ```typescript + * // Check if the 'tags' array contains both of the values from field 'tag1', 'tag2' and "tag3" + * arrayContainsAll(Field.of("tags"), [Field.of("tag1"), "SciFi", "Adventure"]); + * ``` + * + * @param array The array expression to check. + * @param values The elements to check for in the array. + * @return A new {@code Expr} representing the 'array_contains_all' comparison. + */ + export function arrayContainsAll( + array: Expr, + values: any[] + ): ArrayContainsAll; + + /** + * @beta + * + * Creates an expression that checks if a field's array value contains all the specified values or + * expressions. + * + * ```typescript + * // Check if the 'tags' array contains both of the values from field 'tag1' and "tag2" + * arrayContainsAll("tags", [Field.of("tag1"), "SciFi", "Adventure"]); + * ``` + * + * @param array The field name to check. + * @param values The elements to check for in the array. + * @return A new {@code Expr} representing the 'array_contains_all' comparison. + */ + export function arrayContainsAll( + array: string, + values: Expr[] + ): ArrayContainsAll; + + /** + * @beta + * + * Creates an expression that checks if a field's array value contains all the specified values or + * expressions. + * + * ```typescript + * // Check if the 'tags' array contains both of the values from field 'tag1' and "tag2" + * arrayContainsAll("tags", [Field.of("tag1"), "SciFi", "Adventure"]); + * ``` + * + * @param array The field name to check. + * @param values The elements to check for in the array. + * @return A new {@code Expr} representing the 'array_contains_all' comparison. + */ + export function arrayContainsAll( + array: string, + values: any[] + ): ArrayContainsAll; + + /** + * @beta + * + * Creates an expression that filters elements from an array expression using the given {@link + * FilterExpr} and returns the filtered elements as a new array. + * + * ```typescript + * // Get items from the 'inventoryPrices' array where the array item is greater than 0 + * // Note we use {@link arrayElement} to represent array elements to construct a + * // filtering condition. + * arrayFilter(Field.of("inventoryPrices"), arrayElement().gt(0)); + * ``` + * + * @param array The array expression to filter. + * @param filter The {@link FilterExpr} to apply to the array elements. + * @return A new {@code Expr} representing the filtered array. + */ + export function arrayFilter(array: Expr, filter: FilterExpr): ArrayFilter; + + /** + * @beta + * + * Creates an expression that calculates the length of an array expression. + * + * ```typescript + * // Get the number of items in the 'cart' array + * arrayLength(Field.of("cart")); + * ``` + * + * @param array The array expression to calculate the length of. + * @return A new {@code Expr} representing the length of the array. + */ + export function arrayLength(array: Expr): ArrayLength; + + /** + * @beta + * + * Creates an expression that applies a transformation function to each element in an array + * expression and returns the new array as the result of the evaluation. + * + * ```typescript + * // Convert all strings in the 'names' array to uppercase + * // Note we use {@link arrayElement} to represent array elements to construct a + * // transforming function. + * arrayTransform(Field.of("names"), arrayElement().toUppercase()); + * ``` + * + * @param array The array expression to transform. + * @param transform The {@link Function} to apply to each array element. + * @return A new {@code Expr} representing the transformed array. + */ + export function arrayTransform( + array: Expr, + transform: Function + ): ArrayTransform; + + /** + * @beta + * + * Returns an expression that represents an array element within an {@link ArrayFilter} or {@link + * ArrayTransform} expression. + * + * ```typescript + * // Get items from the 'inventoryPrices' array where the array item is greater than 0 + * arrayFilter(Field.of("inventoryPrices"), arrayElement().gt(0)); + * ``` + * + * @return A new {@code Expr} representing an array element. + */ + export function arrayElement(): ArrayElement; + + /** + * @beta + * + * Creates an expression that checks if an expression is equal to any of the provided values or + * expressions. + * + * ```typescript + * // Check if the 'category' field is either "Electronics" or value of field 'primaryType' + * inAny(Field.of("category"), [Constant.of("Electronics"), Field.of("primaryType")]); + * ``` + * + * @param element The expression to compare. + * @param others The values to check against. + * @return A new {@code Expr} representing the 'IN' comparison. + */ + export function inAny(element: Expr, others: Expr[]): In; + + /** + * @beta + * + * Creates an expression that checks if an expression is equal to any of the provided values or + * expressions. + * + * ```typescript + * // Check if the 'category' field is either "Electronics" or value of field 'primaryType' + * inAny(Field.of("category"), ["Electronics", Field.of("primaryType")]); + * ``` + * + * @param element The expression to compare. + * @param others The values to check against. + * @return A new {@code Expr} representing the 'IN' comparison. + */ + export function inAny(element: Expr, others: any[]): In; + + /** + * @beta + * + * Creates an expression that checks if a field's value is equal to any of the provided values or + * expressions. + * + * ```typescript + * // Check if the 'category' field is either "Electronics" or value of field 'primaryType' + * inAny("category", [Constant.of("Electronics"), Field.of("primaryType")]); + * ``` + * + * @param element The field to compare. + * @param others The values to check against. + * @return A new {@code Expr} representing the 'IN' comparison. + */ + export function inAny(element: string, others: Expr[]): In; + + /** + * @beta + * + * Creates an expression that checks if a field's value is equal to any of the provided values or + * expressions. + * + * ```typescript + * // Check if the 'category' field is either "Electronics" or value of field 'primaryType' + * inAny("category", ["Electronics", Field.of("primaryType")]); + * ``` + * + * @param element The field to compare. + * @param others The values to check against. + * @return A new {@code Expr} representing the 'IN' comparison. + */ + export function inAny(element: string, others: any[]): In; + + /** + * @beta + * + * Creates an expression that checks if an expression is not equal to any of the provided values + * or expressions. + * + * ```typescript + * // Check if the 'status' field is neither "pending" nor the value of 'rejectedStatus' + * notInAny(Field.of("status"), [Constant.of("pending"), Field.of("rejectedStatus")]); + * ``` + * + * @param element The expression to compare. + * @param others The values to check against. + * @return A new {@code Expr} representing the 'NOT IN' comparison. + */ + export function notInAny(element: Expr, others: Expr[]): Not; + + /** + * @beta + * + * Creates an expression that checks if an expression is not equal to any of the provided values + * or expressions. + * + * ```typescript + * // Check if the 'status' field is neither "pending" nor the value of 'rejectedStatus' + * notInAny(Field.of("status"), ["pending", Field.of("rejectedStatus")]); + * ``` + * + * @param element The expression to compare. + * @param others The values to check against. + * @return A new {@code Expr} representing the 'NOT IN' comparison. + */ + export function notInAny(element: Expr, others: any[]): Not; + + /** + * @beta + * + * Creates an expression that checks if a field's value is not equal to any of the provided values + * or expressions. + * + * ```typescript + * // Check if the 'status' field is neither "pending" nor the value of 'rejectedStatus' + * notInAny("status", [Constant.of("pending"), Field.of("rejectedStatus")]); + * ``` + * + * @param element The field name to compare. + * @param others The values to check against. + * @return A new {@code Expr} representing the 'NOT IN' comparison. + */ + export function notInAny(element: string, others: Expr[]): Not; + + /** + * @beta + * + * Creates an expression that checks if a field's value is not equal to any of the provided values + * or expressions. + * + * ```typescript + * // Check if the 'status' field is neither "pending" nor the value of 'rejectedStatus' + * notInAny("status", ["pending", Field.of("rejectedStatus")]); + * ``` + * + * @param element The field name to compare. + * @param others The values to check against. + * @return A new {@code Expr} representing the 'NOT IN' comparison. + */ + export function notInAny(element: string, others: any[]): Not; + + /** + * @beta + * + * Creates an expression that performs a logical 'AND' operation on multiple filter conditions. + * + * ```typescript + * // Check if the 'age' field is greater than 18 AND the 'city' field is "London" AND + * // the 'status' field is "active" + * const condition = and(gt("age", 18), eq("city", "London"), eq("status", "active")); + * ``` + * + * @param left The first filter condition. + * @param right Additional filter conditions to 'AND' together. + * @return A new {@code Expr} representing the logical 'AND' operation. + */ + export function and(left: FilterExpr, ...right: FilterExpr[]): And; + + /** + * @beta + * + * Creates an expression that performs a logical 'OR' operation on multiple filter conditions. + * + * ```typescript + * // Check if the 'age' field is greater than 18 OR the 'city' field is "London" OR + * // the 'status' field is "active" + * const condition = or(gt("age", 18), eq("city", "London"), eq("status", "active")); + * ``` + * + * @param left The first filter condition. + * @param right Additional filter conditions to 'OR' together. + * @return A new {@code Expr} representing the logical 'OR' operation. + */ + export function or(left: FilterExpr, ...right: FilterExpr[]): Or; + + /** + * @beta + * + * Creates an expression that performs a logical 'XOR' (exclusive OR) operation on multiple filter + * conditions. + * + * ```typescript + * // Check if only one of the conditions is true: 'age' greater than 18, 'city' is "London", + * // or 'status' is "active". + * const condition = xor( + * gt("age", 18), + * eq("city", "London"), + * eq("status", "active")); + * ``` + * + * @param left The first filter condition. + * @param right Additional filter conditions to 'XOR' together. + * @return A new {@code Expr} representing the logical 'XOR' operation. + */ + export function xor(left: FilterExpr, ...right: FilterExpr[]): Xor; + + /** + * @beta + * + * Creates a conditional expression that evaluates to a 'then' expression if a condition is true + * and an 'else' expression if the condition is false. + * + * ```typescript + * // If 'age' is greater than 18, return "Adult"; otherwise, return "Minor". + * ifFunction( + * gt("age", 18), Constant.of("Adult"), Constant.of("Minor")); + * ``` + * + * @param condition The condition to evaluate. + * @param thenExpr The expression to evaluate if the condition is true. + * @param elseExpr The expression to evaluate if the condition is false. + * @return A new {@code Expr} representing the conditional expression. + */ + export function ifFunction( + condition: FilterExpr, + thenExpr: Expr, + elseExpr: Expr + ): If; + + /** + * @beta + * + * Creates an expression that negates a filter condition. + * + * ```typescript + * // Find documents where the 'completed' field is NOT true + * not(eq("completed", true)); + * ``` + * + * @param filter The filter condition to negate. + * @return A new {@code Expr} representing the negated filter condition. + */ + export function not(filter: FilterExpr): Not; + + /** + * @beta + * + * Creates an expression that checks if a field exists. + * + * ```typescript + * // Check if the document has a field named "phoneNumber" + * exists(Field.of("phoneNumber")); + * ``` + * + * @param value An expression evaluates to the name of the field to check. + * @return A new {@code Expr} representing the 'exists' check. + */ + export function exists(value: Expr): Exists; + + /** + * @beta + * + * Creates an expression that checks if a field exists. + * + * ```typescript + * // Check if the document has a field named "phoneNumber" + * exists("phoneNumber"); + * ``` + * + * @param field The field name to check. + * @return A new {@code Expr} representing the 'exists' check. + */ + export function exists(field: string): Exists; + + /** + * @beta + * + * Creates an expression that checks if an expression evaluates to 'NaN' (Not a Number). + * + * ```typescript + * // Check if the result of a calculation is NaN + * isNaN(Field.of("value").divide(0)); + * ``` + * + * @param value The expression to check. + * @return A new {@code Expr} representing the 'isNaN' check. + */ + export function isNaN(value: Expr): IsNan; + + /** + * @beta + * + * Creates an expression that checks if a field's value evaluates to 'NaN' (Not a Number). + * + * ```typescript + * // Check if the result of a calculation is NaN + * isNaN("value"); + * ``` + * + * @param value The name of the field to check. + * @return A new {@code Expr} representing the 'isNaN' check. + */ + export function isNaN(value: string): IsNan; + + /** + * @beta + * + * Creates an expression that calculates the length of a string field. + * + * ```typescript + * // Get the length of the 'name' field + * length("name"); + * ``` + * + * @param field The name of the field containing the string. + * @return A new {@code Expr} representing the length of the string. + */ + export function length(field: string): Length; + + /** + * @beta + * + * Creates an expression that calculates the length of a string expression. + * + * ```typescript + * // Get the length of the 'name' field + * length(Field.of("name")); + * ``` + * + * @param expr The expression representing the string to calculate the length of. + * @return A new {@code Expr} representing the length of the string. + */ + export function length(expr: Expr): Length; + + /** + * @beta + * + * Creates an expression that performs a case-sensitive wildcard string comparison against a + * field. + * + * ```typescript + * // Check if the 'title' field contains the string "guide" + * like("title", "%guide%"); + * ``` + * + * @param left The name of the field containing the string. + * @param pattern The pattern to search for. You can use "%" as a wildcard character. + * @return A new {@code Expr} representing the 'like' comparison. + */ + export function like(left: string, pattern: string): Like; + + /** + * @beta + * + * Creates an expression that performs a case-sensitive wildcard string comparison against a + * field. + * + * ```typescript + * // Check if the 'title' field contains the string "guide" + * like("title", Field.of("pattern")); + * ``` + * + * @param left The name of the field containing the string. + * @param pattern The pattern to search for. You can use "%" as a wildcard character. + * @return A new {@code Expr} representing the 'like' comparison. + */ + export function like(left: string, pattern: Expr): Like; + + /** + * @beta + * + * Creates an expression that performs a case-sensitive wildcard string comparison. + * + * ```typescript + * // Check if the 'title' field contains the string "guide" + * like(Field.of("title"), "%guide%"); + * ``` + * + * @param left The expression representing the string to perform the comparison on. + * @param pattern The pattern to search for. You can use "%" as a wildcard character. + * @return A new {@code Expr} representing the 'like' comparison. + */ + export function like(left: Expr, pattern: string): Like; + + /** + * @beta + * + * Creates an expression that performs a case-sensitive wildcard string comparison. + * + * ```typescript + * // Check if the 'title' field contains the string "guide" + * like(Field.of("title"), Field.of("pattern")); + * ``` + * + * @param left The expression representing the string to perform the comparison on. + * @param pattern The pattern to search for. You can use "%" as a wildcard character. + * @return A new {@code Expr} representing the 'like' comparison. + */ + export function like(left: Expr, pattern: Expr): Like; + + /** + * @beta + * + * Creates an expression that checks if a string field contains a specified regular expression as + * a substring. + * + * ```typescript + * // Check if the 'description' field contains "example" (case-insensitive) + * regexContains("description", "(?i)example"); + * ``` + * + * @param left The name of the field containing the string. + * @param pattern The regular expression to use for the search. + * @return A new {@code Expr} representing the 'contains' comparison. + */ + export function regexContains(left: string, pattern: string): RegexContains; + + /** + * @beta + * + * Creates an expression that checks if a string field contains a specified regular expression as + * a substring. + * + * ```typescript + * // Check if the 'description' field contains "example" (case-insensitive) + * regexContains("description", Field.of("pattern")); + * ``` + * + * @param left The name of the field containing the string. + * @param pattern The regular expression to use for the search. + * @return A new {@code Expr} representing the 'contains' comparison. + */ + export function regexContains(left: string, pattern: Expr): RegexContains; + + /** + * @beta + * + * Creates an expression that checks if a string expression contains a specified regular + * expression as a substring. + * + * ```typescript + * // Check if the 'description' field contains "example" (case-insensitive) + * regexContains(Field.of("description"), "(?i)example"); + * ``` + * + * @param left The expression representing the string to perform the comparison on. + * @param pattern The regular expression to use for the search. + * @return A new {@code Expr} representing the 'contains' comparison. + */ + export function regexContains(left: Expr, pattern: string): RegexContains; + + /** + * @beta + * + * Creates an expression that checks if a string expression contains a specified regular + * expression as a substring. + * + * ```typescript + * // Check if the 'description' field contains "example" (case-insensitive) + * regexContains(Field.of("description"), Field.of("pattern")); + * ``` + * + * @param left The expression representing the string to perform the comparison on. + * @param pattern The regular expression to use for the search. + * @return A new {@code Expr} representing the 'contains' comparison. + */ + export function regexContains(left: Expr, pattern: Expr): RegexContains; + + /** + * @beta + * + * Creates an expression that checks if a string field matches a specified regular expression. + * + * ```typescript + * // Check if the 'email' field matches a valid email pattern + * regexMatch("email", "[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,}"); + * ``` + * + * @param left The name of the field containing the string. + * @param pattern The regular expression to use for the match. + * @return A new {@code Expr} representing the regular expression match. + */ + export function regexMatch(left: string, pattern: string): RegexMatch; + + /** + * @beta + * + * Creates an expression that checks if a string field matches a specified regular expression. + * + * ```typescript + * // Check if the 'email' field matches a valid email pattern + * regexMatch("email", Field.of("pattern")); + * ``` + * + * @param left The name of the field containing the string. + * @param pattern The regular expression to use for the match. + * @return A new {@code Expr} representing the regular expression match. + */ + export function regexMatch(left: string, pattern: Expr): RegexMatch; + + /** + * @beta + * + * Creates an expression that checks if a string expression matches a specified regular + * expression. + * + * ```typescript + * // Check if the 'email' field matches a valid email pattern + * regexMatch(Field.of("email"), "[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,}"); + * ``` + * + * @param left The expression representing the string to match against. + * @param pattern The regular expression to use for the match. + * @return A new {@code Expr} representing the regular expression match. + */ + export function regexMatch(left: Expr, pattern: string): RegexMatch; + + /** + * @beta + * + * Creates an expression that checks if a string expression matches a specified regular + * expression. + * + * ```typescript + * // Check if the 'email' field matches a valid email pattern + * regexMatch(Field.of("email"), Field.of("pattern")); + * ``` + * + * @param left The expression representing the string to match against. + * @param pattern The regular expression to use for the match. + * @return A new {@code Expr} representing the regular expression match. + */ + export function regexMatch(left: Expr, pattern: Expr): RegexMatch; + + /** + * @beta + * + * Creates an expression that checks if a field's value starts with a given prefix. + * + * ```typescript + * // Check if the 'name' field starts with "Mr." + * startsWith("name", "Mr."); + * ``` + * + * @param expr The field name to check. + * @param prefix The prefix to check for. + * @return A new {@code Expr} representing the 'starts with' comparison. + */ + export function startsWith(expr: string, prefix: string): StartsWith; + + /** + * @beta + * + * Creates an expression that checks if a field's value starts with a given prefix. + * + * ```typescript + * // Check if the 'fullName' field starts with the value of the 'firstName' field + * startsWith("fullName", Field.of("firstName")); + * ``` + * + * @param expr The field name to check. + * @param prefix The expression representing the prefix. + * @return A new {@code Expr} representing the 'starts with' comparison. + */ + export function startsWith(expr: string, prefix: Expr): StartsWith; + + /** + * @beta + * + * Creates an expression that checks if a string expression starts with a given prefix. + * + * ```typescript + * // Check if the result of concatenating 'firstName' and 'lastName' fields starts with "Mr." + * startsWith(Field.of("fullName"), "Mr."); + * ``` + * + * @param expr The expression to check. + * @param prefix The prefix to check for. + * @return A new {@code Expr} representing the 'starts with' comparison. + */ + export function startsWith(expr: Expr, prefix: string): StartsWith; + + /** + * @beta + * + * Creates an expression that checks if a string expression starts with a given prefix. + * + * ```typescript + * // Check if the result of concatenating 'firstName' and 'lastName' fields starts with "Mr." + * startsWith(Field.of("fullName"), Field.of("prefix")); + * ``` + * + * @param expr The expression to check. + * @param prefix The prefix to check for. + * @return A new {@code Expr} representing the 'starts with' comparison. + */ + export function startsWith(expr: Expr, prefix: Expr): StartsWith; + + /** + * @beta + * + * Creates an expression that checks if a field's value ends with a given postfix. + * + * ```typescript + * // Check if the 'filename' field ends with ".txt" + * endsWith("filename", ".txt"); + * ``` + * + * @param expr The field name to check. + * @param suffix The postfix to check for. + * @return A new {@code Expr} representing the 'ends with' comparison. + */ + export function endsWith(expr: string, suffix: string): EndsWith; + + /** + * @beta + * + * Creates an expression that checks if a field's value ends with a given postfix. + * + * ```typescript + * // Check if the 'url' field ends with the value of the 'extension' field + * endsWith("url", Field.of("extension")); + * ``` + * + * @param expr The field name to check. + * @param suffix The expression representing the postfix. + * @return A new {@code Expr} representing the 'ends with' comparison. + */ + export function endsWith(expr: string, suffix: Expr): EndsWith; + + /** + * @beta + * + * Creates an expression that checks if a string expression ends with a given postfix. + * + * ```typescript + * // Check if the result of concatenating 'firstName' and 'lastName' fields ends with "Jr." + * endsWith(Field.of("fullName"), "Jr."); + * ``` + * + * @param expr The expression to check. + * @param suffix The postfix to check for. + * @return A new {@code Expr} representing the 'ends with' comparison. + */ + export function endsWith(expr: Expr, suffix: string): EndsWith; + + /** + * @beta + * + * Creates an expression that checks if a string expression ends with a given postfix. + * + * ```typescript + * // Check if the result of concatenating 'firstName' and 'lastName' fields ends with "Jr." + * endsWith(Field.of("fullName"), Constant.of("Jr.")); + * ``` + * + * @param expr The expression to check. + * @param suffix The postfix to check for. + * @return A new {@code Expr} representing the 'ends with' comparison. + */ + export function endsWith(expr: Expr, suffix: Expr): EndsWith; + + /** + * @beta + * + * Creates an expression that converts a string field to lowercase. + * + * ```typescript + * // Convert the 'name' field to lowercase + * toLowercase("name"); + * ``` + * + * @param expr The name of the field containing the string. + * @return A new {@code Expr} representing the lowercase string. + */ + export function toLowercase(expr: string): ToLowercase; + + /** + * @beta + * + * Creates an expression that converts a string expression to lowercase. + * + * ```typescript + * // Convert the 'name' field to lowercase + * toLowercase(Field.of("name")); + * ``` + * + * @param expr The expression representing the string to convert to lowercase. + * @return A new {@code Expr} representing the lowercase string. + */ + export function toLowercase(expr: Expr): ToLowercase; + + /** + * @beta + * + * Creates an expression that converts a string field to uppercase. + * + * ```typescript + * // Convert the 'title' field to uppercase + * toUppercase("title"); + * ``` + * + * @param expr The name of the field containing the string. + * @return A new {@code Expr} representing the uppercase string. + */ + export function toUppercase(expr: string): ToUppercase; + + /** + * @beta + * + * Creates an expression that converts a string expression to uppercase. + * + * ```typescript + * // Convert the 'title' field to uppercase + * toUppercase(Field.of("title")); + * ``` + * + * @param expr The expression representing the string to convert to uppercase. + * @return A new {@code Expr} representing the uppercase string. + */ + export function toUppercase(expr: Expr): ToUppercase; + + /** + * @beta + * + * Creates an expression that removes leading and trailing whitespace from a string field. + * + * ```typescript + * // Trim whitespace from the 'userInput' field + * trim("userInput"); + * ``` + * + * @param expr The name of the field containing the string. + * @return A new {@code Expr} representing the trimmed string. + */ + export function trim(expr: string): Trim; + + /** + * @beta + * + * Creates an expression that removes leading and trailing whitespace from a string expression. + * + * ```typescript + * // Trim whitespace from the 'userInput' field + * trim(Field.of("userInput")); + * ``` + * + * @param expr The expression representing the string to trim. + * @return A new {@code Expr} representing the trimmed string. + */ + export function trim(expr: Expr): Trim; + + /** + * @beta + * + * Creates an expression that concatenates string functions, fields or constants together. + * + * ```typescript + * // Combine the 'firstName', " ", and 'lastName' fields into a single string + * strConcat("firstName", " ", Field.of("lastName")); + * ``` + * + * @param first The field name containing the initial string value. + * @param elements The expressions (typically strings) to concatenate. + * @return A new {@code Expr} representing the concatenated string. + */ + export function strConcat( + first: string, + ...elements: (Expr | string)[] + ): StrConcat; + + /** + * @beta + * Creates an expression that concatenates string expressions together. + * + * ```typescript + * // Combine the 'firstName', " ", and 'lastName' fields into a single string + * strConcat(Field.of("firstName"), " ", Field.of("lastName")); + * ``` + * + * @param first The initial string expression to concatenate to. + * @param elements The expressions (typically strings) to concatenate. + * @return A new {@code Expr} representing the concatenated string. + */ + export function strConcat( + first: Expr, + ...elements: (Expr | string)[] + ): StrConcat; + + /** + * @beta + * + * Accesses a value from a map (object) field using the provided key. + * + * ```typescript + * // Get the 'city' value from the 'address' map field + * mapGet("address", "city"); + * ``` + * + * @param mapField The field name of the map field. + * @param subField The key to access in the map. + * @return A new {@code Expr} representing the value associated with the given key in the map. + */ + export function mapGet(mapField: string, subField: string): MapGet; + + /** + * @beta + * + * Accesses a value from a map (object) expression using the provided key. + * + * ```typescript + * // Get the 'city' value from the 'address' map field + * mapGet(Field.of("address"), "city"); + * ``` + * + * @param mapExpr The expression representing the map. + * @param subField The key to access in the map. + * @return A new {@code Expr} representing the value associated with the given key in the map. + */ + export function mapGet(mapExpr: Expr, subField: string): MapGet; + + /** + * @beta + * + * Creates an aggregation that counts the total number of stage inputs. + * + * ```typescript + * // Count the total number of users + * countAll().as("totalUsers"); + * ``` + * + * @return A new {@code Accumulator} representing the 'countAll' aggregation. + */ + export function countAll(): Count; + + /** + * @beta + * + * Creates an aggregation that counts the number of stage inputs with valid evaluations of the + * provided expression. + * + * ```typescript + * // Count the number of items where the price is greater than 10 + * count(Field.of("price").gt(10)).as("expensiveItemCount"); + * ``` + * + * @param value The expression to count. + * @return A new {@code Accumulator} representing the 'count' aggregation. + */ + export function count(value: Expr): Count; + + /** + * Creates an aggregation that counts the number of stage inputs with valid evaluations of the + * provided field. + * + * ```typescript + * // Count the total number of products + * count("productId").as("totalProducts"); + * ``` + * + * @param value The name of the field to count. + * @return A new {@code Accumulator} representing the 'count' aggregation. + */ + export function count(value: string): Count; + + /** + * @beta + * + * Creates an aggregation that calculates the sum of values from an expression across multiple + * stage inputs. + * + * ```typescript + * // Calculate the total revenue from a set of orders + * sum(Field.of("orderAmount")).as("totalRevenue"); + * ``` + * + * @param value The expression to sum up. + * @return A new {@code Accumulator} representing the 'sum' aggregation. + */ + export function sum(value: Expr): Sum; + + /** + * @beta + * + * Creates an aggregation that calculates the sum of a field's values across multiple stage + * inputs. + * + * ```typescript + * // Calculate the total revenue from a set of orders + * sum("orderAmount").as("totalRevenue"); + * ``` + * + * @param value The name of the field containing numeric values to sum up. + * @return A new {@code Accumulator} representing the 'sum' aggregation. + */ + export function sum(value: string): Sum; + + /** + * @beta + * + * Creates an aggregation that calculates the average (mean) of values from an expression across + * multiple stage inputs. + * + * ```typescript + * // Calculate the average age of users + * avg(Field.of("age")).as("averageAge"); + * ``` + * + * @param value The expression representing the values to average. + * @return A new {@code Accumulator} representing the 'avg' aggregation. + */ + export function avg(value: Expr): Avg; + + /** + * @beta + * + * Creates an aggregation that calculates the average (mean) of a field's values across multiple + * stage inputs. + * + * ```typescript + * // Calculate the average age of users + * avg("age").as("averageAge"); + * ``` + * + * @param value The name of the field containing numeric values to average. + * @return A new {@code Accumulator} representing the 'avg' aggregation. + */ + export function avg(value: string): Avg; + + /** + * @beta + * + * Creates an aggregation that finds the minimum value of an expression across multiple stage + * inputs. + * + * ```typescript + * // Find the lowest price of all products + * min(Field.of("price")).as("lowestPrice"); + * ``` + * + * @param value The expression to find the minimum value of. + * @return A new {@code Accumulator} representing the 'min' aggregation. + */ + export function min(value: Expr): Min; + + /** + * @beta + * + * Creates an aggregation that finds the minimum value of a field across multiple stage inputs. + * + * ```typescript + * // Find the lowest price of all products + * min("price").as("lowestPrice"); + * ``` + * + * @param value The name of the field to find the minimum value of. + * @return A new {@code Accumulator} representing the 'min' aggregation. + */ + export function min(value: string): Min; + + /** + * @beta + * + * Creates an aggregation that finds the maximum value of an expression across multiple stage + * inputs. + * + * ```typescript + * // Find the highest score in a leaderboard + * max(Field.of("score")).as("highestScore"); + * ``` + * + * @param value The expression to find the maximum value of. + * @return A new {@code Accumulator} representing the 'max' aggregation. + */ + export function max(value: Expr): Max; + + /** + * @beta + * + * Creates an aggregation that finds the maximum value of a field across multiple stage inputs. + * + * ```typescript + * // Find the highest score in a leaderboard + * max("score").as("highestScore"); + * ``` + * + * @param value The name of the field to find the maximum value of. + * @return A new {@code Accumulator} representing the 'max' aggregation. + */ + export function max(value: string): Max; + + /** + * @beta + * + * Calculates the Cosine distance between a field's vector value and a double array. + * + * ```typescript + * // Calculate the Cosine distance between the 'location' field and a target location + * cosineDistance("location", [37.7749, -122.4194]); + * ``` + * + * @param expr The name of the field containing the first vector. + * @param other The other vector (as an array of doubles) to compare against. + * @return A new {@code Expr} representing the Cosine distance between the two vectors. + */ + export function cosineDistance(expr: string, other: number[]): CosineDistance; + + /** + * @beta + * + * Calculates the Cosine distance between a field's vector value and a VectorValue. + * + * ```typescript + * // Calculate the Cosine distance between the 'location' field and a target location + * cosineDistance("location", new VectorValue([37.7749, -122.4194])); + * ``` + * + * @param expr The name of the field containing the first vector. + * @param other The other vector (as a VectorValue) to compare against. + * @return A new {@code Expr} representing the Cosine distance between the two vectors. + */ + export function cosineDistance( + expr: string, + other: VectorValue + ): CosineDistance; + + /** + * @beta + * + * Calculates the Cosine distance between a field's vector value and a vector expression. + * + * ```typescript + * // Calculate the cosine distance between the 'userVector' field and the 'itemVector' field + * cosineDistance("userVector", Field.of("itemVector")); + * ``` + * + * @param expr The name of the field containing the first vector. + * @param other The other vector (represented as an Expr) to compare against. + * @return A new {@code Expr} representing the cosine distance between the two vectors. + */ + export function cosineDistance(expr: string, other: Expr): CosineDistance; + + /** + * @beta + * + * Calculates the Cosine distance between a vector expression and a double array. + * + * ```typescript + * // Calculate the cosine distance between the 'location' field and a target location + * cosineDistance(Field.of("location"), [37.7749, -122.4194]); + * ``` + * + * @param expr The first vector (represented as an Expr) to compare against. + * @param other The other vector (as an array of doubles) to compare against. + * @return A new {@code Expr} representing the cosine distance between the two vectors. + */ + export function cosineDistance(expr: Expr, other: number[]): CosineDistance; + + /** + * @beta + * + * Calculates the Cosine distance between a vector expression and a VectorValue. + * + * ```typescript + * // Calculate the cosine distance between the 'location' field and a target location + * cosineDistance(Field.of("location"), new VectorValue([37.7749, -122.4194])); + * ``` + * + * @param expr The first vector (represented as an Expr) to compare against. + * @param other The other vector (as a VectorValue) to compare against. + * @return A new {@code Expr} representing the cosine distance between the two vectors. + */ + export function cosineDistance( + expr: Expr, + other: VectorValue + ): CosineDistance; + + /** + * @beta + * + * Calculates the Cosine distance between two vector expressions. + * + * ```typescript + * // Calculate the cosine distance between the 'userVector' field and the 'itemVector' field + * cosineDistance(Field.of("userVector"), Field.of("itemVector")); + * ``` + * + * @param expr The first vector (represented as an Expr) to compare against. + * @param other The other vector (represented as an Expr) to compare against. + * @return A new {@code Expr} representing the cosine distance between the two vectors. + */ + export function cosineDistance(expr: Expr, other: Expr): CosineDistance; + + /** + * @beta + * + * Calculates the dot product between a field's vector value and a double array. + * + * ```typescript + * // Calculate the dot product distance between a feature vector and a target vector + * dotProduct("features", [0.5, 0.8, 0.2]); + * ``` + * + * @param expr The name of the field containing the first vector. + * @param other The other vector (as an array of doubles) to calculate with. + * @return A new {@code Expr} representing the dot product between the two vectors. + */ + export function dotProduct(expr: string, other: number[]): DotProduct; + + /** + * @beta + * + * Calculates the dot product between a field's vector value and a VectorValue. + * + * ```typescript + * // Calculate the dot product distance between a feature vector and a target vector + * dotProduct("features", new VectorValue([0.5, 0.8, 0.2])); + * ``` + * + * @param expr The name of the field containing the first vector. + * @param other The other vector (as a VectorValue) to calculate with. + * @return A new {@code Expr} representing the dot product between the two vectors. + */ + export function dotProduct(expr: string, other: VectorValue): DotProduct; + + /** + * @beta + * + * Calculates the dot product between a field's vector value and a vector expression. + * + * ```typescript + * // Calculate the dot product distance between two document vectors: 'docVector1' and 'docVector2' + * dotProduct("docVector1", Field.of("docVector2")); + * ``` + * + * @param expr The name of the field containing the first vector. + * @param other The other vector (represented as an Expr) to calculate with. + * @return A new {@code Expr} representing the dot product between the two vectors. + */ + export function dotProduct(expr: string, other: Expr): DotProduct; + + /** + * @beta + * + * Calculates the dot product between a vector expression and a double array. + * + * ```typescript + * // Calculate the dot product between a feature vector and a target vector + * dotProduct(Field.of("features"), [0.5, 0.8, 0.2]); + * ``` + * + * @param expr The first vector (represented as an Expr) to calculate with. + * @param other The other vector (as an array of doubles) to calculate with. + * @return A new {@code Expr} representing the dot product between the two vectors. + */ + export function dotProduct(expr: Expr, other: number[]): DotProduct; + + /** + * @beta + * + * Calculates the dot product between a vector expression and a VectorValue. + * + * ```typescript + * // Calculate the dot product between a feature vector and a target vector + * dotProduct(Field.of("features"), new VectorValue([0.5, 0.8, 0.2])); + * ``` + * + * @param expr The first vector (represented as an Expr) to calculate with. + * @param other The other vector (as a VectorValue) to calculate with. + * @return A new {@code Expr} representing the dot product between the two vectors. + */ + export function dotProduct(expr: Expr, other: VectorValue): DotProduct; + + /** + * @beta + * + * Calculates the dot product between two vector expressions. + * + * ```typescript + * // Calculate the dot product between two document vectors: 'docVector1' and 'docVector2' + * dotProduct(Field.of("docVector1"), Field.of("docVector2")); + * ``` + * + * @param expr The first vector (represented as an Expr) to calculate with. + * @param other The other vector (represented as an Expr) to calculate with. + * @return A new {@code Expr} representing the dot product between the two vectors. + */ + export function dotProduct(expr: Expr, other: Expr): DotProduct; + + /** + * @beta + * + * Calculates the Euclidean distance between a field's vector value and a double array. + * + * ```typescript + * // Calculate the Euclidean distance between the 'location' field and a target location + * euclideanDistance("location", [37.7749, -122.4194]); + * ``` + * + * @param expr The name of the field containing the first vector. + * @param other The other vector (as an array of doubles) to compare against. + * @return A new {@code Expr} representing the Euclidean distance between the two vectors. + */ + export function euclideanDistance( + expr: string, + other: number[] + ): EuclideanDistance; + + /** + * @beta + * + * Calculates the Euclidean distance between a field's vector value and a VectorValue. + * + * ```typescript + * // Calculate the Euclidean distance between the 'location' field and a target location + * euclideanDistance("location", new VectorValue([37.7749, -122.4194])); + * ``` + * + * @param expr The name of the field containing the first vector. + * @param other The other vector (as a VectorValue) to compare against. + * @return A new {@code Expr} representing the Euclidean distance between the two vectors. + */ + export function euclideanDistance( + expr: string, + other: VectorValue + ): EuclideanDistance; + + /** + * @beta + * + * Calculates the Euclidean distance between a field's vector value and a vector expression. + * + * ```typescript + * // Calculate the Euclidean distance between two vector fields: 'pointA' and 'pointB' + * euclideanDistance("pointA", Field.of("pointB")); + * ``` + * + * @param expr The name of the field containing the first vector. + * @param other The other vector (represented as an Expr) to compare against. + * @return A new {@code Expr} representing the Euclidean distance between the two vectors. + */ + export function euclideanDistance( + expr: string, + other: Expr + ): EuclideanDistance; + + /** + * @beta + * + * Calculates the Euclidean distance between a vector expression and a double array. + * + * ```typescript + * // Calculate the Euclidean distance between the 'location' field and a target location + * + * euclideanDistance(Field.of("location"), [37.7749, -122.4194]); + * ``` + * + * @param expr The first vector (represented as an Expr) to compare against. + * @param other The other vector (as an array of doubles) to compare against. + * @return A new {@code Expr} representing the Euclidean distance between the two vectors. + */ + export function euclideanDistance( + expr: Expr, + other: number[] + ): EuclideanDistance; + + /** + * @beta + * + * Calculates the Euclidean distance between a vector expression and a VectorValue. + * + * ```typescript + * // Calculate the Euclidean distance between the 'location' field and a target location + * euclideanDistance(Field.of("location"), new VectorValue([37.7749, -122.4194])); + * ``` + * + * @param expr The first vector (represented as an Expr) to compare against. + * @param other The other vector (as a VectorValue) to compare against. + * @return A new {@code Expr} representing the Euclidean distance between the two vectors. + */ + export function euclideanDistance( + expr: Expr, + other: VectorValue + ): EuclideanDistance; + + /** + * @beta + * + * Calculates the Euclidean distance between two vector expressions. + * + * ```typescript + * // Calculate the Euclidean distance between two vector fields: 'pointA' and 'pointB' + * euclideanDistance(Field.of("pointA"), Field.of("pointB")); + * ``` + * + * @param expr The first vector (represented as an Expr) to compare against. + * @param other The other vector (represented as an Expr) to compare against. + * @return A new {@code Expr} representing the Euclidean distance between the two vectors. + */ + export function euclideanDistance(expr: Expr, other: Expr): EuclideanDistance; + + /** + * @beta + * + * Creates functions that work on the backend but do not exist in the SDK yet. + * + * ```typescript + * // Call a user defined function named "myFunc" with the arguments 10 and 20 + * // This is the same of the 'sum(Field.of("price"))', if it did not exist + * genericFunction("sum", [Field.of("price")]); + * ``` + * + * @param name The name of the user defined function. + * @param params The arguments to pass to the function. + * @return A new {@code Function} representing the function call. + */ + export function genericFunction(name: string, params: Expr[]): Function; + + /** + * @beta + * + * Creates an {@link Ordering} that sorts documents in ascending order based on this expression. + * + * ```typescript + * // Sort documents by the 'name' field in ascending order + * firestore.pipeline().collection("users") + * .sort(ascending(Field.of("name"))); + * ``` + * + * @param expr The expression to create an ascending ordering for. + * @return A new `Ordering` for ascending sorting. + */ + export function ascending(expr: Expr): Ordering; + + /** + * @beta + * + * Creates an {@link Ordering} that sorts documents in descending order based on this expression. + * + * ```typescript + * // Sort documents by the 'createdAt' field in descending order + * firestore.pipeline().collection("users") + * .sort(descending(Field.of("createdAt"))); + * ``` + * + * @param expr The expression to create a descending ordering for. + * @return A new `Ordering` for descending sorting. + */ + export function descending(expr: Expr): Ordering; + + /** + * @beta + * + * Represents an ordering criterion for sorting documents in a Firestore pipeline. + * + * You create `Ordering` instances using the `ascending` and `descending` helper functions. + */ + export class Ordering { + /** + * @param expr The expression to order by. + * @param direction The direction to order by. + */ + constructor(expr: Expr, direction: 'ascending' | 'descending'); + } + + /** + * @beta + */ + export interface Stage { + name: string; + } + + /** + * @beta + */ + export class AddFields implements Stage { + name: string; + } + + /** + * @beta + */ + export class Aggregate implements Stage { + name: string; + } + + /** + * @beta + */ + export class Distinct implements Stage { + name: string; + } + + /** + * @beta + */ + export class CollectionSource implements Stage { + name: string; + } + + /** + * @beta + */ + export class CollectionGroupSource implements Stage { + name: string; + } + + /** + * @beta + */ + export class DatabaseSource implements Stage { + name: string; + } + + /** + * @beta + */ + export class DocumentsSource implements Stage { + name: string; + + static of(refs: DocumentReference[]): DocumentsSource; + } + + /** + * @beta + */ + export class Where implements Stage { + name: string; + } + + /** + * @beta + */ + export interface FindNearestOptions { + limit: number; + distanceMeasure: 'euclidean' | 'cosine' | 'dot_product'; + distanceField?: string; + } + + /** + * @beta + */ + export class FindNearest implements Stage { + name: string; + } + + /** + * @beta + */ + export class Limit implements Stage { + name: string; + } + + /** + * @beta + */ + export class Offset implements Stage { + name: string; + } + + /** + * @beta + */ + export class Select implements Stage { + name: string; + } + + /** + * @beta + */ + export class Sort implements Stage { + name: string; + } + + /** + * @beta + */ + export class GenericStage implements Stage { + name: string; + } + + /** + * Represents the source of a Firestore {@link Pipeline}. + * @beta + */ + export class PipelineSource { + /** + * Specifies the source as a collection. + * + * @param collectionPath The path to the collection. + * @return A new Pipeline object with the collection as the source. + */ + collection(collectionPath: string): Pipeline; + + /** + * Specifies the source as a collection group. + * + * @param collectionId The ID of the collection group. + * @return A new Pipeline object with the collection group as the source. + */ + collectionGroup(collectionId: string): Pipeline; + + /** + * Specifies the source as a database. + * + * @return A new Pipeline object with the database as the source. + */ + database(): Pipeline; + + /** + * Specifies the source as a set of documents. + * + * @param docs The document references. + * @return A new Pipeline object with the documents as the source. + */ + documents(docs: DocumentReference[]): Pipeline; + } + + /** + * @beta + * + * The Pipeline class provides a flexible and expressive framework for building complex data + * transformation and query pipelines for Firestore. + * + * A pipeline takes data sources, such as Firestore collections or collection groups, and applies + * a series of stages that are chained together. Each stage takes the output from the previous stage + * (or the data source) and produces an output for the next stage (or as the final output of the + * pipeline). + * + * Expressions can be used within each stage to filter and transform data through the stage. + * + * NOTE: The chained stages do not prescribe exactly how Firestore will execute the pipeline. + * Instead, Firestore only guarantees that the result is the same as if the chained stages were + * executed in order. + * + * Usage Examples: + * + * ```typescript + * const db: Firestore; // Assumes a valid firestore instance. + * + * // Example 1: Select specific fields and rename 'rating' to 'bookRating' + * const results1 = await db.pipeline() + * .collection("books") + * .select("title", "author", Field.of("rating").as("bookRating")) + * .execute(); + * + * // Example 2: Filter documents where 'genre' is "Science Fiction" and 'published' is after 1950 + * const results2 = await db.pipeline() + * .collection("books") + * .where(and(Field.of("genre").eq("Science Fiction"), Field.of("published").gt(1950))) + * .execute(); + * + * // Example 3: Calculate the average rating of books published after 1980 + * const results3 = await db.pipeline() + * .collection("books") + * .where(Field.of("published").gt(1980)) + * .aggregate(avg(Field.of("rating")).as("averageRating")) + * .execute(); + * ``` + */ + export class Pipeline { + /** + * Adds new fields to outputs from previous stages. + * + * This stage allows you to compute values on-the-fly based on existing data from previous + * stages or constants. You can use this to create new fields or overwrite existing ones (if there + * is name overlaps). + * + * The added fields are defined using {@link Selectable}s, which can be: + * + * - {@link Field}: References an existing document field. + * - {@link Function}: Performs a calculation using functions like `add`, `multiply` with + * assigned aliases using {@link Expr#as}. + * + * Example: + * + * ```typescript + * firestore.pipeline().collection("books") + * .addFields( + * Field.of("rating").as("bookRating"), // Rename 'rating' to 'bookRating' + * add(5, Field.of("quantity")).as("totalCost") // Calculate 'totalCost' + * ); + * ``` + * + * @param fields The fields to add to the documents, specified as {@link Selectable}s. + * @return A new Pipeline object with this stage appended to the stage list. + */ + addFields(...fields: Selectable[]): Pipeline; + + /** + * Selects or creates a set of fields from the outputs of previous stages. + * + *

    The selected fields are defined using {@link Selectable} expressions, which can be: + * + *

      + *
    • {@code string}: Name of an existing field
    • + *
    • {@link Field}: References an existing field.
    • + *
    • {@link Function}: Represents the result of a function with an assigned alias name using + * {@link Expr#as}
    • + *
    + * + *

    If no selections are provided, the output of this stage is empty. Use {@link + * com.google.cloud.firestore.Pipeline#addFields} instead if only additions are + * desired. + * + *

    Example: + * + * ```typescript + * firestore.pipeline().collection("books") + * .select( + * "firstName", + * Field.of("lastName"), + * Field.of("address").toUppercase().as("upperAddress"), + * ); + * ``` + * + * @param selections The fields to include in the output documents, specified as {@link + * Selectable} expressions or {@code string} values representing field names. + * @return A new Pipeline object with this stage appended to the stage list. + */ + select(...fields: (Selectable | string)[]): Pipeline; + + /** + * Filters the documents from previous stages to only include those matching the specified {@link + * FilterCondition}. + * + *

    This stage allows you to apply conditions to the data, similar to a "WHERE" clause in SQL. + * You can filter documents based on their field values, using implementations of {@link + * FilterCondition}, typically including but not limited to: + * + *

      + *
    • field comparators: {@link Function#eq}, {@link Function#lt} (less than), {@link + * Function#gt} (greater than), etc.
    • + *
    • logical operators: {@link Function#and}, {@link Function#or}, {@link Function#not}, etc.
    • + *
    • advanced functions: {@link Function#regexMatch}, {@link + * Function#arrayContains}, etc.
    • + *
    + * + *

    Example: + * + * ```typescript + * firestore.pipeline().collection("books") + * .where( + * and( + * gt(Field.of("rating"), 4.0), // Filter for ratings greater than 4.0 + * Field.of("genre").eq("Science Fiction") // Equivalent to gt("genre", "Science Fiction") + * ) + * ); + * ``` + * + * @param condition The {@link FilterCondition} to apply. + * @return A new Pipeline object with this stage appended to the stage list. + */ + where(condition: FilterCondition & Expr): Pipeline; + + /** + * Skips the first `offset` number of documents from the results of previous stages. + * + *

    This stage is useful for implementing pagination in your pipelines, allowing you to retrieve + * results in chunks. It is typically used in conjunction with {@link #limit} to control the + * size of each page. + * + *

    Example: + * + * ```typescript + * // Retrieve the second page of 20 results + * firestore.pipeline().collection("books") + * .sort(Field.of("published").descending()) + * .offset(20) // Skip the first 20 results + * .limit(20); // Take the next 20 results + * ``` + * + * @param offset The number of documents to skip. + * @return A new Pipeline object with this stage appended to the stage list. + */ + offset(offset: number): Pipeline; + + /** + * Limits the maximum number of documents returned by previous stages to `limit`. + * + *

    This stage is particularly useful when you want to retrieve a controlled subset of data from + * a potentially large result set. It's often used for: + * + *

      + *
    • **Pagination:** In combination with {@link #offset} to retrieve specific pages of + * results.
    • + *
    • **Limiting Data Retrieval:** To prevent excessive data transfer and improve performance, + * especially when dealing with large collections.
    • + *
    + * + *

    Example: + * + * ```typescript + * // Limit the results to the top 10 highest-rated books + * firestore.pipeline().collection("books") + * .sort(Field.of("rating").descending()) + * .limit(10); + * ``` + * + * @param limit The maximum number of documents to return. + * @return A new Pipeline object with this stage appended to the stage list. + */ + limit(limit: number): Pipeline; + + /** + * Returns a set of distinct {@link Expr} values from the inputs to this stage. + * + *

    This stage run through the results from previous stages to include only results with unique + * combinations of {@link Expr} values ({@link Field}, {@link Function}, etc). + * + *

    The parameters to this stage are defined using {@link Selectable} expressions or {@code string}s: + * + *

      + *
    • {@code string}: Name of an existing field
    • + *
    • {@link Field}: References an existing document field.
    • + *
    • {@link Function}: Represents the result of a function with an assigned alias name using + * {@link Expr#as}
    • + *
    + * + *

    Example: + * + * ```typescript + * // Get a list of unique author names in uppercase and genre combinations. + * firestore.pipeline().collection("books") + * .distinct(toUppercase(Field.of("author")).as("authorName"), Field.of("genre"), "publishedAt") + * .select("authorName"); + * ``` + * + * @param selectables The {@link Selectable} expressions to consider when determining distinct + * value combinations or {@code string}s representing field names. + * @return A new {@code Pipeline} object with this stage appended to the stage list. + */ + distinct(...groups: (string | Selectable)[]): Pipeline; + + /** + * Performs aggregation operations on the documents from previous stages. + * + *

    This stage allows you to calculate aggregate values over a set of documents. You define the + * aggregations to perform using {@link AccumulatorTarget} expressions which are typically results of + * calling {@link Expr#as} on {@link Accumulator} instances. + * + *

    Example: + * + * ```typescript + * // Calculate the average rating and the total number of books + * firestore.pipeline().collection("books") + * .aggregate( + * Field.of("rating").avg().as("averageRating"), + * countAll().as("totalBooks") + * ); + * ``` + * + * @param accumulators The {@link AccumulatorTarget} expressions, each wrapping an {@link Accumulator} + * and provide a name for the accumulated results. + * @return A new Pipeline object with this stage appended to the stage list. + */ + aggregate(...accumulators: AccumulatorTarget[]): Pipeline; + /** + * Performs optionally grouped aggregation operations on the documents from previous stages. + * + *

    This stage allows you to calculate aggregate values over a set of documents, optionally + * grouped by one or more fields or functions. You can specify: + * + *

      + *
    • **Grouping Fields or Functions:** One or more fields or functions to group the documents + * by. For each distinct combination of values in these fields, a separate group is created. + * If no grouping fields are provided, a single group containing all documents is used. Not + * specifying groups is the same as putting the entire inputs into one group.
    • + *
    • **Accumulators:** One or more accumulation operations to perform within each group. These + * are defined using {@link AccumulatorTarget} expressions, which are typically created by + * calling {@link Expr#as} on {@link Accumulator} instances. Each aggregation + * calculates a value (e.g., sum, average, count) based on the documents within its group.
    • + *
    + * + *

    Example: + * + * ```typescript + * // Calculate the average rating for each genre. + * firestore.pipeline().collection("books") + * .aggregate({ + * accumulators: [avg(Field.of("rating")).as("avg_rating")] + * groups: ["genre"] + * }); + * ``` + * + * @param aggregate An {@link Aggregate} object that specifies the grouping fields (if any) and + * the aggregation operations to perform. + * @return A new {@code Pipeline} object with this stage appended to the stage list. + */ + aggregate(options: { + accumulators: AccumulatorTarget[]; + groups?: (string | Selectable)[]; + }): Pipeline; + + findNearest( + field: string, + vector: number[], + options: FindNearestOptions + ): Pipeline; + findNearest( + field: Field, + vector: FirebaseFirestore.VectorValue, + options: FindNearestOptions + ): Pipeline; + findNearest( + field: string | Field, + vector: FirebaseFirestore.VectorValue | number[], + options: FindNearestOptions + ): Pipeline; + + /** + * Sorts the documents from previous stages based on one or more {@link Ordering} criteria. + * + *

    This stage allows you to order the results of your pipeline. You can specify multiple {@link + * Ordering} instances to sort by multiple fields in ascending or descending order. If documents + * have the same value for a field used for sorting, the next specified ordering will be used. If + * all orderings result in equal comparison, the documents are considered equal and the order is + * unspecified. + * + *

    Example: + * + * ```typescript + * // Sort books by rating in descending order, and then by title in ascending order for books + * // with the same rating + * firestore.pipeline().collection("books") + * .sort( + * Ordering.of(Field.of("rating")).descending(), + * Ordering.of(Field.of("title")) // Ascending order is the default + * ); + * ``` + * + * @param orders One or more {@link Ordering} instances specifying the sorting criteria. + * @return A new {@code Pipeline} object with this stage appended to the stage list. + */ + sort(...orderings: Ordering[]): Pipeline; + sort(options: {orderings: Ordering[]}): Pipeline; + + /** + * Adds a generic stage to the pipeline. + * + *

    This method provides a flexible way to extend the pipeline's functionality by adding custom + * stages. Each generic stage is defined by a unique `name` and a set of `params` that control its + * behavior. + * + *

    Example (Assuming there is no "where" stage available in SDK): + * + * ```typescript + * // Assume we don't have a built-in "where" stage + * firestore.pipeline().collection("books") + * .genericStage("where", [Field.of("published").lt(1900)]) // Custom "where" stage + * .select("title", "author"); + * ``` + * + * @param name The unique name of the generic stage to add. + * @param params A list of parameters to configure the generic stage's behavior. + * @return A new {@code Pipeline} object with this stage appended to the stage list. + */ + genericStage(name: string, params: any[]): Pipeline; + withConverter(converter: null): Pipeline; + withConverter( + converter: FirestorePipelineConverter + ): Pipeline; + /** + * Executes this pipeline and returns a Promise to represent the asynchronous operation. + * + *

    The returned Promise can be used to track the progress of the pipeline execution + * and retrieve the results (or handle any errors) asynchronously. + * + *

    The pipeline results are returned as a list of {@link PipelineResult} objects. Each {@link + * PipelineResult} typically represents a single key/value map that has passed through all the + * stages of the pipeline, however this might differ depending on the stages involved in the + * pipeline. For example: + * + *

      + *
    • If there are no stages or only transformation stages, each {@link PipelineResult} + * represents a single document.
    • + *
    • If there is an aggregation, only a single {@link PipelineResult} is returned, + * representing the aggregated results over the entire dataset .
    • + *
    • If there is an aggregation stage with grouping, each {@link PipelineResult} represents a + * distinct group and its associated aggregated values.
    • + *
    + * + *

    Example: + * + * ```typescript + * const futureResults = await firestore.pipeline().collection("books") + * .where(gt(Field.of("rating"), 4.5)) + * .select("title", "author", "rating") + * .execute(); + * ``` + * + * @return A Promise representing the asynchronous pipeline execution. + */ + execute(): Promise>>; + + /** + * Executes this pipeline and streams the results as {@link PipelineResult}s. + * + * @returns {Stream.} A stream of + * PipelineResult. + * + * @example + * ```typescript + * firestore.pipeline().collection("books") + * .where(gt(Field.of("rating"), 4.5)) + * .select("title", "author", "rating") + * .stream() + * .on('data', (pipelineResult) => {}) + * .on('end', () => {}); + * ``` + */ + stream(): NodeJS.ReadableStream; + } + + /** + * @beta + * + * A PipelineResult contains data read from a Firestore Pipeline. The data can be extracted with the + * {@link #data()} or {@link #get(String)} methods. + * + *

    If the PipelineResult represents a non-document result, `ref` will return a undefined + * value. + */ + export class PipelineResult { + readonly executionTime: Timestamp; + readonly createTime: Timestamp | undefined; + readonly updateTime: Timestamp | undefined; + + /** + * The reference of the document, if it is a document; otherwise `undefined`. + */ + get ref(): DocumentReference | undefined; + + /** + * The ID of the document for which this PipelineResult contains data, if it is a document; otherwise `undefined`. + * + * @type {string} + * @readonly + * + */ + get id(): string | undefined; + + /** + * Retrieves all fields in the result as an object. Returns 'undefined' if + * the document doesn't exist. + * + * @returns {T|undefined} An object containing all fields in the document or + * 'undefined' if the document doesn't exist. + * + * @example + * ``` + * let p = firestore.pipeline().collection('col'); + * + * p.execute().then(results => { + * let data = results[0].data(); + * console.log(`Retrieved data: ${JSON.stringify(data)}`); + * }); + * ``` + */ + data(): AppModelType | undefined; + + /** + * Retrieves the field specified by `field`. + * + * @param {string|FieldPath} field The field path + * (e.g. 'foo' or 'foo.bar') to a specific field. + * @returns {*} The data at the specified field location or undefined if no + * such field exists. + * + * @example + * ``` + * let p = firestore.pipeline().collection('col'); + * + * p.execute().then(results => { + * let field = results[0].get('a.b'); + * console.log(`Retrieved field value: ${field}`); + * }); + * ``` + */ + // We deliberately use `any` in the external API to not impose type-checking + // on end users. + // eslint-disable-next-line @typescript-eslint/no-explicit-any + get(field: string | FieldPath): any; + + /** + * Returns true if the document's data and path in this `PipelineResult` is + * equal to the provided value. + * + * @param {*} other The value to compare against. + * @return {boolean} true if this `PipelineResult` is equal to the provided + * value. + */ + isEqual(other: PipelineResult): boolean; + } } declare module '@google-cloud/firestore' { From f0fdad5e58e10717dcc55a1a2cf7f9570373f489 Mon Sep 17 00:00:00 2001 From: Wu-Hui Date: Thu, 5 Sep 2024 14:41:19 -0400 Subject: [PATCH 13/60] FindNearest update --- dev/src/pipeline.ts | 28 ++++------------------------ dev/src/reference/vector-query.ts | 13 +++++++++---- dev/src/stage.ts | 27 +++++++++++++-------------- types/firestore.d.ts | 20 ++++---------------- 4 files changed, 30 insertions(+), 58 deletions(-) diff --git a/dev/src/pipeline.ts b/dev/src/pipeline.ts index c39680714..71c2a7b45 100644 --- a/dev/src/pipeline.ts +++ b/dev/src/pipeline.ts @@ -12,7 +12,6 @@ // See the License for the specific language governing permissions and // limitations under the License. -import {DocumentData} from '@google-cloud/firestore'; import * as firestore from '@google-cloud/firestore'; import * as deepEqual from 'fast-deep-equal'; import {google} from '../protos/firestore_v1_proto_api'; @@ -445,29 +444,10 @@ export class Pipeline { return new Pipeline(this.db, copy, this.converter); } - findNearest( - field: string, - vector: number[], - options: FindNearestOptions - ): Pipeline; - findNearest( - field: Field, - vector: FirebaseFirestore.VectorValue, - options: FindNearestOptions - ): Pipeline; - findNearest( - field: string | Field, - vector: FirebaseFirestore.VectorValue | number[], - options: FindNearestOptions - ): Pipeline; - findNearest( - field: string | Field, - vector: number[] | FirebaseFirestore.VectorValue, - options: FindNearestOptions - ): Pipeline { + findNearest(options: FindNearestOptions): Pipeline; + findNearest(options: FindNearestOptions): Pipeline { const copy = this.stages.map(s => s); - const fieldExpr = typeof field === 'string' ? Field.of(field) : field; - copy.push(new FindNearest(fieldExpr, vector, options)); + copy.push(new FindNearest(options)); return new Pipeline(this.db, copy); } @@ -822,7 +802,7 @@ export class PipelineResult // if a converter has been provided. if (!!this.converter && this.converter !== defaultPipelineConverter()) { return this.converter.fromFirestore( - new PipelineResult( + new PipelineResult( this._serializer, this.ref, this._fieldsProto, diff --git a/dev/src/reference/vector-query.ts b/dev/src/reference/vector-query.ts index 39bcc7c82..c1d783ea8 100644 --- a/dev/src/reference/vector-query.ts +++ b/dev/src/reference/vector-query.ts @@ -132,14 +132,19 @@ export class VectorQuery< } toPipeline(): Pipeline { - const options = { + const options: FindNearestOptions = { + field: Field.of(this.vectorField), + vectorValue: this.queryVector, limit: this.options.limit, - distanceMeasure: this.options.distanceMeasure.toLowerCase(), - } as FindNearestOptions; + distanceMeasure: this.options.distanceMeasure.toLowerCase() as + | 'cosine' + | 'euclidean' + | 'dot_product', + }; return this.query .pipeline() .where(Field.of(this.vectorField).exists()) - .findNearest(Field.of(this.vectorField), this.queryVector, options); + .findNearest(options); } _getResponse( diff --git a/dev/src/stage.ts b/dev/src/stage.ts index 31aeb19cd..f7be929ca 100644 --- a/dev/src/stage.ts +++ b/dev/src/stage.ts @@ -12,6 +12,7 @@ // See the License for the specific language governing permissions and // limitations under the License. +import * as firestore from '@google-cloud/firestore'; import * as protos from '../protos/firestore_v1_proto_api'; import api = protos.google.firestore.v1; @@ -179,8 +180,10 @@ export class Where implements Stage { * @beta */ export interface FindNearestOptions { - limit: number; + field: Field; + vectorValue: firestore.VectorValue | number[]; distanceMeasure: 'euclidean' | 'cosine' | 'dot_product'; + limit?: number; distanceField?: string; } @@ -190,18 +193,14 @@ export interface FindNearestOptions { export class FindNearest implements Stage { name = 'find_nearest'; - constructor( - private property: Field, - private vector: FirebaseFirestore.VectorValue | number[], - private options: FindNearestOptions - ) {} + constructor(private _options: FindNearestOptions) {} _toProto(serializer: Serializer): api.Pipeline.IStage { const options: {[k: string]: api.IValue} = { - limit: serializer.encodeValue(this.options.limit)!, + limit: serializer.encodeValue(this._options.limit)!, }; - if (this.options.distanceField) { - options.distance_field = Field.of(this.options.distanceField)._toProto( + if (this._options.distanceField) { + options.distance_field = Field.of(this._options.distanceField)._toProto( serializer ); } @@ -209,11 +208,11 @@ export class FindNearest implements Stage { return { name: this.name, args: [ - this.property._toProto(serializer), - this.vector instanceof VectorValue - ? serializer.encodeValue(this.vector)! - : serializer.encodeVector(this.vector as number[]), - serializer.encodeValue(this.options.distanceMeasure)!, + this._options.field._toProto(serializer), + this._options.vectorValue instanceof VectorValue + ? serializer.encodeValue(this._options.vectorValue)! + : serializer.encodeVector(this._options.vectorValue as number[]), + serializer.encodeValue(this._options.distanceMeasure)!, ], options, }; diff --git a/types/firestore.d.ts b/types/firestore.d.ts index dc35a6272..db4865253 100644 --- a/types/firestore.d.ts +++ b/types/firestore.d.ts @@ -7100,8 +7100,10 @@ declare namespace FirebaseFirestore { * @beta */ export interface FindNearestOptions { - limit: number; + field: Field; + vectorValue: VectorValue | number[]; distanceMeasure: 'euclidean' | 'cosine' | 'dot_product'; + limit?: number; distanceField?: string; } @@ -7460,21 +7462,7 @@ declare namespace FirebaseFirestore { groups?: (string | Selectable)[]; }): Pipeline; - findNearest( - field: string, - vector: number[], - options: FindNearestOptions - ): Pipeline; - findNearest( - field: Field, - vector: FirebaseFirestore.VectorValue, - options: FindNearestOptions - ): Pipeline; - findNearest( - field: string | Field, - vector: FirebaseFirestore.VectorValue | number[], - options: FindNearestOptions - ): Pipeline; + findNearest(options: FindNearestOptions): Pipeline; /** * Sorts the documents from previous stages based on one or more {@link Ordering} criteria. From f0ba8daf05123d837bba19638b6617334852d216 Mon Sep 17 00:00:00 2001 From: Wu-Hui Date: Tue, 10 Sep 2024 16:04:21 -0400 Subject: [PATCH 14/60] pipeline and stage dts fix done. expr to go. --- dev/src/expression.ts | 64 ++++++++++++++++++++-------------------- dev/src/pipeline-util.ts | 3 +- dev/src/pipeline.ts | 41 +++++++++++++------------ dev/src/stage.ts | 8 ++--- types/firestore.d.ts | 2 ++ 5 files changed, 60 insertions(+), 58 deletions(-) diff --git a/dev/src/expression.ts b/dev/src/expression.ts index b9f3b57f5..c894fcbeb 100644 --- a/dev/src/expression.ts +++ b/dev/src/expression.ts @@ -103,7 +103,7 @@ export type ExprType = * The `Expr` class provides a fluent API for building expressions. You can chain together * method calls to create complex expressions. */ -export abstract class Expr { +export abstract class Expr implements firestore.Expr{ /** * Creates an expression that adds this expression to another expression. * @@ -115,7 +115,7 @@ export abstract class Expr { * @param other The expression to add to this expression. * @return A new `Expr` representing the addition operation. */ - add(other: Expr): Add; + add(other: firestore.Expr): Add; /** * Creates an expression that adds this expression to a constant value. @@ -147,7 +147,7 @@ export abstract class Expr { * @param other The expression to subtract from this expression. * @return A new `Expr` representing the subtraction operation. */ - subtract(other: Expr): Subtract; + subtract(other: firestore.Expr): Subtract; /** * Creates an expression that subtracts a constant value from this expression. @@ -179,7 +179,7 @@ export abstract class Expr { * @param other The expression to multiply by. * @return A new `Expr` representing the multiplication operation. */ - multiply(other: Expr): Multiply; + multiply(other: firestore.Expr): Multiply; /** * Creates an expression that multiplies this expression by a constant value. @@ -211,7 +211,7 @@ export abstract class Expr { * @param other The expression to divide by. * @return A new `Expr` representing the division operation. */ - divide(other: Expr): Divide; + divide(other: firestore.Expr): Divide; /** * Creates an expression that divides this expression by a constant value. @@ -243,7 +243,7 @@ export abstract class Expr { * @param other The expression to compare for equality. * @return A new `Expr` representing the equality comparison. */ - eq(other: Expr): Eq; + eq(other: firestore.Expr): Eq; /** * Creates an expression that checks if this expression is equal to a constant value. @@ -275,7 +275,7 @@ export abstract class Expr { * @param other The expression to compare for inequality. * @return A new `Expr` representing the inequality comparison. */ - neq(other: Expr): Neq; + neq(other: firestore.Expr): Neq; /** * Creates an expression that checks if this expression is not equal to a constant value. @@ -307,7 +307,7 @@ export abstract class Expr { * @param other The expression to compare for less than. * @return A new `Expr` representing the less than comparison. */ - lt(other: Expr): Lt; + lt(other: firestore.Expr): Lt; /** * Creates an expression that checks if this expression is less than a constant value. @@ -340,7 +340,7 @@ export abstract class Expr { * @param other The expression to compare for less than or equal to. * @return A new `Expr` representing the less than or equal to comparison. */ - lte(other: Expr): Lte; + lte(other: firestore.Expr): Lte; /** * Creates an expression that checks if this expression is less than or equal to a constant value. @@ -372,7 +372,7 @@ export abstract class Expr { * @param other The expression to compare for greater than. * @return A new `Expr` representing the greater than comparison. */ - gt(other: Expr): Gt; + gt(other: firestore.Expr): Gt; /** * Creates an expression that checks if this expression is greater than a constant value. @@ -405,7 +405,7 @@ export abstract class Expr { * @param other The expression to compare for greater than or equal to. * @return A new `Expr` representing the greater than or equal to comparison. */ - gte(other: Expr): Gte; + gte(other: firestore.Expr): Gte; /** * Creates an expression that checks if this expression is greater than or equal to a constant @@ -438,7 +438,7 @@ export abstract class Expr { * @param arrays The array expressions to concatenate. * @return A new `Expr` representing the concatenated array. */ - arrayConcat(arrays: Expr[]): ArrayConcat; + arrayConcat(arrays: firestore.Expr[]): ArrayConcat; /** * Creates an expression that concatenates an array expression with one or more other arrays. @@ -470,7 +470,7 @@ export abstract class Expr { * @param element The element to search for in the array. * @return A new `Expr` representing the 'array_contains' comparison. */ - arrayContains(element: Expr): ArrayContains; + arrayContains(element: firestore.Expr): ArrayContains; /** * Creates an expression that checks if an array contains a specific value. @@ -502,7 +502,7 @@ export abstract class Expr { * @param values The elements to check for in the array. * @return A new `Expr` representing the 'array_contains_all' comparison. */ - arrayContainsAll(...values: Expr[]): ArrayContainsAll; + arrayContainsAll(...values: firestore.Expr[]): ArrayContainsAll; /** * Creates an expression that checks if an array contains all the specified elements. @@ -534,7 +534,7 @@ export abstract class Expr { * @param values The elements to check for in the array. * @return A new `Expr` representing the 'array_contains_any' comparison. */ - arrayContainsAny(...values: Expr[]): ArrayContainsAny; + arrayContainsAny(...values: firestore.Expr[]): ArrayContainsAny; /** * Creates an expression that checks if an array contains any of the specified elements. @@ -616,7 +616,7 @@ export abstract class Expr { * @param others The values or expressions to check against. * @return A new `Expr` representing the 'IN' comparison. */ - in(...others: Expr[]): In; + in(...others: firestore.Expr[]): In; /** * Creates an expression that checks if this expression is equal to any of the provided values or @@ -704,8 +704,8 @@ export abstract class Expr { * @param pattern The pattern to search for. You can use "%" as a wildcard character. * @return A new `Expr` representing the 'like' comparison. */ - like(pattern: Expr): Like; - like(stringOrExpr: string | Expr): Like { + like(pattern: firestore.Expr): Like; + like(stringOrExpr: string | firestore.Expr): Like { if (stringOrExpr instanceof Expr) { return new Like(this, stringOrExpr); } @@ -738,8 +738,8 @@ export abstract class Expr { * @param pattern The regular expression to use for the search. * @return A new `Expr` representing the 'contains' comparison. */ - regexContains(pattern: Expr): RegexContains; - regexContains(stringOrExpr: string | Expr): RegexContains { + regexContains(pattern: firestore.Expr): RegexContains; + regexContains(stringOrExpr: string | firestore.Expr): RegexContains { if (stringOrExpr instanceof Expr) { return new RegexContains(this, stringOrExpr); } @@ -770,8 +770,8 @@ export abstract class Expr { * @param pattern The regular expression to use for the match. * @return A new `Expr` representing the regular expression match. */ - regexMatch(pattern: Expr): RegexMatch; - regexMatch(stringOrExpr: string | Expr): RegexMatch { + regexMatch(pattern: firestore.Expr): RegexMatch; + regexMatch(stringOrExpr: string | firestore.Expr): RegexMatch { if (stringOrExpr instanceof Expr) { return new RegexMatch(this, stringOrExpr); } @@ -803,8 +803,8 @@ export abstract class Expr { * @param prefix The prefix expression to check for. * @return A new `Expr` representing the 'starts with' comparison. */ - startsWith(prefix: Expr): StartsWith; - startsWith(stringOrExpr: string | Expr): StartsWith { + startsWith(prefix: firestore.Expr): StartsWith; + startsWith(stringOrExpr: string | firestore.Expr): StartsWith { if (stringOrExpr instanceof Expr) { return new StartsWith(this, stringOrExpr); } @@ -836,8 +836,8 @@ export abstract class Expr { * @param suffix The postfix expression to check for. * @return A new `Expr` representing the 'ends with' comparison. */ - endsWith(suffix: Expr): EndsWith; - endsWith(stringOrExpr: string | Expr): EndsWith { + endsWith(suffix: firestore.Expr): EndsWith; + endsWith(stringOrExpr: string | firestore.Expr): EndsWith { if (stringOrExpr instanceof Expr) { return new EndsWith(this, stringOrExpr); } @@ -1000,7 +1000,7 @@ export abstract class Expr { * @param other The other vector (represented as an Expr) to compare against. * @return A new `Expr` representing the cosine distance between the two vectors. */ - cosineDistance(other: Expr): CosineDistance; + cosineDistance(other: firestore.Expr): CosineDistance; /** * Calculates the Cosine distance between two vectors. * @@ -1025,7 +1025,7 @@ export abstract class Expr { * @return A new `Expr` representing the Cosine distance between the two vectors. */ cosineDistance(other: number[]): CosineDistance; - cosineDistance(other: Expr | VectorValue | number[]): CosineDistance { + cosineDistance(other: firestore.Expr | firestore.VectorValue | number[]): CosineDistance { if (other instanceof Expr) { return new CosineDistance(this, other); } else { @@ -1044,7 +1044,7 @@ export abstract class Expr { * @param other The other vector (as an array of numbers) to calculate with. * @return A new `Expr` representing the dot product between the two vectors. */ - dotProduct(other: Expr): DotProduct; + dotProduct(other: firestore.Expr): DotProduct; /** * Calculates the dot product between two vectors. @@ -1071,7 +1071,7 @@ export abstract class Expr { * @return A new `Expr` representing the dot product between the two vectors. */ dotProduct(other: number[]): DotProduct; - dotProduct(other: Expr | VectorValue | number[]): DotProduct { + dotProduct(other: firestore.Expr | firestore.VectorValue | number[]): DotProduct { if (other instanceof Expr) { return new DotProduct(this, other); } else { @@ -1090,7 +1090,7 @@ export abstract class Expr { * @param other The other vector (as an array of numbers) to calculate with. * @return A new `Expr` representing the Euclidean distance between the two vectors. */ - euclideanDistance(other: Expr): EuclideanDistance; + euclideanDistance(other: firestore.Expr): EuclideanDistance; /** * Calculates the Euclidean distance between two vectors. @@ -1117,7 +1117,7 @@ export abstract class Expr { * @return A new `Expr` representing the Euclidean distance between the two vectors. */ euclideanDistance(other: number[]): EuclideanDistance; - euclideanDistance(other: Expr | VectorValue | number[]): EuclideanDistance { + euclideanDistance(other: firestore.Expr | firestore.VectorValue | number[]): EuclideanDistance { if (other instanceof Expr) { return new EuclideanDistance(this, other); } else { diff --git a/dev/src/pipeline-util.ts b/dev/src/pipeline-util.ts index 866d90cc9..0da348da2 100644 --- a/dev/src/pipeline-util.ts +++ b/dev/src/pipeline-util.ts @@ -27,7 +27,7 @@ import { isNan, Field, not, - Constant, + Constant, AccumulatorTarget, ExprWithAlias, Accumulator, } from './expression'; import Firestore, {DocumentReference, Timestamp} from './index'; import {logger} from './logger'; @@ -47,6 +47,7 @@ import { requestTag, wrapError, } from './util'; +import {invalidArgumentMessage} from "./validate"; import api = protos.google.firestore.v1; /** diff --git a/dev/src/pipeline.ts b/dev/src/pipeline.ts index 71c2a7b45..1239458c0 100644 --- a/dev/src/pipeline.ts +++ b/dev/src/pipeline.ts @@ -50,19 +50,18 @@ import { Stage, Distinct, } from './stage'; -import {ApiMapValue, defaultConverter, defaultPipelineConverter} from './types'; +import {ApiMapValue, defaultPipelineConverter} from './types'; import * as protos from '../protos/firestore_v1_proto_api'; import api = protos.google.firestore.v1; import IStructuredPipeline = google.firestore.v1.IStructuredPipeline; import IStage = google.firestore.v1.Pipeline.IStage; -import {QueryCursor} from './reference/types'; import {isOptionalEqual} from './util'; /** * Represents the source of a Firestore {@link Pipeline}. * @beta */ -export class PipelineSource { +export class PipelineSource implements firestore.PipelineSource{ constructor(private db: Firestore) {} collection(collectionPath: string): Pipeline { @@ -124,7 +123,7 @@ export class PipelineSource { * .execute(); * ``` */ -export class Pipeline { +export class Pipeline implements firestore.Pipeline { constructor( private db: Firestore, private stages: Stage[], @@ -157,7 +156,7 @@ export class Pipeline { * @param fields The fields to add to the documents, specified as {@link Selectable}s. * @return A new Pipeline object with this stage appended to the stage list. */ - addFields(...fields: Selectable[]): Pipeline { + addFields(...fields: firestore.Selectable[]): Pipeline { const copy = this.stages.map(s => s); copy.push(new AddFields(this.selectablesToMap(fields))); return new Pipeline(this.db, copy, this.converter); @@ -194,9 +193,9 @@ export class Pipeline { * Selectable} expressions or {@code string} values representing field names. * @return A new Pipeline object with this stage appended to the stage list. */ - select(...fields: (Selectable | string)[]): Pipeline { + select(...selections: (firestore.Selectable | string)[]): Pipeline { const copy = this.stages.map(s => s); - copy.push(new Select(this.selectablesToMap(fields))); + copy.push(new Select(this.selectablesToMap(selections))); return new Pipeline(this.db, copy, this.converter); } @@ -253,7 +252,7 @@ export class Pipeline { * @param condition The {@link FilterCondition} to apply. * @return A new Pipeline object with this stage appended to the stage list. */ - where(condition: FilterCondition & Expr): Pipeline { + where(condition: FilterCondition & firestore.Expr): Pipeline { const copy = this.stages.map(s => s); copy.push(new Where(condition)); return new Pipeline(this.db, copy, this.converter); @@ -344,7 +343,7 @@ export class Pipeline { * value combinations or {@code string}s representing field names. * @return A new {@code Pipeline} object with this stage appended to the stage list. */ - distinct(...groups: (string | Selectable)[]): Pipeline { + distinct(...groups: (string | firestore.Selectable)[]): Pipeline { const copy = this.stages.map(s => s); copy.push(new Distinct(this.selectablesToMap(groups || []))); return new Pipeline(this.db, copy, this.converter); @@ -372,7 +371,7 @@ export class Pipeline { * and provide a name for the accumulated results. * @return A new Pipeline object with this stage appended to the stage list. */ - aggregate(...accumulators: AccumulatorTarget[]): Pipeline; + aggregate(...accumulators: firestore.AccumulatorTarget[]): Pipeline; /** * Performs optionally grouped aggregation operations on the documents from previous stages. * @@ -406,23 +405,23 @@ export class Pipeline { * @return A new {@code Pipeline} object with this stage appended to the stage list. */ aggregate(options: { - accumulators: AccumulatorTarget[]; + accumulators: firestore.AccumulatorTarget[]; groups?: (string | Selectable)[]; }): Pipeline; aggregate( optionsOrTarget: - | AccumulatorTarget - | {accumulators: AccumulatorTarget[]; groups?: (string | Selectable)[]}, - ...rest: AccumulatorTarget[] + | firestore.AccumulatorTarget + | {accumulators: firestore.AccumulatorTarget[]; groups?: (string | firestore.Selectable)[]}, + ...rest: firestore.AccumulatorTarget[] ): Pipeline { const copy = this.stages.map(s => s); if ('accumulators' in optionsOrTarget) { copy.push( new Aggregate( new Map( - optionsOrTarget.accumulators.map((target: AccumulatorTarget) => [ - target.alias, - target.expr, + optionsOrTarget.accumulators.map((target: firestore.AccumulatorTarget) => [ + (target as unknown as AccumulatorTarget).alias, + (target as unknown as AccumulatorTarget).expr, ]) ), this.selectablesToMap(optionsOrTarget.groups || []) @@ -433,8 +432,8 @@ export class Pipeline { new Aggregate( new Map( [optionsOrTarget, ...rest].map(target => [ - target.alias, - target.expr, + (target as unknown as AccumulatorTarget).alias, + (target as unknown as AccumulatorTarget).expr, ]) ), new Map() @@ -444,8 +443,8 @@ export class Pipeline { return new Pipeline(this.db, copy, this.converter); } - findNearest(options: FindNearestOptions): Pipeline; - findNearest(options: FindNearestOptions): Pipeline { + findNearest(options: firestore.FindNearestOptions): Pipeline; + findNearest(options: firestore.FindNearestOptions): Pipeline { const copy = this.stages.map(s => s); copy.push(new FindNearest(options)); return new Pipeline(this.db, copy); diff --git a/dev/src/stage.ts b/dev/src/stage.ts index f7be929ca..c498e20ae 100644 --- a/dev/src/stage.ts +++ b/dev/src/stage.ts @@ -166,12 +166,12 @@ export class DocumentsSource implements Stage { export class Where implements Stage { name = 'where'; - constructor(private condition: FilterCondition & Expr) {} + constructor(private condition: firestore.FilterCondition & firestore.Expr) {} _toProto(serializer: Serializer): api.Pipeline.IStage { return { name: this.name, - args: [this.condition._toProto(serializer)], + args: [(this.condition as unknown as Expr)._toProto(serializer)], }; } } @@ -180,7 +180,7 @@ export class Where implements Stage { * @beta */ export interface FindNearestOptions { - field: Field; + field: firestore.Field; vectorValue: firestore.VectorValue | number[]; distanceMeasure: 'euclidean' | 'cosine' | 'dot_product'; limit?: number; @@ -208,7 +208,7 @@ export class FindNearest implements Stage { return { name: this.name, args: [ - this._options.field._toProto(serializer), + (this._options.field as unknown as Field)._toProto(serializer), this._options.vectorValue instanceof VectorValue ? serializer.encodeValue(this._options.vectorValue)! : serializer.encodeVector(this._options.vectorValue as number[]), diff --git a/types/firestore.d.ts b/types/firestore.d.ts index db4865253..f44c9056b 100644 --- a/types/firestore.d.ts +++ b/types/firestore.d.ts @@ -549,6 +549,8 @@ declare namespace FirebaseFirestore { */ collectionGroup(collectionId: string): CollectionGroup; + pipeline(): PipelineSource; + /** * Retrieves multiple documents from Firestore. * From 38b39814340419c3f2e943347707d5369d6b896e Mon Sep 17 00:00:00 2001 From: Wu-Hui Date: Wed, 11 Sep 2024 16:50:49 -0400 Subject: [PATCH 15/60] fixing expression.ts type decl --- dev/src/expression.ts | 59 ++++++++++++++++++++------------ dev/src/index.ts | 68 +++++++++++++++++++++++++++++++++++++ dev/src/pipeline-util.ts | 7 ++-- dev/src/pipeline.ts | 33 ++++++++++++------ dev/system-test/pipeline.ts | 2 +- 5 files changed, 134 insertions(+), 35 deletions(-) diff --git a/dev/src/expression.ts b/dev/src/expression.ts index c894fcbeb..0a7117ae8 100644 --- a/dev/src/expression.ts +++ b/dev/src/expression.ts @@ -103,7 +103,7 @@ export type ExprType = * The `Expr` class provides a fluent API for building expressions. You can chain together * method calls to create complex expressions. */ -export abstract class Expr implements firestore.Expr{ +export abstract class Expr implements firestore.Expr { /** * Creates an expression that adds this expression to another expression. * @@ -570,8 +570,8 @@ export abstract class Expr implements firestore.Expr{ * @param filter The {@link FilterCondition} to apply to the array elements. * @return A new `Expr` representing the filtered array. */ - arrayFilter(filter: FilterExpr): ArrayFilter { - return new ArrayFilter(this, filter); + arrayFilter(filter: firestore.FilterExpr): ArrayFilter { + return new ArrayFilter(this, filter as unknown as FilterExpr); } /** @@ -709,7 +709,7 @@ export abstract class Expr implements firestore.Expr{ if (stringOrExpr instanceof Expr) { return new Like(this, stringOrExpr); } - return new Like(this, Constant.of(stringOrExpr)); + return new Like(this, Constant.of(stringOrExpr as string)); } /** @@ -743,7 +743,7 @@ export abstract class Expr implements firestore.Expr{ if (stringOrExpr instanceof Expr) { return new RegexContains(this, stringOrExpr); } - return new RegexContains(this, Constant.of(stringOrExpr)); + return new RegexContains(this, Constant.of(stringOrExpr as string)); } /** @@ -775,7 +775,7 @@ export abstract class Expr implements firestore.Expr{ if (stringOrExpr instanceof Expr) { return new RegexMatch(this, stringOrExpr); } - return new RegexMatch(this, Constant.of(stringOrExpr)); + return new RegexMatch(this, Constant.of(stringOrExpr as string)); } /** @@ -808,7 +808,7 @@ export abstract class Expr implements firestore.Expr{ if (stringOrExpr instanceof Expr) { return new StartsWith(this, stringOrExpr); } - return new StartsWith(this, Constant.of(stringOrExpr)); + return new StartsWith(this, Constant.of(stringOrExpr as string)); } /** @@ -841,7 +841,7 @@ export abstract class Expr implements firestore.Expr{ if (stringOrExpr instanceof Expr) { return new EndsWith(this, stringOrExpr); } - return new EndsWith(this, Constant.of(stringOrExpr)); + return new EndsWith(this, Constant.of(stringOrExpr as string)); } /** @@ -1025,11 +1025,16 @@ export abstract class Expr implements firestore.Expr{ * @return A new `Expr` representing the Cosine distance between the two vectors. */ cosineDistance(other: number[]): CosineDistance; - cosineDistance(other: firestore.Expr | firestore.VectorValue | number[]): CosineDistance { + cosineDistance( + other: firestore.Expr | firestore.VectorValue | number[] + ): CosineDistance { if (other instanceof Expr) { return new CosineDistance(this, other); } else { - return new CosineDistance(this, Constant.vector(other)); + return new CosineDistance( + this, + Constant.vector(other as VectorValue | number[]) + ); } } @@ -1071,11 +1076,16 @@ export abstract class Expr implements firestore.Expr{ * @return A new `Expr` representing the dot product between the two vectors. */ dotProduct(other: number[]): DotProduct; - dotProduct(other: firestore.Expr | firestore.VectorValue | number[]): DotProduct { + dotProduct( + other: firestore.Expr | firestore.VectorValue | number[] + ): DotProduct { if (other instanceof Expr) { return new DotProduct(this, other); } else { - return new DotProduct(this, Constant.vector(other)); + return new DotProduct( + this, + Constant.vector(other as VectorValue | number[]) + ); } } @@ -1117,11 +1127,16 @@ export abstract class Expr implements firestore.Expr{ * @return A new `Expr` representing the Euclidean distance between the two vectors. */ euclideanDistance(other: number[]): EuclideanDistance; - euclideanDistance(other: firestore.Expr | firestore.VectorValue | number[]): EuclideanDistance { + euclideanDistance( + other: firestore.Expr | firestore.VectorValue | number[] + ): EuclideanDistance { if (other instanceof Expr) { return new EuclideanDistance(this, other); } else { - return new EuclideanDistance(this, Constant.vector(other)); + return new EuclideanDistance( + this, + Constant.vector(other as VectorValue | number[]) + ); } } @@ -1264,9 +1279,9 @@ export class Field extends Expr implements Selectable { static of(name: string): Field; static of(path: firestore.FieldPath): Field; static of(nameOrPath: string | firestore.FieldPath): Field; - static of(pipeline: Pipeline, name: string): Field; + static of(pipeline: firestore.Pipeline, name: string): Field; static of( - pipelineOrName: Pipeline | string | firestore.FieldPath, + pipelineOrName: firestore.Pipeline | string | firestore.FieldPath, name?: string ): Field { if (typeof pipelineOrName === 'string') { @@ -1399,7 +1414,7 @@ export class Constant extends Expr { * @param value The GeoPoint value. * @return A new `Constant` instance. */ - static of(value: GeoPoint): Constant; + static of(value: firestore.GeoPoint): Constant; /** * Creates a `Constant` instance for a Timestamp value. @@ -1407,7 +1422,7 @@ export class Constant extends Expr { * @param value The Timestamp value. * @return A new `Constant` instance. */ - static of(value: Timestamp): Constant; + static of(value: firestore.Timestamp): Constant; /** * Creates a `Constant` instance for a Date value. @@ -1431,7 +1446,7 @@ export class Constant extends Expr { * @param value The DocumentReference value. * @return A new `Constant` instance. */ - static of(value: DocumentReference): Constant; + static of(value: firestore.DocumentReference): Constant; /** * Creates a `Constant` instance for a Firestore proto value. @@ -1463,7 +1478,7 @@ export class Constant extends Expr { * @param value The VectorValue value. * @return A new `Constant` instance. */ - static of(value: VectorValue): Constant; + static of(value: firestore.VectorValue): Constant; /** * Creates a `Constant` instance for a Firestore proto value. @@ -1487,11 +1502,11 @@ export class Constant extends Expr { * @param value The VectorValue value. * @return A new `Constant` instance. */ - static vector(value: Array | VectorValue): Constant { + static vector(value: Array | firestore.VectorValue): Constant { if (value instanceof VectorValue) { return new Constant(value); } else { - return new Constant(new VectorValue(value)); + return new Constant(new VectorValue(value as Array)); } } diff --git a/dev/src/index.ts b/dev/src/index.ts index 61982a432..25fc1390f 100644 --- a/dev/src/index.ts +++ b/dev/src/index.ts @@ -123,6 +123,74 @@ export type { ExplainMetrics, ExplainResults, } from './query-profile'; +export {Pipeline, PipelineResult, PipelineSource} from './pipeline'; +export type {FindNearestOptions} from './stage'; +export type { + FilterCondition, + FilterExpr, + AccumulatorTarget, + Accumulator, + Selectable, + SelectableExpr, +} from './expression'; +export { + Expr, + ExprWithAlias, + Field, + Fields, + Constant, + Function, + Ordering, + add, + subtract, + multiply, + divide, + eq, + neq, + lt, + lte, + gt, + gte, + arrayConcat, + arrayContains, + arrayContainsAny, + arrayContainsAll, + arrayFilter, + arrayLength, + arrayTransform, + arrayElement, + inAny, + notInAny, + and, + or, + xor, + ifFunction, + not, + exists, + isNan, + like, + regexContains, + regexMatch, + startsWith, + endsWith, + toLowercase, + toUppercase, + trim, + strConcat, + mapGet, + countAll, + count, + sum, + avg, + min, + max, + cosineDistance, + dotProduct, + euclideanDistance, + genericFunction, + ascending, + descending, +} from './expression'; const libVersion = require('../../package.json').version; setLibVersion(libVersion); diff --git a/dev/src/pipeline-util.ts b/dev/src/pipeline-util.ts index 0da348da2..59ebbcfad 100644 --- a/dev/src/pipeline-util.ts +++ b/dev/src/pipeline-util.ts @@ -27,7 +27,10 @@ import { isNan, Field, not, - Constant, AccumulatorTarget, ExprWithAlias, Accumulator, + Constant, + AccumulatorTarget, + ExprWithAlias, + Accumulator, } from './expression'; import Firestore, {DocumentReference, Timestamp} from './index'; import {logger} from './logger'; @@ -47,7 +50,7 @@ import { requestTag, wrapError, } from './util'; -import {invalidArgumentMessage} from "./validate"; +import {invalidArgumentMessage} from './validate'; import api = protos.google.firestore.v1; /** diff --git a/dev/src/pipeline.ts b/dev/src/pipeline.ts index 1239458c0..aec5790b6 100644 --- a/dev/src/pipeline.ts +++ b/dev/src/pipeline.ts @@ -61,7 +61,7 @@ import {isOptionalEqual} from './util'; * Represents the source of a Firestore {@link Pipeline}. * @beta */ -export class PipelineSource implements firestore.PipelineSource{ +export class PipelineSource implements firestore.PipelineSource { constructor(private db: Firestore) {} collection(collectionPath: string): Pipeline { @@ -123,7 +123,9 @@ export class PipelineSource implements firestore.PipelineSource{ * .execute(); * ``` */ -export class Pipeline implements firestore.Pipeline { +export class Pipeline + implements firestore.Pipeline +{ constructor( private db: Firestore, private stages: Stage[], @@ -193,7 +195,9 @@ export class Pipeline implements firestor * Selectable} expressions or {@code string} values representing field names. * @return A new Pipeline object with this stage appended to the stage list. */ - select(...selections: (firestore.Selectable | string)[]): Pipeline { + select( + ...selections: (firestore.Selectable | string)[] + ): Pipeline { const copy = this.stages.map(s => s); copy.push(new Select(this.selectablesToMap(selections))); return new Pipeline(this.db, copy, this.converter); @@ -343,7 +347,9 @@ export class Pipeline implements firestor * value combinations or {@code string}s representing field names. * @return A new {@code Pipeline} object with this stage appended to the stage list. */ - distinct(...groups: (string | firestore.Selectable)[]): Pipeline { + distinct( + ...groups: (string | firestore.Selectable)[] + ): Pipeline { const copy = this.stages.map(s => s); copy.push(new Distinct(this.selectablesToMap(groups || []))); return new Pipeline(this.db, copy, this.converter); @@ -371,7 +377,9 @@ export class Pipeline implements firestor * and provide a name for the accumulated results. * @return A new Pipeline object with this stage appended to the stage list. */ - aggregate(...accumulators: firestore.AccumulatorTarget[]): Pipeline; + aggregate( + ...accumulators: firestore.AccumulatorTarget[] + ): Pipeline; /** * Performs optionally grouped aggregation operations on the documents from previous stages. * @@ -411,7 +419,10 @@ export class Pipeline implements firestor aggregate( optionsOrTarget: | firestore.AccumulatorTarget - | {accumulators: firestore.AccumulatorTarget[]; groups?: (string | firestore.Selectable)[]}, + | { + accumulators: firestore.AccumulatorTarget[]; + groups?: (string | firestore.Selectable)[]; + }, ...rest: firestore.AccumulatorTarget[] ): Pipeline { const copy = this.stages.map(s => s); @@ -419,10 +430,12 @@ export class Pipeline implements firestor copy.push( new Aggregate( new Map( - optionsOrTarget.accumulators.map((target: firestore.AccumulatorTarget) => [ - (target as unknown as AccumulatorTarget).alias, - (target as unknown as AccumulatorTarget).expr, - ]) + optionsOrTarget.accumulators.map( + (target: firestore.AccumulatorTarget) => [ + (target as unknown as AccumulatorTarget).alias, + (target as unknown as AccumulatorTarget).expr, + ] + ) ), this.selectablesToMap(optionsOrTarget.groups || []) ) diff --git a/dev/system-test/pipeline.ts b/dev/system-test/pipeline.ts index 4af42e931..f143953bf 100644 --- a/dev/system-test/pipeline.ts +++ b/dev/system-test/pipeline.ts @@ -296,7 +296,7 @@ describe.only('Pipeline class', () => { it('returns group and accumulate results', async () => { const results = await randomCol .pipeline() - .where(lt('published', 1984)) + .where(lt(Field.of('published'), 1984)) .aggregate({ accumulators: [avg('rating').as('avg_rating')], groups: ['genre'], From 3aa8edd0be57573a29a2c308140ae5e589e68d67 Mon Sep 17 00:00:00 2001 From: Wu-Hui Date: Wed, 11 Sep 2024 19:47:35 -0400 Subject: [PATCH 16/60] length to strLength --- dev/src/expression.ts | 20 ++++++++++---------- dev/src/index.ts | 1 + dev/system-test/pipeline.ts | 2 +- types/firestore.d.ts | 14 +++++++------- 4 files changed, 19 insertions(+), 18 deletions(-) diff --git a/dev/src/expression.ts b/dev/src/expression.ts index 0a7117ae8..a55dbd776 100644 --- a/dev/src/expression.ts +++ b/dev/src/expression.ts @@ -671,13 +671,13 @@ export abstract class Expr implements firestore.Expr { * * ```typescript * // Get the length of the 'name' field - * Field.of("name").length(); + * Field.of("name").strLength(); * ``` * * @return A new `Expr` representing the length of the string. */ - length(): Length { - return new Length(this); + strLength(): StrLength { + return new StrLength(this); } /** @@ -1857,7 +1857,7 @@ class If extends Function implements FilterCondition { /** * @beta */ -class Length extends Function { +class StrLength extends Function { constructor(private expr: Expr) { super('length', [expr]); } @@ -3492,13 +3492,13 @@ export function isNan(value: Expr | string): IsNan { * * ```typescript * // Get the length of the 'name' field - * length("name"); + * strLength("name"); * ``` * * @param field The name of the field containing the string. * @return A new {@code Expr} representing the length of the string. */ -export function length(field: string): Length; +export function strLength(field: string): StrLength; /** * @beta @@ -3507,16 +3507,16 @@ export function length(field: string): Length; * * ```typescript * // Get the length of the 'name' field - * length(Field.of("name")); + * strLength(Field.of("name")); * ``` * * @param expr The expression representing the string to calculate the length of. * @return A new {@code Expr} representing the length of the string. */ -export function length(expr: Expr): Length; -export function length(value: Expr | string): Length { +export function strLength(expr: Expr): StrLength; +export function strLength(value: Expr | string): StrLength { const valueExpr = value instanceof Expr ? value : Field.of(value); - return new Length(valueExpr); + return new StrLength(valueExpr); } /** diff --git a/dev/src/index.ts b/dev/src/index.ts index 25fc1390f..e2ad0d76a 100644 --- a/dev/src/index.ts +++ b/dev/src/index.ts @@ -168,6 +168,7 @@ export { not, exists, isNan, + strLength, like, regexContains, regexMatch, diff --git a/dev/system-test/pipeline.ts b/dev/system-test/pipeline.ts index f143953bf..b3ef9b2b0 100644 --- a/dev/system-test/pipeline.ts +++ b/dev/system-test/pipeline.ts @@ -525,7 +525,7 @@ describe.only('Pipeline class', () => { it('testLength', async () => { const results = await randomCol .pipeline() - .select(Field.of('title').length().as('titleLength'), Field.of('title')) + .select(Field.of('title').strLength().as('titleLength'), Field.of('title')) .where(gt('titleLength', 20)) .execute(); expectResults( diff --git a/types/firestore.d.ts b/types/firestore.d.ts index f44c9056b..5e13aa930 100644 --- a/types/firestore.d.ts +++ b/types/firestore.d.ts @@ -3744,12 +3744,12 @@ declare namespace FirebaseFirestore { * * ```typescript * // Get the length of the 'name' field - * Field.of("name").length(); + * Field.of("name").strLength(); * ``` * * @return A new `Expr` representing the length of the string. */ - length(): Length; + strLength(): StrLength; /** * Creates an expression that performs a case-sensitive string comparison. @@ -4569,7 +4569,7 @@ declare namespace FirebaseFirestore { /** * @beta */ - export class Length extends Function {} + export class StrLength extends Function {} /** * @beta @@ -5979,13 +5979,13 @@ declare namespace FirebaseFirestore { * * ```typescript * // Get the length of the 'name' field - * length("name"); + * strLength("name"); * ``` * * @param field The name of the field containing the string. * @return A new {@code Expr} representing the length of the string. */ - export function length(field: string): Length; + export function strLength(field: string): StrLength; /** * @beta @@ -5994,13 +5994,13 @@ declare namespace FirebaseFirestore { * * ```typescript * // Get the length of the 'name' field - * length(Field.of("name")); + * strLength(Field.of("name")); * ``` * * @param expr The expression representing the string to calculate the length of. * @return A new {@code Expr} representing the length of the string. */ - export function length(expr: Expr): Length; + export function length(expr: Expr): StrLength; /** * @beta From c97ed975a2dbe6e8e041265e9450e66129e2c381 Mon Sep 17 00:00:00 2001 From: Wu-Hui Date: Thu, 12 Sep 2024 15:01:44 -0400 Subject: [PATCH 17/60] remove __path__ hack --- dev/src/expression.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/dev/src/expression.ts b/dev/src/expression.ts index a55dbd776..555d17bc0 100644 --- a/dev/src/expression.ts +++ b/dev/src/expression.ts @@ -1286,7 +1286,7 @@ export class Field extends Expr implements Selectable { ): Field { if (typeof pipelineOrName === 'string') { if (FieldPath.documentId().formattedName === pipelineOrName) { - return new Field(new FieldPath('__path__')); + return new Field(FieldPath.documentId()); } return new Field(FieldPath.fromArgument(pipelineOrName)); From 9116488c7b504d8250eeaf03cfd78d6f0df9c87c Mon Sep 17 00:00:00 2001 From: Wu-Hui Date: Wed, 25 Sep 2024 15:57:09 -0400 Subject: [PATCH 18/60] resync with expressions catelog --- dev/src/expression.ts | 2934 +++++++++++++++++++++++++++++------ dev/src/index.ts | 31 +- dev/system-test/pipeline.ts | 49 +- types/firestore.d.ts | 2694 +++++++++++++++++++++++++------- 4 files changed, 4619 insertions(+), 1089 deletions(-) diff --git a/dev/src/expression.ts b/dev/src/expression.ts index 555d17bc0..a35134c1e 100644 --- a/dev/src/expression.ts +++ b/dev/src/expression.ts @@ -18,13 +18,10 @@ import api = protos.google.firestore.v1; import * as firestore from '@google-cloud/firestore'; import {VectorValue} from './field-value'; -import {GeoPoint} from './geo-point'; import {FieldPath} from './path'; import {Pipeline} from './pipeline'; import {isFirestoreValue} from './pipeline-util'; -import {DocumentReference} from './reference/document-reference'; import {Serializer} from './serializer'; -import {Timestamp} from './timestamp'; /** * @beta @@ -232,6 +229,212 @@ export abstract class Expr implements firestore.Expr { return new Divide(this, Constant.of(other)); } + /** + * Creates an expression that calculates the modulo (remainder) of dividing this expression by another expression. + * + * ```typescript + * // Calculate the remainder of dividing the 'value' field by the 'divisor' field + * Field.of("value").mod(Field.of("divisor")); + * ``` + * + * @param other The expression to divide by. + * @return A new `Expr` representing the modulo operation. + */ + mod(other: firestore.Expr): Mod; + + /** + * Creates an expression that calculates the modulo (remainder) of dividing this expression by a constant value. + * + * ```typescript + * // Calculate the remainder of dividing the 'value' field by 10 + * Field.of("value").mod(10); + * ``` + * + * @param other The constant value to divide by. + * @return A new `Expr` representing the modulo operation. + */ + mod(other: any): Mod; + mod(other: any): Mod { + if (other instanceof Expr) { + return new Mod(this, other); + } + return new Mod(this, Constant.of(other)); + } + + /** + * Creates an expression that applies a bitwise AND operation between this expression and another expression. + * + * ```typescript + * // Calculate the bitwise AND of 'field1' and 'field2'. + * Field.of("field1").bitAnd(Field.of("field2")); + * ``` + * + * @param other The right operand expression. + * @return A new {@code Expr} representing the bitwise AND operation. + */ + bitAnd(other: firestore.Expr): BitAnd; + + /** + * Creates an expression that applies a bitwise AND operation between this expression and a constant value. + * + * ```typescript + * // Calculate the bitwise AND of 'field1' and 0xFF. + * Field.of("field1").bitAnd(0xFF); + * ``` + * + * @param other The right operand constant. + * @return A new {@code Expr} representing the bitwise AND operation. + */ + bitAnd(other: any): BitAnd; + bitAnd(other: any): BitAnd { + if (other instanceof Expr) { + return new BitAnd(this, other); + } + return new BitAnd(this, Constant.of(other)); + } + + /** + * Creates an expression that applies a bitwise OR operation between this expression and another expression. + * + * ```typescript + * // Calculate the bitwise OR of 'field1' and 'field2'. + * Field.of("field1").bitOr(Field.of("field2")); + * ``` + * + * @param other The right operand expression. + * @return A new {@code Expr} representing the bitwise OR operation. + */ + bitOr(other: firestore.Expr): BitOr; + + /** + * Creates an expression that applies a bitwise OR operation between this expression and a constant value. + * + * ```typescript + * // Calculate the bitwise OR of 'field1' and 0xFF. + * Field.of("field1").bitOr(0xFF); + * ``` + * + * @param other The right operand constant. + * @return A new {@code Expr} representing the bitwise OR operation. + */ + bitOr(other: any): BitOr; + bitOr(other: any): BitOr { + if (other instanceof Expr) { + return new BitOr(this, other); + } + return new BitOr(this, Constant.of(other)); + } + + /** + * Creates an expression that applies a bitwise XOR operation between this expression and another expression. + * + * ```typescript + * // Calculate the bitwise XOR of 'field1' and 'field2'. + * Field.of("field1").bitXor(Field.of("field2")); + * ``` + * + * @param other The right operand expression. + * @return A new {@code Expr} representing the bitwise XOR operation. + */ + bitXor(other: firestore.Expr): BitXor; + + /** + * Creates an expression that applies a bitwise XOR operation between this expression and a constant value. + * + * ```typescript + * // Calculate the bitwise XOR of 'field1' and 0xFF. + * Field.of("field1").bitXor(0xFF); + * ``` + * + * @param other The right operand constant. + * @return A new {@code Expr} representing the bitwise XOR operation. + */ + bitXor(other: any): BitXor; + bitXor(other: any): BitXor { + if (other instanceof Expr) { + return new BitXor(this, other); + } + return new BitXor(this, Constant.of(other)); + } + + /** + * Creates an expression that applies a bitwise NOT operation to this expression. + * + * ```typescript + * // Calculate the bitwise NOT of 'field1'. + * Field.of("field1").bitNot(); + * ``` + * + * @return A new {@code Expr} representing the bitwise NOT operation. + */ + bitNot(): BitNot { + return new BitNot(this); + } + + /** + * Creates an expression that applies a bitwise left shift operation between this expression and another expression. + * + * ```typescript + * // Calculate the bitwise left shift of 'field1' by 'field2' bits. + * Field.of("field1").bitLeftShift(Field.of("field2")); + * ``` + * + * @param other The right operand expression representing the number of bits to shift. + * @return A new {@code Expr} representing the bitwise left shift operation. + */ + bitLeftShift(other: firestore.Expr): BitLeftShift; + + /** + * Creates an expression that applies a bitwise left shift operation between this expression and a constant value. + * + * ```typescript + * // Calculate the bitwise left shift of 'field1' by 2 bits. + * Field.of("field1").bitLeftShift(2); + * ``` + * + * @param other The right operand constant representing the number of bits to shift. + * @return A new {@code Expr} representing the bitwise left shift operation. + */ + bitLeftShift(other: number): BitLeftShift; + bitLeftShift(other: firestore.Expr | number): BitLeftShift { + if (typeof other === 'number') { + return new BitLeftShift(this, Constant.of(other)); + } + return new BitLeftShift(this, other as Expr); + } + + /** + * Creates an expression that applies a bitwise right shift operation between this expression and another expression. + * + * ```typescript + * // Calculate the bitwise right shift of 'field1' by 'field2' bits. + * Field.of("field1").bitRightShift(Field.of("field2")); + * ``` + * + * @param other The right operand expression representing the number of bits to shift. + * @return A new {@code Expr} representing the bitwise right shift operation. + */ + bitRightShift(other: firestore.Expr): BitRightShift; + + /** + * Creates an expression that applies a bitwise right shift operation between this expression and a constant value. + * + * ```typescript + * // Calculate the bitwise right shift of 'field1' by 2 bits. + * Field.of("field1").bitRightShift(2); + * ``` + * + * @param other The right operand constant representing the number of bits to shift. + * @return A new {@code Expr} representing the bitwise right shift operation. + */ + bitRightShift(other: number): BitRightShift; + bitRightShift(other: firestore.Expr | number): BitRightShift { + if (typeof other === 'number') { + return new BitRightShift(this, Constant.of(other)); + } + return new BitRightShift(this, other as Expr); + } + /** * Creates an expression that checks if this expression is equal to another expression. * @@ -556,24 +759,6 @@ export abstract class Expr implements firestore.Expr { return new ArrayContainsAny(this, exprValues); } - /** - * Creates an expression that filters elements from an array using the given {@link - * FilterCondition} and returns the filtered elements as a new array. - * - * ```typescript - * // Get items from the 'inventoryPrices' array where the array item is greater than 0 - * // Note we use {@link Function#arrayElement} to represent array elements to construct a - * // filtering condition. - * Field.of("inventoryPrices").arrayFilter(arrayElement().gt(0)); - * ``` - * - * @param filter The {@link FilterCondition} to apply to the array elements. - * @return A new `Expr` representing the filtered array. - */ - arrayFilter(filter: firestore.FilterExpr): ArrayFilter { - return new ArrayFilter(this, filter as unknown as FilterExpr); - } - /** * Creates an expression that calculates the length of an array. * @@ -588,22 +773,6 @@ export abstract class Expr implements firestore.Expr { return new ArrayLength(this); } - /** - * Creates an expression that applies a transformation function to each element in an array and - * returns the new array as the result of the evaluation. - * - * ```typescript - * // Convert all strings in the 'names' array to uppercase - * Field.of("names").arrayTransform(arrayElement().toUppercase()); - * ``` - * - * @param transform The {@link Function} to apply to each array element. - * @return A new `Expr` representing the transformed array. - */ - arrayTransform(transform: Function): ArrayTransform { - return new ArrayTransform(this, transform); - } - /** * Creates an expression that checks if this expression is equal to any of the provided values or * expressions. @@ -667,17 +836,17 @@ export abstract class Expr implements firestore.Expr { } /** - * Creates an expression that calculates the length of a string. + * Creates an expression that calculates the character length of a string in UTF-8. * * ```typescript - * // Get the length of the 'name' field - * Field.of("name").strLength(); + * // Get the character length of the 'name' field in its UTF-8 form. + * Field.of("name").charLength(); * ``` * * @return A new `Expr` representing the length of the string. */ - strLength(): StrLength { - return new StrLength(this); + charLength(): CharLength { + return new CharLength(this); } /** @@ -706,10 +875,10 @@ export abstract class Expr implements firestore.Expr { */ like(pattern: firestore.Expr): Like; like(stringOrExpr: string | firestore.Expr): Like { - if (stringOrExpr instanceof Expr) { - return new Like(this, stringOrExpr); + if (typeof stringOrExpr === 'string') { + return new Like(this, Constant.of(stringOrExpr)); } - return new Like(this, Constant.of(stringOrExpr as string)); + return new Like(this, stringOrExpr as Expr); } /** @@ -740,10 +909,10 @@ export abstract class Expr implements firestore.Expr { */ regexContains(pattern: firestore.Expr): RegexContains; regexContains(stringOrExpr: string | firestore.Expr): RegexContains { - if (stringOrExpr instanceof Expr) { - return new RegexContains(this, stringOrExpr); + if (typeof stringOrExpr === 'string') { + return new RegexContains(this, Constant.of(stringOrExpr)); } - return new RegexContains(this, Constant.of(stringOrExpr as string)); + return new RegexContains(this, stringOrExpr as Expr); } /** @@ -772,10 +941,10 @@ export abstract class Expr implements firestore.Expr { */ regexMatch(pattern: firestore.Expr): RegexMatch; regexMatch(stringOrExpr: string | firestore.Expr): RegexMatch { - if (stringOrExpr instanceof Expr) { - return new RegexMatch(this, stringOrExpr); + if (typeof stringOrExpr === 'string') { + return new RegexMatch(this, Constant.of(stringOrExpr)); } - return new RegexMatch(this, Constant.of(stringOrExpr as string)); + return new RegexMatch(this, stringOrExpr as Expr); } /** @@ -805,10 +974,10 @@ export abstract class Expr implements firestore.Expr { */ startsWith(prefix: firestore.Expr): StartsWith; startsWith(stringOrExpr: string | firestore.Expr): StartsWith { - if (stringOrExpr instanceof Expr) { - return new StartsWith(this, stringOrExpr); + if (typeof stringOrExpr === 'string') { + return new StartsWith(this, Constant.of(stringOrExpr)); } - return new StartsWith(this, Constant.of(stringOrExpr as string)); + return new StartsWith(this, stringOrExpr as Expr); } /** @@ -838,10 +1007,10 @@ export abstract class Expr implements firestore.Expr { */ endsWith(suffix: firestore.Expr): EndsWith; endsWith(stringOrExpr: string | firestore.Expr): EndsWith { - if (stringOrExpr instanceof Expr) { - return new EndsWith(this, stringOrExpr); + if (typeof stringOrExpr === 'string') { + return new EndsWith(this, Constant.of(stringOrExpr)); } - return new EndsWith(this, Constant.of(stringOrExpr as string)); + return new EndsWith(this, stringOrExpr as Expr); } /** @@ -849,13 +1018,13 @@ export abstract class Expr implements firestore.Expr { * * ```typescript * // Convert the 'name' field to lowercase - * Field.of("name").toLowerCase(); + * Field.of("name").toLower(); * ``` * * @return A new `Expr` representing the lowercase string. */ - toLowercase(): ToLowercase { - return new ToLowercase(this); + toLower(): ToLower { + return new ToLower(this); } /** @@ -863,13 +1032,13 @@ export abstract class Expr implements firestore.Expr { * * ```typescript * // Convert the 'title' field to uppercase - * Field.of("title").toUpperCase(); + * Field.of("title").toUpper(); * ``` * * @return A new `Expr` representing the uppercase string. */ - toUppercase(): ToUppercase { - return new ToUppercase(this); + toUpper(): ToUpper { + return new ToUpper(this); } /** @@ -897,11 +1066,131 @@ export abstract class Expr implements firestore.Expr { * @param elements The expressions (typically strings) to concatenate. * @return A new `Expr` representing the concatenated string. */ - strConcat(...elements: (string | Expr)[]): StrConcat { - const exprs = elements.map(e => (e instanceof Expr ? e : Constant.of(e))); + strConcat(...elements: (string | firestore.Expr)[]): StrConcat { + const exprs = elements.map(e => + typeof e === 'string' ? Constant.of(e) : (e as Expr) + ); return new StrConcat(this, exprs); } + /** + * Creates an expression that reverses this string expression. + * + * ```typescript + * // Reverse the value of the 'myString' field. + * Field.of("myString").reverse(); + * ``` + * + * @return A new {@code Expr} representing the reversed string. + */ + reverse(): Reverse { + return new Reverse(this); + } + + /** + * Creates an expression that replaces the first occurrence of a substring within this string expression with another substring. + * + * ```typescript + * // Replace the first occurrence of "hello" with "hi" in the 'message' field + * Field.of("message").replaceFirst("hello", "hi"); + * ``` + * + * @param find The substring to search for. + * @param replace The substring to replace the first occurrence of 'find' with. + * @return A new {@code Expr} representing the string with the first occurrence replaced. + */ + replaceFirst(find: string, replace: string): firestore.ReplaceFirst; + + /** + * Creates an expression that replaces the first occurrence of a substring within this string expression with another substring, + * where the substring to find and the replacement substring are specified by expressions. + * + * ```typescript + * // Replace the first occurrence of the value in 'findField' with the value in 'replaceField' in the 'message' field + * Field.of("message").replaceFirst(Field.of("findField"), Field.of("replaceField")); + * ``` + * + * @param find The expression representing the substring to search for. + * @param replace The expression representing the substring to replace the first occurrence of 'find' with. + * @return A new {@code Expr} representing the string with the first occurrence replaced. + */ + replaceFirst( + find: firestore.Expr, + replace: firestore.Expr + ): firestore.ReplaceFirst; + replaceFirst( + find: firestore.Expr | string, + replace: firestore.Expr | string + ): firestore.ReplaceFirst { + const normalizedFind = typeof find === 'string' ? Constant.of(find) : find; + const normalizedReplace = + typeof replace === 'string' ? Constant.of(replace) : replace; + return new ReplaceFirst( + this, + normalizedFind as Expr, + normalizedReplace as Expr + ); + } + + /** + * Creates an expression that replaces all occurrences of a substring within this string expression with another substring. + * + * ```typescript + * // Replace all occurrences of "hello" with "hi" in the 'message' field + * Field.of("message").replaceAll("hello", "hi"); + * ``` + * + * @param find The substring to search for. + * @param replace The substring to replace all occurrences of 'find' with. + * @return A new {@code Expr} representing the string with all occurrences replaced. + */ + replaceAll(find: string, replace: string): firestore.ReplaceAll; + + /** + * Creates an expression that replaces all occurrences of a substring within this string expression with another substring, + * where the substring to find and the replacement substring are specified by expressions. + * + * ```typescript + * // Replace all occurrences of the value in 'findField' with the value in 'replaceField' in the 'message' field + * Field.of("message").replaceAll(Field.of("findField"), Field.of("replaceField")); + * ``` + * + * @param find The expression representing the substring to search for. + * @param replace The expression representing the substring to replace all occurrences of 'find' with. + * @return A new {@code Expr} representing the string with all occurrences replaced. + */ + replaceAll( + find: firestore.Expr, + replace: firestore.Expr + ): firestore.ReplaceAll; + replaceAll( + find: firestore.Expr | string, + replace: firestore.Expr | string + ): firestore.ReplaceAll { + const normalizedFind = typeof find === 'string' ? Constant.of(find) : find; + const normalizedReplace = + typeof replace === 'string' ? Constant.of(replace) : replace; + return new ReplaceAll( + this, + normalizedFind as Expr, + normalizedReplace as Expr + ); + } + + /** + * Creates an expression that calculates the length of this string expression in bytes. + * + * ```typescript + * // Calculate the length of the 'myString' field in bytes. + * Field.of("myString").byteLength(); + * ``` + * + * @return A new {@code Expr} representing the length of the string in bytes. + */ + byteLength(): firestore.ByteLength { + return new ByteLength(this); + } + /** * Accesses a value from a map (object) field using the provided key. * @@ -989,6 +1278,84 @@ export abstract class Expr implements firestore.Expr { return new Max(this, false); } + /** + * Creates an expression that returns the larger value between this expression and another expression, based on Firestore's value type ordering. + * + * ```typescript + * // Returns the larger value between the 'timestamp' field and the current timestamp. + * Field.of("timestamp").logicalMax(Function.currentTimestamp()); + * ``` + * + * @param other The expression to compare with. + * @return A new {@code Expr} representing the logical max operation. + */ + logicalMax(other: firestore.Expr): firestore.LogicalMax; + + /** + * Creates an expression that returns the larger value between this expression and a constant value, based on Firestore's value type ordering. + * + * ```typescript + * // Returns the larger value between the 'value' field and 10. + * Field.of("value").logicalMax(10); + * ``` + * + * @param other The constant value to compare with. + * @return A new {@code Expr} representing the logical max operation. + */ + logicalMax(other: any): firestore.LogicalMax; + logicalMax(other: any): firestore.LogicalMax { + if (other instanceof firestore.Expr) { + return new LogicalMax(this, other as Expr); + } + return new LogicalMax(this, Constant.of(other)); + } + + /** + * Creates an expression that returns the smaller value between this expression and another expression, based on Firestore's value type ordering. + * + * ```typescript + * // Returns the smaller value between the 'timestamp' field and the current timestamp. + * Field.of("timestamp").logicalMin(Function.currentTimestamp()); + * ``` + * + * @param other The expression to compare with. + * @return A new {@code Expr} representing the logical min operation. + */ + logicalMin(other: firestore.Expr): firestore.LogicalMin; + + /** + * Creates an expression that returns the smaller value between this expression and a constant value, based on Firestore's value type ordering. + * + * ```typescript + * // Returns the smaller value between the 'value' field and 10. + * Field.of("value").logicalMin(10); + * ``` + * + * @param other The constant value to compare with. + * @return A new {@code Expr} representing the logical min operation. + */ + logicalMin(other: any): firestore.LogicalMin; + logicalMin(other: any): firestore.LogicalMin { + if (other instanceof firestore.Expr) { + return new LogicalMin(this, other as Expr); + } + return new LogicalMin(this, Constant.of(other)); + } + + /** + * Creates an expression that calculates the length (number of dimensions) of this Firestore Vector expression. + * + * ```typescript + * // Get the vector length (dimension) of the field 'embedding'. + * Field.of("embedding").vectorLength(); + * ``` + * + * @return A new {@code Expr} representing the length of the vector. + */ + vectorLength(): VectorLength { + return new VectorLength(this); + } + /** * Calculates the cosine distance between two vectors. * @@ -1028,8 +1395,8 @@ export abstract class Expr implements firestore.Expr { cosineDistance( other: firestore.Expr | firestore.VectorValue | number[] ): CosineDistance { - if (other instanceof Expr) { - return new CosineDistance(this, other); + if (other instanceof firestore.Expr) { + return new CosineDistance(this, other as Expr); } else { return new CosineDistance( this, @@ -1079,8 +1446,8 @@ export abstract class Expr implements firestore.Expr { dotProduct( other: firestore.Expr | firestore.VectorValue | number[] ): DotProduct { - if (other instanceof Expr) { - return new DotProduct(this, other); + if (other instanceof firestore.Expr) { + return new DotProduct(this, other as Expr); } else { return new DotProduct( this, @@ -1130,8 +1497,8 @@ export abstract class Expr implements firestore.Expr { euclideanDistance( other: firestore.Expr | firestore.VectorValue | number[] ): EuclideanDistance { - if (other instanceof Expr) { - return new EuclideanDistance(this, other); + if (other instanceof firestore.Expr) { + return new EuclideanDistance(this, other as Expr); } else { return new EuclideanDistance( this, @@ -1141,61 +1508,256 @@ export abstract class Expr implements firestore.Expr { } /** - * Creates an {@link Ordering} that sorts documents in ascending order based on this expression. + * 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. * * ```typescript - * // Sort documents by the 'name' field in ascending order - * firestore.pipeline().collection("users") - * .sort(Field.of("name").ascending()); + * // Interpret the 'microseconds' field as microseconds since epoch. + * Field.of("microseconds").unixMicrosToTimestamp(); * ``` * - * @return A new `Ordering` for ascending sorting. + * @return A new {@code Expr} representing the timestamp. */ - ascending(): Ordering { - return ascending(this); + unixMicrosToTimestamp(): firestore.UnixMicrosToTimestamp { + return new UnixMicrosToTimestamp(this); } /** - * Creates an {@link Ordering} that sorts documents in descending order based on this expression. + * Creates an expression that converts this timestamp expression to the number of microseconds since the Unix epoch (1970-01-01 00:00:00 UTC). * * ```typescript - * // Sort documents by the 'createdAt' field in descending order - * firestore.pipeline().collection("users") - * .sort(Field.of("createdAt").descending()); + * // Convert the 'timestamp' field to microseconds since epoch. + * Field.of("timestamp").timestampToUnixMicros(); * ``` * - * @return A new `Ordering` for descending sorting. + * @return A new {@code Expr} representing the number of microseconds since epoch. */ - descending(): Ordering { - return descending(this); + timestampToUnixMicros(): firestore.TimestampToUnixMicros { + return new TimestampToUnixMicros(this); } /** - * 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. + * 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. * * ```typescript - * // Calculate the total price and assign it the alias "totalPrice" and add it to the output. - * firestore.pipeline().collection("items") - * .addFields(Field.of("price").multiply(Field.of("quantity")).as("totalPrice")); + * // Interpret the 'milliseconds' field as milliseconds since epoch. + * Field.of("milliseconds").unixMillisToTimestamp(); * ``` * - * @param name The alias to assign to this expression. - * @return A new {@link ExprWithAlias} that wraps this - * expression and associates it with the provided alias. + * @return A new {@code Expr} representing the timestamp. */ - as(name: string): ExprWithAlias { - return new ExprWithAlias(this, name); + unixMillisToTimestamp(): firestore.UnixMillisToTimestamp { + return new UnixMillisToTimestamp(this); } - abstract _toProto(serializer: Serializer): api.IValue; -} + /** + * Creates an expression that converts this timestamp expression to the number of milliseconds since the Unix epoch (1970-01-01 00:00:00 UTC). + * + * ```typescript + * // Convert the 'timestamp' field to milliseconds since epoch. + * Field.of("timestamp").timestampToUnixMillis(); + * ``` + * + * @return A new {@code Expr} representing the number of milliseconds since epoch. + */ + timestampToUnixMillis(): firestore.TimestampToUnixMillis { + return new TimestampToUnixMillis(this); + } -/** - * @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. + * + * ```typescript + * // Interpret the 'seconds' field as seconds since epoch. + * Field.of("seconds").unixSecondsToTimestamp(); + * ``` + * + * @return A new {@code Expr} representing the timestamp. + */ + unixSecondsToTimestamp(): firestore.UnixSecondsToTimestamp { + return new UnixSecondsToTimestamp(this); + } + + /** + * Creates an expression that converts this timestamp expression to the number of seconds since the Unix epoch (1970-01-01 00:00:00 UTC). + * + * ```typescript + * // Convert the 'timestamp' field to seconds since epoch. + * Field.of("timestamp").timestampToUnixSeconds(); + * ``` + * + * @return A new {@code Expr} representing the number of seconds since epoch. + */ + timestampToUnixSeconds(): firestore.TimestampToUnixSeconds { + return new TimestampToUnixSeconds(this); + } + + /** + * Creates an expression that adds a specified amount of time to this timestamp expression. + * + * ```typescript + * // Add some duration determined by field 'unit' and 'amount' to the 'timestamp' field. + * Field.of("timestamp").timestampAdd(Field.of("unit"), Field.of("amount")); + * ``` + * + * @param unit The expression evaluates to unit of time, must be one of 'microsecond', 'millisecond', 'second', 'minute', 'hour', 'day'. + * @param amount The expression evaluates to amount of the unit. + * @return A new {@code Expr} representing the resulting timestamp. + */ + timestampAdd( + unit: firestore.Expr, + amount: firestore.Expr + ): firestore.TimestampAdd; + + /** + * Creates an expression that adds a specified amount of time to this timestamp expression. + * + * ```typescript + * // Add 1 day to the 'timestamp' field. + * Field.of("timestamp").timestampAdd("day", 1); + * ``` + * + * @param unit The unit of time to add (e.g., "day", "hour"). + * @param amount The amount of time to add. + * @return A new {@code Expr} representing the resulting timestamp. + */ + timestampAdd( + unit: 'microsecond' | 'millisecond' | 'second' | 'minute' | 'hour' | 'day', + amount: number + ): firestore.TimestampAdd; + timestampAdd( + unit: + | firestore.Expr + | 'microsecond' + | 'millisecond' + | 'second' + | 'minute' + | 'hour' + | 'day', + amount: firestore.Expr | number + ): firestore.TimestampAdd { + const normalizedUnit = typeof unit === 'string' ? Constant.of(unit) : unit; + const normalizedAmount = + typeof amount === 'number' ? Constant.of(amount) : amount; + return new TimestampAdd( + this, + normalizedUnit as Expr, + normalizedAmount as Expr + ); + } + + /** + * Creates an expression that subtracts a specified amount of time from this timestamp expression. + * + * ```typescript + * // Subtract some duration determined by field 'unit' and 'amount' from the 'timestamp' field. + * Field.of("timestamp").timestampSub(Field.of("unit"), Field.of("amount")); + * ``` + * + * @param unit The expression evaluates to unit of time, must be one of 'microsecond', 'millisecond', 'second', 'minute', 'hour', 'day'. + * @param amount The expression evaluates to amount of the unit. + * @return A new {@code Expr} representing the resulting timestamp. + */ + timestampSub( + unit: firestore.Expr, + amount: firestore.Expr + ): firestore.TimestampSub; + + /** + * Creates an expression that subtracts a specified amount of time from this timestamp expression. + * + * ```typescript + * // Subtract 1 day from the 'timestamp' field. + * Field.of("timestamp").timestampSub("day", 1); + * ``` + * + * @param unit The unit of time to subtract (e.g., "day", "hour"). + * @param amount The amount of time to subtract. + * @return A new {@code Expr} representing the resulting timestamp. + */ + timestampSub( + unit: 'microsecond' | 'millisecond' | 'second' | 'minute' | 'hour' | 'day', + amount: number + ): firestore.TimestampSub; + timestampSub( + unit: + | firestore.Expr + | 'microsecond' + | 'millisecond' + | 'second' + | 'minute' + | 'hour' + | 'day', + amount: firestore.Expr | number + ): firestore.TimestampSub { + const normalizedUnit = typeof unit === 'string' ? Constant.of(unit) : unit; + const normalizedAmount = + typeof amount === 'number' ? Constant.of(amount) : amount; + return new TimestampSub( + this, + normalizedUnit as Expr, + normalizedAmount as Expr + ); + } + + /** + * Creates an {@link Ordering} that sorts documents in ascending order based on this expression. + * + * ```typescript + * // Sort documents by the 'name' field in ascending order + * firestore.pipeline().collection("users") + * .sort(Field.of("name").ascending()); + * ``` + * + * @return A new `Ordering` for ascending sorting. + */ + ascending(): Ordering { + return ascending(this); + } + + /** + * Creates an {@link Ordering} that sorts documents in descending order based on this expression. + * + * ```typescript + * // Sort documents by the 'createdAt' field in descending order + * firestore.pipeline().collection("users") + * .sort(Field.of("createdAt").descending()); + * ``` + * + * @return A new `Ordering` for descending sorting. + */ + descending(): Ordering { + return descending(this); + } + + /** + * 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. + * + * ```typescript + * // Calculate the total price and assign it the alias "totalPrice" and add it to the output. + * firestore.pipeline().collection("items") + * .addFields(Field.of("price").multiply(Field.of("quantity")).as("totalPrice")); + * ``` + * + * @param name The alias to assign to this expression. + * @return A new {@link ExprWithAlias} that wraps this + * expression and associates it with the provided alias. + */ + as(name: string): ExprWithAlias { + return new ExprWithAlias(this, name); + } + + abstract _toProto(serializer: Serializer): api.IValue; +} + +/** + * @beta + */ export class ExprWithAlias extends Expr implements Selectable { exprType: ExprType = 'ExprWithAlias'; selectable = true as const; @@ -1595,6 +2157,87 @@ export class Divide extends Function { } } +/** + * @beta + */ +export class Mod extends Function { + constructor( + private left: Expr, + private right: Expr + ) { + super('mod', [left, right]); + } +} + +/** + * @beta + */ +export class BitAnd extends Function { + constructor( + private left: Expr, + private right: Expr + ) { + super('bit_and', [left, right]); + } +} + +/** + * @beta + */ +export class BitOr extends Function { + constructor( + private left: Expr, + private right: Expr + ) { + super('bit_or', [left, right]); + } +} + +/** + * @beta + */ +export class BitXor extends Function { + constructor( + private left: Expr, + private right: Expr + ) { + super('bit_xor', [left, right]); + } +} + +/** + * @beta + */ +export class BitNot extends Function { + constructor(private operand: Expr) { + super('bit_not', [operand]); + } +} + +/** + * @beta + */ +export class BitLeftShift extends Function { + constructor( + private left: Expr, + private right: Expr + ) { + super('bit_left_shift', [left, right]); + } +} + +/** + * @beta + */ +export class BitRightShift extends Function { + constructor( + private left: Expr, + private right: Expr + ) { + super('bit_right_shift', [left, right]); + } +} + /** * @beta */ @@ -1685,6 +2328,15 @@ class ArrayConcat extends Function { } } +/** + * @beta + */ +class ArrayReverse extends Function { + constructor(private array: Expr) { + super('array_reverse', [array]); + } +} + /** * @beta */ @@ -1724,18 +2376,6 @@ class ArrayContainsAny extends Function implements FilterCondition { filterable = true as const; } -/** - * @beta - */ -class ArrayFilter extends Function { - constructor( - private array: Expr, - private filter: FilterExpr - ) { - super('array_filter', [array, filter]); - } -} - /** * @beta */ @@ -1745,18 +2385,6 @@ class ArrayLength extends Function { } } -/** - * @beta - */ -class ArrayTransform extends Function { - constructor( - private array: Expr, - private transform: Function - ) { - super('array_transform', [array, transform]); - } -} - /** * @beta */ @@ -1857,9 +2485,77 @@ class If extends Function implements FilterCondition { /** * @beta */ -class StrLength extends Function { - constructor(private expr: Expr) { - super('length', [expr]); +class LogicalMax extends Function { + constructor( + private left: Expr, + private right: Expr + ) { + super('logical_max', [left, right]); + } +} + +/** + * @beta + */ +class LogicalMin extends Function { + constructor( + private left: Expr, + private right: Expr + ) { + super('logical_min', [left, right]); + } +} + +/** + * @beta + */ +export class Reverse extends Function { + constructor(private value: Expr) { + super('reverse', [value]); + } +} + +/** + * @beta + */ +export class ReplaceFirst extends Function { + constructor( + private value: Expr, + private find: Expr, + private replace: Expr + ) { + super('replace_first', [value, find, replace]); + } +} + +/** + * @beta + */ +export class ReplaceAll extends Function { + constructor( + private value: Expr, + private find: Expr, + private replace: Expr + ) { + super('replace_all', [value, find, replace]); + } +} + +/** + * @beta + */ +export class CharLength extends Function { + constructor(private value: Expr) { + super('char_length', [value]); + } +} + +/** + * @beta + */ +export class ByteLength extends Function { + constructor(private value: Expr) { + super('byte_length', [value]); } } @@ -1931,18 +2627,18 @@ class EndsWith extends Function implements FilterCondition { /** * @beta */ -class ToLowercase extends Function { +class ToLower extends Function { constructor(private expr: Expr) { - super('to_lowercase', [expr]); + super('to_lower', [expr]); } } /** * @beta */ -class ToUppercase extends Function { +class ToUpper extends Function { constructor(private expr: Expr) { - super('to_uppercase', [expr]); + super('to_upper', [expr]); } } @@ -2079,16 +2775,105 @@ class EuclideanDistance extends Function { /** * @beta - * - * Creates an expression that adds two expressions together. - * - * ```typescript - * // Add the value of the 'quantity' field and the 'reserve' field. - * add(Field.of("quantity"), Field.of("reserve")); - * ``` - * - * @param left The first expression to add. - * @param right The second expression to add. + */ +export class VectorLength extends Function { + constructor(private value: Expr) { + super('vector_length', [value]); + } +} + +/** + * @beta + */ +export class UnixMicrosToTimestamp extends Function { + constructor(private input: Expr) { + super('unix_micros_to_timestamp', [input]); + } +} + +/** + * @beta + */ +export class TimestampToUnixMicros extends Function { + constructor(private input: Expr) { + super('timestamp_to_unix_micros', [input]); + } +} + +/** + * @beta + */ +export class UnixMillisToTimestamp extends Function { + constructor(private input: Expr) { + super('unix_millis_to_timestamp', [input]); + } +} + +/** + * @beta + */ +export class TimestampToUnixMillis extends Function { + constructor(private input: Expr) { + super('timestamp_to_unix_millis', [input]); + } +} + +/** + * @beta + */ +export class UnixSecondsToTimestamp extends Function { + constructor(private input: Expr) { + super('unix_seconds_to_timestamp', [input]); + } +} + +/** + * @beta + */ +export class TimestampToUnixSeconds extends Function { + constructor(private input: Expr) { + super('timestamp_to_unix_seconds', [input]); + } +} + +/** + * @beta + */ +export class TimestampAdd extends Function { + constructor( + private timestamp: Expr, + private unit: Expr, + private amount: Expr + ) { + super('timestamp_add', [timestamp, unit, amount]); + } +} + +/** + * @beta + */ +export class TimestampSub extends Function { + constructor( + private timestamp: Expr, + private unit: Expr, + private amount: Expr + ) { + super('timestamp_sub', [timestamp, unit, amount]); + } +} + +/** + * @beta + * + * Creates an expression that adds two expressions together. + * + * ```typescript + * // Add the value of the 'quantity' field and the 'reserve' field. + * add(Field.of("quantity"), Field.of("reserve")); + * ``` + * + * @param left The first expression to add. + * @param right The second expression to add. * @return A new {@code Expr} representing the addition operation. */ export function add(left: Expr, right: Expr): Add; @@ -2356,378 +3141,833 @@ export function divide(left: Expr | string, right: Expr | any): Divide { /** * @beta * - * Creates an expression that checks if two expressions are equal. + * Creates an expression that calculates the modulo (remainder) of dividing two expressions. * * ```typescript - * // Check if the 'age' field is equal to an expression - * eq(Field.of("age"), Field.of("minAge").add(10)); + * // Calculate the remainder of dividing 'field1' by 'field2'. + * mod(Field.of("field1"), Field.of("field2")); * ``` * - * @param left The first expression to compare. - * @param right The second expression to compare. - * @return A new `Expr` representing the equality comparison. + * @param left The dividend expression. + * @param right The divisor expression. + * @return A new {@code Expr} representing the modulo operation. */ -export function eq(left: Expr, right: Expr): Eq; +export function mod(left: Expr, right: Expr): Mod; /** * @beta * - * Creates an expression that checks if an expression is equal to a constant value. + * Creates an expression that calculates the modulo (remainder) of dividing an expression by a constant. * * ```typescript - * // Check if the 'age' field is equal to 21 - * eq(Field.of("age"), 21); + * // Calculate the remainder of dividing 'field1' by 5. + * mod(Field.of("field1"), 5); * ``` * - * @param left The expression to compare. - * @param right The constant value to compare to. - * @return A new `Expr` representing the equality comparison. + * @param left The dividend expression. + * @param right The divisor constant. + * @return A new {@code Expr} representing the modulo operation. */ -export function eq(left: Expr, right: any): Eq; +export function mod(left: Expr, right: any): Mod; /** * @beta * - * Creates an expression that checks if a field's value is equal to an expression. + * Creates an expression that calculates the modulo (remainder) of dividing a field's value by an expression. * * ```typescript - * // Check if the 'age' field is equal to the 'limit' field - * eq("age", Field.of("limit")); + * // Calculate the remainder of dividing 'field1' by 'field2'. + * mod("field1", Field.of("field2")); * ``` * - * @param left The field name to compare. - * @param right The expression to compare to. - * @return A new `Expr` representing the equality comparison. + * @param left The dividend field name. + * @param right The divisor expression. + * @return A new {@code Expr} representing the modulo operation. */ -export function eq(left: string, right: Expr): Eq; +export function mod(left: string, right: Expr): Mod; /** * @beta * - * Creates an expression that checks if a field's value is equal to a constant value. + * Creates an expression that calculates the modulo (remainder) of dividing a field's value by a constant. * * ```typescript - * // Check if the 'city' field is equal to string constant "London" - * eq("city", "London"); + * // Calculate the remainder of dividing 'field1' by 5. + * mod("field1", 5); * ``` * - * @param left The field name to compare. - * @param right The constant value to compare to. - * @return A new `Expr` representing the equality comparison. + * @param left The dividend field name. + * @param right The divisor constant. + * @return A new {@code Expr} representing the modulo operation. */ -export function eq(left: string, right: any): Eq; -export function eq(left: Expr | string, right: any): Eq { - const leftExpr = left instanceof Expr ? left : Field.of(left); - const rightExpr = right instanceof Expr ? right : Constant.of(right); - return new Eq(leftExpr, rightExpr); +export function mod(left: string, right: any): Mod; +export function mod(left: Expr | string, right: Expr | any): Mod { + const normalizedLeft = typeof left === 'string' ? Field.of(left) : left; + const normalizedRight = right instanceof Expr ? right : Constant.of(right); + return new Mod(normalizedLeft, normalizedRight); } /** * @beta * - * Creates an expression that checks if two expressions are not equal. + * Creates an expression that applies a bitwise AND operation between two expressions. * * ```typescript - * // Check if the 'status' field is not equal to field 'finalState' - * neq(Field.of("status"), Field.of("finalState")); + * // Calculate the bitwise AND of 'field1' and 'field2'. + * bitAnd(Field.of("field1"), Field.of("field2")); * ``` * - * @param left The first expression to compare. - * @param right The second expression to compare. - * @return A new `Expr` representing the inequality comparison. + * @param left The left operand expression. + * @param right The right operand expression. + * @return A new {@code Expr} representing the bitwise AND operation. */ -export function neq(left: Expr, right: Expr): Neq; +export function bitAnd(left: Expr, right: Expr): BitAnd; /** * @beta * - * Creates an expression that checks if an expression is not equal to a constant value. + * Creates an expression that applies a bitwise AND operation between an expression and a constant. * * ```typescript - * // Check if the 'status' field is not equal to "completed" - * neq(Field.of("status"), "completed"); + * // Calculate the bitwise AND of 'field1' and 0xFF. + * bitAnd(Field.of("field1"), 0xFF); * ``` * - * @param left The expression to compare. - * @param right The constant value to compare to. - * @return A new `Expr` representing the inequality comparison. + * @param left The left operand expression. + * @param right The right operand constant. + * @return A new {@code Expr} representing the bitwise AND operation. */ -export function neq(left: Expr, right: any): Neq; +export function bitAnd(left: Expr, right: any): BitAnd; /** * @beta * - * Creates an expression that checks if a field's value is not equal to an expression. + * Creates an expression that applies a bitwise AND operation between a field and an expression. * * ```typescript - * // Check if the 'status' field is not equal to the value of 'expectedStatus' - * neq("status", Field.of("expectedStatus")); + * // Calculate the bitwise AND of 'field1' and 'field2'. + * bitAnd("field1", Field.of("field2")); * ``` * - * @param left The field name to compare. - * @param right The expression to compare to. - * @return A new `Expr` representing the inequality comparison. + * @param left The left operand field name. + * @param right The right operand expression. + * @return A new {@code Expr} representing the bitwise AND operation. */ -export function neq(left: string, right: Expr): Neq; +export function bitAnd(left: string, right: Expr): BitAnd; /** * @beta * - * Creates an expression that checks if a field's value is not equal to a constant value. + * Creates an expression that applies a bitwise AND operation between a field and a constant. * * ```typescript - * // Check if the 'country' field is not equal to "USA" - * neq("country", "USA"); + * // Calculate the bitwise AND of 'field1' and 0xFF. + * bitAnd("field1", 0xFF); * ``` * - * @param left The field name to compare. - * @param right The constant value to compare to. - * @return A new `Expr` representing the inequality comparison. + * @param left The left operand field name. + * @param right The right operand constant. + * @return A new {@code Expr} representing the bitwise AND operation. */ -export function neq(left: string, right: any): Neq; -export function neq(left: Expr | string, right: any): Neq { - const leftExpr = left instanceof Expr ? left : Field.of(left); - const rightExpr = right instanceof Expr ? right : Constant.of(right); - return new Neq(leftExpr, rightExpr); +export function bitAnd(left: string, right: any): BitAnd; +export function bitAnd(left: Expr | string, right: Expr | any): BitAnd { + const normalizedLeft = typeof left === 'string' ? Field.of(left) : left; + const normalizedRight = right instanceof Expr ? right : Constant.of(right); + return new BitAnd(normalizedLeft, normalizedRight); } /** * @beta * - * Creates an expression that checks if the first expression is less than the second expression. + * Creates an expression that applies a bitwise OR operation between two expressions. * * ```typescript - * // Check if the 'age' field is less than 30 - * lt(Field.of("age"), Field.of("limit")); + * // Calculate the bitwise OR of 'field1' and 'field2'. + * bitOr(Field.of("field1"), Field.of("field2")); * ``` * - * @param left The first expression to compare. - * @param right The second expression to compare. - * @return A new `Expr` representing the less than comparison. + * @param left The left operand expression. + * @param right The right operand expression. + * @return A new {@code Expr} representing the bitwise OR operation. */ -export function lt(left: Expr, right: Expr): Lt; +export function bitOr(left: Expr, right: Expr): BitOr; /** * @beta * - * Creates an expression that checks if an expression is less than a constant value. + * Creates an expression that applies a bitwise OR operation between an expression and a constant. * * ```typescript - * // Check if the 'age' field is less than 30 - * lt(Field.of("age"), 30); + * // Calculate the bitwise OR of 'field1' and 0xFF. + * bitOr(Field.of("field1"), 0xFF); * ``` * - * @param left The expression to compare. - * @param right The constant value to compare to. - * @return A new `Expr` representing the less than comparison. + * @param left The left operand expression. + * @param right The right operand constant. + * @return A new {@code Expr} representing the bitwise OR operation. */ -export function lt(left: Expr, right: any): Lt; +export function bitOr(left: Expr, right: any): BitOr; /** * @beta * - * Creates an expression that checks if a field's value is less than an expression. + * Creates an expression that applies a bitwise OR operation between a field and an expression. * * ```typescript - * // Check if the 'age' field is less than the 'limit' field - * lt("age", Field.of("limit")); + * // Calculate the bitwise OR of 'field1' and 'field2'. + * bitOr("field1", Field.of("field2")); * ``` * - * @param left The field name to compare. - * @param right The expression to compare to. - * @return A new `Expr` representing the less than comparison. + * @param left The left operand field name. + * @param right The right operand expression. + * @return A new {@code Expr} representing the bitwise OR operation. */ -export function lt(left: string, right: Expr): Lt; +export function bitOr(left: string, right: Expr): BitOr; /** * @beta * - * Creates an expression that checks if a field's value is less than a constant value. + * Creates an expression that applies a bitwise OR operation between a field and a constant. * * ```typescript - * // Check if the 'price' field is less than 50 - * lt("price", 50); + * // Calculate the bitwise OR of 'field1' and 0xFF. + * bitOr("field1", 0xFF); * ``` * - * @param left The field name to compare. - * @param right The constant value to compare to. - * @return A new `Expr` representing the less than comparison. + * @param left The left operand field name. + * @param right The right operand constant. + * @return A new {@code Expr} representing the bitwise OR operation. */ -export function lt(left: string, right: any): Lt; -export function lt(left: Expr | string, right: any): Lt { - const leftExpr = left instanceof Expr ? left : Field.of(left); - const rightExpr = right instanceof Expr ? right : Constant.of(right); - return new Lt(leftExpr, rightExpr); +export function bitOr(left: string, right: any): BitOr; +export function bitOr(left: Expr | string, right: Expr | any): BitOr { + const normalizedLeft = typeof left === 'string' ? Field.of(left) : left; + const normalizedRight = right instanceof Expr ? right : Constant.of(right); + return new BitOr(normalizedLeft, normalizedRight); } /** * @beta * - * Creates an expression that checks if the first expression is less than or equal to the second - * expression. + * Creates an expression that applies a bitwise XOR operation between two expressions. * * ```typescript - * // Check if the 'quantity' field is less than or equal to 20 - * lte(Field.of("quantity"), Field.of("limit")); + * // Calculate the bitwise XOR of 'field1' and 'field2'. + * bitXor(Field.of("field1"), Field.of("field2")); * ``` * - * @param left The first expression to compare. - * @param right The second expression to compare. - * @return A new `Expr` representing the less than or equal to comparison. + * @param left The left operand expression. + * @param right The right operand expression. + * @return A new {@code Expr} representing the bitwise XOR operation. */ -export function lte(left: Expr, right: Expr): Lte; +export function bitXor(left: Expr, right: Expr): BitXor; /** * @beta * - * Creates an expression that checks if an expression is less than or equal to a constant value. + * Creates an expression that applies a bitwise XOR operation between an expression and a constant. * * ```typescript - * // Check if the 'quantity' field is less than or equal to 20 - * lte(Field.of("quantity"), 20); + * // Calculate the bitwise XOR of 'field1' and 0xFF. + * bitXor(Field.of("field1"), 0xFF); * ``` * - * @param left The expression to compare. - * @param right The constant value to compare to. - * @return A new `Expr` representing the less than or equal to comparison. + * @param left The left operand expression. + * @param right The right operand constant. + * @return A new {@code Expr} representing the bitwise XOR operation. */ -export function lte(left: Expr, right: any): Lte; +export function bitXor(left: Expr, right: any): BitXor; /** - * Creates an expression that checks if a field's value is less than or equal to an expression. + * @beta + * + * Creates an expression that applies a bitwise XOR operation between a field and an expression. * * ```typescript - * // Check if the 'quantity' field is less than or equal to the 'limit' field - * lte("quantity", Field.of("limit")); + * // Calculate the bitwise XOR of 'field1' and 'field2'. + * bitXor("field1", Field.of("field2")); * ``` * - * @param left The field name to compare. - * @param right The expression to compare to. - * @return A new `Expr` representing the less than or equal to comparison. + * @param left The left operand field name. + * @param right The right operand expression. + * @return A new {@code Expr} representing the bitwise XOR operation. */ -export function lte(left: string, right: Expr): Lte; +export function bitXor(left: string, right: Expr): BitXor; /** * @beta * - * Creates an expression that checks if a field's value is less than or equal to a constant value. + * Creates an expression that applies a bitwise XOR operation between a field and a constant. * * ```typescript - * // Check if the 'score' field is less than or equal to 70 - * lte("score", 70); + * // Calculate the bitwise XOR of 'field1' and 0xFF. + * bitXor("field1", 0xFF); * ``` * - * @param left The field name to compare. - * @param right The constant value to compare to. - * @return A new `Expr` representing the less than or equal to comparison. + * @param left The left operand field name. + * @param right The right operand constant. + * @return A new {@code Expr} representing the bitwise XOR operation. */ -export function lte(left: string, right: any): Lte; -export function lte(left: Expr | string, right: any): Lte { - const leftExpr = left instanceof Expr ? left : Field.of(left); - const rightExpr = right instanceof Expr ? right : Constant.of(right); - return new Lte(leftExpr, rightExpr); +export function bitXor(left: string, right: any): BitXor; +export function bitXor(left: Expr | string, right: Expr | any): BitXor { + const normalizedLeft = typeof left === 'string' ? Field.of(left) : left; + const normalizedRight = right instanceof Expr ? right : Constant.of(right); + return new BitXor(normalizedLeft, normalizedRight); } /** * @beta * - * Creates an expression that checks if the first expression is greater than the second - * expression. + * Creates an expression that applies a bitwise NOT operation to an expression. * * ```typescript - * // Check if the 'age' field is greater than 18 - * gt(Field.of("age"), Constant(9).add(9)); + * // Calculate the bitwise NOT of 'field1'. + * bitNot(Field.of("field1")); * ``` * - * @param left The first expression to compare. - * @param right The second expression to compare. - * @return A new `Expr` representing the greater than comparison. + * @param operand The operand expression. + * @return A new {@code Expr} representing the bitwise NOT operation. */ -export function gt(left: Expr, right: Expr): Gt; +export function bitNot(operand: Expr): BitNot; /** * @beta * - * Creates an expression that checks if an expression is greater than a constant value. + * Creates an expression that applies a bitwise NOT operation to a field. * * ```typescript - * // Check if the 'age' field is greater than 18 - * gt(Field.of("age"), 18); + * // Calculate the bitwise NOT of 'field1'. + * bitNot("field1"); * ``` * - * @param left The expression to compare. - * @param right The constant value to compare to. - * @return A new `Expr` representing the greater than comparison. + * @param operand The operand field name. + * @return A new {@code Expr} representing the bitwise NOT operation. */ -export function gt(left: Expr, right: any): Gt; +export function bitNot(operand: string): BitNot; +export function bitNot(operand: Expr | string): BitNot { + const normalizedOperand = + typeof operand === 'string' ? Field.of(operand) : operand; + return new BitNot(normalizedOperand); +} /** * @beta * - * Creates an expression that checks if a field's value is greater than an expression. + * Creates an expression that applies a bitwise left shift operation between two expressions. * * ```typescript - * // Check if the value of field 'age' is greater than the value of field 'limit' - * gt("age", Field.of("limit")); + * // Calculate the bitwise left shift of 'field1' by 'field2' bits. + * bitLeftShift(Field.of("field1"), Field.of("field2")); * ``` * - * @param left The field name to compare. - * @param right The expression to compare to. - * @return A new `Expr` representing the greater than comparison. + * @param left The left operand expression. + * @param right The right operand expression representing the number of bits to shift. + * @return A new {@code Expr} representing the bitwise left shift operation. */ -export function gt(left: string, right: Expr): Gt; +export function bitLeftShift(left: Expr, right: Expr): BitLeftShift; /** * @beta * - * Creates an expression that checks if a field's value is greater than a constant value. + * Creates an expression that applies a bitwise left shift operation between an expression and a constant. * * ```typescript - * // Check if the 'price' field is greater than 100 - * gt("price", 100); + * // Calculate the bitwise left shift of 'field1' by 2 bits. + * bitLeftShift(Field.of("field1"), 2); * ``` * - * @param left The field name to compare. - * @param right The constant value to compare to. - * @return A new `Expr` representing the greater than comparison. + * @param left The left operand expression. + * @param right The right operand constant representing the number of bits to shift. + * @return A new {@code Expr} representing the bitwise left shift operation. */ -export function gt(left: string, right: any): Gt; -export function gt(left: Expr | string, right: any): Gt { - const leftExpr = left instanceof Expr ? left : Field.of(left); - const rightExpr = right instanceof Expr ? right : Constant.of(right); - return new Gt(leftExpr, rightExpr); -} +export function bitLeftShift(left: Expr, right: any): BitLeftShift; /** * @beta * - * Creates an expression that checks if the first expression is greater than or equal to the - * second expression. + * Creates an expression that applies a bitwise left shift operation between a field and an expression. * * ```typescript - * // Check if the 'quantity' field is greater than or equal to the field "threshold" - * gte(Field.of("quantity"), Field.of("threshold")); + * // Calculate the bitwise left shift of 'field1' by 'field2' bits. + * bitLeftShift("field1", Field.of("field2")); * ``` * - * @param left The first expression to compare. - * @param right The second expression to compare. - * @return A new `Expr` representing the greater than or equal to comparison. + * @param left The left operand field name. + * @param right The right operand expression representing the number of bits to shift. + * @return A new {@code Expr} representing the bitwise left shift operation. */ -export function gte(left: Expr, right: Expr): Gte; +export function bitLeftShift(left: string, right: Expr): BitLeftShift; /** * @beta * - * Creates an expression that checks if an expression is greater than or equal to a constant - * value. + * Creates an expression that applies a bitwise left shift operation between a field and a constant. * * ```typescript - * // Check if the 'quantity' field is greater than or equal to 10 - * gte(Field.of("quantity"), 10); + * // Calculate the bitwise left shift of 'field1' by 2 bits. + * bitLeftShift("field1", 2); * ``` * - * @param left The expression to compare. - * @param right The constant value to compare to. + * @param left The left operand field name. + * @param right The right operand constant representing the number of bits to shift. + * @return A new {@code Expr} representing the bitwise left shift operation. + */ +export function bitLeftShift(left: string, right: any): BitLeftShift; +export function bitLeftShift( + left: Expr | string, + right: Expr | any +): BitLeftShift { + const normalizedLeft = typeof left === 'string' ? Field.of(left) : left; + const normalizedRight = right instanceof Expr ? right : Constant.of(right); + return new BitLeftShift(normalizedLeft, normalizedRight); +} + +/** + * @beta + * + * Creates an expression that applies a bitwise right shift operation between two expressions. + * + * ```typescript + * // Calculate the bitwise right shift of 'field1' by 'field2' bits. + * bitRightShift(Field.of("field1"), Field.of("field2")); + * ``` + * + * @param left The left operand expression. + * @param right The right operand expression representing the number of bits to shift. + * @return A new {@code Expr} representing the bitwise right shift operation. + */ +export function bitRightShift(left: Expr, right: Expr): BitRightShift; + +/** + * @beta + * + * Creates an expression that applies a bitwise right shift operation between an expression and a constant. + * + * ```typescript + * // Calculate the bitwise right shift of 'field1' by 2 bits. + * bitRightShift(Field.of("field1"), 2); + * ``` + * + * @param left The left operand expression. + * @param right The right operand constant representing the number of bits to shift. + * @return A new {@code Expr} representing the bitwise right shift operation. + */ +export function bitRightShift(left: Expr, right: any): BitRightShift; + +/** + * @beta + * + * Creates an expression that applies a bitwise right shift operation between a field and an expression. + * + * ```typescript + * // Calculate the bitwise right shift of 'field1' by 'field2' bits. + * bitRightShift("field1", Field.of("field2")); + * ``` + * + * @param left The left operand field name. + * @param right The right operand expression representing the number of bits to shift. + * @return A new {@code Expr} representing the bitwise right shift operation. + */ +export function bitRightShift(left: string, right: Expr): BitRightShift; + +/** + * @beta + * + * Creates an expression that applies a bitwise right shift operation between a field and a constant. + * + * ```typescript + * // Calculate the bitwise right shift of 'field1' by 2 bits. + * bitRightShift("field1", 2); + * ``` + * + * @param left The left operand field name. + * @param right The right operand constant representing the number of bits to shift. + * @return A new {@code Expr} representing the bitwise right shift operation. + */ +export function bitRightShift(left: string, right: any): BitRightShift; +export function bitRightShift( + left: Expr | string, + right: Expr | any +): BitRightShift { + const normalizedLeft = typeof left === 'string' ? Field.of(left) : left; + const normalizedRight = right instanceof Expr ? right : Constant.of(right); + return new BitRightShift(normalizedLeft, normalizedRight); +} + +/** + * @beta + * + * Creates an expression that checks if two expressions are equal. + * + * ```typescript + * // Check if the 'age' field is equal to an expression + * eq(Field.of("age"), Field.of("minAge").add(10)); + * ``` + * + * @param left The first expression to compare. + * @param right The second expression to compare. + * @return A new `Expr` representing the equality comparison. + */ +export function eq(left: Expr, right: Expr): Eq; + +/** + * @beta + * + * Creates an expression that checks if an expression is equal to a constant value. + * + * ```typescript + * // Check if the 'age' field is equal to 21 + * eq(Field.of("age"), 21); + * ``` + * + * @param left The expression to compare. + * @param right The constant value to compare to. + * @return A new `Expr` representing the equality comparison. + */ +export function eq(left: Expr, right: any): Eq; + +/** + * @beta + * + * Creates an expression that checks if a field's value is equal to an expression. + * + * ```typescript + * // Check if the 'age' field is equal to the 'limit' field + * eq("age", Field.of("limit")); + * ``` + * + * @param left The field name to compare. + * @param right The expression to compare to. + * @return A new `Expr` representing the equality comparison. + */ +export function eq(left: string, right: Expr): Eq; + +/** + * @beta + * + * Creates an expression that checks if a field's value is equal to a constant value. + * + * ```typescript + * // Check if the 'city' field is equal to string constant "London" + * eq("city", "London"); + * ``` + * + * @param left The field name to compare. + * @param right The constant value to compare to. + * @return A new `Expr` representing the equality comparison. + */ +export function eq(left: string, right: any): Eq; +export function eq(left: Expr | string, right: any): Eq { + const leftExpr = left instanceof Expr ? left : Field.of(left); + const rightExpr = right instanceof Expr ? right : Constant.of(right); + return new Eq(leftExpr, rightExpr); +} + +/** + * @beta + * + * Creates an expression that checks if two expressions are not equal. + * + * ```typescript + * // Check if the 'status' field is not equal to field 'finalState' + * neq(Field.of("status"), Field.of("finalState")); + * ``` + * + * @param left The first expression to compare. + * @param right The second expression to compare. + * @return A new `Expr` representing the inequality comparison. + */ +export function neq(left: Expr, right: Expr): Neq; + +/** + * @beta + * + * Creates an expression that checks if an expression is not equal to a constant value. + * + * ```typescript + * // Check if the 'status' field is not equal to "completed" + * neq(Field.of("status"), "completed"); + * ``` + * + * @param left The expression to compare. + * @param right The constant value to compare to. + * @return A new `Expr` representing the inequality comparison. + */ +export function neq(left: Expr, right: any): Neq; + +/** + * @beta + * + * Creates an expression that checks if a field's value is not equal to an expression. + * + * ```typescript + * // Check if the 'status' field is not equal to the value of 'expectedStatus' + * neq("status", Field.of("expectedStatus")); + * ``` + * + * @param left The field name to compare. + * @param right The expression to compare to. + * @return A new `Expr` representing the inequality comparison. + */ +export function neq(left: string, right: Expr): Neq; + +/** + * @beta + * + * Creates an expression that checks if a field's value is not equal to a constant value. + * + * ```typescript + * // Check if the 'country' field is not equal to "USA" + * neq("country", "USA"); + * ``` + * + * @param left The field name to compare. + * @param right The constant value to compare to. + * @return A new `Expr` representing the inequality comparison. + */ +export function neq(left: string, right: any): Neq; +export function neq(left: Expr | string, right: any): Neq { + const leftExpr = left instanceof Expr ? left : Field.of(left); + const rightExpr = right instanceof Expr ? right : Constant.of(right); + return new Neq(leftExpr, rightExpr); +} + +/** + * @beta + * + * Creates an expression that checks if the first expression is less than the second expression. + * + * ```typescript + * // Check if the 'age' field is less than 30 + * lt(Field.of("age"), Field.of("limit")); + * ``` + * + * @param left The first expression to compare. + * @param right The second expression to compare. + * @return A new `Expr` representing the less than comparison. + */ +export function lt(left: Expr, right: Expr): Lt; + +/** + * @beta + * + * Creates an expression that checks if an expression is less than a constant value. + * + * ```typescript + * // Check if the 'age' field is less than 30 + * lt(Field.of("age"), 30); + * ``` + * + * @param left The expression to compare. + * @param right The constant value to compare to. + * @return A new `Expr` representing the less than comparison. + */ +export function lt(left: Expr, right: any): Lt; + +/** + * @beta + * + * Creates an expression that checks if a field's value is less than an expression. + * + * ```typescript + * // Check if the 'age' field is less than the 'limit' field + * lt("age", Field.of("limit")); + * ``` + * + * @param left The field name to compare. + * @param right The expression to compare to. + * @return A new `Expr` representing the less than comparison. + */ +export function lt(left: string, right: Expr): Lt; + +/** + * @beta + * + * Creates an expression that checks if a field's value is less than a constant value. + * + * ```typescript + * // Check if the 'price' field is less than 50 + * lt("price", 50); + * ``` + * + * @param left The field name to compare. + * @param right The constant value to compare to. + * @return A new `Expr` representing the less than comparison. + */ +export function lt(left: string, right: any): Lt; +export function lt(left: Expr | string, right: any): Lt { + const leftExpr = left instanceof Expr ? left : Field.of(left); + const rightExpr = right instanceof Expr ? right : Constant.of(right); + return new Lt(leftExpr, rightExpr); +} + +/** + * @beta + * + * Creates an expression that checks if the first expression is less than or equal to the second + * expression. + * + * ```typescript + * // Check if the 'quantity' field is less than or equal to 20 + * lte(Field.of("quantity"), Field.of("limit")); + * ``` + * + * @param left The first expression to compare. + * @param right The second expression to compare. + * @return A new `Expr` representing the less than or equal to comparison. + */ +export function lte(left: Expr, right: Expr): Lte; + +/** + * @beta + * + * Creates an expression that checks if an expression is less than or equal to a constant value. + * + * ```typescript + * // Check if the 'quantity' field is less than or equal to 20 + * lte(Field.of("quantity"), 20); + * ``` + * + * @param left The expression to compare. + * @param right The constant value to compare to. + * @return A new `Expr` representing the less than or equal to comparison. + */ +export function lte(left: Expr, right: any): Lte; + +/** + * Creates an expression that checks if a field's value is less than or equal to an expression. + * + * ```typescript + * // Check if the 'quantity' field is less than or equal to the 'limit' field + * lte("quantity", Field.of("limit")); + * ``` + * + * @param left The field name to compare. + * @param right The expression to compare to. + * @return A new `Expr` representing the less than or equal to comparison. + */ +export function lte(left: string, right: Expr): Lte; + +/** + * @beta + * + * Creates an expression that checks if a field's value is less than or equal to a constant value. + * + * ```typescript + * // Check if the 'score' field is less than or equal to 70 + * lte("score", 70); + * ``` + * + * @param left The field name to compare. + * @param right The constant value to compare to. + * @return A new `Expr` representing the less than or equal to comparison. + */ +export function lte(left: string, right: any): Lte; +export function lte(left: Expr | string, right: any): Lte { + const leftExpr = left instanceof Expr ? left : Field.of(left); + const rightExpr = right instanceof Expr ? right : Constant.of(right); + return new Lte(leftExpr, rightExpr); +} + +/** + * @beta + * + * Creates an expression that checks if the first expression is greater than the second + * expression. + * + * ```typescript + * // Check if the 'age' field is greater than 18 + * gt(Field.of("age"), Constant(9).add(9)); + * ``` + * + * @param left The first expression to compare. + * @param right The second expression to compare. + * @return A new `Expr` representing the greater than comparison. + */ +export function gt(left: Expr, right: Expr): Gt; + +/** + * @beta + * + * Creates an expression that checks if an expression is greater than a constant value. + * + * ```typescript + * // Check if the 'age' field is greater than 18 + * gt(Field.of("age"), 18); + * ``` + * + * @param left The expression to compare. + * @param right The constant value to compare to. + * @return A new `Expr` representing the greater than comparison. + */ +export function gt(left: Expr, right: any): Gt; + +/** + * @beta + * + * Creates an expression that checks if a field's value is greater than an expression. + * + * ```typescript + * // Check if the value of field 'age' is greater than the value of field 'limit' + * gt("age", Field.of("limit")); + * ``` + * + * @param left The field name to compare. + * @param right The expression to compare to. + * @return A new `Expr` representing the greater than comparison. + */ +export function gt(left: string, right: Expr): Gt; + +/** + * @beta + * + * Creates an expression that checks if a field's value is greater than a constant value. + * + * ```typescript + * // Check if the 'price' field is greater than 100 + * gt("price", 100); + * ``` + * + * @param left The field name to compare. + * @param right The constant value to compare to. + * @return A new `Expr` representing the greater than comparison. + */ +export function gt(left: string, right: any): Gt; +export function gt(left: Expr | string, right: any): Gt { + const leftExpr = left instanceof Expr ? left : Field.of(left); + const rightExpr = right instanceof Expr ? right : Constant.of(right); + return new Gt(leftExpr, rightExpr); +} + +/** + * @beta + * + * Creates an expression that checks if the first expression is greater than or equal to the + * second expression. + * + * ```typescript + * // Check if the 'quantity' field is greater than or equal to the field "threshold" + * gte(Field.of("quantity"), Field.of("threshold")); + * ``` + * + * @param left The first expression to compare. + * @param right The second expression to compare. + * @return A new `Expr` representing the greater than or equal to comparison. + */ +export function gte(left: Expr, right: Expr): Gte; + +/** + * @beta + * + * Creates an expression that checks if an expression is greater than or equal to a constant + * value. + * + * ```typescript + * // Check if the 'quantity' field is greater than or equal to 10 + * gte(Field.of("quantity"), 10); + * ``` + * + * @param left The expression to compare. + * @param right The constant value to compare to. * @return A new `Expr` representing the greater than or equal to comparison. */ export function gte(left: Expr, right: any): Gte; @@ -3057,110 +4297,48 @@ export function arrayContainsAll( /** * @beta * - * Creates an expression that checks if a field's array value contains all the specified values or - * expressions. - * - * ```typescript - * // Check if the 'tags' array contains both of the values from field 'tag1' and "tag2" - * arrayContainsAll("tags", [Field.of("tag1"), "SciFi", "Adventure"]); - * ``` - * - * @param array The field name to check. - * @param values The elements to check for in the array. - * @return A new {@code Expr} representing the 'array_contains_all' comparison. - */ -export function arrayContainsAll( - array: string, - values: any[] -): ArrayContainsAll; -export function arrayContainsAll( - array: Expr | string, - values: any[] -): ArrayContainsAll { - const arrayExpr = array instanceof Expr ? array : Field.of(array); - const exprValues = values.map(value => - value instanceof Expr ? value : Constant.of(value) - ); - return new ArrayContainsAll(arrayExpr, exprValues); -} - -/** - * @beta - * - * Creates an expression that filters elements from an array expression using the given {@link - * FilterExpr} and returns the filtered elements as a new array. - * - * ```typescript - * // Get items from the 'inventoryPrices' array where the array item is greater than 0 - * // Note we use {@link arrayElement} to represent array elements to construct a - * // filtering condition. - * arrayFilter(Field.of("inventoryPrices"), arrayElement().gt(0)); - * ``` - * - * @param array The array expression to filter. - * @param filter The {@link FilterExpr} to apply to the array elements. - * @return A new {@code Expr} representing the filtered array. - */ -export function arrayFilter(array: Expr, filter: FilterExpr): ArrayFilter { - return new ArrayFilter(array, filter); -} - -/** - * @beta - * - * Creates an expression that calculates the length of an array expression. - * - * ```typescript - * // Get the number of items in the 'cart' array - * arrayLength(Field.of("cart")); - * ``` - * - * @param array The array expression to calculate the length of. - * @return A new {@code Expr} representing the length of the array. - */ -export function arrayLength(array: Expr): ArrayLength { - return new ArrayLength(array); -} - -/** - * @beta - * - * Creates an expression that applies a transformation function to each element in an array - * expression and returns the new array as the result of the evaluation. + * Creates an expression that checks if a field's array value contains all the specified values or + * expressions. * * ```typescript - * // Convert all strings in the 'names' array to uppercase - * // Note we use {@link arrayElement} to represent array elements to construct a - * // transforming function. - * arrayTransform(Field.of("names"), arrayElement().toUppercase()); + * // Check if the 'tags' array contains both of the values from field 'tag1' and "tag2" + * arrayContainsAll("tags", [Field.of("tag1"), "SciFi", "Adventure"]); * ``` * - * @param array The array expression to transform. - * @param transform The {@link Function} to apply to each array element. - * @return A new {@code Expr} representing the transformed array. + * @param array The field name to check. + * @param values The elements to check for in the array. + * @return A new {@code Expr} representing the 'array_contains_all' comparison. */ -export function arrayTransform( - array: Expr, - transform: Function -): ArrayTransform { - return new ArrayTransform(array, transform); +export function arrayContainsAll( + array: string, + values: any[] +): ArrayContainsAll; +export function arrayContainsAll( + array: Expr | string, + values: any[] +): ArrayContainsAll { + const arrayExpr = array instanceof Expr ? array : Field.of(array); + const exprValues = values.map(value => + value instanceof Expr ? value : Constant.of(value) + ); + return new ArrayContainsAll(arrayExpr, exprValues); } /** * @beta * - * Returns an expression that represents an array element within an {@link ArrayFilter} or {@link - * ArrayTransform} expression. + * Creates an expression that calculates the length of an array expression. * * ```typescript - * // Get items from the 'inventoryPrices' array where the array item is greater than 0 - * arrayFilter(Field.of("inventoryPrices"), arrayElement().gt(0)); + * // Get the number of items in the 'cart' array + * arrayLength(Field.of("cart")); * ``` * - * @return A new {@code Expr} representing an array element. + * @param array The array expression to calculate the length of. + * @return A new {@code Expr} representing the length of the array. */ -export function arrayElement(): ArrayElement { - return new ArrayElement(); +export function arrayLength(array: Expr): ArrayLength { + return new ArrayLength(array); } /** @@ -3366,157 +4544,509 @@ export function or(left: FilterExpr, ...right: FilterExpr[]): Or { * eq("status", "active")); * ``` * - * @param left The first filter condition. - * @param right Additional filter conditions to 'XOR' together. - * @return A new {@code Expr} representing the logical 'XOR' operation. + * @param left The first filter condition. + * @param right Additional filter conditions to 'XOR' together. + * @return A new {@code Expr} representing the logical 'XOR' operation. + */ +export function xor(left: FilterExpr, ...right: FilterExpr[]): Xor { + return new Xor([left, ...right]); +} + +/** + * @beta + * + * Creates a conditional expression that evaluates to a 'then' expression if a condition is true + * and an 'else' expression if the condition is false. + * + * ```typescript + * // If 'age' is greater than 18, return "Adult"; otherwise, return "Minor". + * ifFunction( + * gt("age", 18), Constant.of("Adult"), Constant.of("Minor")); + * ``` + * + * @param condition The condition to evaluate. + * @param thenExpr The expression to evaluate if the condition is true. + * @param elseExpr The expression to evaluate if the condition is false. + * @return A new {@code Expr} representing the conditional expression. + */ +export function ifFunction( + condition: FilterExpr, + thenExpr: Expr, + elseExpr: Expr +): If { + return new If(condition, thenExpr, elseExpr); +} + +/** + * @beta + * + * Creates an expression that negates a filter condition. + * + * ```typescript + * // Find documents where the 'completed' field is NOT true + * not(eq("completed", true)); + * ``` + * + * @param filter The filter condition to negate. + * @return A new {@code Expr} representing the negated filter condition. + */ +export function not(filter: FilterExpr): Not { + return new Not(filter); +} + +/** + * @beta + * + * Creates an expression that returns the larger value between two expressions, based on Firestore's value type ordering. + * + * ```typescript + * // Returns the larger value between the 'field1' field and the 'field2' field. + * logicalMax(Field.of("field1"), Field.of("field2")); + * ``` + * + * @param left The left operand expression. + * @param right The right operand expression. + * @return A new {@code Expr} representing the logical max operation. + */ +export function logicalMax(left: Expr, right: Expr): LogicalMax; + +/** + * @beta + * + * Creates an expression that returns the larger value between an expression and a constant value, based on Firestore's value type ordering. + * + * ```typescript + * // Returns the larger value between the 'value' field and 10. + * logicalMax(Field.of("value"), 10); + * ``` + * + * @param left The left operand expression. + * @param right The right operand constant. + * @return A new {@code Expr} representing the logical max operation. + */ +export function logicalMax(left: Expr, right: any): LogicalMax; + +/** + * @beta + * + * Creates an expression that returns the larger value between a field and an expression, based on Firestore's value type ordering. + * + * ```typescript + * // Returns the larger value between the 'field1' field and the 'field2' field. + * logicalMax("field1", Field.of('field2')); + * ``` + * + * @param left The left operand field name. + * @param right The right operand expression. + * @return A new {@code Expr} representing the logical max operation. + */ +export function logicalMax(left: string, right: Expr): LogicalMax; + +/** + * @beta + * + * Creates an expression that returns the larger value between a field and a constant value, based on Firestore's value type ordering. + * + * ```typescript + * // Returns the larger value between the 'value' field and 10. + * logicalMax("value", 10); + * ``` + * + * @param left The left operand field name. + * @param right The right operand constant. + * @return A new {@code Expr} representing the logical max operation. + */ +export function logicalMax(left: string, right: any): LogicalMax; +export function logicalMax(left: Expr | string, right: Expr | any): LogicalMax { + const normalizedLeft = typeof left === 'string' ? Field.of(left) : left; + const normalizedRight = right instanceof Expr ? right : Constant.of(right); + return new LogicalMax(normalizedLeft, normalizedRight); +} + +/** + * @beta + * + * Creates an expression that returns the smaller value between two expressions, based on Firestore's value type ordering. + * + * ```typescript + * // Returns the smaller value between the 'field1' field and the 'field2' field. + * logicalMin(Field.of("field1"), Field.of("field2")); + * ``` + * + * @param left The left operand expression. + * @param right The right operand expression. + * @return A new {@code Expr} representing the logical min operation. + */ +export function logicalMin(left: Expr, right: Expr): LogicalMin; + +/** + * @beta + * + * Creates an expression that returns the smaller value between an expression and a constant value, based on Firestore's value type ordering. + * + * ```typescript + * // Returns the smaller value between the 'value' field and 10. + * logicalMin(Field.of("value"), 10); + * ``` + * + * @param left The left operand expression. + * @param right The right operand constant. + * @return A new {@code Expr} representing the logical min operation. + */ +export function logicalMin(left: Expr, right: any): LogicalMin; + +/** + * @beta + * + * Creates an expression that returns the smaller value between a field and an expression, based on Firestore's value type ordering. + * + * ```typescript + * // Returns the smaller value between the 'field1' field and the 'field2' field. + * logicalMin("field1", Field.of("field2")); + * ``` + * + * @param left The left operand field name. + * @param right The right operand expression. + * @return A new {@code Expr} representing the logical min operation. + */ +export function logicalMin(left: string, right: Expr): LogicalMin; + +/** + * @beta + * + * Creates an expression that returns the smaller value between a field and a constant value, based on Firestore's value type ordering. + * + * ```typescript + * // Returns the smaller value between the 'value' field and 10. + * logicalMin("value", 10); + * ``` + * + * @param left The left operand field name. + * @param right The right operand constant. + * @return A new {@code Expr} representing the logical min operation. + */ +export function logicalMin(left: string, right: any): LogicalMin; +export function logicalMin(left: Expr | string, right: Expr | any): LogicalMin { + const normalizedLeft = typeof left === 'string' ? Field.of(left) : left; + const normalizedRight = right instanceof Expr ? right : Constant.of(right); + return new LogicalMin(normalizedLeft, normalizedRight); +} + +/** + * @beta + * + * Creates an expression that checks if a field exists. + * + * ```typescript + * // Check if the document has a field named "phoneNumber" + * exists(Field.of("phoneNumber")); + * ``` + * + * @param value An expression evaluates to the name of the field to check. + * @return A new {@code Expr} representing the 'exists' check. + */ +export function exists(value: Expr): Exists; + +/** + * @beta + * + * Creates an expression that checks if a field exists. + * + * ```typescript + * // Check if the document has a field named "phoneNumber" + * exists("phoneNumber"); + * ``` + * + * @param field The field name to check. + * @return A new {@code Expr} representing the 'exists' check. + */ +export function exists(field: string): Exists; +export function exists(valueOrField: Expr | string): Exists { + const valueExpr = + valueOrField instanceof Expr ? valueOrField : Field.of(valueOrField); + return new Exists(valueExpr); +} + +/** + * @beta + * + * Creates an expression that checks if an expression evaluates to 'NaN' (Not a Number). + * + * ```typescript + * // Check if the result of a calculation is NaN + * isNaN(Field.of("value").divide(0)); + * ``` + * + * @param value The expression to check. + * @return A new {@code Expr} representing the 'isNaN' check. + */ +export function isNan(value: Expr): IsNan; + +/** + * @beta + * + * Creates an expression that checks if a field's value evaluates to 'NaN' (Not a Number). + * + * ```typescript + * // Check if the result of a calculation is NaN + * isNaN("value"); + * ``` + * + * @param value The name of the field to check. + * @return A new {@code Expr} representing the 'isNaN' check. + */ +export function isNan(value: string): IsNan; +export function isNan(value: Expr | string): IsNan { + const valueExpr = value instanceof Expr ? value : Field.of(value); + return new IsNan(valueExpr); +} + +/** + * @beta + * + * Creates an expression that reverses a string. + * + * ```typescript + * // Reverse the value of the 'myString' field. + * reverse(Field.of("myString")); + * ``` + * + * @param expr The expression representing the string to reverse. + * @return A new {@code Expr} representing the reversed string. + */ +export function reverse(expr: Expr): Reverse; + +/** + * @beta + * + * Creates an expression that reverses a string represented by a field. + * + * ```typescript + * // Reverse the value of the 'myString' field. + * reverse("myString"); + * ``` + * + * @param field The name of the field representing the string to reverse. + * @return A new {@code Expr} representing the reversed string. + */ +export function reverse(field: string): Reverse; +export function reverse(expr: Expr | string): Reverse { + const normalizedExpr = typeof expr === 'string' ? Field.of(expr) : expr; + return new Reverse(normalizedExpr); +} + +/** + * @beta + * + * Creates an expression that replaces the first occurrence of a substring within a string with another substring. + * + * ```typescript + * // Replace the first occurrence of "hello" with "hi" in the 'message' field. + * replaceFirst(Field.of("message"), "hello", "hi"); + * ``` + * + * @param value The expression representing the string to perform the replacement on. + * @param find The substring to search for. + * @param replace The substring to replace the first occurrence of 'find' with. + * @return A new {@code Expr} representing the string with the first occurrence replaced. + */ +export function replaceFirst( + value: Expr, + find: string, + replace: string +): ReplaceFirst; + +/** + * @beta + * + * Creates an expression that replaces the first occurrence of a substring within a string with another substring, + * where the substring to find and the replacement substring are specified by expressions. + * + * ```typescript + * // Replace the first occurrence of the value in 'findField' with the value in 'replaceField' in the 'message' field. + * replaceFirst(Field.of("message"), Field.of("findField"), Field.of("replaceField")); + * ``` + * + * @param value The expression representing the string to perform the replacement on. + * @param find The expression representing the substring to search for. + * @param replace The expression representing the substring to replace the first occurrence of 'find' with. + * @return A new {@code Expr} representing the string with the first occurrence replaced. */ -export function xor(left: FilterExpr, ...right: FilterExpr[]): Xor { - return new Xor([left, ...right]); -} +export function replaceFirst( + value: Expr, + find: Expr, + replace: Expr +): ReplaceFirst; /** * @beta * - * Creates a conditional expression that evaluates to a 'then' expression if a condition is true - * and an 'else' expression if the condition is false. + * Creates an expression that replaces the first occurrence of a substring within a string represented by a field with another substring. * * ```typescript - * // If 'age' is greater than 18, return "Adult"; otherwise, return "Minor". - * ifFunction( - * gt("age", 18), Constant.of("Adult"), Constant.of("Minor")); + * // Replace the first occurrence of "hello" with "hi" in the 'message' field. + * replaceFirst("message", "hello", "hi"); * ``` * - * @param condition The condition to evaluate. - * @param thenExpr The expression to evaluate if the condition is true. - * @param elseExpr The expression to evaluate if the condition is false. - * @return A new {@code Expr} representing the conditional expression. + * @param field The name of the field representing the string to perform the replacement on. + * @param find The substring to search for. + * @param replace The substring to replace the first occurrence of 'find' with. + * @return A new {@code Expr} representing the string with the first occurrence replaced. */ -export function ifFunction( - condition: FilterExpr, - thenExpr: Expr, - elseExpr: Expr -): If { - return new If(condition, thenExpr, elseExpr); +export function replaceFirst( + field: string, + find: string, + replace: string +): ReplaceFirst; +export function replaceFirst( + value: Expr | string, + find: Expr | string, + replace: Expr | string +): ReplaceFirst { + const normalizedValue = typeof value === 'string' ? Field.of(value) : value; + const normalizedFind = typeof find === 'string' ? Constant.of(find) : find; + const normalizedReplace = + typeof replace === 'string' ? Constant.of(replace) : replace; + return new ReplaceFirst(normalizedValue, normalizedFind, normalizedReplace); } /** * @beta * - * Creates an expression that negates a filter condition. + * Creates an expression that replaces all occurrences of a substring within a string with another substring. * * ```typescript - * // Find documents where the 'completed' field is NOT true - * not(eq("completed", true)); + * // Replace all occurrences of "hello" with "hi" in the 'message' field. + * replaceAll(Field.of("message"), "hello", "hi"); * ``` * - * @param filter The filter condition to negate. - * @return A new {@code Expr} representing the negated filter condition. + * @param value The expression representing the string to perform the replacement on. + * @param find The substring to search for. + * @param replace The substring to replace all occurrences of 'find' with. + * @return A new {@code Expr} representing the string with all occurrences replaced. */ -export function not(filter: FilterExpr): Not { - return new Not(filter); -} +export function replaceAll( + value: Expr, + find: string, + replace: string +): ReplaceAll; /** * @beta * - * Creates an expression that checks if a field exists. + * Creates an expression that replaces all occurrences of a substring within a string with another substring, + * where the substring to find and the replacement substring are specified by expressions. * * ```typescript - * // Check if the document has a field named "phoneNumber" - * exists(Field.of("phoneNumber")); + * // Replace all occurrences of the value in 'findField' with the value in 'replaceField' in the 'message' field. + * replaceAll(Field.of("message"), Field.of("findField"), Field.of("replaceField")); * ``` * - * @param value An expression evaluates to the name of the field to check. - * @return A new {@code Expr} representing the 'exists' check. + * @param value The expression representing the string to perform the replacement on. + * @param find The expression representing the substring to search for. + * @param replace The expression representing the substring to replace all occurrences of 'find' with. + * @return A new {@code Expr} representing the string with all occurrences replaced. */ -export function exists(value: Expr): Exists; +export function replaceAll(value: Expr, find: Expr, replace: Expr): ReplaceAll; /** * @beta * - * Creates an expression that checks if a field exists. + * Creates an expression that replaces all occurrences of a substring within a string represented by a field with another substring. * * ```typescript - * // Check if the document has a field named "phoneNumber" - * exists("phoneNumber"); + * // Replace all occurrences of "hello" with "hi" in the 'message' field. + * replaceAll("message", "hello", "hi"); * ``` * - * @param field The field name to check. - * @return A new {@code Expr} representing the 'exists' check. + * @param field The name of the field representing the string to perform the replacement on. + * @param find The substring to search for. + * @param replace The substring to replace all occurrences of 'find' with. + * @return A new {@code Expr} representing the string with all occurrences replaced. */ -export function exists(field: string): Exists; -export function exists(valueOrField: Expr | string): Exists { - const valueExpr = - valueOrField instanceof Expr ? valueOrField : Field.of(valueOrField); - return new Exists(valueExpr); +export function replaceAll( + field: string, + find: string, + replace: string +): ReplaceAll; +export function replaceAll( + value: Expr | string, + find: Expr | string, + replace: Expr | string +): ReplaceAll { + const normalizedValue = typeof value === 'string' ? Field.of(value) : value; + const normalizedFind = typeof find === 'string' ? Constant.of(find) : find; + const normalizedReplace = + typeof replace === 'string' ? Constant.of(replace) : replace; + return new ReplaceAll(normalizedValue, normalizedFind, normalizedReplace); } /** * @beta * - * Creates an expression that checks if an expression evaluates to 'NaN' (Not a Number). + * Creates an expression that calculates the byte length of a string in UTF-8, or just the length of a Blob. * * ```typescript - * // Check if the result of a calculation is NaN - * isNaN(Field.of("value").divide(0)); + * // Calculate the length of the 'myString' field in bytes. + * byteLength(Field.of("myString")); * ``` * - * @param value The expression to check. - * @return A new {@code Expr} representing the 'isNaN' check. + * @param expr The expression representing the string. + * @return A new {@code Expr} representing the length of the string in bytes. */ -export function isNan(value: Expr): IsNan; +export function byteLength(expr: Expr): ByteLength; /** * @beta * - * Creates an expression that checks if a field's value evaluates to 'NaN' (Not a Number). + * Creates an expression that calculates the length of a string represented by a field in UTF-8 bytes, or just the length of a Blob. * * ```typescript - * // Check if the result of a calculation is NaN - * isNaN("value"); + * // Calculate the length of the 'myString' field in bytes. + * byteLength("myString"); * ``` * - * @param value The name of the field to check. - * @return A new {@code Expr} representing the 'isNaN' check. + * @param field The name of the field representing the string. + * @return A new {@code Expr} representing the length of the string in bytes. */ -export function isNan(value: string): IsNan; -export function isNan(value: Expr | string): IsNan { - const valueExpr = value instanceof Expr ? value : Field.of(value); - return new IsNan(valueExpr); +export function byteLength(field: string): ByteLength; +export function byteLength(expr: Expr | string): ByteLength { + const normalizedExpr = typeof expr === 'string' ? Field.of(expr) : expr; + return new ByteLength(normalizedExpr); } /** * @beta * - * Creates an expression that calculates the length of a string field. + * Creates an expression that calculates the character length of a string field in UTF8. * * ```typescript - * // Get the length of the 'name' field + * // Get the character length of the 'name' field in UTF-8. * strLength("name"); * ``` * * @param field The name of the field containing the string. * @return A new {@code Expr} representing the length of the string. */ -export function strLength(field: string): StrLength; +export function charLength(field: string): CharLength; /** * @beta * - * Creates an expression that calculates the length of a string expression. + * Creates an expression that calculates the character length of a string expression in UTF-8. * * ```typescript - * // Get the length of the 'name' field + * // Get the character length of the 'name' field in UTF-8. * strLength(Field.of("name")); * ``` * * @param expr The expression representing the string to calculate the length of. * @return A new {@code Expr} representing the length of the string. */ -export function strLength(expr: Expr): StrLength; -export function strLength(value: Expr | string): StrLength { +export function charLength(expr: Expr): CharLength; +export function charLength(value: Expr | string): CharLength { const valueExpr = value instanceof Expr ? value : Field.of(value); - return new StrLength(valueExpr); + return new CharLength(valueExpr); } /** @@ -3888,13 +5418,13 @@ export function endsWith(expr: Expr | string, suffix: Expr | string): EndsWith { * * ```typescript * // Convert the 'name' field to lowercase - * toLowercase("name"); + * toLower("name"); * ``` * * @param expr The name of the field containing the string. * @return A new {@code Expr} representing the lowercase string. */ -export function toLowercase(expr: string): ToLowercase; +export function toLower(expr: string): ToLower; /** * @beta @@ -3903,15 +5433,15 @@ export function toLowercase(expr: string): ToLowercase; * * ```typescript * // Convert the 'name' field to lowercase - * toLowercase(Field.of("name")); + * toLower(Field.of("name")); * ``` * * @param expr The expression representing the string to convert to lowercase. * @return A new {@code Expr} representing the lowercase string. */ -export function toLowercase(expr: Expr): ToLowercase; -export function toLowercase(expr: Expr | string): ToLowercase { - return new ToLowercase(expr instanceof Expr ? expr : Field.of(expr)); +export function toLower(expr: Expr): ToLower; +export function toLower(expr: Expr | string): ToLower { + return new ToLower(expr instanceof Expr ? expr : Field.of(expr)); } /** @@ -3921,13 +5451,13 @@ export function toLowercase(expr: Expr | string): ToLowercase { * * ```typescript * // Convert the 'title' field to uppercase - * toUppercase("title"); + * toUpper("title"); * ``` * * @param expr The name of the field containing the string. * @return A new {@code Expr} representing the uppercase string. */ -export function toUppercase(expr: string): ToUppercase; +export function toUpper(expr: string): ToUpper; /** * @beta @@ -3942,9 +5472,9 @@ export function toUppercase(expr: string): ToUppercase; * @param expr The expression representing the string to convert to uppercase. * @return A new {@code Expr} representing the uppercase string. */ -export function toUppercase(expr: Expr): ToUppercase; -export function toUppercase(expr: Expr | string): ToUppercase { - return new ToUppercase(expr instanceof Expr ? expr : Field.of(expr)); +export function toUpper(expr: Expr): ToUpper; +export function toUpper(expr: Expr | string): ToUpper { + return new ToUpper(expr instanceof Expr ? expr : Field.of(expr)); } /** @@ -4582,6 +6112,434 @@ export function euclideanDistance( return new EuclideanDistance(expr1, expr2); } +/** + * @beta + * + * Creates an expression that calculates the length of a Firestore Vector. + * + * ```typescript + * // Get the vector length (dimension) of the field 'embedding'. + * vectorLength(Field.of("embedding")); + * ``` + * + * @param expr The expression representing the Firestore Vector. + * @return A new {@code Expr} representing the length of the array. + */ +export function vectorLength(expr: Expr): VectorLength; + +/** + * @beta + * + * Creates an expression that calculates the length of a Firestore Vector represented by a field. + * + * ```typescript + * // Get the vector length (dimension) of the field 'embedding'. + * vectorLength("embedding"); + * ``` + * + * @param field The name of the field representing the Firestore Vector. + * @return A new {@code Expr} representing the length of the array. + */ +export function vectorLength(field: string): VectorLength; +export function vectorLength(expr: Expr | string): VectorLength { + const normalizedExpr = typeof expr === 'string' ? Field.of(expr) : expr; + return new VectorLength(normalizedExpr); +} + +/** + * @beta + * + * Creates an expression that interprets an expression as the number of microseconds since the Unix epoch (1970-01-01 00:00:00 UTC) + * and returns a timestamp. + * + * ```typescript + * // Interpret the 'microseconds' field as microseconds since epoch. + * unixMicrosToTimestamp(Field.of("microseconds")); + * ``` + * + * @param expr The expression representing the number of microseconds since epoch. + * @return A new {@code Expr} representing the timestamp. + */ +export function unixMicrosToTimestamp(expr: Expr): UnixMicrosToTimestamp; + +/** + * @beta + * + * Creates an expression that interprets a field's value as the number of microseconds since the Unix epoch (1970-01-01 00:00:00 UTC) + * and returns a timestamp. + * + * ```typescript + * // Interpret the 'microseconds' field as microseconds since epoch. + * unixMicrosToTimestamp("microseconds"); + * ``` + * + * @param field The name of the field representing the number of microseconds since epoch. + * @return A new {@code Expr} representing the timestamp. + */ +export function unixMicrosToTimestamp(field: string): UnixMicrosToTimestamp; +export function unixMicrosToTimestamp( + expr: Expr | string +): UnixMicrosToTimestamp { + const normalizedExpr = typeof expr === 'string' ? Field.of(expr) : expr; + return new UnixMicrosToTimestamp(normalizedExpr); +} + +/** + * @beta + * + * Creates an expression that converts a timestamp expression to the number of microseconds since the Unix epoch (1970-01-01 00:00:00 UTC). + * + * ```typescript + * // Convert the 'timestamp' field to microseconds since epoch. + * timestampToUnixMicros(Field.of("timestamp")); + * ``` + * + * @param expr The expression representing the timestamp. + * @return A new {@code Expr} representing the number of microseconds since epoch. + */ +export function timestampToUnixMicros(expr: Expr): TimestampToUnixMicros; + +/** + * @beta + * + * Creates an expression that converts a timestamp field to the number of microseconds since the Unix epoch (1970-01-01 00:00:00 UTC). + * + * ```typescript + * // Convert the 'timestamp' field to microseconds since epoch. + * timestampToUnixMicros("timestamp"); + * ``` + * + * @param field The name of the field representing the timestamp. + * @return A new {@code Expr} representing the number of microseconds since epoch. + */ +export function timestampToUnixMicros(field: string): TimestampToUnixMicros; +export function timestampToUnixMicros( + expr: Expr | string +): TimestampToUnixMicros { + const normalizedExpr = typeof expr === 'string' ? Field.of(expr) : expr; + return new TimestampToUnixMicros(normalizedExpr); +} + +/** + * @beta + * + * Creates an expression that interprets an expression as the number of milliseconds since the Unix epoch (1970-01-01 00:00:00 UTC) + * and returns a timestamp. + * + * ```typescript + * // Interpret the 'milliseconds' field as milliseconds since epoch. + * unixMillisToTimestamp(Field.of("milliseconds")); + * ``` + * + * @param expr The expression representing the number of milliseconds since epoch. + * @return A new {@code Expr} representing the timestamp. + */ +export function unixMillisToTimestamp(expr: Expr): UnixMillisToTimestamp; + +/** + * @beta + * + * Creates an expression that interprets a field's value as the number of milliseconds since the Unix epoch (1970-01-01 00:00:00 UTC) + * and returns a timestamp. + * + * ```typescript + * // Interpret the 'milliseconds' field as milliseconds since epoch. + * unixMillisToTimestamp("milliseconds"); + * ``` + * + * @param field The name of the field representing the number of milliseconds since epoch. + * @return A new {@code Expr} representing the timestamp. + */ +export function unixMillisToTimestamp(field: string): UnixMillisToTimestamp; +export function unixMillisToTimestamp( + expr: Expr | string +): UnixMillisToTimestamp { + const normalizedExpr = typeof expr === 'string' ? Field.of(expr) : expr; + return new UnixMillisToTimestamp(normalizedExpr); +} + +/** + * @beta + * + * Creates an expression that converts a timestamp expression to the number of milliseconds since the Unix epoch (1970-01-01 00:00:00 UTC). + * + * ```typescript + * // Convert the 'timestamp' field to milliseconds since epoch. + * timestampToUnixMillis(Field.of("timestamp")); + * ``` + * + * @param expr The expression representing the timestamp. + * @return A new {@code Expr} representing the number of milliseconds since epoch. + */ +export function timestampToUnixMillis(expr: Expr): TimestampToUnixMillis; + +/** + * @beta + * + * Creates an expression that converts a timestamp field to the number of milliseconds since the Unix epoch (1970-01-01 00:00:00 UTC). + * + * ```typescript + * // Convert the 'timestamp' field to milliseconds since epoch. + * timestampToUnixMillis("timestamp"); + * ``` + * + * @param field The name of the field representing the timestamp. + * @return A new {@code Expr} representing the number of milliseconds since epoch. + */ +export function timestampToUnixMillis(field: string): TimestampToUnixMillis; +export function timestampToUnixMillis( + expr: Expr | string +): TimestampToUnixMillis { + const normalizedExpr = typeof expr === 'string' ? Field.of(expr) : expr; + return new TimestampToUnixMillis(normalizedExpr); +} + +/** + * @beta + * + * Creates an expression that interprets an expression as the number of seconds since the Unix epoch (1970-01-01 00:00:00 UTC) + * and returns a timestamp. + * + * ```typescript + * // Interpret the 'seconds' field as seconds since epoch. + * unixSecondsToTimestamp(Field.of("seconds")); + * ``` + * + * @param expr The expression representing the number of seconds since epoch. + * @return A new {@code Expr} representing the timestamp. + */ +export function unixSecondsToTimestamp(expr: Expr): UnixSecondsToTimestamp; + +/** + * @beta + * + * Creates an expression that interprets a field's value as the number of seconds since the Unix epoch (1970-01-01 00:00:00 UTC) + * and returns a timestamp. + * + * ```typescript + * // Interpret the 'seconds' field as seconds since epoch. + * unixSecondsToTimestamp("seconds"); + * ``` + * + * @param field The name of the field representing the number of seconds since epoch. + * @return A new {@code Expr} representing the timestamp. + */ +export function unixSecondsToTimestamp(field: string): UnixSecondsToTimestamp; +export function unixSecondsToTimestamp( + expr: Expr | string +): UnixSecondsToTimestamp { + const normalizedExpr = typeof expr === 'string' ? Field.of(expr) : expr; + return new UnixSecondsToTimestamp(normalizedExpr); +} + +/** + * @beta + * + * Creates an expression that converts a timestamp expression to the number of seconds since the Unix epoch (1970-01-01 00:00:00 UTC). + * + * ```typescript + * // Convert the 'timestamp' field to seconds since epoch. + * timestampToUnixSeconds(Field.of("timestamp")); + * ``` + * + * @param expr The expression representing the timestamp. + * @return A new {@code Expr} representing the number of seconds since epoch. + */ +export function timestampToUnixSeconds(expr: Expr): TimestampToUnixSeconds; + +/** + * @beta + * + * Creates an expression that converts a timestamp field to the number of seconds since the Unix epoch (1970-01-01 00:00:00 UTC). + * + * ```typescript + * // Convert the 'timestamp' field to seconds since epoch. + * timestampToUnixSeconds("timestamp"); + * ``` + * + * @param field The name of the field representing the timestamp. + * @return A new {@code Expr} representing the number of seconds since epoch. + */ +export function timestampToUnixSeconds(field: string): TimestampToUnixSeconds; +export function timestampToUnixSeconds( + expr: Expr | string +): TimestampToUnixSeconds { + const normalizedExpr = typeof expr === 'string' ? Field.of(expr) : expr; + return new TimestampToUnixSeconds(normalizedExpr); +} + +/** + * @beta + * + * Creates an expression that adds a specified amount of time to a timestamp. + * + * ```typescript + * // Add some duration determined by field 'unit' and 'amount' to the 'timestamp' field. + * timestampAdd(Field.of("timestamp"), Field.of("unit"), Field.of("amount")); + * ``` + * + * @param timestamp The expression representing the timestamp. + * @param unit The expression evaluates to unit of time, must be one of 'microsecond', 'millisecond', 'second', 'minute', 'hour', 'day'. + * @param amount The expression evaluates to amount of the unit. + * @return A new {@code Expr} representing the resulting timestamp. + */ +export function timestampAdd( + timestamp: Expr, + unit: Expr, + amount: Expr +): TimestampAdd; + +/** + * @beta + * + * Creates an expression that adds a specified amount of time to a timestamp. + * + * ```typescript + * // Add 1 day to the 'timestamp' field. + * timestampAdd(Field.of("timestamp"), "day", 1); + * ``` + * + * @param timestamp The expression representing the timestamp. + * @param unit The unit of time to add (e.g., "day", "hour"). + * @param amount The amount of time to add. + * @return A new {@code Expr} representing the resulting timestamp. + */ +export function timestampAdd( + timestamp: Expr, + unit: 'microsecond' | 'millisecond' | 'second' | 'minute' | 'hour' | 'day', + amount: number +): TimestampAdd; + +/** + * @beta + * + * Creates an expression that adds a specified amount of time to a timestamp represented by a field. + * + * ```typescript + * // Add 1 day to the 'timestamp' field. + * timestampAdd("timestamp", "day", 1); + * ``` + * + * @param field The name of the field representing the timestamp. + * @param unit The unit of time to add (e.g., "day", "hour"). + * @param amount The amount of time to add. + * @return A new {@code Expr} representing the resulting timestamp. + */ +export function timestampAdd( + field: string, + unit: 'microsecond' | 'millisecond' | 'second' | 'minute' | 'hour' | 'day', + amount: number +): TimestampAdd; +export function timestampAdd( + timestamp: Expr | string, + unit: + | Expr + | 'microsecond' + | 'millisecond' + | 'second' + | 'minute' + | 'hour' + | 'day', + amount: Expr | number +): TimestampAdd { + const normalizedTimestamp = + typeof timestamp === 'string' ? Field.of(timestamp) : timestamp; + const normalizedUnit = unit instanceof Expr ? unit : Constant.of(unit); + const normalizedAmount = + typeof amount === 'number' ? Constant.of(amount) : amount; + return new TimestampAdd( + normalizedTimestamp, + normalizedUnit, + normalizedAmount + ); +} + +/** + * @beta + * + * Creates an expression that subtracts a specified amount of time from a timestamp. + * + * ```typescript + * // Subtract some duration determined by field 'unit' and 'amount' from the 'timestamp' field. + * timestampSub(Field.of("timestamp"), Field.of("unit"), Field.of("amount")); + * ``` + * + * @param timestamp The expression representing the timestamp. + * @param unit The expression evaluates to unit of time, must be one of 'microsecond', 'millisecond', 'second', 'minute', 'hour', 'day'. + * @param amount The expression evaluates to amount of the unit. + * @return A new {@code Expr} representing the resulting timestamp. + */ +export function timestampSub( + timestamp: Expr, + unit: Expr, + amount: Expr +): TimestampSub; + +/** + * @beta + * + * Creates an expression that subtracts a specified amount of time from a timestamp. + * + * ```typescript + * // Subtract 1 day from the 'timestamp' field. + * timestampSub(Field.of("timestamp"), "day", 1); + * ``` + * + * @param timestamp The expression representing the timestamp. + * @param unit The unit of time to subtract (e.g., "day", "hour"). + * @param amount The amount of time to subtract. + * @return A new {@code Expr} representing the resulting timestamp. + */ +export function timestampSub( + timestamp: Expr, + unit: 'microsecond' | 'millisecond' | 'second' | 'minute' | 'hour' | 'day', + amount: number +): TimestampSub; + +/** + * @beta + * + * Creates an expression that subtracts a specified amount of time from a timestamp represented by a field. + * + * ```typescript + * // Subtract 1 day from the 'timestamp' field. + * timestampSub("timestamp", "day", 1); + * ``` + * + * @param field The name of the field representing the timestamp. + * @param unit The unit of time to subtract (e.g., "day", "hour"). + * @param amount The amount of time to subtract. + * @return A new {@code Expr} representing the resulting timestamp. + */ +export function timestampSub( + field: string, + unit: 'microsecond' | 'millisecond' | 'second' | 'minute' | 'hour' | 'day', + amount: number +): TimestampSub; +export function timestampSub( + timestamp: Expr | string, + unit: + | Expr + | 'microsecond' + | 'millisecond' + | 'second' + | 'minute' + | 'hour' + | 'day', + amount: Expr | number +): TimestampSub { + const normalizedTimestamp = + typeof timestamp === 'string' ? Field.of(timestamp) : timestamp; + const normalizedUnit = unit instanceof Expr ? unit : Constant.of(unit); + const normalizedAmount = + typeof amount === 'number' ? Constant.of(amount) : amount; + return new TimestampSub( + normalizedTimestamp, + normalizedUnit, + normalizedAmount + ); +} + /** * @beta * diff --git a/dev/src/index.ts b/dev/src/index.ts index e2ad0d76a..cfca3b879 100644 --- a/dev/src/index.ts +++ b/dev/src/index.ts @@ -155,10 +155,7 @@ export { arrayContains, arrayContainsAny, arrayContainsAll, - arrayFilter, arrayLength, - arrayTransform, - arrayElement, inAny, notInAny, and, @@ -168,14 +165,14 @@ export { not, exists, isNan, - strLength, + charLength, like, regexContains, regexMatch, startsWith, endsWith, - toLowercase, - toUppercase, + toLower, + toUpper, trim, strConcat, mapGet, @@ -191,6 +188,28 @@ export { genericFunction, ascending, descending, + bitLeftShift, + bitOr, + bitRightShift, + bitXor, + bitAnd, + bitNot, + timestampAdd, + timestampSub, + timestampToUnixMicros, + timestampToUnixMillis, + timestampToUnixSeconds, + unixMicrosToTimestamp, + unixMillisToTimestamp, + unixSecondsToTimestamp, + logicalMax, + logicalMin, + vectorLength, + byteLength, + reverse, + replaceAll, + replaceFirst, + mod, } from './expression'; const libVersion = require('../../package.json').version; diff --git a/dev/system-test/pipeline.ts b/dev/system-test/pipeline.ts index b3ef9b2b0..4bc990b92 100644 --- a/dev/system-test/pipeline.ts +++ b/dev/system-test/pipeline.ts @@ -38,9 +38,6 @@ import { and, arrayContains, arrayContainsAny, - arrayElement, - arrayFilter, - arrayTransform, avg, countAll, endsWith, @@ -284,7 +281,7 @@ describe.only('Pipeline class', () => { const results = await randomCol .pipeline() .where(lt('published', 1900)) - .distinct(Field.of('genre').toLowercase().as('lower_genre')) + .distinct(Field.of('genre').toLower().as('lower_genre')) .execute(); expectResults( results, @@ -444,41 +441,6 @@ describe.only('Pipeline class', () => { }); }); - it('arrayFilter works', async () => { - const results = await randomCol - .pipeline() - .select( - Field.of('tags') - .arrayFilter(arrayElement().eq('comedy')) - .as('filteredTags') - ) - .limit(1) - .execute(); - - expectResults(results, { - filteredTags: ['comedy'], - }); - }); - - it('arrayTransform works', async () => { - const results = await randomCol - .pipeline() - .select( - Field.of('tags') - .arrayTransform(arrayElement().strConcat('transformed')) - .as('transformedTags') - ) - .limit(1) - .execute(); - expectResults(results, { - transformedTags: [ - 'comedytransformed', - 'spacetransformed', - 'adventuretransformed', - ], - }); - }); - it('testStrConcat', async () => { const results = await randomCol .pipeline() @@ -525,7 +487,10 @@ describe.only('Pipeline class', () => { it('testLength', async () => { const results = await randomCol .pipeline() - .select(Field.of('title').strLength().as('titleLength'), Field.of('title')) + .select( + Field.of('title').charLength().as('titleLength'), + Field.of('title') + ) .where(gt('titleLength', 20)) .execute(); expectResults( @@ -541,7 +506,7 @@ describe.only('Pipeline class', () => { it('testToLowercase', async () => { const results = await randomCol .pipeline() - .select(Field.of('title').toLowercase().as('lowercaseTitle')) + .select(Field.of('title').toLower().as('lowercaseTitle')) .limit(1) .execute(); expectResults(results, { @@ -552,7 +517,7 @@ describe.only('Pipeline class', () => { it('testToUppercase', async () => { const results = await randomCol .pipeline() - .select(Field.of('author').toUppercase().as('uppercaseAuthor')) + .select(Field.of('author').toUpper().as('uppercaseAuthor')) .limit(1) .execute(); expectResults(results, {uppercaseAuthor: 'DOUGLAS ADAMS'}); diff --git a/types/firestore.d.ts b/types/firestore.d.ts index 5e13aa930..b8e95db59 100644 --- a/types/firestore.d.ts +++ b/types/firestore.d.ts @@ -3381,6 +3381,174 @@ declare namespace FirebaseFirestore { */ divide(other: any): Divide; + /** + * Creates an expression that calculates the modulo (remainder) of dividing this expression by another expression. + * + * ```typescript + * // Calculate the remainder of dividing the 'value' field by the 'divisor' field + * Field.of("value").mod(Field.of("divisor")); + * ``` + * + * @param other The expression to divide by. + * @return A new `Expr` representing the modulo operation. + */ + mod(other: Expr): Mod; + + /** + * Creates an expression that calculates the modulo (remainder) of dividing this expression by a constant value. + * + * ```typescript + * // Calculate the remainder of dividing the 'value' field by 10 + * Field.of("value").mod(10); + * ``` + * + * @param other The constant value to divide by. + * @return A new `Expr` representing the modulo operation. + */ + mod(other: any): Mod; + + /** + * Creates an expression that applies a bitwise AND operation between this expression and another expression. + * + * ```typescript + * // Calculate the bitwise AND of 'field1' and 'field2'. + * Field.of("field1").bitAnd(Field.of("field2")); + * ``` + * + * @param other The right operand expression. + * @return A new {@code Expr} representing the bitwise AND operation. + */ + bitAnd(other: Expr): BitAnd; + + /** + * Creates an expression that applies a bitwise AND operation between this expression and a constant value. + * + * ```typescript + * // Calculate the bitwise AND of 'field1' and 0xFF. + * Field.of("field1").bitAnd(0xFF); + * ``` + * + * @param other The right operand constant. + * @return A new {@code Expr} representing the bitwise AND operation. + */ + bitAnd(other: any): BitAnd; + + /** + * Creates an expression that applies a bitwise OR operation between this expression and another expression. + * + * ```typescript + * // Calculate the bitwise OR of 'field1' and 'field2'. + * Field.of("field1").bitOr(Field.of("field2")); + * ``` + * + * @param other The right operand expression. + * @return A new {@code Expr} representing the bitwise OR operation. + */ + bitOr(other: Expr): BitOr; + + /** + * Creates an expression that applies a bitwise OR operation between this expression and a constant value. + * + * ```typescript + * // Calculate the bitwise OR of 'field1' and 0xFF. + * Field.of("field1").bitOr(0xFF); + * ``` + * + * @param other The right operand constant. + * @return A new {@code Expr} representing the bitwise OR operation. + */ + bitOr(other: any): BitOr; + + /** + * Creates an expression that applies a bitwise XOR operation between this expression and another expression. + * + * ```typescript + * // Calculate the bitwise XOR of 'field1' and 'field2'. + * Field.of("field1").bitXor(Field.of("field2")); + * ``` + * + * @param other The right operand expression. + * @return A new {@code Expr} representing the bitwise XOR operation. + */ + bitXor(other: Expr): BitXor; + + /** + * Creates an expression that applies a bitwise XOR operation between this expression and a constant value. + * + * ```typescript + * // Calculate the bitwise XOR of 'field1' and 0xFF. + * Field.of("field1").bitXor(0xFF); + * ``` + * + * @param other The right operand constant. + * @return A new {@code Expr} representing the bitwise XOR operation. + */ + bitXor(other: any): BitXor; + + /** + * Creates an expression that applies a bitwise NOT operation to this expression. + * + * ```typescript + * // Calculate the bitwise NOT of 'field1'. + * Field.of("field1").bitNot(); + * ``` + * + * @return A new {@code Expr} representing the bitwise NOT operation. + */ + bitNot(): BitNot; + + /** + * Creates an expression that applies a bitwise left shift operation between this expression and another expression. + * + * ```typescript + * // Calculate the bitwise left shift of 'field1' by 'field2' bits. + * Field.of("field1").bitLeftShift(Field.of("field2")); + * ``` + * + * @param other The right operand expression representing the number of bits to shift. + * @return A new {@code Expr} representing the bitwise left shift operation. + */ + bitLeftShift(other: Expr): BitLeftShift; + + /** + * Creates an expression that applies a bitwise left shift operation between this expression and a constant value. + * + * ```typescript + * // Calculate the bitwise left shift of 'field1' by 2 bits. + * Field.of("field1").bitLeftShift(2); + * ``` + * + * @param other The right operand constant representing the number of bits to shift. + * @return A new {@code Expr} representing the bitwise left shift operation. + */ + bitLeftShift(other: number): BitLeftShift; + + /** + * Creates an expression that applies a bitwise right shift operation between this expression and another expression. + * + * ```typescript + * // Calculate the bitwise right shift of 'field1' by 'field2' bits. + * Field.of("field1").bitRightShift(Field.of("field2")); + * ``` + * + * @param other The right operand expression representing the number of bits to shift. + * @return A new {@code Expr} representing the bitwise right shift operation. + */ + bitRightShift(other: Expr): BitRightShift; + + /** + * Creates an expression that applies a bitwise right shift operation between this expression and a constant value. + * + * ```typescript + * // Calculate the bitwise right shift of 'field1' by 2 bits. + * Field.of("field1").bitRightShift(2); + * ``` + * + * @param other The right operand constant representing the number of bits to shift. + * @return A new {@code Expr} representing the bitwise right shift operation. + */ + bitRightShift(other: number): BitRightShift; + /** * Creates an expression that checks if this expression is equal to another expression. * @@ -3645,22 +3813,6 @@ declare namespace FirebaseFirestore { */ arrayContainsAny(...values: any[]): ArrayContainsAny; - /** - * Creates an expression that filters elements from an array using the given {@link - * FilterCondition} and returns the filtered elements as a new array. - * - * ```typescript - * // Get items from the 'inventoryPrices' array where the array item is greater than 0 - * // Note we use {@link Function#arrayElement} to represent array elements to construct a - * // filtering condition. - * Field.of("inventoryPrices").arrayFilter(arrayElement().gt(0)); - * ``` - * - * @param filter The {@link FilterCondition} to apply to the array elements. - * @return A new `Expr` representing the filtered array. - */ - arrayFilter(filter: FilterExpr): ArrayFilter; - /** * Creates an expression that calculates the length of an array. * @@ -3673,20 +3825,6 @@ declare namespace FirebaseFirestore { */ arrayLength(): ArrayLength; - /** - * Creates an expression that applies a transformation function to each element in an array and - * returns the new array as the result of the evaluation. - * - * ```typescript - * // Convert all strings in the 'names' array to uppercase - * Field.of("names").arrayTransform(arrayElement().toUppercase()); - * ``` - * - * @param transform The {@link Function} to apply to each array element. - * @return A new `Expr` representing the transformed array. - */ - arrayTransform(transform: Function): ArrayTransform; - /** * Creates an expression that checks if this expression is equal to any of the provided values or * expressions. @@ -3740,16 +3878,16 @@ declare namespace FirebaseFirestore { exists(): Exists; /** - * Creates an expression that calculates the length of a string. + * Creates an expression that calculates the character length of a string in UTF-8. * * ```typescript - * // Get the length of the 'name' field + * // Get the character length of the 'name' field of UTF-8. * Field.of("name").strLength(); * ``` * * @return A new `Expr` representing the length of the string. */ - strLength(): StrLength; + charLength(): CharLength; /** * Creates an expression that performs a case-sensitive string comparison. @@ -3890,24 +4028,24 @@ declare namespace FirebaseFirestore { * * ```typescript * // Convert the 'name' field to lowercase - * Field.of("name").toLowerCase(); + * Field.of("name").toLower(); * ``` * * @return A new `Expr` representing the lowercase string. */ - toLowercase(): ToLowercase; + toLower(): ToLower; /** * Creates an expression that converts a string to uppercase. * * ```typescript * // Convert the 'title' field to uppercase - * Field.of("title").toUpperCase(); + * Field.of("title").toUpper(); * ``` * * @return A new `Expr` representing the uppercase string. */ - toUppercase(): ToUppercase; + toUpper(): ToUpper; /** * Creates an expression that removes leading and trailing whitespace from a string. @@ -3934,6 +4072,88 @@ declare namespace FirebaseFirestore { */ strConcat(...elements: (string | Expr)[]): StrConcat; + /** + * Creates an expression that reverses this string expression. + * + * ```typescript + * // Reverse the value of the 'myString' field. + * Field.of("myString").reverse(); + * ``` + * + * @return A new {@code Expr} representing the reversed string. + */ + reverse(): Reverse; + + /** + * Creates an expression that replaces the first occurrence of a substring within this string expression with another substring. + * + * ```typescript + * // Replace the first occurrence of "hello" with "hi" in the 'message' field + * Field.of("message").replaceFirst("hello", "hi"); + * ``` + * + * @param find The substring to search for. + * @param replace The substring to replace the first occurrence of 'find' with. + * @return A new {@code Expr} representing the string with the first occurrence replaced. + */ + replaceFirst(find: string, replace: string): ReplaceFirst; + + /** + * Creates an expression that replaces the first occurrence of a substring within this string expression with another substring, + * where the substring to find and the replacement substring are specified by expressions. + * + * ```typescript + * // Replace the first occurrence of the value in 'findField' with the value in 'replaceField' in the 'message' field + * Field.of("message").replaceFirst(Field.of("findField"), Field.of("replaceField")); + * ``` + * + * @param find The expression representing the substring to search for. + * @param replace The expression representing the substring to replace the first occurrence of 'find' with. + * @return A new {@code Expr} representing the string with the first occurrence replaced. + */ + replaceFirst(find: Expr, replace: Expr): ReplaceFirst; + + /** + * Creates an expression that replaces all occurrences of a substring within this string expression with another substring. + * + * ```typescript + * // Replace all occurrences of "hello" with "hi" in the 'message' field + * Field.of("message").replaceAll("hello", "hi"); + * ``` + * + * @param find The substring to search for. + * @param replace The substring to replace all occurrences of 'find' with. + * @return A new {@code Expr} representing the string with all occurrences replaced. + */ + replaceAll(find: string, replace: string): ReplaceAll; + + /** + * Creates an expression that replaces all occurrences of a substring within this string expression with another substring, + * where the substring to find and the replacement substring are specified by expressions. + * + * ```typescript + * // Replace all occurrences of the value in 'findField' with the value in 'replaceField' in the 'message' field + * Field.of("message").replaceAll(Field.of("findField"), Field.of("replaceField")); + * ``` + * + * @param find The expression representing the substring to search for. + * @param replace The expression representing the substring to replace all occurrences of 'find' with. + * @return A new {@code Expr} representing the string with all occurrences replaced. + */ + replaceAll(find: Expr, replace: Expr): ReplaceAll; + + /** + * Creates an expression that calculates the length of this string expression in bytes. + * + * ```typescript + * // Calculate the length of the 'myString' field in bytes. + * Field.of("myString").byteLength(); + * ``` + * + * @return A new {@code Expr} representing the length of the string in bytes. + */ + byteLength(): ByteLength; + /** * Accesses a value from a map (object) field using the provided key. * @@ -4009,6 +4229,70 @@ declare namespace FirebaseFirestore { */ max(): Max; + /** + * Creates an expression that returns the larger value between this expression and another expression, based on Firestore's value type ordering. + * + * ```typescript + * // Returns the larger value between the 'timestamp' field and the current timestamp. + * Field.of("timestamp").logicalMax(Function.currentTimestamp()); + * ``` + * + * @param other The expression to compare with. + * @return A new {@code Expr} representing the logical max operation. + */ + logicalMax(other: Expr): LogicalMax; + + /** + * Creates an expression that returns the larger value between this expression and a constant value, based on Firestore's value type ordering. + * + * ```typescript + * // Returns the larger value between the 'value' field and 10. + * Field.of("value").logicalMax(10); + * ``` + * + * @param other The constant value to compare with. + * @return A new {@code Expr} representing the logical max operation. + */ + logicalMax(other: any): LogicalMax; + + /** + * Creates an expression that returns the smaller value between this expression and another expression, based on Firestore's value type ordering. + * + * ```typescript + * // Returns the smaller value between the 'timestamp' field and the current timestamp. + * Field.of("timestamp").logicalMin(Function.currentTimestamp()); + * ``` + * + * @param other The expression to compare with. + * @return A new {@code Expr} representing the logical min operation. + */ + logicalMin(other: Expr): LogicalMin; + + /** + * Creates an expression that returns the smaller value between this expression and a constant value, based on Firestore's value type ordering. + * + * ```typescript + * // Returns the smaller value between the 'value' field and 10. + * Field.of("value").logicalMin(10); + * ``` + * + * @param other The constant value to compare with. + * @return A new {@code Expr} representing the logical min operation. + */ + logicalMin(other: any): LogicalMin; + + /** + * Creates an expression that calculates the length (number of dimensions) of this Firestore Vector expression. + * + * ```typescript + * // Get the vector length (dimension) of the field 'embedding'. + * Field.of("embedding").vectorLength(); + * ``` + * + * @return A new {@code Expr} representing the length of the vector. + */ + vectorLength(): VectorLength; + /** * Calculates the cosine distance between two vectors. * @@ -4124,6 +4408,155 @@ declare namespace FirebaseFirestore { */ euclideanDistance(other: number[]): EuclideanDistance; + /** + * 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. + * + * ```typescript + * // Interpret the 'microseconds' field as microseconds since epoch. + * Field.of("microseconds").unixMicrosToTimestamp(); + * ``` + * + * @return A new {@code Expr} representing the timestamp. + */ + unixMicrosToTimestamp(): UnixMicrosToTimestamp; + + /** + * Creates an expression that converts this timestamp expression to the number of microseconds since the Unix epoch (1970-01-01 00:00:00 UTC). + * + * ```typescript + * // Convert the 'timestamp' field to microseconds since epoch. + * Field.of("timestamp").timestampToUnixMicros(); + * ``` + * + * @return A new {@code Expr} representing the number of microseconds since epoch. + */ + timestampToUnixMicros(): TimestampToUnixMicros; + + /** + * 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. + * + * ```typescript + * // Interpret the 'milliseconds' field as milliseconds since epoch. + * Field.of("milliseconds").unixMillisToTimestamp(); + * ``` + * + * @return A new {@code Expr} representing the timestamp. + */ + unixMillisToTimestamp(): UnixMillisToTimestamp; + + /** + * Creates an expression that converts this timestamp expression to the number of milliseconds since the Unix epoch (1970-01-01 00:00:00 UTC). + * + * ```typescript + * // Convert the 'timestamp' field to milliseconds since epoch. + * Field.of("timestamp").timestampToUnixMillis(); + * ``` + * + * @return A new {@code Expr} representing the number of milliseconds since epoch. + */ + timestampToUnixMillis(): TimestampToUnixMillis; + + /** + * 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. + * + * ```typescript + * // Interpret the 'seconds' field as seconds since epoch. + * Field.of("seconds").unixSecondsToTimestamp(); + * ``` + * + * @return A new {@code Expr} representing the timestamp. + */ + unixSecondsToTimestamp(): UnixSecondsToTimestamp; + + /** + * Creates an expression that converts this timestamp expression to the number of seconds since the Unix epoch (1970-01-01 00:00:00 UTC). + * + * ```typescript + * // Convert the 'timestamp' field to seconds since epoch. + * Field.of("timestamp").timestampToUnixSeconds(); + * ``` + * + * @return A new {@code Expr} representing the number of seconds since epoch. + */ + timestampToUnixSeconds(): TimestampToUnixSeconds; + + /** + * Creates an expression that adds a specified amount of time to this timestamp expression. + * + * ```typescript + * // Add some duration determined by field 'unit' and 'amount' to the 'timestamp' field. + * Field.of("timestamp").timestampAdd(Field.of("unit"), Field.of("amount")); + * ``` + * + * @param unit The expression evaluates to unit of time, must be one of 'microsecond', 'millisecond', 'second', 'minute', 'hour', 'day'. + * @param amount The expression evaluates to amount of the unit. + * @return A new {@code Expr} representing the resulting timestamp. + */ + timestampAdd(unit: Expr, amount: Expr): TimestampAdd; + + /** + * Creates an expression that adds a specified amount of time to this timestamp expression. + * + * ```typescript + * // Add 1 day to the 'timestamp' field. + * Field.of("timestamp").timestampAdd("day", 1); + * ``` + * + * @param unit The unit of time to add (e.g., "day", "hour"). + * @param amount The amount of time to add. + * @return A new {@code Expr} representing the resulting timestamp. + */ + timestampAdd( + unit: + | 'microsecond' + | 'millisecond' + | 'second' + | 'minute' + | 'hour' + | 'day', + amount: number + ): TimestampAdd; + + /** + * Creates an expression that subtracts a specified amount of time from this timestamp expression. + * + * ```typescript + * // Subtract some duration determined by field 'unit' and 'amount' from the 'timestamp' field. + * Field.of("timestamp").timestampSub(Field.of("unit"), Field.of("amount")); + * ``` + * + * @param unit The expression evaluates to unit of time, must be one of 'microsecond', 'millisecond', 'second', 'minute', 'hour', 'day'. + * @param amount The expression evaluates to amount of the unit. + * @return A new {@code Expr} representing the resulting timestamp. + */ + timestampSub(unit: Expr, amount: Expr): TimestampSub; + + /** + * Creates an expression that subtracts a specified amount of time from this timestamp expression. + * + * ```typescript + * // Subtract 1 day from the 'timestamp' field. + * Field.of("timestamp").timestampSub("day", 1); + * ``` + * + * @param unit The unit of time to subtract (e.g., "day", "hour"). + * @param amount The amount of time to subtract. + * @return A new {@code Expr} representing the resulting timestamp. + */ + timestampSub( + unit: + | 'microsecond' + | 'millisecond' + | 'second' + | 'minute' + | 'hour' + | 'day', + amount: number + ): TimestampSub; + /** * Creates an {@link Ordering} that sorts documents in ascending order based on this expression. * @@ -4425,8 +4858,43 @@ declare namespace FirebaseFirestore { /** * @beta */ - export class Eq extends Function implements FilterCondition { - filterable: true; + export class Mod extends Function {} + + /** + * @beta + */ + export class BitAnd extends Function {} + + /** + * @beta + */ + export class BitOr extends Function {} + + /** + * @beta + */ + export class BitXor extends Function {} + + /** + * @beta + */ + export class BitNot extends Function {} + + /** + * @beta + */ + export class BitLeftShift extends Function {} + + /** + * @beta + */ + export class BitRightShift extends Function {} + + /** + * @beta + */ + export class Eq extends Function implements FilterCondition { + filterable: true; } /** @@ -4490,26 +4958,11 @@ declare namespace FirebaseFirestore { filterable: true; } - /** - * @beta - */ - export class ArrayFilter extends Function {} - /** * @beta */ export class ArrayLength extends Function {} - /** - * @beta - */ - export class ArrayTransform extends Function {} - - /** - * @beta - */ - export class ArrayElement extends Function {} - /** * @beta */ @@ -4569,7 +5022,17 @@ declare namespace FirebaseFirestore { /** * @beta */ - export class StrLength extends Function {} + export class LogicalMax extends Function {} + + /** + * @beta + */ + export class LogicalMin extends Function {} + + /** + * @beta + */ + export class CharLength extends Function {} /** * @beta @@ -4609,12 +5072,12 @@ declare namespace FirebaseFirestore { /** * @beta */ - export class ToLowercase extends Function {} + export class ToLower extends Function {} /** * @beta */ - export class ToUppercase extends Function {} + export class ToUpper extends Function {} /** * @beta @@ -4626,6 +5089,26 @@ declare namespace FirebaseFirestore { */ export class StrConcat extends Function {} + /** + * @beta + */ + export class Reverse extends Function {} + + /** + * @beta + */ + export class ReplaceFirst extends Function {} + + /** + * @beta + */ + export class ReplaceAll extends Function {} + + /** + * @beta + */ + export class ByteLength extends Function {} + /** * @beta */ @@ -4681,6 +5164,51 @@ declare namespace FirebaseFirestore { */ export class EuclideanDistance extends Function {} + /** + * @beta + */ + export class VectorLength extends Function {} + + /** + * @beta + */ + export class UnixMicrosToTimestamp extends Function {} + + /** + * @beta + */ + export class TimestampToUnixMicros extends Function {} + + /** + * @beta + */ + export class UnixMillisToTimestamp extends Function {} + + /** + * @beta + */ + export class TimestampToUnixMillis extends Function {} + + /** + * @beta + */ + export class UnixSecondsToTimestamp extends Function {} + + /** + * @beta + */ + export class TimestampToUnixSeconds extends Function {} + + /** + * @beta + */ + export class TimestampAdd extends Function {} + + /** + * @beta + */ + export class TimestampSub extends Function {} + /** * @beta * @@ -4940,1067 +5468,1785 @@ declare namespace FirebaseFirestore { /** * @beta * - * Creates an expression that checks if two expressions are equal. + * Creates an expression that calculates the modulo (remainder) of dividing two expressions. * * ```typescript - * // Check if the 'age' field is equal to an expression - * eq(Field.of("age"), Field.of("minAge").add(10)); + * // Calculate the remainder of dividing 'field1' by 'field2'. + * mod(Field.of("field1"), Field.of("field2")); * ``` * - * @param left The first expression to compare. - * @param right The second expression to compare. - * @return A new `Expr` representing the equality comparison. + * @param left The dividend expression. + * @param right The divisor expression. + * @return A new {@code Expr} representing the modulo operation. */ - export function eq(left: Expr, right: Expr): Eq; + export function mod(left: Expr, right: Expr): Mod; /** * @beta * - * Creates an expression that checks if an expression is equal to a constant value. + * Creates an expression that calculates the modulo (remainder) of dividing an expression by a constant. * * ```typescript - * // Check if the 'age' field is equal to 21 - * eq(Field.of("age"), 21); + * // Calculate the remainder of dividing 'field1' by 5. + * mod(Field.of("field1"), 5); * ``` * - * @param left The expression to compare. - * @param right The constant value to compare to. - * @return A new `Expr` representing the equality comparison. + * @param left The dividend expression. + * @param right The divisor constant. + * @return A new {@code Expr} representing the modulo operation. */ - export function eq(left: Expr, right: any): Eq; + export function mod(left: Expr, right: any): Mod; /** * @beta * - * Creates an expression that checks if a field's value is equal to an expression. + * Creates an expression that calculates the modulo (remainder) of dividing a field's value by an expression. * * ```typescript - * // Check if the 'age' field is equal to the 'limit' field - * eq("age", Field.of("limit")); + * // Calculate the remainder of dividing 'field1' by 'field2'. + * mod("field1", Field.of("field2")); * ``` * - * @param left The field name to compare. - * @param right The expression to compare to. - * @return A new `Expr` representing the equality comparison. + * @param left The dividend field name. + * @param right The divisor expression. + * @return A new {@code Expr} representing the modulo operation. */ - export function eq(left: string, right: Expr): Eq; + export function mod(left: string, right: Expr): Mod; /** * @beta * - * Creates an expression that checks if a field's value is equal to a constant value. + * Creates an expression that calculates the modulo (remainder) of dividing a field's value by a constant. * * ```typescript - * // Check if the 'city' field is equal to string constant "London" - * eq("city", "London"); + * // Calculate the remainder of dividing 'field1' by 5. + * mod("field1", 5); * ``` * - * @param left The field name to compare. - * @param right The constant value to compare to. - * @return A new `Expr` representing the equality comparison. + * @param left The dividend field name. + * @param right The divisor constant. + * @return A new {@code Expr} representing the modulo operation. */ - export function eq(left: string, right: any): Eq; + export function mod(left: string, right: any): Mod; /** * @beta * - * Creates an expression that checks if two expressions are not equal. + * Creates an expression that applies a bitwise AND operation between two expressions. * * ```typescript - * // Check if the 'status' field is not equal to field 'finalState' - * neq(Field.of("status"), Field.of("finalState")); + * // Calculate the bitwise AND of 'field1' and 'field2'. + * bitAnd(Field.of("field1"), Field.of("field2")); * ``` * - * @param left The first expression to compare. - * @param right The second expression to compare. - * @return A new `Expr` representing the inequality comparison. + * @param left The left operand expression. + * @param right The right operand expression. + * @return A new {@code Expr} representing the bitwise AND operation. */ - export function neq(left: Expr, right: Expr): Neq; + export function bitAnd(left: Expr, right: Expr): BitAnd; /** * @beta * - * Creates an expression that checks if an expression is not equal to a constant value. + * Creates an expression that applies a bitwise AND operation between an expression and a constant. * * ```typescript - * // Check if the 'status' field is not equal to "completed" - * neq(Field.of("status"), "completed"); + * // Calculate the bitwise AND of 'field1' and 0xFF. + * bitAnd(Field.of("field1"), 0xFF); * ``` * - * @param left The expression to compare. - * @param right The constant value to compare to. - * @return A new `Expr` representing the inequality comparison. + * @param left The left operand expression. + * @param right The right operand constant. + * @return A new {@code Expr} representing the bitwise AND operation. */ - export function neq(left: Expr, right: any): Neq; + export function bitAnd(left: Expr, right: any): BitAnd; /** * @beta * - * Creates an expression that checks if a field's value is not equal to an expression. + * Creates an expression that applies a bitwise AND operation between a field and an expression. * * ```typescript - * // Check if the 'status' field is not equal to the value of 'expectedStatus' - * neq("status", Field.of("expectedStatus")); + * // Calculate the bitwise AND of 'field1' and 'field2'. + * bitAnd("field1", Field.of("field2")); * ``` * - * @param left The field name to compare. - * @param right The expression to compare to. - * @return A new `Expr` representing the inequality comparison. + * @param left The left operand field name. + * @param right The right operand expression. + * @return A new {@code Expr} representing the bitwise AND operation. */ - export function neq(left: string, right: Expr): Neq; + export function bitAnd(left: string, right: Expr): BitAnd; /** * @beta * - * Creates an expression that checks if a field's value is not equal to a constant value. + * Creates an expression that applies a bitwise AND operation between a field and a constant. * * ```typescript - * // Check if the 'country' field is not equal to "USA" - * neq("country", "USA"); + * // Calculate the bitwise AND of 'field1' and 0xFF. + * bitAnd("field1", 0xFF); * ``` * - * @param left The field name to compare. - * @param right The constant value to compare to. - * @return A new `Expr` representing the inequality comparison. + * @param left The left operand field name. + * @param right The right operand constant. + * @return A new {@code Expr} representing the bitwise AND operation. */ - export function neq(left: string, right: any): Neq; + export function bitAnd(left: string, right: any): BitAnd; /** * @beta * - * Creates an expression that checks if the first expression is less than the second expression. + * Creates an expression that applies a bitwise OR operation between two expressions. * * ```typescript - * // Check if the 'age' field is less than 30 - * lt(Field.of("age"), Field.of("limit")); + * // Calculate the bitwise OR of 'field1' and 'field2'. + * bitOr(Field.of("field1"), Field.of("field2")); * ``` * - * @param left The first expression to compare. - * @param right The second expression to compare. - * @return A new `Expr` representing the less than comparison. + * @param left The left operand expression. + * @param right The right operand expression. + * @return A new {@code Expr} representing the bitwise OR operation. */ - export function lt(left: Expr, right: Expr): Lt; + export function bitOr(left: Expr, right: Expr): BitOr; /** * @beta * - * Creates an expression that checks if an expression is less than a constant value. + * Creates an expression that applies a bitwise OR operation between an expression and a constant. * * ```typescript - * // Check if the 'age' field is less than 30 - * lt(Field.of("age"), 30); + * // Calculate the bitwise OR of 'field1' and 0xFF. + * bitOr(Field.of("field1"), 0xFF); * ``` * - * @param left The expression to compare. - * @param right The constant value to compare to. - * @return A new `Expr` representing the less than comparison. + * @param left The left operand expression. + * @param right The right operand constant. + * @return A new {@code Expr} representing the bitwise OR operation. */ - export function lt(left: Expr, right: any): Lt; + export function bitOr(left: Expr, right: any): BitOr; /** * @beta * - * Creates an expression that checks if a field's value is less than an expression. + * Creates an expression that applies a bitwise OR operation between a field and an expression. * * ```typescript - * // Check if the 'age' field is less than the 'limit' field - * lt("age", Field.of("limit")); + * // Calculate the bitwise OR of 'field1' and 'field2'. + * bitOr("field1", Field.of("field2")); * ``` * - * @param left The field name to compare. - * @param right The expression to compare to. - * @return A new `Expr` representing the less than comparison. + * @param left The left operand field name. + * @param right The right operand expression. + * @return A new {@code Expr} representing the bitwise OR operation. */ - export function lt(left: string, right: Expr): Lt; + export function bitOr(left: string, right: Expr): BitOr; /** * @beta * - * Creates an expression that checks if a field's value is less than a constant value. + * Creates an expression that applies a bitwise OR operation between a field and a constant. * * ```typescript - * // Check if the 'price' field is less than 50 - * lt("price", 50); + * // Calculate the bitwise OR of 'field1' and 0xFF. + * bitOr("field1", 0xFF); * ``` * - * @param left The field name to compare. - * @param right The constant value to compare to. - * @return A new `Expr` representing the less than comparison. + * @param left The left operand field name. + * @param right The right operand constant. + * @return A new {@code Expr} representing the bitwise OR operation. */ - export function lt(left: string, right: any): Lt; + export function bitOr(left: string, right: any): BitOr; /** * @beta * - * Creates an expression that checks if the first expression is less than or equal to the second - * expression. + * Creates an expression that applies a bitwise XOR operation between two expressions. * * ```typescript - * // Check if the 'quantity' field is less than or equal to 20 - * lte(Field.of("quantity"), Field.of("limit")); + * // Calculate the bitwise XOR of 'field1' and 'field2'. + * bitXor(Field.of("field1"), Field.of("field2")); * ``` * - * @param left The first expression to compare. - * @param right The second expression to compare. - * @return A new `Expr` representing the less than or equal to comparison. + * @param left The left operand expression. + * @param right The right operand expression. + * @return A new {@code Expr} representing the bitwise XOR operation. */ - export function lte(left: Expr, right: Expr): Lte; + export function bitXor(left: Expr, right: Expr): BitXor; /** * @beta * - * Creates an expression that checks if an expression is less than or equal to a constant value. + * Creates an expression that applies a bitwise XOR operation between an expression and a constant. * * ```typescript - * // Check if the 'quantity' field is less than or equal to 20 - * lte(Field.of("quantity"), 20); + * // Calculate the bitwise XOR of 'field1' and 0xFF. + * bitXor(Field.of("field1"), 0xFF); * ``` * - * @param left The expression to compare. - * @param right The constant value to compare to. - * @return A new `Expr` representing the less than or equal to comparison. + * @param left The left operand expression. + * @param right The right operand constant. + * @return A new {@code Expr} representing the bitwise XOR operation. */ - export function lte(left: Expr, right: any): Lte; + export function bitXor(left: Expr, right: any): BitXor; /** - * Creates an expression that checks if a field's value is less than or equal to an expression. + * @beta + * + * Creates an expression that applies a bitwise XOR operation between a field and an expression. * * ```typescript - * // Check if the 'quantity' field is less than or equal to the 'limit' field - * lte("quantity", Field.of("limit")); + * // Calculate the bitwise XOR of 'field1' and 'field2'. + * bitXor("field1", Field.of("field2")); * ``` * - * @param left The field name to compare. - * @param right The expression to compare to. - * @return A new `Expr` representing the less than or equal to comparison. + * @param left The left operand field name. + * @param right The right operand expression. + * @return A new {@code Expr} representing the bitwise XOR operation. */ - export function lte(left: string, right: Expr): Lte; + export function bitXor(left: string, right: Expr): BitXor; /** * @beta * - * Creates an expression that checks if a field's value is less than or equal to a constant value. + * Creates an expression that applies a bitwise XOR operation between a field and a constant. * * ```typescript - * // Check if the 'score' field is less than or equal to 70 - * lte("score", 70); + * // Calculate the bitwise XOR of 'field1' and 0xFF. + * bitXor("field1", 0xFF); * ``` * - * @param left The field name to compare. - * @param right The constant value to compare to. - * @return A new `Expr` representing the less than or equal to comparison. + * @param left The left operand field name. + * @param right The right operand constant. + * @return A new {@code Expr} representing the bitwise XOR operation. */ - export function lte(left: string, right: any): Lte; + export function bitXor(left: string, right: any): BitXor; /** * @beta * - * Creates an expression that checks if the first expression is greater than the second - * expression. + * Creates an expression that applies a bitwise NOT operation to an expression. * * ```typescript - * // Check if the 'age' field is greater than 18 - * gt(Field.of("age"), Constant(9).add(9)); + * // Calculate the bitwise NOT of 'field1'. + * bitNot(Field.of("field1")); * ``` * - * @param left The first expression to compare. - * @param right The second expression to compare. - * @return A new `Expr` representing the greater than comparison. + * @param operand The operand expression. + * @return A new {@code Expr} representing the bitwise NOT operation. */ - export function gt(left: Expr, right: Expr): Gt; + export function bitNot(operand: Expr): BitNot; /** * @beta * - * Creates an expression that checks if an expression is greater than a constant value. + * Creates an expression that applies a bitwise NOT operation to a field. * * ```typescript - * // Check if the 'age' field is greater than 18 - * gt(Field.of("age"), 18); + * // Calculate the bitwise NOT of 'field1'. + * bitNot("field1"); * ``` * - * @param left The expression to compare. - * @param right The constant value to compare to. - * @return A new `Expr` representing the greater than comparison. + * @param operand The operand field name. + * @return A new {@code Expr} representing the bitwise NOT operation. */ - export function gt(left: Expr, right: any): Gt; + export function bitNot(operand: string): BitNot; /** * @beta * - * Creates an expression that checks if a field's value is greater than an expression. + * Creates an expression that applies a bitwise left shift operation between two expressions. * * ```typescript - * // Check if the value of field 'age' is greater than the value of field 'limit' - * gt("age", Field.of("limit")); + * // Calculate the bitwise left shift of 'field1' by 'field2' bits. + * bitLeftShift(Field.of("field1"), Field.of("field2")); * ``` * - * @param left The field name to compare. - * @param right The expression to compare to. - * @return A new `Expr` representing the greater than comparison. + * @param left The left operand expression. + * @param right The right operand expression representing the number of bits to shift. + * @return A new {@code Expr} representing the bitwise left shift operation. */ - export function gt(left: string, right: Expr): Gt; + export function bitLeftShift(left: Expr, right: Expr): BitLeftShift; /** * @beta * - * Creates an expression that checks if a field's value is greater than a constant value. + * Creates an expression that applies a bitwise left shift operation between an expression and a constant. * * ```typescript - * // Check if the 'price' field is greater than 100 - * gt("price", 100); + * // Calculate the bitwise left shift of 'field1' by 2 bits. + * bitLeftShift(Field.of("field1"), 2); * ``` * - * @param left The field name to compare. - * @param right The constant value to compare to. - * @return A new `Expr` representing the greater than comparison. + * @param left The left operand expression. + * @param right The right operand constant representing the number of bits to shift. + * @return A new {@code Expr} representing the bitwise left shift operation. */ - export function gt(left: string, right: any): Gt; + export function bitLeftShift(left: Expr, right: any): BitLeftShift; /** * @beta * - * Creates an expression that checks if the first expression is greater than or equal to the - * second expression. + * Creates an expression that applies a bitwise left shift operation between a field and an expression. * * ```typescript - * // Check if the 'quantity' field is greater than or equal to the field "threshold" - * gte(Field.of("quantity"), Field.of("threshold")); + * // Calculate the bitwise left shift of 'field1' by 'field2' bits. + * bitLeftShift("field1", Field.of("field2")); * ``` * - * @param left The first expression to compare. - * @param right The second expression to compare. - * @return A new `Expr` representing the greater than or equal to comparison. + * @param left The left operand field name. + * @param right The right operand expression representing the number of bits to shift. + * @return A new {@code Expr} representing the bitwise left shift operation. */ - export function gte(left: Expr, right: Expr): Gte; + export function bitLeftShift(left: string, right: Expr): BitLeftShift; /** * @beta * - * Creates an expression that checks if an expression is greater than or equal to a constant - * value. + * Creates an expression that applies a bitwise left shift operation between a field and a constant. * * ```typescript - * // Check if the 'quantity' field is greater than or equal to 10 - * gte(Field.of("quantity"), 10); + * // Calculate the bitwise left shift of 'field1' by 2 bits. + * bitLeftShift("field1", 2); + * ``` + * + * @param left The left operand field name. + * @param right The right operand constant representing the number of bits to shift. + * @return A new {@code Expr} representing the bitwise left shift operation. + */ + export function bitLeftShift(left: string, right: any): BitLeftShift; + + /** + * @beta + * + * Creates an expression that applies a bitwise right shift operation between two expressions. + * + * ```typescript + * // Calculate the bitwise right shift of 'field1' by 'field2' bits. + * bitRightShift(Field.of("field1"), Field.of("field2")); + * ``` + * + * @param left The left operand expression. + * @param right The right operand expression representing the number of bits to shift. + * @return A new {@code Expr} representing the bitwise right shift operation. + */ + export function bitRightShift(left: Expr, right: Expr): BitRightShift; + + /** + * @beta + * + * Creates an expression that applies a bitwise right shift operation between an expression and a constant. + * + * ```typescript + * // Calculate the bitwise right shift of 'field1' by 2 bits. + * bitRightShift(Field.of("field1"), 2); + * ``` + * + * @param left The left operand expression. + * @param right The right operand constant representing the number of bits to shift. + * @return A new {@code Expr} representing the bitwise right shift operation. + */ + export function bitRightShift(left: Expr, right: any): BitRightShift; + + /** + * @beta + * + * Creates an expression that applies a bitwise right shift operation between a field and an expression. + * + * ```typescript + * // Calculate the bitwise right shift of 'field1' by 'field2' bits. + * bitRightShift("field1", Field.of("field2")); + * ``` + * + * @param left The left operand field name. + * @param right The right operand expression representing the number of bits to shift. + * @return A new {@code Expr} representing the bitwise right shift operation. + */ + export function bitRightShift(left: string, right: Expr): BitRightShift; + + /** + * @beta + * + * Creates an expression that applies a bitwise right shift operation between a field and a constant. + * + * ```typescript + * // Calculate the bitwise right shift of 'field1' by 2 bits. + * bitRightShift("field1", 2); + * ``` + * + * @param left The left operand field name. + * @param right The right operand constant representing the number of bits to shift. + * @return A new {@code Expr} representing the bitwise right shift operation. + */ + export function bitRightShift(left: string, right: any): BitRightShift; + + /** + * @beta + * + * Creates an expression that checks if two expressions are equal. + * + * ```typescript + * // Check if the 'age' field is equal to an expression + * eq(Field.of("age"), Field.of("minAge").add(10)); + * ``` + * + * @param left The first expression to compare. + * @param right The second expression to compare. + * @return A new `Expr` representing the equality comparison. + */ + export function eq(left: Expr, right: Expr): Eq; + + /** + * @beta + * + * Creates an expression that checks if an expression is equal to a constant value. + * + * ```typescript + * // Check if the 'age' field is equal to 21 + * eq(Field.of("age"), 21); * ``` * * @param left The expression to compare. * @param right The constant value to compare to. - * @return A new `Expr` representing the greater than or equal to comparison. + * @return A new `Expr` representing the equality comparison. */ - export function gte(left: Expr, right: any): Gte; + export function eq(left: Expr, right: any): Eq; /** * @beta * - * Creates an expression that checks if a field's value is greater than or equal to an expression. + * Creates an expression that checks if a field's value is equal to an expression. * * ```typescript - * // Check if the value of field 'age' is greater than or equal to the value of field 'limit' - * gte("age", Field.of("limit")); + * // Check if the 'age' field is equal to the 'limit' field + * eq("age", Field.of("limit")); * ``` * * @param left The field name to compare. * @param right The expression to compare to. - * @return A new `Expr` representing the greater than or equal to comparison. + * @return A new `Expr` representing the equality comparison. */ - export function gte(left: string, right: Expr): Gte; + export function eq(left: string, right: Expr): Eq; /** * @beta * - * Creates an expression that checks if a field's value is greater than or equal to a constant - * value. + * Creates an expression that checks if a field's value is equal to a constant value. * * ```typescript - * // Check if the 'score' field is greater than or equal to 80 - * gte("score", 80); + * // Check if the 'city' field is equal to string constant "London" + * eq("city", "London"); * ``` * * @param left The field name to compare. * @param right The constant value to compare to. - * @return A new `Expr` representing the greater than or equal to comparison. + * @return A new `Expr` representing the equality comparison. */ - export function gte(left: string, right: any): Gte; + export function eq(left: string, right: any): Eq; /** * @beta * - * Creates an expression that concatenates an array expression with other arrays. + * Creates an expression that checks if two expressions are not equal. * * ```typescript - * // Combine the 'items' array with two new item arrays - * arrayConcat(Field.of("items"), [Field.of("newItems"), Field.of("otherItems")]); + * // Check if the 'status' field is not equal to field 'finalState' + * neq(Field.of("status"), Field.of("finalState")); * ``` * - * @param array The array expression to concatenate to. - * @param elements The array expressions to concatenate. - * @return A new {@code Expr} representing the concatenated array. + * @param left The first expression to compare. + * @param right The second expression to compare. + * @return A new `Expr` representing the inequality comparison. */ - export function arrayConcat(array: Expr, elements: Expr[]): ArrayConcat; + export function neq(left: Expr, right: Expr): Neq; /** * @beta * - * Creates an expression that concatenates an array expression with other arrays and/or values. + * Creates an expression that checks if an expression is not equal to a constant value. * * ```typescript - * // Combine the 'tags' array with a new array - * arrayConcat(Field.of("tags"), ["newTag1", "newTag2"]); + * // Check if the 'status' field is not equal to "completed" + * neq(Field.of("status"), "completed"); * ``` * - * @param array The array expression to concatenate to. - * @param elements The array expressions or single values to concatenate. - * @return A new {@code Expr} representing the concatenated array. + * @param left The expression to compare. + * @param right The constant value to compare to. + * @return A new `Expr` representing the inequality comparison. */ - export function arrayConcat(array: Expr, elements: any[]): ArrayConcat; + export function neq(left: Expr, right: any): Neq; /** * @beta * - * Creates an expression that concatenates a field's array value with other arrays. + * Creates an expression that checks if a field's value is not equal to an expression. * * ```typescript - * // Combine the 'items' array with two new item arrays - * arrayConcat("items", [Field.of("newItems"), Field.of("otherItems")]); + * // Check if the 'status' field is not equal to the value of 'expectedStatus' + * neq("status", Field.of("expectedStatus")); * ``` * - * @param array The field name containing array values. - * @param elements The array expressions to concatenate. - * @return A new {@code Expr} representing the concatenated array. + * @param left The field name to compare. + * @param right The expression to compare to. + * @return A new `Expr` representing the inequality comparison. */ - export function arrayConcat(array: string, elements: Expr[]): ArrayConcat; + export function neq(left: string, right: Expr): Neq; /** * @beta * - * Creates an expression that concatenates a field's array value with other arrays and/or values. + * Creates an expression that checks if a field's value is not equal to a constant value. * * ```typescript - * // Combine the 'tags' array with a new array - * arrayConcat("tags", ["newTag1", "newTag2"]); + * // Check if the 'country' field is not equal to "USA" + * neq("country", "USA"); * ``` * - * @param array The field name containing array values. - * @param elements The array expressions or single values to concatenate. - * @return A new {@code Expr} representing the concatenated array. + * @param left The field name to compare. + * @param right The constant value to compare to. + * @return A new `Expr` representing the inequality comparison. */ - export function arrayConcat(array: string, elements: any[]): ArrayConcat; + export function neq(left: string, right: any): Neq; /** * @beta * - * Creates an expression that checks if an array expression contains a specific element. + * Creates an expression that checks if the first expression is less than the second expression. * * ```typescript - * // Check if the 'colors' array contains the value of field 'selectedColor' - * arrayContains(Field.of("colors"), Field.of("selectedColor")); + * // Check if the 'age' field is less than 30 + * lt(Field.of("age"), Field.of("limit")); * ``` * - * @param array The array expression to check. - * @param element The element to search for in the array. - * @return A new {@code Expr} representing the 'array_contains' comparison. + * @param left The first expression to compare. + * @param right The second expression to compare. + * @return A new `Expr` representing the less than comparison. */ - export function arrayContains(array: Expr, element: Expr): ArrayContains; + export function lt(left: Expr, right: Expr): Lt; /** * @beta * - * Creates an expression that checks if an array expression contains a specific element. + * Creates an expression that checks if an expression is less than a constant value. * * ```typescript - * // Check if the 'colors' array contains "red" - * arrayContains(Field.of("colors"), "red"); + * // Check if the 'age' field is less than 30 + * lt(Field.of("age"), 30); * ``` * - * @param array The array expression to check. - * @param element The element to search for in the array. - * @return A new {@code Expr} representing the 'array_contains' comparison. + * @param left The expression to compare. + * @param right The constant value to compare to. + * @return A new `Expr` representing the less than comparison. */ - export function arrayContains(array: Expr, element: any): ArrayContains; + export function lt(left: Expr, right: any): Lt; /** * @beta * - * Creates an expression that checks if a field's array value contains a specific element. + * Creates an expression that checks if a field's value is less than an expression. * * ```typescript - * // Check if the 'colors' array contains the value of field 'selectedColor' - * arrayContains("colors", Field.of("selectedColor")); + * // Check if the 'age' field is less than the 'limit' field + * lt("age", Field.of("limit")); + * ``` + * + * @param left The field name to compare. + * @param right The expression to compare to. + * @return A new `Expr` representing the less than comparison. + */ + export function lt(left: string, right: Expr): Lt; + + /** + * @beta + * + * Creates an expression that checks if a field's value is less than a constant value. + * + * ```typescript + * // Check if the 'price' field is less than 50 + * lt("price", 50); + * ``` + * + * @param left The field name to compare. + * @param right The constant value to compare to. + * @return A new `Expr` representing the less than comparison. + */ + export function lt(left: string, right: any): Lt; + + /** + * @beta + * + * Creates an expression that checks if the first expression is less than or equal to the second + * expression. + * + * ```typescript + * // Check if the 'quantity' field is less than or equal to 20 + * lte(Field.of("quantity"), Field.of("limit")); + * ``` + * + * @param left The first expression to compare. + * @param right The second expression to compare. + * @return A new `Expr` representing the less than or equal to comparison. + */ + export function lte(left: Expr, right: Expr): Lte; + + /** + * @beta + * + * Creates an expression that checks if an expression is less than or equal to a constant value. + * + * ```typescript + * // Check if the 'quantity' field is less than or equal to 20 + * lte(Field.of("quantity"), 20); + * ``` + * + * @param left The expression to compare. + * @param right The constant value to compare to. + * @return A new `Expr` representing the less than or equal to comparison. + */ + export function lte(left: Expr, right: any): Lte; + + /** + * Creates an expression that checks if a field's value is less than or equal to an expression. + * + * ```typescript + * // Check if the 'quantity' field is less than or equal to the 'limit' field + * lte("quantity", Field.of("limit")); + * ``` + * + * @param left The field name to compare. + * @param right The expression to compare to. + * @return A new `Expr` representing the less than or equal to comparison. + */ + export function lte(left: string, right: Expr): Lte; + + /** + * @beta + * + * Creates an expression that checks if a field's value is less than or equal to a constant value. + * + * ```typescript + * // Check if the 'score' field is less than or equal to 70 + * lte("score", 70); + * ``` + * + * @param left The field name to compare. + * @param right The constant value to compare to. + * @return A new `Expr` representing the less than or equal to comparison. + */ + export function lte(left: string, right: any): Lte; + + /** + * @beta + * + * Creates an expression that checks if the first expression is greater than the second + * expression. + * + * ```typescript + * // Check if the 'age' field is greater than 18 + * gt(Field.of("age"), Constant(9).add(9)); + * ``` + * + * @param left The first expression to compare. + * @param right The second expression to compare. + * @return A new `Expr` representing the greater than comparison. + */ + export function gt(left: Expr, right: Expr): Gt; + + /** + * @beta + * + * Creates an expression that checks if an expression is greater than a constant value. + * + * ```typescript + * // Check if the 'age' field is greater than 18 + * gt(Field.of("age"), 18); + * ``` + * + * @param left The expression to compare. + * @param right The constant value to compare to. + * @return A new `Expr` representing the greater than comparison. + */ + export function gt(left: Expr, right: any): Gt; + + /** + * @beta + * + * Creates an expression that checks if a field's value is greater than an expression. + * + * ```typescript + * // Check if the value of field 'age' is greater than the value of field 'limit' + * gt("age", Field.of("limit")); + * ``` + * + * @param left The field name to compare. + * @param right The expression to compare to. + * @return A new `Expr` representing the greater than comparison. + */ + export function gt(left: string, right: Expr): Gt; + + /** + * @beta + * + * Creates an expression that checks if a field's value is greater than a constant value. + * + * ```typescript + * // Check if the 'price' field is greater than 100 + * gt("price", 100); + * ``` + * + * @param left The field name to compare. + * @param right The constant value to compare to. + * @return A new `Expr` representing the greater than comparison. + */ + export function gt(left: string, right: any): Gt; + + /** + * @beta + * + * Creates an expression that checks if the first expression is greater than or equal to the + * second expression. + * + * ```typescript + * // Check if the 'quantity' field is greater than or equal to the field "threshold" + * gte(Field.of("quantity"), Field.of("threshold")); + * ``` + * + * @param left The first expression to compare. + * @param right The second expression to compare. + * @return A new `Expr` representing the greater than or equal to comparison. + */ + export function gte(left: Expr, right: Expr): Gte; + + /** + * @beta + * + * Creates an expression that checks if an expression is greater than or equal to a constant + * value. + * + * ```typescript + * // Check if the 'quantity' field is greater than or equal to 10 + * gte(Field.of("quantity"), 10); + * ``` + * + * @param left The expression to compare. + * @param right The constant value to compare to. + * @return A new `Expr` representing the greater than or equal to comparison. + */ + export function gte(left: Expr, right: any): Gte; + + /** + * @beta + * + * Creates an expression that checks if a field's value is greater than or equal to an expression. + * + * ```typescript + * // Check if the value of field 'age' is greater than or equal to the value of field 'limit' + * gte("age", Field.of("limit")); + * ``` + * + * @param left The field name to compare. + * @param right The expression to compare to. + * @return A new `Expr` representing the greater than or equal to comparison. + */ + export function gte(left: string, right: Expr): Gte; + + /** + * @beta + * + * Creates an expression that checks if a field's value is greater than or equal to a constant + * value. + * + * ```typescript + * // Check if the 'score' field is greater than or equal to 80 + * gte("score", 80); + * ``` + * + * @param left The field name to compare. + * @param right The constant value to compare to. + * @return A new `Expr` representing the greater than or equal to comparison. + */ + export function gte(left: string, right: any): Gte; + + /** + * @beta + * + * Creates an expression that concatenates an array expression with other arrays. + * + * ```typescript + * // Combine the 'items' array with two new item arrays + * arrayConcat(Field.of("items"), [Field.of("newItems"), Field.of("otherItems")]); + * ``` + * + * @param array The array expression to concatenate to. + * @param elements The array expressions to concatenate. + * @return A new {@code Expr} representing the concatenated array. + */ + export function arrayConcat(array: Expr, elements: Expr[]): ArrayConcat; + + /** + * @beta + * + * Creates an expression that concatenates an array expression with other arrays and/or values. + * + * ```typescript + * // Combine the 'tags' array with a new array + * arrayConcat(Field.of("tags"), ["newTag1", "newTag2"]); + * ``` + * + * @param array The array expression to concatenate to. + * @param elements The array expressions or single values to concatenate. + * @return A new {@code Expr} representing the concatenated array. + */ + export function arrayConcat(array: Expr, elements: any[]): ArrayConcat; + + /** + * @beta + * + * Creates an expression that concatenates a field's array value with other arrays. + * + * ```typescript + * // Combine the 'items' array with two new item arrays + * arrayConcat("items", [Field.of("newItems"), Field.of("otherItems")]); + * ``` + * + * @param array The field name containing array values. + * @param elements The array expressions to concatenate. + * @return A new {@code Expr} representing the concatenated array. + */ + export function arrayConcat(array: string, elements: Expr[]): ArrayConcat; + + /** + * @beta + * + * Creates an expression that concatenates a field's array value with other arrays and/or values. + * + * ```typescript + * // Combine the 'tags' array with a new array + * arrayConcat("tags", ["newTag1", "newTag2"]); + * ``` + * + * @param array The field name containing array values. + * @param elements The array expressions or single values to concatenate. + * @return A new {@code Expr} representing the concatenated array. + */ + export function arrayConcat(array: string, elements: any[]): ArrayConcat; + + /** + * @beta + * + * Creates an expression that checks if an array expression contains a specific element. + * + * ```typescript + * // Check if the 'colors' array contains the value of field 'selectedColor' + * arrayContains(Field.of("colors"), Field.of("selectedColor")); + * ``` + * + * @param array The array expression to check. + * @param element The element to search for in the array. + * @return A new {@code Expr} representing the 'array_contains' comparison. + */ + export function arrayContains(array: Expr, element: Expr): ArrayContains; + + /** + * @beta + * + * Creates an expression that checks if an array expression contains a specific element. + * + * ```typescript + * // Check if the 'colors' array contains "red" + * arrayContains(Field.of("colors"), "red"); + * ``` + * + * @param array The array expression to check. + * @param element The element to search for in the array. + * @return A new {@code Expr} representing the 'array_contains' comparison. + */ + export function arrayContains(array: Expr, element: any): ArrayContains; + + /** + * @beta + * + * Creates an expression that checks if a field's array value contains a specific element. + * + * ```typescript + * // Check if the 'colors' array contains the value of field 'selectedColor' + * arrayContains("colors", Field.of("selectedColor")); + * ``` + * + * @param array The field name to check. + * @param element The element to search for in the array. + * @return A new {@code Expr} representing the 'array_contains' comparison. + */ + export function arrayContains(array: string, element: Expr): ArrayContains; + + /** + * @beta + * + * Creates an expression that checks if a field's array value contains a specific value. + * + * ```typescript + * // Check if the 'colors' array contains "red" + * arrayContains("colors", "red"); + * ``` + * + * @param array The field name to check. + * @param element The element to search for in the array. + * @return A new {@code Expr} representing the 'array_contains' comparison. + */ + export function arrayContains(array: string, element: any): ArrayContains; + + /** + * @beta + * + * Creates an expression that checks if an array expression contains any of the specified + * elements. + * + * ```typescript + * // Check if the 'categories' array contains either values from field "cate1" or "Science" + * arrayContainsAny(Field.of("categories"), [Field.of("cate1"), "Science"]); + * ``` + * + * @param array The array expression to check. + * @param values The elements to check for in the array. + * @return A new {@code Expr} representing the 'array_contains_any' comparison. + */ + export function arrayContainsAny( + array: Expr, + values: Expr[] + ): ArrayContainsAny; + + /** + * @beta + * + * Creates an expression that checks if an array expression contains any of the specified + * elements. + * + * ```typescript + * // Check if the 'categories' array contains either values from field "cate1" or "Science" + * arrayContainsAny(Field.of("categories"), [Field.of("cate1"), "Science"]); + * ``` + * + * @param array The array expression to check. + * @param values The elements to check for in the array. + * @return A new {@code Expr} representing the 'array_contains_any' comparison. + */ + export function arrayContainsAny( + array: Expr, + values: any[] + ): ArrayContainsAny; + + /** + * @beta + * + * Creates an expression that checks if a field's array value contains any of the specified + * elements. + * + * ```typescript + * // Check if the 'groups' array contains either the value from the 'userGroup' field + * // or the value "guest" + * arrayContainsAny("categories", [Field.of("cate1"), "Science"]); + * ``` + * + * @param array The field name to check. + * @param values The elements to check for in the array. + * @return A new {@code Expr} representing the 'array_contains_any' comparison. + */ + export function arrayContainsAny( + array: string, + values: Expr[] + ): ArrayContainsAny; + + /** + * @beta + * + * Creates an expression that checks if a field's array value contains any of the specified + * elements. + * + * ```typescript + * // Check if the 'groups' array contains either the value from the 'userGroup' field + * // or the value "guest" + * arrayContainsAny("categories", [Field.of("cate1"), "Science"]); + * ``` + * + * @param array The field name to check. + * @param values The elements to check for in the array. + * @return A new {@code Expr} representing the 'array_contains_any' comparison. + */ + export function arrayContainsAny( + array: string, + values: any[] + ): ArrayContainsAny; + + /** + * @beta + * + * Creates an expression that checks if an array expression contains all the specified elements. + * + * ```typescript + * // Check if the 'tags' array contains both of the values from field 'tag1', 'tag2' and "tag3" + * arrayContainsAll(Field.of("tags"), [Field.of("tag1"), "SciFi", "Adventure"]); + * ``` + * + * @param array The array expression to check. + * @param values The elements to check for in the array. + * @return A new {@code Expr} representing the 'array_contains_all' comparison. + */ + export function arrayContainsAll( + array: Expr, + values: Expr[] + ): ArrayContainsAll; + + /** + * @beta + * + * Creates an expression that checks if an array expression contains all the specified elements. + * + * ```typescript + * // Check if the 'tags' array contains both of the values from field 'tag1', 'tag2' and "tag3" + * arrayContainsAll(Field.of("tags"), [Field.of("tag1"), "SciFi", "Adventure"]); + * ``` + * + * @param array The array expression to check. + * @param values The elements to check for in the array. + * @return A new {@code Expr} representing the 'array_contains_all' comparison. + */ + export function arrayContainsAll( + array: Expr, + values: any[] + ): ArrayContainsAll; + + /** + * @beta + * + * Creates an expression that checks if a field's array value contains all the specified values or + * expressions. + * + * ```typescript + * // Check if the 'tags' array contains both of the values from field 'tag1' and "tag2" + * arrayContainsAll("tags", [Field.of("tag1"), "SciFi", "Adventure"]); + * ``` + * + * @param array The field name to check. + * @param values The elements to check for in the array. + * @return A new {@code Expr} representing the 'array_contains_all' comparison. + */ + export function arrayContainsAll( + array: string, + values: Expr[] + ): ArrayContainsAll; + + /** + * @beta + * + * Creates an expression that checks if a field's array value contains all the specified values or + * expressions. + * + * ```typescript + * // Check if the 'tags' array contains both of the values from field 'tag1' and "tag2" + * arrayContainsAll("tags", [Field.of("tag1"), "SciFi", "Adventure"]); + * ``` + * + * @param array The field name to check. + * @param values The elements to check for in the array. + * @return A new {@code Expr} representing the 'array_contains_all' comparison. + */ + export function arrayContainsAll( + array: string, + values: any[] + ): ArrayContainsAll; + + /** + * @beta + * + * Creates an expression that calculates the length of an array expression. + * + * ```typescript + * // Get the number of items in the 'cart' array + * arrayLength(Field.of("cart")); + * ``` + * + * @param array The array expression to calculate the length of. + * @return A new {@code Expr} representing the length of the array. + */ + export function arrayLength(array: Expr): ArrayLength; + + /** + * @beta + * + * Creates an expression that checks if an expression is equal to any of the provided values or + * expressions. + * + * ```typescript + * // Check if the 'category' field is either "Electronics" or value of field 'primaryType' + * inAny(Field.of("category"), [Constant.of("Electronics"), Field.of("primaryType")]); + * ``` + * + * @param element The expression to compare. + * @param others The values to check against. + * @return A new {@code Expr} representing the 'IN' comparison. + */ + export function inAny(element: Expr, others: Expr[]): In; + + /** + * @beta + * + * Creates an expression that checks if an expression is equal to any of the provided values or + * expressions. + * + * ```typescript + * // Check if the 'category' field is either "Electronics" or value of field 'primaryType' + * inAny(Field.of("category"), ["Electronics", Field.of("primaryType")]); + * ``` + * + * @param element The expression to compare. + * @param others The values to check against. + * @return A new {@code Expr} representing the 'IN' comparison. + */ + export function inAny(element: Expr, others: any[]): In; + + /** + * @beta + * + * Creates an expression that checks if a field's value is equal to any of the provided values or + * expressions. + * + * ```typescript + * // Check if the 'category' field is either "Electronics" or value of field 'primaryType' + * inAny("category", [Constant.of("Electronics"), Field.of("primaryType")]); + * ``` + * + * @param element The field to compare. + * @param others The values to check against. + * @return A new {@code Expr} representing the 'IN' comparison. + */ + export function inAny(element: string, others: Expr[]): In; + + /** + * @beta + * + * Creates an expression that checks if a field's value is equal to any of the provided values or + * expressions. + * + * ```typescript + * // Check if the 'category' field is either "Electronics" or value of field 'primaryType' + * inAny("category", ["Electronics", Field.of("primaryType")]); + * ``` + * + * @param element The field to compare. + * @param others The values to check against. + * @return A new {@code Expr} representing the 'IN' comparison. + */ + export function inAny(element: string, others: any[]): In; + + /** + * @beta + * + * Creates an expression that checks if an expression is not equal to any of the provided values + * or expressions. + * + * ```typescript + * // Check if the 'status' field is neither "pending" nor the value of 'rejectedStatus' + * notInAny(Field.of("status"), [Constant.of("pending"), Field.of("rejectedStatus")]); + * ``` + * + * @param element The expression to compare. + * @param others The values to check against. + * @return A new {@code Expr} representing the 'NOT IN' comparison. + */ + export function notInAny(element: Expr, others: Expr[]): Not; + + /** + * @beta + * + * Creates an expression that checks if an expression is not equal to any of the provided values + * or expressions. + * + * ```typescript + * // Check if the 'status' field is neither "pending" nor the value of 'rejectedStatus' + * notInAny(Field.of("status"), ["pending", Field.of("rejectedStatus")]); + * ``` + * + * @param element The expression to compare. + * @param others The values to check against. + * @return A new {@code Expr} representing the 'NOT IN' comparison. + */ + export function notInAny(element: Expr, others: any[]): Not; + + /** + * @beta + * + * Creates an expression that checks if a field's value is not equal to any of the provided values + * or expressions. + * + * ```typescript + * // Check if the 'status' field is neither "pending" nor the value of 'rejectedStatus' + * notInAny("status", [Constant.of("pending"), Field.of("rejectedStatus")]); * ``` * - * @param array The field name to check. - * @param element The element to search for in the array. - * @return A new {@code Expr} representing the 'array_contains' comparison. + * @param element The field name to compare. + * @param others The values to check against. + * @return A new {@code Expr} representing the 'NOT IN' comparison. */ - export function arrayContains(array: string, element: Expr): ArrayContains; + export function notInAny(element: string, others: Expr[]): Not; /** * @beta * - * Creates an expression that checks if a field's array value contains a specific value. + * Creates an expression that checks if a field's value is not equal to any of the provided values + * or expressions. * * ```typescript - * // Check if the 'colors' array contains "red" - * arrayContains("colors", "red"); + * // Check if the 'status' field is neither "pending" nor the value of 'rejectedStatus' + * notInAny("status", ["pending", Field.of("rejectedStatus")]); * ``` * - * @param array The field name to check. - * @param element The element to search for in the array. - * @return A new {@code Expr} representing the 'array_contains' comparison. + * @param element The field name to compare. + * @param others The values to check against. + * @return A new {@code Expr} representing the 'NOT IN' comparison. */ - export function arrayContains(array: string, element: any): ArrayContains; + export function notInAny(element: string, others: any[]): Not; /** * @beta * - * Creates an expression that checks if an array expression contains any of the specified - * elements. + * Creates an expression that performs a logical 'AND' operation on multiple filter conditions. * * ```typescript - * // Check if the 'categories' array contains either values from field "cate1" or "Science" - * arrayContainsAny(Field.of("categories"), [Field.of("cate1"), "Science"]); + * // Check if the 'age' field is greater than 18 AND the 'city' field is "London" AND + * // the 'status' field is "active" + * const condition = and(gt("age", 18), eq("city", "London"), eq("status", "active")); * ``` * - * @param array The array expression to check. - * @param values The elements to check for in the array. - * @return A new {@code Expr} representing the 'array_contains_any' comparison. + * @param left The first filter condition. + * @param right Additional filter conditions to 'AND' together. + * @return A new {@code Expr} representing the logical 'AND' operation. */ - export function arrayContainsAny( - array: Expr, - values: Expr[] - ): ArrayContainsAny; + export function and(left: FilterExpr, ...right: FilterExpr[]): And; /** * @beta * - * Creates an expression that checks if an array expression contains any of the specified - * elements. + * Creates an expression that performs a logical 'OR' operation on multiple filter conditions. * * ```typescript - * // Check if the 'categories' array contains either values from field "cate1" or "Science" - * arrayContainsAny(Field.of("categories"), [Field.of("cate1"), "Science"]); + * // Check if the 'age' field is greater than 18 OR the 'city' field is "London" OR + * // the 'status' field is "active" + * const condition = or(gt("age", 18), eq("city", "London"), eq("status", "active")); * ``` * - * @param array The array expression to check. - * @param values The elements to check for in the array. - * @return A new {@code Expr} representing the 'array_contains_any' comparison. + * @param left The first filter condition. + * @param right Additional filter conditions to 'OR' together. + * @return A new {@code Expr} representing the logical 'OR' operation. */ - export function arrayContainsAny( - array: Expr, - values: any[] - ): ArrayContainsAny; + export function or(left: FilterExpr, ...right: FilterExpr[]): Or; /** * @beta * - * Creates an expression that checks if a field's array value contains any of the specified - * elements. + * Creates an expression that performs a logical 'XOR' (exclusive OR) operation on multiple filter + * conditions. * * ```typescript - * // Check if the 'groups' array contains either the value from the 'userGroup' field - * // or the value "guest" - * arrayContainsAny("categories", [Field.of("cate1"), "Science"]); + * // Check if only one of the conditions is true: 'age' greater than 18, 'city' is "London", + * // or 'status' is "active". + * const condition = xor( + * gt("age", 18), + * eq("city", "London"), + * eq("status", "active")); * ``` * - * @param array The field name to check. - * @param values The elements to check for in the array. - * @return A new {@code Expr} representing the 'array_contains_any' comparison. + * @param left The first filter condition. + * @param right Additional filter conditions to 'XOR' together. + * @return A new {@code Expr} representing the logical 'XOR' operation. */ - export function arrayContainsAny( - array: string, - values: Expr[] - ): ArrayContainsAny; + export function xor(left: FilterExpr, ...right: FilterExpr[]): Xor; /** * @beta * - * Creates an expression that checks if a field's array value contains any of the specified - * elements. + * Creates a conditional expression that evaluates to a 'then' expression if a condition is true + * and an 'else' expression if the condition is false. * * ```typescript - * // Check if the 'groups' array contains either the value from the 'userGroup' field - * // or the value "guest" - * arrayContainsAny("categories", [Field.of("cate1"), "Science"]); + * // If 'age' is greater than 18, return "Adult"; otherwise, return "Minor". + * ifFunction( + * gt("age", 18), Constant.of("Adult"), Constant.of("Minor")); * ``` * - * @param array The field name to check. - * @param values The elements to check for in the array. - * @return A new {@code Expr} representing the 'array_contains_any' comparison. + * @param condition The condition to evaluate. + * @param thenExpr The expression to evaluate if the condition is true. + * @param elseExpr The expression to evaluate if the condition is false. + * @return A new {@code Expr} representing the conditional expression. */ - export function arrayContainsAny( - array: string, - values: any[] - ): ArrayContainsAny; + export function ifFunction( + condition: FilterExpr, + thenExpr: Expr, + elseExpr: Expr + ): If; /** * @beta * - * Creates an expression that checks if an array expression contains all the specified elements. + * Creates an expression that negates a filter condition. * * ```typescript - * // Check if the 'tags' array contains both of the values from field 'tag1', 'tag2' and "tag3" - * arrayContainsAll(Field.of("tags"), [Field.of("tag1"), "SciFi", "Adventure"]); + * // Find documents where the 'completed' field is NOT true + * not(eq("completed", true)); * ``` * - * @param array The array expression to check. - * @param values The elements to check for in the array. - * @return A new {@code Expr} representing the 'array_contains_all' comparison. + * @param filter The filter condition to negate. + * @return A new {@code Expr} representing the negated filter condition. */ - export function arrayContainsAll( - array: Expr, - values: Expr[] - ): ArrayContainsAll; + export function not(filter: FilterExpr): Not; /** * @beta * - * Creates an expression that checks if an array expression contains all the specified elements. + * Creates an expression that returns the larger value between two expressions, based on Firestore's value type ordering. * * ```typescript - * // Check if the 'tags' array contains both of the values from field 'tag1', 'tag2' and "tag3" - * arrayContainsAll(Field.of("tags"), [Field.of("tag1"), "SciFi", "Adventure"]); + * // Returns the larger value between the 'timestamp' field and the current timestamp. + * logicalMax(Field.of("timestamp"), Function.currentTimestamp()); * ``` * - * @param array The array expression to check. - * @param values The elements to check for in the array. - * @return A new {@code Expr} representing the 'array_contains_all' comparison. + * @param left The left operand expression. + * @param right The right operand expression. + * @return A new {@code Expr} representing the logical max operation. */ - export function arrayContainsAll( - array: Expr, - values: any[] - ): ArrayContainsAll; + export function logicalMax(left: Expr, right: Expr): LogicalMax; /** * @beta * - * Creates an expression that checks if a field's array value contains all the specified values or - * expressions. + * Creates an expression that returns the larger value between an expression and a constant value, based on Firestore's value type ordering. * * ```typescript - * // Check if the 'tags' array contains both of the values from field 'tag1' and "tag2" - * arrayContainsAll("tags", [Field.of("tag1"), "SciFi", "Adventure"]); + * // Returns the larger value between the 'value' field and 10. + * logicalMax(Field.of("value"), 10); * ``` * - * @param array The field name to check. - * @param values The elements to check for in the array. - * @return A new {@code Expr} representing the 'array_contains_all' comparison. + * @param left The left operand expression. + * @param right The right operand constant. + * @return A new {@code Expr} representing the logical max operation. */ - export function arrayContainsAll( - array: string, - values: Expr[] - ): ArrayContainsAll; + export function logicalMax(left: Expr, right: any): LogicalMax; /** * @beta * - * Creates an expression that checks if a field's array value contains all the specified values or - * expressions. + * Creates an expression that returns the larger value between a field and an expression, based on Firestore's value type ordering. * * ```typescript - * // Check if the 'tags' array contains both of the values from field 'tag1' and "tag2" - * arrayContainsAll("tags", [Field.of("tag1"), "SciFi", "Adventure"]); + * // Returns the larger value between the 'timestamp' field and the current timestamp. + * logicalMax("timestamp", Function.currentTimestamp()); * ``` * - * @param array The field name to check. - * @param values The elements to check for in the array. - * @return A new {@code Expr} representing the 'array_contains_all' comparison. + * @param left The left operand field name. + * @param right The right operand expression. + * @return A new {@code Expr} representing the logical max operation. */ - export function arrayContainsAll( - array: string, - values: any[] - ): ArrayContainsAll; + export function logicalMax(left: string, right: Expr): LogicalMax; /** * @beta * - * Creates an expression that filters elements from an array expression using the given {@link - * FilterExpr} and returns the filtered elements as a new array. + * Creates an expression that returns the larger value between a field and a constant value, based on Firestore's value type ordering. * * ```typescript - * // Get items from the 'inventoryPrices' array where the array item is greater than 0 - * // Note we use {@link arrayElement} to represent array elements to construct a - * // filtering condition. - * arrayFilter(Field.of("inventoryPrices"), arrayElement().gt(0)); + * // Returns the larger value between the 'value' field and 10. + * logicalMax("value", 10); * ``` * - * @param array The array expression to filter. - * @param filter The {@link FilterExpr} to apply to the array elements. - * @return A new {@code Expr} representing the filtered array. + * @param left The left operand field name. + * @param right The right operand constant. + * @return A new {@code Expr} representing the logical max operation. */ - export function arrayFilter(array: Expr, filter: FilterExpr): ArrayFilter; + export function logicalMax(left: string, right: any): LogicalMax; /** * @beta * - * Creates an expression that calculates the length of an array expression. + * Creates an expression that returns the smaller value between two expressions, based on Firestore's value type ordering. * * ```typescript - * // Get the number of items in the 'cart' array - * arrayLength(Field.of("cart")); + * // Returns the smaller value between the 'timestamp' field and the current timestamp. + * logicalMin(Field.of("timestamp"), Function.currentTimestamp()); * ``` * - * @param array The array expression to calculate the length of. - * @return A new {@code Expr} representing the length of the array. + * @param left The left operand expression. + * @param right The right operand expression. + * @return A new {@code Expr} representing the logical min operation. */ - export function arrayLength(array: Expr): ArrayLength; + export function logicalMin(left: Expr, right: Expr): LogicalMin; /** * @beta * - * Creates an expression that applies a transformation function to each element in an array - * expression and returns the new array as the result of the evaluation. + * Creates an expression that returns the smaller value between an expression and a constant value, based on Firestore's value type ordering. * * ```typescript - * // Convert all strings in the 'names' array to uppercase - * // Note we use {@link arrayElement} to represent array elements to construct a - * // transforming function. - * arrayTransform(Field.of("names"), arrayElement().toUppercase()); + * // Returns the smaller value between the 'value' field and 10. + * logicalMin(Field.of("value"), 10); * ``` * - * @param array The array expression to transform. - * @param transform The {@link Function} to apply to each array element. - * @return A new {@code Expr} representing the transformed array. + * @param left The left operand expression. + * @param right The right operand constant. + * @return A new {@code Expr} representing the logical min operation. */ - export function arrayTransform( - array: Expr, - transform: Function - ): ArrayTransform; + export function logicalMin(left: Expr, right: any): LogicalMin; /** * @beta * - * Returns an expression that represents an array element within an {@link ArrayFilter} or {@link - * ArrayTransform} expression. + * Creates an expression that returns the smaller value between a field and an expression, based on Firestore's value type ordering. * * ```typescript - * // Get items from the 'inventoryPrices' array where the array item is greater than 0 - * arrayFilter(Field.of("inventoryPrices"), arrayElement().gt(0)); + * // Returns the smaller value between the 'timestamp' field and the current timestamp. + * logicalMin("timestamp", Function.currentTimestamp()); * ``` * - * @return A new {@code Expr} representing an array element. + * @param left The left operand field name. + * @param right The right operand expression. + * @return A new {@code Expr} representing the logical min operation. */ - export function arrayElement(): ArrayElement; + export function logicalMin(left: string, right: Expr): LogicalMin; /** * @beta * - * Creates an expression that checks if an expression is equal to any of the provided values or - * expressions. + * Creates an expression that returns the smaller value between a field and a constant value, based on Firestore's value type ordering. * * ```typescript - * // Check if the 'category' field is either "Electronics" or value of field 'primaryType' - * inAny(Field.of("category"), [Constant.of("Electronics"), Field.of("primaryType")]); + * // Returns the smaller value between the 'value' field and 10. + * logicalMin("value", 10); * ``` * - * @param element The expression to compare. - * @param others The values to check against. - * @return A new {@code Expr} representing the 'IN' comparison. + * @param left The left operand field name. + * @param right The right operand constant. + * @return A new {@code Expr} representing the logical min operation. */ - export function inAny(element: Expr, others: Expr[]): In; + export function logicalMin(left: string, right: any): LogicalMin; /** * @beta * - * Creates an expression that checks if an expression is equal to any of the provided values or - * expressions. + * Creates an expression that checks if a field exists. * * ```typescript - * // Check if the 'category' field is either "Electronics" or value of field 'primaryType' - * inAny(Field.of("category"), ["Electronics", Field.of("primaryType")]); + * // Check if the document has a field named "phoneNumber" + * exists(Field.of("phoneNumber")); * ``` * - * @param element The expression to compare. - * @param others The values to check against. - * @return A new {@code Expr} representing the 'IN' comparison. + * @param value An expression evaluates to the name of the field to check. + * @return A new {@code Expr} representing the 'exists' check. */ - export function inAny(element: Expr, others: any[]): In; + export function exists(value: Expr): Exists; /** * @beta * - * Creates an expression that checks if a field's value is equal to any of the provided values or - * expressions. + * Creates an expression that checks if a field exists. * * ```typescript - * // Check if the 'category' field is either "Electronics" or value of field 'primaryType' - * inAny("category", [Constant.of("Electronics"), Field.of("primaryType")]); + * // Check if the document has a field named "phoneNumber" + * exists("phoneNumber"); * ``` * - * @param element The field to compare. - * @param others The values to check against. - * @return A new {@code Expr} representing the 'IN' comparison. + * @param field The field name to check. + * @return A new {@code Expr} representing the 'exists' check. */ - export function inAny(element: string, others: Expr[]): In; + export function exists(field: string): Exists; /** * @beta * - * Creates an expression that checks if a field's value is equal to any of the provided values or - * expressions. + * Creates an expression that checks if an expression evaluates to 'NaN' (Not a Number). * * ```typescript - * // Check if the 'category' field is either "Electronics" or value of field 'primaryType' - * inAny("category", ["Electronics", Field.of("primaryType")]); + * // Check if the result of a calculation is NaN + * isNaN(Field.of("value").divide(0)); * ``` * - * @param element The field to compare. - * @param others The values to check against. - * @return A new {@code Expr} representing the 'IN' comparison. + * @param value The expression to check. + * @return A new {@code Expr} representing the 'isNaN' check. */ - export function inAny(element: string, others: any[]): In; + export function isNaN(value: Expr): IsNan; /** * @beta * - * Creates an expression that checks if an expression is not equal to any of the provided values - * or expressions. + * Creates an expression that checks if a field's value evaluates to 'NaN' (Not a Number). * * ```typescript - * // Check if the 'status' field is neither "pending" nor the value of 'rejectedStatus' - * notInAny(Field.of("status"), [Constant.of("pending"), Field.of("rejectedStatus")]); + * // Check if the result of a calculation is NaN + * isNaN("value"); * ``` * - * @param element The expression to compare. - * @param others The values to check against. - * @return A new {@code Expr} representing the 'NOT IN' comparison. + * @param value The name of the field to check. + * @return A new {@code Expr} representing the 'isNaN' check. */ - export function notInAny(element: Expr, others: Expr[]): Not; + export function isNaN(value: string): IsNan; /** * @beta * - * Creates an expression that checks if an expression is not equal to any of the provided values - * or expressions. + * Creates an expression that reverses a string. * * ```typescript - * // Check if the 'status' field is neither "pending" nor the value of 'rejectedStatus' - * notInAny(Field.of("status"), ["pending", Field.of("rejectedStatus")]); + * // Reverse the value of the 'myString' field. + * reverse(Field.of("myString")); * ``` * - * @param element The expression to compare. - * @param others The values to check against. - * @return A new {@code Expr} representing the 'NOT IN' comparison. + * @param expr The expression representing the string to reverse. + * @return A new {@code Expr} representing the reversed string. */ - export function notInAny(element: Expr, others: any[]): Not; + export function reverse(expr: Expr): Reverse; /** * @beta * - * Creates an expression that checks if a field's value is not equal to any of the provided values - * or expressions. + * Creates an expression that reverses a string represented by a field. * * ```typescript - * // Check if the 'status' field is neither "pending" nor the value of 'rejectedStatus' - * notInAny("status", [Constant.of("pending"), Field.of("rejectedStatus")]); + * // Reverse the value of the 'myString' field. + * reverse("myString"); * ``` * - * @param element The field name to compare. - * @param others The values to check against. - * @return A new {@code Expr} representing the 'NOT IN' comparison. + * @param field The name of the field representing the string to reverse. + * @return A new {@code Expr} representing the reversed string. */ - export function notInAny(element: string, others: Expr[]): Not; + export function reverse(field: string): Reverse; /** * @beta * - * Creates an expression that checks if a field's value is not equal to any of the provided values - * or expressions. + * Creates an expression that replaces the first occurrence of a substring within a string with another substring. * * ```typescript - * // Check if the 'status' field is neither "pending" nor the value of 'rejectedStatus' - * notInAny("status", ["pending", Field.of("rejectedStatus")]); + * // Replace the first occurrence of "hello" with "hi" in the 'message' field. + * replaceFirst(Field.of("message"), "hello", "hi"); * ``` - * - * @param element The field name to compare. - * @param others The values to check against. - * @return A new {@code Expr} representing the 'NOT IN' comparison. + * + * @param value The expression representing the string to perform the replacement on. + * @param find The substring to search for. + * @param replace The substring to replace the first occurrence of 'find' with. + * @return A new {@code Expr} representing the string with the first occurrence replaced. */ - export function notInAny(element: string, others: any[]): Not; + export function replaceFirst( + value: Expr, + find: string, + replace: string + ): ReplaceFirst; /** * @beta * - * Creates an expression that performs a logical 'AND' operation on multiple filter conditions. + * Creates an expression that replaces the first occurrence of a substring within a string with another substring, + * where the substring to find and the replacement substring are specified by expressions. * * ```typescript - * // Check if the 'age' field is greater than 18 AND the 'city' field is "London" AND - * // the 'status' field is "active" - * const condition = and(gt("age", 18), eq("city", "London"), eq("status", "active")); + * // Replace the first occurrence of the value in 'findField' with the value in 'replaceField' in the 'message' field. + * replaceFirst(Field.of("message"), Field.of("findField"), Field.of("replaceField")); * ``` * - * @param left The first filter condition. - * @param right Additional filter conditions to 'AND' together. - * @return A new {@code Expr} representing the logical 'AND' operation. + * @param value The expression representing the string to perform the replacement on. + * @param find The expression representing the substring to search for. + * @param replace The expression representing the substring to replace the first occurrence of 'find' with. + * @return A new {@code Expr} representing the string with the first occurrence replaced. */ - export function and(left: FilterExpr, ...right: FilterExpr[]): And; + export function replaceFirst( + value: Expr, + find: Expr, + replace: Expr + ): ReplaceFirst; /** * @beta * - * Creates an expression that performs a logical 'OR' operation on multiple filter conditions. + * Creates an expression that replaces the first occurrence of a substring within a string represented by a field with another substring. * * ```typescript - * // Check if the 'age' field is greater than 18 OR the 'city' field is "London" OR - * // the 'status' field is "active" - * const condition = or(gt("age", 18), eq("city", "London"), eq("status", "active")); + * // Replace the first occurrence of "hello" with "hi" in the 'message' field. + * replaceFirst("message", "hello", "hi"); * ``` * - * @param left The first filter condition. - * @param right Additional filter conditions to 'OR' together. - * @return A new {@code Expr} representing the logical 'OR' operation. + * @param field The name of the field representing the string to perform the replacement on. + * @param find The substring to search for. + * @param replace The substring to replace the first occurrence of 'find' with. + * @return A new {@code Expr} representing the string with the first occurrence replaced. */ - export function or(left: FilterExpr, ...right: FilterExpr[]): Or; + export function replaceFirst( + field: string, + find: string, + replace: string + ): ReplaceFirst; /** * @beta * - * Creates an expression that performs a logical 'XOR' (exclusive OR) operation on multiple filter - * conditions. + * Creates an expression that replaces the first occurrence of a substring within a string represented by a field with another substring, + * where the substring to find and the replacement substring are specified by expressions. * * ```typescript - * // Check if only one of the conditions is true: 'age' greater than 18, 'city' is "London", - * // or 'status' is "active". - * const condition = xor( - * gt("age", 18), - * eq("city", "London"), - * eq("status", "active")); + * // Replace the first occurrence of the value in 'findField' with the value in 'replaceField' in the 'message' field. + * replaceFirst("message", Field.of("findField"), Field.of("replaceField")); * ``` * - * @param left The first filter condition. - * @param right Additional filter conditions to 'XOR' together. - * @return A new {@code Expr} representing the logical 'XOR' operation. + * @param field The name of the field representing the string to perform the replacement on. + * @param find The expression representing the substring to search for. + * @param replace The expression representing the substring to replace the first occurrence of 'find' with. + * @return A new {@code Expr} representing the string with the first occurrence replaced. */ - export function xor(left: FilterExpr, ...right: FilterExpr[]): Xor; + export function replaceFirst( + field: string, + find: Expr, + replace: Expr + ): ReplaceFirst; /** * @beta * - * Creates a conditional expression that evaluates to a 'then' expression if a condition is true - * and an 'else' expression if the condition is false. + * Creates an expression that replaces all occurrences of a substring within a string with another substring. * * ```typescript - * // If 'age' is greater than 18, return "Adult"; otherwise, return "Minor". - * ifFunction( - * gt("age", 18), Constant.of("Adult"), Constant.of("Minor")); + * // Replace all occurrences of "hello" with "hi" in the 'message' field. + * replaceAll(Field.of("message"), "hello", "hi"); * ``` * - * @param condition The condition to evaluate. - * @param thenExpr The expression to evaluate if the condition is true. - * @param elseExpr The expression to evaluate if the condition is false. - * @return A new {@code Expr} representing the conditional expression. + * @param value The expression representing the string to perform the replacement on. + * @param find The substring to search for. + * @param replace The substring to replace all occurrences of 'find' with. + * @return A new {@code Expr} representing the string with all occurrences replaced. */ - export function ifFunction( - condition: FilterExpr, - thenExpr: Expr, - elseExpr: Expr - ): If; + export function replaceAll( + value: Expr, + find: string, + replace: string + ): ReplaceAll; /** * @beta * - * Creates an expression that negates a filter condition. + * Creates an expression that replaces all occurrences of a substring within a string with another substring, + * where the substring to find and the replacement substring are specified by expressions. * * ```typescript - * // Find documents where the 'completed' field is NOT true - * not(eq("completed", true)); + * // Replace all occurrences of the value in 'findField' with the value in 'replaceField' in the 'message' field. + * replaceAll(Field.of("message"), Field.of("findField"), Field.of("replaceField")); * ``` * - * @param filter The filter condition to negate. - * @return A new {@code Expr} representing the negated filter condition. + * @param value The expression representing the string to perform the replacement on. + * @param find The expression representing the substring to search for. + * @param replace The expression representing the substring to replace all occurrences of 'find' with. + * @return A new {@code Expr} representing the string with all occurrences replaced. */ - export function not(filter: FilterExpr): Not; + export function replaceAll( + value: Expr, + find: Expr, + replace: Expr + ): ReplaceAll; /** * @beta * - * Creates an expression that checks if a field exists. + * Creates an expression that replaces all occurrences of a substring within a string represented by a field with another substring. * * ```typescript - * // Check if the document has a field named "phoneNumber" - * exists(Field.of("phoneNumber")); + * // Replace all occurrences of "hello" with "hi" in the 'message' field. + * replaceAll("message", "hello", "hi"); * ``` * - * @param value An expression evaluates to the name of the field to check. - * @return A new {@code Expr} representing the 'exists' check. + * @param field The name of the field representing the string to perform the replacement on. + * @param find The substring to search for. + * @param replace The substring to replace all occurrences of 'find' with. + * @return A new {@code Expr} representing the string with all occurrences replaced. */ - export function exists(value: Expr): Exists; + export function replaceAll( + field: string, + find: string, + replace: string + ): ReplaceAll; /** * @beta * - * Creates an expression that checks if a field exists. + * Creates an expression that replaces all occurrences of a substring within a string represented by a field with another substring, + * where the substring to find and the replacement substring are specified by expressions. * * ```typescript - * // Check if the document has a field named "phoneNumber" - * exists("phoneNumber"); + * // Replace all occurrences of the value in 'findField' with the value in 'replaceField' in the 'message' field. + * replaceAll("message", Field.of("findField"), Field.of("replaceField")); * ``` * - * @param field The field name to check. - * @return A new {@code Expr} representing the 'exists' check. + * @param field The name of the field representing the string to perform the replacement on. + * @param find The expression representing the substring to search for. + * @param replace The expression representing the substring to replace all occurrences of 'find' with. + * @return A new {@code Expr} representing the string with all occurrences replaced. */ - export function exists(field: string): Exists; + export function replaceAll( + field: string, + find: Expr, + replace: Expr + ): ReplaceAll; /** * @beta * - * Creates an expression that checks if an expression evaluates to 'NaN' (Not a Number). + * Creates an expression that calculates the length of a string in bytes. * * ```typescript - * // Check if the result of a calculation is NaN - * isNaN(Field.of("value").divide(0)); + * // Calculate the length of the 'myString' field in bytes. + * byteLength(Field.of("myString")); * ``` * - * @param value The expression to check. - * @return A new {@code Expr} representing the 'isNaN' check. + * @param expr The expression representing the string. + * @return A new {@code Expr} representing the length of the string in bytes. */ - export function isNaN(value: Expr): IsNan; + export function byteLength(expr: Expr): ByteLength; /** * @beta * - * Creates an expression that checks if a field's value evaluates to 'NaN' (Not a Number). + * Creates an expression that calculates the length of a string represented by a field in bytes. * * ```typescript - * // Check if the result of a calculation is NaN - * isNaN("value"); + * // Calculate the length of the 'myString' field in bytes. + * byteLength("myString"); * ``` * - * @param value The name of the field to check. - * @return A new {@code Expr} representing the 'isNaN' check. + * @param field The name of the field representing the string. + * @return A new {@code Expr} representing the length of the string in bytes. */ - export function isNaN(value: string): IsNan; + export function byteLength(field: string): ByteLength; /** * @beta * - * Creates an expression that calculates the length of a string field. + * Creates an expression that calculates the character length of a string field in UTF-8. * * ```typescript - * // Get the length of the 'name' field + * // Get the character length of the 'name' field in UTF-8. * strLength("name"); * ``` * * @param field The name of the field containing the string. * @return A new {@code Expr} representing the length of the string. */ - export function strLength(field: string): StrLength; + export function charLength(field: string): CharLength; /** * @beta * - * Creates an expression that calculates the length of a string expression. + * Creates an expression that calculates the character length of a string expression in UTF-8. * * ```typescript - * // Get the length of the 'name' field + * // Get the character length of the 'name' field in UTF-8. * strLength(Field.of("name")); * ``` * * @param expr The expression representing the string to calculate the length of. * @return A new {@code Expr} representing the length of the string. */ - export function length(expr: Expr): StrLength; + export function charLength(expr: Expr): CharLength; /** * @beta @@ -6337,13 +7583,13 @@ declare namespace FirebaseFirestore { * * ```typescript * // Convert the 'name' field to lowercase - * toLowercase("name"); + * toLower("name"); * ``` * * @param expr The name of the field containing the string. * @return A new {@code Expr} representing the lowercase string. */ - export function toLowercase(expr: string): ToLowercase; + export function toLower(expr: string): ToLower; /** * @beta @@ -6352,13 +7598,13 @@ declare namespace FirebaseFirestore { * * ```typescript * // Convert the 'name' field to lowercase - * toLowercase(Field.of("name")); + * toLower(Field.of("name")); * ``` * * @param expr The expression representing the string to convert to lowercase. * @return A new {@code Expr} representing the lowercase string. */ - export function toLowercase(expr: Expr): ToLowercase; + export function toLower(expr: Expr): ToLower; /** * @beta @@ -6367,13 +7613,13 @@ declare namespace FirebaseFirestore { * * ```typescript * // Convert the 'title' field to uppercase - * toUppercase("title"); + * toUpper("title"); * ``` * * @param expr The name of the field containing the string. * @return A new {@code Expr} representing the uppercase string. */ - export function toUppercase(expr: string): ToUppercase; + export function toUpper(expr: string): ToUpper; /** * @beta @@ -6388,7 +7634,7 @@ declare namespace FirebaseFirestore { * @param expr The expression representing the string to convert to uppercase. * @return A new {@code Expr} representing the uppercase string. */ - export function toUppercase(expr: Expr): ToUppercase; + export function toUpper(expr: Expr): ToUpper; /** * @beta @@ -6969,6 +8215,348 @@ declare namespace FirebaseFirestore { */ export function euclideanDistance(expr: Expr, other: Expr): EuclideanDistance; + /** + * @beta + * + * Creates an expression that calculates the length of a Firestore Vector. + * + * ```typescript + * // Get the vector length (dimension) of the field 'embedding'. + * vectorLength(Field.of("embedding")); + * ``` + * + * @param expr The expression representing the Firestore Vector. + * @return A new {@code Expr} representing the length of the array. + */ + export function vectorLength(expr: Expr): VectorLength; + + /** + * @beta + * + * Creates an expression that calculates the length of a Firestore Vector represented by a field. + * + * ```typescript + * // Get the vector length (dimension) of the field 'embedding'. + * vectorLength("embedding"); + * ``` + * + * @param field The name of the field representing the Firestore Vector. + * @return A new {@code Expr} representing the length of the array. + */ + export function vectorLength(field: string): VectorLength; + + /** + * @beta + * + * Creates an expression that interprets an expression as the number of microseconds since the Unix epoch (1970-01-01 00:00:00 UTC) + * and returns a timestamp. + * + * ```typescript + * // Interpret the 'microseconds' field as microseconds since epoch. + * unixMicrosToTimestamp(Field.of("microseconds")); + * ``` + * + * @param expr The expression representing the number of microseconds since epoch. + * @return A new {@code Expr} representing the timestamp. + */ + export function unixMicrosToTimestamp(expr: Expr): UnixMicrosToTimestamp; + + /** + * @beta + * + * Creates an expression that interprets a field's value as the number of microseconds since the Unix epoch (1970-01-01 00:00:00 UTC) + * and returns a timestamp. + * + * ```typescript + * // Interpret the 'microseconds' field as microseconds since epoch. + * unixMicrosToTimestamp("microseconds"); + * ``` + * + * @param field The name of the field representing the number of microseconds since epoch. + * @return A new {@code Expr} representing the timestamp. + */ + export function unixMicrosToTimestamp(field: string): UnixMicrosToTimestamp; + + /** + * @beta + * + * Creates an expression that converts a timestamp expression to the number of microseconds since the Unix epoch (1970-01-01 00:00:00 UTC). + * + * ```typescript + * // Convert the 'timestamp' field to microseconds since epoch. + * timestampToUnixMicros(Field.of("timestamp")); + * ``` + * + * @param expr The expression representing the timestamp. + * @return A new {@code Expr} representing the number of microseconds since epoch. + */ + export function timestampToUnixMicros(expr: Expr): TimestampToUnixMicros; + + /** + * @beta + * + * Creates an expression that converts a timestamp field to the number of microseconds since the Unix epoch (1970-01-01 00:00:00 UTC). + * + * ```typescript + * // Convert the 'timestamp' field to microseconds since epoch. + * timestampToUnixMicros("timestamp"); + * ``` + * + * @param field The name of the field representing the timestamp. + * @return A new {@code Expr} representing the number of microseconds since epoch. + */ + export function timestampToUnixMicros(field: string): TimestampToUnixMicros; + + /** + * @beta + * + * Creates an expression that interprets an expression as the number of milliseconds since the Unix epoch (1970-01-01 00:00:00 UTC) + * and returns a timestamp. + * + * ```typescript + * // Interpret the 'milliseconds' field as milliseconds since epoch. + * unixMillisToTimestamp(Field.of("milliseconds")); + * ``` + * + * @param expr The expression representing the number of milliseconds since epoch. + * @return A new {@code Expr} representing the timestamp. + */ + export function unixMillisToTimestamp(expr: Expr): UnixMillisToTimestamp; + + /** + * @beta + * + * Creates an expression that interprets a field's value as the number of milliseconds since the Unix epoch (1970-01-01 00:00:00 UTC) + * and returns a timestamp. + * + * ```typescript + * // Interpret the 'milliseconds' field as milliseconds since epoch. + * unixMillisToTimestamp("milliseconds"); + * ``` + * + * @param field The name of the field representing the number of milliseconds since epoch. + * @return A new {@code Expr} representing the timestamp. + */ + export function unixMillisToTimestamp(field: string): UnixMillisToTimestamp; + + /** + * @beta + * + * Creates an expression that converts a timestamp expression to the number of milliseconds since the Unix epoch (1970-01-01 00:00:00 UTC). + * + * ```typescript + * // Convert the 'timestamp' field to milliseconds since epoch. + * timestampToUnixMillis(Field.of("timestamp")); + * ``` + * + * @param expr The expression representing the timestamp. + * @return A new {@code Expr} representing the number of milliseconds since epoch. + */ + export function timestampToUnixMillis(expr: Expr): TimestampToUnixMillis; + + /** + * @beta + * + * Creates an expression that converts a timestamp field to the number of milliseconds since the Unix epoch (1970-01-01 00:00:00 UTC). + * + * ```typescript + * // Convert the 'timestamp' field to milliseconds since epoch. + * timestampToUnixMillis("timestamp"); + * ``` + * + * @param field The name of the field representing the timestamp. + * @return A new {@code Expr} representing the number of milliseconds since epoch. + */ + export function timestampToUnixMillis(field: string): TimestampToUnixMillis; + + /** + * @beta + * + * Creates an expression that interprets an expression as the number of seconds since the Unix epoch (1970-01-01 00:00:00 UTC) + * and returns a timestamp. + * + * ```typescript + * // Interpret the 'seconds' field as seconds since epoch. + * unixSecondsToTimestamp(Field.of("seconds")); + * ``` + * + * @param expr The expression representing the number of seconds since epoch. + * @return A new {@code Expr} representing the timestamp. + */ + export function unixSecondsToTimestamp(expr: Expr): UnixSecondsToTimestamp; + + /** + * @beta + * + * Creates an expression that interprets a field's value as the number of seconds since the Unix epoch (1970-01-01 00:00:00 UTC) + * and returns a timestamp. + * + * ```typescript + * // Interpret the 'seconds' field as seconds since epoch. + * unixSecondsToTimestamp("seconds"); + * ``` + * + * @param field The name of the field representing the number of seconds since epoch. + * @return A new {@code Expr} representing the timestamp. + */ + export function unixSecondsToTimestamp(field: string): UnixSecondsToTimestamp; + + /** + * @beta + * + * Creates an expression that converts a timestamp expression to the number of seconds since the Unix epoch (1970-01-01 00:00:00 UTC). + * + * ```typescript + * // Convert the 'timestamp' field to seconds since epoch. + * timestampToUnixSeconds(Field.of("timestamp")); + * ``` + * + * @param expr The expression representing the timestamp. + * @return A new {@code Expr} representing the number of seconds since epoch. + */ + export function timestampToUnixSeconds(expr: Expr): TimestampToUnixSeconds; + + /** + * @beta + * + * Creates an expression that converts a timestamp field to the number of seconds since the Unix epoch (1970-01-01 00:00:00 UTC). + * + * ```typescript + * // Convert the 'timestamp' field to seconds since epoch. + * timestampToUnixSeconds("timestamp"); + * ``` + * + * @param field The name of the field representing the timestamp. + * @return A new {@code Expr} representing the number of seconds since epoch. + */ + export function timestampToUnixSeconds(field: string): TimestampToUnixSeconds; + + /** + * @beta + * + * Creates an expression that adds a specified amount of time to a timestamp. + * + * ```typescript + * // Add some duration determined by field 'unit' and 'amount' to the 'timestamp' field. + * timestampAdd(Field.of("timestamp"), Field.of("unit"), Field.of("amount")); + * ``` + * + * @param timestamp The expression representing the timestamp. + * @param unit The expression evaluates to unit of time, must be one of 'microsecond', 'millisecond', 'second', 'minute', 'hour', 'day'. + * @param amount The expression evaluates to amount of the unit. + * @return A new {@code Expr} representing the resulting timestamp. + */ + export function timestampAdd( + timestamp: Expr, + unit: Expr, + amount: Expr + ): TimestampAdd; + + /** + * @beta + * + * Creates an expression that adds a specified amount of time to a timestamp. + * + * ```typescript + * // Add 1 day to the 'timestamp' field. + * timestampAdd(Field.of("timestamp"), "day", 1); + * ``` + * + * @param timestamp The expression representing the timestamp. + * @param unit The unit of time to add (e.g., "day", "hour"). + * @param amount The amount of time to add. + * @return A new {@code Expr} representing the resulting timestamp. + */ + export function timestampAdd( + timestamp: Expr, + unit: 'microsecond' | 'millisecond' | 'second' | 'minute' | 'hour' | 'day', + amount: number + ): TimestampAdd; + + /** + * @beta + * + * Creates an expression that adds a specified amount of time to a timestamp represented by a field. + * + * ```typescript + * // Add 1 day to the 'timestamp' field. + * timestampAdd("timestamp", "day", 1); + * ``` + * + * @param field The name of the field representing the timestamp. + * @param unit The unit of time to add (e.g., "day", "hour"). + * @param amount The amount of time to add. + * @return A new {@code Expr} representing the resulting timestamp. + */ + export function timestampAdd( + field: string, + unit: 'microsecond' | 'millisecond' | 'second' | 'minute' | 'hour' | 'day', + amount: number + ): TimestampAdd; + + /** + * @beta + * + * Creates an expression that subtracts a specified amount of time from a timestamp. + * + * ```typescript + * // Subtract some duration determined by field 'unit' and 'amount' from the 'timestamp' field. + * timestampSub(Field.of("timestamp"), Field.of("unit"), Field.of("amount")); + * ``` + * + * @param timestamp The expression representing the timestamp. + * @param unit The expression evaluates to unit of time, must be one of 'microsecond', 'millisecond', 'second', 'minute', 'hour', 'day'. + * @param amount The expression evaluates to amount of the unit. + * @return A new {@code Expr} representing the resulting timestamp. + */ + export function timestampSub( + timestamp: Expr, + unit: Expr, + amount: Expr + ): TimestampSub; + + /** + * @beta + * + * Creates an expression that subtracts a specified amount of time from a timestamp. + * + * ```typescript + * // Subtract 1 day from the 'timestamp' field. + * timestampSub(Field.of("timestamp"), "day", 1); + * ``` + * + * @param timestamp The expression representing the timestamp. + * @param unit The unit of time to subtract (e.g., "day", "hour"). + * @param amount The amount of time to subtract. + * @return A new {@code Expr} representing the resulting timestamp. + */ + export function timestampSub( + timestamp: Expr, + unit: 'microsecond' | 'millisecond' | 'second' | 'minute' | 'hour' | 'day', + amount: number + ): TimestampSub; + + /** + * @beta + * + * Creates an expression that subtracts a specified amount of time from a timestamp represented by a field. + * + * ```typescript + * // Subtract 1 day from the 'timestamp' field. + * timestampSub("timestamp", "day", 1); + * ``` + * + * @param field The name of the field representing the timestamp. + * @param unit The unit of time to subtract (e.g., "day", "hour"). + * @param amount The amount of time to subtract. + * @return A new {@code Expr} representing the resulting timestamp. + */ + export function timestampSub( + field: string, + unit: 'microsecond' | 'millisecond' | 'second' | 'minute' | 'hour' | 'day', + amount: number + ): TimestampSub; + /** * @beta * From 670a124d0571ce46f6935046debce904fc53332b Mon Sep 17 00:00:00 2001 From: Wu-Hui Date: Wed, 25 Sep 2024 16:29:53 -0400 Subject: [PATCH 19/60] comment out bit operations --- dev/src/expression.ts | 1252 ++++++++++++++++++++--------------------- dev/src/index.ts | 12 +- types/firestore.d.ts | 1038 +++++++++++++++++----------------- 3 files changed, 1151 insertions(+), 1151 deletions(-) diff --git a/dev/src/expression.ts b/dev/src/expression.ts index a35134c1e..22a75b438 100644 --- a/dev/src/expression.ts +++ b/dev/src/expression.ts @@ -261,179 +261,179 @@ export abstract class Expr implements firestore.Expr { return new Mod(this, Constant.of(other)); } - /** - * Creates an expression that applies a bitwise AND operation between this expression and another expression. - * - * ```typescript - * // Calculate the bitwise AND of 'field1' and 'field2'. - * Field.of("field1").bitAnd(Field.of("field2")); - * ``` - * - * @param other The right operand expression. - * @return A new {@code Expr} representing the bitwise AND operation. - */ - bitAnd(other: firestore.Expr): BitAnd; - - /** - * Creates an expression that applies a bitwise AND operation between this expression and a constant value. - * - * ```typescript - * // Calculate the bitwise AND of 'field1' and 0xFF. - * Field.of("field1").bitAnd(0xFF); - * ``` - * - * @param other The right operand constant. - * @return A new {@code Expr} representing the bitwise AND operation. - */ - bitAnd(other: any): BitAnd; - bitAnd(other: any): BitAnd { - if (other instanceof Expr) { - return new BitAnd(this, other); - } - return new BitAnd(this, Constant.of(other)); - } - - /** - * Creates an expression that applies a bitwise OR operation between this expression and another expression. - * - * ```typescript - * // Calculate the bitwise OR of 'field1' and 'field2'. - * Field.of("field1").bitOr(Field.of("field2")); - * ``` - * - * @param other The right operand expression. - * @return A new {@code Expr} representing the bitwise OR operation. - */ - bitOr(other: firestore.Expr): BitOr; - - /** - * Creates an expression that applies a bitwise OR operation between this expression and a constant value. - * - * ```typescript - * // Calculate the bitwise OR of 'field1' and 0xFF. - * Field.of("field1").bitOr(0xFF); - * ``` - * - * @param other The right operand constant. - * @return A new {@code Expr} representing the bitwise OR operation. - */ - bitOr(other: any): BitOr; - bitOr(other: any): BitOr { - if (other instanceof Expr) { - return new BitOr(this, other); - } - return new BitOr(this, Constant.of(other)); - } - - /** - * Creates an expression that applies a bitwise XOR operation between this expression and another expression. - * - * ```typescript - * // Calculate the bitwise XOR of 'field1' and 'field2'. - * Field.of("field1").bitXor(Field.of("field2")); - * ``` - * - * @param other The right operand expression. - * @return A new {@code Expr} representing the bitwise XOR operation. - */ - bitXor(other: firestore.Expr): BitXor; - - /** - * Creates an expression that applies a bitwise XOR operation between this expression and a constant value. - * - * ```typescript - * // Calculate the bitwise XOR of 'field1' and 0xFF. - * Field.of("field1").bitXor(0xFF); - * ``` - * - * @param other The right operand constant. - * @return A new {@code Expr} representing the bitwise XOR operation. - */ - bitXor(other: any): BitXor; - bitXor(other: any): BitXor { - if (other instanceof Expr) { - return new BitXor(this, other); - } - return new BitXor(this, Constant.of(other)); - } - - /** - * Creates an expression that applies a bitwise NOT operation to this expression. - * - * ```typescript - * // Calculate the bitwise NOT of 'field1'. - * Field.of("field1").bitNot(); - * ``` - * - * @return A new {@code Expr} representing the bitwise NOT operation. - */ - bitNot(): BitNot { - return new BitNot(this); - } - - /** - * Creates an expression that applies a bitwise left shift operation between this expression and another expression. - * - * ```typescript - * // Calculate the bitwise left shift of 'field1' by 'field2' bits. - * Field.of("field1").bitLeftShift(Field.of("field2")); - * ``` - * - * @param other The right operand expression representing the number of bits to shift. - * @return A new {@code Expr} representing the bitwise left shift operation. - */ - bitLeftShift(other: firestore.Expr): BitLeftShift; - - /** - * Creates an expression that applies a bitwise left shift operation between this expression and a constant value. - * - * ```typescript - * // Calculate the bitwise left shift of 'field1' by 2 bits. - * Field.of("field1").bitLeftShift(2); - * ``` - * - * @param other The right operand constant representing the number of bits to shift. - * @return A new {@code Expr} representing the bitwise left shift operation. - */ - bitLeftShift(other: number): BitLeftShift; - bitLeftShift(other: firestore.Expr | number): BitLeftShift { - if (typeof other === 'number') { - return new BitLeftShift(this, Constant.of(other)); - } - return new BitLeftShift(this, other as Expr); - } - - /** - * Creates an expression that applies a bitwise right shift operation between this expression and another expression. - * - * ```typescript - * // Calculate the bitwise right shift of 'field1' by 'field2' bits. - * Field.of("field1").bitRightShift(Field.of("field2")); - * ``` - * - * @param other The right operand expression representing the number of bits to shift. - * @return A new {@code Expr} representing the bitwise right shift operation. - */ - bitRightShift(other: firestore.Expr): BitRightShift; - - /** - * Creates an expression that applies a bitwise right shift operation between this expression and a constant value. - * - * ```typescript - * // Calculate the bitwise right shift of 'field1' by 2 bits. - * Field.of("field1").bitRightShift(2); - * ``` - * - * @param other The right operand constant representing the number of bits to shift. - * @return A new {@code Expr} representing the bitwise right shift operation. - */ - bitRightShift(other: number): BitRightShift; - bitRightShift(other: firestore.Expr | number): BitRightShift { - if (typeof other === 'number') { - return new BitRightShift(this, Constant.of(other)); - } - return new BitRightShift(this, other as Expr); - } + // /** + // * Creates an expression that applies a bitwise AND operation between this expression and another expression. + // * + // * ```typescript + // * // Calculate the bitwise AND of 'field1' and 'field2'. + // * Field.of("field1").bitAnd(Field.of("field2")); + // * ``` + // * + // * @param other The right operand expression. + // * @return A new {@code Expr} representing the bitwise AND operation. + // */ + // bitAnd(other: firestore.Expr): BitAnd; + // + // /** + // * Creates an expression that applies a bitwise AND operation between this expression and a constant value. + // * + // * ```typescript + // * // Calculate the bitwise AND of 'field1' and 0xFF. + // * Field.of("field1").bitAnd(0xFF); + // * ``` + // * + // * @param other The right operand constant. + // * @return A new {@code Expr} representing the bitwise AND operation. + // */ + // bitAnd(other: any): BitAnd; + // bitAnd(other: any): BitAnd { + // if (other instanceof Expr) { + // return new BitAnd(this, other); + // } + // return new BitAnd(this, Constant.of(other)); + // } + // + // /** + // * Creates an expression that applies a bitwise OR operation between this expression and another expression. + // * + // * ```typescript + // * // Calculate the bitwise OR of 'field1' and 'field2'. + // * Field.of("field1").bitOr(Field.of("field2")); + // * ``` + // * + // * @param other The right operand expression. + // * @return A new {@code Expr} representing the bitwise OR operation. + // */ + // bitOr(other: firestore.Expr): BitOr; + // + // /** + // * Creates an expression that applies a bitwise OR operation between this expression and a constant value. + // * + // * ```typescript + // * // Calculate the bitwise OR of 'field1' and 0xFF. + // * Field.of("field1").bitOr(0xFF); + // * ``` + // * + // * @param other The right operand constant. + // * @return A new {@code Expr} representing the bitwise OR operation. + // */ + // bitOr(other: any): BitOr; + // bitOr(other: any): BitOr { + // if (other instanceof Expr) { + // return new BitOr(this, other); + // } + // return new BitOr(this, Constant.of(other)); + // } + // + // /** + // * Creates an expression that applies a bitwise XOR operation between this expression and another expression. + // * + // * ```typescript + // * // Calculate the bitwise XOR of 'field1' and 'field2'. + // * Field.of("field1").bitXor(Field.of("field2")); + // * ``` + // * + // * @param other The right operand expression. + // * @return A new {@code Expr} representing the bitwise XOR operation. + // */ + // bitXor(other: firestore.Expr): BitXor; + // + // /** + // * Creates an expression that applies a bitwise XOR operation between this expression and a constant value. + // * + // * ```typescript + // * // Calculate the bitwise XOR of 'field1' and 0xFF. + // * Field.of("field1").bitXor(0xFF); + // * ``` + // * + // * @param other The right operand constant. + // * @return A new {@code Expr} representing the bitwise XOR operation. + // */ + // bitXor(other: any): BitXor; + // bitXor(other: any): BitXor { + // if (other instanceof Expr) { + // return new BitXor(this, other); + // } + // return new BitXor(this, Constant.of(other)); + // } + // + // /** + // * Creates an expression that applies a bitwise NOT operation to this expression. + // * + // * ```typescript + // * // Calculate the bitwise NOT of 'field1'. + // * Field.of("field1").bitNot(); + // * ``` + // * + // * @return A new {@code Expr} representing the bitwise NOT operation. + // */ + // bitNot(): BitNot { + // return new BitNot(this); + // } + // + // /** + // * Creates an expression that applies a bitwise left shift operation between this expression and another expression. + // * + // * ```typescript + // * // Calculate the bitwise left shift of 'field1' by 'field2' bits. + // * Field.of("field1").bitLeftShift(Field.of("field2")); + // * ``` + // * + // * @param other The right operand expression representing the number of bits to shift. + // * @return A new {@code Expr} representing the bitwise left shift operation. + // */ + // bitLeftShift(other: firestore.Expr): BitLeftShift; + // + // /** + // * Creates an expression that applies a bitwise left shift operation between this expression and a constant value. + // * + // * ```typescript + // * // Calculate the bitwise left shift of 'field1' by 2 bits. + // * Field.of("field1").bitLeftShift(2); + // * ``` + // * + // * @param other The right operand constant representing the number of bits to shift. + // * @return A new {@code Expr} representing the bitwise left shift operation. + // */ + // bitLeftShift(other: number): BitLeftShift; + // bitLeftShift(other: firestore.Expr | number): BitLeftShift { + // if (typeof other === 'number') { + // return new BitLeftShift(this, Constant.of(other)); + // } + // return new BitLeftShift(this, other as Expr); + // } + // + // /** + // * Creates an expression that applies a bitwise right shift operation between this expression and another expression. + // * + // * ```typescript + // * // Calculate the bitwise right shift of 'field1' by 'field2' bits. + // * Field.of("field1").bitRightShift(Field.of("field2")); + // * ``` + // * + // * @param other The right operand expression representing the number of bits to shift. + // * @return A new {@code Expr} representing the bitwise right shift operation. + // */ + // bitRightShift(other: firestore.Expr): BitRightShift; + // + // /** + // * Creates an expression that applies a bitwise right shift operation between this expression and a constant value. + // * + // * ```typescript + // * // Calculate the bitwise right shift of 'field1' by 2 bits. + // * Field.of("field1").bitRightShift(2); + // * ``` + // * + // * @param other The right operand constant representing the number of bits to shift. + // * @return A new {@code Expr} representing the bitwise right shift operation. + // */ + // bitRightShift(other: number): BitRightShift; + // bitRightShift(other: firestore.Expr | number): BitRightShift { + // if (typeof other === 'number') { + // return new BitRightShift(this, Constant.of(other)); + // } + // return new BitRightShift(this, other as Expr); + // } /** * Creates an expression that checks if this expression is equal to another expression. @@ -2169,74 +2169,74 @@ export class Mod extends Function { } } -/** - * @beta - */ -export class BitAnd extends Function { - constructor( - private left: Expr, - private right: Expr - ) { - super('bit_and', [left, right]); - } -} - -/** - * @beta - */ -export class BitOr extends Function { - constructor( - private left: Expr, - private right: Expr - ) { - super('bit_or', [left, right]); - } -} - -/** - * @beta - */ -export class BitXor extends Function { - constructor( - private left: Expr, - private right: Expr - ) { - super('bit_xor', [left, right]); - } -} - -/** - * @beta - */ -export class BitNot extends Function { - constructor(private operand: Expr) { - super('bit_not', [operand]); - } -} - -/** - * @beta - */ -export class BitLeftShift extends Function { - constructor( - private left: Expr, - private right: Expr - ) { - super('bit_left_shift', [left, right]); - } -} - -/** - * @beta - */ -export class BitRightShift extends Function { - constructor( - private left: Expr, - private right: Expr - ) { - super('bit_right_shift', [left, right]); - } -} +// /** +// * @beta +// */ +// export class BitAnd extends Function { +// constructor( +// private left: Expr, +// private right: Expr +// ) { +// super('bit_and', [left, right]); +// } +// } +// +// /** +// * @beta +// */ +// export class BitOr extends Function { +// constructor( +// private left: Expr, +// private right: Expr +// ) { +// super('bit_or', [left, right]); +// } +// } +// +// /** +// * @beta +// */ +// export class BitXor extends Function { +// constructor( +// private left: Expr, +// private right: Expr +// ) { +// super('bit_xor', [left, right]); +// } +// } +// +// /** +// * @beta +// */ +// export class BitNot extends Function { +// constructor(private operand: Expr) { +// super('bit_not', [operand]); +// } +// } +// +// /** +// * @beta +// */ +// export class BitLeftShift extends Function { +// constructor( +// private left: Expr, +// private right: Expr +// ) { +// super('bit_left_shift', [left, right]); +// } +// } +// +// /** +// * @beta +// */ +// export class BitRightShift extends Function { +// constructor( +// private left: Expr, +// private right: Expr +// ) { +// super('bit_right_shift', [left, right]); +// } +// } /** * @beta @@ -3207,391 +3207,391 @@ export function mod(left: Expr | string, right: Expr | any): Mod { return new Mod(normalizedLeft, normalizedRight); } -/** - * @beta - * - * Creates an expression that applies a bitwise AND operation between two expressions. - * - * ```typescript - * // Calculate the bitwise AND of 'field1' and 'field2'. - * bitAnd(Field.of("field1"), Field.of("field2")); - * ``` - * - * @param left The left operand expression. - * @param right The right operand expression. - * @return A new {@code Expr} representing the bitwise AND operation. - */ -export function bitAnd(left: Expr, right: Expr): BitAnd; - -/** - * @beta - * - * Creates an expression that applies a bitwise AND operation between an expression and a constant. - * - * ```typescript - * // Calculate the bitwise AND of 'field1' and 0xFF. - * bitAnd(Field.of("field1"), 0xFF); - * ``` - * - * @param left The left operand expression. - * @param right The right operand constant. - * @return A new {@code Expr} representing the bitwise AND operation. - */ -export function bitAnd(left: Expr, right: any): BitAnd; - -/** - * @beta - * - * Creates an expression that applies a bitwise AND operation between a field and an expression. - * - * ```typescript - * // Calculate the bitwise AND of 'field1' and 'field2'. - * bitAnd("field1", Field.of("field2")); - * ``` - * - * @param left The left operand field name. - * @param right The right operand expression. - * @return A new {@code Expr} representing the bitwise AND operation. - */ -export function bitAnd(left: string, right: Expr): BitAnd; - -/** - * @beta - * - * Creates an expression that applies a bitwise AND operation between a field and a constant. - * - * ```typescript - * // Calculate the bitwise AND of 'field1' and 0xFF. - * bitAnd("field1", 0xFF); - * ``` - * - * @param left The left operand field name. - * @param right The right operand constant. - * @return A new {@code Expr} representing the bitwise AND operation. - */ -export function bitAnd(left: string, right: any): BitAnd; -export function bitAnd(left: Expr | string, right: Expr | any): BitAnd { - const normalizedLeft = typeof left === 'string' ? Field.of(left) : left; - const normalizedRight = right instanceof Expr ? right : Constant.of(right); - return new BitAnd(normalizedLeft, normalizedRight); -} - -/** - * @beta - * - * Creates an expression that applies a bitwise OR operation between two expressions. - * - * ```typescript - * // Calculate the bitwise OR of 'field1' and 'field2'. - * bitOr(Field.of("field1"), Field.of("field2")); - * ``` - * - * @param left The left operand expression. - * @param right The right operand expression. - * @return A new {@code Expr} representing the bitwise OR operation. - */ -export function bitOr(left: Expr, right: Expr): BitOr; - -/** - * @beta - * - * Creates an expression that applies a bitwise OR operation between an expression and a constant. - * - * ```typescript - * // Calculate the bitwise OR of 'field1' and 0xFF. - * bitOr(Field.of("field1"), 0xFF); - * ``` - * - * @param left The left operand expression. - * @param right The right operand constant. - * @return A new {@code Expr} representing the bitwise OR operation. - */ -export function bitOr(left: Expr, right: any): BitOr; - -/** - * @beta - * - * Creates an expression that applies a bitwise OR operation between a field and an expression. - * - * ```typescript - * // Calculate the bitwise OR of 'field1' and 'field2'. - * bitOr("field1", Field.of("field2")); - * ``` - * - * @param left The left operand field name. - * @param right The right operand expression. - * @return A new {@code Expr} representing the bitwise OR operation. - */ -export function bitOr(left: string, right: Expr): BitOr; - -/** - * @beta - * - * Creates an expression that applies a bitwise OR operation between a field and a constant. - * - * ```typescript - * // Calculate the bitwise OR of 'field1' and 0xFF. - * bitOr("field1", 0xFF); - * ``` - * - * @param left The left operand field name. - * @param right The right operand constant. - * @return A new {@code Expr} representing the bitwise OR operation. - */ -export function bitOr(left: string, right: any): BitOr; -export function bitOr(left: Expr | string, right: Expr | any): BitOr { - const normalizedLeft = typeof left === 'string' ? Field.of(left) : left; - const normalizedRight = right instanceof Expr ? right : Constant.of(right); - return new BitOr(normalizedLeft, normalizedRight); -} - -/** - * @beta - * - * Creates an expression that applies a bitwise XOR operation between two expressions. - * - * ```typescript - * // Calculate the bitwise XOR of 'field1' and 'field2'. - * bitXor(Field.of("field1"), Field.of("field2")); - * ``` - * - * @param left The left operand expression. - * @param right The right operand expression. - * @return A new {@code Expr} representing the bitwise XOR operation. - */ -export function bitXor(left: Expr, right: Expr): BitXor; - -/** - * @beta - * - * Creates an expression that applies a bitwise XOR operation between an expression and a constant. - * - * ```typescript - * // Calculate the bitwise XOR of 'field1' and 0xFF. - * bitXor(Field.of("field1"), 0xFF); - * ``` - * - * @param left The left operand expression. - * @param right The right operand constant. - * @return A new {@code Expr} representing the bitwise XOR operation. - */ -export function bitXor(left: Expr, right: any): BitXor; - -/** - * @beta - * - * Creates an expression that applies a bitwise XOR operation between a field and an expression. - * - * ```typescript - * // Calculate the bitwise XOR of 'field1' and 'field2'. - * bitXor("field1", Field.of("field2")); - * ``` - * - * @param left The left operand field name. - * @param right The right operand expression. - * @return A new {@code Expr} representing the bitwise XOR operation. - */ -export function bitXor(left: string, right: Expr): BitXor; - -/** - * @beta - * - * Creates an expression that applies a bitwise XOR operation between a field and a constant. - * - * ```typescript - * // Calculate the bitwise XOR of 'field1' and 0xFF. - * bitXor("field1", 0xFF); - * ``` - * - * @param left The left operand field name. - * @param right The right operand constant. - * @return A new {@code Expr} representing the bitwise XOR operation. - */ -export function bitXor(left: string, right: any): BitXor; -export function bitXor(left: Expr | string, right: Expr | any): BitXor { - const normalizedLeft = typeof left === 'string' ? Field.of(left) : left; - const normalizedRight = right instanceof Expr ? right : Constant.of(right); - return new BitXor(normalizedLeft, normalizedRight); -} - -/** - * @beta - * - * Creates an expression that applies a bitwise NOT operation to an expression. - * - * ```typescript - * // Calculate the bitwise NOT of 'field1'. - * bitNot(Field.of("field1")); - * ``` - * - * @param operand The operand expression. - * @return A new {@code Expr} representing the bitwise NOT operation. - */ -export function bitNot(operand: Expr): BitNot; - -/** - * @beta - * - * Creates an expression that applies a bitwise NOT operation to a field. - * - * ```typescript - * // Calculate the bitwise NOT of 'field1'. - * bitNot("field1"); - * ``` - * - * @param operand The operand field name. - * @return A new {@code Expr} representing the bitwise NOT operation. - */ -export function bitNot(operand: string): BitNot; -export function bitNot(operand: Expr | string): BitNot { - const normalizedOperand = - typeof operand === 'string' ? Field.of(operand) : operand; - return new BitNot(normalizedOperand); -} - -/** - * @beta - * - * Creates an expression that applies a bitwise left shift operation between two expressions. - * - * ```typescript - * // Calculate the bitwise left shift of 'field1' by 'field2' bits. - * bitLeftShift(Field.of("field1"), Field.of("field2")); - * ``` - * - * @param left The left operand expression. - * @param right The right operand expression representing the number of bits to shift. - * @return A new {@code Expr} representing the bitwise left shift operation. - */ -export function bitLeftShift(left: Expr, right: Expr): BitLeftShift; - -/** - * @beta - * - * Creates an expression that applies a bitwise left shift operation between an expression and a constant. - * - * ```typescript - * // Calculate the bitwise left shift of 'field1' by 2 bits. - * bitLeftShift(Field.of("field1"), 2); - * ``` - * - * @param left The left operand expression. - * @param right The right operand constant representing the number of bits to shift. - * @return A new {@code Expr} representing the bitwise left shift operation. - */ -export function bitLeftShift(left: Expr, right: any): BitLeftShift; - -/** - * @beta - * - * Creates an expression that applies a bitwise left shift operation between a field and an expression. - * - * ```typescript - * // Calculate the bitwise left shift of 'field1' by 'field2' bits. - * bitLeftShift("field1", Field.of("field2")); - * ``` - * - * @param left The left operand field name. - * @param right The right operand expression representing the number of bits to shift. - * @return A new {@code Expr} representing the bitwise left shift operation. - */ -export function bitLeftShift(left: string, right: Expr): BitLeftShift; - -/** - * @beta - * - * Creates an expression that applies a bitwise left shift operation between a field and a constant. - * - * ```typescript - * // Calculate the bitwise left shift of 'field1' by 2 bits. - * bitLeftShift("field1", 2); - * ``` - * - * @param left The left operand field name. - * @param right The right operand constant representing the number of bits to shift. - * @return A new {@code Expr} representing the bitwise left shift operation. - */ -export function bitLeftShift(left: string, right: any): BitLeftShift; -export function bitLeftShift( - left: Expr | string, - right: Expr | any -): BitLeftShift { - const normalizedLeft = typeof left === 'string' ? Field.of(left) : left; - const normalizedRight = right instanceof Expr ? right : Constant.of(right); - return new BitLeftShift(normalizedLeft, normalizedRight); -} - -/** - * @beta - * - * Creates an expression that applies a bitwise right shift operation between two expressions. - * - * ```typescript - * // Calculate the bitwise right shift of 'field1' by 'field2' bits. - * bitRightShift(Field.of("field1"), Field.of("field2")); - * ``` - * - * @param left The left operand expression. - * @param right The right operand expression representing the number of bits to shift. - * @return A new {@code Expr} representing the bitwise right shift operation. - */ -export function bitRightShift(left: Expr, right: Expr): BitRightShift; - -/** - * @beta - * - * Creates an expression that applies a bitwise right shift operation between an expression and a constant. - * - * ```typescript - * // Calculate the bitwise right shift of 'field1' by 2 bits. - * bitRightShift(Field.of("field1"), 2); - * ``` - * - * @param left The left operand expression. - * @param right The right operand constant representing the number of bits to shift. - * @return A new {@code Expr} representing the bitwise right shift operation. - */ -export function bitRightShift(left: Expr, right: any): BitRightShift; - -/** - * @beta - * - * Creates an expression that applies a bitwise right shift operation between a field and an expression. - * - * ```typescript - * // Calculate the bitwise right shift of 'field1' by 'field2' bits. - * bitRightShift("field1", Field.of("field2")); - * ``` - * - * @param left The left operand field name. - * @param right The right operand expression representing the number of bits to shift. - * @return A new {@code Expr} representing the bitwise right shift operation. - */ -export function bitRightShift(left: string, right: Expr): BitRightShift; - -/** - * @beta - * - * Creates an expression that applies a bitwise right shift operation between a field and a constant. - * - * ```typescript - * // Calculate the bitwise right shift of 'field1' by 2 bits. - * bitRightShift("field1", 2); - * ``` - * - * @param left The left operand field name. - * @param right The right operand constant representing the number of bits to shift. - * @return A new {@code Expr} representing the bitwise right shift operation. - */ -export function bitRightShift(left: string, right: any): BitRightShift; -export function bitRightShift( - left: Expr | string, - right: Expr | any -): BitRightShift { - const normalizedLeft = typeof left === 'string' ? Field.of(left) : left; - const normalizedRight = right instanceof Expr ? right : Constant.of(right); - return new BitRightShift(normalizedLeft, normalizedRight); -} +// /** +// * @beta +// * +// * Creates an expression that applies a bitwise AND operation between two expressions. +// * +// * ```typescript +// * // Calculate the bitwise AND of 'field1' and 'field2'. +// * bitAnd(Field.of("field1"), Field.of("field2")); +// * ``` +// * +// * @param left The left operand expression. +// * @param right The right operand expression. +// * @return A new {@code Expr} representing the bitwise AND operation. +// */ +// export function bitAnd(left: Expr, right: Expr): BitAnd; +// +// /** +// * @beta +// * +// * Creates an expression that applies a bitwise AND operation between an expression and a constant. +// * +// * ```typescript +// * // Calculate the bitwise AND of 'field1' and 0xFF. +// * bitAnd(Field.of("field1"), 0xFF); +// * ``` +// * +// * @param left The left operand expression. +// * @param right The right operand constant. +// * @return A new {@code Expr} representing the bitwise AND operation. +// */ +// export function bitAnd(left: Expr, right: any): BitAnd; +// +// /** +// * @beta +// * +// * Creates an expression that applies a bitwise AND operation between a field and an expression. +// * +// * ```typescript +// * // Calculate the bitwise AND of 'field1' and 'field2'. +// * bitAnd("field1", Field.of("field2")); +// * ``` +// * +// * @param left The left operand field name. +// * @param right The right operand expression. +// * @return A new {@code Expr} representing the bitwise AND operation. +// */ +// export function bitAnd(left: string, right: Expr): BitAnd; +// +// /** +// * @beta +// * +// * Creates an expression that applies a bitwise AND operation between a field and a constant. +// * +// * ```typescript +// * // Calculate the bitwise AND of 'field1' and 0xFF. +// * bitAnd("field1", 0xFF); +// * ``` +// * +// * @param left The left operand field name. +// * @param right The right operand constant. +// * @return A new {@code Expr} representing the bitwise AND operation. +// */ +// export function bitAnd(left: string, right: any): BitAnd; +// export function bitAnd(left: Expr | string, right: Expr | any): BitAnd { +// const normalizedLeft = typeof left === 'string' ? Field.of(left) : left; +// const normalizedRight = right instanceof Expr ? right : Constant.of(right); +// return new BitAnd(normalizedLeft, normalizedRight); +// } +// +// /** +// * @beta +// * +// * Creates an expression that applies a bitwise OR operation between two expressions. +// * +// * ```typescript +// * // Calculate the bitwise OR of 'field1' and 'field2'. +// * bitOr(Field.of("field1"), Field.of("field2")); +// * ``` +// * +// * @param left The left operand expression. +// * @param right The right operand expression. +// * @return A new {@code Expr} representing the bitwise OR operation. +// */ +// export function bitOr(left: Expr, right: Expr): BitOr; +// +// /** +// * @beta +// * +// * Creates an expression that applies a bitwise OR operation between an expression and a constant. +// * +// * ```typescript +// * // Calculate the bitwise OR of 'field1' and 0xFF. +// * bitOr(Field.of("field1"), 0xFF); +// * ``` +// * +// * @param left The left operand expression. +// * @param right The right operand constant. +// * @return A new {@code Expr} representing the bitwise OR operation. +// */ +// export function bitOr(left: Expr, right: any): BitOr; +// +// /** +// * @beta +// * +// * Creates an expression that applies a bitwise OR operation between a field and an expression. +// * +// * ```typescript +// * // Calculate the bitwise OR of 'field1' and 'field2'. +// * bitOr("field1", Field.of("field2")); +// * ``` +// * +// * @param left The left operand field name. +// * @param right The right operand expression. +// * @return A new {@code Expr} representing the bitwise OR operation. +// */ +// export function bitOr(left: string, right: Expr): BitOr; +// +// /** +// * @beta +// * +// * Creates an expression that applies a bitwise OR operation between a field and a constant. +// * +// * ```typescript +// * // Calculate the bitwise OR of 'field1' and 0xFF. +// * bitOr("field1", 0xFF); +// * ``` +// * +// * @param left The left operand field name. +// * @param right The right operand constant. +// * @return A new {@code Expr} representing the bitwise OR operation. +// */ +// export function bitOr(left: string, right: any): BitOr; +// export function bitOr(left: Expr | string, right: Expr | any): BitOr { +// const normalizedLeft = typeof left === 'string' ? Field.of(left) : left; +// const normalizedRight = right instanceof Expr ? right : Constant.of(right); +// return new BitOr(normalizedLeft, normalizedRight); +// } +// +// /** +// * @beta +// * +// * Creates an expression that applies a bitwise XOR operation between two expressions. +// * +// * ```typescript +// * // Calculate the bitwise XOR of 'field1' and 'field2'. +// * bitXor(Field.of("field1"), Field.of("field2")); +// * ``` +// * +// * @param left The left operand expression. +// * @param right The right operand expression. +// * @return A new {@code Expr} representing the bitwise XOR operation. +// */ +// export function bitXor(left: Expr, right: Expr): BitXor; +// +// /** +// * @beta +// * +// * Creates an expression that applies a bitwise XOR operation between an expression and a constant. +// * +// * ```typescript +// * // Calculate the bitwise XOR of 'field1' and 0xFF. +// * bitXor(Field.of("field1"), 0xFF); +// * ``` +// * +// * @param left The left operand expression. +// * @param right The right operand constant. +// * @return A new {@code Expr} representing the bitwise XOR operation. +// */ +// export function bitXor(left: Expr, right: any): BitXor; +// +// /** +// * @beta +// * +// * Creates an expression that applies a bitwise XOR operation between a field and an expression. +// * +// * ```typescript +// * // Calculate the bitwise XOR of 'field1' and 'field2'. +// * bitXor("field1", Field.of("field2")); +// * ``` +// * +// * @param left The left operand field name. +// * @param right The right operand expression. +// * @return A new {@code Expr} representing the bitwise XOR operation. +// */ +// export function bitXor(left: string, right: Expr): BitXor; +// +// /** +// * @beta +// * +// * Creates an expression that applies a bitwise XOR operation between a field and a constant. +// * +// * ```typescript +// * // Calculate the bitwise XOR of 'field1' and 0xFF. +// * bitXor("field1", 0xFF); +// * ``` +// * +// * @param left The left operand field name. +// * @param right The right operand constant. +// * @return A new {@code Expr} representing the bitwise XOR operation. +// */ +// export function bitXor(left: string, right: any): BitXor; +// export function bitXor(left: Expr | string, right: Expr | any): BitXor { +// const normalizedLeft = typeof left === 'string' ? Field.of(left) : left; +// const normalizedRight = right instanceof Expr ? right : Constant.of(right); +// return new BitXor(normalizedLeft, normalizedRight); +// } +// +// /** +// * @beta +// * +// * Creates an expression that applies a bitwise NOT operation to an expression. +// * +// * ```typescript +// * // Calculate the bitwise NOT of 'field1'. +// * bitNot(Field.of("field1")); +// * ``` +// * +// * @param operand The operand expression. +// * @return A new {@code Expr} representing the bitwise NOT operation. +// */ +// export function bitNot(operand: Expr): BitNot; +// +// /** +// * @beta +// * +// * Creates an expression that applies a bitwise NOT operation to a field. +// * +// * ```typescript +// * // Calculate the bitwise NOT of 'field1'. +// * bitNot("field1"); +// * ``` +// * +// * @param operand The operand field name. +// * @return A new {@code Expr} representing the bitwise NOT operation. +// */ +// export function bitNot(operand: string): BitNot; +// export function bitNot(operand: Expr | string): BitNot { +// const normalizedOperand = +// typeof operand === 'string' ? Field.of(operand) : operand; +// return new BitNot(normalizedOperand); +// } +// +// /** +// * @beta +// * +// * Creates an expression that applies a bitwise left shift operation between two expressions. +// * +// * ```typescript +// * // Calculate the bitwise left shift of 'field1' by 'field2' bits. +// * bitLeftShift(Field.of("field1"), Field.of("field2")); +// * ``` +// * +// * @param left The left operand expression. +// * @param right The right operand expression representing the number of bits to shift. +// * @return A new {@code Expr} representing the bitwise left shift operation. +// */ +// export function bitLeftShift(left: Expr, right: Expr): BitLeftShift; +// +// /** +// * @beta +// * +// * Creates an expression that applies a bitwise left shift operation between an expression and a constant. +// * +// * ```typescript +// * // Calculate the bitwise left shift of 'field1' by 2 bits. +// * bitLeftShift(Field.of("field1"), 2); +// * ``` +// * +// * @param left The left operand expression. +// * @param right The right operand constant representing the number of bits to shift. +// * @return A new {@code Expr} representing the bitwise left shift operation. +// */ +// export function bitLeftShift(left: Expr, right: any): BitLeftShift; +// +// /** +// * @beta +// * +// * Creates an expression that applies a bitwise left shift operation between a field and an expression. +// * +// * ```typescript +// * // Calculate the bitwise left shift of 'field1' by 'field2' bits. +// * bitLeftShift("field1", Field.of("field2")); +// * ``` +// * +// * @param left The left operand field name. +// * @param right The right operand expression representing the number of bits to shift. +// * @return A new {@code Expr} representing the bitwise left shift operation. +// */ +// export function bitLeftShift(left: string, right: Expr): BitLeftShift; +// +// /** +// * @beta +// * +// * Creates an expression that applies a bitwise left shift operation between a field and a constant. +// * +// * ```typescript +// * // Calculate the bitwise left shift of 'field1' by 2 bits. +// * bitLeftShift("field1", 2); +// * ``` +// * +// * @param left The left operand field name. +// * @param right The right operand constant representing the number of bits to shift. +// * @return A new {@code Expr} representing the bitwise left shift operation. +// */ +// export function bitLeftShift(left: string, right: any): BitLeftShift; +// export function bitLeftShift( +// left: Expr | string, +// right: Expr | any +// ): BitLeftShift { +// const normalizedLeft = typeof left === 'string' ? Field.of(left) : left; +// const normalizedRight = right instanceof Expr ? right : Constant.of(right); +// return new BitLeftShift(normalizedLeft, normalizedRight); +// } +// +// /** +// * @beta +// * +// * Creates an expression that applies a bitwise right shift operation between two expressions. +// * +// * ```typescript +// * // Calculate the bitwise right shift of 'field1' by 'field2' bits. +// * bitRightShift(Field.of("field1"), Field.of("field2")); +// * ``` +// * +// * @param left The left operand expression. +// * @param right The right operand expression representing the number of bits to shift. +// * @return A new {@code Expr} representing the bitwise right shift operation. +// */ +// export function bitRightShift(left: Expr, right: Expr): BitRightShift; +// +// /** +// * @beta +// * +// * Creates an expression that applies a bitwise right shift operation between an expression and a constant. +// * +// * ```typescript +// * // Calculate the bitwise right shift of 'field1' by 2 bits. +// * bitRightShift(Field.of("field1"), 2); +// * ``` +// * +// * @param left The left operand expression. +// * @param right The right operand constant representing the number of bits to shift. +// * @return A new {@code Expr} representing the bitwise right shift operation. +// */ +// export function bitRightShift(left: Expr, right: any): BitRightShift; +// +// /** +// * @beta +// * +// * Creates an expression that applies a bitwise right shift operation between a field and an expression. +// * +// * ```typescript +// * // Calculate the bitwise right shift of 'field1' by 'field2' bits. +// * bitRightShift("field1", Field.of("field2")); +// * ``` +// * +// * @param left The left operand field name. +// * @param right The right operand expression representing the number of bits to shift. +// * @return A new {@code Expr} representing the bitwise right shift operation. +// */ +// export function bitRightShift(left: string, right: Expr): BitRightShift; +// +// /** +// * @beta +// * +// * Creates an expression that applies a bitwise right shift operation between a field and a constant. +// * +// * ```typescript +// * // Calculate the bitwise right shift of 'field1' by 2 bits. +// * bitRightShift("field1", 2); +// * ``` +// * +// * @param left The left operand field name. +// * @param right The right operand constant representing the number of bits to shift. +// * @return A new {@code Expr} representing the bitwise right shift operation. +// */ +// export function bitRightShift(left: string, right: any): BitRightShift; +// export function bitRightShift( +// left: Expr | string, +// right: Expr | any +// ): BitRightShift { +// const normalizedLeft = typeof left === 'string' ? Field.of(left) : left; +// const normalizedRight = right instanceof Expr ? right : Constant.of(right); +// return new BitRightShift(normalizedLeft, normalizedRight); +// } /** * @beta diff --git a/dev/src/index.ts b/dev/src/index.ts index cfca3b879..54af20aba 100644 --- a/dev/src/index.ts +++ b/dev/src/index.ts @@ -188,12 +188,12 @@ export { genericFunction, ascending, descending, - bitLeftShift, - bitOr, - bitRightShift, - bitXor, - bitAnd, - bitNot, + // bitLeftShift, + // bitOr, + // bitRightShift, + // bitXor, + // bitAnd, + // bitNot, timestampAdd, timestampSub, timestampToUnixMicros, diff --git a/types/firestore.d.ts b/types/firestore.d.ts index b8e95db59..16941d12b 100644 --- a/types/firestore.d.ts +++ b/types/firestore.d.ts @@ -3407,147 +3407,147 @@ declare namespace FirebaseFirestore { */ mod(other: any): Mod; - /** - * Creates an expression that applies a bitwise AND operation between this expression and another expression. - * - * ```typescript - * // Calculate the bitwise AND of 'field1' and 'field2'. - * Field.of("field1").bitAnd(Field.of("field2")); - * ``` - * - * @param other The right operand expression. - * @return A new {@code Expr} representing the bitwise AND operation. - */ - bitAnd(other: Expr): BitAnd; - - /** - * Creates an expression that applies a bitwise AND operation between this expression and a constant value. - * - * ```typescript - * // Calculate the bitwise AND of 'field1' and 0xFF. - * Field.of("field1").bitAnd(0xFF); - * ``` - * - * @param other The right operand constant. - * @return A new {@code Expr} representing the bitwise AND operation. - */ - bitAnd(other: any): BitAnd; - - /** - * Creates an expression that applies a bitwise OR operation between this expression and another expression. - * - * ```typescript - * // Calculate the bitwise OR of 'field1' and 'field2'. - * Field.of("field1").bitOr(Field.of("field2")); - * ``` - * - * @param other The right operand expression. - * @return A new {@code Expr} representing the bitwise OR operation. - */ - bitOr(other: Expr): BitOr; - - /** - * Creates an expression that applies a bitwise OR operation between this expression and a constant value. - * - * ```typescript - * // Calculate the bitwise OR of 'field1' and 0xFF. - * Field.of("field1").bitOr(0xFF); - * ``` - * - * @param other The right operand constant. - * @return A new {@code Expr} representing the bitwise OR operation. - */ - bitOr(other: any): BitOr; - - /** - * Creates an expression that applies a bitwise XOR operation between this expression and another expression. - * - * ```typescript - * // Calculate the bitwise XOR of 'field1' and 'field2'. - * Field.of("field1").bitXor(Field.of("field2")); - * ``` - * - * @param other The right operand expression. - * @return A new {@code Expr} representing the bitwise XOR operation. - */ - bitXor(other: Expr): BitXor; - - /** - * Creates an expression that applies a bitwise XOR operation between this expression and a constant value. - * - * ```typescript - * // Calculate the bitwise XOR of 'field1' and 0xFF. - * Field.of("field1").bitXor(0xFF); - * ``` - * - * @param other The right operand constant. - * @return A new {@code Expr} representing the bitwise XOR operation. - */ - bitXor(other: any): BitXor; - - /** - * Creates an expression that applies a bitwise NOT operation to this expression. - * - * ```typescript - * // Calculate the bitwise NOT of 'field1'. - * Field.of("field1").bitNot(); - * ``` - * - * @return A new {@code Expr} representing the bitwise NOT operation. - */ - bitNot(): BitNot; - - /** - * Creates an expression that applies a bitwise left shift operation between this expression and another expression. - * - * ```typescript - * // Calculate the bitwise left shift of 'field1' by 'field2' bits. - * Field.of("field1").bitLeftShift(Field.of("field2")); - * ``` - * - * @param other The right operand expression representing the number of bits to shift. - * @return A new {@code Expr} representing the bitwise left shift operation. - */ - bitLeftShift(other: Expr): BitLeftShift; - - /** - * Creates an expression that applies a bitwise left shift operation between this expression and a constant value. - * - * ```typescript - * // Calculate the bitwise left shift of 'field1' by 2 bits. - * Field.of("field1").bitLeftShift(2); - * ``` - * - * @param other The right operand constant representing the number of bits to shift. - * @return A new {@code Expr} representing the bitwise left shift operation. - */ - bitLeftShift(other: number): BitLeftShift; - - /** - * Creates an expression that applies a bitwise right shift operation between this expression and another expression. - * - * ```typescript - * // Calculate the bitwise right shift of 'field1' by 'field2' bits. - * Field.of("field1").bitRightShift(Field.of("field2")); - * ``` - * - * @param other The right operand expression representing the number of bits to shift. - * @return A new {@code Expr} representing the bitwise right shift operation. - */ - bitRightShift(other: Expr): BitRightShift; - - /** - * Creates an expression that applies a bitwise right shift operation between this expression and a constant value. - * - * ```typescript - * // Calculate the bitwise right shift of 'field1' by 2 bits. - * Field.of("field1").bitRightShift(2); - * ``` - * - * @param other The right operand constant representing the number of bits to shift. - * @return A new {@code Expr} representing the bitwise right shift operation. - */ - bitRightShift(other: number): BitRightShift; + // /** + // * Creates an expression that applies a bitwise AND operation between this expression and another expression. + // * + // * ```typescript + // * // Calculate the bitwise AND of 'field1' and 'field2'. + // * Field.of("field1").bitAnd(Field.of("field2")); + // * ``` + // * + // * @param other The right operand expression. + // * @return A new {@code Expr} representing the bitwise AND operation. + // */ + // bitAnd(other: Expr): BitAnd; + // + // /** + // * Creates an expression that applies a bitwise AND operation between this expression and a constant value. + // * + // * ```typescript + // * // Calculate the bitwise AND of 'field1' and 0xFF. + // * Field.of("field1").bitAnd(0xFF); + // * ``` + // * + // * @param other The right operand constant. + // * @return A new {@code Expr} representing the bitwise AND operation. + // */ + // bitAnd(other: any): BitAnd; + // + // /** + // * Creates an expression that applies a bitwise OR operation between this expression and another expression. + // * + // * ```typescript + // * // Calculate the bitwise OR of 'field1' and 'field2'. + // * Field.of("field1").bitOr(Field.of("field2")); + // * ``` + // * + // * @param other The right operand expression. + // * @return A new {@code Expr} representing the bitwise OR operation. + // */ + // bitOr(other: Expr): BitOr; + // + // /** + // * Creates an expression that applies a bitwise OR operation between this expression and a constant value. + // * + // * ```typescript + // * // Calculate the bitwise OR of 'field1' and 0xFF. + // * Field.of("field1").bitOr(0xFF); + // * ``` + // * + // * @param other The right operand constant. + // * @return A new {@code Expr} representing the bitwise OR operation. + // */ + // bitOr(other: any): BitOr; + // + // /** + // * Creates an expression that applies a bitwise XOR operation between this expression and another expression. + // * + // * ```typescript + // * // Calculate the bitwise XOR of 'field1' and 'field2'. + // * Field.of("field1").bitXor(Field.of("field2")); + // * ``` + // * + // * @param other The right operand expression. + // * @return A new {@code Expr} representing the bitwise XOR operation. + // */ + // bitXor(other: Expr): BitXor; + // + // /** + // * Creates an expression that applies a bitwise XOR operation between this expression and a constant value. + // * + // * ```typescript + // * // Calculate the bitwise XOR of 'field1' and 0xFF. + // * Field.of("field1").bitXor(0xFF); + // * ``` + // * + // * @param other The right operand constant. + // * @return A new {@code Expr} representing the bitwise XOR operation. + // */ + // bitXor(other: any): BitXor; + // + // /** + // * Creates an expression that applies a bitwise NOT operation to this expression. + // * + // * ```typescript + // * // Calculate the bitwise NOT of 'field1'. + // * Field.of("field1").bitNot(); + // * ``` + // * + // * @return A new {@code Expr} representing the bitwise NOT operation. + // */ + // bitNot(): BitNot; + // + // /** + // * Creates an expression that applies a bitwise left shift operation between this expression and another expression. + // * + // * ```typescript + // * // Calculate the bitwise left shift of 'field1' by 'field2' bits. + // * Field.of("field1").bitLeftShift(Field.of("field2")); + // * ``` + // * + // * @param other The right operand expression representing the number of bits to shift. + // * @return A new {@code Expr} representing the bitwise left shift operation. + // */ + // bitLeftShift(other: Expr): BitLeftShift; + // + // /** + // * Creates an expression that applies a bitwise left shift operation between this expression and a constant value. + // * + // * ```typescript + // * // Calculate the bitwise left shift of 'field1' by 2 bits. + // * Field.of("field1").bitLeftShift(2); + // * ``` + // * + // * @param other The right operand constant representing the number of bits to shift. + // * @return A new {@code Expr} representing the bitwise left shift operation. + // */ + // bitLeftShift(other: number): BitLeftShift; + // + // /** + // * Creates an expression that applies a bitwise right shift operation between this expression and another expression. + // * + // * ```typescript + // * // Calculate the bitwise right shift of 'field1' by 'field2' bits. + // * Field.of("field1").bitRightShift(Field.of("field2")); + // * ``` + // * + // * @param other The right operand expression representing the number of bits to shift. + // * @return A new {@code Expr} representing the bitwise right shift operation. + // */ + // bitRightShift(other: Expr): BitRightShift; + // + // /** + // * Creates an expression that applies a bitwise right shift operation between this expression and a constant value. + // * + // * ```typescript + // * // Calculate the bitwise right shift of 'field1' by 2 bits. + // * Field.of("field1").bitRightShift(2); + // * ``` + // * + // * @param other The right operand constant representing the number of bits to shift. + // * @return A new {@code Expr} representing the bitwise right shift operation. + // */ + // bitRightShift(other: number): BitRightShift; /** * Creates an expression that checks if this expression is equal to another expression. @@ -4860,35 +4860,35 @@ declare namespace FirebaseFirestore { */ export class Mod extends Function {} - /** - * @beta - */ - export class BitAnd extends Function {} - - /** - * @beta - */ - export class BitOr extends Function {} - - /** - * @beta - */ - export class BitXor extends Function {} - - /** - * @beta - */ - export class BitNot extends Function {} - - /** - * @beta - */ - export class BitLeftShift extends Function {} - - /** - * @beta - */ - export class BitRightShift extends Function {} + // /** + // * @beta + // */ + // export class BitAnd extends Function {} + // + // /** + // * @beta + // */ + // export class BitOr extends Function {} + // + // /** + // * @beta + // */ + // export class BitXor extends Function {} + // + // /** + // * @beta + // */ + // export class BitNot extends Function {} + // + // /** + // * @beta + // */ + // export class BitLeftShift extends Function {} + // + // /** + // * @beta + // */ + // export class BitRightShift extends Function {} /** * @beta @@ -5529,355 +5529,355 @@ declare namespace FirebaseFirestore { */ export function mod(left: string, right: any): Mod; - /** - * @beta - * - * Creates an expression that applies a bitwise AND operation between two expressions. - * - * ```typescript - * // Calculate the bitwise AND of 'field1' and 'field2'. - * bitAnd(Field.of("field1"), Field.of("field2")); - * ``` - * - * @param left The left operand expression. - * @param right The right operand expression. - * @return A new {@code Expr} representing the bitwise AND operation. - */ - export function bitAnd(left: Expr, right: Expr): BitAnd; - - /** - * @beta - * - * Creates an expression that applies a bitwise AND operation between an expression and a constant. - * - * ```typescript - * // Calculate the bitwise AND of 'field1' and 0xFF. - * bitAnd(Field.of("field1"), 0xFF); - * ``` - * - * @param left The left operand expression. - * @param right The right operand constant. - * @return A new {@code Expr} representing the bitwise AND operation. - */ - export function bitAnd(left: Expr, right: any): BitAnd; - - /** - * @beta - * - * Creates an expression that applies a bitwise AND operation between a field and an expression. - * - * ```typescript - * // Calculate the bitwise AND of 'field1' and 'field2'. - * bitAnd("field1", Field.of("field2")); - * ``` - * - * @param left The left operand field name. - * @param right The right operand expression. - * @return A new {@code Expr} representing the bitwise AND operation. - */ - export function bitAnd(left: string, right: Expr): BitAnd; - - /** - * @beta - * - * Creates an expression that applies a bitwise AND operation between a field and a constant. - * - * ```typescript - * // Calculate the bitwise AND of 'field1' and 0xFF. - * bitAnd("field1", 0xFF); - * ``` - * - * @param left The left operand field name. - * @param right The right operand constant. - * @return A new {@code Expr} representing the bitwise AND operation. - */ - export function bitAnd(left: string, right: any): BitAnd; - - /** - * @beta - * - * Creates an expression that applies a bitwise OR operation between two expressions. - * - * ```typescript - * // Calculate the bitwise OR of 'field1' and 'field2'. - * bitOr(Field.of("field1"), Field.of("field2")); - * ``` - * - * @param left The left operand expression. - * @param right The right operand expression. - * @return A new {@code Expr} representing the bitwise OR operation. - */ - export function bitOr(left: Expr, right: Expr): BitOr; - - /** - * @beta - * - * Creates an expression that applies a bitwise OR operation between an expression and a constant. - * - * ```typescript - * // Calculate the bitwise OR of 'field1' and 0xFF. - * bitOr(Field.of("field1"), 0xFF); - * ``` - * - * @param left The left operand expression. - * @param right The right operand constant. - * @return A new {@code Expr} representing the bitwise OR operation. - */ - export function bitOr(left: Expr, right: any): BitOr; - - /** - * @beta - * - * Creates an expression that applies a bitwise OR operation between a field and an expression. - * - * ```typescript - * // Calculate the bitwise OR of 'field1' and 'field2'. - * bitOr("field1", Field.of("field2")); - * ``` - * - * @param left The left operand field name. - * @param right The right operand expression. - * @return A new {@code Expr} representing the bitwise OR operation. - */ - export function bitOr(left: string, right: Expr): BitOr; - - /** - * @beta - * - * Creates an expression that applies a bitwise OR operation between a field and a constant. - * - * ```typescript - * // Calculate the bitwise OR of 'field1' and 0xFF. - * bitOr("field1", 0xFF); - * ``` - * - * @param left The left operand field name. - * @param right The right operand constant. - * @return A new {@code Expr} representing the bitwise OR operation. - */ - export function bitOr(left: string, right: any): BitOr; - - /** - * @beta - * - * Creates an expression that applies a bitwise XOR operation between two expressions. - * - * ```typescript - * // Calculate the bitwise XOR of 'field1' and 'field2'. - * bitXor(Field.of("field1"), Field.of("field2")); - * ``` - * - * @param left The left operand expression. - * @param right The right operand expression. - * @return A new {@code Expr} representing the bitwise XOR operation. - */ - export function bitXor(left: Expr, right: Expr): BitXor; - - /** - * @beta - * - * Creates an expression that applies a bitwise XOR operation between an expression and a constant. - * - * ```typescript - * // Calculate the bitwise XOR of 'field1' and 0xFF. - * bitXor(Field.of("field1"), 0xFF); - * ``` - * - * @param left The left operand expression. - * @param right The right operand constant. - * @return A new {@code Expr} representing the bitwise XOR operation. - */ - export function bitXor(left: Expr, right: any): BitXor; - - /** - * @beta - * - * Creates an expression that applies a bitwise XOR operation between a field and an expression. - * - * ```typescript - * // Calculate the bitwise XOR of 'field1' and 'field2'. - * bitXor("field1", Field.of("field2")); - * ``` - * - * @param left The left operand field name. - * @param right The right operand expression. - * @return A new {@code Expr} representing the bitwise XOR operation. - */ - export function bitXor(left: string, right: Expr): BitXor; - - /** - * @beta - * - * Creates an expression that applies a bitwise XOR operation between a field and a constant. - * - * ```typescript - * // Calculate the bitwise XOR of 'field1' and 0xFF. - * bitXor("field1", 0xFF); - * ``` - * - * @param left The left operand field name. - * @param right The right operand constant. - * @return A new {@code Expr} representing the bitwise XOR operation. - */ - export function bitXor(left: string, right: any): BitXor; - - /** - * @beta - * - * Creates an expression that applies a bitwise NOT operation to an expression. - * - * ```typescript - * // Calculate the bitwise NOT of 'field1'. - * bitNot(Field.of("field1")); - * ``` - * - * @param operand The operand expression. - * @return A new {@code Expr} representing the bitwise NOT operation. - */ - export function bitNot(operand: Expr): BitNot; - - /** - * @beta - * - * Creates an expression that applies a bitwise NOT operation to a field. - * - * ```typescript - * // Calculate the bitwise NOT of 'field1'. - * bitNot("field1"); - * ``` - * - * @param operand The operand field name. - * @return A new {@code Expr} representing the bitwise NOT operation. - */ - export function bitNot(operand: string): BitNot; - - /** - * @beta - * - * Creates an expression that applies a bitwise left shift operation between two expressions. - * - * ```typescript - * // Calculate the bitwise left shift of 'field1' by 'field2' bits. - * bitLeftShift(Field.of("field1"), Field.of("field2")); - * ``` - * - * @param left The left operand expression. - * @param right The right operand expression representing the number of bits to shift. - * @return A new {@code Expr} representing the bitwise left shift operation. - */ - export function bitLeftShift(left: Expr, right: Expr): BitLeftShift; - - /** - * @beta - * - * Creates an expression that applies a bitwise left shift operation between an expression and a constant. - * - * ```typescript - * // Calculate the bitwise left shift of 'field1' by 2 bits. - * bitLeftShift(Field.of("field1"), 2); - * ``` - * - * @param left The left operand expression. - * @param right The right operand constant representing the number of bits to shift. - * @return A new {@code Expr} representing the bitwise left shift operation. - */ - export function bitLeftShift(left: Expr, right: any): BitLeftShift; - - /** - * @beta - * - * Creates an expression that applies a bitwise left shift operation between a field and an expression. - * - * ```typescript - * // Calculate the bitwise left shift of 'field1' by 'field2' bits. - * bitLeftShift("field1", Field.of("field2")); - * ``` - * - * @param left The left operand field name. - * @param right The right operand expression representing the number of bits to shift. - * @return A new {@code Expr} representing the bitwise left shift operation. - */ - export function bitLeftShift(left: string, right: Expr): BitLeftShift; - - /** - * @beta - * - * Creates an expression that applies a bitwise left shift operation between a field and a constant. - * - * ```typescript - * // Calculate the bitwise left shift of 'field1' by 2 bits. - * bitLeftShift("field1", 2); - * ``` - * - * @param left The left operand field name. - * @param right The right operand constant representing the number of bits to shift. - * @return A new {@code Expr} representing the bitwise left shift operation. - */ - export function bitLeftShift(left: string, right: any): BitLeftShift; - - /** - * @beta - * - * Creates an expression that applies a bitwise right shift operation between two expressions. - * - * ```typescript - * // Calculate the bitwise right shift of 'field1' by 'field2' bits. - * bitRightShift(Field.of("field1"), Field.of("field2")); - * ``` - * - * @param left The left operand expression. - * @param right The right operand expression representing the number of bits to shift. - * @return A new {@code Expr} representing the bitwise right shift operation. - */ - export function bitRightShift(left: Expr, right: Expr): BitRightShift; - - /** - * @beta - * - * Creates an expression that applies a bitwise right shift operation between an expression and a constant. - * - * ```typescript - * // Calculate the bitwise right shift of 'field1' by 2 bits. - * bitRightShift(Field.of("field1"), 2); - * ``` - * - * @param left The left operand expression. - * @param right The right operand constant representing the number of bits to shift. - * @return A new {@code Expr} representing the bitwise right shift operation. - */ - export function bitRightShift(left: Expr, right: any): BitRightShift; - - /** - * @beta - * - * Creates an expression that applies a bitwise right shift operation between a field and an expression. - * - * ```typescript - * // Calculate the bitwise right shift of 'field1' by 'field2' bits. - * bitRightShift("field1", Field.of("field2")); - * ``` - * - * @param left The left operand field name. - * @param right The right operand expression representing the number of bits to shift. - * @return A new {@code Expr} representing the bitwise right shift operation. - */ - export function bitRightShift(left: string, right: Expr): BitRightShift; - - /** - * @beta - * - * Creates an expression that applies a bitwise right shift operation between a field and a constant. - * - * ```typescript - * // Calculate the bitwise right shift of 'field1' by 2 bits. - * bitRightShift("field1", 2); - * ``` - * - * @param left The left operand field name. - * @param right The right operand constant representing the number of bits to shift. - * @return A new {@code Expr} representing the bitwise right shift operation. - */ - export function bitRightShift(left: string, right: any): BitRightShift; + // /** + // * @beta + // * + // * Creates an expression that applies a bitwise AND operation between two expressions. + // * + // * ```typescript + // * // Calculate the bitwise AND of 'field1' and 'field2'. + // * bitAnd(Field.of("field1"), Field.of("field2")); + // * ``` + // * + // * @param left The left operand expression. + // * @param right The right operand expression. + // * @return A new {@code Expr} representing the bitwise AND operation. + // */ + // export function bitAnd(left: Expr, right: Expr): BitAnd; + // + // /** + // * @beta + // * + // * Creates an expression that applies a bitwise AND operation between an expression and a constant. + // * + // * ```typescript + // * // Calculate the bitwise AND of 'field1' and 0xFF. + // * bitAnd(Field.of("field1"), 0xFF); + // * ``` + // * + // * @param left The left operand expression. + // * @param right The right operand constant. + // * @return A new {@code Expr} representing the bitwise AND operation. + // */ + // export function bitAnd(left: Expr, right: any): BitAnd; + // + // /** + // * @beta + // * + // * Creates an expression that applies a bitwise AND operation between a field and an expression. + // * + // * ```typescript + // * // Calculate the bitwise AND of 'field1' and 'field2'. + // * bitAnd("field1", Field.of("field2")); + // * ``` + // * + // * @param left The left operand field name. + // * @param right The right operand expression. + // * @return A new {@code Expr} representing the bitwise AND operation. + // */ + // export function bitAnd(left: string, right: Expr): BitAnd; + // + // /** + // * @beta + // * + // * Creates an expression that applies a bitwise AND operation between a field and a constant. + // * + // * ```typescript + // * // Calculate the bitwise AND of 'field1' and 0xFF. + // * bitAnd("field1", 0xFF); + // * ``` + // * + // * @param left The left operand field name. + // * @param right The right operand constant. + // * @return A new {@code Expr} representing the bitwise AND operation. + // */ + // export function bitAnd(left: string, right: any): BitAnd; + // + // /** + // * @beta + // * + // * Creates an expression that applies a bitwise OR operation between two expressions. + // * + // * ```typescript + // * // Calculate the bitwise OR of 'field1' and 'field2'. + // * bitOr(Field.of("field1"), Field.of("field2")); + // * ``` + // * + // * @param left The left operand expression. + // * @param right The right operand expression. + // * @return A new {@code Expr} representing the bitwise OR operation. + // */ + // export function bitOr(left: Expr, right: Expr): BitOr; + // + // /** + // * @beta + // * + // * Creates an expression that applies a bitwise OR operation between an expression and a constant. + // * + // * ```typescript + // * // Calculate the bitwise OR of 'field1' and 0xFF. + // * bitOr(Field.of("field1"), 0xFF); + // * ``` + // * + // * @param left The left operand expression. + // * @param right The right operand constant. + // * @return A new {@code Expr} representing the bitwise OR operation. + // */ + // export function bitOr(left: Expr, right: any): BitOr; + // + // /** + // * @beta + // * + // * Creates an expression that applies a bitwise OR operation between a field and an expression. + // * + // * ```typescript + // * // Calculate the bitwise OR of 'field1' and 'field2'. + // * bitOr("field1", Field.of("field2")); + // * ``` + // * + // * @param left The left operand field name. + // * @param right The right operand expression. + // * @return A new {@code Expr} representing the bitwise OR operation. + // */ + // export function bitOr(left: string, right: Expr): BitOr; + // + // /** + // * @beta + // * + // * Creates an expression that applies a bitwise OR operation between a field and a constant. + // * + // * ```typescript + // * // Calculate the bitwise OR of 'field1' and 0xFF. + // * bitOr("field1", 0xFF); + // * ``` + // * + // * @param left The left operand field name. + // * @param right The right operand constant. + // * @return A new {@code Expr} representing the bitwise OR operation. + // */ + // export function bitOr(left: string, right: any): BitOr; + // + // /** + // * @beta + // * + // * Creates an expression that applies a bitwise XOR operation between two expressions. + // * + // * ```typescript + // * // Calculate the bitwise XOR of 'field1' and 'field2'. + // * bitXor(Field.of("field1"), Field.of("field2")); + // * ``` + // * + // * @param left The left operand expression. + // * @param right The right operand expression. + // * @return A new {@code Expr} representing the bitwise XOR operation. + // */ + // export function bitXor(left: Expr, right: Expr): BitXor; + // + // /** + // * @beta + // * + // * Creates an expression that applies a bitwise XOR operation between an expression and a constant. + // * + // * ```typescript + // * // Calculate the bitwise XOR of 'field1' and 0xFF. + // * bitXor(Field.of("field1"), 0xFF); + // * ``` + // * + // * @param left The left operand expression. + // * @param right The right operand constant. + // * @return A new {@code Expr} representing the bitwise XOR operation. + // */ + // export function bitXor(left: Expr, right: any): BitXor; + // + // /** + // * @beta + // * + // * Creates an expression that applies a bitwise XOR operation between a field and an expression. + // * + // * ```typescript + // * // Calculate the bitwise XOR of 'field1' and 'field2'. + // * bitXor("field1", Field.of("field2")); + // * ``` + // * + // * @param left The left operand field name. + // * @param right The right operand expression. + // * @return A new {@code Expr} representing the bitwise XOR operation. + // */ + // export function bitXor(left: string, right: Expr): BitXor; + // + // /** + // * @beta + // * + // * Creates an expression that applies a bitwise XOR operation between a field and a constant. + // * + // * ```typescript + // * // Calculate the bitwise XOR of 'field1' and 0xFF. + // * bitXor("field1", 0xFF); + // * ``` + // * + // * @param left The left operand field name. + // * @param right The right operand constant. + // * @return A new {@code Expr} representing the bitwise XOR operation. + // */ + // export function bitXor(left: string, right: any): BitXor; + // + // /** + // * @beta + // * + // * Creates an expression that applies a bitwise NOT operation to an expression. + // * + // * ```typescript + // * // Calculate the bitwise NOT of 'field1'. + // * bitNot(Field.of("field1")); + // * ``` + // * + // * @param operand The operand expression. + // * @return A new {@code Expr} representing the bitwise NOT operation. + // */ + // export function bitNot(operand: Expr): BitNot; + // + // /** + // * @beta + // * + // * Creates an expression that applies a bitwise NOT operation to a field. + // * + // * ```typescript + // * // Calculate the bitwise NOT of 'field1'. + // * bitNot("field1"); + // * ``` + // * + // * @param operand The operand field name. + // * @return A new {@code Expr} representing the bitwise NOT operation. + // */ + // export function bitNot(operand: string): BitNot; + // + // /** + // * @beta + // * + // * Creates an expression that applies a bitwise left shift operation between two expressions. + // * + // * ```typescript + // * // Calculate the bitwise left shift of 'field1' by 'field2' bits. + // * bitLeftShift(Field.of("field1"), Field.of("field2")); + // * ``` + // * + // * @param left The left operand expression. + // * @param right The right operand expression representing the number of bits to shift. + // * @return A new {@code Expr} representing the bitwise left shift operation. + // */ + // export function bitLeftShift(left: Expr, right: Expr): BitLeftShift; + // + // /** + // * @beta + // * + // * Creates an expression that applies a bitwise left shift operation between an expression and a constant. + // * + // * ```typescript + // * // Calculate the bitwise left shift of 'field1' by 2 bits. + // * bitLeftShift(Field.of("field1"), 2); + // * ``` + // * + // * @param left The left operand expression. + // * @param right The right operand constant representing the number of bits to shift. + // * @return A new {@code Expr} representing the bitwise left shift operation. + // */ + // export function bitLeftShift(left: Expr, right: any): BitLeftShift; + // + // /** + // * @beta + // * + // * Creates an expression that applies a bitwise left shift operation between a field and an expression. + // * + // * ```typescript + // * // Calculate the bitwise left shift of 'field1' by 'field2' bits. + // * bitLeftShift("field1", Field.of("field2")); + // * ``` + // * + // * @param left The left operand field name. + // * @param right The right operand expression representing the number of bits to shift. + // * @return A new {@code Expr} representing the bitwise left shift operation. + // */ + // export function bitLeftShift(left: string, right: Expr): BitLeftShift; + // + // /** + // * @beta + // * + // * Creates an expression that applies a bitwise left shift operation between a field and a constant. + // * + // * ```typescript + // * // Calculate the bitwise left shift of 'field1' by 2 bits. + // * bitLeftShift("field1", 2); + // * ``` + // * + // * @param left The left operand field name. + // * @param right The right operand constant representing the number of bits to shift. + // * @return A new {@code Expr} representing the bitwise left shift operation. + // */ + // export function bitLeftShift(left: string, right: any): BitLeftShift; + // + // /** + // * @beta + // * + // * Creates an expression that applies a bitwise right shift operation between two expressions. + // * + // * ```typescript + // * // Calculate the bitwise right shift of 'field1' by 'field2' bits. + // * bitRightShift(Field.of("field1"), Field.of("field2")); + // * ``` + // * + // * @param left The left operand expression. + // * @param right The right operand expression representing the number of bits to shift. + // * @return A new {@code Expr} representing the bitwise right shift operation. + // */ + // export function bitRightShift(left: Expr, right: Expr): BitRightShift; + // + // /** + // * @beta + // * + // * Creates an expression that applies a bitwise right shift operation between an expression and a constant. + // * + // * ```typescript + // * // Calculate the bitwise right shift of 'field1' by 2 bits. + // * bitRightShift(Field.of("field1"), 2); + // * ``` + // * + // * @param left The left operand expression. + // * @param right The right operand constant representing the number of bits to shift. + // * @return A new {@code Expr} representing the bitwise right shift operation. + // */ + // export function bitRightShift(left: Expr, right: any): BitRightShift; + // + // /** + // * @beta + // * + // * Creates an expression that applies a bitwise right shift operation between a field and an expression. + // * + // * ```typescript + // * // Calculate the bitwise right shift of 'field1' by 'field2' bits. + // * bitRightShift("field1", Field.of("field2")); + // * ``` + // * + // * @param left The left operand field name. + // * @param right The right operand expression representing the number of bits to shift. + // * @return A new {@code Expr} representing the bitwise right shift operation. + // */ + // export function bitRightShift(left: string, right: Expr): BitRightShift; + // + // /** + // * @beta + // * + // * Creates an expression that applies a bitwise right shift operation between a field and a constant. + // * + // * ```typescript + // * // Calculate the bitwise right shift of 'field1' by 2 bits. + // * bitRightShift("field1", 2); + // * ``` + // * + // * @param left The left operand field name. + // * @param right The right operand constant representing the number of bits to shift. + // * @return A new {@code Expr} representing the bitwise right shift operation. + // */ + // export function bitRightShift(left: string, right: any): BitRightShift; /** * @beta From 773bcd76659c9715a7d39276efe50848eaf572af Mon Sep 17 00:00:00 2001 From: Wu-Hui Date: Wed, 25 Sep 2024 18:29:53 -0400 Subject: [PATCH 20/60] more syncs --- dev/src/expression.ts | 118 ++++++++++++++++++++++++++++++++++++++++++ dev/src/index.ts | 1 + types/firestore.d.ts | 97 ++++++++++++++++++++++++++++++++++ 3 files changed, 216 insertions(+) diff --git a/dev/src/expression.ts b/dev/src/expression.ts index 22a75b438..12675bc50 100644 --- a/dev/src/expression.ts +++ b/dev/src/expression.ts @@ -947,6 +947,38 @@ export abstract class Expr implements firestore.Expr { return new RegexMatch(this, stringOrExpr as Expr); } + /** + * Creates an expression that checks if a string contains a specified substring. + * + * ```typescript + * // Check if the 'description' field contains "example". + * Field.of("description").strContains("example"); + * ``` + * + * @param substring The substring to search for. + * @return A new `Expr` representing the 'contains' comparison. + */ + strContains(substring: string): StrContains; + + /** + * Creates an expression that checks if a string contains the string represented by another expression. + * + * ```typescript + * // Check if the 'description' field contains the value of the 'keyword' field. + * Field.of("description").strContains(Field.of("keyword")); + * ``` + * + * @param expr The expression representing the substring to search for. + * @return A new `Expr` representing the 'contains' comparison. + */ + strContains(expr: Expr): StrContains; + strContains(stringOrExpr: string | Expr): StrContains { + if (typeof stringOrExpr === 'string') { + return new StrContains(this, Constant.of(stringOrExpr)); + } + return new StrContains(this, stringOrExpr as Expr); + } + /** * Creates an expression that checks if a string starts with a given prefix. * @@ -2598,6 +2630,19 @@ class RegexMatch extends Function implements FilterCondition { filterable = true as const; } +/** + * @beta + */ +class StrContains extends Function implements FilterCondition { + constructor( + private expr: Expr, + private substring: Expr + ) { + super('str_contains', [expr, substring]); + } + filterable = true as const; +} + /** * @beta */ @@ -5270,6 +5315,79 @@ export function regexMatch( return new RegexMatch(leftExpr, patternExpr); } +/** + * @beta + * + * Creates an expression that checks if a string field contains a specified substring. + * + * ```typescript + * // Check if the 'description' field contains "example". + * strContains("description", "example"); + * ``` + * + * @param left The name of the field containing the string. + * @param substring The substring to search for. + * @return A new {@code Expr} representing the 'contains' comparison. + */ +export function strContains(left: string, substring: string): StrContains; + +/** + * @beta + * + * Creates an expression that checks if a string field contains a substring specified by an expression. + * + * ```typescript + * // Check if the 'description' field contains the value of the 'keyword' field. + * strContains("description", Field.of("keyword")); + * ``` + * + * @param left The name of the field containing the string. + * @param substring The expression representing the substring to search for. + * @return A new {@code Expr} representing the 'contains' comparison. + */ +export function strContains(left: string, substring: Expr): StrContains; + +/** + * @beta + * + * Creates an expression that checks if a string expression contains a specified substring. + * + * ```typescript + * // Check if the 'description' field contains "example". + * strContains(Field.of("description"), "example"); + * ``` + * + * @param left The expression representing the string to perform the comparison on. + * @param substring The substring to search for. + * @return A new {@code Expr} representing the 'contains' comparison. + */ +export function strContains(left: Expr, substring: string): StrContains; + +/** + * @beta + * + * Creates an expression that checks if a string expression contains a substring specified by another expression. + * + * ```typescript + * // Check if the 'description' field contains the value of the 'keyword' field. + * strContains(Field.of("description"), Field.of("keyword")); + * ``` + * + * @param left The expression representing the string to perform the comparison on. + * @param substring The expression representing the substring to search for. + * @return A new {@code Expr} representing the 'contains' comparison. + */ +export function strContains(left: Expr, substring: Expr): StrContains; +export function strContains( + left: Expr | string, + substring: Expr | string +): StrContains { + const leftExpr = left instanceof Expr ? left : Field.of(left); + const substringExpr = + substring instanceof Expr ? substring : Constant.of(substring); + return new StrContains(leftExpr, substringExpr); +} + /** * @beta * diff --git a/dev/src/index.ts b/dev/src/index.ts index 54af20aba..0e0274bc6 100644 --- a/dev/src/index.ts +++ b/dev/src/index.ts @@ -169,6 +169,7 @@ export { like, regexContains, regexMatch, + strContains, startsWith, endsWith, toLower, diff --git a/types/firestore.d.ts b/types/firestore.d.ts index 16941d12b..a92a3b31f 100644 --- a/types/firestore.d.ts +++ b/types/firestore.d.ts @@ -3969,6 +3969,32 @@ declare namespace FirebaseFirestore { */ regexMatch(pattern: Expr): RegexMatch; + /** + * Creates an expression that checks if this string expression contains a specified substring. + * + * ```typescript + * // Check if the 'description' field contains "example". + * Field.of("description").strContains("example"); + * ``` + * + * @param substring The substring to search for. + * @return A new {@code Expr} representing the 'contains' comparison. + */ + strContains(substring: string): StrContains; + + /** + * Creates an expression that checks if this string expression contains the string represented by another expression. + * + * ```typescript + * // Check if the 'description' field contains the value of the 'keyword' field. + * Field.of("description").strContains(Field.of("keyword")); + * ``` + * + * @param expr The expression representing the substring to search for. + * @return A new {@code Expr} representing the 'contains' comparison. + */ + strContains(expr: Expr): StrContains; + /** * Creates an expression that checks if a string starts with a given prefix. * @@ -5055,6 +5081,13 @@ declare namespace FirebaseFirestore { filterable: true; } + /** + * @beta + */ + export class StrContains extends Function implements FilterCondition { + filterable: true; + } + /** * @beta */ @@ -7448,6 +7481,70 @@ declare namespace FirebaseFirestore { */ export function regexMatch(left: Expr, pattern: Expr): RegexMatch; + /** + * @beta + * + * Creates an expression that checks if a string field contains a specified substring. + * + * ```typescript + * // Check if the 'description' field contains "example". + * strContains("description", "example"); + * ``` + * + * @param left The name of the field containing the string. + * @param substring The substring to search for. + * @return A new {@code Expr} representing the 'contains' comparison. + */ + export function strContains(left: string, substring: string): StrContains; + + /** + * @beta + * + * Creates an expression that checks if a string field contains a substring specified by an expression. + * + * ```typescript + * // Check if the 'description' field contains the value of the 'keyword' field. + * strContains("description", Field.of("keyword")); + * ``` + * + * @param left The name of the field containing the string. + * @param substring The expression representing the substring to search for. + * @return A new {@code Expr} representing the 'contains' comparison. + */ + export function strContains(left: string, substring: Expr): StrContains; + + /** + * @beta + * + * Creates an expression that checks if a string expression contains a specified substring. + * + * ```typescript + * // Check if the 'description' field contains "example". + * strContains(Field.of("description"), "example"); + * ``` + * + * @param left The expression representing the string to perform the comparison on. + * @param substring The substring to search for. + * @return A new {@code Expr} representing the 'contains' comparison. + */ + export function strContains(left: Expr, substring: string): StrContains; + + /** + * @beta + * + * Creates an expression that checks if a string expression contains a substring specified by another expression. + * + * ```typescript + * // Check if the 'description' field contains the value of the 'keyword' field. + * strContains(Field.of("description"), Field.of("keyword")); + * ``` + * + * @param left The expression representing the string to perform the comparison on. + * @param substring The expression representing the substring to search for. + * @return A new {@code Expr} representing the 'contains' comparison. + */ + export function strContains(left: Expr, substring: Expr): StrContains; + /** * @beta * From c22a2dbe1459576baf42a897bc068daf95a5fc4a Mon Sep 17 00:00:00 2001 From: Wu-Hui Date: Tue, 1 Oct 2024 10:30:03 -0400 Subject: [PATCH 21/60] Fix rest connection by correct url endpoint. --- dev/protos/google/firestore/v1/firestore.proto | 2 +- dev/protos/v1.json | 4 ++-- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/dev/protos/google/firestore/v1/firestore.proto b/dev/protos/google/firestore/v1/firestore.proto index f8718bb67..8479e7779 100644 --- a/dev/protos/google/firestore/v1/firestore.proto +++ b/dev/protos/google/firestore/v1/firestore.proto @@ -145,7 +145,7 @@ service Firestore { rpc ExecutePipeline(ExecutePipelineRequest) returns (stream ExecutePipelineResponse) { option (google.api.http) = { - post: "/v1beta1/{database=projects/*/databases/*}:executePipeline" + post: "/v1/{database=projects/*/databases/*}/documents:executePipeline" body: "*" }; } diff --git a/dev/protos/v1.json b/dev/protos/v1.json index 7d3336323..35e6ad599 100644 --- a/dev/protos/v1.json +++ b/dev/protos/v1.json @@ -1965,13 +1965,13 @@ "responseType": "ExecutePipelineResponse", "responseStream": true, "options": { - "(google.api.http).post": "/v1beta1/{database=projects/*/databases/*}:executePipeline", + "(google.api.http).post": "/v1/{database=projects/*/databases/*}/documents:executePipeline", "(google.api.http).body": "*" }, "parsedOptions": [ { "(google.api.http)": { - "post": "/v1beta1/{database=projects/*/databases/*}:executePipeline", + "post": "/v1/{database=projects/*/databases/*}/documents:executePipeline", "body": "*" } } From a0fb269b430e62f0709c23a3754f66bec9c7b732 Mon Sep 17 00:00:00 2001 From: Wu-Hui Date: Tue, 1 Oct 2024 10:41:02 -0400 Subject: [PATCH 22/60] documentation fix --- dev/src/pipeline.ts | 4 ++-- types/firestore.d.ts | 4 ++-- 2 files changed, 4 insertions(+), 4 deletions(-) diff --git a/dev/src/pipeline.ts b/dev/src/pipeline.ts index aec5790b6..30b8332f3 100644 --- a/dev/src/pipeline.ts +++ b/dev/src/pipeline.ts @@ -479,8 +479,8 @@ export class Pipeline * // with the same rating * firestore.pipeline().collection("books") * .sort( - * Ordering.of(Field.of("rating")).descending(), - * Ordering.of(Field.of("title")) // Ascending order is the default + * Field.of("rating").descending(), + * Field.of("title").ascending() * ); * ``` * diff --git a/types/firestore.d.ts b/types/firestore.d.ts index a92a3b31f..a615218eb 100644 --- a/types/firestore.d.ts +++ b/types/firestore.d.ts @@ -9167,8 +9167,8 @@ declare namespace FirebaseFirestore { * // with the same rating * firestore.pipeline().collection("books") * .sort( - * Ordering.of(Field.of("rating")).descending(), - * Ordering.of(Field.of("title")) // Ascending order is the default + * Field.of("rating").descending(), + * Field.of("title").ascending() * ); * ``` * From b43de5708e0754f23b0493331f61bdabf6b4759b Mon Sep 17 00:00:00 2001 From: Wu-Hui Date: Tue, 1 Oct 2024 12:09:59 -0400 Subject: [PATCH 23/60] Fix system tests build error by not using `instanceof firestore.Expr` in expression.ts --- dev/src/expression.ts | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/dev/src/expression.ts b/dev/src/expression.ts index 12675bc50..877c5a0fa 100644 --- a/dev/src/expression.ts +++ b/dev/src/expression.ts @@ -1336,7 +1336,7 @@ export abstract class Expr implements firestore.Expr { */ logicalMax(other: any): firestore.LogicalMax; logicalMax(other: any): firestore.LogicalMax { - if (other instanceof firestore.Expr) { + if (other instanceof Expr) { return new LogicalMax(this, other as Expr); } return new LogicalMax(this, Constant.of(other)); @@ -1368,7 +1368,7 @@ export abstract class Expr implements firestore.Expr { */ logicalMin(other: any): firestore.LogicalMin; logicalMin(other: any): firestore.LogicalMin { - if (other instanceof firestore.Expr) { + if (other instanceof Expr) { return new LogicalMin(this, other as Expr); } return new LogicalMin(this, Constant.of(other)); @@ -1427,7 +1427,7 @@ export abstract class Expr implements firestore.Expr { cosineDistance( other: firestore.Expr | firestore.VectorValue | number[] ): CosineDistance { - if (other instanceof firestore.Expr) { + if (other instanceof Expr) { return new CosineDistance(this, other as Expr); } else { return new CosineDistance( @@ -1478,7 +1478,7 @@ export abstract class Expr implements firestore.Expr { dotProduct( other: firestore.Expr | firestore.VectorValue | number[] ): DotProduct { - if (other instanceof firestore.Expr) { + if (other instanceof Expr) { return new DotProduct(this, other as Expr); } else { return new DotProduct( @@ -1529,7 +1529,7 @@ export abstract class Expr implements firestore.Expr { euclideanDistance( other: firestore.Expr | firestore.VectorValue | number[] ): EuclideanDistance { - if (other instanceof firestore.Expr) { + if (other instanceof Expr) { return new EuclideanDistance(this, other as Expr); } else { return new EuclideanDistance( From 1d9c585e2482bb53c5926ed7a7f54d22707d8fb8 Mon Sep 17 00:00:00 2001 From: Wu-Hui Date: Wed, 2 Oct 2024 18:22:23 -0400 Subject: [PATCH 24/60] remove __path__ --- dev/src/expression.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/dev/src/expression.ts b/dev/src/expression.ts index 877c5a0fa..5b5f5678d 100644 --- a/dev/src/expression.ts +++ b/dev/src/expression.ts @@ -1886,7 +1886,7 @@ export class Field extends Expr implements Selectable { return new Field(FieldPath.fromArgument(pipelineOrName)); } else if (pipelineOrName instanceof FieldPath) { if (FieldPath.documentId().isEqual(pipelineOrName)) { - return new Field(new FieldPath('__path__')); + return new Field(FieldPath.documentId()); } return new Field(pipelineOrName); } else { From d9194b71e22694caa5817956df48cfb875686656 Mon Sep 17 00:00:00 2001 From: Wu-Hui Date: Thu, 3 Oct 2024 10:11:52 -0400 Subject: [PATCH 25/60] add reference test --- dev/system-test/pipeline.ts | 9 +++++++++ 1 file changed, 9 insertions(+) diff --git a/dev/system-test/pipeline.ts b/dev/system-test/pipeline.ts index 4bc990b92..96934dd5f 100644 --- a/dev/system-test/pipeline.ts +++ b/dev/system-test/pipeline.ts @@ -564,6 +564,15 @@ describe.only('Pipeline class', () => { expect(results.length).to.equal(5); }); + it('testQueryByDocumentReference', async () => { + const results = await randomCol + .pipeline() + .where(eq(Field.of(FieldPath.documentId()), randomCol.doc('book1'))) + .select('title') + .execute(); + expectResults(results, {title: "The Hitchhiker's Guide to the Galaxy"}); + }); + it('testArithmeticOperations', async () => { const results = await randomCol .pipeline() From 091ddf0f4d1b39381a1d96ccb39b540af0e659a4 Mon Sep 17 00:00:00 2001 From: Wu-Hui Date: Fri, 4 Oct 2024 10:35:38 -0400 Subject: [PATCH 26/60] added transaction support. --- dev/src/pipeline-util.ts | 20 +++++++++++--------- dev/src/pipeline.ts | 25 +++++++++++++++++++++++-- dev/src/reference/types.ts | 7 +++++++ dev/src/transaction.ts | 27 +++++++++++++++++++++++++++ dev/system-test/pipeline.ts | 25 +++++++++++++++++++++++++ types/firestore.d.ts | 4 ++++ 6 files changed, 97 insertions(+), 11 deletions(-) diff --git a/dev/src/pipeline-util.ts b/dev/src/pipeline-util.ts index 59ebbcfad..db24449af 100644 --- a/dev/src/pipeline-util.ts +++ b/dev/src/pipeline-util.ts @@ -40,7 +40,11 @@ import {CompositeFilterInternal} from './reference/composite-filter-internal'; import {NOOP_MESSAGE} from './reference/constants'; import {FieldFilterInternal} from './reference/field-filter-internal'; import {FilterInternal} from './reference/filter-internal'; -import {PipelineStreamElement, QueryResponse} from './reference/types'; +import { + PipelineResponse, + PipelineStreamElement, + QueryResponse, +} from './reference/types'; import {Serializer} from './serializer'; import { Deferred, @@ -50,7 +54,6 @@ import { requestTag, wrapError, } from './util'; -import {invalidArgumentMessage} from './validate'; import api = protos.google.firestore.v1; /** @@ -73,15 +76,13 @@ export class ExecutionUtil { pipeline: Pipeline, transactionOrReadTime?: Uint8Array | Timestamp | api.ITransactionOptions, explainOptions?: firestore.ExplainOptions - ): Promise> | undefined> { + ): Promise> { // Capture the error stack to preserve stack tracing across async calls. const stack = Error().stack!; return new Promise((resolve, reject) => { - const results: Array> = []; - const output: Omit, 'result'> & { - executionTime?: Timestamp; - } = {}; + const result: Array> = []; + const output: PipelineResponse = {}; this._stream(pipeline, transactionOrReadTime, explainOptions) .on('error', err => { @@ -99,12 +100,13 @@ export class ExecutionUtil { output.explainMetrics = element.explainMetrics; } if (element.result) { - results.push(element.result); + result.push(element.result); } } }) .on('end', () => { - resolve(results); + output.result = result; + resolve(output); }); }); } diff --git a/dev/src/pipeline.ts b/dev/src/pipeline.ts index 30b8332f3..c28918213 100644 --- a/dev/src/pipeline.ts +++ b/dev/src/pipeline.ts @@ -31,6 +31,7 @@ import Firestore, {FieldPath, QueryDocumentSnapshot, Timestamp} from './index'; import {validateFieldPath} from './path'; import {ExecutionUtil} from './pipeline-util'; import {DocumentReference} from './reference/document-reference'; +import {PipelineResponse} from './reference/types'; import {Serializer} from './serializer'; import { AddFields, @@ -632,12 +633,21 @@ export class Pipeline * @return A Promise representing the asynchronous pipeline execution. */ execute(): Promise>> { + return this._execute().then(response => response.result || []); + } + + _execute( + transactionOrReadTime?: Uint8Array | Timestamp | api.ITransactionOptions, + explainOptions?: FirebaseFirestore.ExplainOptions + ): Promise> { const util = new ExecutionUtil( this.db, this.db._serializer!, this.converter ); - return util._getResponse(this).then(result => result!); + return util + ._getResponse(this, transactionOrReadTime, explainOptions) + .then(result => result!); } /** @@ -673,10 +683,21 @@ export class Pipeline stage._toProto(this.db._serializer!) ); const structuredPipeline: IStructuredPipeline = {pipeline: {stages}}; - return { + const executePipelineRequest: api.IExecutePipelineRequest = { database: this.db.formattedName, structuredPipeline, }; + + if (transactionOrReadTime instanceof Uint8Array) { + executePipelineRequest.transaction = transactionOrReadTime; + } else if (transactionOrReadTime instanceof Timestamp) { + executePipelineRequest.readTime = + transactionOrReadTime.toProto().timestampValue; + } else if (transactionOrReadTime) { + executePipelineRequest.newTransaction = transactionOrReadTime; + } + + return executePipelineRequest; } } diff --git a/dev/src/reference/types.ts b/dev/src/reference/types.ts index 036994ff6..d282b507f 100644 --- a/dev/src/reference/types.ts +++ b/dev/src/reference/types.ts @@ -70,6 +70,13 @@ export interface PipelineStreamElement< result?: PipelineResult; } +export interface PipelineResponse { + transaction?: Uint8Array; + executionTime?: Timestamp; + explainMetrics?: ExplainMetrics; + result?: Array>; +} + /** * onSnapshot() callback that receives a QuerySnapshot. * diff --git a/dev/src/transaction.ts b/dev/src/transaction.ts index f29fccbe5..c11bcc78b 100644 --- a/dev/src/transaction.ts +++ b/dev/src/transaction.ts @@ -22,6 +22,7 @@ import * as proto from '../protos/firestore_v1_proto_api'; import {ExponentialBackoff} from './backoff'; import {DocumentSnapshot} from './document'; import {DEFAULT_MAX_TRANSACTION_ATTEMPTS, Firestore, WriteBatch} from './index'; +import {Pipeline, PipelineResult} from './pipeline'; import {Timestamp} from './timestamp'; import {logger} from './logger'; import {FieldPath, validateFieldPath} from './path'; @@ -260,6 +261,20 @@ export class Transaction implements firestore.Transaction { ); } + execute( + pipeline: firestore.Pipeline + ): Promise>> { + if (this._writeBatch && !this._writeBatch.isEmpty) { + throw new Error(READ_AFTER_WRITE_ERROR_MSG); + } + + if (pipeline instanceof Pipeline) { + return this.withLazyStartedTransaction(pipeline, this.executePipelineFn); + } + + throw new Error('Value for argument "pipeline" must be a Pipeline'); + } + /** * Create the document referred to by the provided * [DocumentReference]{@link DocumentReference}. The operation will @@ -737,6 +752,18 @@ export class Transaction implements firestore.Transaction { }> { return query._get(opts); } + + private async executePipelineFn( + pipeline: Pipeline, + opts: Uint8Array | api.ITransactionOptions | Timestamp + ): Promise<{ + transaction?: Uint8Array; + result: Array>; + }> { + const {transaction, result, explainMetrics, executionTime} = + await pipeline._execute(opts); + return {transaction, result: result || []}; + } } /** diff --git a/dev/system-test/pipeline.ts b/dev/system-test/pipeline.ts index 96934dd5f..e2ef43c0d 100644 --- a/dev/system-test/pipeline.ts +++ b/dev/system-test/pipeline.ts @@ -784,4 +784,29 @@ describe.only('Pipeline class', () => { myTitle: 'Crime and Punishment', }); }); + + it('run pipeline as part of a transaction', async () => { + const pipeline = randomCol + .pipeline() + .where(eq('awards.hugo', true)) + .select('title', 'awards.hugo'); + + await firestore.runTransaction(async transaction => { + const results = await transaction.execute(pipeline); + expectResults( + results, + {title: "The Hitchhiker's Guide to the Galaxy", 'awards.hugo': true}, + {title: 'Dune', 'awards.hugo': true} + ); + + transaction.update(randomCol.doc('book1'), {foo: 'bar'}); + }); + + const result = await randomCol + .pipeline() + .where(eq('foo', 'bar')) + .select('title', Field.of(FieldPath.documentId())) + .execute(); + expectResults(result, {title: "The Hitchhiker's Guide to the Galaxy"}); + }); }); diff --git a/types/firestore.d.ts b/types/firestore.d.ts index a615218eb..dd0b804b4 100644 --- a/types/firestore.d.ts +++ b/types/firestore.d.ts @@ -808,6 +808,10 @@ declare namespace FirebaseFirestore { > ): Promise>>; + execute( + pipeline: Pipeline + ): Promise>>; + /** * Create the document referred to by the provided `DocumentReference`. * The operation will fail the transaction if a document exists at the From 14b67ddddc8f312b9377ca9e2c53b8540d9d3ad7 Mon Sep 17 00:00:00 2001 From: Wu-Hui Date: Fri, 4 Oct 2024 11:24:09 -0400 Subject: [PATCH 27/60] Add comments --- dev/src/transaction.ts | 34 ++++++++++++++++++++++++++++++++++ types/firestore.d.ts | 36 +++++++++++++++++++++++++++++++++++- 2 files changed, 69 insertions(+), 1 deletion(-) diff --git a/dev/src/transaction.ts b/dev/src/transaction.ts index c11bcc78b..abc101a13 100644 --- a/dev/src/transaction.ts +++ b/dev/src/transaction.ts @@ -261,6 +261,40 @@ export class Transaction implements firestore.Transaction { ); } + /** + * @beta + * + * Executes this pipeline and returns a Promise to represent the asynchronous operation. + * + *

    The returned Promise can be used to track the progress of the pipeline execution + * and retrieve the results (or handle any errors) asynchronously. + * + *

    The pipeline results are returned as a list of {@link PipelineResult} objects. Each {@link + * PipelineResult} typically represents a single key/value map that has passed through all the + * stages of the pipeline, however this might differ depending on the stages involved in the + * pipeline. For example: + * + *

      + *
    • If there are no stages or only transformation stages, each {@link PipelineResult} + * represents a single document.
    • + *
    • If there is an aggregation, only a single {@link PipelineResult} is returned, + * representing the aggregated results over the entire dataset .
    • + *
    • If there is an aggregation stage with grouping, each {@link PipelineResult} represents a + * distinct group and its associated aggregated values.
    • + *
    + * + *

    Example: + * + * ```typescript + * const futureResults = await transaction + * .execute( + * firestore.pipeline().collection("books") + * .where(gt(Field.of("rating"), 4.5)) + * .select("title", "author", "rating")); + * ``` + * + * @return A Promise representing the asynchronous pipeline execution. + */ execute( pipeline: firestore.Pipeline ): Promise>> { diff --git a/types/firestore.d.ts b/types/firestore.d.ts index dd0b804b4..991302a3a 100644 --- a/types/firestore.d.ts +++ b/types/firestore.d.ts @@ -808,8 +808,42 @@ declare namespace FirebaseFirestore { > ): Promise>>; + /** + * @beta + * + * Executes this pipeline and returns a Promise to represent the asynchronous operation. + * + *

    The returned Promise can be used to track the progress of the pipeline execution + * and retrieve the results (or handle any errors) asynchronously. + * + *

    The pipeline results are returned as a list of {@link PipelineResult} objects. Each {@link + * PipelineResult} typically represents a single key/value map that has passed through all the + * stages of the pipeline, however this might differ depending on the stages involved in the + * pipeline. For example: + * + *

      + *
    • If there are no stages or only transformation stages, each {@link PipelineResult} + * represents a single document.
    • + *
    • If there is an aggregation, only a single {@link PipelineResult} is returned, + * representing the aggregated results over the entire dataset .
    • + *
    • If there is an aggregation stage with grouping, each {@link PipelineResult} represents a + * distinct group and its associated aggregated values.
    • + *
    + * + *

    Example: + * + * ```typescript + * const futureResults = await transaction + * .execute( + * firestore.pipeline().collection("books") + * .where(gt(Field.of("rating"), 4.5)) + * .select("title", "author", "rating")); + * ``` + * + * @return A Promise representing the asynchronous pipeline execution. + */ execute( - pipeline: Pipeline + pipeline: Pipeline ): Promise>>; /** From 0c04b48ec5043bb1251f561bf9b0101935e5e082 Mon Sep 17 00:00:00 2001 From: Wu-Hui Date: Thu, 24 Oct 2024 14:46:27 -0400 Subject: [PATCH 28/60] add remove_fields support --- dev/src/pipeline.ts | 30 ++++++++++++++++++++ dev/src/stage.ts | 16 +++++++++++ dev/system-test/pipeline.ts | 55 +++++++++++++++++++++++++++++++++++++ 3 files changed, 101 insertions(+) diff --git a/dev/src/pipeline.ts b/dev/src/pipeline.ts index c28918213..4fc32d402 100644 --- a/dev/src/pipeline.ts +++ b/dev/src/pipeline.ts @@ -50,6 +50,7 @@ import { Sort, Stage, Distinct, + RemoveFields, } from './stage'; import {ApiMapValue, defaultPipelineConverter} from './types'; import * as protos from '../protos/firestore_v1_proto_api'; @@ -165,6 +166,35 @@ export class Pipeline return new Pipeline(this.db, copy, this.converter); } + /** + * Remove fields from outputs of previous stages. + * + * Example: + * + * ```typescript + * firestore.pipeline().collection("books") + * // removes field 'rating' and 'cost' from the previous stage outputs. + * .removeFields( + * Field.of("rating"), + * "cost" + * ); + * ``` + * + * @param fields The fields to remove. + * @return A new Pipeline object with this stage appended to the stage list. + */ + removeFields( + ...fields: (firestore.Field | string)[] + ): Pipeline { + const copy = this.stages.map(s => s); + copy.push( + new RemoveFields( + fields.map(f => (typeof f === 'string' ? Field.of(f) : (f as Field))) + ) + ); + return new Pipeline(this.db, copy, this.converter); + } + /** * Selects or creates a set of fields from the outputs of previous stages. * diff --git a/dev/src/stage.ts b/dev/src/stage.ts index c498e20ae..5be9be513 100644 --- a/dev/src/stage.ts +++ b/dev/src/stage.ts @@ -51,6 +51,22 @@ export class AddFields implements Stage { } } +/** + * @beta + */ +export class RemoveFields implements Stage { + name = 'remove_fields'; + + constructor(private fields: Field[]) {} + + _toProto(serializer: Serializer): api.Pipeline.IStage { + return { + name: this.name, + args: this.fields.map(f => serializer.encodeValue(f)!), + }; + } +} + /** * @beta */ diff --git a/dev/system-test/pipeline.ts b/dev/system-test/pipeline.ts index e2ef43c0d..82d380b11 100644 --- a/dev/system-test/pipeline.ts +++ b/dev/system-test/pipeline.ts @@ -324,6 +324,61 @@ describe.only('Pipeline class', () => { }); }); + it('can add and remove fields', async () => { + const results = await firestore + .pipeline() + .collection(randomCol.path) + .addFields( + strConcat(Field.of('author'), '_', Field.of('title')).as( + 'author_title' + ), + strConcat(Field.of('title'), '_', Field.of('author')).as('title_author') + ) + .removeFields( + 'title_author', + 'tags', + 'awards', + 'rating', + 'title', + 'published', + 'genre', + 'nestedField' + ) + .sort(Field.of('author_title').ascending()) + .execute(); + expectResults( + results, + { + author_title: "Douglas Adams_The Hitchhiker's Guide to the Galaxy", + author: 'Douglas Adams', + }, + { + author_title: 'F. Scott Fitzgerald_The Great Gatsby', + author: 'F. Scott Fitzgerald', + }, + {author_title: 'Frank Herbert_Dune', author: 'Frank Herbert'}, + { + author_title: 'Fyodor Dostoevsky_Crime and Punishment', + author: 'Fyodor Dostoevsky', + }, + { + author_title: 'Gabriel García Márquez_One Hundred Years of Solitude', + author: 'Gabriel García Márquez', + }, + {author_title: 'George Orwell_1984', author: 'George Orwell'}, + {author_title: 'Harper Lee_To Kill a Mockingbird', author: 'Harper Lee'}, + { + author_title: 'J.R.R. Tolkien_The Lord of the Rings', + author: 'J.R.R. Tolkien', + }, + {author_title: 'Jane Austen_Pride and Prejudice', author: 'Jane Austen'}, + { + author_title: "Margaret Atwood_The Handmaid's Tale", + author: 'Margaret Atwood', + } + ); + }); + it('can select fields', async () => { const results = await firestore .pipeline() From 91bd76e6528772d8b80ec7b793a1313e73d0f8a8 Mon Sep 17 00:00:00 2001 From: Wu-Hui Date: Thu, 24 Oct 2024 15:09:04 -0400 Subject: [PATCH 29/60] add d.ts change for removeFields --- types/firestore.d.ts | 26 ++++++++++++++++++++++++++ 1 file changed, 26 insertions(+) diff --git a/types/firestore.d.ts b/types/firestore.d.ts index 991302a3a..fce440cd2 100644 --- a/types/firestore.d.ts +++ b/types/firestore.d.ts @@ -8770,6 +8770,13 @@ declare namespace FirebaseFirestore { name: string; } + /** + * @beta + */ + export class RemoveFields implements Stage { + name: string; + } + /** * @beta */ @@ -8982,6 +8989,25 @@ declare namespace FirebaseFirestore { */ addFields(...fields: Selectable[]): Pipeline; + /** + * Remove fields from outputs of previous stages. + * + * Example: + * + * ```typescript + * firestore.pipeline().collection("books") + * // removes field 'rating' and 'cost' from the previous stage outputs. + * .removeFields( + * Field.of("rating"), + * "cost" + * ); + * ``` + * + * @param fields The fields to remove. + * @return A new Pipeline object with this stage appended to the stage list. + */ + removeFields(...fields: (Field | string)[]): Pipeline; + /** * Selects or creates a set of fields from the outputs of previous stages. * From cb9d69224ba6c472b68e47a2f521e7f73e1b0a49 Mon Sep 17 00:00:00 2001 From: Mark Duckworth <1124037+MarkDuckworth@users.noreply.github.com> Date: Mon, 18 Nov 2024 09:49:20 -0700 Subject: [PATCH 30/60] fix build --- CODE_OF_CONDUCT.md | 2 +- dev/conformance/runner.ts | 2 ++ 2 files changed, 3 insertions(+), 1 deletion(-) diff --git a/CODE_OF_CONDUCT.md b/CODE_OF_CONDUCT.md index 2add2547a..a044123a3 100644 --- a/CODE_OF_CONDUCT.md +++ b/CODE_OF_CONDUCT.md @@ -91,4 +91,4 @@ harassment or threats to anyone's safety, we may take action without notice. This Code of Conduct is adapted from the Contributor Covenant, version 1.4, available at -https://www.contributor-covenant.org/version/1/4/code-of-conduct.html \ No newline at end of file +https://www.contributor-covenant.org/version/1/4/code-of-conduct.html diff --git a/dev/conformance/runner.ts b/dev/conformance/runner.ts index 3ade3a1f5..82a117809 100644 --- a/dev/conformance/runner.ts +++ b/dev/conformance/runner.ts @@ -530,6 +530,7 @@ function normalizeTimestamp(obj: {[key: string]: {}}) { if (fieldNames.includes(key) && typeof obj[key] === 'string') { obj[key] = convertTimestamp(obj[key] as string); } else if (typeof obj[key] === 'object') { + // @ts-ignore normalizeTimestamp(obj[key]); } } @@ -576,6 +577,7 @@ function normalizeInt32Value(obj: {[key: string]: {}}, parent = '') { value: obj[key], }; } else if (typeof obj[key] === 'object') { + // @ts-ignore normalizeInt32Value(obj[key], key); } } From 5db7307d7ab1d09f845603fb269ca3b09647b1d4 Mon Sep 17 00:00:00 2001 From: Mark Duckworth <1124037+MarkDuckworth@users.noreply.github.com> Date: Wed, 20 Nov 2024 12:36:10 -0700 Subject: [PATCH 31/60] Rename cond, *minimum, *maximum, eqAny, and notEqAny. New tests. Implement NotEqAny. --- dev/src/expression.ts | 297 +++++++++++++++++++++--------------- dev/src/index.ts | 14 +- dev/src/pipeline-util.ts | 4 +- dev/system-test/pipeline.ts | 154 ++++++++++++++++--- types/firestore.d.ts | 156 +++++++++---------- 5 files changed, 393 insertions(+), 232 deletions(-) diff --git a/dev/src/expression.ts b/dev/src/expression.ts index 5b5f5678d..399433096 100644 --- a/dev/src/expression.ts +++ b/dev/src/expression.ts @@ -779,13 +779,13 @@ export abstract class Expr implements firestore.Expr { * * ```typescript * // Check if the 'category' field is either "Electronics" or value of field 'primaryType' - * Field.of("category").in("Electronics", Field.of("primaryType")); + * Field.of("category").eqAny("Electronics", Field.of("primaryType")); * ``` * * @param others The values or expressions to check against. - * @return A new `Expr` representing the 'IN' comparison. + * @return A new `Expr` representing the 'EqAny' comparison. */ - in(...others: firestore.Expr[]): In; + eqAny(...others: firestore.Expr[]): EqAny; /** * Creates an expression that checks if this expression is equal to any of the provided values or @@ -793,18 +793,52 @@ export abstract class Expr implements firestore.Expr { * * ```typescript * // Check if the 'category' field is either "Electronics" or value of field 'primaryType' - * Field.of("category").in("Electronics", Field.of("primaryType")); + * Field.of("category").eqAny("Electronics", Field.of("primaryType")); * ``` * * @param others The values or expressions to check against. - * @return A new `Expr` representing the 'IN' comparison. + * @return A new `Expr` representing the 'EqAny' comparison. */ - in(...others: any[]): In; - in(...others: any[]): In { + eqAny(...others: any[]): EqAny; + eqAny(...others: any[]): EqAny { const exprOthers = others.map(other => other instanceof Expr ? other : Constant.of(other) ); - return new In(this, exprOthers); + return new EqAny(this, exprOthers); + } + + /** + * Creates an expression that checks if this expression is not equal to any of the provided values or + * expressions. + * + * ```typescript + * // Check if the 'status' field is neither "pending" nor the value of 'rejectedStatus' + * Field.of("status").notEqAny("pending", Field.of("rejectedStatus")); + * ``` + * + * @param others The values or expressions to check against. + * @return A new `Expr` representing the 'NotEqAny' comparison. + */ + notEqAny(...others: firestore.Expr[]): NotEqAny; + + /** + * Creates an expression that checks if this expression is not equal to any of the provided values or + * expressions. + * + * ```typescript + * // Check if the 'status' field is neither "pending" nor the value of 'rejectedStatus' + * Field.of("status").notEqAny("pending", Field.of("rejectedStatus")); + * ``` + * + * @param others The values or expressions to check against. + * @return A new `Expr` representing the 'NotEqAny' comparison. + */ + notEqAny(...others: any[]): NotEqAny; + notEqAny(...others: any[]): NotEqAny { + const exprOthers = others.map(other => + other instanceof Expr ? other : Constant.of(other) + ); + return new NotEqAny(this, exprOthers); } /** @@ -1287,13 +1321,13 @@ export abstract class Expr implements firestore.Expr { * * ```typescript * // Find the lowest price of all products - * Field.of("price").min().as("lowestPrice"); + * Field.of("price").minimum().as("lowestPrice"); * ``` * - * @return A new `Accumulator` representing the 'min' aggregation. + * @return A new `Accumulator` representing the 'minimum' aggregation. */ - min(): Min { - return new Min(this, false); + minimum(): Minimum { + return new Minimum(this, false); } /** @@ -1301,13 +1335,13 @@ export abstract class Expr implements firestore.Expr { * * ```typescript * // Find the highest score in a leaderboard - * Field.of("score").max().as("highestScore"); + * Field.of("score").maximum().as("highestScore"); * ``` * - * @return A new `Accumulator` representing the 'max' aggregation. + * @return A new `Accumulator` representing the 'maximum' aggregation. */ - max(): Max { - return new Max(this, false); + maximum(): Maximum { + return new Maximum(this, false); } /** @@ -1315,31 +1349,31 @@ export abstract class Expr implements firestore.Expr { * * ```typescript * // Returns the larger value between the 'timestamp' field and the current timestamp. - * Field.of("timestamp").logicalMax(Function.currentTimestamp()); + * Field.of("timestamp").logicalMaximum(Function.currentTimestamp()); * ``` * * @param other The expression to compare with. - * @return A new {@code Expr} representing the logical max operation. + * @return A new {@code Expr} representing the logical maximum operation. */ - logicalMax(other: firestore.Expr): firestore.LogicalMax; + logicalMaximum(other: firestore.Expr): firestore.LogicalMaximum; /** * Creates an expression that returns the larger value between this expression and a constant value, based on Firestore's value type ordering. * * ```typescript * // Returns the larger value between the 'value' field and 10. - * Field.of("value").logicalMax(10); + * Field.of("value").logicalMaximum(10); * ``` * * @param other The constant value to compare with. - * @return A new {@code Expr} representing the logical max operation. + * @return A new {@code Expr} representing the logical maximum operation. */ - logicalMax(other: any): firestore.LogicalMax; - logicalMax(other: any): firestore.LogicalMax { + logicalMaximum(other: any): firestore.LogicalMaximum; + logicalMaximum(other: any): firestore.LogicalMaximum { if (other instanceof Expr) { - return new LogicalMax(this, other as Expr); + return new LogicalMaximum(this, other as Expr); } - return new LogicalMax(this, Constant.of(other)); + return new LogicalMaximum(this, Constant.of(other)); } /** @@ -1347,31 +1381,31 @@ export abstract class Expr implements firestore.Expr { * * ```typescript * // Returns the smaller value between the 'timestamp' field and the current timestamp. - * Field.of("timestamp").logicalMin(Function.currentTimestamp()); + * Field.of("timestamp").logicalMinimum(Function.currentTimestamp()); * ``` * * @param other The expression to compare with. - * @return A new {@code Expr} representing the logical min operation. + * @return A new {@code Expr} representing the logical minimum operation. */ - logicalMin(other: firestore.Expr): firestore.LogicalMin; + logicalMinimum(other: firestore.Expr): firestore.LogicalMinimum; /** * Creates an expression that returns the smaller value between this expression and a constant value, based on Firestore's value type ordering. * * ```typescript * // Returns the smaller value between the 'value' field and 10. - * Field.of("value").logicalMin(10); + * Field.of("value").logicalMinimum(10); * ``` * * @param other The constant value to compare with. - * @return A new {@code Expr} representing the logical min operation. + * @return A new {@code Expr} representing the logical minimum operation. */ - logicalMin(other: any): firestore.LogicalMin; - logicalMin(other: any): firestore.LogicalMin { + logicalMinimum(other: any): firestore.LogicalMinimum; + logicalMinimum(other: any): firestore.LogicalMinimum { if (other instanceof Expr) { - return new LogicalMin(this, other as Expr); + return new LogicalMinimum(this, other as Expr); } - return new LogicalMin(this, Constant.of(other)); + return new LogicalMinimum(this, Constant.of(other)); } /** @@ -2429,12 +2463,25 @@ class ArrayElement extends Function { /** * @beta */ -class In extends Function implements FilterCondition { +class EqAny extends Function implements FilterCondition { constructor( private left: Expr, private others: Expr[] ) { - super('in', [left, new ListOfExprs(others)]); + super('eq_any', [left, new ListOfExprs(others)]); + } + filterable = true as const; +} + +/** + * @beta + */ +class NotEqAny extends Function implements FilterCondition { + constructor( + private left: Expr, + private others: Expr[] + ) { + super('not_eq_any', [left, new ListOfExprs(others)]); } filterable = true as const; } @@ -2503,13 +2550,13 @@ class Xor extends Function implements FilterCondition { /** * @beta */ -class If extends Function implements FilterCondition { +class Cond extends Function implements FilterCondition { constructor( private condition: FilterExpr, private thenExpr: Expr, private elseExpr: Expr ) { - super('if', [condition, thenExpr, elseExpr]); + super('cond', [condition, thenExpr, elseExpr]); } filterable = true as const; } @@ -2517,24 +2564,24 @@ class If extends Function implements FilterCondition { /** * @beta */ -class LogicalMax extends Function { +class LogicalMaximum extends Function { constructor( private left: Expr, private right: Expr ) { - super('logical_max', [left, right]); + super('logical_maximum', [left, right]); } } /** * @beta */ -class LogicalMin extends Function { +class LogicalMinimum extends Function { constructor( private left: Expr, private right: Expr ) { - super('logical_min', [left, right]); + super('logical_minimum', [left, right]); } } @@ -2759,26 +2806,26 @@ class Avg extends Function implements Accumulator { /** * @beta */ -class Min extends Function implements Accumulator { +class Minimum extends Function implements Accumulator { accumulator = true as const; constructor( private value: Expr, private distinct: boolean ) { - super('min', [value]); + super('minimum', [value]); } } /** * @beta */ -class Max extends Function implements Accumulator { +class Maximum extends Function implements Accumulator { accumulator = true as const; constructor( private value: Expr, private distinct: boolean ) { - super('max', [value]); + super('maximum', [value]); } } @@ -4394,14 +4441,14 @@ export function arrayLength(array: Expr): ArrayLength { * * ```typescript * // Check if the 'category' field is either "Electronics" or value of field 'primaryType' - * inAny(Field.of("category"), [Constant.of("Electronics"), Field.of("primaryType")]); + * eqAny(Field.of("category"), [Constant.of("Electronics"), Field.of("primaryType")]); * ``` * * @param element The expression to compare. * @param others The values to check against. - * @return A new {@code Expr} representing the 'IN' comparison. + * @return A new {@code Expr} representing the 'eqAny' comparison. */ -export function inAny(element: Expr, others: Expr[]): In; +export function eqAny(element: Expr, others: Expr[]): EqAny; /** * @beta @@ -4411,14 +4458,14 @@ export function inAny(element: Expr, others: Expr[]): In; * * ```typescript * // Check if the 'category' field is either "Electronics" or value of field 'primaryType' - * inAny(Field.of("category"), ["Electronics", Field.of("primaryType")]); + * eqAny(Field.of("category"), ["Electronics", Field.of("primaryType")]); * ``` * * @param element The expression to compare. * @param others The values to check against. - * @return A new {@code Expr} representing the 'IN' comparison. + * @return A new {@code Expr} representing the 'eqAny' comparison. */ -export function inAny(element: Expr, others: any[]): In; +export function eqAny(element: Expr, others: any[]): EqAny; /** * @beta @@ -4428,14 +4475,14 @@ export function inAny(element: Expr, others: any[]): In; * * ```typescript * // Check if the 'category' field is either "Electronics" or value of field 'primaryType' - * inAny("category", [Constant.of("Electronics"), Field.of("primaryType")]); + * eqAny("category", [Constant.of("Electronics"), Field.of("primaryType")]); * ``` * * @param element The field to compare. * @param others The values to check against. - * @return A new {@code Expr} representing the 'IN' comparison. + * @return A new {@code Expr} representing the 'eqAny' comparison. */ -export function inAny(element: string, others: Expr[]): In; +export function eqAny(element: string, others: Expr[]): EqAny; /** * @beta @@ -4445,20 +4492,20 @@ export function inAny(element: string, others: Expr[]): In; * * ```typescript * // Check if the 'category' field is either "Electronics" or value of field 'primaryType' - * inAny("category", ["Electronics", Field.of("primaryType")]); + * eqAny("category", ["Electronics", Field.of("primaryType")]); * ``` * * @param element The field to compare. * @param others The values to check against. - * @return A new {@code Expr} representing the 'IN' comparison. + * @return A new {@code Expr} representing the 'eqAny' comparison. */ -export function inAny(element: string, others: any[]): In; -export function inAny(element: Expr | string, others: any[]): In { +export function eqAny(element: string, others: any[]): EqAny; +export function eqAny(element: Expr | string, others: any[]): EqAny { const elementExpr = element instanceof Expr ? element : Field.of(element); const exprOthers = others.map(other => other instanceof Expr ? other : Constant.of(other) ); - return new In(elementExpr, exprOthers); + return new EqAny(elementExpr, exprOthers); } /** @@ -4469,14 +4516,14 @@ export function inAny(element: Expr | string, others: any[]): In { * * ```typescript * // Check if the 'status' field is neither "pending" nor the value of 'rejectedStatus' - * notInAny(Field.of("status"), [Constant.of("pending"), Field.of("rejectedStatus")]); + * notEqAny(Field.of("status"), [Constant.of("pending"), Field.of("rejectedStatus")]); * ``` * * @param element The expression to compare. * @param others The values to check against. - * @return A new {@code Expr} representing the 'NOT IN' comparison. + * @return A new {@code Expr} representing the 'NotEqAny' comparison. */ -export function notInAny(element: Expr, others: Expr[]): Not; +export function notEqAny(element: Expr, others: Expr[]): NotEqAny; /** * @beta @@ -4486,14 +4533,14 @@ export function notInAny(element: Expr, others: Expr[]): Not; * * ```typescript * // Check if the 'status' field is neither "pending" nor the value of 'rejectedStatus' - * notInAny(Field.of("status"), ["pending", Field.of("rejectedStatus")]); + * notEqAny(Field.of("status"), ["pending", Field.of("rejectedStatus")]); * ``` * * @param element The expression to compare. * @param others The values to check against. - * @return A new {@code Expr} representing the 'NOT IN' comparison. + * @return A new {@code Expr} representing the 'NotEqAny' comparison. */ -export function notInAny(element: Expr, others: any[]): Not; +export function notEqAny(element: Expr, others: any[]): NotEqAny; /** * @beta @@ -4503,14 +4550,14 @@ export function notInAny(element: Expr, others: any[]): Not; * * ```typescript * // Check if the 'status' field is neither "pending" nor the value of 'rejectedStatus' - * notInAny("status", [Constant.of("pending"), Field.of("rejectedStatus")]); + * notEqAny("status", ["pending", Field.of("rejectedStatus")]); * ``` * * @param element The field name to compare. * @param others The values to check against. - * @return A new {@code Expr} representing the 'NOT IN' comparison. + * @return A new {@code Expr} representing the 'NotEqAny' comparison. */ -export function notInAny(element: string, others: Expr[]): Not; +export function notEqAny(element: string, others: Expr[]): NotEqAny; /** * @beta @@ -4520,20 +4567,20 @@ export function notInAny(element: string, others: Expr[]): Not; * * ```typescript * // Check if the 'status' field is neither "pending" nor the value of 'rejectedStatus' - * notInAny("status", ["pending", Field.of("rejectedStatus")]); + * notEqAny("status", ["pending", Field.of("rejectedStatus")]); * ``` * * @param element The field name to compare. * @param others The values to check against. - * @return A new {@code Expr} representing the 'NOT IN' comparison. + * @return A new {@code Expr} representing the 'NotEqAny' comparison. */ -export function notInAny(element: string, others: any[]): Not; -export function notInAny(element: Expr | string, others: any[]): Not { +export function notEqAny(element: string, others: any[]): NotEqAny; +export function notEqAny(element: Expr | string, others: any[]): NotEqAny { const elementExpr = element instanceof Expr ? element : Field.of(element); const exprOthers = others.map(other => other instanceof Expr ? other : Constant.of(other) ); - return new Not(new In(elementExpr, exprOthers)); + return new NotEqAny(elementExpr, exprOthers); } /** @@ -4605,7 +4652,7 @@ export function xor(left: FilterExpr, ...right: FilterExpr[]): Xor { * * ```typescript * // If 'age' is greater than 18, return "Adult"; otherwise, return "Minor". - * ifFunction( + * cond( * gt("age", 18), Constant.of("Adult"), Constant.of("Minor")); * ``` * @@ -4614,12 +4661,12 @@ export function xor(left: FilterExpr, ...right: FilterExpr[]): Xor { * @param elseExpr The expression to evaluate if the condition is false. * @return A new {@code Expr} representing the conditional expression. */ -export function ifFunction( +export function cond( condition: FilterExpr, thenExpr: Expr, elseExpr: Expr -): If { - return new If(condition, thenExpr, elseExpr); +): Cond { + return new Cond(condition, thenExpr, elseExpr); } /** @@ -4646,14 +4693,14 @@ export function not(filter: FilterExpr): Not { * * ```typescript * // Returns the larger value between the 'field1' field and the 'field2' field. - * logicalMax(Field.of("field1"), Field.of("field2")); + * logicalMaximum(Field.of("field1"), Field.of("field2")); * ``` * * @param left The left operand expression. * @param right The right operand expression. - * @return A new {@code Expr} representing the logical max operation. + * @return A new {@code Expr} representing the logical maximum operation. */ -export function logicalMax(left: Expr, right: Expr): LogicalMax; +export function logicalMaximum(left: Expr, right: Expr): LogicalMaximum; /** * @beta @@ -4662,14 +4709,14 @@ export function logicalMax(left: Expr, right: Expr): LogicalMax; * * ```typescript * // Returns the larger value between the 'value' field and 10. - * logicalMax(Field.of("value"), 10); + * logicalMaximum(Field.of("value"), 10); * ``` * * @param left The left operand expression. * @param right The right operand constant. - * @return A new {@code Expr} representing the logical max operation. + * @return A new {@code Expr} representing the logical maximum operation. */ -export function logicalMax(left: Expr, right: any): LogicalMax; +export function logicalMaximum(left: Expr, right: any): LogicalMaximum; /** * @beta @@ -4678,14 +4725,14 @@ export function logicalMax(left: Expr, right: any): LogicalMax; * * ```typescript * // Returns the larger value between the 'field1' field and the 'field2' field. - * logicalMax("field1", Field.of('field2')); + * logicalMaximum("field1", Field.of('field2')); * ``` * * @param left The left operand field name. * @param right The right operand expression. - * @return A new {@code Expr} representing the logical max operation. + * @return A new {@code Expr} representing the logical maximum operation. */ -export function logicalMax(left: string, right: Expr): LogicalMax; +export function logicalMaximum(left: string, right: Expr): LogicalMaximum; /** * @beta @@ -4694,18 +4741,21 @@ export function logicalMax(left: string, right: Expr): LogicalMax; * * ```typescript * // Returns the larger value between the 'value' field and 10. - * logicalMax("value", 10); + * logicalMaximum("value", 10); * ``` * * @param left The left operand field name. * @param right The right operand constant. - * @return A new {@code Expr} representing the logical max operation. + * @return A new {@code Expr} representing the logical maximum operation. */ -export function logicalMax(left: string, right: any): LogicalMax; -export function logicalMax(left: Expr | string, right: Expr | any): LogicalMax { +export function logicalMaximum(left: string, right: any): LogicalMaximum; +export function logicalMaximum( + left: Expr | string, + right: Expr | any +): LogicalMaximum { const normalizedLeft = typeof left === 'string' ? Field.of(left) : left; const normalizedRight = right instanceof Expr ? right : Constant.of(right); - return new LogicalMax(normalizedLeft, normalizedRight); + return new LogicalMaximum(normalizedLeft, normalizedRight); } /** @@ -4715,14 +4765,14 @@ export function logicalMax(left: Expr | string, right: Expr | any): LogicalMax { * * ```typescript * // Returns the smaller value between the 'field1' field and the 'field2' field. - * logicalMin(Field.of("field1"), Field.of("field2")); + * logicalMinimum(Field.of("field1"), Field.of("field2")); * ``` * * @param left The left operand expression. * @param right The right operand expression. - * @return A new {@code Expr} representing the logical min operation. + * @return A new {@code Expr} representing the logical minimum operation. */ -export function logicalMin(left: Expr, right: Expr): LogicalMin; +export function logicalMinimum(left: Expr, right: Expr): LogicalMinimum; /** * @beta @@ -4731,14 +4781,14 @@ export function logicalMin(left: Expr, right: Expr): LogicalMin; * * ```typescript * // Returns the smaller value between the 'value' field and 10. - * logicalMin(Field.of("value"), 10); + * logicalMinimum(Field.of("value"), 10); * ``` * * @param left The left operand expression. * @param right The right operand constant. - * @return A new {@code Expr} representing the logical min operation. + * @return A new {@code Expr} representing the logical minimum operation. */ -export function logicalMin(left: Expr, right: any): LogicalMin; +export function logicalMinimum(left: Expr, right: any): LogicalMinimum; /** * @beta @@ -4747,14 +4797,14 @@ export function logicalMin(left: Expr, right: any): LogicalMin; * * ```typescript * // Returns the smaller value between the 'field1' field and the 'field2' field. - * logicalMin("field1", Field.of("field2")); + * logicalMinimum("field1", Field.of("field2")); * ``` * * @param left The left operand field name. * @param right The right operand expression. - * @return A new {@code Expr} representing the logical min operation. + * @return A new {@code Expr} representing the logical minimum operation. */ -export function logicalMin(left: string, right: Expr): LogicalMin; +export function logicalMinimum(left: string, right: Expr): LogicalMinimum; /** * @beta @@ -4763,18 +4813,21 @@ export function logicalMin(left: string, right: Expr): LogicalMin; * * ```typescript * // Returns the smaller value between the 'value' field and 10. - * logicalMin("value", 10); + * logicalMinimum("value", 10); * ``` * * @param left The left operand field name. * @param right The right operand constant. - * @return A new {@code Expr} representing the logical min operation. + * @return A new {@code Expr} representing the logical minimum operation. */ -export function logicalMin(left: string, right: any): LogicalMin; -export function logicalMin(left: Expr | string, right: Expr | any): LogicalMin { +export function logicalMinimum(left: string, right: any): LogicalMinimum; +export function logicalMinimum( + left: Expr | string, + right: Expr | any +): LogicalMinimum { const normalizedLeft = typeof left === 'string' ? Field.of(left) : left; const normalizedRight = right instanceof Expr ? right : Constant.of(right); - return new LogicalMin(normalizedLeft, normalizedRight); + return new LogicalMinimum(normalizedLeft, normalizedRight); } /** @@ -5840,13 +5893,13 @@ export function avg(value: Expr | string): Avg { * * ```typescript * // Find the lowest price of all products - * min(Field.of("price")).as("lowestPrice"); + * minimum(Field.of("price")).as("lowestPrice"); * ``` * * @param value The expression to find the minimum value of. - * @return A new {@code Accumulator} representing the 'min' aggregation. + * @return A new {@code Accumulator} representing the 'minimum' aggregation. */ -export function min(value: Expr): Min; +export function minimum(value: Expr): Minimum; /** * @beta @@ -5855,16 +5908,16 @@ export function min(value: Expr): Min; * * ```typescript * // Find the lowest price of all products - * min("price").as("lowestPrice"); + * minimum("price").as("lowestPrice"); * ``` * * @param value The name of the field to find the minimum value of. - * @return A new {@code Accumulator} representing the 'min' aggregation. + * @return A new {@code Accumulator} representing the 'minimum' aggregation. */ -export function min(value: string): Min; -export function min(value: Expr | string): Min { +export function minimum(value: string): Minimum; +export function minimum(value: Expr | string): Minimum { const exprValue = value instanceof Expr ? value : Field.of(value); - return new Min(exprValue, false); + return new Minimum(exprValue, false); } /** @@ -5875,13 +5928,13 @@ export function min(value: Expr | string): Min { * * ```typescript * // Find the highest score in a leaderboard - * max(Field.of("score")).as("highestScore"); + * maximum(Field.of("score")).as("highestScore"); * ``` * * @param value The expression to find the maximum value of. - * @return A new {@code Accumulator} representing the 'max' aggregation. + * @return A new {@code Accumulator} representing the 'maximum' aggregation. */ -export function max(value: Expr): Max; +export function maximum(value: Expr): Maximum; /** * @beta @@ -5890,16 +5943,16 @@ export function max(value: Expr): Max; * * ```typescript * // Find the highest score in a leaderboard - * max("score").as("highestScore"); + * maximum("score").as("highestScore"); * ``` * * @param value The name of the field to find the maximum value of. - * @return A new {@code Accumulator} representing the 'max' aggregation. + * @return A new {@code Accumulator} representing the 'maximum' aggregation. */ -export function max(value: string): Max; -export function max(value: Expr | string): Max { +export function maximum(value: string): Maximum; +export function maximum(value: Expr | string): Maximum { const exprValue = value instanceof Expr ? value : Field.of(value); - return new Max(exprValue, false); + return new Maximum(exprValue, false); } /** diff --git a/dev/src/index.ts b/dev/src/index.ts index 0e0274bc6..5b83d596c 100644 --- a/dev/src/index.ts +++ b/dev/src/index.ts @@ -156,12 +156,12 @@ export { arrayContainsAny, arrayContainsAll, arrayLength, - inAny, - notInAny, + eqAny, + notEqAny, and, or, xor, - ifFunction, + cond, not, exists, isNan, @@ -181,8 +181,8 @@ export { count, sum, avg, - min, - max, + minimum, + maximum, cosineDistance, dotProduct, euclideanDistance, @@ -203,8 +203,8 @@ export { unixMicrosToTimestamp, unixMillisToTimestamp, unixSecondsToTimestamp, - logicalMax, - logicalMin, + logicalMaximum, + logicalMinimum, vectorLength, byteLength, reverse, diff --git a/dev/src/pipeline-util.ts b/dev/src/pipeline-util.ts index db24449af..1bb77b482 100644 --- a/dev/src/pipeline-util.ts +++ b/dev/src/pipeline-util.ts @@ -434,7 +434,7 @@ export function toPipelineFilterCondition( const values = value?.arrayValue?.values?.map(val => Constant.of(val) ); - return and(field.exists(), field.in(...values!)); + return and(field.exists(), field.eqAny(...values!)); } case 'ARRAY_CONTAINS_ANY': { const values = value?.arrayValue?.values?.map(val => @@ -446,7 +446,7 @@ export function toPipelineFilterCondition( const values = value?.arrayValue?.values?.map(val => Constant.of(val) ); - return and(field.exists(), not(field.in(...values!))); + return and(field.exists(), field.notEqAny(...values!)); } } } diff --git a/dev/system-test/pipeline.ts b/dev/system-test/pipeline.ts index 82d380b11..317c4e839 100644 --- a/dev/system-test/pipeline.ts +++ b/dev/system-test/pipeline.ts @@ -13,25 +13,22 @@ // limitations under the License. import { - AggregateQuery, DocumentData, FirestorePipelineConverter, QuerySnapshot, - VectorValue, } from '@google-cloud/firestore'; import {expect} from 'chai'; -import {afterEach, beforeEach, describe, it} from 'mocha'; +import {afterEach, describe, it} from 'mocha'; import { CollectionReference, DocumentReference, - DocumentSnapshot, FieldPath, - FieldValue, - Filter, Firestore, + logicalMinimum, + logicalMaximum, Query, - QueryDocumentSnapshot, + cond, } from '../src'; import { add, @@ -60,6 +57,8 @@ import { Constant, mapGet, lte, + eqAny, + notEqAny, } from '../src/expression'; import {PipelineResult} from '../src/pipeline'; import {verifyInstance} from '../test/util/helpers'; @@ -258,7 +257,7 @@ describe.only('Pipeline class', () => { .aggregate( countAll().as('count'), avg('rating').as('avg_rating'), - Field.of('rating').max().as('max_rating') + Field.of('rating').maximum().as('max_rating') ) .execute(); expectResults(result, {count: 2, avg_rating: 4.4, max_rating: 4.6}); @@ -277,7 +276,8 @@ describe.only('Pipeline class', () => { ).to.be.rejected; }); - it('returns distinct values as expected', async () => { + // toLower not impelemented + it.skip('returns distinct values as expected', async () => { const results = await randomCol .pipeline() .where(lt('published', 1900)) @@ -295,26 +295,27 @@ describe.only('Pipeline class', () => { .pipeline() .where(lt(Field.of('published'), 1984)) .aggregate({ - accumulators: [avg('rating').as('avg_rating')], + accumulators: [avg('rating').as('avgRating')], groups: ['genre'], }) - .where(gt('avg_rating', 4.3)) + .where(gt('avgRating', 4.3)) + .sort(Field.of('avgRating').descending()) .execute(); expectResults( results, - {avg_rating: 4.7, genre: 'Fantasy'}, - {avg_rating: 4.5, genre: 'Romance'}, - {avg_rating: 4.4, genre: 'Science Fiction'} + {avgRating: 4.7, genre: 'Fantasy'}, + {avgRating: 4.5, genre: 'Romance'}, + {avgRating: 4.4, genre: 'Science Fiction'} ); }); - it('returns min and max accumulations', async () => { + it('returns minimum and maximum accumulations', async () => { const results = await randomCol .pipeline() .aggregate( countAll().as('count'), - Field.of('rating').max().as('max_rating'), - Field.of('published').min().as('min_published') + Field.of('rating').maximum().as('max_rating'), + Field.of('published').minimum().as('min_published') ) .execute(); expectResults(results, { @@ -443,6 +444,95 @@ describe.only('Pipeline class', () => { ); }); + it('logical min works', async () => { + const results = await randomCol + .pipeline() + .select( + 'title', + logicalMinimum(Constant.of(1960), Field.of('published')).as( + 'published-safe' + ) + ) + .sort(Field.of('title').ascending()) + .limit(3) + .execute(); + expectResults( + results, + {title: '1984', 'published-safe': 1949}, + {title: 'Crime and Punishment', 'published-safe': 1866}, + {title: 'Dune', 'published-safe': 1960} + ); + }); + + it('logical max works', async () => { + const results = await randomCol + .pipeline() + .select( + 'title', + logicalMaximum(Constant.of(1960), Field.of('published')).as( + 'published-safe' + ) + ) + .sort(Field.of('title').ascending()) + .limit(3) + .execute(); + expectResults( + results, + {title: '1984', 'published-safe': 1960}, + {title: 'Crime and Punishment', 'published-safe': 1960}, + {title: 'Dune', 'published-safe': 1965} + ); + }); + + it('cond works', async () => { + const results = await randomCol + .pipeline() + .select( + 'title', + cond( + lt(Field.of('published'), 1960), + Constant.of(1960), + Field.of('published') + ).as('published-safe') + ) + .sort(Field.of('title').ascending()) + .limit(3) + .execute(); + expectResults( + results, + {title: '1984', 'published-safe': 1960}, + {title: 'Crime and Punishment', 'published-safe': 1960}, + {title: 'Dune', 'published-safe': 1965} + ); + }); + + it('eqAny works', async () => { + const results = await randomCol + .pipeline() + .where(eqAny('published', [1979, 1999, 1967])) + .select('title') + .execute(); + expectResults( + results, + {title: "The Hitchhiker's Guide to the Galaxy"}, + {title: 'One Hundred Years of Solitude'} + ); + }); + + it('notEqAny works', async () => { + const results = await randomCol + .pipeline() + .where( + notEqAny( + 'published', + [1965, 1925, 1949, 1960, 1866, 1985, 1954, 1967, 1979] + ) + ) + .select('title') + .execute(); + expectResults(results, {title: 'Pride and Prejudice'}); + }); + it('arrayContains works', async () => { const results = await randomCol .pipeline() @@ -483,7 +573,8 @@ describe.only('Pipeline class', () => { expect(results.length).to.equal(10); }); - it('arrayConcat works', async () => { + // array_concat not implemented + it.skip('arrayConcat works', async () => { const results = await randomCol .pipeline() .select( @@ -547,18 +638,33 @@ describe.only('Pipeline class', () => { Field.of('title') ) .where(gt('titleLength', 20)) + .sort(Field.of('title').ascending()) .execute(); + expectResults( results, - {titleLength: 32, title: "The Hitchhiker's Guide to the Galaxy"}, + { - titleLength: 27, + titleLength: 29, title: 'One Hundred Years of Solitude', + }, + { + titleLength: 36, + title: "The Hitchhiker's Guide to the Galaxy", + }, + { + titleLength: 21, + title: 'The Lord of the Rings', + }, + { + titleLength: 21, + title: 'To Kill a Mockingbird', } ); }); - it('testToLowercase', async () => { + // to_lower not implemented + it.skip('testToLowercase', async () => { const results = await randomCol .pipeline() .select(Field.of('title').toLower().as('lowercaseTitle')) @@ -569,7 +675,8 @@ describe.only('Pipeline class', () => { }); }); - it('testToUppercase', async () => { + // to_upper not implemented + it.skip('testToUppercase', async () => { const results = await randomCol .pipeline() .select(Field.of('author').toUpper().as('uppercaseAuthor')) @@ -578,7 +685,8 @@ describe.only('Pipeline class', () => { expectResults(results, {uppercaseAuthor: 'DOUGLAS ADAMS'}); }); - it('testTrim', async () => { + // trim not implemented + it.skip('testTrim', async () => { const results = await randomCol .pipeline() .addFields(strConcat(' ', Field.of('title'), ' ').as('spacedTitle')) diff --git a/types/firestore.d.ts b/types/firestore.d.ts index fce440cd2..152f35996 100644 --- a/types/firestore.d.ts +++ b/types/firestore.d.ts @@ -3875,7 +3875,7 @@ declare namespace FirebaseFirestore { * @param others The values or expressions to check against. * @return A new `Expr` representing the 'IN' comparison. */ - in(...others: Expr[]): In; + eqAny(...others: Expr[]): EqAny; /** * Creates an expression that checks if this expression is equal to any of the provided values or @@ -3889,7 +3889,7 @@ declare namespace FirebaseFirestore { * @param others The values or expressions to check against. * @return A new `Expr` representing the 'IN' comparison. */ - in(...others: any[]): In; + eqAny(...others: any[]): EqAny; /** * Creates an expression that checks if this expression evaluates to 'NaN' (Not a Number). @@ -4274,76 +4274,76 @@ declare namespace FirebaseFirestore { * * ```typescript * // Find the lowest price of all products - * Field.of("price").min().as("lowestPrice"); + * Field.of("price").minimum().as("lowestPrice"); * ``` * - * @return A new `Accumulator` representing the 'min' aggregation. + * @return A new `Accumulator` representing the 'minimum' aggregation. */ - min(): Min; + minimum(): Minimum; /** * Creates an aggregation that finds the maximum value of a field across multiple stage inputs. * * ```typescript * // Find the highest score in a leaderboard - * Field.of("score").max().as("highestScore"); + * Field.of("score").maximum().as("highestScore"); * ``` * - * @return A new `Accumulator` representing the 'max' aggregation. + * @return A new `Accumulator` representing the 'maximum' aggregation. */ - max(): Max; + maximum(): Maximim; /** * Creates an expression that returns the larger value between this expression and another expression, based on Firestore's value type ordering. * * ```typescript * // Returns the larger value between the 'timestamp' field and the current timestamp. - * Field.of("timestamp").logicalMax(Function.currentTimestamp()); + * Field.of("timestamp").logicalMaximum(Function.currentTimestamp()); * ``` * * @param other The expression to compare with. - * @return A new {@code Expr} representing the logical max operation. + * @return A new {@code Expr} representing the logical maximum operation. */ - logicalMax(other: Expr): LogicalMax; + logicalMaximum(other: Expr): LogicalMaximum; /** * Creates an expression that returns the larger value between this expression and a constant value, based on Firestore's value type ordering. * * ```typescript * // Returns the larger value between the 'value' field and 10. - * Field.of("value").logicalMax(10); + * Field.of("value").logicalMaximum(10); * ``` * * @param other The constant value to compare with. - * @return A new {@code Expr} representing the logical max operation. + * @return A new {@code Expr} representing the logical maximum operation. */ - logicalMax(other: any): LogicalMax; + logicalMaximum(other: any): LogicalMaximum; /** * Creates an expression that returns the smaller value between this expression and another expression, based on Firestore's value type ordering. * * ```typescript * // Returns the smaller value between the 'timestamp' field and the current timestamp. - * Field.of("timestamp").logicalMin(Function.currentTimestamp()); + * Field.of("timestamp").logicalMinimum(Function.currentTimestamp()); * ``` * * @param other The expression to compare with. - * @return A new {@code Expr} representing the logical min operation. + * @return A new {@code Expr} representing the logical minimum operation. */ - logicalMin(other: Expr): LogicalMin; + logicalMinimum(other: Expr): LogicalMinimum; /** * Creates an expression that returns the smaller value between this expression and a constant value, based on Firestore's value type ordering. * * ```typescript * // Returns the smaller value between the 'value' field and 10. - * Field.of("value").logicalMin(10); + * Field.of("value").logicalMinimum(10); * ``` * * @param other The constant value to compare with. - * @return A new {@code Expr} representing the logical min operation. + * @return A new {@code Expr} representing the logical minimum operation. */ - logicalMin(other: any): LogicalMin; + logicalMinimum(other: any): LogicalMinimum; /** * Creates an expression that calculates the length (number of dimensions) of this Firestore Vector expression. @@ -5030,7 +5030,7 @@ declare namespace FirebaseFirestore { /** * @beta */ - export class In extends Function implements FilterCondition { + export class EqAny extends Function implements FilterCondition { filterable: true; } @@ -5086,12 +5086,12 @@ declare namespace FirebaseFirestore { /** * @beta */ - export class LogicalMax extends Function {} + export class LogicalMaximum extends Function {} /** * @beta */ - export class LogicalMin extends Function {} + export class LogicalMinimum extends Function {} /** * @beta @@ -5209,14 +5209,14 @@ declare namespace FirebaseFirestore { /** * @beta */ - export class Min extends Function implements Accumulator { + export class Minimum extends Function implements Accumulator { accumulator: true; } /** * @beta */ - export class Max extends Function implements Accumulator { + export class Maximim extends Function implements Accumulator { accumulator: true; } @@ -6648,14 +6648,14 @@ declare namespace FirebaseFirestore { * * ```typescript * // Check if the 'category' field is either "Electronics" or value of field 'primaryType' - * inAny(Field.of("category"), [Constant.of("Electronics"), Field.of("primaryType")]); + * eqAny(Field.of("category"), [Constant.of("Electronics"), Field.of("primaryType")]); * ``` * * @param element The expression to compare. * @param others The values to check against. * @return A new {@code Expr} representing the 'IN' comparison. */ - export function inAny(element: Expr, others: Expr[]): In; + export function eqAny(element: Expr, others: Expr[]): EqAny; /** * @beta @@ -6665,14 +6665,14 @@ declare namespace FirebaseFirestore { * * ```typescript * // Check if the 'category' field is either "Electronics" or value of field 'primaryType' - * inAny(Field.of("category"), ["Electronics", Field.of("primaryType")]); + * eqAny(Field.of("category"), ["Electronics", Field.of("primaryType")]); * ``` * * @param element The expression to compare. * @param others The values to check against. * @return A new {@code Expr} representing the 'IN' comparison. */ - export function inAny(element: Expr, others: any[]): In; + export function eqAny(element: Expr, others: any[]): EqAny; /** * @beta @@ -6682,14 +6682,14 @@ declare namespace FirebaseFirestore { * * ```typescript * // Check if the 'category' field is either "Electronics" or value of field 'primaryType' - * inAny("category", [Constant.of("Electronics"), Field.of("primaryType")]); + * eqAny("category", [Constant.of("Electronics"), Field.of("primaryType")]); * ``` * * @param element The field to compare. * @param others The values to check against. * @return A new {@code Expr} representing the 'IN' comparison. */ - export function inAny(element: string, others: Expr[]): In; + export function eqAny(element: string, others: Expr[]): EqAny; /** * @beta @@ -6699,14 +6699,14 @@ declare namespace FirebaseFirestore { * * ```typescript * // Check if the 'category' field is either "Electronics" or value of field 'primaryType' - * inAny("category", ["Electronics", Field.of("primaryType")]); + * eqAny("category", ["Electronics", Field.of("primaryType")]); * ``` * * @param element The field to compare. * @param others The values to check against. * @return A new {@code Expr} representing the 'IN' comparison. */ - export function inAny(element: string, others: any[]): In; + export function eqAny(element: string, others: any[]): EqAny; /** * @beta @@ -6716,14 +6716,14 @@ declare namespace FirebaseFirestore { * * ```typescript * // Check if the 'status' field is neither "pending" nor the value of 'rejectedStatus' - * notInAny(Field.of("status"), [Constant.of("pending"), Field.of("rejectedStatus")]); + * notEqAny(Field.of("status"), [Constant.of("pending"), Field.of("rejectedStatus")]); * ``` * * @param element The expression to compare. * @param others The values to check against. * @return A new {@code Expr} representing the 'NOT IN' comparison. */ - export function notInAny(element: Expr, others: Expr[]): Not; + export function notEqAny(element: Expr, others: Expr[]): NotEqAny; /** * @beta @@ -6733,14 +6733,14 @@ declare namespace FirebaseFirestore { * * ```typescript * // Check if the 'status' field is neither "pending" nor the value of 'rejectedStatus' - * notInAny(Field.of("status"), ["pending", Field.of("rejectedStatus")]); + * notEqAny(Field.of("status"), ["pending", Field.of("rejectedStatus")]); * ``` * * @param element The expression to compare. * @param others The values to check against. * @return A new {@code Expr} representing the 'NOT IN' comparison. */ - export function notInAny(element: Expr, others: any[]): Not; + export function notEqAny(element: Expr, others: any[]): NotEqAny; /** * @beta @@ -6750,14 +6750,14 @@ declare namespace FirebaseFirestore { * * ```typescript * // Check if the 'status' field is neither "pending" nor the value of 'rejectedStatus' - * notInAny("status", [Constant.of("pending"), Field.of("rejectedStatus")]); + * notEqAny("status", [Constant.of("pending"), Field.of("rejectedStatus")]); * ``` * * @param element The field name to compare. * @param others The values to check against. * @return A new {@code Expr} representing the 'NOT IN' comparison. */ - export function notInAny(element: string, others: Expr[]): Not; + export function notEqAny(element: string, others: Expr[]): NotEqAny; /** * @beta @@ -6767,14 +6767,14 @@ declare namespace FirebaseFirestore { * * ```typescript * // Check if the 'status' field is neither "pending" nor the value of 'rejectedStatus' - * notInAny("status", ["pending", Field.of("rejectedStatus")]); + * notEqAny("status", ["pending", Field.of("rejectedStatus")]); * ``` * * @param element The field name to compare. * @param others The values to check against. * @return A new {@code Expr} representing the 'NOT IN' comparison. */ - export function notInAny(element: string, others: any[]): Not; + export function notEqAny(element: string, others: any[]): NotEqAny; /** * @beta @@ -6839,7 +6839,7 @@ declare namespace FirebaseFirestore { * * ```typescript * // If 'age' is greater than 18, return "Adult"; otherwise, return "Minor". - * ifFunction( + * cond( * gt("age", 18), Constant.of("Adult"), Constant.of("Minor")); * ``` * @@ -6876,14 +6876,14 @@ declare namespace FirebaseFirestore { * * ```typescript * // Returns the larger value between the 'timestamp' field and the current timestamp. - * logicalMax(Field.of("timestamp"), Function.currentTimestamp()); + * logicalMaximum(Field.of("timestamp"), Function.currentTimestamp()); * ``` * * @param left The left operand expression. * @param right The right operand expression. - * @return A new {@code Expr} representing the logical max operation. + * @return A new {@code Expr} representing the logical maximum operation. */ - export function logicalMax(left: Expr, right: Expr): LogicalMax; + export function logicalMaximum(left: Expr, right: Expr): LogicalMaximum; /** * @beta @@ -6892,14 +6892,14 @@ declare namespace FirebaseFirestore { * * ```typescript * // Returns the larger value between the 'value' field and 10. - * logicalMax(Field.of("value"), 10); + * logicalMaximum(Field.of("value"), 10); * ``` * * @param left The left operand expression. * @param right The right operand constant. - * @return A new {@code Expr} representing the logical max operation. + * @return A new {@code Expr} representing the logical maximum operation. */ - export function logicalMax(left: Expr, right: any): LogicalMax; + export function logicalMaximum(left: Expr, right: any): LogicalMaximum; /** * @beta @@ -6908,14 +6908,14 @@ declare namespace FirebaseFirestore { * * ```typescript * // Returns the larger value between the 'timestamp' field and the current timestamp. - * logicalMax("timestamp", Function.currentTimestamp()); + * logicalMaximum("timestamp", Function.currentTimestamp()); * ``` * * @param left The left operand field name. * @param right The right operand expression. - * @return A new {@code Expr} representing the logical max operation. + * @return A new {@code Expr} representing the logical maximum operation. */ - export function logicalMax(left: string, right: Expr): LogicalMax; + export function logicalMaximum(left: string, right: Expr): LogicalMaximum; /** * @beta @@ -6924,14 +6924,14 @@ declare namespace FirebaseFirestore { * * ```typescript * // Returns the larger value between the 'value' field and 10. - * logicalMax("value", 10); + * logicalMaximum("value", 10); * ``` * * @param left The left operand field name. * @param right The right operand constant. - * @return A new {@code Expr} representing the logical max operation. + * @return A new {@code Expr} representing the logical maximum operation. */ - export function logicalMax(left: string, right: any): LogicalMax; + export function logicalMaximum(left: string, right: any): LogicalMaximum; /** * @beta @@ -6940,14 +6940,14 @@ declare namespace FirebaseFirestore { * * ```typescript * // Returns the smaller value between the 'timestamp' field and the current timestamp. - * logicalMin(Field.of("timestamp"), Function.currentTimestamp()); + * logicalMinimum(Field.of("timestamp"), Function.currentTimestamp()); * ``` * * @param left The left operand expression. * @param right The right operand expression. - * @return A new {@code Expr} representing the logical min operation. + * @return A new {@code Expr} representing the logical minimum operation. */ - export function logicalMin(left: Expr, right: Expr): LogicalMin; + export function logicalMinimum(left: Expr, right: Expr): LogicalMinimum; /** * @beta @@ -6956,14 +6956,14 @@ declare namespace FirebaseFirestore { * * ```typescript * // Returns the smaller value between the 'value' field and 10. - * logicalMin(Field.of("value"), 10); + * logicalMinimum(Field.of("value"), 10); * ``` * * @param left The left operand expression. * @param right The right operand constant. - * @return A new {@code Expr} representing the logical min operation. + * @return A new {@code Expr} representing the logical minimum operation. */ - export function logicalMin(left: Expr, right: any): LogicalMin; + export function logicalMinimum(left: Expr, right: any): LogicalMinimum; /** * @beta @@ -6972,14 +6972,14 @@ declare namespace FirebaseFirestore { * * ```typescript * // Returns the smaller value between the 'timestamp' field and the current timestamp. - * logicalMin("timestamp", Function.currentTimestamp()); + * logicalMinimum("timestamp", Function.currentTimestamp()); * ``` * * @param left The left operand field name. * @param right The right operand expression. - * @return A new {@code Expr} representing the logical min operation. + * @return A new {@code Expr} representing the logical minimum operation. */ - export function logicalMin(left: string, right: Expr): LogicalMin; + export function logicalMinimum(left: string, right: Expr): LogicalMinimum; /** * @beta @@ -6988,14 +6988,14 @@ declare namespace FirebaseFirestore { * * ```typescript * // Returns the smaller value between the 'value' field and 10. - * logicalMin("value", 10); + * logicalMinimum("value", 10); * ``` * * @param left The left operand field name. * @param right The right operand constant. - * @return A new {@code Expr} representing the logical min operation. + * @return A new {@code Expr} representing the logical minimum operation. */ - export function logicalMin(left: string, right: any): LogicalMin; + export function logicalMinimum(left: string, right: any): LogicalMinimum; /** * @beta @@ -7986,13 +7986,13 @@ declare namespace FirebaseFirestore { * * ```typescript * // Find the lowest price of all products - * min(Field.of("price")).as("lowestPrice"); + * minimum(Field.of("price")).as("lowestPrice"); * ``` * * @param value The expression to find the minimum value of. - * @return A new {@code Accumulator} representing the 'min' aggregation. + * @return A new {@code Accumulator} representing the 'minimum' aggregation. */ - export function min(value: Expr): Min; + export function minimum(value: Expr): Minimum; /** * @beta @@ -8001,13 +8001,13 @@ declare namespace FirebaseFirestore { * * ```typescript * // Find the lowest price of all products - * min("price").as("lowestPrice"); + * minimum("price").as("lowestPrice"); * ``` * * @param value The name of the field to find the minimum value of. - * @return A new {@code Accumulator} representing the 'min' aggregation. + * @return A new {@code Accumulator} representing the 'minimum' aggregation. */ - export function min(value: string): Min; + export function minimum(value: string): Minimum; /** * @beta @@ -8017,13 +8017,13 @@ declare namespace FirebaseFirestore { * * ```typescript * // Find the highest score in a leaderboard - * max(Field.of("score")).as("highestScore"); + * maximum(Field.of("score")).as("highestScore"); * ``` * * @param value The expression to find the maximum value of. - * @return A new {@code Accumulator} representing the 'max' aggregation. + * @return A new {@code Accumulator} representing the 'maximum' aggregation. */ - export function max(value: Expr): Max; + export function maximum(value: Expr): Maximim; /** * @beta @@ -8032,13 +8032,13 @@ declare namespace FirebaseFirestore { * * ```typescript * // Find the highest score in a leaderboard - * max("score").as("highestScore"); + * maximum("score").as("highestScore"); * ``` * * @param value The name of the field to find the maximum value of. - * @return A new {@code Accumulator} representing the 'max' aggregation. + * @return A new {@code Accumulator} representing the 'maximum' aggregation. */ - export function max(value: string): Max; + export function maximum(value: string): Maximim; /** * @beta From 61fc7820210a453c8b65b769d9e3d82425cfc4c1 Mon Sep 17 00:00:00 2001 From: Tom Andersen Date: Mon, 9 Dec 2024 12:39:43 -0500 Subject: [PATCH 32/60] chore: Merge main and resolve conflicts. (#2240) * # Conflicts: # dev/conformance/runner.ts # dev/src/reference/query.ts # dev/system-test/firestore.ts # types/firestore.d.ts * fix --- .github/.OwlBot.lock.yaml | 4 +- .github/ISSUE_TEMPLATE/bug_report.yml | 99 + .../ISSUE_TEMPLATE/documentation_request.yml | 53 + .github/ISSUE_TEMPLATE/feature_request.yml | 53 + .github/ISSUE_TEMPLATE/processs_request.md | 5 + .github/ISSUE_TEMPLATE/questions.md | 8 + .github/auto-approve.yml | 4 +- .github/scripts/close-invalid-link.cjs | 53 + .github/scripts/close-unresponsive.cjs | 69 + .github/scripts/remove-response-label.cjs | 33 + .github/workflows/issues-no-repro.yaml | 18 + .github/workflows/response.yaml | 35 + .idea/runConfigurations/System_Test.xml | 4 +- CHANGELOG.md | 16 + README.md | 4 +- api-report/firestore.api.md | 170 +- dev/conformance/runner.ts | 8 +- dev/protos/admin_v1.json | 150 +- dev/protos/firestore_admin_v1_proto_api.d.ts | 307 +- dev/protos/firestore_admin_v1_proto_api.js | 1002 +- dev/protos/firestore_v1_proto_api.d.ts | 13718 +++--- dev/protos/firestore_v1_proto_api.js | 39606 ++++++++-------- dev/protos/firestore_v1beta1_proto_api.d.ts | 88 +- dev/protos/firestore_v1beta1_proto_api.js | 381 +- dev/protos/google/api/client.proto | 24 +- dev/protos/google/api/http.proto | 48 +- dev/protos/google/api/resource.proto | 9 +- .../google/firestore/admin/v1/field.proto | 33 +- .../firestore/admin/v1/firestore_admin.proto | 77 +- .../google/firestore/admin/v1/index.proto | 2 +- .../google/firestore/admin/v1/operation.proto | 33 + dev/protos/google/firestore/v1/document.proto | 3 +- dev/protos/google/firestore/v1/query.proto | 42 +- dev/protos/google/protobuf/descriptor.proto | 94 +- dev/protos/update.sh | 4 +- dev/protos/v1.json | 7133 ++- dev/protos/v1beta1.json | 49 +- dev/src/bulk-writer.ts | 106 +- dev/src/collection-group.ts | 80 +- dev/src/index.ts | 125 +- dev/src/reference/aggregate-query.ts | 20 +- dev/src/reference/collection-reference.ts | 96 +- dev/src/reference/document-reference.ts | 143 +- dev/src/reference/query-util.ts | 61 +- dev/src/reference/query.ts | 90 +- dev/src/reference/vector-query-options.ts | 59 +- dev/src/reference/vector-query.ts | 65 +- dev/src/telemetry/disabled-trace-util.ts | 42 + dev/src/telemetry/enabled-trace-util.ts | 197 + dev/src/telemetry/span.ts | 36 + dev/src/telemetry/trace-util.ts | 81 + dev/src/transaction.ts | 250 +- dev/src/v1/firestore_admin_client.ts | 190 +- dev/src/v1/firestore_admin_client_config.json | 5 + dev/src/write-batch.ts | 56 +- dev/system-test/firestore.ts | 2562 +- dev/system-test/tracing.ts | 952 + dev/test/gapic_firestore_admin_v1.ts | 242 +- dev/test/gapic_firestore_v1.ts | 72 +- dev/test/gapic_firestore_v1beta1.ts | 72 +- dev/test/query.ts | 395 +- dev/test/recursive-delete.ts | 2 +- dev/test/tracing.ts | 148 + dev/test/vector-query.ts | 347 +- owlbot.py | 5 +- package.json | 29 +- renovate.json | 1 + samples/package.json | 2 +- types/firestore.d.ts | 101 +- .../protos/firestore_admin_v1_proto_api.d.ts | 6997 ++- types/protos/firestore_v1_proto_api.d.ts | 12242 +++-- types/protos/firestore_v1beta1_proto_api.d.ts | 3273 +- types/v1/firestore_admin_client.d.ts | 1402 +- types/v1/firestore_client.d.ts | 551 +- types/v1beta1/firestore_client.d.ts | 173 +- 75 files changed, 55635 insertions(+), 39074 deletions(-) create mode 100644 .github/ISSUE_TEMPLATE/bug_report.yml create mode 100644 .github/ISSUE_TEMPLATE/documentation_request.yml create mode 100644 .github/ISSUE_TEMPLATE/feature_request.yml create mode 100644 .github/ISSUE_TEMPLATE/processs_request.md create mode 100644 .github/ISSUE_TEMPLATE/questions.md create mode 100644 .github/scripts/close-invalid-link.cjs create mode 100644 .github/scripts/close-unresponsive.cjs create mode 100644 .github/scripts/remove-response-label.cjs create mode 100644 .github/workflows/issues-no-repro.yaml create mode 100644 .github/workflows/response.yaml create mode 100644 dev/src/telemetry/disabled-trace-util.ts create mode 100644 dev/src/telemetry/enabled-trace-util.ts create mode 100644 dev/src/telemetry/span.ts create mode 100644 dev/src/telemetry/trace-util.ts create mode 100644 dev/system-test/tracing.ts create mode 100644 dev/test/tracing.ts diff --git a/.github/.OwlBot.lock.yaml b/.github/.OwlBot.lock.yaml index 34bb2086d..460f67f2b 100644 --- a/.github/.OwlBot.lock.yaml +++ b/.github/.OwlBot.lock.yaml @@ -13,5 +13,5 @@ # limitations under the License. docker: image: gcr.io/cloud-devrel-public-resources/owlbot-nodejs:latest - digest: sha256:68e1cece0d6d3336c4f1cb9d2857b020af5574dff6da6349293d1c6d4eea82d8 -# created: 2024-05-31T15:46:42.989947733Z + digest: sha256:a5af6af827a9fffba373151e1453b0498da288024cdd16477900dd42857a42e0 +# created: 2024-09-20T20:26:11.126243246Z diff --git a/.github/ISSUE_TEMPLATE/bug_report.yml b/.github/ISSUE_TEMPLATE/bug_report.yml new file mode 100644 index 000000000..022ad3f3a --- /dev/null +++ b/.github/ISSUE_TEMPLATE/bug_report.yml @@ -0,0 +1,99 @@ +name: Bug Report +description: Create a report to help us improve +labels: + - bug +body: + - type: markdown + attributes: + value: > + **PLEASE READ**: If you have a support contract with Google, please + create an issue in the [support + console](https://cloud.google.com/support/) instead of filing on GitHub. + This will ensure a timely response. Otherwise, please make sure to + follow the steps below. + - type: checkboxes + attributes: + label: Please make sure you have searched for information in the following + guides. + options: + - label: "Search the issues already opened: + https://github.com/GoogleCloudPlatform/google-cloud-node/issues" + required: true + - label: "Search StackOverflow: + http://stackoverflow.com/questions/tagged/google-cloud-platform+nod\ + e.js" + required: true + - label: "Check our Troubleshooting guide: + https://googlecloudplatform.github.io/google-cloud-node/#/docs/guid\ + es/troubleshooting" + required: true + - label: "Check our FAQ: + https://googlecloudplatform.github.io/google-cloud-node/#/docs/guid\ + es/faq" + required: true + - label: "Check our libraries HOW-TO: + https://github.com/googleapis/gax-nodejs/blob/main/client-libraries\ + .md" + required: true + - label: "Check out our authentication guide: + https://github.com/googleapis/google-auth-library-nodejs" + required: true + - label: "Check out handwritten samples for many of our APIs: + https://github.com/GoogleCloudPlatform/nodejs-docs-samples" + required: true + - type: textarea + attributes: + label: > + A screenshot that you have tested with "Try this API". + description: > + As our client libraries are mostly autogenerated, we kindly request + that you test whether your issue is with the client library, or with the + API itself. To do so, please search for your API + here: https://developers.google.com/apis-explorer and attempt to + reproduce the issue in the given method. Please include a screenshot of + the response in "Try this API". This response should NOT match the current + behavior you are experiencing. If the behavior is the same, it means + that you are likely experiencing a bug with the API itself. In that + case, please submit an issue to the API team, either by submitting an + issue in its issue tracker https://cloud.google.com/support/docs/issue-trackers, or by + submitting an issue in its linked tracker in the .repo-metadata.json + file https://issuetracker.google.com/savedsearches/5337669 + validations: + required: true + - type: input + attributes: + label: > + Link to the code that reproduces this issue. A link to a **public** Github Repository or gist with a minimal + reproduction. + description: > + **Skipping this or providing an invalid link will result in the issue being closed** + validations: + required: true + - type: textarea + attributes: + label: > + A step-by-step description of how to reproduce the issue, based on + the linked reproduction. + description: > + Screenshots can be provided in the issue body below. + placeholder: | + 1. Start the application in development (next dev) + 2. Click X + 3. Y will happen + validations: + required: true + - type: textarea + attributes: + label: A clear and concise description of what the bug is, and what you + expected to happen. + placeholder: Following the steps from the previous section, I expected A to + happen, but I observed B instead + validations: + required: true + + - type: textarea + attributes: + label: A clear and concise description WHY you expect this behavior, i.e., was it a recent change, there is documentation that points to this behavior, etc. ** + placeholder: 'Documentation here(link) states that B should happen instead of A' + validations: + required: true diff --git a/.github/ISSUE_TEMPLATE/documentation_request.yml b/.github/ISSUE_TEMPLATE/documentation_request.yml new file mode 100644 index 000000000..24443e355 --- /dev/null +++ b/.github/ISSUE_TEMPLATE/documentation_request.yml @@ -0,0 +1,53 @@ +name: Documentation Requests +description: Requests for more information +body: + - type: markdown + attributes: + value: > + Please use this issue type to log documentation requests against the library itself. + These requests should involve documentation on Github (`.md` files), and should relate to the library + itself. If you have questions or documentation requests for an API, please + reach out to the API tracker itself. + + Please submit an issue to the API team, either by submitting an + issue in its issue tracker https://cloud.google.com/support/docs/issue-trackers), or by + submitting an issue in its linked tracker in the .repo-metadata.json + file in the API under packages/* ([example](https://issuetracker.google.com/savedsearches/5337669)). + You can also submit a request to documentation on cloud.google.com itself with the "Send Feedback" + on the bottom of the page. + + + Please note that documentation requests and questions for specific APIs + will be closed. + - type: checkboxes + attributes: + label: Please make sure you have searched for information in the following + guides. + options: + - label: "Search the issues already opened: + https://github.com/GoogleCloudPlatform/google-cloud-node/issues" + required: true + - label: "Check our Troubleshooting guide: + https://googlecloudplatform.github.io/google-cloud-node/#/docs/guid\ + es/troubleshooting" + required: true + - label: "Check our FAQ: + https://googlecloudplatform.github.io/google-cloud-node/#/docs/guid\ + es/faq" + required: true + - label: "Check our libraries HOW-TO: + https://github.com/googleapis/gax-nodejs/blob/main/client-libraries\ + .md" + required: true + - label: "Check out our authentication guide: + https://github.com/googleapis/google-auth-library-nodejs" + required: true + - label: "Check out handwritten samples for many of our APIs: + https://github.com/GoogleCloudPlatform/nodejs-docs-samples" + required: true + - type: textarea + attributes: + label: > + Documentation Request + validations: + required: true diff --git a/.github/ISSUE_TEMPLATE/feature_request.yml b/.github/ISSUE_TEMPLATE/feature_request.yml new file mode 100644 index 000000000..4598e16f9 --- /dev/null +++ b/.github/ISSUE_TEMPLATE/feature_request.yml @@ -0,0 +1,53 @@ +name: Feature Request +description: Suggest an idea for this library +labels: + - feature request +body: + - type: markdown + attributes: + value: > + **PLEASE READ**: If you have a support contract with Google, please + create an issue in the [support + console](https://cloud.google.com/support/) instead of filing on GitHub. + This will ensure a timely response. Otherwise, please make sure to + follow the steps below. + - type: textarea + attributes: + label: > + A screenshot that you have tested with "Try this API". + description: > + As our client libraries are mostly autogenerated, we kindly request + that you test whether your feature request is with the client library, or with the + API itself. To do so, please search for your API + here: https://developers.google.com/apis-explorer and attempt to + reproduce the issue in the given method. Please include a screenshot of + the response in "Try this API". This response should NOT match the current + behavior you are experiencing. If the behavior is the same, it means + that you are likely requesting a feature for the API itself. In that + case, please submit an issue to the API team, either by submitting an + issue in its issue tracker https://cloud.google.com/support/docs/issue-trackers, or by + submitting an issue in its linked tracker in the .repo-metadata.json + file in the API under packages/* ([example](https://issuetracker.google.com/savedsearches/5337669)) + + Example of library specific issues would be: retry strategies, authentication questions, or issues with typings. + Examples of API issues would include: expanding method parameter types, adding functionality to an API. + validations: + required: true + - type: textarea + attributes: + label: > + What would you like to see in the library? + description: > + Screenshots can be provided in the issue body below. + placeholder: | + 1. Set up authentication like so + 2. Run the program like so + 3. X would be nice to happen + + - type: textarea + attributes: + label: Describe alternatives you've considered + + - type: textarea + attributes: + label: Additional context/notes \ No newline at end of file diff --git a/.github/ISSUE_TEMPLATE/processs_request.md b/.github/ISSUE_TEMPLATE/processs_request.md new file mode 100644 index 000000000..9f88fc1f3 --- /dev/null +++ b/.github/ISSUE_TEMPLATE/processs_request.md @@ -0,0 +1,5 @@ +--- +name: Process Request +about: Submit a process request to the library. Process requests are any requests related to library infrastructure, including CI/CD, publishing, releasing, etc. This issue template should primarily used by internal members. + +--- \ No newline at end of file diff --git a/.github/ISSUE_TEMPLATE/questions.md b/.github/ISSUE_TEMPLATE/questions.md new file mode 100644 index 000000000..62c1dd1b9 --- /dev/null +++ b/.github/ISSUE_TEMPLATE/questions.md @@ -0,0 +1,8 @@ +--- +name: Question +about: If you have a question, please use Discussions + +--- + +If you have a general question that goes beyond the library itself, we encourage you to use [Discussions](https://github.com//discussions) +to engage with fellow community members! diff --git a/.github/auto-approve.yml b/.github/auto-approve.yml index ec51b072d..7cba0af63 100644 --- a/.github/auto-approve.yml +++ b/.github/auto-approve.yml @@ -1,4 +1,2 @@ processes: - - "NodeDependency" - - "OwlBotTemplateChangesNode" - - "OwlBotPRsNode" \ No newline at end of file + - "NodeDependency" \ No newline at end of file diff --git a/.github/scripts/close-invalid-link.cjs b/.github/scripts/close-invalid-link.cjs new file mode 100644 index 000000000..ba7d51372 --- /dev/null +++ b/.github/scripts/close-invalid-link.cjs @@ -0,0 +1,53 @@ +// 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. + +async function closeIssue(github, owner, repo, number) { + await github.rest.issues.createComment({ + owner: owner, + repo: repo, + issue_number: number, + body: 'Issue was opened with an invalid reproduction link. Please make sure the repository is a valid, publicly-accessible github repository, and make sure the url is complete (example: https://github.com/googleapis/google-cloud-node)' + }); + await github.rest.issues.update({ + owner: owner, + repo: repo, + issue_number: number, + state: 'closed' + }); +} +module.exports = async ({github, context}) => { + const owner = context.repo.owner; + const repo = context.repo.repo; + const number = context.issue.number; + + const issue = await github.rest.issues.get({ + owner: owner, + repo: repo, + issue_number: number, + }); + + const isBugTemplate = issue.data.body.includes('Link to the code that reproduces this issue'); + + if (isBugTemplate) { + try { + const link = issue.data.body.split('\n')[18].match(/(https?:\/\/g?i?s?t?\.?github.com\/.*)/); + const isValidLink = (await fetch(link)).ok; + if (!isValidLink) { + await closeIssue(github, owner, repo, number); + } + } catch (err) { + await closeIssue(github, owner, repo, number); + } + } +}; diff --git a/.github/scripts/close-unresponsive.cjs b/.github/scripts/close-unresponsive.cjs new file mode 100644 index 000000000..142dc1265 --- /dev/null +++ b/.github/scripts/close-unresponsive.cjs @@ -0,0 +1,69 @@ +// 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. + +function labeledEvent(data) { + return data.event === 'labeled' && data.label.name === 'needs more info'; + } + + const numberOfDaysLimit = 15; + const close_message = `This has been closed since a request for information has \ + not been answered for ${numberOfDaysLimit} days. It can be reopened when the \ + requested information is provided.`; + + module.exports = async ({github, context}) => { + const owner = context.repo.owner; + const repo = context.repo.repo; + + const issues = await github.rest.issues.listForRepo({ + owner: owner, + repo: repo, + labels: 'needs more info', + }); + const numbers = issues.data.map((e) => e.number); + + for (const number of numbers) { + const events = await github.paginate( + github.rest.issues.listEventsForTimeline, + { + owner: owner, + repo: repo, + issue_number: number, + }, + (response) => response.data.filter(labeledEvent) + ); + + const latest_response_label = events[events.length - 1]; + + const created_at = new Date(latest_response_label.created_at); + const now = new Date(); + const diff = now - created_at; + const diffDays = diff / (1000 * 60 * 60 * 24); + + if (diffDays > numberOfDaysLimit) { + await github.rest.issues.update({ + owner: owner, + repo: repo, + issue_number: number, + state: 'closed', + }); + + await github.rest.issues.createComment({ + owner: owner, + repo: repo, + issue_number: number, + body: close_message, + }); + } + } + }; diff --git a/.github/scripts/remove-response-label.cjs b/.github/scripts/remove-response-label.cjs new file mode 100644 index 000000000..887cf349e --- /dev/null +++ b/.github/scripts/remove-response-label.cjs @@ -0,0 +1,33 @@ +// 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. + +module.exports = async ({ github, context }) => { + const commenter = context.actor; + const issue = await github.rest.issues.get({ + owner: context.repo.owner, + repo: context.repo.repo, + issue_number: context.issue.number, + }); + const author = issue.data.user.login; + const labels = issue.data.labels.map((e) => e.name); + + if (author === commenter && labels.includes('needs more info')) { + await github.rest.issues.removeLabel({ + owner: context.repo.owner, + repo: context.repo.repo, + issue_number: context.issue.number, + name: 'needs more info', + }); + } + }; diff --git a/.github/workflows/issues-no-repro.yaml b/.github/workflows/issues-no-repro.yaml new file mode 100644 index 000000000..442a46bcc --- /dev/null +++ b/.github/workflows/issues-no-repro.yaml @@ -0,0 +1,18 @@ +name: invalid_link +on: + issues: + types: [opened, reopened] + +jobs: + close: + runs-on: ubuntu-latest + permissions: + issues: write + pull-requests: write + steps: + - uses: actions/checkout@v4 + - uses: actions/github-script@v7 + with: + script: | + const script = require('./.github/scripts/close-invalid-link.cjs') + await script({github, context}) diff --git a/.github/workflows/response.yaml b/.github/workflows/response.yaml new file mode 100644 index 000000000..6ed37326f --- /dev/null +++ b/.github/workflows/response.yaml @@ -0,0 +1,35 @@ +name: no_response +on: + schedule: + - cron: '30 1 * * *' # Run every day at 01:30 + workflow_dispatch: + issue_comment: + +jobs: + close: + if: github.event_name == 'schedule' || github.event_name == 'workflow_dispatch' + runs-on: ubuntu-latest + permissions: + issues: write + pull-requests: write + steps: + - uses: actions/checkout@v4 + - uses: actions/github-script@v7 + with: + script: | + const script = require('./.github/scripts/close-unresponsive.cjs') + await script({github, context}) + + remove_label: + if: github.event_name == 'issue_comment' + runs-on: ubuntu-latest + permissions: + issues: write + pull-requests: write + steps: + - uses: actions/checkout@v4 + - uses: actions/github-script@v7 + with: + script: | + const script = require('./.github/scripts/remove-response-label.cjs') + await script({github, context}) diff --git a/.idea/runConfigurations/System_Test.xml b/.idea/runConfigurations/System_Test.xml index fde3707ba..9dad0feea 100644 --- a/.idea/runConfigurations/System_Test.xml +++ b/.idea/runConfigurations/System_Test.xml @@ -10,8 +10,8 @@ bdd --require ts-node/register/type-check --no-cache --timeout 60000 - TEST_FILE - $PROJECT_DIR$/dev/system-test/firestore.ts + PATTERN + $PROJECT_DIR$/dev/system-test/*.js $PROJECT_DIR$/dev/system-test/*.ts \ No newline at end of file diff --git a/CHANGELOG.md b/CHANGELOG.md index d3013fc89..57e34cc6a 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -4,6 +4,22 @@ [1]: https://www.npmjs.com/package/@google-cloud/firestore?activeTab=versions +## [7.10.0](https://github.com/googleapis/nodejs-firestore/compare/v7.9.0...v7.10.0) (2024-09-05) + + +### Features + +* Expose proto changes for the bulk delete api ([23ce891](https://github.com/googleapis/nodejs-firestore/commit/23ce89175ce315648ce9af3994cba0decc48ba47)) +* Expose the proto changes to support FindNearest.distance_result_field parameter and the FindNearest.distance_threshold parameter ([23ce891](https://github.com/googleapis/nodejs-firestore/commit/23ce89175ce315648ce9af3994cba0decc48ba47)) +* Return computed distance and set distance thresholds on VectorQueries ([#2090](https://github.com/googleapis/nodejs-firestore/issues/2090)) ([b5ca84f](https://github.com/googleapis/nodejs-firestore/commit/b5ca84f076ca0668e90ca3fc7dd878f732ccd956)) + +## [7.9.0](https://github.com/googleapis/nodejs-firestore/compare/v7.8.0...v7.9.0) (2024-06-25) + + +### Features + +* Update FirebaseFirestore.v1 and FirebaseFirestore.v1beta1 auto-gen types ([6732d4d](https://github.com/googleapis/nodejs-firestore/commit/6732d4da3c5ea851dccb0515757fbfb521f21410)) + ## [7.8.0](https://github.com/googleapis/nodejs-firestore/compare/v7.7.0...v7.8.0) (2024-05-28) diff --git a/README.md b/README.md index 87ca81d88..e4a568405 100644 --- a/README.md +++ b/README.md @@ -51,7 +51,7 @@ Google APIs Client Libraries, in [Client Libraries Explained][explained]. 1. [Select or create a Cloud Platform project][projects]. 1. [Enable the Cloud Firestore API][enable_api]. -1. [Set up authentication with a service account][auth] so you can access the +1. [Set up authentication][auth] so you can access the API from your local workstation. ### Installing the client library @@ -178,4 +178,4 @@ See [LICENSE](https://github.com/googleapis/nodejs-firestore/blob/main/LICENSE) [projects]: https://console.cloud.google.com/project [billing]: https://support.google.com/cloud/answer/6293499#enable-billing [enable_api]: https://console.cloud.google.com/flows/enableapi?apiid=firestore.googleapis.com -[auth]: https://cloud.google.com/docs/authentication/getting-started +[auth]: https://cloud.google.com/docs/authentication/external/set-up-adc-local diff --git a/api-report/firestore.api.md b/api-report/firestore.api.md index 5f9978015..3a146aef2 100644 --- a/api-report/firestore.api.md +++ b/api-report/firestore.api.md @@ -4,24 +4,23 @@ ```ts -/// - import * as $protobuf from 'protobufjs'; import { DocumentData } from '@google-cloud/firestore'; import { Duplex } from 'stream'; import * as firestore from '@google-cloud/firestore'; import { GoogleError } from 'google-gax'; import { Readable } from 'stream'; +import { Span as Span_2 } from '@opentelemetry/api'; // @public export class Aggregate { - constructor(alias: string, aggregateType: AggregateType, fieldPath?: string | FieldPath | undefined); + constructor(alias: string, aggregateType: AggregateType, fieldPath?: (string | FieldPath) | undefined); // (undocumented) readonly aggregateType: AggregateType; // (undocumented) readonly alias: string; // (undocumented) - readonly fieldPath?: string | FieldPath | undefined; + readonly fieldPath?: (string | FieldPath) | undefined; // Warning: (ae-forgotten-export) The symbol "google" needs to be exported by the entry point index.d.ts // // @internal @@ -920,6 +919,11 @@ class Firestore implements firestore.Firestore { // Warning: (tsdoc-undefined-tag) The TSDoc tag "@return" is not defined in this configuration toJSON(): object; // Warning: (tsdoc-undefined-tag) The TSDoc tag "@private" is not defined in this configuration + // Warning: (ae-forgotten-export) The symbol "TraceUtil" needs to be exported by the entry point index.d.ts + // + // @internal + _traceUtil: TraceUtil; + // Warning: (tsdoc-undefined-tag) The TSDoc tag "@private" is not defined in this configuration // // @internal unregisterListener(): void; @@ -1039,10 +1043,14 @@ export class Query, options: { limit: number; distanceMeasure: 'EUCLIDEAN' | 'COSINE' | 'DOT_PRODUCT'; }): VectorQuery; + findNearest(options: VectorQueryOptions): VectorQuery; + // (undocumented) + _findNearest(options: VectorQueryOptions): VectorQuery; // Warning: (tsdoc-escape-right-brace) The "}" character should be escaped using a backslash to avoid confusion with a TSDoc inline tag // Warning: (tsdoc-malformed-inline-tag) Expecting a TSDoc tag starting with "{@" // Warning: (tsdoc-undefined-tag) The TSDoc tag "@type" is not defined in this configuration @@ -1449,15 +1457,18 @@ export class Transaction implements firestore.Transaction { // @public export class VectorQuery implements firestore.VectorQuery { // Warning: (tsdoc-undefined-tag) The TSDoc tag "@private" is not defined in this configuration - // Warning: (ae-forgotten-export) The symbol "VectorQueryOptions" needs to be exported by the entry point index.d.ts // // @internal - constructor(_query: Query, vectorField: string | firestore.FieldPath, queryVector: firestore.VectorValue | Array, options: VectorQueryOptions); + constructor(_query: Query, _options: VectorQueryOptions); // Warning: (tsdoc-undefined-tag) The TSDoc tag "@private" is not defined in this configuration // // @internal _createSnapshot(readTime: Timestamp, size: number, docs: () => Array>, changes: () => Array>): VectorQuerySnapshot; + // Warning: (tsdoc-undefined-tag) The TSDoc tag "@return" is not defined in this configuration + explain(options?: firestore.ExplainOptions): Promise>>; get(): Promise>; + // (undocumented) + _getResponse(explainOptions?: firestore.ExplainOptions): Promise>>; isEqual(other: firestore.VectorQuery): boolean; get query(): Query; // Warning: (tsdoc-undefined-tag) The TSDoc tag "@private" is not defined in this configuration @@ -1475,7 +1486,17 @@ export class VectorQuery; + vectorField: string | firestore.FieldPath; } // @public @@ -1559,6 +1580,8 @@ export class WriteBatch implements firestore.WriteBatch { // Warning: (tsdoc-escape-right-brace) The "}" character should be escaped using a backslash to avoid confusion with a TSDoc inline tag // Warning: (tsdoc-malformed-inline-tag) Expecting a TSDoc tag starting with "{@" delete(documentRef: firestore.DocumentReference, precondition?: firestore.Precondition): WriteBatch; + // (undocumented) + protected readonly _firestore: Firestore; // Warning: (tsdoc-undefined-tag) The TSDoc tag "@private" is not defined in this configuration // // @internal @@ -1609,81 +1632,82 @@ export class WriteResult implements firestore.WriteResult { // Warnings were encountered during analysis: // +// build/src/aggregate.d.ts:48:8 - (tsdoc-param-tag-missing-hyphen) The @param block should be followed by a parameter name and then a hyphen // build/src/aggregate.d.ts:49:8 - (tsdoc-param-tag-missing-hyphen) The @param block should be followed by a parameter name and then a hyphen -// build/src/aggregate.d.ts:50:8 - (tsdoc-param-tag-missing-hyphen) The @param block should be followed by a parameter name and then a hyphen -// build/src/bulk-writer.d.ts:50:4 - (tsdoc-undefined-tag) The TSDoc tag "@private" is not defined in this configuration -// build/src/bulk-writer.d.ts:84:4 - (tsdoc-undefined-tag) The TSDoc tag "@private" is not defined in this configuration -// build/src/bulk-writer.d.ts:147:8 - (tsdoc-undefined-tag) The TSDoc tag "@private" is not defined in this configuration -// build/src/bulk-writer.d.ts:154:8 - (tsdoc-undefined-tag) The TSDoc tag "@private" is not defined in this configuration -// build/src/bulk-writer.d.ts:161:8 - (tsdoc-undefined-tag) The TSDoc tag "@private" is not defined in this configuration -// build/src/bulk-writer.d.ts:169:8 - (tsdoc-undefined-tag) The TSDoc tag "@private" is not defined in this configuration -// build/src/bulk-writer.d.ts:184:8 - (tsdoc-undefined-tag) The TSDoc tag "@private" is not defined in this configuration -// build/src/bulk-writer.d.ts:191:8 - (tsdoc-undefined-tag) The TSDoc tag "@private" is not defined in this configuration -// build/src/bulk-writer.d.ts:200:8 - (tsdoc-undefined-tag) The TSDoc tag "@private" is not defined in this configuration -// build/src/bulk-writer.d.ts:218:8 - (tsdoc-undefined-tag) The TSDoc tag "@private" is not defined in this configuration -// build/src/bulk-writer.d.ts:230:8 - (tsdoc-undefined-tag) The TSDoc tag "@private" is not defined in this configuration -// build/src/bulk-writer.d.ts:237:8 - (tsdoc-undefined-tag) The TSDoc tag "@private" is not defined in this configuration -// build/src/bulk-writer.d.ts:488:8 - (tsdoc-param-tag-missing-hyphen) The @param block should be followed by a parameter name and then a hyphen -// build/src/bulk-writer.d.ts:491:8 - (tsdoc-undefined-tag) The TSDoc tag "@private" is not defined in this configuration -// build/src/bulk-writer.d.ts:497:8 - (tsdoc-undefined-tag) The TSDoc tag "@private" is not defined in this configuration -// build/src/bulk-writer.d.ts:504:8 - (tsdoc-undefined-tag) The TSDoc tag "@private" is not defined in this configuration -// build/src/bulk-writer.d.ts:510:8 - (tsdoc-undefined-tag) The TSDoc tag "@private" is not defined in this configuration -// build/src/bulk-writer.d.ts:517:8 - (tsdoc-undefined-tag) The TSDoc tag "@private" is not defined in this configuration -// build/src/bundle.d.ts:20:8 - (tsdoc-undefined-tag) The TSDoc tag "@private" is not defined in this configuration -// build/src/filter.d.ts:121:4 - (tsdoc-undefined-tag) The TSDoc tag "@private" is not defined in this configuration -// build/src/filter.d.ts:156:4 - (tsdoc-undefined-tag) The TSDoc tag "@private" is not defined in this configuration +// build/src/bulk-writer.d.ts:49:4 - (tsdoc-undefined-tag) The TSDoc tag "@private" is not defined in this configuration +// build/src/bulk-writer.d.ts:83:4 - (tsdoc-undefined-tag) The TSDoc tag "@private" is not defined in this configuration +// build/src/bulk-writer.d.ts:146:8 - (tsdoc-undefined-tag) The TSDoc tag "@private" is not defined in this configuration +// build/src/bulk-writer.d.ts:153:8 - (tsdoc-undefined-tag) The TSDoc tag "@private" is not defined in this configuration +// build/src/bulk-writer.d.ts:160:8 - (tsdoc-undefined-tag) The TSDoc tag "@private" is not defined in this configuration +// build/src/bulk-writer.d.ts:168:8 - (tsdoc-undefined-tag) The TSDoc tag "@private" is not defined in this configuration +// build/src/bulk-writer.d.ts:183:8 - (tsdoc-undefined-tag) The TSDoc tag "@private" is not defined in this configuration +// build/src/bulk-writer.d.ts:190:8 - (tsdoc-undefined-tag) The TSDoc tag "@private" is not defined in this configuration +// build/src/bulk-writer.d.ts:199:8 - (tsdoc-undefined-tag) The TSDoc tag "@private" is not defined in this configuration +// build/src/bulk-writer.d.ts:217:8 - (tsdoc-undefined-tag) The TSDoc tag "@private" is not defined in this configuration +// build/src/bulk-writer.d.ts:229:8 - (tsdoc-undefined-tag) The TSDoc tag "@private" is not defined in this configuration +// build/src/bulk-writer.d.ts:236:8 - (tsdoc-undefined-tag) The TSDoc tag "@private" is not defined in this configuration +// build/src/bulk-writer.d.ts:487:8 - (tsdoc-param-tag-missing-hyphen) The @param block should be followed by a parameter name and then a hyphen +// build/src/bulk-writer.d.ts:490:8 - (tsdoc-undefined-tag) The TSDoc tag "@private" is not defined in this configuration +// build/src/bulk-writer.d.ts:496:8 - (tsdoc-undefined-tag) The TSDoc tag "@private" is not defined in this configuration +// build/src/bulk-writer.d.ts:503:8 - (tsdoc-undefined-tag) The TSDoc tag "@private" is not defined in this configuration +// build/src/bulk-writer.d.ts:509:8 - (tsdoc-undefined-tag) The TSDoc tag "@private" is not defined in this configuration +// build/src/bulk-writer.d.ts:516:8 - (tsdoc-undefined-tag) The TSDoc tag "@private" is not defined in this configuration +// build/src/bundle.d.ts:19:8 - (tsdoc-undefined-tag) The TSDoc tag "@private" is not defined in this configuration +// build/src/filter.d.ts:120:4 - (tsdoc-undefined-tag) The TSDoc tag "@private" is not defined in this configuration +// build/src/filter.d.ts:155:4 - (tsdoc-undefined-tag) The TSDoc tag "@private" is not defined in this configuration // build/src/index.d.ts:292:8 - (tsdoc-undefined-tag) The TSDoc tag "@private" is not defined in this configuration // build/src/index.d.ts:312:8 - (tsdoc-undefined-tag) The TSDoc tag "@private" is not defined in this configuration // build/src/index.d.ts:319:8 - (tsdoc-undefined-tag) The TSDoc tag "@private" is not defined in this configuration -// build/src/index.d.ts:334:8 - (tsdoc-undefined-tag) The TSDoc tag "@private" is not defined in this configuration -// build/src/index.d.ts:341:8 - (tsdoc-undefined-tag) The TSDoc tag "@private" is not defined in this configuration -// build/src/index.d.ts:350:8 - (tsdoc-undefined-tag) The TSDoc tag "@private" is not defined in this configuration -// build/src/index.d.ts:358:8 - (tsdoc-undefined-tag) The TSDoc tag "@private" is not defined in this configuration -// build/src/index.d.ts:365:8 - (tsdoc-undefined-tag) The TSDoc tag "@private" is not defined in this configuration -// build/src/index.d.ts:374:8 - (tsdoc-undefined-tag) The TSDoc tag "@private" is not defined in this configuration -// build/src/index.d.ts:857:8 - (tsdoc-undefined-tag) The TSDoc tag "@private" is not defined in this configuration -// build/src/index.d.ts:876:8 - (tsdoc-undefined-tag) The TSDoc tag "@private" is not defined in this configuration -// build/src/index.d.ts:878:8 - (tsdoc-param-tag-missing-hyphen) The @param block should be followed by a parameter name and then a hyphen -// build/src/index.d.ts:880:8 - (tsdoc-param-tag-missing-hyphen) The @param block should be followed by a parameter name and then a hyphen -// build/src/index.d.ts:881:8 - (tsdoc-param-tag-missing-hyphen) The @param block should be followed by a parameter name and then a hyphen -// build/src/index.d.ts:891:8 - (tsdoc-undefined-tag) The TSDoc tag "@private" is not defined in this configuration -// build/src/index.d.ts:893:8 - (tsdoc-param-tag-missing-hyphen) The @param block should be followed by a parameter name and then a hyphen -// build/src/index.d.ts:894:8 - (tsdoc-param-tag-missing-hyphen) The @param block should be followed by a parameter name and then a hyphen -// build/src/index.d.ts:896:8 - (tsdoc-param-tag-missing-hyphen) The @param block should be followed by a parameter name and then a hyphen -// build/src/index.d.ts:897:8 - (tsdoc-param-tag-missing-hyphen) The @param block should be followed by a parameter name and then a hyphen -// build/src/path.d.ts:30:4 - (tsdoc-undefined-tag) The TSDoc tag "@private" is not defined in this configuration -// build/src/path.d.ts:32:4 - (tsdoc-undefined-tag) The TSDoc tag "@class" is not defined in this configuration -// build/src/path.d.ts:120:4 - (tsdoc-undefined-tag) The TSDoc tag "@private" is not defined in this configuration -// build/src/path.d.ts:312:8 - (tsdoc-undefined-tag) The TSDoc tag "@private" is not defined in this configuration +// build/src/index.d.ts:340:8 - (tsdoc-undefined-tag) The TSDoc tag "@private" is not defined in this configuration +// build/src/index.d.ts:347:8 - (tsdoc-undefined-tag) The TSDoc tag "@private" is not defined in this configuration +// build/src/index.d.ts:356:8 - (tsdoc-undefined-tag) The TSDoc tag "@private" is not defined in this configuration +// build/src/index.d.ts:364:8 - (tsdoc-undefined-tag) The TSDoc tag "@private" is not defined in this configuration +// build/src/index.d.ts:371:8 - (tsdoc-undefined-tag) The TSDoc tag "@private" is not defined in this configuration +// build/src/index.d.ts:380:8 - (tsdoc-undefined-tag) The TSDoc tag "@private" is not defined in this configuration +// build/src/index.d.ts:864:8 - (tsdoc-undefined-tag) The TSDoc tag "@private" is not defined in this configuration +// build/src/index.d.ts:883:8 - (tsdoc-undefined-tag) The TSDoc tag "@private" is not defined in this configuration +// build/src/index.d.ts:885:8 - (tsdoc-param-tag-missing-hyphen) The @param block should be followed by a parameter name and then a hyphen +// build/src/index.d.ts:887:8 - (tsdoc-param-tag-missing-hyphen) The @param block should be followed by a parameter name and then a hyphen +// build/src/index.d.ts:888:8 - (tsdoc-param-tag-missing-hyphen) The @param block should be followed by a parameter name and then a hyphen +// build/src/index.d.ts:898:8 - (tsdoc-undefined-tag) The TSDoc tag "@private" is not defined in this configuration +// build/src/index.d.ts:900:8 - (tsdoc-param-tag-missing-hyphen) The @param block should be followed by a parameter name and then a hyphen +// build/src/index.d.ts:901:8 - (tsdoc-param-tag-missing-hyphen) The @param block should be followed by a parameter name and then a hyphen +// build/src/index.d.ts:903:8 - (tsdoc-param-tag-missing-hyphen) The @param block should be followed by a parameter name and then a hyphen +// build/src/index.d.ts:904:8 - (tsdoc-param-tag-missing-hyphen) The @param block should be followed by a parameter name and then a hyphen +// build/src/path.d.ts:29:4 - (tsdoc-undefined-tag) The TSDoc tag "@private" is not defined in this configuration +// build/src/path.d.ts:31:4 - (tsdoc-undefined-tag) The TSDoc tag "@class" is not defined in this configuration +// build/src/path.d.ts:119:4 - (tsdoc-undefined-tag) The TSDoc tag "@private" is not defined in this configuration +// build/src/path.d.ts:311:8 - (tsdoc-undefined-tag) The TSDoc tag "@private" is not defined in this configuration // build/src/rate-limiter.d.ts:13:4 - (tsdoc-undefined-tag) The TSDoc tag "@private" is not defined in this configuration -// build/src/reference/aggregate-query.d.ts:87:8 - (tsdoc-undefined-tag) The TSDoc tag "@private" is not defined in this configuration +// build/src/reference/aggregate-query.d.ts:85:8 - (tsdoc-undefined-tag) The TSDoc tag "@private" is not defined in this configuration // build/src/reference/field-filter-internal.d.ts:24:4 - (tsdoc-undefined-tag) The TSDoc tag "@private" is not defined in this configuration // build/src/reference/field-filter-internal.d.ts:26:4 - (tsdoc-undefined-tag) The TSDoc tag "@class" is not defined in this configuration // build/src/reference/field-order.d.ts:22:4 - (tsdoc-undefined-tag) The TSDoc tag "@private" is not defined in this configuration // build/src/reference/field-order.d.ts:24:4 - (tsdoc-undefined-tag) The TSDoc tag "@class" is not defined in this configuration -// build/src/reference/query-options.d.ts:28:4 - (tsdoc-undefined-tag) The TSDoc tag "@private" is not defined in this configuration -// build/src/reference/query.d.ts:393:8 - (tsdoc-undefined-tag) The TSDoc tag "@return" is not defined in this configuration -// build/src/reference/query.d.ts:399:8 - (tsdoc-undefined-tag) The TSDoc tag "@private" is not defined in this configuration -// build/src/reference/query.d.ts:401:8 - (tsdoc-param-tag-missing-hyphen) The @param block should be followed by a parameter name and then a hyphen -// build/src/reference/query.d.ts:409:8 - (tsdoc-undefined-tag) The TSDoc tag "@private" is not defined in this configuration -// build/src/reference/query.d.ts:411:8 - (tsdoc-param-tag-missing-hyphen) The @param block should be followed by a parameter name and then a hyphen -// build/src/reference/query.d.ts:411:15 - (tsdoc-param-tag-with-invalid-type) The @param block should not include a JSDoc-style '{type}' -// build/src/reference/query.d.ts:413:8 - (tsdoc-param-tag-missing-hyphen) The @param block should be followed by a parameter name and then a hyphen -// build/src/reference/query.d.ts:413:15 - (tsdoc-param-tag-with-invalid-type) The @param block should not include a JSDoc-style '{type}' -// build/src/reference/query.d.ts:415:8 - (tsdoc-param-tag-missing-hyphen) The @param block should be followed by a parameter name and then a hyphen -// build/src/reference/query.d.ts:417:24 - (tsdoc-escape-right-brace) The "}" character should be escaped using a backslash to avoid confusion with a TSDoc inline tag -// build/src/reference/query.d.ts:417:17 - (tsdoc-malformed-inline-tag) Expecting a TSDoc tag starting with "{@" -// build/src/reference/query.d.ts:426:8 - (tsdoc-param-tag-missing-hyphen) The @param block should be followed by a parameter name and then a hyphen -// build/src/reference/query.d.ts:428:8 - (tsdoc-undefined-tag) The TSDoc tag "@return" is not defined in this configuration -// build/src/reference/query.d.ts:430:8 - (tsdoc-undefined-tag) The TSDoc tag "@private" is not defined in this configuration -// build/src/reference/query.d.ts:616:8 - (tsdoc-param-tag-missing-hyphen) The @param block should be followed by a parameter name and then a hyphen -// build/src/reference/query.d.ts:617:8 - (tsdoc-undefined-tag) The TSDoc tag "@private" is not defined in this configuration -// build/src/reference/vector-query.d.ts:52:8 - (tsdoc-undefined-tag) The TSDoc tag "@private" is not defined in this configuration -// build/src/reference/vector-query.d.ts:57:8 - (tsdoc-undefined-tag) The TSDoc tag "@private" is not defined in this configuration -// build/src/serializer.d.ts:26:4 - (tsdoc-undefined-tag) The TSDoc tag "@private" is not defined in this configuration -// build/src/serializer.d.ts:36:4 - (tsdoc-undefined-tag) The TSDoc tag "@private" is not defined in this configuration -// build/src/write-batch.d.ts:86:8 - (tsdoc-undefined-tag) The TSDoc tag "@private" is not defined in this configuration -// build/src/write-batch.d.ts:109:8 - (tsdoc-undefined-tag) The TSDoc tag "@private" is not defined in this configuration +// build/src/reference/query-options.d.ts:27:4 - (tsdoc-undefined-tag) The TSDoc tag "@private" is not defined in this configuration +// build/src/reference/query.d.ts:425:8 - (tsdoc-undefined-tag) The TSDoc tag "@return" is not defined in this configuration +// build/src/reference/query.d.ts:431:8 - (tsdoc-undefined-tag) The TSDoc tag "@private" is not defined in this configuration +// build/src/reference/query.d.ts:433:8 - (tsdoc-param-tag-missing-hyphen) The @param block should be followed by a parameter name and then a hyphen +// build/src/reference/query.d.ts:441:8 - (tsdoc-undefined-tag) The TSDoc tag "@private" is not defined in this configuration +// build/src/reference/query.d.ts:443:8 - (tsdoc-param-tag-missing-hyphen) The @param block should be followed by a parameter name and then a hyphen +// build/src/reference/query.d.ts:443:15 - (tsdoc-param-tag-with-invalid-type) The @param block should not include a JSDoc-style '{type}' +// build/src/reference/query.d.ts:445:8 - (tsdoc-param-tag-missing-hyphen) The @param block should be followed by a parameter name and then a hyphen +// build/src/reference/query.d.ts:445:15 - (tsdoc-param-tag-with-invalid-type) The @param block should not include a JSDoc-style '{type}' +// build/src/reference/query.d.ts:447:8 - (tsdoc-param-tag-missing-hyphen) The @param block should be followed by a parameter name and then a hyphen +// build/src/reference/query.d.ts:449:24 - (tsdoc-escape-right-brace) The "}" character should be escaped using a backslash to avoid confusion with a TSDoc inline tag +// build/src/reference/query.d.ts:449:17 - (tsdoc-malformed-inline-tag) Expecting a TSDoc tag starting with "{@" +// build/src/reference/query.d.ts:458:8 - (tsdoc-param-tag-missing-hyphen) The @param block should be followed by a parameter name and then a hyphen +// build/src/reference/query.d.ts:460:8 - (tsdoc-undefined-tag) The TSDoc tag "@return" is not defined in this configuration +// build/src/reference/query.d.ts:462:8 - (tsdoc-undefined-tag) The TSDoc tag "@private" is not defined in this configuration +// build/src/reference/query.d.ts:648:8 - (tsdoc-param-tag-missing-hyphen) The @param block should be followed by a parameter name and then a hyphen +// build/src/reference/query.d.ts:649:8 - (tsdoc-undefined-tag) The TSDoc tag "@private" is not defined in this configuration +// build/src/reference/vector-query.d.ts:50:8 - (tsdoc-undefined-tag) The TSDoc tag "@private" is not defined in this configuration +// build/src/reference/vector-query.d.ts:55:8 - (tsdoc-undefined-tag) The TSDoc tag "@private" is not defined in this configuration +// build/src/reference/vector-query.d.ts:60:8 - (tsdoc-undefined-tag) The TSDoc tag "@private" is not defined in this configuration +// build/src/serializer.d.ts:25:4 - (tsdoc-undefined-tag) The TSDoc tag "@private" is not defined in this configuration +// build/src/serializer.d.ts:35:4 - (tsdoc-undefined-tag) The TSDoc tag "@private" is not defined in this configuration +// build/src/write-batch.d.ts:85:8 - (tsdoc-undefined-tag) The TSDoc tag "@private" is not defined in this configuration +// build/src/write-batch.d.ts:108:8 - (tsdoc-undefined-tag) The TSDoc tag "@private" is not defined in this configuration // (No @packageDocumentation comment for this package) diff --git a/dev/conformance/runner.ts b/dev/conformance/runner.ts index 82a117809..b660b0d2f 100644 --- a/dev/conformance/runner.ts +++ b/dev/conformance/runner.ts @@ -524,14 +524,14 @@ function runTest(spec: ConformanceProto) { * as strings to a proper protobuf type since protobufJS does not support it at * the moment. */ -function normalizeTimestamp(obj: {[key: string]: {}}) { +function normalizeTimestamp(obj: Record) { const fieldNames = ['updateTime', 'createTime', 'readTime']; for (const key of Object.keys(obj)) { if (fieldNames.includes(key) && typeof obj[key] === 'string') { obj[key] = convertTimestamp(obj[key] as string); } else if (typeof obj[key] === 'object') { // @ts-ignore - normalizeTimestamp(obj[key]); + normalizeTimestamp(obj[key] as Record); } } } @@ -564,7 +564,7 @@ function convertTimestamp(text: string): {[key: string]: number} { * Value type, but the 'limit' field in 'query' has Int32Value type, resulting * in the need for an extra layer of specificity. */ -function normalizeInt32Value(obj: {[key: string]: {}}, parent = '') { +function normalizeInt32Value(obj: Record, parent = '') { const fieldNames = ['limit']; const parentNames = ['query']; for (const key of Object.keys(obj)) { @@ -578,7 +578,7 @@ function normalizeInt32Value(obj: {[key: string]: {}}, parent = '') { }; } else if (typeof obj[key] === 'object') { // @ts-ignore - normalizeInt32Value(obj[key], key); + normalizeInt32Value(obj[key] as Record, key); } } } diff --git a/dev/protos/admin_v1.json b/dev/protos/admin_v1.json index 1e62ed1e5..531dcec3a 100644 --- a/dev/protos/admin_v1.json +++ b/dev/protos/admin_v1.json @@ -633,6 +633,34 @@ } ] }, + "BulkDeleteDocuments": { + "requestType": "BulkDeleteDocumentsRequest", + "responseType": "google.longrunning.Operation", + "options": { + "(google.api.http).post": "/v1/{name=projects/*/databases/*}:bulkDeleteDocuments", + "(google.api.http).body": "*", + "(google.api.method_signature)": "name", + "(google.longrunning.operation_info).response_type": "BulkDeleteDocumentsResponse", + "(google.longrunning.operation_info).metadata_type": "BulkDeleteDocumentsMetadata" + }, + "parsedOptions": [ + { + "(google.api.http)": { + "post": "/v1/{name=projects/*/databases/*}:bulkDeleteDocuments", + "body": "*" + } + }, + { + "(google.api.method_signature)": "name" + }, + { + "(google.longrunning.operation_info)": { + "response_type": "BulkDeleteDocumentsResponse", + "metadata_type": "BulkDeleteDocumentsMetadata" + } + } + ] + }, "CreateDatabase": { "requestType": "CreateDatabaseRequest", "responseType": "google.longrunning.Operation", @@ -934,6 +962,10 @@ "(google.api.field_behavior)": "REQUIRED", "(google.api.resource_reference).child_type": "firestore.googleapis.com/Database" } + }, + "showDeleted": { + "type": "bool", + "id": 4 } } }, @@ -1308,6 +1340,37 @@ } } }, + "BulkDeleteDocumentsRequest": { + "fields": { + "name": { + "type": "string", + "id": 1, + "options": { + "(google.api.field_behavior)": "REQUIRED", + "(google.api.resource_reference).type": "firestore.googleapis.com/Database" + } + }, + "collectionIds": { + "rule": "repeated", + "type": "string", + "id": 2, + "options": { + "(google.api.field_behavior)": "OPTIONAL" + } + }, + "namespaceIds": { + "rule": "repeated", + "type": "string", + "id": 3, + "options": { + "(google.api.field_behavior)": "OPTIONAL" + } + } + } + }, + "BulkDeleteDocumentsResponse": { + "fields": {} + }, "GetBackupRequest": { "fields": { "name": { @@ -1570,6 +1633,44 @@ } } }, + "BulkDeleteDocumentsMetadata": { + "fields": { + "startTime": { + "type": "google.protobuf.Timestamp", + "id": 1 + }, + "endTime": { + "type": "google.protobuf.Timestamp", + "id": 2 + }, + "operationState": { + "type": "OperationState", + "id": 3 + }, + "progressDocuments": { + "type": "Progress", + "id": 4 + }, + "progressBytes": { + "type": "Progress", + "id": 5 + }, + "collectionIds": { + "rule": "repeated", + "type": "string", + "id": 6 + }, + "namespaceIds": { + "rule": "repeated", + "type": "string", + "id": 7 + }, + "snapshotTime": { + "type": "google.protobuf.Timestamp", + "id": 8 + } + } + }, "ExportDocumentsResponse": { "fields": { "outputUriPrefix": { @@ -2230,7 +2331,6 @@ "Edition": { "values": { "EDITION_UNKNOWN": 0, - "EDITION_LEGACY": 900, "EDITION_PROTO2": 998, "EDITION_PROTO3": 999, "EDITION_2023": 1000, @@ -2956,10 +3056,6 @@ "type": "FeatureSet", "id": 21 }, - "featureSupport": { - "type": "FeatureSupport", - "id": 22 - }, "uninterpretedOption": { "rule": "repeated", "type": "UninterpretedOption", @@ -3029,26 +3125,6 @@ "id": 2 } } - }, - "FeatureSupport": { - "fields": { - "editionIntroduced": { - "type": "Edition", - "id": 1 - }, - "editionDeprecated": { - "type": "Edition", - "id": 2 - }, - "deprecationWarning": { - "type": "string", - "id": 3 - }, - "editionRemoved": { - "type": "Edition", - "id": 4 - } - } } } }, @@ -3272,7 +3348,6 @@ "options": { "retention": "RETENTION_RUNTIME", "targets": "TARGET_TYPE_FILE", - "feature_support.edition_introduced": "EDITION_2023", "edition_defaults.edition": "EDITION_2023", "edition_defaults.value": "EXPLICIT" } @@ -3283,7 +3358,6 @@ "options": { "retention": "RETENTION_RUNTIME", "targets": "TARGET_TYPE_FILE", - "feature_support.edition_introduced": "EDITION_2023", "edition_defaults.edition": "EDITION_PROTO3", "edition_defaults.value": "OPEN" } @@ -3294,7 +3368,6 @@ "options": { "retention": "RETENTION_RUNTIME", "targets": "TARGET_TYPE_FILE", - "feature_support.edition_introduced": "EDITION_2023", "edition_defaults.edition": "EDITION_PROTO3", "edition_defaults.value": "PACKED" } @@ -3305,7 +3378,6 @@ "options": { "retention": "RETENTION_RUNTIME", "targets": "TARGET_TYPE_FILE", - "feature_support.edition_introduced": "EDITION_2023", "edition_defaults.edition": "EDITION_PROTO3", "edition_defaults.value": "VERIFY" } @@ -3316,7 +3388,6 @@ "options": { "retention": "RETENTION_RUNTIME", "targets": "TARGET_TYPE_FILE", - "feature_support.edition_introduced": "EDITION_2023", "edition_defaults.edition": "EDITION_PROTO2", "edition_defaults.value": "LENGTH_PREFIXED" } @@ -3327,7 +3398,6 @@ "options": { "retention": "RETENTION_RUNTIME", "targets": "TARGET_TYPE_FILE", - "feature_support.edition_introduced": "EDITION_2023", "edition_defaults.edition": "EDITION_PROTO3", "edition_defaults.value": "ALLOW" } @@ -3336,7 +3406,15 @@ "extensions": [ [ 1000, - 9994 + 1000 + ], + [ + 1001, + 1001 + ], + [ + 1002, + 1002 ], [ 9995, @@ -3422,13 +3500,9 @@ "type": "Edition", "id": 3 }, - "overridableFeatures": { + "features": { "type": "FeatureSet", - "id": 4 - }, - "fixedFeatures": { - "type": "FeatureSet", - "id": 5 + "id": 2 } } } diff --git a/dev/protos/firestore_admin_v1_proto_api.d.ts b/dev/protos/firestore_admin_v1_proto_api.d.ts index 4e73f8002..a326cbb3b 100644 --- a/dev/protos/firestore_admin_v1_proto_api.d.ts +++ b/dev/protos/firestore_admin_v1_proto_api.d.ts @@ -918,6 +918,20 @@ export namespace google { */ public importDocuments(request: google.firestore.admin.v1.IImportDocumentsRequest): Promise; + /** + * Calls BulkDeleteDocuments. + * @param request BulkDeleteDocumentsRequest message or plain object + * @param callback Node-style callback called with the error, if any, and Operation + */ + public bulkDeleteDocuments(request: google.firestore.admin.v1.IBulkDeleteDocumentsRequest, callback: google.firestore.admin.v1.FirestoreAdmin.BulkDeleteDocumentsCallback): void; + + /** + * Calls BulkDeleteDocuments. + * @param request BulkDeleteDocumentsRequest message or plain object + * @returns Promise + */ + public bulkDeleteDocuments(request: google.firestore.admin.v1.IBulkDeleteDocumentsRequest): Promise; + /** * Calls CreateDatabase. * @param request CreateDatabaseRequest message or plain object @@ -1180,6 +1194,13 @@ export namespace google { */ type ImportDocumentsCallback = (error: (Error|null), response?: google.longrunning.Operation) => void; + /** + * Callback as used by {@link google.firestore.admin.v1.FirestoreAdmin#bulkDeleteDocuments}. + * @param error Error, if any + * @param [response] Operation + */ + type BulkDeleteDocumentsCallback = (error: (Error|null), response?: google.longrunning.Operation) => void; + /** * Callback as used by {@link google.firestore.admin.v1.FirestoreAdmin#createDatabase}. * @param error Error, if any @@ -1284,6 +1305,9 @@ export namespace google { /** ListDatabasesRequest parent */ parent?: (string|null); + + /** ListDatabasesRequest showDeleted */ + showDeleted?: (boolean|null); } /** Represents a ListDatabasesRequest. */ @@ -1298,6 +1322,9 @@ export namespace google { /** ListDatabasesRequest parent. */ public parent: string; + /** ListDatabasesRequest showDeleted. */ + public showDeleted: boolean; + /** * Creates a ListDatabasesRequest message from a plain object. Also converts values to their respective internal types. * @param object Plain object @@ -2653,6 +2680,108 @@ export namespace google { public static getTypeUrl(typeUrlPrefix?: string): string; } + /** Properties of a BulkDeleteDocumentsRequest. */ + interface IBulkDeleteDocumentsRequest { + + /** BulkDeleteDocumentsRequest name */ + name?: (string|null); + + /** BulkDeleteDocumentsRequest collectionIds */ + collectionIds?: (string[]|null); + + /** BulkDeleteDocumentsRequest namespaceIds */ + namespaceIds?: (string[]|null); + } + + /** Represents a BulkDeleteDocumentsRequest. */ + class BulkDeleteDocumentsRequest implements IBulkDeleteDocumentsRequest { + + /** + * Constructs a new BulkDeleteDocumentsRequest. + * @param [properties] Properties to set + */ + constructor(properties?: google.firestore.admin.v1.IBulkDeleteDocumentsRequest); + + /** BulkDeleteDocumentsRequest name. */ + public name: string; + + /** BulkDeleteDocumentsRequest collectionIds. */ + public collectionIds: string[]; + + /** BulkDeleteDocumentsRequest namespaceIds. */ + public namespaceIds: string[]; + + /** + * Creates a BulkDeleteDocumentsRequest message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns BulkDeleteDocumentsRequest + */ + public static fromObject(object: { [k: string]: any }): google.firestore.admin.v1.BulkDeleteDocumentsRequest; + + /** + * Creates a plain object from a BulkDeleteDocumentsRequest message. Also converts values to other types if specified. + * @param message BulkDeleteDocumentsRequest + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.firestore.admin.v1.BulkDeleteDocumentsRequest, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this BulkDeleteDocumentsRequest to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for BulkDeleteDocumentsRequest + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a BulkDeleteDocumentsResponse. */ + interface IBulkDeleteDocumentsResponse { + } + + /** Represents a BulkDeleteDocumentsResponse. */ + class BulkDeleteDocumentsResponse implements IBulkDeleteDocumentsResponse { + + /** + * Constructs a new BulkDeleteDocumentsResponse. + * @param [properties] Properties to set + */ + constructor(properties?: google.firestore.admin.v1.IBulkDeleteDocumentsResponse); + + /** + * Creates a BulkDeleteDocumentsResponse message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns BulkDeleteDocumentsResponse + */ + public static fromObject(object: { [k: string]: any }): google.firestore.admin.v1.BulkDeleteDocumentsResponse; + + /** + * Creates a plain object from a BulkDeleteDocumentsResponse message. Also converts values to other types if specified. + * @param message BulkDeleteDocumentsResponse + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.firestore.admin.v1.BulkDeleteDocumentsResponse, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this BulkDeleteDocumentsResponse to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for BulkDeleteDocumentsResponse + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + /** Properties of a GetBackupRequest. */ interface IGetBackupRequest { @@ -3384,6 +3513,96 @@ export namespace google { public static getTypeUrl(typeUrlPrefix?: string): string; } + /** Properties of a BulkDeleteDocumentsMetadata. */ + interface IBulkDeleteDocumentsMetadata { + + /** BulkDeleteDocumentsMetadata startTime */ + startTime?: (google.protobuf.ITimestamp|null); + + /** BulkDeleteDocumentsMetadata endTime */ + endTime?: (google.protobuf.ITimestamp|null); + + /** BulkDeleteDocumentsMetadata operationState */ + operationState?: (google.firestore.admin.v1.OperationState|null); + + /** BulkDeleteDocumentsMetadata progressDocuments */ + progressDocuments?: (google.firestore.admin.v1.IProgress|null); + + /** BulkDeleteDocumentsMetadata progressBytes */ + progressBytes?: (google.firestore.admin.v1.IProgress|null); + + /** BulkDeleteDocumentsMetadata collectionIds */ + collectionIds?: (string[]|null); + + /** BulkDeleteDocumentsMetadata namespaceIds */ + namespaceIds?: (string[]|null); + + /** BulkDeleteDocumentsMetadata snapshotTime */ + snapshotTime?: (google.protobuf.ITimestamp|null); + } + + /** Represents a BulkDeleteDocumentsMetadata. */ + class BulkDeleteDocumentsMetadata implements IBulkDeleteDocumentsMetadata { + + /** + * Constructs a new BulkDeleteDocumentsMetadata. + * @param [properties] Properties to set + */ + constructor(properties?: google.firestore.admin.v1.IBulkDeleteDocumentsMetadata); + + /** BulkDeleteDocumentsMetadata startTime. */ + public startTime?: (google.protobuf.ITimestamp|null); + + /** BulkDeleteDocumentsMetadata endTime. */ + public endTime?: (google.protobuf.ITimestamp|null); + + /** BulkDeleteDocumentsMetadata operationState. */ + public operationState: google.firestore.admin.v1.OperationState; + + /** BulkDeleteDocumentsMetadata progressDocuments. */ + public progressDocuments?: (google.firestore.admin.v1.IProgress|null); + + /** BulkDeleteDocumentsMetadata progressBytes. */ + public progressBytes?: (google.firestore.admin.v1.IProgress|null); + + /** BulkDeleteDocumentsMetadata collectionIds. */ + public collectionIds: string[]; + + /** BulkDeleteDocumentsMetadata namespaceIds. */ + public namespaceIds: string[]; + + /** BulkDeleteDocumentsMetadata snapshotTime. */ + public snapshotTime?: (google.protobuf.ITimestamp|null); + + /** + * Creates a BulkDeleteDocumentsMetadata message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns BulkDeleteDocumentsMetadata + */ + public static fromObject(object: { [k: string]: any }): google.firestore.admin.v1.BulkDeleteDocumentsMetadata; + + /** + * Creates a plain object from a BulkDeleteDocumentsMetadata message. Also converts values to other types if specified. + * @param message BulkDeleteDocumentsMetadata + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.firestore.admin.v1.BulkDeleteDocumentsMetadata, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this BulkDeleteDocumentsMetadata to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for BulkDeleteDocumentsMetadata + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + /** Properties of an ExportDocumentsResponse. */ interface IExportDocumentsResponse { @@ -5044,7 +5263,7 @@ export namespace google { /** Edition enum. */ type Edition = - "EDITION_UNKNOWN"| "EDITION_LEGACY"| "EDITION_PROTO2"| "EDITION_PROTO3"| "EDITION_2023"| "EDITION_2024"| "EDITION_1_TEST_ONLY"| "EDITION_2_TEST_ONLY"| "EDITION_99997_TEST_ONLY"| "EDITION_99998_TEST_ONLY"| "EDITION_99999_TEST_ONLY"| "EDITION_MAX"; + "EDITION_UNKNOWN"| "EDITION_PROTO2"| "EDITION_PROTO3"| "EDITION_2023"| "EDITION_2024"| "EDITION_1_TEST_ONLY"| "EDITION_2_TEST_ONLY"| "EDITION_99997_TEST_ONLY"| "EDITION_99998_TEST_ONLY"| "EDITION_99999_TEST_ONLY"| "EDITION_MAX"; /** Properties of a FileDescriptorProto. */ interface IFileDescriptorProto { @@ -6334,9 +6553,6 @@ export namespace google { /** FieldOptions features */ features?: (google.protobuf.IFeatureSet|null); - /** FieldOptions featureSupport */ - featureSupport?: (google.protobuf.FieldOptions.IFeatureSupport|null); - /** FieldOptions uninterpretedOption */ uninterpretedOption?: (google.protobuf.IUninterpretedOption[]|null); @@ -6392,9 +6608,6 @@ export namespace google { /** FieldOptions features. */ public features?: (google.protobuf.IFeatureSet|null); - /** FieldOptions featureSupport. */ - public featureSupport?: (google.protobuf.FieldOptions.IFeatureSupport|null); - /** FieldOptions uninterpretedOption. */ public uninterpretedOption: google.protobuf.IUninterpretedOption[]; @@ -6498,72 +6711,6 @@ export namespace google { */ public static getTypeUrl(typeUrlPrefix?: string): string; } - - /** Properties of a FeatureSupport. */ - interface IFeatureSupport { - - /** FeatureSupport editionIntroduced */ - editionIntroduced?: (google.protobuf.Edition|null); - - /** FeatureSupport editionDeprecated */ - editionDeprecated?: (google.protobuf.Edition|null); - - /** FeatureSupport deprecationWarning */ - deprecationWarning?: (string|null); - - /** FeatureSupport editionRemoved */ - editionRemoved?: (google.protobuf.Edition|null); - } - - /** Represents a FeatureSupport. */ - class FeatureSupport implements IFeatureSupport { - - /** - * Constructs a new FeatureSupport. - * @param [properties] Properties to set - */ - constructor(properties?: google.protobuf.FieldOptions.IFeatureSupport); - - /** FeatureSupport editionIntroduced. */ - public editionIntroduced: google.protobuf.Edition; - - /** FeatureSupport editionDeprecated. */ - public editionDeprecated: google.protobuf.Edition; - - /** FeatureSupport deprecationWarning. */ - public deprecationWarning: string; - - /** FeatureSupport editionRemoved. */ - public editionRemoved: google.protobuf.Edition; - - /** - * Creates a FeatureSupport message from a plain object. Also converts values to their respective internal types. - * @param object Plain object - * @returns FeatureSupport - */ - public static fromObject(object: { [k: string]: any }): google.protobuf.FieldOptions.FeatureSupport; - - /** - * Creates a plain object from a FeatureSupport message. Also converts values to other types if specified. - * @param message FeatureSupport - * @param [options] Conversion options - * @returns Plain object - */ - public static toObject(message: google.protobuf.FieldOptions.FeatureSupport, options?: $protobuf.IConversionOptions): { [k: string]: any }; - - /** - * Converts this FeatureSupport to JSON. - * @returns JSON object - */ - public toJSON(): { [k: string]: any }; - - /** - * Gets the default type url for FeatureSupport - * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") - * @returns The default type url - */ - public static getTypeUrl(typeUrlPrefix?: string): string; - } } /** Properties of an OneofOptions. */ @@ -7223,11 +7370,8 @@ export namespace google { /** FeatureSetEditionDefault edition */ edition?: (google.protobuf.Edition|null); - /** FeatureSetEditionDefault overridableFeatures */ - overridableFeatures?: (google.protobuf.IFeatureSet|null); - - /** FeatureSetEditionDefault fixedFeatures */ - fixedFeatures?: (google.protobuf.IFeatureSet|null); + /** FeatureSetEditionDefault features */ + features?: (google.protobuf.IFeatureSet|null); } /** Represents a FeatureSetEditionDefault. */ @@ -7242,11 +7386,8 @@ export namespace google { /** FeatureSetEditionDefault edition. */ public edition: google.protobuf.Edition; - /** FeatureSetEditionDefault overridableFeatures. */ - public overridableFeatures?: (google.protobuf.IFeatureSet|null); - - /** FeatureSetEditionDefault fixedFeatures. */ - public fixedFeatures?: (google.protobuf.IFeatureSet|null); + /** FeatureSetEditionDefault features. */ + public features?: (google.protobuf.IFeatureSet|null); /** * Creates a FeatureSetEditionDefault message from a plain object. Also converts values to their respective internal types. diff --git a/dev/protos/firestore_admin_v1_proto_api.js b/dev/protos/firestore_admin_v1_proto_api.js index 5f2e03b07..1f923e0b4 100644 --- a/dev/protos/firestore_admin_v1_proto_api.js +++ b/dev/protos/firestore_admin_v1_proto_api.js @@ -2389,6 +2389,39 @@ * @variation 2 */ + /** + * Callback as used by {@link google.firestore.admin.v1.FirestoreAdmin#bulkDeleteDocuments}. + * @memberof google.firestore.admin.v1.FirestoreAdmin + * @typedef BulkDeleteDocumentsCallback + * @type {function} + * @param {Error|null} error Error, if any + * @param {google.longrunning.Operation} [response] Operation + */ + + /** + * Calls BulkDeleteDocuments. + * @function bulkDeleteDocuments + * @memberof google.firestore.admin.v1.FirestoreAdmin + * @instance + * @param {google.firestore.admin.v1.IBulkDeleteDocumentsRequest} request BulkDeleteDocumentsRequest message or plain object + * @param {google.firestore.admin.v1.FirestoreAdmin.BulkDeleteDocumentsCallback} callback Node-style callback called with the error, if any, and Operation + * @returns {undefined} + * @variation 1 + */ + Object.defineProperty(FirestoreAdmin.prototype.bulkDeleteDocuments = function bulkDeleteDocuments(request, callback) { + return this.rpcCall(bulkDeleteDocuments, $root.google.firestore.admin.v1.BulkDeleteDocumentsRequest, $root.google.longrunning.Operation, request, callback); + }, "name", { value: "BulkDeleteDocuments" }); + + /** + * Calls BulkDeleteDocuments. + * @function bulkDeleteDocuments + * @memberof google.firestore.admin.v1.FirestoreAdmin + * @instance + * @param {google.firestore.admin.v1.IBulkDeleteDocumentsRequest} request BulkDeleteDocumentsRequest message or plain object + * @returns {Promise} Promise + * @variation 2 + */ + /** * Callback as used by {@link google.firestore.admin.v1.FirestoreAdmin#createDatabase}. * @memberof google.firestore.admin.v1.FirestoreAdmin @@ -2861,6 +2894,7 @@ * @memberof google.firestore.admin.v1 * @interface IListDatabasesRequest * @property {string|null} [parent] ListDatabasesRequest parent + * @property {boolean|null} [showDeleted] ListDatabasesRequest showDeleted */ /** @@ -2886,6 +2920,14 @@ */ ListDatabasesRequest.prototype.parent = ""; + /** + * ListDatabasesRequest showDeleted. + * @member {boolean} showDeleted + * @memberof google.firestore.admin.v1.ListDatabasesRequest + * @instance + */ + ListDatabasesRequest.prototype.showDeleted = false; + /** * Creates a ListDatabasesRequest message from a plain object. Also converts values to their respective internal types. * @function fromObject @@ -2900,6 +2942,8 @@ var message = new $root.google.firestore.admin.v1.ListDatabasesRequest(); if (object.parent != null) message.parent = String(object.parent); + if (object.showDeleted != null) + message.showDeleted = Boolean(object.showDeleted); return message; }; @@ -2916,10 +2960,14 @@ if (!options) options = {}; var object = {}; - if (options.defaults) + if (options.defaults) { object.parent = ""; + object.showDeleted = false; + } if (message.parent != null && message.hasOwnProperty("parent")) object.parent = message.parent; + if (message.showDeleted != null && message.hasOwnProperty("showDeleted")) + object.showDeleted = message.showDeleted; return object; }; @@ -5822,6 +5870,231 @@ return ImportDocumentsRequest; })(); + v1.BulkDeleteDocumentsRequest = (function() { + + /** + * Properties of a BulkDeleteDocumentsRequest. + * @memberof google.firestore.admin.v1 + * @interface IBulkDeleteDocumentsRequest + * @property {string|null} [name] BulkDeleteDocumentsRequest name + * @property {Array.|null} [collectionIds] BulkDeleteDocumentsRequest collectionIds + * @property {Array.|null} [namespaceIds] BulkDeleteDocumentsRequest namespaceIds + */ + + /** + * Constructs a new BulkDeleteDocumentsRequest. + * @memberof google.firestore.admin.v1 + * @classdesc Represents a BulkDeleteDocumentsRequest. + * @implements IBulkDeleteDocumentsRequest + * @constructor + * @param {google.firestore.admin.v1.IBulkDeleteDocumentsRequest=} [properties] Properties to set + */ + function BulkDeleteDocumentsRequest(properties) { + this.collectionIds = []; + this.namespaceIds = []; + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } + + /** + * BulkDeleteDocumentsRequest name. + * @member {string} name + * @memberof google.firestore.admin.v1.BulkDeleteDocumentsRequest + * @instance + */ + BulkDeleteDocumentsRequest.prototype.name = ""; + + /** + * BulkDeleteDocumentsRequest collectionIds. + * @member {Array.} collectionIds + * @memberof google.firestore.admin.v1.BulkDeleteDocumentsRequest + * @instance + */ + BulkDeleteDocumentsRequest.prototype.collectionIds = $util.emptyArray; + + /** + * BulkDeleteDocumentsRequest namespaceIds. + * @member {Array.} namespaceIds + * @memberof google.firestore.admin.v1.BulkDeleteDocumentsRequest + * @instance + */ + BulkDeleteDocumentsRequest.prototype.namespaceIds = $util.emptyArray; + + /** + * Creates a BulkDeleteDocumentsRequest message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.firestore.admin.v1.BulkDeleteDocumentsRequest + * @static + * @param {Object.} object Plain object + * @returns {google.firestore.admin.v1.BulkDeleteDocumentsRequest} BulkDeleteDocumentsRequest + */ + BulkDeleteDocumentsRequest.fromObject = function fromObject(object) { + if (object instanceof $root.google.firestore.admin.v1.BulkDeleteDocumentsRequest) + return object; + var message = new $root.google.firestore.admin.v1.BulkDeleteDocumentsRequest(); + if (object.name != null) + message.name = String(object.name); + if (object.collectionIds) { + if (!Array.isArray(object.collectionIds)) + throw TypeError(".google.firestore.admin.v1.BulkDeleteDocumentsRequest.collectionIds: array expected"); + message.collectionIds = []; + for (var i = 0; i < object.collectionIds.length; ++i) + message.collectionIds[i] = String(object.collectionIds[i]); + } + if (object.namespaceIds) { + if (!Array.isArray(object.namespaceIds)) + throw TypeError(".google.firestore.admin.v1.BulkDeleteDocumentsRequest.namespaceIds: array expected"); + message.namespaceIds = []; + for (var i = 0; i < object.namespaceIds.length; ++i) + message.namespaceIds[i] = String(object.namespaceIds[i]); + } + return message; + }; + + /** + * Creates a plain object from a BulkDeleteDocumentsRequest message. Also converts values to other types if specified. + * @function toObject + * @memberof google.firestore.admin.v1.BulkDeleteDocumentsRequest + * @static + * @param {google.firestore.admin.v1.BulkDeleteDocumentsRequest} message BulkDeleteDocumentsRequest + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + BulkDeleteDocumentsRequest.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.arrays || options.defaults) { + object.collectionIds = []; + object.namespaceIds = []; + } + if (options.defaults) + object.name = ""; + if (message.name != null && message.hasOwnProperty("name")) + object.name = message.name; + if (message.collectionIds && message.collectionIds.length) { + object.collectionIds = []; + for (var j = 0; j < message.collectionIds.length; ++j) + object.collectionIds[j] = message.collectionIds[j]; + } + if (message.namespaceIds && message.namespaceIds.length) { + object.namespaceIds = []; + for (var j = 0; j < message.namespaceIds.length; ++j) + object.namespaceIds[j] = message.namespaceIds[j]; + } + return object; + }; + + /** + * Converts this BulkDeleteDocumentsRequest to JSON. + * @function toJSON + * @memberof google.firestore.admin.v1.BulkDeleteDocumentsRequest + * @instance + * @returns {Object.} JSON object + */ + BulkDeleteDocumentsRequest.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + + /** + * Gets the default type url for BulkDeleteDocumentsRequest + * @function getTypeUrl + * @memberof google.firestore.admin.v1.BulkDeleteDocumentsRequest + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + BulkDeleteDocumentsRequest.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.firestore.admin.v1.BulkDeleteDocumentsRequest"; + }; + + return BulkDeleteDocumentsRequest; + })(); + + v1.BulkDeleteDocumentsResponse = (function() { + + /** + * Properties of a BulkDeleteDocumentsResponse. + * @memberof google.firestore.admin.v1 + * @interface IBulkDeleteDocumentsResponse + */ + + /** + * Constructs a new BulkDeleteDocumentsResponse. + * @memberof google.firestore.admin.v1 + * @classdesc Represents a BulkDeleteDocumentsResponse. + * @implements IBulkDeleteDocumentsResponse + * @constructor + * @param {google.firestore.admin.v1.IBulkDeleteDocumentsResponse=} [properties] Properties to set + */ + function BulkDeleteDocumentsResponse(properties) { + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } + + /** + * Creates a BulkDeleteDocumentsResponse message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.firestore.admin.v1.BulkDeleteDocumentsResponse + * @static + * @param {Object.} object Plain object + * @returns {google.firestore.admin.v1.BulkDeleteDocumentsResponse} BulkDeleteDocumentsResponse + */ + BulkDeleteDocumentsResponse.fromObject = function fromObject(object) { + if (object instanceof $root.google.firestore.admin.v1.BulkDeleteDocumentsResponse) + return object; + return new $root.google.firestore.admin.v1.BulkDeleteDocumentsResponse(); + }; + + /** + * Creates a plain object from a BulkDeleteDocumentsResponse message. Also converts values to other types if specified. + * @function toObject + * @memberof google.firestore.admin.v1.BulkDeleteDocumentsResponse + * @static + * @param {google.firestore.admin.v1.BulkDeleteDocumentsResponse} message BulkDeleteDocumentsResponse + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + BulkDeleteDocumentsResponse.toObject = function toObject() { + return {}; + }; + + /** + * Converts this BulkDeleteDocumentsResponse to JSON. + * @function toJSON + * @memberof google.firestore.admin.v1.BulkDeleteDocumentsResponse + * @instance + * @returns {Object.} JSON object + */ + BulkDeleteDocumentsResponse.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + + /** + * Gets the default type url for BulkDeleteDocumentsResponse + * @function getTypeUrl + * @memberof google.firestore.admin.v1.BulkDeleteDocumentsResponse + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + BulkDeleteDocumentsResponse.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.firestore.admin.v1.BulkDeleteDocumentsResponse"; + }; + + return BulkDeleteDocumentsResponse; + })(); + v1.GetBackupRequest = (function() { /** @@ -7504,44 +7777,311 @@ * @memberof google.firestore.admin.v1.ImportDocumentsMetadata * @instance */ - ImportDocumentsMetadata.prototype.collectionIds = $util.emptyArray; + ImportDocumentsMetadata.prototype.collectionIds = $util.emptyArray; + + /** + * ImportDocumentsMetadata inputUriPrefix. + * @member {string} inputUriPrefix + * @memberof google.firestore.admin.v1.ImportDocumentsMetadata + * @instance + */ + ImportDocumentsMetadata.prototype.inputUriPrefix = ""; + + /** + * ImportDocumentsMetadata namespaceIds. + * @member {Array.} namespaceIds + * @memberof google.firestore.admin.v1.ImportDocumentsMetadata + * @instance + */ + ImportDocumentsMetadata.prototype.namespaceIds = $util.emptyArray; + + /** + * Creates an ImportDocumentsMetadata message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.firestore.admin.v1.ImportDocumentsMetadata + * @static + * @param {Object.} object Plain object + * @returns {google.firestore.admin.v1.ImportDocumentsMetadata} ImportDocumentsMetadata + */ + ImportDocumentsMetadata.fromObject = function fromObject(object) { + if (object instanceof $root.google.firestore.admin.v1.ImportDocumentsMetadata) + return object; + var message = new $root.google.firestore.admin.v1.ImportDocumentsMetadata(); + if (object.startTime != null) { + if (typeof object.startTime !== "object") + throw TypeError(".google.firestore.admin.v1.ImportDocumentsMetadata.startTime: object expected"); + message.startTime = $root.google.protobuf.Timestamp.fromObject(object.startTime); + } + if (object.endTime != null) { + if (typeof object.endTime !== "object") + throw TypeError(".google.firestore.admin.v1.ImportDocumentsMetadata.endTime: object expected"); + message.endTime = $root.google.protobuf.Timestamp.fromObject(object.endTime); + } + switch (object.operationState) { + default: + if (typeof object.operationState === "number") { + message.operationState = object.operationState; + break; + } + break; + case "OPERATION_STATE_UNSPECIFIED": + case 0: + message.operationState = 0; + break; + case "INITIALIZING": + case 1: + message.operationState = 1; + break; + case "PROCESSING": + case 2: + message.operationState = 2; + break; + case "CANCELLING": + case 3: + message.operationState = 3; + break; + case "FINALIZING": + case 4: + message.operationState = 4; + break; + case "SUCCESSFUL": + case 5: + message.operationState = 5; + break; + case "FAILED": + case 6: + message.operationState = 6; + break; + case "CANCELLED": + case 7: + message.operationState = 7; + break; + } + if (object.progressDocuments != null) { + if (typeof object.progressDocuments !== "object") + throw TypeError(".google.firestore.admin.v1.ImportDocumentsMetadata.progressDocuments: object expected"); + message.progressDocuments = $root.google.firestore.admin.v1.Progress.fromObject(object.progressDocuments); + } + if (object.progressBytes != null) { + if (typeof object.progressBytes !== "object") + throw TypeError(".google.firestore.admin.v1.ImportDocumentsMetadata.progressBytes: object expected"); + message.progressBytes = $root.google.firestore.admin.v1.Progress.fromObject(object.progressBytes); + } + if (object.collectionIds) { + if (!Array.isArray(object.collectionIds)) + throw TypeError(".google.firestore.admin.v1.ImportDocumentsMetadata.collectionIds: array expected"); + message.collectionIds = []; + for (var i = 0; i < object.collectionIds.length; ++i) + message.collectionIds[i] = String(object.collectionIds[i]); + } + if (object.inputUriPrefix != null) + message.inputUriPrefix = String(object.inputUriPrefix); + if (object.namespaceIds) { + if (!Array.isArray(object.namespaceIds)) + throw TypeError(".google.firestore.admin.v1.ImportDocumentsMetadata.namespaceIds: array expected"); + message.namespaceIds = []; + for (var i = 0; i < object.namespaceIds.length; ++i) + message.namespaceIds[i] = String(object.namespaceIds[i]); + } + return message; + }; + + /** + * Creates a plain object from an ImportDocumentsMetadata message. Also converts values to other types if specified. + * @function toObject + * @memberof google.firestore.admin.v1.ImportDocumentsMetadata + * @static + * @param {google.firestore.admin.v1.ImportDocumentsMetadata} message ImportDocumentsMetadata + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + ImportDocumentsMetadata.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.arrays || options.defaults) { + object.collectionIds = []; + object.namespaceIds = []; + } + if (options.defaults) { + object.startTime = null; + object.endTime = null; + object.operationState = options.enums === String ? "OPERATION_STATE_UNSPECIFIED" : 0; + object.progressDocuments = null; + object.progressBytes = null; + object.inputUriPrefix = ""; + } + if (message.startTime != null && message.hasOwnProperty("startTime")) + object.startTime = $root.google.protobuf.Timestamp.toObject(message.startTime, options); + if (message.endTime != null && message.hasOwnProperty("endTime")) + object.endTime = $root.google.protobuf.Timestamp.toObject(message.endTime, options); + if (message.operationState != null && message.hasOwnProperty("operationState")) + object.operationState = options.enums === String ? $root.google.firestore.admin.v1.OperationState[message.operationState] === undefined ? message.operationState : $root.google.firestore.admin.v1.OperationState[message.operationState] : message.operationState; + if (message.progressDocuments != null && message.hasOwnProperty("progressDocuments")) + object.progressDocuments = $root.google.firestore.admin.v1.Progress.toObject(message.progressDocuments, options); + if (message.progressBytes != null && message.hasOwnProperty("progressBytes")) + object.progressBytes = $root.google.firestore.admin.v1.Progress.toObject(message.progressBytes, options); + if (message.collectionIds && message.collectionIds.length) { + object.collectionIds = []; + for (var j = 0; j < message.collectionIds.length; ++j) + object.collectionIds[j] = message.collectionIds[j]; + } + if (message.inputUriPrefix != null && message.hasOwnProperty("inputUriPrefix")) + object.inputUriPrefix = message.inputUriPrefix; + if (message.namespaceIds && message.namespaceIds.length) { + object.namespaceIds = []; + for (var j = 0; j < message.namespaceIds.length; ++j) + object.namespaceIds[j] = message.namespaceIds[j]; + } + return object; + }; + + /** + * Converts this ImportDocumentsMetadata to JSON. + * @function toJSON + * @memberof google.firestore.admin.v1.ImportDocumentsMetadata + * @instance + * @returns {Object.} JSON object + */ + ImportDocumentsMetadata.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + + /** + * Gets the default type url for ImportDocumentsMetadata + * @function getTypeUrl + * @memberof google.firestore.admin.v1.ImportDocumentsMetadata + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + ImportDocumentsMetadata.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.firestore.admin.v1.ImportDocumentsMetadata"; + }; + + return ImportDocumentsMetadata; + })(); + + v1.BulkDeleteDocumentsMetadata = (function() { + + /** + * Properties of a BulkDeleteDocumentsMetadata. + * @memberof google.firestore.admin.v1 + * @interface IBulkDeleteDocumentsMetadata + * @property {google.protobuf.ITimestamp|null} [startTime] BulkDeleteDocumentsMetadata startTime + * @property {google.protobuf.ITimestamp|null} [endTime] BulkDeleteDocumentsMetadata endTime + * @property {google.firestore.admin.v1.OperationState|null} [operationState] BulkDeleteDocumentsMetadata operationState + * @property {google.firestore.admin.v1.IProgress|null} [progressDocuments] BulkDeleteDocumentsMetadata progressDocuments + * @property {google.firestore.admin.v1.IProgress|null} [progressBytes] BulkDeleteDocumentsMetadata progressBytes + * @property {Array.|null} [collectionIds] BulkDeleteDocumentsMetadata collectionIds + * @property {Array.|null} [namespaceIds] BulkDeleteDocumentsMetadata namespaceIds + * @property {google.protobuf.ITimestamp|null} [snapshotTime] BulkDeleteDocumentsMetadata snapshotTime + */ + + /** + * Constructs a new BulkDeleteDocumentsMetadata. + * @memberof google.firestore.admin.v1 + * @classdesc Represents a BulkDeleteDocumentsMetadata. + * @implements IBulkDeleteDocumentsMetadata + * @constructor + * @param {google.firestore.admin.v1.IBulkDeleteDocumentsMetadata=} [properties] Properties to set + */ + function BulkDeleteDocumentsMetadata(properties) { + this.collectionIds = []; + this.namespaceIds = []; + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } + + /** + * BulkDeleteDocumentsMetadata startTime. + * @member {google.protobuf.ITimestamp|null|undefined} startTime + * @memberof google.firestore.admin.v1.BulkDeleteDocumentsMetadata + * @instance + */ + BulkDeleteDocumentsMetadata.prototype.startTime = null; + + /** + * BulkDeleteDocumentsMetadata endTime. + * @member {google.protobuf.ITimestamp|null|undefined} endTime + * @memberof google.firestore.admin.v1.BulkDeleteDocumentsMetadata + * @instance + */ + BulkDeleteDocumentsMetadata.prototype.endTime = null; + + /** + * BulkDeleteDocumentsMetadata operationState. + * @member {google.firestore.admin.v1.OperationState} operationState + * @memberof google.firestore.admin.v1.BulkDeleteDocumentsMetadata + * @instance + */ + BulkDeleteDocumentsMetadata.prototype.operationState = 0; + + /** + * BulkDeleteDocumentsMetadata progressDocuments. + * @member {google.firestore.admin.v1.IProgress|null|undefined} progressDocuments + * @memberof google.firestore.admin.v1.BulkDeleteDocumentsMetadata + * @instance + */ + BulkDeleteDocumentsMetadata.prototype.progressDocuments = null; + + /** + * BulkDeleteDocumentsMetadata progressBytes. + * @member {google.firestore.admin.v1.IProgress|null|undefined} progressBytes + * @memberof google.firestore.admin.v1.BulkDeleteDocumentsMetadata + * @instance + */ + BulkDeleteDocumentsMetadata.prototype.progressBytes = null; + + /** + * BulkDeleteDocumentsMetadata collectionIds. + * @member {Array.} collectionIds + * @memberof google.firestore.admin.v1.BulkDeleteDocumentsMetadata + * @instance + */ + BulkDeleteDocumentsMetadata.prototype.collectionIds = $util.emptyArray; /** - * ImportDocumentsMetadata inputUriPrefix. - * @member {string} inputUriPrefix - * @memberof google.firestore.admin.v1.ImportDocumentsMetadata + * BulkDeleteDocumentsMetadata namespaceIds. + * @member {Array.} namespaceIds + * @memberof google.firestore.admin.v1.BulkDeleteDocumentsMetadata * @instance */ - ImportDocumentsMetadata.prototype.inputUriPrefix = ""; + BulkDeleteDocumentsMetadata.prototype.namespaceIds = $util.emptyArray; /** - * ImportDocumentsMetadata namespaceIds. - * @member {Array.} namespaceIds - * @memberof google.firestore.admin.v1.ImportDocumentsMetadata + * BulkDeleteDocumentsMetadata snapshotTime. + * @member {google.protobuf.ITimestamp|null|undefined} snapshotTime + * @memberof google.firestore.admin.v1.BulkDeleteDocumentsMetadata * @instance */ - ImportDocumentsMetadata.prototype.namespaceIds = $util.emptyArray; + BulkDeleteDocumentsMetadata.prototype.snapshotTime = null; /** - * Creates an ImportDocumentsMetadata message from a plain object. Also converts values to their respective internal types. + * Creates a BulkDeleteDocumentsMetadata message from a plain object. Also converts values to their respective internal types. * @function fromObject - * @memberof google.firestore.admin.v1.ImportDocumentsMetadata + * @memberof google.firestore.admin.v1.BulkDeleteDocumentsMetadata * @static * @param {Object.} object Plain object - * @returns {google.firestore.admin.v1.ImportDocumentsMetadata} ImportDocumentsMetadata + * @returns {google.firestore.admin.v1.BulkDeleteDocumentsMetadata} BulkDeleteDocumentsMetadata */ - ImportDocumentsMetadata.fromObject = function fromObject(object) { - if (object instanceof $root.google.firestore.admin.v1.ImportDocumentsMetadata) + BulkDeleteDocumentsMetadata.fromObject = function fromObject(object) { + if (object instanceof $root.google.firestore.admin.v1.BulkDeleteDocumentsMetadata) return object; - var message = new $root.google.firestore.admin.v1.ImportDocumentsMetadata(); + var message = new $root.google.firestore.admin.v1.BulkDeleteDocumentsMetadata(); if (object.startTime != null) { if (typeof object.startTime !== "object") - throw TypeError(".google.firestore.admin.v1.ImportDocumentsMetadata.startTime: object expected"); + throw TypeError(".google.firestore.admin.v1.BulkDeleteDocumentsMetadata.startTime: object expected"); message.startTime = $root.google.protobuf.Timestamp.fromObject(object.startTime); } if (object.endTime != null) { if (typeof object.endTime !== "object") - throw TypeError(".google.firestore.admin.v1.ImportDocumentsMetadata.endTime: object expected"); + throw TypeError(".google.firestore.admin.v1.BulkDeleteDocumentsMetadata.endTime: object expected"); message.endTime = $root.google.protobuf.Timestamp.fromObject(object.endTime); } switch (object.operationState) { @@ -7586,43 +8126,46 @@ } if (object.progressDocuments != null) { if (typeof object.progressDocuments !== "object") - throw TypeError(".google.firestore.admin.v1.ImportDocumentsMetadata.progressDocuments: object expected"); + throw TypeError(".google.firestore.admin.v1.BulkDeleteDocumentsMetadata.progressDocuments: object expected"); message.progressDocuments = $root.google.firestore.admin.v1.Progress.fromObject(object.progressDocuments); } if (object.progressBytes != null) { if (typeof object.progressBytes !== "object") - throw TypeError(".google.firestore.admin.v1.ImportDocumentsMetadata.progressBytes: object expected"); + throw TypeError(".google.firestore.admin.v1.BulkDeleteDocumentsMetadata.progressBytes: object expected"); message.progressBytes = $root.google.firestore.admin.v1.Progress.fromObject(object.progressBytes); } if (object.collectionIds) { if (!Array.isArray(object.collectionIds)) - throw TypeError(".google.firestore.admin.v1.ImportDocumentsMetadata.collectionIds: array expected"); + throw TypeError(".google.firestore.admin.v1.BulkDeleteDocumentsMetadata.collectionIds: array expected"); message.collectionIds = []; for (var i = 0; i < object.collectionIds.length; ++i) message.collectionIds[i] = String(object.collectionIds[i]); } - if (object.inputUriPrefix != null) - message.inputUriPrefix = String(object.inputUriPrefix); if (object.namespaceIds) { if (!Array.isArray(object.namespaceIds)) - throw TypeError(".google.firestore.admin.v1.ImportDocumentsMetadata.namespaceIds: array expected"); + throw TypeError(".google.firestore.admin.v1.BulkDeleteDocumentsMetadata.namespaceIds: array expected"); message.namespaceIds = []; for (var i = 0; i < object.namespaceIds.length; ++i) message.namespaceIds[i] = String(object.namespaceIds[i]); } + if (object.snapshotTime != null) { + if (typeof object.snapshotTime !== "object") + throw TypeError(".google.firestore.admin.v1.BulkDeleteDocumentsMetadata.snapshotTime: object expected"); + message.snapshotTime = $root.google.protobuf.Timestamp.fromObject(object.snapshotTime); + } return message; }; /** - * Creates a plain object from an ImportDocumentsMetadata message. Also converts values to other types if specified. + * Creates a plain object from a BulkDeleteDocumentsMetadata message. Also converts values to other types if specified. * @function toObject - * @memberof google.firestore.admin.v1.ImportDocumentsMetadata + * @memberof google.firestore.admin.v1.BulkDeleteDocumentsMetadata * @static - * @param {google.firestore.admin.v1.ImportDocumentsMetadata} message ImportDocumentsMetadata + * @param {google.firestore.admin.v1.BulkDeleteDocumentsMetadata} message BulkDeleteDocumentsMetadata * @param {$protobuf.IConversionOptions} [options] Conversion options * @returns {Object.} Plain object */ - ImportDocumentsMetadata.toObject = function toObject(message, options) { + BulkDeleteDocumentsMetadata.toObject = function toObject(message, options) { if (!options) options = {}; var object = {}; @@ -7636,7 +8179,7 @@ object.operationState = options.enums === String ? "OPERATION_STATE_UNSPECIFIED" : 0; object.progressDocuments = null; object.progressBytes = null; - object.inputUriPrefix = ""; + object.snapshotTime = null; } if (message.startTime != null && message.hasOwnProperty("startTime")) object.startTime = $root.google.protobuf.Timestamp.toObject(message.startTime, options); @@ -7653,43 +8196,43 @@ for (var j = 0; j < message.collectionIds.length; ++j) object.collectionIds[j] = message.collectionIds[j]; } - if (message.inputUriPrefix != null && message.hasOwnProperty("inputUriPrefix")) - object.inputUriPrefix = message.inputUriPrefix; if (message.namespaceIds && message.namespaceIds.length) { object.namespaceIds = []; for (var j = 0; j < message.namespaceIds.length; ++j) object.namespaceIds[j] = message.namespaceIds[j]; } + if (message.snapshotTime != null && message.hasOwnProperty("snapshotTime")) + object.snapshotTime = $root.google.protobuf.Timestamp.toObject(message.snapshotTime, options); return object; }; /** - * Converts this ImportDocumentsMetadata to JSON. + * Converts this BulkDeleteDocumentsMetadata to JSON. * @function toJSON - * @memberof google.firestore.admin.v1.ImportDocumentsMetadata + * @memberof google.firestore.admin.v1.BulkDeleteDocumentsMetadata * @instance * @returns {Object.} JSON object */ - ImportDocumentsMetadata.prototype.toJSON = function toJSON() { + BulkDeleteDocumentsMetadata.prototype.toJSON = function toJSON() { return this.constructor.toObject(this, $protobuf.util.toJSONOptions); }; /** - * Gets the default type url for ImportDocumentsMetadata + * Gets the default type url for BulkDeleteDocumentsMetadata * @function getTypeUrl - * @memberof google.firestore.admin.v1.ImportDocumentsMetadata + * @memberof google.firestore.admin.v1.BulkDeleteDocumentsMetadata * @static * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") * @returns {string} The default type url */ - ImportDocumentsMetadata.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + BulkDeleteDocumentsMetadata.getTypeUrl = function getTypeUrl(typeUrlPrefix) { if (typeUrlPrefix === undefined) { typeUrlPrefix = "type.googleapis.com"; } - return typeUrlPrefix + "/google.firestore.admin.v1.ImportDocumentsMetadata"; + return typeUrlPrefix + "/google.firestore.admin.v1.BulkDeleteDocumentsMetadata"; }; - return ImportDocumentsMetadata; + return BulkDeleteDocumentsMetadata; })(); v1.ExportDocumentsResponse = (function() { @@ -11804,7 +12347,6 @@ * @name google.protobuf.Edition * @enum {string} * @property {string} EDITION_UNKNOWN=EDITION_UNKNOWN EDITION_UNKNOWN value - * @property {string} EDITION_LEGACY=EDITION_LEGACY EDITION_LEGACY value * @property {string} EDITION_PROTO2=EDITION_PROTO2 EDITION_PROTO2 value * @property {string} EDITION_PROTO3=EDITION_PROTO3 EDITION_PROTO3 value * @property {string} EDITION_2023=EDITION_2023 EDITION_2023 value @@ -11819,7 +12361,6 @@ protobuf.Edition = (function() { var valuesById = {}, values = Object.create(valuesById); values[valuesById[0] = "EDITION_UNKNOWN"] = "EDITION_UNKNOWN"; - values[valuesById[900] = "EDITION_LEGACY"] = "EDITION_LEGACY"; values[valuesById[998] = "EDITION_PROTO2"] = "EDITION_PROTO2"; values[valuesById[999] = "EDITION_PROTO3"] = "EDITION_PROTO3"; values[valuesById[1000] = "EDITION_2023"] = "EDITION_2023"; @@ -12080,10 +12621,6 @@ case 0: message.edition = 0; break; - case "EDITION_LEGACY": - case 900: - message.edition = 900; - break; case "EDITION_PROTO2": case 998: message.edition = 998; @@ -15113,7 +15650,6 @@ * @property {Array.|null} [targets] FieldOptions targets * @property {Array.|null} [editionDefaults] FieldOptions editionDefaults * @property {google.protobuf.IFeatureSet|null} [features] FieldOptions features - * @property {google.protobuf.FieldOptions.IFeatureSupport|null} [featureSupport] FieldOptions featureSupport * @property {Array.|null} [uninterpretedOption] FieldOptions uninterpretedOption * @property {Array.|null} [".google.api.fieldBehavior"] FieldOptions .google.api.fieldBehavior * @property {google.api.IResourceReference|null} [".google.api.resourceReference"] FieldOptions .google.api.resourceReference @@ -15234,14 +15770,6 @@ */ FieldOptions.prototype.features = null; - /** - * FieldOptions featureSupport. - * @member {google.protobuf.FieldOptions.IFeatureSupport|null|undefined} featureSupport - * @memberof google.protobuf.FieldOptions - * @instance - */ - FieldOptions.prototype.featureSupport = null; - /** * FieldOptions uninterpretedOption. * @member {Array.} uninterpretedOption @@ -15418,11 +15946,6 @@ throw TypeError(".google.protobuf.FieldOptions.features: object expected"); message.features = $root.google.protobuf.FeatureSet.fromObject(object.features); } - if (object.featureSupport != null) { - if (typeof object.featureSupport !== "object") - throw TypeError(".google.protobuf.FieldOptions.featureSupport: object expected"); - message.featureSupport = $root.google.protobuf.FieldOptions.FeatureSupport.fromObject(object.featureSupport); - } if (object.uninterpretedOption) { if (!Array.isArray(object.uninterpretedOption)) throw TypeError(".google.protobuf.FieldOptions.uninterpretedOption: array expected"); @@ -15520,7 +16043,6 @@ object.debugRedact = false; object.retention = options.enums === String ? "RETENTION_UNKNOWN" : 0; object.features = null; - object.featureSupport = null; object[".google.api.resourceReference"] = null; } if (message.ctype != null && message.hasOwnProperty("ctype")) @@ -15553,8 +16075,6 @@ } if (message.features != null && message.hasOwnProperty("features")) object.features = $root.google.protobuf.FeatureSet.toObject(message.features, options); - if (message.featureSupport != null && message.hasOwnProperty("featureSupport")) - object.featureSupport = $root.google.protobuf.FieldOptions.FeatureSupport.toObject(message.featureSupport, options); if (message.uninterpretedOption && message.uninterpretedOption.length) { object.uninterpretedOption = []; for (var j = 0; j < message.uninterpretedOption.length; ++j) @@ -15738,10 +16258,6 @@ case 0: message.edition = 0; break; - case "EDITION_LEGACY": - case 900: - message.edition = 900; - break; case "EDITION_PROTO2": case 998: message.edition = 998; @@ -15841,309 +16357,6 @@ return EditionDefault; })(); - FieldOptions.FeatureSupport = (function() { - - /** - * Properties of a FeatureSupport. - * @memberof google.protobuf.FieldOptions - * @interface IFeatureSupport - * @property {google.protobuf.Edition|null} [editionIntroduced] FeatureSupport editionIntroduced - * @property {google.protobuf.Edition|null} [editionDeprecated] FeatureSupport editionDeprecated - * @property {string|null} [deprecationWarning] FeatureSupport deprecationWarning - * @property {google.protobuf.Edition|null} [editionRemoved] FeatureSupport editionRemoved - */ - - /** - * Constructs a new FeatureSupport. - * @memberof google.protobuf.FieldOptions - * @classdesc Represents a FeatureSupport. - * @implements IFeatureSupport - * @constructor - * @param {google.protobuf.FieldOptions.IFeatureSupport=} [properties] Properties to set - */ - function FeatureSupport(properties) { - if (properties) - for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) - if (properties[keys[i]] != null) - this[keys[i]] = properties[keys[i]]; - } - - /** - * FeatureSupport editionIntroduced. - * @member {google.protobuf.Edition} editionIntroduced - * @memberof google.protobuf.FieldOptions.FeatureSupport - * @instance - */ - FeatureSupport.prototype.editionIntroduced = 0; - - /** - * FeatureSupport editionDeprecated. - * @member {google.protobuf.Edition} editionDeprecated - * @memberof google.protobuf.FieldOptions.FeatureSupport - * @instance - */ - FeatureSupport.prototype.editionDeprecated = 0; - - /** - * FeatureSupport deprecationWarning. - * @member {string} deprecationWarning - * @memberof google.protobuf.FieldOptions.FeatureSupport - * @instance - */ - FeatureSupport.prototype.deprecationWarning = ""; - - /** - * FeatureSupport editionRemoved. - * @member {google.protobuf.Edition} editionRemoved - * @memberof google.protobuf.FieldOptions.FeatureSupport - * @instance - */ - FeatureSupport.prototype.editionRemoved = 0; - - /** - * Creates a FeatureSupport message from a plain object. Also converts values to their respective internal types. - * @function fromObject - * @memberof google.protobuf.FieldOptions.FeatureSupport - * @static - * @param {Object.} object Plain object - * @returns {google.protobuf.FieldOptions.FeatureSupport} FeatureSupport - */ - FeatureSupport.fromObject = function fromObject(object) { - if (object instanceof $root.google.protobuf.FieldOptions.FeatureSupport) - return object; - var message = new $root.google.protobuf.FieldOptions.FeatureSupport(); - switch (object.editionIntroduced) { - default: - if (typeof object.editionIntroduced === "number") { - message.editionIntroduced = object.editionIntroduced; - break; - } - break; - case "EDITION_UNKNOWN": - case 0: - message.editionIntroduced = 0; - break; - case "EDITION_LEGACY": - case 900: - message.editionIntroduced = 900; - break; - case "EDITION_PROTO2": - case 998: - message.editionIntroduced = 998; - break; - case "EDITION_PROTO3": - case 999: - message.editionIntroduced = 999; - break; - case "EDITION_2023": - case 1000: - message.editionIntroduced = 1000; - break; - case "EDITION_2024": - case 1001: - message.editionIntroduced = 1001; - break; - case "EDITION_1_TEST_ONLY": - case 1: - message.editionIntroduced = 1; - break; - case "EDITION_2_TEST_ONLY": - case 2: - message.editionIntroduced = 2; - break; - case "EDITION_99997_TEST_ONLY": - case 99997: - message.editionIntroduced = 99997; - break; - case "EDITION_99998_TEST_ONLY": - case 99998: - message.editionIntroduced = 99998; - break; - case "EDITION_99999_TEST_ONLY": - case 99999: - message.editionIntroduced = 99999; - break; - case "EDITION_MAX": - case 2147483647: - message.editionIntroduced = 2147483647; - break; - } - switch (object.editionDeprecated) { - default: - if (typeof object.editionDeprecated === "number") { - message.editionDeprecated = object.editionDeprecated; - break; - } - break; - case "EDITION_UNKNOWN": - case 0: - message.editionDeprecated = 0; - break; - case "EDITION_LEGACY": - case 900: - message.editionDeprecated = 900; - break; - case "EDITION_PROTO2": - case 998: - message.editionDeprecated = 998; - break; - case "EDITION_PROTO3": - case 999: - message.editionDeprecated = 999; - break; - case "EDITION_2023": - case 1000: - message.editionDeprecated = 1000; - break; - case "EDITION_2024": - case 1001: - message.editionDeprecated = 1001; - break; - case "EDITION_1_TEST_ONLY": - case 1: - message.editionDeprecated = 1; - break; - case "EDITION_2_TEST_ONLY": - case 2: - message.editionDeprecated = 2; - break; - case "EDITION_99997_TEST_ONLY": - case 99997: - message.editionDeprecated = 99997; - break; - case "EDITION_99998_TEST_ONLY": - case 99998: - message.editionDeprecated = 99998; - break; - case "EDITION_99999_TEST_ONLY": - case 99999: - message.editionDeprecated = 99999; - break; - case "EDITION_MAX": - case 2147483647: - message.editionDeprecated = 2147483647; - break; - } - if (object.deprecationWarning != null) - message.deprecationWarning = String(object.deprecationWarning); - switch (object.editionRemoved) { - default: - if (typeof object.editionRemoved === "number") { - message.editionRemoved = object.editionRemoved; - break; - } - break; - case "EDITION_UNKNOWN": - case 0: - message.editionRemoved = 0; - break; - case "EDITION_LEGACY": - case 900: - message.editionRemoved = 900; - break; - case "EDITION_PROTO2": - case 998: - message.editionRemoved = 998; - break; - case "EDITION_PROTO3": - case 999: - message.editionRemoved = 999; - break; - case "EDITION_2023": - case 1000: - message.editionRemoved = 1000; - break; - case "EDITION_2024": - case 1001: - message.editionRemoved = 1001; - break; - case "EDITION_1_TEST_ONLY": - case 1: - message.editionRemoved = 1; - break; - case "EDITION_2_TEST_ONLY": - case 2: - message.editionRemoved = 2; - break; - case "EDITION_99997_TEST_ONLY": - case 99997: - message.editionRemoved = 99997; - break; - case "EDITION_99998_TEST_ONLY": - case 99998: - message.editionRemoved = 99998; - break; - case "EDITION_99999_TEST_ONLY": - case 99999: - message.editionRemoved = 99999; - break; - case "EDITION_MAX": - case 2147483647: - message.editionRemoved = 2147483647; - break; - } - return message; - }; - - /** - * Creates a plain object from a FeatureSupport message. Also converts values to other types if specified. - * @function toObject - * @memberof google.protobuf.FieldOptions.FeatureSupport - * @static - * @param {google.protobuf.FieldOptions.FeatureSupport} message FeatureSupport - * @param {$protobuf.IConversionOptions} [options] Conversion options - * @returns {Object.} Plain object - */ - FeatureSupport.toObject = function toObject(message, options) { - if (!options) - options = {}; - var object = {}; - if (options.defaults) { - object.editionIntroduced = options.enums === String ? "EDITION_UNKNOWN" : 0; - object.editionDeprecated = options.enums === String ? "EDITION_UNKNOWN" : 0; - object.deprecationWarning = ""; - object.editionRemoved = options.enums === String ? "EDITION_UNKNOWN" : 0; - } - if (message.editionIntroduced != null && message.hasOwnProperty("editionIntroduced")) - object.editionIntroduced = options.enums === String ? $root.google.protobuf.Edition[message.editionIntroduced] === undefined ? message.editionIntroduced : $root.google.protobuf.Edition[message.editionIntroduced] : message.editionIntroduced; - if (message.editionDeprecated != null && message.hasOwnProperty("editionDeprecated")) - object.editionDeprecated = options.enums === String ? $root.google.protobuf.Edition[message.editionDeprecated] === undefined ? message.editionDeprecated : $root.google.protobuf.Edition[message.editionDeprecated] : message.editionDeprecated; - if (message.deprecationWarning != null && message.hasOwnProperty("deprecationWarning")) - object.deprecationWarning = message.deprecationWarning; - if (message.editionRemoved != null && message.hasOwnProperty("editionRemoved")) - object.editionRemoved = options.enums === String ? $root.google.protobuf.Edition[message.editionRemoved] === undefined ? message.editionRemoved : $root.google.protobuf.Edition[message.editionRemoved] : message.editionRemoved; - return object; - }; - - /** - * Converts this FeatureSupport to JSON. - * @function toJSON - * @memberof google.protobuf.FieldOptions.FeatureSupport - * @instance - * @returns {Object.} JSON object - */ - FeatureSupport.prototype.toJSON = function toJSON() { - return this.constructor.toObject(this, $protobuf.util.toJSONOptions); - }; - - /** - * Gets the default type url for FeatureSupport - * @function getTypeUrl - * @memberof google.protobuf.FieldOptions.FeatureSupport - * @static - * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") - * @returns {string} The default type url - */ - FeatureSupport.getTypeUrl = function getTypeUrl(typeUrlPrefix) { - if (typeUrlPrefix === undefined) { - typeUrlPrefix = "type.googleapis.com"; - } - return typeUrlPrefix + "/google.protobuf.FieldOptions.FeatureSupport"; - }; - - return FeatureSupport; - })(); - return FieldOptions; })(); @@ -17846,10 +18059,6 @@ case 0: message.minimumEdition = 0; break; - case "EDITION_LEGACY": - case 900: - message.minimumEdition = 900; - break; case "EDITION_PROTO2": case 998: message.minimumEdition = 998; @@ -17902,10 +18111,6 @@ case 0: message.maximumEdition = 0; break; - case "EDITION_LEGACY": - case 900: - message.maximumEdition = 900; - break; case "EDITION_PROTO2": case 998: message.maximumEdition = 998; @@ -18014,8 +18219,7 @@ * @memberof google.protobuf.FeatureSetDefaults * @interface IFeatureSetEditionDefault * @property {google.protobuf.Edition|null} [edition] FeatureSetEditionDefault edition - * @property {google.protobuf.IFeatureSet|null} [overridableFeatures] FeatureSetEditionDefault overridableFeatures - * @property {google.protobuf.IFeatureSet|null} [fixedFeatures] FeatureSetEditionDefault fixedFeatures + * @property {google.protobuf.IFeatureSet|null} [features] FeatureSetEditionDefault features */ /** @@ -18042,20 +18246,12 @@ FeatureSetEditionDefault.prototype.edition = 0; /** - * FeatureSetEditionDefault overridableFeatures. - * @member {google.protobuf.IFeatureSet|null|undefined} overridableFeatures - * @memberof google.protobuf.FeatureSetDefaults.FeatureSetEditionDefault - * @instance - */ - FeatureSetEditionDefault.prototype.overridableFeatures = null; - - /** - * FeatureSetEditionDefault fixedFeatures. - * @member {google.protobuf.IFeatureSet|null|undefined} fixedFeatures + * FeatureSetEditionDefault features. + * @member {google.protobuf.IFeatureSet|null|undefined} features * @memberof google.protobuf.FeatureSetDefaults.FeatureSetEditionDefault * @instance */ - FeatureSetEditionDefault.prototype.fixedFeatures = null; + FeatureSetEditionDefault.prototype.features = null; /** * Creates a FeatureSetEditionDefault message from a plain object. Also converts values to their respective internal types. @@ -18080,10 +18276,6 @@ case 0: message.edition = 0; break; - case "EDITION_LEGACY": - case 900: - message.edition = 900; - break; case "EDITION_PROTO2": case 998: message.edition = 998; @@ -18125,15 +18317,10 @@ message.edition = 2147483647; break; } - if (object.overridableFeatures != null) { - if (typeof object.overridableFeatures !== "object") - throw TypeError(".google.protobuf.FeatureSetDefaults.FeatureSetEditionDefault.overridableFeatures: object expected"); - message.overridableFeatures = $root.google.protobuf.FeatureSet.fromObject(object.overridableFeatures); - } - if (object.fixedFeatures != null) { - if (typeof object.fixedFeatures !== "object") - throw TypeError(".google.protobuf.FeatureSetDefaults.FeatureSetEditionDefault.fixedFeatures: object expected"); - message.fixedFeatures = $root.google.protobuf.FeatureSet.fromObject(object.fixedFeatures); + if (object.features != null) { + if (typeof object.features !== "object") + throw TypeError(".google.protobuf.FeatureSetDefaults.FeatureSetEditionDefault.features: object expected"); + message.features = $root.google.protobuf.FeatureSet.fromObject(object.features); } return message; }; @@ -18152,16 +18339,13 @@ options = {}; var object = {}; if (options.defaults) { + object.features = null; object.edition = options.enums === String ? "EDITION_UNKNOWN" : 0; - object.overridableFeatures = null; - object.fixedFeatures = null; } + if (message.features != null && message.hasOwnProperty("features")) + object.features = $root.google.protobuf.FeatureSet.toObject(message.features, options); if (message.edition != null && message.hasOwnProperty("edition")) object.edition = options.enums === String ? $root.google.protobuf.Edition[message.edition] === undefined ? message.edition : $root.google.protobuf.Edition[message.edition] : message.edition; - if (message.overridableFeatures != null && message.hasOwnProperty("overridableFeatures")) - object.overridableFeatures = $root.google.protobuf.FeatureSet.toObject(message.overridableFeatures, options); - if (message.fixedFeatures != null && message.hasOwnProperty("fixedFeatures")) - object.fixedFeatures = $root.google.protobuf.FeatureSet.toObject(message.fixedFeatures, options); return object; }; diff --git a/dev/protos/firestore_v1_proto_api.d.ts b/dev/protos/firestore_v1_proto_api.d.ts index 0d428b9ef..c8f989169 100644 --- a/dev/protos/firestore_v1_proto_api.d.ts +++ b/dev/protos/firestore_v1_proto_api.d.ts @@ -360,9923 +360,9857 @@ export namespace firestore { /** Namespace google. */ export namespace google { - /** Namespace protobuf. */ - namespace protobuf { - - /** Properties of a Struct. */ - interface IStruct { + /** Namespace firestore. */ + namespace firestore { - /** Struct fields */ - fields?: ({ [k: string]: google.protobuf.IValue }|null); - } + /** Namespace v1. */ + namespace v1 { - /** Represents a Struct. */ - class Struct implements IStruct { + /** Properties of an AggregationResult. */ + interface IAggregationResult { - /** - * Constructs a new Struct. - * @param [properties] Properties to set - */ - constructor(properties?: google.protobuf.IStruct); + /** AggregationResult aggregateFields */ + aggregateFields?: ({ [k: string]: google.firestore.v1.IValue }|null); + } - /** Struct fields. */ - public fields: { [k: string]: google.protobuf.IValue }; + /** Represents an AggregationResult. */ + class AggregationResult implements IAggregationResult { - /** - * Creates a Struct message from a plain object. Also converts values to their respective internal types. - * @param object Plain object - * @returns Struct - */ - public static fromObject(object: { [k: string]: any }): google.protobuf.Struct; + /** + * Constructs a new AggregationResult. + * @param [properties] Properties to set + */ + constructor(properties?: google.firestore.v1.IAggregationResult); - /** - * Creates a plain object from a Struct message. Also converts values to other types if specified. - * @param message Struct - * @param [options] Conversion options - * @returns Plain object - */ - public static toObject(message: google.protobuf.Struct, options?: $protobuf.IConversionOptions): { [k: string]: any }; + /** AggregationResult aggregateFields. */ + public aggregateFields: { [k: string]: google.firestore.v1.IValue }; - /** - * Converts this Struct to JSON. - * @returns JSON object - */ - public toJSON(): { [k: string]: any }; + /** + * Creates an AggregationResult message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns AggregationResult + */ + public static fromObject(object: { [k: string]: any }): google.firestore.v1.AggregationResult; - /** - * Gets the default type url for Struct - * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") - * @returns The default type url - */ - public static getTypeUrl(typeUrlPrefix?: string): string; - } + /** + * Creates a plain object from an AggregationResult message. Also converts values to other types if specified. + * @param message AggregationResult + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.firestore.v1.AggregationResult, options?: $protobuf.IConversionOptions): { [k: string]: any }; - /** Properties of a Value. */ - interface IValue { + /** + * Converts this AggregationResult to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; - /** Value nullValue */ - nullValue?: (google.protobuf.NullValue|null); + /** + * Gets the default type url for AggregationResult + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } - /** Value numberValue */ - numberValue?: (number|null); + /** Properties of a Document. */ + interface IDocument { - /** Value stringValue */ - stringValue?: (string|null); + /** Document name */ + name?: (string|null); - /** Value boolValue */ - boolValue?: (boolean|null); + /** Document fields */ + fields?: ({ [k: string]: google.firestore.v1.IValue }|null); - /** Value structValue */ - structValue?: (google.protobuf.IStruct|null); + /** Document createTime */ + createTime?: (google.protobuf.ITimestamp|null); - /** Value listValue */ - listValue?: (google.protobuf.IListValue|null); - } + /** Document updateTime */ + updateTime?: (google.protobuf.ITimestamp|null); + } - /** Represents a Value. */ - class Value implements IValue { + /** Represents a Document. */ + class Document implements IDocument { - /** - * Constructs a new Value. - * @param [properties] Properties to set - */ - constructor(properties?: google.protobuf.IValue); + /** + * Constructs a new Document. + * @param [properties] Properties to set + */ + constructor(properties?: google.firestore.v1.IDocument); - /** Value nullValue. */ - public nullValue?: (google.protobuf.NullValue|null); + /** Document name. */ + public name: string; - /** Value numberValue. */ - public numberValue?: (number|null); + /** Document fields. */ + public fields: { [k: string]: google.firestore.v1.IValue }; - /** Value stringValue. */ - public stringValue?: (string|null); + /** Document createTime. */ + public createTime?: (google.protobuf.ITimestamp|null); - /** Value boolValue. */ - public boolValue?: (boolean|null); + /** Document updateTime. */ + public updateTime?: (google.protobuf.ITimestamp|null); - /** Value structValue. */ - public structValue?: (google.protobuf.IStruct|null); + /** + * Creates a Document message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns Document + */ + public static fromObject(object: { [k: string]: any }): google.firestore.v1.Document; - /** Value listValue. */ - public listValue?: (google.protobuf.IListValue|null); + /** + * Creates a plain object from a Document message. Also converts values to other types if specified. + * @param message Document + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.firestore.v1.Document, options?: $protobuf.IConversionOptions): { [k: string]: any }; - /** Value kind. */ - public kind?: ("nullValue"|"numberValue"|"stringValue"|"boolValue"|"structValue"|"listValue"); + /** + * Converts this Document to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; - /** - * Creates a Value message from a plain object. Also converts values to their respective internal types. - * @param object Plain object - * @returns Value - */ - public static fromObject(object: { [k: string]: any }): google.protobuf.Value; + /** + * Gets the default type url for Document + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } - /** - * Creates a plain object from a Value message. Also converts values to other types if specified. - * @param message Value - * @param [options] Conversion options - * @returns Plain object - */ - public static toObject(message: google.protobuf.Value, options?: $protobuf.IConversionOptions): { [k: string]: any }; + /** Properties of a Value. */ + interface IValue { - /** - * Converts this Value to JSON. - * @returns JSON object - */ - public toJSON(): { [k: string]: any }; + /** Value nullValue */ + nullValue?: (google.protobuf.NullValue|null); - /** - * Gets the default type url for Value - * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") - * @returns The default type url - */ - public static getTypeUrl(typeUrlPrefix?: string): string; - } + /** Value booleanValue */ + booleanValue?: (boolean|null); - /** NullValue enum. */ - type NullValue = - "NULL_VALUE"; + /** Value integerValue */ + integerValue?: (number|string|null); - /** Properties of a ListValue. */ - interface IListValue { + /** Value doubleValue */ + doubleValue?: (number|null); - /** ListValue values */ - values?: (google.protobuf.IValue[]|null); - } + /** Value timestampValue */ + timestampValue?: (google.protobuf.ITimestamp|null); - /** Represents a ListValue. */ - class ListValue implements IListValue { + /** Value stringValue */ + stringValue?: (string|null); - /** - * Constructs a new ListValue. - * @param [properties] Properties to set - */ - constructor(properties?: google.protobuf.IListValue); + /** Value bytesValue */ + bytesValue?: (Uint8Array|null); - /** ListValue values. */ - public values: google.protobuf.IValue[]; + /** Value referenceValue */ + referenceValue?: (string|null); - /** - * Creates a ListValue message from a plain object. Also converts values to their respective internal types. - * @param object Plain object - * @returns ListValue - */ - public static fromObject(object: { [k: string]: any }): google.protobuf.ListValue; + /** Value geoPointValue */ + geoPointValue?: (google.type.ILatLng|null); - /** - * Creates a plain object from a ListValue message. Also converts values to other types if specified. - * @param message ListValue - * @param [options] Conversion options - * @returns Plain object - */ - public static toObject(message: google.protobuf.ListValue, options?: $protobuf.IConversionOptions): { [k: string]: any }; + /** Value arrayValue */ + arrayValue?: (google.firestore.v1.IArrayValue|null); - /** - * Converts this ListValue to JSON. - * @returns JSON object - */ - public toJSON(): { [k: string]: any }; + /** Value mapValue */ + mapValue?: (google.firestore.v1.IMapValue|null); - /** - * Gets the default type url for ListValue - * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") - * @returns The default type url - */ - public static getTypeUrl(typeUrlPrefix?: string): string; - } - - /** Properties of a Timestamp. */ - interface ITimestamp { - - /** Timestamp seconds */ - seconds?: (number|string|null); + /** Value fieldReferenceValue */ + fieldReferenceValue?: (string|null); - /** Timestamp nanos */ - nanos?: (number|null); - } + /** Value functionValue */ + functionValue?: (google.firestore.v1.IFunction|null); - /** Represents a Timestamp. */ - class Timestamp implements ITimestamp { + /** Value pipelineValue */ + pipelineValue?: (google.firestore.v1.IPipeline|null); + } - /** - * Constructs a new Timestamp. - * @param [properties] Properties to set - */ - constructor(properties?: google.protobuf.ITimestamp); + /** Represents a Value. */ + class Value implements IValue { - /** Timestamp seconds. */ - public seconds: (number|string); + /** + * Constructs a new Value. + * @param [properties] Properties to set + */ + constructor(properties?: google.firestore.v1.IValue); - /** Timestamp nanos. */ - public nanos: number; + /** Value nullValue. */ + public nullValue?: (google.protobuf.NullValue|null); - /** - * Creates a Timestamp message from a plain object. Also converts values to their respective internal types. - * @param object Plain object - * @returns Timestamp - */ - public static fromObject(object: { [k: string]: any }): google.protobuf.Timestamp; + /** Value booleanValue. */ + public booleanValue?: (boolean|null); - /** - * Creates a plain object from a Timestamp message. Also converts values to other types if specified. - * @param message Timestamp - * @param [options] Conversion options - * @returns Plain object - */ - public static toObject(message: google.protobuf.Timestamp, options?: $protobuf.IConversionOptions): { [k: string]: any }; + /** Value integerValue. */ + public integerValue?: (number|string|null); - /** - * Converts this Timestamp to JSON. - * @returns JSON object - */ - public toJSON(): { [k: string]: any }; + /** Value doubleValue. */ + public doubleValue?: (number|null); - /** - * Gets the default type url for Timestamp - * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") - * @returns The default type url - */ - public static getTypeUrl(typeUrlPrefix?: string): string; - } + /** Value timestampValue. */ + public timestampValue?: (google.protobuf.ITimestamp|null); - /** Properties of a FileDescriptorSet. */ - interface IFileDescriptorSet { + /** Value stringValue. */ + public stringValue?: (string|null); - /** FileDescriptorSet file */ - file?: (google.protobuf.IFileDescriptorProto[]|null); - } + /** Value bytesValue. */ + public bytesValue?: (Uint8Array|null); - /** Represents a FileDescriptorSet. */ - class FileDescriptorSet implements IFileDescriptorSet { + /** Value referenceValue. */ + public referenceValue?: (string|null); - /** - * Constructs a new FileDescriptorSet. - * @param [properties] Properties to set - */ - constructor(properties?: google.protobuf.IFileDescriptorSet); + /** Value geoPointValue. */ + public geoPointValue?: (google.type.ILatLng|null); - /** FileDescriptorSet file. */ - public file: google.protobuf.IFileDescriptorProto[]; + /** Value arrayValue. */ + public arrayValue?: (google.firestore.v1.IArrayValue|null); - /** - * Creates a FileDescriptorSet message from a plain object. Also converts values to their respective internal types. - * @param object Plain object - * @returns FileDescriptorSet - */ - public static fromObject(object: { [k: string]: any }): google.protobuf.FileDescriptorSet; + /** Value mapValue. */ + public mapValue?: (google.firestore.v1.IMapValue|null); - /** - * Creates a plain object from a FileDescriptorSet message. Also converts values to other types if specified. - * @param message FileDescriptorSet - * @param [options] Conversion options - * @returns Plain object - */ - public static toObject(message: google.protobuf.FileDescriptorSet, options?: $protobuf.IConversionOptions): { [k: string]: any }; + /** Value fieldReferenceValue. */ + public fieldReferenceValue?: (string|null); - /** - * Converts this FileDescriptorSet to JSON. - * @returns JSON object - */ - public toJSON(): { [k: string]: any }; + /** Value functionValue. */ + public functionValue?: (google.firestore.v1.IFunction|null); - /** - * Gets the default type url for FileDescriptorSet - * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") - * @returns The default type url - */ - public static getTypeUrl(typeUrlPrefix?: string): string; - } + /** Value pipelineValue. */ + public pipelineValue?: (google.firestore.v1.IPipeline|null); - /** Edition enum. */ - type Edition = - "EDITION_UNKNOWN"| "EDITION_LEGACY"| "EDITION_PROTO2"| "EDITION_PROTO3"| "EDITION_2023"| "EDITION_2024"| "EDITION_1_TEST_ONLY"| "EDITION_2_TEST_ONLY"| "EDITION_99997_TEST_ONLY"| "EDITION_99998_TEST_ONLY"| "EDITION_99999_TEST_ONLY"| "EDITION_MAX"; + /** Value valueType. */ + public valueType?: ("nullValue"|"booleanValue"|"integerValue"|"doubleValue"|"timestampValue"|"stringValue"|"bytesValue"|"referenceValue"|"geoPointValue"|"arrayValue"|"mapValue"|"fieldReferenceValue"|"functionValue"|"pipelineValue"); - /** Properties of a FileDescriptorProto. */ - interface IFileDescriptorProto { + /** + * Creates a Value message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns Value + */ + public static fromObject(object: { [k: string]: any }): google.firestore.v1.Value; - /** FileDescriptorProto name */ - name?: (string|null); + /** + * Creates a plain object from a Value message. Also converts values to other types if specified. + * @param message Value + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.firestore.v1.Value, options?: $protobuf.IConversionOptions): { [k: string]: any }; - /** FileDescriptorProto package */ - "package"?: (string|null); + /** + * Converts this Value to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; - /** FileDescriptorProto dependency */ - dependency?: (string[]|null); + /** + * Gets the default type url for Value + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } - /** FileDescriptorProto publicDependency */ - publicDependency?: (number[]|null); + /** Properties of an ArrayValue. */ + interface IArrayValue { - /** FileDescriptorProto weakDependency */ - weakDependency?: (number[]|null); + /** ArrayValue values */ + values?: (google.firestore.v1.IValue[]|null); + } - /** FileDescriptorProto messageType */ - messageType?: (google.protobuf.IDescriptorProto[]|null); + /** Represents an ArrayValue. */ + class ArrayValue implements IArrayValue { - /** FileDescriptorProto enumType */ - enumType?: (google.protobuf.IEnumDescriptorProto[]|null); + /** + * Constructs a new ArrayValue. + * @param [properties] Properties to set + */ + constructor(properties?: google.firestore.v1.IArrayValue); - /** FileDescriptorProto service */ - service?: (google.protobuf.IServiceDescriptorProto[]|null); + /** ArrayValue values. */ + public values: google.firestore.v1.IValue[]; - /** FileDescriptorProto extension */ - extension?: (google.protobuf.IFieldDescriptorProto[]|null); + /** + * Creates an ArrayValue message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns ArrayValue + */ + public static fromObject(object: { [k: string]: any }): google.firestore.v1.ArrayValue; - /** FileDescriptorProto options */ - options?: (google.protobuf.IFileOptions|null); + /** + * Creates a plain object from an ArrayValue message. Also converts values to other types if specified. + * @param message ArrayValue + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.firestore.v1.ArrayValue, options?: $protobuf.IConversionOptions): { [k: string]: any }; - /** FileDescriptorProto sourceCodeInfo */ - sourceCodeInfo?: (google.protobuf.ISourceCodeInfo|null); + /** + * Converts this ArrayValue to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; - /** FileDescriptorProto syntax */ - syntax?: (string|null); + /** + * Gets the default type url for ArrayValue + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } - /** FileDescriptorProto edition */ - edition?: (google.protobuf.Edition|null); - } + /** Properties of a MapValue. */ + interface IMapValue { - /** Represents a FileDescriptorProto. */ - class FileDescriptorProto implements IFileDescriptorProto { + /** MapValue fields */ + fields?: ({ [k: string]: google.firestore.v1.IValue }|null); + } - /** - * Constructs a new FileDescriptorProto. - * @param [properties] Properties to set - */ - constructor(properties?: google.protobuf.IFileDescriptorProto); + /** Represents a MapValue. */ + class MapValue implements IMapValue { - /** FileDescriptorProto name. */ - public name: string; + /** + * Constructs a new MapValue. + * @param [properties] Properties to set + */ + constructor(properties?: google.firestore.v1.IMapValue); - /** FileDescriptorProto package. */ - public package: string; + /** MapValue fields. */ + public fields: { [k: string]: google.firestore.v1.IValue }; - /** FileDescriptorProto dependency. */ - public dependency: string[]; - - /** FileDescriptorProto publicDependency. */ - public publicDependency: number[]; - - /** FileDescriptorProto weakDependency. */ - public weakDependency: number[]; - - /** FileDescriptorProto messageType. */ - public messageType: google.protobuf.IDescriptorProto[]; - - /** FileDescriptorProto enumType. */ - public enumType: google.protobuf.IEnumDescriptorProto[]; - - /** FileDescriptorProto service. */ - public service: google.protobuf.IServiceDescriptorProto[]; - - /** FileDescriptorProto extension. */ - public extension: google.protobuf.IFieldDescriptorProto[]; - - /** FileDescriptorProto options. */ - public options?: (google.protobuf.IFileOptions|null); - - /** FileDescriptorProto sourceCodeInfo. */ - public sourceCodeInfo?: (google.protobuf.ISourceCodeInfo|null); - - /** FileDescriptorProto syntax. */ - public syntax: string; - - /** FileDescriptorProto edition. */ - public edition: google.protobuf.Edition; - - /** - * Creates a FileDescriptorProto message from a plain object. Also converts values to their respective internal types. - * @param object Plain object - * @returns FileDescriptorProto - */ - public static fromObject(object: { [k: string]: any }): google.protobuf.FileDescriptorProto; - - /** - * Creates a plain object from a FileDescriptorProto message. Also converts values to other types if specified. - * @param message FileDescriptorProto - * @param [options] Conversion options - * @returns Plain object - */ - public static toObject(message: google.protobuf.FileDescriptorProto, options?: $protobuf.IConversionOptions): { [k: string]: any }; - - /** - * Converts this FileDescriptorProto to JSON. - * @returns JSON object - */ - public toJSON(): { [k: string]: any }; - - /** - * Gets the default type url for FileDescriptorProto - * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") - * @returns The default type url - */ - public static getTypeUrl(typeUrlPrefix?: string): string; - } - - /** Properties of a DescriptorProto. */ - interface IDescriptorProto { - - /** DescriptorProto name */ - name?: (string|null); - - /** DescriptorProto field */ - field?: (google.protobuf.IFieldDescriptorProto[]|null); - - /** DescriptorProto extension */ - extension?: (google.protobuf.IFieldDescriptorProto[]|null); - - /** DescriptorProto nestedType */ - nestedType?: (google.protobuf.IDescriptorProto[]|null); - - /** DescriptorProto enumType */ - enumType?: (google.protobuf.IEnumDescriptorProto[]|null); - - /** DescriptorProto extensionRange */ - extensionRange?: (google.protobuf.DescriptorProto.IExtensionRange[]|null); - - /** DescriptorProto oneofDecl */ - oneofDecl?: (google.protobuf.IOneofDescriptorProto[]|null); - - /** DescriptorProto options */ - options?: (google.protobuf.IMessageOptions|null); - - /** DescriptorProto reservedRange */ - reservedRange?: (google.protobuf.DescriptorProto.IReservedRange[]|null); - - /** DescriptorProto reservedName */ - reservedName?: (string[]|null); - } - - /** Represents a DescriptorProto. */ - class DescriptorProto implements IDescriptorProto { - - /** - * Constructs a new DescriptorProto. - * @param [properties] Properties to set - */ - constructor(properties?: google.protobuf.IDescriptorProto); - - /** DescriptorProto name. */ - public name: string; - - /** DescriptorProto field. */ - public field: google.protobuf.IFieldDescriptorProto[]; - - /** DescriptorProto extension. */ - public extension: google.protobuf.IFieldDescriptorProto[]; - - /** DescriptorProto nestedType. */ - public nestedType: google.protobuf.IDescriptorProto[]; - - /** DescriptorProto enumType. */ - public enumType: google.protobuf.IEnumDescriptorProto[]; - - /** DescriptorProto extensionRange. */ - public extensionRange: google.protobuf.DescriptorProto.IExtensionRange[]; - - /** DescriptorProto oneofDecl. */ - public oneofDecl: google.protobuf.IOneofDescriptorProto[]; - - /** DescriptorProto options. */ - public options?: (google.protobuf.IMessageOptions|null); - - /** DescriptorProto reservedRange. */ - public reservedRange: google.protobuf.DescriptorProto.IReservedRange[]; - - /** DescriptorProto reservedName. */ - public reservedName: string[]; - - /** - * Creates a DescriptorProto message from a plain object. Also converts values to their respective internal types. - * @param object Plain object - * @returns DescriptorProto - */ - public static fromObject(object: { [k: string]: any }): google.protobuf.DescriptorProto; - - /** - * Creates a plain object from a DescriptorProto message. Also converts values to other types if specified. - * @param message DescriptorProto - * @param [options] Conversion options - * @returns Plain object - */ - public static toObject(message: google.protobuf.DescriptorProto, options?: $protobuf.IConversionOptions): { [k: string]: any }; + /** + * Creates a MapValue message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns MapValue + */ + public static fromObject(object: { [k: string]: any }): google.firestore.v1.MapValue; - /** - * Converts this DescriptorProto to JSON. - * @returns JSON object - */ - public toJSON(): { [k: string]: any }; + /** + * Creates a plain object from a MapValue message. Also converts values to other types if specified. + * @param message MapValue + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.firestore.v1.MapValue, options?: $protobuf.IConversionOptions): { [k: string]: any }; - /** - * Gets the default type url for DescriptorProto - * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") - * @returns The default type url - */ - public static getTypeUrl(typeUrlPrefix?: string): string; - } + /** + * Converts this MapValue to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; - namespace DescriptorProto { + /** + * Gets the default type url for MapValue + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } - /** Properties of an ExtensionRange. */ - interface IExtensionRange { + /** Properties of a Function. */ + interface IFunction { - /** ExtensionRange start */ - start?: (number|null); + /** Function name */ + name?: (string|null); - /** ExtensionRange end */ - end?: (number|null); + /** Function args */ + args?: (google.firestore.v1.IValue[]|null); - /** ExtensionRange options */ - options?: (google.protobuf.IExtensionRangeOptions|null); + /** Function options */ + options?: ({ [k: string]: google.firestore.v1.IValue }|null); } - /** Represents an ExtensionRange. */ - class ExtensionRange implements IExtensionRange { + /** Represents a Function. */ + class Function implements IFunction { /** - * Constructs a new ExtensionRange. + * Constructs a new Function. * @param [properties] Properties to set */ - constructor(properties?: google.protobuf.DescriptorProto.IExtensionRange); + constructor(properties?: google.firestore.v1.IFunction); - /** ExtensionRange start. */ - public start: number; + /** Function name. */ + public name: string; - /** ExtensionRange end. */ - public end: number; + /** Function args. */ + public args: google.firestore.v1.IValue[]; - /** ExtensionRange options. */ - public options?: (google.protobuf.IExtensionRangeOptions|null); + /** Function options. */ + public options: { [k: string]: google.firestore.v1.IValue }; /** - * Creates an ExtensionRange message from a plain object. Also converts values to their respective internal types. + * Creates a Function message from a plain object. Also converts values to their respective internal types. * @param object Plain object - * @returns ExtensionRange + * @returns Function */ - public static fromObject(object: { [k: string]: any }): google.protobuf.DescriptorProto.ExtensionRange; + public static fromObject(object: { [k: string]: any }): google.firestore.v1.Function; /** - * Creates a plain object from an ExtensionRange message. Also converts values to other types if specified. - * @param message ExtensionRange + * Creates a plain object from a Function message. Also converts values to other types if specified. + * @param message Function * @param [options] Conversion options * @returns Plain object */ - public static toObject(message: google.protobuf.DescriptorProto.ExtensionRange, options?: $protobuf.IConversionOptions): { [k: string]: any }; + public static toObject(message: google.firestore.v1.Function, options?: $protobuf.IConversionOptions): { [k: string]: any }; /** - * Converts this ExtensionRange to JSON. + * Converts this Function to JSON. * @returns JSON object */ public toJSON(): { [k: string]: any }; /** - * Gets the default type url for ExtensionRange + * Gets the default type url for Function * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") * @returns The default type url */ public static getTypeUrl(typeUrlPrefix?: string): string; } - /** Properties of a ReservedRange. */ - interface IReservedRange { - - /** ReservedRange start */ - start?: (number|null); + /** Properties of a Pipeline. */ + interface IPipeline { - /** ReservedRange end */ - end?: (number|null); + /** Pipeline stages */ + stages?: (google.firestore.v1.Pipeline.IStage[]|null); } - /** Represents a ReservedRange. */ - class ReservedRange implements IReservedRange { + /** Represents a Pipeline. */ + class Pipeline implements IPipeline { /** - * Constructs a new ReservedRange. + * Constructs a new Pipeline. * @param [properties] Properties to set */ - constructor(properties?: google.protobuf.DescriptorProto.IReservedRange); - - /** ReservedRange start. */ - public start: number; + constructor(properties?: google.firestore.v1.IPipeline); - /** ReservedRange end. */ - public end: number; + /** Pipeline stages. */ + public stages: google.firestore.v1.Pipeline.IStage[]; /** - * Creates a ReservedRange message from a plain object. Also converts values to their respective internal types. + * Creates a Pipeline message from a plain object. Also converts values to their respective internal types. * @param object Plain object - * @returns ReservedRange + * @returns Pipeline */ - public static fromObject(object: { [k: string]: any }): google.protobuf.DescriptorProto.ReservedRange; + public static fromObject(object: { [k: string]: any }): google.firestore.v1.Pipeline; /** - * Creates a plain object from a ReservedRange message. Also converts values to other types if specified. - * @param message ReservedRange + * Creates a plain object from a Pipeline message. Also converts values to other types if specified. + * @param message Pipeline * @param [options] Conversion options * @returns Plain object */ - public static toObject(message: google.protobuf.DescriptorProto.ReservedRange, options?: $protobuf.IConversionOptions): { [k: string]: any }; + public static toObject(message: google.firestore.v1.Pipeline, options?: $protobuf.IConversionOptions): { [k: string]: any }; /** - * Converts this ReservedRange to JSON. + * Converts this Pipeline to JSON. * @returns JSON object */ public toJSON(): { [k: string]: any }; /** - * Gets the default type url for ReservedRange + * Gets the default type url for Pipeline * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") * @returns The default type url */ public static getTypeUrl(typeUrlPrefix?: string): string; } - } - - /** Properties of an ExtensionRangeOptions. */ - interface IExtensionRangeOptions { - - /** ExtensionRangeOptions uninterpretedOption */ - uninterpretedOption?: (google.protobuf.IUninterpretedOption[]|null); - - /** ExtensionRangeOptions declaration */ - declaration?: (google.protobuf.ExtensionRangeOptions.IDeclaration[]|null); - - /** ExtensionRangeOptions features */ - features?: (google.protobuf.IFeatureSet|null); - - /** ExtensionRangeOptions verification */ - verification?: (google.protobuf.ExtensionRangeOptions.VerificationState|null); - } - /** Represents an ExtensionRangeOptions. */ - class ExtensionRangeOptions implements IExtensionRangeOptions { + namespace Pipeline { - /** - * Constructs a new ExtensionRangeOptions. - * @param [properties] Properties to set - */ - constructor(properties?: google.protobuf.IExtensionRangeOptions); + /** Properties of a Stage. */ + interface IStage { - /** ExtensionRangeOptions uninterpretedOption. */ - public uninterpretedOption: google.protobuf.IUninterpretedOption[]; + /** Stage name */ + name?: (string|null); - /** ExtensionRangeOptions declaration. */ - public declaration: google.protobuf.ExtensionRangeOptions.IDeclaration[]; + /** Stage args */ + args?: (google.firestore.v1.IValue[]|null); - /** ExtensionRangeOptions features. */ - public features?: (google.protobuf.IFeatureSet|null); + /** Stage options */ + options?: ({ [k: string]: google.firestore.v1.IValue }|null); + } - /** ExtensionRangeOptions verification. */ - public verification: google.protobuf.ExtensionRangeOptions.VerificationState; + /** Represents a Stage. */ + class Stage implements IStage { - /** - * Creates an ExtensionRangeOptions message from a plain object. Also converts values to their respective internal types. - * @param object Plain object - * @returns ExtensionRangeOptions - */ - public static fromObject(object: { [k: string]: any }): google.protobuf.ExtensionRangeOptions; + /** + * Constructs a new Stage. + * @param [properties] Properties to set + */ + constructor(properties?: google.firestore.v1.Pipeline.IStage); - /** - * Creates a plain object from an ExtensionRangeOptions message. Also converts values to other types if specified. - * @param message ExtensionRangeOptions - * @param [options] Conversion options - * @returns Plain object - */ - public static toObject(message: google.protobuf.ExtensionRangeOptions, options?: $protobuf.IConversionOptions): { [k: string]: any }; + /** Stage name. */ + public name: string; - /** - * Converts this ExtensionRangeOptions to JSON. - * @returns JSON object - */ - public toJSON(): { [k: string]: any }; + /** Stage args. */ + public args: google.firestore.v1.IValue[]; - /** - * Gets the default type url for ExtensionRangeOptions - * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") - * @returns The default type url - */ - public static getTypeUrl(typeUrlPrefix?: string): string; - } + /** Stage options. */ + public options: { [k: string]: google.firestore.v1.IValue }; - namespace ExtensionRangeOptions { + /** + * Creates a Stage message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns Stage + */ + public static fromObject(object: { [k: string]: any }): google.firestore.v1.Pipeline.Stage; - /** Properties of a Declaration. */ - interface IDeclaration { + /** + * Creates a plain object from a Stage message. Also converts values to other types if specified. + * @param message Stage + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.firestore.v1.Pipeline.Stage, options?: $protobuf.IConversionOptions): { [k: string]: any }; - /** Declaration number */ - number?: (number|null); + /** + * Converts this Stage to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; - /** Declaration fullName */ - fullName?: (string|null); + /** + * Gets the default type url for Stage + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + } - /** Declaration type */ - type?: (string|null); + /** Properties of a BitSequence. */ + interface IBitSequence { - /** Declaration reserved */ - reserved?: (boolean|null); + /** BitSequence bitmap */ + bitmap?: (Uint8Array|null); - /** Declaration repeated */ - repeated?: (boolean|null); + /** BitSequence padding */ + padding?: (number|null); } - /** Represents a Declaration. */ - class Declaration implements IDeclaration { + /** Represents a BitSequence. */ + class BitSequence implements IBitSequence { /** - * Constructs a new Declaration. + * Constructs a new BitSequence. * @param [properties] Properties to set */ - constructor(properties?: google.protobuf.ExtensionRangeOptions.IDeclaration); - - /** Declaration number. */ - public number: number; - - /** Declaration fullName. */ - public fullName: string; - - /** Declaration type. */ - public type: string; + constructor(properties?: google.firestore.v1.IBitSequence); - /** Declaration reserved. */ - public reserved: boolean; + /** BitSequence bitmap. */ + public bitmap: Uint8Array; - /** Declaration repeated. */ - public repeated: boolean; + /** BitSequence padding. */ + public padding: number; /** - * Creates a Declaration message from a plain object. Also converts values to their respective internal types. + * Creates a BitSequence message from a plain object. Also converts values to their respective internal types. * @param object Plain object - * @returns Declaration + * @returns BitSequence */ - public static fromObject(object: { [k: string]: any }): google.protobuf.ExtensionRangeOptions.Declaration; + public static fromObject(object: { [k: string]: any }): google.firestore.v1.BitSequence; /** - * Creates a plain object from a Declaration message. Also converts values to other types if specified. - * @param message Declaration + * Creates a plain object from a BitSequence message. Also converts values to other types if specified. + * @param message BitSequence * @param [options] Conversion options * @returns Plain object */ - public static toObject(message: google.protobuf.ExtensionRangeOptions.Declaration, options?: $protobuf.IConversionOptions): { [k: string]: any }; + public static toObject(message: google.firestore.v1.BitSequence, options?: $protobuf.IConversionOptions): { [k: string]: any }; /** - * Converts this Declaration to JSON. + * Converts this BitSequence to JSON. * @returns JSON object */ public toJSON(): { [k: string]: any }; /** - * Gets the default type url for Declaration + * Gets the default type url for BitSequence * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") * @returns The default type url */ public static getTypeUrl(typeUrlPrefix?: string): string; } - /** VerificationState enum. */ - type VerificationState = - "DECLARATION"| "UNVERIFIED"; - } - - /** Properties of a FieldDescriptorProto. */ - interface IFieldDescriptorProto { - - /** FieldDescriptorProto name */ - name?: (string|null); + /** Properties of a BloomFilter. */ + interface IBloomFilter { - /** FieldDescriptorProto number */ - number?: (number|null); + /** BloomFilter bits */ + bits?: (google.firestore.v1.IBitSequence|null); - /** FieldDescriptorProto label */ - label?: (google.protobuf.FieldDescriptorProto.Label|null); + /** BloomFilter hashCount */ + hashCount?: (number|null); + } - /** FieldDescriptorProto type */ - type?: (google.protobuf.FieldDescriptorProto.Type|null); + /** Represents a BloomFilter. */ + class BloomFilter implements IBloomFilter { - /** FieldDescriptorProto typeName */ - typeName?: (string|null); + /** + * Constructs a new BloomFilter. + * @param [properties] Properties to set + */ + constructor(properties?: google.firestore.v1.IBloomFilter); - /** FieldDescriptorProto extendee */ - extendee?: (string|null); + /** BloomFilter bits. */ + public bits?: (google.firestore.v1.IBitSequence|null); - /** FieldDescriptorProto defaultValue */ - defaultValue?: (string|null); + /** BloomFilter hashCount. */ + public hashCount: number; - /** FieldDescriptorProto oneofIndex */ - oneofIndex?: (number|null); + /** + * Creates a BloomFilter message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns BloomFilter + */ + public static fromObject(object: { [k: string]: any }): google.firestore.v1.BloomFilter; - /** FieldDescriptorProto jsonName */ - jsonName?: (string|null); + /** + * Creates a plain object from a BloomFilter message. Also converts values to other types if specified. + * @param message BloomFilter + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.firestore.v1.BloomFilter, options?: $protobuf.IConversionOptions): { [k: string]: any }; - /** FieldDescriptorProto options */ - options?: (google.protobuf.IFieldOptions|null); + /** + * Converts this BloomFilter to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; - /** FieldDescriptorProto proto3Optional */ - proto3Optional?: (boolean|null); - } - - /** Represents a FieldDescriptorProto. */ - class FieldDescriptorProto implements IFieldDescriptorProto { + /** + * Gets the default type url for BloomFilter + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } - /** - * Constructs a new FieldDescriptorProto. - * @param [properties] Properties to set - */ - constructor(properties?: google.protobuf.IFieldDescriptorProto); + /** Properties of a DocumentMask. */ + interface IDocumentMask { - /** FieldDescriptorProto name. */ - public name: string; + /** DocumentMask fieldPaths */ + fieldPaths?: (string[]|null); + } - /** FieldDescriptorProto number. */ - public number: number; + /** Represents a DocumentMask. */ + class DocumentMask implements IDocumentMask { - /** FieldDescriptorProto label. */ - public label: google.protobuf.FieldDescriptorProto.Label; + /** + * Constructs a new DocumentMask. + * @param [properties] Properties to set + */ + constructor(properties?: google.firestore.v1.IDocumentMask); - /** FieldDescriptorProto type. */ - public type: google.protobuf.FieldDescriptorProto.Type; + /** DocumentMask fieldPaths. */ + public fieldPaths: string[]; - /** FieldDescriptorProto typeName. */ - public typeName: string; + /** + * Creates a DocumentMask message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns DocumentMask + */ + public static fromObject(object: { [k: string]: any }): google.firestore.v1.DocumentMask; - /** FieldDescriptorProto extendee. */ - public extendee: string; + /** + * Creates a plain object from a DocumentMask message. Also converts values to other types if specified. + * @param message DocumentMask + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.firestore.v1.DocumentMask, options?: $protobuf.IConversionOptions): { [k: string]: any }; - /** FieldDescriptorProto defaultValue. */ - public defaultValue: string; + /** + * Converts this DocumentMask to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; - /** FieldDescriptorProto oneofIndex. */ - public oneofIndex: number; + /** + * Gets the default type url for DocumentMask + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } - /** FieldDescriptorProto jsonName. */ - public jsonName: string; + /** Properties of a Precondition. */ + interface IPrecondition { - /** FieldDescriptorProto options. */ - public options?: (google.protobuf.IFieldOptions|null); + /** Precondition exists */ + exists?: (boolean|null); - /** FieldDescriptorProto proto3Optional. */ - public proto3Optional: boolean; + /** Precondition updateTime */ + updateTime?: (google.protobuf.ITimestamp|null); + } - /** - * Creates a FieldDescriptorProto message from a plain object. Also converts values to their respective internal types. - * @param object Plain object - * @returns FieldDescriptorProto - */ - public static fromObject(object: { [k: string]: any }): google.protobuf.FieldDescriptorProto; + /** Represents a Precondition. */ + class Precondition implements IPrecondition { - /** - * Creates a plain object from a FieldDescriptorProto message. Also converts values to other types if specified. - * @param message FieldDescriptorProto - * @param [options] Conversion options - * @returns Plain object - */ - public static toObject(message: google.protobuf.FieldDescriptorProto, options?: $protobuf.IConversionOptions): { [k: string]: any }; + /** + * Constructs a new Precondition. + * @param [properties] Properties to set + */ + constructor(properties?: google.firestore.v1.IPrecondition); - /** - * Converts this FieldDescriptorProto to JSON. - * @returns JSON object - */ - public toJSON(): { [k: string]: any }; + /** Precondition exists. */ + public exists?: (boolean|null); - /** - * Gets the default type url for FieldDescriptorProto - * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") - * @returns The default type url - */ - public static getTypeUrl(typeUrlPrefix?: string): string; - } + /** Precondition updateTime. */ + public updateTime?: (google.protobuf.ITimestamp|null); - namespace FieldDescriptorProto { + /** Precondition conditionType. */ + public conditionType?: ("exists"|"updateTime"); - /** Type enum. */ - type Type = - "TYPE_DOUBLE"| "TYPE_FLOAT"| "TYPE_INT64"| "TYPE_UINT64"| "TYPE_INT32"| "TYPE_FIXED64"| "TYPE_FIXED32"| "TYPE_BOOL"| "TYPE_STRING"| "TYPE_GROUP"| "TYPE_MESSAGE"| "TYPE_BYTES"| "TYPE_UINT32"| "TYPE_ENUM"| "TYPE_SFIXED32"| "TYPE_SFIXED64"| "TYPE_SINT32"| "TYPE_SINT64"; + /** + * Creates a Precondition message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns Precondition + */ + public static fromObject(object: { [k: string]: any }): google.firestore.v1.Precondition; - /** Label enum. */ - type Label = - "LABEL_OPTIONAL"| "LABEL_REPEATED"| "LABEL_REQUIRED"; - } + /** + * Creates a plain object from a Precondition message. Also converts values to other types if specified. + * @param message Precondition + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.firestore.v1.Precondition, options?: $protobuf.IConversionOptions): { [k: string]: any }; - /** Properties of an OneofDescriptorProto. */ - interface IOneofDescriptorProto { + /** + * Converts this Precondition to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; - /** OneofDescriptorProto name */ - name?: (string|null); + /** + * Gets the default type url for Precondition + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } - /** OneofDescriptorProto options */ - options?: (google.protobuf.IOneofOptions|null); - } + /** Properties of a TransactionOptions. */ + interface ITransactionOptions { - /** Represents an OneofDescriptorProto. */ - class OneofDescriptorProto implements IOneofDescriptorProto { + /** TransactionOptions readOnly */ + readOnly?: (google.firestore.v1.TransactionOptions.IReadOnly|null); - /** - * Constructs a new OneofDescriptorProto. - * @param [properties] Properties to set - */ - constructor(properties?: google.protobuf.IOneofDescriptorProto); + /** TransactionOptions readWrite */ + readWrite?: (google.firestore.v1.TransactionOptions.IReadWrite|null); + } - /** OneofDescriptorProto name. */ - public name: string; + /** Represents a TransactionOptions. */ + class TransactionOptions implements ITransactionOptions { - /** OneofDescriptorProto options. */ - public options?: (google.protobuf.IOneofOptions|null); + /** + * Constructs a new TransactionOptions. + * @param [properties] Properties to set + */ + constructor(properties?: google.firestore.v1.ITransactionOptions); - /** - * Creates an OneofDescriptorProto message from a plain object. Also converts values to their respective internal types. - * @param object Plain object - * @returns OneofDescriptorProto - */ - public static fromObject(object: { [k: string]: any }): google.protobuf.OneofDescriptorProto; + /** TransactionOptions readOnly. */ + public readOnly?: (google.firestore.v1.TransactionOptions.IReadOnly|null); - /** - * Creates a plain object from an OneofDescriptorProto message. Also converts values to other types if specified. - * @param message OneofDescriptorProto - * @param [options] Conversion options - * @returns Plain object - */ - public static toObject(message: google.protobuf.OneofDescriptorProto, options?: $protobuf.IConversionOptions): { [k: string]: any }; + /** TransactionOptions readWrite. */ + public readWrite?: (google.firestore.v1.TransactionOptions.IReadWrite|null); - /** - * Converts this OneofDescriptorProto to JSON. - * @returns JSON object - */ - public toJSON(): { [k: string]: any }; + /** TransactionOptions mode. */ + public mode?: ("readOnly"|"readWrite"); - /** - * Gets the default type url for OneofDescriptorProto - * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") - * @returns The default type url - */ - public static getTypeUrl(typeUrlPrefix?: string): string; - } + /** + * Creates a TransactionOptions message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns TransactionOptions + */ + public static fromObject(object: { [k: string]: any }): google.firestore.v1.TransactionOptions; - /** Properties of an EnumDescriptorProto. */ - interface IEnumDescriptorProto { + /** + * Creates a plain object from a TransactionOptions message. Also converts values to other types if specified. + * @param message TransactionOptions + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.firestore.v1.TransactionOptions, options?: $protobuf.IConversionOptions): { [k: string]: any }; - /** EnumDescriptorProto name */ - name?: (string|null); + /** + * Converts this TransactionOptions to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; - /** EnumDescriptorProto value */ - value?: (google.protobuf.IEnumValueDescriptorProto[]|null); + /** + * Gets the default type url for TransactionOptions + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } - /** EnumDescriptorProto options */ - options?: (google.protobuf.IEnumOptions|null); + namespace TransactionOptions { - /** EnumDescriptorProto reservedRange */ - reservedRange?: (google.protobuf.EnumDescriptorProto.IEnumReservedRange[]|null); + /** Properties of a ReadWrite. */ + interface IReadWrite { - /** EnumDescriptorProto reservedName */ - reservedName?: (string[]|null); - } + /** ReadWrite retryTransaction */ + retryTransaction?: (Uint8Array|null); + } - /** Represents an EnumDescriptorProto. */ - class EnumDescriptorProto implements IEnumDescriptorProto { + /** Represents a ReadWrite. */ + class ReadWrite implements IReadWrite { - /** - * Constructs a new EnumDescriptorProto. - * @param [properties] Properties to set - */ - constructor(properties?: google.protobuf.IEnumDescriptorProto); + /** + * Constructs a new ReadWrite. + * @param [properties] Properties to set + */ + constructor(properties?: google.firestore.v1.TransactionOptions.IReadWrite); - /** EnumDescriptorProto name. */ - public name: string; + /** ReadWrite retryTransaction. */ + public retryTransaction: Uint8Array; - /** EnumDescriptorProto value. */ - public value: google.protobuf.IEnumValueDescriptorProto[]; + /** + * Creates a ReadWrite message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns ReadWrite + */ + public static fromObject(object: { [k: string]: any }): google.firestore.v1.TransactionOptions.ReadWrite; - /** EnumDescriptorProto options. */ - public options?: (google.protobuf.IEnumOptions|null); + /** + * Creates a plain object from a ReadWrite message. Also converts values to other types if specified. + * @param message ReadWrite + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.firestore.v1.TransactionOptions.ReadWrite, options?: $protobuf.IConversionOptions): { [k: string]: any }; - /** EnumDescriptorProto reservedRange. */ - public reservedRange: google.protobuf.EnumDescriptorProto.IEnumReservedRange[]; + /** + * Converts this ReadWrite to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; - /** EnumDescriptorProto reservedName. */ - public reservedName: string[]; + /** + * Gets the default type url for ReadWrite + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } - /** - * Creates an EnumDescriptorProto message from a plain object. Also converts values to their respective internal types. - * @param object Plain object - * @returns EnumDescriptorProto - */ - public static fromObject(object: { [k: string]: any }): google.protobuf.EnumDescriptorProto; + /** Properties of a ReadOnly. */ + interface IReadOnly { - /** - * Creates a plain object from an EnumDescriptorProto message. Also converts values to other types if specified. - * @param message EnumDescriptorProto - * @param [options] Conversion options - * @returns Plain object - */ - public static toObject(message: google.protobuf.EnumDescriptorProto, options?: $protobuf.IConversionOptions): { [k: string]: any }; + /** ReadOnly readTime */ + readTime?: (google.protobuf.ITimestamp|null); + } - /** - * Converts this EnumDescriptorProto to JSON. - * @returns JSON object - */ - public toJSON(): { [k: string]: any }; + /** Represents a ReadOnly. */ + class ReadOnly implements IReadOnly { - /** - * Gets the default type url for EnumDescriptorProto - * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") - * @returns The default type url - */ - public static getTypeUrl(typeUrlPrefix?: string): string; - } + /** + * Constructs a new ReadOnly. + * @param [properties] Properties to set + */ + constructor(properties?: google.firestore.v1.TransactionOptions.IReadOnly); - namespace EnumDescriptorProto { + /** ReadOnly readTime. */ + public readTime?: (google.protobuf.ITimestamp|null); - /** Properties of an EnumReservedRange. */ - interface IEnumReservedRange { + /** ReadOnly consistencySelector. */ + public consistencySelector?: "readTime"; - /** EnumReservedRange start */ - start?: (number|null); + /** + * Creates a ReadOnly message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns ReadOnly + */ + public static fromObject(object: { [k: string]: any }): google.firestore.v1.TransactionOptions.ReadOnly; - /** EnumReservedRange end */ - end?: (number|null); + /** + * Creates a plain object from a ReadOnly message. Also converts values to other types if specified. + * @param message ReadOnly + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.firestore.v1.TransactionOptions.ReadOnly, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this ReadOnly to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for ReadOnly + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } } - /** Represents an EnumReservedRange. */ - class EnumReservedRange implements IEnumReservedRange { + /** Represents a Firestore */ + class Firestore extends $protobuf.rpc.Service { /** - * Constructs a new EnumReservedRange. - * @param [properties] Properties to set + * Constructs a new Firestore service. + * @param rpcImpl RPC implementation + * @param [requestDelimited=false] Whether requests are length-delimited + * @param [responseDelimited=false] Whether responses are length-delimited */ - constructor(properties?: google.protobuf.EnumDescriptorProto.IEnumReservedRange); + constructor(rpcImpl: $protobuf.RPCImpl, requestDelimited?: boolean, responseDelimited?: boolean); - /** EnumReservedRange start. */ - public start: number; + /** + * Calls GetDocument. + * @param request GetDocumentRequest message or plain object + * @param callback Node-style callback called with the error, if any, and Document + */ + public getDocument(request: google.firestore.v1.IGetDocumentRequest, callback: google.firestore.v1.Firestore.GetDocumentCallback): void; - /** EnumReservedRange end. */ - public end: number; + /** + * Calls GetDocument. + * @param request GetDocumentRequest message or plain object + * @returns Promise + */ + public getDocument(request: google.firestore.v1.IGetDocumentRequest): Promise; /** - * Creates an EnumReservedRange message from a plain object. Also converts values to their respective internal types. - * @param object Plain object - * @returns EnumReservedRange + * Calls ListDocuments. + * @param request ListDocumentsRequest message or plain object + * @param callback Node-style callback called with the error, if any, and ListDocumentsResponse */ - public static fromObject(object: { [k: string]: any }): google.protobuf.EnumDescriptorProto.EnumReservedRange; + public listDocuments(request: google.firestore.v1.IListDocumentsRequest, callback: google.firestore.v1.Firestore.ListDocumentsCallback): void; /** - * Creates a plain object from an EnumReservedRange message. Also converts values to other types if specified. - * @param message EnumReservedRange - * @param [options] Conversion options - * @returns Plain object + * Calls ListDocuments. + * @param request ListDocumentsRequest message or plain object + * @returns Promise */ - public static toObject(message: google.protobuf.EnumDescriptorProto.EnumReservedRange, options?: $protobuf.IConversionOptions): { [k: string]: any }; + public listDocuments(request: google.firestore.v1.IListDocumentsRequest): Promise; /** - * Converts this EnumReservedRange to JSON. - * @returns JSON object + * Calls UpdateDocument. + * @param request UpdateDocumentRequest message or plain object + * @param callback Node-style callback called with the error, if any, and Document */ - public toJSON(): { [k: string]: any }; + public updateDocument(request: google.firestore.v1.IUpdateDocumentRequest, callback: google.firestore.v1.Firestore.UpdateDocumentCallback): void; /** - * Gets the default type url for EnumReservedRange - * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") - * @returns The default type url + * Calls UpdateDocument. + * @param request UpdateDocumentRequest message or plain object + * @returns Promise */ - public static getTypeUrl(typeUrlPrefix?: string): string; - } - } + public updateDocument(request: google.firestore.v1.IUpdateDocumentRequest): Promise; - /** Properties of an EnumValueDescriptorProto. */ - interface IEnumValueDescriptorProto { + /** + * Calls DeleteDocument. + * @param request DeleteDocumentRequest message or plain object + * @param callback Node-style callback called with the error, if any, and Empty + */ + public deleteDocument(request: google.firestore.v1.IDeleteDocumentRequest, callback: google.firestore.v1.Firestore.DeleteDocumentCallback): void; - /** EnumValueDescriptorProto name */ - name?: (string|null); + /** + * Calls DeleteDocument. + * @param request DeleteDocumentRequest message or plain object + * @returns Promise + */ + public deleteDocument(request: google.firestore.v1.IDeleteDocumentRequest): Promise; - /** EnumValueDescriptorProto number */ - number?: (number|null); + /** + * Calls BatchGetDocuments. + * @param request BatchGetDocumentsRequest message or plain object + * @param callback Node-style callback called with the error, if any, and BatchGetDocumentsResponse + */ + public batchGetDocuments(request: google.firestore.v1.IBatchGetDocumentsRequest, callback: google.firestore.v1.Firestore.BatchGetDocumentsCallback): void; - /** EnumValueDescriptorProto options */ - options?: (google.protobuf.IEnumValueOptions|null); - } + /** + * Calls BatchGetDocuments. + * @param request BatchGetDocumentsRequest message or plain object + * @returns Promise + */ + public batchGetDocuments(request: google.firestore.v1.IBatchGetDocumentsRequest): Promise; - /** Represents an EnumValueDescriptorProto. */ - class EnumValueDescriptorProto implements IEnumValueDescriptorProto { + /** + * Calls BeginTransaction. + * @param request BeginTransactionRequest message or plain object + * @param callback Node-style callback called with the error, if any, and BeginTransactionResponse + */ + public beginTransaction(request: google.firestore.v1.IBeginTransactionRequest, callback: google.firestore.v1.Firestore.BeginTransactionCallback): void; - /** - * Constructs a new EnumValueDescriptorProto. - * @param [properties] Properties to set - */ - constructor(properties?: google.protobuf.IEnumValueDescriptorProto); + /** + * Calls BeginTransaction. + * @param request BeginTransactionRequest message or plain object + * @returns Promise + */ + public beginTransaction(request: google.firestore.v1.IBeginTransactionRequest): Promise; - /** EnumValueDescriptorProto name. */ - public name: string; + /** + * Calls Commit. + * @param request CommitRequest message or plain object + * @param callback Node-style callback called with the error, if any, and CommitResponse + */ + public commit(request: google.firestore.v1.ICommitRequest, callback: google.firestore.v1.Firestore.CommitCallback): void; - /** EnumValueDescriptorProto number. */ - public number: number; - - /** EnumValueDescriptorProto options. */ - public options?: (google.protobuf.IEnumValueOptions|null); + /** + * Calls Commit. + * @param request CommitRequest message or plain object + * @returns Promise + */ + public commit(request: google.firestore.v1.ICommitRequest): Promise; - /** - * Creates an EnumValueDescriptorProto message from a plain object. Also converts values to their respective internal types. - * @param object Plain object - * @returns EnumValueDescriptorProto - */ - public static fromObject(object: { [k: string]: any }): google.protobuf.EnumValueDescriptorProto; + /** + * Calls Rollback. + * @param request RollbackRequest message or plain object + * @param callback Node-style callback called with the error, if any, and Empty + */ + public rollback(request: google.firestore.v1.IRollbackRequest, callback: google.firestore.v1.Firestore.RollbackCallback): void; - /** - * Creates a plain object from an EnumValueDescriptorProto message. Also converts values to other types if specified. - * @param message EnumValueDescriptorProto - * @param [options] Conversion options - * @returns Plain object - */ - public static toObject(message: google.protobuf.EnumValueDescriptorProto, options?: $protobuf.IConversionOptions): { [k: string]: any }; + /** + * Calls Rollback. + * @param request RollbackRequest message or plain object + * @returns Promise + */ + public rollback(request: google.firestore.v1.IRollbackRequest): Promise; - /** - * Converts this EnumValueDescriptorProto to JSON. - * @returns JSON object - */ - public toJSON(): { [k: string]: any }; + /** + * Calls RunQuery. + * @param request RunQueryRequest message or plain object + * @param callback Node-style callback called with the error, if any, and RunQueryResponse + */ + public runQuery(request: google.firestore.v1.IRunQueryRequest, callback: google.firestore.v1.Firestore.RunQueryCallback): void; - /** - * Gets the default type url for EnumValueDescriptorProto - * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") - * @returns The default type url - */ - public static getTypeUrl(typeUrlPrefix?: string): string; - } + /** + * Calls RunQuery. + * @param request RunQueryRequest message or plain object + * @returns Promise + */ + public runQuery(request: google.firestore.v1.IRunQueryRequest): Promise; - /** Properties of a ServiceDescriptorProto. */ - interface IServiceDescriptorProto { + /** + * Calls ExecutePipeline. + * @param request ExecutePipelineRequest message or plain object + * @param callback Node-style callback called with the error, if any, and ExecutePipelineResponse + */ + public executePipeline(request: google.firestore.v1.IExecutePipelineRequest, callback: google.firestore.v1.Firestore.ExecutePipelineCallback): void; - /** ServiceDescriptorProto name */ - name?: (string|null); + /** + * Calls ExecutePipeline. + * @param request ExecutePipelineRequest message or plain object + * @returns Promise + */ + public executePipeline(request: google.firestore.v1.IExecutePipelineRequest): Promise; - /** ServiceDescriptorProto method */ - method?: (google.protobuf.IMethodDescriptorProto[]|null); + /** + * Calls RunAggregationQuery. + * @param request RunAggregationQueryRequest message or plain object + * @param callback Node-style callback called with the error, if any, and RunAggregationQueryResponse + */ + public runAggregationQuery(request: google.firestore.v1.IRunAggregationQueryRequest, callback: google.firestore.v1.Firestore.RunAggregationQueryCallback): void; - /** ServiceDescriptorProto options */ - options?: (google.protobuf.IServiceOptions|null); - } + /** + * Calls RunAggregationQuery. + * @param request RunAggregationQueryRequest message or plain object + * @returns Promise + */ + public runAggregationQuery(request: google.firestore.v1.IRunAggregationQueryRequest): Promise; - /** Represents a ServiceDescriptorProto. */ - class ServiceDescriptorProto implements IServiceDescriptorProto { + /** + * Calls PartitionQuery. + * @param request PartitionQueryRequest message or plain object + * @param callback Node-style callback called with the error, if any, and PartitionQueryResponse + */ + public partitionQuery(request: google.firestore.v1.IPartitionQueryRequest, callback: google.firestore.v1.Firestore.PartitionQueryCallback): void; - /** - * Constructs a new ServiceDescriptorProto. - * @param [properties] Properties to set - */ - constructor(properties?: google.protobuf.IServiceDescriptorProto); + /** + * Calls PartitionQuery. + * @param request PartitionQueryRequest message or plain object + * @returns Promise + */ + public partitionQuery(request: google.firestore.v1.IPartitionQueryRequest): Promise; - /** ServiceDescriptorProto name. */ - public name: string; + /** + * Calls Write. + * @param request WriteRequest message or plain object + * @param callback Node-style callback called with the error, if any, and WriteResponse + */ + public write(request: google.firestore.v1.IWriteRequest, callback: google.firestore.v1.Firestore.WriteCallback): void; - /** ServiceDescriptorProto method. */ - public method: google.protobuf.IMethodDescriptorProto[]; + /** + * Calls Write. + * @param request WriteRequest message or plain object + * @returns Promise + */ + public write(request: google.firestore.v1.IWriteRequest): Promise; - /** ServiceDescriptorProto options. */ - public options?: (google.protobuf.IServiceOptions|null); + /** + * Calls Listen. + * @param request ListenRequest message or plain object + * @param callback Node-style callback called with the error, if any, and ListenResponse + */ + public listen(request: google.firestore.v1.IListenRequest, callback: google.firestore.v1.Firestore.ListenCallback): void; - /** - * Creates a ServiceDescriptorProto message from a plain object. Also converts values to their respective internal types. - * @param object Plain object - * @returns ServiceDescriptorProto - */ - public static fromObject(object: { [k: string]: any }): google.protobuf.ServiceDescriptorProto; + /** + * Calls Listen. + * @param request ListenRequest message or plain object + * @returns Promise + */ + public listen(request: google.firestore.v1.IListenRequest): Promise; - /** - * Creates a plain object from a ServiceDescriptorProto message. Also converts values to other types if specified. - * @param message ServiceDescriptorProto - * @param [options] Conversion options - * @returns Plain object - */ - public static toObject(message: google.protobuf.ServiceDescriptorProto, options?: $protobuf.IConversionOptions): { [k: string]: any }; + /** + * Calls ListCollectionIds. + * @param request ListCollectionIdsRequest message or plain object + * @param callback Node-style callback called with the error, if any, and ListCollectionIdsResponse + */ + public listCollectionIds(request: google.firestore.v1.IListCollectionIdsRequest, callback: google.firestore.v1.Firestore.ListCollectionIdsCallback): void; - /** - * Converts this ServiceDescriptorProto to JSON. - * @returns JSON object - */ - public toJSON(): { [k: string]: any }; + /** + * Calls ListCollectionIds. + * @param request ListCollectionIdsRequest message or plain object + * @returns Promise + */ + public listCollectionIds(request: google.firestore.v1.IListCollectionIdsRequest): Promise; - /** - * Gets the default type url for ServiceDescriptorProto - * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") - * @returns The default type url - */ - public static getTypeUrl(typeUrlPrefix?: string): string; - } + /** + * Calls BatchWrite. + * @param request BatchWriteRequest message or plain object + * @param callback Node-style callback called with the error, if any, and BatchWriteResponse + */ + public batchWrite(request: google.firestore.v1.IBatchWriteRequest, callback: google.firestore.v1.Firestore.BatchWriteCallback): void; - /** Properties of a MethodDescriptorProto. */ - interface IMethodDescriptorProto { + /** + * Calls BatchWrite. + * @param request BatchWriteRequest message or plain object + * @returns Promise + */ + public batchWrite(request: google.firestore.v1.IBatchWriteRequest): Promise; - /** MethodDescriptorProto name */ - name?: (string|null); + /** + * Calls CreateDocument. + * @param request CreateDocumentRequest message or plain object + * @param callback Node-style callback called with the error, if any, and Document + */ + public createDocument(request: google.firestore.v1.ICreateDocumentRequest, callback: google.firestore.v1.Firestore.CreateDocumentCallback): void; - /** MethodDescriptorProto inputType */ - inputType?: (string|null); + /** + * Calls CreateDocument. + * @param request CreateDocumentRequest message or plain object + * @returns Promise + */ + public createDocument(request: google.firestore.v1.ICreateDocumentRequest): Promise; + } - /** MethodDescriptorProto outputType */ - outputType?: (string|null); + namespace Firestore { - /** MethodDescriptorProto options */ - options?: (google.protobuf.IMethodOptions|null); + /** + * Callback as used by {@link google.firestore.v1.Firestore#getDocument}. + * @param error Error, if any + * @param [response] Document + */ + type GetDocumentCallback = (error: (Error|null), response?: google.firestore.v1.Document) => void; - /** MethodDescriptorProto clientStreaming */ - clientStreaming?: (boolean|null); + /** + * Callback as used by {@link google.firestore.v1.Firestore#listDocuments}. + * @param error Error, if any + * @param [response] ListDocumentsResponse + */ + type ListDocumentsCallback = (error: (Error|null), response?: google.firestore.v1.ListDocumentsResponse) => void; - /** MethodDescriptorProto serverStreaming */ - serverStreaming?: (boolean|null); - } + /** + * Callback as used by {@link google.firestore.v1.Firestore#updateDocument}. + * @param error Error, if any + * @param [response] Document + */ + type UpdateDocumentCallback = (error: (Error|null), response?: google.firestore.v1.Document) => void; - /** Represents a MethodDescriptorProto. */ - class MethodDescriptorProto implements IMethodDescriptorProto { + /** + * Callback as used by {@link google.firestore.v1.Firestore#deleteDocument}. + * @param error Error, if any + * @param [response] Empty + */ + type DeleteDocumentCallback = (error: (Error|null), response?: google.protobuf.Empty) => void; - /** - * Constructs a new MethodDescriptorProto. - * @param [properties] Properties to set - */ - constructor(properties?: google.protobuf.IMethodDescriptorProto); + /** + * Callback as used by {@link google.firestore.v1.Firestore#batchGetDocuments}. + * @param error Error, if any + * @param [response] BatchGetDocumentsResponse + */ + type BatchGetDocumentsCallback = (error: (Error|null), response?: google.firestore.v1.BatchGetDocumentsResponse) => void; - /** MethodDescriptorProto name. */ - public name: string; + /** + * Callback as used by {@link google.firestore.v1.Firestore#beginTransaction}. + * @param error Error, if any + * @param [response] BeginTransactionResponse + */ + type BeginTransactionCallback = (error: (Error|null), response?: google.firestore.v1.BeginTransactionResponse) => void; - /** MethodDescriptorProto inputType. */ - public inputType: string; + /** + * Callback as used by {@link google.firestore.v1.Firestore#commit}. + * @param error Error, if any + * @param [response] CommitResponse + */ + type CommitCallback = (error: (Error|null), response?: google.firestore.v1.CommitResponse) => void; - /** MethodDescriptorProto outputType. */ - public outputType: string; + /** + * Callback as used by {@link google.firestore.v1.Firestore#rollback}. + * @param error Error, if any + * @param [response] Empty + */ + type RollbackCallback = (error: (Error|null), response?: google.protobuf.Empty) => void; - /** MethodDescriptorProto options. */ - public options?: (google.protobuf.IMethodOptions|null); + /** + * Callback as used by {@link google.firestore.v1.Firestore#runQuery}. + * @param error Error, if any + * @param [response] RunQueryResponse + */ + type RunQueryCallback = (error: (Error|null), response?: google.firestore.v1.RunQueryResponse) => void; - /** MethodDescriptorProto clientStreaming. */ - public clientStreaming: boolean; + /** + * Callback as used by {@link google.firestore.v1.Firestore#executePipeline}. + * @param error Error, if any + * @param [response] ExecutePipelineResponse + */ + type ExecutePipelineCallback = (error: (Error|null), response?: google.firestore.v1.ExecutePipelineResponse) => void; - /** MethodDescriptorProto serverStreaming. */ - public serverStreaming: boolean; + /** + * Callback as used by {@link google.firestore.v1.Firestore#runAggregationQuery}. + * @param error Error, if any + * @param [response] RunAggregationQueryResponse + */ + type RunAggregationQueryCallback = (error: (Error|null), response?: google.firestore.v1.RunAggregationQueryResponse) => void; - /** - * Creates a MethodDescriptorProto message from a plain object. Also converts values to their respective internal types. - * @param object Plain object - * @returns MethodDescriptorProto - */ - public static fromObject(object: { [k: string]: any }): google.protobuf.MethodDescriptorProto; + /** + * Callback as used by {@link google.firestore.v1.Firestore#partitionQuery}. + * @param error Error, if any + * @param [response] PartitionQueryResponse + */ + type PartitionQueryCallback = (error: (Error|null), response?: google.firestore.v1.PartitionQueryResponse) => void; - /** - * Creates a plain object from a MethodDescriptorProto message. Also converts values to other types if specified. - * @param message MethodDescriptorProto - * @param [options] Conversion options - * @returns Plain object - */ - public static toObject(message: google.protobuf.MethodDescriptorProto, options?: $protobuf.IConversionOptions): { [k: string]: any }; + /** + * Callback as used by {@link google.firestore.v1.Firestore#write}. + * @param error Error, if any + * @param [response] WriteResponse + */ + type WriteCallback = (error: (Error|null), response?: google.firestore.v1.WriteResponse) => void; - /** - * Converts this MethodDescriptorProto to JSON. - * @returns JSON object - */ - public toJSON(): { [k: string]: any }; + /** + * Callback as used by {@link google.firestore.v1.Firestore#listen}. + * @param error Error, if any + * @param [response] ListenResponse + */ + type ListenCallback = (error: (Error|null), response?: google.firestore.v1.ListenResponse) => void; - /** - * Gets the default type url for MethodDescriptorProto - * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") - * @returns The default type url - */ - public static getTypeUrl(typeUrlPrefix?: string): string; - } + /** + * Callback as used by {@link google.firestore.v1.Firestore#listCollectionIds}. + * @param error Error, if any + * @param [response] ListCollectionIdsResponse + */ + type ListCollectionIdsCallback = (error: (Error|null), response?: google.firestore.v1.ListCollectionIdsResponse) => void; - /** Properties of a FileOptions. */ - interface IFileOptions { + /** + * Callback as used by {@link google.firestore.v1.Firestore#batchWrite}. + * @param error Error, if any + * @param [response] BatchWriteResponse + */ + type BatchWriteCallback = (error: (Error|null), response?: google.firestore.v1.BatchWriteResponse) => void; - /** FileOptions javaPackage */ - javaPackage?: (string|null); + /** + * Callback as used by {@link google.firestore.v1.Firestore#createDocument}. + * @param error Error, if any + * @param [response] Document + */ + type CreateDocumentCallback = (error: (Error|null), response?: google.firestore.v1.Document) => void; + } - /** FileOptions javaOuterClassname */ - javaOuterClassname?: (string|null); + /** Properties of a GetDocumentRequest. */ + interface IGetDocumentRequest { - /** FileOptions javaMultipleFiles */ - javaMultipleFiles?: (boolean|null); + /** GetDocumentRequest name */ + name?: (string|null); - /** FileOptions javaGenerateEqualsAndHash */ - javaGenerateEqualsAndHash?: (boolean|null); + /** GetDocumentRequest mask */ + mask?: (google.firestore.v1.IDocumentMask|null); - /** FileOptions javaStringCheckUtf8 */ - javaStringCheckUtf8?: (boolean|null); + /** GetDocumentRequest transaction */ + transaction?: (Uint8Array|null); - /** FileOptions optimizeFor */ - optimizeFor?: (google.protobuf.FileOptions.OptimizeMode|null); + /** GetDocumentRequest readTime */ + readTime?: (google.protobuf.ITimestamp|null); + } - /** FileOptions goPackage */ - goPackage?: (string|null); + /** Represents a GetDocumentRequest. */ + class GetDocumentRequest implements IGetDocumentRequest { - /** FileOptions ccGenericServices */ - ccGenericServices?: (boolean|null); + /** + * Constructs a new GetDocumentRequest. + * @param [properties] Properties to set + */ + constructor(properties?: google.firestore.v1.IGetDocumentRequest); - /** FileOptions javaGenericServices */ - javaGenericServices?: (boolean|null); + /** GetDocumentRequest name. */ + public name: string; - /** FileOptions pyGenericServices */ - pyGenericServices?: (boolean|null); + /** GetDocumentRequest mask. */ + public mask?: (google.firestore.v1.IDocumentMask|null); - /** FileOptions deprecated */ - deprecated?: (boolean|null); + /** GetDocumentRequest transaction. */ + public transaction?: (Uint8Array|null); - /** FileOptions ccEnableArenas */ - ccEnableArenas?: (boolean|null); + /** GetDocumentRequest readTime. */ + public readTime?: (google.protobuf.ITimestamp|null); - /** FileOptions objcClassPrefix */ - objcClassPrefix?: (string|null); + /** GetDocumentRequest consistencySelector. */ + public consistencySelector?: ("transaction"|"readTime"); - /** FileOptions csharpNamespace */ - csharpNamespace?: (string|null); + /** + * Creates a GetDocumentRequest message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns GetDocumentRequest + */ + public static fromObject(object: { [k: string]: any }): google.firestore.v1.GetDocumentRequest; - /** FileOptions swiftPrefix */ - swiftPrefix?: (string|null); + /** + * Creates a plain object from a GetDocumentRequest message. Also converts values to other types if specified. + * @param message GetDocumentRequest + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.firestore.v1.GetDocumentRequest, options?: $protobuf.IConversionOptions): { [k: string]: any }; - /** FileOptions phpClassPrefix */ - phpClassPrefix?: (string|null); + /** + * Converts this GetDocumentRequest to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; - /** FileOptions phpNamespace */ - phpNamespace?: (string|null); + /** + * Gets the default type url for GetDocumentRequest + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } - /** FileOptions phpMetadataNamespace */ - phpMetadataNamespace?: (string|null); + /** Properties of a ListDocumentsRequest. */ + interface IListDocumentsRequest { - /** FileOptions rubyPackage */ - rubyPackage?: (string|null); + /** ListDocumentsRequest parent */ + parent?: (string|null); - /** FileOptions features */ - features?: (google.protobuf.IFeatureSet|null); + /** ListDocumentsRequest collectionId */ + collectionId?: (string|null); - /** FileOptions uninterpretedOption */ - uninterpretedOption?: (google.protobuf.IUninterpretedOption[]|null); + /** ListDocumentsRequest pageSize */ + pageSize?: (number|null); - /** FileOptions .google.api.resourceDefinition */ - ".google.api.resourceDefinition"?: (google.api.IResourceDescriptor[]|null); - } + /** ListDocumentsRequest pageToken */ + pageToken?: (string|null); - /** Represents a FileOptions. */ - class FileOptions implements IFileOptions { + /** ListDocumentsRequest orderBy */ + orderBy?: (string|null); - /** - * Constructs a new FileOptions. - * @param [properties] Properties to set - */ - constructor(properties?: google.protobuf.IFileOptions); + /** ListDocumentsRequest mask */ + mask?: (google.firestore.v1.IDocumentMask|null); - /** FileOptions javaPackage. */ - public javaPackage: string; + /** ListDocumentsRequest transaction */ + transaction?: (Uint8Array|null); - /** FileOptions javaOuterClassname. */ - public javaOuterClassname: string; + /** ListDocumentsRequest readTime */ + readTime?: (google.protobuf.ITimestamp|null); - /** FileOptions javaMultipleFiles. */ - public javaMultipleFiles: boolean; + /** ListDocumentsRequest showMissing */ + showMissing?: (boolean|null); + } - /** FileOptions javaGenerateEqualsAndHash. */ - public javaGenerateEqualsAndHash: boolean; + /** Represents a ListDocumentsRequest. */ + class ListDocumentsRequest implements IListDocumentsRequest { - /** FileOptions javaStringCheckUtf8. */ - public javaStringCheckUtf8: boolean; + /** + * Constructs a new ListDocumentsRequest. + * @param [properties] Properties to set + */ + constructor(properties?: google.firestore.v1.IListDocumentsRequest); - /** FileOptions optimizeFor. */ - public optimizeFor: google.protobuf.FileOptions.OptimizeMode; + /** ListDocumentsRequest parent. */ + public parent: string; - /** FileOptions goPackage. */ - public goPackage: string; + /** ListDocumentsRequest collectionId. */ + public collectionId: string; - /** FileOptions ccGenericServices. */ - public ccGenericServices: boolean; + /** ListDocumentsRequest pageSize. */ + public pageSize: number; - /** FileOptions javaGenericServices. */ - public javaGenericServices: boolean; + /** ListDocumentsRequest pageToken. */ + public pageToken: string; - /** FileOptions pyGenericServices. */ - public pyGenericServices: boolean; + /** ListDocumentsRequest orderBy. */ + public orderBy: string; - /** FileOptions deprecated. */ - public deprecated: boolean; + /** ListDocumentsRequest mask. */ + public mask?: (google.firestore.v1.IDocumentMask|null); - /** FileOptions ccEnableArenas. */ - public ccEnableArenas: boolean; + /** ListDocumentsRequest transaction. */ + public transaction?: (Uint8Array|null); - /** FileOptions objcClassPrefix. */ - public objcClassPrefix: string; + /** ListDocumentsRequest readTime. */ + public readTime?: (google.protobuf.ITimestamp|null); - /** FileOptions csharpNamespace. */ - public csharpNamespace: string; + /** ListDocumentsRequest showMissing. */ + public showMissing: boolean; - /** FileOptions swiftPrefix. */ - public swiftPrefix: string; + /** ListDocumentsRequest consistencySelector. */ + public consistencySelector?: ("transaction"|"readTime"); - /** FileOptions phpClassPrefix. */ - public phpClassPrefix: string; + /** + * Creates a ListDocumentsRequest message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns ListDocumentsRequest + */ + public static fromObject(object: { [k: string]: any }): google.firestore.v1.ListDocumentsRequest; - /** FileOptions phpNamespace. */ - public phpNamespace: string; + /** + * Creates a plain object from a ListDocumentsRequest message. Also converts values to other types if specified. + * @param message ListDocumentsRequest + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.firestore.v1.ListDocumentsRequest, options?: $protobuf.IConversionOptions): { [k: string]: any }; - /** FileOptions phpMetadataNamespace. */ - public phpMetadataNamespace: string; + /** + * Converts this ListDocumentsRequest to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; - /** FileOptions rubyPackage. */ - public rubyPackage: string; + /** + * Gets the default type url for ListDocumentsRequest + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } - /** FileOptions features. */ - public features?: (google.protobuf.IFeatureSet|null); + /** Properties of a ListDocumentsResponse. */ + interface IListDocumentsResponse { - /** FileOptions uninterpretedOption. */ - public uninterpretedOption: google.protobuf.IUninterpretedOption[]; + /** ListDocumentsResponse documents */ + documents?: (google.firestore.v1.IDocument[]|null); - /** - * Creates a FileOptions message from a plain object. Also converts values to their respective internal types. - * @param object Plain object - * @returns FileOptions - */ - public static fromObject(object: { [k: string]: any }): google.protobuf.FileOptions; + /** ListDocumentsResponse nextPageToken */ + nextPageToken?: (string|null); + } - /** - * Creates a plain object from a FileOptions message. Also converts values to other types if specified. - * @param message FileOptions - * @param [options] Conversion options - * @returns Plain object - */ - public static toObject(message: google.protobuf.FileOptions, options?: $protobuf.IConversionOptions): { [k: string]: any }; + /** Represents a ListDocumentsResponse. */ + class ListDocumentsResponse implements IListDocumentsResponse { - /** - * Converts this FileOptions to JSON. - * @returns JSON object - */ - public toJSON(): { [k: string]: any }; + /** + * Constructs a new ListDocumentsResponse. + * @param [properties] Properties to set + */ + constructor(properties?: google.firestore.v1.IListDocumentsResponse); - /** - * Gets the default type url for FileOptions - * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") - * @returns The default type url - */ - public static getTypeUrl(typeUrlPrefix?: string): string; - } + /** ListDocumentsResponse documents. */ + public documents: google.firestore.v1.IDocument[]; - namespace FileOptions { + /** ListDocumentsResponse nextPageToken. */ + public nextPageToken: string; - /** OptimizeMode enum. */ - type OptimizeMode = - "SPEED"| "CODE_SIZE"| "LITE_RUNTIME"; - } + /** + * Creates a ListDocumentsResponse message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns ListDocumentsResponse + */ + public static fromObject(object: { [k: string]: any }): google.firestore.v1.ListDocumentsResponse; - /** Properties of a MessageOptions. */ - interface IMessageOptions { + /** + * Creates a plain object from a ListDocumentsResponse message. Also converts values to other types if specified. + * @param message ListDocumentsResponse + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.firestore.v1.ListDocumentsResponse, options?: $protobuf.IConversionOptions): { [k: string]: any }; - /** MessageOptions messageSetWireFormat */ - messageSetWireFormat?: (boolean|null); + /** + * Converts this ListDocumentsResponse to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; - /** MessageOptions noStandardDescriptorAccessor */ - noStandardDescriptorAccessor?: (boolean|null); + /** + * Gets the default type url for ListDocumentsResponse + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } - /** MessageOptions deprecated */ - deprecated?: (boolean|null); + /** Properties of a CreateDocumentRequest. */ + interface ICreateDocumentRequest { - /** MessageOptions mapEntry */ - mapEntry?: (boolean|null); + /** CreateDocumentRequest parent */ + parent?: (string|null); - /** MessageOptions deprecatedLegacyJsonFieldConflicts */ - deprecatedLegacyJsonFieldConflicts?: (boolean|null); + /** CreateDocumentRequest collectionId */ + collectionId?: (string|null); - /** MessageOptions features */ - features?: (google.protobuf.IFeatureSet|null); + /** CreateDocumentRequest documentId */ + documentId?: (string|null); - /** MessageOptions uninterpretedOption */ - uninterpretedOption?: (google.protobuf.IUninterpretedOption[]|null); + /** CreateDocumentRequest document */ + document?: (google.firestore.v1.IDocument|null); - /** MessageOptions .google.api.resource */ - ".google.api.resource"?: (google.api.IResourceDescriptor|null); - } + /** CreateDocumentRequest mask */ + mask?: (google.firestore.v1.IDocumentMask|null); + } - /** Represents a MessageOptions. */ - class MessageOptions implements IMessageOptions { + /** Represents a CreateDocumentRequest. */ + class CreateDocumentRequest implements ICreateDocumentRequest { - /** - * Constructs a new MessageOptions. - * @param [properties] Properties to set - */ - constructor(properties?: google.protobuf.IMessageOptions); + /** + * Constructs a new CreateDocumentRequest. + * @param [properties] Properties to set + */ + constructor(properties?: google.firestore.v1.ICreateDocumentRequest); - /** MessageOptions messageSetWireFormat. */ - public messageSetWireFormat: boolean; + /** CreateDocumentRequest parent. */ + public parent: string; - /** MessageOptions noStandardDescriptorAccessor. */ - public noStandardDescriptorAccessor: boolean; + /** CreateDocumentRequest collectionId. */ + public collectionId: string; - /** MessageOptions deprecated. */ - public deprecated: boolean; + /** CreateDocumentRequest documentId. */ + public documentId: string; - /** MessageOptions mapEntry. */ - public mapEntry: boolean; + /** CreateDocumentRequest document. */ + public document?: (google.firestore.v1.IDocument|null); - /** MessageOptions deprecatedLegacyJsonFieldConflicts. */ - public deprecatedLegacyJsonFieldConflicts: boolean; + /** CreateDocumentRequest mask. */ + public mask?: (google.firestore.v1.IDocumentMask|null); - /** MessageOptions features. */ - public features?: (google.protobuf.IFeatureSet|null); + /** + * Creates a CreateDocumentRequest message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns CreateDocumentRequest + */ + public static fromObject(object: { [k: string]: any }): google.firestore.v1.CreateDocumentRequest; - /** MessageOptions uninterpretedOption. */ - public uninterpretedOption: google.protobuf.IUninterpretedOption[]; + /** + * Creates a plain object from a CreateDocumentRequest message. Also converts values to other types if specified. + * @param message CreateDocumentRequest + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.firestore.v1.CreateDocumentRequest, options?: $protobuf.IConversionOptions): { [k: string]: any }; - /** - * Creates a MessageOptions message from a plain object. Also converts values to their respective internal types. - * @param object Plain object - * @returns MessageOptions - */ - public static fromObject(object: { [k: string]: any }): google.protobuf.MessageOptions; + /** + * Converts this CreateDocumentRequest to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; - /** - * Creates a plain object from a MessageOptions message. Also converts values to other types if specified. - * @param message MessageOptions - * @param [options] Conversion options - * @returns Plain object - */ - public static toObject(message: google.protobuf.MessageOptions, options?: $protobuf.IConversionOptions): { [k: string]: any }; + /** + * Gets the default type url for CreateDocumentRequest + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } - /** - * Converts this MessageOptions to JSON. - * @returns JSON object - */ - public toJSON(): { [k: string]: any }; - - /** - * Gets the default type url for MessageOptions - * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") - * @returns The default type url - */ - public static getTypeUrl(typeUrlPrefix?: string): string; - } - - /** Properties of a FieldOptions. */ - interface IFieldOptions { - - /** FieldOptions ctype */ - ctype?: (google.protobuf.FieldOptions.CType|null); - - /** FieldOptions packed */ - packed?: (boolean|null); - - /** FieldOptions jstype */ - jstype?: (google.protobuf.FieldOptions.JSType|null); - - /** FieldOptions lazy */ - lazy?: (boolean|null); - - /** FieldOptions unverifiedLazy */ - unverifiedLazy?: (boolean|null); - - /** FieldOptions deprecated */ - deprecated?: (boolean|null); - - /** FieldOptions weak */ - weak?: (boolean|null); - - /** FieldOptions debugRedact */ - debugRedact?: (boolean|null); - - /** FieldOptions retention */ - retention?: (google.protobuf.FieldOptions.OptionRetention|null); - - /** FieldOptions targets */ - targets?: (google.protobuf.FieldOptions.OptionTargetType[]|null); - - /** FieldOptions editionDefaults */ - editionDefaults?: (google.protobuf.FieldOptions.IEditionDefault[]|null); - - /** FieldOptions features */ - features?: (google.protobuf.IFeatureSet|null); - - /** FieldOptions featureSupport */ - featureSupport?: (google.protobuf.FieldOptions.IFeatureSupport|null); - - /** FieldOptions uninterpretedOption */ - uninterpretedOption?: (google.protobuf.IUninterpretedOption[]|null); - - /** FieldOptions .google.api.fieldBehavior */ - ".google.api.fieldBehavior"?: (google.api.FieldBehavior[]|null); - - /** FieldOptions .google.api.resourceReference */ - ".google.api.resourceReference"?: (google.api.IResourceReference|null); - } - - /** Represents a FieldOptions. */ - class FieldOptions implements IFieldOptions { - - /** - * Constructs a new FieldOptions. - * @param [properties] Properties to set - */ - constructor(properties?: google.protobuf.IFieldOptions); - - /** FieldOptions ctype. */ - public ctype: google.protobuf.FieldOptions.CType; - - /** FieldOptions packed. */ - public packed: boolean; - - /** FieldOptions jstype. */ - public jstype: google.protobuf.FieldOptions.JSType; - - /** FieldOptions lazy. */ - public lazy: boolean; - - /** FieldOptions unverifiedLazy. */ - public unverifiedLazy: boolean; - - /** FieldOptions deprecated. */ - public deprecated: boolean; - - /** FieldOptions weak. */ - public weak: boolean; - - /** FieldOptions debugRedact. */ - public debugRedact: boolean; - - /** FieldOptions retention. */ - public retention: google.protobuf.FieldOptions.OptionRetention; - - /** FieldOptions targets. */ - public targets: google.protobuf.FieldOptions.OptionTargetType[]; - - /** FieldOptions editionDefaults. */ - public editionDefaults: google.protobuf.FieldOptions.IEditionDefault[]; - - /** FieldOptions features. */ - public features?: (google.protobuf.IFeatureSet|null); - - /** FieldOptions featureSupport. */ - public featureSupport?: (google.protobuf.FieldOptions.IFeatureSupport|null); - - /** FieldOptions uninterpretedOption. */ - public uninterpretedOption: google.protobuf.IUninterpretedOption[]; - - /** - * Creates a FieldOptions message from a plain object. Also converts values to their respective internal types. - * @param object Plain object - * @returns FieldOptions - */ - public static fromObject(object: { [k: string]: any }): google.protobuf.FieldOptions; - - /** - * Creates a plain object from a FieldOptions message. Also converts values to other types if specified. - * @param message FieldOptions - * @param [options] Conversion options - * @returns Plain object - */ - public static toObject(message: google.protobuf.FieldOptions, options?: $protobuf.IConversionOptions): { [k: string]: any }; - - /** - * Converts this FieldOptions to JSON. - * @returns JSON object - */ - public toJSON(): { [k: string]: any }; - - /** - * Gets the default type url for FieldOptions - * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") - * @returns The default type url - */ - public static getTypeUrl(typeUrlPrefix?: string): string; - } - - namespace FieldOptions { - - /** CType enum. */ - type CType = - "STRING"| "CORD"| "STRING_PIECE"; - - /** JSType enum. */ - type JSType = - "JS_NORMAL"| "JS_STRING"| "JS_NUMBER"; - - /** OptionRetention enum. */ - type OptionRetention = - "RETENTION_UNKNOWN"| "RETENTION_RUNTIME"| "RETENTION_SOURCE"; + /** Properties of an UpdateDocumentRequest. */ + interface IUpdateDocumentRequest { - /** OptionTargetType enum. */ - type OptionTargetType = - "TARGET_TYPE_UNKNOWN"| "TARGET_TYPE_FILE"| "TARGET_TYPE_EXTENSION_RANGE"| "TARGET_TYPE_MESSAGE"| "TARGET_TYPE_FIELD"| "TARGET_TYPE_ONEOF"| "TARGET_TYPE_ENUM"| "TARGET_TYPE_ENUM_ENTRY"| "TARGET_TYPE_SERVICE"| "TARGET_TYPE_METHOD"; + /** UpdateDocumentRequest document */ + document?: (google.firestore.v1.IDocument|null); - /** Properties of an EditionDefault. */ - interface IEditionDefault { + /** UpdateDocumentRequest updateMask */ + updateMask?: (google.firestore.v1.IDocumentMask|null); - /** EditionDefault edition */ - edition?: (google.protobuf.Edition|null); + /** UpdateDocumentRequest mask */ + mask?: (google.firestore.v1.IDocumentMask|null); - /** EditionDefault value */ - value?: (string|null); + /** UpdateDocumentRequest currentDocument */ + currentDocument?: (google.firestore.v1.IPrecondition|null); } - /** Represents an EditionDefault. */ - class EditionDefault implements IEditionDefault { + /** Represents an UpdateDocumentRequest. */ + class UpdateDocumentRequest implements IUpdateDocumentRequest { /** - * Constructs a new EditionDefault. + * Constructs a new UpdateDocumentRequest. * @param [properties] Properties to set */ - constructor(properties?: google.protobuf.FieldOptions.IEditionDefault); + constructor(properties?: google.firestore.v1.IUpdateDocumentRequest); - /** EditionDefault edition. */ - public edition: google.protobuf.Edition; + /** UpdateDocumentRequest document. */ + public document?: (google.firestore.v1.IDocument|null); - /** EditionDefault value. */ - public value: string; + /** UpdateDocumentRequest updateMask. */ + public updateMask?: (google.firestore.v1.IDocumentMask|null); + + /** UpdateDocumentRequest mask. */ + public mask?: (google.firestore.v1.IDocumentMask|null); + + /** UpdateDocumentRequest currentDocument. */ + public currentDocument?: (google.firestore.v1.IPrecondition|null); /** - * Creates an EditionDefault message from a plain object. Also converts values to their respective internal types. + * Creates an UpdateDocumentRequest message from a plain object. Also converts values to their respective internal types. * @param object Plain object - * @returns EditionDefault + * @returns UpdateDocumentRequest */ - public static fromObject(object: { [k: string]: any }): google.protobuf.FieldOptions.EditionDefault; + public static fromObject(object: { [k: string]: any }): google.firestore.v1.UpdateDocumentRequest; /** - * Creates a plain object from an EditionDefault message. Also converts values to other types if specified. - * @param message EditionDefault + * Creates a plain object from an UpdateDocumentRequest message. Also converts values to other types if specified. + * @param message UpdateDocumentRequest * @param [options] Conversion options * @returns Plain object */ - public static toObject(message: google.protobuf.FieldOptions.EditionDefault, options?: $protobuf.IConversionOptions): { [k: string]: any }; + public static toObject(message: google.firestore.v1.UpdateDocumentRequest, options?: $protobuf.IConversionOptions): { [k: string]: any }; /** - * Converts this EditionDefault to JSON. + * Converts this UpdateDocumentRequest to JSON. * @returns JSON object */ public toJSON(): { [k: string]: any }; /** - * Gets the default type url for EditionDefault + * Gets the default type url for UpdateDocumentRequest * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") * @returns The default type url */ public static getTypeUrl(typeUrlPrefix?: string): string; } - /** Properties of a FeatureSupport. */ - interface IFeatureSupport { - - /** FeatureSupport editionIntroduced */ - editionIntroduced?: (google.protobuf.Edition|null); - - /** FeatureSupport editionDeprecated */ - editionDeprecated?: (google.protobuf.Edition|null); + /** Properties of a DeleteDocumentRequest. */ + interface IDeleteDocumentRequest { - /** FeatureSupport deprecationWarning */ - deprecationWarning?: (string|null); + /** DeleteDocumentRequest name */ + name?: (string|null); - /** FeatureSupport editionRemoved */ - editionRemoved?: (google.protobuf.Edition|null); + /** DeleteDocumentRequest currentDocument */ + currentDocument?: (google.firestore.v1.IPrecondition|null); } - /** Represents a FeatureSupport. */ - class FeatureSupport implements IFeatureSupport { + /** Represents a DeleteDocumentRequest. */ + class DeleteDocumentRequest implements IDeleteDocumentRequest { /** - * Constructs a new FeatureSupport. + * Constructs a new DeleteDocumentRequest. * @param [properties] Properties to set */ - constructor(properties?: google.protobuf.FieldOptions.IFeatureSupport); - - /** FeatureSupport editionIntroduced. */ - public editionIntroduced: google.protobuf.Edition; - - /** FeatureSupport editionDeprecated. */ - public editionDeprecated: google.protobuf.Edition; + constructor(properties?: google.firestore.v1.IDeleteDocumentRequest); - /** FeatureSupport deprecationWarning. */ - public deprecationWarning: string; + /** DeleteDocumentRequest name. */ + public name: string; - /** FeatureSupport editionRemoved. */ - public editionRemoved: google.protobuf.Edition; + /** DeleteDocumentRequest currentDocument. */ + public currentDocument?: (google.firestore.v1.IPrecondition|null); /** - * Creates a FeatureSupport message from a plain object. Also converts values to their respective internal types. + * Creates a DeleteDocumentRequest message from a plain object. Also converts values to their respective internal types. * @param object Plain object - * @returns FeatureSupport + * @returns DeleteDocumentRequest */ - public static fromObject(object: { [k: string]: any }): google.protobuf.FieldOptions.FeatureSupport; + public static fromObject(object: { [k: string]: any }): google.firestore.v1.DeleteDocumentRequest; /** - * Creates a plain object from a FeatureSupport message. Also converts values to other types if specified. - * @param message FeatureSupport + * Creates a plain object from a DeleteDocumentRequest message. Also converts values to other types if specified. + * @param message DeleteDocumentRequest * @param [options] Conversion options * @returns Plain object */ - public static toObject(message: google.protobuf.FieldOptions.FeatureSupport, options?: $protobuf.IConversionOptions): { [k: string]: any }; + public static toObject(message: google.firestore.v1.DeleteDocumentRequest, options?: $protobuf.IConversionOptions): { [k: string]: any }; /** - * Converts this FeatureSupport to JSON. + * Converts this DeleteDocumentRequest to JSON. * @returns JSON object */ public toJSON(): { [k: string]: any }; /** - * Gets the default type url for FeatureSupport + * Gets the default type url for DeleteDocumentRequest * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") * @returns The default type url */ public static getTypeUrl(typeUrlPrefix?: string): string; } - } - /** Properties of an OneofOptions. */ - interface IOneofOptions { + /** Properties of a BatchGetDocumentsRequest. */ + interface IBatchGetDocumentsRequest { - /** OneofOptions features */ - features?: (google.protobuf.IFeatureSet|null); + /** BatchGetDocumentsRequest database */ + database?: (string|null); - /** OneofOptions uninterpretedOption */ - uninterpretedOption?: (google.protobuf.IUninterpretedOption[]|null); - } + /** BatchGetDocumentsRequest documents */ + documents?: (string[]|null); - /** Represents an OneofOptions. */ - class OneofOptions implements IOneofOptions { + /** BatchGetDocumentsRequest mask */ + mask?: (google.firestore.v1.IDocumentMask|null); - /** - * Constructs a new OneofOptions. - * @param [properties] Properties to set - */ - constructor(properties?: google.protobuf.IOneofOptions); + /** BatchGetDocumentsRequest transaction */ + transaction?: (Uint8Array|null); - /** OneofOptions features. */ - public features?: (google.protobuf.IFeatureSet|null); + /** BatchGetDocumentsRequest newTransaction */ + newTransaction?: (google.firestore.v1.ITransactionOptions|null); - /** OneofOptions uninterpretedOption. */ - public uninterpretedOption: google.protobuf.IUninterpretedOption[]; + /** BatchGetDocumentsRequest readTime */ + readTime?: (google.protobuf.ITimestamp|null); + } - /** - * Creates an OneofOptions message from a plain object. Also converts values to their respective internal types. - * @param object Plain object - * @returns OneofOptions - */ - public static fromObject(object: { [k: string]: any }): google.protobuf.OneofOptions; + /** Represents a BatchGetDocumentsRequest. */ + class BatchGetDocumentsRequest implements IBatchGetDocumentsRequest { - /** - * Creates a plain object from an OneofOptions message. Also converts values to other types if specified. - * @param message OneofOptions - * @param [options] Conversion options - * @returns Plain object - */ - public static toObject(message: google.protobuf.OneofOptions, options?: $protobuf.IConversionOptions): { [k: string]: any }; + /** + * Constructs a new BatchGetDocumentsRequest. + * @param [properties] Properties to set + */ + constructor(properties?: google.firestore.v1.IBatchGetDocumentsRequest); - /** - * Converts this OneofOptions to JSON. - * @returns JSON object - */ - public toJSON(): { [k: string]: any }; + /** BatchGetDocumentsRequest database. */ + public database: string; - /** - * Gets the default type url for OneofOptions - * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") - * @returns The default type url - */ - public static getTypeUrl(typeUrlPrefix?: string): string; - } + /** BatchGetDocumentsRequest documents. */ + public documents: string[]; - /** Properties of an EnumOptions. */ - interface IEnumOptions { + /** BatchGetDocumentsRequest mask. */ + public mask?: (google.firestore.v1.IDocumentMask|null); - /** EnumOptions allowAlias */ - allowAlias?: (boolean|null); + /** BatchGetDocumentsRequest transaction. */ + public transaction?: (Uint8Array|null); - /** EnumOptions deprecated */ - deprecated?: (boolean|null); + /** BatchGetDocumentsRequest newTransaction. */ + public newTransaction?: (google.firestore.v1.ITransactionOptions|null); - /** EnumOptions deprecatedLegacyJsonFieldConflicts */ - deprecatedLegacyJsonFieldConflicts?: (boolean|null); + /** BatchGetDocumentsRequest readTime. */ + public readTime?: (google.protobuf.ITimestamp|null); - /** EnumOptions features */ - features?: (google.protobuf.IFeatureSet|null); + /** BatchGetDocumentsRequest consistencySelector. */ + public consistencySelector?: ("transaction"|"newTransaction"|"readTime"); - /** EnumOptions uninterpretedOption */ - uninterpretedOption?: (google.protobuf.IUninterpretedOption[]|null); - } + /** + * Creates a BatchGetDocumentsRequest message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns BatchGetDocumentsRequest + */ + public static fromObject(object: { [k: string]: any }): google.firestore.v1.BatchGetDocumentsRequest; - /** Represents an EnumOptions. */ - class EnumOptions implements IEnumOptions { + /** + * Creates a plain object from a BatchGetDocumentsRequest message. Also converts values to other types if specified. + * @param message BatchGetDocumentsRequest + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.firestore.v1.BatchGetDocumentsRequest, options?: $protobuf.IConversionOptions): { [k: string]: any }; - /** - * Constructs a new EnumOptions. - * @param [properties] Properties to set - */ - constructor(properties?: google.protobuf.IEnumOptions); + /** + * Converts this BatchGetDocumentsRequest to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; - /** EnumOptions allowAlias. */ - public allowAlias: boolean; + /** + * Gets the default type url for BatchGetDocumentsRequest + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } - /** EnumOptions deprecated. */ - public deprecated: boolean; + /** Properties of a BatchGetDocumentsResponse. */ + interface IBatchGetDocumentsResponse { - /** EnumOptions deprecatedLegacyJsonFieldConflicts. */ - public deprecatedLegacyJsonFieldConflicts: boolean; + /** BatchGetDocumentsResponse found */ + found?: (google.firestore.v1.IDocument|null); - /** EnumOptions features. */ - public features?: (google.protobuf.IFeatureSet|null); + /** BatchGetDocumentsResponse missing */ + missing?: (string|null); - /** EnumOptions uninterpretedOption. */ - public uninterpretedOption: google.protobuf.IUninterpretedOption[]; + /** BatchGetDocumentsResponse transaction */ + transaction?: (Uint8Array|null); - /** - * Creates an EnumOptions message from a plain object. Also converts values to their respective internal types. - * @param object Plain object - * @returns EnumOptions - */ - public static fromObject(object: { [k: string]: any }): google.protobuf.EnumOptions; + /** BatchGetDocumentsResponse readTime */ + readTime?: (google.protobuf.ITimestamp|null); + } - /** - * Creates a plain object from an EnumOptions message. Also converts values to other types if specified. - * @param message EnumOptions - * @param [options] Conversion options - * @returns Plain object - */ - public static toObject(message: google.protobuf.EnumOptions, options?: $protobuf.IConversionOptions): { [k: string]: any }; + /** Represents a BatchGetDocumentsResponse. */ + class BatchGetDocumentsResponse implements IBatchGetDocumentsResponse { - /** - * Converts this EnumOptions to JSON. - * @returns JSON object - */ - public toJSON(): { [k: string]: any }; + /** + * Constructs a new BatchGetDocumentsResponse. + * @param [properties] Properties to set + */ + constructor(properties?: google.firestore.v1.IBatchGetDocumentsResponse); - /** - * Gets the default type url for EnumOptions - * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") - * @returns The default type url - */ - public static getTypeUrl(typeUrlPrefix?: string): string; - } + /** BatchGetDocumentsResponse found. */ + public found?: (google.firestore.v1.IDocument|null); - /** Properties of an EnumValueOptions. */ - interface IEnumValueOptions { + /** BatchGetDocumentsResponse missing. */ + public missing?: (string|null); - /** EnumValueOptions deprecated */ - deprecated?: (boolean|null); + /** BatchGetDocumentsResponse transaction. */ + public transaction: Uint8Array; - /** EnumValueOptions features */ - features?: (google.protobuf.IFeatureSet|null); + /** BatchGetDocumentsResponse readTime. */ + public readTime?: (google.protobuf.ITimestamp|null); - /** EnumValueOptions debugRedact */ - debugRedact?: (boolean|null); + /** BatchGetDocumentsResponse result. */ + public result?: ("found"|"missing"); - /** EnumValueOptions uninterpretedOption */ - uninterpretedOption?: (google.protobuf.IUninterpretedOption[]|null); - } + /** + * Creates a BatchGetDocumentsResponse message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns BatchGetDocumentsResponse + */ + public static fromObject(object: { [k: string]: any }): google.firestore.v1.BatchGetDocumentsResponse; - /** Represents an EnumValueOptions. */ - class EnumValueOptions implements IEnumValueOptions { + /** + * Creates a plain object from a BatchGetDocumentsResponse message. Also converts values to other types if specified. + * @param message BatchGetDocumentsResponse + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.firestore.v1.BatchGetDocumentsResponse, options?: $protobuf.IConversionOptions): { [k: string]: any }; - /** - * Constructs a new EnumValueOptions. - * @param [properties] Properties to set - */ - constructor(properties?: google.protobuf.IEnumValueOptions); + /** + * Converts this BatchGetDocumentsResponse to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; - /** EnumValueOptions deprecated. */ - public deprecated: boolean; + /** + * Gets the default type url for BatchGetDocumentsResponse + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } - /** EnumValueOptions features. */ - public features?: (google.protobuf.IFeatureSet|null); + /** Properties of a BeginTransactionRequest. */ + interface IBeginTransactionRequest { - /** EnumValueOptions debugRedact. */ - public debugRedact: boolean; + /** BeginTransactionRequest database */ + database?: (string|null); - /** EnumValueOptions uninterpretedOption. */ - public uninterpretedOption: google.protobuf.IUninterpretedOption[]; + /** BeginTransactionRequest options */ + options?: (google.firestore.v1.ITransactionOptions|null); + } - /** - * Creates an EnumValueOptions message from a plain object. Also converts values to their respective internal types. - * @param object Plain object - * @returns EnumValueOptions - */ - public static fromObject(object: { [k: string]: any }): google.protobuf.EnumValueOptions; + /** Represents a BeginTransactionRequest. */ + class BeginTransactionRequest implements IBeginTransactionRequest { - /** - * Creates a plain object from an EnumValueOptions message. Also converts values to other types if specified. - * @param message EnumValueOptions - * @param [options] Conversion options - * @returns Plain object - */ - public static toObject(message: google.protobuf.EnumValueOptions, options?: $protobuf.IConversionOptions): { [k: string]: any }; + /** + * Constructs a new BeginTransactionRequest. + * @param [properties] Properties to set + */ + constructor(properties?: google.firestore.v1.IBeginTransactionRequest); - /** - * Converts this EnumValueOptions to JSON. - * @returns JSON object - */ - public toJSON(): { [k: string]: any }; + /** BeginTransactionRequest database. */ + public database: string; - /** - * Gets the default type url for EnumValueOptions - * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") - * @returns The default type url - */ - public static getTypeUrl(typeUrlPrefix?: string): string; - } - - /** Properties of a ServiceOptions. */ - interface IServiceOptions { + /** BeginTransactionRequest options. */ + public options?: (google.firestore.v1.ITransactionOptions|null); - /** ServiceOptions features */ - features?: (google.protobuf.IFeatureSet|null); + /** + * Creates a BeginTransactionRequest message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns BeginTransactionRequest + */ + public static fromObject(object: { [k: string]: any }): google.firestore.v1.BeginTransactionRequest; - /** ServiceOptions deprecated */ - deprecated?: (boolean|null); + /** + * Creates a plain object from a BeginTransactionRequest message. Also converts values to other types if specified. + * @param message BeginTransactionRequest + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.firestore.v1.BeginTransactionRequest, options?: $protobuf.IConversionOptions): { [k: string]: any }; - /** ServiceOptions uninterpretedOption */ - uninterpretedOption?: (google.protobuf.IUninterpretedOption[]|null); + /** + * Converts this BeginTransactionRequest to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; - /** ServiceOptions .google.api.defaultHost */ - ".google.api.defaultHost"?: (string|null); + /** + * Gets the default type url for BeginTransactionRequest + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } - /** ServiceOptions .google.api.oauthScopes */ - ".google.api.oauthScopes"?: (string|null); + /** Properties of a BeginTransactionResponse. */ + interface IBeginTransactionResponse { - /** ServiceOptions .google.api.apiVersion */ - ".google.api.apiVersion"?: (string|null); - } + /** BeginTransactionResponse transaction */ + transaction?: (Uint8Array|null); + } - /** Represents a ServiceOptions. */ - class ServiceOptions implements IServiceOptions { + /** Represents a BeginTransactionResponse. */ + class BeginTransactionResponse implements IBeginTransactionResponse { - /** - * Constructs a new ServiceOptions. - * @param [properties] Properties to set - */ - constructor(properties?: google.protobuf.IServiceOptions); + /** + * Constructs a new BeginTransactionResponse. + * @param [properties] Properties to set + */ + constructor(properties?: google.firestore.v1.IBeginTransactionResponse); - /** ServiceOptions features. */ - public features?: (google.protobuf.IFeatureSet|null); + /** BeginTransactionResponse transaction. */ + public transaction: Uint8Array; - /** ServiceOptions deprecated. */ - public deprecated: boolean; + /** + * Creates a BeginTransactionResponse message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns BeginTransactionResponse + */ + public static fromObject(object: { [k: string]: any }): google.firestore.v1.BeginTransactionResponse; - /** ServiceOptions uninterpretedOption. */ - public uninterpretedOption: google.protobuf.IUninterpretedOption[]; + /** + * Creates a plain object from a BeginTransactionResponse message. Also converts values to other types if specified. + * @param message BeginTransactionResponse + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.firestore.v1.BeginTransactionResponse, options?: $protobuf.IConversionOptions): { [k: string]: any }; - /** - * Creates a ServiceOptions message from a plain object. Also converts values to their respective internal types. - * @param object Plain object - * @returns ServiceOptions - */ - public static fromObject(object: { [k: string]: any }): google.protobuf.ServiceOptions; + /** + * Converts this BeginTransactionResponse to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; - /** - * Creates a plain object from a ServiceOptions message. Also converts values to other types if specified. - * @param message ServiceOptions - * @param [options] Conversion options - * @returns Plain object - */ - public static toObject(message: google.protobuf.ServiceOptions, options?: $protobuf.IConversionOptions): { [k: string]: any }; + /** + * Gets the default type url for BeginTransactionResponse + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } - /** - * Converts this ServiceOptions to JSON. - * @returns JSON object - */ - public toJSON(): { [k: string]: any }; + /** Properties of a CommitRequest. */ + interface ICommitRequest { - /** - * Gets the default type url for ServiceOptions - * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") - * @returns The default type url - */ - public static getTypeUrl(typeUrlPrefix?: string): string; - } + /** CommitRequest database */ + database?: (string|null); - /** Properties of a MethodOptions. */ - interface IMethodOptions { + /** CommitRequest writes */ + writes?: (google.firestore.v1.IWrite[]|null); - /** MethodOptions deprecated */ - deprecated?: (boolean|null); + /** CommitRequest transaction */ + transaction?: (Uint8Array|null); + } - /** MethodOptions idempotencyLevel */ - idempotencyLevel?: (google.protobuf.MethodOptions.IdempotencyLevel|null); + /** Represents a CommitRequest. */ + class CommitRequest implements ICommitRequest { - /** MethodOptions features */ - features?: (google.protobuf.IFeatureSet|null); + /** + * Constructs a new CommitRequest. + * @param [properties] Properties to set + */ + constructor(properties?: google.firestore.v1.ICommitRequest); - /** MethodOptions uninterpretedOption */ - uninterpretedOption?: (google.protobuf.IUninterpretedOption[]|null); + /** CommitRequest database. */ + public database: string; - /** MethodOptions .google.api.http */ - ".google.api.http"?: (google.api.IHttpRule|null); + /** CommitRequest writes. */ + public writes: google.firestore.v1.IWrite[]; - /** MethodOptions .google.api.methodSignature */ - ".google.api.methodSignature"?: (string[]|null); + /** CommitRequest transaction. */ + public transaction: Uint8Array; - /** MethodOptions .google.longrunning.operationInfo */ - ".google.longrunning.operationInfo"?: (google.longrunning.IOperationInfo|null); - } + /** + * Creates a CommitRequest message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns CommitRequest + */ + public static fromObject(object: { [k: string]: any }): google.firestore.v1.CommitRequest; - /** Represents a MethodOptions. */ - class MethodOptions implements IMethodOptions { + /** + * Creates a plain object from a CommitRequest message. Also converts values to other types if specified. + * @param message CommitRequest + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.firestore.v1.CommitRequest, options?: $protobuf.IConversionOptions): { [k: string]: any }; - /** - * Constructs a new MethodOptions. - * @param [properties] Properties to set - */ - constructor(properties?: google.protobuf.IMethodOptions); + /** + * Converts this CommitRequest to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; - /** MethodOptions deprecated. */ - public deprecated: boolean; + /** + * Gets the default type url for CommitRequest + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } - /** MethodOptions idempotencyLevel. */ - public idempotencyLevel: google.protobuf.MethodOptions.IdempotencyLevel; + /** Properties of a CommitResponse. */ + interface ICommitResponse { - /** MethodOptions features. */ - public features?: (google.protobuf.IFeatureSet|null); + /** CommitResponse writeResults */ + writeResults?: (google.firestore.v1.IWriteResult[]|null); - /** MethodOptions uninterpretedOption. */ - public uninterpretedOption: google.protobuf.IUninterpretedOption[]; + /** CommitResponse commitTime */ + commitTime?: (google.protobuf.ITimestamp|null); + } - /** - * Creates a MethodOptions message from a plain object. Also converts values to their respective internal types. - * @param object Plain object - * @returns MethodOptions - */ - public static fromObject(object: { [k: string]: any }): google.protobuf.MethodOptions; + /** Represents a CommitResponse. */ + class CommitResponse implements ICommitResponse { - /** - * Creates a plain object from a MethodOptions message. Also converts values to other types if specified. - * @param message MethodOptions - * @param [options] Conversion options - * @returns Plain object - */ - public static toObject(message: google.protobuf.MethodOptions, options?: $protobuf.IConversionOptions): { [k: string]: any }; + /** + * Constructs a new CommitResponse. + * @param [properties] Properties to set + */ + constructor(properties?: google.firestore.v1.ICommitResponse); - /** - * Converts this MethodOptions to JSON. - * @returns JSON object - */ - public toJSON(): { [k: string]: any }; + /** CommitResponse writeResults. */ + public writeResults: google.firestore.v1.IWriteResult[]; - /** - * Gets the default type url for MethodOptions - * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") - * @returns The default type url - */ - public static getTypeUrl(typeUrlPrefix?: string): string; - } + /** CommitResponse commitTime. */ + public commitTime?: (google.protobuf.ITimestamp|null); - namespace MethodOptions { + /** + * Creates a CommitResponse message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns CommitResponse + */ + public static fromObject(object: { [k: string]: any }): google.firestore.v1.CommitResponse; - /** IdempotencyLevel enum. */ - type IdempotencyLevel = - "IDEMPOTENCY_UNKNOWN"| "NO_SIDE_EFFECTS"| "IDEMPOTENT"; - } + /** + * Creates a plain object from a CommitResponse message. Also converts values to other types if specified. + * @param message CommitResponse + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.firestore.v1.CommitResponse, options?: $protobuf.IConversionOptions): { [k: string]: any }; - /** Properties of an UninterpretedOption. */ - interface IUninterpretedOption { + /** + * Converts this CommitResponse to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; - /** UninterpretedOption name */ - name?: (google.protobuf.UninterpretedOption.INamePart[]|null); + /** + * Gets the default type url for CommitResponse + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } - /** UninterpretedOption identifierValue */ - identifierValue?: (string|null); + /** Properties of a RollbackRequest. */ + interface IRollbackRequest { - /** UninterpretedOption positiveIntValue */ - positiveIntValue?: (number|string|null); + /** RollbackRequest database */ + database?: (string|null); - /** UninterpretedOption negativeIntValue */ - negativeIntValue?: (number|string|null); + /** RollbackRequest transaction */ + transaction?: (Uint8Array|null); + } - /** UninterpretedOption doubleValue */ - doubleValue?: (number|null); + /** Represents a RollbackRequest. */ + class RollbackRequest implements IRollbackRequest { - /** UninterpretedOption stringValue */ - stringValue?: (Uint8Array|null); + /** + * Constructs a new RollbackRequest. + * @param [properties] Properties to set + */ + constructor(properties?: google.firestore.v1.IRollbackRequest); - /** UninterpretedOption aggregateValue */ - aggregateValue?: (string|null); - } + /** RollbackRequest database. */ + public database: string; - /** Represents an UninterpretedOption. */ - class UninterpretedOption implements IUninterpretedOption { + /** RollbackRequest transaction. */ + public transaction: Uint8Array; - /** - * Constructs a new UninterpretedOption. - * @param [properties] Properties to set - */ - constructor(properties?: google.protobuf.IUninterpretedOption); + /** + * Creates a RollbackRequest message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns RollbackRequest + */ + public static fromObject(object: { [k: string]: any }): google.firestore.v1.RollbackRequest; - /** UninterpretedOption name. */ - public name: google.protobuf.UninterpretedOption.INamePart[]; + /** + * Creates a plain object from a RollbackRequest message. Also converts values to other types if specified. + * @param message RollbackRequest + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.firestore.v1.RollbackRequest, options?: $protobuf.IConversionOptions): { [k: string]: any }; - /** UninterpretedOption identifierValue. */ - public identifierValue: string; + /** + * Converts this RollbackRequest to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; - /** UninterpretedOption positiveIntValue. */ - public positiveIntValue: (number|string); + /** + * Gets the default type url for RollbackRequest + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } - /** UninterpretedOption negativeIntValue. */ - public negativeIntValue: (number|string); + /** Properties of a RunQueryRequest. */ + interface IRunQueryRequest { - /** UninterpretedOption doubleValue. */ - public doubleValue: number; + /** RunQueryRequest parent */ + parent?: (string|null); - /** UninterpretedOption stringValue. */ - public stringValue: Uint8Array; + /** RunQueryRequest structuredQuery */ + structuredQuery?: (google.firestore.v1.IStructuredQuery|null); - /** UninterpretedOption aggregateValue. */ - public aggregateValue: string; + /** RunQueryRequest transaction */ + transaction?: (Uint8Array|null); - /** - * Creates an UninterpretedOption message from a plain object. Also converts values to their respective internal types. - * @param object Plain object - * @returns UninterpretedOption - */ - public static fromObject(object: { [k: string]: any }): google.protobuf.UninterpretedOption; + /** RunQueryRequest newTransaction */ + newTransaction?: (google.firestore.v1.ITransactionOptions|null); - /** - * Creates a plain object from an UninterpretedOption message. Also converts values to other types if specified. - * @param message UninterpretedOption - * @param [options] Conversion options - * @returns Plain object - */ - public static toObject(message: google.protobuf.UninterpretedOption, options?: $protobuf.IConversionOptions): { [k: string]: any }; + /** RunQueryRequest readTime */ + readTime?: (google.protobuf.ITimestamp|null); - /** - * Converts this UninterpretedOption to JSON. - * @returns JSON object - */ - public toJSON(): { [k: string]: any }; + /** RunQueryRequest explainOptions */ + explainOptions?: (google.firestore.v1.IExplainOptions|null); + } - /** - * Gets the default type url for UninterpretedOption - * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") - * @returns The default type url - */ - public static getTypeUrl(typeUrlPrefix?: string): string; - } + /** Represents a RunQueryRequest. */ + class RunQueryRequest implements IRunQueryRequest { - namespace UninterpretedOption { + /** + * Constructs a new RunQueryRequest. + * @param [properties] Properties to set + */ + constructor(properties?: google.firestore.v1.IRunQueryRequest); - /** Properties of a NamePart. */ - interface INamePart { + /** RunQueryRequest parent. */ + public parent: string; - /** NamePart namePart */ - namePart: string; + /** RunQueryRequest structuredQuery. */ + public structuredQuery?: (google.firestore.v1.IStructuredQuery|null); - /** NamePart isExtension */ - isExtension: boolean; - } + /** RunQueryRequest transaction. */ + public transaction?: (Uint8Array|null); - /** Represents a NamePart. */ - class NamePart implements INamePart { + /** RunQueryRequest newTransaction. */ + public newTransaction?: (google.firestore.v1.ITransactionOptions|null); - /** - * Constructs a new NamePart. - * @param [properties] Properties to set - */ - constructor(properties?: google.protobuf.UninterpretedOption.INamePart); + /** RunQueryRequest readTime. */ + public readTime?: (google.protobuf.ITimestamp|null); - /** NamePart namePart. */ - public namePart: string; + /** RunQueryRequest explainOptions. */ + public explainOptions?: (google.firestore.v1.IExplainOptions|null); - /** NamePart isExtension. */ - public isExtension: boolean; + /** RunQueryRequest queryType. */ + public queryType?: "structuredQuery"; + + /** RunQueryRequest consistencySelector. */ + public consistencySelector?: ("transaction"|"newTransaction"|"readTime"); /** - * Creates a NamePart message from a plain object. Also converts values to their respective internal types. + * Creates a RunQueryRequest message from a plain object. Also converts values to their respective internal types. * @param object Plain object - * @returns NamePart + * @returns RunQueryRequest */ - public static fromObject(object: { [k: string]: any }): google.protobuf.UninterpretedOption.NamePart; + public static fromObject(object: { [k: string]: any }): google.firestore.v1.RunQueryRequest; /** - * Creates a plain object from a NamePart message. Also converts values to other types if specified. - * @param message NamePart + * Creates a plain object from a RunQueryRequest message. Also converts values to other types if specified. + * @param message RunQueryRequest * @param [options] Conversion options * @returns Plain object */ - public static toObject(message: google.protobuf.UninterpretedOption.NamePart, options?: $protobuf.IConversionOptions): { [k: string]: any }; + public static toObject(message: google.firestore.v1.RunQueryRequest, options?: $protobuf.IConversionOptions): { [k: string]: any }; /** - * Converts this NamePart to JSON. + * Converts this RunQueryRequest to JSON. * @returns JSON object */ public toJSON(): { [k: string]: any }; /** - * Gets the default type url for NamePart + * Gets the default type url for RunQueryRequest * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") * @returns The default type url */ public static getTypeUrl(typeUrlPrefix?: string): string; } - } - /** Properties of a FeatureSet. */ - interface IFeatureSet { + /** Properties of a RunQueryResponse. */ + interface IRunQueryResponse { - /** FeatureSet fieldPresence */ - fieldPresence?: (google.protobuf.FeatureSet.FieldPresence|null); + /** RunQueryResponse transaction */ + transaction?: (Uint8Array|null); - /** FeatureSet enumType */ - enumType?: (google.protobuf.FeatureSet.EnumType|null); + /** RunQueryResponse document */ + document?: (google.firestore.v1.IDocument|null); - /** FeatureSet repeatedFieldEncoding */ - repeatedFieldEncoding?: (google.protobuf.FeatureSet.RepeatedFieldEncoding|null); + /** RunQueryResponse readTime */ + readTime?: (google.protobuf.ITimestamp|null); - /** FeatureSet utf8Validation */ - utf8Validation?: (google.protobuf.FeatureSet.Utf8Validation|null); + /** RunQueryResponse skippedResults */ + skippedResults?: (number|null); - /** FeatureSet messageEncoding */ - messageEncoding?: (google.protobuf.FeatureSet.MessageEncoding|null); + /** RunQueryResponse done */ + done?: (boolean|null); - /** FeatureSet jsonFormat */ - jsonFormat?: (google.protobuf.FeatureSet.JsonFormat|null); - } + /** RunQueryResponse explainMetrics */ + explainMetrics?: (google.firestore.v1.IExplainMetrics|null); + } - /** Represents a FeatureSet. */ - class FeatureSet implements IFeatureSet { + /** Represents a RunQueryResponse. */ + class RunQueryResponse implements IRunQueryResponse { - /** - * Constructs a new FeatureSet. - * @param [properties] Properties to set - */ - constructor(properties?: google.protobuf.IFeatureSet); + /** + * Constructs a new RunQueryResponse. + * @param [properties] Properties to set + */ + constructor(properties?: google.firestore.v1.IRunQueryResponse); - /** FeatureSet fieldPresence. */ - public fieldPresence: google.protobuf.FeatureSet.FieldPresence; + /** RunQueryResponse transaction. */ + public transaction: Uint8Array; - /** FeatureSet enumType. */ - public enumType: google.protobuf.FeatureSet.EnumType; + /** RunQueryResponse document. */ + public document?: (google.firestore.v1.IDocument|null); - /** FeatureSet repeatedFieldEncoding. */ - public repeatedFieldEncoding: google.protobuf.FeatureSet.RepeatedFieldEncoding; - - /** FeatureSet utf8Validation. */ - public utf8Validation: google.protobuf.FeatureSet.Utf8Validation; + /** RunQueryResponse readTime. */ + public readTime?: (google.protobuf.ITimestamp|null); - /** FeatureSet messageEncoding. */ - public messageEncoding: google.protobuf.FeatureSet.MessageEncoding; + /** RunQueryResponse skippedResults. */ + public skippedResults: number; - /** FeatureSet jsonFormat. */ - public jsonFormat: google.protobuf.FeatureSet.JsonFormat; + /** RunQueryResponse done. */ + public done?: (boolean|null); - /** - * Creates a FeatureSet message from a plain object. Also converts values to their respective internal types. - * @param object Plain object - * @returns FeatureSet - */ - public static fromObject(object: { [k: string]: any }): google.protobuf.FeatureSet; + /** RunQueryResponse explainMetrics. */ + public explainMetrics?: (google.firestore.v1.IExplainMetrics|null); - /** - * Creates a plain object from a FeatureSet message. Also converts values to other types if specified. - * @param message FeatureSet - * @param [options] Conversion options - * @returns Plain object - */ - public static toObject(message: google.protobuf.FeatureSet, options?: $protobuf.IConversionOptions): { [k: string]: any }; + /** RunQueryResponse continuationSelector. */ + public continuationSelector?: "done"; - /** - * Converts this FeatureSet to JSON. - * @returns JSON object - */ - public toJSON(): { [k: string]: any }; + /** + * Creates a RunQueryResponse message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns RunQueryResponse + */ + public static fromObject(object: { [k: string]: any }): google.firestore.v1.RunQueryResponse; - /** - * Gets the default type url for FeatureSet - * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") - * @returns The default type url - */ - public static getTypeUrl(typeUrlPrefix?: string): string; - } + /** + * Creates a plain object from a RunQueryResponse message. Also converts values to other types if specified. + * @param message RunQueryResponse + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.firestore.v1.RunQueryResponse, options?: $protobuf.IConversionOptions): { [k: string]: any }; - namespace FeatureSet { + /** + * Converts this RunQueryResponse to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; - /** FieldPresence enum. */ - type FieldPresence = - "FIELD_PRESENCE_UNKNOWN"| "EXPLICIT"| "IMPLICIT"| "LEGACY_REQUIRED"; + /** + * Gets the default type url for RunQueryResponse + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } - /** EnumType enum. */ - type EnumType = - "ENUM_TYPE_UNKNOWN"| "OPEN"| "CLOSED"; + /** Properties of an ExecutePipelineRequest. */ + interface IExecutePipelineRequest { - /** RepeatedFieldEncoding enum. */ - type RepeatedFieldEncoding = - "REPEATED_FIELD_ENCODING_UNKNOWN"| "PACKED"| "EXPANDED"; + /** ExecutePipelineRequest database */ + database?: (string|null); - /** Utf8Validation enum. */ - type Utf8Validation = - "UTF8_VALIDATION_UNKNOWN"| "VERIFY"| "NONE"; + /** ExecutePipelineRequest structuredPipeline */ + structuredPipeline?: (google.firestore.v1.IStructuredPipeline|null); - /** MessageEncoding enum. */ - type MessageEncoding = - "MESSAGE_ENCODING_UNKNOWN"| "LENGTH_PREFIXED"| "DELIMITED"; + /** ExecutePipelineRequest transaction */ + transaction?: (Uint8Array|null); - /** JsonFormat enum. */ - type JsonFormat = - "JSON_FORMAT_UNKNOWN"| "ALLOW"| "LEGACY_BEST_EFFORT"; - } + /** ExecutePipelineRequest newTransaction */ + newTransaction?: (google.firestore.v1.ITransactionOptions|null); - /** Properties of a FeatureSetDefaults. */ - interface IFeatureSetDefaults { + /** ExecutePipelineRequest readTime */ + readTime?: (google.protobuf.ITimestamp|null); + } - /** FeatureSetDefaults defaults */ - defaults?: (google.protobuf.FeatureSetDefaults.IFeatureSetEditionDefault[]|null); + /** Represents an ExecutePipelineRequest. */ + class ExecutePipelineRequest implements IExecutePipelineRequest { - /** FeatureSetDefaults minimumEdition */ - minimumEdition?: (google.protobuf.Edition|null); + /** + * Constructs a new ExecutePipelineRequest. + * @param [properties] Properties to set + */ + constructor(properties?: google.firestore.v1.IExecutePipelineRequest); - /** FeatureSetDefaults maximumEdition */ - maximumEdition?: (google.protobuf.Edition|null); - } + /** ExecutePipelineRequest database. */ + public database: string; - /** Represents a FeatureSetDefaults. */ - class FeatureSetDefaults implements IFeatureSetDefaults { + /** ExecutePipelineRequest structuredPipeline. */ + public structuredPipeline?: (google.firestore.v1.IStructuredPipeline|null); - /** - * Constructs a new FeatureSetDefaults. - * @param [properties] Properties to set - */ - constructor(properties?: google.protobuf.IFeatureSetDefaults); + /** ExecutePipelineRequest transaction. */ + public transaction?: (Uint8Array|null); - /** FeatureSetDefaults defaults. */ - public defaults: google.protobuf.FeatureSetDefaults.IFeatureSetEditionDefault[]; + /** ExecutePipelineRequest newTransaction. */ + public newTransaction?: (google.firestore.v1.ITransactionOptions|null); - /** FeatureSetDefaults minimumEdition. */ - public minimumEdition: google.protobuf.Edition; + /** ExecutePipelineRequest readTime. */ + public readTime?: (google.protobuf.ITimestamp|null); - /** FeatureSetDefaults maximumEdition. */ - public maximumEdition: google.protobuf.Edition; + /** ExecutePipelineRequest pipelineType. */ + public pipelineType?: "structuredPipeline"; - /** - * Creates a FeatureSetDefaults message from a plain object. Also converts values to their respective internal types. - * @param object Plain object - * @returns FeatureSetDefaults - */ - public static fromObject(object: { [k: string]: any }): google.protobuf.FeatureSetDefaults; + /** ExecutePipelineRequest consistencySelector. */ + public consistencySelector?: ("transaction"|"newTransaction"|"readTime"); - /** - * Creates a plain object from a FeatureSetDefaults message. Also converts values to other types if specified. - * @param message FeatureSetDefaults - * @param [options] Conversion options - * @returns Plain object - */ - public static toObject(message: google.protobuf.FeatureSetDefaults, options?: $protobuf.IConversionOptions): { [k: string]: any }; + /** + * Creates an ExecutePipelineRequest message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns ExecutePipelineRequest + */ + public static fromObject(object: { [k: string]: any }): google.firestore.v1.ExecutePipelineRequest; - /** - * Converts this FeatureSetDefaults to JSON. - * @returns JSON object - */ - public toJSON(): { [k: string]: any }; + /** + * Creates a plain object from an ExecutePipelineRequest message. Also converts values to other types if specified. + * @param message ExecutePipelineRequest + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.firestore.v1.ExecutePipelineRequest, options?: $protobuf.IConversionOptions): { [k: string]: any }; - /** - * Gets the default type url for FeatureSetDefaults - * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") - * @returns The default type url - */ - public static getTypeUrl(typeUrlPrefix?: string): string; - } + /** + * Converts this ExecutePipelineRequest to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; - namespace FeatureSetDefaults { + /** + * Gets the default type url for ExecutePipelineRequest + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } - /** Properties of a FeatureSetEditionDefault. */ - interface IFeatureSetEditionDefault { + /** Properties of an ExecutePipelineResponse. */ + interface IExecutePipelineResponse { - /** FeatureSetEditionDefault edition */ - edition?: (google.protobuf.Edition|null); + /** ExecutePipelineResponse transaction */ + transaction?: (Uint8Array|null); - /** FeatureSetEditionDefault overridableFeatures */ - overridableFeatures?: (google.protobuf.IFeatureSet|null); + /** ExecutePipelineResponse results */ + results?: (google.firestore.v1.IDocument[]|null); - /** FeatureSetEditionDefault fixedFeatures */ - fixedFeatures?: (google.protobuf.IFeatureSet|null); + /** ExecutePipelineResponse executionTime */ + executionTime?: (google.protobuf.ITimestamp|null); } - /** Represents a FeatureSetEditionDefault. */ - class FeatureSetEditionDefault implements IFeatureSetEditionDefault { + /** Represents an ExecutePipelineResponse. */ + class ExecutePipelineResponse implements IExecutePipelineResponse { /** - * Constructs a new FeatureSetEditionDefault. + * Constructs a new ExecutePipelineResponse. * @param [properties] Properties to set */ - constructor(properties?: google.protobuf.FeatureSetDefaults.IFeatureSetEditionDefault); + constructor(properties?: google.firestore.v1.IExecutePipelineResponse); - /** FeatureSetEditionDefault edition. */ - public edition: google.protobuf.Edition; + /** ExecutePipelineResponse transaction. */ + public transaction: Uint8Array; - /** FeatureSetEditionDefault overridableFeatures. */ - public overridableFeatures?: (google.protobuf.IFeatureSet|null); + /** ExecutePipelineResponse results. */ + public results: google.firestore.v1.IDocument[]; - /** FeatureSetEditionDefault fixedFeatures. */ - public fixedFeatures?: (google.protobuf.IFeatureSet|null); + /** ExecutePipelineResponse executionTime. */ + public executionTime?: (google.protobuf.ITimestamp|null); /** - * Creates a FeatureSetEditionDefault message from a plain object. Also converts values to their respective internal types. + * Creates an ExecutePipelineResponse message from a plain object. Also converts values to their respective internal types. * @param object Plain object - * @returns FeatureSetEditionDefault + * @returns ExecutePipelineResponse */ - public static fromObject(object: { [k: string]: any }): google.protobuf.FeatureSetDefaults.FeatureSetEditionDefault; + public static fromObject(object: { [k: string]: any }): google.firestore.v1.ExecutePipelineResponse; /** - * Creates a plain object from a FeatureSetEditionDefault message. Also converts values to other types if specified. - * @param message FeatureSetEditionDefault + * Creates a plain object from an ExecutePipelineResponse message. Also converts values to other types if specified. + * @param message ExecutePipelineResponse * @param [options] Conversion options * @returns Plain object */ - public static toObject(message: google.protobuf.FeatureSetDefaults.FeatureSetEditionDefault, options?: $protobuf.IConversionOptions): { [k: string]: any }; + public static toObject(message: google.firestore.v1.ExecutePipelineResponse, options?: $protobuf.IConversionOptions): { [k: string]: any }; /** - * Converts this FeatureSetEditionDefault to JSON. + * Converts this ExecutePipelineResponse to JSON. * @returns JSON object */ public toJSON(): { [k: string]: any }; /** - * Gets the default type url for FeatureSetEditionDefault + * Gets the default type url for ExecutePipelineResponse * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") * @returns The default type url */ public static getTypeUrl(typeUrlPrefix?: string): string; } - } - /** Properties of a SourceCodeInfo. */ - interface ISourceCodeInfo { + /** Properties of a RunAggregationQueryRequest. */ + interface IRunAggregationQueryRequest { - /** SourceCodeInfo location */ - location?: (google.protobuf.SourceCodeInfo.ILocation[]|null); - } + /** RunAggregationQueryRequest parent */ + parent?: (string|null); - /** Represents a SourceCodeInfo. */ - class SourceCodeInfo implements ISourceCodeInfo { + /** RunAggregationQueryRequest structuredAggregationQuery */ + structuredAggregationQuery?: (google.firestore.v1.IStructuredAggregationQuery|null); - /** - * Constructs a new SourceCodeInfo. - * @param [properties] Properties to set - */ - constructor(properties?: google.protobuf.ISourceCodeInfo); - - /** SourceCodeInfo location. */ - public location: google.protobuf.SourceCodeInfo.ILocation[]; - - /** - * Creates a SourceCodeInfo message from a plain object. Also converts values to their respective internal types. - * @param object Plain object - * @returns SourceCodeInfo - */ - public static fromObject(object: { [k: string]: any }): google.protobuf.SourceCodeInfo; - - /** - * Creates a plain object from a SourceCodeInfo message. Also converts values to other types if specified. - * @param message SourceCodeInfo - * @param [options] Conversion options - * @returns Plain object - */ - public static toObject(message: google.protobuf.SourceCodeInfo, options?: $protobuf.IConversionOptions): { [k: string]: any }; - - /** - * Converts this SourceCodeInfo to JSON. - * @returns JSON object - */ - public toJSON(): { [k: string]: any }; - - /** - * Gets the default type url for SourceCodeInfo - * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") - * @returns The default type url - */ - public static getTypeUrl(typeUrlPrefix?: string): string; - } - - namespace SourceCodeInfo { - - /** Properties of a Location. */ - interface ILocation { - - /** Location path */ - path?: (number[]|null); - - /** Location span */ - span?: (number[]|null); + /** RunAggregationQueryRequest transaction */ + transaction?: (Uint8Array|null); - /** Location leadingComments */ - leadingComments?: (string|null); + /** RunAggregationQueryRequest newTransaction */ + newTransaction?: (google.firestore.v1.ITransactionOptions|null); - /** Location trailingComments */ - trailingComments?: (string|null); + /** RunAggregationQueryRequest readTime */ + readTime?: (google.protobuf.ITimestamp|null); - /** Location leadingDetachedComments */ - leadingDetachedComments?: (string[]|null); + /** RunAggregationQueryRequest explainOptions */ + explainOptions?: (google.firestore.v1.IExplainOptions|null); } - /** Represents a Location. */ - class Location implements ILocation { + /** Represents a RunAggregationQueryRequest. */ + class RunAggregationQueryRequest implements IRunAggregationQueryRequest { /** - * Constructs a new Location. + * Constructs a new RunAggregationQueryRequest. * @param [properties] Properties to set */ - constructor(properties?: google.protobuf.SourceCodeInfo.ILocation); + constructor(properties?: google.firestore.v1.IRunAggregationQueryRequest); - /** Location path. */ - public path: number[]; + /** RunAggregationQueryRequest parent. */ + public parent: string; - /** Location span. */ - public span: number[]; + /** RunAggregationQueryRequest structuredAggregationQuery. */ + public structuredAggregationQuery?: (google.firestore.v1.IStructuredAggregationQuery|null); - /** Location leadingComments. */ - public leadingComments: string; + /** RunAggregationQueryRequest transaction. */ + public transaction?: (Uint8Array|null); - /** Location trailingComments. */ - public trailingComments: string; + /** RunAggregationQueryRequest newTransaction. */ + public newTransaction?: (google.firestore.v1.ITransactionOptions|null); - /** Location leadingDetachedComments. */ - public leadingDetachedComments: string[]; + /** RunAggregationQueryRequest readTime. */ + public readTime?: (google.protobuf.ITimestamp|null); + + /** RunAggregationQueryRequest explainOptions. */ + public explainOptions?: (google.firestore.v1.IExplainOptions|null); + + /** RunAggregationQueryRequest queryType. */ + public queryType?: "structuredAggregationQuery"; + + /** RunAggregationQueryRequest consistencySelector. */ + public consistencySelector?: ("transaction"|"newTransaction"|"readTime"); /** - * Creates a Location message from a plain object. Also converts values to their respective internal types. + * Creates a RunAggregationQueryRequest message from a plain object. Also converts values to their respective internal types. * @param object Plain object - * @returns Location + * @returns RunAggregationQueryRequest */ - public static fromObject(object: { [k: string]: any }): google.protobuf.SourceCodeInfo.Location; + public static fromObject(object: { [k: string]: any }): google.firestore.v1.RunAggregationQueryRequest; /** - * Creates a plain object from a Location message. Also converts values to other types if specified. - * @param message Location + * Creates a plain object from a RunAggregationQueryRequest message. Also converts values to other types if specified. + * @param message RunAggregationQueryRequest * @param [options] Conversion options * @returns Plain object */ - public static toObject(message: google.protobuf.SourceCodeInfo.Location, options?: $protobuf.IConversionOptions): { [k: string]: any }; + public static toObject(message: google.firestore.v1.RunAggregationQueryRequest, options?: $protobuf.IConversionOptions): { [k: string]: any }; /** - * Converts this Location to JSON. + * Converts this RunAggregationQueryRequest to JSON. * @returns JSON object */ public toJSON(): { [k: string]: any }; /** - * Gets the default type url for Location + * Gets the default type url for RunAggregationQueryRequest * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") * @returns The default type url */ public static getTypeUrl(typeUrlPrefix?: string): string; } - } - - /** Properties of a GeneratedCodeInfo. */ - interface IGeneratedCodeInfo { - - /** GeneratedCodeInfo annotation */ - annotation?: (google.protobuf.GeneratedCodeInfo.IAnnotation[]|null); - } - - /** Represents a GeneratedCodeInfo. */ - class GeneratedCodeInfo implements IGeneratedCodeInfo { - - /** - * Constructs a new GeneratedCodeInfo. - * @param [properties] Properties to set - */ - constructor(properties?: google.protobuf.IGeneratedCodeInfo); - - /** GeneratedCodeInfo annotation. */ - public annotation: google.protobuf.GeneratedCodeInfo.IAnnotation[]; - - /** - * Creates a GeneratedCodeInfo message from a plain object. Also converts values to their respective internal types. - * @param object Plain object - * @returns GeneratedCodeInfo - */ - public static fromObject(object: { [k: string]: any }): google.protobuf.GeneratedCodeInfo; - - /** - * Creates a plain object from a GeneratedCodeInfo message. Also converts values to other types if specified. - * @param message GeneratedCodeInfo - * @param [options] Conversion options - * @returns Plain object - */ - public static toObject(message: google.protobuf.GeneratedCodeInfo, options?: $protobuf.IConversionOptions): { [k: string]: any }; - - /** - * Converts this GeneratedCodeInfo to JSON. - * @returns JSON object - */ - public toJSON(): { [k: string]: any }; - - /** - * Gets the default type url for GeneratedCodeInfo - * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") - * @returns The default type url - */ - public static getTypeUrl(typeUrlPrefix?: string): string; - } - - namespace GeneratedCodeInfo { - - /** Properties of an Annotation. */ - interface IAnnotation { - /** Annotation path */ - path?: (number[]|null); + /** Properties of a RunAggregationQueryResponse. */ + interface IRunAggregationQueryResponse { - /** Annotation sourceFile */ - sourceFile?: (string|null); + /** RunAggregationQueryResponse result */ + result?: (google.firestore.v1.IAggregationResult|null); - /** Annotation begin */ - begin?: (number|null); + /** RunAggregationQueryResponse transaction */ + transaction?: (Uint8Array|null); - /** Annotation end */ - end?: (number|null); + /** RunAggregationQueryResponse readTime */ + readTime?: (google.protobuf.ITimestamp|null); - /** Annotation semantic */ - semantic?: (google.protobuf.GeneratedCodeInfo.Annotation.Semantic|null); + /** RunAggregationQueryResponse explainMetrics */ + explainMetrics?: (google.firestore.v1.IExplainMetrics|null); } - /** Represents an Annotation. */ - class Annotation implements IAnnotation { + /** Represents a RunAggregationQueryResponse. */ + class RunAggregationQueryResponse implements IRunAggregationQueryResponse { /** - * Constructs a new Annotation. + * Constructs a new RunAggregationQueryResponse. * @param [properties] Properties to set */ - constructor(properties?: google.protobuf.GeneratedCodeInfo.IAnnotation); - - /** Annotation path. */ - public path: number[]; + constructor(properties?: google.firestore.v1.IRunAggregationQueryResponse); - /** Annotation sourceFile. */ - public sourceFile: string; + /** RunAggregationQueryResponse result. */ + public result?: (google.firestore.v1.IAggregationResult|null); - /** Annotation begin. */ - public begin: number; + /** RunAggregationQueryResponse transaction. */ + public transaction: Uint8Array; - /** Annotation end. */ - public end: number; + /** RunAggregationQueryResponse readTime. */ + public readTime?: (google.protobuf.ITimestamp|null); - /** Annotation semantic. */ - public semantic: google.protobuf.GeneratedCodeInfo.Annotation.Semantic; + /** RunAggregationQueryResponse explainMetrics. */ + public explainMetrics?: (google.firestore.v1.IExplainMetrics|null); /** - * Creates an Annotation message from a plain object. Also converts values to their respective internal types. + * Creates a RunAggregationQueryResponse message from a plain object. Also converts values to their respective internal types. * @param object Plain object - * @returns Annotation + * @returns RunAggregationQueryResponse */ - public static fromObject(object: { [k: string]: any }): google.protobuf.GeneratedCodeInfo.Annotation; + public static fromObject(object: { [k: string]: any }): google.firestore.v1.RunAggregationQueryResponse; /** - * Creates a plain object from an Annotation message. Also converts values to other types if specified. - * @param message Annotation + * Creates a plain object from a RunAggregationQueryResponse message. Also converts values to other types if specified. + * @param message RunAggregationQueryResponse * @param [options] Conversion options * @returns Plain object */ - public static toObject(message: google.protobuf.GeneratedCodeInfo.Annotation, options?: $protobuf.IConversionOptions): { [k: string]: any }; + public static toObject(message: google.firestore.v1.RunAggregationQueryResponse, options?: $protobuf.IConversionOptions): { [k: string]: any }; /** - * Converts this Annotation to JSON. + * Converts this RunAggregationQueryResponse to JSON. * @returns JSON object */ public toJSON(): { [k: string]: any }; /** - * Gets the default type url for Annotation + * Gets the default type url for RunAggregationQueryResponse * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") * @returns The default type url */ public static getTypeUrl(typeUrlPrefix?: string): string; } - namespace Annotation { + /** Properties of a PartitionQueryRequest. */ + interface IPartitionQueryRequest { - /** Semantic enum. */ - type Semantic = - "NONE"| "SET"| "ALIAS"; - } - } + /** PartitionQueryRequest parent */ + parent?: (string|null); - /** Properties of a Duration. */ - interface IDuration { + /** PartitionQueryRequest structuredQuery */ + structuredQuery?: (google.firestore.v1.IStructuredQuery|null); - /** Duration seconds */ - seconds?: (number|string|null); + /** PartitionQueryRequest partitionCount */ + partitionCount?: (number|string|null); - /** Duration nanos */ - nanos?: (number|null); - } + /** PartitionQueryRequest pageToken */ + pageToken?: (string|null); - /** Represents a Duration. */ - class Duration implements IDuration { + /** PartitionQueryRequest pageSize */ + pageSize?: (number|null); - /** - * Constructs a new Duration. - * @param [properties] Properties to set - */ - constructor(properties?: google.protobuf.IDuration); + /** PartitionQueryRequest readTime */ + readTime?: (google.protobuf.ITimestamp|null); + } - /** Duration seconds. */ - public seconds: (number|string); + /** Represents a PartitionQueryRequest. */ + class PartitionQueryRequest implements IPartitionQueryRequest { - /** Duration nanos. */ - public nanos: number; + /** + * Constructs a new PartitionQueryRequest. + * @param [properties] Properties to set + */ + constructor(properties?: google.firestore.v1.IPartitionQueryRequest); - /** - * Creates a Duration message from a plain object. Also converts values to their respective internal types. - * @param object Plain object - * @returns Duration - */ - public static fromObject(object: { [k: string]: any }): google.protobuf.Duration; + /** PartitionQueryRequest parent. */ + public parent: string; - /** - * Creates a plain object from a Duration message. Also converts values to other types if specified. - * @param message Duration - * @param [options] Conversion options - * @returns Plain object - */ - public static toObject(message: google.protobuf.Duration, options?: $protobuf.IConversionOptions): { [k: string]: any }; + /** PartitionQueryRequest structuredQuery. */ + public structuredQuery?: (google.firestore.v1.IStructuredQuery|null); - /** - * Converts this Duration to JSON. - * @returns JSON object - */ - public toJSON(): { [k: string]: any }; + /** PartitionQueryRequest partitionCount. */ + public partitionCount: (number|string); - /** - * Gets the default type url for Duration - * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") - * @returns The default type url - */ - public static getTypeUrl(typeUrlPrefix?: string): string; - } + /** PartitionQueryRequest pageToken. */ + public pageToken: string; - /** Properties of a DoubleValue. */ - interface IDoubleValue { + /** PartitionQueryRequest pageSize. */ + public pageSize: number; - /** DoubleValue value */ - value?: (number|null); - } + /** PartitionQueryRequest readTime. */ + public readTime?: (google.protobuf.ITimestamp|null); - /** Represents a DoubleValue. */ - class DoubleValue implements IDoubleValue { + /** PartitionQueryRequest queryType. */ + public queryType?: "structuredQuery"; - /** - * Constructs a new DoubleValue. - * @param [properties] Properties to set - */ - constructor(properties?: google.protobuf.IDoubleValue); + /** PartitionQueryRequest consistencySelector. */ + public consistencySelector?: "readTime"; - /** DoubleValue value. */ - public value: number; + /** + * Creates a PartitionQueryRequest message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns PartitionQueryRequest + */ + public static fromObject(object: { [k: string]: any }): google.firestore.v1.PartitionQueryRequest; - /** - * Creates a DoubleValue message from a plain object. Also converts values to their respective internal types. - * @param object Plain object - * @returns DoubleValue - */ - public static fromObject(object: { [k: string]: any }): google.protobuf.DoubleValue; + /** + * Creates a plain object from a PartitionQueryRequest message. Also converts values to other types if specified. + * @param message PartitionQueryRequest + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.firestore.v1.PartitionQueryRequest, options?: $protobuf.IConversionOptions): { [k: string]: any }; - /** - * Creates a plain object from a DoubleValue message. Also converts values to other types if specified. - * @param message DoubleValue - * @param [options] Conversion options - * @returns Plain object - */ - public static toObject(message: google.protobuf.DoubleValue, options?: $protobuf.IConversionOptions): { [k: string]: any }; + /** + * Converts this PartitionQueryRequest to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; - /** - * Converts this DoubleValue to JSON. - * @returns JSON object - */ - public toJSON(): { [k: string]: any }; + /** + * Gets the default type url for PartitionQueryRequest + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } - /** - * Gets the default type url for DoubleValue - * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") - * @returns The default type url - */ - public static getTypeUrl(typeUrlPrefix?: string): string; - } + /** Properties of a PartitionQueryResponse. */ + interface IPartitionQueryResponse { - /** Properties of a FloatValue. */ - interface IFloatValue { + /** PartitionQueryResponse partitions */ + partitions?: (google.firestore.v1.ICursor[]|null); - /** FloatValue value */ - value?: (number|null); - } + /** PartitionQueryResponse nextPageToken */ + nextPageToken?: (string|null); + } - /** Represents a FloatValue. */ - class FloatValue implements IFloatValue { + /** Represents a PartitionQueryResponse. */ + class PartitionQueryResponse implements IPartitionQueryResponse { - /** - * Constructs a new FloatValue. - * @param [properties] Properties to set - */ - constructor(properties?: google.protobuf.IFloatValue); + /** + * Constructs a new PartitionQueryResponse. + * @param [properties] Properties to set + */ + constructor(properties?: google.firestore.v1.IPartitionQueryResponse); - /** FloatValue value. */ - public value: number; + /** PartitionQueryResponse partitions. */ + public partitions: google.firestore.v1.ICursor[]; - /** - * Creates a FloatValue message from a plain object. Also converts values to their respective internal types. - * @param object Plain object - * @returns FloatValue - */ - public static fromObject(object: { [k: string]: any }): google.protobuf.FloatValue; + /** PartitionQueryResponse nextPageToken. */ + public nextPageToken: string; - /** - * Creates a plain object from a FloatValue message. Also converts values to other types if specified. - * @param message FloatValue - * @param [options] Conversion options - * @returns Plain object - */ - public static toObject(message: google.protobuf.FloatValue, options?: $protobuf.IConversionOptions): { [k: string]: any }; + /** + * Creates a PartitionQueryResponse message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns PartitionQueryResponse + */ + public static fromObject(object: { [k: string]: any }): google.firestore.v1.PartitionQueryResponse; - /** - * Converts this FloatValue to JSON. - * @returns JSON object - */ - public toJSON(): { [k: string]: any }; + /** + * Creates a plain object from a PartitionQueryResponse message. Also converts values to other types if specified. + * @param message PartitionQueryResponse + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.firestore.v1.PartitionQueryResponse, options?: $protobuf.IConversionOptions): { [k: string]: any }; - /** - * Gets the default type url for FloatValue - * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") - * @returns The default type url - */ - public static getTypeUrl(typeUrlPrefix?: string): string; - } + /** + * Converts this PartitionQueryResponse to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; - /** Properties of an Int64Value. */ - interface IInt64Value { + /** + * Gets the default type url for PartitionQueryResponse + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } - /** Int64Value value */ - value?: (number|string|null); - } + /** Properties of a WriteRequest. */ + interface IWriteRequest { - /** Represents an Int64Value. */ - class Int64Value implements IInt64Value { + /** WriteRequest database */ + database?: (string|null); - /** - * Constructs a new Int64Value. - * @param [properties] Properties to set - */ - constructor(properties?: google.protobuf.IInt64Value); + /** WriteRequest streamId */ + streamId?: (string|null); - /** Int64Value value. */ - public value: (number|string); + /** WriteRequest writes */ + writes?: (google.firestore.v1.IWrite[]|null); - /** - * Creates an Int64Value message from a plain object. Also converts values to their respective internal types. - * @param object Plain object - * @returns Int64Value - */ - public static fromObject(object: { [k: string]: any }): google.protobuf.Int64Value; + /** WriteRequest streamToken */ + streamToken?: (Uint8Array|null); - /** - * Creates a plain object from an Int64Value message. Also converts values to other types if specified. - * @param message Int64Value - * @param [options] Conversion options - * @returns Plain object - */ - public static toObject(message: google.protobuf.Int64Value, options?: $protobuf.IConversionOptions): { [k: string]: any }; + /** WriteRequest labels */ + labels?: ({ [k: string]: string }|null); + } - /** - * Converts this Int64Value to JSON. - * @returns JSON object - */ - public toJSON(): { [k: string]: any }; + /** Represents a WriteRequest. */ + class WriteRequest implements IWriteRequest { - /** - * Gets the default type url for Int64Value - * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") - * @returns The default type url - */ - public static getTypeUrl(typeUrlPrefix?: string): string; - } + /** + * Constructs a new WriteRequest. + * @param [properties] Properties to set + */ + constructor(properties?: google.firestore.v1.IWriteRequest); - /** Properties of a UInt64Value. */ - interface IUInt64Value { + /** WriteRequest database. */ + public database: string; - /** UInt64Value value */ - value?: (number|string|null); - } + /** WriteRequest streamId. */ + public streamId: string; - /** Represents a UInt64Value. */ - class UInt64Value implements IUInt64Value { + /** WriteRequest writes. */ + public writes: google.firestore.v1.IWrite[]; - /** - * Constructs a new UInt64Value. - * @param [properties] Properties to set - */ - constructor(properties?: google.protobuf.IUInt64Value); + /** WriteRequest streamToken. */ + public streamToken: Uint8Array; - /** UInt64Value value. */ - public value: (number|string); + /** WriteRequest labels. */ + public labels: { [k: string]: string }; - /** - * Creates a UInt64Value message from a plain object. Also converts values to their respective internal types. - * @param object Plain object - * @returns UInt64Value - */ - public static fromObject(object: { [k: string]: any }): google.protobuf.UInt64Value; + /** + * Creates a WriteRequest message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns WriteRequest + */ + public static fromObject(object: { [k: string]: any }): google.firestore.v1.WriteRequest; - /** - * Creates a plain object from a UInt64Value message. Also converts values to other types if specified. - * @param message UInt64Value - * @param [options] Conversion options - * @returns Plain object - */ - public static toObject(message: google.protobuf.UInt64Value, options?: $protobuf.IConversionOptions): { [k: string]: any }; + /** + * Creates a plain object from a WriteRequest message. Also converts values to other types if specified. + * @param message WriteRequest + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.firestore.v1.WriteRequest, options?: $protobuf.IConversionOptions): { [k: string]: any }; - /** - * Converts this UInt64Value to JSON. - * @returns JSON object - */ - public toJSON(): { [k: string]: any }; + /** + * Converts this WriteRequest to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; - /** - * Gets the default type url for UInt64Value - * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") - * @returns The default type url - */ - public static getTypeUrl(typeUrlPrefix?: string): string; - } + /** + * Gets the default type url for WriteRequest + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } - /** Properties of an Int32Value. */ - interface IInt32Value { + /** Properties of a WriteResponse. */ + interface IWriteResponse { - /** Int32Value value */ - value?: (number|null); - } + /** WriteResponse streamId */ + streamId?: (string|null); - /** Represents an Int32Value. */ - class Int32Value implements IInt32Value { + /** WriteResponse streamToken */ + streamToken?: (Uint8Array|null); - /** - * Constructs a new Int32Value. - * @param [properties] Properties to set - */ - constructor(properties?: google.protobuf.IInt32Value); + /** WriteResponse writeResults */ + writeResults?: (google.firestore.v1.IWriteResult[]|null); - /** Int32Value value. */ - public value: number; + /** WriteResponse commitTime */ + commitTime?: (google.protobuf.ITimestamp|null); + } - /** - * Creates an Int32Value message from a plain object. Also converts values to their respective internal types. - * @param object Plain object - * @returns Int32Value - */ - public static fromObject(object: { [k: string]: any }): google.protobuf.Int32Value; + /** Represents a WriteResponse. */ + class WriteResponse implements IWriteResponse { - /** - * Creates a plain object from an Int32Value message. Also converts values to other types if specified. - * @param message Int32Value - * @param [options] Conversion options - * @returns Plain object - */ - public static toObject(message: google.protobuf.Int32Value, options?: $protobuf.IConversionOptions): { [k: string]: any }; + /** + * Constructs a new WriteResponse. + * @param [properties] Properties to set + */ + constructor(properties?: google.firestore.v1.IWriteResponse); - /** - * Converts this Int32Value to JSON. - * @returns JSON object - */ - public toJSON(): { [k: string]: any }; + /** WriteResponse streamId. */ + public streamId: string; - /** - * Gets the default type url for Int32Value - * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") - * @returns The default type url - */ - public static getTypeUrl(typeUrlPrefix?: string): string; - } + /** WriteResponse streamToken. */ + public streamToken: Uint8Array; - /** Properties of a UInt32Value. */ - interface IUInt32Value { + /** WriteResponse writeResults. */ + public writeResults: google.firestore.v1.IWriteResult[]; - /** UInt32Value value */ - value?: (number|null); - } + /** WriteResponse commitTime. */ + public commitTime?: (google.protobuf.ITimestamp|null); - /** Represents a UInt32Value. */ - class UInt32Value implements IUInt32Value { + /** + * Creates a WriteResponse message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns WriteResponse + */ + public static fromObject(object: { [k: string]: any }): google.firestore.v1.WriteResponse; - /** - * Constructs a new UInt32Value. - * @param [properties] Properties to set - */ - constructor(properties?: google.protobuf.IUInt32Value); + /** + * Creates a plain object from a WriteResponse message. Also converts values to other types if specified. + * @param message WriteResponse + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.firestore.v1.WriteResponse, options?: $protobuf.IConversionOptions): { [k: string]: any }; - /** UInt32Value value. */ - public value: number; + /** + * Converts this WriteResponse to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; - /** - * Creates a UInt32Value message from a plain object. Also converts values to their respective internal types. - * @param object Plain object - * @returns UInt32Value - */ - public static fromObject(object: { [k: string]: any }): google.protobuf.UInt32Value; + /** + * Gets the default type url for WriteResponse + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } - /** - * Creates a plain object from a UInt32Value message. Also converts values to other types if specified. - * @param message UInt32Value - * @param [options] Conversion options - * @returns Plain object - */ - public static toObject(message: google.protobuf.UInt32Value, options?: $protobuf.IConversionOptions): { [k: string]: any }; + /** Properties of a ListenRequest. */ + interface IListenRequest { - /** - * Converts this UInt32Value to JSON. - * @returns JSON object - */ - public toJSON(): { [k: string]: any }; + /** ListenRequest database */ + database?: (string|null); - /** - * Gets the default type url for UInt32Value - * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") - * @returns The default type url - */ - public static getTypeUrl(typeUrlPrefix?: string): string; - } + /** ListenRequest addTarget */ + addTarget?: (google.firestore.v1.ITarget|null); - /** Properties of a BoolValue. */ - interface IBoolValue { + /** ListenRequest removeTarget */ + removeTarget?: (number|null); - /** BoolValue value */ - value?: (boolean|null); - } + /** ListenRequest labels */ + labels?: ({ [k: string]: string }|null); + } - /** Represents a BoolValue. */ - class BoolValue implements IBoolValue { + /** Represents a ListenRequest. */ + class ListenRequest implements IListenRequest { - /** - * Constructs a new BoolValue. - * @param [properties] Properties to set - */ - constructor(properties?: google.protobuf.IBoolValue); + /** + * Constructs a new ListenRequest. + * @param [properties] Properties to set + */ + constructor(properties?: google.firestore.v1.IListenRequest); - /** BoolValue value. */ - public value: boolean; + /** ListenRequest database. */ + public database: string; - /** - * Creates a BoolValue message from a plain object. Also converts values to their respective internal types. - * @param object Plain object - * @returns BoolValue - */ - public static fromObject(object: { [k: string]: any }): google.protobuf.BoolValue; + /** ListenRequest addTarget. */ + public addTarget?: (google.firestore.v1.ITarget|null); - /** - * Creates a plain object from a BoolValue message. Also converts values to other types if specified. - * @param message BoolValue - * @param [options] Conversion options - * @returns Plain object - */ - public static toObject(message: google.protobuf.BoolValue, options?: $protobuf.IConversionOptions): { [k: string]: any }; - - /** - * Converts this BoolValue to JSON. - * @returns JSON object - */ - public toJSON(): { [k: string]: any }; + /** ListenRequest removeTarget. */ + public removeTarget?: (number|null); - /** - * Gets the default type url for BoolValue - * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") - * @returns The default type url - */ - public static getTypeUrl(typeUrlPrefix?: string): string; - } + /** ListenRequest labels. */ + public labels: { [k: string]: string }; - /** Properties of a StringValue. */ - interface IStringValue { + /** ListenRequest targetChange. */ + public targetChange?: ("addTarget"|"removeTarget"); - /** StringValue value */ - value?: (string|null); - } + /** + * Creates a ListenRequest message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns ListenRequest + */ + public static fromObject(object: { [k: string]: any }): google.firestore.v1.ListenRequest; - /** Represents a StringValue. */ - class StringValue implements IStringValue { + /** + * Creates a plain object from a ListenRequest message. Also converts values to other types if specified. + * @param message ListenRequest + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.firestore.v1.ListenRequest, options?: $protobuf.IConversionOptions): { [k: string]: any }; - /** - * Constructs a new StringValue. - * @param [properties] Properties to set - */ - constructor(properties?: google.protobuf.IStringValue); + /** + * Converts this ListenRequest to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; - /** StringValue value. */ - public value: string; + /** + * Gets the default type url for ListenRequest + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } - /** - * Creates a StringValue message from a plain object. Also converts values to their respective internal types. - * @param object Plain object - * @returns StringValue - */ - public static fromObject(object: { [k: string]: any }): google.protobuf.StringValue; + /** Properties of a ListenResponse. */ + interface IListenResponse { - /** - * Creates a plain object from a StringValue message. Also converts values to other types if specified. - * @param message StringValue - * @param [options] Conversion options - * @returns Plain object - */ - public static toObject(message: google.protobuf.StringValue, options?: $protobuf.IConversionOptions): { [k: string]: any }; + /** ListenResponse targetChange */ + targetChange?: (google.firestore.v1.ITargetChange|null); - /** - * Converts this StringValue to JSON. - * @returns JSON object - */ - public toJSON(): { [k: string]: any }; + /** ListenResponse documentChange */ + documentChange?: (google.firestore.v1.IDocumentChange|null); - /** - * Gets the default type url for StringValue - * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") - * @returns The default type url - */ - public static getTypeUrl(typeUrlPrefix?: string): string; - } + /** ListenResponse documentDelete */ + documentDelete?: (google.firestore.v1.IDocumentDelete|null); - /** Properties of a BytesValue. */ - interface IBytesValue { + /** ListenResponse documentRemove */ + documentRemove?: (google.firestore.v1.IDocumentRemove|null); - /** BytesValue value */ - value?: (Uint8Array|null); - } + /** ListenResponse filter */ + filter?: (google.firestore.v1.IExistenceFilter|null); + } - /** Represents a BytesValue. */ - class BytesValue implements IBytesValue { + /** Represents a ListenResponse. */ + class ListenResponse implements IListenResponse { - /** - * Constructs a new BytesValue. - * @param [properties] Properties to set - */ - constructor(properties?: google.protobuf.IBytesValue); + /** + * Constructs a new ListenResponse. + * @param [properties] Properties to set + */ + constructor(properties?: google.firestore.v1.IListenResponse); - /** BytesValue value. */ - public value: Uint8Array; + /** ListenResponse targetChange. */ + public targetChange?: (google.firestore.v1.ITargetChange|null); - /** - * Creates a BytesValue message from a plain object. Also converts values to their respective internal types. - * @param object Plain object - * @returns BytesValue - */ - public static fromObject(object: { [k: string]: any }): google.protobuf.BytesValue; + /** ListenResponse documentChange. */ + public documentChange?: (google.firestore.v1.IDocumentChange|null); - /** - * Creates a plain object from a BytesValue message. Also converts values to other types if specified. - * @param message BytesValue - * @param [options] Conversion options - * @returns Plain object - */ - public static toObject(message: google.protobuf.BytesValue, options?: $protobuf.IConversionOptions): { [k: string]: any }; + /** ListenResponse documentDelete. */ + public documentDelete?: (google.firestore.v1.IDocumentDelete|null); - /** - * Converts this BytesValue to JSON. - * @returns JSON object - */ - public toJSON(): { [k: string]: any }; + /** ListenResponse documentRemove. */ + public documentRemove?: (google.firestore.v1.IDocumentRemove|null); - /** - * Gets the default type url for BytesValue - * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") - * @returns The default type url - */ - public static getTypeUrl(typeUrlPrefix?: string): string; - } + /** ListenResponse filter. */ + public filter?: (google.firestore.v1.IExistenceFilter|null); - /** Properties of an Empty. */ - interface IEmpty { - } + /** ListenResponse responseType. */ + public responseType?: ("targetChange"|"documentChange"|"documentDelete"|"documentRemove"|"filter"); - /** Represents an Empty. */ - class Empty implements IEmpty { + /** + * Creates a ListenResponse message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns ListenResponse + */ + public static fromObject(object: { [k: string]: any }): google.firestore.v1.ListenResponse; - /** - * Constructs a new Empty. - * @param [properties] Properties to set - */ - constructor(properties?: google.protobuf.IEmpty); + /** + * Creates a plain object from a ListenResponse message. Also converts values to other types if specified. + * @param message ListenResponse + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.firestore.v1.ListenResponse, options?: $protobuf.IConversionOptions): { [k: string]: any }; - /** - * Creates an Empty message from a plain object. Also converts values to their respective internal types. - * @param object Plain object - * @returns Empty - */ - public static fromObject(object: { [k: string]: any }): google.protobuf.Empty; + /** + * Converts this ListenResponse to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; - /** - * Creates a plain object from an Empty message. Also converts values to other types if specified. - * @param message Empty - * @param [options] Conversion options - * @returns Plain object - */ - public static toObject(message: google.protobuf.Empty, options?: $protobuf.IConversionOptions): { [k: string]: any }; + /** + * Gets the default type url for ListenResponse + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } - /** - * Converts this Empty to JSON. - * @returns JSON object - */ - public toJSON(): { [k: string]: any }; + /** Properties of a Target. */ + interface ITarget { - /** - * Gets the default type url for Empty - * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") - * @returns The default type url - */ - public static getTypeUrl(typeUrlPrefix?: string): string; - } + /** Target query */ + query?: (google.firestore.v1.Target.IQueryTarget|null); - /** Properties of an Any. */ - interface IAny { + /** Target documents */ + documents?: (google.firestore.v1.Target.IDocumentsTarget|null); - /** Any type_url */ - type_url?: (string|null); + /** Target resumeToken */ + resumeToken?: (Uint8Array|null); - /** Any value */ - value?: (Uint8Array|null); - } + /** Target readTime */ + readTime?: (google.protobuf.ITimestamp|null); - /** Represents an Any. */ - class Any implements IAny { + /** Target targetId */ + targetId?: (number|null); - /** - * Constructs a new Any. - * @param [properties] Properties to set - */ - constructor(properties?: google.protobuf.IAny); + /** Target once */ + once?: (boolean|null); - /** Any type_url. */ - public type_url: string; + /** Target expectedCount */ + expectedCount?: (google.protobuf.IInt32Value|null); + } - /** Any value. */ - public value: Uint8Array; + /** Represents a Target. */ + class Target implements ITarget { - /** - * Creates an Any message from a plain object. Also converts values to their respective internal types. - * @param object Plain object - * @returns Any - */ - public static fromObject(object: { [k: string]: any }): google.protobuf.Any; - - /** - * Creates a plain object from an Any message. Also converts values to other types if specified. - * @param message Any - * @param [options] Conversion options - * @returns Plain object - */ - public static toObject(message: google.protobuf.Any, options?: $protobuf.IConversionOptions): { [k: string]: any }; - - /** - * Converts this Any to JSON. - * @returns JSON object - */ - public toJSON(): { [k: string]: any }; - - /** - * Gets the default type url for Any - * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") - * @returns The default type url - */ - public static getTypeUrl(typeUrlPrefix?: string): string; - } - - /** Properties of a FieldMask. */ - interface IFieldMask { - - /** FieldMask paths */ - paths?: (string[]|null); - } - - /** Represents a FieldMask. */ - class FieldMask implements IFieldMask { - - /** - * Constructs a new FieldMask. - * @param [properties] Properties to set - */ - constructor(properties?: google.protobuf.IFieldMask); - - /** FieldMask paths. */ - public paths: string[]; - - /** - * Creates a FieldMask message from a plain object. Also converts values to their respective internal types. - * @param object Plain object - * @returns FieldMask - */ - public static fromObject(object: { [k: string]: any }): google.protobuf.FieldMask; - - /** - * Creates a plain object from a FieldMask message. Also converts values to other types if specified. - * @param message FieldMask - * @param [options] Conversion options - * @returns Plain object - */ - public static toObject(message: google.protobuf.FieldMask, options?: $protobuf.IConversionOptions): { [k: string]: any }; + /** + * Constructs a new Target. + * @param [properties] Properties to set + */ + constructor(properties?: google.firestore.v1.ITarget); - /** - * Converts this FieldMask to JSON. - * @returns JSON object - */ - public toJSON(): { [k: string]: any }; + /** Target query. */ + public query?: (google.firestore.v1.Target.IQueryTarget|null); - /** - * Gets the default type url for FieldMask - * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") - * @returns The default type url - */ - public static getTypeUrl(typeUrlPrefix?: string): string; - } - } + /** Target documents. */ + public documents?: (google.firestore.v1.Target.IDocumentsTarget|null); - /** Namespace firestore. */ - namespace firestore { + /** Target resumeToken. */ + public resumeToken?: (Uint8Array|null); - /** Namespace v1. */ - namespace v1 { + /** Target readTime. */ + public readTime?: (google.protobuf.ITimestamp|null); - /** Properties of an AggregationResult. */ - interface IAggregationResult { + /** Target targetId. */ + public targetId: number; - /** AggregationResult aggregateFields */ - aggregateFields?: ({ [k: string]: google.firestore.v1.IValue }|null); - } + /** Target once. */ + public once: boolean; - /** Represents an AggregationResult. */ - class AggregationResult implements IAggregationResult { + /** Target expectedCount. */ + public expectedCount?: (google.protobuf.IInt32Value|null); - /** - * Constructs a new AggregationResult. - * @param [properties] Properties to set - */ - constructor(properties?: google.firestore.v1.IAggregationResult); + /** Target targetType. */ + public targetType?: ("query"|"documents"); - /** AggregationResult aggregateFields. */ - public aggregateFields: { [k: string]: google.firestore.v1.IValue }; + /** Target resumeType. */ + public resumeType?: ("resumeToken"|"readTime"); /** - * Creates an AggregationResult message from a plain object. Also converts values to their respective internal types. + * Creates a Target message from a plain object. Also converts values to their respective internal types. * @param object Plain object - * @returns AggregationResult + * @returns Target */ - public static fromObject(object: { [k: string]: any }): google.firestore.v1.AggregationResult; + public static fromObject(object: { [k: string]: any }): google.firestore.v1.Target; /** - * Creates a plain object from an AggregationResult message. Also converts values to other types if specified. - * @param message AggregationResult + * Creates a plain object from a Target message. Also converts values to other types if specified. + * @param message Target * @param [options] Conversion options * @returns Plain object */ - public static toObject(message: google.firestore.v1.AggregationResult, options?: $protobuf.IConversionOptions): { [k: string]: any }; + public static toObject(message: google.firestore.v1.Target, options?: $protobuf.IConversionOptions): { [k: string]: any }; /** - * Converts this AggregationResult to JSON. + * Converts this Target to JSON. * @returns JSON object */ public toJSON(): { [k: string]: any }; /** - * Gets the default type url for AggregationResult + * Gets the default type url for Target * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") * @returns The default type url */ public static getTypeUrl(typeUrlPrefix?: string): string; } - /** Properties of a Document. */ - interface IDocument { - - /** Document name */ - name?: (string|null); - - /** Document fields */ - fields?: ({ [k: string]: google.firestore.v1.IValue }|null); + namespace Target { - /** Document createTime */ - createTime?: (google.protobuf.ITimestamp|null); + /** Properties of a DocumentsTarget. */ + interface IDocumentsTarget { - /** Document updateTime */ - updateTime?: (google.protobuf.ITimestamp|null); - } + /** DocumentsTarget documents */ + documents?: (string[]|null); + } - /** Represents a Document. */ - class Document implements IDocument { + /** Represents a DocumentsTarget. */ + class DocumentsTarget implements IDocumentsTarget { - /** - * Constructs a new Document. - * @param [properties] Properties to set - */ - constructor(properties?: google.firestore.v1.IDocument); + /** + * Constructs a new DocumentsTarget. + * @param [properties] Properties to set + */ + constructor(properties?: google.firestore.v1.Target.IDocumentsTarget); - /** Document name. */ - public name: string; + /** DocumentsTarget documents. */ + public documents: string[]; - /** Document fields. */ - public fields: { [k: string]: google.firestore.v1.IValue }; + /** + * Creates a DocumentsTarget message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns DocumentsTarget + */ + public static fromObject(object: { [k: string]: any }): google.firestore.v1.Target.DocumentsTarget; - /** Document createTime. */ - public createTime?: (google.protobuf.ITimestamp|null); + /** + * Creates a plain object from a DocumentsTarget message. Also converts values to other types if specified. + * @param message DocumentsTarget + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.firestore.v1.Target.DocumentsTarget, options?: $protobuf.IConversionOptions): { [k: string]: any }; - /** Document updateTime. */ - public updateTime?: (google.protobuf.ITimestamp|null); + /** + * Converts this DocumentsTarget to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; - /** - * Creates a Document message from a plain object. Also converts values to their respective internal types. - * @param object Plain object - * @returns Document - */ - public static fromObject(object: { [k: string]: any }): google.firestore.v1.Document; + /** + * Gets the default type url for DocumentsTarget + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } - /** - * Creates a plain object from a Document message. Also converts values to other types if specified. - * @param message Document - * @param [options] Conversion options - * @returns Plain object - */ - public static toObject(message: google.firestore.v1.Document, options?: $protobuf.IConversionOptions): { [k: string]: any }; + /** Properties of a QueryTarget. */ + interface IQueryTarget { - /** - * Converts this Document to JSON. - * @returns JSON object - */ - public toJSON(): { [k: string]: any }; + /** QueryTarget parent */ + parent?: (string|null); - /** - * Gets the default type url for Document - * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") - * @returns The default type url - */ - public static getTypeUrl(typeUrlPrefix?: string): string; - } + /** QueryTarget structuredQuery */ + structuredQuery?: (google.firestore.v1.IStructuredQuery|null); + } - /** Properties of a Value. */ - interface IValue { + /** Represents a QueryTarget. */ + class QueryTarget implements IQueryTarget { - /** Value nullValue */ - nullValue?: (google.protobuf.NullValue|null); + /** + * Constructs a new QueryTarget. + * @param [properties] Properties to set + */ + constructor(properties?: google.firestore.v1.Target.IQueryTarget); - /** Value booleanValue */ - booleanValue?: (boolean|null); + /** QueryTarget parent. */ + public parent: string; - /** Value integerValue */ - integerValue?: (number|string|null); + /** QueryTarget structuredQuery. */ + public structuredQuery?: (google.firestore.v1.IStructuredQuery|null); - /** Value doubleValue */ - doubleValue?: (number|null); + /** QueryTarget queryType. */ + public queryType?: "structuredQuery"; - /** Value timestampValue */ - timestampValue?: (google.protobuf.ITimestamp|null); + /** + * Creates a QueryTarget message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns QueryTarget + */ + public static fromObject(object: { [k: string]: any }): google.firestore.v1.Target.QueryTarget; - /** Value stringValue */ - stringValue?: (string|null); + /** + * Creates a plain object from a QueryTarget message. Also converts values to other types if specified. + * @param message QueryTarget + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.firestore.v1.Target.QueryTarget, options?: $protobuf.IConversionOptions): { [k: string]: any }; - /** Value bytesValue */ - bytesValue?: (Uint8Array|null); + /** + * Converts this QueryTarget to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; - /** Value referenceValue */ - referenceValue?: (string|null); + /** + * Gets the default type url for QueryTarget + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + } - /** Value geoPointValue */ - geoPointValue?: (google.type.ILatLng|null); + /** Properties of a TargetChange. */ + interface ITargetChange { - /** Value arrayValue */ - arrayValue?: (google.firestore.v1.IArrayValue|null); + /** TargetChange targetChangeType */ + targetChangeType?: (google.firestore.v1.TargetChange.TargetChangeType|null); - /** Value mapValue */ - mapValue?: (google.firestore.v1.IMapValue|null); + /** TargetChange targetIds */ + targetIds?: (number[]|null); - /** Value fieldReferenceValue */ - fieldReferenceValue?: (string|null); + /** TargetChange cause */ + cause?: (google.rpc.IStatus|null); - /** Value functionValue */ - functionValue?: (google.firestore.v1.IFunction|null); + /** TargetChange resumeToken */ + resumeToken?: (Uint8Array|null); - /** Value pipelineValue */ - pipelineValue?: (google.firestore.v1.IPipeline|null); + /** TargetChange readTime */ + readTime?: (google.protobuf.ITimestamp|null); } - /** Represents a Value. */ - class Value implements IValue { + /** Represents a TargetChange. */ + class TargetChange implements ITargetChange { /** - * Constructs a new Value. + * Constructs a new TargetChange. * @param [properties] Properties to set */ - constructor(properties?: google.firestore.v1.IValue); - - /** Value nullValue. */ - public nullValue?: (google.protobuf.NullValue|null); - - /** Value booleanValue. */ - public booleanValue?: (boolean|null); - - /** Value integerValue. */ - public integerValue?: (number|string|null); - - /** Value doubleValue. */ - public doubleValue?: (number|null); - - /** Value timestampValue. */ - public timestampValue?: (google.protobuf.ITimestamp|null); - - /** Value stringValue. */ - public stringValue?: (string|null); - - /** Value bytesValue. */ - public bytesValue?: (Uint8Array|null); - - /** Value referenceValue. */ - public referenceValue?: (string|null); - - /** Value geoPointValue. */ - public geoPointValue?: (google.type.ILatLng|null); - - /** Value arrayValue. */ - public arrayValue?: (google.firestore.v1.IArrayValue|null); + constructor(properties?: google.firestore.v1.ITargetChange); - /** Value mapValue. */ - public mapValue?: (google.firestore.v1.IMapValue|null); + /** TargetChange targetChangeType. */ + public targetChangeType: google.firestore.v1.TargetChange.TargetChangeType; - /** Value fieldReferenceValue. */ - public fieldReferenceValue?: (string|null); + /** TargetChange targetIds. */ + public targetIds: number[]; - /** Value functionValue. */ - public functionValue?: (google.firestore.v1.IFunction|null); + /** TargetChange cause. */ + public cause?: (google.rpc.IStatus|null); - /** Value pipelineValue. */ - public pipelineValue?: (google.firestore.v1.IPipeline|null); + /** TargetChange resumeToken. */ + public resumeToken: Uint8Array; - /** Value valueType. */ - public valueType?: ("nullValue"|"booleanValue"|"integerValue"|"doubleValue"|"timestampValue"|"stringValue"|"bytesValue"|"referenceValue"|"geoPointValue"|"arrayValue"|"mapValue"|"fieldReferenceValue"|"functionValue"|"pipelineValue"); + /** TargetChange readTime. */ + public readTime?: (google.protobuf.ITimestamp|null); /** - * Creates a Value message from a plain object. Also converts values to their respective internal types. + * Creates a TargetChange message from a plain object. Also converts values to their respective internal types. * @param object Plain object - * @returns Value + * @returns TargetChange */ - public static fromObject(object: { [k: string]: any }): google.firestore.v1.Value; + public static fromObject(object: { [k: string]: any }): google.firestore.v1.TargetChange; /** - * Creates a plain object from a Value message. Also converts values to other types if specified. - * @param message Value + * Creates a plain object from a TargetChange message. Also converts values to other types if specified. + * @param message TargetChange * @param [options] Conversion options * @returns Plain object */ - public static toObject(message: google.firestore.v1.Value, options?: $protobuf.IConversionOptions): { [k: string]: any }; + public static toObject(message: google.firestore.v1.TargetChange, options?: $protobuf.IConversionOptions): { [k: string]: any }; /** - * Converts this Value to JSON. + * Converts this TargetChange to JSON. * @returns JSON object */ public toJSON(): { [k: string]: any }; /** - * Gets the default type url for Value + * Gets the default type url for TargetChange * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") * @returns The default type url */ public static getTypeUrl(typeUrlPrefix?: string): string; } - /** Properties of an ArrayValue. */ - interface IArrayValue { + namespace TargetChange { - /** ArrayValue values */ - values?: (google.firestore.v1.IValue[]|null); + /** TargetChangeType enum. */ + type TargetChangeType = + "NO_CHANGE"| "ADD"| "REMOVE"| "CURRENT"| "RESET"; } - /** Represents an ArrayValue. */ - class ArrayValue implements IArrayValue { + /** Properties of a ListCollectionIdsRequest. */ + interface IListCollectionIdsRequest { + + /** ListCollectionIdsRequest parent */ + parent?: (string|null); + + /** ListCollectionIdsRequest pageSize */ + pageSize?: (number|null); + + /** ListCollectionIdsRequest pageToken */ + pageToken?: (string|null); + + /** ListCollectionIdsRequest readTime */ + readTime?: (google.protobuf.ITimestamp|null); + } + + /** Represents a ListCollectionIdsRequest. */ + class ListCollectionIdsRequest implements IListCollectionIdsRequest { /** - * Constructs a new ArrayValue. + * Constructs a new ListCollectionIdsRequest. * @param [properties] Properties to set */ - constructor(properties?: google.firestore.v1.IArrayValue); + constructor(properties?: google.firestore.v1.IListCollectionIdsRequest); - /** ArrayValue values. */ - public values: google.firestore.v1.IValue[]; + /** ListCollectionIdsRequest parent. */ + public parent: string; + + /** ListCollectionIdsRequest pageSize. */ + public pageSize: number; + + /** ListCollectionIdsRequest pageToken. */ + public pageToken: string; + + /** ListCollectionIdsRequest readTime. */ + public readTime?: (google.protobuf.ITimestamp|null); + + /** ListCollectionIdsRequest consistencySelector. */ + public consistencySelector?: "readTime"; /** - * Creates an ArrayValue message from a plain object. Also converts values to their respective internal types. + * Creates a ListCollectionIdsRequest message from a plain object. Also converts values to their respective internal types. * @param object Plain object - * @returns ArrayValue + * @returns ListCollectionIdsRequest */ - public static fromObject(object: { [k: string]: any }): google.firestore.v1.ArrayValue; + public static fromObject(object: { [k: string]: any }): google.firestore.v1.ListCollectionIdsRequest; /** - * Creates a plain object from an ArrayValue message. Also converts values to other types if specified. - * @param message ArrayValue + * Creates a plain object from a ListCollectionIdsRequest message. Also converts values to other types if specified. + * @param message ListCollectionIdsRequest * @param [options] Conversion options * @returns Plain object */ - public static toObject(message: google.firestore.v1.ArrayValue, options?: $protobuf.IConversionOptions): { [k: string]: any }; + public static toObject(message: google.firestore.v1.ListCollectionIdsRequest, options?: $protobuf.IConversionOptions): { [k: string]: any }; /** - * Converts this ArrayValue to JSON. + * Converts this ListCollectionIdsRequest to JSON. * @returns JSON object */ public toJSON(): { [k: string]: any }; /** - * Gets the default type url for ArrayValue + * Gets the default type url for ListCollectionIdsRequest * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") * @returns The default type url */ public static getTypeUrl(typeUrlPrefix?: string): string; } - /** Properties of a MapValue. */ - interface IMapValue { + /** Properties of a ListCollectionIdsResponse. */ + interface IListCollectionIdsResponse { - /** MapValue fields */ - fields?: ({ [k: string]: google.firestore.v1.IValue }|null); + /** ListCollectionIdsResponse collectionIds */ + collectionIds?: (string[]|null); + + /** ListCollectionIdsResponse nextPageToken */ + nextPageToken?: (string|null); } - /** Represents a MapValue. */ - class MapValue implements IMapValue { + /** Represents a ListCollectionIdsResponse. */ + class ListCollectionIdsResponse implements IListCollectionIdsResponse { /** - * Constructs a new MapValue. + * Constructs a new ListCollectionIdsResponse. * @param [properties] Properties to set */ - constructor(properties?: google.firestore.v1.IMapValue); + constructor(properties?: google.firestore.v1.IListCollectionIdsResponse); - /** MapValue fields. */ - public fields: { [k: string]: google.firestore.v1.IValue }; + /** ListCollectionIdsResponse collectionIds. */ + public collectionIds: string[]; + + /** ListCollectionIdsResponse nextPageToken. */ + public nextPageToken: string; /** - * Creates a MapValue message from a plain object. Also converts values to their respective internal types. + * Creates a ListCollectionIdsResponse message from a plain object. Also converts values to their respective internal types. * @param object Plain object - * @returns MapValue + * @returns ListCollectionIdsResponse */ - public static fromObject(object: { [k: string]: any }): google.firestore.v1.MapValue; + public static fromObject(object: { [k: string]: any }): google.firestore.v1.ListCollectionIdsResponse; /** - * Creates a plain object from a MapValue message. Also converts values to other types if specified. - * @param message MapValue + * Creates a plain object from a ListCollectionIdsResponse message. Also converts values to other types if specified. + * @param message ListCollectionIdsResponse * @param [options] Conversion options * @returns Plain object */ - public static toObject(message: google.firestore.v1.MapValue, options?: $protobuf.IConversionOptions): { [k: string]: any }; + public static toObject(message: google.firestore.v1.ListCollectionIdsResponse, options?: $protobuf.IConversionOptions): { [k: string]: any }; /** - * Converts this MapValue to JSON. + * Converts this ListCollectionIdsResponse to JSON. * @returns JSON object */ public toJSON(): { [k: string]: any }; /** - * Gets the default type url for MapValue + * Gets the default type url for ListCollectionIdsResponse * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") * @returns The default type url */ public static getTypeUrl(typeUrlPrefix?: string): string; } - /** Properties of a Function. */ - interface IFunction { + /** Properties of a BatchWriteRequest. */ + interface IBatchWriteRequest { - /** Function name */ - name?: (string|null); + /** BatchWriteRequest database */ + database?: (string|null); - /** Function args */ - args?: (google.firestore.v1.IValue[]|null); + /** BatchWriteRequest writes */ + writes?: (google.firestore.v1.IWrite[]|null); - /** Function options */ - options?: ({ [k: string]: google.firestore.v1.IValue }|null); + /** BatchWriteRequest labels */ + labels?: ({ [k: string]: string }|null); } - /** Represents a Function. */ - class Function implements IFunction { - + /** Represents a BatchWriteRequest. */ + class BatchWriteRequest implements IBatchWriteRequest { + /** - * Constructs a new Function. + * Constructs a new BatchWriteRequest. * @param [properties] Properties to set */ - constructor(properties?: google.firestore.v1.IFunction); + constructor(properties?: google.firestore.v1.IBatchWriteRequest); - /** Function name. */ - public name: string; + /** BatchWriteRequest database. */ + public database: string; - /** Function args. */ - public args: google.firestore.v1.IValue[]; + /** BatchWriteRequest writes. */ + public writes: google.firestore.v1.IWrite[]; - /** Function options. */ - public options: { [k: string]: google.firestore.v1.IValue }; + /** BatchWriteRequest labels. */ + public labels: { [k: string]: string }; /** - * Creates a Function message from a plain object. Also converts values to their respective internal types. + * Creates a BatchWriteRequest message from a plain object. Also converts values to their respective internal types. * @param object Plain object - * @returns Function + * @returns BatchWriteRequest */ - public static fromObject(object: { [k: string]: any }): google.firestore.v1.Function; + public static fromObject(object: { [k: string]: any }): google.firestore.v1.BatchWriteRequest; /** - * Creates a plain object from a Function message. Also converts values to other types if specified. - * @param message Function + * Creates a plain object from a BatchWriteRequest message. Also converts values to other types if specified. + * @param message BatchWriteRequest * @param [options] Conversion options * @returns Plain object */ - public static toObject(message: google.firestore.v1.Function, options?: $protobuf.IConversionOptions): { [k: string]: any }; + public static toObject(message: google.firestore.v1.BatchWriteRequest, options?: $protobuf.IConversionOptions): { [k: string]: any }; /** - * Converts this Function to JSON. + * Converts this BatchWriteRequest to JSON. * @returns JSON object */ public toJSON(): { [k: string]: any }; /** - * Gets the default type url for Function + * Gets the default type url for BatchWriteRequest * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") * @returns The default type url */ public static getTypeUrl(typeUrlPrefix?: string): string; } - /** Properties of a Pipeline. */ - interface IPipeline { + /** Properties of a BatchWriteResponse. */ + interface IBatchWriteResponse { - /** Pipeline stages */ - stages?: (google.firestore.v1.Pipeline.IStage[]|null); + /** BatchWriteResponse writeResults */ + writeResults?: (google.firestore.v1.IWriteResult[]|null); + + /** BatchWriteResponse status */ + status?: (google.rpc.IStatus[]|null); } - /** Represents a Pipeline. */ - class Pipeline implements IPipeline { + /** Represents a BatchWriteResponse. */ + class BatchWriteResponse implements IBatchWriteResponse { /** - * Constructs a new Pipeline. + * Constructs a new BatchWriteResponse. * @param [properties] Properties to set */ - constructor(properties?: google.firestore.v1.IPipeline); + constructor(properties?: google.firestore.v1.IBatchWriteResponse); - /** Pipeline stages. */ - public stages: google.firestore.v1.Pipeline.IStage[]; + /** BatchWriteResponse writeResults. */ + public writeResults: google.firestore.v1.IWriteResult[]; + + /** BatchWriteResponse status. */ + public status: google.rpc.IStatus[]; /** - * Creates a Pipeline message from a plain object. Also converts values to their respective internal types. + * Creates a BatchWriteResponse message from a plain object. Also converts values to their respective internal types. * @param object Plain object - * @returns Pipeline + * @returns BatchWriteResponse */ - public static fromObject(object: { [k: string]: any }): google.firestore.v1.Pipeline; + public static fromObject(object: { [k: string]: any }): google.firestore.v1.BatchWriteResponse; /** - * Creates a plain object from a Pipeline message. Also converts values to other types if specified. - * @param message Pipeline + * Creates a plain object from a BatchWriteResponse message. Also converts values to other types if specified. + * @param message BatchWriteResponse * @param [options] Conversion options * @returns Plain object */ - public static toObject(message: google.firestore.v1.Pipeline, options?: $protobuf.IConversionOptions): { [k: string]: any }; + public static toObject(message: google.firestore.v1.BatchWriteResponse, options?: $protobuf.IConversionOptions): { [k: string]: any }; /** - * Converts this Pipeline to JSON. + * Converts this BatchWriteResponse to JSON. * @returns JSON object */ public toJSON(): { [k: string]: any }; /** - * Gets the default type url for Pipeline + * Gets the default type url for BatchWriteResponse * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") * @returns The default type url */ public static getTypeUrl(typeUrlPrefix?: string): string; } - namespace Pipeline { + /** Properties of a StructuredPipeline. */ + interface IStructuredPipeline { - /** Properties of a Stage. */ - interface IStage { + /** StructuredPipeline pipeline */ + pipeline?: (google.firestore.v1.IPipeline|null); - /** Stage name */ - name?: (string|null); + /** StructuredPipeline options */ + options?: ({ [k: string]: google.firestore.v1.IValue }|null); + } - /** Stage args */ - args?: (google.firestore.v1.IValue[]|null); + /** Represents a StructuredPipeline. */ + class StructuredPipeline implements IStructuredPipeline { - /** Stage options */ - options?: ({ [k: string]: google.firestore.v1.IValue }|null); - } + /** + * Constructs a new StructuredPipeline. + * @param [properties] Properties to set + */ + constructor(properties?: google.firestore.v1.IStructuredPipeline); - /** Represents a Stage. */ - class Stage implements IStage { + /** StructuredPipeline pipeline. */ + public pipeline?: (google.firestore.v1.IPipeline|null); - /** - * Constructs a new Stage. - * @param [properties] Properties to set - */ - constructor(properties?: google.firestore.v1.Pipeline.IStage); + /** StructuredPipeline options. */ + public options: { [k: string]: google.firestore.v1.IValue }; - /** Stage name. */ - public name: string; + /** + * Creates a StructuredPipeline message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns StructuredPipeline + */ + public static fromObject(object: { [k: string]: any }): google.firestore.v1.StructuredPipeline; - /** Stage args. */ - public args: google.firestore.v1.IValue[]; + /** + * Creates a plain object from a StructuredPipeline message. Also converts values to other types if specified. + * @param message StructuredPipeline + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.firestore.v1.StructuredPipeline, options?: $protobuf.IConversionOptions): { [k: string]: any }; - /** Stage options. */ - public options: { [k: string]: google.firestore.v1.IValue }; + /** + * Converts this StructuredPipeline to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; - /** - * Creates a Stage message from a plain object. Also converts values to their respective internal types. - * @param object Plain object - * @returns Stage - */ - public static fromObject(object: { [k: string]: any }): google.firestore.v1.Pipeline.Stage; + /** + * Gets the default type url for StructuredPipeline + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } - /** - * Creates a plain object from a Stage message. Also converts values to other types if specified. - * @param message Stage - * @param [options] Conversion options - * @returns Plain object - */ - public static toObject(message: google.firestore.v1.Pipeline.Stage, options?: $protobuf.IConversionOptions): { [k: string]: any }; + /** Properties of a StructuredQuery. */ + interface IStructuredQuery { - /** - * Converts this Stage to JSON. - * @returns JSON object - */ - public toJSON(): { [k: string]: any }; + /** StructuredQuery select */ + select?: (google.firestore.v1.StructuredQuery.IProjection|null); - /** - * Gets the default type url for Stage - * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") - * @returns The default type url - */ - public static getTypeUrl(typeUrlPrefix?: string): string; - } - } + /** StructuredQuery from */ + from?: (google.firestore.v1.StructuredQuery.ICollectionSelector[]|null); - /** Properties of a BitSequence. */ - interface IBitSequence { + /** StructuredQuery where */ + where?: (google.firestore.v1.StructuredQuery.IFilter|null); - /** BitSequence bitmap */ - bitmap?: (Uint8Array|null); + /** StructuredQuery orderBy */ + orderBy?: (google.firestore.v1.StructuredQuery.IOrder[]|null); - /** BitSequence padding */ - padding?: (number|null); + /** StructuredQuery startAt */ + startAt?: (google.firestore.v1.ICursor|null); + + /** StructuredQuery endAt */ + endAt?: (google.firestore.v1.ICursor|null); + + /** StructuredQuery offset */ + offset?: (number|null); + + /** StructuredQuery limit */ + limit?: (google.protobuf.IInt32Value|null); + + /** StructuredQuery findNearest */ + findNearest?: (google.firestore.v1.StructuredQuery.IFindNearest|null); } - /** Represents a BitSequence. */ - class BitSequence implements IBitSequence { + /** Represents a StructuredQuery. */ + class StructuredQuery implements IStructuredQuery { /** - * Constructs a new BitSequence. + * Constructs a new StructuredQuery. * @param [properties] Properties to set */ - constructor(properties?: google.firestore.v1.IBitSequence); + constructor(properties?: google.firestore.v1.IStructuredQuery); - /** BitSequence bitmap. */ - public bitmap: Uint8Array; + /** StructuredQuery select. */ + public select?: (google.firestore.v1.StructuredQuery.IProjection|null); - /** BitSequence padding. */ - public padding: number; + /** StructuredQuery from. */ + public from: google.firestore.v1.StructuredQuery.ICollectionSelector[]; + + /** StructuredQuery where. */ + public where?: (google.firestore.v1.StructuredQuery.IFilter|null); + + /** StructuredQuery orderBy. */ + public orderBy: google.firestore.v1.StructuredQuery.IOrder[]; + + /** StructuredQuery startAt. */ + public startAt?: (google.firestore.v1.ICursor|null); + + /** StructuredQuery endAt. */ + public endAt?: (google.firestore.v1.ICursor|null); + + /** StructuredQuery offset. */ + public offset: number; + + /** StructuredQuery limit. */ + public limit?: (google.protobuf.IInt32Value|null); + + /** StructuredQuery findNearest. */ + public findNearest?: (google.firestore.v1.StructuredQuery.IFindNearest|null); /** - * Creates a BitSequence message from a plain object. Also converts values to their respective internal types. + * Creates a StructuredQuery message from a plain object. Also converts values to their respective internal types. * @param object Plain object - * @returns BitSequence + * @returns StructuredQuery */ - public static fromObject(object: { [k: string]: any }): google.firestore.v1.BitSequence; + public static fromObject(object: { [k: string]: any }): google.firestore.v1.StructuredQuery; /** - * Creates a plain object from a BitSequence message. Also converts values to other types if specified. - * @param message BitSequence + * Creates a plain object from a StructuredQuery message. Also converts values to other types if specified. + * @param message StructuredQuery * @param [options] Conversion options * @returns Plain object */ - public static toObject(message: google.firestore.v1.BitSequence, options?: $protobuf.IConversionOptions): { [k: string]: any }; + public static toObject(message: google.firestore.v1.StructuredQuery, options?: $protobuf.IConversionOptions): { [k: string]: any }; /** - * Converts this BitSequence to JSON. + * Converts this StructuredQuery to JSON. * @returns JSON object */ public toJSON(): { [k: string]: any }; /** - * Gets the default type url for BitSequence + * Gets the default type url for StructuredQuery * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") * @returns The default type url */ public static getTypeUrl(typeUrlPrefix?: string): string; } - /** Properties of a BloomFilter. */ - interface IBloomFilter { + namespace StructuredQuery { - /** BloomFilter bits */ - bits?: (google.firestore.v1.IBitSequence|null); + /** Properties of a CollectionSelector. */ + interface ICollectionSelector { - /** BloomFilter hashCount */ - hashCount?: (number|null); - } + /** CollectionSelector collectionId */ + collectionId?: (string|null); - /** Represents a BloomFilter. */ - class BloomFilter implements IBloomFilter { + /** CollectionSelector allDescendants */ + allDescendants?: (boolean|null); + } - /** - * Constructs a new BloomFilter. - * @param [properties] Properties to set - */ - constructor(properties?: google.firestore.v1.IBloomFilter); + /** Represents a CollectionSelector. */ + class CollectionSelector implements ICollectionSelector { - /** BloomFilter bits. */ - public bits?: (google.firestore.v1.IBitSequence|null); + /** + * Constructs a new CollectionSelector. + * @param [properties] Properties to set + */ + constructor(properties?: google.firestore.v1.StructuredQuery.ICollectionSelector); - /** BloomFilter hashCount. */ - public hashCount: number; + /** CollectionSelector collectionId. */ + public collectionId: string; - /** - * Creates a BloomFilter message from a plain object. Also converts values to their respective internal types. - * @param object Plain object - * @returns BloomFilter - */ - public static fromObject(object: { [k: string]: any }): google.firestore.v1.BloomFilter; + /** CollectionSelector allDescendants. */ + public allDescendants: boolean; - /** - * Creates a plain object from a BloomFilter message. Also converts values to other types if specified. - * @param message BloomFilter - * @param [options] Conversion options - * @returns Plain object - */ - public static toObject(message: google.firestore.v1.BloomFilter, options?: $protobuf.IConversionOptions): { [k: string]: any }; + /** + * Creates a CollectionSelector message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns CollectionSelector + */ + public static fromObject(object: { [k: string]: any }): google.firestore.v1.StructuredQuery.CollectionSelector; - /** - * Converts this BloomFilter to JSON. - * @returns JSON object - */ - public toJSON(): { [k: string]: any }; + /** + * Creates a plain object from a CollectionSelector message. Also converts values to other types if specified. + * @param message CollectionSelector + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.firestore.v1.StructuredQuery.CollectionSelector, options?: $protobuf.IConversionOptions): { [k: string]: any }; - /** - * Gets the default type url for BloomFilter - * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") - * @returns The default type url - */ - public static getTypeUrl(typeUrlPrefix?: string): string; - } + /** + * Converts this CollectionSelector to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; - /** Properties of a DocumentMask. */ - interface IDocumentMask { + /** + * Gets the default type url for CollectionSelector + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } - /** DocumentMask fieldPaths */ - fieldPaths?: (string[]|null); - } + /** Properties of a Filter. */ + interface IFilter { - /** Represents a DocumentMask. */ - class DocumentMask implements IDocumentMask { + /** Filter compositeFilter */ + compositeFilter?: (google.firestore.v1.StructuredQuery.ICompositeFilter|null); - /** - * Constructs a new DocumentMask. - * @param [properties] Properties to set - */ - constructor(properties?: google.firestore.v1.IDocumentMask); + /** Filter fieldFilter */ + fieldFilter?: (google.firestore.v1.StructuredQuery.IFieldFilter|null); - /** DocumentMask fieldPaths. */ - public fieldPaths: string[]; + /** Filter unaryFilter */ + unaryFilter?: (google.firestore.v1.StructuredQuery.IUnaryFilter|null); + } - /** - * Creates a DocumentMask message from a plain object. Also converts values to their respective internal types. - * @param object Plain object - * @returns DocumentMask - */ - public static fromObject(object: { [k: string]: any }): google.firestore.v1.DocumentMask; + /** Represents a Filter. */ + class Filter implements IFilter { - /** - * Creates a plain object from a DocumentMask message. Also converts values to other types if specified. - * @param message DocumentMask - * @param [options] Conversion options - * @returns Plain object - */ - public static toObject(message: google.firestore.v1.DocumentMask, options?: $protobuf.IConversionOptions): { [k: string]: any }; + /** + * Constructs a new Filter. + * @param [properties] Properties to set + */ + constructor(properties?: google.firestore.v1.StructuredQuery.IFilter); - /** - * Converts this DocumentMask to JSON. - * @returns JSON object - */ - public toJSON(): { [k: string]: any }; + /** Filter compositeFilter. */ + public compositeFilter?: (google.firestore.v1.StructuredQuery.ICompositeFilter|null); - /** - * Gets the default type url for DocumentMask - * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") - * @returns The default type url - */ - public static getTypeUrl(typeUrlPrefix?: string): string; - } + /** Filter fieldFilter. */ + public fieldFilter?: (google.firestore.v1.StructuredQuery.IFieldFilter|null); - /** Properties of a Precondition. */ - interface IPrecondition { + /** Filter unaryFilter. */ + public unaryFilter?: (google.firestore.v1.StructuredQuery.IUnaryFilter|null); - /** Precondition exists */ - exists?: (boolean|null); + /** Filter filterType. */ + public filterType?: ("compositeFilter"|"fieldFilter"|"unaryFilter"); - /** Precondition updateTime */ - updateTime?: (google.protobuf.ITimestamp|null); - } + /** + * Creates a Filter message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns Filter + */ + public static fromObject(object: { [k: string]: any }): google.firestore.v1.StructuredQuery.Filter; - /** Represents a Precondition. */ - class Precondition implements IPrecondition { + /** + * Creates a plain object from a Filter message. Also converts values to other types if specified. + * @param message Filter + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.firestore.v1.StructuredQuery.Filter, options?: $protobuf.IConversionOptions): { [k: string]: any }; - /** - * Constructs a new Precondition. - * @param [properties] Properties to set - */ - constructor(properties?: google.firestore.v1.IPrecondition); + /** + * Converts this Filter to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; - /** Precondition exists. */ - public exists?: (boolean|null); + /** + * Gets the default type url for Filter + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } - /** Precondition updateTime. */ - public updateTime?: (google.protobuf.ITimestamp|null); + /** Properties of a CompositeFilter. */ + interface ICompositeFilter { - /** Precondition conditionType. */ - public conditionType?: ("exists"|"updateTime"); + /** CompositeFilter op */ + op?: (google.firestore.v1.StructuredQuery.CompositeFilter.Operator|null); - /** - * Creates a Precondition message from a plain object. Also converts values to their respective internal types. - * @param object Plain object - * @returns Precondition - */ - public static fromObject(object: { [k: string]: any }): google.firestore.v1.Precondition; + /** CompositeFilter filters */ + filters?: (google.firestore.v1.StructuredQuery.IFilter[]|null); + } - /** - * Creates a plain object from a Precondition message. Also converts values to other types if specified. - * @param message Precondition - * @param [options] Conversion options - * @returns Plain object - */ - public static toObject(message: google.firestore.v1.Precondition, options?: $protobuf.IConversionOptions): { [k: string]: any }; + /** Represents a CompositeFilter. */ + class CompositeFilter implements ICompositeFilter { - /** - * Converts this Precondition to JSON. - * @returns JSON object - */ - public toJSON(): { [k: string]: any }; + /** + * Constructs a new CompositeFilter. + * @param [properties] Properties to set + */ + constructor(properties?: google.firestore.v1.StructuredQuery.ICompositeFilter); - /** - * Gets the default type url for Precondition - * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") - * @returns The default type url - */ - public static getTypeUrl(typeUrlPrefix?: string): string; - } + /** CompositeFilter op. */ + public op: google.firestore.v1.StructuredQuery.CompositeFilter.Operator; - /** Properties of a TransactionOptions. */ - interface ITransactionOptions { + /** CompositeFilter filters. */ + public filters: google.firestore.v1.StructuredQuery.IFilter[]; - /** TransactionOptions readOnly */ - readOnly?: (google.firestore.v1.TransactionOptions.IReadOnly|null); + /** + * Creates a CompositeFilter message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns CompositeFilter + */ + public static fromObject(object: { [k: string]: any }): google.firestore.v1.StructuredQuery.CompositeFilter; - /** TransactionOptions readWrite */ - readWrite?: (google.firestore.v1.TransactionOptions.IReadWrite|null); - } + /** + * Creates a plain object from a CompositeFilter message. Also converts values to other types if specified. + * @param message CompositeFilter + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.firestore.v1.StructuredQuery.CompositeFilter, options?: $protobuf.IConversionOptions): { [k: string]: any }; - /** Represents a TransactionOptions. */ - class TransactionOptions implements ITransactionOptions { - - /** - * Constructs a new TransactionOptions. - * @param [properties] Properties to set - */ - constructor(properties?: google.firestore.v1.ITransactionOptions); - - /** TransactionOptions readOnly. */ - public readOnly?: (google.firestore.v1.TransactionOptions.IReadOnly|null); - - /** TransactionOptions readWrite. */ - public readWrite?: (google.firestore.v1.TransactionOptions.IReadWrite|null); - - /** TransactionOptions mode. */ - public mode?: ("readOnly"|"readWrite"); + /** + * Converts this CompositeFilter to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; - /** - * Creates a TransactionOptions message from a plain object. Also converts values to their respective internal types. - * @param object Plain object - * @returns TransactionOptions - */ - public static fromObject(object: { [k: string]: any }): google.firestore.v1.TransactionOptions; + /** + * Gets the default type url for CompositeFilter + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } - /** - * Creates a plain object from a TransactionOptions message. Also converts values to other types if specified. - * @param message TransactionOptions - * @param [options] Conversion options - * @returns Plain object - */ - public static toObject(message: google.firestore.v1.TransactionOptions, options?: $protobuf.IConversionOptions): { [k: string]: any }; + namespace CompositeFilter { - /** - * Converts this TransactionOptions to JSON. - * @returns JSON object - */ - public toJSON(): { [k: string]: any }; + /** Operator enum. */ + type Operator = + "OPERATOR_UNSPECIFIED"| "AND"| "OR"; + } - /** - * Gets the default type url for TransactionOptions - * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") - * @returns The default type url - */ - public static getTypeUrl(typeUrlPrefix?: string): string; - } + /** Properties of a FieldFilter. */ + interface IFieldFilter { - namespace TransactionOptions { + /** FieldFilter field */ + field?: (google.firestore.v1.StructuredQuery.IFieldReference|null); - /** Properties of a ReadWrite. */ - interface IReadWrite { + /** FieldFilter op */ + op?: (google.firestore.v1.StructuredQuery.FieldFilter.Operator|null); - /** ReadWrite retryTransaction */ - retryTransaction?: (Uint8Array|null); + /** FieldFilter value */ + value?: (google.firestore.v1.IValue|null); } - /** Represents a ReadWrite. */ - class ReadWrite implements IReadWrite { + /** Represents a FieldFilter. */ + class FieldFilter implements IFieldFilter { /** - * Constructs a new ReadWrite. + * Constructs a new FieldFilter. * @param [properties] Properties to set */ - constructor(properties?: google.firestore.v1.TransactionOptions.IReadWrite); + constructor(properties?: google.firestore.v1.StructuredQuery.IFieldFilter); - /** ReadWrite retryTransaction. */ - public retryTransaction: Uint8Array; + /** FieldFilter field. */ + public field?: (google.firestore.v1.StructuredQuery.IFieldReference|null); + + /** FieldFilter op. */ + public op: google.firestore.v1.StructuredQuery.FieldFilter.Operator; + + /** FieldFilter value. */ + public value?: (google.firestore.v1.IValue|null); /** - * Creates a ReadWrite message from a plain object. Also converts values to their respective internal types. + * Creates a FieldFilter message from a plain object. Also converts values to their respective internal types. * @param object Plain object - * @returns ReadWrite + * @returns FieldFilter */ - public static fromObject(object: { [k: string]: any }): google.firestore.v1.TransactionOptions.ReadWrite; + public static fromObject(object: { [k: string]: any }): google.firestore.v1.StructuredQuery.FieldFilter; /** - * Creates a plain object from a ReadWrite message. Also converts values to other types if specified. - * @param message ReadWrite + * Creates a plain object from a FieldFilter message. Also converts values to other types if specified. + * @param message FieldFilter * @param [options] Conversion options * @returns Plain object */ - public static toObject(message: google.firestore.v1.TransactionOptions.ReadWrite, options?: $protobuf.IConversionOptions): { [k: string]: any }; + public static toObject(message: google.firestore.v1.StructuredQuery.FieldFilter, options?: $protobuf.IConversionOptions): { [k: string]: any }; /** - * Converts this ReadWrite to JSON. + * Converts this FieldFilter to JSON. * @returns JSON object */ public toJSON(): { [k: string]: any }; /** - * Gets the default type url for ReadWrite + * Gets the default type url for FieldFilter * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") * @returns The default type url */ public static getTypeUrl(typeUrlPrefix?: string): string; } - /** Properties of a ReadOnly. */ - interface IReadOnly { + namespace FieldFilter { - /** ReadOnly readTime */ - readTime?: (google.protobuf.ITimestamp|null); + /** Operator enum. */ + type Operator = + "OPERATOR_UNSPECIFIED"| "LESS_THAN"| "LESS_THAN_OR_EQUAL"| "GREATER_THAN"| "GREATER_THAN_OR_EQUAL"| "EQUAL"| "NOT_EQUAL"| "ARRAY_CONTAINS"| "IN"| "ARRAY_CONTAINS_ANY"| "NOT_IN"; } - /** Represents a ReadOnly. */ - class ReadOnly implements IReadOnly { + /** Properties of an UnaryFilter. */ + interface IUnaryFilter { + + /** UnaryFilter op */ + op?: (google.firestore.v1.StructuredQuery.UnaryFilter.Operator|null); + + /** UnaryFilter field */ + field?: (google.firestore.v1.StructuredQuery.IFieldReference|null); + } + + /** Represents an UnaryFilter. */ + class UnaryFilter implements IUnaryFilter { /** - * Constructs a new ReadOnly. + * Constructs a new UnaryFilter. * @param [properties] Properties to set */ - constructor(properties?: google.firestore.v1.TransactionOptions.IReadOnly); + constructor(properties?: google.firestore.v1.StructuredQuery.IUnaryFilter); - /** ReadOnly readTime. */ - public readTime?: (google.protobuf.ITimestamp|null); + /** UnaryFilter op. */ + public op: google.firestore.v1.StructuredQuery.UnaryFilter.Operator; - /** ReadOnly consistencySelector. */ - public consistencySelector?: "readTime"; + /** UnaryFilter field. */ + public field?: (google.firestore.v1.StructuredQuery.IFieldReference|null); + + /** UnaryFilter operandType. */ + public operandType?: "field"; /** - * Creates a ReadOnly message from a plain object. Also converts values to their respective internal types. + * Creates an UnaryFilter message from a plain object. Also converts values to their respective internal types. * @param object Plain object - * @returns ReadOnly + * @returns UnaryFilter */ - public static fromObject(object: { [k: string]: any }): google.firestore.v1.TransactionOptions.ReadOnly; + public static fromObject(object: { [k: string]: any }): google.firestore.v1.StructuredQuery.UnaryFilter; /** - * Creates a plain object from a ReadOnly message. Also converts values to other types if specified. - * @param message ReadOnly + * Creates a plain object from an UnaryFilter message. Also converts values to other types if specified. + * @param message UnaryFilter * @param [options] Conversion options * @returns Plain object */ - public static toObject(message: google.firestore.v1.TransactionOptions.ReadOnly, options?: $protobuf.IConversionOptions): { [k: string]: any }; + public static toObject(message: google.firestore.v1.StructuredQuery.UnaryFilter, options?: $protobuf.IConversionOptions): { [k: string]: any }; /** - * Converts this ReadOnly to JSON. + * Converts this UnaryFilter to JSON. * @returns JSON object */ public toJSON(): { [k: string]: any }; /** - * Gets the default type url for ReadOnly + * Gets the default type url for UnaryFilter * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") * @returns The default type url */ public static getTypeUrl(typeUrlPrefix?: string): string; } - } - - /** Represents a Firestore */ - class Firestore extends $protobuf.rpc.Service { - /** - * Constructs a new Firestore service. - * @param rpcImpl RPC implementation - * @param [requestDelimited=false] Whether requests are length-delimited - * @param [responseDelimited=false] Whether responses are length-delimited - */ - constructor(rpcImpl: $protobuf.RPCImpl, requestDelimited?: boolean, responseDelimited?: boolean); + namespace UnaryFilter { - /** - * Calls GetDocument. - * @param request GetDocumentRequest message or plain object - * @param callback Node-style callback called with the error, if any, and Document - */ - public getDocument(request: google.firestore.v1.IGetDocumentRequest, callback: google.firestore.v1.Firestore.GetDocumentCallback): void; + /** Operator enum. */ + type Operator = + "OPERATOR_UNSPECIFIED"| "IS_NAN"| "IS_NULL"| "IS_NOT_NAN"| "IS_NOT_NULL"; + } - /** - * Calls GetDocument. - * @param request GetDocumentRequest message or plain object - * @returns Promise - */ - public getDocument(request: google.firestore.v1.IGetDocumentRequest): Promise; + /** Properties of an Order. */ + interface IOrder { - /** - * Calls ListDocuments. - * @param request ListDocumentsRequest message or plain object - * @param callback Node-style callback called with the error, if any, and ListDocumentsResponse - */ - public listDocuments(request: google.firestore.v1.IListDocumentsRequest, callback: google.firestore.v1.Firestore.ListDocumentsCallback): void; + /** Order field */ + field?: (google.firestore.v1.StructuredQuery.IFieldReference|null); - /** - * Calls ListDocuments. - * @param request ListDocumentsRequest message or plain object - * @returns Promise - */ - public listDocuments(request: google.firestore.v1.IListDocumentsRequest): Promise; + /** Order direction */ + direction?: (google.firestore.v1.StructuredQuery.Direction|null); + } - /** - * Calls UpdateDocument. - * @param request UpdateDocumentRequest message or plain object - * @param callback Node-style callback called with the error, if any, and Document - */ - public updateDocument(request: google.firestore.v1.IUpdateDocumentRequest, callback: google.firestore.v1.Firestore.UpdateDocumentCallback): void; + /** Represents an Order. */ + class Order implements IOrder { - /** - * Calls UpdateDocument. - * @param request UpdateDocumentRequest message or plain object - * @returns Promise - */ - public updateDocument(request: google.firestore.v1.IUpdateDocumentRequest): Promise; + /** + * Constructs a new Order. + * @param [properties] Properties to set + */ + constructor(properties?: google.firestore.v1.StructuredQuery.IOrder); - /** - * Calls DeleteDocument. - * @param request DeleteDocumentRequest message or plain object - * @param callback Node-style callback called with the error, if any, and Empty - */ - public deleteDocument(request: google.firestore.v1.IDeleteDocumentRequest, callback: google.firestore.v1.Firestore.DeleteDocumentCallback): void; + /** Order field. */ + public field?: (google.firestore.v1.StructuredQuery.IFieldReference|null); - /** - * Calls DeleteDocument. - * @param request DeleteDocumentRequest message or plain object - * @returns Promise - */ - public deleteDocument(request: google.firestore.v1.IDeleteDocumentRequest): Promise; + /** Order direction. */ + public direction: google.firestore.v1.StructuredQuery.Direction; - /** - * Calls BatchGetDocuments. - * @param request BatchGetDocumentsRequest message or plain object - * @param callback Node-style callback called with the error, if any, and BatchGetDocumentsResponse - */ - public batchGetDocuments(request: google.firestore.v1.IBatchGetDocumentsRequest, callback: google.firestore.v1.Firestore.BatchGetDocumentsCallback): void; + /** + * Creates an Order message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns Order + */ + public static fromObject(object: { [k: string]: any }): google.firestore.v1.StructuredQuery.Order; - /** - * Calls BatchGetDocuments. - * @param request BatchGetDocumentsRequest message or plain object - * @returns Promise - */ - public batchGetDocuments(request: google.firestore.v1.IBatchGetDocumentsRequest): Promise; + /** + * Creates a plain object from an Order message. Also converts values to other types if specified. + * @param message Order + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.firestore.v1.StructuredQuery.Order, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this Order to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for Order + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Direction enum. */ + type Direction = + "DIRECTION_UNSPECIFIED"| "ASCENDING"| "DESCENDING"; + + /** Properties of a FieldReference. */ + interface IFieldReference { + + /** FieldReference fieldPath */ + fieldPath?: (string|null); + } + + /** Represents a FieldReference. */ + class FieldReference implements IFieldReference { + + /** + * Constructs a new FieldReference. + * @param [properties] Properties to set + */ + constructor(properties?: google.firestore.v1.StructuredQuery.IFieldReference); + + /** FieldReference fieldPath. */ + public fieldPath: string; + + /** + * Creates a FieldReference message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns FieldReference + */ + public static fromObject(object: { [k: string]: any }): google.firestore.v1.StructuredQuery.FieldReference; + + /** + * Creates a plain object from a FieldReference message. Also converts values to other types if specified. + * @param message FieldReference + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.firestore.v1.StructuredQuery.FieldReference, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this FieldReference to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for FieldReference + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a Projection. */ + interface IProjection { + + /** Projection fields */ + fields?: (google.firestore.v1.StructuredQuery.IFieldReference[]|null); + } + + /** Represents a Projection. */ + class Projection implements IProjection { + + /** + * Constructs a new Projection. + * @param [properties] Properties to set + */ + constructor(properties?: google.firestore.v1.StructuredQuery.IProjection); + + /** Projection fields. */ + public fields: google.firestore.v1.StructuredQuery.IFieldReference[]; + + /** + * Creates a Projection message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns Projection + */ + public static fromObject(object: { [k: string]: any }): google.firestore.v1.StructuredQuery.Projection; + + /** + * Creates a plain object from a Projection message. Also converts values to other types if specified. + * @param message Projection + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.firestore.v1.StructuredQuery.Projection, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this Projection to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for Projection + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a FindNearest. */ + interface IFindNearest { + + /** FindNearest vectorField */ + vectorField?: (google.firestore.v1.StructuredQuery.IFieldReference|null); + + /** FindNearest queryVector */ + queryVector?: (google.firestore.v1.IValue|null); + + /** FindNearest distanceMeasure */ + distanceMeasure?: (google.firestore.v1.StructuredQuery.FindNearest.DistanceMeasure|null); + + /** FindNearest limit */ + limit?: (google.protobuf.IInt32Value|null); + + /** FindNearest distanceResultField */ + distanceResultField?: (string|null); + + /** FindNearest distanceThreshold */ + distanceThreshold?: (google.protobuf.IDoubleValue|null); + } + + /** Represents a FindNearest. */ + class FindNearest implements IFindNearest { + + /** + * Constructs a new FindNearest. + * @param [properties] Properties to set + */ + constructor(properties?: google.firestore.v1.StructuredQuery.IFindNearest); + + /** FindNearest vectorField. */ + public vectorField?: (google.firestore.v1.StructuredQuery.IFieldReference|null); + + /** FindNearest queryVector. */ + public queryVector?: (google.firestore.v1.IValue|null); + + /** FindNearest distanceMeasure. */ + public distanceMeasure: google.firestore.v1.StructuredQuery.FindNearest.DistanceMeasure; + + /** FindNearest limit. */ + public limit?: (google.protobuf.IInt32Value|null); + + /** FindNearest distanceResultField. */ + public distanceResultField: string; + + /** FindNearest distanceThreshold. */ + public distanceThreshold?: (google.protobuf.IDoubleValue|null); + + /** + * Creates a FindNearest message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns FindNearest + */ + public static fromObject(object: { [k: string]: any }): google.firestore.v1.StructuredQuery.FindNearest; + + /** + * Creates a plain object from a FindNearest message. Also converts values to other types if specified. + * @param message FindNearest + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.firestore.v1.StructuredQuery.FindNearest, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this FindNearest to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for FindNearest + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + namespace FindNearest { + + /** DistanceMeasure enum. */ + type DistanceMeasure = + "DISTANCE_MEASURE_UNSPECIFIED"| "EUCLIDEAN"| "COSINE"| "DOT_PRODUCT"; + } + } + + /** Properties of a StructuredAggregationQuery. */ + interface IStructuredAggregationQuery { + + /** StructuredAggregationQuery structuredQuery */ + structuredQuery?: (google.firestore.v1.IStructuredQuery|null); + + /** StructuredAggregationQuery aggregations */ + aggregations?: (google.firestore.v1.StructuredAggregationQuery.IAggregation[]|null); + } + + /** Represents a StructuredAggregationQuery. */ + class StructuredAggregationQuery implements IStructuredAggregationQuery { + + /** + * Constructs a new StructuredAggregationQuery. + * @param [properties] Properties to set + */ + constructor(properties?: google.firestore.v1.IStructuredAggregationQuery); + + /** StructuredAggregationQuery structuredQuery. */ + public structuredQuery?: (google.firestore.v1.IStructuredQuery|null); + + /** StructuredAggregationQuery aggregations. */ + public aggregations: google.firestore.v1.StructuredAggregationQuery.IAggregation[]; + + /** StructuredAggregationQuery queryType. */ + public queryType?: "structuredQuery"; + + /** + * Creates a StructuredAggregationQuery message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns StructuredAggregationQuery + */ + public static fromObject(object: { [k: string]: any }): google.firestore.v1.StructuredAggregationQuery; + + /** + * Creates a plain object from a StructuredAggregationQuery message. Also converts values to other types if specified. + * @param message StructuredAggregationQuery + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.firestore.v1.StructuredAggregationQuery, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this StructuredAggregationQuery to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for StructuredAggregationQuery + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + namespace StructuredAggregationQuery { + + /** Properties of an Aggregation. */ + interface IAggregation { + + /** Aggregation count */ + count?: (google.firestore.v1.StructuredAggregationQuery.Aggregation.ICount|null); + + /** Aggregation sum */ + sum?: (google.firestore.v1.StructuredAggregationQuery.Aggregation.ISum|null); + + /** Aggregation avg */ + avg?: (google.firestore.v1.StructuredAggregationQuery.Aggregation.IAvg|null); + + /** Aggregation alias */ + alias?: (string|null); + } + + /** Represents an Aggregation. */ + class Aggregation implements IAggregation { + + /** + * Constructs a new Aggregation. + * @param [properties] Properties to set + */ + constructor(properties?: google.firestore.v1.StructuredAggregationQuery.IAggregation); + + /** Aggregation count. */ + public count?: (google.firestore.v1.StructuredAggregationQuery.Aggregation.ICount|null); + + /** Aggregation sum. */ + public sum?: (google.firestore.v1.StructuredAggregationQuery.Aggregation.ISum|null); + + /** Aggregation avg. */ + public avg?: (google.firestore.v1.StructuredAggregationQuery.Aggregation.IAvg|null); + + /** Aggregation alias. */ + public alias: string; + + /** Aggregation operator. */ + public operator?: ("count"|"sum"|"avg"); + + /** + * Creates an Aggregation message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns Aggregation + */ + public static fromObject(object: { [k: string]: any }): google.firestore.v1.StructuredAggregationQuery.Aggregation; + + /** + * Creates a plain object from an Aggregation message. Also converts values to other types if specified. + * @param message Aggregation + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.firestore.v1.StructuredAggregationQuery.Aggregation, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this Aggregation to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for Aggregation + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + namespace Aggregation { + + /** Properties of a Count. */ + interface ICount { + + /** Count upTo */ + upTo?: (google.protobuf.IInt64Value|null); + } + + /** Represents a Count. */ + class Count implements ICount { + + /** + * Constructs a new Count. + * @param [properties] Properties to set + */ + constructor(properties?: google.firestore.v1.StructuredAggregationQuery.Aggregation.ICount); + + /** Count upTo. */ + public upTo?: (google.protobuf.IInt64Value|null); + + /** + * Creates a Count message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns Count + */ + public static fromObject(object: { [k: string]: any }): google.firestore.v1.StructuredAggregationQuery.Aggregation.Count; - /** - * Calls BeginTransaction. - * @param request BeginTransactionRequest message or plain object - * @param callback Node-style callback called with the error, if any, and BeginTransactionResponse - */ - public beginTransaction(request: google.firestore.v1.IBeginTransactionRequest, callback: google.firestore.v1.Firestore.BeginTransactionCallback): void; + /** + * Creates a plain object from a Count message. Also converts values to other types if specified. + * @param message Count + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.firestore.v1.StructuredAggregationQuery.Aggregation.Count, options?: $protobuf.IConversionOptions): { [k: string]: any }; - /** - * Calls BeginTransaction. - * @param request BeginTransactionRequest message or plain object - * @returns Promise - */ - public beginTransaction(request: google.firestore.v1.IBeginTransactionRequest): Promise; + /** + * Converts this Count to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; - /** - * Calls Commit. - * @param request CommitRequest message or plain object - * @param callback Node-style callback called with the error, if any, and CommitResponse - */ - public commit(request: google.firestore.v1.ICommitRequest, callback: google.firestore.v1.Firestore.CommitCallback): void; + /** + * Gets the default type url for Count + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } - /** - * Calls Commit. - * @param request CommitRequest message or plain object - * @returns Promise - */ - public commit(request: google.firestore.v1.ICommitRequest): Promise; + /** Properties of a Sum. */ + interface ISum { - /** - * Calls Rollback. - * @param request RollbackRequest message or plain object - * @param callback Node-style callback called with the error, if any, and Empty - */ - public rollback(request: google.firestore.v1.IRollbackRequest, callback: google.firestore.v1.Firestore.RollbackCallback): void; + /** Sum field */ + field?: (google.firestore.v1.StructuredQuery.IFieldReference|null); + } - /** - * Calls Rollback. - * @param request RollbackRequest message or plain object - * @returns Promise - */ - public rollback(request: google.firestore.v1.IRollbackRequest): Promise; + /** Represents a Sum. */ + class Sum implements ISum { - /** - * Calls RunQuery. - * @param request RunQueryRequest message or plain object - * @param callback Node-style callback called with the error, if any, and RunQueryResponse - */ - public runQuery(request: google.firestore.v1.IRunQueryRequest, callback: google.firestore.v1.Firestore.RunQueryCallback): void; + /** + * Constructs a new Sum. + * @param [properties] Properties to set + */ + constructor(properties?: google.firestore.v1.StructuredAggregationQuery.Aggregation.ISum); - /** - * Calls RunQuery. - * @param request RunQueryRequest message or plain object - * @returns Promise - */ - public runQuery(request: google.firestore.v1.IRunQueryRequest): Promise; + /** Sum field. */ + public field?: (google.firestore.v1.StructuredQuery.IFieldReference|null); - /** - * Calls ExecutePipeline. - * @param request ExecutePipelineRequest message or plain object - * @param callback Node-style callback called with the error, if any, and ExecutePipelineResponse - */ - public executePipeline(request: google.firestore.v1.IExecutePipelineRequest, callback: google.firestore.v1.Firestore.ExecutePipelineCallback): void; + /** + * Creates a Sum message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns Sum + */ + public static fromObject(object: { [k: string]: any }): google.firestore.v1.StructuredAggregationQuery.Aggregation.Sum; - /** - * Calls ExecutePipeline. - * @param request ExecutePipelineRequest message or plain object - * @returns Promise - */ - public executePipeline(request: google.firestore.v1.IExecutePipelineRequest): Promise; + /** + * Creates a plain object from a Sum message. Also converts values to other types if specified. + * @param message Sum + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.firestore.v1.StructuredAggregationQuery.Aggregation.Sum, options?: $protobuf.IConversionOptions): { [k: string]: any }; - /** - * Calls RunAggregationQuery. - * @param request RunAggregationQueryRequest message or plain object - * @param callback Node-style callback called with the error, if any, and RunAggregationQueryResponse - */ - public runAggregationQuery(request: google.firestore.v1.IRunAggregationQueryRequest, callback: google.firestore.v1.Firestore.RunAggregationQueryCallback): void; + /** + * Converts this Sum to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; - /** - * Calls RunAggregationQuery. - * @param request RunAggregationQueryRequest message or plain object - * @returns Promise - */ - public runAggregationQuery(request: google.firestore.v1.IRunAggregationQueryRequest): Promise; + /** + * Gets the default type url for Sum + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } - /** - * Calls PartitionQuery. - * @param request PartitionQueryRequest message or plain object - * @param callback Node-style callback called with the error, if any, and PartitionQueryResponse - */ - public partitionQuery(request: google.firestore.v1.IPartitionQueryRequest, callback: google.firestore.v1.Firestore.PartitionQueryCallback): void; + /** Properties of an Avg. */ + interface IAvg { - /** - * Calls PartitionQuery. - * @param request PartitionQueryRequest message or plain object - * @returns Promise - */ - public partitionQuery(request: google.firestore.v1.IPartitionQueryRequest): Promise; + /** Avg field */ + field?: (google.firestore.v1.StructuredQuery.IFieldReference|null); + } - /** - * Calls Write. - * @param request WriteRequest message or plain object - * @param callback Node-style callback called with the error, if any, and WriteResponse - */ - public write(request: google.firestore.v1.IWriteRequest, callback: google.firestore.v1.Firestore.WriteCallback): void; + /** Represents an Avg. */ + class Avg implements IAvg { - /** - * Calls Write. - * @param request WriteRequest message or plain object - * @returns Promise - */ - public write(request: google.firestore.v1.IWriteRequest): Promise; + /** + * Constructs a new Avg. + * @param [properties] Properties to set + */ + constructor(properties?: google.firestore.v1.StructuredAggregationQuery.Aggregation.IAvg); - /** - * Calls Listen. - * @param request ListenRequest message or plain object - * @param callback Node-style callback called with the error, if any, and ListenResponse - */ - public listen(request: google.firestore.v1.IListenRequest, callback: google.firestore.v1.Firestore.ListenCallback): void; + /** Avg field. */ + public field?: (google.firestore.v1.StructuredQuery.IFieldReference|null); - /** - * Calls Listen. - * @param request ListenRequest message or plain object - * @returns Promise - */ - public listen(request: google.firestore.v1.IListenRequest): Promise; + /** + * Creates an Avg message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns Avg + */ + public static fromObject(object: { [k: string]: any }): google.firestore.v1.StructuredAggregationQuery.Aggregation.Avg; - /** - * Calls ListCollectionIds. - * @param request ListCollectionIdsRequest message or plain object - * @param callback Node-style callback called with the error, if any, and ListCollectionIdsResponse - */ - public listCollectionIds(request: google.firestore.v1.IListCollectionIdsRequest, callback: google.firestore.v1.Firestore.ListCollectionIdsCallback): void; + /** + * Creates a plain object from an Avg message. Also converts values to other types if specified. + * @param message Avg + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.firestore.v1.StructuredAggregationQuery.Aggregation.Avg, options?: $protobuf.IConversionOptions): { [k: string]: any }; - /** - * Calls ListCollectionIds. - * @param request ListCollectionIdsRequest message or plain object - * @returns Promise - */ - public listCollectionIds(request: google.firestore.v1.IListCollectionIdsRequest): Promise; + /** + * Converts this Avg to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; - /** - * Calls BatchWrite. - * @param request BatchWriteRequest message or plain object - * @param callback Node-style callback called with the error, if any, and BatchWriteResponse - */ - public batchWrite(request: google.firestore.v1.IBatchWriteRequest, callback: google.firestore.v1.Firestore.BatchWriteCallback): void; + /** + * Gets the default type url for Avg + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + } + } - /** - * Calls BatchWrite. - * @param request BatchWriteRequest message or plain object - * @returns Promise - */ - public batchWrite(request: google.firestore.v1.IBatchWriteRequest): Promise; + /** Properties of a Cursor. */ + interface ICursor { - /** - * Calls CreateDocument. - * @param request CreateDocumentRequest message or plain object - * @param callback Node-style callback called with the error, if any, and Document - */ - public createDocument(request: google.firestore.v1.ICreateDocumentRequest, callback: google.firestore.v1.Firestore.CreateDocumentCallback): void; + /** Cursor values */ + values?: (google.firestore.v1.IValue[]|null); - /** - * Calls CreateDocument. - * @param request CreateDocumentRequest message or plain object - * @returns Promise - */ - public createDocument(request: google.firestore.v1.ICreateDocumentRequest): Promise; + /** Cursor before */ + before?: (boolean|null); } - namespace Firestore { + /** Represents a Cursor. */ + class Cursor implements ICursor { /** - * Callback as used by {@link google.firestore.v1.Firestore#getDocument}. - * @param error Error, if any - * @param [response] Document + * Constructs a new Cursor. + * @param [properties] Properties to set */ - type GetDocumentCallback = (error: (Error|null), response?: google.firestore.v1.Document) => void; + constructor(properties?: google.firestore.v1.ICursor); - /** - * Callback as used by {@link google.firestore.v1.Firestore#listDocuments}. - * @param error Error, if any - * @param [response] ListDocumentsResponse - */ - type ListDocumentsCallback = (error: (Error|null), response?: google.firestore.v1.ListDocumentsResponse) => void; + /** Cursor values. */ + public values: google.firestore.v1.IValue[]; - /** - * Callback as used by {@link google.firestore.v1.Firestore#updateDocument}. - * @param error Error, if any - * @param [response] Document - */ - type UpdateDocumentCallback = (error: (Error|null), response?: google.firestore.v1.Document) => void; + /** Cursor before. */ + public before: boolean; /** - * Callback as used by {@link google.firestore.v1.Firestore#deleteDocument}. - * @param error Error, if any - * @param [response] Empty + * Creates a Cursor message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns Cursor */ - type DeleteDocumentCallback = (error: (Error|null), response?: google.protobuf.Empty) => void; + public static fromObject(object: { [k: string]: any }): google.firestore.v1.Cursor; /** - * Callback as used by {@link google.firestore.v1.Firestore#batchGetDocuments}. - * @param error Error, if any - * @param [response] BatchGetDocumentsResponse + * Creates a plain object from a Cursor message. Also converts values to other types if specified. + * @param message Cursor + * @param [options] Conversion options + * @returns Plain object */ - type BatchGetDocumentsCallback = (error: (Error|null), response?: google.firestore.v1.BatchGetDocumentsResponse) => void; + public static toObject(message: google.firestore.v1.Cursor, options?: $protobuf.IConversionOptions): { [k: string]: any }; /** - * Callback as used by {@link google.firestore.v1.Firestore#beginTransaction}. - * @param error Error, if any - * @param [response] BeginTransactionResponse + * Converts this Cursor to JSON. + * @returns JSON object */ - type BeginTransactionCallback = (error: (Error|null), response?: google.firestore.v1.BeginTransactionResponse) => void; + public toJSON(): { [k: string]: any }; /** - * Callback as used by {@link google.firestore.v1.Firestore#commit}. - * @param error Error, if any - * @param [response] CommitResponse + * Gets the default type url for Cursor + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url */ - type CommitCallback = (error: (Error|null), response?: google.firestore.v1.CommitResponse) => void; + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of an ExplainOptions. */ + interface IExplainOptions { + + /** ExplainOptions analyze */ + analyze?: (boolean|null); + } + + /** Represents an ExplainOptions. */ + class ExplainOptions implements IExplainOptions { /** - * Callback as used by {@link google.firestore.v1.Firestore#rollback}. - * @param error Error, if any - * @param [response] Empty + * Constructs a new ExplainOptions. + * @param [properties] Properties to set */ - type RollbackCallback = (error: (Error|null), response?: google.protobuf.Empty) => void; + constructor(properties?: google.firestore.v1.IExplainOptions); + + /** ExplainOptions analyze. */ + public analyze: boolean; /** - * Callback as used by {@link google.firestore.v1.Firestore#runQuery}. - * @param error Error, if any - * @param [response] RunQueryResponse + * Creates an ExplainOptions message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns ExplainOptions */ - type RunQueryCallback = (error: (Error|null), response?: google.firestore.v1.RunQueryResponse) => void; + public static fromObject(object: { [k: string]: any }): google.firestore.v1.ExplainOptions; /** - * Callback as used by {@link google.firestore.v1.Firestore#executePipeline}. - * @param error Error, if any - * @param [response] ExecutePipelineResponse + * Creates a plain object from an ExplainOptions message. Also converts values to other types if specified. + * @param message ExplainOptions + * @param [options] Conversion options + * @returns Plain object */ - type ExecutePipelineCallback = (error: (Error|null), response?: google.firestore.v1.ExecutePipelineResponse) => void; + public static toObject(message: google.firestore.v1.ExplainOptions, options?: $protobuf.IConversionOptions): { [k: string]: any }; /** - * Callback as used by {@link google.firestore.v1.Firestore#runAggregationQuery}. - * @param error Error, if any - * @param [response] RunAggregationQueryResponse + * Converts this ExplainOptions to JSON. + * @returns JSON object */ - type RunAggregationQueryCallback = (error: (Error|null), response?: google.firestore.v1.RunAggregationQueryResponse) => void; + public toJSON(): { [k: string]: any }; /** - * Callback as used by {@link google.firestore.v1.Firestore#partitionQuery}. - * @param error Error, if any - * @param [response] PartitionQueryResponse + * Gets the default type url for ExplainOptions + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url */ - type PartitionQueryCallback = (error: (Error|null), response?: google.firestore.v1.PartitionQueryResponse) => void; + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of an ExplainMetrics. */ + interface IExplainMetrics { + + /** ExplainMetrics planSummary */ + planSummary?: (google.firestore.v1.IPlanSummary|null); + + /** ExplainMetrics executionStats */ + executionStats?: (google.firestore.v1.IExecutionStats|null); + } + + /** Represents an ExplainMetrics. */ + class ExplainMetrics implements IExplainMetrics { /** - * Callback as used by {@link google.firestore.v1.Firestore#write}. - * @param error Error, if any - * @param [response] WriteResponse + * Constructs a new ExplainMetrics. + * @param [properties] Properties to set */ - type WriteCallback = (error: (Error|null), response?: google.firestore.v1.WriteResponse) => void; + constructor(properties?: google.firestore.v1.IExplainMetrics); + + /** ExplainMetrics planSummary. */ + public planSummary?: (google.firestore.v1.IPlanSummary|null); + + /** ExplainMetrics executionStats. */ + public executionStats?: (google.firestore.v1.IExecutionStats|null); /** - * Callback as used by {@link google.firestore.v1.Firestore#listen}. - * @param error Error, if any - * @param [response] ListenResponse + * Creates an ExplainMetrics message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns ExplainMetrics */ - type ListenCallback = (error: (Error|null), response?: google.firestore.v1.ListenResponse) => void; + public static fromObject(object: { [k: string]: any }): google.firestore.v1.ExplainMetrics; /** - * Callback as used by {@link google.firestore.v1.Firestore#listCollectionIds}. - * @param error Error, if any - * @param [response] ListCollectionIdsResponse + * Creates a plain object from an ExplainMetrics message. Also converts values to other types if specified. + * @param message ExplainMetrics + * @param [options] Conversion options + * @returns Plain object */ - type ListCollectionIdsCallback = (error: (Error|null), response?: google.firestore.v1.ListCollectionIdsResponse) => void; + public static toObject(message: google.firestore.v1.ExplainMetrics, options?: $protobuf.IConversionOptions): { [k: string]: any }; /** - * Callback as used by {@link google.firestore.v1.Firestore#batchWrite}. - * @param error Error, if any - * @param [response] BatchWriteResponse + * Converts this ExplainMetrics to JSON. + * @returns JSON object */ - type BatchWriteCallback = (error: (Error|null), response?: google.firestore.v1.BatchWriteResponse) => void; + public toJSON(): { [k: string]: any }; /** - * Callback as used by {@link google.firestore.v1.Firestore#createDocument}. - * @param error Error, if any - * @param [response] Document + * Gets the default type url for ExplainMetrics + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url */ - type CreateDocumentCallback = (error: (Error|null), response?: google.firestore.v1.Document) => void; + public static getTypeUrl(typeUrlPrefix?: string): string; } - /** Properties of a GetDocumentRequest. */ - interface IGetDocumentRequest { - - /** GetDocumentRequest name */ - name?: (string|null); - - /** GetDocumentRequest mask */ - mask?: (google.firestore.v1.IDocumentMask|null); - - /** GetDocumentRequest transaction */ - transaction?: (Uint8Array|null); + /** Properties of a PlanSummary. */ + interface IPlanSummary { - /** GetDocumentRequest readTime */ - readTime?: (google.protobuf.ITimestamp|null); + /** PlanSummary indexesUsed */ + indexesUsed?: (google.protobuf.IStruct[]|null); } - /** Represents a GetDocumentRequest. */ - class GetDocumentRequest implements IGetDocumentRequest { + /** Represents a PlanSummary. */ + class PlanSummary implements IPlanSummary { /** - * Constructs a new GetDocumentRequest. + * Constructs a new PlanSummary. * @param [properties] Properties to set */ - constructor(properties?: google.firestore.v1.IGetDocumentRequest); - - /** GetDocumentRequest name. */ - public name: string; - - /** GetDocumentRequest mask. */ - public mask?: (google.firestore.v1.IDocumentMask|null); - - /** GetDocumentRequest transaction. */ - public transaction?: (Uint8Array|null); - - /** GetDocumentRequest readTime. */ - public readTime?: (google.protobuf.ITimestamp|null); + constructor(properties?: google.firestore.v1.IPlanSummary); - /** GetDocumentRequest consistencySelector. */ - public consistencySelector?: ("transaction"|"readTime"); + /** PlanSummary indexesUsed. */ + public indexesUsed: google.protobuf.IStruct[]; /** - * Creates a GetDocumentRequest message from a plain object. Also converts values to their respective internal types. + * Creates a PlanSummary message from a plain object. Also converts values to their respective internal types. * @param object Plain object - * @returns GetDocumentRequest + * @returns PlanSummary */ - public static fromObject(object: { [k: string]: any }): google.firestore.v1.GetDocumentRequest; + public static fromObject(object: { [k: string]: any }): google.firestore.v1.PlanSummary; /** - * Creates a plain object from a GetDocumentRequest message. Also converts values to other types if specified. - * @param message GetDocumentRequest + * Creates a plain object from a PlanSummary message. Also converts values to other types if specified. + * @param message PlanSummary * @param [options] Conversion options * @returns Plain object */ - public static toObject(message: google.firestore.v1.GetDocumentRequest, options?: $protobuf.IConversionOptions): { [k: string]: any }; + public static toObject(message: google.firestore.v1.PlanSummary, options?: $protobuf.IConversionOptions): { [k: string]: any }; /** - * Converts this GetDocumentRequest to JSON. + * Converts this PlanSummary to JSON. * @returns JSON object */ public toJSON(): { [k: string]: any }; /** - * Gets the default type url for GetDocumentRequest + * Gets the default type url for PlanSummary * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") * @returns The default type url */ public static getTypeUrl(typeUrlPrefix?: string): string; } - /** Properties of a ListDocumentsRequest. */ - interface IListDocumentsRequest { - - /** ListDocumentsRequest parent */ - parent?: (string|null); - - /** ListDocumentsRequest collectionId */ - collectionId?: (string|null); - - /** ListDocumentsRequest pageSize */ - pageSize?: (number|null); - - /** ListDocumentsRequest pageToken */ - pageToken?: (string|null); - - /** ListDocumentsRequest orderBy */ - orderBy?: (string|null); - - /** ListDocumentsRequest mask */ - mask?: (google.firestore.v1.IDocumentMask|null); + /** Properties of an ExecutionStats. */ + interface IExecutionStats { - /** ListDocumentsRequest transaction */ - transaction?: (Uint8Array|null); + /** ExecutionStats resultsReturned */ + resultsReturned?: (number|string|null); - /** ListDocumentsRequest readTime */ - readTime?: (google.protobuf.ITimestamp|null); + /** ExecutionStats executionDuration */ + executionDuration?: (google.protobuf.IDuration|null); - /** ListDocumentsRequest showMissing */ - showMissing?: (boolean|null); + /** ExecutionStats readOperations */ + readOperations?: (number|string|null); + + /** ExecutionStats debugStats */ + debugStats?: (google.protobuf.IStruct|null); } - /** Represents a ListDocumentsRequest. */ - class ListDocumentsRequest implements IListDocumentsRequest { + /** Represents an ExecutionStats. */ + class ExecutionStats implements IExecutionStats { /** - * Constructs a new ListDocumentsRequest. + * Constructs a new ExecutionStats. * @param [properties] Properties to set */ - constructor(properties?: google.firestore.v1.IListDocumentsRequest); - - /** ListDocumentsRequest parent. */ - public parent: string; - - /** ListDocumentsRequest collectionId. */ - public collectionId: string; - - /** ListDocumentsRequest pageSize. */ - public pageSize: number; - - /** ListDocumentsRequest pageToken. */ - public pageToken: string; - - /** ListDocumentsRequest orderBy. */ - public orderBy: string; - - /** ListDocumentsRequest mask. */ - public mask?: (google.firestore.v1.IDocumentMask|null); + constructor(properties?: google.firestore.v1.IExecutionStats); - /** ListDocumentsRequest transaction. */ - public transaction?: (Uint8Array|null); + /** ExecutionStats resultsReturned. */ + public resultsReturned: (number|string); - /** ListDocumentsRequest readTime. */ - public readTime?: (google.protobuf.ITimestamp|null); + /** ExecutionStats executionDuration. */ + public executionDuration?: (google.protobuf.IDuration|null); - /** ListDocumentsRequest showMissing. */ - public showMissing: boolean; + /** ExecutionStats readOperations. */ + public readOperations: (number|string); - /** ListDocumentsRequest consistencySelector. */ - public consistencySelector?: ("transaction"|"readTime"); + /** ExecutionStats debugStats. */ + public debugStats?: (google.protobuf.IStruct|null); /** - * Creates a ListDocumentsRequest message from a plain object. Also converts values to their respective internal types. + * Creates an ExecutionStats message from a plain object. Also converts values to their respective internal types. * @param object Plain object - * @returns ListDocumentsRequest + * @returns ExecutionStats */ - public static fromObject(object: { [k: string]: any }): google.firestore.v1.ListDocumentsRequest; + public static fromObject(object: { [k: string]: any }): google.firestore.v1.ExecutionStats; /** - * Creates a plain object from a ListDocumentsRequest message. Also converts values to other types if specified. - * @param message ListDocumentsRequest + * Creates a plain object from an ExecutionStats message. Also converts values to other types if specified. + * @param message ExecutionStats * @param [options] Conversion options * @returns Plain object */ - public static toObject(message: google.firestore.v1.ListDocumentsRequest, options?: $protobuf.IConversionOptions): { [k: string]: any }; + public static toObject(message: google.firestore.v1.ExecutionStats, options?: $protobuf.IConversionOptions): { [k: string]: any }; /** - * Converts this ListDocumentsRequest to JSON. + * Converts this ExecutionStats to JSON. * @returns JSON object */ public toJSON(): { [k: string]: any }; /** - * Gets the default type url for ListDocumentsRequest + * Gets the default type url for ExecutionStats * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") * @returns The default type url */ public static getTypeUrl(typeUrlPrefix?: string): string; } - /** Properties of a ListDocumentsResponse. */ - interface IListDocumentsResponse { + /** Properties of a Write. */ + interface IWrite { - /** ListDocumentsResponse documents */ - documents?: (google.firestore.v1.IDocument[]|null); + /** Write update */ + update?: (google.firestore.v1.IDocument|null); - /** ListDocumentsResponse nextPageToken */ - nextPageToken?: (string|null); + /** Write delete */ + "delete"?: (string|null); + + /** Write transform */ + transform?: (google.firestore.v1.IDocumentTransform|null); + + /** Write updateMask */ + updateMask?: (google.firestore.v1.IDocumentMask|null); + + /** Write updateTransforms */ + updateTransforms?: (google.firestore.v1.DocumentTransform.IFieldTransform[]|null); + + /** Write currentDocument */ + currentDocument?: (google.firestore.v1.IPrecondition|null); } - /** Represents a ListDocumentsResponse. */ - class ListDocumentsResponse implements IListDocumentsResponse { + /** Represents a Write. */ + class Write implements IWrite { /** - * Constructs a new ListDocumentsResponse. + * Constructs a new Write. * @param [properties] Properties to set */ - constructor(properties?: google.firestore.v1.IListDocumentsResponse); + constructor(properties?: google.firestore.v1.IWrite); - /** ListDocumentsResponse documents. */ - public documents: google.firestore.v1.IDocument[]; + /** Write update. */ + public update?: (google.firestore.v1.IDocument|null); - /** ListDocumentsResponse nextPageToken. */ - public nextPageToken: string; + /** Write delete. */ + public delete?: (string|null); + + /** Write transform. */ + public transform?: (google.firestore.v1.IDocumentTransform|null); + + /** Write updateMask. */ + public updateMask?: (google.firestore.v1.IDocumentMask|null); + + /** Write updateTransforms. */ + public updateTransforms: google.firestore.v1.DocumentTransform.IFieldTransform[]; + + /** Write currentDocument. */ + public currentDocument?: (google.firestore.v1.IPrecondition|null); + + /** Write operation. */ + public operation?: ("update"|"delete"|"transform"); /** - * Creates a ListDocumentsResponse message from a plain object. Also converts values to their respective internal types. + * Creates a Write message from a plain object. Also converts values to their respective internal types. * @param object Plain object - * @returns ListDocumentsResponse + * @returns Write */ - public static fromObject(object: { [k: string]: any }): google.firestore.v1.ListDocumentsResponse; + public static fromObject(object: { [k: string]: any }): google.firestore.v1.Write; /** - * Creates a plain object from a ListDocumentsResponse message. Also converts values to other types if specified. - * @param message ListDocumentsResponse + * Creates a plain object from a Write message. Also converts values to other types if specified. + * @param message Write * @param [options] Conversion options * @returns Plain object */ - public static toObject(message: google.firestore.v1.ListDocumentsResponse, options?: $protobuf.IConversionOptions): { [k: string]: any }; + public static toObject(message: google.firestore.v1.Write, options?: $protobuf.IConversionOptions): { [k: string]: any }; /** - * Converts this ListDocumentsResponse to JSON. + * Converts this Write to JSON. * @returns JSON object */ public toJSON(): { [k: string]: any }; /** - * Gets the default type url for ListDocumentsResponse + * Gets the default type url for Write * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") * @returns The default type url */ public static getTypeUrl(typeUrlPrefix?: string): string; } - /** Properties of a CreateDocumentRequest. */ - interface ICreateDocumentRequest { - - /** CreateDocumentRequest parent */ - parent?: (string|null); - - /** CreateDocumentRequest collectionId */ - collectionId?: (string|null); - - /** CreateDocumentRequest documentId */ - documentId?: (string|null); + /** Properties of a DocumentTransform. */ + interface IDocumentTransform { - /** CreateDocumentRequest document */ - document?: (google.firestore.v1.IDocument|null); + /** DocumentTransform document */ + document?: (string|null); - /** CreateDocumentRequest mask */ - mask?: (google.firestore.v1.IDocumentMask|null); + /** DocumentTransform fieldTransforms */ + fieldTransforms?: (google.firestore.v1.DocumentTransform.IFieldTransform[]|null); } - /** Represents a CreateDocumentRequest. */ - class CreateDocumentRequest implements ICreateDocumentRequest { + /** Represents a DocumentTransform. */ + class DocumentTransform implements IDocumentTransform { /** - * Constructs a new CreateDocumentRequest. + * Constructs a new DocumentTransform. * @param [properties] Properties to set */ - constructor(properties?: google.firestore.v1.ICreateDocumentRequest); - - /** CreateDocumentRequest parent. */ - public parent: string; - - /** CreateDocumentRequest collectionId. */ - public collectionId: string; - - /** CreateDocumentRequest documentId. */ - public documentId: string; + constructor(properties?: google.firestore.v1.IDocumentTransform); - /** CreateDocumentRequest document. */ - public document?: (google.firestore.v1.IDocument|null); + /** DocumentTransform document. */ + public document: string; - /** CreateDocumentRequest mask. */ - public mask?: (google.firestore.v1.IDocumentMask|null); + /** DocumentTransform fieldTransforms. */ + public fieldTransforms: google.firestore.v1.DocumentTransform.IFieldTransform[]; /** - * Creates a CreateDocumentRequest message from a plain object. Also converts values to their respective internal types. + * Creates a DocumentTransform message from a plain object. Also converts values to their respective internal types. * @param object Plain object - * @returns CreateDocumentRequest + * @returns DocumentTransform */ - public static fromObject(object: { [k: string]: any }): google.firestore.v1.CreateDocumentRequest; + public static fromObject(object: { [k: string]: any }): google.firestore.v1.DocumentTransform; /** - * Creates a plain object from a CreateDocumentRequest message. Also converts values to other types if specified. - * @param message CreateDocumentRequest + * Creates a plain object from a DocumentTransform message. Also converts values to other types if specified. + * @param message DocumentTransform * @param [options] Conversion options * @returns Plain object */ - public static toObject(message: google.firestore.v1.CreateDocumentRequest, options?: $protobuf.IConversionOptions): { [k: string]: any }; + public static toObject(message: google.firestore.v1.DocumentTransform, options?: $protobuf.IConversionOptions): { [k: string]: any }; /** - * Converts this CreateDocumentRequest to JSON. + * Converts this DocumentTransform to JSON. * @returns JSON object */ public toJSON(): { [k: string]: any }; /** - * Gets the default type url for CreateDocumentRequest + * Gets the default type url for DocumentTransform * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") * @returns The default type url */ public static getTypeUrl(typeUrlPrefix?: string): string; } - /** Properties of an UpdateDocumentRequest. */ - interface IUpdateDocumentRequest { + namespace DocumentTransform { - /** UpdateDocumentRequest document */ - document?: (google.firestore.v1.IDocument|null); + /** Properties of a FieldTransform. */ + interface IFieldTransform { - /** UpdateDocumentRequest updateMask */ - updateMask?: (google.firestore.v1.IDocumentMask|null); + /** FieldTransform fieldPath */ + fieldPath?: (string|null); - /** UpdateDocumentRequest mask */ - mask?: (google.firestore.v1.IDocumentMask|null); + /** FieldTransform setToServerValue */ + setToServerValue?: (google.firestore.v1.DocumentTransform.FieldTransform.ServerValue|null); - /** UpdateDocumentRequest currentDocument */ - currentDocument?: (google.firestore.v1.IPrecondition|null); - } + /** FieldTransform increment */ + increment?: (google.firestore.v1.IValue|null); - /** Represents an UpdateDocumentRequest. */ - class UpdateDocumentRequest implements IUpdateDocumentRequest { + /** FieldTransform maximum */ + maximum?: (google.firestore.v1.IValue|null); + + /** FieldTransform minimum */ + minimum?: (google.firestore.v1.IValue|null); + + /** FieldTransform appendMissingElements */ + appendMissingElements?: (google.firestore.v1.IArrayValue|null); + + /** FieldTransform removeAllFromArray */ + removeAllFromArray?: (google.firestore.v1.IArrayValue|null); + } + + /** Represents a FieldTransform. */ + class FieldTransform implements IFieldTransform { + + /** + * Constructs a new FieldTransform. + * @param [properties] Properties to set + */ + constructor(properties?: google.firestore.v1.DocumentTransform.IFieldTransform); + + /** FieldTransform fieldPath. */ + public fieldPath: string; + + /** FieldTransform setToServerValue. */ + public setToServerValue?: (google.firestore.v1.DocumentTransform.FieldTransform.ServerValue|null); + + /** FieldTransform increment. */ + public increment?: (google.firestore.v1.IValue|null); + + /** FieldTransform maximum. */ + public maximum?: (google.firestore.v1.IValue|null); + + /** FieldTransform minimum. */ + public minimum?: (google.firestore.v1.IValue|null); - /** - * Constructs a new UpdateDocumentRequest. - * @param [properties] Properties to set - */ - constructor(properties?: google.firestore.v1.IUpdateDocumentRequest); + /** FieldTransform appendMissingElements. */ + public appendMissingElements?: (google.firestore.v1.IArrayValue|null); - /** UpdateDocumentRequest document. */ - public document?: (google.firestore.v1.IDocument|null); + /** FieldTransform removeAllFromArray. */ + public removeAllFromArray?: (google.firestore.v1.IArrayValue|null); - /** UpdateDocumentRequest updateMask. */ - public updateMask?: (google.firestore.v1.IDocumentMask|null); + /** FieldTransform transformType. */ + public transformType?: ("setToServerValue"|"increment"|"maximum"|"minimum"|"appendMissingElements"|"removeAllFromArray"); - /** UpdateDocumentRequest mask. */ - public mask?: (google.firestore.v1.IDocumentMask|null); + /** + * Creates a FieldTransform message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns FieldTransform + */ + public static fromObject(object: { [k: string]: any }): google.firestore.v1.DocumentTransform.FieldTransform; - /** UpdateDocumentRequest currentDocument. */ - public currentDocument?: (google.firestore.v1.IPrecondition|null); + /** + * Creates a plain object from a FieldTransform message. Also converts values to other types if specified. + * @param message FieldTransform + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.firestore.v1.DocumentTransform.FieldTransform, options?: $protobuf.IConversionOptions): { [k: string]: any }; - /** - * Creates an UpdateDocumentRequest message from a plain object. Also converts values to their respective internal types. - * @param object Plain object - * @returns UpdateDocumentRequest - */ - public static fromObject(object: { [k: string]: any }): google.firestore.v1.UpdateDocumentRequest; + /** + * Converts this FieldTransform to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; - /** - * Creates a plain object from an UpdateDocumentRequest message. Also converts values to other types if specified. - * @param message UpdateDocumentRequest - * @param [options] Conversion options - * @returns Plain object - */ - public static toObject(message: google.firestore.v1.UpdateDocumentRequest, options?: $protobuf.IConversionOptions): { [k: string]: any }; + /** + * Gets the default type url for FieldTransform + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } - /** - * Converts this UpdateDocumentRequest to JSON. - * @returns JSON object - */ - public toJSON(): { [k: string]: any }; + namespace FieldTransform { - /** - * Gets the default type url for UpdateDocumentRequest - * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") - * @returns The default type url - */ - public static getTypeUrl(typeUrlPrefix?: string): string; + /** ServerValue enum. */ + type ServerValue = + "SERVER_VALUE_UNSPECIFIED"| "REQUEST_TIME"; + } } - /** Properties of a DeleteDocumentRequest. */ - interface IDeleteDocumentRequest { + /** Properties of a WriteResult. */ + interface IWriteResult { - /** DeleteDocumentRequest name */ - name?: (string|null); + /** WriteResult updateTime */ + updateTime?: (google.protobuf.ITimestamp|null); - /** DeleteDocumentRequest currentDocument */ - currentDocument?: (google.firestore.v1.IPrecondition|null); + /** WriteResult transformResults */ + transformResults?: (google.firestore.v1.IValue[]|null); } - /** Represents a DeleteDocumentRequest. */ - class DeleteDocumentRequest implements IDeleteDocumentRequest { + /** Represents a WriteResult. */ + class WriteResult implements IWriteResult { /** - * Constructs a new DeleteDocumentRequest. + * Constructs a new WriteResult. * @param [properties] Properties to set */ - constructor(properties?: google.firestore.v1.IDeleteDocumentRequest); + constructor(properties?: google.firestore.v1.IWriteResult); - /** DeleteDocumentRequest name. */ - public name: string; + /** WriteResult updateTime. */ + public updateTime?: (google.protobuf.ITimestamp|null); - /** DeleteDocumentRequest currentDocument. */ - public currentDocument?: (google.firestore.v1.IPrecondition|null); + /** WriteResult transformResults. */ + public transformResults: google.firestore.v1.IValue[]; /** - * Creates a DeleteDocumentRequest message from a plain object. Also converts values to their respective internal types. + * Creates a WriteResult message from a plain object. Also converts values to their respective internal types. * @param object Plain object - * @returns DeleteDocumentRequest + * @returns WriteResult */ - public static fromObject(object: { [k: string]: any }): google.firestore.v1.DeleteDocumentRequest; + public static fromObject(object: { [k: string]: any }): google.firestore.v1.WriteResult; /** - * Creates a plain object from a DeleteDocumentRequest message. Also converts values to other types if specified. - * @param message DeleteDocumentRequest + * Creates a plain object from a WriteResult message. Also converts values to other types if specified. + * @param message WriteResult * @param [options] Conversion options * @returns Plain object */ - public static toObject(message: google.firestore.v1.DeleteDocumentRequest, options?: $protobuf.IConversionOptions): { [k: string]: any }; + public static toObject(message: google.firestore.v1.WriteResult, options?: $protobuf.IConversionOptions): { [k: string]: any }; /** - * Converts this DeleteDocumentRequest to JSON. + * Converts this WriteResult to JSON. * @returns JSON object */ public toJSON(): { [k: string]: any }; /** - * Gets the default type url for DeleteDocumentRequest + * Gets the default type url for WriteResult * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") * @returns The default type url */ public static getTypeUrl(typeUrlPrefix?: string): string; } - /** Properties of a BatchGetDocumentsRequest. */ - interface IBatchGetDocumentsRequest { - - /** BatchGetDocumentsRequest database */ - database?: (string|null); - - /** BatchGetDocumentsRequest documents */ - documents?: (string[]|null); - - /** BatchGetDocumentsRequest mask */ - mask?: (google.firestore.v1.IDocumentMask|null); + /** Properties of a DocumentChange. */ + interface IDocumentChange { - /** BatchGetDocumentsRequest transaction */ - transaction?: (Uint8Array|null); + /** DocumentChange document */ + document?: (google.firestore.v1.IDocument|null); - /** BatchGetDocumentsRequest newTransaction */ - newTransaction?: (google.firestore.v1.ITransactionOptions|null); + /** DocumentChange targetIds */ + targetIds?: (number[]|null); - /** BatchGetDocumentsRequest readTime */ - readTime?: (google.protobuf.ITimestamp|null); + /** DocumentChange removedTargetIds */ + removedTargetIds?: (number[]|null); } - /** Represents a BatchGetDocumentsRequest. */ - class BatchGetDocumentsRequest implements IBatchGetDocumentsRequest { + /** Represents a DocumentChange. */ + class DocumentChange implements IDocumentChange { /** - * Constructs a new BatchGetDocumentsRequest. + * Constructs a new DocumentChange. * @param [properties] Properties to set */ - constructor(properties?: google.firestore.v1.IBatchGetDocumentsRequest); - - /** BatchGetDocumentsRequest database. */ - public database: string; - - /** BatchGetDocumentsRequest documents. */ - public documents: string[]; - - /** BatchGetDocumentsRequest mask. */ - public mask?: (google.firestore.v1.IDocumentMask|null); - - /** BatchGetDocumentsRequest transaction. */ - public transaction?: (Uint8Array|null); + constructor(properties?: google.firestore.v1.IDocumentChange); - /** BatchGetDocumentsRequest newTransaction. */ - public newTransaction?: (google.firestore.v1.ITransactionOptions|null); + /** DocumentChange document. */ + public document?: (google.firestore.v1.IDocument|null); - /** BatchGetDocumentsRequest readTime. */ - public readTime?: (google.protobuf.ITimestamp|null); + /** DocumentChange targetIds. */ + public targetIds: number[]; - /** BatchGetDocumentsRequest consistencySelector. */ - public consistencySelector?: ("transaction"|"newTransaction"|"readTime"); + /** DocumentChange removedTargetIds. */ + public removedTargetIds: number[]; /** - * Creates a BatchGetDocumentsRequest message from a plain object. Also converts values to their respective internal types. + * Creates a DocumentChange message from a plain object. Also converts values to their respective internal types. * @param object Plain object - * @returns BatchGetDocumentsRequest + * @returns DocumentChange */ - public static fromObject(object: { [k: string]: any }): google.firestore.v1.BatchGetDocumentsRequest; + public static fromObject(object: { [k: string]: any }): google.firestore.v1.DocumentChange; /** - * Creates a plain object from a BatchGetDocumentsRequest message. Also converts values to other types if specified. - * @param message BatchGetDocumentsRequest + * Creates a plain object from a DocumentChange message. Also converts values to other types if specified. + * @param message DocumentChange * @param [options] Conversion options * @returns Plain object */ - public static toObject(message: google.firestore.v1.BatchGetDocumentsRequest, options?: $protobuf.IConversionOptions): { [k: string]: any }; + public static toObject(message: google.firestore.v1.DocumentChange, options?: $protobuf.IConversionOptions): { [k: string]: any }; /** - * Converts this BatchGetDocumentsRequest to JSON. + * Converts this DocumentChange to JSON. * @returns JSON object */ public toJSON(): { [k: string]: any }; /** - * Gets the default type url for BatchGetDocumentsRequest + * Gets the default type url for DocumentChange * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") * @returns The default type url */ public static getTypeUrl(typeUrlPrefix?: string): string; } - /** Properties of a BatchGetDocumentsResponse. */ - interface IBatchGetDocumentsResponse { - - /** BatchGetDocumentsResponse found */ - found?: (google.firestore.v1.IDocument|null); + /** Properties of a DocumentDelete. */ + interface IDocumentDelete { - /** BatchGetDocumentsResponse missing */ - missing?: (string|null); + /** DocumentDelete document */ + document?: (string|null); - /** BatchGetDocumentsResponse transaction */ - transaction?: (Uint8Array|null); + /** DocumentDelete removedTargetIds */ + removedTargetIds?: (number[]|null); - /** BatchGetDocumentsResponse readTime */ + /** DocumentDelete readTime */ readTime?: (google.protobuf.ITimestamp|null); } - /** Represents a BatchGetDocumentsResponse. */ - class BatchGetDocumentsResponse implements IBatchGetDocumentsResponse { + /** Represents a DocumentDelete. */ + class DocumentDelete implements IDocumentDelete { /** - * Constructs a new BatchGetDocumentsResponse. + * Constructs a new DocumentDelete. * @param [properties] Properties to set */ - constructor(properties?: google.firestore.v1.IBatchGetDocumentsResponse); - - /** BatchGetDocumentsResponse found. */ - public found?: (google.firestore.v1.IDocument|null); + constructor(properties?: google.firestore.v1.IDocumentDelete); - /** BatchGetDocumentsResponse missing. */ - public missing?: (string|null); + /** DocumentDelete document. */ + public document: string; - /** BatchGetDocumentsResponse transaction. */ - public transaction: Uint8Array; + /** DocumentDelete removedTargetIds. */ + public removedTargetIds: number[]; - /** BatchGetDocumentsResponse readTime. */ + /** DocumentDelete readTime. */ public readTime?: (google.protobuf.ITimestamp|null); - /** BatchGetDocumentsResponse result. */ - public result?: ("found"|"missing"); - /** - * Creates a BatchGetDocumentsResponse message from a plain object. Also converts values to their respective internal types. + * Creates a DocumentDelete message from a plain object. Also converts values to their respective internal types. * @param object Plain object - * @returns BatchGetDocumentsResponse + * @returns DocumentDelete */ - public static fromObject(object: { [k: string]: any }): google.firestore.v1.BatchGetDocumentsResponse; + public static fromObject(object: { [k: string]: any }): google.firestore.v1.DocumentDelete; /** - * Creates a plain object from a BatchGetDocumentsResponse message. Also converts values to other types if specified. - * @param message BatchGetDocumentsResponse + * Creates a plain object from a DocumentDelete message. Also converts values to other types if specified. + * @param message DocumentDelete * @param [options] Conversion options * @returns Plain object */ - public static toObject(message: google.firestore.v1.BatchGetDocumentsResponse, options?: $protobuf.IConversionOptions): { [k: string]: any }; + public static toObject(message: google.firestore.v1.DocumentDelete, options?: $protobuf.IConversionOptions): { [k: string]: any }; /** - * Converts this BatchGetDocumentsResponse to JSON. + * Converts this DocumentDelete to JSON. * @returns JSON object */ public toJSON(): { [k: string]: any }; /** - * Gets the default type url for BatchGetDocumentsResponse + * Gets the default type url for DocumentDelete * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") * @returns The default type url */ public static getTypeUrl(typeUrlPrefix?: string): string; } - /** Properties of a BeginTransactionRequest. */ - interface IBeginTransactionRequest { + /** Properties of a DocumentRemove. */ + interface IDocumentRemove { - /** BeginTransactionRequest database */ - database?: (string|null); + /** DocumentRemove document */ + document?: (string|null); + + /** DocumentRemove removedTargetIds */ + removedTargetIds?: (number[]|null); - /** BeginTransactionRequest options */ - options?: (google.firestore.v1.ITransactionOptions|null); + /** DocumentRemove readTime */ + readTime?: (google.protobuf.ITimestamp|null); } - /** Represents a BeginTransactionRequest. */ - class BeginTransactionRequest implements IBeginTransactionRequest { + /** Represents a DocumentRemove. */ + class DocumentRemove implements IDocumentRemove { /** - * Constructs a new BeginTransactionRequest. + * Constructs a new DocumentRemove. * @param [properties] Properties to set */ - constructor(properties?: google.firestore.v1.IBeginTransactionRequest); + constructor(properties?: google.firestore.v1.IDocumentRemove); - /** BeginTransactionRequest database. */ - public database: string; + /** DocumentRemove document. */ + public document: string; - /** BeginTransactionRequest options. */ - public options?: (google.firestore.v1.ITransactionOptions|null); + /** DocumentRemove removedTargetIds. */ + public removedTargetIds: number[]; + + /** DocumentRemove readTime. */ + public readTime?: (google.protobuf.ITimestamp|null); /** - * Creates a BeginTransactionRequest message from a plain object. Also converts values to their respective internal types. + * Creates a DocumentRemove message from a plain object. Also converts values to their respective internal types. * @param object Plain object - * @returns BeginTransactionRequest + * @returns DocumentRemove */ - public static fromObject(object: { [k: string]: any }): google.firestore.v1.BeginTransactionRequest; + public static fromObject(object: { [k: string]: any }): google.firestore.v1.DocumentRemove; /** - * Creates a plain object from a BeginTransactionRequest message. Also converts values to other types if specified. - * @param message BeginTransactionRequest + * Creates a plain object from a DocumentRemove message. Also converts values to other types if specified. + * @param message DocumentRemove * @param [options] Conversion options * @returns Plain object */ - public static toObject(message: google.firestore.v1.BeginTransactionRequest, options?: $protobuf.IConversionOptions): { [k: string]: any }; + public static toObject(message: google.firestore.v1.DocumentRemove, options?: $protobuf.IConversionOptions): { [k: string]: any }; /** - * Converts this BeginTransactionRequest to JSON. + * Converts this DocumentRemove to JSON. * @returns JSON object */ public toJSON(): { [k: string]: any }; /** - * Gets the default type url for BeginTransactionRequest + * Gets the default type url for DocumentRemove * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") * @returns The default type url */ public static getTypeUrl(typeUrlPrefix?: string): string; } - /** Properties of a BeginTransactionResponse. */ - interface IBeginTransactionResponse { + /** Properties of an ExistenceFilter. */ + interface IExistenceFilter { - /** BeginTransactionResponse transaction */ - transaction?: (Uint8Array|null); + /** ExistenceFilter targetId */ + targetId?: (number|null); + + /** ExistenceFilter count */ + count?: (number|null); + + /** ExistenceFilter unchangedNames */ + unchangedNames?: (google.firestore.v1.IBloomFilter|null); } - /** Represents a BeginTransactionResponse. */ - class BeginTransactionResponse implements IBeginTransactionResponse { + /** Represents an ExistenceFilter. */ + class ExistenceFilter implements IExistenceFilter { /** - * Constructs a new BeginTransactionResponse. + * Constructs a new ExistenceFilter. * @param [properties] Properties to set */ - constructor(properties?: google.firestore.v1.IBeginTransactionResponse); + constructor(properties?: google.firestore.v1.IExistenceFilter); - /** BeginTransactionResponse transaction. */ - public transaction: Uint8Array; + /** ExistenceFilter targetId. */ + public targetId: number; + + /** ExistenceFilter count. */ + public count: number; + + /** ExistenceFilter unchangedNames. */ + public unchangedNames?: (google.firestore.v1.IBloomFilter|null); /** - * Creates a BeginTransactionResponse message from a plain object. Also converts values to their respective internal types. + * Creates an ExistenceFilter message from a plain object. Also converts values to their respective internal types. * @param object Plain object - * @returns BeginTransactionResponse + * @returns ExistenceFilter */ - public static fromObject(object: { [k: string]: any }): google.firestore.v1.BeginTransactionResponse; + public static fromObject(object: { [k: string]: any }): google.firestore.v1.ExistenceFilter; /** - * Creates a plain object from a BeginTransactionResponse message. Also converts values to other types if specified. - * @param message BeginTransactionResponse + * Creates a plain object from an ExistenceFilter message. Also converts values to other types if specified. + * @param message ExistenceFilter * @param [options] Conversion options * @returns Plain object */ - public static toObject(message: google.firestore.v1.BeginTransactionResponse, options?: $protobuf.IConversionOptions): { [k: string]: any }; + public static toObject(message: google.firestore.v1.ExistenceFilter, options?: $protobuf.IConversionOptions): { [k: string]: any }; /** - * Converts this BeginTransactionResponse to JSON. + * Converts this ExistenceFilter to JSON. * @returns JSON object */ public toJSON(): { [k: string]: any }; /** - * Gets the default type url for BeginTransactionResponse + * Gets the default type url for ExistenceFilter * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") * @returns The default type url */ public static getTypeUrl(typeUrlPrefix?: string): string; } + } + } - /** Properties of a CommitRequest. */ - interface ICommitRequest { + /** Namespace api. */ + namespace api { - /** CommitRequest database */ - database?: (string|null); + /** FieldBehavior enum. */ + type FieldBehavior = + "FIELD_BEHAVIOR_UNSPECIFIED"| "OPTIONAL"| "REQUIRED"| "OUTPUT_ONLY"| "INPUT_ONLY"| "IMMUTABLE"| "UNORDERED_LIST"| "NON_EMPTY_DEFAULT"| "IDENTIFIER"; - /** CommitRequest writes */ - writes?: (google.firestore.v1.IWrite[]|null); + /** Properties of a Http. */ + interface IHttp { - /** CommitRequest transaction */ - transaction?: (Uint8Array|null); - } + /** Http rules */ + rules?: (google.api.IHttpRule[]|null); - /** Represents a CommitRequest. */ - class CommitRequest implements ICommitRequest { + /** Http fullyDecodeReservedExpansion */ + fullyDecodeReservedExpansion?: (boolean|null); + } - /** - * Constructs a new CommitRequest. - * @param [properties] Properties to set - */ - constructor(properties?: google.firestore.v1.ICommitRequest); + /** Represents a Http. */ + class Http implements IHttp { - /** CommitRequest database. */ - public database: string; + /** + * Constructs a new Http. + * @param [properties] Properties to set + */ + constructor(properties?: google.api.IHttp); - /** CommitRequest writes. */ - public writes: google.firestore.v1.IWrite[]; + /** Http rules. */ + public rules: google.api.IHttpRule[]; - /** CommitRequest transaction. */ - public transaction: Uint8Array; + /** Http fullyDecodeReservedExpansion. */ + public fullyDecodeReservedExpansion: boolean; - /** - * Creates a CommitRequest message from a plain object. Also converts values to their respective internal types. - * @param object Plain object - * @returns CommitRequest - */ - public static fromObject(object: { [k: string]: any }): google.firestore.v1.CommitRequest; + /** + * Creates a Http message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns Http + */ + public static fromObject(object: { [k: string]: any }): google.api.Http; - /** - * Creates a plain object from a CommitRequest message. Also converts values to other types if specified. - * @param message CommitRequest - * @param [options] Conversion options - * @returns Plain object - */ - public static toObject(message: google.firestore.v1.CommitRequest, options?: $protobuf.IConversionOptions): { [k: string]: any }; + /** + * Creates a plain object from a Http message. Also converts values to other types if specified. + * @param message Http + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.api.Http, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this Http to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for Http + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a HttpRule. */ + interface IHttpRule { + + /** HttpRule selector */ + selector?: (string|null); + + /** HttpRule get */ + get?: (string|null); + + /** HttpRule put */ + put?: (string|null); + + /** HttpRule post */ + post?: (string|null); + + /** HttpRule delete */ + "delete"?: (string|null); + + /** HttpRule patch */ + patch?: (string|null); + + /** HttpRule custom */ + custom?: (google.api.ICustomHttpPattern|null); + + /** HttpRule body */ + body?: (string|null); + + /** HttpRule responseBody */ + responseBody?: (string|null); + + /** HttpRule additionalBindings */ + additionalBindings?: (google.api.IHttpRule[]|null); + } + + /** Represents a HttpRule. */ + class HttpRule implements IHttpRule { + + /** + * Constructs a new HttpRule. + * @param [properties] Properties to set + */ + constructor(properties?: google.api.IHttpRule); + + /** HttpRule selector. */ + public selector: string; + + /** HttpRule get. */ + public get?: (string|null); + + /** HttpRule put. */ + public put?: (string|null); + + /** HttpRule post. */ + public post?: (string|null); + + /** HttpRule delete. */ + public delete?: (string|null); + + /** HttpRule patch. */ + public patch?: (string|null); + + /** HttpRule custom. */ + public custom?: (google.api.ICustomHttpPattern|null); + + /** HttpRule body. */ + public body: string; + + /** HttpRule responseBody. */ + public responseBody: string; + + /** HttpRule additionalBindings. */ + public additionalBindings: google.api.IHttpRule[]; + + /** HttpRule pattern. */ + public pattern?: ("get"|"put"|"post"|"delete"|"patch"|"custom"); + + /** + * Creates a HttpRule message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns HttpRule + */ + public static fromObject(object: { [k: string]: any }): google.api.HttpRule; - /** - * Converts this CommitRequest to JSON. - * @returns JSON object - */ - public toJSON(): { [k: string]: any }; + /** + * Creates a plain object from a HttpRule message. Also converts values to other types if specified. + * @param message HttpRule + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.api.HttpRule, options?: $protobuf.IConversionOptions): { [k: string]: any }; - /** - * Gets the default type url for CommitRequest - * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") - * @returns The default type url - */ - public static getTypeUrl(typeUrlPrefix?: string): string; - } + /** + * Converts this HttpRule to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; - /** Properties of a CommitResponse. */ - interface ICommitResponse { + /** + * Gets the default type url for HttpRule + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } - /** CommitResponse writeResults */ - writeResults?: (google.firestore.v1.IWriteResult[]|null); + /** Properties of a CustomHttpPattern. */ + interface ICustomHttpPattern { - /** CommitResponse commitTime */ - commitTime?: (google.protobuf.ITimestamp|null); - } + /** CustomHttpPattern kind */ + kind?: (string|null); - /** Represents a CommitResponse. */ - class CommitResponse implements ICommitResponse { + /** CustomHttpPattern path */ + path?: (string|null); + } - /** - * Constructs a new CommitResponse. - * @param [properties] Properties to set - */ - constructor(properties?: google.firestore.v1.ICommitResponse); + /** Represents a CustomHttpPattern. */ + class CustomHttpPattern implements ICustomHttpPattern { - /** CommitResponse writeResults. */ - public writeResults: google.firestore.v1.IWriteResult[]; + /** + * Constructs a new CustomHttpPattern. + * @param [properties] Properties to set + */ + constructor(properties?: google.api.ICustomHttpPattern); - /** CommitResponse commitTime. */ - public commitTime?: (google.protobuf.ITimestamp|null); + /** CustomHttpPattern kind. */ + public kind: string; - /** - * Creates a CommitResponse message from a plain object. Also converts values to their respective internal types. - * @param object Plain object - * @returns CommitResponse - */ - public static fromObject(object: { [k: string]: any }): google.firestore.v1.CommitResponse; + /** CustomHttpPattern path. */ + public path: string; - /** - * Creates a plain object from a CommitResponse message. Also converts values to other types if specified. - * @param message CommitResponse - * @param [options] Conversion options - * @returns Plain object - */ - public static toObject(message: google.firestore.v1.CommitResponse, options?: $protobuf.IConversionOptions): { [k: string]: any }; + /** + * Creates a CustomHttpPattern message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns CustomHttpPattern + */ + public static fromObject(object: { [k: string]: any }): google.api.CustomHttpPattern; - /** - * Converts this CommitResponse to JSON. - * @returns JSON object - */ - public toJSON(): { [k: string]: any }; + /** + * Creates a plain object from a CustomHttpPattern message. Also converts values to other types if specified. + * @param message CustomHttpPattern + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.api.CustomHttpPattern, options?: $protobuf.IConversionOptions): { [k: string]: any }; - /** - * Gets the default type url for CommitResponse - * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") - * @returns The default type url - */ - public static getTypeUrl(typeUrlPrefix?: string): string; - } + /** + * Converts this CustomHttpPattern to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; - /** Properties of a RollbackRequest. */ - interface IRollbackRequest { + /** + * Gets the default type url for CustomHttpPattern + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } - /** RollbackRequest database */ - database?: (string|null); + /** Properties of a CommonLanguageSettings. */ + interface ICommonLanguageSettings { - /** RollbackRequest transaction */ - transaction?: (Uint8Array|null); - } + /** CommonLanguageSettings referenceDocsUri */ + referenceDocsUri?: (string|null); - /** Represents a RollbackRequest. */ - class RollbackRequest implements IRollbackRequest { + /** CommonLanguageSettings destinations */ + destinations?: (google.api.ClientLibraryDestination[]|null); + } - /** - * Constructs a new RollbackRequest. - * @param [properties] Properties to set - */ - constructor(properties?: google.firestore.v1.IRollbackRequest); + /** Represents a CommonLanguageSettings. */ + class CommonLanguageSettings implements ICommonLanguageSettings { - /** RollbackRequest database. */ - public database: string; + /** + * Constructs a new CommonLanguageSettings. + * @param [properties] Properties to set + */ + constructor(properties?: google.api.ICommonLanguageSettings); - /** RollbackRequest transaction. */ - public transaction: Uint8Array; + /** CommonLanguageSettings referenceDocsUri. */ + public referenceDocsUri: string; - /** - * Creates a RollbackRequest message from a plain object. Also converts values to their respective internal types. - * @param object Plain object - * @returns RollbackRequest - */ - public static fromObject(object: { [k: string]: any }): google.firestore.v1.RollbackRequest; + /** CommonLanguageSettings destinations. */ + public destinations: google.api.ClientLibraryDestination[]; - /** - * Creates a plain object from a RollbackRequest message. Also converts values to other types if specified. - * @param message RollbackRequest - * @param [options] Conversion options - * @returns Plain object - */ - public static toObject(message: google.firestore.v1.RollbackRequest, options?: $protobuf.IConversionOptions): { [k: string]: any }; + /** + * Creates a CommonLanguageSettings message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns CommonLanguageSettings + */ + public static fromObject(object: { [k: string]: any }): google.api.CommonLanguageSettings; - /** - * Converts this RollbackRequest to JSON. - * @returns JSON object - */ - public toJSON(): { [k: string]: any }; + /** + * Creates a plain object from a CommonLanguageSettings message. Also converts values to other types if specified. + * @param message CommonLanguageSettings + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.api.CommonLanguageSettings, options?: $protobuf.IConversionOptions): { [k: string]: any }; - /** - * Gets the default type url for RollbackRequest - * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") - * @returns The default type url - */ - public static getTypeUrl(typeUrlPrefix?: string): string; - } + /** + * Converts this CommonLanguageSettings to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; - /** Properties of a RunQueryRequest. */ - interface IRunQueryRequest { + /** + * Gets the default type url for CommonLanguageSettings + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } - /** RunQueryRequest parent */ - parent?: (string|null); + /** Properties of a ClientLibrarySettings. */ + interface IClientLibrarySettings { - /** RunQueryRequest structuredQuery */ - structuredQuery?: (google.firestore.v1.IStructuredQuery|null); + /** ClientLibrarySettings version */ + version?: (string|null); - /** RunQueryRequest transaction */ - transaction?: (Uint8Array|null); + /** ClientLibrarySettings launchStage */ + launchStage?: (google.api.LaunchStage|null); - /** RunQueryRequest newTransaction */ - newTransaction?: (google.firestore.v1.ITransactionOptions|null); + /** ClientLibrarySettings restNumericEnums */ + restNumericEnums?: (boolean|null); - /** RunQueryRequest readTime */ - readTime?: (google.protobuf.ITimestamp|null); + /** ClientLibrarySettings javaSettings */ + javaSettings?: (google.api.IJavaSettings|null); - /** RunQueryRequest explainOptions */ - explainOptions?: (google.firestore.v1.IExplainOptions|null); - } + /** ClientLibrarySettings cppSettings */ + cppSettings?: (google.api.ICppSettings|null); - /** Represents a RunQueryRequest. */ - class RunQueryRequest implements IRunQueryRequest { + /** ClientLibrarySettings phpSettings */ + phpSettings?: (google.api.IPhpSettings|null); - /** - * Constructs a new RunQueryRequest. - * @param [properties] Properties to set - */ - constructor(properties?: google.firestore.v1.IRunQueryRequest); + /** ClientLibrarySettings pythonSettings */ + pythonSettings?: (google.api.IPythonSettings|null); - /** RunQueryRequest parent. */ - public parent: string; + /** ClientLibrarySettings nodeSettings */ + nodeSettings?: (google.api.INodeSettings|null); - /** RunQueryRequest structuredQuery. */ - public structuredQuery?: (google.firestore.v1.IStructuredQuery|null); + /** ClientLibrarySettings dotnetSettings */ + dotnetSettings?: (google.api.IDotnetSettings|null); - /** RunQueryRequest transaction. */ - public transaction?: (Uint8Array|null); + /** ClientLibrarySettings rubySettings */ + rubySettings?: (google.api.IRubySettings|null); - /** RunQueryRequest newTransaction. */ - public newTransaction?: (google.firestore.v1.ITransactionOptions|null); + /** ClientLibrarySettings goSettings */ + goSettings?: (google.api.IGoSettings|null); + } - /** RunQueryRequest readTime. */ - public readTime?: (google.protobuf.ITimestamp|null); + /** Represents a ClientLibrarySettings. */ + class ClientLibrarySettings implements IClientLibrarySettings { - /** RunQueryRequest explainOptions. */ - public explainOptions?: (google.firestore.v1.IExplainOptions|null); + /** + * Constructs a new ClientLibrarySettings. + * @param [properties] Properties to set + */ + constructor(properties?: google.api.IClientLibrarySettings); - /** RunQueryRequest queryType. */ - public queryType?: "structuredQuery"; + /** ClientLibrarySettings version. */ + public version: string; - /** RunQueryRequest consistencySelector. */ - public consistencySelector?: ("transaction"|"newTransaction"|"readTime"); + /** ClientLibrarySettings launchStage. */ + public launchStage: google.api.LaunchStage; - /** - * Creates a RunQueryRequest message from a plain object. Also converts values to their respective internal types. - * @param object Plain object - * @returns RunQueryRequest - */ - public static fromObject(object: { [k: string]: any }): google.firestore.v1.RunQueryRequest; + /** ClientLibrarySettings restNumericEnums. */ + public restNumericEnums: boolean; - /** - * Creates a plain object from a RunQueryRequest message. Also converts values to other types if specified. - * @param message RunQueryRequest - * @param [options] Conversion options - * @returns Plain object - */ - public static toObject(message: google.firestore.v1.RunQueryRequest, options?: $protobuf.IConversionOptions): { [k: string]: any }; + /** ClientLibrarySettings javaSettings. */ + public javaSettings?: (google.api.IJavaSettings|null); - /** - * Converts this RunQueryRequest to JSON. - * @returns JSON object - */ - public toJSON(): { [k: string]: any }; + /** ClientLibrarySettings cppSettings. */ + public cppSettings?: (google.api.ICppSettings|null); - /** - * Gets the default type url for RunQueryRequest - * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") - * @returns The default type url - */ - public static getTypeUrl(typeUrlPrefix?: string): string; - } + /** ClientLibrarySettings phpSettings. */ + public phpSettings?: (google.api.IPhpSettings|null); - /** Properties of a RunQueryResponse. */ - interface IRunQueryResponse { + /** ClientLibrarySettings pythonSettings. */ + public pythonSettings?: (google.api.IPythonSettings|null); - /** RunQueryResponse transaction */ - transaction?: (Uint8Array|null); + /** ClientLibrarySettings nodeSettings. */ + public nodeSettings?: (google.api.INodeSettings|null); - /** RunQueryResponse document */ - document?: (google.firestore.v1.IDocument|null); + /** ClientLibrarySettings dotnetSettings. */ + public dotnetSettings?: (google.api.IDotnetSettings|null); - /** RunQueryResponse readTime */ - readTime?: (google.protobuf.ITimestamp|null); + /** ClientLibrarySettings rubySettings. */ + public rubySettings?: (google.api.IRubySettings|null); - /** RunQueryResponse skippedResults */ - skippedResults?: (number|null); + /** ClientLibrarySettings goSettings. */ + public goSettings?: (google.api.IGoSettings|null); - /** RunQueryResponse done */ - done?: (boolean|null); + /** + * Creates a ClientLibrarySettings message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns ClientLibrarySettings + */ + public static fromObject(object: { [k: string]: any }): google.api.ClientLibrarySettings; - /** RunQueryResponse explainMetrics */ - explainMetrics?: (google.firestore.v1.IExplainMetrics|null); - } + /** + * Creates a plain object from a ClientLibrarySettings message. Also converts values to other types if specified. + * @param message ClientLibrarySettings + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.api.ClientLibrarySettings, options?: $protobuf.IConversionOptions): { [k: string]: any }; - /** Represents a RunQueryResponse. */ - class RunQueryResponse implements IRunQueryResponse { + /** + * Converts this ClientLibrarySettings to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; - /** - * Constructs a new RunQueryResponse. - * @param [properties] Properties to set - */ - constructor(properties?: google.firestore.v1.IRunQueryResponse); + /** + * Gets the default type url for ClientLibrarySettings + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } - /** RunQueryResponse transaction. */ - public transaction: Uint8Array; + /** Properties of a Publishing. */ + interface IPublishing { - /** RunQueryResponse document. */ - public document?: (google.firestore.v1.IDocument|null); + /** Publishing methodSettings */ + methodSettings?: (google.api.IMethodSettings[]|null); - /** RunQueryResponse readTime. */ - public readTime?: (google.protobuf.ITimestamp|null); + /** Publishing newIssueUri */ + newIssueUri?: (string|null); - /** RunQueryResponse skippedResults. */ - public skippedResults: number; + /** Publishing documentationUri */ + documentationUri?: (string|null); - /** RunQueryResponse done. */ - public done?: (boolean|null); + /** Publishing apiShortName */ + apiShortName?: (string|null); - /** RunQueryResponse explainMetrics. */ - public explainMetrics?: (google.firestore.v1.IExplainMetrics|null); + /** Publishing githubLabel */ + githubLabel?: (string|null); - /** RunQueryResponse continuationSelector. */ - public continuationSelector?: "done"; + /** Publishing codeownerGithubTeams */ + codeownerGithubTeams?: (string[]|null); - /** - * Creates a RunQueryResponse message from a plain object. Also converts values to their respective internal types. - * @param object Plain object - * @returns RunQueryResponse - */ - public static fromObject(object: { [k: string]: any }): google.firestore.v1.RunQueryResponse; + /** Publishing docTagPrefix */ + docTagPrefix?: (string|null); - /** - * Creates a plain object from a RunQueryResponse message. Also converts values to other types if specified. - * @param message RunQueryResponse - * @param [options] Conversion options - * @returns Plain object - */ - public static toObject(message: google.firestore.v1.RunQueryResponse, options?: $protobuf.IConversionOptions): { [k: string]: any }; + /** Publishing organization */ + organization?: (google.api.ClientLibraryOrganization|null); - /** - * Converts this RunQueryResponse to JSON. - * @returns JSON object - */ - public toJSON(): { [k: string]: any }; + /** Publishing librarySettings */ + librarySettings?: (google.api.IClientLibrarySettings[]|null); - /** - * Gets the default type url for RunQueryResponse - * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") - * @returns The default type url - */ - public static getTypeUrl(typeUrlPrefix?: string): string; - } + /** Publishing protoReferenceDocumentationUri */ + protoReferenceDocumentationUri?: (string|null); - /** Properties of an ExecutePipelineRequest. */ - interface IExecutePipelineRequest { + /** Publishing restReferenceDocumentationUri */ + restReferenceDocumentationUri?: (string|null); + } - /** ExecutePipelineRequest database */ - database?: (string|null); + /** Represents a Publishing. */ + class Publishing implements IPublishing { - /** ExecutePipelineRequest structuredPipeline */ - structuredPipeline?: (google.firestore.v1.IStructuredPipeline|null); + /** + * Constructs a new Publishing. + * @param [properties] Properties to set + */ + constructor(properties?: google.api.IPublishing); - /** ExecutePipelineRequest transaction */ - transaction?: (Uint8Array|null); + /** Publishing methodSettings. */ + public methodSettings: google.api.IMethodSettings[]; - /** ExecutePipelineRequest newTransaction */ - newTransaction?: (google.firestore.v1.ITransactionOptions|null); + /** Publishing newIssueUri. */ + public newIssueUri: string; - /** ExecutePipelineRequest readTime */ - readTime?: (google.protobuf.ITimestamp|null); - } + /** Publishing documentationUri. */ + public documentationUri: string; - /** Represents an ExecutePipelineRequest. */ - class ExecutePipelineRequest implements IExecutePipelineRequest { + /** Publishing apiShortName. */ + public apiShortName: string; - /** - * Constructs a new ExecutePipelineRequest. - * @param [properties] Properties to set - */ - constructor(properties?: google.firestore.v1.IExecutePipelineRequest); + /** Publishing githubLabel. */ + public githubLabel: string; - /** ExecutePipelineRequest database. */ - public database: string; + /** Publishing codeownerGithubTeams. */ + public codeownerGithubTeams: string[]; - /** ExecutePipelineRequest structuredPipeline. */ - public structuredPipeline?: (google.firestore.v1.IStructuredPipeline|null); + /** Publishing docTagPrefix. */ + public docTagPrefix: string; - /** ExecutePipelineRequest transaction. */ - public transaction?: (Uint8Array|null); + /** Publishing organization. */ + public organization: google.api.ClientLibraryOrganization; - /** ExecutePipelineRequest newTransaction. */ - public newTransaction?: (google.firestore.v1.ITransactionOptions|null); + /** Publishing librarySettings. */ + public librarySettings: google.api.IClientLibrarySettings[]; - /** ExecutePipelineRequest readTime. */ - public readTime?: (google.protobuf.ITimestamp|null); + /** Publishing protoReferenceDocumentationUri. */ + public protoReferenceDocumentationUri: string; - /** ExecutePipelineRequest pipelineType. */ - public pipelineType?: "structuredPipeline"; + /** Publishing restReferenceDocumentationUri. */ + public restReferenceDocumentationUri: string; - /** ExecutePipelineRequest consistencySelector. */ - public consistencySelector?: ("transaction"|"newTransaction"|"readTime"); + /** + * Creates a Publishing message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns Publishing + */ + public static fromObject(object: { [k: string]: any }): google.api.Publishing; - /** - * Creates an ExecutePipelineRequest message from a plain object. Also converts values to their respective internal types. - * @param object Plain object - * @returns ExecutePipelineRequest - */ - public static fromObject(object: { [k: string]: any }): google.firestore.v1.ExecutePipelineRequest; + /** + * Creates a plain object from a Publishing message. Also converts values to other types if specified. + * @param message Publishing + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.api.Publishing, options?: $protobuf.IConversionOptions): { [k: string]: any }; - /** - * Creates a plain object from an ExecutePipelineRequest message. Also converts values to other types if specified. - * @param message ExecutePipelineRequest - * @param [options] Conversion options - * @returns Plain object - */ - public static toObject(message: google.firestore.v1.ExecutePipelineRequest, options?: $protobuf.IConversionOptions): { [k: string]: any }; + /** + * Converts this Publishing to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; - /** - * Converts this ExecutePipelineRequest to JSON. - * @returns JSON object - */ - public toJSON(): { [k: string]: any }; + /** + * Gets the default type url for Publishing + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } - /** - * Gets the default type url for ExecutePipelineRequest - * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") - * @returns The default type url - */ - public static getTypeUrl(typeUrlPrefix?: string): string; - } + /** Properties of a JavaSettings. */ + interface IJavaSettings { - /** Properties of an ExecutePipelineResponse. */ - interface IExecutePipelineResponse { + /** JavaSettings libraryPackage */ + libraryPackage?: (string|null); - /** ExecutePipelineResponse transaction */ - transaction?: (Uint8Array|null); + /** JavaSettings serviceClassNames */ + serviceClassNames?: ({ [k: string]: string }|null); - /** ExecutePipelineResponse results */ - results?: (google.firestore.v1.IDocument[]|null); + /** JavaSettings common */ + common?: (google.api.ICommonLanguageSettings|null); + } - /** ExecutePipelineResponse executionTime */ - executionTime?: (google.protobuf.ITimestamp|null); - } + /** Represents a JavaSettings. */ + class JavaSettings implements IJavaSettings { - /** Represents an ExecutePipelineResponse. */ - class ExecutePipelineResponse implements IExecutePipelineResponse { + /** + * Constructs a new JavaSettings. + * @param [properties] Properties to set + */ + constructor(properties?: google.api.IJavaSettings); - /** - * Constructs a new ExecutePipelineResponse. - * @param [properties] Properties to set - */ - constructor(properties?: google.firestore.v1.IExecutePipelineResponse); + /** JavaSettings libraryPackage. */ + public libraryPackage: string; - /** ExecutePipelineResponse transaction. */ - public transaction: Uint8Array; + /** JavaSettings serviceClassNames. */ + public serviceClassNames: { [k: string]: string }; - /** ExecutePipelineResponse results. */ - public results: google.firestore.v1.IDocument[]; + /** JavaSettings common. */ + public common?: (google.api.ICommonLanguageSettings|null); - /** ExecutePipelineResponse executionTime. */ - public executionTime?: (google.protobuf.ITimestamp|null); + /** + * Creates a JavaSettings message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns JavaSettings + */ + public static fromObject(object: { [k: string]: any }): google.api.JavaSettings; - /** - * Creates an ExecutePipelineResponse message from a plain object. Also converts values to their respective internal types. - * @param object Plain object - * @returns ExecutePipelineResponse - */ - public static fromObject(object: { [k: string]: any }): google.firestore.v1.ExecutePipelineResponse; + /** + * Creates a plain object from a JavaSettings message. Also converts values to other types if specified. + * @param message JavaSettings + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.api.JavaSettings, options?: $protobuf.IConversionOptions): { [k: string]: any }; - /** - * Creates a plain object from an ExecutePipelineResponse message. Also converts values to other types if specified. - * @param message ExecutePipelineResponse - * @param [options] Conversion options - * @returns Plain object - */ - public static toObject(message: google.firestore.v1.ExecutePipelineResponse, options?: $protobuf.IConversionOptions): { [k: string]: any }; + /** + * Converts this JavaSettings to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; - /** - * Converts this ExecutePipelineResponse to JSON. - * @returns JSON object - */ - public toJSON(): { [k: string]: any }; + /** + * Gets the default type url for JavaSettings + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } - /** - * Gets the default type url for ExecutePipelineResponse - * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") - * @returns The default type url - */ - public static getTypeUrl(typeUrlPrefix?: string): string; - } + /** Properties of a CppSettings. */ + interface ICppSettings { - /** Properties of a RunAggregationQueryRequest. */ - interface IRunAggregationQueryRequest { + /** CppSettings common */ + common?: (google.api.ICommonLanguageSettings|null); + } - /** RunAggregationQueryRequest parent */ - parent?: (string|null); + /** Represents a CppSettings. */ + class CppSettings implements ICppSettings { - /** RunAggregationQueryRequest structuredAggregationQuery */ - structuredAggregationQuery?: (google.firestore.v1.IStructuredAggregationQuery|null); + /** + * Constructs a new CppSettings. + * @param [properties] Properties to set + */ + constructor(properties?: google.api.ICppSettings); - /** RunAggregationQueryRequest transaction */ - transaction?: (Uint8Array|null); + /** CppSettings common. */ + public common?: (google.api.ICommonLanguageSettings|null); - /** RunAggregationQueryRequest newTransaction */ - newTransaction?: (google.firestore.v1.ITransactionOptions|null); + /** + * Creates a CppSettings message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns CppSettings + */ + public static fromObject(object: { [k: string]: any }): google.api.CppSettings; - /** RunAggregationQueryRequest readTime */ - readTime?: (google.protobuf.ITimestamp|null); + /** + * Creates a plain object from a CppSettings message. Also converts values to other types if specified. + * @param message CppSettings + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.api.CppSettings, options?: $protobuf.IConversionOptions): { [k: string]: any }; - /** RunAggregationQueryRequest explainOptions */ - explainOptions?: (google.firestore.v1.IExplainOptions|null); - } + /** + * Converts this CppSettings to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; - /** Represents a RunAggregationQueryRequest. */ - class RunAggregationQueryRequest implements IRunAggregationQueryRequest { + /** + * Gets the default type url for CppSettings + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } - /** - * Constructs a new RunAggregationQueryRequest. - * @param [properties] Properties to set - */ - constructor(properties?: google.firestore.v1.IRunAggregationQueryRequest); + /** Properties of a PhpSettings. */ + interface IPhpSettings { - /** RunAggregationQueryRequest parent. */ - public parent: string; + /** PhpSettings common */ + common?: (google.api.ICommonLanguageSettings|null); + } - /** RunAggregationQueryRequest structuredAggregationQuery. */ - public structuredAggregationQuery?: (google.firestore.v1.IStructuredAggregationQuery|null); + /** Represents a PhpSettings. */ + class PhpSettings implements IPhpSettings { - /** RunAggregationQueryRequest transaction. */ - public transaction?: (Uint8Array|null); + /** + * Constructs a new PhpSettings. + * @param [properties] Properties to set + */ + constructor(properties?: google.api.IPhpSettings); - /** RunAggregationQueryRequest newTransaction. */ - public newTransaction?: (google.firestore.v1.ITransactionOptions|null); + /** PhpSettings common. */ + public common?: (google.api.ICommonLanguageSettings|null); - /** RunAggregationQueryRequest readTime. */ - public readTime?: (google.protobuf.ITimestamp|null); + /** + * Creates a PhpSettings message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns PhpSettings + */ + public static fromObject(object: { [k: string]: any }): google.api.PhpSettings; - /** RunAggregationQueryRequest explainOptions. */ - public explainOptions?: (google.firestore.v1.IExplainOptions|null); + /** + * Creates a plain object from a PhpSettings message. Also converts values to other types if specified. + * @param message PhpSettings + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.api.PhpSettings, options?: $protobuf.IConversionOptions): { [k: string]: any }; - /** RunAggregationQueryRequest queryType. */ - public queryType?: "structuredAggregationQuery"; + /** + * Converts this PhpSettings to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; - /** RunAggregationQueryRequest consistencySelector. */ - public consistencySelector?: ("transaction"|"newTransaction"|"readTime"); + /** + * Gets the default type url for PhpSettings + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } - /** - * Creates a RunAggregationQueryRequest message from a plain object. Also converts values to their respective internal types. - * @param object Plain object - * @returns RunAggregationQueryRequest - */ - public static fromObject(object: { [k: string]: any }): google.firestore.v1.RunAggregationQueryRequest; + /** Properties of a PythonSettings. */ + interface IPythonSettings { + + /** PythonSettings common */ + common?: (google.api.ICommonLanguageSettings|null); + } - /** - * Creates a plain object from a RunAggregationQueryRequest message. Also converts values to other types if specified. - * @param message RunAggregationQueryRequest - * @param [options] Conversion options - * @returns Plain object - */ - public static toObject(message: google.firestore.v1.RunAggregationQueryRequest, options?: $protobuf.IConversionOptions): { [k: string]: any }; + /** Represents a PythonSettings. */ + class PythonSettings implements IPythonSettings { - /** - * Converts this RunAggregationQueryRequest to JSON. - * @returns JSON object - */ - public toJSON(): { [k: string]: any }; + /** + * Constructs a new PythonSettings. + * @param [properties] Properties to set + */ + constructor(properties?: google.api.IPythonSettings); - /** - * Gets the default type url for RunAggregationQueryRequest - * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") - * @returns The default type url - */ - public static getTypeUrl(typeUrlPrefix?: string): string; - } + /** PythonSettings common. */ + public common?: (google.api.ICommonLanguageSettings|null); - /** Properties of a RunAggregationQueryResponse. */ - interface IRunAggregationQueryResponse { + /** + * Creates a PythonSettings message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns PythonSettings + */ + public static fromObject(object: { [k: string]: any }): google.api.PythonSettings; - /** RunAggregationQueryResponse result */ - result?: (google.firestore.v1.IAggregationResult|null); + /** + * Creates a plain object from a PythonSettings message. Also converts values to other types if specified. + * @param message PythonSettings + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.api.PythonSettings, options?: $protobuf.IConversionOptions): { [k: string]: any }; - /** RunAggregationQueryResponse transaction */ - transaction?: (Uint8Array|null); + /** + * Converts this PythonSettings to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; - /** RunAggregationQueryResponse readTime */ - readTime?: (google.protobuf.ITimestamp|null); + /** + * Gets the default type url for PythonSettings + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } - /** RunAggregationQueryResponse explainMetrics */ - explainMetrics?: (google.firestore.v1.IExplainMetrics|null); - } + /** Properties of a NodeSettings. */ + interface INodeSettings { - /** Represents a RunAggregationQueryResponse. */ - class RunAggregationQueryResponse implements IRunAggregationQueryResponse { + /** NodeSettings common */ + common?: (google.api.ICommonLanguageSettings|null); + } - /** - * Constructs a new RunAggregationQueryResponse. - * @param [properties] Properties to set - */ - constructor(properties?: google.firestore.v1.IRunAggregationQueryResponse); + /** Represents a NodeSettings. */ + class NodeSettings implements INodeSettings { - /** RunAggregationQueryResponse result. */ - public result?: (google.firestore.v1.IAggregationResult|null); + /** + * Constructs a new NodeSettings. + * @param [properties] Properties to set + */ + constructor(properties?: google.api.INodeSettings); - /** RunAggregationQueryResponse transaction. */ - public transaction: Uint8Array; + /** NodeSettings common. */ + public common?: (google.api.ICommonLanguageSettings|null); - /** RunAggregationQueryResponse readTime. */ - public readTime?: (google.protobuf.ITimestamp|null); + /** + * Creates a NodeSettings message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns NodeSettings + */ + public static fromObject(object: { [k: string]: any }): google.api.NodeSettings; - /** RunAggregationQueryResponse explainMetrics. */ - public explainMetrics?: (google.firestore.v1.IExplainMetrics|null); + /** + * Creates a plain object from a NodeSettings message. Also converts values to other types if specified. + * @param message NodeSettings + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.api.NodeSettings, options?: $protobuf.IConversionOptions): { [k: string]: any }; - /** - * Creates a RunAggregationQueryResponse message from a plain object. Also converts values to their respective internal types. - * @param object Plain object - * @returns RunAggregationQueryResponse - */ - public static fromObject(object: { [k: string]: any }): google.firestore.v1.RunAggregationQueryResponse; + /** + * Converts this NodeSettings to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; - /** - * Creates a plain object from a RunAggregationQueryResponse message. Also converts values to other types if specified. - * @param message RunAggregationQueryResponse - * @param [options] Conversion options - * @returns Plain object - */ - public static toObject(message: google.firestore.v1.RunAggregationQueryResponse, options?: $protobuf.IConversionOptions): { [k: string]: any }; + /** + * Gets the default type url for NodeSettings + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } - /** - * Converts this RunAggregationQueryResponse to JSON. - * @returns JSON object - */ - public toJSON(): { [k: string]: any }; + /** Properties of a DotnetSettings. */ + interface IDotnetSettings { - /** - * Gets the default type url for RunAggregationQueryResponse - * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") - * @returns The default type url - */ - public static getTypeUrl(typeUrlPrefix?: string): string; - } + /** DotnetSettings common */ + common?: (google.api.ICommonLanguageSettings|null); - /** Properties of a PartitionQueryRequest. */ - interface IPartitionQueryRequest { + /** DotnetSettings renamedServices */ + renamedServices?: ({ [k: string]: string }|null); - /** PartitionQueryRequest parent */ - parent?: (string|null); + /** DotnetSettings renamedResources */ + renamedResources?: ({ [k: string]: string }|null); - /** PartitionQueryRequest structuredQuery */ - structuredQuery?: (google.firestore.v1.IStructuredQuery|null); + /** DotnetSettings ignoredResources */ + ignoredResources?: (string[]|null); - /** PartitionQueryRequest partitionCount */ - partitionCount?: (number|string|null); + /** DotnetSettings forcedNamespaceAliases */ + forcedNamespaceAliases?: (string[]|null); - /** PartitionQueryRequest pageToken */ - pageToken?: (string|null); + /** DotnetSettings handwrittenSignatures */ + handwrittenSignatures?: (string[]|null); + } - /** PartitionQueryRequest pageSize */ - pageSize?: (number|null); + /** Represents a DotnetSettings. */ + class DotnetSettings implements IDotnetSettings { - /** PartitionQueryRequest readTime */ - readTime?: (google.protobuf.ITimestamp|null); - } + /** + * Constructs a new DotnetSettings. + * @param [properties] Properties to set + */ + constructor(properties?: google.api.IDotnetSettings); - /** Represents a PartitionQueryRequest. */ - class PartitionQueryRequest implements IPartitionQueryRequest { + /** DotnetSettings common. */ + public common?: (google.api.ICommonLanguageSettings|null); - /** - * Constructs a new PartitionQueryRequest. - * @param [properties] Properties to set - */ - constructor(properties?: google.firestore.v1.IPartitionQueryRequest); + /** DotnetSettings renamedServices. */ + public renamedServices: { [k: string]: string }; - /** PartitionQueryRequest parent. */ - public parent: string; + /** DotnetSettings renamedResources. */ + public renamedResources: { [k: string]: string }; - /** PartitionQueryRequest structuredQuery. */ - public structuredQuery?: (google.firestore.v1.IStructuredQuery|null); + /** DotnetSettings ignoredResources. */ + public ignoredResources: string[]; - /** PartitionQueryRequest partitionCount. */ - public partitionCount: (number|string); + /** DotnetSettings forcedNamespaceAliases. */ + public forcedNamespaceAliases: string[]; - /** PartitionQueryRequest pageToken. */ - public pageToken: string; + /** DotnetSettings handwrittenSignatures. */ + public handwrittenSignatures: string[]; - /** PartitionQueryRequest pageSize. */ - public pageSize: number; + /** + * Creates a DotnetSettings message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns DotnetSettings + */ + public static fromObject(object: { [k: string]: any }): google.api.DotnetSettings; - /** PartitionQueryRequest readTime. */ - public readTime?: (google.protobuf.ITimestamp|null); + /** + * Creates a plain object from a DotnetSettings message. Also converts values to other types if specified. + * @param message DotnetSettings + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.api.DotnetSettings, options?: $protobuf.IConversionOptions): { [k: string]: any }; - /** PartitionQueryRequest queryType. */ - public queryType?: "structuredQuery"; + /** + * Converts this DotnetSettings to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; - /** PartitionQueryRequest consistencySelector. */ - public consistencySelector?: "readTime"; + /** + * Gets the default type url for DotnetSettings + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } - /** - * Creates a PartitionQueryRequest message from a plain object. Also converts values to their respective internal types. - * @param object Plain object - * @returns PartitionQueryRequest - */ - public static fromObject(object: { [k: string]: any }): google.firestore.v1.PartitionQueryRequest; + /** Properties of a RubySettings. */ + interface IRubySettings { - /** - * Creates a plain object from a PartitionQueryRequest message. Also converts values to other types if specified. - * @param message PartitionQueryRequest - * @param [options] Conversion options - * @returns Plain object - */ - public static toObject(message: google.firestore.v1.PartitionQueryRequest, options?: $protobuf.IConversionOptions): { [k: string]: any }; + /** RubySettings common */ + common?: (google.api.ICommonLanguageSettings|null); + } - /** - * Converts this PartitionQueryRequest to JSON. - * @returns JSON object - */ - public toJSON(): { [k: string]: any }; + /** Represents a RubySettings. */ + class RubySettings implements IRubySettings { - /** - * Gets the default type url for PartitionQueryRequest - * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") - * @returns The default type url - */ - public static getTypeUrl(typeUrlPrefix?: string): string; - } + /** + * Constructs a new RubySettings. + * @param [properties] Properties to set + */ + constructor(properties?: google.api.IRubySettings); - /** Properties of a PartitionQueryResponse. */ - interface IPartitionQueryResponse { + /** RubySettings common. */ + public common?: (google.api.ICommonLanguageSettings|null); - /** PartitionQueryResponse partitions */ - partitions?: (google.firestore.v1.ICursor[]|null); + /** + * Creates a RubySettings message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns RubySettings + */ + public static fromObject(object: { [k: string]: any }): google.api.RubySettings; - /** PartitionQueryResponse nextPageToken */ - nextPageToken?: (string|null); - } + /** + * Creates a plain object from a RubySettings message. Also converts values to other types if specified. + * @param message RubySettings + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.api.RubySettings, options?: $protobuf.IConversionOptions): { [k: string]: any }; - /** Represents a PartitionQueryResponse. */ - class PartitionQueryResponse implements IPartitionQueryResponse { + /** + * Converts this RubySettings to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; - /** - * Constructs a new PartitionQueryResponse. - * @param [properties] Properties to set - */ - constructor(properties?: google.firestore.v1.IPartitionQueryResponse); + /** + * Gets the default type url for RubySettings + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } - /** PartitionQueryResponse partitions. */ - public partitions: google.firestore.v1.ICursor[]; + /** Properties of a GoSettings. */ + interface IGoSettings { - /** PartitionQueryResponse nextPageToken. */ - public nextPageToken: string; + /** GoSettings common */ + common?: (google.api.ICommonLanguageSettings|null); + } - /** - * Creates a PartitionQueryResponse message from a plain object. Also converts values to their respective internal types. - * @param object Plain object - * @returns PartitionQueryResponse - */ - public static fromObject(object: { [k: string]: any }): google.firestore.v1.PartitionQueryResponse; + /** Represents a GoSettings. */ + class GoSettings implements IGoSettings { - /** - * Creates a plain object from a PartitionQueryResponse message. Also converts values to other types if specified. - * @param message PartitionQueryResponse - * @param [options] Conversion options - * @returns Plain object - */ - public static toObject(message: google.firestore.v1.PartitionQueryResponse, options?: $protobuf.IConversionOptions): { [k: string]: any }; + /** + * Constructs a new GoSettings. + * @param [properties] Properties to set + */ + constructor(properties?: google.api.IGoSettings); - /** - * Converts this PartitionQueryResponse to JSON. - * @returns JSON object - */ - public toJSON(): { [k: string]: any }; + /** GoSettings common. */ + public common?: (google.api.ICommonLanguageSettings|null); - /** - * Gets the default type url for PartitionQueryResponse - * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") - * @returns The default type url - */ - public static getTypeUrl(typeUrlPrefix?: string): string; - } + /** + * Creates a GoSettings message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns GoSettings + */ + public static fromObject(object: { [k: string]: any }): google.api.GoSettings; - /** Properties of a WriteRequest. */ - interface IWriteRequest { + /** + * Creates a plain object from a GoSettings message. Also converts values to other types if specified. + * @param message GoSettings + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.api.GoSettings, options?: $protobuf.IConversionOptions): { [k: string]: any }; - /** WriteRequest database */ - database?: (string|null); + /** + * Converts this GoSettings to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; - /** WriteRequest streamId */ - streamId?: (string|null); + /** + * Gets the default type url for GoSettings + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } - /** WriteRequest writes */ - writes?: (google.firestore.v1.IWrite[]|null); + /** Properties of a MethodSettings. */ + interface IMethodSettings { - /** WriteRequest streamToken */ - streamToken?: (Uint8Array|null); + /** MethodSettings selector */ + selector?: (string|null); - /** WriteRequest labels */ - labels?: ({ [k: string]: string }|null); - } + /** MethodSettings longRunning */ + longRunning?: (google.api.MethodSettings.ILongRunning|null); - /** Represents a WriteRequest. */ - class WriteRequest implements IWriteRequest { + /** MethodSettings autoPopulatedFields */ + autoPopulatedFields?: (string[]|null); + } - /** - * Constructs a new WriteRequest. - * @param [properties] Properties to set - */ - constructor(properties?: google.firestore.v1.IWriteRequest); + /** Represents a MethodSettings. */ + class MethodSettings implements IMethodSettings { - /** WriteRequest database. */ - public database: string; + /** + * Constructs a new MethodSettings. + * @param [properties] Properties to set + */ + constructor(properties?: google.api.IMethodSettings); - /** WriteRequest streamId. */ - public streamId: string; + /** MethodSettings selector. */ + public selector: string; - /** WriteRequest writes. */ - public writes: google.firestore.v1.IWrite[]; + /** MethodSettings longRunning. */ + public longRunning?: (google.api.MethodSettings.ILongRunning|null); - /** WriteRequest streamToken. */ - public streamToken: Uint8Array; + /** MethodSettings autoPopulatedFields. */ + public autoPopulatedFields: string[]; - /** WriteRequest labels. */ - public labels: { [k: string]: string }; + /** + * Creates a MethodSettings message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns MethodSettings + */ + public static fromObject(object: { [k: string]: any }): google.api.MethodSettings; - /** - * Creates a WriteRequest message from a plain object. Also converts values to their respective internal types. - * @param object Plain object - * @returns WriteRequest - */ - public static fromObject(object: { [k: string]: any }): google.firestore.v1.WriteRequest; + /** + * Creates a plain object from a MethodSettings message. Also converts values to other types if specified. + * @param message MethodSettings + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.api.MethodSettings, options?: $protobuf.IConversionOptions): { [k: string]: any }; - /** - * Creates a plain object from a WriteRequest message. Also converts values to other types if specified. - * @param message WriteRequest - * @param [options] Conversion options - * @returns Plain object - */ - public static toObject(message: google.firestore.v1.WriteRequest, options?: $protobuf.IConversionOptions): { [k: string]: any }; + /** + * Converts this MethodSettings to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; - /** - * Converts this WriteRequest to JSON. - * @returns JSON object - */ - public toJSON(): { [k: string]: any }; + /** + * Gets the default type url for MethodSettings + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } - /** - * Gets the default type url for WriteRequest - * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") - * @returns The default type url - */ - public static getTypeUrl(typeUrlPrefix?: string): string; - } + namespace MethodSettings { - /** Properties of a WriteResponse. */ - interface IWriteResponse { + /** Properties of a LongRunning. */ + interface ILongRunning { - /** WriteResponse streamId */ - streamId?: (string|null); + /** LongRunning initialPollDelay */ + initialPollDelay?: (google.protobuf.IDuration|null); - /** WriteResponse streamToken */ - streamToken?: (Uint8Array|null); + /** LongRunning pollDelayMultiplier */ + pollDelayMultiplier?: (number|null); - /** WriteResponse writeResults */ - writeResults?: (google.firestore.v1.IWriteResult[]|null); + /** LongRunning maxPollDelay */ + maxPollDelay?: (google.protobuf.IDuration|null); - /** WriteResponse commitTime */ - commitTime?: (google.protobuf.ITimestamp|null); + /** LongRunning totalPollTimeout */ + totalPollTimeout?: (google.protobuf.IDuration|null); } - /** Represents a WriteResponse. */ - class WriteResponse implements IWriteResponse { + /** Represents a LongRunning. */ + class LongRunning implements ILongRunning { /** - * Constructs a new WriteResponse. + * Constructs a new LongRunning. * @param [properties] Properties to set */ - constructor(properties?: google.firestore.v1.IWriteResponse); + constructor(properties?: google.api.MethodSettings.ILongRunning); - /** WriteResponse streamId. */ - public streamId: string; + /** LongRunning initialPollDelay. */ + public initialPollDelay?: (google.protobuf.IDuration|null); - /** WriteResponse streamToken. */ - public streamToken: Uint8Array; + /** LongRunning pollDelayMultiplier. */ + public pollDelayMultiplier: number; - /** WriteResponse writeResults. */ - public writeResults: google.firestore.v1.IWriteResult[]; + /** LongRunning maxPollDelay. */ + public maxPollDelay?: (google.protobuf.IDuration|null); - /** WriteResponse commitTime. */ - public commitTime?: (google.protobuf.ITimestamp|null); + /** LongRunning totalPollTimeout. */ + public totalPollTimeout?: (google.protobuf.IDuration|null); /** - * Creates a WriteResponse message from a plain object. Also converts values to their respective internal types. + * Creates a LongRunning message from a plain object. Also converts values to their respective internal types. * @param object Plain object - * @returns WriteResponse + * @returns LongRunning */ - public static fromObject(object: { [k: string]: any }): google.firestore.v1.WriteResponse; + public static fromObject(object: { [k: string]: any }): google.api.MethodSettings.LongRunning; /** - * Creates a plain object from a WriteResponse message. Also converts values to other types if specified. - * @param message WriteResponse + * Creates a plain object from a LongRunning message. Also converts values to other types if specified. + * @param message LongRunning * @param [options] Conversion options * @returns Plain object */ - public static toObject(message: google.firestore.v1.WriteResponse, options?: $protobuf.IConversionOptions): { [k: string]: any }; + public static toObject(message: google.api.MethodSettings.LongRunning, options?: $protobuf.IConversionOptions): { [k: string]: any }; /** - * Converts this WriteResponse to JSON. + * Converts this LongRunning to JSON. * @returns JSON object */ public toJSON(): { [k: string]: any }; /** - * Gets the default type url for WriteResponse + * Gets the default type url for LongRunning * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") * @returns The default type url */ public static getTypeUrl(typeUrlPrefix?: string): string; } + } - /** Properties of a ListenRequest. */ - interface IListenRequest { + /** ClientLibraryOrganization enum. */ + type ClientLibraryOrganization = + "CLIENT_LIBRARY_ORGANIZATION_UNSPECIFIED"| "CLOUD"| "ADS"| "PHOTOS"| "STREET_VIEW"| "SHOPPING"| "GEO"| "GENERATIVE_AI"; - /** ListenRequest database */ - database?: (string|null); + /** ClientLibraryDestination enum. */ + type ClientLibraryDestination = + "CLIENT_LIBRARY_DESTINATION_UNSPECIFIED"| "GITHUB"| "PACKAGE_MANAGER"; - /** ListenRequest addTarget */ - addTarget?: (google.firestore.v1.ITarget|null); + /** LaunchStage enum. */ + type LaunchStage = + "LAUNCH_STAGE_UNSPECIFIED"| "UNIMPLEMENTED"| "PRELAUNCH"| "EARLY_ACCESS"| "ALPHA"| "BETA"| "GA"| "DEPRECATED"; - /** ListenRequest removeTarget */ - removeTarget?: (number|null); + /** Properties of a ResourceDescriptor. */ + interface IResourceDescriptor { - /** ListenRequest labels */ - labels?: ({ [k: string]: string }|null); - } + /** ResourceDescriptor type */ + type?: (string|null); - /** Represents a ListenRequest. */ - class ListenRequest implements IListenRequest { + /** ResourceDescriptor pattern */ + pattern?: (string[]|null); - /** - * Constructs a new ListenRequest. - * @param [properties] Properties to set - */ - constructor(properties?: google.firestore.v1.IListenRequest); + /** ResourceDescriptor nameField */ + nameField?: (string|null); - /** ListenRequest database. */ - public database: string; + /** ResourceDescriptor history */ + history?: (google.api.ResourceDescriptor.History|null); - /** ListenRequest addTarget. */ - public addTarget?: (google.firestore.v1.ITarget|null); + /** ResourceDescriptor plural */ + plural?: (string|null); - /** ListenRequest removeTarget. */ - public removeTarget?: (number|null); + /** ResourceDescriptor singular */ + singular?: (string|null); - /** ListenRequest labels. */ - public labels: { [k: string]: string }; + /** ResourceDescriptor style */ + style?: (google.api.ResourceDescriptor.Style[]|null); + } - /** ListenRequest targetChange. */ - public targetChange?: ("addTarget"|"removeTarget"); + /** Represents a ResourceDescriptor. */ + class ResourceDescriptor implements IResourceDescriptor { - /** - * Creates a ListenRequest message from a plain object. Also converts values to their respective internal types. - * @param object Plain object - * @returns ListenRequest - */ - public static fromObject(object: { [k: string]: any }): google.firestore.v1.ListenRequest; + /** + * Constructs a new ResourceDescriptor. + * @param [properties] Properties to set + */ + constructor(properties?: google.api.IResourceDescriptor); - /** - * Creates a plain object from a ListenRequest message. Also converts values to other types if specified. - * @param message ListenRequest - * @param [options] Conversion options - * @returns Plain object - */ - public static toObject(message: google.firestore.v1.ListenRequest, options?: $protobuf.IConversionOptions): { [k: string]: any }; + /** ResourceDescriptor type. */ + public type: string; - /** - * Converts this ListenRequest to JSON. - * @returns JSON object - */ - public toJSON(): { [k: string]: any }; + /** ResourceDescriptor pattern. */ + public pattern: string[]; - /** - * Gets the default type url for ListenRequest - * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") - * @returns The default type url - */ - public static getTypeUrl(typeUrlPrefix?: string): string; - } + /** ResourceDescriptor nameField. */ + public nameField: string; + + /** ResourceDescriptor history. */ + public history: google.api.ResourceDescriptor.History; + + /** ResourceDescriptor plural. */ + public plural: string; + + /** ResourceDescriptor singular. */ + public singular: string; + + /** ResourceDescriptor style. */ + public style: google.api.ResourceDescriptor.Style[]; + + /** + * Creates a ResourceDescriptor message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns ResourceDescriptor + */ + public static fromObject(object: { [k: string]: any }): google.api.ResourceDescriptor; + + /** + * Creates a plain object from a ResourceDescriptor message. Also converts values to other types if specified. + * @param message ResourceDescriptor + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.api.ResourceDescriptor, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this ResourceDescriptor to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for ResourceDescriptor + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + namespace ResourceDescriptor { + + /** History enum. */ + type History = + "HISTORY_UNSPECIFIED"| "ORIGINALLY_SINGLE_PATTERN"| "FUTURE_MULTI_PATTERN"; + + /** Style enum. */ + type Style = + "STYLE_UNSPECIFIED"| "DECLARATIVE_FRIENDLY"; + } + + /** Properties of a ResourceReference. */ + interface IResourceReference { + + /** ResourceReference type */ + type?: (string|null); + + /** ResourceReference childType */ + childType?: (string|null); + } + + /** Represents a ResourceReference. */ + class ResourceReference implements IResourceReference { + + /** + * Constructs a new ResourceReference. + * @param [properties] Properties to set + */ + constructor(properties?: google.api.IResourceReference); + + /** ResourceReference type. */ + public type: string; + + /** ResourceReference childType. */ + public childType: string; + + /** + * Creates a ResourceReference message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns ResourceReference + */ + public static fromObject(object: { [k: string]: any }): google.api.ResourceReference; + + /** + * Creates a plain object from a ResourceReference message. Also converts values to other types if specified. + * @param message ResourceReference + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.api.ResourceReference, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this ResourceReference to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for ResourceReference + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + } + + /** Namespace protobuf. */ + namespace protobuf { + + /** Properties of a FileDescriptorSet. */ + interface IFileDescriptorSet { + + /** FileDescriptorSet file */ + file?: (google.protobuf.IFileDescriptorProto[]|null); + } + + /** Represents a FileDescriptorSet. */ + class FileDescriptorSet implements IFileDescriptorSet { + + /** + * Constructs a new FileDescriptorSet. + * @param [properties] Properties to set + */ + constructor(properties?: google.protobuf.IFileDescriptorSet); - /** Properties of a ListenResponse. */ - interface IListenResponse { + /** FileDescriptorSet file. */ + public file: google.protobuf.IFileDescriptorProto[]; - /** ListenResponse targetChange */ - targetChange?: (google.firestore.v1.ITargetChange|null); + /** + * Creates a FileDescriptorSet message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns FileDescriptorSet + */ + public static fromObject(object: { [k: string]: any }): google.protobuf.FileDescriptorSet; - /** ListenResponse documentChange */ - documentChange?: (google.firestore.v1.IDocumentChange|null); + /** + * Creates a plain object from a FileDescriptorSet message. Also converts values to other types if specified. + * @param message FileDescriptorSet + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.protobuf.FileDescriptorSet, options?: $protobuf.IConversionOptions): { [k: string]: any }; - /** ListenResponse documentDelete */ - documentDelete?: (google.firestore.v1.IDocumentDelete|null); + /** + * Converts this FileDescriptorSet to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; - /** ListenResponse documentRemove */ - documentRemove?: (google.firestore.v1.IDocumentRemove|null); + /** + * Gets the default type url for FileDescriptorSet + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } - /** ListenResponse filter */ - filter?: (google.firestore.v1.IExistenceFilter|null); - } + /** Edition enum. */ + type Edition = + "EDITION_UNKNOWN"| "EDITION_PROTO2"| "EDITION_PROTO3"| "EDITION_2023"| "EDITION_2024"| "EDITION_1_TEST_ONLY"| "EDITION_2_TEST_ONLY"| "EDITION_99997_TEST_ONLY"| "EDITION_99998_TEST_ONLY"| "EDITION_99999_TEST_ONLY"| "EDITION_MAX"; - /** Represents a ListenResponse. */ - class ListenResponse implements IListenResponse { + /** Properties of a FileDescriptorProto. */ + interface IFileDescriptorProto { - /** - * Constructs a new ListenResponse. - * @param [properties] Properties to set - */ - constructor(properties?: google.firestore.v1.IListenResponse); + /** FileDescriptorProto name */ + name?: (string|null); - /** ListenResponse targetChange. */ - public targetChange?: (google.firestore.v1.ITargetChange|null); + /** FileDescriptorProto package */ + "package"?: (string|null); - /** ListenResponse documentChange. */ - public documentChange?: (google.firestore.v1.IDocumentChange|null); + /** FileDescriptorProto dependency */ + dependency?: (string[]|null); - /** ListenResponse documentDelete. */ - public documentDelete?: (google.firestore.v1.IDocumentDelete|null); + /** FileDescriptorProto publicDependency */ + publicDependency?: (number[]|null); - /** ListenResponse documentRemove. */ - public documentRemove?: (google.firestore.v1.IDocumentRemove|null); + /** FileDescriptorProto weakDependency */ + weakDependency?: (number[]|null); - /** ListenResponse filter. */ - public filter?: (google.firestore.v1.IExistenceFilter|null); + /** FileDescriptorProto messageType */ + messageType?: (google.protobuf.IDescriptorProto[]|null); - /** ListenResponse responseType. */ - public responseType?: ("targetChange"|"documentChange"|"documentDelete"|"documentRemove"|"filter"); + /** FileDescriptorProto enumType */ + enumType?: (google.protobuf.IEnumDescriptorProto[]|null); - /** - * Creates a ListenResponse message from a plain object. Also converts values to their respective internal types. - * @param object Plain object - * @returns ListenResponse - */ - public static fromObject(object: { [k: string]: any }): google.firestore.v1.ListenResponse; + /** FileDescriptorProto service */ + service?: (google.protobuf.IServiceDescriptorProto[]|null); - /** - * Creates a plain object from a ListenResponse message. Also converts values to other types if specified. - * @param message ListenResponse - * @param [options] Conversion options - * @returns Plain object - */ - public static toObject(message: google.firestore.v1.ListenResponse, options?: $protobuf.IConversionOptions): { [k: string]: any }; + /** FileDescriptorProto extension */ + extension?: (google.protobuf.IFieldDescriptorProto[]|null); - /** - * Converts this ListenResponse to JSON. - * @returns JSON object - */ - public toJSON(): { [k: string]: any }; + /** FileDescriptorProto options */ + options?: (google.protobuf.IFileOptions|null); - /** - * Gets the default type url for ListenResponse - * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") - * @returns The default type url - */ - public static getTypeUrl(typeUrlPrefix?: string): string; - } + /** FileDescriptorProto sourceCodeInfo */ + sourceCodeInfo?: (google.protobuf.ISourceCodeInfo|null); - /** Properties of a Target. */ - interface ITarget { + /** FileDescriptorProto syntax */ + syntax?: (string|null); - /** Target query */ - query?: (google.firestore.v1.Target.IQueryTarget|null); + /** FileDescriptorProto edition */ + edition?: (google.protobuf.Edition|null); + } - /** Target documents */ - documents?: (google.firestore.v1.Target.IDocumentsTarget|null); + /** Represents a FileDescriptorProto. */ + class FileDescriptorProto implements IFileDescriptorProto { - /** Target resumeToken */ - resumeToken?: (Uint8Array|null); + /** + * Constructs a new FileDescriptorProto. + * @param [properties] Properties to set + */ + constructor(properties?: google.protobuf.IFileDescriptorProto); - /** Target readTime */ - readTime?: (google.protobuf.ITimestamp|null); + /** FileDescriptorProto name. */ + public name: string; - /** Target targetId */ - targetId?: (number|null); + /** FileDescriptorProto package. */ + public package: string; - /** Target once */ - once?: (boolean|null); + /** FileDescriptorProto dependency. */ + public dependency: string[]; - /** Target expectedCount */ - expectedCount?: (google.protobuf.IInt32Value|null); - } + /** FileDescriptorProto publicDependency. */ + public publicDependency: number[]; - /** Represents a Target. */ - class Target implements ITarget { + /** FileDescriptorProto weakDependency. */ + public weakDependency: number[]; - /** - * Constructs a new Target. - * @param [properties] Properties to set - */ - constructor(properties?: google.firestore.v1.ITarget); + /** FileDescriptorProto messageType. */ + public messageType: google.protobuf.IDescriptorProto[]; - /** Target query. */ - public query?: (google.firestore.v1.Target.IQueryTarget|null); + /** FileDescriptorProto enumType. */ + public enumType: google.protobuf.IEnumDescriptorProto[]; - /** Target documents. */ - public documents?: (google.firestore.v1.Target.IDocumentsTarget|null); + /** FileDescriptorProto service. */ + public service: google.protobuf.IServiceDescriptorProto[]; - /** Target resumeToken. */ - public resumeToken?: (Uint8Array|null); + /** FileDescriptorProto extension. */ + public extension: google.protobuf.IFieldDescriptorProto[]; - /** Target readTime. */ - public readTime?: (google.protobuf.ITimestamp|null); + /** FileDescriptorProto options. */ + public options?: (google.protobuf.IFileOptions|null); - /** Target targetId. */ - public targetId: number; + /** FileDescriptorProto sourceCodeInfo. */ + public sourceCodeInfo?: (google.protobuf.ISourceCodeInfo|null); - /** Target once. */ - public once: boolean; + /** FileDescriptorProto syntax. */ + public syntax: string; - /** Target expectedCount. */ - public expectedCount?: (google.protobuf.IInt32Value|null); + /** FileDescriptorProto edition. */ + public edition: google.protobuf.Edition; - /** Target targetType. */ - public targetType?: ("query"|"documents"); + /** + * Creates a FileDescriptorProto message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns FileDescriptorProto + */ + public static fromObject(object: { [k: string]: any }): google.protobuf.FileDescriptorProto; - /** Target resumeType. */ - public resumeType?: ("resumeToken"|"readTime"); + /** + * Creates a plain object from a FileDescriptorProto message. Also converts values to other types if specified. + * @param message FileDescriptorProto + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.protobuf.FileDescriptorProto, options?: $protobuf.IConversionOptions): { [k: string]: any }; - /** - * Creates a Target message from a plain object. Also converts values to their respective internal types. - * @param object Plain object - * @returns Target - */ - public static fromObject(object: { [k: string]: any }): google.firestore.v1.Target; + /** + * Converts this FileDescriptorProto to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; - /** - * Creates a plain object from a Target message. Also converts values to other types if specified. - * @param message Target - * @param [options] Conversion options - * @returns Plain object - */ - public static toObject(message: google.firestore.v1.Target, options?: $protobuf.IConversionOptions): { [k: string]: any }; + /** + * Gets the default type url for FileDescriptorProto + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } - /** - * Converts this Target to JSON. - * @returns JSON object - */ - public toJSON(): { [k: string]: any }; + /** Properties of a DescriptorProto. */ + interface IDescriptorProto { - /** - * Gets the default type url for Target - * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") - * @returns The default type url - */ - public static getTypeUrl(typeUrlPrefix?: string): string; - } + /** DescriptorProto name */ + name?: (string|null); - namespace Target { + /** DescriptorProto field */ + field?: (google.protobuf.IFieldDescriptorProto[]|null); - /** Properties of a DocumentsTarget. */ - interface IDocumentsTarget { + /** DescriptorProto extension */ + extension?: (google.protobuf.IFieldDescriptorProto[]|null); + + /** DescriptorProto nestedType */ + nestedType?: (google.protobuf.IDescriptorProto[]|null); + + /** DescriptorProto enumType */ + enumType?: (google.protobuf.IEnumDescriptorProto[]|null); - /** DocumentsTarget documents */ - documents?: (string[]|null); - } + /** DescriptorProto extensionRange */ + extensionRange?: (google.protobuf.DescriptorProto.IExtensionRange[]|null); - /** Represents a DocumentsTarget. */ - class DocumentsTarget implements IDocumentsTarget { + /** DescriptorProto oneofDecl */ + oneofDecl?: (google.protobuf.IOneofDescriptorProto[]|null); - /** - * Constructs a new DocumentsTarget. - * @param [properties] Properties to set - */ - constructor(properties?: google.firestore.v1.Target.IDocumentsTarget); + /** DescriptorProto options */ + options?: (google.protobuf.IMessageOptions|null); - /** DocumentsTarget documents. */ - public documents: string[]; + /** DescriptorProto reservedRange */ + reservedRange?: (google.protobuf.DescriptorProto.IReservedRange[]|null); - /** - * Creates a DocumentsTarget message from a plain object. Also converts values to their respective internal types. - * @param object Plain object - * @returns DocumentsTarget - */ - public static fromObject(object: { [k: string]: any }): google.firestore.v1.Target.DocumentsTarget; + /** DescriptorProto reservedName */ + reservedName?: (string[]|null); + } - /** - * Creates a plain object from a DocumentsTarget message. Also converts values to other types if specified. - * @param message DocumentsTarget - * @param [options] Conversion options - * @returns Plain object - */ - public static toObject(message: google.firestore.v1.Target.DocumentsTarget, options?: $protobuf.IConversionOptions): { [k: string]: any }; + /** Represents a DescriptorProto. */ + class DescriptorProto implements IDescriptorProto { - /** - * Converts this DocumentsTarget to JSON. - * @returns JSON object - */ - public toJSON(): { [k: string]: any }; + /** + * Constructs a new DescriptorProto. + * @param [properties] Properties to set + */ + constructor(properties?: google.protobuf.IDescriptorProto); - /** - * Gets the default type url for DocumentsTarget - * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") - * @returns The default type url - */ - public static getTypeUrl(typeUrlPrefix?: string): string; - } + /** DescriptorProto name. */ + public name: string; - /** Properties of a QueryTarget. */ - interface IQueryTarget { + /** DescriptorProto field. */ + public field: google.protobuf.IFieldDescriptorProto[]; - /** QueryTarget parent */ - parent?: (string|null); + /** DescriptorProto extension. */ + public extension: google.protobuf.IFieldDescriptorProto[]; - /** QueryTarget structuredQuery */ - structuredQuery?: (google.firestore.v1.IStructuredQuery|null); - } + /** DescriptorProto nestedType. */ + public nestedType: google.protobuf.IDescriptorProto[]; - /** Represents a QueryTarget. */ - class QueryTarget implements IQueryTarget { + /** DescriptorProto enumType. */ + public enumType: google.protobuf.IEnumDescriptorProto[]; - /** - * Constructs a new QueryTarget. - * @param [properties] Properties to set - */ - constructor(properties?: google.firestore.v1.Target.IQueryTarget); + /** DescriptorProto extensionRange. */ + public extensionRange: google.protobuf.DescriptorProto.IExtensionRange[]; - /** QueryTarget parent. */ - public parent: string; + /** DescriptorProto oneofDecl. */ + public oneofDecl: google.protobuf.IOneofDescriptorProto[]; - /** QueryTarget structuredQuery. */ - public structuredQuery?: (google.firestore.v1.IStructuredQuery|null); + /** DescriptorProto options. */ + public options?: (google.protobuf.IMessageOptions|null); - /** QueryTarget queryType. */ - public queryType?: "structuredQuery"; + /** DescriptorProto reservedRange. */ + public reservedRange: google.protobuf.DescriptorProto.IReservedRange[]; - /** - * Creates a QueryTarget message from a plain object. Also converts values to their respective internal types. - * @param object Plain object - * @returns QueryTarget - */ - public static fromObject(object: { [k: string]: any }): google.firestore.v1.Target.QueryTarget; + /** DescriptorProto reservedName. */ + public reservedName: string[]; - /** - * Creates a plain object from a QueryTarget message. Also converts values to other types if specified. - * @param message QueryTarget - * @param [options] Conversion options - * @returns Plain object - */ - public static toObject(message: google.firestore.v1.Target.QueryTarget, options?: $protobuf.IConversionOptions): { [k: string]: any }; + /** + * Creates a DescriptorProto message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns DescriptorProto + */ + public static fromObject(object: { [k: string]: any }): google.protobuf.DescriptorProto; - /** - * Converts this QueryTarget to JSON. - * @returns JSON object - */ - public toJSON(): { [k: string]: any }; + /** + * Creates a plain object from a DescriptorProto message. Also converts values to other types if specified. + * @param message DescriptorProto + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.protobuf.DescriptorProto, options?: $protobuf.IConversionOptions): { [k: string]: any }; - /** - * Gets the default type url for QueryTarget - * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") - * @returns The default type url - */ - public static getTypeUrl(typeUrlPrefix?: string): string; - } - } + /** + * Converts this DescriptorProto to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; - /** Properties of a TargetChange. */ - interface ITargetChange { + /** + * Gets the default type url for DescriptorProto + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } - /** TargetChange targetChangeType */ - targetChangeType?: (google.firestore.v1.TargetChange.TargetChangeType|null); + namespace DescriptorProto { - /** TargetChange targetIds */ - targetIds?: (number[]|null); + /** Properties of an ExtensionRange. */ + interface IExtensionRange { - /** TargetChange cause */ - cause?: (google.rpc.IStatus|null); + /** ExtensionRange start */ + start?: (number|null); - /** TargetChange resumeToken */ - resumeToken?: (Uint8Array|null); + /** ExtensionRange end */ + end?: (number|null); - /** TargetChange readTime */ - readTime?: (google.protobuf.ITimestamp|null); + /** ExtensionRange options */ + options?: (google.protobuf.IExtensionRangeOptions|null); } - /** Represents a TargetChange. */ - class TargetChange implements ITargetChange { + /** Represents an ExtensionRange. */ + class ExtensionRange implements IExtensionRange { /** - * Constructs a new TargetChange. + * Constructs a new ExtensionRange. * @param [properties] Properties to set */ - constructor(properties?: google.firestore.v1.ITargetChange); - - /** TargetChange targetChangeType. */ - public targetChangeType: google.firestore.v1.TargetChange.TargetChangeType; - - /** TargetChange targetIds. */ - public targetIds: number[]; + constructor(properties?: google.protobuf.DescriptorProto.IExtensionRange); - /** TargetChange cause. */ - public cause?: (google.rpc.IStatus|null); + /** ExtensionRange start. */ + public start: number; - /** TargetChange resumeToken. */ - public resumeToken: Uint8Array; + /** ExtensionRange end. */ + public end: number; - /** TargetChange readTime. */ - public readTime?: (google.protobuf.ITimestamp|null); + /** ExtensionRange options. */ + public options?: (google.protobuf.IExtensionRangeOptions|null); /** - * Creates a TargetChange message from a plain object. Also converts values to their respective internal types. + * Creates an ExtensionRange message from a plain object. Also converts values to their respective internal types. * @param object Plain object - * @returns TargetChange + * @returns ExtensionRange */ - public static fromObject(object: { [k: string]: any }): google.firestore.v1.TargetChange; + public static fromObject(object: { [k: string]: any }): google.protobuf.DescriptorProto.ExtensionRange; /** - * Creates a plain object from a TargetChange message. Also converts values to other types if specified. - * @param message TargetChange + * Creates a plain object from an ExtensionRange message. Also converts values to other types if specified. + * @param message ExtensionRange * @param [options] Conversion options * @returns Plain object */ - public static toObject(message: google.firestore.v1.TargetChange, options?: $protobuf.IConversionOptions): { [k: string]: any }; + public static toObject(message: google.protobuf.DescriptorProto.ExtensionRange, options?: $protobuf.IConversionOptions): { [k: string]: any }; /** - * Converts this TargetChange to JSON. + * Converts this ExtensionRange to JSON. * @returns JSON object */ public toJSON(): { [k: string]: any }; /** - * Gets the default type url for TargetChange + * Gets the default type url for ExtensionRange * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") * @returns The default type url */ public static getTypeUrl(typeUrlPrefix?: string): string; } - namespace TargetChange { - - /** TargetChangeType enum. */ - type TargetChangeType = - "NO_CHANGE"| "ADD"| "REMOVE"| "CURRENT"| "RESET"; - } - - /** Properties of a ListCollectionIdsRequest. */ - interface IListCollectionIdsRequest { - - /** ListCollectionIdsRequest parent */ - parent?: (string|null); - - /** ListCollectionIdsRequest pageSize */ - pageSize?: (number|null); + /** Properties of a ReservedRange. */ + interface IReservedRange { - /** ListCollectionIdsRequest pageToken */ - pageToken?: (string|null); + /** ReservedRange start */ + start?: (number|null); - /** ListCollectionIdsRequest readTime */ - readTime?: (google.protobuf.ITimestamp|null); + /** ReservedRange end */ + end?: (number|null); } - /** Represents a ListCollectionIdsRequest. */ - class ListCollectionIdsRequest implements IListCollectionIdsRequest { + /** Represents a ReservedRange. */ + class ReservedRange implements IReservedRange { /** - * Constructs a new ListCollectionIdsRequest. + * Constructs a new ReservedRange. * @param [properties] Properties to set */ - constructor(properties?: google.firestore.v1.IListCollectionIdsRequest); - - /** ListCollectionIdsRequest parent. */ - public parent: string; - - /** ListCollectionIdsRequest pageSize. */ - public pageSize: number; - - /** ListCollectionIdsRequest pageToken. */ - public pageToken: string; + constructor(properties?: google.protobuf.DescriptorProto.IReservedRange); - /** ListCollectionIdsRequest readTime. */ - public readTime?: (google.protobuf.ITimestamp|null); + /** ReservedRange start. */ + public start: number; - /** ListCollectionIdsRequest consistencySelector. */ - public consistencySelector?: "readTime"; + /** ReservedRange end. */ + public end: number; /** - * Creates a ListCollectionIdsRequest message from a plain object. Also converts values to their respective internal types. + * Creates a ReservedRange message from a plain object. Also converts values to their respective internal types. * @param object Plain object - * @returns ListCollectionIdsRequest + * @returns ReservedRange */ - public static fromObject(object: { [k: string]: any }): google.firestore.v1.ListCollectionIdsRequest; + public static fromObject(object: { [k: string]: any }): google.protobuf.DescriptorProto.ReservedRange; /** - * Creates a plain object from a ListCollectionIdsRequest message. Also converts values to other types if specified. - * @param message ListCollectionIdsRequest + * Creates a plain object from a ReservedRange message. Also converts values to other types if specified. + * @param message ReservedRange * @param [options] Conversion options * @returns Plain object */ - public static toObject(message: google.firestore.v1.ListCollectionIdsRequest, options?: $protobuf.IConversionOptions): { [k: string]: any }; + public static toObject(message: google.protobuf.DescriptorProto.ReservedRange, options?: $protobuf.IConversionOptions): { [k: string]: any }; /** - * Converts this ListCollectionIdsRequest to JSON. + * Converts this ReservedRange to JSON. * @returns JSON object */ public toJSON(): { [k: string]: any }; /** - * Gets the default type url for ListCollectionIdsRequest + * Gets the default type url for ReservedRange * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") * @returns The default type url */ public static getTypeUrl(typeUrlPrefix?: string): string; } + } - /** Properties of a ListCollectionIdsResponse. */ - interface IListCollectionIdsResponse { + /** Properties of an ExtensionRangeOptions. */ + interface IExtensionRangeOptions { - /** ListCollectionIdsResponse collectionIds */ - collectionIds?: (string[]|null); + /** ExtensionRangeOptions uninterpretedOption */ + uninterpretedOption?: (google.protobuf.IUninterpretedOption[]|null); - /** ListCollectionIdsResponse nextPageToken */ - nextPageToken?: (string|null); + /** ExtensionRangeOptions declaration */ + declaration?: (google.protobuf.ExtensionRangeOptions.IDeclaration[]|null); + + /** ExtensionRangeOptions features */ + features?: (google.protobuf.IFeatureSet|null); + + /** ExtensionRangeOptions verification */ + verification?: (google.protobuf.ExtensionRangeOptions.VerificationState|null); + } + + /** Represents an ExtensionRangeOptions. */ + class ExtensionRangeOptions implements IExtensionRangeOptions { + + /** + * Constructs a new ExtensionRangeOptions. + * @param [properties] Properties to set + */ + constructor(properties?: google.protobuf.IExtensionRangeOptions); + + /** ExtensionRangeOptions uninterpretedOption. */ + public uninterpretedOption: google.protobuf.IUninterpretedOption[]; + + /** ExtensionRangeOptions declaration. */ + public declaration: google.protobuf.ExtensionRangeOptions.IDeclaration[]; + + /** ExtensionRangeOptions features. */ + public features?: (google.protobuf.IFeatureSet|null); + + /** ExtensionRangeOptions verification. */ + public verification: google.protobuf.ExtensionRangeOptions.VerificationState; + + /** + * Creates an ExtensionRangeOptions message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns ExtensionRangeOptions + */ + public static fromObject(object: { [k: string]: any }): google.protobuf.ExtensionRangeOptions; + + /** + * Creates a plain object from an ExtensionRangeOptions message. Also converts values to other types if specified. + * @param message ExtensionRangeOptions + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.protobuf.ExtensionRangeOptions, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this ExtensionRangeOptions to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for ExtensionRangeOptions + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + namespace ExtensionRangeOptions { + + /** Properties of a Declaration. */ + interface IDeclaration { + + /** Declaration number */ + number?: (number|null); + + /** Declaration fullName */ + fullName?: (string|null); + + /** Declaration type */ + type?: (string|null); + + /** Declaration reserved */ + reserved?: (boolean|null); + + /** Declaration repeated */ + repeated?: (boolean|null); } - /** Represents a ListCollectionIdsResponse. */ - class ListCollectionIdsResponse implements IListCollectionIdsResponse { + /** Represents a Declaration. */ + class Declaration implements IDeclaration { /** - * Constructs a new ListCollectionIdsResponse. + * Constructs a new Declaration. * @param [properties] Properties to set */ - constructor(properties?: google.firestore.v1.IListCollectionIdsResponse); + constructor(properties?: google.protobuf.ExtensionRangeOptions.IDeclaration); - /** ListCollectionIdsResponse collectionIds. */ - public collectionIds: string[]; + /** Declaration number. */ + public number: number; - /** ListCollectionIdsResponse nextPageToken. */ - public nextPageToken: string; + /** Declaration fullName. */ + public fullName: string; + + /** Declaration type. */ + public type: string; + + /** Declaration reserved. */ + public reserved: boolean; + + /** Declaration repeated. */ + public repeated: boolean; /** - * Creates a ListCollectionIdsResponse message from a plain object. Also converts values to their respective internal types. + * Creates a Declaration message from a plain object. Also converts values to their respective internal types. * @param object Plain object - * @returns ListCollectionIdsResponse + * @returns Declaration */ - public static fromObject(object: { [k: string]: any }): google.firestore.v1.ListCollectionIdsResponse; + public static fromObject(object: { [k: string]: any }): google.protobuf.ExtensionRangeOptions.Declaration; /** - * Creates a plain object from a ListCollectionIdsResponse message. Also converts values to other types if specified. - * @param message ListCollectionIdsResponse + * Creates a plain object from a Declaration message. Also converts values to other types if specified. + * @param message Declaration * @param [options] Conversion options * @returns Plain object */ - public static toObject(message: google.firestore.v1.ListCollectionIdsResponse, options?: $protobuf.IConversionOptions): { [k: string]: any }; + public static toObject(message: google.protobuf.ExtensionRangeOptions.Declaration, options?: $protobuf.IConversionOptions): { [k: string]: any }; /** - * Converts this ListCollectionIdsResponse to JSON. + * Converts this Declaration to JSON. * @returns JSON object */ public toJSON(): { [k: string]: any }; /** - * Gets the default type url for ListCollectionIdsResponse + * Gets the default type url for Declaration * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") * @returns The default type url */ public static getTypeUrl(typeUrlPrefix?: string): string; } - /** Properties of a BatchWriteRequest. */ - interface IBatchWriteRequest { + /** VerificationState enum. */ + type VerificationState = + "DECLARATION"| "UNVERIFIED"; + } - /** BatchWriteRequest database */ - database?: (string|null); + /** Properties of a FieldDescriptorProto. */ + interface IFieldDescriptorProto { - /** BatchWriteRequest writes */ - writes?: (google.firestore.v1.IWrite[]|null); + /** FieldDescriptorProto name */ + name?: (string|null); - /** BatchWriteRequest labels */ - labels?: ({ [k: string]: string }|null); - } + /** FieldDescriptorProto number */ + number?: (number|null); - /** Represents a BatchWriteRequest. */ - class BatchWriteRequest implements IBatchWriteRequest { + /** FieldDescriptorProto label */ + label?: (google.protobuf.FieldDescriptorProto.Label|null); - /** - * Constructs a new BatchWriteRequest. - * @param [properties] Properties to set - */ - constructor(properties?: google.firestore.v1.IBatchWriteRequest); + /** FieldDescriptorProto type */ + type?: (google.protobuf.FieldDescriptorProto.Type|null); - /** BatchWriteRequest database. */ - public database: string; + /** FieldDescriptorProto typeName */ + typeName?: (string|null); - /** BatchWriteRequest writes. */ - public writes: google.firestore.v1.IWrite[]; + /** FieldDescriptorProto extendee */ + extendee?: (string|null); - /** BatchWriteRequest labels. */ - public labels: { [k: string]: string }; + /** FieldDescriptorProto defaultValue */ + defaultValue?: (string|null); - /** - * Creates a BatchWriteRequest message from a plain object. Also converts values to their respective internal types. - * @param object Plain object - * @returns BatchWriteRequest - */ - public static fromObject(object: { [k: string]: any }): google.firestore.v1.BatchWriteRequest; + /** FieldDescriptorProto oneofIndex */ + oneofIndex?: (number|null); - /** - * Creates a plain object from a BatchWriteRequest message. Also converts values to other types if specified. - * @param message BatchWriteRequest - * @param [options] Conversion options - * @returns Plain object - */ - public static toObject(message: google.firestore.v1.BatchWriteRequest, options?: $protobuf.IConversionOptions): { [k: string]: any }; + /** FieldDescriptorProto jsonName */ + jsonName?: (string|null); - /** - * Converts this BatchWriteRequest to JSON. - * @returns JSON object - */ - public toJSON(): { [k: string]: any }; + /** FieldDescriptorProto options */ + options?: (google.protobuf.IFieldOptions|null); + + /** FieldDescriptorProto proto3Optional */ + proto3Optional?: (boolean|null); + } + + /** Represents a FieldDescriptorProto. */ + class FieldDescriptorProto implements IFieldDescriptorProto { + + /** + * Constructs a new FieldDescriptorProto. + * @param [properties] Properties to set + */ + constructor(properties?: google.protobuf.IFieldDescriptorProto); + + /** FieldDescriptorProto name. */ + public name: string; + + /** FieldDescriptorProto number. */ + public number: number; + + /** FieldDescriptorProto label. */ + public label: google.protobuf.FieldDescriptorProto.Label; + + /** FieldDescriptorProto type. */ + public type: google.protobuf.FieldDescriptorProto.Type; + + /** FieldDescriptorProto typeName. */ + public typeName: string; + + /** FieldDescriptorProto extendee. */ + public extendee: string; + + /** FieldDescriptorProto defaultValue. */ + public defaultValue: string; + + /** FieldDescriptorProto oneofIndex. */ + public oneofIndex: number; + + /** FieldDescriptorProto jsonName. */ + public jsonName: string; - /** - * Gets the default type url for BatchWriteRequest - * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") - * @returns The default type url - */ - public static getTypeUrl(typeUrlPrefix?: string): string; - } + /** FieldDescriptorProto options. */ + public options?: (google.protobuf.IFieldOptions|null); - /** Properties of a BatchWriteResponse. */ - interface IBatchWriteResponse { + /** FieldDescriptorProto proto3Optional. */ + public proto3Optional: boolean; - /** BatchWriteResponse writeResults */ - writeResults?: (google.firestore.v1.IWriteResult[]|null); + /** + * Creates a FieldDescriptorProto message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns FieldDescriptorProto + */ + public static fromObject(object: { [k: string]: any }): google.protobuf.FieldDescriptorProto; - /** BatchWriteResponse status */ - status?: (google.rpc.IStatus[]|null); - } + /** + * Creates a plain object from a FieldDescriptorProto message. Also converts values to other types if specified. + * @param message FieldDescriptorProto + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.protobuf.FieldDescriptorProto, options?: $protobuf.IConversionOptions): { [k: string]: any }; - /** Represents a BatchWriteResponse. */ - class BatchWriteResponse implements IBatchWriteResponse { + /** + * Converts this FieldDescriptorProto to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; - /** - * Constructs a new BatchWriteResponse. - * @param [properties] Properties to set - */ - constructor(properties?: google.firestore.v1.IBatchWriteResponse); + /** + * Gets the default type url for FieldDescriptorProto + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } - /** BatchWriteResponse writeResults. */ - public writeResults: google.firestore.v1.IWriteResult[]; + namespace FieldDescriptorProto { - /** BatchWriteResponse status. */ - public status: google.rpc.IStatus[]; + /** Type enum. */ + type Type = + "TYPE_DOUBLE"| "TYPE_FLOAT"| "TYPE_INT64"| "TYPE_UINT64"| "TYPE_INT32"| "TYPE_FIXED64"| "TYPE_FIXED32"| "TYPE_BOOL"| "TYPE_STRING"| "TYPE_GROUP"| "TYPE_MESSAGE"| "TYPE_BYTES"| "TYPE_UINT32"| "TYPE_ENUM"| "TYPE_SFIXED32"| "TYPE_SFIXED64"| "TYPE_SINT32"| "TYPE_SINT64"; - /** - * Creates a BatchWriteResponse message from a plain object. Also converts values to their respective internal types. - * @param object Plain object - * @returns BatchWriteResponse - */ - public static fromObject(object: { [k: string]: any }): google.firestore.v1.BatchWriteResponse; + /** Label enum. */ + type Label = + "LABEL_OPTIONAL"| "LABEL_REPEATED"| "LABEL_REQUIRED"; + } - /** - * Creates a plain object from a BatchWriteResponse message. Also converts values to other types if specified. - * @param message BatchWriteResponse - * @param [options] Conversion options - * @returns Plain object - */ - public static toObject(message: google.firestore.v1.BatchWriteResponse, options?: $protobuf.IConversionOptions): { [k: string]: any }; + /** Properties of an OneofDescriptorProto. */ + interface IOneofDescriptorProto { - /** - * Converts this BatchWriteResponse to JSON. - * @returns JSON object - */ - public toJSON(): { [k: string]: any }; + /** OneofDescriptorProto name */ + name?: (string|null); - /** - * Gets the default type url for BatchWriteResponse - * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") - * @returns The default type url - */ - public static getTypeUrl(typeUrlPrefix?: string): string; - } + /** OneofDescriptorProto options */ + options?: (google.protobuf.IOneofOptions|null); + } - /** Properties of a StructuredPipeline. */ - interface IStructuredPipeline { + /** Represents an OneofDescriptorProto. */ + class OneofDescriptorProto implements IOneofDescriptorProto { - /** StructuredPipeline pipeline */ - pipeline?: (google.firestore.v1.IPipeline|null); + /** + * Constructs a new OneofDescriptorProto. + * @param [properties] Properties to set + */ + constructor(properties?: google.protobuf.IOneofDescriptorProto); - /** StructuredPipeline options */ - options?: ({ [k: string]: google.firestore.v1.IValue }|null); - } + /** OneofDescriptorProto name. */ + public name: string; - /** Represents a StructuredPipeline. */ - class StructuredPipeline implements IStructuredPipeline { + /** OneofDescriptorProto options. */ + public options?: (google.protobuf.IOneofOptions|null); - /** - * Constructs a new StructuredPipeline. - * @param [properties] Properties to set - */ - constructor(properties?: google.firestore.v1.IStructuredPipeline); + /** + * Creates an OneofDescriptorProto message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns OneofDescriptorProto + */ + public static fromObject(object: { [k: string]: any }): google.protobuf.OneofDescriptorProto; - /** StructuredPipeline pipeline. */ - public pipeline?: (google.firestore.v1.IPipeline|null); + /** + * Creates a plain object from an OneofDescriptorProto message. Also converts values to other types if specified. + * @param message OneofDescriptorProto + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.protobuf.OneofDescriptorProto, options?: $protobuf.IConversionOptions): { [k: string]: any }; - /** StructuredPipeline options. */ - public options: { [k: string]: google.firestore.v1.IValue }; + /** + * Converts this OneofDescriptorProto to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; - /** - * Creates a StructuredPipeline message from a plain object. Also converts values to their respective internal types. - * @param object Plain object - * @returns StructuredPipeline - */ - public static fromObject(object: { [k: string]: any }): google.firestore.v1.StructuredPipeline; + /** + * Gets the default type url for OneofDescriptorProto + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } - /** - * Creates a plain object from a StructuredPipeline message. Also converts values to other types if specified. - * @param message StructuredPipeline - * @param [options] Conversion options - * @returns Plain object - */ - public static toObject(message: google.firestore.v1.StructuredPipeline, options?: $protobuf.IConversionOptions): { [k: string]: any }; + /** Properties of an EnumDescriptorProto. */ + interface IEnumDescriptorProto { - /** - * Converts this StructuredPipeline to JSON. - * @returns JSON object - */ - public toJSON(): { [k: string]: any }; + /** EnumDescriptorProto name */ + name?: (string|null); - /** - * Gets the default type url for StructuredPipeline - * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") - * @returns The default type url - */ - public static getTypeUrl(typeUrlPrefix?: string): string; - } + /** EnumDescriptorProto value */ + value?: (google.protobuf.IEnumValueDescriptorProto[]|null); - /** Properties of a StructuredQuery. */ - interface IStructuredQuery { + /** EnumDescriptorProto options */ + options?: (google.protobuf.IEnumOptions|null); - /** StructuredQuery select */ - select?: (google.firestore.v1.StructuredQuery.IProjection|null); + /** EnumDescriptorProto reservedRange */ + reservedRange?: (google.protobuf.EnumDescriptorProto.IEnumReservedRange[]|null); - /** StructuredQuery from */ - from?: (google.firestore.v1.StructuredQuery.ICollectionSelector[]|null); + /** EnumDescriptorProto reservedName */ + reservedName?: (string[]|null); + } - /** StructuredQuery where */ - where?: (google.firestore.v1.StructuredQuery.IFilter|null); + /** Represents an EnumDescriptorProto. */ + class EnumDescriptorProto implements IEnumDescriptorProto { - /** StructuredQuery orderBy */ - orderBy?: (google.firestore.v1.StructuredQuery.IOrder[]|null); + /** + * Constructs a new EnumDescriptorProto. + * @param [properties] Properties to set + */ + constructor(properties?: google.protobuf.IEnumDescriptorProto); - /** StructuredQuery startAt */ - startAt?: (google.firestore.v1.ICursor|null); + /** EnumDescriptorProto name. */ + public name: string; - /** StructuredQuery endAt */ - endAt?: (google.firestore.v1.ICursor|null); + /** EnumDescriptorProto value. */ + public value: google.protobuf.IEnumValueDescriptorProto[]; - /** StructuredQuery offset */ - offset?: (number|null); + /** EnumDescriptorProto options. */ + public options?: (google.protobuf.IEnumOptions|null); - /** StructuredQuery limit */ - limit?: (google.protobuf.IInt32Value|null); + /** EnumDescriptorProto reservedRange. */ + public reservedRange: google.protobuf.EnumDescriptorProto.IEnumReservedRange[]; - /** StructuredQuery findNearest */ - findNearest?: (google.firestore.v1.StructuredQuery.IFindNearest|null); - } + /** EnumDescriptorProto reservedName. */ + public reservedName: string[]; - /** Represents a StructuredQuery. */ - class StructuredQuery implements IStructuredQuery { + /** + * Creates an EnumDescriptorProto message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns EnumDescriptorProto + */ + public static fromObject(object: { [k: string]: any }): google.protobuf.EnumDescriptorProto; - /** - * Constructs a new StructuredQuery. - * @param [properties] Properties to set - */ - constructor(properties?: google.firestore.v1.IStructuredQuery); + /** + * Creates a plain object from an EnumDescriptorProto message. Also converts values to other types if specified. + * @param message EnumDescriptorProto + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.protobuf.EnumDescriptorProto, options?: $protobuf.IConversionOptions): { [k: string]: any }; - /** StructuredQuery select. */ - public select?: (google.firestore.v1.StructuredQuery.IProjection|null); + /** + * Converts this EnumDescriptorProto to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for EnumDescriptorProto + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } - /** StructuredQuery from. */ - public from: google.firestore.v1.StructuredQuery.ICollectionSelector[]; + namespace EnumDescriptorProto { - /** StructuredQuery where. */ - public where?: (google.firestore.v1.StructuredQuery.IFilter|null); + /** Properties of an EnumReservedRange. */ + interface IEnumReservedRange { - /** StructuredQuery orderBy. */ - public orderBy: google.firestore.v1.StructuredQuery.IOrder[]; + /** EnumReservedRange start */ + start?: (number|null); - /** StructuredQuery startAt. */ - public startAt?: (google.firestore.v1.ICursor|null); + /** EnumReservedRange end */ + end?: (number|null); + } - /** StructuredQuery endAt. */ - public endAt?: (google.firestore.v1.ICursor|null); + /** Represents an EnumReservedRange. */ + class EnumReservedRange implements IEnumReservedRange { - /** StructuredQuery offset. */ - public offset: number; + /** + * Constructs a new EnumReservedRange. + * @param [properties] Properties to set + */ + constructor(properties?: google.protobuf.EnumDescriptorProto.IEnumReservedRange); - /** StructuredQuery limit. */ - public limit?: (google.protobuf.IInt32Value|null); + /** EnumReservedRange start. */ + public start: number; - /** StructuredQuery findNearest. */ - public findNearest?: (google.firestore.v1.StructuredQuery.IFindNearest|null); + /** EnumReservedRange end. */ + public end: number; /** - * Creates a StructuredQuery message from a plain object. Also converts values to their respective internal types. + * Creates an EnumReservedRange message from a plain object. Also converts values to their respective internal types. * @param object Plain object - * @returns StructuredQuery + * @returns EnumReservedRange */ - public static fromObject(object: { [k: string]: any }): google.firestore.v1.StructuredQuery; + public static fromObject(object: { [k: string]: any }): google.protobuf.EnumDescriptorProto.EnumReservedRange; /** - * Creates a plain object from a StructuredQuery message. Also converts values to other types if specified. - * @param message StructuredQuery + * Creates a plain object from an EnumReservedRange message. Also converts values to other types if specified. + * @param message EnumReservedRange * @param [options] Conversion options * @returns Plain object */ - public static toObject(message: google.firestore.v1.StructuredQuery, options?: $protobuf.IConversionOptions): { [k: string]: any }; + public static toObject(message: google.protobuf.EnumDescriptorProto.EnumReservedRange, options?: $protobuf.IConversionOptions): { [k: string]: any }; /** - * Converts this StructuredQuery to JSON. + * Converts this EnumReservedRange to JSON. * @returns JSON object */ public toJSON(): { [k: string]: any }; /** - * Gets the default type url for StructuredQuery + * Gets the default type url for EnumReservedRange * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") * @returns The default type url */ public static getTypeUrl(typeUrlPrefix?: string): string; } + } - namespace StructuredQuery { + /** Properties of an EnumValueDescriptorProto. */ + interface IEnumValueDescriptorProto { - /** Properties of a CollectionSelector. */ - interface ICollectionSelector { + /** EnumValueDescriptorProto name */ + name?: (string|null); - /** CollectionSelector collectionId */ - collectionId?: (string|null); + /** EnumValueDescriptorProto number */ + number?: (number|null); - /** CollectionSelector allDescendants */ - allDescendants?: (boolean|null); - } + /** EnumValueDescriptorProto options */ + options?: (google.protobuf.IEnumValueOptions|null); + } - /** Represents a CollectionSelector. */ - class CollectionSelector implements ICollectionSelector { + /** Represents an EnumValueDescriptorProto. */ + class EnumValueDescriptorProto implements IEnumValueDescriptorProto { - /** - * Constructs a new CollectionSelector. - * @param [properties] Properties to set - */ - constructor(properties?: google.firestore.v1.StructuredQuery.ICollectionSelector); + /** + * Constructs a new EnumValueDescriptorProto. + * @param [properties] Properties to set + */ + constructor(properties?: google.protobuf.IEnumValueDescriptorProto); - /** CollectionSelector collectionId. */ - public collectionId: string; + /** EnumValueDescriptorProto name. */ + public name: string; - /** CollectionSelector allDescendants. */ - public allDescendants: boolean; + /** EnumValueDescriptorProto number. */ + public number: number; - /** - * Creates a CollectionSelector message from a plain object. Also converts values to their respective internal types. - * @param object Plain object - * @returns CollectionSelector - */ - public static fromObject(object: { [k: string]: any }): google.firestore.v1.StructuredQuery.CollectionSelector; + /** EnumValueDescriptorProto options. */ + public options?: (google.protobuf.IEnumValueOptions|null); - /** - * Creates a plain object from a CollectionSelector message. Also converts values to other types if specified. - * @param message CollectionSelector - * @param [options] Conversion options - * @returns Plain object - */ - public static toObject(message: google.firestore.v1.StructuredQuery.CollectionSelector, options?: $protobuf.IConversionOptions): { [k: string]: any }; + /** + * Creates an EnumValueDescriptorProto message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns EnumValueDescriptorProto + */ + public static fromObject(object: { [k: string]: any }): google.protobuf.EnumValueDescriptorProto; - /** - * Converts this CollectionSelector to JSON. - * @returns JSON object - */ - public toJSON(): { [k: string]: any }; + /** + * Creates a plain object from an EnumValueDescriptorProto message. Also converts values to other types if specified. + * @param message EnumValueDescriptorProto + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.protobuf.EnumValueDescriptorProto, options?: $protobuf.IConversionOptions): { [k: string]: any }; - /** - * Gets the default type url for CollectionSelector - * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") - * @returns The default type url - */ - public static getTypeUrl(typeUrlPrefix?: string): string; - } + /** + * Converts this EnumValueDescriptorProto to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; - /** Properties of a Filter. */ - interface IFilter { + /** + * Gets the default type url for EnumValueDescriptorProto + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } - /** Filter compositeFilter */ - compositeFilter?: (google.firestore.v1.StructuredQuery.ICompositeFilter|null); + /** Properties of a ServiceDescriptorProto. */ + interface IServiceDescriptorProto { - /** Filter fieldFilter */ - fieldFilter?: (google.firestore.v1.StructuredQuery.IFieldFilter|null); + /** ServiceDescriptorProto name */ + name?: (string|null); - /** Filter unaryFilter */ - unaryFilter?: (google.firestore.v1.StructuredQuery.IUnaryFilter|null); - } + /** ServiceDescriptorProto method */ + method?: (google.protobuf.IMethodDescriptorProto[]|null); - /** Represents a Filter. */ - class Filter implements IFilter { + /** ServiceDescriptorProto options */ + options?: (google.protobuf.IServiceOptions|null); + } - /** - * Constructs a new Filter. - * @param [properties] Properties to set - */ - constructor(properties?: google.firestore.v1.StructuredQuery.IFilter); + /** Represents a ServiceDescriptorProto. */ + class ServiceDescriptorProto implements IServiceDescriptorProto { + + /** + * Constructs a new ServiceDescriptorProto. + * @param [properties] Properties to set + */ + constructor(properties?: google.protobuf.IServiceDescriptorProto); + + /** ServiceDescriptorProto name. */ + public name: string; + + /** ServiceDescriptorProto method. */ + public method: google.protobuf.IMethodDescriptorProto[]; + + /** ServiceDescriptorProto options. */ + public options?: (google.protobuf.IServiceOptions|null); + + /** + * Creates a ServiceDescriptorProto message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns ServiceDescriptorProto + */ + public static fromObject(object: { [k: string]: any }): google.protobuf.ServiceDescriptorProto; + + /** + * Creates a plain object from a ServiceDescriptorProto message. Also converts values to other types if specified. + * @param message ServiceDescriptorProto + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.protobuf.ServiceDescriptorProto, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this ServiceDescriptorProto to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for ServiceDescriptorProto + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a MethodDescriptorProto. */ + interface IMethodDescriptorProto { + + /** MethodDescriptorProto name */ + name?: (string|null); + + /** MethodDescriptorProto inputType */ + inputType?: (string|null); + + /** MethodDescriptorProto outputType */ + outputType?: (string|null); + + /** MethodDescriptorProto options */ + options?: (google.protobuf.IMethodOptions|null); + + /** MethodDescriptorProto clientStreaming */ + clientStreaming?: (boolean|null); + + /** MethodDescriptorProto serverStreaming */ + serverStreaming?: (boolean|null); + } + + /** Represents a MethodDescriptorProto. */ + class MethodDescriptorProto implements IMethodDescriptorProto { + + /** + * Constructs a new MethodDescriptorProto. + * @param [properties] Properties to set + */ + constructor(properties?: google.protobuf.IMethodDescriptorProto); + + /** MethodDescriptorProto name. */ + public name: string; + + /** MethodDescriptorProto inputType. */ + public inputType: string; - /** Filter compositeFilter. */ - public compositeFilter?: (google.firestore.v1.StructuredQuery.ICompositeFilter|null); + /** MethodDescriptorProto outputType. */ + public outputType: string; - /** Filter fieldFilter. */ - public fieldFilter?: (google.firestore.v1.StructuredQuery.IFieldFilter|null); + /** MethodDescriptorProto options. */ + public options?: (google.protobuf.IMethodOptions|null); - /** Filter unaryFilter. */ - public unaryFilter?: (google.firestore.v1.StructuredQuery.IUnaryFilter|null); + /** MethodDescriptorProto clientStreaming. */ + public clientStreaming: boolean; - /** Filter filterType. */ - public filterType?: ("compositeFilter"|"fieldFilter"|"unaryFilter"); + /** MethodDescriptorProto serverStreaming. */ + public serverStreaming: boolean; - /** - * Creates a Filter message from a plain object. Also converts values to their respective internal types. - * @param object Plain object - * @returns Filter - */ - public static fromObject(object: { [k: string]: any }): google.firestore.v1.StructuredQuery.Filter; + /** + * Creates a MethodDescriptorProto message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns MethodDescriptorProto + */ + public static fromObject(object: { [k: string]: any }): google.protobuf.MethodDescriptorProto; - /** - * Creates a plain object from a Filter message. Also converts values to other types if specified. - * @param message Filter - * @param [options] Conversion options - * @returns Plain object - */ - public static toObject(message: google.firestore.v1.StructuredQuery.Filter, options?: $protobuf.IConversionOptions): { [k: string]: any }; + /** + * Creates a plain object from a MethodDescriptorProto message. Also converts values to other types if specified. + * @param message MethodDescriptorProto + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.protobuf.MethodDescriptorProto, options?: $protobuf.IConversionOptions): { [k: string]: any }; - /** - * Converts this Filter to JSON. - * @returns JSON object - */ - public toJSON(): { [k: string]: any }; + /** + * Converts this MethodDescriptorProto to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; - /** - * Gets the default type url for Filter - * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") - * @returns The default type url - */ - public static getTypeUrl(typeUrlPrefix?: string): string; - } + /** + * Gets the default type url for MethodDescriptorProto + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } - /** Properties of a CompositeFilter. */ - interface ICompositeFilter { + /** Properties of a FileOptions. */ + interface IFileOptions { - /** CompositeFilter op */ - op?: (google.firestore.v1.StructuredQuery.CompositeFilter.Operator|null); + /** FileOptions javaPackage */ + javaPackage?: (string|null); - /** CompositeFilter filters */ - filters?: (google.firestore.v1.StructuredQuery.IFilter[]|null); - } + /** FileOptions javaOuterClassname */ + javaOuterClassname?: (string|null); - /** Represents a CompositeFilter. */ - class CompositeFilter implements ICompositeFilter { + /** FileOptions javaMultipleFiles */ + javaMultipleFiles?: (boolean|null); - /** - * Constructs a new CompositeFilter. - * @param [properties] Properties to set - */ - constructor(properties?: google.firestore.v1.StructuredQuery.ICompositeFilter); + /** FileOptions javaGenerateEqualsAndHash */ + javaGenerateEqualsAndHash?: (boolean|null); - /** CompositeFilter op. */ - public op: google.firestore.v1.StructuredQuery.CompositeFilter.Operator; + /** FileOptions javaStringCheckUtf8 */ + javaStringCheckUtf8?: (boolean|null); - /** CompositeFilter filters. */ - public filters: google.firestore.v1.StructuredQuery.IFilter[]; + /** FileOptions optimizeFor */ + optimizeFor?: (google.protobuf.FileOptions.OptimizeMode|null); - /** - * Creates a CompositeFilter message from a plain object. Also converts values to their respective internal types. - * @param object Plain object - * @returns CompositeFilter - */ - public static fromObject(object: { [k: string]: any }): google.firestore.v1.StructuredQuery.CompositeFilter; + /** FileOptions goPackage */ + goPackage?: (string|null); - /** - * Creates a plain object from a CompositeFilter message. Also converts values to other types if specified. - * @param message CompositeFilter - * @param [options] Conversion options - * @returns Plain object - */ - public static toObject(message: google.firestore.v1.StructuredQuery.CompositeFilter, options?: $protobuf.IConversionOptions): { [k: string]: any }; + /** FileOptions ccGenericServices */ + ccGenericServices?: (boolean|null); - /** - * Converts this CompositeFilter to JSON. - * @returns JSON object - */ - public toJSON(): { [k: string]: any }; + /** FileOptions javaGenericServices */ + javaGenericServices?: (boolean|null); - /** - * Gets the default type url for CompositeFilter - * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") - * @returns The default type url - */ - public static getTypeUrl(typeUrlPrefix?: string): string; - } + /** FileOptions pyGenericServices */ + pyGenericServices?: (boolean|null); - namespace CompositeFilter { + /** FileOptions deprecated */ + deprecated?: (boolean|null); - /** Operator enum. */ - type Operator = - "OPERATOR_UNSPECIFIED"| "AND"| "OR"; - } + /** FileOptions ccEnableArenas */ + ccEnableArenas?: (boolean|null); - /** Properties of a FieldFilter. */ - interface IFieldFilter { + /** FileOptions objcClassPrefix */ + objcClassPrefix?: (string|null); - /** FieldFilter field */ - field?: (google.firestore.v1.StructuredQuery.IFieldReference|null); + /** FileOptions csharpNamespace */ + csharpNamespace?: (string|null); - /** FieldFilter op */ - op?: (google.firestore.v1.StructuredQuery.FieldFilter.Operator|null); + /** FileOptions swiftPrefix */ + swiftPrefix?: (string|null); - /** FieldFilter value */ - value?: (google.firestore.v1.IValue|null); - } + /** FileOptions phpClassPrefix */ + phpClassPrefix?: (string|null); - /** Represents a FieldFilter. */ - class FieldFilter implements IFieldFilter { + /** FileOptions phpNamespace */ + phpNamespace?: (string|null); - /** - * Constructs a new FieldFilter. - * @param [properties] Properties to set - */ - constructor(properties?: google.firestore.v1.StructuredQuery.IFieldFilter); + /** FileOptions phpMetadataNamespace */ + phpMetadataNamespace?: (string|null); - /** FieldFilter field. */ - public field?: (google.firestore.v1.StructuredQuery.IFieldReference|null); + /** FileOptions rubyPackage */ + rubyPackage?: (string|null); - /** FieldFilter op. */ - public op: google.firestore.v1.StructuredQuery.FieldFilter.Operator; + /** FileOptions features */ + features?: (google.protobuf.IFeatureSet|null); - /** FieldFilter value. */ - public value?: (google.firestore.v1.IValue|null); + /** FileOptions uninterpretedOption */ + uninterpretedOption?: (google.protobuf.IUninterpretedOption[]|null); - /** - * Creates a FieldFilter message from a plain object. Also converts values to their respective internal types. - * @param object Plain object - * @returns FieldFilter - */ - public static fromObject(object: { [k: string]: any }): google.firestore.v1.StructuredQuery.FieldFilter; + /** FileOptions .google.api.resourceDefinition */ + ".google.api.resourceDefinition"?: (google.api.IResourceDescriptor[]|null); + } - /** - * Creates a plain object from a FieldFilter message. Also converts values to other types if specified. - * @param message FieldFilter - * @param [options] Conversion options - * @returns Plain object - */ - public static toObject(message: google.firestore.v1.StructuredQuery.FieldFilter, options?: $protobuf.IConversionOptions): { [k: string]: any }; + /** Represents a FileOptions. */ + class FileOptions implements IFileOptions { - /** - * Converts this FieldFilter to JSON. - * @returns JSON object - */ - public toJSON(): { [k: string]: any }; + /** + * Constructs a new FileOptions. + * @param [properties] Properties to set + */ + constructor(properties?: google.protobuf.IFileOptions); - /** - * Gets the default type url for FieldFilter - * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") - * @returns The default type url - */ - public static getTypeUrl(typeUrlPrefix?: string): string; - } + /** FileOptions javaPackage. */ + public javaPackage: string; - namespace FieldFilter { + /** FileOptions javaOuterClassname. */ + public javaOuterClassname: string; - /** Operator enum. */ - type Operator = - "OPERATOR_UNSPECIFIED"| "LESS_THAN"| "LESS_THAN_OR_EQUAL"| "GREATER_THAN"| "GREATER_THAN_OR_EQUAL"| "EQUAL"| "NOT_EQUAL"| "ARRAY_CONTAINS"| "IN"| "ARRAY_CONTAINS_ANY"| "NOT_IN"; - } + /** FileOptions javaMultipleFiles. */ + public javaMultipleFiles: boolean; - /** Properties of an UnaryFilter. */ - interface IUnaryFilter { + /** FileOptions javaGenerateEqualsAndHash. */ + public javaGenerateEqualsAndHash: boolean; - /** UnaryFilter op */ - op?: (google.firestore.v1.StructuredQuery.UnaryFilter.Operator|null); + /** FileOptions javaStringCheckUtf8. */ + public javaStringCheckUtf8: boolean; - /** UnaryFilter field */ - field?: (google.firestore.v1.StructuredQuery.IFieldReference|null); - } + /** FileOptions optimizeFor. */ + public optimizeFor: google.protobuf.FileOptions.OptimizeMode; - /** Represents an UnaryFilter. */ - class UnaryFilter implements IUnaryFilter { + /** FileOptions goPackage. */ + public goPackage: string; - /** - * Constructs a new UnaryFilter. - * @param [properties] Properties to set - */ - constructor(properties?: google.firestore.v1.StructuredQuery.IUnaryFilter); + /** FileOptions ccGenericServices. */ + public ccGenericServices: boolean; - /** UnaryFilter op. */ - public op: google.firestore.v1.StructuredQuery.UnaryFilter.Operator; + /** FileOptions javaGenericServices. */ + public javaGenericServices: boolean; + + /** FileOptions pyGenericServices. */ + public pyGenericServices: boolean; - /** UnaryFilter field. */ - public field?: (google.firestore.v1.StructuredQuery.IFieldReference|null); + /** FileOptions deprecated. */ + public deprecated: boolean; - /** UnaryFilter operandType. */ - public operandType?: "field"; + /** FileOptions ccEnableArenas. */ + public ccEnableArenas: boolean; - /** - * Creates an UnaryFilter message from a plain object. Also converts values to their respective internal types. - * @param object Plain object - * @returns UnaryFilter - */ - public static fromObject(object: { [k: string]: any }): google.firestore.v1.StructuredQuery.UnaryFilter; + /** FileOptions objcClassPrefix. */ + public objcClassPrefix: string; - /** - * Creates a plain object from an UnaryFilter message. Also converts values to other types if specified. - * @param message UnaryFilter - * @param [options] Conversion options - * @returns Plain object - */ - public static toObject(message: google.firestore.v1.StructuredQuery.UnaryFilter, options?: $protobuf.IConversionOptions): { [k: string]: any }; + /** FileOptions csharpNamespace. */ + public csharpNamespace: string; - /** - * Converts this UnaryFilter to JSON. - * @returns JSON object - */ - public toJSON(): { [k: string]: any }; + /** FileOptions swiftPrefix. */ + public swiftPrefix: string; - /** - * Gets the default type url for UnaryFilter - * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") - * @returns The default type url - */ - public static getTypeUrl(typeUrlPrefix?: string): string; - } + /** FileOptions phpClassPrefix. */ + public phpClassPrefix: string; - namespace UnaryFilter { + /** FileOptions phpNamespace. */ + public phpNamespace: string; - /** Operator enum. */ - type Operator = - "OPERATOR_UNSPECIFIED"| "IS_NAN"| "IS_NULL"| "IS_NOT_NAN"| "IS_NOT_NULL"; - } + /** FileOptions phpMetadataNamespace. */ + public phpMetadataNamespace: string; - /** Properties of an Order. */ - interface IOrder { + /** FileOptions rubyPackage. */ + public rubyPackage: string; - /** Order field */ - field?: (google.firestore.v1.StructuredQuery.IFieldReference|null); + /** FileOptions features. */ + public features?: (google.protobuf.IFeatureSet|null); - /** Order direction */ - direction?: (google.firestore.v1.StructuredQuery.Direction|null); - } + /** FileOptions uninterpretedOption. */ + public uninterpretedOption: google.protobuf.IUninterpretedOption[]; - /** Represents an Order. */ - class Order implements IOrder { + /** + * Creates a FileOptions message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns FileOptions + */ + public static fromObject(object: { [k: string]: any }): google.protobuf.FileOptions; - /** - * Constructs a new Order. - * @param [properties] Properties to set - */ - constructor(properties?: google.firestore.v1.StructuredQuery.IOrder); + /** + * Creates a plain object from a FileOptions message. Also converts values to other types if specified. + * @param message FileOptions + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.protobuf.FileOptions, options?: $protobuf.IConversionOptions): { [k: string]: any }; - /** Order field. */ - public field?: (google.firestore.v1.StructuredQuery.IFieldReference|null); + /** + * Converts this FileOptions to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; - /** Order direction. */ - public direction: google.firestore.v1.StructuredQuery.Direction; + /** + * Gets the default type url for FileOptions + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } - /** - * Creates an Order message from a plain object. Also converts values to their respective internal types. - * @param object Plain object - * @returns Order - */ - public static fromObject(object: { [k: string]: any }): google.firestore.v1.StructuredQuery.Order; + namespace FileOptions { - /** - * Creates a plain object from an Order message. Also converts values to other types if specified. - * @param message Order - * @param [options] Conversion options - * @returns Plain object - */ - public static toObject(message: google.firestore.v1.StructuredQuery.Order, options?: $protobuf.IConversionOptions): { [k: string]: any }; + /** OptimizeMode enum. */ + type OptimizeMode = + "SPEED"| "CODE_SIZE"| "LITE_RUNTIME"; + } - /** - * Converts this Order to JSON. - * @returns JSON object - */ - public toJSON(): { [k: string]: any }; + /** Properties of a MessageOptions. */ + interface IMessageOptions { - /** - * Gets the default type url for Order - * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") - * @returns The default type url - */ - public static getTypeUrl(typeUrlPrefix?: string): string; - } + /** MessageOptions messageSetWireFormat */ + messageSetWireFormat?: (boolean|null); - /** Direction enum. */ - type Direction = - "DIRECTION_UNSPECIFIED"| "ASCENDING"| "DESCENDING"; + /** MessageOptions noStandardDescriptorAccessor */ + noStandardDescriptorAccessor?: (boolean|null); - /** Properties of a FieldReference. */ - interface IFieldReference { + /** MessageOptions deprecated */ + deprecated?: (boolean|null); - /** FieldReference fieldPath */ - fieldPath?: (string|null); - } + /** MessageOptions mapEntry */ + mapEntry?: (boolean|null); - /** Represents a FieldReference. */ - class FieldReference implements IFieldReference { + /** MessageOptions deprecatedLegacyJsonFieldConflicts */ + deprecatedLegacyJsonFieldConflicts?: (boolean|null); - /** - * Constructs a new FieldReference. - * @param [properties] Properties to set - */ - constructor(properties?: google.firestore.v1.StructuredQuery.IFieldReference); + /** MessageOptions features */ + features?: (google.protobuf.IFeatureSet|null); - /** FieldReference fieldPath. */ - public fieldPath: string; + /** MessageOptions uninterpretedOption */ + uninterpretedOption?: (google.protobuf.IUninterpretedOption[]|null); - /** - * Creates a FieldReference message from a plain object. Also converts values to their respective internal types. - * @param object Plain object - * @returns FieldReference - */ - public static fromObject(object: { [k: string]: any }): google.firestore.v1.StructuredQuery.FieldReference; + /** MessageOptions .google.api.resource */ + ".google.api.resource"?: (google.api.IResourceDescriptor|null); + } - /** - * Creates a plain object from a FieldReference message. Also converts values to other types if specified. - * @param message FieldReference - * @param [options] Conversion options - * @returns Plain object - */ - public static toObject(message: google.firestore.v1.StructuredQuery.FieldReference, options?: $protobuf.IConversionOptions): { [k: string]: any }; + /** Represents a MessageOptions. */ + class MessageOptions implements IMessageOptions { - /** - * Converts this FieldReference to JSON. - * @returns JSON object - */ - public toJSON(): { [k: string]: any }; + /** + * Constructs a new MessageOptions. + * @param [properties] Properties to set + */ + constructor(properties?: google.protobuf.IMessageOptions); - /** - * Gets the default type url for FieldReference - * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") - * @returns The default type url - */ - public static getTypeUrl(typeUrlPrefix?: string): string; - } + /** MessageOptions messageSetWireFormat. */ + public messageSetWireFormat: boolean; - /** Properties of a Projection. */ - interface IProjection { + /** MessageOptions noStandardDescriptorAccessor. */ + public noStandardDescriptorAccessor: boolean; - /** Projection fields */ - fields?: (google.firestore.v1.StructuredQuery.IFieldReference[]|null); - } + /** MessageOptions deprecated. */ + public deprecated: boolean; - /** Represents a Projection. */ - class Projection implements IProjection { + /** MessageOptions mapEntry. */ + public mapEntry: boolean; - /** - * Constructs a new Projection. - * @param [properties] Properties to set - */ - constructor(properties?: google.firestore.v1.StructuredQuery.IProjection); + /** MessageOptions deprecatedLegacyJsonFieldConflicts. */ + public deprecatedLegacyJsonFieldConflicts: boolean; - /** Projection fields. */ - public fields: google.firestore.v1.StructuredQuery.IFieldReference[]; + /** MessageOptions features. */ + public features?: (google.protobuf.IFeatureSet|null); - /** - * Creates a Projection message from a plain object. Also converts values to their respective internal types. - * @param object Plain object - * @returns Projection - */ - public static fromObject(object: { [k: string]: any }): google.firestore.v1.StructuredQuery.Projection; + /** MessageOptions uninterpretedOption. */ + public uninterpretedOption: google.protobuf.IUninterpretedOption[]; - /** - * Creates a plain object from a Projection message. Also converts values to other types if specified. - * @param message Projection - * @param [options] Conversion options - * @returns Plain object - */ - public static toObject(message: google.firestore.v1.StructuredQuery.Projection, options?: $protobuf.IConversionOptions): { [k: string]: any }; + /** + * Creates a MessageOptions message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns MessageOptions + */ + public static fromObject(object: { [k: string]: any }): google.protobuf.MessageOptions; - /** - * Converts this Projection to JSON. - * @returns JSON object - */ - public toJSON(): { [k: string]: any }; + /** + * Creates a plain object from a MessageOptions message. Also converts values to other types if specified. + * @param message MessageOptions + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.protobuf.MessageOptions, options?: $protobuf.IConversionOptions): { [k: string]: any }; - /** - * Gets the default type url for Projection - * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") - * @returns The default type url - */ - public static getTypeUrl(typeUrlPrefix?: string): string; - } + /** + * Converts this MessageOptions to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; - /** Properties of a FindNearest. */ - interface IFindNearest { + /** + * Gets the default type url for MessageOptions + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } - /** FindNearest vectorField */ - vectorField?: (google.firestore.v1.StructuredQuery.IFieldReference|null); + /** Properties of a FieldOptions. */ + interface IFieldOptions { - /** FindNearest queryVector */ - queryVector?: (google.firestore.v1.IValue|null); + /** FieldOptions ctype */ + ctype?: (google.protobuf.FieldOptions.CType|null); - /** FindNearest distanceMeasure */ - distanceMeasure?: (google.firestore.v1.StructuredQuery.FindNearest.DistanceMeasure|null); + /** FieldOptions packed */ + packed?: (boolean|null); - /** FindNearest limit */ - limit?: (google.protobuf.IInt32Value|null); - } + /** FieldOptions jstype */ + jstype?: (google.protobuf.FieldOptions.JSType|null); - /** Represents a FindNearest. */ - class FindNearest implements IFindNearest { + /** FieldOptions lazy */ + lazy?: (boolean|null); - /** - * Constructs a new FindNearest. - * @param [properties] Properties to set - */ - constructor(properties?: google.firestore.v1.StructuredQuery.IFindNearest); + /** FieldOptions unverifiedLazy */ + unverifiedLazy?: (boolean|null); - /** FindNearest vectorField. */ - public vectorField?: (google.firestore.v1.StructuredQuery.IFieldReference|null); + /** FieldOptions deprecated */ + deprecated?: (boolean|null); - /** FindNearest queryVector. */ - public queryVector?: (google.firestore.v1.IValue|null); + /** FieldOptions weak */ + weak?: (boolean|null); - /** FindNearest distanceMeasure. */ - public distanceMeasure: google.firestore.v1.StructuredQuery.FindNearest.DistanceMeasure; + /** FieldOptions debugRedact */ + debugRedact?: (boolean|null); - /** FindNearest limit. */ - public limit?: (google.protobuf.IInt32Value|null); + /** FieldOptions retention */ + retention?: (google.protobuf.FieldOptions.OptionRetention|null); - /** - * Creates a FindNearest message from a plain object. Also converts values to their respective internal types. - * @param object Plain object - * @returns FindNearest - */ - public static fromObject(object: { [k: string]: any }): google.firestore.v1.StructuredQuery.FindNearest; + /** FieldOptions targets */ + targets?: (google.protobuf.FieldOptions.OptionTargetType[]|null); - /** - * Creates a plain object from a FindNearest message. Also converts values to other types if specified. - * @param message FindNearest - * @param [options] Conversion options - * @returns Plain object - */ - public static toObject(message: google.firestore.v1.StructuredQuery.FindNearest, options?: $protobuf.IConversionOptions): { [k: string]: any }; + /** FieldOptions editionDefaults */ + editionDefaults?: (google.protobuf.FieldOptions.IEditionDefault[]|null); - /** - * Converts this FindNearest to JSON. - * @returns JSON object - */ - public toJSON(): { [k: string]: any }; + /** FieldOptions features */ + features?: (google.protobuf.IFeatureSet|null); - /** - * Gets the default type url for FindNearest - * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") - * @returns The default type url - */ - public static getTypeUrl(typeUrlPrefix?: string): string; - } + /** FieldOptions uninterpretedOption */ + uninterpretedOption?: (google.protobuf.IUninterpretedOption[]|null); - namespace FindNearest { + /** FieldOptions .google.api.fieldBehavior */ + ".google.api.fieldBehavior"?: (google.api.FieldBehavior[]|null); - /** DistanceMeasure enum. */ - type DistanceMeasure = - "DISTANCE_MEASURE_UNSPECIFIED"| "EUCLIDEAN"| "COSINE"| "DOT_PRODUCT"; - } - } + /** FieldOptions .google.api.resourceReference */ + ".google.api.resourceReference"?: (google.api.IResourceReference|null); + } - /** Properties of a StructuredAggregationQuery. */ - interface IStructuredAggregationQuery { + /** Represents a FieldOptions. */ + class FieldOptions implements IFieldOptions { - /** StructuredAggregationQuery structuredQuery */ - structuredQuery?: (google.firestore.v1.IStructuredQuery|null); + /** + * Constructs a new FieldOptions. + * @param [properties] Properties to set + */ + constructor(properties?: google.protobuf.IFieldOptions); - /** StructuredAggregationQuery aggregations */ - aggregations?: (google.firestore.v1.StructuredAggregationQuery.IAggregation[]|null); - } + /** FieldOptions ctype. */ + public ctype: google.protobuf.FieldOptions.CType; - /** Represents a StructuredAggregationQuery. */ - class StructuredAggregationQuery implements IStructuredAggregationQuery { + /** FieldOptions packed. */ + public packed: boolean; - /** - * Constructs a new StructuredAggregationQuery. - * @param [properties] Properties to set - */ - constructor(properties?: google.firestore.v1.IStructuredAggregationQuery); + /** FieldOptions jstype. */ + public jstype: google.protobuf.FieldOptions.JSType; - /** StructuredAggregationQuery structuredQuery. */ - public structuredQuery?: (google.firestore.v1.IStructuredQuery|null); + /** FieldOptions lazy. */ + public lazy: boolean; - /** StructuredAggregationQuery aggregations. */ - public aggregations: google.firestore.v1.StructuredAggregationQuery.IAggregation[]; + /** FieldOptions unverifiedLazy. */ + public unverifiedLazy: boolean; - /** StructuredAggregationQuery queryType. */ - public queryType?: "structuredQuery"; + /** FieldOptions deprecated. */ + public deprecated: boolean; - /** - * Creates a StructuredAggregationQuery message from a plain object. Also converts values to their respective internal types. - * @param object Plain object - * @returns StructuredAggregationQuery - */ - public static fromObject(object: { [k: string]: any }): google.firestore.v1.StructuredAggregationQuery; + /** FieldOptions weak. */ + public weak: boolean; - /** - * Creates a plain object from a StructuredAggregationQuery message. Also converts values to other types if specified. - * @param message StructuredAggregationQuery - * @param [options] Conversion options - * @returns Plain object - */ - public static toObject(message: google.firestore.v1.StructuredAggregationQuery, options?: $protobuf.IConversionOptions): { [k: string]: any }; + /** FieldOptions debugRedact. */ + public debugRedact: boolean; - /** - * Converts this StructuredAggregationQuery to JSON. - * @returns JSON object - */ - public toJSON(): { [k: string]: any }; + /** FieldOptions retention. */ + public retention: google.protobuf.FieldOptions.OptionRetention; - /** - * Gets the default type url for StructuredAggregationQuery - * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") - * @returns The default type url - */ - public static getTypeUrl(typeUrlPrefix?: string): string; - } + /** FieldOptions targets. */ + public targets: google.protobuf.FieldOptions.OptionTargetType[]; - namespace StructuredAggregationQuery { + /** FieldOptions editionDefaults. */ + public editionDefaults: google.protobuf.FieldOptions.IEditionDefault[]; - /** Properties of an Aggregation. */ - interface IAggregation { + /** FieldOptions features. */ + public features?: (google.protobuf.IFeatureSet|null); - /** Aggregation count */ - count?: (google.firestore.v1.StructuredAggregationQuery.Aggregation.ICount|null); + /** FieldOptions uninterpretedOption. */ + public uninterpretedOption: google.protobuf.IUninterpretedOption[]; - /** Aggregation sum */ - sum?: (google.firestore.v1.StructuredAggregationQuery.Aggregation.ISum|null); + /** + * Creates a FieldOptions message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns FieldOptions + */ + public static fromObject(object: { [k: string]: any }): google.protobuf.FieldOptions; - /** Aggregation avg */ - avg?: (google.firestore.v1.StructuredAggregationQuery.Aggregation.IAvg|null); + /** + * Creates a plain object from a FieldOptions message. Also converts values to other types if specified. + * @param message FieldOptions + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.protobuf.FieldOptions, options?: $protobuf.IConversionOptions): { [k: string]: any }; - /** Aggregation alias */ - alias?: (string|null); - } + /** + * Converts this FieldOptions to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; - /** Represents an Aggregation. */ - class Aggregation implements IAggregation { + /** + * Gets the default type url for FieldOptions + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } - /** - * Constructs a new Aggregation. - * @param [properties] Properties to set - */ - constructor(properties?: google.firestore.v1.StructuredAggregationQuery.IAggregation); + namespace FieldOptions { - /** Aggregation count. */ - public count?: (google.firestore.v1.StructuredAggregationQuery.Aggregation.ICount|null); + /** CType enum. */ + type CType = + "STRING"| "CORD"| "STRING_PIECE"; - /** Aggregation sum. */ - public sum?: (google.firestore.v1.StructuredAggregationQuery.Aggregation.ISum|null); + /** JSType enum. */ + type JSType = + "JS_NORMAL"| "JS_STRING"| "JS_NUMBER"; - /** Aggregation avg. */ - public avg?: (google.firestore.v1.StructuredAggregationQuery.Aggregation.IAvg|null); + /** OptionRetention enum. */ + type OptionRetention = + "RETENTION_UNKNOWN"| "RETENTION_RUNTIME"| "RETENTION_SOURCE"; - /** Aggregation alias. */ - public alias: string; + /** OptionTargetType enum. */ + type OptionTargetType = + "TARGET_TYPE_UNKNOWN"| "TARGET_TYPE_FILE"| "TARGET_TYPE_EXTENSION_RANGE"| "TARGET_TYPE_MESSAGE"| "TARGET_TYPE_FIELD"| "TARGET_TYPE_ONEOF"| "TARGET_TYPE_ENUM"| "TARGET_TYPE_ENUM_ENTRY"| "TARGET_TYPE_SERVICE"| "TARGET_TYPE_METHOD"; - /** Aggregation operator. */ - public operator?: ("count"|"sum"|"avg"); + /** Properties of an EditionDefault. */ + interface IEditionDefault { - /** - * Creates an Aggregation message from a plain object. Also converts values to their respective internal types. - * @param object Plain object - * @returns Aggregation - */ - public static fromObject(object: { [k: string]: any }): google.firestore.v1.StructuredAggregationQuery.Aggregation; + /** EditionDefault edition */ + edition?: (google.protobuf.Edition|null); - /** - * Creates a plain object from an Aggregation message. Also converts values to other types if specified. - * @param message Aggregation - * @param [options] Conversion options - * @returns Plain object - */ - public static toObject(message: google.firestore.v1.StructuredAggregationQuery.Aggregation, options?: $protobuf.IConversionOptions): { [k: string]: any }; + /** EditionDefault value */ + value?: (string|null); + } - /** - * Converts this Aggregation to JSON. - * @returns JSON object - */ - public toJSON(): { [k: string]: any }; + /** Represents an EditionDefault. */ + class EditionDefault implements IEditionDefault { - /** - * Gets the default type url for Aggregation - * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") - * @returns The default type url - */ - public static getTypeUrl(typeUrlPrefix?: string): string; - } + /** + * Constructs a new EditionDefault. + * @param [properties] Properties to set + */ + constructor(properties?: google.protobuf.FieldOptions.IEditionDefault); - namespace Aggregation { + /** EditionDefault edition. */ + public edition: google.protobuf.Edition; - /** Properties of a Count. */ - interface ICount { + /** EditionDefault value. */ + public value: string; - /** Count upTo */ - upTo?: (google.protobuf.IInt64Value|null); - } + /** + * Creates an EditionDefault message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns EditionDefault + */ + public static fromObject(object: { [k: string]: any }): google.protobuf.FieldOptions.EditionDefault; - /** Represents a Count. */ - class Count implements ICount { + /** + * Creates a plain object from an EditionDefault message. Also converts values to other types if specified. + * @param message EditionDefault + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.protobuf.FieldOptions.EditionDefault, options?: $protobuf.IConversionOptions): { [k: string]: any }; - /** - * Constructs a new Count. - * @param [properties] Properties to set - */ - constructor(properties?: google.firestore.v1.StructuredAggregationQuery.Aggregation.ICount); + /** + * Converts this EditionDefault to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; - /** Count upTo. */ - public upTo?: (google.protobuf.IInt64Value|null); + /** + * Gets the default type url for EditionDefault + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + } - /** - * Creates a Count message from a plain object. Also converts values to their respective internal types. - * @param object Plain object - * @returns Count - */ - public static fromObject(object: { [k: string]: any }): google.firestore.v1.StructuredAggregationQuery.Aggregation.Count; + /** Properties of an OneofOptions. */ + interface IOneofOptions { - /** - * Creates a plain object from a Count message. Also converts values to other types if specified. - * @param message Count - * @param [options] Conversion options - * @returns Plain object - */ - public static toObject(message: google.firestore.v1.StructuredAggregationQuery.Aggregation.Count, options?: $protobuf.IConversionOptions): { [k: string]: any }; + /** OneofOptions features */ + features?: (google.protobuf.IFeatureSet|null); - /** - * Converts this Count to JSON. - * @returns JSON object - */ - public toJSON(): { [k: string]: any }; + /** OneofOptions uninterpretedOption */ + uninterpretedOption?: (google.protobuf.IUninterpretedOption[]|null); + } - /** - * Gets the default type url for Count - * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") - * @returns The default type url - */ - public static getTypeUrl(typeUrlPrefix?: string): string; - } + /** Represents an OneofOptions. */ + class OneofOptions implements IOneofOptions { - /** Properties of a Sum. */ - interface ISum { + /** + * Constructs a new OneofOptions. + * @param [properties] Properties to set + */ + constructor(properties?: google.protobuf.IOneofOptions); - /** Sum field */ - field?: (google.firestore.v1.StructuredQuery.IFieldReference|null); - } + /** OneofOptions features. */ + public features?: (google.protobuf.IFeatureSet|null); - /** Represents a Sum. */ - class Sum implements ISum { + /** OneofOptions uninterpretedOption. */ + public uninterpretedOption: google.protobuf.IUninterpretedOption[]; - /** - * Constructs a new Sum. - * @param [properties] Properties to set - */ - constructor(properties?: google.firestore.v1.StructuredAggregationQuery.Aggregation.ISum); + /** + * Creates an OneofOptions message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns OneofOptions + */ + public static fromObject(object: { [k: string]: any }): google.protobuf.OneofOptions; - /** Sum field. */ - public field?: (google.firestore.v1.StructuredQuery.IFieldReference|null); + /** + * Creates a plain object from an OneofOptions message. Also converts values to other types if specified. + * @param message OneofOptions + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.protobuf.OneofOptions, options?: $protobuf.IConversionOptions): { [k: string]: any }; - /** - * Creates a Sum message from a plain object. Also converts values to their respective internal types. - * @param object Plain object - * @returns Sum - */ - public static fromObject(object: { [k: string]: any }): google.firestore.v1.StructuredAggregationQuery.Aggregation.Sum; + /** + * Converts this OneofOptions to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; - /** - * Creates a plain object from a Sum message. Also converts values to other types if specified. - * @param message Sum - * @param [options] Conversion options - * @returns Plain object - */ - public static toObject(message: google.firestore.v1.StructuredAggregationQuery.Aggregation.Sum, options?: $protobuf.IConversionOptions): { [k: string]: any }; + /** + * Gets the default type url for OneofOptions + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } - /** - * Converts this Sum to JSON. - * @returns JSON object - */ - public toJSON(): { [k: string]: any }; + /** Properties of an EnumOptions. */ + interface IEnumOptions { - /** - * Gets the default type url for Sum - * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") - * @returns The default type url - */ - public static getTypeUrl(typeUrlPrefix?: string): string; - } + /** EnumOptions allowAlias */ + allowAlias?: (boolean|null); - /** Properties of an Avg. */ - interface IAvg { + /** EnumOptions deprecated */ + deprecated?: (boolean|null); - /** Avg field */ - field?: (google.firestore.v1.StructuredQuery.IFieldReference|null); - } + /** EnumOptions deprecatedLegacyJsonFieldConflicts */ + deprecatedLegacyJsonFieldConflicts?: (boolean|null); - /** Represents an Avg. */ - class Avg implements IAvg { + /** EnumOptions features */ + features?: (google.protobuf.IFeatureSet|null); - /** - * Constructs a new Avg. - * @param [properties] Properties to set - */ - constructor(properties?: google.firestore.v1.StructuredAggregationQuery.Aggregation.IAvg); + /** EnumOptions uninterpretedOption */ + uninterpretedOption?: (google.protobuf.IUninterpretedOption[]|null); + } - /** Avg field. */ - public field?: (google.firestore.v1.StructuredQuery.IFieldReference|null); + /** Represents an EnumOptions. */ + class EnumOptions implements IEnumOptions { - /** - * Creates an Avg message from a plain object. Also converts values to their respective internal types. - * @param object Plain object - * @returns Avg - */ - public static fromObject(object: { [k: string]: any }): google.firestore.v1.StructuredAggregationQuery.Aggregation.Avg; + /** + * Constructs a new EnumOptions. + * @param [properties] Properties to set + */ + constructor(properties?: google.protobuf.IEnumOptions); - /** - * Creates a plain object from an Avg message. Also converts values to other types if specified. - * @param message Avg - * @param [options] Conversion options - * @returns Plain object - */ - public static toObject(message: google.firestore.v1.StructuredAggregationQuery.Aggregation.Avg, options?: $protobuf.IConversionOptions): { [k: string]: any }; + /** EnumOptions allowAlias. */ + public allowAlias: boolean; - /** - * Converts this Avg to JSON. - * @returns JSON object - */ - public toJSON(): { [k: string]: any }; + /** EnumOptions deprecated. */ + public deprecated: boolean; - /** - * Gets the default type url for Avg - * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") - * @returns The default type url - */ - public static getTypeUrl(typeUrlPrefix?: string): string; - } - } - } + /** EnumOptions deprecatedLegacyJsonFieldConflicts. */ + public deprecatedLegacyJsonFieldConflicts: boolean; - /** Properties of a Cursor. */ - interface ICursor { + /** EnumOptions features. */ + public features?: (google.protobuf.IFeatureSet|null); - /** Cursor values */ - values?: (google.firestore.v1.IValue[]|null); + /** EnumOptions uninterpretedOption. */ + public uninterpretedOption: google.protobuf.IUninterpretedOption[]; - /** Cursor before */ - before?: (boolean|null); - } + /** + * Creates an EnumOptions message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns EnumOptions + */ + public static fromObject(object: { [k: string]: any }): google.protobuf.EnumOptions; - /** Represents a Cursor. */ - class Cursor implements ICursor { + /** + * Creates a plain object from an EnumOptions message. Also converts values to other types if specified. + * @param message EnumOptions + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.protobuf.EnumOptions, options?: $protobuf.IConversionOptions): { [k: string]: any }; - /** - * Constructs a new Cursor. - * @param [properties] Properties to set - */ - constructor(properties?: google.firestore.v1.ICursor); + /** + * Converts this EnumOptions to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; - /** Cursor values. */ - public values: google.firestore.v1.IValue[]; + /** + * Gets the default type url for EnumOptions + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } - /** Cursor before. */ - public before: boolean; + /** Properties of an EnumValueOptions. */ + interface IEnumValueOptions { - /** - * Creates a Cursor message from a plain object. Also converts values to their respective internal types. - * @param object Plain object - * @returns Cursor - */ - public static fromObject(object: { [k: string]: any }): google.firestore.v1.Cursor; + /** EnumValueOptions deprecated */ + deprecated?: (boolean|null); - /** - * Creates a plain object from a Cursor message. Also converts values to other types if specified. - * @param message Cursor - * @param [options] Conversion options - * @returns Plain object - */ - public static toObject(message: google.firestore.v1.Cursor, options?: $protobuf.IConversionOptions): { [k: string]: any }; + /** EnumValueOptions features */ + features?: (google.protobuf.IFeatureSet|null); - /** - * Converts this Cursor to JSON. - * @returns JSON object - */ - public toJSON(): { [k: string]: any }; + /** EnumValueOptions debugRedact */ + debugRedact?: (boolean|null); - /** - * Gets the default type url for Cursor - * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") - * @returns The default type url - */ - public static getTypeUrl(typeUrlPrefix?: string): string; - } + /** EnumValueOptions uninterpretedOption */ + uninterpretedOption?: (google.protobuf.IUninterpretedOption[]|null); + } - /** Properties of an ExplainOptions. */ - interface IExplainOptions { + /** Represents an EnumValueOptions. */ + class EnumValueOptions implements IEnumValueOptions { - /** ExplainOptions analyze */ - analyze?: (boolean|null); - } + /** + * Constructs a new EnumValueOptions. + * @param [properties] Properties to set + */ + constructor(properties?: google.protobuf.IEnumValueOptions); - /** Represents an ExplainOptions. */ - class ExplainOptions implements IExplainOptions { + /** EnumValueOptions deprecated. */ + public deprecated: boolean; - /** - * Constructs a new ExplainOptions. - * @param [properties] Properties to set - */ - constructor(properties?: google.firestore.v1.IExplainOptions); + /** EnumValueOptions features. */ + public features?: (google.protobuf.IFeatureSet|null); - /** ExplainOptions analyze. */ - public analyze: boolean; + /** EnumValueOptions debugRedact. */ + public debugRedact: boolean; - /** - * Creates an ExplainOptions message from a plain object. Also converts values to their respective internal types. - * @param object Plain object - * @returns ExplainOptions - */ - public static fromObject(object: { [k: string]: any }): google.firestore.v1.ExplainOptions; + /** EnumValueOptions uninterpretedOption. */ + public uninterpretedOption: google.protobuf.IUninterpretedOption[]; - /** - * Creates a plain object from an ExplainOptions message. Also converts values to other types if specified. - * @param message ExplainOptions - * @param [options] Conversion options - * @returns Plain object - */ - public static toObject(message: google.firestore.v1.ExplainOptions, options?: $protobuf.IConversionOptions): { [k: string]: any }; + /** + * Creates an EnumValueOptions message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns EnumValueOptions + */ + public static fromObject(object: { [k: string]: any }): google.protobuf.EnumValueOptions; - /** - * Converts this ExplainOptions to JSON. - * @returns JSON object - */ - public toJSON(): { [k: string]: any }; + /** + * Creates a plain object from an EnumValueOptions message. Also converts values to other types if specified. + * @param message EnumValueOptions + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.protobuf.EnumValueOptions, options?: $protobuf.IConversionOptions): { [k: string]: any }; - /** - * Gets the default type url for ExplainOptions - * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") - * @returns The default type url - */ - public static getTypeUrl(typeUrlPrefix?: string): string; - } + /** + * Converts this EnumValueOptions to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; - /** Properties of an ExplainMetrics. */ - interface IExplainMetrics { + /** + * Gets the default type url for EnumValueOptions + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } - /** ExplainMetrics planSummary */ - planSummary?: (google.firestore.v1.IPlanSummary|null); + /** Properties of a ServiceOptions. */ + interface IServiceOptions { - /** ExplainMetrics executionStats */ - executionStats?: (google.firestore.v1.IExecutionStats|null); - } + /** ServiceOptions features */ + features?: (google.protobuf.IFeatureSet|null); - /** Represents an ExplainMetrics. */ - class ExplainMetrics implements IExplainMetrics { + /** ServiceOptions deprecated */ + deprecated?: (boolean|null); - /** - * Constructs a new ExplainMetrics. - * @param [properties] Properties to set - */ - constructor(properties?: google.firestore.v1.IExplainMetrics); + /** ServiceOptions uninterpretedOption */ + uninterpretedOption?: (google.protobuf.IUninterpretedOption[]|null); - /** ExplainMetrics planSummary. */ - public planSummary?: (google.firestore.v1.IPlanSummary|null); + /** ServiceOptions .google.api.defaultHost */ + ".google.api.defaultHost"?: (string|null); - /** ExplainMetrics executionStats. */ - public executionStats?: (google.firestore.v1.IExecutionStats|null); + /** ServiceOptions .google.api.oauthScopes */ + ".google.api.oauthScopes"?: (string|null); - /** - * Creates an ExplainMetrics message from a plain object. Also converts values to their respective internal types. - * @param object Plain object - * @returns ExplainMetrics - */ - public static fromObject(object: { [k: string]: any }): google.firestore.v1.ExplainMetrics; + /** ServiceOptions .google.api.apiVersion */ + ".google.api.apiVersion"?: (string|null); + } - /** - * Creates a plain object from an ExplainMetrics message. Also converts values to other types if specified. - * @param message ExplainMetrics - * @param [options] Conversion options - * @returns Plain object - */ - public static toObject(message: google.firestore.v1.ExplainMetrics, options?: $protobuf.IConversionOptions): { [k: string]: any }; + /** Represents a ServiceOptions. */ + class ServiceOptions implements IServiceOptions { - /** - * Converts this ExplainMetrics to JSON. - * @returns JSON object - */ - public toJSON(): { [k: string]: any }; + /** + * Constructs a new ServiceOptions. + * @param [properties] Properties to set + */ + constructor(properties?: google.protobuf.IServiceOptions); - /** - * Gets the default type url for ExplainMetrics - * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") - * @returns The default type url - */ - public static getTypeUrl(typeUrlPrefix?: string): string; - } + /** ServiceOptions features. */ + public features?: (google.protobuf.IFeatureSet|null); - /** Properties of a PlanSummary. */ - interface IPlanSummary { + /** ServiceOptions deprecated. */ + public deprecated: boolean; - /** PlanSummary indexesUsed */ - indexesUsed?: (google.protobuf.IStruct[]|null); - } + /** ServiceOptions uninterpretedOption. */ + public uninterpretedOption: google.protobuf.IUninterpretedOption[]; + + /** + * Creates a ServiceOptions message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns ServiceOptions + */ + public static fromObject(object: { [k: string]: any }): google.protobuf.ServiceOptions; + + /** + * Creates a plain object from a ServiceOptions message. Also converts values to other types if specified. + * @param message ServiceOptions + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.protobuf.ServiceOptions, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this ServiceOptions to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; - /** Represents a PlanSummary. */ - class PlanSummary implements IPlanSummary { + /** + * Gets the default type url for ServiceOptions + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } - /** - * Constructs a new PlanSummary. - * @param [properties] Properties to set - */ - constructor(properties?: google.firestore.v1.IPlanSummary); + /** Properties of a MethodOptions. */ + interface IMethodOptions { - /** PlanSummary indexesUsed. */ - public indexesUsed: google.protobuf.IStruct[]; + /** MethodOptions deprecated */ + deprecated?: (boolean|null); - /** - * Creates a PlanSummary message from a plain object. Also converts values to their respective internal types. - * @param object Plain object - * @returns PlanSummary - */ - public static fromObject(object: { [k: string]: any }): google.firestore.v1.PlanSummary; + /** MethodOptions idempotencyLevel */ + idempotencyLevel?: (google.protobuf.MethodOptions.IdempotencyLevel|null); - /** - * Creates a plain object from a PlanSummary message. Also converts values to other types if specified. - * @param message PlanSummary - * @param [options] Conversion options - * @returns Plain object - */ - public static toObject(message: google.firestore.v1.PlanSummary, options?: $protobuf.IConversionOptions): { [k: string]: any }; + /** MethodOptions features */ + features?: (google.protobuf.IFeatureSet|null); - /** - * Converts this PlanSummary to JSON. - * @returns JSON object - */ - public toJSON(): { [k: string]: any }; + /** MethodOptions uninterpretedOption */ + uninterpretedOption?: (google.protobuf.IUninterpretedOption[]|null); - /** - * Gets the default type url for PlanSummary - * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") - * @returns The default type url - */ - public static getTypeUrl(typeUrlPrefix?: string): string; - } + /** MethodOptions .google.api.http */ + ".google.api.http"?: (google.api.IHttpRule|null); - /** Properties of an ExecutionStats. */ - interface IExecutionStats { + /** MethodOptions .google.api.methodSignature */ + ".google.api.methodSignature"?: (string[]|null); - /** ExecutionStats resultsReturned */ - resultsReturned?: (number|string|null); + /** MethodOptions .google.longrunning.operationInfo */ + ".google.longrunning.operationInfo"?: (google.longrunning.IOperationInfo|null); + } - /** ExecutionStats executionDuration */ - executionDuration?: (google.protobuf.IDuration|null); + /** Represents a MethodOptions. */ + class MethodOptions implements IMethodOptions { - /** ExecutionStats readOperations */ - readOperations?: (number|string|null); + /** + * Constructs a new MethodOptions. + * @param [properties] Properties to set + */ + constructor(properties?: google.protobuf.IMethodOptions); - /** ExecutionStats debugStats */ - debugStats?: (google.protobuf.IStruct|null); - } + /** MethodOptions deprecated. */ + public deprecated: boolean; - /** Represents an ExecutionStats. */ - class ExecutionStats implements IExecutionStats { + /** MethodOptions idempotencyLevel. */ + public idempotencyLevel: google.protobuf.MethodOptions.IdempotencyLevel; - /** - * Constructs a new ExecutionStats. - * @param [properties] Properties to set - */ - constructor(properties?: google.firestore.v1.IExecutionStats); + /** MethodOptions features. */ + public features?: (google.protobuf.IFeatureSet|null); - /** ExecutionStats resultsReturned. */ - public resultsReturned: (number|string); + /** MethodOptions uninterpretedOption. */ + public uninterpretedOption: google.protobuf.IUninterpretedOption[]; - /** ExecutionStats executionDuration. */ - public executionDuration?: (google.protobuf.IDuration|null); + /** + * Creates a MethodOptions message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns MethodOptions + */ + public static fromObject(object: { [k: string]: any }): google.protobuf.MethodOptions; - /** ExecutionStats readOperations. */ - public readOperations: (number|string); + /** + * Creates a plain object from a MethodOptions message. Also converts values to other types if specified. + * @param message MethodOptions + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.protobuf.MethodOptions, options?: $protobuf.IConversionOptions): { [k: string]: any }; - /** ExecutionStats debugStats. */ - public debugStats?: (google.protobuf.IStruct|null); + /** + * Converts this MethodOptions to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; - /** - * Creates an ExecutionStats message from a plain object. Also converts values to their respective internal types. - * @param object Plain object - * @returns ExecutionStats - */ - public static fromObject(object: { [k: string]: any }): google.firestore.v1.ExecutionStats; + /** + * Gets the default type url for MethodOptions + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } - /** - * Creates a plain object from an ExecutionStats message. Also converts values to other types if specified. - * @param message ExecutionStats - * @param [options] Conversion options - * @returns Plain object - */ - public static toObject(message: google.firestore.v1.ExecutionStats, options?: $protobuf.IConversionOptions): { [k: string]: any }; + namespace MethodOptions { - /** - * Converts this ExecutionStats to JSON. - * @returns JSON object - */ - public toJSON(): { [k: string]: any }; + /** IdempotencyLevel enum. */ + type IdempotencyLevel = + "IDEMPOTENCY_UNKNOWN"| "NO_SIDE_EFFECTS"| "IDEMPOTENT"; + } - /** - * Gets the default type url for ExecutionStats - * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") - * @returns The default type url - */ - public static getTypeUrl(typeUrlPrefix?: string): string; - } + /** Properties of an UninterpretedOption. */ + interface IUninterpretedOption { - /** Properties of a Write. */ - interface IWrite { + /** UninterpretedOption name */ + name?: (google.protobuf.UninterpretedOption.INamePart[]|null); - /** Write update */ - update?: (google.firestore.v1.IDocument|null); + /** UninterpretedOption identifierValue */ + identifierValue?: (string|null); - /** Write delete */ - "delete"?: (string|null); + /** UninterpretedOption positiveIntValue */ + positiveIntValue?: (number|string|null); - /** Write transform */ - transform?: (google.firestore.v1.IDocumentTransform|null); + /** UninterpretedOption negativeIntValue */ + negativeIntValue?: (number|string|null); - /** Write updateMask */ - updateMask?: (google.firestore.v1.IDocumentMask|null); + /** UninterpretedOption doubleValue */ + doubleValue?: (number|null); - /** Write updateTransforms */ - updateTransforms?: (google.firestore.v1.DocumentTransform.IFieldTransform[]|null); + /** UninterpretedOption stringValue */ + stringValue?: (Uint8Array|null); - /** Write currentDocument */ - currentDocument?: (google.firestore.v1.IPrecondition|null); - } + /** UninterpretedOption aggregateValue */ + aggregateValue?: (string|null); + } - /** Represents a Write. */ - class Write implements IWrite { + /** Represents an UninterpretedOption. */ + class UninterpretedOption implements IUninterpretedOption { - /** - * Constructs a new Write. - * @param [properties] Properties to set - */ - constructor(properties?: google.firestore.v1.IWrite); + /** + * Constructs a new UninterpretedOption. + * @param [properties] Properties to set + */ + constructor(properties?: google.protobuf.IUninterpretedOption); - /** Write update. */ - public update?: (google.firestore.v1.IDocument|null); + /** UninterpretedOption name. */ + public name: google.protobuf.UninterpretedOption.INamePart[]; - /** Write delete. */ - public delete?: (string|null); + /** UninterpretedOption identifierValue. */ + public identifierValue: string; - /** Write transform. */ - public transform?: (google.firestore.v1.IDocumentTransform|null); + /** UninterpretedOption positiveIntValue. */ + public positiveIntValue: (number|string); - /** Write updateMask. */ - public updateMask?: (google.firestore.v1.IDocumentMask|null); + /** UninterpretedOption negativeIntValue. */ + public negativeIntValue: (number|string); - /** Write updateTransforms. */ - public updateTransforms: google.firestore.v1.DocumentTransform.IFieldTransform[]; + /** UninterpretedOption doubleValue. */ + public doubleValue: number; - /** Write currentDocument. */ - public currentDocument?: (google.firestore.v1.IPrecondition|null); + /** UninterpretedOption stringValue. */ + public stringValue: Uint8Array; - /** Write operation. */ - public operation?: ("update"|"delete"|"transform"); + /** UninterpretedOption aggregateValue. */ + public aggregateValue: string; - /** - * Creates a Write message from a plain object. Also converts values to their respective internal types. - * @param object Plain object - * @returns Write - */ - public static fromObject(object: { [k: string]: any }): google.firestore.v1.Write; + /** + * Creates an UninterpretedOption message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns UninterpretedOption + */ + public static fromObject(object: { [k: string]: any }): google.protobuf.UninterpretedOption; - /** - * Creates a plain object from a Write message. Also converts values to other types if specified. - * @param message Write - * @param [options] Conversion options - * @returns Plain object - */ - public static toObject(message: google.firestore.v1.Write, options?: $protobuf.IConversionOptions): { [k: string]: any }; + /** + * Creates a plain object from an UninterpretedOption message. Also converts values to other types if specified. + * @param message UninterpretedOption + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.protobuf.UninterpretedOption, options?: $protobuf.IConversionOptions): { [k: string]: any }; - /** - * Converts this Write to JSON. - * @returns JSON object - */ - public toJSON(): { [k: string]: any }; + /** + * Converts this UninterpretedOption to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; - /** - * Gets the default type url for Write - * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") - * @returns The default type url - */ - public static getTypeUrl(typeUrlPrefix?: string): string; - } + /** + * Gets the default type url for UninterpretedOption + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } - /** Properties of a DocumentTransform. */ - interface IDocumentTransform { + namespace UninterpretedOption { - /** DocumentTransform document */ - document?: (string|null); + /** Properties of a NamePart. */ + interface INamePart { - /** DocumentTransform fieldTransforms */ - fieldTransforms?: (google.firestore.v1.DocumentTransform.IFieldTransform[]|null); + /** NamePart namePart */ + namePart: string; + + /** NamePart isExtension */ + isExtension: boolean; } - /** Represents a DocumentTransform. */ - class DocumentTransform implements IDocumentTransform { + /** Represents a NamePart. */ + class NamePart implements INamePart { /** - * Constructs a new DocumentTransform. + * Constructs a new NamePart. * @param [properties] Properties to set */ - constructor(properties?: google.firestore.v1.IDocumentTransform); + constructor(properties?: google.protobuf.UninterpretedOption.INamePart); - /** DocumentTransform document. */ - public document: string; + /** NamePart namePart. */ + public namePart: string; - /** DocumentTransform fieldTransforms. */ - public fieldTransforms: google.firestore.v1.DocumentTransform.IFieldTransform[]; + /** NamePart isExtension. */ + public isExtension: boolean; /** - * Creates a DocumentTransform message from a plain object. Also converts values to their respective internal types. + * Creates a NamePart message from a plain object. Also converts values to their respective internal types. * @param object Plain object - * @returns DocumentTransform + * @returns NamePart */ - public static fromObject(object: { [k: string]: any }): google.firestore.v1.DocumentTransform; + public static fromObject(object: { [k: string]: any }): google.protobuf.UninterpretedOption.NamePart; /** - * Creates a plain object from a DocumentTransform message. Also converts values to other types if specified. - * @param message DocumentTransform + * Creates a plain object from a NamePart message. Also converts values to other types if specified. + * @param message NamePart * @param [options] Conversion options * @returns Plain object */ - public static toObject(message: google.firestore.v1.DocumentTransform, options?: $protobuf.IConversionOptions): { [k: string]: any }; + public static toObject(message: google.protobuf.UninterpretedOption.NamePart, options?: $protobuf.IConversionOptions): { [k: string]: any }; /** - * Converts this DocumentTransform to JSON. + * Converts this NamePart to JSON. * @returns JSON object */ public toJSON(): { [k: string]: any }; /** - * Gets the default type url for DocumentTransform + * Gets the default type url for NamePart * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") * @returns The default type url */ public static getTypeUrl(typeUrlPrefix?: string): string; } + } - namespace DocumentTransform { - - /** Properties of a FieldTransform. */ - interface IFieldTransform { - - /** FieldTransform fieldPath */ - fieldPath?: (string|null); - - /** FieldTransform setToServerValue */ - setToServerValue?: (google.firestore.v1.DocumentTransform.FieldTransform.ServerValue|null); - - /** FieldTransform increment */ - increment?: (google.firestore.v1.IValue|null); - - /** FieldTransform maximum */ - maximum?: (google.firestore.v1.IValue|null); - - /** FieldTransform minimum */ - minimum?: (google.firestore.v1.IValue|null); - - /** FieldTransform appendMissingElements */ - appendMissingElements?: (google.firestore.v1.IArrayValue|null); - - /** FieldTransform removeAllFromArray */ - removeAllFromArray?: (google.firestore.v1.IArrayValue|null); - } - - /** Represents a FieldTransform. */ - class FieldTransform implements IFieldTransform { - - /** - * Constructs a new FieldTransform. - * @param [properties] Properties to set - */ - constructor(properties?: google.firestore.v1.DocumentTransform.IFieldTransform); - - /** FieldTransform fieldPath. */ - public fieldPath: string; + /** Properties of a FeatureSet. */ + interface IFeatureSet { - /** FieldTransform setToServerValue. */ - public setToServerValue?: (google.firestore.v1.DocumentTransform.FieldTransform.ServerValue|null); + /** FeatureSet fieldPresence */ + fieldPresence?: (google.protobuf.FeatureSet.FieldPresence|null); - /** FieldTransform increment. */ - public increment?: (google.firestore.v1.IValue|null); + /** FeatureSet enumType */ + enumType?: (google.protobuf.FeatureSet.EnumType|null); - /** FieldTransform maximum. */ - public maximum?: (google.firestore.v1.IValue|null); + /** FeatureSet repeatedFieldEncoding */ + repeatedFieldEncoding?: (google.protobuf.FeatureSet.RepeatedFieldEncoding|null); - /** FieldTransform minimum. */ - public minimum?: (google.firestore.v1.IValue|null); + /** FeatureSet utf8Validation */ + utf8Validation?: (google.protobuf.FeatureSet.Utf8Validation|null); - /** FieldTransform appendMissingElements. */ - public appendMissingElements?: (google.firestore.v1.IArrayValue|null); + /** FeatureSet messageEncoding */ + messageEncoding?: (google.protobuf.FeatureSet.MessageEncoding|null); - /** FieldTransform removeAllFromArray. */ - public removeAllFromArray?: (google.firestore.v1.IArrayValue|null); + /** FeatureSet jsonFormat */ + jsonFormat?: (google.protobuf.FeatureSet.JsonFormat|null); + } - /** FieldTransform transformType. */ - public transformType?: ("setToServerValue"|"increment"|"maximum"|"minimum"|"appendMissingElements"|"removeAllFromArray"); + /** Represents a FeatureSet. */ + class FeatureSet implements IFeatureSet { - /** - * Creates a FieldTransform message from a plain object. Also converts values to their respective internal types. - * @param object Plain object - * @returns FieldTransform - */ - public static fromObject(object: { [k: string]: any }): google.firestore.v1.DocumentTransform.FieldTransform; + /** + * Constructs a new FeatureSet. + * @param [properties] Properties to set + */ + constructor(properties?: google.protobuf.IFeatureSet); - /** - * Creates a plain object from a FieldTransform message. Also converts values to other types if specified. - * @param message FieldTransform - * @param [options] Conversion options - * @returns Plain object - */ - public static toObject(message: google.firestore.v1.DocumentTransform.FieldTransform, options?: $protobuf.IConversionOptions): { [k: string]: any }; + /** FeatureSet fieldPresence. */ + public fieldPresence: google.protobuf.FeatureSet.FieldPresence; - /** - * Converts this FieldTransform to JSON. - * @returns JSON object - */ - public toJSON(): { [k: string]: any }; + /** FeatureSet enumType. */ + public enumType: google.protobuf.FeatureSet.EnumType; - /** - * Gets the default type url for FieldTransform - * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") - * @returns The default type url - */ - public static getTypeUrl(typeUrlPrefix?: string): string; - } + /** FeatureSet repeatedFieldEncoding. */ + public repeatedFieldEncoding: google.protobuf.FeatureSet.RepeatedFieldEncoding; - namespace FieldTransform { + /** FeatureSet utf8Validation. */ + public utf8Validation: google.protobuf.FeatureSet.Utf8Validation; - /** ServerValue enum. */ - type ServerValue = - "SERVER_VALUE_UNSPECIFIED"| "REQUEST_TIME"; - } - } + /** FeatureSet messageEncoding. */ + public messageEncoding: google.protobuf.FeatureSet.MessageEncoding; - /** Properties of a WriteResult. */ - interface IWriteResult { + /** FeatureSet jsonFormat. */ + public jsonFormat: google.protobuf.FeatureSet.JsonFormat; - /** WriteResult updateTime */ - updateTime?: (google.protobuf.ITimestamp|null); + /** + * Creates a FeatureSet message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns FeatureSet + */ + public static fromObject(object: { [k: string]: any }): google.protobuf.FeatureSet; - /** WriteResult transformResults */ - transformResults?: (google.firestore.v1.IValue[]|null); - } + /** + * Creates a plain object from a FeatureSet message. Also converts values to other types if specified. + * @param message FeatureSet + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.protobuf.FeatureSet, options?: $protobuf.IConversionOptions): { [k: string]: any }; - /** Represents a WriteResult. */ - class WriteResult implements IWriteResult { + /** + * Converts this FeatureSet to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; - /** - * Constructs a new WriteResult. - * @param [properties] Properties to set - */ - constructor(properties?: google.firestore.v1.IWriteResult); + /** + * Gets the default type url for FeatureSet + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } - /** WriteResult updateTime. */ - public updateTime?: (google.protobuf.ITimestamp|null); + namespace FeatureSet { - /** WriteResult transformResults. */ - public transformResults: google.firestore.v1.IValue[]; + /** FieldPresence enum. */ + type FieldPresence = + "FIELD_PRESENCE_UNKNOWN"| "EXPLICIT"| "IMPLICIT"| "LEGACY_REQUIRED"; - /** - * Creates a WriteResult message from a plain object. Also converts values to their respective internal types. - * @param object Plain object - * @returns WriteResult - */ - public static fromObject(object: { [k: string]: any }): google.firestore.v1.WriteResult; + /** EnumType enum. */ + type EnumType = + "ENUM_TYPE_UNKNOWN"| "OPEN"| "CLOSED"; - /** - * Creates a plain object from a WriteResult message. Also converts values to other types if specified. - * @param message WriteResult - * @param [options] Conversion options - * @returns Plain object - */ - public static toObject(message: google.firestore.v1.WriteResult, options?: $protobuf.IConversionOptions): { [k: string]: any }; + /** RepeatedFieldEncoding enum. */ + type RepeatedFieldEncoding = + "REPEATED_FIELD_ENCODING_UNKNOWN"| "PACKED"| "EXPANDED"; - /** - * Converts this WriteResult to JSON. - * @returns JSON object - */ - public toJSON(): { [k: string]: any }; + /** Utf8Validation enum. */ + type Utf8Validation = + "UTF8_VALIDATION_UNKNOWN"| "VERIFY"| "NONE"; - /** - * Gets the default type url for WriteResult - * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") - * @returns The default type url - */ - public static getTypeUrl(typeUrlPrefix?: string): string; - } + /** MessageEncoding enum. */ + type MessageEncoding = + "MESSAGE_ENCODING_UNKNOWN"| "LENGTH_PREFIXED"| "DELIMITED"; - /** Properties of a DocumentChange. */ - interface IDocumentChange { + /** JsonFormat enum. */ + type JsonFormat = + "JSON_FORMAT_UNKNOWN"| "ALLOW"| "LEGACY_BEST_EFFORT"; + } - /** DocumentChange document */ - document?: (google.firestore.v1.IDocument|null); + /** Properties of a FeatureSetDefaults. */ + interface IFeatureSetDefaults { - /** DocumentChange targetIds */ - targetIds?: (number[]|null); + /** FeatureSetDefaults defaults */ + defaults?: (google.protobuf.FeatureSetDefaults.IFeatureSetEditionDefault[]|null); - /** DocumentChange removedTargetIds */ - removedTargetIds?: (number[]|null); - } + /** FeatureSetDefaults minimumEdition */ + minimumEdition?: (google.protobuf.Edition|null); - /** Represents a DocumentChange. */ - class DocumentChange implements IDocumentChange { + /** FeatureSetDefaults maximumEdition */ + maximumEdition?: (google.protobuf.Edition|null); + } - /** - * Constructs a new DocumentChange. - * @param [properties] Properties to set - */ - constructor(properties?: google.firestore.v1.IDocumentChange); + /** Represents a FeatureSetDefaults. */ + class FeatureSetDefaults implements IFeatureSetDefaults { - /** DocumentChange document. */ - public document?: (google.firestore.v1.IDocument|null); + /** + * Constructs a new FeatureSetDefaults. + * @param [properties] Properties to set + */ + constructor(properties?: google.protobuf.IFeatureSetDefaults); - /** DocumentChange targetIds. */ - public targetIds: number[]; + /** FeatureSetDefaults defaults. */ + public defaults: google.protobuf.FeatureSetDefaults.IFeatureSetEditionDefault[]; - /** DocumentChange removedTargetIds. */ - public removedTargetIds: number[]; + /** FeatureSetDefaults minimumEdition. */ + public minimumEdition: google.protobuf.Edition; - /** - * Creates a DocumentChange message from a plain object. Also converts values to their respective internal types. - * @param object Plain object - * @returns DocumentChange - */ - public static fromObject(object: { [k: string]: any }): google.firestore.v1.DocumentChange; + /** FeatureSetDefaults maximumEdition. */ + public maximumEdition: google.protobuf.Edition; - /** - * Creates a plain object from a DocumentChange message. Also converts values to other types if specified. - * @param message DocumentChange - * @param [options] Conversion options - * @returns Plain object - */ - public static toObject(message: google.firestore.v1.DocumentChange, options?: $protobuf.IConversionOptions): { [k: string]: any }; + /** + * Creates a FeatureSetDefaults message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns FeatureSetDefaults + */ + public static fromObject(object: { [k: string]: any }): google.protobuf.FeatureSetDefaults; - /** - * Converts this DocumentChange to JSON. - * @returns JSON object - */ - public toJSON(): { [k: string]: any }; + /** + * Creates a plain object from a FeatureSetDefaults message. Also converts values to other types if specified. + * @param message FeatureSetDefaults + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.protobuf.FeatureSetDefaults, options?: $protobuf.IConversionOptions): { [k: string]: any }; - /** - * Gets the default type url for DocumentChange - * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") - * @returns The default type url - */ - public static getTypeUrl(typeUrlPrefix?: string): string; - } + /** + * Converts this FeatureSetDefaults to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; - /** Properties of a DocumentDelete. */ - interface IDocumentDelete { + /** + * Gets the default type url for FeatureSetDefaults + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } - /** DocumentDelete document */ - document?: (string|null); + namespace FeatureSetDefaults { - /** DocumentDelete removedTargetIds */ - removedTargetIds?: (number[]|null); + /** Properties of a FeatureSetEditionDefault. */ + interface IFeatureSetEditionDefault { - /** DocumentDelete readTime */ - readTime?: (google.protobuf.ITimestamp|null); + /** FeatureSetEditionDefault edition */ + edition?: (google.protobuf.Edition|null); + + /** FeatureSetEditionDefault features */ + features?: (google.protobuf.IFeatureSet|null); } - /** Represents a DocumentDelete. */ - class DocumentDelete implements IDocumentDelete { + /** Represents a FeatureSetEditionDefault. */ + class FeatureSetEditionDefault implements IFeatureSetEditionDefault { /** - * Constructs a new DocumentDelete. + * Constructs a new FeatureSetEditionDefault. * @param [properties] Properties to set */ - constructor(properties?: google.firestore.v1.IDocumentDelete); - - /** DocumentDelete document. */ - public document: string; + constructor(properties?: google.protobuf.FeatureSetDefaults.IFeatureSetEditionDefault); - /** DocumentDelete removedTargetIds. */ - public removedTargetIds: number[]; + /** FeatureSetEditionDefault edition. */ + public edition: google.protobuf.Edition; - /** DocumentDelete readTime. */ - public readTime?: (google.protobuf.ITimestamp|null); + /** FeatureSetEditionDefault features. */ + public features?: (google.protobuf.IFeatureSet|null); /** - * Creates a DocumentDelete message from a plain object. Also converts values to their respective internal types. + * Creates a FeatureSetEditionDefault message from a plain object. Also converts values to their respective internal types. * @param object Plain object - * @returns DocumentDelete + * @returns FeatureSetEditionDefault */ - public static fromObject(object: { [k: string]: any }): google.firestore.v1.DocumentDelete; + public static fromObject(object: { [k: string]: any }): google.protobuf.FeatureSetDefaults.FeatureSetEditionDefault; /** - * Creates a plain object from a DocumentDelete message. Also converts values to other types if specified. - * @param message DocumentDelete + * Creates a plain object from a FeatureSetEditionDefault message. Also converts values to other types if specified. + * @param message FeatureSetEditionDefault * @param [options] Conversion options * @returns Plain object */ - public static toObject(message: google.firestore.v1.DocumentDelete, options?: $protobuf.IConversionOptions): { [k: string]: any }; + public static toObject(message: google.protobuf.FeatureSetDefaults.FeatureSetEditionDefault, options?: $protobuf.IConversionOptions): { [k: string]: any }; /** - * Converts this DocumentDelete to JSON. + * Converts this FeatureSetEditionDefault to JSON. * @returns JSON object */ public toJSON(): { [k: string]: any }; /** - * Gets the default type url for DocumentDelete + * Gets the default type url for FeatureSetEditionDefault * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") * @returns The default type url */ public static getTypeUrl(typeUrlPrefix?: string): string; } + } - /** Properties of a DocumentRemove. */ - interface IDocumentRemove { - - /** DocumentRemove document */ - document?: (string|null); + /** Properties of a SourceCodeInfo. */ + interface ISourceCodeInfo { - /** DocumentRemove removedTargetIds */ - removedTargetIds?: (number[]|null); + /** SourceCodeInfo location */ + location?: (google.protobuf.SourceCodeInfo.ILocation[]|null); + } - /** DocumentRemove readTime */ - readTime?: (google.protobuf.ITimestamp|null); - } + /** Represents a SourceCodeInfo. */ + class SourceCodeInfo implements ISourceCodeInfo { - /** Represents a DocumentRemove. */ - class DocumentRemove implements IDocumentRemove { + /** + * Constructs a new SourceCodeInfo. + * @param [properties] Properties to set + */ + constructor(properties?: google.protobuf.ISourceCodeInfo); - /** - * Constructs a new DocumentRemove. - * @param [properties] Properties to set - */ - constructor(properties?: google.firestore.v1.IDocumentRemove); + /** SourceCodeInfo location. */ + public location: google.protobuf.SourceCodeInfo.ILocation[]; - /** DocumentRemove document. */ - public document: string; + /** + * Creates a SourceCodeInfo message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns SourceCodeInfo + */ + public static fromObject(object: { [k: string]: any }): google.protobuf.SourceCodeInfo; - /** DocumentRemove removedTargetIds. */ - public removedTargetIds: number[]; + /** + * Creates a plain object from a SourceCodeInfo message. Also converts values to other types if specified. + * @param message SourceCodeInfo + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.protobuf.SourceCodeInfo, options?: $protobuf.IConversionOptions): { [k: string]: any }; - /** DocumentRemove readTime. */ - public readTime?: (google.protobuf.ITimestamp|null); + /** + * Converts this SourceCodeInfo to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; - /** - * Creates a DocumentRemove message from a plain object. Also converts values to their respective internal types. - * @param object Plain object - * @returns DocumentRemove - */ - public static fromObject(object: { [k: string]: any }): google.firestore.v1.DocumentRemove; + /** + * Gets the default type url for SourceCodeInfo + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } - /** - * Creates a plain object from a DocumentRemove message. Also converts values to other types if specified. - * @param message DocumentRemove - * @param [options] Conversion options - * @returns Plain object - */ - public static toObject(message: google.firestore.v1.DocumentRemove, options?: $protobuf.IConversionOptions): { [k: string]: any }; + namespace SourceCodeInfo { - /** - * Converts this DocumentRemove to JSON. - * @returns JSON object - */ - public toJSON(): { [k: string]: any }; + /** Properties of a Location. */ + interface ILocation { - /** - * Gets the default type url for DocumentRemove - * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") - * @returns The default type url - */ - public static getTypeUrl(typeUrlPrefix?: string): string; - } + /** Location path */ + path?: (number[]|null); - /** Properties of an ExistenceFilter. */ - interface IExistenceFilter { + /** Location span */ + span?: (number[]|null); - /** ExistenceFilter targetId */ - targetId?: (number|null); + /** Location leadingComments */ + leadingComments?: (string|null); - /** ExistenceFilter count */ - count?: (number|null); + /** Location trailingComments */ + trailingComments?: (string|null); - /** ExistenceFilter unchangedNames */ - unchangedNames?: (google.firestore.v1.IBloomFilter|null); + /** Location leadingDetachedComments */ + leadingDetachedComments?: (string[]|null); } - /** Represents an ExistenceFilter. */ - class ExistenceFilter implements IExistenceFilter { + /** Represents a Location. */ + class Location implements ILocation { /** - * Constructs a new ExistenceFilter. + * Constructs a new Location. * @param [properties] Properties to set */ - constructor(properties?: google.firestore.v1.IExistenceFilter); + constructor(properties?: google.protobuf.SourceCodeInfo.ILocation); - /** ExistenceFilter targetId. */ - public targetId: number; + /** Location path. */ + public path: number[]; - /** ExistenceFilter count. */ - public count: number; + /** Location span. */ + public span: number[]; - /** ExistenceFilter unchangedNames. */ - public unchangedNames?: (google.firestore.v1.IBloomFilter|null); + /** Location leadingComments. */ + public leadingComments: string; + + /** Location trailingComments. */ + public trailingComments: string; + + /** Location leadingDetachedComments. */ + public leadingDetachedComments: string[]; /** - * Creates an ExistenceFilter message from a plain object. Also converts values to their respective internal types. + * Creates a Location message from a plain object. Also converts values to their respective internal types. * @param object Plain object - * @returns ExistenceFilter + * @returns Location */ - public static fromObject(object: { [k: string]: any }): google.firestore.v1.ExistenceFilter; + public static fromObject(object: { [k: string]: any }): google.protobuf.SourceCodeInfo.Location; /** - * Creates a plain object from an ExistenceFilter message. Also converts values to other types if specified. - * @param message ExistenceFilter + * Creates a plain object from a Location message. Also converts values to other types if specified. + * @param message Location * @param [options] Conversion options * @returns Plain object */ - public static toObject(message: google.firestore.v1.ExistenceFilter, options?: $protobuf.IConversionOptions): { [k: string]: any }; + public static toObject(message: google.protobuf.SourceCodeInfo.Location, options?: $protobuf.IConversionOptions): { [k: string]: any }; /** - * Converts this ExistenceFilter to JSON. + * Converts this Location to JSON. * @returns JSON object */ public toJSON(): { [k: string]: any }; /** - * Gets the default type url for ExistenceFilter + * Gets the default type url for Location * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") * @returns The default type url */ public static getTypeUrl(typeUrlPrefix?: string): string; } } - } - - /** Namespace type. */ - namespace type { - - /** Properties of a LatLng. */ - interface ILatLng { - /** LatLng latitude */ - latitude?: (number|null); + /** Properties of a GeneratedCodeInfo. */ + interface IGeneratedCodeInfo { - /** LatLng longitude */ - longitude?: (number|null); + /** GeneratedCodeInfo annotation */ + annotation?: (google.protobuf.GeneratedCodeInfo.IAnnotation[]|null); } - /** Represents a LatLng. */ - class LatLng implements ILatLng { + /** Represents a GeneratedCodeInfo. */ + class GeneratedCodeInfo implements IGeneratedCodeInfo { /** - * Constructs a new LatLng. + * Constructs a new GeneratedCodeInfo. * @param [properties] Properties to set */ - constructor(properties?: google.type.ILatLng); - - /** LatLng latitude. */ - public latitude: number; + constructor(properties?: google.protobuf.IGeneratedCodeInfo); - /** LatLng longitude. */ - public longitude: number; + /** GeneratedCodeInfo annotation. */ + public annotation: google.protobuf.GeneratedCodeInfo.IAnnotation[]; /** - * Creates a LatLng message from a plain object. Also converts values to their respective internal types. + * Creates a GeneratedCodeInfo message from a plain object. Also converts values to their respective internal types. * @param object Plain object - * @returns LatLng + * @returns GeneratedCodeInfo */ - public static fromObject(object: { [k: string]: any }): google.type.LatLng; + public static fromObject(object: { [k: string]: any }): google.protobuf.GeneratedCodeInfo; /** - * Creates a plain object from a LatLng message. Also converts values to other types if specified. - * @param message LatLng + * Creates a plain object from a GeneratedCodeInfo message. Also converts values to other types if specified. + * @param message GeneratedCodeInfo * @param [options] Conversion options * @returns Plain object */ - public static toObject(message: google.type.LatLng, options?: $protobuf.IConversionOptions): { [k: string]: any }; + public static toObject(message: google.protobuf.GeneratedCodeInfo, options?: $protobuf.IConversionOptions): { [k: string]: any }; /** - * Converts this LatLng to JSON. + * Converts this GeneratedCodeInfo to JSON. * @returns JSON object */ public toJSON(): { [k: string]: any }; /** - * Gets the default type url for LatLng + * Gets the default type url for GeneratedCodeInfo * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") * @returns The default type url */ public static getTypeUrl(typeUrlPrefix?: string): string; } - /** DayOfWeek enum. */ - type DayOfWeek = - "DAY_OF_WEEK_UNSPECIFIED"| "MONDAY"| "TUESDAY"| "WEDNESDAY"| "THURSDAY"| "FRIDAY"| "SATURDAY"| "SUNDAY"; - } - - /** Namespace api. */ - namespace api { - - /** Properties of a Http. */ - interface IHttp { - - /** Http rules */ - rules?: (google.api.IHttpRule[]|null); - - /** Http fullyDecodeReservedExpansion */ - fullyDecodeReservedExpansion?: (boolean|null); - } - - /** Represents a Http. */ - class Http implements IHttp { - - /** - * Constructs a new Http. - * @param [properties] Properties to set - */ - constructor(properties?: google.api.IHttp); - - /** Http rules. */ - public rules: google.api.IHttpRule[]; - - /** Http fullyDecodeReservedExpansion. */ - public fullyDecodeReservedExpansion: boolean; - - /** - * Creates a Http message from a plain object. Also converts values to their respective internal types. - * @param object Plain object - * @returns Http - */ - public static fromObject(object: { [k: string]: any }): google.api.Http; - - /** - * Creates a plain object from a Http message. Also converts values to other types if specified. - * @param message Http - * @param [options] Conversion options - * @returns Plain object - */ - public static toObject(message: google.api.Http, options?: $protobuf.IConversionOptions): { [k: string]: any }; - - /** - * Converts this Http to JSON. - * @returns JSON object - */ - public toJSON(): { [k: string]: any }; - - /** - * Gets the default type url for Http - * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") - * @returns The default type url - */ - public static getTypeUrl(typeUrlPrefix?: string): string; - } + namespace GeneratedCodeInfo { - /** Properties of a HttpRule. */ - interface IHttpRule { + /** Properties of an Annotation. */ + interface IAnnotation { - /** HttpRule selector */ - selector?: (string|null); + /** Annotation path */ + path?: (number[]|null); - /** HttpRule get */ - get?: (string|null); + /** Annotation sourceFile */ + sourceFile?: (string|null); - /** HttpRule put */ - put?: (string|null); + /** Annotation begin */ + begin?: (number|null); - /** HttpRule post */ - post?: (string|null); + /** Annotation end */ + end?: (number|null); - /** HttpRule delete */ - "delete"?: (string|null); + /** Annotation semantic */ + semantic?: (google.protobuf.GeneratedCodeInfo.Annotation.Semantic|null); + } - /** HttpRule patch */ - patch?: (string|null); + /** Represents an Annotation. */ + class Annotation implements IAnnotation { - /** HttpRule custom */ - custom?: (google.api.ICustomHttpPattern|null); + /** + * Constructs a new Annotation. + * @param [properties] Properties to set + */ + constructor(properties?: google.protobuf.GeneratedCodeInfo.IAnnotation); - /** HttpRule body */ - body?: (string|null); + /** Annotation path. */ + public path: number[]; - /** HttpRule responseBody */ - responseBody?: (string|null); + /** Annotation sourceFile. */ + public sourceFile: string; - /** HttpRule additionalBindings */ - additionalBindings?: (google.api.IHttpRule[]|null); - } + /** Annotation begin. */ + public begin: number; - /** Represents a HttpRule. */ - class HttpRule implements IHttpRule { + /** Annotation end. */ + public end: number; - /** - * Constructs a new HttpRule. - * @param [properties] Properties to set - */ - constructor(properties?: google.api.IHttpRule); + /** Annotation semantic. */ + public semantic: google.protobuf.GeneratedCodeInfo.Annotation.Semantic; - /** HttpRule selector. */ - public selector: string; + /** + * Creates an Annotation message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns Annotation + */ + public static fromObject(object: { [k: string]: any }): google.protobuf.GeneratedCodeInfo.Annotation; - /** HttpRule get. */ - public get?: (string|null); + /** + * Creates a plain object from an Annotation message. Also converts values to other types if specified. + * @param message Annotation + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.protobuf.GeneratedCodeInfo.Annotation, options?: $protobuf.IConversionOptions): { [k: string]: any }; - /** HttpRule put. */ - public put?: (string|null); + /** + * Converts this Annotation to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; - /** HttpRule post. */ - public post?: (string|null); + /** + * Gets the default type url for Annotation + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } - /** HttpRule delete. */ - public delete?: (string|null); + namespace Annotation { - /** HttpRule patch. */ - public patch?: (string|null); + /** Semantic enum. */ + type Semantic = + "NONE"| "SET"| "ALIAS"; + } + } - /** HttpRule custom. */ - public custom?: (google.api.ICustomHttpPattern|null); + /** Properties of a Struct. */ + interface IStruct { - /** HttpRule body. */ - public body: string; + /** Struct fields */ + fields?: ({ [k: string]: google.protobuf.IValue }|null); + } - /** HttpRule responseBody. */ - public responseBody: string; + /** Represents a Struct. */ + class Struct implements IStruct { - /** HttpRule additionalBindings. */ - public additionalBindings: google.api.IHttpRule[]; + /** + * Constructs a new Struct. + * @param [properties] Properties to set + */ + constructor(properties?: google.protobuf.IStruct); - /** HttpRule pattern. */ - public pattern?: ("get"|"put"|"post"|"delete"|"patch"|"custom"); + /** Struct fields. */ + public fields: { [k: string]: google.protobuf.IValue }; /** - * Creates a HttpRule message from a plain object. Also converts values to their respective internal types. + * Creates a Struct message from a plain object. Also converts values to their respective internal types. * @param object Plain object - * @returns HttpRule + * @returns Struct */ - public static fromObject(object: { [k: string]: any }): google.api.HttpRule; + public static fromObject(object: { [k: string]: any }): google.protobuf.Struct; /** - * Creates a plain object from a HttpRule message. Also converts values to other types if specified. - * @param message HttpRule + * Creates a plain object from a Struct message. Also converts values to other types if specified. + * @param message Struct * @param [options] Conversion options * @returns Plain object */ - public static toObject(message: google.api.HttpRule, options?: $protobuf.IConversionOptions): { [k: string]: any }; + public static toObject(message: google.protobuf.Struct, options?: $protobuf.IConversionOptions): { [k: string]: any }; /** - * Converts this HttpRule to JSON. + * Converts this Struct to JSON. * @returns JSON object */ public toJSON(): { [k: string]: any }; /** - * Gets the default type url for HttpRule + * Gets the default type url for Struct * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") * @returns The default type url */ public static getTypeUrl(typeUrlPrefix?: string): string; } - /** Properties of a CustomHttpPattern. */ - interface ICustomHttpPattern { + /** Properties of a Value. */ + interface IValue { - /** CustomHttpPattern kind */ - kind?: (string|null); + /** Value nullValue */ + nullValue?: (google.protobuf.NullValue|null); - /** CustomHttpPattern path */ - path?: (string|null); + /** Value numberValue */ + numberValue?: (number|null); + + /** Value stringValue */ + stringValue?: (string|null); + + /** Value boolValue */ + boolValue?: (boolean|null); + + /** Value structValue */ + structValue?: (google.protobuf.IStruct|null); + + /** Value listValue */ + listValue?: (google.protobuf.IListValue|null); } - /** Represents a CustomHttpPattern. */ - class CustomHttpPattern implements ICustomHttpPattern { + /** Represents a Value. */ + class Value implements IValue { /** - * Constructs a new CustomHttpPattern. + * Constructs a new Value. * @param [properties] Properties to set */ - constructor(properties?: google.api.ICustomHttpPattern); + constructor(properties?: google.protobuf.IValue); - /** CustomHttpPattern kind. */ - public kind: string; + /** Value nullValue. */ + public nullValue?: (google.protobuf.NullValue|null); - /** CustomHttpPattern path. */ - public path: string; + /** Value numberValue. */ + public numberValue?: (number|null); + + /** Value stringValue. */ + public stringValue?: (string|null); + + /** Value boolValue. */ + public boolValue?: (boolean|null); + + /** Value structValue. */ + public structValue?: (google.protobuf.IStruct|null); + + /** Value listValue. */ + public listValue?: (google.protobuf.IListValue|null); + + /** Value kind. */ + public kind?: ("nullValue"|"numberValue"|"stringValue"|"boolValue"|"structValue"|"listValue"); /** - * Creates a CustomHttpPattern message from a plain object. Also converts values to their respective internal types. + * Creates a Value message from a plain object. Also converts values to their respective internal types. * @param object Plain object - * @returns CustomHttpPattern + * @returns Value */ - public static fromObject(object: { [k: string]: any }): google.api.CustomHttpPattern; + public static fromObject(object: { [k: string]: any }): google.protobuf.Value; /** - * Creates a plain object from a CustomHttpPattern message. Also converts values to other types if specified. - * @param message CustomHttpPattern + * Creates a plain object from a Value message. Also converts values to other types if specified. + * @param message Value * @param [options] Conversion options * @returns Plain object */ - public static toObject(message: google.api.CustomHttpPattern, options?: $protobuf.IConversionOptions): { [k: string]: any }; + public static toObject(message: google.protobuf.Value, options?: $protobuf.IConversionOptions): { [k: string]: any }; /** - * Converts this CustomHttpPattern to JSON. + * Converts this Value to JSON. * @returns JSON object */ public toJSON(): { [k: string]: any }; /** - * Gets the default type url for CustomHttpPattern + * Gets the default type url for Value * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") * @returns The default type url */ public static getTypeUrl(typeUrlPrefix?: string): string; } - /** Properties of a CommonLanguageSettings. */ - interface ICommonLanguageSettings { + /** NullValue enum. */ + type NullValue = + "NULL_VALUE"; - /** CommonLanguageSettings referenceDocsUri */ - referenceDocsUri?: (string|null); + /** Properties of a ListValue. */ + interface IListValue { - /** CommonLanguageSettings destinations */ - destinations?: (google.api.ClientLibraryDestination[]|null); + /** ListValue values */ + values?: (google.protobuf.IValue[]|null); } - /** Represents a CommonLanguageSettings. */ - class CommonLanguageSettings implements ICommonLanguageSettings { + /** Represents a ListValue. */ + class ListValue implements IListValue { /** - * Constructs a new CommonLanguageSettings. + * Constructs a new ListValue. * @param [properties] Properties to set */ - constructor(properties?: google.api.ICommonLanguageSettings); - - /** CommonLanguageSettings referenceDocsUri. */ - public referenceDocsUri: string; + constructor(properties?: google.protobuf.IListValue); - /** CommonLanguageSettings destinations. */ - public destinations: google.api.ClientLibraryDestination[]; + /** ListValue values. */ + public values: google.protobuf.IValue[]; /** - * Creates a CommonLanguageSettings message from a plain object. Also converts values to their respective internal types. + * Creates a ListValue message from a plain object. Also converts values to their respective internal types. * @param object Plain object - * @returns CommonLanguageSettings + * @returns ListValue */ - public static fromObject(object: { [k: string]: any }): google.api.CommonLanguageSettings; + public static fromObject(object: { [k: string]: any }): google.protobuf.ListValue; /** - * Creates a plain object from a CommonLanguageSettings message. Also converts values to other types if specified. - * @param message CommonLanguageSettings + * Creates a plain object from a ListValue message. Also converts values to other types if specified. + * @param message ListValue * @param [options] Conversion options * @returns Plain object */ - public static toObject(message: google.api.CommonLanguageSettings, options?: $protobuf.IConversionOptions): { [k: string]: any }; + public static toObject(message: google.protobuf.ListValue, options?: $protobuf.IConversionOptions): { [k: string]: any }; /** - * Converts this CommonLanguageSettings to JSON. + * Converts this ListValue to JSON. * @returns JSON object */ public toJSON(): { [k: string]: any }; /** - * Gets the default type url for CommonLanguageSettings + * Gets the default type url for ListValue * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") * @returns The default type url */ public static getTypeUrl(typeUrlPrefix?: string): string; } - /** Properties of a ClientLibrarySettings. */ - interface IClientLibrarySettings { - - /** ClientLibrarySettings version */ - version?: (string|null); - - /** ClientLibrarySettings launchStage */ - launchStage?: (google.api.LaunchStage|null); - - /** ClientLibrarySettings restNumericEnums */ - restNumericEnums?: (boolean|null); - - /** ClientLibrarySettings javaSettings */ - javaSettings?: (google.api.IJavaSettings|null); - - /** ClientLibrarySettings cppSettings */ - cppSettings?: (google.api.ICppSettings|null); - - /** ClientLibrarySettings phpSettings */ - phpSettings?: (google.api.IPhpSettings|null); - - /** ClientLibrarySettings pythonSettings */ - pythonSettings?: (google.api.IPythonSettings|null); - - /** ClientLibrarySettings nodeSettings */ - nodeSettings?: (google.api.INodeSettings|null); - - /** ClientLibrarySettings dotnetSettings */ - dotnetSettings?: (google.api.IDotnetSettings|null); + /** Properties of a Timestamp. */ + interface ITimestamp { - /** ClientLibrarySettings rubySettings */ - rubySettings?: (google.api.IRubySettings|null); + /** Timestamp seconds */ + seconds?: (number|string|null); - /** ClientLibrarySettings goSettings */ - goSettings?: (google.api.IGoSettings|null); + /** Timestamp nanos */ + nanos?: (number|null); } - /** Represents a ClientLibrarySettings. */ - class ClientLibrarySettings implements IClientLibrarySettings { + /** Represents a Timestamp. */ + class Timestamp implements ITimestamp { /** - * Constructs a new ClientLibrarySettings. + * Constructs a new Timestamp. * @param [properties] Properties to set */ - constructor(properties?: google.api.IClientLibrarySettings); - - /** ClientLibrarySettings version. */ - public version: string; - - /** ClientLibrarySettings launchStage. */ - public launchStage: google.api.LaunchStage; - - /** ClientLibrarySettings restNumericEnums. */ - public restNumericEnums: boolean; - - /** ClientLibrarySettings javaSettings. */ - public javaSettings?: (google.api.IJavaSettings|null); - - /** ClientLibrarySettings cppSettings. */ - public cppSettings?: (google.api.ICppSettings|null); - - /** ClientLibrarySettings phpSettings. */ - public phpSettings?: (google.api.IPhpSettings|null); - - /** ClientLibrarySettings pythonSettings. */ - public pythonSettings?: (google.api.IPythonSettings|null); - - /** ClientLibrarySettings nodeSettings. */ - public nodeSettings?: (google.api.INodeSettings|null); - - /** ClientLibrarySettings dotnetSettings. */ - public dotnetSettings?: (google.api.IDotnetSettings|null); + constructor(properties?: google.protobuf.ITimestamp); - /** ClientLibrarySettings rubySettings. */ - public rubySettings?: (google.api.IRubySettings|null); + /** Timestamp seconds. */ + public seconds: (number|string); - /** ClientLibrarySettings goSettings. */ - public goSettings?: (google.api.IGoSettings|null); + /** Timestamp nanos. */ + public nanos: number; /** - * Creates a ClientLibrarySettings message from a plain object. Also converts values to their respective internal types. + * Creates a Timestamp message from a plain object. Also converts values to their respective internal types. * @param object Plain object - * @returns ClientLibrarySettings + * @returns Timestamp */ - public static fromObject(object: { [k: string]: any }): google.api.ClientLibrarySettings; + public static fromObject(object: { [k: string]: any }): google.protobuf.Timestamp; /** - * Creates a plain object from a ClientLibrarySettings message. Also converts values to other types if specified. - * @param message ClientLibrarySettings + * Creates a plain object from a Timestamp message. Also converts values to other types if specified. + * @param message Timestamp * @param [options] Conversion options * @returns Plain object */ - public static toObject(message: google.api.ClientLibrarySettings, options?: $protobuf.IConversionOptions): { [k: string]: any }; + public static toObject(message: google.protobuf.Timestamp, options?: $protobuf.IConversionOptions): { [k: string]: any }; /** - * Converts this ClientLibrarySettings to JSON. + * Converts this Timestamp to JSON. * @returns JSON object */ public toJSON(): { [k: string]: any }; /** - * Gets the default type url for ClientLibrarySettings + * Gets the default type url for Timestamp * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") * @returns The default type url */ public static getTypeUrl(typeUrlPrefix?: string): string; } - /** Properties of a Publishing. */ - interface IPublishing { + /** Properties of a Duration. */ + interface IDuration { - /** Publishing methodSettings */ - methodSettings?: (google.api.IMethodSettings[]|null); + /** Duration seconds */ + seconds?: (number|string|null); - /** Publishing newIssueUri */ - newIssueUri?: (string|null); + /** Duration nanos */ + nanos?: (number|null); + } - /** Publishing documentationUri */ - documentationUri?: (string|null); + /** Represents a Duration. */ + class Duration implements IDuration { - /** Publishing apiShortName */ - apiShortName?: (string|null); + /** + * Constructs a new Duration. + * @param [properties] Properties to set + */ + constructor(properties?: google.protobuf.IDuration); - /** Publishing githubLabel */ - githubLabel?: (string|null); + /** Duration seconds. */ + public seconds: (number|string); - /** Publishing codeownerGithubTeams */ - codeownerGithubTeams?: (string[]|null); + /** Duration nanos. */ + public nanos: number; - /** Publishing docTagPrefix */ - docTagPrefix?: (string|null); + /** + * Creates a Duration message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns Duration + */ + public static fromObject(object: { [k: string]: any }): google.protobuf.Duration; - /** Publishing organization */ - organization?: (google.api.ClientLibraryOrganization|null); + /** + * Creates a plain object from a Duration message. Also converts values to other types if specified. + * @param message Duration + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.protobuf.Duration, options?: $protobuf.IConversionOptions): { [k: string]: any }; - /** Publishing librarySettings */ - librarySettings?: (google.api.IClientLibrarySettings[]|null); + /** + * Converts this Duration to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; - /** Publishing protoReferenceDocumentationUri */ - protoReferenceDocumentationUri?: (string|null); + /** + * Gets the default type url for Duration + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } - /** Publishing restReferenceDocumentationUri */ - restReferenceDocumentationUri?: (string|null); + /** Properties of a DoubleValue. */ + interface IDoubleValue { + + /** DoubleValue value */ + value?: (number|null); } - /** Represents a Publishing. */ - class Publishing implements IPublishing { + /** Represents a DoubleValue. */ + class DoubleValue implements IDoubleValue { /** - * Constructs a new Publishing. + * Constructs a new DoubleValue. * @param [properties] Properties to set */ - constructor(properties?: google.api.IPublishing); - - /** Publishing methodSettings. */ - public methodSettings: google.api.IMethodSettings[]; + constructor(properties?: google.protobuf.IDoubleValue); - /** Publishing newIssueUri. */ - public newIssueUri: string; + /** DoubleValue value. */ + public value: number; - /** Publishing documentationUri. */ - public documentationUri: string; + /** + * Creates a DoubleValue message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns DoubleValue + */ + public static fromObject(object: { [k: string]: any }): google.protobuf.DoubleValue; - /** Publishing apiShortName. */ - public apiShortName: string; + /** + * Creates a plain object from a DoubleValue message. Also converts values to other types if specified. + * @param message DoubleValue + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.protobuf.DoubleValue, options?: $protobuf.IConversionOptions): { [k: string]: any }; - /** Publishing githubLabel. */ - public githubLabel: string; + /** + * Converts this DoubleValue to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; - /** Publishing codeownerGithubTeams. */ - public codeownerGithubTeams: string[]; + /** + * Gets the default type url for DoubleValue + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } - /** Publishing docTagPrefix. */ - public docTagPrefix: string; + /** Properties of a FloatValue. */ + interface IFloatValue { - /** Publishing organization. */ - public organization: google.api.ClientLibraryOrganization; + /** FloatValue value */ + value?: (number|null); + } - /** Publishing librarySettings. */ - public librarySettings: google.api.IClientLibrarySettings[]; + /** Represents a FloatValue. */ + class FloatValue implements IFloatValue { - /** Publishing protoReferenceDocumentationUri. */ - public protoReferenceDocumentationUri: string; + /** + * Constructs a new FloatValue. + * @param [properties] Properties to set + */ + constructor(properties?: google.protobuf.IFloatValue); - /** Publishing restReferenceDocumentationUri. */ - public restReferenceDocumentationUri: string; + /** FloatValue value. */ + public value: number; /** - * Creates a Publishing message from a plain object. Also converts values to their respective internal types. + * Creates a FloatValue message from a plain object. Also converts values to their respective internal types. * @param object Plain object - * @returns Publishing + * @returns FloatValue */ - public static fromObject(object: { [k: string]: any }): google.api.Publishing; + public static fromObject(object: { [k: string]: any }): google.protobuf.FloatValue; /** - * Creates a plain object from a Publishing message. Also converts values to other types if specified. - * @param message Publishing + * Creates a plain object from a FloatValue message. Also converts values to other types if specified. + * @param message FloatValue * @param [options] Conversion options * @returns Plain object */ - public static toObject(message: google.api.Publishing, options?: $protobuf.IConversionOptions): { [k: string]: any }; + public static toObject(message: google.protobuf.FloatValue, options?: $protobuf.IConversionOptions): { [k: string]: any }; /** - * Converts this Publishing to JSON. + * Converts this FloatValue to JSON. * @returns JSON object */ public toJSON(): { [k: string]: any }; /** - * Gets the default type url for Publishing + * Gets the default type url for FloatValue * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") * @returns The default type url */ public static getTypeUrl(typeUrlPrefix?: string): string; } - /** Properties of a JavaSettings. */ - interface IJavaSettings { - - /** JavaSettings libraryPackage */ - libraryPackage?: (string|null); - - /** JavaSettings serviceClassNames */ - serviceClassNames?: ({ [k: string]: string }|null); + /** Properties of an Int64Value. */ + interface IInt64Value { - /** JavaSettings common */ - common?: (google.api.ICommonLanguageSettings|null); + /** Int64Value value */ + value?: (number|string|null); } - /** Represents a JavaSettings. */ - class JavaSettings implements IJavaSettings { + /** Represents an Int64Value. */ + class Int64Value implements IInt64Value { /** - * Constructs a new JavaSettings. + * Constructs a new Int64Value. * @param [properties] Properties to set */ - constructor(properties?: google.api.IJavaSettings); - - /** JavaSettings libraryPackage. */ - public libraryPackage: string; - - /** JavaSettings serviceClassNames. */ - public serviceClassNames: { [k: string]: string }; + constructor(properties?: google.protobuf.IInt64Value); - /** JavaSettings common. */ - public common?: (google.api.ICommonLanguageSettings|null); + /** Int64Value value. */ + public value: (number|string); /** - * Creates a JavaSettings message from a plain object. Also converts values to their respective internal types. + * Creates an Int64Value message from a plain object. Also converts values to their respective internal types. * @param object Plain object - * @returns JavaSettings + * @returns Int64Value */ - public static fromObject(object: { [k: string]: any }): google.api.JavaSettings; + public static fromObject(object: { [k: string]: any }): google.protobuf.Int64Value; /** - * Creates a plain object from a JavaSettings message. Also converts values to other types if specified. - * @param message JavaSettings + * Creates a plain object from an Int64Value message. Also converts values to other types if specified. + * @param message Int64Value * @param [options] Conversion options * @returns Plain object */ - public static toObject(message: google.api.JavaSettings, options?: $protobuf.IConversionOptions): { [k: string]: any }; + public static toObject(message: google.protobuf.Int64Value, options?: $protobuf.IConversionOptions): { [k: string]: any }; /** - * Converts this JavaSettings to JSON. + * Converts this Int64Value to JSON. * @returns JSON object */ public toJSON(): { [k: string]: any }; /** - * Gets the default type url for JavaSettings + * Gets the default type url for Int64Value * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") * @returns The default type url */ public static getTypeUrl(typeUrlPrefix?: string): string; } - /** Properties of a CppSettings. */ - interface ICppSettings { + /** Properties of a UInt64Value. */ + interface IUInt64Value { - /** CppSettings common */ - common?: (google.api.ICommonLanguageSettings|null); + /** UInt64Value value */ + value?: (number|string|null); } - /** Represents a CppSettings. */ - class CppSettings implements ICppSettings { + /** Represents a UInt64Value. */ + class UInt64Value implements IUInt64Value { /** - * Constructs a new CppSettings. + * Constructs a new UInt64Value. * @param [properties] Properties to set */ - constructor(properties?: google.api.ICppSettings); + constructor(properties?: google.protobuf.IUInt64Value); - /** CppSettings common. */ - public common?: (google.api.ICommonLanguageSettings|null); + /** UInt64Value value. */ + public value: (number|string); /** - * Creates a CppSettings message from a plain object. Also converts values to their respective internal types. + * Creates a UInt64Value message from a plain object. Also converts values to their respective internal types. * @param object Plain object - * @returns CppSettings + * @returns UInt64Value */ - public static fromObject(object: { [k: string]: any }): google.api.CppSettings; + public static fromObject(object: { [k: string]: any }): google.protobuf.UInt64Value; /** - * Creates a plain object from a CppSettings message. Also converts values to other types if specified. - * @param message CppSettings + * Creates a plain object from a UInt64Value message. Also converts values to other types if specified. + * @param message UInt64Value * @param [options] Conversion options * @returns Plain object */ - public static toObject(message: google.api.CppSettings, options?: $protobuf.IConversionOptions): { [k: string]: any }; + public static toObject(message: google.protobuf.UInt64Value, options?: $protobuf.IConversionOptions): { [k: string]: any }; /** - * Converts this CppSettings to JSON. + * Converts this UInt64Value to JSON. * @returns JSON object */ public toJSON(): { [k: string]: any }; /** - * Gets the default type url for CppSettings + * Gets the default type url for UInt64Value * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") * @returns The default type url */ public static getTypeUrl(typeUrlPrefix?: string): string; } - /** Properties of a PhpSettings. */ - interface IPhpSettings { + /** Properties of an Int32Value. */ + interface IInt32Value { - /** PhpSettings common */ - common?: (google.api.ICommonLanguageSettings|null); + /** Int32Value value */ + value?: (number|null); } - /** Represents a PhpSettings. */ - class PhpSettings implements IPhpSettings { + /** Represents an Int32Value. */ + class Int32Value implements IInt32Value { /** - * Constructs a new PhpSettings. + * Constructs a new Int32Value. * @param [properties] Properties to set */ - constructor(properties?: google.api.IPhpSettings); + constructor(properties?: google.protobuf.IInt32Value); - /** PhpSettings common. */ - public common?: (google.api.ICommonLanguageSettings|null); + /** Int32Value value. */ + public value: number; /** - * Creates a PhpSettings message from a plain object. Also converts values to their respective internal types. + * Creates an Int32Value message from a plain object. Also converts values to their respective internal types. * @param object Plain object - * @returns PhpSettings + * @returns Int32Value */ - public static fromObject(object: { [k: string]: any }): google.api.PhpSettings; + public static fromObject(object: { [k: string]: any }): google.protobuf.Int32Value; /** - * Creates a plain object from a PhpSettings message. Also converts values to other types if specified. - * @param message PhpSettings + * Creates a plain object from an Int32Value message. Also converts values to other types if specified. + * @param message Int32Value * @param [options] Conversion options * @returns Plain object */ - public static toObject(message: google.api.PhpSettings, options?: $protobuf.IConversionOptions): { [k: string]: any }; + public static toObject(message: google.protobuf.Int32Value, options?: $protobuf.IConversionOptions): { [k: string]: any }; /** - * Converts this PhpSettings to JSON. + * Converts this Int32Value to JSON. * @returns JSON object */ public toJSON(): { [k: string]: any }; /** - * Gets the default type url for PhpSettings + * Gets the default type url for Int32Value * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") * @returns The default type url */ public static getTypeUrl(typeUrlPrefix?: string): string; } - /** Properties of a PythonSettings. */ - interface IPythonSettings { + /** Properties of a UInt32Value. */ + interface IUInt32Value { - /** PythonSettings common */ - common?: (google.api.ICommonLanguageSettings|null); + /** UInt32Value value */ + value?: (number|null); } - /** Represents a PythonSettings. */ - class PythonSettings implements IPythonSettings { + /** Represents a UInt32Value. */ + class UInt32Value implements IUInt32Value { /** - * Constructs a new PythonSettings. + * Constructs a new UInt32Value. * @param [properties] Properties to set */ - constructor(properties?: google.api.IPythonSettings); + constructor(properties?: google.protobuf.IUInt32Value); - /** PythonSettings common. */ - public common?: (google.api.ICommonLanguageSettings|null); + /** UInt32Value value. */ + public value: number; /** - * Creates a PythonSettings message from a plain object. Also converts values to their respective internal types. + * Creates a UInt32Value message from a plain object. Also converts values to their respective internal types. * @param object Plain object - * @returns PythonSettings + * @returns UInt32Value */ - public static fromObject(object: { [k: string]: any }): google.api.PythonSettings; + public static fromObject(object: { [k: string]: any }): google.protobuf.UInt32Value; /** - * Creates a plain object from a PythonSettings message. Also converts values to other types if specified. - * @param message PythonSettings + * Creates a plain object from a UInt32Value message. Also converts values to other types if specified. + * @param message UInt32Value * @param [options] Conversion options * @returns Plain object */ - public static toObject(message: google.api.PythonSettings, options?: $protobuf.IConversionOptions): { [k: string]: any }; + public static toObject(message: google.protobuf.UInt32Value, options?: $protobuf.IConversionOptions): { [k: string]: any }; /** - * Converts this PythonSettings to JSON. + * Converts this UInt32Value to JSON. * @returns JSON object */ public toJSON(): { [k: string]: any }; /** - * Gets the default type url for PythonSettings + * Gets the default type url for UInt32Value * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") * @returns The default type url */ public static getTypeUrl(typeUrlPrefix?: string): string; } - /** Properties of a NodeSettings. */ - interface INodeSettings { + /** Properties of a BoolValue. */ + interface IBoolValue { - /** NodeSettings common */ - common?: (google.api.ICommonLanguageSettings|null); + /** BoolValue value */ + value?: (boolean|null); } - /** Represents a NodeSettings. */ - class NodeSettings implements INodeSettings { + /** Represents a BoolValue. */ + class BoolValue implements IBoolValue { /** - * Constructs a new NodeSettings. + * Constructs a new BoolValue. * @param [properties] Properties to set */ - constructor(properties?: google.api.INodeSettings); + constructor(properties?: google.protobuf.IBoolValue); - /** NodeSettings common. */ - public common?: (google.api.ICommonLanguageSettings|null); + /** BoolValue value. */ + public value: boolean; /** - * Creates a NodeSettings message from a plain object. Also converts values to their respective internal types. + * Creates a BoolValue message from a plain object. Also converts values to their respective internal types. * @param object Plain object - * @returns NodeSettings + * @returns BoolValue */ - public static fromObject(object: { [k: string]: any }): google.api.NodeSettings; + public static fromObject(object: { [k: string]: any }): google.protobuf.BoolValue; /** - * Creates a plain object from a NodeSettings message. Also converts values to other types if specified. - * @param message NodeSettings + * Creates a plain object from a BoolValue message. Also converts values to other types if specified. + * @param message BoolValue * @param [options] Conversion options * @returns Plain object */ - public static toObject(message: google.api.NodeSettings, options?: $protobuf.IConversionOptions): { [k: string]: any }; + public static toObject(message: google.protobuf.BoolValue, options?: $protobuf.IConversionOptions): { [k: string]: any }; /** - * Converts this NodeSettings to JSON. + * Converts this BoolValue to JSON. * @returns JSON object */ public toJSON(): { [k: string]: any }; /** - * Gets the default type url for NodeSettings + * Gets the default type url for BoolValue * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") * @returns The default type url */ public static getTypeUrl(typeUrlPrefix?: string): string; } - /** Properties of a DotnetSettings. */ - interface IDotnetSettings { - - /** DotnetSettings common */ - common?: (google.api.ICommonLanguageSettings|null); - - /** DotnetSettings renamedServices */ - renamedServices?: ({ [k: string]: string }|null); - - /** DotnetSettings renamedResources */ - renamedResources?: ({ [k: string]: string }|null); - - /** DotnetSettings ignoredResources */ - ignoredResources?: (string[]|null); - - /** DotnetSettings forcedNamespaceAliases */ - forcedNamespaceAliases?: (string[]|null); + /** Properties of a StringValue. */ + interface IStringValue { - /** DotnetSettings handwrittenSignatures */ - handwrittenSignatures?: (string[]|null); + /** StringValue value */ + value?: (string|null); } - /** Represents a DotnetSettings. */ - class DotnetSettings implements IDotnetSettings { + /** Represents a StringValue. */ + class StringValue implements IStringValue { /** - * Constructs a new DotnetSettings. + * Constructs a new StringValue. * @param [properties] Properties to set */ - constructor(properties?: google.api.IDotnetSettings); - - /** DotnetSettings common. */ - public common?: (google.api.ICommonLanguageSettings|null); - - /** DotnetSettings renamedServices. */ - public renamedServices: { [k: string]: string }; - - /** DotnetSettings renamedResources. */ - public renamedResources: { [k: string]: string }; - - /** DotnetSettings ignoredResources. */ - public ignoredResources: string[]; - - /** DotnetSettings forcedNamespaceAliases. */ - public forcedNamespaceAliases: string[]; + constructor(properties?: google.protobuf.IStringValue); - /** DotnetSettings handwrittenSignatures. */ - public handwrittenSignatures: string[]; + /** StringValue value. */ + public value: string; /** - * Creates a DotnetSettings message from a plain object. Also converts values to their respective internal types. + * Creates a StringValue message from a plain object. Also converts values to their respective internal types. * @param object Plain object - * @returns DotnetSettings + * @returns StringValue */ - public static fromObject(object: { [k: string]: any }): google.api.DotnetSettings; + public static fromObject(object: { [k: string]: any }): google.protobuf.StringValue; /** - * Creates a plain object from a DotnetSettings message. Also converts values to other types if specified. - * @param message DotnetSettings + * Creates a plain object from a StringValue message. Also converts values to other types if specified. + * @param message StringValue * @param [options] Conversion options * @returns Plain object */ - public static toObject(message: google.api.DotnetSettings, options?: $protobuf.IConversionOptions): { [k: string]: any }; + public static toObject(message: google.protobuf.StringValue, options?: $protobuf.IConversionOptions): { [k: string]: any }; /** - * Converts this DotnetSettings to JSON. + * Converts this StringValue to JSON. * @returns JSON object */ public toJSON(): { [k: string]: any }; /** - * Gets the default type url for DotnetSettings + * Gets the default type url for StringValue * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") * @returns The default type url */ public static getTypeUrl(typeUrlPrefix?: string): string; } - /** Properties of a RubySettings. */ - interface IRubySettings { + /** Properties of a BytesValue. */ + interface IBytesValue { - /** RubySettings common */ - common?: (google.api.ICommonLanguageSettings|null); + /** BytesValue value */ + value?: (Uint8Array|null); } - /** Represents a RubySettings. */ - class RubySettings implements IRubySettings { + /** Represents a BytesValue. */ + class BytesValue implements IBytesValue { /** - * Constructs a new RubySettings. + * Constructs a new BytesValue. * @param [properties] Properties to set */ - constructor(properties?: google.api.IRubySettings); + constructor(properties?: google.protobuf.IBytesValue); - /** RubySettings common. */ - public common?: (google.api.ICommonLanguageSettings|null); + /** BytesValue value. */ + public value: Uint8Array; /** - * Creates a RubySettings message from a plain object. Also converts values to their respective internal types. + * Creates a BytesValue message from a plain object. Also converts values to their respective internal types. * @param object Plain object - * @returns RubySettings + * @returns BytesValue */ - public static fromObject(object: { [k: string]: any }): google.api.RubySettings; + public static fromObject(object: { [k: string]: any }): google.protobuf.BytesValue; /** - * Creates a plain object from a RubySettings message. Also converts values to other types if specified. - * @param message RubySettings + * Creates a plain object from a BytesValue message. Also converts values to other types if specified. + * @param message BytesValue * @param [options] Conversion options * @returns Plain object */ - public static toObject(message: google.api.RubySettings, options?: $protobuf.IConversionOptions): { [k: string]: any }; + public static toObject(message: google.protobuf.BytesValue, options?: $protobuf.IConversionOptions): { [k: string]: any }; /** - * Converts this RubySettings to JSON. + * Converts this BytesValue to JSON. * @returns JSON object */ public toJSON(): { [k: string]: any }; /** - * Gets the default type url for RubySettings + * Gets the default type url for BytesValue * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") * @returns The default type url */ public static getTypeUrl(typeUrlPrefix?: string): string; } - /** Properties of a GoSettings. */ - interface IGoSettings { - - /** GoSettings common */ - common?: (google.api.ICommonLanguageSettings|null); + /** Properties of an Empty. */ + interface IEmpty { } - /** Represents a GoSettings. */ - class GoSettings implements IGoSettings { + /** Represents an Empty. */ + class Empty implements IEmpty { /** - * Constructs a new GoSettings. + * Constructs a new Empty. * @param [properties] Properties to set */ - constructor(properties?: google.api.IGoSettings); - - /** GoSettings common. */ - public common?: (google.api.ICommonLanguageSettings|null); + constructor(properties?: google.protobuf.IEmpty); /** - * Creates a GoSettings message from a plain object. Also converts values to their respective internal types. + * Creates an Empty message from a plain object. Also converts values to their respective internal types. * @param object Plain object - * @returns GoSettings + * @returns Empty */ - public static fromObject(object: { [k: string]: any }): google.api.GoSettings; + public static fromObject(object: { [k: string]: any }): google.protobuf.Empty; /** - * Creates a plain object from a GoSettings message. Also converts values to other types if specified. - * @param message GoSettings + * Creates a plain object from an Empty message. Also converts values to other types if specified. + * @param message Empty * @param [options] Conversion options * @returns Plain object */ - public static toObject(message: google.api.GoSettings, options?: $protobuf.IConversionOptions): { [k: string]: any }; + public static toObject(message: google.protobuf.Empty, options?: $protobuf.IConversionOptions): { [k: string]: any }; /** - * Converts this GoSettings to JSON. + * Converts this Empty to JSON. * @returns JSON object */ public toJSON(): { [k: string]: any }; /** - * Gets the default type url for GoSettings + * Gets the default type url for Empty * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") * @returns The default type url */ public static getTypeUrl(typeUrlPrefix?: string): string; } - /** Properties of a MethodSettings. */ - interface IMethodSettings { - - /** MethodSettings selector */ - selector?: (string|null); - - /** MethodSettings longRunning */ - longRunning?: (google.api.MethodSettings.ILongRunning|null); + /** Properties of an Any. */ + interface IAny { - /** MethodSettings autoPopulatedFields */ - autoPopulatedFields?: (string[]|null); + /** Any type_url */ + type_url?: (string|null); + + /** Any value */ + value?: (Uint8Array|null); } - /** Represents a MethodSettings. */ - class MethodSettings implements IMethodSettings { + /** Represents an Any. */ + class Any implements IAny { /** - * Constructs a new MethodSettings. + * Constructs a new Any. * @param [properties] Properties to set */ - constructor(properties?: google.api.IMethodSettings); - - /** MethodSettings selector. */ - public selector: string; + constructor(properties?: google.protobuf.IAny); - /** MethodSettings longRunning. */ - public longRunning?: (google.api.MethodSettings.ILongRunning|null); + /** Any type_url. */ + public type_url: string; - /** MethodSettings autoPopulatedFields. */ - public autoPopulatedFields: string[]; + /** Any value. */ + public value: Uint8Array; /** - * Creates a MethodSettings message from a plain object. Also converts values to their respective internal types. + * Creates an Any message from a plain object. Also converts values to their respective internal types. * @param object Plain object - * @returns MethodSettings + * @returns Any */ - public static fromObject(object: { [k: string]: any }): google.api.MethodSettings; + public static fromObject(object: { [k: string]: any }): google.protobuf.Any; /** - * Creates a plain object from a MethodSettings message. Also converts values to other types if specified. - * @param message MethodSettings + * Creates a plain object from an Any message. Also converts values to other types if specified. + * @param message Any * @param [options] Conversion options * @returns Plain object */ - public static toObject(message: google.api.MethodSettings, options?: $protobuf.IConversionOptions): { [k: string]: any }; + public static toObject(message: google.protobuf.Any, options?: $protobuf.IConversionOptions): { [k: string]: any }; /** - * Converts this MethodSettings to JSON. + * Converts this Any to JSON. * @returns JSON object */ public toJSON(): { [k: string]: any }; /** - * Gets the default type url for MethodSettings + * Gets the default type url for Any * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") * @returns The default type url */ public static getTypeUrl(typeUrlPrefix?: string): string; } - namespace MethodSettings { - - /** Properties of a LongRunning. */ - interface ILongRunning { - - /** LongRunning initialPollDelay */ - initialPollDelay?: (google.protobuf.IDuration|null); - - /** LongRunning pollDelayMultiplier */ - pollDelayMultiplier?: (number|null); - - /** LongRunning maxPollDelay */ - maxPollDelay?: (google.protobuf.IDuration|null); - - /** LongRunning totalPollTimeout */ - totalPollTimeout?: (google.protobuf.IDuration|null); - } - - /** Represents a LongRunning. */ - class LongRunning implements ILongRunning { - - /** - * Constructs a new LongRunning. - * @param [properties] Properties to set - */ - constructor(properties?: google.api.MethodSettings.ILongRunning); - - /** LongRunning initialPollDelay. */ - public initialPollDelay?: (google.protobuf.IDuration|null); - - /** LongRunning pollDelayMultiplier. */ - public pollDelayMultiplier: number; - - /** LongRunning maxPollDelay. */ - public maxPollDelay?: (google.protobuf.IDuration|null); - - /** LongRunning totalPollTimeout. */ - public totalPollTimeout?: (google.protobuf.IDuration|null); - - /** - * Creates a LongRunning message from a plain object. Also converts values to their respective internal types. - * @param object Plain object - * @returns LongRunning - */ - public static fromObject(object: { [k: string]: any }): google.api.MethodSettings.LongRunning; - - /** - * Creates a plain object from a LongRunning message. Also converts values to other types if specified. - * @param message LongRunning - * @param [options] Conversion options - * @returns Plain object - */ - public static toObject(message: google.api.MethodSettings.LongRunning, options?: $protobuf.IConversionOptions): { [k: string]: any }; - - /** - * Converts this LongRunning to JSON. - * @returns JSON object - */ - public toJSON(): { [k: string]: any }; - - /** - * Gets the default type url for LongRunning - * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") - * @returns The default type url - */ - public static getTypeUrl(typeUrlPrefix?: string): string; - } - } - - /** ClientLibraryOrganization enum. */ - type ClientLibraryOrganization = - "CLIENT_LIBRARY_ORGANIZATION_UNSPECIFIED"| "CLOUD"| "ADS"| "PHOTOS"| "STREET_VIEW"| "SHOPPING"| "GEO"| "GENERATIVE_AI"; - - /** ClientLibraryDestination enum. */ - type ClientLibraryDestination = - "CLIENT_LIBRARY_DESTINATION_UNSPECIFIED"| "GITHUB"| "PACKAGE_MANAGER"; - - /** LaunchStage enum. */ - type LaunchStage = - "LAUNCH_STAGE_UNSPECIFIED"| "UNIMPLEMENTED"| "PRELAUNCH"| "EARLY_ACCESS"| "ALPHA"| "BETA"| "GA"| "DEPRECATED"; - - /** FieldBehavior enum. */ - type FieldBehavior = - "FIELD_BEHAVIOR_UNSPECIFIED"| "OPTIONAL"| "REQUIRED"| "OUTPUT_ONLY"| "INPUT_ONLY"| "IMMUTABLE"| "UNORDERED_LIST"| "NON_EMPTY_DEFAULT"| "IDENTIFIER"; - - /** Properties of a ResourceDescriptor. */ - interface IResourceDescriptor { - - /** ResourceDescriptor type */ - type?: (string|null); - - /** ResourceDescriptor pattern */ - pattern?: (string[]|null); - - /** ResourceDescriptor nameField */ - nameField?: (string|null); - - /** ResourceDescriptor history */ - history?: (google.api.ResourceDescriptor.History|null); - - /** ResourceDescriptor plural */ - plural?: (string|null); - - /** ResourceDescriptor singular */ - singular?: (string|null); + /** Properties of a FieldMask. */ + interface IFieldMask { - /** ResourceDescriptor style */ - style?: (google.api.ResourceDescriptor.Style[]|null); + /** FieldMask paths */ + paths?: (string[]|null); } - /** Represents a ResourceDescriptor. */ - class ResourceDescriptor implements IResourceDescriptor { + /** Represents a FieldMask. */ + class FieldMask implements IFieldMask { /** - * Constructs a new ResourceDescriptor. + * Constructs a new FieldMask. * @param [properties] Properties to set */ - constructor(properties?: google.api.IResourceDescriptor); - - /** ResourceDescriptor type. */ - public type: string; - - /** ResourceDescriptor pattern. */ - public pattern: string[]; - - /** ResourceDescriptor nameField. */ - public nameField: string; - - /** ResourceDescriptor history. */ - public history: google.api.ResourceDescriptor.History; - - /** ResourceDescriptor plural. */ - public plural: string; - - /** ResourceDescriptor singular. */ - public singular: string; + constructor(properties?: google.protobuf.IFieldMask); - /** ResourceDescriptor style. */ - public style: google.api.ResourceDescriptor.Style[]; + /** FieldMask paths. */ + public paths: string[]; /** - * Creates a ResourceDescriptor message from a plain object. Also converts values to their respective internal types. + * Creates a FieldMask message from a plain object. Also converts values to their respective internal types. * @param object Plain object - * @returns ResourceDescriptor + * @returns FieldMask */ - public static fromObject(object: { [k: string]: any }): google.api.ResourceDescriptor; + public static fromObject(object: { [k: string]: any }): google.protobuf.FieldMask; /** - * Creates a plain object from a ResourceDescriptor message. Also converts values to other types if specified. - * @param message ResourceDescriptor + * Creates a plain object from a FieldMask message. Also converts values to other types if specified. + * @param message FieldMask * @param [options] Conversion options * @returns Plain object */ - public static toObject(message: google.api.ResourceDescriptor, options?: $protobuf.IConversionOptions): { [k: string]: any }; + public static toObject(message: google.protobuf.FieldMask, options?: $protobuf.IConversionOptions): { [k: string]: any }; /** - * Converts this ResourceDescriptor to JSON. + * Converts this FieldMask to JSON. * @returns JSON object */ public toJSON(): { [k: string]: any }; /** - * Gets the default type url for ResourceDescriptor + * Gets the default type url for FieldMask * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") * @returns The default type url */ public static getTypeUrl(typeUrlPrefix?: string): string; } + } - namespace ResourceDescriptor { - - /** History enum. */ - type History = - "HISTORY_UNSPECIFIED"| "ORIGINALLY_SINGLE_PATTERN"| "FUTURE_MULTI_PATTERN"; - - /** Style enum. */ - type Style = - "STYLE_UNSPECIFIED"| "DECLARATIVE_FRIENDLY"; - } + /** Namespace type. */ + namespace type { - /** Properties of a ResourceReference. */ - interface IResourceReference { + /** Properties of a LatLng. */ + interface ILatLng { - /** ResourceReference type */ - type?: (string|null); + /** LatLng latitude */ + latitude?: (number|null); - /** ResourceReference childType */ - childType?: (string|null); + /** LatLng longitude */ + longitude?: (number|null); } - /** Represents a ResourceReference. */ - class ResourceReference implements IResourceReference { + /** Represents a LatLng. */ + class LatLng implements ILatLng { /** - * Constructs a new ResourceReference. + * Constructs a new LatLng. * @param [properties] Properties to set */ - constructor(properties?: google.api.IResourceReference); + constructor(properties?: google.type.ILatLng); - /** ResourceReference type. */ - public type: string; + /** LatLng latitude. */ + public latitude: number; - /** ResourceReference childType. */ - public childType: string; + /** LatLng longitude. */ + public longitude: number; /** - * Creates a ResourceReference message from a plain object. Also converts values to their respective internal types. + * Creates a LatLng message from a plain object. Also converts values to their respective internal types. * @param object Plain object - * @returns ResourceReference + * @returns LatLng */ - public static fromObject(object: { [k: string]: any }): google.api.ResourceReference; + public static fromObject(object: { [k: string]: any }): google.type.LatLng; /** - * Creates a plain object from a ResourceReference message. Also converts values to other types if specified. - * @param message ResourceReference + * Creates a plain object from a LatLng message. Also converts values to other types if specified. + * @param message LatLng * @param [options] Conversion options * @returns Plain object */ - public static toObject(message: google.api.ResourceReference, options?: $protobuf.IConversionOptions): { [k: string]: any }; + public static toObject(message: google.type.LatLng, options?: $protobuf.IConversionOptions): { [k: string]: any }; /** - * Converts this ResourceReference to JSON. + * Converts this LatLng to JSON. * @returns JSON object */ public toJSON(): { [k: string]: any }; /** - * Gets the default type url for ResourceReference + * Gets the default type url for LatLng * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") * @returns The default type url */ public static getTypeUrl(typeUrlPrefix?: string): string; } + + /** DayOfWeek enum. */ + type DayOfWeek = + "DAY_OF_WEEK_UNSPECIFIED"| "MONDAY"| "TUESDAY"| "WEDNESDAY"| "THURSDAY"| "FRIDAY"| "SATURDAY"| "SUNDAY"; } /** Namespace rpc. */ diff --git a/dev/protos/firestore_v1_proto_api.js b/dev/protos/firestore_v1_proto_api.js index a123ad6d9..396ac7ce4 100644 --- a/dev/protos/firestore_v1_proto_api.js +++ b/dev/protos/firestore_v1_proto_api.js @@ -859,1472 +859,1314 @@ */ var google = {}; - google.protobuf = (function() { + google.firestore = (function() { /** - * Namespace protobuf. + * Namespace firestore. * @memberof google * @namespace */ - var protobuf = {}; + var firestore = {}; - protobuf.Struct = (function() { + firestore.v1 = (function() { /** - * Properties of a Struct. - * @memberof google.protobuf - * @interface IStruct - * @property {Object.|null} [fields] Struct fields + * Namespace v1. + * @memberof google.firestore + * @namespace */ + var v1 = {}; - /** - * Constructs a new Struct. - * @memberof google.protobuf - * @classdesc Represents a Struct. - * @implements IStruct - * @constructor - * @param {google.protobuf.IStruct=} [properties] Properties to set - */ - function Struct(properties) { - this.fields = {}; - if (properties) - for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) - if (properties[keys[i]] != null) - this[keys[i]] = properties[keys[i]]; - } + v1.AggregationResult = (function() { - /** - * Struct fields. - * @member {Object.} fields - * @memberof google.protobuf.Struct - * @instance - */ - Struct.prototype.fields = $util.emptyObject; + /** + * Properties of an AggregationResult. + * @memberof google.firestore.v1 + * @interface IAggregationResult + * @property {Object.|null} [aggregateFields] AggregationResult aggregateFields + */ - /** - * Creates a Struct message from a plain object. Also converts values to their respective internal types. - * @function fromObject - * @memberof google.protobuf.Struct - * @static - * @param {Object.} object Plain object - * @returns {google.protobuf.Struct} Struct - */ - Struct.fromObject = function fromObject(object) { - if (object instanceof $root.google.protobuf.Struct) - return object; - var message = new $root.google.protobuf.Struct(); - if (object.fields) { - if (typeof object.fields !== "object") - throw TypeError(".google.protobuf.Struct.fields: object expected"); - message.fields = {}; - for (var keys = Object.keys(object.fields), i = 0; i < keys.length; ++i) { - if (typeof object.fields[keys[i]] !== "object") - throw TypeError(".google.protobuf.Struct.fields: object expected"); - message.fields[keys[i]] = $root.google.protobuf.Value.fromObject(object.fields[keys[i]]); - } + /** + * Constructs a new AggregationResult. + * @memberof google.firestore.v1 + * @classdesc Represents an AggregationResult. + * @implements IAggregationResult + * @constructor + * @param {google.firestore.v1.IAggregationResult=} [properties] Properties to set + */ + function AggregationResult(properties) { + this.aggregateFields = {}; + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; } - return message; - }; - /** - * Creates a plain object from a Struct message. Also converts values to other types if specified. - * @function toObject - * @memberof google.protobuf.Struct - * @static - * @param {google.protobuf.Struct} message Struct - * @param {$protobuf.IConversionOptions} [options] Conversion options - * @returns {Object.} Plain object - */ - Struct.toObject = function toObject(message, options) { - if (!options) - options = {}; - var object = {}; - if (options.objects || options.defaults) - object.fields = {}; - var keys2; - if (message.fields && (keys2 = Object.keys(message.fields)).length) { - object.fields = {}; - for (var j = 0; j < keys2.length; ++j) - object.fields[keys2[j]] = $root.google.protobuf.Value.toObject(message.fields[keys2[j]], options); - } - return object; - }; + /** + * AggregationResult aggregateFields. + * @member {Object.} aggregateFields + * @memberof google.firestore.v1.AggregationResult + * @instance + */ + AggregationResult.prototype.aggregateFields = $util.emptyObject; - /** - * Converts this Struct to JSON. - * @function toJSON - * @memberof google.protobuf.Struct - * @instance - * @returns {Object.} JSON object - */ - Struct.prototype.toJSON = function toJSON() { - return this.constructor.toObject(this, $protobuf.util.toJSONOptions); - }; + /** + * Creates an AggregationResult message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.firestore.v1.AggregationResult + * @static + * @param {Object.} object Plain object + * @returns {google.firestore.v1.AggregationResult} AggregationResult + */ + AggregationResult.fromObject = function fromObject(object) { + if (object instanceof $root.google.firestore.v1.AggregationResult) + return object; + var message = new $root.google.firestore.v1.AggregationResult(); + if (object.aggregateFields) { + if (typeof object.aggregateFields !== "object") + throw TypeError(".google.firestore.v1.AggregationResult.aggregateFields: object expected"); + message.aggregateFields = {}; + for (var keys = Object.keys(object.aggregateFields), i = 0; i < keys.length; ++i) { + if (typeof object.aggregateFields[keys[i]] !== "object") + throw TypeError(".google.firestore.v1.AggregationResult.aggregateFields: object expected"); + message.aggregateFields[keys[i]] = $root.google.firestore.v1.Value.fromObject(object.aggregateFields[keys[i]]); + } + } + return message; + }; - /** - * Gets the default type url for Struct - * @function getTypeUrl - * @memberof google.protobuf.Struct - * @static - * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") - * @returns {string} The default type url - */ - Struct.getTypeUrl = function getTypeUrl(typeUrlPrefix) { - if (typeUrlPrefix === undefined) { - typeUrlPrefix = "type.googleapis.com"; - } - return typeUrlPrefix + "/google.protobuf.Struct"; - }; + /** + * Creates a plain object from an AggregationResult message. Also converts values to other types if specified. + * @function toObject + * @memberof google.firestore.v1.AggregationResult + * @static + * @param {google.firestore.v1.AggregationResult} message AggregationResult + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + AggregationResult.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.objects || options.defaults) + object.aggregateFields = {}; + var keys2; + if (message.aggregateFields && (keys2 = Object.keys(message.aggregateFields)).length) { + object.aggregateFields = {}; + for (var j = 0; j < keys2.length; ++j) + object.aggregateFields[keys2[j]] = $root.google.firestore.v1.Value.toObject(message.aggregateFields[keys2[j]], options); + } + return object; + }; - return Struct; - })(); + /** + * Converts this AggregationResult to JSON. + * @function toJSON + * @memberof google.firestore.v1.AggregationResult + * @instance + * @returns {Object.} JSON object + */ + AggregationResult.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; - protobuf.Value = (function() { + /** + * Gets the default type url for AggregationResult + * @function getTypeUrl + * @memberof google.firestore.v1.AggregationResult + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + AggregationResult.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.firestore.v1.AggregationResult"; + }; - /** - * Properties of a Value. - * @memberof google.protobuf - * @interface IValue - * @property {google.protobuf.NullValue|null} [nullValue] Value nullValue - * @property {number|null} [numberValue] Value numberValue - * @property {string|null} [stringValue] Value stringValue - * @property {boolean|null} [boolValue] Value boolValue - * @property {google.protobuf.IStruct|null} [structValue] Value structValue - * @property {google.protobuf.IListValue|null} [listValue] Value listValue - */ + return AggregationResult; + })(); - /** - * Constructs a new Value. - * @memberof google.protobuf - * @classdesc Represents a Value. - * @implements IValue - * @constructor - * @param {google.protobuf.IValue=} [properties] Properties to set - */ - function Value(properties) { - if (properties) - for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) - if (properties[keys[i]] != null) - this[keys[i]] = properties[keys[i]]; - } + v1.Document = (function() { - /** - * Value nullValue. - * @member {google.protobuf.NullValue|null|undefined} nullValue - * @memberof google.protobuf.Value - * @instance - */ - Value.prototype.nullValue = null; + /** + * Properties of a Document. + * @memberof google.firestore.v1 + * @interface IDocument + * @property {string|null} [name] Document name + * @property {Object.|null} [fields] Document fields + * @property {google.protobuf.ITimestamp|null} [createTime] Document createTime + * @property {google.protobuf.ITimestamp|null} [updateTime] Document updateTime + */ - /** - * Value numberValue. - * @member {number|null|undefined} numberValue - * @memberof google.protobuf.Value - * @instance - */ - Value.prototype.numberValue = null; - - /** - * Value stringValue. - * @member {string|null|undefined} stringValue - * @memberof google.protobuf.Value - * @instance - */ - Value.prototype.stringValue = null; + /** + * Constructs a new Document. + * @memberof google.firestore.v1 + * @classdesc Represents a Document. + * @implements IDocument + * @constructor + * @param {google.firestore.v1.IDocument=} [properties] Properties to set + */ + function Document(properties) { + this.fields = {}; + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } - /** - * Value boolValue. - * @member {boolean|null|undefined} boolValue - * @memberof google.protobuf.Value - * @instance - */ - Value.prototype.boolValue = null; + /** + * Document name. + * @member {string} name + * @memberof google.firestore.v1.Document + * @instance + */ + Document.prototype.name = ""; - /** - * Value structValue. - * @member {google.protobuf.IStruct|null|undefined} structValue - * @memberof google.protobuf.Value - * @instance - */ - Value.prototype.structValue = null; + /** + * Document fields. + * @member {Object.} fields + * @memberof google.firestore.v1.Document + * @instance + */ + Document.prototype.fields = $util.emptyObject; - /** - * Value listValue. - * @member {google.protobuf.IListValue|null|undefined} listValue - * @memberof google.protobuf.Value - * @instance - */ - Value.prototype.listValue = null; + /** + * Document createTime. + * @member {google.protobuf.ITimestamp|null|undefined} createTime + * @memberof google.firestore.v1.Document + * @instance + */ + Document.prototype.createTime = null; - // OneOf field names bound to virtual getters and setters - var $oneOfFields; + /** + * Document updateTime. + * @member {google.protobuf.ITimestamp|null|undefined} updateTime + * @memberof google.firestore.v1.Document + * @instance + */ + Document.prototype.updateTime = null; - /** - * Value kind. - * @member {"nullValue"|"numberValue"|"stringValue"|"boolValue"|"structValue"|"listValue"|undefined} kind - * @memberof google.protobuf.Value - * @instance - */ - Object.defineProperty(Value.prototype, "kind", { - get: $util.oneOfGetter($oneOfFields = ["nullValue", "numberValue", "stringValue", "boolValue", "structValue", "listValue"]), - set: $util.oneOfSetter($oneOfFields) - }); + /** + * Creates a Document message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.firestore.v1.Document + * @static + * @param {Object.} object Plain object + * @returns {google.firestore.v1.Document} Document + */ + Document.fromObject = function fromObject(object) { + if (object instanceof $root.google.firestore.v1.Document) + return object; + var message = new $root.google.firestore.v1.Document(); + if (object.name != null) + message.name = String(object.name); + if (object.fields) { + if (typeof object.fields !== "object") + throw TypeError(".google.firestore.v1.Document.fields: object expected"); + message.fields = {}; + for (var keys = Object.keys(object.fields), i = 0; i < keys.length; ++i) { + if (typeof object.fields[keys[i]] !== "object") + throw TypeError(".google.firestore.v1.Document.fields: object expected"); + message.fields[keys[i]] = $root.google.firestore.v1.Value.fromObject(object.fields[keys[i]]); + } + } + if (object.createTime != null) { + if (typeof object.createTime !== "object") + throw TypeError(".google.firestore.v1.Document.createTime: object expected"); + message.createTime = $root.google.protobuf.Timestamp.fromObject(object.createTime); + } + if (object.updateTime != null) { + if (typeof object.updateTime !== "object") + throw TypeError(".google.firestore.v1.Document.updateTime: object expected"); + message.updateTime = $root.google.protobuf.Timestamp.fromObject(object.updateTime); + } + return message; + }; - /** - * Creates a Value message from a plain object. Also converts values to their respective internal types. - * @function fromObject - * @memberof google.protobuf.Value - * @static - * @param {Object.} object Plain object - * @returns {google.protobuf.Value} Value - */ - Value.fromObject = function fromObject(object) { - if (object instanceof $root.google.protobuf.Value) - return object; - var message = new $root.google.protobuf.Value(); - switch (object.nullValue) { - default: - if (typeof object.nullValue === "number") { - message.nullValue = object.nullValue; - break; + /** + * Creates a plain object from a Document message. Also converts values to other types if specified. + * @function toObject + * @memberof google.firestore.v1.Document + * @static + * @param {google.firestore.v1.Document} message Document + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + Document.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.objects || options.defaults) + object.fields = {}; + if (options.defaults) { + object.name = ""; + object.createTime = null; + object.updateTime = null; } - break; - case "NULL_VALUE": - case 0: - message.nullValue = 0; - break; - } - if (object.numberValue != null) - message.numberValue = Number(object.numberValue); - if (object.stringValue != null) - message.stringValue = String(object.stringValue); - if (object.boolValue != null) - message.boolValue = Boolean(object.boolValue); - if (object.structValue != null) { - if (typeof object.structValue !== "object") - throw TypeError(".google.protobuf.Value.structValue: object expected"); - message.structValue = $root.google.protobuf.Struct.fromObject(object.structValue); - } - if (object.listValue != null) { - if (typeof object.listValue !== "object") - throw TypeError(".google.protobuf.Value.listValue: object expected"); - message.listValue = $root.google.protobuf.ListValue.fromObject(object.listValue); - } - return message; - }; + if (message.name != null && message.hasOwnProperty("name")) + object.name = message.name; + var keys2; + if (message.fields && (keys2 = Object.keys(message.fields)).length) { + object.fields = {}; + for (var j = 0; j < keys2.length; ++j) + object.fields[keys2[j]] = $root.google.firestore.v1.Value.toObject(message.fields[keys2[j]], options); + } + if (message.createTime != null && message.hasOwnProperty("createTime")) + object.createTime = $root.google.protobuf.Timestamp.toObject(message.createTime, options); + if (message.updateTime != null && message.hasOwnProperty("updateTime")) + object.updateTime = $root.google.protobuf.Timestamp.toObject(message.updateTime, options); + return object; + }; - /** - * Creates a plain object from a Value message. Also converts values to other types if specified. - * @function toObject - * @memberof google.protobuf.Value - * @static - * @param {google.protobuf.Value} message Value - * @param {$protobuf.IConversionOptions} [options] Conversion options - * @returns {Object.} Plain object - */ - Value.toObject = function toObject(message, options) { - if (!options) - options = {}; - var object = {}; - if (message.nullValue != null && message.hasOwnProperty("nullValue")) { - object.nullValue = options.enums === String ? $root.google.protobuf.NullValue[message.nullValue] === undefined ? message.nullValue : $root.google.protobuf.NullValue[message.nullValue] : message.nullValue; - if (options.oneofs) - object.kind = "nullValue"; - } - if (message.numberValue != null && message.hasOwnProperty("numberValue")) { - object.numberValue = options.json && !isFinite(message.numberValue) ? String(message.numberValue) : message.numberValue; - if (options.oneofs) - object.kind = "numberValue"; - } - if (message.stringValue != null && message.hasOwnProperty("stringValue")) { - object.stringValue = message.stringValue; - if (options.oneofs) - object.kind = "stringValue"; - } - if (message.boolValue != null && message.hasOwnProperty("boolValue")) { - object.boolValue = message.boolValue; - if (options.oneofs) - object.kind = "boolValue"; - } - if (message.structValue != null && message.hasOwnProperty("structValue")) { - object.structValue = $root.google.protobuf.Struct.toObject(message.structValue, options); - if (options.oneofs) - object.kind = "structValue"; - } - if (message.listValue != null && message.hasOwnProperty("listValue")) { - object.listValue = $root.google.protobuf.ListValue.toObject(message.listValue, options); - if (options.oneofs) - object.kind = "listValue"; - } - return object; - }; + /** + * Converts this Document to JSON. + * @function toJSON + * @memberof google.firestore.v1.Document + * @instance + * @returns {Object.} JSON object + */ + Document.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; - /** - * Converts this Value to JSON. - * @function toJSON - * @memberof google.protobuf.Value - * @instance - * @returns {Object.} JSON object - */ - Value.prototype.toJSON = function toJSON() { - return this.constructor.toObject(this, $protobuf.util.toJSONOptions); - }; + /** + * Gets the default type url for Document + * @function getTypeUrl + * @memberof google.firestore.v1.Document + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + Document.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.firestore.v1.Document"; + }; - /** - * Gets the default type url for Value - * @function getTypeUrl - * @memberof google.protobuf.Value - * @static - * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") - * @returns {string} The default type url - */ - Value.getTypeUrl = function getTypeUrl(typeUrlPrefix) { - if (typeUrlPrefix === undefined) { - typeUrlPrefix = "type.googleapis.com"; - } - return typeUrlPrefix + "/google.protobuf.Value"; - }; + return Document; + })(); - return Value; - })(); + v1.Value = (function() { - /** - * NullValue enum. - * @name google.protobuf.NullValue - * @enum {string} - * @property {string} NULL_VALUE=NULL_VALUE NULL_VALUE value - */ - protobuf.NullValue = (function() { - var valuesById = {}, values = Object.create(valuesById); - values[valuesById[0] = "NULL_VALUE"] = "NULL_VALUE"; - return values; - })(); + /** + * Properties of a Value. + * @memberof google.firestore.v1 + * @interface IValue + * @property {google.protobuf.NullValue|null} [nullValue] Value nullValue + * @property {boolean|null} [booleanValue] Value booleanValue + * @property {number|string|null} [integerValue] Value integerValue + * @property {number|null} [doubleValue] Value doubleValue + * @property {google.protobuf.ITimestamp|null} [timestampValue] Value timestampValue + * @property {string|null} [stringValue] Value stringValue + * @property {Uint8Array|null} [bytesValue] Value bytesValue + * @property {string|null} [referenceValue] Value referenceValue + * @property {google.type.ILatLng|null} [geoPointValue] Value geoPointValue + * @property {google.firestore.v1.IArrayValue|null} [arrayValue] Value arrayValue + * @property {google.firestore.v1.IMapValue|null} [mapValue] Value mapValue + * @property {string|null} [fieldReferenceValue] Value fieldReferenceValue + * @property {google.firestore.v1.IFunction|null} [functionValue] Value functionValue + * @property {google.firestore.v1.IPipeline|null} [pipelineValue] Value pipelineValue + */ - protobuf.ListValue = (function() { + /** + * Constructs a new Value. + * @memberof google.firestore.v1 + * @classdesc Represents a Value. + * @implements IValue + * @constructor + * @param {google.firestore.v1.IValue=} [properties] Properties to set + */ + function Value(properties) { + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } - /** - * Properties of a ListValue. - * @memberof google.protobuf - * @interface IListValue - * @property {Array.|null} [values] ListValue values - */ + /** + * Value nullValue. + * @member {google.protobuf.NullValue|null|undefined} nullValue + * @memberof google.firestore.v1.Value + * @instance + */ + Value.prototype.nullValue = null; - /** - * Constructs a new ListValue. - * @memberof google.protobuf - * @classdesc Represents a ListValue. - * @implements IListValue - * @constructor - * @param {google.protobuf.IListValue=} [properties] Properties to set - */ - function ListValue(properties) { - this.values = []; - if (properties) - for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) - if (properties[keys[i]] != null) - this[keys[i]] = properties[keys[i]]; - } + /** + * Value booleanValue. + * @member {boolean|null|undefined} booleanValue + * @memberof google.firestore.v1.Value + * @instance + */ + Value.prototype.booleanValue = null; - /** - * ListValue values. - * @member {Array.} values - * @memberof google.protobuf.ListValue - * @instance - */ - ListValue.prototype.values = $util.emptyArray; + /** + * Value integerValue. + * @member {number|string|null|undefined} integerValue + * @memberof google.firestore.v1.Value + * @instance + */ + Value.prototype.integerValue = null; - /** - * Creates a ListValue message from a plain object. Also converts values to their respective internal types. - * @function fromObject - * @memberof google.protobuf.ListValue - * @static - * @param {Object.} object Plain object - * @returns {google.protobuf.ListValue} ListValue - */ - ListValue.fromObject = function fromObject(object) { - if (object instanceof $root.google.protobuf.ListValue) - return object; - var message = new $root.google.protobuf.ListValue(); - if (object.values) { - if (!Array.isArray(object.values)) - throw TypeError(".google.protobuf.ListValue.values: array expected"); - message.values = []; - for (var i = 0; i < object.values.length; ++i) { - if (typeof object.values[i] !== "object") - throw TypeError(".google.protobuf.ListValue.values: object expected"); - message.values[i] = $root.google.protobuf.Value.fromObject(object.values[i]); - } - } - return message; - }; + /** + * Value doubleValue. + * @member {number|null|undefined} doubleValue + * @memberof google.firestore.v1.Value + * @instance + */ + Value.prototype.doubleValue = null; - /** - * Creates a plain object from a ListValue message. Also converts values to other types if specified. - * @function toObject - * @memberof google.protobuf.ListValue - * @static - * @param {google.protobuf.ListValue} message ListValue - * @param {$protobuf.IConversionOptions} [options] Conversion options - * @returns {Object.} Plain object - */ - ListValue.toObject = function toObject(message, options) { - if (!options) - options = {}; - var object = {}; - if (options.arrays || options.defaults) - object.values = []; - if (message.values && message.values.length) { - object.values = []; - for (var j = 0; j < message.values.length; ++j) - object.values[j] = $root.google.protobuf.Value.toObject(message.values[j], options); - } - return object; - }; + /** + * Value timestampValue. + * @member {google.protobuf.ITimestamp|null|undefined} timestampValue + * @memberof google.firestore.v1.Value + * @instance + */ + Value.prototype.timestampValue = null; - /** - * Converts this ListValue to JSON. - * @function toJSON - * @memberof google.protobuf.ListValue - * @instance - * @returns {Object.} JSON object - */ - ListValue.prototype.toJSON = function toJSON() { - return this.constructor.toObject(this, $protobuf.util.toJSONOptions); - }; + /** + * Value stringValue. + * @member {string|null|undefined} stringValue + * @memberof google.firestore.v1.Value + * @instance + */ + Value.prototype.stringValue = null; - /** - * Gets the default type url for ListValue - * @function getTypeUrl - * @memberof google.protobuf.ListValue - * @static - * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") - * @returns {string} The default type url - */ - ListValue.getTypeUrl = function getTypeUrl(typeUrlPrefix) { - if (typeUrlPrefix === undefined) { - typeUrlPrefix = "type.googleapis.com"; - } - return typeUrlPrefix + "/google.protobuf.ListValue"; - }; + /** + * Value bytesValue. + * @member {Uint8Array|null|undefined} bytesValue + * @memberof google.firestore.v1.Value + * @instance + */ + Value.prototype.bytesValue = null; - return ListValue; - })(); + /** + * Value referenceValue. + * @member {string|null|undefined} referenceValue + * @memberof google.firestore.v1.Value + * @instance + */ + Value.prototype.referenceValue = null; - protobuf.Timestamp = (function() { + /** + * Value geoPointValue. + * @member {google.type.ILatLng|null|undefined} geoPointValue + * @memberof google.firestore.v1.Value + * @instance + */ + Value.prototype.geoPointValue = null; - /** - * Properties of a Timestamp. - * @memberof google.protobuf - * @interface ITimestamp - * @property {number|string|null} [seconds] Timestamp seconds - * @property {number|null} [nanos] Timestamp nanos - */ - - /** - * Constructs a new Timestamp. - * @memberof google.protobuf - * @classdesc Represents a Timestamp. - * @implements ITimestamp - * @constructor - * @param {google.protobuf.ITimestamp=} [properties] Properties to set - */ - function Timestamp(properties) { - if (properties) - for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) - if (properties[keys[i]] != null) - this[keys[i]] = properties[keys[i]]; - } - - /** - * Timestamp seconds. - * @member {number|string} seconds - * @memberof google.protobuf.Timestamp - * @instance - */ - Timestamp.prototype.seconds = $util.Long ? $util.Long.fromBits(0,0,false) : 0; - - /** - * Timestamp nanos. - * @member {number} nanos - * @memberof google.protobuf.Timestamp - * @instance - */ - Timestamp.prototype.nanos = 0; - - /** - * Creates a Timestamp message from a plain object. Also converts values to their respective internal types. - * @function fromObject - * @memberof google.protobuf.Timestamp - * @static - * @param {Object.} object Plain object - * @returns {google.protobuf.Timestamp} Timestamp - */ - Timestamp.fromObject = function fromObject(object) { - if (object instanceof $root.google.protobuf.Timestamp) - return object; - var message = new $root.google.protobuf.Timestamp(); - if (object.seconds != null) - if ($util.Long) - (message.seconds = $util.Long.fromValue(object.seconds)).unsigned = false; - else if (typeof object.seconds === "string") - message.seconds = parseInt(object.seconds, 10); - else if (typeof object.seconds === "number") - message.seconds = object.seconds; - else if (typeof object.seconds === "object") - message.seconds = new $util.LongBits(object.seconds.low >>> 0, object.seconds.high >>> 0).toNumber(); - if (object.nanos != null) - message.nanos = object.nanos | 0; - return message; - }; - - /** - * Creates a plain object from a Timestamp message. Also converts values to other types if specified. - * @function toObject - * @memberof google.protobuf.Timestamp - * @static - * @param {google.protobuf.Timestamp} message Timestamp - * @param {$protobuf.IConversionOptions} [options] Conversion options - * @returns {Object.} Plain object - */ - Timestamp.toObject = function toObject(message, options) { - if (!options) - options = {}; - var object = {}; - if (options.defaults) { - if ($util.Long) { - var long = new $util.Long(0, 0, false); - object.seconds = options.longs === String ? long.toString() : options.longs === Number ? long.toNumber() : long; - } else - object.seconds = options.longs === String ? "0" : 0; - object.nanos = 0; - } - if (message.seconds != null && message.hasOwnProperty("seconds")) - if (typeof message.seconds === "number") - object.seconds = options.longs === String ? String(message.seconds) : message.seconds; - else - object.seconds = options.longs === String ? $util.Long.prototype.toString.call(message.seconds) : options.longs === Number ? new $util.LongBits(message.seconds.low >>> 0, message.seconds.high >>> 0).toNumber() : message.seconds; - if (message.nanos != null && message.hasOwnProperty("nanos")) - object.nanos = message.nanos; - return object; - }; - - /** - * Converts this Timestamp to JSON. - * @function toJSON - * @memberof google.protobuf.Timestamp - * @instance - * @returns {Object.} JSON object - */ - Timestamp.prototype.toJSON = function toJSON() { - return this.constructor.toObject(this, $protobuf.util.toJSONOptions); - }; + /** + * Value arrayValue. + * @member {google.firestore.v1.IArrayValue|null|undefined} arrayValue + * @memberof google.firestore.v1.Value + * @instance + */ + Value.prototype.arrayValue = null; - /** - * Gets the default type url for Timestamp - * @function getTypeUrl - * @memberof google.protobuf.Timestamp - * @static - * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") - * @returns {string} The default type url - */ - Timestamp.getTypeUrl = function getTypeUrl(typeUrlPrefix) { - if (typeUrlPrefix === undefined) { - typeUrlPrefix = "type.googleapis.com"; - } - return typeUrlPrefix + "/google.protobuf.Timestamp"; - }; + /** + * Value mapValue. + * @member {google.firestore.v1.IMapValue|null|undefined} mapValue + * @memberof google.firestore.v1.Value + * @instance + */ + Value.prototype.mapValue = null; - return Timestamp; - })(); + /** + * Value fieldReferenceValue. + * @member {string|null|undefined} fieldReferenceValue + * @memberof google.firestore.v1.Value + * @instance + */ + Value.prototype.fieldReferenceValue = null; - protobuf.FileDescriptorSet = (function() { + /** + * Value functionValue. + * @member {google.firestore.v1.IFunction|null|undefined} functionValue + * @memberof google.firestore.v1.Value + * @instance + */ + Value.prototype.functionValue = null; - /** - * Properties of a FileDescriptorSet. - * @memberof google.protobuf - * @interface IFileDescriptorSet - * @property {Array.|null} [file] FileDescriptorSet file - */ + /** + * Value pipelineValue. + * @member {google.firestore.v1.IPipeline|null|undefined} pipelineValue + * @memberof google.firestore.v1.Value + * @instance + */ + Value.prototype.pipelineValue = null; - /** - * Constructs a new FileDescriptorSet. - * @memberof google.protobuf - * @classdesc Represents a FileDescriptorSet. - * @implements IFileDescriptorSet - * @constructor - * @param {google.protobuf.IFileDescriptorSet=} [properties] Properties to set - */ - function FileDescriptorSet(properties) { - this.file = []; - if (properties) - for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) - if (properties[keys[i]] != null) - this[keys[i]] = properties[keys[i]]; - } + // OneOf field names bound to virtual getters and setters + var $oneOfFields; - /** - * FileDescriptorSet file. - * @member {Array.} file - * @memberof google.protobuf.FileDescriptorSet - * @instance - */ - FileDescriptorSet.prototype.file = $util.emptyArray; + /** + * Value valueType. + * @member {"nullValue"|"booleanValue"|"integerValue"|"doubleValue"|"timestampValue"|"stringValue"|"bytesValue"|"referenceValue"|"geoPointValue"|"arrayValue"|"mapValue"|"fieldReferenceValue"|"functionValue"|"pipelineValue"|undefined} valueType + * @memberof google.firestore.v1.Value + * @instance + */ + Object.defineProperty(Value.prototype, "valueType", { + get: $util.oneOfGetter($oneOfFields = ["nullValue", "booleanValue", "integerValue", "doubleValue", "timestampValue", "stringValue", "bytesValue", "referenceValue", "geoPointValue", "arrayValue", "mapValue", "fieldReferenceValue", "functionValue", "pipelineValue"]), + set: $util.oneOfSetter($oneOfFields) + }); - /** - * Creates a FileDescriptorSet message from a plain object. Also converts values to their respective internal types. - * @function fromObject - * @memberof google.protobuf.FileDescriptorSet - * @static - * @param {Object.} object Plain object - * @returns {google.protobuf.FileDescriptorSet} FileDescriptorSet - */ - FileDescriptorSet.fromObject = function fromObject(object) { - if (object instanceof $root.google.protobuf.FileDescriptorSet) - return object; - var message = new $root.google.protobuf.FileDescriptorSet(); - if (object.file) { - if (!Array.isArray(object.file)) - throw TypeError(".google.protobuf.FileDescriptorSet.file: array expected"); - message.file = []; - for (var i = 0; i < object.file.length; ++i) { - if (typeof object.file[i] !== "object") - throw TypeError(".google.protobuf.FileDescriptorSet.file: object expected"); - message.file[i] = $root.google.protobuf.FileDescriptorProto.fromObject(object.file[i]); + /** + * Creates a Value message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.firestore.v1.Value + * @static + * @param {Object.} object Plain object + * @returns {google.firestore.v1.Value} Value + */ + Value.fromObject = function fromObject(object) { + if (object instanceof $root.google.firestore.v1.Value) + return object; + var message = new $root.google.firestore.v1.Value(); + switch (object.nullValue) { + default: + if (typeof object.nullValue === "number") { + message.nullValue = object.nullValue; + break; + } + break; + case "NULL_VALUE": + case 0: + message.nullValue = 0; + break; } - } - return message; - }; - - /** - * Creates a plain object from a FileDescriptorSet message. Also converts values to other types if specified. - * @function toObject - * @memberof google.protobuf.FileDescriptorSet - * @static - * @param {google.protobuf.FileDescriptorSet} message FileDescriptorSet - * @param {$protobuf.IConversionOptions} [options] Conversion options - * @returns {Object.} Plain object - */ - FileDescriptorSet.toObject = function toObject(message, options) { - if (!options) - options = {}; - var object = {}; - if (options.arrays || options.defaults) - object.file = []; - if (message.file && message.file.length) { - object.file = []; - for (var j = 0; j < message.file.length; ++j) - object.file[j] = $root.google.protobuf.FileDescriptorProto.toObject(message.file[j], options); - } - return object; - }; - - /** - * Converts this FileDescriptorSet to JSON. - * @function toJSON - * @memberof google.protobuf.FileDescriptorSet - * @instance - * @returns {Object.} JSON object - */ - FileDescriptorSet.prototype.toJSON = function toJSON() { - return this.constructor.toObject(this, $protobuf.util.toJSONOptions); - }; + if (object.booleanValue != null) + message.booleanValue = Boolean(object.booleanValue); + if (object.integerValue != null) + if ($util.Long) + (message.integerValue = $util.Long.fromValue(object.integerValue)).unsigned = false; + else if (typeof object.integerValue === "string") + message.integerValue = parseInt(object.integerValue, 10); + else if (typeof object.integerValue === "number") + message.integerValue = object.integerValue; + else if (typeof object.integerValue === "object") + message.integerValue = new $util.LongBits(object.integerValue.low >>> 0, object.integerValue.high >>> 0).toNumber(); + if (object.doubleValue != null) + message.doubleValue = Number(object.doubleValue); + if (object.timestampValue != null) { + if (typeof object.timestampValue !== "object") + throw TypeError(".google.firestore.v1.Value.timestampValue: object expected"); + message.timestampValue = $root.google.protobuf.Timestamp.fromObject(object.timestampValue); + } + if (object.stringValue != null) + message.stringValue = String(object.stringValue); + if (object.bytesValue != null) + if (typeof object.bytesValue === "string") + $util.base64.decode(object.bytesValue, message.bytesValue = $util.newBuffer($util.base64.length(object.bytesValue)), 0); + else if (object.bytesValue.length >= 0) + message.bytesValue = object.bytesValue; + if (object.referenceValue != null) + message.referenceValue = String(object.referenceValue); + if (object.geoPointValue != null) { + if (typeof object.geoPointValue !== "object") + throw TypeError(".google.firestore.v1.Value.geoPointValue: object expected"); + message.geoPointValue = $root.google.type.LatLng.fromObject(object.geoPointValue); + } + if (object.arrayValue != null) { + if (typeof object.arrayValue !== "object") + throw TypeError(".google.firestore.v1.Value.arrayValue: object expected"); + message.arrayValue = $root.google.firestore.v1.ArrayValue.fromObject(object.arrayValue); + } + if (object.mapValue != null) { + if (typeof object.mapValue !== "object") + throw TypeError(".google.firestore.v1.Value.mapValue: object expected"); + message.mapValue = $root.google.firestore.v1.MapValue.fromObject(object.mapValue); + } + if (object.fieldReferenceValue != null) + message.fieldReferenceValue = String(object.fieldReferenceValue); + if (object.functionValue != null) { + if (typeof object.functionValue !== "object") + throw TypeError(".google.firestore.v1.Value.functionValue: object expected"); + message.functionValue = $root.google.firestore.v1.Function.fromObject(object.functionValue); + } + if (object.pipelineValue != null) { + if (typeof object.pipelineValue !== "object") + throw TypeError(".google.firestore.v1.Value.pipelineValue: object expected"); + message.pipelineValue = $root.google.firestore.v1.Pipeline.fromObject(object.pipelineValue); + } + return message; + }; - /** - * Gets the default type url for FileDescriptorSet - * @function getTypeUrl - * @memberof google.protobuf.FileDescriptorSet - * @static - * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") - * @returns {string} The default type url - */ - FileDescriptorSet.getTypeUrl = function getTypeUrl(typeUrlPrefix) { - if (typeUrlPrefix === undefined) { - typeUrlPrefix = "type.googleapis.com"; - } - return typeUrlPrefix + "/google.protobuf.FileDescriptorSet"; - }; + /** + * Creates a plain object from a Value message. Also converts values to other types if specified. + * @function toObject + * @memberof google.firestore.v1.Value + * @static + * @param {google.firestore.v1.Value} message Value + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + Value.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (message.booleanValue != null && message.hasOwnProperty("booleanValue")) { + object.booleanValue = message.booleanValue; + if (options.oneofs) + object.valueType = "booleanValue"; + } + if (message.integerValue != null && message.hasOwnProperty("integerValue")) { + if (typeof message.integerValue === "number") + object.integerValue = options.longs === String ? String(message.integerValue) : message.integerValue; + else + object.integerValue = options.longs === String ? $util.Long.prototype.toString.call(message.integerValue) : options.longs === Number ? new $util.LongBits(message.integerValue.low >>> 0, message.integerValue.high >>> 0).toNumber() : message.integerValue; + if (options.oneofs) + object.valueType = "integerValue"; + } + if (message.doubleValue != null && message.hasOwnProperty("doubleValue")) { + object.doubleValue = options.json && !isFinite(message.doubleValue) ? String(message.doubleValue) : message.doubleValue; + if (options.oneofs) + object.valueType = "doubleValue"; + } + if (message.referenceValue != null && message.hasOwnProperty("referenceValue")) { + object.referenceValue = message.referenceValue; + if (options.oneofs) + object.valueType = "referenceValue"; + } + if (message.mapValue != null && message.hasOwnProperty("mapValue")) { + object.mapValue = $root.google.firestore.v1.MapValue.toObject(message.mapValue, options); + if (options.oneofs) + object.valueType = "mapValue"; + } + if (message.geoPointValue != null && message.hasOwnProperty("geoPointValue")) { + object.geoPointValue = $root.google.type.LatLng.toObject(message.geoPointValue, options); + if (options.oneofs) + object.valueType = "geoPointValue"; + } + if (message.arrayValue != null && message.hasOwnProperty("arrayValue")) { + object.arrayValue = $root.google.firestore.v1.ArrayValue.toObject(message.arrayValue, options); + if (options.oneofs) + object.valueType = "arrayValue"; + } + if (message.timestampValue != null && message.hasOwnProperty("timestampValue")) { + object.timestampValue = $root.google.protobuf.Timestamp.toObject(message.timestampValue, options); + if (options.oneofs) + object.valueType = "timestampValue"; + } + if (message.nullValue != null && message.hasOwnProperty("nullValue")) { + object.nullValue = options.enums === String ? $root.google.protobuf.NullValue[message.nullValue] === undefined ? message.nullValue : $root.google.protobuf.NullValue[message.nullValue] : message.nullValue; + if (options.oneofs) + object.valueType = "nullValue"; + } + if (message.stringValue != null && message.hasOwnProperty("stringValue")) { + object.stringValue = message.stringValue; + if (options.oneofs) + object.valueType = "stringValue"; + } + if (message.bytesValue != null && message.hasOwnProperty("bytesValue")) { + object.bytesValue = options.bytes === String ? $util.base64.encode(message.bytesValue, 0, message.bytesValue.length) : options.bytes === Array ? Array.prototype.slice.call(message.bytesValue) : message.bytesValue; + if (options.oneofs) + object.valueType = "bytesValue"; + } + if (message.fieldReferenceValue != null && message.hasOwnProperty("fieldReferenceValue")) { + object.fieldReferenceValue = message.fieldReferenceValue; + if (options.oneofs) + object.valueType = "fieldReferenceValue"; + } + if (message.functionValue != null && message.hasOwnProperty("functionValue")) { + object.functionValue = $root.google.firestore.v1.Function.toObject(message.functionValue, options); + if (options.oneofs) + object.valueType = "functionValue"; + } + if (message.pipelineValue != null && message.hasOwnProperty("pipelineValue")) { + object.pipelineValue = $root.google.firestore.v1.Pipeline.toObject(message.pipelineValue, options); + if (options.oneofs) + object.valueType = "pipelineValue"; + } + return object; + }; - return FileDescriptorSet; - })(); + /** + * Converts this Value to JSON. + * @function toJSON + * @memberof google.firestore.v1.Value + * @instance + * @returns {Object.} JSON object + */ + Value.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; - /** - * Edition enum. - * @name google.protobuf.Edition - * @enum {string} - * @property {string} EDITION_UNKNOWN=EDITION_UNKNOWN EDITION_UNKNOWN value - * @property {string} EDITION_LEGACY=EDITION_LEGACY EDITION_LEGACY value - * @property {string} EDITION_PROTO2=EDITION_PROTO2 EDITION_PROTO2 value - * @property {string} EDITION_PROTO3=EDITION_PROTO3 EDITION_PROTO3 value - * @property {string} EDITION_2023=EDITION_2023 EDITION_2023 value - * @property {string} EDITION_2024=EDITION_2024 EDITION_2024 value - * @property {string} EDITION_1_TEST_ONLY=EDITION_1_TEST_ONLY EDITION_1_TEST_ONLY value - * @property {string} EDITION_2_TEST_ONLY=EDITION_2_TEST_ONLY EDITION_2_TEST_ONLY value - * @property {string} EDITION_99997_TEST_ONLY=EDITION_99997_TEST_ONLY EDITION_99997_TEST_ONLY value - * @property {string} EDITION_99998_TEST_ONLY=EDITION_99998_TEST_ONLY EDITION_99998_TEST_ONLY value - * @property {string} EDITION_99999_TEST_ONLY=EDITION_99999_TEST_ONLY EDITION_99999_TEST_ONLY value - * @property {string} EDITION_MAX=EDITION_MAX EDITION_MAX value - */ - protobuf.Edition = (function() { - var valuesById = {}, values = Object.create(valuesById); - values[valuesById[0] = "EDITION_UNKNOWN"] = "EDITION_UNKNOWN"; - values[valuesById[900] = "EDITION_LEGACY"] = "EDITION_LEGACY"; - values[valuesById[998] = "EDITION_PROTO2"] = "EDITION_PROTO2"; - values[valuesById[999] = "EDITION_PROTO3"] = "EDITION_PROTO3"; - values[valuesById[1000] = "EDITION_2023"] = "EDITION_2023"; - values[valuesById[1001] = "EDITION_2024"] = "EDITION_2024"; - values[valuesById[1] = "EDITION_1_TEST_ONLY"] = "EDITION_1_TEST_ONLY"; - values[valuesById[2] = "EDITION_2_TEST_ONLY"] = "EDITION_2_TEST_ONLY"; - values[valuesById[99997] = "EDITION_99997_TEST_ONLY"] = "EDITION_99997_TEST_ONLY"; - values[valuesById[99998] = "EDITION_99998_TEST_ONLY"] = "EDITION_99998_TEST_ONLY"; - values[valuesById[99999] = "EDITION_99999_TEST_ONLY"] = "EDITION_99999_TEST_ONLY"; - values[valuesById[2147483647] = "EDITION_MAX"] = "EDITION_MAX"; - return values; - })(); + /** + * Gets the default type url for Value + * @function getTypeUrl + * @memberof google.firestore.v1.Value + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + Value.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.firestore.v1.Value"; + }; - protobuf.FileDescriptorProto = (function() { + return Value; + })(); - /** - * Properties of a FileDescriptorProto. - * @memberof google.protobuf - * @interface IFileDescriptorProto - * @property {string|null} [name] FileDescriptorProto name - * @property {string|null} ["package"] FileDescriptorProto package - * @property {Array.|null} [dependency] FileDescriptorProto dependency - * @property {Array.|null} [publicDependency] FileDescriptorProto publicDependency - * @property {Array.|null} [weakDependency] FileDescriptorProto weakDependency - * @property {Array.|null} [messageType] FileDescriptorProto messageType - * @property {Array.|null} [enumType] FileDescriptorProto enumType - * @property {Array.|null} [service] FileDescriptorProto service - * @property {Array.|null} [extension] FileDescriptorProto extension - * @property {google.protobuf.IFileOptions|null} [options] FileDescriptorProto options - * @property {google.protobuf.ISourceCodeInfo|null} [sourceCodeInfo] FileDescriptorProto sourceCodeInfo - * @property {string|null} [syntax] FileDescriptorProto syntax - * @property {google.protobuf.Edition|null} [edition] FileDescriptorProto edition - */ + v1.ArrayValue = (function() { - /** - * Constructs a new FileDescriptorProto. - * @memberof google.protobuf - * @classdesc Represents a FileDescriptorProto. - * @implements IFileDescriptorProto - * @constructor - * @param {google.protobuf.IFileDescriptorProto=} [properties] Properties to set - */ - function FileDescriptorProto(properties) { - this.dependency = []; - this.publicDependency = []; - this.weakDependency = []; - this.messageType = []; - this.enumType = []; - this.service = []; - this.extension = []; - if (properties) - for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) - if (properties[keys[i]] != null) - this[keys[i]] = properties[keys[i]]; - } + /** + * Properties of an ArrayValue. + * @memberof google.firestore.v1 + * @interface IArrayValue + * @property {Array.|null} [values] ArrayValue values + */ - /** - * FileDescriptorProto name. - * @member {string} name - * @memberof google.protobuf.FileDescriptorProto - * @instance - */ - FileDescriptorProto.prototype.name = ""; + /** + * Constructs a new ArrayValue. + * @memberof google.firestore.v1 + * @classdesc Represents an ArrayValue. + * @implements IArrayValue + * @constructor + * @param {google.firestore.v1.IArrayValue=} [properties] Properties to set + */ + function ArrayValue(properties) { + this.values = []; + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } - /** - * FileDescriptorProto package. - * @member {string} package - * @memberof google.protobuf.FileDescriptorProto - * @instance - */ - FileDescriptorProto.prototype["package"] = ""; + /** + * ArrayValue values. + * @member {Array.} values + * @memberof google.firestore.v1.ArrayValue + * @instance + */ + ArrayValue.prototype.values = $util.emptyArray; - /** - * FileDescriptorProto dependency. - * @member {Array.} dependency - * @memberof google.protobuf.FileDescriptorProto - * @instance - */ - FileDescriptorProto.prototype.dependency = $util.emptyArray; + /** + * Creates an ArrayValue message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.firestore.v1.ArrayValue + * @static + * @param {Object.} object Plain object + * @returns {google.firestore.v1.ArrayValue} ArrayValue + */ + ArrayValue.fromObject = function fromObject(object) { + if (object instanceof $root.google.firestore.v1.ArrayValue) + return object; + var message = new $root.google.firestore.v1.ArrayValue(); + if (object.values) { + if (!Array.isArray(object.values)) + throw TypeError(".google.firestore.v1.ArrayValue.values: array expected"); + message.values = []; + for (var i = 0; i < object.values.length; ++i) { + if (typeof object.values[i] !== "object") + throw TypeError(".google.firestore.v1.ArrayValue.values: object expected"); + message.values[i] = $root.google.firestore.v1.Value.fromObject(object.values[i]); + } + } + return message; + }; - /** - * FileDescriptorProto publicDependency. - * @member {Array.} publicDependency - * @memberof google.protobuf.FileDescriptorProto - * @instance - */ - FileDescriptorProto.prototype.publicDependency = $util.emptyArray; + /** + * Creates a plain object from an ArrayValue message. Also converts values to other types if specified. + * @function toObject + * @memberof google.firestore.v1.ArrayValue + * @static + * @param {google.firestore.v1.ArrayValue} message ArrayValue + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + ArrayValue.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.arrays || options.defaults) + object.values = []; + if (message.values && message.values.length) { + object.values = []; + for (var j = 0; j < message.values.length; ++j) + object.values[j] = $root.google.firestore.v1.Value.toObject(message.values[j], options); + } + return object; + }; - /** - * FileDescriptorProto weakDependency. - * @member {Array.} weakDependency - * @memberof google.protobuf.FileDescriptorProto - * @instance - */ - FileDescriptorProto.prototype.weakDependency = $util.emptyArray; + /** + * Converts this ArrayValue to JSON. + * @function toJSON + * @memberof google.firestore.v1.ArrayValue + * @instance + * @returns {Object.} JSON object + */ + ArrayValue.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; - /** - * FileDescriptorProto messageType. - * @member {Array.} messageType - * @memberof google.protobuf.FileDescriptorProto - * @instance - */ - FileDescriptorProto.prototype.messageType = $util.emptyArray; + /** + * Gets the default type url for ArrayValue + * @function getTypeUrl + * @memberof google.firestore.v1.ArrayValue + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + ArrayValue.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.firestore.v1.ArrayValue"; + }; - /** - * FileDescriptorProto enumType. - * @member {Array.} enumType - * @memberof google.protobuf.FileDescriptorProto - * @instance - */ - FileDescriptorProto.prototype.enumType = $util.emptyArray; + return ArrayValue; + })(); - /** - * FileDescriptorProto service. - * @member {Array.} service - * @memberof google.protobuf.FileDescriptorProto - * @instance - */ - FileDescriptorProto.prototype.service = $util.emptyArray; + v1.MapValue = (function() { - /** - * FileDescriptorProto extension. - * @member {Array.} extension - * @memberof google.protobuf.FileDescriptorProto - * @instance - */ - FileDescriptorProto.prototype.extension = $util.emptyArray; + /** + * Properties of a MapValue. + * @memberof google.firestore.v1 + * @interface IMapValue + * @property {Object.|null} [fields] MapValue fields + */ - /** - * FileDescriptorProto options. - * @member {google.protobuf.IFileOptions|null|undefined} options - * @memberof google.protobuf.FileDescriptorProto - * @instance - */ - FileDescriptorProto.prototype.options = null; + /** + * Constructs a new MapValue. + * @memberof google.firestore.v1 + * @classdesc Represents a MapValue. + * @implements IMapValue + * @constructor + * @param {google.firestore.v1.IMapValue=} [properties] Properties to set + */ + function MapValue(properties) { + this.fields = {}; + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } - /** - * FileDescriptorProto sourceCodeInfo. - * @member {google.protobuf.ISourceCodeInfo|null|undefined} sourceCodeInfo - * @memberof google.protobuf.FileDescriptorProto - * @instance - */ - FileDescriptorProto.prototype.sourceCodeInfo = null; + /** + * MapValue fields. + * @member {Object.} fields + * @memberof google.firestore.v1.MapValue + * @instance + */ + MapValue.prototype.fields = $util.emptyObject; - /** - * FileDescriptorProto syntax. - * @member {string} syntax - * @memberof google.protobuf.FileDescriptorProto - * @instance - */ - FileDescriptorProto.prototype.syntax = ""; + /** + * Creates a MapValue message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.firestore.v1.MapValue + * @static + * @param {Object.} object Plain object + * @returns {google.firestore.v1.MapValue} MapValue + */ + MapValue.fromObject = function fromObject(object) { + if (object instanceof $root.google.firestore.v1.MapValue) + return object; + var message = new $root.google.firestore.v1.MapValue(); + if (object.fields) { + if (typeof object.fields !== "object") + throw TypeError(".google.firestore.v1.MapValue.fields: object expected"); + message.fields = {}; + for (var keys = Object.keys(object.fields), i = 0; i < keys.length; ++i) { + if (typeof object.fields[keys[i]] !== "object") + throw TypeError(".google.firestore.v1.MapValue.fields: object expected"); + message.fields[keys[i]] = $root.google.firestore.v1.Value.fromObject(object.fields[keys[i]]); + } + } + return message; + }; - /** - * FileDescriptorProto edition. - * @member {google.protobuf.Edition} edition - * @memberof google.protobuf.FileDescriptorProto - * @instance - */ - FileDescriptorProto.prototype.edition = 0; - - /** - * Creates a FileDescriptorProto message from a plain object. Also converts values to their respective internal types. - * @function fromObject - * @memberof google.protobuf.FileDescriptorProto - * @static - * @param {Object.} object Plain object - * @returns {google.protobuf.FileDescriptorProto} FileDescriptorProto - */ - FileDescriptorProto.fromObject = function fromObject(object) { - if (object instanceof $root.google.protobuf.FileDescriptorProto) + /** + * Creates a plain object from a MapValue message. Also converts values to other types if specified. + * @function toObject + * @memberof google.firestore.v1.MapValue + * @static + * @param {google.firestore.v1.MapValue} message MapValue + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + MapValue.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.objects || options.defaults) + object.fields = {}; + var keys2; + if (message.fields && (keys2 = Object.keys(message.fields)).length) { + object.fields = {}; + for (var j = 0; j < keys2.length; ++j) + object.fields[keys2[j]] = $root.google.firestore.v1.Value.toObject(message.fields[keys2[j]], options); + } return object; - var message = new $root.google.protobuf.FileDescriptorProto(); - if (object.name != null) - message.name = String(object.name); - if (object["package"] != null) - message["package"] = String(object["package"]); - if (object.dependency) { - if (!Array.isArray(object.dependency)) - throw TypeError(".google.protobuf.FileDescriptorProto.dependency: array expected"); - message.dependency = []; - for (var i = 0; i < object.dependency.length; ++i) - message.dependency[i] = String(object.dependency[i]); - } - if (object.publicDependency) { - if (!Array.isArray(object.publicDependency)) - throw TypeError(".google.protobuf.FileDescriptorProto.publicDependency: array expected"); - message.publicDependency = []; - for (var i = 0; i < object.publicDependency.length; ++i) - message.publicDependency[i] = object.publicDependency[i] | 0; - } - if (object.weakDependency) { - if (!Array.isArray(object.weakDependency)) - throw TypeError(".google.protobuf.FileDescriptorProto.weakDependency: array expected"); - message.weakDependency = []; - for (var i = 0; i < object.weakDependency.length; ++i) - message.weakDependency[i] = object.weakDependency[i] | 0; - } - if (object.messageType) { - if (!Array.isArray(object.messageType)) - throw TypeError(".google.protobuf.FileDescriptorProto.messageType: array expected"); - message.messageType = []; - for (var i = 0; i < object.messageType.length; ++i) { - if (typeof object.messageType[i] !== "object") - throw TypeError(".google.protobuf.FileDescriptorProto.messageType: object expected"); - message.messageType[i] = $root.google.protobuf.DescriptorProto.fromObject(object.messageType[i]); + }; + + /** + * Converts this MapValue to JSON. + * @function toJSON + * @memberof google.firestore.v1.MapValue + * @instance + * @returns {Object.} JSON object + */ + MapValue.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + + /** + * Gets the default type url for MapValue + * @function getTypeUrl + * @memberof google.firestore.v1.MapValue + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + MapValue.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; } + return typeUrlPrefix + "/google.firestore.v1.MapValue"; + }; + + return MapValue; + })(); + + v1.Function = (function() { + + /** + * Properties of a Function. + * @memberof google.firestore.v1 + * @interface IFunction + * @property {string|null} [name] Function name + * @property {Array.|null} [args] Function args + * @property {Object.|null} [options] Function options + */ + + /** + * Constructs a new Function. + * @memberof google.firestore.v1 + * @classdesc Represents a Function. + * @implements IFunction + * @constructor + * @param {google.firestore.v1.IFunction=} [properties] Properties to set + */ + function Function(properties) { + this.args = []; + this.options = {}; + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; } - if (object.enumType) { - if (!Array.isArray(object.enumType)) - throw TypeError(".google.protobuf.FileDescriptorProto.enumType: array expected"); - message.enumType = []; - for (var i = 0; i < object.enumType.length; ++i) { - if (typeof object.enumType[i] !== "object") - throw TypeError(".google.protobuf.FileDescriptorProto.enumType: object expected"); - message.enumType[i] = $root.google.protobuf.EnumDescriptorProto.fromObject(object.enumType[i]); + + /** + * Function name. + * @member {string} name + * @memberof google.firestore.v1.Function + * @instance + */ + Function.prototype.name = ""; + + /** + * Function args. + * @member {Array.} args + * @memberof google.firestore.v1.Function + * @instance + */ + Function.prototype.args = $util.emptyArray; + + /** + * Function options. + * @member {Object.} options + * @memberof google.firestore.v1.Function + * @instance + */ + Function.prototype.options = $util.emptyObject; + + /** + * Creates a Function message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.firestore.v1.Function + * @static + * @param {Object.} object Plain object + * @returns {google.firestore.v1.Function} Function + */ + Function.fromObject = function fromObject(object) { + if (object instanceof $root.google.firestore.v1.Function) + return object; + var message = new $root.google.firestore.v1.Function(); + if (object.name != null) + message.name = String(object.name); + if (object.args) { + if (!Array.isArray(object.args)) + throw TypeError(".google.firestore.v1.Function.args: array expected"); + message.args = []; + for (var i = 0; i < object.args.length; ++i) { + if (typeof object.args[i] !== "object") + throw TypeError(".google.firestore.v1.Function.args: object expected"); + message.args[i] = $root.google.firestore.v1.Value.fromObject(object.args[i]); + } } - } - if (object.service) { - if (!Array.isArray(object.service)) - throw TypeError(".google.protobuf.FileDescriptorProto.service: array expected"); - message.service = []; - for (var i = 0; i < object.service.length; ++i) { - if (typeof object.service[i] !== "object") - throw TypeError(".google.protobuf.FileDescriptorProto.service: object expected"); - message.service[i] = $root.google.protobuf.ServiceDescriptorProto.fromObject(object.service[i]); + if (object.options) { + if (typeof object.options !== "object") + throw TypeError(".google.firestore.v1.Function.options: object expected"); + message.options = {}; + for (var keys = Object.keys(object.options), i = 0; i < keys.length; ++i) { + if (typeof object.options[keys[i]] !== "object") + throw TypeError(".google.firestore.v1.Function.options: object expected"); + message.options[keys[i]] = $root.google.firestore.v1.Value.fromObject(object.options[keys[i]]); + } } - } - if (object.extension) { - if (!Array.isArray(object.extension)) - throw TypeError(".google.protobuf.FileDescriptorProto.extension: array expected"); - message.extension = []; - for (var i = 0; i < object.extension.length; ++i) { - if (typeof object.extension[i] !== "object") - throw TypeError(".google.protobuf.FileDescriptorProto.extension: object expected"); - message.extension[i] = $root.google.protobuf.FieldDescriptorProto.fromObject(object.extension[i]); + return message; + }; + + /** + * Creates a plain object from a Function message. Also converts values to other types if specified. + * @function toObject + * @memberof google.firestore.v1.Function + * @static + * @param {google.firestore.v1.Function} message Function + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + Function.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.arrays || options.defaults) + object.args = []; + if (options.objects || options.defaults) + object.options = {}; + if (options.defaults) + object.name = ""; + if (message.name != null && message.hasOwnProperty("name")) + object.name = message.name; + if (message.args && message.args.length) { + object.args = []; + for (var j = 0; j < message.args.length; ++j) + object.args[j] = $root.google.firestore.v1.Value.toObject(message.args[j], options); } - } - if (object.options != null) { - if (typeof object.options !== "object") - throw TypeError(".google.protobuf.FileDescriptorProto.options: object expected"); - message.options = $root.google.protobuf.FileOptions.fromObject(object.options); - } - if (object.sourceCodeInfo != null) { - if (typeof object.sourceCodeInfo !== "object") - throw TypeError(".google.protobuf.FileDescriptorProto.sourceCodeInfo: object expected"); - message.sourceCodeInfo = $root.google.protobuf.SourceCodeInfo.fromObject(object.sourceCodeInfo); - } - if (object.syntax != null) - message.syntax = String(object.syntax); - switch (object.edition) { - default: - if (typeof object.edition === "number") { - message.edition = object.edition; - break; + var keys2; + if (message.options && (keys2 = Object.keys(message.options)).length) { + object.options = {}; + for (var j = 0; j < keys2.length; ++j) + object.options[keys2[j]] = $root.google.firestore.v1.Value.toObject(message.options[keys2[j]], options); } - break; - case "EDITION_UNKNOWN": - case 0: - message.edition = 0; - break; - case "EDITION_LEGACY": - case 900: - message.edition = 900; - break; - case "EDITION_PROTO2": - case 998: - message.edition = 998; - break; - case "EDITION_PROTO3": - case 999: - message.edition = 999; - break; - case "EDITION_2023": - case 1000: - message.edition = 1000; - break; - case "EDITION_2024": - case 1001: - message.edition = 1001; - break; - case "EDITION_1_TEST_ONLY": - case 1: - message.edition = 1; - break; - case "EDITION_2_TEST_ONLY": - case 2: - message.edition = 2; - break; - case "EDITION_99997_TEST_ONLY": - case 99997: - message.edition = 99997; - break; - case "EDITION_99998_TEST_ONLY": - case 99998: - message.edition = 99998; - break; - case "EDITION_99999_TEST_ONLY": - case 99999: - message.edition = 99999; - break; - case "EDITION_MAX": - case 2147483647: - message.edition = 2147483647; - break; - } - return message; - }; + return object; + }; - /** - * Creates a plain object from a FileDescriptorProto message. Also converts values to other types if specified. - * @function toObject - * @memberof google.protobuf.FileDescriptorProto - * @static - * @param {google.protobuf.FileDescriptorProto} message FileDescriptorProto - * @param {$protobuf.IConversionOptions} [options] Conversion options - * @returns {Object.} Plain object - */ - FileDescriptorProto.toObject = function toObject(message, options) { - if (!options) - options = {}; - var object = {}; - if (options.arrays || options.defaults) { - object.dependency = []; - object.messageType = []; - object.enumType = []; - object.service = []; - object.extension = []; - object.publicDependency = []; - object.weakDependency = []; - } - if (options.defaults) { - object.name = ""; - object["package"] = ""; - object.options = null; - object.sourceCodeInfo = null; - object.syntax = ""; - object.edition = options.enums === String ? "EDITION_UNKNOWN" : 0; - } - if (message.name != null && message.hasOwnProperty("name")) - object.name = message.name; - if (message["package"] != null && message.hasOwnProperty("package")) - object["package"] = message["package"]; - if (message.dependency && message.dependency.length) { - object.dependency = []; - for (var j = 0; j < message.dependency.length; ++j) - object.dependency[j] = message.dependency[j]; - } - if (message.messageType && message.messageType.length) { - object.messageType = []; - for (var j = 0; j < message.messageType.length; ++j) - object.messageType[j] = $root.google.protobuf.DescriptorProto.toObject(message.messageType[j], options); - } - if (message.enumType && message.enumType.length) { - object.enumType = []; - for (var j = 0; j < message.enumType.length; ++j) - object.enumType[j] = $root.google.protobuf.EnumDescriptorProto.toObject(message.enumType[j], options); - } - if (message.service && message.service.length) { - object.service = []; - for (var j = 0; j < message.service.length; ++j) - object.service[j] = $root.google.protobuf.ServiceDescriptorProto.toObject(message.service[j], options); - } - if (message.extension && message.extension.length) { - object.extension = []; - for (var j = 0; j < message.extension.length; ++j) - object.extension[j] = $root.google.protobuf.FieldDescriptorProto.toObject(message.extension[j], options); - } - if (message.options != null && message.hasOwnProperty("options")) - object.options = $root.google.protobuf.FileOptions.toObject(message.options, options); - if (message.sourceCodeInfo != null && message.hasOwnProperty("sourceCodeInfo")) - object.sourceCodeInfo = $root.google.protobuf.SourceCodeInfo.toObject(message.sourceCodeInfo, options); - if (message.publicDependency && message.publicDependency.length) { - object.publicDependency = []; - for (var j = 0; j < message.publicDependency.length; ++j) - object.publicDependency[j] = message.publicDependency[j]; - } - if (message.weakDependency && message.weakDependency.length) { - object.weakDependency = []; - for (var j = 0; j < message.weakDependency.length; ++j) - object.weakDependency[j] = message.weakDependency[j]; - } - if (message.syntax != null && message.hasOwnProperty("syntax")) - object.syntax = message.syntax; - if (message.edition != null && message.hasOwnProperty("edition")) - object.edition = options.enums === String ? $root.google.protobuf.Edition[message.edition] === undefined ? message.edition : $root.google.protobuf.Edition[message.edition] : message.edition; - return object; - }; + /** + * Converts this Function to JSON. + * @function toJSON + * @memberof google.firestore.v1.Function + * @instance + * @returns {Object.} JSON object + */ + Function.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; - /** - * Converts this FileDescriptorProto to JSON. - * @function toJSON - * @memberof google.protobuf.FileDescriptorProto - * @instance - * @returns {Object.} JSON object - */ - FileDescriptorProto.prototype.toJSON = function toJSON() { - return this.constructor.toObject(this, $protobuf.util.toJSONOptions); - }; + /** + * Gets the default type url for Function + * @function getTypeUrl + * @memberof google.firestore.v1.Function + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + Function.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.firestore.v1.Function"; + }; - /** - * Gets the default type url for FileDescriptorProto - * @function getTypeUrl - * @memberof google.protobuf.FileDescriptorProto - * @static - * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") - * @returns {string} The default type url - */ - FileDescriptorProto.getTypeUrl = function getTypeUrl(typeUrlPrefix) { - if (typeUrlPrefix === undefined) { - typeUrlPrefix = "type.googleapis.com"; - } - return typeUrlPrefix + "/google.protobuf.FileDescriptorProto"; - }; + return Function; + })(); - return FileDescriptorProto; - })(); + v1.Pipeline = (function() { - protobuf.DescriptorProto = (function() { + /** + * Properties of a Pipeline. + * @memberof google.firestore.v1 + * @interface IPipeline + * @property {Array.|null} [stages] Pipeline stages + */ - /** - * Properties of a DescriptorProto. - * @memberof google.protobuf - * @interface IDescriptorProto - * @property {string|null} [name] DescriptorProto name - * @property {Array.|null} [field] DescriptorProto field - * @property {Array.|null} [extension] DescriptorProto extension - * @property {Array.|null} [nestedType] DescriptorProto nestedType - * @property {Array.|null} [enumType] DescriptorProto enumType - * @property {Array.|null} [extensionRange] DescriptorProto extensionRange - * @property {Array.|null} [oneofDecl] DescriptorProto oneofDecl - * @property {google.protobuf.IMessageOptions|null} [options] DescriptorProto options - * @property {Array.|null} [reservedRange] DescriptorProto reservedRange - * @property {Array.|null} [reservedName] DescriptorProto reservedName - */ + /** + * Constructs a new Pipeline. + * @memberof google.firestore.v1 + * @classdesc Represents a Pipeline. + * @implements IPipeline + * @constructor + * @param {google.firestore.v1.IPipeline=} [properties] Properties to set + */ + function Pipeline(properties) { + this.stages = []; + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } - /** - * Constructs a new DescriptorProto. - * @memberof google.protobuf - * @classdesc Represents a DescriptorProto. - * @implements IDescriptorProto - * @constructor - * @param {google.protobuf.IDescriptorProto=} [properties] Properties to set - */ - function DescriptorProto(properties) { - this.field = []; - this.extension = []; - this.nestedType = []; - this.enumType = []; - this.extensionRange = []; - this.oneofDecl = []; - this.reservedRange = []; - this.reservedName = []; - if (properties) - for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) - if (properties[keys[i]] != null) - this[keys[i]] = properties[keys[i]]; - } + /** + * Pipeline stages. + * @member {Array.} stages + * @memberof google.firestore.v1.Pipeline + * @instance + */ + Pipeline.prototype.stages = $util.emptyArray; - /** - * DescriptorProto name. - * @member {string} name - * @memberof google.protobuf.DescriptorProto - * @instance - */ - DescriptorProto.prototype.name = ""; + /** + * Creates a Pipeline message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.firestore.v1.Pipeline + * @static + * @param {Object.} object Plain object + * @returns {google.firestore.v1.Pipeline} Pipeline + */ + Pipeline.fromObject = function fromObject(object) { + if (object instanceof $root.google.firestore.v1.Pipeline) + return object; + var message = new $root.google.firestore.v1.Pipeline(); + if (object.stages) { + if (!Array.isArray(object.stages)) + throw TypeError(".google.firestore.v1.Pipeline.stages: array expected"); + message.stages = []; + for (var i = 0; i < object.stages.length; ++i) { + if (typeof object.stages[i] !== "object") + throw TypeError(".google.firestore.v1.Pipeline.stages: object expected"); + message.stages[i] = $root.google.firestore.v1.Pipeline.Stage.fromObject(object.stages[i]); + } + } + return message; + }; - /** - * DescriptorProto field. - * @member {Array.} field - * @memberof google.protobuf.DescriptorProto - * @instance - */ - DescriptorProto.prototype.field = $util.emptyArray; + /** + * Creates a plain object from a Pipeline message. Also converts values to other types if specified. + * @function toObject + * @memberof google.firestore.v1.Pipeline + * @static + * @param {google.firestore.v1.Pipeline} message Pipeline + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + Pipeline.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.arrays || options.defaults) + object.stages = []; + if (message.stages && message.stages.length) { + object.stages = []; + for (var j = 0; j < message.stages.length; ++j) + object.stages[j] = $root.google.firestore.v1.Pipeline.Stage.toObject(message.stages[j], options); + } + return object; + }; - /** - * DescriptorProto extension. - * @member {Array.} extension - * @memberof google.protobuf.DescriptorProto - * @instance - */ - DescriptorProto.prototype.extension = $util.emptyArray; + /** + * Converts this Pipeline to JSON. + * @function toJSON + * @memberof google.firestore.v1.Pipeline + * @instance + * @returns {Object.} JSON object + */ + Pipeline.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; - /** - * DescriptorProto nestedType. - * @member {Array.} nestedType - * @memberof google.protobuf.DescriptorProto - * @instance - */ - DescriptorProto.prototype.nestedType = $util.emptyArray; + /** + * Gets the default type url for Pipeline + * @function getTypeUrl + * @memberof google.firestore.v1.Pipeline + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + Pipeline.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.firestore.v1.Pipeline"; + }; - /** - * DescriptorProto enumType. - * @member {Array.} enumType - * @memberof google.protobuf.DescriptorProto - * @instance - */ - DescriptorProto.prototype.enumType = $util.emptyArray; + Pipeline.Stage = (function() { - /** - * DescriptorProto extensionRange. - * @member {Array.} extensionRange - * @memberof google.protobuf.DescriptorProto - * @instance - */ - DescriptorProto.prototype.extensionRange = $util.emptyArray; + /** + * Properties of a Stage. + * @memberof google.firestore.v1.Pipeline + * @interface IStage + * @property {string|null} [name] Stage name + * @property {Array.|null} [args] Stage args + * @property {Object.|null} [options] Stage options + */ - /** - * DescriptorProto oneofDecl. - * @member {Array.} oneofDecl - * @memberof google.protobuf.DescriptorProto - * @instance - */ - DescriptorProto.prototype.oneofDecl = $util.emptyArray; + /** + * Constructs a new Stage. + * @memberof google.firestore.v1.Pipeline + * @classdesc Represents a Stage. + * @implements IStage + * @constructor + * @param {google.firestore.v1.Pipeline.IStage=} [properties] Properties to set + */ + function Stage(properties) { + this.args = []; + this.options = {}; + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } - /** - * DescriptorProto options. - * @member {google.protobuf.IMessageOptions|null|undefined} options - * @memberof google.protobuf.DescriptorProto - * @instance - */ - DescriptorProto.prototype.options = null; + /** + * Stage name. + * @member {string} name + * @memberof google.firestore.v1.Pipeline.Stage + * @instance + */ + Stage.prototype.name = ""; - /** - * DescriptorProto reservedRange. - * @member {Array.} reservedRange - * @memberof google.protobuf.DescriptorProto - * @instance - */ - DescriptorProto.prototype.reservedRange = $util.emptyArray; + /** + * Stage args. + * @member {Array.} args + * @memberof google.firestore.v1.Pipeline.Stage + * @instance + */ + Stage.prototype.args = $util.emptyArray; - /** - * DescriptorProto reservedName. - * @member {Array.} reservedName - * @memberof google.protobuf.DescriptorProto - * @instance - */ - DescriptorProto.prototype.reservedName = $util.emptyArray; + /** + * Stage options. + * @member {Object.} options + * @memberof google.firestore.v1.Pipeline.Stage + * @instance + */ + Stage.prototype.options = $util.emptyObject; - /** - * Creates a DescriptorProto message from a plain object. Also converts values to their respective internal types. - * @function fromObject - * @memberof google.protobuf.DescriptorProto - * @static - * @param {Object.} object Plain object - * @returns {google.protobuf.DescriptorProto} DescriptorProto - */ - DescriptorProto.fromObject = function fromObject(object) { - if (object instanceof $root.google.protobuf.DescriptorProto) - return object; - var message = new $root.google.protobuf.DescriptorProto(); - if (object.name != null) - message.name = String(object.name); - if (object.field) { - if (!Array.isArray(object.field)) - throw TypeError(".google.protobuf.DescriptorProto.field: array expected"); - message.field = []; - for (var i = 0; i < object.field.length; ++i) { - if (typeof object.field[i] !== "object") - throw TypeError(".google.protobuf.DescriptorProto.field: object expected"); - message.field[i] = $root.google.protobuf.FieldDescriptorProto.fromObject(object.field[i]); - } - } - if (object.extension) { - if (!Array.isArray(object.extension)) - throw TypeError(".google.protobuf.DescriptorProto.extension: array expected"); - message.extension = []; - for (var i = 0; i < object.extension.length; ++i) { - if (typeof object.extension[i] !== "object") - throw TypeError(".google.protobuf.DescriptorProto.extension: object expected"); - message.extension[i] = $root.google.protobuf.FieldDescriptorProto.fromObject(object.extension[i]); - } - } - if (object.nestedType) { - if (!Array.isArray(object.nestedType)) - throw TypeError(".google.protobuf.DescriptorProto.nestedType: array expected"); - message.nestedType = []; - for (var i = 0; i < object.nestedType.length; ++i) { - if (typeof object.nestedType[i] !== "object") - throw TypeError(".google.protobuf.DescriptorProto.nestedType: object expected"); - message.nestedType[i] = $root.google.protobuf.DescriptorProto.fromObject(object.nestedType[i]); - } - } - if (object.enumType) { - if (!Array.isArray(object.enumType)) - throw TypeError(".google.protobuf.DescriptorProto.enumType: array expected"); - message.enumType = []; - for (var i = 0; i < object.enumType.length; ++i) { - if (typeof object.enumType[i] !== "object") - throw TypeError(".google.protobuf.DescriptorProto.enumType: object expected"); - message.enumType[i] = $root.google.protobuf.EnumDescriptorProto.fromObject(object.enumType[i]); - } - } - if (object.extensionRange) { - if (!Array.isArray(object.extensionRange)) - throw TypeError(".google.protobuf.DescriptorProto.extensionRange: array expected"); - message.extensionRange = []; - for (var i = 0; i < object.extensionRange.length; ++i) { - if (typeof object.extensionRange[i] !== "object") - throw TypeError(".google.protobuf.DescriptorProto.extensionRange: object expected"); - message.extensionRange[i] = $root.google.protobuf.DescriptorProto.ExtensionRange.fromObject(object.extensionRange[i]); - } - } - if (object.oneofDecl) { - if (!Array.isArray(object.oneofDecl)) - throw TypeError(".google.protobuf.DescriptorProto.oneofDecl: array expected"); - message.oneofDecl = []; - for (var i = 0; i < object.oneofDecl.length; ++i) { - if (typeof object.oneofDecl[i] !== "object") - throw TypeError(".google.protobuf.DescriptorProto.oneofDecl: object expected"); - message.oneofDecl[i] = $root.google.protobuf.OneofDescriptorProto.fromObject(object.oneofDecl[i]); - } - } - if (object.options != null) { - if (typeof object.options !== "object") - throw TypeError(".google.protobuf.DescriptorProto.options: object expected"); - message.options = $root.google.protobuf.MessageOptions.fromObject(object.options); - } - if (object.reservedRange) { - if (!Array.isArray(object.reservedRange)) - throw TypeError(".google.protobuf.DescriptorProto.reservedRange: array expected"); - message.reservedRange = []; - for (var i = 0; i < object.reservedRange.length; ++i) { - if (typeof object.reservedRange[i] !== "object") - throw TypeError(".google.protobuf.DescriptorProto.reservedRange: object expected"); - message.reservedRange[i] = $root.google.protobuf.DescriptorProto.ReservedRange.fromObject(object.reservedRange[i]); - } - } - if (object.reservedName) { - if (!Array.isArray(object.reservedName)) - throw TypeError(".google.protobuf.DescriptorProto.reservedName: array expected"); - message.reservedName = []; - for (var i = 0; i < object.reservedName.length; ++i) - message.reservedName[i] = String(object.reservedName[i]); - } - return message; - }; + /** + * Creates a Stage message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.firestore.v1.Pipeline.Stage + * @static + * @param {Object.} object Plain object + * @returns {google.firestore.v1.Pipeline.Stage} Stage + */ + Stage.fromObject = function fromObject(object) { + if (object instanceof $root.google.firestore.v1.Pipeline.Stage) + return object; + var message = new $root.google.firestore.v1.Pipeline.Stage(); + if (object.name != null) + message.name = String(object.name); + if (object.args) { + if (!Array.isArray(object.args)) + throw TypeError(".google.firestore.v1.Pipeline.Stage.args: array expected"); + message.args = []; + for (var i = 0; i < object.args.length; ++i) { + if (typeof object.args[i] !== "object") + throw TypeError(".google.firestore.v1.Pipeline.Stage.args: object expected"); + message.args[i] = $root.google.firestore.v1.Value.fromObject(object.args[i]); + } + } + if (object.options) { + if (typeof object.options !== "object") + throw TypeError(".google.firestore.v1.Pipeline.Stage.options: object expected"); + message.options = {}; + for (var keys = Object.keys(object.options), i = 0; i < keys.length; ++i) { + if (typeof object.options[keys[i]] !== "object") + throw TypeError(".google.firestore.v1.Pipeline.Stage.options: object expected"); + message.options[keys[i]] = $root.google.firestore.v1.Value.fromObject(object.options[keys[i]]); + } + } + return message; + }; - /** - * Creates a plain object from a DescriptorProto message. Also converts values to other types if specified. - * @function toObject - * @memberof google.protobuf.DescriptorProto - * @static - * @param {google.protobuf.DescriptorProto} message DescriptorProto - * @param {$protobuf.IConversionOptions} [options] Conversion options - * @returns {Object.} Plain object - */ - DescriptorProto.toObject = function toObject(message, options) { - if (!options) - options = {}; - var object = {}; - if (options.arrays || options.defaults) { - object.field = []; - object.nestedType = []; - object.enumType = []; - object.extensionRange = []; - object.extension = []; - object.oneofDecl = []; - object.reservedRange = []; - object.reservedName = []; - } - if (options.defaults) { - object.name = ""; - object.options = null; - } - if (message.name != null && message.hasOwnProperty("name")) - object.name = message.name; - if (message.field && message.field.length) { - object.field = []; - for (var j = 0; j < message.field.length; ++j) - object.field[j] = $root.google.protobuf.FieldDescriptorProto.toObject(message.field[j], options); - } - if (message.nestedType && message.nestedType.length) { - object.nestedType = []; - for (var j = 0; j < message.nestedType.length; ++j) - object.nestedType[j] = $root.google.protobuf.DescriptorProto.toObject(message.nestedType[j], options); - } - if (message.enumType && message.enumType.length) { - object.enumType = []; - for (var j = 0; j < message.enumType.length; ++j) - object.enumType[j] = $root.google.protobuf.EnumDescriptorProto.toObject(message.enumType[j], options); - } - if (message.extensionRange && message.extensionRange.length) { - object.extensionRange = []; - for (var j = 0; j < message.extensionRange.length; ++j) - object.extensionRange[j] = $root.google.protobuf.DescriptorProto.ExtensionRange.toObject(message.extensionRange[j], options); - } - if (message.extension && message.extension.length) { - object.extension = []; - for (var j = 0; j < message.extension.length; ++j) - object.extension[j] = $root.google.protobuf.FieldDescriptorProto.toObject(message.extension[j], options); - } - if (message.options != null && message.hasOwnProperty("options")) - object.options = $root.google.protobuf.MessageOptions.toObject(message.options, options); - if (message.oneofDecl && message.oneofDecl.length) { - object.oneofDecl = []; - for (var j = 0; j < message.oneofDecl.length; ++j) - object.oneofDecl[j] = $root.google.protobuf.OneofDescriptorProto.toObject(message.oneofDecl[j], options); - } - if (message.reservedRange && message.reservedRange.length) { - object.reservedRange = []; - for (var j = 0; j < message.reservedRange.length; ++j) - object.reservedRange[j] = $root.google.protobuf.DescriptorProto.ReservedRange.toObject(message.reservedRange[j], options); - } - if (message.reservedName && message.reservedName.length) { - object.reservedName = []; - for (var j = 0; j < message.reservedName.length; ++j) - object.reservedName[j] = message.reservedName[j]; - } - return object; - }; + /** + * Creates a plain object from a Stage message. Also converts values to other types if specified. + * @function toObject + * @memberof google.firestore.v1.Pipeline.Stage + * @static + * @param {google.firestore.v1.Pipeline.Stage} message Stage + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + Stage.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.arrays || options.defaults) + object.args = []; + if (options.objects || options.defaults) + object.options = {}; + if (options.defaults) + object.name = ""; + if (message.name != null && message.hasOwnProperty("name")) + object.name = message.name; + if (message.args && message.args.length) { + object.args = []; + for (var j = 0; j < message.args.length; ++j) + object.args[j] = $root.google.firestore.v1.Value.toObject(message.args[j], options); + } + var keys2; + if (message.options && (keys2 = Object.keys(message.options)).length) { + object.options = {}; + for (var j = 0; j < keys2.length; ++j) + object.options[keys2[j]] = $root.google.firestore.v1.Value.toObject(message.options[keys2[j]], options); + } + return object; + }; - /** - * Converts this DescriptorProto to JSON. - * @function toJSON - * @memberof google.protobuf.DescriptorProto - * @instance - * @returns {Object.} JSON object - */ - DescriptorProto.prototype.toJSON = function toJSON() { - return this.constructor.toObject(this, $protobuf.util.toJSONOptions); - }; + /** + * Converts this Stage to JSON. + * @function toJSON + * @memberof google.firestore.v1.Pipeline.Stage + * @instance + * @returns {Object.} JSON object + */ + Stage.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; - /** - * Gets the default type url for DescriptorProto - * @function getTypeUrl - * @memberof google.protobuf.DescriptorProto - * @static - * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") - * @returns {string} The default type url - */ - DescriptorProto.getTypeUrl = function getTypeUrl(typeUrlPrefix) { - if (typeUrlPrefix === undefined) { - typeUrlPrefix = "type.googleapis.com"; - } - return typeUrlPrefix + "/google.protobuf.DescriptorProto"; - }; + /** + * Gets the default type url for Stage + * @function getTypeUrl + * @memberof google.firestore.v1.Pipeline.Stage + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + Stage.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.firestore.v1.Pipeline.Stage"; + }; - DescriptorProto.ExtensionRange = (function() { + return Stage; + })(); + + return Pipeline; + })(); + + v1.BitSequence = (function() { /** - * Properties of an ExtensionRange. - * @memberof google.protobuf.DescriptorProto - * @interface IExtensionRange - * @property {number|null} [start] ExtensionRange start - * @property {number|null} [end] ExtensionRange end - * @property {google.protobuf.IExtensionRangeOptions|null} [options] ExtensionRange options + * Properties of a BitSequence. + * @memberof google.firestore.v1 + * @interface IBitSequence + * @property {Uint8Array|null} [bitmap] BitSequence bitmap + * @property {number|null} [padding] BitSequence padding */ /** - * Constructs a new ExtensionRange. - * @memberof google.protobuf.DescriptorProto - * @classdesc Represents an ExtensionRange. - * @implements IExtensionRange + * Constructs a new BitSequence. + * @memberof google.firestore.v1 + * @classdesc Represents a BitSequence. + * @implements IBitSequence * @constructor - * @param {google.protobuf.DescriptorProto.IExtensionRange=} [properties] Properties to set + * @param {google.firestore.v1.IBitSequence=} [properties] Properties to set */ - function ExtensionRange(properties) { + function BitSequence(properties) { if (properties) for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) if (properties[keys[i]] != null) @@ -2332,128 +2174,121 @@ } /** - * ExtensionRange start. - * @member {number} start - * @memberof google.protobuf.DescriptorProto.ExtensionRange + * BitSequence bitmap. + * @member {Uint8Array} bitmap + * @memberof google.firestore.v1.BitSequence * @instance */ - ExtensionRange.prototype.start = 0; - - /** - * ExtensionRange end. - * @member {number} end - * @memberof google.protobuf.DescriptorProto.ExtensionRange - * @instance - */ - ExtensionRange.prototype.end = 0; + BitSequence.prototype.bitmap = $util.newBuffer([]); /** - * ExtensionRange options. - * @member {google.protobuf.IExtensionRangeOptions|null|undefined} options - * @memberof google.protobuf.DescriptorProto.ExtensionRange + * BitSequence padding. + * @member {number} padding + * @memberof google.firestore.v1.BitSequence * @instance */ - ExtensionRange.prototype.options = null; + BitSequence.prototype.padding = 0; /** - * Creates an ExtensionRange message from a plain object. Also converts values to their respective internal types. + * Creates a BitSequence message from a plain object. Also converts values to their respective internal types. * @function fromObject - * @memberof google.protobuf.DescriptorProto.ExtensionRange + * @memberof google.firestore.v1.BitSequence * @static * @param {Object.} object Plain object - * @returns {google.protobuf.DescriptorProto.ExtensionRange} ExtensionRange + * @returns {google.firestore.v1.BitSequence} BitSequence */ - ExtensionRange.fromObject = function fromObject(object) { - if (object instanceof $root.google.protobuf.DescriptorProto.ExtensionRange) + BitSequence.fromObject = function fromObject(object) { + if (object instanceof $root.google.firestore.v1.BitSequence) return object; - var message = new $root.google.protobuf.DescriptorProto.ExtensionRange(); - if (object.start != null) - message.start = object.start | 0; - if (object.end != null) - message.end = object.end | 0; - if (object.options != null) { - if (typeof object.options !== "object") - throw TypeError(".google.protobuf.DescriptorProto.ExtensionRange.options: object expected"); - message.options = $root.google.protobuf.ExtensionRangeOptions.fromObject(object.options); - } + var message = new $root.google.firestore.v1.BitSequence(); + if (object.bitmap != null) + if (typeof object.bitmap === "string") + $util.base64.decode(object.bitmap, message.bitmap = $util.newBuffer($util.base64.length(object.bitmap)), 0); + else if (object.bitmap.length >= 0) + message.bitmap = object.bitmap; + if (object.padding != null) + message.padding = object.padding | 0; return message; }; /** - * Creates a plain object from an ExtensionRange message. Also converts values to other types if specified. + * Creates a plain object from a BitSequence message. Also converts values to other types if specified. * @function toObject - * @memberof google.protobuf.DescriptorProto.ExtensionRange + * @memberof google.firestore.v1.BitSequence * @static - * @param {google.protobuf.DescriptorProto.ExtensionRange} message ExtensionRange + * @param {google.firestore.v1.BitSequence} message BitSequence * @param {$protobuf.IConversionOptions} [options] Conversion options * @returns {Object.} Plain object */ - ExtensionRange.toObject = function toObject(message, options) { + BitSequence.toObject = function toObject(message, options) { if (!options) options = {}; var object = {}; if (options.defaults) { - object.start = 0; - object.end = 0; - object.options = null; + if (options.bytes === String) + object.bitmap = ""; + else { + object.bitmap = []; + if (options.bytes !== Array) + object.bitmap = $util.newBuffer(object.bitmap); + } + object.padding = 0; } - if (message.start != null && message.hasOwnProperty("start")) - object.start = message.start; - if (message.end != null && message.hasOwnProperty("end")) - object.end = message.end; - if (message.options != null && message.hasOwnProperty("options")) - object.options = $root.google.protobuf.ExtensionRangeOptions.toObject(message.options, options); + if (message.bitmap != null && message.hasOwnProperty("bitmap")) + object.bitmap = options.bytes === String ? $util.base64.encode(message.bitmap, 0, message.bitmap.length) : options.bytes === Array ? Array.prototype.slice.call(message.bitmap) : message.bitmap; + if (message.padding != null && message.hasOwnProperty("padding")) + object.padding = message.padding; return object; }; /** - * Converts this ExtensionRange to JSON. + * Converts this BitSequence to JSON. * @function toJSON - * @memberof google.protobuf.DescriptorProto.ExtensionRange + * @memberof google.firestore.v1.BitSequence * @instance * @returns {Object.} JSON object */ - ExtensionRange.prototype.toJSON = function toJSON() { + BitSequence.prototype.toJSON = function toJSON() { return this.constructor.toObject(this, $protobuf.util.toJSONOptions); }; /** - * Gets the default type url for ExtensionRange + * Gets the default type url for BitSequence * @function getTypeUrl - * @memberof google.protobuf.DescriptorProto.ExtensionRange + * @memberof google.firestore.v1.BitSequence * @static * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") * @returns {string} The default type url */ - ExtensionRange.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + BitSequence.getTypeUrl = function getTypeUrl(typeUrlPrefix) { if (typeUrlPrefix === undefined) { typeUrlPrefix = "type.googleapis.com"; } - return typeUrlPrefix + "/google.protobuf.DescriptorProto.ExtensionRange"; + return typeUrlPrefix + "/google.firestore.v1.BitSequence"; }; - return ExtensionRange; + return BitSequence; })(); - DescriptorProto.ReservedRange = (function() { + v1.BloomFilter = (function() { /** - * Properties of a ReservedRange. - * @memberof google.protobuf.DescriptorProto - * @interface IReservedRange - * @property {number|null} [start] ReservedRange start - * @property {number|null} [end] ReservedRange end + * Properties of a BloomFilter. + * @memberof google.firestore.v1 + * @interface IBloomFilter + * @property {google.firestore.v1.IBitSequence|null} [bits] BloomFilter bits + * @property {number|null} [hashCount] BloomFilter hashCount */ /** - * Constructs a new ReservedRange. - * @memberof google.protobuf.DescriptorProto - * @classdesc Represents a ReservedRange. - * @implements IReservedRange + * Constructs a new BloomFilter. + * @memberof google.firestore.v1 + * @classdesc Represents a BloomFilter. + * @implements IBloomFilter * @constructor - * @param {google.protobuf.DescriptorProto.IReservedRange=} [properties] Properties to set + * @param {google.firestore.v1.IBloomFilter=} [properties] Properties to set */ - function ReservedRange(properties) { + function BloomFilter(properties) { if (properties) for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) if (properties[keys[i]] != null) @@ -2461,299 +2296,222 @@ } /** - * ReservedRange start. - * @member {number} start - * @memberof google.protobuf.DescriptorProto.ReservedRange + * BloomFilter bits. + * @member {google.firestore.v1.IBitSequence|null|undefined} bits + * @memberof google.firestore.v1.BloomFilter * @instance */ - ReservedRange.prototype.start = 0; + BloomFilter.prototype.bits = null; /** - * ReservedRange end. - * @member {number} end - * @memberof google.protobuf.DescriptorProto.ReservedRange + * BloomFilter hashCount. + * @member {number} hashCount + * @memberof google.firestore.v1.BloomFilter * @instance */ - ReservedRange.prototype.end = 0; + BloomFilter.prototype.hashCount = 0; /** - * Creates a ReservedRange message from a plain object. Also converts values to their respective internal types. + * Creates a BloomFilter message from a plain object. Also converts values to their respective internal types. * @function fromObject - * @memberof google.protobuf.DescriptorProto.ReservedRange + * @memberof google.firestore.v1.BloomFilter * @static * @param {Object.} object Plain object - * @returns {google.protobuf.DescriptorProto.ReservedRange} ReservedRange + * @returns {google.firestore.v1.BloomFilter} BloomFilter */ - ReservedRange.fromObject = function fromObject(object) { - if (object instanceof $root.google.protobuf.DescriptorProto.ReservedRange) + BloomFilter.fromObject = function fromObject(object) { + if (object instanceof $root.google.firestore.v1.BloomFilter) return object; - var message = new $root.google.protobuf.DescriptorProto.ReservedRange(); - if (object.start != null) - message.start = object.start | 0; - if (object.end != null) - message.end = object.end | 0; + var message = new $root.google.firestore.v1.BloomFilter(); + if (object.bits != null) { + if (typeof object.bits !== "object") + throw TypeError(".google.firestore.v1.BloomFilter.bits: object expected"); + message.bits = $root.google.firestore.v1.BitSequence.fromObject(object.bits); + } + if (object.hashCount != null) + message.hashCount = object.hashCount | 0; return message; }; /** - * Creates a plain object from a ReservedRange message. Also converts values to other types if specified. + * Creates a plain object from a BloomFilter message. Also converts values to other types if specified. * @function toObject - * @memberof google.protobuf.DescriptorProto.ReservedRange + * @memberof google.firestore.v1.BloomFilter * @static - * @param {google.protobuf.DescriptorProto.ReservedRange} message ReservedRange + * @param {google.firestore.v1.BloomFilter} message BloomFilter * @param {$protobuf.IConversionOptions} [options] Conversion options * @returns {Object.} Plain object */ - ReservedRange.toObject = function toObject(message, options) { + BloomFilter.toObject = function toObject(message, options) { if (!options) options = {}; var object = {}; if (options.defaults) { - object.start = 0; - object.end = 0; + object.bits = null; + object.hashCount = 0; } - if (message.start != null && message.hasOwnProperty("start")) - object.start = message.start; - if (message.end != null && message.hasOwnProperty("end")) - object.end = message.end; + if (message.bits != null && message.hasOwnProperty("bits")) + object.bits = $root.google.firestore.v1.BitSequence.toObject(message.bits, options); + if (message.hashCount != null && message.hasOwnProperty("hashCount")) + object.hashCount = message.hashCount; return object; }; /** - * Converts this ReservedRange to JSON. + * Converts this BloomFilter to JSON. * @function toJSON - * @memberof google.protobuf.DescriptorProto.ReservedRange + * @memberof google.firestore.v1.BloomFilter * @instance * @returns {Object.} JSON object */ - ReservedRange.prototype.toJSON = function toJSON() { + BloomFilter.prototype.toJSON = function toJSON() { return this.constructor.toObject(this, $protobuf.util.toJSONOptions); }; /** - * Gets the default type url for ReservedRange + * Gets the default type url for BloomFilter * @function getTypeUrl - * @memberof google.protobuf.DescriptorProto.ReservedRange + * @memberof google.firestore.v1.BloomFilter * @static * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") * @returns {string} The default type url */ - ReservedRange.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + BloomFilter.getTypeUrl = function getTypeUrl(typeUrlPrefix) { if (typeUrlPrefix === undefined) { typeUrlPrefix = "type.googleapis.com"; } - return typeUrlPrefix + "/google.protobuf.DescriptorProto.ReservedRange"; + return typeUrlPrefix + "/google.firestore.v1.BloomFilter"; }; - return ReservedRange; + return BloomFilter; })(); - return DescriptorProto; - })(); - - protobuf.ExtensionRangeOptions = (function() { + v1.DocumentMask = (function() { - /** - * Properties of an ExtensionRangeOptions. - * @memberof google.protobuf - * @interface IExtensionRangeOptions - * @property {Array.|null} [uninterpretedOption] ExtensionRangeOptions uninterpretedOption - * @property {Array.|null} [declaration] ExtensionRangeOptions declaration - * @property {google.protobuf.IFeatureSet|null} [features] ExtensionRangeOptions features - * @property {google.protobuf.ExtensionRangeOptions.VerificationState|null} [verification] ExtensionRangeOptions verification - */ + /** + * Properties of a DocumentMask. + * @memberof google.firestore.v1 + * @interface IDocumentMask + * @property {Array.|null} [fieldPaths] DocumentMask fieldPaths + */ - /** - * Constructs a new ExtensionRangeOptions. - * @memberof google.protobuf - * @classdesc Represents an ExtensionRangeOptions. - * @implements IExtensionRangeOptions - * @constructor - * @param {google.protobuf.IExtensionRangeOptions=} [properties] Properties to set - */ - function ExtensionRangeOptions(properties) { - this.uninterpretedOption = []; - this.declaration = []; - if (properties) - for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) - if (properties[keys[i]] != null) - this[keys[i]] = properties[keys[i]]; - } + /** + * Constructs a new DocumentMask. + * @memberof google.firestore.v1 + * @classdesc Represents a DocumentMask. + * @implements IDocumentMask + * @constructor + * @param {google.firestore.v1.IDocumentMask=} [properties] Properties to set + */ + function DocumentMask(properties) { + this.fieldPaths = []; + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } - /** - * ExtensionRangeOptions uninterpretedOption. - * @member {Array.} uninterpretedOption - * @memberof google.protobuf.ExtensionRangeOptions - * @instance - */ - ExtensionRangeOptions.prototype.uninterpretedOption = $util.emptyArray; + /** + * DocumentMask fieldPaths. + * @member {Array.} fieldPaths + * @memberof google.firestore.v1.DocumentMask + * @instance + */ + DocumentMask.prototype.fieldPaths = $util.emptyArray; - /** - * ExtensionRangeOptions declaration. - * @member {Array.} declaration - * @memberof google.protobuf.ExtensionRangeOptions - * @instance - */ - ExtensionRangeOptions.prototype.declaration = $util.emptyArray; - - /** - * ExtensionRangeOptions features. - * @member {google.protobuf.IFeatureSet|null|undefined} features - * @memberof google.protobuf.ExtensionRangeOptions - * @instance - */ - ExtensionRangeOptions.prototype.features = null; - - /** - * ExtensionRangeOptions verification. - * @member {google.protobuf.ExtensionRangeOptions.VerificationState} verification - * @memberof google.protobuf.ExtensionRangeOptions - * @instance - */ - ExtensionRangeOptions.prototype.verification = 1; - - /** - * Creates an ExtensionRangeOptions message from a plain object. Also converts values to their respective internal types. - * @function fromObject - * @memberof google.protobuf.ExtensionRangeOptions - * @static - * @param {Object.} object Plain object - * @returns {google.protobuf.ExtensionRangeOptions} ExtensionRangeOptions - */ - ExtensionRangeOptions.fromObject = function fromObject(object) { - if (object instanceof $root.google.protobuf.ExtensionRangeOptions) - return object; - var message = new $root.google.protobuf.ExtensionRangeOptions(); - if (object.uninterpretedOption) { - if (!Array.isArray(object.uninterpretedOption)) - throw TypeError(".google.protobuf.ExtensionRangeOptions.uninterpretedOption: array expected"); - message.uninterpretedOption = []; - for (var i = 0; i < object.uninterpretedOption.length; ++i) { - if (typeof object.uninterpretedOption[i] !== "object") - throw TypeError(".google.protobuf.ExtensionRangeOptions.uninterpretedOption: object expected"); - message.uninterpretedOption[i] = $root.google.protobuf.UninterpretedOption.fromObject(object.uninterpretedOption[i]); - } - } - if (object.declaration) { - if (!Array.isArray(object.declaration)) - throw TypeError(".google.protobuf.ExtensionRangeOptions.declaration: array expected"); - message.declaration = []; - for (var i = 0; i < object.declaration.length; ++i) { - if (typeof object.declaration[i] !== "object") - throw TypeError(".google.protobuf.ExtensionRangeOptions.declaration: object expected"); - message.declaration[i] = $root.google.protobuf.ExtensionRangeOptions.Declaration.fromObject(object.declaration[i]); + /** + * Creates a DocumentMask message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.firestore.v1.DocumentMask + * @static + * @param {Object.} object Plain object + * @returns {google.firestore.v1.DocumentMask} DocumentMask + */ + DocumentMask.fromObject = function fromObject(object) { + if (object instanceof $root.google.firestore.v1.DocumentMask) + return object; + var message = new $root.google.firestore.v1.DocumentMask(); + if (object.fieldPaths) { + if (!Array.isArray(object.fieldPaths)) + throw TypeError(".google.firestore.v1.DocumentMask.fieldPaths: array expected"); + message.fieldPaths = []; + for (var i = 0; i < object.fieldPaths.length; ++i) + message.fieldPaths[i] = String(object.fieldPaths[i]); } - } - if (object.features != null) { - if (typeof object.features !== "object") - throw TypeError(".google.protobuf.ExtensionRangeOptions.features: object expected"); - message.features = $root.google.protobuf.FeatureSet.fromObject(object.features); - } - switch (object.verification) { - case "DECLARATION": - case 0: - message.verification = 0; - break; - default: - if (typeof object.verification === "number") { - message.verification = object.verification; - break; + return message; + }; + + /** + * Creates a plain object from a DocumentMask message. Also converts values to other types if specified. + * @function toObject + * @memberof google.firestore.v1.DocumentMask + * @static + * @param {google.firestore.v1.DocumentMask} message DocumentMask + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + DocumentMask.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.arrays || options.defaults) + object.fieldPaths = []; + if (message.fieldPaths && message.fieldPaths.length) { + object.fieldPaths = []; + for (var j = 0; j < message.fieldPaths.length; ++j) + object.fieldPaths[j] = message.fieldPaths[j]; } - break; - case "UNVERIFIED": - case 1: - message.verification = 1; - break; - } - return message; - }; + return object; + }; - /** - * Creates a plain object from an ExtensionRangeOptions message. Also converts values to other types if specified. - * @function toObject - * @memberof google.protobuf.ExtensionRangeOptions - * @static - * @param {google.protobuf.ExtensionRangeOptions} message ExtensionRangeOptions - * @param {$protobuf.IConversionOptions} [options] Conversion options - * @returns {Object.} Plain object - */ - ExtensionRangeOptions.toObject = function toObject(message, options) { - if (!options) - options = {}; - var object = {}; - if (options.arrays || options.defaults) { - object.declaration = []; - object.uninterpretedOption = []; - } - if (options.defaults) { - object.verification = options.enums === String ? "UNVERIFIED" : 1; - object.features = null; - } - if (message.declaration && message.declaration.length) { - object.declaration = []; - for (var j = 0; j < message.declaration.length; ++j) - object.declaration[j] = $root.google.protobuf.ExtensionRangeOptions.Declaration.toObject(message.declaration[j], options); - } - if (message.verification != null && message.hasOwnProperty("verification")) - object.verification = options.enums === String ? $root.google.protobuf.ExtensionRangeOptions.VerificationState[message.verification] === undefined ? message.verification : $root.google.protobuf.ExtensionRangeOptions.VerificationState[message.verification] : message.verification; - if (message.features != null && message.hasOwnProperty("features")) - object.features = $root.google.protobuf.FeatureSet.toObject(message.features, options); - if (message.uninterpretedOption && message.uninterpretedOption.length) { - object.uninterpretedOption = []; - for (var j = 0; j < message.uninterpretedOption.length; ++j) - object.uninterpretedOption[j] = $root.google.protobuf.UninterpretedOption.toObject(message.uninterpretedOption[j], options); - } - return object; - }; + /** + * Converts this DocumentMask to JSON. + * @function toJSON + * @memberof google.firestore.v1.DocumentMask + * @instance + * @returns {Object.} JSON object + */ + DocumentMask.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; - /** - * Converts this ExtensionRangeOptions to JSON. - * @function toJSON - * @memberof google.protobuf.ExtensionRangeOptions - * @instance - * @returns {Object.} JSON object - */ - ExtensionRangeOptions.prototype.toJSON = function toJSON() { - return this.constructor.toObject(this, $protobuf.util.toJSONOptions); - }; + /** + * Gets the default type url for DocumentMask + * @function getTypeUrl + * @memberof google.firestore.v1.DocumentMask + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + DocumentMask.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.firestore.v1.DocumentMask"; + }; - /** - * Gets the default type url for ExtensionRangeOptions - * @function getTypeUrl - * @memberof google.protobuf.ExtensionRangeOptions - * @static - * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") - * @returns {string} The default type url - */ - ExtensionRangeOptions.getTypeUrl = function getTypeUrl(typeUrlPrefix) { - if (typeUrlPrefix === undefined) { - typeUrlPrefix = "type.googleapis.com"; - } - return typeUrlPrefix + "/google.protobuf.ExtensionRangeOptions"; - }; + return DocumentMask; + })(); - ExtensionRangeOptions.Declaration = (function() { + v1.Precondition = (function() { /** - * Properties of a Declaration. - * @memberof google.protobuf.ExtensionRangeOptions - * @interface IDeclaration - * @property {number|null} [number] Declaration number - * @property {string|null} [fullName] Declaration fullName - * @property {string|null} [type] Declaration type - * @property {boolean|null} [reserved] Declaration reserved - * @property {boolean|null} [repeated] Declaration repeated + * Properties of a Precondition. + * @memberof google.firestore.v1 + * @interface IPrecondition + * @property {boolean|null} [exists] Precondition exists + * @property {google.protobuf.ITimestamp|null} [updateTime] Precondition updateTime */ /** - * Constructs a new Declaration. - * @memberof google.protobuf.ExtensionRangeOptions - * @classdesc Represents a Declaration. - * @implements IDeclaration + * Constructs a new Precondition. + * @memberof google.firestore.v1 + * @classdesc Represents a Precondition. + * @implements IPrecondition * @constructor - * @param {google.protobuf.ExtensionRangeOptions.IDeclaration=} [properties] Properties to set + * @param {google.firestore.v1.IPrecondition=} [properties] Properties to set */ - function Declaration(properties) { + function Precondition(properties) { if (properties) for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) if (properties[keys[i]] != null) @@ -2761,2686 +2519,1605 @@ } /** - * Declaration number. - * @member {number} number - * @memberof google.protobuf.ExtensionRangeOptions.Declaration + * Precondition exists. + * @member {boolean|null|undefined} exists + * @memberof google.firestore.v1.Precondition * @instance */ - Declaration.prototype.number = 0; + Precondition.prototype.exists = null; /** - * Declaration fullName. - * @member {string} fullName - * @memberof google.protobuf.ExtensionRangeOptions.Declaration + * Precondition updateTime. + * @member {google.protobuf.ITimestamp|null|undefined} updateTime + * @memberof google.firestore.v1.Precondition * @instance */ - Declaration.prototype.fullName = ""; + Precondition.prototype.updateTime = null; + + // OneOf field names bound to virtual getters and setters + var $oneOfFields; /** - * Declaration type. - * @member {string} type - * @memberof google.protobuf.ExtensionRangeOptions.Declaration + * Precondition conditionType. + * @member {"exists"|"updateTime"|undefined} conditionType + * @memberof google.firestore.v1.Precondition * @instance */ - Declaration.prototype.type = ""; + Object.defineProperty(Precondition.prototype, "conditionType", { + get: $util.oneOfGetter($oneOfFields = ["exists", "updateTime"]), + set: $util.oneOfSetter($oneOfFields) + }); /** - * Declaration reserved. - * @member {boolean} reserved - * @memberof google.protobuf.ExtensionRangeOptions.Declaration + * Creates a Precondition message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.firestore.v1.Precondition + * @static + * @param {Object.} object Plain object + * @returns {google.firestore.v1.Precondition} Precondition + */ + Precondition.fromObject = function fromObject(object) { + if (object instanceof $root.google.firestore.v1.Precondition) + return object; + var message = new $root.google.firestore.v1.Precondition(); + if (object.exists != null) + message.exists = Boolean(object.exists); + if (object.updateTime != null) { + if (typeof object.updateTime !== "object") + throw TypeError(".google.firestore.v1.Precondition.updateTime: object expected"); + message.updateTime = $root.google.protobuf.Timestamp.fromObject(object.updateTime); + } + return message; + }; + + /** + * Creates a plain object from a Precondition message. Also converts values to other types if specified. + * @function toObject + * @memberof google.firestore.v1.Precondition + * @static + * @param {google.firestore.v1.Precondition} message Precondition + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + Precondition.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (message.exists != null && message.hasOwnProperty("exists")) { + object.exists = message.exists; + if (options.oneofs) + object.conditionType = "exists"; + } + if (message.updateTime != null && message.hasOwnProperty("updateTime")) { + object.updateTime = $root.google.protobuf.Timestamp.toObject(message.updateTime, options); + if (options.oneofs) + object.conditionType = "updateTime"; + } + return object; + }; + + /** + * Converts this Precondition to JSON. + * @function toJSON + * @memberof google.firestore.v1.Precondition * @instance + * @returns {Object.} JSON object */ - Declaration.prototype.reserved = false; + Precondition.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; /** - * Declaration repeated. - * @member {boolean} repeated - * @memberof google.protobuf.ExtensionRangeOptions.Declaration + * Gets the default type url for Precondition + * @function getTypeUrl + * @memberof google.firestore.v1.Precondition + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + Precondition.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.firestore.v1.Precondition"; + }; + + return Precondition; + })(); + + v1.TransactionOptions = (function() { + + /** + * Properties of a TransactionOptions. + * @memberof google.firestore.v1 + * @interface ITransactionOptions + * @property {google.firestore.v1.TransactionOptions.IReadOnly|null} [readOnly] TransactionOptions readOnly + * @property {google.firestore.v1.TransactionOptions.IReadWrite|null} [readWrite] TransactionOptions readWrite + */ + + /** + * Constructs a new TransactionOptions. + * @memberof google.firestore.v1 + * @classdesc Represents a TransactionOptions. + * @implements ITransactionOptions + * @constructor + * @param {google.firestore.v1.ITransactionOptions=} [properties] Properties to set + */ + function TransactionOptions(properties) { + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } + + /** + * TransactionOptions readOnly. + * @member {google.firestore.v1.TransactionOptions.IReadOnly|null|undefined} readOnly + * @memberof google.firestore.v1.TransactionOptions * @instance */ - Declaration.prototype.repeated = false; + TransactionOptions.prototype.readOnly = null; /** - * Creates a Declaration message from a plain object. Also converts values to their respective internal types. + * TransactionOptions readWrite. + * @member {google.firestore.v1.TransactionOptions.IReadWrite|null|undefined} readWrite + * @memberof google.firestore.v1.TransactionOptions + * @instance + */ + TransactionOptions.prototype.readWrite = null; + + // OneOf field names bound to virtual getters and setters + var $oneOfFields; + + /** + * TransactionOptions mode. + * @member {"readOnly"|"readWrite"|undefined} mode + * @memberof google.firestore.v1.TransactionOptions + * @instance + */ + Object.defineProperty(TransactionOptions.prototype, "mode", { + get: $util.oneOfGetter($oneOfFields = ["readOnly", "readWrite"]), + set: $util.oneOfSetter($oneOfFields) + }); + + /** + * Creates a TransactionOptions message from a plain object. Also converts values to their respective internal types. * @function fromObject - * @memberof google.protobuf.ExtensionRangeOptions.Declaration + * @memberof google.firestore.v1.TransactionOptions * @static * @param {Object.} object Plain object - * @returns {google.protobuf.ExtensionRangeOptions.Declaration} Declaration + * @returns {google.firestore.v1.TransactionOptions} TransactionOptions */ - Declaration.fromObject = function fromObject(object) { - if (object instanceof $root.google.protobuf.ExtensionRangeOptions.Declaration) + TransactionOptions.fromObject = function fromObject(object) { + if (object instanceof $root.google.firestore.v1.TransactionOptions) return object; - var message = new $root.google.protobuf.ExtensionRangeOptions.Declaration(); - if (object.number != null) - message.number = object.number | 0; - if (object.fullName != null) - message.fullName = String(object.fullName); - if (object.type != null) - message.type = String(object.type); - if (object.reserved != null) - message.reserved = Boolean(object.reserved); - if (object.repeated != null) - message.repeated = Boolean(object.repeated); + var message = new $root.google.firestore.v1.TransactionOptions(); + if (object.readOnly != null) { + if (typeof object.readOnly !== "object") + throw TypeError(".google.firestore.v1.TransactionOptions.readOnly: object expected"); + message.readOnly = $root.google.firestore.v1.TransactionOptions.ReadOnly.fromObject(object.readOnly); + } + if (object.readWrite != null) { + if (typeof object.readWrite !== "object") + throw TypeError(".google.firestore.v1.TransactionOptions.readWrite: object expected"); + message.readWrite = $root.google.firestore.v1.TransactionOptions.ReadWrite.fromObject(object.readWrite); + } return message; }; /** - * Creates a plain object from a Declaration message. Also converts values to other types if specified. + * Creates a plain object from a TransactionOptions message. Also converts values to other types if specified. * @function toObject - * @memberof google.protobuf.ExtensionRangeOptions.Declaration + * @memberof google.firestore.v1.TransactionOptions * @static - * @param {google.protobuf.ExtensionRangeOptions.Declaration} message Declaration + * @param {google.firestore.v1.TransactionOptions} message TransactionOptions * @param {$protobuf.IConversionOptions} [options] Conversion options * @returns {Object.} Plain object */ - Declaration.toObject = function toObject(message, options) { + TransactionOptions.toObject = function toObject(message, options) { if (!options) options = {}; var object = {}; - if (options.defaults) { - object.number = 0; - object.fullName = ""; - object.type = ""; - object.reserved = false; - object.repeated = false; + if (message.readOnly != null && message.hasOwnProperty("readOnly")) { + object.readOnly = $root.google.firestore.v1.TransactionOptions.ReadOnly.toObject(message.readOnly, options); + if (options.oneofs) + object.mode = "readOnly"; + } + if (message.readWrite != null && message.hasOwnProperty("readWrite")) { + object.readWrite = $root.google.firestore.v1.TransactionOptions.ReadWrite.toObject(message.readWrite, options); + if (options.oneofs) + object.mode = "readWrite"; } - if (message.number != null && message.hasOwnProperty("number")) - object.number = message.number; - if (message.fullName != null && message.hasOwnProperty("fullName")) - object.fullName = message.fullName; - if (message.type != null && message.hasOwnProperty("type")) - object.type = message.type; - if (message.reserved != null && message.hasOwnProperty("reserved")) - object.reserved = message.reserved; - if (message.repeated != null && message.hasOwnProperty("repeated")) - object.repeated = message.repeated; return object; }; /** - * Converts this Declaration to JSON. + * Converts this TransactionOptions to JSON. * @function toJSON - * @memberof google.protobuf.ExtensionRangeOptions.Declaration + * @memberof google.firestore.v1.TransactionOptions * @instance * @returns {Object.} JSON object */ - Declaration.prototype.toJSON = function toJSON() { + TransactionOptions.prototype.toJSON = function toJSON() { return this.constructor.toObject(this, $protobuf.util.toJSONOptions); }; /** - * Gets the default type url for Declaration + * Gets the default type url for TransactionOptions * @function getTypeUrl - * @memberof google.protobuf.ExtensionRangeOptions.Declaration + * @memberof google.firestore.v1.TransactionOptions * @static * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") * @returns {string} The default type url */ - Declaration.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + TransactionOptions.getTypeUrl = function getTypeUrl(typeUrlPrefix) { if (typeUrlPrefix === undefined) { typeUrlPrefix = "type.googleapis.com"; } - return typeUrlPrefix + "/google.protobuf.ExtensionRangeOptions.Declaration"; + return typeUrlPrefix + "/google.firestore.v1.TransactionOptions"; }; - return Declaration; - })(); - - /** - * VerificationState enum. - * @name google.protobuf.ExtensionRangeOptions.VerificationState - * @enum {string} - * @property {string} DECLARATION=DECLARATION DECLARATION value - * @property {string} UNVERIFIED=UNVERIFIED UNVERIFIED value - */ - ExtensionRangeOptions.VerificationState = (function() { - var valuesById = {}, values = Object.create(valuesById); - values[valuesById[0] = "DECLARATION"] = "DECLARATION"; - values[valuesById[1] = "UNVERIFIED"] = "UNVERIFIED"; - return values; - })(); + TransactionOptions.ReadWrite = (function() { - return ExtensionRangeOptions; - })(); + /** + * Properties of a ReadWrite. + * @memberof google.firestore.v1.TransactionOptions + * @interface IReadWrite + * @property {Uint8Array|null} [retryTransaction] ReadWrite retryTransaction + */ - protobuf.FieldDescriptorProto = (function() { + /** + * Constructs a new ReadWrite. + * @memberof google.firestore.v1.TransactionOptions + * @classdesc Represents a ReadWrite. + * @implements IReadWrite + * @constructor + * @param {google.firestore.v1.TransactionOptions.IReadWrite=} [properties] Properties to set + */ + function ReadWrite(properties) { + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } - /** - * Properties of a FieldDescriptorProto. - * @memberof google.protobuf - * @interface IFieldDescriptorProto - * @property {string|null} [name] FieldDescriptorProto name - * @property {number|null} [number] FieldDescriptorProto number - * @property {google.protobuf.FieldDescriptorProto.Label|null} [label] FieldDescriptorProto label - * @property {google.protobuf.FieldDescriptorProto.Type|null} [type] FieldDescriptorProto type - * @property {string|null} [typeName] FieldDescriptorProto typeName - * @property {string|null} [extendee] FieldDescriptorProto extendee - * @property {string|null} [defaultValue] FieldDescriptorProto defaultValue - * @property {number|null} [oneofIndex] FieldDescriptorProto oneofIndex - * @property {string|null} [jsonName] FieldDescriptorProto jsonName - * @property {google.protobuf.IFieldOptions|null} [options] FieldDescriptorProto options - * @property {boolean|null} [proto3Optional] FieldDescriptorProto proto3Optional - */ + /** + * ReadWrite retryTransaction. + * @member {Uint8Array} retryTransaction + * @memberof google.firestore.v1.TransactionOptions.ReadWrite + * @instance + */ + ReadWrite.prototype.retryTransaction = $util.newBuffer([]); - /** - * Constructs a new FieldDescriptorProto. - * @memberof google.protobuf - * @classdesc Represents a FieldDescriptorProto. - * @implements IFieldDescriptorProto - * @constructor - * @param {google.protobuf.IFieldDescriptorProto=} [properties] Properties to set - */ - function FieldDescriptorProto(properties) { - if (properties) - for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) - if (properties[keys[i]] != null) - this[keys[i]] = properties[keys[i]]; - } + /** + * Creates a ReadWrite message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.firestore.v1.TransactionOptions.ReadWrite + * @static + * @param {Object.} object Plain object + * @returns {google.firestore.v1.TransactionOptions.ReadWrite} ReadWrite + */ + ReadWrite.fromObject = function fromObject(object) { + if (object instanceof $root.google.firestore.v1.TransactionOptions.ReadWrite) + return object; + var message = new $root.google.firestore.v1.TransactionOptions.ReadWrite(); + if (object.retryTransaction != null) + if (typeof object.retryTransaction === "string") + $util.base64.decode(object.retryTransaction, message.retryTransaction = $util.newBuffer($util.base64.length(object.retryTransaction)), 0); + else if (object.retryTransaction.length >= 0) + message.retryTransaction = object.retryTransaction; + return message; + }; - /** - * FieldDescriptorProto name. - * @member {string} name - * @memberof google.protobuf.FieldDescriptorProto - * @instance - */ - FieldDescriptorProto.prototype.name = ""; + /** + * Creates a plain object from a ReadWrite message. Also converts values to other types if specified. + * @function toObject + * @memberof google.firestore.v1.TransactionOptions.ReadWrite + * @static + * @param {google.firestore.v1.TransactionOptions.ReadWrite} message ReadWrite + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + ReadWrite.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.defaults) + if (options.bytes === String) + object.retryTransaction = ""; + else { + object.retryTransaction = []; + if (options.bytes !== Array) + object.retryTransaction = $util.newBuffer(object.retryTransaction); + } + if (message.retryTransaction != null && message.hasOwnProperty("retryTransaction")) + object.retryTransaction = options.bytes === String ? $util.base64.encode(message.retryTransaction, 0, message.retryTransaction.length) : options.bytes === Array ? Array.prototype.slice.call(message.retryTransaction) : message.retryTransaction; + return object; + }; - /** - * FieldDescriptorProto number. - * @member {number} number - * @memberof google.protobuf.FieldDescriptorProto - * @instance - */ - FieldDescriptorProto.prototype.number = 0; + /** + * Converts this ReadWrite to JSON. + * @function toJSON + * @memberof google.firestore.v1.TransactionOptions.ReadWrite + * @instance + * @returns {Object.} JSON object + */ + ReadWrite.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; - /** - * FieldDescriptorProto label. - * @member {google.protobuf.FieldDescriptorProto.Label} label - * @memberof google.protobuf.FieldDescriptorProto - * @instance - */ - FieldDescriptorProto.prototype.label = 1; + /** + * Gets the default type url for ReadWrite + * @function getTypeUrl + * @memberof google.firestore.v1.TransactionOptions.ReadWrite + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + ReadWrite.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.firestore.v1.TransactionOptions.ReadWrite"; + }; - /** - * FieldDescriptorProto type. - * @member {google.protobuf.FieldDescriptorProto.Type} type - * @memberof google.protobuf.FieldDescriptorProto - * @instance - */ - FieldDescriptorProto.prototype.type = 1; + return ReadWrite; + })(); - /** - * FieldDescriptorProto typeName. - * @member {string} typeName - * @memberof google.protobuf.FieldDescriptorProto - * @instance - */ - FieldDescriptorProto.prototype.typeName = ""; + TransactionOptions.ReadOnly = (function() { - /** - * FieldDescriptorProto extendee. - * @member {string} extendee - * @memberof google.protobuf.FieldDescriptorProto - * @instance - */ - FieldDescriptorProto.prototype.extendee = ""; + /** + * Properties of a ReadOnly. + * @memberof google.firestore.v1.TransactionOptions + * @interface IReadOnly + * @property {google.protobuf.ITimestamp|null} [readTime] ReadOnly readTime + */ - /** - * FieldDescriptorProto defaultValue. - * @member {string} defaultValue - * @memberof google.protobuf.FieldDescriptorProto - * @instance - */ - FieldDescriptorProto.prototype.defaultValue = ""; + /** + * Constructs a new ReadOnly. + * @memberof google.firestore.v1.TransactionOptions + * @classdesc Represents a ReadOnly. + * @implements IReadOnly + * @constructor + * @param {google.firestore.v1.TransactionOptions.IReadOnly=} [properties] Properties to set + */ + function ReadOnly(properties) { + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } - /** - * FieldDescriptorProto oneofIndex. - * @member {number} oneofIndex - * @memberof google.protobuf.FieldDescriptorProto - * @instance - */ - FieldDescriptorProto.prototype.oneofIndex = 0; + /** + * ReadOnly readTime. + * @member {google.protobuf.ITimestamp|null|undefined} readTime + * @memberof google.firestore.v1.TransactionOptions.ReadOnly + * @instance + */ + ReadOnly.prototype.readTime = null; - /** - * FieldDescriptorProto jsonName. - * @member {string} jsonName - * @memberof google.protobuf.FieldDescriptorProto - * @instance - */ - FieldDescriptorProto.prototype.jsonName = ""; + // OneOf field names bound to virtual getters and setters + var $oneOfFields; - /** - * FieldDescriptorProto options. - * @member {google.protobuf.IFieldOptions|null|undefined} options - * @memberof google.protobuf.FieldDescriptorProto - * @instance - */ - FieldDescriptorProto.prototype.options = null; + /** + * ReadOnly consistencySelector. + * @member {"readTime"|undefined} consistencySelector + * @memberof google.firestore.v1.TransactionOptions.ReadOnly + * @instance + */ + Object.defineProperty(ReadOnly.prototype, "consistencySelector", { + get: $util.oneOfGetter($oneOfFields = ["readTime"]), + set: $util.oneOfSetter($oneOfFields) + }); - /** - * FieldDescriptorProto proto3Optional. - * @member {boolean} proto3Optional - * @memberof google.protobuf.FieldDescriptorProto - * @instance - */ - FieldDescriptorProto.prototype.proto3Optional = false; + /** + * Creates a ReadOnly message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.firestore.v1.TransactionOptions.ReadOnly + * @static + * @param {Object.} object Plain object + * @returns {google.firestore.v1.TransactionOptions.ReadOnly} ReadOnly + */ + ReadOnly.fromObject = function fromObject(object) { + if (object instanceof $root.google.firestore.v1.TransactionOptions.ReadOnly) + return object; + var message = new $root.google.firestore.v1.TransactionOptions.ReadOnly(); + if (object.readTime != null) { + if (typeof object.readTime !== "object") + throw TypeError(".google.firestore.v1.TransactionOptions.ReadOnly.readTime: object expected"); + message.readTime = $root.google.protobuf.Timestamp.fromObject(object.readTime); + } + return message; + }; - /** - * Creates a FieldDescriptorProto message from a plain object. Also converts values to their respective internal types. - * @function fromObject - * @memberof google.protobuf.FieldDescriptorProto - * @static - * @param {Object.} object Plain object - * @returns {google.protobuf.FieldDescriptorProto} FieldDescriptorProto - */ - FieldDescriptorProto.fromObject = function fromObject(object) { - if (object instanceof $root.google.protobuf.FieldDescriptorProto) - return object; - var message = new $root.google.protobuf.FieldDescriptorProto(); - if (object.name != null) - message.name = String(object.name); - if (object.number != null) - message.number = object.number | 0; - switch (object.label) { - default: - if (typeof object.label === "number") { - message.label = object.label; - break; - } - break; - case "LABEL_OPTIONAL": - case 1: - message.label = 1; - break; - case "LABEL_REPEATED": - case 3: - message.label = 3; - break; - case "LABEL_REQUIRED": - case 2: - message.label = 2; - break; - } - switch (object.type) { - default: - if (typeof object.type === "number") { - message.type = object.type; - break; - } - break; - case "TYPE_DOUBLE": - case 1: - message.type = 1; - break; - case "TYPE_FLOAT": - case 2: - message.type = 2; - break; - case "TYPE_INT64": - case 3: - message.type = 3; - break; - case "TYPE_UINT64": - case 4: - message.type = 4; - break; - case "TYPE_INT32": - case 5: - message.type = 5; - break; - case "TYPE_FIXED64": - case 6: - message.type = 6; - break; - case "TYPE_FIXED32": - case 7: - message.type = 7; - break; - case "TYPE_BOOL": - case 8: - message.type = 8; - break; - case "TYPE_STRING": - case 9: - message.type = 9; - break; - case "TYPE_GROUP": - case 10: - message.type = 10; - break; - case "TYPE_MESSAGE": - case 11: - message.type = 11; - break; - case "TYPE_BYTES": - case 12: - message.type = 12; - break; - case "TYPE_UINT32": - case 13: - message.type = 13; - break; - case "TYPE_ENUM": - case 14: - message.type = 14; - break; - case "TYPE_SFIXED32": - case 15: - message.type = 15; - break; - case "TYPE_SFIXED64": - case 16: - message.type = 16; - break; - case "TYPE_SINT32": - case 17: - message.type = 17; - break; - case "TYPE_SINT64": - case 18: - message.type = 18; - break; - } - if (object.typeName != null) - message.typeName = String(object.typeName); - if (object.extendee != null) - message.extendee = String(object.extendee); - if (object.defaultValue != null) - message.defaultValue = String(object.defaultValue); - if (object.oneofIndex != null) - message.oneofIndex = object.oneofIndex | 0; - if (object.jsonName != null) - message.jsonName = String(object.jsonName); - if (object.options != null) { - if (typeof object.options !== "object") - throw TypeError(".google.protobuf.FieldDescriptorProto.options: object expected"); - message.options = $root.google.protobuf.FieldOptions.fromObject(object.options); - } - if (object.proto3Optional != null) - message.proto3Optional = Boolean(object.proto3Optional); - return message; - }; + /** + * Creates a plain object from a ReadOnly message. Also converts values to other types if specified. + * @function toObject + * @memberof google.firestore.v1.TransactionOptions.ReadOnly + * @static + * @param {google.firestore.v1.TransactionOptions.ReadOnly} message ReadOnly + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + ReadOnly.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (message.readTime != null && message.hasOwnProperty("readTime")) { + object.readTime = $root.google.protobuf.Timestamp.toObject(message.readTime, options); + if (options.oneofs) + object.consistencySelector = "readTime"; + } + return object; + }; - /** - * Creates a plain object from a FieldDescriptorProto message. Also converts values to other types if specified. - * @function toObject - * @memberof google.protobuf.FieldDescriptorProto - * @static - * @param {google.protobuf.FieldDescriptorProto} message FieldDescriptorProto - * @param {$protobuf.IConversionOptions} [options] Conversion options - * @returns {Object.} Plain object - */ - FieldDescriptorProto.toObject = function toObject(message, options) { - if (!options) - options = {}; - var object = {}; - if (options.defaults) { - object.name = ""; - object.extendee = ""; - object.number = 0; - object.label = options.enums === String ? "LABEL_OPTIONAL" : 1; - object.type = options.enums === String ? "TYPE_DOUBLE" : 1; - object.typeName = ""; - object.defaultValue = ""; - object.options = null; - object.oneofIndex = 0; - object.jsonName = ""; - object.proto3Optional = false; - } - if (message.name != null && message.hasOwnProperty("name")) - object.name = message.name; - if (message.extendee != null && message.hasOwnProperty("extendee")) - object.extendee = message.extendee; - if (message.number != null && message.hasOwnProperty("number")) - object.number = message.number; - if (message.label != null && message.hasOwnProperty("label")) - object.label = options.enums === String ? $root.google.protobuf.FieldDescriptorProto.Label[message.label] === undefined ? message.label : $root.google.protobuf.FieldDescriptorProto.Label[message.label] : message.label; - if (message.type != null && message.hasOwnProperty("type")) - object.type = options.enums === String ? $root.google.protobuf.FieldDescriptorProto.Type[message.type] === undefined ? message.type : $root.google.protobuf.FieldDescriptorProto.Type[message.type] : message.type; - if (message.typeName != null && message.hasOwnProperty("typeName")) - object.typeName = message.typeName; - if (message.defaultValue != null && message.hasOwnProperty("defaultValue")) - object.defaultValue = message.defaultValue; - if (message.options != null && message.hasOwnProperty("options")) - object.options = $root.google.protobuf.FieldOptions.toObject(message.options, options); - if (message.oneofIndex != null && message.hasOwnProperty("oneofIndex")) - object.oneofIndex = message.oneofIndex; - if (message.jsonName != null && message.hasOwnProperty("jsonName")) - object.jsonName = message.jsonName; - if (message.proto3Optional != null && message.hasOwnProperty("proto3Optional")) - object.proto3Optional = message.proto3Optional; - return object; - }; + /** + * Converts this ReadOnly to JSON. + * @function toJSON + * @memberof google.firestore.v1.TransactionOptions.ReadOnly + * @instance + * @returns {Object.} JSON object + */ + ReadOnly.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; - /** - * Converts this FieldDescriptorProto to JSON. - * @function toJSON - * @memberof google.protobuf.FieldDescriptorProto - * @instance - * @returns {Object.} JSON object - */ - FieldDescriptorProto.prototype.toJSON = function toJSON() { - return this.constructor.toObject(this, $protobuf.util.toJSONOptions); - }; + /** + * Gets the default type url for ReadOnly + * @function getTypeUrl + * @memberof google.firestore.v1.TransactionOptions.ReadOnly + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + ReadOnly.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.firestore.v1.TransactionOptions.ReadOnly"; + }; - /** - * Gets the default type url for FieldDescriptorProto - * @function getTypeUrl - * @memberof google.protobuf.FieldDescriptorProto - * @static - * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") - * @returns {string} The default type url - */ - FieldDescriptorProto.getTypeUrl = function getTypeUrl(typeUrlPrefix) { - if (typeUrlPrefix === undefined) { - typeUrlPrefix = "type.googleapis.com"; - } - return typeUrlPrefix + "/google.protobuf.FieldDescriptorProto"; - }; + return ReadOnly; + })(); - /** - * Type enum. - * @name google.protobuf.FieldDescriptorProto.Type - * @enum {string} - * @property {string} TYPE_DOUBLE=TYPE_DOUBLE TYPE_DOUBLE value - * @property {string} TYPE_FLOAT=TYPE_FLOAT TYPE_FLOAT value - * @property {string} TYPE_INT64=TYPE_INT64 TYPE_INT64 value - * @property {string} TYPE_UINT64=TYPE_UINT64 TYPE_UINT64 value - * @property {string} TYPE_INT32=TYPE_INT32 TYPE_INT32 value - * @property {string} TYPE_FIXED64=TYPE_FIXED64 TYPE_FIXED64 value - * @property {string} TYPE_FIXED32=TYPE_FIXED32 TYPE_FIXED32 value - * @property {string} TYPE_BOOL=TYPE_BOOL TYPE_BOOL value - * @property {string} TYPE_STRING=TYPE_STRING TYPE_STRING value - * @property {string} TYPE_GROUP=TYPE_GROUP TYPE_GROUP value - * @property {string} TYPE_MESSAGE=TYPE_MESSAGE TYPE_MESSAGE value - * @property {string} TYPE_BYTES=TYPE_BYTES TYPE_BYTES value - * @property {string} TYPE_UINT32=TYPE_UINT32 TYPE_UINT32 value - * @property {string} TYPE_ENUM=TYPE_ENUM TYPE_ENUM value - * @property {string} TYPE_SFIXED32=TYPE_SFIXED32 TYPE_SFIXED32 value - * @property {string} TYPE_SFIXED64=TYPE_SFIXED64 TYPE_SFIXED64 value - * @property {string} TYPE_SINT32=TYPE_SINT32 TYPE_SINT32 value - * @property {string} TYPE_SINT64=TYPE_SINT64 TYPE_SINT64 value - */ - FieldDescriptorProto.Type = (function() { - var valuesById = {}, values = Object.create(valuesById); - values[valuesById[1] = "TYPE_DOUBLE"] = "TYPE_DOUBLE"; - values[valuesById[2] = "TYPE_FLOAT"] = "TYPE_FLOAT"; - values[valuesById[3] = "TYPE_INT64"] = "TYPE_INT64"; - values[valuesById[4] = "TYPE_UINT64"] = "TYPE_UINT64"; - values[valuesById[5] = "TYPE_INT32"] = "TYPE_INT32"; - values[valuesById[6] = "TYPE_FIXED64"] = "TYPE_FIXED64"; - values[valuesById[7] = "TYPE_FIXED32"] = "TYPE_FIXED32"; - values[valuesById[8] = "TYPE_BOOL"] = "TYPE_BOOL"; - values[valuesById[9] = "TYPE_STRING"] = "TYPE_STRING"; - values[valuesById[10] = "TYPE_GROUP"] = "TYPE_GROUP"; - values[valuesById[11] = "TYPE_MESSAGE"] = "TYPE_MESSAGE"; - values[valuesById[12] = "TYPE_BYTES"] = "TYPE_BYTES"; - values[valuesById[13] = "TYPE_UINT32"] = "TYPE_UINT32"; - values[valuesById[14] = "TYPE_ENUM"] = "TYPE_ENUM"; - values[valuesById[15] = "TYPE_SFIXED32"] = "TYPE_SFIXED32"; - values[valuesById[16] = "TYPE_SFIXED64"] = "TYPE_SFIXED64"; - values[valuesById[17] = "TYPE_SINT32"] = "TYPE_SINT32"; - values[valuesById[18] = "TYPE_SINT64"] = "TYPE_SINT64"; - return values; - })(); - - /** - * Label enum. - * @name google.protobuf.FieldDescriptorProto.Label - * @enum {string} - * @property {string} LABEL_OPTIONAL=LABEL_OPTIONAL LABEL_OPTIONAL value - * @property {string} LABEL_REPEATED=LABEL_REPEATED LABEL_REPEATED value - * @property {string} LABEL_REQUIRED=LABEL_REQUIRED LABEL_REQUIRED value - */ - FieldDescriptorProto.Label = (function() { - var valuesById = {}, values = Object.create(valuesById); - values[valuesById[1] = "LABEL_OPTIONAL"] = "LABEL_OPTIONAL"; - values[valuesById[3] = "LABEL_REPEATED"] = "LABEL_REPEATED"; - values[valuesById[2] = "LABEL_REQUIRED"] = "LABEL_REQUIRED"; - return values; + return TransactionOptions; })(); - return FieldDescriptorProto; - })(); - - protobuf.OneofDescriptorProto = (function() { + v1.Firestore = (function() { - /** - * Properties of an OneofDescriptorProto. - * @memberof google.protobuf - * @interface IOneofDescriptorProto - * @property {string|null} [name] OneofDescriptorProto name - * @property {google.protobuf.IOneofOptions|null} [options] OneofDescriptorProto options - */ + /** + * Constructs a new Firestore service. + * @memberof google.firestore.v1 + * @classdesc Represents a Firestore + * @extends $protobuf.rpc.Service + * @constructor + * @param {$protobuf.RPCImpl} rpcImpl RPC implementation + * @param {boolean} [requestDelimited=false] Whether requests are length-delimited + * @param {boolean} [responseDelimited=false] Whether responses are length-delimited + */ + function Firestore(rpcImpl, requestDelimited, responseDelimited) { + $protobuf.rpc.Service.call(this, rpcImpl, requestDelimited, responseDelimited); + } - /** - * Constructs a new OneofDescriptorProto. - * @memberof google.protobuf - * @classdesc Represents an OneofDescriptorProto. - * @implements IOneofDescriptorProto - * @constructor - * @param {google.protobuf.IOneofDescriptorProto=} [properties] Properties to set - */ - function OneofDescriptorProto(properties) { - if (properties) - for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) - if (properties[keys[i]] != null) - this[keys[i]] = properties[keys[i]]; - } + (Firestore.prototype = Object.create($protobuf.rpc.Service.prototype)).constructor = Firestore; - /** - * OneofDescriptorProto name. - * @member {string} name - * @memberof google.protobuf.OneofDescriptorProto - * @instance - */ - OneofDescriptorProto.prototype.name = ""; + /** + * Callback as used by {@link google.firestore.v1.Firestore#getDocument}. + * @memberof google.firestore.v1.Firestore + * @typedef GetDocumentCallback + * @type {function} + * @param {Error|null} error Error, if any + * @param {google.firestore.v1.Document} [response] Document + */ - /** - * OneofDescriptorProto options. - * @member {google.protobuf.IOneofOptions|null|undefined} options - * @memberof google.protobuf.OneofDescriptorProto - * @instance - */ - OneofDescriptorProto.prototype.options = null; + /** + * Calls GetDocument. + * @function getDocument + * @memberof google.firestore.v1.Firestore + * @instance + * @param {google.firestore.v1.IGetDocumentRequest} request GetDocumentRequest message or plain object + * @param {google.firestore.v1.Firestore.GetDocumentCallback} callback Node-style callback called with the error, if any, and Document + * @returns {undefined} + * @variation 1 + */ + Object.defineProperty(Firestore.prototype.getDocument = function getDocument(request, callback) { + return this.rpcCall(getDocument, $root.google.firestore.v1.GetDocumentRequest, $root.google.firestore.v1.Document, request, callback); + }, "name", { value: "GetDocument" }); - /** - * Creates an OneofDescriptorProto message from a plain object. Also converts values to their respective internal types. - * @function fromObject - * @memberof google.protobuf.OneofDescriptorProto - * @static - * @param {Object.} object Plain object - * @returns {google.protobuf.OneofDescriptorProto} OneofDescriptorProto - */ - OneofDescriptorProto.fromObject = function fromObject(object) { - if (object instanceof $root.google.protobuf.OneofDescriptorProto) - return object; - var message = new $root.google.protobuf.OneofDescriptorProto(); - if (object.name != null) - message.name = String(object.name); - if (object.options != null) { - if (typeof object.options !== "object") - throw TypeError(".google.protobuf.OneofDescriptorProto.options: object expected"); - message.options = $root.google.protobuf.OneofOptions.fromObject(object.options); - } - return message; - }; + /** + * Calls GetDocument. + * @function getDocument + * @memberof google.firestore.v1.Firestore + * @instance + * @param {google.firestore.v1.IGetDocumentRequest} request GetDocumentRequest message or plain object + * @returns {Promise} Promise + * @variation 2 + */ - /** - * Creates a plain object from an OneofDescriptorProto message. Also converts values to other types if specified. - * @function toObject - * @memberof google.protobuf.OneofDescriptorProto - * @static - * @param {google.protobuf.OneofDescriptorProto} message OneofDescriptorProto - * @param {$protobuf.IConversionOptions} [options] Conversion options - * @returns {Object.} Plain object - */ - OneofDescriptorProto.toObject = function toObject(message, options) { - if (!options) - options = {}; - var object = {}; - if (options.defaults) { - object.name = ""; - object.options = null; - } - if (message.name != null && message.hasOwnProperty("name")) - object.name = message.name; - if (message.options != null && message.hasOwnProperty("options")) - object.options = $root.google.protobuf.OneofOptions.toObject(message.options, options); - return object; - }; + /** + * Callback as used by {@link google.firestore.v1.Firestore#listDocuments}. + * @memberof google.firestore.v1.Firestore + * @typedef ListDocumentsCallback + * @type {function} + * @param {Error|null} error Error, if any + * @param {google.firestore.v1.ListDocumentsResponse} [response] ListDocumentsResponse + */ - /** - * Converts this OneofDescriptorProto to JSON. - * @function toJSON - * @memberof google.protobuf.OneofDescriptorProto - * @instance - * @returns {Object.} JSON object - */ - OneofDescriptorProto.prototype.toJSON = function toJSON() { - return this.constructor.toObject(this, $protobuf.util.toJSONOptions); - }; + /** + * Calls ListDocuments. + * @function listDocuments + * @memberof google.firestore.v1.Firestore + * @instance + * @param {google.firestore.v1.IListDocumentsRequest} request ListDocumentsRequest message or plain object + * @param {google.firestore.v1.Firestore.ListDocumentsCallback} callback Node-style callback called with the error, if any, and ListDocumentsResponse + * @returns {undefined} + * @variation 1 + */ + Object.defineProperty(Firestore.prototype.listDocuments = function listDocuments(request, callback) { + return this.rpcCall(listDocuments, $root.google.firestore.v1.ListDocumentsRequest, $root.google.firestore.v1.ListDocumentsResponse, request, callback); + }, "name", { value: "ListDocuments" }); - /** - * Gets the default type url for OneofDescriptorProto - * @function getTypeUrl - * @memberof google.protobuf.OneofDescriptorProto - * @static - * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") - * @returns {string} The default type url - */ - OneofDescriptorProto.getTypeUrl = function getTypeUrl(typeUrlPrefix) { - if (typeUrlPrefix === undefined) { - typeUrlPrefix = "type.googleapis.com"; - } - return typeUrlPrefix + "/google.protobuf.OneofDescriptorProto"; - }; + /** + * Calls ListDocuments. + * @function listDocuments + * @memberof google.firestore.v1.Firestore + * @instance + * @param {google.firestore.v1.IListDocumentsRequest} request ListDocumentsRequest message or plain object + * @returns {Promise} Promise + * @variation 2 + */ - return OneofDescriptorProto; - })(); + /** + * Callback as used by {@link google.firestore.v1.Firestore#updateDocument}. + * @memberof google.firestore.v1.Firestore + * @typedef UpdateDocumentCallback + * @type {function} + * @param {Error|null} error Error, if any + * @param {google.firestore.v1.Document} [response] Document + */ - protobuf.EnumDescriptorProto = (function() { - - /** - * Properties of an EnumDescriptorProto. - * @memberof google.protobuf - * @interface IEnumDescriptorProto - * @property {string|null} [name] EnumDescriptorProto name - * @property {Array.|null} [value] EnumDescriptorProto value - * @property {google.protobuf.IEnumOptions|null} [options] EnumDescriptorProto options - * @property {Array.|null} [reservedRange] EnumDescriptorProto reservedRange - * @property {Array.|null} [reservedName] EnumDescriptorProto reservedName - */ - - /** - * Constructs a new EnumDescriptorProto. - * @memberof google.protobuf - * @classdesc Represents an EnumDescriptorProto. - * @implements IEnumDescriptorProto - * @constructor - * @param {google.protobuf.IEnumDescriptorProto=} [properties] Properties to set - */ - function EnumDescriptorProto(properties) { - this.value = []; - this.reservedRange = []; - this.reservedName = []; - if (properties) - for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) - if (properties[keys[i]] != null) - this[keys[i]] = properties[keys[i]]; - } - - /** - * EnumDescriptorProto name. - * @member {string} name - * @memberof google.protobuf.EnumDescriptorProto - * @instance - */ - EnumDescriptorProto.prototype.name = ""; - - /** - * EnumDescriptorProto value. - * @member {Array.} value - * @memberof google.protobuf.EnumDescriptorProto - * @instance - */ - EnumDescriptorProto.prototype.value = $util.emptyArray; - - /** - * EnumDescriptorProto options. - * @member {google.protobuf.IEnumOptions|null|undefined} options - * @memberof google.protobuf.EnumDescriptorProto - * @instance - */ - EnumDescriptorProto.prototype.options = null; - - /** - * EnumDescriptorProto reservedRange. - * @member {Array.} reservedRange - * @memberof google.protobuf.EnumDescriptorProto - * @instance - */ - EnumDescriptorProto.prototype.reservedRange = $util.emptyArray; - - /** - * EnumDescriptorProto reservedName. - * @member {Array.} reservedName - * @memberof google.protobuf.EnumDescriptorProto - * @instance - */ - EnumDescriptorProto.prototype.reservedName = $util.emptyArray; - - /** - * Creates an EnumDescriptorProto message from a plain object. Also converts values to their respective internal types. - * @function fromObject - * @memberof google.protobuf.EnumDescriptorProto - * @static - * @param {Object.} object Plain object - * @returns {google.protobuf.EnumDescriptorProto} EnumDescriptorProto - */ - EnumDescriptorProto.fromObject = function fromObject(object) { - if (object instanceof $root.google.protobuf.EnumDescriptorProto) - return object; - var message = new $root.google.protobuf.EnumDescriptorProto(); - if (object.name != null) - message.name = String(object.name); - if (object.value) { - if (!Array.isArray(object.value)) - throw TypeError(".google.protobuf.EnumDescriptorProto.value: array expected"); - message.value = []; - for (var i = 0; i < object.value.length; ++i) { - if (typeof object.value[i] !== "object") - throw TypeError(".google.protobuf.EnumDescriptorProto.value: object expected"); - message.value[i] = $root.google.protobuf.EnumValueDescriptorProto.fromObject(object.value[i]); - } - } - if (object.options != null) { - if (typeof object.options !== "object") - throw TypeError(".google.protobuf.EnumDescriptorProto.options: object expected"); - message.options = $root.google.protobuf.EnumOptions.fromObject(object.options); - } - if (object.reservedRange) { - if (!Array.isArray(object.reservedRange)) - throw TypeError(".google.protobuf.EnumDescriptorProto.reservedRange: array expected"); - message.reservedRange = []; - for (var i = 0; i < object.reservedRange.length; ++i) { - if (typeof object.reservedRange[i] !== "object") - throw TypeError(".google.protobuf.EnumDescriptorProto.reservedRange: object expected"); - message.reservedRange[i] = $root.google.protobuf.EnumDescriptorProto.EnumReservedRange.fromObject(object.reservedRange[i]); - } - } - if (object.reservedName) { - if (!Array.isArray(object.reservedName)) - throw TypeError(".google.protobuf.EnumDescriptorProto.reservedName: array expected"); - message.reservedName = []; - for (var i = 0; i < object.reservedName.length; ++i) - message.reservedName[i] = String(object.reservedName[i]); - } - return message; - }; - - /** - * Creates a plain object from an EnumDescriptorProto message. Also converts values to other types if specified. - * @function toObject - * @memberof google.protobuf.EnumDescriptorProto - * @static - * @param {google.protobuf.EnumDescriptorProto} message EnumDescriptorProto - * @param {$protobuf.IConversionOptions} [options] Conversion options - * @returns {Object.} Plain object - */ - EnumDescriptorProto.toObject = function toObject(message, options) { - if (!options) - options = {}; - var object = {}; - if (options.arrays || options.defaults) { - object.value = []; - object.reservedRange = []; - object.reservedName = []; - } - if (options.defaults) { - object.name = ""; - object.options = null; - } - if (message.name != null && message.hasOwnProperty("name")) - object.name = message.name; - if (message.value && message.value.length) { - object.value = []; - for (var j = 0; j < message.value.length; ++j) - object.value[j] = $root.google.protobuf.EnumValueDescriptorProto.toObject(message.value[j], options); - } - if (message.options != null && message.hasOwnProperty("options")) - object.options = $root.google.protobuf.EnumOptions.toObject(message.options, options); - if (message.reservedRange && message.reservedRange.length) { - object.reservedRange = []; - for (var j = 0; j < message.reservedRange.length; ++j) - object.reservedRange[j] = $root.google.protobuf.EnumDescriptorProto.EnumReservedRange.toObject(message.reservedRange[j], options); - } - if (message.reservedName && message.reservedName.length) { - object.reservedName = []; - for (var j = 0; j < message.reservedName.length; ++j) - object.reservedName[j] = message.reservedName[j]; - } - return object; - }; - - /** - * Converts this EnumDescriptorProto to JSON. - * @function toJSON - * @memberof google.protobuf.EnumDescriptorProto - * @instance - * @returns {Object.} JSON object - */ - EnumDescriptorProto.prototype.toJSON = function toJSON() { - return this.constructor.toObject(this, $protobuf.util.toJSONOptions); - }; - - /** - * Gets the default type url for EnumDescriptorProto - * @function getTypeUrl - * @memberof google.protobuf.EnumDescriptorProto - * @static - * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") - * @returns {string} The default type url - */ - EnumDescriptorProto.getTypeUrl = function getTypeUrl(typeUrlPrefix) { - if (typeUrlPrefix === undefined) { - typeUrlPrefix = "type.googleapis.com"; - } - return typeUrlPrefix + "/google.protobuf.EnumDescriptorProto"; - }; - - EnumDescriptorProto.EnumReservedRange = (function() { + /** + * Calls UpdateDocument. + * @function updateDocument + * @memberof google.firestore.v1.Firestore + * @instance + * @param {google.firestore.v1.IUpdateDocumentRequest} request UpdateDocumentRequest message or plain object + * @param {google.firestore.v1.Firestore.UpdateDocumentCallback} callback Node-style callback called with the error, if any, and Document + * @returns {undefined} + * @variation 1 + */ + Object.defineProperty(Firestore.prototype.updateDocument = function updateDocument(request, callback) { + return this.rpcCall(updateDocument, $root.google.firestore.v1.UpdateDocumentRequest, $root.google.firestore.v1.Document, request, callback); + }, "name", { value: "UpdateDocument" }); /** - * Properties of an EnumReservedRange. - * @memberof google.protobuf.EnumDescriptorProto - * @interface IEnumReservedRange - * @property {number|null} [start] EnumReservedRange start - * @property {number|null} [end] EnumReservedRange end + * Calls UpdateDocument. + * @function updateDocument + * @memberof google.firestore.v1.Firestore + * @instance + * @param {google.firestore.v1.IUpdateDocumentRequest} request UpdateDocumentRequest message or plain object + * @returns {Promise} Promise + * @variation 2 */ /** - * Constructs a new EnumReservedRange. - * @memberof google.protobuf.EnumDescriptorProto - * @classdesc Represents an EnumReservedRange. - * @implements IEnumReservedRange - * @constructor - * @param {google.protobuf.EnumDescriptorProto.IEnumReservedRange=} [properties] Properties to set + * Callback as used by {@link google.firestore.v1.Firestore#deleteDocument}. + * @memberof google.firestore.v1.Firestore + * @typedef DeleteDocumentCallback + * @type {function} + * @param {Error|null} error Error, if any + * @param {google.protobuf.Empty} [response] Empty */ - function EnumReservedRange(properties) { - if (properties) - for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) - if (properties[keys[i]] != null) - this[keys[i]] = properties[keys[i]]; - } /** - * EnumReservedRange start. - * @member {number} start - * @memberof google.protobuf.EnumDescriptorProto.EnumReservedRange + * Calls DeleteDocument. + * @function deleteDocument + * @memberof google.firestore.v1.Firestore * @instance + * @param {google.firestore.v1.IDeleteDocumentRequest} request DeleteDocumentRequest message or plain object + * @param {google.firestore.v1.Firestore.DeleteDocumentCallback} callback Node-style callback called with the error, if any, and Empty + * @returns {undefined} + * @variation 1 */ - EnumReservedRange.prototype.start = 0; + Object.defineProperty(Firestore.prototype.deleteDocument = function deleteDocument(request, callback) { + return this.rpcCall(deleteDocument, $root.google.firestore.v1.DeleteDocumentRequest, $root.google.protobuf.Empty, request, callback); + }, "name", { value: "DeleteDocument" }); /** - * EnumReservedRange end. - * @member {number} end - * @memberof google.protobuf.EnumDescriptorProto.EnumReservedRange + * Calls DeleteDocument. + * @function deleteDocument + * @memberof google.firestore.v1.Firestore * @instance + * @param {google.firestore.v1.IDeleteDocumentRequest} request DeleteDocumentRequest message or plain object + * @returns {Promise} Promise + * @variation 2 */ - EnumReservedRange.prototype.end = 0; /** - * Creates an EnumReservedRange message from a plain object. Also converts values to their respective internal types. - * @function fromObject - * @memberof google.protobuf.EnumDescriptorProto.EnumReservedRange - * @static - * @param {Object.} object Plain object - * @returns {google.protobuf.EnumDescriptorProto.EnumReservedRange} EnumReservedRange + * Callback as used by {@link google.firestore.v1.Firestore#batchGetDocuments}. + * @memberof google.firestore.v1.Firestore + * @typedef BatchGetDocumentsCallback + * @type {function} + * @param {Error|null} error Error, if any + * @param {google.firestore.v1.BatchGetDocumentsResponse} [response] BatchGetDocumentsResponse */ - EnumReservedRange.fromObject = function fromObject(object) { - if (object instanceof $root.google.protobuf.EnumDescriptorProto.EnumReservedRange) - return object; - var message = new $root.google.protobuf.EnumDescriptorProto.EnumReservedRange(); - if (object.start != null) - message.start = object.start | 0; - if (object.end != null) - message.end = object.end | 0; - return message; - }; /** - * Creates a plain object from an EnumReservedRange message. Also converts values to other types if specified. - * @function toObject - * @memberof google.protobuf.EnumDescriptorProto.EnumReservedRange - * @static - * @param {google.protobuf.EnumDescriptorProto.EnumReservedRange} message EnumReservedRange - * @param {$protobuf.IConversionOptions} [options] Conversion options - * @returns {Object.} Plain object + * Calls BatchGetDocuments. + * @function batchGetDocuments + * @memberof google.firestore.v1.Firestore + * @instance + * @param {google.firestore.v1.IBatchGetDocumentsRequest} request BatchGetDocumentsRequest message or plain object + * @param {google.firestore.v1.Firestore.BatchGetDocumentsCallback} callback Node-style callback called with the error, if any, and BatchGetDocumentsResponse + * @returns {undefined} + * @variation 1 */ - EnumReservedRange.toObject = function toObject(message, options) { - if (!options) - options = {}; - var object = {}; - if (options.defaults) { - object.start = 0; - object.end = 0; - } - if (message.start != null && message.hasOwnProperty("start")) - object.start = message.start; - if (message.end != null && message.hasOwnProperty("end")) - object.end = message.end; - return object; - }; + Object.defineProperty(Firestore.prototype.batchGetDocuments = function batchGetDocuments(request, callback) { + return this.rpcCall(batchGetDocuments, $root.google.firestore.v1.BatchGetDocumentsRequest, $root.google.firestore.v1.BatchGetDocumentsResponse, request, callback); + }, "name", { value: "BatchGetDocuments" }); /** - * Converts this EnumReservedRange to JSON. - * @function toJSON - * @memberof google.protobuf.EnumDescriptorProto.EnumReservedRange + * Calls BatchGetDocuments. + * @function batchGetDocuments + * @memberof google.firestore.v1.Firestore * @instance - * @returns {Object.} JSON object + * @param {google.firestore.v1.IBatchGetDocumentsRequest} request BatchGetDocumentsRequest message or plain object + * @returns {Promise} Promise + * @variation 2 */ - EnumReservedRange.prototype.toJSON = function toJSON() { - return this.constructor.toObject(this, $protobuf.util.toJSONOptions); - }; /** - * Gets the default type url for EnumReservedRange - * @function getTypeUrl - * @memberof google.protobuf.EnumDescriptorProto.EnumReservedRange - * @static - * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") - * @returns {string} The default type url + * Callback as used by {@link google.firestore.v1.Firestore#beginTransaction}. + * @memberof google.firestore.v1.Firestore + * @typedef BeginTransactionCallback + * @type {function} + * @param {Error|null} error Error, if any + * @param {google.firestore.v1.BeginTransactionResponse} [response] BeginTransactionResponse */ - EnumReservedRange.getTypeUrl = function getTypeUrl(typeUrlPrefix) { - if (typeUrlPrefix === undefined) { - typeUrlPrefix = "type.googleapis.com"; - } - return typeUrlPrefix + "/google.protobuf.EnumDescriptorProto.EnumReservedRange"; - }; - return EnumReservedRange; - })(); + /** + * Calls BeginTransaction. + * @function beginTransaction + * @memberof google.firestore.v1.Firestore + * @instance + * @param {google.firestore.v1.IBeginTransactionRequest} request BeginTransactionRequest message or plain object + * @param {google.firestore.v1.Firestore.BeginTransactionCallback} callback Node-style callback called with the error, if any, and BeginTransactionResponse + * @returns {undefined} + * @variation 1 + */ + Object.defineProperty(Firestore.prototype.beginTransaction = function beginTransaction(request, callback) { + return this.rpcCall(beginTransaction, $root.google.firestore.v1.BeginTransactionRequest, $root.google.firestore.v1.BeginTransactionResponse, request, callback); + }, "name", { value: "BeginTransaction" }); - return EnumDescriptorProto; - })(); + /** + * Calls BeginTransaction. + * @function beginTransaction + * @memberof google.firestore.v1.Firestore + * @instance + * @param {google.firestore.v1.IBeginTransactionRequest} request BeginTransactionRequest message or plain object + * @returns {Promise} Promise + * @variation 2 + */ - protobuf.EnumValueDescriptorProto = (function() { + /** + * Callback as used by {@link google.firestore.v1.Firestore#commit}. + * @memberof google.firestore.v1.Firestore + * @typedef CommitCallback + * @type {function} + * @param {Error|null} error Error, if any + * @param {google.firestore.v1.CommitResponse} [response] CommitResponse + */ - /** - * Properties of an EnumValueDescriptorProto. - * @memberof google.protobuf - * @interface IEnumValueDescriptorProto - * @property {string|null} [name] EnumValueDescriptorProto name - * @property {number|null} [number] EnumValueDescriptorProto number - * @property {google.protobuf.IEnumValueOptions|null} [options] EnumValueDescriptorProto options - */ + /** + * Calls Commit. + * @function commit + * @memberof google.firestore.v1.Firestore + * @instance + * @param {google.firestore.v1.ICommitRequest} request CommitRequest message or plain object + * @param {google.firestore.v1.Firestore.CommitCallback} callback Node-style callback called with the error, if any, and CommitResponse + * @returns {undefined} + * @variation 1 + */ + Object.defineProperty(Firestore.prototype.commit = function commit(request, callback) { + return this.rpcCall(commit, $root.google.firestore.v1.CommitRequest, $root.google.firestore.v1.CommitResponse, request, callback); + }, "name", { value: "Commit" }); - /** - * Constructs a new EnumValueDescriptorProto. - * @memberof google.protobuf - * @classdesc Represents an EnumValueDescriptorProto. - * @implements IEnumValueDescriptorProto - * @constructor - * @param {google.protobuf.IEnumValueDescriptorProto=} [properties] Properties to set - */ - function EnumValueDescriptorProto(properties) { - if (properties) - for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) - if (properties[keys[i]] != null) - this[keys[i]] = properties[keys[i]]; - } + /** + * Calls Commit. + * @function commit + * @memberof google.firestore.v1.Firestore + * @instance + * @param {google.firestore.v1.ICommitRequest} request CommitRequest message or plain object + * @returns {Promise} Promise + * @variation 2 + */ - /** - * EnumValueDescriptorProto name. - * @member {string} name - * @memberof google.protobuf.EnumValueDescriptorProto - * @instance - */ - EnumValueDescriptorProto.prototype.name = ""; + /** + * Callback as used by {@link google.firestore.v1.Firestore#rollback}. + * @memberof google.firestore.v1.Firestore + * @typedef RollbackCallback + * @type {function} + * @param {Error|null} error Error, if any + * @param {google.protobuf.Empty} [response] Empty + */ - /** - * EnumValueDescriptorProto number. - * @member {number} number - * @memberof google.protobuf.EnumValueDescriptorProto - * @instance - */ - EnumValueDescriptorProto.prototype.number = 0; + /** + * Calls Rollback. + * @function rollback + * @memberof google.firestore.v1.Firestore + * @instance + * @param {google.firestore.v1.IRollbackRequest} request RollbackRequest message or plain object + * @param {google.firestore.v1.Firestore.RollbackCallback} callback Node-style callback called with the error, if any, and Empty + * @returns {undefined} + * @variation 1 + */ + Object.defineProperty(Firestore.prototype.rollback = function rollback(request, callback) { + return this.rpcCall(rollback, $root.google.firestore.v1.RollbackRequest, $root.google.protobuf.Empty, request, callback); + }, "name", { value: "Rollback" }); - /** - * EnumValueDescriptorProto options. - * @member {google.protobuf.IEnumValueOptions|null|undefined} options - * @memberof google.protobuf.EnumValueDescriptorProto - * @instance - */ - EnumValueDescriptorProto.prototype.options = null; + /** + * Calls Rollback. + * @function rollback + * @memberof google.firestore.v1.Firestore + * @instance + * @param {google.firestore.v1.IRollbackRequest} request RollbackRequest message or plain object + * @returns {Promise} Promise + * @variation 2 + */ - /** - * Creates an EnumValueDescriptorProto message from a plain object. Also converts values to their respective internal types. - * @function fromObject - * @memberof google.protobuf.EnumValueDescriptorProto - * @static - * @param {Object.} object Plain object - * @returns {google.protobuf.EnumValueDescriptorProto} EnumValueDescriptorProto - */ - EnumValueDescriptorProto.fromObject = function fromObject(object) { - if (object instanceof $root.google.protobuf.EnumValueDescriptorProto) - return object; - var message = new $root.google.protobuf.EnumValueDescriptorProto(); - if (object.name != null) - message.name = String(object.name); - if (object.number != null) - message.number = object.number | 0; - if (object.options != null) { - if (typeof object.options !== "object") - throw TypeError(".google.protobuf.EnumValueDescriptorProto.options: object expected"); - message.options = $root.google.protobuf.EnumValueOptions.fromObject(object.options); - } - return message; - }; + /** + * Callback as used by {@link google.firestore.v1.Firestore#runQuery}. + * @memberof google.firestore.v1.Firestore + * @typedef RunQueryCallback + * @type {function} + * @param {Error|null} error Error, if any + * @param {google.firestore.v1.RunQueryResponse} [response] RunQueryResponse + */ - /** - * Creates a plain object from an EnumValueDescriptorProto message. Also converts values to other types if specified. - * @function toObject - * @memberof google.protobuf.EnumValueDescriptorProto - * @static - * @param {google.protobuf.EnumValueDescriptorProto} message EnumValueDescriptorProto - * @param {$protobuf.IConversionOptions} [options] Conversion options - * @returns {Object.} Plain object - */ - EnumValueDescriptorProto.toObject = function toObject(message, options) { - if (!options) - options = {}; - var object = {}; - if (options.defaults) { - object.name = ""; - object.number = 0; - object.options = null; - } - if (message.name != null && message.hasOwnProperty("name")) - object.name = message.name; - if (message.number != null && message.hasOwnProperty("number")) - object.number = message.number; - if (message.options != null && message.hasOwnProperty("options")) - object.options = $root.google.protobuf.EnumValueOptions.toObject(message.options, options); - return object; - }; + /** + * Calls RunQuery. + * @function runQuery + * @memberof google.firestore.v1.Firestore + * @instance + * @param {google.firestore.v1.IRunQueryRequest} request RunQueryRequest message or plain object + * @param {google.firestore.v1.Firestore.RunQueryCallback} callback Node-style callback called with the error, if any, and RunQueryResponse + * @returns {undefined} + * @variation 1 + */ + Object.defineProperty(Firestore.prototype.runQuery = function runQuery(request, callback) { + return this.rpcCall(runQuery, $root.google.firestore.v1.RunQueryRequest, $root.google.firestore.v1.RunQueryResponse, request, callback); + }, "name", { value: "RunQuery" }); - /** - * Converts this EnumValueDescriptorProto to JSON. - * @function toJSON - * @memberof google.protobuf.EnumValueDescriptorProto - * @instance - * @returns {Object.} JSON object - */ - EnumValueDescriptorProto.prototype.toJSON = function toJSON() { - return this.constructor.toObject(this, $protobuf.util.toJSONOptions); - }; + /** + * Calls RunQuery. + * @function runQuery + * @memberof google.firestore.v1.Firestore + * @instance + * @param {google.firestore.v1.IRunQueryRequest} request RunQueryRequest message or plain object + * @returns {Promise} Promise + * @variation 2 + */ - /** - * Gets the default type url for EnumValueDescriptorProto - * @function getTypeUrl - * @memberof google.protobuf.EnumValueDescriptorProto - * @static - * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") - * @returns {string} The default type url - */ - EnumValueDescriptorProto.getTypeUrl = function getTypeUrl(typeUrlPrefix) { - if (typeUrlPrefix === undefined) { - typeUrlPrefix = "type.googleapis.com"; - } - return typeUrlPrefix + "/google.protobuf.EnumValueDescriptorProto"; - }; + /** + * Callback as used by {@link google.firestore.v1.Firestore#executePipeline}. + * @memberof google.firestore.v1.Firestore + * @typedef ExecutePipelineCallback + * @type {function} + * @param {Error|null} error Error, if any + * @param {google.firestore.v1.ExecutePipelineResponse} [response] ExecutePipelineResponse + */ - return EnumValueDescriptorProto; - })(); + /** + * Calls ExecutePipeline. + * @function executePipeline + * @memberof google.firestore.v1.Firestore + * @instance + * @param {google.firestore.v1.IExecutePipelineRequest} request ExecutePipelineRequest message or plain object + * @param {google.firestore.v1.Firestore.ExecutePipelineCallback} callback Node-style callback called with the error, if any, and ExecutePipelineResponse + * @returns {undefined} + * @variation 1 + */ + Object.defineProperty(Firestore.prototype.executePipeline = function executePipeline(request, callback) { + return this.rpcCall(executePipeline, $root.google.firestore.v1.ExecutePipelineRequest, $root.google.firestore.v1.ExecutePipelineResponse, request, callback); + }, "name", { value: "ExecutePipeline" }); - protobuf.ServiceDescriptorProto = (function() { + /** + * Calls ExecutePipeline. + * @function executePipeline + * @memberof google.firestore.v1.Firestore + * @instance + * @param {google.firestore.v1.IExecutePipelineRequest} request ExecutePipelineRequest message or plain object + * @returns {Promise} Promise + * @variation 2 + */ - /** - * Properties of a ServiceDescriptorProto. - * @memberof google.protobuf - * @interface IServiceDescriptorProto - * @property {string|null} [name] ServiceDescriptorProto name - * @property {Array.|null} [method] ServiceDescriptorProto method - * @property {google.protobuf.IServiceOptions|null} [options] ServiceDescriptorProto options - */ + /** + * Callback as used by {@link google.firestore.v1.Firestore#runAggregationQuery}. + * @memberof google.firestore.v1.Firestore + * @typedef RunAggregationQueryCallback + * @type {function} + * @param {Error|null} error Error, if any + * @param {google.firestore.v1.RunAggregationQueryResponse} [response] RunAggregationQueryResponse + */ - /** - * Constructs a new ServiceDescriptorProto. - * @memberof google.protobuf - * @classdesc Represents a ServiceDescriptorProto. - * @implements IServiceDescriptorProto - * @constructor - * @param {google.protobuf.IServiceDescriptorProto=} [properties] Properties to set - */ - function ServiceDescriptorProto(properties) { - this.method = []; - if (properties) - for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) - if (properties[keys[i]] != null) - this[keys[i]] = properties[keys[i]]; - } + /** + * Calls RunAggregationQuery. + * @function runAggregationQuery + * @memberof google.firestore.v1.Firestore + * @instance + * @param {google.firestore.v1.IRunAggregationQueryRequest} request RunAggregationQueryRequest message or plain object + * @param {google.firestore.v1.Firestore.RunAggregationQueryCallback} callback Node-style callback called with the error, if any, and RunAggregationQueryResponse + * @returns {undefined} + * @variation 1 + */ + Object.defineProperty(Firestore.prototype.runAggregationQuery = function runAggregationQuery(request, callback) { + return this.rpcCall(runAggregationQuery, $root.google.firestore.v1.RunAggregationQueryRequest, $root.google.firestore.v1.RunAggregationQueryResponse, request, callback); + }, "name", { value: "RunAggregationQuery" }); - /** - * ServiceDescriptorProto name. - * @member {string} name - * @memberof google.protobuf.ServiceDescriptorProto - * @instance - */ - ServiceDescriptorProto.prototype.name = ""; + /** + * Calls RunAggregationQuery. + * @function runAggregationQuery + * @memberof google.firestore.v1.Firestore + * @instance + * @param {google.firestore.v1.IRunAggregationQueryRequest} request RunAggregationQueryRequest message or plain object + * @returns {Promise} Promise + * @variation 2 + */ - /** - * ServiceDescriptorProto method. - * @member {Array.} method - * @memberof google.protobuf.ServiceDescriptorProto - * @instance - */ - ServiceDescriptorProto.prototype.method = $util.emptyArray; + /** + * Callback as used by {@link google.firestore.v1.Firestore#partitionQuery}. + * @memberof google.firestore.v1.Firestore + * @typedef PartitionQueryCallback + * @type {function} + * @param {Error|null} error Error, if any + * @param {google.firestore.v1.PartitionQueryResponse} [response] PartitionQueryResponse + */ - /** - * ServiceDescriptorProto options. - * @member {google.protobuf.IServiceOptions|null|undefined} options - * @memberof google.protobuf.ServiceDescriptorProto - * @instance - */ - ServiceDescriptorProto.prototype.options = null; + /** + * Calls PartitionQuery. + * @function partitionQuery + * @memberof google.firestore.v1.Firestore + * @instance + * @param {google.firestore.v1.IPartitionQueryRequest} request PartitionQueryRequest message or plain object + * @param {google.firestore.v1.Firestore.PartitionQueryCallback} callback Node-style callback called with the error, if any, and PartitionQueryResponse + * @returns {undefined} + * @variation 1 + */ + Object.defineProperty(Firestore.prototype.partitionQuery = function partitionQuery(request, callback) { + return this.rpcCall(partitionQuery, $root.google.firestore.v1.PartitionQueryRequest, $root.google.firestore.v1.PartitionQueryResponse, request, callback); + }, "name", { value: "PartitionQuery" }); - /** - * Creates a ServiceDescriptorProto message from a plain object. Also converts values to their respective internal types. - * @function fromObject - * @memberof google.protobuf.ServiceDescriptorProto - * @static - * @param {Object.} object Plain object - * @returns {google.protobuf.ServiceDescriptorProto} ServiceDescriptorProto - */ - ServiceDescriptorProto.fromObject = function fromObject(object) { - if (object instanceof $root.google.protobuf.ServiceDescriptorProto) - return object; - var message = new $root.google.protobuf.ServiceDescriptorProto(); - if (object.name != null) - message.name = String(object.name); - if (object.method) { - if (!Array.isArray(object.method)) - throw TypeError(".google.protobuf.ServiceDescriptorProto.method: array expected"); - message.method = []; - for (var i = 0; i < object.method.length; ++i) { - if (typeof object.method[i] !== "object") - throw TypeError(".google.protobuf.ServiceDescriptorProto.method: object expected"); - message.method[i] = $root.google.protobuf.MethodDescriptorProto.fromObject(object.method[i]); - } - } - if (object.options != null) { - if (typeof object.options !== "object") - throw TypeError(".google.protobuf.ServiceDescriptorProto.options: object expected"); - message.options = $root.google.protobuf.ServiceOptions.fromObject(object.options); - } - return message; - }; + /** + * Calls PartitionQuery. + * @function partitionQuery + * @memberof google.firestore.v1.Firestore + * @instance + * @param {google.firestore.v1.IPartitionQueryRequest} request PartitionQueryRequest message or plain object + * @returns {Promise} Promise + * @variation 2 + */ - /** - * Creates a plain object from a ServiceDescriptorProto message. Also converts values to other types if specified. - * @function toObject - * @memberof google.protobuf.ServiceDescriptorProto - * @static - * @param {google.protobuf.ServiceDescriptorProto} message ServiceDescriptorProto - * @param {$protobuf.IConversionOptions} [options] Conversion options - * @returns {Object.} Plain object - */ - ServiceDescriptorProto.toObject = function toObject(message, options) { - if (!options) - options = {}; - var object = {}; - if (options.arrays || options.defaults) - object.method = []; - if (options.defaults) { - object.name = ""; - object.options = null; - } - if (message.name != null && message.hasOwnProperty("name")) - object.name = message.name; - if (message.method && message.method.length) { - object.method = []; - for (var j = 0; j < message.method.length; ++j) - object.method[j] = $root.google.protobuf.MethodDescriptorProto.toObject(message.method[j], options); - } - if (message.options != null && message.hasOwnProperty("options")) - object.options = $root.google.protobuf.ServiceOptions.toObject(message.options, options); - return object; - }; + /** + * Callback as used by {@link google.firestore.v1.Firestore#write}. + * @memberof google.firestore.v1.Firestore + * @typedef WriteCallback + * @type {function} + * @param {Error|null} error Error, if any + * @param {google.firestore.v1.WriteResponse} [response] WriteResponse + */ - /** - * Converts this ServiceDescriptorProto to JSON. - * @function toJSON - * @memberof google.protobuf.ServiceDescriptorProto - * @instance - * @returns {Object.} JSON object - */ - ServiceDescriptorProto.prototype.toJSON = function toJSON() { - return this.constructor.toObject(this, $protobuf.util.toJSONOptions); - }; + /** + * Calls Write. + * @function write + * @memberof google.firestore.v1.Firestore + * @instance + * @param {google.firestore.v1.IWriteRequest} request WriteRequest message or plain object + * @param {google.firestore.v1.Firestore.WriteCallback} callback Node-style callback called with the error, if any, and WriteResponse + * @returns {undefined} + * @variation 1 + */ + Object.defineProperty(Firestore.prototype.write = function write(request, callback) { + return this.rpcCall(write, $root.google.firestore.v1.WriteRequest, $root.google.firestore.v1.WriteResponse, request, callback); + }, "name", { value: "Write" }); - /** - * Gets the default type url for ServiceDescriptorProto - * @function getTypeUrl - * @memberof google.protobuf.ServiceDescriptorProto - * @static - * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") - * @returns {string} The default type url - */ - ServiceDescriptorProto.getTypeUrl = function getTypeUrl(typeUrlPrefix) { - if (typeUrlPrefix === undefined) { - typeUrlPrefix = "type.googleapis.com"; - } - return typeUrlPrefix + "/google.protobuf.ServiceDescriptorProto"; - }; + /** + * Calls Write. + * @function write + * @memberof google.firestore.v1.Firestore + * @instance + * @param {google.firestore.v1.IWriteRequest} request WriteRequest message or plain object + * @returns {Promise} Promise + * @variation 2 + */ - return ServiceDescriptorProto; - })(); + /** + * Callback as used by {@link google.firestore.v1.Firestore#listen}. + * @memberof google.firestore.v1.Firestore + * @typedef ListenCallback + * @type {function} + * @param {Error|null} error Error, if any + * @param {google.firestore.v1.ListenResponse} [response] ListenResponse + */ - protobuf.MethodDescriptorProto = (function() { + /** + * Calls Listen. + * @function listen + * @memberof google.firestore.v1.Firestore + * @instance + * @param {google.firestore.v1.IListenRequest} request ListenRequest message or plain object + * @param {google.firestore.v1.Firestore.ListenCallback} callback Node-style callback called with the error, if any, and ListenResponse + * @returns {undefined} + * @variation 1 + */ + Object.defineProperty(Firestore.prototype.listen = function listen(request, callback) { + return this.rpcCall(listen, $root.google.firestore.v1.ListenRequest, $root.google.firestore.v1.ListenResponse, request, callback); + }, "name", { value: "Listen" }); - /** - * Properties of a MethodDescriptorProto. - * @memberof google.protobuf - * @interface IMethodDescriptorProto - * @property {string|null} [name] MethodDescriptorProto name - * @property {string|null} [inputType] MethodDescriptorProto inputType - * @property {string|null} [outputType] MethodDescriptorProto outputType - * @property {google.protobuf.IMethodOptions|null} [options] MethodDescriptorProto options - * @property {boolean|null} [clientStreaming] MethodDescriptorProto clientStreaming - * @property {boolean|null} [serverStreaming] MethodDescriptorProto serverStreaming - */ + /** + * Calls Listen. + * @function listen + * @memberof google.firestore.v1.Firestore + * @instance + * @param {google.firestore.v1.IListenRequest} request ListenRequest message or plain object + * @returns {Promise} Promise + * @variation 2 + */ - /** - * Constructs a new MethodDescriptorProto. - * @memberof google.protobuf - * @classdesc Represents a MethodDescriptorProto. - * @implements IMethodDescriptorProto - * @constructor - * @param {google.protobuf.IMethodDescriptorProto=} [properties] Properties to set - */ - function MethodDescriptorProto(properties) { - if (properties) - for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) - if (properties[keys[i]] != null) - this[keys[i]] = properties[keys[i]]; - } + /** + * Callback as used by {@link google.firestore.v1.Firestore#listCollectionIds}. + * @memberof google.firestore.v1.Firestore + * @typedef ListCollectionIdsCallback + * @type {function} + * @param {Error|null} error Error, if any + * @param {google.firestore.v1.ListCollectionIdsResponse} [response] ListCollectionIdsResponse + */ - /** - * MethodDescriptorProto name. - * @member {string} name - * @memberof google.protobuf.MethodDescriptorProto - * @instance - */ - MethodDescriptorProto.prototype.name = ""; + /** + * Calls ListCollectionIds. + * @function listCollectionIds + * @memberof google.firestore.v1.Firestore + * @instance + * @param {google.firestore.v1.IListCollectionIdsRequest} request ListCollectionIdsRequest message or plain object + * @param {google.firestore.v1.Firestore.ListCollectionIdsCallback} callback Node-style callback called with the error, if any, and ListCollectionIdsResponse + * @returns {undefined} + * @variation 1 + */ + Object.defineProperty(Firestore.prototype.listCollectionIds = function listCollectionIds(request, callback) { + return this.rpcCall(listCollectionIds, $root.google.firestore.v1.ListCollectionIdsRequest, $root.google.firestore.v1.ListCollectionIdsResponse, request, callback); + }, "name", { value: "ListCollectionIds" }); - /** - * MethodDescriptorProto inputType. - * @member {string} inputType - * @memberof google.protobuf.MethodDescriptorProto - * @instance - */ - MethodDescriptorProto.prototype.inputType = ""; + /** + * Calls ListCollectionIds. + * @function listCollectionIds + * @memberof google.firestore.v1.Firestore + * @instance + * @param {google.firestore.v1.IListCollectionIdsRequest} request ListCollectionIdsRequest message or plain object + * @returns {Promise} Promise + * @variation 2 + */ - /** - * MethodDescriptorProto outputType. - * @member {string} outputType - * @memberof google.protobuf.MethodDescriptorProto - * @instance - */ - MethodDescriptorProto.prototype.outputType = ""; + /** + * Callback as used by {@link google.firestore.v1.Firestore#batchWrite}. + * @memberof google.firestore.v1.Firestore + * @typedef BatchWriteCallback + * @type {function} + * @param {Error|null} error Error, if any + * @param {google.firestore.v1.BatchWriteResponse} [response] BatchWriteResponse + */ - /** - * MethodDescriptorProto options. - * @member {google.protobuf.IMethodOptions|null|undefined} options - * @memberof google.protobuf.MethodDescriptorProto - * @instance - */ - MethodDescriptorProto.prototype.options = null; + /** + * Calls BatchWrite. + * @function batchWrite + * @memberof google.firestore.v1.Firestore + * @instance + * @param {google.firestore.v1.IBatchWriteRequest} request BatchWriteRequest message or plain object + * @param {google.firestore.v1.Firestore.BatchWriteCallback} callback Node-style callback called with the error, if any, and BatchWriteResponse + * @returns {undefined} + * @variation 1 + */ + Object.defineProperty(Firestore.prototype.batchWrite = function batchWrite(request, callback) { + return this.rpcCall(batchWrite, $root.google.firestore.v1.BatchWriteRequest, $root.google.firestore.v1.BatchWriteResponse, request, callback); + }, "name", { value: "BatchWrite" }); - /** - * MethodDescriptorProto clientStreaming. - * @member {boolean} clientStreaming - * @memberof google.protobuf.MethodDescriptorProto - * @instance - */ - MethodDescriptorProto.prototype.clientStreaming = false; + /** + * Calls BatchWrite. + * @function batchWrite + * @memberof google.firestore.v1.Firestore + * @instance + * @param {google.firestore.v1.IBatchWriteRequest} request BatchWriteRequest message or plain object + * @returns {Promise} Promise + * @variation 2 + */ - /** - * MethodDescriptorProto serverStreaming. - * @member {boolean} serverStreaming - * @memberof google.protobuf.MethodDescriptorProto - * @instance - */ - MethodDescriptorProto.prototype.serverStreaming = false; + /** + * Callback as used by {@link google.firestore.v1.Firestore#createDocument}. + * @memberof google.firestore.v1.Firestore + * @typedef CreateDocumentCallback + * @type {function} + * @param {Error|null} error Error, if any + * @param {google.firestore.v1.Document} [response] Document + */ - /** - * Creates a MethodDescriptorProto message from a plain object. Also converts values to their respective internal types. - * @function fromObject - * @memberof google.protobuf.MethodDescriptorProto - * @static - * @param {Object.} object Plain object - * @returns {google.protobuf.MethodDescriptorProto} MethodDescriptorProto - */ - MethodDescriptorProto.fromObject = function fromObject(object) { - if (object instanceof $root.google.protobuf.MethodDescriptorProto) - return object; - var message = new $root.google.protobuf.MethodDescriptorProto(); - if (object.name != null) - message.name = String(object.name); - if (object.inputType != null) - message.inputType = String(object.inputType); - if (object.outputType != null) - message.outputType = String(object.outputType); - if (object.options != null) { - if (typeof object.options !== "object") - throw TypeError(".google.protobuf.MethodDescriptorProto.options: object expected"); - message.options = $root.google.protobuf.MethodOptions.fromObject(object.options); - } - if (object.clientStreaming != null) - message.clientStreaming = Boolean(object.clientStreaming); - if (object.serverStreaming != null) - message.serverStreaming = Boolean(object.serverStreaming); - return message; - }; + /** + * Calls CreateDocument. + * @function createDocument + * @memberof google.firestore.v1.Firestore + * @instance + * @param {google.firestore.v1.ICreateDocumentRequest} request CreateDocumentRequest message or plain object + * @param {google.firestore.v1.Firestore.CreateDocumentCallback} callback Node-style callback called with the error, if any, and Document + * @returns {undefined} + * @variation 1 + */ + Object.defineProperty(Firestore.prototype.createDocument = function createDocument(request, callback) { + return this.rpcCall(createDocument, $root.google.firestore.v1.CreateDocumentRequest, $root.google.firestore.v1.Document, request, callback); + }, "name", { value: "CreateDocument" }); - /** - * Creates a plain object from a MethodDescriptorProto message. Also converts values to other types if specified. - * @function toObject - * @memberof google.protobuf.MethodDescriptorProto - * @static - * @param {google.protobuf.MethodDescriptorProto} message MethodDescriptorProto - * @param {$protobuf.IConversionOptions} [options] Conversion options - * @returns {Object.} Plain object - */ - MethodDescriptorProto.toObject = function toObject(message, options) { - if (!options) - options = {}; - var object = {}; - if (options.defaults) { - object.name = ""; - object.inputType = ""; - object.outputType = ""; - object.options = null; - object.clientStreaming = false; - object.serverStreaming = false; - } - if (message.name != null && message.hasOwnProperty("name")) - object.name = message.name; - if (message.inputType != null && message.hasOwnProperty("inputType")) - object.inputType = message.inputType; - if (message.outputType != null && message.hasOwnProperty("outputType")) - object.outputType = message.outputType; - if (message.options != null && message.hasOwnProperty("options")) - object.options = $root.google.protobuf.MethodOptions.toObject(message.options, options); - if (message.clientStreaming != null && message.hasOwnProperty("clientStreaming")) - object.clientStreaming = message.clientStreaming; - if (message.serverStreaming != null && message.hasOwnProperty("serverStreaming")) - object.serverStreaming = message.serverStreaming; - return object; - }; - - /** - * Converts this MethodDescriptorProto to JSON. - * @function toJSON - * @memberof google.protobuf.MethodDescriptorProto - * @instance - * @returns {Object.} JSON object - */ - MethodDescriptorProto.prototype.toJSON = function toJSON() { - return this.constructor.toObject(this, $protobuf.util.toJSONOptions); - }; + /** + * Calls CreateDocument. + * @function createDocument + * @memberof google.firestore.v1.Firestore + * @instance + * @param {google.firestore.v1.ICreateDocumentRequest} request CreateDocumentRequest message or plain object + * @returns {Promise} Promise + * @variation 2 + */ - /** - * Gets the default type url for MethodDescriptorProto - * @function getTypeUrl - * @memberof google.protobuf.MethodDescriptorProto - * @static - * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") - * @returns {string} The default type url - */ - MethodDescriptorProto.getTypeUrl = function getTypeUrl(typeUrlPrefix) { - if (typeUrlPrefix === undefined) { - typeUrlPrefix = "type.googleapis.com"; - } - return typeUrlPrefix + "/google.protobuf.MethodDescriptorProto"; - }; + return Firestore; + })(); - return MethodDescriptorProto; - })(); + v1.GetDocumentRequest = (function() { - protobuf.FileOptions = (function() { + /** + * Properties of a GetDocumentRequest. + * @memberof google.firestore.v1 + * @interface IGetDocumentRequest + * @property {string|null} [name] GetDocumentRequest name + * @property {google.firestore.v1.IDocumentMask|null} [mask] GetDocumentRequest mask + * @property {Uint8Array|null} [transaction] GetDocumentRequest transaction + * @property {google.protobuf.ITimestamp|null} [readTime] GetDocumentRequest readTime + */ - /** - * Properties of a FileOptions. - * @memberof google.protobuf - * @interface IFileOptions - * @property {string|null} [javaPackage] FileOptions javaPackage - * @property {string|null} [javaOuterClassname] FileOptions javaOuterClassname - * @property {boolean|null} [javaMultipleFiles] FileOptions javaMultipleFiles - * @property {boolean|null} [javaGenerateEqualsAndHash] FileOptions javaGenerateEqualsAndHash - * @property {boolean|null} [javaStringCheckUtf8] FileOptions javaStringCheckUtf8 - * @property {google.protobuf.FileOptions.OptimizeMode|null} [optimizeFor] FileOptions optimizeFor - * @property {string|null} [goPackage] FileOptions goPackage - * @property {boolean|null} [ccGenericServices] FileOptions ccGenericServices - * @property {boolean|null} [javaGenericServices] FileOptions javaGenericServices - * @property {boolean|null} [pyGenericServices] FileOptions pyGenericServices - * @property {boolean|null} [deprecated] FileOptions deprecated - * @property {boolean|null} [ccEnableArenas] FileOptions ccEnableArenas - * @property {string|null} [objcClassPrefix] FileOptions objcClassPrefix - * @property {string|null} [csharpNamespace] FileOptions csharpNamespace - * @property {string|null} [swiftPrefix] FileOptions swiftPrefix - * @property {string|null} [phpClassPrefix] FileOptions phpClassPrefix - * @property {string|null} [phpNamespace] FileOptions phpNamespace - * @property {string|null} [phpMetadataNamespace] FileOptions phpMetadataNamespace - * @property {string|null} [rubyPackage] FileOptions rubyPackage - * @property {google.protobuf.IFeatureSet|null} [features] FileOptions features - * @property {Array.|null} [uninterpretedOption] FileOptions uninterpretedOption - * @property {Array.|null} [".google.api.resourceDefinition"] FileOptions .google.api.resourceDefinition - */ + /** + * Constructs a new GetDocumentRequest. + * @memberof google.firestore.v1 + * @classdesc Represents a GetDocumentRequest. + * @implements IGetDocumentRequest + * @constructor + * @param {google.firestore.v1.IGetDocumentRequest=} [properties] Properties to set + */ + function GetDocumentRequest(properties) { + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } - /** - * Constructs a new FileOptions. - * @memberof google.protobuf - * @classdesc Represents a FileOptions. - * @implements IFileOptions - * @constructor - * @param {google.protobuf.IFileOptions=} [properties] Properties to set - */ - function FileOptions(properties) { - this.uninterpretedOption = []; - this[".google.api.resourceDefinition"] = []; - if (properties) - for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) - if (properties[keys[i]] != null) - this[keys[i]] = properties[keys[i]]; - } + /** + * GetDocumentRequest name. + * @member {string} name + * @memberof google.firestore.v1.GetDocumentRequest + * @instance + */ + GetDocumentRequest.prototype.name = ""; - /** - * FileOptions javaPackage. - * @member {string} javaPackage - * @memberof google.protobuf.FileOptions - * @instance - */ - FileOptions.prototype.javaPackage = ""; + /** + * GetDocumentRequest mask. + * @member {google.firestore.v1.IDocumentMask|null|undefined} mask + * @memberof google.firestore.v1.GetDocumentRequest + * @instance + */ + GetDocumentRequest.prototype.mask = null; - /** - * FileOptions javaOuterClassname. - * @member {string} javaOuterClassname - * @memberof google.protobuf.FileOptions - * @instance - */ - FileOptions.prototype.javaOuterClassname = ""; + /** + * GetDocumentRequest transaction. + * @member {Uint8Array|null|undefined} transaction + * @memberof google.firestore.v1.GetDocumentRequest + * @instance + */ + GetDocumentRequest.prototype.transaction = null; - /** - * FileOptions javaMultipleFiles. - * @member {boolean} javaMultipleFiles - * @memberof google.protobuf.FileOptions - * @instance - */ - FileOptions.prototype.javaMultipleFiles = false; + /** + * GetDocumentRequest readTime. + * @member {google.protobuf.ITimestamp|null|undefined} readTime + * @memberof google.firestore.v1.GetDocumentRequest + * @instance + */ + GetDocumentRequest.prototype.readTime = null; - /** - * FileOptions javaGenerateEqualsAndHash. - * @member {boolean} javaGenerateEqualsAndHash - * @memberof google.protobuf.FileOptions - * @instance - */ - FileOptions.prototype.javaGenerateEqualsAndHash = false; + // OneOf field names bound to virtual getters and setters + var $oneOfFields; - /** - * FileOptions javaStringCheckUtf8. - * @member {boolean} javaStringCheckUtf8 - * @memberof google.protobuf.FileOptions - * @instance - */ - FileOptions.prototype.javaStringCheckUtf8 = false; + /** + * GetDocumentRequest consistencySelector. + * @member {"transaction"|"readTime"|undefined} consistencySelector + * @memberof google.firestore.v1.GetDocumentRequest + * @instance + */ + Object.defineProperty(GetDocumentRequest.prototype, "consistencySelector", { + get: $util.oneOfGetter($oneOfFields = ["transaction", "readTime"]), + set: $util.oneOfSetter($oneOfFields) + }); - /** - * FileOptions optimizeFor. - * @member {google.protobuf.FileOptions.OptimizeMode} optimizeFor - * @memberof google.protobuf.FileOptions - * @instance - */ - FileOptions.prototype.optimizeFor = 1; + /** + * Creates a GetDocumentRequest message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.firestore.v1.GetDocumentRequest + * @static + * @param {Object.} object Plain object + * @returns {google.firestore.v1.GetDocumentRequest} GetDocumentRequest + */ + GetDocumentRequest.fromObject = function fromObject(object) { + if (object instanceof $root.google.firestore.v1.GetDocumentRequest) + return object; + var message = new $root.google.firestore.v1.GetDocumentRequest(); + if (object.name != null) + message.name = String(object.name); + if (object.mask != null) { + if (typeof object.mask !== "object") + throw TypeError(".google.firestore.v1.GetDocumentRequest.mask: object expected"); + message.mask = $root.google.firestore.v1.DocumentMask.fromObject(object.mask); + } + if (object.transaction != null) + if (typeof object.transaction === "string") + $util.base64.decode(object.transaction, message.transaction = $util.newBuffer($util.base64.length(object.transaction)), 0); + else if (object.transaction.length >= 0) + message.transaction = object.transaction; + if (object.readTime != null) { + if (typeof object.readTime !== "object") + throw TypeError(".google.firestore.v1.GetDocumentRequest.readTime: object expected"); + message.readTime = $root.google.protobuf.Timestamp.fromObject(object.readTime); + } + return message; + }; - /** - * FileOptions goPackage. - * @member {string} goPackage - * @memberof google.protobuf.FileOptions - * @instance - */ - FileOptions.prototype.goPackage = ""; - - /** - * FileOptions ccGenericServices. - * @member {boolean} ccGenericServices - * @memberof google.protobuf.FileOptions - * @instance - */ - FileOptions.prototype.ccGenericServices = false; + /** + * Creates a plain object from a GetDocumentRequest message. Also converts values to other types if specified. + * @function toObject + * @memberof google.firestore.v1.GetDocumentRequest + * @static + * @param {google.firestore.v1.GetDocumentRequest} message GetDocumentRequest + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + GetDocumentRequest.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.defaults) { + object.name = ""; + object.mask = null; + } + if (message.name != null && message.hasOwnProperty("name")) + object.name = message.name; + if (message.mask != null && message.hasOwnProperty("mask")) + object.mask = $root.google.firestore.v1.DocumentMask.toObject(message.mask, options); + if (message.transaction != null && message.hasOwnProperty("transaction")) { + object.transaction = options.bytes === String ? $util.base64.encode(message.transaction, 0, message.transaction.length) : options.bytes === Array ? Array.prototype.slice.call(message.transaction) : message.transaction; + if (options.oneofs) + object.consistencySelector = "transaction"; + } + if (message.readTime != null && message.hasOwnProperty("readTime")) { + object.readTime = $root.google.protobuf.Timestamp.toObject(message.readTime, options); + if (options.oneofs) + object.consistencySelector = "readTime"; + } + return object; + }; - /** - * FileOptions javaGenericServices. - * @member {boolean} javaGenericServices - * @memberof google.protobuf.FileOptions - * @instance - */ - FileOptions.prototype.javaGenericServices = false; + /** + * Converts this GetDocumentRequest to JSON. + * @function toJSON + * @memberof google.firestore.v1.GetDocumentRequest + * @instance + * @returns {Object.} JSON object + */ + GetDocumentRequest.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; - /** - * FileOptions pyGenericServices. - * @member {boolean} pyGenericServices - * @memberof google.protobuf.FileOptions - * @instance - */ - FileOptions.prototype.pyGenericServices = false; + /** + * Gets the default type url for GetDocumentRequest + * @function getTypeUrl + * @memberof google.firestore.v1.GetDocumentRequest + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + GetDocumentRequest.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.firestore.v1.GetDocumentRequest"; + }; - /** - * FileOptions deprecated. - * @member {boolean} deprecated - * @memberof google.protobuf.FileOptions - * @instance - */ - FileOptions.prototype.deprecated = false; + return GetDocumentRequest; + })(); - /** - * FileOptions ccEnableArenas. - * @member {boolean} ccEnableArenas - * @memberof google.protobuf.FileOptions - * @instance - */ - FileOptions.prototype.ccEnableArenas = true; + v1.ListDocumentsRequest = (function() { - /** - * FileOptions objcClassPrefix. - * @member {string} objcClassPrefix - * @memberof google.protobuf.FileOptions - * @instance - */ - FileOptions.prototype.objcClassPrefix = ""; + /** + * Properties of a ListDocumentsRequest. + * @memberof google.firestore.v1 + * @interface IListDocumentsRequest + * @property {string|null} [parent] ListDocumentsRequest parent + * @property {string|null} [collectionId] ListDocumentsRequest collectionId + * @property {number|null} [pageSize] ListDocumentsRequest pageSize + * @property {string|null} [pageToken] ListDocumentsRequest pageToken + * @property {string|null} [orderBy] ListDocumentsRequest orderBy + * @property {google.firestore.v1.IDocumentMask|null} [mask] ListDocumentsRequest mask + * @property {Uint8Array|null} [transaction] ListDocumentsRequest transaction + * @property {google.protobuf.ITimestamp|null} [readTime] ListDocumentsRequest readTime + * @property {boolean|null} [showMissing] ListDocumentsRequest showMissing + */ - /** - * FileOptions csharpNamespace. - * @member {string} csharpNamespace - * @memberof google.protobuf.FileOptions - * @instance - */ - FileOptions.prototype.csharpNamespace = ""; + /** + * Constructs a new ListDocumentsRequest. + * @memberof google.firestore.v1 + * @classdesc Represents a ListDocumentsRequest. + * @implements IListDocumentsRequest + * @constructor + * @param {google.firestore.v1.IListDocumentsRequest=} [properties] Properties to set + */ + function ListDocumentsRequest(properties) { + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } - /** - * FileOptions swiftPrefix. - * @member {string} swiftPrefix - * @memberof google.protobuf.FileOptions - * @instance - */ - FileOptions.prototype.swiftPrefix = ""; + /** + * ListDocumentsRequest parent. + * @member {string} parent + * @memberof google.firestore.v1.ListDocumentsRequest + * @instance + */ + ListDocumentsRequest.prototype.parent = ""; - /** - * FileOptions phpClassPrefix. - * @member {string} phpClassPrefix - * @memberof google.protobuf.FileOptions - * @instance - */ - FileOptions.prototype.phpClassPrefix = ""; + /** + * ListDocumentsRequest collectionId. + * @member {string} collectionId + * @memberof google.firestore.v1.ListDocumentsRequest + * @instance + */ + ListDocumentsRequest.prototype.collectionId = ""; - /** - * FileOptions phpNamespace. - * @member {string} phpNamespace - * @memberof google.protobuf.FileOptions - * @instance - */ - FileOptions.prototype.phpNamespace = ""; + /** + * ListDocumentsRequest pageSize. + * @member {number} pageSize + * @memberof google.firestore.v1.ListDocumentsRequest + * @instance + */ + ListDocumentsRequest.prototype.pageSize = 0; - /** - * FileOptions phpMetadataNamespace. - * @member {string} phpMetadataNamespace - * @memberof google.protobuf.FileOptions - * @instance - */ - FileOptions.prototype.phpMetadataNamespace = ""; + /** + * ListDocumentsRequest pageToken. + * @member {string} pageToken + * @memberof google.firestore.v1.ListDocumentsRequest + * @instance + */ + ListDocumentsRequest.prototype.pageToken = ""; - /** - * FileOptions rubyPackage. - * @member {string} rubyPackage - * @memberof google.protobuf.FileOptions - * @instance - */ - FileOptions.prototype.rubyPackage = ""; + /** + * ListDocumentsRequest orderBy. + * @member {string} orderBy + * @memberof google.firestore.v1.ListDocumentsRequest + * @instance + */ + ListDocumentsRequest.prototype.orderBy = ""; - /** - * FileOptions features. - * @member {google.protobuf.IFeatureSet|null|undefined} features - * @memberof google.protobuf.FileOptions - * @instance - */ - FileOptions.prototype.features = null; + /** + * ListDocumentsRequest mask. + * @member {google.firestore.v1.IDocumentMask|null|undefined} mask + * @memberof google.firestore.v1.ListDocumentsRequest + * @instance + */ + ListDocumentsRequest.prototype.mask = null; - /** - * FileOptions uninterpretedOption. - * @member {Array.} uninterpretedOption - * @memberof google.protobuf.FileOptions - * @instance - */ - FileOptions.prototype.uninterpretedOption = $util.emptyArray; + /** + * ListDocumentsRequest transaction. + * @member {Uint8Array|null|undefined} transaction + * @memberof google.firestore.v1.ListDocumentsRequest + * @instance + */ + ListDocumentsRequest.prototype.transaction = null; - /** - * FileOptions .google.api.resourceDefinition. - * @member {Array.} .google.api.resourceDefinition - * @memberof google.protobuf.FileOptions - * @instance - */ - FileOptions.prototype[".google.api.resourceDefinition"] = $util.emptyArray; + /** + * ListDocumentsRequest readTime. + * @member {google.protobuf.ITimestamp|null|undefined} readTime + * @memberof google.firestore.v1.ListDocumentsRequest + * @instance + */ + ListDocumentsRequest.prototype.readTime = null; - /** - * Creates a FileOptions message from a plain object. Also converts values to their respective internal types. - * @function fromObject - * @memberof google.protobuf.FileOptions - * @static - * @param {Object.} object Plain object - * @returns {google.protobuf.FileOptions} FileOptions - */ - FileOptions.fromObject = function fromObject(object) { - if (object instanceof $root.google.protobuf.FileOptions) - return object; - var message = new $root.google.protobuf.FileOptions(); - if (object.javaPackage != null) - message.javaPackage = String(object.javaPackage); - if (object.javaOuterClassname != null) - message.javaOuterClassname = String(object.javaOuterClassname); - if (object.javaMultipleFiles != null) - message.javaMultipleFiles = Boolean(object.javaMultipleFiles); - if (object.javaGenerateEqualsAndHash != null) - message.javaGenerateEqualsAndHash = Boolean(object.javaGenerateEqualsAndHash); - if (object.javaStringCheckUtf8 != null) - message.javaStringCheckUtf8 = Boolean(object.javaStringCheckUtf8); - switch (object.optimizeFor) { - default: - if (typeof object.optimizeFor === "number") { - message.optimizeFor = object.optimizeFor; - break; - } - break; - case "SPEED": - case 1: - message.optimizeFor = 1; - break; - case "CODE_SIZE": - case 2: - message.optimizeFor = 2; - break; - case "LITE_RUNTIME": - case 3: - message.optimizeFor = 3; - break; - } - if (object.goPackage != null) - message.goPackage = String(object.goPackage); - if (object.ccGenericServices != null) - message.ccGenericServices = Boolean(object.ccGenericServices); - if (object.javaGenericServices != null) - message.javaGenericServices = Boolean(object.javaGenericServices); - if (object.pyGenericServices != null) - message.pyGenericServices = Boolean(object.pyGenericServices); - if (object.deprecated != null) - message.deprecated = Boolean(object.deprecated); - if (object.ccEnableArenas != null) - message.ccEnableArenas = Boolean(object.ccEnableArenas); - if (object.objcClassPrefix != null) - message.objcClassPrefix = String(object.objcClassPrefix); - if (object.csharpNamespace != null) - message.csharpNamespace = String(object.csharpNamespace); - if (object.swiftPrefix != null) - message.swiftPrefix = String(object.swiftPrefix); - if (object.phpClassPrefix != null) - message.phpClassPrefix = String(object.phpClassPrefix); - if (object.phpNamespace != null) - message.phpNamespace = String(object.phpNamespace); - if (object.phpMetadataNamespace != null) - message.phpMetadataNamespace = String(object.phpMetadataNamespace); - if (object.rubyPackage != null) - message.rubyPackage = String(object.rubyPackage); - if (object.features != null) { - if (typeof object.features !== "object") - throw TypeError(".google.protobuf.FileOptions.features: object expected"); - message.features = $root.google.protobuf.FeatureSet.fromObject(object.features); - } - if (object.uninterpretedOption) { - if (!Array.isArray(object.uninterpretedOption)) - throw TypeError(".google.protobuf.FileOptions.uninterpretedOption: array expected"); - message.uninterpretedOption = []; - for (var i = 0; i < object.uninterpretedOption.length; ++i) { - if (typeof object.uninterpretedOption[i] !== "object") - throw TypeError(".google.protobuf.FileOptions.uninterpretedOption: object expected"); - message.uninterpretedOption[i] = $root.google.protobuf.UninterpretedOption.fromObject(object.uninterpretedOption[i]); - } - } - if (object[".google.api.resourceDefinition"]) { - if (!Array.isArray(object[".google.api.resourceDefinition"])) - throw TypeError(".google.protobuf.FileOptions..google.api.resourceDefinition: array expected"); - message[".google.api.resourceDefinition"] = []; - for (var i = 0; i < object[".google.api.resourceDefinition"].length; ++i) { - if (typeof object[".google.api.resourceDefinition"][i] !== "object") - throw TypeError(".google.protobuf.FileOptions..google.api.resourceDefinition: object expected"); - message[".google.api.resourceDefinition"][i] = $root.google.api.ResourceDescriptor.fromObject(object[".google.api.resourceDefinition"][i]); - } - } - return message; - }; - - /** - * Creates a plain object from a FileOptions message. Also converts values to other types if specified. - * @function toObject - * @memberof google.protobuf.FileOptions - * @static - * @param {google.protobuf.FileOptions} message FileOptions - * @param {$protobuf.IConversionOptions} [options] Conversion options - * @returns {Object.} Plain object - */ - FileOptions.toObject = function toObject(message, options) { - if (!options) - options = {}; - var object = {}; - if (options.arrays || options.defaults) { - object.uninterpretedOption = []; - object[".google.api.resourceDefinition"] = []; - } - if (options.defaults) { - object.javaPackage = ""; - object.javaOuterClassname = ""; - object.optimizeFor = options.enums === String ? "SPEED" : 1; - object.javaMultipleFiles = false; - object.goPackage = ""; - object.ccGenericServices = false; - object.javaGenericServices = false; - object.pyGenericServices = false; - object.javaGenerateEqualsAndHash = false; - object.deprecated = false; - object.javaStringCheckUtf8 = false; - object.ccEnableArenas = true; - object.objcClassPrefix = ""; - object.csharpNamespace = ""; - object.swiftPrefix = ""; - object.phpClassPrefix = ""; - object.phpNamespace = ""; - object.phpMetadataNamespace = ""; - object.rubyPackage = ""; - object.features = null; - } - if (message.javaPackage != null && message.hasOwnProperty("javaPackage")) - object.javaPackage = message.javaPackage; - if (message.javaOuterClassname != null && message.hasOwnProperty("javaOuterClassname")) - object.javaOuterClassname = message.javaOuterClassname; - if (message.optimizeFor != null && message.hasOwnProperty("optimizeFor")) - object.optimizeFor = options.enums === String ? $root.google.protobuf.FileOptions.OptimizeMode[message.optimizeFor] === undefined ? message.optimizeFor : $root.google.protobuf.FileOptions.OptimizeMode[message.optimizeFor] : message.optimizeFor; - if (message.javaMultipleFiles != null && message.hasOwnProperty("javaMultipleFiles")) - object.javaMultipleFiles = message.javaMultipleFiles; - if (message.goPackage != null && message.hasOwnProperty("goPackage")) - object.goPackage = message.goPackage; - if (message.ccGenericServices != null && message.hasOwnProperty("ccGenericServices")) - object.ccGenericServices = message.ccGenericServices; - if (message.javaGenericServices != null && message.hasOwnProperty("javaGenericServices")) - object.javaGenericServices = message.javaGenericServices; - if (message.pyGenericServices != null && message.hasOwnProperty("pyGenericServices")) - object.pyGenericServices = message.pyGenericServices; - if (message.javaGenerateEqualsAndHash != null && message.hasOwnProperty("javaGenerateEqualsAndHash")) - object.javaGenerateEqualsAndHash = message.javaGenerateEqualsAndHash; - if (message.deprecated != null && message.hasOwnProperty("deprecated")) - object.deprecated = message.deprecated; - if (message.javaStringCheckUtf8 != null && message.hasOwnProperty("javaStringCheckUtf8")) - object.javaStringCheckUtf8 = message.javaStringCheckUtf8; - if (message.ccEnableArenas != null && message.hasOwnProperty("ccEnableArenas")) - object.ccEnableArenas = message.ccEnableArenas; - if (message.objcClassPrefix != null && message.hasOwnProperty("objcClassPrefix")) - object.objcClassPrefix = message.objcClassPrefix; - if (message.csharpNamespace != null && message.hasOwnProperty("csharpNamespace")) - object.csharpNamespace = message.csharpNamespace; - if (message.swiftPrefix != null && message.hasOwnProperty("swiftPrefix")) - object.swiftPrefix = message.swiftPrefix; - if (message.phpClassPrefix != null && message.hasOwnProperty("phpClassPrefix")) - object.phpClassPrefix = message.phpClassPrefix; - if (message.phpNamespace != null && message.hasOwnProperty("phpNamespace")) - object.phpNamespace = message.phpNamespace; - if (message.phpMetadataNamespace != null && message.hasOwnProperty("phpMetadataNamespace")) - object.phpMetadataNamespace = message.phpMetadataNamespace; - if (message.rubyPackage != null && message.hasOwnProperty("rubyPackage")) - object.rubyPackage = message.rubyPackage; - if (message.features != null && message.hasOwnProperty("features")) - object.features = $root.google.protobuf.FeatureSet.toObject(message.features, options); - if (message.uninterpretedOption && message.uninterpretedOption.length) { - object.uninterpretedOption = []; - for (var j = 0; j < message.uninterpretedOption.length; ++j) - object.uninterpretedOption[j] = $root.google.protobuf.UninterpretedOption.toObject(message.uninterpretedOption[j], options); - } - if (message[".google.api.resourceDefinition"] && message[".google.api.resourceDefinition"].length) { - object[".google.api.resourceDefinition"] = []; - for (var j = 0; j < message[".google.api.resourceDefinition"].length; ++j) - object[".google.api.resourceDefinition"][j] = $root.google.api.ResourceDescriptor.toObject(message[".google.api.resourceDefinition"][j], options); - } - return object; - }; - - /** - * Converts this FileOptions to JSON. - * @function toJSON - * @memberof google.protobuf.FileOptions - * @instance - * @returns {Object.} JSON object - */ - FileOptions.prototype.toJSON = function toJSON() { - return this.constructor.toObject(this, $protobuf.util.toJSONOptions); - }; - - /** - * Gets the default type url for FileOptions - * @function getTypeUrl - * @memberof google.protobuf.FileOptions - * @static - * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") - * @returns {string} The default type url - */ - FileOptions.getTypeUrl = function getTypeUrl(typeUrlPrefix) { - if (typeUrlPrefix === undefined) { - typeUrlPrefix = "type.googleapis.com"; - } - return typeUrlPrefix + "/google.protobuf.FileOptions"; - }; - - /** - * OptimizeMode enum. - * @name google.protobuf.FileOptions.OptimizeMode - * @enum {string} - * @property {string} SPEED=SPEED SPEED value - * @property {string} CODE_SIZE=CODE_SIZE CODE_SIZE value - * @property {string} LITE_RUNTIME=LITE_RUNTIME LITE_RUNTIME value - */ - FileOptions.OptimizeMode = (function() { - var valuesById = {}, values = Object.create(valuesById); - values[valuesById[1] = "SPEED"] = "SPEED"; - values[valuesById[2] = "CODE_SIZE"] = "CODE_SIZE"; - values[valuesById[3] = "LITE_RUNTIME"] = "LITE_RUNTIME"; - return values; - })(); - - return FileOptions; - })(); - - protobuf.MessageOptions = (function() { - - /** - * Properties of a MessageOptions. - * @memberof google.protobuf - * @interface IMessageOptions - * @property {boolean|null} [messageSetWireFormat] MessageOptions messageSetWireFormat - * @property {boolean|null} [noStandardDescriptorAccessor] MessageOptions noStandardDescriptorAccessor - * @property {boolean|null} [deprecated] MessageOptions deprecated - * @property {boolean|null} [mapEntry] MessageOptions mapEntry - * @property {boolean|null} [deprecatedLegacyJsonFieldConflicts] MessageOptions deprecatedLegacyJsonFieldConflicts - * @property {google.protobuf.IFeatureSet|null} [features] MessageOptions features - * @property {Array.|null} [uninterpretedOption] MessageOptions uninterpretedOption - * @property {google.api.IResourceDescriptor|null} [".google.api.resource"] MessageOptions .google.api.resource - */ - - /** - * Constructs a new MessageOptions. - * @memberof google.protobuf - * @classdesc Represents a MessageOptions. - * @implements IMessageOptions - * @constructor - * @param {google.protobuf.IMessageOptions=} [properties] Properties to set - */ - function MessageOptions(properties) { - this.uninterpretedOption = []; - if (properties) - for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) - if (properties[keys[i]] != null) - this[keys[i]] = properties[keys[i]]; - } - - /** - * MessageOptions messageSetWireFormat. - * @member {boolean} messageSetWireFormat - * @memberof google.protobuf.MessageOptions - * @instance - */ - MessageOptions.prototype.messageSetWireFormat = false; - - /** - * MessageOptions noStandardDescriptorAccessor. - * @member {boolean} noStandardDescriptorAccessor - * @memberof google.protobuf.MessageOptions - * @instance - */ - MessageOptions.prototype.noStandardDescriptorAccessor = false; - - /** - * MessageOptions deprecated. - * @member {boolean} deprecated - * @memberof google.protobuf.MessageOptions - * @instance - */ - MessageOptions.prototype.deprecated = false; - - /** - * MessageOptions mapEntry. - * @member {boolean} mapEntry - * @memberof google.protobuf.MessageOptions - * @instance - */ - MessageOptions.prototype.mapEntry = false; - - /** - * MessageOptions deprecatedLegacyJsonFieldConflicts. - * @member {boolean} deprecatedLegacyJsonFieldConflicts - * @memberof google.protobuf.MessageOptions - * @instance - */ - MessageOptions.prototype.deprecatedLegacyJsonFieldConflicts = false; - - /** - * MessageOptions features. - * @member {google.protobuf.IFeatureSet|null|undefined} features - * @memberof google.protobuf.MessageOptions - * @instance - */ - MessageOptions.prototype.features = null; - - /** - * MessageOptions uninterpretedOption. - * @member {Array.} uninterpretedOption - * @memberof google.protobuf.MessageOptions - * @instance - */ - MessageOptions.prototype.uninterpretedOption = $util.emptyArray; - - /** - * MessageOptions .google.api.resource. - * @member {google.api.IResourceDescriptor|null|undefined} .google.api.resource - * @memberof google.protobuf.MessageOptions - * @instance - */ - MessageOptions.prototype[".google.api.resource"] = null; - - /** - * Creates a MessageOptions message from a plain object. Also converts values to their respective internal types. - * @function fromObject - * @memberof google.protobuf.MessageOptions - * @static - * @param {Object.} object Plain object - * @returns {google.protobuf.MessageOptions} MessageOptions - */ - MessageOptions.fromObject = function fromObject(object) { - if (object instanceof $root.google.protobuf.MessageOptions) - return object; - var message = new $root.google.protobuf.MessageOptions(); - if (object.messageSetWireFormat != null) - message.messageSetWireFormat = Boolean(object.messageSetWireFormat); - if (object.noStandardDescriptorAccessor != null) - message.noStandardDescriptorAccessor = Boolean(object.noStandardDescriptorAccessor); - if (object.deprecated != null) - message.deprecated = Boolean(object.deprecated); - if (object.mapEntry != null) - message.mapEntry = Boolean(object.mapEntry); - if (object.deprecatedLegacyJsonFieldConflicts != null) - message.deprecatedLegacyJsonFieldConflicts = Boolean(object.deprecatedLegacyJsonFieldConflicts); - if (object.features != null) { - if (typeof object.features !== "object") - throw TypeError(".google.protobuf.MessageOptions.features: object expected"); - message.features = $root.google.protobuf.FeatureSet.fromObject(object.features); - } - if (object.uninterpretedOption) { - if (!Array.isArray(object.uninterpretedOption)) - throw TypeError(".google.protobuf.MessageOptions.uninterpretedOption: array expected"); - message.uninterpretedOption = []; - for (var i = 0; i < object.uninterpretedOption.length; ++i) { - if (typeof object.uninterpretedOption[i] !== "object") - throw TypeError(".google.protobuf.MessageOptions.uninterpretedOption: object expected"); - message.uninterpretedOption[i] = $root.google.protobuf.UninterpretedOption.fromObject(object.uninterpretedOption[i]); - } - } - if (object[".google.api.resource"] != null) { - if (typeof object[".google.api.resource"] !== "object") - throw TypeError(".google.protobuf.MessageOptions..google.api.resource: object expected"); - message[".google.api.resource"] = $root.google.api.ResourceDescriptor.fromObject(object[".google.api.resource"]); - } - return message; - }; - - /** - * Creates a plain object from a MessageOptions message. Also converts values to other types if specified. - * @function toObject - * @memberof google.protobuf.MessageOptions - * @static - * @param {google.protobuf.MessageOptions} message MessageOptions - * @param {$protobuf.IConversionOptions} [options] Conversion options - * @returns {Object.} Plain object - */ - MessageOptions.toObject = function toObject(message, options) { - if (!options) - options = {}; - var object = {}; - if (options.arrays || options.defaults) - object.uninterpretedOption = []; - if (options.defaults) { - object.messageSetWireFormat = false; - object.noStandardDescriptorAccessor = false; - object.deprecated = false; - object.mapEntry = false; - object.deprecatedLegacyJsonFieldConflicts = false; - object.features = null; - object[".google.api.resource"] = null; - } - if (message.messageSetWireFormat != null && message.hasOwnProperty("messageSetWireFormat")) - object.messageSetWireFormat = message.messageSetWireFormat; - if (message.noStandardDescriptorAccessor != null && message.hasOwnProperty("noStandardDescriptorAccessor")) - object.noStandardDescriptorAccessor = message.noStandardDescriptorAccessor; - if (message.deprecated != null && message.hasOwnProperty("deprecated")) - object.deprecated = message.deprecated; - if (message.mapEntry != null && message.hasOwnProperty("mapEntry")) - object.mapEntry = message.mapEntry; - if (message.deprecatedLegacyJsonFieldConflicts != null && message.hasOwnProperty("deprecatedLegacyJsonFieldConflicts")) - object.deprecatedLegacyJsonFieldConflicts = message.deprecatedLegacyJsonFieldConflicts; - if (message.features != null && message.hasOwnProperty("features")) - object.features = $root.google.protobuf.FeatureSet.toObject(message.features, options); - if (message.uninterpretedOption && message.uninterpretedOption.length) { - object.uninterpretedOption = []; - for (var j = 0; j < message.uninterpretedOption.length; ++j) - object.uninterpretedOption[j] = $root.google.protobuf.UninterpretedOption.toObject(message.uninterpretedOption[j], options); - } - if (message[".google.api.resource"] != null && message.hasOwnProperty(".google.api.resource")) - object[".google.api.resource"] = $root.google.api.ResourceDescriptor.toObject(message[".google.api.resource"], options); - return object; - }; - - /** - * Converts this MessageOptions to JSON. - * @function toJSON - * @memberof google.protobuf.MessageOptions - * @instance - * @returns {Object.} JSON object - */ - MessageOptions.prototype.toJSON = function toJSON() { - return this.constructor.toObject(this, $protobuf.util.toJSONOptions); - }; - - /** - * Gets the default type url for MessageOptions - * @function getTypeUrl - * @memberof google.protobuf.MessageOptions - * @static - * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") - * @returns {string} The default type url - */ - MessageOptions.getTypeUrl = function getTypeUrl(typeUrlPrefix) { - if (typeUrlPrefix === undefined) { - typeUrlPrefix = "type.googleapis.com"; - } - return typeUrlPrefix + "/google.protobuf.MessageOptions"; - }; - - return MessageOptions; - })(); - - protobuf.FieldOptions = (function() { - - /** - * Properties of a FieldOptions. - * @memberof google.protobuf - * @interface IFieldOptions - * @property {google.protobuf.FieldOptions.CType|null} [ctype] FieldOptions ctype - * @property {boolean|null} [packed] FieldOptions packed - * @property {google.protobuf.FieldOptions.JSType|null} [jstype] FieldOptions jstype - * @property {boolean|null} [lazy] FieldOptions lazy - * @property {boolean|null} [unverifiedLazy] FieldOptions unverifiedLazy - * @property {boolean|null} [deprecated] FieldOptions deprecated - * @property {boolean|null} [weak] FieldOptions weak - * @property {boolean|null} [debugRedact] FieldOptions debugRedact - * @property {google.protobuf.FieldOptions.OptionRetention|null} [retention] FieldOptions retention - * @property {Array.|null} [targets] FieldOptions targets - * @property {Array.|null} [editionDefaults] FieldOptions editionDefaults - * @property {google.protobuf.IFeatureSet|null} [features] FieldOptions features - * @property {google.protobuf.FieldOptions.IFeatureSupport|null} [featureSupport] FieldOptions featureSupport - * @property {Array.|null} [uninterpretedOption] FieldOptions uninterpretedOption - * @property {Array.|null} [".google.api.fieldBehavior"] FieldOptions .google.api.fieldBehavior - * @property {google.api.IResourceReference|null} [".google.api.resourceReference"] FieldOptions .google.api.resourceReference - */ - - /** - * Constructs a new FieldOptions. - * @memberof google.protobuf - * @classdesc Represents a FieldOptions. - * @implements IFieldOptions - * @constructor - * @param {google.protobuf.IFieldOptions=} [properties] Properties to set - */ - function FieldOptions(properties) { - this.targets = []; - this.editionDefaults = []; - this.uninterpretedOption = []; - this[".google.api.fieldBehavior"] = []; - if (properties) - for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) - if (properties[keys[i]] != null) - this[keys[i]] = properties[keys[i]]; - } - - /** - * FieldOptions ctype. - * @member {google.protobuf.FieldOptions.CType} ctype - * @memberof google.protobuf.FieldOptions - * @instance - */ - FieldOptions.prototype.ctype = 0; - - /** - * FieldOptions packed. - * @member {boolean} packed - * @memberof google.protobuf.FieldOptions - * @instance - */ - FieldOptions.prototype.packed = false; - - /** - * FieldOptions jstype. - * @member {google.protobuf.FieldOptions.JSType} jstype - * @memberof google.protobuf.FieldOptions - * @instance - */ - FieldOptions.prototype.jstype = 0; - - /** - * FieldOptions lazy. - * @member {boolean} lazy - * @memberof google.protobuf.FieldOptions - * @instance - */ - FieldOptions.prototype.lazy = false; - - /** - * FieldOptions unverifiedLazy. - * @member {boolean} unverifiedLazy - * @memberof google.protobuf.FieldOptions - * @instance - */ - FieldOptions.prototype.unverifiedLazy = false; - - /** - * FieldOptions deprecated. - * @member {boolean} deprecated - * @memberof google.protobuf.FieldOptions - * @instance - */ - FieldOptions.prototype.deprecated = false; - - /** - * FieldOptions weak. - * @member {boolean} weak - * @memberof google.protobuf.FieldOptions - * @instance - */ - FieldOptions.prototype.weak = false; - - /** - * FieldOptions debugRedact. - * @member {boolean} debugRedact - * @memberof google.protobuf.FieldOptions - * @instance - */ - FieldOptions.prototype.debugRedact = false; - - /** - * FieldOptions retention. - * @member {google.protobuf.FieldOptions.OptionRetention} retention - * @memberof google.protobuf.FieldOptions - * @instance - */ - FieldOptions.prototype.retention = 0; - - /** - * FieldOptions targets. - * @member {Array.} targets - * @memberof google.protobuf.FieldOptions - * @instance - */ - FieldOptions.prototype.targets = $util.emptyArray; - - /** - * FieldOptions editionDefaults. - * @member {Array.} editionDefaults - * @memberof google.protobuf.FieldOptions - * @instance - */ - FieldOptions.prototype.editionDefaults = $util.emptyArray; - - /** - * FieldOptions features. - * @member {google.protobuf.IFeatureSet|null|undefined} features - * @memberof google.protobuf.FieldOptions - * @instance - */ - FieldOptions.prototype.features = null; - - /** - * FieldOptions featureSupport. - * @member {google.protobuf.FieldOptions.IFeatureSupport|null|undefined} featureSupport - * @memberof google.protobuf.FieldOptions - * @instance - */ - FieldOptions.prototype.featureSupport = null; - - /** - * FieldOptions uninterpretedOption. - * @member {Array.} uninterpretedOption - * @memberof google.protobuf.FieldOptions - * @instance - */ - FieldOptions.prototype.uninterpretedOption = $util.emptyArray; - - /** - * FieldOptions .google.api.fieldBehavior. - * @member {Array.} .google.api.fieldBehavior - * @memberof google.protobuf.FieldOptions - * @instance - */ - FieldOptions.prototype[".google.api.fieldBehavior"] = $util.emptyArray; - - /** - * FieldOptions .google.api.resourceReference. - * @member {google.api.IResourceReference|null|undefined} .google.api.resourceReference - * @memberof google.protobuf.FieldOptions - * @instance - */ - FieldOptions.prototype[".google.api.resourceReference"] = null; - - /** - * Creates a FieldOptions message from a plain object. Also converts values to their respective internal types. - * @function fromObject - * @memberof google.protobuf.FieldOptions - * @static - * @param {Object.} object Plain object - * @returns {google.protobuf.FieldOptions} FieldOptions - */ - FieldOptions.fromObject = function fromObject(object) { - if (object instanceof $root.google.protobuf.FieldOptions) - return object; - var message = new $root.google.protobuf.FieldOptions(); - switch (object.ctype) { - default: - if (typeof object.ctype === "number") { - message.ctype = object.ctype; - break; - } - break; - case "STRING": - case 0: - message.ctype = 0; - break; - case "CORD": - case 1: - message.ctype = 1; - break; - case "STRING_PIECE": - case 2: - message.ctype = 2; - break; - } - if (object.packed != null) - message.packed = Boolean(object.packed); - switch (object.jstype) { - default: - if (typeof object.jstype === "number") { - message.jstype = object.jstype; - break; - } - break; - case "JS_NORMAL": - case 0: - message.jstype = 0; - break; - case "JS_STRING": - case 1: - message.jstype = 1; - break; - case "JS_NUMBER": - case 2: - message.jstype = 2; - break; - } - if (object.lazy != null) - message.lazy = Boolean(object.lazy); - if (object.unverifiedLazy != null) - message.unverifiedLazy = Boolean(object.unverifiedLazy); - if (object.deprecated != null) - message.deprecated = Boolean(object.deprecated); - if (object.weak != null) - message.weak = Boolean(object.weak); - if (object.debugRedact != null) - message.debugRedact = Boolean(object.debugRedact); - switch (object.retention) { - default: - if (typeof object.retention === "number") { - message.retention = object.retention; - break; - } - break; - case "RETENTION_UNKNOWN": - case 0: - message.retention = 0; - break; - case "RETENTION_RUNTIME": - case 1: - message.retention = 1; - break; - case "RETENTION_SOURCE": - case 2: - message.retention = 2; - break; - } - if (object.targets) { - if (!Array.isArray(object.targets)) - throw TypeError(".google.protobuf.FieldOptions.targets: array expected"); - message.targets = []; - for (var i = 0; i < object.targets.length; ++i) - switch (object.targets[i]) { - default: - if (typeof object.targets[i] === "number") { - message.targets[i] = object.targets[i]; - break; - } - case "TARGET_TYPE_UNKNOWN": - case 0: - message.targets[i] = 0; - break; - case "TARGET_TYPE_FILE": - case 1: - message.targets[i] = 1; - break; - case "TARGET_TYPE_EXTENSION_RANGE": - case 2: - message.targets[i] = 2; - break; - case "TARGET_TYPE_MESSAGE": - case 3: - message.targets[i] = 3; - break; - case "TARGET_TYPE_FIELD": - case 4: - message.targets[i] = 4; - break; - case "TARGET_TYPE_ONEOF": - case 5: - message.targets[i] = 5; - break; - case "TARGET_TYPE_ENUM": - case 6: - message.targets[i] = 6; - break; - case "TARGET_TYPE_ENUM_ENTRY": - case 7: - message.targets[i] = 7; - break; - case "TARGET_TYPE_SERVICE": - case 8: - message.targets[i] = 8; - break; - case "TARGET_TYPE_METHOD": - case 9: - message.targets[i] = 9; - break; - } - } - if (object.editionDefaults) { - if (!Array.isArray(object.editionDefaults)) - throw TypeError(".google.protobuf.FieldOptions.editionDefaults: array expected"); - message.editionDefaults = []; - for (var i = 0; i < object.editionDefaults.length; ++i) { - if (typeof object.editionDefaults[i] !== "object") - throw TypeError(".google.protobuf.FieldOptions.editionDefaults: object expected"); - message.editionDefaults[i] = $root.google.protobuf.FieldOptions.EditionDefault.fromObject(object.editionDefaults[i]); + /** + * ListDocumentsRequest showMissing. + * @member {boolean} showMissing + * @memberof google.firestore.v1.ListDocumentsRequest + * @instance + */ + ListDocumentsRequest.prototype.showMissing = false; + + // OneOf field names bound to virtual getters and setters + var $oneOfFields; + + /** + * ListDocumentsRequest consistencySelector. + * @member {"transaction"|"readTime"|undefined} consistencySelector + * @memberof google.firestore.v1.ListDocumentsRequest + * @instance + */ + Object.defineProperty(ListDocumentsRequest.prototype, "consistencySelector", { + get: $util.oneOfGetter($oneOfFields = ["transaction", "readTime"]), + set: $util.oneOfSetter($oneOfFields) + }); + + /** + * Creates a ListDocumentsRequest message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.firestore.v1.ListDocumentsRequest + * @static + * @param {Object.} object Plain object + * @returns {google.firestore.v1.ListDocumentsRequest} ListDocumentsRequest + */ + ListDocumentsRequest.fromObject = function fromObject(object) { + if (object instanceof $root.google.firestore.v1.ListDocumentsRequest) + return object; + var message = new $root.google.firestore.v1.ListDocumentsRequest(); + if (object.parent != null) + message.parent = String(object.parent); + if (object.collectionId != null) + message.collectionId = String(object.collectionId); + if (object.pageSize != null) + message.pageSize = object.pageSize | 0; + if (object.pageToken != null) + message.pageToken = String(object.pageToken); + if (object.orderBy != null) + message.orderBy = String(object.orderBy); + if (object.mask != null) { + if (typeof object.mask !== "object") + throw TypeError(".google.firestore.v1.ListDocumentsRequest.mask: object expected"); + message.mask = $root.google.firestore.v1.DocumentMask.fromObject(object.mask); } - } - if (object.features != null) { - if (typeof object.features !== "object") - throw TypeError(".google.protobuf.FieldOptions.features: object expected"); - message.features = $root.google.protobuf.FeatureSet.fromObject(object.features); - } - if (object.featureSupport != null) { - if (typeof object.featureSupport !== "object") - throw TypeError(".google.protobuf.FieldOptions.featureSupport: object expected"); - message.featureSupport = $root.google.protobuf.FieldOptions.FeatureSupport.fromObject(object.featureSupport); - } - if (object.uninterpretedOption) { - if (!Array.isArray(object.uninterpretedOption)) - throw TypeError(".google.protobuf.FieldOptions.uninterpretedOption: array expected"); - message.uninterpretedOption = []; - for (var i = 0; i < object.uninterpretedOption.length; ++i) { - if (typeof object.uninterpretedOption[i] !== "object") - throw TypeError(".google.protobuf.FieldOptions.uninterpretedOption: object expected"); - message.uninterpretedOption[i] = $root.google.protobuf.UninterpretedOption.fromObject(object.uninterpretedOption[i]); + if (object.transaction != null) + if (typeof object.transaction === "string") + $util.base64.decode(object.transaction, message.transaction = $util.newBuffer($util.base64.length(object.transaction)), 0); + else if (object.transaction.length >= 0) + message.transaction = object.transaction; + if (object.readTime != null) { + if (typeof object.readTime !== "object") + throw TypeError(".google.firestore.v1.ListDocumentsRequest.readTime: object expected"); + message.readTime = $root.google.protobuf.Timestamp.fromObject(object.readTime); } - } - if (object[".google.api.fieldBehavior"]) { - if (!Array.isArray(object[".google.api.fieldBehavior"])) - throw TypeError(".google.protobuf.FieldOptions..google.api.fieldBehavior: array expected"); - message[".google.api.fieldBehavior"] = []; - for (var i = 0; i < object[".google.api.fieldBehavior"].length; ++i) - switch (object[".google.api.fieldBehavior"][i]) { - default: - if (typeof object[".google.api.fieldBehavior"][i] === "number") { - message[".google.api.fieldBehavior"][i] = object[".google.api.fieldBehavior"][i]; - break; - } - case "FIELD_BEHAVIOR_UNSPECIFIED": - case 0: - message[".google.api.fieldBehavior"][i] = 0; - break; - case "OPTIONAL": - case 1: - message[".google.api.fieldBehavior"][i] = 1; - break; - case "REQUIRED": - case 2: - message[".google.api.fieldBehavior"][i] = 2; - break; - case "OUTPUT_ONLY": - case 3: - message[".google.api.fieldBehavior"][i] = 3; - break; - case "INPUT_ONLY": - case 4: - message[".google.api.fieldBehavior"][i] = 4; - break; - case "IMMUTABLE": - case 5: - message[".google.api.fieldBehavior"][i] = 5; - break; - case "UNORDERED_LIST": - case 6: - message[".google.api.fieldBehavior"][i] = 6; - break; - case "NON_EMPTY_DEFAULT": - case 7: - message[".google.api.fieldBehavior"][i] = 7; - break; - case "IDENTIFIER": - case 8: - message[".google.api.fieldBehavior"][i] = 8; - break; - } - } - if (object[".google.api.resourceReference"] != null) { - if (typeof object[".google.api.resourceReference"] !== "object") - throw TypeError(".google.protobuf.FieldOptions..google.api.resourceReference: object expected"); - message[".google.api.resourceReference"] = $root.google.api.ResourceReference.fromObject(object[".google.api.resourceReference"]); - } - return message; - }; + if (object.showMissing != null) + message.showMissing = Boolean(object.showMissing); + return message; + }; - /** - * Creates a plain object from a FieldOptions message. Also converts values to other types if specified. - * @function toObject - * @memberof google.protobuf.FieldOptions - * @static - * @param {google.protobuf.FieldOptions} message FieldOptions - * @param {$protobuf.IConversionOptions} [options] Conversion options - * @returns {Object.} Plain object - */ - FieldOptions.toObject = function toObject(message, options) { - if (!options) - options = {}; - var object = {}; - if (options.arrays || options.defaults) { - object.targets = []; - object.editionDefaults = []; - object.uninterpretedOption = []; - object[".google.api.fieldBehavior"] = []; - } - if (options.defaults) { - object.ctype = options.enums === String ? "STRING" : 0; - object.packed = false; - object.deprecated = false; - object.lazy = false; - object.jstype = options.enums === String ? "JS_NORMAL" : 0; - object.weak = false; - object.unverifiedLazy = false; - object.debugRedact = false; - object.retention = options.enums === String ? "RETENTION_UNKNOWN" : 0; - object.features = null; - object.featureSupport = null; - object[".google.api.resourceReference"] = null; - } - if (message.ctype != null && message.hasOwnProperty("ctype")) - object.ctype = options.enums === String ? $root.google.protobuf.FieldOptions.CType[message.ctype] === undefined ? message.ctype : $root.google.protobuf.FieldOptions.CType[message.ctype] : message.ctype; - if (message.packed != null && message.hasOwnProperty("packed")) - object.packed = message.packed; - if (message.deprecated != null && message.hasOwnProperty("deprecated")) - object.deprecated = message.deprecated; - if (message.lazy != null && message.hasOwnProperty("lazy")) - object.lazy = message.lazy; - if (message.jstype != null && message.hasOwnProperty("jstype")) - object.jstype = options.enums === String ? $root.google.protobuf.FieldOptions.JSType[message.jstype] === undefined ? message.jstype : $root.google.protobuf.FieldOptions.JSType[message.jstype] : message.jstype; - if (message.weak != null && message.hasOwnProperty("weak")) - object.weak = message.weak; - if (message.unverifiedLazy != null && message.hasOwnProperty("unverifiedLazy")) - object.unverifiedLazy = message.unverifiedLazy; - if (message.debugRedact != null && message.hasOwnProperty("debugRedact")) - object.debugRedact = message.debugRedact; - if (message.retention != null && message.hasOwnProperty("retention")) - object.retention = options.enums === String ? $root.google.protobuf.FieldOptions.OptionRetention[message.retention] === undefined ? message.retention : $root.google.protobuf.FieldOptions.OptionRetention[message.retention] : message.retention; - if (message.targets && message.targets.length) { - object.targets = []; - for (var j = 0; j < message.targets.length; ++j) - object.targets[j] = options.enums === String ? $root.google.protobuf.FieldOptions.OptionTargetType[message.targets[j]] === undefined ? message.targets[j] : $root.google.protobuf.FieldOptions.OptionTargetType[message.targets[j]] : message.targets[j]; - } - if (message.editionDefaults && message.editionDefaults.length) { - object.editionDefaults = []; - for (var j = 0; j < message.editionDefaults.length; ++j) - object.editionDefaults[j] = $root.google.protobuf.FieldOptions.EditionDefault.toObject(message.editionDefaults[j], options); - } - if (message.features != null && message.hasOwnProperty("features")) - object.features = $root.google.protobuf.FeatureSet.toObject(message.features, options); - if (message.featureSupport != null && message.hasOwnProperty("featureSupport")) - object.featureSupport = $root.google.protobuf.FieldOptions.FeatureSupport.toObject(message.featureSupport, options); - if (message.uninterpretedOption && message.uninterpretedOption.length) { - object.uninterpretedOption = []; - for (var j = 0; j < message.uninterpretedOption.length; ++j) - object.uninterpretedOption[j] = $root.google.protobuf.UninterpretedOption.toObject(message.uninterpretedOption[j], options); - } - if (message[".google.api.fieldBehavior"] && message[".google.api.fieldBehavior"].length) { - object[".google.api.fieldBehavior"] = []; - for (var j = 0; j < message[".google.api.fieldBehavior"].length; ++j) - object[".google.api.fieldBehavior"][j] = options.enums === String ? $root.google.api.FieldBehavior[message[".google.api.fieldBehavior"][j]] === undefined ? message[".google.api.fieldBehavior"][j] : $root.google.api.FieldBehavior[message[".google.api.fieldBehavior"][j]] : message[".google.api.fieldBehavior"][j]; - } - if (message[".google.api.resourceReference"] != null && message.hasOwnProperty(".google.api.resourceReference")) - object[".google.api.resourceReference"] = $root.google.api.ResourceReference.toObject(message[".google.api.resourceReference"], options); - return object; - }; + /** + * Creates a plain object from a ListDocumentsRequest message. Also converts values to other types if specified. + * @function toObject + * @memberof google.firestore.v1.ListDocumentsRequest + * @static + * @param {google.firestore.v1.ListDocumentsRequest} message ListDocumentsRequest + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + ListDocumentsRequest.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.defaults) { + object.parent = ""; + object.collectionId = ""; + object.pageSize = 0; + object.pageToken = ""; + object.orderBy = ""; + object.mask = null; + object.showMissing = false; + } + if (message.parent != null && message.hasOwnProperty("parent")) + object.parent = message.parent; + if (message.collectionId != null && message.hasOwnProperty("collectionId")) + object.collectionId = message.collectionId; + if (message.pageSize != null && message.hasOwnProperty("pageSize")) + object.pageSize = message.pageSize; + if (message.pageToken != null && message.hasOwnProperty("pageToken")) + object.pageToken = message.pageToken; + if (message.orderBy != null && message.hasOwnProperty("orderBy")) + object.orderBy = message.orderBy; + if (message.mask != null && message.hasOwnProperty("mask")) + object.mask = $root.google.firestore.v1.DocumentMask.toObject(message.mask, options); + if (message.transaction != null && message.hasOwnProperty("transaction")) { + object.transaction = options.bytes === String ? $util.base64.encode(message.transaction, 0, message.transaction.length) : options.bytes === Array ? Array.prototype.slice.call(message.transaction) : message.transaction; + if (options.oneofs) + object.consistencySelector = "transaction"; + } + if (message.readTime != null && message.hasOwnProperty("readTime")) { + object.readTime = $root.google.protobuf.Timestamp.toObject(message.readTime, options); + if (options.oneofs) + object.consistencySelector = "readTime"; + } + if (message.showMissing != null && message.hasOwnProperty("showMissing")) + object.showMissing = message.showMissing; + return object; + }; - /** - * Converts this FieldOptions to JSON. - * @function toJSON - * @memberof google.protobuf.FieldOptions - * @instance - * @returns {Object.} JSON object - */ - FieldOptions.prototype.toJSON = function toJSON() { - return this.constructor.toObject(this, $protobuf.util.toJSONOptions); - }; + /** + * Converts this ListDocumentsRequest to JSON. + * @function toJSON + * @memberof google.firestore.v1.ListDocumentsRequest + * @instance + * @returns {Object.} JSON object + */ + ListDocumentsRequest.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; - /** - * Gets the default type url for FieldOptions - * @function getTypeUrl - * @memberof google.protobuf.FieldOptions - * @static - * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") - * @returns {string} The default type url - */ - FieldOptions.getTypeUrl = function getTypeUrl(typeUrlPrefix) { - if (typeUrlPrefix === undefined) { - typeUrlPrefix = "type.googleapis.com"; - } - return typeUrlPrefix + "/google.protobuf.FieldOptions"; - }; + /** + * Gets the default type url for ListDocumentsRequest + * @function getTypeUrl + * @memberof google.firestore.v1.ListDocumentsRequest + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + ListDocumentsRequest.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.firestore.v1.ListDocumentsRequest"; + }; - /** - * CType enum. - * @name google.protobuf.FieldOptions.CType - * @enum {string} - * @property {string} STRING=STRING STRING value - * @property {string} CORD=CORD CORD value - * @property {string} STRING_PIECE=STRING_PIECE STRING_PIECE value - */ - FieldOptions.CType = (function() { - var valuesById = {}, values = Object.create(valuesById); - values[valuesById[0] = "STRING"] = "STRING"; - values[valuesById[1] = "CORD"] = "CORD"; - values[valuesById[2] = "STRING_PIECE"] = "STRING_PIECE"; - return values; + return ListDocumentsRequest; })(); - /** - * JSType enum. - * @name google.protobuf.FieldOptions.JSType - * @enum {string} - * @property {string} JS_NORMAL=JS_NORMAL JS_NORMAL value - * @property {string} JS_STRING=JS_STRING JS_STRING value - * @property {string} JS_NUMBER=JS_NUMBER JS_NUMBER value - */ - FieldOptions.JSType = (function() { - var valuesById = {}, values = Object.create(valuesById); - values[valuesById[0] = "JS_NORMAL"] = "JS_NORMAL"; - values[valuesById[1] = "JS_STRING"] = "JS_STRING"; - values[valuesById[2] = "JS_NUMBER"] = "JS_NUMBER"; - return values; - })(); + v1.ListDocumentsResponse = (function() { - /** - * OptionRetention enum. - * @name google.protobuf.FieldOptions.OptionRetention - * @enum {string} - * @property {string} RETENTION_UNKNOWN=RETENTION_UNKNOWN RETENTION_UNKNOWN value - * @property {string} RETENTION_RUNTIME=RETENTION_RUNTIME RETENTION_RUNTIME value - * @property {string} RETENTION_SOURCE=RETENTION_SOURCE RETENTION_SOURCE value - */ - FieldOptions.OptionRetention = (function() { - var valuesById = {}, values = Object.create(valuesById); - values[valuesById[0] = "RETENTION_UNKNOWN"] = "RETENTION_UNKNOWN"; - values[valuesById[1] = "RETENTION_RUNTIME"] = "RETENTION_RUNTIME"; - values[valuesById[2] = "RETENTION_SOURCE"] = "RETENTION_SOURCE"; - return values; - })(); + /** + * Properties of a ListDocumentsResponse. + * @memberof google.firestore.v1 + * @interface IListDocumentsResponse + * @property {Array.|null} [documents] ListDocumentsResponse documents + * @property {string|null} [nextPageToken] ListDocumentsResponse nextPageToken + */ - /** - * OptionTargetType enum. - * @name google.protobuf.FieldOptions.OptionTargetType - * @enum {string} - * @property {string} TARGET_TYPE_UNKNOWN=TARGET_TYPE_UNKNOWN TARGET_TYPE_UNKNOWN value - * @property {string} TARGET_TYPE_FILE=TARGET_TYPE_FILE TARGET_TYPE_FILE value - * @property {string} TARGET_TYPE_EXTENSION_RANGE=TARGET_TYPE_EXTENSION_RANGE TARGET_TYPE_EXTENSION_RANGE value - * @property {string} TARGET_TYPE_MESSAGE=TARGET_TYPE_MESSAGE TARGET_TYPE_MESSAGE value - * @property {string} TARGET_TYPE_FIELD=TARGET_TYPE_FIELD TARGET_TYPE_FIELD value - * @property {string} TARGET_TYPE_ONEOF=TARGET_TYPE_ONEOF TARGET_TYPE_ONEOF value - * @property {string} TARGET_TYPE_ENUM=TARGET_TYPE_ENUM TARGET_TYPE_ENUM value - * @property {string} TARGET_TYPE_ENUM_ENTRY=TARGET_TYPE_ENUM_ENTRY TARGET_TYPE_ENUM_ENTRY value - * @property {string} TARGET_TYPE_SERVICE=TARGET_TYPE_SERVICE TARGET_TYPE_SERVICE value - * @property {string} TARGET_TYPE_METHOD=TARGET_TYPE_METHOD TARGET_TYPE_METHOD value - */ - FieldOptions.OptionTargetType = (function() { - var valuesById = {}, values = Object.create(valuesById); - values[valuesById[0] = "TARGET_TYPE_UNKNOWN"] = "TARGET_TYPE_UNKNOWN"; - values[valuesById[1] = "TARGET_TYPE_FILE"] = "TARGET_TYPE_FILE"; - values[valuesById[2] = "TARGET_TYPE_EXTENSION_RANGE"] = "TARGET_TYPE_EXTENSION_RANGE"; - values[valuesById[3] = "TARGET_TYPE_MESSAGE"] = "TARGET_TYPE_MESSAGE"; - values[valuesById[4] = "TARGET_TYPE_FIELD"] = "TARGET_TYPE_FIELD"; - values[valuesById[5] = "TARGET_TYPE_ONEOF"] = "TARGET_TYPE_ONEOF"; - values[valuesById[6] = "TARGET_TYPE_ENUM"] = "TARGET_TYPE_ENUM"; - values[valuesById[7] = "TARGET_TYPE_ENUM_ENTRY"] = "TARGET_TYPE_ENUM_ENTRY"; - values[valuesById[8] = "TARGET_TYPE_SERVICE"] = "TARGET_TYPE_SERVICE"; - values[valuesById[9] = "TARGET_TYPE_METHOD"] = "TARGET_TYPE_METHOD"; - return values; + /** + * Constructs a new ListDocumentsResponse. + * @memberof google.firestore.v1 + * @classdesc Represents a ListDocumentsResponse. + * @implements IListDocumentsResponse + * @constructor + * @param {google.firestore.v1.IListDocumentsResponse=} [properties] Properties to set + */ + function ListDocumentsResponse(properties) { + this.documents = []; + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } + + /** + * ListDocumentsResponse documents. + * @member {Array.} documents + * @memberof google.firestore.v1.ListDocumentsResponse + * @instance + */ + ListDocumentsResponse.prototype.documents = $util.emptyArray; + + /** + * ListDocumentsResponse nextPageToken. + * @member {string} nextPageToken + * @memberof google.firestore.v1.ListDocumentsResponse + * @instance + */ + ListDocumentsResponse.prototype.nextPageToken = ""; + + /** + * Creates a ListDocumentsResponse message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.firestore.v1.ListDocumentsResponse + * @static + * @param {Object.} object Plain object + * @returns {google.firestore.v1.ListDocumentsResponse} ListDocumentsResponse + */ + ListDocumentsResponse.fromObject = function fromObject(object) { + if (object instanceof $root.google.firestore.v1.ListDocumentsResponse) + return object; + var message = new $root.google.firestore.v1.ListDocumentsResponse(); + if (object.documents) { + if (!Array.isArray(object.documents)) + throw TypeError(".google.firestore.v1.ListDocumentsResponse.documents: array expected"); + message.documents = []; + for (var i = 0; i < object.documents.length; ++i) { + if (typeof object.documents[i] !== "object") + throw TypeError(".google.firestore.v1.ListDocumentsResponse.documents: object expected"); + message.documents[i] = $root.google.firestore.v1.Document.fromObject(object.documents[i]); + } + } + if (object.nextPageToken != null) + message.nextPageToken = String(object.nextPageToken); + return message; + }; + + /** + * Creates a plain object from a ListDocumentsResponse message. Also converts values to other types if specified. + * @function toObject + * @memberof google.firestore.v1.ListDocumentsResponse + * @static + * @param {google.firestore.v1.ListDocumentsResponse} message ListDocumentsResponse + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + ListDocumentsResponse.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.arrays || options.defaults) + object.documents = []; + if (options.defaults) + object.nextPageToken = ""; + if (message.documents && message.documents.length) { + object.documents = []; + for (var j = 0; j < message.documents.length; ++j) + object.documents[j] = $root.google.firestore.v1.Document.toObject(message.documents[j], options); + } + if (message.nextPageToken != null && message.hasOwnProperty("nextPageToken")) + object.nextPageToken = message.nextPageToken; + return object; + }; + + /** + * Converts this ListDocumentsResponse to JSON. + * @function toJSON + * @memberof google.firestore.v1.ListDocumentsResponse + * @instance + * @returns {Object.} JSON object + */ + ListDocumentsResponse.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + + /** + * Gets the default type url for ListDocumentsResponse + * @function getTypeUrl + * @memberof google.firestore.v1.ListDocumentsResponse + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + ListDocumentsResponse.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.firestore.v1.ListDocumentsResponse"; + }; + + return ListDocumentsResponse; })(); - FieldOptions.EditionDefault = (function() { + v1.CreateDocumentRequest = (function() { /** - * Properties of an EditionDefault. - * @memberof google.protobuf.FieldOptions - * @interface IEditionDefault - * @property {google.protobuf.Edition|null} [edition] EditionDefault edition - * @property {string|null} [value] EditionDefault value + * Properties of a CreateDocumentRequest. + * @memberof google.firestore.v1 + * @interface ICreateDocumentRequest + * @property {string|null} [parent] CreateDocumentRequest parent + * @property {string|null} [collectionId] CreateDocumentRequest collectionId + * @property {string|null} [documentId] CreateDocumentRequest documentId + * @property {google.firestore.v1.IDocument|null} [document] CreateDocumentRequest document + * @property {google.firestore.v1.IDocumentMask|null} [mask] CreateDocumentRequest mask */ /** - * Constructs a new EditionDefault. - * @memberof google.protobuf.FieldOptions - * @classdesc Represents an EditionDefault. - * @implements IEditionDefault + * Constructs a new CreateDocumentRequest. + * @memberof google.firestore.v1 + * @classdesc Represents a CreateDocumentRequest. + * @implements ICreateDocumentRequest * @constructor - * @param {google.protobuf.FieldOptions.IEditionDefault=} [properties] Properties to set + * @param {google.firestore.v1.ICreateDocumentRequest=} [properties] Properties to set */ - function EditionDefault(properties) { + function CreateDocumentRequest(properties) { if (properties) for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) if (properties[keys[i]] != null) @@ -5448,168 +4125,159 @@ } /** - * EditionDefault edition. - * @member {google.protobuf.Edition} edition - * @memberof google.protobuf.FieldOptions.EditionDefault + * CreateDocumentRequest parent. + * @member {string} parent + * @memberof google.firestore.v1.CreateDocumentRequest * @instance */ - EditionDefault.prototype.edition = 0; + CreateDocumentRequest.prototype.parent = ""; /** - * EditionDefault value. - * @member {string} value - * @memberof google.protobuf.FieldOptions.EditionDefault + * CreateDocumentRequest collectionId. + * @member {string} collectionId + * @memberof google.firestore.v1.CreateDocumentRequest * @instance */ - EditionDefault.prototype.value = ""; + CreateDocumentRequest.prototype.collectionId = ""; /** - * Creates an EditionDefault message from a plain object. Also converts values to their respective internal types. + * CreateDocumentRequest documentId. + * @member {string} documentId + * @memberof google.firestore.v1.CreateDocumentRequest + * @instance + */ + CreateDocumentRequest.prototype.documentId = ""; + + /** + * CreateDocumentRequest document. + * @member {google.firestore.v1.IDocument|null|undefined} document + * @memberof google.firestore.v1.CreateDocumentRequest + * @instance + */ + CreateDocumentRequest.prototype.document = null; + + /** + * CreateDocumentRequest mask. + * @member {google.firestore.v1.IDocumentMask|null|undefined} mask + * @memberof google.firestore.v1.CreateDocumentRequest + * @instance + */ + CreateDocumentRequest.prototype.mask = null; + + /** + * Creates a CreateDocumentRequest message from a plain object. Also converts values to their respective internal types. * @function fromObject - * @memberof google.protobuf.FieldOptions.EditionDefault + * @memberof google.firestore.v1.CreateDocumentRequest * @static * @param {Object.} object Plain object - * @returns {google.protobuf.FieldOptions.EditionDefault} EditionDefault + * @returns {google.firestore.v1.CreateDocumentRequest} CreateDocumentRequest */ - EditionDefault.fromObject = function fromObject(object) { - if (object instanceof $root.google.protobuf.FieldOptions.EditionDefault) + CreateDocumentRequest.fromObject = function fromObject(object) { + if (object instanceof $root.google.firestore.v1.CreateDocumentRequest) return object; - var message = new $root.google.protobuf.FieldOptions.EditionDefault(); - switch (object.edition) { - default: - if (typeof object.edition === "number") { - message.edition = object.edition; - break; - } - break; - case "EDITION_UNKNOWN": - case 0: - message.edition = 0; - break; - case "EDITION_LEGACY": - case 900: - message.edition = 900; - break; - case "EDITION_PROTO2": - case 998: - message.edition = 998; - break; - case "EDITION_PROTO3": - case 999: - message.edition = 999; - break; - case "EDITION_2023": - case 1000: - message.edition = 1000; - break; - case "EDITION_2024": - case 1001: - message.edition = 1001; - break; - case "EDITION_1_TEST_ONLY": - case 1: - message.edition = 1; - break; - case "EDITION_2_TEST_ONLY": - case 2: - message.edition = 2; - break; - case "EDITION_99997_TEST_ONLY": - case 99997: - message.edition = 99997; - break; - case "EDITION_99998_TEST_ONLY": - case 99998: - message.edition = 99998; - break; - case "EDITION_99999_TEST_ONLY": - case 99999: - message.edition = 99999; - break; - case "EDITION_MAX": - case 2147483647: - message.edition = 2147483647; - break; + var message = new $root.google.firestore.v1.CreateDocumentRequest(); + if (object.parent != null) + message.parent = String(object.parent); + if (object.collectionId != null) + message.collectionId = String(object.collectionId); + if (object.documentId != null) + message.documentId = String(object.documentId); + if (object.document != null) { + if (typeof object.document !== "object") + throw TypeError(".google.firestore.v1.CreateDocumentRequest.document: object expected"); + message.document = $root.google.firestore.v1.Document.fromObject(object.document); + } + if (object.mask != null) { + if (typeof object.mask !== "object") + throw TypeError(".google.firestore.v1.CreateDocumentRequest.mask: object expected"); + message.mask = $root.google.firestore.v1.DocumentMask.fromObject(object.mask); } - if (object.value != null) - message.value = String(object.value); return message; }; /** - * Creates a plain object from an EditionDefault message. Also converts values to other types if specified. + * Creates a plain object from a CreateDocumentRequest message. Also converts values to other types if specified. * @function toObject - * @memberof google.protobuf.FieldOptions.EditionDefault + * @memberof google.firestore.v1.CreateDocumentRequest * @static - * @param {google.protobuf.FieldOptions.EditionDefault} message EditionDefault + * @param {google.firestore.v1.CreateDocumentRequest} message CreateDocumentRequest * @param {$protobuf.IConversionOptions} [options] Conversion options * @returns {Object.} Plain object */ - EditionDefault.toObject = function toObject(message, options) { + CreateDocumentRequest.toObject = function toObject(message, options) { if (!options) options = {}; var object = {}; if (options.defaults) { - object.value = ""; - object.edition = options.enums === String ? "EDITION_UNKNOWN" : 0; + object.parent = ""; + object.collectionId = ""; + object.documentId = ""; + object.document = null; + object.mask = null; } - if (message.value != null && message.hasOwnProperty("value")) - object.value = message.value; - if (message.edition != null && message.hasOwnProperty("edition")) - object.edition = options.enums === String ? $root.google.protobuf.Edition[message.edition] === undefined ? message.edition : $root.google.protobuf.Edition[message.edition] : message.edition; + if (message.parent != null && message.hasOwnProperty("parent")) + object.parent = message.parent; + if (message.collectionId != null && message.hasOwnProperty("collectionId")) + object.collectionId = message.collectionId; + if (message.documentId != null && message.hasOwnProperty("documentId")) + object.documentId = message.documentId; + if (message.document != null && message.hasOwnProperty("document")) + object.document = $root.google.firestore.v1.Document.toObject(message.document, options); + if (message.mask != null && message.hasOwnProperty("mask")) + object.mask = $root.google.firestore.v1.DocumentMask.toObject(message.mask, options); return object; }; /** - * Converts this EditionDefault to JSON. + * Converts this CreateDocumentRequest to JSON. * @function toJSON - * @memberof google.protobuf.FieldOptions.EditionDefault + * @memberof google.firestore.v1.CreateDocumentRequest * @instance * @returns {Object.} JSON object */ - EditionDefault.prototype.toJSON = function toJSON() { + CreateDocumentRequest.prototype.toJSON = function toJSON() { return this.constructor.toObject(this, $protobuf.util.toJSONOptions); }; /** - * Gets the default type url for EditionDefault + * Gets the default type url for CreateDocumentRequest * @function getTypeUrl - * @memberof google.protobuf.FieldOptions.EditionDefault + * @memberof google.firestore.v1.CreateDocumentRequest * @static * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") * @returns {string} The default type url */ - EditionDefault.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + CreateDocumentRequest.getTypeUrl = function getTypeUrl(typeUrlPrefix) { if (typeUrlPrefix === undefined) { typeUrlPrefix = "type.googleapis.com"; } - return typeUrlPrefix + "/google.protobuf.FieldOptions.EditionDefault"; + return typeUrlPrefix + "/google.firestore.v1.CreateDocumentRequest"; }; - return EditionDefault; + return CreateDocumentRequest; })(); - FieldOptions.FeatureSupport = (function() { + v1.UpdateDocumentRequest = (function() { /** - * Properties of a FeatureSupport. - * @memberof google.protobuf.FieldOptions - * @interface IFeatureSupport - * @property {google.protobuf.Edition|null} [editionIntroduced] FeatureSupport editionIntroduced - * @property {google.protobuf.Edition|null} [editionDeprecated] FeatureSupport editionDeprecated - * @property {string|null} [deprecationWarning] FeatureSupport deprecationWarning - * @property {google.protobuf.Edition|null} [editionRemoved] FeatureSupport editionRemoved + * Properties of an UpdateDocumentRequest. + * @memberof google.firestore.v1 + * @interface IUpdateDocumentRequest + * @property {google.firestore.v1.IDocument|null} [document] UpdateDocumentRequest document + * @property {google.firestore.v1.IDocumentMask|null} [updateMask] UpdateDocumentRequest updateMask + * @property {google.firestore.v1.IDocumentMask|null} [mask] UpdateDocumentRequest mask + * @property {google.firestore.v1.IPrecondition|null} [currentDocument] UpdateDocumentRequest currentDocument */ /** - * Constructs a new FeatureSupport. - * @memberof google.protobuf.FieldOptions - * @classdesc Represents a FeatureSupport. - * @implements IFeatureSupport + * Constructs a new UpdateDocumentRequest. + * @memberof google.firestore.v1 + * @classdesc Represents an UpdateDocumentRequest. + * @implements IUpdateDocumentRequest * @constructor - * @param {google.protobuf.FieldOptions.IFeatureSupport=} [properties] Properties to set + * @param {google.firestore.v1.IUpdateDocumentRequest=} [properties] Properties to set */ - function FeatureSupport(properties) { + function UpdateDocumentRequest(properties) { if (properties) for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) if (properties[keys[i]] != null) @@ -5617,1423 +4285,1277 @@ } /** - * FeatureSupport editionIntroduced. - * @member {google.protobuf.Edition} editionIntroduced - * @memberof google.protobuf.FieldOptions.FeatureSupport + * UpdateDocumentRequest document. + * @member {google.firestore.v1.IDocument|null|undefined} document + * @memberof google.firestore.v1.UpdateDocumentRequest * @instance */ - FeatureSupport.prototype.editionIntroduced = 0; + UpdateDocumentRequest.prototype.document = null; /** - * FeatureSupport editionDeprecated. - * @member {google.protobuf.Edition} editionDeprecated - * @memberof google.protobuf.FieldOptions.FeatureSupport + * UpdateDocumentRequest updateMask. + * @member {google.firestore.v1.IDocumentMask|null|undefined} updateMask + * @memberof google.firestore.v1.UpdateDocumentRequest * @instance */ - FeatureSupport.prototype.editionDeprecated = 0; + UpdateDocumentRequest.prototype.updateMask = null; /** - * FeatureSupport deprecationWarning. - * @member {string} deprecationWarning - * @memberof google.protobuf.FieldOptions.FeatureSupport + * UpdateDocumentRequest mask. + * @member {google.firestore.v1.IDocumentMask|null|undefined} mask + * @memberof google.firestore.v1.UpdateDocumentRequest * @instance */ - FeatureSupport.prototype.deprecationWarning = ""; + UpdateDocumentRequest.prototype.mask = null; /** - * FeatureSupport editionRemoved. - * @member {google.protobuf.Edition} editionRemoved - * @memberof google.protobuf.FieldOptions.FeatureSupport + * UpdateDocumentRequest currentDocument. + * @member {google.firestore.v1.IPrecondition|null|undefined} currentDocument + * @memberof google.firestore.v1.UpdateDocumentRequest * @instance */ - FeatureSupport.prototype.editionRemoved = 0; + UpdateDocumentRequest.prototype.currentDocument = null; /** - * Creates a FeatureSupport message from a plain object. Also converts values to their respective internal types. + * Creates an UpdateDocumentRequest message from a plain object. Also converts values to their respective internal types. * @function fromObject - * @memberof google.protobuf.FieldOptions.FeatureSupport - * @static - * @param {Object.} object Plain object - * @returns {google.protobuf.FieldOptions.FeatureSupport} FeatureSupport - */ - FeatureSupport.fromObject = function fromObject(object) { - if (object instanceof $root.google.protobuf.FieldOptions.FeatureSupport) - return object; - var message = new $root.google.protobuf.FieldOptions.FeatureSupport(); - switch (object.editionIntroduced) { - default: - if (typeof object.editionIntroduced === "number") { - message.editionIntroduced = object.editionIntroduced; - break; - } - break; - case "EDITION_UNKNOWN": - case 0: - message.editionIntroduced = 0; - break; - case "EDITION_LEGACY": - case 900: - message.editionIntroduced = 900; - break; - case "EDITION_PROTO2": - case 998: - message.editionIntroduced = 998; - break; - case "EDITION_PROTO3": - case 999: - message.editionIntroduced = 999; - break; - case "EDITION_2023": - case 1000: - message.editionIntroduced = 1000; - break; - case "EDITION_2024": - case 1001: - message.editionIntroduced = 1001; - break; - case "EDITION_1_TEST_ONLY": - case 1: - message.editionIntroduced = 1; - break; - case "EDITION_2_TEST_ONLY": - case 2: - message.editionIntroduced = 2; - break; - case "EDITION_99997_TEST_ONLY": - case 99997: - message.editionIntroduced = 99997; - break; - case "EDITION_99998_TEST_ONLY": - case 99998: - message.editionIntroduced = 99998; - break; - case "EDITION_99999_TEST_ONLY": - case 99999: - message.editionIntroduced = 99999; - break; - case "EDITION_MAX": - case 2147483647: - message.editionIntroduced = 2147483647; - break; + * @memberof google.firestore.v1.UpdateDocumentRequest + * @static + * @param {Object.} object Plain object + * @returns {google.firestore.v1.UpdateDocumentRequest} UpdateDocumentRequest + */ + UpdateDocumentRequest.fromObject = function fromObject(object) { + if (object instanceof $root.google.firestore.v1.UpdateDocumentRequest) + return object; + var message = new $root.google.firestore.v1.UpdateDocumentRequest(); + if (object.document != null) { + if (typeof object.document !== "object") + throw TypeError(".google.firestore.v1.UpdateDocumentRequest.document: object expected"); + message.document = $root.google.firestore.v1.Document.fromObject(object.document); } - switch (object.editionDeprecated) { - default: - if (typeof object.editionDeprecated === "number") { - message.editionDeprecated = object.editionDeprecated; - break; - } - break; - case "EDITION_UNKNOWN": - case 0: - message.editionDeprecated = 0; - break; - case "EDITION_LEGACY": - case 900: - message.editionDeprecated = 900; - break; - case "EDITION_PROTO2": - case 998: - message.editionDeprecated = 998; - break; - case "EDITION_PROTO3": - case 999: - message.editionDeprecated = 999; - break; - case "EDITION_2023": - case 1000: - message.editionDeprecated = 1000; - break; - case "EDITION_2024": - case 1001: - message.editionDeprecated = 1001; - break; - case "EDITION_1_TEST_ONLY": - case 1: - message.editionDeprecated = 1; - break; - case "EDITION_2_TEST_ONLY": - case 2: - message.editionDeprecated = 2; - break; - case "EDITION_99997_TEST_ONLY": - case 99997: - message.editionDeprecated = 99997; - break; - case "EDITION_99998_TEST_ONLY": - case 99998: - message.editionDeprecated = 99998; - break; - case "EDITION_99999_TEST_ONLY": - case 99999: - message.editionDeprecated = 99999; - break; - case "EDITION_MAX": - case 2147483647: - message.editionDeprecated = 2147483647; - break; + if (object.updateMask != null) { + if (typeof object.updateMask !== "object") + throw TypeError(".google.firestore.v1.UpdateDocumentRequest.updateMask: object expected"); + message.updateMask = $root.google.firestore.v1.DocumentMask.fromObject(object.updateMask); } - if (object.deprecationWarning != null) - message.deprecationWarning = String(object.deprecationWarning); - switch (object.editionRemoved) { - default: - if (typeof object.editionRemoved === "number") { - message.editionRemoved = object.editionRemoved; - break; - } - break; - case "EDITION_UNKNOWN": - case 0: - message.editionRemoved = 0; - break; - case "EDITION_LEGACY": - case 900: - message.editionRemoved = 900; - break; - case "EDITION_PROTO2": - case 998: - message.editionRemoved = 998; - break; - case "EDITION_PROTO3": - case 999: - message.editionRemoved = 999; - break; - case "EDITION_2023": - case 1000: - message.editionRemoved = 1000; - break; - case "EDITION_2024": - case 1001: - message.editionRemoved = 1001; - break; - case "EDITION_1_TEST_ONLY": - case 1: - message.editionRemoved = 1; - break; - case "EDITION_2_TEST_ONLY": - case 2: - message.editionRemoved = 2; - break; - case "EDITION_99997_TEST_ONLY": - case 99997: - message.editionRemoved = 99997; - break; - case "EDITION_99998_TEST_ONLY": - case 99998: - message.editionRemoved = 99998; - break; - case "EDITION_99999_TEST_ONLY": - case 99999: - message.editionRemoved = 99999; - break; - case "EDITION_MAX": - case 2147483647: - message.editionRemoved = 2147483647; - break; + if (object.mask != null) { + if (typeof object.mask !== "object") + throw TypeError(".google.firestore.v1.UpdateDocumentRequest.mask: object expected"); + message.mask = $root.google.firestore.v1.DocumentMask.fromObject(object.mask); + } + if (object.currentDocument != null) { + if (typeof object.currentDocument !== "object") + throw TypeError(".google.firestore.v1.UpdateDocumentRequest.currentDocument: object expected"); + message.currentDocument = $root.google.firestore.v1.Precondition.fromObject(object.currentDocument); } return message; }; /** - * Creates a plain object from a FeatureSupport message. Also converts values to other types if specified. + * Creates a plain object from an UpdateDocumentRequest message. Also converts values to other types if specified. * @function toObject - * @memberof google.protobuf.FieldOptions.FeatureSupport + * @memberof google.firestore.v1.UpdateDocumentRequest * @static - * @param {google.protobuf.FieldOptions.FeatureSupport} message FeatureSupport + * @param {google.firestore.v1.UpdateDocumentRequest} message UpdateDocumentRequest * @param {$protobuf.IConversionOptions} [options] Conversion options * @returns {Object.} Plain object */ - FeatureSupport.toObject = function toObject(message, options) { + UpdateDocumentRequest.toObject = function toObject(message, options) { if (!options) options = {}; var object = {}; if (options.defaults) { - object.editionIntroduced = options.enums === String ? "EDITION_UNKNOWN" : 0; - object.editionDeprecated = options.enums === String ? "EDITION_UNKNOWN" : 0; - object.deprecationWarning = ""; - object.editionRemoved = options.enums === String ? "EDITION_UNKNOWN" : 0; - } - if (message.editionIntroduced != null && message.hasOwnProperty("editionIntroduced")) - object.editionIntroduced = options.enums === String ? $root.google.protobuf.Edition[message.editionIntroduced] === undefined ? message.editionIntroduced : $root.google.protobuf.Edition[message.editionIntroduced] : message.editionIntroduced; - if (message.editionDeprecated != null && message.hasOwnProperty("editionDeprecated")) - object.editionDeprecated = options.enums === String ? $root.google.protobuf.Edition[message.editionDeprecated] === undefined ? message.editionDeprecated : $root.google.protobuf.Edition[message.editionDeprecated] : message.editionDeprecated; - if (message.deprecationWarning != null && message.hasOwnProperty("deprecationWarning")) - object.deprecationWarning = message.deprecationWarning; - if (message.editionRemoved != null && message.hasOwnProperty("editionRemoved")) - object.editionRemoved = options.enums === String ? $root.google.protobuf.Edition[message.editionRemoved] === undefined ? message.editionRemoved : $root.google.protobuf.Edition[message.editionRemoved] : message.editionRemoved; + object.document = null; + object.updateMask = null; + object.mask = null; + object.currentDocument = null; + } + if (message.document != null && message.hasOwnProperty("document")) + object.document = $root.google.firestore.v1.Document.toObject(message.document, options); + if (message.updateMask != null && message.hasOwnProperty("updateMask")) + object.updateMask = $root.google.firestore.v1.DocumentMask.toObject(message.updateMask, options); + if (message.mask != null && message.hasOwnProperty("mask")) + object.mask = $root.google.firestore.v1.DocumentMask.toObject(message.mask, options); + if (message.currentDocument != null && message.hasOwnProperty("currentDocument")) + object.currentDocument = $root.google.firestore.v1.Precondition.toObject(message.currentDocument, options); return object; }; /** - * Converts this FeatureSupport to JSON. + * Converts this UpdateDocumentRequest to JSON. * @function toJSON - * @memberof google.protobuf.FieldOptions.FeatureSupport + * @memberof google.firestore.v1.UpdateDocumentRequest * @instance * @returns {Object.} JSON object */ - FeatureSupport.prototype.toJSON = function toJSON() { + UpdateDocumentRequest.prototype.toJSON = function toJSON() { return this.constructor.toObject(this, $protobuf.util.toJSONOptions); }; /** - * Gets the default type url for FeatureSupport + * Gets the default type url for UpdateDocumentRequest * @function getTypeUrl - * @memberof google.protobuf.FieldOptions.FeatureSupport + * @memberof google.firestore.v1.UpdateDocumentRequest * @static * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") * @returns {string} The default type url */ - FeatureSupport.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + UpdateDocumentRequest.getTypeUrl = function getTypeUrl(typeUrlPrefix) { if (typeUrlPrefix === undefined) { typeUrlPrefix = "type.googleapis.com"; } - return typeUrlPrefix + "/google.protobuf.FieldOptions.FeatureSupport"; - }; - - return FeatureSupport; - })(); - - return FieldOptions; - })(); - - protobuf.OneofOptions = (function() { - - /** - * Properties of an OneofOptions. - * @memberof google.protobuf - * @interface IOneofOptions - * @property {google.protobuf.IFeatureSet|null} [features] OneofOptions features - * @property {Array.|null} [uninterpretedOption] OneofOptions uninterpretedOption - */ - - /** - * Constructs a new OneofOptions. - * @memberof google.protobuf - * @classdesc Represents an OneofOptions. - * @implements IOneofOptions - * @constructor - * @param {google.protobuf.IOneofOptions=} [properties] Properties to set - */ - function OneofOptions(properties) { - this.uninterpretedOption = []; - if (properties) - for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) - if (properties[keys[i]] != null) - this[keys[i]] = properties[keys[i]]; - } - - /** - * OneofOptions features. - * @member {google.protobuf.IFeatureSet|null|undefined} features - * @memberof google.protobuf.OneofOptions - * @instance - */ - OneofOptions.prototype.features = null; - - /** - * OneofOptions uninterpretedOption. - * @member {Array.} uninterpretedOption - * @memberof google.protobuf.OneofOptions - * @instance - */ - OneofOptions.prototype.uninterpretedOption = $util.emptyArray; - - /** - * Creates an OneofOptions message from a plain object. Also converts values to their respective internal types. - * @function fromObject - * @memberof google.protobuf.OneofOptions - * @static - * @param {Object.} object Plain object - * @returns {google.protobuf.OneofOptions} OneofOptions - */ - OneofOptions.fromObject = function fromObject(object) { - if (object instanceof $root.google.protobuf.OneofOptions) - return object; - var message = new $root.google.protobuf.OneofOptions(); - if (object.features != null) { - if (typeof object.features !== "object") - throw TypeError(".google.protobuf.OneofOptions.features: object expected"); - message.features = $root.google.protobuf.FeatureSet.fromObject(object.features); - } - if (object.uninterpretedOption) { - if (!Array.isArray(object.uninterpretedOption)) - throw TypeError(".google.protobuf.OneofOptions.uninterpretedOption: array expected"); - message.uninterpretedOption = []; - for (var i = 0; i < object.uninterpretedOption.length; ++i) { - if (typeof object.uninterpretedOption[i] !== "object") - throw TypeError(".google.protobuf.OneofOptions.uninterpretedOption: object expected"); - message.uninterpretedOption[i] = $root.google.protobuf.UninterpretedOption.fromObject(object.uninterpretedOption[i]); - } - } - return message; - }; - - /** - * Creates a plain object from an OneofOptions message. Also converts values to other types if specified. - * @function toObject - * @memberof google.protobuf.OneofOptions - * @static - * @param {google.protobuf.OneofOptions} message OneofOptions - * @param {$protobuf.IConversionOptions} [options] Conversion options - * @returns {Object.} Plain object - */ - OneofOptions.toObject = function toObject(message, options) { - if (!options) - options = {}; - var object = {}; - if (options.arrays || options.defaults) - object.uninterpretedOption = []; - if (options.defaults) - object.features = null; - if (message.features != null && message.hasOwnProperty("features")) - object.features = $root.google.protobuf.FeatureSet.toObject(message.features, options); - if (message.uninterpretedOption && message.uninterpretedOption.length) { - object.uninterpretedOption = []; - for (var j = 0; j < message.uninterpretedOption.length; ++j) - object.uninterpretedOption[j] = $root.google.protobuf.UninterpretedOption.toObject(message.uninterpretedOption[j], options); - } - return object; - }; - - /** - * Converts this OneofOptions to JSON. - * @function toJSON - * @memberof google.protobuf.OneofOptions - * @instance - * @returns {Object.} JSON object - */ - OneofOptions.prototype.toJSON = function toJSON() { - return this.constructor.toObject(this, $protobuf.util.toJSONOptions); - }; - - /** - * Gets the default type url for OneofOptions - * @function getTypeUrl - * @memberof google.protobuf.OneofOptions - * @static - * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") - * @returns {string} The default type url - */ - OneofOptions.getTypeUrl = function getTypeUrl(typeUrlPrefix) { - if (typeUrlPrefix === undefined) { - typeUrlPrefix = "type.googleapis.com"; - } - return typeUrlPrefix + "/google.protobuf.OneofOptions"; - }; + return typeUrlPrefix + "/google.firestore.v1.UpdateDocumentRequest"; + }; - return OneofOptions; - })(); + return UpdateDocumentRequest; + })(); - protobuf.EnumOptions = (function() { + v1.DeleteDocumentRequest = (function() { - /** - * Properties of an EnumOptions. - * @memberof google.protobuf - * @interface IEnumOptions - * @property {boolean|null} [allowAlias] EnumOptions allowAlias - * @property {boolean|null} [deprecated] EnumOptions deprecated - * @property {boolean|null} [deprecatedLegacyJsonFieldConflicts] EnumOptions deprecatedLegacyJsonFieldConflicts - * @property {google.protobuf.IFeatureSet|null} [features] EnumOptions features - * @property {Array.|null} [uninterpretedOption] EnumOptions uninterpretedOption - */ + /** + * Properties of a DeleteDocumentRequest. + * @memberof google.firestore.v1 + * @interface IDeleteDocumentRequest + * @property {string|null} [name] DeleteDocumentRequest name + * @property {google.firestore.v1.IPrecondition|null} [currentDocument] DeleteDocumentRequest currentDocument + */ - /** - * Constructs a new EnumOptions. - * @memberof google.protobuf - * @classdesc Represents an EnumOptions. - * @implements IEnumOptions - * @constructor - * @param {google.protobuf.IEnumOptions=} [properties] Properties to set - */ - function EnumOptions(properties) { - this.uninterpretedOption = []; - if (properties) - for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) - if (properties[keys[i]] != null) - this[keys[i]] = properties[keys[i]]; - } + /** + * Constructs a new DeleteDocumentRequest. + * @memberof google.firestore.v1 + * @classdesc Represents a DeleteDocumentRequest. + * @implements IDeleteDocumentRequest + * @constructor + * @param {google.firestore.v1.IDeleteDocumentRequest=} [properties] Properties to set + */ + function DeleteDocumentRequest(properties) { + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } - /** - * EnumOptions allowAlias. - * @member {boolean} allowAlias - * @memberof google.protobuf.EnumOptions - * @instance - */ - EnumOptions.prototype.allowAlias = false; + /** + * DeleteDocumentRequest name. + * @member {string} name + * @memberof google.firestore.v1.DeleteDocumentRequest + * @instance + */ + DeleteDocumentRequest.prototype.name = ""; - /** - * EnumOptions deprecated. - * @member {boolean} deprecated - * @memberof google.protobuf.EnumOptions - * @instance - */ - EnumOptions.prototype.deprecated = false; + /** + * DeleteDocumentRequest currentDocument. + * @member {google.firestore.v1.IPrecondition|null|undefined} currentDocument + * @memberof google.firestore.v1.DeleteDocumentRequest + * @instance + */ + DeleteDocumentRequest.prototype.currentDocument = null; - /** - * EnumOptions deprecatedLegacyJsonFieldConflicts. - * @member {boolean} deprecatedLegacyJsonFieldConflicts - * @memberof google.protobuf.EnumOptions - * @instance - */ - EnumOptions.prototype.deprecatedLegacyJsonFieldConflicts = false; + /** + * Creates a DeleteDocumentRequest message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.firestore.v1.DeleteDocumentRequest + * @static + * @param {Object.} object Plain object + * @returns {google.firestore.v1.DeleteDocumentRequest} DeleteDocumentRequest + */ + DeleteDocumentRequest.fromObject = function fromObject(object) { + if (object instanceof $root.google.firestore.v1.DeleteDocumentRequest) + return object; + var message = new $root.google.firestore.v1.DeleteDocumentRequest(); + if (object.name != null) + message.name = String(object.name); + if (object.currentDocument != null) { + if (typeof object.currentDocument !== "object") + throw TypeError(".google.firestore.v1.DeleteDocumentRequest.currentDocument: object expected"); + message.currentDocument = $root.google.firestore.v1.Precondition.fromObject(object.currentDocument); + } + return message; + }; - /** - * EnumOptions features. - * @member {google.protobuf.IFeatureSet|null|undefined} features - * @memberof google.protobuf.EnumOptions - * @instance - */ - EnumOptions.prototype.features = null; + /** + * Creates a plain object from a DeleteDocumentRequest message. Also converts values to other types if specified. + * @function toObject + * @memberof google.firestore.v1.DeleteDocumentRequest + * @static + * @param {google.firestore.v1.DeleteDocumentRequest} message DeleteDocumentRequest + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + DeleteDocumentRequest.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.defaults) { + object.name = ""; + object.currentDocument = null; + } + if (message.name != null && message.hasOwnProperty("name")) + object.name = message.name; + if (message.currentDocument != null && message.hasOwnProperty("currentDocument")) + object.currentDocument = $root.google.firestore.v1.Precondition.toObject(message.currentDocument, options); + return object; + }; - /** - * EnumOptions uninterpretedOption. - * @member {Array.} uninterpretedOption - * @memberof google.protobuf.EnumOptions - * @instance - */ - EnumOptions.prototype.uninterpretedOption = $util.emptyArray; + /** + * Converts this DeleteDocumentRequest to JSON. + * @function toJSON + * @memberof google.firestore.v1.DeleteDocumentRequest + * @instance + * @returns {Object.} JSON object + */ + DeleteDocumentRequest.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; - /** - * Creates an EnumOptions message from a plain object. Also converts values to their respective internal types. - * @function fromObject - * @memberof google.protobuf.EnumOptions - * @static - * @param {Object.} object Plain object - * @returns {google.protobuf.EnumOptions} EnumOptions - */ - EnumOptions.fromObject = function fromObject(object) { - if (object instanceof $root.google.protobuf.EnumOptions) - return object; - var message = new $root.google.protobuf.EnumOptions(); - if (object.allowAlias != null) - message.allowAlias = Boolean(object.allowAlias); - if (object.deprecated != null) - message.deprecated = Boolean(object.deprecated); - if (object.deprecatedLegacyJsonFieldConflicts != null) - message.deprecatedLegacyJsonFieldConflicts = Boolean(object.deprecatedLegacyJsonFieldConflicts); - if (object.features != null) { - if (typeof object.features !== "object") - throw TypeError(".google.protobuf.EnumOptions.features: object expected"); - message.features = $root.google.protobuf.FeatureSet.fromObject(object.features); - } - if (object.uninterpretedOption) { - if (!Array.isArray(object.uninterpretedOption)) - throw TypeError(".google.protobuf.EnumOptions.uninterpretedOption: array expected"); - message.uninterpretedOption = []; - for (var i = 0; i < object.uninterpretedOption.length; ++i) { - if (typeof object.uninterpretedOption[i] !== "object") - throw TypeError(".google.protobuf.EnumOptions.uninterpretedOption: object expected"); - message.uninterpretedOption[i] = $root.google.protobuf.UninterpretedOption.fromObject(object.uninterpretedOption[i]); + /** + * Gets the default type url for DeleteDocumentRequest + * @function getTypeUrl + * @memberof google.firestore.v1.DeleteDocumentRequest + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + DeleteDocumentRequest.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; } - } - return message; - }; + return typeUrlPrefix + "/google.firestore.v1.DeleteDocumentRequest"; + }; - /** - * Creates a plain object from an EnumOptions message. Also converts values to other types if specified. - * @function toObject - * @memberof google.protobuf.EnumOptions - * @static - * @param {google.protobuf.EnumOptions} message EnumOptions - * @param {$protobuf.IConversionOptions} [options] Conversion options - * @returns {Object.} Plain object - */ - EnumOptions.toObject = function toObject(message, options) { - if (!options) - options = {}; - var object = {}; - if (options.arrays || options.defaults) - object.uninterpretedOption = []; - if (options.defaults) { - object.allowAlias = false; - object.deprecated = false; - object.deprecatedLegacyJsonFieldConflicts = false; - object.features = null; - } - if (message.allowAlias != null && message.hasOwnProperty("allowAlias")) - object.allowAlias = message.allowAlias; - if (message.deprecated != null && message.hasOwnProperty("deprecated")) - object.deprecated = message.deprecated; - if (message.deprecatedLegacyJsonFieldConflicts != null && message.hasOwnProperty("deprecatedLegacyJsonFieldConflicts")) - object.deprecatedLegacyJsonFieldConflicts = message.deprecatedLegacyJsonFieldConflicts; - if (message.features != null && message.hasOwnProperty("features")) - object.features = $root.google.protobuf.FeatureSet.toObject(message.features, options); - if (message.uninterpretedOption && message.uninterpretedOption.length) { - object.uninterpretedOption = []; - for (var j = 0; j < message.uninterpretedOption.length; ++j) - object.uninterpretedOption[j] = $root.google.protobuf.UninterpretedOption.toObject(message.uninterpretedOption[j], options); + return DeleteDocumentRequest; + })(); + + v1.BatchGetDocumentsRequest = (function() { + + /** + * Properties of a BatchGetDocumentsRequest. + * @memberof google.firestore.v1 + * @interface IBatchGetDocumentsRequest + * @property {string|null} [database] BatchGetDocumentsRequest database + * @property {Array.|null} [documents] BatchGetDocumentsRequest documents + * @property {google.firestore.v1.IDocumentMask|null} [mask] BatchGetDocumentsRequest mask + * @property {Uint8Array|null} [transaction] BatchGetDocumentsRequest transaction + * @property {google.firestore.v1.ITransactionOptions|null} [newTransaction] BatchGetDocumentsRequest newTransaction + * @property {google.protobuf.ITimestamp|null} [readTime] BatchGetDocumentsRequest readTime + */ + + /** + * Constructs a new BatchGetDocumentsRequest. + * @memberof google.firestore.v1 + * @classdesc Represents a BatchGetDocumentsRequest. + * @implements IBatchGetDocumentsRequest + * @constructor + * @param {google.firestore.v1.IBatchGetDocumentsRequest=} [properties] Properties to set + */ + function BatchGetDocumentsRequest(properties) { + this.documents = []; + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; } - return object; - }; - /** - * Converts this EnumOptions to JSON. - * @function toJSON - * @memberof google.protobuf.EnumOptions - * @instance - * @returns {Object.} JSON object - */ - EnumOptions.prototype.toJSON = function toJSON() { - return this.constructor.toObject(this, $protobuf.util.toJSONOptions); - }; + /** + * BatchGetDocumentsRequest database. + * @member {string} database + * @memberof google.firestore.v1.BatchGetDocumentsRequest + * @instance + */ + BatchGetDocumentsRequest.prototype.database = ""; - /** - * Gets the default type url for EnumOptions - * @function getTypeUrl - * @memberof google.protobuf.EnumOptions - * @static - * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") - * @returns {string} The default type url - */ - EnumOptions.getTypeUrl = function getTypeUrl(typeUrlPrefix) { - if (typeUrlPrefix === undefined) { - typeUrlPrefix = "type.googleapis.com"; - } - return typeUrlPrefix + "/google.protobuf.EnumOptions"; - }; + /** + * BatchGetDocumentsRequest documents. + * @member {Array.} documents + * @memberof google.firestore.v1.BatchGetDocumentsRequest + * @instance + */ + BatchGetDocumentsRequest.prototype.documents = $util.emptyArray; - return EnumOptions; - })(); + /** + * BatchGetDocumentsRequest mask. + * @member {google.firestore.v1.IDocumentMask|null|undefined} mask + * @memberof google.firestore.v1.BatchGetDocumentsRequest + * @instance + */ + BatchGetDocumentsRequest.prototype.mask = null; - protobuf.EnumValueOptions = (function() { + /** + * BatchGetDocumentsRequest transaction. + * @member {Uint8Array|null|undefined} transaction + * @memberof google.firestore.v1.BatchGetDocumentsRequest + * @instance + */ + BatchGetDocumentsRequest.prototype.transaction = null; - /** - * Properties of an EnumValueOptions. - * @memberof google.protobuf - * @interface IEnumValueOptions - * @property {boolean|null} [deprecated] EnumValueOptions deprecated - * @property {google.protobuf.IFeatureSet|null} [features] EnumValueOptions features - * @property {boolean|null} [debugRedact] EnumValueOptions debugRedact - * @property {Array.|null} [uninterpretedOption] EnumValueOptions uninterpretedOption - */ + /** + * BatchGetDocumentsRequest newTransaction. + * @member {google.firestore.v1.ITransactionOptions|null|undefined} newTransaction + * @memberof google.firestore.v1.BatchGetDocumentsRequest + * @instance + */ + BatchGetDocumentsRequest.prototype.newTransaction = null; - /** - * Constructs a new EnumValueOptions. - * @memberof google.protobuf - * @classdesc Represents an EnumValueOptions. - * @implements IEnumValueOptions - * @constructor - * @param {google.protobuf.IEnumValueOptions=} [properties] Properties to set - */ - function EnumValueOptions(properties) { - this.uninterpretedOption = []; - if (properties) - for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) - if (properties[keys[i]] != null) - this[keys[i]] = properties[keys[i]]; - } + /** + * BatchGetDocumentsRequest readTime. + * @member {google.protobuf.ITimestamp|null|undefined} readTime + * @memberof google.firestore.v1.BatchGetDocumentsRequest + * @instance + */ + BatchGetDocumentsRequest.prototype.readTime = null; - /** - * EnumValueOptions deprecated. - * @member {boolean} deprecated - * @memberof google.protobuf.EnumValueOptions - * @instance - */ - EnumValueOptions.prototype.deprecated = false; + // OneOf field names bound to virtual getters and setters + var $oneOfFields; - /** - * EnumValueOptions features. - * @member {google.protobuf.IFeatureSet|null|undefined} features - * @memberof google.protobuf.EnumValueOptions - * @instance - */ - EnumValueOptions.prototype.features = null; + /** + * BatchGetDocumentsRequest consistencySelector. + * @member {"transaction"|"newTransaction"|"readTime"|undefined} consistencySelector + * @memberof google.firestore.v1.BatchGetDocumentsRequest + * @instance + */ + Object.defineProperty(BatchGetDocumentsRequest.prototype, "consistencySelector", { + get: $util.oneOfGetter($oneOfFields = ["transaction", "newTransaction", "readTime"]), + set: $util.oneOfSetter($oneOfFields) + }); - /** - * EnumValueOptions debugRedact. - * @member {boolean} debugRedact - * @memberof google.protobuf.EnumValueOptions - * @instance - */ - EnumValueOptions.prototype.debugRedact = false; + /** + * Creates a BatchGetDocumentsRequest message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.firestore.v1.BatchGetDocumentsRequest + * @static + * @param {Object.} object Plain object + * @returns {google.firestore.v1.BatchGetDocumentsRequest} BatchGetDocumentsRequest + */ + BatchGetDocumentsRequest.fromObject = function fromObject(object) { + if (object instanceof $root.google.firestore.v1.BatchGetDocumentsRequest) + return object; + var message = new $root.google.firestore.v1.BatchGetDocumentsRequest(); + if (object.database != null) + message.database = String(object.database); + if (object.documents) { + if (!Array.isArray(object.documents)) + throw TypeError(".google.firestore.v1.BatchGetDocumentsRequest.documents: array expected"); + message.documents = []; + for (var i = 0; i < object.documents.length; ++i) + message.documents[i] = String(object.documents[i]); + } + if (object.mask != null) { + if (typeof object.mask !== "object") + throw TypeError(".google.firestore.v1.BatchGetDocumentsRequest.mask: object expected"); + message.mask = $root.google.firestore.v1.DocumentMask.fromObject(object.mask); + } + if (object.transaction != null) + if (typeof object.transaction === "string") + $util.base64.decode(object.transaction, message.transaction = $util.newBuffer($util.base64.length(object.transaction)), 0); + else if (object.transaction.length >= 0) + message.transaction = object.transaction; + if (object.newTransaction != null) { + if (typeof object.newTransaction !== "object") + throw TypeError(".google.firestore.v1.BatchGetDocumentsRequest.newTransaction: object expected"); + message.newTransaction = $root.google.firestore.v1.TransactionOptions.fromObject(object.newTransaction); + } + if (object.readTime != null) { + if (typeof object.readTime !== "object") + throw TypeError(".google.firestore.v1.BatchGetDocumentsRequest.readTime: object expected"); + message.readTime = $root.google.protobuf.Timestamp.fromObject(object.readTime); + } + return message; + }; + + /** + * Creates a plain object from a BatchGetDocumentsRequest message. Also converts values to other types if specified. + * @function toObject + * @memberof google.firestore.v1.BatchGetDocumentsRequest + * @static + * @param {google.firestore.v1.BatchGetDocumentsRequest} message BatchGetDocumentsRequest + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + BatchGetDocumentsRequest.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.arrays || options.defaults) + object.documents = []; + if (options.defaults) { + object.database = ""; + object.mask = null; + } + if (message.database != null && message.hasOwnProperty("database")) + object.database = message.database; + if (message.documents && message.documents.length) { + object.documents = []; + for (var j = 0; j < message.documents.length; ++j) + object.documents[j] = message.documents[j]; + } + if (message.mask != null && message.hasOwnProperty("mask")) + object.mask = $root.google.firestore.v1.DocumentMask.toObject(message.mask, options); + if (message.transaction != null && message.hasOwnProperty("transaction")) { + object.transaction = options.bytes === String ? $util.base64.encode(message.transaction, 0, message.transaction.length) : options.bytes === Array ? Array.prototype.slice.call(message.transaction) : message.transaction; + if (options.oneofs) + object.consistencySelector = "transaction"; + } + if (message.newTransaction != null && message.hasOwnProperty("newTransaction")) { + object.newTransaction = $root.google.firestore.v1.TransactionOptions.toObject(message.newTransaction, options); + if (options.oneofs) + object.consistencySelector = "newTransaction"; + } + if (message.readTime != null && message.hasOwnProperty("readTime")) { + object.readTime = $root.google.protobuf.Timestamp.toObject(message.readTime, options); + if (options.oneofs) + object.consistencySelector = "readTime"; + } + return object; + }; + + /** + * Converts this BatchGetDocumentsRequest to JSON. + * @function toJSON + * @memberof google.firestore.v1.BatchGetDocumentsRequest + * @instance + * @returns {Object.} JSON object + */ + BatchGetDocumentsRequest.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + + /** + * Gets the default type url for BatchGetDocumentsRequest + * @function getTypeUrl + * @memberof google.firestore.v1.BatchGetDocumentsRequest + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + BatchGetDocumentsRequest.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.firestore.v1.BatchGetDocumentsRequest"; + }; + + return BatchGetDocumentsRequest; + })(); - /** - * EnumValueOptions uninterpretedOption. - * @member {Array.} uninterpretedOption - * @memberof google.protobuf.EnumValueOptions - * @instance - */ - EnumValueOptions.prototype.uninterpretedOption = $util.emptyArray; + v1.BatchGetDocumentsResponse = (function() { - /** - * Creates an EnumValueOptions message from a plain object. Also converts values to their respective internal types. - * @function fromObject - * @memberof google.protobuf.EnumValueOptions - * @static - * @param {Object.} object Plain object - * @returns {google.protobuf.EnumValueOptions} EnumValueOptions - */ - EnumValueOptions.fromObject = function fromObject(object) { - if (object instanceof $root.google.protobuf.EnumValueOptions) - return object; - var message = new $root.google.protobuf.EnumValueOptions(); - if (object.deprecated != null) - message.deprecated = Boolean(object.deprecated); - if (object.features != null) { - if (typeof object.features !== "object") - throw TypeError(".google.protobuf.EnumValueOptions.features: object expected"); - message.features = $root.google.protobuf.FeatureSet.fromObject(object.features); - } - if (object.debugRedact != null) - message.debugRedact = Boolean(object.debugRedact); - if (object.uninterpretedOption) { - if (!Array.isArray(object.uninterpretedOption)) - throw TypeError(".google.protobuf.EnumValueOptions.uninterpretedOption: array expected"); - message.uninterpretedOption = []; - for (var i = 0; i < object.uninterpretedOption.length; ++i) { - if (typeof object.uninterpretedOption[i] !== "object") - throw TypeError(".google.protobuf.EnumValueOptions.uninterpretedOption: object expected"); - message.uninterpretedOption[i] = $root.google.protobuf.UninterpretedOption.fromObject(object.uninterpretedOption[i]); - } - } - return message; - }; + /** + * Properties of a BatchGetDocumentsResponse. + * @memberof google.firestore.v1 + * @interface IBatchGetDocumentsResponse + * @property {google.firestore.v1.IDocument|null} [found] BatchGetDocumentsResponse found + * @property {string|null} [missing] BatchGetDocumentsResponse missing + * @property {Uint8Array|null} [transaction] BatchGetDocumentsResponse transaction + * @property {google.protobuf.ITimestamp|null} [readTime] BatchGetDocumentsResponse readTime + */ - /** - * Creates a plain object from an EnumValueOptions message. Also converts values to other types if specified. - * @function toObject - * @memberof google.protobuf.EnumValueOptions - * @static - * @param {google.protobuf.EnumValueOptions} message EnumValueOptions - * @param {$protobuf.IConversionOptions} [options] Conversion options - * @returns {Object.} Plain object - */ - EnumValueOptions.toObject = function toObject(message, options) { - if (!options) - options = {}; - var object = {}; - if (options.arrays || options.defaults) - object.uninterpretedOption = []; - if (options.defaults) { - object.deprecated = false; - object.features = null; - object.debugRedact = false; - } - if (message.deprecated != null && message.hasOwnProperty("deprecated")) - object.deprecated = message.deprecated; - if (message.features != null && message.hasOwnProperty("features")) - object.features = $root.google.protobuf.FeatureSet.toObject(message.features, options); - if (message.debugRedact != null && message.hasOwnProperty("debugRedact")) - object.debugRedact = message.debugRedact; - if (message.uninterpretedOption && message.uninterpretedOption.length) { - object.uninterpretedOption = []; - for (var j = 0; j < message.uninterpretedOption.length; ++j) - object.uninterpretedOption[j] = $root.google.protobuf.UninterpretedOption.toObject(message.uninterpretedOption[j], options); + /** + * Constructs a new BatchGetDocumentsResponse. + * @memberof google.firestore.v1 + * @classdesc Represents a BatchGetDocumentsResponse. + * @implements IBatchGetDocumentsResponse + * @constructor + * @param {google.firestore.v1.IBatchGetDocumentsResponse=} [properties] Properties to set + */ + function BatchGetDocumentsResponse(properties) { + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; } - return object; - }; - /** - * Converts this EnumValueOptions to JSON. - * @function toJSON - * @memberof google.protobuf.EnumValueOptions - * @instance - * @returns {Object.} JSON object - */ - EnumValueOptions.prototype.toJSON = function toJSON() { - return this.constructor.toObject(this, $protobuf.util.toJSONOptions); - }; + /** + * BatchGetDocumentsResponse found. + * @member {google.firestore.v1.IDocument|null|undefined} found + * @memberof google.firestore.v1.BatchGetDocumentsResponse + * @instance + */ + BatchGetDocumentsResponse.prototype.found = null; - /** - * Gets the default type url for EnumValueOptions - * @function getTypeUrl - * @memberof google.protobuf.EnumValueOptions - * @static - * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") - * @returns {string} The default type url - */ - EnumValueOptions.getTypeUrl = function getTypeUrl(typeUrlPrefix) { - if (typeUrlPrefix === undefined) { - typeUrlPrefix = "type.googleapis.com"; - } - return typeUrlPrefix + "/google.protobuf.EnumValueOptions"; - }; + /** + * BatchGetDocumentsResponse missing. + * @member {string|null|undefined} missing + * @memberof google.firestore.v1.BatchGetDocumentsResponse + * @instance + */ + BatchGetDocumentsResponse.prototype.missing = null; - return EnumValueOptions; - })(); + /** + * BatchGetDocumentsResponse transaction. + * @member {Uint8Array} transaction + * @memberof google.firestore.v1.BatchGetDocumentsResponse + * @instance + */ + BatchGetDocumentsResponse.prototype.transaction = $util.newBuffer([]); - protobuf.ServiceOptions = (function() { + /** + * BatchGetDocumentsResponse readTime. + * @member {google.protobuf.ITimestamp|null|undefined} readTime + * @memberof google.firestore.v1.BatchGetDocumentsResponse + * @instance + */ + BatchGetDocumentsResponse.prototype.readTime = null; - /** - * Properties of a ServiceOptions. - * @memberof google.protobuf - * @interface IServiceOptions - * @property {google.protobuf.IFeatureSet|null} [features] ServiceOptions features - * @property {boolean|null} [deprecated] ServiceOptions deprecated - * @property {Array.|null} [uninterpretedOption] ServiceOptions uninterpretedOption - * @property {string|null} [".google.api.defaultHost"] ServiceOptions .google.api.defaultHost - * @property {string|null} [".google.api.oauthScopes"] ServiceOptions .google.api.oauthScopes - * @property {string|null} [".google.api.apiVersion"] ServiceOptions .google.api.apiVersion - */ + // OneOf field names bound to virtual getters and setters + var $oneOfFields; - /** - * Constructs a new ServiceOptions. - * @memberof google.protobuf - * @classdesc Represents a ServiceOptions. - * @implements IServiceOptions - * @constructor - * @param {google.protobuf.IServiceOptions=} [properties] Properties to set - */ - function ServiceOptions(properties) { - this.uninterpretedOption = []; - if (properties) - for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) - if (properties[keys[i]] != null) - this[keys[i]] = properties[keys[i]]; - } + /** + * BatchGetDocumentsResponse result. + * @member {"found"|"missing"|undefined} result + * @memberof google.firestore.v1.BatchGetDocumentsResponse + * @instance + */ + Object.defineProperty(BatchGetDocumentsResponse.prototype, "result", { + get: $util.oneOfGetter($oneOfFields = ["found", "missing"]), + set: $util.oneOfSetter($oneOfFields) + }); - /** - * ServiceOptions features. - * @member {google.protobuf.IFeatureSet|null|undefined} features - * @memberof google.protobuf.ServiceOptions - * @instance - */ - ServiceOptions.prototype.features = null; + /** + * Creates a BatchGetDocumentsResponse message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.firestore.v1.BatchGetDocumentsResponse + * @static + * @param {Object.} object Plain object + * @returns {google.firestore.v1.BatchGetDocumentsResponse} BatchGetDocumentsResponse + */ + BatchGetDocumentsResponse.fromObject = function fromObject(object) { + if (object instanceof $root.google.firestore.v1.BatchGetDocumentsResponse) + return object; + var message = new $root.google.firestore.v1.BatchGetDocumentsResponse(); + if (object.found != null) { + if (typeof object.found !== "object") + throw TypeError(".google.firestore.v1.BatchGetDocumentsResponse.found: object expected"); + message.found = $root.google.firestore.v1.Document.fromObject(object.found); + } + if (object.missing != null) + message.missing = String(object.missing); + if (object.transaction != null) + if (typeof object.transaction === "string") + $util.base64.decode(object.transaction, message.transaction = $util.newBuffer($util.base64.length(object.transaction)), 0); + else if (object.transaction.length >= 0) + message.transaction = object.transaction; + if (object.readTime != null) { + if (typeof object.readTime !== "object") + throw TypeError(".google.firestore.v1.BatchGetDocumentsResponse.readTime: object expected"); + message.readTime = $root.google.protobuf.Timestamp.fromObject(object.readTime); + } + return message; + }; - /** - * ServiceOptions deprecated. - * @member {boolean} deprecated - * @memberof google.protobuf.ServiceOptions - * @instance - */ - ServiceOptions.prototype.deprecated = false; + /** + * Creates a plain object from a BatchGetDocumentsResponse message. Also converts values to other types if specified. + * @function toObject + * @memberof google.firestore.v1.BatchGetDocumentsResponse + * @static + * @param {google.firestore.v1.BatchGetDocumentsResponse} message BatchGetDocumentsResponse + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + BatchGetDocumentsResponse.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.defaults) { + if (options.bytes === String) + object.transaction = ""; + else { + object.transaction = []; + if (options.bytes !== Array) + object.transaction = $util.newBuffer(object.transaction); + } + object.readTime = null; + } + if (message.found != null && message.hasOwnProperty("found")) { + object.found = $root.google.firestore.v1.Document.toObject(message.found, options); + if (options.oneofs) + object.result = "found"; + } + if (message.missing != null && message.hasOwnProperty("missing")) { + object.missing = message.missing; + if (options.oneofs) + object.result = "missing"; + } + if (message.transaction != null && message.hasOwnProperty("transaction")) + object.transaction = options.bytes === String ? $util.base64.encode(message.transaction, 0, message.transaction.length) : options.bytes === Array ? Array.prototype.slice.call(message.transaction) : message.transaction; + if (message.readTime != null && message.hasOwnProperty("readTime")) + object.readTime = $root.google.protobuf.Timestamp.toObject(message.readTime, options); + return object; + }; - /** - * ServiceOptions uninterpretedOption. - * @member {Array.} uninterpretedOption - * @memberof google.protobuf.ServiceOptions - * @instance - */ - ServiceOptions.prototype.uninterpretedOption = $util.emptyArray; + /** + * Converts this BatchGetDocumentsResponse to JSON. + * @function toJSON + * @memberof google.firestore.v1.BatchGetDocumentsResponse + * @instance + * @returns {Object.} JSON object + */ + BatchGetDocumentsResponse.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; - /** - * ServiceOptions .google.api.defaultHost. - * @member {string} .google.api.defaultHost - * @memberof google.protobuf.ServiceOptions - * @instance - */ - ServiceOptions.prototype[".google.api.defaultHost"] = ""; + /** + * Gets the default type url for BatchGetDocumentsResponse + * @function getTypeUrl + * @memberof google.firestore.v1.BatchGetDocumentsResponse + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + BatchGetDocumentsResponse.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.firestore.v1.BatchGetDocumentsResponse"; + }; - /** - * ServiceOptions .google.api.oauthScopes. - * @member {string} .google.api.oauthScopes - * @memberof google.protobuf.ServiceOptions - * @instance - */ - ServiceOptions.prototype[".google.api.oauthScopes"] = ""; + return BatchGetDocumentsResponse; + })(); - /** - * ServiceOptions .google.api.apiVersion. - * @member {string} .google.api.apiVersion - * @memberof google.protobuf.ServiceOptions - * @instance - */ - ServiceOptions.prototype[".google.api.apiVersion"] = ""; + v1.BeginTransactionRequest = (function() { - /** - * Creates a ServiceOptions message from a plain object. Also converts values to their respective internal types. - * @function fromObject - * @memberof google.protobuf.ServiceOptions - * @static - * @param {Object.} object Plain object - * @returns {google.protobuf.ServiceOptions} ServiceOptions - */ - ServiceOptions.fromObject = function fromObject(object) { - if (object instanceof $root.google.protobuf.ServiceOptions) - return object; - var message = new $root.google.protobuf.ServiceOptions(); - if (object.features != null) { - if (typeof object.features !== "object") - throw TypeError(".google.protobuf.ServiceOptions.features: object expected"); - message.features = $root.google.protobuf.FeatureSet.fromObject(object.features); - } - if (object.deprecated != null) - message.deprecated = Boolean(object.deprecated); - if (object.uninterpretedOption) { - if (!Array.isArray(object.uninterpretedOption)) - throw TypeError(".google.protobuf.ServiceOptions.uninterpretedOption: array expected"); - message.uninterpretedOption = []; - for (var i = 0; i < object.uninterpretedOption.length; ++i) { - if (typeof object.uninterpretedOption[i] !== "object") - throw TypeError(".google.protobuf.ServiceOptions.uninterpretedOption: object expected"); - message.uninterpretedOption[i] = $root.google.protobuf.UninterpretedOption.fromObject(object.uninterpretedOption[i]); - } - } - if (object[".google.api.defaultHost"] != null) - message[".google.api.defaultHost"] = String(object[".google.api.defaultHost"]); - if (object[".google.api.oauthScopes"] != null) - message[".google.api.oauthScopes"] = String(object[".google.api.oauthScopes"]); - if (object[".google.api.apiVersion"] != null) - message[".google.api.apiVersion"] = String(object[".google.api.apiVersion"]); - return message; - }; + /** + * Properties of a BeginTransactionRequest. + * @memberof google.firestore.v1 + * @interface IBeginTransactionRequest + * @property {string|null} [database] BeginTransactionRequest database + * @property {google.firestore.v1.ITransactionOptions|null} [options] BeginTransactionRequest options + */ - /** - * Creates a plain object from a ServiceOptions message. Also converts values to other types if specified. - * @function toObject - * @memberof google.protobuf.ServiceOptions - * @static - * @param {google.protobuf.ServiceOptions} message ServiceOptions - * @param {$protobuf.IConversionOptions} [options] Conversion options - * @returns {Object.} Plain object - */ - ServiceOptions.toObject = function toObject(message, options) { - if (!options) - options = {}; - var object = {}; - if (options.arrays || options.defaults) - object.uninterpretedOption = []; - if (options.defaults) { - object.deprecated = false; - object.features = null; - object[".google.api.defaultHost"] = ""; - object[".google.api.oauthScopes"] = ""; - object[".google.api.apiVersion"] = ""; - } - if (message.deprecated != null && message.hasOwnProperty("deprecated")) - object.deprecated = message.deprecated; - if (message.features != null && message.hasOwnProperty("features")) - object.features = $root.google.protobuf.FeatureSet.toObject(message.features, options); - if (message.uninterpretedOption && message.uninterpretedOption.length) { - object.uninterpretedOption = []; - for (var j = 0; j < message.uninterpretedOption.length; ++j) - object.uninterpretedOption[j] = $root.google.protobuf.UninterpretedOption.toObject(message.uninterpretedOption[j], options); + /** + * Constructs a new BeginTransactionRequest. + * @memberof google.firestore.v1 + * @classdesc Represents a BeginTransactionRequest. + * @implements IBeginTransactionRequest + * @constructor + * @param {google.firestore.v1.IBeginTransactionRequest=} [properties] Properties to set + */ + function BeginTransactionRequest(properties) { + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; } - if (message[".google.api.defaultHost"] != null && message.hasOwnProperty(".google.api.defaultHost")) - object[".google.api.defaultHost"] = message[".google.api.defaultHost"]; - if (message[".google.api.oauthScopes"] != null && message.hasOwnProperty(".google.api.oauthScopes")) - object[".google.api.oauthScopes"] = message[".google.api.oauthScopes"]; - if (message[".google.api.apiVersion"] != null && message.hasOwnProperty(".google.api.apiVersion")) - object[".google.api.apiVersion"] = message[".google.api.apiVersion"]; - return object; - }; - - /** - * Converts this ServiceOptions to JSON. - * @function toJSON - * @memberof google.protobuf.ServiceOptions - * @instance - * @returns {Object.} JSON object - */ - ServiceOptions.prototype.toJSON = function toJSON() { - return this.constructor.toObject(this, $protobuf.util.toJSONOptions); - }; - /** - * Gets the default type url for ServiceOptions - * @function getTypeUrl - * @memberof google.protobuf.ServiceOptions - * @static - * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") - * @returns {string} The default type url - */ - ServiceOptions.getTypeUrl = function getTypeUrl(typeUrlPrefix) { - if (typeUrlPrefix === undefined) { - typeUrlPrefix = "type.googleapis.com"; - } - return typeUrlPrefix + "/google.protobuf.ServiceOptions"; - }; + /** + * BeginTransactionRequest database. + * @member {string} database + * @memberof google.firestore.v1.BeginTransactionRequest + * @instance + */ + BeginTransactionRequest.prototype.database = ""; - return ServiceOptions; - })(); + /** + * BeginTransactionRequest options. + * @member {google.firestore.v1.ITransactionOptions|null|undefined} options + * @memberof google.firestore.v1.BeginTransactionRequest + * @instance + */ + BeginTransactionRequest.prototype.options = null; - protobuf.MethodOptions = (function() { + /** + * Creates a BeginTransactionRequest message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.firestore.v1.BeginTransactionRequest + * @static + * @param {Object.} object Plain object + * @returns {google.firestore.v1.BeginTransactionRequest} BeginTransactionRequest + */ + BeginTransactionRequest.fromObject = function fromObject(object) { + if (object instanceof $root.google.firestore.v1.BeginTransactionRequest) + return object; + var message = new $root.google.firestore.v1.BeginTransactionRequest(); + if (object.database != null) + message.database = String(object.database); + if (object.options != null) { + if (typeof object.options !== "object") + throw TypeError(".google.firestore.v1.BeginTransactionRequest.options: object expected"); + message.options = $root.google.firestore.v1.TransactionOptions.fromObject(object.options); + } + return message; + }; - /** - * Properties of a MethodOptions. - * @memberof google.protobuf - * @interface IMethodOptions - * @property {boolean|null} [deprecated] MethodOptions deprecated - * @property {google.protobuf.MethodOptions.IdempotencyLevel|null} [idempotencyLevel] MethodOptions idempotencyLevel - * @property {google.protobuf.IFeatureSet|null} [features] MethodOptions features - * @property {Array.|null} [uninterpretedOption] MethodOptions uninterpretedOption - * @property {google.api.IHttpRule|null} [".google.api.http"] MethodOptions .google.api.http - * @property {Array.|null} [".google.api.methodSignature"] MethodOptions .google.api.methodSignature - * @property {google.longrunning.IOperationInfo|null} [".google.longrunning.operationInfo"] MethodOptions .google.longrunning.operationInfo - */ + /** + * Creates a plain object from a BeginTransactionRequest message. Also converts values to other types if specified. + * @function toObject + * @memberof google.firestore.v1.BeginTransactionRequest + * @static + * @param {google.firestore.v1.BeginTransactionRequest} message BeginTransactionRequest + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + BeginTransactionRequest.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.defaults) { + object.database = ""; + object.options = null; + } + if (message.database != null && message.hasOwnProperty("database")) + object.database = message.database; + if (message.options != null && message.hasOwnProperty("options")) + object.options = $root.google.firestore.v1.TransactionOptions.toObject(message.options, options); + return object; + }; - /** - * Constructs a new MethodOptions. - * @memberof google.protobuf - * @classdesc Represents a MethodOptions. - * @implements IMethodOptions - * @constructor - * @param {google.protobuf.IMethodOptions=} [properties] Properties to set - */ - function MethodOptions(properties) { - this.uninterpretedOption = []; - this[".google.api.methodSignature"] = []; - if (properties) - for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) - if (properties[keys[i]] != null) - this[keys[i]] = properties[keys[i]]; - } + /** + * Converts this BeginTransactionRequest to JSON. + * @function toJSON + * @memberof google.firestore.v1.BeginTransactionRequest + * @instance + * @returns {Object.} JSON object + */ + BeginTransactionRequest.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; - /** - * MethodOptions deprecated. - * @member {boolean} deprecated - * @memberof google.protobuf.MethodOptions - * @instance - */ - MethodOptions.prototype.deprecated = false; + /** + * Gets the default type url for BeginTransactionRequest + * @function getTypeUrl + * @memberof google.firestore.v1.BeginTransactionRequest + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + BeginTransactionRequest.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.firestore.v1.BeginTransactionRequest"; + }; - /** - * MethodOptions idempotencyLevel. - * @member {google.protobuf.MethodOptions.IdempotencyLevel} idempotencyLevel - * @memberof google.protobuf.MethodOptions - * @instance - */ - MethodOptions.prototype.idempotencyLevel = 0; + return BeginTransactionRequest; + })(); - /** - * MethodOptions features. - * @member {google.protobuf.IFeatureSet|null|undefined} features - * @memberof google.protobuf.MethodOptions - * @instance - */ - MethodOptions.prototype.features = null; + v1.BeginTransactionResponse = (function() { - /** - * MethodOptions uninterpretedOption. - * @member {Array.} uninterpretedOption - * @memberof google.protobuf.MethodOptions - * @instance - */ - MethodOptions.prototype.uninterpretedOption = $util.emptyArray; + /** + * Properties of a BeginTransactionResponse. + * @memberof google.firestore.v1 + * @interface IBeginTransactionResponse + * @property {Uint8Array|null} [transaction] BeginTransactionResponse transaction + */ - /** - * MethodOptions .google.api.http. - * @member {google.api.IHttpRule|null|undefined} .google.api.http - * @memberof google.protobuf.MethodOptions - * @instance - */ - MethodOptions.prototype[".google.api.http"] = null; + /** + * Constructs a new BeginTransactionResponse. + * @memberof google.firestore.v1 + * @classdesc Represents a BeginTransactionResponse. + * @implements IBeginTransactionResponse + * @constructor + * @param {google.firestore.v1.IBeginTransactionResponse=} [properties] Properties to set + */ + function BeginTransactionResponse(properties) { + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } - /** - * MethodOptions .google.api.methodSignature. - * @member {Array.} .google.api.methodSignature - * @memberof google.protobuf.MethodOptions - * @instance - */ - MethodOptions.prototype[".google.api.methodSignature"] = $util.emptyArray; + /** + * BeginTransactionResponse transaction. + * @member {Uint8Array} transaction + * @memberof google.firestore.v1.BeginTransactionResponse + * @instance + */ + BeginTransactionResponse.prototype.transaction = $util.newBuffer([]); - /** - * MethodOptions .google.longrunning.operationInfo. - * @member {google.longrunning.IOperationInfo|null|undefined} .google.longrunning.operationInfo - * @memberof google.protobuf.MethodOptions - * @instance - */ - MethodOptions.prototype[".google.longrunning.operationInfo"] = null; + /** + * Creates a BeginTransactionResponse message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.firestore.v1.BeginTransactionResponse + * @static + * @param {Object.} object Plain object + * @returns {google.firestore.v1.BeginTransactionResponse} BeginTransactionResponse + */ + BeginTransactionResponse.fromObject = function fromObject(object) { + if (object instanceof $root.google.firestore.v1.BeginTransactionResponse) + return object; + var message = new $root.google.firestore.v1.BeginTransactionResponse(); + if (object.transaction != null) + if (typeof object.transaction === "string") + $util.base64.decode(object.transaction, message.transaction = $util.newBuffer($util.base64.length(object.transaction)), 0); + else if (object.transaction.length >= 0) + message.transaction = object.transaction; + return message; + }; - /** - * Creates a MethodOptions message from a plain object. Also converts values to their respective internal types. - * @function fromObject - * @memberof google.protobuf.MethodOptions - * @static - * @param {Object.} object Plain object - * @returns {google.protobuf.MethodOptions} MethodOptions - */ - MethodOptions.fromObject = function fromObject(object) { - if (object instanceof $root.google.protobuf.MethodOptions) + /** + * Creates a plain object from a BeginTransactionResponse message. Also converts values to other types if specified. + * @function toObject + * @memberof google.firestore.v1.BeginTransactionResponse + * @static + * @param {google.firestore.v1.BeginTransactionResponse} message BeginTransactionResponse + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + BeginTransactionResponse.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.defaults) + if (options.bytes === String) + object.transaction = ""; + else { + object.transaction = []; + if (options.bytes !== Array) + object.transaction = $util.newBuffer(object.transaction); + } + if (message.transaction != null && message.hasOwnProperty("transaction")) + object.transaction = options.bytes === String ? $util.base64.encode(message.transaction, 0, message.transaction.length) : options.bytes === Array ? Array.prototype.slice.call(message.transaction) : message.transaction; return object; - var message = new $root.google.protobuf.MethodOptions(); - if (object.deprecated != null) - message.deprecated = Boolean(object.deprecated); - switch (object.idempotencyLevel) { - default: - if (typeof object.idempotencyLevel === "number") { - message.idempotencyLevel = object.idempotencyLevel; - break; - } - break; - case "IDEMPOTENCY_UNKNOWN": - case 0: - message.idempotencyLevel = 0; - break; - case "NO_SIDE_EFFECTS": - case 1: - message.idempotencyLevel = 1; - break; - case "IDEMPOTENT": - case 2: - message.idempotencyLevel = 2; - break; - } - if (object.features != null) { - if (typeof object.features !== "object") - throw TypeError(".google.protobuf.MethodOptions.features: object expected"); - message.features = $root.google.protobuf.FeatureSet.fromObject(object.features); - } - if (object.uninterpretedOption) { - if (!Array.isArray(object.uninterpretedOption)) - throw TypeError(".google.protobuf.MethodOptions.uninterpretedOption: array expected"); - message.uninterpretedOption = []; - for (var i = 0; i < object.uninterpretedOption.length; ++i) { - if (typeof object.uninterpretedOption[i] !== "object") - throw TypeError(".google.protobuf.MethodOptions.uninterpretedOption: object expected"); - message.uninterpretedOption[i] = $root.google.protobuf.UninterpretedOption.fromObject(object.uninterpretedOption[i]); - } - } - if (object[".google.api.http"] != null) { - if (typeof object[".google.api.http"] !== "object") - throw TypeError(".google.protobuf.MethodOptions..google.api.http: object expected"); - message[".google.api.http"] = $root.google.api.HttpRule.fromObject(object[".google.api.http"]); - } - if (object[".google.api.methodSignature"]) { - if (!Array.isArray(object[".google.api.methodSignature"])) - throw TypeError(".google.protobuf.MethodOptions..google.api.methodSignature: array expected"); - message[".google.api.methodSignature"] = []; - for (var i = 0; i < object[".google.api.methodSignature"].length; ++i) - message[".google.api.methodSignature"][i] = String(object[".google.api.methodSignature"][i]); - } - if (object[".google.longrunning.operationInfo"] != null) { - if (typeof object[".google.longrunning.operationInfo"] !== "object") - throw TypeError(".google.protobuf.MethodOptions..google.longrunning.operationInfo: object expected"); - message[".google.longrunning.operationInfo"] = $root.google.longrunning.OperationInfo.fromObject(object[".google.longrunning.operationInfo"]); - } - return message; - }; + }; + + /** + * Converts this BeginTransactionResponse to JSON. + * @function toJSON + * @memberof google.firestore.v1.BeginTransactionResponse + * @instance + * @returns {Object.} JSON object + */ + BeginTransactionResponse.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + + /** + * Gets the default type url for BeginTransactionResponse + * @function getTypeUrl + * @memberof google.firestore.v1.BeginTransactionResponse + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + BeginTransactionResponse.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.firestore.v1.BeginTransactionResponse"; + }; - /** - * Creates a plain object from a MethodOptions message. Also converts values to other types if specified. - * @function toObject - * @memberof google.protobuf.MethodOptions - * @static - * @param {google.protobuf.MethodOptions} message MethodOptions - * @param {$protobuf.IConversionOptions} [options] Conversion options - * @returns {Object.} Plain object - */ - MethodOptions.toObject = function toObject(message, options) { - if (!options) - options = {}; - var object = {}; - if (options.arrays || options.defaults) { - object.uninterpretedOption = []; - object[".google.api.methodSignature"] = []; - } - if (options.defaults) { - object.deprecated = false; - object.idempotencyLevel = options.enums === String ? "IDEMPOTENCY_UNKNOWN" : 0; - object.features = null; - object[".google.longrunning.operationInfo"] = null; - object[".google.api.http"] = null; - } - if (message.deprecated != null && message.hasOwnProperty("deprecated")) - object.deprecated = message.deprecated; - if (message.idempotencyLevel != null && message.hasOwnProperty("idempotencyLevel")) - object.idempotencyLevel = options.enums === String ? $root.google.protobuf.MethodOptions.IdempotencyLevel[message.idempotencyLevel] === undefined ? message.idempotencyLevel : $root.google.protobuf.MethodOptions.IdempotencyLevel[message.idempotencyLevel] : message.idempotencyLevel; - if (message.features != null && message.hasOwnProperty("features")) - object.features = $root.google.protobuf.FeatureSet.toObject(message.features, options); - if (message.uninterpretedOption && message.uninterpretedOption.length) { - object.uninterpretedOption = []; - for (var j = 0; j < message.uninterpretedOption.length; ++j) - object.uninterpretedOption[j] = $root.google.protobuf.UninterpretedOption.toObject(message.uninterpretedOption[j], options); - } - if (message[".google.longrunning.operationInfo"] != null && message.hasOwnProperty(".google.longrunning.operationInfo")) - object[".google.longrunning.operationInfo"] = $root.google.longrunning.OperationInfo.toObject(message[".google.longrunning.operationInfo"], options); - if (message[".google.api.methodSignature"] && message[".google.api.methodSignature"].length) { - object[".google.api.methodSignature"] = []; - for (var j = 0; j < message[".google.api.methodSignature"].length; ++j) - object[".google.api.methodSignature"][j] = message[".google.api.methodSignature"][j]; - } - if (message[".google.api.http"] != null && message.hasOwnProperty(".google.api.http")) - object[".google.api.http"] = $root.google.api.HttpRule.toObject(message[".google.api.http"], options); - return object; - }; + return BeginTransactionResponse; + })(); - /** - * Converts this MethodOptions to JSON. - * @function toJSON - * @memberof google.protobuf.MethodOptions - * @instance - * @returns {Object.} JSON object - */ - MethodOptions.prototype.toJSON = function toJSON() { - return this.constructor.toObject(this, $protobuf.util.toJSONOptions); - }; + v1.CommitRequest = (function() { - /** - * Gets the default type url for MethodOptions - * @function getTypeUrl - * @memberof google.protobuf.MethodOptions - * @static - * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") - * @returns {string} The default type url - */ - MethodOptions.getTypeUrl = function getTypeUrl(typeUrlPrefix) { - if (typeUrlPrefix === undefined) { - typeUrlPrefix = "type.googleapis.com"; + /** + * Properties of a CommitRequest. + * @memberof google.firestore.v1 + * @interface ICommitRequest + * @property {string|null} [database] CommitRequest database + * @property {Array.|null} [writes] CommitRequest writes + * @property {Uint8Array|null} [transaction] CommitRequest transaction + */ + + /** + * Constructs a new CommitRequest. + * @memberof google.firestore.v1 + * @classdesc Represents a CommitRequest. + * @implements ICommitRequest + * @constructor + * @param {google.firestore.v1.ICommitRequest=} [properties] Properties to set + */ + function CommitRequest(properties) { + this.writes = []; + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; } - return typeUrlPrefix + "/google.protobuf.MethodOptions"; - }; - /** - * IdempotencyLevel enum. - * @name google.protobuf.MethodOptions.IdempotencyLevel - * @enum {string} - * @property {string} IDEMPOTENCY_UNKNOWN=IDEMPOTENCY_UNKNOWN IDEMPOTENCY_UNKNOWN value - * @property {string} NO_SIDE_EFFECTS=NO_SIDE_EFFECTS NO_SIDE_EFFECTS value - * @property {string} IDEMPOTENT=IDEMPOTENT IDEMPOTENT value - */ - MethodOptions.IdempotencyLevel = (function() { - var valuesById = {}, values = Object.create(valuesById); - values[valuesById[0] = "IDEMPOTENCY_UNKNOWN"] = "IDEMPOTENCY_UNKNOWN"; - values[valuesById[1] = "NO_SIDE_EFFECTS"] = "NO_SIDE_EFFECTS"; - values[valuesById[2] = "IDEMPOTENT"] = "IDEMPOTENT"; - return values; - })(); + /** + * CommitRequest database. + * @member {string} database + * @memberof google.firestore.v1.CommitRequest + * @instance + */ + CommitRequest.prototype.database = ""; - return MethodOptions; - })(); + /** + * CommitRequest writes. + * @member {Array.} writes + * @memberof google.firestore.v1.CommitRequest + * @instance + */ + CommitRequest.prototype.writes = $util.emptyArray; - protobuf.UninterpretedOption = (function() { + /** + * CommitRequest transaction. + * @member {Uint8Array} transaction + * @memberof google.firestore.v1.CommitRequest + * @instance + */ + CommitRequest.prototype.transaction = $util.newBuffer([]); - /** - * Properties of an UninterpretedOption. - * @memberof google.protobuf - * @interface IUninterpretedOption - * @property {Array.|null} [name] UninterpretedOption name - * @property {string|null} [identifierValue] UninterpretedOption identifierValue - * @property {number|string|null} [positiveIntValue] UninterpretedOption positiveIntValue - * @property {number|string|null} [negativeIntValue] UninterpretedOption negativeIntValue - * @property {number|null} [doubleValue] UninterpretedOption doubleValue - * @property {Uint8Array|null} [stringValue] UninterpretedOption stringValue - * @property {string|null} [aggregateValue] UninterpretedOption aggregateValue - */ + /** + * Creates a CommitRequest message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.firestore.v1.CommitRequest + * @static + * @param {Object.} object Plain object + * @returns {google.firestore.v1.CommitRequest} CommitRequest + */ + CommitRequest.fromObject = function fromObject(object) { + if (object instanceof $root.google.firestore.v1.CommitRequest) + return object; + var message = new $root.google.firestore.v1.CommitRequest(); + if (object.database != null) + message.database = String(object.database); + if (object.writes) { + if (!Array.isArray(object.writes)) + throw TypeError(".google.firestore.v1.CommitRequest.writes: array expected"); + message.writes = []; + for (var i = 0; i < object.writes.length; ++i) { + if (typeof object.writes[i] !== "object") + throw TypeError(".google.firestore.v1.CommitRequest.writes: object expected"); + message.writes[i] = $root.google.firestore.v1.Write.fromObject(object.writes[i]); + } + } + if (object.transaction != null) + if (typeof object.transaction === "string") + $util.base64.decode(object.transaction, message.transaction = $util.newBuffer($util.base64.length(object.transaction)), 0); + else if (object.transaction.length >= 0) + message.transaction = object.transaction; + return message; + }; - /** - * Constructs a new UninterpretedOption. - * @memberof google.protobuf - * @classdesc Represents an UninterpretedOption. - * @implements IUninterpretedOption - * @constructor - * @param {google.protobuf.IUninterpretedOption=} [properties] Properties to set - */ - function UninterpretedOption(properties) { - this.name = []; - if (properties) - for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) - if (properties[keys[i]] != null) - this[keys[i]] = properties[keys[i]]; - } + /** + * Creates a plain object from a CommitRequest message. Also converts values to other types if specified. + * @function toObject + * @memberof google.firestore.v1.CommitRequest + * @static + * @param {google.firestore.v1.CommitRequest} message CommitRequest + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + CommitRequest.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.arrays || options.defaults) + object.writes = []; + if (options.defaults) { + object.database = ""; + if (options.bytes === String) + object.transaction = ""; + else { + object.transaction = []; + if (options.bytes !== Array) + object.transaction = $util.newBuffer(object.transaction); + } + } + if (message.database != null && message.hasOwnProperty("database")) + object.database = message.database; + if (message.writes && message.writes.length) { + object.writes = []; + for (var j = 0; j < message.writes.length; ++j) + object.writes[j] = $root.google.firestore.v1.Write.toObject(message.writes[j], options); + } + if (message.transaction != null && message.hasOwnProperty("transaction")) + object.transaction = options.bytes === String ? $util.base64.encode(message.transaction, 0, message.transaction.length) : options.bytes === Array ? Array.prototype.slice.call(message.transaction) : message.transaction; + return object; + }; + + /** + * Converts this CommitRequest to JSON. + * @function toJSON + * @memberof google.firestore.v1.CommitRequest + * @instance + * @returns {Object.} JSON object + */ + CommitRequest.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + + /** + * Gets the default type url for CommitRequest + * @function getTypeUrl + * @memberof google.firestore.v1.CommitRequest + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + CommitRequest.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.firestore.v1.CommitRequest"; + }; - /** - * UninterpretedOption name. - * @member {Array.} name - * @memberof google.protobuf.UninterpretedOption - * @instance - */ - UninterpretedOption.prototype.name = $util.emptyArray; + return CommitRequest; + })(); - /** - * UninterpretedOption identifierValue. - * @member {string} identifierValue - * @memberof google.protobuf.UninterpretedOption - * @instance - */ - UninterpretedOption.prototype.identifierValue = ""; + v1.CommitResponse = (function() { - /** - * UninterpretedOption positiveIntValue. - * @member {number|string} positiveIntValue - * @memberof google.protobuf.UninterpretedOption - * @instance - */ - UninterpretedOption.prototype.positiveIntValue = $util.Long ? $util.Long.fromBits(0,0,true) : 0; + /** + * Properties of a CommitResponse. + * @memberof google.firestore.v1 + * @interface ICommitResponse + * @property {Array.|null} [writeResults] CommitResponse writeResults + * @property {google.protobuf.ITimestamp|null} [commitTime] CommitResponse commitTime + */ - /** - * UninterpretedOption negativeIntValue. - * @member {number|string} negativeIntValue - * @memberof google.protobuf.UninterpretedOption - * @instance - */ - UninterpretedOption.prototype.negativeIntValue = $util.Long ? $util.Long.fromBits(0,0,false) : 0; + /** + * Constructs a new CommitResponse. + * @memberof google.firestore.v1 + * @classdesc Represents a CommitResponse. + * @implements ICommitResponse + * @constructor + * @param {google.firestore.v1.ICommitResponse=} [properties] Properties to set + */ + function CommitResponse(properties) { + this.writeResults = []; + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } - /** - * UninterpretedOption doubleValue. - * @member {number} doubleValue - * @memberof google.protobuf.UninterpretedOption - * @instance - */ - UninterpretedOption.prototype.doubleValue = 0; + /** + * CommitResponse writeResults. + * @member {Array.} writeResults + * @memberof google.firestore.v1.CommitResponse + * @instance + */ + CommitResponse.prototype.writeResults = $util.emptyArray; - /** - * UninterpretedOption stringValue. - * @member {Uint8Array} stringValue - * @memberof google.protobuf.UninterpretedOption - * @instance - */ - UninterpretedOption.prototype.stringValue = $util.newBuffer([]); + /** + * CommitResponse commitTime. + * @member {google.protobuf.ITimestamp|null|undefined} commitTime + * @memberof google.firestore.v1.CommitResponse + * @instance + */ + CommitResponse.prototype.commitTime = null; - /** - * UninterpretedOption aggregateValue. - * @member {string} aggregateValue - * @memberof google.protobuf.UninterpretedOption - * @instance - */ - UninterpretedOption.prototype.aggregateValue = ""; + /** + * Creates a CommitResponse message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.firestore.v1.CommitResponse + * @static + * @param {Object.} object Plain object + * @returns {google.firestore.v1.CommitResponse} CommitResponse + */ + CommitResponse.fromObject = function fromObject(object) { + if (object instanceof $root.google.firestore.v1.CommitResponse) + return object; + var message = new $root.google.firestore.v1.CommitResponse(); + if (object.writeResults) { + if (!Array.isArray(object.writeResults)) + throw TypeError(".google.firestore.v1.CommitResponse.writeResults: array expected"); + message.writeResults = []; + for (var i = 0; i < object.writeResults.length; ++i) { + if (typeof object.writeResults[i] !== "object") + throw TypeError(".google.firestore.v1.CommitResponse.writeResults: object expected"); + message.writeResults[i] = $root.google.firestore.v1.WriteResult.fromObject(object.writeResults[i]); + } + } + if (object.commitTime != null) { + if (typeof object.commitTime !== "object") + throw TypeError(".google.firestore.v1.CommitResponse.commitTime: object expected"); + message.commitTime = $root.google.protobuf.Timestamp.fromObject(object.commitTime); + } + return message; + }; - /** - * Creates an UninterpretedOption message from a plain object. Also converts values to their respective internal types. - * @function fromObject - * @memberof google.protobuf.UninterpretedOption - * @static - * @param {Object.} object Plain object - * @returns {google.protobuf.UninterpretedOption} UninterpretedOption - */ - UninterpretedOption.fromObject = function fromObject(object) { - if (object instanceof $root.google.protobuf.UninterpretedOption) + /** + * Creates a plain object from a CommitResponse message. Also converts values to other types if specified. + * @function toObject + * @memberof google.firestore.v1.CommitResponse + * @static + * @param {google.firestore.v1.CommitResponse} message CommitResponse + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + CommitResponse.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.arrays || options.defaults) + object.writeResults = []; + if (options.defaults) + object.commitTime = null; + if (message.writeResults && message.writeResults.length) { + object.writeResults = []; + for (var j = 0; j < message.writeResults.length; ++j) + object.writeResults[j] = $root.google.firestore.v1.WriteResult.toObject(message.writeResults[j], options); + } + if (message.commitTime != null && message.hasOwnProperty("commitTime")) + object.commitTime = $root.google.protobuf.Timestamp.toObject(message.commitTime, options); return object; - var message = new $root.google.protobuf.UninterpretedOption(); - if (object.name) { - if (!Array.isArray(object.name)) - throw TypeError(".google.protobuf.UninterpretedOption.name: array expected"); - message.name = []; - for (var i = 0; i < object.name.length; ++i) { - if (typeof object.name[i] !== "object") - throw TypeError(".google.protobuf.UninterpretedOption.name: object expected"); - message.name[i] = $root.google.protobuf.UninterpretedOption.NamePart.fromObject(object.name[i]); + }; + + /** + * Converts this CommitResponse to JSON. + * @function toJSON + * @memberof google.firestore.v1.CommitResponse + * @instance + * @returns {Object.} JSON object + */ + CommitResponse.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + + /** + * Gets the default type url for CommitResponse + * @function getTypeUrl + * @memberof google.firestore.v1.CommitResponse + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + CommitResponse.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; } + return typeUrlPrefix + "/google.firestore.v1.CommitResponse"; + }; + + return CommitResponse; + })(); + + v1.RollbackRequest = (function() { + + /** + * Properties of a RollbackRequest. + * @memberof google.firestore.v1 + * @interface IRollbackRequest + * @property {string|null} [database] RollbackRequest database + * @property {Uint8Array|null} [transaction] RollbackRequest transaction + */ + + /** + * Constructs a new RollbackRequest. + * @memberof google.firestore.v1 + * @classdesc Represents a RollbackRequest. + * @implements IRollbackRequest + * @constructor + * @param {google.firestore.v1.IRollbackRequest=} [properties] Properties to set + */ + function RollbackRequest(properties) { + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; } - if (object.identifierValue != null) - message.identifierValue = String(object.identifierValue); - if (object.positiveIntValue != null) - if ($util.Long) - (message.positiveIntValue = $util.Long.fromValue(object.positiveIntValue)).unsigned = true; - else if (typeof object.positiveIntValue === "string") - message.positiveIntValue = parseInt(object.positiveIntValue, 10); - else if (typeof object.positiveIntValue === "number") - message.positiveIntValue = object.positiveIntValue; - else if (typeof object.positiveIntValue === "object") - message.positiveIntValue = new $util.LongBits(object.positiveIntValue.low >>> 0, object.positiveIntValue.high >>> 0).toNumber(true); - if (object.negativeIntValue != null) - if ($util.Long) - (message.negativeIntValue = $util.Long.fromValue(object.negativeIntValue)).unsigned = false; - else if (typeof object.negativeIntValue === "string") - message.negativeIntValue = parseInt(object.negativeIntValue, 10); - else if (typeof object.negativeIntValue === "number") - message.negativeIntValue = object.negativeIntValue; - else if (typeof object.negativeIntValue === "object") - message.negativeIntValue = new $util.LongBits(object.negativeIntValue.low >>> 0, object.negativeIntValue.high >>> 0).toNumber(); - if (object.doubleValue != null) - message.doubleValue = Number(object.doubleValue); - if (object.stringValue != null) - if (typeof object.stringValue === "string") - $util.base64.decode(object.stringValue, message.stringValue = $util.newBuffer($util.base64.length(object.stringValue)), 0); - else if (object.stringValue.length >= 0) - message.stringValue = object.stringValue; - if (object.aggregateValue != null) - message.aggregateValue = String(object.aggregateValue); - return message; - }; - /** - * Creates a plain object from an UninterpretedOption message. Also converts values to other types if specified. - * @function toObject - * @memberof google.protobuf.UninterpretedOption - * @static - * @param {google.protobuf.UninterpretedOption} message UninterpretedOption - * @param {$protobuf.IConversionOptions} [options] Conversion options - * @returns {Object.} Plain object - */ - UninterpretedOption.toObject = function toObject(message, options) { - if (!options) - options = {}; - var object = {}; - if (options.arrays || options.defaults) - object.name = []; - if (options.defaults) { - object.identifierValue = ""; - if ($util.Long) { - var long = new $util.Long(0, 0, true); - object.positiveIntValue = options.longs === String ? long.toString() : options.longs === Number ? long.toNumber() : long; - } else - object.positiveIntValue = options.longs === String ? "0" : 0; - if ($util.Long) { - var long = new $util.Long(0, 0, false); - object.negativeIntValue = options.longs === String ? long.toString() : options.longs === Number ? long.toNumber() : long; - } else - object.negativeIntValue = options.longs === String ? "0" : 0; - object.doubleValue = 0; - if (options.bytes === String) - object.stringValue = ""; - else { - object.stringValue = []; - if (options.bytes !== Array) - object.stringValue = $util.newBuffer(object.stringValue); + /** + * RollbackRequest database. + * @member {string} database + * @memberof google.firestore.v1.RollbackRequest + * @instance + */ + RollbackRequest.prototype.database = ""; + + /** + * RollbackRequest transaction. + * @member {Uint8Array} transaction + * @memberof google.firestore.v1.RollbackRequest + * @instance + */ + RollbackRequest.prototype.transaction = $util.newBuffer([]); + + /** + * Creates a RollbackRequest message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.firestore.v1.RollbackRequest + * @static + * @param {Object.} object Plain object + * @returns {google.firestore.v1.RollbackRequest} RollbackRequest + */ + RollbackRequest.fromObject = function fromObject(object) { + if (object instanceof $root.google.firestore.v1.RollbackRequest) + return object; + var message = new $root.google.firestore.v1.RollbackRequest(); + if (object.database != null) + message.database = String(object.database); + if (object.transaction != null) + if (typeof object.transaction === "string") + $util.base64.decode(object.transaction, message.transaction = $util.newBuffer($util.base64.length(object.transaction)), 0); + else if (object.transaction.length >= 0) + message.transaction = object.transaction; + return message; + }; + + /** + * Creates a plain object from a RollbackRequest message. Also converts values to other types if specified. + * @function toObject + * @memberof google.firestore.v1.RollbackRequest + * @static + * @param {google.firestore.v1.RollbackRequest} message RollbackRequest + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + RollbackRequest.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.defaults) { + object.database = ""; + if (options.bytes === String) + object.transaction = ""; + else { + object.transaction = []; + if (options.bytes !== Array) + object.transaction = $util.newBuffer(object.transaction); + } } - object.aggregateValue = ""; - } - if (message.name && message.name.length) { - object.name = []; - for (var j = 0; j < message.name.length; ++j) - object.name[j] = $root.google.protobuf.UninterpretedOption.NamePart.toObject(message.name[j], options); - } - if (message.identifierValue != null && message.hasOwnProperty("identifierValue")) - object.identifierValue = message.identifierValue; - if (message.positiveIntValue != null && message.hasOwnProperty("positiveIntValue")) - if (typeof message.positiveIntValue === "number") - object.positiveIntValue = options.longs === String ? String(message.positiveIntValue) : message.positiveIntValue; - else - object.positiveIntValue = options.longs === String ? $util.Long.prototype.toString.call(message.positiveIntValue) : options.longs === Number ? new $util.LongBits(message.positiveIntValue.low >>> 0, message.positiveIntValue.high >>> 0).toNumber(true) : message.positiveIntValue; - if (message.negativeIntValue != null && message.hasOwnProperty("negativeIntValue")) - if (typeof message.negativeIntValue === "number") - object.negativeIntValue = options.longs === String ? String(message.negativeIntValue) : message.negativeIntValue; - else - object.negativeIntValue = options.longs === String ? $util.Long.prototype.toString.call(message.negativeIntValue) : options.longs === Number ? new $util.LongBits(message.negativeIntValue.low >>> 0, message.negativeIntValue.high >>> 0).toNumber() : message.negativeIntValue; - if (message.doubleValue != null && message.hasOwnProperty("doubleValue")) - object.doubleValue = options.json && !isFinite(message.doubleValue) ? String(message.doubleValue) : message.doubleValue; - if (message.stringValue != null && message.hasOwnProperty("stringValue")) - object.stringValue = options.bytes === String ? $util.base64.encode(message.stringValue, 0, message.stringValue.length) : options.bytes === Array ? Array.prototype.slice.call(message.stringValue) : message.stringValue; - if (message.aggregateValue != null && message.hasOwnProperty("aggregateValue")) - object.aggregateValue = message.aggregateValue; - return object; - }; + if (message.database != null && message.hasOwnProperty("database")) + object.database = message.database; + if (message.transaction != null && message.hasOwnProperty("transaction")) + object.transaction = options.bytes === String ? $util.base64.encode(message.transaction, 0, message.transaction.length) : options.bytes === Array ? Array.prototype.slice.call(message.transaction) : message.transaction; + return object; + }; - /** - * Converts this UninterpretedOption to JSON. - * @function toJSON - * @memberof google.protobuf.UninterpretedOption - * @instance - * @returns {Object.} JSON object - */ - UninterpretedOption.prototype.toJSON = function toJSON() { - return this.constructor.toObject(this, $protobuf.util.toJSONOptions); - }; + /** + * Converts this RollbackRequest to JSON. + * @function toJSON + * @memberof google.firestore.v1.RollbackRequest + * @instance + * @returns {Object.} JSON object + */ + RollbackRequest.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; - /** - * Gets the default type url for UninterpretedOption - * @function getTypeUrl - * @memberof google.protobuf.UninterpretedOption - * @static - * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") - * @returns {string} The default type url - */ - UninterpretedOption.getTypeUrl = function getTypeUrl(typeUrlPrefix) { - if (typeUrlPrefix === undefined) { - typeUrlPrefix = "type.googleapis.com"; - } - return typeUrlPrefix + "/google.protobuf.UninterpretedOption"; - }; + /** + * Gets the default type url for RollbackRequest + * @function getTypeUrl + * @memberof google.firestore.v1.RollbackRequest + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + RollbackRequest.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.firestore.v1.RollbackRequest"; + }; - UninterpretedOption.NamePart = (function() { + return RollbackRequest; + })(); + + v1.RunQueryRequest = (function() { /** - * Properties of a NamePart. - * @memberof google.protobuf.UninterpretedOption - * @interface INamePart - * @property {string} namePart NamePart namePart - * @property {boolean} isExtension NamePart isExtension + * Properties of a RunQueryRequest. + * @memberof google.firestore.v1 + * @interface IRunQueryRequest + * @property {string|null} [parent] RunQueryRequest parent + * @property {google.firestore.v1.IStructuredQuery|null} [structuredQuery] RunQueryRequest structuredQuery + * @property {Uint8Array|null} [transaction] RunQueryRequest transaction + * @property {google.firestore.v1.ITransactionOptions|null} [newTransaction] RunQueryRequest newTransaction + * @property {google.protobuf.ITimestamp|null} [readTime] RunQueryRequest readTime + * @property {google.firestore.v1.IExplainOptions|null} [explainOptions] RunQueryRequest explainOptions */ /** - * Constructs a new NamePart. - * @memberof google.protobuf.UninterpretedOption - * @classdesc Represents a NamePart. - * @implements INamePart + * Constructs a new RunQueryRequest. + * @memberof google.firestore.v1 + * @classdesc Represents a RunQueryRequest. + * @implements IRunQueryRequest * @constructor - * @param {google.protobuf.UninterpretedOption.INamePart=} [properties] Properties to set + * @param {google.firestore.v1.IRunQueryRequest=} [properties] Properties to set */ - function NamePart(properties) { + function RunQueryRequest(properties) { if (properties) for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) if (properties[keys[i]] != null) @@ -7041,740 +5563,616 @@ } /** - * NamePart namePart. - * @member {string} namePart - * @memberof google.protobuf.UninterpretedOption.NamePart + * RunQueryRequest parent. + * @member {string} parent + * @memberof google.firestore.v1.RunQueryRequest + * @instance + */ + RunQueryRequest.prototype.parent = ""; + + /** + * RunQueryRequest structuredQuery. + * @member {google.firestore.v1.IStructuredQuery|null|undefined} structuredQuery + * @memberof google.firestore.v1.RunQueryRequest + * @instance + */ + RunQueryRequest.prototype.structuredQuery = null; + + /** + * RunQueryRequest transaction. + * @member {Uint8Array|null|undefined} transaction + * @memberof google.firestore.v1.RunQueryRequest + * @instance + */ + RunQueryRequest.prototype.transaction = null; + + /** + * RunQueryRequest newTransaction. + * @member {google.firestore.v1.ITransactionOptions|null|undefined} newTransaction + * @memberof google.firestore.v1.RunQueryRequest + * @instance + */ + RunQueryRequest.prototype.newTransaction = null; + + /** + * RunQueryRequest readTime. + * @member {google.protobuf.ITimestamp|null|undefined} readTime + * @memberof google.firestore.v1.RunQueryRequest + * @instance + */ + RunQueryRequest.prototype.readTime = null; + + /** + * RunQueryRequest explainOptions. + * @member {google.firestore.v1.IExplainOptions|null|undefined} explainOptions + * @memberof google.firestore.v1.RunQueryRequest + * @instance + */ + RunQueryRequest.prototype.explainOptions = null; + + // OneOf field names bound to virtual getters and setters + var $oneOfFields; + + /** + * RunQueryRequest queryType. + * @member {"structuredQuery"|undefined} queryType + * @memberof google.firestore.v1.RunQueryRequest * @instance */ - NamePart.prototype.namePart = ""; + Object.defineProperty(RunQueryRequest.prototype, "queryType", { + get: $util.oneOfGetter($oneOfFields = ["structuredQuery"]), + set: $util.oneOfSetter($oneOfFields) + }); /** - * NamePart isExtension. - * @member {boolean} isExtension - * @memberof google.protobuf.UninterpretedOption.NamePart + * RunQueryRequest consistencySelector. + * @member {"transaction"|"newTransaction"|"readTime"|undefined} consistencySelector + * @memberof google.firestore.v1.RunQueryRequest * @instance */ - NamePart.prototype.isExtension = false; + Object.defineProperty(RunQueryRequest.prototype, "consistencySelector", { + get: $util.oneOfGetter($oneOfFields = ["transaction", "newTransaction", "readTime"]), + set: $util.oneOfSetter($oneOfFields) + }); /** - * Creates a NamePart message from a plain object. Also converts values to their respective internal types. + * Creates a RunQueryRequest message from a plain object. Also converts values to their respective internal types. * @function fromObject - * @memberof google.protobuf.UninterpretedOption.NamePart + * @memberof google.firestore.v1.RunQueryRequest * @static * @param {Object.} object Plain object - * @returns {google.protobuf.UninterpretedOption.NamePart} NamePart + * @returns {google.firestore.v1.RunQueryRequest} RunQueryRequest */ - NamePart.fromObject = function fromObject(object) { - if (object instanceof $root.google.protobuf.UninterpretedOption.NamePart) + RunQueryRequest.fromObject = function fromObject(object) { + if (object instanceof $root.google.firestore.v1.RunQueryRequest) return object; - var message = new $root.google.protobuf.UninterpretedOption.NamePart(); - if (object.namePart != null) - message.namePart = String(object.namePart); - if (object.isExtension != null) - message.isExtension = Boolean(object.isExtension); + var message = new $root.google.firestore.v1.RunQueryRequest(); + if (object.parent != null) + message.parent = String(object.parent); + if (object.structuredQuery != null) { + if (typeof object.structuredQuery !== "object") + throw TypeError(".google.firestore.v1.RunQueryRequest.structuredQuery: object expected"); + message.structuredQuery = $root.google.firestore.v1.StructuredQuery.fromObject(object.structuredQuery); + } + if (object.transaction != null) + if (typeof object.transaction === "string") + $util.base64.decode(object.transaction, message.transaction = $util.newBuffer($util.base64.length(object.transaction)), 0); + else if (object.transaction.length >= 0) + message.transaction = object.transaction; + if (object.newTransaction != null) { + if (typeof object.newTransaction !== "object") + throw TypeError(".google.firestore.v1.RunQueryRequest.newTransaction: object expected"); + message.newTransaction = $root.google.firestore.v1.TransactionOptions.fromObject(object.newTransaction); + } + if (object.readTime != null) { + if (typeof object.readTime !== "object") + throw TypeError(".google.firestore.v1.RunQueryRequest.readTime: object expected"); + message.readTime = $root.google.protobuf.Timestamp.fromObject(object.readTime); + } + if (object.explainOptions != null) { + if (typeof object.explainOptions !== "object") + throw TypeError(".google.firestore.v1.RunQueryRequest.explainOptions: object expected"); + message.explainOptions = $root.google.firestore.v1.ExplainOptions.fromObject(object.explainOptions); + } return message; }; /** - * Creates a plain object from a NamePart message. Also converts values to other types if specified. + * Creates a plain object from a RunQueryRequest message. Also converts values to other types if specified. * @function toObject - * @memberof google.protobuf.UninterpretedOption.NamePart + * @memberof google.firestore.v1.RunQueryRequest * @static - * @param {google.protobuf.UninterpretedOption.NamePart} message NamePart + * @param {google.firestore.v1.RunQueryRequest} message RunQueryRequest * @param {$protobuf.IConversionOptions} [options] Conversion options * @returns {Object.} Plain object */ - NamePart.toObject = function toObject(message, options) { + RunQueryRequest.toObject = function toObject(message, options) { if (!options) options = {}; var object = {}; if (options.defaults) { - object.namePart = ""; - object.isExtension = false; - } - if (message.namePart != null && message.hasOwnProperty("namePart")) - object.namePart = message.namePart; - if (message.isExtension != null && message.hasOwnProperty("isExtension")) - object.isExtension = message.isExtension; - return object; - }; - - /** - * Converts this NamePart to JSON. - * @function toJSON - * @memberof google.protobuf.UninterpretedOption.NamePart - * @instance - * @returns {Object.} JSON object - */ - NamePart.prototype.toJSON = function toJSON() { - return this.constructor.toObject(this, $protobuf.util.toJSONOptions); - }; - - /** - * Gets the default type url for NamePart - * @function getTypeUrl - * @memberof google.protobuf.UninterpretedOption.NamePart - * @static - * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") - * @returns {string} The default type url - */ - NamePart.getTypeUrl = function getTypeUrl(typeUrlPrefix) { - if (typeUrlPrefix === undefined) { - typeUrlPrefix = "type.googleapis.com"; - } - return typeUrlPrefix + "/google.protobuf.UninterpretedOption.NamePart"; - }; - - return NamePart; - })(); - - return UninterpretedOption; - })(); - - protobuf.FeatureSet = (function() { - - /** - * Properties of a FeatureSet. - * @memberof google.protobuf - * @interface IFeatureSet - * @property {google.protobuf.FeatureSet.FieldPresence|null} [fieldPresence] FeatureSet fieldPresence - * @property {google.protobuf.FeatureSet.EnumType|null} [enumType] FeatureSet enumType - * @property {google.protobuf.FeatureSet.RepeatedFieldEncoding|null} [repeatedFieldEncoding] FeatureSet repeatedFieldEncoding - * @property {google.protobuf.FeatureSet.Utf8Validation|null} [utf8Validation] FeatureSet utf8Validation - * @property {google.protobuf.FeatureSet.MessageEncoding|null} [messageEncoding] FeatureSet messageEncoding - * @property {google.protobuf.FeatureSet.JsonFormat|null} [jsonFormat] FeatureSet jsonFormat - */ - - /** - * Constructs a new FeatureSet. - * @memberof google.protobuf - * @classdesc Represents a FeatureSet. - * @implements IFeatureSet - * @constructor - * @param {google.protobuf.IFeatureSet=} [properties] Properties to set - */ - function FeatureSet(properties) { - if (properties) - for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) - if (properties[keys[i]] != null) - this[keys[i]] = properties[keys[i]]; - } - - /** - * FeatureSet fieldPresence. - * @member {google.protobuf.FeatureSet.FieldPresence} fieldPresence - * @memberof google.protobuf.FeatureSet - * @instance - */ - FeatureSet.prototype.fieldPresence = 0; - - /** - * FeatureSet enumType. - * @member {google.protobuf.FeatureSet.EnumType} enumType - * @memberof google.protobuf.FeatureSet - * @instance - */ - FeatureSet.prototype.enumType = 0; - - /** - * FeatureSet repeatedFieldEncoding. - * @member {google.protobuf.FeatureSet.RepeatedFieldEncoding} repeatedFieldEncoding - * @memberof google.protobuf.FeatureSet - * @instance - */ - FeatureSet.prototype.repeatedFieldEncoding = 0; - - /** - * FeatureSet utf8Validation. - * @member {google.protobuf.FeatureSet.Utf8Validation} utf8Validation - * @memberof google.protobuf.FeatureSet - * @instance - */ - FeatureSet.prototype.utf8Validation = 0; - - /** - * FeatureSet messageEncoding. - * @member {google.protobuf.FeatureSet.MessageEncoding} messageEncoding - * @memberof google.protobuf.FeatureSet - * @instance - */ - FeatureSet.prototype.messageEncoding = 0; - - /** - * FeatureSet jsonFormat. - * @member {google.protobuf.FeatureSet.JsonFormat} jsonFormat - * @memberof google.protobuf.FeatureSet - * @instance - */ - FeatureSet.prototype.jsonFormat = 0; - - /** - * Creates a FeatureSet message from a plain object. Also converts values to their respective internal types. - * @function fromObject - * @memberof google.protobuf.FeatureSet - * @static - * @param {Object.} object Plain object - * @returns {google.protobuf.FeatureSet} FeatureSet - */ - FeatureSet.fromObject = function fromObject(object) { - if (object instanceof $root.google.protobuf.FeatureSet) - return object; - var message = new $root.google.protobuf.FeatureSet(); - switch (object.fieldPresence) { - default: - if (typeof object.fieldPresence === "number") { - message.fieldPresence = object.fieldPresence; - break; + object.parent = ""; + object.explainOptions = null; } - break; - case "FIELD_PRESENCE_UNKNOWN": - case 0: - message.fieldPresence = 0; - break; - case "EXPLICIT": - case 1: - message.fieldPresence = 1; - break; - case "IMPLICIT": - case 2: - message.fieldPresence = 2; - break; - case "LEGACY_REQUIRED": - case 3: - message.fieldPresence = 3; - break; - } - switch (object.enumType) { - default: - if (typeof object.enumType === "number") { - message.enumType = object.enumType; - break; + if (message.parent != null && message.hasOwnProperty("parent")) + object.parent = message.parent; + if (message.structuredQuery != null && message.hasOwnProperty("structuredQuery")) { + object.structuredQuery = $root.google.firestore.v1.StructuredQuery.toObject(message.structuredQuery, options); + if (options.oneofs) + object.queryType = "structuredQuery"; } - break; - case "ENUM_TYPE_UNKNOWN": - case 0: - message.enumType = 0; - break; - case "OPEN": - case 1: - message.enumType = 1; - break; - case "CLOSED": - case 2: - message.enumType = 2; - break; - } - switch (object.repeatedFieldEncoding) { - default: - if (typeof object.repeatedFieldEncoding === "number") { - message.repeatedFieldEncoding = object.repeatedFieldEncoding; - break; + if (message.transaction != null && message.hasOwnProperty("transaction")) { + object.transaction = options.bytes === String ? $util.base64.encode(message.transaction, 0, message.transaction.length) : options.bytes === Array ? Array.prototype.slice.call(message.transaction) : message.transaction; + if (options.oneofs) + object.consistencySelector = "transaction"; } - break; - case "REPEATED_FIELD_ENCODING_UNKNOWN": - case 0: - message.repeatedFieldEncoding = 0; - break; - case "PACKED": - case 1: - message.repeatedFieldEncoding = 1; - break; - case "EXPANDED": - case 2: - message.repeatedFieldEncoding = 2; - break; - } - switch (object.utf8Validation) { - default: - if (typeof object.utf8Validation === "number") { - message.utf8Validation = object.utf8Validation; - break; + if (message.newTransaction != null && message.hasOwnProperty("newTransaction")) { + object.newTransaction = $root.google.firestore.v1.TransactionOptions.toObject(message.newTransaction, options); + if (options.oneofs) + object.consistencySelector = "newTransaction"; } - break; - case "UTF8_VALIDATION_UNKNOWN": - case 0: - message.utf8Validation = 0; - break; - case "VERIFY": - case 2: - message.utf8Validation = 2; - break; - case "NONE": - case 3: - message.utf8Validation = 3; - break; - } - switch (object.messageEncoding) { - default: - if (typeof object.messageEncoding === "number") { - message.messageEncoding = object.messageEncoding; - break; + if (message.readTime != null && message.hasOwnProperty("readTime")) { + object.readTime = $root.google.protobuf.Timestamp.toObject(message.readTime, options); + if (options.oneofs) + object.consistencySelector = "readTime"; } - break; - case "MESSAGE_ENCODING_UNKNOWN": - case 0: - message.messageEncoding = 0; - break; - case "LENGTH_PREFIXED": - case 1: - message.messageEncoding = 1; - break; - case "DELIMITED": - case 2: - message.messageEncoding = 2; - break; - } - switch (object.jsonFormat) { - default: - if (typeof object.jsonFormat === "number") { - message.jsonFormat = object.jsonFormat; - break; + if (message.explainOptions != null && message.hasOwnProperty("explainOptions")) + object.explainOptions = $root.google.firestore.v1.ExplainOptions.toObject(message.explainOptions, options); + return object; + }; + + /** + * Converts this RunQueryRequest to JSON. + * @function toJSON + * @memberof google.firestore.v1.RunQueryRequest + * @instance + * @returns {Object.} JSON object + */ + RunQueryRequest.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + + /** + * Gets the default type url for RunQueryRequest + * @function getTypeUrl + * @memberof google.firestore.v1.RunQueryRequest + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + RunQueryRequest.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; } - break; - case "JSON_FORMAT_UNKNOWN": - case 0: - message.jsonFormat = 0; - break; - case "ALLOW": - case 1: - message.jsonFormat = 1; - break; - case "LEGACY_BEST_EFFORT": - case 2: - message.jsonFormat = 2; - break; - } - return message; - }; + return typeUrlPrefix + "/google.firestore.v1.RunQueryRequest"; + }; - /** - * Creates a plain object from a FeatureSet message. Also converts values to other types if specified. - * @function toObject - * @memberof google.protobuf.FeatureSet - * @static - * @param {google.protobuf.FeatureSet} message FeatureSet - * @param {$protobuf.IConversionOptions} [options] Conversion options - * @returns {Object.} Plain object - */ - FeatureSet.toObject = function toObject(message, options) { - if (!options) - options = {}; - var object = {}; - if (options.defaults) { - object.fieldPresence = options.enums === String ? "FIELD_PRESENCE_UNKNOWN" : 0; - object.enumType = options.enums === String ? "ENUM_TYPE_UNKNOWN" : 0; - object.repeatedFieldEncoding = options.enums === String ? "REPEATED_FIELD_ENCODING_UNKNOWN" : 0; - object.utf8Validation = options.enums === String ? "UTF8_VALIDATION_UNKNOWN" : 0; - object.messageEncoding = options.enums === String ? "MESSAGE_ENCODING_UNKNOWN" : 0; - object.jsonFormat = options.enums === String ? "JSON_FORMAT_UNKNOWN" : 0; + return RunQueryRequest; + })(); + + v1.RunQueryResponse = (function() { + + /** + * Properties of a RunQueryResponse. + * @memberof google.firestore.v1 + * @interface IRunQueryResponse + * @property {Uint8Array|null} [transaction] RunQueryResponse transaction + * @property {google.firestore.v1.IDocument|null} [document] RunQueryResponse document + * @property {google.protobuf.ITimestamp|null} [readTime] RunQueryResponse readTime + * @property {number|null} [skippedResults] RunQueryResponse skippedResults + * @property {boolean|null} [done] RunQueryResponse done + * @property {google.firestore.v1.IExplainMetrics|null} [explainMetrics] RunQueryResponse explainMetrics + */ + + /** + * Constructs a new RunQueryResponse. + * @memberof google.firestore.v1 + * @classdesc Represents a RunQueryResponse. + * @implements IRunQueryResponse + * @constructor + * @param {google.firestore.v1.IRunQueryResponse=} [properties] Properties to set + */ + function RunQueryResponse(properties) { + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; } - if (message.fieldPresence != null && message.hasOwnProperty("fieldPresence")) - object.fieldPresence = options.enums === String ? $root.google.protobuf.FeatureSet.FieldPresence[message.fieldPresence] === undefined ? message.fieldPresence : $root.google.protobuf.FeatureSet.FieldPresence[message.fieldPresence] : message.fieldPresence; - if (message.enumType != null && message.hasOwnProperty("enumType")) - object.enumType = options.enums === String ? $root.google.protobuf.FeatureSet.EnumType[message.enumType] === undefined ? message.enumType : $root.google.protobuf.FeatureSet.EnumType[message.enumType] : message.enumType; - if (message.repeatedFieldEncoding != null && message.hasOwnProperty("repeatedFieldEncoding")) - object.repeatedFieldEncoding = options.enums === String ? $root.google.protobuf.FeatureSet.RepeatedFieldEncoding[message.repeatedFieldEncoding] === undefined ? message.repeatedFieldEncoding : $root.google.protobuf.FeatureSet.RepeatedFieldEncoding[message.repeatedFieldEncoding] : message.repeatedFieldEncoding; - if (message.utf8Validation != null && message.hasOwnProperty("utf8Validation")) - object.utf8Validation = options.enums === String ? $root.google.protobuf.FeatureSet.Utf8Validation[message.utf8Validation] === undefined ? message.utf8Validation : $root.google.protobuf.FeatureSet.Utf8Validation[message.utf8Validation] : message.utf8Validation; - if (message.messageEncoding != null && message.hasOwnProperty("messageEncoding")) - object.messageEncoding = options.enums === String ? $root.google.protobuf.FeatureSet.MessageEncoding[message.messageEncoding] === undefined ? message.messageEncoding : $root.google.protobuf.FeatureSet.MessageEncoding[message.messageEncoding] : message.messageEncoding; - if (message.jsonFormat != null && message.hasOwnProperty("jsonFormat")) - object.jsonFormat = options.enums === String ? $root.google.protobuf.FeatureSet.JsonFormat[message.jsonFormat] === undefined ? message.jsonFormat : $root.google.protobuf.FeatureSet.JsonFormat[message.jsonFormat] : message.jsonFormat; - return object; - }; - /** - * Converts this FeatureSet to JSON. - * @function toJSON - * @memberof google.protobuf.FeatureSet - * @instance - * @returns {Object.} JSON object - */ - FeatureSet.prototype.toJSON = function toJSON() { - return this.constructor.toObject(this, $protobuf.util.toJSONOptions); - }; + /** + * RunQueryResponse transaction. + * @member {Uint8Array} transaction + * @memberof google.firestore.v1.RunQueryResponse + * @instance + */ + RunQueryResponse.prototype.transaction = $util.newBuffer([]); + + /** + * RunQueryResponse document. + * @member {google.firestore.v1.IDocument|null|undefined} document + * @memberof google.firestore.v1.RunQueryResponse + * @instance + */ + RunQueryResponse.prototype.document = null; + + /** + * RunQueryResponse readTime. + * @member {google.protobuf.ITimestamp|null|undefined} readTime + * @memberof google.firestore.v1.RunQueryResponse + * @instance + */ + RunQueryResponse.prototype.readTime = null; + + /** + * RunQueryResponse skippedResults. + * @member {number} skippedResults + * @memberof google.firestore.v1.RunQueryResponse + * @instance + */ + RunQueryResponse.prototype.skippedResults = 0; + + /** + * RunQueryResponse done. + * @member {boolean|null|undefined} done + * @memberof google.firestore.v1.RunQueryResponse + * @instance + */ + RunQueryResponse.prototype.done = null; + + /** + * RunQueryResponse explainMetrics. + * @member {google.firestore.v1.IExplainMetrics|null|undefined} explainMetrics + * @memberof google.firestore.v1.RunQueryResponse + * @instance + */ + RunQueryResponse.prototype.explainMetrics = null; + + // OneOf field names bound to virtual getters and setters + var $oneOfFields; + + /** + * RunQueryResponse continuationSelector. + * @member {"done"|undefined} continuationSelector + * @memberof google.firestore.v1.RunQueryResponse + * @instance + */ + Object.defineProperty(RunQueryResponse.prototype, "continuationSelector", { + get: $util.oneOfGetter($oneOfFields = ["done"]), + set: $util.oneOfSetter($oneOfFields) + }); + + /** + * Creates a RunQueryResponse message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.firestore.v1.RunQueryResponse + * @static + * @param {Object.} object Plain object + * @returns {google.firestore.v1.RunQueryResponse} RunQueryResponse + */ + RunQueryResponse.fromObject = function fromObject(object) { + if (object instanceof $root.google.firestore.v1.RunQueryResponse) + return object; + var message = new $root.google.firestore.v1.RunQueryResponse(); + if (object.transaction != null) + if (typeof object.transaction === "string") + $util.base64.decode(object.transaction, message.transaction = $util.newBuffer($util.base64.length(object.transaction)), 0); + else if (object.transaction.length >= 0) + message.transaction = object.transaction; + if (object.document != null) { + if (typeof object.document !== "object") + throw TypeError(".google.firestore.v1.RunQueryResponse.document: object expected"); + message.document = $root.google.firestore.v1.Document.fromObject(object.document); + } + if (object.readTime != null) { + if (typeof object.readTime !== "object") + throw TypeError(".google.firestore.v1.RunQueryResponse.readTime: object expected"); + message.readTime = $root.google.protobuf.Timestamp.fromObject(object.readTime); + } + if (object.skippedResults != null) + message.skippedResults = object.skippedResults | 0; + if (object.done != null) + message.done = Boolean(object.done); + if (object.explainMetrics != null) { + if (typeof object.explainMetrics !== "object") + throw TypeError(".google.firestore.v1.RunQueryResponse.explainMetrics: object expected"); + message.explainMetrics = $root.google.firestore.v1.ExplainMetrics.fromObject(object.explainMetrics); + } + return message; + }; - /** - * Gets the default type url for FeatureSet - * @function getTypeUrl - * @memberof google.protobuf.FeatureSet - * @static - * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") - * @returns {string} The default type url - */ - FeatureSet.getTypeUrl = function getTypeUrl(typeUrlPrefix) { - if (typeUrlPrefix === undefined) { - typeUrlPrefix = "type.googleapis.com"; - } - return typeUrlPrefix + "/google.protobuf.FeatureSet"; - }; + /** + * Creates a plain object from a RunQueryResponse message. Also converts values to other types if specified. + * @function toObject + * @memberof google.firestore.v1.RunQueryResponse + * @static + * @param {google.firestore.v1.RunQueryResponse} message RunQueryResponse + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + RunQueryResponse.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.defaults) { + object.document = null; + if (options.bytes === String) + object.transaction = ""; + else { + object.transaction = []; + if (options.bytes !== Array) + object.transaction = $util.newBuffer(object.transaction); + } + object.readTime = null; + object.skippedResults = 0; + object.explainMetrics = null; + } + if (message.document != null && message.hasOwnProperty("document")) + object.document = $root.google.firestore.v1.Document.toObject(message.document, options); + if (message.transaction != null && message.hasOwnProperty("transaction")) + object.transaction = options.bytes === String ? $util.base64.encode(message.transaction, 0, message.transaction.length) : options.bytes === Array ? Array.prototype.slice.call(message.transaction) : message.transaction; + if (message.readTime != null && message.hasOwnProperty("readTime")) + object.readTime = $root.google.protobuf.Timestamp.toObject(message.readTime, options); + if (message.skippedResults != null && message.hasOwnProperty("skippedResults")) + object.skippedResults = message.skippedResults; + if (message.done != null && message.hasOwnProperty("done")) { + object.done = message.done; + if (options.oneofs) + object.continuationSelector = "done"; + } + if (message.explainMetrics != null && message.hasOwnProperty("explainMetrics")) + object.explainMetrics = $root.google.firestore.v1.ExplainMetrics.toObject(message.explainMetrics, options); + return object; + }; - /** - * FieldPresence enum. - * @name google.protobuf.FeatureSet.FieldPresence - * @enum {string} - * @property {string} FIELD_PRESENCE_UNKNOWN=FIELD_PRESENCE_UNKNOWN FIELD_PRESENCE_UNKNOWN value - * @property {string} EXPLICIT=EXPLICIT EXPLICIT value - * @property {string} IMPLICIT=IMPLICIT IMPLICIT value - * @property {string} LEGACY_REQUIRED=LEGACY_REQUIRED LEGACY_REQUIRED value - */ - FeatureSet.FieldPresence = (function() { - var valuesById = {}, values = Object.create(valuesById); - values[valuesById[0] = "FIELD_PRESENCE_UNKNOWN"] = "FIELD_PRESENCE_UNKNOWN"; - values[valuesById[1] = "EXPLICIT"] = "EXPLICIT"; - values[valuesById[2] = "IMPLICIT"] = "IMPLICIT"; - values[valuesById[3] = "LEGACY_REQUIRED"] = "LEGACY_REQUIRED"; - return values; - })(); + /** + * Converts this RunQueryResponse to JSON. + * @function toJSON + * @memberof google.firestore.v1.RunQueryResponse + * @instance + * @returns {Object.} JSON object + */ + RunQueryResponse.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; - /** - * EnumType enum. - * @name google.protobuf.FeatureSet.EnumType - * @enum {string} - * @property {string} ENUM_TYPE_UNKNOWN=ENUM_TYPE_UNKNOWN ENUM_TYPE_UNKNOWN value - * @property {string} OPEN=OPEN OPEN value - * @property {string} CLOSED=CLOSED CLOSED value - */ - FeatureSet.EnumType = (function() { - var valuesById = {}, values = Object.create(valuesById); - values[valuesById[0] = "ENUM_TYPE_UNKNOWN"] = "ENUM_TYPE_UNKNOWN"; - values[valuesById[1] = "OPEN"] = "OPEN"; - values[valuesById[2] = "CLOSED"] = "CLOSED"; - return values; - })(); + /** + * Gets the default type url for RunQueryResponse + * @function getTypeUrl + * @memberof google.firestore.v1.RunQueryResponse + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + RunQueryResponse.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.firestore.v1.RunQueryResponse"; + }; - /** - * RepeatedFieldEncoding enum. - * @name google.protobuf.FeatureSet.RepeatedFieldEncoding - * @enum {string} - * @property {string} REPEATED_FIELD_ENCODING_UNKNOWN=REPEATED_FIELD_ENCODING_UNKNOWN REPEATED_FIELD_ENCODING_UNKNOWN value - * @property {string} PACKED=PACKED PACKED value - * @property {string} EXPANDED=EXPANDED EXPANDED value - */ - FeatureSet.RepeatedFieldEncoding = (function() { - var valuesById = {}, values = Object.create(valuesById); - values[valuesById[0] = "REPEATED_FIELD_ENCODING_UNKNOWN"] = "REPEATED_FIELD_ENCODING_UNKNOWN"; - values[valuesById[1] = "PACKED"] = "PACKED"; - values[valuesById[2] = "EXPANDED"] = "EXPANDED"; - return values; + return RunQueryResponse; })(); - /** - * Utf8Validation enum. - * @name google.protobuf.FeatureSet.Utf8Validation - * @enum {string} - * @property {string} UTF8_VALIDATION_UNKNOWN=UTF8_VALIDATION_UNKNOWN UTF8_VALIDATION_UNKNOWN value - * @property {string} VERIFY=VERIFY VERIFY value - * @property {string} NONE=NONE NONE value - */ - FeatureSet.Utf8Validation = (function() { - var valuesById = {}, values = Object.create(valuesById); - values[valuesById[0] = "UTF8_VALIDATION_UNKNOWN"] = "UTF8_VALIDATION_UNKNOWN"; - values[valuesById[2] = "VERIFY"] = "VERIFY"; - values[valuesById[3] = "NONE"] = "NONE"; - return values; - })(); + v1.ExecutePipelineRequest = (function() { - /** - * MessageEncoding enum. - * @name google.protobuf.FeatureSet.MessageEncoding - * @enum {string} - * @property {string} MESSAGE_ENCODING_UNKNOWN=MESSAGE_ENCODING_UNKNOWN MESSAGE_ENCODING_UNKNOWN value - * @property {string} LENGTH_PREFIXED=LENGTH_PREFIXED LENGTH_PREFIXED value - * @property {string} DELIMITED=DELIMITED DELIMITED value - */ - FeatureSet.MessageEncoding = (function() { - var valuesById = {}, values = Object.create(valuesById); - values[valuesById[0] = "MESSAGE_ENCODING_UNKNOWN"] = "MESSAGE_ENCODING_UNKNOWN"; - values[valuesById[1] = "LENGTH_PREFIXED"] = "LENGTH_PREFIXED"; - values[valuesById[2] = "DELIMITED"] = "DELIMITED"; - return values; - })(); + /** + * Properties of an ExecutePipelineRequest. + * @memberof google.firestore.v1 + * @interface IExecutePipelineRequest + * @property {string|null} [database] ExecutePipelineRequest database + * @property {google.firestore.v1.IStructuredPipeline|null} [structuredPipeline] ExecutePipelineRequest structuredPipeline + * @property {Uint8Array|null} [transaction] ExecutePipelineRequest transaction + * @property {google.firestore.v1.ITransactionOptions|null} [newTransaction] ExecutePipelineRequest newTransaction + * @property {google.protobuf.ITimestamp|null} [readTime] ExecutePipelineRequest readTime + */ - /** - * JsonFormat enum. - * @name google.protobuf.FeatureSet.JsonFormat - * @enum {string} - * @property {string} JSON_FORMAT_UNKNOWN=JSON_FORMAT_UNKNOWN JSON_FORMAT_UNKNOWN value - * @property {string} ALLOW=ALLOW ALLOW value - * @property {string} LEGACY_BEST_EFFORT=LEGACY_BEST_EFFORT LEGACY_BEST_EFFORT value - */ - FeatureSet.JsonFormat = (function() { - var valuesById = {}, values = Object.create(valuesById); - values[valuesById[0] = "JSON_FORMAT_UNKNOWN"] = "JSON_FORMAT_UNKNOWN"; - values[valuesById[1] = "ALLOW"] = "ALLOW"; - values[valuesById[2] = "LEGACY_BEST_EFFORT"] = "LEGACY_BEST_EFFORT"; - return values; - })(); + /** + * Constructs a new ExecutePipelineRequest. + * @memberof google.firestore.v1 + * @classdesc Represents an ExecutePipelineRequest. + * @implements IExecutePipelineRequest + * @constructor + * @param {google.firestore.v1.IExecutePipelineRequest=} [properties] Properties to set + */ + function ExecutePipelineRequest(properties) { + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } - return FeatureSet; - })(); + /** + * ExecutePipelineRequest database. + * @member {string} database + * @memberof google.firestore.v1.ExecutePipelineRequest + * @instance + */ + ExecutePipelineRequest.prototype.database = ""; - protobuf.FeatureSetDefaults = (function() { + /** + * ExecutePipelineRequest structuredPipeline. + * @member {google.firestore.v1.IStructuredPipeline|null|undefined} structuredPipeline + * @memberof google.firestore.v1.ExecutePipelineRequest + * @instance + */ + ExecutePipelineRequest.prototype.structuredPipeline = null; - /** - * Properties of a FeatureSetDefaults. - * @memberof google.protobuf - * @interface IFeatureSetDefaults - * @property {Array.|null} [defaults] FeatureSetDefaults defaults - * @property {google.protobuf.Edition|null} [minimumEdition] FeatureSetDefaults minimumEdition - * @property {google.protobuf.Edition|null} [maximumEdition] FeatureSetDefaults maximumEdition - */ + /** + * ExecutePipelineRequest transaction. + * @member {Uint8Array|null|undefined} transaction + * @memberof google.firestore.v1.ExecutePipelineRequest + * @instance + */ + ExecutePipelineRequest.prototype.transaction = null; - /** - * Constructs a new FeatureSetDefaults. - * @memberof google.protobuf - * @classdesc Represents a FeatureSetDefaults. - * @implements IFeatureSetDefaults - * @constructor - * @param {google.protobuf.IFeatureSetDefaults=} [properties] Properties to set - */ - function FeatureSetDefaults(properties) { - this.defaults = []; - if (properties) - for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) - if (properties[keys[i]] != null) - this[keys[i]] = properties[keys[i]]; - } + /** + * ExecutePipelineRequest newTransaction. + * @member {google.firestore.v1.ITransactionOptions|null|undefined} newTransaction + * @memberof google.firestore.v1.ExecutePipelineRequest + * @instance + */ + ExecutePipelineRequest.prototype.newTransaction = null; - /** - * FeatureSetDefaults defaults. - * @member {Array.} defaults - * @memberof google.protobuf.FeatureSetDefaults - * @instance - */ - FeatureSetDefaults.prototype.defaults = $util.emptyArray; + /** + * ExecutePipelineRequest readTime. + * @member {google.protobuf.ITimestamp|null|undefined} readTime + * @memberof google.firestore.v1.ExecutePipelineRequest + * @instance + */ + ExecutePipelineRequest.prototype.readTime = null; - /** - * FeatureSetDefaults minimumEdition. - * @member {google.protobuf.Edition} minimumEdition - * @memberof google.protobuf.FeatureSetDefaults - * @instance - */ - FeatureSetDefaults.prototype.minimumEdition = 0; + // OneOf field names bound to virtual getters and setters + var $oneOfFields; - /** - * FeatureSetDefaults maximumEdition. - * @member {google.protobuf.Edition} maximumEdition - * @memberof google.protobuf.FeatureSetDefaults - * @instance - */ - FeatureSetDefaults.prototype.maximumEdition = 0; + /** + * ExecutePipelineRequest pipelineType. + * @member {"structuredPipeline"|undefined} pipelineType + * @memberof google.firestore.v1.ExecutePipelineRequest + * @instance + */ + Object.defineProperty(ExecutePipelineRequest.prototype, "pipelineType", { + get: $util.oneOfGetter($oneOfFields = ["structuredPipeline"]), + set: $util.oneOfSetter($oneOfFields) + }); - /** - * Creates a FeatureSetDefaults message from a plain object. Also converts values to their respective internal types. - * @function fromObject - * @memberof google.protobuf.FeatureSetDefaults - * @static - * @param {Object.} object Plain object - * @returns {google.protobuf.FeatureSetDefaults} FeatureSetDefaults - */ - FeatureSetDefaults.fromObject = function fromObject(object) { - if (object instanceof $root.google.protobuf.FeatureSetDefaults) - return object; - var message = new $root.google.protobuf.FeatureSetDefaults(); - if (object.defaults) { - if (!Array.isArray(object.defaults)) - throw TypeError(".google.protobuf.FeatureSetDefaults.defaults: array expected"); - message.defaults = []; - for (var i = 0; i < object.defaults.length; ++i) { - if (typeof object.defaults[i] !== "object") - throw TypeError(".google.protobuf.FeatureSetDefaults.defaults: object expected"); - message.defaults[i] = $root.google.protobuf.FeatureSetDefaults.FeatureSetEditionDefault.fromObject(object.defaults[i]); + /** + * ExecutePipelineRequest consistencySelector. + * @member {"transaction"|"newTransaction"|"readTime"|undefined} consistencySelector + * @memberof google.firestore.v1.ExecutePipelineRequest + * @instance + */ + Object.defineProperty(ExecutePipelineRequest.prototype, "consistencySelector", { + get: $util.oneOfGetter($oneOfFields = ["transaction", "newTransaction", "readTime"]), + set: $util.oneOfSetter($oneOfFields) + }); + + /** + * Creates an ExecutePipelineRequest message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.firestore.v1.ExecutePipelineRequest + * @static + * @param {Object.} object Plain object + * @returns {google.firestore.v1.ExecutePipelineRequest} ExecutePipelineRequest + */ + ExecutePipelineRequest.fromObject = function fromObject(object) { + if (object instanceof $root.google.firestore.v1.ExecutePipelineRequest) + return object; + var message = new $root.google.firestore.v1.ExecutePipelineRequest(); + if (object.database != null) + message.database = String(object.database); + if (object.structuredPipeline != null) { + if (typeof object.structuredPipeline !== "object") + throw TypeError(".google.firestore.v1.ExecutePipelineRequest.structuredPipeline: object expected"); + message.structuredPipeline = $root.google.firestore.v1.StructuredPipeline.fromObject(object.structuredPipeline); } - } - switch (object.minimumEdition) { - default: - if (typeof object.minimumEdition === "number") { - message.minimumEdition = object.minimumEdition; - break; + if (object.transaction != null) + if (typeof object.transaction === "string") + $util.base64.decode(object.transaction, message.transaction = $util.newBuffer($util.base64.length(object.transaction)), 0); + else if (object.transaction.length >= 0) + message.transaction = object.transaction; + if (object.newTransaction != null) { + if (typeof object.newTransaction !== "object") + throw TypeError(".google.firestore.v1.ExecutePipelineRequest.newTransaction: object expected"); + message.newTransaction = $root.google.firestore.v1.TransactionOptions.fromObject(object.newTransaction); } - break; - case "EDITION_UNKNOWN": - case 0: - message.minimumEdition = 0; - break; - case "EDITION_LEGACY": - case 900: - message.minimumEdition = 900; - break; - case "EDITION_PROTO2": - case 998: - message.minimumEdition = 998; - break; - case "EDITION_PROTO3": - case 999: - message.minimumEdition = 999; - break; - case "EDITION_2023": - case 1000: - message.minimumEdition = 1000; - break; - case "EDITION_2024": - case 1001: - message.minimumEdition = 1001; - break; - case "EDITION_1_TEST_ONLY": - case 1: - message.minimumEdition = 1; - break; - case "EDITION_2_TEST_ONLY": - case 2: - message.minimumEdition = 2; - break; - case "EDITION_99997_TEST_ONLY": - case 99997: - message.minimumEdition = 99997; - break; - case "EDITION_99998_TEST_ONLY": - case 99998: - message.minimumEdition = 99998; - break; - case "EDITION_99999_TEST_ONLY": - case 99999: - message.minimumEdition = 99999; - break; - case "EDITION_MAX": - case 2147483647: - message.minimumEdition = 2147483647; - break; - } - switch (object.maximumEdition) { - default: - if (typeof object.maximumEdition === "number") { - message.maximumEdition = object.maximumEdition; - break; + if (object.readTime != null) { + if (typeof object.readTime !== "object") + throw TypeError(".google.firestore.v1.ExecutePipelineRequest.readTime: object expected"); + message.readTime = $root.google.protobuf.Timestamp.fromObject(object.readTime); } - break; - case "EDITION_UNKNOWN": - case 0: - message.maximumEdition = 0; - break; - case "EDITION_LEGACY": - case 900: - message.maximumEdition = 900; - break; - case "EDITION_PROTO2": - case 998: - message.maximumEdition = 998; - break; - case "EDITION_PROTO3": - case 999: - message.maximumEdition = 999; - break; - case "EDITION_2023": - case 1000: - message.maximumEdition = 1000; - break; - case "EDITION_2024": - case 1001: - message.maximumEdition = 1001; - break; - case "EDITION_1_TEST_ONLY": - case 1: - message.maximumEdition = 1; - break; - case "EDITION_2_TEST_ONLY": - case 2: - message.maximumEdition = 2; - break; - case "EDITION_99997_TEST_ONLY": - case 99997: - message.maximumEdition = 99997; - break; - case "EDITION_99998_TEST_ONLY": - case 99998: - message.maximumEdition = 99998; - break; - case "EDITION_99999_TEST_ONLY": - case 99999: - message.maximumEdition = 99999; - break; - case "EDITION_MAX": - case 2147483647: - message.maximumEdition = 2147483647; - break; - } - return message; - }; + return message; + }; + + /** + * Creates a plain object from an ExecutePipelineRequest message. Also converts values to other types if specified. + * @function toObject + * @memberof google.firestore.v1.ExecutePipelineRequest + * @static + * @param {google.firestore.v1.ExecutePipelineRequest} message ExecutePipelineRequest + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + ExecutePipelineRequest.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.defaults) + object.database = ""; + if (message.database != null && message.hasOwnProperty("database")) + object.database = message.database; + if (message.structuredPipeline != null && message.hasOwnProperty("structuredPipeline")) { + object.structuredPipeline = $root.google.firestore.v1.StructuredPipeline.toObject(message.structuredPipeline, options); + if (options.oneofs) + object.pipelineType = "structuredPipeline"; + } + if (message.transaction != null && message.hasOwnProperty("transaction")) { + object.transaction = options.bytes === String ? $util.base64.encode(message.transaction, 0, message.transaction.length) : options.bytes === Array ? Array.prototype.slice.call(message.transaction) : message.transaction; + if (options.oneofs) + object.consistencySelector = "transaction"; + } + if (message.newTransaction != null && message.hasOwnProperty("newTransaction")) { + object.newTransaction = $root.google.firestore.v1.TransactionOptions.toObject(message.newTransaction, options); + if (options.oneofs) + object.consistencySelector = "newTransaction"; + } + if (message.readTime != null && message.hasOwnProperty("readTime")) { + object.readTime = $root.google.protobuf.Timestamp.toObject(message.readTime, options); + if (options.oneofs) + object.consistencySelector = "readTime"; + } + return object; + }; - /** - * Creates a plain object from a FeatureSetDefaults message. Also converts values to other types if specified. - * @function toObject - * @memberof google.protobuf.FeatureSetDefaults - * @static - * @param {google.protobuf.FeatureSetDefaults} message FeatureSetDefaults - * @param {$protobuf.IConversionOptions} [options] Conversion options - * @returns {Object.} Plain object - */ - FeatureSetDefaults.toObject = function toObject(message, options) { - if (!options) - options = {}; - var object = {}; - if (options.arrays || options.defaults) - object.defaults = []; - if (options.defaults) { - object.minimumEdition = options.enums === String ? "EDITION_UNKNOWN" : 0; - object.maximumEdition = options.enums === String ? "EDITION_UNKNOWN" : 0; - } - if (message.defaults && message.defaults.length) { - object.defaults = []; - for (var j = 0; j < message.defaults.length; ++j) - object.defaults[j] = $root.google.protobuf.FeatureSetDefaults.FeatureSetEditionDefault.toObject(message.defaults[j], options); - } - if (message.minimumEdition != null && message.hasOwnProperty("minimumEdition")) - object.minimumEdition = options.enums === String ? $root.google.protobuf.Edition[message.minimumEdition] === undefined ? message.minimumEdition : $root.google.protobuf.Edition[message.minimumEdition] : message.minimumEdition; - if (message.maximumEdition != null && message.hasOwnProperty("maximumEdition")) - object.maximumEdition = options.enums === String ? $root.google.protobuf.Edition[message.maximumEdition] === undefined ? message.maximumEdition : $root.google.protobuf.Edition[message.maximumEdition] : message.maximumEdition; - return object; - }; + /** + * Converts this ExecutePipelineRequest to JSON. + * @function toJSON + * @memberof google.firestore.v1.ExecutePipelineRequest + * @instance + * @returns {Object.} JSON object + */ + ExecutePipelineRequest.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; - /** - * Converts this FeatureSetDefaults to JSON. - * @function toJSON - * @memberof google.protobuf.FeatureSetDefaults - * @instance - * @returns {Object.} JSON object - */ - FeatureSetDefaults.prototype.toJSON = function toJSON() { - return this.constructor.toObject(this, $protobuf.util.toJSONOptions); - }; + /** + * Gets the default type url for ExecutePipelineRequest + * @function getTypeUrl + * @memberof google.firestore.v1.ExecutePipelineRequest + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + ExecutePipelineRequest.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.firestore.v1.ExecutePipelineRequest"; + }; - /** - * Gets the default type url for FeatureSetDefaults - * @function getTypeUrl - * @memberof google.protobuf.FeatureSetDefaults - * @static - * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") - * @returns {string} The default type url - */ - FeatureSetDefaults.getTypeUrl = function getTypeUrl(typeUrlPrefix) { - if (typeUrlPrefix === undefined) { - typeUrlPrefix = "type.googleapis.com"; - } - return typeUrlPrefix + "/google.protobuf.FeatureSetDefaults"; - }; + return ExecutePipelineRequest; + })(); - FeatureSetDefaults.FeatureSetEditionDefault = (function() { + v1.ExecutePipelineResponse = (function() { /** - * Properties of a FeatureSetEditionDefault. - * @memberof google.protobuf.FeatureSetDefaults - * @interface IFeatureSetEditionDefault - * @property {google.protobuf.Edition|null} [edition] FeatureSetEditionDefault edition - * @property {google.protobuf.IFeatureSet|null} [overridableFeatures] FeatureSetEditionDefault overridableFeatures - * @property {google.protobuf.IFeatureSet|null} [fixedFeatures] FeatureSetEditionDefault fixedFeatures + * Properties of an ExecutePipelineResponse. + * @memberof google.firestore.v1 + * @interface IExecutePipelineResponse + * @property {Uint8Array|null} [transaction] ExecutePipelineResponse transaction + * @property {Array.|null} [results] ExecutePipelineResponse results + * @property {google.protobuf.ITimestamp|null} [executionTime] ExecutePipelineResponse executionTime */ /** - * Constructs a new FeatureSetEditionDefault. - * @memberof google.protobuf.FeatureSetDefaults - * @classdesc Represents a FeatureSetEditionDefault. - * @implements IFeatureSetEditionDefault + * Constructs a new ExecutePipelineResponse. + * @memberof google.firestore.v1 + * @classdesc Represents an ExecutePipelineResponse. + * @implements IExecutePipelineResponse * @constructor - * @param {google.protobuf.FeatureSetDefaults.IFeatureSetEditionDefault=} [properties] Properties to set + * @param {google.firestore.v1.IExecutePipelineResponse=} [properties] Properties to set */ - function FeatureSetEditionDefault(properties) { + function ExecutePipelineResponse(properties) { + this.results = []; if (properties) for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) if (properties[keys[i]] != null) @@ -7782,301 +6180,153 @@ } /** - * FeatureSetEditionDefault edition. - * @member {google.protobuf.Edition} edition - * @memberof google.protobuf.FeatureSetDefaults.FeatureSetEditionDefault + * ExecutePipelineResponse transaction. + * @member {Uint8Array} transaction + * @memberof google.firestore.v1.ExecutePipelineResponse * @instance */ - FeatureSetEditionDefault.prototype.edition = 0; + ExecutePipelineResponse.prototype.transaction = $util.newBuffer([]); /** - * FeatureSetEditionDefault overridableFeatures. - * @member {google.protobuf.IFeatureSet|null|undefined} overridableFeatures - * @memberof google.protobuf.FeatureSetDefaults.FeatureSetEditionDefault + * ExecutePipelineResponse results. + * @member {Array.} results + * @memberof google.firestore.v1.ExecutePipelineResponse * @instance */ - FeatureSetEditionDefault.prototype.overridableFeatures = null; + ExecutePipelineResponse.prototype.results = $util.emptyArray; /** - * FeatureSetEditionDefault fixedFeatures. - * @member {google.protobuf.IFeatureSet|null|undefined} fixedFeatures - * @memberof google.protobuf.FeatureSetDefaults.FeatureSetEditionDefault + * ExecutePipelineResponse executionTime. + * @member {google.protobuf.ITimestamp|null|undefined} executionTime + * @memberof google.firestore.v1.ExecutePipelineResponse * @instance */ - FeatureSetEditionDefault.prototype.fixedFeatures = null; + ExecutePipelineResponse.prototype.executionTime = null; /** - * Creates a FeatureSetEditionDefault message from a plain object. Also converts values to their respective internal types. + * Creates an ExecutePipelineResponse message from a plain object. Also converts values to their respective internal types. * @function fromObject - * @memberof google.protobuf.FeatureSetDefaults.FeatureSetEditionDefault + * @memberof google.firestore.v1.ExecutePipelineResponse * @static * @param {Object.} object Plain object - * @returns {google.protobuf.FeatureSetDefaults.FeatureSetEditionDefault} FeatureSetEditionDefault + * @returns {google.firestore.v1.ExecutePipelineResponse} ExecutePipelineResponse */ - FeatureSetEditionDefault.fromObject = function fromObject(object) { - if (object instanceof $root.google.protobuf.FeatureSetDefaults.FeatureSetEditionDefault) + ExecutePipelineResponse.fromObject = function fromObject(object) { + if (object instanceof $root.google.firestore.v1.ExecutePipelineResponse) return object; - var message = new $root.google.protobuf.FeatureSetDefaults.FeatureSetEditionDefault(); - switch (object.edition) { - default: - if (typeof object.edition === "number") { - message.edition = object.edition; - break; + var message = new $root.google.firestore.v1.ExecutePipelineResponse(); + if (object.transaction != null) + if (typeof object.transaction === "string") + $util.base64.decode(object.transaction, message.transaction = $util.newBuffer($util.base64.length(object.transaction)), 0); + else if (object.transaction.length >= 0) + message.transaction = object.transaction; + if (object.results) { + if (!Array.isArray(object.results)) + throw TypeError(".google.firestore.v1.ExecutePipelineResponse.results: array expected"); + message.results = []; + for (var i = 0; i < object.results.length; ++i) { + if (typeof object.results[i] !== "object") + throw TypeError(".google.firestore.v1.ExecutePipelineResponse.results: object expected"); + message.results[i] = $root.google.firestore.v1.Document.fromObject(object.results[i]); } - break; - case "EDITION_UNKNOWN": - case 0: - message.edition = 0; - break; - case "EDITION_LEGACY": - case 900: - message.edition = 900; - break; - case "EDITION_PROTO2": - case 998: - message.edition = 998; - break; - case "EDITION_PROTO3": - case 999: - message.edition = 999; - break; - case "EDITION_2023": - case 1000: - message.edition = 1000; - break; - case "EDITION_2024": - case 1001: - message.edition = 1001; - break; - case "EDITION_1_TEST_ONLY": - case 1: - message.edition = 1; - break; - case "EDITION_2_TEST_ONLY": - case 2: - message.edition = 2; - break; - case "EDITION_99997_TEST_ONLY": - case 99997: - message.edition = 99997; - break; - case "EDITION_99998_TEST_ONLY": - case 99998: - message.edition = 99998; - break; - case "EDITION_99999_TEST_ONLY": - case 99999: - message.edition = 99999; - break; - case "EDITION_MAX": - case 2147483647: - message.edition = 2147483647; - break; } - if (object.overridableFeatures != null) { - if (typeof object.overridableFeatures !== "object") - throw TypeError(".google.protobuf.FeatureSetDefaults.FeatureSetEditionDefault.overridableFeatures: object expected"); - message.overridableFeatures = $root.google.protobuf.FeatureSet.fromObject(object.overridableFeatures); - } - if (object.fixedFeatures != null) { - if (typeof object.fixedFeatures !== "object") - throw TypeError(".google.protobuf.FeatureSetDefaults.FeatureSetEditionDefault.fixedFeatures: object expected"); - message.fixedFeatures = $root.google.protobuf.FeatureSet.fromObject(object.fixedFeatures); + if (object.executionTime != null) { + if (typeof object.executionTime !== "object") + throw TypeError(".google.firestore.v1.ExecutePipelineResponse.executionTime: object expected"); + message.executionTime = $root.google.protobuf.Timestamp.fromObject(object.executionTime); } return message; }; /** - * Creates a plain object from a FeatureSetEditionDefault message. Also converts values to other types if specified. + * Creates a plain object from an ExecutePipelineResponse message. Also converts values to other types if specified. * @function toObject - * @memberof google.protobuf.FeatureSetDefaults.FeatureSetEditionDefault + * @memberof google.firestore.v1.ExecutePipelineResponse * @static - * @param {google.protobuf.FeatureSetDefaults.FeatureSetEditionDefault} message FeatureSetEditionDefault + * @param {google.firestore.v1.ExecutePipelineResponse} message ExecutePipelineResponse * @param {$protobuf.IConversionOptions} [options] Conversion options * @returns {Object.} Plain object */ - FeatureSetEditionDefault.toObject = function toObject(message, options) { + ExecutePipelineResponse.toObject = function toObject(message, options) { if (!options) options = {}; var object = {}; + if (options.arrays || options.defaults) + object.results = []; if (options.defaults) { - object.edition = options.enums === String ? "EDITION_UNKNOWN" : 0; - object.overridableFeatures = null; - object.fixedFeatures = null; + if (options.bytes === String) + object.transaction = ""; + else { + object.transaction = []; + if (options.bytes !== Array) + object.transaction = $util.newBuffer(object.transaction); + } + object.executionTime = null; } - if (message.edition != null && message.hasOwnProperty("edition")) - object.edition = options.enums === String ? $root.google.protobuf.Edition[message.edition] === undefined ? message.edition : $root.google.protobuf.Edition[message.edition] : message.edition; - if (message.overridableFeatures != null && message.hasOwnProperty("overridableFeatures")) - object.overridableFeatures = $root.google.protobuf.FeatureSet.toObject(message.overridableFeatures, options); - if (message.fixedFeatures != null && message.hasOwnProperty("fixedFeatures")) - object.fixedFeatures = $root.google.protobuf.FeatureSet.toObject(message.fixedFeatures, options); + if (message.transaction != null && message.hasOwnProperty("transaction")) + object.transaction = options.bytes === String ? $util.base64.encode(message.transaction, 0, message.transaction.length) : options.bytes === Array ? Array.prototype.slice.call(message.transaction) : message.transaction; + if (message.results && message.results.length) { + object.results = []; + for (var j = 0; j < message.results.length; ++j) + object.results[j] = $root.google.firestore.v1.Document.toObject(message.results[j], options); + } + if (message.executionTime != null && message.hasOwnProperty("executionTime")) + object.executionTime = $root.google.protobuf.Timestamp.toObject(message.executionTime, options); return object; }; /** - * Converts this FeatureSetEditionDefault to JSON. + * Converts this ExecutePipelineResponse to JSON. * @function toJSON - * @memberof google.protobuf.FeatureSetDefaults.FeatureSetEditionDefault + * @memberof google.firestore.v1.ExecutePipelineResponse * @instance * @returns {Object.} JSON object */ - FeatureSetEditionDefault.prototype.toJSON = function toJSON() { + ExecutePipelineResponse.prototype.toJSON = function toJSON() { return this.constructor.toObject(this, $protobuf.util.toJSONOptions); }; /** - * Gets the default type url for FeatureSetEditionDefault + * Gets the default type url for ExecutePipelineResponse * @function getTypeUrl - * @memberof google.protobuf.FeatureSetDefaults.FeatureSetEditionDefault + * @memberof google.firestore.v1.ExecutePipelineResponse * @static * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") * @returns {string} The default type url */ - FeatureSetEditionDefault.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + ExecutePipelineResponse.getTypeUrl = function getTypeUrl(typeUrlPrefix) { if (typeUrlPrefix === undefined) { typeUrlPrefix = "type.googleapis.com"; } - return typeUrlPrefix + "/google.protobuf.FeatureSetDefaults.FeatureSetEditionDefault"; + return typeUrlPrefix + "/google.firestore.v1.ExecutePipelineResponse"; }; - return FeatureSetEditionDefault; + return ExecutePipelineResponse; })(); - return FeatureSetDefaults; - })(); - - protobuf.SourceCodeInfo = (function() { - - /** - * Properties of a SourceCodeInfo. - * @memberof google.protobuf - * @interface ISourceCodeInfo - * @property {Array.|null} [location] SourceCodeInfo location - */ - - /** - * Constructs a new SourceCodeInfo. - * @memberof google.protobuf - * @classdesc Represents a SourceCodeInfo. - * @implements ISourceCodeInfo - * @constructor - * @param {google.protobuf.ISourceCodeInfo=} [properties] Properties to set - */ - function SourceCodeInfo(properties) { - this.location = []; - if (properties) - for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) - if (properties[keys[i]] != null) - this[keys[i]] = properties[keys[i]]; - } - - /** - * SourceCodeInfo location. - * @member {Array.} location - * @memberof google.protobuf.SourceCodeInfo - * @instance - */ - SourceCodeInfo.prototype.location = $util.emptyArray; - - /** - * Creates a SourceCodeInfo message from a plain object. Also converts values to their respective internal types. - * @function fromObject - * @memberof google.protobuf.SourceCodeInfo - * @static - * @param {Object.} object Plain object - * @returns {google.protobuf.SourceCodeInfo} SourceCodeInfo - */ - SourceCodeInfo.fromObject = function fromObject(object) { - if (object instanceof $root.google.protobuf.SourceCodeInfo) - return object; - var message = new $root.google.protobuf.SourceCodeInfo(); - if (object.location) { - if (!Array.isArray(object.location)) - throw TypeError(".google.protobuf.SourceCodeInfo.location: array expected"); - message.location = []; - for (var i = 0; i < object.location.length; ++i) { - if (typeof object.location[i] !== "object") - throw TypeError(".google.protobuf.SourceCodeInfo.location: object expected"); - message.location[i] = $root.google.protobuf.SourceCodeInfo.Location.fromObject(object.location[i]); - } - } - return message; - }; - - /** - * Creates a plain object from a SourceCodeInfo message. Also converts values to other types if specified. - * @function toObject - * @memberof google.protobuf.SourceCodeInfo - * @static - * @param {google.protobuf.SourceCodeInfo} message SourceCodeInfo - * @param {$protobuf.IConversionOptions} [options] Conversion options - * @returns {Object.} Plain object - */ - SourceCodeInfo.toObject = function toObject(message, options) { - if (!options) - options = {}; - var object = {}; - if (options.arrays || options.defaults) - object.location = []; - if (message.location && message.location.length) { - object.location = []; - for (var j = 0; j < message.location.length; ++j) - object.location[j] = $root.google.protobuf.SourceCodeInfo.Location.toObject(message.location[j], options); - } - return object; - }; - - /** - * Converts this SourceCodeInfo to JSON. - * @function toJSON - * @memberof google.protobuf.SourceCodeInfo - * @instance - * @returns {Object.} JSON object - */ - SourceCodeInfo.prototype.toJSON = function toJSON() { - return this.constructor.toObject(this, $protobuf.util.toJSONOptions); - }; - - /** - * Gets the default type url for SourceCodeInfo - * @function getTypeUrl - * @memberof google.protobuf.SourceCodeInfo - * @static - * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") - * @returns {string} The default type url - */ - SourceCodeInfo.getTypeUrl = function getTypeUrl(typeUrlPrefix) { - if (typeUrlPrefix === undefined) { - typeUrlPrefix = "type.googleapis.com"; - } - return typeUrlPrefix + "/google.protobuf.SourceCodeInfo"; - }; - - SourceCodeInfo.Location = (function() { + v1.RunAggregationQueryRequest = (function() { /** - * Properties of a Location. - * @memberof google.protobuf.SourceCodeInfo - * @interface ILocation - * @property {Array.|null} [path] Location path - * @property {Array.|null} [span] Location span - * @property {string|null} [leadingComments] Location leadingComments - * @property {string|null} [trailingComments] Location trailingComments - * @property {Array.|null} [leadingDetachedComments] Location leadingDetachedComments + * Properties of a RunAggregationQueryRequest. + * @memberof google.firestore.v1 + * @interface IRunAggregationQueryRequest + * @property {string|null} [parent] RunAggregationQueryRequest parent + * @property {google.firestore.v1.IStructuredAggregationQuery|null} [structuredAggregationQuery] RunAggregationQueryRequest structuredAggregationQuery + * @property {Uint8Array|null} [transaction] RunAggregationQueryRequest transaction + * @property {google.firestore.v1.ITransactionOptions|null} [newTransaction] RunAggregationQueryRequest newTransaction + * @property {google.protobuf.ITimestamp|null} [readTime] RunAggregationQueryRequest readTime + * @property {google.firestore.v1.IExplainOptions|null} [explainOptions] RunAggregationQueryRequest explainOptions */ /** - * Constructs a new Location. - * @memberof google.protobuf.SourceCodeInfo - * @classdesc Represents a Location. - * @implements ILocation + * Constructs a new RunAggregationQueryRequest. + * @memberof google.firestore.v1 + * @classdesc Represents a RunAggregationQueryRequest. + * @implements IRunAggregationQueryRequest * @constructor - * @param {google.protobuf.SourceCodeInfo.ILocation=} [properties] Properties to set + * @param {google.firestore.v1.IRunAggregationQueryRequest=} [properties] Properties to set */ - function Location(properties) { - this.path = []; - this.span = []; - this.leadingDetachedComments = []; + function RunAggregationQueryRequest(properties) { if (properties) for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) if (properties[keys[i]] != null) @@ -8084,1864 +6334,2129 @@ } /** - * Location path. - * @member {Array.} path - * @memberof google.protobuf.SourceCodeInfo.Location + * RunAggregationQueryRequest parent. + * @member {string} parent + * @memberof google.firestore.v1.RunAggregationQueryRequest * @instance */ - Location.prototype.path = $util.emptyArray; + RunAggregationQueryRequest.prototype.parent = ""; /** - * Location span. - * @member {Array.} span - * @memberof google.protobuf.SourceCodeInfo.Location + * RunAggregationQueryRequest structuredAggregationQuery. + * @member {google.firestore.v1.IStructuredAggregationQuery|null|undefined} structuredAggregationQuery + * @memberof google.firestore.v1.RunAggregationQueryRequest * @instance */ - Location.prototype.span = $util.emptyArray; + RunAggregationQueryRequest.prototype.structuredAggregationQuery = null; /** - * Location leadingComments. - * @member {string} leadingComments - * @memberof google.protobuf.SourceCodeInfo.Location + * RunAggregationQueryRequest transaction. + * @member {Uint8Array|null|undefined} transaction + * @memberof google.firestore.v1.RunAggregationQueryRequest * @instance */ - Location.prototype.leadingComments = ""; + RunAggregationQueryRequest.prototype.transaction = null; /** - * Location trailingComments. - * @member {string} trailingComments - * @memberof google.protobuf.SourceCodeInfo.Location + * RunAggregationQueryRequest newTransaction. + * @member {google.firestore.v1.ITransactionOptions|null|undefined} newTransaction + * @memberof google.firestore.v1.RunAggregationQueryRequest * @instance */ - Location.prototype.trailingComments = ""; + RunAggregationQueryRequest.prototype.newTransaction = null; /** - * Location leadingDetachedComments. - * @member {Array.} leadingDetachedComments - * @memberof google.protobuf.SourceCodeInfo.Location + * RunAggregationQueryRequest readTime. + * @member {google.protobuf.ITimestamp|null|undefined} readTime + * @memberof google.firestore.v1.RunAggregationQueryRequest * @instance */ - Location.prototype.leadingDetachedComments = $util.emptyArray; + RunAggregationQueryRequest.prototype.readTime = null; /** - * Creates a Location message from a plain object. Also converts values to their respective internal types. + * RunAggregationQueryRequest explainOptions. + * @member {google.firestore.v1.IExplainOptions|null|undefined} explainOptions + * @memberof google.firestore.v1.RunAggregationQueryRequest + * @instance + */ + RunAggregationQueryRequest.prototype.explainOptions = null; + + // OneOf field names bound to virtual getters and setters + var $oneOfFields; + + /** + * RunAggregationQueryRequest queryType. + * @member {"structuredAggregationQuery"|undefined} queryType + * @memberof google.firestore.v1.RunAggregationQueryRequest + * @instance + */ + Object.defineProperty(RunAggregationQueryRequest.prototype, "queryType", { + get: $util.oneOfGetter($oneOfFields = ["structuredAggregationQuery"]), + set: $util.oneOfSetter($oneOfFields) + }); + + /** + * RunAggregationQueryRequest consistencySelector. + * @member {"transaction"|"newTransaction"|"readTime"|undefined} consistencySelector + * @memberof google.firestore.v1.RunAggregationQueryRequest + * @instance + */ + Object.defineProperty(RunAggregationQueryRequest.prototype, "consistencySelector", { + get: $util.oneOfGetter($oneOfFields = ["transaction", "newTransaction", "readTime"]), + set: $util.oneOfSetter($oneOfFields) + }); + + /** + * Creates a RunAggregationQueryRequest message from a plain object. Also converts values to their respective internal types. * @function fromObject - * @memberof google.protobuf.SourceCodeInfo.Location + * @memberof google.firestore.v1.RunAggregationQueryRequest * @static * @param {Object.} object Plain object - * @returns {google.protobuf.SourceCodeInfo.Location} Location + * @returns {google.firestore.v1.RunAggregationQueryRequest} RunAggregationQueryRequest */ - Location.fromObject = function fromObject(object) { - if (object instanceof $root.google.protobuf.SourceCodeInfo.Location) + RunAggregationQueryRequest.fromObject = function fromObject(object) { + if (object instanceof $root.google.firestore.v1.RunAggregationQueryRequest) return object; - var message = new $root.google.protobuf.SourceCodeInfo.Location(); - if (object.path) { - if (!Array.isArray(object.path)) - throw TypeError(".google.protobuf.SourceCodeInfo.Location.path: array expected"); - message.path = []; - for (var i = 0; i < object.path.length; ++i) - message.path[i] = object.path[i] | 0; + var message = new $root.google.firestore.v1.RunAggregationQueryRequest(); + if (object.parent != null) + message.parent = String(object.parent); + if (object.structuredAggregationQuery != null) { + if (typeof object.structuredAggregationQuery !== "object") + throw TypeError(".google.firestore.v1.RunAggregationQueryRequest.structuredAggregationQuery: object expected"); + message.structuredAggregationQuery = $root.google.firestore.v1.StructuredAggregationQuery.fromObject(object.structuredAggregationQuery); } - if (object.span) { - if (!Array.isArray(object.span)) - throw TypeError(".google.protobuf.SourceCodeInfo.Location.span: array expected"); - message.span = []; - for (var i = 0; i < object.span.length; ++i) - message.span[i] = object.span[i] | 0; + if (object.transaction != null) + if (typeof object.transaction === "string") + $util.base64.decode(object.transaction, message.transaction = $util.newBuffer($util.base64.length(object.transaction)), 0); + else if (object.transaction.length >= 0) + message.transaction = object.transaction; + if (object.newTransaction != null) { + if (typeof object.newTransaction !== "object") + throw TypeError(".google.firestore.v1.RunAggregationQueryRequest.newTransaction: object expected"); + message.newTransaction = $root.google.firestore.v1.TransactionOptions.fromObject(object.newTransaction); } - if (object.leadingComments != null) - message.leadingComments = String(object.leadingComments); - if (object.trailingComments != null) - message.trailingComments = String(object.trailingComments); - if (object.leadingDetachedComments) { - if (!Array.isArray(object.leadingDetachedComments)) - throw TypeError(".google.protobuf.SourceCodeInfo.Location.leadingDetachedComments: array expected"); - message.leadingDetachedComments = []; - for (var i = 0; i < object.leadingDetachedComments.length; ++i) - message.leadingDetachedComments[i] = String(object.leadingDetachedComments[i]); + if (object.readTime != null) { + if (typeof object.readTime !== "object") + throw TypeError(".google.firestore.v1.RunAggregationQueryRequest.readTime: object expected"); + message.readTime = $root.google.protobuf.Timestamp.fromObject(object.readTime); + } + if (object.explainOptions != null) { + if (typeof object.explainOptions !== "object") + throw TypeError(".google.firestore.v1.RunAggregationQueryRequest.explainOptions: object expected"); + message.explainOptions = $root.google.firestore.v1.ExplainOptions.fromObject(object.explainOptions); } return message; }; /** - * Creates a plain object from a Location message. Also converts values to other types if specified. + * Creates a plain object from a RunAggregationQueryRequest message. Also converts values to other types if specified. * @function toObject - * @memberof google.protobuf.SourceCodeInfo.Location + * @memberof google.firestore.v1.RunAggregationQueryRequest * @static - * @param {google.protobuf.SourceCodeInfo.Location} message Location + * @param {google.firestore.v1.RunAggregationQueryRequest} message RunAggregationQueryRequest * @param {$protobuf.IConversionOptions} [options] Conversion options * @returns {Object.} Plain object */ - Location.toObject = function toObject(message, options) { + RunAggregationQueryRequest.toObject = function toObject(message, options) { if (!options) options = {}; var object = {}; - if (options.arrays || options.defaults) { - object.path = []; - object.span = []; - object.leadingDetachedComments = []; - } if (options.defaults) { - object.leadingComments = ""; - object.trailingComments = ""; + object.parent = ""; + object.explainOptions = null; } - if (message.path && message.path.length) { - object.path = []; - for (var j = 0; j < message.path.length; ++j) - object.path[j] = message.path[j]; + if (message.parent != null && message.hasOwnProperty("parent")) + object.parent = message.parent; + if (message.structuredAggregationQuery != null && message.hasOwnProperty("structuredAggregationQuery")) { + object.structuredAggregationQuery = $root.google.firestore.v1.StructuredAggregationQuery.toObject(message.structuredAggregationQuery, options); + if (options.oneofs) + object.queryType = "structuredAggregationQuery"; } - if (message.span && message.span.length) { - object.span = []; - for (var j = 0; j < message.span.length; ++j) - object.span[j] = message.span[j]; + if (message.transaction != null && message.hasOwnProperty("transaction")) { + object.transaction = options.bytes === String ? $util.base64.encode(message.transaction, 0, message.transaction.length) : options.bytes === Array ? Array.prototype.slice.call(message.transaction) : message.transaction; + if (options.oneofs) + object.consistencySelector = "transaction"; } - if (message.leadingComments != null && message.hasOwnProperty("leadingComments")) - object.leadingComments = message.leadingComments; - if (message.trailingComments != null && message.hasOwnProperty("trailingComments")) - object.trailingComments = message.trailingComments; - if (message.leadingDetachedComments && message.leadingDetachedComments.length) { - object.leadingDetachedComments = []; - for (var j = 0; j < message.leadingDetachedComments.length; ++j) - object.leadingDetachedComments[j] = message.leadingDetachedComments[j]; + if (message.newTransaction != null && message.hasOwnProperty("newTransaction")) { + object.newTransaction = $root.google.firestore.v1.TransactionOptions.toObject(message.newTransaction, options); + if (options.oneofs) + object.consistencySelector = "newTransaction"; + } + if (message.readTime != null && message.hasOwnProperty("readTime")) { + object.readTime = $root.google.protobuf.Timestamp.toObject(message.readTime, options); + if (options.oneofs) + object.consistencySelector = "readTime"; } + if (message.explainOptions != null && message.hasOwnProperty("explainOptions")) + object.explainOptions = $root.google.firestore.v1.ExplainOptions.toObject(message.explainOptions, options); return object; }; /** - * Converts this Location to JSON. + * Converts this RunAggregationQueryRequest to JSON. * @function toJSON - * @memberof google.protobuf.SourceCodeInfo.Location + * @memberof google.firestore.v1.RunAggregationQueryRequest * @instance * @returns {Object.} JSON object */ - Location.prototype.toJSON = function toJSON() { + RunAggregationQueryRequest.prototype.toJSON = function toJSON() { return this.constructor.toObject(this, $protobuf.util.toJSONOptions); }; /** - * Gets the default type url for Location + * Gets the default type url for RunAggregationQueryRequest * @function getTypeUrl - * @memberof google.protobuf.SourceCodeInfo.Location + * @memberof google.firestore.v1.RunAggregationQueryRequest * @static * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") * @returns {string} The default type url */ - Location.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + RunAggregationQueryRequest.getTypeUrl = function getTypeUrl(typeUrlPrefix) { if (typeUrlPrefix === undefined) { typeUrlPrefix = "type.googleapis.com"; } - return typeUrlPrefix + "/google.protobuf.SourceCodeInfo.Location"; + return typeUrlPrefix + "/google.firestore.v1.RunAggregationQueryRequest"; }; - return Location; + return RunAggregationQueryRequest; })(); - return SourceCodeInfo; - })(); - - protobuf.GeneratedCodeInfo = (function() { - - /** - * Properties of a GeneratedCodeInfo. - * @memberof google.protobuf - * @interface IGeneratedCodeInfo - * @property {Array.|null} [annotation] GeneratedCodeInfo annotation - */ - - /** - * Constructs a new GeneratedCodeInfo. - * @memberof google.protobuf - * @classdesc Represents a GeneratedCodeInfo. - * @implements IGeneratedCodeInfo - * @constructor - * @param {google.protobuf.IGeneratedCodeInfo=} [properties] Properties to set - */ - function GeneratedCodeInfo(properties) { - this.annotation = []; - if (properties) - for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) - if (properties[keys[i]] != null) - this[keys[i]] = properties[keys[i]]; - } - - /** - * GeneratedCodeInfo annotation. - * @member {Array.} annotation - * @memberof google.protobuf.GeneratedCodeInfo - * @instance - */ - GeneratedCodeInfo.prototype.annotation = $util.emptyArray; - - /** - * Creates a GeneratedCodeInfo message from a plain object. Also converts values to their respective internal types. - * @function fromObject - * @memberof google.protobuf.GeneratedCodeInfo - * @static - * @param {Object.} object Plain object - * @returns {google.protobuf.GeneratedCodeInfo} GeneratedCodeInfo - */ - GeneratedCodeInfo.fromObject = function fromObject(object) { - if (object instanceof $root.google.protobuf.GeneratedCodeInfo) - return object; - var message = new $root.google.protobuf.GeneratedCodeInfo(); - if (object.annotation) { - if (!Array.isArray(object.annotation)) - throw TypeError(".google.protobuf.GeneratedCodeInfo.annotation: array expected"); - message.annotation = []; - for (var i = 0; i < object.annotation.length; ++i) { - if (typeof object.annotation[i] !== "object") - throw TypeError(".google.protobuf.GeneratedCodeInfo.annotation: object expected"); - message.annotation[i] = $root.google.protobuf.GeneratedCodeInfo.Annotation.fromObject(object.annotation[i]); - } - } - return message; - }; - - /** - * Creates a plain object from a GeneratedCodeInfo message. Also converts values to other types if specified. - * @function toObject - * @memberof google.protobuf.GeneratedCodeInfo - * @static - * @param {google.protobuf.GeneratedCodeInfo} message GeneratedCodeInfo - * @param {$protobuf.IConversionOptions} [options] Conversion options - * @returns {Object.} Plain object - */ - GeneratedCodeInfo.toObject = function toObject(message, options) { - if (!options) - options = {}; - var object = {}; - if (options.arrays || options.defaults) - object.annotation = []; - if (message.annotation && message.annotation.length) { - object.annotation = []; - for (var j = 0; j < message.annotation.length; ++j) - object.annotation[j] = $root.google.protobuf.GeneratedCodeInfo.Annotation.toObject(message.annotation[j], options); - } - return object; - }; - - /** - * Converts this GeneratedCodeInfo to JSON. - * @function toJSON - * @memberof google.protobuf.GeneratedCodeInfo - * @instance - * @returns {Object.} JSON object - */ - GeneratedCodeInfo.prototype.toJSON = function toJSON() { - return this.constructor.toObject(this, $protobuf.util.toJSONOptions); - }; - - /** - * Gets the default type url for GeneratedCodeInfo - * @function getTypeUrl - * @memberof google.protobuf.GeneratedCodeInfo - * @static - * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") - * @returns {string} The default type url - */ - GeneratedCodeInfo.getTypeUrl = function getTypeUrl(typeUrlPrefix) { - if (typeUrlPrefix === undefined) { - typeUrlPrefix = "type.googleapis.com"; - } - return typeUrlPrefix + "/google.protobuf.GeneratedCodeInfo"; - }; - - GeneratedCodeInfo.Annotation = (function() { + v1.RunAggregationQueryResponse = (function() { /** - * Properties of an Annotation. - * @memberof google.protobuf.GeneratedCodeInfo - * @interface IAnnotation - * @property {Array.|null} [path] Annotation path - * @property {string|null} [sourceFile] Annotation sourceFile - * @property {number|null} [begin] Annotation begin - * @property {number|null} [end] Annotation end - * @property {google.protobuf.GeneratedCodeInfo.Annotation.Semantic|null} [semantic] Annotation semantic + * Properties of a RunAggregationQueryResponse. + * @memberof google.firestore.v1 + * @interface IRunAggregationQueryResponse + * @property {google.firestore.v1.IAggregationResult|null} [result] RunAggregationQueryResponse result + * @property {Uint8Array|null} [transaction] RunAggregationQueryResponse transaction + * @property {google.protobuf.ITimestamp|null} [readTime] RunAggregationQueryResponse readTime + * @property {google.firestore.v1.IExplainMetrics|null} [explainMetrics] RunAggregationQueryResponse explainMetrics */ /** - * Constructs a new Annotation. - * @memberof google.protobuf.GeneratedCodeInfo - * @classdesc Represents an Annotation. - * @implements IAnnotation + * Constructs a new RunAggregationQueryResponse. + * @memberof google.firestore.v1 + * @classdesc Represents a RunAggregationQueryResponse. + * @implements IRunAggregationQueryResponse * @constructor - * @param {google.protobuf.GeneratedCodeInfo.IAnnotation=} [properties] Properties to set - */ - function Annotation(properties) { - this.path = []; - if (properties) - for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) - if (properties[keys[i]] != null) - this[keys[i]] = properties[keys[i]]; - } - - /** - * Annotation path. - * @member {Array.} path - * @memberof google.protobuf.GeneratedCodeInfo.Annotation - * @instance + * @param {google.firestore.v1.IRunAggregationQueryResponse=} [properties] Properties to set */ - Annotation.prototype.path = $util.emptyArray; + function RunAggregationQueryResponse(properties) { + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } /** - * Annotation sourceFile. - * @member {string} sourceFile - * @memberof google.protobuf.GeneratedCodeInfo.Annotation + * RunAggregationQueryResponse result. + * @member {google.firestore.v1.IAggregationResult|null|undefined} result + * @memberof google.firestore.v1.RunAggregationQueryResponse * @instance */ - Annotation.prototype.sourceFile = ""; + RunAggregationQueryResponse.prototype.result = null; /** - * Annotation begin. - * @member {number} begin - * @memberof google.protobuf.GeneratedCodeInfo.Annotation + * RunAggregationQueryResponse transaction. + * @member {Uint8Array} transaction + * @memberof google.firestore.v1.RunAggregationQueryResponse * @instance */ - Annotation.prototype.begin = 0; + RunAggregationQueryResponse.prototype.transaction = $util.newBuffer([]); /** - * Annotation end. - * @member {number} end - * @memberof google.protobuf.GeneratedCodeInfo.Annotation + * RunAggregationQueryResponse readTime. + * @member {google.protobuf.ITimestamp|null|undefined} readTime + * @memberof google.firestore.v1.RunAggregationQueryResponse * @instance */ - Annotation.prototype.end = 0; + RunAggregationQueryResponse.prototype.readTime = null; /** - * Annotation semantic. - * @member {google.protobuf.GeneratedCodeInfo.Annotation.Semantic} semantic - * @memberof google.protobuf.GeneratedCodeInfo.Annotation + * RunAggregationQueryResponse explainMetrics. + * @member {google.firestore.v1.IExplainMetrics|null|undefined} explainMetrics + * @memberof google.firestore.v1.RunAggregationQueryResponse * @instance */ - Annotation.prototype.semantic = 0; + RunAggregationQueryResponse.prototype.explainMetrics = null; /** - * Creates an Annotation message from a plain object. Also converts values to their respective internal types. + * Creates a RunAggregationQueryResponse message from a plain object. Also converts values to their respective internal types. * @function fromObject - * @memberof google.protobuf.GeneratedCodeInfo.Annotation + * @memberof google.firestore.v1.RunAggregationQueryResponse * @static * @param {Object.} object Plain object - * @returns {google.protobuf.GeneratedCodeInfo.Annotation} Annotation + * @returns {google.firestore.v1.RunAggregationQueryResponse} RunAggregationQueryResponse */ - Annotation.fromObject = function fromObject(object) { - if (object instanceof $root.google.protobuf.GeneratedCodeInfo.Annotation) + RunAggregationQueryResponse.fromObject = function fromObject(object) { + if (object instanceof $root.google.firestore.v1.RunAggregationQueryResponse) return object; - var message = new $root.google.protobuf.GeneratedCodeInfo.Annotation(); - if (object.path) { - if (!Array.isArray(object.path)) - throw TypeError(".google.protobuf.GeneratedCodeInfo.Annotation.path: array expected"); - message.path = []; - for (var i = 0; i < object.path.length; ++i) - message.path[i] = object.path[i] | 0; + var message = new $root.google.firestore.v1.RunAggregationQueryResponse(); + if (object.result != null) { + if (typeof object.result !== "object") + throw TypeError(".google.firestore.v1.RunAggregationQueryResponse.result: object expected"); + message.result = $root.google.firestore.v1.AggregationResult.fromObject(object.result); } - if (object.sourceFile != null) - message.sourceFile = String(object.sourceFile); - if (object.begin != null) - message.begin = object.begin | 0; - if (object.end != null) - message.end = object.end | 0; - switch (object.semantic) { - default: - if (typeof object.semantic === "number") { - message.semantic = object.semantic; - break; - } - break; - case "NONE": - case 0: - message.semantic = 0; - break; - case "SET": - case 1: - message.semantic = 1; - break; - case "ALIAS": - case 2: - message.semantic = 2; - break; + if (object.transaction != null) + if (typeof object.transaction === "string") + $util.base64.decode(object.transaction, message.transaction = $util.newBuffer($util.base64.length(object.transaction)), 0); + else if (object.transaction.length >= 0) + message.transaction = object.transaction; + if (object.readTime != null) { + if (typeof object.readTime !== "object") + throw TypeError(".google.firestore.v1.RunAggregationQueryResponse.readTime: object expected"); + message.readTime = $root.google.protobuf.Timestamp.fromObject(object.readTime); + } + if (object.explainMetrics != null) { + if (typeof object.explainMetrics !== "object") + throw TypeError(".google.firestore.v1.RunAggregationQueryResponse.explainMetrics: object expected"); + message.explainMetrics = $root.google.firestore.v1.ExplainMetrics.fromObject(object.explainMetrics); } return message; }; /** - * Creates a plain object from an Annotation message. Also converts values to other types if specified. + * Creates a plain object from a RunAggregationQueryResponse message. Also converts values to other types if specified. * @function toObject - * @memberof google.protobuf.GeneratedCodeInfo.Annotation + * @memberof google.firestore.v1.RunAggregationQueryResponse * @static - * @param {google.protobuf.GeneratedCodeInfo.Annotation} message Annotation + * @param {google.firestore.v1.RunAggregationQueryResponse} message RunAggregationQueryResponse * @param {$protobuf.IConversionOptions} [options] Conversion options * @returns {Object.} Plain object */ - Annotation.toObject = function toObject(message, options) { + RunAggregationQueryResponse.toObject = function toObject(message, options) { if (!options) options = {}; var object = {}; - if (options.arrays || options.defaults) - object.path = []; if (options.defaults) { - object.sourceFile = ""; - object.begin = 0; - object.end = 0; - object.semantic = options.enums === String ? "NONE" : 0; - } - if (message.path && message.path.length) { - object.path = []; - for (var j = 0; j < message.path.length; ++j) - object.path[j] = message.path[j]; + object.result = null; + if (options.bytes === String) + object.transaction = ""; + else { + object.transaction = []; + if (options.bytes !== Array) + object.transaction = $util.newBuffer(object.transaction); + } + object.readTime = null; + object.explainMetrics = null; } - if (message.sourceFile != null && message.hasOwnProperty("sourceFile")) - object.sourceFile = message.sourceFile; - if (message.begin != null && message.hasOwnProperty("begin")) - object.begin = message.begin; - if (message.end != null && message.hasOwnProperty("end")) - object.end = message.end; - if (message.semantic != null && message.hasOwnProperty("semantic")) - object.semantic = options.enums === String ? $root.google.protobuf.GeneratedCodeInfo.Annotation.Semantic[message.semantic] === undefined ? message.semantic : $root.google.protobuf.GeneratedCodeInfo.Annotation.Semantic[message.semantic] : message.semantic; + if (message.result != null && message.hasOwnProperty("result")) + object.result = $root.google.firestore.v1.AggregationResult.toObject(message.result, options); + if (message.transaction != null && message.hasOwnProperty("transaction")) + object.transaction = options.bytes === String ? $util.base64.encode(message.transaction, 0, message.transaction.length) : options.bytes === Array ? Array.prototype.slice.call(message.transaction) : message.transaction; + if (message.readTime != null && message.hasOwnProperty("readTime")) + object.readTime = $root.google.protobuf.Timestamp.toObject(message.readTime, options); + if (message.explainMetrics != null && message.hasOwnProperty("explainMetrics")) + object.explainMetrics = $root.google.firestore.v1.ExplainMetrics.toObject(message.explainMetrics, options); return object; }; /** - * Converts this Annotation to JSON. + * Converts this RunAggregationQueryResponse to JSON. * @function toJSON - * @memberof google.protobuf.GeneratedCodeInfo.Annotation + * @memberof google.firestore.v1.RunAggregationQueryResponse * @instance * @returns {Object.} JSON object */ - Annotation.prototype.toJSON = function toJSON() { + RunAggregationQueryResponse.prototype.toJSON = function toJSON() { return this.constructor.toObject(this, $protobuf.util.toJSONOptions); }; /** - * Gets the default type url for Annotation + * Gets the default type url for RunAggregationQueryResponse * @function getTypeUrl - * @memberof google.protobuf.GeneratedCodeInfo.Annotation + * @memberof google.firestore.v1.RunAggregationQueryResponse * @static * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") * @returns {string} The default type url */ - Annotation.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + RunAggregationQueryResponse.getTypeUrl = function getTypeUrl(typeUrlPrefix) { if (typeUrlPrefix === undefined) { typeUrlPrefix = "type.googleapis.com"; } - return typeUrlPrefix + "/google.protobuf.GeneratedCodeInfo.Annotation"; + return typeUrlPrefix + "/google.firestore.v1.RunAggregationQueryResponse"; }; - /** - * Semantic enum. - * @name google.protobuf.GeneratedCodeInfo.Annotation.Semantic - * @enum {string} - * @property {string} NONE=NONE NONE value - * @property {string} SET=SET SET value - * @property {string} ALIAS=ALIAS ALIAS value - */ - Annotation.Semantic = (function() { - var valuesById = {}, values = Object.create(valuesById); - values[valuesById[0] = "NONE"] = "NONE"; - values[valuesById[1] = "SET"] = "SET"; - values[valuesById[2] = "ALIAS"] = "ALIAS"; - return values; - })(); - - return Annotation; + return RunAggregationQueryResponse; })(); - return GeneratedCodeInfo; - })(); - - protobuf.Duration = (function() { - - /** - * Properties of a Duration. - * @memberof google.protobuf - * @interface IDuration - * @property {number|string|null} [seconds] Duration seconds - * @property {number|null} [nanos] Duration nanos - */ - - /** - * Constructs a new Duration. - * @memberof google.protobuf - * @classdesc Represents a Duration. - * @implements IDuration - * @constructor - * @param {google.protobuf.IDuration=} [properties] Properties to set - */ - function Duration(properties) { - if (properties) - for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) - if (properties[keys[i]] != null) - this[keys[i]] = properties[keys[i]]; - } - - /** - * Duration seconds. - * @member {number|string} seconds - * @memberof google.protobuf.Duration - * @instance - */ - Duration.prototype.seconds = $util.Long ? $util.Long.fromBits(0,0,false) : 0; - - /** - * Duration nanos. - * @member {number} nanos - * @memberof google.protobuf.Duration - * @instance - */ - Duration.prototype.nanos = 0; + v1.PartitionQueryRequest = (function() { - /** - * Creates a Duration message from a plain object. Also converts values to their respective internal types. - * @function fromObject - * @memberof google.protobuf.Duration - * @static - * @param {Object.} object Plain object - * @returns {google.protobuf.Duration} Duration - */ - Duration.fromObject = function fromObject(object) { - if (object instanceof $root.google.protobuf.Duration) - return object; - var message = new $root.google.protobuf.Duration(); - if (object.seconds != null) - if ($util.Long) - (message.seconds = $util.Long.fromValue(object.seconds)).unsigned = false; - else if (typeof object.seconds === "string") - message.seconds = parseInt(object.seconds, 10); - else if (typeof object.seconds === "number") - message.seconds = object.seconds; - else if (typeof object.seconds === "object") - message.seconds = new $util.LongBits(object.seconds.low >>> 0, object.seconds.high >>> 0).toNumber(); - if (object.nanos != null) - message.nanos = object.nanos | 0; - return message; - }; + /** + * Properties of a PartitionQueryRequest. + * @memberof google.firestore.v1 + * @interface IPartitionQueryRequest + * @property {string|null} [parent] PartitionQueryRequest parent + * @property {google.firestore.v1.IStructuredQuery|null} [structuredQuery] PartitionQueryRequest structuredQuery + * @property {number|string|null} [partitionCount] PartitionQueryRequest partitionCount + * @property {string|null} [pageToken] PartitionQueryRequest pageToken + * @property {number|null} [pageSize] PartitionQueryRequest pageSize + * @property {google.protobuf.ITimestamp|null} [readTime] PartitionQueryRequest readTime + */ - /** - * Creates a plain object from a Duration message. Also converts values to other types if specified. - * @function toObject - * @memberof google.protobuf.Duration - * @static - * @param {google.protobuf.Duration} message Duration - * @param {$protobuf.IConversionOptions} [options] Conversion options - * @returns {Object.} Plain object - */ - Duration.toObject = function toObject(message, options) { - if (!options) - options = {}; - var object = {}; - if (options.defaults) { - if ($util.Long) { - var long = new $util.Long(0, 0, false); - object.seconds = options.longs === String ? long.toString() : options.longs === Number ? long.toNumber() : long; - } else - object.seconds = options.longs === String ? "0" : 0; - object.nanos = 0; + /** + * Constructs a new PartitionQueryRequest. + * @memberof google.firestore.v1 + * @classdesc Represents a PartitionQueryRequest. + * @implements IPartitionQueryRequest + * @constructor + * @param {google.firestore.v1.IPartitionQueryRequest=} [properties] Properties to set + */ + function PartitionQueryRequest(properties) { + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; } - if (message.seconds != null && message.hasOwnProperty("seconds")) - if (typeof message.seconds === "number") - object.seconds = options.longs === String ? String(message.seconds) : message.seconds; - else - object.seconds = options.longs === String ? $util.Long.prototype.toString.call(message.seconds) : options.longs === Number ? new $util.LongBits(message.seconds.low >>> 0, message.seconds.high >>> 0).toNumber() : message.seconds; - if (message.nanos != null && message.hasOwnProperty("nanos")) - object.nanos = message.nanos; - return object; - }; - /** - * Converts this Duration to JSON. - * @function toJSON - * @memberof google.protobuf.Duration - * @instance - * @returns {Object.} JSON object - */ - Duration.prototype.toJSON = function toJSON() { - return this.constructor.toObject(this, $protobuf.util.toJSONOptions); - }; + /** + * PartitionQueryRequest parent. + * @member {string} parent + * @memberof google.firestore.v1.PartitionQueryRequest + * @instance + */ + PartitionQueryRequest.prototype.parent = ""; - /** - * Gets the default type url for Duration - * @function getTypeUrl - * @memberof google.protobuf.Duration - * @static - * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") - * @returns {string} The default type url - */ - Duration.getTypeUrl = function getTypeUrl(typeUrlPrefix) { - if (typeUrlPrefix === undefined) { - typeUrlPrefix = "type.googleapis.com"; - } - return typeUrlPrefix + "/google.protobuf.Duration"; - }; + /** + * PartitionQueryRequest structuredQuery. + * @member {google.firestore.v1.IStructuredQuery|null|undefined} structuredQuery + * @memberof google.firestore.v1.PartitionQueryRequest + * @instance + */ + PartitionQueryRequest.prototype.structuredQuery = null; - return Duration; - })(); + /** + * PartitionQueryRequest partitionCount. + * @member {number|string} partitionCount + * @memberof google.firestore.v1.PartitionQueryRequest + * @instance + */ + PartitionQueryRequest.prototype.partitionCount = $util.Long ? $util.Long.fromBits(0,0,false) : 0; - protobuf.DoubleValue = (function() { + /** + * PartitionQueryRequest pageToken. + * @member {string} pageToken + * @memberof google.firestore.v1.PartitionQueryRequest + * @instance + */ + PartitionQueryRequest.prototype.pageToken = ""; - /** - * Properties of a DoubleValue. - * @memberof google.protobuf - * @interface IDoubleValue - * @property {number|null} [value] DoubleValue value - */ + /** + * PartitionQueryRequest pageSize. + * @member {number} pageSize + * @memberof google.firestore.v1.PartitionQueryRequest + * @instance + */ + PartitionQueryRequest.prototype.pageSize = 0; - /** - * Constructs a new DoubleValue. - * @memberof google.protobuf - * @classdesc Represents a DoubleValue. - * @implements IDoubleValue - * @constructor - * @param {google.protobuf.IDoubleValue=} [properties] Properties to set - */ - function DoubleValue(properties) { - if (properties) - for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) - if (properties[keys[i]] != null) - this[keys[i]] = properties[keys[i]]; - } + /** + * PartitionQueryRequest readTime. + * @member {google.protobuf.ITimestamp|null|undefined} readTime + * @memberof google.firestore.v1.PartitionQueryRequest + * @instance + */ + PartitionQueryRequest.prototype.readTime = null; - /** - * DoubleValue value. - * @member {number} value - * @memberof google.protobuf.DoubleValue - * @instance - */ - DoubleValue.prototype.value = 0; + // OneOf field names bound to virtual getters and setters + var $oneOfFields; - /** - * Creates a DoubleValue message from a plain object. Also converts values to their respective internal types. - * @function fromObject - * @memberof google.protobuf.DoubleValue - * @static - * @param {Object.} object Plain object - * @returns {google.protobuf.DoubleValue} DoubleValue - */ - DoubleValue.fromObject = function fromObject(object) { - if (object instanceof $root.google.protobuf.DoubleValue) + /** + * PartitionQueryRequest queryType. + * @member {"structuredQuery"|undefined} queryType + * @memberof google.firestore.v1.PartitionQueryRequest + * @instance + */ + Object.defineProperty(PartitionQueryRequest.prototype, "queryType", { + get: $util.oneOfGetter($oneOfFields = ["structuredQuery"]), + set: $util.oneOfSetter($oneOfFields) + }); + + /** + * PartitionQueryRequest consistencySelector. + * @member {"readTime"|undefined} consistencySelector + * @memberof google.firestore.v1.PartitionQueryRequest + * @instance + */ + Object.defineProperty(PartitionQueryRequest.prototype, "consistencySelector", { + get: $util.oneOfGetter($oneOfFields = ["readTime"]), + set: $util.oneOfSetter($oneOfFields) + }); + + /** + * Creates a PartitionQueryRequest message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.firestore.v1.PartitionQueryRequest + * @static + * @param {Object.} object Plain object + * @returns {google.firestore.v1.PartitionQueryRequest} PartitionQueryRequest + */ + PartitionQueryRequest.fromObject = function fromObject(object) { + if (object instanceof $root.google.firestore.v1.PartitionQueryRequest) + return object; + var message = new $root.google.firestore.v1.PartitionQueryRequest(); + if (object.parent != null) + message.parent = String(object.parent); + if (object.structuredQuery != null) { + if (typeof object.structuredQuery !== "object") + throw TypeError(".google.firestore.v1.PartitionQueryRequest.structuredQuery: object expected"); + message.structuredQuery = $root.google.firestore.v1.StructuredQuery.fromObject(object.structuredQuery); + } + if (object.partitionCount != null) + if ($util.Long) + (message.partitionCount = $util.Long.fromValue(object.partitionCount)).unsigned = false; + else if (typeof object.partitionCount === "string") + message.partitionCount = parseInt(object.partitionCount, 10); + else if (typeof object.partitionCount === "number") + message.partitionCount = object.partitionCount; + else if (typeof object.partitionCount === "object") + message.partitionCount = new $util.LongBits(object.partitionCount.low >>> 0, object.partitionCount.high >>> 0).toNumber(); + if (object.pageToken != null) + message.pageToken = String(object.pageToken); + if (object.pageSize != null) + message.pageSize = object.pageSize | 0; + if (object.readTime != null) { + if (typeof object.readTime !== "object") + throw TypeError(".google.firestore.v1.PartitionQueryRequest.readTime: object expected"); + message.readTime = $root.google.protobuf.Timestamp.fromObject(object.readTime); + } + return message; + }; + + /** + * Creates a plain object from a PartitionQueryRequest message. Also converts values to other types if specified. + * @function toObject + * @memberof google.firestore.v1.PartitionQueryRequest + * @static + * @param {google.firestore.v1.PartitionQueryRequest} message PartitionQueryRequest + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + PartitionQueryRequest.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.defaults) { + object.parent = ""; + if ($util.Long) { + var long = new $util.Long(0, 0, false); + object.partitionCount = options.longs === String ? long.toString() : options.longs === Number ? long.toNumber() : long; + } else + object.partitionCount = options.longs === String ? "0" : 0; + object.pageToken = ""; + object.pageSize = 0; + } + if (message.parent != null && message.hasOwnProperty("parent")) + object.parent = message.parent; + if (message.structuredQuery != null && message.hasOwnProperty("structuredQuery")) { + object.structuredQuery = $root.google.firestore.v1.StructuredQuery.toObject(message.structuredQuery, options); + if (options.oneofs) + object.queryType = "structuredQuery"; + } + if (message.partitionCount != null && message.hasOwnProperty("partitionCount")) + if (typeof message.partitionCount === "number") + object.partitionCount = options.longs === String ? String(message.partitionCount) : message.partitionCount; + else + object.partitionCount = options.longs === String ? $util.Long.prototype.toString.call(message.partitionCount) : options.longs === Number ? new $util.LongBits(message.partitionCount.low >>> 0, message.partitionCount.high >>> 0).toNumber() : message.partitionCount; + if (message.pageToken != null && message.hasOwnProperty("pageToken")) + object.pageToken = message.pageToken; + if (message.pageSize != null && message.hasOwnProperty("pageSize")) + object.pageSize = message.pageSize; + if (message.readTime != null && message.hasOwnProperty("readTime")) { + object.readTime = $root.google.protobuf.Timestamp.toObject(message.readTime, options); + if (options.oneofs) + object.consistencySelector = "readTime"; + } return object; - var message = new $root.google.protobuf.DoubleValue(); - if (object.value != null) - message.value = Number(object.value); - return message; - }; + }; - /** - * Creates a plain object from a DoubleValue message. Also converts values to other types if specified. - * @function toObject - * @memberof google.protobuf.DoubleValue - * @static - * @param {google.protobuf.DoubleValue} message DoubleValue - * @param {$protobuf.IConversionOptions} [options] Conversion options - * @returns {Object.} Plain object - */ - DoubleValue.toObject = function toObject(message, options) { - if (!options) - options = {}; - var object = {}; - if (options.defaults) - object.value = 0; - if (message.value != null && message.hasOwnProperty("value")) - object.value = options.json && !isFinite(message.value) ? String(message.value) : message.value; - return object; - }; + /** + * Converts this PartitionQueryRequest to JSON. + * @function toJSON + * @memberof google.firestore.v1.PartitionQueryRequest + * @instance + * @returns {Object.} JSON object + */ + PartitionQueryRequest.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; - /** - * Converts this DoubleValue to JSON. - * @function toJSON - * @memberof google.protobuf.DoubleValue - * @instance - * @returns {Object.} JSON object - */ - DoubleValue.prototype.toJSON = function toJSON() { - return this.constructor.toObject(this, $protobuf.util.toJSONOptions); - }; + /** + * Gets the default type url for PartitionQueryRequest + * @function getTypeUrl + * @memberof google.firestore.v1.PartitionQueryRequest + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + PartitionQueryRequest.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.firestore.v1.PartitionQueryRequest"; + }; - /** - * Gets the default type url for DoubleValue - * @function getTypeUrl - * @memberof google.protobuf.DoubleValue - * @static - * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") - * @returns {string} The default type url - */ - DoubleValue.getTypeUrl = function getTypeUrl(typeUrlPrefix) { - if (typeUrlPrefix === undefined) { - typeUrlPrefix = "type.googleapis.com"; - } - return typeUrlPrefix + "/google.protobuf.DoubleValue"; - }; + return PartitionQueryRequest; + })(); - return DoubleValue; - })(); + v1.PartitionQueryResponse = (function() { - protobuf.FloatValue = (function() { + /** + * Properties of a PartitionQueryResponse. + * @memberof google.firestore.v1 + * @interface IPartitionQueryResponse + * @property {Array.|null} [partitions] PartitionQueryResponse partitions + * @property {string|null} [nextPageToken] PartitionQueryResponse nextPageToken + */ - /** - * Properties of a FloatValue. - * @memberof google.protobuf - * @interface IFloatValue - * @property {number|null} [value] FloatValue value - */ + /** + * Constructs a new PartitionQueryResponse. + * @memberof google.firestore.v1 + * @classdesc Represents a PartitionQueryResponse. + * @implements IPartitionQueryResponse + * @constructor + * @param {google.firestore.v1.IPartitionQueryResponse=} [properties] Properties to set + */ + function PartitionQueryResponse(properties) { + this.partitions = []; + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } - /** - * Constructs a new FloatValue. - * @memberof google.protobuf - * @classdesc Represents a FloatValue. - * @implements IFloatValue - * @constructor - * @param {google.protobuf.IFloatValue=} [properties] Properties to set - */ - function FloatValue(properties) { - if (properties) - for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) - if (properties[keys[i]] != null) - this[keys[i]] = properties[keys[i]]; - } + /** + * PartitionQueryResponse partitions. + * @member {Array.} partitions + * @memberof google.firestore.v1.PartitionQueryResponse + * @instance + */ + PartitionQueryResponse.prototype.partitions = $util.emptyArray; - /** - * FloatValue value. - * @member {number} value - * @memberof google.protobuf.FloatValue - * @instance - */ - FloatValue.prototype.value = 0; + /** + * PartitionQueryResponse nextPageToken. + * @member {string} nextPageToken + * @memberof google.firestore.v1.PartitionQueryResponse + * @instance + */ + PartitionQueryResponse.prototype.nextPageToken = ""; - /** - * Creates a FloatValue message from a plain object. Also converts values to their respective internal types. - * @function fromObject - * @memberof google.protobuf.FloatValue - * @static - * @param {Object.} object Plain object - * @returns {google.protobuf.FloatValue} FloatValue - */ - FloatValue.fromObject = function fromObject(object) { - if (object instanceof $root.google.protobuf.FloatValue) + /** + * Creates a PartitionQueryResponse message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.firestore.v1.PartitionQueryResponse + * @static + * @param {Object.} object Plain object + * @returns {google.firestore.v1.PartitionQueryResponse} PartitionQueryResponse + */ + PartitionQueryResponse.fromObject = function fromObject(object) { + if (object instanceof $root.google.firestore.v1.PartitionQueryResponse) + return object; + var message = new $root.google.firestore.v1.PartitionQueryResponse(); + if (object.partitions) { + if (!Array.isArray(object.partitions)) + throw TypeError(".google.firestore.v1.PartitionQueryResponse.partitions: array expected"); + message.partitions = []; + for (var i = 0; i < object.partitions.length; ++i) { + if (typeof object.partitions[i] !== "object") + throw TypeError(".google.firestore.v1.PartitionQueryResponse.partitions: object expected"); + message.partitions[i] = $root.google.firestore.v1.Cursor.fromObject(object.partitions[i]); + } + } + if (object.nextPageToken != null) + message.nextPageToken = String(object.nextPageToken); + return message; + }; + + /** + * Creates a plain object from a PartitionQueryResponse message. Also converts values to other types if specified. + * @function toObject + * @memberof google.firestore.v1.PartitionQueryResponse + * @static + * @param {google.firestore.v1.PartitionQueryResponse} message PartitionQueryResponse + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + PartitionQueryResponse.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.arrays || options.defaults) + object.partitions = []; + if (options.defaults) + object.nextPageToken = ""; + if (message.partitions && message.partitions.length) { + object.partitions = []; + for (var j = 0; j < message.partitions.length; ++j) + object.partitions[j] = $root.google.firestore.v1.Cursor.toObject(message.partitions[j], options); + } + if (message.nextPageToken != null && message.hasOwnProperty("nextPageToken")) + object.nextPageToken = message.nextPageToken; return object; - var message = new $root.google.protobuf.FloatValue(); - if (object.value != null) - message.value = Number(object.value); - return message; - }; + }; - /** - * Creates a plain object from a FloatValue message. Also converts values to other types if specified. - * @function toObject - * @memberof google.protobuf.FloatValue - * @static - * @param {google.protobuf.FloatValue} message FloatValue - * @param {$protobuf.IConversionOptions} [options] Conversion options - * @returns {Object.} Plain object - */ - FloatValue.toObject = function toObject(message, options) { - if (!options) - options = {}; - var object = {}; - if (options.defaults) - object.value = 0; - if (message.value != null && message.hasOwnProperty("value")) - object.value = options.json && !isFinite(message.value) ? String(message.value) : message.value; - return object; - }; + /** + * Converts this PartitionQueryResponse to JSON. + * @function toJSON + * @memberof google.firestore.v1.PartitionQueryResponse + * @instance + * @returns {Object.} JSON object + */ + PartitionQueryResponse.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + + /** + * Gets the default type url for PartitionQueryResponse + * @function getTypeUrl + * @memberof google.firestore.v1.PartitionQueryResponse + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + PartitionQueryResponse.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.firestore.v1.PartitionQueryResponse"; + }; + + return PartitionQueryResponse; + })(); - /** - * Converts this FloatValue to JSON. - * @function toJSON - * @memberof google.protobuf.FloatValue - * @instance - * @returns {Object.} JSON object - */ - FloatValue.prototype.toJSON = function toJSON() { - return this.constructor.toObject(this, $protobuf.util.toJSONOptions); - }; + v1.WriteRequest = (function() { - /** - * Gets the default type url for FloatValue - * @function getTypeUrl - * @memberof google.protobuf.FloatValue - * @static - * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") - * @returns {string} The default type url - */ - FloatValue.getTypeUrl = function getTypeUrl(typeUrlPrefix) { - if (typeUrlPrefix === undefined) { - typeUrlPrefix = "type.googleapis.com"; + /** + * Properties of a WriteRequest. + * @memberof google.firestore.v1 + * @interface IWriteRequest + * @property {string|null} [database] WriteRequest database + * @property {string|null} [streamId] WriteRequest streamId + * @property {Array.|null} [writes] WriteRequest writes + * @property {Uint8Array|null} [streamToken] WriteRequest streamToken + * @property {Object.|null} [labels] WriteRequest labels + */ + + /** + * Constructs a new WriteRequest. + * @memberof google.firestore.v1 + * @classdesc Represents a WriteRequest. + * @implements IWriteRequest + * @constructor + * @param {google.firestore.v1.IWriteRequest=} [properties] Properties to set + */ + function WriteRequest(properties) { + this.writes = []; + this.labels = {}; + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; } - return typeUrlPrefix + "/google.protobuf.FloatValue"; - }; - return FloatValue; - })(); + /** + * WriteRequest database. + * @member {string} database + * @memberof google.firestore.v1.WriteRequest + * @instance + */ + WriteRequest.prototype.database = ""; - protobuf.Int64Value = (function() { + /** + * WriteRequest streamId. + * @member {string} streamId + * @memberof google.firestore.v1.WriteRequest + * @instance + */ + WriteRequest.prototype.streamId = ""; - /** - * Properties of an Int64Value. - * @memberof google.protobuf - * @interface IInt64Value - * @property {number|string|null} [value] Int64Value value - */ + /** + * WriteRequest writes. + * @member {Array.} writes + * @memberof google.firestore.v1.WriteRequest + * @instance + */ + WriteRequest.prototype.writes = $util.emptyArray; - /** - * Constructs a new Int64Value. - * @memberof google.protobuf - * @classdesc Represents an Int64Value. - * @implements IInt64Value - * @constructor - * @param {google.protobuf.IInt64Value=} [properties] Properties to set - */ - function Int64Value(properties) { - if (properties) - for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) - if (properties[keys[i]] != null) - this[keys[i]] = properties[keys[i]]; - } + /** + * WriteRequest streamToken. + * @member {Uint8Array} streamToken + * @memberof google.firestore.v1.WriteRequest + * @instance + */ + WriteRequest.prototype.streamToken = $util.newBuffer([]); - /** - * Int64Value value. - * @member {number|string} value - * @memberof google.protobuf.Int64Value - * @instance - */ - Int64Value.prototype.value = $util.Long ? $util.Long.fromBits(0,0,false) : 0; + /** + * WriteRequest labels. + * @member {Object.} labels + * @memberof google.firestore.v1.WriteRequest + * @instance + */ + WriteRequest.prototype.labels = $util.emptyObject; - /** - * Creates an Int64Value message from a plain object. Also converts values to their respective internal types. - * @function fromObject - * @memberof google.protobuf.Int64Value - * @static - * @param {Object.} object Plain object - * @returns {google.protobuf.Int64Value} Int64Value - */ - Int64Value.fromObject = function fromObject(object) { - if (object instanceof $root.google.protobuf.Int64Value) + /** + * Creates a WriteRequest message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.firestore.v1.WriteRequest + * @static + * @param {Object.} object Plain object + * @returns {google.firestore.v1.WriteRequest} WriteRequest + */ + WriteRequest.fromObject = function fromObject(object) { + if (object instanceof $root.google.firestore.v1.WriteRequest) + return object; + var message = new $root.google.firestore.v1.WriteRequest(); + if (object.database != null) + message.database = String(object.database); + if (object.streamId != null) + message.streamId = String(object.streamId); + if (object.writes) { + if (!Array.isArray(object.writes)) + throw TypeError(".google.firestore.v1.WriteRequest.writes: array expected"); + message.writes = []; + for (var i = 0; i < object.writes.length; ++i) { + if (typeof object.writes[i] !== "object") + throw TypeError(".google.firestore.v1.WriteRequest.writes: object expected"); + message.writes[i] = $root.google.firestore.v1.Write.fromObject(object.writes[i]); + } + } + if (object.streamToken != null) + if (typeof object.streamToken === "string") + $util.base64.decode(object.streamToken, message.streamToken = $util.newBuffer($util.base64.length(object.streamToken)), 0); + else if (object.streamToken.length >= 0) + message.streamToken = object.streamToken; + if (object.labels) { + if (typeof object.labels !== "object") + throw TypeError(".google.firestore.v1.WriteRequest.labels: object expected"); + message.labels = {}; + for (var keys = Object.keys(object.labels), i = 0; i < keys.length; ++i) + message.labels[keys[i]] = String(object.labels[keys[i]]); + } + return message; + }; + + /** + * Creates a plain object from a WriteRequest message. Also converts values to other types if specified. + * @function toObject + * @memberof google.firestore.v1.WriteRequest + * @static + * @param {google.firestore.v1.WriteRequest} message WriteRequest + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + WriteRequest.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.arrays || options.defaults) + object.writes = []; + if (options.objects || options.defaults) + object.labels = {}; + if (options.defaults) { + object.database = ""; + object.streamId = ""; + if (options.bytes === String) + object.streamToken = ""; + else { + object.streamToken = []; + if (options.bytes !== Array) + object.streamToken = $util.newBuffer(object.streamToken); + } + } + if (message.database != null && message.hasOwnProperty("database")) + object.database = message.database; + if (message.streamId != null && message.hasOwnProperty("streamId")) + object.streamId = message.streamId; + if (message.writes && message.writes.length) { + object.writes = []; + for (var j = 0; j < message.writes.length; ++j) + object.writes[j] = $root.google.firestore.v1.Write.toObject(message.writes[j], options); + } + if (message.streamToken != null && message.hasOwnProperty("streamToken")) + object.streamToken = options.bytes === String ? $util.base64.encode(message.streamToken, 0, message.streamToken.length) : options.bytes === Array ? Array.prototype.slice.call(message.streamToken) : message.streamToken; + var keys2; + if (message.labels && (keys2 = Object.keys(message.labels)).length) { + object.labels = {}; + for (var j = 0; j < keys2.length; ++j) + object.labels[keys2[j]] = message.labels[keys2[j]]; + } return object; - var message = new $root.google.protobuf.Int64Value(); - if (object.value != null) - if ($util.Long) - (message.value = $util.Long.fromValue(object.value)).unsigned = false; - else if (typeof object.value === "string") - message.value = parseInt(object.value, 10); - else if (typeof object.value === "number") - message.value = object.value; - else if (typeof object.value === "object") - message.value = new $util.LongBits(object.value.low >>> 0, object.value.high >>> 0).toNumber(); - return message; - }; + }; - /** - * Creates a plain object from an Int64Value message. Also converts values to other types if specified. - * @function toObject - * @memberof google.protobuf.Int64Value - * @static - * @param {google.protobuf.Int64Value} message Int64Value - * @param {$protobuf.IConversionOptions} [options] Conversion options - * @returns {Object.} Plain object - */ - Int64Value.toObject = function toObject(message, options) { - if (!options) - options = {}; - var object = {}; - if (options.defaults) - if ($util.Long) { - var long = new $util.Long(0, 0, false); - object.value = options.longs === String ? long.toString() : options.longs === Number ? long.toNumber() : long; - } else - object.value = options.longs === String ? "0" : 0; - if (message.value != null && message.hasOwnProperty("value")) - if (typeof message.value === "number") - object.value = options.longs === String ? String(message.value) : message.value; - else - object.value = options.longs === String ? $util.Long.prototype.toString.call(message.value) : options.longs === Number ? new $util.LongBits(message.value.low >>> 0, message.value.high >>> 0).toNumber() : message.value; - return object; - }; + /** + * Converts this WriteRequest to JSON. + * @function toJSON + * @memberof google.firestore.v1.WriteRequest + * @instance + * @returns {Object.} JSON object + */ + WriteRequest.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; - /** - * Converts this Int64Value to JSON. - * @function toJSON - * @memberof google.protobuf.Int64Value - * @instance - * @returns {Object.} JSON object - */ - Int64Value.prototype.toJSON = function toJSON() { - return this.constructor.toObject(this, $protobuf.util.toJSONOptions); - }; + /** + * Gets the default type url for WriteRequest + * @function getTypeUrl + * @memberof google.firestore.v1.WriteRequest + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + WriteRequest.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.firestore.v1.WriteRequest"; + }; - /** - * Gets the default type url for Int64Value - * @function getTypeUrl - * @memberof google.protobuf.Int64Value - * @static - * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") - * @returns {string} The default type url - */ - Int64Value.getTypeUrl = function getTypeUrl(typeUrlPrefix) { - if (typeUrlPrefix === undefined) { - typeUrlPrefix = "type.googleapis.com"; + return WriteRequest; + })(); + + v1.WriteResponse = (function() { + + /** + * Properties of a WriteResponse. + * @memberof google.firestore.v1 + * @interface IWriteResponse + * @property {string|null} [streamId] WriteResponse streamId + * @property {Uint8Array|null} [streamToken] WriteResponse streamToken + * @property {Array.|null} [writeResults] WriteResponse writeResults + * @property {google.protobuf.ITimestamp|null} [commitTime] WriteResponse commitTime + */ + + /** + * Constructs a new WriteResponse. + * @memberof google.firestore.v1 + * @classdesc Represents a WriteResponse. + * @implements IWriteResponse + * @constructor + * @param {google.firestore.v1.IWriteResponse=} [properties] Properties to set + */ + function WriteResponse(properties) { + this.writeResults = []; + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; } - return typeUrlPrefix + "/google.protobuf.Int64Value"; - }; - return Int64Value; - })(); + /** + * WriteResponse streamId. + * @member {string} streamId + * @memberof google.firestore.v1.WriteResponse + * @instance + */ + WriteResponse.prototype.streamId = ""; - protobuf.UInt64Value = (function() { + /** + * WriteResponse streamToken. + * @member {Uint8Array} streamToken + * @memberof google.firestore.v1.WriteResponse + * @instance + */ + WriteResponse.prototype.streamToken = $util.newBuffer([]); - /** - * Properties of a UInt64Value. - * @memberof google.protobuf - * @interface IUInt64Value - * @property {number|string|null} [value] UInt64Value value - */ + /** + * WriteResponse writeResults. + * @member {Array.} writeResults + * @memberof google.firestore.v1.WriteResponse + * @instance + */ + WriteResponse.prototype.writeResults = $util.emptyArray; - /** - * Constructs a new UInt64Value. - * @memberof google.protobuf - * @classdesc Represents a UInt64Value. - * @implements IUInt64Value - * @constructor - * @param {google.protobuf.IUInt64Value=} [properties] Properties to set - */ - function UInt64Value(properties) { - if (properties) - for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) - if (properties[keys[i]] != null) - this[keys[i]] = properties[keys[i]]; - } + /** + * WriteResponse commitTime. + * @member {google.protobuf.ITimestamp|null|undefined} commitTime + * @memberof google.firestore.v1.WriteResponse + * @instance + */ + WriteResponse.prototype.commitTime = null; - /** - * UInt64Value value. - * @member {number|string} value - * @memberof google.protobuf.UInt64Value - * @instance - */ - UInt64Value.prototype.value = $util.Long ? $util.Long.fromBits(0,0,true) : 0; + /** + * Creates a WriteResponse message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.firestore.v1.WriteResponse + * @static + * @param {Object.} object Plain object + * @returns {google.firestore.v1.WriteResponse} WriteResponse + */ + WriteResponse.fromObject = function fromObject(object) { + if (object instanceof $root.google.firestore.v1.WriteResponse) + return object; + var message = new $root.google.firestore.v1.WriteResponse(); + if (object.streamId != null) + message.streamId = String(object.streamId); + if (object.streamToken != null) + if (typeof object.streamToken === "string") + $util.base64.decode(object.streamToken, message.streamToken = $util.newBuffer($util.base64.length(object.streamToken)), 0); + else if (object.streamToken.length >= 0) + message.streamToken = object.streamToken; + if (object.writeResults) { + if (!Array.isArray(object.writeResults)) + throw TypeError(".google.firestore.v1.WriteResponse.writeResults: array expected"); + message.writeResults = []; + for (var i = 0; i < object.writeResults.length; ++i) { + if (typeof object.writeResults[i] !== "object") + throw TypeError(".google.firestore.v1.WriteResponse.writeResults: object expected"); + message.writeResults[i] = $root.google.firestore.v1.WriteResult.fromObject(object.writeResults[i]); + } + } + if (object.commitTime != null) { + if (typeof object.commitTime !== "object") + throw TypeError(".google.firestore.v1.WriteResponse.commitTime: object expected"); + message.commitTime = $root.google.protobuf.Timestamp.fromObject(object.commitTime); + } + return message; + }; - /** - * Creates a UInt64Value message from a plain object. Also converts values to their respective internal types. - * @function fromObject - * @memberof google.protobuf.UInt64Value - * @static - * @param {Object.} object Plain object - * @returns {google.protobuf.UInt64Value} UInt64Value - */ - UInt64Value.fromObject = function fromObject(object) { - if (object instanceof $root.google.protobuf.UInt64Value) + /** + * Creates a plain object from a WriteResponse message. Also converts values to other types if specified. + * @function toObject + * @memberof google.firestore.v1.WriteResponse + * @static + * @param {google.firestore.v1.WriteResponse} message WriteResponse + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + WriteResponse.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.arrays || options.defaults) + object.writeResults = []; + if (options.defaults) { + object.streamId = ""; + if (options.bytes === String) + object.streamToken = ""; + else { + object.streamToken = []; + if (options.bytes !== Array) + object.streamToken = $util.newBuffer(object.streamToken); + } + object.commitTime = null; + } + if (message.streamId != null && message.hasOwnProperty("streamId")) + object.streamId = message.streamId; + if (message.streamToken != null && message.hasOwnProperty("streamToken")) + object.streamToken = options.bytes === String ? $util.base64.encode(message.streamToken, 0, message.streamToken.length) : options.bytes === Array ? Array.prototype.slice.call(message.streamToken) : message.streamToken; + if (message.writeResults && message.writeResults.length) { + object.writeResults = []; + for (var j = 0; j < message.writeResults.length; ++j) + object.writeResults[j] = $root.google.firestore.v1.WriteResult.toObject(message.writeResults[j], options); + } + if (message.commitTime != null && message.hasOwnProperty("commitTime")) + object.commitTime = $root.google.protobuf.Timestamp.toObject(message.commitTime, options); return object; - var message = new $root.google.protobuf.UInt64Value(); - if (object.value != null) - if ($util.Long) - (message.value = $util.Long.fromValue(object.value)).unsigned = true; - else if (typeof object.value === "string") - message.value = parseInt(object.value, 10); - else if (typeof object.value === "number") - message.value = object.value; - else if (typeof object.value === "object") - message.value = new $util.LongBits(object.value.low >>> 0, object.value.high >>> 0).toNumber(true); - return message; - }; + }; - /** - * Creates a plain object from a UInt64Value message. Also converts values to other types if specified. - * @function toObject - * @memberof google.protobuf.UInt64Value - * @static - * @param {google.protobuf.UInt64Value} message UInt64Value - * @param {$protobuf.IConversionOptions} [options] Conversion options - * @returns {Object.} Plain object - */ - UInt64Value.toObject = function toObject(message, options) { - if (!options) - options = {}; - var object = {}; - if (options.defaults) - if ($util.Long) { - var long = new $util.Long(0, 0, true); - object.value = options.longs === String ? long.toString() : options.longs === Number ? long.toNumber() : long; - } else - object.value = options.longs === String ? "0" : 0; - if (message.value != null && message.hasOwnProperty("value")) - if (typeof message.value === "number") - object.value = options.longs === String ? String(message.value) : message.value; - else - object.value = options.longs === String ? $util.Long.prototype.toString.call(message.value) : options.longs === Number ? new $util.LongBits(message.value.low >>> 0, message.value.high >>> 0).toNumber(true) : message.value; - return object; - }; + /** + * Converts this WriteResponse to JSON. + * @function toJSON + * @memberof google.firestore.v1.WriteResponse + * @instance + * @returns {Object.} JSON object + */ + WriteResponse.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; - /** - * Converts this UInt64Value to JSON. - * @function toJSON - * @memberof google.protobuf.UInt64Value - * @instance - * @returns {Object.} JSON object - */ - UInt64Value.prototype.toJSON = function toJSON() { - return this.constructor.toObject(this, $protobuf.util.toJSONOptions); - }; + /** + * Gets the default type url for WriteResponse + * @function getTypeUrl + * @memberof google.firestore.v1.WriteResponse + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + WriteResponse.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.firestore.v1.WriteResponse"; + }; - /** - * Gets the default type url for UInt64Value - * @function getTypeUrl - * @memberof google.protobuf.UInt64Value - * @static - * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") - * @returns {string} The default type url - */ - UInt64Value.getTypeUrl = function getTypeUrl(typeUrlPrefix) { - if (typeUrlPrefix === undefined) { - typeUrlPrefix = "type.googleapis.com"; - } - return typeUrlPrefix + "/google.protobuf.UInt64Value"; - }; + return WriteResponse; + })(); - return UInt64Value; - })(); + v1.ListenRequest = (function() { - protobuf.Int32Value = (function() { + /** + * Properties of a ListenRequest. + * @memberof google.firestore.v1 + * @interface IListenRequest + * @property {string|null} [database] ListenRequest database + * @property {google.firestore.v1.ITarget|null} [addTarget] ListenRequest addTarget + * @property {number|null} [removeTarget] ListenRequest removeTarget + * @property {Object.|null} [labels] ListenRequest labels + */ - /** - * Properties of an Int32Value. - * @memberof google.protobuf - * @interface IInt32Value - * @property {number|null} [value] Int32Value value - */ + /** + * Constructs a new ListenRequest. + * @memberof google.firestore.v1 + * @classdesc Represents a ListenRequest. + * @implements IListenRequest + * @constructor + * @param {google.firestore.v1.IListenRequest=} [properties] Properties to set + */ + function ListenRequest(properties) { + this.labels = {}; + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } - /** - * Constructs a new Int32Value. - * @memberof google.protobuf - * @classdesc Represents an Int32Value. - * @implements IInt32Value - * @constructor - * @param {google.protobuf.IInt32Value=} [properties] Properties to set - */ - function Int32Value(properties) { - if (properties) - for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) - if (properties[keys[i]] != null) - this[keys[i]] = properties[keys[i]]; - } + /** + * ListenRequest database. + * @member {string} database + * @memberof google.firestore.v1.ListenRequest + * @instance + */ + ListenRequest.prototype.database = ""; - /** - * Int32Value value. - * @member {number} value - * @memberof google.protobuf.Int32Value - * @instance - */ - Int32Value.prototype.value = 0; + /** + * ListenRequest addTarget. + * @member {google.firestore.v1.ITarget|null|undefined} addTarget + * @memberof google.firestore.v1.ListenRequest + * @instance + */ + ListenRequest.prototype.addTarget = null; - /** - * Creates an Int32Value message from a plain object. Also converts values to their respective internal types. - * @function fromObject - * @memberof google.protobuf.Int32Value - * @static - * @param {Object.} object Plain object - * @returns {google.protobuf.Int32Value} Int32Value - */ - Int32Value.fromObject = function fromObject(object) { - if (object instanceof $root.google.protobuf.Int32Value) - return object; - var message = new $root.google.protobuf.Int32Value(); - if (object.value != null) - message.value = object.value | 0; - return message; - }; + /** + * ListenRequest removeTarget. + * @member {number|null|undefined} removeTarget + * @memberof google.firestore.v1.ListenRequest + * @instance + */ + ListenRequest.prototype.removeTarget = null; - /** - * Creates a plain object from an Int32Value message. Also converts values to other types if specified. - * @function toObject - * @memberof google.protobuf.Int32Value - * @static - * @param {google.protobuf.Int32Value} message Int32Value - * @param {$protobuf.IConversionOptions} [options] Conversion options - * @returns {Object.} Plain object - */ - Int32Value.toObject = function toObject(message, options) { - if (!options) - options = {}; - var object = {}; - if (options.defaults) - object.value = 0; - if (message.value != null && message.hasOwnProperty("value")) - object.value = message.value; - return object; - }; + /** + * ListenRequest labels. + * @member {Object.} labels + * @memberof google.firestore.v1.ListenRequest + * @instance + */ + ListenRequest.prototype.labels = $util.emptyObject; - /** - * Converts this Int32Value to JSON. - * @function toJSON - * @memberof google.protobuf.Int32Value - * @instance - * @returns {Object.} JSON object - */ - Int32Value.prototype.toJSON = function toJSON() { - return this.constructor.toObject(this, $protobuf.util.toJSONOptions); - }; + // OneOf field names bound to virtual getters and setters + var $oneOfFields; - /** - * Gets the default type url for Int32Value - * @function getTypeUrl - * @memberof google.protobuf.Int32Value - * @static - * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") - * @returns {string} The default type url - */ - Int32Value.getTypeUrl = function getTypeUrl(typeUrlPrefix) { - if (typeUrlPrefix === undefined) { - typeUrlPrefix = "type.googleapis.com"; - } - return typeUrlPrefix + "/google.protobuf.Int32Value"; - }; + /** + * ListenRequest targetChange. + * @member {"addTarget"|"removeTarget"|undefined} targetChange + * @memberof google.firestore.v1.ListenRequest + * @instance + */ + Object.defineProperty(ListenRequest.prototype, "targetChange", { + get: $util.oneOfGetter($oneOfFields = ["addTarget", "removeTarget"]), + set: $util.oneOfSetter($oneOfFields) + }); + + /** + * Creates a ListenRequest message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.firestore.v1.ListenRequest + * @static + * @param {Object.} object Plain object + * @returns {google.firestore.v1.ListenRequest} ListenRequest + */ + ListenRequest.fromObject = function fromObject(object) { + if (object instanceof $root.google.firestore.v1.ListenRequest) + return object; + var message = new $root.google.firestore.v1.ListenRequest(); + if (object.database != null) + message.database = String(object.database); + if (object.addTarget != null) { + if (typeof object.addTarget !== "object") + throw TypeError(".google.firestore.v1.ListenRequest.addTarget: object expected"); + message.addTarget = $root.google.firestore.v1.Target.fromObject(object.addTarget); + } + if (object.removeTarget != null) + message.removeTarget = object.removeTarget | 0; + if (object.labels) { + if (typeof object.labels !== "object") + throw TypeError(".google.firestore.v1.ListenRequest.labels: object expected"); + message.labels = {}; + for (var keys = Object.keys(object.labels), i = 0; i < keys.length; ++i) + message.labels[keys[i]] = String(object.labels[keys[i]]); + } + return message; + }; + + /** + * Creates a plain object from a ListenRequest message. Also converts values to other types if specified. + * @function toObject + * @memberof google.firestore.v1.ListenRequest + * @static + * @param {google.firestore.v1.ListenRequest} message ListenRequest + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + ListenRequest.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.objects || options.defaults) + object.labels = {}; + if (options.defaults) + object.database = ""; + if (message.database != null && message.hasOwnProperty("database")) + object.database = message.database; + if (message.addTarget != null && message.hasOwnProperty("addTarget")) { + object.addTarget = $root.google.firestore.v1.Target.toObject(message.addTarget, options); + if (options.oneofs) + object.targetChange = "addTarget"; + } + if (message.removeTarget != null && message.hasOwnProperty("removeTarget")) { + object.removeTarget = message.removeTarget; + if (options.oneofs) + object.targetChange = "removeTarget"; + } + var keys2; + if (message.labels && (keys2 = Object.keys(message.labels)).length) { + object.labels = {}; + for (var j = 0; j < keys2.length; ++j) + object.labels[keys2[j]] = message.labels[keys2[j]]; + } + return object; + }; - return Int32Value; - })(); + /** + * Converts this ListenRequest to JSON. + * @function toJSON + * @memberof google.firestore.v1.ListenRequest + * @instance + * @returns {Object.} JSON object + */ + ListenRequest.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; - protobuf.UInt32Value = (function() { + /** + * Gets the default type url for ListenRequest + * @function getTypeUrl + * @memberof google.firestore.v1.ListenRequest + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + ListenRequest.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.firestore.v1.ListenRequest"; + }; - /** - * Properties of a UInt32Value. - * @memberof google.protobuf - * @interface IUInt32Value - * @property {number|null} [value] UInt32Value value - */ + return ListenRequest; + })(); - /** - * Constructs a new UInt32Value. - * @memberof google.protobuf - * @classdesc Represents a UInt32Value. - * @implements IUInt32Value - * @constructor - * @param {google.protobuf.IUInt32Value=} [properties] Properties to set - */ - function UInt32Value(properties) { - if (properties) - for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) - if (properties[keys[i]] != null) - this[keys[i]] = properties[keys[i]]; - } + v1.ListenResponse = (function() { - /** - * UInt32Value value. - * @member {number} value - * @memberof google.protobuf.UInt32Value - * @instance - */ - UInt32Value.prototype.value = 0; + /** + * Properties of a ListenResponse. + * @memberof google.firestore.v1 + * @interface IListenResponse + * @property {google.firestore.v1.ITargetChange|null} [targetChange] ListenResponse targetChange + * @property {google.firestore.v1.IDocumentChange|null} [documentChange] ListenResponse documentChange + * @property {google.firestore.v1.IDocumentDelete|null} [documentDelete] ListenResponse documentDelete + * @property {google.firestore.v1.IDocumentRemove|null} [documentRemove] ListenResponse documentRemove + * @property {google.firestore.v1.IExistenceFilter|null} [filter] ListenResponse filter + */ - /** - * Creates a UInt32Value message from a plain object. Also converts values to their respective internal types. - * @function fromObject - * @memberof google.protobuf.UInt32Value - * @static - * @param {Object.} object Plain object - * @returns {google.protobuf.UInt32Value} UInt32Value - */ - UInt32Value.fromObject = function fromObject(object) { - if (object instanceof $root.google.protobuf.UInt32Value) - return object; - var message = new $root.google.protobuf.UInt32Value(); - if (object.value != null) - message.value = object.value >>> 0; - return message; - }; + /** + * Constructs a new ListenResponse. + * @memberof google.firestore.v1 + * @classdesc Represents a ListenResponse. + * @implements IListenResponse + * @constructor + * @param {google.firestore.v1.IListenResponse=} [properties] Properties to set + */ + function ListenResponse(properties) { + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } - /** - * Creates a plain object from a UInt32Value message. Also converts values to other types if specified. - * @function toObject - * @memberof google.protobuf.UInt32Value - * @static - * @param {google.protobuf.UInt32Value} message UInt32Value - * @param {$protobuf.IConversionOptions} [options] Conversion options - * @returns {Object.} Plain object - */ - UInt32Value.toObject = function toObject(message, options) { - if (!options) - options = {}; - var object = {}; - if (options.defaults) - object.value = 0; - if (message.value != null && message.hasOwnProperty("value")) - object.value = message.value; - return object; - }; + /** + * ListenResponse targetChange. + * @member {google.firestore.v1.ITargetChange|null|undefined} targetChange + * @memberof google.firestore.v1.ListenResponse + * @instance + */ + ListenResponse.prototype.targetChange = null; - /** - * Converts this UInt32Value to JSON. - * @function toJSON - * @memberof google.protobuf.UInt32Value - * @instance - * @returns {Object.} JSON object - */ - UInt32Value.prototype.toJSON = function toJSON() { - return this.constructor.toObject(this, $protobuf.util.toJSONOptions); - }; + /** + * ListenResponse documentChange. + * @member {google.firestore.v1.IDocumentChange|null|undefined} documentChange + * @memberof google.firestore.v1.ListenResponse + * @instance + */ + ListenResponse.prototype.documentChange = null; - /** - * Gets the default type url for UInt32Value - * @function getTypeUrl - * @memberof google.protobuf.UInt32Value - * @static - * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") - * @returns {string} The default type url - */ - UInt32Value.getTypeUrl = function getTypeUrl(typeUrlPrefix) { - if (typeUrlPrefix === undefined) { - typeUrlPrefix = "type.googleapis.com"; - } - return typeUrlPrefix + "/google.protobuf.UInt32Value"; - }; + /** + * ListenResponse documentDelete. + * @member {google.firestore.v1.IDocumentDelete|null|undefined} documentDelete + * @memberof google.firestore.v1.ListenResponse + * @instance + */ + ListenResponse.prototype.documentDelete = null; - return UInt32Value; - })(); + /** + * ListenResponse documentRemove. + * @member {google.firestore.v1.IDocumentRemove|null|undefined} documentRemove + * @memberof google.firestore.v1.ListenResponse + * @instance + */ + ListenResponse.prototype.documentRemove = null; - protobuf.BoolValue = (function() { + /** + * ListenResponse filter. + * @member {google.firestore.v1.IExistenceFilter|null|undefined} filter + * @memberof google.firestore.v1.ListenResponse + * @instance + */ + ListenResponse.prototype.filter = null; - /** - * Properties of a BoolValue. - * @memberof google.protobuf - * @interface IBoolValue - * @property {boolean|null} [value] BoolValue value - */ + // OneOf field names bound to virtual getters and setters + var $oneOfFields; - /** - * Constructs a new BoolValue. - * @memberof google.protobuf - * @classdesc Represents a BoolValue. - * @implements IBoolValue - * @constructor - * @param {google.protobuf.IBoolValue=} [properties] Properties to set - */ - function BoolValue(properties) { - if (properties) - for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) - if (properties[keys[i]] != null) - this[keys[i]] = properties[keys[i]]; - } + /** + * ListenResponse responseType. + * @member {"targetChange"|"documentChange"|"documentDelete"|"documentRemove"|"filter"|undefined} responseType + * @memberof google.firestore.v1.ListenResponse + * @instance + */ + Object.defineProperty(ListenResponse.prototype, "responseType", { + get: $util.oneOfGetter($oneOfFields = ["targetChange", "documentChange", "documentDelete", "documentRemove", "filter"]), + set: $util.oneOfSetter($oneOfFields) + }); - /** - * BoolValue value. - * @member {boolean} value - * @memberof google.protobuf.BoolValue - * @instance - */ - BoolValue.prototype.value = false; + /** + * Creates a ListenResponse message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.firestore.v1.ListenResponse + * @static + * @param {Object.} object Plain object + * @returns {google.firestore.v1.ListenResponse} ListenResponse + */ + ListenResponse.fromObject = function fromObject(object) { + if (object instanceof $root.google.firestore.v1.ListenResponse) + return object; + var message = new $root.google.firestore.v1.ListenResponse(); + if (object.targetChange != null) { + if (typeof object.targetChange !== "object") + throw TypeError(".google.firestore.v1.ListenResponse.targetChange: object expected"); + message.targetChange = $root.google.firestore.v1.TargetChange.fromObject(object.targetChange); + } + if (object.documentChange != null) { + if (typeof object.documentChange !== "object") + throw TypeError(".google.firestore.v1.ListenResponse.documentChange: object expected"); + message.documentChange = $root.google.firestore.v1.DocumentChange.fromObject(object.documentChange); + } + if (object.documentDelete != null) { + if (typeof object.documentDelete !== "object") + throw TypeError(".google.firestore.v1.ListenResponse.documentDelete: object expected"); + message.documentDelete = $root.google.firestore.v1.DocumentDelete.fromObject(object.documentDelete); + } + if (object.documentRemove != null) { + if (typeof object.documentRemove !== "object") + throw TypeError(".google.firestore.v1.ListenResponse.documentRemove: object expected"); + message.documentRemove = $root.google.firestore.v1.DocumentRemove.fromObject(object.documentRemove); + } + if (object.filter != null) { + if (typeof object.filter !== "object") + throw TypeError(".google.firestore.v1.ListenResponse.filter: object expected"); + message.filter = $root.google.firestore.v1.ExistenceFilter.fromObject(object.filter); + } + return message; + }; - /** - * Creates a BoolValue message from a plain object. Also converts values to their respective internal types. - * @function fromObject - * @memberof google.protobuf.BoolValue - * @static - * @param {Object.} object Plain object - * @returns {google.protobuf.BoolValue} BoolValue - */ - BoolValue.fromObject = function fromObject(object) { - if (object instanceof $root.google.protobuf.BoolValue) + /** + * Creates a plain object from a ListenResponse message. Also converts values to other types if specified. + * @function toObject + * @memberof google.firestore.v1.ListenResponse + * @static + * @param {google.firestore.v1.ListenResponse} message ListenResponse + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + ListenResponse.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (message.targetChange != null && message.hasOwnProperty("targetChange")) { + object.targetChange = $root.google.firestore.v1.TargetChange.toObject(message.targetChange, options); + if (options.oneofs) + object.responseType = "targetChange"; + } + if (message.documentChange != null && message.hasOwnProperty("documentChange")) { + object.documentChange = $root.google.firestore.v1.DocumentChange.toObject(message.documentChange, options); + if (options.oneofs) + object.responseType = "documentChange"; + } + if (message.documentDelete != null && message.hasOwnProperty("documentDelete")) { + object.documentDelete = $root.google.firestore.v1.DocumentDelete.toObject(message.documentDelete, options); + if (options.oneofs) + object.responseType = "documentDelete"; + } + if (message.filter != null && message.hasOwnProperty("filter")) { + object.filter = $root.google.firestore.v1.ExistenceFilter.toObject(message.filter, options); + if (options.oneofs) + object.responseType = "filter"; + } + if (message.documentRemove != null && message.hasOwnProperty("documentRemove")) { + object.documentRemove = $root.google.firestore.v1.DocumentRemove.toObject(message.documentRemove, options); + if (options.oneofs) + object.responseType = "documentRemove"; + } return object; - var message = new $root.google.protobuf.BoolValue(); - if (object.value != null) - message.value = Boolean(object.value); - return message; - }; - - /** - * Creates a plain object from a BoolValue message. Also converts values to other types if specified. - * @function toObject - * @memberof google.protobuf.BoolValue - * @static - * @param {google.protobuf.BoolValue} message BoolValue - * @param {$protobuf.IConversionOptions} [options] Conversion options - * @returns {Object.} Plain object - */ - BoolValue.toObject = function toObject(message, options) { - if (!options) - options = {}; - var object = {}; - if (options.defaults) - object.value = false; - if (message.value != null && message.hasOwnProperty("value")) - object.value = message.value; - return object; - }; - - /** - * Converts this BoolValue to JSON. - * @function toJSON - * @memberof google.protobuf.BoolValue - * @instance - * @returns {Object.} JSON object - */ - BoolValue.prototype.toJSON = function toJSON() { - return this.constructor.toObject(this, $protobuf.util.toJSONOptions); - }; + }; - /** - * Gets the default type url for BoolValue - * @function getTypeUrl - * @memberof google.protobuf.BoolValue - * @static - * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") - * @returns {string} The default type url - */ - BoolValue.getTypeUrl = function getTypeUrl(typeUrlPrefix) { - if (typeUrlPrefix === undefined) { - typeUrlPrefix = "type.googleapis.com"; - } - return typeUrlPrefix + "/google.protobuf.BoolValue"; - }; + /** + * Converts this ListenResponse to JSON. + * @function toJSON + * @memberof google.firestore.v1.ListenResponse + * @instance + * @returns {Object.} JSON object + */ + ListenResponse.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; - return BoolValue; - })(); + /** + * Gets the default type url for ListenResponse + * @function getTypeUrl + * @memberof google.firestore.v1.ListenResponse + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + ListenResponse.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.firestore.v1.ListenResponse"; + }; - protobuf.StringValue = (function() { + return ListenResponse; + })(); - /** - * Properties of a StringValue. - * @memberof google.protobuf - * @interface IStringValue - * @property {string|null} [value] StringValue value - */ + v1.Target = (function() { - /** - * Constructs a new StringValue. - * @memberof google.protobuf - * @classdesc Represents a StringValue. - * @implements IStringValue - * @constructor - * @param {google.protobuf.IStringValue=} [properties] Properties to set - */ - function StringValue(properties) { - if (properties) - for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) - if (properties[keys[i]] != null) - this[keys[i]] = properties[keys[i]]; - } + /** + * Properties of a Target. + * @memberof google.firestore.v1 + * @interface ITarget + * @property {google.firestore.v1.Target.IQueryTarget|null} [query] Target query + * @property {google.firestore.v1.Target.IDocumentsTarget|null} [documents] Target documents + * @property {Uint8Array|null} [resumeToken] Target resumeToken + * @property {google.protobuf.ITimestamp|null} [readTime] Target readTime + * @property {number|null} [targetId] Target targetId + * @property {boolean|null} [once] Target once + * @property {google.protobuf.IInt32Value|null} [expectedCount] Target expectedCount + */ - /** - * StringValue value. - * @member {string} value - * @memberof google.protobuf.StringValue - * @instance - */ - StringValue.prototype.value = ""; + /** + * Constructs a new Target. + * @memberof google.firestore.v1 + * @classdesc Represents a Target. + * @implements ITarget + * @constructor + * @param {google.firestore.v1.ITarget=} [properties] Properties to set + */ + function Target(properties) { + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } - /** - * Creates a StringValue message from a plain object. Also converts values to their respective internal types. - * @function fromObject - * @memberof google.protobuf.StringValue - * @static - * @param {Object.} object Plain object - * @returns {google.protobuf.StringValue} StringValue - */ - StringValue.fromObject = function fromObject(object) { - if (object instanceof $root.google.protobuf.StringValue) - return object; - var message = new $root.google.protobuf.StringValue(); - if (object.value != null) - message.value = String(object.value); - return message; - }; + /** + * Target query. + * @member {google.firestore.v1.Target.IQueryTarget|null|undefined} query + * @memberof google.firestore.v1.Target + * @instance + */ + Target.prototype.query = null; - /** - * Creates a plain object from a StringValue message. Also converts values to other types if specified. - * @function toObject - * @memberof google.protobuf.StringValue - * @static - * @param {google.protobuf.StringValue} message StringValue - * @param {$protobuf.IConversionOptions} [options] Conversion options - * @returns {Object.} Plain object - */ - StringValue.toObject = function toObject(message, options) { - if (!options) - options = {}; - var object = {}; - if (options.defaults) - object.value = ""; - if (message.value != null && message.hasOwnProperty("value")) - object.value = message.value; - return object; - }; + /** + * Target documents. + * @member {google.firestore.v1.Target.IDocumentsTarget|null|undefined} documents + * @memberof google.firestore.v1.Target + * @instance + */ + Target.prototype.documents = null; - /** - * Converts this StringValue to JSON. - * @function toJSON - * @memberof google.protobuf.StringValue - * @instance - * @returns {Object.} JSON object - */ - StringValue.prototype.toJSON = function toJSON() { - return this.constructor.toObject(this, $protobuf.util.toJSONOptions); - }; + /** + * Target resumeToken. + * @member {Uint8Array|null|undefined} resumeToken + * @memberof google.firestore.v1.Target + * @instance + */ + Target.prototype.resumeToken = null; - /** - * Gets the default type url for StringValue - * @function getTypeUrl - * @memberof google.protobuf.StringValue - * @static - * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") - * @returns {string} The default type url - */ - StringValue.getTypeUrl = function getTypeUrl(typeUrlPrefix) { - if (typeUrlPrefix === undefined) { - typeUrlPrefix = "type.googleapis.com"; - } - return typeUrlPrefix + "/google.protobuf.StringValue"; - }; + /** + * Target readTime. + * @member {google.protobuf.ITimestamp|null|undefined} readTime + * @memberof google.firestore.v1.Target + * @instance + */ + Target.prototype.readTime = null; - return StringValue; - })(); + /** + * Target targetId. + * @member {number} targetId + * @memberof google.firestore.v1.Target + * @instance + */ + Target.prototype.targetId = 0; - protobuf.BytesValue = (function() { + /** + * Target once. + * @member {boolean} once + * @memberof google.firestore.v1.Target + * @instance + */ + Target.prototype.once = false; - /** - * Properties of a BytesValue. - * @memberof google.protobuf - * @interface IBytesValue - * @property {Uint8Array|null} [value] BytesValue value - */ + /** + * Target expectedCount. + * @member {google.protobuf.IInt32Value|null|undefined} expectedCount + * @memberof google.firestore.v1.Target + * @instance + */ + Target.prototype.expectedCount = null; - /** - * Constructs a new BytesValue. - * @memberof google.protobuf - * @classdesc Represents a BytesValue. - * @implements IBytesValue - * @constructor - * @param {google.protobuf.IBytesValue=} [properties] Properties to set - */ - function BytesValue(properties) { - if (properties) - for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) - if (properties[keys[i]] != null) - this[keys[i]] = properties[keys[i]]; - } + // OneOf field names bound to virtual getters and setters + var $oneOfFields; - /** - * BytesValue value. - * @member {Uint8Array} value - * @memberof google.protobuf.BytesValue - * @instance - */ - BytesValue.prototype.value = $util.newBuffer([]); + /** + * Target targetType. + * @member {"query"|"documents"|undefined} targetType + * @memberof google.firestore.v1.Target + * @instance + */ + Object.defineProperty(Target.prototype, "targetType", { + get: $util.oneOfGetter($oneOfFields = ["query", "documents"]), + set: $util.oneOfSetter($oneOfFields) + }); - /** - * Creates a BytesValue message from a plain object. Also converts values to their respective internal types. - * @function fromObject - * @memberof google.protobuf.BytesValue - * @static - * @param {Object.} object Plain object - * @returns {google.protobuf.BytesValue} BytesValue - */ - BytesValue.fromObject = function fromObject(object) { - if (object instanceof $root.google.protobuf.BytesValue) - return object; - var message = new $root.google.protobuf.BytesValue(); - if (object.value != null) - if (typeof object.value === "string") - $util.base64.decode(object.value, message.value = $util.newBuffer($util.base64.length(object.value)), 0); - else if (object.value.length >= 0) - message.value = object.value; - return message; - }; + /** + * Target resumeType. + * @member {"resumeToken"|"readTime"|undefined} resumeType + * @memberof google.firestore.v1.Target + * @instance + */ + Object.defineProperty(Target.prototype, "resumeType", { + get: $util.oneOfGetter($oneOfFields = ["resumeToken", "readTime"]), + set: $util.oneOfSetter($oneOfFields) + }); - /** - * Creates a plain object from a BytesValue message. Also converts values to other types if specified. - * @function toObject - * @memberof google.protobuf.BytesValue - * @static - * @param {google.protobuf.BytesValue} message BytesValue - * @param {$protobuf.IConversionOptions} [options] Conversion options - * @returns {Object.} Plain object - */ - BytesValue.toObject = function toObject(message, options) { - if (!options) - options = {}; - var object = {}; - if (options.defaults) - if (options.bytes === String) - object.value = ""; - else { - object.value = []; - if (options.bytes !== Array) - object.value = $util.newBuffer(object.value); + /** + * Creates a Target message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.firestore.v1.Target + * @static + * @param {Object.} object Plain object + * @returns {google.firestore.v1.Target} Target + */ + Target.fromObject = function fromObject(object) { + if (object instanceof $root.google.firestore.v1.Target) + return object; + var message = new $root.google.firestore.v1.Target(); + if (object.query != null) { + if (typeof object.query !== "object") + throw TypeError(".google.firestore.v1.Target.query: object expected"); + message.query = $root.google.firestore.v1.Target.QueryTarget.fromObject(object.query); } - if (message.value != null && message.hasOwnProperty("value")) - object.value = options.bytes === String ? $util.base64.encode(message.value, 0, message.value.length) : options.bytes === Array ? Array.prototype.slice.call(message.value) : message.value; - return object; - }; + if (object.documents != null) { + if (typeof object.documents !== "object") + throw TypeError(".google.firestore.v1.Target.documents: object expected"); + message.documents = $root.google.firestore.v1.Target.DocumentsTarget.fromObject(object.documents); + } + if (object.resumeToken != null) + if (typeof object.resumeToken === "string") + $util.base64.decode(object.resumeToken, message.resumeToken = $util.newBuffer($util.base64.length(object.resumeToken)), 0); + else if (object.resumeToken.length >= 0) + message.resumeToken = object.resumeToken; + if (object.readTime != null) { + if (typeof object.readTime !== "object") + throw TypeError(".google.firestore.v1.Target.readTime: object expected"); + message.readTime = $root.google.protobuf.Timestamp.fromObject(object.readTime); + } + if (object.targetId != null) + message.targetId = object.targetId | 0; + if (object.once != null) + message.once = Boolean(object.once); + if (object.expectedCount != null) { + if (typeof object.expectedCount !== "object") + throw TypeError(".google.firestore.v1.Target.expectedCount: object expected"); + message.expectedCount = $root.google.protobuf.Int32Value.fromObject(object.expectedCount); + } + return message; + }; - /** - * Converts this BytesValue to JSON. - * @function toJSON - * @memberof google.protobuf.BytesValue - * @instance - * @returns {Object.} JSON object - */ - BytesValue.prototype.toJSON = function toJSON() { - return this.constructor.toObject(this, $protobuf.util.toJSONOptions); - }; + /** + * Creates a plain object from a Target message. Also converts values to other types if specified. + * @function toObject + * @memberof google.firestore.v1.Target + * @static + * @param {google.firestore.v1.Target} message Target + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + Target.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.defaults) { + object.targetId = 0; + object.once = false; + object.expectedCount = null; + } + if (message.query != null && message.hasOwnProperty("query")) { + object.query = $root.google.firestore.v1.Target.QueryTarget.toObject(message.query, options); + if (options.oneofs) + object.targetType = "query"; + } + if (message.documents != null && message.hasOwnProperty("documents")) { + object.documents = $root.google.firestore.v1.Target.DocumentsTarget.toObject(message.documents, options); + if (options.oneofs) + object.targetType = "documents"; + } + if (message.resumeToken != null && message.hasOwnProperty("resumeToken")) { + object.resumeToken = options.bytes === String ? $util.base64.encode(message.resumeToken, 0, message.resumeToken.length) : options.bytes === Array ? Array.prototype.slice.call(message.resumeToken) : message.resumeToken; + if (options.oneofs) + object.resumeType = "resumeToken"; + } + if (message.targetId != null && message.hasOwnProperty("targetId")) + object.targetId = message.targetId; + if (message.once != null && message.hasOwnProperty("once")) + object.once = message.once; + if (message.readTime != null && message.hasOwnProperty("readTime")) { + object.readTime = $root.google.protobuf.Timestamp.toObject(message.readTime, options); + if (options.oneofs) + object.resumeType = "readTime"; + } + if (message.expectedCount != null && message.hasOwnProperty("expectedCount")) + object.expectedCount = $root.google.protobuf.Int32Value.toObject(message.expectedCount, options); + return object; + }; - /** - * Gets the default type url for BytesValue - * @function getTypeUrl - * @memberof google.protobuf.BytesValue - * @static - * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") - * @returns {string} The default type url - */ - BytesValue.getTypeUrl = function getTypeUrl(typeUrlPrefix) { - if (typeUrlPrefix === undefined) { - typeUrlPrefix = "type.googleapis.com"; - } - return typeUrlPrefix + "/google.protobuf.BytesValue"; - }; + /** + * Converts this Target to JSON. + * @function toJSON + * @memberof google.firestore.v1.Target + * @instance + * @returns {Object.} JSON object + */ + Target.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; - return BytesValue; - })(); + /** + * Gets the default type url for Target + * @function getTypeUrl + * @memberof google.firestore.v1.Target + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + Target.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.firestore.v1.Target"; + }; - protobuf.Empty = (function() { + Target.DocumentsTarget = (function() { - /** - * Properties of an Empty. - * @memberof google.protobuf - * @interface IEmpty - */ + /** + * Properties of a DocumentsTarget. + * @memberof google.firestore.v1.Target + * @interface IDocumentsTarget + * @property {Array.|null} [documents] DocumentsTarget documents + */ - /** - * Constructs a new Empty. - * @memberof google.protobuf - * @classdesc Represents an Empty. - * @implements IEmpty - * @constructor - * @param {google.protobuf.IEmpty=} [properties] Properties to set - */ - function Empty(properties) { - if (properties) - for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) - if (properties[keys[i]] != null) - this[keys[i]] = properties[keys[i]]; - } + /** + * Constructs a new DocumentsTarget. + * @memberof google.firestore.v1.Target + * @classdesc Represents a DocumentsTarget. + * @implements IDocumentsTarget + * @constructor + * @param {google.firestore.v1.Target.IDocumentsTarget=} [properties] Properties to set + */ + function DocumentsTarget(properties) { + this.documents = []; + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } - /** - * Creates an Empty message from a plain object. Also converts values to their respective internal types. - * @function fromObject - * @memberof google.protobuf.Empty - * @static - * @param {Object.} object Plain object - * @returns {google.protobuf.Empty} Empty - */ - Empty.fromObject = function fromObject(object) { - if (object instanceof $root.google.protobuf.Empty) - return object; - return new $root.google.protobuf.Empty(); - }; + /** + * DocumentsTarget documents. + * @member {Array.} documents + * @memberof google.firestore.v1.Target.DocumentsTarget + * @instance + */ + DocumentsTarget.prototype.documents = $util.emptyArray; - /** - * Creates a plain object from an Empty message. Also converts values to other types if specified. - * @function toObject - * @memberof google.protobuf.Empty - * @static - * @param {google.protobuf.Empty} message Empty - * @param {$protobuf.IConversionOptions} [options] Conversion options - * @returns {Object.} Plain object - */ - Empty.toObject = function toObject() { - return {}; - }; + /** + * Creates a DocumentsTarget message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.firestore.v1.Target.DocumentsTarget + * @static + * @param {Object.} object Plain object + * @returns {google.firestore.v1.Target.DocumentsTarget} DocumentsTarget + */ + DocumentsTarget.fromObject = function fromObject(object) { + if (object instanceof $root.google.firestore.v1.Target.DocumentsTarget) + return object; + var message = new $root.google.firestore.v1.Target.DocumentsTarget(); + if (object.documents) { + if (!Array.isArray(object.documents)) + throw TypeError(".google.firestore.v1.Target.DocumentsTarget.documents: array expected"); + message.documents = []; + for (var i = 0; i < object.documents.length; ++i) + message.documents[i] = String(object.documents[i]); + } + return message; + }; - /** - * Converts this Empty to JSON. - * @function toJSON - * @memberof google.protobuf.Empty - * @instance - * @returns {Object.} JSON object - */ - Empty.prototype.toJSON = function toJSON() { - return this.constructor.toObject(this, $protobuf.util.toJSONOptions); - }; + /** + * Creates a plain object from a DocumentsTarget message. Also converts values to other types if specified. + * @function toObject + * @memberof google.firestore.v1.Target.DocumentsTarget + * @static + * @param {google.firestore.v1.Target.DocumentsTarget} message DocumentsTarget + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + DocumentsTarget.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.arrays || options.defaults) + object.documents = []; + if (message.documents && message.documents.length) { + object.documents = []; + for (var j = 0; j < message.documents.length; ++j) + object.documents[j] = message.documents[j]; + } + return object; + }; - /** - * Gets the default type url for Empty - * @function getTypeUrl - * @memberof google.protobuf.Empty - * @static - * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") - * @returns {string} The default type url - */ - Empty.getTypeUrl = function getTypeUrl(typeUrlPrefix) { - if (typeUrlPrefix === undefined) { - typeUrlPrefix = "type.googleapis.com"; - } - return typeUrlPrefix + "/google.protobuf.Empty"; - }; + /** + * Converts this DocumentsTarget to JSON. + * @function toJSON + * @memberof google.firestore.v1.Target.DocumentsTarget + * @instance + * @returns {Object.} JSON object + */ + DocumentsTarget.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; - return Empty; - })(); + /** + * Gets the default type url for DocumentsTarget + * @function getTypeUrl + * @memberof google.firestore.v1.Target.DocumentsTarget + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + DocumentsTarget.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.firestore.v1.Target.DocumentsTarget"; + }; - protobuf.Any = (function() { + return DocumentsTarget; + })(); - /** - * Properties of an Any. - * @memberof google.protobuf - * @interface IAny - * @property {string|null} [type_url] Any type_url - * @property {Uint8Array|null} [value] Any value - */ + Target.QueryTarget = (function() { - /** - * Constructs a new Any. - * @memberof google.protobuf - * @classdesc Represents an Any. - * @implements IAny - * @constructor - * @param {google.protobuf.IAny=} [properties] Properties to set - */ - function Any(properties) { - if (properties) - for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) - if (properties[keys[i]] != null) - this[keys[i]] = properties[keys[i]]; - } + /** + * Properties of a QueryTarget. + * @memberof google.firestore.v1.Target + * @interface IQueryTarget + * @property {string|null} [parent] QueryTarget parent + * @property {google.firestore.v1.IStructuredQuery|null} [structuredQuery] QueryTarget structuredQuery + */ - /** - * Any type_url. - * @member {string} type_url - * @memberof google.protobuf.Any - * @instance - */ - Any.prototype.type_url = ""; + /** + * Constructs a new QueryTarget. + * @memberof google.firestore.v1.Target + * @classdesc Represents a QueryTarget. + * @implements IQueryTarget + * @constructor + * @param {google.firestore.v1.Target.IQueryTarget=} [properties] Properties to set + */ + function QueryTarget(properties) { + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } - /** - * Any value. - * @member {Uint8Array} value - * @memberof google.protobuf.Any - * @instance - */ - Any.prototype.value = $util.newBuffer([]); + /** + * QueryTarget parent. + * @member {string} parent + * @memberof google.firestore.v1.Target.QueryTarget + * @instance + */ + QueryTarget.prototype.parent = ""; - /** - * Creates an Any message from a plain object. Also converts values to their respective internal types. - * @function fromObject - * @memberof google.protobuf.Any - * @static - * @param {Object.} object Plain object - * @returns {google.protobuf.Any} Any - */ - Any.fromObject = function fromObject(object) { - if (object instanceof $root.google.protobuf.Any) - return object; - var message = new $root.google.protobuf.Any(); - if (object.type_url != null) - message.type_url = String(object.type_url); - if (object.value != null) - if (typeof object.value === "string") - $util.base64.decode(object.value, message.value = $util.newBuffer($util.base64.length(object.value)), 0); - else if (object.value.length >= 0) - message.value = object.value; - return message; - }; + /** + * QueryTarget structuredQuery. + * @member {google.firestore.v1.IStructuredQuery|null|undefined} structuredQuery + * @memberof google.firestore.v1.Target.QueryTarget + * @instance + */ + QueryTarget.prototype.structuredQuery = null; - /** - * Creates a plain object from an Any message. Also converts values to other types if specified. - * @function toObject - * @memberof google.protobuf.Any - * @static - * @param {google.protobuf.Any} message Any - * @param {$protobuf.IConversionOptions} [options] Conversion options - * @returns {Object.} Plain object - */ - Any.toObject = function toObject(message, options) { - if (!options) - options = {}; - var object = {}; - if (options.defaults) { - object.type_url = ""; - if (options.bytes === String) - object.value = ""; - else { - object.value = []; - if (options.bytes !== Array) - object.value = $util.newBuffer(object.value); - } - } - if (message.type_url != null && message.hasOwnProperty("type_url")) - object.type_url = message.type_url; - if (message.value != null && message.hasOwnProperty("value")) - object.value = options.bytes === String ? $util.base64.encode(message.value, 0, message.value.length) : options.bytes === Array ? Array.prototype.slice.call(message.value) : message.value; - return object; - }; + // OneOf field names bound to virtual getters and setters + var $oneOfFields; - /** - * Converts this Any to JSON. - * @function toJSON - * @memberof google.protobuf.Any - * @instance - * @returns {Object.} JSON object - */ - Any.prototype.toJSON = function toJSON() { - return this.constructor.toObject(this, $protobuf.util.toJSONOptions); - }; + /** + * QueryTarget queryType. + * @member {"structuredQuery"|undefined} queryType + * @memberof google.firestore.v1.Target.QueryTarget + * @instance + */ + Object.defineProperty(QueryTarget.prototype, "queryType", { + get: $util.oneOfGetter($oneOfFields = ["structuredQuery"]), + set: $util.oneOfSetter($oneOfFields) + }); - /** - * Gets the default type url for Any - * @function getTypeUrl - * @memberof google.protobuf.Any - * @static - * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") - * @returns {string} The default type url - */ - Any.getTypeUrl = function getTypeUrl(typeUrlPrefix) { - if (typeUrlPrefix === undefined) { - typeUrlPrefix = "type.googleapis.com"; - } - return typeUrlPrefix + "/google.protobuf.Any"; - }; + /** + * Creates a QueryTarget message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.firestore.v1.Target.QueryTarget + * @static + * @param {Object.} object Plain object + * @returns {google.firestore.v1.Target.QueryTarget} QueryTarget + */ + QueryTarget.fromObject = function fromObject(object) { + if (object instanceof $root.google.firestore.v1.Target.QueryTarget) + return object; + var message = new $root.google.firestore.v1.Target.QueryTarget(); + if (object.parent != null) + message.parent = String(object.parent); + if (object.structuredQuery != null) { + if (typeof object.structuredQuery !== "object") + throw TypeError(".google.firestore.v1.Target.QueryTarget.structuredQuery: object expected"); + message.structuredQuery = $root.google.firestore.v1.StructuredQuery.fromObject(object.structuredQuery); + } + return message; + }; - return Any; - })(); + /** + * Creates a plain object from a QueryTarget message. Also converts values to other types if specified. + * @function toObject + * @memberof google.firestore.v1.Target.QueryTarget + * @static + * @param {google.firestore.v1.Target.QueryTarget} message QueryTarget + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + QueryTarget.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.defaults) + object.parent = ""; + if (message.parent != null && message.hasOwnProperty("parent")) + object.parent = message.parent; + if (message.structuredQuery != null && message.hasOwnProperty("structuredQuery")) { + object.structuredQuery = $root.google.firestore.v1.StructuredQuery.toObject(message.structuredQuery, options); + if (options.oneofs) + object.queryType = "structuredQuery"; + } + return object; + }; - protobuf.FieldMask = (function() { + /** + * Converts this QueryTarget to JSON. + * @function toJSON + * @memberof google.firestore.v1.Target.QueryTarget + * @instance + * @returns {Object.} JSON object + */ + QueryTarget.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; - /** - * Properties of a FieldMask. - * @memberof google.protobuf - * @interface IFieldMask - * @property {Array.|null} [paths] FieldMask paths - */ + /** + * Gets the default type url for QueryTarget + * @function getTypeUrl + * @memberof google.firestore.v1.Target.QueryTarget + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + QueryTarget.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.firestore.v1.Target.QueryTarget"; + }; - /** - * Constructs a new FieldMask. - * @memberof google.protobuf - * @classdesc Represents a FieldMask. - * @implements IFieldMask - * @constructor - * @param {google.protobuf.IFieldMask=} [properties] Properties to set - */ - function FieldMask(properties) { - this.paths = []; - if (properties) - for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) - if (properties[keys[i]] != null) - this[keys[i]] = properties[keys[i]]; - } + return QueryTarget; + })(); - /** - * FieldMask paths. - * @member {Array.} paths - * @memberof google.protobuf.FieldMask - * @instance - */ - FieldMask.prototype.paths = $util.emptyArray; + return Target; + })(); - /** - * Creates a FieldMask message from a plain object. Also converts values to their respective internal types. - * @function fromObject - * @memberof google.protobuf.FieldMask - * @static - * @param {Object.} object Plain object - * @returns {google.protobuf.FieldMask} FieldMask - */ - FieldMask.fromObject = function fromObject(object) { - if (object instanceof $root.google.protobuf.FieldMask) - return object; - var message = new $root.google.protobuf.FieldMask(); - if (object.paths) { - if (!Array.isArray(object.paths)) - throw TypeError(".google.protobuf.FieldMask.paths: array expected"); - message.paths = []; - for (var i = 0; i < object.paths.length; ++i) - message.paths[i] = String(object.paths[i]); - } - return message; - }; + v1.TargetChange = (function() { - /** - * Creates a plain object from a FieldMask message. Also converts values to other types if specified. - * @function toObject - * @memberof google.protobuf.FieldMask - * @static - * @param {google.protobuf.FieldMask} message FieldMask - * @param {$protobuf.IConversionOptions} [options] Conversion options - * @returns {Object.} Plain object - */ - FieldMask.toObject = function toObject(message, options) { - if (!options) - options = {}; - var object = {}; - if (options.arrays || options.defaults) - object.paths = []; - if (message.paths && message.paths.length) { - object.paths = []; - for (var j = 0; j < message.paths.length; ++j) - object.paths[j] = message.paths[j]; + /** + * Properties of a TargetChange. + * @memberof google.firestore.v1 + * @interface ITargetChange + * @property {google.firestore.v1.TargetChange.TargetChangeType|null} [targetChangeType] TargetChange targetChangeType + * @property {Array.|null} [targetIds] TargetChange targetIds + * @property {google.rpc.IStatus|null} [cause] TargetChange cause + * @property {Uint8Array|null} [resumeToken] TargetChange resumeToken + * @property {google.protobuf.ITimestamp|null} [readTime] TargetChange readTime + */ + + /** + * Constructs a new TargetChange. + * @memberof google.firestore.v1 + * @classdesc Represents a TargetChange. + * @implements ITargetChange + * @constructor + * @param {google.firestore.v1.ITargetChange=} [properties] Properties to set + */ + function TargetChange(properties) { + this.targetIds = []; + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; } - return object; - }; - /** - * Converts this FieldMask to JSON. - * @function toJSON - * @memberof google.protobuf.FieldMask - * @instance - * @returns {Object.} JSON object - */ - FieldMask.prototype.toJSON = function toJSON() { - return this.constructor.toObject(this, $protobuf.util.toJSONOptions); - }; + /** + * TargetChange targetChangeType. + * @member {google.firestore.v1.TargetChange.TargetChangeType} targetChangeType + * @memberof google.firestore.v1.TargetChange + * @instance + */ + TargetChange.prototype.targetChangeType = 0; - /** - * Gets the default type url for FieldMask - * @function getTypeUrl - * @memberof google.protobuf.FieldMask - * @static - * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") - * @returns {string} The default type url - */ - FieldMask.getTypeUrl = function getTypeUrl(typeUrlPrefix) { - if (typeUrlPrefix === undefined) { - typeUrlPrefix = "type.googleapis.com"; - } - return typeUrlPrefix + "/google.protobuf.FieldMask"; - }; + /** + * TargetChange targetIds. + * @member {Array.} targetIds + * @memberof google.firestore.v1.TargetChange + * @instance + */ + TargetChange.prototype.targetIds = $util.emptyArray; - return FieldMask; - })(); + /** + * TargetChange cause. + * @member {google.rpc.IStatus|null|undefined} cause + * @memberof google.firestore.v1.TargetChange + * @instance + */ + TargetChange.prototype.cause = null; - return protobuf; - })(); + /** + * TargetChange resumeToken. + * @member {Uint8Array} resumeToken + * @memberof google.firestore.v1.TargetChange + * @instance + */ + TargetChange.prototype.resumeToken = $util.newBuffer([]); - google.firestore = (function() { + /** + * TargetChange readTime. + * @member {google.protobuf.ITimestamp|null|undefined} readTime + * @memberof google.firestore.v1.TargetChange + * @instance + */ + TargetChange.prototype.readTime = null; - /** - * Namespace firestore. - * @memberof google - * @namespace - */ - var firestore = {}; + /** + * Creates a TargetChange message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.firestore.v1.TargetChange + * @static + * @param {Object.} object Plain object + * @returns {google.firestore.v1.TargetChange} TargetChange + */ + TargetChange.fromObject = function fromObject(object) { + if (object instanceof $root.google.firestore.v1.TargetChange) + return object; + var message = new $root.google.firestore.v1.TargetChange(); + switch (object.targetChangeType) { + default: + if (typeof object.targetChangeType === "number") { + message.targetChangeType = object.targetChangeType; + break; + } + break; + case "NO_CHANGE": + case 0: + message.targetChangeType = 0; + break; + case "ADD": + case 1: + message.targetChangeType = 1; + break; + case "REMOVE": + case 2: + message.targetChangeType = 2; + break; + case "CURRENT": + case 3: + message.targetChangeType = 3; + break; + case "RESET": + case 4: + message.targetChangeType = 4; + break; + } + if (object.targetIds) { + if (!Array.isArray(object.targetIds)) + throw TypeError(".google.firestore.v1.TargetChange.targetIds: array expected"); + message.targetIds = []; + for (var i = 0; i < object.targetIds.length; ++i) + message.targetIds[i] = object.targetIds[i] | 0; + } + if (object.cause != null) { + if (typeof object.cause !== "object") + throw TypeError(".google.firestore.v1.TargetChange.cause: object expected"); + message.cause = $root.google.rpc.Status.fromObject(object.cause); + } + if (object.resumeToken != null) + if (typeof object.resumeToken === "string") + $util.base64.decode(object.resumeToken, message.resumeToken = $util.newBuffer($util.base64.length(object.resumeToken)), 0); + else if (object.resumeToken.length >= 0) + message.resumeToken = object.resumeToken; + if (object.readTime != null) { + if (typeof object.readTime !== "object") + throw TypeError(".google.firestore.v1.TargetChange.readTime: object expected"); + message.readTime = $root.google.protobuf.Timestamp.fromObject(object.readTime); + } + return message; + }; - firestore.v1 = (function() { + /** + * Creates a plain object from a TargetChange message. Also converts values to other types if specified. + * @function toObject + * @memberof google.firestore.v1.TargetChange + * @static + * @param {google.firestore.v1.TargetChange} message TargetChange + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + TargetChange.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.arrays || options.defaults) + object.targetIds = []; + if (options.defaults) { + object.targetChangeType = options.enums === String ? "NO_CHANGE" : 0; + object.cause = null; + if (options.bytes === String) + object.resumeToken = ""; + else { + object.resumeToken = []; + if (options.bytes !== Array) + object.resumeToken = $util.newBuffer(object.resumeToken); + } + object.readTime = null; + } + if (message.targetChangeType != null && message.hasOwnProperty("targetChangeType")) + object.targetChangeType = options.enums === String ? $root.google.firestore.v1.TargetChange.TargetChangeType[message.targetChangeType] === undefined ? message.targetChangeType : $root.google.firestore.v1.TargetChange.TargetChangeType[message.targetChangeType] : message.targetChangeType; + if (message.targetIds && message.targetIds.length) { + object.targetIds = []; + for (var j = 0; j < message.targetIds.length; ++j) + object.targetIds[j] = message.targetIds[j]; + } + if (message.cause != null && message.hasOwnProperty("cause")) + object.cause = $root.google.rpc.Status.toObject(message.cause, options); + if (message.resumeToken != null && message.hasOwnProperty("resumeToken")) + object.resumeToken = options.bytes === String ? $util.base64.encode(message.resumeToken, 0, message.resumeToken.length) : options.bytes === Array ? Array.prototype.slice.call(message.resumeToken) : message.resumeToken; + if (message.readTime != null && message.hasOwnProperty("readTime")) + object.readTime = $root.google.protobuf.Timestamp.toObject(message.readTime, options); + return object; + }; - /** - * Namespace v1. - * @memberof google.firestore - * @namespace - */ - var v1 = {}; + /** + * Converts this TargetChange to JSON. + * @function toJSON + * @memberof google.firestore.v1.TargetChange + * @instance + * @returns {Object.} JSON object + */ + TargetChange.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; - v1.AggregationResult = (function() { + /** + * Gets the default type url for TargetChange + * @function getTypeUrl + * @memberof google.firestore.v1.TargetChange + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + TargetChange.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.firestore.v1.TargetChange"; + }; /** - * Properties of an AggregationResult. + * TargetChangeType enum. + * @name google.firestore.v1.TargetChange.TargetChangeType + * @enum {string} + * @property {string} NO_CHANGE=NO_CHANGE NO_CHANGE value + * @property {string} ADD=ADD ADD value + * @property {string} REMOVE=REMOVE REMOVE value + * @property {string} CURRENT=CURRENT CURRENT value + * @property {string} RESET=RESET RESET value + */ + TargetChange.TargetChangeType = (function() { + var valuesById = {}, values = Object.create(valuesById); + values[valuesById[0] = "NO_CHANGE"] = "NO_CHANGE"; + values[valuesById[1] = "ADD"] = "ADD"; + values[valuesById[2] = "REMOVE"] = "REMOVE"; + values[valuesById[3] = "CURRENT"] = "CURRENT"; + values[valuesById[4] = "RESET"] = "RESET"; + return values; + })(); + + return TargetChange; + })(); + + v1.ListCollectionIdsRequest = (function() { + + /** + * Properties of a ListCollectionIdsRequest. * @memberof google.firestore.v1 - * @interface IAggregationResult - * @property {Object.|null} [aggregateFields] AggregationResult aggregateFields + * @interface IListCollectionIdsRequest + * @property {string|null} [parent] ListCollectionIdsRequest parent + * @property {number|null} [pageSize] ListCollectionIdsRequest pageSize + * @property {string|null} [pageToken] ListCollectionIdsRequest pageToken + * @property {google.protobuf.ITimestamp|null} [readTime] ListCollectionIdsRequest readTime */ /** - * Constructs a new AggregationResult. + * Constructs a new ListCollectionIdsRequest. * @memberof google.firestore.v1 - * @classdesc Represents an AggregationResult. - * @implements IAggregationResult + * @classdesc Represents a ListCollectionIdsRequest. + * @implements IListCollectionIdsRequest * @constructor - * @param {google.firestore.v1.IAggregationResult=} [properties] Properties to set + * @param {google.firestore.v1.IListCollectionIdsRequest=} [properties] Properties to set */ - function AggregationResult(properties) { - this.aggregateFields = {}; + function ListCollectionIdsRequest(properties) { if (properties) for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) if (properties[keys[i]] != null) @@ -9949,113 +8464,158 @@ } /** - * AggregationResult aggregateFields. - * @member {Object.} aggregateFields - * @memberof google.firestore.v1.AggregationResult + * ListCollectionIdsRequest parent. + * @member {string} parent + * @memberof google.firestore.v1.ListCollectionIdsRequest * @instance */ - AggregationResult.prototype.aggregateFields = $util.emptyObject; + ListCollectionIdsRequest.prototype.parent = ""; /** - * Creates an AggregationResult message from a plain object. Also converts values to their respective internal types. + * ListCollectionIdsRequest pageSize. + * @member {number} pageSize + * @memberof google.firestore.v1.ListCollectionIdsRequest + * @instance + */ + ListCollectionIdsRequest.prototype.pageSize = 0; + + /** + * ListCollectionIdsRequest pageToken. + * @member {string} pageToken + * @memberof google.firestore.v1.ListCollectionIdsRequest + * @instance + */ + ListCollectionIdsRequest.prototype.pageToken = ""; + + /** + * ListCollectionIdsRequest readTime. + * @member {google.protobuf.ITimestamp|null|undefined} readTime + * @memberof google.firestore.v1.ListCollectionIdsRequest + * @instance + */ + ListCollectionIdsRequest.prototype.readTime = null; + + // OneOf field names bound to virtual getters and setters + var $oneOfFields; + + /** + * ListCollectionIdsRequest consistencySelector. + * @member {"readTime"|undefined} consistencySelector + * @memberof google.firestore.v1.ListCollectionIdsRequest + * @instance + */ + Object.defineProperty(ListCollectionIdsRequest.prototype, "consistencySelector", { + get: $util.oneOfGetter($oneOfFields = ["readTime"]), + set: $util.oneOfSetter($oneOfFields) + }); + + /** + * Creates a ListCollectionIdsRequest message from a plain object. Also converts values to their respective internal types. * @function fromObject - * @memberof google.firestore.v1.AggregationResult + * @memberof google.firestore.v1.ListCollectionIdsRequest * @static * @param {Object.} object Plain object - * @returns {google.firestore.v1.AggregationResult} AggregationResult + * @returns {google.firestore.v1.ListCollectionIdsRequest} ListCollectionIdsRequest */ - AggregationResult.fromObject = function fromObject(object) { - if (object instanceof $root.google.firestore.v1.AggregationResult) + ListCollectionIdsRequest.fromObject = function fromObject(object) { + if (object instanceof $root.google.firestore.v1.ListCollectionIdsRequest) return object; - var message = new $root.google.firestore.v1.AggregationResult(); - if (object.aggregateFields) { - if (typeof object.aggregateFields !== "object") - throw TypeError(".google.firestore.v1.AggregationResult.aggregateFields: object expected"); - message.aggregateFields = {}; - for (var keys = Object.keys(object.aggregateFields), i = 0; i < keys.length; ++i) { - if (typeof object.aggregateFields[keys[i]] !== "object") - throw TypeError(".google.firestore.v1.AggregationResult.aggregateFields: object expected"); - message.aggregateFields[keys[i]] = $root.google.firestore.v1.Value.fromObject(object.aggregateFields[keys[i]]); - } + var message = new $root.google.firestore.v1.ListCollectionIdsRequest(); + if (object.parent != null) + message.parent = String(object.parent); + if (object.pageSize != null) + message.pageSize = object.pageSize | 0; + if (object.pageToken != null) + message.pageToken = String(object.pageToken); + if (object.readTime != null) { + if (typeof object.readTime !== "object") + throw TypeError(".google.firestore.v1.ListCollectionIdsRequest.readTime: object expected"); + message.readTime = $root.google.protobuf.Timestamp.fromObject(object.readTime); } return message; }; /** - * Creates a plain object from an AggregationResult message. Also converts values to other types if specified. + * Creates a plain object from a ListCollectionIdsRequest message. Also converts values to other types if specified. * @function toObject - * @memberof google.firestore.v1.AggregationResult + * @memberof google.firestore.v1.ListCollectionIdsRequest * @static - * @param {google.firestore.v1.AggregationResult} message AggregationResult + * @param {google.firestore.v1.ListCollectionIdsRequest} message ListCollectionIdsRequest * @param {$protobuf.IConversionOptions} [options] Conversion options * @returns {Object.} Plain object */ - AggregationResult.toObject = function toObject(message, options) { + ListCollectionIdsRequest.toObject = function toObject(message, options) { if (!options) options = {}; var object = {}; - if (options.objects || options.defaults) - object.aggregateFields = {}; - var keys2; - if (message.aggregateFields && (keys2 = Object.keys(message.aggregateFields)).length) { - object.aggregateFields = {}; - for (var j = 0; j < keys2.length; ++j) - object.aggregateFields[keys2[j]] = $root.google.firestore.v1.Value.toObject(message.aggregateFields[keys2[j]], options); + if (options.defaults) { + object.parent = ""; + object.pageSize = 0; + object.pageToken = ""; + } + if (message.parent != null && message.hasOwnProperty("parent")) + object.parent = message.parent; + if (message.pageSize != null && message.hasOwnProperty("pageSize")) + object.pageSize = message.pageSize; + if (message.pageToken != null && message.hasOwnProperty("pageToken")) + object.pageToken = message.pageToken; + if (message.readTime != null && message.hasOwnProperty("readTime")) { + object.readTime = $root.google.protobuf.Timestamp.toObject(message.readTime, options); + if (options.oneofs) + object.consistencySelector = "readTime"; } return object; }; /** - * Converts this AggregationResult to JSON. + * Converts this ListCollectionIdsRequest to JSON. * @function toJSON - * @memberof google.firestore.v1.AggregationResult + * @memberof google.firestore.v1.ListCollectionIdsRequest * @instance * @returns {Object.} JSON object */ - AggregationResult.prototype.toJSON = function toJSON() { + ListCollectionIdsRequest.prototype.toJSON = function toJSON() { return this.constructor.toObject(this, $protobuf.util.toJSONOptions); }; /** - * Gets the default type url for AggregationResult + * Gets the default type url for ListCollectionIdsRequest * @function getTypeUrl - * @memberof google.firestore.v1.AggregationResult + * @memberof google.firestore.v1.ListCollectionIdsRequest * @static * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") * @returns {string} The default type url */ - AggregationResult.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + ListCollectionIdsRequest.getTypeUrl = function getTypeUrl(typeUrlPrefix) { if (typeUrlPrefix === undefined) { typeUrlPrefix = "type.googleapis.com"; } - return typeUrlPrefix + "/google.firestore.v1.AggregationResult"; + return typeUrlPrefix + "/google.firestore.v1.ListCollectionIdsRequest"; }; - return AggregationResult; + return ListCollectionIdsRequest; })(); - v1.Document = (function() { + v1.ListCollectionIdsResponse = (function() { /** - * Properties of a Document. + * Properties of a ListCollectionIdsResponse. * @memberof google.firestore.v1 - * @interface IDocument - * @property {string|null} [name] Document name - * @property {Object.|null} [fields] Document fields - * @property {google.protobuf.ITimestamp|null} [createTime] Document createTime - * @property {google.protobuf.ITimestamp|null} [updateTime] Document updateTime + * @interface IListCollectionIdsResponse + * @property {Array.|null} [collectionIds] ListCollectionIdsResponse collectionIds + * @property {string|null} [nextPageToken] ListCollectionIdsResponse nextPageToken */ /** - * Constructs a new Document. + * Constructs a new ListCollectionIdsResponse. * @memberof google.firestore.v1 - * @classdesc Represents a Document. - * @implements IDocument + * @classdesc Represents a ListCollectionIdsResponse. + * @implements IListCollectionIdsResponse * @constructor - * @param {google.firestore.v1.IDocument=} [properties] Properties to set + * @param {google.firestore.v1.IListCollectionIdsResponse=} [properties] Properties to set */ - function Document(properties) { - this.fields = {}; + function ListCollectionIdsResponse(properties) { + this.collectionIds = []; if (properties) for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) if (properties[keys[i]] != null) @@ -10063,169 +8623,123 @@ } /** - * Document name. - * @member {string} name - * @memberof google.firestore.v1.Document - * @instance - */ - Document.prototype.name = ""; - - /** - * Document fields. - * @member {Object.} fields - * @memberof google.firestore.v1.Document - * @instance - */ - Document.prototype.fields = $util.emptyObject; - - /** - * Document createTime. - * @member {google.protobuf.ITimestamp|null|undefined} createTime - * @memberof google.firestore.v1.Document + * ListCollectionIdsResponse collectionIds. + * @member {Array.} collectionIds + * @memberof google.firestore.v1.ListCollectionIdsResponse * @instance */ - Document.prototype.createTime = null; + ListCollectionIdsResponse.prototype.collectionIds = $util.emptyArray; /** - * Document updateTime. - * @member {google.protobuf.ITimestamp|null|undefined} updateTime - * @memberof google.firestore.v1.Document + * ListCollectionIdsResponse nextPageToken. + * @member {string} nextPageToken + * @memberof google.firestore.v1.ListCollectionIdsResponse * @instance */ - Document.prototype.updateTime = null; + ListCollectionIdsResponse.prototype.nextPageToken = ""; /** - * Creates a Document message from a plain object. Also converts values to their respective internal types. + * Creates a ListCollectionIdsResponse message from a plain object. Also converts values to their respective internal types. * @function fromObject - * @memberof google.firestore.v1.Document + * @memberof google.firestore.v1.ListCollectionIdsResponse * @static * @param {Object.} object Plain object - * @returns {google.firestore.v1.Document} Document + * @returns {google.firestore.v1.ListCollectionIdsResponse} ListCollectionIdsResponse */ - Document.fromObject = function fromObject(object) { - if (object instanceof $root.google.firestore.v1.Document) + ListCollectionIdsResponse.fromObject = function fromObject(object) { + if (object instanceof $root.google.firestore.v1.ListCollectionIdsResponse) return object; - var message = new $root.google.firestore.v1.Document(); - if (object.name != null) - message.name = String(object.name); - if (object.fields) { - if (typeof object.fields !== "object") - throw TypeError(".google.firestore.v1.Document.fields: object expected"); - message.fields = {}; - for (var keys = Object.keys(object.fields), i = 0; i < keys.length; ++i) { - if (typeof object.fields[keys[i]] !== "object") - throw TypeError(".google.firestore.v1.Document.fields: object expected"); - message.fields[keys[i]] = $root.google.firestore.v1.Value.fromObject(object.fields[keys[i]]); - } - } - if (object.createTime != null) { - if (typeof object.createTime !== "object") - throw TypeError(".google.firestore.v1.Document.createTime: object expected"); - message.createTime = $root.google.protobuf.Timestamp.fromObject(object.createTime); - } - if (object.updateTime != null) { - if (typeof object.updateTime !== "object") - throw TypeError(".google.firestore.v1.Document.updateTime: object expected"); - message.updateTime = $root.google.protobuf.Timestamp.fromObject(object.updateTime); + var message = new $root.google.firestore.v1.ListCollectionIdsResponse(); + if (object.collectionIds) { + if (!Array.isArray(object.collectionIds)) + throw TypeError(".google.firestore.v1.ListCollectionIdsResponse.collectionIds: array expected"); + message.collectionIds = []; + for (var i = 0; i < object.collectionIds.length; ++i) + message.collectionIds[i] = String(object.collectionIds[i]); } + if (object.nextPageToken != null) + message.nextPageToken = String(object.nextPageToken); return message; }; /** - * Creates a plain object from a Document message. Also converts values to other types if specified. + * Creates a plain object from a ListCollectionIdsResponse message. Also converts values to other types if specified. * @function toObject - * @memberof google.firestore.v1.Document + * @memberof google.firestore.v1.ListCollectionIdsResponse * @static - * @param {google.firestore.v1.Document} message Document + * @param {google.firestore.v1.ListCollectionIdsResponse} message ListCollectionIdsResponse * @param {$protobuf.IConversionOptions} [options] Conversion options * @returns {Object.} Plain object */ - Document.toObject = function toObject(message, options) { + ListCollectionIdsResponse.toObject = function toObject(message, options) { if (!options) options = {}; var object = {}; - if (options.objects || options.defaults) - object.fields = {}; - if (options.defaults) { - object.name = ""; - object.createTime = null; - object.updateTime = null; - } - if (message.name != null && message.hasOwnProperty("name")) - object.name = message.name; - var keys2; - if (message.fields && (keys2 = Object.keys(message.fields)).length) { - object.fields = {}; - for (var j = 0; j < keys2.length; ++j) - object.fields[keys2[j]] = $root.google.firestore.v1.Value.toObject(message.fields[keys2[j]], options); + if (options.arrays || options.defaults) + object.collectionIds = []; + if (options.defaults) + object.nextPageToken = ""; + if (message.collectionIds && message.collectionIds.length) { + object.collectionIds = []; + for (var j = 0; j < message.collectionIds.length; ++j) + object.collectionIds[j] = message.collectionIds[j]; } - if (message.createTime != null && message.hasOwnProperty("createTime")) - object.createTime = $root.google.protobuf.Timestamp.toObject(message.createTime, options); - if (message.updateTime != null && message.hasOwnProperty("updateTime")) - object.updateTime = $root.google.protobuf.Timestamp.toObject(message.updateTime, options); + if (message.nextPageToken != null && message.hasOwnProperty("nextPageToken")) + object.nextPageToken = message.nextPageToken; return object; }; /** - * Converts this Document to JSON. + * Converts this ListCollectionIdsResponse to JSON. * @function toJSON - * @memberof google.firestore.v1.Document + * @memberof google.firestore.v1.ListCollectionIdsResponse * @instance * @returns {Object.} JSON object */ - Document.prototype.toJSON = function toJSON() { + ListCollectionIdsResponse.prototype.toJSON = function toJSON() { return this.constructor.toObject(this, $protobuf.util.toJSONOptions); }; /** - * Gets the default type url for Document + * Gets the default type url for ListCollectionIdsResponse * @function getTypeUrl - * @memberof google.firestore.v1.Document + * @memberof google.firestore.v1.ListCollectionIdsResponse * @static * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") * @returns {string} The default type url */ - Document.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + ListCollectionIdsResponse.getTypeUrl = function getTypeUrl(typeUrlPrefix) { if (typeUrlPrefix === undefined) { typeUrlPrefix = "type.googleapis.com"; } - return typeUrlPrefix + "/google.firestore.v1.Document"; + return typeUrlPrefix + "/google.firestore.v1.ListCollectionIdsResponse"; }; - return Document; + return ListCollectionIdsResponse; })(); - v1.Value = (function() { + v1.BatchWriteRequest = (function() { /** - * Properties of a Value. + * Properties of a BatchWriteRequest. * @memberof google.firestore.v1 - * @interface IValue - * @property {google.protobuf.NullValue|null} [nullValue] Value nullValue - * @property {boolean|null} [booleanValue] Value booleanValue - * @property {number|string|null} [integerValue] Value integerValue - * @property {number|null} [doubleValue] Value doubleValue - * @property {google.protobuf.ITimestamp|null} [timestampValue] Value timestampValue - * @property {string|null} [stringValue] Value stringValue - * @property {Uint8Array|null} [bytesValue] Value bytesValue - * @property {string|null} [referenceValue] Value referenceValue - * @property {google.type.ILatLng|null} [geoPointValue] Value geoPointValue - * @property {google.firestore.v1.IArrayValue|null} [arrayValue] Value arrayValue - * @property {google.firestore.v1.IMapValue|null} [mapValue] Value mapValue - * @property {string|null} [fieldReferenceValue] Value fieldReferenceValue - * @property {google.firestore.v1.IFunction|null} [functionValue] Value functionValue - * @property {google.firestore.v1.IPipeline|null} [pipelineValue] Value pipelineValue + * @interface IBatchWriteRequest + * @property {string|null} [database] BatchWriteRequest database + * @property {Array.|null} [writes] BatchWriteRequest writes + * @property {Object.|null} [labels] BatchWriteRequest labels */ /** - * Constructs a new Value. + * Constructs a new BatchWriteRequest. * @memberof google.firestore.v1 - * @classdesc Represents a Value. - * @implements IValue + * @classdesc Represents a BatchWriteRequest. + * @implements IBatchWriteRequest * @constructor - * @param {google.firestore.v1.IValue=} [properties] Properties to set + * @param {google.firestore.v1.IBatchWriteRequest=} [properties] Properties to set */ - function Value(properties) { + function BatchWriteRequest(properties) { + this.writes = []; + this.labels = {}; if (properties) for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) if (properties[keys[i]] != null) @@ -10233,349 +8747,148 @@ } /** - * Value nullValue. - * @member {google.protobuf.NullValue|null|undefined} nullValue - * @memberof google.firestore.v1.Value - * @instance - */ - Value.prototype.nullValue = null; - - /** - * Value booleanValue. - * @member {boolean|null|undefined} booleanValue - * @memberof google.firestore.v1.Value - * @instance - */ - Value.prototype.booleanValue = null; - - /** - * Value integerValue. - * @member {number|string|null|undefined} integerValue - * @memberof google.firestore.v1.Value - * @instance - */ - Value.prototype.integerValue = null; - - /** - * Value doubleValue. - * @member {number|null|undefined} doubleValue - * @memberof google.firestore.v1.Value - * @instance - */ - Value.prototype.doubleValue = null; - - /** - * Value timestampValue. - * @member {google.protobuf.ITimestamp|null|undefined} timestampValue - * @memberof google.firestore.v1.Value - * @instance - */ - Value.prototype.timestampValue = null; - - /** - * Value stringValue. - * @member {string|null|undefined} stringValue - * @memberof google.firestore.v1.Value - * @instance - */ - Value.prototype.stringValue = null; - - /** - * Value bytesValue. - * @member {Uint8Array|null|undefined} bytesValue - * @memberof google.firestore.v1.Value - * @instance - */ - Value.prototype.bytesValue = null; - - /** - * Value referenceValue. - * @member {string|null|undefined} referenceValue - * @memberof google.firestore.v1.Value - * @instance - */ - Value.prototype.referenceValue = null; - - /** - * Value geoPointValue. - * @member {google.type.ILatLng|null|undefined} geoPointValue - * @memberof google.firestore.v1.Value - * @instance - */ - Value.prototype.geoPointValue = null; - - /** - * Value arrayValue. - * @member {google.firestore.v1.IArrayValue|null|undefined} arrayValue - * @memberof google.firestore.v1.Value - * @instance - */ - Value.prototype.arrayValue = null; - - /** - * Value mapValue. - * @member {google.firestore.v1.IMapValue|null|undefined} mapValue - * @memberof google.firestore.v1.Value - * @instance - */ - Value.prototype.mapValue = null; - - /** - * Value fieldReferenceValue. - * @member {string|null|undefined} fieldReferenceValue - * @memberof google.firestore.v1.Value - * @instance - */ - Value.prototype.fieldReferenceValue = null; - - /** - * Value functionValue. - * @member {google.firestore.v1.IFunction|null|undefined} functionValue - * @memberof google.firestore.v1.Value - * @instance - */ - Value.prototype.functionValue = null; - - /** - * Value pipelineValue. - * @member {google.firestore.v1.IPipeline|null|undefined} pipelineValue - * @memberof google.firestore.v1.Value - * @instance - */ - Value.prototype.pipelineValue = null; - - // OneOf field names bound to virtual getters and setters - var $oneOfFields; - - /** - * Value valueType. - * @member {"nullValue"|"booleanValue"|"integerValue"|"doubleValue"|"timestampValue"|"stringValue"|"bytesValue"|"referenceValue"|"geoPointValue"|"arrayValue"|"mapValue"|"fieldReferenceValue"|"functionValue"|"pipelineValue"|undefined} valueType - * @memberof google.firestore.v1.Value + * BatchWriteRequest database. + * @member {string} database + * @memberof google.firestore.v1.BatchWriteRequest * @instance */ - Object.defineProperty(Value.prototype, "valueType", { - get: $util.oneOfGetter($oneOfFields = ["nullValue", "booleanValue", "integerValue", "doubleValue", "timestampValue", "stringValue", "bytesValue", "referenceValue", "geoPointValue", "arrayValue", "mapValue", "fieldReferenceValue", "functionValue", "pipelineValue"]), - set: $util.oneOfSetter($oneOfFields) - }); + BatchWriteRequest.prototype.database = ""; /** - * Creates a Value message from a plain object. Also converts values to their respective internal types. - * @function fromObject - * @memberof google.firestore.v1.Value - * @static - * @param {Object.} object Plain object - * @returns {google.firestore.v1.Value} Value - */ - Value.fromObject = function fromObject(object) { - if (object instanceof $root.google.firestore.v1.Value) - return object; - var message = new $root.google.firestore.v1.Value(); - switch (object.nullValue) { - default: - if (typeof object.nullValue === "number") { - message.nullValue = object.nullValue; - break; - } - break; - case "NULL_VALUE": - case 0: - message.nullValue = 0; - break; - } - if (object.booleanValue != null) - message.booleanValue = Boolean(object.booleanValue); - if (object.integerValue != null) - if ($util.Long) - (message.integerValue = $util.Long.fromValue(object.integerValue)).unsigned = false; - else if (typeof object.integerValue === "string") - message.integerValue = parseInt(object.integerValue, 10); - else if (typeof object.integerValue === "number") - message.integerValue = object.integerValue; - else if (typeof object.integerValue === "object") - message.integerValue = new $util.LongBits(object.integerValue.low >>> 0, object.integerValue.high >>> 0).toNumber(); - if (object.doubleValue != null) - message.doubleValue = Number(object.doubleValue); - if (object.timestampValue != null) { - if (typeof object.timestampValue !== "object") - throw TypeError(".google.firestore.v1.Value.timestampValue: object expected"); - message.timestampValue = $root.google.protobuf.Timestamp.fromObject(object.timestampValue); - } - if (object.stringValue != null) - message.stringValue = String(object.stringValue); - if (object.bytesValue != null) - if (typeof object.bytesValue === "string") - $util.base64.decode(object.bytesValue, message.bytesValue = $util.newBuffer($util.base64.length(object.bytesValue)), 0); - else if (object.bytesValue.length >= 0) - message.bytesValue = object.bytesValue; - if (object.referenceValue != null) - message.referenceValue = String(object.referenceValue); - if (object.geoPointValue != null) { - if (typeof object.geoPointValue !== "object") - throw TypeError(".google.firestore.v1.Value.geoPointValue: object expected"); - message.geoPointValue = $root.google.type.LatLng.fromObject(object.geoPointValue); - } - if (object.arrayValue != null) { - if (typeof object.arrayValue !== "object") - throw TypeError(".google.firestore.v1.Value.arrayValue: object expected"); - message.arrayValue = $root.google.firestore.v1.ArrayValue.fromObject(object.arrayValue); - } - if (object.mapValue != null) { - if (typeof object.mapValue !== "object") - throw TypeError(".google.firestore.v1.Value.mapValue: object expected"); - message.mapValue = $root.google.firestore.v1.MapValue.fromObject(object.mapValue); - } - if (object.fieldReferenceValue != null) - message.fieldReferenceValue = String(object.fieldReferenceValue); - if (object.functionValue != null) { - if (typeof object.functionValue !== "object") - throw TypeError(".google.firestore.v1.Value.functionValue: object expected"); - message.functionValue = $root.google.firestore.v1.Function.fromObject(object.functionValue); + * BatchWriteRequest writes. + * @member {Array.} writes + * @memberof google.firestore.v1.BatchWriteRequest + * @instance + */ + BatchWriteRequest.prototype.writes = $util.emptyArray; + + /** + * BatchWriteRequest labels. + * @member {Object.} labels + * @memberof google.firestore.v1.BatchWriteRequest + * @instance + */ + BatchWriteRequest.prototype.labels = $util.emptyObject; + + /** + * Creates a BatchWriteRequest message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.firestore.v1.BatchWriteRequest + * @static + * @param {Object.} object Plain object + * @returns {google.firestore.v1.BatchWriteRequest} BatchWriteRequest + */ + BatchWriteRequest.fromObject = function fromObject(object) { + if (object instanceof $root.google.firestore.v1.BatchWriteRequest) + return object; + var message = new $root.google.firestore.v1.BatchWriteRequest(); + if (object.database != null) + message.database = String(object.database); + if (object.writes) { + if (!Array.isArray(object.writes)) + throw TypeError(".google.firestore.v1.BatchWriteRequest.writes: array expected"); + message.writes = []; + for (var i = 0; i < object.writes.length; ++i) { + if (typeof object.writes[i] !== "object") + throw TypeError(".google.firestore.v1.BatchWriteRequest.writes: object expected"); + message.writes[i] = $root.google.firestore.v1.Write.fromObject(object.writes[i]); + } } - if (object.pipelineValue != null) { - if (typeof object.pipelineValue !== "object") - throw TypeError(".google.firestore.v1.Value.pipelineValue: object expected"); - message.pipelineValue = $root.google.firestore.v1.Pipeline.fromObject(object.pipelineValue); + if (object.labels) { + if (typeof object.labels !== "object") + throw TypeError(".google.firestore.v1.BatchWriteRequest.labels: object expected"); + message.labels = {}; + for (var keys = Object.keys(object.labels), i = 0; i < keys.length; ++i) + message.labels[keys[i]] = String(object.labels[keys[i]]); } return message; }; /** - * Creates a plain object from a Value message. Also converts values to other types if specified. + * Creates a plain object from a BatchWriteRequest message. Also converts values to other types if specified. * @function toObject - * @memberof google.firestore.v1.Value + * @memberof google.firestore.v1.BatchWriteRequest * @static - * @param {google.firestore.v1.Value} message Value + * @param {google.firestore.v1.BatchWriteRequest} message BatchWriteRequest * @param {$protobuf.IConversionOptions} [options] Conversion options * @returns {Object.} Plain object */ - Value.toObject = function toObject(message, options) { + BatchWriteRequest.toObject = function toObject(message, options) { if (!options) options = {}; var object = {}; - if (message.booleanValue != null && message.hasOwnProperty("booleanValue")) { - object.booleanValue = message.booleanValue; - if (options.oneofs) - object.valueType = "booleanValue"; - } - if (message.integerValue != null && message.hasOwnProperty("integerValue")) { - if (typeof message.integerValue === "number") - object.integerValue = options.longs === String ? String(message.integerValue) : message.integerValue; - else - object.integerValue = options.longs === String ? $util.Long.prototype.toString.call(message.integerValue) : options.longs === Number ? new $util.LongBits(message.integerValue.low >>> 0, message.integerValue.high >>> 0).toNumber() : message.integerValue; - if (options.oneofs) - object.valueType = "integerValue"; - } - if (message.doubleValue != null && message.hasOwnProperty("doubleValue")) { - object.doubleValue = options.json && !isFinite(message.doubleValue) ? String(message.doubleValue) : message.doubleValue; - if (options.oneofs) - object.valueType = "doubleValue"; - } - if (message.referenceValue != null && message.hasOwnProperty("referenceValue")) { - object.referenceValue = message.referenceValue; - if (options.oneofs) - object.valueType = "referenceValue"; - } - if (message.mapValue != null && message.hasOwnProperty("mapValue")) { - object.mapValue = $root.google.firestore.v1.MapValue.toObject(message.mapValue, options); - if (options.oneofs) - object.valueType = "mapValue"; - } - if (message.geoPointValue != null && message.hasOwnProperty("geoPointValue")) { - object.geoPointValue = $root.google.type.LatLng.toObject(message.geoPointValue, options); - if (options.oneofs) - object.valueType = "geoPointValue"; - } - if (message.arrayValue != null && message.hasOwnProperty("arrayValue")) { - object.arrayValue = $root.google.firestore.v1.ArrayValue.toObject(message.arrayValue, options); - if (options.oneofs) - object.valueType = "arrayValue"; - } - if (message.timestampValue != null && message.hasOwnProperty("timestampValue")) { - object.timestampValue = $root.google.protobuf.Timestamp.toObject(message.timestampValue, options); - if (options.oneofs) - object.valueType = "timestampValue"; - } - if (message.nullValue != null && message.hasOwnProperty("nullValue")) { - object.nullValue = options.enums === String ? $root.google.protobuf.NullValue[message.nullValue] === undefined ? message.nullValue : $root.google.protobuf.NullValue[message.nullValue] : message.nullValue; - if (options.oneofs) - object.valueType = "nullValue"; - } - if (message.stringValue != null && message.hasOwnProperty("stringValue")) { - object.stringValue = message.stringValue; - if (options.oneofs) - object.valueType = "stringValue"; - } - if (message.bytesValue != null && message.hasOwnProperty("bytesValue")) { - object.bytesValue = options.bytes === String ? $util.base64.encode(message.bytesValue, 0, message.bytesValue.length) : options.bytes === Array ? Array.prototype.slice.call(message.bytesValue) : message.bytesValue; - if (options.oneofs) - object.valueType = "bytesValue"; - } - if (message.fieldReferenceValue != null && message.hasOwnProperty("fieldReferenceValue")) { - object.fieldReferenceValue = message.fieldReferenceValue; - if (options.oneofs) - object.valueType = "fieldReferenceValue"; - } - if (message.functionValue != null && message.hasOwnProperty("functionValue")) { - object.functionValue = $root.google.firestore.v1.Function.toObject(message.functionValue, options); - if (options.oneofs) - object.valueType = "functionValue"; + if (options.arrays || options.defaults) + object.writes = []; + if (options.objects || options.defaults) + object.labels = {}; + if (options.defaults) + object.database = ""; + if (message.database != null && message.hasOwnProperty("database")) + object.database = message.database; + if (message.writes && message.writes.length) { + object.writes = []; + for (var j = 0; j < message.writes.length; ++j) + object.writes[j] = $root.google.firestore.v1.Write.toObject(message.writes[j], options); } - if (message.pipelineValue != null && message.hasOwnProperty("pipelineValue")) { - object.pipelineValue = $root.google.firestore.v1.Pipeline.toObject(message.pipelineValue, options); - if (options.oneofs) - object.valueType = "pipelineValue"; + var keys2; + if (message.labels && (keys2 = Object.keys(message.labels)).length) { + object.labels = {}; + for (var j = 0; j < keys2.length; ++j) + object.labels[keys2[j]] = message.labels[keys2[j]]; } return object; }; /** - * Converts this Value to JSON. + * Converts this BatchWriteRequest to JSON. * @function toJSON - * @memberof google.firestore.v1.Value + * @memberof google.firestore.v1.BatchWriteRequest * @instance * @returns {Object.} JSON object */ - Value.prototype.toJSON = function toJSON() { + BatchWriteRequest.prototype.toJSON = function toJSON() { return this.constructor.toObject(this, $protobuf.util.toJSONOptions); }; /** - * Gets the default type url for Value + * Gets the default type url for BatchWriteRequest * @function getTypeUrl - * @memberof google.firestore.v1.Value + * @memberof google.firestore.v1.BatchWriteRequest * @static * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") * @returns {string} The default type url */ - Value.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + BatchWriteRequest.getTypeUrl = function getTypeUrl(typeUrlPrefix) { if (typeUrlPrefix === undefined) { typeUrlPrefix = "type.googleapis.com"; } - return typeUrlPrefix + "/google.firestore.v1.Value"; + return typeUrlPrefix + "/google.firestore.v1.BatchWriteRequest"; }; - return Value; + return BatchWriteRequest; })(); - v1.ArrayValue = (function() { + v1.BatchWriteResponse = (function() { /** - * Properties of an ArrayValue. + * Properties of a BatchWriteResponse. * @memberof google.firestore.v1 - * @interface IArrayValue - * @property {Array.|null} [values] ArrayValue values + * @interface IBatchWriteResponse + * @property {Array.|null} [writeResults] BatchWriteResponse writeResults + * @property {Array.|null} [status] BatchWriteResponse status */ /** - * Constructs a new ArrayValue. + * Constructs a new BatchWriteResponse. * @memberof google.firestore.v1 - * @classdesc Represents an ArrayValue. - * @implements IArrayValue + * @classdesc Represents a BatchWriteResponse. + * @implements IBatchWriteResponse * @constructor - * @param {google.firestore.v1.IArrayValue=} [properties] Properties to set + * @param {google.firestore.v1.IBatchWriteResponse=} [properties] Properties to set */ - function ArrayValue(properties) { - this.values = []; + function BatchWriteResponse(properties) { + this.writeResults = []; + this.status = []; if (properties) for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) if (properties[keys[i]] != null) @@ -10583,109 +8896,135 @@ } /** - * ArrayValue values. - * @member {Array.} values - * @memberof google.firestore.v1.ArrayValue + * BatchWriteResponse writeResults. + * @member {Array.} writeResults + * @memberof google.firestore.v1.BatchWriteResponse * @instance */ - ArrayValue.prototype.values = $util.emptyArray; + BatchWriteResponse.prototype.writeResults = $util.emptyArray; /** - * Creates an ArrayValue message from a plain object. Also converts values to their respective internal types. + * BatchWriteResponse status. + * @member {Array.} status + * @memberof google.firestore.v1.BatchWriteResponse + * @instance + */ + BatchWriteResponse.prototype.status = $util.emptyArray; + + /** + * Creates a BatchWriteResponse message from a plain object. Also converts values to their respective internal types. * @function fromObject - * @memberof google.firestore.v1.ArrayValue + * @memberof google.firestore.v1.BatchWriteResponse * @static * @param {Object.} object Plain object - * @returns {google.firestore.v1.ArrayValue} ArrayValue + * @returns {google.firestore.v1.BatchWriteResponse} BatchWriteResponse */ - ArrayValue.fromObject = function fromObject(object) { - if (object instanceof $root.google.firestore.v1.ArrayValue) + BatchWriteResponse.fromObject = function fromObject(object) { + if (object instanceof $root.google.firestore.v1.BatchWriteResponse) return object; - var message = new $root.google.firestore.v1.ArrayValue(); - if (object.values) { - if (!Array.isArray(object.values)) - throw TypeError(".google.firestore.v1.ArrayValue.values: array expected"); - message.values = []; - for (var i = 0; i < object.values.length; ++i) { - if (typeof object.values[i] !== "object") - throw TypeError(".google.firestore.v1.ArrayValue.values: object expected"); - message.values[i] = $root.google.firestore.v1.Value.fromObject(object.values[i]); + var message = new $root.google.firestore.v1.BatchWriteResponse(); + if (object.writeResults) { + if (!Array.isArray(object.writeResults)) + throw TypeError(".google.firestore.v1.BatchWriteResponse.writeResults: array expected"); + message.writeResults = []; + for (var i = 0; i < object.writeResults.length; ++i) { + if (typeof object.writeResults[i] !== "object") + throw TypeError(".google.firestore.v1.BatchWriteResponse.writeResults: object expected"); + message.writeResults[i] = $root.google.firestore.v1.WriteResult.fromObject(object.writeResults[i]); + } + } + if (object.status) { + if (!Array.isArray(object.status)) + throw TypeError(".google.firestore.v1.BatchWriteResponse.status: array expected"); + message.status = []; + for (var i = 0; i < object.status.length; ++i) { + if (typeof object.status[i] !== "object") + throw TypeError(".google.firestore.v1.BatchWriteResponse.status: object expected"); + message.status[i] = $root.google.rpc.Status.fromObject(object.status[i]); } } return message; }; /** - * Creates a plain object from an ArrayValue message. Also converts values to other types if specified. + * Creates a plain object from a BatchWriteResponse message. Also converts values to other types if specified. * @function toObject - * @memberof google.firestore.v1.ArrayValue + * @memberof google.firestore.v1.BatchWriteResponse * @static - * @param {google.firestore.v1.ArrayValue} message ArrayValue + * @param {google.firestore.v1.BatchWriteResponse} message BatchWriteResponse * @param {$protobuf.IConversionOptions} [options] Conversion options * @returns {Object.} Plain object */ - ArrayValue.toObject = function toObject(message, options) { + BatchWriteResponse.toObject = function toObject(message, options) { if (!options) options = {}; var object = {}; - if (options.arrays || options.defaults) - object.values = []; - if (message.values && message.values.length) { - object.values = []; - for (var j = 0; j < message.values.length; ++j) - object.values[j] = $root.google.firestore.v1.Value.toObject(message.values[j], options); + if (options.arrays || options.defaults) { + object.writeResults = []; + object.status = []; + } + if (message.writeResults && message.writeResults.length) { + object.writeResults = []; + for (var j = 0; j < message.writeResults.length; ++j) + object.writeResults[j] = $root.google.firestore.v1.WriteResult.toObject(message.writeResults[j], options); + } + if (message.status && message.status.length) { + object.status = []; + for (var j = 0; j < message.status.length; ++j) + object.status[j] = $root.google.rpc.Status.toObject(message.status[j], options); } return object; }; /** - * Converts this ArrayValue to JSON. + * Converts this BatchWriteResponse to JSON. * @function toJSON - * @memberof google.firestore.v1.ArrayValue + * @memberof google.firestore.v1.BatchWriteResponse * @instance * @returns {Object.} JSON object */ - ArrayValue.prototype.toJSON = function toJSON() { + BatchWriteResponse.prototype.toJSON = function toJSON() { return this.constructor.toObject(this, $protobuf.util.toJSONOptions); }; /** - * Gets the default type url for ArrayValue + * Gets the default type url for BatchWriteResponse * @function getTypeUrl - * @memberof google.firestore.v1.ArrayValue + * @memberof google.firestore.v1.BatchWriteResponse * @static * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") * @returns {string} The default type url */ - ArrayValue.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + BatchWriteResponse.getTypeUrl = function getTypeUrl(typeUrlPrefix) { if (typeUrlPrefix === undefined) { typeUrlPrefix = "type.googleapis.com"; } - return typeUrlPrefix + "/google.firestore.v1.ArrayValue"; + return typeUrlPrefix + "/google.firestore.v1.BatchWriteResponse"; }; - return ArrayValue; + return BatchWriteResponse; })(); - v1.MapValue = (function() { + v1.StructuredPipeline = (function() { /** - * Properties of a MapValue. + * Properties of a StructuredPipeline. * @memberof google.firestore.v1 - * @interface IMapValue - * @property {Object.|null} [fields] MapValue fields + * @interface IStructuredPipeline + * @property {google.firestore.v1.IPipeline|null} [pipeline] StructuredPipeline pipeline + * @property {Object.|null} [options] StructuredPipeline options */ /** - * Constructs a new MapValue. + * Constructs a new StructuredPipeline. * @memberof google.firestore.v1 - * @classdesc Represents a MapValue. - * @implements IMapValue + * @classdesc Represents a StructuredPipeline. + * @implements IStructuredPipeline * @constructor - * @param {google.firestore.v1.IMapValue=} [properties] Properties to set + * @param {google.firestore.v1.IStructuredPipeline=} [properties] Properties to set */ - function MapValue(properties) { - this.fields = {}; + function StructuredPipeline(properties) { + this.options = {}; if (properties) for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) if (properties[keys[i]] != null) @@ -10693,113 +9032,136 @@ } /** - * MapValue fields. - * @member {Object.} fields - * @memberof google.firestore.v1.MapValue + * StructuredPipeline pipeline. + * @member {google.firestore.v1.IPipeline|null|undefined} pipeline + * @memberof google.firestore.v1.StructuredPipeline * @instance */ - MapValue.prototype.fields = $util.emptyObject; + StructuredPipeline.prototype.pipeline = null; /** - * Creates a MapValue message from a plain object. Also converts values to their respective internal types. + * StructuredPipeline options. + * @member {Object.} options + * @memberof google.firestore.v1.StructuredPipeline + * @instance + */ + StructuredPipeline.prototype.options = $util.emptyObject; + + /** + * Creates a StructuredPipeline message from a plain object. Also converts values to their respective internal types. * @function fromObject - * @memberof google.firestore.v1.MapValue + * @memberof google.firestore.v1.StructuredPipeline * @static * @param {Object.} object Plain object - * @returns {google.firestore.v1.MapValue} MapValue + * @returns {google.firestore.v1.StructuredPipeline} StructuredPipeline */ - MapValue.fromObject = function fromObject(object) { - if (object instanceof $root.google.firestore.v1.MapValue) + StructuredPipeline.fromObject = function fromObject(object) { + if (object instanceof $root.google.firestore.v1.StructuredPipeline) return object; - var message = new $root.google.firestore.v1.MapValue(); - if (object.fields) { - if (typeof object.fields !== "object") - throw TypeError(".google.firestore.v1.MapValue.fields: object expected"); - message.fields = {}; - for (var keys = Object.keys(object.fields), i = 0; i < keys.length; ++i) { - if (typeof object.fields[keys[i]] !== "object") - throw TypeError(".google.firestore.v1.MapValue.fields: object expected"); - message.fields[keys[i]] = $root.google.firestore.v1.Value.fromObject(object.fields[keys[i]]); + var message = new $root.google.firestore.v1.StructuredPipeline(); + if (object.pipeline != null) { + if (typeof object.pipeline !== "object") + throw TypeError(".google.firestore.v1.StructuredPipeline.pipeline: object expected"); + message.pipeline = $root.google.firestore.v1.Pipeline.fromObject(object.pipeline); + } + if (object.options) { + if (typeof object.options !== "object") + throw TypeError(".google.firestore.v1.StructuredPipeline.options: object expected"); + message.options = {}; + for (var keys = Object.keys(object.options), i = 0; i < keys.length; ++i) { + if (typeof object.options[keys[i]] !== "object") + throw TypeError(".google.firestore.v1.StructuredPipeline.options: object expected"); + message.options[keys[i]] = $root.google.firestore.v1.Value.fromObject(object.options[keys[i]]); } } return message; }; /** - * Creates a plain object from a MapValue message. Also converts values to other types if specified. + * Creates a plain object from a StructuredPipeline message. Also converts values to other types if specified. * @function toObject - * @memberof google.firestore.v1.MapValue + * @memberof google.firestore.v1.StructuredPipeline * @static - * @param {google.firestore.v1.MapValue} message MapValue + * @param {google.firestore.v1.StructuredPipeline} message StructuredPipeline * @param {$protobuf.IConversionOptions} [options] Conversion options * @returns {Object.} Plain object */ - MapValue.toObject = function toObject(message, options) { + StructuredPipeline.toObject = function toObject(message, options) { if (!options) options = {}; var object = {}; if (options.objects || options.defaults) - object.fields = {}; + object.options = {}; + if (options.defaults) + object.pipeline = null; + if (message.pipeline != null && message.hasOwnProperty("pipeline")) + object.pipeline = $root.google.firestore.v1.Pipeline.toObject(message.pipeline, options); var keys2; - if (message.fields && (keys2 = Object.keys(message.fields)).length) { - object.fields = {}; + if (message.options && (keys2 = Object.keys(message.options)).length) { + object.options = {}; for (var j = 0; j < keys2.length; ++j) - object.fields[keys2[j]] = $root.google.firestore.v1.Value.toObject(message.fields[keys2[j]], options); + object.options[keys2[j]] = $root.google.firestore.v1.Value.toObject(message.options[keys2[j]], options); } return object; }; /** - * Converts this MapValue to JSON. + * Converts this StructuredPipeline to JSON. * @function toJSON - * @memberof google.firestore.v1.MapValue + * @memberof google.firestore.v1.StructuredPipeline * @instance * @returns {Object.} JSON object */ - MapValue.prototype.toJSON = function toJSON() { + StructuredPipeline.prototype.toJSON = function toJSON() { return this.constructor.toObject(this, $protobuf.util.toJSONOptions); }; /** - * Gets the default type url for MapValue + * Gets the default type url for StructuredPipeline * @function getTypeUrl - * @memberof google.firestore.v1.MapValue + * @memberof google.firestore.v1.StructuredPipeline * @static * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") * @returns {string} The default type url */ - MapValue.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + StructuredPipeline.getTypeUrl = function getTypeUrl(typeUrlPrefix) { if (typeUrlPrefix === undefined) { typeUrlPrefix = "type.googleapis.com"; } - return typeUrlPrefix + "/google.firestore.v1.MapValue"; + return typeUrlPrefix + "/google.firestore.v1.StructuredPipeline"; }; - return MapValue; + return StructuredPipeline; })(); - v1.Function = (function() { + v1.StructuredQuery = (function() { /** - * Properties of a Function. + * Properties of a StructuredQuery. * @memberof google.firestore.v1 - * @interface IFunction - * @property {string|null} [name] Function name - * @property {Array.|null} [args] Function args - * @property {Object.|null} [options] Function options + * @interface IStructuredQuery + * @property {google.firestore.v1.StructuredQuery.IProjection|null} [select] StructuredQuery select + * @property {Array.|null} [from] StructuredQuery from + * @property {google.firestore.v1.StructuredQuery.IFilter|null} [where] StructuredQuery where + * @property {Array.|null} [orderBy] StructuredQuery orderBy + * @property {google.firestore.v1.ICursor|null} [startAt] StructuredQuery startAt + * @property {google.firestore.v1.ICursor|null} [endAt] StructuredQuery endAt + * @property {number|null} [offset] StructuredQuery offset + * @property {google.protobuf.IInt32Value|null} [limit] StructuredQuery limit + * @property {google.firestore.v1.StructuredQuery.IFindNearest|null} [findNearest] StructuredQuery findNearest */ /** - * Constructs a new Function. + * Constructs a new StructuredQuery. * @memberof google.firestore.v1 - * @classdesc Represents a Function. - * @implements IFunction + * @classdesc Represents a StructuredQuery. + * @implements IStructuredQuery * @constructor - * @param {google.firestore.v1.IFunction=} [properties] Properties to set + * @param {google.firestore.v1.IStructuredQuery=} [properties] Properties to set */ - function Function(properties) { - this.args = []; - this.options = {}; + function StructuredQuery(properties) { + this.from = []; + this.orderBy = []; if (properties) for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) if (properties[keys[i]] != null) @@ -10807,1020 +9169,1060 @@ } /** - * Function name. - * @member {string} name - * @memberof google.firestore.v1.Function - * @instance - */ - Function.prototype.name = ""; - - /** - * Function args. - * @member {Array.} args - * @memberof google.firestore.v1.Function - * @instance - */ - Function.prototype.args = $util.emptyArray; - - /** - * Function options. - * @member {Object.} options - * @memberof google.firestore.v1.Function + * StructuredQuery select. + * @member {google.firestore.v1.StructuredQuery.IProjection|null|undefined} select + * @memberof google.firestore.v1.StructuredQuery * @instance */ - Function.prototype.options = $util.emptyObject; - - /** - * Creates a Function message from a plain object. Also converts values to their respective internal types. - * @function fromObject - * @memberof google.firestore.v1.Function - * @static - * @param {Object.} object Plain object - * @returns {google.firestore.v1.Function} Function - */ - Function.fromObject = function fromObject(object) { - if (object instanceof $root.google.firestore.v1.Function) - return object; - var message = new $root.google.firestore.v1.Function(); - if (object.name != null) - message.name = String(object.name); - if (object.args) { - if (!Array.isArray(object.args)) - throw TypeError(".google.firestore.v1.Function.args: array expected"); - message.args = []; - for (var i = 0; i < object.args.length; ++i) { - if (typeof object.args[i] !== "object") - throw TypeError(".google.firestore.v1.Function.args: object expected"); - message.args[i] = $root.google.firestore.v1.Value.fromObject(object.args[i]); - } - } - if (object.options) { - if (typeof object.options !== "object") - throw TypeError(".google.firestore.v1.Function.options: object expected"); - message.options = {}; - for (var keys = Object.keys(object.options), i = 0; i < keys.length; ++i) { - if (typeof object.options[keys[i]] !== "object") - throw TypeError(".google.firestore.v1.Function.options: object expected"); - message.options[keys[i]] = $root.google.firestore.v1.Value.fromObject(object.options[keys[i]]); - } - } - return message; - }; + StructuredQuery.prototype.select = null; /** - * Creates a plain object from a Function message. Also converts values to other types if specified. - * @function toObject - * @memberof google.firestore.v1.Function - * @static - * @param {google.firestore.v1.Function} message Function - * @param {$protobuf.IConversionOptions} [options] Conversion options - * @returns {Object.} Plain object - */ - Function.toObject = function toObject(message, options) { - if (!options) - options = {}; - var object = {}; - if (options.arrays || options.defaults) - object.args = []; - if (options.objects || options.defaults) - object.options = {}; - if (options.defaults) - object.name = ""; - if (message.name != null && message.hasOwnProperty("name")) - object.name = message.name; - if (message.args && message.args.length) { - object.args = []; - for (var j = 0; j < message.args.length; ++j) - object.args[j] = $root.google.firestore.v1.Value.toObject(message.args[j], options); - } - var keys2; - if (message.options && (keys2 = Object.keys(message.options)).length) { - object.options = {}; - for (var j = 0; j < keys2.length; ++j) - object.options[keys2[j]] = $root.google.firestore.v1.Value.toObject(message.options[keys2[j]], options); - } - return object; - }; + * StructuredQuery from. + * @member {Array.} from + * @memberof google.firestore.v1.StructuredQuery + * @instance + */ + StructuredQuery.prototype.from = $util.emptyArray; /** - * Converts this Function to JSON. - * @function toJSON - * @memberof google.firestore.v1.Function + * StructuredQuery where. + * @member {google.firestore.v1.StructuredQuery.IFilter|null|undefined} where + * @memberof google.firestore.v1.StructuredQuery * @instance - * @returns {Object.} JSON object */ - Function.prototype.toJSON = function toJSON() { - return this.constructor.toObject(this, $protobuf.util.toJSONOptions); - }; + StructuredQuery.prototype.where = null; /** - * Gets the default type url for Function - * @function getTypeUrl - * @memberof google.firestore.v1.Function - * @static - * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") - * @returns {string} The default type url + * StructuredQuery orderBy. + * @member {Array.} orderBy + * @memberof google.firestore.v1.StructuredQuery + * @instance */ - Function.getTypeUrl = function getTypeUrl(typeUrlPrefix) { - if (typeUrlPrefix === undefined) { - typeUrlPrefix = "type.googleapis.com"; - } - return typeUrlPrefix + "/google.firestore.v1.Function"; - }; + StructuredQuery.prototype.orderBy = $util.emptyArray; - return Function; - })(); + /** + * StructuredQuery startAt. + * @member {google.firestore.v1.ICursor|null|undefined} startAt + * @memberof google.firestore.v1.StructuredQuery + * @instance + */ + StructuredQuery.prototype.startAt = null; - v1.Pipeline = (function() { + /** + * StructuredQuery endAt. + * @member {google.firestore.v1.ICursor|null|undefined} endAt + * @memberof google.firestore.v1.StructuredQuery + * @instance + */ + StructuredQuery.prototype.endAt = null; /** - * Properties of a Pipeline. - * @memberof google.firestore.v1 - * @interface IPipeline - * @property {Array.|null} [stages] Pipeline stages + * StructuredQuery offset. + * @member {number} offset + * @memberof google.firestore.v1.StructuredQuery + * @instance */ + StructuredQuery.prototype.offset = 0; /** - * Constructs a new Pipeline. - * @memberof google.firestore.v1 - * @classdesc Represents a Pipeline. - * @implements IPipeline - * @constructor - * @param {google.firestore.v1.IPipeline=} [properties] Properties to set + * StructuredQuery limit. + * @member {google.protobuf.IInt32Value|null|undefined} limit + * @memberof google.firestore.v1.StructuredQuery + * @instance */ - function Pipeline(properties) { - this.stages = []; - if (properties) - for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) - if (properties[keys[i]] != null) - this[keys[i]] = properties[keys[i]]; - } + StructuredQuery.prototype.limit = null; /** - * Pipeline stages. - * @member {Array.} stages - * @memberof google.firestore.v1.Pipeline + * StructuredQuery findNearest. + * @member {google.firestore.v1.StructuredQuery.IFindNearest|null|undefined} findNearest + * @memberof google.firestore.v1.StructuredQuery * @instance */ - Pipeline.prototype.stages = $util.emptyArray; + StructuredQuery.prototype.findNearest = null; /** - * Creates a Pipeline message from a plain object. Also converts values to their respective internal types. + * Creates a StructuredQuery message from a plain object. Also converts values to their respective internal types. * @function fromObject - * @memberof google.firestore.v1.Pipeline + * @memberof google.firestore.v1.StructuredQuery * @static * @param {Object.} object Plain object - * @returns {google.firestore.v1.Pipeline} Pipeline + * @returns {google.firestore.v1.StructuredQuery} StructuredQuery */ - Pipeline.fromObject = function fromObject(object) { - if (object instanceof $root.google.firestore.v1.Pipeline) + StructuredQuery.fromObject = function fromObject(object) { + if (object instanceof $root.google.firestore.v1.StructuredQuery) return object; - var message = new $root.google.firestore.v1.Pipeline(); - if (object.stages) { - if (!Array.isArray(object.stages)) - throw TypeError(".google.firestore.v1.Pipeline.stages: array expected"); - message.stages = []; - for (var i = 0; i < object.stages.length; ++i) { - if (typeof object.stages[i] !== "object") - throw TypeError(".google.firestore.v1.Pipeline.stages: object expected"); - message.stages[i] = $root.google.firestore.v1.Pipeline.Stage.fromObject(object.stages[i]); + var message = new $root.google.firestore.v1.StructuredQuery(); + if (object.select != null) { + if (typeof object.select !== "object") + throw TypeError(".google.firestore.v1.StructuredQuery.select: object expected"); + message.select = $root.google.firestore.v1.StructuredQuery.Projection.fromObject(object.select); + } + if (object.from) { + if (!Array.isArray(object.from)) + throw TypeError(".google.firestore.v1.StructuredQuery.from: array expected"); + message.from = []; + for (var i = 0; i < object.from.length; ++i) { + if (typeof object.from[i] !== "object") + throw TypeError(".google.firestore.v1.StructuredQuery.from: object expected"); + message.from[i] = $root.google.firestore.v1.StructuredQuery.CollectionSelector.fromObject(object.from[i]); + } + } + if (object.where != null) { + if (typeof object.where !== "object") + throw TypeError(".google.firestore.v1.StructuredQuery.where: object expected"); + message.where = $root.google.firestore.v1.StructuredQuery.Filter.fromObject(object.where); + } + if (object.orderBy) { + if (!Array.isArray(object.orderBy)) + throw TypeError(".google.firestore.v1.StructuredQuery.orderBy: array expected"); + message.orderBy = []; + for (var i = 0; i < object.orderBy.length; ++i) { + if (typeof object.orderBy[i] !== "object") + throw TypeError(".google.firestore.v1.StructuredQuery.orderBy: object expected"); + message.orderBy[i] = $root.google.firestore.v1.StructuredQuery.Order.fromObject(object.orderBy[i]); } } + if (object.startAt != null) { + if (typeof object.startAt !== "object") + throw TypeError(".google.firestore.v1.StructuredQuery.startAt: object expected"); + message.startAt = $root.google.firestore.v1.Cursor.fromObject(object.startAt); + } + if (object.endAt != null) { + if (typeof object.endAt !== "object") + throw TypeError(".google.firestore.v1.StructuredQuery.endAt: object expected"); + message.endAt = $root.google.firestore.v1.Cursor.fromObject(object.endAt); + } + if (object.offset != null) + message.offset = object.offset | 0; + if (object.limit != null) { + if (typeof object.limit !== "object") + throw TypeError(".google.firestore.v1.StructuredQuery.limit: object expected"); + message.limit = $root.google.protobuf.Int32Value.fromObject(object.limit); + } + if (object.findNearest != null) { + if (typeof object.findNearest !== "object") + throw TypeError(".google.firestore.v1.StructuredQuery.findNearest: object expected"); + message.findNearest = $root.google.firestore.v1.StructuredQuery.FindNearest.fromObject(object.findNearest); + } return message; }; /** - * Creates a plain object from a Pipeline message. Also converts values to other types if specified. + * Creates a plain object from a StructuredQuery message. Also converts values to other types if specified. * @function toObject - * @memberof google.firestore.v1.Pipeline + * @memberof google.firestore.v1.StructuredQuery * @static - * @param {google.firestore.v1.Pipeline} message Pipeline + * @param {google.firestore.v1.StructuredQuery} message StructuredQuery * @param {$protobuf.IConversionOptions} [options] Conversion options * @returns {Object.} Plain object */ - Pipeline.toObject = function toObject(message, options) { + StructuredQuery.toObject = function toObject(message, options) { if (!options) options = {}; var object = {}; - if (options.arrays || options.defaults) - object.stages = []; - if (message.stages && message.stages.length) { - object.stages = []; - for (var j = 0; j < message.stages.length; ++j) - object.stages[j] = $root.google.firestore.v1.Pipeline.Stage.toObject(message.stages[j], options); + if (options.arrays || options.defaults) { + object.from = []; + object.orderBy = []; + } + if (options.defaults) { + object.select = null; + object.where = null; + object.limit = null; + object.offset = 0; + object.startAt = null; + object.endAt = null; + object.findNearest = null; + } + if (message.select != null && message.hasOwnProperty("select")) + object.select = $root.google.firestore.v1.StructuredQuery.Projection.toObject(message.select, options); + if (message.from && message.from.length) { + object.from = []; + for (var j = 0; j < message.from.length; ++j) + object.from[j] = $root.google.firestore.v1.StructuredQuery.CollectionSelector.toObject(message.from[j], options); + } + if (message.where != null && message.hasOwnProperty("where")) + object.where = $root.google.firestore.v1.StructuredQuery.Filter.toObject(message.where, options); + if (message.orderBy && message.orderBy.length) { + object.orderBy = []; + for (var j = 0; j < message.orderBy.length; ++j) + object.orderBy[j] = $root.google.firestore.v1.StructuredQuery.Order.toObject(message.orderBy[j], options); } + if (message.limit != null && message.hasOwnProperty("limit")) + object.limit = $root.google.protobuf.Int32Value.toObject(message.limit, options); + if (message.offset != null && message.hasOwnProperty("offset")) + object.offset = message.offset; + if (message.startAt != null && message.hasOwnProperty("startAt")) + object.startAt = $root.google.firestore.v1.Cursor.toObject(message.startAt, options); + if (message.endAt != null && message.hasOwnProperty("endAt")) + object.endAt = $root.google.firestore.v1.Cursor.toObject(message.endAt, options); + if (message.findNearest != null && message.hasOwnProperty("findNearest")) + object.findNearest = $root.google.firestore.v1.StructuredQuery.FindNearest.toObject(message.findNearest, options); return object; }; /** - * Converts this Pipeline to JSON. + * Converts this StructuredQuery to JSON. * @function toJSON - * @memberof google.firestore.v1.Pipeline + * @memberof google.firestore.v1.StructuredQuery * @instance * @returns {Object.} JSON object */ - Pipeline.prototype.toJSON = function toJSON() { + StructuredQuery.prototype.toJSON = function toJSON() { return this.constructor.toObject(this, $protobuf.util.toJSONOptions); }; /** - * Gets the default type url for Pipeline + * Gets the default type url for StructuredQuery * @function getTypeUrl - * @memberof google.firestore.v1.Pipeline + * @memberof google.firestore.v1.StructuredQuery * @static * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") * @returns {string} The default type url */ - Pipeline.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + StructuredQuery.getTypeUrl = function getTypeUrl(typeUrlPrefix) { if (typeUrlPrefix === undefined) { typeUrlPrefix = "type.googleapis.com"; } - return typeUrlPrefix + "/google.firestore.v1.Pipeline"; + return typeUrlPrefix + "/google.firestore.v1.StructuredQuery"; }; - Pipeline.Stage = (function() { + StructuredQuery.CollectionSelector = (function() { /** - * Properties of a Stage. - * @memberof google.firestore.v1.Pipeline - * @interface IStage - * @property {string|null} [name] Stage name - * @property {Array.|null} [args] Stage args - * @property {Object.|null} [options] Stage options + * Properties of a CollectionSelector. + * @memberof google.firestore.v1.StructuredQuery + * @interface ICollectionSelector + * @property {string|null} [collectionId] CollectionSelector collectionId + * @property {boolean|null} [allDescendants] CollectionSelector allDescendants */ /** - * Constructs a new Stage. - * @memberof google.firestore.v1.Pipeline - * @classdesc Represents a Stage. - * @implements IStage + * Constructs a new CollectionSelector. + * @memberof google.firestore.v1.StructuredQuery + * @classdesc Represents a CollectionSelector. + * @implements ICollectionSelector * @constructor - * @param {google.firestore.v1.Pipeline.IStage=} [properties] Properties to set + * @param {google.firestore.v1.StructuredQuery.ICollectionSelector=} [properties] Properties to set */ - function Stage(properties) { - this.args = []; - this.options = {}; + function CollectionSelector(properties) { if (properties) - for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) - if (properties[keys[i]] != null) - this[keys[i]] = properties[keys[i]]; - } - - /** - * Stage name. - * @member {string} name - * @memberof google.firestore.v1.Pipeline.Stage - * @instance - */ - Stage.prototype.name = ""; + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } /** - * Stage args. - * @member {Array.} args - * @memberof google.firestore.v1.Pipeline.Stage + * CollectionSelector collectionId. + * @member {string} collectionId + * @memberof google.firestore.v1.StructuredQuery.CollectionSelector * @instance */ - Stage.prototype.args = $util.emptyArray; + CollectionSelector.prototype.collectionId = ""; /** - * Stage options. - * @member {Object.} options - * @memberof google.firestore.v1.Pipeline.Stage + * CollectionSelector allDescendants. + * @member {boolean} allDescendants + * @memberof google.firestore.v1.StructuredQuery.CollectionSelector * @instance */ - Stage.prototype.options = $util.emptyObject; + CollectionSelector.prototype.allDescendants = false; /** - * Creates a Stage message from a plain object. Also converts values to their respective internal types. + * Creates a CollectionSelector message from a plain object. Also converts values to their respective internal types. * @function fromObject - * @memberof google.firestore.v1.Pipeline.Stage + * @memberof google.firestore.v1.StructuredQuery.CollectionSelector * @static * @param {Object.} object Plain object - * @returns {google.firestore.v1.Pipeline.Stage} Stage + * @returns {google.firestore.v1.StructuredQuery.CollectionSelector} CollectionSelector */ - Stage.fromObject = function fromObject(object) { - if (object instanceof $root.google.firestore.v1.Pipeline.Stage) + CollectionSelector.fromObject = function fromObject(object) { + if (object instanceof $root.google.firestore.v1.StructuredQuery.CollectionSelector) return object; - var message = new $root.google.firestore.v1.Pipeline.Stage(); - if (object.name != null) - message.name = String(object.name); - if (object.args) { - if (!Array.isArray(object.args)) - throw TypeError(".google.firestore.v1.Pipeline.Stage.args: array expected"); - message.args = []; - for (var i = 0; i < object.args.length; ++i) { - if (typeof object.args[i] !== "object") - throw TypeError(".google.firestore.v1.Pipeline.Stage.args: object expected"); - message.args[i] = $root.google.firestore.v1.Value.fromObject(object.args[i]); - } - } - if (object.options) { - if (typeof object.options !== "object") - throw TypeError(".google.firestore.v1.Pipeline.Stage.options: object expected"); - message.options = {}; - for (var keys = Object.keys(object.options), i = 0; i < keys.length; ++i) { - if (typeof object.options[keys[i]] !== "object") - throw TypeError(".google.firestore.v1.Pipeline.Stage.options: object expected"); - message.options[keys[i]] = $root.google.firestore.v1.Value.fromObject(object.options[keys[i]]); - } - } + var message = new $root.google.firestore.v1.StructuredQuery.CollectionSelector(); + if (object.collectionId != null) + message.collectionId = String(object.collectionId); + if (object.allDescendants != null) + message.allDescendants = Boolean(object.allDescendants); return message; }; /** - * Creates a plain object from a Stage message. Also converts values to other types if specified. + * Creates a plain object from a CollectionSelector message. Also converts values to other types if specified. * @function toObject - * @memberof google.firestore.v1.Pipeline.Stage + * @memberof google.firestore.v1.StructuredQuery.CollectionSelector * @static - * @param {google.firestore.v1.Pipeline.Stage} message Stage + * @param {google.firestore.v1.StructuredQuery.CollectionSelector} message CollectionSelector * @param {$protobuf.IConversionOptions} [options] Conversion options * @returns {Object.} Plain object */ - Stage.toObject = function toObject(message, options) { + CollectionSelector.toObject = function toObject(message, options) { if (!options) options = {}; var object = {}; - if (options.arrays || options.defaults) - object.args = []; - if (options.objects || options.defaults) - object.options = {}; - if (options.defaults) - object.name = ""; - if (message.name != null && message.hasOwnProperty("name")) - object.name = message.name; - if (message.args && message.args.length) { - object.args = []; - for (var j = 0; j < message.args.length; ++j) - object.args[j] = $root.google.firestore.v1.Value.toObject(message.args[j], options); - } - var keys2; - if (message.options && (keys2 = Object.keys(message.options)).length) { - object.options = {}; - for (var j = 0; j < keys2.length; ++j) - object.options[keys2[j]] = $root.google.firestore.v1.Value.toObject(message.options[keys2[j]], options); + if (options.defaults) { + object.collectionId = ""; + object.allDescendants = false; } + if (message.collectionId != null && message.hasOwnProperty("collectionId")) + object.collectionId = message.collectionId; + if (message.allDescendants != null && message.hasOwnProperty("allDescendants")) + object.allDescendants = message.allDescendants; return object; }; /** - * Converts this Stage to JSON. + * Converts this CollectionSelector to JSON. * @function toJSON - * @memberof google.firestore.v1.Pipeline.Stage + * @memberof google.firestore.v1.StructuredQuery.CollectionSelector * @instance * @returns {Object.} JSON object */ - Stage.prototype.toJSON = function toJSON() { + CollectionSelector.prototype.toJSON = function toJSON() { return this.constructor.toObject(this, $protobuf.util.toJSONOptions); }; /** - * Gets the default type url for Stage + * Gets the default type url for CollectionSelector * @function getTypeUrl - * @memberof google.firestore.v1.Pipeline.Stage + * @memberof google.firestore.v1.StructuredQuery.CollectionSelector * @static * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") * @returns {string} The default type url */ - Stage.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + CollectionSelector.getTypeUrl = function getTypeUrl(typeUrlPrefix) { if (typeUrlPrefix === undefined) { typeUrlPrefix = "type.googleapis.com"; } - return typeUrlPrefix + "/google.firestore.v1.Pipeline.Stage"; + return typeUrlPrefix + "/google.firestore.v1.StructuredQuery.CollectionSelector"; }; - return Stage; + return CollectionSelector; })(); - return Pipeline; - })(); - - v1.BitSequence = (function() { - - /** - * Properties of a BitSequence. - * @memberof google.firestore.v1 - * @interface IBitSequence - * @property {Uint8Array|null} [bitmap] BitSequence bitmap - * @property {number|null} [padding] BitSequence padding - */ - - /** - * Constructs a new BitSequence. - * @memberof google.firestore.v1 - * @classdesc Represents a BitSequence. - * @implements IBitSequence - * @constructor - * @param {google.firestore.v1.IBitSequence=} [properties] Properties to set - */ - function BitSequence(properties) { - if (properties) - for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) - if (properties[keys[i]] != null) - this[keys[i]] = properties[keys[i]]; - } - - /** - * BitSequence bitmap. - * @member {Uint8Array} bitmap - * @memberof google.firestore.v1.BitSequence - * @instance - */ - BitSequence.prototype.bitmap = $util.newBuffer([]); - - /** - * BitSequence padding. - * @member {number} padding - * @memberof google.firestore.v1.BitSequence - * @instance - */ - BitSequence.prototype.padding = 0; - - /** - * Creates a BitSequence message from a plain object. Also converts values to their respective internal types. - * @function fromObject - * @memberof google.firestore.v1.BitSequence - * @static - * @param {Object.} object Plain object - * @returns {google.firestore.v1.BitSequence} BitSequence - */ - BitSequence.fromObject = function fromObject(object) { - if (object instanceof $root.google.firestore.v1.BitSequence) - return object; - var message = new $root.google.firestore.v1.BitSequence(); - if (object.bitmap != null) - if (typeof object.bitmap === "string") - $util.base64.decode(object.bitmap, message.bitmap = $util.newBuffer($util.base64.length(object.bitmap)), 0); - else if (object.bitmap.length >= 0) - message.bitmap = object.bitmap; - if (object.padding != null) - message.padding = object.padding | 0; - return message; - }; - - /** - * Creates a plain object from a BitSequence message. Also converts values to other types if specified. - * @function toObject - * @memberof google.firestore.v1.BitSequence - * @static - * @param {google.firestore.v1.BitSequence} message BitSequence - * @param {$protobuf.IConversionOptions} [options] Conversion options - * @returns {Object.} Plain object - */ - BitSequence.toObject = function toObject(message, options) { - if (!options) - options = {}; - var object = {}; - if (options.defaults) { - if (options.bytes === String) - object.bitmap = ""; - else { - object.bitmap = []; - if (options.bytes !== Array) - object.bitmap = $util.newBuffer(object.bitmap); - } - object.padding = 0; - } - if (message.bitmap != null && message.hasOwnProperty("bitmap")) - object.bitmap = options.bytes === String ? $util.base64.encode(message.bitmap, 0, message.bitmap.length) : options.bytes === Array ? Array.prototype.slice.call(message.bitmap) : message.bitmap; - if (message.padding != null && message.hasOwnProperty("padding")) - object.padding = message.padding; - return object; - }; + StructuredQuery.Filter = (function() { - /** - * Converts this BitSequence to JSON. - * @function toJSON - * @memberof google.firestore.v1.BitSequence - * @instance - * @returns {Object.} JSON object - */ - BitSequence.prototype.toJSON = function toJSON() { - return this.constructor.toObject(this, $protobuf.util.toJSONOptions); - }; + /** + * Properties of a Filter. + * @memberof google.firestore.v1.StructuredQuery + * @interface IFilter + * @property {google.firestore.v1.StructuredQuery.ICompositeFilter|null} [compositeFilter] Filter compositeFilter + * @property {google.firestore.v1.StructuredQuery.IFieldFilter|null} [fieldFilter] Filter fieldFilter + * @property {google.firestore.v1.StructuredQuery.IUnaryFilter|null} [unaryFilter] Filter unaryFilter + */ - /** - * Gets the default type url for BitSequence - * @function getTypeUrl - * @memberof google.firestore.v1.BitSequence - * @static - * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") - * @returns {string} The default type url - */ - BitSequence.getTypeUrl = function getTypeUrl(typeUrlPrefix) { - if (typeUrlPrefix === undefined) { - typeUrlPrefix = "type.googleapis.com"; + /** + * Constructs a new Filter. + * @memberof google.firestore.v1.StructuredQuery + * @classdesc Represents a Filter. + * @implements IFilter + * @constructor + * @param {google.firestore.v1.StructuredQuery.IFilter=} [properties] Properties to set + */ + function Filter(properties) { + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; } - return typeUrlPrefix + "/google.firestore.v1.BitSequence"; - }; - return BitSequence; - })(); + /** + * Filter compositeFilter. + * @member {google.firestore.v1.StructuredQuery.ICompositeFilter|null|undefined} compositeFilter + * @memberof google.firestore.v1.StructuredQuery.Filter + * @instance + */ + Filter.prototype.compositeFilter = null; - v1.BloomFilter = (function() { + /** + * Filter fieldFilter. + * @member {google.firestore.v1.StructuredQuery.IFieldFilter|null|undefined} fieldFilter + * @memberof google.firestore.v1.StructuredQuery.Filter + * @instance + */ + Filter.prototype.fieldFilter = null; - /** - * Properties of a BloomFilter. - * @memberof google.firestore.v1 - * @interface IBloomFilter - * @property {google.firestore.v1.IBitSequence|null} [bits] BloomFilter bits - * @property {number|null} [hashCount] BloomFilter hashCount - */ + /** + * Filter unaryFilter. + * @member {google.firestore.v1.StructuredQuery.IUnaryFilter|null|undefined} unaryFilter + * @memberof google.firestore.v1.StructuredQuery.Filter + * @instance + */ + Filter.prototype.unaryFilter = null; - /** - * Constructs a new BloomFilter. - * @memberof google.firestore.v1 - * @classdesc Represents a BloomFilter. - * @implements IBloomFilter - * @constructor - * @param {google.firestore.v1.IBloomFilter=} [properties] Properties to set - */ - function BloomFilter(properties) { - if (properties) - for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) - if (properties[keys[i]] != null) - this[keys[i]] = properties[keys[i]]; - } + // OneOf field names bound to virtual getters and setters + var $oneOfFields; - /** - * BloomFilter bits. - * @member {google.firestore.v1.IBitSequence|null|undefined} bits - * @memberof google.firestore.v1.BloomFilter - * @instance - */ - BloomFilter.prototype.bits = null; + /** + * Filter filterType. + * @member {"compositeFilter"|"fieldFilter"|"unaryFilter"|undefined} filterType + * @memberof google.firestore.v1.StructuredQuery.Filter + * @instance + */ + Object.defineProperty(Filter.prototype, "filterType", { + get: $util.oneOfGetter($oneOfFields = ["compositeFilter", "fieldFilter", "unaryFilter"]), + set: $util.oneOfSetter($oneOfFields) + }); - /** - * BloomFilter hashCount. - * @member {number} hashCount - * @memberof google.firestore.v1.BloomFilter - * @instance - */ - BloomFilter.prototype.hashCount = 0; + /** + * Creates a Filter message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.firestore.v1.StructuredQuery.Filter + * @static + * @param {Object.} object Plain object + * @returns {google.firestore.v1.StructuredQuery.Filter} Filter + */ + Filter.fromObject = function fromObject(object) { + if (object instanceof $root.google.firestore.v1.StructuredQuery.Filter) + return object; + var message = new $root.google.firestore.v1.StructuredQuery.Filter(); + if (object.compositeFilter != null) { + if (typeof object.compositeFilter !== "object") + throw TypeError(".google.firestore.v1.StructuredQuery.Filter.compositeFilter: object expected"); + message.compositeFilter = $root.google.firestore.v1.StructuredQuery.CompositeFilter.fromObject(object.compositeFilter); + } + if (object.fieldFilter != null) { + if (typeof object.fieldFilter !== "object") + throw TypeError(".google.firestore.v1.StructuredQuery.Filter.fieldFilter: object expected"); + message.fieldFilter = $root.google.firestore.v1.StructuredQuery.FieldFilter.fromObject(object.fieldFilter); + } + if (object.unaryFilter != null) { + if (typeof object.unaryFilter !== "object") + throw TypeError(".google.firestore.v1.StructuredQuery.Filter.unaryFilter: object expected"); + message.unaryFilter = $root.google.firestore.v1.StructuredQuery.UnaryFilter.fromObject(object.unaryFilter); + } + return message; + }; - /** - * Creates a BloomFilter message from a plain object. Also converts values to their respective internal types. - * @function fromObject - * @memberof google.firestore.v1.BloomFilter - * @static - * @param {Object.} object Plain object - * @returns {google.firestore.v1.BloomFilter} BloomFilter - */ - BloomFilter.fromObject = function fromObject(object) { - if (object instanceof $root.google.firestore.v1.BloomFilter) + /** + * Creates a plain object from a Filter message. Also converts values to other types if specified. + * @function toObject + * @memberof google.firestore.v1.StructuredQuery.Filter + * @static + * @param {google.firestore.v1.StructuredQuery.Filter} message Filter + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + Filter.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (message.compositeFilter != null && message.hasOwnProperty("compositeFilter")) { + object.compositeFilter = $root.google.firestore.v1.StructuredQuery.CompositeFilter.toObject(message.compositeFilter, options); + if (options.oneofs) + object.filterType = "compositeFilter"; + } + if (message.fieldFilter != null && message.hasOwnProperty("fieldFilter")) { + object.fieldFilter = $root.google.firestore.v1.StructuredQuery.FieldFilter.toObject(message.fieldFilter, options); + if (options.oneofs) + object.filterType = "fieldFilter"; + } + if (message.unaryFilter != null && message.hasOwnProperty("unaryFilter")) { + object.unaryFilter = $root.google.firestore.v1.StructuredQuery.UnaryFilter.toObject(message.unaryFilter, options); + if (options.oneofs) + object.filterType = "unaryFilter"; + } return object; - var message = new $root.google.firestore.v1.BloomFilter(); - if (object.bits != null) { - if (typeof object.bits !== "object") - throw TypeError(".google.firestore.v1.BloomFilter.bits: object expected"); - message.bits = $root.google.firestore.v1.BitSequence.fromObject(object.bits); - } - if (object.hashCount != null) - message.hashCount = object.hashCount | 0; - return message; - }; - - /** - * Creates a plain object from a BloomFilter message. Also converts values to other types if specified. - * @function toObject - * @memberof google.firestore.v1.BloomFilter - * @static - * @param {google.firestore.v1.BloomFilter} message BloomFilter - * @param {$protobuf.IConversionOptions} [options] Conversion options - * @returns {Object.} Plain object - */ - BloomFilter.toObject = function toObject(message, options) { - if (!options) - options = {}; - var object = {}; - if (options.defaults) { - object.bits = null; - object.hashCount = 0; - } - if (message.bits != null && message.hasOwnProperty("bits")) - object.bits = $root.google.firestore.v1.BitSequence.toObject(message.bits, options); - if (message.hashCount != null && message.hasOwnProperty("hashCount")) - object.hashCount = message.hashCount; - return object; - }; + }; - /** - * Converts this BloomFilter to JSON. - * @function toJSON - * @memberof google.firestore.v1.BloomFilter - * @instance - * @returns {Object.} JSON object - */ - BloomFilter.prototype.toJSON = function toJSON() { - return this.constructor.toObject(this, $protobuf.util.toJSONOptions); - }; + /** + * Converts this Filter to JSON. + * @function toJSON + * @memberof google.firestore.v1.StructuredQuery.Filter + * @instance + * @returns {Object.} JSON object + */ + Filter.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; - /** - * Gets the default type url for BloomFilter - * @function getTypeUrl - * @memberof google.firestore.v1.BloomFilter - * @static - * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") - * @returns {string} The default type url - */ - BloomFilter.getTypeUrl = function getTypeUrl(typeUrlPrefix) { - if (typeUrlPrefix === undefined) { - typeUrlPrefix = "type.googleapis.com"; - } - return typeUrlPrefix + "/google.firestore.v1.BloomFilter"; - }; + /** + * Gets the default type url for Filter + * @function getTypeUrl + * @memberof google.firestore.v1.StructuredQuery.Filter + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + Filter.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.firestore.v1.StructuredQuery.Filter"; + }; - return BloomFilter; - })(); + return Filter; + })(); - v1.DocumentMask = (function() { + StructuredQuery.CompositeFilter = (function() { - /** - * Properties of a DocumentMask. - * @memberof google.firestore.v1 - * @interface IDocumentMask - * @property {Array.|null} [fieldPaths] DocumentMask fieldPaths - */ + /** + * Properties of a CompositeFilter. + * @memberof google.firestore.v1.StructuredQuery + * @interface ICompositeFilter + * @property {google.firestore.v1.StructuredQuery.CompositeFilter.Operator|null} [op] CompositeFilter op + * @property {Array.|null} [filters] CompositeFilter filters + */ - /** - * Constructs a new DocumentMask. - * @memberof google.firestore.v1 - * @classdesc Represents a DocumentMask. - * @implements IDocumentMask - * @constructor - * @param {google.firestore.v1.IDocumentMask=} [properties] Properties to set - */ - function DocumentMask(properties) { - this.fieldPaths = []; - if (properties) - for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) - if (properties[keys[i]] != null) - this[keys[i]] = properties[keys[i]]; - } + /** + * Constructs a new CompositeFilter. + * @memberof google.firestore.v1.StructuredQuery + * @classdesc Represents a CompositeFilter. + * @implements ICompositeFilter + * @constructor + * @param {google.firestore.v1.StructuredQuery.ICompositeFilter=} [properties] Properties to set + */ + function CompositeFilter(properties) { + this.filters = []; + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } - /** - * DocumentMask fieldPaths. - * @member {Array.} fieldPaths - * @memberof google.firestore.v1.DocumentMask - * @instance - */ - DocumentMask.prototype.fieldPaths = $util.emptyArray; + /** + * CompositeFilter op. + * @member {google.firestore.v1.StructuredQuery.CompositeFilter.Operator} op + * @memberof google.firestore.v1.StructuredQuery.CompositeFilter + * @instance + */ + CompositeFilter.prototype.op = 0; - /** - * Creates a DocumentMask message from a plain object. Also converts values to their respective internal types. - * @function fromObject - * @memberof google.firestore.v1.DocumentMask - * @static - * @param {Object.} object Plain object - * @returns {google.firestore.v1.DocumentMask} DocumentMask - */ - DocumentMask.fromObject = function fromObject(object) { - if (object instanceof $root.google.firestore.v1.DocumentMask) - return object; - var message = new $root.google.firestore.v1.DocumentMask(); - if (object.fieldPaths) { - if (!Array.isArray(object.fieldPaths)) - throw TypeError(".google.firestore.v1.DocumentMask.fieldPaths: array expected"); - message.fieldPaths = []; - for (var i = 0; i < object.fieldPaths.length; ++i) - message.fieldPaths[i] = String(object.fieldPaths[i]); - } - return message; - }; + /** + * CompositeFilter filters. + * @member {Array.} filters + * @memberof google.firestore.v1.StructuredQuery.CompositeFilter + * @instance + */ + CompositeFilter.prototype.filters = $util.emptyArray; - /** - * Creates a plain object from a DocumentMask message. Also converts values to other types if specified. - * @function toObject - * @memberof google.firestore.v1.DocumentMask - * @static - * @param {google.firestore.v1.DocumentMask} message DocumentMask - * @param {$protobuf.IConversionOptions} [options] Conversion options - * @returns {Object.} Plain object - */ - DocumentMask.toObject = function toObject(message, options) { - if (!options) - options = {}; - var object = {}; - if (options.arrays || options.defaults) - object.fieldPaths = []; - if (message.fieldPaths && message.fieldPaths.length) { - object.fieldPaths = []; - for (var j = 0; j < message.fieldPaths.length; ++j) - object.fieldPaths[j] = message.fieldPaths[j]; - } - return object; - }; + /** + * Creates a CompositeFilter message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.firestore.v1.StructuredQuery.CompositeFilter + * @static + * @param {Object.} object Plain object + * @returns {google.firestore.v1.StructuredQuery.CompositeFilter} CompositeFilter + */ + CompositeFilter.fromObject = function fromObject(object) { + if (object instanceof $root.google.firestore.v1.StructuredQuery.CompositeFilter) + return object; + var message = new $root.google.firestore.v1.StructuredQuery.CompositeFilter(); + switch (object.op) { + default: + if (typeof object.op === "number") { + message.op = object.op; + break; + } + break; + case "OPERATOR_UNSPECIFIED": + case 0: + message.op = 0; + break; + case "AND": + case 1: + message.op = 1; + break; + case "OR": + case 2: + message.op = 2; + break; + } + if (object.filters) { + if (!Array.isArray(object.filters)) + throw TypeError(".google.firestore.v1.StructuredQuery.CompositeFilter.filters: array expected"); + message.filters = []; + for (var i = 0; i < object.filters.length; ++i) { + if (typeof object.filters[i] !== "object") + throw TypeError(".google.firestore.v1.StructuredQuery.CompositeFilter.filters: object expected"); + message.filters[i] = $root.google.firestore.v1.StructuredQuery.Filter.fromObject(object.filters[i]); + } + } + return message; + }; - /** - * Converts this DocumentMask to JSON. - * @function toJSON - * @memberof google.firestore.v1.DocumentMask - * @instance - * @returns {Object.} JSON object - */ - DocumentMask.prototype.toJSON = function toJSON() { - return this.constructor.toObject(this, $protobuf.util.toJSONOptions); - }; + /** + * Creates a plain object from a CompositeFilter message. Also converts values to other types if specified. + * @function toObject + * @memberof google.firestore.v1.StructuredQuery.CompositeFilter + * @static + * @param {google.firestore.v1.StructuredQuery.CompositeFilter} message CompositeFilter + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + CompositeFilter.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.arrays || options.defaults) + object.filters = []; + if (options.defaults) + object.op = options.enums === String ? "OPERATOR_UNSPECIFIED" : 0; + if (message.op != null && message.hasOwnProperty("op")) + object.op = options.enums === String ? $root.google.firestore.v1.StructuredQuery.CompositeFilter.Operator[message.op] === undefined ? message.op : $root.google.firestore.v1.StructuredQuery.CompositeFilter.Operator[message.op] : message.op; + if (message.filters && message.filters.length) { + object.filters = []; + for (var j = 0; j < message.filters.length; ++j) + object.filters[j] = $root.google.firestore.v1.StructuredQuery.Filter.toObject(message.filters[j], options); + } + return object; + }; - /** - * Gets the default type url for DocumentMask - * @function getTypeUrl - * @memberof google.firestore.v1.DocumentMask - * @static - * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") - * @returns {string} The default type url - */ - DocumentMask.getTypeUrl = function getTypeUrl(typeUrlPrefix) { - if (typeUrlPrefix === undefined) { - typeUrlPrefix = "type.googleapis.com"; - } - return typeUrlPrefix + "/google.firestore.v1.DocumentMask"; - }; + /** + * Converts this CompositeFilter to JSON. + * @function toJSON + * @memberof google.firestore.v1.StructuredQuery.CompositeFilter + * @instance + * @returns {Object.} JSON object + */ + CompositeFilter.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; - return DocumentMask; - })(); + /** + * Gets the default type url for CompositeFilter + * @function getTypeUrl + * @memberof google.firestore.v1.StructuredQuery.CompositeFilter + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + CompositeFilter.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.firestore.v1.StructuredQuery.CompositeFilter"; + }; - v1.Precondition = (function() { + /** + * Operator enum. + * @name google.firestore.v1.StructuredQuery.CompositeFilter.Operator + * @enum {string} + * @property {string} OPERATOR_UNSPECIFIED=OPERATOR_UNSPECIFIED OPERATOR_UNSPECIFIED value + * @property {string} AND=AND AND value + * @property {string} OR=OR OR value + */ + CompositeFilter.Operator = (function() { + var valuesById = {}, values = Object.create(valuesById); + values[valuesById[0] = "OPERATOR_UNSPECIFIED"] = "OPERATOR_UNSPECIFIED"; + values[valuesById[1] = "AND"] = "AND"; + values[valuesById[2] = "OR"] = "OR"; + return values; + })(); - /** - * Properties of a Precondition. - * @memberof google.firestore.v1 - * @interface IPrecondition - * @property {boolean|null} [exists] Precondition exists - * @property {google.protobuf.ITimestamp|null} [updateTime] Precondition updateTime - */ + return CompositeFilter; + })(); - /** - * Constructs a new Precondition. - * @memberof google.firestore.v1 - * @classdesc Represents a Precondition. - * @implements IPrecondition - * @constructor - * @param {google.firestore.v1.IPrecondition=} [properties] Properties to set - */ - function Precondition(properties) { - if (properties) - for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) - if (properties[keys[i]] != null) - this[keys[i]] = properties[keys[i]]; - } + StructuredQuery.FieldFilter = (function() { - /** - * Precondition exists. - * @member {boolean|null|undefined} exists - * @memberof google.firestore.v1.Precondition - * @instance - */ - Precondition.prototype.exists = null; + /** + * Properties of a FieldFilter. + * @memberof google.firestore.v1.StructuredQuery + * @interface IFieldFilter + * @property {google.firestore.v1.StructuredQuery.IFieldReference|null} [field] FieldFilter field + * @property {google.firestore.v1.StructuredQuery.FieldFilter.Operator|null} [op] FieldFilter op + * @property {google.firestore.v1.IValue|null} [value] FieldFilter value + */ + + /** + * Constructs a new FieldFilter. + * @memberof google.firestore.v1.StructuredQuery + * @classdesc Represents a FieldFilter. + * @implements IFieldFilter + * @constructor + * @param {google.firestore.v1.StructuredQuery.IFieldFilter=} [properties] Properties to set + */ + function FieldFilter(properties) { + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } - /** - * Precondition updateTime. - * @member {google.protobuf.ITimestamp|null|undefined} updateTime - * @memberof google.firestore.v1.Precondition - * @instance - */ - Precondition.prototype.updateTime = null; + /** + * FieldFilter field. + * @member {google.firestore.v1.StructuredQuery.IFieldReference|null|undefined} field + * @memberof google.firestore.v1.StructuredQuery.FieldFilter + * @instance + */ + FieldFilter.prototype.field = null; - // OneOf field names bound to virtual getters and setters - var $oneOfFields; + /** + * FieldFilter op. + * @member {google.firestore.v1.StructuredQuery.FieldFilter.Operator} op + * @memberof google.firestore.v1.StructuredQuery.FieldFilter + * @instance + */ + FieldFilter.prototype.op = 0; - /** - * Precondition conditionType. - * @member {"exists"|"updateTime"|undefined} conditionType - * @memberof google.firestore.v1.Precondition - * @instance - */ - Object.defineProperty(Precondition.prototype, "conditionType", { - get: $util.oneOfGetter($oneOfFields = ["exists", "updateTime"]), - set: $util.oneOfSetter($oneOfFields) - }); + /** + * FieldFilter value. + * @member {google.firestore.v1.IValue|null|undefined} value + * @memberof google.firestore.v1.StructuredQuery.FieldFilter + * @instance + */ + FieldFilter.prototype.value = null; - /** - * Creates a Precondition message from a plain object. Also converts values to their respective internal types. - * @function fromObject - * @memberof google.firestore.v1.Precondition - * @static - * @param {Object.} object Plain object - * @returns {google.firestore.v1.Precondition} Precondition - */ - Precondition.fromObject = function fromObject(object) { - if (object instanceof $root.google.firestore.v1.Precondition) + /** + * Creates a FieldFilter message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.firestore.v1.StructuredQuery.FieldFilter + * @static + * @param {Object.} object Plain object + * @returns {google.firestore.v1.StructuredQuery.FieldFilter} FieldFilter + */ + FieldFilter.fromObject = function fromObject(object) { + if (object instanceof $root.google.firestore.v1.StructuredQuery.FieldFilter) + return object; + var message = new $root.google.firestore.v1.StructuredQuery.FieldFilter(); + if (object.field != null) { + if (typeof object.field !== "object") + throw TypeError(".google.firestore.v1.StructuredQuery.FieldFilter.field: object expected"); + message.field = $root.google.firestore.v1.StructuredQuery.FieldReference.fromObject(object.field); + } + switch (object.op) { + default: + if (typeof object.op === "number") { + message.op = object.op; + break; + } + break; + case "OPERATOR_UNSPECIFIED": + case 0: + message.op = 0; + break; + case "LESS_THAN": + case 1: + message.op = 1; + break; + case "LESS_THAN_OR_EQUAL": + case 2: + message.op = 2; + break; + case "GREATER_THAN": + case 3: + message.op = 3; + break; + case "GREATER_THAN_OR_EQUAL": + case 4: + message.op = 4; + break; + case "EQUAL": + case 5: + message.op = 5; + break; + case "NOT_EQUAL": + case 6: + message.op = 6; + break; + case "ARRAY_CONTAINS": + case 7: + message.op = 7; + break; + case "IN": + case 8: + message.op = 8; + break; + case "ARRAY_CONTAINS_ANY": + case 9: + message.op = 9; + break; + case "NOT_IN": + case 10: + message.op = 10; + break; + } + if (object.value != null) { + if (typeof object.value !== "object") + throw TypeError(".google.firestore.v1.StructuredQuery.FieldFilter.value: object expected"); + message.value = $root.google.firestore.v1.Value.fromObject(object.value); + } + return message; + }; + + /** + * Creates a plain object from a FieldFilter message. Also converts values to other types if specified. + * @function toObject + * @memberof google.firestore.v1.StructuredQuery.FieldFilter + * @static + * @param {google.firestore.v1.StructuredQuery.FieldFilter} message FieldFilter + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + FieldFilter.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.defaults) { + object.field = null; + object.op = options.enums === String ? "OPERATOR_UNSPECIFIED" : 0; + object.value = null; + } + if (message.field != null && message.hasOwnProperty("field")) + object.field = $root.google.firestore.v1.StructuredQuery.FieldReference.toObject(message.field, options); + if (message.op != null && message.hasOwnProperty("op")) + object.op = options.enums === String ? $root.google.firestore.v1.StructuredQuery.FieldFilter.Operator[message.op] === undefined ? message.op : $root.google.firestore.v1.StructuredQuery.FieldFilter.Operator[message.op] : message.op; + if (message.value != null && message.hasOwnProperty("value")) + object.value = $root.google.firestore.v1.Value.toObject(message.value, options); return object; - var message = new $root.google.firestore.v1.Precondition(); - if (object.exists != null) - message.exists = Boolean(object.exists); - if (object.updateTime != null) { - if (typeof object.updateTime !== "object") - throw TypeError(".google.firestore.v1.Precondition.updateTime: object expected"); - message.updateTime = $root.google.protobuf.Timestamp.fromObject(object.updateTime); - } - return message; - }; + }; - /** - * Creates a plain object from a Precondition message. Also converts values to other types if specified. - * @function toObject - * @memberof google.firestore.v1.Precondition - * @static - * @param {google.firestore.v1.Precondition} message Precondition - * @param {$protobuf.IConversionOptions} [options] Conversion options - * @returns {Object.} Plain object - */ - Precondition.toObject = function toObject(message, options) { - if (!options) - options = {}; - var object = {}; - if (message.exists != null && message.hasOwnProperty("exists")) { - object.exists = message.exists; - if (options.oneofs) - object.conditionType = "exists"; - } - if (message.updateTime != null && message.hasOwnProperty("updateTime")) { - object.updateTime = $root.google.protobuf.Timestamp.toObject(message.updateTime, options); - if (options.oneofs) - object.conditionType = "updateTime"; - } - return object; - }; + /** + * Converts this FieldFilter to JSON. + * @function toJSON + * @memberof google.firestore.v1.StructuredQuery.FieldFilter + * @instance + * @returns {Object.} JSON object + */ + FieldFilter.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; - /** - * Converts this Precondition to JSON. - * @function toJSON - * @memberof google.firestore.v1.Precondition - * @instance - * @returns {Object.} JSON object - */ - Precondition.prototype.toJSON = function toJSON() { - return this.constructor.toObject(this, $protobuf.util.toJSONOptions); - }; + /** + * Gets the default type url for FieldFilter + * @function getTypeUrl + * @memberof google.firestore.v1.StructuredQuery.FieldFilter + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + FieldFilter.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.firestore.v1.StructuredQuery.FieldFilter"; + }; + + /** + * Operator enum. + * @name google.firestore.v1.StructuredQuery.FieldFilter.Operator + * @enum {string} + * @property {string} OPERATOR_UNSPECIFIED=OPERATOR_UNSPECIFIED OPERATOR_UNSPECIFIED value + * @property {string} LESS_THAN=LESS_THAN LESS_THAN value + * @property {string} LESS_THAN_OR_EQUAL=LESS_THAN_OR_EQUAL LESS_THAN_OR_EQUAL value + * @property {string} GREATER_THAN=GREATER_THAN GREATER_THAN value + * @property {string} GREATER_THAN_OR_EQUAL=GREATER_THAN_OR_EQUAL GREATER_THAN_OR_EQUAL value + * @property {string} EQUAL=EQUAL EQUAL value + * @property {string} NOT_EQUAL=NOT_EQUAL NOT_EQUAL value + * @property {string} ARRAY_CONTAINS=ARRAY_CONTAINS ARRAY_CONTAINS value + * @property {string} IN=IN IN value + * @property {string} ARRAY_CONTAINS_ANY=ARRAY_CONTAINS_ANY ARRAY_CONTAINS_ANY value + * @property {string} NOT_IN=NOT_IN NOT_IN value + */ + FieldFilter.Operator = (function() { + var valuesById = {}, values = Object.create(valuesById); + values[valuesById[0] = "OPERATOR_UNSPECIFIED"] = "OPERATOR_UNSPECIFIED"; + values[valuesById[1] = "LESS_THAN"] = "LESS_THAN"; + values[valuesById[2] = "LESS_THAN_OR_EQUAL"] = "LESS_THAN_OR_EQUAL"; + values[valuesById[3] = "GREATER_THAN"] = "GREATER_THAN"; + values[valuesById[4] = "GREATER_THAN_OR_EQUAL"] = "GREATER_THAN_OR_EQUAL"; + values[valuesById[5] = "EQUAL"] = "EQUAL"; + values[valuesById[6] = "NOT_EQUAL"] = "NOT_EQUAL"; + values[valuesById[7] = "ARRAY_CONTAINS"] = "ARRAY_CONTAINS"; + values[valuesById[8] = "IN"] = "IN"; + values[valuesById[9] = "ARRAY_CONTAINS_ANY"] = "ARRAY_CONTAINS_ANY"; + values[valuesById[10] = "NOT_IN"] = "NOT_IN"; + return values; + })(); - /** - * Gets the default type url for Precondition - * @function getTypeUrl - * @memberof google.firestore.v1.Precondition - * @static - * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") - * @returns {string} The default type url - */ - Precondition.getTypeUrl = function getTypeUrl(typeUrlPrefix) { - if (typeUrlPrefix === undefined) { - typeUrlPrefix = "type.googleapis.com"; - } - return typeUrlPrefix + "/google.firestore.v1.Precondition"; - }; + return FieldFilter; + })(); - return Precondition; - })(); + StructuredQuery.UnaryFilter = (function() { - v1.TransactionOptions = (function() { + /** + * Properties of an UnaryFilter. + * @memberof google.firestore.v1.StructuredQuery + * @interface IUnaryFilter + * @property {google.firestore.v1.StructuredQuery.UnaryFilter.Operator|null} [op] UnaryFilter op + * @property {google.firestore.v1.StructuredQuery.IFieldReference|null} [field] UnaryFilter field + */ - /** - * Properties of a TransactionOptions. - * @memberof google.firestore.v1 - * @interface ITransactionOptions - * @property {google.firestore.v1.TransactionOptions.IReadOnly|null} [readOnly] TransactionOptions readOnly - * @property {google.firestore.v1.TransactionOptions.IReadWrite|null} [readWrite] TransactionOptions readWrite - */ + /** + * Constructs a new UnaryFilter. + * @memberof google.firestore.v1.StructuredQuery + * @classdesc Represents an UnaryFilter. + * @implements IUnaryFilter + * @constructor + * @param {google.firestore.v1.StructuredQuery.IUnaryFilter=} [properties] Properties to set + */ + function UnaryFilter(properties) { + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } - /** - * Constructs a new TransactionOptions. - * @memberof google.firestore.v1 - * @classdesc Represents a TransactionOptions. - * @implements ITransactionOptions - * @constructor - * @param {google.firestore.v1.ITransactionOptions=} [properties] Properties to set - */ - function TransactionOptions(properties) { - if (properties) - for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) - if (properties[keys[i]] != null) - this[keys[i]] = properties[keys[i]]; - } + /** + * UnaryFilter op. + * @member {google.firestore.v1.StructuredQuery.UnaryFilter.Operator} op + * @memberof google.firestore.v1.StructuredQuery.UnaryFilter + * @instance + */ + UnaryFilter.prototype.op = 0; - /** - * TransactionOptions readOnly. - * @member {google.firestore.v1.TransactionOptions.IReadOnly|null|undefined} readOnly - * @memberof google.firestore.v1.TransactionOptions - * @instance - */ - TransactionOptions.prototype.readOnly = null; + /** + * UnaryFilter field. + * @member {google.firestore.v1.StructuredQuery.IFieldReference|null|undefined} field + * @memberof google.firestore.v1.StructuredQuery.UnaryFilter + * @instance + */ + UnaryFilter.prototype.field = null; - /** - * TransactionOptions readWrite. - * @member {google.firestore.v1.TransactionOptions.IReadWrite|null|undefined} readWrite - * @memberof google.firestore.v1.TransactionOptions - * @instance - */ - TransactionOptions.prototype.readWrite = null; + // OneOf field names bound to virtual getters and setters + var $oneOfFields; - // OneOf field names bound to virtual getters and setters - var $oneOfFields; + /** + * UnaryFilter operandType. + * @member {"field"|undefined} operandType + * @memberof google.firestore.v1.StructuredQuery.UnaryFilter + * @instance + */ + Object.defineProperty(UnaryFilter.prototype, "operandType", { + get: $util.oneOfGetter($oneOfFields = ["field"]), + set: $util.oneOfSetter($oneOfFields) + }); - /** - * TransactionOptions mode. - * @member {"readOnly"|"readWrite"|undefined} mode - * @memberof google.firestore.v1.TransactionOptions - * @instance - */ - Object.defineProperty(TransactionOptions.prototype, "mode", { - get: $util.oneOfGetter($oneOfFields = ["readOnly", "readWrite"]), - set: $util.oneOfSetter($oneOfFields) - }); + /** + * Creates an UnaryFilter message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.firestore.v1.StructuredQuery.UnaryFilter + * @static + * @param {Object.} object Plain object + * @returns {google.firestore.v1.StructuredQuery.UnaryFilter} UnaryFilter + */ + UnaryFilter.fromObject = function fromObject(object) { + if (object instanceof $root.google.firestore.v1.StructuredQuery.UnaryFilter) + return object; + var message = new $root.google.firestore.v1.StructuredQuery.UnaryFilter(); + switch (object.op) { + default: + if (typeof object.op === "number") { + message.op = object.op; + break; + } + break; + case "OPERATOR_UNSPECIFIED": + case 0: + message.op = 0; + break; + case "IS_NAN": + case 2: + message.op = 2; + break; + case "IS_NULL": + case 3: + message.op = 3; + break; + case "IS_NOT_NAN": + case 4: + message.op = 4; + break; + case "IS_NOT_NULL": + case 5: + message.op = 5; + break; + } + if (object.field != null) { + if (typeof object.field !== "object") + throw TypeError(".google.firestore.v1.StructuredQuery.UnaryFilter.field: object expected"); + message.field = $root.google.firestore.v1.StructuredQuery.FieldReference.fromObject(object.field); + } + return message; + }; - /** - * Creates a TransactionOptions message from a plain object. Also converts values to their respective internal types. - * @function fromObject - * @memberof google.firestore.v1.TransactionOptions - * @static - * @param {Object.} object Plain object - * @returns {google.firestore.v1.TransactionOptions} TransactionOptions - */ - TransactionOptions.fromObject = function fromObject(object) { - if (object instanceof $root.google.firestore.v1.TransactionOptions) + /** + * Creates a plain object from an UnaryFilter message. Also converts values to other types if specified. + * @function toObject + * @memberof google.firestore.v1.StructuredQuery.UnaryFilter + * @static + * @param {google.firestore.v1.StructuredQuery.UnaryFilter} message UnaryFilter + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + UnaryFilter.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.defaults) + object.op = options.enums === String ? "OPERATOR_UNSPECIFIED" : 0; + if (message.op != null && message.hasOwnProperty("op")) + object.op = options.enums === String ? $root.google.firestore.v1.StructuredQuery.UnaryFilter.Operator[message.op] === undefined ? message.op : $root.google.firestore.v1.StructuredQuery.UnaryFilter.Operator[message.op] : message.op; + if (message.field != null && message.hasOwnProperty("field")) { + object.field = $root.google.firestore.v1.StructuredQuery.FieldReference.toObject(message.field, options); + if (options.oneofs) + object.operandType = "field"; + } return object; - var message = new $root.google.firestore.v1.TransactionOptions(); - if (object.readOnly != null) { - if (typeof object.readOnly !== "object") - throw TypeError(".google.firestore.v1.TransactionOptions.readOnly: object expected"); - message.readOnly = $root.google.firestore.v1.TransactionOptions.ReadOnly.fromObject(object.readOnly); - } - if (object.readWrite != null) { - if (typeof object.readWrite !== "object") - throw TypeError(".google.firestore.v1.TransactionOptions.readWrite: object expected"); - message.readWrite = $root.google.firestore.v1.TransactionOptions.ReadWrite.fromObject(object.readWrite); - } - return message; - }; + }; - /** - * Creates a plain object from a TransactionOptions message. Also converts values to other types if specified. - * @function toObject - * @memberof google.firestore.v1.TransactionOptions - * @static - * @param {google.firestore.v1.TransactionOptions} message TransactionOptions - * @param {$protobuf.IConversionOptions} [options] Conversion options - * @returns {Object.} Plain object - */ - TransactionOptions.toObject = function toObject(message, options) { - if (!options) - options = {}; - var object = {}; - if (message.readOnly != null && message.hasOwnProperty("readOnly")) { - object.readOnly = $root.google.firestore.v1.TransactionOptions.ReadOnly.toObject(message.readOnly, options); - if (options.oneofs) - object.mode = "readOnly"; - } - if (message.readWrite != null && message.hasOwnProperty("readWrite")) { - object.readWrite = $root.google.firestore.v1.TransactionOptions.ReadWrite.toObject(message.readWrite, options); - if (options.oneofs) - object.mode = "readWrite"; - } - return object; - }; + /** + * Converts this UnaryFilter to JSON. + * @function toJSON + * @memberof google.firestore.v1.StructuredQuery.UnaryFilter + * @instance + * @returns {Object.} JSON object + */ + UnaryFilter.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + + /** + * Gets the default type url for UnaryFilter + * @function getTypeUrl + * @memberof google.firestore.v1.StructuredQuery.UnaryFilter + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + UnaryFilter.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.firestore.v1.StructuredQuery.UnaryFilter"; + }; - /** - * Converts this TransactionOptions to JSON. - * @function toJSON - * @memberof google.firestore.v1.TransactionOptions - * @instance - * @returns {Object.} JSON object - */ - TransactionOptions.prototype.toJSON = function toJSON() { - return this.constructor.toObject(this, $protobuf.util.toJSONOptions); - }; + /** + * Operator enum. + * @name google.firestore.v1.StructuredQuery.UnaryFilter.Operator + * @enum {string} + * @property {string} OPERATOR_UNSPECIFIED=OPERATOR_UNSPECIFIED OPERATOR_UNSPECIFIED value + * @property {string} IS_NAN=IS_NAN IS_NAN value + * @property {string} IS_NULL=IS_NULL IS_NULL value + * @property {string} IS_NOT_NAN=IS_NOT_NAN IS_NOT_NAN value + * @property {string} IS_NOT_NULL=IS_NOT_NULL IS_NOT_NULL value + */ + UnaryFilter.Operator = (function() { + var valuesById = {}, values = Object.create(valuesById); + values[valuesById[0] = "OPERATOR_UNSPECIFIED"] = "OPERATOR_UNSPECIFIED"; + values[valuesById[2] = "IS_NAN"] = "IS_NAN"; + values[valuesById[3] = "IS_NULL"] = "IS_NULL"; + values[valuesById[4] = "IS_NOT_NAN"] = "IS_NOT_NAN"; + values[valuesById[5] = "IS_NOT_NULL"] = "IS_NOT_NULL"; + return values; + })(); - /** - * Gets the default type url for TransactionOptions - * @function getTypeUrl - * @memberof google.firestore.v1.TransactionOptions - * @static - * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") - * @returns {string} The default type url - */ - TransactionOptions.getTypeUrl = function getTypeUrl(typeUrlPrefix) { - if (typeUrlPrefix === undefined) { - typeUrlPrefix = "type.googleapis.com"; - } - return typeUrlPrefix + "/google.firestore.v1.TransactionOptions"; - }; + return UnaryFilter; + })(); - TransactionOptions.ReadWrite = (function() { + StructuredQuery.Order = (function() { /** - * Properties of a ReadWrite. - * @memberof google.firestore.v1.TransactionOptions - * @interface IReadWrite - * @property {Uint8Array|null} [retryTransaction] ReadWrite retryTransaction + * Properties of an Order. + * @memberof google.firestore.v1.StructuredQuery + * @interface IOrder + * @property {google.firestore.v1.StructuredQuery.IFieldReference|null} [field] Order field + * @property {google.firestore.v1.StructuredQuery.Direction|null} [direction] Order direction */ /** - * Constructs a new ReadWrite. - * @memberof google.firestore.v1.TransactionOptions - * @classdesc Represents a ReadWrite. - * @implements IReadWrite + * Constructs a new Order. + * @memberof google.firestore.v1.StructuredQuery + * @classdesc Represents an Order. + * @implements IOrder * @constructor - * @param {google.firestore.v1.TransactionOptions.IReadWrite=} [properties] Properties to set + * @param {google.firestore.v1.StructuredQuery.IOrder=} [properties] Properties to set */ - function ReadWrite(properties) { + function Order(properties) { if (properties) for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) if (properties[keys[i]] != null) @@ -11828,106 +10230,247 @@ } /** - * ReadWrite retryTransaction. - * @member {Uint8Array} retryTransaction - * @memberof google.firestore.v1.TransactionOptions.ReadWrite + * Order field. + * @member {google.firestore.v1.StructuredQuery.IFieldReference|null|undefined} field + * @memberof google.firestore.v1.StructuredQuery.Order * @instance */ - ReadWrite.prototype.retryTransaction = $util.newBuffer([]); + Order.prototype.field = null; /** - * Creates a ReadWrite message from a plain object. Also converts values to their respective internal types. + * Order direction. + * @member {google.firestore.v1.StructuredQuery.Direction} direction + * @memberof google.firestore.v1.StructuredQuery.Order + * @instance + */ + Order.prototype.direction = 0; + + /** + * Creates an Order message from a plain object. Also converts values to their respective internal types. * @function fromObject - * @memberof google.firestore.v1.TransactionOptions.ReadWrite + * @memberof google.firestore.v1.StructuredQuery.Order * @static * @param {Object.} object Plain object - * @returns {google.firestore.v1.TransactionOptions.ReadWrite} ReadWrite + * @returns {google.firestore.v1.StructuredQuery.Order} Order */ - ReadWrite.fromObject = function fromObject(object) { - if (object instanceof $root.google.firestore.v1.TransactionOptions.ReadWrite) + Order.fromObject = function fromObject(object) { + if (object instanceof $root.google.firestore.v1.StructuredQuery.Order) return object; - var message = new $root.google.firestore.v1.TransactionOptions.ReadWrite(); - if (object.retryTransaction != null) - if (typeof object.retryTransaction === "string") - $util.base64.decode(object.retryTransaction, message.retryTransaction = $util.newBuffer($util.base64.length(object.retryTransaction)), 0); - else if (object.retryTransaction.length >= 0) - message.retryTransaction = object.retryTransaction; + var message = new $root.google.firestore.v1.StructuredQuery.Order(); + if (object.field != null) { + if (typeof object.field !== "object") + throw TypeError(".google.firestore.v1.StructuredQuery.Order.field: object expected"); + message.field = $root.google.firestore.v1.StructuredQuery.FieldReference.fromObject(object.field); + } + switch (object.direction) { + default: + if (typeof object.direction === "number") { + message.direction = object.direction; + break; + } + break; + case "DIRECTION_UNSPECIFIED": + case 0: + message.direction = 0; + break; + case "ASCENDING": + case 1: + message.direction = 1; + break; + case "DESCENDING": + case 2: + message.direction = 2; + break; + } return message; }; /** - * Creates a plain object from a ReadWrite message. Also converts values to other types if specified. + * Creates a plain object from an Order message. Also converts values to other types if specified. * @function toObject - * @memberof google.firestore.v1.TransactionOptions.ReadWrite + * @memberof google.firestore.v1.StructuredQuery.Order * @static - * @param {google.firestore.v1.TransactionOptions.ReadWrite} message ReadWrite + * @param {google.firestore.v1.StructuredQuery.Order} message Order * @param {$protobuf.IConversionOptions} [options] Conversion options * @returns {Object.} Plain object */ - ReadWrite.toObject = function toObject(message, options) { + Order.toObject = function toObject(message, options) { if (!options) options = {}; var object = {}; - if (options.defaults) - if (options.bytes === String) - object.retryTransaction = ""; - else { - object.retryTransaction = []; - if (options.bytes !== Array) - object.retryTransaction = $util.newBuffer(object.retryTransaction); - } - if (message.retryTransaction != null && message.hasOwnProperty("retryTransaction")) - object.retryTransaction = options.bytes === String ? $util.base64.encode(message.retryTransaction, 0, message.retryTransaction.length) : options.bytes === Array ? Array.prototype.slice.call(message.retryTransaction) : message.retryTransaction; + if (options.defaults) { + object.field = null; + object.direction = options.enums === String ? "DIRECTION_UNSPECIFIED" : 0; + } + if (message.field != null && message.hasOwnProperty("field")) + object.field = $root.google.firestore.v1.StructuredQuery.FieldReference.toObject(message.field, options); + if (message.direction != null && message.hasOwnProperty("direction")) + object.direction = options.enums === String ? $root.google.firestore.v1.StructuredQuery.Direction[message.direction] === undefined ? message.direction : $root.google.firestore.v1.StructuredQuery.Direction[message.direction] : message.direction; + return object; + }; + + /** + * Converts this Order to JSON. + * @function toJSON + * @memberof google.firestore.v1.StructuredQuery.Order + * @instance + * @returns {Object.} JSON object + */ + Order.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + + /** + * Gets the default type url for Order + * @function getTypeUrl + * @memberof google.firestore.v1.StructuredQuery.Order + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + Order.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.firestore.v1.StructuredQuery.Order"; + }; + + return Order; + })(); + + /** + * Direction enum. + * @name google.firestore.v1.StructuredQuery.Direction + * @enum {string} + * @property {string} DIRECTION_UNSPECIFIED=DIRECTION_UNSPECIFIED DIRECTION_UNSPECIFIED value + * @property {string} ASCENDING=ASCENDING ASCENDING value + * @property {string} DESCENDING=DESCENDING DESCENDING value + */ + StructuredQuery.Direction = (function() { + var valuesById = {}, values = Object.create(valuesById); + values[valuesById[0] = "DIRECTION_UNSPECIFIED"] = "DIRECTION_UNSPECIFIED"; + values[valuesById[1] = "ASCENDING"] = "ASCENDING"; + values[valuesById[2] = "DESCENDING"] = "DESCENDING"; + return values; + })(); + + StructuredQuery.FieldReference = (function() { + + /** + * Properties of a FieldReference. + * @memberof google.firestore.v1.StructuredQuery + * @interface IFieldReference + * @property {string|null} [fieldPath] FieldReference fieldPath + */ + + /** + * Constructs a new FieldReference. + * @memberof google.firestore.v1.StructuredQuery + * @classdesc Represents a FieldReference. + * @implements IFieldReference + * @constructor + * @param {google.firestore.v1.StructuredQuery.IFieldReference=} [properties] Properties to set + */ + function FieldReference(properties) { + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } + + /** + * FieldReference fieldPath. + * @member {string} fieldPath + * @memberof google.firestore.v1.StructuredQuery.FieldReference + * @instance + */ + FieldReference.prototype.fieldPath = ""; + + /** + * Creates a FieldReference message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.firestore.v1.StructuredQuery.FieldReference + * @static + * @param {Object.} object Plain object + * @returns {google.firestore.v1.StructuredQuery.FieldReference} FieldReference + */ + FieldReference.fromObject = function fromObject(object) { + if (object instanceof $root.google.firestore.v1.StructuredQuery.FieldReference) + return object; + var message = new $root.google.firestore.v1.StructuredQuery.FieldReference(); + if (object.fieldPath != null) + message.fieldPath = String(object.fieldPath); + return message; + }; + + /** + * Creates a plain object from a FieldReference message. Also converts values to other types if specified. + * @function toObject + * @memberof google.firestore.v1.StructuredQuery.FieldReference + * @static + * @param {google.firestore.v1.StructuredQuery.FieldReference} message FieldReference + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + FieldReference.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.defaults) + object.fieldPath = ""; + if (message.fieldPath != null && message.hasOwnProperty("fieldPath")) + object.fieldPath = message.fieldPath; return object; }; /** - * Converts this ReadWrite to JSON. + * Converts this FieldReference to JSON. * @function toJSON - * @memberof google.firestore.v1.TransactionOptions.ReadWrite + * @memberof google.firestore.v1.StructuredQuery.FieldReference * @instance * @returns {Object.} JSON object */ - ReadWrite.prototype.toJSON = function toJSON() { + FieldReference.prototype.toJSON = function toJSON() { return this.constructor.toObject(this, $protobuf.util.toJSONOptions); }; /** - * Gets the default type url for ReadWrite + * Gets the default type url for FieldReference * @function getTypeUrl - * @memberof google.firestore.v1.TransactionOptions.ReadWrite + * @memberof google.firestore.v1.StructuredQuery.FieldReference * @static * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") * @returns {string} The default type url */ - ReadWrite.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + FieldReference.getTypeUrl = function getTypeUrl(typeUrlPrefix) { if (typeUrlPrefix === undefined) { typeUrlPrefix = "type.googleapis.com"; } - return typeUrlPrefix + "/google.firestore.v1.TransactionOptions.ReadWrite"; + return typeUrlPrefix + "/google.firestore.v1.StructuredQuery.FieldReference"; }; - return ReadWrite; + return FieldReference; })(); - TransactionOptions.ReadOnly = (function() { + StructuredQuery.Projection = (function() { /** - * Properties of a ReadOnly. - * @memberof google.firestore.v1.TransactionOptions - * @interface IReadOnly - * @property {google.protobuf.ITimestamp|null} [readTime] ReadOnly readTime + * Properties of a Projection. + * @memberof google.firestore.v1.StructuredQuery + * @interface IProjection + * @property {Array.|null} [fields] Projection fields */ /** - * Constructs a new ReadOnly. - * @memberof google.firestore.v1.TransactionOptions - * @classdesc Represents a ReadOnly. - * @implements IReadOnly + * Constructs a new Projection. + * @memberof google.firestore.v1.StructuredQuery + * @classdesc Represents a Projection. + * @implements IProjection * @constructor - * @param {google.firestore.v1.TransactionOptions.IReadOnly=} [properties] Properties to set + * @param {google.firestore.v1.StructuredQuery.IProjection=} [properties] Properties to set */ - function ReadOnly(properties) { + function Projection(properties) { + this.fields = []; if (properties) for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) if (properties[keys[i]] != null) @@ -11935,876 +10478,949 @@ } /** - * ReadOnly readTime. - * @member {google.protobuf.ITimestamp|null|undefined} readTime - * @memberof google.firestore.v1.TransactionOptions.ReadOnly - * @instance - */ - ReadOnly.prototype.readTime = null; - - // OneOf field names bound to virtual getters and setters - var $oneOfFields; - - /** - * ReadOnly consistencySelector. - * @member {"readTime"|undefined} consistencySelector - * @memberof google.firestore.v1.TransactionOptions.ReadOnly + * Projection fields. + * @member {Array.} fields + * @memberof google.firestore.v1.StructuredQuery.Projection * @instance */ - Object.defineProperty(ReadOnly.prototype, "consistencySelector", { - get: $util.oneOfGetter($oneOfFields = ["readTime"]), - set: $util.oneOfSetter($oneOfFields) - }); + Projection.prototype.fields = $util.emptyArray; /** - * Creates a ReadOnly message from a plain object. Also converts values to their respective internal types. + * Creates a Projection message from a plain object. Also converts values to their respective internal types. * @function fromObject - * @memberof google.firestore.v1.TransactionOptions.ReadOnly + * @memberof google.firestore.v1.StructuredQuery.Projection * @static * @param {Object.} object Plain object - * @returns {google.firestore.v1.TransactionOptions.ReadOnly} ReadOnly + * @returns {google.firestore.v1.StructuredQuery.Projection} Projection */ - ReadOnly.fromObject = function fromObject(object) { - if (object instanceof $root.google.firestore.v1.TransactionOptions.ReadOnly) + Projection.fromObject = function fromObject(object) { + if (object instanceof $root.google.firestore.v1.StructuredQuery.Projection) return object; - var message = new $root.google.firestore.v1.TransactionOptions.ReadOnly(); - if (object.readTime != null) { - if (typeof object.readTime !== "object") - throw TypeError(".google.firestore.v1.TransactionOptions.ReadOnly.readTime: object expected"); - message.readTime = $root.google.protobuf.Timestamp.fromObject(object.readTime); + var message = new $root.google.firestore.v1.StructuredQuery.Projection(); + if (object.fields) { + if (!Array.isArray(object.fields)) + throw TypeError(".google.firestore.v1.StructuredQuery.Projection.fields: array expected"); + message.fields = []; + for (var i = 0; i < object.fields.length; ++i) { + if (typeof object.fields[i] !== "object") + throw TypeError(".google.firestore.v1.StructuredQuery.Projection.fields: object expected"); + message.fields[i] = $root.google.firestore.v1.StructuredQuery.FieldReference.fromObject(object.fields[i]); + } } return message; }; /** - * Creates a plain object from a ReadOnly message. Also converts values to other types if specified. + * Creates a plain object from a Projection message. Also converts values to other types if specified. * @function toObject - * @memberof google.firestore.v1.TransactionOptions.ReadOnly + * @memberof google.firestore.v1.StructuredQuery.Projection * @static - * @param {google.firestore.v1.TransactionOptions.ReadOnly} message ReadOnly + * @param {google.firestore.v1.StructuredQuery.Projection} message Projection * @param {$protobuf.IConversionOptions} [options] Conversion options * @returns {Object.} Plain object */ - ReadOnly.toObject = function toObject(message, options) { + Projection.toObject = function toObject(message, options) { if (!options) options = {}; var object = {}; - if (message.readTime != null && message.hasOwnProperty("readTime")) { - object.readTime = $root.google.protobuf.Timestamp.toObject(message.readTime, options); - if (options.oneofs) - object.consistencySelector = "readTime"; - } - return object; - }; - - /** - * Converts this ReadOnly to JSON. - * @function toJSON - * @memberof google.firestore.v1.TransactionOptions.ReadOnly - * @instance - * @returns {Object.} JSON object - */ - ReadOnly.prototype.toJSON = function toJSON() { - return this.constructor.toObject(this, $protobuf.util.toJSONOptions); - }; - - /** - * Gets the default type url for ReadOnly - * @function getTypeUrl - * @memberof google.firestore.v1.TransactionOptions.ReadOnly - * @static - * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") - * @returns {string} The default type url - */ - ReadOnly.getTypeUrl = function getTypeUrl(typeUrlPrefix) { - if (typeUrlPrefix === undefined) { - typeUrlPrefix = "type.googleapis.com"; + if (options.arrays || options.defaults) + object.fields = []; + if (message.fields && message.fields.length) { + object.fields = []; + for (var j = 0; j < message.fields.length; ++j) + object.fields[j] = $root.google.firestore.v1.StructuredQuery.FieldReference.toObject(message.fields[j], options); } - return typeUrlPrefix + "/google.firestore.v1.TransactionOptions.ReadOnly"; - }; - - return ReadOnly; - })(); - - return TransactionOptions; - })(); - - v1.Firestore = (function() { - - /** - * Constructs a new Firestore service. - * @memberof google.firestore.v1 - * @classdesc Represents a Firestore - * @extends $protobuf.rpc.Service - * @constructor - * @param {$protobuf.RPCImpl} rpcImpl RPC implementation - * @param {boolean} [requestDelimited=false] Whether requests are length-delimited - * @param {boolean} [responseDelimited=false] Whether responses are length-delimited - */ - function Firestore(rpcImpl, requestDelimited, responseDelimited) { - $protobuf.rpc.Service.call(this, rpcImpl, requestDelimited, responseDelimited); - } - - (Firestore.prototype = Object.create($protobuf.rpc.Service.prototype)).constructor = Firestore; - - /** - * Callback as used by {@link google.firestore.v1.Firestore#getDocument}. - * @memberof google.firestore.v1.Firestore - * @typedef GetDocumentCallback - * @type {function} - * @param {Error|null} error Error, if any - * @param {google.firestore.v1.Document} [response] Document - */ - - /** - * Calls GetDocument. - * @function getDocument - * @memberof google.firestore.v1.Firestore - * @instance - * @param {google.firestore.v1.IGetDocumentRequest} request GetDocumentRequest message or plain object - * @param {google.firestore.v1.Firestore.GetDocumentCallback} callback Node-style callback called with the error, if any, and Document - * @returns {undefined} - * @variation 1 - */ - Object.defineProperty(Firestore.prototype.getDocument = function getDocument(request, callback) { - return this.rpcCall(getDocument, $root.google.firestore.v1.GetDocumentRequest, $root.google.firestore.v1.Document, request, callback); - }, "name", { value: "GetDocument" }); - - /** - * Calls GetDocument. - * @function getDocument - * @memberof google.firestore.v1.Firestore - * @instance - * @param {google.firestore.v1.IGetDocumentRequest} request GetDocumentRequest message or plain object - * @returns {Promise} Promise - * @variation 2 - */ - - /** - * Callback as used by {@link google.firestore.v1.Firestore#listDocuments}. - * @memberof google.firestore.v1.Firestore - * @typedef ListDocumentsCallback - * @type {function} - * @param {Error|null} error Error, if any - * @param {google.firestore.v1.ListDocumentsResponse} [response] ListDocumentsResponse - */ - - /** - * Calls ListDocuments. - * @function listDocuments - * @memberof google.firestore.v1.Firestore - * @instance - * @param {google.firestore.v1.IListDocumentsRequest} request ListDocumentsRequest message or plain object - * @param {google.firestore.v1.Firestore.ListDocumentsCallback} callback Node-style callback called with the error, if any, and ListDocumentsResponse - * @returns {undefined} - * @variation 1 - */ - Object.defineProperty(Firestore.prototype.listDocuments = function listDocuments(request, callback) { - return this.rpcCall(listDocuments, $root.google.firestore.v1.ListDocumentsRequest, $root.google.firestore.v1.ListDocumentsResponse, request, callback); - }, "name", { value: "ListDocuments" }); - - /** - * Calls ListDocuments. - * @function listDocuments - * @memberof google.firestore.v1.Firestore - * @instance - * @param {google.firestore.v1.IListDocumentsRequest} request ListDocumentsRequest message or plain object - * @returns {Promise} Promise - * @variation 2 - */ - - /** - * Callback as used by {@link google.firestore.v1.Firestore#updateDocument}. - * @memberof google.firestore.v1.Firestore - * @typedef UpdateDocumentCallback - * @type {function} - * @param {Error|null} error Error, if any - * @param {google.firestore.v1.Document} [response] Document - */ - - /** - * Calls UpdateDocument. - * @function updateDocument - * @memberof google.firestore.v1.Firestore - * @instance - * @param {google.firestore.v1.IUpdateDocumentRequest} request UpdateDocumentRequest message or plain object - * @param {google.firestore.v1.Firestore.UpdateDocumentCallback} callback Node-style callback called with the error, if any, and Document - * @returns {undefined} - * @variation 1 - */ - Object.defineProperty(Firestore.prototype.updateDocument = function updateDocument(request, callback) { - return this.rpcCall(updateDocument, $root.google.firestore.v1.UpdateDocumentRequest, $root.google.firestore.v1.Document, request, callback); - }, "name", { value: "UpdateDocument" }); + return object; + }; - /** - * Calls UpdateDocument. - * @function updateDocument - * @memberof google.firestore.v1.Firestore - * @instance - * @param {google.firestore.v1.IUpdateDocumentRequest} request UpdateDocumentRequest message or plain object - * @returns {Promise} Promise - * @variation 2 - */ + /** + * Converts this Projection to JSON. + * @function toJSON + * @memberof google.firestore.v1.StructuredQuery.Projection + * @instance + * @returns {Object.} JSON object + */ + Projection.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; - /** - * Callback as used by {@link google.firestore.v1.Firestore#deleteDocument}. - * @memberof google.firestore.v1.Firestore - * @typedef DeleteDocumentCallback - * @type {function} - * @param {Error|null} error Error, if any - * @param {google.protobuf.Empty} [response] Empty - */ + /** + * Gets the default type url for Projection + * @function getTypeUrl + * @memberof google.firestore.v1.StructuredQuery.Projection + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + Projection.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.firestore.v1.StructuredQuery.Projection"; + }; - /** - * Calls DeleteDocument. - * @function deleteDocument - * @memberof google.firestore.v1.Firestore - * @instance - * @param {google.firestore.v1.IDeleteDocumentRequest} request DeleteDocumentRequest message or plain object - * @param {google.firestore.v1.Firestore.DeleteDocumentCallback} callback Node-style callback called with the error, if any, and Empty - * @returns {undefined} - * @variation 1 - */ - Object.defineProperty(Firestore.prototype.deleteDocument = function deleteDocument(request, callback) { - return this.rpcCall(deleteDocument, $root.google.firestore.v1.DeleteDocumentRequest, $root.google.protobuf.Empty, request, callback); - }, "name", { value: "DeleteDocument" }); + return Projection; + })(); - /** - * Calls DeleteDocument. - * @function deleteDocument - * @memberof google.firestore.v1.Firestore - * @instance - * @param {google.firestore.v1.IDeleteDocumentRequest} request DeleteDocumentRequest message or plain object - * @returns {Promise} Promise - * @variation 2 - */ + StructuredQuery.FindNearest = (function() { - /** - * Callback as used by {@link google.firestore.v1.Firestore#batchGetDocuments}. - * @memberof google.firestore.v1.Firestore - * @typedef BatchGetDocumentsCallback - * @type {function} - * @param {Error|null} error Error, if any - * @param {google.firestore.v1.BatchGetDocumentsResponse} [response] BatchGetDocumentsResponse - */ + /** + * Properties of a FindNearest. + * @memberof google.firestore.v1.StructuredQuery + * @interface IFindNearest + * @property {google.firestore.v1.StructuredQuery.IFieldReference|null} [vectorField] FindNearest vectorField + * @property {google.firestore.v1.IValue|null} [queryVector] FindNearest queryVector + * @property {google.firestore.v1.StructuredQuery.FindNearest.DistanceMeasure|null} [distanceMeasure] FindNearest distanceMeasure + * @property {google.protobuf.IInt32Value|null} [limit] FindNearest limit + * @property {string|null} [distanceResultField] FindNearest distanceResultField + * @property {google.protobuf.IDoubleValue|null} [distanceThreshold] FindNearest distanceThreshold + */ - /** - * Calls BatchGetDocuments. - * @function batchGetDocuments - * @memberof google.firestore.v1.Firestore - * @instance - * @param {google.firestore.v1.IBatchGetDocumentsRequest} request BatchGetDocumentsRequest message or plain object - * @param {google.firestore.v1.Firestore.BatchGetDocumentsCallback} callback Node-style callback called with the error, if any, and BatchGetDocumentsResponse - * @returns {undefined} - * @variation 1 - */ - Object.defineProperty(Firestore.prototype.batchGetDocuments = function batchGetDocuments(request, callback) { - return this.rpcCall(batchGetDocuments, $root.google.firestore.v1.BatchGetDocumentsRequest, $root.google.firestore.v1.BatchGetDocumentsResponse, request, callback); - }, "name", { value: "BatchGetDocuments" }); + /** + * Constructs a new FindNearest. + * @memberof google.firestore.v1.StructuredQuery + * @classdesc Represents a FindNearest. + * @implements IFindNearest + * @constructor + * @param {google.firestore.v1.StructuredQuery.IFindNearest=} [properties] Properties to set + */ + function FindNearest(properties) { + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } - /** - * Calls BatchGetDocuments. - * @function batchGetDocuments - * @memberof google.firestore.v1.Firestore - * @instance - * @param {google.firestore.v1.IBatchGetDocumentsRequest} request BatchGetDocumentsRequest message or plain object - * @returns {Promise} Promise - * @variation 2 - */ + /** + * FindNearest vectorField. + * @member {google.firestore.v1.StructuredQuery.IFieldReference|null|undefined} vectorField + * @memberof google.firestore.v1.StructuredQuery.FindNearest + * @instance + */ + FindNearest.prototype.vectorField = null; - /** - * Callback as used by {@link google.firestore.v1.Firestore#beginTransaction}. - * @memberof google.firestore.v1.Firestore - * @typedef BeginTransactionCallback - * @type {function} - * @param {Error|null} error Error, if any - * @param {google.firestore.v1.BeginTransactionResponse} [response] BeginTransactionResponse - */ + /** + * FindNearest queryVector. + * @member {google.firestore.v1.IValue|null|undefined} queryVector + * @memberof google.firestore.v1.StructuredQuery.FindNearest + * @instance + */ + FindNearest.prototype.queryVector = null; - /** - * Calls BeginTransaction. - * @function beginTransaction - * @memberof google.firestore.v1.Firestore - * @instance - * @param {google.firestore.v1.IBeginTransactionRequest} request BeginTransactionRequest message or plain object - * @param {google.firestore.v1.Firestore.BeginTransactionCallback} callback Node-style callback called with the error, if any, and BeginTransactionResponse - * @returns {undefined} - * @variation 1 - */ - Object.defineProperty(Firestore.prototype.beginTransaction = function beginTransaction(request, callback) { - return this.rpcCall(beginTransaction, $root.google.firestore.v1.BeginTransactionRequest, $root.google.firestore.v1.BeginTransactionResponse, request, callback); - }, "name", { value: "BeginTransaction" }); + /** + * FindNearest distanceMeasure. + * @member {google.firestore.v1.StructuredQuery.FindNearest.DistanceMeasure} distanceMeasure + * @memberof google.firestore.v1.StructuredQuery.FindNearest + * @instance + */ + FindNearest.prototype.distanceMeasure = 0; - /** - * Calls BeginTransaction. - * @function beginTransaction - * @memberof google.firestore.v1.Firestore - * @instance - * @param {google.firestore.v1.IBeginTransactionRequest} request BeginTransactionRequest message or plain object - * @returns {Promise} Promise - * @variation 2 - */ + /** + * FindNearest limit. + * @member {google.protobuf.IInt32Value|null|undefined} limit + * @memberof google.firestore.v1.StructuredQuery.FindNearest + * @instance + */ + FindNearest.prototype.limit = null; - /** - * Callback as used by {@link google.firestore.v1.Firestore#commit}. - * @memberof google.firestore.v1.Firestore - * @typedef CommitCallback - * @type {function} - * @param {Error|null} error Error, if any - * @param {google.firestore.v1.CommitResponse} [response] CommitResponse - */ + /** + * FindNearest distanceResultField. + * @member {string} distanceResultField + * @memberof google.firestore.v1.StructuredQuery.FindNearest + * @instance + */ + FindNearest.prototype.distanceResultField = ""; - /** - * Calls Commit. - * @function commit - * @memberof google.firestore.v1.Firestore - * @instance - * @param {google.firestore.v1.ICommitRequest} request CommitRequest message or plain object - * @param {google.firestore.v1.Firestore.CommitCallback} callback Node-style callback called with the error, if any, and CommitResponse - * @returns {undefined} - * @variation 1 - */ - Object.defineProperty(Firestore.prototype.commit = function commit(request, callback) { - return this.rpcCall(commit, $root.google.firestore.v1.CommitRequest, $root.google.firestore.v1.CommitResponse, request, callback); - }, "name", { value: "Commit" }); + /** + * FindNearest distanceThreshold. + * @member {google.protobuf.IDoubleValue|null|undefined} distanceThreshold + * @memberof google.firestore.v1.StructuredQuery.FindNearest + * @instance + */ + FindNearest.prototype.distanceThreshold = null; + + /** + * Creates a FindNearest message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.firestore.v1.StructuredQuery.FindNearest + * @static + * @param {Object.} object Plain object + * @returns {google.firestore.v1.StructuredQuery.FindNearest} FindNearest + */ + FindNearest.fromObject = function fromObject(object) { + if (object instanceof $root.google.firestore.v1.StructuredQuery.FindNearest) + return object; + var message = new $root.google.firestore.v1.StructuredQuery.FindNearest(); + if (object.vectorField != null) { + if (typeof object.vectorField !== "object") + throw TypeError(".google.firestore.v1.StructuredQuery.FindNearest.vectorField: object expected"); + message.vectorField = $root.google.firestore.v1.StructuredQuery.FieldReference.fromObject(object.vectorField); + } + if (object.queryVector != null) { + if (typeof object.queryVector !== "object") + throw TypeError(".google.firestore.v1.StructuredQuery.FindNearest.queryVector: object expected"); + message.queryVector = $root.google.firestore.v1.Value.fromObject(object.queryVector); + } + switch (object.distanceMeasure) { + default: + if (typeof object.distanceMeasure === "number") { + message.distanceMeasure = object.distanceMeasure; + break; + } + break; + case "DISTANCE_MEASURE_UNSPECIFIED": + case 0: + message.distanceMeasure = 0; + break; + case "EUCLIDEAN": + case 1: + message.distanceMeasure = 1; + break; + case "COSINE": + case 2: + message.distanceMeasure = 2; + break; + case "DOT_PRODUCT": + case 3: + message.distanceMeasure = 3; + break; + } + if (object.limit != null) { + if (typeof object.limit !== "object") + throw TypeError(".google.firestore.v1.StructuredQuery.FindNearest.limit: object expected"); + message.limit = $root.google.protobuf.Int32Value.fromObject(object.limit); + } + if (object.distanceResultField != null) + message.distanceResultField = String(object.distanceResultField); + if (object.distanceThreshold != null) { + if (typeof object.distanceThreshold !== "object") + throw TypeError(".google.firestore.v1.StructuredQuery.FindNearest.distanceThreshold: object expected"); + message.distanceThreshold = $root.google.protobuf.DoubleValue.fromObject(object.distanceThreshold); + } + return message; + }; - /** - * Calls Commit. - * @function commit - * @memberof google.firestore.v1.Firestore - * @instance - * @param {google.firestore.v1.ICommitRequest} request CommitRequest message or plain object - * @returns {Promise} Promise - * @variation 2 - */ + /** + * Creates a plain object from a FindNearest message. Also converts values to other types if specified. + * @function toObject + * @memberof google.firestore.v1.StructuredQuery.FindNearest + * @static + * @param {google.firestore.v1.StructuredQuery.FindNearest} message FindNearest + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + FindNearest.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.defaults) { + object.vectorField = null; + object.queryVector = null; + object.distanceMeasure = options.enums === String ? "DISTANCE_MEASURE_UNSPECIFIED" : 0; + object.limit = null; + object.distanceResultField = ""; + object.distanceThreshold = null; + } + if (message.vectorField != null && message.hasOwnProperty("vectorField")) + object.vectorField = $root.google.firestore.v1.StructuredQuery.FieldReference.toObject(message.vectorField, options); + if (message.queryVector != null && message.hasOwnProperty("queryVector")) + object.queryVector = $root.google.firestore.v1.Value.toObject(message.queryVector, options); + if (message.distanceMeasure != null && message.hasOwnProperty("distanceMeasure")) + object.distanceMeasure = options.enums === String ? $root.google.firestore.v1.StructuredQuery.FindNearest.DistanceMeasure[message.distanceMeasure] === undefined ? message.distanceMeasure : $root.google.firestore.v1.StructuredQuery.FindNearest.DistanceMeasure[message.distanceMeasure] : message.distanceMeasure; + if (message.limit != null && message.hasOwnProperty("limit")) + object.limit = $root.google.protobuf.Int32Value.toObject(message.limit, options); + if (message.distanceResultField != null && message.hasOwnProperty("distanceResultField")) + object.distanceResultField = message.distanceResultField; + if (message.distanceThreshold != null && message.hasOwnProperty("distanceThreshold")) + object.distanceThreshold = $root.google.protobuf.DoubleValue.toObject(message.distanceThreshold, options); + return object; + }; - /** - * Callback as used by {@link google.firestore.v1.Firestore#rollback}. - * @memberof google.firestore.v1.Firestore - * @typedef RollbackCallback - * @type {function} - * @param {Error|null} error Error, if any - * @param {google.protobuf.Empty} [response] Empty - */ + /** + * Converts this FindNearest to JSON. + * @function toJSON + * @memberof google.firestore.v1.StructuredQuery.FindNearest + * @instance + * @returns {Object.} JSON object + */ + FindNearest.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; - /** - * Calls Rollback. - * @function rollback - * @memberof google.firestore.v1.Firestore - * @instance - * @param {google.firestore.v1.IRollbackRequest} request RollbackRequest message or plain object - * @param {google.firestore.v1.Firestore.RollbackCallback} callback Node-style callback called with the error, if any, and Empty - * @returns {undefined} - * @variation 1 - */ - Object.defineProperty(Firestore.prototype.rollback = function rollback(request, callback) { - return this.rpcCall(rollback, $root.google.firestore.v1.RollbackRequest, $root.google.protobuf.Empty, request, callback); - }, "name", { value: "Rollback" }); + /** + * Gets the default type url for FindNearest + * @function getTypeUrl + * @memberof google.firestore.v1.StructuredQuery.FindNearest + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + FindNearest.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.firestore.v1.StructuredQuery.FindNearest"; + }; - /** - * Calls Rollback. - * @function rollback - * @memberof google.firestore.v1.Firestore - * @instance - * @param {google.firestore.v1.IRollbackRequest} request RollbackRequest message or plain object - * @returns {Promise} Promise - * @variation 2 - */ + /** + * DistanceMeasure enum. + * @name google.firestore.v1.StructuredQuery.FindNearest.DistanceMeasure + * @enum {string} + * @property {string} DISTANCE_MEASURE_UNSPECIFIED=DISTANCE_MEASURE_UNSPECIFIED DISTANCE_MEASURE_UNSPECIFIED value + * @property {string} EUCLIDEAN=EUCLIDEAN EUCLIDEAN value + * @property {string} COSINE=COSINE COSINE value + * @property {string} DOT_PRODUCT=DOT_PRODUCT DOT_PRODUCT value + */ + FindNearest.DistanceMeasure = (function() { + var valuesById = {}, values = Object.create(valuesById); + values[valuesById[0] = "DISTANCE_MEASURE_UNSPECIFIED"] = "DISTANCE_MEASURE_UNSPECIFIED"; + values[valuesById[1] = "EUCLIDEAN"] = "EUCLIDEAN"; + values[valuesById[2] = "COSINE"] = "COSINE"; + values[valuesById[3] = "DOT_PRODUCT"] = "DOT_PRODUCT"; + return values; + })(); - /** - * Callback as used by {@link google.firestore.v1.Firestore#runQuery}. - * @memberof google.firestore.v1.Firestore - * @typedef RunQueryCallback - * @type {function} - * @param {Error|null} error Error, if any - * @param {google.firestore.v1.RunQueryResponse} [response] RunQueryResponse - */ + return FindNearest; + })(); - /** - * Calls RunQuery. - * @function runQuery - * @memberof google.firestore.v1.Firestore - * @instance - * @param {google.firestore.v1.IRunQueryRequest} request RunQueryRequest message or plain object - * @param {google.firestore.v1.Firestore.RunQueryCallback} callback Node-style callback called with the error, if any, and RunQueryResponse - * @returns {undefined} - * @variation 1 - */ - Object.defineProperty(Firestore.prototype.runQuery = function runQuery(request, callback) { - return this.rpcCall(runQuery, $root.google.firestore.v1.RunQueryRequest, $root.google.firestore.v1.RunQueryResponse, request, callback); - }, "name", { value: "RunQuery" }); + return StructuredQuery; + })(); + + v1.StructuredAggregationQuery = (function() { /** - * Calls RunQuery. - * @function runQuery - * @memberof google.firestore.v1.Firestore - * @instance - * @param {google.firestore.v1.IRunQueryRequest} request RunQueryRequest message or plain object - * @returns {Promise} Promise - * @variation 2 + * Properties of a StructuredAggregationQuery. + * @memberof google.firestore.v1 + * @interface IStructuredAggregationQuery + * @property {google.firestore.v1.IStructuredQuery|null} [structuredQuery] StructuredAggregationQuery structuredQuery + * @property {Array.|null} [aggregations] StructuredAggregationQuery aggregations */ /** - * Callback as used by {@link google.firestore.v1.Firestore#executePipeline}. - * @memberof google.firestore.v1.Firestore - * @typedef ExecutePipelineCallback - * @type {function} - * @param {Error|null} error Error, if any - * @param {google.firestore.v1.ExecutePipelineResponse} [response] ExecutePipelineResponse + * Constructs a new StructuredAggregationQuery. + * @memberof google.firestore.v1 + * @classdesc Represents a StructuredAggregationQuery. + * @implements IStructuredAggregationQuery + * @constructor + * @param {google.firestore.v1.IStructuredAggregationQuery=} [properties] Properties to set */ + function StructuredAggregationQuery(properties) { + this.aggregations = []; + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } /** - * Calls ExecutePipeline. - * @function executePipeline - * @memberof google.firestore.v1.Firestore + * StructuredAggregationQuery structuredQuery. + * @member {google.firestore.v1.IStructuredQuery|null|undefined} structuredQuery + * @memberof google.firestore.v1.StructuredAggregationQuery * @instance - * @param {google.firestore.v1.IExecutePipelineRequest} request ExecutePipelineRequest message or plain object - * @param {google.firestore.v1.Firestore.ExecutePipelineCallback} callback Node-style callback called with the error, if any, and ExecutePipelineResponse - * @returns {undefined} - * @variation 1 */ - Object.defineProperty(Firestore.prototype.executePipeline = function executePipeline(request, callback) { - return this.rpcCall(executePipeline, $root.google.firestore.v1.ExecutePipelineRequest, $root.google.firestore.v1.ExecutePipelineResponse, request, callback); - }, "name", { value: "ExecutePipeline" }); + StructuredAggregationQuery.prototype.structuredQuery = null; /** - * Calls ExecutePipeline. - * @function executePipeline - * @memberof google.firestore.v1.Firestore + * StructuredAggregationQuery aggregations. + * @member {Array.} aggregations + * @memberof google.firestore.v1.StructuredAggregationQuery * @instance - * @param {google.firestore.v1.IExecutePipelineRequest} request ExecutePipelineRequest message or plain object - * @returns {Promise} Promise - * @variation 2 */ + StructuredAggregationQuery.prototype.aggregations = $util.emptyArray; - /** - * Callback as used by {@link google.firestore.v1.Firestore#runAggregationQuery}. - * @memberof google.firestore.v1.Firestore - * @typedef RunAggregationQueryCallback - * @type {function} - * @param {Error|null} error Error, if any - * @param {google.firestore.v1.RunAggregationQueryResponse} [response] RunAggregationQueryResponse - */ + // OneOf field names bound to virtual getters and setters + var $oneOfFields; /** - * Calls RunAggregationQuery. - * @function runAggregationQuery - * @memberof google.firestore.v1.Firestore + * StructuredAggregationQuery queryType. + * @member {"structuredQuery"|undefined} queryType + * @memberof google.firestore.v1.StructuredAggregationQuery * @instance - * @param {google.firestore.v1.IRunAggregationQueryRequest} request RunAggregationQueryRequest message or plain object - * @param {google.firestore.v1.Firestore.RunAggregationQueryCallback} callback Node-style callback called with the error, if any, and RunAggregationQueryResponse - * @returns {undefined} - * @variation 1 */ - Object.defineProperty(Firestore.prototype.runAggregationQuery = function runAggregationQuery(request, callback) { - return this.rpcCall(runAggregationQuery, $root.google.firestore.v1.RunAggregationQueryRequest, $root.google.firestore.v1.RunAggregationQueryResponse, request, callback); - }, "name", { value: "RunAggregationQuery" }); + Object.defineProperty(StructuredAggregationQuery.prototype, "queryType", { + get: $util.oneOfGetter($oneOfFields = ["structuredQuery"]), + set: $util.oneOfSetter($oneOfFields) + }); /** - * Calls RunAggregationQuery. - * @function runAggregationQuery - * @memberof google.firestore.v1.Firestore - * @instance - * @param {google.firestore.v1.IRunAggregationQueryRequest} request RunAggregationQueryRequest message or plain object - * @returns {Promise} Promise - * @variation 2 + * Creates a StructuredAggregationQuery message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.firestore.v1.StructuredAggregationQuery + * @static + * @param {Object.} object Plain object + * @returns {google.firestore.v1.StructuredAggregationQuery} StructuredAggregationQuery */ + StructuredAggregationQuery.fromObject = function fromObject(object) { + if (object instanceof $root.google.firestore.v1.StructuredAggregationQuery) + return object; + var message = new $root.google.firestore.v1.StructuredAggregationQuery(); + if (object.structuredQuery != null) { + if (typeof object.structuredQuery !== "object") + throw TypeError(".google.firestore.v1.StructuredAggregationQuery.structuredQuery: object expected"); + message.structuredQuery = $root.google.firestore.v1.StructuredQuery.fromObject(object.structuredQuery); + } + if (object.aggregations) { + if (!Array.isArray(object.aggregations)) + throw TypeError(".google.firestore.v1.StructuredAggregationQuery.aggregations: array expected"); + message.aggregations = []; + for (var i = 0; i < object.aggregations.length; ++i) { + if (typeof object.aggregations[i] !== "object") + throw TypeError(".google.firestore.v1.StructuredAggregationQuery.aggregations: object expected"); + message.aggregations[i] = $root.google.firestore.v1.StructuredAggregationQuery.Aggregation.fromObject(object.aggregations[i]); + } + } + return message; + }; /** - * Callback as used by {@link google.firestore.v1.Firestore#partitionQuery}. - * @memberof google.firestore.v1.Firestore - * @typedef PartitionQueryCallback - * @type {function} - * @param {Error|null} error Error, if any - * @param {google.firestore.v1.PartitionQueryResponse} [response] PartitionQueryResponse + * Creates a plain object from a StructuredAggregationQuery message. Also converts values to other types if specified. + * @function toObject + * @memberof google.firestore.v1.StructuredAggregationQuery + * @static + * @param {google.firestore.v1.StructuredAggregationQuery} message StructuredAggregationQuery + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object */ + StructuredAggregationQuery.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.arrays || options.defaults) + object.aggregations = []; + if (message.structuredQuery != null && message.hasOwnProperty("structuredQuery")) { + object.structuredQuery = $root.google.firestore.v1.StructuredQuery.toObject(message.structuredQuery, options); + if (options.oneofs) + object.queryType = "structuredQuery"; + } + if (message.aggregations && message.aggregations.length) { + object.aggregations = []; + for (var j = 0; j < message.aggregations.length; ++j) + object.aggregations[j] = $root.google.firestore.v1.StructuredAggregationQuery.Aggregation.toObject(message.aggregations[j], options); + } + return object; + }; /** - * Calls PartitionQuery. - * @function partitionQuery - * @memberof google.firestore.v1.Firestore + * Converts this StructuredAggregationQuery to JSON. + * @function toJSON + * @memberof google.firestore.v1.StructuredAggregationQuery * @instance - * @param {google.firestore.v1.IPartitionQueryRequest} request PartitionQueryRequest message or plain object - * @param {google.firestore.v1.Firestore.PartitionQueryCallback} callback Node-style callback called with the error, if any, and PartitionQueryResponse - * @returns {undefined} - * @variation 1 + * @returns {Object.} JSON object */ - Object.defineProperty(Firestore.prototype.partitionQuery = function partitionQuery(request, callback) { - return this.rpcCall(partitionQuery, $root.google.firestore.v1.PartitionQueryRequest, $root.google.firestore.v1.PartitionQueryResponse, request, callback); - }, "name", { value: "PartitionQuery" }); + StructuredAggregationQuery.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; /** - * Calls PartitionQuery. - * @function partitionQuery - * @memberof google.firestore.v1.Firestore - * @instance - * @param {google.firestore.v1.IPartitionQueryRequest} request PartitionQueryRequest message or plain object - * @returns {Promise} Promise - * @variation 2 + * Gets the default type url for StructuredAggregationQuery + * @function getTypeUrl + * @memberof google.firestore.v1.StructuredAggregationQuery + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url */ + StructuredAggregationQuery.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.firestore.v1.StructuredAggregationQuery"; + }; - /** - * Callback as used by {@link google.firestore.v1.Firestore#write}. - * @memberof google.firestore.v1.Firestore - * @typedef WriteCallback - * @type {function} - * @param {Error|null} error Error, if any - * @param {google.firestore.v1.WriteResponse} [response] WriteResponse - */ + StructuredAggregationQuery.Aggregation = (function() { - /** - * Calls Write. - * @function write - * @memberof google.firestore.v1.Firestore - * @instance - * @param {google.firestore.v1.IWriteRequest} request WriteRequest message or plain object - * @param {google.firestore.v1.Firestore.WriteCallback} callback Node-style callback called with the error, if any, and WriteResponse - * @returns {undefined} - * @variation 1 - */ - Object.defineProperty(Firestore.prototype.write = function write(request, callback) { - return this.rpcCall(write, $root.google.firestore.v1.WriteRequest, $root.google.firestore.v1.WriteResponse, request, callback); - }, "name", { value: "Write" }); + /** + * Properties of an Aggregation. + * @memberof google.firestore.v1.StructuredAggregationQuery + * @interface IAggregation + * @property {google.firestore.v1.StructuredAggregationQuery.Aggregation.ICount|null} [count] Aggregation count + * @property {google.firestore.v1.StructuredAggregationQuery.Aggregation.ISum|null} [sum] Aggregation sum + * @property {google.firestore.v1.StructuredAggregationQuery.Aggregation.IAvg|null} [avg] Aggregation avg + * @property {string|null} [alias] Aggregation alias + */ - /** - * Calls Write. - * @function write - * @memberof google.firestore.v1.Firestore - * @instance - * @param {google.firestore.v1.IWriteRequest} request WriteRequest message or plain object - * @returns {Promise} Promise - * @variation 2 - */ + /** + * Constructs a new Aggregation. + * @memberof google.firestore.v1.StructuredAggregationQuery + * @classdesc Represents an Aggregation. + * @implements IAggregation + * @constructor + * @param {google.firestore.v1.StructuredAggregationQuery.IAggregation=} [properties] Properties to set + */ + function Aggregation(properties) { + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } + + /** + * Aggregation count. + * @member {google.firestore.v1.StructuredAggregationQuery.Aggregation.ICount|null|undefined} count + * @memberof google.firestore.v1.StructuredAggregationQuery.Aggregation + * @instance + */ + Aggregation.prototype.count = null; + + /** + * Aggregation sum. + * @member {google.firestore.v1.StructuredAggregationQuery.Aggregation.ISum|null|undefined} sum + * @memberof google.firestore.v1.StructuredAggregationQuery.Aggregation + * @instance + */ + Aggregation.prototype.sum = null; + + /** + * Aggregation avg. + * @member {google.firestore.v1.StructuredAggregationQuery.Aggregation.IAvg|null|undefined} avg + * @memberof google.firestore.v1.StructuredAggregationQuery.Aggregation + * @instance + */ + Aggregation.prototype.avg = null; + + /** + * Aggregation alias. + * @member {string} alias + * @memberof google.firestore.v1.StructuredAggregationQuery.Aggregation + * @instance + */ + Aggregation.prototype.alias = ""; + + // OneOf field names bound to virtual getters and setters + var $oneOfFields; + + /** + * Aggregation operator. + * @member {"count"|"sum"|"avg"|undefined} operator + * @memberof google.firestore.v1.StructuredAggregationQuery.Aggregation + * @instance + */ + Object.defineProperty(Aggregation.prototype, "operator", { + get: $util.oneOfGetter($oneOfFields = ["count", "sum", "avg"]), + set: $util.oneOfSetter($oneOfFields) + }); + + /** + * Creates an Aggregation message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.firestore.v1.StructuredAggregationQuery.Aggregation + * @static + * @param {Object.} object Plain object + * @returns {google.firestore.v1.StructuredAggregationQuery.Aggregation} Aggregation + */ + Aggregation.fromObject = function fromObject(object) { + if (object instanceof $root.google.firestore.v1.StructuredAggregationQuery.Aggregation) + return object; + var message = new $root.google.firestore.v1.StructuredAggregationQuery.Aggregation(); + if (object.count != null) { + if (typeof object.count !== "object") + throw TypeError(".google.firestore.v1.StructuredAggregationQuery.Aggregation.count: object expected"); + message.count = $root.google.firestore.v1.StructuredAggregationQuery.Aggregation.Count.fromObject(object.count); + } + if (object.sum != null) { + if (typeof object.sum !== "object") + throw TypeError(".google.firestore.v1.StructuredAggregationQuery.Aggregation.sum: object expected"); + message.sum = $root.google.firestore.v1.StructuredAggregationQuery.Aggregation.Sum.fromObject(object.sum); + } + if (object.avg != null) { + if (typeof object.avg !== "object") + throw TypeError(".google.firestore.v1.StructuredAggregationQuery.Aggregation.avg: object expected"); + message.avg = $root.google.firestore.v1.StructuredAggregationQuery.Aggregation.Avg.fromObject(object.avg); + } + if (object.alias != null) + message.alias = String(object.alias); + return message; + }; + + /** + * Creates a plain object from an Aggregation message. Also converts values to other types if specified. + * @function toObject + * @memberof google.firestore.v1.StructuredAggregationQuery.Aggregation + * @static + * @param {google.firestore.v1.StructuredAggregationQuery.Aggregation} message Aggregation + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + Aggregation.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.defaults) + object.alias = ""; + if (message.count != null && message.hasOwnProperty("count")) { + object.count = $root.google.firestore.v1.StructuredAggregationQuery.Aggregation.Count.toObject(message.count, options); + if (options.oneofs) + object.operator = "count"; + } + if (message.sum != null && message.hasOwnProperty("sum")) { + object.sum = $root.google.firestore.v1.StructuredAggregationQuery.Aggregation.Sum.toObject(message.sum, options); + if (options.oneofs) + object.operator = "sum"; + } + if (message.avg != null && message.hasOwnProperty("avg")) { + object.avg = $root.google.firestore.v1.StructuredAggregationQuery.Aggregation.Avg.toObject(message.avg, options); + if (options.oneofs) + object.operator = "avg"; + } + if (message.alias != null && message.hasOwnProperty("alias")) + object.alias = message.alias; + return object; + }; + + /** + * Converts this Aggregation to JSON. + * @function toJSON + * @memberof google.firestore.v1.StructuredAggregationQuery.Aggregation + * @instance + * @returns {Object.} JSON object + */ + Aggregation.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + + /** + * Gets the default type url for Aggregation + * @function getTypeUrl + * @memberof google.firestore.v1.StructuredAggregationQuery.Aggregation + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + Aggregation.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.firestore.v1.StructuredAggregationQuery.Aggregation"; + }; - /** - * Callback as used by {@link google.firestore.v1.Firestore#listen}. - * @memberof google.firestore.v1.Firestore - * @typedef ListenCallback - * @type {function} - * @param {Error|null} error Error, if any - * @param {google.firestore.v1.ListenResponse} [response] ListenResponse - */ + Aggregation.Count = (function() { - /** - * Calls Listen. - * @function listen - * @memberof google.firestore.v1.Firestore - * @instance - * @param {google.firestore.v1.IListenRequest} request ListenRequest message or plain object - * @param {google.firestore.v1.Firestore.ListenCallback} callback Node-style callback called with the error, if any, and ListenResponse - * @returns {undefined} - * @variation 1 - */ - Object.defineProperty(Firestore.prototype.listen = function listen(request, callback) { - return this.rpcCall(listen, $root.google.firestore.v1.ListenRequest, $root.google.firestore.v1.ListenResponse, request, callback); - }, "name", { value: "Listen" }); + /** + * Properties of a Count. + * @memberof google.firestore.v1.StructuredAggregationQuery.Aggregation + * @interface ICount + * @property {google.protobuf.IInt64Value|null} [upTo] Count upTo + */ - /** - * Calls Listen. - * @function listen - * @memberof google.firestore.v1.Firestore - * @instance - * @param {google.firestore.v1.IListenRequest} request ListenRequest message or plain object - * @returns {Promise} Promise - * @variation 2 - */ + /** + * Constructs a new Count. + * @memberof google.firestore.v1.StructuredAggregationQuery.Aggregation + * @classdesc Represents a Count. + * @implements ICount + * @constructor + * @param {google.firestore.v1.StructuredAggregationQuery.Aggregation.ICount=} [properties] Properties to set + */ + function Count(properties) { + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } - /** - * Callback as used by {@link google.firestore.v1.Firestore#listCollectionIds}. - * @memberof google.firestore.v1.Firestore - * @typedef ListCollectionIdsCallback - * @type {function} - * @param {Error|null} error Error, if any - * @param {google.firestore.v1.ListCollectionIdsResponse} [response] ListCollectionIdsResponse - */ + /** + * Count upTo. + * @member {google.protobuf.IInt64Value|null|undefined} upTo + * @memberof google.firestore.v1.StructuredAggregationQuery.Aggregation.Count + * @instance + */ + Count.prototype.upTo = null; - /** - * Calls ListCollectionIds. - * @function listCollectionIds - * @memberof google.firestore.v1.Firestore - * @instance - * @param {google.firestore.v1.IListCollectionIdsRequest} request ListCollectionIdsRequest message or plain object - * @param {google.firestore.v1.Firestore.ListCollectionIdsCallback} callback Node-style callback called with the error, if any, and ListCollectionIdsResponse - * @returns {undefined} - * @variation 1 - */ - Object.defineProperty(Firestore.prototype.listCollectionIds = function listCollectionIds(request, callback) { - return this.rpcCall(listCollectionIds, $root.google.firestore.v1.ListCollectionIdsRequest, $root.google.firestore.v1.ListCollectionIdsResponse, request, callback); - }, "name", { value: "ListCollectionIds" }); + /** + * Creates a Count message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.firestore.v1.StructuredAggregationQuery.Aggregation.Count + * @static + * @param {Object.} object Plain object + * @returns {google.firestore.v1.StructuredAggregationQuery.Aggregation.Count} Count + */ + Count.fromObject = function fromObject(object) { + if (object instanceof $root.google.firestore.v1.StructuredAggregationQuery.Aggregation.Count) + return object; + var message = new $root.google.firestore.v1.StructuredAggregationQuery.Aggregation.Count(); + if (object.upTo != null) { + if (typeof object.upTo !== "object") + throw TypeError(".google.firestore.v1.StructuredAggregationQuery.Aggregation.Count.upTo: object expected"); + message.upTo = $root.google.protobuf.Int64Value.fromObject(object.upTo); + } + return message; + }; - /** - * Calls ListCollectionIds. - * @function listCollectionIds - * @memberof google.firestore.v1.Firestore - * @instance - * @param {google.firestore.v1.IListCollectionIdsRequest} request ListCollectionIdsRequest message or plain object - * @returns {Promise} Promise - * @variation 2 - */ + /** + * Creates a plain object from a Count message. Also converts values to other types if specified. + * @function toObject + * @memberof google.firestore.v1.StructuredAggregationQuery.Aggregation.Count + * @static + * @param {google.firestore.v1.StructuredAggregationQuery.Aggregation.Count} message Count + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + Count.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.defaults) + object.upTo = null; + if (message.upTo != null && message.hasOwnProperty("upTo")) + object.upTo = $root.google.protobuf.Int64Value.toObject(message.upTo, options); + return object; + }; - /** - * Callback as used by {@link google.firestore.v1.Firestore#batchWrite}. - * @memberof google.firestore.v1.Firestore - * @typedef BatchWriteCallback - * @type {function} - * @param {Error|null} error Error, if any - * @param {google.firestore.v1.BatchWriteResponse} [response] BatchWriteResponse - */ + /** + * Converts this Count to JSON. + * @function toJSON + * @memberof google.firestore.v1.StructuredAggregationQuery.Aggregation.Count + * @instance + * @returns {Object.} JSON object + */ + Count.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; - /** - * Calls BatchWrite. - * @function batchWrite - * @memberof google.firestore.v1.Firestore - * @instance - * @param {google.firestore.v1.IBatchWriteRequest} request BatchWriteRequest message or plain object - * @param {google.firestore.v1.Firestore.BatchWriteCallback} callback Node-style callback called with the error, if any, and BatchWriteResponse - * @returns {undefined} - * @variation 1 - */ - Object.defineProperty(Firestore.prototype.batchWrite = function batchWrite(request, callback) { - return this.rpcCall(batchWrite, $root.google.firestore.v1.BatchWriteRequest, $root.google.firestore.v1.BatchWriteResponse, request, callback); - }, "name", { value: "BatchWrite" }); + /** + * Gets the default type url for Count + * @function getTypeUrl + * @memberof google.firestore.v1.StructuredAggregationQuery.Aggregation.Count + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + Count.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.firestore.v1.StructuredAggregationQuery.Aggregation.Count"; + }; - /** - * Calls BatchWrite. - * @function batchWrite - * @memberof google.firestore.v1.Firestore - * @instance - * @param {google.firestore.v1.IBatchWriteRequest} request BatchWriteRequest message or plain object - * @returns {Promise} Promise - * @variation 2 - */ + return Count; + })(); - /** - * Callback as used by {@link google.firestore.v1.Firestore#createDocument}. - * @memberof google.firestore.v1.Firestore - * @typedef CreateDocumentCallback - * @type {function} - * @param {Error|null} error Error, if any - * @param {google.firestore.v1.Document} [response] Document - */ + Aggregation.Sum = (function() { - /** - * Calls CreateDocument. - * @function createDocument - * @memberof google.firestore.v1.Firestore - * @instance - * @param {google.firestore.v1.ICreateDocumentRequest} request CreateDocumentRequest message or plain object - * @param {google.firestore.v1.Firestore.CreateDocumentCallback} callback Node-style callback called with the error, if any, and Document - * @returns {undefined} - * @variation 1 - */ - Object.defineProperty(Firestore.prototype.createDocument = function createDocument(request, callback) { - return this.rpcCall(createDocument, $root.google.firestore.v1.CreateDocumentRequest, $root.google.firestore.v1.Document, request, callback); - }, "name", { value: "CreateDocument" }); + /** + * Properties of a Sum. + * @memberof google.firestore.v1.StructuredAggregationQuery.Aggregation + * @interface ISum + * @property {google.firestore.v1.StructuredQuery.IFieldReference|null} [field] Sum field + */ - /** - * Calls CreateDocument. - * @function createDocument - * @memberof google.firestore.v1.Firestore - * @instance - * @param {google.firestore.v1.ICreateDocumentRequest} request CreateDocumentRequest message or plain object - * @returns {Promise} Promise - * @variation 2 - */ + /** + * Constructs a new Sum. + * @memberof google.firestore.v1.StructuredAggregationQuery.Aggregation + * @classdesc Represents a Sum. + * @implements ISum + * @constructor + * @param {google.firestore.v1.StructuredAggregationQuery.Aggregation.ISum=} [properties] Properties to set + */ + function Sum(properties) { + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } - return Firestore; - })(); + /** + * Sum field. + * @member {google.firestore.v1.StructuredQuery.IFieldReference|null|undefined} field + * @memberof google.firestore.v1.StructuredAggregationQuery.Aggregation.Sum + * @instance + */ + Sum.prototype.field = null; + + /** + * Creates a Sum message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.firestore.v1.StructuredAggregationQuery.Aggregation.Sum + * @static + * @param {Object.} object Plain object + * @returns {google.firestore.v1.StructuredAggregationQuery.Aggregation.Sum} Sum + */ + Sum.fromObject = function fromObject(object) { + if (object instanceof $root.google.firestore.v1.StructuredAggregationQuery.Aggregation.Sum) + return object; + var message = new $root.google.firestore.v1.StructuredAggregationQuery.Aggregation.Sum(); + if (object.field != null) { + if (typeof object.field !== "object") + throw TypeError(".google.firestore.v1.StructuredAggregationQuery.Aggregation.Sum.field: object expected"); + message.field = $root.google.firestore.v1.StructuredQuery.FieldReference.fromObject(object.field); + } + return message; + }; - v1.GetDocumentRequest = (function() { + /** + * Creates a plain object from a Sum message. Also converts values to other types if specified. + * @function toObject + * @memberof google.firestore.v1.StructuredAggregationQuery.Aggregation.Sum + * @static + * @param {google.firestore.v1.StructuredAggregationQuery.Aggregation.Sum} message Sum + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + Sum.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.defaults) + object.field = null; + if (message.field != null && message.hasOwnProperty("field")) + object.field = $root.google.firestore.v1.StructuredQuery.FieldReference.toObject(message.field, options); + return object; + }; - /** - * Properties of a GetDocumentRequest. - * @memberof google.firestore.v1 - * @interface IGetDocumentRequest - * @property {string|null} [name] GetDocumentRequest name - * @property {google.firestore.v1.IDocumentMask|null} [mask] GetDocumentRequest mask - * @property {Uint8Array|null} [transaction] GetDocumentRequest transaction - * @property {google.protobuf.ITimestamp|null} [readTime] GetDocumentRequest readTime - */ + /** + * Converts this Sum to JSON. + * @function toJSON + * @memberof google.firestore.v1.StructuredAggregationQuery.Aggregation.Sum + * @instance + * @returns {Object.} JSON object + */ + Sum.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; - /** - * Constructs a new GetDocumentRequest. - * @memberof google.firestore.v1 - * @classdesc Represents a GetDocumentRequest. - * @implements IGetDocumentRequest - * @constructor - * @param {google.firestore.v1.IGetDocumentRequest=} [properties] Properties to set - */ - function GetDocumentRequest(properties) { - if (properties) - for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) - if (properties[keys[i]] != null) - this[keys[i]] = properties[keys[i]]; - } + /** + * Gets the default type url for Sum + * @function getTypeUrl + * @memberof google.firestore.v1.StructuredAggregationQuery.Aggregation.Sum + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + Sum.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.firestore.v1.StructuredAggregationQuery.Aggregation.Sum"; + }; - /** - * GetDocumentRequest name. - * @member {string} name - * @memberof google.firestore.v1.GetDocumentRequest - * @instance - */ - GetDocumentRequest.prototype.name = ""; + return Sum; + })(); - /** - * GetDocumentRequest mask. - * @member {google.firestore.v1.IDocumentMask|null|undefined} mask - * @memberof google.firestore.v1.GetDocumentRequest - * @instance - */ - GetDocumentRequest.prototype.mask = null; + Aggregation.Avg = (function() { - /** - * GetDocumentRequest transaction. - * @member {Uint8Array|null|undefined} transaction - * @memberof google.firestore.v1.GetDocumentRequest - * @instance - */ - GetDocumentRequest.prototype.transaction = null; + /** + * Properties of an Avg. + * @memberof google.firestore.v1.StructuredAggregationQuery.Aggregation + * @interface IAvg + * @property {google.firestore.v1.StructuredQuery.IFieldReference|null} [field] Avg field + */ - /** - * GetDocumentRequest readTime. - * @member {google.protobuf.ITimestamp|null|undefined} readTime - * @memberof google.firestore.v1.GetDocumentRequest - * @instance - */ - GetDocumentRequest.prototype.readTime = null; + /** + * Constructs a new Avg. + * @memberof google.firestore.v1.StructuredAggregationQuery.Aggregation + * @classdesc Represents an Avg. + * @implements IAvg + * @constructor + * @param {google.firestore.v1.StructuredAggregationQuery.Aggregation.IAvg=} [properties] Properties to set + */ + function Avg(properties) { + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } - // OneOf field names bound to virtual getters and setters - var $oneOfFields; + /** + * Avg field. + * @member {google.firestore.v1.StructuredQuery.IFieldReference|null|undefined} field + * @memberof google.firestore.v1.StructuredAggregationQuery.Aggregation.Avg + * @instance + */ + Avg.prototype.field = null; - /** - * GetDocumentRequest consistencySelector. - * @member {"transaction"|"readTime"|undefined} consistencySelector - * @memberof google.firestore.v1.GetDocumentRequest - * @instance - */ - Object.defineProperty(GetDocumentRequest.prototype, "consistencySelector", { - get: $util.oneOfGetter($oneOfFields = ["transaction", "readTime"]), - set: $util.oneOfSetter($oneOfFields) - }); + /** + * Creates an Avg message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.firestore.v1.StructuredAggregationQuery.Aggregation.Avg + * @static + * @param {Object.} object Plain object + * @returns {google.firestore.v1.StructuredAggregationQuery.Aggregation.Avg} Avg + */ + Avg.fromObject = function fromObject(object) { + if (object instanceof $root.google.firestore.v1.StructuredAggregationQuery.Aggregation.Avg) + return object; + var message = new $root.google.firestore.v1.StructuredAggregationQuery.Aggregation.Avg(); + if (object.field != null) { + if (typeof object.field !== "object") + throw TypeError(".google.firestore.v1.StructuredAggregationQuery.Aggregation.Avg.field: object expected"); + message.field = $root.google.firestore.v1.StructuredQuery.FieldReference.fromObject(object.field); + } + return message; + }; - /** - * Creates a GetDocumentRequest message from a plain object. Also converts values to their respective internal types. - * @function fromObject - * @memberof google.firestore.v1.GetDocumentRequest - * @static - * @param {Object.} object Plain object - * @returns {google.firestore.v1.GetDocumentRequest} GetDocumentRequest - */ - GetDocumentRequest.fromObject = function fromObject(object) { - if (object instanceof $root.google.firestore.v1.GetDocumentRequest) - return object; - var message = new $root.google.firestore.v1.GetDocumentRequest(); - if (object.name != null) - message.name = String(object.name); - if (object.mask != null) { - if (typeof object.mask !== "object") - throw TypeError(".google.firestore.v1.GetDocumentRequest.mask: object expected"); - message.mask = $root.google.firestore.v1.DocumentMask.fromObject(object.mask); - } - if (object.transaction != null) - if (typeof object.transaction === "string") - $util.base64.decode(object.transaction, message.transaction = $util.newBuffer($util.base64.length(object.transaction)), 0); - else if (object.transaction.length >= 0) - message.transaction = object.transaction; - if (object.readTime != null) { - if (typeof object.readTime !== "object") - throw TypeError(".google.firestore.v1.GetDocumentRequest.readTime: object expected"); - message.readTime = $root.google.protobuf.Timestamp.fromObject(object.readTime); - } - return message; - }; + /** + * Creates a plain object from an Avg message. Also converts values to other types if specified. + * @function toObject + * @memberof google.firestore.v1.StructuredAggregationQuery.Aggregation.Avg + * @static + * @param {google.firestore.v1.StructuredAggregationQuery.Aggregation.Avg} message Avg + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + Avg.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.defaults) + object.field = null; + if (message.field != null && message.hasOwnProperty("field")) + object.field = $root.google.firestore.v1.StructuredQuery.FieldReference.toObject(message.field, options); + return object; + }; - /** - * Creates a plain object from a GetDocumentRequest message. Also converts values to other types if specified. - * @function toObject - * @memberof google.firestore.v1.GetDocumentRequest - * @static - * @param {google.firestore.v1.GetDocumentRequest} message GetDocumentRequest - * @param {$protobuf.IConversionOptions} [options] Conversion options - * @returns {Object.} Plain object - */ - GetDocumentRequest.toObject = function toObject(message, options) { - if (!options) - options = {}; - var object = {}; - if (options.defaults) { - object.name = ""; - object.mask = null; - } - if (message.name != null && message.hasOwnProperty("name")) - object.name = message.name; - if (message.mask != null && message.hasOwnProperty("mask")) - object.mask = $root.google.firestore.v1.DocumentMask.toObject(message.mask, options); - if (message.transaction != null && message.hasOwnProperty("transaction")) { - object.transaction = options.bytes === String ? $util.base64.encode(message.transaction, 0, message.transaction.length) : options.bytes === Array ? Array.prototype.slice.call(message.transaction) : message.transaction; - if (options.oneofs) - object.consistencySelector = "transaction"; - } - if (message.readTime != null && message.hasOwnProperty("readTime")) { - object.readTime = $root.google.protobuf.Timestamp.toObject(message.readTime, options); - if (options.oneofs) - object.consistencySelector = "readTime"; - } - return object; - }; + /** + * Converts this Avg to JSON. + * @function toJSON + * @memberof google.firestore.v1.StructuredAggregationQuery.Aggregation.Avg + * @instance + * @returns {Object.} JSON object + */ + Avg.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; - /** - * Converts this GetDocumentRequest to JSON. - * @function toJSON - * @memberof google.firestore.v1.GetDocumentRequest - * @instance - * @returns {Object.} JSON object - */ - GetDocumentRequest.prototype.toJSON = function toJSON() { - return this.constructor.toObject(this, $protobuf.util.toJSONOptions); - }; + /** + * Gets the default type url for Avg + * @function getTypeUrl + * @memberof google.firestore.v1.StructuredAggregationQuery.Aggregation.Avg + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + Avg.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.firestore.v1.StructuredAggregationQuery.Aggregation.Avg"; + }; - /** - * Gets the default type url for GetDocumentRequest - * @function getTypeUrl - * @memberof google.firestore.v1.GetDocumentRequest - * @static - * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") - * @returns {string} The default type url - */ - GetDocumentRequest.getTypeUrl = function getTypeUrl(typeUrlPrefix) { - if (typeUrlPrefix === undefined) { - typeUrlPrefix = "type.googleapis.com"; - } - return typeUrlPrefix + "/google.firestore.v1.GetDocumentRequest"; - }; + return Avg; + })(); - return GetDocumentRequest; + return Aggregation; + })(); + + return StructuredAggregationQuery; })(); - v1.ListDocumentsRequest = (function() { + v1.Cursor = (function() { /** - * Properties of a ListDocumentsRequest. + * Properties of a Cursor. * @memberof google.firestore.v1 - * @interface IListDocumentsRequest - * @property {string|null} [parent] ListDocumentsRequest parent - * @property {string|null} [collectionId] ListDocumentsRequest collectionId - * @property {number|null} [pageSize] ListDocumentsRequest pageSize - * @property {string|null} [pageToken] ListDocumentsRequest pageToken - * @property {string|null} [orderBy] ListDocumentsRequest orderBy - * @property {google.firestore.v1.IDocumentMask|null} [mask] ListDocumentsRequest mask - * @property {Uint8Array|null} [transaction] ListDocumentsRequest transaction - * @property {google.protobuf.ITimestamp|null} [readTime] ListDocumentsRequest readTime - * @property {boolean|null} [showMissing] ListDocumentsRequest showMissing + * @interface ICursor + * @property {Array.|null} [values] Cursor values + * @property {boolean|null} [before] Cursor before */ /** - * Constructs a new ListDocumentsRequest. + * Constructs a new Cursor. * @memberof google.firestore.v1 - * @classdesc Represents a ListDocumentsRequest. - * @implements IListDocumentsRequest + * @classdesc Represents a Cursor. + * @implements ICursor * @constructor - * @param {google.firestore.v1.IListDocumentsRequest=} [properties] Properties to set + * @param {google.firestore.v1.ICursor=} [properties] Properties to set */ - function ListDocumentsRequest(properties) { + function Cursor(properties) { + this.values = []; if (properties) for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) if (properties[keys[i]] != null) @@ -12812,231 +11428,122 @@ } /** - * ListDocumentsRequest parent. - * @member {string} parent - * @memberof google.firestore.v1.ListDocumentsRequest - * @instance - */ - ListDocumentsRequest.prototype.parent = ""; - - /** - * ListDocumentsRequest collectionId. - * @member {string} collectionId - * @memberof google.firestore.v1.ListDocumentsRequest - * @instance - */ - ListDocumentsRequest.prototype.collectionId = ""; - - /** - * ListDocumentsRequest pageSize. - * @member {number} pageSize - * @memberof google.firestore.v1.ListDocumentsRequest - * @instance - */ - ListDocumentsRequest.prototype.pageSize = 0; - - /** - * ListDocumentsRequest pageToken. - * @member {string} pageToken - * @memberof google.firestore.v1.ListDocumentsRequest - * @instance - */ - ListDocumentsRequest.prototype.pageToken = ""; - - /** - * ListDocumentsRequest orderBy. - * @member {string} orderBy - * @memberof google.firestore.v1.ListDocumentsRequest - * @instance - */ - ListDocumentsRequest.prototype.orderBy = ""; - - /** - * ListDocumentsRequest mask. - * @member {google.firestore.v1.IDocumentMask|null|undefined} mask - * @memberof google.firestore.v1.ListDocumentsRequest - * @instance - */ - ListDocumentsRequest.prototype.mask = null; - - /** - * ListDocumentsRequest transaction. - * @member {Uint8Array|null|undefined} transaction - * @memberof google.firestore.v1.ListDocumentsRequest - * @instance - */ - ListDocumentsRequest.prototype.transaction = null; - - /** - * ListDocumentsRequest readTime. - * @member {google.protobuf.ITimestamp|null|undefined} readTime - * @memberof google.firestore.v1.ListDocumentsRequest - * @instance - */ - ListDocumentsRequest.prototype.readTime = null; - - /** - * ListDocumentsRequest showMissing. - * @member {boolean} showMissing - * @memberof google.firestore.v1.ListDocumentsRequest + * Cursor values. + * @member {Array.} values + * @memberof google.firestore.v1.Cursor * @instance */ - ListDocumentsRequest.prototype.showMissing = false; - - // OneOf field names bound to virtual getters and setters - var $oneOfFields; + Cursor.prototype.values = $util.emptyArray; /** - * ListDocumentsRequest consistencySelector. - * @member {"transaction"|"readTime"|undefined} consistencySelector - * @memberof google.firestore.v1.ListDocumentsRequest + * Cursor before. + * @member {boolean} before + * @memberof google.firestore.v1.Cursor * @instance */ - Object.defineProperty(ListDocumentsRequest.prototype, "consistencySelector", { - get: $util.oneOfGetter($oneOfFields = ["transaction", "readTime"]), - set: $util.oneOfSetter($oneOfFields) - }); + Cursor.prototype.before = false; /** - * Creates a ListDocumentsRequest message from a plain object. Also converts values to their respective internal types. + * Creates a Cursor message from a plain object. Also converts values to their respective internal types. * @function fromObject - * @memberof google.firestore.v1.ListDocumentsRequest + * @memberof google.firestore.v1.Cursor * @static * @param {Object.} object Plain object - * @returns {google.firestore.v1.ListDocumentsRequest} ListDocumentsRequest + * @returns {google.firestore.v1.Cursor} Cursor */ - ListDocumentsRequest.fromObject = function fromObject(object) { - if (object instanceof $root.google.firestore.v1.ListDocumentsRequest) + Cursor.fromObject = function fromObject(object) { + if (object instanceof $root.google.firestore.v1.Cursor) return object; - var message = new $root.google.firestore.v1.ListDocumentsRequest(); - if (object.parent != null) - message.parent = String(object.parent); - if (object.collectionId != null) - message.collectionId = String(object.collectionId); - if (object.pageSize != null) - message.pageSize = object.pageSize | 0; - if (object.pageToken != null) - message.pageToken = String(object.pageToken); - if (object.orderBy != null) - message.orderBy = String(object.orderBy); - if (object.mask != null) { - if (typeof object.mask !== "object") - throw TypeError(".google.firestore.v1.ListDocumentsRequest.mask: object expected"); - message.mask = $root.google.firestore.v1.DocumentMask.fromObject(object.mask); - } - if (object.transaction != null) - if (typeof object.transaction === "string") - $util.base64.decode(object.transaction, message.transaction = $util.newBuffer($util.base64.length(object.transaction)), 0); - else if (object.transaction.length >= 0) - message.transaction = object.transaction; - if (object.readTime != null) { - if (typeof object.readTime !== "object") - throw TypeError(".google.firestore.v1.ListDocumentsRequest.readTime: object expected"); - message.readTime = $root.google.protobuf.Timestamp.fromObject(object.readTime); + var message = new $root.google.firestore.v1.Cursor(); + if (object.values) { + if (!Array.isArray(object.values)) + throw TypeError(".google.firestore.v1.Cursor.values: array expected"); + message.values = []; + for (var i = 0; i < object.values.length; ++i) { + if (typeof object.values[i] !== "object") + throw TypeError(".google.firestore.v1.Cursor.values: object expected"); + message.values[i] = $root.google.firestore.v1.Value.fromObject(object.values[i]); + } } - if (object.showMissing != null) - message.showMissing = Boolean(object.showMissing); + if (object.before != null) + message.before = Boolean(object.before); return message; }; /** - * Creates a plain object from a ListDocumentsRequest message. Also converts values to other types if specified. + * Creates a plain object from a Cursor message. Also converts values to other types if specified. * @function toObject - * @memberof google.firestore.v1.ListDocumentsRequest + * @memberof google.firestore.v1.Cursor * @static - * @param {google.firestore.v1.ListDocumentsRequest} message ListDocumentsRequest + * @param {google.firestore.v1.Cursor} message Cursor * @param {$protobuf.IConversionOptions} [options] Conversion options * @returns {Object.} Plain object */ - ListDocumentsRequest.toObject = function toObject(message, options) { + Cursor.toObject = function toObject(message, options) { if (!options) options = {}; var object = {}; - if (options.defaults) { - object.parent = ""; - object.collectionId = ""; - object.pageSize = 0; - object.pageToken = ""; - object.orderBy = ""; - object.mask = null; - object.showMissing = false; - } - if (message.parent != null && message.hasOwnProperty("parent")) - object.parent = message.parent; - if (message.collectionId != null && message.hasOwnProperty("collectionId")) - object.collectionId = message.collectionId; - if (message.pageSize != null && message.hasOwnProperty("pageSize")) - object.pageSize = message.pageSize; - if (message.pageToken != null && message.hasOwnProperty("pageToken")) - object.pageToken = message.pageToken; - if (message.orderBy != null && message.hasOwnProperty("orderBy")) - object.orderBy = message.orderBy; - if (message.mask != null && message.hasOwnProperty("mask")) - object.mask = $root.google.firestore.v1.DocumentMask.toObject(message.mask, options); - if (message.transaction != null && message.hasOwnProperty("transaction")) { - object.transaction = options.bytes === String ? $util.base64.encode(message.transaction, 0, message.transaction.length) : options.bytes === Array ? Array.prototype.slice.call(message.transaction) : message.transaction; - if (options.oneofs) - object.consistencySelector = "transaction"; - } - if (message.readTime != null && message.hasOwnProperty("readTime")) { - object.readTime = $root.google.protobuf.Timestamp.toObject(message.readTime, options); - if (options.oneofs) - object.consistencySelector = "readTime"; + if (options.arrays || options.defaults) + object.values = []; + if (options.defaults) + object.before = false; + if (message.values && message.values.length) { + object.values = []; + for (var j = 0; j < message.values.length; ++j) + object.values[j] = $root.google.firestore.v1.Value.toObject(message.values[j], options); } - if (message.showMissing != null && message.hasOwnProperty("showMissing")) - object.showMissing = message.showMissing; + if (message.before != null && message.hasOwnProperty("before")) + object.before = message.before; return object; }; /** - * Converts this ListDocumentsRequest to JSON. + * Converts this Cursor to JSON. * @function toJSON - * @memberof google.firestore.v1.ListDocumentsRequest + * @memberof google.firestore.v1.Cursor * @instance * @returns {Object.} JSON object */ - ListDocumentsRequest.prototype.toJSON = function toJSON() { + Cursor.prototype.toJSON = function toJSON() { return this.constructor.toObject(this, $protobuf.util.toJSONOptions); }; /** - * Gets the default type url for ListDocumentsRequest + * Gets the default type url for Cursor * @function getTypeUrl - * @memberof google.firestore.v1.ListDocumentsRequest + * @memberof google.firestore.v1.Cursor * @static * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") * @returns {string} The default type url */ - ListDocumentsRequest.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + Cursor.getTypeUrl = function getTypeUrl(typeUrlPrefix) { if (typeUrlPrefix === undefined) { typeUrlPrefix = "type.googleapis.com"; } - return typeUrlPrefix + "/google.firestore.v1.ListDocumentsRequest"; + return typeUrlPrefix + "/google.firestore.v1.Cursor"; }; - return ListDocumentsRequest; + return Cursor; })(); - v1.ListDocumentsResponse = (function() { + v1.ExplainOptions = (function() { /** - * Properties of a ListDocumentsResponse. + * Properties of an ExplainOptions. * @memberof google.firestore.v1 - * @interface IListDocumentsResponse - * @property {Array.|null} [documents] ListDocumentsResponse documents - * @property {string|null} [nextPageToken] ListDocumentsResponse nextPageToken + * @interface IExplainOptions + * @property {boolean|null} [analyze] ExplainOptions analyze */ /** - * Constructs a new ListDocumentsResponse. + * Constructs a new ExplainOptions. * @memberof google.firestore.v1 - * @classdesc Represents a ListDocumentsResponse. - * @implements IListDocumentsResponse + * @classdesc Represents an ExplainOptions. + * @implements IExplainOptions * @constructor - * @param {google.firestore.v1.IListDocumentsResponse=} [properties] Properties to set + * @param {google.firestore.v1.IExplainOptions=} [properties] Properties to set */ - function ListDocumentsResponse(properties) { - this.documents = []; + function ExplainOptions(properties) { if (properties) for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) if (properties[keys[i]] != null) @@ -13044,126 +11551,98 @@ } /** - * ListDocumentsResponse documents. - * @member {Array.} documents - * @memberof google.firestore.v1.ListDocumentsResponse - * @instance - */ - ListDocumentsResponse.prototype.documents = $util.emptyArray; - - /** - * ListDocumentsResponse nextPageToken. - * @member {string} nextPageToken - * @memberof google.firestore.v1.ListDocumentsResponse + * ExplainOptions analyze. + * @member {boolean} analyze + * @memberof google.firestore.v1.ExplainOptions * @instance */ - ListDocumentsResponse.prototype.nextPageToken = ""; + ExplainOptions.prototype.analyze = false; /** - * Creates a ListDocumentsResponse message from a plain object. Also converts values to their respective internal types. + * Creates an ExplainOptions message from a plain object. Also converts values to their respective internal types. * @function fromObject - * @memberof google.firestore.v1.ListDocumentsResponse + * @memberof google.firestore.v1.ExplainOptions * @static * @param {Object.} object Plain object - * @returns {google.firestore.v1.ListDocumentsResponse} ListDocumentsResponse + * @returns {google.firestore.v1.ExplainOptions} ExplainOptions */ - ListDocumentsResponse.fromObject = function fromObject(object) { - if (object instanceof $root.google.firestore.v1.ListDocumentsResponse) + ExplainOptions.fromObject = function fromObject(object) { + if (object instanceof $root.google.firestore.v1.ExplainOptions) return object; - var message = new $root.google.firestore.v1.ListDocumentsResponse(); - if (object.documents) { - if (!Array.isArray(object.documents)) - throw TypeError(".google.firestore.v1.ListDocumentsResponse.documents: array expected"); - message.documents = []; - for (var i = 0; i < object.documents.length; ++i) { - if (typeof object.documents[i] !== "object") - throw TypeError(".google.firestore.v1.ListDocumentsResponse.documents: object expected"); - message.documents[i] = $root.google.firestore.v1.Document.fromObject(object.documents[i]); - } - } - if (object.nextPageToken != null) - message.nextPageToken = String(object.nextPageToken); + var message = new $root.google.firestore.v1.ExplainOptions(); + if (object.analyze != null) + message.analyze = Boolean(object.analyze); return message; }; /** - * Creates a plain object from a ListDocumentsResponse message. Also converts values to other types if specified. + * Creates a plain object from an ExplainOptions message. Also converts values to other types if specified. * @function toObject - * @memberof google.firestore.v1.ListDocumentsResponse + * @memberof google.firestore.v1.ExplainOptions * @static - * @param {google.firestore.v1.ListDocumentsResponse} message ListDocumentsResponse + * @param {google.firestore.v1.ExplainOptions} message ExplainOptions * @param {$protobuf.IConversionOptions} [options] Conversion options * @returns {Object.} Plain object */ - ListDocumentsResponse.toObject = function toObject(message, options) { + ExplainOptions.toObject = function toObject(message, options) { if (!options) options = {}; var object = {}; - if (options.arrays || options.defaults) - object.documents = []; if (options.defaults) - object.nextPageToken = ""; - if (message.documents && message.documents.length) { - object.documents = []; - for (var j = 0; j < message.documents.length; ++j) - object.documents[j] = $root.google.firestore.v1.Document.toObject(message.documents[j], options); - } - if (message.nextPageToken != null && message.hasOwnProperty("nextPageToken")) - object.nextPageToken = message.nextPageToken; + object.analyze = false; + if (message.analyze != null && message.hasOwnProperty("analyze")) + object.analyze = message.analyze; return object; }; /** - * Converts this ListDocumentsResponse to JSON. + * Converts this ExplainOptions to JSON. * @function toJSON - * @memberof google.firestore.v1.ListDocumentsResponse + * @memberof google.firestore.v1.ExplainOptions * @instance * @returns {Object.} JSON object */ - ListDocumentsResponse.prototype.toJSON = function toJSON() { + ExplainOptions.prototype.toJSON = function toJSON() { return this.constructor.toObject(this, $protobuf.util.toJSONOptions); }; /** - * Gets the default type url for ListDocumentsResponse + * Gets the default type url for ExplainOptions * @function getTypeUrl - * @memberof google.firestore.v1.ListDocumentsResponse + * @memberof google.firestore.v1.ExplainOptions * @static * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") * @returns {string} The default type url */ - ListDocumentsResponse.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + ExplainOptions.getTypeUrl = function getTypeUrl(typeUrlPrefix) { if (typeUrlPrefix === undefined) { typeUrlPrefix = "type.googleapis.com"; } - return typeUrlPrefix + "/google.firestore.v1.ListDocumentsResponse"; + return typeUrlPrefix + "/google.firestore.v1.ExplainOptions"; }; - return ListDocumentsResponse; + return ExplainOptions; })(); - v1.CreateDocumentRequest = (function() { + v1.ExplainMetrics = (function() { /** - * Properties of a CreateDocumentRequest. + * Properties of an ExplainMetrics. * @memberof google.firestore.v1 - * @interface ICreateDocumentRequest - * @property {string|null} [parent] CreateDocumentRequest parent - * @property {string|null} [collectionId] CreateDocumentRequest collectionId - * @property {string|null} [documentId] CreateDocumentRequest documentId - * @property {google.firestore.v1.IDocument|null} [document] CreateDocumentRequest document - * @property {google.firestore.v1.IDocumentMask|null} [mask] CreateDocumentRequest mask + * @interface IExplainMetrics + * @property {google.firestore.v1.IPlanSummary|null} [planSummary] ExplainMetrics planSummary + * @property {google.firestore.v1.IExecutionStats|null} [executionStats] ExplainMetrics executionStats */ /** - * Constructs a new CreateDocumentRequest. + * Constructs a new ExplainMetrics. * @memberof google.firestore.v1 - * @classdesc Represents a CreateDocumentRequest. - * @implements ICreateDocumentRequest + * @classdesc Represents an ExplainMetrics. + * @implements IExplainMetrics * @constructor - * @param {google.firestore.v1.ICreateDocumentRequest=} [properties] Properties to set + * @param {google.firestore.v1.IExplainMetrics=} [properties] Properties to set */ - function CreateDocumentRequest(properties) { + function ExplainMetrics(properties) { if (properties) for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) if (properties[keys[i]] != null) @@ -13171,159 +11650,118 @@ } /** - * CreateDocumentRequest parent. - * @member {string} parent - * @memberof google.firestore.v1.CreateDocumentRequest - * @instance - */ - CreateDocumentRequest.prototype.parent = ""; - - /** - * CreateDocumentRequest collectionId. - * @member {string} collectionId - * @memberof google.firestore.v1.CreateDocumentRequest - * @instance - */ - CreateDocumentRequest.prototype.collectionId = ""; - - /** - * CreateDocumentRequest documentId. - * @member {string} documentId - * @memberof google.firestore.v1.CreateDocumentRequest - * @instance - */ - CreateDocumentRequest.prototype.documentId = ""; - - /** - * CreateDocumentRequest document. - * @member {google.firestore.v1.IDocument|null|undefined} document - * @memberof google.firestore.v1.CreateDocumentRequest + * ExplainMetrics planSummary. + * @member {google.firestore.v1.IPlanSummary|null|undefined} planSummary + * @memberof google.firestore.v1.ExplainMetrics * @instance */ - CreateDocumentRequest.prototype.document = null; + ExplainMetrics.prototype.planSummary = null; /** - * CreateDocumentRequest mask. - * @member {google.firestore.v1.IDocumentMask|null|undefined} mask - * @memberof google.firestore.v1.CreateDocumentRequest + * ExplainMetrics executionStats. + * @member {google.firestore.v1.IExecutionStats|null|undefined} executionStats + * @memberof google.firestore.v1.ExplainMetrics * @instance */ - CreateDocumentRequest.prototype.mask = null; + ExplainMetrics.prototype.executionStats = null; /** - * Creates a CreateDocumentRequest message from a plain object. Also converts values to their respective internal types. + * Creates an ExplainMetrics message from a plain object. Also converts values to their respective internal types. * @function fromObject - * @memberof google.firestore.v1.CreateDocumentRequest + * @memberof google.firestore.v1.ExplainMetrics * @static * @param {Object.} object Plain object - * @returns {google.firestore.v1.CreateDocumentRequest} CreateDocumentRequest + * @returns {google.firestore.v1.ExplainMetrics} ExplainMetrics */ - CreateDocumentRequest.fromObject = function fromObject(object) { - if (object instanceof $root.google.firestore.v1.CreateDocumentRequest) + ExplainMetrics.fromObject = function fromObject(object) { + if (object instanceof $root.google.firestore.v1.ExplainMetrics) return object; - var message = new $root.google.firestore.v1.CreateDocumentRequest(); - if (object.parent != null) - message.parent = String(object.parent); - if (object.collectionId != null) - message.collectionId = String(object.collectionId); - if (object.documentId != null) - message.documentId = String(object.documentId); - if (object.document != null) { - if (typeof object.document !== "object") - throw TypeError(".google.firestore.v1.CreateDocumentRequest.document: object expected"); - message.document = $root.google.firestore.v1.Document.fromObject(object.document); + var message = new $root.google.firestore.v1.ExplainMetrics(); + if (object.planSummary != null) { + if (typeof object.planSummary !== "object") + throw TypeError(".google.firestore.v1.ExplainMetrics.planSummary: object expected"); + message.planSummary = $root.google.firestore.v1.PlanSummary.fromObject(object.planSummary); } - if (object.mask != null) { - if (typeof object.mask !== "object") - throw TypeError(".google.firestore.v1.CreateDocumentRequest.mask: object expected"); - message.mask = $root.google.firestore.v1.DocumentMask.fromObject(object.mask); + if (object.executionStats != null) { + if (typeof object.executionStats !== "object") + throw TypeError(".google.firestore.v1.ExplainMetrics.executionStats: object expected"); + message.executionStats = $root.google.firestore.v1.ExecutionStats.fromObject(object.executionStats); } return message; }; /** - * Creates a plain object from a CreateDocumentRequest message. Also converts values to other types if specified. + * Creates a plain object from an ExplainMetrics message. Also converts values to other types if specified. * @function toObject - * @memberof google.firestore.v1.CreateDocumentRequest + * @memberof google.firestore.v1.ExplainMetrics * @static - * @param {google.firestore.v1.CreateDocumentRequest} message CreateDocumentRequest + * @param {google.firestore.v1.ExplainMetrics} message ExplainMetrics * @param {$protobuf.IConversionOptions} [options] Conversion options * @returns {Object.} Plain object */ - CreateDocumentRequest.toObject = function toObject(message, options) { + ExplainMetrics.toObject = function toObject(message, options) { if (!options) options = {}; var object = {}; if (options.defaults) { - object.parent = ""; - object.collectionId = ""; - object.documentId = ""; - object.document = null; - object.mask = null; + object.planSummary = null; + object.executionStats = null; } - if (message.parent != null && message.hasOwnProperty("parent")) - object.parent = message.parent; - if (message.collectionId != null && message.hasOwnProperty("collectionId")) - object.collectionId = message.collectionId; - if (message.documentId != null && message.hasOwnProperty("documentId")) - object.documentId = message.documentId; - if (message.document != null && message.hasOwnProperty("document")) - object.document = $root.google.firestore.v1.Document.toObject(message.document, options); - if (message.mask != null && message.hasOwnProperty("mask")) - object.mask = $root.google.firestore.v1.DocumentMask.toObject(message.mask, options); + if (message.planSummary != null && message.hasOwnProperty("planSummary")) + object.planSummary = $root.google.firestore.v1.PlanSummary.toObject(message.planSummary, options); + if (message.executionStats != null && message.hasOwnProperty("executionStats")) + object.executionStats = $root.google.firestore.v1.ExecutionStats.toObject(message.executionStats, options); return object; }; /** - * Converts this CreateDocumentRequest to JSON. + * Converts this ExplainMetrics to JSON. * @function toJSON - * @memberof google.firestore.v1.CreateDocumentRequest + * @memberof google.firestore.v1.ExplainMetrics * @instance * @returns {Object.} JSON object */ - CreateDocumentRequest.prototype.toJSON = function toJSON() { + ExplainMetrics.prototype.toJSON = function toJSON() { return this.constructor.toObject(this, $protobuf.util.toJSONOptions); }; /** - * Gets the default type url for CreateDocumentRequest + * Gets the default type url for ExplainMetrics * @function getTypeUrl - * @memberof google.firestore.v1.CreateDocumentRequest + * @memberof google.firestore.v1.ExplainMetrics * @static * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") * @returns {string} The default type url */ - CreateDocumentRequest.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + ExplainMetrics.getTypeUrl = function getTypeUrl(typeUrlPrefix) { if (typeUrlPrefix === undefined) { typeUrlPrefix = "type.googleapis.com"; } - return typeUrlPrefix + "/google.firestore.v1.CreateDocumentRequest"; + return typeUrlPrefix + "/google.firestore.v1.ExplainMetrics"; }; - return CreateDocumentRequest; + return ExplainMetrics; })(); - v1.UpdateDocumentRequest = (function() { + v1.PlanSummary = (function() { /** - * Properties of an UpdateDocumentRequest. + * Properties of a PlanSummary. * @memberof google.firestore.v1 - * @interface IUpdateDocumentRequest - * @property {google.firestore.v1.IDocument|null} [document] UpdateDocumentRequest document - * @property {google.firestore.v1.IDocumentMask|null} [updateMask] UpdateDocumentRequest updateMask - * @property {google.firestore.v1.IDocumentMask|null} [mask] UpdateDocumentRequest mask - * @property {google.firestore.v1.IPrecondition|null} [currentDocument] UpdateDocumentRequest currentDocument + * @interface IPlanSummary + * @property {Array.|null} [indexesUsed] PlanSummary indexesUsed */ /** - * Constructs a new UpdateDocumentRequest. + * Constructs a new PlanSummary. * @memberof google.firestore.v1 - * @classdesc Represents an UpdateDocumentRequest. - * @implements IUpdateDocumentRequest + * @classdesc Represents a PlanSummary. + * @implements IPlanSummary * @constructor - * @param {google.firestore.v1.IUpdateDocumentRequest=} [properties] Properties to set + * @param {google.firestore.v1.IPlanSummary=} [properties] Properties to set */ - function UpdateDocumentRequest(properties) { + function PlanSummary(properties) { + this.indexesUsed = []; if (properties) for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) if (properties[keys[i]] != null) @@ -13331,150 +11769,111 @@ } /** - * UpdateDocumentRequest document. - * @member {google.firestore.v1.IDocument|null|undefined} document - * @memberof google.firestore.v1.UpdateDocumentRequest - * @instance - */ - UpdateDocumentRequest.prototype.document = null; - - /** - * UpdateDocumentRequest updateMask. - * @member {google.firestore.v1.IDocumentMask|null|undefined} updateMask - * @memberof google.firestore.v1.UpdateDocumentRequest - * @instance - */ - UpdateDocumentRequest.prototype.updateMask = null; - - /** - * UpdateDocumentRequest mask. - * @member {google.firestore.v1.IDocumentMask|null|undefined} mask - * @memberof google.firestore.v1.UpdateDocumentRequest - * @instance - */ - UpdateDocumentRequest.prototype.mask = null; - - /** - * UpdateDocumentRequest currentDocument. - * @member {google.firestore.v1.IPrecondition|null|undefined} currentDocument - * @memberof google.firestore.v1.UpdateDocumentRequest + * PlanSummary indexesUsed. + * @member {Array.} indexesUsed + * @memberof google.firestore.v1.PlanSummary * @instance */ - UpdateDocumentRequest.prototype.currentDocument = null; + PlanSummary.prototype.indexesUsed = $util.emptyArray; /** - * Creates an UpdateDocumentRequest message from a plain object. Also converts values to their respective internal types. + * Creates a PlanSummary message from a plain object. Also converts values to their respective internal types. * @function fromObject - * @memberof google.firestore.v1.UpdateDocumentRequest + * @memberof google.firestore.v1.PlanSummary * @static * @param {Object.} object Plain object - * @returns {google.firestore.v1.UpdateDocumentRequest} UpdateDocumentRequest + * @returns {google.firestore.v1.PlanSummary} PlanSummary */ - UpdateDocumentRequest.fromObject = function fromObject(object) { - if (object instanceof $root.google.firestore.v1.UpdateDocumentRequest) + PlanSummary.fromObject = function fromObject(object) { + if (object instanceof $root.google.firestore.v1.PlanSummary) return object; - var message = new $root.google.firestore.v1.UpdateDocumentRequest(); - if (object.document != null) { - if (typeof object.document !== "object") - throw TypeError(".google.firestore.v1.UpdateDocumentRequest.document: object expected"); - message.document = $root.google.firestore.v1.Document.fromObject(object.document); - } - if (object.updateMask != null) { - if (typeof object.updateMask !== "object") - throw TypeError(".google.firestore.v1.UpdateDocumentRequest.updateMask: object expected"); - message.updateMask = $root.google.firestore.v1.DocumentMask.fromObject(object.updateMask); - } - if (object.mask != null) { - if (typeof object.mask !== "object") - throw TypeError(".google.firestore.v1.UpdateDocumentRequest.mask: object expected"); - message.mask = $root.google.firestore.v1.DocumentMask.fromObject(object.mask); - } - if (object.currentDocument != null) { - if (typeof object.currentDocument !== "object") - throw TypeError(".google.firestore.v1.UpdateDocumentRequest.currentDocument: object expected"); - message.currentDocument = $root.google.firestore.v1.Precondition.fromObject(object.currentDocument); + var message = new $root.google.firestore.v1.PlanSummary(); + if (object.indexesUsed) { + if (!Array.isArray(object.indexesUsed)) + throw TypeError(".google.firestore.v1.PlanSummary.indexesUsed: array expected"); + message.indexesUsed = []; + for (var i = 0; i < object.indexesUsed.length; ++i) { + if (typeof object.indexesUsed[i] !== "object") + throw TypeError(".google.firestore.v1.PlanSummary.indexesUsed: object expected"); + message.indexesUsed[i] = $root.google.protobuf.Struct.fromObject(object.indexesUsed[i]); + } } return message; }; /** - * Creates a plain object from an UpdateDocumentRequest message. Also converts values to other types if specified. + * Creates a plain object from a PlanSummary message. Also converts values to other types if specified. * @function toObject - * @memberof google.firestore.v1.UpdateDocumentRequest + * @memberof google.firestore.v1.PlanSummary * @static - * @param {google.firestore.v1.UpdateDocumentRequest} message UpdateDocumentRequest + * @param {google.firestore.v1.PlanSummary} message PlanSummary * @param {$protobuf.IConversionOptions} [options] Conversion options * @returns {Object.} Plain object */ - UpdateDocumentRequest.toObject = function toObject(message, options) { + PlanSummary.toObject = function toObject(message, options) { if (!options) options = {}; var object = {}; - if (options.defaults) { - object.document = null; - object.updateMask = null; - object.mask = null; - object.currentDocument = null; + if (options.arrays || options.defaults) + object.indexesUsed = []; + if (message.indexesUsed && message.indexesUsed.length) { + object.indexesUsed = []; + for (var j = 0; j < message.indexesUsed.length; ++j) + object.indexesUsed[j] = $root.google.protobuf.Struct.toObject(message.indexesUsed[j], options); } - if (message.document != null && message.hasOwnProperty("document")) - object.document = $root.google.firestore.v1.Document.toObject(message.document, options); - if (message.updateMask != null && message.hasOwnProperty("updateMask")) - object.updateMask = $root.google.firestore.v1.DocumentMask.toObject(message.updateMask, options); - if (message.mask != null && message.hasOwnProperty("mask")) - object.mask = $root.google.firestore.v1.DocumentMask.toObject(message.mask, options); - if (message.currentDocument != null && message.hasOwnProperty("currentDocument")) - object.currentDocument = $root.google.firestore.v1.Precondition.toObject(message.currentDocument, options); return object; }; /** - * Converts this UpdateDocumentRequest to JSON. + * Converts this PlanSummary to JSON. * @function toJSON - * @memberof google.firestore.v1.UpdateDocumentRequest + * @memberof google.firestore.v1.PlanSummary * @instance * @returns {Object.} JSON object */ - UpdateDocumentRequest.prototype.toJSON = function toJSON() { + PlanSummary.prototype.toJSON = function toJSON() { return this.constructor.toObject(this, $protobuf.util.toJSONOptions); }; /** - * Gets the default type url for UpdateDocumentRequest + * Gets the default type url for PlanSummary * @function getTypeUrl - * @memberof google.firestore.v1.UpdateDocumentRequest + * @memberof google.firestore.v1.PlanSummary * @static * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") * @returns {string} The default type url */ - UpdateDocumentRequest.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + PlanSummary.getTypeUrl = function getTypeUrl(typeUrlPrefix) { if (typeUrlPrefix === undefined) { typeUrlPrefix = "type.googleapis.com"; } - return typeUrlPrefix + "/google.firestore.v1.UpdateDocumentRequest"; + return typeUrlPrefix + "/google.firestore.v1.PlanSummary"; }; - return UpdateDocumentRequest; + return PlanSummary; })(); - v1.DeleteDocumentRequest = (function() { + v1.ExecutionStats = (function() { /** - * Properties of a DeleteDocumentRequest. + * Properties of an ExecutionStats. * @memberof google.firestore.v1 - * @interface IDeleteDocumentRequest - * @property {string|null} [name] DeleteDocumentRequest name - * @property {google.firestore.v1.IPrecondition|null} [currentDocument] DeleteDocumentRequest currentDocument + * @interface IExecutionStats + * @property {number|string|null} [resultsReturned] ExecutionStats resultsReturned + * @property {google.protobuf.IDuration|null} [executionDuration] ExecutionStats executionDuration + * @property {number|string|null} [readOperations] ExecutionStats readOperations + * @property {google.protobuf.IStruct|null} [debugStats] ExecutionStats debugStats */ /** - * Constructs a new DeleteDocumentRequest. + * Constructs a new ExecutionStats. * @memberof google.firestore.v1 - * @classdesc Represents a DeleteDocumentRequest. - * @implements IDeleteDocumentRequest + * @classdesc Represents an ExecutionStats. + * @implements IExecutionStats * @constructor - * @param {google.firestore.v1.IDeleteDocumentRequest=} [properties] Properties to set + * @param {google.firestore.v1.IExecutionStats=} [properties] Properties to set */ - function DeleteDocumentRequest(properties) { + function ExecutionStats(properties) { if (properties) for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) if (properties[keys[i]] != null) @@ -13482,120 +11881,177 @@ } /** - * DeleteDocumentRequest name. - * @member {string} name - * @memberof google.firestore.v1.DeleteDocumentRequest + * ExecutionStats resultsReturned. + * @member {number|string} resultsReturned + * @memberof google.firestore.v1.ExecutionStats * @instance */ - DeleteDocumentRequest.prototype.name = ""; + ExecutionStats.prototype.resultsReturned = $util.Long ? $util.Long.fromBits(0,0,false) : 0; /** - * DeleteDocumentRequest currentDocument. - * @member {google.firestore.v1.IPrecondition|null|undefined} currentDocument - * @memberof google.firestore.v1.DeleteDocumentRequest + * ExecutionStats executionDuration. + * @member {google.protobuf.IDuration|null|undefined} executionDuration + * @memberof google.firestore.v1.ExecutionStats * @instance */ - DeleteDocumentRequest.prototype.currentDocument = null; + ExecutionStats.prototype.executionDuration = null; /** - * Creates a DeleteDocumentRequest message from a plain object. Also converts values to their respective internal types. + * ExecutionStats readOperations. + * @member {number|string} readOperations + * @memberof google.firestore.v1.ExecutionStats + * @instance + */ + ExecutionStats.prototype.readOperations = $util.Long ? $util.Long.fromBits(0,0,false) : 0; + + /** + * ExecutionStats debugStats. + * @member {google.protobuf.IStruct|null|undefined} debugStats + * @memberof google.firestore.v1.ExecutionStats + * @instance + */ + ExecutionStats.prototype.debugStats = null; + + /** + * Creates an ExecutionStats message from a plain object. Also converts values to their respective internal types. * @function fromObject - * @memberof google.firestore.v1.DeleteDocumentRequest + * @memberof google.firestore.v1.ExecutionStats * @static * @param {Object.} object Plain object - * @returns {google.firestore.v1.DeleteDocumentRequest} DeleteDocumentRequest + * @returns {google.firestore.v1.ExecutionStats} ExecutionStats */ - DeleteDocumentRequest.fromObject = function fromObject(object) { - if (object instanceof $root.google.firestore.v1.DeleteDocumentRequest) + ExecutionStats.fromObject = function fromObject(object) { + if (object instanceof $root.google.firestore.v1.ExecutionStats) return object; - var message = new $root.google.firestore.v1.DeleteDocumentRequest(); - if (object.name != null) - message.name = String(object.name); - if (object.currentDocument != null) { - if (typeof object.currentDocument !== "object") - throw TypeError(".google.firestore.v1.DeleteDocumentRequest.currentDocument: object expected"); - message.currentDocument = $root.google.firestore.v1.Precondition.fromObject(object.currentDocument); + var message = new $root.google.firestore.v1.ExecutionStats(); + if (object.resultsReturned != null) + if ($util.Long) + (message.resultsReturned = $util.Long.fromValue(object.resultsReturned)).unsigned = false; + else if (typeof object.resultsReturned === "string") + message.resultsReturned = parseInt(object.resultsReturned, 10); + else if (typeof object.resultsReturned === "number") + message.resultsReturned = object.resultsReturned; + else if (typeof object.resultsReturned === "object") + message.resultsReturned = new $util.LongBits(object.resultsReturned.low >>> 0, object.resultsReturned.high >>> 0).toNumber(); + if (object.executionDuration != null) { + if (typeof object.executionDuration !== "object") + throw TypeError(".google.firestore.v1.ExecutionStats.executionDuration: object expected"); + message.executionDuration = $root.google.protobuf.Duration.fromObject(object.executionDuration); + } + if (object.readOperations != null) + if ($util.Long) + (message.readOperations = $util.Long.fromValue(object.readOperations)).unsigned = false; + else if (typeof object.readOperations === "string") + message.readOperations = parseInt(object.readOperations, 10); + else if (typeof object.readOperations === "number") + message.readOperations = object.readOperations; + else if (typeof object.readOperations === "object") + message.readOperations = new $util.LongBits(object.readOperations.low >>> 0, object.readOperations.high >>> 0).toNumber(); + if (object.debugStats != null) { + if (typeof object.debugStats !== "object") + throw TypeError(".google.firestore.v1.ExecutionStats.debugStats: object expected"); + message.debugStats = $root.google.protobuf.Struct.fromObject(object.debugStats); } return message; }; /** - * Creates a plain object from a DeleteDocumentRequest message. Also converts values to other types if specified. + * Creates a plain object from an ExecutionStats message. Also converts values to other types if specified. * @function toObject - * @memberof google.firestore.v1.DeleteDocumentRequest + * @memberof google.firestore.v1.ExecutionStats * @static - * @param {google.firestore.v1.DeleteDocumentRequest} message DeleteDocumentRequest + * @param {google.firestore.v1.ExecutionStats} message ExecutionStats * @param {$protobuf.IConversionOptions} [options] Conversion options * @returns {Object.} Plain object */ - DeleteDocumentRequest.toObject = function toObject(message, options) { + ExecutionStats.toObject = function toObject(message, options) { if (!options) options = {}; var object = {}; - if (options.defaults) { - object.name = ""; - object.currentDocument = null; + if (options.defaults) { + if ($util.Long) { + var long = new $util.Long(0, 0, false); + object.resultsReturned = options.longs === String ? long.toString() : options.longs === Number ? long.toNumber() : long; + } else + object.resultsReturned = options.longs === String ? "0" : 0; + object.executionDuration = null; + if ($util.Long) { + var long = new $util.Long(0, 0, false); + object.readOperations = options.longs === String ? long.toString() : options.longs === Number ? long.toNumber() : long; + } else + object.readOperations = options.longs === String ? "0" : 0; + object.debugStats = null; } - if (message.name != null && message.hasOwnProperty("name")) - object.name = message.name; - if (message.currentDocument != null && message.hasOwnProperty("currentDocument")) - object.currentDocument = $root.google.firestore.v1.Precondition.toObject(message.currentDocument, options); + if (message.resultsReturned != null && message.hasOwnProperty("resultsReturned")) + if (typeof message.resultsReturned === "number") + object.resultsReturned = options.longs === String ? String(message.resultsReturned) : message.resultsReturned; + else + object.resultsReturned = options.longs === String ? $util.Long.prototype.toString.call(message.resultsReturned) : options.longs === Number ? new $util.LongBits(message.resultsReturned.low >>> 0, message.resultsReturned.high >>> 0).toNumber() : message.resultsReturned; + if (message.executionDuration != null && message.hasOwnProperty("executionDuration")) + object.executionDuration = $root.google.protobuf.Duration.toObject(message.executionDuration, options); + if (message.readOperations != null && message.hasOwnProperty("readOperations")) + if (typeof message.readOperations === "number") + object.readOperations = options.longs === String ? String(message.readOperations) : message.readOperations; + else + object.readOperations = options.longs === String ? $util.Long.prototype.toString.call(message.readOperations) : options.longs === Number ? new $util.LongBits(message.readOperations.low >>> 0, message.readOperations.high >>> 0).toNumber() : message.readOperations; + if (message.debugStats != null && message.hasOwnProperty("debugStats")) + object.debugStats = $root.google.protobuf.Struct.toObject(message.debugStats, options); return object; }; /** - * Converts this DeleteDocumentRequest to JSON. + * Converts this ExecutionStats to JSON. * @function toJSON - * @memberof google.firestore.v1.DeleteDocumentRequest + * @memberof google.firestore.v1.ExecutionStats * @instance * @returns {Object.} JSON object */ - DeleteDocumentRequest.prototype.toJSON = function toJSON() { + ExecutionStats.prototype.toJSON = function toJSON() { return this.constructor.toObject(this, $protobuf.util.toJSONOptions); }; /** - * Gets the default type url for DeleteDocumentRequest + * Gets the default type url for ExecutionStats * @function getTypeUrl - * @memberof google.firestore.v1.DeleteDocumentRequest + * @memberof google.firestore.v1.ExecutionStats * @static * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") * @returns {string} The default type url */ - DeleteDocumentRequest.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + ExecutionStats.getTypeUrl = function getTypeUrl(typeUrlPrefix) { if (typeUrlPrefix === undefined) { typeUrlPrefix = "type.googleapis.com"; } - return typeUrlPrefix + "/google.firestore.v1.DeleteDocumentRequest"; + return typeUrlPrefix + "/google.firestore.v1.ExecutionStats"; }; - return DeleteDocumentRequest; + return ExecutionStats; })(); - v1.BatchGetDocumentsRequest = (function() { + v1.Write = (function() { /** - * Properties of a BatchGetDocumentsRequest. + * Properties of a Write. * @memberof google.firestore.v1 - * @interface IBatchGetDocumentsRequest - * @property {string|null} [database] BatchGetDocumentsRequest database - * @property {Array.|null} [documents] BatchGetDocumentsRequest documents - * @property {google.firestore.v1.IDocumentMask|null} [mask] BatchGetDocumentsRequest mask - * @property {Uint8Array|null} [transaction] BatchGetDocumentsRequest transaction - * @property {google.firestore.v1.ITransactionOptions|null} [newTransaction] BatchGetDocumentsRequest newTransaction - * @property {google.protobuf.ITimestamp|null} [readTime] BatchGetDocumentsRequest readTime + * @interface IWrite + * @property {google.firestore.v1.IDocument|null} [update] Write update + * @property {string|null} ["delete"] Write delete + * @property {google.firestore.v1.IDocumentTransform|null} [transform] Write transform + * @property {google.firestore.v1.IDocumentMask|null} [updateMask] Write updateMask + * @property {Array.|null} [updateTransforms] Write updateTransforms + * @property {google.firestore.v1.IPrecondition|null} [currentDocument] Write currentDocument */ /** - * Constructs a new BatchGetDocumentsRequest. + * Constructs a new Write. * @memberof google.firestore.v1 - * @classdesc Represents a BatchGetDocumentsRequest. - * @implements IBatchGetDocumentsRequest + * @classdesc Represents a Write. + * @implements IWrite * @constructor - * @param {google.firestore.v1.IBatchGetDocumentsRequest=} [properties] Properties to set + * @param {google.firestore.v1.IWrite=} [properties] Properties to set */ - function BatchGetDocumentsRequest(properties) { - this.documents = []; + function Write(properties) { + this.updateTransforms = []; if (properties) for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) if (properties[keys[i]] != null) @@ -13603,207 +12059,209 @@ } /** - * BatchGetDocumentsRequest database. - * @member {string} database - * @memberof google.firestore.v1.BatchGetDocumentsRequest + * Write update. + * @member {google.firestore.v1.IDocument|null|undefined} update + * @memberof google.firestore.v1.Write * @instance */ - BatchGetDocumentsRequest.prototype.database = ""; + Write.prototype.update = null; /** - * BatchGetDocumentsRequest documents. - * @member {Array.} documents - * @memberof google.firestore.v1.BatchGetDocumentsRequest + * Write delete. + * @member {string|null|undefined} delete + * @memberof google.firestore.v1.Write * @instance */ - BatchGetDocumentsRequest.prototype.documents = $util.emptyArray; + Write.prototype["delete"] = null; /** - * BatchGetDocumentsRequest mask. - * @member {google.firestore.v1.IDocumentMask|null|undefined} mask - * @memberof google.firestore.v1.BatchGetDocumentsRequest + * Write transform. + * @member {google.firestore.v1.IDocumentTransform|null|undefined} transform + * @memberof google.firestore.v1.Write * @instance */ - BatchGetDocumentsRequest.prototype.mask = null; + Write.prototype.transform = null; /** - * BatchGetDocumentsRequest transaction. - * @member {Uint8Array|null|undefined} transaction - * @memberof google.firestore.v1.BatchGetDocumentsRequest + * Write updateMask. + * @member {google.firestore.v1.IDocumentMask|null|undefined} updateMask + * @memberof google.firestore.v1.Write * @instance */ - BatchGetDocumentsRequest.prototype.transaction = null; + Write.prototype.updateMask = null; /** - * BatchGetDocumentsRequest newTransaction. - * @member {google.firestore.v1.ITransactionOptions|null|undefined} newTransaction - * @memberof google.firestore.v1.BatchGetDocumentsRequest + * Write updateTransforms. + * @member {Array.} updateTransforms + * @memberof google.firestore.v1.Write * @instance */ - BatchGetDocumentsRequest.prototype.newTransaction = null; + Write.prototype.updateTransforms = $util.emptyArray; /** - * BatchGetDocumentsRequest readTime. - * @member {google.protobuf.ITimestamp|null|undefined} readTime - * @memberof google.firestore.v1.BatchGetDocumentsRequest + * Write currentDocument. + * @member {google.firestore.v1.IPrecondition|null|undefined} currentDocument + * @memberof google.firestore.v1.Write * @instance */ - BatchGetDocumentsRequest.prototype.readTime = null; + Write.prototype.currentDocument = null; // OneOf field names bound to virtual getters and setters var $oneOfFields; /** - * BatchGetDocumentsRequest consistencySelector. - * @member {"transaction"|"newTransaction"|"readTime"|undefined} consistencySelector - * @memberof google.firestore.v1.BatchGetDocumentsRequest + * Write operation. + * @member {"update"|"delete"|"transform"|undefined} operation + * @memberof google.firestore.v1.Write * @instance */ - Object.defineProperty(BatchGetDocumentsRequest.prototype, "consistencySelector", { - get: $util.oneOfGetter($oneOfFields = ["transaction", "newTransaction", "readTime"]), + Object.defineProperty(Write.prototype, "operation", { + get: $util.oneOfGetter($oneOfFields = ["update", "delete", "transform"]), set: $util.oneOfSetter($oneOfFields) }); /** - * Creates a BatchGetDocumentsRequest message from a plain object. Also converts values to their respective internal types. + * Creates a Write message from a plain object. Also converts values to their respective internal types. * @function fromObject - * @memberof google.firestore.v1.BatchGetDocumentsRequest + * @memberof google.firestore.v1.Write * @static * @param {Object.} object Plain object - * @returns {google.firestore.v1.BatchGetDocumentsRequest} BatchGetDocumentsRequest + * @returns {google.firestore.v1.Write} Write */ - BatchGetDocumentsRequest.fromObject = function fromObject(object) { - if (object instanceof $root.google.firestore.v1.BatchGetDocumentsRequest) + Write.fromObject = function fromObject(object) { + if (object instanceof $root.google.firestore.v1.Write) return object; - var message = new $root.google.firestore.v1.BatchGetDocumentsRequest(); - if (object.database != null) - message.database = String(object.database); - if (object.documents) { - if (!Array.isArray(object.documents)) - throw TypeError(".google.firestore.v1.BatchGetDocumentsRequest.documents: array expected"); - message.documents = []; - for (var i = 0; i < object.documents.length; ++i) - message.documents[i] = String(object.documents[i]); + var message = new $root.google.firestore.v1.Write(); + if (object.update != null) { + if (typeof object.update !== "object") + throw TypeError(".google.firestore.v1.Write.update: object expected"); + message.update = $root.google.firestore.v1.Document.fromObject(object.update); } - if (object.mask != null) { - if (typeof object.mask !== "object") - throw TypeError(".google.firestore.v1.BatchGetDocumentsRequest.mask: object expected"); - message.mask = $root.google.firestore.v1.DocumentMask.fromObject(object.mask); + if (object["delete"] != null) + message["delete"] = String(object["delete"]); + if (object.transform != null) { + if (typeof object.transform !== "object") + throw TypeError(".google.firestore.v1.Write.transform: object expected"); + message.transform = $root.google.firestore.v1.DocumentTransform.fromObject(object.transform); } - if (object.transaction != null) - if (typeof object.transaction === "string") - $util.base64.decode(object.transaction, message.transaction = $util.newBuffer($util.base64.length(object.transaction)), 0); - else if (object.transaction.length >= 0) - message.transaction = object.transaction; - if (object.newTransaction != null) { - if (typeof object.newTransaction !== "object") - throw TypeError(".google.firestore.v1.BatchGetDocumentsRequest.newTransaction: object expected"); - message.newTransaction = $root.google.firestore.v1.TransactionOptions.fromObject(object.newTransaction); + if (object.updateMask != null) { + if (typeof object.updateMask !== "object") + throw TypeError(".google.firestore.v1.Write.updateMask: object expected"); + message.updateMask = $root.google.firestore.v1.DocumentMask.fromObject(object.updateMask); } - if (object.readTime != null) { - if (typeof object.readTime !== "object") - throw TypeError(".google.firestore.v1.BatchGetDocumentsRequest.readTime: object expected"); - message.readTime = $root.google.protobuf.Timestamp.fromObject(object.readTime); + if (object.updateTransforms) { + if (!Array.isArray(object.updateTransforms)) + throw TypeError(".google.firestore.v1.Write.updateTransforms: array expected"); + message.updateTransforms = []; + for (var i = 0; i < object.updateTransforms.length; ++i) { + if (typeof object.updateTransforms[i] !== "object") + throw TypeError(".google.firestore.v1.Write.updateTransforms: object expected"); + message.updateTransforms[i] = $root.google.firestore.v1.DocumentTransform.FieldTransform.fromObject(object.updateTransforms[i]); + } + } + if (object.currentDocument != null) { + if (typeof object.currentDocument !== "object") + throw TypeError(".google.firestore.v1.Write.currentDocument: object expected"); + message.currentDocument = $root.google.firestore.v1.Precondition.fromObject(object.currentDocument); } return message; }; /** - * Creates a plain object from a BatchGetDocumentsRequest message. Also converts values to other types if specified. + * Creates a plain object from a Write message. Also converts values to other types if specified. * @function toObject - * @memberof google.firestore.v1.BatchGetDocumentsRequest + * @memberof google.firestore.v1.Write * @static - * @param {google.firestore.v1.BatchGetDocumentsRequest} message BatchGetDocumentsRequest + * @param {google.firestore.v1.Write} message Write * @param {$protobuf.IConversionOptions} [options] Conversion options * @returns {Object.} Plain object */ - BatchGetDocumentsRequest.toObject = function toObject(message, options) { + Write.toObject = function toObject(message, options) { if (!options) options = {}; var object = {}; if (options.arrays || options.defaults) - object.documents = []; + object.updateTransforms = []; if (options.defaults) { - object.database = ""; - object.mask = null; - } - if (message.database != null && message.hasOwnProperty("database")) - object.database = message.database; - if (message.documents && message.documents.length) { - object.documents = []; - for (var j = 0; j < message.documents.length; ++j) - object.documents[j] = message.documents[j]; + object.updateMask = null; + object.currentDocument = null; } - if (message.mask != null && message.hasOwnProperty("mask")) - object.mask = $root.google.firestore.v1.DocumentMask.toObject(message.mask, options); - if (message.transaction != null && message.hasOwnProperty("transaction")) { - object.transaction = options.bytes === String ? $util.base64.encode(message.transaction, 0, message.transaction.length) : options.bytes === Array ? Array.prototype.slice.call(message.transaction) : message.transaction; + if (message.update != null && message.hasOwnProperty("update")) { + object.update = $root.google.firestore.v1.Document.toObject(message.update, options); if (options.oneofs) - object.consistencySelector = "transaction"; + object.operation = "update"; } - if (message.newTransaction != null && message.hasOwnProperty("newTransaction")) { - object.newTransaction = $root.google.firestore.v1.TransactionOptions.toObject(message.newTransaction, options); + if (message["delete"] != null && message.hasOwnProperty("delete")) { + object["delete"] = message["delete"]; if (options.oneofs) - object.consistencySelector = "newTransaction"; + object.operation = "delete"; } - if (message.readTime != null && message.hasOwnProperty("readTime")) { - object.readTime = $root.google.protobuf.Timestamp.toObject(message.readTime, options); + if (message.updateMask != null && message.hasOwnProperty("updateMask")) + object.updateMask = $root.google.firestore.v1.DocumentMask.toObject(message.updateMask, options); + if (message.currentDocument != null && message.hasOwnProperty("currentDocument")) + object.currentDocument = $root.google.firestore.v1.Precondition.toObject(message.currentDocument, options); + if (message.transform != null && message.hasOwnProperty("transform")) { + object.transform = $root.google.firestore.v1.DocumentTransform.toObject(message.transform, options); if (options.oneofs) - object.consistencySelector = "readTime"; + object.operation = "transform"; + } + if (message.updateTransforms && message.updateTransforms.length) { + object.updateTransforms = []; + for (var j = 0; j < message.updateTransforms.length; ++j) + object.updateTransforms[j] = $root.google.firestore.v1.DocumentTransform.FieldTransform.toObject(message.updateTransforms[j], options); } return object; }; /** - * Converts this BatchGetDocumentsRequest to JSON. + * Converts this Write to JSON. * @function toJSON - * @memberof google.firestore.v1.BatchGetDocumentsRequest + * @memberof google.firestore.v1.Write * @instance * @returns {Object.} JSON object */ - BatchGetDocumentsRequest.prototype.toJSON = function toJSON() { + Write.prototype.toJSON = function toJSON() { return this.constructor.toObject(this, $protobuf.util.toJSONOptions); }; /** - * Gets the default type url for BatchGetDocumentsRequest + * Gets the default type url for Write * @function getTypeUrl - * @memberof google.firestore.v1.BatchGetDocumentsRequest + * @memberof google.firestore.v1.Write * @static * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") * @returns {string} The default type url */ - BatchGetDocumentsRequest.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + Write.getTypeUrl = function getTypeUrl(typeUrlPrefix) { if (typeUrlPrefix === undefined) { typeUrlPrefix = "type.googleapis.com"; } - return typeUrlPrefix + "/google.firestore.v1.BatchGetDocumentsRequest"; + return typeUrlPrefix + "/google.firestore.v1.Write"; }; - return BatchGetDocumentsRequest; + return Write; })(); - v1.BatchGetDocumentsResponse = (function() { + v1.DocumentTransform = (function() { /** - * Properties of a BatchGetDocumentsResponse. + * Properties of a DocumentTransform. * @memberof google.firestore.v1 - * @interface IBatchGetDocumentsResponse - * @property {google.firestore.v1.IDocument|null} [found] BatchGetDocumentsResponse found - * @property {string|null} [missing] BatchGetDocumentsResponse missing - * @property {Uint8Array|null} [transaction] BatchGetDocumentsResponse transaction - * @property {google.protobuf.ITimestamp|null} [readTime] BatchGetDocumentsResponse readTime + * @interface IDocumentTransform + * @property {string|null} [document] DocumentTransform document + * @property {Array.|null} [fieldTransforms] DocumentTransform fieldTransforms */ /** - * Constructs a new BatchGetDocumentsResponse. + * Constructs a new DocumentTransform. * @memberof google.firestore.v1 - * @classdesc Represents a BatchGetDocumentsResponse. - * @implements IBatchGetDocumentsResponse + * @classdesc Represents a DocumentTransform. + * @implements IDocumentTransform * @constructor - * @param {google.firestore.v1.IBatchGetDocumentsResponse=} [properties] Properties to set + * @param {google.firestore.v1.IDocumentTransform=} [properties] Properties to set */ - function BatchGetDocumentsResponse(properties) { + function DocumentTransform(properties) { + this.fieldTransforms = []; if (properties) for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) if (properties[keys[i]] != null) @@ -13811,171 +12269,375 @@ } /** - * BatchGetDocumentsResponse found. - * @member {google.firestore.v1.IDocument|null|undefined} found - * @memberof google.firestore.v1.BatchGetDocumentsResponse + * DocumentTransform document. + * @member {string} document + * @memberof google.firestore.v1.DocumentTransform * @instance */ - BatchGetDocumentsResponse.prototype.found = null; + DocumentTransform.prototype.document = ""; /** - * BatchGetDocumentsResponse missing. - * @member {string|null|undefined} missing - * @memberof google.firestore.v1.BatchGetDocumentsResponse + * DocumentTransform fieldTransforms. + * @member {Array.} fieldTransforms + * @memberof google.firestore.v1.DocumentTransform * @instance */ - BatchGetDocumentsResponse.prototype.missing = null; + DocumentTransform.prototype.fieldTransforms = $util.emptyArray; /** - * BatchGetDocumentsResponse transaction. - * @member {Uint8Array} transaction - * @memberof google.firestore.v1.BatchGetDocumentsResponse - * @instance + * Creates a DocumentTransform message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.firestore.v1.DocumentTransform + * @static + * @param {Object.} object Plain object + * @returns {google.firestore.v1.DocumentTransform} DocumentTransform */ - BatchGetDocumentsResponse.prototype.transaction = $util.newBuffer([]); + DocumentTransform.fromObject = function fromObject(object) { + if (object instanceof $root.google.firestore.v1.DocumentTransform) + return object; + var message = new $root.google.firestore.v1.DocumentTransform(); + if (object.document != null) + message.document = String(object.document); + if (object.fieldTransforms) { + if (!Array.isArray(object.fieldTransforms)) + throw TypeError(".google.firestore.v1.DocumentTransform.fieldTransforms: array expected"); + message.fieldTransforms = []; + for (var i = 0; i < object.fieldTransforms.length; ++i) { + if (typeof object.fieldTransforms[i] !== "object") + throw TypeError(".google.firestore.v1.DocumentTransform.fieldTransforms: object expected"); + message.fieldTransforms[i] = $root.google.firestore.v1.DocumentTransform.FieldTransform.fromObject(object.fieldTransforms[i]); + } + } + return message; + }; /** - * BatchGetDocumentsResponse readTime. - * @member {google.protobuf.ITimestamp|null|undefined} readTime - * @memberof google.firestore.v1.BatchGetDocumentsResponse - * @instance + * Creates a plain object from a DocumentTransform message. Also converts values to other types if specified. + * @function toObject + * @memberof google.firestore.v1.DocumentTransform + * @static + * @param {google.firestore.v1.DocumentTransform} message DocumentTransform + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object */ - BatchGetDocumentsResponse.prototype.readTime = null; - - // OneOf field names bound to virtual getters and setters - var $oneOfFields; + DocumentTransform.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.arrays || options.defaults) + object.fieldTransforms = []; + if (options.defaults) + object.document = ""; + if (message.document != null && message.hasOwnProperty("document")) + object.document = message.document; + if (message.fieldTransforms && message.fieldTransforms.length) { + object.fieldTransforms = []; + for (var j = 0; j < message.fieldTransforms.length; ++j) + object.fieldTransforms[j] = $root.google.firestore.v1.DocumentTransform.FieldTransform.toObject(message.fieldTransforms[j], options); + } + return object; + }; /** - * BatchGetDocumentsResponse result. - * @member {"found"|"missing"|undefined} result - * @memberof google.firestore.v1.BatchGetDocumentsResponse + * Converts this DocumentTransform to JSON. + * @function toJSON + * @memberof google.firestore.v1.DocumentTransform * @instance + * @returns {Object.} JSON object */ - Object.defineProperty(BatchGetDocumentsResponse.prototype, "result", { - get: $util.oneOfGetter($oneOfFields = ["found", "missing"]), - set: $util.oneOfSetter($oneOfFields) - }); + DocumentTransform.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + + /** + * Gets the default type url for DocumentTransform + * @function getTypeUrl + * @memberof google.firestore.v1.DocumentTransform + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + DocumentTransform.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.firestore.v1.DocumentTransform"; + }; + + DocumentTransform.FieldTransform = (function() { + + /** + * Properties of a FieldTransform. + * @memberof google.firestore.v1.DocumentTransform + * @interface IFieldTransform + * @property {string|null} [fieldPath] FieldTransform fieldPath + * @property {google.firestore.v1.DocumentTransform.FieldTransform.ServerValue|null} [setToServerValue] FieldTransform setToServerValue + * @property {google.firestore.v1.IValue|null} [increment] FieldTransform increment + * @property {google.firestore.v1.IValue|null} [maximum] FieldTransform maximum + * @property {google.firestore.v1.IValue|null} [minimum] FieldTransform minimum + * @property {google.firestore.v1.IArrayValue|null} [appendMissingElements] FieldTransform appendMissingElements + * @property {google.firestore.v1.IArrayValue|null} [removeAllFromArray] FieldTransform removeAllFromArray + */ + + /** + * Constructs a new FieldTransform. + * @memberof google.firestore.v1.DocumentTransform + * @classdesc Represents a FieldTransform. + * @implements IFieldTransform + * @constructor + * @param {google.firestore.v1.DocumentTransform.IFieldTransform=} [properties] Properties to set + */ + function FieldTransform(properties) { + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } + + /** + * FieldTransform fieldPath. + * @member {string} fieldPath + * @memberof google.firestore.v1.DocumentTransform.FieldTransform + * @instance + */ + FieldTransform.prototype.fieldPath = ""; + + /** + * FieldTransform setToServerValue. + * @member {google.firestore.v1.DocumentTransform.FieldTransform.ServerValue|null|undefined} setToServerValue + * @memberof google.firestore.v1.DocumentTransform.FieldTransform + * @instance + */ + FieldTransform.prototype.setToServerValue = null; + + /** + * FieldTransform increment. + * @member {google.firestore.v1.IValue|null|undefined} increment + * @memberof google.firestore.v1.DocumentTransform.FieldTransform + * @instance + */ + FieldTransform.prototype.increment = null; + + /** + * FieldTransform maximum. + * @member {google.firestore.v1.IValue|null|undefined} maximum + * @memberof google.firestore.v1.DocumentTransform.FieldTransform + * @instance + */ + FieldTransform.prototype.maximum = null; + + /** + * FieldTransform minimum. + * @member {google.firestore.v1.IValue|null|undefined} minimum + * @memberof google.firestore.v1.DocumentTransform.FieldTransform + * @instance + */ + FieldTransform.prototype.minimum = null; + + /** + * FieldTransform appendMissingElements. + * @member {google.firestore.v1.IArrayValue|null|undefined} appendMissingElements + * @memberof google.firestore.v1.DocumentTransform.FieldTransform + * @instance + */ + FieldTransform.prototype.appendMissingElements = null; + + /** + * FieldTransform removeAllFromArray. + * @member {google.firestore.v1.IArrayValue|null|undefined} removeAllFromArray + * @memberof google.firestore.v1.DocumentTransform.FieldTransform + * @instance + */ + FieldTransform.prototype.removeAllFromArray = null; + + // OneOf field names bound to virtual getters and setters + var $oneOfFields; + + /** + * FieldTransform transformType. + * @member {"setToServerValue"|"increment"|"maximum"|"minimum"|"appendMissingElements"|"removeAllFromArray"|undefined} transformType + * @memberof google.firestore.v1.DocumentTransform.FieldTransform + * @instance + */ + Object.defineProperty(FieldTransform.prototype, "transformType", { + get: $util.oneOfGetter($oneOfFields = ["setToServerValue", "increment", "maximum", "minimum", "appendMissingElements", "removeAllFromArray"]), + set: $util.oneOfSetter($oneOfFields) + }); + + /** + * Creates a FieldTransform message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.firestore.v1.DocumentTransform.FieldTransform + * @static + * @param {Object.} object Plain object + * @returns {google.firestore.v1.DocumentTransform.FieldTransform} FieldTransform + */ + FieldTransform.fromObject = function fromObject(object) { + if (object instanceof $root.google.firestore.v1.DocumentTransform.FieldTransform) + return object; + var message = new $root.google.firestore.v1.DocumentTransform.FieldTransform(); + if (object.fieldPath != null) + message.fieldPath = String(object.fieldPath); + switch (object.setToServerValue) { + default: + if (typeof object.setToServerValue === "number") { + message.setToServerValue = object.setToServerValue; + break; + } + break; + case "SERVER_VALUE_UNSPECIFIED": + case 0: + message.setToServerValue = 0; + break; + case "REQUEST_TIME": + case 1: + message.setToServerValue = 1; + break; + } + if (object.increment != null) { + if (typeof object.increment !== "object") + throw TypeError(".google.firestore.v1.DocumentTransform.FieldTransform.increment: object expected"); + message.increment = $root.google.firestore.v1.Value.fromObject(object.increment); + } + if (object.maximum != null) { + if (typeof object.maximum !== "object") + throw TypeError(".google.firestore.v1.DocumentTransform.FieldTransform.maximum: object expected"); + message.maximum = $root.google.firestore.v1.Value.fromObject(object.maximum); + } + if (object.minimum != null) { + if (typeof object.minimum !== "object") + throw TypeError(".google.firestore.v1.DocumentTransform.FieldTransform.minimum: object expected"); + message.minimum = $root.google.firestore.v1.Value.fromObject(object.minimum); + } + if (object.appendMissingElements != null) { + if (typeof object.appendMissingElements !== "object") + throw TypeError(".google.firestore.v1.DocumentTransform.FieldTransform.appendMissingElements: object expected"); + message.appendMissingElements = $root.google.firestore.v1.ArrayValue.fromObject(object.appendMissingElements); + } + if (object.removeAllFromArray != null) { + if (typeof object.removeAllFromArray !== "object") + throw TypeError(".google.firestore.v1.DocumentTransform.FieldTransform.removeAllFromArray: object expected"); + message.removeAllFromArray = $root.google.firestore.v1.ArrayValue.fromObject(object.removeAllFromArray); + } + return message; + }; - /** - * Creates a BatchGetDocumentsResponse message from a plain object. Also converts values to their respective internal types. - * @function fromObject - * @memberof google.firestore.v1.BatchGetDocumentsResponse - * @static - * @param {Object.} object Plain object - * @returns {google.firestore.v1.BatchGetDocumentsResponse} BatchGetDocumentsResponse - */ - BatchGetDocumentsResponse.fromObject = function fromObject(object) { - if (object instanceof $root.google.firestore.v1.BatchGetDocumentsResponse) + /** + * Creates a plain object from a FieldTransform message. Also converts values to other types if specified. + * @function toObject + * @memberof google.firestore.v1.DocumentTransform.FieldTransform + * @static + * @param {google.firestore.v1.DocumentTransform.FieldTransform} message FieldTransform + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + FieldTransform.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.defaults) + object.fieldPath = ""; + if (message.fieldPath != null && message.hasOwnProperty("fieldPath")) + object.fieldPath = message.fieldPath; + if (message.setToServerValue != null && message.hasOwnProperty("setToServerValue")) { + object.setToServerValue = options.enums === String ? $root.google.firestore.v1.DocumentTransform.FieldTransform.ServerValue[message.setToServerValue] === undefined ? message.setToServerValue : $root.google.firestore.v1.DocumentTransform.FieldTransform.ServerValue[message.setToServerValue] : message.setToServerValue; + if (options.oneofs) + object.transformType = "setToServerValue"; + } + if (message.increment != null && message.hasOwnProperty("increment")) { + object.increment = $root.google.firestore.v1.Value.toObject(message.increment, options); + if (options.oneofs) + object.transformType = "increment"; + } + if (message.maximum != null && message.hasOwnProperty("maximum")) { + object.maximum = $root.google.firestore.v1.Value.toObject(message.maximum, options); + if (options.oneofs) + object.transformType = "maximum"; + } + if (message.minimum != null && message.hasOwnProperty("minimum")) { + object.minimum = $root.google.firestore.v1.Value.toObject(message.minimum, options); + if (options.oneofs) + object.transformType = "minimum"; + } + if (message.appendMissingElements != null && message.hasOwnProperty("appendMissingElements")) { + object.appendMissingElements = $root.google.firestore.v1.ArrayValue.toObject(message.appendMissingElements, options); + if (options.oneofs) + object.transformType = "appendMissingElements"; + } + if (message.removeAllFromArray != null && message.hasOwnProperty("removeAllFromArray")) { + object.removeAllFromArray = $root.google.firestore.v1.ArrayValue.toObject(message.removeAllFromArray, options); + if (options.oneofs) + object.transformType = "removeAllFromArray"; + } return object; - var message = new $root.google.firestore.v1.BatchGetDocumentsResponse(); - if (object.found != null) { - if (typeof object.found !== "object") - throw TypeError(".google.firestore.v1.BatchGetDocumentsResponse.found: object expected"); - message.found = $root.google.firestore.v1.Document.fromObject(object.found); - } - if (object.missing != null) - message.missing = String(object.missing); - if (object.transaction != null) - if (typeof object.transaction === "string") - $util.base64.decode(object.transaction, message.transaction = $util.newBuffer($util.base64.length(object.transaction)), 0); - else if (object.transaction.length >= 0) - message.transaction = object.transaction; - if (object.readTime != null) { - if (typeof object.readTime !== "object") - throw TypeError(".google.firestore.v1.BatchGetDocumentsResponse.readTime: object expected"); - message.readTime = $root.google.protobuf.Timestamp.fromObject(object.readTime); - } - return message; - }; + }; - /** - * Creates a plain object from a BatchGetDocumentsResponse message. Also converts values to other types if specified. - * @function toObject - * @memberof google.firestore.v1.BatchGetDocumentsResponse - * @static - * @param {google.firestore.v1.BatchGetDocumentsResponse} message BatchGetDocumentsResponse - * @param {$protobuf.IConversionOptions} [options] Conversion options - * @returns {Object.} Plain object - */ - BatchGetDocumentsResponse.toObject = function toObject(message, options) { - if (!options) - options = {}; - var object = {}; - if (options.defaults) { - if (options.bytes === String) - object.transaction = ""; - else { - object.transaction = []; - if (options.bytes !== Array) - object.transaction = $util.newBuffer(object.transaction); + /** + * Converts this FieldTransform to JSON. + * @function toJSON + * @memberof google.firestore.v1.DocumentTransform.FieldTransform + * @instance + * @returns {Object.} JSON object + */ + FieldTransform.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + + /** + * Gets the default type url for FieldTransform + * @function getTypeUrl + * @memberof google.firestore.v1.DocumentTransform.FieldTransform + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + FieldTransform.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; } - object.readTime = null; - } - if (message.found != null && message.hasOwnProperty("found")) { - object.found = $root.google.firestore.v1.Document.toObject(message.found, options); - if (options.oneofs) - object.result = "found"; - } - if (message.missing != null && message.hasOwnProperty("missing")) { - object.missing = message.missing; - if (options.oneofs) - object.result = "missing"; - } - if (message.transaction != null && message.hasOwnProperty("transaction")) - object.transaction = options.bytes === String ? $util.base64.encode(message.transaction, 0, message.transaction.length) : options.bytes === Array ? Array.prototype.slice.call(message.transaction) : message.transaction; - if (message.readTime != null && message.hasOwnProperty("readTime")) - object.readTime = $root.google.protobuf.Timestamp.toObject(message.readTime, options); - return object; - }; + return typeUrlPrefix + "/google.firestore.v1.DocumentTransform.FieldTransform"; + }; - /** - * Converts this BatchGetDocumentsResponse to JSON. - * @function toJSON - * @memberof google.firestore.v1.BatchGetDocumentsResponse - * @instance - * @returns {Object.} JSON object - */ - BatchGetDocumentsResponse.prototype.toJSON = function toJSON() { - return this.constructor.toObject(this, $protobuf.util.toJSONOptions); - }; + /** + * ServerValue enum. + * @name google.firestore.v1.DocumentTransform.FieldTransform.ServerValue + * @enum {string} + * @property {string} SERVER_VALUE_UNSPECIFIED=SERVER_VALUE_UNSPECIFIED SERVER_VALUE_UNSPECIFIED value + * @property {string} REQUEST_TIME=REQUEST_TIME REQUEST_TIME value + */ + FieldTransform.ServerValue = (function() { + var valuesById = {}, values = Object.create(valuesById); + values[valuesById[0] = "SERVER_VALUE_UNSPECIFIED"] = "SERVER_VALUE_UNSPECIFIED"; + values[valuesById[1] = "REQUEST_TIME"] = "REQUEST_TIME"; + return values; + })(); - /** - * Gets the default type url for BatchGetDocumentsResponse - * @function getTypeUrl - * @memberof google.firestore.v1.BatchGetDocumentsResponse - * @static - * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") - * @returns {string} The default type url - */ - BatchGetDocumentsResponse.getTypeUrl = function getTypeUrl(typeUrlPrefix) { - if (typeUrlPrefix === undefined) { - typeUrlPrefix = "type.googleapis.com"; - } - return typeUrlPrefix + "/google.firestore.v1.BatchGetDocumentsResponse"; - }; + return FieldTransform; + })(); - return BatchGetDocumentsResponse; + return DocumentTransform; })(); - v1.BeginTransactionRequest = (function() { + v1.WriteResult = (function() { /** - * Properties of a BeginTransactionRequest. + * Properties of a WriteResult. * @memberof google.firestore.v1 - * @interface IBeginTransactionRequest - * @property {string|null} [database] BeginTransactionRequest database - * @property {google.firestore.v1.ITransactionOptions|null} [options] BeginTransactionRequest options + * @interface IWriteResult + * @property {google.protobuf.ITimestamp|null} [updateTime] WriteResult updateTime + * @property {Array.|null} [transformResults] WriteResult transformResults */ /** - * Constructs a new BeginTransactionRequest. + * Constructs a new WriteResult. * @memberof google.firestore.v1 - * @classdesc Represents a BeginTransactionRequest. - * @implements IBeginTransactionRequest + * @classdesc Represents a WriteResult. + * @implements IWriteResult * @constructor - * @param {google.firestore.v1.IBeginTransactionRequest=} [properties] Properties to set + * @param {google.firestore.v1.IWriteResult=} [properties] Properties to set */ - function BeginTransactionRequest(properties) { + function WriteResult(properties) { + this.transformResults = []; if (properties) for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) if (properties[keys[i]] != null) @@ -13983,114 +12645,129 @@ } /** - * BeginTransactionRequest database. - * @member {string} database - * @memberof google.firestore.v1.BeginTransactionRequest + * WriteResult updateTime. + * @member {google.protobuf.ITimestamp|null|undefined} updateTime + * @memberof google.firestore.v1.WriteResult * @instance */ - BeginTransactionRequest.prototype.database = ""; + WriteResult.prototype.updateTime = null; /** - * BeginTransactionRequest options. - * @member {google.firestore.v1.ITransactionOptions|null|undefined} options - * @memberof google.firestore.v1.BeginTransactionRequest + * WriteResult transformResults. + * @member {Array.} transformResults + * @memberof google.firestore.v1.WriteResult * @instance */ - BeginTransactionRequest.prototype.options = null; + WriteResult.prototype.transformResults = $util.emptyArray; /** - * Creates a BeginTransactionRequest message from a plain object. Also converts values to their respective internal types. + * Creates a WriteResult message from a plain object. Also converts values to their respective internal types. * @function fromObject - * @memberof google.firestore.v1.BeginTransactionRequest + * @memberof google.firestore.v1.WriteResult * @static * @param {Object.} object Plain object - * @returns {google.firestore.v1.BeginTransactionRequest} BeginTransactionRequest + * @returns {google.firestore.v1.WriteResult} WriteResult */ - BeginTransactionRequest.fromObject = function fromObject(object) { - if (object instanceof $root.google.firestore.v1.BeginTransactionRequest) + WriteResult.fromObject = function fromObject(object) { + if (object instanceof $root.google.firestore.v1.WriteResult) return object; - var message = new $root.google.firestore.v1.BeginTransactionRequest(); - if (object.database != null) - message.database = String(object.database); - if (object.options != null) { - if (typeof object.options !== "object") - throw TypeError(".google.firestore.v1.BeginTransactionRequest.options: object expected"); - message.options = $root.google.firestore.v1.TransactionOptions.fromObject(object.options); + var message = new $root.google.firestore.v1.WriteResult(); + if (object.updateTime != null) { + if (typeof object.updateTime !== "object") + throw TypeError(".google.firestore.v1.WriteResult.updateTime: object expected"); + message.updateTime = $root.google.protobuf.Timestamp.fromObject(object.updateTime); + } + if (object.transformResults) { + if (!Array.isArray(object.transformResults)) + throw TypeError(".google.firestore.v1.WriteResult.transformResults: array expected"); + message.transformResults = []; + for (var i = 0; i < object.transformResults.length; ++i) { + if (typeof object.transformResults[i] !== "object") + throw TypeError(".google.firestore.v1.WriteResult.transformResults: object expected"); + message.transformResults[i] = $root.google.firestore.v1.Value.fromObject(object.transformResults[i]); + } } return message; }; /** - * Creates a plain object from a BeginTransactionRequest message. Also converts values to other types if specified. + * Creates a plain object from a WriteResult message. Also converts values to other types if specified. * @function toObject - * @memberof google.firestore.v1.BeginTransactionRequest + * @memberof google.firestore.v1.WriteResult * @static - * @param {google.firestore.v1.BeginTransactionRequest} message BeginTransactionRequest + * @param {google.firestore.v1.WriteResult} message WriteResult * @param {$protobuf.IConversionOptions} [options] Conversion options * @returns {Object.} Plain object */ - BeginTransactionRequest.toObject = function toObject(message, options) { + WriteResult.toObject = function toObject(message, options) { if (!options) options = {}; var object = {}; - if (options.defaults) { - object.database = ""; - object.options = null; + if (options.arrays || options.defaults) + object.transformResults = []; + if (options.defaults) + object.updateTime = null; + if (message.updateTime != null && message.hasOwnProperty("updateTime")) + object.updateTime = $root.google.protobuf.Timestamp.toObject(message.updateTime, options); + if (message.transformResults && message.transformResults.length) { + object.transformResults = []; + for (var j = 0; j < message.transformResults.length; ++j) + object.transformResults[j] = $root.google.firestore.v1.Value.toObject(message.transformResults[j], options); } - if (message.database != null && message.hasOwnProperty("database")) - object.database = message.database; - if (message.options != null && message.hasOwnProperty("options")) - object.options = $root.google.firestore.v1.TransactionOptions.toObject(message.options, options); return object; }; /** - * Converts this BeginTransactionRequest to JSON. + * Converts this WriteResult to JSON. * @function toJSON - * @memberof google.firestore.v1.BeginTransactionRequest + * @memberof google.firestore.v1.WriteResult * @instance * @returns {Object.} JSON object */ - BeginTransactionRequest.prototype.toJSON = function toJSON() { + WriteResult.prototype.toJSON = function toJSON() { return this.constructor.toObject(this, $protobuf.util.toJSONOptions); }; /** - * Gets the default type url for BeginTransactionRequest + * Gets the default type url for WriteResult * @function getTypeUrl - * @memberof google.firestore.v1.BeginTransactionRequest + * @memberof google.firestore.v1.WriteResult * @static * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") * @returns {string} The default type url */ - BeginTransactionRequest.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + WriteResult.getTypeUrl = function getTypeUrl(typeUrlPrefix) { if (typeUrlPrefix === undefined) { typeUrlPrefix = "type.googleapis.com"; } - return typeUrlPrefix + "/google.firestore.v1.BeginTransactionRequest"; + return typeUrlPrefix + "/google.firestore.v1.WriteResult"; }; - return BeginTransactionRequest; + return WriteResult; })(); - v1.BeginTransactionResponse = (function() { + v1.DocumentChange = (function() { /** - * Properties of a BeginTransactionResponse. + * Properties of a DocumentChange. * @memberof google.firestore.v1 - * @interface IBeginTransactionResponse - * @property {Uint8Array|null} [transaction] BeginTransactionResponse transaction + * @interface IDocumentChange + * @property {google.firestore.v1.IDocument|null} [document] DocumentChange document + * @property {Array.|null} [targetIds] DocumentChange targetIds + * @property {Array.|null} [removedTargetIds] DocumentChange removedTargetIds */ /** - * Constructs a new BeginTransactionResponse. + * Constructs a new DocumentChange. * @memberof google.firestore.v1 - * @classdesc Represents a BeginTransactionResponse. - * @implements IBeginTransactionResponse + * @classdesc Represents a DocumentChange. + * @implements IDocumentChange * @constructor - * @param {google.firestore.v1.IBeginTransactionResponse=} [properties] Properties to set + * @param {google.firestore.v1.IDocumentChange=} [properties] Properties to set */ - function BeginTransactionResponse(properties) { + function DocumentChange(properties) { + this.targetIds = []; + this.removedTargetIds = []; if (properties) for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) if (properties[keys[i]] != null) @@ -14098,109 +12775,147 @@ } /** - * BeginTransactionResponse transaction. - * @member {Uint8Array} transaction - * @memberof google.firestore.v1.BeginTransactionResponse + * DocumentChange document. + * @member {google.firestore.v1.IDocument|null|undefined} document + * @memberof google.firestore.v1.DocumentChange * @instance */ - BeginTransactionResponse.prototype.transaction = $util.newBuffer([]); + DocumentChange.prototype.document = null; /** - * Creates a BeginTransactionResponse message from a plain object. Also converts values to their respective internal types. + * DocumentChange targetIds. + * @member {Array.} targetIds + * @memberof google.firestore.v1.DocumentChange + * @instance + */ + DocumentChange.prototype.targetIds = $util.emptyArray; + + /** + * DocumentChange removedTargetIds. + * @member {Array.} removedTargetIds + * @memberof google.firestore.v1.DocumentChange + * @instance + */ + DocumentChange.prototype.removedTargetIds = $util.emptyArray; + + /** + * Creates a DocumentChange message from a plain object. Also converts values to their respective internal types. * @function fromObject - * @memberof google.firestore.v1.BeginTransactionResponse + * @memberof google.firestore.v1.DocumentChange * @static * @param {Object.} object Plain object - * @returns {google.firestore.v1.BeginTransactionResponse} BeginTransactionResponse + * @returns {google.firestore.v1.DocumentChange} DocumentChange */ - BeginTransactionResponse.fromObject = function fromObject(object) { - if (object instanceof $root.google.firestore.v1.BeginTransactionResponse) + DocumentChange.fromObject = function fromObject(object) { + if (object instanceof $root.google.firestore.v1.DocumentChange) return object; - var message = new $root.google.firestore.v1.BeginTransactionResponse(); - if (object.transaction != null) - if (typeof object.transaction === "string") - $util.base64.decode(object.transaction, message.transaction = $util.newBuffer($util.base64.length(object.transaction)), 0); - else if (object.transaction.length >= 0) - message.transaction = object.transaction; + var message = new $root.google.firestore.v1.DocumentChange(); + if (object.document != null) { + if (typeof object.document !== "object") + throw TypeError(".google.firestore.v1.DocumentChange.document: object expected"); + message.document = $root.google.firestore.v1.Document.fromObject(object.document); + } + if (object.targetIds) { + if (!Array.isArray(object.targetIds)) + throw TypeError(".google.firestore.v1.DocumentChange.targetIds: array expected"); + message.targetIds = []; + for (var i = 0; i < object.targetIds.length; ++i) + message.targetIds[i] = object.targetIds[i] | 0; + } + if (object.removedTargetIds) { + if (!Array.isArray(object.removedTargetIds)) + throw TypeError(".google.firestore.v1.DocumentChange.removedTargetIds: array expected"); + message.removedTargetIds = []; + for (var i = 0; i < object.removedTargetIds.length; ++i) + message.removedTargetIds[i] = object.removedTargetIds[i] | 0; + } return message; }; /** - * Creates a plain object from a BeginTransactionResponse message. Also converts values to other types if specified. + * Creates a plain object from a DocumentChange message. Also converts values to other types if specified. * @function toObject - * @memberof google.firestore.v1.BeginTransactionResponse + * @memberof google.firestore.v1.DocumentChange * @static - * @param {google.firestore.v1.BeginTransactionResponse} message BeginTransactionResponse + * @param {google.firestore.v1.DocumentChange} message DocumentChange * @param {$protobuf.IConversionOptions} [options] Conversion options * @returns {Object.} Plain object */ - BeginTransactionResponse.toObject = function toObject(message, options) { + DocumentChange.toObject = function toObject(message, options) { if (!options) options = {}; var object = {}; + if (options.arrays || options.defaults) { + object.targetIds = []; + object.removedTargetIds = []; + } if (options.defaults) - if (options.bytes === String) - object.transaction = ""; - else { - object.transaction = []; - if (options.bytes !== Array) - object.transaction = $util.newBuffer(object.transaction); - } - if (message.transaction != null && message.hasOwnProperty("transaction")) - object.transaction = options.bytes === String ? $util.base64.encode(message.transaction, 0, message.transaction.length) : options.bytes === Array ? Array.prototype.slice.call(message.transaction) : message.transaction; + object.document = null; + if (message.document != null && message.hasOwnProperty("document")) + object.document = $root.google.firestore.v1.Document.toObject(message.document, options); + if (message.targetIds && message.targetIds.length) { + object.targetIds = []; + for (var j = 0; j < message.targetIds.length; ++j) + object.targetIds[j] = message.targetIds[j]; + } + if (message.removedTargetIds && message.removedTargetIds.length) { + object.removedTargetIds = []; + for (var j = 0; j < message.removedTargetIds.length; ++j) + object.removedTargetIds[j] = message.removedTargetIds[j]; + } return object; }; /** - * Converts this BeginTransactionResponse to JSON. + * Converts this DocumentChange to JSON. * @function toJSON - * @memberof google.firestore.v1.BeginTransactionResponse + * @memberof google.firestore.v1.DocumentChange * @instance * @returns {Object.} JSON object */ - BeginTransactionResponse.prototype.toJSON = function toJSON() { + DocumentChange.prototype.toJSON = function toJSON() { return this.constructor.toObject(this, $protobuf.util.toJSONOptions); }; /** - * Gets the default type url for BeginTransactionResponse + * Gets the default type url for DocumentChange * @function getTypeUrl - * @memberof google.firestore.v1.BeginTransactionResponse + * @memberof google.firestore.v1.DocumentChange * @static * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") * @returns {string} The default type url */ - BeginTransactionResponse.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + DocumentChange.getTypeUrl = function getTypeUrl(typeUrlPrefix) { if (typeUrlPrefix === undefined) { typeUrlPrefix = "type.googleapis.com"; } - return typeUrlPrefix + "/google.firestore.v1.BeginTransactionResponse"; + return typeUrlPrefix + "/google.firestore.v1.DocumentChange"; }; - return BeginTransactionResponse; + return DocumentChange; })(); - v1.CommitRequest = (function() { + v1.DocumentDelete = (function() { /** - * Properties of a CommitRequest. + * Properties of a DocumentDelete. * @memberof google.firestore.v1 - * @interface ICommitRequest - * @property {string|null} [database] CommitRequest database - * @property {Array.|null} [writes] CommitRequest writes - * @property {Uint8Array|null} [transaction] CommitRequest transaction + * @interface IDocumentDelete + * @property {string|null} [document] DocumentDelete document + * @property {Array.|null} [removedTargetIds] DocumentDelete removedTargetIds + * @property {google.protobuf.ITimestamp|null} [readTime] DocumentDelete readTime */ /** - * Constructs a new CommitRequest. + * Constructs a new DocumentDelete. * @memberof google.firestore.v1 - * @classdesc Represents a CommitRequest. - * @implements ICommitRequest + * @classdesc Represents a DocumentDelete. + * @implements IDocumentDelete * @constructor - * @param {google.firestore.v1.ICommitRequest=} [properties] Properties to set + * @param {google.firestore.v1.IDocumentDelete=} [properties] Properties to set */ - function CommitRequest(properties) { - this.writes = []; + function DocumentDelete(properties) { + this.removedTargetIds = []; if (properties) for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) if (properties[keys[i]] != null) @@ -14208,147 +12923,139 @@ } /** - * CommitRequest database. - * @member {string} database - * @memberof google.firestore.v1.CommitRequest + * DocumentDelete document. + * @member {string} document + * @memberof google.firestore.v1.DocumentDelete * @instance */ - CommitRequest.prototype.database = ""; + DocumentDelete.prototype.document = ""; /** - * CommitRequest writes. - * @member {Array.} writes - * @memberof google.firestore.v1.CommitRequest + * DocumentDelete removedTargetIds. + * @member {Array.} removedTargetIds + * @memberof google.firestore.v1.DocumentDelete * @instance */ - CommitRequest.prototype.writes = $util.emptyArray; + DocumentDelete.prototype.removedTargetIds = $util.emptyArray; /** - * CommitRequest transaction. - * @member {Uint8Array} transaction - * @memberof google.firestore.v1.CommitRequest + * DocumentDelete readTime. + * @member {google.protobuf.ITimestamp|null|undefined} readTime + * @memberof google.firestore.v1.DocumentDelete * @instance */ - CommitRequest.prototype.transaction = $util.newBuffer([]); + DocumentDelete.prototype.readTime = null; /** - * Creates a CommitRequest message from a plain object. Also converts values to their respective internal types. + * Creates a DocumentDelete message from a plain object. Also converts values to their respective internal types. * @function fromObject - * @memberof google.firestore.v1.CommitRequest + * @memberof google.firestore.v1.DocumentDelete * @static * @param {Object.} object Plain object - * @returns {google.firestore.v1.CommitRequest} CommitRequest + * @returns {google.firestore.v1.DocumentDelete} DocumentDelete */ - CommitRequest.fromObject = function fromObject(object) { - if (object instanceof $root.google.firestore.v1.CommitRequest) + DocumentDelete.fromObject = function fromObject(object) { + if (object instanceof $root.google.firestore.v1.DocumentDelete) return object; - var message = new $root.google.firestore.v1.CommitRequest(); - if (object.database != null) - message.database = String(object.database); - if (object.writes) { - if (!Array.isArray(object.writes)) - throw TypeError(".google.firestore.v1.CommitRequest.writes: array expected"); - message.writes = []; - for (var i = 0; i < object.writes.length; ++i) { - if (typeof object.writes[i] !== "object") - throw TypeError(".google.firestore.v1.CommitRequest.writes: object expected"); - message.writes[i] = $root.google.firestore.v1.Write.fromObject(object.writes[i]); - } + var message = new $root.google.firestore.v1.DocumentDelete(); + if (object.document != null) + message.document = String(object.document); + if (object.removedTargetIds) { + if (!Array.isArray(object.removedTargetIds)) + throw TypeError(".google.firestore.v1.DocumentDelete.removedTargetIds: array expected"); + message.removedTargetIds = []; + for (var i = 0; i < object.removedTargetIds.length; ++i) + message.removedTargetIds[i] = object.removedTargetIds[i] | 0; + } + if (object.readTime != null) { + if (typeof object.readTime !== "object") + throw TypeError(".google.firestore.v1.DocumentDelete.readTime: object expected"); + message.readTime = $root.google.protobuf.Timestamp.fromObject(object.readTime); } - if (object.transaction != null) - if (typeof object.transaction === "string") - $util.base64.decode(object.transaction, message.transaction = $util.newBuffer($util.base64.length(object.transaction)), 0); - else if (object.transaction.length >= 0) - message.transaction = object.transaction; return message; }; /** - * Creates a plain object from a CommitRequest message. Also converts values to other types if specified. + * Creates a plain object from a DocumentDelete message. Also converts values to other types if specified. * @function toObject - * @memberof google.firestore.v1.CommitRequest + * @memberof google.firestore.v1.DocumentDelete * @static - * @param {google.firestore.v1.CommitRequest} message CommitRequest + * @param {google.firestore.v1.DocumentDelete} message DocumentDelete * @param {$protobuf.IConversionOptions} [options] Conversion options * @returns {Object.} Plain object */ - CommitRequest.toObject = function toObject(message, options) { + DocumentDelete.toObject = function toObject(message, options) { if (!options) options = {}; var object = {}; if (options.arrays || options.defaults) - object.writes = []; + object.removedTargetIds = []; if (options.defaults) { - object.database = ""; - if (options.bytes === String) - object.transaction = ""; - else { - object.transaction = []; - if (options.bytes !== Array) - object.transaction = $util.newBuffer(object.transaction); - } + object.document = ""; + object.readTime = null; } - if (message.database != null && message.hasOwnProperty("database")) - object.database = message.database; - if (message.writes && message.writes.length) { - object.writes = []; - for (var j = 0; j < message.writes.length; ++j) - object.writes[j] = $root.google.firestore.v1.Write.toObject(message.writes[j], options); + if (message.document != null && message.hasOwnProperty("document")) + object.document = message.document; + if (message.readTime != null && message.hasOwnProperty("readTime")) + object.readTime = $root.google.protobuf.Timestamp.toObject(message.readTime, options); + if (message.removedTargetIds && message.removedTargetIds.length) { + object.removedTargetIds = []; + for (var j = 0; j < message.removedTargetIds.length; ++j) + object.removedTargetIds[j] = message.removedTargetIds[j]; } - if (message.transaction != null && message.hasOwnProperty("transaction")) - object.transaction = options.bytes === String ? $util.base64.encode(message.transaction, 0, message.transaction.length) : options.bytes === Array ? Array.prototype.slice.call(message.transaction) : message.transaction; return object; }; /** - * Converts this CommitRequest to JSON. + * Converts this DocumentDelete to JSON. * @function toJSON - * @memberof google.firestore.v1.CommitRequest + * @memberof google.firestore.v1.DocumentDelete * @instance * @returns {Object.} JSON object */ - CommitRequest.prototype.toJSON = function toJSON() { + DocumentDelete.prototype.toJSON = function toJSON() { return this.constructor.toObject(this, $protobuf.util.toJSONOptions); }; /** - * Gets the default type url for CommitRequest + * Gets the default type url for DocumentDelete * @function getTypeUrl - * @memberof google.firestore.v1.CommitRequest + * @memberof google.firestore.v1.DocumentDelete * @static * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") * @returns {string} The default type url */ - CommitRequest.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + DocumentDelete.getTypeUrl = function getTypeUrl(typeUrlPrefix) { if (typeUrlPrefix === undefined) { typeUrlPrefix = "type.googleapis.com"; } - return typeUrlPrefix + "/google.firestore.v1.CommitRequest"; + return typeUrlPrefix + "/google.firestore.v1.DocumentDelete"; }; - return CommitRequest; + return DocumentDelete; })(); - v1.CommitResponse = (function() { + v1.DocumentRemove = (function() { /** - * Properties of a CommitResponse. + * Properties of a DocumentRemove. * @memberof google.firestore.v1 - * @interface ICommitResponse - * @property {Array.|null} [writeResults] CommitResponse writeResults - * @property {google.protobuf.ITimestamp|null} [commitTime] CommitResponse commitTime + * @interface IDocumentRemove + * @property {string|null} [document] DocumentRemove document + * @property {Array.|null} [removedTargetIds] DocumentRemove removedTargetIds + * @property {google.protobuf.ITimestamp|null} [readTime] DocumentRemove readTime */ /** - * Constructs a new CommitResponse. + * Constructs a new DocumentRemove. * @memberof google.firestore.v1 - * @classdesc Represents a CommitResponse. - * @implements ICommitResponse + * @classdesc Represents a DocumentRemove. + * @implements IDocumentRemove * @constructor - * @param {google.firestore.v1.ICommitResponse=} [properties] Properties to set + * @param {google.firestore.v1.IDocumentRemove=} [properties] Properties to set */ - function CommitResponse(properties) { - this.writeResults = []; + function DocumentRemove(properties) { + this.removedTargetIds = []; if (properties) for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) if (properties[keys[i]] != null) @@ -14356,126 +13063,138 @@ } /** - * CommitResponse writeResults. - * @member {Array.} writeResults - * @memberof google.firestore.v1.CommitResponse + * DocumentRemove document. + * @member {string} document + * @memberof google.firestore.v1.DocumentRemove * @instance */ - CommitResponse.prototype.writeResults = $util.emptyArray; + DocumentRemove.prototype.document = ""; /** - * CommitResponse commitTime. - * @member {google.protobuf.ITimestamp|null|undefined} commitTime - * @memberof google.firestore.v1.CommitResponse + * DocumentRemove removedTargetIds. + * @member {Array.} removedTargetIds + * @memberof google.firestore.v1.DocumentRemove * @instance */ - CommitResponse.prototype.commitTime = null; + DocumentRemove.prototype.removedTargetIds = $util.emptyArray; /** - * Creates a CommitResponse message from a plain object. Also converts values to their respective internal types. + * DocumentRemove readTime. + * @member {google.protobuf.ITimestamp|null|undefined} readTime + * @memberof google.firestore.v1.DocumentRemove + * @instance + */ + DocumentRemove.prototype.readTime = null; + + /** + * Creates a DocumentRemove message from a plain object. Also converts values to their respective internal types. * @function fromObject - * @memberof google.firestore.v1.CommitResponse + * @memberof google.firestore.v1.DocumentRemove * @static * @param {Object.} object Plain object - * @returns {google.firestore.v1.CommitResponse} CommitResponse + * @returns {google.firestore.v1.DocumentRemove} DocumentRemove */ - CommitResponse.fromObject = function fromObject(object) { - if (object instanceof $root.google.firestore.v1.CommitResponse) + DocumentRemove.fromObject = function fromObject(object) { + if (object instanceof $root.google.firestore.v1.DocumentRemove) return object; - var message = new $root.google.firestore.v1.CommitResponse(); - if (object.writeResults) { - if (!Array.isArray(object.writeResults)) - throw TypeError(".google.firestore.v1.CommitResponse.writeResults: array expected"); - message.writeResults = []; - for (var i = 0; i < object.writeResults.length; ++i) { - if (typeof object.writeResults[i] !== "object") - throw TypeError(".google.firestore.v1.CommitResponse.writeResults: object expected"); - message.writeResults[i] = $root.google.firestore.v1.WriteResult.fromObject(object.writeResults[i]); - } + var message = new $root.google.firestore.v1.DocumentRemove(); + if (object.document != null) + message.document = String(object.document); + if (object.removedTargetIds) { + if (!Array.isArray(object.removedTargetIds)) + throw TypeError(".google.firestore.v1.DocumentRemove.removedTargetIds: array expected"); + message.removedTargetIds = []; + for (var i = 0; i < object.removedTargetIds.length; ++i) + message.removedTargetIds[i] = object.removedTargetIds[i] | 0; } - if (object.commitTime != null) { - if (typeof object.commitTime !== "object") - throw TypeError(".google.firestore.v1.CommitResponse.commitTime: object expected"); - message.commitTime = $root.google.protobuf.Timestamp.fromObject(object.commitTime); + if (object.readTime != null) { + if (typeof object.readTime !== "object") + throw TypeError(".google.firestore.v1.DocumentRemove.readTime: object expected"); + message.readTime = $root.google.protobuf.Timestamp.fromObject(object.readTime); } return message; }; /** - * Creates a plain object from a CommitResponse message. Also converts values to other types if specified. + * Creates a plain object from a DocumentRemove message. Also converts values to other types if specified. * @function toObject - * @memberof google.firestore.v1.CommitResponse + * @memberof google.firestore.v1.DocumentRemove * @static - * @param {google.firestore.v1.CommitResponse} message CommitResponse + * @param {google.firestore.v1.DocumentRemove} message DocumentRemove * @param {$protobuf.IConversionOptions} [options] Conversion options * @returns {Object.} Plain object */ - CommitResponse.toObject = function toObject(message, options) { + DocumentRemove.toObject = function toObject(message, options) { if (!options) options = {}; var object = {}; if (options.arrays || options.defaults) - object.writeResults = []; - if (options.defaults) - object.commitTime = null; - if (message.writeResults && message.writeResults.length) { - object.writeResults = []; - for (var j = 0; j < message.writeResults.length; ++j) - object.writeResults[j] = $root.google.firestore.v1.WriteResult.toObject(message.writeResults[j], options); + object.removedTargetIds = []; + if (options.defaults) { + object.document = ""; + object.readTime = null; } - if (message.commitTime != null && message.hasOwnProperty("commitTime")) - object.commitTime = $root.google.protobuf.Timestamp.toObject(message.commitTime, options); + if (message.document != null && message.hasOwnProperty("document")) + object.document = message.document; + if (message.removedTargetIds && message.removedTargetIds.length) { + object.removedTargetIds = []; + for (var j = 0; j < message.removedTargetIds.length; ++j) + object.removedTargetIds[j] = message.removedTargetIds[j]; + } + if (message.readTime != null && message.hasOwnProperty("readTime")) + object.readTime = $root.google.protobuf.Timestamp.toObject(message.readTime, options); return object; }; /** - * Converts this CommitResponse to JSON. + * Converts this DocumentRemove to JSON. * @function toJSON - * @memberof google.firestore.v1.CommitResponse + * @memberof google.firestore.v1.DocumentRemove * @instance * @returns {Object.} JSON object */ - CommitResponse.prototype.toJSON = function toJSON() { + DocumentRemove.prototype.toJSON = function toJSON() { return this.constructor.toObject(this, $protobuf.util.toJSONOptions); }; /** - * Gets the default type url for CommitResponse + * Gets the default type url for DocumentRemove * @function getTypeUrl - * @memberof google.firestore.v1.CommitResponse + * @memberof google.firestore.v1.DocumentRemove * @static * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") * @returns {string} The default type url */ - CommitResponse.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + DocumentRemove.getTypeUrl = function getTypeUrl(typeUrlPrefix) { if (typeUrlPrefix === undefined) { typeUrlPrefix = "type.googleapis.com"; } - return typeUrlPrefix + "/google.firestore.v1.CommitResponse"; + return typeUrlPrefix + "/google.firestore.v1.DocumentRemove"; }; - return CommitResponse; + return DocumentRemove; })(); - v1.RollbackRequest = (function() { + v1.ExistenceFilter = (function() { /** - * Properties of a RollbackRequest. + * Properties of an ExistenceFilter. * @memberof google.firestore.v1 - * @interface IRollbackRequest - * @property {string|null} [database] RollbackRequest database - * @property {Uint8Array|null} [transaction] RollbackRequest transaction + * @interface IExistenceFilter + * @property {number|null} [targetId] ExistenceFilter targetId + * @property {number|null} [count] ExistenceFilter count + * @property {google.firestore.v1.IBloomFilter|null} [unchangedNames] ExistenceFilter unchangedNames */ /** - * Constructs a new RollbackRequest. + * Constructs a new ExistenceFilter. * @memberof google.firestore.v1 - * @classdesc Represents a RollbackRequest. - * @implements IRollbackRequest + * @classdesc Represents an ExistenceFilter. + * @implements IExistenceFilter * @constructor - * @param {google.firestore.v1.IRollbackRequest=} [properties] Properties to set + * @param {google.firestore.v1.IExistenceFilter=} [properties] Properties to set */ - function RollbackRequest(properties) { + function ExistenceFilter(properties) { if (properties) for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) if (properties[keys[i]] != null) @@ -14483,2140 +13202,2536 @@ } /** - * RollbackRequest database. - * @member {string} database - * @memberof google.firestore.v1.RollbackRequest + * ExistenceFilter targetId. + * @member {number} targetId + * @memberof google.firestore.v1.ExistenceFilter + * @instance + */ + ExistenceFilter.prototype.targetId = 0; + + /** + * ExistenceFilter count. + * @member {number} count + * @memberof google.firestore.v1.ExistenceFilter * @instance */ - RollbackRequest.prototype.database = ""; + ExistenceFilter.prototype.count = 0; /** - * RollbackRequest transaction. - * @member {Uint8Array} transaction - * @memberof google.firestore.v1.RollbackRequest + * ExistenceFilter unchangedNames. + * @member {google.firestore.v1.IBloomFilter|null|undefined} unchangedNames + * @memberof google.firestore.v1.ExistenceFilter * @instance */ - RollbackRequest.prototype.transaction = $util.newBuffer([]); + ExistenceFilter.prototype.unchangedNames = null; /** - * Creates a RollbackRequest message from a plain object. Also converts values to their respective internal types. + * Creates an ExistenceFilter message from a plain object. Also converts values to their respective internal types. * @function fromObject - * @memberof google.firestore.v1.RollbackRequest + * @memberof google.firestore.v1.ExistenceFilter * @static * @param {Object.} object Plain object - * @returns {google.firestore.v1.RollbackRequest} RollbackRequest + * @returns {google.firestore.v1.ExistenceFilter} ExistenceFilter */ - RollbackRequest.fromObject = function fromObject(object) { - if (object instanceof $root.google.firestore.v1.RollbackRequest) + ExistenceFilter.fromObject = function fromObject(object) { + if (object instanceof $root.google.firestore.v1.ExistenceFilter) return object; - var message = new $root.google.firestore.v1.RollbackRequest(); - if (object.database != null) - message.database = String(object.database); - if (object.transaction != null) - if (typeof object.transaction === "string") - $util.base64.decode(object.transaction, message.transaction = $util.newBuffer($util.base64.length(object.transaction)), 0); - else if (object.transaction.length >= 0) - message.transaction = object.transaction; + var message = new $root.google.firestore.v1.ExistenceFilter(); + if (object.targetId != null) + message.targetId = object.targetId | 0; + if (object.count != null) + message.count = object.count | 0; + if (object.unchangedNames != null) { + if (typeof object.unchangedNames !== "object") + throw TypeError(".google.firestore.v1.ExistenceFilter.unchangedNames: object expected"); + message.unchangedNames = $root.google.firestore.v1.BloomFilter.fromObject(object.unchangedNames); + } return message; }; /** - * Creates a plain object from a RollbackRequest message. Also converts values to other types if specified. + * Creates a plain object from an ExistenceFilter message. Also converts values to other types if specified. * @function toObject - * @memberof google.firestore.v1.RollbackRequest + * @memberof google.firestore.v1.ExistenceFilter * @static - * @param {google.firestore.v1.RollbackRequest} message RollbackRequest + * @param {google.firestore.v1.ExistenceFilter} message ExistenceFilter * @param {$protobuf.IConversionOptions} [options] Conversion options * @returns {Object.} Plain object */ - RollbackRequest.toObject = function toObject(message, options) { + ExistenceFilter.toObject = function toObject(message, options) { if (!options) options = {}; var object = {}; if (options.defaults) { - object.database = ""; - if (options.bytes === String) - object.transaction = ""; - else { - object.transaction = []; - if (options.bytes !== Array) - object.transaction = $util.newBuffer(object.transaction); - } + object.targetId = 0; + object.count = 0; + object.unchangedNames = null; } - if (message.database != null && message.hasOwnProperty("database")) - object.database = message.database; - if (message.transaction != null && message.hasOwnProperty("transaction")) - object.transaction = options.bytes === String ? $util.base64.encode(message.transaction, 0, message.transaction.length) : options.bytes === Array ? Array.prototype.slice.call(message.transaction) : message.transaction; + if (message.targetId != null && message.hasOwnProperty("targetId")) + object.targetId = message.targetId; + if (message.count != null && message.hasOwnProperty("count")) + object.count = message.count; + if (message.unchangedNames != null && message.hasOwnProperty("unchangedNames")) + object.unchangedNames = $root.google.firestore.v1.BloomFilter.toObject(message.unchangedNames, options); return object; }; /** - * Converts this RollbackRequest to JSON. + * Converts this ExistenceFilter to JSON. * @function toJSON - * @memberof google.firestore.v1.RollbackRequest + * @memberof google.firestore.v1.ExistenceFilter * @instance * @returns {Object.} JSON object */ - RollbackRequest.prototype.toJSON = function toJSON() { + ExistenceFilter.prototype.toJSON = function toJSON() { return this.constructor.toObject(this, $protobuf.util.toJSONOptions); }; /** - * Gets the default type url for RollbackRequest + * Gets the default type url for ExistenceFilter * @function getTypeUrl - * @memberof google.firestore.v1.RollbackRequest + * @memberof google.firestore.v1.ExistenceFilter * @static * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") * @returns {string} The default type url */ - RollbackRequest.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + ExistenceFilter.getTypeUrl = function getTypeUrl(typeUrlPrefix) { if (typeUrlPrefix === undefined) { typeUrlPrefix = "type.googleapis.com"; } - return typeUrlPrefix + "/google.firestore.v1.RollbackRequest"; + return typeUrlPrefix + "/google.firestore.v1.ExistenceFilter"; }; - return RollbackRequest; + return ExistenceFilter; })(); - v1.RunQueryRequest = (function() { + return v1; + })(); - /** - * Properties of a RunQueryRequest. - * @memberof google.firestore.v1 - * @interface IRunQueryRequest - * @property {string|null} [parent] RunQueryRequest parent - * @property {google.firestore.v1.IStructuredQuery|null} [structuredQuery] RunQueryRequest structuredQuery - * @property {Uint8Array|null} [transaction] RunQueryRequest transaction - * @property {google.firestore.v1.ITransactionOptions|null} [newTransaction] RunQueryRequest newTransaction - * @property {google.protobuf.ITimestamp|null} [readTime] RunQueryRequest readTime - * @property {google.firestore.v1.IExplainOptions|null} [explainOptions] RunQueryRequest explainOptions - */ + return firestore; + })(); - /** - * Constructs a new RunQueryRequest. - * @memberof google.firestore.v1 - * @classdesc Represents a RunQueryRequest. - * @implements IRunQueryRequest - * @constructor - * @param {google.firestore.v1.IRunQueryRequest=} [properties] Properties to set - */ - function RunQueryRequest(properties) { - if (properties) - for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) - if (properties[keys[i]] != null) - this[keys[i]] = properties[keys[i]]; + google.api = (function() { + + /** + * Namespace api. + * @memberof google + * @namespace + */ + var api = {}; + + /** + * FieldBehavior enum. + * @name google.api.FieldBehavior + * @enum {string} + * @property {string} FIELD_BEHAVIOR_UNSPECIFIED=FIELD_BEHAVIOR_UNSPECIFIED FIELD_BEHAVIOR_UNSPECIFIED value + * @property {string} OPTIONAL=OPTIONAL OPTIONAL value + * @property {string} REQUIRED=REQUIRED REQUIRED value + * @property {string} OUTPUT_ONLY=OUTPUT_ONLY OUTPUT_ONLY value + * @property {string} INPUT_ONLY=INPUT_ONLY INPUT_ONLY value + * @property {string} IMMUTABLE=IMMUTABLE IMMUTABLE value + * @property {string} UNORDERED_LIST=UNORDERED_LIST UNORDERED_LIST value + * @property {string} NON_EMPTY_DEFAULT=NON_EMPTY_DEFAULT NON_EMPTY_DEFAULT value + * @property {string} IDENTIFIER=IDENTIFIER IDENTIFIER value + */ + api.FieldBehavior = (function() { + var valuesById = {}, values = Object.create(valuesById); + values[valuesById[0] = "FIELD_BEHAVIOR_UNSPECIFIED"] = "FIELD_BEHAVIOR_UNSPECIFIED"; + values[valuesById[1] = "OPTIONAL"] = "OPTIONAL"; + values[valuesById[2] = "REQUIRED"] = "REQUIRED"; + values[valuesById[3] = "OUTPUT_ONLY"] = "OUTPUT_ONLY"; + values[valuesById[4] = "INPUT_ONLY"] = "INPUT_ONLY"; + values[valuesById[5] = "IMMUTABLE"] = "IMMUTABLE"; + values[valuesById[6] = "UNORDERED_LIST"] = "UNORDERED_LIST"; + values[valuesById[7] = "NON_EMPTY_DEFAULT"] = "NON_EMPTY_DEFAULT"; + values[valuesById[8] = "IDENTIFIER"] = "IDENTIFIER"; + return values; + })(); + + api.Http = (function() { + + /** + * Properties of a Http. + * @memberof google.api + * @interface IHttp + * @property {Array.|null} [rules] Http rules + * @property {boolean|null} [fullyDecodeReservedExpansion] Http fullyDecodeReservedExpansion + */ + + /** + * Constructs a new Http. + * @memberof google.api + * @classdesc Represents a Http. + * @implements IHttp + * @constructor + * @param {google.api.IHttp=} [properties] Properties to set + */ + function Http(properties) { + this.rules = []; + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } + + /** + * Http rules. + * @member {Array.} rules + * @memberof google.api.Http + * @instance + */ + Http.prototype.rules = $util.emptyArray; + + /** + * Http fullyDecodeReservedExpansion. + * @member {boolean} fullyDecodeReservedExpansion + * @memberof google.api.Http + * @instance + */ + Http.prototype.fullyDecodeReservedExpansion = false; + + /** + * Creates a Http message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.api.Http + * @static + * @param {Object.} object Plain object + * @returns {google.api.Http} Http + */ + Http.fromObject = function fromObject(object) { + if (object instanceof $root.google.api.Http) + return object; + var message = new $root.google.api.Http(); + if (object.rules) { + if (!Array.isArray(object.rules)) + throw TypeError(".google.api.Http.rules: array expected"); + message.rules = []; + for (var i = 0; i < object.rules.length; ++i) { + if (typeof object.rules[i] !== "object") + throw TypeError(".google.api.Http.rules: object expected"); + message.rules[i] = $root.google.api.HttpRule.fromObject(object.rules[i]); + } + } + if (object.fullyDecodeReservedExpansion != null) + message.fullyDecodeReservedExpansion = Boolean(object.fullyDecodeReservedExpansion); + return message; + }; + + /** + * Creates a plain object from a Http message. Also converts values to other types if specified. + * @function toObject + * @memberof google.api.Http + * @static + * @param {google.api.Http} message Http + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + Http.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.arrays || options.defaults) + object.rules = []; + if (options.defaults) + object.fullyDecodeReservedExpansion = false; + if (message.rules && message.rules.length) { + object.rules = []; + for (var j = 0; j < message.rules.length; ++j) + object.rules[j] = $root.google.api.HttpRule.toObject(message.rules[j], options); + } + if (message.fullyDecodeReservedExpansion != null && message.hasOwnProperty("fullyDecodeReservedExpansion")) + object.fullyDecodeReservedExpansion = message.fullyDecodeReservedExpansion; + return object; + }; + + /** + * Converts this Http to JSON. + * @function toJSON + * @memberof google.api.Http + * @instance + * @returns {Object.} JSON object + */ + Http.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + + /** + * Gets the default type url for Http + * @function getTypeUrl + * @memberof google.api.Http + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + Http.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; } + return typeUrlPrefix + "/google.api.Http"; + }; - /** - * RunQueryRequest parent. - * @member {string} parent - * @memberof google.firestore.v1.RunQueryRequest - * @instance - */ - RunQueryRequest.prototype.parent = ""; + return Http; + })(); - /** - * RunQueryRequest structuredQuery. - * @member {google.firestore.v1.IStructuredQuery|null|undefined} structuredQuery - * @memberof google.firestore.v1.RunQueryRequest - * @instance - */ - RunQueryRequest.prototype.structuredQuery = null; + api.HttpRule = (function() { - /** - * RunQueryRequest transaction. - * @member {Uint8Array|null|undefined} transaction - * @memberof google.firestore.v1.RunQueryRequest - * @instance - */ - RunQueryRequest.prototype.transaction = null; + /** + * Properties of a HttpRule. + * @memberof google.api + * @interface IHttpRule + * @property {string|null} [selector] HttpRule selector + * @property {string|null} [get] HttpRule get + * @property {string|null} [put] HttpRule put + * @property {string|null} [post] HttpRule post + * @property {string|null} ["delete"] HttpRule delete + * @property {string|null} [patch] HttpRule patch + * @property {google.api.ICustomHttpPattern|null} [custom] HttpRule custom + * @property {string|null} [body] HttpRule body + * @property {string|null} [responseBody] HttpRule responseBody + * @property {Array.|null} [additionalBindings] HttpRule additionalBindings + */ - /** - * RunQueryRequest newTransaction. - * @member {google.firestore.v1.ITransactionOptions|null|undefined} newTransaction - * @memberof google.firestore.v1.RunQueryRequest - * @instance - */ - RunQueryRequest.prototype.newTransaction = null; + /** + * Constructs a new HttpRule. + * @memberof google.api + * @classdesc Represents a HttpRule. + * @implements IHttpRule + * @constructor + * @param {google.api.IHttpRule=} [properties] Properties to set + */ + function HttpRule(properties) { + this.additionalBindings = []; + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } - /** - * RunQueryRequest readTime. - * @member {google.protobuf.ITimestamp|null|undefined} readTime - * @memberof google.firestore.v1.RunQueryRequest - * @instance - */ - RunQueryRequest.prototype.readTime = null; + /** + * HttpRule selector. + * @member {string} selector + * @memberof google.api.HttpRule + * @instance + */ + HttpRule.prototype.selector = ""; - /** - * RunQueryRequest explainOptions. - * @member {google.firestore.v1.IExplainOptions|null|undefined} explainOptions - * @memberof google.firestore.v1.RunQueryRequest - * @instance - */ - RunQueryRequest.prototype.explainOptions = null; + /** + * HttpRule get. + * @member {string|null|undefined} get + * @memberof google.api.HttpRule + * @instance + */ + HttpRule.prototype.get = null; - // OneOf field names bound to virtual getters and setters - var $oneOfFields; + /** + * HttpRule put. + * @member {string|null|undefined} put + * @memberof google.api.HttpRule + * @instance + */ + HttpRule.prototype.put = null; - /** - * RunQueryRequest queryType. - * @member {"structuredQuery"|undefined} queryType - * @memberof google.firestore.v1.RunQueryRequest - * @instance - */ - Object.defineProperty(RunQueryRequest.prototype, "queryType", { - get: $util.oneOfGetter($oneOfFields = ["structuredQuery"]), - set: $util.oneOfSetter($oneOfFields) - }); + /** + * HttpRule post. + * @member {string|null|undefined} post + * @memberof google.api.HttpRule + * @instance + */ + HttpRule.prototype.post = null; - /** - * RunQueryRequest consistencySelector. - * @member {"transaction"|"newTransaction"|"readTime"|undefined} consistencySelector - * @memberof google.firestore.v1.RunQueryRequest - * @instance - */ - Object.defineProperty(RunQueryRequest.prototype, "consistencySelector", { - get: $util.oneOfGetter($oneOfFields = ["transaction", "newTransaction", "readTime"]), - set: $util.oneOfSetter($oneOfFields) - }); + /** + * HttpRule delete. + * @member {string|null|undefined} delete + * @memberof google.api.HttpRule + * @instance + */ + HttpRule.prototype["delete"] = null; - /** - * Creates a RunQueryRequest message from a plain object. Also converts values to their respective internal types. - * @function fromObject - * @memberof google.firestore.v1.RunQueryRequest - * @static - * @param {Object.} object Plain object - * @returns {google.firestore.v1.RunQueryRequest} RunQueryRequest - */ - RunQueryRequest.fromObject = function fromObject(object) { - if (object instanceof $root.google.firestore.v1.RunQueryRequest) - return object; - var message = new $root.google.firestore.v1.RunQueryRequest(); - if (object.parent != null) - message.parent = String(object.parent); - if (object.structuredQuery != null) { - if (typeof object.structuredQuery !== "object") - throw TypeError(".google.firestore.v1.RunQueryRequest.structuredQuery: object expected"); - message.structuredQuery = $root.google.firestore.v1.StructuredQuery.fromObject(object.structuredQuery); - } - if (object.transaction != null) - if (typeof object.transaction === "string") - $util.base64.decode(object.transaction, message.transaction = $util.newBuffer($util.base64.length(object.transaction)), 0); - else if (object.transaction.length >= 0) - message.transaction = object.transaction; - if (object.newTransaction != null) { - if (typeof object.newTransaction !== "object") - throw TypeError(".google.firestore.v1.RunQueryRequest.newTransaction: object expected"); - message.newTransaction = $root.google.firestore.v1.TransactionOptions.fromObject(object.newTransaction); - } - if (object.readTime != null) { - if (typeof object.readTime !== "object") - throw TypeError(".google.firestore.v1.RunQueryRequest.readTime: object expected"); - message.readTime = $root.google.protobuf.Timestamp.fromObject(object.readTime); - } - if (object.explainOptions != null) { - if (typeof object.explainOptions !== "object") - throw TypeError(".google.firestore.v1.RunQueryRequest.explainOptions: object expected"); - message.explainOptions = $root.google.firestore.v1.ExplainOptions.fromObject(object.explainOptions); - } - return message; - }; + /** + * HttpRule patch. + * @member {string|null|undefined} patch + * @memberof google.api.HttpRule + * @instance + */ + HttpRule.prototype.patch = null; - /** - * Creates a plain object from a RunQueryRequest message. Also converts values to other types if specified. - * @function toObject - * @memberof google.firestore.v1.RunQueryRequest - * @static - * @param {google.firestore.v1.RunQueryRequest} message RunQueryRequest - * @param {$protobuf.IConversionOptions} [options] Conversion options - * @returns {Object.} Plain object - */ - RunQueryRequest.toObject = function toObject(message, options) { - if (!options) - options = {}; - var object = {}; - if (options.defaults) { - object.parent = ""; - object.explainOptions = null; - } - if (message.parent != null && message.hasOwnProperty("parent")) - object.parent = message.parent; - if (message.structuredQuery != null && message.hasOwnProperty("structuredQuery")) { - object.structuredQuery = $root.google.firestore.v1.StructuredQuery.toObject(message.structuredQuery, options); - if (options.oneofs) - object.queryType = "structuredQuery"; - } - if (message.transaction != null && message.hasOwnProperty("transaction")) { - object.transaction = options.bytes === String ? $util.base64.encode(message.transaction, 0, message.transaction.length) : options.bytes === Array ? Array.prototype.slice.call(message.transaction) : message.transaction; - if (options.oneofs) - object.consistencySelector = "transaction"; - } - if (message.newTransaction != null && message.hasOwnProperty("newTransaction")) { - object.newTransaction = $root.google.firestore.v1.TransactionOptions.toObject(message.newTransaction, options); - if (options.oneofs) - object.consistencySelector = "newTransaction"; - } - if (message.readTime != null && message.hasOwnProperty("readTime")) { - object.readTime = $root.google.protobuf.Timestamp.toObject(message.readTime, options); - if (options.oneofs) - object.consistencySelector = "readTime"; - } - if (message.explainOptions != null && message.hasOwnProperty("explainOptions")) - object.explainOptions = $root.google.firestore.v1.ExplainOptions.toObject(message.explainOptions, options); - return object; - }; + /** + * HttpRule custom. + * @member {google.api.ICustomHttpPattern|null|undefined} custom + * @memberof google.api.HttpRule + * @instance + */ + HttpRule.prototype.custom = null; - /** - * Converts this RunQueryRequest to JSON. - * @function toJSON - * @memberof google.firestore.v1.RunQueryRequest - * @instance - * @returns {Object.} JSON object - */ - RunQueryRequest.prototype.toJSON = function toJSON() { - return this.constructor.toObject(this, $protobuf.util.toJSONOptions); - }; + /** + * HttpRule body. + * @member {string} body + * @memberof google.api.HttpRule + * @instance + */ + HttpRule.prototype.body = ""; - /** - * Gets the default type url for RunQueryRequest - * @function getTypeUrl - * @memberof google.firestore.v1.RunQueryRequest - * @static - * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") - * @returns {string} The default type url - */ - RunQueryRequest.getTypeUrl = function getTypeUrl(typeUrlPrefix) { - if (typeUrlPrefix === undefined) { - typeUrlPrefix = "type.googleapis.com"; - } - return typeUrlPrefix + "/google.firestore.v1.RunQueryRequest"; - }; + /** + * HttpRule responseBody. + * @member {string} responseBody + * @memberof google.api.HttpRule + * @instance + */ + HttpRule.prototype.responseBody = ""; - return RunQueryRequest; - })(); + /** + * HttpRule additionalBindings. + * @member {Array.} additionalBindings + * @memberof google.api.HttpRule + * @instance + */ + HttpRule.prototype.additionalBindings = $util.emptyArray; - v1.RunQueryResponse = (function() { + // OneOf field names bound to virtual getters and setters + var $oneOfFields; - /** - * Properties of a RunQueryResponse. - * @memberof google.firestore.v1 - * @interface IRunQueryResponse - * @property {Uint8Array|null} [transaction] RunQueryResponse transaction - * @property {google.firestore.v1.IDocument|null} [document] RunQueryResponse document - * @property {google.protobuf.ITimestamp|null} [readTime] RunQueryResponse readTime - * @property {number|null} [skippedResults] RunQueryResponse skippedResults - * @property {boolean|null} [done] RunQueryResponse done - * @property {google.firestore.v1.IExplainMetrics|null} [explainMetrics] RunQueryResponse explainMetrics - */ + /** + * HttpRule pattern. + * @member {"get"|"put"|"post"|"delete"|"patch"|"custom"|undefined} pattern + * @memberof google.api.HttpRule + * @instance + */ + Object.defineProperty(HttpRule.prototype, "pattern", { + get: $util.oneOfGetter($oneOfFields = ["get", "put", "post", "delete", "patch", "custom"]), + set: $util.oneOfSetter($oneOfFields) + }); - /** - * Constructs a new RunQueryResponse. - * @memberof google.firestore.v1 - * @classdesc Represents a RunQueryResponse. - * @implements IRunQueryResponse - * @constructor - * @param {google.firestore.v1.IRunQueryResponse=} [properties] Properties to set - */ - function RunQueryResponse(properties) { - if (properties) - for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) - if (properties[keys[i]] != null) - this[keys[i]] = properties[keys[i]]; + /** + * Creates a HttpRule message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.api.HttpRule + * @static + * @param {Object.} object Plain object + * @returns {google.api.HttpRule} HttpRule + */ + HttpRule.fromObject = function fromObject(object) { + if (object instanceof $root.google.api.HttpRule) + return object; + var message = new $root.google.api.HttpRule(); + if (object.selector != null) + message.selector = String(object.selector); + if (object.get != null) + message.get = String(object.get); + if (object.put != null) + message.put = String(object.put); + if (object.post != null) + message.post = String(object.post); + if (object["delete"] != null) + message["delete"] = String(object["delete"]); + if (object.patch != null) + message.patch = String(object.patch); + if (object.custom != null) { + if (typeof object.custom !== "object") + throw TypeError(".google.api.HttpRule.custom: object expected"); + message.custom = $root.google.api.CustomHttpPattern.fromObject(object.custom); + } + if (object.body != null) + message.body = String(object.body); + if (object.responseBody != null) + message.responseBody = String(object.responseBody); + if (object.additionalBindings) { + if (!Array.isArray(object.additionalBindings)) + throw TypeError(".google.api.HttpRule.additionalBindings: array expected"); + message.additionalBindings = []; + for (var i = 0; i < object.additionalBindings.length; ++i) { + if (typeof object.additionalBindings[i] !== "object") + throw TypeError(".google.api.HttpRule.additionalBindings: object expected"); + message.additionalBindings[i] = $root.google.api.HttpRule.fromObject(object.additionalBindings[i]); + } } + return message; + }; - /** - * RunQueryResponse transaction. - * @member {Uint8Array} transaction - * @memberof google.firestore.v1.RunQueryResponse - * @instance - */ - RunQueryResponse.prototype.transaction = $util.newBuffer([]); + /** + * Creates a plain object from a HttpRule message. Also converts values to other types if specified. + * @function toObject + * @memberof google.api.HttpRule + * @static + * @param {google.api.HttpRule} message HttpRule + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + HttpRule.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.arrays || options.defaults) + object.additionalBindings = []; + if (options.defaults) { + object.selector = ""; + object.body = ""; + object.responseBody = ""; + } + if (message.selector != null && message.hasOwnProperty("selector")) + object.selector = message.selector; + if (message.get != null && message.hasOwnProperty("get")) { + object.get = message.get; + if (options.oneofs) + object.pattern = "get"; + } + if (message.put != null && message.hasOwnProperty("put")) { + object.put = message.put; + if (options.oneofs) + object.pattern = "put"; + } + if (message.post != null && message.hasOwnProperty("post")) { + object.post = message.post; + if (options.oneofs) + object.pattern = "post"; + } + if (message["delete"] != null && message.hasOwnProperty("delete")) { + object["delete"] = message["delete"]; + if (options.oneofs) + object.pattern = "delete"; + } + if (message.patch != null && message.hasOwnProperty("patch")) { + object.patch = message.patch; + if (options.oneofs) + object.pattern = "patch"; + } + if (message.body != null && message.hasOwnProperty("body")) + object.body = message.body; + if (message.custom != null && message.hasOwnProperty("custom")) { + object.custom = $root.google.api.CustomHttpPattern.toObject(message.custom, options); + if (options.oneofs) + object.pattern = "custom"; + } + if (message.additionalBindings && message.additionalBindings.length) { + object.additionalBindings = []; + for (var j = 0; j < message.additionalBindings.length; ++j) + object.additionalBindings[j] = $root.google.api.HttpRule.toObject(message.additionalBindings[j], options); + } + if (message.responseBody != null && message.hasOwnProperty("responseBody")) + object.responseBody = message.responseBody; + return object; + }; - /** - * RunQueryResponse document. - * @member {google.firestore.v1.IDocument|null|undefined} document - * @memberof google.firestore.v1.RunQueryResponse - * @instance - */ - RunQueryResponse.prototype.document = null; + /** + * Converts this HttpRule to JSON. + * @function toJSON + * @memberof google.api.HttpRule + * @instance + * @returns {Object.} JSON object + */ + HttpRule.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; - /** - * RunQueryResponse readTime. - * @member {google.protobuf.ITimestamp|null|undefined} readTime - * @memberof google.firestore.v1.RunQueryResponse - * @instance - */ - RunQueryResponse.prototype.readTime = null; + /** + * Gets the default type url for HttpRule + * @function getTypeUrl + * @memberof google.api.HttpRule + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + HttpRule.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.api.HttpRule"; + }; - /** - * RunQueryResponse skippedResults. - * @member {number} skippedResults - * @memberof google.firestore.v1.RunQueryResponse - * @instance - */ - RunQueryResponse.prototype.skippedResults = 0; + return HttpRule; + })(); - /** - * RunQueryResponse done. - * @member {boolean|null|undefined} done - * @memberof google.firestore.v1.RunQueryResponse - * @instance - */ - RunQueryResponse.prototype.done = null; + api.CustomHttpPattern = (function() { - /** - * RunQueryResponse explainMetrics. - * @member {google.firestore.v1.IExplainMetrics|null|undefined} explainMetrics - * @memberof google.firestore.v1.RunQueryResponse - * @instance - */ - RunQueryResponse.prototype.explainMetrics = null; + /** + * Properties of a CustomHttpPattern. + * @memberof google.api + * @interface ICustomHttpPattern + * @property {string|null} [kind] CustomHttpPattern kind + * @property {string|null} [path] CustomHttpPattern path + */ - // OneOf field names bound to virtual getters and setters - var $oneOfFields; + /** + * Constructs a new CustomHttpPattern. + * @memberof google.api + * @classdesc Represents a CustomHttpPattern. + * @implements ICustomHttpPattern + * @constructor + * @param {google.api.ICustomHttpPattern=} [properties] Properties to set + */ + function CustomHttpPattern(properties) { + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } - /** - * RunQueryResponse continuationSelector. - * @member {"done"|undefined} continuationSelector - * @memberof google.firestore.v1.RunQueryResponse - * @instance - */ - Object.defineProperty(RunQueryResponse.prototype, "continuationSelector", { - get: $util.oneOfGetter($oneOfFields = ["done"]), - set: $util.oneOfSetter($oneOfFields) - }); + /** + * CustomHttpPattern kind. + * @member {string} kind + * @memberof google.api.CustomHttpPattern + * @instance + */ + CustomHttpPattern.prototype.kind = ""; - /** - * Creates a RunQueryResponse message from a plain object. Also converts values to their respective internal types. - * @function fromObject - * @memberof google.firestore.v1.RunQueryResponse - * @static - * @param {Object.} object Plain object - * @returns {google.firestore.v1.RunQueryResponse} RunQueryResponse - */ - RunQueryResponse.fromObject = function fromObject(object) { - if (object instanceof $root.google.firestore.v1.RunQueryResponse) - return object; - var message = new $root.google.firestore.v1.RunQueryResponse(); - if (object.transaction != null) - if (typeof object.transaction === "string") - $util.base64.decode(object.transaction, message.transaction = $util.newBuffer($util.base64.length(object.transaction)), 0); - else if (object.transaction.length >= 0) - message.transaction = object.transaction; - if (object.document != null) { - if (typeof object.document !== "object") - throw TypeError(".google.firestore.v1.RunQueryResponse.document: object expected"); - message.document = $root.google.firestore.v1.Document.fromObject(object.document); - } - if (object.readTime != null) { - if (typeof object.readTime !== "object") - throw TypeError(".google.firestore.v1.RunQueryResponse.readTime: object expected"); - message.readTime = $root.google.protobuf.Timestamp.fromObject(object.readTime); - } - if (object.skippedResults != null) - message.skippedResults = object.skippedResults | 0; - if (object.done != null) - message.done = Boolean(object.done); - if (object.explainMetrics != null) { - if (typeof object.explainMetrics !== "object") - throw TypeError(".google.firestore.v1.RunQueryResponse.explainMetrics: object expected"); - message.explainMetrics = $root.google.firestore.v1.ExplainMetrics.fromObject(object.explainMetrics); - } - return message; - }; + /** + * CustomHttpPattern path. + * @member {string} path + * @memberof google.api.CustomHttpPattern + * @instance + */ + CustomHttpPattern.prototype.path = ""; - /** - * Creates a plain object from a RunQueryResponse message. Also converts values to other types if specified. - * @function toObject - * @memberof google.firestore.v1.RunQueryResponse - * @static - * @param {google.firestore.v1.RunQueryResponse} message RunQueryResponse - * @param {$protobuf.IConversionOptions} [options] Conversion options - * @returns {Object.} Plain object - */ - RunQueryResponse.toObject = function toObject(message, options) { - if (!options) - options = {}; - var object = {}; - if (options.defaults) { - object.document = null; - if (options.bytes === String) - object.transaction = ""; - else { - object.transaction = []; - if (options.bytes !== Array) - object.transaction = $util.newBuffer(object.transaction); - } - object.readTime = null; - object.skippedResults = 0; - object.explainMetrics = null; - } - if (message.document != null && message.hasOwnProperty("document")) - object.document = $root.google.firestore.v1.Document.toObject(message.document, options); - if (message.transaction != null && message.hasOwnProperty("transaction")) - object.transaction = options.bytes === String ? $util.base64.encode(message.transaction, 0, message.transaction.length) : options.bytes === Array ? Array.prototype.slice.call(message.transaction) : message.transaction; - if (message.readTime != null && message.hasOwnProperty("readTime")) - object.readTime = $root.google.protobuf.Timestamp.toObject(message.readTime, options); - if (message.skippedResults != null && message.hasOwnProperty("skippedResults")) - object.skippedResults = message.skippedResults; - if (message.done != null && message.hasOwnProperty("done")) { - object.done = message.done; - if (options.oneofs) - object.continuationSelector = "done"; - } - if (message.explainMetrics != null && message.hasOwnProperty("explainMetrics")) - object.explainMetrics = $root.google.firestore.v1.ExplainMetrics.toObject(message.explainMetrics, options); + /** + * Creates a CustomHttpPattern message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.api.CustomHttpPattern + * @static + * @param {Object.} object Plain object + * @returns {google.api.CustomHttpPattern} CustomHttpPattern + */ + CustomHttpPattern.fromObject = function fromObject(object) { + if (object instanceof $root.google.api.CustomHttpPattern) return object; - }; + var message = new $root.google.api.CustomHttpPattern(); + if (object.kind != null) + message.kind = String(object.kind); + if (object.path != null) + message.path = String(object.path); + return message; + }; - /** - * Converts this RunQueryResponse to JSON. - * @function toJSON - * @memberof google.firestore.v1.RunQueryResponse - * @instance - * @returns {Object.} JSON object - */ - RunQueryResponse.prototype.toJSON = function toJSON() { - return this.constructor.toObject(this, $protobuf.util.toJSONOptions); - }; + /** + * Creates a plain object from a CustomHttpPattern message. Also converts values to other types if specified. + * @function toObject + * @memberof google.api.CustomHttpPattern + * @static + * @param {google.api.CustomHttpPattern} message CustomHttpPattern + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + CustomHttpPattern.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.defaults) { + object.kind = ""; + object.path = ""; + } + if (message.kind != null && message.hasOwnProperty("kind")) + object.kind = message.kind; + if (message.path != null && message.hasOwnProperty("path")) + object.path = message.path; + return object; + }; - /** - * Gets the default type url for RunQueryResponse - * @function getTypeUrl - * @memberof google.firestore.v1.RunQueryResponse - * @static - * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") - * @returns {string} The default type url - */ - RunQueryResponse.getTypeUrl = function getTypeUrl(typeUrlPrefix) { - if (typeUrlPrefix === undefined) { - typeUrlPrefix = "type.googleapis.com"; - } - return typeUrlPrefix + "/google.firestore.v1.RunQueryResponse"; - }; + /** + * Converts this CustomHttpPattern to JSON. + * @function toJSON + * @memberof google.api.CustomHttpPattern + * @instance + * @returns {Object.} JSON object + */ + CustomHttpPattern.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; - return RunQueryResponse; - })(); + /** + * Gets the default type url for CustomHttpPattern + * @function getTypeUrl + * @memberof google.api.CustomHttpPattern + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + CustomHttpPattern.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.api.CustomHttpPattern"; + }; - v1.ExecutePipelineRequest = (function() { + return CustomHttpPattern; + })(); - /** - * Properties of an ExecutePipelineRequest. - * @memberof google.firestore.v1 - * @interface IExecutePipelineRequest - * @property {string|null} [database] ExecutePipelineRequest database - * @property {google.firestore.v1.IStructuredPipeline|null} [structuredPipeline] ExecutePipelineRequest structuredPipeline - * @property {Uint8Array|null} [transaction] ExecutePipelineRequest transaction - * @property {google.firestore.v1.ITransactionOptions|null} [newTransaction] ExecutePipelineRequest newTransaction - * @property {google.protobuf.ITimestamp|null} [readTime] ExecutePipelineRequest readTime - */ + api.CommonLanguageSettings = (function() { - /** - * Constructs a new ExecutePipelineRequest. - * @memberof google.firestore.v1 - * @classdesc Represents an ExecutePipelineRequest. - * @implements IExecutePipelineRequest - * @constructor - * @param {google.firestore.v1.IExecutePipelineRequest=} [properties] Properties to set - */ - function ExecutePipelineRequest(properties) { - if (properties) - for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) - if (properties[keys[i]] != null) - this[keys[i]] = properties[keys[i]]; - } + /** + * Properties of a CommonLanguageSettings. + * @memberof google.api + * @interface ICommonLanguageSettings + * @property {string|null} [referenceDocsUri] CommonLanguageSettings referenceDocsUri + * @property {Array.|null} [destinations] CommonLanguageSettings destinations + */ - /** - * ExecutePipelineRequest database. - * @member {string} database - * @memberof google.firestore.v1.ExecutePipelineRequest - * @instance - */ - ExecutePipelineRequest.prototype.database = ""; + /** + * Constructs a new CommonLanguageSettings. + * @memberof google.api + * @classdesc Represents a CommonLanguageSettings. + * @implements ICommonLanguageSettings + * @constructor + * @param {google.api.ICommonLanguageSettings=} [properties] Properties to set + */ + function CommonLanguageSettings(properties) { + this.destinations = []; + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } - /** - * ExecutePipelineRequest structuredPipeline. - * @member {google.firestore.v1.IStructuredPipeline|null|undefined} structuredPipeline - * @memberof google.firestore.v1.ExecutePipelineRequest - * @instance - */ - ExecutePipelineRequest.prototype.structuredPipeline = null; + /** + * CommonLanguageSettings referenceDocsUri. + * @member {string} referenceDocsUri + * @memberof google.api.CommonLanguageSettings + * @instance + */ + CommonLanguageSettings.prototype.referenceDocsUri = ""; - /** - * ExecutePipelineRequest transaction. - * @member {Uint8Array|null|undefined} transaction - * @memberof google.firestore.v1.ExecutePipelineRequest - * @instance - */ - ExecutePipelineRequest.prototype.transaction = null; + /** + * CommonLanguageSettings destinations. + * @member {Array.} destinations + * @memberof google.api.CommonLanguageSettings + * @instance + */ + CommonLanguageSettings.prototype.destinations = $util.emptyArray; - /** - * ExecutePipelineRequest newTransaction. - * @member {google.firestore.v1.ITransactionOptions|null|undefined} newTransaction - * @memberof google.firestore.v1.ExecutePipelineRequest - * @instance - */ - ExecutePipelineRequest.prototype.newTransaction = null; + /** + * Creates a CommonLanguageSettings message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.api.CommonLanguageSettings + * @static + * @param {Object.} object Plain object + * @returns {google.api.CommonLanguageSettings} CommonLanguageSettings + */ + CommonLanguageSettings.fromObject = function fromObject(object) { + if (object instanceof $root.google.api.CommonLanguageSettings) + return object; + var message = new $root.google.api.CommonLanguageSettings(); + if (object.referenceDocsUri != null) + message.referenceDocsUri = String(object.referenceDocsUri); + if (object.destinations) { + if (!Array.isArray(object.destinations)) + throw TypeError(".google.api.CommonLanguageSettings.destinations: array expected"); + message.destinations = []; + for (var i = 0; i < object.destinations.length; ++i) + switch (object.destinations[i]) { + default: + if (typeof object.destinations[i] === "number") { + message.destinations[i] = object.destinations[i]; + break; + } + case "CLIENT_LIBRARY_DESTINATION_UNSPECIFIED": + case 0: + message.destinations[i] = 0; + break; + case "GITHUB": + case 10: + message.destinations[i] = 10; + break; + case "PACKAGE_MANAGER": + case 20: + message.destinations[i] = 20; + break; + } + } + return message; + }; - /** - * ExecutePipelineRequest readTime. - * @member {google.protobuf.ITimestamp|null|undefined} readTime - * @memberof google.firestore.v1.ExecutePipelineRequest - * @instance - */ - ExecutePipelineRequest.prototype.readTime = null; + /** + * Creates a plain object from a CommonLanguageSettings message. Also converts values to other types if specified. + * @function toObject + * @memberof google.api.CommonLanguageSettings + * @static + * @param {google.api.CommonLanguageSettings} message CommonLanguageSettings + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + CommonLanguageSettings.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.arrays || options.defaults) + object.destinations = []; + if (options.defaults) + object.referenceDocsUri = ""; + if (message.referenceDocsUri != null && message.hasOwnProperty("referenceDocsUri")) + object.referenceDocsUri = message.referenceDocsUri; + if (message.destinations && message.destinations.length) { + object.destinations = []; + for (var j = 0; j < message.destinations.length; ++j) + object.destinations[j] = options.enums === String ? $root.google.api.ClientLibraryDestination[message.destinations[j]] === undefined ? message.destinations[j] : $root.google.api.ClientLibraryDestination[message.destinations[j]] : message.destinations[j]; + } + return object; + }; - // OneOf field names bound to virtual getters and setters - var $oneOfFields; + /** + * Converts this CommonLanguageSettings to JSON. + * @function toJSON + * @memberof google.api.CommonLanguageSettings + * @instance + * @returns {Object.} JSON object + */ + CommonLanguageSettings.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; - /** - * ExecutePipelineRequest pipelineType. - * @member {"structuredPipeline"|undefined} pipelineType - * @memberof google.firestore.v1.ExecutePipelineRequest - * @instance - */ - Object.defineProperty(ExecutePipelineRequest.prototype, "pipelineType", { - get: $util.oneOfGetter($oneOfFields = ["structuredPipeline"]), - set: $util.oneOfSetter($oneOfFields) - }); + /** + * Gets the default type url for CommonLanguageSettings + * @function getTypeUrl + * @memberof google.api.CommonLanguageSettings + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + CommonLanguageSettings.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.api.CommonLanguageSettings"; + }; - /** - * ExecutePipelineRequest consistencySelector. - * @member {"transaction"|"newTransaction"|"readTime"|undefined} consistencySelector - * @memberof google.firestore.v1.ExecutePipelineRequest - * @instance - */ - Object.defineProperty(ExecutePipelineRequest.prototype, "consistencySelector", { - get: $util.oneOfGetter($oneOfFields = ["transaction", "newTransaction", "readTime"]), - set: $util.oneOfSetter($oneOfFields) - }); + return CommonLanguageSettings; + })(); - /** - * Creates an ExecutePipelineRequest message from a plain object. Also converts values to their respective internal types. - * @function fromObject - * @memberof google.firestore.v1.ExecutePipelineRequest - * @static - * @param {Object.} object Plain object - * @returns {google.firestore.v1.ExecutePipelineRequest} ExecutePipelineRequest - */ - ExecutePipelineRequest.fromObject = function fromObject(object) { - if (object instanceof $root.google.firestore.v1.ExecutePipelineRequest) - return object; - var message = new $root.google.firestore.v1.ExecutePipelineRequest(); - if (object.database != null) - message.database = String(object.database); - if (object.structuredPipeline != null) { - if (typeof object.structuredPipeline !== "object") - throw TypeError(".google.firestore.v1.ExecutePipelineRequest.structuredPipeline: object expected"); - message.structuredPipeline = $root.google.firestore.v1.StructuredPipeline.fromObject(object.structuredPipeline); - } - if (object.transaction != null) - if (typeof object.transaction === "string") - $util.base64.decode(object.transaction, message.transaction = $util.newBuffer($util.base64.length(object.transaction)), 0); - else if (object.transaction.length >= 0) - message.transaction = object.transaction; - if (object.newTransaction != null) { - if (typeof object.newTransaction !== "object") - throw TypeError(".google.firestore.v1.ExecutePipelineRequest.newTransaction: object expected"); - message.newTransaction = $root.google.firestore.v1.TransactionOptions.fromObject(object.newTransaction); - } - if (object.readTime != null) { - if (typeof object.readTime !== "object") - throw TypeError(".google.firestore.v1.ExecutePipelineRequest.readTime: object expected"); - message.readTime = $root.google.protobuf.Timestamp.fromObject(object.readTime); - } - return message; - }; + api.ClientLibrarySettings = (function() { - /** - * Creates a plain object from an ExecutePipelineRequest message. Also converts values to other types if specified. - * @function toObject - * @memberof google.firestore.v1.ExecutePipelineRequest - * @static - * @param {google.firestore.v1.ExecutePipelineRequest} message ExecutePipelineRequest - * @param {$protobuf.IConversionOptions} [options] Conversion options - * @returns {Object.} Plain object - */ - ExecutePipelineRequest.toObject = function toObject(message, options) { - if (!options) - options = {}; - var object = {}; - if (options.defaults) - object.database = ""; - if (message.database != null && message.hasOwnProperty("database")) - object.database = message.database; - if (message.structuredPipeline != null && message.hasOwnProperty("structuredPipeline")) { - object.structuredPipeline = $root.google.firestore.v1.StructuredPipeline.toObject(message.structuredPipeline, options); - if (options.oneofs) - object.pipelineType = "structuredPipeline"; - } - if (message.transaction != null && message.hasOwnProperty("transaction")) { - object.transaction = options.bytes === String ? $util.base64.encode(message.transaction, 0, message.transaction.length) : options.bytes === Array ? Array.prototype.slice.call(message.transaction) : message.transaction; - if (options.oneofs) - object.consistencySelector = "transaction"; - } - if (message.newTransaction != null && message.hasOwnProperty("newTransaction")) { - object.newTransaction = $root.google.firestore.v1.TransactionOptions.toObject(message.newTransaction, options); - if (options.oneofs) - object.consistencySelector = "newTransaction"; - } - if (message.readTime != null && message.hasOwnProperty("readTime")) { - object.readTime = $root.google.protobuf.Timestamp.toObject(message.readTime, options); - if (options.oneofs) - object.consistencySelector = "readTime"; - } - return object; - }; + /** + * Properties of a ClientLibrarySettings. + * @memberof google.api + * @interface IClientLibrarySettings + * @property {string|null} [version] ClientLibrarySettings version + * @property {google.api.LaunchStage|null} [launchStage] ClientLibrarySettings launchStage + * @property {boolean|null} [restNumericEnums] ClientLibrarySettings restNumericEnums + * @property {google.api.IJavaSettings|null} [javaSettings] ClientLibrarySettings javaSettings + * @property {google.api.ICppSettings|null} [cppSettings] ClientLibrarySettings cppSettings + * @property {google.api.IPhpSettings|null} [phpSettings] ClientLibrarySettings phpSettings + * @property {google.api.IPythonSettings|null} [pythonSettings] ClientLibrarySettings pythonSettings + * @property {google.api.INodeSettings|null} [nodeSettings] ClientLibrarySettings nodeSettings + * @property {google.api.IDotnetSettings|null} [dotnetSettings] ClientLibrarySettings dotnetSettings + * @property {google.api.IRubySettings|null} [rubySettings] ClientLibrarySettings rubySettings + * @property {google.api.IGoSettings|null} [goSettings] ClientLibrarySettings goSettings + */ - /** - * Converts this ExecutePipelineRequest to JSON. - * @function toJSON - * @memberof google.firestore.v1.ExecutePipelineRequest - * @instance - * @returns {Object.} JSON object - */ - ExecutePipelineRequest.prototype.toJSON = function toJSON() { - return this.constructor.toObject(this, $protobuf.util.toJSONOptions); - }; + /** + * Constructs a new ClientLibrarySettings. + * @memberof google.api + * @classdesc Represents a ClientLibrarySettings. + * @implements IClientLibrarySettings + * @constructor + * @param {google.api.IClientLibrarySettings=} [properties] Properties to set + */ + function ClientLibrarySettings(properties) { + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } - /** - * Gets the default type url for ExecutePipelineRequest - * @function getTypeUrl - * @memberof google.firestore.v1.ExecutePipelineRequest - * @static - * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") - * @returns {string} The default type url - */ - ExecutePipelineRequest.getTypeUrl = function getTypeUrl(typeUrlPrefix) { - if (typeUrlPrefix === undefined) { - typeUrlPrefix = "type.googleapis.com"; - } - return typeUrlPrefix + "/google.firestore.v1.ExecutePipelineRequest"; - }; + /** + * ClientLibrarySettings version. + * @member {string} version + * @memberof google.api.ClientLibrarySettings + * @instance + */ + ClientLibrarySettings.prototype.version = ""; - return ExecutePipelineRequest; - })(); + /** + * ClientLibrarySettings launchStage. + * @member {google.api.LaunchStage} launchStage + * @memberof google.api.ClientLibrarySettings + * @instance + */ + ClientLibrarySettings.prototype.launchStage = 0; - v1.ExecutePipelineResponse = (function() { + /** + * ClientLibrarySettings restNumericEnums. + * @member {boolean} restNumericEnums + * @memberof google.api.ClientLibrarySettings + * @instance + */ + ClientLibrarySettings.prototype.restNumericEnums = false; - /** - * Properties of an ExecutePipelineResponse. - * @memberof google.firestore.v1 - * @interface IExecutePipelineResponse - * @property {Uint8Array|null} [transaction] ExecutePipelineResponse transaction - * @property {Array.|null} [results] ExecutePipelineResponse results - * @property {google.protobuf.ITimestamp|null} [executionTime] ExecutePipelineResponse executionTime - */ + /** + * ClientLibrarySettings javaSettings. + * @member {google.api.IJavaSettings|null|undefined} javaSettings + * @memberof google.api.ClientLibrarySettings + * @instance + */ + ClientLibrarySettings.prototype.javaSettings = null; - /** - * Constructs a new ExecutePipelineResponse. - * @memberof google.firestore.v1 - * @classdesc Represents an ExecutePipelineResponse. - * @implements IExecutePipelineResponse - * @constructor - * @param {google.firestore.v1.IExecutePipelineResponse=} [properties] Properties to set - */ - function ExecutePipelineResponse(properties) { - this.results = []; - if (properties) - for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) - if (properties[keys[i]] != null) - this[keys[i]] = properties[keys[i]]; - } + /** + * ClientLibrarySettings cppSettings. + * @member {google.api.ICppSettings|null|undefined} cppSettings + * @memberof google.api.ClientLibrarySettings + * @instance + */ + ClientLibrarySettings.prototype.cppSettings = null; - /** - * ExecutePipelineResponse transaction. - * @member {Uint8Array} transaction - * @memberof google.firestore.v1.ExecutePipelineResponse - * @instance - */ - ExecutePipelineResponse.prototype.transaction = $util.newBuffer([]); + /** + * ClientLibrarySettings phpSettings. + * @member {google.api.IPhpSettings|null|undefined} phpSettings + * @memberof google.api.ClientLibrarySettings + * @instance + */ + ClientLibrarySettings.prototype.phpSettings = null; - /** - * ExecutePipelineResponse results. - * @member {Array.} results - * @memberof google.firestore.v1.ExecutePipelineResponse - * @instance - */ - ExecutePipelineResponse.prototype.results = $util.emptyArray; + /** + * ClientLibrarySettings pythonSettings. + * @member {google.api.IPythonSettings|null|undefined} pythonSettings + * @memberof google.api.ClientLibrarySettings + * @instance + */ + ClientLibrarySettings.prototype.pythonSettings = null; - /** - * ExecutePipelineResponse executionTime. - * @member {google.protobuf.ITimestamp|null|undefined} executionTime - * @memberof google.firestore.v1.ExecutePipelineResponse - * @instance - */ - ExecutePipelineResponse.prototype.executionTime = null; + /** + * ClientLibrarySettings nodeSettings. + * @member {google.api.INodeSettings|null|undefined} nodeSettings + * @memberof google.api.ClientLibrarySettings + * @instance + */ + ClientLibrarySettings.prototype.nodeSettings = null; - /** - * Creates an ExecutePipelineResponse message from a plain object. Also converts values to their respective internal types. - * @function fromObject - * @memberof google.firestore.v1.ExecutePipelineResponse - * @static - * @param {Object.} object Plain object - * @returns {google.firestore.v1.ExecutePipelineResponse} ExecutePipelineResponse - */ - ExecutePipelineResponse.fromObject = function fromObject(object) { - if (object instanceof $root.google.firestore.v1.ExecutePipelineResponse) - return object; - var message = new $root.google.firestore.v1.ExecutePipelineResponse(); - if (object.transaction != null) - if (typeof object.transaction === "string") - $util.base64.decode(object.transaction, message.transaction = $util.newBuffer($util.base64.length(object.transaction)), 0); - else if (object.transaction.length >= 0) - message.transaction = object.transaction; - if (object.results) { - if (!Array.isArray(object.results)) - throw TypeError(".google.firestore.v1.ExecutePipelineResponse.results: array expected"); - message.results = []; - for (var i = 0; i < object.results.length; ++i) { - if (typeof object.results[i] !== "object") - throw TypeError(".google.firestore.v1.ExecutePipelineResponse.results: object expected"); - message.results[i] = $root.google.firestore.v1.Document.fromObject(object.results[i]); - } - } - if (object.executionTime != null) { - if (typeof object.executionTime !== "object") - throw TypeError(".google.firestore.v1.ExecutePipelineResponse.executionTime: object expected"); - message.executionTime = $root.google.protobuf.Timestamp.fromObject(object.executionTime); - } - return message; - }; + /** + * ClientLibrarySettings dotnetSettings. + * @member {google.api.IDotnetSettings|null|undefined} dotnetSettings + * @memberof google.api.ClientLibrarySettings + * @instance + */ + ClientLibrarySettings.prototype.dotnetSettings = null; - /** - * Creates a plain object from an ExecutePipelineResponse message. Also converts values to other types if specified. - * @function toObject - * @memberof google.firestore.v1.ExecutePipelineResponse - * @static - * @param {google.firestore.v1.ExecutePipelineResponse} message ExecutePipelineResponse - * @param {$protobuf.IConversionOptions} [options] Conversion options - * @returns {Object.} Plain object - */ - ExecutePipelineResponse.toObject = function toObject(message, options) { - if (!options) - options = {}; - var object = {}; - if (options.arrays || options.defaults) - object.results = []; - if (options.defaults) { - if (options.bytes === String) - object.transaction = ""; - else { - object.transaction = []; - if (options.bytes !== Array) - object.transaction = $util.newBuffer(object.transaction); - } - object.executionTime = null; - } - if (message.transaction != null && message.hasOwnProperty("transaction")) - object.transaction = options.bytes === String ? $util.base64.encode(message.transaction, 0, message.transaction.length) : options.bytes === Array ? Array.prototype.slice.call(message.transaction) : message.transaction; - if (message.results && message.results.length) { - object.results = []; - for (var j = 0; j < message.results.length; ++j) - object.results[j] = $root.google.firestore.v1.Document.toObject(message.results[j], options); - } - if (message.executionTime != null && message.hasOwnProperty("executionTime")) - object.executionTime = $root.google.protobuf.Timestamp.toObject(message.executionTime, options); + /** + * ClientLibrarySettings rubySettings. + * @member {google.api.IRubySettings|null|undefined} rubySettings + * @memberof google.api.ClientLibrarySettings + * @instance + */ + ClientLibrarySettings.prototype.rubySettings = null; + + /** + * ClientLibrarySettings goSettings. + * @member {google.api.IGoSettings|null|undefined} goSettings + * @memberof google.api.ClientLibrarySettings + * @instance + */ + ClientLibrarySettings.prototype.goSettings = null; + + /** + * Creates a ClientLibrarySettings message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.api.ClientLibrarySettings + * @static + * @param {Object.} object Plain object + * @returns {google.api.ClientLibrarySettings} ClientLibrarySettings + */ + ClientLibrarySettings.fromObject = function fromObject(object) { + if (object instanceof $root.google.api.ClientLibrarySettings) return object; - }; + var message = new $root.google.api.ClientLibrarySettings(); + if (object.version != null) + message.version = String(object.version); + switch (object.launchStage) { + default: + if (typeof object.launchStage === "number") { + message.launchStage = object.launchStage; + break; + } + break; + case "LAUNCH_STAGE_UNSPECIFIED": + case 0: + message.launchStage = 0; + break; + case "UNIMPLEMENTED": + case 6: + message.launchStage = 6; + break; + case "PRELAUNCH": + case 7: + message.launchStage = 7; + break; + case "EARLY_ACCESS": + case 1: + message.launchStage = 1; + break; + case "ALPHA": + case 2: + message.launchStage = 2; + break; + case "BETA": + case 3: + message.launchStage = 3; + break; + case "GA": + case 4: + message.launchStage = 4; + break; + case "DEPRECATED": + case 5: + message.launchStage = 5; + break; + } + if (object.restNumericEnums != null) + message.restNumericEnums = Boolean(object.restNumericEnums); + if (object.javaSettings != null) { + if (typeof object.javaSettings !== "object") + throw TypeError(".google.api.ClientLibrarySettings.javaSettings: object expected"); + message.javaSettings = $root.google.api.JavaSettings.fromObject(object.javaSettings); + } + if (object.cppSettings != null) { + if (typeof object.cppSettings !== "object") + throw TypeError(".google.api.ClientLibrarySettings.cppSettings: object expected"); + message.cppSettings = $root.google.api.CppSettings.fromObject(object.cppSettings); + } + if (object.phpSettings != null) { + if (typeof object.phpSettings !== "object") + throw TypeError(".google.api.ClientLibrarySettings.phpSettings: object expected"); + message.phpSettings = $root.google.api.PhpSettings.fromObject(object.phpSettings); + } + if (object.pythonSettings != null) { + if (typeof object.pythonSettings !== "object") + throw TypeError(".google.api.ClientLibrarySettings.pythonSettings: object expected"); + message.pythonSettings = $root.google.api.PythonSettings.fromObject(object.pythonSettings); + } + if (object.nodeSettings != null) { + if (typeof object.nodeSettings !== "object") + throw TypeError(".google.api.ClientLibrarySettings.nodeSettings: object expected"); + message.nodeSettings = $root.google.api.NodeSettings.fromObject(object.nodeSettings); + } + if (object.dotnetSettings != null) { + if (typeof object.dotnetSettings !== "object") + throw TypeError(".google.api.ClientLibrarySettings.dotnetSettings: object expected"); + message.dotnetSettings = $root.google.api.DotnetSettings.fromObject(object.dotnetSettings); + } + if (object.rubySettings != null) { + if (typeof object.rubySettings !== "object") + throw TypeError(".google.api.ClientLibrarySettings.rubySettings: object expected"); + message.rubySettings = $root.google.api.RubySettings.fromObject(object.rubySettings); + } + if (object.goSettings != null) { + if (typeof object.goSettings !== "object") + throw TypeError(".google.api.ClientLibrarySettings.goSettings: object expected"); + message.goSettings = $root.google.api.GoSettings.fromObject(object.goSettings); + } + return message; + }; - /** - * Converts this ExecutePipelineResponse to JSON. - * @function toJSON - * @memberof google.firestore.v1.ExecutePipelineResponse - * @instance - * @returns {Object.} JSON object - */ - ExecutePipelineResponse.prototype.toJSON = function toJSON() { - return this.constructor.toObject(this, $protobuf.util.toJSONOptions); - }; + /** + * Creates a plain object from a ClientLibrarySettings message. Also converts values to other types if specified. + * @function toObject + * @memberof google.api.ClientLibrarySettings + * @static + * @param {google.api.ClientLibrarySettings} message ClientLibrarySettings + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + ClientLibrarySettings.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.defaults) { + object.version = ""; + object.launchStage = options.enums === String ? "LAUNCH_STAGE_UNSPECIFIED" : 0; + object.restNumericEnums = false; + object.javaSettings = null; + object.cppSettings = null; + object.phpSettings = null; + object.pythonSettings = null; + object.nodeSettings = null; + object.dotnetSettings = null; + object.rubySettings = null; + object.goSettings = null; + } + if (message.version != null && message.hasOwnProperty("version")) + object.version = message.version; + if (message.launchStage != null && message.hasOwnProperty("launchStage")) + object.launchStage = options.enums === String ? $root.google.api.LaunchStage[message.launchStage] === undefined ? message.launchStage : $root.google.api.LaunchStage[message.launchStage] : message.launchStage; + if (message.restNumericEnums != null && message.hasOwnProperty("restNumericEnums")) + object.restNumericEnums = message.restNumericEnums; + if (message.javaSettings != null && message.hasOwnProperty("javaSettings")) + object.javaSettings = $root.google.api.JavaSettings.toObject(message.javaSettings, options); + if (message.cppSettings != null && message.hasOwnProperty("cppSettings")) + object.cppSettings = $root.google.api.CppSettings.toObject(message.cppSettings, options); + if (message.phpSettings != null && message.hasOwnProperty("phpSettings")) + object.phpSettings = $root.google.api.PhpSettings.toObject(message.phpSettings, options); + if (message.pythonSettings != null && message.hasOwnProperty("pythonSettings")) + object.pythonSettings = $root.google.api.PythonSettings.toObject(message.pythonSettings, options); + if (message.nodeSettings != null && message.hasOwnProperty("nodeSettings")) + object.nodeSettings = $root.google.api.NodeSettings.toObject(message.nodeSettings, options); + if (message.dotnetSettings != null && message.hasOwnProperty("dotnetSettings")) + object.dotnetSettings = $root.google.api.DotnetSettings.toObject(message.dotnetSettings, options); + if (message.rubySettings != null && message.hasOwnProperty("rubySettings")) + object.rubySettings = $root.google.api.RubySettings.toObject(message.rubySettings, options); + if (message.goSettings != null && message.hasOwnProperty("goSettings")) + object.goSettings = $root.google.api.GoSettings.toObject(message.goSettings, options); + return object; + }; - /** - * Gets the default type url for ExecutePipelineResponse - * @function getTypeUrl - * @memberof google.firestore.v1.ExecutePipelineResponse - * @static - * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") - * @returns {string} The default type url - */ - ExecutePipelineResponse.getTypeUrl = function getTypeUrl(typeUrlPrefix) { - if (typeUrlPrefix === undefined) { - typeUrlPrefix = "type.googleapis.com"; - } - return typeUrlPrefix + "/google.firestore.v1.ExecutePipelineResponse"; - }; + /** + * Converts this ClientLibrarySettings to JSON. + * @function toJSON + * @memberof google.api.ClientLibrarySettings + * @instance + * @returns {Object.} JSON object + */ + ClientLibrarySettings.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; - return ExecutePipelineResponse; - })(); + /** + * Gets the default type url for ClientLibrarySettings + * @function getTypeUrl + * @memberof google.api.ClientLibrarySettings + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + ClientLibrarySettings.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.api.ClientLibrarySettings"; + }; - v1.RunAggregationQueryRequest = (function() { + return ClientLibrarySettings; + })(); - /** - * Properties of a RunAggregationQueryRequest. - * @memberof google.firestore.v1 - * @interface IRunAggregationQueryRequest - * @property {string|null} [parent] RunAggregationQueryRequest parent - * @property {google.firestore.v1.IStructuredAggregationQuery|null} [structuredAggregationQuery] RunAggregationQueryRequest structuredAggregationQuery - * @property {Uint8Array|null} [transaction] RunAggregationQueryRequest transaction - * @property {google.firestore.v1.ITransactionOptions|null} [newTransaction] RunAggregationQueryRequest newTransaction - * @property {google.protobuf.ITimestamp|null} [readTime] RunAggregationQueryRequest readTime - * @property {google.firestore.v1.IExplainOptions|null} [explainOptions] RunAggregationQueryRequest explainOptions - */ + api.Publishing = (function() { - /** - * Constructs a new RunAggregationQueryRequest. - * @memberof google.firestore.v1 - * @classdesc Represents a RunAggregationQueryRequest. - * @implements IRunAggregationQueryRequest - * @constructor - * @param {google.firestore.v1.IRunAggregationQueryRequest=} [properties] Properties to set - */ - function RunAggregationQueryRequest(properties) { - if (properties) - for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) - if (properties[keys[i]] != null) - this[keys[i]] = properties[keys[i]]; - } + /** + * Properties of a Publishing. + * @memberof google.api + * @interface IPublishing + * @property {Array.|null} [methodSettings] Publishing methodSettings + * @property {string|null} [newIssueUri] Publishing newIssueUri + * @property {string|null} [documentationUri] Publishing documentationUri + * @property {string|null} [apiShortName] Publishing apiShortName + * @property {string|null} [githubLabel] Publishing githubLabel + * @property {Array.|null} [codeownerGithubTeams] Publishing codeownerGithubTeams + * @property {string|null} [docTagPrefix] Publishing docTagPrefix + * @property {google.api.ClientLibraryOrganization|null} [organization] Publishing organization + * @property {Array.|null} [librarySettings] Publishing librarySettings + * @property {string|null} [protoReferenceDocumentationUri] Publishing protoReferenceDocumentationUri + * @property {string|null} [restReferenceDocumentationUri] Publishing restReferenceDocumentationUri + */ - /** - * RunAggregationQueryRequest parent. - * @member {string} parent - * @memberof google.firestore.v1.RunAggregationQueryRequest - * @instance - */ - RunAggregationQueryRequest.prototype.parent = ""; + /** + * Constructs a new Publishing. + * @memberof google.api + * @classdesc Represents a Publishing. + * @implements IPublishing + * @constructor + * @param {google.api.IPublishing=} [properties] Properties to set + */ + function Publishing(properties) { + this.methodSettings = []; + this.codeownerGithubTeams = []; + this.librarySettings = []; + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } - /** - * RunAggregationQueryRequest structuredAggregationQuery. - * @member {google.firestore.v1.IStructuredAggregationQuery|null|undefined} structuredAggregationQuery - * @memberof google.firestore.v1.RunAggregationQueryRequest - * @instance - */ - RunAggregationQueryRequest.prototype.structuredAggregationQuery = null; + /** + * Publishing methodSettings. + * @member {Array.} methodSettings + * @memberof google.api.Publishing + * @instance + */ + Publishing.prototype.methodSettings = $util.emptyArray; - /** - * RunAggregationQueryRequest transaction. - * @member {Uint8Array|null|undefined} transaction - * @memberof google.firestore.v1.RunAggregationQueryRequest - * @instance - */ - RunAggregationQueryRequest.prototype.transaction = null; + /** + * Publishing newIssueUri. + * @member {string} newIssueUri + * @memberof google.api.Publishing + * @instance + */ + Publishing.prototype.newIssueUri = ""; - /** - * RunAggregationQueryRequest newTransaction. - * @member {google.firestore.v1.ITransactionOptions|null|undefined} newTransaction - * @memberof google.firestore.v1.RunAggregationQueryRequest - * @instance - */ - RunAggregationQueryRequest.prototype.newTransaction = null; + /** + * Publishing documentationUri. + * @member {string} documentationUri + * @memberof google.api.Publishing + * @instance + */ + Publishing.prototype.documentationUri = ""; - /** - * RunAggregationQueryRequest readTime. - * @member {google.protobuf.ITimestamp|null|undefined} readTime - * @memberof google.firestore.v1.RunAggregationQueryRequest - * @instance - */ - RunAggregationQueryRequest.prototype.readTime = null; + /** + * Publishing apiShortName. + * @member {string} apiShortName + * @memberof google.api.Publishing + * @instance + */ + Publishing.prototype.apiShortName = ""; - /** - * RunAggregationQueryRequest explainOptions. - * @member {google.firestore.v1.IExplainOptions|null|undefined} explainOptions - * @memberof google.firestore.v1.RunAggregationQueryRequest - * @instance - */ - RunAggregationQueryRequest.prototype.explainOptions = null; + /** + * Publishing githubLabel. + * @member {string} githubLabel + * @memberof google.api.Publishing + * @instance + */ + Publishing.prototype.githubLabel = ""; - // OneOf field names bound to virtual getters and setters - var $oneOfFields; + /** + * Publishing codeownerGithubTeams. + * @member {Array.} codeownerGithubTeams + * @memberof google.api.Publishing + * @instance + */ + Publishing.prototype.codeownerGithubTeams = $util.emptyArray; - /** - * RunAggregationQueryRequest queryType. - * @member {"structuredAggregationQuery"|undefined} queryType - * @memberof google.firestore.v1.RunAggregationQueryRequest - * @instance - */ - Object.defineProperty(RunAggregationQueryRequest.prototype, "queryType", { - get: $util.oneOfGetter($oneOfFields = ["structuredAggregationQuery"]), - set: $util.oneOfSetter($oneOfFields) - }); + /** + * Publishing docTagPrefix. + * @member {string} docTagPrefix + * @memberof google.api.Publishing + * @instance + */ + Publishing.prototype.docTagPrefix = ""; - /** - * RunAggregationQueryRequest consistencySelector. - * @member {"transaction"|"newTransaction"|"readTime"|undefined} consistencySelector - * @memberof google.firestore.v1.RunAggregationQueryRequest - * @instance - */ - Object.defineProperty(RunAggregationQueryRequest.prototype, "consistencySelector", { - get: $util.oneOfGetter($oneOfFields = ["transaction", "newTransaction", "readTime"]), - set: $util.oneOfSetter($oneOfFields) - }); + /** + * Publishing organization. + * @member {google.api.ClientLibraryOrganization} organization + * @memberof google.api.Publishing + * @instance + */ + Publishing.prototype.organization = 0; - /** - * Creates a RunAggregationQueryRequest message from a plain object. Also converts values to their respective internal types. - * @function fromObject - * @memberof google.firestore.v1.RunAggregationQueryRequest - * @static - * @param {Object.} object Plain object - * @returns {google.firestore.v1.RunAggregationQueryRequest} RunAggregationQueryRequest - */ - RunAggregationQueryRequest.fromObject = function fromObject(object) { - if (object instanceof $root.google.firestore.v1.RunAggregationQueryRequest) - return object; - var message = new $root.google.firestore.v1.RunAggregationQueryRequest(); - if (object.parent != null) - message.parent = String(object.parent); - if (object.structuredAggregationQuery != null) { - if (typeof object.structuredAggregationQuery !== "object") - throw TypeError(".google.firestore.v1.RunAggregationQueryRequest.structuredAggregationQuery: object expected"); - message.structuredAggregationQuery = $root.google.firestore.v1.StructuredAggregationQuery.fromObject(object.structuredAggregationQuery); - } - if (object.transaction != null) - if (typeof object.transaction === "string") - $util.base64.decode(object.transaction, message.transaction = $util.newBuffer($util.base64.length(object.transaction)), 0); - else if (object.transaction.length >= 0) - message.transaction = object.transaction; - if (object.newTransaction != null) { - if (typeof object.newTransaction !== "object") - throw TypeError(".google.firestore.v1.RunAggregationQueryRequest.newTransaction: object expected"); - message.newTransaction = $root.google.firestore.v1.TransactionOptions.fromObject(object.newTransaction); - } - if (object.readTime != null) { - if (typeof object.readTime !== "object") - throw TypeError(".google.firestore.v1.RunAggregationQueryRequest.readTime: object expected"); - message.readTime = $root.google.protobuf.Timestamp.fromObject(object.readTime); - } - if (object.explainOptions != null) { - if (typeof object.explainOptions !== "object") - throw TypeError(".google.firestore.v1.RunAggregationQueryRequest.explainOptions: object expected"); - message.explainOptions = $root.google.firestore.v1.ExplainOptions.fromObject(object.explainOptions); - } - return message; - }; + /** + * Publishing librarySettings. + * @member {Array.} librarySettings + * @memberof google.api.Publishing + * @instance + */ + Publishing.prototype.librarySettings = $util.emptyArray; - /** - * Creates a plain object from a RunAggregationQueryRequest message. Also converts values to other types if specified. - * @function toObject - * @memberof google.firestore.v1.RunAggregationQueryRequest - * @static - * @param {google.firestore.v1.RunAggregationQueryRequest} message RunAggregationQueryRequest - * @param {$protobuf.IConversionOptions} [options] Conversion options - * @returns {Object.} Plain object - */ - RunAggregationQueryRequest.toObject = function toObject(message, options) { - if (!options) - options = {}; - var object = {}; - if (options.defaults) { - object.parent = ""; - object.explainOptions = null; - } - if (message.parent != null && message.hasOwnProperty("parent")) - object.parent = message.parent; - if (message.structuredAggregationQuery != null && message.hasOwnProperty("structuredAggregationQuery")) { - object.structuredAggregationQuery = $root.google.firestore.v1.StructuredAggregationQuery.toObject(message.structuredAggregationQuery, options); - if (options.oneofs) - object.queryType = "structuredAggregationQuery"; - } - if (message.transaction != null && message.hasOwnProperty("transaction")) { - object.transaction = options.bytes === String ? $util.base64.encode(message.transaction, 0, message.transaction.length) : options.bytes === Array ? Array.prototype.slice.call(message.transaction) : message.transaction; - if (options.oneofs) - object.consistencySelector = "transaction"; - } - if (message.newTransaction != null && message.hasOwnProperty("newTransaction")) { - object.newTransaction = $root.google.firestore.v1.TransactionOptions.toObject(message.newTransaction, options); - if (options.oneofs) - object.consistencySelector = "newTransaction"; - } - if (message.readTime != null && message.hasOwnProperty("readTime")) { - object.readTime = $root.google.protobuf.Timestamp.toObject(message.readTime, options); - if (options.oneofs) - object.consistencySelector = "readTime"; - } - if (message.explainOptions != null && message.hasOwnProperty("explainOptions")) - object.explainOptions = $root.google.firestore.v1.ExplainOptions.toObject(message.explainOptions, options); - return object; - }; + /** + * Publishing protoReferenceDocumentationUri. + * @member {string} protoReferenceDocumentationUri + * @memberof google.api.Publishing + * @instance + */ + Publishing.prototype.protoReferenceDocumentationUri = ""; - /** - * Converts this RunAggregationQueryRequest to JSON. - * @function toJSON - * @memberof google.firestore.v1.RunAggregationQueryRequest - * @instance - * @returns {Object.} JSON object - */ - RunAggregationQueryRequest.prototype.toJSON = function toJSON() { - return this.constructor.toObject(this, $protobuf.util.toJSONOptions); - }; + /** + * Publishing restReferenceDocumentationUri. + * @member {string} restReferenceDocumentationUri + * @memberof google.api.Publishing + * @instance + */ + Publishing.prototype.restReferenceDocumentationUri = ""; - /** - * Gets the default type url for RunAggregationQueryRequest - * @function getTypeUrl - * @memberof google.firestore.v1.RunAggregationQueryRequest - * @static - * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") - * @returns {string} The default type url - */ - RunAggregationQueryRequest.getTypeUrl = function getTypeUrl(typeUrlPrefix) { - if (typeUrlPrefix === undefined) { - typeUrlPrefix = "type.googleapis.com"; + /** + * Creates a Publishing message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.api.Publishing + * @static + * @param {Object.} object Plain object + * @returns {google.api.Publishing} Publishing + */ + Publishing.fromObject = function fromObject(object) { + if (object instanceof $root.google.api.Publishing) + return object; + var message = new $root.google.api.Publishing(); + if (object.methodSettings) { + if (!Array.isArray(object.methodSettings)) + throw TypeError(".google.api.Publishing.methodSettings: array expected"); + message.methodSettings = []; + for (var i = 0; i < object.methodSettings.length; ++i) { + if (typeof object.methodSettings[i] !== "object") + throw TypeError(".google.api.Publishing.methodSettings: object expected"); + message.methodSettings[i] = $root.google.api.MethodSettings.fromObject(object.methodSettings[i]); + } + } + if (object.newIssueUri != null) + message.newIssueUri = String(object.newIssueUri); + if (object.documentationUri != null) + message.documentationUri = String(object.documentationUri); + if (object.apiShortName != null) + message.apiShortName = String(object.apiShortName); + if (object.githubLabel != null) + message.githubLabel = String(object.githubLabel); + if (object.codeownerGithubTeams) { + if (!Array.isArray(object.codeownerGithubTeams)) + throw TypeError(".google.api.Publishing.codeownerGithubTeams: array expected"); + message.codeownerGithubTeams = []; + for (var i = 0; i < object.codeownerGithubTeams.length; ++i) + message.codeownerGithubTeams[i] = String(object.codeownerGithubTeams[i]); + } + if (object.docTagPrefix != null) + message.docTagPrefix = String(object.docTagPrefix); + switch (object.organization) { + default: + if (typeof object.organization === "number") { + message.organization = object.organization; + break; } - return typeUrlPrefix + "/google.firestore.v1.RunAggregationQueryRequest"; - }; - - return RunAggregationQueryRequest; - })(); + break; + case "CLIENT_LIBRARY_ORGANIZATION_UNSPECIFIED": + case 0: + message.organization = 0; + break; + case "CLOUD": + case 1: + message.organization = 1; + break; + case "ADS": + case 2: + message.organization = 2; + break; + case "PHOTOS": + case 3: + message.organization = 3; + break; + case "STREET_VIEW": + case 4: + message.organization = 4; + break; + case "SHOPPING": + case 5: + message.organization = 5; + break; + case "GEO": + case 6: + message.organization = 6; + break; + case "GENERATIVE_AI": + case 7: + message.organization = 7; + break; + } + if (object.librarySettings) { + if (!Array.isArray(object.librarySettings)) + throw TypeError(".google.api.Publishing.librarySettings: array expected"); + message.librarySettings = []; + for (var i = 0; i < object.librarySettings.length; ++i) { + if (typeof object.librarySettings[i] !== "object") + throw TypeError(".google.api.Publishing.librarySettings: object expected"); + message.librarySettings[i] = $root.google.api.ClientLibrarySettings.fromObject(object.librarySettings[i]); + } + } + if (object.protoReferenceDocumentationUri != null) + message.protoReferenceDocumentationUri = String(object.protoReferenceDocumentationUri); + if (object.restReferenceDocumentationUri != null) + message.restReferenceDocumentationUri = String(object.restReferenceDocumentationUri); + return message; + }; - v1.RunAggregationQueryResponse = (function() { + /** + * Creates a plain object from a Publishing message. Also converts values to other types if specified. + * @function toObject + * @memberof google.api.Publishing + * @static + * @param {google.api.Publishing} message Publishing + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + Publishing.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.arrays || options.defaults) { + object.methodSettings = []; + object.codeownerGithubTeams = []; + object.librarySettings = []; + } + if (options.defaults) { + object.newIssueUri = ""; + object.documentationUri = ""; + object.apiShortName = ""; + object.githubLabel = ""; + object.docTagPrefix = ""; + object.organization = options.enums === String ? "CLIENT_LIBRARY_ORGANIZATION_UNSPECIFIED" : 0; + object.protoReferenceDocumentationUri = ""; + object.restReferenceDocumentationUri = ""; + } + if (message.methodSettings && message.methodSettings.length) { + object.methodSettings = []; + for (var j = 0; j < message.methodSettings.length; ++j) + object.methodSettings[j] = $root.google.api.MethodSettings.toObject(message.methodSettings[j], options); + } + if (message.newIssueUri != null && message.hasOwnProperty("newIssueUri")) + object.newIssueUri = message.newIssueUri; + if (message.documentationUri != null && message.hasOwnProperty("documentationUri")) + object.documentationUri = message.documentationUri; + if (message.apiShortName != null && message.hasOwnProperty("apiShortName")) + object.apiShortName = message.apiShortName; + if (message.githubLabel != null && message.hasOwnProperty("githubLabel")) + object.githubLabel = message.githubLabel; + if (message.codeownerGithubTeams && message.codeownerGithubTeams.length) { + object.codeownerGithubTeams = []; + for (var j = 0; j < message.codeownerGithubTeams.length; ++j) + object.codeownerGithubTeams[j] = message.codeownerGithubTeams[j]; + } + if (message.docTagPrefix != null && message.hasOwnProperty("docTagPrefix")) + object.docTagPrefix = message.docTagPrefix; + if (message.organization != null && message.hasOwnProperty("organization")) + object.organization = options.enums === String ? $root.google.api.ClientLibraryOrganization[message.organization] === undefined ? message.organization : $root.google.api.ClientLibraryOrganization[message.organization] : message.organization; + if (message.librarySettings && message.librarySettings.length) { + object.librarySettings = []; + for (var j = 0; j < message.librarySettings.length; ++j) + object.librarySettings[j] = $root.google.api.ClientLibrarySettings.toObject(message.librarySettings[j], options); + } + if (message.protoReferenceDocumentationUri != null && message.hasOwnProperty("protoReferenceDocumentationUri")) + object.protoReferenceDocumentationUri = message.protoReferenceDocumentationUri; + if (message.restReferenceDocumentationUri != null && message.hasOwnProperty("restReferenceDocumentationUri")) + object.restReferenceDocumentationUri = message.restReferenceDocumentationUri; + return object; + }; - /** - * Properties of a RunAggregationQueryResponse. - * @memberof google.firestore.v1 - * @interface IRunAggregationQueryResponse - * @property {google.firestore.v1.IAggregationResult|null} [result] RunAggregationQueryResponse result - * @property {Uint8Array|null} [transaction] RunAggregationQueryResponse transaction - * @property {google.protobuf.ITimestamp|null} [readTime] RunAggregationQueryResponse readTime - * @property {google.firestore.v1.IExplainMetrics|null} [explainMetrics] RunAggregationQueryResponse explainMetrics - */ + /** + * Converts this Publishing to JSON. + * @function toJSON + * @memberof google.api.Publishing + * @instance + * @returns {Object.} JSON object + */ + Publishing.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; - /** - * Constructs a new RunAggregationQueryResponse. - * @memberof google.firestore.v1 - * @classdesc Represents a RunAggregationQueryResponse. - * @implements IRunAggregationQueryResponse - * @constructor - * @param {google.firestore.v1.IRunAggregationQueryResponse=} [properties] Properties to set - */ - function RunAggregationQueryResponse(properties) { - if (properties) - for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) - if (properties[keys[i]] != null) - this[keys[i]] = properties[keys[i]]; + /** + * Gets the default type url for Publishing + * @function getTypeUrl + * @memberof google.api.Publishing + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + Publishing.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; } + return typeUrlPrefix + "/google.api.Publishing"; + }; - /** - * RunAggregationQueryResponse result. - * @member {google.firestore.v1.IAggregationResult|null|undefined} result - * @memberof google.firestore.v1.RunAggregationQueryResponse - * @instance - */ - RunAggregationQueryResponse.prototype.result = null; - - /** - * RunAggregationQueryResponse transaction. - * @member {Uint8Array} transaction - * @memberof google.firestore.v1.RunAggregationQueryResponse - * @instance - */ - RunAggregationQueryResponse.prototype.transaction = $util.newBuffer([]); + return Publishing; + })(); - /** - * RunAggregationQueryResponse readTime. - * @member {google.protobuf.ITimestamp|null|undefined} readTime - * @memberof google.firestore.v1.RunAggregationQueryResponse - * @instance - */ - RunAggregationQueryResponse.prototype.readTime = null; + api.JavaSettings = (function() { - /** - * RunAggregationQueryResponse explainMetrics. - * @member {google.firestore.v1.IExplainMetrics|null|undefined} explainMetrics - * @memberof google.firestore.v1.RunAggregationQueryResponse - * @instance - */ - RunAggregationQueryResponse.prototype.explainMetrics = null; + /** + * Properties of a JavaSettings. + * @memberof google.api + * @interface IJavaSettings + * @property {string|null} [libraryPackage] JavaSettings libraryPackage + * @property {Object.|null} [serviceClassNames] JavaSettings serviceClassNames + * @property {google.api.ICommonLanguageSettings|null} [common] JavaSettings common + */ - /** - * Creates a RunAggregationQueryResponse message from a plain object. Also converts values to their respective internal types. - * @function fromObject - * @memberof google.firestore.v1.RunAggregationQueryResponse - * @static - * @param {Object.} object Plain object - * @returns {google.firestore.v1.RunAggregationQueryResponse} RunAggregationQueryResponse - */ - RunAggregationQueryResponse.fromObject = function fromObject(object) { - if (object instanceof $root.google.firestore.v1.RunAggregationQueryResponse) - return object; - var message = new $root.google.firestore.v1.RunAggregationQueryResponse(); - if (object.result != null) { - if (typeof object.result !== "object") - throw TypeError(".google.firestore.v1.RunAggregationQueryResponse.result: object expected"); - message.result = $root.google.firestore.v1.AggregationResult.fromObject(object.result); - } - if (object.transaction != null) - if (typeof object.transaction === "string") - $util.base64.decode(object.transaction, message.transaction = $util.newBuffer($util.base64.length(object.transaction)), 0); - else if (object.transaction.length >= 0) - message.transaction = object.transaction; - if (object.readTime != null) { - if (typeof object.readTime !== "object") - throw TypeError(".google.firestore.v1.RunAggregationQueryResponse.readTime: object expected"); - message.readTime = $root.google.protobuf.Timestamp.fromObject(object.readTime); - } - if (object.explainMetrics != null) { - if (typeof object.explainMetrics !== "object") - throw TypeError(".google.firestore.v1.RunAggregationQueryResponse.explainMetrics: object expected"); - message.explainMetrics = $root.google.firestore.v1.ExplainMetrics.fromObject(object.explainMetrics); - } - return message; - }; + /** + * Constructs a new JavaSettings. + * @memberof google.api + * @classdesc Represents a JavaSettings. + * @implements IJavaSettings + * @constructor + * @param {google.api.IJavaSettings=} [properties] Properties to set + */ + function JavaSettings(properties) { + this.serviceClassNames = {}; + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } - /** - * Creates a plain object from a RunAggregationQueryResponse message. Also converts values to other types if specified. - * @function toObject - * @memberof google.firestore.v1.RunAggregationQueryResponse - * @static - * @param {google.firestore.v1.RunAggregationQueryResponse} message RunAggregationQueryResponse - * @param {$protobuf.IConversionOptions} [options] Conversion options - * @returns {Object.} Plain object - */ - RunAggregationQueryResponse.toObject = function toObject(message, options) { - if (!options) - options = {}; - var object = {}; - if (options.defaults) { - object.result = null; - if (options.bytes === String) - object.transaction = ""; - else { - object.transaction = []; - if (options.bytes !== Array) - object.transaction = $util.newBuffer(object.transaction); - } - object.readTime = null; - object.explainMetrics = null; - } - if (message.result != null && message.hasOwnProperty("result")) - object.result = $root.google.firestore.v1.AggregationResult.toObject(message.result, options); - if (message.transaction != null && message.hasOwnProperty("transaction")) - object.transaction = options.bytes === String ? $util.base64.encode(message.transaction, 0, message.transaction.length) : options.bytes === Array ? Array.prototype.slice.call(message.transaction) : message.transaction; - if (message.readTime != null && message.hasOwnProperty("readTime")) - object.readTime = $root.google.protobuf.Timestamp.toObject(message.readTime, options); - if (message.explainMetrics != null && message.hasOwnProperty("explainMetrics")) - object.explainMetrics = $root.google.firestore.v1.ExplainMetrics.toObject(message.explainMetrics, options); - return object; - }; + /** + * JavaSettings libraryPackage. + * @member {string} libraryPackage + * @memberof google.api.JavaSettings + * @instance + */ + JavaSettings.prototype.libraryPackage = ""; - /** - * Converts this RunAggregationQueryResponse to JSON. - * @function toJSON - * @memberof google.firestore.v1.RunAggregationQueryResponse - * @instance - * @returns {Object.} JSON object - */ - RunAggregationQueryResponse.prototype.toJSON = function toJSON() { - return this.constructor.toObject(this, $protobuf.util.toJSONOptions); - }; + /** + * JavaSettings serviceClassNames. + * @member {Object.} serviceClassNames + * @memberof google.api.JavaSettings + * @instance + */ + JavaSettings.prototype.serviceClassNames = $util.emptyObject; - /** - * Gets the default type url for RunAggregationQueryResponse - * @function getTypeUrl - * @memberof google.firestore.v1.RunAggregationQueryResponse - * @static - * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") - * @returns {string} The default type url - */ - RunAggregationQueryResponse.getTypeUrl = function getTypeUrl(typeUrlPrefix) { - if (typeUrlPrefix === undefined) { - typeUrlPrefix = "type.googleapis.com"; - } - return typeUrlPrefix + "/google.firestore.v1.RunAggregationQueryResponse"; - }; + /** + * JavaSettings common. + * @member {google.api.ICommonLanguageSettings|null|undefined} common + * @memberof google.api.JavaSettings + * @instance + */ + JavaSettings.prototype.common = null; - return RunAggregationQueryResponse; - })(); + /** + * Creates a JavaSettings message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.api.JavaSettings + * @static + * @param {Object.} object Plain object + * @returns {google.api.JavaSettings} JavaSettings + */ + JavaSettings.fromObject = function fromObject(object) { + if (object instanceof $root.google.api.JavaSettings) + return object; + var message = new $root.google.api.JavaSettings(); + if (object.libraryPackage != null) + message.libraryPackage = String(object.libraryPackage); + if (object.serviceClassNames) { + if (typeof object.serviceClassNames !== "object") + throw TypeError(".google.api.JavaSettings.serviceClassNames: object expected"); + message.serviceClassNames = {}; + for (var keys = Object.keys(object.serviceClassNames), i = 0; i < keys.length; ++i) + message.serviceClassNames[keys[i]] = String(object.serviceClassNames[keys[i]]); + } + if (object.common != null) { + if (typeof object.common !== "object") + throw TypeError(".google.api.JavaSettings.common: object expected"); + message.common = $root.google.api.CommonLanguageSettings.fromObject(object.common); + } + return message; + }; - v1.PartitionQueryRequest = (function() { + /** + * Creates a plain object from a JavaSettings message. Also converts values to other types if specified. + * @function toObject + * @memberof google.api.JavaSettings + * @static + * @param {google.api.JavaSettings} message JavaSettings + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + JavaSettings.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.objects || options.defaults) + object.serviceClassNames = {}; + if (options.defaults) { + object.libraryPackage = ""; + object.common = null; + } + if (message.libraryPackage != null && message.hasOwnProperty("libraryPackage")) + object.libraryPackage = message.libraryPackage; + var keys2; + if (message.serviceClassNames && (keys2 = Object.keys(message.serviceClassNames)).length) { + object.serviceClassNames = {}; + for (var j = 0; j < keys2.length; ++j) + object.serviceClassNames[keys2[j]] = message.serviceClassNames[keys2[j]]; + } + if (message.common != null && message.hasOwnProperty("common")) + object.common = $root.google.api.CommonLanguageSettings.toObject(message.common, options); + return object; + }; - /** - * Properties of a PartitionQueryRequest. - * @memberof google.firestore.v1 - * @interface IPartitionQueryRequest - * @property {string|null} [parent] PartitionQueryRequest parent - * @property {google.firestore.v1.IStructuredQuery|null} [structuredQuery] PartitionQueryRequest structuredQuery - * @property {number|string|null} [partitionCount] PartitionQueryRequest partitionCount - * @property {string|null} [pageToken] PartitionQueryRequest pageToken - * @property {number|null} [pageSize] PartitionQueryRequest pageSize - * @property {google.protobuf.ITimestamp|null} [readTime] PartitionQueryRequest readTime - */ + /** + * Converts this JavaSettings to JSON. + * @function toJSON + * @memberof google.api.JavaSettings + * @instance + * @returns {Object.} JSON object + */ + JavaSettings.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; - /** - * Constructs a new PartitionQueryRequest. - * @memberof google.firestore.v1 - * @classdesc Represents a PartitionQueryRequest. - * @implements IPartitionQueryRequest - * @constructor - * @param {google.firestore.v1.IPartitionQueryRequest=} [properties] Properties to set - */ - function PartitionQueryRequest(properties) { - if (properties) - for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) - if (properties[keys[i]] != null) - this[keys[i]] = properties[keys[i]]; + /** + * Gets the default type url for JavaSettings + * @function getTypeUrl + * @memberof google.api.JavaSettings + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + JavaSettings.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; } + return typeUrlPrefix + "/google.api.JavaSettings"; + }; - /** - * PartitionQueryRequest parent. - * @member {string} parent - * @memberof google.firestore.v1.PartitionQueryRequest - * @instance - */ - PartitionQueryRequest.prototype.parent = ""; + return JavaSettings; + })(); - /** - * PartitionQueryRequest structuredQuery. - * @member {google.firestore.v1.IStructuredQuery|null|undefined} structuredQuery - * @memberof google.firestore.v1.PartitionQueryRequest - * @instance - */ - PartitionQueryRequest.prototype.structuredQuery = null; + api.CppSettings = (function() { + + /** + * Properties of a CppSettings. + * @memberof google.api + * @interface ICppSettings + * @property {google.api.ICommonLanguageSettings|null} [common] CppSettings common + */ + + /** + * Constructs a new CppSettings. + * @memberof google.api + * @classdesc Represents a CppSettings. + * @implements ICppSettings + * @constructor + * @param {google.api.ICppSettings=} [properties] Properties to set + */ + function CppSettings(properties) { + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } + + /** + * CppSettings common. + * @member {google.api.ICommonLanguageSettings|null|undefined} common + * @memberof google.api.CppSettings + * @instance + */ + CppSettings.prototype.common = null; + + /** + * Creates a CppSettings message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.api.CppSettings + * @static + * @param {Object.} object Plain object + * @returns {google.api.CppSettings} CppSettings + */ + CppSettings.fromObject = function fromObject(object) { + if (object instanceof $root.google.api.CppSettings) + return object; + var message = new $root.google.api.CppSettings(); + if (object.common != null) { + if (typeof object.common !== "object") + throw TypeError(".google.api.CppSettings.common: object expected"); + message.common = $root.google.api.CommonLanguageSettings.fromObject(object.common); + } + return message; + }; - /** - * PartitionQueryRequest partitionCount. - * @member {number|string} partitionCount - * @memberof google.firestore.v1.PartitionQueryRequest - * @instance - */ - PartitionQueryRequest.prototype.partitionCount = $util.Long ? $util.Long.fromBits(0,0,false) : 0; + /** + * Creates a plain object from a CppSettings message. Also converts values to other types if specified. + * @function toObject + * @memberof google.api.CppSettings + * @static + * @param {google.api.CppSettings} message CppSettings + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + CppSettings.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.defaults) + object.common = null; + if (message.common != null && message.hasOwnProperty("common")) + object.common = $root.google.api.CommonLanguageSettings.toObject(message.common, options); + return object; + }; - /** - * PartitionQueryRequest pageToken. - * @member {string} pageToken - * @memberof google.firestore.v1.PartitionQueryRequest - * @instance - */ - PartitionQueryRequest.prototype.pageToken = ""; + /** + * Converts this CppSettings to JSON. + * @function toJSON + * @memberof google.api.CppSettings + * @instance + * @returns {Object.} JSON object + */ + CppSettings.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; - /** - * PartitionQueryRequest pageSize. - * @member {number} pageSize - * @memberof google.firestore.v1.PartitionQueryRequest - * @instance - */ - PartitionQueryRequest.prototype.pageSize = 0; + /** + * Gets the default type url for CppSettings + * @function getTypeUrl + * @memberof google.api.CppSettings + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + CppSettings.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.api.CppSettings"; + }; - /** - * PartitionQueryRequest readTime. - * @member {google.protobuf.ITimestamp|null|undefined} readTime - * @memberof google.firestore.v1.PartitionQueryRequest - * @instance - */ - PartitionQueryRequest.prototype.readTime = null; + return CppSettings; + })(); - // OneOf field names bound to virtual getters and setters - var $oneOfFields; + api.PhpSettings = (function() { - /** - * PartitionQueryRequest queryType. - * @member {"structuredQuery"|undefined} queryType - * @memberof google.firestore.v1.PartitionQueryRequest - * @instance - */ - Object.defineProperty(PartitionQueryRequest.prototype, "queryType", { - get: $util.oneOfGetter($oneOfFields = ["structuredQuery"]), - set: $util.oneOfSetter($oneOfFields) - }); + /** + * Properties of a PhpSettings. + * @memberof google.api + * @interface IPhpSettings + * @property {google.api.ICommonLanguageSettings|null} [common] PhpSettings common + */ - /** - * PartitionQueryRequest consistencySelector. - * @member {"readTime"|undefined} consistencySelector - * @memberof google.firestore.v1.PartitionQueryRequest - * @instance - */ - Object.defineProperty(PartitionQueryRequest.prototype, "consistencySelector", { - get: $util.oneOfGetter($oneOfFields = ["readTime"]), - set: $util.oneOfSetter($oneOfFields) - }); + /** + * Constructs a new PhpSettings. + * @memberof google.api + * @classdesc Represents a PhpSettings. + * @implements IPhpSettings + * @constructor + * @param {google.api.IPhpSettings=} [properties] Properties to set + */ + function PhpSettings(properties) { + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } - /** - * Creates a PartitionQueryRequest message from a plain object. Also converts values to their respective internal types. - * @function fromObject - * @memberof google.firestore.v1.PartitionQueryRequest - * @static - * @param {Object.} object Plain object - * @returns {google.firestore.v1.PartitionQueryRequest} PartitionQueryRequest - */ - PartitionQueryRequest.fromObject = function fromObject(object) { - if (object instanceof $root.google.firestore.v1.PartitionQueryRequest) - return object; - var message = new $root.google.firestore.v1.PartitionQueryRequest(); - if (object.parent != null) - message.parent = String(object.parent); - if (object.structuredQuery != null) { - if (typeof object.structuredQuery !== "object") - throw TypeError(".google.firestore.v1.PartitionQueryRequest.structuredQuery: object expected"); - message.structuredQuery = $root.google.firestore.v1.StructuredQuery.fromObject(object.structuredQuery); - } - if (object.partitionCount != null) - if ($util.Long) - (message.partitionCount = $util.Long.fromValue(object.partitionCount)).unsigned = false; - else if (typeof object.partitionCount === "string") - message.partitionCount = parseInt(object.partitionCount, 10); - else if (typeof object.partitionCount === "number") - message.partitionCount = object.partitionCount; - else if (typeof object.partitionCount === "object") - message.partitionCount = new $util.LongBits(object.partitionCount.low >>> 0, object.partitionCount.high >>> 0).toNumber(); - if (object.pageToken != null) - message.pageToken = String(object.pageToken); - if (object.pageSize != null) - message.pageSize = object.pageSize | 0; - if (object.readTime != null) { - if (typeof object.readTime !== "object") - throw TypeError(".google.firestore.v1.PartitionQueryRequest.readTime: object expected"); - message.readTime = $root.google.protobuf.Timestamp.fromObject(object.readTime); - } - return message; - }; + /** + * PhpSettings common. + * @member {google.api.ICommonLanguageSettings|null|undefined} common + * @memberof google.api.PhpSettings + * @instance + */ + PhpSettings.prototype.common = null; - /** - * Creates a plain object from a PartitionQueryRequest message. Also converts values to other types if specified. - * @function toObject - * @memberof google.firestore.v1.PartitionQueryRequest - * @static - * @param {google.firestore.v1.PartitionQueryRequest} message PartitionQueryRequest - * @param {$protobuf.IConversionOptions} [options] Conversion options - * @returns {Object.} Plain object - */ - PartitionQueryRequest.toObject = function toObject(message, options) { - if (!options) - options = {}; - var object = {}; - if (options.defaults) { - object.parent = ""; - if ($util.Long) { - var long = new $util.Long(0, 0, false); - object.partitionCount = options.longs === String ? long.toString() : options.longs === Number ? long.toNumber() : long; - } else - object.partitionCount = options.longs === String ? "0" : 0; - object.pageToken = ""; - object.pageSize = 0; - } - if (message.parent != null && message.hasOwnProperty("parent")) - object.parent = message.parent; - if (message.structuredQuery != null && message.hasOwnProperty("structuredQuery")) { - object.structuredQuery = $root.google.firestore.v1.StructuredQuery.toObject(message.structuredQuery, options); - if (options.oneofs) - object.queryType = "structuredQuery"; - } - if (message.partitionCount != null && message.hasOwnProperty("partitionCount")) - if (typeof message.partitionCount === "number") - object.partitionCount = options.longs === String ? String(message.partitionCount) : message.partitionCount; - else - object.partitionCount = options.longs === String ? $util.Long.prototype.toString.call(message.partitionCount) : options.longs === Number ? new $util.LongBits(message.partitionCount.low >>> 0, message.partitionCount.high >>> 0).toNumber() : message.partitionCount; - if (message.pageToken != null && message.hasOwnProperty("pageToken")) - object.pageToken = message.pageToken; - if (message.pageSize != null && message.hasOwnProperty("pageSize")) - object.pageSize = message.pageSize; - if (message.readTime != null && message.hasOwnProperty("readTime")) { - object.readTime = $root.google.protobuf.Timestamp.toObject(message.readTime, options); - if (options.oneofs) - object.consistencySelector = "readTime"; - } + /** + * Creates a PhpSettings message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.api.PhpSettings + * @static + * @param {Object.} object Plain object + * @returns {google.api.PhpSettings} PhpSettings + */ + PhpSettings.fromObject = function fromObject(object) { + if (object instanceof $root.google.api.PhpSettings) return object; - }; + var message = new $root.google.api.PhpSettings(); + if (object.common != null) { + if (typeof object.common !== "object") + throw TypeError(".google.api.PhpSettings.common: object expected"); + message.common = $root.google.api.CommonLanguageSettings.fromObject(object.common); + } + return message; + }; + + /** + * Creates a plain object from a PhpSettings message. Also converts values to other types if specified. + * @function toObject + * @memberof google.api.PhpSettings + * @static + * @param {google.api.PhpSettings} message PhpSettings + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + PhpSettings.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.defaults) + object.common = null; + if (message.common != null && message.hasOwnProperty("common")) + object.common = $root.google.api.CommonLanguageSettings.toObject(message.common, options); + return object; + }; - /** - * Converts this PartitionQueryRequest to JSON. - * @function toJSON - * @memberof google.firestore.v1.PartitionQueryRequest - * @instance - * @returns {Object.} JSON object - */ - PartitionQueryRequest.prototype.toJSON = function toJSON() { - return this.constructor.toObject(this, $protobuf.util.toJSONOptions); - }; + /** + * Converts this PhpSettings to JSON. + * @function toJSON + * @memberof google.api.PhpSettings + * @instance + * @returns {Object.} JSON object + */ + PhpSettings.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; - /** - * Gets the default type url for PartitionQueryRequest - * @function getTypeUrl - * @memberof google.firestore.v1.PartitionQueryRequest - * @static - * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") - * @returns {string} The default type url - */ - PartitionQueryRequest.getTypeUrl = function getTypeUrl(typeUrlPrefix) { - if (typeUrlPrefix === undefined) { - typeUrlPrefix = "type.googleapis.com"; - } - return typeUrlPrefix + "/google.firestore.v1.PartitionQueryRequest"; - }; + /** + * Gets the default type url for PhpSettings + * @function getTypeUrl + * @memberof google.api.PhpSettings + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + PhpSettings.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.api.PhpSettings"; + }; - return PartitionQueryRequest; - })(); + return PhpSettings; + })(); - v1.PartitionQueryResponse = (function() { + api.PythonSettings = (function() { - /** - * Properties of a PartitionQueryResponse. - * @memberof google.firestore.v1 - * @interface IPartitionQueryResponse - * @property {Array.|null} [partitions] PartitionQueryResponse partitions - * @property {string|null} [nextPageToken] PartitionQueryResponse nextPageToken - */ + /** + * Properties of a PythonSettings. + * @memberof google.api + * @interface IPythonSettings + * @property {google.api.ICommonLanguageSettings|null} [common] PythonSettings common + */ - /** - * Constructs a new PartitionQueryResponse. - * @memberof google.firestore.v1 - * @classdesc Represents a PartitionQueryResponse. - * @implements IPartitionQueryResponse - * @constructor - * @param {google.firestore.v1.IPartitionQueryResponse=} [properties] Properties to set - */ - function PartitionQueryResponse(properties) { - this.partitions = []; - if (properties) - for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) - if (properties[keys[i]] != null) - this[keys[i]] = properties[keys[i]]; + /** + * Constructs a new PythonSettings. + * @memberof google.api + * @classdesc Represents a PythonSettings. + * @implements IPythonSettings + * @constructor + * @param {google.api.IPythonSettings=} [properties] Properties to set + */ + function PythonSettings(properties) { + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } + + /** + * PythonSettings common. + * @member {google.api.ICommonLanguageSettings|null|undefined} common + * @memberof google.api.PythonSettings + * @instance + */ + PythonSettings.prototype.common = null; + + /** + * Creates a PythonSettings message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.api.PythonSettings + * @static + * @param {Object.} object Plain object + * @returns {google.api.PythonSettings} PythonSettings + */ + PythonSettings.fromObject = function fromObject(object) { + if (object instanceof $root.google.api.PythonSettings) + return object; + var message = new $root.google.api.PythonSettings(); + if (object.common != null) { + if (typeof object.common !== "object") + throw TypeError(".google.api.PythonSettings.common: object expected"); + message.common = $root.google.api.CommonLanguageSettings.fromObject(object.common); } + return message; + }; - /** - * PartitionQueryResponse partitions. - * @member {Array.} partitions - * @memberof google.firestore.v1.PartitionQueryResponse - * @instance - */ - PartitionQueryResponse.prototype.partitions = $util.emptyArray; + /** + * Creates a plain object from a PythonSettings message. Also converts values to other types if specified. + * @function toObject + * @memberof google.api.PythonSettings + * @static + * @param {google.api.PythonSettings} message PythonSettings + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + PythonSettings.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.defaults) + object.common = null; + if (message.common != null && message.hasOwnProperty("common")) + object.common = $root.google.api.CommonLanguageSettings.toObject(message.common, options); + return object; + }; - /** - * PartitionQueryResponse nextPageToken. - * @member {string} nextPageToken - * @memberof google.firestore.v1.PartitionQueryResponse - * @instance - */ - PartitionQueryResponse.prototype.nextPageToken = ""; + /** + * Converts this PythonSettings to JSON. + * @function toJSON + * @memberof google.api.PythonSettings + * @instance + * @returns {Object.} JSON object + */ + PythonSettings.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; - /** - * Creates a PartitionQueryResponse message from a plain object. Also converts values to their respective internal types. - * @function fromObject - * @memberof google.firestore.v1.PartitionQueryResponse - * @static - * @param {Object.} object Plain object - * @returns {google.firestore.v1.PartitionQueryResponse} PartitionQueryResponse - */ - PartitionQueryResponse.fromObject = function fromObject(object) { - if (object instanceof $root.google.firestore.v1.PartitionQueryResponse) - return object; - var message = new $root.google.firestore.v1.PartitionQueryResponse(); - if (object.partitions) { - if (!Array.isArray(object.partitions)) - throw TypeError(".google.firestore.v1.PartitionQueryResponse.partitions: array expected"); - message.partitions = []; - for (var i = 0; i < object.partitions.length; ++i) { - if (typeof object.partitions[i] !== "object") - throw TypeError(".google.firestore.v1.PartitionQueryResponse.partitions: object expected"); - message.partitions[i] = $root.google.firestore.v1.Cursor.fromObject(object.partitions[i]); - } - } - if (object.nextPageToken != null) - message.nextPageToken = String(object.nextPageToken); - return message; - }; + /** + * Gets the default type url for PythonSettings + * @function getTypeUrl + * @memberof google.api.PythonSettings + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + PythonSettings.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.api.PythonSettings"; + }; - /** - * Creates a plain object from a PartitionQueryResponse message. Also converts values to other types if specified. - * @function toObject - * @memberof google.firestore.v1.PartitionQueryResponse - * @static - * @param {google.firestore.v1.PartitionQueryResponse} message PartitionQueryResponse - * @param {$protobuf.IConversionOptions} [options] Conversion options - * @returns {Object.} Plain object - */ - PartitionQueryResponse.toObject = function toObject(message, options) { - if (!options) - options = {}; - var object = {}; - if (options.arrays || options.defaults) - object.partitions = []; - if (options.defaults) - object.nextPageToken = ""; - if (message.partitions && message.partitions.length) { - object.partitions = []; - for (var j = 0; j < message.partitions.length; ++j) - object.partitions[j] = $root.google.firestore.v1.Cursor.toObject(message.partitions[j], options); - } - if (message.nextPageToken != null && message.hasOwnProperty("nextPageToken")) - object.nextPageToken = message.nextPageToken; - return object; - }; + return PythonSettings; + })(); - /** - * Converts this PartitionQueryResponse to JSON. - * @function toJSON - * @memberof google.firestore.v1.PartitionQueryResponse - * @instance - * @returns {Object.} JSON object - */ - PartitionQueryResponse.prototype.toJSON = function toJSON() { - return this.constructor.toObject(this, $protobuf.util.toJSONOptions); - }; + api.NodeSettings = (function() { + + /** + * Properties of a NodeSettings. + * @memberof google.api + * @interface INodeSettings + * @property {google.api.ICommonLanguageSettings|null} [common] NodeSettings common + */ + + /** + * Constructs a new NodeSettings. + * @memberof google.api + * @classdesc Represents a NodeSettings. + * @implements INodeSettings + * @constructor + * @param {google.api.INodeSettings=} [properties] Properties to set + */ + function NodeSettings(properties) { + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } - /** - * Gets the default type url for PartitionQueryResponse - * @function getTypeUrl - * @memberof google.firestore.v1.PartitionQueryResponse - * @static - * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") - * @returns {string} The default type url - */ - PartitionQueryResponse.getTypeUrl = function getTypeUrl(typeUrlPrefix) { - if (typeUrlPrefix === undefined) { - typeUrlPrefix = "type.googleapis.com"; - } - return typeUrlPrefix + "/google.firestore.v1.PartitionQueryResponse"; - }; + /** + * NodeSettings common. + * @member {google.api.ICommonLanguageSettings|null|undefined} common + * @memberof google.api.NodeSettings + * @instance + */ + NodeSettings.prototype.common = null; - return PartitionQueryResponse; - })(); + /** + * Creates a NodeSettings message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.api.NodeSettings + * @static + * @param {Object.} object Plain object + * @returns {google.api.NodeSettings} NodeSettings + */ + NodeSettings.fromObject = function fromObject(object) { + if (object instanceof $root.google.api.NodeSettings) + return object; + var message = new $root.google.api.NodeSettings(); + if (object.common != null) { + if (typeof object.common !== "object") + throw TypeError(".google.api.NodeSettings.common: object expected"); + message.common = $root.google.api.CommonLanguageSettings.fromObject(object.common); + } + return message; + }; - v1.WriteRequest = (function() { + /** + * Creates a plain object from a NodeSettings message. Also converts values to other types if specified. + * @function toObject + * @memberof google.api.NodeSettings + * @static + * @param {google.api.NodeSettings} message NodeSettings + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + NodeSettings.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.defaults) + object.common = null; + if (message.common != null && message.hasOwnProperty("common")) + object.common = $root.google.api.CommonLanguageSettings.toObject(message.common, options); + return object; + }; - /** - * Properties of a WriteRequest. - * @memberof google.firestore.v1 - * @interface IWriteRequest - * @property {string|null} [database] WriteRequest database - * @property {string|null} [streamId] WriteRequest streamId - * @property {Array.|null} [writes] WriteRequest writes - * @property {Uint8Array|null} [streamToken] WriteRequest streamToken - * @property {Object.|null} [labels] WriteRequest labels - */ + /** + * Converts this NodeSettings to JSON. + * @function toJSON + * @memberof google.api.NodeSettings + * @instance + * @returns {Object.} JSON object + */ + NodeSettings.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; - /** - * Constructs a new WriteRequest. - * @memberof google.firestore.v1 - * @classdesc Represents a WriteRequest. - * @implements IWriteRequest - * @constructor - * @param {google.firestore.v1.IWriteRequest=} [properties] Properties to set - */ - function WriteRequest(properties) { - this.writes = []; - this.labels = {}; - if (properties) - for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) - if (properties[keys[i]] != null) - this[keys[i]] = properties[keys[i]]; + /** + * Gets the default type url for NodeSettings + * @function getTypeUrl + * @memberof google.api.NodeSettings + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + NodeSettings.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; } + return typeUrlPrefix + "/google.api.NodeSettings"; + }; - /** - * WriteRequest database. - * @member {string} database - * @memberof google.firestore.v1.WriteRequest - * @instance - */ - WriteRequest.prototype.database = ""; + return NodeSettings; + })(); - /** - * WriteRequest streamId. - * @member {string} streamId - * @memberof google.firestore.v1.WriteRequest - * @instance - */ - WriteRequest.prototype.streamId = ""; + api.DotnetSettings = (function() { - /** - * WriteRequest writes. - * @member {Array.} writes - * @memberof google.firestore.v1.WriteRequest - * @instance - */ - WriteRequest.prototype.writes = $util.emptyArray; + /** + * Properties of a DotnetSettings. + * @memberof google.api + * @interface IDotnetSettings + * @property {google.api.ICommonLanguageSettings|null} [common] DotnetSettings common + * @property {Object.|null} [renamedServices] DotnetSettings renamedServices + * @property {Object.|null} [renamedResources] DotnetSettings renamedResources + * @property {Array.|null} [ignoredResources] DotnetSettings ignoredResources + * @property {Array.|null} [forcedNamespaceAliases] DotnetSettings forcedNamespaceAliases + * @property {Array.|null} [handwrittenSignatures] DotnetSettings handwrittenSignatures + */ - /** - * WriteRequest streamToken. - * @member {Uint8Array} streamToken - * @memberof google.firestore.v1.WriteRequest - * @instance - */ - WriteRequest.prototype.streamToken = $util.newBuffer([]); + /** + * Constructs a new DotnetSettings. + * @memberof google.api + * @classdesc Represents a DotnetSettings. + * @implements IDotnetSettings + * @constructor + * @param {google.api.IDotnetSettings=} [properties] Properties to set + */ + function DotnetSettings(properties) { + this.renamedServices = {}; + this.renamedResources = {}; + this.ignoredResources = []; + this.forcedNamespaceAliases = []; + this.handwrittenSignatures = []; + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } - /** - * WriteRequest labels. - * @member {Object.} labels - * @memberof google.firestore.v1.WriteRequest - * @instance - */ - WriteRequest.prototype.labels = $util.emptyObject; + /** + * DotnetSettings common. + * @member {google.api.ICommonLanguageSettings|null|undefined} common + * @memberof google.api.DotnetSettings + * @instance + */ + DotnetSettings.prototype.common = null; - /** - * Creates a WriteRequest message from a plain object. Also converts values to their respective internal types. - * @function fromObject - * @memberof google.firestore.v1.WriteRequest - * @static - * @param {Object.} object Plain object - * @returns {google.firestore.v1.WriteRequest} WriteRequest - */ - WriteRequest.fromObject = function fromObject(object) { - if (object instanceof $root.google.firestore.v1.WriteRequest) - return object; - var message = new $root.google.firestore.v1.WriteRequest(); - if (object.database != null) - message.database = String(object.database); - if (object.streamId != null) - message.streamId = String(object.streamId); - if (object.writes) { - if (!Array.isArray(object.writes)) - throw TypeError(".google.firestore.v1.WriteRequest.writes: array expected"); - message.writes = []; - for (var i = 0; i < object.writes.length; ++i) { - if (typeof object.writes[i] !== "object") - throw TypeError(".google.firestore.v1.WriteRequest.writes: object expected"); - message.writes[i] = $root.google.firestore.v1.Write.fromObject(object.writes[i]); - } - } - if (object.streamToken != null) - if (typeof object.streamToken === "string") - $util.base64.decode(object.streamToken, message.streamToken = $util.newBuffer($util.base64.length(object.streamToken)), 0); - else if (object.streamToken.length >= 0) - message.streamToken = object.streamToken; - if (object.labels) { - if (typeof object.labels !== "object") - throw TypeError(".google.firestore.v1.WriteRequest.labels: object expected"); - message.labels = {}; - for (var keys = Object.keys(object.labels), i = 0; i < keys.length; ++i) - message.labels[keys[i]] = String(object.labels[keys[i]]); - } - return message; - }; + /** + * DotnetSettings renamedServices. + * @member {Object.} renamedServices + * @memberof google.api.DotnetSettings + * @instance + */ + DotnetSettings.prototype.renamedServices = $util.emptyObject; + + /** + * DotnetSettings renamedResources. + * @member {Object.} renamedResources + * @memberof google.api.DotnetSettings + * @instance + */ + DotnetSettings.prototype.renamedResources = $util.emptyObject; + + /** + * DotnetSettings ignoredResources. + * @member {Array.} ignoredResources + * @memberof google.api.DotnetSettings + * @instance + */ + DotnetSettings.prototype.ignoredResources = $util.emptyArray; - /** - * Creates a plain object from a WriteRequest message. Also converts values to other types if specified. - * @function toObject - * @memberof google.firestore.v1.WriteRequest - * @static - * @param {google.firestore.v1.WriteRequest} message WriteRequest - * @param {$protobuf.IConversionOptions} [options] Conversion options - * @returns {Object.} Plain object - */ - WriteRequest.toObject = function toObject(message, options) { - if (!options) - options = {}; - var object = {}; - if (options.arrays || options.defaults) - object.writes = []; - if (options.objects || options.defaults) - object.labels = {}; - if (options.defaults) { - object.database = ""; - object.streamId = ""; - if (options.bytes === String) - object.streamToken = ""; - else { - object.streamToken = []; - if (options.bytes !== Array) - object.streamToken = $util.newBuffer(object.streamToken); - } - } - if (message.database != null && message.hasOwnProperty("database")) - object.database = message.database; - if (message.streamId != null && message.hasOwnProperty("streamId")) - object.streamId = message.streamId; - if (message.writes && message.writes.length) { - object.writes = []; - for (var j = 0; j < message.writes.length; ++j) - object.writes[j] = $root.google.firestore.v1.Write.toObject(message.writes[j], options); - } - if (message.streamToken != null && message.hasOwnProperty("streamToken")) - object.streamToken = options.bytes === String ? $util.base64.encode(message.streamToken, 0, message.streamToken.length) : options.bytes === Array ? Array.prototype.slice.call(message.streamToken) : message.streamToken; - var keys2; - if (message.labels && (keys2 = Object.keys(message.labels)).length) { - object.labels = {}; - for (var j = 0; j < keys2.length; ++j) - object.labels[keys2[j]] = message.labels[keys2[j]]; - } + /** + * DotnetSettings forcedNamespaceAliases. + * @member {Array.} forcedNamespaceAliases + * @memberof google.api.DotnetSettings + * @instance + */ + DotnetSettings.prototype.forcedNamespaceAliases = $util.emptyArray; + + /** + * DotnetSettings handwrittenSignatures. + * @member {Array.} handwrittenSignatures + * @memberof google.api.DotnetSettings + * @instance + */ + DotnetSettings.prototype.handwrittenSignatures = $util.emptyArray; + + /** + * Creates a DotnetSettings message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.api.DotnetSettings + * @static + * @param {Object.} object Plain object + * @returns {google.api.DotnetSettings} DotnetSettings + */ + DotnetSettings.fromObject = function fromObject(object) { + if (object instanceof $root.google.api.DotnetSettings) return object; - }; + var message = new $root.google.api.DotnetSettings(); + if (object.common != null) { + if (typeof object.common !== "object") + throw TypeError(".google.api.DotnetSettings.common: object expected"); + message.common = $root.google.api.CommonLanguageSettings.fromObject(object.common); + } + if (object.renamedServices) { + if (typeof object.renamedServices !== "object") + throw TypeError(".google.api.DotnetSettings.renamedServices: object expected"); + message.renamedServices = {}; + for (var keys = Object.keys(object.renamedServices), i = 0; i < keys.length; ++i) + message.renamedServices[keys[i]] = String(object.renamedServices[keys[i]]); + } + if (object.renamedResources) { + if (typeof object.renamedResources !== "object") + throw TypeError(".google.api.DotnetSettings.renamedResources: object expected"); + message.renamedResources = {}; + for (var keys = Object.keys(object.renamedResources), i = 0; i < keys.length; ++i) + message.renamedResources[keys[i]] = String(object.renamedResources[keys[i]]); + } + if (object.ignoredResources) { + if (!Array.isArray(object.ignoredResources)) + throw TypeError(".google.api.DotnetSettings.ignoredResources: array expected"); + message.ignoredResources = []; + for (var i = 0; i < object.ignoredResources.length; ++i) + message.ignoredResources[i] = String(object.ignoredResources[i]); + } + if (object.forcedNamespaceAliases) { + if (!Array.isArray(object.forcedNamespaceAliases)) + throw TypeError(".google.api.DotnetSettings.forcedNamespaceAliases: array expected"); + message.forcedNamespaceAliases = []; + for (var i = 0; i < object.forcedNamespaceAliases.length; ++i) + message.forcedNamespaceAliases[i] = String(object.forcedNamespaceAliases[i]); + } + if (object.handwrittenSignatures) { + if (!Array.isArray(object.handwrittenSignatures)) + throw TypeError(".google.api.DotnetSettings.handwrittenSignatures: array expected"); + message.handwrittenSignatures = []; + for (var i = 0; i < object.handwrittenSignatures.length; ++i) + message.handwrittenSignatures[i] = String(object.handwrittenSignatures[i]); + } + return message; + }; - /** - * Converts this WriteRequest to JSON. - * @function toJSON - * @memberof google.firestore.v1.WriteRequest - * @instance - * @returns {Object.} JSON object - */ - WriteRequest.prototype.toJSON = function toJSON() { - return this.constructor.toObject(this, $protobuf.util.toJSONOptions); - }; + /** + * Creates a plain object from a DotnetSettings message. Also converts values to other types if specified. + * @function toObject + * @memberof google.api.DotnetSettings + * @static + * @param {google.api.DotnetSettings} message DotnetSettings + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + DotnetSettings.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.arrays || options.defaults) { + object.ignoredResources = []; + object.forcedNamespaceAliases = []; + object.handwrittenSignatures = []; + } + if (options.objects || options.defaults) { + object.renamedServices = {}; + object.renamedResources = {}; + } + if (options.defaults) + object.common = null; + if (message.common != null && message.hasOwnProperty("common")) + object.common = $root.google.api.CommonLanguageSettings.toObject(message.common, options); + var keys2; + if (message.renamedServices && (keys2 = Object.keys(message.renamedServices)).length) { + object.renamedServices = {}; + for (var j = 0; j < keys2.length; ++j) + object.renamedServices[keys2[j]] = message.renamedServices[keys2[j]]; + } + if (message.renamedResources && (keys2 = Object.keys(message.renamedResources)).length) { + object.renamedResources = {}; + for (var j = 0; j < keys2.length; ++j) + object.renamedResources[keys2[j]] = message.renamedResources[keys2[j]]; + } + if (message.ignoredResources && message.ignoredResources.length) { + object.ignoredResources = []; + for (var j = 0; j < message.ignoredResources.length; ++j) + object.ignoredResources[j] = message.ignoredResources[j]; + } + if (message.forcedNamespaceAliases && message.forcedNamespaceAliases.length) { + object.forcedNamespaceAliases = []; + for (var j = 0; j < message.forcedNamespaceAliases.length; ++j) + object.forcedNamespaceAliases[j] = message.forcedNamespaceAliases[j]; + } + if (message.handwrittenSignatures && message.handwrittenSignatures.length) { + object.handwrittenSignatures = []; + for (var j = 0; j < message.handwrittenSignatures.length; ++j) + object.handwrittenSignatures[j] = message.handwrittenSignatures[j]; + } + return object; + }; - /** - * Gets the default type url for WriteRequest - * @function getTypeUrl - * @memberof google.firestore.v1.WriteRequest - * @static - * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") - * @returns {string} The default type url - */ - WriteRequest.getTypeUrl = function getTypeUrl(typeUrlPrefix) { - if (typeUrlPrefix === undefined) { - typeUrlPrefix = "type.googleapis.com"; - } - return typeUrlPrefix + "/google.firestore.v1.WriteRequest"; - }; + /** + * Converts this DotnetSettings to JSON. + * @function toJSON + * @memberof google.api.DotnetSettings + * @instance + * @returns {Object.} JSON object + */ + DotnetSettings.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; - return WriteRequest; - })(); + /** + * Gets the default type url for DotnetSettings + * @function getTypeUrl + * @memberof google.api.DotnetSettings + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + DotnetSettings.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.api.DotnetSettings"; + }; - v1.WriteResponse = (function() { + return DotnetSettings; + })(); - /** - * Properties of a WriteResponse. - * @memberof google.firestore.v1 - * @interface IWriteResponse - * @property {string|null} [streamId] WriteResponse streamId - * @property {Uint8Array|null} [streamToken] WriteResponse streamToken - * @property {Array.|null} [writeResults] WriteResponse writeResults - * @property {google.protobuf.ITimestamp|null} [commitTime] WriteResponse commitTime - */ + api.RubySettings = (function() { + + /** + * Properties of a RubySettings. + * @memberof google.api + * @interface IRubySettings + * @property {google.api.ICommonLanguageSettings|null} [common] RubySettings common + */ + + /** + * Constructs a new RubySettings. + * @memberof google.api + * @classdesc Represents a RubySettings. + * @implements IRubySettings + * @constructor + * @param {google.api.IRubySettings=} [properties] Properties to set + */ + function RubySettings(properties) { + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } - /** - * Constructs a new WriteResponse. - * @memberof google.firestore.v1 - * @classdesc Represents a WriteResponse. - * @implements IWriteResponse - * @constructor - * @param {google.firestore.v1.IWriteResponse=} [properties] Properties to set - */ - function WriteResponse(properties) { - this.writeResults = []; - if (properties) - for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) - if (properties[keys[i]] != null) - this[keys[i]] = properties[keys[i]]; + /** + * RubySettings common. + * @member {google.api.ICommonLanguageSettings|null|undefined} common + * @memberof google.api.RubySettings + * @instance + */ + RubySettings.prototype.common = null; + + /** + * Creates a RubySettings message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.api.RubySettings + * @static + * @param {Object.} object Plain object + * @returns {google.api.RubySettings} RubySettings + */ + RubySettings.fromObject = function fromObject(object) { + if (object instanceof $root.google.api.RubySettings) + return object; + var message = new $root.google.api.RubySettings(); + if (object.common != null) { + if (typeof object.common !== "object") + throw TypeError(".google.api.RubySettings.common: object expected"); + message.common = $root.google.api.CommonLanguageSettings.fromObject(object.common); } + return message; + }; - /** - * WriteResponse streamId. - * @member {string} streamId - * @memberof google.firestore.v1.WriteResponse - * @instance - */ - WriteResponse.prototype.streamId = ""; + /** + * Creates a plain object from a RubySettings message. Also converts values to other types if specified. + * @function toObject + * @memberof google.api.RubySettings + * @static + * @param {google.api.RubySettings} message RubySettings + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + RubySettings.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.defaults) + object.common = null; + if (message.common != null && message.hasOwnProperty("common")) + object.common = $root.google.api.CommonLanguageSettings.toObject(message.common, options); + return object; + }; - /** - * WriteResponse streamToken. - * @member {Uint8Array} streamToken - * @memberof google.firestore.v1.WriteResponse - * @instance - */ - WriteResponse.prototype.streamToken = $util.newBuffer([]); + /** + * Converts this RubySettings to JSON. + * @function toJSON + * @memberof google.api.RubySettings + * @instance + * @returns {Object.} JSON object + */ + RubySettings.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; - /** - * WriteResponse writeResults. - * @member {Array.} writeResults - * @memberof google.firestore.v1.WriteResponse - * @instance - */ - WriteResponse.prototype.writeResults = $util.emptyArray; + /** + * Gets the default type url for RubySettings + * @function getTypeUrl + * @memberof google.api.RubySettings + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + RubySettings.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.api.RubySettings"; + }; - /** - * WriteResponse commitTime. - * @member {google.protobuf.ITimestamp|null|undefined} commitTime - * @memberof google.firestore.v1.WriteResponse - * @instance - */ - WriteResponse.prototype.commitTime = null; + return RubySettings; + })(); - /** - * Creates a WriteResponse message from a plain object. Also converts values to their respective internal types. - * @function fromObject - * @memberof google.firestore.v1.WriteResponse - * @static - * @param {Object.} object Plain object - * @returns {google.firestore.v1.WriteResponse} WriteResponse - */ - WriteResponse.fromObject = function fromObject(object) { - if (object instanceof $root.google.firestore.v1.WriteResponse) - return object; - var message = new $root.google.firestore.v1.WriteResponse(); - if (object.streamId != null) - message.streamId = String(object.streamId); - if (object.streamToken != null) - if (typeof object.streamToken === "string") - $util.base64.decode(object.streamToken, message.streamToken = $util.newBuffer($util.base64.length(object.streamToken)), 0); - else if (object.streamToken.length >= 0) - message.streamToken = object.streamToken; - if (object.writeResults) { - if (!Array.isArray(object.writeResults)) - throw TypeError(".google.firestore.v1.WriteResponse.writeResults: array expected"); - message.writeResults = []; - for (var i = 0; i < object.writeResults.length; ++i) { - if (typeof object.writeResults[i] !== "object") - throw TypeError(".google.firestore.v1.WriteResponse.writeResults: object expected"); - message.writeResults[i] = $root.google.firestore.v1.WriteResult.fromObject(object.writeResults[i]); - } - } - if (object.commitTime != null) { - if (typeof object.commitTime !== "object") - throw TypeError(".google.firestore.v1.WriteResponse.commitTime: object expected"); - message.commitTime = $root.google.protobuf.Timestamp.fromObject(object.commitTime); - } - return message; - }; + api.GoSettings = (function() { - /** - * Creates a plain object from a WriteResponse message. Also converts values to other types if specified. - * @function toObject - * @memberof google.firestore.v1.WriteResponse - * @static - * @param {google.firestore.v1.WriteResponse} message WriteResponse - * @param {$protobuf.IConversionOptions} [options] Conversion options - * @returns {Object.} Plain object - */ - WriteResponse.toObject = function toObject(message, options) { - if (!options) - options = {}; - var object = {}; - if (options.arrays || options.defaults) - object.writeResults = []; - if (options.defaults) { - object.streamId = ""; - if (options.bytes === String) - object.streamToken = ""; - else { - object.streamToken = []; - if (options.bytes !== Array) - object.streamToken = $util.newBuffer(object.streamToken); - } - object.commitTime = null; - } - if (message.streamId != null && message.hasOwnProperty("streamId")) - object.streamId = message.streamId; - if (message.streamToken != null && message.hasOwnProperty("streamToken")) - object.streamToken = options.bytes === String ? $util.base64.encode(message.streamToken, 0, message.streamToken.length) : options.bytes === Array ? Array.prototype.slice.call(message.streamToken) : message.streamToken; - if (message.writeResults && message.writeResults.length) { - object.writeResults = []; - for (var j = 0; j < message.writeResults.length; ++j) - object.writeResults[j] = $root.google.firestore.v1.WriteResult.toObject(message.writeResults[j], options); - } - if (message.commitTime != null && message.hasOwnProperty("commitTime")) - object.commitTime = $root.google.protobuf.Timestamp.toObject(message.commitTime, options); - return object; - }; + /** + * Properties of a GoSettings. + * @memberof google.api + * @interface IGoSettings + * @property {google.api.ICommonLanguageSettings|null} [common] GoSettings common + */ - /** - * Converts this WriteResponse to JSON. - * @function toJSON - * @memberof google.firestore.v1.WriteResponse - * @instance - * @returns {Object.} JSON object - */ - WriteResponse.prototype.toJSON = function toJSON() { - return this.constructor.toObject(this, $protobuf.util.toJSONOptions); - }; + /** + * Constructs a new GoSettings. + * @memberof google.api + * @classdesc Represents a GoSettings. + * @implements IGoSettings + * @constructor + * @param {google.api.IGoSettings=} [properties] Properties to set + */ + function GoSettings(properties) { + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } - /** - * Gets the default type url for WriteResponse - * @function getTypeUrl - * @memberof google.firestore.v1.WriteResponse - * @static - * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") - * @returns {string} The default type url - */ - WriteResponse.getTypeUrl = function getTypeUrl(typeUrlPrefix) { - if (typeUrlPrefix === undefined) { - typeUrlPrefix = "type.googleapis.com"; - } - return typeUrlPrefix + "/google.firestore.v1.WriteResponse"; - }; + /** + * GoSettings common. + * @member {google.api.ICommonLanguageSettings|null|undefined} common + * @memberof google.api.GoSettings + * @instance + */ + GoSettings.prototype.common = null; - return WriteResponse; - })(); + /** + * Creates a GoSettings message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.api.GoSettings + * @static + * @param {Object.} object Plain object + * @returns {google.api.GoSettings} GoSettings + */ + GoSettings.fromObject = function fromObject(object) { + if (object instanceof $root.google.api.GoSettings) + return object; + var message = new $root.google.api.GoSettings(); + if (object.common != null) { + if (typeof object.common !== "object") + throw TypeError(".google.api.GoSettings.common: object expected"); + message.common = $root.google.api.CommonLanguageSettings.fromObject(object.common); + } + return message; + }; - v1.ListenRequest = (function() { + /** + * Creates a plain object from a GoSettings message. Also converts values to other types if specified. + * @function toObject + * @memberof google.api.GoSettings + * @static + * @param {google.api.GoSettings} message GoSettings + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + GoSettings.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.defaults) + object.common = null; + if (message.common != null && message.hasOwnProperty("common")) + object.common = $root.google.api.CommonLanguageSettings.toObject(message.common, options); + return object; + }; - /** - * Properties of a ListenRequest. - * @memberof google.firestore.v1 - * @interface IListenRequest - * @property {string|null} [database] ListenRequest database - * @property {google.firestore.v1.ITarget|null} [addTarget] ListenRequest addTarget - * @property {number|null} [removeTarget] ListenRequest removeTarget - * @property {Object.|null} [labels] ListenRequest labels - */ + /** + * Converts this GoSettings to JSON. + * @function toJSON + * @memberof google.api.GoSettings + * @instance + * @returns {Object.} JSON object + */ + GoSettings.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; - /** - * Constructs a new ListenRequest. - * @memberof google.firestore.v1 - * @classdesc Represents a ListenRequest. - * @implements IListenRequest - * @constructor - * @param {google.firestore.v1.IListenRequest=} [properties] Properties to set - */ - function ListenRequest(properties) { - this.labels = {}; - if (properties) - for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) - if (properties[keys[i]] != null) - this[keys[i]] = properties[keys[i]]; + /** + * Gets the default type url for GoSettings + * @function getTypeUrl + * @memberof google.api.GoSettings + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + GoSettings.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; } + return typeUrlPrefix + "/google.api.GoSettings"; + }; - /** - * ListenRequest database. - * @member {string} database - * @memberof google.firestore.v1.ListenRequest - * @instance - */ - ListenRequest.prototype.database = ""; + return GoSettings; + })(); - /** - * ListenRequest addTarget. - * @member {google.firestore.v1.ITarget|null|undefined} addTarget - * @memberof google.firestore.v1.ListenRequest - * @instance - */ - ListenRequest.prototype.addTarget = null; + api.MethodSettings = (function() { - /** - * ListenRequest removeTarget. - * @member {number|null|undefined} removeTarget - * @memberof google.firestore.v1.ListenRequest - * @instance - */ - ListenRequest.prototype.removeTarget = null; + /** + * Properties of a MethodSettings. + * @memberof google.api + * @interface IMethodSettings + * @property {string|null} [selector] MethodSettings selector + * @property {google.api.MethodSettings.ILongRunning|null} [longRunning] MethodSettings longRunning + * @property {Array.|null} [autoPopulatedFields] MethodSettings autoPopulatedFields + */ - /** - * ListenRequest labels. - * @member {Object.} labels - * @memberof google.firestore.v1.ListenRequest - * @instance - */ - ListenRequest.prototype.labels = $util.emptyObject; + /** + * Constructs a new MethodSettings. + * @memberof google.api + * @classdesc Represents a MethodSettings. + * @implements IMethodSettings + * @constructor + * @param {google.api.IMethodSettings=} [properties] Properties to set + */ + function MethodSettings(properties) { + this.autoPopulatedFields = []; + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } - // OneOf field names bound to virtual getters and setters - var $oneOfFields; + /** + * MethodSettings selector. + * @member {string} selector + * @memberof google.api.MethodSettings + * @instance + */ + MethodSettings.prototype.selector = ""; - /** - * ListenRequest targetChange. - * @member {"addTarget"|"removeTarget"|undefined} targetChange - * @memberof google.firestore.v1.ListenRequest - * @instance - */ - Object.defineProperty(ListenRequest.prototype, "targetChange", { - get: $util.oneOfGetter($oneOfFields = ["addTarget", "removeTarget"]), - set: $util.oneOfSetter($oneOfFields) - }); + /** + * MethodSettings longRunning. + * @member {google.api.MethodSettings.ILongRunning|null|undefined} longRunning + * @memberof google.api.MethodSettings + * @instance + */ + MethodSettings.prototype.longRunning = null; - /** - * Creates a ListenRequest message from a plain object. Also converts values to their respective internal types. - * @function fromObject - * @memberof google.firestore.v1.ListenRequest - * @static - * @param {Object.} object Plain object - * @returns {google.firestore.v1.ListenRequest} ListenRequest - */ - ListenRequest.fromObject = function fromObject(object) { - if (object instanceof $root.google.firestore.v1.ListenRequest) - return object; - var message = new $root.google.firestore.v1.ListenRequest(); - if (object.database != null) - message.database = String(object.database); - if (object.addTarget != null) { - if (typeof object.addTarget !== "object") - throw TypeError(".google.firestore.v1.ListenRequest.addTarget: object expected"); - message.addTarget = $root.google.firestore.v1.Target.fromObject(object.addTarget); - } - if (object.removeTarget != null) - message.removeTarget = object.removeTarget | 0; - if (object.labels) { - if (typeof object.labels !== "object") - throw TypeError(".google.firestore.v1.ListenRequest.labels: object expected"); - message.labels = {}; - for (var keys = Object.keys(object.labels), i = 0; i < keys.length; ++i) - message.labels[keys[i]] = String(object.labels[keys[i]]); - } - return message; - }; + /** + * MethodSettings autoPopulatedFields. + * @member {Array.} autoPopulatedFields + * @memberof google.api.MethodSettings + * @instance + */ + MethodSettings.prototype.autoPopulatedFields = $util.emptyArray; - /** - * Creates a plain object from a ListenRequest message. Also converts values to other types if specified. - * @function toObject - * @memberof google.firestore.v1.ListenRequest - * @static - * @param {google.firestore.v1.ListenRequest} message ListenRequest - * @param {$protobuf.IConversionOptions} [options] Conversion options - * @returns {Object.} Plain object - */ - ListenRequest.toObject = function toObject(message, options) { - if (!options) - options = {}; - var object = {}; - if (options.objects || options.defaults) - object.labels = {}; - if (options.defaults) - object.database = ""; - if (message.database != null && message.hasOwnProperty("database")) - object.database = message.database; - if (message.addTarget != null && message.hasOwnProperty("addTarget")) { - object.addTarget = $root.google.firestore.v1.Target.toObject(message.addTarget, options); - if (options.oneofs) - object.targetChange = "addTarget"; - } - if (message.removeTarget != null && message.hasOwnProperty("removeTarget")) { - object.removeTarget = message.removeTarget; - if (options.oneofs) - object.targetChange = "removeTarget"; - } - var keys2; - if (message.labels && (keys2 = Object.keys(message.labels)).length) { - object.labels = {}; - for (var j = 0; j < keys2.length; ++j) - object.labels[keys2[j]] = message.labels[keys2[j]]; - } + /** + * Creates a MethodSettings message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.api.MethodSettings + * @static + * @param {Object.} object Plain object + * @returns {google.api.MethodSettings} MethodSettings + */ + MethodSettings.fromObject = function fromObject(object) { + if (object instanceof $root.google.api.MethodSettings) return object; - }; - - /** - * Converts this ListenRequest to JSON. - * @function toJSON - * @memberof google.firestore.v1.ListenRequest - * @instance - * @returns {Object.} JSON object - */ - ListenRequest.prototype.toJSON = function toJSON() { - return this.constructor.toObject(this, $protobuf.util.toJSONOptions); - }; + var message = new $root.google.api.MethodSettings(); + if (object.selector != null) + message.selector = String(object.selector); + if (object.longRunning != null) { + if (typeof object.longRunning !== "object") + throw TypeError(".google.api.MethodSettings.longRunning: object expected"); + message.longRunning = $root.google.api.MethodSettings.LongRunning.fromObject(object.longRunning); + } + if (object.autoPopulatedFields) { + if (!Array.isArray(object.autoPopulatedFields)) + throw TypeError(".google.api.MethodSettings.autoPopulatedFields: array expected"); + message.autoPopulatedFields = []; + for (var i = 0; i < object.autoPopulatedFields.length; ++i) + message.autoPopulatedFields[i] = String(object.autoPopulatedFields[i]); + } + return message; + }; - /** - * Gets the default type url for ListenRequest - * @function getTypeUrl - * @memberof google.firestore.v1.ListenRequest - * @static - * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") - * @returns {string} The default type url - */ - ListenRequest.getTypeUrl = function getTypeUrl(typeUrlPrefix) { - if (typeUrlPrefix === undefined) { - typeUrlPrefix = "type.googleapis.com"; - } - return typeUrlPrefix + "/google.firestore.v1.ListenRequest"; - }; + /** + * Creates a plain object from a MethodSettings message. Also converts values to other types if specified. + * @function toObject + * @memberof google.api.MethodSettings + * @static + * @param {google.api.MethodSettings} message MethodSettings + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + MethodSettings.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.arrays || options.defaults) + object.autoPopulatedFields = []; + if (options.defaults) { + object.selector = ""; + object.longRunning = null; + } + if (message.selector != null && message.hasOwnProperty("selector")) + object.selector = message.selector; + if (message.longRunning != null && message.hasOwnProperty("longRunning")) + object.longRunning = $root.google.api.MethodSettings.LongRunning.toObject(message.longRunning, options); + if (message.autoPopulatedFields && message.autoPopulatedFields.length) { + object.autoPopulatedFields = []; + for (var j = 0; j < message.autoPopulatedFields.length; ++j) + object.autoPopulatedFields[j] = message.autoPopulatedFields[j]; + } + return object; + }; - return ListenRequest; - })(); + /** + * Converts this MethodSettings to JSON. + * @function toJSON + * @memberof google.api.MethodSettings + * @instance + * @returns {Object.} JSON object + */ + MethodSettings.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; - v1.ListenResponse = (function() { + /** + * Gets the default type url for MethodSettings + * @function getTypeUrl + * @memberof google.api.MethodSettings + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + MethodSettings.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.api.MethodSettings"; + }; + + MethodSettings.LongRunning = (function() { /** - * Properties of a ListenResponse. - * @memberof google.firestore.v1 - * @interface IListenResponse - * @property {google.firestore.v1.ITargetChange|null} [targetChange] ListenResponse targetChange - * @property {google.firestore.v1.IDocumentChange|null} [documentChange] ListenResponse documentChange - * @property {google.firestore.v1.IDocumentDelete|null} [documentDelete] ListenResponse documentDelete - * @property {google.firestore.v1.IDocumentRemove|null} [documentRemove] ListenResponse documentRemove - * @property {google.firestore.v1.IExistenceFilter|null} [filter] ListenResponse filter + * Properties of a LongRunning. + * @memberof google.api.MethodSettings + * @interface ILongRunning + * @property {google.protobuf.IDuration|null} [initialPollDelay] LongRunning initialPollDelay + * @property {number|null} [pollDelayMultiplier] LongRunning pollDelayMultiplier + * @property {google.protobuf.IDuration|null} [maxPollDelay] LongRunning maxPollDelay + * @property {google.protobuf.IDuration|null} [totalPollTimeout] LongRunning totalPollTimeout */ /** - * Constructs a new ListenResponse. - * @memberof google.firestore.v1 - * @classdesc Represents a ListenResponse. - * @implements IListenResponse + * Constructs a new LongRunning. + * @memberof google.api.MethodSettings + * @classdesc Represents a LongRunning. + * @implements ILongRunning * @constructor - * @param {google.firestore.v1.IListenResponse=} [properties] Properties to set + * @param {google.api.MethodSettings.ILongRunning=} [properties] Properties to set */ - function ListenResponse(properties) { + function LongRunning(properties) { if (properties) for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) if (properties[keys[i]] != null) @@ -16624,1168 +15739,1471 @@ } /** - * ListenResponse targetChange. - * @member {google.firestore.v1.ITargetChange|null|undefined} targetChange - * @memberof google.firestore.v1.ListenResponse - * @instance - */ - ListenResponse.prototype.targetChange = null; - - /** - * ListenResponse documentChange. - * @member {google.firestore.v1.IDocumentChange|null|undefined} documentChange - * @memberof google.firestore.v1.ListenResponse - * @instance - */ - ListenResponse.prototype.documentChange = null; - - /** - * ListenResponse documentDelete. - * @member {google.firestore.v1.IDocumentDelete|null|undefined} documentDelete - * @memberof google.firestore.v1.ListenResponse + * LongRunning initialPollDelay. + * @member {google.protobuf.IDuration|null|undefined} initialPollDelay + * @memberof google.api.MethodSettings.LongRunning * @instance */ - ListenResponse.prototype.documentDelete = null; + LongRunning.prototype.initialPollDelay = null; /** - * ListenResponse documentRemove. - * @member {google.firestore.v1.IDocumentRemove|null|undefined} documentRemove - * @memberof google.firestore.v1.ListenResponse + * LongRunning pollDelayMultiplier. + * @member {number} pollDelayMultiplier + * @memberof google.api.MethodSettings.LongRunning * @instance */ - ListenResponse.prototype.documentRemove = null; + LongRunning.prototype.pollDelayMultiplier = 0; /** - * ListenResponse filter. - * @member {google.firestore.v1.IExistenceFilter|null|undefined} filter - * @memberof google.firestore.v1.ListenResponse + * LongRunning maxPollDelay. + * @member {google.protobuf.IDuration|null|undefined} maxPollDelay + * @memberof google.api.MethodSettings.LongRunning * @instance */ - ListenResponse.prototype.filter = null; - - // OneOf field names bound to virtual getters and setters - var $oneOfFields; + LongRunning.prototype.maxPollDelay = null; /** - * ListenResponse responseType. - * @member {"targetChange"|"documentChange"|"documentDelete"|"documentRemove"|"filter"|undefined} responseType - * @memberof google.firestore.v1.ListenResponse + * LongRunning totalPollTimeout. + * @member {google.protobuf.IDuration|null|undefined} totalPollTimeout + * @memberof google.api.MethodSettings.LongRunning * @instance */ - Object.defineProperty(ListenResponse.prototype, "responseType", { - get: $util.oneOfGetter($oneOfFields = ["targetChange", "documentChange", "documentDelete", "documentRemove", "filter"]), - set: $util.oneOfSetter($oneOfFields) - }); + LongRunning.prototype.totalPollTimeout = null; /** - * Creates a ListenResponse message from a plain object. Also converts values to their respective internal types. + * Creates a LongRunning message from a plain object. Also converts values to their respective internal types. * @function fromObject - * @memberof google.firestore.v1.ListenResponse + * @memberof google.api.MethodSettings.LongRunning * @static * @param {Object.} object Plain object - * @returns {google.firestore.v1.ListenResponse} ListenResponse + * @returns {google.api.MethodSettings.LongRunning} LongRunning */ - ListenResponse.fromObject = function fromObject(object) { - if (object instanceof $root.google.firestore.v1.ListenResponse) + LongRunning.fromObject = function fromObject(object) { + if (object instanceof $root.google.api.MethodSettings.LongRunning) return object; - var message = new $root.google.firestore.v1.ListenResponse(); - if (object.targetChange != null) { - if (typeof object.targetChange !== "object") - throw TypeError(".google.firestore.v1.ListenResponse.targetChange: object expected"); - message.targetChange = $root.google.firestore.v1.TargetChange.fromObject(object.targetChange); - } - if (object.documentChange != null) { - if (typeof object.documentChange !== "object") - throw TypeError(".google.firestore.v1.ListenResponse.documentChange: object expected"); - message.documentChange = $root.google.firestore.v1.DocumentChange.fromObject(object.documentChange); - } - if (object.documentDelete != null) { - if (typeof object.documentDelete !== "object") - throw TypeError(".google.firestore.v1.ListenResponse.documentDelete: object expected"); - message.documentDelete = $root.google.firestore.v1.DocumentDelete.fromObject(object.documentDelete); + var message = new $root.google.api.MethodSettings.LongRunning(); + if (object.initialPollDelay != null) { + if (typeof object.initialPollDelay !== "object") + throw TypeError(".google.api.MethodSettings.LongRunning.initialPollDelay: object expected"); + message.initialPollDelay = $root.google.protobuf.Duration.fromObject(object.initialPollDelay); } - if (object.documentRemove != null) { - if (typeof object.documentRemove !== "object") - throw TypeError(".google.firestore.v1.ListenResponse.documentRemove: object expected"); - message.documentRemove = $root.google.firestore.v1.DocumentRemove.fromObject(object.documentRemove); + if (object.pollDelayMultiplier != null) + message.pollDelayMultiplier = Number(object.pollDelayMultiplier); + if (object.maxPollDelay != null) { + if (typeof object.maxPollDelay !== "object") + throw TypeError(".google.api.MethodSettings.LongRunning.maxPollDelay: object expected"); + message.maxPollDelay = $root.google.protobuf.Duration.fromObject(object.maxPollDelay); } - if (object.filter != null) { - if (typeof object.filter !== "object") - throw TypeError(".google.firestore.v1.ListenResponse.filter: object expected"); - message.filter = $root.google.firestore.v1.ExistenceFilter.fromObject(object.filter); + if (object.totalPollTimeout != null) { + if (typeof object.totalPollTimeout !== "object") + throw TypeError(".google.api.MethodSettings.LongRunning.totalPollTimeout: object expected"); + message.totalPollTimeout = $root.google.protobuf.Duration.fromObject(object.totalPollTimeout); } return message; }; /** - * Creates a plain object from a ListenResponse message. Also converts values to other types if specified. + * Creates a plain object from a LongRunning message. Also converts values to other types if specified. * @function toObject - * @memberof google.firestore.v1.ListenResponse + * @memberof google.api.MethodSettings.LongRunning * @static - * @param {google.firestore.v1.ListenResponse} message ListenResponse + * @param {google.api.MethodSettings.LongRunning} message LongRunning * @param {$protobuf.IConversionOptions} [options] Conversion options * @returns {Object.} Plain object */ - ListenResponse.toObject = function toObject(message, options) { + LongRunning.toObject = function toObject(message, options) { if (!options) options = {}; var object = {}; - if (message.targetChange != null && message.hasOwnProperty("targetChange")) { - object.targetChange = $root.google.firestore.v1.TargetChange.toObject(message.targetChange, options); - if (options.oneofs) - object.responseType = "targetChange"; - } - if (message.documentChange != null && message.hasOwnProperty("documentChange")) { - object.documentChange = $root.google.firestore.v1.DocumentChange.toObject(message.documentChange, options); - if (options.oneofs) - object.responseType = "documentChange"; - } - if (message.documentDelete != null && message.hasOwnProperty("documentDelete")) { - object.documentDelete = $root.google.firestore.v1.DocumentDelete.toObject(message.documentDelete, options); - if (options.oneofs) - object.responseType = "documentDelete"; - } - if (message.filter != null && message.hasOwnProperty("filter")) { - object.filter = $root.google.firestore.v1.ExistenceFilter.toObject(message.filter, options); - if (options.oneofs) - object.responseType = "filter"; - } - if (message.documentRemove != null && message.hasOwnProperty("documentRemove")) { - object.documentRemove = $root.google.firestore.v1.DocumentRemove.toObject(message.documentRemove, options); - if (options.oneofs) - object.responseType = "documentRemove"; + if (options.defaults) { + object.initialPollDelay = null; + object.pollDelayMultiplier = 0; + object.maxPollDelay = null; + object.totalPollTimeout = null; } + if (message.initialPollDelay != null && message.hasOwnProperty("initialPollDelay")) + object.initialPollDelay = $root.google.protobuf.Duration.toObject(message.initialPollDelay, options); + if (message.pollDelayMultiplier != null && message.hasOwnProperty("pollDelayMultiplier")) + object.pollDelayMultiplier = options.json && !isFinite(message.pollDelayMultiplier) ? String(message.pollDelayMultiplier) : message.pollDelayMultiplier; + if (message.maxPollDelay != null && message.hasOwnProperty("maxPollDelay")) + object.maxPollDelay = $root.google.protobuf.Duration.toObject(message.maxPollDelay, options); + if (message.totalPollTimeout != null && message.hasOwnProperty("totalPollTimeout")) + object.totalPollTimeout = $root.google.protobuf.Duration.toObject(message.totalPollTimeout, options); return object; }; /** - * Converts this ListenResponse to JSON. + * Converts this LongRunning to JSON. * @function toJSON - * @memberof google.firestore.v1.ListenResponse + * @memberof google.api.MethodSettings.LongRunning * @instance * @returns {Object.} JSON object */ - ListenResponse.prototype.toJSON = function toJSON() { + LongRunning.prototype.toJSON = function toJSON() { return this.constructor.toObject(this, $protobuf.util.toJSONOptions); }; /** - * Gets the default type url for ListenResponse + * Gets the default type url for LongRunning * @function getTypeUrl - * @memberof google.firestore.v1.ListenResponse + * @memberof google.api.MethodSettings.LongRunning * @static * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") * @returns {string} The default type url */ - ListenResponse.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + LongRunning.getTypeUrl = function getTypeUrl(typeUrlPrefix) { if (typeUrlPrefix === undefined) { typeUrlPrefix = "type.googleapis.com"; } - return typeUrlPrefix + "/google.firestore.v1.ListenResponse"; + return typeUrlPrefix + "/google.api.MethodSettings.LongRunning"; }; - return ListenResponse; + return LongRunning; })(); - v1.Target = (function() { + return MethodSettings; + })(); - /** - * Properties of a Target. - * @memberof google.firestore.v1 - * @interface ITarget - * @property {google.firestore.v1.Target.IQueryTarget|null} [query] Target query - * @property {google.firestore.v1.Target.IDocumentsTarget|null} [documents] Target documents - * @property {Uint8Array|null} [resumeToken] Target resumeToken - * @property {google.protobuf.ITimestamp|null} [readTime] Target readTime - * @property {number|null} [targetId] Target targetId - * @property {boolean|null} [once] Target once - * @property {google.protobuf.IInt32Value|null} [expectedCount] Target expectedCount - */ + /** + * ClientLibraryOrganization enum. + * @name google.api.ClientLibraryOrganization + * @enum {string} + * @property {string} CLIENT_LIBRARY_ORGANIZATION_UNSPECIFIED=CLIENT_LIBRARY_ORGANIZATION_UNSPECIFIED CLIENT_LIBRARY_ORGANIZATION_UNSPECIFIED value + * @property {string} CLOUD=CLOUD CLOUD value + * @property {string} ADS=ADS ADS value + * @property {string} PHOTOS=PHOTOS PHOTOS value + * @property {string} STREET_VIEW=STREET_VIEW STREET_VIEW value + * @property {string} SHOPPING=SHOPPING SHOPPING value + * @property {string} GEO=GEO GEO value + * @property {string} GENERATIVE_AI=GENERATIVE_AI GENERATIVE_AI value + */ + api.ClientLibraryOrganization = (function() { + var valuesById = {}, values = Object.create(valuesById); + values[valuesById[0] = "CLIENT_LIBRARY_ORGANIZATION_UNSPECIFIED"] = "CLIENT_LIBRARY_ORGANIZATION_UNSPECIFIED"; + values[valuesById[1] = "CLOUD"] = "CLOUD"; + values[valuesById[2] = "ADS"] = "ADS"; + values[valuesById[3] = "PHOTOS"] = "PHOTOS"; + values[valuesById[4] = "STREET_VIEW"] = "STREET_VIEW"; + values[valuesById[5] = "SHOPPING"] = "SHOPPING"; + values[valuesById[6] = "GEO"] = "GEO"; + values[valuesById[7] = "GENERATIVE_AI"] = "GENERATIVE_AI"; + return values; + })(); - /** - * Constructs a new Target. - * @memberof google.firestore.v1 - * @classdesc Represents a Target. - * @implements ITarget - * @constructor - * @param {google.firestore.v1.ITarget=} [properties] Properties to set - */ - function Target(properties) { - if (properties) - for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) - if (properties[keys[i]] != null) - this[keys[i]] = properties[keys[i]]; + /** + * ClientLibraryDestination enum. + * @name google.api.ClientLibraryDestination + * @enum {string} + * @property {string} CLIENT_LIBRARY_DESTINATION_UNSPECIFIED=CLIENT_LIBRARY_DESTINATION_UNSPECIFIED CLIENT_LIBRARY_DESTINATION_UNSPECIFIED value + * @property {string} GITHUB=GITHUB GITHUB value + * @property {string} PACKAGE_MANAGER=PACKAGE_MANAGER PACKAGE_MANAGER value + */ + api.ClientLibraryDestination = (function() { + var valuesById = {}, values = Object.create(valuesById); + values[valuesById[0] = "CLIENT_LIBRARY_DESTINATION_UNSPECIFIED"] = "CLIENT_LIBRARY_DESTINATION_UNSPECIFIED"; + values[valuesById[10] = "GITHUB"] = "GITHUB"; + values[valuesById[20] = "PACKAGE_MANAGER"] = "PACKAGE_MANAGER"; + return values; + })(); + + /** + * LaunchStage enum. + * @name google.api.LaunchStage + * @enum {string} + * @property {string} LAUNCH_STAGE_UNSPECIFIED=LAUNCH_STAGE_UNSPECIFIED LAUNCH_STAGE_UNSPECIFIED value + * @property {string} UNIMPLEMENTED=UNIMPLEMENTED UNIMPLEMENTED value + * @property {string} PRELAUNCH=PRELAUNCH PRELAUNCH value + * @property {string} EARLY_ACCESS=EARLY_ACCESS EARLY_ACCESS value + * @property {string} ALPHA=ALPHA ALPHA value + * @property {string} BETA=BETA BETA value + * @property {string} GA=GA GA value + * @property {string} DEPRECATED=DEPRECATED DEPRECATED value + */ + api.LaunchStage = (function() { + var valuesById = {}, values = Object.create(valuesById); + values[valuesById[0] = "LAUNCH_STAGE_UNSPECIFIED"] = "LAUNCH_STAGE_UNSPECIFIED"; + values[valuesById[6] = "UNIMPLEMENTED"] = "UNIMPLEMENTED"; + values[valuesById[7] = "PRELAUNCH"] = "PRELAUNCH"; + values[valuesById[1] = "EARLY_ACCESS"] = "EARLY_ACCESS"; + values[valuesById[2] = "ALPHA"] = "ALPHA"; + values[valuesById[3] = "BETA"] = "BETA"; + values[valuesById[4] = "GA"] = "GA"; + values[valuesById[5] = "DEPRECATED"] = "DEPRECATED"; + return values; + })(); + + api.ResourceDescriptor = (function() { + + /** + * Properties of a ResourceDescriptor. + * @memberof google.api + * @interface IResourceDescriptor + * @property {string|null} [type] ResourceDescriptor type + * @property {Array.|null} [pattern] ResourceDescriptor pattern + * @property {string|null} [nameField] ResourceDescriptor nameField + * @property {google.api.ResourceDescriptor.History|null} [history] ResourceDescriptor history + * @property {string|null} [plural] ResourceDescriptor plural + * @property {string|null} [singular] ResourceDescriptor singular + * @property {Array.|null} [style] ResourceDescriptor style + */ + + /** + * Constructs a new ResourceDescriptor. + * @memberof google.api + * @classdesc Represents a ResourceDescriptor. + * @implements IResourceDescriptor + * @constructor + * @param {google.api.IResourceDescriptor=} [properties] Properties to set + */ + function ResourceDescriptor(properties) { + this.pattern = []; + this.style = []; + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } + + /** + * ResourceDescriptor type. + * @member {string} type + * @memberof google.api.ResourceDescriptor + * @instance + */ + ResourceDescriptor.prototype.type = ""; + + /** + * ResourceDescriptor pattern. + * @member {Array.} pattern + * @memberof google.api.ResourceDescriptor + * @instance + */ + ResourceDescriptor.prototype.pattern = $util.emptyArray; + + /** + * ResourceDescriptor nameField. + * @member {string} nameField + * @memberof google.api.ResourceDescriptor + * @instance + */ + ResourceDescriptor.prototype.nameField = ""; + + /** + * ResourceDescriptor history. + * @member {google.api.ResourceDescriptor.History} history + * @memberof google.api.ResourceDescriptor + * @instance + */ + ResourceDescriptor.prototype.history = 0; + + /** + * ResourceDescriptor plural. + * @member {string} plural + * @memberof google.api.ResourceDescriptor + * @instance + */ + ResourceDescriptor.prototype.plural = ""; + + /** + * ResourceDescriptor singular. + * @member {string} singular + * @memberof google.api.ResourceDescriptor + * @instance + */ + ResourceDescriptor.prototype.singular = ""; + + /** + * ResourceDescriptor style. + * @member {Array.} style + * @memberof google.api.ResourceDescriptor + * @instance + */ + ResourceDescriptor.prototype.style = $util.emptyArray; + + /** + * Creates a ResourceDescriptor message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.api.ResourceDescriptor + * @static + * @param {Object.} object Plain object + * @returns {google.api.ResourceDescriptor} ResourceDescriptor + */ + ResourceDescriptor.fromObject = function fromObject(object) { + if (object instanceof $root.google.api.ResourceDescriptor) + return object; + var message = new $root.google.api.ResourceDescriptor(); + if (object.type != null) + message.type = String(object.type); + if (object.pattern) { + if (!Array.isArray(object.pattern)) + throw TypeError(".google.api.ResourceDescriptor.pattern: array expected"); + message.pattern = []; + for (var i = 0; i < object.pattern.length; ++i) + message.pattern[i] = String(object.pattern[i]); + } + if (object.nameField != null) + message.nameField = String(object.nameField); + switch (object.history) { + default: + if (typeof object.history === "number") { + message.history = object.history; + break; + } + break; + case "HISTORY_UNSPECIFIED": + case 0: + message.history = 0; + break; + case "ORIGINALLY_SINGLE_PATTERN": + case 1: + message.history = 1; + break; + case "FUTURE_MULTI_PATTERN": + case 2: + message.history = 2; + break; + } + if (object.plural != null) + message.plural = String(object.plural); + if (object.singular != null) + message.singular = String(object.singular); + if (object.style) { + if (!Array.isArray(object.style)) + throw TypeError(".google.api.ResourceDescriptor.style: array expected"); + message.style = []; + for (var i = 0; i < object.style.length; ++i) + switch (object.style[i]) { + default: + if (typeof object.style[i] === "number") { + message.style[i] = object.style[i]; + break; + } + case "STYLE_UNSPECIFIED": + case 0: + message.style[i] = 0; + break; + case "DECLARATIVE_FRIENDLY": + case 1: + message.style[i] = 1; + break; + } } + return message; + }; - /** - * Target query. - * @member {google.firestore.v1.Target.IQueryTarget|null|undefined} query - * @memberof google.firestore.v1.Target - * @instance - */ - Target.prototype.query = null; - - /** - * Target documents. - * @member {google.firestore.v1.Target.IDocumentsTarget|null|undefined} documents - * @memberof google.firestore.v1.Target - * @instance - */ - Target.prototype.documents = null; - - /** - * Target resumeToken. - * @member {Uint8Array|null|undefined} resumeToken - * @memberof google.firestore.v1.Target - * @instance - */ - Target.prototype.resumeToken = null; - - /** - * Target readTime. - * @member {google.protobuf.ITimestamp|null|undefined} readTime - * @memberof google.firestore.v1.Target - * @instance - */ - Target.prototype.readTime = null; - - /** - * Target targetId. - * @member {number} targetId - * @memberof google.firestore.v1.Target - * @instance - */ - Target.prototype.targetId = 0; - - /** - * Target once. - * @member {boolean} once - * @memberof google.firestore.v1.Target - * @instance - */ - Target.prototype.once = false; - - /** - * Target expectedCount. - * @member {google.protobuf.IInt32Value|null|undefined} expectedCount - * @memberof google.firestore.v1.Target - * @instance - */ - Target.prototype.expectedCount = null; - - // OneOf field names bound to virtual getters and setters - var $oneOfFields; - - /** - * Target targetType. - * @member {"query"|"documents"|undefined} targetType - * @memberof google.firestore.v1.Target - * @instance - */ - Object.defineProperty(Target.prototype, "targetType", { - get: $util.oneOfGetter($oneOfFields = ["query", "documents"]), - set: $util.oneOfSetter($oneOfFields) - }); + /** + * Creates a plain object from a ResourceDescriptor message. Also converts values to other types if specified. + * @function toObject + * @memberof google.api.ResourceDescriptor + * @static + * @param {google.api.ResourceDescriptor} message ResourceDescriptor + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + ResourceDescriptor.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.arrays || options.defaults) { + object.pattern = []; + object.style = []; + } + if (options.defaults) { + object.type = ""; + object.nameField = ""; + object.history = options.enums === String ? "HISTORY_UNSPECIFIED" : 0; + object.plural = ""; + object.singular = ""; + } + if (message.type != null && message.hasOwnProperty("type")) + object.type = message.type; + if (message.pattern && message.pattern.length) { + object.pattern = []; + for (var j = 0; j < message.pattern.length; ++j) + object.pattern[j] = message.pattern[j]; + } + if (message.nameField != null && message.hasOwnProperty("nameField")) + object.nameField = message.nameField; + if (message.history != null && message.hasOwnProperty("history")) + object.history = options.enums === String ? $root.google.api.ResourceDescriptor.History[message.history] === undefined ? message.history : $root.google.api.ResourceDescriptor.History[message.history] : message.history; + if (message.plural != null && message.hasOwnProperty("plural")) + object.plural = message.plural; + if (message.singular != null && message.hasOwnProperty("singular")) + object.singular = message.singular; + if (message.style && message.style.length) { + object.style = []; + for (var j = 0; j < message.style.length; ++j) + object.style[j] = options.enums === String ? $root.google.api.ResourceDescriptor.Style[message.style[j]] === undefined ? message.style[j] : $root.google.api.ResourceDescriptor.Style[message.style[j]] : message.style[j]; + } + return object; + }; - /** - * Target resumeType. - * @member {"resumeToken"|"readTime"|undefined} resumeType - * @memberof google.firestore.v1.Target - * @instance - */ - Object.defineProperty(Target.prototype, "resumeType", { - get: $util.oneOfGetter($oneOfFields = ["resumeToken", "readTime"]), - set: $util.oneOfSetter($oneOfFields) - }); + /** + * Converts this ResourceDescriptor to JSON. + * @function toJSON + * @memberof google.api.ResourceDescriptor + * @instance + * @returns {Object.} JSON object + */ + ResourceDescriptor.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; - /** - * Creates a Target message from a plain object. Also converts values to their respective internal types. - * @function fromObject - * @memberof google.firestore.v1.Target - * @static - * @param {Object.} object Plain object - * @returns {google.firestore.v1.Target} Target - */ - Target.fromObject = function fromObject(object) { - if (object instanceof $root.google.firestore.v1.Target) - return object; - var message = new $root.google.firestore.v1.Target(); - if (object.query != null) { - if (typeof object.query !== "object") - throw TypeError(".google.firestore.v1.Target.query: object expected"); - message.query = $root.google.firestore.v1.Target.QueryTarget.fromObject(object.query); - } - if (object.documents != null) { - if (typeof object.documents !== "object") - throw TypeError(".google.firestore.v1.Target.documents: object expected"); - message.documents = $root.google.firestore.v1.Target.DocumentsTarget.fromObject(object.documents); - } - if (object.resumeToken != null) - if (typeof object.resumeToken === "string") - $util.base64.decode(object.resumeToken, message.resumeToken = $util.newBuffer($util.base64.length(object.resumeToken)), 0); - else if (object.resumeToken.length >= 0) - message.resumeToken = object.resumeToken; - if (object.readTime != null) { - if (typeof object.readTime !== "object") - throw TypeError(".google.firestore.v1.Target.readTime: object expected"); - message.readTime = $root.google.protobuf.Timestamp.fromObject(object.readTime); - } - if (object.targetId != null) - message.targetId = object.targetId | 0; - if (object.once != null) - message.once = Boolean(object.once); - if (object.expectedCount != null) { - if (typeof object.expectedCount !== "object") - throw TypeError(".google.firestore.v1.Target.expectedCount: object expected"); - message.expectedCount = $root.google.protobuf.Int32Value.fromObject(object.expectedCount); - } - return message; - }; + /** + * Gets the default type url for ResourceDescriptor + * @function getTypeUrl + * @memberof google.api.ResourceDescriptor + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + ResourceDescriptor.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.api.ResourceDescriptor"; + }; - /** - * Creates a plain object from a Target message. Also converts values to other types if specified. - * @function toObject - * @memberof google.firestore.v1.Target - * @static - * @param {google.firestore.v1.Target} message Target - * @param {$protobuf.IConversionOptions} [options] Conversion options - * @returns {Object.} Plain object - */ - Target.toObject = function toObject(message, options) { - if (!options) - options = {}; - var object = {}; - if (options.defaults) { - object.targetId = 0; - object.once = false; - object.expectedCount = null; - } - if (message.query != null && message.hasOwnProperty("query")) { - object.query = $root.google.firestore.v1.Target.QueryTarget.toObject(message.query, options); - if (options.oneofs) - object.targetType = "query"; - } - if (message.documents != null && message.hasOwnProperty("documents")) { - object.documents = $root.google.firestore.v1.Target.DocumentsTarget.toObject(message.documents, options); - if (options.oneofs) - object.targetType = "documents"; - } - if (message.resumeToken != null && message.hasOwnProperty("resumeToken")) { - object.resumeToken = options.bytes === String ? $util.base64.encode(message.resumeToken, 0, message.resumeToken.length) : options.bytes === Array ? Array.prototype.slice.call(message.resumeToken) : message.resumeToken; - if (options.oneofs) - object.resumeType = "resumeToken"; - } - if (message.targetId != null && message.hasOwnProperty("targetId")) - object.targetId = message.targetId; - if (message.once != null && message.hasOwnProperty("once")) - object.once = message.once; - if (message.readTime != null && message.hasOwnProperty("readTime")) { - object.readTime = $root.google.protobuf.Timestamp.toObject(message.readTime, options); - if (options.oneofs) - object.resumeType = "readTime"; - } - if (message.expectedCount != null && message.hasOwnProperty("expectedCount")) - object.expectedCount = $root.google.protobuf.Int32Value.toObject(message.expectedCount, options); - return object; - }; + /** + * History enum. + * @name google.api.ResourceDescriptor.History + * @enum {string} + * @property {string} HISTORY_UNSPECIFIED=HISTORY_UNSPECIFIED HISTORY_UNSPECIFIED value + * @property {string} ORIGINALLY_SINGLE_PATTERN=ORIGINALLY_SINGLE_PATTERN ORIGINALLY_SINGLE_PATTERN value + * @property {string} FUTURE_MULTI_PATTERN=FUTURE_MULTI_PATTERN FUTURE_MULTI_PATTERN value + */ + ResourceDescriptor.History = (function() { + var valuesById = {}, values = Object.create(valuesById); + values[valuesById[0] = "HISTORY_UNSPECIFIED"] = "HISTORY_UNSPECIFIED"; + values[valuesById[1] = "ORIGINALLY_SINGLE_PATTERN"] = "ORIGINALLY_SINGLE_PATTERN"; + values[valuesById[2] = "FUTURE_MULTI_PATTERN"] = "FUTURE_MULTI_PATTERN"; + return values; + })(); - /** - * Converts this Target to JSON. - * @function toJSON - * @memberof google.firestore.v1.Target - * @instance - * @returns {Object.} JSON object - */ - Target.prototype.toJSON = function toJSON() { - return this.constructor.toObject(this, $protobuf.util.toJSONOptions); - }; + /** + * Style enum. + * @name google.api.ResourceDescriptor.Style + * @enum {string} + * @property {string} STYLE_UNSPECIFIED=STYLE_UNSPECIFIED STYLE_UNSPECIFIED value + * @property {string} DECLARATIVE_FRIENDLY=DECLARATIVE_FRIENDLY DECLARATIVE_FRIENDLY value + */ + ResourceDescriptor.Style = (function() { + var valuesById = {}, values = Object.create(valuesById); + values[valuesById[0] = "STYLE_UNSPECIFIED"] = "STYLE_UNSPECIFIED"; + values[valuesById[1] = "DECLARATIVE_FRIENDLY"] = "DECLARATIVE_FRIENDLY"; + return values; + })(); - /** - * Gets the default type url for Target - * @function getTypeUrl - * @memberof google.firestore.v1.Target - * @static - * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") - * @returns {string} The default type url - */ - Target.getTypeUrl = function getTypeUrl(typeUrlPrefix) { - if (typeUrlPrefix === undefined) { - typeUrlPrefix = "type.googleapis.com"; - } - return typeUrlPrefix + "/google.firestore.v1.Target"; - }; + return ResourceDescriptor; + })(); - Target.DocumentsTarget = (function() { + api.ResourceReference = (function() { - /** - * Properties of a DocumentsTarget. - * @memberof google.firestore.v1.Target - * @interface IDocumentsTarget - * @property {Array.|null} [documents] DocumentsTarget documents - */ + /** + * Properties of a ResourceReference. + * @memberof google.api + * @interface IResourceReference + * @property {string|null} [type] ResourceReference type + * @property {string|null} [childType] ResourceReference childType + */ - /** - * Constructs a new DocumentsTarget. - * @memberof google.firestore.v1.Target - * @classdesc Represents a DocumentsTarget. - * @implements IDocumentsTarget - * @constructor - * @param {google.firestore.v1.Target.IDocumentsTarget=} [properties] Properties to set - */ - function DocumentsTarget(properties) { - this.documents = []; - if (properties) - for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) - if (properties[keys[i]] != null) - this[keys[i]] = properties[keys[i]]; - } + /** + * Constructs a new ResourceReference. + * @memberof google.api + * @classdesc Represents a ResourceReference. + * @implements IResourceReference + * @constructor + * @param {google.api.IResourceReference=} [properties] Properties to set + */ + function ResourceReference(properties) { + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } - /** - * DocumentsTarget documents. - * @member {Array.} documents - * @memberof google.firestore.v1.Target.DocumentsTarget - * @instance - */ - DocumentsTarget.prototype.documents = $util.emptyArray; + /** + * ResourceReference type. + * @member {string} type + * @memberof google.api.ResourceReference + * @instance + */ + ResourceReference.prototype.type = ""; - /** - * Creates a DocumentsTarget message from a plain object. Also converts values to their respective internal types. - * @function fromObject - * @memberof google.firestore.v1.Target.DocumentsTarget - * @static - * @param {Object.} object Plain object - * @returns {google.firestore.v1.Target.DocumentsTarget} DocumentsTarget - */ - DocumentsTarget.fromObject = function fromObject(object) { - if (object instanceof $root.google.firestore.v1.Target.DocumentsTarget) - return object; - var message = new $root.google.firestore.v1.Target.DocumentsTarget(); - if (object.documents) { - if (!Array.isArray(object.documents)) - throw TypeError(".google.firestore.v1.Target.DocumentsTarget.documents: array expected"); - message.documents = []; - for (var i = 0; i < object.documents.length; ++i) - message.documents[i] = String(object.documents[i]); - } - return message; - }; + /** + * ResourceReference childType. + * @member {string} childType + * @memberof google.api.ResourceReference + * @instance + */ + ResourceReference.prototype.childType = ""; - /** - * Creates a plain object from a DocumentsTarget message. Also converts values to other types if specified. - * @function toObject - * @memberof google.firestore.v1.Target.DocumentsTarget - * @static - * @param {google.firestore.v1.Target.DocumentsTarget} message DocumentsTarget - * @param {$protobuf.IConversionOptions} [options] Conversion options - * @returns {Object.} Plain object - */ - DocumentsTarget.toObject = function toObject(message, options) { - if (!options) - options = {}; - var object = {}; - if (options.arrays || options.defaults) - object.documents = []; - if (message.documents && message.documents.length) { - object.documents = []; - for (var j = 0; j < message.documents.length; ++j) - object.documents[j] = message.documents[j]; - } - return object; - }; + /** + * Creates a ResourceReference message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.api.ResourceReference + * @static + * @param {Object.} object Plain object + * @returns {google.api.ResourceReference} ResourceReference + */ + ResourceReference.fromObject = function fromObject(object) { + if (object instanceof $root.google.api.ResourceReference) + return object; + var message = new $root.google.api.ResourceReference(); + if (object.type != null) + message.type = String(object.type); + if (object.childType != null) + message.childType = String(object.childType); + return message; + }; - /** - * Converts this DocumentsTarget to JSON. - * @function toJSON - * @memberof google.firestore.v1.Target.DocumentsTarget - * @instance - * @returns {Object.} JSON object - */ - DocumentsTarget.prototype.toJSON = function toJSON() { - return this.constructor.toObject(this, $protobuf.util.toJSONOptions); - }; + /** + * Creates a plain object from a ResourceReference message. Also converts values to other types if specified. + * @function toObject + * @memberof google.api.ResourceReference + * @static + * @param {google.api.ResourceReference} message ResourceReference + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + ResourceReference.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.defaults) { + object.type = ""; + object.childType = ""; + } + if (message.type != null && message.hasOwnProperty("type")) + object.type = message.type; + if (message.childType != null && message.hasOwnProperty("childType")) + object.childType = message.childType; + return object; + }; - /** - * Gets the default type url for DocumentsTarget - * @function getTypeUrl - * @memberof google.firestore.v1.Target.DocumentsTarget - * @static - * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") - * @returns {string} The default type url - */ - DocumentsTarget.getTypeUrl = function getTypeUrl(typeUrlPrefix) { - if (typeUrlPrefix === undefined) { - typeUrlPrefix = "type.googleapis.com"; - } - return typeUrlPrefix + "/google.firestore.v1.Target.DocumentsTarget"; - }; + /** + * Converts this ResourceReference to JSON. + * @function toJSON + * @memberof google.api.ResourceReference + * @instance + * @returns {Object.} JSON object + */ + ResourceReference.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; - return DocumentsTarget; - })(); + /** + * Gets the default type url for ResourceReference + * @function getTypeUrl + * @memberof google.api.ResourceReference + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + ResourceReference.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.api.ResourceReference"; + }; - Target.QueryTarget = (function() { + return ResourceReference; + })(); - /** - * Properties of a QueryTarget. - * @memberof google.firestore.v1.Target - * @interface IQueryTarget - * @property {string|null} [parent] QueryTarget parent - * @property {google.firestore.v1.IStructuredQuery|null} [structuredQuery] QueryTarget structuredQuery - */ + return api; + })(); - /** - * Constructs a new QueryTarget. - * @memberof google.firestore.v1.Target - * @classdesc Represents a QueryTarget. - * @implements IQueryTarget - * @constructor - * @param {google.firestore.v1.Target.IQueryTarget=} [properties] Properties to set - */ - function QueryTarget(properties) { - if (properties) - for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) - if (properties[keys[i]] != null) - this[keys[i]] = properties[keys[i]]; - } + google.protobuf = (function() { - /** - * QueryTarget parent. - * @member {string} parent - * @memberof google.firestore.v1.Target.QueryTarget - * @instance - */ - QueryTarget.prototype.parent = ""; + /** + * Namespace protobuf. + * @memberof google + * @namespace + */ + var protobuf = {}; - /** - * QueryTarget structuredQuery. - * @member {google.firestore.v1.IStructuredQuery|null|undefined} structuredQuery - * @memberof google.firestore.v1.Target.QueryTarget - * @instance - */ - QueryTarget.prototype.structuredQuery = null; + protobuf.FileDescriptorSet = (function() { - // OneOf field names bound to virtual getters and setters - var $oneOfFields; + /** + * Properties of a FileDescriptorSet. + * @memberof google.protobuf + * @interface IFileDescriptorSet + * @property {Array.|null} [file] FileDescriptorSet file + */ - /** - * QueryTarget queryType. - * @member {"structuredQuery"|undefined} queryType - * @memberof google.firestore.v1.Target.QueryTarget - * @instance - */ - Object.defineProperty(QueryTarget.prototype, "queryType", { - get: $util.oneOfGetter($oneOfFields = ["structuredQuery"]), - set: $util.oneOfSetter($oneOfFields) - }); + /** + * Constructs a new FileDescriptorSet. + * @memberof google.protobuf + * @classdesc Represents a FileDescriptorSet. + * @implements IFileDescriptorSet + * @constructor + * @param {google.protobuf.IFileDescriptorSet=} [properties] Properties to set + */ + function FileDescriptorSet(properties) { + this.file = []; + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } - /** - * Creates a QueryTarget message from a plain object. Also converts values to their respective internal types. - * @function fromObject - * @memberof google.firestore.v1.Target.QueryTarget - * @static - * @param {Object.} object Plain object - * @returns {google.firestore.v1.Target.QueryTarget} QueryTarget - */ - QueryTarget.fromObject = function fromObject(object) { - if (object instanceof $root.google.firestore.v1.Target.QueryTarget) - return object; - var message = new $root.google.firestore.v1.Target.QueryTarget(); - if (object.parent != null) - message.parent = String(object.parent); - if (object.structuredQuery != null) { - if (typeof object.structuredQuery !== "object") - throw TypeError(".google.firestore.v1.Target.QueryTarget.structuredQuery: object expected"); - message.structuredQuery = $root.google.firestore.v1.StructuredQuery.fromObject(object.structuredQuery); - } - return message; - }; + /** + * FileDescriptorSet file. + * @member {Array.} file + * @memberof google.protobuf.FileDescriptorSet + * @instance + */ + FileDescriptorSet.prototype.file = $util.emptyArray; - /** - * Creates a plain object from a QueryTarget message. Also converts values to other types if specified. - * @function toObject - * @memberof google.firestore.v1.Target.QueryTarget - * @static - * @param {google.firestore.v1.Target.QueryTarget} message QueryTarget - * @param {$protobuf.IConversionOptions} [options] Conversion options - * @returns {Object.} Plain object - */ - QueryTarget.toObject = function toObject(message, options) { - if (!options) - options = {}; - var object = {}; - if (options.defaults) - object.parent = ""; - if (message.parent != null && message.hasOwnProperty("parent")) - object.parent = message.parent; - if (message.structuredQuery != null && message.hasOwnProperty("structuredQuery")) { - object.structuredQuery = $root.google.firestore.v1.StructuredQuery.toObject(message.structuredQuery, options); - if (options.oneofs) - object.queryType = "structuredQuery"; - } - return object; - }; + /** + * Creates a FileDescriptorSet message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.protobuf.FileDescriptorSet + * @static + * @param {Object.} object Plain object + * @returns {google.protobuf.FileDescriptorSet} FileDescriptorSet + */ + FileDescriptorSet.fromObject = function fromObject(object) { + if (object instanceof $root.google.protobuf.FileDescriptorSet) + return object; + var message = new $root.google.protobuf.FileDescriptorSet(); + if (object.file) { + if (!Array.isArray(object.file)) + throw TypeError(".google.protobuf.FileDescriptorSet.file: array expected"); + message.file = []; + for (var i = 0; i < object.file.length; ++i) { + if (typeof object.file[i] !== "object") + throw TypeError(".google.protobuf.FileDescriptorSet.file: object expected"); + message.file[i] = $root.google.protobuf.FileDescriptorProto.fromObject(object.file[i]); + } + } + return message; + }; - /** - * Converts this QueryTarget to JSON. - * @function toJSON - * @memberof google.firestore.v1.Target.QueryTarget - * @instance - * @returns {Object.} JSON object - */ - QueryTarget.prototype.toJSON = function toJSON() { - return this.constructor.toObject(this, $protobuf.util.toJSONOptions); - }; + /** + * Creates a plain object from a FileDescriptorSet message. Also converts values to other types if specified. + * @function toObject + * @memberof google.protobuf.FileDescriptorSet + * @static + * @param {google.protobuf.FileDescriptorSet} message FileDescriptorSet + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + FileDescriptorSet.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.arrays || options.defaults) + object.file = []; + if (message.file && message.file.length) { + object.file = []; + for (var j = 0; j < message.file.length; ++j) + object.file[j] = $root.google.protobuf.FileDescriptorProto.toObject(message.file[j], options); + } + return object; + }; - /** - * Gets the default type url for QueryTarget - * @function getTypeUrl - * @memberof google.firestore.v1.Target.QueryTarget - * @static - * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") - * @returns {string} The default type url - */ - QueryTarget.getTypeUrl = function getTypeUrl(typeUrlPrefix) { - if (typeUrlPrefix === undefined) { - typeUrlPrefix = "type.googleapis.com"; - } - return typeUrlPrefix + "/google.firestore.v1.Target.QueryTarget"; - }; + /** + * Converts this FileDescriptorSet to JSON. + * @function toJSON + * @memberof google.protobuf.FileDescriptorSet + * @instance + * @returns {Object.} JSON object + */ + FileDescriptorSet.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; - return QueryTarget; - })(); + /** + * Gets the default type url for FileDescriptorSet + * @function getTypeUrl + * @memberof google.protobuf.FileDescriptorSet + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + FileDescriptorSet.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.protobuf.FileDescriptorSet"; + }; - return Target; - })(); + return FileDescriptorSet; + })(); + + /** + * Edition enum. + * @name google.protobuf.Edition + * @enum {string} + * @property {string} EDITION_UNKNOWN=EDITION_UNKNOWN EDITION_UNKNOWN value + * @property {string} EDITION_PROTO2=EDITION_PROTO2 EDITION_PROTO2 value + * @property {string} EDITION_PROTO3=EDITION_PROTO3 EDITION_PROTO3 value + * @property {string} EDITION_2023=EDITION_2023 EDITION_2023 value + * @property {string} EDITION_2024=EDITION_2024 EDITION_2024 value + * @property {string} EDITION_1_TEST_ONLY=EDITION_1_TEST_ONLY EDITION_1_TEST_ONLY value + * @property {string} EDITION_2_TEST_ONLY=EDITION_2_TEST_ONLY EDITION_2_TEST_ONLY value + * @property {string} EDITION_99997_TEST_ONLY=EDITION_99997_TEST_ONLY EDITION_99997_TEST_ONLY value + * @property {string} EDITION_99998_TEST_ONLY=EDITION_99998_TEST_ONLY EDITION_99998_TEST_ONLY value + * @property {string} EDITION_99999_TEST_ONLY=EDITION_99999_TEST_ONLY EDITION_99999_TEST_ONLY value + * @property {string} EDITION_MAX=EDITION_MAX EDITION_MAX value + */ + protobuf.Edition = (function() { + var valuesById = {}, values = Object.create(valuesById); + values[valuesById[0] = "EDITION_UNKNOWN"] = "EDITION_UNKNOWN"; + values[valuesById[998] = "EDITION_PROTO2"] = "EDITION_PROTO2"; + values[valuesById[999] = "EDITION_PROTO3"] = "EDITION_PROTO3"; + values[valuesById[1000] = "EDITION_2023"] = "EDITION_2023"; + values[valuesById[1001] = "EDITION_2024"] = "EDITION_2024"; + values[valuesById[1] = "EDITION_1_TEST_ONLY"] = "EDITION_1_TEST_ONLY"; + values[valuesById[2] = "EDITION_2_TEST_ONLY"] = "EDITION_2_TEST_ONLY"; + values[valuesById[99997] = "EDITION_99997_TEST_ONLY"] = "EDITION_99997_TEST_ONLY"; + values[valuesById[99998] = "EDITION_99998_TEST_ONLY"] = "EDITION_99998_TEST_ONLY"; + values[valuesById[99999] = "EDITION_99999_TEST_ONLY"] = "EDITION_99999_TEST_ONLY"; + values[valuesById[2147483647] = "EDITION_MAX"] = "EDITION_MAX"; + return values; + })(); + + protobuf.FileDescriptorProto = (function() { - v1.TargetChange = (function() { + /** + * Properties of a FileDescriptorProto. + * @memberof google.protobuf + * @interface IFileDescriptorProto + * @property {string|null} [name] FileDescriptorProto name + * @property {string|null} ["package"] FileDescriptorProto package + * @property {Array.|null} [dependency] FileDescriptorProto dependency + * @property {Array.|null} [publicDependency] FileDescriptorProto publicDependency + * @property {Array.|null} [weakDependency] FileDescriptorProto weakDependency + * @property {Array.|null} [messageType] FileDescriptorProto messageType + * @property {Array.|null} [enumType] FileDescriptorProto enumType + * @property {Array.|null} [service] FileDescriptorProto service + * @property {Array.|null} [extension] FileDescriptorProto extension + * @property {google.protobuf.IFileOptions|null} [options] FileDescriptorProto options + * @property {google.protobuf.ISourceCodeInfo|null} [sourceCodeInfo] FileDescriptorProto sourceCodeInfo + * @property {string|null} [syntax] FileDescriptorProto syntax + * @property {google.protobuf.Edition|null} [edition] FileDescriptorProto edition + */ - /** - * Properties of a TargetChange. - * @memberof google.firestore.v1 - * @interface ITargetChange - * @property {google.firestore.v1.TargetChange.TargetChangeType|null} [targetChangeType] TargetChange targetChangeType - * @property {Array.|null} [targetIds] TargetChange targetIds - * @property {google.rpc.IStatus|null} [cause] TargetChange cause - * @property {Uint8Array|null} [resumeToken] TargetChange resumeToken - * @property {google.protobuf.ITimestamp|null} [readTime] TargetChange readTime - */ + /** + * Constructs a new FileDescriptorProto. + * @memberof google.protobuf + * @classdesc Represents a FileDescriptorProto. + * @implements IFileDescriptorProto + * @constructor + * @param {google.protobuf.IFileDescriptorProto=} [properties] Properties to set + */ + function FileDescriptorProto(properties) { + this.dependency = []; + this.publicDependency = []; + this.weakDependency = []; + this.messageType = []; + this.enumType = []; + this.service = []; + this.extension = []; + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } - /** - * Constructs a new TargetChange. - * @memberof google.firestore.v1 - * @classdesc Represents a TargetChange. - * @implements ITargetChange - * @constructor - * @param {google.firestore.v1.ITargetChange=} [properties] Properties to set - */ - function TargetChange(properties) { - this.targetIds = []; - if (properties) - for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) - if (properties[keys[i]] != null) - this[keys[i]] = properties[keys[i]]; - } + /** + * FileDescriptorProto name. + * @member {string} name + * @memberof google.protobuf.FileDescriptorProto + * @instance + */ + FileDescriptorProto.prototype.name = ""; - /** - * TargetChange targetChangeType. - * @member {google.firestore.v1.TargetChange.TargetChangeType} targetChangeType - * @memberof google.firestore.v1.TargetChange - * @instance - */ - TargetChange.prototype.targetChangeType = 0; + /** + * FileDescriptorProto package. + * @member {string} package + * @memberof google.protobuf.FileDescriptorProto + * @instance + */ + FileDescriptorProto.prototype["package"] = ""; - /** - * TargetChange targetIds. - * @member {Array.} targetIds - * @memberof google.firestore.v1.TargetChange - * @instance - */ - TargetChange.prototype.targetIds = $util.emptyArray; + /** + * FileDescriptorProto dependency. + * @member {Array.} dependency + * @memberof google.protobuf.FileDescriptorProto + * @instance + */ + FileDescriptorProto.prototype.dependency = $util.emptyArray; - /** - * TargetChange cause. - * @member {google.rpc.IStatus|null|undefined} cause - * @memberof google.firestore.v1.TargetChange - * @instance - */ - TargetChange.prototype.cause = null; + /** + * FileDescriptorProto publicDependency. + * @member {Array.} publicDependency + * @memberof google.protobuf.FileDescriptorProto + * @instance + */ + FileDescriptorProto.prototype.publicDependency = $util.emptyArray; - /** - * TargetChange resumeToken. - * @member {Uint8Array} resumeToken - * @memberof google.firestore.v1.TargetChange - * @instance - */ - TargetChange.prototype.resumeToken = $util.newBuffer([]); + /** + * FileDescriptorProto weakDependency. + * @member {Array.} weakDependency + * @memberof google.protobuf.FileDescriptorProto + * @instance + */ + FileDescriptorProto.prototype.weakDependency = $util.emptyArray; - /** - * TargetChange readTime. - * @member {google.protobuf.ITimestamp|null|undefined} readTime - * @memberof google.firestore.v1.TargetChange - * @instance - */ - TargetChange.prototype.readTime = null; + /** + * FileDescriptorProto messageType. + * @member {Array.} messageType + * @memberof google.protobuf.FileDescriptorProto + * @instance + */ + FileDescriptorProto.prototype.messageType = $util.emptyArray; - /** - * Creates a TargetChange message from a plain object. Also converts values to their respective internal types. - * @function fromObject - * @memberof google.firestore.v1.TargetChange - * @static - * @param {Object.} object Plain object - * @returns {google.firestore.v1.TargetChange} TargetChange - */ - TargetChange.fromObject = function fromObject(object) { - if (object instanceof $root.google.firestore.v1.TargetChange) - return object; - var message = new $root.google.firestore.v1.TargetChange(); - switch (object.targetChangeType) { - default: - if (typeof object.targetChangeType === "number") { - message.targetChangeType = object.targetChangeType; - break; - } - break; - case "NO_CHANGE": - case 0: - message.targetChangeType = 0; - break; - case "ADD": - case 1: - message.targetChangeType = 1; - break; - case "REMOVE": - case 2: - message.targetChangeType = 2; - break; - case "CURRENT": - case 3: - message.targetChangeType = 3; - break; - case "RESET": - case 4: - message.targetChangeType = 4; - break; - } - if (object.targetIds) { - if (!Array.isArray(object.targetIds)) - throw TypeError(".google.firestore.v1.TargetChange.targetIds: array expected"); - message.targetIds = []; - for (var i = 0; i < object.targetIds.length; ++i) - message.targetIds[i] = object.targetIds[i] | 0; - } - if (object.cause != null) { - if (typeof object.cause !== "object") - throw TypeError(".google.firestore.v1.TargetChange.cause: object expected"); - message.cause = $root.google.rpc.Status.fromObject(object.cause); - } - if (object.resumeToken != null) - if (typeof object.resumeToken === "string") - $util.base64.decode(object.resumeToken, message.resumeToken = $util.newBuffer($util.base64.length(object.resumeToken)), 0); - else if (object.resumeToken.length >= 0) - message.resumeToken = object.resumeToken; - if (object.readTime != null) { - if (typeof object.readTime !== "object") - throw TypeError(".google.firestore.v1.TargetChange.readTime: object expected"); - message.readTime = $root.google.protobuf.Timestamp.fromObject(object.readTime); - } - return message; - }; + /** + * FileDescriptorProto enumType. + * @member {Array.} enumType + * @memberof google.protobuf.FileDescriptorProto + * @instance + */ + FileDescriptorProto.prototype.enumType = $util.emptyArray; - /** - * Creates a plain object from a TargetChange message. Also converts values to other types if specified. - * @function toObject - * @memberof google.firestore.v1.TargetChange - * @static - * @param {google.firestore.v1.TargetChange} message TargetChange - * @param {$protobuf.IConversionOptions} [options] Conversion options - * @returns {Object.} Plain object - */ - TargetChange.toObject = function toObject(message, options) { - if (!options) - options = {}; - var object = {}; - if (options.arrays || options.defaults) - object.targetIds = []; - if (options.defaults) { - object.targetChangeType = options.enums === String ? "NO_CHANGE" : 0; - object.cause = null; - if (options.bytes === String) - object.resumeToken = ""; - else { - object.resumeToken = []; - if (options.bytes !== Array) - object.resumeToken = $util.newBuffer(object.resumeToken); - } - object.readTime = null; - } - if (message.targetChangeType != null && message.hasOwnProperty("targetChangeType")) - object.targetChangeType = options.enums === String ? $root.google.firestore.v1.TargetChange.TargetChangeType[message.targetChangeType] === undefined ? message.targetChangeType : $root.google.firestore.v1.TargetChange.TargetChangeType[message.targetChangeType] : message.targetChangeType; - if (message.targetIds && message.targetIds.length) { - object.targetIds = []; - for (var j = 0; j < message.targetIds.length; ++j) - object.targetIds[j] = message.targetIds[j]; - } - if (message.cause != null && message.hasOwnProperty("cause")) - object.cause = $root.google.rpc.Status.toObject(message.cause, options); - if (message.resumeToken != null && message.hasOwnProperty("resumeToken")) - object.resumeToken = options.bytes === String ? $util.base64.encode(message.resumeToken, 0, message.resumeToken.length) : options.bytes === Array ? Array.prototype.slice.call(message.resumeToken) : message.resumeToken; - if (message.readTime != null && message.hasOwnProperty("readTime")) - object.readTime = $root.google.protobuf.Timestamp.toObject(message.readTime, options); - return object; - }; + /** + * FileDescriptorProto service. + * @member {Array.} service + * @memberof google.protobuf.FileDescriptorProto + * @instance + */ + FileDescriptorProto.prototype.service = $util.emptyArray; - /** - * Converts this TargetChange to JSON. - * @function toJSON - * @memberof google.firestore.v1.TargetChange - * @instance - * @returns {Object.} JSON object - */ - TargetChange.prototype.toJSON = function toJSON() { - return this.constructor.toObject(this, $protobuf.util.toJSONOptions); - }; + /** + * FileDescriptorProto extension. + * @member {Array.} extension + * @memberof google.protobuf.FileDescriptorProto + * @instance + */ + FileDescriptorProto.prototype.extension = $util.emptyArray; - /** - * Gets the default type url for TargetChange - * @function getTypeUrl - * @memberof google.firestore.v1.TargetChange - * @static - * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") - * @returns {string} The default type url - */ - TargetChange.getTypeUrl = function getTypeUrl(typeUrlPrefix) { - if (typeUrlPrefix === undefined) { - typeUrlPrefix = "type.googleapis.com"; - } - return typeUrlPrefix + "/google.firestore.v1.TargetChange"; - }; + /** + * FileDescriptorProto options. + * @member {google.protobuf.IFileOptions|null|undefined} options + * @memberof google.protobuf.FileDescriptorProto + * @instance + */ + FileDescriptorProto.prototype.options = null; - /** - * TargetChangeType enum. - * @name google.firestore.v1.TargetChange.TargetChangeType - * @enum {string} - * @property {string} NO_CHANGE=NO_CHANGE NO_CHANGE value - * @property {string} ADD=ADD ADD value - * @property {string} REMOVE=REMOVE REMOVE value - * @property {string} CURRENT=CURRENT CURRENT value - * @property {string} RESET=RESET RESET value - */ - TargetChange.TargetChangeType = (function() { - var valuesById = {}, values = Object.create(valuesById); - values[valuesById[0] = "NO_CHANGE"] = "NO_CHANGE"; - values[valuesById[1] = "ADD"] = "ADD"; - values[valuesById[2] = "REMOVE"] = "REMOVE"; - values[valuesById[3] = "CURRENT"] = "CURRENT"; - values[valuesById[4] = "RESET"] = "RESET"; - return values; - })(); + /** + * FileDescriptorProto sourceCodeInfo. + * @member {google.protobuf.ISourceCodeInfo|null|undefined} sourceCodeInfo + * @memberof google.protobuf.FileDescriptorProto + * @instance + */ + FileDescriptorProto.prototype.sourceCodeInfo = null; - return TargetChange; - })(); + /** + * FileDescriptorProto syntax. + * @member {string} syntax + * @memberof google.protobuf.FileDescriptorProto + * @instance + */ + FileDescriptorProto.prototype.syntax = ""; - v1.ListCollectionIdsRequest = (function() { + /** + * FileDescriptorProto edition. + * @member {google.protobuf.Edition} edition + * @memberof google.protobuf.FileDescriptorProto + * @instance + */ + FileDescriptorProto.prototype.edition = 0; - /** - * Properties of a ListCollectionIdsRequest. - * @memberof google.firestore.v1 - * @interface IListCollectionIdsRequest - * @property {string|null} [parent] ListCollectionIdsRequest parent - * @property {number|null} [pageSize] ListCollectionIdsRequest pageSize - * @property {string|null} [pageToken] ListCollectionIdsRequest pageToken - * @property {google.protobuf.ITimestamp|null} [readTime] ListCollectionIdsRequest readTime - */ + /** + * Creates a FileDescriptorProto message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.protobuf.FileDescriptorProto + * @static + * @param {Object.} object Plain object + * @returns {google.protobuf.FileDescriptorProto} FileDescriptorProto + */ + FileDescriptorProto.fromObject = function fromObject(object) { + if (object instanceof $root.google.protobuf.FileDescriptorProto) + return object; + var message = new $root.google.protobuf.FileDescriptorProto(); + if (object.name != null) + message.name = String(object.name); + if (object["package"] != null) + message["package"] = String(object["package"]); + if (object.dependency) { + if (!Array.isArray(object.dependency)) + throw TypeError(".google.protobuf.FileDescriptorProto.dependency: array expected"); + message.dependency = []; + for (var i = 0; i < object.dependency.length; ++i) + message.dependency[i] = String(object.dependency[i]); + } + if (object.publicDependency) { + if (!Array.isArray(object.publicDependency)) + throw TypeError(".google.protobuf.FileDescriptorProto.publicDependency: array expected"); + message.publicDependency = []; + for (var i = 0; i < object.publicDependency.length; ++i) + message.publicDependency[i] = object.publicDependency[i] | 0; + } + if (object.weakDependency) { + if (!Array.isArray(object.weakDependency)) + throw TypeError(".google.protobuf.FileDescriptorProto.weakDependency: array expected"); + message.weakDependency = []; + for (var i = 0; i < object.weakDependency.length; ++i) + message.weakDependency[i] = object.weakDependency[i] | 0; + } + if (object.messageType) { + if (!Array.isArray(object.messageType)) + throw TypeError(".google.protobuf.FileDescriptorProto.messageType: array expected"); + message.messageType = []; + for (var i = 0; i < object.messageType.length; ++i) { + if (typeof object.messageType[i] !== "object") + throw TypeError(".google.protobuf.FileDescriptorProto.messageType: object expected"); + message.messageType[i] = $root.google.protobuf.DescriptorProto.fromObject(object.messageType[i]); + } + } + if (object.enumType) { + if (!Array.isArray(object.enumType)) + throw TypeError(".google.protobuf.FileDescriptorProto.enumType: array expected"); + message.enumType = []; + for (var i = 0; i < object.enumType.length; ++i) { + if (typeof object.enumType[i] !== "object") + throw TypeError(".google.protobuf.FileDescriptorProto.enumType: object expected"); + message.enumType[i] = $root.google.protobuf.EnumDescriptorProto.fromObject(object.enumType[i]); + } + } + if (object.service) { + if (!Array.isArray(object.service)) + throw TypeError(".google.protobuf.FileDescriptorProto.service: array expected"); + message.service = []; + for (var i = 0; i < object.service.length; ++i) { + if (typeof object.service[i] !== "object") + throw TypeError(".google.protobuf.FileDescriptorProto.service: object expected"); + message.service[i] = $root.google.protobuf.ServiceDescriptorProto.fromObject(object.service[i]); + } + } + if (object.extension) { + if (!Array.isArray(object.extension)) + throw TypeError(".google.protobuf.FileDescriptorProto.extension: array expected"); + message.extension = []; + for (var i = 0; i < object.extension.length; ++i) { + if (typeof object.extension[i] !== "object") + throw TypeError(".google.protobuf.FileDescriptorProto.extension: object expected"); + message.extension[i] = $root.google.protobuf.FieldDescriptorProto.fromObject(object.extension[i]); + } + } + if (object.options != null) { + if (typeof object.options !== "object") + throw TypeError(".google.protobuf.FileDescriptorProto.options: object expected"); + message.options = $root.google.protobuf.FileOptions.fromObject(object.options); + } + if (object.sourceCodeInfo != null) { + if (typeof object.sourceCodeInfo !== "object") + throw TypeError(".google.protobuf.FileDescriptorProto.sourceCodeInfo: object expected"); + message.sourceCodeInfo = $root.google.protobuf.SourceCodeInfo.fromObject(object.sourceCodeInfo); + } + if (object.syntax != null) + message.syntax = String(object.syntax); + switch (object.edition) { + default: + if (typeof object.edition === "number") { + message.edition = object.edition; + break; + } + break; + case "EDITION_UNKNOWN": + case 0: + message.edition = 0; + break; + case "EDITION_PROTO2": + case 998: + message.edition = 998; + break; + case "EDITION_PROTO3": + case 999: + message.edition = 999; + break; + case "EDITION_2023": + case 1000: + message.edition = 1000; + break; + case "EDITION_2024": + case 1001: + message.edition = 1001; + break; + case "EDITION_1_TEST_ONLY": + case 1: + message.edition = 1; + break; + case "EDITION_2_TEST_ONLY": + case 2: + message.edition = 2; + break; + case "EDITION_99997_TEST_ONLY": + case 99997: + message.edition = 99997; + break; + case "EDITION_99998_TEST_ONLY": + case 99998: + message.edition = 99998; + break; + case "EDITION_99999_TEST_ONLY": + case 99999: + message.edition = 99999; + break; + case "EDITION_MAX": + case 2147483647: + message.edition = 2147483647; + break; + } + return message; + }; - /** - * Constructs a new ListCollectionIdsRequest. - * @memberof google.firestore.v1 - * @classdesc Represents a ListCollectionIdsRequest. - * @implements IListCollectionIdsRequest - * @constructor - * @param {google.firestore.v1.IListCollectionIdsRequest=} [properties] Properties to set - */ - function ListCollectionIdsRequest(properties) { - if (properties) - for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) - if (properties[keys[i]] != null) - this[keys[i]] = properties[keys[i]]; + /** + * Creates a plain object from a FileDescriptorProto message. Also converts values to other types if specified. + * @function toObject + * @memberof google.protobuf.FileDescriptorProto + * @static + * @param {google.protobuf.FileDescriptorProto} message FileDescriptorProto + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + FileDescriptorProto.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.arrays || options.defaults) { + object.dependency = []; + object.messageType = []; + object.enumType = []; + object.service = []; + object.extension = []; + object.publicDependency = []; + object.weakDependency = []; } + if (options.defaults) { + object.name = ""; + object["package"] = ""; + object.options = null; + object.sourceCodeInfo = null; + object.syntax = ""; + object.edition = options.enums === String ? "EDITION_UNKNOWN" : 0; + } + if (message.name != null && message.hasOwnProperty("name")) + object.name = message.name; + if (message["package"] != null && message.hasOwnProperty("package")) + object["package"] = message["package"]; + if (message.dependency && message.dependency.length) { + object.dependency = []; + for (var j = 0; j < message.dependency.length; ++j) + object.dependency[j] = message.dependency[j]; + } + if (message.messageType && message.messageType.length) { + object.messageType = []; + for (var j = 0; j < message.messageType.length; ++j) + object.messageType[j] = $root.google.protobuf.DescriptorProto.toObject(message.messageType[j], options); + } + if (message.enumType && message.enumType.length) { + object.enumType = []; + for (var j = 0; j < message.enumType.length; ++j) + object.enumType[j] = $root.google.protobuf.EnumDescriptorProto.toObject(message.enumType[j], options); + } + if (message.service && message.service.length) { + object.service = []; + for (var j = 0; j < message.service.length; ++j) + object.service[j] = $root.google.protobuf.ServiceDescriptorProto.toObject(message.service[j], options); + } + if (message.extension && message.extension.length) { + object.extension = []; + for (var j = 0; j < message.extension.length; ++j) + object.extension[j] = $root.google.protobuf.FieldDescriptorProto.toObject(message.extension[j], options); + } + if (message.options != null && message.hasOwnProperty("options")) + object.options = $root.google.protobuf.FileOptions.toObject(message.options, options); + if (message.sourceCodeInfo != null && message.hasOwnProperty("sourceCodeInfo")) + object.sourceCodeInfo = $root.google.protobuf.SourceCodeInfo.toObject(message.sourceCodeInfo, options); + if (message.publicDependency && message.publicDependency.length) { + object.publicDependency = []; + for (var j = 0; j < message.publicDependency.length; ++j) + object.publicDependency[j] = message.publicDependency[j]; + } + if (message.weakDependency && message.weakDependency.length) { + object.weakDependency = []; + for (var j = 0; j < message.weakDependency.length; ++j) + object.weakDependency[j] = message.weakDependency[j]; + } + if (message.syntax != null && message.hasOwnProperty("syntax")) + object.syntax = message.syntax; + if (message.edition != null && message.hasOwnProperty("edition")) + object.edition = options.enums === String ? $root.google.protobuf.Edition[message.edition] === undefined ? message.edition : $root.google.protobuf.Edition[message.edition] : message.edition; + return object; + }; - /** - * ListCollectionIdsRequest parent. - * @member {string} parent - * @memberof google.firestore.v1.ListCollectionIdsRequest - * @instance - */ - ListCollectionIdsRequest.prototype.parent = ""; - - /** - * ListCollectionIdsRequest pageSize. - * @member {number} pageSize - * @memberof google.firestore.v1.ListCollectionIdsRequest - * @instance - */ - ListCollectionIdsRequest.prototype.pageSize = 0; + /** + * Converts this FileDescriptorProto to JSON. + * @function toJSON + * @memberof google.protobuf.FileDescriptorProto + * @instance + * @returns {Object.} JSON object + */ + FileDescriptorProto.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; - /** - * ListCollectionIdsRequest pageToken. - * @member {string} pageToken - * @memberof google.firestore.v1.ListCollectionIdsRequest - * @instance - */ - ListCollectionIdsRequest.prototype.pageToken = ""; + /** + * Gets the default type url for FileDescriptorProto + * @function getTypeUrl + * @memberof google.protobuf.FileDescriptorProto + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + FileDescriptorProto.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.protobuf.FileDescriptorProto"; + }; - /** - * ListCollectionIdsRequest readTime. - * @member {google.protobuf.ITimestamp|null|undefined} readTime - * @memberof google.firestore.v1.ListCollectionIdsRequest - * @instance - */ - ListCollectionIdsRequest.prototype.readTime = null; + return FileDescriptorProto; + })(); - // OneOf field names bound to virtual getters and setters - var $oneOfFields; + protobuf.DescriptorProto = (function() { - /** - * ListCollectionIdsRequest consistencySelector. - * @member {"readTime"|undefined} consistencySelector - * @memberof google.firestore.v1.ListCollectionIdsRequest - * @instance - */ - Object.defineProperty(ListCollectionIdsRequest.prototype, "consistencySelector", { - get: $util.oneOfGetter($oneOfFields = ["readTime"]), - set: $util.oneOfSetter($oneOfFields) - }); + /** + * Properties of a DescriptorProto. + * @memberof google.protobuf + * @interface IDescriptorProto + * @property {string|null} [name] DescriptorProto name + * @property {Array.|null} [field] DescriptorProto field + * @property {Array.|null} [extension] DescriptorProto extension + * @property {Array.|null} [nestedType] DescriptorProto nestedType + * @property {Array.|null} [enumType] DescriptorProto enumType + * @property {Array.|null} [extensionRange] DescriptorProto extensionRange + * @property {Array.|null} [oneofDecl] DescriptorProto oneofDecl + * @property {google.protobuf.IMessageOptions|null} [options] DescriptorProto options + * @property {Array.|null} [reservedRange] DescriptorProto reservedRange + * @property {Array.|null} [reservedName] DescriptorProto reservedName + */ - /** - * Creates a ListCollectionIdsRequest message from a plain object. Also converts values to their respective internal types. - * @function fromObject - * @memberof google.firestore.v1.ListCollectionIdsRequest - * @static - * @param {Object.} object Plain object - * @returns {google.firestore.v1.ListCollectionIdsRequest} ListCollectionIdsRequest - */ - ListCollectionIdsRequest.fromObject = function fromObject(object) { - if (object instanceof $root.google.firestore.v1.ListCollectionIdsRequest) - return object; - var message = new $root.google.firestore.v1.ListCollectionIdsRequest(); - if (object.parent != null) - message.parent = String(object.parent); - if (object.pageSize != null) - message.pageSize = object.pageSize | 0; - if (object.pageToken != null) - message.pageToken = String(object.pageToken); - if (object.readTime != null) { - if (typeof object.readTime !== "object") - throw TypeError(".google.firestore.v1.ListCollectionIdsRequest.readTime: object expected"); - message.readTime = $root.google.protobuf.Timestamp.fromObject(object.readTime); - } - return message; - }; + /** + * Constructs a new DescriptorProto. + * @memberof google.protobuf + * @classdesc Represents a DescriptorProto. + * @implements IDescriptorProto + * @constructor + * @param {google.protobuf.IDescriptorProto=} [properties] Properties to set + */ + function DescriptorProto(properties) { + this.field = []; + this.extension = []; + this.nestedType = []; + this.enumType = []; + this.extensionRange = []; + this.oneofDecl = []; + this.reservedRange = []; + this.reservedName = []; + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } - /** - * Creates a plain object from a ListCollectionIdsRequest message. Also converts values to other types if specified. - * @function toObject - * @memberof google.firestore.v1.ListCollectionIdsRequest - * @static - * @param {google.firestore.v1.ListCollectionIdsRequest} message ListCollectionIdsRequest - * @param {$protobuf.IConversionOptions} [options] Conversion options - * @returns {Object.} Plain object - */ - ListCollectionIdsRequest.toObject = function toObject(message, options) { - if (!options) - options = {}; - var object = {}; - if (options.defaults) { - object.parent = ""; - object.pageSize = 0; - object.pageToken = ""; - } - if (message.parent != null && message.hasOwnProperty("parent")) - object.parent = message.parent; - if (message.pageSize != null && message.hasOwnProperty("pageSize")) - object.pageSize = message.pageSize; - if (message.pageToken != null && message.hasOwnProperty("pageToken")) - object.pageToken = message.pageToken; - if (message.readTime != null && message.hasOwnProperty("readTime")) { - object.readTime = $root.google.protobuf.Timestamp.toObject(message.readTime, options); - if (options.oneofs) - object.consistencySelector = "readTime"; - } - return object; - }; + /** + * DescriptorProto name. + * @member {string} name + * @memberof google.protobuf.DescriptorProto + * @instance + */ + DescriptorProto.prototype.name = ""; - /** - * Converts this ListCollectionIdsRequest to JSON. - * @function toJSON - * @memberof google.firestore.v1.ListCollectionIdsRequest - * @instance - * @returns {Object.} JSON object - */ - ListCollectionIdsRequest.prototype.toJSON = function toJSON() { - return this.constructor.toObject(this, $protobuf.util.toJSONOptions); - }; + /** + * DescriptorProto field. + * @member {Array.} field + * @memberof google.protobuf.DescriptorProto + * @instance + */ + DescriptorProto.prototype.field = $util.emptyArray; - /** - * Gets the default type url for ListCollectionIdsRequest - * @function getTypeUrl - * @memberof google.firestore.v1.ListCollectionIdsRequest - * @static - * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") - * @returns {string} The default type url - */ - ListCollectionIdsRequest.getTypeUrl = function getTypeUrl(typeUrlPrefix) { - if (typeUrlPrefix === undefined) { - typeUrlPrefix = "type.googleapis.com"; - } - return typeUrlPrefix + "/google.firestore.v1.ListCollectionIdsRequest"; - }; + /** + * DescriptorProto extension. + * @member {Array.} extension + * @memberof google.protobuf.DescriptorProto + * @instance + */ + DescriptorProto.prototype.extension = $util.emptyArray; - return ListCollectionIdsRequest; - })(); + /** + * DescriptorProto nestedType. + * @member {Array.} nestedType + * @memberof google.protobuf.DescriptorProto + * @instance + */ + DescriptorProto.prototype.nestedType = $util.emptyArray; - v1.ListCollectionIdsResponse = (function() { + /** + * DescriptorProto enumType. + * @member {Array.} enumType + * @memberof google.protobuf.DescriptorProto + * @instance + */ + DescriptorProto.prototype.enumType = $util.emptyArray; - /** - * Properties of a ListCollectionIdsResponse. - * @memberof google.firestore.v1 - * @interface IListCollectionIdsResponse - * @property {Array.|null} [collectionIds] ListCollectionIdsResponse collectionIds - * @property {string|null} [nextPageToken] ListCollectionIdsResponse nextPageToken - */ + /** + * DescriptorProto extensionRange. + * @member {Array.} extensionRange + * @memberof google.protobuf.DescriptorProto + * @instance + */ + DescriptorProto.prototype.extensionRange = $util.emptyArray; - /** - * Constructs a new ListCollectionIdsResponse. - * @memberof google.firestore.v1 - * @classdesc Represents a ListCollectionIdsResponse. - * @implements IListCollectionIdsResponse - * @constructor - * @param {google.firestore.v1.IListCollectionIdsResponse=} [properties] Properties to set - */ - function ListCollectionIdsResponse(properties) { - this.collectionIds = []; - if (properties) - for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) - if (properties[keys[i]] != null) - this[keys[i]] = properties[keys[i]]; - } + /** + * DescriptorProto oneofDecl. + * @member {Array.} oneofDecl + * @memberof google.protobuf.DescriptorProto + * @instance + */ + DescriptorProto.prototype.oneofDecl = $util.emptyArray; - /** - * ListCollectionIdsResponse collectionIds. - * @member {Array.} collectionIds - * @memberof google.firestore.v1.ListCollectionIdsResponse - * @instance - */ - ListCollectionIdsResponse.prototype.collectionIds = $util.emptyArray; + /** + * DescriptorProto options. + * @member {google.protobuf.IMessageOptions|null|undefined} options + * @memberof google.protobuf.DescriptorProto + * @instance + */ + DescriptorProto.prototype.options = null; - /** - * ListCollectionIdsResponse nextPageToken. - * @member {string} nextPageToken - * @memberof google.firestore.v1.ListCollectionIdsResponse - * @instance - */ - ListCollectionIdsResponse.prototype.nextPageToken = ""; + /** + * DescriptorProto reservedRange. + * @member {Array.} reservedRange + * @memberof google.protobuf.DescriptorProto + * @instance + */ + DescriptorProto.prototype.reservedRange = $util.emptyArray; - /** - * Creates a ListCollectionIdsResponse message from a plain object. Also converts values to their respective internal types. - * @function fromObject - * @memberof google.firestore.v1.ListCollectionIdsResponse - * @static - * @param {Object.} object Plain object - * @returns {google.firestore.v1.ListCollectionIdsResponse} ListCollectionIdsResponse - */ - ListCollectionIdsResponse.fromObject = function fromObject(object) { - if (object instanceof $root.google.firestore.v1.ListCollectionIdsResponse) - return object; - var message = new $root.google.firestore.v1.ListCollectionIdsResponse(); - if (object.collectionIds) { - if (!Array.isArray(object.collectionIds)) - throw TypeError(".google.firestore.v1.ListCollectionIdsResponse.collectionIds: array expected"); - message.collectionIds = []; - for (var i = 0; i < object.collectionIds.length; ++i) - message.collectionIds[i] = String(object.collectionIds[i]); - } - if (object.nextPageToken != null) - message.nextPageToken = String(object.nextPageToken); - return message; - }; + /** + * DescriptorProto reservedName. + * @member {Array.} reservedName + * @memberof google.protobuf.DescriptorProto + * @instance + */ + DescriptorProto.prototype.reservedName = $util.emptyArray; - /** - * Creates a plain object from a ListCollectionIdsResponse message. Also converts values to other types if specified. - * @function toObject - * @memberof google.firestore.v1.ListCollectionIdsResponse - * @static - * @param {google.firestore.v1.ListCollectionIdsResponse} message ListCollectionIdsResponse - * @param {$protobuf.IConversionOptions} [options] Conversion options - * @returns {Object.} Plain object - */ - ListCollectionIdsResponse.toObject = function toObject(message, options) { - if (!options) - options = {}; - var object = {}; - if (options.arrays || options.defaults) - object.collectionIds = []; - if (options.defaults) - object.nextPageToken = ""; - if (message.collectionIds && message.collectionIds.length) { - object.collectionIds = []; - for (var j = 0; j < message.collectionIds.length; ++j) - object.collectionIds[j] = message.collectionIds[j]; - } - if (message.nextPageToken != null && message.hasOwnProperty("nextPageToken")) - object.nextPageToken = message.nextPageToken; + /** + * Creates a DescriptorProto message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.protobuf.DescriptorProto + * @static + * @param {Object.} object Plain object + * @returns {google.protobuf.DescriptorProto} DescriptorProto + */ + DescriptorProto.fromObject = function fromObject(object) { + if (object instanceof $root.google.protobuf.DescriptorProto) return object; - }; + var message = new $root.google.protobuf.DescriptorProto(); + if (object.name != null) + message.name = String(object.name); + if (object.field) { + if (!Array.isArray(object.field)) + throw TypeError(".google.protobuf.DescriptorProto.field: array expected"); + message.field = []; + for (var i = 0; i < object.field.length; ++i) { + if (typeof object.field[i] !== "object") + throw TypeError(".google.protobuf.DescriptorProto.field: object expected"); + message.field[i] = $root.google.protobuf.FieldDescriptorProto.fromObject(object.field[i]); + } + } + if (object.extension) { + if (!Array.isArray(object.extension)) + throw TypeError(".google.protobuf.DescriptorProto.extension: array expected"); + message.extension = []; + for (var i = 0; i < object.extension.length; ++i) { + if (typeof object.extension[i] !== "object") + throw TypeError(".google.protobuf.DescriptorProto.extension: object expected"); + message.extension[i] = $root.google.protobuf.FieldDescriptorProto.fromObject(object.extension[i]); + } + } + if (object.nestedType) { + if (!Array.isArray(object.nestedType)) + throw TypeError(".google.protobuf.DescriptorProto.nestedType: array expected"); + message.nestedType = []; + for (var i = 0; i < object.nestedType.length; ++i) { + if (typeof object.nestedType[i] !== "object") + throw TypeError(".google.protobuf.DescriptorProto.nestedType: object expected"); + message.nestedType[i] = $root.google.protobuf.DescriptorProto.fromObject(object.nestedType[i]); + } + } + if (object.enumType) { + if (!Array.isArray(object.enumType)) + throw TypeError(".google.protobuf.DescriptorProto.enumType: array expected"); + message.enumType = []; + for (var i = 0; i < object.enumType.length; ++i) { + if (typeof object.enumType[i] !== "object") + throw TypeError(".google.protobuf.DescriptorProto.enumType: object expected"); + message.enumType[i] = $root.google.protobuf.EnumDescriptorProto.fromObject(object.enumType[i]); + } + } + if (object.extensionRange) { + if (!Array.isArray(object.extensionRange)) + throw TypeError(".google.protobuf.DescriptorProto.extensionRange: array expected"); + message.extensionRange = []; + for (var i = 0; i < object.extensionRange.length; ++i) { + if (typeof object.extensionRange[i] !== "object") + throw TypeError(".google.protobuf.DescriptorProto.extensionRange: object expected"); + message.extensionRange[i] = $root.google.protobuf.DescriptorProto.ExtensionRange.fromObject(object.extensionRange[i]); + } + } + if (object.oneofDecl) { + if (!Array.isArray(object.oneofDecl)) + throw TypeError(".google.protobuf.DescriptorProto.oneofDecl: array expected"); + message.oneofDecl = []; + for (var i = 0; i < object.oneofDecl.length; ++i) { + if (typeof object.oneofDecl[i] !== "object") + throw TypeError(".google.protobuf.DescriptorProto.oneofDecl: object expected"); + message.oneofDecl[i] = $root.google.protobuf.OneofDescriptorProto.fromObject(object.oneofDecl[i]); + } + } + if (object.options != null) { + if (typeof object.options !== "object") + throw TypeError(".google.protobuf.DescriptorProto.options: object expected"); + message.options = $root.google.protobuf.MessageOptions.fromObject(object.options); + } + if (object.reservedRange) { + if (!Array.isArray(object.reservedRange)) + throw TypeError(".google.protobuf.DescriptorProto.reservedRange: array expected"); + message.reservedRange = []; + for (var i = 0; i < object.reservedRange.length; ++i) { + if (typeof object.reservedRange[i] !== "object") + throw TypeError(".google.protobuf.DescriptorProto.reservedRange: object expected"); + message.reservedRange[i] = $root.google.protobuf.DescriptorProto.ReservedRange.fromObject(object.reservedRange[i]); + } + } + if (object.reservedName) { + if (!Array.isArray(object.reservedName)) + throw TypeError(".google.protobuf.DescriptorProto.reservedName: array expected"); + message.reservedName = []; + for (var i = 0; i < object.reservedName.length; ++i) + message.reservedName[i] = String(object.reservedName[i]); + } + return message; + }; - /** - * Converts this ListCollectionIdsResponse to JSON. - * @function toJSON - * @memberof google.firestore.v1.ListCollectionIdsResponse - * @instance - * @returns {Object.} JSON object - */ - ListCollectionIdsResponse.prototype.toJSON = function toJSON() { - return this.constructor.toObject(this, $protobuf.util.toJSONOptions); - }; + /** + * Creates a plain object from a DescriptorProto message. Also converts values to other types if specified. + * @function toObject + * @memberof google.protobuf.DescriptorProto + * @static + * @param {google.protobuf.DescriptorProto} message DescriptorProto + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + DescriptorProto.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.arrays || options.defaults) { + object.field = []; + object.nestedType = []; + object.enumType = []; + object.extensionRange = []; + object.extension = []; + object.oneofDecl = []; + object.reservedRange = []; + object.reservedName = []; + } + if (options.defaults) { + object.name = ""; + object.options = null; + } + if (message.name != null && message.hasOwnProperty("name")) + object.name = message.name; + if (message.field && message.field.length) { + object.field = []; + for (var j = 0; j < message.field.length; ++j) + object.field[j] = $root.google.protobuf.FieldDescriptorProto.toObject(message.field[j], options); + } + if (message.nestedType && message.nestedType.length) { + object.nestedType = []; + for (var j = 0; j < message.nestedType.length; ++j) + object.nestedType[j] = $root.google.protobuf.DescriptorProto.toObject(message.nestedType[j], options); + } + if (message.enumType && message.enumType.length) { + object.enumType = []; + for (var j = 0; j < message.enumType.length; ++j) + object.enumType[j] = $root.google.protobuf.EnumDescriptorProto.toObject(message.enumType[j], options); + } + if (message.extensionRange && message.extensionRange.length) { + object.extensionRange = []; + for (var j = 0; j < message.extensionRange.length; ++j) + object.extensionRange[j] = $root.google.protobuf.DescriptorProto.ExtensionRange.toObject(message.extensionRange[j], options); + } + if (message.extension && message.extension.length) { + object.extension = []; + for (var j = 0; j < message.extension.length; ++j) + object.extension[j] = $root.google.protobuf.FieldDescriptorProto.toObject(message.extension[j], options); + } + if (message.options != null && message.hasOwnProperty("options")) + object.options = $root.google.protobuf.MessageOptions.toObject(message.options, options); + if (message.oneofDecl && message.oneofDecl.length) { + object.oneofDecl = []; + for (var j = 0; j < message.oneofDecl.length; ++j) + object.oneofDecl[j] = $root.google.protobuf.OneofDescriptorProto.toObject(message.oneofDecl[j], options); + } + if (message.reservedRange && message.reservedRange.length) { + object.reservedRange = []; + for (var j = 0; j < message.reservedRange.length; ++j) + object.reservedRange[j] = $root.google.protobuf.DescriptorProto.ReservedRange.toObject(message.reservedRange[j], options); + } + if (message.reservedName && message.reservedName.length) { + object.reservedName = []; + for (var j = 0; j < message.reservedName.length; ++j) + object.reservedName[j] = message.reservedName[j]; + } + return object; + }; - /** - * Gets the default type url for ListCollectionIdsResponse - * @function getTypeUrl - * @memberof google.firestore.v1.ListCollectionIdsResponse - * @static - * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") - * @returns {string} The default type url - */ - ListCollectionIdsResponse.getTypeUrl = function getTypeUrl(typeUrlPrefix) { - if (typeUrlPrefix === undefined) { - typeUrlPrefix = "type.googleapis.com"; - } - return typeUrlPrefix + "/google.firestore.v1.ListCollectionIdsResponse"; - }; + /** + * Converts this DescriptorProto to JSON. + * @function toJSON + * @memberof google.protobuf.DescriptorProto + * @instance + * @returns {Object.} JSON object + */ + DescriptorProto.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; - return ListCollectionIdsResponse; - })(); + /** + * Gets the default type url for DescriptorProto + * @function getTypeUrl + * @memberof google.protobuf.DescriptorProto + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + DescriptorProto.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.protobuf.DescriptorProto"; + }; - v1.BatchWriteRequest = (function() { + DescriptorProto.ExtensionRange = (function() { /** - * Properties of a BatchWriteRequest. - * @memberof google.firestore.v1 - * @interface IBatchWriteRequest - * @property {string|null} [database] BatchWriteRequest database - * @property {Array.|null} [writes] BatchWriteRequest writes - * @property {Object.|null} [labels] BatchWriteRequest labels + * Properties of an ExtensionRange. + * @memberof google.protobuf.DescriptorProto + * @interface IExtensionRange + * @property {number|null} [start] ExtensionRange start + * @property {number|null} [end] ExtensionRange end + * @property {google.protobuf.IExtensionRangeOptions|null} [options] ExtensionRange options */ /** - * Constructs a new BatchWriteRequest. - * @memberof google.firestore.v1 - * @classdesc Represents a BatchWriteRequest. - * @implements IBatchWriteRequest + * Constructs a new ExtensionRange. + * @memberof google.protobuf.DescriptorProto + * @classdesc Represents an ExtensionRange. + * @implements IExtensionRange * @constructor - * @param {google.firestore.v1.IBatchWriteRequest=} [properties] Properties to set + * @param {google.protobuf.DescriptorProto.IExtensionRange=} [properties] Properties to set */ - function BatchWriteRequest(properties) { - this.writes = []; - this.labels = {}; + function ExtensionRange(properties) { if (properties) for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) if (properties[keys[i]] != null) @@ -17793,148 +17211,128 @@ } /** - * BatchWriteRequest database. - * @member {string} database - * @memberof google.firestore.v1.BatchWriteRequest + * ExtensionRange start. + * @member {number} start + * @memberof google.protobuf.DescriptorProto.ExtensionRange * @instance */ - BatchWriteRequest.prototype.database = ""; + ExtensionRange.prototype.start = 0; /** - * BatchWriteRequest writes. - * @member {Array.} writes - * @memberof google.firestore.v1.BatchWriteRequest + * ExtensionRange end. + * @member {number} end + * @memberof google.protobuf.DescriptorProto.ExtensionRange * @instance */ - BatchWriteRequest.prototype.writes = $util.emptyArray; + ExtensionRange.prototype.end = 0; /** - * BatchWriteRequest labels. - * @member {Object.} labels - * @memberof google.firestore.v1.BatchWriteRequest + * ExtensionRange options. + * @member {google.protobuf.IExtensionRangeOptions|null|undefined} options + * @memberof google.protobuf.DescriptorProto.ExtensionRange * @instance */ - BatchWriteRequest.prototype.labels = $util.emptyObject; + ExtensionRange.prototype.options = null; /** - * Creates a BatchWriteRequest message from a plain object. Also converts values to their respective internal types. + * Creates an ExtensionRange message from a plain object. Also converts values to their respective internal types. * @function fromObject - * @memberof google.firestore.v1.BatchWriteRequest + * @memberof google.protobuf.DescriptorProto.ExtensionRange * @static * @param {Object.} object Plain object - * @returns {google.firestore.v1.BatchWriteRequest} BatchWriteRequest + * @returns {google.protobuf.DescriptorProto.ExtensionRange} ExtensionRange */ - BatchWriteRequest.fromObject = function fromObject(object) { - if (object instanceof $root.google.firestore.v1.BatchWriteRequest) + ExtensionRange.fromObject = function fromObject(object) { + if (object instanceof $root.google.protobuf.DescriptorProto.ExtensionRange) return object; - var message = new $root.google.firestore.v1.BatchWriteRequest(); - if (object.database != null) - message.database = String(object.database); - if (object.writes) { - if (!Array.isArray(object.writes)) - throw TypeError(".google.firestore.v1.BatchWriteRequest.writes: array expected"); - message.writes = []; - for (var i = 0; i < object.writes.length; ++i) { - if (typeof object.writes[i] !== "object") - throw TypeError(".google.firestore.v1.BatchWriteRequest.writes: object expected"); - message.writes[i] = $root.google.firestore.v1.Write.fromObject(object.writes[i]); - } - } - if (object.labels) { - if (typeof object.labels !== "object") - throw TypeError(".google.firestore.v1.BatchWriteRequest.labels: object expected"); - message.labels = {}; - for (var keys = Object.keys(object.labels), i = 0; i < keys.length; ++i) - message.labels[keys[i]] = String(object.labels[keys[i]]); + var message = new $root.google.protobuf.DescriptorProto.ExtensionRange(); + if (object.start != null) + message.start = object.start | 0; + if (object.end != null) + message.end = object.end | 0; + if (object.options != null) { + if (typeof object.options !== "object") + throw TypeError(".google.protobuf.DescriptorProto.ExtensionRange.options: object expected"); + message.options = $root.google.protobuf.ExtensionRangeOptions.fromObject(object.options); } return message; }; /** - * Creates a plain object from a BatchWriteRequest message. Also converts values to other types if specified. + * Creates a plain object from an ExtensionRange message. Also converts values to other types if specified. * @function toObject - * @memberof google.firestore.v1.BatchWriteRequest + * @memberof google.protobuf.DescriptorProto.ExtensionRange * @static - * @param {google.firestore.v1.BatchWriteRequest} message BatchWriteRequest + * @param {google.protobuf.DescriptorProto.ExtensionRange} message ExtensionRange * @param {$protobuf.IConversionOptions} [options] Conversion options * @returns {Object.} Plain object */ - BatchWriteRequest.toObject = function toObject(message, options) { + ExtensionRange.toObject = function toObject(message, options) { if (!options) options = {}; var object = {}; - if (options.arrays || options.defaults) - object.writes = []; - if (options.objects || options.defaults) - object.labels = {}; - if (options.defaults) - object.database = ""; - if (message.database != null && message.hasOwnProperty("database")) - object.database = message.database; - if (message.writes && message.writes.length) { - object.writes = []; - for (var j = 0; j < message.writes.length; ++j) - object.writes[j] = $root.google.firestore.v1.Write.toObject(message.writes[j], options); - } - var keys2; - if (message.labels && (keys2 = Object.keys(message.labels)).length) { - object.labels = {}; - for (var j = 0; j < keys2.length; ++j) - object.labels[keys2[j]] = message.labels[keys2[j]]; + if (options.defaults) { + object.start = 0; + object.end = 0; + object.options = null; } + if (message.start != null && message.hasOwnProperty("start")) + object.start = message.start; + if (message.end != null && message.hasOwnProperty("end")) + object.end = message.end; + if (message.options != null && message.hasOwnProperty("options")) + object.options = $root.google.protobuf.ExtensionRangeOptions.toObject(message.options, options); return object; }; /** - * Converts this BatchWriteRequest to JSON. + * Converts this ExtensionRange to JSON. * @function toJSON - * @memberof google.firestore.v1.BatchWriteRequest + * @memberof google.protobuf.DescriptorProto.ExtensionRange * @instance * @returns {Object.} JSON object */ - BatchWriteRequest.prototype.toJSON = function toJSON() { + ExtensionRange.prototype.toJSON = function toJSON() { return this.constructor.toObject(this, $protobuf.util.toJSONOptions); }; /** - * Gets the default type url for BatchWriteRequest + * Gets the default type url for ExtensionRange * @function getTypeUrl - * @memberof google.firestore.v1.BatchWriteRequest + * @memberof google.protobuf.DescriptorProto.ExtensionRange * @static * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") * @returns {string} The default type url */ - BatchWriteRequest.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + ExtensionRange.getTypeUrl = function getTypeUrl(typeUrlPrefix) { if (typeUrlPrefix === undefined) { typeUrlPrefix = "type.googleapis.com"; } - return typeUrlPrefix + "/google.firestore.v1.BatchWriteRequest"; + return typeUrlPrefix + "/google.protobuf.DescriptorProto.ExtensionRange"; }; - return BatchWriteRequest; + return ExtensionRange; })(); - v1.BatchWriteResponse = (function() { + DescriptorProto.ReservedRange = (function() { /** - * Properties of a BatchWriteResponse. - * @memberof google.firestore.v1 - * @interface IBatchWriteResponse - * @property {Array.|null} [writeResults] BatchWriteResponse writeResults - * @property {Array.|null} [status] BatchWriteResponse status + * Properties of a ReservedRange. + * @memberof google.protobuf.DescriptorProto + * @interface IReservedRange + * @property {number|null} [start] ReservedRange start + * @property {number|null} [end] ReservedRange end */ /** - * Constructs a new BatchWriteResponse. - * @memberof google.firestore.v1 - * @classdesc Represents a BatchWriteResponse. - * @implements IBatchWriteResponse + * Constructs a new ReservedRange. + * @memberof google.protobuf.DescriptorProto + * @classdesc Represents a ReservedRange. + * @implements IReservedRange * @constructor - * @param {google.firestore.v1.IBatchWriteResponse=} [properties] Properties to set + * @param {google.protobuf.DescriptorProto.IReservedRange=} [properties] Properties to set */ - function BatchWriteResponse(properties) { - this.writeResults = []; - this.status = []; + function ReservedRange(properties) { if (properties) for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) if (properties[keys[i]] != null) @@ -17942,272 +17340,299 @@ } /** - * BatchWriteResponse writeResults. - * @member {Array.} writeResults - * @memberof google.firestore.v1.BatchWriteResponse + * ReservedRange start. + * @member {number} start + * @memberof google.protobuf.DescriptorProto.ReservedRange * @instance */ - BatchWriteResponse.prototype.writeResults = $util.emptyArray; + ReservedRange.prototype.start = 0; /** - * BatchWriteResponse status. - * @member {Array.} status - * @memberof google.firestore.v1.BatchWriteResponse + * ReservedRange end. + * @member {number} end + * @memberof google.protobuf.DescriptorProto.ReservedRange * @instance */ - BatchWriteResponse.prototype.status = $util.emptyArray; + ReservedRange.prototype.end = 0; /** - * Creates a BatchWriteResponse message from a plain object. Also converts values to their respective internal types. + * Creates a ReservedRange message from a plain object. Also converts values to their respective internal types. * @function fromObject - * @memberof google.firestore.v1.BatchWriteResponse + * @memberof google.protobuf.DescriptorProto.ReservedRange * @static * @param {Object.} object Plain object - * @returns {google.firestore.v1.BatchWriteResponse} BatchWriteResponse + * @returns {google.protobuf.DescriptorProto.ReservedRange} ReservedRange */ - BatchWriteResponse.fromObject = function fromObject(object) { - if (object instanceof $root.google.firestore.v1.BatchWriteResponse) + ReservedRange.fromObject = function fromObject(object) { + if (object instanceof $root.google.protobuf.DescriptorProto.ReservedRange) return object; - var message = new $root.google.firestore.v1.BatchWriteResponse(); - if (object.writeResults) { - if (!Array.isArray(object.writeResults)) - throw TypeError(".google.firestore.v1.BatchWriteResponse.writeResults: array expected"); - message.writeResults = []; - for (var i = 0; i < object.writeResults.length; ++i) { - if (typeof object.writeResults[i] !== "object") - throw TypeError(".google.firestore.v1.BatchWriteResponse.writeResults: object expected"); - message.writeResults[i] = $root.google.firestore.v1.WriteResult.fromObject(object.writeResults[i]); - } - } - if (object.status) { - if (!Array.isArray(object.status)) - throw TypeError(".google.firestore.v1.BatchWriteResponse.status: array expected"); - message.status = []; - for (var i = 0; i < object.status.length; ++i) { - if (typeof object.status[i] !== "object") - throw TypeError(".google.firestore.v1.BatchWriteResponse.status: object expected"); - message.status[i] = $root.google.rpc.Status.fromObject(object.status[i]); - } - } + var message = new $root.google.protobuf.DescriptorProto.ReservedRange(); + if (object.start != null) + message.start = object.start | 0; + if (object.end != null) + message.end = object.end | 0; return message; }; /** - * Creates a plain object from a BatchWriteResponse message. Also converts values to other types if specified. + * Creates a plain object from a ReservedRange message. Also converts values to other types if specified. * @function toObject - * @memberof google.firestore.v1.BatchWriteResponse + * @memberof google.protobuf.DescriptorProto.ReservedRange * @static - * @param {google.firestore.v1.BatchWriteResponse} message BatchWriteResponse + * @param {google.protobuf.DescriptorProto.ReservedRange} message ReservedRange * @param {$protobuf.IConversionOptions} [options] Conversion options * @returns {Object.} Plain object */ - BatchWriteResponse.toObject = function toObject(message, options) { + ReservedRange.toObject = function toObject(message, options) { if (!options) options = {}; var object = {}; - if (options.arrays || options.defaults) { - object.writeResults = []; - object.status = []; - } - if (message.writeResults && message.writeResults.length) { - object.writeResults = []; - for (var j = 0; j < message.writeResults.length; ++j) - object.writeResults[j] = $root.google.firestore.v1.WriteResult.toObject(message.writeResults[j], options); - } - if (message.status && message.status.length) { - object.status = []; - for (var j = 0; j < message.status.length; ++j) - object.status[j] = $root.google.rpc.Status.toObject(message.status[j], options); + if (options.defaults) { + object.start = 0; + object.end = 0; } + if (message.start != null && message.hasOwnProperty("start")) + object.start = message.start; + if (message.end != null && message.hasOwnProperty("end")) + object.end = message.end; return object; }; /** - * Converts this BatchWriteResponse to JSON. + * Converts this ReservedRange to JSON. * @function toJSON - * @memberof google.firestore.v1.BatchWriteResponse + * @memberof google.protobuf.DescriptorProto.ReservedRange * @instance * @returns {Object.} JSON object */ - BatchWriteResponse.prototype.toJSON = function toJSON() { + ReservedRange.prototype.toJSON = function toJSON() { return this.constructor.toObject(this, $protobuf.util.toJSONOptions); }; /** - * Gets the default type url for BatchWriteResponse + * Gets the default type url for ReservedRange * @function getTypeUrl - * @memberof google.firestore.v1.BatchWriteResponse + * @memberof google.protobuf.DescriptorProto.ReservedRange * @static * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") * @returns {string} The default type url */ - BatchWriteResponse.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + ReservedRange.getTypeUrl = function getTypeUrl(typeUrlPrefix) { if (typeUrlPrefix === undefined) { typeUrlPrefix = "type.googleapis.com"; } - return typeUrlPrefix + "/google.firestore.v1.BatchWriteResponse"; + return typeUrlPrefix + "/google.protobuf.DescriptorProto.ReservedRange"; }; - return BatchWriteResponse; + return ReservedRange; })(); - v1.StructuredPipeline = (function() { + return DescriptorProto; + })(); - /** - * Properties of a StructuredPipeline. - * @memberof google.firestore.v1 - * @interface IStructuredPipeline - * @property {google.firestore.v1.IPipeline|null} [pipeline] StructuredPipeline pipeline - * @property {Object.|null} [options] StructuredPipeline options - */ + protobuf.ExtensionRangeOptions = (function() { - /** - * Constructs a new StructuredPipeline. - * @memberof google.firestore.v1 - * @classdesc Represents a StructuredPipeline. - * @implements IStructuredPipeline - * @constructor - * @param {google.firestore.v1.IStructuredPipeline=} [properties] Properties to set - */ - function StructuredPipeline(properties) { - this.options = {}; - if (properties) - for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) - if (properties[keys[i]] != null) - this[keys[i]] = properties[keys[i]]; - } + /** + * Properties of an ExtensionRangeOptions. + * @memberof google.protobuf + * @interface IExtensionRangeOptions + * @property {Array.|null} [uninterpretedOption] ExtensionRangeOptions uninterpretedOption + * @property {Array.|null} [declaration] ExtensionRangeOptions declaration + * @property {google.protobuf.IFeatureSet|null} [features] ExtensionRangeOptions features + * @property {google.protobuf.ExtensionRangeOptions.VerificationState|null} [verification] ExtensionRangeOptions verification + */ - /** - * StructuredPipeline pipeline. - * @member {google.firestore.v1.IPipeline|null|undefined} pipeline - * @memberof google.firestore.v1.StructuredPipeline - * @instance - */ - StructuredPipeline.prototype.pipeline = null; + /** + * Constructs a new ExtensionRangeOptions. + * @memberof google.protobuf + * @classdesc Represents an ExtensionRangeOptions. + * @implements IExtensionRangeOptions + * @constructor + * @param {google.protobuf.IExtensionRangeOptions=} [properties] Properties to set + */ + function ExtensionRangeOptions(properties) { + this.uninterpretedOption = []; + this.declaration = []; + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } - /** - * StructuredPipeline options. - * @member {Object.} options - * @memberof google.firestore.v1.StructuredPipeline - * @instance - */ - StructuredPipeline.prototype.options = $util.emptyObject; + /** + * ExtensionRangeOptions uninterpretedOption. + * @member {Array.} uninterpretedOption + * @memberof google.protobuf.ExtensionRangeOptions + * @instance + */ + ExtensionRangeOptions.prototype.uninterpretedOption = $util.emptyArray; - /** - * Creates a StructuredPipeline message from a plain object. Also converts values to their respective internal types. - * @function fromObject - * @memberof google.firestore.v1.StructuredPipeline - * @static - * @param {Object.} object Plain object - * @returns {google.firestore.v1.StructuredPipeline} StructuredPipeline - */ - StructuredPipeline.fromObject = function fromObject(object) { - if (object instanceof $root.google.firestore.v1.StructuredPipeline) - return object; - var message = new $root.google.firestore.v1.StructuredPipeline(); - if (object.pipeline != null) { - if (typeof object.pipeline !== "object") - throw TypeError(".google.firestore.v1.StructuredPipeline.pipeline: object expected"); - message.pipeline = $root.google.firestore.v1.Pipeline.fromObject(object.pipeline); + /** + * ExtensionRangeOptions declaration. + * @member {Array.} declaration + * @memberof google.protobuf.ExtensionRangeOptions + * @instance + */ + ExtensionRangeOptions.prototype.declaration = $util.emptyArray; + + /** + * ExtensionRangeOptions features. + * @member {google.protobuf.IFeatureSet|null|undefined} features + * @memberof google.protobuf.ExtensionRangeOptions + * @instance + */ + ExtensionRangeOptions.prototype.features = null; + + /** + * ExtensionRangeOptions verification. + * @member {google.protobuf.ExtensionRangeOptions.VerificationState} verification + * @memberof google.protobuf.ExtensionRangeOptions + * @instance + */ + ExtensionRangeOptions.prototype.verification = 1; + + /** + * Creates an ExtensionRangeOptions message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.protobuf.ExtensionRangeOptions + * @static + * @param {Object.} object Plain object + * @returns {google.protobuf.ExtensionRangeOptions} ExtensionRangeOptions + */ + ExtensionRangeOptions.fromObject = function fromObject(object) { + if (object instanceof $root.google.protobuf.ExtensionRangeOptions) + return object; + var message = new $root.google.protobuf.ExtensionRangeOptions(); + if (object.uninterpretedOption) { + if (!Array.isArray(object.uninterpretedOption)) + throw TypeError(".google.protobuf.ExtensionRangeOptions.uninterpretedOption: array expected"); + message.uninterpretedOption = []; + for (var i = 0; i < object.uninterpretedOption.length; ++i) { + if (typeof object.uninterpretedOption[i] !== "object") + throw TypeError(".google.protobuf.ExtensionRangeOptions.uninterpretedOption: object expected"); + message.uninterpretedOption[i] = $root.google.protobuf.UninterpretedOption.fromObject(object.uninterpretedOption[i]); } - if (object.options) { - if (typeof object.options !== "object") - throw TypeError(".google.firestore.v1.StructuredPipeline.options: object expected"); - message.options = {}; - for (var keys = Object.keys(object.options), i = 0; i < keys.length; ++i) { - if (typeof object.options[keys[i]] !== "object") - throw TypeError(".google.firestore.v1.StructuredPipeline.options: object expected"); - message.options[keys[i]] = $root.google.firestore.v1.Value.fromObject(object.options[keys[i]]); - } + } + if (object.declaration) { + if (!Array.isArray(object.declaration)) + throw TypeError(".google.protobuf.ExtensionRangeOptions.declaration: array expected"); + message.declaration = []; + for (var i = 0; i < object.declaration.length; ++i) { + if (typeof object.declaration[i] !== "object") + throw TypeError(".google.protobuf.ExtensionRangeOptions.declaration: object expected"); + message.declaration[i] = $root.google.protobuf.ExtensionRangeOptions.Declaration.fromObject(object.declaration[i]); } - return message; - }; - - /** - * Creates a plain object from a StructuredPipeline message. Also converts values to other types if specified. - * @function toObject - * @memberof google.firestore.v1.StructuredPipeline - * @static - * @param {google.firestore.v1.StructuredPipeline} message StructuredPipeline - * @param {$protobuf.IConversionOptions} [options] Conversion options - * @returns {Object.} Plain object - */ - StructuredPipeline.toObject = function toObject(message, options) { - if (!options) - options = {}; - var object = {}; - if (options.objects || options.defaults) - object.options = {}; - if (options.defaults) - object.pipeline = null; - if (message.pipeline != null && message.hasOwnProperty("pipeline")) - object.pipeline = $root.google.firestore.v1.Pipeline.toObject(message.pipeline, options); - var keys2; - if (message.options && (keys2 = Object.keys(message.options)).length) { - object.options = {}; - for (var j = 0; j < keys2.length; ++j) - object.options[keys2[j]] = $root.google.firestore.v1.Value.toObject(message.options[keys2[j]], options); + } + if (object.features != null) { + if (typeof object.features !== "object") + throw TypeError(".google.protobuf.ExtensionRangeOptions.features: object expected"); + message.features = $root.google.protobuf.FeatureSet.fromObject(object.features); + } + switch (object.verification) { + case "DECLARATION": + case 0: + message.verification = 0; + break; + default: + if (typeof object.verification === "number") { + message.verification = object.verification; + break; } - return object; - }; + break; + case "UNVERIFIED": + case 1: + message.verification = 1; + break; + } + return message; + }; - /** - * Converts this StructuredPipeline to JSON. - * @function toJSON - * @memberof google.firestore.v1.StructuredPipeline - * @instance - * @returns {Object.} JSON object - */ - StructuredPipeline.prototype.toJSON = function toJSON() { - return this.constructor.toObject(this, $protobuf.util.toJSONOptions); - }; + /** + * Creates a plain object from an ExtensionRangeOptions message. Also converts values to other types if specified. + * @function toObject + * @memberof google.protobuf.ExtensionRangeOptions + * @static + * @param {google.protobuf.ExtensionRangeOptions} message ExtensionRangeOptions + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + ExtensionRangeOptions.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.arrays || options.defaults) { + object.declaration = []; + object.uninterpretedOption = []; + } + if (options.defaults) { + object.verification = options.enums === String ? "UNVERIFIED" : 1; + object.features = null; + } + if (message.declaration && message.declaration.length) { + object.declaration = []; + for (var j = 0; j < message.declaration.length; ++j) + object.declaration[j] = $root.google.protobuf.ExtensionRangeOptions.Declaration.toObject(message.declaration[j], options); + } + if (message.verification != null && message.hasOwnProperty("verification")) + object.verification = options.enums === String ? $root.google.protobuf.ExtensionRangeOptions.VerificationState[message.verification] === undefined ? message.verification : $root.google.protobuf.ExtensionRangeOptions.VerificationState[message.verification] : message.verification; + if (message.features != null && message.hasOwnProperty("features")) + object.features = $root.google.protobuf.FeatureSet.toObject(message.features, options); + if (message.uninterpretedOption && message.uninterpretedOption.length) { + object.uninterpretedOption = []; + for (var j = 0; j < message.uninterpretedOption.length; ++j) + object.uninterpretedOption[j] = $root.google.protobuf.UninterpretedOption.toObject(message.uninterpretedOption[j], options); + } + return object; + }; - /** - * Gets the default type url for StructuredPipeline - * @function getTypeUrl - * @memberof google.firestore.v1.StructuredPipeline - * @static - * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") - * @returns {string} The default type url - */ - StructuredPipeline.getTypeUrl = function getTypeUrl(typeUrlPrefix) { - if (typeUrlPrefix === undefined) { - typeUrlPrefix = "type.googleapis.com"; - } - return typeUrlPrefix + "/google.firestore.v1.StructuredPipeline"; - }; + /** + * Converts this ExtensionRangeOptions to JSON. + * @function toJSON + * @memberof google.protobuf.ExtensionRangeOptions + * @instance + * @returns {Object.} JSON object + */ + ExtensionRangeOptions.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; - return StructuredPipeline; - })(); + /** + * Gets the default type url for ExtensionRangeOptions + * @function getTypeUrl + * @memberof google.protobuf.ExtensionRangeOptions + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + ExtensionRangeOptions.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.protobuf.ExtensionRangeOptions"; + }; - v1.StructuredQuery = (function() { + ExtensionRangeOptions.Declaration = (function() { /** - * Properties of a StructuredQuery. - * @memberof google.firestore.v1 - * @interface IStructuredQuery - * @property {google.firestore.v1.StructuredQuery.IProjection|null} [select] StructuredQuery select - * @property {Array.|null} [from] StructuredQuery from - * @property {google.firestore.v1.StructuredQuery.IFilter|null} [where] StructuredQuery where - * @property {Array.|null} [orderBy] StructuredQuery orderBy - * @property {google.firestore.v1.ICursor|null} [startAt] StructuredQuery startAt - * @property {google.firestore.v1.ICursor|null} [endAt] StructuredQuery endAt - * @property {number|null} [offset] StructuredQuery offset - * @property {google.protobuf.IInt32Value|null} [limit] StructuredQuery limit - * @property {google.firestore.v1.StructuredQuery.IFindNearest|null} [findNearest] StructuredQuery findNearest + * Properties of a Declaration. + * @memberof google.protobuf.ExtensionRangeOptions + * @interface IDeclaration + * @property {number|null} [number] Declaration number + * @property {string|null} [fullName] Declaration fullName + * @property {string|null} [type] Declaration type + * @property {boolean|null} [reserved] Declaration reserved + * @property {boolean|null} [repeated] Declaration repeated */ /** - * Constructs a new StructuredQuery. - * @memberof google.firestore.v1 - * @classdesc Represents a StructuredQuery. - * @implements IStructuredQuery + * Constructs a new Declaration. + * @memberof google.protobuf.ExtensionRangeOptions + * @classdesc Represents a Declaration. + * @implements IDeclaration * @constructor - * @param {google.firestore.v1.IStructuredQuery=} [properties] Properties to set + * @param {google.protobuf.ExtensionRangeOptions.IDeclaration=} [properties] Properties to set */ - function StructuredQuery(properties) { - this.from = []; - this.orderBy = []; + function Declaration(properties) { if (properties) for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) if (properties[keys[i]] != null) @@ -18215,2449 +17640,2669 @@ } /** - * StructuredQuery select. - * @member {google.firestore.v1.StructuredQuery.IProjection|null|undefined} select - * @memberof google.firestore.v1.StructuredQuery - * @instance - */ - StructuredQuery.prototype.select = null; - - /** - * StructuredQuery from. - * @member {Array.} from - * @memberof google.firestore.v1.StructuredQuery - * @instance - */ - StructuredQuery.prototype.from = $util.emptyArray; - - /** - * StructuredQuery where. - * @member {google.firestore.v1.StructuredQuery.IFilter|null|undefined} where - * @memberof google.firestore.v1.StructuredQuery - * @instance - */ - StructuredQuery.prototype.where = null; - - /** - * StructuredQuery orderBy. - * @member {Array.} orderBy - * @memberof google.firestore.v1.StructuredQuery - * @instance - */ - StructuredQuery.prototype.orderBy = $util.emptyArray; - - /** - * StructuredQuery startAt. - * @member {google.firestore.v1.ICursor|null|undefined} startAt - * @memberof google.firestore.v1.StructuredQuery + * Declaration number. + * @member {number} number + * @memberof google.protobuf.ExtensionRangeOptions.Declaration * @instance */ - StructuredQuery.prototype.startAt = null; + Declaration.prototype.number = 0; /** - * StructuredQuery endAt. - * @member {google.firestore.v1.ICursor|null|undefined} endAt - * @memberof google.firestore.v1.StructuredQuery + * Declaration fullName. + * @member {string} fullName + * @memberof google.protobuf.ExtensionRangeOptions.Declaration * @instance */ - StructuredQuery.prototype.endAt = null; + Declaration.prototype.fullName = ""; /** - * StructuredQuery offset. - * @member {number} offset - * @memberof google.firestore.v1.StructuredQuery + * Declaration type. + * @member {string} type + * @memberof google.protobuf.ExtensionRangeOptions.Declaration * @instance */ - StructuredQuery.prototype.offset = 0; + Declaration.prototype.type = ""; /** - * StructuredQuery limit. - * @member {google.protobuf.IInt32Value|null|undefined} limit - * @memberof google.firestore.v1.StructuredQuery + * Declaration reserved. + * @member {boolean} reserved + * @memberof google.protobuf.ExtensionRangeOptions.Declaration * @instance */ - StructuredQuery.prototype.limit = null; + Declaration.prototype.reserved = false; /** - * StructuredQuery findNearest. - * @member {google.firestore.v1.StructuredQuery.IFindNearest|null|undefined} findNearest - * @memberof google.firestore.v1.StructuredQuery + * Declaration repeated. + * @member {boolean} repeated + * @memberof google.protobuf.ExtensionRangeOptions.Declaration * @instance */ - StructuredQuery.prototype.findNearest = null; + Declaration.prototype.repeated = false; /** - * Creates a StructuredQuery message from a plain object. Also converts values to their respective internal types. + * Creates a Declaration message from a plain object. Also converts values to their respective internal types. * @function fromObject - * @memberof google.firestore.v1.StructuredQuery + * @memberof google.protobuf.ExtensionRangeOptions.Declaration * @static * @param {Object.} object Plain object - * @returns {google.firestore.v1.StructuredQuery} StructuredQuery + * @returns {google.protobuf.ExtensionRangeOptions.Declaration} Declaration */ - StructuredQuery.fromObject = function fromObject(object) { - if (object instanceof $root.google.firestore.v1.StructuredQuery) + Declaration.fromObject = function fromObject(object) { + if (object instanceof $root.google.protobuf.ExtensionRangeOptions.Declaration) return object; - var message = new $root.google.firestore.v1.StructuredQuery(); - if (object.select != null) { - if (typeof object.select !== "object") - throw TypeError(".google.firestore.v1.StructuredQuery.select: object expected"); - message.select = $root.google.firestore.v1.StructuredQuery.Projection.fromObject(object.select); - } - if (object.from) { - if (!Array.isArray(object.from)) - throw TypeError(".google.firestore.v1.StructuredQuery.from: array expected"); - message.from = []; - for (var i = 0; i < object.from.length; ++i) { - if (typeof object.from[i] !== "object") - throw TypeError(".google.firestore.v1.StructuredQuery.from: object expected"); - message.from[i] = $root.google.firestore.v1.StructuredQuery.CollectionSelector.fromObject(object.from[i]); - } - } - if (object.where != null) { - if (typeof object.where !== "object") - throw TypeError(".google.firestore.v1.StructuredQuery.where: object expected"); - message.where = $root.google.firestore.v1.StructuredQuery.Filter.fromObject(object.where); - } - if (object.orderBy) { - if (!Array.isArray(object.orderBy)) - throw TypeError(".google.firestore.v1.StructuredQuery.orderBy: array expected"); - message.orderBy = []; - for (var i = 0; i < object.orderBy.length; ++i) { - if (typeof object.orderBy[i] !== "object") - throw TypeError(".google.firestore.v1.StructuredQuery.orderBy: object expected"); - message.orderBy[i] = $root.google.firestore.v1.StructuredQuery.Order.fromObject(object.orderBy[i]); - } - } - if (object.startAt != null) { - if (typeof object.startAt !== "object") - throw TypeError(".google.firestore.v1.StructuredQuery.startAt: object expected"); - message.startAt = $root.google.firestore.v1.Cursor.fromObject(object.startAt); - } - if (object.endAt != null) { - if (typeof object.endAt !== "object") - throw TypeError(".google.firestore.v1.StructuredQuery.endAt: object expected"); - message.endAt = $root.google.firestore.v1.Cursor.fromObject(object.endAt); - } - if (object.offset != null) - message.offset = object.offset | 0; - if (object.limit != null) { - if (typeof object.limit !== "object") - throw TypeError(".google.firestore.v1.StructuredQuery.limit: object expected"); - message.limit = $root.google.protobuf.Int32Value.fromObject(object.limit); - } - if (object.findNearest != null) { - if (typeof object.findNearest !== "object") - throw TypeError(".google.firestore.v1.StructuredQuery.findNearest: object expected"); - message.findNearest = $root.google.firestore.v1.StructuredQuery.FindNearest.fromObject(object.findNearest); - } + var message = new $root.google.protobuf.ExtensionRangeOptions.Declaration(); + if (object.number != null) + message.number = object.number | 0; + if (object.fullName != null) + message.fullName = String(object.fullName); + if (object.type != null) + message.type = String(object.type); + if (object.reserved != null) + message.reserved = Boolean(object.reserved); + if (object.repeated != null) + message.repeated = Boolean(object.repeated); return message; }; /** - * Creates a plain object from a StructuredQuery message. Also converts values to other types if specified. + * Creates a plain object from a Declaration message. Also converts values to other types if specified. * @function toObject - * @memberof google.firestore.v1.StructuredQuery + * @memberof google.protobuf.ExtensionRangeOptions.Declaration * @static - * @param {google.firestore.v1.StructuredQuery} message StructuredQuery + * @param {google.protobuf.ExtensionRangeOptions.Declaration} message Declaration * @param {$protobuf.IConversionOptions} [options] Conversion options * @returns {Object.} Plain object */ - StructuredQuery.toObject = function toObject(message, options) { + Declaration.toObject = function toObject(message, options) { if (!options) options = {}; var object = {}; - if (options.arrays || options.defaults) { - object.from = []; - object.orderBy = []; - } if (options.defaults) { - object.select = null; - object.where = null; - object.limit = null; - object.offset = 0; - object.startAt = null; - object.endAt = null; - object.findNearest = null; - } - if (message.select != null && message.hasOwnProperty("select")) - object.select = $root.google.firestore.v1.StructuredQuery.Projection.toObject(message.select, options); - if (message.from && message.from.length) { - object.from = []; - for (var j = 0; j < message.from.length; ++j) - object.from[j] = $root.google.firestore.v1.StructuredQuery.CollectionSelector.toObject(message.from[j], options); - } - if (message.where != null && message.hasOwnProperty("where")) - object.where = $root.google.firestore.v1.StructuredQuery.Filter.toObject(message.where, options); - if (message.orderBy && message.orderBy.length) { - object.orderBy = []; - for (var j = 0; j < message.orderBy.length; ++j) - object.orderBy[j] = $root.google.firestore.v1.StructuredQuery.Order.toObject(message.orderBy[j], options); + object.number = 0; + object.fullName = ""; + object.type = ""; + object.reserved = false; + object.repeated = false; } - if (message.limit != null && message.hasOwnProperty("limit")) - object.limit = $root.google.protobuf.Int32Value.toObject(message.limit, options); - if (message.offset != null && message.hasOwnProperty("offset")) - object.offset = message.offset; - if (message.startAt != null && message.hasOwnProperty("startAt")) - object.startAt = $root.google.firestore.v1.Cursor.toObject(message.startAt, options); - if (message.endAt != null && message.hasOwnProperty("endAt")) - object.endAt = $root.google.firestore.v1.Cursor.toObject(message.endAt, options); - if (message.findNearest != null && message.hasOwnProperty("findNearest")) - object.findNearest = $root.google.firestore.v1.StructuredQuery.FindNearest.toObject(message.findNearest, options); + if (message.number != null && message.hasOwnProperty("number")) + object.number = message.number; + if (message.fullName != null && message.hasOwnProperty("fullName")) + object.fullName = message.fullName; + if (message.type != null && message.hasOwnProperty("type")) + object.type = message.type; + if (message.reserved != null && message.hasOwnProperty("reserved")) + object.reserved = message.reserved; + if (message.repeated != null && message.hasOwnProperty("repeated")) + object.repeated = message.repeated; return object; }; /** - * Converts this StructuredQuery to JSON. + * Converts this Declaration to JSON. * @function toJSON - * @memberof google.firestore.v1.StructuredQuery + * @memberof google.protobuf.ExtensionRangeOptions.Declaration * @instance * @returns {Object.} JSON object */ - StructuredQuery.prototype.toJSON = function toJSON() { + Declaration.prototype.toJSON = function toJSON() { return this.constructor.toObject(this, $protobuf.util.toJSONOptions); - }; - - /** - * Gets the default type url for StructuredQuery - * @function getTypeUrl - * @memberof google.firestore.v1.StructuredQuery - * @static - * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") - * @returns {string} The default type url - */ - StructuredQuery.getTypeUrl = function getTypeUrl(typeUrlPrefix) { - if (typeUrlPrefix === undefined) { - typeUrlPrefix = "type.googleapis.com"; - } - return typeUrlPrefix + "/google.firestore.v1.StructuredQuery"; - }; - - StructuredQuery.CollectionSelector = (function() { - - /** - * Properties of a CollectionSelector. - * @memberof google.firestore.v1.StructuredQuery - * @interface ICollectionSelector - * @property {string|null} [collectionId] CollectionSelector collectionId - * @property {boolean|null} [allDescendants] CollectionSelector allDescendants - */ - - /** - * Constructs a new CollectionSelector. - * @memberof google.firestore.v1.StructuredQuery - * @classdesc Represents a CollectionSelector. - * @implements ICollectionSelector - * @constructor - * @param {google.firestore.v1.StructuredQuery.ICollectionSelector=} [properties] Properties to set - */ - function CollectionSelector(properties) { - if (properties) - for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) - if (properties[keys[i]] != null) - this[keys[i]] = properties[keys[i]]; - } - - /** - * CollectionSelector collectionId. - * @member {string} collectionId - * @memberof google.firestore.v1.StructuredQuery.CollectionSelector - * @instance - */ - CollectionSelector.prototype.collectionId = ""; - - /** - * CollectionSelector allDescendants. - * @member {boolean} allDescendants - * @memberof google.firestore.v1.StructuredQuery.CollectionSelector - * @instance - */ - CollectionSelector.prototype.allDescendants = false; - - /** - * Creates a CollectionSelector message from a plain object. Also converts values to their respective internal types. - * @function fromObject - * @memberof google.firestore.v1.StructuredQuery.CollectionSelector - * @static - * @param {Object.} object Plain object - * @returns {google.firestore.v1.StructuredQuery.CollectionSelector} CollectionSelector - */ - CollectionSelector.fromObject = function fromObject(object) { - if (object instanceof $root.google.firestore.v1.StructuredQuery.CollectionSelector) - return object; - var message = new $root.google.firestore.v1.StructuredQuery.CollectionSelector(); - if (object.collectionId != null) - message.collectionId = String(object.collectionId); - if (object.allDescendants != null) - message.allDescendants = Boolean(object.allDescendants); - return message; - }; - - /** - * Creates a plain object from a CollectionSelector message. Also converts values to other types if specified. - * @function toObject - * @memberof google.firestore.v1.StructuredQuery.CollectionSelector - * @static - * @param {google.firestore.v1.StructuredQuery.CollectionSelector} message CollectionSelector - * @param {$protobuf.IConversionOptions} [options] Conversion options - * @returns {Object.} Plain object - */ - CollectionSelector.toObject = function toObject(message, options) { - if (!options) - options = {}; - var object = {}; - if (options.defaults) { - object.collectionId = ""; - object.allDescendants = false; - } - if (message.collectionId != null && message.hasOwnProperty("collectionId")) - object.collectionId = message.collectionId; - if (message.allDescendants != null && message.hasOwnProperty("allDescendants")) - object.allDescendants = message.allDescendants; - return object; - }; + }; - /** - * Converts this CollectionSelector to JSON. - * @function toJSON - * @memberof google.firestore.v1.StructuredQuery.CollectionSelector - * @instance - * @returns {Object.} JSON object - */ - CollectionSelector.prototype.toJSON = function toJSON() { - return this.constructor.toObject(this, $protobuf.util.toJSONOptions); - }; + /** + * Gets the default type url for Declaration + * @function getTypeUrl + * @memberof google.protobuf.ExtensionRangeOptions.Declaration + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + Declaration.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.protobuf.ExtensionRangeOptions.Declaration"; + }; - /** - * Gets the default type url for CollectionSelector - * @function getTypeUrl - * @memberof google.firestore.v1.StructuredQuery.CollectionSelector - * @static - * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") - * @returns {string} The default type url - */ - CollectionSelector.getTypeUrl = function getTypeUrl(typeUrlPrefix) { - if (typeUrlPrefix === undefined) { - typeUrlPrefix = "type.googleapis.com"; - } - return typeUrlPrefix + "/google.firestore.v1.StructuredQuery.CollectionSelector"; - }; + return Declaration; + })(); - return CollectionSelector; - })(); + /** + * VerificationState enum. + * @name google.protobuf.ExtensionRangeOptions.VerificationState + * @enum {string} + * @property {string} DECLARATION=DECLARATION DECLARATION value + * @property {string} UNVERIFIED=UNVERIFIED UNVERIFIED value + */ + ExtensionRangeOptions.VerificationState = (function() { + var valuesById = {}, values = Object.create(valuesById); + values[valuesById[0] = "DECLARATION"] = "DECLARATION"; + values[valuesById[1] = "UNVERIFIED"] = "UNVERIFIED"; + return values; + })(); - StructuredQuery.Filter = (function() { + return ExtensionRangeOptions; + })(); - /** - * Properties of a Filter. - * @memberof google.firestore.v1.StructuredQuery - * @interface IFilter - * @property {google.firestore.v1.StructuredQuery.ICompositeFilter|null} [compositeFilter] Filter compositeFilter - * @property {google.firestore.v1.StructuredQuery.IFieldFilter|null} [fieldFilter] Filter fieldFilter - * @property {google.firestore.v1.StructuredQuery.IUnaryFilter|null} [unaryFilter] Filter unaryFilter - */ + protobuf.FieldDescriptorProto = (function() { - /** - * Constructs a new Filter. - * @memberof google.firestore.v1.StructuredQuery - * @classdesc Represents a Filter. - * @implements IFilter - * @constructor - * @param {google.firestore.v1.StructuredQuery.IFilter=} [properties] Properties to set - */ - function Filter(properties) { - if (properties) - for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) - if (properties[keys[i]] != null) - this[keys[i]] = properties[keys[i]]; - } + /** + * Properties of a FieldDescriptorProto. + * @memberof google.protobuf + * @interface IFieldDescriptorProto + * @property {string|null} [name] FieldDescriptorProto name + * @property {number|null} [number] FieldDescriptorProto number + * @property {google.protobuf.FieldDescriptorProto.Label|null} [label] FieldDescriptorProto label + * @property {google.protobuf.FieldDescriptorProto.Type|null} [type] FieldDescriptorProto type + * @property {string|null} [typeName] FieldDescriptorProto typeName + * @property {string|null} [extendee] FieldDescriptorProto extendee + * @property {string|null} [defaultValue] FieldDescriptorProto defaultValue + * @property {number|null} [oneofIndex] FieldDescriptorProto oneofIndex + * @property {string|null} [jsonName] FieldDescriptorProto jsonName + * @property {google.protobuf.IFieldOptions|null} [options] FieldDescriptorProto options + * @property {boolean|null} [proto3Optional] FieldDescriptorProto proto3Optional + */ - /** - * Filter compositeFilter. - * @member {google.firestore.v1.StructuredQuery.ICompositeFilter|null|undefined} compositeFilter - * @memberof google.firestore.v1.StructuredQuery.Filter - * @instance - */ - Filter.prototype.compositeFilter = null; + /** + * Constructs a new FieldDescriptorProto. + * @memberof google.protobuf + * @classdesc Represents a FieldDescriptorProto. + * @implements IFieldDescriptorProto + * @constructor + * @param {google.protobuf.IFieldDescriptorProto=} [properties] Properties to set + */ + function FieldDescriptorProto(properties) { + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } - /** - * Filter fieldFilter. - * @member {google.firestore.v1.StructuredQuery.IFieldFilter|null|undefined} fieldFilter - * @memberof google.firestore.v1.StructuredQuery.Filter - * @instance - */ - Filter.prototype.fieldFilter = null; + /** + * FieldDescriptorProto name. + * @member {string} name + * @memberof google.protobuf.FieldDescriptorProto + * @instance + */ + FieldDescriptorProto.prototype.name = ""; - /** - * Filter unaryFilter. - * @member {google.firestore.v1.StructuredQuery.IUnaryFilter|null|undefined} unaryFilter - * @memberof google.firestore.v1.StructuredQuery.Filter - * @instance - */ - Filter.prototype.unaryFilter = null; + /** + * FieldDescriptorProto number. + * @member {number} number + * @memberof google.protobuf.FieldDescriptorProto + * @instance + */ + FieldDescriptorProto.prototype.number = 0; - // OneOf field names bound to virtual getters and setters - var $oneOfFields; + /** + * FieldDescriptorProto label. + * @member {google.protobuf.FieldDescriptorProto.Label} label + * @memberof google.protobuf.FieldDescriptorProto + * @instance + */ + FieldDescriptorProto.prototype.label = 1; - /** - * Filter filterType. - * @member {"compositeFilter"|"fieldFilter"|"unaryFilter"|undefined} filterType - * @memberof google.firestore.v1.StructuredQuery.Filter - * @instance - */ - Object.defineProperty(Filter.prototype, "filterType", { - get: $util.oneOfGetter($oneOfFields = ["compositeFilter", "fieldFilter", "unaryFilter"]), - set: $util.oneOfSetter($oneOfFields) - }); + /** + * FieldDescriptorProto type. + * @member {google.protobuf.FieldDescriptorProto.Type} type + * @memberof google.protobuf.FieldDescriptorProto + * @instance + */ + FieldDescriptorProto.prototype.type = 1; - /** - * Creates a Filter message from a plain object. Also converts values to their respective internal types. - * @function fromObject - * @memberof google.firestore.v1.StructuredQuery.Filter - * @static - * @param {Object.} object Plain object - * @returns {google.firestore.v1.StructuredQuery.Filter} Filter - */ - Filter.fromObject = function fromObject(object) { - if (object instanceof $root.google.firestore.v1.StructuredQuery.Filter) - return object; - var message = new $root.google.firestore.v1.StructuredQuery.Filter(); - if (object.compositeFilter != null) { - if (typeof object.compositeFilter !== "object") - throw TypeError(".google.firestore.v1.StructuredQuery.Filter.compositeFilter: object expected"); - message.compositeFilter = $root.google.firestore.v1.StructuredQuery.CompositeFilter.fromObject(object.compositeFilter); - } - if (object.fieldFilter != null) { - if (typeof object.fieldFilter !== "object") - throw TypeError(".google.firestore.v1.StructuredQuery.Filter.fieldFilter: object expected"); - message.fieldFilter = $root.google.firestore.v1.StructuredQuery.FieldFilter.fromObject(object.fieldFilter); - } - if (object.unaryFilter != null) { - if (typeof object.unaryFilter !== "object") - throw TypeError(".google.firestore.v1.StructuredQuery.Filter.unaryFilter: object expected"); - message.unaryFilter = $root.google.firestore.v1.StructuredQuery.UnaryFilter.fromObject(object.unaryFilter); - } - return message; - }; + /** + * FieldDescriptorProto typeName. + * @member {string} typeName + * @memberof google.protobuf.FieldDescriptorProto + * @instance + */ + FieldDescriptorProto.prototype.typeName = ""; - /** - * Creates a plain object from a Filter message. Also converts values to other types if specified. - * @function toObject - * @memberof google.firestore.v1.StructuredQuery.Filter - * @static - * @param {google.firestore.v1.StructuredQuery.Filter} message Filter - * @param {$protobuf.IConversionOptions} [options] Conversion options - * @returns {Object.} Plain object - */ - Filter.toObject = function toObject(message, options) { - if (!options) - options = {}; - var object = {}; - if (message.compositeFilter != null && message.hasOwnProperty("compositeFilter")) { - object.compositeFilter = $root.google.firestore.v1.StructuredQuery.CompositeFilter.toObject(message.compositeFilter, options); - if (options.oneofs) - object.filterType = "compositeFilter"; - } - if (message.fieldFilter != null && message.hasOwnProperty("fieldFilter")) { - object.fieldFilter = $root.google.firestore.v1.StructuredQuery.FieldFilter.toObject(message.fieldFilter, options); - if (options.oneofs) - object.filterType = "fieldFilter"; - } - if (message.unaryFilter != null && message.hasOwnProperty("unaryFilter")) { - object.unaryFilter = $root.google.firestore.v1.StructuredQuery.UnaryFilter.toObject(message.unaryFilter, options); - if (options.oneofs) - object.filterType = "unaryFilter"; - } - return object; - }; + /** + * FieldDescriptorProto extendee. + * @member {string} extendee + * @memberof google.protobuf.FieldDescriptorProto + * @instance + */ + FieldDescriptorProto.prototype.extendee = ""; - /** - * Converts this Filter to JSON. - * @function toJSON - * @memberof google.firestore.v1.StructuredQuery.Filter - * @instance - * @returns {Object.} JSON object - */ - Filter.prototype.toJSON = function toJSON() { - return this.constructor.toObject(this, $protobuf.util.toJSONOptions); - }; + /** + * FieldDescriptorProto defaultValue. + * @member {string} defaultValue + * @memberof google.protobuf.FieldDescriptorProto + * @instance + */ + FieldDescriptorProto.prototype.defaultValue = ""; - /** - * Gets the default type url for Filter - * @function getTypeUrl - * @memberof google.firestore.v1.StructuredQuery.Filter - * @static - * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") - * @returns {string} The default type url - */ - Filter.getTypeUrl = function getTypeUrl(typeUrlPrefix) { - if (typeUrlPrefix === undefined) { - typeUrlPrefix = "type.googleapis.com"; - } - return typeUrlPrefix + "/google.firestore.v1.StructuredQuery.Filter"; - }; + /** + * FieldDescriptorProto oneofIndex. + * @member {number} oneofIndex + * @memberof google.protobuf.FieldDescriptorProto + * @instance + */ + FieldDescriptorProto.prototype.oneofIndex = 0; - return Filter; - })(); + /** + * FieldDescriptorProto jsonName. + * @member {string} jsonName + * @memberof google.protobuf.FieldDescriptorProto + * @instance + */ + FieldDescriptorProto.prototype.jsonName = ""; - StructuredQuery.CompositeFilter = (function() { + /** + * FieldDescriptorProto options. + * @member {google.protobuf.IFieldOptions|null|undefined} options + * @memberof google.protobuf.FieldDescriptorProto + * @instance + */ + FieldDescriptorProto.prototype.options = null; - /** - * Properties of a CompositeFilter. - * @memberof google.firestore.v1.StructuredQuery - * @interface ICompositeFilter - * @property {google.firestore.v1.StructuredQuery.CompositeFilter.Operator|null} [op] CompositeFilter op - * @property {Array.|null} [filters] CompositeFilter filters - */ + /** + * FieldDescriptorProto proto3Optional. + * @member {boolean} proto3Optional + * @memberof google.protobuf.FieldDescriptorProto + * @instance + */ + FieldDescriptorProto.prototype.proto3Optional = false; - /** - * Constructs a new CompositeFilter. - * @memberof google.firestore.v1.StructuredQuery - * @classdesc Represents a CompositeFilter. - * @implements ICompositeFilter - * @constructor - * @param {google.firestore.v1.StructuredQuery.ICompositeFilter=} [properties] Properties to set - */ - function CompositeFilter(properties) { - this.filters = []; - if (properties) - for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) - if (properties[keys[i]] != null) - this[keys[i]] = properties[keys[i]]; + /** + * Creates a FieldDescriptorProto message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.protobuf.FieldDescriptorProto + * @static + * @param {Object.} object Plain object + * @returns {google.protobuf.FieldDescriptorProto} FieldDescriptorProto + */ + FieldDescriptorProto.fromObject = function fromObject(object) { + if (object instanceof $root.google.protobuf.FieldDescriptorProto) + return object; + var message = new $root.google.protobuf.FieldDescriptorProto(); + if (object.name != null) + message.name = String(object.name); + if (object.number != null) + message.number = object.number | 0; + switch (object.label) { + default: + if (typeof object.label === "number") { + message.label = object.label; + break; + } + break; + case "LABEL_OPTIONAL": + case 1: + message.label = 1; + break; + case "LABEL_REPEATED": + case 3: + message.label = 3; + break; + case "LABEL_REQUIRED": + case 2: + message.label = 2; + break; + } + switch (object.type) { + default: + if (typeof object.type === "number") { + message.type = object.type; + break; } + break; + case "TYPE_DOUBLE": + case 1: + message.type = 1; + break; + case "TYPE_FLOAT": + case 2: + message.type = 2; + break; + case "TYPE_INT64": + case 3: + message.type = 3; + break; + case "TYPE_UINT64": + case 4: + message.type = 4; + break; + case "TYPE_INT32": + case 5: + message.type = 5; + break; + case "TYPE_FIXED64": + case 6: + message.type = 6; + break; + case "TYPE_FIXED32": + case 7: + message.type = 7; + break; + case "TYPE_BOOL": + case 8: + message.type = 8; + break; + case "TYPE_STRING": + case 9: + message.type = 9; + break; + case "TYPE_GROUP": + case 10: + message.type = 10; + break; + case "TYPE_MESSAGE": + case 11: + message.type = 11; + break; + case "TYPE_BYTES": + case 12: + message.type = 12; + break; + case "TYPE_UINT32": + case 13: + message.type = 13; + break; + case "TYPE_ENUM": + case 14: + message.type = 14; + break; + case "TYPE_SFIXED32": + case 15: + message.type = 15; + break; + case "TYPE_SFIXED64": + case 16: + message.type = 16; + break; + case "TYPE_SINT32": + case 17: + message.type = 17; + break; + case "TYPE_SINT64": + case 18: + message.type = 18; + break; + } + if (object.typeName != null) + message.typeName = String(object.typeName); + if (object.extendee != null) + message.extendee = String(object.extendee); + if (object.defaultValue != null) + message.defaultValue = String(object.defaultValue); + if (object.oneofIndex != null) + message.oneofIndex = object.oneofIndex | 0; + if (object.jsonName != null) + message.jsonName = String(object.jsonName); + if (object.options != null) { + if (typeof object.options !== "object") + throw TypeError(".google.protobuf.FieldDescriptorProto.options: object expected"); + message.options = $root.google.protobuf.FieldOptions.fromObject(object.options); + } + if (object.proto3Optional != null) + message.proto3Optional = Boolean(object.proto3Optional); + return message; + }; + + /** + * Creates a plain object from a FieldDescriptorProto message. Also converts values to other types if specified. + * @function toObject + * @memberof google.protobuf.FieldDescriptorProto + * @static + * @param {google.protobuf.FieldDescriptorProto} message FieldDescriptorProto + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + FieldDescriptorProto.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.defaults) { + object.name = ""; + object.extendee = ""; + object.number = 0; + object.label = options.enums === String ? "LABEL_OPTIONAL" : 1; + object.type = options.enums === String ? "TYPE_DOUBLE" : 1; + object.typeName = ""; + object.defaultValue = ""; + object.options = null; + object.oneofIndex = 0; + object.jsonName = ""; + object.proto3Optional = false; + } + if (message.name != null && message.hasOwnProperty("name")) + object.name = message.name; + if (message.extendee != null && message.hasOwnProperty("extendee")) + object.extendee = message.extendee; + if (message.number != null && message.hasOwnProperty("number")) + object.number = message.number; + if (message.label != null && message.hasOwnProperty("label")) + object.label = options.enums === String ? $root.google.protobuf.FieldDescriptorProto.Label[message.label] === undefined ? message.label : $root.google.protobuf.FieldDescriptorProto.Label[message.label] : message.label; + if (message.type != null && message.hasOwnProperty("type")) + object.type = options.enums === String ? $root.google.protobuf.FieldDescriptorProto.Type[message.type] === undefined ? message.type : $root.google.protobuf.FieldDescriptorProto.Type[message.type] : message.type; + if (message.typeName != null && message.hasOwnProperty("typeName")) + object.typeName = message.typeName; + if (message.defaultValue != null && message.hasOwnProperty("defaultValue")) + object.defaultValue = message.defaultValue; + if (message.options != null && message.hasOwnProperty("options")) + object.options = $root.google.protobuf.FieldOptions.toObject(message.options, options); + if (message.oneofIndex != null && message.hasOwnProperty("oneofIndex")) + object.oneofIndex = message.oneofIndex; + if (message.jsonName != null && message.hasOwnProperty("jsonName")) + object.jsonName = message.jsonName; + if (message.proto3Optional != null && message.hasOwnProperty("proto3Optional")) + object.proto3Optional = message.proto3Optional; + return object; + }; - /** - * CompositeFilter op. - * @member {google.firestore.v1.StructuredQuery.CompositeFilter.Operator} op - * @memberof google.firestore.v1.StructuredQuery.CompositeFilter - * @instance - */ - CompositeFilter.prototype.op = 0; + /** + * Converts this FieldDescriptorProto to JSON. + * @function toJSON + * @memberof google.protobuf.FieldDescriptorProto + * @instance + * @returns {Object.} JSON object + */ + FieldDescriptorProto.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; - /** - * CompositeFilter filters. - * @member {Array.} filters - * @memberof google.firestore.v1.StructuredQuery.CompositeFilter - * @instance - */ - CompositeFilter.prototype.filters = $util.emptyArray; + /** + * Gets the default type url for FieldDescriptorProto + * @function getTypeUrl + * @memberof google.protobuf.FieldDescriptorProto + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + FieldDescriptorProto.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.protobuf.FieldDescriptorProto"; + }; - /** - * Creates a CompositeFilter message from a plain object. Also converts values to their respective internal types. - * @function fromObject - * @memberof google.firestore.v1.StructuredQuery.CompositeFilter - * @static - * @param {Object.} object Plain object - * @returns {google.firestore.v1.StructuredQuery.CompositeFilter} CompositeFilter - */ - CompositeFilter.fromObject = function fromObject(object) { - if (object instanceof $root.google.firestore.v1.StructuredQuery.CompositeFilter) - return object; - var message = new $root.google.firestore.v1.StructuredQuery.CompositeFilter(); - switch (object.op) { - default: - if (typeof object.op === "number") { - message.op = object.op; - break; - } - break; - case "OPERATOR_UNSPECIFIED": - case 0: - message.op = 0; - break; - case "AND": - case 1: - message.op = 1; - break; - case "OR": - case 2: - message.op = 2; - break; - } - if (object.filters) { - if (!Array.isArray(object.filters)) - throw TypeError(".google.firestore.v1.StructuredQuery.CompositeFilter.filters: array expected"); - message.filters = []; - for (var i = 0; i < object.filters.length; ++i) { - if (typeof object.filters[i] !== "object") - throw TypeError(".google.firestore.v1.StructuredQuery.CompositeFilter.filters: object expected"); - message.filters[i] = $root.google.firestore.v1.StructuredQuery.Filter.fromObject(object.filters[i]); - } - } - return message; - }; + /** + * Type enum. + * @name google.protobuf.FieldDescriptorProto.Type + * @enum {string} + * @property {string} TYPE_DOUBLE=TYPE_DOUBLE TYPE_DOUBLE value + * @property {string} TYPE_FLOAT=TYPE_FLOAT TYPE_FLOAT value + * @property {string} TYPE_INT64=TYPE_INT64 TYPE_INT64 value + * @property {string} TYPE_UINT64=TYPE_UINT64 TYPE_UINT64 value + * @property {string} TYPE_INT32=TYPE_INT32 TYPE_INT32 value + * @property {string} TYPE_FIXED64=TYPE_FIXED64 TYPE_FIXED64 value + * @property {string} TYPE_FIXED32=TYPE_FIXED32 TYPE_FIXED32 value + * @property {string} TYPE_BOOL=TYPE_BOOL TYPE_BOOL value + * @property {string} TYPE_STRING=TYPE_STRING TYPE_STRING value + * @property {string} TYPE_GROUP=TYPE_GROUP TYPE_GROUP value + * @property {string} TYPE_MESSAGE=TYPE_MESSAGE TYPE_MESSAGE value + * @property {string} TYPE_BYTES=TYPE_BYTES TYPE_BYTES value + * @property {string} TYPE_UINT32=TYPE_UINT32 TYPE_UINT32 value + * @property {string} TYPE_ENUM=TYPE_ENUM TYPE_ENUM value + * @property {string} TYPE_SFIXED32=TYPE_SFIXED32 TYPE_SFIXED32 value + * @property {string} TYPE_SFIXED64=TYPE_SFIXED64 TYPE_SFIXED64 value + * @property {string} TYPE_SINT32=TYPE_SINT32 TYPE_SINT32 value + * @property {string} TYPE_SINT64=TYPE_SINT64 TYPE_SINT64 value + */ + FieldDescriptorProto.Type = (function() { + var valuesById = {}, values = Object.create(valuesById); + values[valuesById[1] = "TYPE_DOUBLE"] = "TYPE_DOUBLE"; + values[valuesById[2] = "TYPE_FLOAT"] = "TYPE_FLOAT"; + values[valuesById[3] = "TYPE_INT64"] = "TYPE_INT64"; + values[valuesById[4] = "TYPE_UINT64"] = "TYPE_UINT64"; + values[valuesById[5] = "TYPE_INT32"] = "TYPE_INT32"; + values[valuesById[6] = "TYPE_FIXED64"] = "TYPE_FIXED64"; + values[valuesById[7] = "TYPE_FIXED32"] = "TYPE_FIXED32"; + values[valuesById[8] = "TYPE_BOOL"] = "TYPE_BOOL"; + values[valuesById[9] = "TYPE_STRING"] = "TYPE_STRING"; + values[valuesById[10] = "TYPE_GROUP"] = "TYPE_GROUP"; + values[valuesById[11] = "TYPE_MESSAGE"] = "TYPE_MESSAGE"; + values[valuesById[12] = "TYPE_BYTES"] = "TYPE_BYTES"; + values[valuesById[13] = "TYPE_UINT32"] = "TYPE_UINT32"; + values[valuesById[14] = "TYPE_ENUM"] = "TYPE_ENUM"; + values[valuesById[15] = "TYPE_SFIXED32"] = "TYPE_SFIXED32"; + values[valuesById[16] = "TYPE_SFIXED64"] = "TYPE_SFIXED64"; + values[valuesById[17] = "TYPE_SINT32"] = "TYPE_SINT32"; + values[valuesById[18] = "TYPE_SINT64"] = "TYPE_SINT64"; + return values; + })(); - /** - * Creates a plain object from a CompositeFilter message. Also converts values to other types if specified. - * @function toObject - * @memberof google.firestore.v1.StructuredQuery.CompositeFilter - * @static - * @param {google.firestore.v1.StructuredQuery.CompositeFilter} message CompositeFilter - * @param {$protobuf.IConversionOptions} [options] Conversion options - * @returns {Object.} Plain object - */ - CompositeFilter.toObject = function toObject(message, options) { - if (!options) - options = {}; - var object = {}; - if (options.arrays || options.defaults) - object.filters = []; - if (options.defaults) - object.op = options.enums === String ? "OPERATOR_UNSPECIFIED" : 0; - if (message.op != null && message.hasOwnProperty("op")) - object.op = options.enums === String ? $root.google.firestore.v1.StructuredQuery.CompositeFilter.Operator[message.op] === undefined ? message.op : $root.google.firestore.v1.StructuredQuery.CompositeFilter.Operator[message.op] : message.op; - if (message.filters && message.filters.length) { - object.filters = []; - for (var j = 0; j < message.filters.length; ++j) - object.filters[j] = $root.google.firestore.v1.StructuredQuery.Filter.toObject(message.filters[j], options); - } - return object; - }; + /** + * Label enum. + * @name google.protobuf.FieldDescriptorProto.Label + * @enum {string} + * @property {string} LABEL_OPTIONAL=LABEL_OPTIONAL LABEL_OPTIONAL value + * @property {string} LABEL_REPEATED=LABEL_REPEATED LABEL_REPEATED value + * @property {string} LABEL_REQUIRED=LABEL_REQUIRED LABEL_REQUIRED value + */ + FieldDescriptorProto.Label = (function() { + var valuesById = {}, values = Object.create(valuesById); + values[valuesById[1] = "LABEL_OPTIONAL"] = "LABEL_OPTIONAL"; + values[valuesById[3] = "LABEL_REPEATED"] = "LABEL_REPEATED"; + values[valuesById[2] = "LABEL_REQUIRED"] = "LABEL_REQUIRED"; + return values; + })(); - /** - * Converts this CompositeFilter to JSON. - * @function toJSON - * @memberof google.firestore.v1.StructuredQuery.CompositeFilter - * @instance - * @returns {Object.} JSON object - */ - CompositeFilter.prototype.toJSON = function toJSON() { - return this.constructor.toObject(this, $protobuf.util.toJSONOptions); - }; + return FieldDescriptorProto; + })(); - /** - * Gets the default type url for CompositeFilter - * @function getTypeUrl - * @memberof google.firestore.v1.StructuredQuery.CompositeFilter - * @static - * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") - * @returns {string} The default type url - */ - CompositeFilter.getTypeUrl = function getTypeUrl(typeUrlPrefix) { - if (typeUrlPrefix === undefined) { - typeUrlPrefix = "type.googleapis.com"; - } - return typeUrlPrefix + "/google.firestore.v1.StructuredQuery.CompositeFilter"; - }; + protobuf.OneofDescriptorProto = (function() { - /** - * Operator enum. - * @name google.firestore.v1.StructuredQuery.CompositeFilter.Operator - * @enum {string} - * @property {string} OPERATOR_UNSPECIFIED=OPERATOR_UNSPECIFIED OPERATOR_UNSPECIFIED value - * @property {string} AND=AND AND value - * @property {string} OR=OR OR value - */ - CompositeFilter.Operator = (function() { - var valuesById = {}, values = Object.create(valuesById); - values[valuesById[0] = "OPERATOR_UNSPECIFIED"] = "OPERATOR_UNSPECIFIED"; - values[valuesById[1] = "AND"] = "AND"; - values[valuesById[2] = "OR"] = "OR"; - return values; - })(); + /** + * Properties of an OneofDescriptorProto. + * @memberof google.protobuf + * @interface IOneofDescriptorProto + * @property {string|null} [name] OneofDescriptorProto name + * @property {google.protobuf.IOneofOptions|null} [options] OneofDescriptorProto options + */ - return CompositeFilter; - })(); + /** + * Constructs a new OneofDescriptorProto. + * @memberof google.protobuf + * @classdesc Represents an OneofDescriptorProto. + * @implements IOneofDescriptorProto + * @constructor + * @param {google.protobuf.IOneofDescriptorProto=} [properties] Properties to set + */ + function OneofDescriptorProto(properties) { + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } - StructuredQuery.FieldFilter = (function() { + /** + * OneofDescriptorProto name. + * @member {string} name + * @memberof google.protobuf.OneofDescriptorProto + * @instance + */ + OneofDescriptorProto.prototype.name = ""; - /** - * Properties of a FieldFilter. - * @memberof google.firestore.v1.StructuredQuery - * @interface IFieldFilter - * @property {google.firestore.v1.StructuredQuery.IFieldReference|null} [field] FieldFilter field - * @property {google.firestore.v1.StructuredQuery.FieldFilter.Operator|null} [op] FieldFilter op - * @property {google.firestore.v1.IValue|null} [value] FieldFilter value - */ + /** + * OneofDescriptorProto options. + * @member {google.protobuf.IOneofOptions|null|undefined} options + * @memberof google.protobuf.OneofDescriptorProto + * @instance + */ + OneofDescriptorProto.prototype.options = null; - /** - * Constructs a new FieldFilter. - * @memberof google.firestore.v1.StructuredQuery - * @classdesc Represents a FieldFilter. - * @implements IFieldFilter - * @constructor - * @param {google.firestore.v1.StructuredQuery.IFieldFilter=} [properties] Properties to set - */ - function FieldFilter(properties) { - if (properties) - for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) - if (properties[keys[i]] != null) - this[keys[i]] = properties[keys[i]]; - } + /** + * Creates an OneofDescriptorProto message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.protobuf.OneofDescriptorProto + * @static + * @param {Object.} object Plain object + * @returns {google.protobuf.OneofDescriptorProto} OneofDescriptorProto + */ + OneofDescriptorProto.fromObject = function fromObject(object) { + if (object instanceof $root.google.protobuf.OneofDescriptorProto) + return object; + var message = new $root.google.protobuf.OneofDescriptorProto(); + if (object.name != null) + message.name = String(object.name); + if (object.options != null) { + if (typeof object.options !== "object") + throw TypeError(".google.protobuf.OneofDescriptorProto.options: object expected"); + message.options = $root.google.protobuf.OneofOptions.fromObject(object.options); + } + return message; + }; - /** - * FieldFilter field. - * @member {google.firestore.v1.StructuredQuery.IFieldReference|null|undefined} field - * @memberof google.firestore.v1.StructuredQuery.FieldFilter - * @instance - */ - FieldFilter.prototype.field = null; + /** + * Creates a plain object from an OneofDescriptorProto message. Also converts values to other types if specified. + * @function toObject + * @memberof google.protobuf.OneofDescriptorProto + * @static + * @param {google.protobuf.OneofDescriptorProto} message OneofDescriptorProto + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + OneofDescriptorProto.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.defaults) { + object.name = ""; + object.options = null; + } + if (message.name != null && message.hasOwnProperty("name")) + object.name = message.name; + if (message.options != null && message.hasOwnProperty("options")) + object.options = $root.google.protobuf.OneofOptions.toObject(message.options, options); + return object; + }; - /** - * FieldFilter op. - * @member {google.firestore.v1.StructuredQuery.FieldFilter.Operator} op - * @memberof google.firestore.v1.StructuredQuery.FieldFilter - * @instance - */ - FieldFilter.prototype.op = 0; + /** + * Converts this OneofDescriptorProto to JSON. + * @function toJSON + * @memberof google.protobuf.OneofDescriptorProto + * @instance + * @returns {Object.} JSON object + */ + OneofDescriptorProto.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; - /** - * FieldFilter value. - * @member {google.firestore.v1.IValue|null|undefined} value - * @memberof google.firestore.v1.StructuredQuery.FieldFilter - * @instance - */ - FieldFilter.prototype.value = null; + /** + * Gets the default type url for OneofDescriptorProto + * @function getTypeUrl + * @memberof google.protobuf.OneofDescriptorProto + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + OneofDescriptorProto.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.protobuf.OneofDescriptorProto"; + }; - /** - * Creates a FieldFilter message from a plain object. Also converts values to their respective internal types. - * @function fromObject - * @memberof google.firestore.v1.StructuredQuery.FieldFilter - * @static - * @param {Object.} object Plain object - * @returns {google.firestore.v1.StructuredQuery.FieldFilter} FieldFilter - */ - FieldFilter.fromObject = function fromObject(object) { - if (object instanceof $root.google.firestore.v1.StructuredQuery.FieldFilter) - return object; - var message = new $root.google.firestore.v1.StructuredQuery.FieldFilter(); - if (object.field != null) { - if (typeof object.field !== "object") - throw TypeError(".google.firestore.v1.StructuredQuery.FieldFilter.field: object expected"); - message.field = $root.google.firestore.v1.StructuredQuery.FieldReference.fromObject(object.field); - } - switch (object.op) { - default: - if (typeof object.op === "number") { - message.op = object.op; - break; - } - break; - case "OPERATOR_UNSPECIFIED": - case 0: - message.op = 0; - break; - case "LESS_THAN": - case 1: - message.op = 1; - break; - case "LESS_THAN_OR_EQUAL": - case 2: - message.op = 2; - break; - case "GREATER_THAN": - case 3: - message.op = 3; - break; - case "GREATER_THAN_OR_EQUAL": - case 4: - message.op = 4; - break; - case "EQUAL": - case 5: - message.op = 5; - break; - case "NOT_EQUAL": - case 6: - message.op = 6; - break; - case "ARRAY_CONTAINS": - case 7: - message.op = 7; - break; - case "IN": - case 8: - message.op = 8; - break; - case "ARRAY_CONTAINS_ANY": - case 9: - message.op = 9; - break; - case "NOT_IN": - case 10: - message.op = 10; - break; - } - if (object.value != null) { - if (typeof object.value !== "object") - throw TypeError(".google.firestore.v1.StructuredQuery.FieldFilter.value: object expected"); - message.value = $root.google.firestore.v1.Value.fromObject(object.value); - } - return message; - }; + return OneofDescriptorProto; + })(); - /** - * Creates a plain object from a FieldFilter message. Also converts values to other types if specified. - * @function toObject - * @memberof google.firestore.v1.StructuredQuery.FieldFilter - * @static - * @param {google.firestore.v1.StructuredQuery.FieldFilter} message FieldFilter - * @param {$protobuf.IConversionOptions} [options] Conversion options - * @returns {Object.} Plain object - */ - FieldFilter.toObject = function toObject(message, options) { - if (!options) - options = {}; - var object = {}; - if (options.defaults) { - object.field = null; - object.op = options.enums === String ? "OPERATOR_UNSPECIFIED" : 0; - object.value = null; - } - if (message.field != null && message.hasOwnProperty("field")) - object.field = $root.google.firestore.v1.StructuredQuery.FieldReference.toObject(message.field, options); - if (message.op != null && message.hasOwnProperty("op")) - object.op = options.enums === String ? $root.google.firestore.v1.StructuredQuery.FieldFilter.Operator[message.op] === undefined ? message.op : $root.google.firestore.v1.StructuredQuery.FieldFilter.Operator[message.op] : message.op; - if (message.value != null && message.hasOwnProperty("value")) - object.value = $root.google.firestore.v1.Value.toObject(message.value, options); - return object; - }; + protobuf.EnumDescriptorProto = (function() { - /** - * Converts this FieldFilter to JSON. - * @function toJSON - * @memberof google.firestore.v1.StructuredQuery.FieldFilter - * @instance - * @returns {Object.} JSON object - */ - FieldFilter.prototype.toJSON = function toJSON() { - return this.constructor.toObject(this, $protobuf.util.toJSONOptions); - }; + /** + * Properties of an EnumDescriptorProto. + * @memberof google.protobuf + * @interface IEnumDescriptorProto + * @property {string|null} [name] EnumDescriptorProto name + * @property {Array.|null} [value] EnumDescriptorProto value + * @property {google.protobuf.IEnumOptions|null} [options] EnumDescriptorProto options + * @property {Array.|null} [reservedRange] EnumDescriptorProto reservedRange + * @property {Array.|null} [reservedName] EnumDescriptorProto reservedName + */ - /** - * Gets the default type url for FieldFilter - * @function getTypeUrl - * @memberof google.firestore.v1.StructuredQuery.FieldFilter - * @static - * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") - * @returns {string} The default type url - */ - FieldFilter.getTypeUrl = function getTypeUrl(typeUrlPrefix) { - if (typeUrlPrefix === undefined) { - typeUrlPrefix = "type.googleapis.com"; - } - return typeUrlPrefix + "/google.firestore.v1.StructuredQuery.FieldFilter"; - }; + /** + * Constructs a new EnumDescriptorProto. + * @memberof google.protobuf + * @classdesc Represents an EnumDescriptorProto. + * @implements IEnumDescriptorProto + * @constructor + * @param {google.protobuf.IEnumDescriptorProto=} [properties] Properties to set + */ + function EnumDescriptorProto(properties) { + this.value = []; + this.reservedRange = []; + this.reservedName = []; + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } - /** - * Operator enum. - * @name google.firestore.v1.StructuredQuery.FieldFilter.Operator - * @enum {string} - * @property {string} OPERATOR_UNSPECIFIED=OPERATOR_UNSPECIFIED OPERATOR_UNSPECIFIED value - * @property {string} LESS_THAN=LESS_THAN LESS_THAN value - * @property {string} LESS_THAN_OR_EQUAL=LESS_THAN_OR_EQUAL LESS_THAN_OR_EQUAL value - * @property {string} GREATER_THAN=GREATER_THAN GREATER_THAN value - * @property {string} GREATER_THAN_OR_EQUAL=GREATER_THAN_OR_EQUAL GREATER_THAN_OR_EQUAL value - * @property {string} EQUAL=EQUAL EQUAL value - * @property {string} NOT_EQUAL=NOT_EQUAL NOT_EQUAL value - * @property {string} ARRAY_CONTAINS=ARRAY_CONTAINS ARRAY_CONTAINS value - * @property {string} IN=IN IN value - * @property {string} ARRAY_CONTAINS_ANY=ARRAY_CONTAINS_ANY ARRAY_CONTAINS_ANY value - * @property {string} NOT_IN=NOT_IN NOT_IN value - */ - FieldFilter.Operator = (function() { - var valuesById = {}, values = Object.create(valuesById); - values[valuesById[0] = "OPERATOR_UNSPECIFIED"] = "OPERATOR_UNSPECIFIED"; - values[valuesById[1] = "LESS_THAN"] = "LESS_THAN"; - values[valuesById[2] = "LESS_THAN_OR_EQUAL"] = "LESS_THAN_OR_EQUAL"; - values[valuesById[3] = "GREATER_THAN"] = "GREATER_THAN"; - values[valuesById[4] = "GREATER_THAN_OR_EQUAL"] = "GREATER_THAN_OR_EQUAL"; - values[valuesById[5] = "EQUAL"] = "EQUAL"; - values[valuesById[6] = "NOT_EQUAL"] = "NOT_EQUAL"; - values[valuesById[7] = "ARRAY_CONTAINS"] = "ARRAY_CONTAINS"; - values[valuesById[8] = "IN"] = "IN"; - values[valuesById[9] = "ARRAY_CONTAINS_ANY"] = "ARRAY_CONTAINS_ANY"; - values[valuesById[10] = "NOT_IN"] = "NOT_IN"; - return values; - })(); + /** + * EnumDescriptorProto name. + * @member {string} name + * @memberof google.protobuf.EnumDescriptorProto + * @instance + */ + EnumDescriptorProto.prototype.name = ""; - return FieldFilter; - })(); + /** + * EnumDescriptorProto value. + * @member {Array.} value + * @memberof google.protobuf.EnumDescriptorProto + * @instance + */ + EnumDescriptorProto.prototype.value = $util.emptyArray; - StructuredQuery.UnaryFilter = (function() { + /** + * EnumDescriptorProto options. + * @member {google.protobuf.IEnumOptions|null|undefined} options + * @memberof google.protobuf.EnumDescriptorProto + * @instance + */ + EnumDescriptorProto.prototype.options = null; - /** - * Properties of an UnaryFilter. - * @memberof google.firestore.v1.StructuredQuery - * @interface IUnaryFilter - * @property {google.firestore.v1.StructuredQuery.UnaryFilter.Operator|null} [op] UnaryFilter op - * @property {google.firestore.v1.StructuredQuery.IFieldReference|null} [field] UnaryFilter field - */ + /** + * EnumDescriptorProto reservedRange. + * @member {Array.} reservedRange + * @memberof google.protobuf.EnumDescriptorProto + * @instance + */ + EnumDescriptorProto.prototype.reservedRange = $util.emptyArray; - /** - * Constructs a new UnaryFilter. - * @memberof google.firestore.v1.StructuredQuery - * @classdesc Represents an UnaryFilter. - * @implements IUnaryFilter - * @constructor - * @param {google.firestore.v1.StructuredQuery.IUnaryFilter=} [properties] Properties to set - */ - function UnaryFilter(properties) { - if (properties) - for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) - if (properties[keys[i]] != null) - this[keys[i]] = properties[keys[i]]; + /** + * EnumDescriptorProto reservedName. + * @member {Array.} reservedName + * @memberof google.protobuf.EnumDescriptorProto + * @instance + */ + EnumDescriptorProto.prototype.reservedName = $util.emptyArray; + + /** + * Creates an EnumDescriptorProto message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.protobuf.EnumDescriptorProto + * @static + * @param {Object.} object Plain object + * @returns {google.protobuf.EnumDescriptorProto} EnumDescriptorProto + */ + EnumDescriptorProto.fromObject = function fromObject(object) { + if (object instanceof $root.google.protobuf.EnumDescriptorProto) + return object; + var message = new $root.google.protobuf.EnumDescriptorProto(); + if (object.name != null) + message.name = String(object.name); + if (object.value) { + if (!Array.isArray(object.value)) + throw TypeError(".google.protobuf.EnumDescriptorProto.value: array expected"); + message.value = []; + for (var i = 0; i < object.value.length; ++i) { + if (typeof object.value[i] !== "object") + throw TypeError(".google.protobuf.EnumDescriptorProto.value: object expected"); + message.value[i] = $root.google.protobuf.EnumValueDescriptorProto.fromObject(object.value[i]); + } + } + if (object.options != null) { + if (typeof object.options !== "object") + throw TypeError(".google.protobuf.EnumDescriptorProto.options: object expected"); + message.options = $root.google.protobuf.EnumOptions.fromObject(object.options); + } + if (object.reservedRange) { + if (!Array.isArray(object.reservedRange)) + throw TypeError(".google.protobuf.EnumDescriptorProto.reservedRange: array expected"); + message.reservedRange = []; + for (var i = 0; i < object.reservedRange.length; ++i) { + if (typeof object.reservedRange[i] !== "object") + throw TypeError(".google.protobuf.EnumDescriptorProto.reservedRange: object expected"); + message.reservedRange[i] = $root.google.protobuf.EnumDescriptorProto.EnumReservedRange.fromObject(object.reservedRange[i]); } + } + if (object.reservedName) { + if (!Array.isArray(object.reservedName)) + throw TypeError(".google.protobuf.EnumDescriptorProto.reservedName: array expected"); + message.reservedName = []; + for (var i = 0; i < object.reservedName.length; ++i) + message.reservedName[i] = String(object.reservedName[i]); + } + return message; + }; - /** - * UnaryFilter op. - * @member {google.firestore.v1.StructuredQuery.UnaryFilter.Operator} op - * @memberof google.firestore.v1.StructuredQuery.UnaryFilter - * @instance - */ - UnaryFilter.prototype.op = 0; + /** + * Creates a plain object from an EnumDescriptorProto message. Also converts values to other types if specified. + * @function toObject + * @memberof google.protobuf.EnumDescriptorProto + * @static + * @param {google.protobuf.EnumDescriptorProto} message EnumDescriptorProto + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + EnumDescriptorProto.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.arrays || options.defaults) { + object.value = []; + object.reservedRange = []; + object.reservedName = []; + } + if (options.defaults) { + object.name = ""; + object.options = null; + } + if (message.name != null && message.hasOwnProperty("name")) + object.name = message.name; + if (message.value && message.value.length) { + object.value = []; + for (var j = 0; j < message.value.length; ++j) + object.value[j] = $root.google.protobuf.EnumValueDescriptorProto.toObject(message.value[j], options); + } + if (message.options != null && message.hasOwnProperty("options")) + object.options = $root.google.protobuf.EnumOptions.toObject(message.options, options); + if (message.reservedRange && message.reservedRange.length) { + object.reservedRange = []; + for (var j = 0; j < message.reservedRange.length; ++j) + object.reservedRange[j] = $root.google.protobuf.EnumDescriptorProto.EnumReservedRange.toObject(message.reservedRange[j], options); + } + if (message.reservedName && message.reservedName.length) { + object.reservedName = []; + for (var j = 0; j < message.reservedName.length; ++j) + object.reservedName[j] = message.reservedName[j]; + } + return object; + }; - /** - * UnaryFilter field. - * @member {google.firestore.v1.StructuredQuery.IFieldReference|null|undefined} field - * @memberof google.firestore.v1.StructuredQuery.UnaryFilter - * @instance - */ - UnaryFilter.prototype.field = null; + /** + * Converts this EnumDescriptorProto to JSON. + * @function toJSON + * @memberof google.protobuf.EnumDescriptorProto + * @instance + * @returns {Object.} JSON object + */ + EnumDescriptorProto.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; - // OneOf field names bound to virtual getters and setters - var $oneOfFields; + /** + * Gets the default type url for EnumDescriptorProto + * @function getTypeUrl + * @memberof google.protobuf.EnumDescriptorProto + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + EnumDescriptorProto.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.protobuf.EnumDescriptorProto"; + }; - /** - * UnaryFilter operandType. - * @member {"field"|undefined} operandType - * @memberof google.firestore.v1.StructuredQuery.UnaryFilter - * @instance - */ - Object.defineProperty(UnaryFilter.prototype, "operandType", { - get: $util.oneOfGetter($oneOfFields = ["field"]), - set: $util.oneOfSetter($oneOfFields) - }); + EnumDescriptorProto.EnumReservedRange = (function() { + + /** + * Properties of an EnumReservedRange. + * @memberof google.protobuf.EnumDescriptorProto + * @interface IEnumReservedRange + * @property {number|null} [start] EnumReservedRange start + * @property {number|null} [end] EnumReservedRange end + */ + + /** + * Constructs a new EnumReservedRange. + * @memberof google.protobuf.EnumDescriptorProto + * @classdesc Represents an EnumReservedRange. + * @implements IEnumReservedRange + * @constructor + * @param {google.protobuf.EnumDescriptorProto.IEnumReservedRange=} [properties] Properties to set + */ + function EnumReservedRange(properties) { + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } - /** - * Creates an UnaryFilter message from a plain object. Also converts values to their respective internal types. - * @function fromObject - * @memberof google.firestore.v1.StructuredQuery.UnaryFilter - * @static - * @param {Object.} object Plain object - * @returns {google.firestore.v1.StructuredQuery.UnaryFilter} UnaryFilter - */ - UnaryFilter.fromObject = function fromObject(object) { - if (object instanceof $root.google.firestore.v1.StructuredQuery.UnaryFilter) - return object; - var message = new $root.google.firestore.v1.StructuredQuery.UnaryFilter(); - switch (object.op) { - default: - if (typeof object.op === "number") { - message.op = object.op; - break; - } - break; - case "OPERATOR_UNSPECIFIED": - case 0: - message.op = 0; - break; - case "IS_NAN": - case 2: - message.op = 2; - break; - case "IS_NULL": - case 3: - message.op = 3; - break; - case "IS_NOT_NAN": - case 4: - message.op = 4; - break; - case "IS_NOT_NULL": - case 5: - message.op = 5; - break; - } - if (object.field != null) { - if (typeof object.field !== "object") - throw TypeError(".google.firestore.v1.StructuredQuery.UnaryFilter.field: object expected"); - message.field = $root.google.firestore.v1.StructuredQuery.FieldReference.fromObject(object.field); - } - return message; - }; + /** + * EnumReservedRange start. + * @member {number} start + * @memberof google.protobuf.EnumDescriptorProto.EnumReservedRange + * @instance + */ + EnumReservedRange.prototype.start = 0; - /** - * Creates a plain object from an UnaryFilter message. Also converts values to other types if specified. - * @function toObject - * @memberof google.firestore.v1.StructuredQuery.UnaryFilter - * @static - * @param {google.firestore.v1.StructuredQuery.UnaryFilter} message UnaryFilter - * @param {$protobuf.IConversionOptions} [options] Conversion options - * @returns {Object.} Plain object - */ - UnaryFilter.toObject = function toObject(message, options) { - if (!options) - options = {}; - var object = {}; - if (options.defaults) - object.op = options.enums === String ? "OPERATOR_UNSPECIFIED" : 0; - if (message.op != null && message.hasOwnProperty("op")) - object.op = options.enums === String ? $root.google.firestore.v1.StructuredQuery.UnaryFilter.Operator[message.op] === undefined ? message.op : $root.google.firestore.v1.StructuredQuery.UnaryFilter.Operator[message.op] : message.op; - if (message.field != null && message.hasOwnProperty("field")) { - object.field = $root.google.firestore.v1.StructuredQuery.FieldReference.toObject(message.field, options); - if (options.oneofs) - object.operandType = "field"; - } + /** + * EnumReservedRange end. + * @member {number} end + * @memberof google.protobuf.EnumDescriptorProto.EnumReservedRange + * @instance + */ + EnumReservedRange.prototype.end = 0; + + /** + * Creates an EnumReservedRange message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.protobuf.EnumDescriptorProto.EnumReservedRange + * @static + * @param {Object.} object Plain object + * @returns {google.protobuf.EnumDescriptorProto.EnumReservedRange} EnumReservedRange + */ + EnumReservedRange.fromObject = function fromObject(object) { + if (object instanceof $root.google.protobuf.EnumDescriptorProto.EnumReservedRange) return object; - }; + var message = new $root.google.protobuf.EnumDescriptorProto.EnumReservedRange(); + if (object.start != null) + message.start = object.start | 0; + if (object.end != null) + message.end = object.end | 0; + return message; + }; - /** - * Converts this UnaryFilter to JSON. - * @function toJSON - * @memberof google.firestore.v1.StructuredQuery.UnaryFilter - * @instance - * @returns {Object.} JSON object - */ - UnaryFilter.prototype.toJSON = function toJSON() { - return this.constructor.toObject(this, $protobuf.util.toJSONOptions); - }; + /** + * Creates a plain object from an EnumReservedRange message. Also converts values to other types if specified. + * @function toObject + * @memberof google.protobuf.EnumDescriptorProto.EnumReservedRange + * @static + * @param {google.protobuf.EnumDescriptorProto.EnumReservedRange} message EnumReservedRange + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + EnumReservedRange.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.defaults) { + object.start = 0; + object.end = 0; + } + if (message.start != null && message.hasOwnProperty("start")) + object.start = message.start; + if (message.end != null && message.hasOwnProperty("end")) + object.end = message.end; + return object; + }; - /** - * Gets the default type url for UnaryFilter - * @function getTypeUrl - * @memberof google.firestore.v1.StructuredQuery.UnaryFilter - * @static - * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") - * @returns {string} The default type url - */ - UnaryFilter.getTypeUrl = function getTypeUrl(typeUrlPrefix) { - if (typeUrlPrefix === undefined) { - typeUrlPrefix = "type.googleapis.com"; - } - return typeUrlPrefix + "/google.firestore.v1.StructuredQuery.UnaryFilter"; - }; + /** + * Converts this EnumReservedRange to JSON. + * @function toJSON + * @memberof google.protobuf.EnumDescriptorProto.EnumReservedRange + * @instance + * @returns {Object.} JSON object + */ + EnumReservedRange.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; - /** - * Operator enum. - * @name google.firestore.v1.StructuredQuery.UnaryFilter.Operator - * @enum {string} - * @property {string} OPERATOR_UNSPECIFIED=OPERATOR_UNSPECIFIED OPERATOR_UNSPECIFIED value - * @property {string} IS_NAN=IS_NAN IS_NAN value - * @property {string} IS_NULL=IS_NULL IS_NULL value - * @property {string} IS_NOT_NAN=IS_NOT_NAN IS_NOT_NAN value - * @property {string} IS_NOT_NULL=IS_NOT_NULL IS_NOT_NULL value - */ - UnaryFilter.Operator = (function() { - var valuesById = {}, values = Object.create(valuesById); - values[valuesById[0] = "OPERATOR_UNSPECIFIED"] = "OPERATOR_UNSPECIFIED"; - values[valuesById[2] = "IS_NAN"] = "IS_NAN"; - values[valuesById[3] = "IS_NULL"] = "IS_NULL"; - values[valuesById[4] = "IS_NOT_NAN"] = "IS_NOT_NAN"; - values[valuesById[5] = "IS_NOT_NULL"] = "IS_NOT_NULL"; - return values; - })(); + /** + * Gets the default type url for EnumReservedRange + * @function getTypeUrl + * @memberof google.protobuf.EnumDescriptorProto.EnumReservedRange + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + EnumReservedRange.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.protobuf.EnumDescriptorProto.EnumReservedRange"; + }; - return UnaryFilter; - })(); + return EnumReservedRange; + })(); - StructuredQuery.Order = (function() { + return EnumDescriptorProto; + })(); - /** - * Properties of an Order. - * @memberof google.firestore.v1.StructuredQuery - * @interface IOrder - * @property {google.firestore.v1.StructuredQuery.IFieldReference|null} [field] Order field - * @property {google.firestore.v1.StructuredQuery.Direction|null} [direction] Order direction - */ + protobuf.EnumValueDescriptorProto = (function() { - /** - * Constructs a new Order. - * @memberof google.firestore.v1.StructuredQuery - * @classdesc Represents an Order. - * @implements IOrder - * @constructor - * @param {google.firestore.v1.StructuredQuery.IOrder=} [properties] Properties to set - */ - function Order(properties) { - if (properties) - for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) - if (properties[keys[i]] != null) - this[keys[i]] = properties[keys[i]]; - } + /** + * Properties of an EnumValueDescriptorProto. + * @memberof google.protobuf + * @interface IEnumValueDescriptorProto + * @property {string|null} [name] EnumValueDescriptorProto name + * @property {number|null} [number] EnumValueDescriptorProto number + * @property {google.protobuf.IEnumValueOptions|null} [options] EnumValueDescriptorProto options + */ - /** - * Order field. - * @member {google.firestore.v1.StructuredQuery.IFieldReference|null|undefined} field - * @memberof google.firestore.v1.StructuredQuery.Order - * @instance - */ - Order.prototype.field = null; + /** + * Constructs a new EnumValueDescriptorProto. + * @memberof google.protobuf + * @classdesc Represents an EnumValueDescriptorProto. + * @implements IEnumValueDescriptorProto + * @constructor + * @param {google.protobuf.IEnumValueDescriptorProto=} [properties] Properties to set + */ + function EnumValueDescriptorProto(properties) { + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } + + /** + * EnumValueDescriptorProto name. + * @member {string} name + * @memberof google.protobuf.EnumValueDescriptorProto + * @instance + */ + EnumValueDescriptorProto.prototype.name = ""; - /** - * Order direction. - * @member {google.firestore.v1.StructuredQuery.Direction} direction - * @memberof google.firestore.v1.StructuredQuery.Order - * @instance - */ - Order.prototype.direction = 0; + /** + * EnumValueDescriptorProto number. + * @member {number} number + * @memberof google.protobuf.EnumValueDescriptorProto + * @instance + */ + EnumValueDescriptorProto.prototype.number = 0; - /** - * Creates an Order message from a plain object. Also converts values to their respective internal types. - * @function fromObject - * @memberof google.firestore.v1.StructuredQuery.Order - * @static - * @param {Object.} object Plain object - * @returns {google.firestore.v1.StructuredQuery.Order} Order - */ - Order.fromObject = function fromObject(object) { - if (object instanceof $root.google.firestore.v1.StructuredQuery.Order) - return object; - var message = new $root.google.firestore.v1.StructuredQuery.Order(); - if (object.field != null) { - if (typeof object.field !== "object") - throw TypeError(".google.firestore.v1.StructuredQuery.Order.field: object expected"); - message.field = $root.google.firestore.v1.StructuredQuery.FieldReference.fromObject(object.field); - } - switch (object.direction) { - default: - if (typeof object.direction === "number") { - message.direction = object.direction; - break; - } - break; - case "DIRECTION_UNSPECIFIED": - case 0: - message.direction = 0; - break; - case "ASCENDING": - case 1: - message.direction = 1; - break; - case "DESCENDING": - case 2: - message.direction = 2; - break; - } - return message; - }; + /** + * EnumValueDescriptorProto options. + * @member {google.protobuf.IEnumValueOptions|null|undefined} options + * @memberof google.protobuf.EnumValueDescriptorProto + * @instance + */ + EnumValueDescriptorProto.prototype.options = null; - /** - * Creates a plain object from an Order message. Also converts values to other types if specified. - * @function toObject - * @memberof google.firestore.v1.StructuredQuery.Order - * @static - * @param {google.firestore.v1.StructuredQuery.Order} message Order - * @param {$protobuf.IConversionOptions} [options] Conversion options - * @returns {Object.} Plain object - */ - Order.toObject = function toObject(message, options) { - if (!options) - options = {}; - var object = {}; - if (options.defaults) { - object.field = null; - object.direction = options.enums === String ? "DIRECTION_UNSPECIFIED" : 0; - } - if (message.field != null && message.hasOwnProperty("field")) - object.field = $root.google.firestore.v1.StructuredQuery.FieldReference.toObject(message.field, options); - if (message.direction != null && message.hasOwnProperty("direction")) - object.direction = options.enums === String ? $root.google.firestore.v1.StructuredQuery.Direction[message.direction] === undefined ? message.direction : $root.google.firestore.v1.StructuredQuery.Direction[message.direction] : message.direction; - return object; - }; + /** + * Creates an EnumValueDescriptorProto message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.protobuf.EnumValueDescriptorProto + * @static + * @param {Object.} object Plain object + * @returns {google.protobuf.EnumValueDescriptorProto} EnumValueDescriptorProto + */ + EnumValueDescriptorProto.fromObject = function fromObject(object) { + if (object instanceof $root.google.protobuf.EnumValueDescriptorProto) + return object; + var message = new $root.google.protobuf.EnumValueDescriptorProto(); + if (object.name != null) + message.name = String(object.name); + if (object.number != null) + message.number = object.number | 0; + if (object.options != null) { + if (typeof object.options !== "object") + throw TypeError(".google.protobuf.EnumValueDescriptorProto.options: object expected"); + message.options = $root.google.protobuf.EnumValueOptions.fromObject(object.options); + } + return message; + }; - /** - * Converts this Order to JSON. - * @function toJSON - * @memberof google.firestore.v1.StructuredQuery.Order - * @instance - * @returns {Object.} JSON object - */ - Order.prototype.toJSON = function toJSON() { - return this.constructor.toObject(this, $protobuf.util.toJSONOptions); - }; + /** + * Creates a plain object from an EnumValueDescriptorProto message. Also converts values to other types if specified. + * @function toObject + * @memberof google.protobuf.EnumValueDescriptorProto + * @static + * @param {google.protobuf.EnumValueDescriptorProto} message EnumValueDescriptorProto + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + EnumValueDescriptorProto.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.defaults) { + object.name = ""; + object.number = 0; + object.options = null; + } + if (message.name != null && message.hasOwnProperty("name")) + object.name = message.name; + if (message.number != null && message.hasOwnProperty("number")) + object.number = message.number; + if (message.options != null && message.hasOwnProperty("options")) + object.options = $root.google.protobuf.EnumValueOptions.toObject(message.options, options); + return object; + }; - /** - * Gets the default type url for Order - * @function getTypeUrl - * @memberof google.firestore.v1.StructuredQuery.Order - * @static - * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") - * @returns {string} The default type url - */ - Order.getTypeUrl = function getTypeUrl(typeUrlPrefix) { - if (typeUrlPrefix === undefined) { - typeUrlPrefix = "type.googleapis.com"; - } - return typeUrlPrefix + "/google.firestore.v1.StructuredQuery.Order"; - }; + /** + * Converts this EnumValueDescriptorProto to JSON. + * @function toJSON + * @memberof google.protobuf.EnumValueDescriptorProto + * @instance + * @returns {Object.} JSON object + */ + EnumValueDescriptorProto.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; - return Order; - })(); + /** + * Gets the default type url for EnumValueDescriptorProto + * @function getTypeUrl + * @memberof google.protobuf.EnumValueDescriptorProto + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + EnumValueDescriptorProto.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.protobuf.EnumValueDescriptorProto"; + }; - /** - * Direction enum. - * @name google.firestore.v1.StructuredQuery.Direction - * @enum {string} - * @property {string} DIRECTION_UNSPECIFIED=DIRECTION_UNSPECIFIED DIRECTION_UNSPECIFIED value - * @property {string} ASCENDING=ASCENDING ASCENDING value - * @property {string} DESCENDING=DESCENDING DESCENDING value - */ - StructuredQuery.Direction = (function() { - var valuesById = {}, values = Object.create(valuesById); - values[valuesById[0] = "DIRECTION_UNSPECIFIED"] = "DIRECTION_UNSPECIFIED"; - values[valuesById[1] = "ASCENDING"] = "ASCENDING"; - values[valuesById[2] = "DESCENDING"] = "DESCENDING"; - return values; - })(); + return EnumValueDescriptorProto; + })(); - StructuredQuery.FieldReference = (function() { + protobuf.ServiceDescriptorProto = (function() { - /** - * Properties of a FieldReference. - * @memberof google.firestore.v1.StructuredQuery - * @interface IFieldReference - * @property {string|null} [fieldPath] FieldReference fieldPath - */ + /** + * Properties of a ServiceDescriptorProto. + * @memberof google.protobuf + * @interface IServiceDescriptorProto + * @property {string|null} [name] ServiceDescriptorProto name + * @property {Array.|null} [method] ServiceDescriptorProto method + * @property {google.protobuf.IServiceOptions|null} [options] ServiceDescriptorProto options + */ - /** - * Constructs a new FieldReference. - * @memberof google.firestore.v1.StructuredQuery - * @classdesc Represents a FieldReference. - * @implements IFieldReference - * @constructor - * @param {google.firestore.v1.StructuredQuery.IFieldReference=} [properties] Properties to set - */ - function FieldReference(properties) { - if (properties) - for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) - if (properties[keys[i]] != null) - this[keys[i]] = properties[keys[i]]; - } + /** + * Constructs a new ServiceDescriptorProto. + * @memberof google.protobuf + * @classdesc Represents a ServiceDescriptorProto. + * @implements IServiceDescriptorProto + * @constructor + * @param {google.protobuf.IServiceDescriptorProto=} [properties] Properties to set + */ + function ServiceDescriptorProto(properties) { + this.method = []; + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } + + /** + * ServiceDescriptorProto name. + * @member {string} name + * @memberof google.protobuf.ServiceDescriptorProto + * @instance + */ + ServiceDescriptorProto.prototype.name = ""; - /** - * FieldReference fieldPath. - * @member {string} fieldPath - * @memberof google.firestore.v1.StructuredQuery.FieldReference - * @instance - */ - FieldReference.prototype.fieldPath = ""; + /** + * ServiceDescriptorProto method. + * @member {Array.} method + * @memberof google.protobuf.ServiceDescriptorProto + * @instance + */ + ServiceDescriptorProto.prototype.method = $util.emptyArray; - /** - * Creates a FieldReference message from a plain object. Also converts values to their respective internal types. - * @function fromObject - * @memberof google.firestore.v1.StructuredQuery.FieldReference - * @static - * @param {Object.} object Plain object - * @returns {google.firestore.v1.StructuredQuery.FieldReference} FieldReference - */ - FieldReference.fromObject = function fromObject(object) { - if (object instanceof $root.google.firestore.v1.StructuredQuery.FieldReference) - return object; - var message = new $root.google.firestore.v1.StructuredQuery.FieldReference(); - if (object.fieldPath != null) - message.fieldPath = String(object.fieldPath); - return message; - }; + /** + * ServiceDescriptorProto options. + * @member {google.protobuf.IServiceOptions|null|undefined} options + * @memberof google.protobuf.ServiceDescriptorProto + * @instance + */ + ServiceDescriptorProto.prototype.options = null; - /** - * Creates a plain object from a FieldReference message. Also converts values to other types if specified. - * @function toObject - * @memberof google.firestore.v1.StructuredQuery.FieldReference - * @static - * @param {google.firestore.v1.StructuredQuery.FieldReference} message FieldReference - * @param {$protobuf.IConversionOptions} [options] Conversion options - * @returns {Object.} Plain object - */ - FieldReference.toObject = function toObject(message, options) { - if (!options) - options = {}; - var object = {}; - if (options.defaults) - object.fieldPath = ""; - if (message.fieldPath != null && message.hasOwnProperty("fieldPath")) - object.fieldPath = message.fieldPath; - return object; - }; + /** + * Creates a ServiceDescriptorProto message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.protobuf.ServiceDescriptorProto + * @static + * @param {Object.} object Plain object + * @returns {google.protobuf.ServiceDescriptorProto} ServiceDescriptorProto + */ + ServiceDescriptorProto.fromObject = function fromObject(object) { + if (object instanceof $root.google.protobuf.ServiceDescriptorProto) + return object; + var message = new $root.google.protobuf.ServiceDescriptorProto(); + if (object.name != null) + message.name = String(object.name); + if (object.method) { + if (!Array.isArray(object.method)) + throw TypeError(".google.protobuf.ServiceDescriptorProto.method: array expected"); + message.method = []; + for (var i = 0; i < object.method.length; ++i) { + if (typeof object.method[i] !== "object") + throw TypeError(".google.protobuf.ServiceDescriptorProto.method: object expected"); + message.method[i] = $root.google.protobuf.MethodDescriptorProto.fromObject(object.method[i]); + } + } + if (object.options != null) { + if (typeof object.options !== "object") + throw TypeError(".google.protobuf.ServiceDescriptorProto.options: object expected"); + message.options = $root.google.protobuf.ServiceOptions.fromObject(object.options); + } + return message; + }; - /** - * Converts this FieldReference to JSON. - * @function toJSON - * @memberof google.firestore.v1.StructuredQuery.FieldReference - * @instance - * @returns {Object.} JSON object - */ - FieldReference.prototype.toJSON = function toJSON() { - return this.constructor.toObject(this, $protobuf.util.toJSONOptions); - }; + /** + * Creates a plain object from a ServiceDescriptorProto message. Also converts values to other types if specified. + * @function toObject + * @memberof google.protobuf.ServiceDescriptorProto + * @static + * @param {google.protobuf.ServiceDescriptorProto} message ServiceDescriptorProto + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + ServiceDescriptorProto.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.arrays || options.defaults) + object.method = []; + if (options.defaults) { + object.name = ""; + object.options = null; + } + if (message.name != null && message.hasOwnProperty("name")) + object.name = message.name; + if (message.method && message.method.length) { + object.method = []; + for (var j = 0; j < message.method.length; ++j) + object.method[j] = $root.google.protobuf.MethodDescriptorProto.toObject(message.method[j], options); + } + if (message.options != null && message.hasOwnProperty("options")) + object.options = $root.google.protobuf.ServiceOptions.toObject(message.options, options); + return object; + }; - /** - * Gets the default type url for FieldReference - * @function getTypeUrl - * @memberof google.firestore.v1.StructuredQuery.FieldReference - * @static - * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") - * @returns {string} The default type url - */ - FieldReference.getTypeUrl = function getTypeUrl(typeUrlPrefix) { - if (typeUrlPrefix === undefined) { - typeUrlPrefix = "type.googleapis.com"; - } - return typeUrlPrefix + "/google.firestore.v1.StructuredQuery.FieldReference"; - }; + /** + * Converts this ServiceDescriptorProto to JSON. + * @function toJSON + * @memberof google.protobuf.ServiceDescriptorProto + * @instance + * @returns {Object.} JSON object + */ + ServiceDescriptorProto.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; - return FieldReference; - })(); + /** + * Gets the default type url for ServiceDescriptorProto + * @function getTypeUrl + * @memberof google.protobuf.ServiceDescriptorProto + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + ServiceDescriptorProto.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.protobuf.ServiceDescriptorProto"; + }; - StructuredQuery.Projection = (function() { + return ServiceDescriptorProto; + })(); - /** - * Properties of a Projection. - * @memberof google.firestore.v1.StructuredQuery - * @interface IProjection - * @property {Array.|null} [fields] Projection fields - */ + protobuf.MethodDescriptorProto = (function() { - /** - * Constructs a new Projection. - * @memberof google.firestore.v1.StructuredQuery - * @classdesc Represents a Projection. - * @implements IProjection - * @constructor - * @param {google.firestore.v1.StructuredQuery.IProjection=} [properties] Properties to set - */ - function Projection(properties) { - this.fields = []; - if (properties) - for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) - if (properties[keys[i]] != null) - this[keys[i]] = properties[keys[i]]; - } + /** + * Properties of a MethodDescriptorProto. + * @memberof google.protobuf + * @interface IMethodDescriptorProto + * @property {string|null} [name] MethodDescriptorProto name + * @property {string|null} [inputType] MethodDescriptorProto inputType + * @property {string|null} [outputType] MethodDescriptorProto outputType + * @property {google.protobuf.IMethodOptions|null} [options] MethodDescriptorProto options + * @property {boolean|null} [clientStreaming] MethodDescriptorProto clientStreaming + * @property {boolean|null} [serverStreaming] MethodDescriptorProto serverStreaming + */ - /** - * Projection fields. - * @member {Array.} fields - * @memberof google.firestore.v1.StructuredQuery.Projection - * @instance - */ - Projection.prototype.fields = $util.emptyArray; + /** + * Constructs a new MethodDescriptorProto. + * @memberof google.protobuf + * @classdesc Represents a MethodDescriptorProto. + * @implements IMethodDescriptorProto + * @constructor + * @param {google.protobuf.IMethodDescriptorProto=} [properties] Properties to set + */ + function MethodDescriptorProto(properties) { + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } - /** - * Creates a Projection message from a plain object. Also converts values to their respective internal types. - * @function fromObject - * @memberof google.firestore.v1.StructuredQuery.Projection - * @static - * @param {Object.} object Plain object - * @returns {google.firestore.v1.StructuredQuery.Projection} Projection - */ - Projection.fromObject = function fromObject(object) { - if (object instanceof $root.google.firestore.v1.StructuredQuery.Projection) - return object; - var message = new $root.google.firestore.v1.StructuredQuery.Projection(); - if (object.fields) { - if (!Array.isArray(object.fields)) - throw TypeError(".google.firestore.v1.StructuredQuery.Projection.fields: array expected"); - message.fields = []; - for (var i = 0; i < object.fields.length; ++i) { - if (typeof object.fields[i] !== "object") - throw TypeError(".google.firestore.v1.StructuredQuery.Projection.fields: object expected"); - message.fields[i] = $root.google.firestore.v1.StructuredQuery.FieldReference.fromObject(object.fields[i]); - } - } - return message; - }; + /** + * MethodDescriptorProto name. + * @member {string} name + * @memberof google.protobuf.MethodDescriptorProto + * @instance + */ + MethodDescriptorProto.prototype.name = ""; - /** - * Creates a plain object from a Projection message. Also converts values to other types if specified. - * @function toObject - * @memberof google.firestore.v1.StructuredQuery.Projection - * @static - * @param {google.firestore.v1.StructuredQuery.Projection} message Projection - * @param {$protobuf.IConversionOptions} [options] Conversion options - * @returns {Object.} Plain object - */ - Projection.toObject = function toObject(message, options) { - if (!options) - options = {}; - var object = {}; - if (options.arrays || options.defaults) - object.fields = []; - if (message.fields && message.fields.length) { - object.fields = []; - for (var j = 0; j < message.fields.length; ++j) - object.fields[j] = $root.google.firestore.v1.StructuredQuery.FieldReference.toObject(message.fields[j], options); - } - return object; - }; + /** + * MethodDescriptorProto inputType. + * @member {string} inputType + * @memberof google.protobuf.MethodDescriptorProto + * @instance + */ + MethodDescriptorProto.prototype.inputType = ""; - /** - * Converts this Projection to JSON. - * @function toJSON - * @memberof google.firestore.v1.StructuredQuery.Projection - * @instance - * @returns {Object.} JSON object - */ - Projection.prototype.toJSON = function toJSON() { - return this.constructor.toObject(this, $protobuf.util.toJSONOptions); - }; + /** + * MethodDescriptorProto outputType. + * @member {string} outputType + * @memberof google.protobuf.MethodDescriptorProto + * @instance + */ + MethodDescriptorProto.prototype.outputType = ""; - /** - * Gets the default type url for Projection - * @function getTypeUrl - * @memberof google.firestore.v1.StructuredQuery.Projection - * @static - * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") - * @returns {string} The default type url - */ - Projection.getTypeUrl = function getTypeUrl(typeUrlPrefix) { - if (typeUrlPrefix === undefined) { - typeUrlPrefix = "type.googleapis.com"; - } - return typeUrlPrefix + "/google.firestore.v1.StructuredQuery.Projection"; - }; + /** + * MethodDescriptorProto options. + * @member {google.protobuf.IMethodOptions|null|undefined} options + * @memberof google.protobuf.MethodDescriptorProto + * @instance + */ + MethodDescriptorProto.prototype.options = null; - return Projection; - })(); + /** + * MethodDescriptorProto clientStreaming. + * @member {boolean} clientStreaming + * @memberof google.protobuf.MethodDescriptorProto + * @instance + */ + MethodDescriptorProto.prototype.clientStreaming = false; - StructuredQuery.FindNearest = (function() { + /** + * MethodDescriptorProto serverStreaming. + * @member {boolean} serverStreaming + * @memberof google.protobuf.MethodDescriptorProto + * @instance + */ + MethodDescriptorProto.prototype.serverStreaming = false; - /** - * Properties of a FindNearest. - * @memberof google.firestore.v1.StructuredQuery - * @interface IFindNearest - * @property {google.firestore.v1.StructuredQuery.IFieldReference|null} [vectorField] FindNearest vectorField - * @property {google.firestore.v1.IValue|null} [queryVector] FindNearest queryVector - * @property {google.firestore.v1.StructuredQuery.FindNearest.DistanceMeasure|null} [distanceMeasure] FindNearest distanceMeasure - * @property {google.protobuf.IInt32Value|null} [limit] FindNearest limit - */ + /** + * Creates a MethodDescriptorProto message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.protobuf.MethodDescriptorProto + * @static + * @param {Object.} object Plain object + * @returns {google.protobuf.MethodDescriptorProto} MethodDescriptorProto + */ + MethodDescriptorProto.fromObject = function fromObject(object) { + if (object instanceof $root.google.protobuf.MethodDescriptorProto) + return object; + var message = new $root.google.protobuf.MethodDescriptorProto(); + if (object.name != null) + message.name = String(object.name); + if (object.inputType != null) + message.inputType = String(object.inputType); + if (object.outputType != null) + message.outputType = String(object.outputType); + if (object.options != null) { + if (typeof object.options !== "object") + throw TypeError(".google.protobuf.MethodDescriptorProto.options: object expected"); + message.options = $root.google.protobuf.MethodOptions.fromObject(object.options); + } + if (object.clientStreaming != null) + message.clientStreaming = Boolean(object.clientStreaming); + if (object.serverStreaming != null) + message.serverStreaming = Boolean(object.serverStreaming); + return message; + }; - /** - * Constructs a new FindNearest. - * @memberof google.firestore.v1.StructuredQuery - * @classdesc Represents a FindNearest. - * @implements IFindNearest - * @constructor - * @param {google.firestore.v1.StructuredQuery.IFindNearest=} [properties] Properties to set - */ - function FindNearest(properties) { - if (properties) - for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) - if (properties[keys[i]] != null) - this[keys[i]] = properties[keys[i]]; - } + /** + * Creates a plain object from a MethodDescriptorProto message. Also converts values to other types if specified. + * @function toObject + * @memberof google.protobuf.MethodDescriptorProto + * @static + * @param {google.protobuf.MethodDescriptorProto} message MethodDescriptorProto + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + MethodDescriptorProto.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.defaults) { + object.name = ""; + object.inputType = ""; + object.outputType = ""; + object.options = null; + object.clientStreaming = false; + object.serverStreaming = false; + } + if (message.name != null && message.hasOwnProperty("name")) + object.name = message.name; + if (message.inputType != null && message.hasOwnProperty("inputType")) + object.inputType = message.inputType; + if (message.outputType != null && message.hasOwnProperty("outputType")) + object.outputType = message.outputType; + if (message.options != null && message.hasOwnProperty("options")) + object.options = $root.google.protobuf.MethodOptions.toObject(message.options, options); + if (message.clientStreaming != null && message.hasOwnProperty("clientStreaming")) + object.clientStreaming = message.clientStreaming; + if (message.serverStreaming != null && message.hasOwnProperty("serverStreaming")) + object.serverStreaming = message.serverStreaming; + return object; + }; - /** - * FindNearest vectorField. - * @member {google.firestore.v1.StructuredQuery.IFieldReference|null|undefined} vectorField - * @memberof google.firestore.v1.StructuredQuery.FindNearest - * @instance - */ - FindNearest.prototype.vectorField = null; + /** + * Converts this MethodDescriptorProto to JSON. + * @function toJSON + * @memberof google.protobuf.MethodDescriptorProto + * @instance + * @returns {Object.} JSON object + */ + MethodDescriptorProto.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; - /** - * FindNearest queryVector. - * @member {google.firestore.v1.IValue|null|undefined} queryVector - * @memberof google.firestore.v1.StructuredQuery.FindNearest - * @instance - */ - FindNearest.prototype.queryVector = null; + /** + * Gets the default type url for MethodDescriptorProto + * @function getTypeUrl + * @memberof google.protobuf.MethodDescriptorProto + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + MethodDescriptorProto.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.protobuf.MethodDescriptorProto"; + }; - /** - * FindNearest distanceMeasure. - * @member {google.firestore.v1.StructuredQuery.FindNearest.DistanceMeasure} distanceMeasure - * @memberof google.firestore.v1.StructuredQuery.FindNearest - * @instance - */ - FindNearest.prototype.distanceMeasure = 0; + return MethodDescriptorProto; + })(); + + protobuf.FileOptions = (function() { + + /** + * Properties of a FileOptions. + * @memberof google.protobuf + * @interface IFileOptions + * @property {string|null} [javaPackage] FileOptions javaPackage + * @property {string|null} [javaOuterClassname] FileOptions javaOuterClassname + * @property {boolean|null} [javaMultipleFiles] FileOptions javaMultipleFiles + * @property {boolean|null} [javaGenerateEqualsAndHash] FileOptions javaGenerateEqualsAndHash + * @property {boolean|null} [javaStringCheckUtf8] FileOptions javaStringCheckUtf8 + * @property {google.protobuf.FileOptions.OptimizeMode|null} [optimizeFor] FileOptions optimizeFor + * @property {string|null} [goPackage] FileOptions goPackage + * @property {boolean|null} [ccGenericServices] FileOptions ccGenericServices + * @property {boolean|null} [javaGenericServices] FileOptions javaGenericServices + * @property {boolean|null} [pyGenericServices] FileOptions pyGenericServices + * @property {boolean|null} [deprecated] FileOptions deprecated + * @property {boolean|null} [ccEnableArenas] FileOptions ccEnableArenas + * @property {string|null} [objcClassPrefix] FileOptions objcClassPrefix + * @property {string|null} [csharpNamespace] FileOptions csharpNamespace + * @property {string|null} [swiftPrefix] FileOptions swiftPrefix + * @property {string|null} [phpClassPrefix] FileOptions phpClassPrefix + * @property {string|null} [phpNamespace] FileOptions phpNamespace + * @property {string|null} [phpMetadataNamespace] FileOptions phpMetadataNamespace + * @property {string|null} [rubyPackage] FileOptions rubyPackage + * @property {google.protobuf.IFeatureSet|null} [features] FileOptions features + * @property {Array.|null} [uninterpretedOption] FileOptions uninterpretedOption + * @property {Array.|null} [".google.api.resourceDefinition"] FileOptions .google.api.resourceDefinition + */ + + /** + * Constructs a new FileOptions. + * @memberof google.protobuf + * @classdesc Represents a FileOptions. + * @implements IFileOptions + * @constructor + * @param {google.protobuf.IFileOptions=} [properties] Properties to set + */ + function FileOptions(properties) { + this.uninterpretedOption = []; + this[".google.api.resourceDefinition"] = []; + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } - /** - * FindNearest limit. - * @member {google.protobuf.IInt32Value|null|undefined} limit - * @memberof google.firestore.v1.StructuredQuery.FindNearest - * @instance - */ - FindNearest.prototype.limit = null; + /** + * FileOptions javaPackage. + * @member {string} javaPackage + * @memberof google.protobuf.FileOptions + * @instance + */ + FileOptions.prototype.javaPackage = ""; - /** - * Creates a FindNearest message from a plain object. Also converts values to their respective internal types. - * @function fromObject - * @memberof google.firestore.v1.StructuredQuery.FindNearest - * @static - * @param {Object.} object Plain object - * @returns {google.firestore.v1.StructuredQuery.FindNearest} FindNearest - */ - FindNearest.fromObject = function fromObject(object) { - if (object instanceof $root.google.firestore.v1.StructuredQuery.FindNearest) - return object; - var message = new $root.google.firestore.v1.StructuredQuery.FindNearest(); - if (object.vectorField != null) { - if (typeof object.vectorField !== "object") - throw TypeError(".google.firestore.v1.StructuredQuery.FindNearest.vectorField: object expected"); - message.vectorField = $root.google.firestore.v1.StructuredQuery.FieldReference.fromObject(object.vectorField); - } - if (object.queryVector != null) { - if (typeof object.queryVector !== "object") - throw TypeError(".google.firestore.v1.StructuredQuery.FindNearest.queryVector: object expected"); - message.queryVector = $root.google.firestore.v1.Value.fromObject(object.queryVector); - } - switch (object.distanceMeasure) { - default: - if (typeof object.distanceMeasure === "number") { - message.distanceMeasure = object.distanceMeasure; - break; - } - break; - case "DISTANCE_MEASURE_UNSPECIFIED": - case 0: - message.distanceMeasure = 0; - break; - case "EUCLIDEAN": - case 1: - message.distanceMeasure = 1; - break; - case "COSINE": - case 2: - message.distanceMeasure = 2; - break; - case "DOT_PRODUCT": - case 3: - message.distanceMeasure = 3; - break; - } - if (object.limit != null) { - if (typeof object.limit !== "object") - throw TypeError(".google.firestore.v1.StructuredQuery.FindNearest.limit: object expected"); - message.limit = $root.google.protobuf.Int32Value.fromObject(object.limit); - } - return message; - }; + /** + * FileOptions javaOuterClassname. + * @member {string} javaOuterClassname + * @memberof google.protobuf.FileOptions + * @instance + */ + FileOptions.prototype.javaOuterClassname = ""; - /** - * Creates a plain object from a FindNearest message. Also converts values to other types if specified. - * @function toObject - * @memberof google.firestore.v1.StructuredQuery.FindNearest - * @static - * @param {google.firestore.v1.StructuredQuery.FindNearest} message FindNearest - * @param {$protobuf.IConversionOptions} [options] Conversion options - * @returns {Object.} Plain object - */ - FindNearest.toObject = function toObject(message, options) { - if (!options) - options = {}; - var object = {}; - if (options.defaults) { - object.vectorField = null; - object.queryVector = null; - object.distanceMeasure = options.enums === String ? "DISTANCE_MEASURE_UNSPECIFIED" : 0; - object.limit = null; - } - if (message.vectorField != null && message.hasOwnProperty("vectorField")) - object.vectorField = $root.google.firestore.v1.StructuredQuery.FieldReference.toObject(message.vectorField, options); - if (message.queryVector != null && message.hasOwnProperty("queryVector")) - object.queryVector = $root.google.firestore.v1.Value.toObject(message.queryVector, options); - if (message.distanceMeasure != null && message.hasOwnProperty("distanceMeasure")) - object.distanceMeasure = options.enums === String ? $root.google.firestore.v1.StructuredQuery.FindNearest.DistanceMeasure[message.distanceMeasure] === undefined ? message.distanceMeasure : $root.google.firestore.v1.StructuredQuery.FindNearest.DistanceMeasure[message.distanceMeasure] : message.distanceMeasure; - if (message.limit != null && message.hasOwnProperty("limit")) - object.limit = $root.google.protobuf.Int32Value.toObject(message.limit, options); - return object; - }; + /** + * FileOptions javaMultipleFiles. + * @member {boolean} javaMultipleFiles + * @memberof google.protobuf.FileOptions + * @instance + */ + FileOptions.prototype.javaMultipleFiles = false; - /** - * Converts this FindNearest to JSON. - * @function toJSON - * @memberof google.firestore.v1.StructuredQuery.FindNearest - * @instance - * @returns {Object.} JSON object - */ - FindNearest.prototype.toJSON = function toJSON() { - return this.constructor.toObject(this, $protobuf.util.toJSONOptions); - }; + /** + * FileOptions javaGenerateEqualsAndHash. + * @member {boolean} javaGenerateEqualsAndHash + * @memberof google.protobuf.FileOptions + * @instance + */ + FileOptions.prototype.javaGenerateEqualsAndHash = false; - /** - * Gets the default type url for FindNearest - * @function getTypeUrl - * @memberof google.firestore.v1.StructuredQuery.FindNearest - * @static - * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") - * @returns {string} The default type url - */ - FindNearest.getTypeUrl = function getTypeUrl(typeUrlPrefix) { - if (typeUrlPrefix === undefined) { - typeUrlPrefix = "type.googleapis.com"; - } - return typeUrlPrefix + "/google.firestore.v1.StructuredQuery.FindNearest"; - }; + /** + * FileOptions javaStringCheckUtf8. + * @member {boolean} javaStringCheckUtf8 + * @memberof google.protobuf.FileOptions + * @instance + */ + FileOptions.prototype.javaStringCheckUtf8 = false; - /** - * DistanceMeasure enum. - * @name google.firestore.v1.StructuredQuery.FindNearest.DistanceMeasure - * @enum {string} - * @property {string} DISTANCE_MEASURE_UNSPECIFIED=DISTANCE_MEASURE_UNSPECIFIED DISTANCE_MEASURE_UNSPECIFIED value - * @property {string} EUCLIDEAN=EUCLIDEAN EUCLIDEAN value - * @property {string} COSINE=COSINE COSINE value - * @property {string} DOT_PRODUCT=DOT_PRODUCT DOT_PRODUCT value - */ - FindNearest.DistanceMeasure = (function() { - var valuesById = {}, values = Object.create(valuesById); - values[valuesById[0] = "DISTANCE_MEASURE_UNSPECIFIED"] = "DISTANCE_MEASURE_UNSPECIFIED"; - values[valuesById[1] = "EUCLIDEAN"] = "EUCLIDEAN"; - values[valuesById[2] = "COSINE"] = "COSINE"; - values[valuesById[3] = "DOT_PRODUCT"] = "DOT_PRODUCT"; - return values; - })(); + /** + * FileOptions optimizeFor. + * @member {google.protobuf.FileOptions.OptimizeMode} optimizeFor + * @memberof google.protobuf.FileOptions + * @instance + */ + FileOptions.prototype.optimizeFor = 1; - return FindNearest; - })(); + /** + * FileOptions goPackage. + * @member {string} goPackage + * @memberof google.protobuf.FileOptions + * @instance + */ + FileOptions.prototype.goPackage = ""; - return StructuredQuery; - })(); + /** + * FileOptions ccGenericServices. + * @member {boolean} ccGenericServices + * @memberof google.protobuf.FileOptions + * @instance + */ + FileOptions.prototype.ccGenericServices = false; - v1.StructuredAggregationQuery = (function() { + /** + * FileOptions javaGenericServices. + * @member {boolean} javaGenericServices + * @memberof google.protobuf.FileOptions + * @instance + */ + FileOptions.prototype.javaGenericServices = false; - /** - * Properties of a StructuredAggregationQuery. - * @memberof google.firestore.v1 - * @interface IStructuredAggregationQuery - * @property {google.firestore.v1.IStructuredQuery|null} [structuredQuery] StructuredAggregationQuery structuredQuery - * @property {Array.|null} [aggregations] StructuredAggregationQuery aggregations - */ + /** + * FileOptions pyGenericServices. + * @member {boolean} pyGenericServices + * @memberof google.protobuf.FileOptions + * @instance + */ + FileOptions.prototype.pyGenericServices = false; - /** - * Constructs a new StructuredAggregationQuery. - * @memberof google.firestore.v1 - * @classdesc Represents a StructuredAggregationQuery. - * @implements IStructuredAggregationQuery - * @constructor - * @param {google.firestore.v1.IStructuredAggregationQuery=} [properties] Properties to set - */ - function StructuredAggregationQuery(properties) { - this.aggregations = []; - if (properties) - for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) - if (properties[keys[i]] != null) - this[keys[i]] = properties[keys[i]]; - } + /** + * FileOptions deprecated. + * @member {boolean} deprecated + * @memberof google.protobuf.FileOptions + * @instance + */ + FileOptions.prototype.deprecated = false; - /** - * StructuredAggregationQuery structuredQuery. - * @member {google.firestore.v1.IStructuredQuery|null|undefined} structuredQuery - * @memberof google.firestore.v1.StructuredAggregationQuery - * @instance - */ - StructuredAggregationQuery.prototype.structuredQuery = null; + /** + * FileOptions ccEnableArenas. + * @member {boolean} ccEnableArenas + * @memberof google.protobuf.FileOptions + * @instance + */ + FileOptions.prototype.ccEnableArenas = true; - /** - * StructuredAggregationQuery aggregations. - * @member {Array.} aggregations - * @memberof google.firestore.v1.StructuredAggregationQuery - * @instance - */ - StructuredAggregationQuery.prototype.aggregations = $util.emptyArray; + /** + * FileOptions objcClassPrefix. + * @member {string} objcClassPrefix + * @memberof google.protobuf.FileOptions + * @instance + */ + FileOptions.prototype.objcClassPrefix = ""; - // OneOf field names bound to virtual getters and setters - var $oneOfFields; + /** + * FileOptions csharpNamespace. + * @member {string} csharpNamespace + * @memberof google.protobuf.FileOptions + * @instance + */ + FileOptions.prototype.csharpNamespace = ""; - /** - * StructuredAggregationQuery queryType. - * @member {"structuredQuery"|undefined} queryType - * @memberof google.firestore.v1.StructuredAggregationQuery - * @instance - */ - Object.defineProperty(StructuredAggregationQuery.prototype, "queryType", { - get: $util.oneOfGetter($oneOfFields = ["structuredQuery"]), - set: $util.oneOfSetter($oneOfFields) - }); + /** + * FileOptions swiftPrefix. + * @member {string} swiftPrefix + * @memberof google.protobuf.FileOptions + * @instance + */ + FileOptions.prototype.swiftPrefix = ""; - /** - * Creates a StructuredAggregationQuery message from a plain object. Also converts values to their respective internal types. - * @function fromObject - * @memberof google.firestore.v1.StructuredAggregationQuery - * @static - * @param {Object.} object Plain object - * @returns {google.firestore.v1.StructuredAggregationQuery} StructuredAggregationQuery - */ - StructuredAggregationQuery.fromObject = function fromObject(object) { - if (object instanceof $root.google.firestore.v1.StructuredAggregationQuery) - return object; - var message = new $root.google.firestore.v1.StructuredAggregationQuery(); - if (object.structuredQuery != null) { - if (typeof object.structuredQuery !== "object") - throw TypeError(".google.firestore.v1.StructuredAggregationQuery.structuredQuery: object expected"); - message.structuredQuery = $root.google.firestore.v1.StructuredQuery.fromObject(object.structuredQuery); - } - if (object.aggregations) { - if (!Array.isArray(object.aggregations)) - throw TypeError(".google.firestore.v1.StructuredAggregationQuery.aggregations: array expected"); - message.aggregations = []; - for (var i = 0; i < object.aggregations.length; ++i) { - if (typeof object.aggregations[i] !== "object") - throw TypeError(".google.firestore.v1.StructuredAggregationQuery.aggregations: object expected"); - message.aggregations[i] = $root.google.firestore.v1.StructuredAggregationQuery.Aggregation.fromObject(object.aggregations[i]); - } - } - return message; - }; + /** + * FileOptions phpClassPrefix. + * @member {string} phpClassPrefix + * @memberof google.protobuf.FileOptions + * @instance + */ + FileOptions.prototype.phpClassPrefix = ""; - /** - * Creates a plain object from a StructuredAggregationQuery message. Also converts values to other types if specified. - * @function toObject - * @memberof google.firestore.v1.StructuredAggregationQuery - * @static - * @param {google.firestore.v1.StructuredAggregationQuery} message StructuredAggregationQuery - * @param {$protobuf.IConversionOptions} [options] Conversion options - * @returns {Object.} Plain object - */ - StructuredAggregationQuery.toObject = function toObject(message, options) { - if (!options) - options = {}; - var object = {}; - if (options.arrays || options.defaults) - object.aggregations = []; - if (message.structuredQuery != null && message.hasOwnProperty("structuredQuery")) { - object.structuredQuery = $root.google.firestore.v1.StructuredQuery.toObject(message.structuredQuery, options); - if (options.oneofs) - object.queryType = "structuredQuery"; - } - if (message.aggregations && message.aggregations.length) { - object.aggregations = []; - for (var j = 0; j < message.aggregations.length; ++j) - object.aggregations[j] = $root.google.firestore.v1.StructuredAggregationQuery.Aggregation.toObject(message.aggregations[j], options); - } - return object; - }; + /** + * FileOptions phpNamespace. + * @member {string} phpNamespace + * @memberof google.protobuf.FileOptions + * @instance + */ + FileOptions.prototype.phpNamespace = ""; - /** - * Converts this StructuredAggregationQuery to JSON. - * @function toJSON - * @memberof google.firestore.v1.StructuredAggregationQuery - * @instance - * @returns {Object.} JSON object - */ - StructuredAggregationQuery.prototype.toJSON = function toJSON() { - return this.constructor.toObject(this, $protobuf.util.toJSONOptions); - }; + /** + * FileOptions phpMetadataNamespace. + * @member {string} phpMetadataNamespace + * @memberof google.protobuf.FileOptions + * @instance + */ + FileOptions.prototype.phpMetadataNamespace = ""; - /** - * Gets the default type url for StructuredAggregationQuery - * @function getTypeUrl - * @memberof google.firestore.v1.StructuredAggregationQuery - * @static - * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") - * @returns {string} The default type url - */ - StructuredAggregationQuery.getTypeUrl = function getTypeUrl(typeUrlPrefix) { - if (typeUrlPrefix === undefined) { - typeUrlPrefix = "type.googleapis.com"; - } - return typeUrlPrefix + "/google.firestore.v1.StructuredAggregationQuery"; - }; + /** + * FileOptions rubyPackage. + * @member {string} rubyPackage + * @memberof google.protobuf.FileOptions + * @instance + */ + FileOptions.prototype.rubyPackage = ""; - StructuredAggregationQuery.Aggregation = (function() { + /** + * FileOptions features. + * @member {google.protobuf.IFeatureSet|null|undefined} features + * @memberof google.protobuf.FileOptions + * @instance + */ + FileOptions.prototype.features = null; - /** - * Properties of an Aggregation. - * @memberof google.firestore.v1.StructuredAggregationQuery - * @interface IAggregation - * @property {google.firestore.v1.StructuredAggregationQuery.Aggregation.ICount|null} [count] Aggregation count - * @property {google.firestore.v1.StructuredAggregationQuery.Aggregation.ISum|null} [sum] Aggregation sum - * @property {google.firestore.v1.StructuredAggregationQuery.Aggregation.IAvg|null} [avg] Aggregation avg - * @property {string|null} [alias] Aggregation alias - */ + /** + * FileOptions uninterpretedOption. + * @member {Array.} uninterpretedOption + * @memberof google.protobuf.FileOptions + * @instance + */ + FileOptions.prototype.uninterpretedOption = $util.emptyArray; - /** - * Constructs a new Aggregation. - * @memberof google.firestore.v1.StructuredAggregationQuery - * @classdesc Represents an Aggregation. - * @implements IAggregation - * @constructor - * @param {google.firestore.v1.StructuredAggregationQuery.IAggregation=} [properties] Properties to set - */ - function Aggregation(properties) { - if (properties) - for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) - if (properties[keys[i]] != null) - this[keys[i]] = properties[keys[i]]; + /** + * FileOptions .google.api.resourceDefinition. + * @member {Array.} .google.api.resourceDefinition + * @memberof google.protobuf.FileOptions + * @instance + */ + FileOptions.prototype[".google.api.resourceDefinition"] = $util.emptyArray; + + /** + * Creates a FileOptions message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.protobuf.FileOptions + * @static + * @param {Object.} object Plain object + * @returns {google.protobuf.FileOptions} FileOptions + */ + FileOptions.fromObject = function fromObject(object) { + if (object instanceof $root.google.protobuf.FileOptions) + return object; + var message = new $root.google.protobuf.FileOptions(); + if (object.javaPackage != null) + message.javaPackage = String(object.javaPackage); + if (object.javaOuterClassname != null) + message.javaOuterClassname = String(object.javaOuterClassname); + if (object.javaMultipleFiles != null) + message.javaMultipleFiles = Boolean(object.javaMultipleFiles); + if (object.javaGenerateEqualsAndHash != null) + message.javaGenerateEqualsAndHash = Boolean(object.javaGenerateEqualsAndHash); + if (object.javaStringCheckUtf8 != null) + message.javaStringCheckUtf8 = Boolean(object.javaStringCheckUtf8); + switch (object.optimizeFor) { + default: + if (typeof object.optimizeFor === "number") { + message.optimizeFor = object.optimizeFor; + break; + } + break; + case "SPEED": + case 1: + message.optimizeFor = 1; + break; + case "CODE_SIZE": + case 2: + message.optimizeFor = 2; + break; + case "LITE_RUNTIME": + case 3: + message.optimizeFor = 3; + break; + } + if (object.goPackage != null) + message.goPackage = String(object.goPackage); + if (object.ccGenericServices != null) + message.ccGenericServices = Boolean(object.ccGenericServices); + if (object.javaGenericServices != null) + message.javaGenericServices = Boolean(object.javaGenericServices); + if (object.pyGenericServices != null) + message.pyGenericServices = Boolean(object.pyGenericServices); + if (object.deprecated != null) + message.deprecated = Boolean(object.deprecated); + if (object.ccEnableArenas != null) + message.ccEnableArenas = Boolean(object.ccEnableArenas); + if (object.objcClassPrefix != null) + message.objcClassPrefix = String(object.objcClassPrefix); + if (object.csharpNamespace != null) + message.csharpNamespace = String(object.csharpNamespace); + if (object.swiftPrefix != null) + message.swiftPrefix = String(object.swiftPrefix); + if (object.phpClassPrefix != null) + message.phpClassPrefix = String(object.phpClassPrefix); + if (object.phpNamespace != null) + message.phpNamespace = String(object.phpNamespace); + if (object.phpMetadataNamespace != null) + message.phpMetadataNamespace = String(object.phpMetadataNamespace); + if (object.rubyPackage != null) + message.rubyPackage = String(object.rubyPackage); + if (object.features != null) { + if (typeof object.features !== "object") + throw TypeError(".google.protobuf.FileOptions.features: object expected"); + message.features = $root.google.protobuf.FeatureSet.fromObject(object.features); + } + if (object.uninterpretedOption) { + if (!Array.isArray(object.uninterpretedOption)) + throw TypeError(".google.protobuf.FileOptions.uninterpretedOption: array expected"); + message.uninterpretedOption = []; + for (var i = 0; i < object.uninterpretedOption.length; ++i) { + if (typeof object.uninterpretedOption[i] !== "object") + throw TypeError(".google.protobuf.FileOptions.uninterpretedOption: object expected"); + message.uninterpretedOption[i] = $root.google.protobuf.UninterpretedOption.fromObject(object.uninterpretedOption[i]); } + } + if (object[".google.api.resourceDefinition"]) { + if (!Array.isArray(object[".google.api.resourceDefinition"])) + throw TypeError(".google.protobuf.FileOptions..google.api.resourceDefinition: array expected"); + message[".google.api.resourceDefinition"] = []; + for (var i = 0; i < object[".google.api.resourceDefinition"].length; ++i) { + if (typeof object[".google.api.resourceDefinition"][i] !== "object") + throw TypeError(".google.protobuf.FileOptions..google.api.resourceDefinition: object expected"); + message[".google.api.resourceDefinition"][i] = $root.google.api.ResourceDescriptor.fromObject(object[".google.api.resourceDefinition"][i]); + } + } + return message; + }; - /** - * Aggregation count. - * @member {google.firestore.v1.StructuredAggregationQuery.Aggregation.ICount|null|undefined} count - * @memberof google.firestore.v1.StructuredAggregationQuery.Aggregation - * @instance - */ - Aggregation.prototype.count = null; - - /** - * Aggregation sum. - * @member {google.firestore.v1.StructuredAggregationQuery.Aggregation.ISum|null|undefined} sum - * @memberof google.firestore.v1.StructuredAggregationQuery.Aggregation - * @instance - */ - Aggregation.prototype.sum = null; - - /** - * Aggregation avg. - * @member {google.firestore.v1.StructuredAggregationQuery.Aggregation.IAvg|null|undefined} avg - * @memberof google.firestore.v1.StructuredAggregationQuery.Aggregation - * @instance - */ - Aggregation.prototype.avg = null; - - /** - * Aggregation alias. - * @member {string} alias - * @memberof google.firestore.v1.StructuredAggregationQuery.Aggregation - * @instance - */ - Aggregation.prototype.alias = ""; - - // OneOf field names bound to virtual getters and setters - var $oneOfFields; + /** + * Creates a plain object from a FileOptions message. Also converts values to other types if specified. + * @function toObject + * @memberof google.protobuf.FileOptions + * @static + * @param {google.protobuf.FileOptions} message FileOptions + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + FileOptions.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.arrays || options.defaults) { + object.uninterpretedOption = []; + object[".google.api.resourceDefinition"] = []; + } + if (options.defaults) { + object.javaPackage = ""; + object.javaOuterClassname = ""; + object.optimizeFor = options.enums === String ? "SPEED" : 1; + object.javaMultipleFiles = false; + object.goPackage = ""; + object.ccGenericServices = false; + object.javaGenericServices = false; + object.pyGenericServices = false; + object.javaGenerateEqualsAndHash = false; + object.deprecated = false; + object.javaStringCheckUtf8 = false; + object.ccEnableArenas = true; + object.objcClassPrefix = ""; + object.csharpNamespace = ""; + object.swiftPrefix = ""; + object.phpClassPrefix = ""; + object.phpNamespace = ""; + object.phpMetadataNamespace = ""; + object.rubyPackage = ""; + object.features = null; + } + if (message.javaPackage != null && message.hasOwnProperty("javaPackage")) + object.javaPackage = message.javaPackage; + if (message.javaOuterClassname != null && message.hasOwnProperty("javaOuterClassname")) + object.javaOuterClassname = message.javaOuterClassname; + if (message.optimizeFor != null && message.hasOwnProperty("optimizeFor")) + object.optimizeFor = options.enums === String ? $root.google.protobuf.FileOptions.OptimizeMode[message.optimizeFor] === undefined ? message.optimizeFor : $root.google.protobuf.FileOptions.OptimizeMode[message.optimizeFor] : message.optimizeFor; + if (message.javaMultipleFiles != null && message.hasOwnProperty("javaMultipleFiles")) + object.javaMultipleFiles = message.javaMultipleFiles; + if (message.goPackage != null && message.hasOwnProperty("goPackage")) + object.goPackage = message.goPackage; + if (message.ccGenericServices != null && message.hasOwnProperty("ccGenericServices")) + object.ccGenericServices = message.ccGenericServices; + if (message.javaGenericServices != null && message.hasOwnProperty("javaGenericServices")) + object.javaGenericServices = message.javaGenericServices; + if (message.pyGenericServices != null && message.hasOwnProperty("pyGenericServices")) + object.pyGenericServices = message.pyGenericServices; + if (message.javaGenerateEqualsAndHash != null && message.hasOwnProperty("javaGenerateEqualsAndHash")) + object.javaGenerateEqualsAndHash = message.javaGenerateEqualsAndHash; + if (message.deprecated != null && message.hasOwnProperty("deprecated")) + object.deprecated = message.deprecated; + if (message.javaStringCheckUtf8 != null && message.hasOwnProperty("javaStringCheckUtf8")) + object.javaStringCheckUtf8 = message.javaStringCheckUtf8; + if (message.ccEnableArenas != null && message.hasOwnProperty("ccEnableArenas")) + object.ccEnableArenas = message.ccEnableArenas; + if (message.objcClassPrefix != null && message.hasOwnProperty("objcClassPrefix")) + object.objcClassPrefix = message.objcClassPrefix; + if (message.csharpNamespace != null && message.hasOwnProperty("csharpNamespace")) + object.csharpNamespace = message.csharpNamespace; + if (message.swiftPrefix != null && message.hasOwnProperty("swiftPrefix")) + object.swiftPrefix = message.swiftPrefix; + if (message.phpClassPrefix != null && message.hasOwnProperty("phpClassPrefix")) + object.phpClassPrefix = message.phpClassPrefix; + if (message.phpNamespace != null && message.hasOwnProperty("phpNamespace")) + object.phpNamespace = message.phpNamespace; + if (message.phpMetadataNamespace != null && message.hasOwnProperty("phpMetadataNamespace")) + object.phpMetadataNamespace = message.phpMetadataNamespace; + if (message.rubyPackage != null && message.hasOwnProperty("rubyPackage")) + object.rubyPackage = message.rubyPackage; + if (message.features != null && message.hasOwnProperty("features")) + object.features = $root.google.protobuf.FeatureSet.toObject(message.features, options); + if (message.uninterpretedOption && message.uninterpretedOption.length) { + object.uninterpretedOption = []; + for (var j = 0; j < message.uninterpretedOption.length; ++j) + object.uninterpretedOption[j] = $root.google.protobuf.UninterpretedOption.toObject(message.uninterpretedOption[j], options); + } + if (message[".google.api.resourceDefinition"] && message[".google.api.resourceDefinition"].length) { + object[".google.api.resourceDefinition"] = []; + for (var j = 0; j < message[".google.api.resourceDefinition"].length; ++j) + object[".google.api.resourceDefinition"][j] = $root.google.api.ResourceDescriptor.toObject(message[".google.api.resourceDefinition"][j], options); + } + return object; + }; - /** - * Aggregation operator. - * @member {"count"|"sum"|"avg"|undefined} operator - * @memberof google.firestore.v1.StructuredAggregationQuery.Aggregation - * @instance - */ - Object.defineProperty(Aggregation.prototype, "operator", { - get: $util.oneOfGetter($oneOfFields = ["count", "sum", "avg"]), - set: $util.oneOfSetter($oneOfFields) - }); + /** + * Converts this FileOptions to JSON. + * @function toJSON + * @memberof google.protobuf.FileOptions + * @instance + * @returns {Object.} JSON object + */ + FileOptions.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; - /** - * Creates an Aggregation message from a plain object. Also converts values to their respective internal types. - * @function fromObject - * @memberof google.firestore.v1.StructuredAggregationQuery.Aggregation - * @static - * @param {Object.} object Plain object - * @returns {google.firestore.v1.StructuredAggregationQuery.Aggregation} Aggregation - */ - Aggregation.fromObject = function fromObject(object) { - if (object instanceof $root.google.firestore.v1.StructuredAggregationQuery.Aggregation) - return object; - var message = new $root.google.firestore.v1.StructuredAggregationQuery.Aggregation(); - if (object.count != null) { - if (typeof object.count !== "object") - throw TypeError(".google.firestore.v1.StructuredAggregationQuery.Aggregation.count: object expected"); - message.count = $root.google.firestore.v1.StructuredAggregationQuery.Aggregation.Count.fromObject(object.count); - } - if (object.sum != null) { - if (typeof object.sum !== "object") - throw TypeError(".google.firestore.v1.StructuredAggregationQuery.Aggregation.sum: object expected"); - message.sum = $root.google.firestore.v1.StructuredAggregationQuery.Aggregation.Sum.fromObject(object.sum); - } - if (object.avg != null) { - if (typeof object.avg !== "object") - throw TypeError(".google.firestore.v1.StructuredAggregationQuery.Aggregation.avg: object expected"); - message.avg = $root.google.firestore.v1.StructuredAggregationQuery.Aggregation.Avg.fromObject(object.avg); - } - if (object.alias != null) - message.alias = String(object.alias); - return message; - }; + /** + * Gets the default type url for FileOptions + * @function getTypeUrl + * @memberof google.protobuf.FileOptions + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + FileOptions.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.protobuf.FileOptions"; + }; - /** - * Creates a plain object from an Aggregation message. Also converts values to other types if specified. - * @function toObject - * @memberof google.firestore.v1.StructuredAggregationQuery.Aggregation - * @static - * @param {google.firestore.v1.StructuredAggregationQuery.Aggregation} message Aggregation - * @param {$protobuf.IConversionOptions} [options] Conversion options - * @returns {Object.} Plain object - */ - Aggregation.toObject = function toObject(message, options) { - if (!options) - options = {}; - var object = {}; - if (options.defaults) - object.alias = ""; - if (message.count != null && message.hasOwnProperty("count")) { - object.count = $root.google.firestore.v1.StructuredAggregationQuery.Aggregation.Count.toObject(message.count, options); - if (options.oneofs) - object.operator = "count"; - } - if (message.sum != null && message.hasOwnProperty("sum")) { - object.sum = $root.google.firestore.v1.StructuredAggregationQuery.Aggregation.Sum.toObject(message.sum, options); - if (options.oneofs) - object.operator = "sum"; - } - if (message.avg != null && message.hasOwnProperty("avg")) { - object.avg = $root.google.firestore.v1.StructuredAggregationQuery.Aggregation.Avg.toObject(message.avg, options); - if (options.oneofs) - object.operator = "avg"; - } - if (message.alias != null && message.hasOwnProperty("alias")) - object.alias = message.alias; - return object; - }; + /** + * OptimizeMode enum. + * @name google.protobuf.FileOptions.OptimizeMode + * @enum {string} + * @property {string} SPEED=SPEED SPEED value + * @property {string} CODE_SIZE=CODE_SIZE CODE_SIZE value + * @property {string} LITE_RUNTIME=LITE_RUNTIME LITE_RUNTIME value + */ + FileOptions.OptimizeMode = (function() { + var valuesById = {}, values = Object.create(valuesById); + values[valuesById[1] = "SPEED"] = "SPEED"; + values[valuesById[2] = "CODE_SIZE"] = "CODE_SIZE"; + values[valuesById[3] = "LITE_RUNTIME"] = "LITE_RUNTIME"; + return values; + })(); - /** - * Converts this Aggregation to JSON. - * @function toJSON - * @memberof google.firestore.v1.StructuredAggregationQuery.Aggregation - * @instance - * @returns {Object.} JSON object - */ - Aggregation.prototype.toJSON = function toJSON() { - return this.constructor.toObject(this, $protobuf.util.toJSONOptions); - }; + return FileOptions; + })(); - /** - * Gets the default type url for Aggregation - * @function getTypeUrl - * @memberof google.firestore.v1.StructuredAggregationQuery.Aggregation - * @static - * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") - * @returns {string} The default type url - */ - Aggregation.getTypeUrl = function getTypeUrl(typeUrlPrefix) { - if (typeUrlPrefix === undefined) { - typeUrlPrefix = "type.googleapis.com"; - } - return typeUrlPrefix + "/google.firestore.v1.StructuredAggregationQuery.Aggregation"; - }; + protobuf.MessageOptions = (function() { - Aggregation.Count = (function() { + /** + * Properties of a MessageOptions. + * @memberof google.protobuf + * @interface IMessageOptions + * @property {boolean|null} [messageSetWireFormat] MessageOptions messageSetWireFormat + * @property {boolean|null} [noStandardDescriptorAccessor] MessageOptions noStandardDescriptorAccessor + * @property {boolean|null} [deprecated] MessageOptions deprecated + * @property {boolean|null} [mapEntry] MessageOptions mapEntry + * @property {boolean|null} [deprecatedLegacyJsonFieldConflicts] MessageOptions deprecatedLegacyJsonFieldConflicts + * @property {google.protobuf.IFeatureSet|null} [features] MessageOptions features + * @property {Array.|null} [uninterpretedOption] MessageOptions uninterpretedOption + * @property {google.api.IResourceDescriptor|null} [".google.api.resource"] MessageOptions .google.api.resource + */ - /** - * Properties of a Count. - * @memberof google.firestore.v1.StructuredAggregationQuery.Aggregation - * @interface ICount - * @property {google.protobuf.IInt64Value|null} [upTo] Count upTo - */ + /** + * Constructs a new MessageOptions. + * @memberof google.protobuf + * @classdesc Represents a MessageOptions. + * @implements IMessageOptions + * @constructor + * @param {google.protobuf.IMessageOptions=} [properties] Properties to set + */ + function MessageOptions(properties) { + this.uninterpretedOption = []; + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } - /** - * Constructs a new Count. - * @memberof google.firestore.v1.StructuredAggregationQuery.Aggregation - * @classdesc Represents a Count. - * @implements ICount - * @constructor - * @param {google.firestore.v1.StructuredAggregationQuery.Aggregation.ICount=} [properties] Properties to set - */ - function Count(properties) { - if (properties) - for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) - if (properties[keys[i]] != null) - this[keys[i]] = properties[keys[i]]; - } + /** + * MessageOptions messageSetWireFormat. + * @member {boolean} messageSetWireFormat + * @memberof google.protobuf.MessageOptions + * @instance + */ + MessageOptions.prototype.messageSetWireFormat = false; - /** - * Count upTo. - * @member {google.protobuf.IInt64Value|null|undefined} upTo - * @memberof google.firestore.v1.StructuredAggregationQuery.Aggregation.Count - * @instance - */ - Count.prototype.upTo = null; + /** + * MessageOptions noStandardDescriptorAccessor. + * @member {boolean} noStandardDescriptorAccessor + * @memberof google.protobuf.MessageOptions + * @instance + */ + MessageOptions.prototype.noStandardDescriptorAccessor = false; - /** - * Creates a Count message from a plain object. Also converts values to their respective internal types. - * @function fromObject - * @memberof google.firestore.v1.StructuredAggregationQuery.Aggregation.Count - * @static - * @param {Object.} object Plain object - * @returns {google.firestore.v1.StructuredAggregationQuery.Aggregation.Count} Count - */ - Count.fromObject = function fromObject(object) { - if (object instanceof $root.google.firestore.v1.StructuredAggregationQuery.Aggregation.Count) - return object; - var message = new $root.google.firestore.v1.StructuredAggregationQuery.Aggregation.Count(); - if (object.upTo != null) { - if (typeof object.upTo !== "object") - throw TypeError(".google.firestore.v1.StructuredAggregationQuery.Aggregation.Count.upTo: object expected"); - message.upTo = $root.google.protobuf.Int64Value.fromObject(object.upTo); - } - return message; - }; + /** + * MessageOptions deprecated. + * @member {boolean} deprecated + * @memberof google.protobuf.MessageOptions + * @instance + */ + MessageOptions.prototype.deprecated = false; - /** - * Creates a plain object from a Count message. Also converts values to other types if specified. - * @function toObject - * @memberof google.firestore.v1.StructuredAggregationQuery.Aggregation.Count - * @static - * @param {google.firestore.v1.StructuredAggregationQuery.Aggregation.Count} message Count - * @param {$protobuf.IConversionOptions} [options] Conversion options - * @returns {Object.} Plain object - */ - Count.toObject = function toObject(message, options) { - if (!options) - options = {}; - var object = {}; - if (options.defaults) - object.upTo = null; - if (message.upTo != null && message.hasOwnProperty("upTo")) - object.upTo = $root.google.protobuf.Int64Value.toObject(message.upTo, options); - return object; - }; + /** + * MessageOptions mapEntry. + * @member {boolean} mapEntry + * @memberof google.protobuf.MessageOptions + * @instance + */ + MessageOptions.prototype.mapEntry = false; - /** - * Converts this Count to JSON. - * @function toJSON - * @memberof google.firestore.v1.StructuredAggregationQuery.Aggregation.Count - * @instance - * @returns {Object.} JSON object - */ - Count.prototype.toJSON = function toJSON() { - return this.constructor.toObject(this, $protobuf.util.toJSONOptions); - }; + /** + * MessageOptions deprecatedLegacyJsonFieldConflicts. + * @member {boolean} deprecatedLegacyJsonFieldConflicts + * @memberof google.protobuf.MessageOptions + * @instance + */ + MessageOptions.prototype.deprecatedLegacyJsonFieldConflicts = false; - /** - * Gets the default type url for Count - * @function getTypeUrl - * @memberof google.firestore.v1.StructuredAggregationQuery.Aggregation.Count - * @static - * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") - * @returns {string} The default type url - */ - Count.getTypeUrl = function getTypeUrl(typeUrlPrefix) { - if (typeUrlPrefix === undefined) { - typeUrlPrefix = "type.googleapis.com"; - } - return typeUrlPrefix + "/google.firestore.v1.StructuredAggregationQuery.Aggregation.Count"; - }; + /** + * MessageOptions features. + * @member {google.protobuf.IFeatureSet|null|undefined} features + * @memberof google.protobuf.MessageOptions + * @instance + */ + MessageOptions.prototype.features = null; - return Count; - })(); + /** + * MessageOptions uninterpretedOption. + * @member {Array.} uninterpretedOption + * @memberof google.protobuf.MessageOptions + * @instance + */ + MessageOptions.prototype.uninterpretedOption = $util.emptyArray; - Aggregation.Sum = (function() { + /** + * MessageOptions .google.api.resource. + * @member {google.api.IResourceDescriptor|null|undefined} .google.api.resource + * @memberof google.protobuf.MessageOptions + * @instance + */ + MessageOptions.prototype[".google.api.resource"] = null; + + /** + * Creates a MessageOptions message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.protobuf.MessageOptions + * @static + * @param {Object.} object Plain object + * @returns {google.protobuf.MessageOptions} MessageOptions + */ + MessageOptions.fromObject = function fromObject(object) { + if (object instanceof $root.google.protobuf.MessageOptions) + return object; + var message = new $root.google.protobuf.MessageOptions(); + if (object.messageSetWireFormat != null) + message.messageSetWireFormat = Boolean(object.messageSetWireFormat); + if (object.noStandardDescriptorAccessor != null) + message.noStandardDescriptorAccessor = Boolean(object.noStandardDescriptorAccessor); + if (object.deprecated != null) + message.deprecated = Boolean(object.deprecated); + if (object.mapEntry != null) + message.mapEntry = Boolean(object.mapEntry); + if (object.deprecatedLegacyJsonFieldConflicts != null) + message.deprecatedLegacyJsonFieldConflicts = Boolean(object.deprecatedLegacyJsonFieldConflicts); + if (object.features != null) { + if (typeof object.features !== "object") + throw TypeError(".google.protobuf.MessageOptions.features: object expected"); + message.features = $root.google.protobuf.FeatureSet.fromObject(object.features); + } + if (object.uninterpretedOption) { + if (!Array.isArray(object.uninterpretedOption)) + throw TypeError(".google.protobuf.MessageOptions.uninterpretedOption: array expected"); + message.uninterpretedOption = []; + for (var i = 0; i < object.uninterpretedOption.length; ++i) { + if (typeof object.uninterpretedOption[i] !== "object") + throw TypeError(".google.protobuf.MessageOptions.uninterpretedOption: object expected"); + message.uninterpretedOption[i] = $root.google.protobuf.UninterpretedOption.fromObject(object.uninterpretedOption[i]); + } + } + if (object[".google.api.resource"] != null) { + if (typeof object[".google.api.resource"] !== "object") + throw TypeError(".google.protobuf.MessageOptions..google.api.resource: object expected"); + message[".google.api.resource"] = $root.google.api.ResourceDescriptor.fromObject(object[".google.api.resource"]); + } + return message; + }; - /** - * Properties of a Sum. - * @memberof google.firestore.v1.StructuredAggregationQuery.Aggregation - * @interface ISum - * @property {google.firestore.v1.StructuredQuery.IFieldReference|null} [field] Sum field - */ + /** + * Creates a plain object from a MessageOptions message. Also converts values to other types if specified. + * @function toObject + * @memberof google.protobuf.MessageOptions + * @static + * @param {google.protobuf.MessageOptions} message MessageOptions + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + MessageOptions.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.arrays || options.defaults) + object.uninterpretedOption = []; + if (options.defaults) { + object.messageSetWireFormat = false; + object.noStandardDescriptorAccessor = false; + object.deprecated = false; + object.mapEntry = false; + object.deprecatedLegacyJsonFieldConflicts = false; + object.features = null; + object[".google.api.resource"] = null; + } + if (message.messageSetWireFormat != null && message.hasOwnProperty("messageSetWireFormat")) + object.messageSetWireFormat = message.messageSetWireFormat; + if (message.noStandardDescriptorAccessor != null && message.hasOwnProperty("noStandardDescriptorAccessor")) + object.noStandardDescriptorAccessor = message.noStandardDescriptorAccessor; + if (message.deprecated != null && message.hasOwnProperty("deprecated")) + object.deprecated = message.deprecated; + if (message.mapEntry != null && message.hasOwnProperty("mapEntry")) + object.mapEntry = message.mapEntry; + if (message.deprecatedLegacyJsonFieldConflicts != null && message.hasOwnProperty("deprecatedLegacyJsonFieldConflicts")) + object.deprecatedLegacyJsonFieldConflicts = message.deprecatedLegacyJsonFieldConflicts; + if (message.features != null && message.hasOwnProperty("features")) + object.features = $root.google.protobuf.FeatureSet.toObject(message.features, options); + if (message.uninterpretedOption && message.uninterpretedOption.length) { + object.uninterpretedOption = []; + for (var j = 0; j < message.uninterpretedOption.length; ++j) + object.uninterpretedOption[j] = $root.google.protobuf.UninterpretedOption.toObject(message.uninterpretedOption[j], options); + } + if (message[".google.api.resource"] != null && message.hasOwnProperty(".google.api.resource")) + object[".google.api.resource"] = $root.google.api.ResourceDescriptor.toObject(message[".google.api.resource"], options); + return object; + }; - /** - * Constructs a new Sum. - * @memberof google.firestore.v1.StructuredAggregationQuery.Aggregation - * @classdesc Represents a Sum. - * @implements ISum - * @constructor - * @param {google.firestore.v1.StructuredAggregationQuery.Aggregation.ISum=} [properties] Properties to set - */ - function Sum(properties) { - if (properties) - for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) - if (properties[keys[i]] != null) - this[keys[i]] = properties[keys[i]]; - } + /** + * Converts this MessageOptions to JSON. + * @function toJSON + * @memberof google.protobuf.MessageOptions + * @instance + * @returns {Object.} JSON object + */ + MessageOptions.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; - /** - * Sum field. - * @member {google.firestore.v1.StructuredQuery.IFieldReference|null|undefined} field - * @memberof google.firestore.v1.StructuredAggregationQuery.Aggregation.Sum - * @instance - */ - Sum.prototype.field = null; + /** + * Gets the default type url for MessageOptions + * @function getTypeUrl + * @memberof google.protobuf.MessageOptions + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + MessageOptions.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.protobuf.MessageOptions"; + }; - /** - * Creates a Sum message from a plain object. Also converts values to their respective internal types. - * @function fromObject - * @memberof google.firestore.v1.StructuredAggregationQuery.Aggregation.Sum - * @static - * @param {Object.} object Plain object - * @returns {google.firestore.v1.StructuredAggregationQuery.Aggregation.Sum} Sum - */ - Sum.fromObject = function fromObject(object) { - if (object instanceof $root.google.firestore.v1.StructuredAggregationQuery.Aggregation.Sum) - return object; - var message = new $root.google.firestore.v1.StructuredAggregationQuery.Aggregation.Sum(); - if (object.field != null) { - if (typeof object.field !== "object") - throw TypeError(".google.firestore.v1.StructuredAggregationQuery.Aggregation.Sum.field: object expected"); - message.field = $root.google.firestore.v1.StructuredQuery.FieldReference.fromObject(object.field); - } - return message; - }; + return MessageOptions; + })(); - /** - * Creates a plain object from a Sum message. Also converts values to other types if specified. - * @function toObject - * @memberof google.firestore.v1.StructuredAggregationQuery.Aggregation.Sum - * @static - * @param {google.firestore.v1.StructuredAggregationQuery.Aggregation.Sum} message Sum - * @param {$protobuf.IConversionOptions} [options] Conversion options - * @returns {Object.} Plain object - */ - Sum.toObject = function toObject(message, options) { - if (!options) - options = {}; - var object = {}; - if (options.defaults) - object.field = null; - if (message.field != null && message.hasOwnProperty("field")) - object.field = $root.google.firestore.v1.StructuredQuery.FieldReference.toObject(message.field, options); - return object; - }; + protobuf.FieldOptions = (function() { - /** - * Converts this Sum to JSON. - * @function toJSON - * @memberof google.firestore.v1.StructuredAggregationQuery.Aggregation.Sum - * @instance - * @returns {Object.} JSON object - */ - Sum.prototype.toJSON = function toJSON() { - return this.constructor.toObject(this, $protobuf.util.toJSONOptions); - }; + /** + * Properties of a FieldOptions. + * @memberof google.protobuf + * @interface IFieldOptions + * @property {google.protobuf.FieldOptions.CType|null} [ctype] FieldOptions ctype + * @property {boolean|null} [packed] FieldOptions packed + * @property {google.protobuf.FieldOptions.JSType|null} [jstype] FieldOptions jstype + * @property {boolean|null} [lazy] FieldOptions lazy + * @property {boolean|null} [unverifiedLazy] FieldOptions unverifiedLazy + * @property {boolean|null} [deprecated] FieldOptions deprecated + * @property {boolean|null} [weak] FieldOptions weak + * @property {boolean|null} [debugRedact] FieldOptions debugRedact + * @property {google.protobuf.FieldOptions.OptionRetention|null} [retention] FieldOptions retention + * @property {Array.|null} [targets] FieldOptions targets + * @property {Array.|null} [editionDefaults] FieldOptions editionDefaults + * @property {google.protobuf.IFeatureSet|null} [features] FieldOptions features + * @property {Array.|null} [uninterpretedOption] FieldOptions uninterpretedOption + * @property {Array.|null} [".google.api.fieldBehavior"] FieldOptions .google.api.fieldBehavior + * @property {google.api.IResourceReference|null} [".google.api.resourceReference"] FieldOptions .google.api.resourceReference + */ - /** - * Gets the default type url for Sum - * @function getTypeUrl - * @memberof google.firestore.v1.StructuredAggregationQuery.Aggregation.Sum - * @static - * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") - * @returns {string} The default type url - */ - Sum.getTypeUrl = function getTypeUrl(typeUrlPrefix) { - if (typeUrlPrefix === undefined) { - typeUrlPrefix = "type.googleapis.com"; - } - return typeUrlPrefix + "/google.firestore.v1.StructuredAggregationQuery.Aggregation.Sum"; - }; + /** + * Constructs a new FieldOptions. + * @memberof google.protobuf + * @classdesc Represents a FieldOptions. + * @implements IFieldOptions + * @constructor + * @param {google.protobuf.IFieldOptions=} [properties] Properties to set + */ + function FieldOptions(properties) { + this.targets = []; + this.editionDefaults = []; + this.uninterpretedOption = []; + this[".google.api.fieldBehavior"] = []; + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } - return Sum; - })(); + /** + * FieldOptions ctype. + * @member {google.protobuf.FieldOptions.CType} ctype + * @memberof google.protobuf.FieldOptions + * @instance + */ + FieldOptions.prototype.ctype = 0; - Aggregation.Avg = (function() { + /** + * FieldOptions packed. + * @member {boolean} packed + * @memberof google.protobuf.FieldOptions + * @instance + */ + FieldOptions.prototype.packed = false; - /** - * Properties of an Avg. - * @memberof google.firestore.v1.StructuredAggregationQuery.Aggregation - * @interface IAvg - * @property {google.firestore.v1.StructuredQuery.IFieldReference|null} [field] Avg field - */ + /** + * FieldOptions jstype. + * @member {google.protobuf.FieldOptions.JSType} jstype + * @memberof google.protobuf.FieldOptions + * @instance + */ + FieldOptions.prototype.jstype = 0; - /** - * Constructs a new Avg. - * @memberof google.firestore.v1.StructuredAggregationQuery.Aggregation - * @classdesc Represents an Avg. - * @implements IAvg - * @constructor - * @param {google.firestore.v1.StructuredAggregationQuery.Aggregation.IAvg=} [properties] Properties to set - */ - function Avg(properties) { - if (properties) - for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) - if (properties[keys[i]] != null) - this[keys[i]] = properties[keys[i]]; - } + /** + * FieldOptions lazy. + * @member {boolean} lazy + * @memberof google.protobuf.FieldOptions + * @instance + */ + FieldOptions.prototype.lazy = false; - /** - * Avg field. - * @member {google.firestore.v1.StructuredQuery.IFieldReference|null|undefined} field - * @memberof google.firestore.v1.StructuredAggregationQuery.Aggregation.Avg - * @instance - */ - Avg.prototype.field = null; + /** + * FieldOptions unverifiedLazy. + * @member {boolean} unverifiedLazy + * @memberof google.protobuf.FieldOptions + * @instance + */ + FieldOptions.prototype.unverifiedLazy = false; - /** - * Creates an Avg message from a plain object. Also converts values to their respective internal types. - * @function fromObject - * @memberof google.firestore.v1.StructuredAggregationQuery.Aggregation.Avg - * @static - * @param {Object.} object Plain object - * @returns {google.firestore.v1.StructuredAggregationQuery.Aggregation.Avg} Avg - */ - Avg.fromObject = function fromObject(object) { - if (object instanceof $root.google.firestore.v1.StructuredAggregationQuery.Aggregation.Avg) - return object; - var message = new $root.google.firestore.v1.StructuredAggregationQuery.Aggregation.Avg(); - if (object.field != null) { - if (typeof object.field !== "object") - throw TypeError(".google.firestore.v1.StructuredAggregationQuery.Aggregation.Avg.field: object expected"); - message.field = $root.google.firestore.v1.StructuredQuery.FieldReference.fromObject(object.field); - } - return message; - }; + /** + * FieldOptions deprecated. + * @member {boolean} deprecated + * @memberof google.protobuf.FieldOptions + * @instance + */ + FieldOptions.prototype.deprecated = false; - /** - * Creates a plain object from an Avg message. Also converts values to other types if specified. - * @function toObject - * @memberof google.firestore.v1.StructuredAggregationQuery.Aggregation.Avg - * @static - * @param {google.firestore.v1.StructuredAggregationQuery.Aggregation.Avg} message Avg - * @param {$protobuf.IConversionOptions} [options] Conversion options - * @returns {Object.} Plain object - */ - Avg.toObject = function toObject(message, options) { - if (!options) - options = {}; - var object = {}; - if (options.defaults) - object.field = null; - if (message.field != null && message.hasOwnProperty("field")) - object.field = $root.google.firestore.v1.StructuredQuery.FieldReference.toObject(message.field, options); - return object; - }; + /** + * FieldOptions weak. + * @member {boolean} weak + * @memberof google.protobuf.FieldOptions + * @instance + */ + FieldOptions.prototype.weak = false; - /** - * Converts this Avg to JSON. - * @function toJSON - * @memberof google.firestore.v1.StructuredAggregationQuery.Aggregation.Avg - * @instance - * @returns {Object.} JSON object - */ - Avg.prototype.toJSON = function toJSON() { - return this.constructor.toObject(this, $protobuf.util.toJSONOptions); - }; + /** + * FieldOptions debugRedact. + * @member {boolean} debugRedact + * @memberof google.protobuf.FieldOptions + * @instance + */ + FieldOptions.prototype.debugRedact = false; - /** - * Gets the default type url for Avg - * @function getTypeUrl - * @memberof google.firestore.v1.StructuredAggregationQuery.Aggregation.Avg - * @static - * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") - * @returns {string} The default type url - */ - Avg.getTypeUrl = function getTypeUrl(typeUrlPrefix) { - if (typeUrlPrefix === undefined) { - typeUrlPrefix = "type.googleapis.com"; - } - return typeUrlPrefix + "/google.firestore.v1.StructuredAggregationQuery.Aggregation.Avg"; - }; + /** + * FieldOptions retention. + * @member {google.protobuf.FieldOptions.OptionRetention} retention + * @memberof google.protobuf.FieldOptions + * @instance + */ + FieldOptions.prototype.retention = 0; - return Avg; - })(); + /** + * FieldOptions targets. + * @member {Array.} targets + * @memberof google.protobuf.FieldOptions + * @instance + */ + FieldOptions.prototype.targets = $util.emptyArray; - return Aggregation; - })(); + /** + * FieldOptions editionDefaults. + * @member {Array.} editionDefaults + * @memberof google.protobuf.FieldOptions + * @instance + */ + FieldOptions.prototype.editionDefaults = $util.emptyArray; - return StructuredAggregationQuery; - })(); + /** + * FieldOptions features. + * @member {google.protobuf.IFeatureSet|null|undefined} features + * @memberof google.protobuf.FieldOptions + * @instance + */ + FieldOptions.prototype.features = null; - v1.Cursor = (function() { + /** + * FieldOptions uninterpretedOption. + * @member {Array.} uninterpretedOption + * @memberof google.protobuf.FieldOptions + * @instance + */ + FieldOptions.prototype.uninterpretedOption = $util.emptyArray; - /** - * Properties of a Cursor. - * @memberof google.firestore.v1 - * @interface ICursor - * @property {Array.|null} [values] Cursor values - * @property {boolean|null} [before] Cursor before - */ + /** + * FieldOptions .google.api.fieldBehavior. + * @member {Array.} .google.api.fieldBehavior + * @memberof google.protobuf.FieldOptions + * @instance + */ + FieldOptions.prototype[".google.api.fieldBehavior"] = $util.emptyArray; - /** - * Constructs a new Cursor. - * @memberof google.firestore.v1 - * @classdesc Represents a Cursor. - * @implements ICursor - * @constructor - * @param {google.firestore.v1.ICursor=} [properties] Properties to set - */ - function Cursor(properties) { - this.values = []; - if (properties) - for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) - if (properties[keys[i]] != null) - this[keys[i]] = properties[keys[i]]; + /** + * FieldOptions .google.api.resourceReference. + * @member {google.api.IResourceReference|null|undefined} .google.api.resourceReference + * @memberof google.protobuf.FieldOptions + * @instance + */ + FieldOptions.prototype[".google.api.resourceReference"] = null; + + /** + * Creates a FieldOptions message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.protobuf.FieldOptions + * @static + * @param {Object.} object Plain object + * @returns {google.protobuf.FieldOptions} FieldOptions + */ + FieldOptions.fromObject = function fromObject(object) { + if (object instanceof $root.google.protobuf.FieldOptions) + return object; + var message = new $root.google.protobuf.FieldOptions(); + switch (object.ctype) { + default: + if (typeof object.ctype === "number") { + message.ctype = object.ctype; + break; + } + break; + case "STRING": + case 0: + message.ctype = 0; + break; + case "CORD": + case 1: + message.ctype = 1; + break; + case "STRING_PIECE": + case 2: + message.ctype = 2; + break; + } + if (object.packed != null) + message.packed = Boolean(object.packed); + switch (object.jstype) { + default: + if (typeof object.jstype === "number") { + message.jstype = object.jstype; + break; + } + break; + case "JS_NORMAL": + case 0: + message.jstype = 0; + break; + case "JS_STRING": + case 1: + message.jstype = 1; + break; + case "JS_NUMBER": + case 2: + message.jstype = 2; + break; + } + if (object.lazy != null) + message.lazy = Boolean(object.lazy); + if (object.unverifiedLazy != null) + message.unverifiedLazy = Boolean(object.unverifiedLazy); + if (object.deprecated != null) + message.deprecated = Boolean(object.deprecated); + if (object.weak != null) + message.weak = Boolean(object.weak); + if (object.debugRedact != null) + message.debugRedact = Boolean(object.debugRedact); + switch (object.retention) { + default: + if (typeof object.retention === "number") { + message.retention = object.retention; + break; + } + break; + case "RETENTION_UNKNOWN": + case 0: + message.retention = 0; + break; + case "RETENTION_RUNTIME": + case 1: + message.retention = 1; + break; + case "RETENTION_SOURCE": + case 2: + message.retention = 2; + break; } - - /** - * Cursor values. - * @member {Array.} values - * @memberof google.firestore.v1.Cursor - * @instance - */ - Cursor.prototype.values = $util.emptyArray; - - /** - * Cursor before. - * @member {boolean} before - * @memberof google.firestore.v1.Cursor - * @instance - */ - Cursor.prototype.before = false; - - /** - * Creates a Cursor message from a plain object. Also converts values to their respective internal types. - * @function fromObject - * @memberof google.firestore.v1.Cursor - * @static - * @param {Object.} object Plain object - * @returns {google.firestore.v1.Cursor} Cursor - */ - Cursor.fromObject = function fromObject(object) { - if (object instanceof $root.google.firestore.v1.Cursor) - return object; - var message = new $root.google.firestore.v1.Cursor(); - if (object.values) { - if (!Array.isArray(object.values)) - throw TypeError(".google.firestore.v1.Cursor.values: array expected"); - message.values = []; - for (var i = 0; i < object.values.length; ++i) { - if (typeof object.values[i] !== "object") - throw TypeError(".google.firestore.v1.Cursor.values: object expected"); - message.values[i] = $root.google.firestore.v1.Value.fromObject(object.values[i]); + if (object.targets) { + if (!Array.isArray(object.targets)) + throw TypeError(".google.protobuf.FieldOptions.targets: array expected"); + message.targets = []; + for (var i = 0; i < object.targets.length; ++i) + switch (object.targets[i]) { + default: + if (typeof object.targets[i] === "number") { + message.targets[i] = object.targets[i]; + break; + } + case "TARGET_TYPE_UNKNOWN": + case 0: + message.targets[i] = 0; + break; + case "TARGET_TYPE_FILE": + case 1: + message.targets[i] = 1; + break; + case "TARGET_TYPE_EXTENSION_RANGE": + case 2: + message.targets[i] = 2; + break; + case "TARGET_TYPE_MESSAGE": + case 3: + message.targets[i] = 3; + break; + case "TARGET_TYPE_FIELD": + case 4: + message.targets[i] = 4; + break; + case "TARGET_TYPE_ONEOF": + case 5: + message.targets[i] = 5; + break; + case "TARGET_TYPE_ENUM": + case 6: + message.targets[i] = 6; + break; + case "TARGET_TYPE_ENUM_ENTRY": + case 7: + message.targets[i] = 7; + break; + case "TARGET_TYPE_SERVICE": + case 8: + message.targets[i] = 8; + break; + case "TARGET_TYPE_METHOD": + case 9: + message.targets[i] = 9; + break; } + } + if (object.editionDefaults) { + if (!Array.isArray(object.editionDefaults)) + throw TypeError(".google.protobuf.FieldOptions.editionDefaults: array expected"); + message.editionDefaults = []; + for (var i = 0; i < object.editionDefaults.length; ++i) { + if (typeof object.editionDefaults[i] !== "object") + throw TypeError(".google.protobuf.FieldOptions.editionDefaults: object expected"); + message.editionDefaults[i] = $root.google.protobuf.FieldOptions.EditionDefault.fromObject(object.editionDefaults[i]); } - if (object.before != null) - message.before = Boolean(object.before); - return message; - }; - - /** - * Creates a plain object from a Cursor message. Also converts values to other types if specified. - * @function toObject - * @memberof google.firestore.v1.Cursor - * @static - * @param {google.firestore.v1.Cursor} message Cursor - * @param {$protobuf.IConversionOptions} [options] Conversion options - * @returns {Object.} Plain object - */ - Cursor.toObject = function toObject(message, options) { - if (!options) - options = {}; - var object = {}; - if (options.arrays || options.defaults) - object.values = []; - if (options.defaults) - object.before = false; - if (message.values && message.values.length) { - object.values = []; - for (var j = 0; j < message.values.length; ++j) - object.values[j] = $root.google.firestore.v1.Value.toObject(message.values[j], options); - } - if (message.before != null && message.hasOwnProperty("before")) - object.before = message.before; - return object; - }; - - /** - * Converts this Cursor to JSON. - * @function toJSON - * @memberof google.firestore.v1.Cursor - * @instance - * @returns {Object.} JSON object - */ - Cursor.prototype.toJSON = function toJSON() { - return this.constructor.toObject(this, $protobuf.util.toJSONOptions); - }; - - /** - * Gets the default type url for Cursor - * @function getTypeUrl - * @memberof google.firestore.v1.Cursor - * @static - * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") - * @returns {string} The default type url - */ - Cursor.getTypeUrl = function getTypeUrl(typeUrlPrefix) { - if (typeUrlPrefix === undefined) { - typeUrlPrefix = "type.googleapis.com"; + } + if (object.features != null) { + if (typeof object.features !== "object") + throw TypeError(".google.protobuf.FieldOptions.features: object expected"); + message.features = $root.google.protobuf.FeatureSet.fromObject(object.features); + } + if (object.uninterpretedOption) { + if (!Array.isArray(object.uninterpretedOption)) + throw TypeError(".google.protobuf.FieldOptions.uninterpretedOption: array expected"); + message.uninterpretedOption = []; + for (var i = 0; i < object.uninterpretedOption.length; ++i) { + if (typeof object.uninterpretedOption[i] !== "object") + throw TypeError(".google.protobuf.FieldOptions.uninterpretedOption: object expected"); + message.uninterpretedOption[i] = $root.google.protobuf.UninterpretedOption.fromObject(object.uninterpretedOption[i]); } - return typeUrlPrefix + "/google.firestore.v1.Cursor"; - }; - - return Cursor; - })(); - - v1.ExplainOptions = (function() { - - /** - * Properties of an ExplainOptions. - * @memberof google.firestore.v1 - * @interface IExplainOptions - * @property {boolean|null} [analyze] ExplainOptions analyze - */ + } + if (object[".google.api.fieldBehavior"]) { + if (!Array.isArray(object[".google.api.fieldBehavior"])) + throw TypeError(".google.protobuf.FieldOptions..google.api.fieldBehavior: array expected"); + message[".google.api.fieldBehavior"] = []; + for (var i = 0; i < object[".google.api.fieldBehavior"].length; ++i) + switch (object[".google.api.fieldBehavior"][i]) { + default: + if (typeof object[".google.api.fieldBehavior"][i] === "number") { + message[".google.api.fieldBehavior"][i] = object[".google.api.fieldBehavior"][i]; + break; + } + case "FIELD_BEHAVIOR_UNSPECIFIED": + case 0: + message[".google.api.fieldBehavior"][i] = 0; + break; + case "OPTIONAL": + case 1: + message[".google.api.fieldBehavior"][i] = 1; + break; + case "REQUIRED": + case 2: + message[".google.api.fieldBehavior"][i] = 2; + break; + case "OUTPUT_ONLY": + case 3: + message[".google.api.fieldBehavior"][i] = 3; + break; + case "INPUT_ONLY": + case 4: + message[".google.api.fieldBehavior"][i] = 4; + break; + case "IMMUTABLE": + case 5: + message[".google.api.fieldBehavior"][i] = 5; + break; + case "UNORDERED_LIST": + case 6: + message[".google.api.fieldBehavior"][i] = 6; + break; + case "NON_EMPTY_DEFAULT": + case 7: + message[".google.api.fieldBehavior"][i] = 7; + break; + case "IDENTIFIER": + case 8: + message[".google.api.fieldBehavior"][i] = 8; + break; + } + } + if (object[".google.api.resourceReference"] != null) { + if (typeof object[".google.api.resourceReference"] !== "object") + throw TypeError(".google.protobuf.FieldOptions..google.api.resourceReference: object expected"); + message[".google.api.resourceReference"] = $root.google.api.ResourceReference.fromObject(object[".google.api.resourceReference"]); + } + return message; + }; - /** - * Constructs a new ExplainOptions. - * @memberof google.firestore.v1 - * @classdesc Represents an ExplainOptions. - * @implements IExplainOptions - * @constructor - * @param {google.firestore.v1.IExplainOptions=} [properties] Properties to set - */ - function ExplainOptions(properties) { - if (properties) - for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) - if (properties[keys[i]] != null) - this[keys[i]] = properties[keys[i]]; + /** + * Creates a plain object from a FieldOptions message. Also converts values to other types if specified. + * @function toObject + * @memberof google.protobuf.FieldOptions + * @static + * @param {google.protobuf.FieldOptions} message FieldOptions + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + FieldOptions.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.arrays || options.defaults) { + object.targets = []; + object.editionDefaults = []; + object.uninterpretedOption = []; + object[".google.api.fieldBehavior"] = []; + } + if (options.defaults) { + object.ctype = options.enums === String ? "STRING" : 0; + object.packed = false; + object.deprecated = false; + object.lazy = false; + object.jstype = options.enums === String ? "JS_NORMAL" : 0; + object.weak = false; + object.unverifiedLazy = false; + object.debugRedact = false; + object.retention = options.enums === String ? "RETENTION_UNKNOWN" : 0; + object.features = null; + object[".google.api.resourceReference"] = null; + } + if (message.ctype != null && message.hasOwnProperty("ctype")) + object.ctype = options.enums === String ? $root.google.protobuf.FieldOptions.CType[message.ctype] === undefined ? message.ctype : $root.google.protobuf.FieldOptions.CType[message.ctype] : message.ctype; + if (message.packed != null && message.hasOwnProperty("packed")) + object.packed = message.packed; + if (message.deprecated != null && message.hasOwnProperty("deprecated")) + object.deprecated = message.deprecated; + if (message.lazy != null && message.hasOwnProperty("lazy")) + object.lazy = message.lazy; + if (message.jstype != null && message.hasOwnProperty("jstype")) + object.jstype = options.enums === String ? $root.google.protobuf.FieldOptions.JSType[message.jstype] === undefined ? message.jstype : $root.google.protobuf.FieldOptions.JSType[message.jstype] : message.jstype; + if (message.weak != null && message.hasOwnProperty("weak")) + object.weak = message.weak; + if (message.unverifiedLazy != null && message.hasOwnProperty("unverifiedLazy")) + object.unverifiedLazy = message.unverifiedLazy; + if (message.debugRedact != null && message.hasOwnProperty("debugRedact")) + object.debugRedact = message.debugRedact; + if (message.retention != null && message.hasOwnProperty("retention")) + object.retention = options.enums === String ? $root.google.protobuf.FieldOptions.OptionRetention[message.retention] === undefined ? message.retention : $root.google.protobuf.FieldOptions.OptionRetention[message.retention] : message.retention; + if (message.targets && message.targets.length) { + object.targets = []; + for (var j = 0; j < message.targets.length; ++j) + object.targets[j] = options.enums === String ? $root.google.protobuf.FieldOptions.OptionTargetType[message.targets[j]] === undefined ? message.targets[j] : $root.google.protobuf.FieldOptions.OptionTargetType[message.targets[j]] : message.targets[j]; + } + if (message.editionDefaults && message.editionDefaults.length) { + object.editionDefaults = []; + for (var j = 0; j < message.editionDefaults.length; ++j) + object.editionDefaults[j] = $root.google.protobuf.FieldOptions.EditionDefault.toObject(message.editionDefaults[j], options); + } + if (message.features != null && message.hasOwnProperty("features")) + object.features = $root.google.protobuf.FeatureSet.toObject(message.features, options); + if (message.uninterpretedOption && message.uninterpretedOption.length) { + object.uninterpretedOption = []; + for (var j = 0; j < message.uninterpretedOption.length; ++j) + object.uninterpretedOption[j] = $root.google.protobuf.UninterpretedOption.toObject(message.uninterpretedOption[j], options); + } + if (message[".google.api.fieldBehavior"] && message[".google.api.fieldBehavior"].length) { + object[".google.api.fieldBehavior"] = []; + for (var j = 0; j < message[".google.api.fieldBehavior"].length; ++j) + object[".google.api.fieldBehavior"][j] = options.enums === String ? $root.google.api.FieldBehavior[message[".google.api.fieldBehavior"][j]] === undefined ? message[".google.api.fieldBehavior"][j] : $root.google.api.FieldBehavior[message[".google.api.fieldBehavior"][j]] : message[".google.api.fieldBehavior"][j]; } + if (message[".google.api.resourceReference"] != null && message.hasOwnProperty(".google.api.resourceReference")) + object[".google.api.resourceReference"] = $root.google.api.ResourceReference.toObject(message[".google.api.resourceReference"], options); + return object; + }; - /** - * ExplainOptions analyze. - * @member {boolean} analyze - * @memberof google.firestore.v1.ExplainOptions - * @instance - */ - ExplainOptions.prototype.analyze = false; + /** + * Converts this FieldOptions to JSON. + * @function toJSON + * @memberof google.protobuf.FieldOptions + * @instance + * @returns {Object.} JSON object + */ + FieldOptions.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; - /** - * Creates an ExplainOptions message from a plain object. Also converts values to their respective internal types. - * @function fromObject - * @memberof google.firestore.v1.ExplainOptions - * @static - * @param {Object.} object Plain object - * @returns {google.firestore.v1.ExplainOptions} ExplainOptions - */ - ExplainOptions.fromObject = function fromObject(object) { - if (object instanceof $root.google.firestore.v1.ExplainOptions) - return object; - var message = new $root.google.firestore.v1.ExplainOptions(); - if (object.analyze != null) - message.analyze = Boolean(object.analyze); - return message; - }; + /** + * Gets the default type url for FieldOptions + * @function getTypeUrl + * @memberof google.protobuf.FieldOptions + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + FieldOptions.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.protobuf.FieldOptions"; + }; - /** - * Creates a plain object from an ExplainOptions message. Also converts values to other types if specified. - * @function toObject - * @memberof google.firestore.v1.ExplainOptions - * @static - * @param {google.firestore.v1.ExplainOptions} message ExplainOptions - * @param {$protobuf.IConversionOptions} [options] Conversion options - * @returns {Object.} Plain object - */ - ExplainOptions.toObject = function toObject(message, options) { - if (!options) - options = {}; - var object = {}; - if (options.defaults) - object.analyze = false; - if (message.analyze != null && message.hasOwnProperty("analyze")) - object.analyze = message.analyze; - return object; - }; + /** + * CType enum. + * @name google.protobuf.FieldOptions.CType + * @enum {string} + * @property {string} STRING=STRING STRING value + * @property {string} CORD=CORD CORD value + * @property {string} STRING_PIECE=STRING_PIECE STRING_PIECE value + */ + FieldOptions.CType = (function() { + var valuesById = {}, values = Object.create(valuesById); + values[valuesById[0] = "STRING"] = "STRING"; + values[valuesById[1] = "CORD"] = "CORD"; + values[valuesById[2] = "STRING_PIECE"] = "STRING_PIECE"; + return values; + })(); - /** - * Converts this ExplainOptions to JSON. - * @function toJSON - * @memberof google.firestore.v1.ExplainOptions - * @instance - * @returns {Object.} JSON object - */ - ExplainOptions.prototype.toJSON = function toJSON() { - return this.constructor.toObject(this, $protobuf.util.toJSONOptions); - }; + /** + * JSType enum. + * @name google.protobuf.FieldOptions.JSType + * @enum {string} + * @property {string} JS_NORMAL=JS_NORMAL JS_NORMAL value + * @property {string} JS_STRING=JS_STRING JS_STRING value + * @property {string} JS_NUMBER=JS_NUMBER JS_NUMBER value + */ + FieldOptions.JSType = (function() { + var valuesById = {}, values = Object.create(valuesById); + values[valuesById[0] = "JS_NORMAL"] = "JS_NORMAL"; + values[valuesById[1] = "JS_STRING"] = "JS_STRING"; + values[valuesById[2] = "JS_NUMBER"] = "JS_NUMBER"; + return values; + })(); - /** - * Gets the default type url for ExplainOptions - * @function getTypeUrl - * @memberof google.firestore.v1.ExplainOptions - * @static - * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") - * @returns {string} The default type url - */ - ExplainOptions.getTypeUrl = function getTypeUrl(typeUrlPrefix) { - if (typeUrlPrefix === undefined) { - typeUrlPrefix = "type.googleapis.com"; - } - return typeUrlPrefix + "/google.firestore.v1.ExplainOptions"; - }; + /** + * OptionRetention enum. + * @name google.protobuf.FieldOptions.OptionRetention + * @enum {string} + * @property {string} RETENTION_UNKNOWN=RETENTION_UNKNOWN RETENTION_UNKNOWN value + * @property {string} RETENTION_RUNTIME=RETENTION_RUNTIME RETENTION_RUNTIME value + * @property {string} RETENTION_SOURCE=RETENTION_SOURCE RETENTION_SOURCE value + */ + FieldOptions.OptionRetention = (function() { + var valuesById = {}, values = Object.create(valuesById); + values[valuesById[0] = "RETENTION_UNKNOWN"] = "RETENTION_UNKNOWN"; + values[valuesById[1] = "RETENTION_RUNTIME"] = "RETENTION_RUNTIME"; + values[valuesById[2] = "RETENTION_SOURCE"] = "RETENTION_SOURCE"; + return values; + })(); - return ExplainOptions; + /** + * OptionTargetType enum. + * @name google.protobuf.FieldOptions.OptionTargetType + * @enum {string} + * @property {string} TARGET_TYPE_UNKNOWN=TARGET_TYPE_UNKNOWN TARGET_TYPE_UNKNOWN value + * @property {string} TARGET_TYPE_FILE=TARGET_TYPE_FILE TARGET_TYPE_FILE value + * @property {string} TARGET_TYPE_EXTENSION_RANGE=TARGET_TYPE_EXTENSION_RANGE TARGET_TYPE_EXTENSION_RANGE value + * @property {string} TARGET_TYPE_MESSAGE=TARGET_TYPE_MESSAGE TARGET_TYPE_MESSAGE value + * @property {string} TARGET_TYPE_FIELD=TARGET_TYPE_FIELD TARGET_TYPE_FIELD value + * @property {string} TARGET_TYPE_ONEOF=TARGET_TYPE_ONEOF TARGET_TYPE_ONEOF value + * @property {string} TARGET_TYPE_ENUM=TARGET_TYPE_ENUM TARGET_TYPE_ENUM value + * @property {string} TARGET_TYPE_ENUM_ENTRY=TARGET_TYPE_ENUM_ENTRY TARGET_TYPE_ENUM_ENTRY value + * @property {string} TARGET_TYPE_SERVICE=TARGET_TYPE_SERVICE TARGET_TYPE_SERVICE value + * @property {string} TARGET_TYPE_METHOD=TARGET_TYPE_METHOD TARGET_TYPE_METHOD value + */ + FieldOptions.OptionTargetType = (function() { + var valuesById = {}, values = Object.create(valuesById); + values[valuesById[0] = "TARGET_TYPE_UNKNOWN"] = "TARGET_TYPE_UNKNOWN"; + values[valuesById[1] = "TARGET_TYPE_FILE"] = "TARGET_TYPE_FILE"; + values[valuesById[2] = "TARGET_TYPE_EXTENSION_RANGE"] = "TARGET_TYPE_EXTENSION_RANGE"; + values[valuesById[3] = "TARGET_TYPE_MESSAGE"] = "TARGET_TYPE_MESSAGE"; + values[valuesById[4] = "TARGET_TYPE_FIELD"] = "TARGET_TYPE_FIELD"; + values[valuesById[5] = "TARGET_TYPE_ONEOF"] = "TARGET_TYPE_ONEOF"; + values[valuesById[6] = "TARGET_TYPE_ENUM"] = "TARGET_TYPE_ENUM"; + values[valuesById[7] = "TARGET_TYPE_ENUM_ENTRY"] = "TARGET_TYPE_ENUM_ENTRY"; + values[valuesById[8] = "TARGET_TYPE_SERVICE"] = "TARGET_TYPE_SERVICE"; + values[valuesById[9] = "TARGET_TYPE_METHOD"] = "TARGET_TYPE_METHOD"; + return values; })(); - v1.ExplainMetrics = (function() { + FieldOptions.EditionDefault = (function() { /** - * Properties of an ExplainMetrics. - * @memberof google.firestore.v1 - * @interface IExplainMetrics - * @property {google.firestore.v1.IPlanSummary|null} [planSummary] ExplainMetrics planSummary - * @property {google.firestore.v1.IExecutionStats|null} [executionStats] ExplainMetrics executionStats + * Properties of an EditionDefault. + * @memberof google.protobuf.FieldOptions + * @interface IEditionDefault + * @property {google.protobuf.Edition|null} [edition] EditionDefault edition + * @property {string|null} [value] EditionDefault value */ /** - * Constructs a new ExplainMetrics. - * @memberof google.firestore.v1 - * @classdesc Represents an ExplainMetrics. - * @implements IExplainMetrics + * Constructs a new EditionDefault. + * @memberof google.protobuf.FieldOptions + * @classdesc Represents an EditionDefault. + * @implements IEditionDefault * @constructor - * @param {google.firestore.v1.IExplainMetrics=} [properties] Properties to set + * @param {google.protobuf.FieldOptions.IEditionDefault=} [properties] Properties to set */ - function ExplainMetrics(properties) { + function EditionDefault(properties) { if (properties) for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) if (properties[keys[i]] != null) @@ -20665,994 +20310,1285 @@ } /** - * ExplainMetrics planSummary. - * @member {google.firestore.v1.IPlanSummary|null|undefined} planSummary - * @memberof google.firestore.v1.ExplainMetrics + * EditionDefault edition. + * @member {google.protobuf.Edition} edition + * @memberof google.protobuf.FieldOptions.EditionDefault * @instance */ - ExplainMetrics.prototype.planSummary = null; + EditionDefault.prototype.edition = 0; /** - * ExplainMetrics executionStats. - * @member {google.firestore.v1.IExecutionStats|null|undefined} executionStats - * @memberof google.firestore.v1.ExplainMetrics + * EditionDefault value. + * @member {string} value + * @memberof google.protobuf.FieldOptions.EditionDefault * @instance */ - ExplainMetrics.prototype.executionStats = null; + EditionDefault.prototype.value = ""; /** - * Creates an ExplainMetrics message from a plain object. Also converts values to their respective internal types. + * Creates an EditionDefault message from a plain object. Also converts values to their respective internal types. * @function fromObject - * @memberof google.firestore.v1.ExplainMetrics + * @memberof google.protobuf.FieldOptions.EditionDefault * @static * @param {Object.} object Plain object - * @returns {google.firestore.v1.ExplainMetrics} ExplainMetrics + * @returns {google.protobuf.FieldOptions.EditionDefault} EditionDefault */ - ExplainMetrics.fromObject = function fromObject(object) { - if (object instanceof $root.google.firestore.v1.ExplainMetrics) + EditionDefault.fromObject = function fromObject(object) { + if (object instanceof $root.google.protobuf.FieldOptions.EditionDefault) return object; - var message = new $root.google.firestore.v1.ExplainMetrics(); - if (object.planSummary != null) { - if (typeof object.planSummary !== "object") - throw TypeError(".google.firestore.v1.ExplainMetrics.planSummary: object expected"); - message.planSummary = $root.google.firestore.v1.PlanSummary.fromObject(object.planSummary); - } - if (object.executionStats != null) { - if (typeof object.executionStats !== "object") - throw TypeError(".google.firestore.v1.ExplainMetrics.executionStats: object expected"); - message.executionStats = $root.google.firestore.v1.ExecutionStats.fromObject(object.executionStats); + var message = new $root.google.protobuf.FieldOptions.EditionDefault(); + switch (object.edition) { + default: + if (typeof object.edition === "number") { + message.edition = object.edition; + break; + } + break; + case "EDITION_UNKNOWN": + case 0: + message.edition = 0; + break; + case "EDITION_PROTO2": + case 998: + message.edition = 998; + break; + case "EDITION_PROTO3": + case 999: + message.edition = 999; + break; + case "EDITION_2023": + case 1000: + message.edition = 1000; + break; + case "EDITION_2024": + case 1001: + message.edition = 1001; + break; + case "EDITION_1_TEST_ONLY": + case 1: + message.edition = 1; + break; + case "EDITION_2_TEST_ONLY": + case 2: + message.edition = 2; + break; + case "EDITION_99997_TEST_ONLY": + case 99997: + message.edition = 99997; + break; + case "EDITION_99998_TEST_ONLY": + case 99998: + message.edition = 99998; + break; + case "EDITION_99999_TEST_ONLY": + case 99999: + message.edition = 99999; + break; + case "EDITION_MAX": + case 2147483647: + message.edition = 2147483647; + break; } + if (object.value != null) + message.value = String(object.value); return message; }; /** - * Creates a plain object from an ExplainMetrics message. Also converts values to other types if specified. + * Creates a plain object from an EditionDefault message. Also converts values to other types if specified. * @function toObject - * @memberof google.firestore.v1.ExplainMetrics + * @memberof google.protobuf.FieldOptions.EditionDefault * @static - * @param {google.firestore.v1.ExplainMetrics} message ExplainMetrics + * @param {google.protobuf.FieldOptions.EditionDefault} message EditionDefault * @param {$protobuf.IConversionOptions} [options] Conversion options * @returns {Object.} Plain object */ - ExplainMetrics.toObject = function toObject(message, options) { + EditionDefault.toObject = function toObject(message, options) { if (!options) options = {}; var object = {}; if (options.defaults) { - object.planSummary = null; - object.executionStats = null; + object.value = ""; + object.edition = options.enums === String ? "EDITION_UNKNOWN" : 0; } - if (message.planSummary != null && message.hasOwnProperty("planSummary")) - object.planSummary = $root.google.firestore.v1.PlanSummary.toObject(message.planSummary, options); - if (message.executionStats != null && message.hasOwnProperty("executionStats")) - object.executionStats = $root.google.firestore.v1.ExecutionStats.toObject(message.executionStats, options); + if (message.value != null && message.hasOwnProperty("value")) + object.value = message.value; + if (message.edition != null && message.hasOwnProperty("edition")) + object.edition = options.enums === String ? $root.google.protobuf.Edition[message.edition] === undefined ? message.edition : $root.google.protobuf.Edition[message.edition] : message.edition; return object; }; /** - * Converts this ExplainMetrics to JSON. + * Converts this EditionDefault to JSON. * @function toJSON - * @memberof google.firestore.v1.ExplainMetrics + * @memberof google.protobuf.FieldOptions.EditionDefault * @instance * @returns {Object.} JSON object */ - ExplainMetrics.prototype.toJSON = function toJSON() { + EditionDefault.prototype.toJSON = function toJSON() { return this.constructor.toObject(this, $protobuf.util.toJSONOptions); }; - /** - * Gets the default type url for ExplainMetrics - * @function getTypeUrl - * @memberof google.firestore.v1.ExplainMetrics - * @static - * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") - * @returns {string} The default type url - */ - ExplainMetrics.getTypeUrl = function getTypeUrl(typeUrlPrefix) { - if (typeUrlPrefix === undefined) { - typeUrlPrefix = "type.googleapis.com"; - } - return typeUrlPrefix + "/google.firestore.v1.ExplainMetrics"; - }; + /** + * Gets the default type url for EditionDefault + * @function getTypeUrl + * @memberof google.protobuf.FieldOptions.EditionDefault + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + EditionDefault.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.protobuf.FieldOptions.EditionDefault"; + }; + + return EditionDefault; + })(); + + return FieldOptions; + })(); + + protobuf.OneofOptions = (function() { + + /** + * Properties of an OneofOptions. + * @memberof google.protobuf + * @interface IOneofOptions + * @property {google.protobuf.IFeatureSet|null} [features] OneofOptions features + * @property {Array.|null} [uninterpretedOption] OneofOptions uninterpretedOption + */ + + /** + * Constructs a new OneofOptions. + * @memberof google.protobuf + * @classdesc Represents an OneofOptions. + * @implements IOneofOptions + * @constructor + * @param {google.protobuf.IOneofOptions=} [properties] Properties to set + */ + function OneofOptions(properties) { + this.uninterpretedOption = []; + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } + + /** + * OneofOptions features. + * @member {google.protobuf.IFeatureSet|null|undefined} features + * @memberof google.protobuf.OneofOptions + * @instance + */ + OneofOptions.prototype.features = null; + + /** + * OneofOptions uninterpretedOption. + * @member {Array.} uninterpretedOption + * @memberof google.protobuf.OneofOptions + * @instance + */ + OneofOptions.prototype.uninterpretedOption = $util.emptyArray; + + /** + * Creates an OneofOptions message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.protobuf.OneofOptions + * @static + * @param {Object.} object Plain object + * @returns {google.protobuf.OneofOptions} OneofOptions + */ + OneofOptions.fromObject = function fromObject(object) { + if (object instanceof $root.google.protobuf.OneofOptions) + return object; + var message = new $root.google.protobuf.OneofOptions(); + if (object.features != null) { + if (typeof object.features !== "object") + throw TypeError(".google.protobuf.OneofOptions.features: object expected"); + message.features = $root.google.protobuf.FeatureSet.fromObject(object.features); + } + if (object.uninterpretedOption) { + if (!Array.isArray(object.uninterpretedOption)) + throw TypeError(".google.protobuf.OneofOptions.uninterpretedOption: array expected"); + message.uninterpretedOption = []; + for (var i = 0; i < object.uninterpretedOption.length; ++i) { + if (typeof object.uninterpretedOption[i] !== "object") + throw TypeError(".google.protobuf.OneofOptions.uninterpretedOption: object expected"); + message.uninterpretedOption[i] = $root.google.protobuf.UninterpretedOption.fromObject(object.uninterpretedOption[i]); + } + } + return message; + }; + + /** + * Creates a plain object from an OneofOptions message. Also converts values to other types if specified. + * @function toObject + * @memberof google.protobuf.OneofOptions + * @static + * @param {google.protobuf.OneofOptions} message OneofOptions + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + OneofOptions.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.arrays || options.defaults) + object.uninterpretedOption = []; + if (options.defaults) + object.features = null; + if (message.features != null && message.hasOwnProperty("features")) + object.features = $root.google.protobuf.FeatureSet.toObject(message.features, options); + if (message.uninterpretedOption && message.uninterpretedOption.length) { + object.uninterpretedOption = []; + for (var j = 0; j < message.uninterpretedOption.length; ++j) + object.uninterpretedOption[j] = $root.google.protobuf.UninterpretedOption.toObject(message.uninterpretedOption[j], options); + } + return object; + }; + + /** + * Converts this OneofOptions to JSON. + * @function toJSON + * @memberof google.protobuf.OneofOptions + * @instance + * @returns {Object.} JSON object + */ + OneofOptions.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + + /** + * Gets the default type url for OneofOptions + * @function getTypeUrl + * @memberof google.protobuf.OneofOptions + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + OneofOptions.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.protobuf.OneofOptions"; + }; + + return OneofOptions; + })(); - return ExplainMetrics; - })(); + protobuf.EnumOptions = (function() { - v1.PlanSummary = (function() { + /** + * Properties of an EnumOptions. + * @memberof google.protobuf + * @interface IEnumOptions + * @property {boolean|null} [allowAlias] EnumOptions allowAlias + * @property {boolean|null} [deprecated] EnumOptions deprecated + * @property {boolean|null} [deprecatedLegacyJsonFieldConflicts] EnumOptions deprecatedLegacyJsonFieldConflicts + * @property {google.protobuf.IFeatureSet|null} [features] EnumOptions features + * @property {Array.|null} [uninterpretedOption] EnumOptions uninterpretedOption + */ - /** - * Properties of a PlanSummary. - * @memberof google.firestore.v1 - * @interface IPlanSummary - * @property {Array.|null} [indexesUsed] PlanSummary indexesUsed - */ + /** + * Constructs a new EnumOptions. + * @memberof google.protobuf + * @classdesc Represents an EnumOptions. + * @implements IEnumOptions + * @constructor + * @param {google.protobuf.IEnumOptions=} [properties] Properties to set + */ + function EnumOptions(properties) { + this.uninterpretedOption = []; + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } - /** - * Constructs a new PlanSummary. - * @memberof google.firestore.v1 - * @classdesc Represents a PlanSummary. - * @implements IPlanSummary - * @constructor - * @param {google.firestore.v1.IPlanSummary=} [properties] Properties to set - */ - function PlanSummary(properties) { - this.indexesUsed = []; - if (properties) - for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) - if (properties[keys[i]] != null) - this[keys[i]] = properties[keys[i]]; - } + /** + * EnumOptions allowAlias. + * @member {boolean} allowAlias + * @memberof google.protobuf.EnumOptions + * @instance + */ + EnumOptions.prototype.allowAlias = false; - /** - * PlanSummary indexesUsed. - * @member {Array.} indexesUsed - * @memberof google.firestore.v1.PlanSummary - * @instance - */ - PlanSummary.prototype.indexesUsed = $util.emptyArray; + /** + * EnumOptions deprecated. + * @member {boolean} deprecated + * @memberof google.protobuf.EnumOptions + * @instance + */ + EnumOptions.prototype.deprecated = false; - /** - * Creates a PlanSummary message from a plain object. Also converts values to their respective internal types. - * @function fromObject - * @memberof google.firestore.v1.PlanSummary - * @static - * @param {Object.} object Plain object - * @returns {google.firestore.v1.PlanSummary} PlanSummary - */ - PlanSummary.fromObject = function fromObject(object) { - if (object instanceof $root.google.firestore.v1.PlanSummary) - return object; - var message = new $root.google.firestore.v1.PlanSummary(); - if (object.indexesUsed) { - if (!Array.isArray(object.indexesUsed)) - throw TypeError(".google.firestore.v1.PlanSummary.indexesUsed: array expected"); - message.indexesUsed = []; - for (var i = 0; i < object.indexesUsed.length; ++i) { - if (typeof object.indexesUsed[i] !== "object") - throw TypeError(".google.firestore.v1.PlanSummary.indexesUsed: object expected"); - message.indexesUsed[i] = $root.google.protobuf.Struct.fromObject(object.indexesUsed[i]); - } - } - return message; - }; + /** + * EnumOptions deprecatedLegacyJsonFieldConflicts. + * @member {boolean} deprecatedLegacyJsonFieldConflicts + * @memberof google.protobuf.EnumOptions + * @instance + */ + EnumOptions.prototype.deprecatedLegacyJsonFieldConflicts = false; - /** - * Creates a plain object from a PlanSummary message. Also converts values to other types if specified. - * @function toObject - * @memberof google.firestore.v1.PlanSummary - * @static - * @param {google.firestore.v1.PlanSummary} message PlanSummary - * @param {$protobuf.IConversionOptions} [options] Conversion options - * @returns {Object.} Plain object - */ - PlanSummary.toObject = function toObject(message, options) { - if (!options) - options = {}; - var object = {}; - if (options.arrays || options.defaults) - object.indexesUsed = []; - if (message.indexesUsed && message.indexesUsed.length) { - object.indexesUsed = []; - for (var j = 0; j < message.indexesUsed.length; ++j) - object.indexesUsed[j] = $root.google.protobuf.Struct.toObject(message.indexesUsed[j], options); - } - return object; - }; + /** + * EnumOptions features. + * @member {google.protobuf.IFeatureSet|null|undefined} features + * @memberof google.protobuf.EnumOptions + * @instance + */ + EnumOptions.prototype.features = null; - /** - * Converts this PlanSummary to JSON. - * @function toJSON - * @memberof google.firestore.v1.PlanSummary - * @instance - * @returns {Object.} JSON object - */ - PlanSummary.prototype.toJSON = function toJSON() { - return this.constructor.toObject(this, $protobuf.util.toJSONOptions); - }; + /** + * EnumOptions uninterpretedOption. + * @member {Array.} uninterpretedOption + * @memberof google.protobuf.EnumOptions + * @instance + */ + EnumOptions.prototype.uninterpretedOption = $util.emptyArray; - /** - * Gets the default type url for PlanSummary - * @function getTypeUrl - * @memberof google.firestore.v1.PlanSummary - * @static - * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") - * @returns {string} The default type url - */ - PlanSummary.getTypeUrl = function getTypeUrl(typeUrlPrefix) { - if (typeUrlPrefix === undefined) { - typeUrlPrefix = "type.googleapis.com"; + /** + * Creates an EnumOptions message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.protobuf.EnumOptions + * @static + * @param {Object.} object Plain object + * @returns {google.protobuf.EnumOptions} EnumOptions + */ + EnumOptions.fromObject = function fromObject(object) { + if (object instanceof $root.google.protobuf.EnumOptions) + return object; + var message = new $root.google.protobuf.EnumOptions(); + if (object.allowAlias != null) + message.allowAlias = Boolean(object.allowAlias); + if (object.deprecated != null) + message.deprecated = Boolean(object.deprecated); + if (object.deprecatedLegacyJsonFieldConflicts != null) + message.deprecatedLegacyJsonFieldConflicts = Boolean(object.deprecatedLegacyJsonFieldConflicts); + if (object.features != null) { + if (typeof object.features !== "object") + throw TypeError(".google.protobuf.EnumOptions.features: object expected"); + message.features = $root.google.protobuf.FeatureSet.fromObject(object.features); + } + if (object.uninterpretedOption) { + if (!Array.isArray(object.uninterpretedOption)) + throw TypeError(".google.protobuf.EnumOptions.uninterpretedOption: array expected"); + message.uninterpretedOption = []; + for (var i = 0; i < object.uninterpretedOption.length; ++i) { + if (typeof object.uninterpretedOption[i] !== "object") + throw TypeError(".google.protobuf.EnumOptions.uninterpretedOption: object expected"); + message.uninterpretedOption[i] = $root.google.protobuf.UninterpretedOption.fromObject(object.uninterpretedOption[i]); } - return typeUrlPrefix + "/google.firestore.v1.PlanSummary"; - }; - - return PlanSummary; - })(); + } + return message; + }; - v1.ExecutionStats = (function() { + /** + * Creates a plain object from an EnumOptions message. Also converts values to other types if specified. + * @function toObject + * @memberof google.protobuf.EnumOptions + * @static + * @param {google.protobuf.EnumOptions} message EnumOptions + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + EnumOptions.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.arrays || options.defaults) + object.uninterpretedOption = []; + if (options.defaults) { + object.allowAlias = false; + object.deprecated = false; + object.deprecatedLegacyJsonFieldConflicts = false; + object.features = null; + } + if (message.allowAlias != null && message.hasOwnProperty("allowAlias")) + object.allowAlias = message.allowAlias; + if (message.deprecated != null && message.hasOwnProperty("deprecated")) + object.deprecated = message.deprecated; + if (message.deprecatedLegacyJsonFieldConflicts != null && message.hasOwnProperty("deprecatedLegacyJsonFieldConflicts")) + object.deprecatedLegacyJsonFieldConflicts = message.deprecatedLegacyJsonFieldConflicts; + if (message.features != null && message.hasOwnProperty("features")) + object.features = $root.google.protobuf.FeatureSet.toObject(message.features, options); + if (message.uninterpretedOption && message.uninterpretedOption.length) { + object.uninterpretedOption = []; + for (var j = 0; j < message.uninterpretedOption.length; ++j) + object.uninterpretedOption[j] = $root.google.protobuf.UninterpretedOption.toObject(message.uninterpretedOption[j], options); + } + return object; + }; - /** - * Properties of an ExecutionStats. - * @memberof google.firestore.v1 - * @interface IExecutionStats - * @property {number|string|null} [resultsReturned] ExecutionStats resultsReturned - * @property {google.protobuf.IDuration|null} [executionDuration] ExecutionStats executionDuration - * @property {number|string|null} [readOperations] ExecutionStats readOperations - * @property {google.protobuf.IStruct|null} [debugStats] ExecutionStats debugStats - */ + /** + * Converts this EnumOptions to JSON. + * @function toJSON + * @memberof google.protobuf.EnumOptions + * @instance + * @returns {Object.} JSON object + */ + EnumOptions.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; - /** - * Constructs a new ExecutionStats. - * @memberof google.firestore.v1 - * @classdesc Represents an ExecutionStats. - * @implements IExecutionStats - * @constructor - * @param {google.firestore.v1.IExecutionStats=} [properties] Properties to set - */ - function ExecutionStats(properties) { - if (properties) - for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) - if (properties[keys[i]] != null) - this[keys[i]] = properties[keys[i]]; + /** + * Gets the default type url for EnumOptions + * @function getTypeUrl + * @memberof google.protobuf.EnumOptions + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + EnumOptions.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; } + return typeUrlPrefix + "/google.protobuf.EnumOptions"; + }; - /** - * ExecutionStats resultsReturned. - * @member {number|string} resultsReturned - * @memberof google.firestore.v1.ExecutionStats - * @instance - */ - ExecutionStats.prototype.resultsReturned = $util.Long ? $util.Long.fromBits(0,0,false) : 0; + return EnumOptions; + })(); - /** - * ExecutionStats executionDuration. - * @member {google.protobuf.IDuration|null|undefined} executionDuration - * @memberof google.firestore.v1.ExecutionStats - * @instance - */ - ExecutionStats.prototype.executionDuration = null; + protobuf.EnumValueOptions = (function() { - /** - * ExecutionStats readOperations. - * @member {number|string} readOperations - * @memberof google.firestore.v1.ExecutionStats - * @instance - */ - ExecutionStats.prototype.readOperations = $util.Long ? $util.Long.fromBits(0,0,false) : 0; + /** + * Properties of an EnumValueOptions. + * @memberof google.protobuf + * @interface IEnumValueOptions + * @property {boolean|null} [deprecated] EnumValueOptions deprecated + * @property {google.protobuf.IFeatureSet|null} [features] EnumValueOptions features + * @property {boolean|null} [debugRedact] EnumValueOptions debugRedact + * @property {Array.|null} [uninterpretedOption] EnumValueOptions uninterpretedOption + */ - /** - * ExecutionStats debugStats. - * @member {google.protobuf.IStruct|null|undefined} debugStats - * @memberof google.firestore.v1.ExecutionStats - * @instance - */ - ExecutionStats.prototype.debugStats = null; + /** + * Constructs a new EnumValueOptions. + * @memberof google.protobuf + * @classdesc Represents an EnumValueOptions. + * @implements IEnumValueOptions + * @constructor + * @param {google.protobuf.IEnumValueOptions=} [properties] Properties to set + */ + function EnumValueOptions(properties) { + this.uninterpretedOption = []; + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } - /** - * Creates an ExecutionStats message from a plain object. Also converts values to their respective internal types. - * @function fromObject - * @memberof google.firestore.v1.ExecutionStats - * @static - * @param {Object.} object Plain object - * @returns {google.firestore.v1.ExecutionStats} ExecutionStats - */ - ExecutionStats.fromObject = function fromObject(object) { - if (object instanceof $root.google.firestore.v1.ExecutionStats) - return object; - var message = new $root.google.firestore.v1.ExecutionStats(); - if (object.resultsReturned != null) - if ($util.Long) - (message.resultsReturned = $util.Long.fromValue(object.resultsReturned)).unsigned = false; - else if (typeof object.resultsReturned === "string") - message.resultsReturned = parseInt(object.resultsReturned, 10); - else if (typeof object.resultsReturned === "number") - message.resultsReturned = object.resultsReturned; - else if (typeof object.resultsReturned === "object") - message.resultsReturned = new $util.LongBits(object.resultsReturned.low >>> 0, object.resultsReturned.high >>> 0).toNumber(); - if (object.executionDuration != null) { - if (typeof object.executionDuration !== "object") - throw TypeError(".google.firestore.v1.ExecutionStats.executionDuration: object expected"); - message.executionDuration = $root.google.protobuf.Duration.fromObject(object.executionDuration); - } - if (object.readOperations != null) - if ($util.Long) - (message.readOperations = $util.Long.fromValue(object.readOperations)).unsigned = false; - else if (typeof object.readOperations === "string") - message.readOperations = parseInt(object.readOperations, 10); - else if (typeof object.readOperations === "number") - message.readOperations = object.readOperations; - else if (typeof object.readOperations === "object") - message.readOperations = new $util.LongBits(object.readOperations.low >>> 0, object.readOperations.high >>> 0).toNumber(); - if (object.debugStats != null) { - if (typeof object.debugStats !== "object") - throw TypeError(".google.firestore.v1.ExecutionStats.debugStats: object expected"); - message.debugStats = $root.google.protobuf.Struct.fromObject(object.debugStats); - } - return message; - }; + /** + * EnumValueOptions deprecated. + * @member {boolean} deprecated + * @memberof google.protobuf.EnumValueOptions + * @instance + */ + EnumValueOptions.prototype.deprecated = false; - /** - * Creates a plain object from an ExecutionStats message. Also converts values to other types if specified. - * @function toObject - * @memberof google.firestore.v1.ExecutionStats - * @static - * @param {google.firestore.v1.ExecutionStats} message ExecutionStats - * @param {$protobuf.IConversionOptions} [options] Conversion options - * @returns {Object.} Plain object - */ - ExecutionStats.toObject = function toObject(message, options) { - if (!options) - options = {}; - var object = {}; - if (options.defaults) { - if ($util.Long) { - var long = new $util.Long(0, 0, false); - object.resultsReturned = options.longs === String ? long.toString() : options.longs === Number ? long.toNumber() : long; - } else - object.resultsReturned = options.longs === String ? "0" : 0; - object.executionDuration = null; - if ($util.Long) { - var long = new $util.Long(0, 0, false); - object.readOperations = options.longs === String ? long.toString() : options.longs === Number ? long.toNumber() : long; - } else - object.readOperations = options.longs === String ? "0" : 0; - object.debugStats = null; - } - if (message.resultsReturned != null && message.hasOwnProperty("resultsReturned")) - if (typeof message.resultsReturned === "number") - object.resultsReturned = options.longs === String ? String(message.resultsReturned) : message.resultsReturned; - else - object.resultsReturned = options.longs === String ? $util.Long.prototype.toString.call(message.resultsReturned) : options.longs === Number ? new $util.LongBits(message.resultsReturned.low >>> 0, message.resultsReturned.high >>> 0).toNumber() : message.resultsReturned; - if (message.executionDuration != null && message.hasOwnProperty("executionDuration")) - object.executionDuration = $root.google.protobuf.Duration.toObject(message.executionDuration, options); - if (message.readOperations != null && message.hasOwnProperty("readOperations")) - if (typeof message.readOperations === "number") - object.readOperations = options.longs === String ? String(message.readOperations) : message.readOperations; - else - object.readOperations = options.longs === String ? $util.Long.prototype.toString.call(message.readOperations) : options.longs === Number ? new $util.LongBits(message.readOperations.low >>> 0, message.readOperations.high >>> 0).toNumber() : message.readOperations; - if (message.debugStats != null && message.hasOwnProperty("debugStats")) - object.debugStats = $root.google.protobuf.Struct.toObject(message.debugStats, options); - return object; - }; + /** + * EnumValueOptions features. + * @member {google.protobuf.IFeatureSet|null|undefined} features + * @memberof google.protobuf.EnumValueOptions + * @instance + */ + EnumValueOptions.prototype.features = null; - /** - * Converts this ExecutionStats to JSON. - * @function toJSON - * @memberof google.firestore.v1.ExecutionStats - * @instance - * @returns {Object.} JSON object - */ - ExecutionStats.prototype.toJSON = function toJSON() { - return this.constructor.toObject(this, $protobuf.util.toJSONOptions); - }; + /** + * EnumValueOptions debugRedact. + * @member {boolean} debugRedact + * @memberof google.protobuf.EnumValueOptions + * @instance + */ + EnumValueOptions.prototype.debugRedact = false; - /** - * Gets the default type url for ExecutionStats - * @function getTypeUrl - * @memberof google.firestore.v1.ExecutionStats - * @static - * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") - * @returns {string} The default type url - */ - ExecutionStats.getTypeUrl = function getTypeUrl(typeUrlPrefix) { - if (typeUrlPrefix === undefined) { - typeUrlPrefix = "type.googleapis.com"; + /** + * EnumValueOptions uninterpretedOption. + * @member {Array.} uninterpretedOption + * @memberof google.protobuf.EnumValueOptions + * @instance + */ + EnumValueOptions.prototype.uninterpretedOption = $util.emptyArray; + + /** + * Creates an EnumValueOptions message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.protobuf.EnumValueOptions + * @static + * @param {Object.} object Plain object + * @returns {google.protobuf.EnumValueOptions} EnumValueOptions + */ + EnumValueOptions.fromObject = function fromObject(object) { + if (object instanceof $root.google.protobuf.EnumValueOptions) + return object; + var message = new $root.google.protobuf.EnumValueOptions(); + if (object.deprecated != null) + message.deprecated = Boolean(object.deprecated); + if (object.features != null) { + if (typeof object.features !== "object") + throw TypeError(".google.protobuf.EnumValueOptions.features: object expected"); + message.features = $root.google.protobuf.FeatureSet.fromObject(object.features); + } + if (object.debugRedact != null) + message.debugRedact = Boolean(object.debugRedact); + if (object.uninterpretedOption) { + if (!Array.isArray(object.uninterpretedOption)) + throw TypeError(".google.protobuf.EnumValueOptions.uninterpretedOption: array expected"); + message.uninterpretedOption = []; + for (var i = 0; i < object.uninterpretedOption.length; ++i) { + if (typeof object.uninterpretedOption[i] !== "object") + throw TypeError(".google.protobuf.EnumValueOptions.uninterpretedOption: object expected"); + message.uninterpretedOption[i] = $root.google.protobuf.UninterpretedOption.fromObject(object.uninterpretedOption[i]); } - return typeUrlPrefix + "/google.firestore.v1.ExecutionStats"; - }; - - return ExecutionStats; - })(); + } + return message; + }; - v1.Write = (function() { + /** + * Creates a plain object from an EnumValueOptions message. Also converts values to other types if specified. + * @function toObject + * @memberof google.protobuf.EnumValueOptions + * @static + * @param {google.protobuf.EnumValueOptions} message EnumValueOptions + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + EnumValueOptions.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.arrays || options.defaults) + object.uninterpretedOption = []; + if (options.defaults) { + object.deprecated = false; + object.features = null; + object.debugRedact = false; + } + if (message.deprecated != null && message.hasOwnProperty("deprecated")) + object.deprecated = message.deprecated; + if (message.features != null && message.hasOwnProperty("features")) + object.features = $root.google.protobuf.FeatureSet.toObject(message.features, options); + if (message.debugRedact != null && message.hasOwnProperty("debugRedact")) + object.debugRedact = message.debugRedact; + if (message.uninterpretedOption && message.uninterpretedOption.length) { + object.uninterpretedOption = []; + for (var j = 0; j < message.uninterpretedOption.length; ++j) + object.uninterpretedOption[j] = $root.google.protobuf.UninterpretedOption.toObject(message.uninterpretedOption[j], options); + } + return object; + }; - /** - * Properties of a Write. - * @memberof google.firestore.v1 - * @interface IWrite - * @property {google.firestore.v1.IDocument|null} [update] Write update - * @property {string|null} ["delete"] Write delete - * @property {google.firestore.v1.IDocumentTransform|null} [transform] Write transform - * @property {google.firestore.v1.IDocumentMask|null} [updateMask] Write updateMask - * @property {Array.|null} [updateTransforms] Write updateTransforms - * @property {google.firestore.v1.IPrecondition|null} [currentDocument] Write currentDocument - */ + /** + * Converts this EnumValueOptions to JSON. + * @function toJSON + * @memberof google.protobuf.EnumValueOptions + * @instance + * @returns {Object.} JSON object + */ + EnumValueOptions.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; - /** - * Constructs a new Write. - * @memberof google.firestore.v1 - * @classdesc Represents a Write. - * @implements IWrite - * @constructor - * @param {google.firestore.v1.IWrite=} [properties] Properties to set - */ - function Write(properties) { - this.updateTransforms = []; - if (properties) - for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) - if (properties[keys[i]] != null) - this[keys[i]] = properties[keys[i]]; + /** + * Gets the default type url for EnumValueOptions + * @function getTypeUrl + * @memberof google.protobuf.EnumValueOptions + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + EnumValueOptions.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; } + return typeUrlPrefix + "/google.protobuf.EnumValueOptions"; + }; - /** - * Write update. - * @member {google.firestore.v1.IDocument|null|undefined} update - * @memberof google.firestore.v1.Write - * @instance - */ - Write.prototype.update = null; - - /** - * Write delete. - * @member {string|null|undefined} delete - * @memberof google.firestore.v1.Write - * @instance - */ - Write.prototype["delete"] = null; + return EnumValueOptions; + })(); - /** - * Write transform. - * @member {google.firestore.v1.IDocumentTransform|null|undefined} transform - * @memberof google.firestore.v1.Write - * @instance - */ - Write.prototype.transform = null; + protobuf.ServiceOptions = (function() { - /** - * Write updateMask. - * @member {google.firestore.v1.IDocumentMask|null|undefined} updateMask - * @memberof google.firestore.v1.Write - * @instance - */ - Write.prototype.updateMask = null; + /** + * Properties of a ServiceOptions. + * @memberof google.protobuf + * @interface IServiceOptions + * @property {google.protobuf.IFeatureSet|null} [features] ServiceOptions features + * @property {boolean|null} [deprecated] ServiceOptions deprecated + * @property {Array.|null} [uninterpretedOption] ServiceOptions uninterpretedOption + * @property {string|null} [".google.api.defaultHost"] ServiceOptions .google.api.defaultHost + * @property {string|null} [".google.api.oauthScopes"] ServiceOptions .google.api.oauthScopes + * @property {string|null} [".google.api.apiVersion"] ServiceOptions .google.api.apiVersion + */ - /** - * Write updateTransforms. - * @member {Array.} updateTransforms - * @memberof google.firestore.v1.Write - * @instance - */ - Write.prototype.updateTransforms = $util.emptyArray; + /** + * Constructs a new ServiceOptions. + * @memberof google.protobuf + * @classdesc Represents a ServiceOptions. + * @implements IServiceOptions + * @constructor + * @param {google.protobuf.IServiceOptions=} [properties] Properties to set + */ + function ServiceOptions(properties) { + this.uninterpretedOption = []; + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } - /** - * Write currentDocument. - * @member {google.firestore.v1.IPrecondition|null|undefined} currentDocument - * @memberof google.firestore.v1.Write - * @instance - */ - Write.prototype.currentDocument = null; + /** + * ServiceOptions features. + * @member {google.protobuf.IFeatureSet|null|undefined} features + * @memberof google.protobuf.ServiceOptions + * @instance + */ + ServiceOptions.prototype.features = null; - // OneOf field names bound to virtual getters and setters - var $oneOfFields; + /** + * ServiceOptions deprecated. + * @member {boolean} deprecated + * @memberof google.protobuf.ServiceOptions + * @instance + */ + ServiceOptions.prototype.deprecated = false; - /** - * Write operation. - * @member {"update"|"delete"|"transform"|undefined} operation - * @memberof google.firestore.v1.Write - * @instance - */ - Object.defineProperty(Write.prototype, "operation", { - get: $util.oneOfGetter($oneOfFields = ["update", "delete", "transform"]), - set: $util.oneOfSetter($oneOfFields) - }); + /** + * ServiceOptions uninterpretedOption. + * @member {Array.} uninterpretedOption + * @memberof google.protobuf.ServiceOptions + * @instance + */ + ServiceOptions.prototype.uninterpretedOption = $util.emptyArray; - /** - * Creates a Write message from a plain object. Also converts values to their respective internal types. - * @function fromObject - * @memberof google.firestore.v1.Write - * @static - * @param {Object.} object Plain object - * @returns {google.firestore.v1.Write} Write - */ - Write.fromObject = function fromObject(object) { - if (object instanceof $root.google.firestore.v1.Write) - return object; - var message = new $root.google.firestore.v1.Write(); - if (object.update != null) { - if (typeof object.update !== "object") - throw TypeError(".google.firestore.v1.Write.update: object expected"); - message.update = $root.google.firestore.v1.Document.fromObject(object.update); - } - if (object["delete"] != null) - message["delete"] = String(object["delete"]); - if (object.transform != null) { - if (typeof object.transform !== "object") - throw TypeError(".google.firestore.v1.Write.transform: object expected"); - message.transform = $root.google.firestore.v1.DocumentTransform.fromObject(object.transform); - } - if (object.updateMask != null) { - if (typeof object.updateMask !== "object") - throw TypeError(".google.firestore.v1.Write.updateMask: object expected"); - message.updateMask = $root.google.firestore.v1.DocumentMask.fromObject(object.updateMask); - } - if (object.updateTransforms) { - if (!Array.isArray(object.updateTransforms)) - throw TypeError(".google.firestore.v1.Write.updateTransforms: array expected"); - message.updateTransforms = []; - for (var i = 0; i < object.updateTransforms.length; ++i) { - if (typeof object.updateTransforms[i] !== "object") - throw TypeError(".google.firestore.v1.Write.updateTransforms: object expected"); - message.updateTransforms[i] = $root.google.firestore.v1.DocumentTransform.FieldTransform.fromObject(object.updateTransforms[i]); - } - } - if (object.currentDocument != null) { - if (typeof object.currentDocument !== "object") - throw TypeError(".google.firestore.v1.Write.currentDocument: object expected"); - message.currentDocument = $root.google.firestore.v1.Precondition.fromObject(object.currentDocument); - } - return message; - }; + /** + * ServiceOptions .google.api.defaultHost. + * @member {string} .google.api.defaultHost + * @memberof google.protobuf.ServiceOptions + * @instance + */ + ServiceOptions.prototype[".google.api.defaultHost"] = ""; - /** - * Creates a plain object from a Write message. Also converts values to other types if specified. - * @function toObject - * @memberof google.firestore.v1.Write - * @static - * @param {google.firestore.v1.Write} message Write - * @param {$protobuf.IConversionOptions} [options] Conversion options - * @returns {Object.} Plain object - */ - Write.toObject = function toObject(message, options) { - if (!options) - options = {}; - var object = {}; - if (options.arrays || options.defaults) - object.updateTransforms = []; - if (options.defaults) { - object.updateMask = null; - object.currentDocument = null; - } - if (message.update != null && message.hasOwnProperty("update")) { - object.update = $root.google.firestore.v1.Document.toObject(message.update, options); - if (options.oneofs) - object.operation = "update"; - } - if (message["delete"] != null && message.hasOwnProperty("delete")) { - object["delete"] = message["delete"]; - if (options.oneofs) - object.operation = "delete"; - } - if (message.updateMask != null && message.hasOwnProperty("updateMask")) - object.updateMask = $root.google.firestore.v1.DocumentMask.toObject(message.updateMask, options); - if (message.currentDocument != null && message.hasOwnProperty("currentDocument")) - object.currentDocument = $root.google.firestore.v1.Precondition.toObject(message.currentDocument, options); - if (message.transform != null && message.hasOwnProperty("transform")) { - object.transform = $root.google.firestore.v1.DocumentTransform.toObject(message.transform, options); - if (options.oneofs) - object.operation = "transform"; - } - if (message.updateTransforms && message.updateTransforms.length) { - object.updateTransforms = []; - for (var j = 0; j < message.updateTransforms.length; ++j) - object.updateTransforms[j] = $root.google.firestore.v1.DocumentTransform.FieldTransform.toObject(message.updateTransforms[j], options); - } - return object; - }; + /** + * ServiceOptions .google.api.oauthScopes. + * @member {string} .google.api.oauthScopes + * @memberof google.protobuf.ServiceOptions + * @instance + */ + ServiceOptions.prototype[".google.api.oauthScopes"] = ""; - /** - * Converts this Write to JSON. - * @function toJSON - * @memberof google.firestore.v1.Write - * @instance - * @returns {Object.} JSON object - */ - Write.prototype.toJSON = function toJSON() { - return this.constructor.toObject(this, $protobuf.util.toJSONOptions); - }; + /** + * ServiceOptions .google.api.apiVersion. + * @member {string} .google.api.apiVersion + * @memberof google.protobuf.ServiceOptions + * @instance + */ + ServiceOptions.prototype[".google.api.apiVersion"] = ""; - /** - * Gets the default type url for Write - * @function getTypeUrl - * @memberof google.firestore.v1.Write - * @static - * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") - * @returns {string} The default type url - */ - Write.getTypeUrl = function getTypeUrl(typeUrlPrefix) { - if (typeUrlPrefix === undefined) { - typeUrlPrefix = "type.googleapis.com"; + /** + * Creates a ServiceOptions message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.protobuf.ServiceOptions + * @static + * @param {Object.} object Plain object + * @returns {google.protobuf.ServiceOptions} ServiceOptions + */ + ServiceOptions.fromObject = function fromObject(object) { + if (object instanceof $root.google.protobuf.ServiceOptions) + return object; + var message = new $root.google.protobuf.ServiceOptions(); + if (object.features != null) { + if (typeof object.features !== "object") + throw TypeError(".google.protobuf.ServiceOptions.features: object expected"); + message.features = $root.google.protobuf.FeatureSet.fromObject(object.features); + } + if (object.deprecated != null) + message.deprecated = Boolean(object.deprecated); + if (object.uninterpretedOption) { + if (!Array.isArray(object.uninterpretedOption)) + throw TypeError(".google.protobuf.ServiceOptions.uninterpretedOption: array expected"); + message.uninterpretedOption = []; + for (var i = 0; i < object.uninterpretedOption.length; ++i) { + if (typeof object.uninterpretedOption[i] !== "object") + throw TypeError(".google.protobuf.ServiceOptions.uninterpretedOption: object expected"); + message.uninterpretedOption[i] = $root.google.protobuf.UninterpretedOption.fromObject(object.uninterpretedOption[i]); } - return typeUrlPrefix + "/google.firestore.v1.Write"; - }; - - return Write; - })(); + } + if (object[".google.api.defaultHost"] != null) + message[".google.api.defaultHost"] = String(object[".google.api.defaultHost"]); + if (object[".google.api.oauthScopes"] != null) + message[".google.api.oauthScopes"] = String(object[".google.api.oauthScopes"]); + if (object[".google.api.apiVersion"] != null) + message[".google.api.apiVersion"] = String(object[".google.api.apiVersion"]); + return message; + }; - v1.DocumentTransform = (function() { + /** + * Creates a plain object from a ServiceOptions message. Also converts values to other types if specified. + * @function toObject + * @memberof google.protobuf.ServiceOptions + * @static + * @param {google.protobuf.ServiceOptions} message ServiceOptions + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + ServiceOptions.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.arrays || options.defaults) + object.uninterpretedOption = []; + if (options.defaults) { + object.deprecated = false; + object.features = null; + object[".google.api.defaultHost"] = ""; + object[".google.api.oauthScopes"] = ""; + object[".google.api.apiVersion"] = ""; + } + if (message.deprecated != null && message.hasOwnProperty("deprecated")) + object.deprecated = message.deprecated; + if (message.features != null && message.hasOwnProperty("features")) + object.features = $root.google.protobuf.FeatureSet.toObject(message.features, options); + if (message.uninterpretedOption && message.uninterpretedOption.length) { + object.uninterpretedOption = []; + for (var j = 0; j < message.uninterpretedOption.length; ++j) + object.uninterpretedOption[j] = $root.google.protobuf.UninterpretedOption.toObject(message.uninterpretedOption[j], options); + } + if (message[".google.api.defaultHost"] != null && message.hasOwnProperty(".google.api.defaultHost")) + object[".google.api.defaultHost"] = message[".google.api.defaultHost"]; + if (message[".google.api.oauthScopes"] != null && message.hasOwnProperty(".google.api.oauthScopes")) + object[".google.api.oauthScopes"] = message[".google.api.oauthScopes"]; + if (message[".google.api.apiVersion"] != null && message.hasOwnProperty(".google.api.apiVersion")) + object[".google.api.apiVersion"] = message[".google.api.apiVersion"]; + return object; + }; - /** - * Properties of a DocumentTransform. - * @memberof google.firestore.v1 - * @interface IDocumentTransform - * @property {string|null} [document] DocumentTransform document - * @property {Array.|null} [fieldTransforms] DocumentTransform fieldTransforms - */ + /** + * Converts this ServiceOptions to JSON. + * @function toJSON + * @memberof google.protobuf.ServiceOptions + * @instance + * @returns {Object.} JSON object + */ + ServiceOptions.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; - /** - * Constructs a new DocumentTransform. - * @memberof google.firestore.v1 - * @classdesc Represents a DocumentTransform. - * @implements IDocumentTransform - * @constructor - * @param {google.firestore.v1.IDocumentTransform=} [properties] Properties to set - */ - function DocumentTransform(properties) { - this.fieldTransforms = []; - if (properties) - for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) - if (properties[keys[i]] != null) - this[keys[i]] = properties[keys[i]]; + /** + * Gets the default type url for ServiceOptions + * @function getTypeUrl + * @memberof google.protobuf.ServiceOptions + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + ServiceOptions.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; } + return typeUrlPrefix + "/google.protobuf.ServiceOptions"; + }; - /** - * DocumentTransform document. - * @member {string} document - * @memberof google.firestore.v1.DocumentTransform - * @instance - */ - DocumentTransform.prototype.document = ""; + return ServiceOptions; + })(); - /** - * DocumentTransform fieldTransforms. - * @member {Array.} fieldTransforms - * @memberof google.firestore.v1.DocumentTransform - * @instance - */ - DocumentTransform.prototype.fieldTransforms = $util.emptyArray; + protobuf.MethodOptions = (function() { + + /** + * Properties of a MethodOptions. + * @memberof google.protobuf + * @interface IMethodOptions + * @property {boolean|null} [deprecated] MethodOptions deprecated + * @property {google.protobuf.MethodOptions.IdempotencyLevel|null} [idempotencyLevel] MethodOptions idempotencyLevel + * @property {google.protobuf.IFeatureSet|null} [features] MethodOptions features + * @property {Array.|null} [uninterpretedOption] MethodOptions uninterpretedOption + * @property {google.api.IHttpRule|null} [".google.api.http"] MethodOptions .google.api.http + * @property {Array.|null} [".google.api.methodSignature"] MethodOptions .google.api.methodSignature + * @property {google.longrunning.IOperationInfo|null} [".google.longrunning.operationInfo"] MethodOptions .google.longrunning.operationInfo + */ + + /** + * Constructs a new MethodOptions. + * @memberof google.protobuf + * @classdesc Represents a MethodOptions. + * @implements IMethodOptions + * @constructor + * @param {google.protobuf.IMethodOptions=} [properties] Properties to set + */ + function MethodOptions(properties) { + this.uninterpretedOption = []; + this[".google.api.methodSignature"] = []; + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } - /** - * Creates a DocumentTransform message from a plain object. Also converts values to their respective internal types. - * @function fromObject - * @memberof google.firestore.v1.DocumentTransform - * @static - * @param {Object.} object Plain object - * @returns {google.firestore.v1.DocumentTransform} DocumentTransform - */ - DocumentTransform.fromObject = function fromObject(object) { - if (object instanceof $root.google.firestore.v1.DocumentTransform) - return object; - var message = new $root.google.firestore.v1.DocumentTransform(); - if (object.document != null) - message.document = String(object.document); - if (object.fieldTransforms) { - if (!Array.isArray(object.fieldTransforms)) - throw TypeError(".google.firestore.v1.DocumentTransform.fieldTransforms: array expected"); - message.fieldTransforms = []; - for (var i = 0; i < object.fieldTransforms.length; ++i) { - if (typeof object.fieldTransforms[i] !== "object") - throw TypeError(".google.firestore.v1.DocumentTransform.fieldTransforms: object expected"); - message.fieldTransforms[i] = $root.google.firestore.v1.DocumentTransform.FieldTransform.fromObject(object.fieldTransforms[i]); - } - } - return message; - }; + /** + * MethodOptions deprecated. + * @member {boolean} deprecated + * @memberof google.protobuf.MethodOptions + * @instance + */ + MethodOptions.prototype.deprecated = false; - /** - * Creates a plain object from a DocumentTransform message. Also converts values to other types if specified. - * @function toObject - * @memberof google.firestore.v1.DocumentTransform - * @static - * @param {google.firestore.v1.DocumentTransform} message DocumentTransform - * @param {$protobuf.IConversionOptions} [options] Conversion options - * @returns {Object.} Plain object - */ - DocumentTransform.toObject = function toObject(message, options) { - if (!options) - options = {}; - var object = {}; - if (options.arrays || options.defaults) - object.fieldTransforms = []; - if (options.defaults) - object.document = ""; - if (message.document != null && message.hasOwnProperty("document")) - object.document = message.document; - if (message.fieldTransforms && message.fieldTransforms.length) { - object.fieldTransforms = []; - for (var j = 0; j < message.fieldTransforms.length; ++j) - object.fieldTransforms[j] = $root.google.firestore.v1.DocumentTransform.FieldTransform.toObject(message.fieldTransforms[j], options); - } - return object; - }; + /** + * MethodOptions idempotencyLevel. + * @member {google.protobuf.MethodOptions.IdempotencyLevel} idempotencyLevel + * @memberof google.protobuf.MethodOptions + * @instance + */ + MethodOptions.prototype.idempotencyLevel = 0; - /** - * Converts this DocumentTransform to JSON. - * @function toJSON - * @memberof google.firestore.v1.DocumentTransform - * @instance - * @returns {Object.} JSON object - */ - DocumentTransform.prototype.toJSON = function toJSON() { - return this.constructor.toObject(this, $protobuf.util.toJSONOptions); - }; + /** + * MethodOptions features. + * @member {google.protobuf.IFeatureSet|null|undefined} features + * @memberof google.protobuf.MethodOptions + * @instance + */ + MethodOptions.prototype.features = null; - /** - * Gets the default type url for DocumentTransform - * @function getTypeUrl - * @memberof google.firestore.v1.DocumentTransform - * @static - * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") - * @returns {string} The default type url - */ - DocumentTransform.getTypeUrl = function getTypeUrl(typeUrlPrefix) { - if (typeUrlPrefix === undefined) { - typeUrlPrefix = "type.googleapis.com"; - } - return typeUrlPrefix + "/google.firestore.v1.DocumentTransform"; - }; + /** + * MethodOptions uninterpretedOption. + * @member {Array.} uninterpretedOption + * @memberof google.protobuf.MethodOptions + * @instance + */ + MethodOptions.prototype.uninterpretedOption = $util.emptyArray; - DocumentTransform.FieldTransform = (function() { + /** + * MethodOptions .google.api.http. + * @member {google.api.IHttpRule|null|undefined} .google.api.http + * @memberof google.protobuf.MethodOptions + * @instance + */ + MethodOptions.prototype[".google.api.http"] = null; - /** - * Properties of a FieldTransform. - * @memberof google.firestore.v1.DocumentTransform - * @interface IFieldTransform - * @property {string|null} [fieldPath] FieldTransform fieldPath - * @property {google.firestore.v1.DocumentTransform.FieldTransform.ServerValue|null} [setToServerValue] FieldTransform setToServerValue - * @property {google.firestore.v1.IValue|null} [increment] FieldTransform increment - * @property {google.firestore.v1.IValue|null} [maximum] FieldTransform maximum - * @property {google.firestore.v1.IValue|null} [minimum] FieldTransform minimum - * @property {google.firestore.v1.IArrayValue|null} [appendMissingElements] FieldTransform appendMissingElements - * @property {google.firestore.v1.IArrayValue|null} [removeAllFromArray] FieldTransform removeAllFromArray - */ + /** + * MethodOptions .google.api.methodSignature. + * @member {Array.} .google.api.methodSignature + * @memberof google.protobuf.MethodOptions + * @instance + */ + MethodOptions.prototype[".google.api.methodSignature"] = $util.emptyArray; - /** - * Constructs a new FieldTransform. - * @memberof google.firestore.v1.DocumentTransform - * @classdesc Represents a FieldTransform. - * @implements IFieldTransform - * @constructor - * @param {google.firestore.v1.DocumentTransform.IFieldTransform=} [properties] Properties to set - */ - function FieldTransform(properties) { - if (properties) - for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) - if (properties[keys[i]] != null) - this[keys[i]] = properties[keys[i]]; - } + /** + * MethodOptions .google.longrunning.operationInfo. + * @member {google.longrunning.IOperationInfo|null|undefined} .google.longrunning.operationInfo + * @memberof google.protobuf.MethodOptions + * @instance + */ + MethodOptions.prototype[".google.longrunning.operationInfo"] = null; - /** - * FieldTransform fieldPath. - * @member {string} fieldPath - * @memberof google.firestore.v1.DocumentTransform.FieldTransform - * @instance - */ - FieldTransform.prototype.fieldPath = ""; + /** + * Creates a MethodOptions message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.protobuf.MethodOptions + * @static + * @param {Object.} object Plain object + * @returns {google.protobuf.MethodOptions} MethodOptions + */ + MethodOptions.fromObject = function fromObject(object) { + if (object instanceof $root.google.protobuf.MethodOptions) + return object; + var message = new $root.google.protobuf.MethodOptions(); + if (object.deprecated != null) + message.deprecated = Boolean(object.deprecated); + switch (object.idempotencyLevel) { + default: + if (typeof object.idempotencyLevel === "number") { + message.idempotencyLevel = object.idempotencyLevel; + break; + } + break; + case "IDEMPOTENCY_UNKNOWN": + case 0: + message.idempotencyLevel = 0; + break; + case "NO_SIDE_EFFECTS": + case 1: + message.idempotencyLevel = 1; + break; + case "IDEMPOTENT": + case 2: + message.idempotencyLevel = 2; + break; + } + if (object.features != null) { + if (typeof object.features !== "object") + throw TypeError(".google.protobuf.MethodOptions.features: object expected"); + message.features = $root.google.protobuf.FeatureSet.fromObject(object.features); + } + if (object.uninterpretedOption) { + if (!Array.isArray(object.uninterpretedOption)) + throw TypeError(".google.protobuf.MethodOptions.uninterpretedOption: array expected"); + message.uninterpretedOption = []; + for (var i = 0; i < object.uninterpretedOption.length; ++i) { + if (typeof object.uninterpretedOption[i] !== "object") + throw TypeError(".google.protobuf.MethodOptions.uninterpretedOption: object expected"); + message.uninterpretedOption[i] = $root.google.protobuf.UninterpretedOption.fromObject(object.uninterpretedOption[i]); + } + } + if (object[".google.api.http"] != null) { + if (typeof object[".google.api.http"] !== "object") + throw TypeError(".google.protobuf.MethodOptions..google.api.http: object expected"); + message[".google.api.http"] = $root.google.api.HttpRule.fromObject(object[".google.api.http"]); + } + if (object[".google.api.methodSignature"]) { + if (!Array.isArray(object[".google.api.methodSignature"])) + throw TypeError(".google.protobuf.MethodOptions..google.api.methodSignature: array expected"); + message[".google.api.methodSignature"] = []; + for (var i = 0; i < object[".google.api.methodSignature"].length; ++i) + message[".google.api.methodSignature"][i] = String(object[".google.api.methodSignature"][i]); + } + if (object[".google.longrunning.operationInfo"] != null) { + if (typeof object[".google.longrunning.operationInfo"] !== "object") + throw TypeError(".google.protobuf.MethodOptions..google.longrunning.operationInfo: object expected"); + message[".google.longrunning.operationInfo"] = $root.google.longrunning.OperationInfo.fromObject(object[".google.longrunning.operationInfo"]); + } + return message; + }; - /** - * FieldTransform setToServerValue. - * @member {google.firestore.v1.DocumentTransform.FieldTransform.ServerValue|null|undefined} setToServerValue - * @memberof google.firestore.v1.DocumentTransform.FieldTransform - * @instance - */ - FieldTransform.prototype.setToServerValue = null; + /** + * Creates a plain object from a MethodOptions message. Also converts values to other types if specified. + * @function toObject + * @memberof google.protobuf.MethodOptions + * @static + * @param {google.protobuf.MethodOptions} message MethodOptions + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + MethodOptions.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.arrays || options.defaults) { + object.uninterpretedOption = []; + object[".google.api.methodSignature"] = []; + } + if (options.defaults) { + object.deprecated = false; + object.idempotencyLevel = options.enums === String ? "IDEMPOTENCY_UNKNOWN" : 0; + object.features = null; + object[".google.longrunning.operationInfo"] = null; + object[".google.api.http"] = null; + } + if (message.deprecated != null && message.hasOwnProperty("deprecated")) + object.deprecated = message.deprecated; + if (message.idempotencyLevel != null && message.hasOwnProperty("idempotencyLevel")) + object.idempotencyLevel = options.enums === String ? $root.google.protobuf.MethodOptions.IdempotencyLevel[message.idempotencyLevel] === undefined ? message.idempotencyLevel : $root.google.protobuf.MethodOptions.IdempotencyLevel[message.idempotencyLevel] : message.idempotencyLevel; + if (message.features != null && message.hasOwnProperty("features")) + object.features = $root.google.protobuf.FeatureSet.toObject(message.features, options); + if (message.uninterpretedOption && message.uninterpretedOption.length) { + object.uninterpretedOption = []; + for (var j = 0; j < message.uninterpretedOption.length; ++j) + object.uninterpretedOption[j] = $root.google.protobuf.UninterpretedOption.toObject(message.uninterpretedOption[j], options); + } + if (message[".google.longrunning.operationInfo"] != null && message.hasOwnProperty(".google.longrunning.operationInfo")) + object[".google.longrunning.operationInfo"] = $root.google.longrunning.OperationInfo.toObject(message[".google.longrunning.operationInfo"], options); + if (message[".google.api.methodSignature"] && message[".google.api.methodSignature"].length) { + object[".google.api.methodSignature"] = []; + for (var j = 0; j < message[".google.api.methodSignature"].length; ++j) + object[".google.api.methodSignature"][j] = message[".google.api.methodSignature"][j]; + } + if (message[".google.api.http"] != null && message.hasOwnProperty(".google.api.http")) + object[".google.api.http"] = $root.google.api.HttpRule.toObject(message[".google.api.http"], options); + return object; + }; - /** - * FieldTransform increment. - * @member {google.firestore.v1.IValue|null|undefined} increment - * @memberof google.firestore.v1.DocumentTransform.FieldTransform - * @instance - */ - FieldTransform.prototype.increment = null; + /** + * Converts this MethodOptions to JSON. + * @function toJSON + * @memberof google.protobuf.MethodOptions + * @instance + * @returns {Object.} JSON object + */ + MethodOptions.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; - /** - * FieldTransform maximum. - * @member {google.firestore.v1.IValue|null|undefined} maximum - * @memberof google.firestore.v1.DocumentTransform.FieldTransform - * @instance - */ - FieldTransform.prototype.maximum = null; + /** + * Gets the default type url for MethodOptions + * @function getTypeUrl + * @memberof google.protobuf.MethodOptions + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + MethodOptions.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.protobuf.MethodOptions"; + }; - /** - * FieldTransform minimum. - * @member {google.firestore.v1.IValue|null|undefined} minimum - * @memberof google.firestore.v1.DocumentTransform.FieldTransform - * @instance - */ - FieldTransform.prototype.minimum = null; + /** + * IdempotencyLevel enum. + * @name google.protobuf.MethodOptions.IdempotencyLevel + * @enum {string} + * @property {string} IDEMPOTENCY_UNKNOWN=IDEMPOTENCY_UNKNOWN IDEMPOTENCY_UNKNOWN value + * @property {string} NO_SIDE_EFFECTS=NO_SIDE_EFFECTS NO_SIDE_EFFECTS value + * @property {string} IDEMPOTENT=IDEMPOTENT IDEMPOTENT value + */ + MethodOptions.IdempotencyLevel = (function() { + var valuesById = {}, values = Object.create(valuesById); + values[valuesById[0] = "IDEMPOTENCY_UNKNOWN"] = "IDEMPOTENCY_UNKNOWN"; + values[valuesById[1] = "NO_SIDE_EFFECTS"] = "NO_SIDE_EFFECTS"; + values[valuesById[2] = "IDEMPOTENT"] = "IDEMPOTENT"; + return values; + })(); - /** - * FieldTransform appendMissingElements. - * @member {google.firestore.v1.IArrayValue|null|undefined} appendMissingElements - * @memberof google.firestore.v1.DocumentTransform.FieldTransform - * @instance - */ - FieldTransform.prototype.appendMissingElements = null; + return MethodOptions; + })(); - /** - * FieldTransform removeAllFromArray. - * @member {google.firestore.v1.IArrayValue|null|undefined} removeAllFromArray - * @memberof google.firestore.v1.DocumentTransform.FieldTransform - * @instance - */ - FieldTransform.prototype.removeAllFromArray = null; + protobuf.UninterpretedOption = (function() { - // OneOf field names bound to virtual getters and setters - var $oneOfFields; + /** + * Properties of an UninterpretedOption. + * @memberof google.protobuf + * @interface IUninterpretedOption + * @property {Array.|null} [name] UninterpretedOption name + * @property {string|null} [identifierValue] UninterpretedOption identifierValue + * @property {number|string|null} [positiveIntValue] UninterpretedOption positiveIntValue + * @property {number|string|null} [negativeIntValue] UninterpretedOption negativeIntValue + * @property {number|null} [doubleValue] UninterpretedOption doubleValue + * @property {Uint8Array|null} [stringValue] UninterpretedOption stringValue + * @property {string|null} [aggregateValue] UninterpretedOption aggregateValue + */ - /** - * FieldTransform transformType. - * @member {"setToServerValue"|"increment"|"maximum"|"minimum"|"appendMissingElements"|"removeAllFromArray"|undefined} transformType - * @memberof google.firestore.v1.DocumentTransform.FieldTransform - * @instance - */ - Object.defineProperty(FieldTransform.prototype, "transformType", { - get: $util.oneOfGetter($oneOfFields = ["setToServerValue", "increment", "maximum", "minimum", "appendMissingElements", "removeAllFromArray"]), - set: $util.oneOfSetter($oneOfFields) - }); + /** + * Constructs a new UninterpretedOption. + * @memberof google.protobuf + * @classdesc Represents an UninterpretedOption. + * @implements IUninterpretedOption + * @constructor + * @param {google.protobuf.IUninterpretedOption=} [properties] Properties to set + */ + function UninterpretedOption(properties) { + this.name = []; + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } - /** - * Creates a FieldTransform message from a plain object. Also converts values to their respective internal types. - * @function fromObject - * @memberof google.firestore.v1.DocumentTransform.FieldTransform - * @static - * @param {Object.} object Plain object - * @returns {google.firestore.v1.DocumentTransform.FieldTransform} FieldTransform - */ - FieldTransform.fromObject = function fromObject(object) { - if (object instanceof $root.google.firestore.v1.DocumentTransform.FieldTransform) - return object; - var message = new $root.google.firestore.v1.DocumentTransform.FieldTransform(); - if (object.fieldPath != null) - message.fieldPath = String(object.fieldPath); - switch (object.setToServerValue) { - default: - if (typeof object.setToServerValue === "number") { - message.setToServerValue = object.setToServerValue; - break; - } - break; - case "SERVER_VALUE_UNSPECIFIED": - case 0: - message.setToServerValue = 0; - break; - case "REQUEST_TIME": - case 1: - message.setToServerValue = 1; - break; - } - if (object.increment != null) { - if (typeof object.increment !== "object") - throw TypeError(".google.firestore.v1.DocumentTransform.FieldTransform.increment: object expected"); - message.increment = $root.google.firestore.v1.Value.fromObject(object.increment); - } - if (object.maximum != null) { - if (typeof object.maximum !== "object") - throw TypeError(".google.firestore.v1.DocumentTransform.FieldTransform.maximum: object expected"); - message.maximum = $root.google.firestore.v1.Value.fromObject(object.maximum); - } - if (object.minimum != null) { - if (typeof object.minimum !== "object") - throw TypeError(".google.firestore.v1.DocumentTransform.FieldTransform.minimum: object expected"); - message.minimum = $root.google.firestore.v1.Value.fromObject(object.minimum); - } - if (object.appendMissingElements != null) { - if (typeof object.appendMissingElements !== "object") - throw TypeError(".google.firestore.v1.DocumentTransform.FieldTransform.appendMissingElements: object expected"); - message.appendMissingElements = $root.google.firestore.v1.ArrayValue.fromObject(object.appendMissingElements); - } - if (object.removeAllFromArray != null) { - if (typeof object.removeAllFromArray !== "object") - throw TypeError(".google.firestore.v1.DocumentTransform.FieldTransform.removeAllFromArray: object expected"); - message.removeAllFromArray = $root.google.firestore.v1.ArrayValue.fromObject(object.removeAllFromArray); - } - return message; - }; + /** + * UninterpretedOption name. + * @member {Array.} name + * @memberof google.protobuf.UninterpretedOption + * @instance + */ + UninterpretedOption.prototype.name = $util.emptyArray; - /** - * Creates a plain object from a FieldTransform message. Also converts values to other types if specified. - * @function toObject - * @memberof google.firestore.v1.DocumentTransform.FieldTransform - * @static - * @param {google.firestore.v1.DocumentTransform.FieldTransform} message FieldTransform - * @param {$protobuf.IConversionOptions} [options] Conversion options - * @returns {Object.} Plain object - */ - FieldTransform.toObject = function toObject(message, options) { - if (!options) - options = {}; - var object = {}; - if (options.defaults) - object.fieldPath = ""; - if (message.fieldPath != null && message.hasOwnProperty("fieldPath")) - object.fieldPath = message.fieldPath; - if (message.setToServerValue != null && message.hasOwnProperty("setToServerValue")) { - object.setToServerValue = options.enums === String ? $root.google.firestore.v1.DocumentTransform.FieldTransform.ServerValue[message.setToServerValue] === undefined ? message.setToServerValue : $root.google.firestore.v1.DocumentTransform.FieldTransform.ServerValue[message.setToServerValue] : message.setToServerValue; - if (options.oneofs) - object.transformType = "setToServerValue"; - } - if (message.increment != null && message.hasOwnProperty("increment")) { - object.increment = $root.google.firestore.v1.Value.toObject(message.increment, options); - if (options.oneofs) - object.transformType = "increment"; - } - if (message.maximum != null && message.hasOwnProperty("maximum")) { - object.maximum = $root.google.firestore.v1.Value.toObject(message.maximum, options); - if (options.oneofs) - object.transformType = "maximum"; - } - if (message.minimum != null && message.hasOwnProperty("minimum")) { - object.minimum = $root.google.firestore.v1.Value.toObject(message.minimum, options); - if (options.oneofs) - object.transformType = "minimum"; - } - if (message.appendMissingElements != null && message.hasOwnProperty("appendMissingElements")) { - object.appendMissingElements = $root.google.firestore.v1.ArrayValue.toObject(message.appendMissingElements, options); - if (options.oneofs) - object.transformType = "appendMissingElements"; - } - if (message.removeAllFromArray != null && message.hasOwnProperty("removeAllFromArray")) { - object.removeAllFromArray = $root.google.firestore.v1.ArrayValue.toObject(message.removeAllFromArray, options); - if (options.oneofs) - object.transformType = "removeAllFromArray"; - } - return object; - }; + /** + * UninterpretedOption identifierValue. + * @member {string} identifierValue + * @memberof google.protobuf.UninterpretedOption + * @instance + */ + UninterpretedOption.prototype.identifierValue = ""; - /** - * Converts this FieldTransform to JSON. - * @function toJSON - * @memberof google.firestore.v1.DocumentTransform.FieldTransform - * @instance - * @returns {Object.} JSON object - */ - FieldTransform.prototype.toJSON = function toJSON() { - return this.constructor.toObject(this, $protobuf.util.toJSONOptions); - }; + /** + * UninterpretedOption positiveIntValue. + * @member {number|string} positiveIntValue + * @memberof google.protobuf.UninterpretedOption + * @instance + */ + UninterpretedOption.prototype.positiveIntValue = $util.Long ? $util.Long.fromBits(0,0,true) : 0; - /** - * Gets the default type url for FieldTransform - * @function getTypeUrl - * @memberof google.firestore.v1.DocumentTransform.FieldTransform - * @static - * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") - * @returns {string} The default type url - */ - FieldTransform.getTypeUrl = function getTypeUrl(typeUrlPrefix) { - if (typeUrlPrefix === undefined) { - typeUrlPrefix = "type.googleapis.com"; - } - return typeUrlPrefix + "/google.firestore.v1.DocumentTransform.FieldTransform"; - }; + /** + * UninterpretedOption negativeIntValue. + * @member {number|string} negativeIntValue + * @memberof google.protobuf.UninterpretedOption + * @instance + */ + UninterpretedOption.prototype.negativeIntValue = $util.Long ? $util.Long.fromBits(0,0,false) : 0; - /** - * ServerValue enum. - * @name google.firestore.v1.DocumentTransform.FieldTransform.ServerValue - * @enum {string} - * @property {string} SERVER_VALUE_UNSPECIFIED=SERVER_VALUE_UNSPECIFIED SERVER_VALUE_UNSPECIFIED value - * @property {string} REQUEST_TIME=REQUEST_TIME REQUEST_TIME value - */ - FieldTransform.ServerValue = (function() { - var valuesById = {}, values = Object.create(valuesById); - values[valuesById[0] = "SERVER_VALUE_UNSPECIFIED"] = "SERVER_VALUE_UNSPECIFIED"; - values[valuesById[1] = "REQUEST_TIME"] = "REQUEST_TIME"; - return values; - })(); + /** + * UninterpretedOption doubleValue. + * @member {number} doubleValue + * @memberof google.protobuf.UninterpretedOption + * @instance + */ + UninterpretedOption.prototype.doubleValue = 0; - return FieldTransform; - })(); + /** + * UninterpretedOption stringValue. + * @member {Uint8Array} stringValue + * @memberof google.protobuf.UninterpretedOption + * @instance + */ + UninterpretedOption.prototype.stringValue = $util.newBuffer([]); - return DocumentTransform; - })(); + /** + * UninterpretedOption aggregateValue. + * @member {string} aggregateValue + * @memberof google.protobuf.UninterpretedOption + * @instance + */ + UninterpretedOption.prototype.aggregateValue = ""; - v1.WriteResult = (function() { + /** + * Creates an UninterpretedOption message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.protobuf.UninterpretedOption + * @static + * @param {Object.} object Plain object + * @returns {google.protobuf.UninterpretedOption} UninterpretedOption + */ + UninterpretedOption.fromObject = function fromObject(object) { + if (object instanceof $root.google.protobuf.UninterpretedOption) + return object; + var message = new $root.google.protobuf.UninterpretedOption(); + if (object.name) { + if (!Array.isArray(object.name)) + throw TypeError(".google.protobuf.UninterpretedOption.name: array expected"); + message.name = []; + for (var i = 0; i < object.name.length; ++i) { + if (typeof object.name[i] !== "object") + throw TypeError(".google.protobuf.UninterpretedOption.name: object expected"); + message.name[i] = $root.google.protobuf.UninterpretedOption.NamePart.fromObject(object.name[i]); + } + } + if (object.identifierValue != null) + message.identifierValue = String(object.identifierValue); + if (object.positiveIntValue != null) + if ($util.Long) + (message.positiveIntValue = $util.Long.fromValue(object.positiveIntValue)).unsigned = true; + else if (typeof object.positiveIntValue === "string") + message.positiveIntValue = parseInt(object.positiveIntValue, 10); + else if (typeof object.positiveIntValue === "number") + message.positiveIntValue = object.positiveIntValue; + else if (typeof object.positiveIntValue === "object") + message.positiveIntValue = new $util.LongBits(object.positiveIntValue.low >>> 0, object.positiveIntValue.high >>> 0).toNumber(true); + if (object.negativeIntValue != null) + if ($util.Long) + (message.negativeIntValue = $util.Long.fromValue(object.negativeIntValue)).unsigned = false; + else if (typeof object.negativeIntValue === "string") + message.negativeIntValue = parseInt(object.negativeIntValue, 10); + else if (typeof object.negativeIntValue === "number") + message.negativeIntValue = object.negativeIntValue; + else if (typeof object.negativeIntValue === "object") + message.negativeIntValue = new $util.LongBits(object.negativeIntValue.low >>> 0, object.negativeIntValue.high >>> 0).toNumber(); + if (object.doubleValue != null) + message.doubleValue = Number(object.doubleValue); + if (object.stringValue != null) + if (typeof object.stringValue === "string") + $util.base64.decode(object.stringValue, message.stringValue = $util.newBuffer($util.base64.length(object.stringValue)), 0); + else if (object.stringValue.length >= 0) + message.stringValue = object.stringValue; + if (object.aggregateValue != null) + message.aggregateValue = String(object.aggregateValue); + return message; + }; + + /** + * Creates a plain object from an UninterpretedOption message. Also converts values to other types if specified. + * @function toObject + * @memberof google.protobuf.UninterpretedOption + * @static + * @param {google.protobuf.UninterpretedOption} message UninterpretedOption + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + UninterpretedOption.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.arrays || options.defaults) + object.name = []; + if (options.defaults) { + object.identifierValue = ""; + if ($util.Long) { + var long = new $util.Long(0, 0, true); + object.positiveIntValue = options.longs === String ? long.toString() : options.longs === Number ? long.toNumber() : long; + } else + object.positiveIntValue = options.longs === String ? "0" : 0; + if ($util.Long) { + var long = new $util.Long(0, 0, false); + object.negativeIntValue = options.longs === String ? long.toString() : options.longs === Number ? long.toNumber() : long; + } else + object.negativeIntValue = options.longs === String ? "0" : 0; + object.doubleValue = 0; + if (options.bytes === String) + object.stringValue = ""; + else { + object.stringValue = []; + if (options.bytes !== Array) + object.stringValue = $util.newBuffer(object.stringValue); + } + object.aggregateValue = ""; + } + if (message.name && message.name.length) { + object.name = []; + for (var j = 0; j < message.name.length; ++j) + object.name[j] = $root.google.protobuf.UninterpretedOption.NamePart.toObject(message.name[j], options); + } + if (message.identifierValue != null && message.hasOwnProperty("identifierValue")) + object.identifierValue = message.identifierValue; + if (message.positiveIntValue != null && message.hasOwnProperty("positiveIntValue")) + if (typeof message.positiveIntValue === "number") + object.positiveIntValue = options.longs === String ? String(message.positiveIntValue) : message.positiveIntValue; + else + object.positiveIntValue = options.longs === String ? $util.Long.prototype.toString.call(message.positiveIntValue) : options.longs === Number ? new $util.LongBits(message.positiveIntValue.low >>> 0, message.positiveIntValue.high >>> 0).toNumber(true) : message.positiveIntValue; + if (message.negativeIntValue != null && message.hasOwnProperty("negativeIntValue")) + if (typeof message.negativeIntValue === "number") + object.negativeIntValue = options.longs === String ? String(message.negativeIntValue) : message.negativeIntValue; + else + object.negativeIntValue = options.longs === String ? $util.Long.prototype.toString.call(message.negativeIntValue) : options.longs === Number ? new $util.LongBits(message.negativeIntValue.low >>> 0, message.negativeIntValue.high >>> 0).toNumber() : message.negativeIntValue; + if (message.doubleValue != null && message.hasOwnProperty("doubleValue")) + object.doubleValue = options.json && !isFinite(message.doubleValue) ? String(message.doubleValue) : message.doubleValue; + if (message.stringValue != null && message.hasOwnProperty("stringValue")) + object.stringValue = options.bytes === String ? $util.base64.encode(message.stringValue, 0, message.stringValue.length) : options.bytes === Array ? Array.prototype.slice.call(message.stringValue) : message.stringValue; + if (message.aggregateValue != null && message.hasOwnProperty("aggregateValue")) + object.aggregateValue = message.aggregateValue; + return object; + }; + + /** + * Converts this UninterpretedOption to JSON. + * @function toJSON + * @memberof google.protobuf.UninterpretedOption + * @instance + * @returns {Object.} JSON object + */ + UninterpretedOption.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + + /** + * Gets the default type url for UninterpretedOption + * @function getTypeUrl + * @memberof google.protobuf.UninterpretedOption + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + UninterpretedOption.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.protobuf.UninterpretedOption"; + }; + + UninterpretedOption.NamePart = (function() { /** - * Properties of a WriteResult. - * @memberof google.firestore.v1 - * @interface IWriteResult - * @property {google.protobuf.ITimestamp|null} [updateTime] WriteResult updateTime - * @property {Array.|null} [transformResults] WriteResult transformResults + * Properties of a NamePart. + * @memberof google.protobuf.UninterpretedOption + * @interface INamePart + * @property {string} namePart NamePart namePart + * @property {boolean} isExtension NamePart isExtension */ /** - * Constructs a new WriteResult. - * @memberof google.firestore.v1 - * @classdesc Represents a WriteResult. - * @implements IWriteResult + * Constructs a new NamePart. + * @memberof google.protobuf.UninterpretedOption + * @classdesc Represents a NamePart. + * @implements INamePart * @constructor - * @param {google.firestore.v1.IWriteResult=} [properties] Properties to set + * @param {google.protobuf.UninterpretedOption.INamePart=} [properties] Properties to set */ - function WriteResult(properties) { - this.transformResults = []; + function NamePart(properties) { if (properties) for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) if (properties[keys[i]] != null) @@ -21660,417 +21596,731 @@ } /** - * WriteResult updateTime. - * @member {google.protobuf.ITimestamp|null|undefined} updateTime - * @memberof google.firestore.v1.WriteResult + * NamePart namePart. + * @member {string} namePart + * @memberof google.protobuf.UninterpretedOption.NamePart * @instance */ - WriteResult.prototype.updateTime = null; + NamePart.prototype.namePart = ""; /** - * WriteResult transformResults. - * @member {Array.} transformResults - * @memberof google.firestore.v1.WriteResult + * NamePart isExtension. + * @member {boolean} isExtension + * @memberof google.protobuf.UninterpretedOption.NamePart * @instance */ - WriteResult.prototype.transformResults = $util.emptyArray; + NamePart.prototype.isExtension = false; /** - * Creates a WriteResult message from a plain object. Also converts values to their respective internal types. + * Creates a NamePart message from a plain object. Also converts values to their respective internal types. * @function fromObject - * @memberof google.firestore.v1.WriteResult + * @memberof google.protobuf.UninterpretedOption.NamePart * @static * @param {Object.} object Plain object - * @returns {google.firestore.v1.WriteResult} WriteResult + * @returns {google.protobuf.UninterpretedOption.NamePart} NamePart */ - WriteResult.fromObject = function fromObject(object) { - if (object instanceof $root.google.firestore.v1.WriteResult) + NamePart.fromObject = function fromObject(object) { + if (object instanceof $root.google.protobuf.UninterpretedOption.NamePart) return object; - var message = new $root.google.firestore.v1.WriteResult(); - if (object.updateTime != null) { - if (typeof object.updateTime !== "object") - throw TypeError(".google.firestore.v1.WriteResult.updateTime: object expected"); - message.updateTime = $root.google.protobuf.Timestamp.fromObject(object.updateTime); - } - if (object.transformResults) { - if (!Array.isArray(object.transformResults)) - throw TypeError(".google.firestore.v1.WriteResult.transformResults: array expected"); - message.transformResults = []; - for (var i = 0; i < object.transformResults.length; ++i) { - if (typeof object.transformResults[i] !== "object") - throw TypeError(".google.firestore.v1.WriteResult.transformResults: object expected"); - message.transformResults[i] = $root.google.firestore.v1.Value.fromObject(object.transformResults[i]); - } - } + var message = new $root.google.protobuf.UninterpretedOption.NamePart(); + if (object.namePart != null) + message.namePart = String(object.namePart); + if (object.isExtension != null) + message.isExtension = Boolean(object.isExtension); return message; }; /** - * Creates a plain object from a WriteResult message. Also converts values to other types if specified. + * Creates a plain object from a NamePart message. Also converts values to other types if specified. * @function toObject - * @memberof google.firestore.v1.WriteResult + * @memberof google.protobuf.UninterpretedOption.NamePart * @static - * @param {google.firestore.v1.WriteResult} message WriteResult + * @param {google.protobuf.UninterpretedOption.NamePart} message NamePart * @param {$protobuf.IConversionOptions} [options] Conversion options * @returns {Object.} Plain object */ - WriteResult.toObject = function toObject(message, options) { + NamePart.toObject = function toObject(message, options) { if (!options) options = {}; var object = {}; - if (options.arrays || options.defaults) - object.transformResults = []; - if (options.defaults) - object.updateTime = null; - if (message.updateTime != null && message.hasOwnProperty("updateTime")) - object.updateTime = $root.google.protobuf.Timestamp.toObject(message.updateTime, options); - if (message.transformResults && message.transformResults.length) { - object.transformResults = []; - for (var j = 0; j < message.transformResults.length; ++j) - object.transformResults[j] = $root.google.firestore.v1.Value.toObject(message.transformResults[j], options); + if (options.defaults) { + object.namePart = ""; + object.isExtension = false; + } + if (message.namePart != null && message.hasOwnProperty("namePart")) + object.namePart = message.namePart; + if (message.isExtension != null && message.hasOwnProperty("isExtension")) + object.isExtension = message.isExtension; + return object; + }; + + /** + * Converts this NamePart to JSON. + * @function toJSON + * @memberof google.protobuf.UninterpretedOption.NamePart + * @instance + * @returns {Object.} JSON object + */ + NamePart.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + + /** + * Gets the default type url for NamePart + * @function getTypeUrl + * @memberof google.protobuf.UninterpretedOption.NamePart + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + NamePart.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.protobuf.UninterpretedOption.NamePart"; + }; + + return NamePart; + })(); + + return UninterpretedOption; + })(); + + protobuf.FeatureSet = (function() { + + /** + * Properties of a FeatureSet. + * @memberof google.protobuf + * @interface IFeatureSet + * @property {google.protobuf.FeatureSet.FieldPresence|null} [fieldPresence] FeatureSet fieldPresence + * @property {google.protobuf.FeatureSet.EnumType|null} [enumType] FeatureSet enumType + * @property {google.protobuf.FeatureSet.RepeatedFieldEncoding|null} [repeatedFieldEncoding] FeatureSet repeatedFieldEncoding + * @property {google.protobuf.FeatureSet.Utf8Validation|null} [utf8Validation] FeatureSet utf8Validation + * @property {google.protobuf.FeatureSet.MessageEncoding|null} [messageEncoding] FeatureSet messageEncoding + * @property {google.protobuf.FeatureSet.JsonFormat|null} [jsonFormat] FeatureSet jsonFormat + */ + + /** + * Constructs a new FeatureSet. + * @memberof google.protobuf + * @classdesc Represents a FeatureSet. + * @implements IFeatureSet + * @constructor + * @param {google.protobuf.IFeatureSet=} [properties] Properties to set + */ + function FeatureSet(properties) { + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } + + /** + * FeatureSet fieldPresence. + * @member {google.protobuf.FeatureSet.FieldPresence} fieldPresence + * @memberof google.protobuf.FeatureSet + * @instance + */ + FeatureSet.prototype.fieldPresence = 0; + + /** + * FeatureSet enumType. + * @member {google.protobuf.FeatureSet.EnumType} enumType + * @memberof google.protobuf.FeatureSet + * @instance + */ + FeatureSet.prototype.enumType = 0; + + /** + * FeatureSet repeatedFieldEncoding. + * @member {google.protobuf.FeatureSet.RepeatedFieldEncoding} repeatedFieldEncoding + * @memberof google.protobuf.FeatureSet + * @instance + */ + FeatureSet.prototype.repeatedFieldEncoding = 0; + + /** + * FeatureSet utf8Validation. + * @member {google.protobuf.FeatureSet.Utf8Validation} utf8Validation + * @memberof google.protobuf.FeatureSet + * @instance + */ + FeatureSet.prototype.utf8Validation = 0; + + /** + * FeatureSet messageEncoding. + * @member {google.protobuf.FeatureSet.MessageEncoding} messageEncoding + * @memberof google.protobuf.FeatureSet + * @instance + */ + FeatureSet.prototype.messageEncoding = 0; + + /** + * FeatureSet jsonFormat. + * @member {google.protobuf.FeatureSet.JsonFormat} jsonFormat + * @memberof google.protobuf.FeatureSet + * @instance + */ + FeatureSet.prototype.jsonFormat = 0; + + /** + * Creates a FeatureSet message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.protobuf.FeatureSet + * @static + * @param {Object.} object Plain object + * @returns {google.protobuf.FeatureSet} FeatureSet + */ + FeatureSet.fromObject = function fromObject(object) { + if (object instanceof $root.google.protobuf.FeatureSet) + return object; + var message = new $root.google.protobuf.FeatureSet(); + switch (object.fieldPresence) { + default: + if (typeof object.fieldPresence === "number") { + message.fieldPresence = object.fieldPresence; + break; + } + break; + case "FIELD_PRESENCE_UNKNOWN": + case 0: + message.fieldPresence = 0; + break; + case "EXPLICIT": + case 1: + message.fieldPresence = 1; + break; + case "IMPLICIT": + case 2: + message.fieldPresence = 2; + break; + case "LEGACY_REQUIRED": + case 3: + message.fieldPresence = 3; + break; + } + switch (object.enumType) { + default: + if (typeof object.enumType === "number") { + message.enumType = object.enumType; + break; + } + break; + case "ENUM_TYPE_UNKNOWN": + case 0: + message.enumType = 0; + break; + case "OPEN": + case 1: + message.enumType = 1; + break; + case "CLOSED": + case 2: + message.enumType = 2; + break; + } + switch (object.repeatedFieldEncoding) { + default: + if (typeof object.repeatedFieldEncoding === "number") { + message.repeatedFieldEncoding = object.repeatedFieldEncoding; + break; + } + break; + case "REPEATED_FIELD_ENCODING_UNKNOWN": + case 0: + message.repeatedFieldEncoding = 0; + break; + case "PACKED": + case 1: + message.repeatedFieldEncoding = 1; + break; + case "EXPANDED": + case 2: + message.repeatedFieldEncoding = 2; + break; + } + switch (object.utf8Validation) { + default: + if (typeof object.utf8Validation === "number") { + message.utf8Validation = object.utf8Validation; + break; } - return object; - }; - - /** - * Converts this WriteResult to JSON. - * @function toJSON - * @memberof google.firestore.v1.WriteResult - * @instance - * @returns {Object.} JSON object - */ - WriteResult.prototype.toJSON = function toJSON() { - return this.constructor.toObject(this, $protobuf.util.toJSONOptions); - }; - - /** - * Gets the default type url for WriteResult - * @function getTypeUrl - * @memberof google.firestore.v1.WriteResult - * @static - * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") - * @returns {string} The default type url - */ - WriteResult.getTypeUrl = function getTypeUrl(typeUrlPrefix) { - if (typeUrlPrefix === undefined) { - typeUrlPrefix = "type.googleapis.com"; + break; + case "UTF8_VALIDATION_UNKNOWN": + case 0: + message.utf8Validation = 0; + break; + case "VERIFY": + case 2: + message.utf8Validation = 2; + break; + case "NONE": + case 3: + message.utf8Validation = 3; + break; + } + switch (object.messageEncoding) { + default: + if (typeof object.messageEncoding === "number") { + message.messageEncoding = object.messageEncoding; + break; } - return typeUrlPrefix + "/google.firestore.v1.WriteResult"; - }; - - return WriteResult; - })(); - - v1.DocumentChange = (function() { - - /** - * Properties of a DocumentChange. - * @memberof google.firestore.v1 - * @interface IDocumentChange - * @property {google.firestore.v1.IDocument|null} [document] DocumentChange document - * @property {Array.|null} [targetIds] DocumentChange targetIds - * @property {Array.|null} [removedTargetIds] DocumentChange removedTargetIds - */ + break; + case "MESSAGE_ENCODING_UNKNOWN": + case 0: + message.messageEncoding = 0; + break; + case "LENGTH_PREFIXED": + case 1: + message.messageEncoding = 1; + break; + case "DELIMITED": + case 2: + message.messageEncoding = 2; + break; + } + switch (object.jsonFormat) { + default: + if (typeof object.jsonFormat === "number") { + message.jsonFormat = object.jsonFormat; + break; + } + break; + case "JSON_FORMAT_UNKNOWN": + case 0: + message.jsonFormat = 0; + break; + case "ALLOW": + case 1: + message.jsonFormat = 1; + break; + case "LEGACY_BEST_EFFORT": + case 2: + message.jsonFormat = 2; + break; + } + return message; + }; - /** - * Constructs a new DocumentChange. - * @memberof google.firestore.v1 - * @classdesc Represents a DocumentChange. - * @implements IDocumentChange - * @constructor - * @param {google.firestore.v1.IDocumentChange=} [properties] Properties to set - */ - function DocumentChange(properties) { - this.targetIds = []; - this.removedTargetIds = []; - if (properties) - for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) - if (properties[keys[i]] != null) - this[keys[i]] = properties[keys[i]]; + /** + * Creates a plain object from a FeatureSet message. Also converts values to other types if specified. + * @function toObject + * @memberof google.protobuf.FeatureSet + * @static + * @param {google.protobuf.FeatureSet} message FeatureSet + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + FeatureSet.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.defaults) { + object.fieldPresence = options.enums === String ? "FIELD_PRESENCE_UNKNOWN" : 0; + object.enumType = options.enums === String ? "ENUM_TYPE_UNKNOWN" : 0; + object.repeatedFieldEncoding = options.enums === String ? "REPEATED_FIELD_ENCODING_UNKNOWN" : 0; + object.utf8Validation = options.enums === String ? "UTF8_VALIDATION_UNKNOWN" : 0; + object.messageEncoding = options.enums === String ? "MESSAGE_ENCODING_UNKNOWN" : 0; + object.jsonFormat = options.enums === String ? "JSON_FORMAT_UNKNOWN" : 0; } + if (message.fieldPresence != null && message.hasOwnProperty("fieldPresence")) + object.fieldPresence = options.enums === String ? $root.google.protobuf.FeatureSet.FieldPresence[message.fieldPresence] === undefined ? message.fieldPresence : $root.google.protobuf.FeatureSet.FieldPresence[message.fieldPresence] : message.fieldPresence; + if (message.enumType != null && message.hasOwnProperty("enumType")) + object.enumType = options.enums === String ? $root.google.protobuf.FeatureSet.EnumType[message.enumType] === undefined ? message.enumType : $root.google.protobuf.FeatureSet.EnumType[message.enumType] : message.enumType; + if (message.repeatedFieldEncoding != null && message.hasOwnProperty("repeatedFieldEncoding")) + object.repeatedFieldEncoding = options.enums === String ? $root.google.protobuf.FeatureSet.RepeatedFieldEncoding[message.repeatedFieldEncoding] === undefined ? message.repeatedFieldEncoding : $root.google.protobuf.FeatureSet.RepeatedFieldEncoding[message.repeatedFieldEncoding] : message.repeatedFieldEncoding; + if (message.utf8Validation != null && message.hasOwnProperty("utf8Validation")) + object.utf8Validation = options.enums === String ? $root.google.protobuf.FeatureSet.Utf8Validation[message.utf8Validation] === undefined ? message.utf8Validation : $root.google.protobuf.FeatureSet.Utf8Validation[message.utf8Validation] : message.utf8Validation; + if (message.messageEncoding != null && message.hasOwnProperty("messageEncoding")) + object.messageEncoding = options.enums === String ? $root.google.protobuf.FeatureSet.MessageEncoding[message.messageEncoding] === undefined ? message.messageEncoding : $root.google.protobuf.FeatureSet.MessageEncoding[message.messageEncoding] : message.messageEncoding; + if (message.jsonFormat != null && message.hasOwnProperty("jsonFormat")) + object.jsonFormat = options.enums === String ? $root.google.protobuf.FeatureSet.JsonFormat[message.jsonFormat] === undefined ? message.jsonFormat : $root.google.protobuf.FeatureSet.JsonFormat[message.jsonFormat] : message.jsonFormat; + return object; + }; - /** - * DocumentChange document. - * @member {google.firestore.v1.IDocument|null|undefined} document - * @memberof google.firestore.v1.DocumentChange - * @instance - */ - DocumentChange.prototype.document = null; + /** + * Converts this FeatureSet to JSON. + * @function toJSON + * @memberof google.protobuf.FeatureSet + * @instance + * @returns {Object.} JSON object + */ + FeatureSet.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; - /** - * DocumentChange targetIds. - * @member {Array.} targetIds - * @memberof google.firestore.v1.DocumentChange - * @instance - */ - DocumentChange.prototype.targetIds = $util.emptyArray; + /** + * Gets the default type url for FeatureSet + * @function getTypeUrl + * @memberof google.protobuf.FeatureSet + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + FeatureSet.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.protobuf.FeatureSet"; + }; - /** - * DocumentChange removedTargetIds. - * @member {Array.} removedTargetIds - * @memberof google.firestore.v1.DocumentChange - * @instance - */ - DocumentChange.prototype.removedTargetIds = $util.emptyArray; + /** + * FieldPresence enum. + * @name google.protobuf.FeatureSet.FieldPresence + * @enum {string} + * @property {string} FIELD_PRESENCE_UNKNOWN=FIELD_PRESENCE_UNKNOWN FIELD_PRESENCE_UNKNOWN value + * @property {string} EXPLICIT=EXPLICIT EXPLICIT value + * @property {string} IMPLICIT=IMPLICIT IMPLICIT value + * @property {string} LEGACY_REQUIRED=LEGACY_REQUIRED LEGACY_REQUIRED value + */ + FeatureSet.FieldPresence = (function() { + var valuesById = {}, values = Object.create(valuesById); + values[valuesById[0] = "FIELD_PRESENCE_UNKNOWN"] = "FIELD_PRESENCE_UNKNOWN"; + values[valuesById[1] = "EXPLICIT"] = "EXPLICIT"; + values[valuesById[2] = "IMPLICIT"] = "IMPLICIT"; + values[valuesById[3] = "LEGACY_REQUIRED"] = "LEGACY_REQUIRED"; + return values; + })(); - /** - * Creates a DocumentChange message from a plain object. Also converts values to their respective internal types. - * @function fromObject - * @memberof google.firestore.v1.DocumentChange - * @static - * @param {Object.} object Plain object - * @returns {google.firestore.v1.DocumentChange} DocumentChange - */ - DocumentChange.fromObject = function fromObject(object) { - if (object instanceof $root.google.firestore.v1.DocumentChange) - return object; - var message = new $root.google.firestore.v1.DocumentChange(); - if (object.document != null) { - if (typeof object.document !== "object") - throw TypeError(".google.firestore.v1.DocumentChange.document: object expected"); - message.document = $root.google.firestore.v1.Document.fromObject(object.document); - } - if (object.targetIds) { - if (!Array.isArray(object.targetIds)) - throw TypeError(".google.firestore.v1.DocumentChange.targetIds: array expected"); - message.targetIds = []; - for (var i = 0; i < object.targetIds.length; ++i) - message.targetIds[i] = object.targetIds[i] | 0; - } - if (object.removedTargetIds) { - if (!Array.isArray(object.removedTargetIds)) - throw TypeError(".google.firestore.v1.DocumentChange.removedTargetIds: array expected"); - message.removedTargetIds = []; - for (var i = 0; i < object.removedTargetIds.length; ++i) - message.removedTargetIds[i] = object.removedTargetIds[i] | 0; - } - return message; - }; + /** + * EnumType enum. + * @name google.protobuf.FeatureSet.EnumType + * @enum {string} + * @property {string} ENUM_TYPE_UNKNOWN=ENUM_TYPE_UNKNOWN ENUM_TYPE_UNKNOWN value + * @property {string} OPEN=OPEN OPEN value + * @property {string} CLOSED=CLOSED CLOSED value + */ + FeatureSet.EnumType = (function() { + var valuesById = {}, values = Object.create(valuesById); + values[valuesById[0] = "ENUM_TYPE_UNKNOWN"] = "ENUM_TYPE_UNKNOWN"; + values[valuesById[1] = "OPEN"] = "OPEN"; + values[valuesById[2] = "CLOSED"] = "CLOSED"; + return values; + })(); - /** - * Creates a plain object from a DocumentChange message. Also converts values to other types if specified. - * @function toObject - * @memberof google.firestore.v1.DocumentChange - * @static - * @param {google.firestore.v1.DocumentChange} message DocumentChange - * @param {$protobuf.IConversionOptions} [options] Conversion options - * @returns {Object.} Plain object - */ - DocumentChange.toObject = function toObject(message, options) { - if (!options) - options = {}; - var object = {}; - if (options.arrays || options.defaults) { - object.targetIds = []; - object.removedTargetIds = []; - } - if (options.defaults) - object.document = null; - if (message.document != null && message.hasOwnProperty("document")) - object.document = $root.google.firestore.v1.Document.toObject(message.document, options); - if (message.targetIds && message.targetIds.length) { - object.targetIds = []; - for (var j = 0; j < message.targetIds.length; ++j) - object.targetIds[j] = message.targetIds[j]; - } - if (message.removedTargetIds && message.removedTargetIds.length) { - object.removedTargetIds = []; - for (var j = 0; j < message.removedTargetIds.length; ++j) - object.removedTargetIds[j] = message.removedTargetIds[j]; - } - return object; - }; + /** + * RepeatedFieldEncoding enum. + * @name google.protobuf.FeatureSet.RepeatedFieldEncoding + * @enum {string} + * @property {string} REPEATED_FIELD_ENCODING_UNKNOWN=REPEATED_FIELD_ENCODING_UNKNOWN REPEATED_FIELD_ENCODING_UNKNOWN value + * @property {string} PACKED=PACKED PACKED value + * @property {string} EXPANDED=EXPANDED EXPANDED value + */ + FeatureSet.RepeatedFieldEncoding = (function() { + var valuesById = {}, values = Object.create(valuesById); + values[valuesById[0] = "REPEATED_FIELD_ENCODING_UNKNOWN"] = "REPEATED_FIELD_ENCODING_UNKNOWN"; + values[valuesById[1] = "PACKED"] = "PACKED"; + values[valuesById[2] = "EXPANDED"] = "EXPANDED"; + return values; + })(); - /** - * Converts this DocumentChange to JSON. - * @function toJSON - * @memberof google.firestore.v1.DocumentChange - * @instance - * @returns {Object.} JSON object - */ - DocumentChange.prototype.toJSON = function toJSON() { - return this.constructor.toObject(this, $protobuf.util.toJSONOptions); - }; + /** + * Utf8Validation enum. + * @name google.protobuf.FeatureSet.Utf8Validation + * @enum {string} + * @property {string} UTF8_VALIDATION_UNKNOWN=UTF8_VALIDATION_UNKNOWN UTF8_VALIDATION_UNKNOWN value + * @property {string} VERIFY=VERIFY VERIFY value + * @property {string} NONE=NONE NONE value + */ + FeatureSet.Utf8Validation = (function() { + var valuesById = {}, values = Object.create(valuesById); + values[valuesById[0] = "UTF8_VALIDATION_UNKNOWN"] = "UTF8_VALIDATION_UNKNOWN"; + values[valuesById[2] = "VERIFY"] = "VERIFY"; + values[valuesById[3] = "NONE"] = "NONE"; + return values; + })(); - /** - * Gets the default type url for DocumentChange - * @function getTypeUrl - * @memberof google.firestore.v1.DocumentChange - * @static - * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") - * @returns {string} The default type url - */ - DocumentChange.getTypeUrl = function getTypeUrl(typeUrlPrefix) { - if (typeUrlPrefix === undefined) { - typeUrlPrefix = "type.googleapis.com"; - } - return typeUrlPrefix + "/google.firestore.v1.DocumentChange"; - }; + /** + * MessageEncoding enum. + * @name google.protobuf.FeatureSet.MessageEncoding + * @enum {string} + * @property {string} MESSAGE_ENCODING_UNKNOWN=MESSAGE_ENCODING_UNKNOWN MESSAGE_ENCODING_UNKNOWN value + * @property {string} LENGTH_PREFIXED=LENGTH_PREFIXED LENGTH_PREFIXED value + * @property {string} DELIMITED=DELIMITED DELIMITED value + */ + FeatureSet.MessageEncoding = (function() { + var valuesById = {}, values = Object.create(valuesById); + values[valuesById[0] = "MESSAGE_ENCODING_UNKNOWN"] = "MESSAGE_ENCODING_UNKNOWN"; + values[valuesById[1] = "LENGTH_PREFIXED"] = "LENGTH_PREFIXED"; + values[valuesById[2] = "DELIMITED"] = "DELIMITED"; + return values; + })(); - return DocumentChange; + /** + * JsonFormat enum. + * @name google.protobuf.FeatureSet.JsonFormat + * @enum {string} + * @property {string} JSON_FORMAT_UNKNOWN=JSON_FORMAT_UNKNOWN JSON_FORMAT_UNKNOWN value + * @property {string} ALLOW=ALLOW ALLOW value + * @property {string} LEGACY_BEST_EFFORT=LEGACY_BEST_EFFORT LEGACY_BEST_EFFORT value + */ + FeatureSet.JsonFormat = (function() { + var valuesById = {}, values = Object.create(valuesById); + values[valuesById[0] = "JSON_FORMAT_UNKNOWN"] = "JSON_FORMAT_UNKNOWN"; + values[valuesById[1] = "ALLOW"] = "ALLOW"; + values[valuesById[2] = "LEGACY_BEST_EFFORT"] = "LEGACY_BEST_EFFORT"; + return values; })(); - v1.DocumentDelete = (function() { + return FeatureSet; + })(); - /** - * Properties of a DocumentDelete. - * @memberof google.firestore.v1 - * @interface IDocumentDelete - * @property {string|null} [document] DocumentDelete document - * @property {Array.|null} [removedTargetIds] DocumentDelete removedTargetIds - * @property {google.protobuf.ITimestamp|null} [readTime] DocumentDelete readTime - */ + protobuf.FeatureSetDefaults = (function() { - /** - * Constructs a new DocumentDelete. - * @memberof google.firestore.v1 - * @classdesc Represents a DocumentDelete. - * @implements IDocumentDelete - * @constructor - * @param {google.firestore.v1.IDocumentDelete=} [properties] Properties to set - */ - function DocumentDelete(properties) { - this.removedTargetIds = []; - if (properties) - for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) - if (properties[keys[i]] != null) - this[keys[i]] = properties[keys[i]]; - } + /** + * Properties of a FeatureSetDefaults. + * @memberof google.protobuf + * @interface IFeatureSetDefaults + * @property {Array.|null} [defaults] FeatureSetDefaults defaults + * @property {google.protobuf.Edition|null} [minimumEdition] FeatureSetDefaults minimumEdition + * @property {google.protobuf.Edition|null} [maximumEdition] FeatureSetDefaults maximumEdition + */ - /** - * DocumentDelete document. - * @member {string} document - * @memberof google.firestore.v1.DocumentDelete - * @instance - */ - DocumentDelete.prototype.document = ""; + /** + * Constructs a new FeatureSetDefaults. + * @memberof google.protobuf + * @classdesc Represents a FeatureSetDefaults. + * @implements IFeatureSetDefaults + * @constructor + * @param {google.protobuf.IFeatureSetDefaults=} [properties] Properties to set + */ + function FeatureSetDefaults(properties) { + this.defaults = []; + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } - /** - * DocumentDelete removedTargetIds. - * @member {Array.} removedTargetIds - * @memberof google.firestore.v1.DocumentDelete - * @instance - */ - DocumentDelete.prototype.removedTargetIds = $util.emptyArray; + /** + * FeatureSetDefaults defaults. + * @member {Array.} defaults + * @memberof google.protobuf.FeatureSetDefaults + * @instance + */ + FeatureSetDefaults.prototype.defaults = $util.emptyArray; - /** - * DocumentDelete readTime. - * @member {google.protobuf.ITimestamp|null|undefined} readTime - * @memberof google.firestore.v1.DocumentDelete - * @instance - */ - DocumentDelete.prototype.readTime = null; + /** + * FeatureSetDefaults minimumEdition. + * @member {google.protobuf.Edition} minimumEdition + * @memberof google.protobuf.FeatureSetDefaults + * @instance + */ + FeatureSetDefaults.prototype.minimumEdition = 0; - /** - * Creates a DocumentDelete message from a plain object. Also converts values to their respective internal types. - * @function fromObject - * @memberof google.firestore.v1.DocumentDelete - * @static - * @param {Object.} object Plain object - * @returns {google.firestore.v1.DocumentDelete} DocumentDelete - */ - DocumentDelete.fromObject = function fromObject(object) { - if (object instanceof $root.google.firestore.v1.DocumentDelete) - return object; - var message = new $root.google.firestore.v1.DocumentDelete(); - if (object.document != null) - message.document = String(object.document); - if (object.removedTargetIds) { - if (!Array.isArray(object.removedTargetIds)) - throw TypeError(".google.firestore.v1.DocumentDelete.removedTargetIds: array expected"); - message.removedTargetIds = []; - for (var i = 0; i < object.removedTargetIds.length; ++i) - message.removedTargetIds[i] = object.removedTargetIds[i] | 0; - } - if (object.readTime != null) { - if (typeof object.readTime !== "object") - throw TypeError(".google.firestore.v1.DocumentDelete.readTime: object expected"); - message.readTime = $root.google.protobuf.Timestamp.fromObject(object.readTime); + /** + * FeatureSetDefaults maximumEdition. + * @member {google.protobuf.Edition} maximumEdition + * @memberof google.protobuf.FeatureSetDefaults + * @instance + */ + FeatureSetDefaults.prototype.maximumEdition = 0; + + /** + * Creates a FeatureSetDefaults message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.protobuf.FeatureSetDefaults + * @static + * @param {Object.} object Plain object + * @returns {google.protobuf.FeatureSetDefaults} FeatureSetDefaults + */ + FeatureSetDefaults.fromObject = function fromObject(object) { + if (object instanceof $root.google.protobuf.FeatureSetDefaults) + return object; + var message = new $root.google.protobuf.FeatureSetDefaults(); + if (object.defaults) { + if (!Array.isArray(object.defaults)) + throw TypeError(".google.protobuf.FeatureSetDefaults.defaults: array expected"); + message.defaults = []; + for (var i = 0; i < object.defaults.length; ++i) { + if (typeof object.defaults[i] !== "object") + throw TypeError(".google.protobuf.FeatureSetDefaults.defaults: object expected"); + message.defaults[i] = $root.google.protobuf.FeatureSetDefaults.FeatureSetEditionDefault.fromObject(object.defaults[i]); } - return message; - }; - - /** - * Creates a plain object from a DocumentDelete message. Also converts values to other types if specified. - * @function toObject - * @memberof google.firestore.v1.DocumentDelete - * @static - * @param {google.firestore.v1.DocumentDelete} message DocumentDelete - * @param {$protobuf.IConversionOptions} [options] Conversion options - * @returns {Object.} Plain object - */ - DocumentDelete.toObject = function toObject(message, options) { - if (!options) - options = {}; - var object = {}; - if (options.arrays || options.defaults) - object.removedTargetIds = []; - if (options.defaults) { - object.document = ""; - object.readTime = null; + } + switch (object.minimumEdition) { + default: + if (typeof object.minimumEdition === "number") { + message.minimumEdition = object.minimumEdition; + break; } - if (message.document != null && message.hasOwnProperty("document")) - object.document = message.document; - if (message.readTime != null && message.hasOwnProperty("readTime")) - object.readTime = $root.google.protobuf.Timestamp.toObject(message.readTime, options); - if (message.removedTargetIds && message.removedTargetIds.length) { - object.removedTargetIds = []; - for (var j = 0; j < message.removedTargetIds.length; ++j) - object.removedTargetIds[j] = message.removedTargetIds[j]; + break; + case "EDITION_UNKNOWN": + case 0: + message.minimumEdition = 0; + break; + case "EDITION_PROTO2": + case 998: + message.minimumEdition = 998; + break; + case "EDITION_PROTO3": + case 999: + message.minimumEdition = 999; + break; + case "EDITION_2023": + case 1000: + message.minimumEdition = 1000; + break; + case "EDITION_2024": + case 1001: + message.minimumEdition = 1001; + break; + case "EDITION_1_TEST_ONLY": + case 1: + message.minimumEdition = 1; + break; + case "EDITION_2_TEST_ONLY": + case 2: + message.minimumEdition = 2; + break; + case "EDITION_99997_TEST_ONLY": + case 99997: + message.minimumEdition = 99997; + break; + case "EDITION_99998_TEST_ONLY": + case 99998: + message.minimumEdition = 99998; + break; + case "EDITION_99999_TEST_ONLY": + case 99999: + message.minimumEdition = 99999; + break; + case "EDITION_MAX": + case 2147483647: + message.minimumEdition = 2147483647; + break; + } + switch (object.maximumEdition) { + default: + if (typeof object.maximumEdition === "number") { + message.maximumEdition = object.maximumEdition; + break; } - return object; - }; + break; + case "EDITION_UNKNOWN": + case 0: + message.maximumEdition = 0; + break; + case "EDITION_PROTO2": + case 998: + message.maximumEdition = 998; + break; + case "EDITION_PROTO3": + case 999: + message.maximumEdition = 999; + break; + case "EDITION_2023": + case 1000: + message.maximumEdition = 1000; + break; + case "EDITION_2024": + case 1001: + message.maximumEdition = 1001; + break; + case "EDITION_1_TEST_ONLY": + case 1: + message.maximumEdition = 1; + break; + case "EDITION_2_TEST_ONLY": + case 2: + message.maximumEdition = 2; + break; + case "EDITION_99997_TEST_ONLY": + case 99997: + message.maximumEdition = 99997; + break; + case "EDITION_99998_TEST_ONLY": + case 99998: + message.maximumEdition = 99998; + break; + case "EDITION_99999_TEST_ONLY": + case 99999: + message.maximumEdition = 99999; + break; + case "EDITION_MAX": + case 2147483647: + message.maximumEdition = 2147483647; + break; + } + return message; + }; - /** - * Converts this DocumentDelete to JSON. - * @function toJSON - * @memberof google.firestore.v1.DocumentDelete - * @instance - * @returns {Object.} JSON object - */ - DocumentDelete.prototype.toJSON = function toJSON() { - return this.constructor.toObject(this, $protobuf.util.toJSONOptions); - }; + /** + * Creates a plain object from a FeatureSetDefaults message. Also converts values to other types if specified. + * @function toObject + * @memberof google.protobuf.FeatureSetDefaults + * @static + * @param {google.protobuf.FeatureSetDefaults} message FeatureSetDefaults + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + FeatureSetDefaults.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.arrays || options.defaults) + object.defaults = []; + if (options.defaults) { + object.minimumEdition = options.enums === String ? "EDITION_UNKNOWN" : 0; + object.maximumEdition = options.enums === String ? "EDITION_UNKNOWN" : 0; + } + if (message.defaults && message.defaults.length) { + object.defaults = []; + for (var j = 0; j < message.defaults.length; ++j) + object.defaults[j] = $root.google.protobuf.FeatureSetDefaults.FeatureSetEditionDefault.toObject(message.defaults[j], options); + } + if (message.minimumEdition != null && message.hasOwnProperty("minimumEdition")) + object.minimumEdition = options.enums === String ? $root.google.protobuf.Edition[message.minimumEdition] === undefined ? message.minimumEdition : $root.google.protobuf.Edition[message.minimumEdition] : message.minimumEdition; + if (message.maximumEdition != null && message.hasOwnProperty("maximumEdition")) + object.maximumEdition = options.enums === String ? $root.google.protobuf.Edition[message.maximumEdition] === undefined ? message.maximumEdition : $root.google.protobuf.Edition[message.maximumEdition] : message.maximumEdition; + return object; + }; - /** - * Gets the default type url for DocumentDelete - * @function getTypeUrl - * @memberof google.firestore.v1.DocumentDelete - * @static - * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") - * @returns {string} The default type url - */ - DocumentDelete.getTypeUrl = function getTypeUrl(typeUrlPrefix) { - if (typeUrlPrefix === undefined) { - typeUrlPrefix = "type.googleapis.com"; - } - return typeUrlPrefix + "/google.firestore.v1.DocumentDelete"; - }; + /** + * Converts this FeatureSetDefaults to JSON. + * @function toJSON + * @memberof google.protobuf.FeatureSetDefaults + * @instance + * @returns {Object.} JSON object + */ + FeatureSetDefaults.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; - return DocumentDelete; - })(); + /** + * Gets the default type url for FeatureSetDefaults + * @function getTypeUrl + * @memberof google.protobuf.FeatureSetDefaults + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + FeatureSetDefaults.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.protobuf.FeatureSetDefaults"; + }; - v1.DocumentRemove = (function() { + FeatureSetDefaults.FeatureSetEditionDefault = (function() { /** - * Properties of a DocumentRemove. - * @memberof google.firestore.v1 - * @interface IDocumentRemove - * @property {string|null} [document] DocumentRemove document - * @property {Array.|null} [removedTargetIds] DocumentRemove removedTargetIds - * @property {google.protobuf.ITimestamp|null} [readTime] DocumentRemove readTime + * Properties of a FeatureSetEditionDefault. + * @memberof google.protobuf.FeatureSetDefaults + * @interface IFeatureSetEditionDefault + * @property {google.protobuf.Edition|null} [edition] FeatureSetEditionDefault edition + * @property {google.protobuf.IFeatureSet|null} [features] FeatureSetEditionDefault features */ /** - * Constructs a new DocumentRemove. - * @memberof google.firestore.v1 - * @classdesc Represents a DocumentRemove. - * @implements IDocumentRemove + * Constructs a new FeatureSetEditionDefault. + * @memberof google.protobuf.FeatureSetDefaults + * @classdesc Represents a FeatureSetEditionDefault. + * @implements IFeatureSetEditionDefault * @constructor - * @param {google.firestore.v1.IDocumentRemove=} [properties] Properties to set + * @param {google.protobuf.FeatureSetDefaults.IFeatureSetEditionDefault=} [properties] Properties to set */ - function DocumentRemove(properties) { - this.removedTargetIds = []; + function FeatureSetEditionDefault(properties) { if (properties) for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) if (properties[keys[i]] != null) @@ -22078,138 +22328,281 @@ } /** - * DocumentRemove document. - * @member {string} document - * @memberof google.firestore.v1.DocumentRemove - * @instance - */ - DocumentRemove.prototype.document = ""; - - /** - * DocumentRemove removedTargetIds. - * @member {Array.} removedTargetIds - * @memberof google.firestore.v1.DocumentRemove + * FeatureSetEditionDefault edition. + * @member {google.protobuf.Edition} edition + * @memberof google.protobuf.FeatureSetDefaults.FeatureSetEditionDefault * @instance */ - DocumentRemove.prototype.removedTargetIds = $util.emptyArray; + FeatureSetEditionDefault.prototype.edition = 0; /** - * DocumentRemove readTime. - * @member {google.protobuf.ITimestamp|null|undefined} readTime - * @memberof google.firestore.v1.DocumentRemove + * FeatureSetEditionDefault features. + * @member {google.protobuf.IFeatureSet|null|undefined} features + * @memberof google.protobuf.FeatureSetDefaults.FeatureSetEditionDefault * @instance */ - DocumentRemove.prototype.readTime = null; + FeatureSetEditionDefault.prototype.features = null; /** - * Creates a DocumentRemove message from a plain object. Also converts values to their respective internal types. + * Creates a FeatureSetEditionDefault message from a plain object. Also converts values to their respective internal types. * @function fromObject - * @memberof google.firestore.v1.DocumentRemove + * @memberof google.protobuf.FeatureSetDefaults.FeatureSetEditionDefault * @static * @param {Object.} object Plain object - * @returns {google.firestore.v1.DocumentRemove} DocumentRemove + * @returns {google.protobuf.FeatureSetDefaults.FeatureSetEditionDefault} FeatureSetEditionDefault */ - DocumentRemove.fromObject = function fromObject(object) { - if (object instanceof $root.google.firestore.v1.DocumentRemove) + FeatureSetEditionDefault.fromObject = function fromObject(object) { + if (object instanceof $root.google.protobuf.FeatureSetDefaults.FeatureSetEditionDefault) return object; - var message = new $root.google.firestore.v1.DocumentRemove(); - if (object.document != null) - message.document = String(object.document); - if (object.removedTargetIds) { - if (!Array.isArray(object.removedTargetIds)) - throw TypeError(".google.firestore.v1.DocumentRemove.removedTargetIds: array expected"); - message.removedTargetIds = []; - for (var i = 0; i < object.removedTargetIds.length; ++i) - message.removedTargetIds[i] = object.removedTargetIds[i] | 0; + var message = new $root.google.protobuf.FeatureSetDefaults.FeatureSetEditionDefault(); + switch (object.edition) { + default: + if (typeof object.edition === "number") { + message.edition = object.edition; + break; + } + break; + case "EDITION_UNKNOWN": + case 0: + message.edition = 0; + break; + case "EDITION_PROTO2": + case 998: + message.edition = 998; + break; + case "EDITION_PROTO3": + case 999: + message.edition = 999; + break; + case "EDITION_2023": + case 1000: + message.edition = 1000; + break; + case "EDITION_2024": + case 1001: + message.edition = 1001; + break; + case "EDITION_1_TEST_ONLY": + case 1: + message.edition = 1; + break; + case "EDITION_2_TEST_ONLY": + case 2: + message.edition = 2; + break; + case "EDITION_99997_TEST_ONLY": + case 99997: + message.edition = 99997; + break; + case "EDITION_99998_TEST_ONLY": + case 99998: + message.edition = 99998; + break; + case "EDITION_99999_TEST_ONLY": + case 99999: + message.edition = 99999; + break; + case "EDITION_MAX": + case 2147483647: + message.edition = 2147483647; + break; } - if (object.readTime != null) { - if (typeof object.readTime !== "object") - throw TypeError(".google.firestore.v1.DocumentRemove.readTime: object expected"); - message.readTime = $root.google.protobuf.Timestamp.fromObject(object.readTime); + if (object.features != null) { + if (typeof object.features !== "object") + throw TypeError(".google.protobuf.FeatureSetDefaults.FeatureSetEditionDefault.features: object expected"); + message.features = $root.google.protobuf.FeatureSet.fromObject(object.features); } return message; }; /** - * Creates a plain object from a DocumentRemove message. Also converts values to other types if specified. + * Creates a plain object from a FeatureSetEditionDefault message. Also converts values to other types if specified. * @function toObject - * @memberof google.firestore.v1.DocumentRemove + * @memberof google.protobuf.FeatureSetDefaults.FeatureSetEditionDefault * @static - * @param {google.firestore.v1.DocumentRemove} message DocumentRemove + * @param {google.protobuf.FeatureSetDefaults.FeatureSetEditionDefault} message FeatureSetEditionDefault * @param {$protobuf.IConversionOptions} [options] Conversion options * @returns {Object.} Plain object */ - DocumentRemove.toObject = function toObject(message, options) { + FeatureSetEditionDefault.toObject = function toObject(message, options) { if (!options) options = {}; var object = {}; - if (options.arrays || options.defaults) - object.removedTargetIds = []; if (options.defaults) { - object.document = ""; - object.readTime = null; - } - if (message.document != null && message.hasOwnProperty("document")) - object.document = message.document; - if (message.removedTargetIds && message.removedTargetIds.length) { - object.removedTargetIds = []; - for (var j = 0; j < message.removedTargetIds.length; ++j) - object.removedTargetIds[j] = message.removedTargetIds[j]; + object.features = null; + object.edition = options.enums === String ? "EDITION_UNKNOWN" : 0; } - if (message.readTime != null && message.hasOwnProperty("readTime")) - object.readTime = $root.google.protobuf.Timestamp.toObject(message.readTime, options); + if (message.features != null && message.hasOwnProperty("features")) + object.features = $root.google.protobuf.FeatureSet.toObject(message.features, options); + if (message.edition != null && message.hasOwnProperty("edition")) + object.edition = options.enums === String ? $root.google.protobuf.Edition[message.edition] === undefined ? message.edition : $root.google.protobuf.Edition[message.edition] : message.edition; return object; }; /** - * Converts this DocumentRemove to JSON. + * Converts this FeatureSetEditionDefault to JSON. * @function toJSON - * @memberof google.firestore.v1.DocumentRemove + * @memberof google.protobuf.FeatureSetDefaults.FeatureSetEditionDefault * @instance * @returns {Object.} JSON object */ - DocumentRemove.prototype.toJSON = function toJSON() { + FeatureSetEditionDefault.prototype.toJSON = function toJSON() { return this.constructor.toObject(this, $protobuf.util.toJSONOptions); }; /** - * Gets the default type url for DocumentRemove + * Gets the default type url for FeatureSetEditionDefault * @function getTypeUrl - * @memberof google.firestore.v1.DocumentRemove + * @memberof google.protobuf.FeatureSetDefaults.FeatureSetEditionDefault * @static * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") * @returns {string} The default type url */ - DocumentRemove.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + FeatureSetEditionDefault.getTypeUrl = function getTypeUrl(typeUrlPrefix) { if (typeUrlPrefix === undefined) { typeUrlPrefix = "type.googleapis.com"; } - return typeUrlPrefix + "/google.firestore.v1.DocumentRemove"; + return typeUrlPrefix + "/google.protobuf.FeatureSetDefaults.FeatureSetEditionDefault"; }; - return DocumentRemove; + return FeatureSetEditionDefault; })(); - v1.ExistenceFilter = (function() { + return FeatureSetDefaults; + })(); + + protobuf.SourceCodeInfo = (function() { + + /** + * Properties of a SourceCodeInfo. + * @memberof google.protobuf + * @interface ISourceCodeInfo + * @property {Array.|null} [location] SourceCodeInfo location + */ + + /** + * Constructs a new SourceCodeInfo. + * @memberof google.protobuf + * @classdesc Represents a SourceCodeInfo. + * @implements ISourceCodeInfo + * @constructor + * @param {google.protobuf.ISourceCodeInfo=} [properties] Properties to set + */ + function SourceCodeInfo(properties) { + this.location = []; + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } + + /** + * SourceCodeInfo location. + * @member {Array.} location + * @memberof google.protobuf.SourceCodeInfo + * @instance + */ + SourceCodeInfo.prototype.location = $util.emptyArray; + + /** + * Creates a SourceCodeInfo message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.protobuf.SourceCodeInfo + * @static + * @param {Object.} object Plain object + * @returns {google.protobuf.SourceCodeInfo} SourceCodeInfo + */ + SourceCodeInfo.fromObject = function fromObject(object) { + if (object instanceof $root.google.protobuf.SourceCodeInfo) + return object; + var message = new $root.google.protobuf.SourceCodeInfo(); + if (object.location) { + if (!Array.isArray(object.location)) + throw TypeError(".google.protobuf.SourceCodeInfo.location: array expected"); + message.location = []; + for (var i = 0; i < object.location.length; ++i) { + if (typeof object.location[i] !== "object") + throw TypeError(".google.protobuf.SourceCodeInfo.location: object expected"); + message.location[i] = $root.google.protobuf.SourceCodeInfo.Location.fromObject(object.location[i]); + } + } + return message; + }; + + /** + * Creates a plain object from a SourceCodeInfo message. Also converts values to other types if specified. + * @function toObject + * @memberof google.protobuf.SourceCodeInfo + * @static + * @param {google.protobuf.SourceCodeInfo} message SourceCodeInfo + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + SourceCodeInfo.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.arrays || options.defaults) + object.location = []; + if (message.location && message.location.length) { + object.location = []; + for (var j = 0; j < message.location.length; ++j) + object.location[j] = $root.google.protobuf.SourceCodeInfo.Location.toObject(message.location[j], options); + } + return object; + }; + + /** + * Converts this SourceCodeInfo to JSON. + * @function toJSON + * @memberof google.protobuf.SourceCodeInfo + * @instance + * @returns {Object.} JSON object + */ + SourceCodeInfo.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + + /** + * Gets the default type url for SourceCodeInfo + * @function getTypeUrl + * @memberof google.protobuf.SourceCodeInfo + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + SourceCodeInfo.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.protobuf.SourceCodeInfo"; + }; + + SourceCodeInfo.Location = (function() { /** - * Properties of an ExistenceFilter. - * @memberof google.firestore.v1 - * @interface IExistenceFilter - * @property {number|null} [targetId] ExistenceFilter targetId - * @property {number|null} [count] ExistenceFilter count - * @property {google.firestore.v1.IBloomFilter|null} [unchangedNames] ExistenceFilter unchangedNames + * Properties of a Location. + * @memberof google.protobuf.SourceCodeInfo + * @interface ILocation + * @property {Array.|null} [path] Location path + * @property {Array.|null} [span] Location span + * @property {string|null} [leadingComments] Location leadingComments + * @property {string|null} [trailingComments] Location trailingComments + * @property {Array.|null} [leadingDetachedComments] Location leadingDetachedComments */ /** - * Constructs a new ExistenceFilter. - * @memberof google.firestore.v1 - * @classdesc Represents an ExistenceFilter. - * @implements IExistenceFilter + * Constructs a new Location. + * @memberof google.protobuf.SourceCodeInfo + * @classdesc Represents a Location. + * @implements ILocation * @constructor - * @param {google.firestore.v1.IExistenceFilter=} [properties] Properties to set + * @param {google.protobuf.SourceCodeInfo.ILocation=} [properties] Properties to set */ - function ExistenceFilter(properties) { + function Location(properties) { + this.path = []; + this.span = []; + this.leadingDetachedComments = []; if (properties) for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) if (properties[keys[i]] != null) @@ -22217,143 +22610,180 @@ } /** - * ExistenceFilter targetId. - * @member {number} targetId - * @memberof google.firestore.v1.ExistenceFilter + * Location path. + * @member {Array.} path + * @memberof google.protobuf.SourceCodeInfo.Location * @instance */ - ExistenceFilter.prototype.targetId = 0; + Location.prototype.path = $util.emptyArray; /** - * ExistenceFilter count. - * @member {number} count - * @memberof google.firestore.v1.ExistenceFilter + * Location span. + * @member {Array.} span + * @memberof google.protobuf.SourceCodeInfo.Location * @instance */ - ExistenceFilter.prototype.count = 0; + Location.prototype.span = $util.emptyArray; /** - * ExistenceFilter unchangedNames. - * @member {google.firestore.v1.IBloomFilter|null|undefined} unchangedNames - * @memberof google.firestore.v1.ExistenceFilter + * Location leadingComments. + * @member {string} leadingComments + * @memberof google.protobuf.SourceCodeInfo.Location * @instance */ - ExistenceFilter.prototype.unchangedNames = null; + Location.prototype.leadingComments = ""; /** - * Creates an ExistenceFilter message from a plain object. Also converts values to their respective internal types. + * Location trailingComments. + * @member {string} trailingComments + * @memberof google.protobuf.SourceCodeInfo.Location + * @instance + */ + Location.prototype.trailingComments = ""; + + /** + * Location leadingDetachedComments. + * @member {Array.} leadingDetachedComments + * @memberof google.protobuf.SourceCodeInfo.Location + * @instance + */ + Location.prototype.leadingDetachedComments = $util.emptyArray; + + /** + * Creates a Location message from a plain object. Also converts values to their respective internal types. * @function fromObject - * @memberof google.firestore.v1.ExistenceFilter + * @memberof google.protobuf.SourceCodeInfo.Location * @static * @param {Object.} object Plain object - * @returns {google.firestore.v1.ExistenceFilter} ExistenceFilter + * @returns {google.protobuf.SourceCodeInfo.Location} Location */ - ExistenceFilter.fromObject = function fromObject(object) { - if (object instanceof $root.google.firestore.v1.ExistenceFilter) + Location.fromObject = function fromObject(object) { + if (object instanceof $root.google.protobuf.SourceCodeInfo.Location) return object; - var message = new $root.google.firestore.v1.ExistenceFilter(); - if (object.targetId != null) - message.targetId = object.targetId | 0; - if (object.count != null) - message.count = object.count | 0; - if (object.unchangedNames != null) { - if (typeof object.unchangedNames !== "object") - throw TypeError(".google.firestore.v1.ExistenceFilter.unchangedNames: object expected"); - message.unchangedNames = $root.google.firestore.v1.BloomFilter.fromObject(object.unchangedNames); + var message = new $root.google.protobuf.SourceCodeInfo.Location(); + if (object.path) { + if (!Array.isArray(object.path)) + throw TypeError(".google.protobuf.SourceCodeInfo.Location.path: array expected"); + message.path = []; + for (var i = 0; i < object.path.length; ++i) + message.path[i] = object.path[i] | 0; + } + if (object.span) { + if (!Array.isArray(object.span)) + throw TypeError(".google.protobuf.SourceCodeInfo.Location.span: array expected"); + message.span = []; + for (var i = 0; i < object.span.length; ++i) + message.span[i] = object.span[i] | 0; + } + if (object.leadingComments != null) + message.leadingComments = String(object.leadingComments); + if (object.trailingComments != null) + message.trailingComments = String(object.trailingComments); + if (object.leadingDetachedComments) { + if (!Array.isArray(object.leadingDetachedComments)) + throw TypeError(".google.protobuf.SourceCodeInfo.Location.leadingDetachedComments: array expected"); + message.leadingDetachedComments = []; + for (var i = 0; i < object.leadingDetachedComments.length; ++i) + message.leadingDetachedComments[i] = String(object.leadingDetachedComments[i]); } return message; }; /** - * Creates a plain object from an ExistenceFilter message. Also converts values to other types if specified. + * Creates a plain object from a Location message. Also converts values to other types if specified. * @function toObject - * @memberof google.firestore.v1.ExistenceFilter + * @memberof google.protobuf.SourceCodeInfo.Location * @static - * @param {google.firestore.v1.ExistenceFilter} message ExistenceFilter + * @param {google.protobuf.SourceCodeInfo.Location} message Location * @param {$protobuf.IConversionOptions} [options] Conversion options * @returns {Object.} Plain object */ - ExistenceFilter.toObject = function toObject(message, options) { + Location.toObject = function toObject(message, options) { if (!options) options = {}; var object = {}; + if (options.arrays || options.defaults) { + object.path = []; + object.span = []; + object.leadingDetachedComments = []; + } if (options.defaults) { - object.targetId = 0; - object.count = 0; - object.unchangedNames = null; + object.leadingComments = ""; + object.trailingComments = ""; + } + if (message.path && message.path.length) { + object.path = []; + for (var j = 0; j < message.path.length; ++j) + object.path[j] = message.path[j]; + } + if (message.span && message.span.length) { + object.span = []; + for (var j = 0; j < message.span.length; ++j) + object.span[j] = message.span[j]; + } + if (message.leadingComments != null && message.hasOwnProperty("leadingComments")) + object.leadingComments = message.leadingComments; + if (message.trailingComments != null && message.hasOwnProperty("trailingComments")) + object.trailingComments = message.trailingComments; + if (message.leadingDetachedComments && message.leadingDetachedComments.length) { + object.leadingDetachedComments = []; + for (var j = 0; j < message.leadingDetachedComments.length; ++j) + object.leadingDetachedComments[j] = message.leadingDetachedComments[j]; } - if (message.targetId != null && message.hasOwnProperty("targetId")) - object.targetId = message.targetId; - if (message.count != null && message.hasOwnProperty("count")) - object.count = message.count; - if (message.unchangedNames != null && message.hasOwnProperty("unchangedNames")) - object.unchangedNames = $root.google.firestore.v1.BloomFilter.toObject(message.unchangedNames, options); return object; }; /** - * Converts this ExistenceFilter to JSON. + * Converts this Location to JSON. * @function toJSON - * @memberof google.firestore.v1.ExistenceFilter + * @memberof google.protobuf.SourceCodeInfo.Location * @instance * @returns {Object.} JSON object */ - ExistenceFilter.prototype.toJSON = function toJSON() { + Location.prototype.toJSON = function toJSON() { return this.constructor.toObject(this, $protobuf.util.toJSONOptions); }; /** - * Gets the default type url for ExistenceFilter + * Gets the default type url for Location * @function getTypeUrl - * @memberof google.firestore.v1.ExistenceFilter + * @memberof google.protobuf.SourceCodeInfo.Location * @static * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") * @returns {string} The default type url */ - ExistenceFilter.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + Location.getTypeUrl = function getTypeUrl(typeUrlPrefix) { if (typeUrlPrefix === undefined) { typeUrlPrefix = "type.googleapis.com"; } - return typeUrlPrefix + "/google.firestore.v1.ExistenceFilter"; + return typeUrlPrefix + "/google.protobuf.SourceCodeInfo.Location"; }; - return ExistenceFilter; + return Location; })(); - return v1; + return SourceCodeInfo; })(); - return firestore; - })(); - - google.type = (function() { - - /** - * Namespace type. - * @memberof google - * @namespace - */ - var type = {}; - - type.LatLng = (function() { + protobuf.GeneratedCodeInfo = (function() { /** - * Properties of a LatLng. - * @memberof google.type - * @interface ILatLng - * @property {number|null} [latitude] LatLng latitude - * @property {number|null} [longitude] LatLng longitude + * Properties of a GeneratedCodeInfo. + * @memberof google.protobuf + * @interface IGeneratedCodeInfo + * @property {Array.|null} [annotation] GeneratedCodeInfo annotation */ /** - * Constructs a new LatLng. - * @memberof google.type - * @classdesc Represents a LatLng. - * @implements ILatLng + * Constructs a new GeneratedCodeInfo. + * @memberof google.protobuf + * @classdesc Represents a GeneratedCodeInfo. + * @implements IGeneratedCodeInfo * @constructor - * @param {google.type.ILatLng=} [properties] Properties to set + * @param {google.protobuf.IGeneratedCodeInfo=} [properties] Properties to set */ - function LatLng(properties) { + function GeneratedCodeInfo(properties) { + this.annotation = []; if (properties) for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) if (properties[keys[i]] != null) @@ -22361,284 +22791,308 @@ } /** - * LatLng latitude. - * @member {number} latitude - * @memberof google.type.LatLng - * @instance - */ - LatLng.prototype.latitude = 0; - - /** - * LatLng longitude. - * @member {number} longitude - * @memberof google.type.LatLng + * GeneratedCodeInfo annotation. + * @member {Array.} annotation + * @memberof google.protobuf.GeneratedCodeInfo * @instance */ - LatLng.prototype.longitude = 0; + GeneratedCodeInfo.prototype.annotation = $util.emptyArray; /** - * Creates a LatLng message from a plain object. Also converts values to their respective internal types. + * Creates a GeneratedCodeInfo message from a plain object. Also converts values to their respective internal types. * @function fromObject - * @memberof google.type.LatLng + * @memberof google.protobuf.GeneratedCodeInfo * @static * @param {Object.} object Plain object - * @returns {google.type.LatLng} LatLng + * @returns {google.protobuf.GeneratedCodeInfo} GeneratedCodeInfo */ - LatLng.fromObject = function fromObject(object) { - if (object instanceof $root.google.type.LatLng) + GeneratedCodeInfo.fromObject = function fromObject(object) { + if (object instanceof $root.google.protobuf.GeneratedCodeInfo) return object; - var message = new $root.google.type.LatLng(); - if (object.latitude != null) - message.latitude = Number(object.latitude); - if (object.longitude != null) - message.longitude = Number(object.longitude); + var message = new $root.google.protobuf.GeneratedCodeInfo(); + if (object.annotation) { + if (!Array.isArray(object.annotation)) + throw TypeError(".google.protobuf.GeneratedCodeInfo.annotation: array expected"); + message.annotation = []; + for (var i = 0; i < object.annotation.length; ++i) { + if (typeof object.annotation[i] !== "object") + throw TypeError(".google.protobuf.GeneratedCodeInfo.annotation: object expected"); + message.annotation[i] = $root.google.protobuf.GeneratedCodeInfo.Annotation.fromObject(object.annotation[i]); + } + } return message; }; /** - * Creates a plain object from a LatLng message. Also converts values to other types if specified. + * Creates a plain object from a GeneratedCodeInfo message. Also converts values to other types if specified. * @function toObject - * @memberof google.type.LatLng + * @memberof google.protobuf.GeneratedCodeInfo * @static - * @param {google.type.LatLng} message LatLng + * @param {google.protobuf.GeneratedCodeInfo} message GeneratedCodeInfo * @param {$protobuf.IConversionOptions} [options] Conversion options * @returns {Object.} Plain object */ - LatLng.toObject = function toObject(message, options) { + GeneratedCodeInfo.toObject = function toObject(message, options) { if (!options) options = {}; var object = {}; - if (options.defaults) { - object.latitude = 0; - object.longitude = 0; + if (options.arrays || options.defaults) + object.annotation = []; + if (message.annotation && message.annotation.length) { + object.annotation = []; + for (var j = 0; j < message.annotation.length; ++j) + object.annotation[j] = $root.google.protobuf.GeneratedCodeInfo.Annotation.toObject(message.annotation[j], options); } - if (message.latitude != null && message.hasOwnProperty("latitude")) - object.latitude = options.json && !isFinite(message.latitude) ? String(message.latitude) : message.latitude; - if (message.longitude != null && message.hasOwnProperty("longitude")) - object.longitude = options.json && !isFinite(message.longitude) ? String(message.longitude) : message.longitude; return object; }; /** - * Converts this LatLng to JSON. + * Converts this GeneratedCodeInfo to JSON. * @function toJSON - * @memberof google.type.LatLng + * @memberof google.protobuf.GeneratedCodeInfo * @instance * @returns {Object.} JSON object */ - LatLng.prototype.toJSON = function toJSON() { + GeneratedCodeInfo.prototype.toJSON = function toJSON() { return this.constructor.toObject(this, $protobuf.util.toJSONOptions); }; /** - * Gets the default type url for LatLng + * Gets the default type url for GeneratedCodeInfo * @function getTypeUrl - * @memberof google.type.LatLng + * @memberof google.protobuf.GeneratedCodeInfo * @static * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") * @returns {string} The default type url */ - LatLng.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + GeneratedCodeInfo.getTypeUrl = function getTypeUrl(typeUrlPrefix) { if (typeUrlPrefix === undefined) { typeUrlPrefix = "type.googleapis.com"; } - return typeUrlPrefix + "/google.type.LatLng"; + return typeUrlPrefix + "/google.protobuf.GeneratedCodeInfo"; }; - return LatLng; - })(); - - /** - * DayOfWeek enum. - * @name google.type.DayOfWeek - * @enum {string} - * @property {string} DAY_OF_WEEK_UNSPECIFIED=DAY_OF_WEEK_UNSPECIFIED DAY_OF_WEEK_UNSPECIFIED value - * @property {string} MONDAY=MONDAY MONDAY value - * @property {string} TUESDAY=TUESDAY TUESDAY value - * @property {string} WEDNESDAY=WEDNESDAY WEDNESDAY value - * @property {string} THURSDAY=THURSDAY THURSDAY value - * @property {string} FRIDAY=FRIDAY FRIDAY value - * @property {string} SATURDAY=SATURDAY SATURDAY value - * @property {string} SUNDAY=SUNDAY SUNDAY value - */ - type.DayOfWeek = (function() { - var valuesById = {}, values = Object.create(valuesById); - values[valuesById[0] = "DAY_OF_WEEK_UNSPECIFIED"] = "DAY_OF_WEEK_UNSPECIFIED"; - values[valuesById[1] = "MONDAY"] = "MONDAY"; - values[valuesById[2] = "TUESDAY"] = "TUESDAY"; - values[valuesById[3] = "WEDNESDAY"] = "WEDNESDAY"; - values[valuesById[4] = "THURSDAY"] = "THURSDAY"; - values[valuesById[5] = "FRIDAY"] = "FRIDAY"; - values[valuesById[6] = "SATURDAY"] = "SATURDAY"; - values[valuesById[7] = "SUNDAY"] = "SUNDAY"; - return values; - })(); + GeneratedCodeInfo.Annotation = (function() { - return type; - })(); + /** + * Properties of an Annotation. + * @memberof google.protobuf.GeneratedCodeInfo + * @interface IAnnotation + * @property {Array.|null} [path] Annotation path + * @property {string|null} [sourceFile] Annotation sourceFile + * @property {number|null} [begin] Annotation begin + * @property {number|null} [end] Annotation end + * @property {google.protobuf.GeneratedCodeInfo.Annotation.Semantic|null} [semantic] Annotation semantic + */ - google.api = (function() { + /** + * Constructs a new Annotation. + * @memberof google.protobuf.GeneratedCodeInfo + * @classdesc Represents an Annotation. + * @implements IAnnotation + * @constructor + * @param {google.protobuf.GeneratedCodeInfo.IAnnotation=} [properties] Properties to set + */ + function Annotation(properties) { + this.path = []; + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } - /** - * Namespace api. - * @memberof google - * @namespace - */ - var api = {}; + /** + * Annotation path. + * @member {Array.} path + * @memberof google.protobuf.GeneratedCodeInfo.Annotation + * @instance + */ + Annotation.prototype.path = $util.emptyArray; - api.Http = (function() { + /** + * Annotation sourceFile. + * @member {string} sourceFile + * @memberof google.protobuf.GeneratedCodeInfo.Annotation + * @instance + */ + Annotation.prototype.sourceFile = ""; - /** - * Properties of a Http. - * @memberof google.api - * @interface IHttp - * @property {Array.|null} [rules] Http rules - * @property {boolean|null} [fullyDecodeReservedExpansion] Http fullyDecodeReservedExpansion - */ + /** + * Annotation begin. + * @member {number} begin + * @memberof google.protobuf.GeneratedCodeInfo.Annotation + * @instance + */ + Annotation.prototype.begin = 0; - /** - * Constructs a new Http. - * @memberof google.api - * @classdesc Represents a Http. - * @implements IHttp - * @constructor - * @param {google.api.IHttp=} [properties] Properties to set - */ - function Http(properties) { - this.rules = []; - if (properties) - for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) - if (properties[keys[i]] != null) - this[keys[i]] = properties[keys[i]]; - } + /** + * Annotation end. + * @member {number} end + * @memberof google.protobuf.GeneratedCodeInfo.Annotation + * @instance + */ + Annotation.prototype.end = 0; - /** - * Http rules. - * @member {Array.} rules - * @memberof google.api.Http - * @instance - */ - Http.prototype.rules = $util.emptyArray; + /** + * Annotation semantic. + * @member {google.protobuf.GeneratedCodeInfo.Annotation.Semantic} semantic + * @memberof google.protobuf.GeneratedCodeInfo.Annotation + * @instance + */ + Annotation.prototype.semantic = 0; - /** - * Http fullyDecodeReservedExpansion. - * @member {boolean} fullyDecodeReservedExpansion - * @memberof google.api.Http - * @instance - */ - Http.prototype.fullyDecodeReservedExpansion = false; + /** + * Creates an Annotation message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.protobuf.GeneratedCodeInfo.Annotation + * @static + * @param {Object.} object Plain object + * @returns {google.protobuf.GeneratedCodeInfo.Annotation} Annotation + */ + Annotation.fromObject = function fromObject(object) { + if (object instanceof $root.google.protobuf.GeneratedCodeInfo.Annotation) + return object; + var message = new $root.google.protobuf.GeneratedCodeInfo.Annotation(); + if (object.path) { + if (!Array.isArray(object.path)) + throw TypeError(".google.protobuf.GeneratedCodeInfo.Annotation.path: array expected"); + message.path = []; + for (var i = 0; i < object.path.length; ++i) + message.path[i] = object.path[i] | 0; + } + if (object.sourceFile != null) + message.sourceFile = String(object.sourceFile); + if (object.begin != null) + message.begin = object.begin | 0; + if (object.end != null) + message.end = object.end | 0; + switch (object.semantic) { + default: + if (typeof object.semantic === "number") { + message.semantic = object.semantic; + break; + } + break; + case "NONE": + case 0: + message.semantic = 0; + break; + case "SET": + case 1: + message.semantic = 1; + break; + case "ALIAS": + case 2: + message.semantic = 2; + break; + } + return message; + }; - /** - * Creates a Http message from a plain object. Also converts values to their respective internal types. - * @function fromObject - * @memberof google.api.Http - * @static - * @param {Object.} object Plain object - * @returns {google.api.Http} Http - */ - Http.fromObject = function fromObject(object) { - if (object instanceof $root.google.api.Http) - return object; - var message = new $root.google.api.Http(); - if (object.rules) { - if (!Array.isArray(object.rules)) - throw TypeError(".google.api.Http.rules: array expected"); - message.rules = []; - for (var i = 0; i < object.rules.length; ++i) { - if (typeof object.rules[i] !== "object") - throw TypeError(".google.api.Http.rules: object expected"); - message.rules[i] = $root.google.api.HttpRule.fromObject(object.rules[i]); + /** + * Creates a plain object from an Annotation message. Also converts values to other types if specified. + * @function toObject + * @memberof google.protobuf.GeneratedCodeInfo.Annotation + * @static + * @param {google.protobuf.GeneratedCodeInfo.Annotation} message Annotation + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + Annotation.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.arrays || options.defaults) + object.path = []; + if (options.defaults) { + object.sourceFile = ""; + object.begin = 0; + object.end = 0; + object.semantic = options.enums === String ? "NONE" : 0; } - } - if (object.fullyDecodeReservedExpansion != null) - message.fullyDecodeReservedExpansion = Boolean(object.fullyDecodeReservedExpansion); - return message; - }; + if (message.path && message.path.length) { + object.path = []; + for (var j = 0; j < message.path.length; ++j) + object.path[j] = message.path[j]; + } + if (message.sourceFile != null && message.hasOwnProperty("sourceFile")) + object.sourceFile = message.sourceFile; + if (message.begin != null && message.hasOwnProperty("begin")) + object.begin = message.begin; + if (message.end != null && message.hasOwnProperty("end")) + object.end = message.end; + if (message.semantic != null && message.hasOwnProperty("semantic")) + object.semantic = options.enums === String ? $root.google.protobuf.GeneratedCodeInfo.Annotation.Semantic[message.semantic] === undefined ? message.semantic : $root.google.protobuf.GeneratedCodeInfo.Annotation.Semantic[message.semantic] : message.semantic; + return object; + }; + + /** + * Converts this Annotation to JSON. + * @function toJSON + * @memberof google.protobuf.GeneratedCodeInfo.Annotation + * @instance + * @returns {Object.} JSON object + */ + Annotation.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; - /** - * Creates a plain object from a Http message. Also converts values to other types if specified. - * @function toObject - * @memberof google.api.Http - * @static - * @param {google.api.Http} message Http - * @param {$protobuf.IConversionOptions} [options] Conversion options - * @returns {Object.} Plain object - */ - Http.toObject = function toObject(message, options) { - if (!options) - options = {}; - var object = {}; - if (options.arrays || options.defaults) - object.rules = []; - if (options.defaults) - object.fullyDecodeReservedExpansion = false; - if (message.rules && message.rules.length) { - object.rules = []; - for (var j = 0; j < message.rules.length; ++j) - object.rules[j] = $root.google.api.HttpRule.toObject(message.rules[j], options); - } - if (message.fullyDecodeReservedExpansion != null && message.hasOwnProperty("fullyDecodeReservedExpansion")) - object.fullyDecodeReservedExpansion = message.fullyDecodeReservedExpansion; - return object; - }; + /** + * Gets the default type url for Annotation + * @function getTypeUrl + * @memberof google.protobuf.GeneratedCodeInfo.Annotation + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + Annotation.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.protobuf.GeneratedCodeInfo.Annotation"; + }; - /** - * Converts this Http to JSON. - * @function toJSON - * @memberof google.api.Http - * @instance - * @returns {Object.} JSON object - */ - Http.prototype.toJSON = function toJSON() { - return this.constructor.toObject(this, $protobuf.util.toJSONOptions); - }; + /** + * Semantic enum. + * @name google.protobuf.GeneratedCodeInfo.Annotation.Semantic + * @enum {string} + * @property {string} NONE=NONE NONE value + * @property {string} SET=SET SET value + * @property {string} ALIAS=ALIAS ALIAS value + */ + Annotation.Semantic = (function() { + var valuesById = {}, values = Object.create(valuesById); + values[valuesById[0] = "NONE"] = "NONE"; + values[valuesById[1] = "SET"] = "SET"; + values[valuesById[2] = "ALIAS"] = "ALIAS"; + return values; + })(); - /** - * Gets the default type url for Http - * @function getTypeUrl - * @memberof google.api.Http - * @static - * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") - * @returns {string} The default type url - */ - Http.getTypeUrl = function getTypeUrl(typeUrlPrefix) { - if (typeUrlPrefix === undefined) { - typeUrlPrefix = "type.googleapis.com"; - } - return typeUrlPrefix + "/google.api.Http"; - }; + return Annotation; + })(); - return Http; + return GeneratedCodeInfo; })(); - api.HttpRule = (function() { + protobuf.Struct = (function() { /** - * Properties of a HttpRule. - * @memberof google.api - * @interface IHttpRule - * @property {string|null} [selector] HttpRule selector - * @property {string|null} [get] HttpRule get - * @property {string|null} [put] HttpRule put - * @property {string|null} [post] HttpRule post - * @property {string|null} ["delete"] HttpRule delete - * @property {string|null} [patch] HttpRule patch - * @property {google.api.ICustomHttpPattern|null} [custom] HttpRule custom - * @property {string|null} [body] HttpRule body - * @property {string|null} [responseBody] HttpRule responseBody - * @property {Array.|null} [additionalBindings] HttpRule additionalBindings + * Properties of a Struct. + * @memberof google.protobuf + * @interface IStruct + * @property {Object.|null} [fields] Struct fields */ /** - * Constructs a new HttpRule. - * @memberof google.api - * @classdesc Represents a HttpRule. - * @implements IHttpRule + * Constructs a new Struct. + * @memberof google.protobuf + * @classdesc Represents a Struct. + * @implements IStruct * @constructor - * @param {google.api.IHttpRule=} [properties] Properties to set + * @param {google.protobuf.IStruct=} [properties] Properties to set */ - function HttpRule(properties) { - this.additionalBindings = []; + function Struct(properties) { + this.fields = {}; if (properties) for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) if (properties[keys[i]] != null) @@ -22646,257 +23100,114 @@ } /** - * HttpRule selector. - * @member {string} selector - * @memberof google.api.HttpRule - * @instance - */ - HttpRule.prototype.selector = ""; - - /** - * HttpRule get. - * @member {string|null|undefined} get - * @memberof google.api.HttpRule - * @instance - */ - HttpRule.prototype.get = null; - - /** - * HttpRule put. - * @member {string|null|undefined} put - * @memberof google.api.HttpRule - * @instance - */ - HttpRule.prototype.put = null; - - /** - * HttpRule post. - * @member {string|null|undefined} post - * @memberof google.api.HttpRule - * @instance - */ - HttpRule.prototype.post = null; - - /** - * HttpRule delete. - * @member {string|null|undefined} delete - * @memberof google.api.HttpRule - * @instance - */ - HttpRule.prototype["delete"] = null; - - /** - * HttpRule patch. - * @member {string|null|undefined} patch - * @memberof google.api.HttpRule - * @instance - */ - HttpRule.prototype.patch = null; - - /** - * HttpRule custom. - * @member {google.api.ICustomHttpPattern|null|undefined} custom - * @memberof google.api.HttpRule - * @instance - */ - HttpRule.prototype.custom = null; - - /** - * HttpRule body. - * @member {string} body - * @memberof google.api.HttpRule - * @instance - */ - HttpRule.prototype.body = ""; - - /** - * HttpRule responseBody. - * @member {string} responseBody - * @memberof google.api.HttpRule - * @instance - */ - HttpRule.prototype.responseBody = ""; - - /** - * HttpRule additionalBindings. - * @member {Array.} additionalBindings - * @memberof google.api.HttpRule - * @instance - */ - HttpRule.prototype.additionalBindings = $util.emptyArray; - - // OneOf field names bound to virtual getters and setters - var $oneOfFields; - - /** - * HttpRule pattern. - * @member {"get"|"put"|"post"|"delete"|"patch"|"custom"|undefined} pattern - * @memberof google.api.HttpRule + * Struct fields. + * @member {Object.} fields + * @memberof google.protobuf.Struct * @instance */ - Object.defineProperty(HttpRule.prototype, "pattern", { - get: $util.oneOfGetter($oneOfFields = ["get", "put", "post", "delete", "patch", "custom"]), - set: $util.oneOfSetter($oneOfFields) - }); + Struct.prototype.fields = $util.emptyObject; /** - * Creates a HttpRule message from a plain object. Also converts values to their respective internal types. + * Creates a Struct message from a plain object. Also converts values to their respective internal types. * @function fromObject - * @memberof google.api.HttpRule + * @memberof google.protobuf.Struct * @static * @param {Object.} object Plain object - * @returns {google.api.HttpRule} HttpRule + * @returns {google.protobuf.Struct} Struct */ - HttpRule.fromObject = function fromObject(object) { - if (object instanceof $root.google.api.HttpRule) - return object; - var message = new $root.google.api.HttpRule(); - if (object.selector != null) - message.selector = String(object.selector); - if (object.get != null) - message.get = String(object.get); - if (object.put != null) - message.put = String(object.put); - if (object.post != null) - message.post = String(object.post); - if (object["delete"] != null) - message["delete"] = String(object["delete"]); - if (object.patch != null) - message.patch = String(object.patch); - if (object.custom != null) { - if (typeof object.custom !== "object") - throw TypeError(".google.api.HttpRule.custom: object expected"); - message.custom = $root.google.api.CustomHttpPattern.fromObject(object.custom); - } - if (object.body != null) - message.body = String(object.body); - if (object.responseBody != null) - message.responseBody = String(object.responseBody); - if (object.additionalBindings) { - if (!Array.isArray(object.additionalBindings)) - throw TypeError(".google.api.HttpRule.additionalBindings: array expected"); - message.additionalBindings = []; - for (var i = 0; i < object.additionalBindings.length; ++i) { - if (typeof object.additionalBindings[i] !== "object") - throw TypeError(".google.api.HttpRule.additionalBindings: object expected"); - message.additionalBindings[i] = $root.google.api.HttpRule.fromObject(object.additionalBindings[i]); + Struct.fromObject = function fromObject(object) { + if (object instanceof $root.google.protobuf.Struct) + return object; + var message = new $root.google.protobuf.Struct(); + if (object.fields) { + if (typeof object.fields !== "object") + throw TypeError(".google.protobuf.Struct.fields: object expected"); + message.fields = {}; + for (var keys = Object.keys(object.fields), i = 0; i < keys.length; ++i) { + if (typeof object.fields[keys[i]] !== "object") + throw TypeError(".google.protobuf.Struct.fields: object expected"); + message.fields[keys[i]] = $root.google.protobuf.Value.fromObject(object.fields[keys[i]]); } } return message; }; /** - * Creates a plain object from a HttpRule message. Also converts values to other types if specified. + * Creates a plain object from a Struct message. Also converts values to other types if specified. * @function toObject - * @memberof google.api.HttpRule + * @memberof google.protobuf.Struct * @static - * @param {google.api.HttpRule} message HttpRule + * @param {google.protobuf.Struct} message Struct * @param {$protobuf.IConversionOptions} [options] Conversion options * @returns {Object.} Plain object */ - HttpRule.toObject = function toObject(message, options) { + Struct.toObject = function toObject(message, options) { if (!options) options = {}; var object = {}; - if (options.arrays || options.defaults) - object.additionalBindings = []; - if (options.defaults) { - object.selector = ""; - object.body = ""; - object.responseBody = ""; - } - if (message.selector != null && message.hasOwnProperty("selector")) - object.selector = message.selector; - if (message.get != null && message.hasOwnProperty("get")) { - object.get = message.get; - if (options.oneofs) - object.pattern = "get"; - } - if (message.put != null && message.hasOwnProperty("put")) { - object.put = message.put; - if (options.oneofs) - object.pattern = "put"; - } - if (message.post != null && message.hasOwnProperty("post")) { - object.post = message.post; - if (options.oneofs) - object.pattern = "post"; - } - if (message["delete"] != null && message.hasOwnProperty("delete")) { - object["delete"] = message["delete"]; - if (options.oneofs) - object.pattern = "delete"; - } - if (message.patch != null && message.hasOwnProperty("patch")) { - object.patch = message.patch; - if (options.oneofs) - object.pattern = "patch"; - } - if (message.body != null && message.hasOwnProperty("body")) - object.body = message.body; - if (message.custom != null && message.hasOwnProperty("custom")) { - object.custom = $root.google.api.CustomHttpPattern.toObject(message.custom, options); - if (options.oneofs) - object.pattern = "custom"; - } - if (message.additionalBindings && message.additionalBindings.length) { - object.additionalBindings = []; - for (var j = 0; j < message.additionalBindings.length; ++j) - object.additionalBindings[j] = $root.google.api.HttpRule.toObject(message.additionalBindings[j], options); + if (options.objects || options.defaults) + object.fields = {}; + var keys2; + if (message.fields && (keys2 = Object.keys(message.fields)).length) { + object.fields = {}; + for (var j = 0; j < keys2.length; ++j) + object.fields[keys2[j]] = $root.google.protobuf.Value.toObject(message.fields[keys2[j]], options); } - if (message.responseBody != null && message.hasOwnProperty("responseBody")) - object.responseBody = message.responseBody; return object; }; /** - * Converts this HttpRule to JSON. + * Converts this Struct to JSON. * @function toJSON - * @memberof google.api.HttpRule + * @memberof google.protobuf.Struct * @instance * @returns {Object.} JSON object */ - HttpRule.prototype.toJSON = function toJSON() { + Struct.prototype.toJSON = function toJSON() { return this.constructor.toObject(this, $protobuf.util.toJSONOptions); }; /** - * Gets the default type url for HttpRule + * Gets the default type url for Struct * @function getTypeUrl - * @memberof google.api.HttpRule + * @memberof google.protobuf.Struct * @static * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") * @returns {string} The default type url */ - HttpRule.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + Struct.getTypeUrl = function getTypeUrl(typeUrlPrefix) { if (typeUrlPrefix === undefined) { typeUrlPrefix = "type.googleapis.com"; } - return typeUrlPrefix + "/google.api.HttpRule"; + return typeUrlPrefix + "/google.protobuf.Struct"; }; - return HttpRule; + return Struct; })(); - api.CustomHttpPattern = (function() { + protobuf.Value = (function() { /** - * Properties of a CustomHttpPattern. - * @memberof google.api - * @interface ICustomHttpPattern - * @property {string|null} [kind] CustomHttpPattern kind - * @property {string|null} [path] CustomHttpPattern path + * Properties of a Value. + * @memberof google.protobuf + * @interface IValue + * @property {google.protobuf.NullValue|null} [nullValue] Value nullValue + * @property {number|null} [numberValue] Value numberValue + * @property {string|null} [stringValue] Value stringValue + * @property {boolean|null} [boolValue] Value boolValue + * @property {google.protobuf.IStruct|null} [structValue] Value structValue + * @property {google.protobuf.IListValue|null} [listValue] Value listValue */ /** - * Constructs a new CustomHttpPattern. - * @memberof google.api - * @classdesc Represents a CustomHttpPattern. - * @implements ICustomHttpPattern + * Constructs a new Value. + * @memberof google.protobuf + * @classdesc Represents a Value. + * @implements IValue * @constructor - * @param {google.api.ICustomHttpPattern=} [properties] Properties to set + * @param {google.protobuf.IValue=} [properties] Properties to set */ - function CustomHttpPattern(properties) { + function Value(properties) { if (properties) for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) if (properties[keys[i]] != null) @@ -22904,113 +23215,216 @@ } /** - * CustomHttpPattern kind. - * @member {string} kind - * @memberof google.api.CustomHttpPattern + * Value nullValue. + * @member {google.protobuf.NullValue|null|undefined} nullValue + * @memberof google.protobuf.Value * @instance */ - CustomHttpPattern.prototype.kind = ""; + Value.prototype.nullValue = null; /** - * CustomHttpPattern path. - * @member {string} path - * @memberof google.api.CustomHttpPattern + * Value numberValue. + * @member {number|null|undefined} numberValue + * @memberof google.protobuf.Value * @instance */ - CustomHttpPattern.prototype.path = ""; + Value.prototype.numberValue = null; /** - * Creates a CustomHttpPattern message from a plain object. Also converts values to their respective internal types. + * Value stringValue. + * @member {string|null|undefined} stringValue + * @memberof google.protobuf.Value + * @instance + */ + Value.prototype.stringValue = null; + + /** + * Value boolValue. + * @member {boolean|null|undefined} boolValue + * @memberof google.protobuf.Value + * @instance + */ + Value.prototype.boolValue = null; + + /** + * Value structValue. + * @member {google.protobuf.IStruct|null|undefined} structValue + * @memberof google.protobuf.Value + * @instance + */ + Value.prototype.structValue = null; + + /** + * Value listValue. + * @member {google.protobuf.IListValue|null|undefined} listValue + * @memberof google.protobuf.Value + * @instance + */ + Value.prototype.listValue = null; + + // OneOf field names bound to virtual getters and setters + var $oneOfFields; + + /** + * Value kind. + * @member {"nullValue"|"numberValue"|"stringValue"|"boolValue"|"structValue"|"listValue"|undefined} kind + * @memberof google.protobuf.Value + * @instance + */ + Object.defineProperty(Value.prototype, "kind", { + get: $util.oneOfGetter($oneOfFields = ["nullValue", "numberValue", "stringValue", "boolValue", "structValue", "listValue"]), + set: $util.oneOfSetter($oneOfFields) + }); + + /** + * Creates a Value message from a plain object. Also converts values to their respective internal types. * @function fromObject - * @memberof google.api.CustomHttpPattern + * @memberof google.protobuf.Value * @static * @param {Object.} object Plain object - * @returns {google.api.CustomHttpPattern} CustomHttpPattern + * @returns {google.protobuf.Value} Value */ - CustomHttpPattern.fromObject = function fromObject(object) { - if (object instanceof $root.google.api.CustomHttpPattern) + Value.fromObject = function fromObject(object) { + if (object instanceof $root.google.protobuf.Value) return object; - var message = new $root.google.api.CustomHttpPattern(); - if (object.kind != null) - message.kind = String(object.kind); - if (object.path != null) - message.path = String(object.path); + var message = new $root.google.protobuf.Value(); + switch (object.nullValue) { + default: + if (typeof object.nullValue === "number") { + message.nullValue = object.nullValue; + break; + } + break; + case "NULL_VALUE": + case 0: + message.nullValue = 0; + break; + } + if (object.numberValue != null) + message.numberValue = Number(object.numberValue); + if (object.stringValue != null) + message.stringValue = String(object.stringValue); + if (object.boolValue != null) + message.boolValue = Boolean(object.boolValue); + if (object.structValue != null) { + if (typeof object.structValue !== "object") + throw TypeError(".google.protobuf.Value.structValue: object expected"); + message.structValue = $root.google.protobuf.Struct.fromObject(object.structValue); + } + if (object.listValue != null) { + if (typeof object.listValue !== "object") + throw TypeError(".google.protobuf.Value.listValue: object expected"); + message.listValue = $root.google.protobuf.ListValue.fromObject(object.listValue); + } return message; }; /** - * Creates a plain object from a CustomHttpPattern message. Also converts values to other types if specified. + * Creates a plain object from a Value message. Also converts values to other types if specified. * @function toObject - * @memberof google.api.CustomHttpPattern + * @memberof google.protobuf.Value * @static - * @param {google.api.CustomHttpPattern} message CustomHttpPattern + * @param {google.protobuf.Value} message Value * @param {$protobuf.IConversionOptions} [options] Conversion options * @returns {Object.} Plain object */ - CustomHttpPattern.toObject = function toObject(message, options) { + Value.toObject = function toObject(message, options) { if (!options) options = {}; var object = {}; - if (options.defaults) { - object.kind = ""; - object.path = ""; + if (message.nullValue != null && message.hasOwnProperty("nullValue")) { + object.nullValue = options.enums === String ? $root.google.protobuf.NullValue[message.nullValue] === undefined ? message.nullValue : $root.google.protobuf.NullValue[message.nullValue] : message.nullValue; + if (options.oneofs) + object.kind = "nullValue"; + } + if (message.numberValue != null && message.hasOwnProperty("numberValue")) { + object.numberValue = options.json && !isFinite(message.numberValue) ? String(message.numberValue) : message.numberValue; + if (options.oneofs) + object.kind = "numberValue"; + } + if (message.stringValue != null && message.hasOwnProperty("stringValue")) { + object.stringValue = message.stringValue; + if (options.oneofs) + object.kind = "stringValue"; + } + if (message.boolValue != null && message.hasOwnProperty("boolValue")) { + object.boolValue = message.boolValue; + if (options.oneofs) + object.kind = "boolValue"; + } + if (message.structValue != null && message.hasOwnProperty("structValue")) { + object.structValue = $root.google.protobuf.Struct.toObject(message.structValue, options); + if (options.oneofs) + object.kind = "structValue"; + } + if (message.listValue != null && message.hasOwnProperty("listValue")) { + object.listValue = $root.google.protobuf.ListValue.toObject(message.listValue, options); + if (options.oneofs) + object.kind = "listValue"; } - if (message.kind != null && message.hasOwnProperty("kind")) - object.kind = message.kind; - if (message.path != null && message.hasOwnProperty("path")) - object.path = message.path; return object; }; /** - * Converts this CustomHttpPattern to JSON. + * Converts this Value to JSON. * @function toJSON - * @memberof google.api.CustomHttpPattern + * @memberof google.protobuf.Value * @instance * @returns {Object.} JSON object */ - CustomHttpPattern.prototype.toJSON = function toJSON() { + Value.prototype.toJSON = function toJSON() { return this.constructor.toObject(this, $protobuf.util.toJSONOptions); }; /** - * Gets the default type url for CustomHttpPattern + * Gets the default type url for Value * @function getTypeUrl - * @memberof google.api.CustomHttpPattern + * @memberof google.protobuf.Value * @static * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") * @returns {string} The default type url */ - CustomHttpPattern.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + Value.getTypeUrl = function getTypeUrl(typeUrlPrefix) { if (typeUrlPrefix === undefined) { typeUrlPrefix = "type.googleapis.com"; } - return typeUrlPrefix + "/google.api.CustomHttpPattern"; + return typeUrlPrefix + "/google.protobuf.Value"; }; - return CustomHttpPattern; + return Value; })(); - api.CommonLanguageSettings = (function() { + /** + * NullValue enum. + * @name google.protobuf.NullValue + * @enum {string} + * @property {string} NULL_VALUE=NULL_VALUE NULL_VALUE value + */ + protobuf.NullValue = (function() { + var valuesById = {}, values = Object.create(valuesById); + values[valuesById[0] = "NULL_VALUE"] = "NULL_VALUE"; + return values; + })(); + + protobuf.ListValue = (function() { /** - * Properties of a CommonLanguageSettings. - * @memberof google.api - * @interface ICommonLanguageSettings - * @property {string|null} [referenceDocsUri] CommonLanguageSettings referenceDocsUri - * @property {Array.|null} [destinations] CommonLanguageSettings destinations + * Properties of a ListValue. + * @memberof google.protobuf + * @interface IListValue + * @property {Array.|null} [values] ListValue values */ /** - * Constructs a new CommonLanguageSettings. - * @memberof google.api - * @classdesc Represents a CommonLanguageSettings. - * @implements ICommonLanguageSettings + * Constructs a new ListValue. + * @memberof google.protobuf + * @classdesc Represents a ListValue. + * @implements IListValue * @constructor - * @param {google.api.ICommonLanguageSettings=} [properties] Properties to set + * @param {google.protobuf.IListValue=} [properties] Properties to set */ - function CommonLanguageSettings(properties) { - this.destinations = []; + function ListValue(properties) { + this.values = []; if (properties) for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) if (properties[keys[i]] != null) @@ -23018,451 +23432,236 @@ } /** - * CommonLanguageSettings referenceDocsUri. - * @member {string} referenceDocsUri - * @memberof google.api.CommonLanguageSettings - * @instance - */ - CommonLanguageSettings.prototype.referenceDocsUri = ""; - - /** - * CommonLanguageSettings destinations. - * @member {Array.} destinations - * @memberof google.api.CommonLanguageSettings + * ListValue values. + * @member {Array.} values + * @memberof google.protobuf.ListValue * @instance */ - CommonLanguageSettings.prototype.destinations = $util.emptyArray; + ListValue.prototype.values = $util.emptyArray; /** - * Creates a CommonLanguageSettings message from a plain object. Also converts values to their respective internal types. + * Creates a ListValue message from a plain object. Also converts values to their respective internal types. * @function fromObject - * @memberof google.api.CommonLanguageSettings + * @memberof google.protobuf.ListValue * @static * @param {Object.} object Plain object - * @returns {google.api.CommonLanguageSettings} CommonLanguageSettings + * @returns {google.protobuf.ListValue} ListValue */ - CommonLanguageSettings.fromObject = function fromObject(object) { - if (object instanceof $root.google.api.CommonLanguageSettings) + ListValue.fromObject = function fromObject(object) { + if (object instanceof $root.google.protobuf.ListValue) return object; - var message = new $root.google.api.CommonLanguageSettings(); - if (object.referenceDocsUri != null) - message.referenceDocsUri = String(object.referenceDocsUri); - if (object.destinations) { - if (!Array.isArray(object.destinations)) - throw TypeError(".google.api.CommonLanguageSettings.destinations: array expected"); - message.destinations = []; - for (var i = 0; i < object.destinations.length; ++i) - switch (object.destinations[i]) { - default: - if (typeof object.destinations[i] === "number") { - message.destinations[i] = object.destinations[i]; - break; - } - case "CLIENT_LIBRARY_DESTINATION_UNSPECIFIED": - case 0: - message.destinations[i] = 0; - break; - case "GITHUB": - case 10: - message.destinations[i] = 10; - break; - case "PACKAGE_MANAGER": - case 20: - message.destinations[i] = 20; - break; - } + var message = new $root.google.protobuf.ListValue(); + if (object.values) { + if (!Array.isArray(object.values)) + throw TypeError(".google.protobuf.ListValue.values: array expected"); + message.values = []; + for (var i = 0; i < object.values.length; ++i) { + if (typeof object.values[i] !== "object") + throw TypeError(".google.protobuf.ListValue.values: object expected"); + message.values[i] = $root.google.protobuf.Value.fromObject(object.values[i]); + } } return message; }; /** - * Creates a plain object from a CommonLanguageSettings message. Also converts values to other types if specified. + * Creates a plain object from a ListValue message. Also converts values to other types if specified. * @function toObject - * @memberof google.api.CommonLanguageSettings + * @memberof google.protobuf.ListValue * @static - * @param {google.api.CommonLanguageSettings} message CommonLanguageSettings + * @param {google.protobuf.ListValue} message ListValue * @param {$protobuf.IConversionOptions} [options] Conversion options * @returns {Object.} Plain object */ - CommonLanguageSettings.toObject = function toObject(message, options) { + ListValue.toObject = function toObject(message, options) { if (!options) options = {}; var object = {}; if (options.arrays || options.defaults) - object.destinations = []; - if (options.defaults) - object.referenceDocsUri = ""; - if (message.referenceDocsUri != null && message.hasOwnProperty("referenceDocsUri")) - object.referenceDocsUri = message.referenceDocsUri; - if (message.destinations && message.destinations.length) { - object.destinations = []; - for (var j = 0; j < message.destinations.length; ++j) - object.destinations[j] = options.enums === String ? $root.google.api.ClientLibraryDestination[message.destinations[j]] === undefined ? message.destinations[j] : $root.google.api.ClientLibraryDestination[message.destinations[j]] : message.destinations[j]; + object.values = []; + if (message.values && message.values.length) { + object.values = []; + for (var j = 0; j < message.values.length; ++j) + object.values[j] = $root.google.protobuf.Value.toObject(message.values[j], options); } return object; }; /** - * Converts this CommonLanguageSettings to JSON. + * Converts this ListValue to JSON. * @function toJSON - * @memberof google.api.CommonLanguageSettings + * @memberof google.protobuf.ListValue * @instance * @returns {Object.} JSON object */ - CommonLanguageSettings.prototype.toJSON = function toJSON() { + ListValue.prototype.toJSON = function toJSON() { return this.constructor.toObject(this, $protobuf.util.toJSONOptions); }; /** - * Gets the default type url for CommonLanguageSettings + * Gets the default type url for ListValue * @function getTypeUrl - * @memberof google.api.CommonLanguageSettings + * @memberof google.protobuf.ListValue * @static * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") * @returns {string} The default type url */ - CommonLanguageSettings.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + ListValue.getTypeUrl = function getTypeUrl(typeUrlPrefix) { if (typeUrlPrefix === undefined) { typeUrlPrefix = "type.googleapis.com"; } - return typeUrlPrefix + "/google.api.CommonLanguageSettings"; - }; - - return CommonLanguageSettings; - })(); - - api.ClientLibrarySettings = (function() { - - /** - * Properties of a ClientLibrarySettings. - * @memberof google.api - * @interface IClientLibrarySettings - * @property {string|null} [version] ClientLibrarySettings version - * @property {google.api.LaunchStage|null} [launchStage] ClientLibrarySettings launchStage - * @property {boolean|null} [restNumericEnums] ClientLibrarySettings restNumericEnums - * @property {google.api.IJavaSettings|null} [javaSettings] ClientLibrarySettings javaSettings - * @property {google.api.ICppSettings|null} [cppSettings] ClientLibrarySettings cppSettings - * @property {google.api.IPhpSettings|null} [phpSettings] ClientLibrarySettings phpSettings - * @property {google.api.IPythonSettings|null} [pythonSettings] ClientLibrarySettings pythonSettings - * @property {google.api.INodeSettings|null} [nodeSettings] ClientLibrarySettings nodeSettings - * @property {google.api.IDotnetSettings|null} [dotnetSettings] ClientLibrarySettings dotnetSettings - * @property {google.api.IRubySettings|null} [rubySettings] ClientLibrarySettings rubySettings - * @property {google.api.IGoSettings|null} [goSettings] ClientLibrarySettings goSettings - */ - - /** - * Constructs a new ClientLibrarySettings. - * @memberof google.api - * @classdesc Represents a ClientLibrarySettings. - * @implements IClientLibrarySettings - * @constructor - * @param {google.api.IClientLibrarySettings=} [properties] Properties to set - */ - function ClientLibrarySettings(properties) { - if (properties) - for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) - if (properties[keys[i]] != null) - this[keys[i]] = properties[keys[i]]; - } - - /** - * ClientLibrarySettings version. - * @member {string} version - * @memberof google.api.ClientLibrarySettings - * @instance - */ - ClientLibrarySettings.prototype.version = ""; - - /** - * ClientLibrarySettings launchStage. - * @member {google.api.LaunchStage} launchStage - * @memberof google.api.ClientLibrarySettings - * @instance - */ - ClientLibrarySettings.prototype.launchStage = 0; - - /** - * ClientLibrarySettings restNumericEnums. - * @member {boolean} restNumericEnums - * @memberof google.api.ClientLibrarySettings - * @instance - */ - ClientLibrarySettings.prototype.restNumericEnums = false; - - /** - * ClientLibrarySettings javaSettings. - * @member {google.api.IJavaSettings|null|undefined} javaSettings - * @memberof google.api.ClientLibrarySettings - * @instance - */ - ClientLibrarySettings.prototype.javaSettings = null; - - /** - * ClientLibrarySettings cppSettings. - * @member {google.api.ICppSettings|null|undefined} cppSettings - * @memberof google.api.ClientLibrarySettings - * @instance - */ - ClientLibrarySettings.prototype.cppSettings = null; - - /** - * ClientLibrarySettings phpSettings. - * @member {google.api.IPhpSettings|null|undefined} phpSettings - * @memberof google.api.ClientLibrarySettings - * @instance - */ - ClientLibrarySettings.prototype.phpSettings = null; - - /** - * ClientLibrarySettings pythonSettings. - * @member {google.api.IPythonSettings|null|undefined} pythonSettings - * @memberof google.api.ClientLibrarySettings - * @instance - */ - ClientLibrarySettings.prototype.pythonSettings = null; + return typeUrlPrefix + "/google.protobuf.ListValue"; + }; + + return ListValue; + })(); + + protobuf.Timestamp = (function() { /** - * ClientLibrarySettings nodeSettings. - * @member {google.api.INodeSettings|null|undefined} nodeSettings - * @memberof google.api.ClientLibrarySettings - * @instance + * Properties of a Timestamp. + * @memberof google.protobuf + * @interface ITimestamp + * @property {number|string|null} [seconds] Timestamp seconds + * @property {number|null} [nanos] Timestamp nanos */ - ClientLibrarySettings.prototype.nodeSettings = null; /** - * ClientLibrarySettings dotnetSettings. - * @member {google.api.IDotnetSettings|null|undefined} dotnetSettings - * @memberof google.api.ClientLibrarySettings - * @instance + * Constructs a new Timestamp. + * @memberof google.protobuf + * @classdesc Represents a Timestamp. + * @implements ITimestamp + * @constructor + * @param {google.protobuf.ITimestamp=} [properties] Properties to set */ - ClientLibrarySettings.prototype.dotnetSettings = null; + function Timestamp(properties) { + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } /** - * ClientLibrarySettings rubySettings. - * @member {google.api.IRubySettings|null|undefined} rubySettings - * @memberof google.api.ClientLibrarySettings + * Timestamp seconds. + * @member {number|string} seconds + * @memberof google.protobuf.Timestamp * @instance */ - ClientLibrarySettings.prototype.rubySettings = null; + Timestamp.prototype.seconds = $util.Long ? $util.Long.fromBits(0,0,false) : 0; /** - * ClientLibrarySettings goSettings. - * @member {google.api.IGoSettings|null|undefined} goSettings - * @memberof google.api.ClientLibrarySettings + * Timestamp nanos. + * @member {number} nanos + * @memberof google.protobuf.Timestamp * @instance */ - ClientLibrarySettings.prototype.goSettings = null; + Timestamp.prototype.nanos = 0; /** - * Creates a ClientLibrarySettings message from a plain object. Also converts values to their respective internal types. + * Creates a Timestamp message from a plain object. Also converts values to their respective internal types. * @function fromObject - * @memberof google.api.ClientLibrarySettings + * @memberof google.protobuf.Timestamp * @static * @param {Object.} object Plain object - * @returns {google.api.ClientLibrarySettings} ClientLibrarySettings + * @returns {google.protobuf.Timestamp} Timestamp */ - ClientLibrarySettings.fromObject = function fromObject(object) { - if (object instanceof $root.google.api.ClientLibrarySettings) + Timestamp.fromObject = function fromObject(object) { + if (object instanceof $root.google.protobuf.Timestamp) return object; - var message = new $root.google.api.ClientLibrarySettings(); - if (object.version != null) - message.version = String(object.version); - switch (object.launchStage) { - default: - if (typeof object.launchStage === "number") { - message.launchStage = object.launchStage; - break; - } - break; - case "LAUNCH_STAGE_UNSPECIFIED": - case 0: - message.launchStage = 0; - break; - case "UNIMPLEMENTED": - case 6: - message.launchStage = 6; - break; - case "PRELAUNCH": - case 7: - message.launchStage = 7; - break; - case "EARLY_ACCESS": - case 1: - message.launchStage = 1; - break; - case "ALPHA": - case 2: - message.launchStage = 2; - break; - case "BETA": - case 3: - message.launchStage = 3; - break; - case "GA": - case 4: - message.launchStage = 4; - break; - case "DEPRECATED": - case 5: - message.launchStage = 5; - break; - } - if (object.restNumericEnums != null) - message.restNumericEnums = Boolean(object.restNumericEnums); - if (object.javaSettings != null) { - if (typeof object.javaSettings !== "object") - throw TypeError(".google.api.ClientLibrarySettings.javaSettings: object expected"); - message.javaSettings = $root.google.api.JavaSettings.fromObject(object.javaSettings); - } - if (object.cppSettings != null) { - if (typeof object.cppSettings !== "object") - throw TypeError(".google.api.ClientLibrarySettings.cppSettings: object expected"); - message.cppSettings = $root.google.api.CppSettings.fromObject(object.cppSettings); - } - if (object.phpSettings != null) { - if (typeof object.phpSettings !== "object") - throw TypeError(".google.api.ClientLibrarySettings.phpSettings: object expected"); - message.phpSettings = $root.google.api.PhpSettings.fromObject(object.phpSettings); - } - if (object.pythonSettings != null) { - if (typeof object.pythonSettings !== "object") - throw TypeError(".google.api.ClientLibrarySettings.pythonSettings: object expected"); - message.pythonSettings = $root.google.api.PythonSettings.fromObject(object.pythonSettings); - } - if (object.nodeSettings != null) { - if (typeof object.nodeSettings !== "object") - throw TypeError(".google.api.ClientLibrarySettings.nodeSettings: object expected"); - message.nodeSettings = $root.google.api.NodeSettings.fromObject(object.nodeSettings); - } - if (object.dotnetSettings != null) { - if (typeof object.dotnetSettings !== "object") - throw TypeError(".google.api.ClientLibrarySettings.dotnetSettings: object expected"); - message.dotnetSettings = $root.google.api.DotnetSettings.fromObject(object.dotnetSettings); - } - if (object.rubySettings != null) { - if (typeof object.rubySettings !== "object") - throw TypeError(".google.api.ClientLibrarySettings.rubySettings: object expected"); - message.rubySettings = $root.google.api.RubySettings.fromObject(object.rubySettings); - } - if (object.goSettings != null) { - if (typeof object.goSettings !== "object") - throw TypeError(".google.api.ClientLibrarySettings.goSettings: object expected"); - message.goSettings = $root.google.api.GoSettings.fromObject(object.goSettings); - } + var message = new $root.google.protobuf.Timestamp(); + if (object.seconds != null) + if ($util.Long) + (message.seconds = $util.Long.fromValue(object.seconds)).unsigned = false; + else if (typeof object.seconds === "string") + message.seconds = parseInt(object.seconds, 10); + else if (typeof object.seconds === "number") + message.seconds = object.seconds; + else if (typeof object.seconds === "object") + message.seconds = new $util.LongBits(object.seconds.low >>> 0, object.seconds.high >>> 0).toNumber(); + if (object.nanos != null) + message.nanos = object.nanos | 0; return message; }; /** - * Creates a plain object from a ClientLibrarySettings message. Also converts values to other types if specified. + * Creates a plain object from a Timestamp message. Also converts values to other types if specified. * @function toObject - * @memberof google.api.ClientLibrarySettings + * @memberof google.protobuf.Timestamp * @static - * @param {google.api.ClientLibrarySettings} message ClientLibrarySettings + * @param {google.protobuf.Timestamp} message Timestamp * @param {$protobuf.IConversionOptions} [options] Conversion options * @returns {Object.} Plain object */ - ClientLibrarySettings.toObject = function toObject(message, options) { + Timestamp.toObject = function toObject(message, options) { if (!options) options = {}; var object = {}; if (options.defaults) { - object.version = ""; - object.launchStage = options.enums === String ? "LAUNCH_STAGE_UNSPECIFIED" : 0; - object.restNumericEnums = false; - object.javaSettings = null; - object.cppSettings = null; - object.phpSettings = null; - object.pythonSettings = null; - object.nodeSettings = null; - object.dotnetSettings = null; - object.rubySettings = null; - object.goSettings = null; + if ($util.Long) { + var long = new $util.Long(0, 0, false); + object.seconds = options.longs === String ? long.toString() : options.longs === Number ? long.toNumber() : long; + } else + object.seconds = options.longs === String ? "0" : 0; + object.nanos = 0; } - if (message.version != null && message.hasOwnProperty("version")) - object.version = message.version; - if (message.launchStage != null && message.hasOwnProperty("launchStage")) - object.launchStage = options.enums === String ? $root.google.api.LaunchStage[message.launchStage] === undefined ? message.launchStage : $root.google.api.LaunchStage[message.launchStage] : message.launchStage; - if (message.restNumericEnums != null && message.hasOwnProperty("restNumericEnums")) - object.restNumericEnums = message.restNumericEnums; - if (message.javaSettings != null && message.hasOwnProperty("javaSettings")) - object.javaSettings = $root.google.api.JavaSettings.toObject(message.javaSettings, options); - if (message.cppSettings != null && message.hasOwnProperty("cppSettings")) - object.cppSettings = $root.google.api.CppSettings.toObject(message.cppSettings, options); - if (message.phpSettings != null && message.hasOwnProperty("phpSettings")) - object.phpSettings = $root.google.api.PhpSettings.toObject(message.phpSettings, options); - if (message.pythonSettings != null && message.hasOwnProperty("pythonSettings")) - object.pythonSettings = $root.google.api.PythonSettings.toObject(message.pythonSettings, options); - if (message.nodeSettings != null && message.hasOwnProperty("nodeSettings")) - object.nodeSettings = $root.google.api.NodeSettings.toObject(message.nodeSettings, options); - if (message.dotnetSettings != null && message.hasOwnProperty("dotnetSettings")) - object.dotnetSettings = $root.google.api.DotnetSettings.toObject(message.dotnetSettings, options); - if (message.rubySettings != null && message.hasOwnProperty("rubySettings")) - object.rubySettings = $root.google.api.RubySettings.toObject(message.rubySettings, options); - if (message.goSettings != null && message.hasOwnProperty("goSettings")) - object.goSettings = $root.google.api.GoSettings.toObject(message.goSettings, options); + if (message.seconds != null && message.hasOwnProperty("seconds")) + if (typeof message.seconds === "number") + object.seconds = options.longs === String ? String(message.seconds) : message.seconds; + else + object.seconds = options.longs === String ? $util.Long.prototype.toString.call(message.seconds) : options.longs === Number ? new $util.LongBits(message.seconds.low >>> 0, message.seconds.high >>> 0).toNumber() : message.seconds; + if (message.nanos != null && message.hasOwnProperty("nanos")) + object.nanos = message.nanos; return object; }; /** - * Converts this ClientLibrarySettings to JSON. + * Converts this Timestamp to JSON. * @function toJSON - * @memberof google.api.ClientLibrarySettings + * @memberof google.protobuf.Timestamp * @instance * @returns {Object.} JSON object */ - ClientLibrarySettings.prototype.toJSON = function toJSON() { + Timestamp.prototype.toJSON = function toJSON() { return this.constructor.toObject(this, $protobuf.util.toJSONOptions); }; /** - * Gets the default type url for ClientLibrarySettings + * Gets the default type url for Timestamp * @function getTypeUrl - * @memberof google.api.ClientLibrarySettings + * @memberof google.protobuf.Timestamp * @static * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") * @returns {string} The default type url */ - ClientLibrarySettings.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + Timestamp.getTypeUrl = function getTypeUrl(typeUrlPrefix) { if (typeUrlPrefix === undefined) { typeUrlPrefix = "type.googleapis.com"; } - return typeUrlPrefix + "/google.api.ClientLibrarySettings"; + return typeUrlPrefix + "/google.protobuf.Timestamp"; }; - return ClientLibrarySettings; + return Timestamp; })(); - api.Publishing = (function() { + protobuf.Duration = (function() { /** - * Properties of a Publishing. - * @memberof google.api - * @interface IPublishing - * @property {Array.|null} [methodSettings] Publishing methodSettings - * @property {string|null} [newIssueUri] Publishing newIssueUri - * @property {string|null} [documentationUri] Publishing documentationUri - * @property {string|null} [apiShortName] Publishing apiShortName - * @property {string|null} [githubLabel] Publishing githubLabel - * @property {Array.|null} [codeownerGithubTeams] Publishing codeownerGithubTeams - * @property {string|null} [docTagPrefix] Publishing docTagPrefix - * @property {google.api.ClientLibraryOrganization|null} [organization] Publishing organization - * @property {Array.|null} [librarySettings] Publishing librarySettings - * @property {string|null} [protoReferenceDocumentationUri] Publishing protoReferenceDocumentationUri - * @property {string|null} [restReferenceDocumentationUri] Publishing restReferenceDocumentationUri + * Properties of a Duration. + * @memberof google.protobuf + * @interface IDuration + * @property {number|string|null} [seconds] Duration seconds + * @property {number|null} [nanos] Duration nanos */ /** - * Constructs a new Publishing. - * @memberof google.api - * @classdesc Represents a Publishing. - * @implements IPublishing + * Constructs a new Duration. + * @memberof google.protobuf + * @classdesc Represents a Duration. + * @implements IDuration * @constructor - * @param {google.api.IPublishing=} [properties] Properties to set + * @param {google.protobuf.IDuration=} [properties] Properties to set */ - function Publishing(properties) { - this.methodSettings = []; - this.codeownerGithubTeams = []; - this.librarySettings = []; + function Duration(properties) { if (properties) for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) if (properties[keys[i]] != null) @@ -23470,301 +23669,223 @@ } /** - * Publishing methodSettings. - * @member {Array.} methodSettings - * @memberof google.api.Publishing + * Duration seconds. + * @member {number|string} seconds + * @memberof google.protobuf.Duration * @instance */ - Publishing.prototype.methodSettings = $util.emptyArray; + Duration.prototype.seconds = $util.Long ? $util.Long.fromBits(0,0,false) : 0; /** - * Publishing newIssueUri. - * @member {string} newIssueUri - * @memberof google.api.Publishing + * Duration nanos. + * @member {number} nanos + * @memberof google.protobuf.Duration * @instance */ - Publishing.prototype.newIssueUri = ""; + Duration.prototype.nanos = 0; /** - * Publishing documentationUri. - * @member {string} documentationUri - * @memberof google.api.Publishing - * @instance + * Creates a Duration message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.protobuf.Duration + * @static + * @param {Object.} object Plain object + * @returns {google.protobuf.Duration} Duration */ - Publishing.prototype.documentationUri = ""; + Duration.fromObject = function fromObject(object) { + if (object instanceof $root.google.protobuf.Duration) + return object; + var message = new $root.google.protobuf.Duration(); + if (object.seconds != null) + if ($util.Long) + (message.seconds = $util.Long.fromValue(object.seconds)).unsigned = false; + else if (typeof object.seconds === "string") + message.seconds = parseInt(object.seconds, 10); + else if (typeof object.seconds === "number") + message.seconds = object.seconds; + else if (typeof object.seconds === "object") + message.seconds = new $util.LongBits(object.seconds.low >>> 0, object.seconds.high >>> 0).toNumber(); + if (object.nanos != null) + message.nanos = object.nanos | 0; + return message; + }; /** - * Publishing apiShortName. - * @member {string} apiShortName - * @memberof google.api.Publishing - * @instance + * Creates a plain object from a Duration message. Also converts values to other types if specified. + * @function toObject + * @memberof google.protobuf.Duration + * @static + * @param {google.protobuf.Duration} message Duration + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object */ - Publishing.prototype.apiShortName = ""; + Duration.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.defaults) { + if ($util.Long) { + var long = new $util.Long(0, 0, false); + object.seconds = options.longs === String ? long.toString() : options.longs === Number ? long.toNumber() : long; + } else + object.seconds = options.longs === String ? "0" : 0; + object.nanos = 0; + } + if (message.seconds != null && message.hasOwnProperty("seconds")) + if (typeof message.seconds === "number") + object.seconds = options.longs === String ? String(message.seconds) : message.seconds; + else + object.seconds = options.longs === String ? $util.Long.prototype.toString.call(message.seconds) : options.longs === Number ? new $util.LongBits(message.seconds.low >>> 0, message.seconds.high >>> 0).toNumber() : message.seconds; + if (message.nanos != null && message.hasOwnProperty("nanos")) + object.nanos = message.nanos; + return object; + }; /** - * Publishing githubLabel. - * @member {string} githubLabel - * @memberof google.api.Publishing + * Converts this Duration to JSON. + * @function toJSON + * @memberof google.protobuf.Duration * @instance + * @returns {Object.} JSON object */ - Publishing.prototype.githubLabel = ""; + Duration.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; /** - * Publishing codeownerGithubTeams. - * @member {Array.} codeownerGithubTeams - * @memberof google.api.Publishing - * @instance + * Gets the default type url for Duration + * @function getTypeUrl + * @memberof google.protobuf.Duration + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url */ - Publishing.prototype.codeownerGithubTeams = $util.emptyArray; + Duration.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.protobuf.Duration"; + }; - /** - * Publishing docTagPrefix. - * @member {string} docTagPrefix - * @memberof google.api.Publishing - * @instance - */ - Publishing.prototype.docTagPrefix = ""; + return Duration; + })(); - /** - * Publishing organization. - * @member {google.api.ClientLibraryOrganization} organization - * @memberof google.api.Publishing - * @instance - */ - Publishing.prototype.organization = 0; + protobuf.DoubleValue = (function() { /** - * Publishing librarySettings. - * @member {Array.} librarySettings - * @memberof google.api.Publishing - * @instance + * Properties of a DoubleValue. + * @memberof google.protobuf + * @interface IDoubleValue + * @property {number|null} [value] DoubleValue value */ - Publishing.prototype.librarySettings = $util.emptyArray; /** - * Publishing protoReferenceDocumentationUri. - * @member {string} protoReferenceDocumentationUri - * @memberof google.api.Publishing - * @instance + * Constructs a new DoubleValue. + * @memberof google.protobuf + * @classdesc Represents a DoubleValue. + * @implements IDoubleValue + * @constructor + * @param {google.protobuf.IDoubleValue=} [properties] Properties to set */ - Publishing.prototype.protoReferenceDocumentationUri = ""; + function DoubleValue(properties) { + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } /** - * Publishing restReferenceDocumentationUri. - * @member {string} restReferenceDocumentationUri - * @memberof google.api.Publishing + * DoubleValue value. + * @member {number} value + * @memberof google.protobuf.DoubleValue * @instance */ - Publishing.prototype.restReferenceDocumentationUri = ""; + DoubleValue.prototype.value = 0; - /** - * Creates a Publishing message from a plain object. Also converts values to their respective internal types. - * @function fromObject - * @memberof google.api.Publishing - * @static - * @param {Object.} object Plain object - * @returns {google.api.Publishing} Publishing - */ - Publishing.fromObject = function fromObject(object) { - if (object instanceof $root.google.api.Publishing) - return object; - var message = new $root.google.api.Publishing(); - if (object.methodSettings) { - if (!Array.isArray(object.methodSettings)) - throw TypeError(".google.api.Publishing.methodSettings: array expected"); - message.methodSettings = []; - for (var i = 0; i < object.methodSettings.length; ++i) { - if (typeof object.methodSettings[i] !== "object") - throw TypeError(".google.api.Publishing.methodSettings: object expected"); - message.methodSettings[i] = $root.google.api.MethodSettings.fromObject(object.methodSettings[i]); - } - } - if (object.newIssueUri != null) - message.newIssueUri = String(object.newIssueUri); - if (object.documentationUri != null) - message.documentationUri = String(object.documentationUri); - if (object.apiShortName != null) - message.apiShortName = String(object.apiShortName); - if (object.githubLabel != null) - message.githubLabel = String(object.githubLabel); - if (object.codeownerGithubTeams) { - if (!Array.isArray(object.codeownerGithubTeams)) - throw TypeError(".google.api.Publishing.codeownerGithubTeams: array expected"); - message.codeownerGithubTeams = []; - for (var i = 0; i < object.codeownerGithubTeams.length; ++i) - message.codeownerGithubTeams[i] = String(object.codeownerGithubTeams[i]); - } - if (object.docTagPrefix != null) - message.docTagPrefix = String(object.docTagPrefix); - switch (object.organization) { - default: - if (typeof object.organization === "number") { - message.organization = object.organization; - break; - } - break; - case "CLIENT_LIBRARY_ORGANIZATION_UNSPECIFIED": - case 0: - message.organization = 0; - break; - case "CLOUD": - case 1: - message.organization = 1; - break; - case "ADS": - case 2: - message.organization = 2; - break; - case "PHOTOS": - case 3: - message.organization = 3; - break; - case "STREET_VIEW": - case 4: - message.organization = 4; - break; - case "SHOPPING": - case 5: - message.organization = 5; - break; - case "GEO": - case 6: - message.organization = 6; - break; - case "GENERATIVE_AI": - case 7: - message.organization = 7; - break; - } - if (object.librarySettings) { - if (!Array.isArray(object.librarySettings)) - throw TypeError(".google.api.Publishing.librarySettings: array expected"); - message.librarySettings = []; - for (var i = 0; i < object.librarySettings.length; ++i) { - if (typeof object.librarySettings[i] !== "object") - throw TypeError(".google.api.Publishing.librarySettings: object expected"); - message.librarySettings[i] = $root.google.api.ClientLibrarySettings.fromObject(object.librarySettings[i]); - } - } - if (object.protoReferenceDocumentationUri != null) - message.protoReferenceDocumentationUri = String(object.protoReferenceDocumentationUri); - if (object.restReferenceDocumentationUri != null) - message.restReferenceDocumentationUri = String(object.restReferenceDocumentationUri); + /** + * Creates a DoubleValue message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.protobuf.DoubleValue + * @static + * @param {Object.} object Plain object + * @returns {google.protobuf.DoubleValue} DoubleValue + */ + DoubleValue.fromObject = function fromObject(object) { + if (object instanceof $root.google.protobuf.DoubleValue) + return object; + var message = new $root.google.protobuf.DoubleValue(); + if (object.value != null) + message.value = Number(object.value); return message; }; /** - * Creates a plain object from a Publishing message. Also converts values to other types if specified. + * Creates a plain object from a DoubleValue message. Also converts values to other types if specified. * @function toObject - * @memberof google.api.Publishing + * @memberof google.protobuf.DoubleValue * @static - * @param {google.api.Publishing} message Publishing + * @param {google.protobuf.DoubleValue} message DoubleValue * @param {$protobuf.IConversionOptions} [options] Conversion options * @returns {Object.} Plain object */ - Publishing.toObject = function toObject(message, options) { + DoubleValue.toObject = function toObject(message, options) { if (!options) options = {}; var object = {}; - if (options.arrays || options.defaults) { - object.methodSettings = []; - object.codeownerGithubTeams = []; - object.librarySettings = []; - } - if (options.defaults) { - object.newIssueUri = ""; - object.documentationUri = ""; - object.apiShortName = ""; - object.githubLabel = ""; - object.docTagPrefix = ""; - object.organization = options.enums === String ? "CLIENT_LIBRARY_ORGANIZATION_UNSPECIFIED" : 0; - object.protoReferenceDocumentationUri = ""; - object.restReferenceDocumentationUri = ""; - } - if (message.methodSettings && message.methodSettings.length) { - object.methodSettings = []; - for (var j = 0; j < message.methodSettings.length; ++j) - object.methodSettings[j] = $root.google.api.MethodSettings.toObject(message.methodSettings[j], options); - } - if (message.newIssueUri != null && message.hasOwnProperty("newIssueUri")) - object.newIssueUri = message.newIssueUri; - if (message.documentationUri != null && message.hasOwnProperty("documentationUri")) - object.documentationUri = message.documentationUri; - if (message.apiShortName != null && message.hasOwnProperty("apiShortName")) - object.apiShortName = message.apiShortName; - if (message.githubLabel != null && message.hasOwnProperty("githubLabel")) - object.githubLabel = message.githubLabel; - if (message.codeownerGithubTeams && message.codeownerGithubTeams.length) { - object.codeownerGithubTeams = []; - for (var j = 0; j < message.codeownerGithubTeams.length; ++j) - object.codeownerGithubTeams[j] = message.codeownerGithubTeams[j]; - } - if (message.docTagPrefix != null && message.hasOwnProperty("docTagPrefix")) - object.docTagPrefix = message.docTagPrefix; - if (message.organization != null && message.hasOwnProperty("organization")) - object.organization = options.enums === String ? $root.google.api.ClientLibraryOrganization[message.organization] === undefined ? message.organization : $root.google.api.ClientLibraryOrganization[message.organization] : message.organization; - if (message.librarySettings && message.librarySettings.length) { - object.librarySettings = []; - for (var j = 0; j < message.librarySettings.length; ++j) - object.librarySettings[j] = $root.google.api.ClientLibrarySettings.toObject(message.librarySettings[j], options); - } - if (message.protoReferenceDocumentationUri != null && message.hasOwnProperty("protoReferenceDocumentationUri")) - object.protoReferenceDocumentationUri = message.protoReferenceDocumentationUri; - if (message.restReferenceDocumentationUri != null && message.hasOwnProperty("restReferenceDocumentationUri")) - object.restReferenceDocumentationUri = message.restReferenceDocumentationUri; + if (options.defaults) + object.value = 0; + if (message.value != null && message.hasOwnProperty("value")) + object.value = options.json && !isFinite(message.value) ? String(message.value) : message.value; return object; }; /** - * Converts this Publishing to JSON. + * Converts this DoubleValue to JSON. * @function toJSON - * @memberof google.api.Publishing + * @memberof google.protobuf.DoubleValue * @instance * @returns {Object.} JSON object */ - Publishing.prototype.toJSON = function toJSON() { + DoubleValue.prototype.toJSON = function toJSON() { return this.constructor.toObject(this, $protobuf.util.toJSONOptions); }; /** - * Gets the default type url for Publishing + * Gets the default type url for DoubleValue * @function getTypeUrl - * @memberof google.api.Publishing + * @memberof google.protobuf.DoubleValue * @static * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") * @returns {string} The default type url */ - Publishing.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + DoubleValue.getTypeUrl = function getTypeUrl(typeUrlPrefix) { if (typeUrlPrefix === undefined) { typeUrlPrefix = "type.googleapis.com"; } - return typeUrlPrefix + "/google.api.Publishing"; + return typeUrlPrefix + "/google.protobuf.DoubleValue"; }; - return Publishing; + return DoubleValue; })(); - api.JavaSettings = (function() { + protobuf.FloatValue = (function() { /** - * Properties of a JavaSettings. - * @memberof google.api - * @interface IJavaSettings - * @property {string|null} [libraryPackage] JavaSettings libraryPackage - * @property {Object.|null} [serviceClassNames] JavaSettings serviceClassNames - * @property {google.api.ICommonLanguageSettings|null} [common] JavaSettings common + * Properties of a FloatValue. + * @memberof google.protobuf + * @interface IFloatValue + * @property {number|null} [value] FloatValue value */ /** - * Constructs a new JavaSettings. - * @memberof google.api - * @classdesc Represents a JavaSettings. - * @implements IJavaSettings + * Constructs a new FloatValue. + * @memberof google.protobuf + * @classdesc Represents a FloatValue. + * @implements IFloatValue * @constructor - * @param {google.api.IJavaSettings=} [properties] Properties to set + * @param {google.protobuf.IFloatValue=} [properties] Properties to set */ - function JavaSettings(properties) { - this.serviceClassNames = {}; + function FloatValue(properties) { if (properties) for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) if (properties[keys[i]] != null) @@ -23772,137 +23893,97 @@ } /** - * JavaSettings libraryPackage. - * @member {string} libraryPackage - * @memberof google.api.JavaSettings - * @instance - */ - JavaSettings.prototype.libraryPackage = ""; - - /** - * JavaSettings serviceClassNames. - * @member {Object.} serviceClassNames - * @memberof google.api.JavaSettings - * @instance - */ - JavaSettings.prototype.serviceClassNames = $util.emptyObject; - - /** - * JavaSettings common. - * @member {google.api.ICommonLanguageSettings|null|undefined} common - * @memberof google.api.JavaSettings + * FloatValue value. + * @member {number} value + * @memberof google.protobuf.FloatValue * @instance */ - JavaSettings.prototype.common = null; + FloatValue.prototype.value = 0; /** - * Creates a JavaSettings message from a plain object. Also converts values to their respective internal types. + * Creates a FloatValue message from a plain object. Also converts values to their respective internal types. * @function fromObject - * @memberof google.api.JavaSettings + * @memberof google.protobuf.FloatValue * @static * @param {Object.} object Plain object - * @returns {google.api.JavaSettings} JavaSettings + * @returns {google.protobuf.FloatValue} FloatValue */ - JavaSettings.fromObject = function fromObject(object) { - if (object instanceof $root.google.api.JavaSettings) + FloatValue.fromObject = function fromObject(object) { + if (object instanceof $root.google.protobuf.FloatValue) return object; - var message = new $root.google.api.JavaSettings(); - if (object.libraryPackage != null) - message.libraryPackage = String(object.libraryPackage); - if (object.serviceClassNames) { - if (typeof object.serviceClassNames !== "object") - throw TypeError(".google.api.JavaSettings.serviceClassNames: object expected"); - message.serviceClassNames = {}; - for (var keys = Object.keys(object.serviceClassNames), i = 0; i < keys.length; ++i) - message.serviceClassNames[keys[i]] = String(object.serviceClassNames[keys[i]]); - } - if (object.common != null) { - if (typeof object.common !== "object") - throw TypeError(".google.api.JavaSettings.common: object expected"); - message.common = $root.google.api.CommonLanguageSettings.fromObject(object.common); - } + var message = new $root.google.protobuf.FloatValue(); + if (object.value != null) + message.value = Number(object.value); return message; }; /** - * Creates a plain object from a JavaSettings message. Also converts values to other types if specified. + * Creates a plain object from a FloatValue message. Also converts values to other types if specified. * @function toObject - * @memberof google.api.JavaSettings + * @memberof google.protobuf.FloatValue * @static - * @param {google.api.JavaSettings} message JavaSettings + * @param {google.protobuf.FloatValue} message FloatValue * @param {$protobuf.IConversionOptions} [options] Conversion options * @returns {Object.} Plain object */ - JavaSettings.toObject = function toObject(message, options) { + FloatValue.toObject = function toObject(message, options) { if (!options) options = {}; var object = {}; - if (options.objects || options.defaults) - object.serviceClassNames = {}; - if (options.defaults) { - object.libraryPackage = ""; - object.common = null; - } - if (message.libraryPackage != null && message.hasOwnProperty("libraryPackage")) - object.libraryPackage = message.libraryPackage; - var keys2; - if (message.serviceClassNames && (keys2 = Object.keys(message.serviceClassNames)).length) { - object.serviceClassNames = {}; - for (var j = 0; j < keys2.length; ++j) - object.serviceClassNames[keys2[j]] = message.serviceClassNames[keys2[j]]; - } - if (message.common != null && message.hasOwnProperty("common")) - object.common = $root.google.api.CommonLanguageSettings.toObject(message.common, options); + if (options.defaults) + object.value = 0; + if (message.value != null && message.hasOwnProperty("value")) + object.value = options.json && !isFinite(message.value) ? String(message.value) : message.value; return object; }; /** - * Converts this JavaSettings to JSON. + * Converts this FloatValue to JSON. * @function toJSON - * @memberof google.api.JavaSettings + * @memberof google.protobuf.FloatValue * @instance * @returns {Object.} JSON object */ - JavaSettings.prototype.toJSON = function toJSON() { + FloatValue.prototype.toJSON = function toJSON() { return this.constructor.toObject(this, $protobuf.util.toJSONOptions); }; /** - * Gets the default type url for JavaSettings + * Gets the default type url for FloatValue * @function getTypeUrl - * @memberof google.api.JavaSettings + * @memberof google.protobuf.FloatValue * @static * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") * @returns {string} The default type url */ - JavaSettings.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + FloatValue.getTypeUrl = function getTypeUrl(typeUrlPrefix) { if (typeUrlPrefix === undefined) { typeUrlPrefix = "type.googleapis.com"; } - return typeUrlPrefix + "/google.api.JavaSettings"; + return typeUrlPrefix + "/google.protobuf.FloatValue"; }; - return JavaSettings; + return FloatValue; })(); - api.CppSettings = (function() { + protobuf.Int64Value = (function() { /** - * Properties of a CppSettings. - * @memberof google.api - * @interface ICppSettings - * @property {google.api.ICommonLanguageSettings|null} [common] CppSettings common + * Properties of an Int64Value. + * @memberof google.protobuf + * @interface IInt64Value + * @property {number|string|null} [value] Int64Value value */ /** - * Constructs a new CppSettings. - * @memberof google.api - * @classdesc Represents a CppSettings. - * @implements ICppSettings + * Constructs a new Int64Value. + * @memberof google.protobuf + * @classdesc Represents an Int64Value. + * @implements IInt64Value * @constructor - * @param {google.api.ICppSettings=} [properties] Properties to set + * @param {google.protobuf.IInt64Value=} [properties] Properties to set */ - function CppSettings(properties) { + function Int64Value(properties) { if (properties) for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) if (properties[keys[i]] != null) @@ -23910,100 +23991,111 @@ } /** - * CppSettings common. - * @member {google.api.ICommonLanguageSettings|null|undefined} common - * @memberof google.api.CppSettings + * Int64Value value. + * @member {number|string} value + * @memberof google.protobuf.Int64Value * @instance */ - CppSettings.prototype.common = null; + Int64Value.prototype.value = $util.Long ? $util.Long.fromBits(0,0,false) : 0; /** - * Creates a CppSettings message from a plain object. Also converts values to their respective internal types. + * Creates an Int64Value message from a plain object. Also converts values to their respective internal types. * @function fromObject - * @memberof google.api.CppSettings + * @memberof google.protobuf.Int64Value * @static * @param {Object.} object Plain object - * @returns {google.api.CppSettings} CppSettings + * @returns {google.protobuf.Int64Value} Int64Value */ - CppSettings.fromObject = function fromObject(object) { - if (object instanceof $root.google.api.CppSettings) + Int64Value.fromObject = function fromObject(object) { + if (object instanceof $root.google.protobuf.Int64Value) return object; - var message = new $root.google.api.CppSettings(); - if (object.common != null) { - if (typeof object.common !== "object") - throw TypeError(".google.api.CppSettings.common: object expected"); - message.common = $root.google.api.CommonLanguageSettings.fromObject(object.common); - } + var message = new $root.google.protobuf.Int64Value(); + if (object.value != null) + if ($util.Long) + (message.value = $util.Long.fromValue(object.value)).unsigned = false; + else if (typeof object.value === "string") + message.value = parseInt(object.value, 10); + else if (typeof object.value === "number") + message.value = object.value; + else if (typeof object.value === "object") + message.value = new $util.LongBits(object.value.low >>> 0, object.value.high >>> 0).toNumber(); return message; }; /** - * Creates a plain object from a CppSettings message. Also converts values to other types if specified. + * Creates a plain object from an Int64Value message. Also converts values to other types if specified. * @function toObject - * @memberof google.api.CppSettings + * @memberof google.protobuf.Int64Value * @static - * @param {google.api.CppSettings} message CppSettings + * @param {google.protobuf.Int64Value} message Int64Value * @param {$protobuf.IConversionOptions} [options] Conversion options * @returns {Object.} Plain object */ - CppSettings.toObject = function toObject(message, options) { + Int64Value.toObject = function toObject(message, options) { if (!options) options = {}; var object = {}; if (options.defaults) - object.common = null; - if (message.common != null && message.hasOwnProperty("common")) - object.common = $root.google.api.CommonLanguageSettings.toObject(message.common, options); + if ($util.Long) { + var long = new $util.Long(0, 0, false); + object.value = options.longs === String ? long.toString() : options.longs === Number ? long.toNumber() : long; + } else + object.value = options.longs === String ? "0" : 0; + if (message.value != null && message.hasOwnProperty("value")) + if (typeof message.value === "number") + object.value = options.longs === String ? String(message.value) : message.value; + else + object.value = options.longs === String ? $util.Long.prototype.toString.call(message.value) : options.longs === Number ? new $util.LongBits(message.value.low >>> 0, message.value.high >>> 0).toNumber() : message.value; return object; }; /** - * Converts this CppSettings to JSON. + * Converts this Int64Value to JSON. * @function toJSON - * @memberof google.api.CppSettings + * @memberof google.protobuf.Int64Value * @instance * @returns {Object.} JSON object */ - CppSettings.prototype.toJSON = function toJSON() { + Int64Value.prototype.toJSON = function toJSON() { return this.constructor.toObject(this, $protobuf.util.toJSONOptions); }; /** - * Gets the default type url for CppSettings + * Gets the default type url for Int64Value * @function getTypeUrl - * @memberof google.api.CppSettings + * @memberof google.protobuf.Int64Value * @static * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") * @returns {string} The default type url */ - CppSettings.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + Int64Value.getTypeUrl = function getTypeUrl(typeUrlPrefix) { if (typeUrlPrefix === undefined) { typeUrlPrefix = "type.googleapis.com"; } - return typeUrlPrefix + "/google.api.CppSettings"; + return typeUrlPrefix + "/google.protobuf.Int64Value"; }; - return CppSettings; + return Int64Value; })(); - api.PhpSettings = (function() { + protobuf.UInt64Value = (function() { /** - * Properties of a PhpSettings. - * @memberof google.api - * @interface IPhpSettings - * @property {google.api.ICommonLanguageSettings|null} [common] PhpSettings common + * Properties of a UInt64Value. + * @memberof google.protobuf + * @interface IUInt64Value + * @property {number|string|null} [value] UInt64Value value */ /** - * Constructs a new PhpSettings. - * @memberof google.api - * @classdesc Represents a PhpSettings. - * @implements IPhpSettings + * Constructs a new UInt64Value. + * @memberof google.protobuf + * @classdesc Represents a UInt64Value. + * @implements IUInt64Value * @constructor - * @param {google.api.IPhpSettings=} [properties] Properties to set + * @param {google.protobuf.IUInt64Value=} [properties] Properties to set */ - function PhpSettings(properties) { + function UInt64Value(properties) { if (properties) for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) if (properties[keys[i]] != null) @@ -24011,100 +24103,111 @@ } /** - * PhpSettings common. - * @member {google.api.ICommonLanguageSettings|null|undefined} common - * @memberof google.api.PhpSettings + * UInt64Value value. + * @member {number|string} value + * @memberof google.protobuf.UInt64Value * @instance */ - PhpSettings.prototype.common = null; + UInt64Value.prototype.value = $util.Long ? $util.Long.fromBits(0,0,true) : 0; /** - * Creates a PhpSettings message from a plain object. Also converts values to their respective internal types. + * Creates a UInt64Value message from a plain object. Also converts values to their respective internal types. * @function fromObject - * @memberof google.api.PhpSettings + * @memberof google.protobuf.UInt64Value * @static * @param {Object.} object Plain object - * @returns {google.api.PhpSettings} PhpSettings + * @returns {google.protobuf.UInt64Value} UInt64Value */ - PhpSettings.fromObject = function fromObject(object) { - if (object instanceof $root.google.api.PhpSettings) + UInt64Value.fromObject = function fromObject(object) { + if (object instanceof $root.google.protobuf.UInt64Value) return object; - var message = new $root.google.api.PhpSettings(); - if (object.common != null) { - if (typeof object.common !== "object") - throw TypeError(".google.api.PhpSettings.common: object expected"); - message.common = $root.google.api.CommonLanguageSettings.fromObject(object.common); - } + var message = new $root.google.protobuf.UInt64Value(); + if (object.value != null) + if ($util.Long) + (message.value = $util.Long.fromValue(object.value)).unsigned = true; + else if (typeof object.value === "string") + message.value = parseInt(object.value, 10); + else if (typeof object.value === "number") + message.value = object.value; + else if (typeof object.value === "object") + message.value = new $util.LongBits(object.value.low >>> 0, object.value.high >>> 0).toNumber(true); return message; }; /** - * Creates a plain object from a PhpSettings message. Also converts values to other types if specified. + * Creates a plain object from a UInt64Value message. Also converts values to other types if specified. * @function toObject - * @memberof google.api.PhpSettings + * @memberof google.protobuf.UInt64Value * @static - * @param {google.api.PhpSettings} message PhpSettings + * @param {google.protobuf.UInt64Value} message UInt64Value * @param {$protobuf.IConversionOptions} [options] Conversion options * @returns {Object.} Plain object */ - PhpSettings.toObject = function toObject(message, options) { + UInt64Value.toObject = function toObject(message, options) { if (!options) options = {}; var object = {}; if (options.defaults) - object.common = null; - if (message.common != null && message.hasOwnProperty("common")) - object.common = $root.google.api.CommonLanguageSettings.toObject(message.common, options); + if ($util.Long) { + var long = new $util.Long(0, 0, true); + object.value = options.longs === String ? long.toString() : options.longs === Number ? long.toNumber() : long; + } else + object.value = options.longs === String ? "0" : 0; + if (message.value != null && message.hasOwnProperty("value")) + if (typeof message.value === "number") + object.value = options.longs === String ? String(message.value) : message.value; + else + object.value = options.longs === String ? $util.Long.prototype.toString.call(message.value) : options.longs === Number ? new $util.LongBits(message.value.low >>> 0, message.value.high >>> 0).toNumber(true) : message.value; return object; }; /** - * Converts this PhpSettings to JSON. + * Converts this UInt64Value to JSON. * @function toJSON - * @memberof google.api.PhpSettings + * @memberof google.protobuf.UInt64Value * @instance * @returns {Object.} JSON object */ - PhpSettings.prototype.toJSON = function toJSON() { + UInt64Value.prototype.toJSON = function toJSON() { return this.constructor.toObject(this, $protobuf.util.toJSONOptions); }; /** - * Gets the default type url for PhpSettings + * Gets the default type url for UInt64Value * @function getTypeUrl - * @memberof google.api.PhpSettings + * @memberof google.protobuf.UInt64Value * @static * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") * @returns {string} The default type url */ - PhpSettings.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + UInt64Value.getTypeUrl = function getTypeUrl(typeUrlPrefix) { if (typeUrlPrefix === undefined) { typeUrlPrefix = "type.googleapis.com"; } - return typeUrlPrefix + "/google.api.PhpSettings"; + return typeUrlPrefix + "/google.protobuf.UInt64Value"; }; - return PhpSettings; + return UInt64Value; })(); - api.PythonSettings = (function() { + protobuf.Int32Value = (function() { /** - * Properties of a PythonSettings. - * @memberof google.api - * @interface IPythonSettings - * @property {google.api.ICommonLanguageSettings|null} [common] PythonSettings common + * Properties of an Int32Value. + * @memberof google.protobuf + * @interface IInt32Value + * @property {number|null} [value] Int32Value value */ /** - * Constructs a new PythonSettings. - * @memberof google.api - * @classdesc Represents a PythonSettings. - * @implements IPythonSettings + * Constructs a new Int32Value. + * @memberof google.protobuf + * @classdesc Represents an Int32Value. + * @implements IInt32Value * @constructor - * @param {google.api.IPythonSettings=} [properties] Properties to set + * @param {google.protobuf.IInt32Value=} [properties] Properties to set */ - function PythonSettings(properties) { + function Int32Value(properties) { if (properties) for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) if (properties[keys[i]] != null) @@ -24112,100 +24215,97 @@ } /** - * PythonSettings common. - * @member {google.api.ICommonLanguageSettings|null|undefined} common - * @memberof google.api.PythonSettings + * Int32Value value. + * @member {number} value + * @memberof google.protobuf.Int32Value * @instance */ - PythonSettings.prototype.common = null; + Int32Value.prototype.value = 0; /** - * Creates a PythonSettings message from a plain object. Also converts values to their respective internal types. + * Creates an Int32Value message from a plain object. Also converts values to their respective internal types. * @function fromObject - * @memberof google.api.PythonSettings + * @memberof google.protobuf.Int32Value * @static * @param {Object.} object Plain object - * @returns {google.api.PythonSettings} PythonSettings + * @returns {google.protobuf.Int32Value} Int32Value */ - PythonSettings.fromObject = function fromObject(object) { - if (object instanceof $root.google.api.PythonSettings) + Int32Value.fromObject = function fromObject(object) { + if (object instanceof $root.google.protobuf.Int32Value) return object; - var message = new $root.google.api.PythonSettings(); - if (object.common != null) { - if (typeof object.common !== "object") - throw TypeError(".google.api.PythonSettings.common: object expected"); - message.common = $root.google.api.CommonLanguageSettings.fromObject(object.common); - } + var message = new $root.google.protobuf.Int32Value(); + if (object.value != null) + message.value = object.value | 0; return message; }; /** - * Creates a plain object from a PythonSettings message. Also converts values to other types if specified. + * Creates a plain object from an Int32Value message. Also converts values to other types if specified. * @function toObject - * @memberof google.api.PythonSettings + * @memberof google.protobuf.Int32Value * @static - * @param {google.api.PythonSettings} message PythonSettings + * @param {google.protobuf.Int32Value} message Int32Value * @param {$protobuf.IConversionOptions} [options] Conversion options * @returns {Object.} Plain object */ - PythonSettings.toObject = function toObject(message, options) { + Int32Value.toObject = function toObject(message, options) { if (!options) options = {}; var object = {}; if (options.defaults) - object.common = null; - if (message.common != null && message.hasOwnProperty("common")) - object.common = $root.google.api.CommonLanguageSettings.toObject(message.common, options); + object.value = 0; + if (message.value != null && message.hasOwnProperty("value")) + object.value = message.value; return object; }; /** - * Converts this PythonSettings to JSON. + * Converts this Int32Value to JSON. * @function toJSON - * @memberof google.api.PythonSettings + * @memberof google.protobuf.Int32Value * @instance * @returns {Object.} JSON object */ - PythonSettings.prototype.toJSON = function toJSON() { + Int32Value.prototype.toJSON = function toJSON() { return this.constructor.toObject(this, $protobuf.util.toJSONOptions); }; /** - * Gets the default type url for PythonSettings + * Gets the default type url for Int32Value * @function getTypeUrl - * @memberof google.api.PythonSettings + * @memberof google.protobuf.Int32Value * @static * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") * @returns {string} The default type url */ - PythonSettings.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + Int32Value.getTypeUrl = function getTypeUrl(typeUrlPrefix) { if (typeUrlPrefix === undefined) { typeUrlPrefix = "type.googleapis.com"; } - return typeUrlPrefix + "/google.api.PythonSettings"; + return typeUrlPrefix + "/google.protobuf.Int32Value"; }; - return PythonSettings; + return Int32Value; })(); - api.NodeSettings = (function() { + protobuf.UInt32Value = (function() { /** - * Properties of a NodeSettings. - * @memberof google.api - * @interface INodeSettings - * @property {google.api.ICommonLanguageSettings|null} [common] NodeSettings common + * Properties of a UInt32Value. + * @memberof google.protobuf + * @interface IUInt32Value + * @property {number|null} [value] UInt32Value value */ /** - * Constructs a new NodeSettings. - * @memberof google.api - * @classdesc Represents a NodeSettings. - * @implements INodeSettings + * Constructs a new UInt32Value. + * @memberof google.protobuf + * @classdesc Represents a UInt32Value. + * @implements IUInt32Value * @constructor - * @param {google.api.INodeSettings=} [properties] Properties to set + * @param {google.protobuf.IUInt32Value=} [properties] Properties to set */ - function NodeSettings(properties) { + function UInt32Value(properties) { if (properties) for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) if (properties[keys[i]] != null) @@ -24213,110 +24313,97 @@ } /** - * NodeSettings common. - * @member {google.api.ICommonLanguageSettings|null|undefined} common - * @memberof google.api.NodeSettings + * UInt32Value value. + * @member {number} value + * @memberof google.protobuf.UInt32Value * @instance */ - NodeSettings.prototype.common = null; + UInt32Value.prototype.value = 0; /** - * Creates a NodeSettings message from a plain object. Also converts values to their respective internal types. + * Creates a UInt32Value message from a plain object. Also converts values to their respective internal types. * @function fromObject - * @memberof google.api.NodeSettings + * @memberof google.protobuf.UInt32Value * @static * @param {Object.} object Plain object - * @returns {google.api.NodeSettings} NodeSettings + * @returns {google.protobuf.UInt32Value} UInt32Value */ - NodeSettings.fromObject = function fromObject(object) { - if (object instanceof $root.google.api.NodeSettings) + UInt32Value.fromObject = function fromObject(object) { + if (object instanceof $root.google.protobuf.UInt32Value) return object; - var message = new $root.google.api.NodeSettings(); - if (object.common != null) { - if (typeof object.common !== "object") - throw TypeError(".google.api.NodeSettings.common: object expected"); - message.common = $root.google.api.CommonLanguageSettings.fromObject(object.common); - } + var message = new $root.google.protobuf.UInt32Value(); + if (object.value != null) + message.value = object.value >>> 0; return message; }; /** - * Creates a plain object from a NodeSettings message. Also converts values to other types if specified. + * Creates a plain object from a UInt32Value message. Also converts values to other types if specified. * @function toObject - * @memberof google.api.NodeSettings + * @memberof google.protobuf.UInt32Value * @static - * @param {google.api.NodeSettings} message NodeSettings + * @param {google.protobuf.UInt32Value} message UInt32Value * @param {$protobuf.IConversionOptions} [options] Conversion options * @returns {Object.} Plain object */ - NodeSettings.toObject = function toObject(message, options) { + UInt32Value.toObject = function toObject(message, options) { if (!options) options = {}; var object = {}; if (options.defaults) - object.common = null; - if (message.common != null && message.hasOwnProperty("common")) - object.common = $root.google.api.CommonLanguageSettings.toObject(message.common, options); + object.value = 0; + if (message.value != null && message.hasOwnProperty("value")) + object.value = message.value; return object; }; /** - * Converts this NodeSettings to JSON. + * Converts this UInt32Value to JSON. * @function toJSON - * @memberof google.api.NodeSettings + * @memberof google.protobuf.UInt32Value * @instance * @returns {Object.} JSON object */ - NodeSettings.prototype.toJSON = function toJSON() { + UInt32Value.prototype.toJSON = function toJSON() { return this.constructor.toObject(this, $protobuf.util.toJSONOptions); }; /** - * Gets the default type url for NodeSettings + * Gets the default type url for UInt32Value * @function getTypeUrl - * @memberof google.api.NodeSettings + * @memberof google.protobuf.UInt32Value * @static * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") * @returns {string} The default type url */ - NodeSettings.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + UInt32Value.getTypeUrl = function getTypeUrl(typeUrlPrefix) { if (typeUrlPrefix === undefined) { typeUrlPrefix = "type.googleapis.com"; } - return typeUrlPrefix + "/google.api.NodeSettings"; + return typeUrlPrefix + "/google.protobuf.UInt32Value"; }; - return NodeSettings; + return UInt32Value; })(); - api.DotnetSettings = (function() { + protobuf.BoolValue = (function() { /** - * Properties of a DotnetSettings. - * @memberof google.api - * @interface IDotnetSettings - * @property {google.api.ICommonLanguageSettings|null} [common] DotnetSettings common - * @property {Object.|null} [renamedServices] DotnetSettings renamedServices - * @property {Object.|null} [renamedResources] DotnetSettings renamedResources - * @property {Array.|null} [ignoredResources] DotnetSettings ignoredResources - * @property {Array.|null} [forcedNamespaceAliases] DotnetSettings forcedNamespaceAliases - * @property {Array.|null} [handwrittenSignatures] DotnetSettings handwrittenSignatures + * Properties of a BoolValue. + * @memberof google.protobuf + * @interface IBoolValue + * @property {boolean|null} [value] BoolValue value */ /** - * Constructs a new DotnetSettings. - * @memberof google.api - * @classdesc Represents a DotnetSettings. - * @implements IDotnetSettings + * Constructs a new BoolValue. + * @memberof google.protobuf + * @classdesc Represents a BoolValue. + * @implements IBoolValue * @constructor - * @param {google.api.IDotnetSettings=} [properties] Properties to set + * @param {google.protobuf.IBoolValue=} [properties] Properties to set */ - function DotnetSettings(properties) { - this.renamedServices = {}; - this.renamedResources = {}; - this.ignoredResources = []; - this.forcedNamespaceAliases = []; - this.handwrittenSignatures = []; + function BoolValue(properties) { if (properties) for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) if (properties[keys[i]] != null) @@ -24324,210 +24411,97 @@ } /** - * DotnetSettings common. - * @member {google.api.ICommonLanguageSettings|null|undefined} common - * @memberof google.api.DotnetSettings - * @instance - */ - DotnetSettings.prototype.common = null; - - /** - * DotnetSettings renamedServices. - * @member {Object.} renamedServices - * @memberof google.api.DotnetSettings - * @instance - */ - DotnetSettings.prototype.renamedServices = $util.emptyObject; - - /** - * DotnetSettings renamedResources. - * @member {Object.} renamedResources - * @memberof google.api.DotnetSettings - * @instance - */ - DotnetSettings.prototype.renamedResources = $util.emptyObject; - - /** - * DotnetSettings ignoredResources. - * @member {Array.} ignoredResources - * @memberof google.api.DotnetSettings - * @instance - */ - DotnetSettings.prototype.ignoredResources = $util.emptyArray; - - /** - * DotnetSettings forcedNamespaceAliases. - * @member {Array.} forcedNamespaceAliases - * @memberof google.api.DotnetSettings - * @instance - */ - DotnetSettings.prototype.forcedNamespaceAliases = $util.emptyArray; - - /** - * DotnetSettings handwrittenSignatures. - * @member {Array.} handwrittenSignatures - * @memberof google.api.DotnetSettings + * BoolValue value. + * @member {boolean} value + * @memberof google.protobuf.BoolValue * @instance */ - DotnetSettings.prototype.handwrittenSignatures = $util.emptyArray; + BoolValue.prototype.value = false; /** - * Creates a DotnetSettings message from a plain object. Also converts values to their respective internal types. + * Creates a BoolValue message from a plain object. Also converts values to their respective internal types. * @function fromObject - * @memberof google.api.DotnetSettings + * @memberof google.protobuf.BoolValue * @static * @param {Object.} object Plain object - * @returns {google.api.DotnetSettings} DotnetSettings + * @returns {google.protobuf.BoolValue} BoolValue */ - DotnetSettings.fromObject = function fromObject(object) { - if (object instanceof $root.google.api.DotnetSettings) + BoolValue.fromObject = function fromObject(object) { + if (object instanceof $root.google.protobuf.BoolValue) return object; - var message = new $root.google.api.DotnetSettings(); - if (object.common != null) { - if (typeof object.common !== "object") - throw TypeError(".google.api.DotnetSettings.common: object expected"); - message.common = $root.google.api.CommonLanguageSettings.fromObject(object.common); - } - if (object.renamedServices) { - if (typeof object.renamedServices !== "object") - throw TypeError(".google.api.DotnetSettings.renamedServices: object expected"); - message.renamedServices = {}; - for (var keys = Object.keys(object.renamedServices), i = 0; i < keys.length; ++i) - message.renamedServices[keys[i]] = String(object.renamedServices[keys[i]]); - } - if (object.renamedResources) { - if (typeof object.renamedResources !== "object") - throw TypeError(".google.api.DotnetSettings.renamedResources: object expected"); - message.renamedResources = {}; - for (var keys = Object.keys(object.renamedResources), i = 0; i < keys.length; ++i) - message.renamedResources[keys[i]] = String(object.renamedResources[keys[i]]); - } - if (object.ignoredResources) { - if (!Array.isArray(object.ignoredResources)) - throw TypeError(".google.api.DotnetSettings.ignoredResources: array expected"); - message.ignoredResources = []; - for (var i = 0; i < object.ignoredResources.length; ++i) - message.ignoredResources[i] = String(object.ignoredResources[i]); - } - if (object.forcedNamespaceAliases) { - if (!Array.isArray(object.forcedNamespaceAliases)) - throw TypeError(".google.api.DotnetSettings.forcedNamespaceAliases: array expected"); - message.forcedNamespaceAliases = []; - for (var i = 0; i < object.forcedNamespaceAliases.length; ++i) - message.forcedNamespaceAliases[i] = String(object.forcedNamespaceAliases[i]); - } - if (object.handwrittenSignatures) { - if (!Array.isArray(object.handwrittenSignatures)) - throw TypeError(".google.api.DotnetSettings.handwrittenSignatures: array expected"); - message.handwrittenSignatures = []; - for (var i = 0; i < object.handwrittenSignatures.length; ++i) - message.handwrittenSignatures[i] = String(object.handwrittenSignatures[i]); - } + var message = new $root.google.protobuf.BoolValue(); + if (object.value != null) + message.value = Boolean(object.value); return message; }; /** - * Creates a plain object from a DotnetSettings message. Also converts values to other types if specified. + * Creates a plain object from a BoolValue message. Also converts values to other types if specified. * @function toObject - * @memberof google.api.DotnetSettings + * @memberof google.protobuf.BoolValue * @static - * @param {google.api.DotnetSettings} message DotnetSettings + * @param {google.protobuf.BoolValue} message BoolValue * @param {$protobuf.IConversionOptions} [options] Conversion options * @returns {Object.} Plain object */ - DotnetSettings.toObject = function toObject(message, options) { + BoolValue.toObject = function toObject(message, options) { if (!options) options = {}; var object = {}; - if (options.arrays || options.defaults) { - object.ignoredResources = []; - object.forcedNamespaceAliases = []; - object.handwrittenSignatures = []; - } - if (options.objects || options.defaults) { - object.renamedServices = {}; - object.renamedResources = {}; - } if (options.defaults) - object.common = null; - if (message.common != null && message.hasOwnProperty("common")) - object.common = $root.google.api.CommonLanguageSettings.toObject(message.common, options); - var keys2; - if (message.renamedServices && (keys2 = Object.keys(message.renamedServices)).length) { - object.renamedServices = {}; - for (var j = 0; j < keys2.length; ++j) - object.renamedServices[keys2[j]] = message.renamedServices[keys2[j]]; - } - if (message.renamedResources && (keys2 = Object.keys(message.renamedResources)).length) { - object.renamedResources = {}; - for (var j = 0; j < keys2.length; ++j) - object.renamedResources[keys2[j]] = message.renamedResources[keys2[j]]; - } - if (message.ignoredResources && message.ignoredResources.length) { - object.ignoredResources = []; - for (var j = 0; j < message.ignoredResources.length; ++j) - object.ignoredResources[j] = message.ignoredResources[j]; - } - if (message.forcedNamespaceAliases && message.forcedNamespaceAliases.length) { - object.forcedNamespaceAliases = []; - for (var j = 0; j < message.forcedNamespaceAliases.length; ++j) - object.forcedNamespaceAliases[j] = message.forcedNamespaceAliases[j]; - } - if (message.handwrittenSignatures && message.handwrittenSignatures.length) { - object.handwrittenSignatures = []; - for (var j = 0; j < message.handwrittenSignatures.length; ++j) - object.handwrittenSignatures[j] = message.handwrittenSignatures[j]; - } + object.value = false; + if (message.value != null && message.hasOwnProperty("value")) + object.value = message.value; return object; }; /** - * Converts this DotnetSettings to JSON. + * Converts this BoolValue to JSON. * @function toJSON - * @memberof google.api.DotnetSettings + * @memberof google.protobuf.BoolValue * @instance * @returns {Object.} JSON object */ - DotnetSettings.prototype.toJSON = function toJSON() { + BoolValue.prototype.toJSON = function toJSON() { return this.constructor.toObject(this, $protobuf.util.toJSONOptions); }; /** - * Gets the default type url for DotnetSettings + * Gets the default type url for BoolValue * @function getTypeUrl - * @memberof google.api.DotnetSettings + * @memberof google.protobuf.BoolValue * @static * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") * @returns {string} The default type url */ - DotnetSettings.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + BoolValue.getTypeUrl = function getTypeUrl(typeUrlPrefix) { if (typeUrlPrefix === undefined) { typeUrlPrefix = "type.googleapis.com"; } - return typeUrlPrefix + "/google.api.DotnetSettings"; + return typeUrlPrefix + "/google.protobuf.BoolValue"; }; - return DotnetSettings; + return BoolValue; })(); - api.RubySettings = (function() { + protobuf.StringValue = (function() { /** - * Properties of a RubySettings. - * @memberof google.api - * @interface IRubySettings - * @property {google.api.ICommonLanguageSettings|null} [common] RubySettings common + * Properties of a StringValue. + * @memberof google.protobuf + * @interface IStringValue + * @property {string|null} [value] StringValue value */ /** - * Constructs a new RubySettings. - * @memberof google.api - * @classdesc Represents a RubySettings. - * @implements IRubySettings + * Constructs a new StringValue. + * @memberof google.protobuf + * @classdesc Represents a StringValue. + * @implements IStringValue * @constructor - * @param {google.api.IRubySettings=} [properties] Properties to set + * @param {google.protobuf.IStringValue=} [properties] Properties to set */ - function RubySettings(properties) { + function StringValue(properties) { if (properties) for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) if (properties[keys[i]] != null) @@ -24535,100 +24509,97 @@ } /** - * RubySettings common. - * @member {google.api.ICommonLanguageSettings|null|undefined} common - * @memberof google.api.RubySettings + * StringValue value. + * @member {string} value + * @memberof google.protobuf.StringValue * @instance */ - RubySettings.prototype.common = null; + StringValue.prototype.value = ""; /** - * Creates a RubySettings message from a plain object. Also converts values to their respective internal types. + * Creates a StringValue message from a plain object. Also converts values to their respective internal types. * @function fromObject - * @memberof google.api.RubySettings + * @memberof google.protobuf.StringValue * @static * @param {Object.} object Plain object - * @returns {google.api.RubySettings} RubySettings + * @returns {google.protobuf.StringValue} StringValue */ - RubySettings.fromObject = function fromObject(object) { - if (object instanceof $root.google.api.RubySettings) + StringValue.fromObject = function fromObject(object) { + if (object instanceof $root.google.protobuf.StringValue) return object; - var message = new $root.google.api.RubySettings(); - if (object.common != null) { - if (typeof object.common !== "object") - throw TypeError(".google.api.RubySettings.common: object expected"); - message.common = $root.google.api.CommonLanguageSettings.fromObject(object.common); - } + var message = new $root.google.protobuf.StringValue(); + if (object.value != null) + message.value = String(object.value); return message; }; /** - * Creates a plain object from a RubySettings message. Also converts values to other types if specified. + * Creates a plain object from a StringValue message. Also converts values to other types if specified. * @function toObject - * @memberof google.api.RubySettings + * @memberof google.protobuf.StringValue * @static - * @param {google.api.RubySettings} message RubySettings + * @param {google.protobuf.StringValue} message StringValue * @param {$protobuf.IConversionOptions} [options] Conversion options * @returns {Object.} Plain object */ - RubySettings.toObject = function toObject(message, options) { + StringValue.toObject = function toObject(message, options) { if (!options) options = {}; var object = {}; if (options.defaults) - object.common = null; - if (message.common != null && message.hasOwnProperty("common")) - object.common = $root.google.api.CommonLanguageSettings.toObject(message.common, options); + object.value = ""; + if (message.value != null && message.hasOwnProperty("value")) + object.value = message.value; return object; }; /** - * Converts this RubySettings to JSON. + * Converts this StringValue to JSON. * @function toJSON - * @memberof google.api.RubySettings + * @memberof google.protobuf.StringValue * @instance * @returns {Object.} JSON object */ - RubySettings.prototype.toJSON = function toJSON() { + StringValue.prototype.toJSON = function toJSON() { return this.constructor.toObject(this, $protobuf.util.toJSONOptions); }; /** - * Gets the default type url for RubySettings + * Gets the default type url for StringValue * @function getTypeUrl - * @memberof google.api.RubySettings + * @memberof google.protobuf.StringValue * @static * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") * @returns {string} The default type url */ - RubySettings.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + StringValue.getTypeUrl = function getTypeUrl(typeUrlPrefix) { if (typeUrlPrefix === undefined) { typeUrlPrefix = "type.googleapis.com"; } - return typeUrlPrefix + "/google.api.RubySettings"; + return typeUrlPrefix + "/google.protobuf.StringValue"; }; - return RubySettings; + return StringValue; })(); - api.GoSettings = (function() { + protobuf.BytesValue = (function() { /** - * Properties of a GoSettings. - * @memberof google.api - * @interface IGoSettings - * @property {google.api.ICommonLanguageSettings|null} [common] GoSettings common + * Properties of a BytesValue. + * @memberof google.protobuf + * @interface IBytesValue + * @property {Uint8Array|null} [value] BytesValue value */ /** - * Constructs a new GoSettings. - * @memberof google.api - * @classdesc Represents a GoSettings. - * @implements IGoSettings + * Constructs a new BytesValue. + * @memberof google.protobuf + * @classdesc Represents a BytesValue. + * @implements IBytesValue * @constructor - * @param {google.api.IGoSettings=} [properties] Properties to set + * @param {google.protobuf.IBytesValue=} [properties] Properties to set */ - function GoSettings(properties) { + function BytesValue(properties) { if (properties) for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) if (properties[keys[i]] != null) @@ -24636,103 +24607,105 @@ } /** - * GoSettings common. - * @member {google.api.ICommonLanguageSettings|null|undefined} common - * @memberof google.api.GoSettings + * BytesValue value. + * @member {Uint8Array} value + * @memberof google.protobuf.BytesValue * @instance */ - GoSettings.prototype.common = null; + BytesValue.prototype.value = $util.newBuffer([]); /** - * Creates a GoSettings message from a plain object. Also converts values to their respective internal types. + * Creates a BytesValue message from a plain object. Also converts values to their respective internal types. * @function fromObject - * @memberof google.api.GoSettings + * @memberof google.protobuf.BytesValue * @static * @param {Object.} object Plain object - * @returns {google.api.GoSettings} GoSettings + * @returns {google.protobuf.BytesValue} BytesValue */ - GoSettings.fromObject = function fromObject(object) { - if (object instanceof $root.google.api.GoSettings) + BytesValue.fromObject = function fromObject(object) { + if (object instanceof $root.google.protobuf.BytesValue) return object; - var message = new $root.google.api.GoSettings(); - if (object.common != null) { - if (typeof object.common !== "object") - throw TypeError(".google.api.GoSettings.common: object expected"); - message.common = $root.google.api.CommonLanguageSettings.fromObject(object.common); - } + var message = new $root.google.protobuf.BytesValue(); + if (object.value != null) + if (typeof object.value === "string") + $util.base64.decode(object.value, message.value = $util.newBuffer($util.base64.length(object.value)), 0); + else if (object.value.length >= 0) + message.value = object.value; return message; }; /** - * Creates a plain object from a GoSettings message. Also converts values to other types if specified. + * Creates a plain object from a BytesValue message. Also converts values to other types if specified. * @function toObject - * @memberof google.api.GoSettings + * @memberof google.protobuf.BytesValue * @static - * @param {google.api.GoSettings} message GoSettings + * @param {google.protobuf.BytesValue} message BytesValue * @param {$protobuf.IConversionOptions} [options] Conversion options * @returns {Object.} Plain object */ - GoSettings.toObject = function toObject(message, options) { + BytesValue.toObject = function toObject(message, options) { if (!options) options = {}; var object = {}; if (options.defaults) - object.common = null; - if (message.common != null && message.hasOwnProperty("common")) - object.common = $root.google.api.CommonLanguageSettings.toObject(message.common, options); + if (options.bytes === String) + object.value = ""; + else { + object.value = []; + if (options.bytes !== Array) + object.value = $util.newBuffer(object.value); + } + if (message.value != null && message.hasOwnProperty("value")) + object.value = options.bytes === String ? $util.base64.encode(message.value, 0, message.value.length) : options.bytes === Array ? Array.prototype.slice.call(message.value) : message.value; return object; }; /** - * Converts this GoSettings to JSON. + * Converts this BytesValue to JSON. * @function toJSON - * @memberof google.api.GoSettings + * @memberof google.protobuf.BytesValue * @instance * @returns {Object.} JSON object */ - GoSettings.prototype.toJSON = function toJSON() { + BytesValue.prototype.toJSON = function toJSON() { return this.constructor.toObject(this, $protobuf.util.toJSONOptions); }; /** - * Gets the default type url for GoSettings + * Gets the default type url for BytesValue * @function getTypeUrl - * @memberof google.api.GoSettings + * @memberof google.protobuf.BytesValue * @static * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") * @returns {string} The default type url */ - GoSettings.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + BytesValue.getTypeUrl = function getTypeUrl(typeUrlPrefix) { if (typeUrlPrefix === undefined) { typeUrlPrefix = "type.googleapis.com"; } - return typeUrlPrefix + "/google.api.GoSettings"; + return typeUrlPrefix + "/google.protobuf.BytesValue"; }; - return GoSettings; + return BytesValue; })(); - api.MethodSettings = (function() { + protobuf.Empty = (function() { /** - * Properties of a MethodSettings. - * @memberof google.api - * @interface IMethodSettings - * @property {string|null} [selector] MethodSettings selector - * @property {google.api.MethodSettings.ILongRunning|null} [longRunning] MethodSettings longRunning - * @property {Array.|null} [autoPopulatedFields] MethodSettings autoPopulatedFields + * Properties of an Empty. + * @memberof google.protobuf + * @interface IEmpty */ /** - * Constructs a new MethodSettings. - * @memberof google.api - * @classdesc Represents a MethodSettings. - * @implements IMethodSettings + * Constructs a new Empty. + * @memberof google.protobuf + * @classdesc Represents an Empty. + * @implements IEmpty * @constructor - * @param {google.api.IMethodSettings=} [properties] Properties to set + * @param {google.protobuf.IEmpty=} [properties] Properties to set */ - function MethodSettings(properties) { - this.autoPopulatedFields = []; + function Empty(properties) { if (properties) for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) if (properties[keys[i]] != null) @@ -24740,390 +24713,80 @@ } /** - * MethodSettings selector. - * @member {string} selector - * @memberof google.api.MethodSettings - * @instance - */ - MethodSettings.prototype.selector = ""; - - /** - * MethodSettings longRunning. - * @member {google.api.MethodSettings.ILongRunning|null|undefined} longRunning - * @memberof google.api.MethodSettings - * @instance - */ - MethodSettings.prototype.longRunning = null; - - /** - * MethodSettings autoPopulatedFields. - * @member {Array.} autoPopulatedFields - * @memberof google.api.MethodSettings - * @instance - */ - MethodSettings.prototype.autoPopulatedFields = $util.emptyArray; - - /** - * Creates a MethodSettings message from a plain object. Also converts values to their respective internal types. + * Creates an Empty message from a plain object. Also converts values to their respective internal types. * @function fromObject - * @memberof google.api.MethodSettings + * @memberof google.protobuf.Empty * @static * @param {Object.} object Plain object - * @returns {google.api.MethodSettings} MethodSettings - */ - MethodSettings.fromObject = function fromObject(object) { - if (object instanceof $root.google.api.MethodSettings) - return object; - var message = new $root.google.api.MethodSettings(); - if (object.selector != null) - message.selector = String(object.selector); - if (object.longRunning != null) { - if (typeof object.longRunning !== "object") - throw TypeError(".google.api.MethodSettings.longRunning: object expected"); - message.longRunning = $root.google.api.MethodSettings.LongRunning.fromObject(object.longRunning); - } - if (object.autoPopulatedFields) { - if (!Array.isArray(object.autoPopulatedFields)) - throw TypeError(".google.api.MethodSettings.autoPopulatedFields: array expected"); - message.autoPopulatedFields = []; - for (var i = 0; i < object.autoPopulatedFields.length; ++i) - message.autoPopulatedFields[i] = String(object.autoPopulatedFields[i]); - } - return message; - }; - - /** - * Creates a plain object from a MethodSettings message. Also converts values to other types if specified. - * @function toObject - * @memberof google.api.MethodSettings - * @static - * @param {google.api.MethodSettings} message MethodSettings - * @param {$protobuf.IConversionOptions} [options] Conversion options - * @returns {Object.} Plain object + * @returns {google.protobuf.Empty} Empty */ - MethodSettings.toObject = function toObject(message, options) { - if (!options) - options = {}; - var object = {}; - if (options.arrays || options.defaults) - object.autoPopulatedFields = []; - if (options.defaults) { - object.selector = ""; - object.longRunning = null; - } - if (message.selector != null && message.hasOwnProperty("selector")) - object.selector = message.selector; - if (message.longRunning != null && message.hasOwnProperty("longRunning")) - object.longRunning = $root.google.api.MethodSettings.LongRunning.toObject(message.longRunning, options); - if (message.autoPopulatedFields && message.autoPopulatedFields.length) { - object.autoPopulatedFields = []; - for (var j = 0; j < message.autoPopulatedFields.length; ++j) - object.autoPopulatedFields[j] = message.autoPopulatedFields[j]; - } - return object; + Empty.fromObject = function fromObject(object) { + if (object instanceof $root.google.protobuf.Empty) + return object; + return new $root.google.protobuf.Empty(); }; /** - * Converts this MethodSettings to JSON. + * Creates a plain object from an Empty message. Also converts values to other types if specified. + * @function toObject + * @memberof google.protobuf.Empty + * @static + * @param {google.protobuf.Empty} message Empty + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + Empty.toObject = function toObject() { + return {}; + }; + + /** + * Converts this Empty to JSON. * @function toJSON - * @memberof google.api.MethodSettings + * @memberof google.protobuf.Empty * @instance * @returns {Object.} JSON object */ - MethodSettings.prototype.toJSON = function toJSON() { + Empty.prototype.toJSON = function toJSON() { return this.constructor.toObject(this, $protobuf.util.toJSONOptions); }; /** - * Gets the default type url for MethodSettings + * Gets the default type url for Empty * @function getTypeUrl - * @memberof google.api.MethodSettings - * @static - * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") - * @returns {string} The default type url - */ - MethodSettings.getTypeUrl = function getTypeUrl(typeUrlPrefix) { - if (typeUrlPrefix === undefined) { - typeUrlPrefix = "type.googleapis.com"; - } - return typeUrlPrefix + "/google.api.MethodSettings"; - }; - - MethodSettings.LongRunning = (function() { - - /** - * Properties of a LongRunning. - * @memberof google.api.MethodSettings - * @interface ILongRunning - * @property {google.protobuf.IDuration|null} [initialPollDelay] LongRunning initialPollDelay - * @property {number|null} [pollDelayMultiplier] LongRunning pollDelayMultiplier - * @property {google.protobuf.IDuration|null} [maxPollDelay] LongRunning maxPollDelay - * @property {google.protobuf.IDuration|null} [totalPollTimeout] LongRunning totalPollTimeout - */ - - /** - * Constructs a new LongRunning. - * @memberof google.api.MethodSettings - * @classdesc Represents a LongRunning. - * @implements ILongRunning - * @constructor - * @param {google.api.MethodSettings.ILongRunning=} [properties] Properties to set - */ - function LongRunning(properties) { - if (properties) - for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) - if (properties[keys[i]] != null) - this[keys[i]] = properties[keys[i]]; - } - - /** - * LongRunning initialPollDelay. - * @member {google.protobuf.IDuration|null|undefined} initialPollDelay - * @memberof google.api.MethodSettings.LongRunning - * @instance - */ - LongRunning.prototype.initialPollDelay = null; - - /** - * LongRunning pollDelayMultiplier. - * @member {number} pollDelayMultiplier - * @memberof google.api.MethodSettings.LongRunning - * @instance - */ - LongRunning.prototype.pollDelayMultiplier = 0; - - /** - * LongRunning maxPollDelay. - * @member {google.protobuf.IDuration|null|undefined} maxPollDelay - * @memberof google.api.MethodSettings.LongRunning - * @instance - */ - LongRunning.prototype.maxPollDelay = null; - - /** - * LongRunning totalPollTimeout. - * @member {google.protobuf.IDuration|null|undefined} totalPollTimeout - * @memberof google.api.MethodSettings.LongRunning - * @instance - */ - LongRunning.prototype.totalPollTimeout = null; - - /** - * Creates a LongRunning message from a plain object. Also converts values to their respective internal types. - * @function fromObject - * @memberof google.api.MethodSettings.LongRunning - * @static - * @param {Object.} object Plain object - * @returns {google.api.MethodSettings.LongRunning} LongRunning - */ - LongRunning.fromObject = function fromObject(object) { - if (object instanceof $root.google.api.MethodSettings.LongRunning) - return object; - var message = new $root.google.api.MethodSettings.LongRunning(); - if (object.initialPollDelay != null) { - if (typeof object.initialPollDelay !== "object") - throw TypeError(".google.api.MethodSettings.LongRunning.initialPollDelay: object expected"); - message.initialPollDelay = $root.google.protobuf.Duration.fromObject(object.initialPollDelay); - } - if (object.pollDelayMultiplier != null) - message.pollDelayMultiplier = Number(object.pollDelayMultiplier); - if (object.maxPollDelay != null) { - if (typeof object.maxPollDelay !== "object") - throw TypeError(".google.api.MethodSettings.LongRunning.maxPollDelay: object expected"); - message.maxPollDelay = $root.google.protobuf.Duration.fromObject(object.maxPollDelay); - } - if (object.totalPollTimeout != null) { - if (typeof object.totalPollTimeout !== "object") - throw TypeError(".google.api.MethodSettings.LongRunning.totalPollTimeout: object expected"); - message.totalPollTimeout = $root.google.protobuf.Duration.fromObject(object.totalPollTimeout); - } - return message; - }; - - /** - * Creates a plain object from a LongRunning message. Also converts values to other types if specified. - * @function toObject - * @memberof google.api.MethodSettings.LongRunning - * @static - * @param {google.api.MethodSettings.LongRunning} message LongRunning - * @param {$protobuf.IConversionOptions} [options] Conversion options - * @returns {Object.} Plain object - */ - LongRunning.toObject = function toObject(message, options) { - if (!options) - options = {}; - var object = {}; - if (options.defaults) { - object.initialPollDelay = null; - object.pollDelayMultiplier = 0; - object.maxPollDelay = null; - object.totalPollTimeout = null; - } - if (message.initialPollDelay != null && message.hasOwnProperty("initialPollDelay")) - object.initialPollDelay = $root.google.protobuf.Duration.toObject(message.initialPollDelay, options); - if (message.pollDelayMultiplier != null && message.hasOwnProperty("pollDelayMultiplier")) - object.pollDelayMultiplier = options.json && !isFinite(message.pollDelayMultiplier) ? String(message.pollDelayMultiplier) : message.pollDelayMultiplier; - if (message.maxPollDelay != null && message.hasOwnProperty("maxPollDelay")) - object.maxPollDelay = $root.google.protobuf.Duration.toObject(message.maxPollDelay, options); - if (message.totalPollTimeout != null && message.hasOwnProperty("totalPollTimeout")) - object.totalPollTimeout = $root.google.protobuf.Duration.toObject(message.totalPollTimeout, options); - return object; - }; - - /** - * Converts this LongRunning to JSON. - * @function toJSON - * @memberof google.api.MethodSettings.LongRunning - * @instance - * @returns {Object.} JSON object - */ - LongRunning.prototype.toJSON = function toJSON() { - return this.constructor.toObject(this, $protobuf.util.toJSONOptions); - }; - - /** - * Gets the default type url for LongRunning - * @function getTypeUrl - * @memberof google.api.MethodSettings.LongRunning - * @static - * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") - * @returns {string} The default type url - */ - LongRunning.getTypeUrl = function getTypeUrl(typeUrlPrefix) { - if (typeUrlPrefix === undefined) { - typeUrlPrefix = "type.googleapis.com"; - } - return typeUrlPrefix + "/google.api.MethodSettings.LongRunning"; - }; - - return LongRunning; - })(); - - return MethodSettings; - })(); - - /** - * ClientLibraryOrganization enum. - * @name google.api.ClientLibraryOrganization - * @enum {string} - * @property {string} CLIENT_LIBRARY_ORGANIZATION_UNSPECIFIED=CLIENT_LIBRARY_ORGANIZATION_UNSPECIFIED CLIENT_LIBRARY_ORGANIZATION_UNSPECIFIED value - * @property {string} CLOUD=CLOUD CLOUD value - * @property {string} ADS=ADS ADS value - * @property {string} PHOTOS=PHOTOS PHOTOS value - * @property {string} STREET_VIEW=STREET_VIEW STREET_VIEW value - * @property {string} SHOPPING=SHOPPING SHOPPING value - * @property {string} GEO=GEO GEO value - * @property {string} GENERATIVE_AI=GENERATIVE_AI GENERATIVE_AI value - */ - api.ClientLibraryOrganization = (function() { - var valuesById = {}, values = Object.create(valuesById); - values[valuesById[0] = "CLIENT_LIBRARY_ORGANIZATION_UNSPECIFIED"] = "CLIENT_LIBRARY_ORGANIZATION_UNSPECIFIED"; - values[valuesById[1] = "CLOUD"] = "CLOUD"; - values[valuesById[2] = "ADS"] = "ADS"; - values[valuesById[3] = "PHOTOS"] = "PHOTOS"; - values[valuesById[4] = "STREET_VIEW"] = "STREET_VIEW"; - values[valuesById[5] = "SHOPPING"] = "SHOPPING"; - values[valuesById[6] = "GEO"] = "GEO"; - values[valuesById[7] = "GENERATIVE_AI"] = "GENERATIVE_AI"; - return values; - })(); - - /** - * ClientLibraryDestination enum. - * @name google.api.ClientLibraryDestination - * @enum {string} - * @property {string} CLIENT_LIBRARY_DESTINATION_UNSPECIFIED=CLIENT_LIBRARY_DESTINATION_UNSPECIFIED CLIENT_LIBRARY_DESTINATION_UNSPECIFIED value - * @property {string} GITHUB=GITHUB GITHUB value - * @property {string} PACKAGE_MANAGER=PACKAGE_MANAGER PACKAGE_MANAGER value - */ - api.ClientLibraryDestination = (function() { - var valuesById = {}, values = Object.create(valuesById); - values[valuesById[0] = "CLIENT_LIBRARY_DESTINATION_UNSPECIFIED"] = "CLIENT_LIBRARY_DESTINATION_UNSPECIFIED"; - values[valuesById[10] = "GITHUB"] = "GITHUB"; - values[valuesById[20] = "PACKAGE_MANAGER"] = "PACKAGE_MANAGER"; - return values; - })(); - - /** - * LaunchStage enum. - * @name google.api.LaunchStage - * @enum {string} - * @property {string} LAUNCH_STAGE_UNSPECIFIED=LAUNCH_STAGE_UNSPECIFIED LAUNCH_STAGE_UNSPECIFIED value - * @property {string} UNIMPLEMENTED=UNIMPLEMENTED UNIMPLEMENTED value - * @property {string} PRELAUNCH=PRELAUNCH PRELAUNCH value - * @property {string} EARLY_ACCESS=EARLY_ACCESS EARLY_ACCESS value - * @property {string} ALPHA=ALPHA ALPHA value - * @property {string} BETA=BETA BETA value - * @property {string} GA=GA GA value - * @property {string} DEPRECATED=DEPRECATED DEPRECATED value - */ - api.LaunchStage = (function() { - var valuesById = {}, values = Object.create(valuesById); - values[valuesById[0] = "LAUNCH_STAGE_UNSPECIFIED"] = "LAUNCH_STAGE_UNSPECIFIED"; - values[valuesById[6] = "UNIMPLEMENTED"] = "UNIMPLEMENTED"; - values[valuesById[7] = "PRELAUNCH"] = "PRELAUNCH"; - values[valuesById[1] = "EARLY_ACCESS"] = "EARLY_ACCESS"; - values[valuesById[2] = "ALPHA"] = "ALPHA"; - values[valuesById[3] = "BETA"] = "BETA"; - values[valuesById[4] = "GA"] = "GA"; - values[valuesById[5] = "DEPRECATED"] = "DEPRECATED"; - return values; - })(); + * @memberof google.protobuf.Empty + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + Empty.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.protobuf.Empty"; + }; - /** - * FieldBehavior enum. - * @name google.api.FieldBehavior - * @enum {string} - * @property {string} FIELD_BEHAVIOR_UNSPECIFIED=FIELD_BEHAVIOR_UNSPECIFIED FIELD_BEHAVIOR_UNSPECIFIED value - * @property {string} OPTIONAL=OPTIONAL OPTIONAL value - * @property {string} REQUIRED=REQUIRED REQUIRED value - * @property {string} OUTPUT_ONLY=OUTPUT_ONLY OUTPUT_ONLY value - * @property {string} INPUT_ONLY=INPUT_ONLY INPUT_ONLY value - * @property {string} IMMUTABLE=IMMUTABLE IMMUTABLE value - * @property {string} UNORDERED_LIST=UNORDERED_LIST UNORDERED_LIST value - * @property {string} NON_EMPTY_DEFAULT=NON_EMPTY_DEFAULT NON_EMPTY_DEFAULT value - * @property {string} IDENTIFIER=IDENTIFIER IDENTIFIER value - */ - api.FieldBehavior = (function() { - var valuesById = {}, values = Object.create(valuesById); - values[valuesById[0] = "FIELD_BEHAVIOR_UNSPECIFIED"] = "FIELD_BEHAVIOR_UNSPECIFIED"; - values[valuesById[1] = "OPTIONAL"] = "OPTIONAL"; - values[valuesById[2] = "REQUIRED"] = "REQUIRED"; - values[valuesById[3] = "OUTPUT_ONLY"] = "OUTPUT_ONLY"; - values[valuesById[4] = "INPUT_ONLY"] = "INPUT_ONLY"; - values[valuesById[5] = "IMMUTABLE"] = "IMMUTABLE"; - values[valuesById[6] = "UNORDERED_LIST"] = "UNORDERED_LIST"; - values[valuesById[7] = "NON_EMPTY_DEFAULT"] = "NON_EMPTY_DEFAULT"; - values[valuesById[8] = "IDENTIFIER"] = "IDENTIFIER"; - return values; + return Empty; })(); - api.ResourceDescriptor = (function() { + protobuf.Any = (function() { /** - * Properties of a ResourceDescriptor. - * @memberof google.api - * @interface IResourceDescriptor - * @property {string|null} [type] ResourceDescriptor type - * @property {Array.|null} [pattern] ResourceDescriptor pattern - * @property {string|null} [nameField] ResourceDescriptor nameField - * @property {google.api.ResourceDescriptor.History|null} [history] ResourceDescriptor history - * @property {string|null} [plural] ResourceDescriptor plural - * @property {string|null} [singular] ResourceDescriptor singular - * @property {Array.|null} [style] ResourceDescriptor style + * Properties of an Any. + * @memberof google.protobuf + * @interface IAny + * @property {string|null} [type_url] Any type_url + * @property {Uint8Array|null} [value] Any value */ /** - * Constructs a new ResourceDescriptor. - * @memberof google.api - * @classdesc Represents a ResourceDescriptor. - * @implements IResourceDescriptor + * Constructs a new Any. + * @memberof google.protobuf + * @classdesc Represents an Any. + * @implements IAny * @constructor - * @param {google.api.IResourceDescriptor=} [properties] Properties to set + * @param {google.protobuf.IAny=} [properties] Properties to set */ - function ResourceDescriptor(properties) { - this.pattern = []; - this.style = []; + function Any(properties) { if (properties) for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) if (properties[keys[i]] != null) @@ -25131,257 +24794,240 @@ } /** - * ResourceDescriptor type. - * @member {string} type - * @memberof google.api.ResourceDescriptor + * Any type_url. + * @member {string} type_url + * @memberof google.protobuf.Any * @instance */ - ResourceDescriptor.prototype.type = ""; + Any.prototype.type_url = ""; /** - * ResourceDescriptor pattern. - * @member {Array.} pattern - * @memberof google.api.ResourceDescriptor + * Any value. + * @member {Uint8Array} value + * @memberof google.protobuf.Any * @instance */ - ResourceDescriptor.prototype.pattern = $util.emptyArray; + Any.prototype.value = $util.newBuffer([]); /** - * ResourceDescriptor nameField. - * @member {string} nameField - * @memberof google.api.ResourceDescriptor - * @instance + * Creates an Any message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.protobuf.Any + * @static + * @param {Object.} object Plain object + * @returns {google.protobuf.Any} Any */ - ResourceDescriptor.prototype.nameField = ""; + Any.fromObject = function fromObject(object) { + if (object instanceof $root.google.protobuf.Any) + return object; + var message = new $root.google.protobuf.Any(); + if (object.type_url != null) + message.type_url = String(object.type_url); + if (object.value != null) + if (typeof object.value === "string") + $util.base64.decode(object.value, message.value = $util.newBuffer($util.base64.length(object.value)), 0); + else if (object.value.length >= 0) + message.value = object.value; + return message; + }; /** - * ResourceDescriptor history. - * @member {google.api.ResourceDescriptor.History} history - * @memberof google.api.ResourceDescriptor - * @instance + * Creates a plain object from an Any message. Also converts values to other types if specified. + * @function toObject + * @memberof google.protobuf.Any + * @static + * @param {google.protobuf.Any} message Any + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object */ - ResourceDescriptor.prototype.history = 0; + Any.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.defaults) { + object.type_url = ""; + if (options.bytes === String) + object.value = ""; + else { + object.value = []; + if (options.bytes !== Array) + object.value = $util.newBuffer(object.value); + } + } + if (message.type_url != null && message.hasOwnProperty("type_url")) + object.type_url = message.type_url; + if (message.value != null && message.hasOwnProperty("value")) + object.value = options.bytes === String ? $util.base64.encode(message.value, 0, message.value.length) : options.bytes === Array ? Array.prototype.slice.call(message.value) : message.value; + return object; + }; /** - * ResourceDescriptor plural. - * @member {string} plural - * @memberof google.api.ResourceDescriptor + * Converts this Any to JSON. + * @function toJSON + * @memberof google.protobuf.Any * @instance + * @returns {Object.} JSON object */ - ResourceDescriptor.prototype.plural = ""; + Any.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; /** - * ResourceDescriptor singular. - * @member {string} singular - * @memberof google.api.ResourceDescriptor - * @instance + * Gets the default type url for Any + * @function getTypeUrl + * @memberof google.protobuf.Any + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url */ - ResourceDescriptor.prototype.singular = ""; + Any.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.protobuf.Any"; + }; + + return Any; + })(); + + protobuf.FieldMask = (function() { /** - * ResourceDescriptor style. - * @member {Array.} style - * @memberof google.api.ResourceDescriptor - * @instance + * Properties of a FieldMask. + * @memberof google.protobuf + * @interface IFieldMask + * @property {Array.|null} [paths] FieldMask paths */ - ResourceDescriptor.prototype.style = $util.emptyArray; /** - * Creates a ResourceDescriptor message from a plain object. Also converts values to their respective internal types. - * @function fromObject - * @memberof google.api.ResourceDescriptor - * @static - * @param {Object.} object Plain object - * @returns {google.api.ResourceDescriptor} ResourceDescriptor + * Constructs a new FieldMask. + * @memberof google.protobuf + * @classdesc Represents a FieldMask. + * @implements IFieldMask + * @constructor + * @param {google.protobuf.IFieldMask=} [properties] Properties to set */ - ResourceDescriptor.fromObject = function fromObject(object) { - if (object instanceof $root.google.api.ResourceDescriptor) - return object; - var message = new $root.google.api.ResourceDescriptor(); - if (object.type != null) - message.type = String(object.type); - if (object.pattern) { - if (!Array.isArray(object.pattern)) - throw TypeError(".google.api.ResourceDescriptor.pattern: array expected"); - message.pattern = []; - for (var i = 0; i < object.pattern.length; ++i) - message.pattern[i] = String(object.pattern[i]); - } - if (object.nameField != null) - message.nameField = String(object.nameField); - switch (object.history) { - default: - if (typeof object.history === "number") { - message.history = object.history; - break; - } - break; - case "HISTORY_UNSPECIFIED": - case 0: - message.history = 0; - break; - case "ORIGINALLY_SINGLE_PATTERN": - case 1: - message.history = 1; - break; - case "FUTURE_MULTI_PATTERN": - case 2: - message.history = 2; - break; - } - if (object.plural != null) - message.plural = String(object.plural); - if (object.singular != null) - message.singular = String(object.singular); - if (object.style) { - if (!Array.isArray(object.style)) - throw TypeError(".google.api.ResourceDescriptor.style: array expected"); - message.style = []; - for (var i = 0; i < object.style.length; ++i) - switch (object.style[i]) { - default: - if (typeof object.style[i] === "number") { - message.style[i] = object.style[i]; - break; - } - case "STYLE_UNSPECIFIED": - case 0: - message.style[i] = 0; - break; - case "DECLARATIVE_FRIENDLY": - case 1: - message.style[i] = 1; - break; - } + function FieldMask(properties) { + this.paths = []; + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } + + /** + * FieldMask paths. + * @member {Array.} paths + * @memberof google.protobuf.FieldMask + * @instance + */ + FieldMask.prototype.paths = $util.emptyArray; + + /** + * Creates a FieldMask message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.protobuf.FieldMask + * @static + * @param {Object.} object Plain object + * @returns {google.protobuf.FieldMask} FieldMask + */ + FieldMask.fromObject = function fromObject(object) { + if (object instanceof $root.google.protobuf.FieldMask) + return object; + var message = new $root.google.protobuf.FieldMask(); + if (object.paths) { + if (!Array.isArray(object.paths)) + throw TypeError(".google.protobuf.FieldMask.paths: array expected"); + message.paths = []; + for (var i = 0; i < object.paths.length; ++i) + message.paths[i] = String(object.paths[i]); } return message; }; /** - * Creates a plain object from a ResourceDescriptor message. Also converts values to other types if specified. + * Creates a plain object from a FieldMask message. Also converts values to other types if specified. * @function toObject - * @memberof google.api.ResourceDescriptor + * @memberof google.protobuf.FieldMask * @static - * @param {google.api.ResourceDescriptor} message ResourceDescriptor + * @param {google.protobuf.FieldMask} message FieldMask * @param {$protobuf.IConversionOptions} [options] Conversion options * @returns {Object.} Plain object */ - ResourceDescriptor.toObject = function toObject(message, options) { + FieldMask.toObject = function toObject(message, options) { if (!options) options = {}; var object = {}; - if (options.arrays || options.defaults) { - object.pattern = []; - object.style = []; - } - if (options.defaults) { - object.type = ""; - object.nameField = ""; - object.history = options.enums === String ? "HISTORY_UNSPECIFIED" : 0; - object.plural = ""; - object.singular = ""; - } - if (message.type != null && message.hasOwnProperty("type")) - object.type = message.type; - if (message.pattern && message.pattern.length) { - object.pattern = []; - for (var j = 0; j < message.pattern.length; ++j) - object.pattern[j] = message.pattern[j]; - } - if (message.nameField != null && message.hasOwnProperty("nameField")) - object.nameField = message.nameField; - if (message.history != null && message.hasOwnProperty("history")) - object.history = options.enums === String ? $root.google.api.ResourceDescriptor.History[message.history] === undefined ? message.history : $root.google.api.ResourceDescriptor.History[message.history] : message.history; - if (message.plural != null && message.hasOwnProperty("plural")) - object.plural = message.plural; - if (message.singular != null && message.hasOwnProperty("singular")) - object.singular = message.singular; - if (message.style && message.style.length) { - object.style = []; - for (var j = 0; j < message.style.length; ++j) - object.style[j] = options.enums === String ? $root.google.api.ResourceDescriptor.Style[message.style[j]] === undefined ? message.style[j] : $root.google.api.ResourceDescriptor.Style[message.style[j]] : message.style[j]; + if (options.arrays || options.defaults) + object.paths = []; + if (message.paths && message.paths.length) { + object.paths = []; + for (var j = 0; j < message.paths.length; ++j) + object.paths[j] = message.paths[j]; } return object; }; /** - * Converts this ResourceDescriptor to JSON. + * Converts this FieldMask to JSON. * @function toJSON - * @memberof google.api.ResourceDescriptor + * @memberof google.protobuf.FieldMask * @instance * @returns {Object.} JSON object */ - ResourceDescriptor.prototype.toJSON = function toJSON() { + FieldMask.prototype.toJSON = function toJSON() { return this.constructor.toObject(this, $protobuf.util.toJSONOptions); }; /** - * Gets the default type url for ResourceDescriptor + * Gets the default type url for FieldMask * @function getTypeUrl - * @memberof google.api.ResourceDescriptor + * @memberof google.protobuf.FieldMask * @static * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") * @returns {string} The default type url */ - ResourceDescriptor.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + FieldMask.getTypeUrl = function getTypeUrl(typeUrlPrefix) { if (typeUrlPrefix === undefined) { typeUrlPrefix = "type.googleapis.com"; } - return typeUrlPrefix + "/google.api.ResourceDescriptor"; + return typeUrlPrefix + "/google.protobuf.FieldMask"; }; - /** - * History enum. - * @name google.api.ResourceDescriptor.History - * @enum {string} - * @property {string} HISTORY_UNSPECIFIED=HISTORY_UNSPECIFIED HISTORY_UNSPECIFIED value - * @property {string} ORIGINALLY_SINGLE_PATTERN=ORIGINALLY_SINGLE_PATTERN ORIGINALLY_SINGLE_PATTERN value - * @property {string} FUTURE_MULTI_PATTERN=FUTURE_MULTI_PATTERN FUTURE_MULTI_PATTERN value - */ - ResourceDescriptor.History = (function() { - var valuesById = {}, values = Object.create(valuesById); - values[valuesById[0] = "HISTORY_UNSPECIFIED"] = "HISTORY_UNSPECIFIED"; - values[valuesById[1] = "ORIGINALLY_SINGLE_PATTERN"] = "ORIGINALLY_SINGLE_PATTERN"; - values[valuesById[2] = "FUTURE_MULTI_PATTERN"] = "FUTURE_MULTI_PATTERN"; - return values; - })(); + return FieldMask; + })(); - /** - * Style enum. - * @name google.api.ResourceDescriptor.Style - * @enum {string} - * @property {string} STYLE_UNSPECIFIED=STYLE_UNSPECIFIED STYLE_UNSPECIFIED value - * @property {string} DECLARATIVE_FRIENDLY=DECLARATIVE_FRIENDLY DECLARATIVE_FRIENDLY value - */ - ResourceDescriptor.Style = (function() { - var valuesById = {}, values = Object.create(valuesById); - values[valuesById[0] = "STYLE_UNSPECIFIED"] = "STYLE_UNSPECIFIED"; - values[valuesById[1] = "DECLARATIVE_FRIENDLY"] = "DECLARATIVE_FRIENDLY"; - return values; - })(); + return protobuf; + })(); - return ResourceDescriptor; - })(); + google.type = (function() { - api.ResourceReference = (function() { + /** + * Namespace type. + * @memberof google + * @namespace + */ + var type = {}; + + type.LatLng = (function() { /** - * Properties of a ResourceReference. - * @memberof google.api - * @interface IResourceReference - * @property {string|null} [type] ResourceReference type - * @property {string|null} [childType] ResourceReference childType + * Properties of a LatLng. + * @memberof google.type + * @interface ILatLng + * @property {number|null} [latitude] LatLng latitude + * @property {number|null} [longitude] LatLng longitude */ /** - * Constructs a new ResourceReference. - * @memberof google.api - * @classdesc Represents a ResourceReference. - * @implements IResourceReference + * Constructs a new LatLng. + * @memberof google.type + * @classdesc Represents a LatLng. + * @implements ILatLng * @constructor - * @param {google.api.IResourceReference=} [properties] Properties to set + * @param {google.type.ILatLng=} [properties] Properties to set */ - function ResourceReference(properties) { + function LatLng(properties) { if (properties) for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) if (properties[keys[i]] != null) @@ -25389,94 +25035,120 @@ } /** - * ResourceReference type. - * @member {string} type - * @memberof google.api.ResourceReference + * LatLng latitude. + * @member {number} latitude + * @memberof google.type.LatLng * @instance */ - ResourceReference.prototype.type = ""; + LatLng.prototype.latitude = 0; /** - * ResourceReference childType. - * @member {string} childType - * @memberof google.api.ResourceReference + * LatLng longitude. + * @member {number} longitude + * @memberof google.type.LatLng * @instance */ - ResourceReference.prototype.childType = ""; + LatLng.prototype.longitude = 0; /** - * Creates a ResourceReference message from a plain object. Also converts values to their respective internal types. + * Creates a LatLng message from a plain object. Also converts values to their respective internal types. * @function fromObject - * @memberof google.api.ResourceReference + * @memberof google.type.LatLng * @static * @param {Object.} object Plain object - * @returns {google.api.ResourceReference} ResourceReference + * @returns {google.type.LatLng} LatLng */ - ResourceReference.fromObject = function fromObject(object) { - if (object instanceof $root.google.api.ResourceReference) + LatLng.fromObject = function fromObject(object) { + if (object instanceof $root.google.type.LatLng) return object; - var message = new $root.google.api.ResourceReference(); - if (object.type != null) - message.type = String(object.type); - if (object.childType != null) - message.childType = String(object.childType); + var message = new $root.google.type.LatLng(); + if (object.latitude != null) + message.latitude = Number(object.latitude); + if (object.longitude != null) + message.longitude = Number(object.longitude); return message; }; /** - * Creates a plain object from a ResourceReference message. Also converts values to other types if specified. + * Creates a plain object from a LatLng message. Also converts values to other types if specified. * @function toObject - * @memberof google.api.ResourceReference + * @memberof google.type.LatLng * @static - * @param {google.api.ResourceReference} message ResourceReference + * @param {google.type.LatLng} message LatLng * @param {$protobuf.IConversionOptions} [options] Conversion options * @returns {Object.} Plain object */ - ResourceReference.toObject = function toObject(message, options) { + LatLng.toObject = function toObject(message, options) { if (!options) options = {}; var object = {}; if (options.defaults) { - object.type = ""; - object.childType = ""; + object.latitude = 0; + object.longitude = 0; } - if (message.type != null && message.hasOwnProperty("type")) - object.type = message.type; - if (message.childType != null && message.hasOwnProperty("childType")) - object.childType = message.childType; + if (message.latitude != null && message.hasOwnProperty("latitude")) + object.latitude = options.json && !isFinite(message.latitude) ? String(message.latitude) : message.latitude; + if (message.longitude != null && message.hasOwnProperty("longitude")) + object.longitude = options.json && !isFinite(message.longitude) ? String(message.longitude) : message.longitude; return object; }; /** - * Converts this ResourceReference to JSON. + * Converts this LatLng to JSON. * @function toJSON - * @memberof google.api.ResourceReference + * @memberof google.type.LatLng * @instance * @returns {Object.} JSON object */ - ResourceReference.prototype.toJSON = function toJSON() { + LatLng.prototype.toJSON = function toJSON() { return this.constructor.toObject(this, $protobuf.util.toJSONOptions); }; /** - * Gets the default type url for ResourceReference + * Gets the default type url for LatLng * @function getTypeUrl - * @memberof google.api.ResourceReference + * @memberof google.type.LatLng * @static * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") * @returns {string} The default type url */ - ResourceReference.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + LatLng.getTypeUrl = function getTypeUrl(typeUrlPrefix) { if (typeUrlPrefix === undefined) { typeUrlPrefix = "type.googleapis.com"; } - return typeUrlPrefix + "/google.api.ResourceReference"; + return typeUrlPrefix + "/google.type.LatLng"; }; - return ResourceReference; + return LatLng; })(); - return api; + /** + * DayOfWeek enum. + * @name google.type.DayOfWeek + * @enum {string} + * @property {string} DAY_OF_WEEK_UNSPECIFIED=DAY_OF_WEEK_UNSPECIFIED DAY_OF_WEEK_UNSPECIFIED value + * @property {string} MONDAY=MONDAY MONDAY value + * @property {string} TUESDAY=TUESDAY TUESDAY value + * @property {string} WEDNESDAY=WEDNESDAY WEDNESDAY value + * @property {string} THURSDAY=THURSDAY THURSDAY value + * @property {string} FRIDAY=FRIDAY FRIDAY value + * @property {string} SATURDAY=SATURDAY SATURDAY value + * @property {string} SUNDAY=SUNDAY SUNDAY value + */ + type.DayOfWeek = (function() { + var valuesById = {}, values = Object.create(valuesById); + values[valuesById[0] = "DAY_OF_WEEK_UNSPECIFIED"] = "DAY_OF_WEEK_UNSPECIFIED"; + values[valuesById[1] = "MONDAY"] = "MONDAY"; + values[valuesById[2] = "TUESDAY"] = "TUESDAY"; + values[valuesById[3] = "WEDNESDAY"] = "WEDNESDAY"; + values[valuesById[4] = "THURSDAY"] = "THURSDAY"; + values[valuesById[5] = "FRIDAY"] = "FRIDAY"; + values[valuesById[6] = "SATURDAY"] = "SATURDAY"; + values[valuesById[7] = "SUNDAY"] = "SUNDAY"; + return values; + })(); + + return type; })(); google.rpc = (function() { diff --git a/dev/protos/firestore_v1beta1_proto_api.d.ts b/dev/protos/firestore_v1beta1_proto_api.d.ts index 13c57392f..1a37aaa0e 100644 --- a/dev/protos/firestore_v1beta1_proto_api.d.ts +++ b/dev/protos/firestore_v1beta1_proto_api.d.ts @@ -307,7 +307,7 @@ export namespace google { /** Edition enum. */ type Edition = - "EDITION_UNKNOWN"| "EDITION_LEGACY"| "EDITION_PROTO2"| "EDITION_PROTO3"| "EDITION_2023"| "EDITION_2024"| "EDITION_1_TEST_ONLY"| "EDITION_2_TEST_ONLY"| "EDITION_99997_TEST_ONLY"| "EDITION_99998_TEST_ONLY"| "EDITION_99999_TEST_ONLY"| "EDITION_MAX"; + "EDITION_UNKNOWN"| "EDITION_PROTO2"| "EDITION_PROTO3"| "EDITION_2023"| "EDITION_2024"| "EDITION_1_TEST_ONLY"| "EDITION_2_TEST_ONLY"| "EDITION_99997_TEST_ONLY"| "EDITION_99998_TEST_ONLY"| "EDITION_99999_TEST_ONLY"| "EDITION_MAX"; /** Properties of a FileDescriptorProto. */ interface IFileDescriptorProto { @@ -1597,9 +1597,6 @@ export namespace google { /** FieldOptions features */ features?: (google.protobuf.IFeatureSet|null); - /** FieldOptions featureSupport */ - featureSupport?: (google.protobuf.FieldOptions.IFeatureSupport|null); - /** FieldOptions uninterpretedOption */ uninterpretedOption?: (google.protobuf.IUninterpretedOption[]|null); @@ -1655,9 +1652,6 @@ export namespace google { /** FieldOptions features. */ public features?: (google.protobuf.IFeatureSet|null); - /** FieldOptions featureSupport. */ - public featureSupport?: (google.protobuf.FieldOptions.IFeatureSupport|null); - /** FieldOptions uninterpretedOption. */ public uninterpretedOption: google.protobuf.IUninterpretedOption[]; @@ -1761,72 +1755,6 @@ export namespace google { */ public static getTypeUrl(typeUrlPrefix?: string): string; } - - /** Properties of a FeatureSupport. */ - interface IFeatureSupport { - - /** FeatureSupport editionIntroduced */ - editionIntroduced?: (google.protobuf.Edition|null); - - /** FeatureSupport editionDeprecated */ - editionDeprecated?: (google.protobuf.Edition|null); - - /** FeatureSupport deprecationWarning */ - deprecationWarning?: (string|null); - - /** FeatureSupport editionRemoved */ - editionRemoved?: (google.protobuf.Edition|null); - } - - /** Represents a FeatureSupport. */ - class FeatureSupport implements IFeatureSupport { - - /** - * Constructs a new FeatureSupport. - * @param [properties] Properties to set - */ - constructor(properties?: google.protobuf.FieldOptions.IFeatureSupport); - - /** FeatureSupport editionIntroduced. */ - public editionIntroduced: google.protobuf.Edition; - - /** FeatureSupport editionDeprecated. */ - public editionDeprecated: google.protobuf.Edition; - - /** FeatureSupport deprecationWarning. */ - public deprecationWarning: string; - - /** FeatureSupport editionRemoved. */ - public editionRemoved: google.protobuf.Edition; - - /** - * Creates a FeatureSupport message from a plain object. Also converts values to their respective internal types. - * @param object Plain object - * @returns FeatureSupport - */ - public static fromObject(object: { [k: string]: any }): google.protobuf.FieldOptions.FeatureSupport; - - /** - * Creates a plain object from a FeatureSupport message. Also converts values to other types if specified. - * @param message FeatureSupport - * @param [options] Conversion options - * @returns Plain object - */ - public static toObject(message: google.protobuf.FieldOptions.FeatureSupport, options?: $protobuf.IConversionOptions): { [k: string]: any }; - - /** - * Converts this FeatureSupport to JSON. - * @returns JSON object - */ - public toJSON(): { [k: string]: any }; - - /** - * Gets the default type url for FeatureSupport - * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") - * @returns The default type url - */ - public static getTypeUrl(typeUrlPrefix?: string): string; - } } /** Properties of an OneofOptions. */ @@ -2486,11 +2414,8 @@ export namespace google { /** FeatureSetEditionDefault edition */ edition?: (google.protobuf.Edition|null); - /** FeatureSetEditionDefault overridableFeatures */ - overridableFeatures?: (google.protobuf.IFeatureSet|null); - - /** FeatureSetEditionDefault fixedFeatures */ - fixedFeatures?: (google.protobuf.IFeatureSet|null); + /** FeatureSetEditionDefault features */ + features?: (google.protobuf.IFeatureSet|null); } /** Represents a FeatureSetEditionDefault. */ @@ -2505,11 +2430,8 @@ export namespace google { /** FeatureSetEditionDefault edition. */ public edition: google.protobuf.Edition; - /** FeatureSetEditionDefault overridableFeatures. */ - public overridableFeatures?: (google.protobuf.IFeatureSet|null); - - /** FeatureSetEditionDefault fixedFeatures. */ - public fixedFeatures?: (google.protobuf.IFeatureSet|null); + /** FeatureSetEditionDefault features. */ + public features?: (google.protobuf.IFeatureSet|null); /** * Creates a FeatureSetEditionDefault message from a plain object. Also converts values to their respective internal types. diff --git a/dev/protos/firestore_v1beta1_proto_api.js b/dev/protos/firestore_v1beta1_proto_api.js index 817f81d7a..14cdf1c2a 100644 --- a/dev/protos/firestore_v1beta1_proto_api.js +++ b/dev/protos/firestore_v1beta1_proto_api.js @@ -734,7 +734,6 @@ * @name google.protobuf.Edition * @enum {string} * @property {string} EDITION_UNKNOWN=EDITION_UNKNOWN EDITION_UNKNOWN value - * @property {string} EDITION_LEGACY=EDITION_LEGACY EDITION_LEGACY value * @property {string} EDITION_PROTO2=EDITION_PROTO2 EDITION_PROTO2 value * @property {string} EDITION_PROTO3=EDITION_PROTO3 EDITION_PROTO3 value * @property {string} EDITION_2023=EDITION_2023 EDITION_2023 value @@ -749,7 +748,6 @@ protobuf.Edition = (function() { var valuesById = {}, values = Object.create(valuesById); values[valuesById[0] = "EDITION_UNKNOWN"] = "EDITION_UNKNOWN"; - values[valuesById[900] = "EDITION_LEGACY"] = "EDITION_LEGACY"; values[valuesById[998] = "EDITION_PROTO2"] = "EDITION_PROTO2"; values[valuesById[999] = "EDITION_PROTO3"] = "EDITION_PROTO3"; values[valuesById[1000] = "EDITION_2023"] = "EDITION_2023"; @@ -1010,10 +1008,6 @@ case 0: message.edition = 0; break; - case "EDITION_LEGACY": - case 900: - message.edition = 900; - break; case "EDITION_PROTO2": case 998: message.edition = 998; @@ -4043,7 +4037,6 @@ * @property {Array.|null} [targets] FieldOptions targets * @property {Array.|null} [editionDefaults] FieldOptions editionDefaults * @property {google.protobuf.IFeatureSet|null} [features] FieldOptions features - * @property {google.protobuf.FieldOptions.IFeatureSupport|null} [featureSupport] FieldOptions featureSupport * @property {Array.|null} [uninterpretedOption] FieldOptions uninterpretedOption * @property {Array.|null} [".google.api.fieldBehavior"] FieldOptions .google.api.fieldBehavior * @property {google.api.IResourceReference|null} [".google.api.resourceReference"] FieldOptions .google.api.resourceReference @@ -4164,14 +4157,6 @@ */ FieldOptions.prototype.features = null; - /** - * FieldOptions featureSupport. - * @member {google.protobuf.FieldOptions.IFeatureSupport|null|undefined} featureSupport - * @memberof google.protobuf.FieldOptions - * @instance - */ - FieldOptions.prototype.featureSupport = null; - /** * FieldOptions uninterpretedOption. * @member {Array.} uninterpretedOption @@ -4348,11 +4333,6 @@ throw TypeError(".google.protobuf.FieldOptions.features: object expected"); message.features = $root.google.protobuf.FeatureSet.fromObject(object.features); } - if (object.featureSupport != null) { - if (typeof object.featureSupport !== "object") - throw TypeError(".google.protobuf.FieldOptions.featureSupport: object expected"); - message.featureSupport = $root.google.protobuf.FieldOptions.FeatureSupport.fromObject(object.featureSupport); - } if (object.uninterpretedOption) { if (!Array.isArray(object.uninterpretedOption)) throw TypeError(".google.protobuf.FieldOptions.uninterpretedOption: array expected"); @@ -4450,7 +4430,6 @@ object.debugRedact = false; object.retention = options.enums === String ? "RETENTION_UNKNOWN" : 0; object.features = null; - object.featureSupport = null; object[".google.api.resourceReference"] = null; } if (message.ctype != null && message.hasOwnProperty("ctype")) @@ -4483,8 +4462,6 @@ } if (message.features != null && message.hasOwnProperty("features")) object.features = $root.google.protobuf.FeatureSet.toObject(message.features, options); - if (message.featureSupport != null && message.hasOwnProperty("featureSupport")) - object.featureSupport = $root.google.protobuf.FieldOptions.FeatureSupport.toObject(message.featureSupport, options); if (message.uninterpretedOption && message.uninterpretedOption.length) { object.uninterpretedOption = []; for (var j = 0; j < message.uninterpretedOption.length; ++j) @@ -4668,10 +4645,6 @@ case 0: message.edition = 0; break; - case "EDITION_LEGACY": - case 900: - message.edition = 900; - break; case "EDITION_PROTO2": case 998: message.edition = 998; @@ -4771,309 +4744,6 @@ return EditionDefault; })(); - FieldOptions.FeatureSupport = (function() { - - /** - * Properties of a FeatureSupport. - * @memberof google.protobuf.FieldOptions - * @interface IFeatureSupport - * @property {google.protobuf.Edition|null} [editionIntroduced] FeatureSupport editionIntroduced - * @property {google.protobuf.Edition|null} [editionDeprecated] FeatureSupport editionDeprecated - * @property {string|null} [deprecationWarning] FeatureSupport deprecationWarning - * @property {google.protobuf.Edition|null} [editionRemoved] FeatureSupport editionRemoved - */ - - /** - * Constructs a new FeatureSupport. - * @memberof google.protobuf.FieldOptions - * @classdesc Represents a FeatureSupport. - * @implements IFeatureSupport - * @constructor - * @param {google.protobuf.FieldOptions.IFeatureSupport=} [properties] Properties to set - */ - function FeatureSupport(properties) { - if (properties) - for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) - if (properties[keys[i]] != null) - this[keys[i]] = properties[keys[i]]; - } - - /** - * FeatureSupport editionIntroduced. - * @member {google.protobuf.Edition} editionIntroduced - * @memberof google.protobuf.FieldOptions.FeatureSupport - * @instance - */ - FeatureSupport.prototype.editionIntroduced = 0; - - /** - * FeatureSupport editionDeprecated. - * @member {google.protobuf.Edition} editionDeprecated - * @memberof google.protobuf.FieldOptions.FeatureSupport - * @instance - */ - FeatureSupport.prototype.editionDeprecated = 0; - - /** - * FeatureSupport deprecationWarning. - * @member {string} deprecationWarning - * @memberof google.protobuf.FieldOptions.FeatureSupport - * @instance - */ - FeatureSupport.prototype.deprecationWarning = ""; - - /** - * FeatureSupport editionRemoved. - * @member {google.protobuf.Edition} editionRemoved - * @memberof google.protobuf.FieldOptions.FeatureSupport - * @instance - */ - FeatureSupport.prototype.editionRemoved = 0; - - /** - * Creates a FeatureSupport message from a plain object. Also converts values to their respective internal types. - * @function fromObject - * @memberof google.protobuf.FieldOptions.FeatureSupport - * @static - * @param {Object.} object Plain object - * @returns {google.protobuf.FieldOptions.FeatureSupport} FeatureSupport - */ - FeatureSupport.fromObject = function fromObject(object) { - if (object instanceof $root.google.protobuf.FieldOptions.FeatureSupport) - return object; - var message = new $root.google.protobuf.FieldOptions.FeatureSupport(); - switch (object.editionIntroduced) { - default: - if (typeof object.editionIntroduced === "number") { - message.editionIntroduced = object.editionIntroduced; - break; - } - break; - case "EDITION_UNKNOWN": - case 0: - message.editionIntroduced = 0; - break; - case "EDITION_LEGACY": - case 900: - message.editionIntroduced = 900; - break; - case "EDITION_PROTO2": - case 998: - message.editionIntroduced = 998; - break; - case "EDITION_PROTO3": - case 999: - message.editionIntroduced = 999; - break; - case "EDITION_2023": - case 1000: - message.editionIntroduced = 1000; - break; - case "EDITION_2024": - case 1001: - message.editionIntroduced = 1001; - break; - case "EDITION_1_TEST_ONLY": - case 1: - message.editionIntroduced = 1; - break; - case "EDITION_2_TEST_ONLY": - case 2: - message.editionIntroduced = 2; - break; - case "EDITION_99997_TEST_ONLY": - case 99997: - message.editionIntroduced = 99997; - break; - case "EDITION_99998_TEST_ONLY": - case 99998: - message.editionIntroduced = 99998; - break; - case "EDITION_99999_TEST_ONLY": - case 99999: - message.editionIntroduced = 99999; - break; - case "EDITION_MAX": - case 2147483647: - message.editionIntroduced = 2147483647; - break; - } - switch (object.editionDeprecated) { - default: - if (typeof object.editionDeprecated === "number") { - message.editionDeprecated = object.editionDeprecated; - break; - } - break; - case "EDITION_UNKNOWN": - case 0: - message.editionDeprecated = 0; - break; - case "EDITION_LEGACY": - case 900: - message.editionDeprecated = 900; - break; - case "EDITION_PROTO2": - case 998: - message.editionDeprecated = 998; - break; - case "EDITION_PROTO3": - case 999: - message.editionDeprecated = 999; - break; - case "EDITION_2023": - case 1000: - message.editionDeprecated = 1000; - break; - case "EDITION_2024": - case 1001: - message.editionDeprecated = 1001; - break; - case "EDITION_1_TEST_ONLY": - case 1: - message.editionDeprecated = 1; - break; - case "EDITION_2_TEST_ONLY": - case 2: - message.editionDeprecated = 2; - break; - case "EDITION_99997_TEST_ONLY": - case 99997: - message.editionDeprecated = 99997; - break; - case "EDITION_99998_TEST_ONLY": - case 99998: - message.editionDeprecated = 99998; - break; - case "EDITION_99999_TEST_ONLY": - case 99999: - message.editionDeprecated = 99999; - break; - case "EDITION_MAX": - case 2147483647: - message.editionDeprecated = 2147483647; - break; - } - if (object.deprecationWarning != null) - message.deprecationWarning = String(object.deprecationWarning); - switch (object.editionRemoved) { - default: - if (typeof object.editionRemoved === "number") { - message.editionRemoved = object.editionRemoved; - break; - } - break; - case "EDITION_UNKNOWN": - case 0: - message.editionRemoved = 0; - break; - case "EDITION_LEGACY": - case 900: - message.editionRemoved = 900; - break; - case "EDITION_PROTO2": - case 998: - message.editionRemoved = 998; - break; - case "EDITION_PROTO3": - case 999: - message.editionRemoved = 999; - break; - case "EDITION_2023": - case 1000: - message.editionRemoved = 1000; - break; - case "EDITION_2024": - case 1001: - message.editionRemoved = 1001; - break; - case "EDITION_1_TEST_ONLY": - case 1: - message.editionRemoved = 1; - break; - case "EDITION_2_TEST_ONLY": - case 2: - message.editionRemoved = 2; - break; - case "EDITION_99997_TEST_ONLY": - case 99997: - message.editionRemoved = 99997; - break; - case "EDITION_99998_TEST_ONLY": - case 99998: - message.editionRemoved = 99998; - break; - case "EDITION_99999_TEST_ONLY": - case 99999: - message.editionRemoved = 99999; - break; - case "EDITION_MAX": - case 2147483647: - message.editionRemoved = 2147483647; - break; - } - return message; - }; - - /** - * Creates a plain object from a FeatureSupport message. Also converts values to other types if specified. - * @function toObject - * @memberof google.protobuf.FieldOptions.FeatureSupport - * @static - * @param {google.protobuf.FieldOptions.FeatureSupport} message FeatureSupport - * @param {$protobuf.IConversionOptions} [options] Conversion options - * @returns {Object.} Plain object - */ - FeatureSupport.toObject = function toObject(message, options) { - if (!options) - options = {}; - var object = {}; - if (options.defaults) { - object.editionIntroduced = options.enums === String ? "EDITION_UNKNOWN" : 0; - object.editionDeprecated = options.enums === String ? "EDITION_UNKNOWN" : 0; - object.deprecationWarning = ""; - object.editionRemoved = options.enums === String ? "EDITION_UNKNOWN" : 0; - } - if (message.editionIntroduced != null && message.hasOwnProperty("editionIntroduced")) - object.editionIntroduced = options.enums === String ? $root.google.protobuf.Edition[message.editionIntroduced] === undefined ? message.editionIntroduced : $root.google.protobuf.Edition[message.editionIntroduced] : message.editionIntroduced; - if (message.editionDeprecated != null && message.hasOwnProperty("editionDeprecated")) - object.editionDeprecated = options.enums === String ? $root.google.protobuf.Edition[message.editionDeprecated] === undefined ? message.editionDeprecated : $root.google.protobuf.Edition[message.editionDeprecated] : message.editionDeprecated; - if (message.deprecationWarning != null && message.hasOwnProperty("deprecationWarning")) - object.deprecationWarning = message.deprecationWarning; - if (message.editionRemoved != null && message.hasOwnProperty("editionRemoved")) - object.editionRemoved = options.enums === String ? $root.google.protobuf.Edition[message.editionRemoved] === undefined ? message.editionRemoved : $root.google.protobuf.Edition[message.editionRemoved] : message.editionRemoved; - return object; - }; - - /** - * Converts this FeatureSupport to JSON. - * @function toJSON - * @memberof google.protobuf.FieldOptions.FeatureSupport - * @instance - * @returns {Object.} JSON object - */ - FeatureSupport.prototype.toJSON = function toJSON() { - return this.constructor.toObject(this, $protobuf.util.toJSONOptions); - }; - - /** - * Gets the default type url for FeatureSupport - * @function getTypeUrl - * @memberof google.protobuf.FieldOptions.FeatureSupport - * @static - * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") - * @returns {string} The default type url - */ - FeatureSupport.getTypeUrl = function getTypeUrl(typeUrlPrefix) { - if (typeUrlPrefix === undefined) { - typeUrlPrefix = "type.googleapis.com"; - } - return typeUrlPrefix + "/google.protobuf.FieldOptions.FeatureSupport"; - }; - - return FeatureSupport; - })(); - return FieldOptions; })(); @@ -6776,10 +6446,6 @@ case 0: message.minimumEdition = 0; break; - case "EDITION_LEGACY": - case 900: - message.minimumEdition = 900; - break; case "EDITION_PROTO2": case 998: message.minimumEdition = 998; @@ -6832,10 +6498,6 @@ case 0: message.maximumEdition = 0; break; - case "EDITION_LEGACY": - case 900: - message.maximumEdition = 900; - break; case "EDITION_PROTO2": case 998: message.maximumEdition = 998; @@ -6944,8 +6606,7 @@ * @memberof google.protobuf.FeatureSetDefaults * @interface IFeatureSetEditionDefault * @property {google.protobuf.Edition|null} [edition] FeatureSetEditionDefault edition - * @property {google.protobuf.IFeatureSet|null} [overridableFeatures] FeatureSetEditionDefault overridableFeatures - * @property {google.protobuf.IFeatureSet|null} [fixedFeatures] FeatureSetEditionDefault fixedFeatures + * @property {google.protobuf.IFeatureSet|null} [features] FeatureSetEditionDefault features */ /** @@ -6972,20 +6633,12 @@ FeatureSetEditionDefault.prototype.edition = 0; /** - * FeatureSetEditionDefault overridableFeatures. - * @member {google.protobuf.IFeatureSet|null|undefined} overridableFeatures + * FeatureSetEditionDefault features. + * @member {google.protobuf.IFeatureSet|null|undefined} features * @memberof google.protobuf.FeatureSetDefaults.FeatureSetEditionDefault * @instance */ - FeatureSetEditionDefault.prototype.overridableFeatures = null; - - /** - * FeatureSetEditionDefault fixedFeatures. - * @member {google.protobuf.IFeatureSet|null|undefined} fixedFeatures - * @memberof google.protobuf.FeatureSetDefaults.FeatureSetEditionDefault - * @instance - */ - FeatureSetEditionDefault.prototype.fixedFeatures = null; + FeatureSetEditionDefault.prototype.features = null; /** * Creates a FeatureSetEditionDefault message from a plain object. Also converts values to their respective internal types. @@ -7010,10 +6663,6 @@ case 0: message.edition = 0; break; - case "EDITION_LEGACY": - case 900: - message.edition = 900; - break; case "EDITION_PROTO2": case 998: message.edition = 998; @@ -7055,15 +6704,10 @@ message.edition = 2147483647; break; } - if (object.overridableFeatures != null) { - if (typeof object.overridableFeatures !== "object") - throw TypeError(".google.protobuf.FeatureSetDefaults.FeatureSetEditionDefault.overridableFeatures: object expected"); - message.overridableFeatures = $root.google.protobuf.FeatureSet.fromObject(object.overridableFeatures); - } - if (object.fixedFeatures != null) { - if (typeof object.fixedFeatures !== "object") - throw TypeError(".google.protobuf.FeatureSetDefaults.FeatureSetEditionDefault.fixedFeatures: object expected"); - message.fixedFeatures = $root.google.protobuf.FeatureSet.fromObject(object.fixedFeatures); + if (object.features != null) { + if (typeof object.features !== "object") + throw TypeError(".google.protobuf.FeatureSetDefaults.FeatureSetEditionDefault.features: object expected"); + message.features = $root.google.protobuf.FeatureSet.fromObject(object.features); } return message; }; @@ -7082,16 +6726,13 @@ options = {}; var object = {}; if (options.defaults) { + object.features = null; object.edition = options.enums === String ? "EDITION_UNKNOWN" : 0; - object.overridableFeatures = null; - object.fixedFeatures = null; } + if (message.features != null && message.hasOwnProperty("features")) + object.features = $root.google.protobuf.FeatureSet.toObject(message.features, options); if (message.edition != null && message.hasOwnProperty("edition")) object.edition = options.enums === String ? $root.google.protobuf.Edition[message.edition] === undefined ? message.edition : $root.google.protobuf.Edition[message.edition] : message.edition; - if (message.overridableFeatures != null && message.hasOwnProperty("overridableFeatures")) - object.overridableFeatures = $root.google.protobuf.FeatureSet.toObject(message.overridableFeatures, options); - if (message.fixedFeatures != null && message.hasOwnProperty("fixedFeatures")) - object.fixedFeatures = $root.google.protobuf.FeatureSet.toObject(message.fixedFeatures, options); return object; }; diff --git a/dev/protos/google/api/client.proto b/dev/protos/google/api/client.proto index 3a5f9290f..7f6ef41f5 100644 --- a/dev/protos/google/api/client.proto +++ b/dev/protos/google/api/client.proto @@ -349,6 +349,13 @@ message MethodSettings { // The fully qualified name of the method, for which the options below apply. // This is used to find the method to apply the options. + // + // Example: + // + // publishing: + // method_settings: + // - selector: google.storage.control.v2.StorageControl.CreateFolder + // # method settings for CreateFolder... string selector = 1; // Describes settings to use for long-running operations when generating @@ -357,17 +364,14 @@ message MethodSettings { // // Example of a YAML configuration:: // - // publishing: - // method_settings: + // publishing: + // method_settings: // - selector: google.cloud.speech.v2.Speech.BatchRecognize // long_running: - // initial_poll_delay: - // seconds: 60 # 1 minute + // initial_poll_delay: 60s # 1 minute // poll_delay_multiplier: 1.5 - // max_poll_delay: - // seconds: 360 # 6 minutes - // total_poll_timeout: - // seconds: 54000 # 90 minutes + // max_poll_delay: 360s # 6 minutes + // total_poll_timeout: 54000s # 90 minutes LongRunning long_running = 2; // List of top-level fields of the request message, that should be @@ -376,8 +380,8 @@ message MethodSettings { // // Example of a YAML configuration: // - // publishing: - // method_settings: + // publishing: + // method_settings: // - selector: google.example.v1.ExampleService.CreateExample // auto_populated_fields: // - request_id diff --git a/dev/protos/google/api/http.proto b/dev/protos/google/api/http.proto index afa00aede..e3270371d 100644 --- a/dev/protos/google/api/http.proto +++ b/dev/protos/google/api/http.proto @@ -41,7 +41,7 @@ message Http { bool fully_decode_reserved_expansion = 2; } -// # gRPC Transcoding +// gRPC Transcoding // // gRPC Transcoding is a feature for mapping between a gRPC method and one or // more HTTP REST endpoints. It allows developers to build a single API service @@ -82,9 +82,8 @@ message Http { // // This enables an HTTP REST to gRPC mapping as below: // -// HTTP | gRPC -// -----|----- -// `GET /v1/messages/123456` | `GetMessage(name: "messages/123456")` +// - HTTP: `GET /v1/messages/123456` +// - gRPC: `GetMessage(name: "messages/123456")` // // Any fields in the request message which are not bound by the path template // automatically become HTTP query parameters if there is no HTTP request body. @@ -108,11 +107,9 @@ message Http { // // This enables a HTTP JSON to RPC mapping as below: // -// HTTP | gRPC -// -----|----- -// `GET /v1/messages/123456?revision=2&sub.subfield=foo` | -// `GetMessage(message_id: "123456" revision: 2 sub: SubMessage(subfield: -// "foo"))` +// - HTTP: `GET /v1/messages/123456?revision=2&sub.subfield=foo` +// - gRPC: `GetMessage(message_id: "123456" revision: 2 sub: +// SubMessage(subfield: "foo"))` // // Note that fields which are mapped to URL query parameters must have a // primitive type or a repeated primitive type or a non-repeated message type. @@ -142,10 +139,8 @@ message Http { // representation of the JSON in the request body is determined by // protos JSON encoding: // -// HTTP | gRPC -// -----|----- -// `PATCH /v1/messages/123456 { "text": "Hi!" }` | `UpdateMessage(message_id: -// "123456" message { text: "Hi!" })` +// - HTTP: `PATCH /v1/messages/123456 { "text": "Hi!" }` +// - gRPC: `UpdateMessage(message_id: "123456" message { text: "Hi!" })` // // The special name `*` can be used in the body mapping to define that // every field not bound by the path template should be mapped to the @@ -168,10 +163,8 @@ message Http { // // The following HTTP JSON to RPC mapping is enabled: // -// HTTP | gRPC -// -----|----- -// `PATCH /v1/messages/123456 { "text": "Hi!" }` | `UpdateMessage(message_id: -// "123456" text: "Hi!")` +// - HTTP: `PATCH /v1/messages/123456 { "text": "Hi!" }` +// - gRPC: `UpdateMessage(message_id: "123456" text: "Hi!")` // // Note that when using `*` in the body mapping, it is not possible to // have HTTP parameters, as all fields not bound by the path end in @@ -199,13 +192,13 @@ message Http { // // This enables the following two alternative HTTP JSON to RPC mappings: // -// HTTP | gRPC -// -----|----- -// `GET /v1/messages/123456` | `GetMessage(message_id: "123456")` -// `GET /v1/users/me/messages/123456` | `GetMessage(user_id: "me" message_id: -// "123456")` +// - HTTP: `GET /v1/messages/123456` +// - gRPC: `GetMessage(message_id: "123456")` // -// ## Rules for HTTP mapping +// - HTTP: `GET /v1/users/me/messages/123456` +// - gRPC: `GetMessage(user_id: "me" message_id: "123456")` +// +// Rules for HTTP mapping // // 1. Leaf request fields (recursive expansion nested messages in the request // message) are classified into three categories: @@ -224,7 +217,7 @@ message Http { // request body, all // fields are passed via URL path and URL query parameters. // -// ### Path template syntax +// Path template syntax // // Template = "/" Segments [ Verb ] ; // Segments = Segment { "/" Segment } ; @@ -263,7 +256,7 @@ message Http { // Document](https://developers.google.com/discovery/v1/reference/apis) as // `{+var}`. // -// ## Using gRPC API Service Configuration +// Using gRPC API Service Configuration // // gRPC API Service Configuration (service config) is a configuration language // for configuring a gRPC service to become a user-facing product. The @@ -278,15 +271,14 @@ message Http { // specified in the service config will override any matching transcoding // configuration in the proto. // -// Example: +// The following example selects a gRPC method and applies an `HttpRule` to it: // // http: // rules: -// # Selects a gRPC method and applies HttpRule to it. // - selector: example.v1.Messaging.GetMessage // get: /v1/messages/{message_id}/{sub.subfield} // -// ## Special notes +// Special notes // // When gRPC Transcoding is used to map a gRPC to JSON REST endpoints, the // proto to JSON conversion must follow the [proto3 diff --git a/dev/protos/google/api/resource.proto b/dev/protos/google/api/resource.proto index f17520d20..3762af84a 100644 --- a/dev/protos/google/api/resource.proto +++ b/dev/protos/google/api/resource.proto @@ -179,8 +179,13 @@ message ResourceDescriptor { // The plural name used in the resource name and permission names, such as // 'projects' for the resource name of 'projects/{project}' and the permission - // name of 'cloudresourcemanager.googleapis.com/projects.get'. It is the same - // concept of the `plural` field in k8s CRD spec + // name of 'cloudresourcemanager.googleapis.com/projects.get'. One exception + // to this is for Nested Collections that have stuttering names, as defined + // in [AIP-122](https://google.aip.dev/122#nested-collections), where the + // collection ID in the resource name pattern does not necessarily directly + // match the `plural` value. + // + // It is the same concept of the `plural` field in k8s CRD spec // https://kubernetes.io/docs/tasks/access-kubernetes-api/custom-resources/custom-resource-definitions/ // // Note: The plural form is required even for singleton resources. See diff --git a/dev/protos/google/firestore/admin/v1/field.proto b/dev/protos/google/firestore/admin/v1/field.proto index 930f91146..eefee763c 100644 --- a/dev/protos/google/firestore/admin/v1/field.proto +++ b/dev/protos/google/firestore/admin/v1/field.proto @@ -49,8 +49,8 @@ message Field { // When false, the `Field`'s index configuration is defined explicitly. bool uses_ancestor_config = 2; - // Output only. Specifies the resource name of the `Field` from which this field's - // index configuration is set (when `uses_ancestor_config` is true), + // Output only. Specifies the resource name of the `Field` from which this + // field's index configuration is set (when `uses_ancestor_config` is true), // or from which it *would* be set if this field had no index configuration // (when `uses_ancestor_config` is false). string ancestor_field = 3; @@ -65,9 +65,12 @@ message Field { // The TTL (time-to-live) configuration for documents that have this `Field` // set. + // // Storing a timestamp value into a TTL-enabled field will be treated as - // the document's absolute expiration time. Using any other data type or - // leaving the field absent will disable the TTL for the individual document. + // the document's absolute expiration time. Timestamp values in the past + // indicate that the document is eligible for immediate expiration. Using any + // other data type or leaving the field absent will disable expiration for the + // individual document. message TtlConfig { // The state of applying the TTL configuration to all documents. enum State { @@ -95,26 +98,24 @@ message Field { State state = 1 [(google.api.field_behavior) = OUTPUT_ONLY]; } - // Required. A field name of the form + // Required. A field name of the form: // `projects/{project_id}/databases/{database_id}/collectionGroups/{collection_id}/fields/{field_path}` // - // A field path may be a simple field name, e.g. `address` or a path to fields - // within map_value , e.g. `address.city`, + // A field path can be a simple field name, e.g. `address` or a path to fields + // within `map_value` , e.g. `address.city`, // or a special field path. The only valid special field is `*`, which // represents any field. // - // Field paths may be quoted using ` (backtick). The only character that needs - // to be escaped within a quoted field path is the backtick character itself, - // escaped using a backslash. Special characters in field paths that + // Field paths can be quoted using `` ` `` (backtick). The only character that + // must be escaped within a quoted field path is the backtick character + // itself, escaped using a backslash. Special characters in field paths that // must be quoted include: `*`, `.`, - // ``` (backtick), `[`, `]`, as well as any ascii symbolic characters. + // `` ` `` (backtick), `[`, `]`, as well as any ascii symbolic characters. // // Examples: - // (Note: Comments here are written in markdown syntax, so there is an - // additional layer of backticks to represent a code block) - // `\`address.city\`` represents a field named `address.city`, not the map key - // `city` in the field `address`. - // `\`*\`` represents a field named `*`, not any field. + // `` `address.city` `` represents a field named `address.city`, not the map + // key `city` in the field `address`. `` `*` `` represents a field named `*`, + // not any field. // // A special `Field` contains the default indexing settings for all fields. // This field's resource name is: diff --git a/dev/protos/google/firestore/admin/v1/firestore_admin.proto b/dev/protos/google/firestore/admin/v1/firestore_admin.proto index 2a19b4fea..dd95c2ce7 100644 --- a/dev/protos/google/firestore/admin/v1/firestore_admin.proto +++ b/dev/protos/google/firestore/admin/v1/firestore_admin.proto @@ -217,6 +217,27 @@ service FirestoreAdmin { }; } + // Bulk deletes a subset of documents from Google Cloud Firestore. + // Documents created or updated after the underlying system starts to process + // the request will not be deleted. The bulk delete occurs in the background + // and its progress can be monitored and managed via the Operation resource + // that is created. + // + // For more details on bulk delete behavior, refer to: + // https://cloud.google.com/firestore/docs/manage-data/bulk-delete + rpc BulkDeleteDocuments(BulkDeleteDocumentsRequest) + returns (google.longrunning.Operation) { + option (google.api.http) = { + post: "/v1/{name=projects/*/databases/*}:bulkDeleteDocuments" + body: "*" + }; + option (google.api.method_signature) = "name"; + option (google.longrunning.operation_info) = { + response_type: "BulkDeleteDocumentsResponse" + metadata_type: "BulkDeleteDocumentsMetadata" + }; + } + // Create a database. rpc CreateDatabase(CreateDatabaseRequest) returns (google.longrunning.Operation) { @@ -302,7 +323,7 @@ service FirestoreAdmin { // // The new database must be in the same cloud region or multi-region location // as the existing backup. This behaves similar to - // [FirestoreAdmin.CreateDatabase][google.firestore.admin.v1.CreateDatabase] + // [FirestoreAdmin.CreateDatabase][google.firestore.admin.v1.FirestoreAdmin.CreateDatabase] // except instead of creating a new empty database, a new database is created // with the database type, index configuration, and documents from an existing // backup. @@ -386,6 +407,9 @@ message ListDatabasesRequest { child_type: "firestore.googleapis.com/Database" } ]; + + // If true, also returns deleted resources. + bool show_deleted = 4; } // The request for @@ -670,7 +694,8 @@ message ListFieldsRequest { // only supports listing fields that have been explicitly overridden. To issue // this query, call // [FirestoreAdmin.ListFields][google.firestore.admin.v1.FirestoreAdmin.ListFields] - // with a filter that includes `indexConfig.usesAncestorConfig:false` . + // with a filter that includes `indexConfig.usesAncestorConfig:false` or + // `ttlConfig:*`. string filter = 2; // The number of results to return. @@ -705,7 +730,8 @@ message ExportDocumentsRequest { } ]; - // Which collection ids to export. Unspecified means all collections. + // Which collection ids to export. Unspecified means all collections. Each + // collection id in this list must be unique. repeated string collection_ids = 2; // The output URI. Currently only supports Google Cloud Storage URIs of the @@ -749,7 +775,7 @@ message ImportDocumentsRequest { ]; // Which collection ids to import. Unspecified means all collections included - // in the import. + // in the import. Each collection id in this list must be unique. repeated string collection_ids = 2; // Location of the exported files. @@ -768,6 +794,49 @@ message ImportDocumentsRequest { repeated string namespace_ids = 4; } +// The request for +// [FirestoreAdmin.BulkDeleteDocuments][google.firestore.admin.v1.FirestoreAdmin.BulkDeleteDocuments]. +// +// When both collection_ids and namespace_ids are set, only documents satisfying +// both conditions will be deleted. +// +// Requests with namespace_ids and collection_ids both empty will be rejected. +// Please use +// [FirestoreAdmin.DeleteDatabase][google.firestore.admin.v1.FirestoreAdmin.DeleteDatabase] +// instead. +message BulkDeleteDocumentsRequest { + // Required. Database to operate. Should be of the form: + // `projects/{project_id}/databases/{database_id}`. + string name = 1 [ + (google.api.field_behavior) = REQUIRED, + (google.api.resource_reference) = { + type: "firestore.googleapis.com/Database" + } + ]; + + // Optional. IDs of the collection groups to delete. Unspecified means all + // collection groups. + // + // Each collection group in this list must be unique. + repeated string collection_ids = 2 [(google.api.field_behavior) = OPTIONAL]; + + // Optional. Namespaces to delete. + // + // An empty list means all namespaces. This is the recommended + // usage for databases that don't use namespaces. + // + // An empty string element represents the default namespace. This should be + // used if the database has data in non-default namespaces, but doesn't want + // to delete from them. + // + // Each namespace in this list must be unique. + repeated string namespace_ids = 3 [(google.api.field_behavior) = OPTIONAL]; +} + +// The response for +// [FirestoreAdmin.BulkDeleteDocuments][google.firestore.admin.v1.FirestoreAdmin.BulkDeleteDocuments]. +message BulkDeleteDocumentsResponse {} + // The request for // [FirestoreAdmin.GetBackup][google.firestore.admin.v1.FirestoreAdmin.GetBackup]. message GetBackupRequest { diff --git a/dev/protos/google/firestore/admin/v1/index.proto b/dev/protos/google/firestore/admin/v1/index.proto index 2eec079d3..f2a3cc373 100644 --- a/dev/protos/google/firestore/admin/v1/index.proto +++ b/dev/protos/google/firestore/admin/v1/index.proto @@ -126,7 +126,7 @@ message Index { // Indicates that this field supports operations on `array_value`s. ArrayConfig array_config = 3; - // Indicates that this field supports nearest neighbors and distance + // Indicates that this field supports nearest neighbor and distance // operations on vector. VectorConfig vector_config = 4; } diff --git a/dev/protos/google/firestore/admin/v1/operation.proto b/dev/protos/google/firestore/admin/v1/operation.proto index 1087e8cfc..80b133764 100644 --- a/dev/protos/google/firestore/admin/v1/operation.proto +++ b/dev/protos/google/firestore/admin/v1/operation.proto @@ -191,6 +191,39 @@ message ImportDocumentsMetadata { repeated string namespace_ids = 8; } +// Metadata for [google.longrunning.Operation][google.longrunning.Operation] +// results from +// [FirestoreAdmin.BulkDeleteDocuments][google.firestore.admin.v1.FirestoreAdmin.BulkDeleteDocuments]. +message BulkDeleteDocumentsMetadata { + // The time this operation started. + google.protobuf.Timestamp start_time = 1; + + // The time this operation completed. Will be unset if operation still in + // progress. + google.protobuf.Timestamp end_time = 2; + + // The state of the operation. + OperationState operation_state = 3; + + // The progress, in documents, of this operation. + Progress progress_documents = 4; + + // The progress, in bytes, of this operation. + Progress progress_bytes = 5; + + // The ids of the collection groups that are being deleted. + repeated string collection_ids = 6; + + // Which namespace ids are being deleted. + repeated string namespace_ids = 7; + + // The timestamp that corresponds to the version of the database that is being + // read to get the list of documents to delete. This time can also be used as + // the timestamp of PITR in case of disaster recovery (subject to PITR window + // limit). + google.protobuf.Timestamp snapshot_time = 8; +} + // Returned in the [google.longrunning.Operation][google.longrunning.Operation] // response field. message ExportDocumentsResponse { diff --git a/dev/protos/google/firestore/v1/document.proto b/dev/protos/google/firestore/v1/document.proto index 5348fe643..9947a289a 100644 --- a/dev/protos/google/firestore/v1/document.proto +++ b/dev/protos/google/firestore/v1/document.proto @@ -16,6 +16,7 @@ syntax = "proto3"; package google.firestore.v1; +import "google/api/field_behavior.proto"; import "google/protobuf/struct.proto"; import "google/protobuf/timestamp.proto"; import "google/type/latlng.proto"; @@ -122,7 +123,7 @@ message Value { // An array value. // - // Cannot directly contain another array value, though can contain an + // Cannot directly contain another array value, though can contain a // map which contains another array. ArrayValue array_value = 9; diff --git a/dev/protos/google/firestore/v1/query.proto b/dev/protos/google/firestore/v1/query.proto index f0fda1832..3b2280076 100644 --- a/dev/protos/google/firestore/v1/query.proto +++ b/dev/protos/google/firestore/v1/query.proto @@ -263,7 +263,10 @@ message StructuredQuery { repeated FieldReference fields = 2; } - // Nearest Neighbors search config. + // Nearest Neighbors search config. The ordering provided by FindNearest + // supersedes the order_by stage. If multiple documents have the same vector + // distance, the returned document order is not guaranteed to be stable + // between queries. message FindNearest { // The distance measure to use when comparing vectors. enum DistanceMeasure { @@ -272,20 +275,23 @@ message StructuredQuery { // Measures the EUCLIDEAN distance between the vectors. See // [Euclidean](https://en.wikipedia.org/wiki/Euclidean_distance) to learn - // more + // more. The resulting distance decreases the more similar two vectors + // are. EUCLIDEAN = 1; - // Compares vectors based on the angle between them, which allows you to - // measure similarity that isn't based on the vectors magnitude. - // We recommend using DOT_PRODUCT with unit normalized vectors instead of - // COSINE distance, which is mathematically equivalent with better - // performance. See [Cosine + // COSINE distance compares vectors based on the angle between them, which + // allows you to measure similarity that isn't based on the vectors + // magnitude. We recommend using DOT_PRODUCT with unit normalized vectors + // instead of COSINE distance, which is mathematically equivalent with + // better performance. See [Cosine // Similarity](https://en.wikipedia.org/wiki/Cosine_similarity) to learn - // more. + // more about COSINE similarity and COSINE distance. The resulting + // COSINE distance decreases the more similar two vectors are. COSINE = 2; // Similar to cosine but is affected by the magnitude of the vectors. See // [Dot Product](https://en.wikipedia.org/wiki/Dot_product) to learn more. + // The resulting distance increases the more similar two vectors are. DOT_PRODUCT = 3; } @@ -298,7 +304,7 @@ message StructuredQuery { // no more than 2048 dimensions. Value query_vector = 2 [(google.api.field_behavior) = REQUIRED]; - // Required. The Distance Measure to use, required. + // Required. The distance measure to use, required. DistanceMeasure distance_measure = 3 [(google.api.field_behavior) = REQUIRED]; @@ -306,6 +312,22 @@ message StructuredQuery { // integer of no more than 1000. google.protobuf.Int32Value limit = 4 [(google.api.field_behavior) = REQUIRED]; + + // Optional. Optional name of the field to output the result of the vector + // distance calculation. Must conform to [document field + // name][google.firestore.v1.Document.fields] limitations. + string distance_result_field = 5 [(google.api.field_behavior) = OPTIONAL]; + + // Optional. Option to specify a threshold for which no less similar + // documents will be returned. The behavior of the specified + // `distance_measure` will affect the meaning of the distance threshold. + // Since DOT_PRODUCT distances increase when the vectors are more similar, + // the comparison is inverted. + // + // For EUCLIDEAN, COSINE: WHERE distance <= distance_threshold + // For DOT_PRODUCT: WHERE distance >= distance_threshold + google.protobuf.DoubleValue distance_threshold = 6 + [(google.api.field_behavior) = OPTIONAL]; } // Optional sub-set of the fields to return. @@ -406,7 +428,7 @@ message StructuredQuery { // * The value must be greater than or equal to zero if specified. google.protobuf.Int32Value limit = 5; - // Optional. A potential Nearest Neighbors Search. + // Optional. A potential nearest neighbors search. // // Applies after all other filters and ordering. // diff --git a/dev/protos/google/protobuf/descriptor.proto b/dev/protos/google/protobuf/descriptor.proto index b4a62d3ef..8f619e85c 100644 --- a/dev/protos/google/protobuf/descriptor.proto +++ b/dev/protos/google/protobuf/descriptor.proto @@ -62,10 +62,6 @@ enum Edition { // A placeholder for an unknown edition value. EDITION_UNKNOWN = 0; - // A placeholder edition for specifying default behaviors *before* a feature - // was first introduced. This is effectively an "infinite past". - EDITION_LEGACY = 900; - // Legacy syntax "editions". These pre-date editions, but behave much like // distinct editions. These can't be used to specify the edition of proto // files, but feature definitions must supply proto2/proto3 defaults for @@ -452,16 +448,12 @@ message FileOptions { // This option does nothing. optional bool java_generate_equals_and_hash = 20 [deprecated=true]; - // A proto2 file can set this to true to opt in to UTF-8 checking for Java, - // which will throw an exception if invalid UTF-8 is parsed from the wire or - // assigned to a string field. - // - // TODO: clarify exactly what kinds of field types this option - // applies to, and update these docs accordingly. - // - // Proto3 files already perform these checks. Setting the option explicitly to - // false has no effect: it cannot be used to opt proto3 files out of UTF-8 - // checks. + // If set true, then the Java2 code generator will generate code that + // throws an exception whenever an attempt is made to assign a non-UTF-8 + // byte sequence to a string field. + // Message reflection will do the same. + // However, an extension field still accepts non-UTF-8 byte sequences. + // This option has no effect on when used with the lite runtime. optional bool java_string_check_utf8 = 27 [default = false]; // Generated classes can be optimized for speed or code size. @@ -768,28 +760,6 @@ message FieldOptions { // Any features defined in the specific edition. optional FeatureSet features = 21; - // Information about the support window of a feature. - message FeatureSupport { - // The edition that this feature was first available in. In editions - // earlier than this one, the default assigned to EDITION_LEGACY will be - // used, and proto files will not be able to override it. - optional Edition edition_introduced = 1; - - // The edition this feature becomes deprecated in. Using this after this - // edition may trigger warnings. - optional Edition edition_deprecated = 2; - - // The deprecation warning text if this feature is used after the edition it - // was marked deprecated in. - optional string deprecation_warning = 3; - - // The edition this feature is no longer available in. In editions after - // this one, the last default assigned will be used, and proto files will - // not be able to override it. - optional Edition edition_removed = 4; - } - optional FeatureSupport feature_support = 22; - // The parser stores options it doesn't recognize here. See above. repeated UninterpretedOption uninterpreted_option = 999; @@ -970,10 +940,6 @@ message FeatureSet { retention = RETENTION_RUNTIME, targets = TARGET_TYPE_FIELD, targets = TARGET_TYPE_FILE, - // TODO Enable this in google3 once protoc rolls out. - feature_support = { - edition_introduced: EDITION_2023, - }, edition_defaults = { edition: EDITION_PROTO2, value: "EXPLICIT" }, edition_defaults = { edition: EDITION_PROTO3, value: "IMPLICIT" }, edition_defaults = { edition: EDITION_2023, value: "EXPLICIT" } @@ -988,10 +954,6 @@ message FeatureSet { retention = RETENTION_RUNTIME, targets = TARGET_TYPE_ENUM, targets = TARGET_TYPE_FILE, - // TODO Enable this in google3 once protoc rolls out. - feature_support = { - edition_introduced: EDITION_2023, - }, edition_defaults = { edition: EDITION_PROTO2, value: "CLOSED" }, edition_defaults = { edition: EDITION_PROTO3, value: "OPEN" } ]; @@ -1005,10 +967,6 @@ message FeatureSet { retention = RETENTION_RUNTIME, targets = TARGET_TYPE_FIELD, targets = TARGET_TYPE_FILE, - // TODO Enable this in google3 once protoc rolls out. - feature_support = { - edition_introduced: EDITION_2023, - }, edition_defaults = { edition: EDITION_PROTO2, value: "EXPANDED" }, edition_defaults = { edition: EDITION_PROTO3, value: "PACKED" } ]; @@ -1022,10 +980,6 @@ message FeatureSet { retention = RETENTION_RUNTIME, targets = TARGET_TYPE_FIELD, targets = TARGET_TYPE_FILE, - // TODO Enable this in google3 once protoc rolls out. - feature_support = { - edition_introduced: EDITION_2023, - }, edition_defaults = { edition: EDITION_PROTO2, value: "NONE" }, edition_defaults = { edition: EDITION_PROTO3, value: "VERIFY" } ]; @@ -1039,10 +993,6 @@ message FeatureSet { retention = RETENTION_RUNTIME, targets = TARGET_TYPE_FIELD, targets = TARGET_TYPE_FILE, - // TODO Enable this in google3 once protoc rolls out. - feature_support = { - edition_introduced: EDITION_2023, - }, edition_defaults = { edition: EDITION_PROTO2, value: "LENGTH_PREFIXED" } ]; @@ -1056,34 +1006,15 @@ message FeatureSet { targets = TARGET_TYPE_MESSAGE, targets = TARGET_TYPE_ENUM, targets = TARGET_TYPE_FILE, - // TODO Enable this in google3 once protoc rolls out. - feature_support = { - edition_introduced: EDITION_2023, - }, edition_defaults = { edition: EDITION_PROTO2, value: "LEGACY_BEST_EFFORT" }, edition_defaults = { edition: EDITION_PROTO3, value: "ALLOW" } ]; reserved 999; - extensions 1000 to 9994 [ - declaration = { - number: 1000, - full_name: ".pb.cpp", - type: ".pb.CppFeatures" - }, - declaration = { - number: 1001, - full_name: ".pb.java", - type: ".pb.JavaFeatures" - }, - declaration = { number: 1002, full_name: ".pb.go", type: ".pb.GoFeatures" }, - declaration = { - number: 9990, - full_name: ".pb.proto1", - type: ".pb.Proto1Features" - } - ]; + extensions 1000; // for Protobuf C++ + extensions 1001; // for Protobuf Java + extensions 1002; // for Protobuf Go extensions 9995 to 9999; // For internal testing extensions 10000; // for https://github.com/bufbuild/protobuf-es @@ -1100,12 +1031,7 @@ message FeatureSetDefaults { // be used. This field must be in strict ascending order by edition. message FeatureSetEditionDefault { optional Edition edition = 3; - - // Defaults of features that can be overridden in this edition. - optional FeatureSet overridable_features = 4; - - // Defaults of features that can't be overridden in this edition. - optional FeatureSet fixed_features = 5; + optional FeatureSet features = 2; } repeated FeatureSetEditionDefault defaults = 1; diff --git a/dev/protos/update.sh b/dev/protos/update.sh index a2cf11a12..028d8fdd0 100755 --- a/dev/protos/update.sh +++ b/dev/protos/update.sh @@ -42,7 +42,9 @@ pushd "$WORK_DIR" # Clone necessary git repos. git clone --depth 1 https://github.com/googleapis/googleapis.git -git clone --depth 1 https://github.com/google/protobuf.git +# Protobuf may have breaking changes, so it will be pinned to a specific release. +# TODO(version) nodejs-firestore should maintain the version number of protobuf manually +git clone --single-branch --branch v26.1 --depth 1 https://github.com/google/protobuf.git # Copy necessary protos. mkdir -p "${PROTOS_DIR}/google/api" diff --git a/dev/protos/v1.json b/dev/protos/v1.json index 35e6ad599..66e151234 100644 --- a/dev/protos/v1.json +++ b/dev/protos/v1.json @@ -2,2365 +2,2094 @@ "nested": { "google": { "nested": { - "protobuf": { - "options": { - "go_package": "google.golang.org/protobuf/types/descriptorpb", - "java_package": "com.google.protobuf", - "java_outer_classname": "DescriptorProtos", - "csharp_namespace": "Google.Protobuf.Reflection", - "objc_class_prefix": "GPB", - "cc_enable_arenas": true, - "optimize_for": "SPEED" - }, + "firestore": { "nested": { - "Struct": { - "fields": { - "fields": { - "keyType": "string", - "type": "Value", - "id": 1 - } - } - }, - "Value": { - "oneofs": { - "kind": { - "oneof": [ - "nullValue", - "numberValue", - "stringValue", - "boolValue", - "structValue", - "listValue" - ] - } - }, - "fields": { - "nullValue": { - "type": "NullValue", - "id": 1 - }, - "numberValue": { - "type": "double", - "id": 2 - }, - "stringValue": { - "type": "string", - "id": 3 - }, - "boolValue": { - "type": "bool", - "id": 4 - }, - "structValue": { - "type": "Struct", - "id": 5 - }, - "listValue": { - "type": "ListValue", - "id": 6 - } - } - }, - "NullValue": { - "values": { - "NULL_VALUE": 0 - } - }, - "ListValue": { - "fields": { - "values": { - "rule": "repeated", - "type": "Value", - "id": 1 - } - } - }, - "Timestamp": { - "fields": { - "seconds": { - "type": "int64", - "id": 1 - }, - "nanos": { - "type": "int32", - "id": 2 - } - } - }, - "FileDescriptorSet": { - "fields": { - "file": { - "rule": "repeated", - "type": "FileDescriptorProto", - "id": 1 - } - } - }, - "Edition": { - "values": { - "EDITION_UNKNOWN": 0, - "EDITION_LEGACY": 900, - "EDITION_PROTO2": 998, - "EDITION_PROTO3": 999, - "EDITION_2023": 1000, - "EDITION_2024": 1001, - "EDITION_1_TEST_ONLY": 1, - "EDITION_2_TEST_ONLY": 2, - "EDITION_99997_TEST_ONLY": 99997, - "EDITION_99998_TEST_ONLY": 99998, - "EDITION_99999_TEST_ONLY": 99999, - "EDITION_MAX": 2147483647 - } - }, - "FileDescriptorProto": { - "fields": { - "name": { - "type": "string", - "id": 1 - }, - "package": { - "type": "string", - "id": 2 - }, - "dependency": { - "rule": "repeated", - "type": "string", - "id": 3 - }, - "publicDependency": { - "rule": "repeated", - "type": "int32", - "id": 10, - "options": { - "packed": false - } - }, - "weakDependency": { - "rule": "repeated", - "type": "int32", - "id": 11, - "options": { - "packed": false - } - }, - "messageType": { - "rule": "repeated", - "type": "DescriptorProto", - "id": 4 - }, - "enumType": { - "rule": "repeated", - "type": "EnumDescriptorProto", - "id": 5 - }, - "service": { - "rule": "repeated", - "type": "ServiceDescriptorProto", - "id": 6 - }, - "extension": { - "rule": "repeated", - "type": "FieldDescriptorProto", - "id": 7 - }, - "options": { - "type": "FileOptions", - "id": 8 - }, - "sourceCodeInfo": { - "type": "SourceCodeInfo", - "id": 9 - }, - "syntax": { - "type": "string", - "id": 12 - }, - "edition": { - "type": "Edition", - "id": 14 - } - } - }, - "DescriptorProto": { - "fields": { - "name": { - "type": "string", - "id": 1 - }, - "field": { - "rule": "repeated", - "type": "FieldDescriptorProto", - "id": 2 - }, - "extension": { - "rule": "repeated", - "type": "FieldDescriptorProto", - "id": 6 - }, - "nestedType": { - "rule": "repeated", - "type": "DescriptorProto", - "id": 3 - }, - "enumType": { - "rule": "repeated", - "type": "EnumDescriptorProto", - "id": 4 - }, - "extensionRange": { - "rule": "repeated", - "type": "ExtensionRange", - "id": 5 - }, - "oneofDecl": { - "rule": "repeated", - "type": "OneofDescriptorProto", - "id": 8 - }, - "options": { - "type": "MessageOptions", - "id": 7 - }, - "reservedRange": { - "rule": "repeated", - "type": "ReservedRange", - "id": 9 - }, - "reservedName": { - "rule": "repeated", - "type": "string", - "id": 10 - } + "v1": { + "options": { + "csharp_namespace": "Google.Cloud.Firestore.V1", + "go_package": "cloud.google.com/go/firestore/apiv1/firestorepb;firestorepb", + "java_multiple_files": true, + "java_outer_classname": "WriteProto", + "java_package": "com.google.firestore.v1", + "objc_class_prefix": "GCFS", + "php_namespace": "Google\\Cloud\\Firestore\\V1", + "ruby_package": "Google::Cloud::Firestore::V1" }, "nested": { - "ExtensionRange": { + "AggregationResult": { "fields": { - "start": { - "type": "int32", - "id": 1 - }, - "end": { - "type": "int32", + "aggregateFields": { + "keyType": "string", + "type": "Value", "id": 2 - }, - "options": { - "type": "ExtensionRangeOptions", - "id": 3 } } }, - "ReservedRange": { + "Document": { "fields": { - "start": { - "type": "int32", + "name": { + "type": "string", "id": 1 }, - "end": { - "type": "int32", + "fields": { + "keyType": "string", + "type": "Value", "id": 2 + }, + "createTime": { + "type": "google.protobuf.Timestamp", + "id": 3 + }, + "updateTime": { + "type": "google.protobuf.Timestamp", + "id": 4 } } - } - } - }, - "ExtensionRangeOptions": { - "fields": { - "uninterpretedOption": { - "rule": "repeated", - "type": "UninterpretedOption", - "id": 999 - }, - "declaration": { - "rule": "repeated", - "type": "Declaration", - "id": 2, - "options": { - "retention": "RETENTION_SOURCE" - } - }, - "features": { - "type": "FeatureSet", - "id": 50 }, - "verification": { - "type": "VerificationState", - "id": 3, - "options": { - "default": "UNVERIFIED", - "retention": "RETENTION_SOURCE" - } - } - }, - "extensions": [ - [ - 1000, - 536870911 - ] - ], - "nested": { - "Declaration": { + "Value": { + "oneofs": { + "valueType": { + "oneof": [ + "nullValue", + "booleanValue", + "integerValue", + "doubleValue", + "timestampValue", + "stringValue", + "bytesValue", + "referenceValue", + "geoPointValue", + "arrayValue", + "mapValue", + "fieldReferenceValue", + "functionValue", + "pipelineValue" + ] + } + }, "fields": { - "number": { - "type": "int32", + "nullValue": { + "type": "google.protobuf.NullValue", + "id": 11 + }, + "booleanValue": { + "type": "bool", "id": 1 }, - "fullName": { - "type": "string", + "integerValue": { + "type": "int64", "id": 2 }, - "type": { - "type": "string", + "doubleValue": { + "type": "double", "id": 3 }, - "reserved": { - "type": "bool", + "timestampValue": { + "type": "google.protobuf.Timestamp", + "id": 10 + }, + "stringValue": { + "type": "string", + "id": 17 + }, + "bytesValue": { + "type": "bytes", + "id": 18 + }, + "referenceValue": { + "type": "string", "id": 5 }, - "repeated": { - "type": "bool", + "geoPointValue": { + "type": "google.type.LatLng", + "id": 8 + }, + "arrayValue": { + "type": "ArrayValue", + "id": 9 + }, + "mapValue": { + "type": "MapValue", "id": 6 + }, + "fieldReferenceValue": { + "type": "string", + "id": 19 + }, + "functionValue": { + "type": "Function", + "id": 20 + }, + "pipelineValue": { + "type": "Pipeline", + "id": 21 } - }, - "reserved": [ - [ - 4, - 4 - ] - ] - }, - "VerificationState": { - "values": { - "DECLARATION": 0, - "UNVERIFIED": 1 } - } - } - }, - "FieldDescriptorProto": { - "fields": { - "name": { - "type": "string", - "id": 1 }, - "number": { - "type": "int32", - "id": 3 + "ArrayValue": { + "fields": { + "values": { + "rule": "repeated", + "type": "Value", + "id": 1 + } + } }, - "label": { - "type": "Label", - "id": 4 + "MapValue": { + "fields": { + "fields": { + "keyType": "string", + "type": "Value", + "id": 1 + } + } }, - "type": { - "type": "Type", - "id": 5 + "Function": { + "fields": { + "name": { + "type": "string", + "id": 1 + }, + "args": { + "rule": "repeated", + "type": "Value", + "id": 2 + }, + "options": { + "keyType": "string", + "type": "Value", + "id": 3 + } + } }, - "typeName": { - "type": "string", - "id": 6 + "Pipeline": { + "fields": { + "stages": { + "rule": "repeated", + "type": "Stage", + "id": 1 + } + }, + "nested": { + "Stage": { + "fields": { + "name": { + "type": "string", + "id": 1 + }, + "args": { + "rule": "repeated", + "type": "Value", + "id": 2 + }, + "options": { + "keyType": "string", + "type": "Value", + "id": 3 + } + } + } + } }, - "extendee": { - "type": "string", - "id": 2 + "BitSequence": { + "fields": { + "bitmap": { + "type": "bytes", + "id": 1 + }, + "padding": { + "type": "int32", + "id": 2 + } + } }, - "defaultValue": { - "type": "string", - "id": 7 + "BloomFilter": { + "fields": { + "bits": { + "type": "BitSequence", + "id": 1 + }, + "hashCount": { + "type": "int32", + "id": 2 + } + } }, - "oneofIndex": { - "type": "int32", - "id": 9 - }, - "jsonName": { - "type": "string", - "id": 10 - }, - "options": { - "type": "FieldOptions", - "id": 8 - }, - "proto3Optional": { - "type": "bool", - "id": 17 - } - }, - "nested": { - "Type": { - "values": { - "TYPE_DOUBLE": 1, - "TYPE_FLOAT": 2, - "TYPE_INT64": 3, - "TYPE_UINT64": 4, - "TYPE_INT32": 5, - "TYPE_FIXED64": 6, - "TYPE_FIXED32": 7, - "TYPE_BOOL": 8, - "TYPE_STRING": 9, - "TYPE_GROUP": 10, - "TYPE_MESSAGE": 11, - "TYPE_BYTES": 12, - "TYPE_UINT32": 13, - "TYPE_ENUM": 14, - "TYPE_SFIXED32": 15, - "TYPE_SFIXED64": 16, - "TYPE_SINT32": 17, - "TYPE_SINT64": 18 - } - }, - "Label": { - "values": { - "LABEL_OPTIONAL": 1, - "LABEL_REPEATED": 3, - "LABEL_REQUIRED": 2 + "DocumentMask": { + "fields": { + "fieldPaths": { + "rule": "repeated", + "type": "string", + "id": 1 + } } - } - } - }, - "OneofDescriptorProto": { - "fields": { - "name": { - "type": "string", - "id": 1 - }, - "options": { - "type": "OneofOptions", - "id": 2 - } - } - }, - "EnumDescriptorProto": { - "fields": { - "name": { - "type": "string", - "id": 1 - }, - "value": { - "rule": "repeated", - "type": "EnumValueDescriptorProto", - "id": 2 - }, - "options": { - "type": "EnumOptions", - "id": 3 - }, - "reservedRange": { - "rule": "repeated", - "type": "EnumReservedRange", - "id": 4 }, - "reservedName": { - "rule": "repeated", - "type": "string", - "id": 5 - } - }, - "nested": { - "EnumReservedRange": { + "Precondition": { + "oneofs": { + "conditionType": { + "oneof": [ + "exists", + "updateTime" + ] + } + }, "fields": { - "start": { - "type": "int32", + "exists": { + "type": "bool", "id": 1 }, - "end": { - "type": "int32", + "updateTime": { + "type": "google.protobuf.Timestamp", "id": 2 } } - } - } - }, - "EnumValueDescriptorProto": { - "fields": { - "name": { - "type": "string", - "id": 1 - }, - "number": { - "type": "int32", - "id": 2 - }, - "options": { - "type": "EnumValueOptions", - "id": 3 - } - } - }, - "ServiceDescriptorProto": { - "fields": { - "name": { - "type": "string", - "id": 1 - }, - "method": { - "rule": "repeated", - "type": "MethodDescriptorProto", - "id": 2 - }, - "options": { - "type": "ServiceOptions", - "id": 3 - } - } - }, - "MethodDescriptorProto": { - "fields": { - "name": { - "type": "string", - "id": 1 - }, - "inputType": { - "type": "string", - "id": 2 - }, - "outputType": { - "type": "string", - "id": 3 - }, - "options": { - "type": "MethodOptions", - "id": 4 - }, - "clientStreaming": { - "type": "bool", - "id": 5, - "options": { - "default": false - } - }, - "serverStreaming": { - "type": "bool", - "id": 6, - "options": { - "default": false - } - } - } - }, - "FileOptions": { - "fields": { - "javaPackage": { - "type": "string", - "id": 1 - }, - "javaOuterClassname": { - "type": "string", - "id": 8 - }, - "javaMultipleFiles": { - "type": "bool", - "id": 10, - "options": { - "default": false - } - }, - "javaGenerateEqualsAndHash": { - "type": "bool", - "id": 20, - "options": { - "deprecated": true - } }, - "javaStringCheckUtf8": { - "type": "bool", - "id": 27, - "options": { - "default": false + "TransactionOptions": { + "oneofs": { + "mode": { + "oneof": [ + "readOnly", + "readWrite" + ] + } + }, + "fields": { + "readOnly": { + "type": "ReadOnly", + "id": 2 + }, + "readWrite": { + "type": "ReadWrite", + "id": 3 + } + }, + "nested": { + "ReadWrite": { + "fields": { + "retryTransaction": { + "type": "bytes", + "id": 1 + } + } + }, + "ReadOnly": { + "oneofs": { + "consistencySelector": { + "oneof": [ + "readTime" + ] + } + }, + "fields": { + "readTime": { + "type": "google.protobuf.Timestamp", + "id": 2 + } + } + } } }, - "optimizeFor": { - "type": "OptimizeMode", - "id": 9, + "Firestore": { "options": { - "default": "SPEED" - } - }, - "goPackage": { - "type": "string", - "id": 11 - }, - "ccGenericServices": { - "type": "bool", - "id": 16, - "options": { - "default": false - } - }, - "javaGenericServices": { - "type": "bool", - "id": 17, - "options": { - "default": false - } - }, - "pyGenericServices": { - "type": "bool", - "id": 18, - "options": { - "default": false - } - }, - "deprecated": { - "type": "bool", - "id": 23, - "options": { - "default": false - } - }, - "ccEnableArenas": { - "type": "bool", - "id": 31, - "options": { - "default": true - } - }, - "objcClassPrefix": { - "type": "string", - "id": 36 - }, - "csharpNamespace": { - "type": "string", - "id": 37 - }, - "swiftPrefix": { - "type": "string", - "id": 39 - }, - "phpClassPrefix": { - "type": "string", - "id": 40 - }, - "phpNamespace": { - "type": "string", - "id": 41 - }, - "phpMetadataNamespace": { - "type": "string", - "id": 44 - }, - "rubyPackage": { - "type": "string", - "id": 45 - }, - "features": { - "type": "FeatureSet", - "id": 50 - }, - "uninterpretedOption": { - "rule": "repeated", - "type": "UninterpretedOption", - "id": 999 - } - }, - "extensions": [ - [ - 1000, - 536870911 - ] - ], - "reserved": [ - [ - 42, - 42 - ], - [ - 38, - 38 - ] - ], - "nested": { - "OptimizeMode": { - "values": { - "SPEED": 1, - "CODE_SIZE": 2, - "LITE_RUNTIME": 3 - } - } - } - }, - "MessageOptions": { - "fields": { - "messageSetWireFormat": { - "type": "bool", - "id": 1, - "options": { - "default": false - } - }, - "noStandardDescriptorAccessor": { - "type": "bool", - "id": 2, - "options": { - "default": false - } - }, - "deprecated": { - "type": "bool", - "id": 3, - "options": { - "default": false - } - }, - "mapEntry": { - "type": "bool", - "id": 7 - }, - "deprecatedLegacyJsonFieldConflicts": { - "type": "bool", - "id": 11, - "options": { - "deprecated": true - } - }, - "features": { - "type": "FeatureSet", - "id": 12 - }, - "uninterpretedOption": { - "rule": "repeated", - "type": "UninterpretedOption", - "id": 999 - } - }, - "extensions": [ - [ - 1000, - 536870911 - ] - ], - "reserved": [ - [ - 4, - 4 - ], - [ - 5, - 5 - ], - [ - 6, - 6 - ], - [ - 8, - 8 - ], - [ - 9, - 9 - ] - ] - }, - "FieldOptions": { - "fields": { - "ctype": { - "type": "CType", - "id": 1, - "options": { - "default": "STRING" - } - }, - "packed": { - "type": "bool", - "id": 2 - }, - "jstype": { - "type": "JSType", - "id": 6, - "options": { - "default": "JS_NORMAL" - } - }, - "lazy": { - "type": "bool", - "id": 5, - "options": { - "default": false - } - }, - "unverifiedLazy": { - "type": "bool", - "id": 15, - "options": { - "default": false - } - }, - "deprecated": { - "type": "bool", - "id": 3, - "options": { - "default": false - } - }, - "weak": { - "type": "bool", - "id": 10, - "options": { - "default": false - } - }, - "debugRedact": { - "type": "bool", - "id": 16, - "options": { - "default": false - } - }, - "retention": { - "type": "OptionRetention", - "id": 17 - }, - "targets": { - "rule": "repeated", - "type": "OptionTargetType", - "id": 19, - "options": { - "packed": false - } - }, - "editionDefaults": { - "rule": "repeated", - "type": "EditionDefault", - "id": 20 - }, - "features": { - "type": "FeatureSet", - "id": 21 - }, - "featureSupport": { - "type": "FeatureSupport", - "id": 22 - }, - "uninterpretedOption": { - "rule": "repeated", - "type": "UninterpretedOption", - "id": 999 - } - }, - "extensions": [ - [ - 1000, - 536870911 - ] - ], - "reserved": [ - [ - 4, - 4 - ], - [ - 18, - 18 - ] - ], - "nested": { - "CType": { - "values": { - "STRING": 0, - "CORD": 1, - "STRING_PIECE": 2 - } - }, - "JSType": { - "values": { - "JS_NORMAL": 0, - "JS_STRING": 1, - "JS_NUMBER": 2 + "(google.api.default_host)": "firestore.googleapis.com", + "(google.api.oauth_scopes)": "https://www.googleapis.com/auth/cloud-platform,https://www.googleapis.com/auth/datastore" + }, + "methods": { + "GetDocument": { + "requestType": "GetDocumentRequest", + "responseType": "Document", + "options": { + "(google.api.http).get": "/v1/{name=projects/*/databases/*/documents/*/**}" + }, + "parsedOptions": [ + { + "(google.api.http)": { + "get": "/v1/{name=projects/*/databases/*/documents/*/**}" + } + } + ] + }, + "ListDocuments": { + "requestType": "ListDocumentsRequest", + "responseType": "ListDocumentsResponse", + "options": { + "(google.api.http).get": "/v1/{parent=projects/*/databases/*/documents/*/**}/{collection_id}", + "(google.api.http).additional_bindings.get": "/v1/{parent=projects/*/databases/*/documents}/{collection_id}" + }, + "parsedOptions": [ + { + "(google.api.http)": { + "get": "/v1/{parent=projects/*/databases/*/documents/*/**}/{collection_id}", + "additional_bindings": { + "get": "/v1/{parent=projects/*/databases/*/documents}/{collection_id}" + } + } + } + ] + }, + "UpdateDocument": { + "requestType": "UpdateDocumentRequest", + "responseType": "Document", + "options": { + "(google.api.http).patch": "/v1/{document.name=projects/*/databases/*/documents/*/**}", + "(google.api.http).body": "document", + "(google.api.method_signature)": "document,update_mask" + }, + "parsedOptions": [ + { + "(google.api.http)": { + "patch": "/v1/{document.name=projects/*/databases/*/documents/*/**}", + "body": "document" + } + }, + { + "(google.api.method_signature)": "document,update_mask" + } + ] + }, + "DeleteDocument": { + "requestType": "DeleteDocumentRequest", + "responseType": "google.protobuf.Empty", + "options": { + "(google.api.http).delete": "/v1/{name=projects/*/databases/*/documents/*/**}", + "(google.api.method_signature)": "name" + }, + "parsedOptions": [ + { + "(google.api.http)": { + "delete": "/v1/{name=projects/*/databases/*/documents/*/**}" + } + }, + { + "(google.api.method_signature)": "name" + } + ] + }, + "BatchGetDocuments": { + "requestType": "BatchGetDocumentsRequest", + "responseType": "BatchGetDocumentsResponse", + "responseStream": true, + "options": { + "(google.api.http).post": "/v1/{database=projects/*/databases/*}/documents:batchGet", + "(google.api.http).body": "*" + }, + "parsedOptions": [ + { + "(google.api.http)": { + "post": "/v1/{database=projects/*/databases/*}/documents:batchGet", + "body": "*" + } + } + ] + }, + "BeginTransaction": { + "requestType": "BeginTransactionRequest", + "responseType": "BeginTransactionResponse", + "options": { + "(google.api.http).post": "/v1/{database=projects/*/databases/*}/documents:beginTransaction", + "(google.api.http).body": "*", + "(google.api.method_signature)": "database" + }, + "parsedOptions": [ + { + "(google.api.http)": { + "post": "/v1/{database=projects/*/databases/*}/documents:beginTransaction", + "body": "*" + } + }, + { + "(google.api.method_signature)": "database" + } + ] + }, + "Commit": { + "requestType": "CommitRequest", + "responseType": "CommitResponse", + "options": { + "(google.api.http).post": "/v1/{database=projects/*/databases/*}/documents:commit", + "(google.api.http).body": "*", + "(google.api.method_signature)": "database,writes" + }, + "parsedOptions": [ + { + "(google.api.http)": { + "post": "/v1/{database=projects/*/databases/*}/documents:commit", + "body": "*" + } + }, + { + "(google.api.method_signature)": "database,writes" + } + ] + }, + "Rollback": { + "requestType": "RollbackRequest", + "responseType": "google.protobuf.Empty", + "options": { + "(google.api.http).post": "/v1/{database=projects/*/databases/*}/documents:rollback", + "(google.api.http).body": "*", + "(google.api.method_signature)": "database,transaction" + }, + "parsedOptions": [ + { + "(google.api.http)": { + "post": "/v1/{database=projects/*/databases/*}/documents:rollback", + "body": "*" + } + }, + { + "(google.api.method_signature)": "database,transaction" + } + ] + }, + "RunQuery": { + "requestType": "RunQueryRequest", + "responseType": "RunQueryResponse", + "responseStream": true, + "options": { + "(google.api.http).post": "/v1/{parent=projects/*/databases/*/documents}:runQuery", + "(google.api.http).body": "*", + "(google.api.http).additional_bindings.post": "/v1/{parent=projects/*/databases/*/documents/*/**}:runQuery", + "(google.api.http).additional_bindings.body": "*" + }, + "parsedOptions": [ + { + "(google.api.http)": { + "post": "/v1/{parent=projects/*/databases/*/documents}:runQuery", + "body": "*", + "additional_bindings": { + "post": "/v1/{parent=projects/*/databases/*/documents/*/**}:runQuery", + "body": "*" + } + } + } + ] + }, + "ExecutePipeline": { + "requestType": "ExecutePipelineRequest", + "responseType": "ExecutePipelineResponse", + "responseStream": true, + "options": { + "(google.api.http).post": "/v1/{database=projects/*/databases/*}/documents:executePipeline", + "(google.api.http).body": "*" + }, + "parsedOptions": [ + { + "(google.api.http)": { + "post": "/v1/{database=projects/*/databases/*}/documents:executePipeline", + "body": "*" + } + } + ] + }, + "RunAggregationQuery": { + "requestType": "RunAggregationQueryRequest", + "responseType": "RunAggregationQueryResponse", + "responseStream": true, + "options": { + "(google.api.http).post": "/v1/{parent=projects/*/databases/*/documents}:runAggregationQuery", + "(google.api.http).body": "*", + "(google.api.http).additional_bindings.post": "/v1/{parent=projects/*/databases/*/documents/*/**}:runAggregationQuery", + "(google.api.http).additional_bindings.body": "*" + }, + "parsedOptions": [ + { + "(google.api.http)": { + "post": "/v1/{parent=projects/*/databases/*/documents}:runAggregationQuery", + "body": "*", + "additional_bindings": { + "post": "/v1/{parent=projects/*/databases/*/documents/*/**}:runAggregationQuery", + "body": "*" + } + } + } + ] + }, + "PartitionQuery": { + "requestType": "PartitionQueryRequest", + "responseType": "PartitionQueryResponse", + "options": { + "(google.api.http).post": "/v1/{parent=projects/*/databases/*/documents}:partitionQuery", + "(google.api.http).body": "*", + "(google.api.http).additional_bindings.post": "/v1/{parent=projects/*/databases/*/documents/*/**}:partitionQuery", + "(google.api.http).additional_bindings.body": "*" + }, + "parsedOptions": [ + { + "(google.api.http)": { + "post": "/v1/{parent=projects/*/databases/*/documents}:partitionQuery", + "body": "*", + "additional_bindings": { + "post": "/v1/{parent=projects/*/databases/*/documents/*/**}:partitionQuery", + "body": "*" + } + } + } + ] + }, + "Write": { + "requestType": "WriteRequest", + "requestStream": true, + "responseType": "WriteResponse", + "responseStream": true, + "options": { + "(google.api.http).post": "/v1/{database=projects/*/databases/*}/documents:write", + "(google.api.http).body": "*" + }, + "parsedOptions": [ + { + "(google.api.http)": { + "post": "/v1/{database=projects/*/databases/*}/documents:write", + "body": "*" + } + } + ] + }, + "Listen": { + "requestType": "ListenRequest", + "requestStream": true, + "responseType": "ListenResponse", + "responseStream": true, + "options": { + "(google.api.http).post": "/v1/{database=projects/*/databases/*}/documents:listen", + "(google.api.http).body": "*" + }, + "parsedOptions": [ + { + "(google.api.http)": { + "post": "/v1/{database=projects/*/databases/*}/documents:listen", + "body": "*" + } + } + ] + }, + "ListCollectionIds": { + "requestType": "ListCollectionIdsRequest", + "responseType": "ListCollectionIdsResponse", + "options": { + "(google.api.http).post": "/v1/{parent=projects/*/databases/*/documents}:listCollectionIds", + "(google.api.http).body": "*", + "(google.api.http).additional_bindings.post": "/v1/{parent=projects/*/databases/*/documents/*/**}:listCollectionIds", + "(google.api.http).additional_bindings.body": "*", + "(google.api.method_signature)": "parent" + }, + "parsedOptions": [ + { + "(google.api.http)": { + "post": "/v1/{parent=projects/*/databases/*/documents}:listCollectionIds", + "body": "*", + "additional_bindings": { + "post": "/v1/{parent=projects/*/databases/*/documents/*/**}:listCollectionIds", + "body": "*" + } + } + }, + { + "(google.api.method_signature)": "parent" + } + ] + }, + "BatchWrite": { + "requestType": "BatchWriteRequest", + "responseType": "BatchWriteResponse", + "options": { + "(google.api.http).post": "/v1/{database=projects/*/databases/*}/documents:batchWrite", + "(google.api.http).body": "*" + }, + "parsedOptions": [ + { + "(google.api.http)": { + "post": "/v1/{database=projects/*/databases/*}/documents:batchWrite", + "body": "*" + } + } + ] + }, + "CreateDocument": { + "requestType": "CreateDocumentRequest", + "responseType": "Document", + "options": { + "(google.api.http).post": "/v1/{parent=projects/*/databases/*/documents/**}/{collection_id}", + "(google.api.http).body": "document" + }, + "parsedOptions": [ + { + "(google.api.http)": { + "post": "/v1/{parent=projects/*/databases/*/documents/**}/{collection_id}", + "body": "document" + } + } + ] + } } }, - "OptionRetention": { - "values": { - "RETENTION_UNKNOWN": 0, - "RETENTION_RUNTIME": 1, - "RETENTION_SOURCE": 2 + "GetDocumentRequest": { + "oneofs": { + "consistencySelector": { + "oneof": [ + "transaction", + "readTime" + ] + } + }, + "fields": { + "name": { + "type": "string", + "id": 1, + "options": { + "(google.api.field_behavior)": "REQUIRED" + } + }, + "mask": { + "type": "DocumentMask", + "id": 2 + }, + "transaction": { + "type": "bytes", + "id": 3 + }, + "readTime": { + "type": "google.protobuf.Timestamp", + "id": 5 + } } }, - "OptionTargetType": { - "values": { - "TARGET_TYPE_UNKNOWN": 0, - "TARGET_TYPE_FILE": 1, - "TARGET_TYPE_EXTENSION_RANGE": 2, - "TARGET_TYPE_MESSAGE": 3, - "TARGET_TYPE_FIELD": 4, - "TARGET_TYPE_ONEOF": 5, - "TARGET_TYPE_ENUM": 6, - "TARGET_TYPE_ENUM_ENTRY": 7, - "TARGET_TYPE_SERVICE": 8, - "TARGET_TYPE_METHOD": 9 + "ListDocumentsRequest": { + "oneofs": { + "consistencySelector": { + "oneof": [ + "transaction", + "readTime" + ] + } + }, + "fields": { + "parent": { + "type": "string", + "id": 1, + "options": { + "(google.api.field_behavior)": "REQUIRED" + } + }, + "collectionId": { + "type": "string", + "id": 2, + "options": { + "(google.api.field_behavior)": "OPTIONAL" + } + }, + "pageSize": { + "type": "int32", + "id": 3, + "options": { + "(google.api.field_behavior)": "OPTIONAL" + } + }, + "pageToken": { + "type": "string", + "id": 4, + "options": { + "(google.api.field_behavior)": "OPTIONAL" + } + }, + "orderBy": { + "type": "string", + "id": 6, + "options": { + "(google.api.field_behavior)": "OPTIONAL" + } + }, + "mask": { + "type": "DocumentMask", + "id": 7, + "options": { + "(google.api.field_behavior)": "OPTIONAL" + } + }, + "transaction": { + "type": "bytes", + "id": 8 + }, + "readTime": { + "type": "google.protobuf.Timestamp", + "id": 10 + }, + "showMissing": { + "type": "bool", + "id": 12 + } } }, - "EditionDefault": { + "ListDocumentsResponse": { "fields": { - "edition": { - "type": "Edition", - "id": 3 + "documents": { + "rule": "repeated", + "type": "Document", + "id": 1 }, - "value": { + "nextPageToken": { "type": "string", "id": 2 } } }, - "FeatureSupport": { + "CreateDocumentRequest": { "fields": { - "editionIntroduced": { - "type": "Edition", - "id": 1 + "parent": { + "type": "string", + "id": 1, + "options": { + "(google.api.field_behavior)": "REQUIRED" + } }, - "editionDeprecated": { - "type": "Edition", - "id": 2 + "collectionId": { + "type": "string", + "id": 2, + "options": { + "(google.api.field_behavior)": "REQUIRED" + } }, - "deprecationWarning": { + "documentId": { "type": "string", "id": 3 }, - "editionRemoved": { - "type": "Edition", - "id": 4 + "document": { + "type": "Document", + "id": 4, + "options": { + "(google.api.field_behavior)": "REQUIRED" + } + }, + "mask": { + "type": "DocumentMask", + "id": 5 } } - } - } - }, - "OneofOptions": { - "fields": { - "features": { - "type": "FeatureSet", - "id": 1 - }, - "uninterpretedOption": { - "rule": "repeated", - "type": "UninterpretedOption", - "id": 999 - } - }, - "extensions": [ - [ - 1000, - 536870911 - ] - ] - }, - "EnumOptions": { - "fields": { - "allowAlias": { - "type": "bool", - "id": 2 - }, - "deprecated": { - "type": "bool", - "id": 3, - "options": { - "default": false - } - }, - "deprecatedLegacyJsonFieldConflicts": { - "type": "bool", - "id": 6, - "options": { - "deprecated": true - } - }, - "features": { - "type": "FeatureSet", - "id": 7 - }, - "uninterpretedOption": { - "rule": "repeated", - "type": "UninterpretedOption", - "id": 999 - } - }, - "extensions": [ - [ - 1000, - 536870911 - ] - ], - "reserved": [ - [ - 5, - 5 - ] - ] - }, - "EnumValueOptions": { - "fields": { - "deprecated": { - "type": "bool", - "id": 1, - "options": { - "default": false - } - }, - "features": { - "type": "FeatureSet", - "id": 2 - }, - "debugRedact": { - "type": "bool", - "id": 3, - "options": { - "default": false - } - }, - "uninterpretedOption": { - "rule": "repeated", - "type": "UninterpretedOption", - "id": 999 - } - }, - "extensions": [ - [ - 1000, - 536870911 - ] - ] - }, - "ServiceOptions": { - "fields": { - "features": { - "type": "FeatureSet", - "id": 34 - }, - "deprecated": { - "type": "bool", - "id": 33, - "options": { - "default": false - } - }, - "uninterpretedOption": { - "rule": "repeated", - "type": "UninterpretedOption", - "id": 999 - } - }, - "extensions": [ - [ - 1000, - 536870911 - ] - ] - }, - "MethodOptions": { - "fields": { - "deprecated": { - "type": "bool", - "id": 33, - "options": { - "default": false - } - }, - "idempotencyLevel": { - "type": "IdempotencyLevel", - "id": 34, - "options": { - "default": "IDEMPOTENCY_UNKNOWN" - } - }, - "features": { - "type": "FeatureSet", - "id": 35 - }, - "uninterpretedOption": { - "rule": "repeated", - "type": "UninterpretedOption", - "id": 999 - } - }, - "extensions": [ - [ - 1000, - 536870911 - ] - ], - "nested": { - "IdempotencyLevel": { - "values": { - "IDEMPOTENCY_UNKNOWN": 0, - "NO_SIDE_EFFECTS": 1, - "IDEMPOTENT": 2 - } - } - } - }, - "UninterpretedOption": { - "fields": { - "name": { - "rule": "repeated", - "type": "NamePart", - "id": 2 - }, - "identifierValue": { - "type": "string", - "id": 3 - }, - "positiveIntValue": { - "type": "uint64", - "id": 4 - }, - "negativeIntValue": { - "type": "int64", - "id": 5 }, - "doubleValue": { - "type": "double", - "id": 6 + "UpdateDocumentRequest": { + "fields": { + "document": { + "type": "Document", + "id": 1, + "options": { + "(google.api.field_behavior)": "REQUIRED" + } + }, + "updateMask": { + "type": "DocumentMask", + "id": 2 + }, + "mask": { + "type": "DocumentMask", + "id": 3 + }, + "currentDocument": { + "type": "Precondition", + "id": 4 + } + } }, - "stringValue": { - "type": "bytes", - "id": 7 + "DeleteDocumentRequest": { + "fields": { + "name": { + "type": "string", + "id": 1, + "options": { + "(google.api.field_behavior)": "REQUIRED" + } + }, + "currentDocument": { + "type": "Precondition", + "id": 2 + } + } }, - "aggregateValue": { - "type": "string", - "id": 8 - } - }, - "nested": { - "NamePart": { + "BatchGetDocumentsRequest": { + "oneofs": { + "consistencySelector": { + "oneof": [ + "transaction", + "newTransaction", + "readTime" + ] + } + }, "fields": { - "namePart": { - "rule": "required", + "database": { "type": "string", - "id": 1 + "id": 1, + "options": { + "(google.api.field_behavior)": "REQUIRED" + } }, - "isExtension": { - "rule": "required", - "type": "bool", + "documents": { + "rule": "repeated", + "type": "string", "id": 2 + }, + "mask": { + "type": "DocumentMask", + "id": 3 + }, + "transaction": { + "type": "bytes", + "id": 4 + }, + "newTransaction": { + "type": "TransactionOptions", + "id": 5 + }, + "readTime": { + "type": "google.protobuf.Timestamp", + "id": 7 } } - } - } - }, - "FeatureSet": { - "fields": { - "fieldPresence": { - "type": "FieldPresence", - "id": 1, - "options": { - "retention": "RETENTION_RUNTIME", - "targets": "TARGET_TYPE_FILE", - "feature_support.edition_introduced": "EDITION_2023", - "edition_defaults.edition": "EDITION_2023", - "edition_defaults.value": "EXPLICIT" + }, + "BatchGetDocumentsResponse": { + "oneofs": { + "result": { + "oneof": [ + "found", + "missing" + ] + } + }, + "fields": { + "found": { + "type": "Document", + "id": 1 + }, + "missing": { + "type": "string", + "id": 2 + }, + "transaction": { + "type": "bytes", + "id": 3 + }, + "readTime": { + "type": "google.protobuf.Timestamp", + "id": 4 + } } }, - "enumType": { - "type": "EnumType", - "id": 2, - "options": { - "retention": "RETENTION_RUNTIME", - "targets": "TARGET_TYPE_FILE", - "feature_support.edition_introduced": "EDITION_2023", - "edition_defaults.edition": "EDITION_PROTO3", - "edition_defaults.value": "OPEN" + "BeginTransactionRequest": { + "fields": { + "database": { + "type": "string", + "id": 1, + "options": { + "(google.api.field_behavior)": "REQUIRED" + } + }, + "options": { + "type": "TransactionOptions", + "id": 2 + } } }, - "repeatedFieldEncoding": { - "type": "RepeatedFieldEncoding", - "id": 3, - "options": { - "retention": "RETENTION_RUNTIME", - "targets": "TARGET_TYPE_FILE", - "feature_support.edition_introduced": "EDITION_2023", - "edition_defaults.edition": "EDITION_PROTO3", - "edition_defaults.value": "PACKED" + "BeginTransactionResponse": { + "fields": { + "transaction": { + "type": "bytes", + "id": 1 + } } }, - "utf8Validation": { - "type": "Utf8Validation", - "id": 4, - "options": { - "retention": "RETENTION_RUNTIME", - "targets": "TARGET_TYPE_FILE", - "feature_support.edition_introduced": "EDITION_2023", - "edition_defaults.edition": "EDITION_PROTO3", - "edition_defaults.value": "VERIFY" + "CommitRequest": { + "fields": { + "database": { + "type": "string", + "id": 1, + "options": { + "(google.api.field_behavior)": "REQUIRED" + } + }, + "writes": { + "rule": "repeated", + "type": "Write", + "id": 2 + }, + "transaction": { + "type": "bytes", + "id": 3 + } } }, - "messageEncoding": { - "type": "MessageEncoding", - "id": 5, - "options": { - "retention": "RETENTION_RUNTIME", - "targets": "TARGET_TYPE_FILE", - "feature_support.edition_introduced": "EDITION_2023", - "edition_defaults.edition": "EDITION_PROTO2", - "edition_defaults.value": "LENGTH_PREFIXED" + "CommitResponse": { + "fields": { + "writeResults": { + "rule": "repeated", + "type": "WriteResult", + "id": 1 + }, + "commitTime": { + "type": "google.protobuf.Timestamp", + "id": 2 + } } }, - "jsonFormat": { - "type": "JsonFormat", - "id": 6, - "options": { - "retention": "RETENTION_RUNTIME", - "targets": "TARGET_TYPE_FILE", - "feature_support.edition_introduced": "EDITION_2023", - "edition_defaults.edition": "EDITION_PROTO3", - "edition_defaults.value": "ALLOW" + "RollbackRequest": { + "fields": { + "database": { + "type": "string", + "id": 1, + "options": { + "(google.api.field_behavior)": "REQUIRED" + } + }, + "transaction": { + "type": "bytes", + "id": 2, + "options": { + "(google.api.field_behavior)": "REQUIRED" + } + } } - } - }, - "extensions": [ - [ - 1000, - 9994 - ], - [ - 9995, - 9999 - ], - [ - 10000, - 10000 - ] - ], - "reserved": [ - [ - 999, - 999 - ] - ], - "nested": { - "FieldPresence": { - "values": { - "FIELD_PRESENCE_UNKNOWN": 0, - "EXPLICIT": 1, - "IMPLICIT": 2, - "LEGACY_REQUIRED": 3 + }, + "RunQueryRequest": { + "oneofs": { + "queryType": { + "oneof": [ + "structuredQuery" + ] + }, + "consistencySelector": { + "oneof": [ + "transaction", + "newTransaction", + "readTime" + ] + } + }, + "fields": { + "parent": { + "type": "string", + "id": 1, + "options": { + "(google.api.field_behavior)": "REQUIRED" + } + }, + "structuredQuery": { + "type": "StructuredQuery", + "id": 2 + }, + "transaction": { + "type": "bytes", + "id": 5 + }, + "newTransaction": { + "type": "TransactionOptions", + "id": 6 + }, + "readTime": { + "type": "google.protobuf.Timestamp", + "id": 7 + }, + "explainOptions": { + "type": "ExplainOptions", + "id": 10, + "options": { + "(google.api.field_behavior)": "OPTIONAL" + } + } } }, - "EnumType": { - "values": { - "ENUM_TYPE_UNKNOWN": 0, - "OPEN": 1, - "CLOSED": 2 + "RunQueryResponse": { + "oneofs": { + "continuationSelector": { + "oneof": [ + "done" + ] + } + }, + "fields": { + "transaction": { + "type": "bytes", + "id": 2 + }, + "document": { + "type": "Document", + "id": 1 + }, + "readTime": { + "type": "google.protobuf.Timestamp", + "id": 3 + }, + "skippedResults": { + "type": "int32", + "id": 4 + }, + "done": { + "type": "bool", + "id": 6 + }, + "explainMetrics": { + "type": "ExplainMetrics", + "id": 11 + } } }, - "RepeatedFieldEncoding": { - "values": { - "REPEATED_FIELD_ENCODING_UNKNOWN": 0, - "PACKED": 1, - "EXPANDED": 2 + "ExecutePipelineRequest": { + "oneofs": { + "pipelineType": { + "oneof": [ + "structuredPipeline" + ] + }, + "consistencySelector": { + "oneof": [ + "transaction", + "newTransaction", + "readTime" + ] + } + }, + "fields": { + "database": { + "type": "string", + "id": 1, + "options": { + "(google.api.field_behavior)": "REQUIRED" + } + }, + "structuredPipeline": { + "type": "StructuredPipeline", + "id": 2 + }, + "transaction": { + "type": "bytes", + "id": 5 + }, + "newTransaction": { + "type": "TransactionOptions", + "id": 6 + }, + "readTime": { + "type": "google.protobuf.Timestamp", + "id": 7 + } } }, - "Utf8Validation": { - "values": { - "UTF8_VALIDATION_UNKNOWN": 0, - "VERIFY": 2, - "NONE": 3 + "ExecutePipelineResponse": { + "fields": { + "transaction": { + "type": "bytes", + "id": 1 + }, + "results": { + "rule": "repeated", + "type": "Document", + "id": 2 + }, + "executionTime": { + "type": "google.protobuf.Timestamp", + "id": 3 + } } }, - "MessageEncoding": { - "values": { - "MESSAGE_ENCODING_UNKNOWN": 0, - "LENGTH_PREFIXED": 1, - "DELIMITED": 2 + "RunAggregationQueryRequest": { + "oneofs": { + "queryType": { + "oneof": [ + "structuredAggregationQuery" + ] + }, + "consistencySelector": { + "oneof": [ + "transaction", + "newTransaction", + "readTime" + ] + } + }, + "fields": { + "parent": { + "type": "string", + "id": 1, + "options": { + "(google.api.field_behavior)": "REQUIRED" + } + }, + "structuredAggregationQuery": { + "type": "StructuredAggregationQuery", + "id": 2 + }, + "transaction": { + "type": "bytes", + "id": 4 + }, + "newTransaction": { + "type": "TransactionOptions", + "id": 5 + }, + "readTime": { + "type": "google.protobuf.Timestamp", + "id": 6 + }, + "explainOptions": { + "type": "ExplainOptions", + "id": 8, + "options": { + "(google.api.field_behavior)": "OPTIONAL" + } + } } }, - "JsonFormat": { - "values": { - "JSON_FORMAT_UNKNOWN": 0, - "ALLOW": 1, - "LEGACY_BEST_EFFORT": 2 + "RunAggregationQueryResponse": { + "fields": { + "result": { + "type": "AggregationResult", + "id": 1 + }, + "transaction": { + "type": "bytes", + "id": 2 + }, + "readTime": { + "type": "google.protobuf.Timestamp", + "id": 3 + }, + "explainMetrics": { + "type": "ExplainMetrics", + "id": 10 + } } - } - } - }, - "FeatureSetDefaults": { - "fields": { - "defaults": { - "rule": "repeated", - "type": "FeatureSetEditionDefault", - "id": 1 - }, - "minimumEdition": { - "type": "Edition", - "id": 4 }, - "maximumEdition": { - "type": "Edition", - "id": 5 - } - }, - "nested": { - "FeatureSetEditionDefault": { + "PartitionQueryRequest": { + "oneofs": { + "queryType": { + "oneof": [ + "structuredQuery" + ] + }, + "consistencySelector": { + "oneof": [ + "readTime" + ] + } + }, "fields": { - "edition": { - "type": "Edition", + "parent": { + "type": "string", + "id": 1, + "options": { + "(google.api.field_behavior)": "REQUIRED" + } + }, + "structuredQuery": { + "type": "StructuredQuery", + "id": 2 + }, + "partitionCount": { + "type": "int64", "id": 3 }, - "overridableFeatures": { - "type": "FeatureSet", + "pageToken": { + "type": "string", "id": 4 }, - "fixedFeatures": { - "type": "FeatureSet", + "pageSize": { + "type": "int32", "id": 5 + }, + "readTime": { + "type": "google.protobuf.Timestamp", + "id": 6 } } - } - } - }, - "SourceCodeInfo": { - "fields": { - "location": { - "rule": "repeated", - "type": "Location", - "id": 1 - } - }, - "nested": { - "Location": { + }, + "PartitionQueryResponse": { "fields": { - "path": { + "partitions": { "rule": "repeated", - "type": "int32", + "type": "Cursor", "id": 1 }, - "span": { - "rule": "repeated", - "type": "int32", + "nextPageToken": { + "type": "string", "id": 2 + } + } + }, + "WriteRequest": { + "fields": { + "database": { + "type": "string", + "id": 1, + "options": { + "(google.api.field_behavior)": "REQUIRED" + } }, - "leadingComments": { + "streamId": { "type": "string", + "id": 2 + }, + "writes": { + "rule": "repeated", + "type": "Write", "id": 3 }, - "trailingComments": { - "type": "string", + "streamToken": { + "type": "bytes", "id": 4 }, - "leadingDetachedComments": { - "rule": "repeated", + "labels": { + "keyType": "string", "type": "string", - "id": 6 + "id": 5 } } - } - } - }, - "GeneratedCodeInfo": { - "fields": { - "annotation": { - "rule": "repeated", - "type": "Annotation", - "id": 1 - } - }, - "nested": { - "Annotation": { + }, + "WriteResponse": { "fields": { - "path": { - "rule": "repeated", - "type": "int32", + "streamId": { + "type": "string", "id": 1 }, - "sourceFile": { - "type": "string", + "streamToken": { + "type": "bytes", "id": 2 }, - "begin": { - "type": "int32", + "writeResults": { + "rule": "repeated", + "type": "WriteResult", "id": 3 }, - "end": { - "type": "int32", + "commitTime": { + "type": "google.protobuf.Timestamp", "id": 4 - }, - "semantic": { - "type": "Semantic", - "id": 5 - } - }, - "nested": { - "Semantic": { - "values": { - "NONE": 0, - "SET": 1, - "ALIAS": 2 - } } } - } - } - }, - "Duration": { - "fields": { - "seconds": { - "type": "int64", - "id": 1 - }, - "nanos": { - "type": "int32", - "id": 2 - } - } - }, - "DoubleValue": { - "fields": { - "value": { - "type": "double", - "id": 1 - } - } - }, - "FloatValue": { - "fields": { - "value": { - "type": "float", - "id": 1 - } - } - }, - "Int64Value": { - "fields": { - "value": { - "type": "int64", - "id": 1 - } - } - }, - "UInt64Value": { - "fields": { - "value": { - "type": "uint64", - "id": 1 - } - } - }, - "Int32Value": { - "fields": { - "value": { - "type": "int32", - "id": 1 - } - } - }, - "UInt32Value": { - "fields": { - "value": { - "type": "uint32", - "id": 1 - } - } - }, - "BoolValue": { - "fields": { - "value": { - "type": "bool", - "id": 1 - } - } - }, - "StringValue": { - "fields": { - "value": { - "type": "string", - "id": 1 - } - } - }, - "BytesValue": { - "fields": { - "value": { - "type": "bytes", - "id": 1 - } - } - }, - "Empty": { - "fields": {} - }, - "Any": { - "fields": { - "type_url": { - "type": "string", - "id": 1 }, - "value": { - "type": "bytes", - "id": 2 - } - } - }, - "FieldMask": { - "fields": { - "paths": { - "rule": "repeated", - "type": "string", - "id": 1 - } - } - } - } - }, - "firestore": { - "nested": { - "v1": { - "options": { - "csharp_namespace": "Google.Cloud.Firestore.V1", - "go_package": "cloud.google.com/go/firestore/apiv1/firestorepb;firestorepb", - "java_multiple_files": true, - "java_outer_classname": "WriteProto", - "java_package": "com.google.firestore.v1", - "objc_class_prefix": "GCFS", - "php_namespace": "Google\\Cloud\\Firestore\\V1", - "ruby_package": "Google::Cloud::Firestore::V1" - }, - "nested": { - "AggregationResult": { - "fields": { - "aggregateFields": { - "keyType": "string", - "type": "Value", - "id": 2 + "ListenRequest": { + "oneofs": { + "targetChange": { + "oneof": [ + "addTarget", + "removeTarget" + ] } - } - }, - "Document": { + }, "fields": { - "name": { + "database": { "type": "string", - "id": 1 + "id": 1, + "options": { + "(google.api.field_behavior)": "REQUIRED" + } }, - "fields": { - "keyType": "string", - "type": "Value", + "addTarget": { + "type": "Target", "id": 2 }, - "createTime": { - "type": "google.protobuf.Timestamp", + "removeTarget": { + "type": "int32", "id": 3 }, - "updateTime": { - "type": "google.protobuf.Timestamp", + "labels": { + "keyType": "string", + "type": "string", "id": 4 } } }, - "Value": { + "ListenResponse": { "oneofs": { - "valueType": { + "responseType": { "oneof": [ - "nullValue", - "booleanValue", - "integerValue", - "doubleValue", - "timestampValue", - "stringValue", - "bytesValue", - "referenceValue", - "geoPointValue", - "arrayValue", - "mapValue", - "fieldReferenceValue", - "functionValue", - "pipelineValue" + "targetChange", + "documentChange", + "documentDelete", + "documentRemove", + "filter" ] } }, "fields": { - "nullValue": { - "type": "google.protobuf.NullValue", - "id": 11 - }, - "booleanValue": { - "type": "bool", - "id": 1 - }, - "integerValue": { - "type": "int64", + "targetChange": { + "type": "TargetChange", "id": 2 }, - "doubleValue": { - "type": "double", + "documentChange": { + "type": "DocumentChange", "id": 3 }, - "timestampValue": { - "type": "google.protobuf.Timestamp", - "id": 10 - }, - "stringValue": { - "type": "string", - "id": 17 + "documentDelete": { + "type": "DocumentDelete", + "id": 4 }, - "bytesValue": { - "type": "bytes", - "id": 18 + "documentRemove": { + "type": "DocumentRemove", + "id": 6 }, - "referenceValue": { - "type": "string", + "filter": { + "type": "ExistenceFilter", "id": 5 + } + } + }, + "Target": { + "oneofs": { + "targetType": { + "oneof": [ + "query", + "documents" + ] }, - "geoPointValue": { - "type": "google.type.LatLng", - "id": 8 + "resumeType": { + "oneof": [ + "resumeToken", + "readTime" + ] + } + }, + "fields": { + "query": { + "type": "QueryTarget", + "id": 2 }, - "arrayValue": { - "type": "ArrayValue", - "id": 9 + "documents": { + "type": "DocumentsTarget", + "id": 3 }, - "mapValue": { - "type": "MapValue", - "id": 6 + "resumeToken": { + "type": "bytes", + "id": 4 }, - "fieldReferenceValue": { - "type": "string", - "id": 19 + "readTime": { + "type": "google.protobuf.Timestamp", + "id": 11 }, - "functionValue": { - "type": "Function", - "id": 20 + "targetId": { + "type": "int32", + "id": 5 }, - "pipelineValue": { - "type": "Pipeline", - "id": 21 - } - } - }, - "ArrayValue": { - "fields": { - "values": { - "rule": "repeated", - "type": "Value", - "id": 1 + "once": { + "type": "bool", + "id": 6 + }, + "expectedCount": { + "type": "google.protobuf.Int32Value", + "id": 12 } - } - }, - "MapValue": { - "fields": { - "fields": { - "keyType": "string", - "type": "Value", - "id": 1 + }, + "nested": { + "DocumentsTarget": { + "fields": { + "documents": { + "rule": "repeated", + "type": "string", + "id": 2 + } + } + }, + "QueryTarget": { + "oneofs": { + "queryType": { + "oneof": [ + "structuredQuery" + ] + } + }, + "fields": { + "parent": { + "type": "string", + "id": 1 + }, + "structuredQuery": { + "type": "StructuredQuery", + "id": 2 + } + } } } }, - "Function": { + "TargetChange": { "fields": { - "name": { - "type": "string", + "targetChangeType": { + "type": "TargetChangeType", "id": 1 }, - "args": { + "targetIds": { "rule": "repeated", - "type": "Value", + "type": "int32", "id": 2 }, - "options": { - "keyType": "string", - "type": "Value", + "cause": { + "type": "google.rpc.Status", "id": 3 - } - } - }, - "Pipeline": { - "fields": { - "stages": { - "rule": "repeated", - "type": "Stage", - "id": 1 + }, + "resumeToken": { + "type": "bytes", + "id": 4 + }, + "readTime": { + "type": "google.protobuf.Timestamp", + "id": 6 } }, "nested": { - "Stage": { - "fields": { - "name": { - "type": "string", - "id": 1 - }, - "args": { - "rule": "repeated", - "type": "Value", - "id": 2 - }, - "options": { - "keyType": "string", - "type": "Value", - "id": 3 - } + "TargetChangeType": { + "values": { + "NO_CHANGE": 0, + "ADD": 1, + "REMOVE": 2, + "CURRENT": 3, + "RESET": 4 + } + } + } + }, + "ListCollectionIdsRequest": { + "oneofs": { + "consistencySelector": { + "oneof": [ + "readTime" + ] + } + }, + "fields": { + "parent": { + "type": "string", + "id": 1, + "options": { + "(google.api.field_behavior)": "REQUIRED" } + }, + "pageSize": { + "type": "int32", + "id": 2 + }, + "pageToken": { + "type": "string", + "id": 3 + }, + "readTime": { + "type": "google.protobuf.Timestamp", + "id": 4 } } }, - "BitSequence": { + "ListCollectionIdsResponse": { "fields": { - "bitmap": { - "type": "bytes", + "collectionIds": { + "rule": "repeated", + "type": "string", "id": 1 }, - "padding": { - "type": "int32", + "nextPageToken": { + "type": "string", "id": 2 } } }, - "BloomFilter": { + "BatchWriteRequest": { "fields": { - "bits": { - "type": "BitSequence", - "id": 1 + "database": { + "type": "string", + "id": 1, + "options": { + "(google.api.field_behavior)": "REQUIRED" + } }, - "hashCount": { - "type": "int32", + "writes": { + "rule": "repeated", + "type": "Write", "id": 2 + }, + "labels": { + "keyType": "string", + "type": "string", + "id": 3 } } }, - "DocumentMask": { + "BatchWriteResponse": { "fields": { - "fieldPaths": { + "writeResults": { "rule": "repeated", - "type": "string", + "type": "WriteResult", "id": 1 + }, + "status": { + "rule": "repeated", + "type": "google.rpc.Status", + "id": 2 } } }, - "Precondition": { - "oneofs": { - "conditionType": { - "oneof": [ - "exists", - "updateTime" - ] - } - }, + "StructuredPipeline": { "fields": { - "exists": { - "type": "bool", + "pipeline": { + "type": "Pipeline", "id": 1 }, - "updateTime": { - "type": "google.protobuf.Timestamp", + "options": { + "keyType": "string", + "type": "Value", "id": 2 } } }, - "TransactionOptions": { - "oneofs": { - "mode": { - "oneof": [ - "readOnly", - "readWrite" - ] - } - }, + "StructuredQuery": { "fields": { - "readOnly": { - "type": "ReadOnly", + "select": { + "type": "Projection", + "id": 1 + }, + "from": { + "rule": "repeated", + "type": "CollectionSelector", "id": 2 }, - "readWrite": { - "type": "ReadWrite", + "where": { + "type": "Filter", "id": 3 + }, + "orderBy": { + "rule": "repeated", + "type": "Order", + "id": 4 + }, + "startAt": { + "type": "Cursor", + "id": 7 + }, + "endAt": { + "type": "Cursor", + "id": 8 + }, + "offset": { + "type": "int32", + "id": 6 + }, + "limit": { + "type": "google.protobuf.Int32Value", + "id": 5 + }, + "findNearest": { + "type": "FindNearest", + "id": 9, + "options": { + "(google.api.field_behavior)": "OPTIONAL" + } } }, "nested": { - "ReadWrite": { + "CollectionSelector": { "fields": { - "retryTransaction": { - "type": "bytes", - "id": 1 + "collectionId": { + "type": "string", + "id": 2 + }, + "allDescendants": { + "type": "bool", + "id": 3 } } }, - "ReadOnly": { + "Filter": { "oneofs": { - "consistencySelector": { + "filterType": { "oneof": [ - "readTime" + "compositeFilter", + "fieldFilter", + "unaryFilter" ] } }, "fields": { - "readTime": { - "type": "google.protobuf.Timestamp", - "id": 2 - } - } - } - } - }, - "Firestore": { - "options": { - "(google.api.default_host)": "firestore.googleapis.com", - "(google.api.oauth_scopes)": "https://www.googleapis.com/auth/cloud-platform,https://www.googleapis.com/auth/datastore" - }, - "methods": { - "GetDocument": { - "requestType": "GetDocumentRequest", - "responseType": "Document", - "options": { - "(google.api.http).get": "/v1/{name=projects/*/databases/*/documents/*/**}" - }, - "parsedOptions": [ - { - "(google.api.http)": { - "get": "/v1/{name=projects/*/databases/*/documents/*/**}" - } - } - ] - }, - "ListDocuments": { - "requestType": "ListDocumentsRequest", - "responseType": "ListDocumentsResponse", - "options": { - "(google.api.http).get": "/v1/{parent=projects/*/databases/*/documents/*/**}/{collection_id}", - "(google.api.http).additional_bindings.get": "/v1/{parent=projects/*/databases/*/documents}/{collection_id}" - }, - "parsedOptions": [ - { - "(google.api.http)": { - "get": "/v1/{parent=projects/*/databases/*/documents/*/**}/{collection_id}", - "additional_bindings": { - "get": "/v1/{parent=projects/*/databases/*/documents}/{collection_id}" - } - } - } - ] - }, - "UpdateDocument": { - "requestType": "UpdateDocumentRequest", - "responseType": "Document", - "options": { - "(google.api.http).patch": "/v1/{document.name=projects/*/databases/*/documents/*/**}", - "(google.api.http).body": "document", - "(google.api.method_signature)": "document,update_mask" - }, - "parsedOptions": [ - { - "(google.api.http)": { - "patch": "/v1/{document.name=projects/*/databases/*/documents/*/**}", - "body": "document" - } + "compositeFilter": { + "type": "CompositeFilter", + "id": 1 }, - { - "(google.api.method_signature)": "document,update_mask" - } - ] - }, - "DeleteDocument": { - "requestType": "DeleteDocumentRequest", - "responseType": "google.protobuf.Empty", - "options": { - "(google.api.http).delete": "/v1/{name=projects/*/databases/*/documents/*/**}", - "(google.api.method_signature)": "name" - }, - "parsedOptions": [ - { - "(google.api.http)": { - "delete": "/v1/{name=projects/*/databases/*/documents/*/**}" - } + "fieldFilter": { + "type": "FieldFilter", + "id": 2 }, - { - "(google.api.method_signature)": "name" + "unaryFilter": { + "type": "UnaryFilter", + "id": 3 } - ] + } }, - "BatchGetDocuments": { - "requestType": "BatchGetDocumentsRequest", - "responseType": "BatchGetDocumentsResponse", - "responseStream": true, - "options": { - "(google.api.http).post": "/v1/{database=projects/*/databases/*}/documents:batchGet", - "(google.api.http).body": "*" + "CompositeFilter": { + "fields": { + "op": { + "type": "Operator", + "id": 1 + }, + "filters": { + "rule": "repeated", + "type": "Filter", + "id": 2 + } }, - "parsedOptions": [ - { - "(google.api.http)": { - "post": "/v1/{database=projects/*/databases/*}/documents:batchGet", - "body": "*" + "nested": { + "Operator": { + "values": { + "OPERATOR_UNSPECIFIED": 0, + "AND": 1, + "OR": 2 } } - ] + } }, - "BeginTransaction": { - "requestType": "BeginTransactionRequest", - "responseType": "BeginTransactionResponse", - "options": { - "(google.api.http).post": "/v1/{database=projects/*/databases/*}/documents:beginTransaction", - "(google.api.http).body": "*", - "(google.api.method_signature)": "database" - }, - "parsedOptions": [ - { - "(google.api.http)": { - "post": "/v1/{database=projects/*/databases/*}/documents:beginTransaction", - "body": "*" - } + "FieldFilter": { + "fields": { + "field": { + "type": "FieldReference", + "id": 1 }, - { - "(google.api.method_signature)": "database" + "op": { + "type": "Operator", + "id": 2 + }, + "value": { + "type": "Value", + "id": 3 } - ] - }, - "Commit": { - "requestType": "CommitRequest", - "responseType": "CommitResponse", - "options": { - "(google.api.http).post": "/v1/{database=projects/*/databases/*}/documents:commit", - "(google.api.http).body": "*", - "(google.api.method_signature)": "database,writes" }, - "parsedOptions": [ - { - "(google.api.http)": { - "post": "/v1/{database=projects/*/databases/*}/documents:commit", - "body": "*" + "nested": { + "Operator": { + "values": { + "OPERATOR_UNSPECIFIED": 0, + "LESS_THAN": 1, + "LESS_THAN_OR_EQUAL": 2, + "GREATER_THAN": 3, + "GREATER_THAN_OR_EQUAL": 4, + "EQUAL": 5, + "NOT_EQUAL": 6, + "ARRAY_CONTAINS": 7, + "IN": 8, + "ARRAY_CONTAINS_ANY": 9, + "NOT_IN": 10 } - }, - { - "(google.api.method_signature)": "database,writes" } - ] + } }, - "Rollback": { - "requestType": "RollbackRequest", - "responseType": "google.protobuf.Empty", - "options": { - "(google.api.http).post": "/v1/{database=projects/*/databases/*}/documents:rollback", - "(google.api.http).body": "*", - "(google.api.method_signature)": "database,transaction" + "UnaryFilter": { + "oneofs": { + "operandType": { + "oneof": [ + "field" + ] + } }, - "parsedOptions": [ - { - "(google.api.http)": { - "post": "/v1/{database=projects/*/databases/*}/documents:rollback", - "body": "*" - } + "fields": { + "op": { + "type": "Operator", + "id": 1 }, - { - "(google.api.method_signature)": "database,transaction" + "field": { + "type": "FieldReference", + "id": 2 } - ] - }, - "RunQuery": { - "requestType": "RunQueryRequest", - "responseType": "RunQueryResponse", - "responseStream": true, - "options": { - "(google.api.http).post": "/v1/{parent=projects/*/databases/*/documents}:runQuery", - "(google.api.http).body": "*", - "(google.api.http).additional_bindings.post": "/v1/{parent=projects/*/databases/*/documents/*/**}:runQuery", - "(google.api.http).additional_bindings.body": "*" }, - "parsedOptions": [ - { - "(google.api.http)": { - "post": "/v1/{parent=projects/*/databases/*/documents}:runQuery", - "body": "*", - "additional_bindings": { - "post": "/v1/{parent=projects/*/databases/*/documents/*/**}:runQuery", - "body": "*" - } + "nested": { + "Operator": { + "values": { + "OPERATOR_UNSPECIFIED": 0, + "IS_NAN": 2, + "IS_NULL": 3, + "IS_NOT_NAN": 4, + "IS_NOT_NULL": 5 } } - ] + } }, - "ExecutePipeline": { - "requestType": "ExecutePipelineRequest", - "responseType": "ExecutePipelineResponse", - "responseStream": true, - "options": { - "(google.api.http).post": "/v1/{database=projects/*/databases/*}/documents:executePipeline", - "(google.api.http).body": "*" - }, - "parsedOptions": [ - { - "(google.api.http)": { - "post": "/v1/{database=projects/*/databases/*}/documents:executePipeline", - "body": "*" - } + "Order": { + "fields": { + "field": { + "type": "FieldReference", + "id": 1 + }, + "direction": { + "type": "Direction", + "id": 2 } - ] + } }, - "RunAggregationQuery": { - "requestType": "RunAggregationQueryRequest", - "responseType": "RunAggregationQueryResponse", - "responseStream": true, - "options": { - "(google.api.http).post": "/v1/{parent=projects/*/databases/*/documents}:runAggregationQuery", - "(google.api.http).body": "*", - "(google.api.http).additional_bindings.post": "/v1/{parent=projects/*/databases/*/documents/*/**}:runAggregationQuery", - "(google.api.http).additional_bindings.body": "*" - }, - "parsedOptions": [ - { - "(google.api.http)": { - "post": "/v1/{parent=projects/*/databases/*/documents}:runAggregationQuery", - "body": "*", - "additional_bindings": { - "post": "/v1/{parent=projects/*/databases/*/documents/*/**}:runAggregationQuery", - "body": "*" - } - } + "Direction": { + "values": { + "DIRECTION_UNSPECIFIED": 0, + "ASCENDING": 1, + "DESCENDING": 2 + } + }, + "FieldReference": { + "fields": { + "fieldPath": { + "type": "string", + "id": 2 } - ] + } }, - "PartitionQuery": { - "requestType": "PartitionQueryRequest", - "responseType": "PartitionQueryResponse", - "options": { - "(google.api.http).post": "/v1/{parent=projects/*/databases/*/documents}:partitionQuery", - "(google.api.http).body": "*", - "(google.api.http).additional_bindings.post": "/v1/{parent=projects/*/databases/*/documents/*/**}:partitionQuery", - "(google.api.http).additional_bindings.body": "*" - }, - "parsedOptions": [ - { - "(google.api.http)": { - "post": "/v1/{parent=projects/*/databases/*/documents}:partitionQuery", - "body": "*", - "additional_bindings": { - "post": "/v1/{parent=projects/*/databases/*/documents/*/**}:partitionQuery", - "body": "*" - } - } + "Projection": { + "fields": { + "fields": { + "rule": "repeated", + "type": "FieldReference", + "id": 2 } - ] + } }, - "Write": { - "requestType": "WriteRequest", - "requestStream": true, - "responseType": "WriteResponse", - "responseStream": true, - "options": { - "(google.api.http).post": "/v1/{database=projects/*/databases/*}/documents:write", - "(google.api.http).body": "*" - }, - "parsedOptions": [ - { - "(google.api.http)": { - "post": "/v1/{database=projects/*/databases/*}/documents:write", - "body": "*" + "FindNearest": { + "fields": { + "vectorField": { + "type": "FieldReference", + "id": 1, + "options": { + "(google.api.field_behavior)": "REQUIRED" + } + }, + "queryVector": { + "type": "Value", + "id": 2, + "options": { + "(google.api.field_behavior)": "REQUIRED" + } + }, + "distanceMeasure": { + "type": "DistanceMeasure", + "id": 3, + "options": { + "(google.api.field_behavior)": "REQUIRED" } - } - ] - }, - "Listen": { - "requestType": "ListenRequest", - "requestStream": true, - "responseType": "ListenResponse", - "responseStream": true, - "options": { - "(google.api.http).post": "/v1/{database=projects/*/databases/*}/documents:listen", - "(google.api.http).body": "*" - }, - "parsedOptions": [ - { - "(google.api.http)": { - "post": "/v1/{database=projects/*/databases/*}/documents:listen", - "body": "*" + }, + "limit": { + "type": "google.protobuf.Int32Value", + "id": 4, + "options": { + "(google.api.field_behavior)": "REQUIRED" } - } - ] - }, - "ListCollectionIds": { - "requestType": "ListCollectionIdsRequest", - "responseType": "ListCollectionIdsResponse", - "options": { - "(google.api.http).post": "/v1/{parent=projects/*/databases/*/documents}:listCollectionIds", - "(google.api.http).body": "*", - "(google.api.http).additional_bindings.post": "/v1/{parent=projects/*/databases/*/documents/*/**}:listCollectionIds", - "(google.api.http).additional_bindings.body": "*", - "(google.api.method_signature)": "parent" - }, - "parsedOptions": [ - { - "(google.api.http)": { - "post": "/v1/{parent=projects/*/databases/*/documents}:listCollectionIds", - "body": "*", - "additional_bindings": { - "post": "/v1/{parent=projects/*/databases/*/documents/*/**}:listCollectionIds", - "body": "*" - } + }, + "distanceResultField": { + "type": "string", + "id": 5, + "options": { + "(google.api.field_behavior)": "OPTIONAL" } }, - { - "(google.api.method_signature)": "parent" - } - ] - }, - "BatchWrite": { - "requestType": "BatchWriteRequest", - "responseType": "BatchWriteResponse", - "options": { - "(google.api.http).post": "/v1/{database=projects/*/databases/*}/documents:batchWrite", - "(google.api.http).body": "*" - }, - "parsedOptions": [ - { - "(google.api.http)": { - "post": "/v1/{database=projects/*/databases/*}/documents:batchWrite", - "body": "*" + "distanceThreshold": { + "type": "google.protobuf.DoubleValue", + "id": 6, + "options": { + "(google.api.field_behavior)": "OPTIONAL" } } - ] - }, - "CreateDocument": { - "requestType": "CreateDocumentRequest", - "responseType": "Document", - "options": { - "(google.api.http).post": "/v1/{parent=projects/*/databases/*/documents/**}/{collection_id}", - "(google.api.http).body": "document" }, - "parsedOptions": [ - { - "(google.api.http)": { - "post": "/v1/{parent=projects/*/databases/*/documents/**}/{collection_id}", - "body": "document" + "nested": { + "DistanceMeasure": { + "values": { + "DISTANCE_MEASURE_UNSPECIFIED": 0, + "EUCLIDEAN": 1, + "COSINE": 2, + "DOT_PRODUCT": 3 } } - ] - } - } - }, - "GetDocumentRequest": { - "oneofs": { - "consistencySelector": { - "oneof": [ - "transaction", - "readTime" - ] - } - }, - "fields": { - "name": { - "type": "string", - "id": 1, - "options": { - "(google.api.field_behavior)": "REQUIRED" } - }, - "mask": { - "type": "DocumentMask", - "id": 2 - }, - "transaction": { - "type": "bytes", - "id": 3 - }, - "readTime": { - "type": "google.protobuf.Timestamp", - "id": 5 } } }, - "ListDocumentsRequest": { + "StructuredAggregationQuery": { "oneofs": { - "consistencySelector": { + "queryType": { "oneof": [ - "transaction", - "readTime" + "structuredQuery" ] } }, "fields": { - "parent": { - "type": "string", - "id": 1, - "options": { - "(google.api.field_behavior)": "REQUIRED" - } - }, - "collectionId": { - "type": "string", - "id": 2, - "options": { - "(google.api.field_behavior)": "OPTIONAL" - } + "structuredQuery": { + "type": "StructuredQuery", + "id": 1 }, - "pageSize": { - "type": "int32", + "aggregations": { + "rule": "repeated", + "type": "Aggregation", "id": 3, "options": { "(google.api.field_behavior)": "OPTIONAL" } - }, - "pageToken": { - "type": "string", - "id": 4, - "options": { - "(google.api.field_behavior)": "OPTIONAL" - } - }, - "orderBy": { - "type": "string", - "id": 6, - "options": { - "(google.api.field_behavior)": "OPTIONAL" - } - }, - "mask": { - "type": "DocumentMask", - "id": 7, - "options": { - "(google.api.field_behavior)": "OPTIONAL" + } + }, + "nested": { + "Aggregation": { + "oneofs": { + "operator": { + "oneof": [ + "count", + "sum", + "avg" + ] + } + }, + "fields": { + "count": { + "type": "Count", + "id": 1 + }, + "sum": { + "type": "Sum", + "id": 2 + }, + "avg": { + "type": "Avg", + "id": 3 + }, + "alias": { + "type": "string", + "id": 7, + "options": { + "(google.api.field_behavior)": "OPTIONAL" + } + } + }, + "nested": { + "Count": { + "fields": { + "upTo": { + "type": "google.protobuf.Int64Value", + "id": 1, + "options": { + "(google.api.field_behavior)": "OPTIONAL" + } + } + } + }, + "Sum": { + "fields": { + "field": { + "type": "StructuredQuery.FieldReference", + "id": 1 + } + } + }, + "Avg": { + "fields": { + "field": { + "type": "StructuredQuery.FieldReference", + "id": 1 + } + } + } } + } + } + }, + "Cursor": { + "fields": { + "values": { + "rule": "repeated", + "type": "Value", + "id": 1 }, - "transaction": { - "type": "bytes", - "id": 8 - }, - "readTime": { - "type": "google.protobuf.Timestamp", - "id": 10 - }, - "showMissing": { + "before": { + "type": "bool", + "id": 2 + } + } + }, + "ExplainOptions": { + "fields": { + "analyze": { "type": "bool", - "id": 12 + "id": 1, + "options": { + "(google.api.field_behavior)": "OPTIONAL" + } } } }, - "ListDocumentsResponse": { + "ExplainMetrics": { "fields": { - "documents": { - "rule": "repeated", - "type": "Document", + "planSummary": { + "type": "PlanSummary", "id": 1 }, - "nextPageToken": { - "type": "string", + "executionStats": { + "type": "ExecutionStats", "id": 2 } } }, - "CreateDocumentRequest": { + "PlanSummary": { "fields": { - "parent": { - "type": "string", - "id": 1, - "options": { - "(google.api.field_behavior)": "REQUIRED" - } - }, - "collectionId": { - "type": "string", - "id": 2, - "options": { - "(google.api.field_behavior)": "REQUIRED" - } + "indexesUsed": { + "rule": "repeated", + "type": "google.protobuf.Struct", + "id": 1 + } + } + }, + "ExecutionStats": { + "fields": { + "resultsReturned": { + "type": "int64", + "id": 1 }, - "documentId": { - "type": "string", + "executionDuration": { + "type": "google.protobuf.Duration", "id": 3 }, - "document": { - "type": "Document", - "id": 4, - "options": { - "(google.api.field_behavior)": "REQUIRED" - } + "readOperations": { + "type": "int64", + "id": 4 }, - "mask": { - "type": "DocumentMask", + "debugStats": { + "type": "google.protobuf.Struct", "id": 5 } } }, - "UpdateDocumentRequest": { + "Write": { + "oneofs": { + "operation": { + "oneof": [ + "update", + "delete", + "transform" + ] + } + }, "fields": { - "document": { + "update": { "type": "Document", - "id": 1, - "options": { - "(google.api.field_behavior)": "REQUIRED" - } + "id": 1 }, - "updateMask": { - "type": "DocumentMask", + "delete": { + "type": "string", "id": 2 }, - "mask": { + "transform": { + "type": "DocumentTransform", + "id": 6 + }, + "updateMask": { "type": "DocumentMask", "id": 3 }, + "updateTransforms": { + "rule": "repeated", + "type": "DocumentTransform.FieldTransform", + "id": 7 + }, "currentDocument": { "type": "Precondition", "id": 4 } } }, - "DeleteDocumentRequest": { + "DocumentTransform": { "fields": { - "name": { + "document": { "type": "string", - "id": 1, - "options": { - "(google.api.field_behavior)": "REQUIRED" - } + "id": 1 }, - "currentDocument": { - "type": "Precondition", + "fieldTransforms": { + "rule": "repeated", + "type": "FieldTransform", "id": 2 } + }, + "nested": { + "FieldTransform": { + "oneofs": { + "transformType": { + "oneof": [ + "setToServerValue", + "increment", + "maximum", + "minimum", + "appendMissingElements", + "removeAllFromArray" + ] + } + }, + "fields": { + "fieldPath": { + "type": "string", + "id": 1 + }, + "setToServerValue": { + "type": "ServerValue", + "id": 2 + }, + "increment": { + "type": "Value", + "id": 3 + }, + "maximum": { + "type": "Value", + "id": 4 + }, + "minimum": { + "type": "Value", + "id": 5 + }, + "appendMissingElements": { + "type": "ArrayValue", + "id": 6 + }, + "removeAllFromArray": { + "type": "ArrayValue", + "id": 7 + } + }, + "nested": { + "ServerValue": { + "values": { + "SERVER_VALUE_UNSPECIFIED": 0, + "REQUEST_TIME": 1 + } + } + } + } } }, - "BatchGetDocumentsRequest": { - "oneofs": { - "consistencySelector": { - "oneof": [ - "transaction", - "newTransaction", - "readTime" - ] - } - }, + "WriteResult": { "fields": { - "database": { - "type": "string", - "id": 1, - "options": { - "(google.api.field_behavior)": "REQUIRED" - } + "updateTime": { + "type": "google.protobuf.Timestamp", + "id": 1 }, - "documents": { + "transformResults": { "rule": "repeated", - "type": "string", + "type": "Value", "id": 2 - }, - "mask": { - "type": "DocumentMask", - "id": 3 - }, - "transaction": { - "type": "bytes", - "id": 4 - }, - "newTransaction": { - "type": "TransactionOptions", - "id": 5 - }, - "readTime": { - "type": "google.protobuf.Timestamp", - "id": 7 } } }, - "BatchGetDocumentsResponse": { - "oneofs": { - "result": { - "oneof": [ - "found", - "missing" - ] - } - }, + "DocumentChange": { "fields": { - "found": { + "document": { "type": "Document", "id": 1 }, - "missing": { + "targetIds": { + "rule": "repeated", + "type": "int32", + "id": 5 + }, + "removedTargetIds": { + "rule": "repeated", + "type": "int32", + "id": 6 + } + } + }, + "DocumentDelete": { + "fields": { + "document": { "type": "string", - "id": 2 + "id": 1 }, - "transaction": { - "type": "bytes", - "id": 3 + "removedTargetIds": { + "rule": "repeated", + "type": "int32", + "id": 6 }, "readTime": { "type": "google.protobuf.Timestamp", @@ -2368,1788 +2097,2046 @@ } } }, - "BeginTransactionRequest": { + "DocumentRemove": { "fields": { - "database": { + "document": { "type": "string", - "id": 1, - "options": { - "(google.api.field_behavior)": "REQUIRED" - } + "id": 1 }, - "options": { - "type": "TransactionOptions", + "removedTargetIds": { + "rule": "repeated", + "type": "int32", "id": 2 + }, + "readTime": { + "type": "google.protobuf.Timestamp", + "id": 4 } } }, - "BeginTransactionResponse": { + "ExistenceFilter": { "fields": { - "transaction": { - "type": "bytes", + "targetId": { + "type": "int32", "id": 1 - } - } - }, - "CommitRequest": { - "fields": { - "database": { - "type": "string", - "id": 1, - "options": { - "(google.api.field_behavior)": "REQUIRED" - } }, - "writes": { - "rule": "repeated", - "type": "Write", + "count": { + "type": "int32", "id": 2 }, - "transaction": { - "type": "bytes", + "unchangedNames": { + "type": "BloomFilter", "id": 3 } } + } + } + } + } + }, + "api": { + "options": { + "go_package": "google.golang.org/genproto/googleapis/api/annotations;annotations", + "java_multiple_files": true, + "java_outer_classname": "ResourceProto", + "java_package": "com.google.api", + "objc_class_prefix": "GAPI", + "cc_enable_arenas": true + }, + "nested": { + "fieldBehavior": { + "rule": "repeated", + "type": "google.api.FieldBehavior", + "id": 1052, + "extend": "google.protobuf.FieldOptions", + "options": { + "packed": false + } + }, + "FieldBehavior": { + "values": { + "FIELD_BEHAVIOR_UNSPECIFIED": 0, + "OPTIONAL": 1, + "REQUIRED": 2, + "OUTPUT_ONLY": 3, + "INPUT_ONLY": 4, + "IMMUTABLE": 5, + "UNORDERED_LIST": 6, + "NON_EMPTY_DEFAULT": 7, + "IDENTIFIER": 8 + } + }, + "http": { + "type": "HttpRule", + "id": 72295728, + "extend": "google.protobuf.MethodOptions" + }, + "Http": { + "fields": { + "rules": { + "rule": "repeated", + "type": "HttpRule", + "id": 1 + }, + "fullyDecodeReservedExpansion": { + "type": "bool", + "id": 2 + } + } + }, + "HttpRule": { + "oneofs": { + "pattern": { + "oneof": [ + "get", + "put", + "post", + "delete", + "patch", + "custom" + ] + } + }, + "fields": { + "selector": { + "type": "string", + "id": 1 + }, + "get": { + "type": "string", + "id": 2 + }, + "put": { + "type": "string", + "id": 3 + }, + "post": { + "type": "string", + "id": 4 + }, + "delete": { + "type": "string", + "id": 5 + }, + "patch": { + "type": "string", + "id": 6 + }, + "custom": { + "type": "CustomHttpPattern", + "id": 8 + }, + "body": { + "type": "string", + "id": 7 + }, + "responseBody": { + "type": "string", + "id": 12 + }, + "additionalBindings": { + "rule": "repeated", + "type": "HttpRule", + "id": 11 + } + } + }, + "CustomHttpPattern": { + "fields": { + "kind": { + "type": "string", + "id": 1 + }, + "path": { + "type": "string", + "id": 2 + } + } + }, + "methodSignature": { + "rule": "repeated", + "type": "string", + "id": 1051, + "extend": "google.protobuf.MethodOptions" + }, + "defaultHost": { + "type": "string", + "id": 1049, + "extend": "google.protobuf.ServiceOptions" + }, + "oauthScopes": { + "type": "string", + "id": 1050, + "extend": "google.protobuf.ServiceOptions" + }, + "apiVersion": { + "type": "string", + "id": 525000001, + "extend": "google.protobuf.ServiceOptions" + }, + "CommonLanguageSettings": { + "fields": { + "referenceDocsUri": { + "type": "string", + "id": 1, + "options": { + "deprecated": true + } + }, + "destinations": { + "rule": "repeated", + "type": "ClientLibraryDestination", + "id": 2 + } + } + }, + "ClientLibrarySettings": { + "fields": { + "version": { + "type": "string", + "id": 1 + }, + "launchStage": { + "type": "LaunchStage", + "id": 2 + }, + "restNumericEnums": { + "type": "bool", + "id": 3 + }, + "javaSettings": { + "type": "JavaSettings", + "id": 21 + }, + "cppSettings": { + "type": "CppSettings", + "id": 22 + }, + "phpSettings": { + "type": "PhpSettings", + "id": 23 + }, + "pythonSettings": { + "type": "PythonSettings", + "id": 24 + }, + "nodeSettings": { + "type": "NodeSettings", + "id": 25 + }, + "dotnetSettings": { + "type": "DotnetSettings", + "id": 26 + }, + "rubySettings": { + "type": "RubySettings", + "id": 27 + }, + "goSettings": { + "type": "GoSettings", + "id": 28 + } + } + }, + "Publishing": { + "fields": { + "methodSettings": { + "rule": "repeated", + "type": "MethodSettings", + "id": 2 + }, + "newIssueUri": { + "type": "string", + "id": 101 + }, + "documentationUri": { + "type": "string", + "id": 102 + }, + "apiShortName": { + "type": "string", + "id": 103 }, - "CommitResponse": { - "fields": { - "writeResults": { - "rule": "repeated", - "type": "WriteResult", - "id": 1 - }, - "commitTime": { - "type": "google.protobuf.Timestamp", - "id": 2 - } - } + "githubLabel": { + "type": "string", + "id": 104 }, - "RollbackRequest": { - "fields": { - "database": { - "type": "string", - "id": 1, - "options": { - "(google.api.field_behavior)": "REQUIRED" - } - }, - "transaction": { - "type": "bytes", - "id": 2, - "options": { - "(google.api.field_behavior)": "REQUIRED" - } - } - } + "codeownerGithubTeams": { + "rule": "repeated", + "type": "string", + "id": 105 }, - "RunQueryRequest": { - "oneofs": { - "queryType": { - "oneof": [ - "structuredQuery" - ] - }, - "consistencySelector": { - "oneof": [ - "transaction", - "newTransaction", - "readTime" - ] - } - }, - "fields": { - "parent": { - "type": "string", - "id": 1, - "options": { - "(google.api.field_behavior)": "REQUIRED" - } - }, - "structuredQuery": { - "type": "StructuredQuery", - "id": 2 - }, - "transaction": { - "type": "bytes", - "id": 5 - }, - "newTransaction": { - "type": "TransactionOptions", - "id": 6 - }, - "readTime": { - "type": "google.protobuf.Timestamp", - "id": 7 - }, - "explainOptions": { - "type": "ExplainOptions", - "id": 10, - "options": { - "(google.api.field_behavior)": "OPTIONAL" - } - } - } + "docTagPrefix": { + "type": "string", + "id": 106 }, - "RunQueryResponse": { - "oneofs": { - "continuationSelector": { - "oneof": [ - "done" - ] - } - }, - "fields": { - "transaction": { - "type": "bytes", - "id": 2 - }, - "document": { - "type": "Document", - "id": 1 - }, - "readTime": { - "type": "google.protobuf.Timestamp", - "id": 3 - }, - "skippedResults": { - "type": "int32", - "id": 4 - }, - "done": { - "type": "bool", - "id": 6 - }, - "explainMetrics": { - "type": "ExplainMetrics", - "id": 11 - } - } + "organization": { + "type": "ClientLibraryOrganization", + "id": 107 }, - "ExecutePipelineRequest": { - "oneofs": { - "pipelineType": { - "oneof": [ - "structuredPipeline" - ] - }, - "consistencySelector": { - "oneof": [ - "transaction", - "newTransaction", - "readTime" - ] - } - }, - "fields": { - "database": { - "type": "string", - "id": 1, - "options": { - "(google.api.field_behavior)": "REQUIRED" - } - }, - "structuredPipeline": { - "type": "StructuredPipeline", - "id": 2 - }, - "transaction": { - "type": "bytes", - "id": 5 - }, - "newTransaction": { - "type": "TransactionOptions", - "id": 6 - }, - "readTime": { - "type": "google.protobuf.Timestamp", - "id": 7 - } - } + "librarySettings": { + "rule": "repeated", + "type": "ClientLibrarySettings", + "id": 109 }, - "ExecutePipelineResponse": { - "fields": { - "transaction": { - "type": "bytes", - "id": 1 - }, - "results": { - "rule": "repeated", - "type": "Document", - "id": 2 - }, - "executionTime": { - "type": "google.protobuf.Timestamp", - "id": 3 - } - } + "protoReferenceDocumentationUri": { + "type": "string", + "id": 110 }, - "RunAggregationQueryRequest": { - "oneofs": { - "queryType": { - "oneof": [ - "structuredAggregationQuery" - ] - }, - "consistencySelector": { - "oneof": [ - "transaction", - "newTransaction", - "readTime" - ] - } - }, - "fields": { - "parent": { - "type": "string", - "id": 1, - "options": { - "(google.api.field_behavior)": "REQUIRED" - } - }, - "structuredAggregationQuery": { - "type": "StructuredAggregationQuery", - "id": 2 - }, - "transaction": { - "type": "bytes", - "id": 4 - }, - "newTransaction": { - "type": "TransactionOptions", - "id": 5 - }, - "readTime": { - "type": "google.protobuf.Timestamp", - "id": 6 - }, - "explainOptions": { - "type": "ExplainOptions", - "id": 8, - "options": { - "(google.api.field_behavior)": "OPTIONAL" - } - } - } + "restReferenceDocumentationUri": { + "type": "string", + "id": 111 + } + } + }, + "JavaSettings": { + "fields": { + "libraryPackage": { + "type": "string", + "id": 1 + }, + "serviceClassNames": { + "keyType": "string", + "type": "string", + "id": 2 + }, + "common": { + "type": "CommonLanguageSettings", + "id": 3 + } + } + }, + "CppSettings": { + "fields": { + "common": { + "type": "CommonLanguageSettings", + "id": 1 + } + } + }, + "PhpSettings": { + "fields": { + "common": { + "type": "CommonLanguageSettings", + "id": 1 + } + } + }, + "PythonSettings": { + "fields": { + "common": { + "type": "CommonLanguageSettings", + "id": 1 + } + } + }, + "NodeSettings": { + "fields": { + "common": { + "type": "CommonLanguageSettings", + "id": 1 + } + } + }, + "DotnetSettings": { + "fields": { + "common": { + "type": "CommonLanguageSettings", + "id": 1 }, - "RunAggregationQueryResponse": { - "fields": { - "result": { - "type": "AggregationResult", - "id": 1 - }, - "transaction": { - "type": "bytes", - "id": 2 - }, - "readTime": { - "type": "google.protobuf.Timestamp", - "id": 3 - }, - "explainMetrics": { - "type": "ExplainMetrics", - "id": 10 - } - } + "renamedServices": { + "keyType": "string", + "type": "string", + "id": 2 }, - "PartitionQueryRequest": { - "oneofs": { - "queryType": { - "oneof": [ - "structuredQuery" - ] - }, - "consistencySelector": { - "oneof": [ - "readTime" - ] - } - }, - "fields": { - "parent": { - "type": "string", - "id": 1, - "options": { - "(google.api.field_behavior)": "REQUIRED" - } - }, - "structuredQuery": { - "type": "StructuredQuery", - "id": 2 - }, - "partitionCount": { - "type": "int64", - "id": 3 - }, - "pageToken": { - "type": "string", - "id": 4 - }, - "pageSize": { - "type": "int32", - "id": 5 - }, - "readTime": { - "type": "google.protobuf.Timestamp", - "id": 6 - } - } + "renamedResources": { + "keyType": "string", + "type": "string", + "id": 3 }, - "PartitionQueryResponse": { - "fields": { - "partitions": { - "rule": "repeated", - "type": "Cursor", - "id": 1 - }, - "nextPageToken": { - "type": "string", - "id": 2 - } - } + "ignoredResources": { + "rule": "repeated", + "type": "string", + "id": 4 }, - "WriteRequest": { - "fields": { - "database": { - "type": "string", - "id": 1, - "options": { - "(google.api.field_behavior)": "REQUIRED" - } - }, - "streamId": { - "type": "string", - "id": 2 - }, - "writes": { - "rule": "repeated", - "type": "Write", - "id": 3 - }, - "streamToken": { - "type": "bytes", - "id": 4 - }, - "labels": { - "keyType": "string", - "type": "string", - "id": 5 - } - } + "forcedNamespaceAliases": { + "rule": "repeated", + "type": "string", + "id": 5 }, - "WriteResponse": { - "fields": { - "streamId": { - "type": "string", - "id": 1 - }, - "streamToken": { - "type": "bytes", - "id": 2 - }, - "writeResults": { - "rule": "repeated", - "type": "WriteResult", - "id": 3 - }, - "commitTime": { - "type": "google.protobuf.Timestamp", - "id": 4 - } - } + "handwrittenSignatures": { + "rule": "repeated", + "type": "string", + "id": 6 + } + } + }, + "RubySettings": { + "fields": { + "common": { + "type": "CommonLanguageSettings", + "id": 1 + } + } + }, + "GoSettings": { + "fields": { + "common": { + "type": "CommonLanguageSettings", + "id": 1 + } + } + }, + "MethodSettings": { + "fields": { + "selector": { + "type": "string", + "id": 1 }, - "ListenRequest": { - "oneofs": { - "targetChange": { - "oneof": [ - "addTarget", - "removeTarget" - ] - } - }, - "fields": { - "database": { - "type": "string", - "id": 1, - "options": { - "(google.api.field_behavior)": "REQUIRED" - } - }, - "addTarget": { - "type": "Target", - "id": 2 - }, - "removeTarget": { - "type": "int32", - "id": 3 - }, - "labels": { - "keyType": "string", - "type": "string", - "id": 4 - } - } + "longRunning": { + "type": "LongRunning", + "id": 2 }, - "ListenResponse": { - "oneofs": { - "responseType": { - "oneof": [ - "targetChange", - "documentChange", - "documentDelete", - "documentRemove", - "filter" - ] - } - }, + "autoPopulatedFields": { + "rule": "repeated", + "type": "string", + "id": 3 + } + }, + "nested": { + "LongRunning": { "fields": { - "targetChange": { - "type": "TargetChange", + "initialPollDelay": { + "type": "google.protobuf.Duration", + "id": 1 + }, + "pollDelayMultiplier": { + "type": "float", "id": 2 }, - "documentChange": { - "type": "DocumentChange", + "maxPollDelay": { + "type": "google.protobuf.Duration", "id": 3 }, - "documentDelete": { - "type": "DocumentDelete", + "totalPollTimeout": { + "type": "google.protobuf.Duration", "id": 4 - }, - "documentRemove": { - "type": "DocumentRemove", - "id": 6 - }, - "filter": { - "type": "ExistenceFilter", - "id": 5 } } + } + } + }, + "ClientLibraryOrganization": { + "values": { + "CLIENT_LIBRARY_ORGANIZATION_UNSPECIFIED": 0, + "CLOUD": 1, + "ADS": 2, + "PHOTOS": 3, + "STREET_VIEW": 4, + "SHOPPING": 5, + "GEO": 6, + "GENERATIVE_AI": 7 + } + }, + "ClientLibraryDestination": { + "values": { + "CLIENT_LIBRARY_DESTINATION_UNSPECIFIED": 0, + "GITHUB": 10, + "PACKAGE_MANAGER": 20 + } + }, + "LaunchStage": { + "values": { + "LAUNCH_STAGE_UNSPECIFIED": 0, + "UNIMPLEMENTED": 6, + "PRELAUNCH": 7, + "EARLY_ACCESS": 1, + "ALPHA": 2, + "BETA": 3, + "GA": 4, + "DEPRECATED": 5 + } + }, + "resourceReference": { + "type": "google.api.ResourceReference", + "id": 1055, + "extend": "google.protobuf.FieldOptions" + }, + "resourceDefinition": { + "rule": "repeated", + "type": "google.api.ResourceDescriptor", + "id": 1053, + "extend": "google.protobuf.FileOptions" + }, + "resource": { + "type": "google.api.ResourceDescriptor", + "id": 1053, + "extend": "google.protobuf.MessageOptions" + }, + "ResourceDescriptor": { + "fields": { + "type": { + "type": "string", + "id": 1 }, - "Target": { - "oneofs": { - "targetType": { - "oneof": [ - "query", - "documents" - ] - }, - "resumeType": { - "oneof": [ - "resumeToken", - "readTime" - ] - } - }, - "fields": { - "query": { - "type": "QueryTarget", - "id": 2 - }, - "documents": { - "type": "DocumentsTarget", - "id": 3 - }, - "resumeToken": { - "type": "bytes", - "id": 4 - }, - "readTime": { - "type": "google.protobuf.Timestamp", - "id": 11 - }, - "targetId": { - "type": "int32", - "id": 5 - }, - "once": { - "type": "bool", - "id": 6 - }, - "expectedCount": { - "type": "google.protobuf.Int32Value", - "id": 12 - } - }, - "nested": { - "DocumentsTarget": { - "fields": { - "documents": { - "rule": "repeated", - "type": "string", - "id": 2 - } - } - }, - "QueryTarget": { - "oneofs": { - "queryType": { - "oneof": [ - "structuredQuery" - ] - } - }, - "fields": { - "parent": { - "type": "string", - "id": 1 - }, - "structuredQuery": { - "type": "StructuredQuery", - "id": 2 - } - } - } + "pattern": { + "rule": "repeated", + "type": "string", + "id": 2 + }, + "nameField": { + "type": "string", + "id": 3 + }, + "history": { + "type": "History", + "id": 4 + }, + "plural": { + "type": "string", + "id": 5 + }, + "singular": { + "type": "string", + "id": 6 + }, + "style": { + "rule": "repeated", + "type": "Style", + "id": 10 + } + }, + "nested": { + "History": { + "values": { + "HISTORY_UNSPECIFIED": 0, + "ORIGINALLY_SINGLE_PATTERN": 1, + "FUTURE_MULTI_PATTERN": 2 + } + }, + "Style": { + "values": { + "STYLE_UNSPECIFIED": 0, + "DECLARATIVE_FRIENDLY": 1 + } + } + } + }, + "ResourceReference": { + "fields": { + "type": { + "type": "string", + "id": 1 + }, + "childType": { + "type": "string", + "id": 2 + } + } + } + } + }, + "protobuf": { + "options": { + "go_package": "google.golang.org/protobuf/types/descriptorpb", + "java_package": "com.google.protobuf", + "java_outer_classname": "DescriptorProtos", + "csharp_namespace": "Google.Protobuf.Reflection", + "objc_class_prefix": "GPB", + "cc_enable_arenas": true, + "optimize_for": "SPEED" + }, + "nested": { + "FileDescriptorSet": { + "fields": { + "file": { + "rule": "repeated", + "type": "FileDescriptorProto", + "id": 1 + } + } + }, + "Edition": { + "values": { + "EDITION_UNKNOWN": 0, + "EDITION_PROTO2": 998, + "EDITION_PROTO3": 999, + "EDITION_2023": 1000, + "EDITION_2024": 1001, + "EDITION_1_TEST_ONLY": 1, + "EDITION_2_TEST_ONLY": 2, + "EDITION_99997_TEST_ONLY": 99997, + "EDITION_99998_TEST_ONLY": 99998, + "EDITION_99999_TEST_ONLY": 99999, + "EDITION_MAX": 2147483647 + } + }, + "FileDescriptorProto": { + "fields": { + "name": { + "type": "string", + "id": 1 + }, + "package": { + "type": "string", + "id": 2 + }, + "dependency": { + "rule": "repeated", + "type": "string", + "id": 3 + }, + "publicDependency": { + "rule": "repeated", + "type": "int32", + "id": 10, + "options": { + "packed": false } }, - "TargetChange": { - "fields": { - "targetChangeType": { - "type": "TargetChangeType", - "id": 1 - }, - "targetIds": { - "rule": "repeated", - "type": "int32", - "id": 2 - }, - "cause": { - "type": "google.rpc.Status", - "id": 3 - }, - "resumeToken": { - "type": "bytes", - "id": 4 - }, - "readTime": { - "type": "google.protobuf.Timestamp", - "id": 6 - } - }, - "nested": { - "TargetChangeType": { - "values": { - "NO_CHANGE": 0, - "ADD": 1, - "REMOVE": 2, - "CURRENT": 3, - "RESET": 4 - } - } + "weakDependency": { + "rule": "repeated", + "type": "int32", + "id": 11, + "options": { + "packed": false } }, - "ListCollectionIdsRequest": { - "oneofs": { - "consistencySelector": { - "oneof": [ - "readTime" - ] - } - }, + "messageType": { + "rule": "repeated", + "type": "DescriptorProto", + "id": 4 + }, + "enumType": { + "rule": "repeated", + "type": "EnumDescriptorProto", + "id": 5 + }, + "service": { + "rule": "repeated", + "type": "ServiceDescriptorProto", + "id": 6 + }, + "extension": { + "rule": "repeated", + "type": "FieldDescriptorProto", + "id": 7 + }, + "options": { + "type": "FileOptions", + "id": 8 + }, + "sourceCodeInfo": { + "type": "SourceCodeInfo", + "id": 9 + }, + "syntax": { + "type": "string", + "id": 12 + }, + "edition": { + "type": "Edition", + "id": 14 + } + } + }, + "DescriptorProto": { + "fields": { + "name": { + "type": "string", + "id": 1 + }, + "field": { + "rule": "repeated", + "type": "FieldDescriptorProto", + "id": 2 + }, + "extension": { + "rule": "repeated", + "type": "FieldDescriptorProto", + "id": 6 + }, + "nestedType": { + "rule": "repeated", + "type": "DescriptorProto", + "id": 3 + }, + "enumType": { + "rule": "repeated", + "type": "EnumDescriptorProto", + "id": 4 + }, + "extensionRange": { + "rule": "repeated", + "type": "ExtensionRange", + "id": 5 + }, + "oneofDecl": { + "rule": "repeated", + "type": "OneofDescriptorProto", + "id": 8 + }, + "options": { + "type": "MessageOptions", + "id": 7 + }, + "reservedRange": { + "rule": "repeated", + "type": "ReservedRange", + "id": 9 + }, + "reservedName": { + "rule": "repeated", + "type": "string", + "id": 10 + } + }, + "nested": { + "ExtensionRange": { "fields": { - "parent": { - "type": "string", - "id": 1, - "options": { - "(google.api.field_behavior)": "REQUIRED" - } + "start": { + "type": "int32", + "id": 1 }, - "pageSize": { + "end": { "type": "int32", "id": 2 }, - "pageToken": { - "type": "string", + "options": { + "type": "ExtensionRangeOptions", "id": 3 - }, - "readTime": { - "type": "google.protobuf.Timestamp", - "id": 4 } } }, - "ListCollectionIdsResponse": { + "ReservedRange": { "fields": { - "collectionIds": { - "rule": "repeated", - "type": "string", + "start": { + "type": "int32", "id": 1 }, - "nextPageToken": { - "type": "string", + "end": { + "type": "int32", "id": 2 } } + } + } + }, + "ExtensionRangeOptions": { + "fields": { + "uninterpretedOption": { + "rule": "repeated", + "type": "UninterpretedOption", + "id": 999 }, - "BatchWriteRequest": { - "fields": { - "database": { - "type": "string", - "id": 1, - "options": { - "(google.api.field_behavior)": "REQUIRED" - } - }, - "writes": { - "rule": "repeated", - "type": "Write", - "id": 2 - }, - "labels": { - "keyType": "string", - "type": "string", - "id": 3 - } + "declaration": { + "rule": "repeated", + "type": "Declaration", + "id": 2, + "options": { + "retention": "RETENTION_SOURCE" } }, - "BatchWriteResponse": { - "fields": { - "writeResults": { - "rule": "repeated", - "type": "WriteResult", - "id": 1 - }, - "status": { - "rule": "repeated", - "type": "google.rpc.Status", - "id": 2 - } - } + "features": { + "type": "FeatureSet", + "id": 50 }, - "StructuredPipeline": { - "fields": { - "pipeline": { - "type": "Pipeline", - "id": 1 - }, - "options": { - "keyType": "string", - "type": "Value", - "id": 2 - } + "verification": { + "type": "VerificationState", + "id": 3, + "options": { + "default": "UNVERIFIED", + "retention": "RETENTION_SOURCE" } - }, - "StructuredQuery": { + } + }, + "extensions": [ + [ + 1000, + 536870911 + ] + ], + "nested": { + "Declaration": { "fields": { - "select": { - "type": "Projection", + "number": { + "type": "int32", "id": 1 }, - "from": { - "rule": "repeated", - "type": "CollectionSelector", + "fullName": { + "type": "string", "id": 2 }, - "where": { - "type": "Filter", + "type": { + "type": "string", "id": 3 }, - "orderBy": { - "rule": "repeated", - "type": "Order", - "id": 4 - }, - "startAt": { - "type": "Cursor", - "id": 7 - }, - "endAt": { - "type": "Cursor", - "id": 8 - }, - "offset": { - "type": "int32", - "id": 6 - }, - "limit": { - "type": "google.protobuf.Int32Value", + "reserved": { + "type": "bool", "id": 5 }, - "findNearest": { - "type": "FindNearest", - "id": 9, - "options": { - "(google.api.field_behavior)": "OPTIONAL" - } + "repeated": { + "type": "bool", + "id": 6 } }, - "nested": { - "CollectionSelector": { - "fields": { - "collectionId": { - "type": "string", - "id": 2 - }, - "allDescendants": { - "type": "bool", - "id": 3 - } - } - }, - "Filter": { - "oneofs": { - "filterType": { - "oneof": [ - "compositeFilter", - "fieldFilter", - "unaryFilter" - ] - } - }, - "fields": { - "compositeFilter": { - "type": "CompositeFilter", - "id": 1 - }, - "fieldFilter": { - "type": "FieldFilter", - "id": 2 - }, - "unaryFilter": { - "type": "UnaryFilter", - "id": 3 - } - } - }, - "CompositeFilter": { - "fields": { - "op": { - "type": "Operator", - "id": 1 - }, - "filters": { - "rule": "repeated", - "type": "Filter", - "id": 2 - } - }, - "nested": { - "Operator": { - "values": { - "OPERATOR_UNSPECIFIED": 0, - "AND": 1, - "OR": 2 - } - } - } - }, - "FieldFilter": { - "fields": { - "field": { - "type": "FieldReference", - "id": 1 - }, - "op": { - "type": "Operator", - "id": 2 - }, - "value": { - "type": "Value", - "id": 3 - } - }, - "nested": { - "Operator": { - "values": { - "OPERATOR_UNSPECIFIED": 0, - "LESS_THAN": 1, - "LESS_THAN_OR_EQUAL": 2, - "GREATER_THAN": 3, - "GREATER_THAN_OR_EQUAL": 4, - "EQUAL": 5, - "NOT_EQUAL": 6, - "ARRAY_CONTAINS": 7, - "IN": 8, - "ARRAY_CONTAINS_ANY": 9, - "NOT_IN": 10 - } - } - } - }, - "UnaryFilter": { - "oneofs": { - "operandType": { - "oneof": [ - "field" - ] - } - }, - "fields": { - "op": { - "type": "Operator", - "id": 1 - }, - "field": { - "type": "FieldReference", - "id": 2 - } - }, - "nested": { - "Operator": { - "values": { - "OPERATOR_UNSPECIFIED": 0, - "IS_NAN": 2, - "IS_NULL": 3, - "IS_NOT_NAN": 4, - "IS_NOT_NULL": 5 - } - } - } - }, - "Order": { - "fields": { - "field": { - "type": "FieldReference", - "id": 1 - }, - "direction": { - "type": "Direction", - "id": 2 - } - } - }, - "Direction": { - "values": { - "DIRECTION_UNSPECIFIED": 0, - "ASCENDING": 1, - "DESCENDING": 2 - } - }, - "FieldReference": { - "fields": { - "fieldPath": { - "type": "string", - "id": 2 - } - } - }, - "Projection": { - "fields": { - "fields": { - "rule": "repeated", - "type": "FieldReference", - "id": 2 - } - } + "reserved": [ + [ + 4, + 4 + ] + ] + }, + "VerificationState": { + "values": { + "DECLARATION": 0, + "UNVERIFIED": 1 + } + } + } + }, + "FieldDescriptorProto": { + "fields": { + "name": { + "type": "string", + "id": 1 + }, + "number": { + "type": "int32", + "id": 3 + }, + "label": { + "type": "Label", + "id": 4 + }, + "type": { + "type": "Type", + "id": 5 + }, + "typeName": { + "type": "string", + "id": 6 + }, + "extendee": { + "type": "string", + "id": 2 + }, + "defaultValue": { + "type": "string", + "id": 7 + }, + "oneofIndex": { + "type": "int32", + "id": 9 + }, + "jsonName": { + "type": "string", + "id": 10 + }, + "options": { + "type": "FieldOptions", + "id": 8 + }, + "proto3Optional": { + "type": "bool", + "id": 17 + } + }, + "nested": { + "Type": { + "values": { + "TYPE_DOUBLE": 1, + "TYPE_FLOAT": 2, + "TYPE_INT64": 3, + "TYPE_UINT64": 4, + "TYPE_INT32": 5, + "TYPE_FIXED64": 6, + "TYPE_FIXED32": 7, + "TYPE_BOOL": 8, + "TYPE_STRING": 9, + "TYPE_GROUP": 10, + "TYPE_MESSAGE": 11, + "TYPE_BYTES": 12, + "TYPE_UINT32": 13, + "TYPE_ENUM": 14, + "TYPE_SFIXED32": 15, + "TYPE_SFIXED64": 16, + "TYPE_SINT32": 17, + "TYPE_SINT64": 18 + } + }, + "Label": { + "values": { + "LABEL_OPTIONAL": 1, + "LABEL_REPEATED": 3, + "LABEL_REQUIRED": 2 + } + } + } + }, + "OneofDescriptorProto": { + "fields": { + "name": { + "type": "string", + "id": 1 + }, + "options": { + "type": "OneofOptions", + "id": 2 + } + } + }, + "EnumDescriptorProto": { + "fields": { + "name": { + "type": "string", + "id": 1 + }, + "value": { + "rule": "repeated", + "type": "EnumValueDescriptorProto", + "id": 2 + }, + "options": { + "type": "EnumOptions", + "id": 3 + }, + "reservedRange": { + "rule": "repeated", + "type": "EnumReservedRange", + "id": 4 + }, + "reservedName": { + "rule": "repeated", + "type": "string", + "id": 5 + } + }, + "nested": { + "EnumReservedRange": { + "fields": { + "start": { + "type": "int32", + "id": 1 }, - "FindNearest": { - "fields": { - "vectorField": { - "type": "FieldReference", - "id": 1, - "options": { - "(google.api.field_behavior)": "REQUIRED" - } - }, - "queryVector": { - "type": "Value", - "id": 2, - "options": { - "(google.api.field_behavior)": "REQUIRED" - } - }, - "distanceMeasure": { - "type": "DistanceMeasure", - "id": 3, - "options": { - "(google.api.field_behavior)": "REQUIRED" - } - }, - "limit": { - "type": "google.protobuf.Int32Value", - "id": 4, - "options": { - "(google.api.field_behavior)": "REQUIRED" - } - } - }, - "nested": { - "DistanceMeasure": { - "values": { - "DISTANCE_MEASURE_UNSPECIFIED": 0, - "EUCLIDEAN": 1, - "COSINE": 2, - "DOT_PRODUCT": 3 - } - } - } + "end": { + "type": "int32", + "id": 2 } } + } + } + }, + "EnumValueDescriptorProto": { + "fields": { + "name": { + "type": "string", + "id": 1 + }, + "number": { + "type": "int32", + "id": 2 + }, + "options": { + "type": "EnumValueOptions", + "id": 3 + } + } + }, + "ServiceDescriptorProto": { + "fields": { + "name": { + "type": "string", + "id": 1 + }, + "method": { + "rule": "repeated", + "type": "MethodDescriptorProto", + "id": 2 + }, + "options": { + "type": "ServiceOptions", + "id": 3 + } + } + }, + "MethodDescriptorProto": { + "fields": { + "name": { + "type": "string", + "id": 1 + }, + "inputType": { + "type": "string", + "id": 2 + }, + "outputType": { + "type": "string", + "id": 3 + }, + "options": { + "type": "MethodOptions", + "id": 4 + }, + "clientStreaming": { + "type": "bool", + "id": 5, + "options": { + "default": false + } + }, + "serverStreaming": { + "type": "bool", + "id": 6, + "options": { + "default": false + } + } + } + }, + "FileOptions": { + "fields": { + "javaPackage": { + "type": "string", + "id": 1 + }, + "javaOuterClassname": { + "type": "string", + "id": 8 + }, + "javaMultipleFiles": { + "type": "bool", + "id": 10, + "options": { + "default": false + } + }, + "javaGenerateEqualsAndHash": { + "type": "bool", + "id": 20, + "options": { + "deprecated": true + } + }, + "javaStringCheckUtf8": { + "type": "bool", + "id": 27, + "options": { + "default": false + } + }, + "optimizeFor": { + "type": "OptimizeMode", + "id": 9, + "options": { + "default": "SPEED" + } + }, + "goPackage": { + "type": "string", + "id": 11 + }, + "ccGenericServices": { + "type": "bool", + "id": 16, + "options": { + "default": false + } + }, + "javaGenericServices": { + "type": "bool", + "id": 17, + "options": { + "default": false + } + }, + "pyGenericServices": { + "type": "bool", + "id": 18, + "options": { + "default": false + } + }, + "deprecated": { + "type": "bool", + "id": 23, + "options": { + "default": false + } + }, + "ccEnableArenas": { + "type": "bool", + "id": 31, + "options": { + "default": true + } + }, + "objcClassPrefix": { + "type": "string", + "id": 36 + }, + "csharpNamespace": { + "type": "string", + "id": 37 + }, + "swiftPrefix": { + "type": "string", + "id": 39 + }, + "phpClassPrefix": { + "type": "string", + "id": 40 + }, + "phpNamespace": { + "type": "string", + "id": 41 + }, + "phpMetadataNamespace": { + "type": "string", + "id": 44 + }, + "rubyPackage": { + "type": "string", + "id": 45 + }, + "features": { + "type": "FeatureSet", + "id": 50 + }, + "uninterpretedOption": { + "rule": "repeated", + "type": "UninterpretedOption", + "id": 999 + } + }, + "extensions": [ + [ + 1000, + 536870911 + ] + ], + "reserved": [ + [ + 42, + 42 + ], + [ + 38, + 38 + ] + ], + "nested": { + "OptimizeMode": { + "values": { + "SPEED": 1, + "CODE_SIZE": 2, + "LITE_RUNTIME": 3 + } + } + } + }, + "MessageOptions": { + "fields": { + "messageSetWireFormat": { + "type": "bool", + "id": 1, + "options": { + "default": false + } + }, + "noStandardDescriptorAccessor": { + "type": "bool", + "id": 2, + "options": { + "default": false + } + }, + "deprecated": { + "type": "bool", + "id": 3, + "options": { + "default": false + } + }, + "mapEntry": { + "type": "bool", + "id": 7 + }, + "deprecatedLegacyJsonFieldConflicts": { + "type": "bool", + "id": 11, + "options": { + "deprecated": true + } + }, + "features": { + "type": "FeatureSet", + "id": 12 + }, + "uninterpretedOption": { + "rule": "repeated", + "type": "UninterpretedOption", + "id": 999 + } + }, + "extensions": [ + [ + 1000, + 536870911 + ] + ], + "reserved": [ + [ + 4, + 4 + ], + [ + 5, + 5 + ], + [ + 6, + 6 + ], + [ + 8, + 8 + ], + [ + 9, + 9 + ] + ] + }, + "FieldOptions": { + "fields": { + "ctype": { + "type": "CType", + "id": 1, + "options": { + "default": "STRING" + } + }, + "packed": { + "type": "bool", + "id": 2 + }, + "jstype": { + "type": "JSType", + "id": 6, + "options": { + "default": "JS_NORMAL" + } + }, + "lazy": { + "type": "bool", + "id": 5, + "options": { + "default": false + } + }, + "unverifiedLazy": { + "type": "bool", + "id": 15, + "options": { + "default": false + } + }, + "deprecated": { + "type": "bool", + "id": 3, + "options": { + "default": false + } + }, + "weak": { + "type": "bool", + "id": 10, + "options": { + "default": false + } + }, + "debugRedact": { + "type": "bool", + "id": 16, + "options": { + "default": false + } + }, + "retention": { + "type": "OptionRetention", + "id": 17 + }, + "targets": { + "rule": "repeated", + "type": "OptionTargetType", + "id": 19, + "options": { + "packed": false + } + }, + "editionDefaults": { + "rule": "repeated", + "type": "EditionDefault", + "id": 20 + }, + "features": { + "type": "FeatureSet", + "id": 21 + }, + "uninterpretedOption": { + "rule": "repeated", + "type": "UninterpretedOption", + "id": 999 + } + }, + "extensions": [ + [ + 1000, + 536870911 + ] + ], + "reserved": [ + [ + 4, + 4 + ], + [ + 18, + 18 + ] + ], + "nested": { + "CType": { + "values": { + "STRING": 0, + "CORD": 1, + "STRING_PIECE": 2 + } }, - "StructuredAggregationQuery": { - "oneofs": { - "queryType": { - "oneof": [ - "structuredQuery" - ] - } - }, + "JSType": { + "values": { + "JS_NORMAL": 0, + "JS_STRING": 1, + "JS_NUMBER": 2 + } + }, + "OptionRetention": { + "values": { + "RETENTION_UNKNOWN": 0, + "RETENTION_RUNTIME": 1, + "RETENTION_SOURCE": 2 + } + }, + "OptionTargetType": { + "values": { + "TARGET_TYPE_UNKNOWN": 0, + "TARGET_TYPE_FILE": 1, + "TARGET_TYPE_EXTENSION_RANGE": 2, + "TARGET_TYPE_MESSAGE": 3, + "TARGET_TYPE_FIELD": 4, + "TARGET_TYPE_ONEOF": 5, + "TARGET_TYPE_ENUM": 6, + "TARGET_TYPE_ENUM_ENTRY": 7, + "TARGET_TYPE_SERVICE": 8, + "TARGET_TYPE_METHOD": 9 + } + }, + "EditionDefault": { "fields": { - "structuredQuery": { - "type": "StructuredQuery", - "id": 1 + "edition": { + "type": "Edition", + "id": 3 }, - "aggregations": { - "rule": "repeated", - "type": "Aggregation", - "id": 3, - "options": { - "(google.api.field_behavior)": "OPTIONAL" - } - } - }, - "nested": { - "Aggregation": { - "oneofs": { - "operator": { - "oneof": [ - "count", - "sum", - "avg" - ] - } - }, - "fields": { - "count": { - "type": "Count", - "id": 1 - }, - "sum": { - "type": "Sum", - "id": 2 - }, - "avg": { - "type": "Avg", - "id": 3 - }, - "alias": { - "type": "string", - "id": 7, - "options": { - "(google.api.field_behavior)": "OPTIONAL" - } - } - }, - "nested": { - "Count": { - "fields": { - "upTo": { - "type": "google.protobuf.Int64Value", - "id": 1, - "options": { - "(google.api.field_behavior)": "OPTIONAL" - } - } - } - }, - "Sum": { - "fields": { - "field": { - "type": "StructuredQuery.FieldReference", - "id": 1 - } - } - }, - "Avg": { - "fields": { - "field": { - "type": "StructuredQuery.FieldReference", - "id": 1 - } - } - } - } + "value": { + "type": "string", + "id": 2 } } + } + } + }, + "OneofOptions": { + "fields": { + "features": { + "type": "FeatureSet", + "id": 1 + }, + "uninterpretedOption": { + "rule": "repeated", + "type": "UninterpretedOption", + "id": 999 + } + }, + "extensions": [ + [ + 1000, + 536870911 + ] + ] + }, + "EnumOptions": { + "fields": { + "allowAlias": { + "type": "bool", + "id": 2 + }, + "deprecated": { + "type": "bool", + "id": 3, + "options": { + "default": false + } + }, + "deprecatedLegacyJsonFieldConflicts": { + "type": "bool", + "id": 6, + "options": { + "deprecated": true + } + }, + "features": { + "type": "FeatureSet", + "id": 7 + }, + "uninterpretedOption": { + "rule": "repeated", + "type": "UninterpretedOption", + "id": 999 + } + }, + "extensions": [ + [ + 1000, + 536870911 + ] + ], + "reserved": [ + [ + 5, + 5 + ] + ] + }, + "EnumValueOptions": { + "fields": { + "deprecated": { + "type": "bool", + "id": 1, + "options": { + "default": false + } + }, + "features": { + "type": "FeatureSet", + "id": 2 + }, + "debugRedact": { + "type": "bool", + "id": 3, + "options": { + "default": false + } + }, + "uninterpretedOption": { + "rule": "repeated", + "type": "UninterpretedOption", + "id": 999 + } + }, + "extensions": [ + [ + 1000, + 536870911 + ] + ] + }, + "ServiceOptions": { + "fields": { + "features": { + "type": "FeatureSet", + "id": 34 + }, + "deprecated": { + "type": "bool", + "id": 33, + "options": { + "default": false + } + }, + "uninterpretedOption": { + "rule": "repeated", + "type": "UninterpretedOption", + "id": 999 + } + }, + "extensions": [ + [ + 1000, + 536870911 + ] + ] + }, + "MethodOptions": { + "fields": { + "deprecated": { + "type": "bool", + "id": 33, + "options": { + "default": false + } + }, + "idempotencyLevel": { + "type": "IdempotencyLevel", + "id": 34, + "options": { + "default": "IDEMPOTENCY_UNKNOWN" + } }, - "Cursor": { + "features": { + "type": "FeatureSet", + "id": 35 + }, + "uninterpretedOption": { + "rule": "repeated", + "type": "UninterpretedOption", + "id": 999 + } + }, + "extensions": [ + [ + 1000, + 536870911 + ] + ], + "nested": { + "IdempotencyLevel": { + "values": { + "IDEMPOTENCY_UNKNOWN": 0, + "NO_SIDE_EFFECTS": 1, + "IDEMPOTENT": 2 + } + } + } + }, + "UninterpretedOption": { + "fields": { + "name": { + "rule": "repeated", + "type": "NamePart", + "id": 2 + }, + "identifierValue": { + "type": "string", + "id": 3 + }, + "positiveIntValue": { + "type": "uint64", + "id": 4 + }, + "negativeIntValue": { + "type": "int64", + "id": 5 + }, + "doubleValue": { + "type": "double", + "id": 6 + }, + "stringValue": { + "type": "bytes", + "id": 7 + }, + "aggregateValue": { + "type": "string", + "id": 8 + } + }, + "nested": { + "NamePart": { "fields": { - "values": { - "rule": "repeated", - "type": "Value", + "namePart": { + "rule": "required", + "type": "string", "id": 1 }, - "before": { + "isExtension": { + "rule": "required", "type": "bool", "id": 2 } } + } + } + }, + "FeatureSet": { + "fields": { + "fieldPresence": { + "type": "FieldPresence", + "id": 1, + "options": { + "retention": "RETENTION_RUNTIME", + "targets": "TARGET_TYPE_FILE", + "edition_defaults.edition": "EDITION_2023", + "edition_defaults.value": "EXPLICIT" + } }, - "ExplainOptions": { - "fields": { - "analyze": { - "type": "bool", - "id": 1, - "options": { - "(google.api.field_behavior)": "OPTIONAL" - } - } + "enumType": { + "type": "EnumType", + "id": 2, + "options": { + "retention": "RETENTION_RUNTIME", + "targets": "TARGET_TYPE_FILE", + "edition_defaults.edition": "EDITION_PROTO3", + "edition_defaults.value": "OPEN" } }, - "ExplainMetrics": { - "fields": { - "planSummary": { - "type": "PlanSummary", - "id": 1 - }, - "executionStats": { - "type": "ExecutionStats", - "id": 2 - } + "repeatedFieldEncoding": { + "type": "RepeatedFieldEncoding", + "id": 3, + "options": { + "retention": "RETENTION_RUNTIME", + "targets": "TARGET_TYPE_FILE", + "edition_defaults.edition": "EDITION_PROTO3", + "edition_defaults.value": "PACKED" } }, - "PlanSummary": { - "fields": { - "indexesUsed": { - "rule": "repeated", - "type": "google.protobuf.Struct", - "id": 1 - } + "utf8Validation": { + "type": "Utf8Validation", + "id": 4, + "options": { + "retention": "RETENTION_RUNTIME", + "targets": "TARGET_TYPE_FILE", + "edition_defaults.edition": "EDITION_PROTO3", + "edition_defaults.value": "VERIFY" } }, - "ExecutionStats": { - "fields": { - "resultsReturned": { - "type": "int64", - "id": 1 - }, - "executionDuration": { - "type": "google.protobuf.Duration", - "id": 3 - }, - "readOperations": { - "type": "int64", - "id": 4 - }, - "debugStats": { - "type": "google.protobuf.Struct", - "id": 5 - } + "messageEncoding": { + "type": "MessageEncoding", + "id": 5, + "options": { + "retention": "RETENTION_RUNTIME", + "targets": "TARGET_TYPE_FILE", + "edition_defaults.edition": "EDITION_PROTO2", + "edition_defaults.value": "LENGTH_PREFIXED" } }, - "Write": { - "oneofs": { - "operation": { - "oneof": [ - "update", - "delete", - "transform" - ] - } - }, - "fields": { - "update": { - "type": "Document", - "id": 1 - }, - "delete": { - "type": "string", - "id": 2 - }, - "transform": { - "type": "DocumentTransform", - "id": 6 - }, - "updateMask": { - "type": "DocumentMask", - "id": 3 - }, - "updateTransforms": { - "rule": "repeated", - "type": "DocumentTransform.FieldTransform", - "id": 7 - }, - "currentDocument": { - "type": "Precondition", - "id": 4 - } + "jsonFormat": { + "type": "JsonFormat", + "id": 6, + "options": { + "retention": "RETENTION_RUNTIME", + "targets": "TARGET_TYPE_FILE", + "edition_defaults.edition": "EDITION_PROTO3", + "edition_defaults.value": "ALLOW" + } + } + }, + "extensions": [ + [ + 1000, + 1000 + ], + [ + 1001, + 1001 + ], + [ + 1002, + 1002 + ], + [ + 9995, + 9999 + ], + [ + 10000, + 10000 + ] + ], + "reserved": [ + [ + 999, + 999 + ] + ], + "nested": { + "FieldPresence": { + "values": { + "FIELD_PRESENCE_UNKNOWN": 0, + "EXPLICIT": 1, + "IMPLICIT": 2, + "LEGACY_REQUIRED": 3 + } + }, + "EnumType": { + "values": { + "ENUM_TYPE_UNKNOWN": 0, + "OPEN": 1, + "CLOSED": 2 + } + }, + "RepeatedFieldEncoding": { + "values": { + "REPEATED_FIELD_ENCODING_UNKNOWN": 0, + "PACKED": 1, + "EXPANDED": 2 } }, - "DocumentTransform": { - "fields": { - "document": { - "type": "string", - "id": 1 - }, - "fieldTransforms": { - "rule": "repeated", - "type": "FieldTransform", - "id": 2 - } - }, - "nested": { - "FieldTransform": { - "oneofs": { - "transformType": { - "oneof": [ - "setToServerValue", - "increment", - "maximum", - "minimum", - "appendMissingElements", - "removeAllFromArray" - ] - } - }, - "fields": { - "fieldPath": { - "type": "string", - "id": 1 - }, - "setToServerValue": { - "type": "ServerValue", - "id": 2 - }, - "increment": { - "type": "Value", - "id": 3 - }, - "maximum": { - "type": "Value", - "id": 4 - }, - "minimum": { - "type": "Value", - "id": 5 - }, - "appendMissingElements": { - "type": "ArrayValue", - "id": 6 - }, - "removeAllFromArray": { - "type": "ArrayValue", - "id": 7 - } - }, - "nested": { - "ServerValue": { - "values": { - "SERVER_VALUE_UNSPECIFIED": 0, - "REQUEST_TIME": 1 - } - } - } - } + "Utf8Validation": { + "values": { + "UTF8_VALIDATION_UNKNOWN": 0, + "VERIFY": 2, + "NONE": 3 } }, - "WriteResult": { + "MessageEncoding": { + "values": { + "MESSAGE_ENCODING_UNKNOWN": 0, + "LENGTH_PREFIXED": 1, + "DELIMITED": 2 + } + }, + "JsonFormat": { + "values": { + "JSON_FORMAT_UNKNOWN": 0, + "ALLOW": 1, + "LEGACY_BEST_EFFORT": 2 + } + } + } + }, + "FeatureSetDefaults": { + "fields": { + "defaults": { + "rule": "repeated", + "type": "FeatureSetEditionDefault", + "id": 1 + }, + "minimumEdition": { + "type": "Edition", + "id": 4 + }, + "maximumEdition": { + "type": "Edition", + "id": 5 + } + }, + "nested": { + "FeatureSetEditionDefault": { "fields": { - "updateTime": { - "type": "google.protobuf.Timestamp", - "id": 1 + "edition": { + "type": "Edition", + "id": 3 }, - "transformResults": { - "rule": "repeated", - "type": "Value", + "features": { + "type": "FeatureSet", "id": 2 } } - }, - "DocumentChange": { + } + } + }, + "SourceCodeInfo": { + "fields": { + "location": { + "rule": "repeated", + "type": "Location", + "id": 1 + } + }, + "nested": { + "Location": { "fields": { - "document": { - "type": "Document", - "id": 1 - }, - "targetIds": { + "path": { "rule": "repeated", "type": "int32", - "id": 5 + "id": 1 }, - "removedTargetIds": { + "span": { "rule": "repeated", "type": "int32", - "id": 6 - } - } - }, - "DocumentDelete": { - "fields": { - "document": { + "id": 2 + }, + "leadingComments": { "type": "string", - "id": 1 + "id": 3 }, - "removedTargetIds": { + "trailingComments": { + "type": "string", + "id": 4 + }, + "leadingDetachedComments": { "rule": "repeated", - "type": "int32", + "type": "string", "id": 6 - }, - "readTime": { - "type": "google.protobuf.Timestamp", - "id": 4 } } - }, - "DocumentRemove": { + } + } + }, + "GeneratedCodeInfo": { + "fields": { + "annotation": { + "rule": "repeated", + "type": "Annotation", + "id": 1 + } + }, + "nested": { + "Annotation": { "fields": { - "document": { - "type": "string", - "id": 1 - }, - "removedTargetIds": { + "path": { "rule": "repeated", "type": "int32", + "id": 1 + }, + "sourceFile": { + "type": "string", "id": 2 }, - "readTime": { - "type": "google.protobuf.Timestamp", - "id": 4 - } - } - }, - "ExistenceFilter": { - "fields": { - "targetId": { + "begin": { "type": "int32", - "id": 1 + "id": 3 }, - "count": { + "end": { "type": "int32", - "id": 2 + "id": 4 }, - "unchangedNames": { - "type": "BloomFilter", - "id": 3 + "semantic": { + "type": "Semantic", + "id": 5 } - } - } - } - } - } - }, - "type": { - "options": { - "cc_enable_arenas": true, - "go_package": "google.golang.org/genproto/googleapis/type/dayofweek;dayofweek", - "java_multiple_files": true, - "java_outer_classname": "DayOfWeekProto", - "java_package": "com.google.type", - "objc_class_prefix": "GTP" - }, - "nested": { - "LatLng": { - "fields": { - "latitude": { - "type": "double", - "id": 1 - }, - "longitude": { - "type": "double", - "id": 2 - } - } - }, - "DayOfWeek": { - "values": { - "DAY_OF_WEEK_UNSPECIFIED": 0, - "MONDAY": 1, - "TUESDAY": 2, - "WEDNESDAY": 3, - "THURSDAY": 4, - "FRIDAY": 5, - "SATURDAY": 6, - "SUNDAY": 7 + }, + "nested": { + "Semantic": { + "values": { + "NONE": 0, + "SET": 1, + "ALIAS": 2 + } + } + } + } } - } - } - }, - "api": { - "options": { - "go_package": "google.golang.org/genproto/googleapis/api/annotations;annotations", - "java_multiple_files": true, - "java_outer_classname": "ResourceProto", - "java_package": "com.google.api", - "objc_class_prefix": "GAPI", - "cc_enable_arenas": true - }, - "nested": { - "http": { - "type": "HttpRule", - "id": 72295728, - "extend": "google.protobuf.MethodOptions" }, - "Http": { + "Struct": { "fields": { - "rules": { - "rule": "repeated", - "type": "HttpRule", + "fields": { + "keyType": "string", + "type": "Value", "id": 1 - }, - "fullyDecodeReservedExpansion": { - "type": "bool", - "id": 2 } } }, - "HttpRule": { + "Value": { "oneofs": { - "pattern": { + "kind": { "oneof": [ - "get", - "put", - "post", - "delete", - "patch", - "custom" + "nullValue", + "numberValue", + "stringValue", + "boolValue", + "structValue", + "listValue" ] } }, "fields": { - "selector": { - "type": "string", + "nullValue": { + "type": "NullValue", "id": 1 }, - "get": { - "type": "string", + "numberValue": { + "type": "double", "id": 2 }, - "put": { + "stringValue": { "type": "string", "id": 3 }, - "post": { - "type": "string", + "boolValue": { + "type": "bool", "id": 4 }, - "delete": { - "type": "string", + "structValue": { + "type": "Struct", "id": 5 }, - "patch": { - "type": "string", + "listValue": { + "type": "ListValue", "id": 6 - }, - "custom": { - "type": "CustomHttpPattern", - "id": 8 - }, - "body": { - "type": "string", - "id": 7 - }, - "responseBody": { - "type": "string", - "id": 12 - }, - "additionalBindings": { - "rule": "repeated", - "type": "HttpRule", - "id": 11 } } }, - "CustomHttpPattern": { - "fields": { - "kind": { - "type": "string", - "id": 1 - }, - "path": { - "type": "string", - "id": 2 - } + "NullValue": { + "values": { + "NULL_VALUE": 0 } }, - "methodSignature": { - "rule": "repeated", - "type": "string", - "id": 1051, - "extend": "google.protobuf.MethodOptions" - }, - "defaultHost": { - "type": "string", - "id": 1049, - "extend": "google.protobuf.ServiceOptions" - }, - "oauthScopes": { - "type": "string", - "id": 1050, - "extend": "google.protobuf.ServiceOptions" - }, - "apiVersion": { - "type": "string", - "id": 525000001, - "extend": "google.protobuf.ServiceOptions" - }, - "CommonLanguageSettings": { + "ListValue": { "fields": { - "referenceDocsUri": { - "type": "string", - "id": 1, - "options": { - "deprecated": true - } - }, - "destinations": { + "values": { "rule": "repeated", - "type": "ClientLibraryDestination", - "id": 2 + "type": "Value", + "id": 1 } } }, - "ClientLibrarySettings": { + "Timestamp": { "fields": { - "version": { - "type": "string", + "seconds": { + "type": "int64", "id": 1 }, - "launchStage": { - "type": "LaunchStage", - "id": 2 - }, - "restNumericEnums": { - "type": "bool", - "id": 3 - }, - "javaSettings": { - "type": "JavaSettings", - "id": 21 - }, - "cppSettings": { - "type": "CppSettings", - "id": 22 - }, - "phpSettings": { - "type": "PhpSettings", - "id": 23 - }, - "pythonSettings": { - "type": "PythonSettings", - "id": 24 - }, - "nodeSettings": { - "type": "NodeSettings", - "id": 25 - }, - "dotnetSettings": { - "type": "DotnetSettings", - "id": 26 - }, - "rubySettings": { - "type": "RubySettings", - "id": 27 - }, - "goSettings": { - "type": "GoSettings", - "id": 28 - } - } - }, - "Publishing": { - "fields": { - "methodSettings": { - "rule": "repeated", - "type": "MethodSettings", + "nanos": { + "type": "int32", "id": 2 - }, - "newIssueUri": { - "type": "string", - "id": 101 - }, - "documentationUri": { - "type": "string", - "id": 102 - }, - "apiShortName": { - "type": "string", - "id": 103 - }, - "githubLabel": { - "type": "string", - "id": 104 - }, - "codeownerGithubTeams": { - "rule": "repeated", - "type": "string", - "id": 105 - }, - "docTagPrefix": { - "type": "string", - "id": 106 - }, - "organization": { - "type": "ClientLibraryOrganization", - "id": 107 - }, - "librarySettings": { - "rule": "repeated", - "type": "ClientLibrarySettings", - "id": 109 - }, - "protoReferenceDocumentationUri": { - "type": "string", - "id": 110 - }, - "restReferenceDocumentationUri": { - "type": "string", - "id": 111 } } }, - "JavaSettings": { + "Duration": { "fields": { - "libraryPackage": { - "type": "string", + "seconds": { + "type": "int64", "id": 1 }, - "serviceClassNames": { - "keyType": "string", - "type": "string", + "nanos": { + "type": "int32", "id": 2 - }, - "common": { - "type": "CommonLanguageSettings", - "id": 3 } } }, - "CppSettings": { + "DoubleValue": { "fields": { - "common": { - "type": "CommonLanguageSettings", + "value": { + "type": "double", "id": 1 } } }, - "PhpSettings": { + "FloatValue": { "fields": { - "common": { - "type": "CommonLanguageSettings", + "value": { + "type": "float", "id": 1 } } }, - "PythonSettings": { + "Int64Value": { "fields": { - "common": { - "type": "CommonLanguageSettings", + "value": { + "type": "int64", "id": 1 } } }, - "NodeSettings": { + "UInt64Value": { "fields": { - "common": { - "type": "CommonLanguageSettings", + "value": { + "type": "uint64", "id": 1 } } }, - "DotnetSettings": { + "Int32Value": { "fields": { - "common": { - "type": "CommonLanguageSettings", + "value": { + "type": "int32", "id": 1 - }, - "renamedServices": { - "keyType": "string", - "type": "string", - "id": 2 - }, - "renamedResources": { - "keyType": "string", - "type": "string", - "id": 3 - }, - "ignoredResources": { - "rule": "repeated", - "type": "string", - "id": 4 - }, - "forcedNamespaceAliases": { - "rule": "repeated", - "type": "string", - "id": 5 - }, - "handwrittenSignatures": { - "rule": "repeated", - "type": "string", - "id": 6 } } }, - "RubySettings": { + "UInt32Value": { "fields": { - "common": { - "type": "CommonLanguageSettings", + "value": { + "type": "uint32", "id": 1 } } }, - "GoSettings": { + "BoolValue": { "fields": { - "common": { - "type": "CommonLanguageSettings", + "value": { + "type": "bool", "id": 1 } } }, - "MethodSettings": { + "StringValue": { "fields": { - "selector": { + "value": { "type": "string", "id": 1 - }, - "longRunning": { - "type": "LongRunning", - "id": 2 - }, - "autoPopulatedFields": { - "rule": "repeated", - "type": "string", - "id": 3 - } - }, - "nested": { - "LongRunning": { - "fields": { - "initialPollDelay": { - "type": "google.protobuf.Duration", - "id": 1 - }, - "pollDelayMultiplier": { - "type": "float", - "id": 2 - }, - "maxPollDelay": { - "type": "google.protobuf.Duration", - "id": 3 - }, - "totalPollTimeout": { - "type": "google.protobuf.Duration", - "id": 4 - } - } } } }, - "ClientLibraryOrganization": { - "values": { - "CLIENT_LIBRARY_ORGANIZATION_UNSPECIFIED": 0, - "CLOUD": 1, - "ADS": 2, - "PHOTOS": 3, - "STREET_VIEW": 4, - "SHOPPING": 5, - "GEO": 6, - "GENERATIVE_AI": 7 - } - }, - "ClientLibraryDestination": { - "values": { - "CLIENT_LIBRARY_DESTINATION_UNSPECIFIED": 0, - "GITHUB": 10, - "PACKAGE_MANAGER": 20 - } - }, - "LaunchStage": { - "values": { - "LAUNCH_STAGE_UNSPECIFIED": 0, - "UNIMPLEMENTED": 6, - "PRELAUNCH": 7, - "EARLY_ACCESS": 1, - "ALPHA": 2, - "BETA": 3, - "GA": 4, - "DEPRECATED": 5 - } - }, - "fieldBehavior": { - "rule": "repeated", - "type": "google.api.FieldBehavior", - "id": 1052, - "extend": "google.protobuf.FieldOptions", - "options": { - "packed": false - } - }, - "FieldBehavior": { - "values": { - "FIELD_BEHAVIOR_UNSPECIFIED": 0, - "OPTIONAL": 1, - "REQUIRED": 2, - "OUTPUT_ONLY": 3, - "INPUT_ONLY": 4, - "IMMUTABLE": 5, - "UNORDERED_LIST": 6, - "NON_EMPTY_DEFAULT": 7, - "IDENTIFIER": 8 + "BytesValue": { + "fields": { + "value": { + "type": "bytes", + "id": 1 + } } }, - "resourceReference": { - "type": "google.api.ResourceReference", - "id": 1055, - "extend": "google.protobuf.FieldOptions" - }, - "resourceDefinition": { - "rule": "repeated", - "type": "google.api.ResourceDescriptor", - "id": 1053, - "extend": "google.protobuf.FileOptions" - }, - "resource": { - "type": "google.api.ResourceDescriptor", - "id": 1053, - "extend": "google.protobuf.MessageOptions" + "Empty": { + "fields": {} }, - "ResourceDescriptor": { + "Any": { "fields": { - "type": { + "type_url": { "type": "string", "id": 1 }, - "pattern": { - "rule": "repeated", - "type": "string", + "value": { + "type": "bytes", "id": 2 - }, - "nameField": { - "type": "string", - "id": 3 - }, - "history": { - "type": "History", - "id": 4 - }, - "plural": { - "type": "string", - "id": 5 - }, - "singular": { - "type": "string", - "id": 6 - }, - "style": { - "rule": "repeated", - "type": "Style", - "id": 10 - } - }, - "nested": { - "History": { - "values": { - "HISTORY_UNSPECIFIED": 0, - "ORIGINALLY_SINGLE_PATTERN": 1, - "FUTURE_MULTI_PATTERN": 2 - } - }, - "Style": { - "values": { - "STYLE_UNSPECIFIED": 0, - "DECLARATIVE_FRIENDLY": 1 - } } } }, - "ResourceReference": { + "FieldMask": { "fields": { - "type": { + "paths": { + "rule": "repeated", "type": "string", "id": 1 + } + } + } + } + }, + "type": { + "options": { + "cc_enable_arenas": true, + "go_package": "google.golang.org/genproto/googleapis/type/dayofweek;dayofweek", + "java_multiple_files": true, + "java_outer_classname": "DayOfWeekProto", + "java_package": "com.google.type", + "objc_class_prefix": "GTP" + }, + "nested": { + "LatLng": { + "fields": { + "latitude": { + "type": "double", + "id": 1 }, - "childType": { - "type": "string", + "longitude": { + "type": "double", "id": 2 } } + }, + "DayOfWeek": { + "values": { + "DAY_OF_WEEK_UNSPECIFIED": 0, + "MONDAY": 1, + "TUESDAY": 2, + "WEDNESDAY": 3, + "THURSDAY": 4, + "FRIDAY": 5, + "SATURDAY": 6, + "SUNDAY": 7 + } } } }, diff --git a/dev/protos/v1beta1.json b/dev/protos/v1beta1.json index ae6a2499b..e892f5e33 100644 --- a/dev/protos/v1beta1.json +++ b/dev/protos/v1beta1.json @@ -100,7 +100,6 @@ "Edition": { "values": { "EDITION_UNKNOWN": 0, - "EDITION_LEGACY": 900, "EDITION_PROTO2": 998, "EDITION_PROTO3": 999, "EDITION_2023": 1000, @@ -826,10 +825,6 @@ "type": "FeatureSet", "id": 21 }, - "featureSupport": { - "type": "FeatureSupport", - "id": 22 - }, "uninterpretedOption": { "rule": "repeated", "type": "UninterpretedOption", @@ -899,26 +894,6 @@ "id": 2 } } - }, - "FeatureSupport": { - "fields": { - "editionIntroduced": { - "type": "Edition", - "id": 1 - }, - "editionDeprecated": { - "type": "Edition", - "id": 2 - }, - "deprecationWarning": { - "type": "string", - "id": 3 - }, - "editionRemoved": { - "type": "Edition", - "id": 4 - } - } } } }, @@ -1142,7 +1117,6 @@ "options": { "retention": "RETENTION_RUNTIME", "targets": "TARGET_TYPE_FILE", - "feature_support.edition_introduced": "EDITION_2023", "edition_defaults.edition": "EDITION_2023", "edition_defaults.value": "EXPLICIT" } @@ -1153,7 +1127,6 @@ "options": { "retention": "RETENTION_RUNTIME", "targets": "TARGET_TYPE_FILE", - "feature_support.edition_introduced": "EDITION_2023", "edition_defaults.edition": "EDITION_PROTO3", "edition_defaults.value": "OPEN" } @@ -1164,7 +1137,6 @@ "options": { "retention": "RETENTION_RUNTIME", "targets": "TARGET_TYPE_FILE", - "feature_support.edition_introduced": "EDITION_2023", "edition_defaults.edition": "EDITION_PROTO3", "edition_defaults.value": "PACKED" } @@ -1175,7 +1147,6 @@ "options": { "retention": "RETENTION_RUNTIME", "targets": "TARGET_TYPE_FILE", - "feature_support.edition_introduced": "EDITION_2023", "edition_defaults.edition": "EDITION_PROTO3", "edition_defaults.value": "VERIFY" } @@ -1186,7 +1157,6 @@ "options": { "retention": "RETENTION_RUNTIME", "targets": "TARGET_TYPE_FILE", - "feature_support.edition_introduced": "EDITION_2023", "edition_defaults.edition": "EDITION_PROTO2", "edition_defaults.value": "LENGTH_PREFIXED" } @@ -1197,7 +1167,6 @@ "options": { "retention": "RETENTION_RUNTIME", "targets": "TARGET_TYPE_FILE", - "feature_support.edition_introduced": "EDITION_2023", "edition_defaults.edition": "EDITION_PROTO3", "edition_defaults.value": "ALLOW" } @@ -1206,7 +1175,15 @@ "extensions": [ [ 1000, - 9994 + 1000 + ], + [ + 1001, + 1001 + ], + [ + 1002, + 1002 ], [ 9995, @@ -1292,13 +1269,9 @@ "type": "Edition", "id": 3 }, - "overridableFeatures": { - "type": "FeatureSet", - "id": 4 - }, - "fixedFeatures": { + "features": { "type": "FeatureSet", - "id": 5 + "id": 2 } } } diff --git a/dev/src/bulk-writer.ts b/dev/src/bulk-writer.ts index 1acca5aa5..4b2f2621f 100644 --- a/dev/src/bulk-writer.ts +++ b/dev/src/bulk-writer.ts @@ -49,6 +49,10 @@ import {StatusCode} from './status-code'; // eslint-disable-next-line no-undef import GrpcStatus = FirebaseFirestore.GrpcStatus; import api = google.firestore.v1; +import { + ATTRIBUTE_KEY_DOC_COUNT, + SPAN_NAME_BULK_WRITER_COMMIT, +} from './telemetry/trace-util'; /*! * The maximum number of writes that can be in a single batch. @@ -243,55 +247,63 @@ class BulkCommitBatch extends WriteBatch { } async bulkCommit(options: {requestTag?: string} = {}): Promise { - const tag = options?.requestTag ?? requestTag(); - - // Capture the error stack to preserve stack tracing across async calls. - const stack = Error().stack!; - - let response: api.IBatchWriteResponse; - try { - logger( - 'BulkCommitBatch.bulkCommit', - tag, - `Sending next batch with ${this._opCount} writes` - ); - const retryCodes = getRetryCodes('batchWrite'); - response = await this._commit< - api.BatchWriteRequest, - api.BatchWriteResponse - >({retryCodes, methodName: 'batchWrite', requestTag: tag}); - } catch (err) { - // Map the failure to each individual write's result. - const ops = Array.from({length: this.pendingOps.length}); - response = { - writeResults: ops.map(() => { - return {}; - }), - status: ops.map(() => err), - }; - } - - for (let i = 0; i < (response.writeResults || []).length; ++i) { - // Since delete operations currently do not have write times, use a - // sentinel Timestamp value. - // TODO(b/158502664): Use actual delete timestamp. - const DELETE_TIMESTAMP_SENTINEL = Timestamp.fromMillis(0); - - const status = (response.status || [])[i]; - if (status.code === StatusCode.OK) { - const updateTime = Timestamp.fromProto( - response.writeResults![i].updateTime || DELETE_TIMESTAMP_SENTINEL - ); - this.pendingOps[i].onSuccess(new WriteResult(updateTime)); - } else { - const error = - new (require('google-gax/build/src/fallback').GoogleError)( - status.message || undefined + return this._firestore._traceUtil.startActiveSpan( + SPAN_NAME_BULK_WRITER_COMMIT, + async () => { + const tag = options?.requestTag ?? requestTag(); + + // Capture the error stack to preserve stack tracing across async calls. + const stack = Error().stack!; + + let response: api.IBatchWriteResponse; + try { + logger( + 'BulkCommitBatch.bulkCommit', + tag, + `Sending next batch with ${this._opCount} writes` ); - error.code = status.code as number; - this.pendingOps[i].onError(wrapError(error, stack)); + const retryCodes = getRetryCodes('batchWrite'); + response = await this._commit< + api.BatchWriteRequest, + api.BatchWriteResponse + >({retryCodes, methodName: 'batchWrite', requestTag: tag}); + } catch (err) { + // Map the failure to each individual write's result. + const ops = Array.from({length: this.pendingOps.length}); + response = { + writeResults: ops.map(() => { + return {}; + }), + status: ops.map(() => err), + }; + } + + for (let i = 0; i < (response.writeResults || []).length; ++i) { + // Since delete operations currently do not have write times, use a + // sentinel Timestamp value. + // TODO(b/158502664): Use actual delete timestamp. + const DELETE_TIMESTAMP_SENTINEL = Timestamp.fromMillis(0); + + const status = (response.status || [])[i]; + if (status.code === StatusCode.OK) { + const updateTime = Timestamp.fromProto( + response.writeResults![i].updateTime || DELETE_TIMESTAMP_SENTINEL + ); + this.pendingOps[i].onSuccess(new WriteResult(updateTime)); + } else { + const error = + new (require('google-gax/build/src/fallback').GoogleError)( + status.message || undefined + ); + error.code = status.code as number; + this.pendingOps[i].onError(wrapError(error, stack)); + } + } + }, + { + [ATTRIBUTE_KEY_DOC_COUNT]: this._opCount, } - } + ); } /** diff --git a/dev/src/collection-group.ts b/dev/src/collection-group.ts index 363cd6de6..92ca05879 100644 --- a/dev/src/collection-group.ts +++ b/dev/src/collection-group.ts @@ -29,6 +29,7 @@ import {validateInteger} from './validate'; import api = protos.google.firestore.v1; import {defaultConverter} from './types'; import {compareArrays} from './order'; +import {SPAN_NAME_PARTITION_QUERY} from './telemetry/trace-util'; /** * A `CollectionGroup` refers to all documents that are contained in a @@ -81,48 +82,53 @@ export class CollectionGroup< async *getPartitions( desiredPartitionCount: number ): AsyncIterable> { - validateInteger('desiredPartitionCount', desiredPartitionCount, { - minValue: 1, - }); - - const tag = requestTag(); - await this.firestore.initializeIfNeeded(tag); - const partitions: Array[] = []; - if (desiredPartitionCount > 1) { - // Partition queries require explicit ordering by __name__. - const queryWithDefaultOrder = this.orderBy(FieldPath.documentId()); - const request: api.IPartitionQueryRequest = - queryWithDefaultOrder.toProto(); - - // Since we are always returning an extra partition (with an empty endBefore - // cursor), we reduce the desired partition count by one. - request.partitionCount = desiredPartitionCount - 1; - - const stream = await this.firestore.requestStream( - 'partitionQueryStream', - /* bidirectional= */ false, - request, - tag - ); - stream.resume(); - - for await (const currentCursor of stream) { - partitions.push(currentCursor.values ?? []); + await this._firestore._traceUtil.startActiveSpan( + SPAN_NAME_PARTITION_QUERY, + async () => { + validateInteger('desiredPartitionCount', desiredPartitionCount, { + minValue: 1, + }); + + const tag = requestTag(); + await this.firestore.initializeIfNeeded(tag); + + if (desiredPartitionCount > 1) { + // Partition queries require explicit ordering by __name__. + const queryWithDefaultOrder = this.orderBy(FieldPath.documentId()); + const request: api.IPartitionQueryRequest = + queryWithDefaultOrder.toProto(); + + // Since we are always returning an extra partition (with an empty endBefore + // cursor), we reduce the desired partition count by one. + request.partitionCount = desiredPartitionCount - 1; + + const stream = await this.firestore.requestStream( + 'partitionQueryStream', + /* bidirectional= */ false, + request, + tag + ); + stream.resume(); + + for await (const currentCursor of stream) { + partitions.push(currentCursor.values ?? []); + } + } + + logger( + 'Firestore.getPartitions', + tag, + 'Received %d partitions', + partitions.length + ); + + // Sort the partitions as they may not be ordered if responses are paged. + partitions.sort((l, r) => compareArrays(l, r)); } - } - - logger( - 'Firestore.getPartitions', - tag, - 'Received %d partitions', - partitions.length ); - // Sort the partitions as they may not be ordered if responses are paged. - partitions.sort((l, r) => compareArrays(l, r)); - for (let i = 0; i < partitions.length; ++i) { yield new QueryPartition( this._firestore, diff --git a/dev/src/index.ts b/dev/src/index.ts index 5b83d596c..99e15c01a 100644 --- a/dev/src/index.ts +++ b/dev/src/index.ts @@ -86,6 +86,15 @@ import { RECURSIVE_DELETE_MIN_PENDING_OPS, RecursiveDelete, } from './recursive-delete'; +import { + ATTRIBUTE_KEY_DOC_COUNT, + ATTRIBUTE_KEY_IS_TRANSACTIONAL, + ATTRIBUTE_KEY_NUM_RESPONSES, + SPAN_NAME_BATCH_GET_DOCUMENTS, + TraceUtil, +} from './telemetry/trace-util'; +import {DisabledTraceUtil} from './telemetry/disabled-trace-util'; +import {EnabledTraceUtil} from './telemetry/enabled-trace-util'; export {CollectionReference} from './reference/collection-reference'; export {DocumentReference} from './reference/document-reference'; @@ -95,6 +104,7 @@ export type {AggregateQuery} from './reference/aggregate-query'; export type {AggregateQuerySnapshot} from './reference/aggregate-query-snapshot'; export type {VectorQuery} from './reference/vector-query'; export type {VectorQuerySnapshot} from './reference/vector-query-snapshot'; +export type {VectorQueryOptions} from './reference/vector-query-options'; export {BulkWriter} from './bulk-writer'; export type {BulkWriterError} from './bulk-writer'; export type {BundleBuilder} from './bundle'; @@ -259,7 +269,7 @@ export const DEFAULT_MAX_TRANSACTION_ATTEMPTS = 5; /*! * The default number of idle GRPC channel to keep. */ -const DEFAULT_MAX_IDLE_CHANNELS = 1; +export const DEFAULT_MAX_IDLE_CHANNELS = 1; /*! * The maximum number of concurrent requests supported by a single GRPC channel, @@ -545,6 +555,13 @@ export class Firestore implements firestore.Firestore { */ _serializer: Serializer | null = null; + /** + * The OpenTelemetry tracing utility object. + * @private + * @internal + */ + _traceUtil: TraceUtil; + /** * The project ID for this client. * @@ -662,6 +679,7 @@ export class Firestore implements firestore.Firestore { } this.validateAndApplySettings({...settings, ...libraryHeader}); + this._traceUtil = this.newTraceUtilInstance(this._settings); const retryConfig = serviceConfig.retry_params.default; this._backoffSettings = { @@ -767,6 +785,7 @@ export class Firestore implements firestore.Firestore { const mergedSettings = {...this._settings, ...settings}; this.validateAndApplySettings(mergedSettings); + this._traceUtil = this.newTraceUtilInstance(this._settings); this._settingsFrozen = true; } @@ -862,6 +881,29 @@ export class Firestore implements firestore.Firestore { this._serializer = new Serializer(this); } + private newTraceUtilInstance(settings: firestore.Settings): TraceUtil { + // Take the tracing option from the settings. + let createEnabledInstance = settings.openTelemetryOptions?.enableTracing; + + // The environment variable can override options to enable/disable telemetry collection. + if ('FIRESTORE_ENABLE_TRACING' in process.env) { + const enableTracingEnvVar = + process.env.FIRESTORE_ENABLE_TRACING!.toLowerCase(); + if (enableTracingEnvVar === 'on' || enableTracingEnvVar === 'true') { + createEnabledInstance = true; + } + if (enableTracingEnvVar === 'off' || enableTracingEnvVar === 'false') { + createEnabledInstance = false; + } + } + + if (createEnabledInstance) { + return new EnabledTraceUtil(settings); + } else { + return new DisabledTraceUtil(); + } + } + /** * Returns the Project ID for this Firestore instance. Validates that * `initializeIfNeeded()` was called before. @@ -1370,28 +1412,39 @@ export class Firestore implements firestore.Firestore { | firestore.ReadOptions > ): Promise>> { - validateMinNumberOfArguments( - 'Firestore.getAll', - documentRefsOrReadOptions, - 1 - ); + return this._traceUtil.startActiveSpan( + SPAN_NAME_BATCH_GET_DOCUMENTS, + () => { + validateMinNumberOfArguments( + 'Firestore.getAll', + documentRefsOrReadOptions, + 1 + ); - const {documents, fieldMask} = parseGetAllArguments( - documentRefsOrReadOptions - ); - const tag = requestTag(); + const {documents, fieldMask} = parseGetAllArguments( + documentRefsOrReadOptions + ); - // Capture the error stack to preserve stack tracing across async calls. - const stack = Error().stack!; + this._traceUtil.currentSpan().setAttributes({ + [ATTRIBUTE_KEY_IS_TRANSACTIONAL]: false, + [ATTRIBUTE_KEY_DOC_COUNT]: documents.length, + }); - return this.initializeIfNeeded(tag) - .then(() => { - const reader = new DocumentReader(this, documents, fieldMask); - return reader.get(tag); - }) - .catch(err => { - throw wrapError(err, stack); - }); + const tag = requestTag(); + + // Capture the error stack to preserve stack tracing across async calls. + const stack = Error().stack!; + + return this.initializeIfNeeded(tag) + .then(() => { + const reader = new DocumentReader(this, documents, fieldMask); + return reader.get(tag); + }) + .catch(err => { + throw wrapError(err, stack); + }); + } + ); } /** @@ -1586,6 +1639,10 @@ export class Firestore implements firestore.Firestore { 'Detected project ID: %s', this._projectId ); + + // If the project ID was undefined when the TraceUtil was set up, we + // need to record it. + this._traceUtil.recordProjectId(this.projectId); } catch (err) { logger( 'Firestore.initializeIfNeeded', @@ -1881,6 +1938,8 @@ export class Firestore implements firestore.Firestore { const callOptions = this.createCallOptions(methodName); const bidirectional = methodName === 'listen'; + let numResponses = 0; + const NUM_RESPONSES_PER_TRACE_EVENT = 100; return this._retry(methodName, requestTag, () => { const result = new Deferred(); @@ -1892,6 +1951,11 @@ export class Firestore implements firestore.Firestore { 'Sending request: %j', request ); + + this._traceUtil + .currentSpan() + .addEvent(`Firestore.${methodName}: Start`); + try { const stream = bidirectional ? gapicClient[methodName](callOptions) @@ -1905,6 +1969,18 @@ export class Firestore implements firestore.Firestore { 'Received response: %j', chunk ); + numResponses++; + if (numResponses === 1) { + this._traceUtil + .currentSpan() + .addEvent(`Firestore.${methodName}: First response received`); + } else if (numResponses % NUM_RESPONSES_PER_TRACE_EVENT === 0) { + this._traceUtil + .currentSpan() + .addEvent( + `Firestore.${methodName}: Received ${numResponses} responses` + ); + } callback(); }, }); @@ -1917,7 +1993,14 @@ export class Firestore implements firestore.Firestore { requestTag, bidirectional ? request : undefined ); - resultStream.on('end', () => stream.end()); + resultStream.on('end', () => { + stream.end(); + this._traceUtil + .currentSpan() + .addEvent(`Firestore.${methodName}: Completed`, { + [ATTRIBUTE_KEY_NUM_RESPONSES]: numResponses, + }); + }); result.resolve(resultStream); // While we return the stream to the callee early, we don't want to diff --git a/dev/src/reference/aggregate-query.ts b/dev/src/reference/aggregate-query.ts index fa88567a2..57e63d671 100644 --- a/dev/src/reference/aggregate-query.ts +++ b/dev/src/reference/aggregate-query.ts @@ -39,6 +39,10 @@ import {AggregateQuerySnapshot} from './aggregate-query-snapshot'; import {Query} from './query'; import {Readable, Transform} from 'stream'; import {QueryResponse, QuerySnapshotResponse} from './types'; +import { + SPAN_NAME_AGGREGATION_QUERY_GET, + SPAN_NAME_RUN_AGGREGATION_QUERY, +} from '../telemetry/trace-util'; /** * A query that calculates aggregations over an underlying query. @@ -90,8 +94,13 @@ export class AggregateQuery< async get(): Promise< AggregateQuerySnapshot > { - const {result} = await this._get(); - return result; + return this._query._firestore._traceUtil.startActiveSpan( + SPAN_NAME_AGGREGATION_QUERY_GET, + async () => { + const {result} = await this._get(); + return result; + } + ); } /** @@ -254,6 +263,13 @@ export class AggregateQuery< 'AggregateQuery failed with stream error:', err ); + + this._query._firestore._traceUtil + .currentSpan() + .addEvent(`${SPAN_NAME_RUN_AGGREGATION_QUERY}: Error.`, { + 'error.message': err.message, + }); + stream.destroy(err); }); backendStream.resume(); diff --git a/dev/src/reference/collection-reference.ts b/dev/src/reference/collection-reference.ts index 9a50a1709..8b065d64b 100644 --- a/dev/src/reference/collection-reference.ts +++ b/dev/src/reference/collection-reference.ts @@ -30,6 +30,10 @@ import {Query} from './query'; import Firestore from '../index'; import {DocumentReference} from './document-reference'; import {QueryOptions} from './query-options'; +import { + SPAN_NAME_COL_REF_ADD, + SPAN_NAME_COL_REF_LIST_DOCUMENTS, +} from '../telemetry/trace-util'; /** * A CollectionReference object can be used for adding documents, getting @@ -164,41 +168,46 @@ export class CollectionReference< listDocuments(): Promise< Array> > { - const tag = requestTag(); - return this.firestore.initializeIfNeeded(tag).then(() => { - const parentPath = this._queryOptions.parentPath.toQualifiedResourcePath( - this.firestore.projectId, - this.firestore.databaseId - ); + return this._firestore._traceUtil.startActiveSpan( + SPAN_NAME_COL_REF_LIST_DOCUMENTS, + () => { + const tag = requestTag(); + return this.firestore.initializeIfNeeded(tag).then(() => { + const parentPath = + this._queryOptions.parentPath.toQualifiedResourcePath( + this.firestore.projectId, + this.firestore.databaseId + ); - const request: api.IListDocumentsRequest = { - parent: parentPath.formattedName, - collectionId: this.id, - showMissing: true, - // Setting `pageSize` to an arbitrarily large value lets the backend cap - // the page size (currently to 300). Note that the backend rejects - // MAX_INT32 (b/146883794). - pageSize: Math.pow(2, 16) - 1, - mask: {fieldPaths: []}, - }; + const request: api.IListDocumentsRequest = { + parent: parentPath.formattedName, + collectionId: this.id, + showMissing: true, + // Setting `pageSize` to an arbitrarily large value lets the backend cap + // the page size (currently to 300). Note that the backend rejects + // MAX_INT32 (b/146883794). + pageSize: Math.pow(2, 16) - 1, + mask: {fieldPaths: []}, + }; - return this.firestore - .request( - 'listDocuments', - request, - tag - ) - .then(documents => { - // Note that the backend already orders these documents by name, - // so we do not need to manually sort them. - return documents.map(doc => { - const path = QualifiedResourcePath.fromSlashSeparatedString( - doc.name! - ); - return this.doc(path.id!); - }); + return this.firestore + .request< + api.IListDocumentsRequest, + api.IDocument[] + >('listDocuments', request, tag) + .then(documents => { + // Note that the backend already orders these documents by name, + // so we do not need to manually sort them. + return documents.map(doc => { + const path = QualifiedResourcePath.fromSlashSeparatedString( + doc.name! + ); + return this.doc(path.id!); + }); + }); }); - }); + } + ); } doc(): DocumentReference; @@ -265,16 +274,21 @@ export class CollectionReference< add( data: firestore.WithFieldValue ): Promise> { - const firestoreData = this._queryOptions.converter.toFirestore(data); - validateDocumentData( - 'data', - firestoreData, - /*allowDeletes=*/ false, - this._allowUndefined - ); + return this._firestore._traceUtil.startActiveSpan( + SPAN_NAME_COL_REF_ADD, + () => { + const firestoreData = this._queryOptions.converter.toFirestore(data); + validateDocumentData( + 'data', + firestoreData, + /*allowDeletes=*/ false, + this._allowUndefined + ); - const documentRef = this.doc(); - return documentRef.create(data).then(() => documentRef); + const documentRef = this.doc(); + return documentRef.create(data).then(() => documentRef); + } + ); } /** diff --git a/dev/src/reference/document-reference.ts b/dev/src/reference/document-reference.ts index 48c2799aa..52f6d8425 100644 --- a/dev/src/reference/document-reference.ts +++ b/dev/src/reference/document-reference.ts @@ -27,6 +27,14 @@ import {requestTag} from '../util'; import {validateFunction, validateMinNumberOfArguments} from '../validate'; import {DocumentWatch} from '../watch'; import {DocumentSnapshotBuilder} from '../document'; +import { + SPAN_NAME_DOC_REF_CREATE, + SPAN_NAME_DOC_REF_DELETE, + SPAN_NAME_DOC_REF_GET, + SPAN_NAME_DOC_REF_LIST_COLLECTIONS, + SPAN_NAME_DOC_REF_SET, + SPAN_NAME_DOC_REF_UPDATE, +} from '../telemetry/trace-util'; /** * A DocumentReference refers to a document location in a Firestore database @@ -198,7 +206,12 @@ export class DocumentReference< * ``` */ get(): Promise> { - return this._firestore.getAll(this).then(([result]) => result); + return this._firestore._traceUtil.startActiveSpan( + SPAN_NAME_DOC_REF_GET, + () => { + return this._firestore.getAll(this).then(([result]) => result); + } + ); } /** @@ -247,35 +260,39 @@ export class DocumentReference< * ``` */ listCollections(): Promise> { - const tag = requestTag(); - return this.firestore.initializeIfNeeded(tag).then(() => { - const request: api.IListCollectionIdsRequest = { - parent: this.formattedName, - // Setting `pageSize` to an arbitrarily large value lets the backend cap - // the page size (currently to 300). Note that the backend rejects - // MAX_INT32 (b/146883794). - pageSize: Math.pow(2, 16) - 1, - }; - return this._firestore - .request( - 'listCollectionIds', - request, - tag - ) - .then(collectionIds => { - const collections: Array = []; + return this._firestore._traceUtil.startActiveSpan( + SPAN_NAME_DOC_REF_LIST_COLLECTIONS, + () => { + const tag = requestTag(); + return this.firestore.initializeIfNeeded(tag).then(() => { + const request: api.IListCollectionIdsRequest = { + parent: this.formattedName, + // Setting `pageSize` to an arbitrarily large value lets the backend cap + // the page size (currently to 300). Note that the backend rejects + // MAX_INT32 (b/146883794). + pageSize: Math.pow(2, 16) - 1, + }; + return this._firestore + .request< + api.IListCollectionIdsRequest, + string[] + >('listCollectionIds', request, tag) + .then(collectionIds => { + const collections: Array = []; - // We can just sort this list using the default comparator since it - // will only contain collection ids. - collectionIds.sort(); + // We can just sort this list using the default comparator since it + // will only contain collection ids. + collectionIds.sort(); - for (const collectionId of collectionIds) { - collections.push(this.collection(collectionId)); - } + for (const collectionId of collectionIds) { + collections.push(this.collection(collectionId)); + } - return collections; + return collections; + }); }); - }); + } + ); } /** @@ -300,11 +317,16 @@ export class DocumentReference< * ``` */ create(data: firestore.WithFieldValue): Promise { - const writeBatch = new WriteBatch(this._firestore); - return writeBatch - .create(this, data) - .commit() - .then(([writeResult]) => writeResult); + return this._firestore._traceUtil.startActiveSpan( + SPAN_NAME_DOC_REF_CREATE, + () => { + const writeBatch = new WriteBatch(this._firestore); + return writeBatch + .create(this, data) + .commit() + .then(([writeResult]) => writeResult); + } + ); } /** @@ -333,11 +355,16 @@ export class DocumentReference< * ``` */ delete(precondition?: firestore.Precondition): Promise { - const writeBatch = new WriteBatch(this._firestore); - return writeBatch - .delete(this, precondition) - .commit() - .then(([writeResult]) => writeResult); + return this._firestore._traceUtil.startActiveSpan( + SPAN_NAME_DOC_REF_DELETE, + () => { + const writeBatch = new WriteBatch(this._firestore); + return writeBatch + .delete(this, precondition) + .commit() + .then(([writeResult]) => writeResult); + } + ); } set( @@ -379,16 +406,21 @@ export class DocumentReference< data: firestore.PartialWithFieldValue, options?: firestore.SetOptions ): Promise { - let writeBatch = new WriteBatch(this._firestore); - if (options) { - writeBatch = writeBatch.set(this, data, options); - } else { - writeBatch = writeBatch.set( - this, - data as firestore.WithFieldValue - ); - } - return writeBatch.commit().then(([writeResult]) => writeResult); + return this._firestore._traceUtil.startActiveSpan( + SPAN_NAME_DOC_REF_SET, + () => { + let writeBatch = new WriteBatch(this._firestore); + if (options) { + writeBatch = writeBatch.set(this, data, options); + } else { + writeBatch = writeBatch.set( + this, + data as firestore.WithFieldValue + ); + } + return writeBatch.commit().then(([writeResult]) => writeResult); + } + ); } /** @@ -432,14 +464,19 @@ export class DocumentReference< unknown | string | firestore.FieldPath | firestore.Precondition > ): Promise { - // eslint-disable-next-line prefer-rest-params - validateMinNumberOfArguments('DocumentReference.update', arguments, 1); + return this._firestore._traceUtil.startActiveSpan( + SPAN_NAME_DOC_REF_UPDATE, + () => { + // eslint-disable-next-line prefer-rest-params + validateMinNumberOfArguments('DocumentReference.update', arguments, 1); - const writeBatch = new WriteBatch(this._firestore); - return writeBatch - .update(this, dataOrField, ...preconditionOrValues) - .commit() - .then(([writeResult]) => writeResult); + const writeBatch = new WriteBatch(this._firestore); + return writeBatch + .update(this, dataOrField, ...preconditionOrValues) + .commit() + .then(([writeResult]) => writeResult); + } + ); } /** diff --git a/dev/src/reference/query-util.ts b/dev/src/reference/query-util.ts index a475ce7a2..8aad95888 100644 --- a/dev/src/reference/query-util.ts +++ b/dev/src/reference/query-util.ts @@ -40,6 +40,11 @@ import {NOOP_MESSAGE} from './constants'; import * as protos from '../../protos/firestore_v1_proto_api'; import api = protos.google.firestore.v1; +import { + ATTRIBUTE_KEY_IS_RETRY_WITH_CURSOR, + ATTRIBUTE_KEY_IS_TRANSACTIONAL, + SPAN_NAME_RUN_QUERY, +} from '../telemetry/trace-util'; export class QueryUtil< AppModelType, @@ -176,6 +181,7 @@ export class QueryUtil< const startTime = Date.now(); const isExplain = explainOptions !== undefined; + let numDocumentsReceived = 0; let lastReceivedDocument: QueryDocumentSnapshot< AppModelType, DbModelType @@ -234,6 +240,7 @@ export class QueryUtil< ); } + ++numDocumentsReceived; callback(undefined, output); if (proto.done) { @@ -254,10 +261,19 @@ export class QueryUtil< // catch below. let request = query.toProto(transactionOrReadTime, explainOptions); + let isRetryRequestWithCursor = false; let streamActive: Deferred; do { streamActive = new Deferred(); const methodName = 'runQuery'; + + this._firestore._traceUtil + .currentSpan() + .addEvent(SPAN_NAME_RUN_QUERY, { + [ATTRIBUTE_KEY_IS_TRANSACTIONAL]: !!request.transaction, + [ATTRIBUTE_KEY_IS_RETRY_WITH_CURSOR]: isRetryRequestWithCursor, + }); + backendStream = await this._firestore.requestStream( methodName, /* bidirectional= */ false, @@ -274,7 +290,7 @@ export class QueryUtil< if ( !isExplain && !transactionOrReadTime && - !this._isPermanentRpcError(err, 'runQuery') + !this._isPermanentRpcError(err, methodName) ) { logger( 'QueryUtil._stream', @@ -283,6 +299,12 @@ export class QueryUtil< err ); + this._firestore._traceUtil + .currentSpan() + .addEvent(`${SPAN_NAME_RUN_QUERY}: Retryable Error.`, { + 'error.message': err.message, + }); + // Enqueue a "no-op" write into the stream and wait for it to be // read by the downstream consumer. This ensures that all enqueued // results in the stream are consumed, which will give us an accurate @@ -297,6 +319,12 @@ export class QueryUtil< stream.destroy(err); streamActive.resolve(/* active= */ false); } else if (lastReceivedDocument && retryWithCursor) { + if (query instanceof VectorQuery) { + throw new Error( + 'Unimplemented: Vector query does not support cursors yet.' + ); + } + logger( 'Query._stream', tag, @@ -304,16 +332,36 @@ export class QueryUtil< 'documents, so the stream is being retried.' ); + isRetryRequestWithCursor = true; + // Restart the query but use the last document we received as // the query cursor. Note that we do not use backoff here. The // call to `requestStream()` will backoff should the restart // fail before delivering any results. + let newQuery: Query; + if (!this._queryOptions.limit) { + newQuery = query; + } else { + const newLimit = + this._queryOptions.limit - numDocumentsReceived; + if ( + this._queryOptions.limitType === undefined || + this._queryOptions.limitType === LimitType.First + ) { + newQuery = query.limit(newLimit); + } else { + newQuery = query.limitToLast(newLimit); + } + } + if (this._queryOptions.requireConsistency) { - request = query + request = newQuery .startAfter(lastReceivedDocument) .toProto(lastReceivedDocument.readTime); } else { - request = query.startAfter(lastReceivedDocument).toProto(); + request = newQuery + .startAfter(lastReceivedDocument) + .toProto(); } // Set lastReceivedDocument to null before each retry attempt to ensure the retry makes progress @@ -338,6 +386,13 @@ export class QueryUtil< 'Query failed with stream error:', err ); + + this._firestore._traceUtil + .currentSpan() + .addEvent(`${SPAN_NAME_RUN_QUERY}: Error.`, { + 'error.message': err.message, + }); + stream.destroy(err); streamActive.resolve(/* active= */ false); } diff --git a/dev/src/reference/query.ts b/dev/src/reference/query.ts index e6f1e8d4a..8f900d603 100644 --- a/dev/src/reference/query.ts +++ b/dev/src/reference/query.ts @@ -72,6 +72,7 @@ import { import {VectorQuery} from './vector-query'; import {VectorQueryOptions} from './vector-query-options'; import api = protos.google.firestore.v1; +import {SPAN_NAME_QUERY_GET} from '../telemetry/trace-util'; /** * A Query refers to a query which you can read or stream from. You can also @@ -632,6 +633,9 @@ export class Query< * @param options - Options control the vector query. `limit` specifies the upper bound of documents to return, must * be a positive integer with a maximum value of 1000. `distanceMeasure` specifies what type of distance is calculated * when performing the query. + * + * @deprecated Use the new {@link findNearest} implementation + * accepting a single `options` param. */ findNearest( vectorField: string | firestore.FieldPath, @@ -640,17 +644,77 @@ export class Query< limit: number; distanceMeasure: 'EUCLIDEAN' | 'COSINE' | 'DOT_PRODUCT'; } + ): VectorQuery; + + /** + * Returns a query that can perform vector distance (similarity) search with given parameters. + * + * The returned query, when executed, performs a distance (similarity) search on the specified + * `vectorField` against the given `queryVector` and returns the top documents that are closest + * to the `queryVector`. + * + * Only documents whose `vectorField` field is a {@link VectorValue} of the same dimension as `queryVector` + * participate in the query, all other documents are ignored. + * + * @example + * ``` + * // Returns the closest 10 documents whose Euclidean distance from their 'embedding' fields are closed to [41, 42]. + * const vectorQuery = col.findNearest({ + * vectorField: 'embedding', + * queryVector: [41, 42], + * limit: 10, + * distanceMeasure: 'EUCLIDEAN', + * distanceResultField: 'distance', + * distanceThreshold: 0.125 + * }); + * + * const querySnapshot = await aggregateQuery.get(); + * querySnapshot.forEach(...); + * ``` + * @param options - An argument specifying the behavior of the {@link VectorQuery} returned by this function. + * See {@link VectorQueryOptions}. + */ + findNearest( + options: VectorQueryOptions + ): VectorQuery; + + findNearest( + vectorFieldOrOptions: string | firestore.FieldPath | VectorQueryOptions, + queryVector?: firestore.VectorValue | Array, + options?: { + limit?: number; + distanceMeasure?: 'EUCLIDEAN' | 'COSINE' | 'DOT_PRODUCT'; + } + ): VectorQuery { + if ( + typeof vectorFieldOrOptions === 'string' || + vectorFieldOrOptions instanceof FieldPath + ) { + const vqOptions: VectorQueryOptions = { + distanceMeasure: options!.distanceMeasure!, + limit: options!.limit!, + queryVector: queryVector!, + vectorField: vectorFieldOrOptions, + }; + return this._findNearest(vqOptions); + } else { + return this._findNearest(vectorFieldOrOptions as VectorQueryOptions); + } + } + + _findNearest( + options: VectorQueryOptions ): VectorQuery { - validateFieldPath('vectorField', vectorField); + validateFieldPath('vectorField', options.vectorField); if (options.limit <= 0) { - throw invalidArgumentMessage('options.limit', 'positive limit number'); + throw invalidArgumentMessage('limit', 'positive limit number'); } if ( - (Array.isArray(queryVector) - ? queryVector.length - : queryVector.toArray().length) === 0 + (Array.isArray(options.queryVector) + ? options.queryVector.length + : options.queryVector.toArray().length) === 0 ) { throw invalidArgumentMessage( 'queryVector', @@ -658,12 +722,7 @@ export class Query< ); } - return new VectorQuery( - this, - vectorField, - queryVector, - new VectorQueryOptions(options.limit, options.distanceMeasure) - ); + return new VectorQuery(this, options); } pipeline(): Pipeline { @@ -1161,8 +1220,13 @@ export class Query< * ``` */ async get(): Promise> { - const {result} = await this._get(); - return result; + return this._firestore._traceUtil.startActiveSpan( + SPAN_NAME_QUERY_GET, + async () => { + const {result} = await this._get(); + return result; + } + ); } /** diff --git a/dev/src/reference/vector-query-options.ts b/dev/src/reference/vector-query-options.ts index cc083aa62..10a851a96 100644 --- a/dev/src/reference/vector-query-options.ts +++ b/dev/src/reference/vector-query-options.ts @@ -14,23 +14,48 @@ * limitations under the License. */ -export class VectorQueryOptions { - constructor( - readonly limit: number, - readonly distanceMeasure: 'EUCLIDEAN' | 'COSINE' | 'DOT_PRODUCT' - ) {} +import * as firestore from '@google-cloud/firestore'; - isEqual(other: VectorQueryOptions): boolean { - if (this === other) { - return true; - } - if (!(other instanceof VectorQueryOptions)) { - return false; - } +/** + * Specifies the behavior of the {@link VectorQuery} generated by a call to {@link Query.findNearest}. + */ +export interface VectorQueryOptions { + /** + * A string or {@link FieldPath} specifying the vector field to search on. + */ + vectorField: string | firestore.FieldPath; + + /** + * The {@link VectorValue} used to measure the distance from `vectorField` values in the documents. + */ + queryVector: firestore.VectorValue | Array; + + /** + * Specifies the upper bound of documents to return, must be a positive integer with a maximum value of 1000. + */ + limit: number; + + /** + * Specifies what type of distance is calculated when performing the query. + */ + distanceMeasure: 'EUCLIDEAN' | 'COSINE' | 'DOT_PRODUCT'; + + /** + * Optionally specifies the name of a field that will be set on each returned DocumentSnapshot, + * which will contain the computed distance for the document. + */ + distanceResultField?: string | firestore.FieldPath; - return ( - this.limit === other.limit && - this.distanceMeasure === other.distanceMeasure - ); - } + /** + * Specifies a threshold for which no less similar documents will be returned. The behavior + * of the specified `distanceMeasure` will affect the meaning of the distance threshold. + * + * - For `distanceMeasure: "EUCLIDEAN"`, the meaning of `distanceThreshold` is: + * SELECT docs WHERE euclidean_distance <= distanceThreshold + * - For `distanceMeasure: "COSINE"`, the meaning of `distanceThreshold` is: + * SELECT docs WHERE cosine_distance <= distanceThreshold + * - For `distanceMeasure: "DOT_PRODUCT"`, the meaning of `distanceThreshold` is: + * SELECT docs WHERE dot_product_distance >= distanceThreshold + */ + distanceThreshold?: number; } diff --git a/dev/src/reference/vector-query.ts b/dev/src/reference/vector-query.ts index c1d783ea8..62553a875 100644 --- a/dev/src/reference/vector-query.ts +++ b/dev/src/reference/vector-query.ts @@ -59,9 +59,7 @@ export class VectorQuery< */ constructor( private readonly _query: Query, - private readonly vectorField: string | firestore.FieldPath, - private readonly queryVector: firestore.VectorValue | Array, - private readonly options: VectorQueryOptions + private readonly _options: VectorQueryOptions ) { this._queryUtil = new QueryUtil< AppModelType, @@ -82,9 +80,21 @@ export class VectorQuery< * @internal */ private get _rawVectorField(): string { - return typeof this.vectorField === 'string' - ? this.vectorField - : this.vectorField.toString(); + return typeof this._options.vectorField === 'string' + ? this._options.vectorField + : this._options.vectorField.toString(); + } + + /** + * @private + * @internal + */ + private get _rawDistanceResultField(): string | undefined { + if (typeof this._options.distanceResultField === 'undefined') return; + + return typeof this._options.distanceResultField === 'string' + ? this._options.distanceResultField + : this._options.distanceResultField.toString(); } /** @@ -92,9 +102,9 @@ export class VectorQuery< * @internal */ private get _rawQueryVector(): Array { - return Array.isArray(this.queryVector) - ? this.queryVector - : this.queryVector.toArray(); + return Array.isArray(this._options.queryVector) + ? this._options.queryVector + : this._options.queryVector.toArray(); } /** @@ -133,17 +143,17 @@ export class VectorQuery< toPipeline(): Pipeline { const options: FindNearestOptions = { - field: Field.of(this.vectorField), - vectorValue: this.queryVector, - limit: this.options.limit, - distanceMeasure: this.options.distanceMeasure.toLowerCase() as + field: Field.of(this._options.vectorField), + vectorValue: this._options.queryVector, + limit: this._options.limit, + distanceMeasure: this._options.distanceMeasure.toLowerCase() as | 'cosine' | 'euclidean' | 'dot_product', }; return this.query .pipeline() - .where(Field.of(this.vectorField).exists()) + .where(Field.of(this._options.vectorField).exists()) .findNearest(options); } @@ -176,7 +186,7 @@ export class VectorQuery< } /** - * Internal method for serializing a query to its RunAggregationQuery proto + * Internal method for serializing a query to its proto * representation with an optional transaction id. * * @private @@ -189,17 +199,25 @@ export class VectorQuery< ): api.IRunQueryRequest { const queryProto = this._query.toProto(transactionOrReadTime); - const queryVector = Array.isArray(this.queryVector) - ? new VectorValue(this.queryVector) - : (this.queryVector as VectorValue); + const queryVector = Array.isArray(this._options.queryVector) + ? new VectorValue(this._options.queryVector) + : (this._options.queryVector as VectorValue); queryProto.structuredQuery!.findNearest = { - limit: {value: this.options.limit}, - distanceMeasure: this.options.distanceMeasure, + limit: {value: this._options.limit}, + distanceMeasure: this._options.distanceMeasure, vectorField: { - fieldPath: FieldPath.fromArgument(this.vectorField).formattedName, + fieldPath: FieldPath.fromArgument(this._options.vectorField) + .formattedName, }, queryVector: queryVector._toProto(this._query._serializer), + distanceResultField: this._options?.distanceResultField + ? FieldPath.fromArgument(this._options.distanceResultField!) + .formattedName + : undefined, + distanceThreshold: this._options?.distanceThreshold + ? {value: this._options?.distanceThreshold} + : undefined, }; if (explainOptions) { @@ -272,7 +290,10 @@ export class VectorQuery< return ( this._rawVectorField === other._rawVectorField && isPrimitiveArrayEqual(this._rawQueryVector, other._rawQueryVector) && - this.options.isEqual(other.options) + this._options.limit === other._options.limit && + this._options.distanceMeasure === other._options.distanceMeasure && + this._options.distanceThreshold === other._options.distanceThreshold && + this._rawDistanceResultField === other._rawDistanceResultField ); } } diff --git a/dev/src/telemetry/disabled-trace-util.ts b/dev/src/telemetry/disabled-trace-util.ts new file mode 100644 index 000000000..c4c6cce6a --- /dev/null +++ b/dev/src/telemetry/disabled-trace-util.ts @@ -0,0 +1,42 @@ +/** + * Copyright 2024 Google LLC. All Rights Reserved. + * + * 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. + */ +import {Attributes, TraceUtil} from './trace-util'; +import {Span} from './span'; + +export class DisabledTraceUtil implements TraceUtil { + // eslint-disable-next-line @typescript-eslint/no-unused-vars + startSpan(name: string): Span { + return new Span(); + } + + startActiveSpan unknown>( + // eslint-disable-next-line @typescript-eslint/no-unused-vars + name: string, + fn: F, + // eslint-disable-next-line @typescript-eslint/no-unused-vars + attributes?: Attributes + ): ReturnType { + const emptySpan = new Span(); + return fn(emptySpan) as ReturnType; + } + + currentSpan(): Span { + return new Span(); + } + + // eslint-disable-next-line @typescript-eslint/no-unused-vars + recordProjectId(projectId: string): void {} +} diff --git a/dev/src/telemetry/enabled-trace-util.ts b/dev/src/telemetry/enabled-trace-util.ts new file mode 100644 index 000000000..0fdbaf582 --- /dev/null +++ b/dev/src/telemetry/enabled-trace-util.ts @@ -0,0 +1,197 @@ +/** + * Copyright 2024 Google LLC. All Rights Reserved. + * + * 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. + */ + +import {Settings} from '@google-cloud/firestore'; + +import { + context, + SpanStatusCode, + trace, + Tracer, + Span as OpenTelemetrySpan, +} from '@opentelemetry/api'; + +import {Span} from './span'; +import {ATTRIBUTE_SETTINGS_PREFIX, Attributes, TraceUtil} from './trace-util'; + +import {interfaces} from '../v1/firestore_client_config.json'; +import {FirestoreClient} from '../v1'; +import {DEFAULT_DATABASE_ID} from '../path'; +import {DEFAULT_MAX_IDLE_CHANNELS} from '../index'; +const serviceConfig = interfaces['google.firestore.v1.Firestore']; + +export class EnabledTraceUtil implements TraceUtil { + private tracer: Tracer; + private settingsAttributes: Attributes; + + constructor(settings: Settings) { + let tracerProvider = settings.openTelemetryOptions?.tracerProvider; + + // If a TracerProvider has not been given to us, we try to use the global one. + if (!tracerProvider) { + const {trace} = require('@opentelemetry/api'); + tracerProvider = trace.getTracerProvider(); + } + + const libVersion = require('../../../package.json').version; + const libName = require('../../../package.json').name; + this.tracer = tracerProvider.getTracer(libName, libVersion); + + this.settingsAttributes = {}; + this.settingsAttributes['otel.scope.name'] = libName; + this.settingsAttributes['otel.scope.version'] = libVersion; + + if (settings.projectId) { + this.settingsAttributes[`${ATTRIBUTE_SETTINGS_PREFIX}.project_id`] = + settings.projectId; + } + + this.settingsAttributes[`${ATTRIBUTE_SETTINGS_PREFIX}.database_id`] = + settings.databaseId || DEFAULT_DATABASE_ID; + + const host = + settings.servicePath ?? settings.host ?? 'firestore.googleapis.com'; + const port = settings.port ?? FirestoreClient.port; + this.settingsAttributes[`${ATTRIBUTE_SETTINGS_PREFIX}.host`] = + `${host}:${port}`; + + if (settings.preferRest !== undefined) { + this.settingsAttributes[`${ATTRIBUTE_SETTINGS_PREFIX}.prefer_REST`] = + settings.preferRest; + } + + this.settingsAttributes[`${ATTRIBUTE_SETTINGS_PREFIX}.max_idle_channels`] = + settings.maxIdleChannels ?? DEFAULT_MAX_IDLE_CHANNELS; + + const defaultRetrySettings = serviceConfig.retry_params.default; + const customRetrySettings = + settings.clientConfig?.interfaces?.['google.firestore.v1.Firestore']?.[ + 'retry_params' + ]?.['default']; + this.settingsAttributes[ + `${ATTRIBUTE_SETTINGS_PREFIX}.initial_retry_delay` + ] = this.millisToSecondString( + customRetrySettings?.initial_retry_delay_millis ?? + defaultRetrySettings.initial_retry_delay_millis + ); + this.settingsAttributes[ + `${ATTRIBUTE_SETTINGS_PREFIX}.initial_rpc_timeout` + ] = this.millisToSecondString( + customRetrySettings?.initial_rpc_timeout_millis ?? + defaultRetrySettings.initial_rpc_timeout_millis + ); + this.settingsAttributes[`${ATTRIBUTE_SETTINGS_PREFIX}.total_timeout`] = + this.millisToSecondString( + customRetrySettings?.total_timeout_millis ?? + defaultRetrySettings.total_timeout_millis + ); + this.settingsAttributes[`${ATTRIBUTE_SETTINGS_PREFIX}.max_retry_delay`] = + this.millisToSecondString( + customRetrySettings?.max_retry_delay_millis ?? + defaultRetrySettings.max_retry_delay_millis + ); + this.settingsAttributes[`${ATTRIBUTE_SETTINGS_PREFIX}.max_rpc_timeout`] = + this.millisToSecondString( + customRetrySettings?.max_rpc_timeout_millis ?? + defaultRetrySettings.max_rpc_timeout_millis + ); + this.settingsAttributes[ + `${ATTRIBUTE_SETTINGS_PREFIX}.retry_delay_multiplier` + ] = + customRetrySettings?.retry_delay_multiplier.toString() ?? + defaultRetrySettings.retry_delay_multiplier.toString(); + this.settingsAttributes[ + `${ATTRIBUTE_SETTINGS_PREFIX}.rpc_timeout_multiplier` + ] = + customRetrySettings?.rpc_timeout_multiplier.toString() ?? + defaultRetrySettings.rpc_timeout_multiplier.toString(); + } + + recordProjectId(projectId: string): void { + this.settingsAttributes[`${ATTRIBUTE_SETTINGS_PREFIX}.project_id`] = + projectId; + this.currentSpan().setAttributes(this.settingsAttributes); + } + + private millisToSecondString(millis: number): string { + return `${millis / 1000}s`; + } + + private endSpan(otelSpan: OpenTelemetrySpan, error: Error): void { + otelSpan.setStatus({ + code: SpanStatusCode.ERROR, + message: error.message, + }); + otelSpan.recordException(error); + otelSpan.end(); + } + + startActiveSpan unknown>( + name: string, + fn: F, + attributes?: Attributes + ): ReturnType { + return this.tracer.startActiveSpan( + name, + { + attributes: attributes, + }, + (otelSpan: OpenTelemetrySpan) => { + this.addCommonAttributes(otelSpan); + + // Note that if `fn` returns a `Promise`, we want the otelSpan to end + // after the `Promise` has resolved, NOT after the `fn` has returned. + // Therefore, we should not use a `finally` clause to end the otelSpan. + try { + let result = fn(new Span(otelSpan)); + if (result instanceof Promise) { + result = result + .then(value => { + otelSpan.end(); + return value; + }) + .catch(error => { + this.endSpan(otelSpan, error); + // Returns a Promise.reject the same as the underlying function. + return Promise.reject(error); + }); + } else { + otelSpan.end(); + } + return result as ReturnType; + } catch (error) { + this.endSpan(otelSpan, error); + // Re-throw the exception to maintain normal error handling. + throw error; + } + } + ); + } + + startSpan(name: string): Span { + const otelSpan = this.tracer.startSpan(name, undefined, context.active()); + this.addCommonAttributes(otelSpan); + return new Span(otelSpan); + } + + currentSpan(): Span { + return new Span(trace.getActiveSpan()); + } + + addCommonAttributes(otelSpan: OpenTelemetrySpan): void { + otelSpan.setAttributes(this.settingsAttributes); + } +} diff --git a/dev/src/telemetry/span.ts b/dev/src/telemetry/span.ts new file mode 100644 index 000000000..a4ad6e249 --- /dev/null +++ b/dev/src/telemetry/span.ts @@ -0,0 +1,36 @@ +/** + * Copyright 2024 Google LLC. All Rights Reserved. + * + * 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. + */ + +import {Span as OpenTelemetrySpan} from '@opentelemetry/api'; +import {Attributes} from './trace-util'; + +export class Span { + constructor(private span?: OpenTelemetrySpan) {} + + end(): void { + this.span?.end(); + } + + addEvent(name: string, attributes?: Attributes): this { + this.span = this.span?.addEvent(name, attributes); + return this; + } + + setAttributes(attributes: Attributes): this { + this.span = this.span?.setAttributes(attributes); + return this; + } +} diff --git a/dev/src/telemetry/trace-util.ts b/dev/src/telemetry/trace-util.ts new file mode 100644 index 000000000..ff5a8b071 --- /dev/null +++ b/dev/src/telemetry/trace-util.ts @@ -0,0 +1,81 @@ +/** + * Copyright 2024 Google LLC. All Rights Reserved. + * + * 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. + */ + +import {Span} from './span'; + +export interface Attributes { + [attributeKey: string]: AttributeValue | undefined; +} +export declare type AttributeValue = + | string + | number + | boolean + | Array + | Array + | Array; + +/** + * Span names for instrumented operations. + */ +export const SERVICE = 'google.firestore.v1.Firestore/'; +export const SPAN_NAME_BATCH_GET_DOCUMENTS = 'BatchGetDocuments'; +export const SPAN_NAME_RUN_QUERY = 'RunQuery'; +export const SPAN_NAME_RUN_AGGREGATION_QUERY = 'RunAggregationQuery'; +export const SPAN_NAME_DOC_REF_CREATE = 'DocumentReference.Create'; +export const SPAN_NAME_DOC_REF_SET = 'DocumentReference.Set'; +export const SPAN_NAME_DOC_REF_UPDATE = 'DocumentReference.Update'; +export const SPAN_NAME_DOC_REF_DELETE = 'DocumentReference.Delete'; +export const SPAN_NAME_DOC_REF_GET = 'DocumentReference.Get'; +export const SPAN_NAME_DOC_REF_LIST_COLLECTIONS = + 'DocumentReference.ListCollections'; +export const SPAN_NAME_COL_REF_ADD = 'CollectionReference.Add'; +export const SPAN_NAME_COL_REF_LIST_DOCUMENTS = + 'CollectionReference.ListDocuments'; +export const SPAN_NAME_QUERY_GET = 'Query.Get'; +export const SPAN_NAME_AGGREGATION_QUERY_GET = 'AggregationQuery.Get'; +export const SPAN_NAME_TRANSACTION_RUN = 'Transaction.Run'; +export const SPAN_NAME_TRANSACTION_GET_QUERY = 'Transaction.Get.Query'; +export const SPAN_NAME_TRANSACTION_GET_AGGREGATION_QUERY = + 'Transaction.Get.AggregationQuery'; +export const SPAN_NAME_TRANSACTION_GET_DOCUMENT = 'Transaction.Get.Document'; +export const SPAN_NAME_TRANSACTION_GET_DOCUMENTS = 'Transaction.Get.Documents'; +export const SPAN_NAME_TRANSACTION_ROLLBACK = 'Transaction.Rollback'; +export const SPAN_NAME_TRANSACTION_COMMIT = 'Transaction.Commit'; +export const SPAN_NAME_BATCH_COMMIT = 'Batch.Commit'; +export const SPAN_NAME_PARTITION_QUERY = 'PartitionQuery'; +export const SPAN_NAME_BULK_WRITER_COMMIT = 'BulkWriter.Commit'; +export const ATTRIBUTE_SERVICE_PREFIX = 'gcp.firestore'; +export const ATTRIBUTE_SETTINGS_PREFIX = `${ATTRIBUTE_SERVICE_PREFIX}.settings`; +export const ATTRIBUTE_KEY_DOC_COUNT = 'doc_count'; +export const ATTRIBUTE_KEY_IS_TRANSACTIONAL = 'transactional'; +export const ATTRIBUTE_KEY_NUM_RESPONSES = 'response_count'; +export const ATTRIBUTE_KEY_IS_RETRY_WITH_CURSOR = 'retry_query_with_cursor'; +export const ATTRIBUTE_KEY_TRANSACTION_TYPE = 'transaction_type'; +export const ATTRIBUTE_KEY_ATTEMPTS_ALLOWED = 'attempts_allowed'; +export const ATTRIBUTE_KEY_ATTEMPTS_REMAINING = 'attempts_remaining'; + +export interface TraceUtil { + startActiveSpan unknown>( + name: string, + fn: F, + attributes?: Attributes + ): ReturnType; + startSpan(name: string): Span; + + currentSpan(): Span; + + recordProjectId(projectId: string): void; +} diff --git a/dev/src/transaction.ts b/dev/src/transaction.ts index abc101a13..f2b105246 100644 --- a/dev/src/transaction.ts +++ b/dev/src/transaction.ts @@ -43,6 +43,20 @@ import { } from './validate'; import {DocumentReader} from './document-reader'; import api = proto.google.firestore.v1; +import { + ATTRIBUTE_KEY_ATTEMPTS_ALLOWED, + ATTRIBUTE_KEY_ATTEMPTS_REMAINING, + ATTRIBUTE_KEY_DOC_COUNT, + ATTRIBUTE_KEY_IS_TRANSACTIONAL, + ATTRIBUTE_KEY_TRANSACTION_TYPE, + SPAN_NAME_TRANSACTION_COMMIT, + SPAN_NAME_TRANSACTION_GET_AGGREGATION_QUERY, + SPAN_NAME_TRANSACTION_GET_DOCUMENT, + SPAN_NAME_TRANSACTION_GET_DOCUMENTS, + SPAN_NAME_TRANSACTION_GET_QUERY, + SPAN_NAME_TRANSACTION_ROLLBACK, + SPAN_NAME_TRANSACTION_RUN, +} from './telemetry/trace-util'; /*! * Error message for transactional reads that were executed after performing @@ -199,11 +213,23 @@ export class Transaction implements firestore.Transaction { } if (refOrQuery instanceof DocumentReference) { - return this.withLazyStartedTransaction(refOrQuery, this.getSingleFn); + return this._firestore._traceUtil.startActiveSpan( + SPAN_NAME_TRANSACTION_GET_DOCUMENT, + () => { + return this.withLazyStartedTransaction(refOrQuery, this.getSingleFn); + } + ); } if (refOrQuery instanceof Query || refOrQuery instanceof AggregateQuery) { - return this.withLazyStartedTransaction(refOrQuery, this.getQueryFn); + return this._firestore._traceUtil.startActiveSpan( + refOrQuery instanceof Query + ? SPAN_NAME_TRANSACTION_GET_QUERY + : SPAN_NAME_TRANSACTION_GET_AGGREGATION_QUERY, + () => { + return this.withLazyStartedTransaction(refOrQuery, this.getQueryFn); + } + ); } throw new Error( @@ -509,27 +535,36 @@ export class Transaction implements firestore.Transaction { * @internal */ async commit(): Promise { - if (!this._writeBatch) { - throw new Error(READ_ONLY_WRITE_ERROR_MSG); - } + return this._firestore._traceUtil.startActiveSpan( + SPAN_NAME_TRANSACTION_COMMIT, + async () => { + if (!this._writeBatch) { + throw new Error(READ_ONLY_WRITE_ERROR_MSG); + } - // If we have not performed any reads in this particular attempt - // then the writes will be atomically committed without a transaction ID - let transactionId: Uint8Array | undefined; - if (this._transactionIdPromise) { - transactionId = await this._transactionIdPromise; - } else if (this._writeBatch.isEmpty) { - // If we have not started a transaction (no reads) and we have no writes - // then the commit is a no-op (success) - return; - } + // If we have not performed any reads in this particular attempt + // then the writes will be atomically committed without a transaction ID + let transactionId: Uint8Array | undefined; + if (this._transactionIdPromise) { + transactionId = await this._transactionIdPromise; + } else if (this._writeBatch.isEmpty) { + // If we have not started a transaction (no reads) and we have no writes + // then the commit is a no-op (success) + return; + } - await this._writeBatch._commit({ - transactionId, - requestTag: this._requestTag, - }); - this._transactionIdPromise = undefined; - this._prevTransactionId = transactionId; + await this._writeBatch._commit({ + transactionId, + requestTag: this._requestTag, + }); + this._transactionIdPromise = undefined; + this._prevTransactionId = transactionId; + }, + { + [ATTRIBUTE_KEY_IS_TRANSACTIONAL]: true, + [ATTRIBUTE_KEY_DOC_COUNT]: this._writeBatch?._opCount, + } + ); } /** @@ -541,43 +576,48 @@ export class Transaction implements firestore.Transaction { * @internal */ async rollback(): Promise { - // No need to roll back if we have not lazily started the transaction - // or if we are read only - if (!this._transactionIdPromise || !this._writeBatch) { - return; - } + return this._firestore._traceUtil.startActiveSpan( + SPAN_NAME_TRANSACTION_ROLLBACK, + async () => { + // No need to roll back if we have not lazily started the transaction + // or if we are read only + if (!this._transactionIdPromise || !this._writeBatch) { + return; + } - let transactionId: Uint8Array; - try { - transactionId = await this._transactionIdPromise; - } catch { - // This means the initial read operation rejected - // and we do not have a transaction ID to roll back - this._transactionIdPromise = undefined; - return; - } + let transactionId: Uint8Array; + try { + transactionId = await this._transactionIdPromise; + } catch { + // This means the initial read operation rejected + // and we do not have a transaction ID to roll back + this._transactionIdPromise = undefined; + return; + } - const request: api.IRollbackRequest = { - database: this._firestore.formattedName, - transaction: transactionId, - }; - this._transactionIdPromise = undefined; - this._prevTransactionId = transactionId; - - // We don't need to wait for rollback to completed before continuing. - // If there are any locks held, then rollback will eventually release them. - // Rollback can be done concurrently thereby reducing latency caused by - // otherwise blocking. - this._firestore - .request('rollback', request, this._requestTag) - .catch(err => { - logger( - 'Firestore.runTransaction', - this._requestTag, - 'Best effort to rollback failed with error:', - err - ); - }); + const request: api.IRollbackRequest = { + database: this._firestore.formattedName, + transaction: transactionId, + }; + this._transactionIdPromise = undefined; + this._prevTransactionId = transactionId; + + // We don't need to wait for rollback to completed before continuing. + // If there are any locks held, then rollback will eventually release them. + // Rollback can be done concurrently thereby reducing latency caused by + // otherwise blocking. + this._firestore + .request('rollback', request, this._requestTag) + .catch(err => { + logger( + 'Firestore.runTransaction', + this._requestTag, + 'Best effort to rollback failed with error:', + err + ); + }); + } + ); } /** @@ -591,45 +631,60 @@ export class Transaction implements firestore.Transaction { async runTransaction( updateFunction: (transaction: Transaction) => Promise ): Promise { - // No backoff is set for readonly transactions (i.e. attempts == 1) - if (!this._writeBatch) { - return this.runTransactionOnce(updateFunction); - } - - let lastError: GoogleError | undefined = undefined; - for (let attempt = 0; attempt < this._maxAttempts; ++attempt) { - try { - if (lastError) { - logger( - 'Firestore.runTransaction', - this._requestTag, - 'Retrying transaction after error:', - lastError - ); + return this._firestore._traceUtil.startActiveSpan( + SPAN_NAME_TRANSACTION_RUN, + async span => { + // No backoff is set for readonly transactions (i.e. attempts == 1) + if (!this._writeBatch) { + return this.runTransactionOnce(updateFunction); } - this._writeBatch._reset(); - - await maybeBackoff(this._backoff!, lastError); + let lastError: GoogleError | undefined = undefined; + for (let attempt = 0; attempt < this._maxAttempts; ++attempt) { + span.setAttributes({ + [ATTRIBUTE_KEY_TRANSACTION_TYPE]: this._writeBatch + ? 'READ_WRITE' + : 'READ_ONLY', + [ATTRIBUTE_KEY_ATTEMPTS_ALLOWED]: this._maxAttempts, + [ATTRIBUTE_KEY_ATTEMPTS_REMAINING]: this._maxAttempts - attempt - 1, + }); + + try { + if (lastError) { + logger( + 'Firestore.runTransaction', + this._requestTag, + 'Retrying transaction after error:', + lastError + ); + + span.addEvent('Initiate transaction retry'); + } + + this._writeBatch._reset(); + + await maybeBackoff(this._backoff!, lastError); + + return await this.runTransactionOnce(updateFunction); + } catch (err) { + lastError = err; + + if (!isRetryableTransactionError(err)) { + break; + } + } + } - return await this.runTransactionOnce(updateFunction); - } catch (err) { - lastError = err; + logger( + 'Firestore.runTransaction', + this._requestTag, + 'Transaction not eligible for retry, returning error: %s', + lastError + ); - if (!isRetryableTransactionError(err)) { - break; - } + return Promise.reject(lastError); } - } - - logger( - 'Firestore.runTransaction', - this._requestTag, - 'Transaction not eligible for retry, returning error: %s', - lastError ); - - return Promise.reject(lastError); } /** @@ -765,13 +820,18 @@ export class Transaction implements firestore.Transaction { transaction?: Uint8Array; result: DocumentSnapshot[]; }> { - const documentReader = new DocumentReader( - this._firestore, - documents, - fieldMask, - opts + return this._firestore._traceUtil.startActiveSpan( + SPAN_NAME_TRANSACTION_GET_DOCUMENTS, + async () => { + const documentReader = new DocumentReader( + this._firestore, + documents, + fieldMask, + opts + ); + return documentReader._get(this._requestTag); + } ); - return documentReader._get(this._requestTag); } private async getQueryFn< diff --git a/dev/src/v1/firestore_admin_client.ts b/dev/src/v1/firestore_admin_client.ts index c4f53923f..bd38f2156 100644 --- a/dev/src/v1/firestore_admin_client.ts +++ b/dev/src/v1/firestore_admin_client.ts @@ -335,6 +335,12 @@ export class FirestoreAdminClient { const importDocumentsMetadata = protoFilesRoot.lookup( '.google.firestore.admin.v1.ImportDocumentsMetadata' ) as gax.protobuf.Type; + const bulkDeleteDocumentsResponse = protoFilesRoot.lookup( + '.google.firestore.admin.v1.BulkDeleteDocumentsResponse' + ) as gax.protobuf.Type; + const bulkDeleteDocumentsMetadata = protoFilesRoot.lookup( + '.google.firestore.admin.v1.BulkDeleteDocumentsMetadata' + ) as gax.protobuf.Type; const createDatabaseResponse = protoFilesRoot.lookup( '.google.firestore.admin.v1.Database' ) as gax.protobuf.Type; @@ -381,6 +387,11 @@ export class FirestoreAdminClient { importDocumentsResponse.decode.bind(importDocumentsResponse), importDocumentsMetadata.decode.bind(importDocumentsMetadata) ), + bulkDeleteDocuments: new this._gaxModule.LongrunningDescriptor( + this.operationsClient, + bulkDeleteDocumentsResponse.decode.bind(bulkDeleteDocumentsResponse), + bulkDeleteDocumentsMetadata.decode.bind(bulkDeleteDocumentsMetadata) + ), createDatabase: new this._gaxModule.LongrunningDescriptor( this.operationsClient, createDatabaseResponse.decode.bind(createDatabaseResponse), @@ -462,6 +473,7 @@ export class FirestoreAdminClient { 'listFields', 'exportDocuments', 'importDocuments', + 'bulkDeleteDocuments', 'createDatabase', 'getDatabase', 'listDatabases', @@ -940,6 +952,8 @@ export class FirestoreAdminClient { * @param {string} request.parent * Required. A parent name of the form * `projects/{project_id}` + * @param {boolean} request.showDeleted + * If true, also returns deleted resources. * @param {object} [options] * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. * @returns {Promise} - The promise which resolves to an array. @@ -2059,7 +2073,8 @@ export class FirestoreAdminClient { * Required. Database to export. Should be of the form: * `projects/{project_id}/databases/{database_id}`. * @param {string[]} request.collectionIds - * Which collection ids to export. Unspecified means all collections. + * Which collection ids to export. Unspecified means all collections. Each + * collection id in this list must be unique. * @param {string} request.outputUriPrefix * The output URI. Currently only supports Google Cloud Storage URIs of the * form: `gs://BUCKET_NAME[/NAMESPACE_PATH]`, where `BUCKET_NAME` is the name @@ -2227,7 +2242,7 @@ export class FirestoreAdminClient { * `projects/{project_id}/databases/{database_id}`. * @param {string[]} request.collectionIds * Which collection ids to import. Unspecified means all collections included - * in the import. + * in the import. Each collection id in this list must be unique. * @param {string} request.inputUriPrefix * Location of the exported files. * This must match the output_uri_prefix of an ExportDocumentsResponse from @@ -2370,6 +2385,166 @@ export class FirestoreAdminClient { protos.google.firestore.admin.v1.ImportDocumentsMetadata >; } + /** + * Bulk deletes a subset of documents from Google Cloud Firestore. + * Documents created or updated after the underlying system starts to process + * the request will not be deleted. The bulk delete occurs in the background + * and its progress can be monitored and managed via the Operation resource + * that is created. + * + * For more details on bulk delete behavior, refer to: + * https://cloud.google.com/firestore/docs/manage-data/bulk-delete + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.name + * Required. Database to operate. Should be of the form: + * `projects/{project_id}/databases/{database_id}`. + * @param {string[]} [request.collectionIds] + * Optional. IDs of the collection groups to delete. Unspecified means all + * collection groups. + * + * Each collection group in this list must be unique. + * @param {string[]} [request.namespaceIds] + * Optional. Namespaces to delete. + * + * An empty list means all namespaces. This is the recommended + * usage for databases that don't use namespaces. + * + * An empty string element represents the default namespace. This should be + * used if the database has data in non-default namespaces, but doesn't want + * to delete from them. + * + * Each namespace in this list must be unique. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is an object representing + * a long running operation. Its `promise()` method returns a promise + * you can `await` for. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#long-running-operations | documentation } + * for more details and examples. + * @example include:samples/generated/v1/firestore_admin.bulk_delete_documents.js + * region_tag:firestore_v1_generated_FirestoreAdmin_BulkDeleteDocuments_async + */ + bulkDeleteDocuments( + request?: protos.google.firestore.admin.v1.IBulkDeleteDocumentsRequest, + options?: CallOptions + ): Promise< + [ + LROperation< + protos.google.firestore.admin.v1.IBulkDeleteDocumentsResponse, + protos.google.firestore.admin.v1.IBulkDeleteDocumentsMetadata + >, + protos.google.longrunning.IOperation | undefined, + {} | undefined, + ] + >; + bulkDeleteDocuments( + request: protos.google.firestore.admin.v1.IBulkDeleteDocumentsRequest, + options: CallOptions, + callback: Callback< + LROperation< + protos.google.firestore.admin.v1.IBulkDeleteDocumentsResponse, + protos.google.firestore.admin.v1.IBulkDeleteDocumentsMetadata + >, + protos.google.longrunning.IOperation | null | undefined, + {} | null | undefined + > + ): void; + bulkDeleteDocuments( + request: protos.google.firestore.admin.v1.IBulkDeleteDocumentsRequest, + callback: Callback< + LROperation< + protos.google.firestore.admin.v1.IBulkDeleteDocumentsResponse, + protos.google.firestore.admin.v1.IBulkDeleteDocumentsMetadata + >, + protos.google.longrunning.IOperation | null | undefined, + {} | null | undefined + > + ): void; + bulkDeleteDocuments( + request?: protos.google.firestore.admin.v1.IBulkDeleteDocumentsRequest, + optionsOrCallback?: + | CallOptions + | Callback< + LROperation< + protos.google.firestore.admin.v1.IBulkDeleteDocumentsResponse, + protos.google.firestore.admin.v1.IBulkDeleteDocumentsMetadata + >, + protos.google.longrunning.IOperation | null | undefined, + {} | null | undefined + >, + callback?: Callback< + LROperation< + protos.google.firestore.admin.v1.IBulkDeleteDocumentsResponse, + protos.google.firestore.admin.v1.IBulkDeleteDocumentsMetadata + >, + protos.google.longrunning.IOperation | null | undefined, + {} | null | undefined + > + ): Promise< + [ + LROperation< + protos.google.firestore.admin.v1.IBulkDeleteDocumentsResponse, + protos.google.firestore.admin.v1.IBulkDeleteDocumentsMetadata + >, + protos.google.longrunning.IOperation | undefined, + {} | undefined, + ] + > | void { + request = request || {}; + let options: CallOptions; + if (typeof optionsOrCallback === 'function' && callback === undefined) { + callback = optionsOrCallback; + options = {}; + } else { + options = optionsOrCallback as CallOptions; + } + options = options || {}; + options.otherArgs = options.otherArgs || {}; + options.otherArgs.headers = options.otherArgs.headers || {}; + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + name: request.name ?? '', + }); + this.initialize(); + return this.innerApiCalls.bulkDeleteDocuments(request, options, callback); + } + /** + * Check the status of the long running operation returned by `bulkDeleteDocuments()`. + * @param {String} name + * The operation name that will be passed. + * @returns {Promise} - The promise which resolves to an object. + * The decoded operation object has result and metadata field to get information from. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#long-running-operations | documentation } + * for more details and examples. + * @example include:samples/generated/v1/firestore_admin.bulk_delete_documents.js + * region_tag:firestore_v1_generated_FirestoreAdmin_BulkDeleteDocuments_async + */ + async checkBulkDeleteDocumentsProgress( + name: string + ): Promise< + LROperation< + protos.google.firestore.admin.v1.BulkDeleteDocumentsResponse, + protos.google.firestore.admin.v1.BulkDeleteDocumentsMetadata + > + > { + const request = + new this._gaxModule.operationsProtos.google.longrunning.GetOperationRequest( + {name} + ); + const [operation] = await this.operationsClient.getOperation(request); + const decodeOperation = new this._gaxModule.Operation( + operation, + this.descriptors.longrunning.bulkDeleteDocuments, + this._gaxModule.createDefaultBackoffSettings() + ); + return decodeOperation as LROperation< + protos.google.firestore.admin.v1.BulkDeleteDocumentsResponse, + protos.google.firestore.admin.v1.BulkDeleteDocumentsMetadata + >; + } /** * Create a database. * @@ -2802,7 +2977,7 @@ export class FirestoreAdminClient { * * The new database must be in the same cloud region or multi-region location * as the existing backup. This behaves similar to - * {@link protos.google.firestore.admin.v1.CreateDatabase|FirestoreAdmin.CreateDatabase} + * {@link protos.google.firestore.admin.v1.FirestoreAdmin.CreateDatabase|FirestoreAdmin.CreateDatabase} * except instead of creating a new empty database, a new database is created * with the database type, index configuration, and documents from an existing * backup. @@ -3182,7 +3357,8 @@ export class FirestoreAdminClient { * only supports listing fields that have been explicitly overridden. To issue * this query, call * {@link protos.google.firestore.admin.v1.FirestoreAdmin.ListFields|FirestoreAdmin.ListFields} - * with a filter that includes `indexConfig.usesAncestorConfig:false` . + * with a filter that includes `indexConfig.usesAncestorConfig:false` or + * `ttlConfig:*`. * @param {number} request.pageSize * The number of results to return. * @param {string} request.pageToken @@ -3283,7 +3459,8 @@ export class FirestoreAdminClient { * only supports listing fields that have been explicitly overridden. To issue * this query, call * {@link protos.google.firestore.admin.v1.FirestoreAdmin.ListFields|FirestoreAdmin.ListFields} - * with a filter that includes `indexConfig.usesAncestorConfig:false` . + * with a filter that includes `indexConfig.usesAncestorConfig:false` or + * `ttlConfig:*`. * @param {number} request.pageSize * The number of results to return. * @param {string} request.pageToken @@ -3338,7 +3515,8 @@ export class FirestoreAdminClient { * only supports listing fields that have been explicitly overridden. To issue * this query, call * {@link protos.google.firestore.admin.v1.FirestoreAdmin.ListFields|FirestoreAdmin.ListFields} - * with a filter that includes `indexConfig.usesAncestorConfig:false` . + * with a filter that includes `indexConfig.usesAncestorConfig:false` or + * `ttlConfig:*`. * @param {number} request.pageSize * The number of results to return. * @param {string} request.pageToken diff --git a/dev/src/v1/firestore_admin_client_config.json b/dev/src/v1/firestore_admin_client_config.json index e264ab5cf..751554ce8 100644 --- a/dev/src/v1/firestore_admin_client_config.json +++ b/dev/src/v1/firestore_admin_client_config.json @@ -70,6 +70,11 @@ "retry_codes_name": "non_idempotent", "retry_params_name": "default" }, + "BulkDeleteDocuments": { + "timeout_millis": 60000, + "retry_codes_name": "non_idempotent", + "retry_params_name": "default" + }, "CreateDatabase": { "retry_codes_name": "non_idempotent", "retry_params_name": "default" diff --git a/dev/src/write-batch.ts b/dev/src/write-batch.ts index 4a139fd26..62fe7d996 100644 --- a/dev/src/write-batch.ts +++ b/dev/src/write-batch.ts @@ -48,6 +48,11 @@ import { import {StatusCode} from './status-code'; import api = google.firestore.v1; +import { + ATTRIBUTE_KEY_DOC_COUNT, + ATTRIBUTE_KEY_IS_TRANSACTIONAL, + SPAN_NAME_BATCH_COMMIT, +} from './telemetry/trace-util'; /** * A WriteResult wraps the write time set by the Firestore servers on sets(), @@ -113,7 +118,7 @@ export type PendingWriteOp = () => api.IWrite; * @class WriteBatch */ export class WriteBatch implements firestore.WriteBatch { - private readonly _firestore: Firestore; + protected readonly _firestore: Firestore; private readonly _serializer: Serializer; private readonly _allowUndefined: boolean; @@ -571,26 +576,35 @@ export class WriteBatch implements firestore.WriteBatch { * ``` */ commit(): Promise { - // Capture the error stack to preserve stack tracing across async calls. - const stack = Error().stack!; - - // Commits should also be retried when they fail with status code ABORTED. - const retryCodes = [StatusCode.ABORTED, ...getRetryCodes('commit')]; - - return this._commit({retryCodes}) - .then(response => { - return (response.writeResults || []).map( - writeResult => - new WriteResult( - Timestamp.fromProto( - writeResult.updateTime || response.commitTime! - ) - ) - ); - }) - .catch(err => { - throw wrapError(err, stack); - }); + return this._firestore._traceUtil.startActiveSpan( + SPAN_NAME_BATCH_COMMIT, + async () => { + // Capture the error stack to preserve stack tracing across async calls. + const stack = Error().stack!; + + // Commits should also be retried when they fail with status code ABORTED. + const retryCodes = [StatusCode.ABORTED, ...getRetryCodes('commit')]; + + return this._commit({retryCodes}) + .then(response => { + return (response.writeResults || []).map( + writeResult => + new WriteResult( + Timestamp.fromProto( + writeResult.updateTime || response.commitTime! + ) + ) + ); + }) + .catch(err => { + throw wrapError(err, stack); + }); + }, + { + [ATTRIBUTE_KEY_IS_TRANSACTIONAL]: false, + [ATTRIBUTE_KEY_DOC_COUNT]: this._opCount, + } + ); } /** diff --git a/dev/system-test/firestore.ts b/dev/system-test/firestore.ts index cf040220b..cc3c929e0 100644 --- a/dev/system-test/firestore.ts +++ b/dev/system-test/firestore.ts @@ -462,7 +462,9 @@ describe('Firestore class', () => { const explainResults = await indexTestHelper .query(collectionReference) - .findNearest('embedding', FieldValue.vector([1, 3]), { + .findNearest({ + vectorField: 'embedding', + queryVector: FieldValue.vector([1, 3]), limit: 10, distanceMeasure: 'COSINE', }) @@ -492,7 +494,9 @@ describe('Firestore class', () => { const explainResults = await indexTestHelper .query(collectionReference) - .findNearest('embedding', FieldValue.vector([1, 3]), { + .findNearest({ + vectorField: 'embedding', + queryVector: FieldValue.vector([1, 3]), limit: 10, distanceMeasure: 'COSINE', }) @@ -1832,6 +1836,2560 @@ describe('runs query on a large collection', () => { }); }); +describe('Query class', () => { + interface PaginatedResults { + pages: number; + docs: QueryDocumentSnapshot[]; + } + + let firestore: Firestore; + let randomCol: CollectionReference; + + const paginateResults = ( + query: Query, + startAfter?: unknown + ): Promise => { + return (startAfter ? query.startAfter(startAfter) : query) + .get() + .then(snapshot => { + if (snapshot.empty) { + return {pages: 0, docs: []}; + } else { + const docs = snapshot.docs; + return paginateResults(query, docs[docs.length - 1]).then( + nextPage => { + return { + pages: nextPage.pages + 1, + docs: docs.concat(nextPage.docs), + }; + } + ); + } + }); + }; + + async function addDocs( + ...docs: DocumentData[] + ): Promise { + let id = 0; // Guarantees consistent ordering for the first documents + const refs: DocumentReference[] = []; + for (const doc of docs) { + const ref = randomCol.doc('doc' + id++); + await ref.set(doc); + refs.push(ref); + } + return refs; + } + + async function testCollectionWithDocs(docs: { + [id: string]: DocumentData; + }): Promise> { + for (const id in docs) { + const ref = randomCol.doc(id); + await ref.set(docs[id]); + } + return randomCol; + } + + function expectDocs(result: QuerySnapshot, ...docs: string[]): void; + function expectDocs(result: QuerySnapshot, ...data: DocumentData[]): void; + + function expectDocs( + result: QuerySnapshot, + ...data: DocumentData[] | string[] + ): void { + expect(result.size).to.equal(data.length); + + if (data.length > 0) { + if (typeof data[0] === 'string') { + const actualIds = result.docs.map(docSnapshot => docSnapshot.id); + expect(actualIds).to.deep.equal(data); + } else { + result.forEach(doc => { + expect(doc.data()).to.deep.equal(data.shift()); + }); + } + } + } + + beforeEach(() => { + randomCol = getTestRoot(); + firestore = randomCol.firestore; + }); + + afterEach(() => verifyInstance(firestore)); + + it('has firestore property', () => { + const ref = randomCol.limit(0); + expect(ref.firestore).to.be.an.instanceOf(Firestore); + }); + + it('has select() method', () => { + const ref = randomCol.doc('doc'); + return ref + .set({foo: 'bar', bar: 'foo'}) + .then(() => { + return randomCol.select('foo').get(); + }) + .then(res => { + expect(res.docs[0].data()).to.deep.equal({foo: 'bar'}); + }); + }); + + it('select() supports empty fields', () => { + const ref = randomCol.doc('doc'); + return ref + .set({foo: 'bar', bar: 'foo'}) + .then(() => { + return randomCol.select().get(); + }) + .then(res => { + expect(res.docs[0].ref.id).to.deep.equal('doc'); + expect(res.docs[0].data()).to.deep.equal({}); + }); + }); + + it('has where() method', () => { + const ref = randomCol.doc('doc'); + return ref + .set({foo: 'bar'}) + .then(() => { + return randomCol.where('foo', '==', 'bar').get(); + }) + .then(res => { + expect(res.docs[0].data()).to.deep.equal({foo: 'bar'}); + }); + }); + + it('supports NaN and Null', () => { + const ref = randomCol.doc('doc'); + return ref + .set({foo: NaN, bar: null}) + .then(() => { + return randomCol.where('foo', '==', NaN).where('bar', '==', null).get(); + }) + .then(res => { + expect( + typeof res.docs[0].get('foo') === 'number' && + isNaN(res.docs[0].get('foo')) + ); + expect(res.docs[0].get('bar')).to.equal(null); + }); + }); + + it('supports array-contains', () => { + return Promise.all([ + randomCol.add({foo: ['bar']}), + randomCol.add({foo: []}), + ]) + .then(() => randomCol.where('foo', 'array-contains', 'bar').get()) + .then(res => { + expect(res.size).to.equal(1); + expect(res.docs[0].get('foo')).to.deep.equal(['bar']); + }); + }); + + describe('vector search', () => { + it('supports findNearest by EUCLIDEAN distance', async () => { + const indexTestHelper = new IndexTestHelper(firestore); + + const collectionReference = await indexTestHelper.createTestDocs([ + {foo: 'bar'}, + {foo: 'xxx', embedding: FieldValue.vector([10, 10])}, + {foo: 'bar', embedding: FieldValue.vector([1, 1])}, + {foo: 'bar', embedding: FieldValue.vector([10, 0])}, + {foo: 'bar', embedding: FieldValue.vector([20, 0])}, + {foo: 'bar', embedding: FieldValue.vector([100, 100])}, + ]); + + const vectorQuery = indexTestHelper + .query(collectionReference) + .where('foo', '==', 'bar') + .findNearest({ + vectorField: 'embedding', + queryVector: [10, 10], + limit: 3, + distanceMeasure: 'EUCLIDEAN', + }); + + const res = await vectorQuery.get(); + expect(res.size).to.equal(3); + expect(res.docs[0].get('embedding').isEqual(FieldValue.vector([10, 0]))) + .to.be.true; + expect(res.docs[1].get('embedding').isEqual(FieldValue.vector([1, 1]))).to + .be.true; + expect(res.docs[2].get('embedding').isEqual(FieldValue.vector([20, 0]))) + .to.be.true; + }); + + it('supports findNearest by COSINE distance', async () => { + const indexTestHelper = new IndexTestHelper(firestore); + + const collectionReference = await indexTestHelper.setTestDocs({ + '1': {foo: 'bar'}, + '2': {foo: 'xxx', embedding: FieldValue.vector([10, 10])}, + '3': {foo: 'bar', embedding: FieldValue.vector([1, 1])}, + '4': {foo: 'bar', embedding: FieldValue.vector([20, 0])}, + '5': {foo: 'bar', embedding: FieldValue.vector([10, 0])}, + '6': {foo: 'bar', embedding: FieldValue.vector([100, 100])}, + }); + + const vectorQuery = indexTestHelper + .query(collectionReference) + .where('foo', '==', 'bar') + .findNearest({ + vectorField: 'embedding', + queryVector: [10, 10], + limit: 3, + distanceMeasure: 'COSINE', + }); + + const res = await vectorQuery.get(); + + expect(res.size).to.equal(3); + + if (res.docs[0].get('embedding').isEqual(FieldValue.vector([1, 1]))) { + expect( + res.docs[1].get('embedding').isEqual(FieldValue.vector([100, 100])) + ).to.be.true; + } else { + expect( + res.docs[0].get('embedding').isEqual(FieldValue.vector([100, 100])) + ).to.be.true; + expect(res.docs[1].get('embedding').isEqual(FieldValue.vector([1, 1]))) + .to.be.true; + } + + expect( + res.docs[2].get('embedding').isEqual(FieldValue.vector([20, 0])) || + res.docs[2].get('embedding').isEqual(FieldValue.vector([20, 0])) + ).to.be.true; + }); + + it('supports findNearest by DOT_PRODUCT distance', async () => { + const indexTestHelper = new IndexTestHelper(firestore); + + const collectionReference = await indexTestHelper.createTestDocs([ + {foo: 'bar'}, + {foo: 'xxx', embedding: FieldValue.vector([10, 10])}, + {foo: 'bar', embedding: FieldValue.vector([1, 1])}, + {foo: 'bar', embedding: FieldValue.vector([10, 0])}, + {foo: 'bar', embedding: FieldValue.vector([20, 0])}, + {foo: 'bar', embedding: FieldValue.vector([100, 100])}, + ]); + + const vectorQuery = indexTestHelper + .query(collectionReference) + .where('foo', '==', 'bar') + .findNearest({ + vectorField: 'embedding', + queryVector: [10, 10], + limit: 3, + distanceMeasure: 'DOT_PRODUCT', + }); + + const res = await vectorQuery.get(); + expect(res.size).to.equal(3); + expect( + res.docs[0].get('embedding').isEqual(FieldValue.vector([100, 100])) + ).to.be.true; + expect(res.docs[1].get('embedding').isEqual(FieldValue.vector([20, 0]))) + .to.be.true; + expect(res.docs[2].get('embedding').isEqual(FieldValue.vector([10, 0]))) + .to.be.true; + }); + + it('findNearest works with converters', async () => { + const indexTestHelper = new IndexTestHelper(firestore); + + class FooDistance { + constructor( + readonly foo: string, + readonly embedding: Array + ) {} + } + + const fooConverter = { + toFirestore(d: FooDistance): DocumentData { + return {title: d.foo, embedding: FieldValue.vector(d.embedding)}; + }, + fromFirestore(snapshot: QueryDocumentSnapshot): FooDistance { + const data = snapshot.data(); + return new FooDistance(data.foo, data.embedding.toArray()); + }, + }; + + const collectionRef = await indexTestHelper.createTestDocs([ + {foo: 'bar', embedding: FieldValue.vector([5, 5])}, + ]); + + const vectorQuery = indexTestHelper + .query(collectionRef) + .withConverter(fooConverter) + .where('foo', '==', 'bar') + .findNearest({ + vectorField: 'embedding', + queryVector: [10, 10], + limit: 3, + distanceMeasure: 'EUCLIDEAN', + }); + + const res = await vectorQuery.get(); + + expect(res.size).to.equal(1); + expect(res.docs[0].data().foo).to.equal('bar'); + expect(res.docs[0].data().embedding).to.deep.equal([5, 5]); + }); + + it('supports findNearest skipping fields of wrong types', async () => { + const indexTestHelper = new IndexTestHelper(firestore); + + const collectionRef = await indexTestHelper.createTestDocs([ + {foo: 'bar'}, + + // These documents are skipped because it is not really a vector value + {foo: 'bar', embedding: [10, 10]}, + {foo: 'bar', embedding: 'not actually a vector'}, + {foo: 'bar', embedding: null}, + + // Actual vector values + {foo: 'bar', embedding: FieldValue.vector([9, 9])}, + {foo: 'bar', embedding: FieldValue.vector([50, 50])}, + {foo: 'bar', embedding: FieldValue.vector([100, 100])}, + ]); + + const vectorQuery = indexTestHelper + .query(collectionRef) + .where('foo', '==', 'bar') + .findNearest({ + vectorField: 'embedding', + queryVector: [10, 10], + limit: 100, // Intentionally large to get all matches. + distanceMeasure: 'EUCLIDEAN', + }); + + const res = await vectorQuery.get(); + expect(res.size).to.equal(3); + expect(res.docs[0].get('embedding').isEqual(FieldValue.vector([9, 9]))).to + .be.true; + expect(res.docs[1].get('embedding').isEqual(FieldValue.vector([50, 50]))) + .to.be.true; + expect( + res.docs[2].get('embedding').isEqual(FieldValue.vector([100, 100])) + ).to.be.true; + }); + + it('findNearest ignores mismatching dimensions', async () => { + const indexTestHelper = new IndexTestHelper(firestore); + + const collectionRef = await indexTestHelper.createTestDocs([ + {foo: 'bar'}, + + // Vectors with dimension mismatch + {foo: 'bar', embedding: FieldValue.vector([10])}, + + // Vectors with dimension match + {foo: 'bar', embedding: FieldValue.vector([9, 9])}, + {foo: 'bar', embedding: FieldValue.vector([50, 50])}, + ]); + + const vectorQuery = indexTestHelper + .query(collectionRef) + .where('foo', '==', 'bar') + .findNearest({ + vectorField: 'embedding', + queryVector: [10, 10], + limit: 3, + distanceMeasure: 'EUCLIDEAN', + }); + + const res = await vectorQuery.get(); + expect(res.size).to.equal(2); + expect(res.docs[0].get('embedding').isEqual(FieldValue.vector([9, 9]))).to + .be.true; + expect(res.docs[1].get('embedding').isEqual(FieldValue.vector([50, 50]))) + .to.be.true; + }); + + it('supports findNearest on non-existent field', async () => { + const indexTestHelper = new IndexTestHelper(firestore); + + const collectionRef = await indexTestHelper.createTestDocs([ + {foo: 'bar'}, + {foo: 'bar', otherField: [10, 10]}, + {foo: 'bar', otherField: 'not actually a vector'}, + {foo: 'bar', otherField: null}, + ]); + + const vectorQuery = indexTestHelper + .query(collectionRef) + .where('foo', '==', 'bar') + .findNearest({ + vectorField: 'embedding', + queryVector: [10, 10], + limit: 3, + distanceMeasure: 'EUCLIDEAN', + }); + + const res = await vectorQuery.get(); + + expect(res.size).to.equal(0); + }); + + it('supports findNearest on vector nested in a map', async () => { + const indexTestHelper = new IndexTestHelper(firestore); + + const collectionReference = await indexTestHelper.createTestDocs([ + {nested: {foo: 'bar'}}, + {nested: {foo: 'xxx', embedding: FieldValue.vector([10, 10])}}, + {nested: {foo: 'bar', embedding: FieldValue.vector([1, 1])}}, + {nested: {foo: 'bar', embedding: FieldValue.vector([10, 0])}}, + {nested: {foo: 'bar', embedding: FieldValue.vector([20, 0])}}, + {nested: {foo: 'bar', embedding: FieldValue.vector([100, 100])}}, + ]); + + const vectorQuery = indexTestHelper + .query(collectionReference) + .findNearest({ + vectorField: 'nested.embedding', + queryVector: [10, 10], + limit: 3, + distanceMeasure: 'EUCLIDEAN', + }); + + const res = await vectorQuery.get(); + expect(res.size).to.equal(3); + expect( + res.docs[0].get('nested.embedding').isEqual(FieldValue.vector([10, 10])) + ).to.be.true; + expect( + res.docs[1].get('nested.embedding').isEqual(FieldValue.vector([10, 0])) + ).to.be.true; + expect( + res.docs[2].get('nested.embedding').isEqual(FieldValue.vector([1, 1])) + ).to.be.true; + }); + + it('supports findNearest with select to exclude vector data in response', async () => { + const indexTestHelper = new IndexTestHelper(firestore); + + const collectionReference = await indexTestHelper.createTestDocs([ + {foo: 1}, + {foo: 2, embedding: FieldValue.vector([10, 10])}, + {foo: 3, embedding: FieldValue.vector([1, 1])}, + {foo: 4, embedding: FieldValue.vector([10, 0])}, + {foo: 5, embedding: FieldValue.vector([20, 0])}, + {foo: 6, embedding: FieldValue.vector([100, 100])}, + ]); + + const vectorQuery = indexTestHelper + .query(collectionReference) + .where('foo', 'in', [1, 2, 3, 4, 5, 6]) + .select('foo') + .findNearest({ + vectorField: 'embedding', + queryVector: [10, 10], + limit: 10, + distanceMeasure: 'EUCLIDEAN', + }); + + const res = await vectorQuery.get(); + expect(res.size).to.equal(5); + expect(res.docs[0].get('foo')).to.equal(2); + expect(res.docs[1].get('foo')).to.equal(4); + expect(res.docs[2].get('foo')).to.equal(3); + expect(res.docs[3].get('foo')).to.equal(5); + expect(res.docs[4].get('foo')).to.equal(6); + + res.docs.forEach(ds => expect(ds.get('embedding')).to.be.undefined); + }); + + it('supports findNearest limits', async () => { + const indexTestHelper = new IndexTestHelper(firestore); + + const embeddingVector = []; + const queryVector = []; + for (let i = 0; i < 2048; i++) { + embeddingVector.push(i + 1); + queryVector.push(i - 1); + } + + const collectionReference = await indexTestHelper.createTestDocs([ + {embedding: FieldValue.vector(embeddingVector)}, + ]); + + const vectorQuery = indexTestHelper + .query(collectionReference) + .findNearest({ + vectorField: 'embedding', + queryVector: queryVector, + limit: 1000, + distanceMeasure: 'EUCLIDEAN', + }); + + const res = await vectorQuery.get(); + expect(res.size).to.equal(1); + expect( + (res.docs[0].get('embedding') as VectorValue).toArray() + ).to.deep.equal(embeddingVector); + }); + + describe('preview API (deprecated)', () => { + it('supports findNearest with EUCLIDEAN', async () => { + const indexTestHelper = new IndexTestHelper(firestore); + + const collectionReference = await indexTestHelper.createTestDocs([ + {foo: 'bar'}, + {foo: 'bar', embedding: FieldValue.vector([10, 10])}, + {foo: 'bar', embedding: FieldValue.vector([1, 1.1])}, + {foo: 'x', embedding: FieldValue.vector([1, 1])}, + {foo: 'bar', embedding: FieldValue.vector([10, 0])}, + {foo: 'bar', embedding: FieldValue.vector([-100, -100])}, + ]); + + const vectorQuery = indexTestHelper + .query(collectionReference) + .where('foo', '==', 'bar') + .findNearest('embedding', [1, 1], { + limit: 3, + distanceMeasure: 'EUCLIDEAN', + }); + + const res = await vectorQuery.get(); + expect(res.size).to.equal(3); + expect( + res.docs[0].get('embedding').isEqual(FieldValue.vector([1, 1.1])) + ).to.be.true; + expect(res.docs[1].get('embedding').isEqual(FieldValue.vector([10, 0]))) + .to.be.true; + expect( + res.docs[2].get('embedding').isEqual(FieldValue.vector([10, 10])) + ).to.be.true; + }); + + it('supports findNearest with COSINE', async () => { + const indexTestHelper = new IndexTestHelper(firestore); + + const collectionReference = await indexTestHelper.createTestDocs([ + {foo: 'bar'}, + {foo: 'bar', embedding: FieldValue.vector([10, 10])}, + {foo: 'bar', embedding: FieldValue.vector([1, 1.1])}, + {foo: 'x', embedding: FieldValue.vector([1, 1])}, + {foo: 'bar', embedding: FieldValue.vector([10, 0])}, + {foo: 'bar', embedding: FieldValue.vector([-100, -100])}, + ]); + + const vectorQuery = indexTestHelper + .query(collectionReference) + .where('foo', '==', 'bar') + .findNearest('embedding', [1, 1], { + limit: 3, + distanceMeasure: 'COSINE', + }); + + const res = await vectorQuery.get(); + expect(res.size).to.equal(3); + expect( + res.docs[0].get('embedding').isEqual(FieldValue.vector([10, 10])) + ).to.be.true; + expect( + res.docs[1].get('embedding').isEqual(FieldValue.vector([1, 1.1])) + ).to.be.true; + expect(res.docs[2].get('embedding').isEqual(FieldValue.vector([10, 0]))) + .to.be.true; + }); + }); + + describe('requesting computed distance', () => { + it('supports COSINE distance', async () => { + const indexTestHelper = new IndexTestHelper(firestore); + + const collectionReference = await indexTestHelper.setTestDocs({ + '1': {foo: 'bar'}, + '2': {foo: 'bar', embedding: FieldValue.vector([1, 0])}, + '3': {foo: 'bar', embedding: FieldValue.vector([0, 1])}, + '4': {foo: 'bar', embedding: FieldValue.vector([0, -0.1])}, + '5': {foo: 'bar', embedding: FieldValue.vector([-1, 0])}, + }); + + const vectorQuery = indexTestHelper + .query(collectionReference) + .findNearest({ + vectorField: 'embedding', + queryVector: [1, 0], + limit: 5, + distanceMeasure: 'COSINE', + distanceResultField: 'distance', + }); + + const res = await vectorQuery.get(); + + expect(res.size).to.equal(4); + + expect(res.docs[0].get('embedding').isEqual(FieldValue.vector([1, 0]))) + .to.be.true; + expect(res.docs[0].get('distance')).to.equal(0); + + expect(res.docs[1].get('distance')).to.equal(1); + expect(res.docs[2].get('distance')).to.equal(1); + + expect(res.docs[3].get('embedding').isEqual(FieldValue.vector([-1, 0]))) + .to.be.true; + expect(res.docs[3].get('distance')).to.equal(2); + }); + + it('supports EUCLIDEAN distance', async () => { + const indexTestHelper = new IndexTestHelper(firestore); + + const collectionReference = await indexTestHelper.setTestDocs({ + '1': {foo: 'bar'}, + '2': {foo: 'bar', embedding: FieldValue.vector([2, 0])}, + '3': {foo: 'bar', embedding: FieldValue.vector([1, 100])}, + '4': {foo: 'bar', embedding: FieldValue.vector([1, -0.1])}, + '5': {foo: 'bar', embedding: FieldValue.vector([4, 4])}, + }); + + const vectorQuery = indexTestHelper + .query(collectionReference) + .findNearest({ + vectorField: 'embedding', + queryVector: [1, 0], + limit: 5, + distanceMeasure: 'EUCLIDEAN', + distanceResultField: 'distance', + }); + + const res = await vectorQuery.get(); + + expect(res.size).to.equal(4); + + expect( + res.docs[0].get('embedding').isEqual(FieldValue.vector([1, -0.1])) + ).to.be.true; + expect(res.docs[0].get('distance')).to.equal(0.1); + + expect(res.docs[1].get('embedding').isEqual(FieldValue.vector([2, 0]))) + .to.be.true; + expect(res.docs[1].get('distance')).to.equal(1); + + expect(res.docs[2].get('embedding').isEqual(FieldValue.vector([4, 4]))) + .to.be.true; + expect(res.docs[2].get('distance')).to.equal(5); + + expect( + res.docs[3].get('embedding').isEqual(FieldValue.vector([1, 100])) + ).to.be.true; + expect(res.docs[3].get('distance')).to.equal(100); + }); + + it('supports DOT_PRODUCT distance', async () => { + const indexTestHelper = new IndexTestHelper(firestore); + + const collectionReference = await indexTestHelper.setTestDocs({ + '1': {foo: 'bar'}, + '2': {foo: 'bar', embedding: FieldValue.vector([2, 0])}, + '3': {foo: 'bar', embedding: FieldValue.vector([1, 100])}, + '4': {foo: 'bar', embedding: FieldValue.vector([-20, 0])}, + '5': {foo: 'bar', embedding: FieldValue.vector([0.1, 4])}, + }); + + const vectorQuery = indexTestHelper + .query(collectionReference) + .findNearest({ + vectorField: 'embedding', + queryVector: [1, 0], + limit: 5, + distanceMeasure: 'DOT_PRODUCT', + distanceResultField: 'distance', + }); + + const res = await vectorQuery.get(); + + expect(res.size).to.equal(4); + + expect(res.docs[0].get('distance')).to.equal(2); + expect(res.docs[0].get('embedding').isEqual(FieldValue.vector([2, 0]))) + .to.be.true; + + expect(res.docs[1].get('distance')).to.equal(1); + expect( + res.docs[1].get('embedding').isEqual(FieldValue.vector([1, 100])) + ).to.be.true; + + expect(res.docs[2].get('distance')).to.equal(0.1); + expect( + res.docs[2].get('embedding').isEqual(FieldValue.vector([0.1, 4])) + ).to.be.true; + + expect(res.docs[3].get('distance')).to.equal(-20); + expect( + res.docs[3].get('embedding').isEqual(FieldValue.vector([-20, 0])) + ).to.be.true; + }); + + it('overwrites distance result field on conflict', async () => { + const indexTestHelper = new IndexTestHelper(firestore); + + const collectionReference = await indexTestHelper.setTestDocs({ + '1': { + foo: 'bar', + embedding: FieldValue.vector([0, 1]), + distance: '100 miles', + }, + }); + + const vectorQuery = indexTestHelper + .query(collectionReference) + .findNearest({ + vectorField: 'embedding', + queryVector: [1, 0], + limit: 5, + distanceMeasure: 'COSINE', + distanceResultField: 'distance', + }); + + const res = await vectorQuery.get(); + + expect(res.size).to.equal(1); + + expect(res.docs[0].get('embedding').isEqual(FieldValue.vector([0, 1]))) + .to.be.true; + expect(res.docs[0].get('distance')).to.equal(1); + }); + + it('supports select queries', async () => { + const indexTestHelper = new IndexTestHelper(firestore); + + const collectionReference = await indexTestHelper.setTestDocs({ + '1': {foo: 'bar'}, + '2': {foo: 'bar', embedding: FieldValue.vector([1, 0])}, + '3': {foo: 'bar', embedding: FieldValue.vector([0, 1])}, + '4': {foo: 'bar', embedding: FieldValue.vector([0, -0.1])}, + '5': {foo: 'bar', embedding: FieldValue.vector([-1, 0])}, + }); + + const vectorQuery = indexTestHelper + .query(collectionReference) + // value of `distanceResultField` must also be in select statement + .select('embedding', 'distance') + .findNearest({ + vectorField: 'embedding', + queryVector: [1, 0], + limit: 5, + distanceMeasure: 'COSINE', + distanceResultField: 'distance', + }); + + const res = await vectorQuery.get(); + + expect(res.size).to.equal(4); + + expect(res.docs[0].get('embedding').isEqual(FieldValue.vector([1, 0]))) + .to.be.true; + expect(res.docs[0].get('distance')).to.equal(0); + + expect(res.docs[1].get('distance')).to.equal(1); + expect(res.docs[2].get('distance')).to.equal(1); + + expect(res.docs[3].get('embedding').isEqual(FieldValue.vector([-1, 0]))) + .to.be.true; + expect(res.docs[3].get('distance')).to.equal(2); + }); + }); + + describe('querying with distance threshold', () => { + it('supports COSINE distance', async () => { + const indexTestHelper = new IndexTestHelper(firestore); + + const collectionReference = await indexTestHelper.setTestDocs({ + '1': {foo: 'bar'}, + '2': {foo: 'bar', embedding: FieldValue.vector([1, 0])}, + '3': {foo: 'bar', embedding: FieldValue.vector([1, 1])}, + '4': {foo: 'bar', embedding: FieldValue.vector([0, -0.1])}, + '5': {foo: 'bar', embedding: FieldValue.vector([-1, 0])}, + }); + + const vectorQuery = indexTestHelper + .query(collectionReference) + .findNearest({ + vectorField: 'embedding', + queryVector: [1, 0], + limit: 5, + distanceMeasure: 'COSINE', + distanceThreshold: 1, + }); + + const res = await vectorQuery.get(); + + expect(res.size).to.equal(3); + + expect(res.docs[0].get('embedding').isEqual(FieldValue.vector([1, 0]))) + .to.be.true; + expect(res.docs[1].get('embedding').isEqual(FieldValue.vector([1, 1]))) + .to.be.true; + expect( + res.docs[2].get('embedding').isEqual(FieldValue.vector([0, -0.1])) + ).to.be.true; + }); + + it('supports EUCLIDEAN distance', async () => { + const indexTestHelper = new IndexTestHelper(firestore); + + const collectionReference = await indexTestHelper.setTestDocs({ + '1': {foo: 'bar'}, + '2': {foo: 'bar', embedding: FieldValue.vector([2, 0])}, + '3': {foo: 'bar', embedding: FieldValue.vector([1, 100])}, + '4': {foo: 'bar', embedding: FieldValue.vector([1, -0.1])}, + '5': {foo: 'bar', embedding: FieldValue.vector([4, 4])}, + }); + + const vectorQuery = indexTestHelper + .query(collectionReference) + .findNearest({ + vectorField: 'embedding', + queryVector: [1, 0], + limit: 5, + distanceMeasure: 'EUCLIDEAN', + distanceThreshold: 5, + }); + + const res = await vectorQuery.get(); + + expect(res.size).to.equal(3); + + expect( + res.docs[0].get('embedding').isEqual(FieldValue.vector([1, -0.1])) + ).to.be.true; + expect(res.docs[1].get('embedding').isEqual(FieldValue.vector([2, 0]))) + .to.be.true; + expect(res.docs[2].get('embedding').isEqual(FieldValue.vector([4, 4]))) + .to.be.true; + }); + + it('supports DOT_PRODUCT distance', async () => { + const indexTestHelper = new IndexTestHelper(firestore); + + const collectionReference = await indexTestHelper.setTestDocs({ + '1': {foo: 'bar'}, + '2': {foo: 'bar', embedding: FieldValue.vector([2, 0])}, + '3': {foo: 'bar', embedding: FieldValue.vector([1, 100])}, + '4': {foo: 'bar', embedding: FieldValue.vector([-20, 0])}, + '5': {foo: 'bar', embedding: FieldValue.vector([0.1, 4])}, + }); + + const vectorQuery = indexTestHelper + .query(collectionReference) + .findNearest({ + vectorField: 'embedding', + queryVector: [1, 0], + limit: 5, + distanceMeasure: 'DOT_PRODUCT', + distanceThreshold: 1, + }); + + const res = await vectorQuery.get(); + + expect(res.size).to.equal(2); + + expect(res.docs[0].get('embedding').isEqual(FieldValue.vector([2, 0]))) + .to.be.true; + + expect( + res.docs[1].get('embedding').isEqual(FieldValue.vector([1, 100])) + ).to.be.true; + }); + + it('works with distance threshold', async () => { + const indexTestHelper = new IndexTestHelper(firestore); + + const collectionReference = await indexTestHelper.setTestDocs({ + '1': {foo: 'bar'}, + '2': {foo: 'bar', embedding: FieldValue.vector([2, 0])}, + '3': {foo: 'bar', embedding: FieldValue.vector([1, 100])}, + '4': {foo: 'bar', embedding: FieldValue.vector([-20, 0])}, + '5': {foo: 'bar', embedding: FieldValue.vector([0.1, 4])}, + }); + + const vectorQuery = indexTestHelper + .query(collectionReference) + .findNearest({ + vectorField: 'embedding', + queryVector: [1, 0], + limit: 5, + distanceMeasure: 'DOT_PRODUCT', + distanceThreshold: 0.11, + distanceResultField: 'foo', + }); + + const res = await vectorQuery.get(); + + expect(res.size).to.equal(2); + + expect(res.docs[0].get('foo')).to.equal(2); + expect(res.docs[0].get('embedding').isEqual(FieldValue.vector([2, 0]))) + .to.be.true; + + expect(res.docs[1].get('foo')).to.equal(1); + expect( + res.docs[1].get('embedding').isEqual(FieldValue.vector([1, 100])) + ).to.be.true; + }); + + it('will not exceed limit even if there are more results more similar than distanceThreshold', async () => { + const indexTestHelper = new IndexTestHelper(firestore); + + const collectionReference = await indexTestHelper.setTestDocs({ + '1': {foo: 'bar'}, + '2': {foo: 'bar', embedding: FieldValue.vector([2, 0])}, + '3': {foo: 'bar', embedding: FieldValue.vector([1, 100])}, + '4': {foo: 'bar', embedding: FieldValue.vector([-20, 0])}, + '5': {foo: 'bar', embedding: FieldValue.vector([0.1, 4])}, + }); + + const vectorQuery = indexTestHelper + .query(collectionReference) + .findNearest({ + vectorField: 'embedding', + queryVector: [1, 0], + limit: 2, + distanceMeasure: 'DOT_PRODUCT', + distanceThreshold: 0.0, + }); + + const res = await vectorQuery.get(); + + expect(res.size).to.equal(2); + + expect(res.docs[0].get('embedding').isEqual(FieldValue.vector([2, 0]))) + .to.be.true; + + expect( + res.docs[1].get('embedding').isEqual(FieldValue.vector([1, 100])) + ).to.be.true; + }); + }); + }); + + it('supports !=', async () => { + await addDocs( + {zip: NaN}, + {zip: 91102}, + {zip: 98101}, + {zip: 98103}, + {zip: [98101]}, + {zip: ['98101', {zip: 98101}]}, + {zip: {zip: 98101}}, + {zip: null} + ); + + let res = await randomCol.where('zip', '!=', 98101).get(); + expectDocs( + res, + {zip: NaN}, + {zip: 91102}, + {zip: 98103}, + {zip: [98101]}, + {zip: ['98101', {zip: 98101}]}, + {zip: {zip: 98101}} + ); + + res = await randomCol.where('zip', '!=', NaN).get(); + expectDocs( + res, + {zip: 91102}, + {zip: 98101}, + {zip: 98103}, + {zip: [98101]}, + {zip: ['98101', {zip: 98101}]}, + {zip: {zip: 98101}} + ); + + res = await randomCol.where('zip', '!=', null).get(); + expectDocs( + res, + {zip: NaN}, + {zip: 91102}, + {zip: 98101}, + {zip: 98103}, + {zip: [98101]}, + {zip: ['98101', {zip: 98101}]}, + {zip: {zip: 98101}} + ); + }); + + it('supports != with document ID', async () => { + const refs = await addDocs({count: 1}, {count: 2}, {count: 3}); + const res = await randomCol + .where(FieldPath.documentId(), '!=', refs[0].id) + .get(); + expectDocs(res, {count: 2}, {count: 3}); + }); + + it('supports not-in', async () => { + await addDocs( + {zip: 98101}, + {zip: 91102}, + {zip: 98103}, + {zip: [98101]}, + {zip: ['98101', {zip: 98101}]}, + {zip: {zip: 98101}} + ); + let res = await randomCol.where('zip', 'not-in', [98101, 98103]).get(); + expectDocs( + res, + {zip: 91102}, + {zip: [98101]}, + {zip: ['98101', {zip: 98101}]}, + {zip: {zip: 98101}} + ); + + res = await randomCol.where('zip', 'not-in', [NaN]).get(); + expectDocs( + res, + {zip: 91102}, + {zip: 98101}, + {zip: 98103}, + {zip: [98101]}, + {zip: ['98101', {zip: 98101}]}, + {zip: {zip: 98101}} + ); + + res = await randomCol.where('zip', 'not-in', [null]).get(); + expect(res.size).to.equal(0); + }); + + it('supports not-in with document ID array', async () => { + const refs = await addDocs({count: 1}, {count: 2}, {count: 3}); + const res = await randomCol + .where(FieldPath.documentId(), 'not-in', [refs[0].id, refs[1]]) + .get(); + expectDocs(res, {count: 3}); + }); + + it('supports "in"', async () => { + await addDocs( + {zip: 98101}, + {zip: 91102}, + {zip: 98103}, + {zip: [98101]}, + {zip: ['98101', {zip: 98101}]}, + {zip: {zip: 98101}} + ); + const res = await randomCol.where('zip', 'in', [98101, 98103]).get(); + expectDocs(res, {zip: 98101}, {zip: 98103}); + }); + + it('supports "in" with document ID array', async () => { + const refs = await addDocs({count: 1}, {count: 2}, {count: 3}); + const res = await randomCol + .where(FieldPath.documentId(), 'in', [refs[0].id, refs[1]]) + .get(); + expectDocs(res, {count: 1}, {count: 2}); + }); + + it('supports array-contains-any', async () => { + await addDocs( + {array: [42]}, + {array: ['a', 42, 'c']}, + {array: [41.999, '42', {a: [42]}]}, + {array: [42], array2: ['sigh']}, + {array: [43]}, + {array: [{a: 42}]}, + {array: 42} + ); + + const res = await randomCol + .where('array', 'array-contains-any', [42, 43]) + .get(); + + expectDocs( + res, + {array: [42]}, + {array: ['a', 42, 'c']}, + { + array: [42], + array2: ['sigh'], + }, + {array: [43]} + ); + }); + + it('can query by FieldPath.documentId()', () => { + const ref = randomCol.doc('foo'); + + return ref + .set({}) + .then(() => { + return randomCol.where(FieldPath.documentId(), '>=', 'bar').get(); + }) + .then(res => { + expect(res.docs.length).to.equal(1); + }); + }); + + it('has orderBy() method', async () => { + await addDocs({foo: 'a'}, {foo: 'b'}); + + let res = await randomCol.orderBy('foo').get(); + expectDocs(res, {foo: 'a'}, {foo: 'b'}); + + res = await randomCol.orderBy('foo', 'desc').get(); + expectDocs(res, {foo: 'b'}, {foo: 'a'}); + }); + + it('can order by FieldPath.documentId()', () => { + const ref1 = randomCol.doc('doc1'); + const ref2 = randomCol.doc('doc2'); + + return Promise.all([ref1.set({foo: 'a'}), ref2.set({foo: 'b'})]) + .then(() => { + return randomCol.orderBy(FieldPath.documentId()).get(); + }) + .then(res => { + expect(res.docs[0].data()).to.deep.equal({foo: 'a'}); + expect(res.docs[1].data()).to.deep.equal({foo: 'b'}); + }); + }); + + it('can run get() on empty collection', async () => { + return randomCol.get().then(res => { + return expect(res.empty); + }); + }); + + it('can run stream() on empty collection', async () => { + let received = 0; + const stream = randomCol.stream(); + + for await (const doc of stream) { + expect(doc).to.be.an.instanceOf(QueryDocumentSnapshot); + ++received; + } + + expect(received).to.equal(0); + }); + + it('has limit() method on get()', async () => { + await addDocs({foo: 'a'}, {foo: 'b'}); + const res = await randomCol.orderBy('foo').limit(1).get(); + expectDocs(res, {foo: 'a'}); + }); + + it('has limit() method on stream()', async () => { + let received = 0; + await addDocs({foo: 'a'}, {foo: 'b'}); + + const stream = randomCol.orderBy('foo').limit(1).stream(); + for await (const doc of stream) { + expect(doc).to.be.an.instanceOf(QueryDocumentSnapshot); + ++received; + } + + expect(received).to.equal(1); + }); + + it('can run limit(num), where num is larger than the collection size on get()', async () => { + await addDocs({foo: 'a'}, {foo: 'b'}); + const res = await randomCol.orderBy('foo').limit(3).get(); + expectDocs(res, {foo: 'a'}, {foo: 'b'}); + }); + + it('can run limit(num), where num is larger than the collection size on stream()', async () => { + let received = 0; + await addDocs({foo: 'a'}, {foo: 'b'}); + + const stream = randomCol.orderBy('foo').limit(3).stream(); + for await (const doc of stream) { + expect(doc).to.be.an.instanceOf(QueryDocumentSnapshot); + ++received; + } + + expect(received).to.equal(2); + }); + + it('has limitToLast() method', async () => { + await addDocs({doc: 1}, {doc: 2}, {doc: 3}); + const res = await randomCol.orderBy('doc').limitToLast(2).get(); + expectDocs(res, {doc: 2}, {doc: 3}); + }); + + it('limitToLast() supports Query cursors', async () => { + await addDocs({doc: 1}, {doc: 2}, {doc: 3}, {doc: 4}, {doc: 5}); + const res = await randomCol + .orderBy('doc') + .startAt(2) + .endAt(4) + .limitToLast(5) + .get(); + expectDocs(res, {doc: 2}, {doc: 3}, {doc: 4}); + }); + + it('can use offset() method with get()', async () => { + await addDocs({foo: 'a'}, {foo: 'b'}); + const res = await randomCol.orderBy('foo').offset(1).get(); + expectDocs(res, {foo: 'b'}); + }); + + it('can use offset() method with stream()', async () => { + let received = 0; + await addDocs({foo: 'a'}, {foo: 'b'}); + + const stream = randomCol.orderBy('foo').offset(1).stream(); + for await (const doc of stream) { + expect(doc).to.be.an.instanceOf(QueryDocumentSnapshot); + ++received; + } + + expect(received).to.equal(1); + }); + + it('can run offset(num), where num is larger than the collection size on get()', async () => { + await addDocs({foo: 'a'}, {foo: 'b'}); + const res = await randomCol.orderBy('foo').offset(3).get(); + expect(res.empty); + }); + + it('can run offset(num), where num is larger than the collection size on stream()', async () => { + let received = 0; + await addDocs({foo: 'a'}, {foo: 'b'}); + const stream = randomCol.orderBy('foo').offset(3).stream(); + for await (const doc of stream) { + expect(doc).to.be.an.instanceOf(QueryDocumentSnapshot); + ++received; + } + expect(received).to.equal(0); + }); + + it('supports Unicode in document names', async () => { + const collRef = randomCol.doc('доброеутро').collection('coll'); + await collRef.add({}); + const snapshot = await collRef.get(); + expect(snapshot.size).to.equal(1); + }); + + it('supports pagination', () => { + const batch = firestore.batch(); + + for (let i = 0; i < 10; ++i) { + batch.set(randomCol.doc('doc' + i), {val: i}); + } + + const query = randomCol.orderBy('val').limit(3); + + return batch + .commit() + .then(() => paginateResults(query)) + .then(results => { + expect(results.pages).to.equal(4); + expect(results.docs).to.have.length(10); + }); + }); + + it('supports pagination with where() clauses', () => { + const batch = firestore.batch(); + + for (let i = 0; i < 10; ++i) { + batch.set(randomCol.doc('doc' + i), {val: i}); + } + + const query = randomCol.where('val', '>=', 1).limit(3); + + return batch + .commit() + .then(() => paginateResults(query)) + .then(results => { + expect(results.pages).to.equal(3); + expect(results.docs).to.have.length(9); + }); + }); + + it('supports pagination with array-contains filter', () => { + const batch = firestore.batch(); + + for (let i = 0; i < 10; ++i) { + batch.set(randomCol.doc('doc' + i), {array: ['foo']}); + } + + const query = randomCol.where('array', 'array-contains', 'foo').limit(3); + + return batch + .commit() + .then(() => paginateResults(query)) + .then(results => { + expect(results.pages).to.equal(4); + expect(results.docs).to.have.length(10); + }); + }); + + it('has startAt() method', async () => { + await addDocs({foo: 'a'}, {foo: 'b'}); + const res = await randomCol.orderBy('foo').startAt('b').get(); + expectDocs(res, {foo: 'b'}); + }); + + it('startAt() adds implicit order by for DocumentSnapshot', async () => { + const references = await addDocs({foo: 'a'}, {foo: 'b'}); + const docSnap = await references[1].get(); + const res = await randomCol.startAt(docSnap).get(); + expectDocs(res, {foo: 'b'}); + }); + + it('has startAfter() method', async () => { + await addDocs({foo: 'a'}, {foo: 'b'}); + const res = await randomCol.orderBy('foo').startAfter('a').get(); + expectDocs(res, {foo: 'b'}); + }); + + it('has endAt() method', async () => { + await addDocs({foo: 'a'}, {foo: 'b'}); + const res = await randomCol.orderBy('foo').endAt('b').get(); + expectDocs(res, {foo: 'a'}, {foo: 'b'}); + }); + + it('has endBefore() method', async () => { + await addDocs({foo: 'a'}, {foo: 'b'}); + const res = await randomCol.orderBy('foo').endBefore('b').get(); + expectDocs(res, {foo: 'a'}); + }); + + it('has stream() method', done => { + let received = 0; + const ref1 = randomCol.doc('doc1'); + const ref2 = randomCol.doc('doc2'); + + Promise.all([ref1.set({foo: 'a'}), ref2.set({foo: 'b'})]).then(() => { + return randomCol + .stream() + .on('data', d => { + expect(d).to.be.an.instanceOf(DocumentSnapshot); + ++received; + }) + .on('end', () => { + expect(received).to.equal(2); + done(); + }); + }); + }); + + it('stream() supports readable[Symbol.asyncIterator]()', async () => { + let received = 0; + await randomCol.doc().set({foo: 'bar'}); + await randomCol.doc().set({foo: 'bar'}); + + const stream = randomCol.stream(); + for await (const doc of stream) { + expect(doc).to.be.an.instanceOf(QueryDocumentSnapshot); + ++received; + } + + expect(received).to.equal(2); + }); + + it('can query collection groups', async () => { + // Use `randomCol` to get a random collection group name to use but ensure + // it starts with 'b' for predictable ordering. + const collectionGroup = 'b' + randomCol.id; + + const docPaths = [ + `abc/123/${collectionGroup}/cg-doc1`, + `abc/123/${collectionGroup}/cg-doc2`, + `${collectionGroup}/cg-doc3`, + `${collectionGroup}/cg-doc4`, + `def/456/${collectionGroup}/cg-doc5`, + `${collectionGroup}/virtual-doc/nested-coll/not-cg-doc`, + `x${collectionGroup}/not-cg-doc`, + `${collectionGroup}x/not-cg-doc`, + `abc/123/${collectionGroup}x/not-cg-doc`, + `abc/123/x${collectionGroup}/not-cg-doc`, + `abc/${collectionGroup}`, + ]; + const batch = firestore.batch(); + for (const docPath of docPaths) { + batch.set(firestore.doc(docPath), {x: 1}); + } + await batch.commit(); + + const querySnapshot = await firestore + .collectionGroup(collectionGroup) + .get(); + expect(querySnapshot.docs.map(d => d.id)).to.deep.equal([ + 'cg-doc1', + 'cg-doc2', + 'cg-doc3', + 'cg-doc4', + 'cg-doc5', + ]); + }); + + it('can query collection groups with startAt / endAt by arbitrary documentId', async () => { + // Use `randomCol` to get a random collection group name to use but + // ensure it starts with 'b' for predictable ordering. + const collectionGroup = 'b' + randomCol.id; + + const docPaths = [ + `a/a/${collectionGroup}/cg-doc1`, + `a/b/a/b/${collectionGroup}/cg-doc2`, + `a/b/${collectionGroup}/cg-doc3`, + `a/b/c/d/${collectionGroup}/cg-doc4`, + `a/c/${collectionGroup}/cg-doc5`, + `${collectionGroup}/cg-doc6`, + 'a/b/nope/nope', + ]; + const batch = firestore.batch(); + for (const docPath of docPaths) { + batch.set(firestore.doc(docPath), {x: 1}); + } + await batch.commit(); + + let querySnapshot = await firestore + .collectionGroup(collectionGroup) + .orderBy(FieldPath.documentId()) + .startAt('a/b') + .endAt('a/b0') + .get(); + expect(querySnapshot.docs.map(d => d.id)).to.deep.equal([ + 'cg-doc2', + 'cg-doc3', + 'cg-doc4', + ]); + + querySnapshot = await firestore + .collectionGroup(collectionGroup) + .orderBy(FieldPath.documentId()) + .startAfter('a/b') + .endBefore(`a/b/${collectionGroup}/cg-doc3`) + .get(); + expect(querySnapshot.docs.map(d => d.id)).to.deep.equal(['cg-doc2']); + }); + + it('can query collection groups with where filters on arbitrary documentId', async () => { + // Use `randomCol` to get a random collection group name to use but + // ensure it starts with 'b' for predictable ordering. + const collectionGroup = 'b' + randomCol.id; + + const docPaths = [ + `a/a/${collectionGroup}/cg-doc1`, + `a/b/a/b/${collectionGroup}/cg-doc2`, + `a/b/${collectionGroup}/cg-doc3`, + `a/b/c/d/${collectionGroup}/cg-doc4`, + `a/c/${collectionGroup}/cg-doc5`, + `${collectionGroup}/cg-doc6`, + 'a/b/nope/nope', + ]; + const batch = firestore.batch(); + for (const docPath of docPaths) { + batch.set(firestore.doc(docPath), {x: 1}); + } + await batch.commit(); + + let querySnapshot = await firestore + .collectionGroup(collectionGroup) + .where(FieldPath.documentId(), '>=', 'a/b') + .where(FieldPath.documentId(), '<=', 'a/b0') + .get(); + expect(querySnapshot.docs.map(d => d.id)).to.deep.equal([ + 'cg-doc2', + 'cg-doc3', + 'cg-doc4', + ]); + + querySnapshot = await firestore + .collectionGroup(collectionGroup) + .where(FieldPath.documentId(), '>', 'a/b') + .where(FieldPath.documentId(), '<', `a/b/${collectionGroup}/cg-doc3`) + .get(); + expect(querySnapshot.docs.map(d => d.id)).to.deep.equal(['cg-doc2']); + }); + + it('can query large collections', async () => { + // @grpc/grpc-js v0.4.1 failed to deliver the full set of query results for + // larger collections (https://github.com/grpc/grpc-node/issues/895); + const batch = firestore.batch(); + for (let i = 0; i < 100; ++i) { + batch.create(randomCol.doc(), {}); + } + await batch.commit(); + + const snapshot = await randomCol.get(); + expect(snapshot.size).to.equal(100); + }); + + it('supports OR queries', async () => { + const collection = await testCollectionWithDocs({ + doc1: {a: 1, b: 0}, + doc2: {a: 2, b: 1}, + doc3: {a: 3, b: 2}, + doc4: {a: 1, b: 3}, + doc5: {a: 1, b: 1}, + }); + + // Two equalities: a==1 || b==1. + expectDocs( + await collection + .where( + Filter.or(Filter.where('a', '==', 1), Filter.where('b', '==', 1)) + ) + .get(), + 'doc1', + 'doc2', + 'doc4', + 'doc5' + ); + + // (a==1 && b==0) || (a==3 && b==2) + expectDocs( + await collection + .where( + Filter.or( + Filter.and(Filter.where('a', '==', 1), Filter.where('b', '==', 0)), + Filter.and(Filter.where('a', '==', 3), Filter.where('b', '==', 2)) + ) + ) + .get(), + 'doc1', + 'doc3' + ); + + // a==1 && (b==0 || b==3). + expectDocs( + await collection + .where( + Filter.and( + Filter.where('a', '==', 1), + Filter.or(Filter.where('b', '==', 0), Filter.where('b', '==', 3)) + ) + ) + .get(), + 'doc1', + 'doc4' + ); + + // (a==2 || b==2) && (a==3 || b==3) + expectDocs( + await collection + .where( + Filter.and( + Filter.or(Filter.where('a', '==', 2), Filter.where('b', '==', 2)), + Filter.or(Filter.where('a', '==', 3), Filter.where('b', '==', 3)) + ) + ) + .get(), + 'doc3' + ); + + // Test with limits without orderBy (the __name__ ordering is the tie breaker). + expectDocs( + await collection + .where( + Filter.or(Filter.where('a', '==', 2), Filter.where('b', '==', 1)) + ) + .limit(1) + .get(), + 'doc2' + ); + }); + + // Skip this test if running against production because it results in a 'missing index' error. + // The Firestore Emulator, however, does serve these queries. + (process.env.FIRESTORE_EMULATOR_HOST === undefined ? it.skip : it)( + 'supports OR queries with composite indexes', + async () => { + const collection = await testCollectionWithDocs({ + doc1: {a: 1, b: 0}, + doc2: {a: 2, b: 1}, + doc3: {a: 3, b: 2}, + doc4: {a: 1, b: 3}, + doc5: {a: 1, b: 1}, + }); + + // with one inequality: a>2 || b==1. + expectDocs( + await collection + .where( + Filter.or(Filter.where('a', '>', 2), Filter.where('b', '==', 1)) + ) + .get(), + 'doc5', + 'doc2', + 'doc3' + ); + + // Test with limits (implicit order by ASC): (a==1) || (b > 0) LIMIT 2 + expectDocs( + await collection + .where( + Filter.or(Filter.where('a', '==', 1), Filter.where('b', '>', 0)) + ) + .limit(2) + .get(), + 'doc1', + 'doc2' + ); + + // Test with limits (explicit order by): (a==1) || (b > 0) LIMIT_TO_LAST 2 + // Note: The public query API does not allow implicit ordering when limitToLast is used. + expectDocs( + await collection + .where( + Filter.or(Filter.where('a', '==', 1), Filter.where('b', '>', 0)) + ) + .limitToLast(2) + .orderBy('b') + .get(), + 'doc3', + 'doc4' + ); + + // Test with limits (explicit order by ASC): (a==2) || (b == 1) ORDER BY a LIMIT 1 + expectDocs( + await collection + .where( + Filter.or(Filter.where('a', '==', 2), Filter.where('b', '==', 1)) + ) + .limit(1) + .orderBy('a') + .get(), + 'doc5' + ); + + // Test with limits (explicit order by DESC): (a==2) || (b == 1) ORDER BY a LIMIT 1 + expectDocs( + await collection + .where( + Filter.or(Filter.where('a', '==', 2), Filter.where('b', '==', 1)) + ) + .limit(1) + .orderBy('a', 'desc') + .get(), + 'doc2' + ); + } + ); + + it('supports OR queries on documents with missing fields', async () => { + const collection = await testCollectionWithDocs({ + doc1: {a: 1, b: 0}, + doc2: {b: 1}, + doc3: {a: 3, b: 2}, + doc4: {a: 1, b: 3}, + doc5: {a: 1}, + doc6: {a: 2}, + }); + + // Query: a==1 || b==1 + // There's no explicit nor implicit orderBy. Documents with missing 'a' or missing 'b' should be + // allowed if the document matches at least one disjunction term. + expectDocs( + await collection + .where( + Filter.or(Filter.where('a', '==', 1), Filter.where('b', '==', 1)) + ) + .get(), + 'doc1', + 'doc2', + 'doc4', + 'doc5' + ); + }); + + // Skip this test if running against production because it results in a 'missing index' error. + // The Firestore Emulator, however, does serve these queries. + (process.env.FIRESTORE_EMULATOR_HOST === undefined ? it.skip : it)( + 'supports OR queries on documents with missing fields', + async () => { + const collection = await testCollectionWithDocs({ + doc1: {a: 1, b: 0}, + doc2: {b: 1}, + doc3: {a: 3, b: 2}, + doc4: {a: 1, b: 3}, + doc5: {a: 1}, + doc6: {a: 2}, + }); + + // Query: a==1 || b==1 order by a. + // doc2 should not be included because it's missing the field 'a', and we have "orderBy a". + expectDocs( + await collection + .where( + Filter.or(Filter.where('a', '==', 1), Filter.where('b', '==', 1)) + ) + .orderBy('a') + .get(), + 'doc1', + 'doc4', + 'doc5' + ); + + // Query: a==1 || b==1 order by b. + // doc5 should not be included because it's missing the field 'b', and we have "orderBy b". + expectDocs( + await collection + .where( + Filter.or(Filter.where('a', '==', 1), Filter.where('b', '==', 1)) + ) + .orderBy('b') + .get(), + 'doc1', + 'doc2', + 'doc4' + ); + + // Query: a>2 || b==1. + // This query has an implicit 'order by a'. + // doc2 should not be included because it's missing the field 'a'. + expectDocs( + await collection + .where( + Filter.or(Filter.where('a', '>', 2), Filter.where('b', '==', 1)) + ) + .get(), + 'doc3' + ); + + // Query: a>1 || b==1 order by a order by b. + // doc6 should not be included because it's missing the field 'b'. + // doc2 should not be included because it's missing the field 'a'. + expectDocs( + await collection + .where( + Filter.or(Filter.where('a', '>', 1), Filter.where('b', '==', 1)) + ) + .orderBy('a') + .orderBy('b') + .get(), + 'doc3' + ); + } + ); + + it('supports OR queries with in', async () => { + const collection = await testCollectionWithDocs({ + doc1: {a: 1, b: 0}, + doc2: {b: 1}, + doc3: {a: 3, b: 2}, + doc4: {a: 1, b: 3}, + doc5: {a: 1}, + doc6: {a: 2}, + }); + + // Query: a==2 || b in [2, 3] + expectDocs( + await collection + .where( + Filter.or(Filter.where('a', '==', 2), Filter.where('b', 'in', [2, 3])) + ) + .get(), + 'doc3', + 'doc4', + 'doc6' + ); + }); + + // Skip this test if running against production because it results in a 'missing index' error. + // The Firestore Emulator, however, does serve these queries. + (process.env.FIRESTORE_EMULATOR_HOST === undefined ? it.skip : it)( + 'supports OR queries with not-in', + async () => { + const collection = await testCollectionWithDocs({ + doc1: {a: 1, b: 0}, + doc2: {b: 1}, + doc3: {a: 3, b: 2}, + doc4: {a: 1, b: 3}, + doc5: {a: 1}, + doc6: {a: 2}, + }); + + // a==2 || (b != 2 && b != 3) + // Has implicit "orderBy b" + expectDocs( + await collection + .where( + Filter.or( + Filter.where('a', '==', 2), + Filter.where('b', 'not-in', [2, 3]) + ) + ) + .get(), + 'doc1', + 'doc2' + ); + } + ); + + it('supports OR queries with array membership', async () => { + const collection = await testCollectionWithDocs({ + doc1: {a: 1, b: [0]}, + doc2: {b: [1]}, + doc3: {a: 3, b: [2, 7]}, + doc4: {a: 1, b: [3, 7]}, + doc5: {a: 1}, + doc6: {a: 2}, + }); + + // Query: a==2 || b array-contains 7 + expectDocs( + await collection + .where( + Filter.or( + Filter.where('a', '==', 2), + Filter.where('b', 'array-contains', 7) + ) + ) + .get(), + 'doc3', + 'doc4', + 'doc6' + ); + + // a==2 || b array-contains-any [0, 3] + // Has implicit "orderBy b" + expectDocs( + await collection + .where( + Filter.or( + Filter.where('a', '==', 2), + Filter.where('b', 'array-contains-any', [0, 3]) + ) + ) + .get(), + 'doc1', + 'doc4', + 'doc6' + ); + }); + + describe('watch', () => { + interface ExpectedChange { + type: string; + doc: DocumentSnapshot; + } + + const currentDeferred = new DeferredPromise(); + + const snapshot = (id: string, data: DocumentData) => { + const ref = randomCol.doc(id); + const fields = ref.firestore._serializer!.encodeFields(data); + return randomCol.firestore.snapshot_( + { + name: + 'projects/ignored/databases/(default)/documents/' + + ref._path.relativeName, + fields, + createTime: {seconds: 0, nanos: 0}, + updateTime: {seconds: 0, nanos: 0}, + }, + {seconds: 0, nanos: 0} + ); + }; + + const docChange = ( + type: string, + id: string, + data: DocumentData + ): ExpectedChange => { + return { + type, + doc: snapshot(id, data), + }; + }; + + const added = (id: string, data: DocumentData) => + docChange('added', id, data); + const modified = (id: string, data: DocumentData) => + docChange('modified', id, data); + const removed = (id: string, data: DocumentData) => + docChange('removed', id, data); + + function resetPromise() { + currentDeferred.promise = new Promise((resolve, reject) => { + currentDeferred.resolve = resolve; + currentDeferred.reject = reject; + }); + } + + function waitForSnapshot(): Promise { + return currentDeferred.promise!.then(snapshot => { + resetPromise(); + return snapshot; + }); + } + + function snapshotsEqual( + actual: QuerySnapshot, + expected: {docs: DocumentSnapshot[]; docChanges: ExpectedChange[]} + ) { + let i; + expect(actual.size).to.equal(expected.docs.length); + for (i = 0; i < expected.docs.length && i < actual.size; i++) { + expect(actual.docs[i].ref.id).to.equal(expected.docs[i].ref.id); + expect(actual.docs[i].data()).to.deep.equal(expected.docs[i].data()); + } + const actualDocChanges = actual.docChanges(); + expect(actualDocChanges.length).to.equal(expected.docChanges.length); + for (i = 0; i < expected.docChanges.length; i++) { + expect(actualDocChanges[i].type).to.equal(expected.docChanges[i].type); + expect(actualDocChanges[i].doc.ref.id).to.equal( + expected.docChanges[i].doc.ref.id + ); + expect(actualDocChanges[i].doc.data()).to.deep.equal( + expected.docChanges[i].doc.data() + ); + expect(actualDocChanges[i].doc.readTime).to.exist; + expect(actualDocChanges[i].doc.createTime).to.exist; + expect(actualDocChanges[i].doc.updateTime).to.exist; + } + expect(actual.readTime).to.exist; + } + + beforeEach(() => resetPromise()); + + it('handles changing a doc', () => { + const ref1 = randomCol.doc('doc1'); + const ref2 = randomCol.doc('doc2'); + + const unsubscribe = randomCol.onSnapshot( + snapshot => { + currentDeferred.resolve(snapshot); + }, + err => { + currentDeferred.reject!(err); + } + ); + + return waitForSnapshot() + .then(results => { + snapshotsEqual(results, {docs: [], docChanges: []}); + // Add a result. + return ref1.set({foo: 'a'}); + }) + .then(() => { + return waitForSnapshot(); + }) + .then(results => { + snapshotsEqual(results, { + docs: [snapshot('doc1', {foo: 'a'})], + docChanges: [added('doc1', {foo: 'a'})], + }); + // Add another result. + return ref2.set({foo: 'b'}); + }) + .then(() => { + return waitForSnapshot(); + }) + .then(results => { + snapshotsEqual(results, { + docs: [snapshot('doc1', {foo: 'a'}), snapshot('doc2', {foo: 'b'})], + docChanges: [added('doc2', {foo: 'b'})], + }); + // Change a result. + return ref2.set({bar: 'c'}); + }) + .then(() => { + return waitForSnapshot(); + }) + .then(results => { + snapshotsEqual(results, { + docs: [snapshot('doc1', {foo: 'a'}), snapshot('doc2', {bar: 'c'})], + docChanges: [modified('doc2', {bar: 'c'})], + }); + unsubscribe(); + }); + }); + + it("handles changing a doc so it doesn't match", () => { + const ref1 = randomCol.doc('doc1'); + const ref2 = randomCol.doc('doc2'); + + const query = randomCol.where('included', '==', 'yes'); + const unsubscribe = query.onSnapshot( + snapshot => { + currentDeferred.resolve(snapshot); + }, + err => { + currentDeferred.reject(err); + } + ); + + return waitForSnapshot() + .then(results => { + snapshotsEqual(results, {docs: [], docChanges: []}); + // Add a result. + return ref1.set({included: 'yes'}); + }) + .then(() => { + return waitForSnapshot(); + }) + .then(results => { + snapshotsEqual(results, { + docs: [snapshot('doc1', {included: 'yes'})], + docChanges: [added('doc1', {included: 'yes'})], + }); + // Add another result. + return ref2.set({included: 'yes'}); + }) + .then(() => { + return waitForSnapshot(); + }) + .then(results => { + snapshotsEqual(results, { + docs: [ + snapshot('doc1', {included: 'yes'}), + snapshot('doc2', {included: 'yes'}), + ], + docChanges: [added('doc2', {included: 'yes'})], + }); + // Change a result. + return ref2.set({included: 'no'}); + }) + .then(() => { + return waitForSnapshot(); + }) + .then(results => { + snapshotsEqual(results, { + docs: [snapshot('doc1', {included: 'yes'})], + docChanges: [removed('doc2', {included: 'yes'})], + }); + unsubscribe(); + }); + }); + + it('handles deleting a doc', () => { + const ref1 = randomCol.doc('doc1'); + const ref2 = randomCol.doc('doc2'); + + const unsubscribe = randomCol.onSnapshot( + snapshot => { + currentDeferred.resolve(snapshot); + }, + err => { + currentDeferred.reject(err); + } + ); + + return waitForSnapshot() + .then(results => { + snapshotsEqual(results, {docs: [], docChanges: []}); + // Add a result. + return ref1.set({included: 'yes'}); + }) + .then(() => { + return waitForSnapshot(); + }) + .then(results => { + snapshotsEqual(results, { + docs: [snapshot('doc1', {included: 'yes'})], + docChanges: [added('doc1', {included: 'yes'})], + }); + // Add another result. + return ref2.set({included: 'yes'}); + }) + .then(() => { + return waitForSnapshot(); + }) + .then(results => { + snapshotsEqual(results, { + docs: [ + snapshot('doc1', {included: 'yes'}), + snapshot('doc2', {included: 'yes'}), + ], + docChanges: [added('doc2', {included: 'yes'})], + }); + // Delete a result. + return ref2.delete(); + }) + .then(() => { + return waitForSnapshot(); + }) + .then(results => { + snapshotsEqual(results, { + docs: [snapshot('doc1', {included: 'yes'})], + docChanges: [removed('doc2', {included: 'yes'})], + }); + unsubscribe(); + }); + }); + + it('orders limitToLast() correctly', async () => { + const ref1 = randomCol.doc('doc1'); + const ref2 = randomCol.doc('doc2'); + const ref3 = randomCol.doc('doc3'); + + await ref1.set({doc: 1}); + await ref2.set({doc: 2}); + await ref3.set({doc: 3}); + + const unsubscribe = randomCol + .orderBy('doc') + .limitToLast(2) + .onSnapshot(snapshot => currentDeferred.resolve(snapshot)); + + const results = await waitForSnapshot(); + snapshotsEqual(results, { + docs: [snapshot('doc2', {doc: 2}), snapshot('doc3', {doc: 3})], + docChanges: [added('doc2', {doc: 2}), added('doc3', {doc: 3})], + }); + + unsubscribe(); + }); + + it('SDK orders vector field same way as backend', async () => { + // We validate that the SDK orders the vector field the same way as the backend + // by comparing the sort order of vector fields from a Query.get() and + // Query.onSnapshot(). Query.onSnapshot() will return sort order of the SDK, + // and Query.get() will return sort order of the backend. + + // Test data in the order that we expect the backend to sort it. + const docsInOrder = [ + {embedding: [1, 2, 3, 4, 5, 6]}, + {embedding: [100]}, + {embedding: FieldValue.vector([Number.NEGATIVE_INFINITY])}, + {embedding: FieldValue.vector([-100])}, + {embedding: FieldValue.vector([100])}, + {embedding: FieldValue.vector([Number.POSITIVE_INFINITY])}, + {embedding: FieldValue.vector([1, 2])}, + {embedding: FieldValue.vector([2, 2])}, + {embedding: FieldValue.vector([1, 2, 3])}, + {embedding: FieldValue.vector([1, 2, 3, 4])}, + {embedding: FieldValue.vector([1, 2, 3, 4, 5])}, + {embedding: FieldValue.vector([1, 2, 100, 4, 4])}, + {embedding: FieldValue.vector([100, 2, 3, 4, 5])}, + {embedding: {HELLO: 'WORLD'}}, + {embedding: {hello: 'world'}}, + ]; + + const expectedSnapshots = []; + const expectedChanges = []; + + for (let i = 0; i < docsInOrder.length; i++) { + const dr = await randomCol.add(docsInOrder[i]); + expectedSnapshots.push(snapshot(dr.id, docsInOrder[i])); + expectedChanges.push(added(dr.id, docsInOrder[i])); + } + + const orderedQuery = randomCol.orderBy('embedding'); + + const unsubscribe = orderedQuery.onSnapshot( + snapshot => { + currentDeferred.resolve(snapshot); + }, + err => { + currentDeferred.reject!(err); + } + ); + + const watchSnapshot = await waitForSnapshot(); + unsubscribe(); + + const getSnapshot = await orderedQuery.get(); + + // Compare the snapshot (including sort order) of a snapshot + // from Query.onSnapshot() to an actual snapshot from Query.get() + snapshotsEqual(watchSnapshot, { + docs: getSnapshot.docs, + docChanges: getSnapshot.docChanges(), + }); + + // Compare the snapshot (including sort order) of a snapshot + // from Query.onSnapshot() to the expected sort order from + // the backend. + snapshotsEqual(watchSnapshot, { + docs: expectedSnapshots, + docChanges: expectedChanges, + }); + }); + }); + + (process.env.FIRESTORE_EMULATOR_HOST === undefined + ? describe.skip + : describe)('multiple inequality', () => { + it('supports multiple inequality queries', async () => { + const collection = await testCollectionWithDocs({ + doc1: {key: 'a', sort: 0, v: 0}, + doc2: {key: 'b', sort: 3, v: 1}, + doc3: {key: 'c', sort: 1, v: 3}, + doc4: {key: 'd', sort: 2, v: 2}, + }); + + // Multiple inequality fields + let results = await collection + .where('key', '!=', 'a') + .where('sort', '<=', 2) + .where('v', '>', 2) + .get(); + expectDocs(results, 'doc3'); + + // Duplicate inequality fields + results = await collection + .where('key', '!=', 'a') + .where('sort', '<=', 2) + .where('sort', '>', 1) + .get(); + expectDocs(results, 'doc4'); + + // With multiple IN + results = await collection + .where('key', '>=', 'a') + .where('sort', '<=', 2) + .where('v', 'in', [2, 3, 4]) + .where('sort', 'in', [2, 3]) + .get(); + expectDocs(results, 'doc4'); + + // With NOT-IN + results = await collection + .where('key', '>=', 'a') + .where('sort', '<=', 2) + .where('v', 'not-in', [2, 4, 5]) + .get(); + expectDocs(results, 'doc1', 'doc3'); + + // With orderby + results = await collection + .where('key', '>=', 'a') + .where('sort', '<=', 2) + .orderBy('v', 'desc') + .get(); + expectDocs(results, 'doc3', 'doc4', 'doc1'); + + // With limit + results = await collection + .where('key', '>=', 'a') + .where('sort', '<=', 2) + .orderBy('v', 'desc') + .limit(2) + .get(); + expectDocs(results, 'doc3', 'doc4'); + + // With limitToLast + results = await collection + .where('key', '>=', 'a') + .where('sort', '<=', 2) + .orderBy('v', 'desc') + .limitToLast(2) + .get(); + expectDocs(results, 'doc4', 'doc1'); + }); + + it('can use on special values', async () => { + const collection = await testCollectionWithDocs({ + doc1: {key: 'a', sort: 0, v: 0}, + doc2: {key: 'b', sort: NaN, v: 1}, + doc3: {key: 'c', sort: null, v: 3}, + doc4: {key: 'd', v: 0}, + doc5: {key: 'e', sort: 1}, + doc6: {key: 'f', sort: 1, v: 1}, + }); + + let results = await collection + .where('key', '!=', 'a') + .where('sort', '<=', 2) + .get(); + expectDocs(results, 'doc5', 'doc6'); + + results = await collection + .where('key', '!=', 'a') + .where('sort', '<=', 2) + .where('v', '<=', 1) + .get(); + expectDocs(results, 'doc6'); + }); + + it('can use with array membership', async () => { + const collection = await testCollectionWithDocs({ + doc1: {key: 'a', sort: 0, v: [0]}, + doc2: {key: 'b', sort: 1, v: [0, 1, 3]}, + doc3: {key: 'c', sort: 1, v: []}, + doc4: {key: 'd', sort: 2, v: [1]}, + doc5: {key: 'e', sort: 3, v: [2, 4]}, + doc6: {key: 'f', sort: 4, v: [NaN]}, + doc7: {key: 'g', sort: 4, v: [null]}, + }); + + let results = await collection + .where('key', '!=', 'a') + .where('sort', '>=', 1) + .where('v', 'array-contains', 0) + .get(); + expectDocs(results, 'doc2'); + + results = await collection + .where('key', '!=', 'a') + .where('sort', '>=', 1) + .where('v', 'array-contains-any', [0, 1]) + .get(); + expectDocs(results, 'doc2', 'doc4'); + }); + + // Use cursor in following test cases to add implicit order by fields in the sdk and compare the + // result with the query fields normalized in the server. + it('can use with nested field', async () => { + // eslint-disable-next-line @typescript-eslint/no-explicit-any + const testData = (n?: number): any => { + n = n || 1; + return { + name: 'room ' + n, + metadata: { + createdAt: n, + }, + field: 'field ' + n, + 'field.dot': n, + 'field\\slash': n, + }; + }; + + const collection = await testCollectionWithDocs({ + doc1: testData(400), + doc2: testData(200), + doc3: testData(100), + doc4: testData(300), + }); + + // ordered by: name asc, metadata.createdAt asc, __name__ asc + let query = collection + .where('metadata.createdAt', '<=', 500) + .where('metadata.createdAt', '>', 100) + .where('name', '!=', 'room 200') + .orderBy('name'); + let docSnap = await collection.doc('doc4').get(); + let queryWithCursor = query.startAt(docSnap); + expectDocs(await query.get(), 'doc4', 'doc1'); + expectDocs(await queryWithCursor.get(), 'doc4', 'doc1'); + + // ordered by: name desc, field desc, field.dot desc, field\\slash desc, __name__ desc + query = collection + .where('field', '>=', 'field 100') + .where(new FieldPath('field.dot'), '!=', 300) + .where('field\\slash', '<', 400) + .orderBy('name', 'desc'); + docSnap = await collection.doc('doc2').get(); + queryWithCursor = query.startAt(docSnap); + expectDocs(await query.get(), 'doc2', 'doc3'); + expectDocs(await queryWithCursor.get(), 'doc2', 'doc3'); + }); + + it('can use with nested composite filters', async () => { + const collection = await testCollectionWithDocs({ + doc1: {key: 'a', sort: 0, v: 5}, + doc2: {key: 'aa', sort: 4, v: 4}, + doc3: {key: 'c', sort: 3, v: 3}, + doc4: {key: 'b', sort: 2, v: 2}, + doc5: {key: 'b', sort: 2, v: 1}, + doc6: {key: 'b', sort: 0, v: 0}, + }); + + // Implicitly ordered by: 'key' asc, 'sort' asc, 'v' asc, __name__ asc + let query = collection.where( + Filter.or( + Filter.and( + Filter.where('key', '==', 'b'), + Filter.where('sort', '<=', 2) + ), + Filter.and(Filter.where('key', '!=', 'b'), Filter.where('v', '>', 4)) + ) + ); + let docSnap = await collection.doc('doc1').get(); + let queryWithCursor = query.startAt(docSnap); + expectDocs(await query.get(), 'doc1', 'doc6', 'doc5', 'doc4'); + expectDocs(await queryWithCursor.get(), 'doc1', 'doc6', 'doc5', 'doc4'); + + // Ordered by: 'sort' desc, 'key' asc, 'v' asc, __name__ asc + query = collection + .where( + Filter.or( + Filter.and( + Filter.where('key', '==', 'b'), + Filter.where('sort', '<=', 2) + ), + Filter.and( + Filter.where('key', '!=', 'b'), + Filter.where('v', '>', 4) + ) + ) + ) + .orderBy('sort', 'desc') + .orderBy('key'); + docSnap = await collection.doc('doc5').get(); + queryWithCursor = query.startAt(docSnap); + expectDocs(await query.get(), 'doc5', 'doc4', 'doc1', 'doc6'); + expectDocs(await queryWithCursor.get(), 'doc5', 'doc4', 'doc1', 'doc6'); + + // Implicitly ordered by: 'key' asc, 'sort' asc, 'v' asc, __name__ asc + query = collection.where( + Filter.and( + Filter.or( + Filter.and( + Filter.where('key', '==', 'b'), + Filter.where('sort', '<=', 4) + ), + Filter.and( + Filter.where('key', '!=', 'b'), + Filter.where('v', '>=', 4) + ) + ), + Filter.or( + Filter.and( + Filter.where('key', '>', 'b'), + Filter.where('sort', '>=', 1) + ), + Filter.and(Filter.where('key', '<', 'b'), Filter.where('v', '>', 0)) + ) + ) + ); + docSnap = await collection.doc('doc1').get(); + queryWithCursor = query.startAt(docSnap); + expectDocs(await query.get(), 'doc1', 'doc2'); + expectDocs(await queryWithCursor.get(), 'doc1', 'doc2'); + }); + + it('inequality fields will be implicitly ordered lexicographically by the server', async () => { + const collection = await testCollectionWithDocs({ + doc1: {key: 'a', sort: 0, v: 5}, + doc2: {key: 'aa', sort: 4, v: 4}, + doc3: {key: 'b', sort: 3, v: 3}, + doc4: {key: 'b', sort: 2, v: 2}, + doc5: {key: 'b', sort: 2, v: 1}, + doc6: {key: 'b', sort: 0, v: 0}, + }); + + const docSnap = await collection.doc('doc2').get(); + + // Implicitly ordered by: 'key' asc, 'sort' asc, __name__ asc + let query = collection + .where('key', '!=', 'a') + .where('sort', '>', 1) + .where('v', 'in', [1, 2, 3, 4]); + let queryWithCursor = query.startAt(docSnap); + expectDocs(await query.get(), 'doc2', 'doc4', 'doc5', 'doc3'); + expectDocs(await queryWithCursor.get(), 'doc2', 'doc4', 'doc5', 'doc3'); + + // Changing filters order will not effect implicit order. + // Implicitly ordered by: 'key' asc, 'sort' asc, __name__ asc + query = collection + .where('sort', '>', 1) + .where('key', '!=', 'a') + .where('v', 'in', [1, 2, 3, 4]); + queryWithCursor = query.startAt(docSnap); + expectDocs(await query.get(), 'doc2', 'doc4', 'doc5', 'doc3'); + expectDocs(await queryWithCursor.get(), 'doc2', 'doc4', 'doc5', 'doc3'); + }); + + it('can use multiple explicit order by field', async () => { + const collection = await testCollectionWithDocs({ + doc1: {key: 'a', sort: 5, v: 0}, + doc2: {key: 'aa', sort: 4, v: 0}, + doc3: {key: 'b', sort: 3, v: 1}, + doc4: {key: 'b', sort: 2, v: 1}, + doc5: {key: 'bb', sort: 1, v: 1}, + doc6: {key: 'c', sort: 0, v: 2}, + }); + + let docSnap = await collection.doc('doc2').get(); + + // Ordered by: 'v' asc, 'key' asc, 'sort' asc, __name__ asc + let query = collection + .where('key', '>', 'a') + .where('sort', '>=', 1) + .orderBy('v'); + let queryWithCursor = query.startAt(docSnap); + expectDocs(await query.get(), 'doc2', 'doc4', 'doc3', 'doc5'); + expectDocs(await queryWithCursor.get(), 'doc2', 'doc4', 'doc3', 'doc5'); + + // Ordered by: 'v asc, 'sort' asc, 'key' asc, __name__ asc + query = collection + .where('key', '>', 'a') + .where('sort', '>=', 1) + .orderBy('v') + .orderBy('sort'); + queryWithCursor = query.startAt(docSnap); + expectDocs(await query.get(), 'doc2', 'doc5', 'doc4', 'doc3'); + expectDocs(await queryWithCursor.get(), 'doc2', 'doc5', 'doc4', 'doc3'); + + docSnap = await collection.doc('doc5').get(); + + // Implicit order by matches the direction of last explicit order by. + // Ordered by: 'v' desc, 'key' desc, 'sort' desc, __name__ desc + query = collection + .where('key', '>', 'a') + .where('sort', '>=', 1) + .orderBy('v', 'desc'); + queryWithCursor = query.startAt(docSnap); + expectDocs(await query.get(), 'doc5', 'doc3', 'doc4', 'doc2'); + expectDocs(await queryWithCursor.get(), 'doc5', 'doc3', 'doc4', 'doc2'); + + // Ordered by: 'v desc, 'sort' asc, 'key' asc, __name__ asc + query = collection + .where('key', '>', 'a') + .where('sort', '>=', 1) + .orderBy('v', 'desc') + .orderBy('sort'); + queryWithCursor = query.startAt(docSnap); + expectDocs(await query.get(), 'doc5', 'doc4', 'doc3', 'doc2'); + expectDocs(await queryWithCursor.get(), 'doc5', 'doc4', 'doc3', 'doc2'); + }); + + it('can use in aggregate query', async () => { + const collection = await testCollectionWithDocs({ + doc1: {key: 'a', sort: 5, v: 0}, + doc2: {key: 'aa', sort: 4, v: 0}, + doc3: {key: 'b', sort: 3, v: 1}, + doc4: {key: 'b', sort: 2, v: 1}, + doc5: {key: 'bb', sort: 1, v: 1}, + }); + + const results = await collection + .where('key', '>', 'a') + .where('sort', '>=', 1) + .orderBy('v') + .count() + .get(); + expect(results.data().count).to.be.equal(4); + //TODO(MIEQ): Add sum and average when they are public. + }); + + it('can use document ID im multiple inequality query', async () => { + const collection = await testCollectionWithDocs({ + doc1: {key: 'a', sort: 5}, + doc2: {key: 'aa', sort: 4}, + doc3: {key: 'b', sort: 3}, + doc4: {key: 'b', sort: 2}, + doc5: {key: 'bb', sort: 1}, + }); + + const docSnap = await collection.doc('doc2').get(); + + // Document Key in inequality field will implicitly ordered to the last. + // Implicitly ordered by: 'key' asc, 'sort' asc, __name__ asc + let query = collection + .where('sort', '>=', 1) + .where('key', '!=', 'a') + .where(FieldPath.documentId(), '<', 'doc5'); + let queryWithCursor = query.startAt(docSnap); + expectDocs(await query.get(), 'doc2', 'doc4', 'doc3'); + expectDocs(await queryWithCursor.get(), 'doc2', 'doc4', 'doc3'); + + // Changing filters order will not effect implicit order. + // Implicitly ordered by: 'key' asc, 'sort' asc, __name__ asc + query = collection + .where(FieldPath.documentId(), '<', 'doc5') + .where('sort', '>=', 1) + .where('key', '!=', 'a'); + queryWithCursor = query.startAt(docSnap); + expectDocs(await query.get(), 'doc2', 'doc4', 'doc3'); + expectDocs(await queryWithCursor.get(), 'doc2', 'doc4', 'doc3'); + + // Ordered by: 'sort' desc,'key' desc, __name__ desc + query = collection + .where(FieldPath.documentId(), '<', 'doc5') + .where('sort', '>=', 1) + .where('key', '!=', 'a') + .orderBy('sort', 'desc'); + queryWithCursor = query.startAt(docSnap); + expectDocs(await query.get(), 'doc2', 'doc3', 'doc4'); + expectDocs(await queryWithCursor.get(), 'doc2', 'doc3', 'doc4'); + }); + }); +}); + describe('count queries', () => { let firestore: Firestore; let randomCol: CollectionReference; diff --git a/dev/system-test/tracing.ts b/dev/system-test/tracing.ts new file mode 100644 index 000000000..d808447ec --- /dev/null +++ b/dev/system-test/tracing.ts @@ -0,0 +1,952 @@ +// 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. + +import * as chaiAsPromised from 'chai-as-promised'; +import {expect, use} from 'chai'; +import {describe, it, beforeEach, afterEach, Test} from 'mocha'; +import { + Attributes, + context, + diag, + DiagConsoleLogger, + DiagLogLevel, + ROOT_CONTEXT, + SpanContext, + trace, + TraceFlags, + Tracer, + TracerProvider, + Context as OpenTelemetryContext, +} from '@opentelemetry/api'; +import {TraceExporter} from '@google-cloud/opentelemetry-cloud-trace-exporter'; +import {Settings} from '@google-cloud/firestore'; +import { + AlwaysOnSampler, + BatchSpanProcessor, + ConsoleSpanExporter, + InMemorySpanExporter, + NodeTracerProvider, + ReadableSpan, + TimedEvent, +} from '@opentelemetry/sdk-trace-node'; +import {setLogFunction, Firestore} from '../src'; +import {verifyInstance} from '../test/util/helpers'; +import { + ATTRIBUTE_KEY_DOC_COUNT, + ATTRIBUTE_SETTINGS_PREFIX, + SPAN_NAME_AGGREGATION_QUERY_GET, + SPAN_NAME_BATCH_COMMIT, + SPAN_NAME_BATCH_GET_DOCUMENTS, + SPAN_NAME_BULK_WRITER_COMMIT, + SPAN_NAME_COL_REF_ADD, + SPAN_NAME_COL_REF_LIST_DOCUMENTS, + SPAN_NAME_DOC_REF_CREATE, + SPAN_NAME_DOC_REF_DELETE, + SPAN_NAME_DOC_REF_GET, + SPAN_NAME_DOC_REF_LIST_COLLECTIONS, + SPAN_NAME_DOC_REF_SET, + SPAN_NAME_DOC_REF_UPDATE, + SPAN_NAME_PARTITION_QUERY, + SPAN_NAME_QUERY_GET, + SPAN_NAME_TRANSACTION_COMMIT, + SPAN_NAME_TRANSACTION_GET_AGGREGATION_QUERY, + SPAN_NAME_TRANSACTION_GET_DOCUMENT, + SPAN_NAME_TRANSACTION_GET_DOCUMENTS, + SPAN_NAME_TRANSACTION_GET_QUERY, + SPAN_NAME_TRANSACTION_RUN, +} from '../src/telemetry/trace-util'; +import {AsyncLocalStorageContextManager} from '@opentelemetry/context-async-hooks'; +import {cloudtrace_v1, auth as gAuth} from '@googleapis/cloudtrace'; +import Schema$Trace = cloudtrace_v1.Schema$Trace; +import Schema$TraceSpan = cloudtrace_v1.Schema$TraceSpan; +import {logger} from '../src/logger'; + +use(chaiAsPromised); + +const NUM_TRACE_ID_BYTES = 32; +const NUM_SPAN_ID_BYTES = 16; +const SPAN_NAME_TEST_ROOT = 'TestRootSpan'; +const GET_TRACE_INITIAL_WAIT_MILLIS = 2000; +const GET_TRACE_RETRY_BACKOFF_MILLIS = 2000; +const GET_TRACE_MAX_RETRY_COUNT = 10; + +const E2E_TEST_SUITE_TITLE = 'E2E'; +const IN_MEMORY_TEST_SUITE_TITLE = 'IN-MEMORY'; +const GLOBAL_OTEL_TEST_SUITE_TITLE = 'GLOBAL-OTEL'; +const NON_GLOBAL_OTEL_TEST_SUITE_TITLE = 'NON-GLOBAL-OTEL'; +const GRPC_TEST_SUITE_TITLE = 'GRPC'; +const REST_TEST_SUITE_TITLE = 'REST'; + +// Enable OpenTelemetry debug message for local debugging. +diag.setLogger(new DiagConsoleLogger(), DiagLogLevel.DEBUG); + +// Enable Firestore debug messages for local debugging. +setLogFunction((msg: string) => { + console.log(`LOG: ${msg}`); +}); + +// TODO(tracing): This should be moved to firestore.d.ts when we want to +// release the feature. +export interface FirestoreOpenTelemetryOptions { + enableTracing?: boolean; + tracerProvider?: any; +} + +interface TestConfig { + // In-Memory tests check trace correctness by inspecting traces in memory by + // utilizing InMemorySpanExporter. These tests have `e2e` set to `false`. + // End-to-End tests check trace correctness by querying the Google Cloud Trace + // backend and making sure it has recorded all the expected spans. These + // tests have `e2e` set to `true`. + e2e: boolean; + + // OpenTelemetry allows registering a specific OpenTelemetry instance as the + // "global" instance. We should make sure that the tracing works in two + // circumstances: (1) the user provides us with a specific OpenTelemetry + // instance. (2) the user does not provide an instance and we find the + // global instance to use. + useGlobalOpenTelemetry: boolean; + + // Whether the Firestore instance should use gRPC or REST. + preferRest: boolean; +} + +// Unfortunately the in-memory spans and Cloud Trace spans do not share the +// same data-structures. This interface is useful to abstract that away for +// testing. +// Also note that Cloud Trace currently does NOT return span attributes nor +// span events. So we'll have to leave those as empty and not check them for +// end-to-end tests. +class SpanData { + constructor( + public id: string | null | undefined, + public parentId: string | null | undefined, + public traceId: string, + public name: string | null | undefined, + public attributes: Attributes, + public events: TimedEvent[] + ) {} + static fromInMemorySpan(span: ReadableSpan): SpanData { + return new SpanData( + span.spanContext().spanId, + span.parentSpanId, + span.spanContext().traceId, + span.name, + span.attributes, + span.events + ); + } + + static fromCloudTraceSpan(span: Schema$TraceSpan, traceId: string): SpanData { + return new SpanData( + span.spanId, + span.parentSpanId, + traceId, + span.name, + {}, + [] + ); + } +} + +describe('Tracing Tests', () => { + let firestore: Firestore; + let tracerProvider: NodeTracerProvider; + let inMemorySpanExporter: InMemorySpanExporter; + let consoleSpanExporter: ConsoleSpanExporter; + let gcpTraceExporter: TraceExporter; + let tracer: Tracer; + let cloudTraceInfo: Schema$Trace; + let testConfig: TestConfig; + + // Custom SpanContext for each test, required for trace ID injection. + let customSpanContext: SpanContext; + + // Custom Context for each test, required for trace ID injection. + let customContext: OpenTelemetryContext; + + const spanIdToChildrenSpanIds = new Map(); + const spanIdToSpanData = new Map(); + let rootSpanIds: string[] = []; + + function afterEachTest(): Promise { + spanIdToChildrenSpanIds.clear(); + spanIdToSpanData.clear(); + rootSpanIds = []; + + return verifyInstance(firestore); + } + + function getOpenTelemetryOptions( + tracerProvider: TracerProvider + ): FirestoreOpenTelemetryOptions { + const options: FirestoreOpenTelemetryOptions = { + enableTracing: true, + tracerProvider: undefined, + }; + + // If we are *not* using a global OpenTelemetry instance, a TracerProvider + // must be passed to the Firestore SDK. + if (!testConfig.useGlobalOpenTelemetry) { + options.tracerProvider = tracerProvider; + } + + return options; + } + + function generateRandomHexString(length: number): string { + if (length <= 0) { + throw new Error('Length must be a positive integer'); + } + + const hexCharacters = '0123456789abcdef'; + let hexString = ''; + for (let i = 0; i < length; i++) { + const randomIndex = Math.floor(Math.random() * hexCharacters.length); + hexString += hexCharacters[randomIndex]; + } + + return hexString; + } + + function getNewSpanContext(): SpanContext { + const spanContext: SpanContext = { + traceId: generateRandomHexString(NUM_TRACE_ID_BYTES), + spanId: generateRandomHexString(NUM_SPAN_ID_BYTES), + traceFlags: TraceFlags.SAMPLED, + }; + logger('getNewSpanContext', null, `custom span context:${spanContext}`); + return spanContext; + } + + function beforeEachTest(test: Test) { + testConfig = { + preferRest: test.parent?.title === REST_TEST_SUITE_TITLE, + useGlobalOpenTelemetry: + test.parent?.parent?.title === GLOBAL_OTEL_TEST_SUITE_TITLE, + e2e: test.parent?.parent?.parent?.title === E2E_TEST_SUITE_TITLE, + }; + + logger('beforeEach', null, 'Starting test with config:', testConfig); + + // Remove the global tracer provider in case anything was registered + // in order to avoid duplicate global tracers. + trace.disable(); + context.disable(); + + // Set up a context manager. + const contextManager = new AsyncLocalStorageContextManager(); + contextManager.enable(); + context.setGlobalContextManager(contextManager); + + // Create a new tracer and span processor for each test to make sure there + // are no overlaps when reading the results. + tracerProvider = new NodeTracerProvider({ + sampler: new AlwaysOnSampler(), + }); + + inMemorySpanExporter = new InMemorySpanExporter(); + consoleSpanExporter = new ConsoleSpanExporter(); + gcpTraceExporter = new TraceExporter(); + + // Always add the console exporter for local debugging. + tracerProvider.addSpanProcessor( + new BatchSpanProcessor(consoleSpanExporter) + ); + + if (testConfig.e2e) { + tracerProvider.addSpanProcessor(new BatchSpanProcessor(gcpTraceExporter)); + } else { + tracerProvider.addSpanProcessor( + new BatchSpanProcessor(inMemorySpanExporter) + ); + } + + if (testConfig.useGlobalOpenTelemetry) { + trace.setGlobalTracerProvider(tracerProvider); + } + + // Using a unique tracer name for each test. + tracer = tracerProvider.getTracer(`${test.title}${Date.now()}`); + + customSpanContext = getNewSpanContext(); + customContext = trace.setSpanContext(ROOT_CONTEXT, customSpanContext); + + const settings: Settings = { + preferRest: testConfig.preferRest, + openTelemetryOptions: getOpenTelemetryOptions(tracerProvider), + }; + + // Named-database tests use an environment variable to specify the database ID. Add it to the settings. + if (process.env.FIRESTORE_NAMED_DATABASE) { + settings.databaseId = process.env.FIRESTORE_NAMED_DATABASE; + } + // If a database ID has not been specified in the settings, check whether + // it's been specified using an environment variable. + if (!settings.databaseId && process.env.DATABASE_ID) { + settings.databaseId = process.env.DATABASE_ID; + } + // If a Project ID has not been specified in the settings, check whether + // it's been specified using an environment variable. + if (!settings.projectId && process.env.PROJECT_ID) { + settings.projectId = process.env.PROJECT_ID; + } + + firestore = new Firestore(settings); + } + + function getSettingsAttributes(): Attributes { + const settingsAttributes: Attributes = {}; + settingsAttributes['otel.scope.name'] = require('../../package.json').name; + settingsAttributes['otel.scope.version'] = + require('../../package.json').version; + settingsAttributes[`${ATTRIBUTE_SETTINGS_PREFIX}.database_id`] = + firestore.databaseId; + settingsAttributes[`${ATTRIBUTE_SETTINGS_PREFIX}.host`] = + 'firestore.googleapis.com:443'; + settingsAttributes[`${ATTRIBUTE_SETTINGS_PREFIX}.prefer_REST`] = + testConfig.preferRest; + settingsAttributes[`${ATTRIBUTE_SETTINGS_PREFIX}.max_idle_channels`] = 1; + settingsAttributes[`${ATTRIBUTE_SETTINGS_PREFIX}.initial_retry_delay`] = + '0.1s'; + settingsAttributes[`${ATTRIBUTE_SETTINGS_PREFIX}.initial_rpc_timeout`] = + '60s'; + settingsAttributes[`${ATTRIBUTE_SETTINGS_PREFIX}.total_timeout`] = '600s'; + settingsAttributes[`${ATTRIBUTE_SETTINGS_PREFIX}.max_retry_delay`] = '60s'; + settingsAttributes[`${ATTRIBUTE_SETTINGS_PREFIX}.max_rpc_timeout`] = '60s'; + settingsAttributes[`${ATTRIBUTE_SETTINGS_PREFIX}.retry_delay_multiplier`] = + '1.3'; + settingsAttributes[`${ATTRIBUTE_SETTINGS_PREFIX}.rpc_timeout_multiplier`] = + '1'; + + // Project ID is not set on the Firestore object until _after_ the first + // operation is done. Therefore, the spans that are created _before_ the + // first operation do not contain a project ID. + try { + const projectId = firestore.projectId; + settingsAttributes[`${ATTRIBUTE_SETTINGS_PREFIX}.project_id`] = projectId; + } catch (e) { + // Project ID has not been set yet. + } + + return settingsAttributes; + } + + // Take a function and runs it inside a new root span. This makes it possible to + // encapsulate all the SDK-generated spans inside a test root span. It also makes + // it easy to query a trace storage backend for a known trace ID and span Id. + function runFirestoreOperationInRootSpan void>( + fn: F + ): Promise { + return tracer.startActiveSpan( + SPAN_NAME_TEST_ROOT, + {}, + customContext, + async span => { + await fn(); + span.end(); + } + ); + } + + // Returns true on success, and false otherwise. + async function waitForCompletedInMemorySpans(): Promise { + await tracerProvider.forceFlush(); + await inMemorySpanExporter.forceFlush(); + await new Promise(resolve => setTimeout(resolve, 1000)); + return true; + } + + // Returns true on success, and false otherwise. + async function waitForCompletedCloudTraceSpans( + numExpectedSpans: number + ): Promise { + const auth = new gAuth.GoogleAuth({ + projectId: firestore.projectId, + scopes: ['https://www.googleapis.com/auth/cloud-platform'], + }); + const client = new cloudtrace_v1.Cloudtrace({auth}); + const projectTraces = new cloudtrace_v1.Resource$Projects$Traces( + client.context + ); + + // Querying the trace from Cloud Trace immediately is almost always going + // to fail. So we have an initial delay before making our first attempt. + await new Promise(resolve => + setTimeout(resolve, GET_TRACE_INITIAL_WAIT_MILLIS) + ); + + let remainingAttempts = GET_TRACE_MAX_RETRY_COUNT; + let receivedFullTrace = false; + do { + try { + const getTraceResponse = await projectTraces.get({ + projectId: firestore.projectId, + traceId: customSpanContext.traceId, + }); + + cloudTraceInfo = getTraceResponse.data; + + receivedFullTrace = cloudTraceInfo.spans?.length === numExpectedSpans; + logger( + 'waitForCompletedCloudTraceSpans', + null, + `fetched a trace with ${cloudTraceInfo.spans?.length} spans` + ); + } catch (error) { + logger( + 'waitForCompletedCloudTraceSpans', + null, + 'failed with error:', + error + ); + } + + // Using a constant backoff for each attempt. + if (!receivedFullTrace) { + logger( + 'waitForCompletedCloudTraceSpans', + null, + `Could not fetch a full trace from the server. Retrying in ${GET_TRACE_RETRY_BACKOFF_MILLIS}ms.` + ); + await new Promise(resolve => + setTimeout(resolve, GET_TRACE_RETRY_BACKOFF_MILLIS) + ); + } + } while (!receivedFullTrace && --remainingAttempts > 0); + return receivedFullTrace; + } + + async function waitForCompletedSpans( + numExpectedSpans: number + ): Promise { + let success = false; + if (testConfig.e2e) { + success = await waitForCompletedCloudTraceSpans(numExpectedSpans); + } else { + success = await waitForCompletedInMemorySpans(); + } + + if (success) { + buildSpanMaps(); + } + expect(spanIdToSpanData.size).to.equal( + numExpectedSpans, + `Could not find expected number of spans (${numExpectedSpans})` + ); + } + + function buildSpanMapsFromInMemorySpanExporter(): void { + const spans = inMemorySpanExporter.getFinishedSpans(); + spans.forEach(span => { + const id = span?.spanContext().spanId; + const parentId = span?.parentSpanId; + if (!parentId || span.name === SPAN_NAME_TEST_ROOT) { + rootSpanIds.push(id); + } else { + let children = spanIdToChildrenSpanIds.get(parentId); + // Initialize to empty array if it hasn't been seen before. + if (!children) { + children = []; + } + // Add the new child. + children.push(id); + spanIdToChildrenSpanIds.set(parentId, children); + } + spanIdToSpanData.set(id, SpanData.fromInMemorySpan(span)); + }); + } + + function buildSpanMapsFromCloudTraceInfo(): void { + const spans = cloudTraceInfo.spans; + spans?.forEach(span => { + const id = span.spanId; + const parentId = span.parentSpanId; + if (!parentId || span.name === SPAN_NAME_TEST_ROOT) { + rootSpanIds.push(id!); + } else { + let children = spanIdToChildrenSpanIds.get(parentId); + if (!children) { + children = []; + } + children.push(id!); + spanIdToChildrenSpanIds.set(parentId, children); + } + spanIdToSpanData.set( + id!, + SpanData.fromCloudTraceSpan(span, customSpanContext.traceId) + ); + }); + } + + function buildSpanMaps(): void { + if (testConfig.e2e) { + buildSpanMapsFromCloudTraceInfo(); + } else { + buildSpanMapsFromInMemorySpanExporter(); + } + logger( + 'buildSpanMaps', + null, + 'Built the following spans:', + rootSpanIds, + spanIdToSpanData, + spanIdToChildrenSpanIds + ); + } + + function getChildSpans(spanId: string): string[] | undefined { + return spanIdToChildrenSpanIds.get(spanId); + } + + // Returns the first span it can find with the given name, or null if it cannot find a span with the given name. + // If there are multiple spans with the same name, it'll return the first one. + function getSpanByName(spanName: string): SpanData | null { + for (const spanData of spanIdToSpanData.values()) { + if (spanData.name === spanName) { + return spanData; + } + } + return null; + } + + // Returns the array of spans that match the given span hierarchy names starting + // at the given root. Returns an empty list if it cannot find such hierarchy under + // the given root. + function dfsSpanHierarchy( + rootSpanId: string, + spanNamesHierarchy: string[] + ): SpanData[] { + // This function returns an empty list if it cannot find a full match. + const notAMatch: SpanData[] = []; + const rootSpan = spanIdToSpanData.get(rootSpanId); + + if (spanNamesHierarchy.length === 0 || !rootSpan) { + return notAMatch; + } + + if (spanIdToSpanData.get(rootSpanId)?.name !== spanNamesHierarchy[0]) { + // The root names didn't match. + return notAMatch; + } else { + // The root names matched. The new hierarchy to match can be obtained by + // popping the first element of `spanNamesHierarchy`. + const newSpanNamesHierarchy = spanNamesHierarchy.slice(1); + + const children = getChildSpans(rootSpanId); + if (!children || children.length === 0) { + if (newSpanNamesHierarchy.length === 0) { + // The root span doesn't have any more children, and there are no + // more span names to match. This is a successful match, and it is + // a base case for the recursion. + return [rootSpan]; + } else { + // The root span doesn't have any more children, but there are still + // more span names to match. + return notAMatch; + } + } else { + // See which (if any) of the child trees matches `newSpanNamesHierarchy`. + for (let childIndex = 0; childIndex < children.length; ++childIndex) { + const newRootSpanId = children[childIndex]; + const subtreeMatch = dfsSpanHierarchy( + newRootSpanId, + newSpanNamesHierarchy + ); + if (subtreeMatch.length > 0) { + // We found a full match in the child tree. + return [rootSpan].concat(subtreeMatch); + } + } + + // If none of the child trees matched `newSpanNamesHierarchy`, we were + // not able to find a full match anywhere in our child trees. + return notAMatch; + } + } + } + + // Asserts that the span hierarchy exists for the given span names. + // The hierarchy starts with the root span, followed by the child span, + // grandchild span, and so on. It also asserts that all the given spans belong + // to the same trace, and that Firestore-generated spans contain the expected + // Firestore attributes. + function expectSpanHierarchy(...spanNamesHierarchy: string[]): void { + expect(spanNamesHierarchy.length).to.be.greaterThan( + 0, + 'The expected spans hierarchy was empty' + ); + + let matchingSpanHierarchy: SpanData[] = []; + + // The Firestore operations that have been executed generate a number of + // spans. The span names, however, are not unique. For example, we could have: + // "DocRef.Get" (id:1) -> "grpc.GET" (id:2) -> "POST" (id:3) + // "DocRef.Set" (id:4) -> "grpc.SET" (id:5) -> "POST" (id:6) + // Note that span names are not unique (e.g. span 3 and span 6). + // Let's say we want to check if the following span hierarchy exists: + // [DocRef.Set -> grpc.SET -> POST] + // We start at each root span (span 1 and span 4 in this case), and check if + // the span hierarchy matches the given `spanNamesHierarchy`. + for (let i = 0; i < rootSpanIds.length; ++i) { + matchingSpanHierarchy = dfsSpanHierarchy( + rootSpanIds[i], + spanNamesHierarchy + ); + if (matchingSpanHierarchy.length > 0) break; + } + + expect(matchingSpanHierarchy.length).to.be.greaterThan( + 0, + `Was not able to find the following span hierarchy: ${spanNamesHierarchy}` + ); + logger( + 'expectSpanHierarchy', + null, + 'Found the following span hierarchy:', + matchingSpanHierarchy + ); + + for (let i = 0; i + 1 < matchingSpanHierarchy.length; ++i) { + const parentSpan = matchingSpanHierarchy[i]; + const childSpan = matchingSpanHierarchy[i + 1]; + expect(childSpan.traceId).to.equal( + parentSpan.traceId, + `'${childSpan.name}' and '${parentSpan.name}' spans do not belong to the same trace` + ); + + // The Cloud Trace API does not return span attributes and events. + if (!testConfig.e2e) { + const settingsAttributes = getSettingsAttributes(); + for (const attributesKey in settingsAttributes) { + if ( + attributesKey.endsWith('.project_id') && + i + 1 !== matchingSpanHierarchy.length + ) { + // Project ID is not set on the Firestore object until _after_ the first + // operation is done. Therefore, the spans that are created _before_ the + // first operation do not contain a project ID. So, we'll just compare + // this attribute on the leaf spans. + } else { + expect(childSpan.attributes[attributesKey]).to.be.equal( + settingsAttributes[attributesKey] + ); + } + } + } + } + } + + // Ensures that the given span exists and has exactly all the given attributes. + function expectSpanHasAttributes( + spanName: string, + attributes: Attributes + ): void { + // The Cloud Trace API does not return span attributes and events. + if (testConfig.e2e) { + return; + } + + // Expect that the span exists first. + const span = getSpanByName(spanName); + expect(span).to.not.be.null; + + // Assert that the expected attributes are present in the span attributes. + // Note that the span attributes may be a superset of the attributes passed + // to this function. + for (const attributesKey in attributes) { + expect(span!.attributes[attributesKey]).to.be.equal( + attributes[attributesKey] + ); + } + } + + describe(IN_MEMORY_TEST_SUITE_TITLE, () => { + describe(NON_GLOBAL_OTEL_TEST_SUITE_TITLE, () => { + describe(GRPC_TEST_SUITE_TITLE, () => { + beforeEach(function () { + beforeEachTest(this.currentTest!); + }); + runTestCases(); + afterEach(async () => afterEachTest()); + }); + describe(REST_TEST_SUITE_TITLE, () => { + beforeEach(function () { + beforeEachTest(this.currentTest!); + }); + runTestCases(); + afterEach(async () => afterEachTest()); + }); + }); + describe(GLOBAL_OTEL_TEST_SUITE_TITLE, () => { + describe(GRPC_TEST_SUITE_TITLE, () => { + beforeEach(function () { + beforeEachTest(this.currentTest!); + }); + runTestCases(); + afterEach(async () => afterEachTest()); + }); + describe(REST_TEST_SUITE_TITLE, () => { + beforeEach(function () { + beforeEachTest(this.currentTest!); + }); + runTestCases(); + afterEach(async () => afterEachTest()); + }); + }); + }); + + describe(E2E_TEST_SUITE_TITLE, () => { + describe(NON_GLOBAL_OTEL_TEST_SUITE_TITLE, () => { + describe(GRPC_TEST_SUITE_TITLE, () => { + beforeEach(function () { + beforeEachTest(this.currentTest!); + }); + runTestCases(); + afterEach(async () => afterEachTest()); + }); + describe(REST_TEST_SUITE_TITLE, () => { + beforeEach(function () { + beforeEachTest(this.currentTest!); + }); + runTestCases(); + afterEach(async () => afterEachTest()); + }); + }); + describe(GLOBAL_OTEL_TEST_SUITE_TITLE, () => { + describe(GRPC_TEST_SUITE_TITLE, () => { + beforeEach(function () { + beforeEachTest(this.currentTest!); + }); + runTestCases(); + afterEach(async () => afterEachTest()); + }); + describe(REST_TEST_SUITE_TITLE, () => { + beforeEach(function () { + beforeEachTest(this.currentTest!); + }); + runTestCases(); + afterEach(async () => afterEachTest()); + }); + }); + }); + + function runTestCases() { + it('document reference get()', async () => { + await runFirestoreOperationInRootSpan(() => + firestore.collection('foo').doc('bar').get() + ); + await waitForCompletedSpans(3); + expectSpanHierarchy( + SPAN_NAME_TEST_ROOT, + SPAN_NAME_DOC_REF_GET, + SPAN_NAME_BATCH_GET_DOCUMENTS + ); + }); + + it('document reference create()', async () => { + await runFirestoreOperationInRootSpan(() => + firestore.collection('foo').doc().create({}) + ); + await waitForCompletedSpans(3); + expectSpanHierarchy( + SPAN_NAME_TEST_ROOT, + SPAN_NAME_DOC_REF_CREATE, + SPAN_NAME_BATCH_COMMIT + ); + }); + + it('document reference delete()', async () => { + await runFirestoreOperationInRootSpan(() => + firestore.collection('foo').doc('bar').delete() + ); + await waitForCompletedSpans(3); + expectSpanHierarchy( + SPAN_NAME_TEST_ROOT, + SPAN_NAME_DOC_REF_DELETE, + SPAN_NAME_BATCH_COMMIT + ); + }); + + it('document reference set()', async () => { + await runFirestoreOperationInRootSpan(() => + firestore.collection('foo').doc('bar').set({foo: 'bar'}) + ); + await waitForCompletedSpans(3); + expectSpanHierarchy( + SPAN_NAME_TEST_ROOT, + SPAN_NAME_DOC_REF_SET, + SPAN_NAME_BATCH_COMMIT + ); + }); + + it('document reference update()', async () => { + await runFirestoreOperationInRootSpan(() => + firestore.collection('foo').doc('bar').update('foo', 'bar2') + ); + await waitForCompletedSpans(3); + expectSpanHierarchy( + SPAN_NAME_TEST_ROOT, + SPAN_NAME_DOC_REF_UPDATE, + SPAN_NAME_BATCH_COMMIT + ); + }); + + it('document reference list collections', async () => { + await runFirestoreOperationInRootSpan(() => + firestore.collection('foo').doc('bar').listCollections() + ); + await waitForCompletedSpans(2); + expectSpanHierarchy( + SPAN_NAME_TEST_ROOT, + SPAN_NAME_DOC_REF_LIST_COLLECTIONS + ); + }); + + it('aggregate query get()', async () => { + await runFirestoreOperationInRootSpan(() => + firestore.collection('foo').count().get() + ); + await waitForCompletedSpans(2); + expectSpanHierarchy(SPAN_NAME_TEST_ROOT, SPAN_NAME_AGGREGATION_QUERY_GET); + }); + + it('collection reference add()', async () => { + await runFirestoreOperationInRootSpan(() => + firestore.collection('foo').add({foo: 'bar'}) + ); + await waitForCompletedSpans(4); + expectSpanHierarchy( + SPAN_NAME_TEST_ROOT, + SPAN_NAME_COL_REF_ADD, + SPAN_NAME_DOC_REF_CREATE, + SPAN_NAME_BATCH_COMMIT + ); + }); + + it('collection reference list documents', async () => { + await runFirestoreOperationInRootSpan(() => + firestore.collection('foo').listDocuments() + ); + await waitForCompletedSpans(2); + expectSpanHierarchy( + SPAN_NAME_TEST_ROOT, + SPAN_NAME_COL_REF_LIST_DOCUMENTS + ); + }); + + it('query get()', async () => { + await runFirestoreOperationInRootSpan(() => + firestore.collection('foo').where('foo', '==', 'bar').limit(1).get() + ); + await waitForCompletedSpans(2); + expectSpanHierarchy(SPAN_NAME_TEST_ROOT, SPAN_NAME_QUERY_GET); + }); + + it('firestore getAll()', async () => { + const docRef1 = firestore.collection('foo').doc('1'); + const docRef2 = firestore.collection('foo').doc('2'); + await runFirestoreOperationInRootSpan(() => + firestore.getAll(docRef1, docRef2) + ); + await waitForCompletedSpans(2); + expectSpanHierarchy(SPAN_NAME_TEST_ROOT, SPAN_NAME_BATCH_GET_DOCUMENTS); + }); + + it('transaction', async () => { + const docRef1 = firestore.collection('foo').doc('bar'); + const docRef2 = firestore.collection('foo').doc('bar'); + + await runFirestoreOperationInRootSpan(async () => { + return firestore.runTransaction(async transaction => { + await transaction.get(docRef1); + await transaction.getAll(docRef1, docRef2); + await transaction.get(firestore.collection('foo').limit(1)); + await transaction.get(firestore.collection('nonexistent').count()); + transaction.set(firestore.collection('foo').doc(), {foo: 'bar'}); + }); + }); + + await waitForCompletedSpans(7); + expectSpanHierarchy( + SPAN_NAME_TEST_ROOT, + SPAN_NAME_TRANSACTION_RUN, + SPAN_NAME_TRANSACTION_GET_DOCUMENT + ); + expectSpanHierarchy( + SPAN_NAME_TEST_ROOT, + SPAN_NAME_TRANSACTION_RUN, + SPAN_NAME_TRANSACTION_GET_DOCUMENTS + ); + expectSpanHierarchy( + SPAN_NAME_TEST_ROOT, + SPAN_NAME_TRANSACTION_RUN, + SPAN_NAME_TRANSACTION_GET_QUERY + ); + expectSpanHierarchy( + SPAN_NAME_TEST_ROOT, + SPAN_NAME_TRANSACTION_RUN, + SPAN_NAME_TRANSACTION_GET_AGGREGATION_QUERY + ); + expectSpanHierarchy( + SPAN_NAME_TEST_ROOT, + SPAN_NAME_TRANSACTION_RUN, + SPAN_NAME_TRANSACTION_COMMIT + ); + }); + + it('batch', async () => { + const writeBatch = firestore.batch(); + const documentRef = firestore.doc('col/doc'); + writeBatch.set(documentRef, {foo: 'bar'}); + + await runFirestoreOperationInRootSpan(() => writeBatch.commit()); + await waitForCompletedSpans(2); + expectSpanHierarchy(SPAN_NAME_TEST_ROOT, SPAN_NAME_BATCH_COMMIT); + }); + + it('partition query', async () => { + await runFirestoreOperationInRootSpan(async () => { + const query = firestore.collectionGroup('foo'); + let numPartitions = 0; + for await (const partition of query.getPartitions(3)) { + numPartitions++; + } + return numPartitions; + }); + + await waitForCompletedSpans(2); + expectSpanHierarchy(SPAN_NAME_TEST_ROOT, SPAN_NAME_PARTITION_QUERY); + }); + + it('bulk writer', async () => { + await runFirestoreOperationInRootSpan(async () => { + const bulkWriter = firestore.bulkWriter(); + // No need to await the set operations as 'close()' will commit all writes before closing. + bulkWriter.set(firestore.collection('foo').doc(), {foo: 1}); + bulkWriter.set(firestore.collection('foo').doc(), {foo: 2}); + bulkWriter.set(firestore.collection('foo').doc(), {foo: 3}); + bulkWriter.set(firestore.collection('foo').doc(), {foo: 4}); + bulkWriter.set(firestore.collection('foo').doc(), {foo: 5}); + await bulkWriter.close(); + }); + + await waitForCompletedSpans(2); + expectSpanHierarchy(SPAN_NAME_TEST_ROOT, SPAN_NAME_BULK_WRITER_COMMIT); + expectSpanHasAttributes(SPAN_NAME_BULK_WRITER_COMMIT, { + [ATTRIBUTE_KEY_DOC_COUNT]: 5, + }); + }); + } +}); diff --git a/dev/test/gapic_firestore_admin_v1.ts b/dev/test/gapic_firestore_admin_v1.ts index 6d577b987..6f19b971c 100644 --- a/dev/test/gapic_firestore_admin_v1.ts +++ b/dev/test/gapic_firestore_admin_v1.ts @@ -2803,6 +2803,200 @@ describe('v1.FirestoreAdminClient', () => { }); }); + describe('bulkDeleteDocuments', () => { + it('invokes bulkDeleteDocuments without error', async () => { + const client = new firestoreadminModule.FirestoreAdminClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + client.initialize(); + const request = generateSampleMessage( + new protos.google.firestore.admin.v1.BulkDeleteDocumentsRequest() + ); + const defaultValue1 = getTypeDefaultValue( + '.google.firestore.admin.v1.BulkDeleteDocumentsRequest', + ['name'] + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1}`; + const expectedResponse = generateSampleMessage( + new protos.google.longrunning.Operation() + ); + client.innerApiCalls.bulkDeleteDocuments = + stubLongRunningCall(expectedResponse); + const [operation] = await client.bulkDeleteDocuments(request); + const [response] = await operation.promise(); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.bulkDeleteDocuments as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.bulkDeleteDocuments as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes bulkDeleteDocuments without error using callback', async () => { + const client = new firestoreadminModule.FirestoreAdminClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + client.initialize(); + const request = generateSampleMessage( + new protos.google.firestore.admin.v1.BulkDeleteDocumentsRequest() + ); + const defaultValue1 = getTypeDefaultValue( + '.google.firestore.admin.v1.BulkDeleteDocumentsRequest', + ['name'] + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1}`; + const expectedResponse = generateSampleMessage( + new protos.google.longrunning.Operation() + ); + client.innerApiCalls.bulkDeleteDocuments = + stubLongRunningCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.bulkDeleteDocuments( + request, + ( + err?: Error | null, + result?: LROperation< + protos.google.firestore.admin.v1.IBulkDeleteDocumentsResponse, + protos.google.firestore.admin.v1.IBulkDeleteDocumentsMetadata + > | null + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + } + ); + }); + const operation = (await promise) as LROperation< + protos.google.firestore.admin.v1.IBulkDeleteDocumentsResponse, + protos.google.firestore.admin.v1.IBulkDeleteDocumentsMetadata + >; + const [response] = await operation.promise(); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.bulkDeleteDocuments as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.bulkDeleteDocuments as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes bulkDeleteDocuments with call error', async () => { + const client = new firestoreadminModule.FirestoreAdminClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + client.initialize(); + const request = generateSampleMessage( + new protos.google.firestore.admin.v1.BulkDeleteDocumentsRequest() + ); + const defaultValue1 = getTypeDefaultValue( + '.google.firestore.admin.v1.BulkDeleteDocumentsRequest', + ['name'] + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1}`; + const expectedError = new Error('expected'); + client.innerApiCalls.bulkDeleteDocuments = stubLongRunningCall( + undefined, + expectedError + ); + await assert.rejects(client.bulkDeleteDocuments(request), expectedError); + const actualRequest = ( + client.innerApiCalls.bulkDeleteDocuments as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.bulkDeleteDocuments as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes bulkDeleteDocuments with LRO error', async () => { + const client = new firestoreadminModule.FirestoreAdminClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + client.initialize(); + const request = generateSampleMessage( + new protos.google.firestore.admin.v1.BulkDeleteDocumentsRequest() + ); + const defaultValue1 = getTypeDefaultValue( + '.google.firestore.admin.v1.BulkDeleteDocumentsRequest', + ['name'] + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1}`; + const expectedError = new Error('expected'); + client.innerApiCalls.bulkDeleteDocuments = stubLongRunningCall( + undefined, + undefined, + expectedError + ); + const [operation] = await client.bulkDeleteDocuments(request); + await assert.rejects(operation.promise(), expectedError); + const actualRequest = ( + client.innerApiCalls.bulkDeleteDocuments as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.bulkDeleteDocuments as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes checkBulkDeleteDocumentsProgress without error', async () => { + const client = new firestoreadminModule.FirestoreAdminClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + client.initialize(); + const expectedResponse = generateSampleMessage( + new operationsProtos.google.longrunning.Operation() + ); + expectedResponse.name = 'test'; + expectedResponse.response = {type_url: 'url', value: Buffer.from('')}; + expectedResponse.metadata = {type_url: 'url', value: Buffer.from('')}; + + client.operationsClient.getOperation = stubSimpleCall(expectedResponse); + const decodedOperation = await client.checkBulkDeleteDocumentsProgress( + expectedResponse.name + ); + assert.deepStrictEqual(decodedOperation.name, expectedResponse.name); + assert(decodedOperation.metadata); + assert((client.operationsClient.getOperation as SinonStub).getCall(0)); + }); + + it('invokes checkBulkDeleteDocumentsProgress with error', async () => { + const client = new firestoreadminModule.FirestoreAdminClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + client.initialize(); + const expectedError = new Error('expected'); + + client.operationsClient.getOperation = stubSimpleCall( + undefined, + expectedError + ); + await assert.rejects( + client.checkBulkDeleteDocumentsProgress(''), + expectedError + ); + assert((client.operationsClient.getOperation as SinonStub).getCall(0)); + }); + }); + describe('createDatabase', () => { it('invokes createDatabase without error', async () => { const client = new firestoreadminModule.FirestoreAdminClient({ @@ -3745,9 +3939,9 @@ describe('v1.FirestoreAdminClient', () => { assert( (client.descriptors.page.listIndexes.createStream as SinonStub) .getCall(0) - .args[2].otherArgs.headers['x-goog-request-params'].includes( - expectedHeaderRequestParams - ) + .args[2].otherArgs.headers[ + 'x-goog-request-params' + ].includes(expectedHeaderRequestParams) ); }); @@ -3796,9 +3990,9 @@ describe('v1.FirestoreAdminClient', () => { assert( (client.descriptors.page.listIndexes.createStream as SinonStub) .getCall(0) - .args[2].otherArgs.headers['x-goog-request-params'].includes( - expectedHeaderRequestParams - ) + .args[2].otherArgs.headers[ + 'x-goog-request-params' + ].includes(expectedHeaderRequestParams) ); }); @@ -3839,9 +4033,9 @@ describe('v1.FirestoreAdminClient', () => { assert( (client.descriptors.page.listIndexes.asyncIterate as SinonStub) .getCall(0) - .args[2].otherArgs.headers['x-goog-request-params'].includes( - expectedHeaderRequestParams - ) + .args[2].otherArgs.headers[ + 'x-goog-request-params' + ].includes(expectedHeaderRequestParams) ); }); @@ -3881,9 +4075,9 @@ describe('v1.FirestoreAdminClient', () => { assert( (client.descriptors.page.listIndexes.asyncIterate as SinonStub) .getCall(0) - .args[2].otherArgs.headers['x-goog-request-params'].includes( - expectedHeaderRequestParams - ) + .args[2].otherArgs.headers[ + 'x-goog-request-params' + ].includes(expectedHeaderRequestParams) ); }); }); @@ -4050,9 +4244,9 @@ describe('v1.FirestoreAdminClient', () => { assert( (client.descriptors.page.listFields.createStream as SinonStub) .getCall(0) - .args[2].otherArgs.headers['x-goog-request-params'].includes( - expectedHeaderRequestParams - ) + .args[2].otherArgs.headers[ + 'x-goog-request-params' + ].includes(expectedHeaderRequestParams) ); }); @@ -4101,9 +4295,9 @@ describe('v1.FirestoreAdminClient', () => { assert( (client.descriptors.page.listFields.createStream as SinonStub) .getCall(0) - .args[2].otherArgs.headers['x-goog-request-params'].includes( - expectedHeaderRequestParams - ) + .args[2].otherArgs.headers[ + 'x-goog-request-params' + ].includes(expectedHeaderRequestParams) ); }); @@ -4144,9 +4338,9 @@ describe('v1.FirestoreAdminClient', () => { assert( (client.descriptors.page.listFields.asyncIterate as SinonStub) .getCall(0) - .args[2].otherArgs.headers['x-goog-request-params'].includes( - expectedHeaderRequestParams - ) + .args[2].otherArgs.headers[ + 'x-goog-request-params' + ].includes(expectedHeaderRequestParams) ); }); @@ -4186,9 +4380,9 @@ describe('v1.FirestoreAdminClient', () => { assert( (client.descriptors.page.listFields.asyncIterate as SinonStub) .getCall(0) - .args[2].otherArgs.headers['x-goog-request-params'].includes( - expectedHeaderRequestParams - ) + .args[2].otherArgs.headers[ + 'x-goog-request-params' + ].includes(expectedHeaderRequestParams) ); }); }); diff --git a/dev/test/gapic_firestore_v1.ts b/dev/test/gapic_firestore_v1.ts index df6a2f4dc..006f11f32 100644 --- a/dev/test/gapic_firestore_v1.ts +++ b/dev/test/gapic_firestore_v1.ts @@ -2254,9 +2254,9 @@ describe('v1.FirestoreClient', () => { assert( (client.descriptors.page.listDocuments.createStream as SinonStub) .getCall(0) - .args[2].otherArgs.headers['x-goog-request-params'].includes( - expectedHeaderRequestParams - ) + .args[2].otherArgs.headers[ + 'x-goog-request-params' + ].includes(expectedHeaderRequestParams) ); }); @@ -2305,9 +2305,9 @@ describe('v1.FirestoreClient', () => { assert( (client.descriptors.page.listDocuments.createStream as SinonStub) .getCall(0) - .args[2].otherArgs.headers['x-goog-request-params'].includes( - expectedHeaderRequestParams - ) + .args[2].otherArgs.headers[ + 'x-goog-request-params' + ].includes(expectedHeaderRequestParams) ); }); @@ -2353,9 +2353,9 @@ describe('v1.FirestoreClient', () => { assert( (client.descriptors.page.listDocuments.asyncIterate as SinonStub) .getCall(0) - .args[2].otherArgs.headers['x-goog-request-params'].includes( - expectedHeaderRequestParams - ) + .args[2].otherArgs.headers[ + 'x-goog-request-params' + ].includes(expectedHeaderRequestParams) ); }); @@ -2398,9 +2398,9 @@ describe('v1.FirestoreClient', () => { assert( (client.descriptors.page.listDocuments.asyncIterate as SinonStub) .getCall(0) - .args[2].otherArgs.headers['x-goog-request-params'].includes( - expectedHeaderRequestParams - ) + .args[2].otherArgs.headers[ + 'x-goog-request-params' + ].includes(expectedHeaderRequestParams) ); }); }); @@ -2564,9 +2564,9 @@ describe('v1.FirestoreClient', () => { assert( (client.descriptors.page.partitionQuery.createStream as SinonStub) .getCall(0) - .args[2].otherArgs.headers['x-goog-request-params'].includes( - expectedHeaderRequestParams - ) + .args[2].otherArgs.headers[ + 'x-goog-request-params' + ].includes(expectedHeaderRequestParams) ); }); @@ -2610,9 +2610,9 @@ describe('v1.FirestoreClient', () => { assert( (client.descriptors.page.partitionQuery.createStream as SinonStub) .getCall(0) - .args[2].otherArgs.headers['x-goog-request-params'].includes( - expectedHeaderRequestParams - ) + .args[2].otherArgs.headers[ + 'x-goog-request-params' + ].includes(expectedHeaderRequestParams) ); }); @@ -2653,9 +2653,9 @@ describe('v1.FirestoreClient', () => { assert( (client.descriptors.page.partitionQuery.asyncIterate as SinonStub) .getCall(0) - .args[2].otherArgs.headers['x-goog-request-params'].includes( - expectedHeaderRequestParams - ) + .args[2].otherArgs.headers[ + 'x-goog-request-params' + ].includes(expectedHeaderRequestParams) ); }); @@ -2693,9 +2693,9 @@ describe('v1.FirestoreClient', () => { assert( (client.descriptors.page.partitionQuery.asyncIterate as SinonStub) .getCall(0) - .args[2].otherArgs.headers['x-goog-request-params'].includes( - expectedHeaderRequestParams - ) + .args[2].otherArgs.headers[ + 'x-goog-request-params' + ].includes(expectedHeaderRequestParams) ); }); }); @@ -2844,9 +2844,9 @@ describe('v1.FirestoreClient', () => { assert( (client.descriptors.page.listCollectionIds.createStream as SinonStub) .getCall(0) - .args[2].otherArgs.headers['x-goog-request-params'].includes( - expectedHeaderRequestParams - ) + .args[2].otherArgs.headers[ + 'x-goog-request-params' + ].includes(expectedHeaderRequestParams) ); }); @@ -2890,9 +2890,9 @@ describe('v1.FirestoreClient', () => { assert( (client.descriptors.page.listCollectionIds.createStream as SinonStub) .getCall(0) - .args[2].otherArgs.headers['x-goog-request-params'].includes( - expectedHeaderRequestParams - ) + .args[2].otherArgs.headers[ + 'x-goog-request-params' + ].includes(expectedHeaderRequestParams) ); }); @@ -2929,9 +2929,9 @@ describe('v1.FirestoreClient', () => { assert( (client.descriptors.page.listCollectionIds.asyncIterate as SinonStub) .getCall(0) - .args[2].otherArgs.headers['x-goog-request-params'].includes( - expectedHeaderRequestParams - ) + .args[2].otherArgs.headers[ + 'x-goog-request-params' + ].includes(expectedHeaderRequestParams) ); }); @@ -2969,9 +2969,9 @@ describe('v1.FirestoreClient', () => { assert( (client.descriptors.page.listCollectionIds.asyncIterate as SinonStub) .getCall(0) - .args[2].otherArgs.headers['x-goog-request-params'].includes( - expectedHeaderRequestParams - ) + .args[2].otherArgs.headers[ + 'x-goog-request-params' + ].includes(expectedHeaderRequestParams) ); }); }); diff --git a/dev/test/gapic_firestore_v1beta1.ts b/dev/test/gapic_firestore_v1beta1.ts index e6431944f..5e168c725 100644 --- a/dev/test/gapic_firestore_v1beta1.ts +++ b/dev/test/gapic_firestore_v1beta1.ts @@ -2088,9 +2088,9 @@ describe('v1beta1.FirestoreClient', () => { assert( (client.descriptors.page.listDocuments.createStream as SinonStub) .getCall(0) - .args[2].otherArgs.headers['x-goog-request-params'].includes( - expectedHeaderRequestParams - ) + .args[2].otherArgs.headers[ + 'x-goog-request-params' + ].includes(expectedHeaderRequestParams) ); }); @@ -2142,9 +2142,9 @@ describe('v1beta1.FirestoreClient', () => { assert( (client.descriptors.page.listDocuments.createStream as SinonStub) .getCall(0) - .args[2].otherArgs.headers['x-goog-request-params'].includes( - expectedHeaderRequestParams - ) + .args[2].otherArgs.headers[ + 'x-goog-request-params' + ].includes(expectedHeaderRequestParams) ); }); @@ -2190,9 +2190,9 @@ describe('v1beta1.FirestoreClient', () => { assert( (client.descriptors.page.listDocuments.asyncIterate as SinonStub) .getCall(0) - .args[2].otherArgs.headers['x-goog-request-params'].includes( - expectedHeaderRequestParams - ) + .args[2].otherArgs.headers[ + 'x-goog-request-params' + ].includes(expectedHeaderRequestParams) ); }); @@ -2235,9 +2235,9 @@ describe('v1beta1.FirestoreClient', () => { assert( (client.descriptors.page.listDocuments.asyncIterate as SinonStub) .getCall(0) - .args[2].otherArgs.headers['x-goog-request-params'].includes( - expectedHeaderRequestParams - ) + .args[2].otherArgs.headers[ + 'x-goog-request-params' + ].includes(expectedHeaderRequestParams) ); }); }); @@ -2404,9 +2404,9 @@ describe('v1beta1.FirestoreClient', () => { assert( (client.descriptors.page.partitionQuery.createStream as SinonStub) .getCall(0) - .args[2].otherArgs.headers['x-goog-request-params'].includes( - expectedHeaderRequestParams - ) + .args[2].otherArgs.headers[ + 'x-goog-request-params' + ].includes(expectedHeaderRequestParams) ); }); @@ -2453,9 +2453,9 @@ describe('v1beta1.FirestoreClient', () => { assert( (client.descriptors.page.partitionQuery.createStream as SinonStub) .getCall(0) - .args[2].otherArgs.headers['x-goog-request-params'].includes( - expectedHeaderRequestParams - ) + .args[2].otherArgs.headers[ + 'x-goog-request-params' + ].includes(expectedHeaderRequestParams) ); }); @@ -2496,9 +2496,9 @@ describe('v1beta1.FirestoreClient', () => { assert( (client.descriptors.page.partitionQuery.asyncIterate as SinonStub) .getCall(0) - .args[2].otherArgs.headers['x-goog-request-params'].includes( - expectedHeaderRequestParams - ) + .args[2].otherArgs.headers[ + 'x-goog-request-params' + ].includes(expectedHeaderRequestParams) ); }); @@ -2536,9 +2536,9 @@ describe('v1beta1.FirestoreClient', () => { assert( (client.descriptors.page.partitionQuery.asyncIterate as SinonStub) .getCall(0) - .args[2].otherArgs.headers['x-goog-request-params'].includes( - expectedHeaderRequestParams - ) + .args[2].otherArgs.headers[ + 'x-goog-request-params' + ].includes(expectedHeaderRequestParams) ); }); }); @@ -2687,9 +2687,9 @@ describe('v1beta1.FirestoreClient', () => { assert( (client.descriptors.page.listCollectionIds.createStream as SinonStub) .getCall(0) - .args[2].otherArgs.headers['x-goog-request-params'].includes( - expectedHeaderRequestParams - ) + .args[2].otherArgs.headers[ + 'x-goog-request-params' + ].includes(expectedHeaderRequestParams) ); }); @@ -2733,9 +2733,9 @@ describe('v1beta1.FirestoreClient', () => { assert( (client.descriptors.page.listCollectionIds.createStream as SinonStub) .getCall(0) - .args[2].otherArgs.headers['x-goog-request-params'].includes( - expectedHeaderRequestParams - ) + .args[2].otherArgs.headers[ + 'x-goog-request-params' + ].includes(expectedHeaderRequestParams) ); }); @@ -2772,9 +2772,9 @@ describe('v1beta1.FirestoreClient', () => { assert( (client.descriptors.page.listCollectionIds.asyncIterate as SinonStub) .getCall(0) - .args[2].otherArgs.headers['x-goog-request-params'].includes( - expectedHeaderRequestParams - ) + .args[2].otherArgs.headers[ + 'x-goog-request-params' + ].includes(expectedHeaderRequestParams) ); }); @@ -2812,9 +2812,9 @@ describe('v1beta1.FirestoreClient', () => { assert( (client.descriptors.page.listCollectionIds.asyncIterate as SinonStub) .getCall(0) - .args[2].otherArgs.headers['x-goog-request-params'].includes( - expectedHeaderRequestParams - ) + .args[2].otherArgs.headers[ + 'x-goog-request-params' + ].includes(expectedHeaderRequestParams) ); }); }); diff --git a/dev/test/query.ts b/dev/test/query.ts index a5eee6841..a45278208 100644 --- a/dev/test/query.ts +++ b/dev/test/query.ts @@ -18,6 +18,7 @@ import {describe, it, beforeEach, afterEach} from 'mocha'; import {expect, use} from 'chai'; import * as chaiAsPromised from 'chai-as-promised'; import * as extend from 'extend'; +import * as assert from 'assert'; import {firestore, google} from '../protos/firestore_v1_proto_api'; import { @@ -55,7 +56,6 @@ import {GoogleError, Status} from 'google-gax'; import api = google.firestore.v1; import protobuf = google.protobuf; import {Filter} from '../src/filter'; -import {Deferred} from '../src/util'; const PROJECT_ID = 'test-project'; const DATABASE_ROOT = `projects/${PROJECT_ID}/databases/(default)`; @@ -3577,70 +3577,136 @@ describe('query resumption', () => { setTimeoutHandler(setTimeout); }); - // Prevent regression of - // https://github.com/googleapis/nodejs-firestore/issues/1790 - it('results should not be double produced on retryable error with back pressure', async () => { - // Generate the IDs of the documents that will match the query. - const documentIds = Array.from(new Array(500), (_, index) => `doc${index}`); + // Return `numDocs` document responses, followed by an error response. + function* getDocResponsesFollowedByError( + documentIds: string[], + numDocs: number, + error: Error, + startAtEnd?: boolean + ): Generator { + assert(numDocs <= documentIds.length); + const sliced = startAtEnd + ? documentIds.slice(-1 * numDocs) + : documentIds.slice(0, numDocs); + let runQueryResponses = sliced.map(documentId => result(documentId)); + if (startAtEnd) { + runQueryResponses = runQueryResponses.reverse(); + } + for (const runQueryResponse of runQueryResponses) { + yield runQueryResponse; + } + yield error; + } - // Finds the index in `documentIds` of the document referred to in the - // "startAt" of the given request. - function getStartAtDocumentIndex( - request: api.IRunQueryRequest - ): number | null { - const startAt = request.structuredQuery?.startAt; - const startAtValue = startAt?.values?.[0]?.referenceValue; - const startAtBefore = startAt?.before; - if (typeof startAtValue !== 'string') { - return null; + // Returns the documents from the given `documentIds` starting at the cursor + // determined by `startAt` (or `endAt`) in the request. It will continue to + // return documents until either the request `limit` is reached or `numDocs` + // (if provided) is reached. If an `error` is provided, it will return the + // given error after the docs are returned. + function* getDocResponsesForRequest( + request: api.IRunQueryRequest, + documentIds: string[], + options?: { + numDocs?: number; + error?: Error; + } + ): Generator { + let begin: number | null | undefined; + let end: number | null | undefined; + let reverseOrder: boolean; + if (request.structuredQuery?.startAt) { + begin = getStartAtDocumentIndex(request, documentIds); + if (begin === null) { + throw new Error('the request should specify a valid startAt'); + } + if (request.structuredQuery.limit?.value) { + end = begin + request.structuredQuery.limit.value; + } else { + end = undefined; } - const docId = startAtValue.split('/').pop()!; - const docIdIndex = documentIds.indexOf(docId); - if (docIdIndex < 0) { - return null; + reverseOrder = false; + } else if (request.structuredQuery?.endAt) { + end = getEndAtDocumentIndex(request, documentIds); + if (end === null) { + throw new Error('the request should specify a valid endAt'); } - return startAtBefore ? docIdIndex : docIdIndex + 1; + if (request.structuredQuery.limit?.value) { + begin = end - request.structuredQuery.limit.value; + } else { + begin = undefined; + } + reverseOrder = true; + } else { + throw new Error('the request does not specify a valid startAt or endAt'); } - const RETRYABLE_ERROR_DOMAIN = 'RETRYABLE_ERROR_DOMAIN'; + const runQueryResponses = documentIds + .slice(begin, end) + .map(documentId => result(documentId)); + + let numDocsReturned = 0; + for (const runQueryResponse of reverseOrder + ? runQueryResponses.reverse() + : runQueryResponses) { + // If `numDocs` is provided, stop iterating when it is reached. + if (options?.numDocs && numDocsReturned === options.numDocs) { + break; + } + numDocsReturned++; + yield runQueryResponse; + } - // A mock replacement for Query._isPermanentRpcError which (a) resolves - // a promise once invoked and (b) treats a specific error "domain" as - // non-retryable. - function mockIsPermanentRpcError(err: GoogleError): boolean { - mockIsPermanentRpcError.invoked.resolve(true); - return err?.domain !== RETRYABLE_ERROR_DOMAIN; + // If `error` is provided, emit it after all the docs. + if (options?.error) { + yield options.error; } - mockIsPermanentRpcError.invoked = new Deferred(); - - // Return the first half of the documents, followed by a retryable error. - function* getRequest1Responses(): Generator { - const runQueryResponses = documentIds - .slice(0, documentIds.length / 2) - .map(documentId => result(documentId)); - for (const runQueryResponse of runQueryResponses) { - yield runQueryResponse; - } - const retryableError = new GoogleError('simulated retryable error'); - retryableError.domain = RETRYABLE_ERROR_DOMAIN; - yield retryableError; + } + + // Finds the index in `documentIds` of the document referred to in the + // "startAt" of the given request. Returns `null` if it cannot find one. + function getStartAtDocumentIndex( + request: api.IRunQueryRequest, + documentIds: string[] + ): number | null { + const startAt = request.structuredQuery?.startAt; + const startAtValue = startAt?.values?.[0]?.referenceValue; + const startAtBefore = startAt?.before; + if (typeof startAtValue !== 'string') { + return null; + } + const docId = startAtValue.split('/').pop()!; + const docIdIndex = documentIds.indexOf(docId); + if (docIdIndex < 0) { + return null; } + return startAtBefore ? docIdIndex : docIdIndex + 1; + } - // Return the remaining documents. - function* getRequest2Responses( - request: api.IRunQueryRequest - ): Generator { - const startAtDocumentIndex = getStartAtDocumentIndex(request); - if (startAtDocumentIndex === null) { - throw new Error('request #2 should specify a valid startAt'); - } - const runQueryResponses = documentIds - .slice(startAtDocumentIndex) - .map(documentId => result(documentId)); - for (const runQueryResponse of runQueryResponses) { - yield runQueryResponse; - } + // Finds the index in `documentIds` of the document referred to in the + // "endAt" of the given request. Returns `null` if it cannot find one. + function getEndAtDocumentIndex( + request: api.IRunQueryRequest, + documentIds: string[] + ): number | null { + const endAt = request.structuredQuery?.endAt; + const endAtValue = endAt?.values?.[0]?.referenceValue; + const endAtBefore = endAt?.before; + if (typeof endAtValue !== 'string') { + return null; + } + const docId = endAtValue.split('/').pop()!; + const docIdIndex = documentIds.indexOf(docId); + if (docIdIndex < 0) { + return null; } + return endAtBefore ? docIdIndex : docIdIndex - 1; + } + + // Prevent regression of + // https://github.com/googleapis/nodejs-firestore/issues/1790 + it('results should not be double produced on retryable error with back pressure', async () => { + // Generate the IDs of the documents that will match the query. + const documentIds = Array.from(new Array(500), (_, index) => `doc${index}`); // Set up the mocked responses from Watch. let requestNum = 0; @@ -3649,27 +3715,30 @@ describe('query resumption', () => { requestNum++; switch (requestNum) { case 1: - return stream(...getRequest1Responses()); + // Return the first half of the documents, followed by a retryable error. + return stream( + ...getDocResponsesFollowedByError( + documentIds, + documentIds.length / 2, + new GoogleError('simulated retryable error') + ) + ); case 2: - return stream(...getRequest2Responses(request!)); + // Return the remaining documents. + return stream(...getDocResponsesForRequest(request!, documentIds)); default: throw new Error(`should never get here (requestNum=${requestNum})`); } }, }; - // Create an async iterator to get the result set but DO NOT iterate over - // it immediately. Instead, allow the responses to pile up and fill the - // buffers. Once isPermanentError() is invoked, indicating that the first - // request has failed and is about to be retried, collect the results from - // the async iterator into an array. + // Create an async iterator to get the result set. firestore = await createInstance(overrides); const query = firestore.collection('collectionId'); - query._queryUtil._isPermanentRpcError = mockIsPermanentRpcError; + query._queryUtil._isPermanentRpcError = () => false; const iterator = query .stream() [Symbol.asyncIterator]() as AsyncIterator; - await mockIsPermanentRpcError.invoked.promise; const snapshots = await collect(iterator); // Verify that the async iterator returned the correct documents and, @@ -3677,4 +3746,202 @@ describe('query resumption', () => { const actualDocumentIds = snapshots.map(snapshot => snapshot.id); expect(actualDocumentIds).to.eql(documentIds); }); + + it('resuming queries with a cursor should respect the original query limit', async () => { + // Generate the IDs of the documents that will match the query. + const documentIds = Array.from(new Array(500), (_, index) => `doc${index}`); + + // Set up the mocked responses from Watch. + let requestNum = 0; + const overrides: ApiOverride = { + runQuery: request => { + requestNum++; + switch (requestNum) { + case 1: + return stream( + ...getDocResponsesFollowedByError( + documentIds, + documentIds.length / 2, + new GoogleError('simulated retryable error') + ) + ); + case 2: + return stream(...getDocResponsesForRequest(request!, documentIds)); + default: + throw new Error(`should never get here (requestNum=${requestNum})`); + } + }, + }; + + // Create an async iterator to get the result set. + const limit = 300; + firestore = await createInstance(overrides); + const query = firestore.collection('collectionId').limit(limit); + query._queryUtil._isPermanentRpcError = () => false; + const iterator = query + .stream() + [Symbol.asyncIterator]() as AsyncIterator; + const snapshots = await collect(iterator); + + // Verify that we got the correct number of results, and the results match + // the documents we expect. + const actualDocumentIds = snapshots.map(snapshot => snapshot.id); + expect(actualDocumentIds.length).to.eql(limit); + expect(actualDocumentIds).to.eql(documentIds.slice(0, limit)); + }); + + it('resuming queries with a cursor should respect the original query limitToLast', async () => { + // Generate the IDs of the documents that will match the query. + const documentIds = Array.from(new Array(500), (_, index) => `doc${index}`); + + // Set up the mocked responses from Watch. + let requestNum = 0; + const overrides: ApiOverride = { + runQuery: request => { + requestNum++; + switch (requestNum) { + case 1: + return stream( + ...getDocResponsesFollowedByError( + documentIds, + documentIds.length / 2, + new GoogleError('simulated retryable error'), + /*startAtEnd*/ true + ) + ); + case 2: + return stream(...getDocResponsesForRequest(request!, documentIds)); + default: + throw new Error(`should never get here (requestNum=${requestNum})`); + } + }, + }; + + // `stream()` cannot be called for `limitToLast` queries. We can, however, + // test using the `.get()` method which does some additional processing. + const limit = 300; + firestore = await createInstance(overrides); + const query = firestore + .collection('collectionId') + .orderBy(FieldPath.documentId()) + .limitToLast(limit); + query._queryUtil._isPermanentRpcError = () => false; + const snapshots = await query.get(); + + // Verify that we got the correct number of results, and the results match + // the documents we expect. + const actualDocumentIds = snapshots.docs.map(snapshot => snapshot.id); + expect(actualDocumentIds.length).to.eql(limit); + // slice(-limit) returns the last `limit` documents in the array. + expect(actualDocumentIds).to.eql(documentIds.slice(-limit)); + }); + + it('resuming queries with multiple failures should respect the original limit', async () => { + // Generate the IDs of the documents that will match the query. + const documentIds = Array.from(new Array(600), (_, index) => `doc${index}`); + + // Set up the mocked responses from Watch. + let requestNum = 0; + const overrides: ApiOverride = { + runQuery: request => { + requestNum++; + switch (requestNum) { + case 1: + // Get the first 60 documents followed by a retryable error. + return stream( + ...getDocResponsesFollowedByError( + documentIds, + documentIds.length / 10, + new GoogleError('simulated retryable error') + ) + ); + case 2: + // Get the another 120 documents followed by a retryable error. + return stream( + ...getDocResponsesForRequest(request!, documentIds, { + numDocs: documentIds.length / 5, + error: new GoogleError('simulated retryable error'), + }) + ); + case 3: + // Get the rest of the documents. + return stream(...getDocResponsesForRequest(request!, documentIds)); + default: + throw new Error(`should never get here (requestNum=${requestNum})`); + } + }, + }; + + // Create an async iterator to get the result set. + const limit = 300; + firestore = await createInstance(overrides); + const query = firestore.collection('collectionId').limit(limit); + query._queryUtil._isPermanentRpcError = () => false; + const iterator = query + .stream() + [Symbol.asyncIterator]() as AsyncIterator; + const snapshots = await collect(iterator); + + // Verify that we got the correct number of results, and the results match + // the documents we expect. + const actualDocumentIds = snapshots.map(snapshot => snapshot.id); + expect(actualDocumentIds.length).to.eql(limit); + expect(actualDocumentIds).to.eql(documentIds.slice(0, limit)); + }); + + it('resuming queries with multiple failures should respect the original limitToLast', async () => { + // Generate the IDs of the documents that will match the query. + const documentIds = Array.from(new Array(600), (_, index) => `doc${index}`); + + // Set up the mocked responses from Watch. + let requestNum = 0; + const overrides: ApiOverride = { + runQuery: request => { + requestNum++; + switch (requestNum) { + case 1: + // Get the first 60 documents followed by a retryable error. + return stream( + ...getDocResponsesFollowedByError( + documentIds, + documentIds.length / 10, + new GoogleError('simulated retryable error'), + /*startAtEnd*/ true + ) + ); + case 2: + // Get the another 120 documents followed by a retryable error. + return stream( + ...getDocResponsesForRequest(request!, documentIds, { + numDocs: documentIds.length / 5, + error: new GoogleError('simulated retryable error'), + }) + ); + case 3: + // Get the rest of the documents. + return stream(...getDocResponsesForRequest(request!, documentIds)); + default: + throw new Error(`should never get here (requestNum=${requestNum})`); + } + }, + }; + + // `stream()` cannot be called for `limitToLast` queries. We can, however, + // test using the `.get()` method which does some additional processing. + const limit = 300; + firestore = await createInstance(overrides); + const query = firestore + .collection('collectionId') + .orderBy(FieldPath.documentId()) + .limitToLast(limit); + query._queryUtil._isPermanentRpcError = () => false; + const snapshots = await query.get(); + + // Verify that we got the correct number of results, and the results match + // the documents we expect. + const actualDocumentIds = snapshots.docs.map(snapshot => snapshot.id); + expect(actualDocumentIds.length).to.eql(limit); + // slice(-limit) returns the last `limit` documents in the array. + expect(actualDocumentIds).to.eql(documentIds.slice(-limit)); + }); }); diff --git a/dev/test/recursive-delete.ts b/dev/test/recursive-delete.ts index e96f6c4f6..121d29033 100644 --- a/dev/test/recursive-delete.ts +++ b/dev/test/recursive-delete.ts @@ -226,7 +226,7 @@ describe('recursiveDelete() method:', () => { 'LESS_THAN', endAt('root') ), - limit(RECURSIVE_DELETE_MAX_PENDING_OPS) + limit(RECURSIVE_DELETE_MAX_PENDING_OPS - 1) ); return stream(); } diff --git a/dev/test/tracing.ts b/dev/test/tracing.ts new file mode 100644 index 000000000..d356fc3fd --- /dev/null +++ b/dev/test/tracing.ts @@ -0,0 +1,148 @@ +// 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. + +import {describe, it} from 'mocha'; +import {createInstance} from './util/helpers'; +import {expect} from 'chai'; +import {DisabledTraceUtil} from '../src/telemetry/disabled-trace-util'; +import {EnabledTraceUtil} from '../src/telemetry/enabled-trace-util'; + +describe('Firestore Tracing Controls', () => { + let originalEnvVarValue: string | undefined; + + beforeEach(() => { + originalEnvVarValue = process.env.FIRESTORE_ENABLE_TRACING; + }); + + afterEach(() => { + if (originalEnvVarValue === undefined) { + delete process.env.FIRESTORE_ENABLE_TRACING; + } else { + process.env.FIRESTORE_ENABLE_TRACING = originalEnvVarValue; + } + }); + + it('default firestore settings have tracing disabled', async () => { + const firestore = await createInstance(); + expect(firestore._traceUtil instanceof DisabledTraceUtil).to.be.true; + }); + + it('no openTelemetryOptions results in tracing disabled', async () => { + const firestore = await createInstance(undefined, { + openTelemetryOptions: undefined, + }); + expect(firestore._traceUtil instanceof DisabledTraceUtil).to.be.true; + }); + + it('openTelemetryOptions.enableTracing controls the tracing feature', async () => { + let firestore = await createInstance(undefined, { + openTelemetryOptions: { + enableTracing: undefined, + }, + }); + expect(firestore._traceUtil instanceof DisabledTraceUtil).to.be.true; + + firestore = await createInstance(undefined, { + openTelemetryOptions: { + enableTracing: false, + }, + }); + expect(firestore._traceUtil instanceof DisabledTraceUtil).to.be.true; + + firestore = await createInstance(undefined, { + openTelemetryOptions: { + enableTracing: true, + }, + }); + expect(firestore._traceUtil instanceof EnabledTraceUtil).to.be.true; + }); + + /// Tests to make sure environment variable can override settings. + + it('env var disabled, default firestore settings', async () => { + process.env.FIRESTORE_ENABLE_TRACING = 'OFF'; + const firestore = await createInstance(); + expect(firestore._traceUtil instanceof DisabledTraceUtil).to.be.true; + }); + + it('env var enabled, default firestore settings', async () => { + process.env.FIRESTORE_ENABLE_TRACING = 'ON'; + const firestore = await createInstance(); + expect(firestore._traceUtil instanceof EnabledTraceUtil).to.be.true; + }); + + it('env var disabled, no openTelemetryOptions', async () => { + process.env.FIRESTORE_ENABLE_TRACING = 'OFF'; + const firestore = await createInstance(undefined, { + openTelemetryOptions: undefined, + }); + expect(firestore._traceUtil instanceof DisabledTraceUtil).to.be.true; + }); + + it('env var enabled, no openTelemetryOptions', async () => { + process.env.FIRESTORE_ENABLE_TRACING = 'ON'; + const firestore = await createInstance(undefined, { + openTelemetryOptions: undefined, + }); + expect(firestore._traceUtil instanceof EnabledTraceUtil).to.be.true; + }); + + it('env var disabled, with openTelemetryOptions.enableTracing', async () => { + process.env.FIRESTORE_ENABLE_TRACING = 'OFF'; + let firestore = await createInstance(undefined, { + openTelemetryOptions: { + enableTracing: undefined, + }, + }); + expect(firestore._traceUtil instanceof DisabledTraceUtil).to.be.true; + + firestore = await createInstance(undefined, { + openTelemetryOptions: { + enableTracing: false, + }, + }); + expect(firestore._traceUtil instanceof DisabledTraceUtil).to.be.true; + + firestore = await createInstance(undefined, { + openTelemetryOptions: { + enableTracing: true, + }, + }); + expect(firestore._traceUtil instanceof DisabledTraceUtil).to.be.true; + }); + + it('env var enabled, with openTelemetryOptions.enableTracing', async () => { + process.env.FIRESTORE_ENABLE_TRACING = 'ON'; + let firestore = await createInstance(undefined, { + openTelemetryOptions: { + enableTracing: undefined, + }, + }); + expect(firestore._traceUtil instanceof EnabledTraceUtil).to.be.true; + + firestore = await createInstance(undefined, { + openTelemetryOptions: { + enableTracing: false, + }, + }); + expect(firestore._traceUtil instanceof EnabledTraceUtil).to.be.true; + + firestore = await createInstance(undefined, { + openTelemetryOptions: { + enableTracing: true, + }, + }); + expect(firestore._traceUtil instanceof EnabledTraceUtil).to.be.true; + }); +}); diff --git a/dev/test/vector-query.ts b/dev/test/vector-query.ts index 4da0d6e66..9897e0afc 100644 --- a/dev/test/vector-query.ts +++ b/dev/test/vector-query.ts @@ -25,6 +25,7 @@ import { import { DocumentSnapshot, FieldValue, + FieldPath, Firestore, Query, Timestamp, @@ -86,12 +87,16 @@ describe('Vector(findNearest) query interface', () => { expect( queryA - .findNearest('embedding', [40, 41, 42], { + .findNearest({ + vectorField: 'embedding', + queryVector: [40, 41, 42], limit: 10, distanceMeasure: 'COSINE', }) .isEqual( - queryA.findNearest('embedding', [40, 41, 42], { + queryA.findNearest({ + vectorField: 'embedding', + queryVector: [40, 41, 42], distanceMeasure: 'COSINE', limit: 10, }) @@ -99,41 +104,110 @@ describe('Vector(findNearest) query interface', () => { ).to.be.true; expect( queryA - .findNearest('embedding', [40, 41, 42], { + .findNearest({ + vectorField: 'embedding', + queryVector: [40, 41, 42], + distanceMeasure: 'EUCLIDEAN', limit: 10, - distanceMeasure: 'COSINE', }) .isEqual( - queryB.findNearest('embedding', [40, 41, 42], { - distanceMeasure: 'COSINE', + queryB.findNearest({ + vectorField: 'embedding', + queryVector: [40, 41, 42], + distanceMeasure: 'EUCLIDEAN', limit: 10, }) ) ).to.be.true; + expect( + queryA + .findNearest({ + vectorField: 'embedding', + queryVector: [40, 41, 42], + distanceMeasure: 'EUCLIDEAN', + limit: 10, + distanceThreshold: 0.125, + }) + .isEqual( + queryB.findNearest({ + vectorField: 'embedding', + queryVector: [40, 41, 42], + distanceMeasure: 'EUCLIDEAN', + limit: 10, + distanceThreshold: 0.125, + }) + ) + ).to.be.true; + expect( + queryA + .findNearest({ + vectorField: 'embedding', + queryVector: [40, 41, 42], + distanceMeasure: 'EUCLIDEAN', + limit: 10, + distanceThreshold: 0.125, + distanceResultField: new FieldPath('foo'), + }) + .isEqual( + queryB.findNearest({ + vectorField: 'embedding', + queryVector: [40, 41, 42], + distanceMeasure: 'EUCLIDEAN', + limit: 10, + distanceThreshold: 0.125, + distanceResultField: new FieldPath('foo'), + }) + ) + ).to.be.true; + expect( + queryA + .findNearest({ + vectorField: 'embedding', + queryVector: [40, 41, 42], + distanceMeasure: 'EUCLIDEAN', + limit: 10, + distanceResultField: 'distance', + }) + .isEqual( + queryB.findNearest({ + vectorField: 'embedding', + queryVector: [40, 41, 42], + distanceMeasure: 'EUCLIDEAN', + limit: 10, + distanceResultField: new FieldPath('distance'), + }) + ) + ).to.be.true; expect( queryA - .findNearest('embedding', [40, 41, 42], { + .findNearest({ + vectorField: 'embedding', + queryVector: [40, 41, 42], limit: 10, distanceMeasure: 'COSINE', }) .isEqual( - firestore - .collection('collectionId') - .findNearest('embedding', [40, 41, 42], { - distanceMeasure: 'COSINE', - limit: 10, - }) + firestore.collection('collectionId').findNearest({ + vectorField: 'embedding', + queryVector: [40, 41, 42], + distanceMeasure: 'COSINE', + limit: 10, + }) ) ).to.be.false; expect( queryA - .findNearest('embedding', [40, 41, 42], { + .findNearest({ + vectorField: 'embedding', + queryVector: [40, 41, 42], limit: 10, distanceMeasure: 'COSINE', }) .isEqual( - queryB.findNearest('embedding', [40, 42], { + queryB.findNearest({ + vectorField: 'embedding', + queryVector: [40, 42], distanceMeasure: 'COSINE', limit: 10, }) @@ -141,12 +215,16 @@ describe('Vector(findNearest) query interface', () => { ).to.be.false; expect( queryA - .findNearest('embedding', [40, 41, 42], { + .findNearest({ + vectorField: 'embedding', + queryVector: [40, 41, 42], limit: 10, distanceMeasure: 'COSINE', }) .isEqual( - queryB.findNearest('embedding', [40, 42], { + queryB.findNearest({ + vectorField: 'embedding', + queryVector: [40, 42], distanceMeasure: 'COSINE', limit: 1000, }) @@ -154,19 +232,188 @@ describe('Vector(findNearest) query interface', () => { ).to.be.false; expect( queryA - .findNearest('embedding', [40, 41, 42], { + .findNearest({ + vectorField: 'embedding', + queryVector: [40, 41, 42], limit: 10, distanceMeasure: 'COSINE', }) .isEqual( - queryB.findNearest('embedding', [40, 42], { + queryB.findNearest({ + vectorField: 'embedding', + queryVector: [40, 42], distanceMeasure: 'EUCLIDEAN', - limit: 1000, + limit: 10, + }) + ) + ).to.be.false; + expect( + queryA + .findNearest({ + vectorField: 'embedding', + queryVector: [40, 41, 42], + distanceMeasure: 'EUCLIDEAN', + limit: 10, + distanceThreshold: 1.125, + }) + .isEqual( + queryB.findNearest({ + vectorField: 'embedding', + queryVector: [40, 41, 42], + distanceMeasure: 'EUCLIDEAN', + limit: 10, + distanceThreshold: 0.125, + }) + ) + ).to.be.false; + expect( + queryA + .findNearest({ + vectorField: 'embedding', + queryVector: [40, 41, 42], + distanceMeasure: 'EUCLIDEAN', + limit: 10, + }) + .isEqual( + queryB.findNearest({ + vectorField: 'embedding', + queryVector: [40, 41, 42], + distanceMeasure: 'EUCLIDEAN', + limit: 10, + distanceThreshold: 1, + }) + ) + ).to.be.false; + expect( + queryA + .findNearest({ + vectorField: 'embedding', + queryVector: [40, 41, 42], + distanceMeasure: 'EUCLIDEAN', + limit: 10, + distanceThreshold: 1, + }) + .isEqual( + queryB.findNearest({ + vectorField: 'embedding', + queryVector: [40, 41, 42], + distanceMeasure: 'EUCLIDEAN', + limit: 10, + }) + ) + ).to.be.false; + expect( + queryA + .findNearest({ + vectorField: 'embedding', + queryVector: [40, 41, 42], + distanceMeasure: 'EUCLIDEAN', + limit: 10, + distanceResultField: 'distance', + }) + .isEqual( + queryB.findNearest({ + vectorField: 'embedding', + queryVector: [40, 41, 42], + distanceMeasure: 'EUCLIDEAN', + limit: 10, + distanceResultField: 'result', + }) + ) + ).to.be.false; + expect( + queryA + .findNearest({ + vectorField: 'embedding', + queryVector: [40, 41, 42], + distanceMeasure: 'EUCLIDEAN', + limit: 10, + distanceResultField: new FieldPath('bar'), + }) + .isEqual( + queryB.findNearest({ + vectorField: 'embedding', + queryVector: [40, 41, 42], + distanceMeasure: 'EUCLIDEAN', + limit: 10, + distanceResultField: new FieldPath('foo'), + }) + ) + ).to.be.false; + expect( + queryA + .findNearest({ + vectorField: 'embedding', + queryVector: [40, 41, 42], + distanceMeasure: 'EUCLIDEAN', + limit: 10, + }) + .isEqual( + queryB.findNearest({ + vectorField: 'embedding', + queryVector: [40, 41, 42], + distanceMeasure: 'EUCLIDEAN', + limit: 10, + distanceResultField: new FieldPath('foo'), + }) + ) + ).to.be.false; + expect( + queryA + .findNearest({ + vectorField: 'embedding', + queryVector: [40, 41, 42], + distanceMeasure: 'EUCLIDEAN', + limit: 10, + distanceResultField: 'result', + }) + .isEqual( + queryB.findNearest({ + vectorField: 'embedding', + queryVector: [40, 41, 42], + distanceMeasure: 'EUCLIDEAN', + limit: 10, }) ) ).to.be.false; }); + it('generates equal vector queries with deprecated API', () => { + const queryA = firestore.collection('collectionId').where('foo', '==', 42); + const queryB = firestore.collection('collectionId').where('foo', '==', 42); + + expect( + queryA + .findNearest('embedding', [40, 41, 42], { + limit: 10, + distanceMeasure: 'COSINE', + }) + .isEqual( + queryB.findNearest({ + vectorField: 'embedding', + queryVector: [40, 41, 42], + distanceMeasure: 'COSINE', + limit: 10, + }) + ) + ).to.be.true; + expect( + queryA + .findNearest('foo', [40, 41, 42, 43], { + limit: 1, + distanceMeasure: 'DOT_PRODUCT', + }) + .isEqual( + queryB.findNearest({ + vectorField: 'foo', + queryVector: [40, 41, 42, 43], + distanceMeasure: 'DOT_PRODUCT', + limit: 1, + }) + ) + ).to.be.true; + }); + it('generates proto', async () => { const overrides: ApiOverride = { runQuery: request => { @@ -193,6 +440,26 @@ describe('Vector(findNearest) query interface', () => { }); it('validates inputs', async () => { + const query: Query = firestore.collection('collectionId'); + expect(() => { + query.findNearest({ + vectorField: 'embedding', + queryVector: [], + limit: 10, + distanceMeasure: 'EUCLIDEAN', + }); + }).to.throw('not a valid vector size'); + expect(() => { + query.findNearest({ + vectorField: 'embedding', + queryVector: [10, 1000], + limit: 0, + distanceMeasure: 'EUCLIDEAN', + }); + }).to.throw('not a valid positive limit number'); + }); + + it('validates inputs - preview (deprecated) API', async () => { const query: Query = firestore.collection('collectionId'); expect(() => { query.findNearest('embedding', [], { @@ -227,12 +494,12 @@ describe('Vector(findNearest) query interface', () => { return createInstance(overrides).then(firestoreInstance => { firestore = firestoreInstance; - const query = firestore - .collection('collectionId') - .findNearest('embedding', [1], { - limit: 2, - distanceMeasure: distanceMeasure, - }); + const query = firestore.collection('collectionId').findNearest({ + vectorField: 'embedding', + queryVector: [1], + limit: 2, + distanceMeasure: distanceMeasure, + }); return query.get().then(results => { expect(results.size).to.equal(2); expect(results.empty).to.be.false; @@ -268,9 +535,12 @@ describe('Vector(findNearest) query interface', () => { let counter = 0; return createInstance(overrides).then(firestoreInstance => { firestore = firestoreInstance; - const query = firestore - .collection('collectionId') - .findNearest('vector', [1], {limit: 10, distanceMeasure: 'COSINE'}); + const query = firestore.collection('collectionId').findNearest({ + vectorField: 'vector', + queryVector: [1], + limit: 10, + distanceMeasure: 'COSINE', + }); return query.get().then(results => { expect(++counter).to.equal(1); expect(results.size).to.equal(2); @@ -285,12 +555,12 @@ describe('Vector(findNearest) query interface', () => { it('handles stream exception at initialization', async () => { let attempts = 0; - const query = firestore - .collection('collectionId') - .findNearest('embedding', [1], { - limit: 100, - distanceMeasure: 'EUCLIDEAN', - }); + const query = firestore.collection('collectionId').findNearest({ + vectorField: 'embedding', + queryVector: [1], + limit: 100, + distanceMeasure: 'EUCLIDEAN', + }); query._queryUtil._stream = () => { ++attempts; @@ -322,7 +592,12 @@ describe('Vector(findNearest) query interface', () => { firestore = firestoreInstance; return firestore .collection('collectionId') - .findNearest('embedding', [1], {limit: 10, distanceMeasure: 'COSINE'}) + .findNearest({ + vectorField: 'embedding', + queryVector: [1], + limit: 10, + distanceMeasure: 'COSINE', + }) .get() .then(() => { throw new Error('Unexpected success in Promise'); diff --git a/owlbot.py b/owlbot.py index fb1d27ec4..63c7bd42d 100644 --- a/owlbot.py +++ b/owlbot.py @@ -8,6 +8,7 @@ from synthtool import _tracked_paths import shutil from synthtool import shell +from synthtool.log import logger logging.basicConfig(level=logging.DEBUG) @@ -190,7 +191,8 @@ os.chdir("../../") # Copy types into types/ - # These files were generated by node.compile_protos_hermetic() above. + logger.debug("Running compile...") + shell.run(["npm", "run", "compile"], hide_output=True) s.copy("build/src/v1/firestore*.d.ts", "types/v1") s.copy("build/src/v1beta1/firestore_client.d.ts", "types/v1beta1") s.copy("build/protos/firestore*.d.ts", "types/protos") @@ -227,6 +229,7 @@ shell.run(('rm', '-rf', 'dev/samples/generated'), hide_output = False) shell.run(('node', 'scripts/license.js', 'dev/protos'), hide_output = False) +shell.run(('node', 'scripts/license.js', 'types'), hide_output = False) node.fix() # fix formatting diff --git a/package.json b/package.json index 9ed6b98f4..4a57c8cef 100644 --- a/package.json +++ b/package.json @@ -1,7 +1,7 @@ { "name": "@google-cloud/firestore", "description": "Firestore Client Library for Node.js", - "version": "7.8.0", + "version": "7.10.0", "license": "Apache-2.0", "author": "Google Inc.", "engines": { @@ -34,14 +34,14 @@ "api-report": "node scripts/api-report.js", "predocs": "npm run compile", "docs": "jsdoc -c .jsdoc.js", - "system-test:rest": "FIRESTORE_PREFER_REST=true mocha build/system-test --timeout 600000", - "system-test:named-db:rest": "FIRESTORE_NAMED_DATABASE=test-db FIRESTORE_PREFER_REST=true mocha build/system-test --timeout 600000", - "system-test:grpc": "mocha build/system-test --timeout 600000", - "system-test:named-db:grpc": "FIRESTORE_NAMED_DATABASE=test-db mocha build/system-test --timeout 600000", - "system-test:emulator:rest": "FIRESTORE_EMULATOR_HOST=localhost:8080 FIRESTORE_PREFER_REST=true mocha build/system-test --timeout 600000", - "system-test:named-db:emulator:rest": "FIRESTORE_NAMED_DATABASE=test-db FIRESTORE_EMULATOR_HOST=localhost:8080 FIRESTORE_PREFER_REST=true mocha build/system-test --timeout 600000", - "system-test:emulator:grpc": "FIRESTORE_EMULATOR_HOST=localhost:8080 mocha build/system-test --timeout 600000", - "system-test:named-db:emulator:grpc": "FIRESTORE_NAMED_DATABASE=test-db FIRESTORE_EMULATOR_HOST=localhost:8080 mocha build/system-test --timeout 600000", + "system-test:rest": "FIRESTORE_PREFER_REST=true mocha build/system-test --timeout 1200000", + "system-test:named-db:rest": "FIRESTORE_NAMED_DATABASE=test-db FIRESTORE_PREFER_REST=true mocha build/system-test --timeout 1200000", + "system-test:grpc": "mocha build/system-test --timeout 1200000", + "system-test:named-db:grpc": "FIRESTORE_NAMED_DATABASE=test-db mocha build/system-test --timeout 1200000", + "system-test:emulator:rest": "FIRESTORE_EMULATOR_HOST=localhost:8080 FIRESTORE_PREFER_REST=true mocha build/system-test --timeout 1200000", + "system-test:named-db:emulator:rest": "FIRESTORE_NAMED_DATABASE=test-db FIRESTORE_EMULATOR_HOST=localhost:8080 FIRESTORE_PREFER_REST=true mocha build/system-test --timeout 1200000", + "system-test:emulator:grpc": "FIRESTORE_EMULATOR_HOST=localhost:8080 mocha build/system-test --timeout 1200000", + "system-test:named-db:emulator:grpc": "FIRESTORE_NAMED_DATABASE=test-db FIRESTORE_EMULATOR_HOST=localhost:8080 mocha build/system-test --timeout 1200000", "system-test": "npm run system-test:grpc && npm run system-test:rest && npm run system-test:named-db:grpc && npm run system-test:named-db:rest", "system-test:emulator": "npm run system-test:emulator:grpc && npm run system-test:emulator:rest && npm run system-test:named-db:emulator:grpc && npm run system-test:named-db:emulator:rest", "presystem-test": "npm run compile", @@ -63,13 +63,19 @@ "precompile": "gts clean" }, "dependencies": { + "@opentelemetry/api": "^1.3.0", "fast-deep-equal": "^3.1.1", "functional-red-black-tree": "^1.0.1", "google-gax": "^4.3.3", "protobufjs": "^7.2.6" }, "devDependencies": { + "@google-cloud/trace-agent": "^8.0.0", + "@googleapis/cloudtrace": "^1.1.2", "@google-cloud/cloud-rad": "^0.4.0", + "@google-cloud/opentelemetry-cloud-trace-exporter": "^2.0.0", + "@opentelemetry/context-async-hooks": "^1.24.1", + "@opentelemetry/sdk-trace-node": "^1.24.1", "@types/assert": "^1.4.0", "@types/chai": "^4.2.7", "@types/chai-as-promised": "^7.1.2", @@ -84,7 +90,9 @@ "chai-as-promised": "^7.1.1", "codecov": "^3.6.1", "duplexify": "^4.0.0", + "execa": "^5.1.1", "extend": "^3.0.2", + "fs-extra": "7.0.1", "gapic-tools": "^0.4.0", "gts": "^5.0.1", "jsdoc": "^4.0.0", @@ -92,10 +100,13 @@ "jsdoc-region-tag": "^3.0.0", "length-prefixed-json-stream": "^1.0.1", "linkinator": "^3.0.0", + "mkdirp": "^1.0.4", "mocha": "^9.2.2", "protobufjs-cli": "^1.1.2", "proxyquire": "^2.1.3", "sinon": "^18.0.0", + "nise": "6.0.0", + "path-to-regexp": "^6.0.0", "through2": "^4.0.0", "ts-node": "^10.0.0", "typescript": "^5.2.2" diff --git a/renovate.json b/renovate.json index 26428fcfc..c5c702cf4 100644 --- a/renovate.json +++ b/renovate.json @@ -4,6 +4,7 @@ "docker:disable", ":disableDependencyDashboard" ], + "constraintsFiltering": "strict", "pinVersions": false, "rebaseStalePrs": true, "schedule": [ diff --git a/samples/package.json b/samples/package.json index b5b3f7e70..d3a07204d 100644 --- a/samples/package.json +++ b/samples/package.json @@ -11,7 +11,7 @@ "test": "mocha --timeout 600000" }, "dependencies": { - "@google-cloud/firestore": "^7.8.0" + "@google-cloud/firestore": "^7.10.0" }, "devDependencies": { "chai": "^4.2.0", diff --git a/types/firestore.d.ts b/types/firestore.d.ts index 152f35996..d6a566b41 100644 --- a/types/firestore.d.ts +++ b/types/firestore.d.ts @@ -20,6 +20,7 @@ // Declare a global (ambient) namespace // (used when not using import statement, but just script include). + declare namespace FirebaseFirestore { /** Alias for `any` but used where a Firestore field value would be provided. */ export type DocumentFieldValue = any; @@ -2079,11 +2080,11 @@ declare namespace FirebaseFirestore { * `vectorField` against the given `queryVector` and returns the top documents that are closest * to the `queryVector`. * - * Only documents whose `vectorField` field is a `VectorValue` of the same dimension as `queryVector` + * Only documents whose `vectorField` field is a {@link VectorValue} of the same dimension as `queryVector` * participate in the query, all other documents are ignored. * * @example - * ```typescript + * ``` * // Returns the closest 10 documents whose Euclidean distance from their 'embedding' fields are closed to [41, 42]. * const vectorQuery = col.findNearest('embedding', [41, 42], {limit: 10, distanceMeasure: 'EUCLIDEAN'}); * @@ -2091,11 +2092,14 @@ declare namespace FirebaseFirestore { * querySnapshot.forEach(...); * ``` * - * @param vectorField The field path this vector query executes on. - * @param queryVector The vector value used to measure the distance from `vectorField` values in the documents. - * @param options Options control the vector query. `limit` specifies the upper bound of documents to return, must - * be a positive integer with a maximum value of 1000. `distanceMeasure` specifies what type of distance is - * calculated when performing the query. + * @param vectorField - A string or {@link FieldPath} specifying the vector field to search on. + * @param queryVector - The {@link VectorValue} used to measure the distance from `vectorField` values in the documents. + * @param options - Options control the vector query. `limit` specifies the upper bound of documents to return, must + * be a positive integer with a maximum value of 1000. `distanceMeasure` specifies what type of distance is calculated + * when performing the query. + * + * @deprecated Use the new {@link findNearest} implementation + * accepting a single `options` param. */ findNearest( vectorField: string | FieldPath, @@ -2106,6 +2110,38 @@ declare namespace FirebaseFirestore { } ): VectorQuery; + /** + * Returns a query that can perform vector distance (similarity) search with given parameters. + * + * The returned query, when executed, performs a distance (similarity) search on the specified + * `vectorField` against the given `queryVector` and returns the top documents that are closest + * to the `queryVector`. + * + * Only documents whose `vectorField` field is a {@link VectorValue} of the same dimension as `queryVector` + * participate in the query, all other documents are ignored. + * + * @example + * ``` + * // Returns the closest 10 documents whose Euclidean distance from their 'embedding' fields are closed to [41, 42]. + * const vectorQuery = col.findNearest({ + * vectorField: 'embedding', + * queryVector: [41, 42], + * limit: 10, + * distanceMeasure: 'EUCLIDEAN', + * distanceResultField: 'distance', + * distanceThreshold: 0.125 + * }); + * + * const querySnapshot = await aggregateQuery.get(); + * querySnapshot.forEach(...); + * ``` + * @param options - An argument specifying the behavior of the {@link VectorQuery} returned by this function. + * See {@link VectorQueryOptions}. + */ + findNearest( + options: VectorQueryOptions + ): VectorQuery; + /** * Returns true if this `Query` is equal to the provided one. * @@ -5034,6 +5070,13 @@ declare namespace FirebaseFirestore { filterable: true; } + /** + * @beta + */ + export class NotEqAny extends Function implements FilterCondition { + filterable: true; + } + /** * @beta */ @@ -9399,6 +9442,50 @@ declare namespace FirebaseFirestore { */ isEqual(other: PipelineResult): boolean; } + + /** + * Specifies the behavior of the {@link VectorQuery} generated by a call to {@link Query.findNearest}. + */ + export interface VectorQueryOptions { + /** + * A string or {@link FieldPath} specifying the vector field to search on. + */ + vectorField: string | FieldPath; + + /** + * The {@link VectorValue} used to measure the distance from `vectorField` values in the documents. + */ + queryVector: VectorValue | Array; + + /** + * Specifies the upper bound of documents to return, must be a positive integer with a maximum value of 1000. + */ + limit: number; + + /** + * Specifies what type of distance is calculated when performing the query. + */ + distanceMeasure: 'EUCLIDEAN' | 'COSINE' | 'DOT_PRODUCT'; + + /** + * Optionally specifies the name of a field that will be set on each returned DocumentSnapshot, + * which will contain the computed distance for the document. + */ + distanceResultField?: string | FieldPath; + + /** + * Specifies a threshold for which no less similar documents will be returned. The behavior + * of the specified `distanceMeasure` will affect the meaning of the distance threshold. + * + * - For `distanceMeasure: "EUCLIDEAN"`, the meaning of `distanceThreshold` is: + * SELECT docs WHERE euclidean_distance <= distanceThreshold + * - For `distanceMeasure: "COSINE"`, the meaning of `distanceThreshold` is: + * SELECT docs WHERE cosine_distance <= distanceThreshold + * - For `distanceMeasure: "DOT_PRODUCT"`, the meaning of `distanceThreshold` is: + * SELECT docs WHERE dot_product_distance >= distanceThreshold + */ + distanceThreshold?: number; + } } declare module '@google-cloud/firestore' { diff --git a/types/protos/firestore_admin_v1_proto_api.d.ts b/types/protos/firestore_admin_v1_proto_api.d.ts index d236a5d6b..a326cbb3b 100644 --- a/types/protos/firestore_admin_v1_proto_api.d.ts +++ b/types/protos/firestore_admin_v1_proto_api.d.ts @@ -1,5 +1,5 @@ /*! - * Copyright 2022 Google LLC + * 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. @@ -15,6 +15,7 @@ */ import * as $protobuf from "protobufjs"; +import Long = require("long"); /** Namespace google. */ export namespace google { @@ -27,12 +28,172 @@ export namespace google { /** Namespace v1. */ namespace v1 { + /** Properties of a Backup. */ + interface IBackup { + + /** Backup name */ + name?: (string|null); + + /** Backup database */ + database?: (string|null); + + /** Backup databaseUid */ + databaseUid?: (string|null); + + /** Backup snapshotTime */ + snapshotTime?: (google.protobuf.ITimestamp|null); + + /** Backup expireTime */ + expireTime?: (google.protobuf.ITimestamp|null); + + /** Backup stats */ + stats?: (google.firestore.admin.v1.Backup.IStats|null); + + /** Backup state */ + state?: (google.firestore.admin.v1.Backup.State|null); + } + + /** Represents a Backup. */ + class Backup implements IBackup { + + /** + * Constructs a new Backup. + * @param [properties] Properties to set + */ + constructor(properties?: google.firestore.admin.v1.IBackup); + + /** Backup name. */ + public name: string; + + /** Backup database. */ + public database: string; + + /** Backup databaseUid. */ + public databaseUid: string; + + /** Backup snapshotTime. */ + public snapshotTime?: (google.protobuf.ITimestamp|null); + + /** Backup expireTime. */ + public expireTime?: (google.protobuf.ITimestamp|null); + + /** Backup stats. */ + public stats?: (google.firestore.admin.v1.Backup.IStats|null); + + /** Backup state. */ + public state: google.firestore.admin.v1.Backup.State; + + /** + * Creates a Backup message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns Backup + */ + public static fromObject(object: { [k: string]: any }): google.firestore.admin.v1.Backup; + + /** + * Creates a plain object from a Backup message. Also converts values to other types if specified. + * @param message Backup + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.firestore.admin.v1.Backup, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this Backup to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for Backup + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + namespace Backup { + + /** Properties of a Stats. */ + interface IStats { + + /** Stats sizeBytes */ + sizeBytes?: (number|string|null); + + /** Stats documentCount */ + documentCount?: (number|string|null); + + /** Stats indexCount */ + indexCount?: (number|string|null); + } + + /** Represents a Stats. */ + class Stats implements IStats { + + /** + * Constructs a new Stats. + * @param [properties] Properties to set + */ + constructor(properties?: google.firestore.admin.v1.Backup.IStats); + + /** Stats sizeBytes. */ + public sizeBytes: (number|string); + + /** Stats documentCount. */ + public documentCount: (number|string); + + /** Stats indexCount. */ + public indexCount: (number|string); + + /** + * Creates a Stats message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns Stats + */ + public static fromObject(object: { [k: string]: any }): google.firestore.admin.v1.Backup.Stats; + + /** + * Creates a plain object from a Stats message. Also converts values to other types if specified. + * @param message Stats + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.firestore.admin.v1.Backup.Stats, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this Stats to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for Stats + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** State enum. */ + type State = + "STATE_UNSPECIFIED"| "CREATING"| "READY"| "NOT_AVAILABLE"; + } + /** Properties of a Database. */ interface IDatabase { /** Database name */ name?: (string|null); + /** Database uid */ + uid?: (string|null); + + /** Database createTime */ + createTime?: (google.protobuf.ITimestamp|null); + + /** Database updateTime */ + updateTime?: (google.protobuf.ITimestamp|null); + /** Database locationId */ locationId?: (string|null); @@ -42,6 +203,24 @@ export namespace google { /** Database concurrencyMode */ concurrencyMode?: (google.firestore.admin.v1.Database.ConcurrencyMode|null); + /** Database versionRetentionPeriod */ + versionRetentionPeriod?: (google.protobuf.IDuration|null); + + /** Database earliestVersionTime */ + earliestVersionTime?: (google.protobuf.ITimestamp|null); + + /** Database pointInTimeRecoveryEnablement */ + pointInTimeRecoveryEnablement?: (google.firestore.admin.v1.Database.PointInTimeRecoveryEnablement|null); + + /** Database appEngineIntegrationMode */ + appEngineIntegrationMode?: (google.firestore.admin.v1.Database.AppEngineIntegrationMode|null); + + /** Database keyPrefix */ + keyPrefix?: (string|null); + + /** Database deleteProtectionState */ + deleteProtectionState?: (google.firestore.admin.v1.Database.DeleteProtectionState|null); + /** Database etag */ etag?: (string|null); } @@ -58,6 +237,15 @@ export namespace google { /** Database name. */ public name: string; + /** Database uid. */ + public uid: string; + + /** Database createTime. */ + public createTime?: (google.protobuf.ITimestamp|null); + + /** Database updateTime. */ + public updateTime?: (google.protobuf.ITimestamp|null); + /** Database locationId. */ public locationId: string; @@ -67,6 +255,24 @@ export namespace google { /** Database concurrencyMode. */ public concurrencyMode: google.firestore.admin.v1.Database.ConcurrencyMode; + /** Database versionRetentionPeriod. */ + public versionRetentionPeriod?: (google.protobuf.IDuration|null); + + /** Database earliestVersionTime. */ + public earliestVersionTime?: (google.protobuf.ITimestamp|null); + + /** Database pointInTimeRecoveryEnablement. */ + public pointInTimeRecoveryEnablement: google.firestore.admin.v1.Database.PointInTimeRecoveryEnablement; + + /** Database appEngineIntegrationMode. */ + public appEngineIntegrationMode: google.firestore.admin.v1.Database.AppEngineIntegrationMode; + + /** Database keyPrefix. */ + public keyPrefix: string; + + /** Database deleteProtectionState. */ + public deleteProtectionState: google.firestore.admin.v1.Database.DeleteProtectionState; + /** Database etag. */ public etag: string; @@ -90,6 +296,13 @@ export namespace google { * @returns JSON object */ public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for Database + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; } namespace Database { @@ -101,6 +314,18 @@ export namespace google { /** ConcurrencyMode enum. */ type ConcurrencyMode = "CONCURRENCY_MODE_UNSPECIFIED"| "OPTIMISTIC"| "PESSIMISTIC"| "OPTIMISTIC_WITH_ENTITY_GROUPS"; + + /** PointInTimeRecoveryEnablement enum. */ + type PointInTimeRecoveryEnablement = + "POINT_IN_TIME_RECOVERY_ENABLEMENT_UNSPECIFIED"| "POINT_IN_TIME_RECOVERY_ENABLED"| "POINT_IN_TIME_RECOVERY_DISABLED"; + + /** AppEngineIntegrationMode enum. */ + type AppEngineIntegrationMode = + "APP_ENGINE_INTEGRATION_MODE_UNSPECIFIED"| "ENABLED"| "DISABLED"; + + /** DeleteProtectionState enum. */ + type DeleteProtectionState = + "DELETE_PROTECTION_STATE_UNSPECIFIED"| "DELETE_PROTECTION_DISABLED"| "DELETE_PROTECTION_ENABLED"; } /** Properties of a Field. */ @@ -111,6 +336,9 @@ export namespace google { /** Field indexConfig */ indexConfig?: (google.firestore.admin.v1.Field.IIndexConfig|null); + + /** Field ttlConfig */ + ttlConfig?: (google.firestore.admin.v1.Field.ITtlConfig|null); } /** Represents a Field. */ @@ -128,6 +356,9 @@ export namespace google { /** Field indexConfig. */ public indexConfig?: (google.firestore.admin.v1.Field.IIndexConfig|null); + /** Field ttlConfig. */ + public ttlConfig?: (google.firestore.admin.v1.Field.ITtlConfig|null); + /** * Creates a Field message from a plain object. Also converts values to their respective internal types. * @param object Plain object @@ -148,6 +379,13 @@ export namespace google { * @returns JSON object */ public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for Field + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; } namespace Field { @@ -209,2071 +447,4767 @@ export namespace google { * @returns JSON object */ public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for IndexConfig + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a TtlConfig. */ + interface ITtlConfig { + + /** TtlConfig state */ + state?: (google.firestore.admin.v1.Field.TtlConfig.State|null); + } + + /** Represents a TtlConfig. */ + class TtlConfig implements ITtlConfig { + + /** + * Constructs a new TtlConfig. + * @param [properties] Properties to set + */ + constructor(properties?: google.firestore.admin.v1.Field.ITtlConfig); + + /** TtlConfig state. */ + public state: google.firestore.admin.v1.Field.TtlConfig.State; + + /** + * Creates a TtlConfig message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns TtlConfig + */ + public static fromObject(object: { [k: string]: any }): google.firestore.admin.v1.Field.TtlConfig; + + /** + * Creates a plain object from a TtlConfig message. Also converts values to other types if specified. + * @param message TtlConfig + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.firestore.admin.v1.Field.TtlConfig, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this TtlConfig to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for TtlConfig + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + namespace TtlConfig { + + /** State enum. */ + type State = + "STATE_UNSPECIFIED"| "CREATING"| "ACTIVE"| "NEEDS_REPAIR"; } } - /** Represents a FirestoreAdmin */ - class FirestoreAdmin extends $protobuf.rpc.Service { + /** Properties of an Index. */ + interface IIndex { - /** - * Constructs a new FirestoreAdmin service. - * @param rpcImpl RPC implementation - * @param [requestDelimited=false] Whether requests are length-delimited - * @param [responseDelimited=false] Whether responses are length-delimited - */ - constructor(rpcImpl: $protobuf.RPCImpl, requestDelimited?: boolean, responseDelimited?: boolean); + /** Index name */ + name?: (string|null); - /** - * Calls CreateIndex. - * @param request CreateIndexRequest message or plain object - * @param callback Node-style callback called with the error, if any, and Operation - */ - public createIndex(request: google.firestore.admin.v1.ICreateIndexRequest, callback: google.firestore.admin.v1.FirestoreAdmin.CreateIndexCallback): void; + /** Index queryScope */ + queryScope?: (google.firestore.admin.v1.Index.QueryScope|null); - /** - * Calls CreateIndex. - * @param request CreateIndexRequest message or plain object - * @returns Promise - */ - public createIndex(request: google.firestore.admin.v1.ICreateIndexRequest): Promise; + /** Index apiScope */ + apiScope?: (google.firestore.admin.v1.Index.ApiScope|null); - /** - * Calls ListIndexes. - * @param request ListIndexesRequest message or plain object - * @param callback Node-style callback called with the error, if any, and ListIndexesResponse - */ - public listIndexes(request: google.firestore.admin.v1.IListIndexesRequest, callback: google.firestore.admin.v1.FirestoreAdmin.ListIndexesCallback): void; + /** Index fields */ + fields?: (google.firestore.admin.v1.Index.IIndexField[]|null); - /** - * Calls ListIndexes. - * @param request ListIndexesRequest message or plain object - * @returns Promise - */ - public listIndexes(request: google.firestore.admin.v1.IListIndexesRequest): Promise; + /** Index state */ + state?: (google.firestore.admin.v1.Index.State|null); + } - /** - * Calls GetIndex. - * @param request GetIndexRequest message or plain object - * @param callback Node-style callback called with the error, if any, and Index - */ - public getIndex(request: google.firestore.admin.v1.IGetIndexRequest, callback: google.firestore.admin.v1.FirestoreAdmin.GetIndexCallback): void; + /** Represents an Index. */ + class Index implements IIndex { /** - * Calls GetIndex. - * @param request GetIndexRequest message or plain object - * @returns Promise + * Constructs a new Index. + * @param [properties] Properties to set */ - public getIndex(request: google.firestore.admin.v1.IGetIndexRequest): Promise; + constructor(properties?: google.firestore.admin.v1.IIndex); - /** - * Calls DeleteIndex. - * @param request DeleteIndexRequest message or plain object - * @param callback Node-style callback called with the error, if any, and Empty - */ - public deleteIndex(request: google.firestore.admin.v1.IDeleteIndexRequest, callback: google.firestore.admin.v1.FirestoreAdmin.DeleteIndexCallback): void; + /** Index name. */ + public name: string; - /** - * Calls DeleteIndex. - * @param request DeleteIndexRequest message or plain object - * @returns Promise - */ - public deleteIndex(request: google.firestore.admin.v1.IDeleteIndexRequest): Promise; + /** Index queryScope. */ + public queryScope: google.firestore.admin.v1.Index.QueryScope; - /** - * Calls GetField. - * @param request GetFieldRequest message or plain object - * @param callback Node-style callback called with the error, if any, and Field - */ - public getField(request: google.firestore.admin.v1.IGetFieldRequest, callback: google.firestore.admin.v1.FirestoreAdmin.GetFieldCallback): void; + /** Index apiScope. */ + public apiScope: google.firestore.admin.v1.Index.ApiScope; + + /** Index fields. */ + public fields: google.firestore.admin.v1.Index.IIndexField[]; + + /** Index state. */ + public state: google.firestore.admin.v1.Index.State; /** - * Calls GetField. - * @param request GetFieldRequest message or plain object - * @returns Promise + * Creates an Index message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns Index */ - public getField(request: google.firestore.admin.v1.IGetFieldRequest): Promise; + public static fromObject(object: { [k: string]: any }): google.firestore.admin.v1.Index; /** - * Calls UpdateField. - * @param request UpdateFieldRequest message or plain object - * @param callback Node-style callback called with the error, if any, and Operation + * Creates a plain object from an Index message. Also converts values to other types if specified. + * @param message Index + * @param [options] Conversion options + * @returns Plain object */ - public updateField(request: google.firestore.admin.v1.IUpdateFieldRequest, callback: google.firestore.admin.v1.FirestoreAdmin.UpdateFieldCallback): void; + public static toObject(message: google.firestore.admin.v1.Index, options?: $protobuf.IConversionOptions): { [k: string]: any }; /** - * Calls UpdateField. - * @param request UpdateFieldRequest message or plain object - * @returns Promise + * Converts this Index to JSON. + * @returns JSON object */ - public updateField(request: google.firestore.admin.v1.IUpdateFieldRequest): Promise; + public toJSON(): { [k: string]: any }; /** - * Calls ListFields. - * @param request ListFieldsRequest message or plain object - * @param callback Node-style callback called with the error, if any, and ListFieldsResponse + * Gets the default type url for Index + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url */ - public listFields(request: google.firestore.admin.v1.IListFieldsRequest, callback: google.firestore.admin.v1.FirestoreAdmin.ListFieldsCallback): void; + public static getTypeUrl(typeUrlPrefix?: string): string; + } - /** - * Calls ListFields. - * @param request ListFieldsRequest message or plain object - * @returns Promise + namespace Index { + + /** QueryScope enum. */ + type QueryScope = + "QUERY_SCOPE_UNSPECIFIED"| "COLLECTION"| "COLLECTION_GROUP"| "COLLECTION_RECURSIVE"; + + /** ApiScope enum. */ + type ApiScope = + "ANY_API"| "DATASTORE_MODE_API"; + + /** Properties of an IndexField. */ + interface IIndexField { + + /** IndexField fieldPath */ + fieldPath?: (string|null); + + /** IndexField order */ + order?: (google.firestore.admin.v1.Index.IndexField.Order|null); + + /** IndexField arrayConfig */ + arrayConfig?: (google.firestore.admin.v1.Index.IndexField.ArrayConfig|null); + + /** IndexField vectorConfig */ + vectorConfig?: (google.firestore.admin.v1.Index.IndexField.IVectorConfig|null); + } + + /** Represents an IndexField. */ + class IndexField implements IIndexField { + + /** + * Constructs a new IndexField. + * @param [properties] Properties to set + */ + constructor(properties?: google.firestore.admin.v1.Index.IIndexField); + + /** IndexField fieldPath. */ + public fieldPath: string; + + /** IndexField order. */ + public order?: (google.firestore.admin.v1.Index.IndexField.Order|null); + + /** IndexField arrayConfig. */ + public arrayConfig?: (google.firestore.admin.v1.Index.IndexField.ArrayConfig|null); + + /** IndexField vectorConfig. */ + public vectorConfig?: (google.firestore.admin.v1.Index.IndexField.IVectorConfig|null); + + /** IndexField valueMode. */ + public valueMode?: ("order"|"arrayConfig"|"vectorConfig"); + + /** + * Creates an IndexField message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns IndexField + */ + public static fromObject(object: { [k: string]: any }): google.firestore.admin.v1.Index.IndexField; + + /** + * Creates a plain object from an IndexField message. Also converts values to other types if specified. + * @param message IndexField + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.firestore.admin.v1.Index.IndexField, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this IndexField to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for IndexField + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + namespace IndexField { + + /** Order enum. */ + type Order = + "ORDER_UNSPECIFIED"| "ASCENDING"| "DESCENDING"; + + /** ArrayConfig enum. */ + type ArrayConfig = + "ARRAY_CONFIG_UNSPECIFIED"| "CONTAINS"; + + /** Properties of a VectorConfig. */ + interface IVectorConfig { + + /** VectorConfig dimension */ + dimension?: (number|null); + + /** VectorConfig flat */ + flat?: (google.firestore.admin.v1.Index.IndexField.VectorConfig.IFlatIndex|null); + } + + /** Represents a VectorConfig. */ + class VectorConfig implements IVectorConfig { + + /** + * Constructs a new VectorConfig. + * @param [properties] Properties to set + */ + constructor(properties?: google.firestore.admin.v1.Index.IndexField.IVectorConfig); + + /** VectorConfig dimension. */ + public dimension: number; + + /** VectorConfig flat. */ + public flat?: (google.firestore.admin.v1.Index.IndexField.VectorConfig.IFlatIndex|null); + + /** VectorConfig type. */ + public type?: "flat"; + + /** + * Creates a VectorConfig message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns VectorConfig + */ + public static fromObject(object: { [k: string]: any }): google.firestore.admin.v1.Index.IndexField.VectorConfig; + + /** + * Creates a plain object from a VectorConfig message. Also converts values to other types if specified. + * @param message VectorConfig + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.firestore.admin.v1.Index.IndexField.VectorConfig, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this VectorConfig to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for VectorConfig + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + namespace VectorConfig { + + /** Properties of a FlatIndex. */ + interface IFlatIndex { + } + + /** Represents a FlatIndex. */ + class FlatIndex implements IFlatIndex { + + /** + * Constructs a new FlatIndex. + * @param [properties] Properties to set + */ + constructor(properties?: google.firestore.admin.v1.Index.IndexField.VectorConfig.IFlatIndex); + + /** + * Creates a FlatIndex message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns FlatIndex + */ + public static fromObject(object: { [k: string]: any }): google.firestore.admin.v1.Index.IndexField.VectorConfig.FlatIndex; + + /** + * Creates a plain object from a FlatIndex message. Also converts values to other types if specified. + * @param message FlatIndex + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.firestore.admin.v1.Index.IndexField.VectorConfig.FlatIndex, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this FlatIndex to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for FlatIndex + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + } + } + + /** State enum. */ + type State = + "STATE_UNSPECIFIED"| "CREATING"| "READY"| "NEEDS_REPAIR"; + } + + /** Represents a FirestoreAdmin */ + class FirestoreAdmin extends $protobuf.rpc.Service { + + /** + * Constructs a new FirestoreAdmin service. + * @param rpcImpl RPC implementation + * @param [requestDelimited=false] Whether requests are length-delimited + * @param [responseDelimited=false] Whether responses are length-delimited */ - public listFields(request: google.firestore.admin.v1.IListFieldsRequest): Promise; + constructor(rpcImpl: $protobuf.RPCImpl, requestDelimited?: boolean, responseDelimited?: boolean); /** - * Calls ExportDocuments. - * @param request ExportDocumentsRequest message or plain object + * Calls CreateIndex. + * @param request CreateIndexRequest message or plain object * @param callback Node-style callback called with the error, if any, and Operation */ - public exportDocuments(request: google.firestore.admin.v1.IExportDocumentsRequest, callback: google.firestore.admin.v1.FirestoreAdmin.ExportDocumentsCallback): void; + public createIndex(request: google.firestore.admin.v1.ICreateIndexRequest, callback: google.firestore.admin.v1.FirestoreAdmin.CreateIndexCallback): void; + + /** + * Calls CreateIndex. + * @param request CreateIndexRequest message or plain object + * @returns Promise + */ + public createIndex(request: google.firestore.admin.v1.ICreateIndexRequest): Promise; + + /** + * Calls ListIndexes. + * @param request ListIndexesRequest message or plain object + * @param callback Node-style callback called with the error, if any, and ListIndexesResponse + */ + public listIndexes(request: google.firestore.admin.v1.IListIndexesRequest, callback: google.firestore.admin.v1.FirestoreAdmin.ListIndexesCallback): void; + + /** + * Calls ListIndexes. + * @param request ListIndexesRequest message or plain object + * @returns Promise + */ + public listIndexes(request: google.firestore.admin.v1.IListIndexesRequest): Promise; + + /** + * Calls GetIndex. + * @param request GetIndexRequest message or plain object + * @param callback Node-style callback called with the error, if any, and Index + */ + public getIndex(request: google.firestore.admin.v1.IGetIndexRequest, callback: google.firestore.admin.v1.FirestoreAdmin.GetIndexCallback): void; + + /** + * Calls GetIndex. + * @param request GetIndexRequest message or plain object + * @returns Promise + */ + public getIndex(request: google.firestore.admin.v1.IGetIndexRequest): Promise; + + /** + * Calls DeleteIndex. + * @param request DeleteIndexRequest message or plain object + * @param callback Node-style callback called with the error, if any, and Empty + */ + public deleteIndex(request: google.firestore.admin.v1.IDeleteIndexRequest, callback: google.firestore.admin.v1.FirestoreAdmin.DeleteIndexCallback): void; + + /** + * Calls DeleteIndex. + * @param request DeleteIndexRequest message or plain object + * @returns Promise + */ + public deleteIndex(request: google.firestore.admin.v1.IDeleteIndexRequest): Promise; + + /** + * Calls GetField. + * @param request GetFieldRequest message or plain object + * @param callback Node-style callback called with the error, if any, and Field + */ + public getField(request: google.firestore.admin.v1.IGetFieldRequest, callback: google.firestore.admin.v1.FirestoreAdmin.GetFieldCallback): void; + + /** + * Calls GetField. + * @param request GetFieldRequest message or plain object + * @returns Promise + */ + public getField(request: google.firestore.admin.v1.IGetFieldRequest): Promise; + + /** + * Calls UpdateField. + * @param request UpdateFieldRequest message or plain object + * @param callback Node-style callback called with the error, if any, and Operation + */ + public updateField(request: google.firestore.admin.v1.IUpdateFieldRequest, callback: google.firestore.admin.v1.FirestoreAdmin.UpdateFieldCallback): void; + + /** + * Calls UpdateField. + * @param request UpdateFieldRequest message or plain object + * @returns Promise + */ + public updateField(request: google.firestore.admin.v1.IUpdateFieldRequest): Promise; + + /** + * Calls ListFields. + * @param request ListFieldsRequest message or plain object + * @param callback Node-style callback called with the error, if any, and ListFieldsResponse + */ + public listFields(request: google.firestore.admin.v1.IListFieldsRequest, callback: google.firestore.admin.v1.FirestoreAdmin.ListFieldsCallback): void; + + /** + * Calls ListFields. + * @param request ListFieldsRequest message or plain object + * @returns Promise + */ + public listFields(request: google.firestore.admin.v1.IListFieldsRequest): Promise; + + /** + * Calls ExportDocuments. + * @param request ExportDocumentsRequest message or plain object + * @param callback Node-style callback called with the error, if any, and Operation + */ + public exportDocuments(request: google.firestore.admin.v1.IExportDocumentsRequest, callback: google.firestore.admin.v1.FirestoreAdmin.ExportDocumentsCallback): void; + + /** + * Calls ExportDocuments. + * @param request ExportDocumentsRequest message or plain object + * @returns Promise + */ + public exportDocuments(request: google.firestore.admin.v1.IExportDocumentsRequest): Promise; + + /** + * Calls ImportDocuments. + * @param request ImportDocumentsRequest message or plain object + * @param callback Node-style callback called with the error, if any, and Operation + */ + public importDocuments(request: google.firestore.admin.v1.IImportDocumentsRequest, callback: google.firestore.admin.v1.FirestoreAdmin.ImportDocumentsCallback): void; + + /** + * Calls ImportDocuments. + * @param request ImportDocumentsRequest message or plain object + * @returns Promise + */ + public importDocuments(request: google.firestore.admin.v1.IImportDocumentsRequest): Promise; + + /** + * Calls BulkDeleteDocuments. + * @param request BulkDeleteDocumentsRequest message or plain object + * @param callback Node-style callback called with the error, if any, and Operation + */ + public bulkDeleteDocuments(request: google.firestore.admin.v1.IBulkDeleteDocumentsRequest, callback: google.firestore.admin.v1.FirestoreAdmin.BulkDeleteDocumentsCallback): void; + + /** + * Calls BulkDeleteDocuments. + * @param request BulkDeleteDocumentsRequest message or plain object + * @returns Promise + */ + public bulkDeleteDocuments(request: google.firestore.admin.v1.IBulkDeleteDocumentsRequest): Promise; + + /** + * Calls CreateDatabase. + * @param request CreateDatabaseRequest message or plain object + * @param callback Node-style callback called with the error, if any, and Operation + */ + public createDatabase(request: google.firestore.admin.v1.ICreateDatabaseRequest, callback: google.firestore.admin.v1.FirestoreAdmin.CreateDatabaseCallback): void; + + /** + * Calls CreateDatabase. + * @param request CreateDatabaseRequest message or plain object + * @returns Promise + */ + public createDatabase(request: google.firestore.admin.v1.ICreateDatabaseRequest): Promise; + + /** + * Calls GetDatabase. + * @param request GetDatabaseRequest message or plain object + * @param callback Node-style callback called with the error, if any, and Database + */ + public getDatabase(request: google.firestore.admin.v1.IGetDatabaseRequest, callback: google.firestore.admin.v1.FirestoreAdmin.GetDatabaseCallback): void; + + /** + * Calls GetDatabase. + * @param request GetDatabaseRequest message or plain object + * @returns Promise + */ + public getDatabase(request: google.firestore.admin.v1.IGetDatabaseRequest): Promise; + + /** + * Calls ListDatabases. + * @param request ListDatabasesRequest message or plain object + * @param callback Node-style callback called with the error, if any, and ListDatabasesResponse + */ + public listDatabases(request: google.firestore.admin.v1.IListDatabasesRequest, callback: google.firestore.admin.v1.FirestoreAdmin.ListDatabasesCallback): void; + + /** + * Calls ListDatabases. + * @param request ListDatabasesRequest message or plain object + * @returns Promise + */ + public listDatabases(request: google.firestore.admin.v1.IListDatabasesRequest): Promise; + + /** + * Calls UpdateDatabase. + * @param request UpdateDatabaseRequest message or plain object + * @param callback Node-style callback called with the error, if any, and Operation + */ + public updateDatabase(request: google.firestore.admin.v1.IUpdateDatabaseRequest, callback: google.firestore.admin.v1.FirestoreAdmin.UpdateDatabaseCallback): void; + + /** + * Calls UpdateDatabase. + * @param request UpdateDatabaseRequest message or plain object + * @returns Promise + */ + public updateDatabase(request: google.firestore.admin.v1.IUpdateDatabaseRequest): Promise; + + /** + * Calls DeleteDatabase. + * @param request DeleteDatabaseRequest message or plain object + * @param callback Node-style callback called with the error, if any, and Operation + */ + public deleteDatabase(request: google.firestore.admin.v1.IDeleteDatabaseRequest, callback: google.firestore.admin.v1.FirestoreAdmin.DeleteDatabaseCallback): void; + + /** + * Calls DeleteDatabase. + * @param request DeleteDatabaseRequest message or plain object + * @returns Promise + */ + public deleteDatabase(request: google.firestore.admin.v1.IDeleteDatabaseRequest): Promise; + + /** + * Calls GetBackup. + * @param request GetBackupRequest message or plain object + * @param callback Node-style callback called with the error, if any, and Backup + */ + public getBackup(request: google.firestore.admin.v1.IGetBackupRequest, callback: google.firestore.admin.v1.FirestoreAdmin.GetBackupCallback): void; + + /** + * Calls GetBackup. + * @param request GetBackupRequest message or plain object + * @returns Promise + */ + public getBackup(request: google.firestore.admin.v1.IGetBackupRequest): Promise; + + /** + * Calls ListBackups. + * @param request ListBackupsRequest message or plain object + * @param callback Node-style callback called with the error, if any, and ListBackupsResponse + */ + public listBackups(request: google.firestore.admin.v1.IListBackupsRequest, callback: google.firestore.admin.v1.FirestoreAdmin.ListBackupsCallback): void; + + /** + * Calls ListBackups. + * @param request ListBackupsRequest message or plain object + * @returns Promise + */ + public listBackups(request: google.firestore.admin.v1.IListBackupsRequest): Promise; + + /** + * Calls DeleteBackup. + * @param request DeleteBackupRequest message or plain object + * @param callback Node-style callback called with the error, if any, and Empty + */ + public deleteBackup(request: google.firestore.admin.v1.IDeleteBackupRequest, callback: google.firestore.admin.v1.FirestoreAdmin.DeleteBackupCallback): void; + + /** + * Calls DeleteBackup. + * @param request DeleteBackupRequest message or plain object + * @returns Promise + */ + public deleteBackup(request: google.firestore.admin.v1.IDeleteBackupRequest): Promise; + + /** + * Calls RestoreDatabase. + * @param request RestoreDatabaseRequest message or plain object + * @param callback Node-style callback called with the error, if any, and Operation + */ + public restoreDatabase(request: google.firestore.admin.v1.IRestoreDatabaseRequest, callback: google.firestore.admin.v1.FirestoreAdmin.RestoreDatabaseCallback): void; + + /** + * Calls RestoreDatabase. + * @param request RestoreDatabaseRequest message or plain object + * @returns Promise + */ + public restoreDatabase(request: google.firestore.admin.v1.IRestoreDatabaseRequest): Promise; + + /** + * Calls CreateBackupSchedule. + * @param request CreateBackupScheduleRequest message or plain object + * @param callback Node-style callback called with the error, if any, and BackupSchedule + */ + public createBackupSchedule(request: google.firestore.admin.v1.ICreateBackupScheduleRequest, callback: google.firestore.admin.v1.FirestoreAdmin.CreateBackupScheduleCallback): void; + + /** + * Calls CreateBackupSchedule. + * @param request CreateBackupScheduleRequest message or plain object + * @returns Promise + */ + public createBackupSchedule(request: google.firestore.admin.v1.ICreateBackupScheduleRequest): Promise; + + /** + * Calls GetBackupSchedule. + * @param request GetBackupScheduleRequest message or plain object + * @param callback Node-style callback called with the error, if any, and BackupSchedule + */ + public getBackupSchedule(request: google.firestore.admin.v1.IGetBackupScheduleRequest, callback: google.firestore.admin.v1.FirestoreAdmin.GetBackupScheduleCallback): void; + + /** + * Calls GetBackupSchedule. + * @param request GetBackupScheduleRequest message or plain object + * @returns Promise + */ + public getBackupSchedule(request: google.firestore.admin.v1.IGetBackupScheduleRequest): Promise; + + /** + * Calls ListBackupSchedules. + * @param request ListBackupSchedulesRequest message or plain object + * @param callback Node-style callback called with the error, if any, and ListBackupSchedulesResponse + */ + public listBackupSchedules(request: google.firestore.admin.v1.IListBackupSchedulesRequest, callback: google.firestore.admin.v1.FirestoreAdmin.ListBackupSchedulesCallback): void; + + /** + * Calls ListBackupSchedules. + * @param request ListBackupSchedulesRequest message or plain object + * @returns Promise + */ + public listBackupSchedules(request: google.firestore.admin.v1.IListBackupSchedulesRequest): Promise; + + /** + * Calls UpdateBackupSchedule. + * @param request UpdateBackupScheduleRequest message or plain object + * @param callback Node-style callback called with the error, if any, and BackupSchedule + */ + public updateBackupSchedule(request: google.firestore.admin.v1.IUpdateBackupScheduleRequest, callback: google.firestore.admin.v1.FirestoreAdmin.UpdateBackupScheduleCallback): void; + + /** + * Calls UpdateBackupSchedule. + * @param request UpdateBackupScheduleRequest message or plain object + * @returns Promise + */ + public updateBackupSchedule(request: google.firestore.admin.v1.IUpdateBackupScheduleRequest): Promise; + + /** + * Calls DeleteBackupSchedule. + * @param request DeleteBackupScheduleRequest message or plain object + * @param callback Node-style callback called with the error, if any, and Empty + */ + public deleteBackupSchedule(request: google.firestore.admin.v1.IDeleteBackupScheduleRequest, callback: google.firestore.admin.v1.FirestoreAdmin.DeleteBackupScheduleCallback): void; + + /** + * Calls DeleteBackupSchedule. + * @param request DeleteBackupScheduleRequest message or plain object + * @returns Promise + */ + public deleteBackupSchedule(request: google.firestore.admin.v1.IDeleteBackupScheduleRequest): Promise; + } + + namespace FirestoreAdmin { + + /** + * Callback as used by {@link google.firestore.admin.v1.FirestoreAdmin#createIndex}. + * @param error Error, if any + * @param [response] Operation + */ + type CreateIndexCallback = (error: (Error|null), response?: google.longrunning.Operation) => void; + + /** + * Callback as used by {@link google.firestore.admin.v1.FirestoreAdmin#listIndexes}. + * @param error Error, if any + * @param [response] ListIndexesResponse + */ + type ListIndexesCallback = (error: (Error|null), response?: google.firestore.admin.v1.ListIndexesResponse) => void; + + /** + * Callback as used by {@link google.firestore.admin.v1.FirestoreAdmin#getIndex}. + * @param error Error, if any + * @param [response] Index + */ + type GetIndexCallback = (error: (Error|null), response?: google.firestore.admin.v1.Index) => void; + + /** + * Callback as used by {@link google.firestore.admin.v1.FirestoreAdmin#deleteIndex}. + * @param error Error, if any + * @param [response] Empty + */ + type DeleteIndexCallback = (error: (Error|null), response?: google.protobuf.Empty) => void; + + /** + * Callback as used by {@link google.firestore.admin.v1.FirestoreAdmin#getField}. + * @param error Error, if any + * @param [response] Field + */ + type GetFieldCallback = (error: (Error|null), response?: google.firestore.admin.v1.Field) => void; + + /** + * Callback as used by {@link google.firestore.admin.v1.FirestoreAdmin#updateField}. + * @param error Error, if any + * @param [response] Operation + */ + type UpdateFieldCallback = (error: (Error|null), response?: google.longrunning.Operation) => void; + + /** + * Callback as used by {@link google.firestore.admin.v1.FirestoreAdmin#listFields}. + * @param error Error, if any + * @param [response] ListFieldsResponse + */ + type ListFieldsCallback = (error: (Error|null), response?: google.firestore.admin.v1.ListFieldsResponse) => void; + + /** + * Callback as used by {@link google.firestore.admin.v1.FirestoreAdmin#exportDocuments}. + * @param error Error, if any + * @param [response] Operation + */ + type ExportDocumentsCallback = (error: (Error|null), response?: google.longrunning.Operation) => void; + + /** + * Callback as used by {@link google.firestore.admin.v1.FirestoreAdmin#importDocuments}. + * @param error Error, if any + * @param [response] Operation + */ + type ImportDocumentsCallback = (error: (Error|null), response?: google.longrunning.Operation) => void; + + /** + * Callback as used by {@link google.firestore.admin.v1.FirestoreAdmin#bulkDeleteDocuments}. + * @param error Error, if any + * @param [response] Operation + */ + type BulkDeleteDocumentsCallback = (error: (Error|null), response?: google.longrunning.Operation) => void; + + /** + * Callback as used by {@link google.firestore.admin.v1.FirestoreAdmin#createDatabase}. + * @param error Error, if any + * @param [response] Operation + */ + type CreateDatabaseCallback = (error: (Error|null), response?: google.longrunning.Operation) => void; + + /** + * Callback as used by {@link google.firestore.admin.v1.FirestoreAdmin#getDatabase}. + * @param error Error, if any + * @param [response] Database + */ + type GetDatabaseCallback = (error: (Error|null), response?: google.firestore.admin.v1.Database) => void; + + /** + * Callback as used by {@link google.firestore.admin.v1.FirestoreAdmin#listDatabases}. + * @param error Error, if any + * @param [response] ListDatabasesResponse + */ + type ListDatabasesCallback = (error: (Error|null), response?: google.firestore.admin.v1.ListDatabasesResponse) => void; + + /** + * Callback as used by {@link google.firestore.admin.v1.FirestoreAdmin#updateDatabase}. + * @param error Error, if any + * @param [response] Operation + */ + type UpdateDatabaseCallback = (error: (Error|null), response?: google.longrunning.Operation) => void; + + /** + * Callback as used by {@link google.firestore.admin.v1.FirestoreAdmin#deleteDatabase}. + * @param error Error, if any + * @param [response] Operation + */ + type DeleteDatabaseCallback = (error: (Error|null), response?: google.longrunning.Operation) => void; + + /** + * Callback as used by {@link google.firestore.admin.v1.FirestoreAdmin#getBackup}. + * @param error Error, if any + * @param [response] Backup + */ + type GetBackupCallback = (error: (Error|null), response?: google.firestore.admin.v1.Backup) => void; + + /** + * Callback as used by {@link google.firestore.admin.v1.FirestoreAdmin#listBackups}. + * @param error Error, if any + * @param [response] ListBackupsResponse + */ + type ListBackupsCallback = (error: (Error|null), response?: google.firestore.admin.v1.ListBackupsResponse) => void; + + /** + * Callback as used by {@link google.firestore.admin.v1.FirestoreAdmin#deleteBackup}. + * @param error Error, if any + * @param [response] Empty + */ + type DeleteBackupCallback = (error: (Error|null), response?: google.protobuf.Empty) => void; + + /** + * Callback as used by {@link google.firestore.admin.v1.FirestoreAdmin#restoreDatabase}. + * @param error Error, if any + * @param [response] Operation + */ + type RestoreDatabaseCallback = (error: (Error|null), response?: google.longrunning.Operation) => void; + + /** + * Callback as used by {@link google.firestore.admin.v1.FirestoreAdmin#createBackupSchedule}. + * @param error Error, if any + * @param [response] BackupSchedule + */ + type CreateBackupScheduleCallback = (error: (Error|null), response?: google.firestore.admin.v1.BackupSchedule) => void; + + /** + * Callback as used by {@link google.firestore.admin.v1.FirestoreAdmin#getBackupSchedule}. + * @param error Error, if any + * @param [response] BackupSchedule + */ + type GetBackupScheduleCallback = (error: (Error|null), response?: google.firestore.admin.v1.BackupSchedule) => void; + + /** + * Callback as used by {@link google.firestore.admin.v1.FirestoreAdmin#listBackupSchedules}. + * @param error Error, if any + * @param [response] ListBackupSchedulesResponse + */ + type ListBackupSchedulesCallback = (error: (Error|null), response?: google.firestore.admin.v1.ListBackupSchedulesResponse) => void; + + /** + * Callback as used by {@link google.firestore.admin.v1.FirestoreAdmin#updateBackupSchedule}. + * @param error Error, if any + * @param [response] BackupSchedule + */ + type UpdateBackupScheduleCallback = (error: (Error|null), response?: google.firestore.admin.v1.BackupSchedule) => void; + + /** + * Callback as used by {@link google.firestore.admin.v1.FirestoreAdmin#deleteBackupSchedule}. + * @param error Error, if any + * @param [response] Empty + */ + type DeleteBackupScheduleCallback = (error: (Error|null), response?: google.protobuf.Empty) => void; + } + + /** Properties of a ListDatabasesRequest. */ + interface IListDatabasesRequest { + + /** ListDatabasesRequest parent */ + parent?: (string|null); + + /** ListDatabasesRequest showDeleted */ + showDeleted?: (boolean|null); + } + + /** Represents a ListDatabasesRequest. */ + class ListDatabasesRequest implements IListDatabasesRequest { + + /** + * Constructs a new ListDatabasesRequest. + * @param [properties] Properties to set + */ + constructor(properties?: google.firestore.admin.v1.IListDatabasesRequest); + + /** ListDatabasesRequest parent. */ + public parent: string; + + /** ListDatabasesRequest showDeleted. */ + public showDeleted: boolean; + + /** + * Creates a ListDatabasesRequest message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns ListDatabasesRequest + */ + public static fromObject(object: { [k: string]: any }): google.firestore.admin.v1.ListDatabasesRequest; + + /** + * Creates a plain object from a ListDatabasesRequest message. Also converts values to other types if specified. + * @param message ListDatabasesRequest + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.firestore.admin.v1.ListDatabasesRequest, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this ListDatabasesRequest to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for ListDatabasesRequest + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a CreateDatabaseRequest. */ + interface ICreateDatabaseRequest { + + /** CreateDatabaseRequest parent */ + parent?: (string|null); + + /** CreateDatabaseRequest database */ + database?: (google.firestore.admin.v1.IDatabase|null); + + /** CreateDatabaseRequest databaseId */ + databaseId?: (string|null); + } + + /** Represents a CreateDatabaseRequest. */ + class CreateDatabaseRequest implements ICreateDatabaseRequest { + + /** + * Constructs a new CreateDatabaseRequest. + * @param [properties] Properties to set + */ + constructor(properties?: google.firestore.admin.v1.ICreateDatabaseRequest); + + /** CreateDatabaseRequest parent. */ + public parent: string; + + /** CreateDatabaseRequest database. */ + public database?: (google.firestore.admin.v1.IDatabase|null); + + /** CreateDatabaseRequest databaseId. */ + public databaseId: string; + + /** + * Creates a CreateDatabaseRequest message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns CreateDatabaseRequest + */ + public static fromObject(object: { [k: string]: any }): google.firestore.admin.v1.CreateDatabaseRequest; + + /** + * Creates a plain object from a CreateDatabaseRequest message. Also converts values to other types if specified. + * @param message CreateDatabaseRequest + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.firestore.admin.v1.CreateDatabaseRequest, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this CreateDatabaseRequest to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for CreateDatabaseRequest + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a CreateDatabaseMetadata. */ + interface ICreateDatabaseMetadata { + } + + /** Represents a CreateDatabaseMetadata. */ + class CreateDatabaseMetadata implements ICreateDatabaseMetadata { + + /** + * Constructs a new CreateDatabaseMetadata. + * @param [properties] Properties to set + */ + constructor(properties?: google.firestore.admin.v1.ICreateDatabaseMetadata); + + /** + * Creates a CreateDatabaseMetadata message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns CreateDatabaseMetadata + */ + public static fromObject(object: { [k: string]: any }): google.firestore.admin.v1.CreateDatabaseMetadata; + + /** + * Creates a plain object from a CreateDatabaseMetadata message. Also converts values to other types if specified. + * @param message CreateDatabaseMetadata + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.firestore.admin.v1.CreateDatabaseMetadata, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this CreateDatabaseMetadata to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for CreateDatabaseMetadata + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a ListDatabasesResponse. */ + interface IListDatabasesResponse { + + /** ListDatabasesResponse databases */ + databases?: (google.firestore.admin.v1.IDatabase[]|null); + + /** ListDatabasesResponse unreachable */ + unreachable?: (string[]|null); + } + + /** Represents a ListDatabasesResponse. */ + class ListDatabasesResponse implements IListDatabasesResponse { + + /** + * Constructs a new ListDatabasesResponse. + * @param [properties] Properties to set + */ + constructor(properties?: google.firestore.admin.v1.IListDatabasesResponse); + + /** ListDatabasesResponse databases. */ + public databases: google.firestore.admin.v1.IDatabase[]; + + /** ListDatabasesResponse unreachable. */ + public unreachable: string[]; + + /** + * Creates a ListDatabasesResponse message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns ListDatabasesResponse + */ + public static fromObject(object: { [k: string]: any }): google.firestore.admin.v1.ListDatabasesResponse; + + /** + * Creates a plain object from a ListDatabasesResponse message. Also converts values to other types if specified. + * @param message ListDatabasesResponse + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.firestore.admin.v1.ListDatabasesResponse, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this ListDatabasesResponse to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for ListDatabasesResponse + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a GetDatabaseRequest. */ + interface IGetDatabaseRequest { + + /** GetDatabaseRequest name */ + name?: (string|null); + } + + /** Represents a GetDatabaseRequest. */ + class GetDatabaseRequest implements IGetDatabaseRequest { + + /** + * Constructs a new GetDatabaseRequest. + * @param [properties] Properties to set + */ + constructor(properties?: google.firestore.admin.v1.IGetDatabaseRequest); + + /** GetDatabaseRequest name. */ + public name: string; + + /** + * Creates a GetDatabaseRequest message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns GetDatabaseRequest + */ + public static fromObject(object: { [k: string]: any }): google.firestore.admin.v1.GetDatabaseRequest; + + /** + * Creates a plain object from a GetDatabaseRequest message. Also converts values to other types if specified. + * @param message GetDatabaseRequest + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.firestore.admin.v1.GetDatabaseRequest, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this GetDatabaseRequest to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for GetDatabaseRequest + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of an UpdateDatabaseRequest. */ + interface IUpdateDatabaseRequest { + + /** UpdateDatabaseRequest database */ + database?: (google.firestore.admin.v1.IDatabase|null); + + /** UpdateDatabaseRequest updateMask */ + updateMask?: (google.protobuf.IFieldMask|null); + } + + /** Represents an UpdateDatabaseRequest. */ + class UpdateDatabaseRequest implements IUpdateDatabaseRequest { + + /** + * Constructs a new UpdateDatabaseRequest. + * @param [properties] Properties to set + */ + constructor(properties?: google.firestore.admin.v1.IUpdateDatabaseRequest); + + /** UpdateDatabaseRequest database. */ + public database?: (google.firestore.admin.v1.IDatabase|null); + + /** UpdateDatabaseRequest updateMask. */ + public updateMask?: (google.protobuf.IFieldMask|null); + + /** + * Creates an UpdateDatabaseRequest message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns UpdateDatabaseRequest + */ + public static fromObject(object: { [k: string]: any }): google.firestore.admin.v1.UpdateDatabaseRequest; + + /** + * Creates a plain object from an UpdateDatabaseRequest message. Also converts values to other types if specified. + * @param message UpdateDatabaseRequest + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.firestore.admin.v1.UpdateDatabaseRequest, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this UpdateDatabaseRequest to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for UpdateDatabaseRequest + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of an UpdateDatabaseMetadata. */ + interface IUpdateDatabaseMetadata { + } + + /** Represents an UpdateDatabaseMetadata. */ + class UpdateDatabaseMetadata implements IUpdateDatabaseMetadata { + + /** + * Constructs a new UpdateDatabaseMetadata. + * @param [properties] Properties to set + */ + constructor(properties?: google.firestore.admin.v1.IUpdateDatabaseMetadata); + + /** + * Creates an UpdateDatabaseMetadata message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns UpdateDatabaseMetadata + */ + public static fromObject(object: { [k: string]: any }): google.firestore.admin.v1.UpdateDatabaseMetadata; + + /** + * Creates a plain object from an UpdateDatabaseMetadata message. Also converts values to other types if specified. + * @param message UpdateDatabaseMetadata + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.firestore.admin.v1.UpdateDatabaseMetadata, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this UpdateDatabaseMetadata to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for UpdateDatabaseMetadata + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a DeleteDatabaseRequest. */ + interface IDeleteDatabaseRequest { + + /** DeleteDatabaseRequest name */ + name?: (string|null); + + /** DeleteDatabaseRequest etag */ + etag?: (string|null); + } + + /** Represents a DeleteDatabaseRequest. */ + class DeleteDatabaseRequest implements IDeleteDatabaseRequest { + + /** + * Constructs a new DeleteDatabaseRequest. + * @param [properties] Properties to set + */ + constructor(properties?: google.firestore.admin.v1.IDeleteDatabaseRequest); + + /** DeleteDatabaseRequest name. */ + public name: string; + + /** DeleteDatabaseRequest etag. */ + public etag: string; + + /** + * Creates a DeleteDatabaseRequest message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns DeleteDatabaseRequest + */ + public static fromObject(object: { [k: string]: any }): google.firestore.admin.v1.DeleteDatabaseRequest; + + /** + * Creates a plain object from a DeleteDatabaseRequest message. Also converts values to other types if specified. + * @param message DeleteDatabaseRequest + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.firestore.admin.v1.DeleteDatabaseRequest, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this DeleteDatabaseRequest to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for DeleteDatabaseRequest + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a DeleteDatabaseMetadata. */ + interface IDeleteDatabaseMetadata { + } + + /** Represents a DeleteDatabaseMetadata. */ + class DeleteDatabaseMetadata implements IDeleteDatabaseMetadata { + + /** + * Constructs a new DeleteDatabaseMetadata. + * @param [properties] Properties to set + */ + constructor(properties?: google.firestore.admin.v1.IDeleteDatabaseMetadata); + + /** + * Creates a DeleteDatabaseMetadata message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns DeleteDatabaseMetadata + */ + public static fromObject(object: { [k: string]: any }): google.firestore.admin.v1.DeleteDatabaseMetadata; + + /** + * Creates a plain object from a DeleteDatabaseMetadata message. Also converts values to other types if specified. + * @param message DeleteDatabaseMetadata + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.firestore.admin.v1.DeleteDatabaseMetadata, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this DeleteDatabaseMetadata to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for DeleteDatabaseMetadata + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a CreateBackupScheduleRequest. */ + interface ICreateBackupScheduleRequest { + + /** CreateBackupScheduleRequest parent */ + parent?: (string|null); + + /** CreateBackupScheduleRequest backupSchedule */ + backupSchedule?: (google.firestore.admin.v1.IBackupSchedule|null); + } + + /** Represents a CreateBackupScheduleRequest. */ + class CreateBackupScheduleRequest implements ICreateBackupScheduleRequest { + + /** + * Constructs a new CreateBackupScheduleRequest. + * @param [properties] Properties to set + */ + constructor(properties?: google.firestore.admin.v1.ICreateBackupScheduleRequest); + + /** CreateBackupScheduleRequest parent. */ + public parent: string; + + /** CreateBackupScheduleRequest backupSchedule. */ + public backupSchedule?: (google.firestore.admin.v1.IBackupSchedule|null); + + /** + * Creates a CreateBackupScheduleRequest message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns CreateBackupScheduleRequest + */ + public static fromObject(object: { [k: string]: any }): google.firestore.admin.v1.CreateBackupScheduleRequest; + + /** + * Creates a plain object from a CreateBackupScheduleRequest message. Also converts values to other types if specified. + * @param message CreateBackupScheduleRequest + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.firestore.admin.v1.CreateBackupScheduleRequest, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this CreateBackupScheduleRequest to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for CreateBackupScheduleRequest + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a GetBackupScheduleRequest. */ + interface IGetBackupScheduleRequest { + + /** GetBackupScheduleRequest name */ + name?: (string|null); + } + + /** Represents a GetBackupScheduleRequest. */ + class GetBackupScheduleRequest implements IGetBackupScheduleRequest { + + /** + * Constructs a new GetBackupScheduleRequest. + * @param [properties] Properties to set + */ + constructor(properties?: google.firestore.admin.v1.IGetBackupScheduleRequest); + + /** GetBackupScheduleRequest name. */ + public name: string; + + /** + * Creates a GetBackupScheduleRequest message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns GetBackupScheduleRequest + */ + public static fromObject(object: { [k: string]: any }): google.firestore.admin.v1.GetBackupScheduleRequest; + + /** + * Creates a plain object from a GetBackupScheduleRequest message. Also converts values to other types if specified. + * @param message GetBackupScheduleRequest + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.firestore.admin.v1.GetBackupScheduleRequest, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this GetBackupScheduleRequest to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for GetBackupScheduleRequest + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of an UpdateBackupScheduleRequest. */ + interface IUpdateBackupScheduleRequest { + + /** UpdateBackupScheduleRequest backupSchedule */ + backupSchedule?: (google.firestore.admin.v1.IBackupSchedule|null); + + /** UpdateBackupScheduleRequest updateMask */ + updateMask?: (google.protobuf.IFieldMask|null); + } + + /** Represents an UpdateBackupScheduleRequest. */ + class UpdateBackupScheduleRequest implements IUpdateBackupScheduleRequest { + + /** + * Constructs a new UpdateBackupScheduleRequest. + * @param [properties] Properties to set + */ + constructor(properties?: google.firestore.admin.v1.IUpdateBackupScheduleRequest); + + /** UpdateBackupScheduleRequest backupSchedule. */ + public backupSchedule?: (google.firestore.admin.v1.IBackupSchedule|null); + + /** UpdateBackupScheduleRequest updateMask. */ + public updateMask?: (google.protobuf.IFieldMask|null); + + /** + * Creates an UpdateBackupScheduleRequest message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns UpdateBackupScheduleRequest + */ + public static fromObject(object: { [k: string]: any }): google.firestore.admin.v1.UpdateBackupScheduleRequest; + + /** + * Creates a plain object from an UpdateBackupScheduleRequest message. Also converts values to other types if specified. + * @param message UpdateBackupScheduleRequest + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.firestore.admin.v1.UpdateBackupScheduleRequest, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this UpdateBackupScheduleRequest to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for UpdateBackupScheduleRequest + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a ListBackupSchedulesRequest. */ + interface IListBackupSchedulesRequest { + + /** ListBackupSchedulesRequest parent */ + parent?: (string|null); + } + + /** Represents a ListBackupSchedulesRequest. */ + class ListBackupSchedulesRequest implements IListBackupSchedulesRequest { + + /** + * Constructs a new ListBackupSchedulesRequest. + * @param [properties] Properties to set + */ + constructor(properties?: google.firestore.admin.v1.IListBackupSchedulesRequest); + + /** ListBackupSchedulesRequest parent. */ + public parent: string; + + /** + * Creates a ListBackupSchedulesRequest message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns ListBackupSchedulesRequest + */ + public static fromObject(object: { [k: string]: any }): google.firestore.admin.v1.ListBackupSchedulesRequest; + + /** + * Creates a plain object from a ListBackupSchedulesRequest message. Also converts values to other types if specified. + * @param message ListBackupSchedulesRequest + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.firestore.admin.v1.ListBackupSchedulesRequest, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this ListBackupSchedulesRequest to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for ListBackupSchedulesRequest + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a ListBackupSchedulesResponse. */ + interface IListBackupSchedulesResponse { + + /** ListBackupSchedulesResponse backupSchedules */ + backupSchedules?: (google.firestore.admin.v1.IBackupSchedule[]|null); + } + + /** Represents a ListBackupSchedulesResponse. */ + class ListBackupSchedulesResponse implements IListBackupSchedulesResponse { + + /** + * Constructs a new ListBackupSchedulesResponse. + * @param [properties] Properties to set + */ + constructor(properties?: google.firestore.admin.v1.IListBackupSchedulesResponse); + + /** ListBackupSchedulesResponse backupSchedules. */ + public backupSchedules: google.firestore.admin.v1.IBackupSchedule[]; + + /** + * Creates a ListBackupSchedulesResponse message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns ListBackupSchedulesResponse + */ + public static fromObject(object: { [k: string]: any }): google.firestore.admin.v1.ListBackupSchedulesResponse; + + /** + * Creates a plain object from a ListBackupSchedulesResponse message. Also converts values to other types if specified. + * @param message ListBackupSchedulesResponse + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.firestore.admin.v1.ListBackupSchedulesResponse, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this ListBackupSchedulesResponse to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for ListBackupSchedulesResponse + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a DeleteBackupScheduleRequest. */ + interface IDeleteBackupScheduleRequest { + + /** DeleteBackupScheduleRequest name */ + name?: (string|null); + } + + /** Represents a DeleteBackupScheduleRequest. */ + class DeleteBackupScheduleRequest implements IDeleteBackupScheduleRequest { + + /** + * Constructs a new DeleteBackupScheduleRequest. + * @param [properties] Properties to set + */ + constructor(properties?: google.firestore.admin.v1.IDeleteBackupScheduleRequest); + + /** DeleteBackupScheduleRequest name. */ + public name: string; + + /** + * Creates a DeleteBackupScheduleRequest message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns DeleteBackupScheduleRequest + */ + public static fromObject(object: { [k: string]: any }): google.firestore.admin.v1.DeleteBackupScheduleRequest; + + /** + * Creates a plain object from a DeleteBackupScheduleRequest message. Also converts values to other types if specified. + * @param message DeleteBackupScheduleRequest + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.firestore.admin.v1.DeleteBackupScheduleRequest, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this DeleteBackupScheduleRequest to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for DeleteBackupScheduleRequest + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a CreateIndexRequest. */ + interface ICreateIndexRequest { + + /** CreateIndexRequest parent */ + parent?: (string|null); + + /** CreateIndexRequest index */ + index?: (google.firestore.admin.v1.IIndex|null); + } + + /** Represents a CreateIndexRequest. */ + class CreateIndexRequest implements ICreateIndexRequest { + + /** + * Constructs a new CreateIndexRequest. + * @param [properties] Properties to set + */ + constructor(properties?: google.firestore.admin.v1.ICreateIndexRequest); + + /** CreateIndexRequest parent. */ + public parent: string; + + /** CreateIndexRequest index. */ + public index?: (google.firestore.admin.v1.IIndex|null); + + /** + * Creates a CreateIndexRequest message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns CreateIndexRequest + */ + public static fromObject(object: { [k: string]: any }): google.firestore.admin.v1.CreateIndexRequest; + + /** + * Creates a plain object from a CreateIndexRequest message. Also converts values to other types if specified. + * @param message CreateIndexRequest + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.firestore.admin.v1.CreateIndexRequest, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this CreateIndexRequest to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for CreateIndexRequest + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a ListIndexesRequest. */ + interface IListIndexesRequest { + + /** ListIndexesRequest parent */ + parent?: (string|null); + + /** ListIndexesRequest filter */ + filter?: (string|null); + + /** ListIndexesRequest pageSize */ + pageSize?: (number|null); + + /** ListIndexesRequest pageToken */ + pageToken?: (string|null); + } + + /** Represents a ListIndexesRequest. */ + class ListIndexesRequest implements IListIndexesRequest { + + /** + * Constructs a new ListIndexesRequest. + * @param [properties] Properties to set + */ + constructor(properties?: google.firestore.admin.v1.IListIndexesRequest); + + /** ListIndexesRequest parent. */ + public parent: string; + + /** ListIndexesRequest filter. */ + public filter: string; + + /** ListIndexesRequest pageSize. */ + public pageSize: number; + + /** ListIndexesRequest pageToken. */ + public pageToken: string; + + /** + * Creates a ListIndexesRequest message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns ListIndexesRequest + */ + public static fromObject(object: { [k: string]: any }): google.firestore.admin.v1.ListIndexesRequest; + + /** + * Creates a plain object from a ListIndexesRequest message. Also converts values to other types if specified. + * @param message ListIndexesRequest + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.firestore.admin.v1.ListIndexesRequest, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this ListIndexesRequest to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for ListIndexesRequest + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a ListIndexesResponse. */ + interface IListIndexesResponse { + + /** ListIndexesResponse indexes */ + indexes?: (google.firestore.admin.v1.IIndex[]|null); + + /** ListIndexesResponse nextPageToken */ + nextPageToken?: (string|null); + } + + /** Represents a ListIndexesResponse. */ + class ListIndexesResponse implements IListIndexesResponse { + + /** + * Constructs a new ListIndexesResponse. + * @param [properties] Properties to set + */ + constructor(properties?: google.firestore.admin.v1.IListIndexesResponse); + + /** ListIndexesResponse indexes. */ + public indexes: google.firestore.admin.v1.IIndex[]; + + /** ListIndexesResponse nextPageToken. */ + public nextPageToken: string; + + /** + * Creates a ListIndexesResponse message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns ListIndexesResponse + */ + public static fromObject(object: { [k: string]: any }): google.firestore.admin.v1.ListIndexesResponse; + + /** + * Creates a plain object from a ListIndexesResponse message. Also converts values to other types if specified. + * @param message ListIndexesResponse + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.firestore.admin.v1.ListIndexesResponse, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this ListIndexesResponse to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for ListIndexesResponse + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a GetIndexRequest. */ + interface IGetIndexRequest { + + /** GetIndexRequest name */ + name?: (string|null); + } + + /** Represents a GetIndexRequest. */ + class GetIndexRequest implements IGetIndexRequest { + + /** + * Constructs a new GetIndexRequest. + * @param [properties] Properties to set + */ + constructor(properties?: google.firestore.admin.v1.IGetIndexRequest); + + /** GetIndexRequest name. */ + public name: string; + + /** + * Creates a GetIndexRequest message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns GetIndexRequest + */ + public static fromObject(object: { [k: string]: any }): google.firestore.admin.v1.GetIndexRequest; + + /** + * Creates a plain object from a GetIndexRequest message. Also converts values to other types if specified. + * @param message GetIndexRequest + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.firestore.admin.v1.GetIndexRequest, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this GetIndexRequest to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for GetIndexRequest + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a DeleteIndexRequest. */ + interface IDeleteIndexRequest { + + /** DeleteIndexRequest name */ + name?: (string|null); + } + + /** Represents a DeleteIndexRequest. */ + class DeleteIndexRequest implements IDeleteIndexRequest { + + /** + * Constructs a new DeleteIndexRequest. + * @param [properties] Properties to set + */ + constructor(properties?: google.firestore.admin.v1.IDeleteIndexRequest); + + /** DeleteIndexRequest name. */ + public name: string; + + /** + * Creates a DeleteIndexRequest message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns DeleteIndexRequest + */ + public static fromObject(object: { [k: string]: any }): google.firestore.admin.v1.DeleteIndexRequest; + + /** + * Creates a plain object from a DeleteIndexRequest message. Also converts values to other types if specified. + * @param message DeleteIndexRequest + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.firestore.admin.v1.DeleteIndexRequest, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this DeleteIndexRequest to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for DeleteIndexRequest + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of an UpdateFieldRequest. */ + interface IUpdateFieldRequest { + + /** UpdateFieldRequest field */ + field?: (google.firestore.admin.v1.IField|null); + + /** UpdateFieldRequest updateMask */ + updateMask?: (google.protobuf.IFieldMask|null); + } + + /** Represents an UpdateFieldRequest. */ + class UpdateFieldRequest implements IUpdateFieldRequest { + + /** + * Constructs a new UpdateFieldRequest. + * @param [properties] Properties to set + */ + constructor(properties?: google.firestore.admin.v1.IUpdateFieldRequest); + + /** UpdateFieldRequest field. */ + public field?: (google.firestore.admin.v1.IField|null); + + /** UpdateFieldRequest updateMask. */ + public updateMask?: (google.protobuf.IFieldMask|null); + + /** + * Creates an UpdateFieldRequest message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns UpdateFieldRequest + */ + public static fromObject(object: { [k: string]: any }): google.firestore.admin.v1.UpdateFieldRequest; + + /** + * Creates a plain object from an UpdateFieldRequest message. Also converts values to other types if specified. + * @param message UpdateFieldRequest + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.firestore.admin.v1.UpdateFieldRequest, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this UpdateFieldRequest to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for UpdateFieldRequest + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a GetFieldRequest. */ + interface IGetFieldRequest { + + /** GetFieldRequest name */ + name?: (string|null); + } + + /** Represents a GetFieldRequest. */ + class GetFieldRequest implements IGetFieldRequest { + + /** + * Constructs a new GetFieldRequest. + * @param [properties] Properties to set + */ + constructor(properties?: google.firestore.admin.v1.IGetFieldRequest); + + /** GetFieldRequest name. */ + public name: string; + + /** + * Creates a GetFieldRequest message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns GetFieldRequest + */ + public static fromObject(object: { [k: string]: any }): google.firestore.admin.v1.GetFieldRequest; + + /** + * Creates a plain object from a GetFieldRequest message. Also converts values to other types if specified. + * @param message GetFieldRequest + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.firestore.admin.v1.GetFieldRequest, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this GetFieldRequest to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for GetFieldRequest + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a ListFieldsRequest. */ + interface IListFieldsRequest { + + /** ListFieldsRequest parent */ + parent?: (string|null); + + /** ListFieldsRequest filter */ + filter?: (string|null); + + /** ListFieldsRequest pageSize */ + pageSize?: (number|null); + + /** ListFieldsRequest pageToken */ + pageToken?: (string|null); + } + + /** Represents a ListFieldsRequest. */ + class ListFieldsRequest implements IListFieldsRequest { + + /** + * Constructs a new ListFieldsRequest. + * @param [properties] Properties to set + */ + constructor(properties?: google.firestore.admin.v1.IListFieldsRequest); + + /** ListFieldsRequest parent. */ + public parent: string; + + /** ListFieldsRequest filter. */ + public filter: string; + + /** ListFieldsRequest pageSize. */ + public pageSize: number; + + /** ListFieldsRequest pageToken. */ + public pageToken: string; + + /** + * Creates a ListFieldsRequest message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns ListFieldsRequest + */ + public static fromObject(object: { [k: string]: any }): google.firestore.admin.v1.ListFieldsRequest; + + /** + * Creates a plain object from a ListFieldsRequest message. Also converts values to other types if specified. + * @param message ListFieldsRequest + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.firestore.admin.v1.ListFieldsRequest, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this ListFieldsRequest to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for ListFieldsRequest + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a ListFieldsResponse. */ + interface IListFieldsResponse { + + /** ListFieldsResponse fields */ + fields?: (google.firestore.admin.v1.IField[]|null); + + /** ListFieldsResponse nextPageToken */ + nextPageToken?: (string|null); + } + + /** Represents a ListFieldsResponse. */ + class ListFieldsResponse implements IListFieldsResponse { + + /** + * Constructs a new ListFieldsResponse. + * @param [properties] Properties to set + */ + constructor(properties?: google.firestore.admin.v1.IListFieldsResponse); + + /** ListFieldsResponse fields. */ + public fields: google.firestore.admin.v1.IField[]; + + /** ListFieldsResponse nextPageToken. */ + public nextPageToken: string; + + /** + * Creates a ListFieldsResponse message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns ListFieldsResponse + */ + public static fromObject(object: { [k: string]: any }): google.firestore.admin.v1.ListFieldsResponse; + + /** + * Creates a plain object from a ListFieldsResponse message. Also converts values to other types if specified. + * @param message ListFieldsResponse + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.firestore.admin.v1.ListFieldsResponse, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this ListFieldsResponse to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for ListFieldsResponse + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of an ExportDocumentsRequest. */ + interface IExportDocumentsRequest { + + /** ExportDocumentsRequest name */ + name?: (string|null); + + /** ExportDocumentsRequest collectionIds */ + collectionIds?: (string[]|null); + + /** ExportDocumentsRequest outputUriPrefix */ + outputUriPrefix?: (string|null); + + /** ExportDocumentsRequest namespaceIds */ + namespaceIds?: (string[]|null); + + /** ExportDocumentsRequest snapshotTime */ + snapshotTime?: (google.protobuf.ITimestamp|null); + } + + /** Represents an ExportDocumentsRequest. */ + class ExportDocumentsRequest implements IExportDocumentsRequest { + + /** + * Constructs a new ExportDocumentsRequest. + * @param [properties] Properties to set + */ + constructor(properties?: google.firestore.admin.v1.IExportDocumentsRequest); + + /** ExportDocumentsRequest name. */ + public name: string; + + /** ExportDocumentsRequest collectionIds. */ + public collectionIds: string[]; + + /** ExportDocumentsRequest outputUriPrefix. */ + public outputUriPrefix: string; + + /** ExportDocumentsRequest namespaceIds. */ + public namespaceIds: string[]; + + /** ExportDocumentsRequest snapshotTime. */ + public snapshotTime?: (google.protobuf.ITimestamp|null); + + /** + * Creates an ExportDocumentsRequest message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns ExportDocumentsRequest + */ + public static fromObject(object: { [k: string]: any }): google.firestore.admin.v1.ExportDocumentsRequest; + + /** + * Creates a plain object from an ExportDocumentsRequest message. Also converts values to other types if specified. + * @param message ExportDocumentsRequest + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.firestore.admin.v1.ExportDocumentsRequest, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this ExportDocumentsRequest to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for ExportDocumentsRequest + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of an ImportDocumentsRequest. */ + interface IImportDocumentsRequest { + + /** ImportDocumentsRequest name */ + name?: (string|null); + + /** ImportDocumentsRequest collectionIds */ + collectionIds?: (string[]|null); + + /** ImportDocumentsRequest inputUriPrefix */ + inputUriPrefix?: (string|null); + + /** ImportDocumentsRequest namespaceIds */ + namespaceIds?: (string[]|null); + } + + /** Represents an ImportDocumentsRequest. */ + class ImportDocumentsRequest implements IImportDocumentsRequest { + + /** + * Constructs a new ImportDocumentsRequest. + * @param [properties] Properties to set + */ + constructor(properties?: google.firestore.admin.v1.IImportDocumentsRequest); + + /** ImportDocumentsRequest name. */ + public name: string; + + /** ImportDocumentsRequest collectionIds. */ + public collectionIds: string[]; + + /** ImportDocumentsRequest inputUriPrefix. */ + public inputUriPrefix: string; + + /** ImportDocumentsRequest namespaceIds. */ + public namespaceIds: string[]; + + /** + * Creates an ImportDocumentsRequest message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns ImportDocumentsRequest + */ + public static fromObject(object: { [k: string]: any }): google.firestore.admin.v1.ImportDocumentsRequest; + + /** + * Creates a plain object from an ImportDocumentsRequest message. Also converts values to other types if specified. + * @param message ImportDocumentsRequest + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.firestore.admin.v1.ImportDocumentsRequest, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this ImportDocumentsRequest to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for ImportDocumentsRequest + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a BulkDeleteDocumentsRequest. */ + interface IBulkDeleteDocumentsRequest { + + /** BulkDeleteDocumentsRequest name */ + name?: (string|null); + + /** BulkDeleteDocumentsRequest collectionIds */ + collectionIds?: (string[]|null); + + /** BulkDeleteDocumentsRequest namespaceIds */ + namespaceIds?: (string[]|null); + } + + /** Represents a BulkDeleteDocumentsRequest. */ + class BulkDeleteDocumentsRequest implements IBulkDeleteDocumentsRequest { + + /** + * Constructs a new BulkDeleteDocumentsRequest. + * @param [properties] Properties to set + */ + constructor(properties?: google.firestore.admin.v1.IBulkDeleteDocumentsRequest); + + /** BulkDeleteDocumentsRequest name. */ + public name: string; + + /** BulkDeleteDocumentsRequest collectionIds. */ + public collectionIds: string[]; + + /** BulkDeleteDocumentsRequest namespaceIds. */ + public namespaceIds: string[]; /** - * Calls ExportDocuments. - * @param request ExportDocumentsRequest message or plain object - * @returns Promise + * Creates a BulkDeleteDocumentsRequest message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns BulkDeleteDocumentsRequest */ - public exportDocuments(request: google.firestore.admin.v1.IExportDocumentsRequest): Promise; + public static fromObject(object: { [k: string]: any }): google.firestore.admin.v1.BulkDeleteDocumentsRequest; /** - * Calls ImportDocuments. - * @param request ImportDocumentsRequest message or plain object - * @param callback Node-style callback called with the error, if any, and Operation + * Creates a plain object from a BulkDeleteDocumentsRequest message. Also converts values to other types if specified. + * @param message BulkDeleteDocumentsRequest + * @param [options] Conversion options + * @returns Plain object */ - public importDocuments(request: google.firestore.admin.v1.IImportDocumentsRequest, callback: google.firestore.admin.v1.FirestoreAdmin.ImportDocumentsCallback): void; + public static toObject(message: google.firestore.admin.v1.BulkDeleteDocumentsRequest, options?: $protobuf.IConversionOptions): { [k: string]: any }; /** - * Calls ImportDocuments. - * @param request ImportDocumentsRequest message or plain object - * @returns Promise + * Converts this BulkDeleteDocumentsRequest to JSON. + * @returns JSON object */ - public importDocuments(request: google.firestore.admin.v1.IImportDocumentsRequest): Promise; + public toJSON(): { [k: string]: any }; /** - * Calls GetDatabase. - * @param request GetDatabaseRequest message or plain object - * @param callback Node-style callback called with the error, if any, and Database + * Gets the default type url for BulkDeleteDocumentsRequest + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url */ - public getDatabase(request: google.firestore.admin.v1.IGetDatabaseRequest, callback: google.firestore.admin.v1.FirestoreAdmin.GetDatabaseCallback): void; + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a BulkDeleteDocumentsResponse. */ + interface IBulkDeleteDocumentsResponse { + } + + /** Represents a BulkDeleteDocumentsResponse. */ + class BulkDeleteDocumentsResponse implements IBulkDeleteDocumentsResponse { /** - * Calls GetDatabase. - * @param request GetDatabaseRequest message or plain object - * @returns Promise + * Constructs a new BulkDeleteDocumentsResponse. + * @param [properties] Properties to set */ - public getDatabase(request: google.firestore.admin.v1.IGetDatabaseRequest): Promise; + constructor(properties?: google.firestore.admin.v1.IBulkDeleteDocumentsResponse); /** - * Calls ListDatabases. - * @param request ListDatabasesRequest message or plain object - * @param callback Node-style callback called with the error, if any, and ListDatabasesResponse + * Creates a BulkDeleteDocumentsResponse message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns BulkDeleteDocumentsResponse */ - public listDatabases(request: google.firestore.admin.v1.IListDatabasesRequest, callback: google.firestore.admin.v1.FirestoreAdmin.ListDatabasesCallback): void; + public static fromObject(object: { [k: string]: any }): google.firestore.admin.v1.BulkDeleteDocumentsResponse; /** - * Calls ListDatabases. - * @param request ListDatabasesRequest message or plain object - * @returns Promise + * Creates a plain object from a BulkDeleteDocumentsResponse message. Also converts values to other types if specified. + * @param message BulkDeleteDocumentsResponse + * @param [options] Conversion options + * @returns Plain object */ - public listDatabases(request: google.firestore.admin.v1.IListDatabasesRequest): Promise; + public static toObject(message: google.firestore.admin.v1.BulkDeleteDocumentsResponse, options?: $protobuf.IConversionOptions): { [k: string]: any }; /** - * Calls UpdateDatabase. - * @param request UpdateDatabaseRequest message or plain object - * @param callback Node-style callback called with the error, if any, and Operation + * Converts this BulkDeleteDocumentsResponse to JSON. + * @returns JSON object */ - public updateDatabase(request: google.firestore.admin.v1.IUpdateDatabaseRequest, callback: google.firestore.admin.v1.FirestoreAdmin.UpdateDatabaseCallback): void; + public toJSON(): { [k: string]: any }; /** - * Calls UpdateDatabase. - * @param request UpdateDatabaseRequest message or plain object - * @returns Promise + * Gets the default type url for BulkDeleteDocumentsResponse + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url */ - public updateDatabase(request: google.firestore.admin.v1.IUpdateDatabaseRequest): Promise; + public static getTypeUrl(typeUrlPrefix?: string): string; } - namespace FirestoreAdmin { + /** Properties of a GetBackupRequest. */ + interface IGetBackupRequest { - /** - * Callback as used by {@link google.firestore.admin.v1.FirestoreAdmin#createIndex}. - * @param error Error, if any - * @param [response] Operation - */ - type CreateIndexCallback = (error: (Error|null), response?: google.longrunning.Operation) => void; + /** GetBackupRequest name */ + name?: (string|null); + } - /** - * Callback as used by {@link google.firestore.admin.v1.FirestoreAdmin#listIndexes}. - * @param error Error, if any - * @param [response] ListIndexesResponse - */ - type ListIndexesCallback = (error: (Error|null), response?: google.firestore.admin.v1.ListIndexesResponse) => void; + /** Represents a GetBackupRequest. */ + class GetBackupRequest implements IGetBackupRequest { /** - * Callback as used by {@link google.firestore.admin.v1.FirestoreAdmin#getIndex}. - * @param error Error, if any - * @param [response] Index + * Constructs a new GetBackupRequest. + * @param [properties] Properties to set */ - type GetIndexCallback = (error: (Error|null), response?: google.firestore.admin.v1.Index) => void; + constructor(properties?: google.firestore.admin.v1.IGetBackupRequest); + + /** GetBackupRequest name. */ + public name: string; /** - * Callback as used by {@link google.firestore.admin.v1.FirestoreAdmin#deleteIndex}. - * @param error Error, if any - * @param [response] Empty + * Creates a GetBackupRequest message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns GetBackupRequest */ - type DeleteIndexCallback = (error: (Error|null), response?: google.protobuf.Empty) => void; + public static fromObject(object: { [k: string]: any }): google.firestore.admin.v1.GetBackupRequest; /** - * Callback as used by {@link google.firestore.admin.v1.FirestoreAdmin#getField}. - * @param error Error, if any - * @param [response] Field + * Creates a plain object from a GetBackupRequest message. Also converts values to other types if specified. + * @param message GetBackupRequest + * @param [options] Conversion options + * @returns Plain object */ - type GetFieldCallback = (error: (Error|null), response?: google.firestore.admin.v1.Field) => void; + public static toObject(message: google.firestore.admin.v1.GetBackupRequest, options?: $protobuf.IConversionOptions): { [k: string]: any }; /** - * Callback as used by {@link google.firestore.admin.v1.FirestoreAdmin#updateField}. - * @param error Error, if any - * @param [response] Operation + * Converts this GetBackupRequest to JSON. + * @returns JSON object */ - type UpdateFieldCallback = (error: (Error|null), response?: google.longrunning.Operation) => void; + public toJSON(): { [k: string]: any }; /** - * Callback as used by {@link google.firestore.admin.v1.FirestoreAdmin#listFields}. - * @param error Error, if any - * @param [response] ListFieldsResponse + * Gets the default type url for GetBackupRequest + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url */ - type ListFieldsCallback = (error: (Error|null), response?: google.firestore.admin.v1.ListFieldsResponse) => void; + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a ListBackupsRequest. */ + interface IListBackupsRequest { + + /** ListBackupsRequest parent */ + parent?: (string|null); + } + + /** Represents a ListBackupsRequest. */ + class ListBackupsRequest implements IListBackupsRequest { /** - * Callback as used by {@link google.firestore.admin.v1.FirestoreAdmin#exportDocuments}. - * @param error Error, if any - * @param [response] Operation + * Constructs a new ListBackupsRequest. + * @param [properties] Properties to set */ - type ExportDocumentsCallback = (error: (Error|null), response?: google.longrunning.Operation) => void; + constructor(properties?: google.firestore.admin.v1.IListBackupsRequest); + + /** ListBackupsRequest parent. */ + public parent: string; /** - * Callback as used by {@link google.firestore.admin.v1.FirestoreAdmin#importDocuments}. - * @param error Error, if any - * @param [response] Operation + * Creates a ListBackupsRequest message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns ListBackupsRequest */ - type ImportDocumentsCallback = (error: (Error|null), response?: google.longrunning.Operation) => void; + public static fromObject(object: { [k: string]: any }): google.firestore.admin.v1.ListBackupsRequest; /** - * Callback as used by {@link google.firestore.admin.v1.FirestoreAdmin#getDatabase}. - * @param error Error, if any - * @param [response] Database + * Creates a plain object from a ListBackupsRequest message. Also converts values to other types if specified. + * @param message ListBackupsRequest + * @param [options] Conversion options + * @returns Plain object */ - type GetDatabaseCallback = (error: (Error|null), response?: google.firestore.admin.v1.Database) => void; + public static toObject(message: google.firestore.admin.v1.ListBackupsRequest, options?: $protobuf.IConversionOptions): { [k: string]: any }; /** - * Callback as used by {@link google.firestore.admin.v1.FirestoreAdmin#listDatabases}. - * @param error Error, if any - * @param [response] ListDatabasesResponse + * Converts this ListBackupsRequest to JSON. + * @returns JSON object */ - type ListDatabasesCallback = (error: (Error|null), response?: google.firestore.admin.v1.ListDatabasesResponse) => void; + public toJSON(): { [k: string]: any }; /** - * Callback as used by {@link google.firestore.admin.v1.FirestoreAdmin#updateDatabase}. - * @param error Error, if any - * @param [response] Operation + * Gets the default type url for ListBackupsRequest + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url */ - type UpdateDatabaseCallback = (error: (Error|null), response?: google.longrunning.Operation) => void; + public static getTypeUrl(typeUrlPrefix?: string): string; } - /** Properties of a ListDatabasesRequest. */ - interface IListDatabasesRequest { + /** Properties of a ListBackupsResponse. */ + interface IListBackupsResponse { - /** ListDatabasesRequest parent */ - parent?: (string|null); + /** ListBackupsResponse backups */ + backups?: (google.firestore.admin.v1.IBackup[]|null); + + /** ListBackupsResponse unreachable */ + unreachable?: (string[]|null); } - /** Represents a ListDatabasesRequest. */ - class ListDatabasesRequest implements IListDatabasesRequest { + /** Represents a ListBackupsResponse. */ + class ListBackupsResponse implements IListBackupsResponse { /** - * Constructs a new ListDatabasesRequest. + * Constructs a new ListBackupsResponse. * @param [properties] Properties to set */ - constructor(properties?: google.firestore.admin.v1.IListDatabasesRequest); + constructor(properties?: google.firestore.admin.v1.IListBackupsResponse); - /** ListDatabasesRequest parent. */ - public parent: string; + /** ListBackupsResponse backups. */ + public backups: google.firestore.admin.v1.IBackup[]; + + /** ListBackupsResponse unreachable. */ + public unreachable: string[]; /** - * Creates a ListDatabasesRequest message from a plain object. Also converts values to their respective internal types. + * Creates a ListBackupsResponse message from a plain object. Also converts values to their respective internal types. * @param object Plain object - * @returns ListDatabasesRequest + * @returns ListBackupsResponse */ - public static fromObject(object: { [k: string]: any }): google.firestore.admin.v1.ListDatabasesRequest; + public static fromObject(object: { [k: string]: any }): google.firestore.admin.v1.ListBackupsResponse; /** - * Creates a plain object from a ListDatabasesRequest message. Also converts values to other types if specified. - * @param message ListDatabasesRequest + * Creates a plain object from a ListBackupsResponse message. Also converts values to other types if specified. + * @param message ListBackupsResponse * @param [options] Conversion options * @returns Plain object */ - public static toObject(message: google.firestore.admin.v1.ListDatabasesRequest, options?: $protobuf.IConversionOptions): { [k: string]: any }; + public static toObject(message: google.firestore.admin.v1.ListBackupsResponse, options?: $protobuf.IConversionOptions): { [k: string]: any }; /** - * Converts this ListDatabasesRequest to JSON. + * Converts this ListBackupsResponse to JSON. * @returns JSON object */ public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for ListBackupsResponse + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; } - /** Properties of a ListDatabasesResponse. */ - interface IListDatabasesResponse { + /** Properties of a DeleteBackupRequest. */ + interface IDeleteBackupRequest { - /** ListDatabasesResponse databases */ - databases?: (google.firestore.admin.v1.IDatabase[]|null); + /** DeleteBackupRequest name */ + name?: (string|null); } - /** Represents a ListDatabasesResponse. */ - class ListDatabasesResponse implements IListDatabasesResponse { + /** Represents a DeleteBackupRequest. */ + class DeleteBackupRequest implements IDeleteBackupRequest { /** - * Constructs a new ListDatabasesResponse. + * Constructs a new DeleteBackupRequest. * @param [properties] Properties to set */ - constructor(properties?: google.firestore.admin.v1.IListDatabasesResponse); + constructor(properties?: google.firestore.admin.v1.IDeleteBackupRequest); - /** ListDatabasesResponse databases. */ - public databases: google.firestore.admin.v1.IDatabase[]; + /** DeleteBackupRequest name. */ + public name: string; /** - * Creates a ListDatabasesResponse message from a plain object. Also converts values to their respective internal types. + * Creates a DeleteBackupRequest message from a plain object. Also converts values to their respective internal types. * @param object Plain object - * @returns ListDatabasesResponse + * @returns DeleteBackupRequest */ - public static fromObject(object: { [k: string]: any }): google.firestore.admin.v1.ListDatabasesResponse; + public static fromObject(object: { [k: string]: any }): google.firestore.admin.v1.DeleteBackupRequest; /** - * Creates a plain object from a ListDatabasesResponse message. Also converts values to other types if specified. - * @param message ListDatabasesResponse + * Creates a plain object from a DeleteBackupRequest message. Also converts values to other types if specified. + * @param message DeleteBackupRequest * @param [options] Conversion options * @returns Plain object */ - public static toObject(message: google.firestore.admin.v1.ListDatabasesResponse, options?: $protobuf.IConversionOptions): { [k: string]: any }; + public static toObject(message: google.firestore.admin.v1.DeleteBackupRequest, options?: $protobuf.IConversionOptions): { [k: string]: any }; /** - * Converts this ListDatabasesResponse to JSON. + * Converts this DeleteBackupRequest to JSON. * @returns JSON object */ public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for DeleteBackupRequest + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; } - /** Properties of a GetDatabaseRequest. */ - interface IGetDatabaseRequest { + /** Properties of a RestoreDatabaseRequest. */ + interface IRestoreDatabaseRequest { - /** GetDatabaseRequest name */ - name?: (string|null); + /** RestoreDatabaseRequest parent */ + parent?: (string|null); + + /** RestoreDatabaseRequest databaseId */ + databaseId?: (string|null); + + /** RestoreDatabaseRequest backup */ + backup?: (string|null); } - /** Represents a GetDatabaseRequest. */ - class GetDatabaseRequest implements IGetDatabaseRequest { + /** Represents a RestoreDatabaseRequest. */ + class RestoreDatabaseRequest implements IRestoreDatabaseRequest { /** - * Constructs a new GetDatabaseRequest. + * Constructs a new RestoreDatabaseRequest. * @param [properties] Properties to set */ - constructor(properties?: google.firestore.admin.v1.IGetDatabaseRequest); + constructor(properties?: google.firestore.admin.v1.IRestoreDatabaseRequest); - /** GetDatabaseRequest name. */ - public name: string; + /** RestoreDatabaseRequest parent. */ + public parent: string; + + /** RestoreDatabaseRequest databaseId. */ + public databaseId: string; + + /** RestoreDatabaseRequest backup. */ + public backup: string; /** - * Creates a GetDatabaseRequest message from a plain object. Also converts values to their respective internal types. + * Creates a RestoreDatabaseRequest message from a plain object. Also converts values to their respective internal types. * @param object Plain object - * @returns GetDatabaseRequest + * @returns RestoreDatabaseRequest */ - public static fromObject(object: { [k: string]: any }): google.firestore.admin.v1.GetDatabaseRequest; + public static fromObject(object: { [k: string]: any }): google.firestore.admin.v1.RestoreDatabaseRequest; /** - * Creates a plain object from a GetDatabaseRequest message. Also converts values to other types if specified. - * @param message GetDatabaseRequest + * Creates a plain object from a RestoreDatabaseRequest message. Also converts values to other types if specified. + * @param message RestoreDatabaseRequest * @param [options] Conversion options * @returns Plain object */ - public static toObject(message: google.firestore.admin.v1.GetDatabaseRequest, options?: $protobuf.IConversionOptions): { [k: string]: any }; + public static toObject(message: google.firestore.admin.v1.RestoreDatabaseRequest, options?: $protobuf.IConversionOptions): { [k: string]: any }; /** - * Converts this GetDatabaseRequest to JSON. + * Converts this RestoreDatabaseRequest to JSON. * @returns JSON object */ public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for RestoreDatabaseRequest + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; } - /** Properties of an UpdateDatabaseRequest. */ - interface IUpdateDatabaseRequest { + /** Properties of an IndexOperationMetadata. */ + interface IIndexOperationMetadata { - /** UpdateDatabaseRequest database */ - database?: (google.firestore.admin.v1.IDatabase|null); + /** IndexOperationMetadata startTime */ + startTime?: (google.protobuf.ITimestamp|null); - /** UpdateDatabaseRequest updateMask */ - updateMask?: (google.protobuf.IFieldMask|null); + /** IndexOperationMetadata endTime */ + endTime?: (google.protobuf.ITimestamp|null); + + /** IndexOperationMetadata index */ + index?: (string|null); + + /** IndexOperationMetadata state */ + state?: (google.firestore.admin.v1.OperationState|null); + + /** IndexOperationMetadata progressDocuments */ + progressDocuments?: (google.firestore.admin.v1.IProgress|null); + + /** IndexOperationMetadata progressBytes */ + progressBytes?: (google.firestore.admin.v1.IProgress|null); } - /** Represents an UpdateDatabaseRequest. */ - class UpdateDatabaseRequest implements IUpdateDatabaseRequest { + /** Represents an IndexOperationMetadata. */ + class IndexOperationMetadata implements IIndexOperationMetadata { /** - * Constructs a new UpdateDatabaseRequest. + * Constructs a new IndexOperationMetadata. * @param [properties] Properties to set */ - constructor(properties?: google.firestore.admin.v1.IUpdateDatabaseRequest); + constructor(properties?: google.firestore.admin.v1.IIndexOperationMetadata); - /** UpdateDatabaseRequest database. */ - public database?: (google.firestore.admin.v1.IDatabase|null); + /** IndexOperationMetadata startTime. */ + public startTime?: (google.protobuf.ITimestamp|null); - /** UpdateDatabaseRequest updateMask. */ - public updateMask?: (google.protobuf.IFieldMask|null); + /** IndexOperationMetadata endTime. */ + public endTime?: (google.protobuf.ITimestamp|null); + + /** IndexOperationMetadata index. */ + public index: string; + + /** IndexOperationMetadata state. */ + public state: google.firestore.admin.v1.OperationState; + + /** IndexOperationMetadata progressDocuments. */ + public progressDocuments?: (google.firestore.admin.v1.IProgress|null); + + /** IndexOperationMetadata progressBytes. */ + public progressBytes?: (google.firestore.admin.v1.IProgress|null); /** - * Creates an UpdateDatabaseRequest message from a plain object. Also converts values to their respective internal types. + * Creates an IndexOperationMetadata message from a plain object. Also converts values to their respective internal types. * @param object Plain object - * @returns UpdateDatabaseRequest + * @returns IndexOperationMetadata */ - public static fromObject(object: { [k: string]: any }): google.firestore.admin.v1.UpdateDatabaseRequest; + public static fromObject(object: { [k: string]: any }): google.firestore.admin.v1.IndexOperationMetadata; /** - * Creates a plain object from an UpdateDatabaseRequest message. Also converts values to other types if specified. - * @param message UpdateDatabaseRequest + * Creates a plain object from an IndexOperationMetadata message. Also converts values to other types if specified. + * @param message IndexOperationMetadata * @param [options] Conversion options * @returns Plain object */ - public static toObject(message: google.firestore.admin.v1.UpdateDatabaseRequest, options?: $protobuf.IConversionOptions): { [k: string]: any }; + public static toObject(message: google.firestore.admin.v1.IndexOperationMetadata, options?: $protobuf.IConversionOptions): { [k: string]: any }; /** - * Converts this UpdateDatabaseRequest to JSON. + * Converts this IndexOperationMetadata to JSON. * @returns JSON object */ public toJSON(): { [k: string]: any }; - } - /** Properties of an UpdateDatabaseMetadata. */ - interface IUpdateDatabaseMetadata { + /** + * Gets the default type url for IndexOperationMetadata + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; } - /** Represents an UpdateDatabaseMetadata. */ - class UpdateDatabaseMetadata implements IUpdateDatabaseMetadata { + /** Properties of a FieldOperationMetadata. */ + interface IFieldOperationMetadata { - /** - * Constructs a new UpdateDatabaseMetadata. - * @param [properties] Properties to set - */ - constructor(properties?: google.firestore.admin.v1.IUpdateDatabaseMetadata); + /** FieldOperationMetadata startTime */ + startTime?: (google.protobuf.ITimestamp|null); - /** - * Creates an UpdateDatabaseMetadata message from a plain object. Also converts values to their respective internal types. - * @param object Plain object - * @returns UpdateDatabaseMetadata - */ - public static fromObject(object: { [k: string]: any }): google.firestore.admin.v1.UpdateDatabaseMetadata; + /** FieldOperationMetadata endTime */ + endTime?: (google.protobuf.ITimestamp|null); - /** - * Creates a plain object from an UpdateDatabaseMetadata message. Also converts values to other types if specified. - * @param message UpdateDatabaseMetadata - * @param [options] Conversion options - * @returns Plain object - */ - public static toObject(message: google.firestore.admin.v1.UpdateDatabaseMetadata, options?: $protobuf.IConversionOptions): { [k: string]: any }; + /** FieldOperationMetadata field */ + field?: (string|null); - /** - * Converts this UpdateDatabaseMetadata to JSON. - * @returns JSON object - */ - public toJSON(): { [k: string]: any }; - } + /** FieldOperationMetadata indexConfigDeltas */ + indexConfigDeltas?: (google.firestore.admin.v1.FieldOperationMetadata.IIndexConfigDelta[]|null); - /** Properties of a CreateIndexRequest. */ - interface ICreateIndexRequest { + /** FieldOperationMetadata state */ + state?: (google.firestore.admin.v1.OperationState|null); - /** CreateIndexRequest parent */ - parent?: (string|null); + /** FieldOperationMetadata progressDocuments */ + progressDocuments?: (google.firestore.admin.v1.IProgress|null); - /** CreateIndexRequest index */ - index?: (google.firestore.admin.v1.IIndex|null); + /** FieldOperationMetadata progressBytes */ + progressBytes?: (google.firestore.admin.v1.IProgress|null); + + /** FieldOperationMetadata ttlConfigDelta */ + ttlConfigDelta?: (google.firestore.admin.v1.FieldOperationMetadata.ITtlConfigDelta|null); } - /** Represents a CreateIndexRequest. */ - class CreateIndexRequest implements ICreateIndexRequest { + /** Represents a FieldOperationMetadata. */ + class FieldOperationMetadata implements IFieldOperationMetadata { /** - * Constructs a new CreateIndexRequest. + * Constructs a new FieldOperationMetadata. * @param [properties] Properties to set */ - constructor(properties?: google.firestore.admin.v1.ICreateIndexRequest); + constructor(properties?: google.firestore.admin.v1.IFieldOperationMetadata); - /** CreateIndexRequest parent. */ - public parent: string; + /** FieldOperationMetadata startTime. */ + public startTime?: (google.protobuf.ITimestamp|null); - /** CreateIndexRequest index. */ - public index?: (google.firestore.admin.v1.IIndex|null); + /** FieldOperationMetadata endTime. */ + public endTime?: (google.protobuf.ITimestamp|null); + + /** FieldOperationMetadata field. */ + public field: string; + + /** FieldOperationMetadata indexConfigDeltas. */ + public indexConfigDeltas: google.firestore.admin.v1.FieldOperationMetadata.IIndexConfigDelta[]; + + /** FieldOperationMetadata state. */ + public state: google.firestore.admin.v1.OperationState; + + /** FieldOperationMetadata progressDocuments. */ + public progressDocuments?: (google.firestore.admin.v1.IProgress|null); + + /** FieldOperationMetadata progressBytes. */ + public progressBytes?: (google.firestore.admin.v1.IProgress|null); + + /** FieldOperationMetadata ttlConfigDelta. */ + public ttlConfigDelta?: (google.firestore.admin.v1.FieldOperationMetadata.ITtlConfigDelta|null); /** - * Creates a CreateIndexRequest message from a plain object. Also converts values to their respective internal types. + * Creates a FieldOperationMetadata message from a plain object. Also converts values to their respective internal types. * @param object Plain object - * @returns CreateIndexRequest + * @returns FieldOperationMetadata */ - public static fromObject(object: { [k: string]: any }): google.firestore.admin.v1.CreateIndexRequest; + public static fromObject(object: { [k: string]: any }): google.firestore.admin.v1.FieldOperationMetadata; /** - * Creates a plain object from a CreateIndexRequest message. Also converts values to other types if specified. - * @param message CreateIndexRequest + * Creates a plain object from a FieldOperationMetadata message. Also converts values to other types if specified. + * @param message FieldOperationMetadata * @param [options] Conversion options * @returns Plain object */ - public static toObject(message: google.firestore.admin.v1.CreateIndexRequest, options?: $protobuf.IConversionOptions): { [k: string]: any }; + public static toObject(message: google.firestore.admin.v1.FieldOperationMetadata, options?: $protobuf.IConversionOptions): { [k: string]: any }; /** - * Converts this CreateIndexRequest to JSON. + * Converts this FieldOperationMetadata to JSON. * @returns JSON object */ public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for FieldOperationMetadata + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; } - /** Properties of a ListIndexesRequest. */ - interface IListIndexesRequest { + namespace FieldOperationMetadata { - /** ListIndexesRequest parent */ - parent?: (string|null); + /** Properties of an IndexConfigDelta. */ + interface IIndexConfigDelta { - /** ListIndexesRequest filter */ - filter?: (string|null); + /** IndexConfigDelta changeType */ + changeType?: (google.firestore.admin.v1.FieldOperationMetadata.IndexConfigDelta.ChangeType|null); - /** ListIndexesRequest pageSize */ - pageSize?: (number|null); + /** IndexConfigDelta index */ + index?: (google.firestore.admin.v1.IIndex|null); + } - /** ListIndexesRequest pageToken */ - pageToken?: (string|null); - } + /** Represents an IndexConfigDelta. */ + class IndexConfigDelta implements IIndexConfigDelta { - /** Represents a ListIndexesRequest. */ - class ListIndexesRequest implements IListIndexesRequest { + /** + * Constructs a new IndexConfigDelta. + * @param [properties] Properties to set + */ + constructor(properties?: google.firestore.admin.v1.FieldOperationMetadata.IIndexConfigDelta); - /** - * Constructs a new ListIndexesRequest. - * @param [properties] Properties to set - */ - constructor(properties?: google.firestore.admin.v1.IListIndexesRequest); + /** IndexConfigDelta changeType. */ + public changeType: google.firestore.admin.v1.FieldOperationMetadata.IndexConfigDelta.ChangeType; - /** ListIndexesRequest parent. */ - public parent: string; + /** IndexConfigDelta index. */ + public index?: (google.firestore.admin.v1.IIndex|null); - /** ListIndexesRequest filter. */ - public filter: string; + /** + * Creates an IndexConfigDelta message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns IndexConfigDelta + */ + public static fromObject(object: { [k: string]: any }): google.firestore.admin.v1.FieldOperationMetadata.IndexConfigDelta; - /** ListIndexesRequest pageSize. */ - public pageSize: number; + /** + * Creates a plain object from an IndexConfigDelta message. Also converts values to other types if specified. + * @param message IndexConfigDelta + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.firestore.admin.v1.FieldOperationMetadata.IndexConfigDelta, options?: $protobuf.IConversionOptions): { [k: string]: any }; - /** ListIndexesRequest pageToken. */ - public pageToken: string; + /** + * Converts this IndexConfigDelta to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; - /** - * Creates a ListIndexesRequest message from a plain object. Also converts values to their respective internal types. - * @param object Plain object - * @returns ListIndexesRequest - */ - public static fromObject(object: { [k: string]: any }): google.firestore.admin.v1.ListIndexesRequest; + /** + * Gets the default type url for IndexConfigDelta + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } - /** - * Creates a plain object from a ListIndexesRequest message. Also converts values to other types if specified. - * @param message ListIndexesRequest - * @param [options] Conversion options - * @returns Plain object - */ - public static toObject(message: google.firestore.admin.v1.ListIndexesRequest, options?: $protobuf.IConversionOptions): { [k: string]: any }; + namespace IndexConfigDelta { + + /** ChangeType enum. */ + type ChangeType = + "CHANGE_TYPE_UNSPECIFIED"| "ADD"| "REMOVE"; + } + + /** Properties of a TtlConfigDelta. */ + interface ITtlConfigDelta { + + /** TtlConfigDelta changeType */ + changeType?: (google.firestore.admin.v1.FieldOperationMetadata.TtlConfigDelta.ChangeType|null); + } + + /** Represents a TtlConfigDelta. */ + class TtlConfigDelta implements ITtlConfigDelta { + + /** + * Constructs a new TtlConfigDelta. + * @param [properties] Properties to set + */ + constructor(properties?: google.firestore.admin.v1.FieldOperationMetadata.ITtlConfigDelta); + + /** TtlConfigDelta changeType. */ + public changeType: google.firestore.admin.v1.FieldOperationMetadata.TtlConfigDelta.ChangeType; + + /** + * Creates a TtlConfigDelta message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns TtlConfigDelta + */ + public static fromObject(object: { [k: string]: any }): google.firestore.admin.v1.FieldOperationMetadata.TtlConfigDelta; + + /** + * Creates a plain object from a TtlConfigDelta message. Also converts values to other types if specified. + * @param message TtlConfigDelta + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.firestore.admin.v1.FieldOperationMetadata.TtlConfigDelta, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this TtlConfigDelta to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for TtlConfigDelta + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + namespace TtlConfigDelta { + + /** ChangeType enum. */ + type ChangeType = + "CHANGE_TYPE_UNSPECIFIED"| "ADD"| "REMOVE"; + } + } + + /** Properties of an ExportDocumentsMetadata. */ + interface IExportDocumentsMetadata { + + /** ExportDocumentsMetadata startTime */ + startTime?: (google.protobuf.ITimestamp|null); + + /** ExportDocumentsMetadata endTime */ + endTime?: (google.protobuf.ITimestamp|null); + + /** ExportDocumentsMetadata operationState */ + operationState?: (google.firestore.admin.v1.OperationState|null); + + /** ExportDocumentsMetadata progressDocuments */ + progressDocuments?: (google.firestore.admin.v1.IProgress|null); + + /** ExportDocumentsMetadata progressBytes */ + progressBytes?: (google.firestore.admin.v1.IProgress|null); - /** - * Converts this ListIndexesRequest to JSON. - * @returns JSON object - */ - public toJSON(): { [k: string]: any }; - } + /** ExportDocumentsMetadata collectionIds */ + collectionIds?: (string[]|null); - /** Properties of a ListIndexesResponse. */ - interface IListIndexesResponse { + /** ExportDocumentsMetadata outputUriPrefix */ + outputUriPrefix?: (string|null); - /** ListIndexesResponse indexes */ - indexes?: (google.firestore.admin.v1.IIndex[]|null); + /** ExportDocumentsMetadata namespaceIds */ + namespaceIds?: (string[]|null); - /** ListIndexesResponse nextPageToken */ - nextPageToken?: (string|null); + /** ExportDocumentsMetadata snapshotTime */ + snapshotTime?: (google.protobuf.ITimestamp|null); } - /** Represents a ListIndexesResponse. */ - class ListIndexesResponse implements IListIndexesResponse { + /** Represents an ExportDocumentsMetadata. */ + class ExportDocumentsMetadata implements IExportDocumentsMetadata { /** - * Constructs a new ListIndexesResponse. + * Constructs a new ExportDocumentsMetadata. * @param [properties] Properties to set */ - constructor(properties?: google.firestore.admin.v1.IListIndexesResponse); - - /** ListIndexesResponse indexes. */ - public indexes: google.firestore.admin.v1.IIndex[]; + constructor(properties?: google.firestore.admin.v1.IExportDocumentsMetadata); - /** ListIndexesResponse nextPageToken. */ - public nextPageToken: string; + /** ExportDocumentsMetadata startTime. */ + public startTime?: (google.protobuf.ITimestamp|null); - /** - * Creates a ListIndexesResponse message from a plain object. Also converts values to their respective internal types. - * @param object Plain object - * @returns ListIndexesResponse - */ - public static fromObject(object: { [k: string]: any }): google.firestore.admin.v1.ListIndexesResponse; + /** ExportDocumentsMetadata endTime. */ + public endTime?: (google.protobuf.ITimestamp|null); - /** - * Creates a plain object from a ListIndexesResponse message. Also converts values to other types if specified. - * @param message ListIndexesResponse - * @param [options] Conversion options - * @returns Plain object - */ - public static toObject(message: google.firestore.admin.v1.ListIndexesResponse, options?: $protobuf.IConversionOptions): { [k: string]: any }; + /** ExportDocumentsMetadata operationState. */ + public operationState: google.firestore.admin.v1.OperationState; - /** - * Converts this ListIndexesResponse to JSON. - * @returns JSON object - */ - public toJSON(): { [k: string]: any }; - } + /** ExportDocumentsMetadata progressDocuments. */ + public progressDocuments?: (google.firestore.admin.v1.IProgress|null); - /** Properties of a GetIndexRequest. */ - interface IGetIndexRequest { + /** ExportDocumentsMetadata progressBytes. */ + public progressBytes?: (google.firestore.admin.v1.IProgress|null); - /** GetIndexRequest name */ - name?: (string|null); - } + /** ExportDocumentsMetadata collectionIds. */ + public collectionIds: string[]; - /** Represents a GetIndexRequest. */ - class GetIndexRequest implements IGetIndexRequest { + /** ExportDocumentsMetadata outputUriPrefix. */ + public outputUriPrefix: string; - /** - * Constructs a new GetIndexRequest. - * @param [properties] Properties to set - */ - constructor(properties?: google.firestore.admin.v1.IGetIndexRequest); + /** ExportDocumentsMetadata namespaceIds. */ + public namespaceIds: string[]; - /** GetIndexRequest name. */ - public name: string; + /** ExportDocumentsMetadata snapshotTime. */ + public snapshotTime?: (google.protobuf.ITimestamp|null); /** - * Creates a GetIndexRequest message from a plain object. Also converts values to their respective internal types. + * Creates an ExportDocumentsMetadata message from a plain object. Also converts values to their respective internal types. * @param object Plain object - * @returns GetIndexRequest + * @returns ExportDocumentsMetadata */ - public static fromObject(object: { [k: string]: any }): google.firestore.admin.v1.GetIndexRequest; + public static fromObject(object: { [k: string]: any }): google.firestore.admin.v1.ExportDocumentsMetadata; /** - * Creates a plain object from a GetIndexRequest message. Also converts values to other types if specified. - * @param message GetIndexRequest + * Creates a plain object from an ExportDocumentsMetadata message. Also converts values to other types if specified. + * @param message ExportDocumentsMetadata * @param [options] Conversion options * @returns Plain object */ - public static toObject(message: google.firestore.admin.v1.GetIndexRequest, options?: $protobuf.IConversionOptions): { [k: string]: any }; + public static toObject(message: google.firestore.admin.v1.ExportDocumentsMetadata, options?: $protobuf.IConversionOptions): { [k: string]: any }; /** - * Converts this GetIndexRequest to JSON. + * Converts this ExportDocumentsMetadata to JSON. * @returns JSON object */ public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for ExportDocumentsMetadata + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; } - /** Properties of a DeleteIndexRequest. */ - interface IDeleteIndexRequest { + /** Properties of an ImportDocumentsMetadata. */ + interface IImportDocumentsMetadata { - /** DeleteIndexRequest name */ - name?: (string|null); + /** ImportDocumentsMetadata startTime */ + startTime?: (google.protobuf.ITimestamp|null); + + /** ImportDocumentsMetadata endTime */ + endTime?: (google.protobuf.ITimestamp|null); + + /** ImportDocumentsMetadata operationState */ + operationState?: (google.firestore.admin.v1.OperationState|null); + + /** ImportDocumentsMetadata progressDocuments */ + progressDocuments?: (google.firestore.admin.v1.IProgress|null); + + /** ImportDocumentsMetadata progressBytes */ + progressBytes?: (google.firestore.admin.v1.IProgress|null); + + /** ImportDocumentsMetadata collectionIds */ + collectionIds?: (string[]|null); + + /** ImportDocumentsMetadata inputUriPrefix */ + inputUriPrefix?: (string|null); + + /** ImportDocumentsMetadata namespaceIds */ + namespaceIds?: (string[]|null); } - /** Represents a DeleteIndexRequest. */ - class DeleteIndexRequest implements IDeleteIndexRequest { + /** Represents an ImportDocumentsMetadata. */ + class ImportDocumentsMetadata implements IImportDocumentsMetadata { /** - * Constructs a new DeleteIndexRequest. + * Constructs a new ImportDocumentsMetadata. * @param [properties] Properties to set */ - constructor(properties?: google.firestore.admin.v1.IDeleteIndexRequest); + constructor(properties?: google.firestore.admin.v1.IImportDocumentsMetadata); - /** DeleteIndexRequest name. */ - public name: string; + /** ImportDocumentsMetadata startTime. */ + public startTime?: (google.protobuf.ITimestamp|null); + + /** ImportDocumentsMetadata endTime. */ + public endTime?: (google.protobuf.ITimestamp|null); + + /** ImportDocumentsMetadata operationState. */ + public operationState: google.firestore.admin.v1.OperationState; + + /** ImportDocumentsMetadata progressDocuments. */ + public progressDocuments?: (google.firestore.admin.v1.IProgress|null); + + /** ImportDocumentsMetadata progressBytes. */ + public progressBytes?: (google.firestore.admin.v1.IProgress|null); + + /** ImportDocumentsMetadata collectionIds. */ + public collectionIds: string[]; + + /** ImportDocumentsMetadata inputUriPrefix. */ + public inputUriPrefix: string; + + /** ImportDocumentsMetadata namespaceIds. */ + public namespaceIds: string[]; /** - * Creates a DeleteIndexRequest message from a plain object. Also converts values to their respective internal types. + * Creates an ImportDocumentsMetadata message from a plain object. Also converts values to their respective internal types. * @param object Plain object - * @returns DeleteIndexRequest + * @returns ImportDocumentsMetadata */ - public static fromObject(object: { [k: string]: any }): google.firestore.admin.v1.DeleteIndexRequest; + public static fromObject(object: { [k: string]: any }): google.firestore.admin.v1.ImportDocumentsMetadata; /** - * Creates a plain object from a DeleteIndexRequest message. Also converts values to other types if specified. - * @param message DeleteIndexRequest + * Creates a plain object from an ImportDocumentsMetadata message. Also converts values to other types if specified. + * @param message ImportDocumentsMetadata * @param [options] Conversion options * @returns Plain object */ - public static toObject(message: google.firestore.admin.v1.DeleteIndexRequest, options?: $protobuf.IConversionOptions): { [k: string]: any }; + public static toObject(message: google.firestore.admin.v1.ImportDocumentsMetadata, options?: $protobuf.IConversionOptions): { [k: string]: any }; /** - * Converts this DeleteIndexRequest to JSON. + * Converts this ImportDocumentsMetadata to JSON. * @returns JSON object */ public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for ImportDocumentsMetadata + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; } - /** Properties of an UpdateFieldRequest. */ - interface IUpdateFieldRequest { + /** Properties of a BulkDeleteDocumentsMetadata. */ + interface IBulkDeleteDocumentsMetadata { - /** UpdateFieldRequest field */ - field?: (google.firestore.admin.v1.IField|null); + /** BulkDeleteDocumentsMetadata startTime */ + startTime?: (google.protobuf.ITimestamp|null); - /** UpdateFieldRequest updateMask */ - updateMask?: (google.protobuf.IFieldMask|null); + /** BulkDeleteDocumentsMetadata endTime */ + endTime?: (google.protobuf.ITimestamp|null); + + /** BulkDeleteDocumentsMetadata operationState */ + operationState?: (google.firestore.admin.v1.OperationState|null); + + /** BulkDeleteDocumentsMetadata progressDocuments */ + progressDocuments?: (google.firestore.admin.v1.IProgress|null); + + /** BulkDeleteDocumentsMetadata progressBytes */ + progressBytes?: (google.firestore.admin.v1.IProgress|null); + + /** BulkDeleteDocumentsMetadata collectionIds */ + collectionIds?: (string[]|null); + + /** BulkDeleteDocumentsMetadata namespaceIds */ + namespaceIds?: (string[]|null); + + /** BulkDeleteDocumentsMetadata snapshotTime */ + snapshotTime?: (google.protobuf.ITimestamp|null); } - /** Represents an UpdateFieldRequest. */ - class UpdateFieldRequest implements IUpdateFieldRequest { + /** Represents a BulkDeleteDocumentsMetadata. */ + class BulkDeleteDocumentsMetadata implements IBulkDeleteDocumentsMetadata { /** - * Constructs a new UpdateFieldRequest. + * Constructs a new BulkDeleteDocumentsMetadata. * @param [properties] Properties to set */ - constructor(properties?: google.firestore.admin.v1.IUpdateFieldRequest); + constructor(properties?: google.firestore.admin.v1.IBulkDeleteDocumentsMetadata); - /** UpdateFieldRequest field. */ - public field?: (google.firestore.admin.v1.IField|null); + /** BulkDeleteDocumentsMetadata startTime. */ + public startTime?: (google.protobuf.ITimestamp|null); - /** UpdateFieldRequest updateMask. */ - public updateMask?: (google.protobuf.IFieldMask|null); + /** BulkDeleteDocumentsMetadata endTime. */ + public endTime?: (google.protobuf.ITimestamp|null); + + /** BulkDeleteDocumentsMetadata operationState. */ + public operationState: google.firestore.admin.v1.OperationState; + + /** BulkDeleteDocumentsMetadata progressDocuments. */ + public progressDocuments?: (google.firestore.admin.v1.IProgress|null); + + /** BulkDeleteDocumentsMetadata progressBytes. */ + public progressBytes?: (google.firestore.admin.v1.IProgress|null); + + /** BulkDeleteDocumentsMetadata collectionIds. */ + public collectionIds: string[]; + + /** BulkDeleteDocumentsMetadata namespaceIds. */ + public namespaceIds: string[]; + + /** BulkDeleteDocumentsMetadata snapshotTime. */ + public snapshotTime?: (google.protobuf.ITimestamp|null); /** - * Creates an UpdateFieldRequest message from a plain object. Also converts values to their respective internal types. + * Creates a BulkDeleteDocumentsMetadata message from a plain object. Also converts values to their respective internal types. * @param object Plain object - * @returns UpdateFieldRequest + * @returns BulkDeleteDocumentsMetadata */ - public static fromObject(object: { [k: string]: any }): google.firestore.admin.v1.UpdateFieldRequest; + public static fromObject(object: { [k: string]: any }): google.firestore.admin.v1.BulkDeleteDocumentsMetadata; /** - * Creates a plain object from an UpdateFieldRequest message. Also converts values to other types if specified. - * @param message UpdateFieldRequest + * Creates a plain object from a BulkDeleteDocumentsMetadata message. Also converts values to other types if specified. + * @param message BulkDeleteDocumentsMetadata * @param [options] Conversion options * @returns Plain object */ - public static toObject(message: google.firestore.admin.v1.UpdateFieldRequest, options?: $protobuf.IConversionOptions): { [k: string]: any }; + public static toObject(message: google.firestore.admin.v1.BulkDeleteDocumentsMetadata, options?: $protobuf.IConversionOptions): { [k: string]: any }; /** - * Converts this UpdateFieldRequest to JSON. + * Converts this BulkDeleteDocumentsMetadata to JSON. * @returns JSON object */ public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for BulkDeleteDocumentsMetadata + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; } - /** Properties of a GetFieldRequest. */ - interface IGetFieldRequest { + /** Properties of an ExportDocumentsResponse. */ + interface IExportDocumentsResponse { - /** GetFieldRequest name */ - name?: (string|null); + /** ExportDocumentsResponse outputUriPrefix */ + outputUriPrefix?: (string|null); } - /** Represents a GetFieldRequest. */ - class GetFieldRequest implements IGetFieldRequest { + /** Represents an ExportDocumentsResponse. */ + class ExportDocumentsResponse implements IExportDocumentsResponse { /** - * Constructs a new GetFieldRequest. + * Constructs a new ExportDocumentsResponse. * @param [properties] Properties to set */ - constructor(properties?: google.firestore.admin.v1.IGetFieldRequest); + constructor(properties?: google.firestore.admin.v1.IExportDocumentsResponse); - /** GetFieldRequest name. */ - public name: string; + /** ExportDocumentsResponse outputUriPrefix. */ + public outputUriPrefix: string; /** - * Creates a GetFieldRequest message from a plain object. Also converts values to their respective internal types. + * Creates an ExportDocumentsResponse message from a plain object. Also converts values to their respective internal types. * @param object Plain object - * @returns GetFieldRequest + * @returns ExportDocumentsResponse */ - public static fromObject(object: { [k: string]: any }): google.firestore.admin.v1.GetFieldRequest; + public static fromObject(object: { [k: string]: any }): google.firestore.admin.v1.ExportDocumentsResponse; /** - * Creates a plain object from a GetFieldRequest message. Also converts values to other types if specified. - * @param message GetFieldRequest + * Creates a plain object from an ExportDocumentsResponse message. Also converts values to other types if specified. + * @param message ExportDocumentsResponse * @param [options] Conversion options * @returns Plain object */ - public static toObject(message: google.firestore.admin.v1.GetFieldRequest, options?: $protobuf.IConversionOptions): { [k: string]: any }; + public static toObject(message: google.firestore.admin.v1.ExportDocumentsResponse, options?: $protobuf.IConversionOptions): { [k: string]: any }; /** - * Converts this GetFieldRequest to JSON. + * Converts this ExportDocumentsResponse to JSON. * @returns JSON object */ public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for ExportDocumentsResponse + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; } - /** Properties of a ListFieldsRequest. */ - interface IListFieldsRequest { + /** Properties of a RestoreDatabaseMetadata. */ + interface IRestoreDatabaseMetadata { + + /** RestoreDatabaseMetadata startTime */ + startTime?: (google.protobuf.ITimestamp|null); + + /** RestoreDatabaseMetadata endTime */ + endTime?: (google.protobuf.ITimestamp|null); - /** ListFieldsRequest parent */ - parent?: (string|null); + /** RestoreDatabaseMetadata operationState */ + operationState?: (google.firestore.admin.v1.OperationState|null); - /** ListFieldsRequest filter */ - filter?: (string|null); + /** RestoreDatabaseMetadata database */ + database?: (string|null); - /** ListFieldsRequest pageSize */ - pageSize?: (number|null); + /** RestoreDatabaseMetadata backup */ + backup?: (string|null); - /** ListFieldsRequest pageToken */ - pageToken?: (string|null); + /** RestoreDatabaseMetadata progressPercentage */ + progressPercentage?: (google.firestore.admin.v1.IProgress|null); } - /** Represents a ListFieldsRequest. */ - class ListFieldsRequest implements IListFieldsRequest { + /** Represents a RestoreDatabaseMetadata. */ + class RestoreDatabaseMetadata implements IRestoreDatabaseMetadata { /** - * Constructs a new ListFieldsRequest. + * Constructs a new RestoreDatabaseMetadata. * @param [properties] Properties to set */ - constructor(properties?: google.firestore.admin.v1.IListFieldsRequest); + constructor(properties?: google.firestore.admin.v1.IRestoreDatabaseMetadata); - /** ListFieldsRequest parent. */ - public parent: string; + /** RestoreDatabaseMetadata startTime. */ + public startTime?: (google.protobuf.ITimestamp|null); - /** ListFieldsRequest filter. */ - public filter: string; + /** RestoreDatabaseMetadata endTime. */ + public endTime?: (google.protobuf.ITimestamp|null); - /** ListFieldsRequest pageSize. */ - public pageSize: number; + /** RestoreDatabaseMetadata operationState. */ + public operationState: google.firestore.admin.v1.OperationState; - /** ListFieldsRequest pageToken. */ - public pageToken: string; + /** RestoreDatabaseMetadata database. */ + public database: string; + + /** RestoreDatabaseMetadata backup. */ + public backup: string; + + /** RestoreDatabaseMetadata progressPercentage. */ + public progressPercentage?: (google.firestore.admin.v1.IProgress|null); /** - * Creates a ListFieldsRequest message from a plain object. Also converts values to their respective internal types. + * Creates a RestoreDatabaseMetadata message from a plain object. Also converts values to their respective internal types. * @param object Plain object - * @returns ListFieldsRequest + * @returns RestoreDatabaseMetadata */ - public static fromObject(object: { [k: string]: any }): google.firestore.admin.v1.ListFieldsRequest; + public static fromObject(object: { [k: string]: any }): google.firestore.admin.v1.RestoreDatabaseMetadata; /** - * Creates a plain object from a ListFieldsRequest message. Also converts values to other types if specified. - * @param message ListFieldsRequest + * Creates a plain object from a RestoreDatabaseMetadata message. Also converts values to other types if specified. + * @param message RestoreDatabaseMetadata * @param [options] Conversion options * @returns Plain object */ - public static toObject(message: google.firestore.admin.v1.ListFieldsRequest, options?: $protobuf.IConversionOptions): { [k: string]: any }; + public static toObject(message: google.firestore.admin.v1.RestoreDatabaseMetadata, options?: $protobuf.IConversionOptions): { [k: string]: any }; /** - * Converts this ListFieldsRequest to JSON. + * Converts this RestoreDatabaseMetadata to JSON. * @returns JSON object */ public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for RestoreDatabaseMetadata + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; } - /** Properties of a ListFieldsResponse. */ - interface IListFieldsResponse { + /** Properties of a Progress. */ + interface IProgress { - /** ListFieldsResponse fields */ - fields?: (google.firestore.admin.v1.IField[]|null); + /** Progress estimatedWork */ + estimatedWork?: (number|string|null); - /** ListFieldsResponse nextPageToken */ - nextPageToken?: (string|null); + /** Progress completedWork */ + completedWork?: (number|string|null); } - /** Represents a ListFieldsResponse. */ - class ListFieldsResponse implements IListFieldsResponse { + /** Represents a Progress. */ + class Progress implements IProgress { /** - * Constructs a new ListFieldsResponse. + * Constructs a new Progress. * @param [properties] Properties to set */ - constructor(properties?: google.firestore.admin.v1.IListFieldsResponse); + constructor(properties?: google.firestore.admin.v1.IProgress); - /** ListFieldsResponse fields. */ - public fields: google.firestore.admin.v1.IField[]; + /** Progress estimatedWork. */ + public estimatedWork: (number|string); - /** ListFieldsResponse nextPageToken. */ - public nextPageToken: string; + /** Progress completedWork. */ + public completedWork: (number|string); /** - * Creates a ListFieldsResponse message from a plain object. Also converts values to their respective internal types. + * Creates a Progress message from a plain object. Also converts values to their respective internal types. * @param object Plain object - * @returns ListFieldsResponse + * @returns Progress */ - public static fromObject(object: { [k: string]: any }): google.firestore.admin.v1.ListFieldsResponse; + public static fromObject(object: { [k: string]: any }): google.firestore.admin.v1.Progress; /** - * Creates a plain object from a ListFieldsResponse message. Also converts values to other types if specified. - * @param message ListFieldsResponse + * Creates a plain object from a Progress message. Also converts values to other types if specified. + * @param message Progress * @param [options] Conversion options * @returns Plain object */ - public static toObject(message: google.firestore.admin.v1.ListFieldsResponse, options?: $protobuf.IConversionOptions): { [k: string]: any }; + public static toObject(message: google.firestore.admin.v1.Progress, options?: $protobuf.IConversionOptions): { [k: string]: any }; /** - * Converts this ListFieldsResponse to JSON. + * Converts this Progress to JSON. * @returns JSON object */ public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for Progress + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; } - /** Properties of an ExportDocumentsRequest. */ - interface IExportDocumentsRequest { + /** OperationState enum. */ + type OperationState = + "OPERATION_STATE_UNSPECIFIED"| "INITIALIZING"| "PROCESSING"| "CANCELLING"| "FINALIZING"| "SUCCESSFUL"| "FAILED"| "CANCELLED"; - /** ExportDocumentsRequest name */ + /** Properties of a BackupSchedule. */ + interface IBackupSchedule { + + /** BackupSchedule name */ name?: (string|null); - /** ExportDocumentsRequest collectionIds */ - collectionIds?: (string[]|null); + /** BackupSchedule createTime */ + createTime?: (google.protobuf.ITimestamp|null); - /** ExportDocumentsRequest outputUriPrefix */ - outputUriPrefix?: (string|null); + /** BackupSchedule updateTime */ + updateTime?: (google.protobuf.ITimestamp|null); + + /** BackupSchedule retention */ + retention?: (google.protobuf.IDuration|null); + + /** BackupSchedule dailyRecurrence */ + dailyRecurrence?: (google.firestore.admin.v1.IDailyRecurrence|null); + + /** BackupSchedule weeklyRecurrence */ + weeklyRecurrence?: (google.firestore.admin.v1.IWeeklyRecurrence|null); } - /** Represents an ExportDocumentsRequest. */ - class ExportDocumentsRequest implements IExportDocumentsRequest { + /** Represents a BackupSchedule. */ + class BackupSchedule implements IBackupSchedule { /** - * Constructs a new ExportDocumentsRequest. + * Constructs a new BackupSchedule. * @param [properties] Properties to set */ - constructor(properties?: google.firestore.admin.v1.IExportDocumentsRequest); + constructor(properties?: google.firestore.admin.v1.IBackupSchedule); - /** ExportDocumentsRequest name. */ + /** BackupSchedule name. */ public name: string; - /** ExportDocumentsRequest collectionIds. */ - public collectionIds: string[]; + /** BackupSchedule createTime. */ + public createTime?: (google.protobuf.ITimestamp|null); - /** ExportDocumentsRequest outputUriPrefix. */ - public outputUriPrefix: string; + /** BackupSchedule updateTime. */ + public updateTime?: (google.protobuf.ITimestamp|null); + + /** BackupSchedule retention. */ + public retention?: (google.protobuf.IDuration|null); + + /** BackupSchedule dailyRecurrence. */ + public dailyRecurrence?: (google.firestore.admin.v1.IDailyRecurrence|null); + + /** BackupSchedule weeklyRecurrence. */ + public weeklyRecurrence?: (google.firestore.admin.v1.IWeeklyRecurrence|null); + + /** BackupSchedule recurrence. */ + public recurrence?: ("dailyRecurrence"|"weeklyRecurrence"); /** - * Creates an ExportDocumentsRequest message from a plain object. Also converts values to their respective internal types. + * Creates a BackupSchedule message from a plain object. Also converts values to their respective internal types. * @param object Plain object - * @returns ExportDocumentsRequest + * @returns BackupSchedule */ - public static fromObject(object: { [k: string]: any }): google.firestore.admin.v1.ExportDocumentsRequest; + public static fromObject(object: { [k: string]: any }): google.firestore.admin.v1.BackupSchedule; /** - * Creates a plain object from an ExportDocumentsRequest message. Also converts values to other types if specified. - * @param message ExportDocumentsRequest + * Creates a plain object from a BackupSchedule message. Also converts values to other types if specified. + * @param message BackupSchedule * @param [options] Conversion options * @returns Plain object */ - public static toObject(message: google.firestore.admin.v1.ExportDocumentsRequest, options?: $protobuf.IConversionOptions): { [k: string]: any }; + public static toObject(message: google.firestore.admin.v1.BackupSchedule, options?: $protobuf.IConversionOptions): { [k: string]: any }; /** - * Converts this ExportDocumentsRequest to JSON. + * Converts this BackupSchedule to JSON. * @returns JSON object */ public toJSON(): { [k: string]: any }; - } - - /** Properties of an ImportDocumentsRequest. */ - interface IImportDocumentsRequest { - - /** ImportDocumentsRequest name */ - name?: (string|null); - /** ImportDocumentsRequest collectionIds */ - collectionIds?: (string[]|null); + /** + * Gets the default type url for BackupSchedule + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } - /** ImportDocumentsRequest inputUriPrefix */ - inputUriPrefix?: (string|null); + /** Properties of a DailyRecurrence. */ + interface IDailyRecurrence { } - /** Represents an ImportDocumentsRequest. */ - class ImportDocumentsRequest implements IImportDocumentsRequest { + /** Represents a DailyRecurrence. */ + class DailyRecurrence implements IDailyRecurrence { /** - * Constructs a new ImportDocumentsRequest. + * Constructs a new DailyRecurrence. * @param [properties] Properties to set */ - constructor(properties?: google.firestore.admin.v1.IImportDocumentsRequest); - - /** ImportDocumentsRequest name. */ - public name: string; - - /** ImportDocumentsRequest collectionIds. */ - public collectionIds: string[]; - - /** ImportDocumentsRequest inputUriPrefix. */ - public inputUriPrefix: string; + constructor(properties?: google.firestore.admin.v1.IDailyRecurrence); /** - * Creates an ImportDocumentsRequest message from a plain object. Also converts values to their respective internal types. + * Creates a DailyRecurrence message from a plain object. Also converts values to their respective internal types. * @param object Plain object - * @returns ImportDocumentsRequest + * @returns DailyRecurrence */ - public static fromObject(object: { [k: string]: any }): google.firestore.admin.v1.ImportDocumentsRequest; + public static fromObject(object: { [k: string]: any }): google.firestore.admin.v1.DailyRecurrence; /** - * Creates a plain object from an ImportDocumentsRequest message. Also converts values to other types if specified. - * @param message ImportDocumentsRequest + * Creates a plain object from a DailyRecurrence message. Also converts values to other types if specified. + * @param message DailyRecurrence * @param [options] Conversion options * @returns Plain object */ - public static toObject(message: google.firestore.admin.v1.ImportDocumentsRequest, options?: $protobuf.IConversionOptions): { [k: string]: any }; + public static toObject(message: google.firestore.admin.v1.DailyRecurrence, options?: $protobuf.IConversionOptions): { [k: string]: any }; /** - * Converts this ImportDocumentsRequest to JSON. + * Converts this DailyRecurrence to JSON. * @returns JSON object */ public toJSON(): { [k: string]: any }; - } - - /** Properties of an Index. */ - interface IIndex { - /** Index name */ - name?: (string|null); - - /** Index queryScope */ - queryScope?: (google.firestore.admin.v1.Index.QueryScope|null); + /** + * Gets the default type url for DailyRecurrence + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } - /** Index fields */ - fields?: (google.firestore.admin.v1.Index.IIndexField[]|null); + /** Properties of a WeeklyRecurrence. */ + interface IWeeklyRecurrence { - /** Index state */ - state?: (google.firestore.admin.v1.Index.State|null); + /** WeeklyRecurrence day */ + day?: (google.type.DayOfWeek|null); } - /** Represents an Index. */ - class Index implements IIndex { + /** Represents a WeeklyRecurrence. */ + class WeeklyRecurrence implements IWeeklyRecurrence { /** - * Constructs a new Index. + * Constructs a new WeeklyRecurrence. * @param [properties] Properties to set */ - constructor(properties?: google.firestore.admin.v1.IIndex); - - /** Index name. */ - public name: string; - - /** Index queryScope. */ - public queryScope: google.firestore.admin.v1.Index.QueryScope; - - /** Index fields. */ - public fields: google.firestore.admin.v1.Index.IIndexField[]; + constructor(properties?: google.firestore.admin.v1.IWeeklyRecurrence); - /** Index state. */ - public state: google.firestore.admin.v1.Index.State; + /** WeeklyRecurrence day. */ + public day: google.type.DayOfWeek; /** - * Creates an Index message from a plain object. Also converts values to their respective internal types. + * Creates a WeeklyRecurrence message from a plain object. Also converts values to their respective internal types. * @param object Plain object - * @returns Index + * @returns WeeklyRecurrence */ - public static fromObject(object: { [k: string]: any }): google.firestore.admin.v1.Index; + public static fromObject(object: { [k: string]: any }): google.firestore.admin.v1.WeeklyRecurrence; /** - * Creates a plain object from an Index message. Also converts values to other types if specified. - * @param message Index + * Creates a plain object from a WeeklyRecurrence message. Also converts values to other types if specified. + * @param message WeeklyRecurrence * @param [options] Conversion options * @returns Plain object */ - public static toObject(message: google.firestore.admin.v1.Index, options?: $protobuf.IConversionOptions): { [k: string]: any }; + public static toObject(message: google.firestore.admin.v1.WeeklyRecurrence, options?: $protobuf.IConversionOptions): { [k: string]: any }; /** - * Converts this Index to JSON. + * Converts this WeeklyRecurrence to JSON. * @returns JSON object */ public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for WeeklyRecurrence + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; } - namespace Index { + /** Properties of a LocationMetadata. */ + interface ILocationMetadata { + } - /** Properties of an IndexField. */ - interface IIndexField { + /** Represents a LocationMetadata. */ + class LocationMetadata implements ILocationMetadata { - /** IndexField fieldPath */ - fieldPath?: (string|null); + /** + * Constructs a new LocationMetadata. + * @param [properties] Properties to set + */ + constructor(properties?: google.firestore.admin.v1.ILocationMetadata); - /** IndexField order */ - order?: (google.firestore.admin.v1.Index.IndexField.Order|null); + /** + * Creates a LocationMetadata message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns LocationMetadata + */ + public static fromObject(object: { [k: string]: any }): google.firestore.admin.v1.LocationMetadata; - /** IndexField arrayConfig */ - arrayConfig?: (google.firestore.admin.v1.Index.IndexField.ArrayConfig|null); + /** + * Creates a plain object from a LocationMetadata message. Also converts values to other types if specified. + * @param message LocationMetadata + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.firestore.admin.v1.LocationMetadata, options?: $protobuf.IConversionOptions): { [k: string]: any }; - /** IndexField vectorConfig */ - vectorConfig?: (google.firestore.admin.v1.Index.IndexField.IVectorConfig|null); - } + /** + * Converts this LocationMetadata to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; - /** Represents an IndexField. */ - class IndexField implements IIndexField { + /** + * Gets the default type url for LocationMetadata + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + } + } + } - /** - * Constructs a new IndexField. - * @param [properties] Properties to set - */ - constructor(properties?: google.firestore.admin.v1.Index.IIndexField); + /** Namespace api. */ + namespace api { + + /** FieldBehavior enum. */ + type FieldBehavior = + "FIELD_BEHAVIOR_UNSPECIFIED"| "OPTIONAL"| "REQUIRED"| "OUTPUT_ONLY"| "INPUT_ONLY"| "IMMUTABLE"| "UNORDERED_LIST"| "NON_EMPTY_DEFAULT"| "IDENTIFIER"; + + /** Properties of a ResourceDescriptor. */ + interface IResourceDescriptor { + + /** ResourceDescriptor type */ + type?: (string|null); - /** IndexField fieldPath. */ - public fieldPath: string; + /** ResourceDescriptor pattern */ + pattern?: (string[]|null); - /** IndexField order. */ - public order?: (google.firestore.admin.v1.Index.IndexField.Order|null); + /** ResourceDescriptor nameField */ + nameField?: (string|null); - /** IndexField arrayConfig. */ - public arrayConfig?: (google.firestore.admin.v1.Index.IndexField.ArrayConfig|null); + /** ResourceDescriptor history */ + history?: (google.api.ResourceDescriptor.History|null); - /** IndexField vectorConfig. */ - public vectorConfig?: (google.firestore.admin.v1.Index.IndexField.IVectorConfig|null); + /** ResourceDescriptor plural */ + plural?: (string|null); - /** IndexField valueMode. */ - public valueMode?: ("order"|"arrayConfig"|"vectorConfig"); + /** ResourceDescriptor singular */ + singular?: (string|null); - /** - * Creates an IndexField message from a plain object. Also converts values to their respective internal types. - * @param object Plain object - * @returns IndexField - */ - public static fromObject(object: { [k: string]: any }): google.firestore.admin.v1.Index.IndexField; + /** ResourceDescriptor style */ + style?: (google.api.ResourceDescriptor.Style[]|null); + } - /** - * Creates a plain object from an IndexField message. Also converts values to other types if specified. - * @param message IndexField - * @param [options] Conversion options - * @returns Plain object - */ - public static toObject(message: google.firestore.admin.v1.Index.IndexField, options?: $protobuf.IConversionOptions): { [k: string]: any }; + /** Represents a ResourceDescriptor. */ + class ResourceDescriptor implements IResourceDescriptor { - /** - * Converts this IndexField to JSON. - * @returns JSON object - */ - public toJSON(): { [k: string]: any }; - } + /** + * Constructs a new ResourceDescriptor. + * @param [properties] Properties to set + */ + constructor(properties?: google.api.IResourceDescriptor); - namespace IndexField { + /** ResourceDescriptor type. */ + public type: string; - /** Order enum. */ - type Order = - "ORDER_UNSPECIFIED"| "ASCENDING"| "DESCENDING"; + /** ResourceDescriptor pattern. */ + public pattern: string[]; - /** ArrayConfig enum. */ - type ArrayConfig = - "ARRAY_CONFIG_UNSPECIFIED"| "CONTAINS"; + /** ResourceDescriptor nameField. */ + public nameField: string; - /** Properties of a VectorConfig. */ - interface IVectorConfig { + /** ResourceDescriptor history. */ + public history: google.api.ResourceDescriptor.History; - /** VectorConfig dimension */ - dimension?: (number|null); + /** ResourceDescriptor plural. */ + public plural: string; - /** VectorConfig flat */ - flat?: (google.firestore.admin.v1.Index.IndexField.VectorConfig.IFlatIndex|null); - } + /** ResourceDescriptor singular. */ + public singular: string; - /** Represents a VectorConfig. */ - class VectorConfig implements IVectorConfig { + /** ResourceDescriptor style. */ + public style: google.api.ResourceDescriptor.Style[]; - /** - * Constructs a new VectorConfig. - * @param [properties] Properties to set - */ - constructor(properties?: google.firestore.admin.v1.Index.IndexField.IVectorConfig); + /** + * Creates a ResourceDescriptor message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns ResourceDescriptor + */ + public static fromObject(object: { [k: string]: any }): google.api.ResourceDescriptor; - /** VectorConfig dimension. */ - public dimension: number; + /** + * Creates a plain object from a ResourceDescriptor message. Also converts values to other types if specified. + * @param message ResourceDescriptor + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.api.ResourceDescriptor, options?: $protobuf.IConversionOptions): { [k: string]: any }; - /** VectorConfig flat. */ - public flat?: (google.firestore.admin.v1.Index.IndexField.VectorConfig.IFlatIndex|null); + /** + * Converts this ResourceDescriptor to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; - /** VectorConfig type. */ - public type?: "flat"; + /** + * Gets the default type url for ResourceDescriptor + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } - /** - * Creates a VectorConfig message from a plain object. Also converts values to their respective internal types. - * @param object Plain object - * @returns VectorConfig - */ - public static fromObject(object: { [k: string]: any }): google.firestore.admin.v1.Index.IndexField.VectorConfig; + namespace ResourceDescriptor { - /** - * Creates a plain object from a VectorConfig message. Also converts values to other types if specified. - * @param message VectorConfig - * @param [options] Conversion options - * @returns Plain object - */ - public static toObject(message: google.firestore.admin.v1.Index.IndexField.VectorConfig, options?: $protobuf.IConversionOptions): { [k: string]: any }; + /** History enum. */ + type History = + "HISTORY_UNSPECIFIED"| "ORIGINALLY_SINGLE_PATTERN"| "FUTURE_MULTI_PATTERN"; - /** - * Converts this VectorConfig to JSON. - * @returns JSON object - */ - public toJSON(): { [k: string]: any }; + /** Style enum. */ + type Style = + "STYLE_UNSPECIFIED"| "DECLARATIVE_FRIENDLY"; + } - /** - * Gets the default type url for VectorConfig - * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") - * @returns The default type url - */ - public static getTypeUrl(typeUrlPrefix?: string): string; - } + /** Properties of a ResourceReference. */ + interface IResourceReference { - namespace VectorConfig { + /** ResourceReference type */ + type?: (string|null); - /** Properties of a FlatIndex. */ - interface IFlatIndex { - } + /** ResourceReference childType */ + childType?: (string|null); + } - /** Represents a FlatIndex. */ - class FlatIndex implements IFlatIndex { + /** Represents a ResourceReference. */ + class ResourceReference implements IResourceReference { - /** - * Constructs a new FlatIndex. - * @param [properties] Properties to set - */ - constructor(properties?: google.firestore.admin.v1.Index.IndexField.VectorConfig.IFlatIndex); + /** + * Constructs a new ResourceReference. + * @param [properties] Properties to set + */ + constructor(properties?: google.api.IResourceReference); - /** - * Creates a FlatIndex message from a plain object. Also converts values to their respective internal types. - * @param object Plain object - * @returns FlatIndex - */ - public static fromObject(object: { [k: string]: any }): google.firestore.admin.v1.Index.IndexField.VectorConfig.FlatIndex; + /** ResourceReference type. */ + public type: string; - /** - * Creates a plain object from a FlatIndex message. Also converts values to other types if specified. - * @param message FlatIndex - * @param [options] Conversion options - * @returns Plain object - */ - public static toObject(message: google.firestore.admin.v1.Index.IndexField.VectorConfig.FlatIndex, options?: $protobuf.IConversionOptions): { [k: string]: any }; + /** ResourceReference childType. */ + public childType: string; - /** - * Converts this FlatIndex to JSON. - * @returns JSON object - */ - public toJSON(): { [k: string]: any }; + /** + * Creates a ResourceReference message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns ResourceReference + */ + public static fromObject(object: { [k: string]: any }): google.api.ResourceReference; - /** - * Gets the default type url for FlatIndex - * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") - * @returns The default type url - */ - public static getTypeUrl(typeUrlPrefix?: string): string; - } - } - } + /** + * Creates a plain object from a ResourceReference message. Also converts values to other types if specified. + * @param message ResourceReference + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.api.ResourceReference, options?: $protobuf.IConversionOptions): { [k: string]: any }; - /** QueryScope enum. */ - type QueryScope = - "QUERY_SCOPE_UNSPECIFIED"| "COLLECTION"| "COLLECTION_GROUP"; + /** + * Converts this ResourceReference to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; - /** State enum. */ - type State = - "STATE_UNSPECIFIED"| "CREATING"| "READY"| "NEEDS_REPAIR"; - } + /** + * Gets the default type url for ResourceReference + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } - /** Properties of a LocationMetadata. */ - interface ILocationMetadata { - } + /** Properties of a Http. */ + interface IHttp { - /** Represents a LocationMetadata. */ - class LocationMetadata implements ILocationMetadata { + /** Http rules */ + rules?: (google.api.IHttpRule[]|null); - /** - * Constructs a new LocationMetadata. - * @param [properties] Properties to set - */ - constructor(properties?: google.firestore.admin.v1.ILocationMetadata); + /** Http fullyDecodeReservedExpansion */ + fullyDecodeReservedExpansion?: (boolean|null); + } - /** - * Creates a LocationMetadata message from a plain object. Also converts values to their respective internal types. - * @param object Plain object - * @returns LocationMetadata - */ - public static fromObject(object: { [k: string]: any }): google.firestore.admin.v1.LocationMetadata; + /** Represents a Http. */ + class Http implements IHttp { + + /** + * Constructs a new Http. + * @param [properties] Properties to set + */ + constructor(properties?: google.api.IHttp); - /** - * Creates a plain object from a LocationMetadata message. Also converts values to other types if specified. - * @param message LocationMetadata - * @param [options] Conversion options - * @returns Plain object - */ - public static toObject(message: google.firestore.admin.v1.LocationMetadata, options?: $protobuf.IConversionOptions): { [k: string]: any }; + /** Http rules. */ + public rules: google.api.IHttpRule[]; - /** - * Converts this LocationMetadata to JSON. - * @returns JSON object - */ - public toJSON(): { [k: string]: any }; - } + /** Http fullyDecodeReservedExpansion. */ + public fullyDecodeReservedExpansion: boolean; - /** Properties of an IndexOperationMetadata. */ - interface IIndexOperationMetadata { + /** + * Creates a Http message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns Http + */ + public static fromObject(object: { [k: string]: any }): google.api.Http; - /** IndexOperationMetadata startTime */ - startTime?: (google.protobuf.ITimestamp|null); + /** + * Creates a plain object from a Http message. Also converts values to other types if specified. + * @param message Http + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.api.Http, options?: $protobuf.IConversionOptions): { [k: string]: any }; - /** IndexOperationMetadata endTime */ - endTime?: (google.protobuf.ITimestamp|null); + /** + * Converts this Http to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; - /** IndexOperationMetadata index */ - index?: (string|null); + /** + * Gets the default type url for Http + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } - /** IndexOperationMetadata state */ - state?: (google.firestore.admin.v1.OperationState|null); + /** Properties of a HttpRule. */ + interface IHttpRule { - /** IndexOperationMetadata progressDocuments */ - progressDocuments?: (google.firestore.admin.v1.IProgress|null); + /** HttpRule selector */ + selector?: (string|null); - /** IndexOperationMetadata progressBytes */ - progressBytes?: (google.firestore.admin.v1.IProgress|null); - } + /** HttpRule get */ + get?: (string|null); - /** Represents an IndexOperationMetadata. */ - class IndexOperationMetadata implements IIndexOperationMetadata { + /** HttpRule put */ + put?: (string|null); - /** - * Constructs a new IndexOperationMetadata. - * @param [properties] Properties to set - */ - constructor(properties?: google.firestore.admin.v1.IIndexOperationMetadata); + /** HttpRule post */ + post?: (string|null); - /** IndexOperationMetadata startTime. */ - public startTime?: (google.protobuf.ITimestamp|null); + /** HttpRule delete */ + "delete"?: (string|null); - /** IndexOperationMetadata endTime. */ - public endTime?: (google.protobuf.ITimestamp|null); + /** HttpRule patch */ + patch?: (string|null); - /** IndexOperationMetadata index. */ - public index: string; + /** HttpRule custom */ + custom?: (google.api.ICustomHttpPattern|null); - /** IndexOperationMetadata state. */ - public state: google.firestore.admin.v1.OperationState; + /** HttpRule body */ + body?: (string|null); - /** IndexOperationMetadata progressDocuments. */ - public progressDocuments?: (google.firestore.admin.v1.IProgress|null); + /** HttpRule responseBody */ + responseBody?: (string|null); - /** IndexOperationMetadata progressBytes. */ - public progressBytes?: (google.firestore.admin.v1.IProgress|null); + /** HttpRule additionalBindings */ + additionalBindings?: (google.api.IHttpRule[]|null); + } - /** - * Creates an IndexOperationMetadata message from a plain object. Also converts values to their respective internal types. - * @param object Plain object - * @returns IndexOperationMetadata - */ - public static fromObject(object: { [k: string]: any }): google.firestore.admin.v1.IndexOperationMetadata; + /** Represents a HttpRule. */ + class HttpRule implements IHttpRule { - /** - * Creates a plain object from an IndexOperationMetadata message. Also converts values to other types if specified. - * @param message IndexOperationMetadata - * @param [options] Conversion options - * @returns Plain object - */ - public static toObject(message: google.firestore.admin.v1.IndexOperationMetadata, options?: $protobuf.IConversionOptions): { [k: string]: any }; + /** + * Constructs a new HttpRule. + * @param [properties] Properties to set + */ + constructor(properties?: google.api.IHttpRule); - /** - * Converts this IndexOperationMetadata to JSON. - * @returns JSON object - */ - public toJSON(): { [k: string]: any }; - } + /** HttpRule selector. */ + public selector: string; - /** Properties of a FieldOperationMetadata. */ - interface IFieldOperationMetadata { + /** HttpRule get. */ + public get?: (string|null); - /** FieldOperationMetadata startTime */ - startTime?: (google.protobuf.ITimestamp|null); + /** HttpRule put. */ + public put?: (string|null); - /** FieldOperationMetadata endTime */ - endTime?: (google.protobuf.ITimestamp|null); + /** HttpRule post. */ + public post?: (string|null); - /** FieldOperationMetadata field */ - field?: (string|null); + /** HttpRule delete. */ + public delete?: (string|null); - /** FieldOperationMetadata indexConfigDeltas */ - indexConfigDeltas?: (google.firestore.admin.v1.FieldOperationMetadata.IIndexConfigDelta[]|null); + /** HttpRule patch. */ + public patch?: (string|null); - /** FieldOperationMetadata state */ - state?: (google.firestore.admin.v1.OperationState|null); + /** HttpRule custom. */ + public custom?: (google.api.ICustomHttpPattern|null); - /** FieldOperationMetadata progressDocuments */ - progressDocuments?: (google.firestore.admin.v1.IProgress|null); + /** HttpRule body. */ + public body: string; - /** FieldOperationMetadata progressBytes */ - progressBytes?: (google.firestore.admin.v1.IProgress|null); - } + /** HttpRule responseBody. */ + public responseBody: string; - /** Represents a FieldOperationMetadata. */ - class FieldOperationMetadata implements IFieldOperationMetadata { + /** HttpRule additionalBindings. */ + public additionalBindings: google.api.IHttpRule[]; - /** - * Constructs a new FieldOperationMetadata. - * @param [properties] Properties to set - */ - constructor(properties?: google.firestore.admin.v1.IFieldOperationMetadata); + /** HttpRule pattern. */ + public pattern?: ("get"|"put"|"post"|"delete"|"patch"|"custom"); - /** FieldOperationMetadata startTime. */ - public startTime?: (google.protobuf.ITimestamp|null); + /** + * Creates a HttpRule message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns HttpRule + */ + public static fromObject(object: { [k: string]: any }): google.api.HttpRule; - /** FieldOperationMetadata endTime. */ - public endTime?: (google.protobuf.ITimestamp|null); + /** + * Creates a plain object from a HttpRule message. Also converts values to other types if specified. + * @param message HttpRule + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.api.HttpRule, options?: $protobuf.IConversionOptions): { [k: string]: any }; - /** FieldOperationMetadata field. */ - public field: string; + /** + * Converts this HttpRule to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; - /** FieldOperationMetadata indexConfigDeltas. */ - public indexConfigDeltas: google.firestore.admin.v1.FieldOperationMetadata.IIndexConfigDelta[]; + /** + * Gets the default type url for HttpRule + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } - /** FieldOperationMetadata state. */ - public state: google.firestore.admin.v1.OperationState; + /** Properties of a CustomHttpPattern. */ + interface ICustomHttpPattern { - /** FieldOperationMetadata progressDocuments. */ - public progressDocuments?: (google.firestore.admin.v1.IProgress|null); + /** CustomHttpPattern kind */ + kind?: (string|null); - /** FieldOperationMetadata progressBytes. */ - public progressBytes?: (google.firestore.admin.v1.IProgress|null); + /** CustomHttpPattern path */ + path?: (string|null); + } - /** - * Creates a FieldOperationMetadata message from a plain object. Also converts values to their respective internal types. - * @param object Plain object - * @returns FieldOperationMetadata - */ - public static fromObject(object: { [k: string]: any }): google.firestore.admin.v1.FieldOperationMetadata; + /** Represents a CustomHttpPattern. */ + class CustomHttpPattern implements ICustomHttpPattern { - /** - * Creates a plain object from a FieldOperationMetadata message. Also converts values to other types if specified. - * @param message FieldOperationMetadata - * @param [options] Conversion options - * @returns Plain object - */ - public static toObject(message: google.firestore.admin.v1.FieldOperationMetadata, options?: $protobuf.IConversionOptions): { [k: string]: any }; + /** + * Constructs a new CustomHttpPattern. + * @param [properties] Properties to set + */ + constructor(properties?: google.api.ICustomHttpPattern); - /** - * Converts this FieldOperationMetadata to JSON. - * @returns JSON object - */ - public toJSON(): { [k: string]: any }; - } + /** CustomHttpPattern kind. */ + public kind: string; - namespace FieldOperationMetadata { + /** CustomHttpPattern path. */ + public path: string; - /** Properties of an IndexConfigDelta. */ - interface IIndexConfigDelta { + /** + * Creates a CustomHttpPattern message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns CustomHttpPattern + */ + public static fromObject(object: { [k: string]: any }): google.api.CustomHttpPattern; + + /** + * Creates a plain object from a CustomHttpPattern message. Also converts values to other types if specified. + * @param message CustomHttpPattern + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.api.CustomHttpPattern, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this CustomHttpPattern to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; - /** IndexConfigDelta changeType */ - changeType?: (google.firestore.admin.v1.FieldOperationMetadata.IndexConfigDelta.ChangeType|null); + /** + * Gets the default type url for CustomHttpPattern + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } - /** IndexConfigDelta index */ - index?: (google.firestore.admin.v1.IIndex|null); - } + /** Properties of a CommonLanguageSettings. */ + interface ICommonLanguageSettings { - /** Represents an IndexConfigDelta. */ - class IndexConfigDelta implements IIndexConfigDelta { + /** CommonLanguageSettings referenceDocsUri */ + referenceDocsUri?: (string|null); - /** - * Constructs a new IndexConfigDelta. - * @param [properties] Properties to set - */ - constructor(properties?: google.firestore.admin.v1.FieldOperationMetadata.IIndexConfigDelta); + /** CommonLanguageSettings destinations */ + destinations?: (google.api.ClientLibraryDestination[]|null); + } - /** IndexConfigDelta changeType. */ - public changeType: google.firestore.admin.v1.FieldOperationMetadata.IndexConfigDelta.ChangeType; + /** Represents a CommonLanguageSettings. */ + class CommonLanguageSettings implements ICommonLanguageSettings { - /** IndexConfigDelta index. */ - public index?: (google.firestore.admin.v1.IIndex|null); + /** + * Constructs a new CommonLanguageSettings. + * @param [properties] Properties to set + */ + constructor(properties?: google.api.ICommonLanguageSettings); - /** - * Creates an IndexConfigDelta message from a plain object. Also converts values to their respective internal types. - * @param object Plain object - * @returns IndexConfigDelta - */ - public static fromObject(object: { [k: string]: any }): google.firestore.admin.v1.FieldOperationMetadata.IndexConfigDelta; + /** CommonLanguageSettings referenceDocsUri. */ + public referenceDocsUri: string; - /** - * Creates a plain object from an IndexConfigDelta message. Also converts values to other types if specified. - * @param message IndexConfigDelta - * @param [options] Conversion options - * @returns Plain object - */ - public static toObject(message: google.firestore.admin.v1.FieldOperationMetadata.IndexConfigDelta, options?: $protobuf.IConversionOptions): { [k: string]: any }; + /** CommonLanguageSettings destinations. */ + public destinations: google.api.ClientLibraryDestination[]; - /** - * Converts this IndexConfigDelta to JSON. - * @returns JSON object - */ - public toJSON(): { [k: string]: any }; - } + /** + * Creates a CommonLanguageSettings message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns CommonLanguageSettings + */ + public static fromObject(object: { [k: string]: any }): google.api.CommonLanguageSettings; - namespace IndexConfigDelta { + /** + * Creates a plain object from a CommonLanguageSettings message. Also converts values to other types if specified. + * @param message CommonLanguageSettings + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.api.CommonLanguageSettings, options?: $protobuf.IConversionOptions): { [k: string]: any }; - /** ChangeType enum. */ - type ChangeType = - "CHANGE_TYPE_UNSPECIFIED"| "ADD"| "REMOVE"; - } - } + /** + * Converts this CommonLanguageSettings to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; - /** Properties of an ExportDocumentsMetadata. */ - interface IExportDocumentsMetadata { + /** + * Gets the default type url for CommonLanguageSettings + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } - /** ExportDocumentsMetadata startTime */ - startTime?: (google.protobuf.ITimestamp|null); + /** Properties of a ClientLibrarySettings. */ + interface IClientLibrarySettings { - /** ExportDocumentsMetadata endTime */ - endTime?: (google.protobuf.ITimestamp|null); + /** ClientLibrarySettings version */ + version?: (string|null); - /** ExportDocumentsMetadata operationState */ - operationState?: (google.firestore.admin.v1.OperationState|null); + /** ClientLibrarySettings launchStage */ + launchStage?: (google.api.LaunchStage|null); - /** ExportDocumentsMetadata progressDocuments */ - progressDocuments?: (google.firestore.admin.v1.IProgress|null); + /** ClientLibrarySettings restNumericEnums */ + restNumericEnums?: (boolean|null); - /** ExportDocumentsMetadata progressBytes */ - progressBytes?: (google.firestore.admin.v1.IProgress|null); + /** ClientLibrarySettings javaSettings */ + javaSettings?: (google.api.IJavaSettings|null); - /** ExportDocumentsMetadata collectionIds */ - collectionIds?: (string[]|null); + /** ClientLibrarySettings cppSettings */ + cppSettings?: (google.api.ICppSettings|null); - /** ExportDocumentsMetadata outputUriPrefix */ - outputUriPrefix?: (string|null); - } + /** ClientLibrarySettings phpSettings */ + phpSettings?: (google.api.IPhpSettings|null); - /** Represents an ExportDocumentsMetadata. */ - class ExportDocumentsMetadata implements IExportDocumentsMetadata { + /** ClientLibrarySettings pythonSettings */ + pythonSettings?: (google.api.IPythonSettings|null); - /** - * Constructs a new ExportDocumentsMetadata. - * @param [properties] Properties to set - */ - constructor(properties?: google.firestore.admin.v1.IExportDocumentsMetadata); + /** ClientLibrarySettings nodeSettings */ + nodeSettings?: (google.api.INodeSettings|null); - /** ExportDocumentsMetadata startTime. */ - public startTime?: (google.protobuf.ITimestamp|null); + /** ClientLibrarySettings dotnetSettings */ + dotnetSettings?: (google.api.IDotnetSettings|null); - /** ExportDocumentsMetadata endTime. */ - public endTime?: (google.protobuf.ITimestamp|null); + /** ClientLibrarySettings rubySettings */ + rubySettings?: (google.api.IRubySettings|null); - /** ExportDocumentsMetadata operationState. */ - public operationState: google.firestore.admin.v1.OperationState; + /** ClientLibrarySettings goSettings */ + goSettings?: (google.api.IGoSettings|null); + } - /** ExportDocumentsMetadata progressDocuments. */ - public progressDocuments?: (google.firestore.admin.v1.IProgress|null); + /** Represents a ClientLibrarySettings. */ + class ClientLibrarySettings implements IClientLibrarySettings { - /** ExportDocumentsMetadata progressBytes. */ - public progressBytes?: (google.firestore.admin.v1.IProgress|null); + /** + * Constructs a new ClientLibrarySettings. + * @param [properties] Properties to set + */ + constructor(properties?: google.api.IClientLibrarySettings); - /** ExportDocumentsMetadata collectionIds. */ - public collectionIds: string[]; + /** ClientLibrarySettings version. */ + public version: string; - /** ExportDocumentsMetadata outputUriPrefix. */ - public outputUriPrefix: string; + /** ClientLibrarySettings launchStage. */ + public launchStage: google.api.LaunchStage; - /** - * Creates an ExportDocumentsMetadata message from a plain object. Also converts values to their respective internal types. - * @param object Plain object - * @returns ExportDocumentsMetadata - */ - public static fromObject(object: { [k: string]: any }): google.firestore.admin.v1.ExportDocumentsMetadata; + /** ClientLibrarySettings restNumericEnums. */ + public restNumericEnums: boolean; - /** - * Creates a plain object from an ExportDocumentsMetadata message. Also converts values to other types if specified. - * @param message ExportDocumentsMetadata - * @param [options] Conversion options - * @returns Plain object - */ - public static toObject(message: google.firestore.admin.v1.ExportDocumentsMetadata, options?: $protobuf.IConversionOptions): { [k: string]: any }; + /** ClientLibrarySettings javaSettings. */ + public javaSettings?: (google.api.IJavaSettings|null); - /** - * Converts this ExportDocumentsMetadata to JSON. - * @returns JSON object - */ - public toJSON(): { [k: string]: any }; - } + /** ClientLibrarySettings cppSettings. */ + public cppSettings?: (google.api.ICppSettings|null); - /** Properties of an ImportDocumentsMetadata. */ - interface IImportDocumentsMetadata { + /** ClientLibrarySettings phpSettings. */ + public phpSettings?: (google.api.IPhpSettings|null); - /** ImportDocumentsMetadata startTime */ - startTime?: (google.protobuf.ITimestamp|null); + /** ClientLibrarySettings pythonSettings. */ + public pythonSettings?: (google.api.IPythonSettings|null); - /** ImportDocumentsMetadata endTime */ - endTime?: (google.protobuf.ITimestamp|null); + /** ClientLibrarySettings nodeSettings. */ + public nodeSettings?: (google.api.INodeSettings|null); - /** ImportDocumentsMetadata operationState */ - operationState?: (google.firestore.admin.v1.OperationState|null); + /** ClientLibrarySettings dotnetSettings. */ + public dotnetSettings?: (google.api.IDotnetSettings|null); - /** ImportDocumentsMetadata progressDocuments */ - progressDocuments?: (google.firestore.admin.v1.IProgress|null); + /** ClientLibrarySettings rubySettings. */ + public rubySettings?: (google.api.IRubySettings|null); - /** ImportDocumentsMetadata progressBytes */ - progressBytes?: (google.firestore.admin.v1.IProgress|null); + /** ClientLibrarySettings goSettings. */ + public goSettings?: (google.api.IGoSettings|null); - /** ImportDocumentsMetadata collectionIds */ - collectionIds?: (string[]|null); + /** + * Creates a ClientLibrarySettings message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns ClientLibrarySettings + */ + public static fromObject(object: { [k: string]: any }): google.api.ClientLibrarySettings; - /** ImportDocumentsMetadata inputUriPrefix */ - inputUriPrefix?: (string|null); - } + /** + * Creates a plain object from a ClientLibrarySettings message. Also converts values to other types if specified. + * @param message ClientLibrarySettings + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.api.ClientLibrarySettings, options?: $protobuf.IConversionOptions): { [k: string]: any }; - /** Represents an ImportDocumentsMetadata. */ - class ImportDocumentsMetadata implements IImportDocumentsMetadata { + /** + * Converts this ClientLibrarySettings to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; - /** - * Constructs a new ImportDocumentsMetadata. - * @param [properties] Properties to set - */ - constructor(properties?: google.firestore.admin.v1.IImportDocumentsMetadata); + /** + * Gets the default type url for ClientLibrarySettings + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } - /** ImportDocumentsMetadata startTime. */ - public startTime?: (google.protobuf.ITimestamp|null); + /** Properties of a Publishing. */ + interface IPublishing { - /** ImportDocumentsMetadata endTime. */ - public endTime?: (google.protobuf.ITimestamp|null); + /** Publishing methodSettings */ + methodSettings?: (google.api.IMethodSettings[]|null); - /** ImportDocumentsMetadata operationState. */ - public operationState: google.firestore.admin.v1.OperationState; + /** Publishing newIssueUri */ + newIssueUri?: (string|null); - /** ImportDocumentsMetadata progressDocuments. */ - public progressDocuments?: (google.firestore.admin.v1.IProgress|null); + /** Publishing documentationUri */ + documentationUri?: (string|null); - /** ImportDocumentsMetadata progressBytes. */ - public progressBytes?: (google.firestore.admin.v1.IProgress|null); + /** Publishing apiShortName */ + apiShortName?: (string|null); - /** ImportDocumentsMetadata collectionIds. */ - public collectionIds: string[]; + /** Publishing githubLabel */ + githubLabel?: (string|null); - /** ImportDocumentsMetadata inputUriPrefix. */ - public inputUriPrefix: string; + /** Publishing codeownerGithubTeams */ + codeownerGithubTeams?: (string[]|null); - /** - * Creates an ImportDocumentsMetadata message from a plain object. Also converts values to their respective internal types. - * @param object Plain object - * @returns ImportDocumentsMetadata - */ - public static fromObject(object: { [k: string]: any }): google.firestore.admin.v1.ImportDocumentsMetadata; + /** Publishing docTagPrefix */ + docTagPrefix?: (string|null); - /** - * Creates a plain object from an ImportDocumentsMetadata message. Also converts values to other types if specified. - * @param message ImportDocumentsMetadata - * @param [options] Conversion options - * @returns Plain object - */ - public static toObject(message: google.firestore.admin.v1.ImportDocumentsMetadata, options?: $protobuf.IConversionOptions): { [k: string]: any }; + /** Publishing organization */ + organization?: (google.api.ClientLibraryOrganization|null); - /** - * Converts this ImportDocumentsMetadata to JSON. - * @returns JSON object - */ - public toJSON(): { [k: string]: any }; - } + /** Publishing librarySettings */ + librarySettings?: (google.api.IClientLibrarySettings[]|null); - /** Properties of an ExportDocumentsResponse. */ - interface IExportDocumentsResponse { + /** Publishing protoReferenceDocumentationUri */ + protoReferenceDocumentationUri?: (string|null); - /** ExportDocumentsResponse outputUriPrefix */ - outputUriPrefix?: (string|null); - } + /** Publishing restReferenceDocumentationUri */ + restReferenceDocumentationUri?: (string|null); + } - /** Represents an ExportDocumentsResponse. */ - class ExportDocumentsResponse implements IExportDocumentsResponse { + /** Represents a Publishing. */ + class Publishing implements IPublishing { - /** - * Constructs a new ExportDocumentsResponse. - * @param [properties] Properties to set - */ - constructor(properties?: google.firestore.admin.v1.IExportDocumentsResponse); + /** + * Constructs a new Publishing. + * @param [properties] Properties to set + */ + constructor(properties?: google.api.IPublishing); - /** ExportDocumentsResponse outputUriPrefix. */ - public outputUriPrefix: string; + /** Publishing methodSettings. */ + public methodSettings: google.api.IMethodSettings[]; - /** - * Creates an ExportDocumentsResponse message from a plain object. Also converts values to their respective internal types. - * @param object Plain object - * @returns ExportDocumentsResponse - */ - public static fromObject(object: { [k: string]: any }): google.firestore.admin.v1.ExportDocumentsResponse; + /** Publishing newIssueUri. */ + public newIssueUri: string; - /** - * Creates a plain object from an ExportDocumentsResponse message. Also converts values to other types if specified. - * @param message ExportDocumentsResponse - * @param [options] Conversion options - * @returns Plain object - */ - public static toObject(message: google.firestore.admin.v1.ExportDocumentsResponse, options?: $protobuf.IConversionOptions): { [k: string]: any }; + /** Publishing documentationUri. */ + public documentationUri: string; - /** - * Converts this ExportDocumentsResponse to JSON. - * @returns JSON object - */ - public toJSON(): { [k: string]: any }; - } + /** Publishing apiShortName. */ + public apiShortName: string; - /** OperationState enum. */ - type OperationState = - "OPERATION_STATE_UNSPECIFIED"| "INITIALIZING"| "PROCESSING"| "CANCELLING"| "FINALIZING"| "SUCCESSFUL"| "FAILED"| "CANCELLED"; + /** Publishing githubLabel. */ + public githubLabel: string; - /** Properties of a Progress. */ - interface IProgress { + /** Publishing codeownerGithubTeams. */ + public codeownerGithubTeams: string[]; - /** Progress estimatedWork */ - estimatedWork?: (number|string|null); + /** Publishing docTagPrefix. */ + public docTagPrefix: string; - /** Progress completedWork */ - completedWork?: (number|string|null); - } + /** Publishing organization. */ + public organization: google.api.ClientLibraryOrganization; - /** Represents a Progress. */ - class Progress implements IProgress { + /** Publishing librarySettings. */ + public librarySettings: google.api.IClientLibrarySettings[]; - /** - * Constructs a new Progress. - * @param [properties] Properties to set - */ - constructor(properties?: google.firestore.admin.v1.IProgress); + /** Publishing protoReferenceDocumentationUri. */ + public protoReferenceDocumentationUri: string; - /** Progress estimatedWork. */ - public estimatedWork: (number|string); + /** Publishing restReferenceDocumentationUri. */ + public restReferenceDocumentationUri: string; - /** Progress completedWork. */ - public completedWork: (number|string); + /** + * Creates a Publishing message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns Publishing + */ + public static fromObject(object: { [k: string]: any }): google.api.Publishing; - /** - * Creates a Progress message from a plain object. Also converts values to their respective internal types. - * @param object Plain object - * @returns Progress - */ - public static fromObject(object: { [k: string]: any }): google.firestore.admin.v1.Progress; + /** + * Creates a plain object from a Publishing message. Also converts values to other types if specified. + * @param message Publishing + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.api.Publishing, options?: $protobuf.IConversionOptions): { [k: string]: any }; - /** - * Creates a plain object from a Progress message. Also converts values to other types if specified. - * @param message Progress - * @param [options] Conversion options - * @returns Plain object - */ - public static toObject(message: google.firestore.admin.v1.Progress, options?: $protobuf.IConversionOptions): { [k: string]: any }; + /** + * Converts this Publishing to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; - /** - * Converts this Progress to JSON. - * @returns JSON object - */ - public toJSON(): { [k: string]: any }; - } - } + /** + * Gets the default type url for Publishing + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; } - } - /** Namespace api. */ - namespace api { + /** Properties of a JavaSettings. */ + interface IJavaSettings { - /** Properties of a Http. */ - interface IHttp { + /** JavaSettings libraryPackage */ + libraryPackage?: (string|null); - /** Http rules */ - rules?: (google.api.IHttpRule[]|null); + /** JavaSettings serviceClassNames */ + serviceClassNames?: ({ [k: string]: string }|null); + + /** JavaSettings common */ + common?: (google.api.ICommonLanguageSettings|null); } - /** Represents a Http. */ - class Http implements IHttp { + /** Represents a JavaSettings. */ + class JavaSettings implements IJavaSettings { /** - * Constructs a new Http. + * Constructs a new JavaSettings. * @param [properties] Properties to set */ - constructor(properties?: google.api.IHttp); + constructor(properties?: google.api.IJavaSettings); - /** Http rules. */ - public rules: google.api.IHttpRule[]; + /** JavaSettings libraryPackage. */ + public libraryPackage: string; + + /** JavaSettings serviceClassNames. */ + public serviceClassNames: { [k: string]: string }; + + /** JavaSettings common. */ + public common?: (google.api.ICommonLanguageSettings|null); /** - * Creates a Http message from a plain object. Also converts values to their respective internal types. + * Creates a JavaSettings message from a plain object. Also converts values to their respective internal types. * @param object Plain object - * @returns Http + * @returns JavaSettings */ - public static fromObject(object: { [k: string]: any }): google.api.Http; + public static fromObject(object: { [k: string]: any }): google.api.JavaSettings; /** - * Creates a plain object from a Http message. Also converts values to other types if specified. - * @param message Http + * Creates a plain object from a JavaSettings message. Also converts values to other types if specified. + * @param message JavaSettings * @param [options] Conversion options * @returns Plain object */ - public static toObject(message: google.api.Http, options?: $protobuf.IConversionOptions): { [k: string]: any }; + public static toObject(message: google.api.JavaSettings, options?: $protobuf.IConversionOptions): { [k: string]: any }; /** - * Converts this Http to JSON. + * Converts this JavaSettings to JSON. * @returns JSON object */ public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for JavaSettings + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; } - /** Properties of a HttpRule. */ - interface IHttpRule { + /** Properties of a CppSettings. */ + interface ICppSettings { - /** HttpRule get */ - get?: (string|null); + /** CppSettings common */ + common?: (google.api.ICommonLanguageSettings|null); + } - /** HttpRule put */ - put?: (string|null); + /** Represents a CppSettings. */ + class CppSettings implements ICppSettings { - /** HttpRule post */ - post?: (string|null); + /** + * Constructs a new CppSettings. + * @param [properties] Properties to set + */ + constructor(properties?: google.api.ICppSettings); - /** HttpRule delete */ - "delete"?: (string|null); + /** CppSettings common. */ + public common?: (google.api.ICommonLanguageSettings|null); - /** HttpRule patch */ - patch?: (string|null); + /** + * Creates a CppSettings message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns CppSettings + */ + public static fromObject(object: { [k: string]: any }): google.api.CppSettings; - /** HttpRule custom */ - custom?: (google.api.ICustomHttpPattern|null); + /** + * Creates a plain object from a CppSettings message. Also converts values to other types if specified. + * @param message CppSettings + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.api.CppSettings, options?: $protobuf.IConversionOptions): { [k: string]: any }; - /** HttpRule selector */ - selector?: (string|null); + /** + * Converts this CppSettings to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; - /** HttpRule body */ - body?: (string|null); + /** + * Gets the default type url for CppSettings + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } - /** HttpRule additionalBindings */ - additionalBindings?: (google.api.IHttpRule[]|null); + /** Properties of a PhpSettings. */ + interface IPhpSettings { + + /** PhpSettings common */ + common?: (google.api.ICommonLanguageSettings|null); } - /** Represents a HttpRule. */ - class HttpRule implements IHttpRule { + /** Represents a PhpSettings. */ + class PhpSettings implements IPhpSettings { /** - * Constructs a new HttpRule. + * Constructs a new PhpSettings. * @param [properties] Properties to set */ - constructor(properties?: google.api.IHttpRule); + constructor(properties?: google.api.IPhpSettings); - /** HttpRule get. */ - public get?: (string|null); + /** PhpSettings common. */ + public common?: (google.api.ICommonLanguageSettings|null); - /** HttpRule put. */ - public put?: (string|null); + /** + * Creates a PhpSettings message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns PhpSettings + */ + public static fromObject(object: { [k: string]: any }): google.api.PhpSettings; - /** HttpRule post. */ - public post?: (string|null); + /** + * Creates a plain object from a PhpSettings message. Also converts values to other types if specified. + * @param message PhpSettings + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.api.PhpSettings, options?: $protobuf.IConversionOptions): { [k: string]: any }; - /** HttpRule delete. */ - public delete?: (string|null); + /** + * Converts this PhpSettings to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; - /** HttpRule patch. */ - public patch?: (string|null); + /** + * Gets the default type url for PhpSettings + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } - /** HttpRule custom. */ - public custom?: (google.api.ICustomHttpPattern|null); + /** Properties of a PythonSettings. */ + interface IPythonSettings { - /** HttpRule selector. */ - public selector: string; + /** PythonSettings common */ + common?: (google.api.ICommonLanguageSettings|null); + } - /** HttpRule body. */ - public body: string; + /** Represents a PythonSettings. */ + class PythonSettings implements IPythonSettings { - /** HttpRule additionalBindings. */ - public additionalBindings: google.api.IHttpRule[]; + /** + * Constructs a new PythonSettings. + * @param [properties] Properties to set + */ + constructor(properties?: google.api.IPythonSettings); - /** HttpRule pattern. */ - public pattern?: ("get"|"put"|"post"|"delete"|"patch"|"custom"); + /** PythonSettings common. */ + public common?: (google.api.ICommonLanguageSettings|null); /** - * Creates a HttpRule message from a plain object. Also converts values to their respective internal types. + * Creates a PythonSettings message from a plain object. Also converts values to their respective internal types. * @param object Plain object - * @returns HttpRule + * @returns PythonSettings */ - public static fromObject(object: { [k: string]: any }): google.api.HttpRule; + public static fromObject(object: { [k: string]: any }): google.api.PythonSettings; /** - * Creates a plain object from a HttpRule message. Also converts values to other types if specified. - * @param message HttpRule + * Creates a plain object from a PythonSettings message. Also converts values to other types if specified. + * @param message PythonSettings * @param [options] Conversion options * @returns Plain object */ - public static toObject(message: google.api.HttpRule, options?: $protobuf.IConversionOptions): { [k: string]: any }; + public static toObject(message: google.api.PythonSettings, options?: $protobuf.IConversionOptions): { [k: string]: any }; /** - * Converts this HttpRule to JSON. + * Converts this PythonSettings to JSON. * @returns JSON object */ public toJSON(): { [k: string]: any }; - } - /** Properties of a CustomHttpPattern. */ - interface ICustomHttpPattern { + /** + * Gets the default type url for PythonSettings + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } - /** CustomHttpPattern kind */ - kind?: (string|null); + /** Properties of a NodeSettings. */ + interface INodeSettings { - /** CustomHttpPattern path */ - path?: (string|null); + /** NodeSettings common */ + common?: (google.api.ICommonLanguageSettings|null); } - /** Represents a CustomHttpPattern. */ - class CustomHttpPattern implements ICustomHttpPattern { + /** Represents a NodeSettings. */ + class NodeSettings implements INodeSettings { /** - * Constructs a new CustomHttpPattern. + * Constructs a new NodeSettings. * @param [properties] Properties to set */ - constructor(properties?: google.api.ICustomHttpPattern); - - /** CustomHttpPattern kind. */ - public kind: string; + constructor(properties?: google.api.INodeSettings); - /** CustomHttpPattern path. */ - public path: string; + /** NodeSettings common. */ + public common?: (google.api.ICommonLanguageSettings|null); /** - * Creates a CustomHttpPattern message from a plain object. Also converts values to their respective internal types. + * Creates a NodeSettings message from a plain object. Also converts values to their respective internal types. * @param object Plain object - * @returns CustomHttpPattern + * @returns NodeSettings */ - public static fromObject(object: { [k: string]: any }): google.api.CustomHttpPattern; + public static fromObject(object: { [k: string]: any }): google.api.NodeSettings; /** - * Creates a plain object from a CustomHttpPattern message. Also converts values to other types if specified. - * @param message CustomHttpPattern + * Creates a plain object from a NodeSettings message. Also converts values to other types if specified. + * @param message NodeSettings * @param [options] Conversion options * @returns Plain object */ - public static toObject(message: google.api.CustomHttpPattern, options?: $protobuf.IConversionOptions): { [k: string]: any }; + public static toObject(message: google.api.NodeSettings, options?: $protobuf.IConversionOptions): { [k: string]: any }; /** - * Converts this CustomHttpPattern to JSON. + * Converts this NodeSettings to JSON. * @returns JSON object */ public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for NodeSettings + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; } - /** FieldBehavior enum. */ - type FieldBehavior = - "FIELD_BEHAVIOR_UNSPECIFIED"| "OPTIONAL"| "REQUIRED"| "OUTPUT_ONLY"| "INPUT_ONLY"| "IMMUTABLE"| "UNORDERED_LIST"| "NON_EMPTY_DEFAULT"; + /** Properties of a DotnetSettings. */ + interface IDotnetSettings { - /** Properties of a ResourceDescriptor. */ - interface IResourceDescriptor { + /** DotnetSettings common */ + common?: (google.api.ICommonLanguageSettings|null); - /** ResourceDescriptor type */ - type?: (string|null); + /** DotnetSettings renamedServices */ + renamedServices?: ({ [k: string]: string }|null); - /** ResourceDescriptor pattern */ - pattern?: (string[]|null); + /** DotnetSettings renamedResources */ + renamedResources?: ({ [k: string]: string }|null); - /** ResourceDescriptor nameField */ - nameField?: (string|null); + /** DotnetSettings ignoredResources */ + ignoredResources?: (string[]|null); - /** ResourceDescriptor history */ - history?: (google.api.ResourceDescriptor.History|null); + /** DotnetSettings forcedNamespaceAliases */ + forcedNamespaceAliases?: (string[]|null); - /** ResourceDescriptor plural */ - plural?: (string|null); + /** DotnetSettings handwrittenSignatures */ + handwrittenSignatures?: (string[]|null); + } - /** ResourceDescriptor singular */ - singular?: (string|null); + /** Represents a DotnetSettings. */ + class DotnetSettings implements IDotnetSettings { - /** ResourceDescriptor style */ - style?: (google.api.ResourceDescriptor.Style[]|null); + /** + * Constructs a new DotnetSettings. + * @param [properties] Properties to set + */ + constructor(properties?: google.api.IDotnetSettings); + + /** DotnetSettings common. */ + public common?: (google.api.ICommonLanguageSettings|null); + + /** DotnetSettings renamedServices. */ + public renamedServices: { [k: string]: string }; + + /** DotnetSettings renamedResources. */ + public renamedResources: { [k: string]: string }; + + /** DotnetSettings ignoredResources. */ + public ignoredResources: string[]; + + /** DotnetSettings forcedNamespaceAliases. */ + public forcedNamespaceAliases: string[]; + + /** DotnetSettings handwrittenSignatures. */ + public handwrittenSignatures: string[]; + + /** + * Creates a DotnetSettings message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns DotnetSettings + */ + public static fromObject(object: { [k: string]: any }): google.api.DotnetSettings; + + /** + * Creates a plain object from a DotnetSettings message. Also converts values to other types if specified. + * @param message DotnetSettings + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.api.DotnetSettings, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this DotnetSettings to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for DotnetSettings + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; } - /** Represents a ResourceDescriptor. */ - class ResourceDescriptor implements IResourceDescriptor { + /** Properties of a RubySettings. */ + interface IRubySettings { + + /** RubySettings common */ + common?: (google.api.ICommonLanguageSettings|null); + } + + /** Represents a RubySettings. */ + class RubySettings implements IRubySettings { /** - * Constructs a new ResourceDescriptor. + * Constructs a new RubySettings. * @param [properties] Properties to set */ - constructor(properties?: google.api.IResourceDescriptor); + constructor(properties?: google.api.IRubySettings); - /** ResourceDescriptor type. */ - public type: string; + /** RubySettings common. */ + public common?: (google.api.ICommonLanguageSettings|null); - /** ResourceDescriptor pattern. */ - public pattern: string[]; + /** + * Creates a RubySettings message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns RubySettings + */ + public static fromObject(object: { [k: string]: any }): google.api.RubySettings; - /** ResourceDescriptor nameField. */ - public nameField: string; + /** + * Creates a plain object from a RubySettings message. Also converts values to other types if specified. + * @param message RubySettings + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.api.RubySettings, options?: $protobuf.IConversionOptions): { [k: string]: any }; - /** ResourceDescriptor history. */ - public history: google.api.ResourceDescriptor.History; + /** + * Converts this RubySettings to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; - /** ResourceDescriptor plural. */ - public plural: string; + /** + * Gets the default type url for RubySettings + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } - /** ResourceDescriptor singular. */ - public singular: string; + /** Properties of a GoSettings. */ + interface IGoSettings { + + /** GoSettings common */ + common?: (google.api.ICommonLanguageSettings|null); + } + + /** Represents a GoSettings. */ + class GoSettings implements IGoSettings { + + /** + * Constructs a new GoSettings. + * @param [properties] Properties to set + */ + constructor(properties?: google.api.IGoSettings); - /** ResourceDescriptor style. */ - public style: google.api.ResourceDescriptor.Style[]; + /** GoSettings common. */ + public common?: (google.api.ICommonLanguageSettings|null); /** - * Creates a ResourceDescriptor message from a plain object. Also converts values to their respective internal types. + * Creates a GoSettings message from a plain object. Also converts values to their respective internal types. * @param object Plain object - * @returns ResourceDescriptor + * @returns GoSettings */ - public static fromObject(object: { [k: string]: any }): google.api.ResourceDescriptor; + public static fromObject(object: { [k: string]: any }): google.api.GoSettings; /** - * Creates a plain object from a ResourceDescriptor message. Also converts values to other types if specified. - * @param message ResourceDescriptor + * Creates a plain object from a GoSettings message. Also converts values to other types if specified. + * @param message GoSettings * @param [options] Conversion options * @returns Plain object */ - public static toObject(message: google.api.ResourceDescriptor, options?: $protobuf.IConversionOptions): { [k: string]: any }; + public static toObject(message: google.api.GoSettings, options?: $protobuf.IConversionOptions): { [k: string]: any }; /** - * Converts this ResourceDescriptor to JSON. + * Converts this GoSettings to JSON. * @returns JSON object */ public toJSON(): { [k: string]: any }; - } - - namespace ResourceDescriptor { - - /** History enum. */ - type History = - "HISTORY_UNSPECIFIED"| "ORIGINALLY_SINGLE_PATTERN"| "FUTURE_MULTI_PATTERN"; - /** Style enum. */ - type Style = - "STYLE_UNSPECIFIED"| "DECLARATIVE_FRIENDLY"; + /** + * Gets the default type url for GoSettings + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; } - /** Properties of a ResourceReference. */ - interface IResourceReference { + /** Properties of a MethodSettings. */ + interface IMethodSettings { - /** ResourceReference type */ - type?: (string|null); + /** MethodSettings selector */ + selector?: (string|null); - /** ResourceReference childType */ - childType?: (string|null); + /** MethodSettings longRunning */ + longRunning?: (google.api.MethodSettings.ILongRunning|null); + + /** MethodSettings autoPopulatedFields */ + autoPopulatedFields?: (string[]|null); } - /** Represents a ResourceReference. */ - class ResourceReference implements IResourceReference { + /** Represents a MethodSettings. */ + class MethodSettings implements IMethodSettings { /** - * Constructs a new ResourceReference. + * Constructs a new MethodSettings. * @param [properties] Properties to set */ - constructor(properties?: google.api.IResourceReference); + constructor(properties?: google.api.IMethodSettings); - /** ResourceReference type. */ - public type: string; + /** MethodSettings selector. */ + public selector: string; - /** ResourceReference childType. */ - public childType: string; + /** MethodSettings longRunning. */ + public longRunning?: (google.api.MethodSettings.ILongRunning|null); + + /** MethodSettings autoPopulatedFields. */ + public autoPopulatedFields: string[]; /** - * Creates a ResourceReference message from a plain object. Also converts values to their respective internal types. + * Creates a MethodSettings message from a plain object. Also converts values to their respective internal types. * @param object Plain object - * @returns ResourceReference + * @returns MethodSettings */ - public static fromObject(object: { [k: string]: any }): google.api.ResourceReference; + public static fromObject(object: { [k: string]: any }): google.api.MethodSettings; /** - * Creates a plain object from a ResourceReference message. Also converts values to other types if specified. - * @param message ResourceReference + * Creates a plain object from a MethodSettings message. Also converts values to other types if specified. + * @param message MethodSettings * @param [options] Conversion options * @returns Plain object */ - public static toObject(message: google.api.ResourceReference, options?: $protobuf.IConversionOptions): { [k: string]: any }; + public static toObject(message: google.api.MethodSettings, options?: $protobuf.IConversionOptions): { [k: string]: any }; /** - * Converts this ResourceReference to JSON. + * Converts this MethodSettings to JSON. * @returns JSON object */ public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for MethodSettings + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + namespace MethodSettings { + + /** Properties of a LongRunning. */ + interface ILongRunning { + + /** LongRunning initialPollDelay */ + initialPollDelay?: (google.protobuf.IDuration|null); + + /** LongRunning pollDelayMultiplier */ + pollDelayMultiplier?: (number|null); + + /** LongRunning maxPollDelay */ + maxPollDelay?: (google.protobuf.IDuration|null); + + /** LongRunning totalPollTimeout */ + totalPollTimeout?: (google.protobuf.IDuration|null); + } + + /** Represents a LongRunning. */ + class LongRunning implements ILongRunning { + + /** + * Constructs a new LongRunning. + * @param [properties] Properties to set + */ + constructor(properties?: google.api.MethodSettings.ILongRunning); + + /** LongRunning initialPollDelay. */ + public initialPollDelay?: (google.protobuf.IDuration|null); + + /** LongRunning pollDelayMultiplier. */ + public pollDelayMultiplier: number; + + /** LongRunning maxPollDelay. */ + public maxPollDelay?: (google.protobuf.IDuration|null); + + /** LongRunning totalPollTimeout. */ + public totalPollTimeout?: (google.protobuf.IDuration|null); + + /** + * Creates a LongRunning message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns LongRunning + */ + public static fromObject(object: { [k: string]: any }): google.api.MethodSettings.LongRunning; + + /** + * Creates a plain object from a LongRunning message. Also converts values to other types if specified. + * @param message LongRunning + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.api.MethodSettings.LongRunning, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this LongRunning to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for LongRunning + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } } + + /** ClientLibraryOrganization enum. */ + type ClientLibraryOrganization = + "CLIENT_LIBRARY_ORGANIZATION_UNSPECIFIED"| "CLOUD"| "ADS"| "PHOTOS"| "STREET_VIEW"| "SHOPPING"| "GEO"| "GENERATIVE_AI"; + + /** ClientLibraryDestination enum. */ + type ClientLibraryDestination = + "CLIENT_LIBRARY_DESTINATION_UNSPECIFIED"| "GITHUB"| "PACKAGE_MANAGER"; + + /** LaunchStage enum. */ + type LaunchStage = + "LAUNCH_STAGE_UNSPECIFIED"| "UNIMPLEMENTED"| "PRELAUNCH"| "EARLY_ACCESS"| "ALPHA"| "BETA"| "GA"| "DEPRECATED"; } /** Namespace protobuf. */ @@ -2318,8 +5252,19 @@ export namespace google { * @returns JSON object */ public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for FileDescriptorSet + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; } + /** Edition enum. */ + type Edition = + "EDITION_UNKNOWN"| "EDITION_PROTO2"| "EDITION_PROTO3"| "EDITION_2023"| "EDITION_2024"| "EDITION_1_TEST_ONLY"| "EDITION_2_TEST_ONLY"| "EDITION_99997_TEST_ONLY"| "EDITION_99998_TEST_ONLY"| "EDITION_99999_TEST_ONLY"| "EDITION_MAX"; + /** Properties of a FileDescriptorProto. */ interface IFileDescriptorProto { @@ -2358,6 +5303,9 @@ export namespace google { /** FileDescriptorProto syntax */ syntax?: (string|null); + + /** FileDescriptorProto edition */ + edition?: (google.protobuf.Edition|null); } /** Represents a FileDescriptorProto. */ @@ -2405,6 +5353,9 @@ export namespace google { /** FileDescriptorProto syntax. */ public syntax: string; + /** FileDescriptorProto edition. */ + public edition: google.protobuf.Edition; + /** * Creates a FileDescriptorProto message from a plain object. Also converts values to their respective internal types. * @param object Plain object @@ -2425,6 +5376,13 @@ export namespace google { * @returns JSON object */ public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for FileDescriptorProto + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; } /** Properties of a DescriptorProto. */ @@ -2520,6 +5478,13 @@ export namespace google { * @returns JSON object */ public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for DescriptorProto + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; } namespace DescriptorProto { @@ -2532,6 +5497,9 @@ export namespace google { /** ExtensionRange end */ end?: (number|null); + + /** ExtensionRange options */ + options?: (google.protobuf.IExtensionRangeOptions|null); } /** Represents an ExtensionRange. */ @@ -2549,6 +5517,9 @@ export namespace google { /** ExtensionRange end. */ public end: number; + /** ExtensionRange options. */ + public options?: (google.protobuf.IExtensionRangeOptions|null); + /** * Creates an ExtensionRange message from a plain object. Also converts values to their respective internal types. * @param object Plain object @@ -2569,6 +5540,13 @@ export namespace google { * @returns JSON object */ public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for ExtensionRange + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; } /** Properties of a ReservedRange. */ @@ -2616,7 +5594,159 @@ export namespace google { * @returns JSON object */ public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for ReservedRange + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + } + + /** Properties of an ExtensionRangeOptions. */ + interface IExtensionRangeOptions { + + /** ExtensionRangeOptions uninterpretedOption */ + uninterpretedOption?: (google.protobuf.IUninterpretedOption[]|null); + + /** ExtensionRangeOptions declaration */ + declaration?: (google.protobuf.ExtensionRangeOptions.IDeclaration[]|null); + + /** ExtensionRangeOptions features */ + features?: (google.protobuf.IFeatureSet|null); + + /** ExtensionRangeOptions verification */ + verification?: (google.protobuf.ExtensionRangeOptions.VerificationState|null); + } + + /** Represents an ExtensionRangeOptions. */ + class ExtensionRangeOptions implements IExtensionRangeOptions { + + /** + * Constructs a new ExtensionRangeOptions. + * @param [properties] Properties to set + */ + constructor(properties?: google.protobuf.IExtensionRangeOptions); + + /** ExtensionRangeOptions uninterpretedOption. */ + public uninterpretedOption: google.protobuf.IUninterpretedOption[]; + + /** ExtensionRangeOptions declaration. */ + public declaration: google.protobuf.ExtensionRangeOptions.IDeclaration[]; + + /** ExtensionRangeOptions features. */ + public features?: (google.protobuf.IFeatureSet|null); + + /** ExtensionRangeOptions verification. */ + public verification: google.protobuf.ExtensionRangeOptions.VerificationState; + + /** + * Creates an ExtensionRangeOptions message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns ExtensionRangeOptions + */ + public static fromObject(object: { [k: string]: any }): google.protobuf.ExtensionRangeOptions; + + /** + * Creates a plain object from an ExtensionRangeOptions message. Also converts values to other types if specified. + * @param message ExtensionRangeOptions + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.protobuf.ExtensionRangeOptions, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this ExtensionRangeOptions to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for ExtensionRangeOptions + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + namespace ExtensionRangeOptions { + + /** Properties of a Declaration. */ + interface IDeclaration { + + /** Declaration number */ + number?: (number|null); + + /** Declaration fullName */ + fullName?: (string|null); + + /** Declaration type */ + type?: (string|null); + + /** Declaration reserved */ + reserved?: (boolean|null); + + /** Declaration repeated */ + repeated?: (boolean|null); + } + + /** Represents a Declaration. */ + class Declaration implements IDeclaration { + + /** + * Constructs a new Declaration. + * @param [properties] Properties to set + */ + constructor(properties?: google.protobuf.ExtensionRangeOptions.IDeclaration); + + /** Declaration number. */ + public number: number; + + /** Declaration fullName. */ + public fullName: string; + + /** Declaration type. */ + public type: string; + + /** Declaration reserved. */ + public reserved: boolean; + + /** Declaration repeated. */ + public repeated: boolean; + + /** + * Creates a Declaration message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns Declaration + */ + public static fromObject(object: { [k: string]: any }): google.protobuf.ExtensionRangeOptions.Declaration; + + /** + * Creates a plain object from a Declaration message. Also converts values to other types if specified. + * @param message Declaration + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.protobuf.ExtensionRangeOptions.Declaration, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this Declaration to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for Declaration + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; } + + /** VerificationState enum. */ + type VerificationState = + "DECLARATION"| "UNVERIFIED"; } /** Properties of a FieldDescriptorProto. */ @@ -2651,6 +5781,9 @@ export namespace google { /** FieldDescriptorProto options */ options?: (google.protobuf.IFieldOptions|null); + + /** FieldDescriptorProto proto3Optional */ + proto3Optional?: (boolean|null); } /** Represents a FieldDescriptorProto. */ @@ -2692,6 +5825,9 @@ export namespace google { /** FieldDescriptorProto options. */ public options?: (google.protobuf.IFieldOptions|null); + /** FieldDescriptorProto proto3Optional. */ + public proto3Optional: boolean; + /** * Creates a FieldDescriptorProto message from a plain object. Also converts values to their respective internal types. * @param object Plain object @@ -2712,6 +5848,13 @@ export namespace google { * @returns JSON object */ public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for FieldDescriptorProto + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; } namespace FieldDescriptorProto { @@ -2722,7 +5865,7 @@ export namespace google { /** Label enum. */ type Label = - "LABEL_OPTIONAL"| "LABEL_REQUIRED"| "LABEL_REPEATED"; + "LABEL_OPTIONAL"| "LABEL_REPEATED"| "LABEL_REQUIRED"; } /** Properties of an OneofDescriptorProto. */ @@ -2770,6 +5913,13 @@ export namespace google { * @returns JSON object */ public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for OneofDescriptorProto + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; } /** Properties of an EnumDescriptorProto. */ @@ -2783,6 +5933,12 @@ export namespace google { /** EnumDescriptorProto options */ options?: (google.protobuf.IEnumOptions|null); + + /** EnumDescriptorProto reservedRange */ + reservedRange?: (google.protobuf.EnumDescriptorProto.IEnumReservedRange[]|null); + + /** EnumDescriptorProto reservedName */ + reservedName?: (string[]|null); } /** Represents an EnumDescriptorProto. */ @@ -2803,6 +5959,12 @@ export namespace google { /** EnumDescriptorProto options. */ public options?: (google.protobuf.IEnumOptions|null); + /** EnumDescriptorProto reservedRange. */ + public reservedRange: google.protobuf.EnumDescriptorProto.IEnumReservedRange[]; + + /** EnumDescriptorProto reservedName. */ + public reservedName: string[]; + /** * Creates an EnumDescriptorProto message from a plain object. Also converts values to their respective internal types. * @param object Plain object @@ -2823,6 +5985,70 @@ export namespace google { * @returns JSON object */ public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for EnumDescriptorProto + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + namespace EnumDescriptorProto { + + /** Properties of an EnumReservedRange. */ + interface IEnumReservedRange { + + /** EnumReservedRange start */ + start?: (number|null); + + /** EnumReservedRange end */ + end?: (number|null); + } + + /** Represents an EnumReservedRange. */ + class EnumReservedRange implements IEnumReservedRange { + + /** + * Constructs a new EnumReservedRange. + * @param [properties] Properties to set + */ + constructor(properties?: google.protobuf.EnumDescriptorProto.IEnumReservedRange); + + /** EnumReservedRange start. */ + public start: number; + + /** EnumReservedRange end. */ + public end: number; + + /** + * Creates an EnumReservedRange message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns EnumReservedRange + */ + public static fromObject(object: { [k: string]: any }): google.protobuf.EnumDescriptorProto.EnumReservedRange; + + /** + * Creates a plain object from an EnumReservedRange message. Also converts values to other types if specified. + * @param message EnumReservedRange + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.protobuf.EnumDescriptorProto.EnumReservedRange, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this EnumReservedRange to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for EnumReservedRange + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } } /** Properties of an EnumValueDescriptorProto. */ @@ -2876,6 +6102,13 @@ export namespace google { * @returns JSON object */ public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for EnumValueDescriptorProto + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; } /** Properties of a ServiceDescriptorProto. */ @@ -2929,6 +6162,13 @@ export namespace google { * @returns JSON object */ public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for ServiceDescriptorProto + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; } /** Properties of a MethodDescriptorProto. */ @@ -3000,6 +6240,13 @@ export namespace google { * @returns JSON object */ public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for MethodDescriptorProto + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; } /** Properties of a FileOptions. */ @@ -3047,6 +6294,24 @@ export namespace google { /** FileOptions csharpNamespace */ csharpNamespace?: (string|null); + /** FileOptions swiftPrefix */ + swiftPrefix?: (string|null); + + /** FileOptions phpClassPrefix */ + phpClassPrefix?: (string|null); + + /** FileOptions phpNamespace */ + phpNamespace?: (string|null); + + /** FileOptions phpMetadataNamespace */ + phpMetadataNamespace?: (string|null); + + /** FileOptions rubyPackage */ + rubyPackage?: (string|null); + + /** FileOptions features */ + features?: (google.protobuf.IFeatureSet|null); + /** FileOptions uninterpretedOption */ uninterpretedOption?: (google.protobuf.IUninterpretedOption[]|null); @@ -3102,8 +6367,26 @@ export namespace google { /** FileOptions objcClassPrefix. */ public objcClassPrefix: string; - /** FileOptions csharpNamespace. */ - public csharpNamespace: string; + /** FileOptions csharpNamespace. */ + public csharpNamespace: string; + + /** FileOptions swiftPrefix. */ + public swiftPrefix: string; + + /** FileOptions phpClassPrefix. */ + public phpClassPrefix: string; + + /** FileOptions phpNamespace. */ + public phpNamespace: string; + + /** FileOptions phpMetadataNamespace. */ + public phpMetadataNamespace: string; + + /** FileOptions rubyPackage. */ + public rubyPackage: string; + + /** FileOptions features. */ + public features?: (google.protobuf.IFeatureSet|null); /** FileOptions uninterpretedOption. */ public uninterpretedOption: google.protobuf.IUninterpretedOption[]; @@ -3128,6 +6411,13 @@ export namespace google { * @returns JSON object */ public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for FileOptions + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; } namespace FileOptions { @@ -3152,6 +6442,12 @@ export namespace google { /** MessageOptions mapEntry */ mapEntry?: (boolean|null); + /** MessageOptions deprecatedLegacyJsonFieldConflicts */ + deprecatedLegacyJsonFieldConflicts?: (boolean|null); + + /** MessageOptions features */ + features?: (google.protobuf.IFeatureSet|null); + /** MessageOptions uninterpretedOption */ uninterpretedOption?: (google.protobuf.IUninterpretedOption[]|null); @@ -3180,6 +6476,12 @@ export namespace google { /** MessageOptions mapEntry. */ public mapEntry: boolean; + /** MessageOptions deprecatedLegacyJsonFieldConflicts. */ + public deprecatedLegacyJsonFieldConflicts: boolean; + + /** MessageOptions features. */ + public features?: (google.protobuf.IFeatureSet|null); + /** MessageOptions uninterpretedOption. */ public uninterpretedOption: google.protobuf.IUninterpretedOption[]; @@ -3203,6 +6505,13 @@ export namespace google { * @returns JSON object */ public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for MessageOptions + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; } /** Properties of a FieldOptions. */ @@ -3220,12 +6529,30 @@ export namespace google { /** FieldOptions lazy */ lazy?: (boolean|null); + /** FieldOptions unverifiedLazy */ + unverifiedLazy?: (boolean|null); + /** FieldOptions deprecated */ deprecated?: (boolean|null); /** FieldOptions weak */ weak?: (boolean|null); + /** FieldOptions debugRedact */ + debugRedact?: (boolean|null); + + /** FieldOptions retention */ + retention?: (google.protobuf.FieldOptions.OptionRetention|null); + + /** FieldOptions targets */ + targets?: (google.protobuf.FieldOptions.OptionTargetType[]|null); + + /** FieldOptions editionDefaults */ + editionDefaults?: (google.protobuf.FieldOptions.IEditionDefault[]|null); + + /** FieldOptions features */ + features?: (google.protobuf.IFeatureSet|null); + /** FieldOptions uninterpretedOption */ uninterpretedOption?: (google.protobuf.IUninterpretedOption[]|null); @@ -3257,12 +6584,30 @@ export namespace google { /** FieldOptions lazy. */ public lazy: boolean; + /** FieldOptions unverifiedLazy. */ + public unverifiedLazy: boolean; + /** FieldOptions deprecated. */ public deprecated: boolean; /** FieldOptions weak. */ public weak: boolean; + /** FieldOptions debugRedact. */ + public debugRedact: boolean; + + /** FieldOptions retention. */ + public retention: google.protobuf.FieldOptions.OptionRetention; + + /** FieldOptions targets. */ + public targets: google.protobuf.FieldOptions.OptionTargetType[]; + + /** FieldOptions editionDefaults. */ + public editionDefaults: google.protobuf.FieldOptions.IEditionDefault[]; + + /** FieldOptions features. */ + public features?: (google.protobuf.IFeatureSet|null); + /** FieldOptions uninterpretedOption. */ public uninterpretedOption: google.protobuf.IUninterpretedOption[]; @@ -3286,6 +6631,13 @@ export namespace google { * @returns JSON object */ public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for FieldOptions + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; } namespace FieldOptions { @@ -3297,11 +6649,76 @@ export namespace google { /** JSType enum. */ type JSType = "JS_NORMAL"| "JS_STRING"| "JS_NUMBER"; + + /** OptionRetention enum. */ + type OptionRetention = + "RETENTION_UNKNOWN"| "RETENTION_RUNTIME"| "RETENTION_SOURCE"; + + /** OptionTargetType enum. */ + type OptionTargetType = + "TARGET_TYPE_UNKNOWN"| "TARGET_TYPE_FILE"| "TARGET_TYPE_EXTENSION_RANGE"| "TARGET_TYPE_MESSAGE"| "TARGET_TYPE_FIELD"| "TARGET_TYPE_ONEOF"| "TARGET_TYPE_ENUM"| "TARGET_TYPE_ENUM_ENTRY"| "TARGET_TYPE_SERVICE"| "TARGET_TYPE_METHOD"; + + /** Properties of an EditionDefault. */ + interface IEditionDefault { + + /** EditionDefault edition */ + edition?: (google.protobuf.Edition|null); + + /** EditionDefault value */ + value?: (string|null); + } + + /** Represents an EditionDefault. */ + class EditionDefault implements IEditionDefault { + + /** + * Constructs a new EditionDefault. + * @param [properties] Properties to set + */ + constructor(properties?: google.protobuf.FieldOptions.IEditionDefault); + + /** EditionDefault edition. */ + public edition: google.protobuf.Edition; + + /** EditionDefault value. */ + public value: string; + + /** + * Creates an EditionDefault message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns EditionDefault + */ + public static fromObject(object: { [k: string]: any }): google.protobuf.FieldOptions.EditionDefault; + + /** + * Creates a plain object from an EditionDefault message. Also converts values to other types if specified. + * @param message EditionDefault + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.protobuf.FieldOptions.EditionDefault, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this EditionDefault to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for EditionDefault + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } } /** Properties of an OneofOptions. */ interface IOneofOptions { + /** OneofOptions features */ + features?: (google.protobuf.IFeatureSet|null); + /** OneofOptions uninterpretedOption */ uninterpretedOption?: (google.protobuf.IUninterpretedOption[]|null); } @@ -3315,6 +6732,9 @@ export namespace google { */ constructor(properties?: google.protobuf.IOneofOptions); + /** OneofOptions features. */ + public features?: (google.protobuf.IFeatureSet|null); + /** OneofOptions uninterpretedOption. */ public uninterpretedOption: google.protobuf.IUninterpretedOption[]; @@ -3338,6 +6758,13 @@ export namespace google { * @returns JSON object */ public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for OneofOptions + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; } /** Properties of an EnumOptions. */ @@ -3349,6 +6776,12 @@ export namespace google { /** EnumOptions deprecated */ deprecated?: (boolean|null); + /** EnumOptions deprecatedLegacyJsonFieldConflicts */ + deprecatedLegacyJsonFieldConflicts?: (boolean|null); + + /** EnumOptions features */ + features?: (google.protobuf.IFeatureSet|null); + /** EnumOptions uninterpretedOption */ uninterpretedOption?: (google.protobuf.IUninterpretedOption[]|null); } @@ -3368,6 +6801,12 @@ export namespace google { /** EnumOptions deprecated. */ public deprecated: boolean; + /** EnumOptions deprecatedLegacyJsonFieldConflicts. */ + public deprecatedLegacyJsonFieldConflicts: boolean; + + /** EnumOptions features. */ + public features?: (google.protobuf.IFeatureSet|null); + /** EnumOptions uninterpretedOption. */ public uninterpretedOption: google.protobuf.IUninterpretedOption[]; @@ -3391,6 +6830,13 @@ export namespace google { * @returns JSON object */ public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for EnumOptions + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; } /** Properties of an EnumValueOptions. */ @@ -3399,6 +6845,12 @@ export namespace google { /** EnumValueOptions deprecated */ deprecated?: (boolean|null); + /** EnumValueOptions features */ + features?: (google.protobuf.IFeatureSet|null); + + /** EnumValueOptions debugRedact */ + debugRedact?: (boolean|null); + /** EnumValueOptions uninterpretedOption */ uninterpretedOption?: (google.protobuf.IUninterpretedOption[]|null); } @@ -3415,6 +6867,12 @@ export namespace google { /** EnumValueOptions deprecated. */ public deprecated: boolean; + /** EnumValueOptions features. */ + public features?: (google.protobuf.IFeatureSet|null); + + /** EnumValueOptions debugRedact. */ + public debugRedact: boolean; + /** EnumValueOptions uninterpretedOption. */ public uninterpretedOption: google.protobuf.IUninterpretedOption[]; @@ -3438,11 +6896,21 @@ export namespace google { * @returns JSON object */ public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for EnumValueOptions + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; } /** Properties of a ServiceOptions. */ interface IServiceOptions { + /** ServiceOptions features */ + features?: (google.protobuf.IFeatureSet|null); + /** ServiceOptions deprecated */ deprecated?: (boolean|null); @@ -3454,6 +6922,9 @@ export namespace google { /** ServiceOptions .google.api.oauthScopes */ ".google.api.oauthScopes"?: (string|null); + + /** ServiceOptions .google.api.apiVersion */ + ".google.api.apiVersion"?: (string|null); } /** Represents a ServiceOptions. */ @@ -3465,6 +6936,9 @@ export namespace google { */ constructor(properties?: google.protobuf.IServiceOptions); + /** ServiceOptions features. */ + public features?: (google.protobuf.IFeatureSet|null); + /** ServiceOptions deprecated. */ public deprecated: boolean; @@ -3491,6 +6965,13 @@ export namespace google { * @returns JSON object */ public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for ServiceOptions + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; } /** Properties of a MethodOptions. */ @@ -3499,6 +6980,12 @@ export namespace google { /** MethodOptions deprecated */ deprecated?: (boolean|null); + /** MethodOptions idempotencyLevel */ + idempotencyLevel?: (google.protobuf.MethodOptions.IdempotencyLevel|null); + + /** MethodOptions features */ + features?: (google.protobuf.IFeatureSet|null); + /** MethodOptions uninterpretedOption */ uninterpretedOption?: (google.protobuf.IUninterpretedOption[]|null); @@ -3524,6 +7011,12 @@ export namespace google { /** MethodOptions deprecated. */ public deprecated: boolean; + /** MethodOptions idempotencyLevel. */ + public idempotencyLevel: google.protobuf.MethodOptions.IdempotencyLevel; + + /** MethodOptions features. */ + public features?: (google.protobuf.IFeatureSet|null); + /** MethodOptions uninterpretedOption. */ public uninterpretedOption: google.protobuf.IUninterpretedOption[]; @@ -3547,6 +7040,20 @@ export namespace google { * @returns JSON object */ public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for MethodOptions + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + namespace MethodOptions { + + /** IdempotencyLevel enum. */ + type IdempotencyLevel = + "IDEMPOTENCY_UNKNOWN"| "NO_SIDE_EFFECTS"| "IDEMPOTENT"; } /** Properties of an UninterpretedOption. */ @@ -3558,121 +7065,357 @@ export namespace google { /** UninterpretedOption identifierValue */ identifierValue?: (string|null); - /** UninterpretedOption positiveIntValue */ - positiveIntValue?: (number|string|null); + /** UninterpretedOption positiveIntValue */ + positiveIntValue?: (number|string|null); + + /** UninterpretedOption negativeIntValue */ + negativeIntValue?: (number|string|null); + + /** UninterpretedOption doubleValue */ + doubleValue?: (number|null); + + /** UninterpretedOption stringValue */ + stringValue?: (Uint8Array|null); + + /** UninterpretedOption aggregateValue */ + aggregateValue?: (string|null); + } + + /** Represents an UninterpretedOption. */ + class UninterpretedOption implements IUninterpretedOption { + + /** + * Constructs a new UninterpretedOption. + * @param [properties] Properties to set + */ + constructor(properties?: google.protobuf.IUninterpretedOption); + + /** UninterpretedOption name. */ + public name: google.protobuf.UninterpretedOption.INamePart[]; + + /** UninterpretedOption identifierValue. */ + public identifierValue: string; + + /** UninterpretedOption positiveIntValue. */ + public positiveIntValue: (number|string); + + /** UninterpretedOption negativeIntValue. */ + public negativeIntValue: (number|string); + + /** UninterpretedOption doubleValue. */ + public doubleValue: number; + + /** UninterpretedOption stringValue. */ + public stringValue: Uint8Array; + + /** UninterpretedOption aggregateValue. */ + public aggregateValue: string; + + /** + * Creates an UninterpretedOption message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns UninterpretedOption + */ + public static fromObject(object: { [k: string]: any }): google.protobuf.UninterpretedOption; + + /** + * Creates a plain object from an UninterpretedOption message. Also converts values to other types if specified. + * @param message UninterpretedOption + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.protobuf.UninterpretedOption, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this UninterpretedOption to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for UninterpretedOption + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + namespace UninterpretedOption { + + /** Properties of a NamePart. */ + interface INamePart { + + /** NamePart namePart */ + namePart: string; + + /** NamePart isExtension */ + isExtension: boolean; + } + + /** Represents a NamePart. */ + class NamePart implements INamePart { + + /** + * Constructs a new NamePart. + * @param [properties] Properties to set + */ + constructor(properties?: google.protobuf.UninterpretedOption.INamePart); + + /** NamePart namePart. */ + public namePart: string; + + /** NamePart isExtension. */ + public isExtension: boolean; + + /** + * Creates a NamePart message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns NamePart + */ + public static fromObject(object: { [k: string]: any }): google.protobuf.UninterpretedOption.NamePart; + + /** + * Creates a plain object from a NamePart message. Also converts values to other types if specified. + * @param message NamePart + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.protobuf.UninterpretedOption.NamePart, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this NamePart to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for NamePart + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + } + + /** Properties of a FeatureSet. */ + interface IFeatureSet { + + /** FeatureSet fieldPresence */ + fieldPresence?: (google.protobuf.FeatureSet.FieldPresence|null); + + /** FeatureSet enumType */ + enumType?: (google.protobuf.FeatureSet.EnumType|null); + + /** FeatureSet repeatedFieldEncoding */ + repeatedFieldEncoding?: (google.protobuf.FeatureSet.RepeatedFieldEncoding|null); + + /** FeatureSet utf8Validation */ + utf8Validation?: (google.protobuf.FeatureSet.Utf8Validation|null); + + /** FeatureSet messageEncoding */ + messageEncoding?: (google.protobuf.FeatureSet.MessageEncoding|null); + + /** FeatureSet jsonFormat */ + jsonFormat?: (google.protobuf.FeatureSet.JsonFormat|null); + } + + /** Represents a FeatureSet. */ + class FeatureSet implements IFeatureSet { + + /** + * Constructs a new FeatureSet. + * @param [properties] Properties to set + */ + constructor(properties?: google.protobuf.IFeatureSet); + + /** FeatureSet fieldPresence. */ + public fieldPresence: google.protobuf.FeatureSet.FieldPresence; + + /** FeatureSet enumType. */ + public enumType: google.protobuf.FeatureSet.EnumType; + + /** FeatureSet repeatedFieldEncoding. */ + public repeatedFieldEncoding: google.protobuf.FeatureSet.RepeatedFieldEncoding; + + /** FeatureSet utf8Validation. */ + public utf8Validation: google.protobuf.FeatureSet.Utf8Validation; + + /** FeatureSet messageEncoding. */ + public messageEncoding: google.protobuf.FeatureSet.MessageEncoding; + + /** FeatureSet jsonFormat. */ + public jsonFormat: google.protobuf.FeatureSet.JsonFormat; + + /** + * Creates a FeatureSet message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns FeatureSet + */ + public static fromObject(object: { [k: string]: any }): google.protobuf.FeatureSet; + + /** + * Creates a plain object from a FeatureSet message. Also converts values to other types if specified. + * @param message FeatureSet + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.protobuf.FeatureSet, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this FeatureSet to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for FeatureSet + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + namespace FeatureSet { + + /** FieldPresence enum. */ + type FieldPresence = + "FIELD_PRESENCE_UNKNOWN"| "EXPLICIT"| "IMPLICIT"| "LEGACY_REQUIRED"; - /** UninterpretedOption negativeIntValue */ - negativeIntValue?: (number|string|null); + /** EnumType enum. */ + type EnumType = + "ENUM_TYPE_UNKNOWN"| "OPEN"| "CLOSED"; - /** UninterpretedOption doubleValue */ - doubleValue?: (number|null); + /** RepeatedFieldEncoding enum. */ + type RepeatedFieldEncoding = + "REPEATED_FIELD_ENCODING_UNKNOWN"| "PACKED"| "EXPANDED"; - /** UninterpretedOption stringValue */ - stringValue?: (Uint8Array|null); + /** Utf8Validation enum. */ + type Utf8Validation = + "UTF8_VALIDATION_UNKNOWN"| "VERIFY"| "NONE"; - /** UninterpretedOption aggregateValue */ - aggregateValue?: (string|null); + /** MessageEncoding enum. */ + type MessageEncoding = + "MESSAGE_ENCODING_UNKNOWN"| "LENGTH_PREFIXED"| "DELIMITED"; + + /** JsonFormat enum. */ + type JsonFormat = + "JSON_FORMAT_UNKNOWN"| "ALLOW"| "LEGACY_BEST_EFFORT"; } - /** Represents an UninterpretedOption. */ - class UninterpretedOption implements IUninterpretedOption { + /** Properties of a FeatureSetDefaults. */ + interface IFeatureSetDefaults { - /** - * Constructs a new UninterpretedOption. - * @param [properties] Properties to set - */ - constructor(properties?: google.protobuf.IUninterpretedOption); + /** FeatureSetDefaults defaults */ + defaults?: (google.protobuf.FeatureSetDefaults.IFeatureSetEditionDefault[]|null); - /** UninterpretedOption name. */ - public name: google.protobuf.UninterpretedOption.INamePart[]; + /** FeatureSetDefaults minimumEdition */ + minimumEdition?: (google.protobuf.Edition|null); - /** UninterpretedOption identifierValue. */ - public identifierValue: string; + /** FeatureSetDefaults maximumEdition */ + maximumEdition?: (google.protobuf.Edition|null); + } - /** UninterpretedOption positiveIntValue. */ - public positiveIntValue: (number|string); + /** Represents a FeatureSetDefaults. */ + class FeatureSetDefaults implements IFeatureSetDefaults { - /** UninterpretedOption negativeIntValue. */ - public negativeIntValue: (number|string); + /** + * Constructs a new FeatureSetDefaults. + * @param [properties] Properties to set + */ + constructor(properties?: google.protobuf.IFeatureSetDefaults); - /** UninterpretedOption doubleValue. */ - public doubleValue: number; + /** FeatureSetDefaults defaults. */ + public defaults: google.protobuf.FeatureSetDefaults.IFeatureSetEditionDefault[]; - /** UninterpretedOption stringValue. */ - public stringValue: Uint8Array; + /** FeatureSetDefaults minimumEdition. */ + public minimumEdition: google.protobuf.Edition; - /** UninterpretedOption aggregateValue. */ - public aggregateValue: string; + /** FeatureSetDefaults maximumEdition. */ + public maximumEdition: google.protobuf.Edition; /** - * Creates an UninterpretedOption message from a plain object. Also converts values to their respective internal types. + * Creates a FeatureSetDefaults message from a plain object. Also converts values to their respective internal types. * @param object Plain object - * @returns UninterpretedOption + * @returns FeatureSetDefaults */ - public static fromObject(object: { [k: string]: any }): google.protobuf.UninterpretedOption; + public static fromObject(object: { [k: string]: any }): google.protobuf.FeatureSetDefaults; /** - * Creates a plain object from an UninterpretedOption message. Also converts values to other types if specified. - * @param message UninterpretedOption + * Creates a plain object from a FeatureSetDefaults message. Also converts values to other types if specified. + * @param message FeatureSetDefaults * @param [options] Conversion options * @returns Plain object */ - public static toObject(message: google.protobuf.UninterpretedOption, options?: $protobuf.IConversionOptions): { [k: string]: any }; + public static toObject(message: google.protobuf.FeatureSetDefaults, options?: $protobuf.IConversionOptions): { [k: string]: any }; /** - * Converts this UninterpretedOption to JSON. + * Converts this FeatureSetDefaults to JSON. * @returns JSON object */ public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for FeatureSetDefaults + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; } - namespace UninterpretedOption { + namespace FeatureSetDefaults { - /** Properties of a NamePart. */ - interface INamePart { + /** Properties of a FeatureSetEditionDefault. */ + interface IFeatureSetEditionDefault { - /** NamePart namePart */ - namePart: string; + /** FeatureSetEditionDefault edition */ + edition?: (google.protobuf.Edition|null); - /** NamePart isExtension */ - isExtension: boolean; + /** FeatureSetEditionDefault features */ + features?: (google.protobuf.IFeatureSet|null); } - /** Represents a NamePart. */ - class NamePart implements INamePart { + /** Represents a FeatureSetEditionDefault. */ + class FeatureSetEditionDefault implements IFeatureSetEditionDefault { /** - * Constructs a new NamePart. + * Constructs a new FeatureSetEditionDefault. * @param [properties] Properties to set */ - constructor(properties?: google.protobuf.UninterpretedOption.INamePart); + constructor(properties?: google.protobuf.FeatureSetDefaults.IFeatureSetEditionDefault); - /** NamePart namePart. */ - public namePart: string; + /** FeatureSetEditionDefault edition. */ + public edition: google.protobuf.Edition; - /** NamePart isExtension. */ - public isExtension: boolean; + /** FeatureSetEditionDefault features. */ + public features?: (google.protobuf.IFeatureSet|null); /** - * Creates a NamePart message from a plain object. Also converts values to their respective internal types. + * Creates a FeatureSetEditionDefault message from a plain object. Also converts values to their respective internal types. * @param object Plain object - * @returns NamePart + * @returns FeatureSetEditionDefault */ - public static fromObject(object: { [k: string]: any }): google.protobuf.UninterpretedOption.NamePart; + public static fromObject(object: { [k: string]: any }): google.protobuf.FeatureSetDefaults.FeatureSetEditionDefault; /** - * Creates a plain object from a NamePart message. Also converts values to other types if specified. - * @param message NamePart + * Creates a plain object from a FeatureSetEditionDefault message. Also converts values to other types if specified. + * @param message FeatureSetEditionDefault * @param [options] Conversion options * @returns Plain object */ - public static toObject(message: google.protobuf.UninterpretedOption.NamePart, options?: $protobuf.IConversionOptions): { [k: string]: any }; + public static toObject(message: google.protobuf.FeatureSetDefaults.FeatureSetEditionDefault, options?: $protobuf.IConversionOptions): { [k: string]: any }; /** - * Converts this NamePart to JSON. + * Converts this FeatureSetEditionDefault to JSON. * @returns JSON object */ public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for FeatureSetEditionDefault + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; } } @@ -3715,6 +7458,13 @@ export namespace google { * @returns JSON object */ public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for SourceCodeInfo + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; } namespace SourceCodeInfo { @@ -3782,6 +7532,13 @@ export namespace google { * @returns JSON object */ public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for Location + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; } } @@ -3824,6 +7581,13 @@ export namespace google { * @returns JSON object */ public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for GeneratedCodeInfo + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; } namespace GeneratedCodeInfo { @@ -3842,6 +7606,9 @@ export namespace google { /** Annotation end */ end?: (number|null); + + /** Annotation semantic */ + semantic?: (google.protobuf.GeneratedCodeInfo.Annotation.Semantic|null); } /** Represents an Annotation. */ @@ -3865,6 +7632,9 @@ export namespace google { /** Annotation end. */ public end: number; + /** Annotation semantic. */ + public semantic: google.protobuf.GeneratedCodeInfo.Annotation.Semantic; + /** * Creates an Annotation message from a plain object. Also converts values to their respective internal types. * @param object Plain object @@ -3885,177 +7655,273 @@ export namespace google { * @returns JSON object */ public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for Annotation + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + namespace Annotation { + + /** Semantic enum. */ + type Semantic = + "NONE"| "SET"| "ALIAS"; } } - /** Properties of an Empty. */ - interface IEmpty { + /** Properties of a Timestamp. */ + interface ITimestamp { + + /** Timestamp seconds */ + seconds?: (number|string|null); + + /** Timestamp nanos */ + nanos?: (number|null); } - /** Represents an Empty. */ - class Empty implements IEmpty { + /** Represents a Timestamp. */ + class Timestamp implements ITimestamp { /** - * Constructs a new Empty. + * Constructs a new Timestamp. * @param [properties] Properties to set */ - constructor(properties?: google.protobuf.IEmpty); + constructor(properties?: google.protobuf.ITimestamp); + + /** Timestamp seconds. */ + public seconds: (number|string); + + /** Timestamp nanos. */ + public nanos: number; /** - * Creates an Empty message from a plain object. Also converts values to their respective internal types. + * Creates a Timestamp message from a plain object. Also converts values to their respective internal types. * @param object Plain object - * @returns Empty + * @returns Timestamp */ - public static fromObject(object: { [k: string]: any }): google.protobuf.Empty; + public static fromObject(object: { [k: string]: any }): google.protobuf.Timestamp; /** - * Creates a plain object from an Empty message. Also converts values to other types if specified. - * @param message Empty + * Creates a plain object from a Timestamp message. Also converts values to other types if specified. + * @param message Timestamp * @param [options] Conversion options * @returns Plain object */ - public static toObject(message: google.protobuf.Empty, options?: $protobuf.IConversionOptions): { [k: string]: any }; + public static toObject(message: google.protobuf.Timestamp, options?: $protobuf.IConversionOptions): { [k: string]: any }; /** - * Converts this Empty to JSON. + * Converts this Timestamp to JSON. * @returns JSON object */ public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for Timestamp + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; } - /** Properties of a FieldMask. */ - interface IFieldMask { + /** Properties of a Duration. */ + interface IDuration { - /** FieldMask paths */ - paths?: (string[]|null); + /** Duration seconds */ + seconds?: (number|string|null); + + /** Duration nanos */ + nanos?: (number|null); } - /** Represents a FieldMask. */ - class FieldMask implements IFieldMask { + /** Represents a Duration. */ + class Duration implements IDuration { /** - * Constructs a new FieldMask. + * Constructs a new Duration. * @param [properties] Properties to set */ - constructor(properties?: google.protobuf.IFieldMask); + constructor(properties?: google.protobuf.IDuration); - /** FieldMask paths. */ - public paths: string[]; + /** Duration seconds. */ + public seconds: (number|string); + + /** Duration nanos. */ + public nanos: number; /** - * Creates a FieldMask message from a plain object. Also converts values to their respective internal types. + * Creates a Duration message from a plain object. Also converts values to their respective internal types. * @param object Plain object - * @returns FieldMask + * @returns Duration */ - public static fromObject(object: { [k: string]: any }): google.protobuf.FieldMask; + public static fromObject(object: { [k: string]: any }): google.protobuf.Duration; /** - * Creates a plain object from a FieldMask message. Also converts values to other types if specified. - * @param message FieldMask + * Creates a plain object from a Duration message. Also converts values to other types if specified. + * @param message Duration * @param [options] Conversion options * @returns Plain object */ - public static toObject(message: google.protobuf.FieldMask, options?: $protobuf.IConversionOptions): { [k: string]: any }; + public static toObject(message: google.protobuf.Duration, options?: $protobuf.IConversionOptions): { [k: string]: any }; /** - * Converts this FieldMask to JSON. + * Converts this Duration to JSON. * @returns JSON object */ public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for Duration + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; } - /** Properties of a Timestamp. */ - interface ITimestamp { + /** Properties of an Any. */ + interface IAny { - /** Timestamp seconds */ - seconds?: (number|string|null); + /** Any type_url */ + type_url?: (string|null); - /** Timestamp nanos */ - nanos?: (number|null); + /** Any value */ + value?: (Uint8Array|null); } - /** Represents a Timestamp. */ - class Timestamp implements ITimestamp { + /** Represents an Any. */ + class Any implements IAny { /** - * Constructs a new Timestamp. + * Constructs a new Any. * @param [properties] Properties to set */ - constructor(properties?: google.protobuf.ITimestamp); + constructor(properties?: google.protobuf.IAny); - /** Timestamp seconds. */ - public seconds: (number|string); + /** Any type_url. */ + public type_url: string; - /** Timestamp nanos. */ - public nanos: number; + /** Any value. */ + public value: Uint8Array; /** - * Creates a Timestamp message from a plain object. Also converts values to their respective internal types. + * Creates an Any message from a plain object. Also converts values to their respective internal types. * @param object Plain object - * @returns Timestamp + * @returns Any */ - public static fromObject(object: { [k: string]: any }): google.protobuf.Timestamp; + public static fromObject(object: { [k: string]: any }): google.protobuf.Any; /** - * Creates a plain object from a Timestamp message. Also converts values to other types if specified. - * @param message Timestamp + * Creates a plain object from an Any message. Also converts values to other types if specified. + * @param message Any * @param [options] Conversion options * @returns Plain object */ - public static toObject(message: google.protobuf.Timestamp, options?: $protobuf.IConversionOptions): { [k: string]: any }; + public static toObject(message: google.protobuf.Any, options?: $protobuf.IConversionOptions): { [k: string]: any }; /** - * Converts this Timestamp to JSON. + * Converts this Any to JSON. * @returns JSON object */ public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for Any + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; } - /** Properties of an Any. */ - interface IAny { + /** Properties of an Empty. */ + interface IEmpty { + } + + /** Represents an Empty. */ + class Empty implements IEmpty { + + /** + * Constructs a new Empty. + * @param [properties] Properties to set + */ + constructor(properties?: google.protobuf.IEmpty); + + /** + * Creates an Empty message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns Empty + */ + public static fromObject(object: { [k: string]: any }): google.protobuf.Empty; + + /** + * Creates a plain object from an Empty message. Also converts values to other types if specified. + * @param message Empty + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.protobuf.Empty, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this Empty to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for Empty + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } - /** Any type_url */ - type_url?: (string|null); + /** Properties of a FieldMask. */ + interface IFieldMask { - /** Any value */ - value?: (Uint8Array|null); + /** FieldMask paths */ + paths?: (string[]|null); } - /** Represents an Any. */ - class Any implements IAny { + /** Represents a FieldMask. */ + class FieldMask implements IFieldMask { /** - * Constructs a new Any. + * Constructs a new FieldMask. * @param [properties] Properties to set */ - constructor(properties?: google.protobuf.IAny); - - /** Any type_url. */ - public type_url: string; + constructor(properties?: google.protobuf.IFieldMask); - /** Any value. */ - public value: Uint8Array; + /** FieldMask paths. */ + public paths: string[]; /** - * Creates an Any message from a plain object. Also converts values to their respective internal types. + * Creates a FieldMask message from a plain object. Also converts values to their respective internal types. * @param object Plain object - * @returns Any + * @returns FieldMask */ - public static fromObject(object: { [k: string]: any }): google.protobuf.Any; + public static fromObject(object: { [k: string]: any }): google.protobuf.FieldMask; /** - * Creates a plain object from an Any message. Also converts values to other types if specified. - * @param message Any + * Creates a plain object from a FieldMask message. Also converts values to other types if specified. + * @param message FieldMask * @param [options] Conversion options * @returns Plain object */ - public static toObject(message: google.protobuf.Any, options?: $protobuf.IConversionOptions): { [k: string]: any }; + public static toObject(message: google.protobuf.FieldMask, options?: $protobuf.IConversionOptions): { [k: string]: any }; /** - * Converts this Any to JSON. + * Converts this FieldMask to JSON. * @returns JSON object */ public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for FieldMask + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; } /** Properties of a Struct. */ @@ -4097,6 +7963,13 @@ export namespace google { * @returns JSON object */ public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for Struct + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; } /** Properties of a Value. */ @@ -4171,6 +8044,13 @@ export namespace google { * @returns JSON object */ public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for Value + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; } /** NullValue enum. */ @@ -4216,6 +8096,13 @@ export namespace google { * @returns JSON object */ public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for ListValue + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; } /** Properties of a DoubleValue. */ @@ -4257,6 +8144,13 @@ export namespace google { * @returns JSON object */ public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for DoubleValue + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; } /** Properties of a FloatValue. */ @@ -4298,6 +8192,13 @@ export namespace google { * @returns JSON object */ public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for FloatValue + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; } /** Properties of an Int64Value. */ @@ -4339,6 +8240,13 @@ export namespace google { * @returns JSON object */ public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for Int64Value + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; } /** Properties of a UInt64Value. */ @@ -4380,6 +8288,13 @@ export namespace google { * @returns JSON object */ public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for UInt64Value + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; } /** Properties of an Int32Value. */ @@ -4421,6 +8336,13 @@ export namespace google { * @returns JSON object */ public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for Int32Value + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; } /** Properties of a UInt32Value. */ @@ -4462,6 +8384,13 @@ export namespace google { * @returns JSON object */ public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for UInt32Value + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; } /** Properties of a BoolValue. */ @@ -4503,6 +8432,13 @@ export namespace google { * @returns JSON object */ public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for BoolValue + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; } /** Properties of a StringValue. */ @@ -4544,6 +8480,13 @@ export namespace google { * @returns JSON object */ public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for StringValue + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; } /** Properties of a BytesValue. */ @@ -4585,59 +8528,23 @@ export namespace google { * @returns JSON object */ public toJSON(): { [k: string]: any }; - } - - /** Properties of a Duration. */ - interface IDuration { - - /** Duration seconds */ - seconds?: (number|string|null); - - /** Duration nanos */ - nanos?: (number|null); - } - - /** Represents a Duration. */ - class Duration implements IDuration { - - /** - * Constructs a new Duration. - * @param [properties] Properties to set - */ - constructor(properties?: google.protobuf.IDuration); - - /** Duration seconds. */ - public seconds: (number|string); - - /** Duration nanos. */ - public nanos: number; - - /** - * Creates a Duration message from a plain object. Also converts values to their respective internal types. - * @param object Plain object - * @returns Duration - */ - public static fromObject(object: { [k: string]: any }): google.protobuf.Duration; - - /** - * Creates a plain object from a Duration message. Also converts values to other types if specified. - * @param message Duration - * @param [options] Conversion options - * @returns Plain object - */ - public static toObject(message: google.protobuf.Duration, options?: $protobuf.IConversionOptions): { [k: string]: any }; /** - * Converts this Duration to JSON. - * @returns JSON object + * Gets the default type url for BytesValue + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url */ - public toJSON(): { [k: string]: any }; + public static getTypeUrl(typeUrlPrefix?: string): string; } } /** Namespace type. */ namespace type { + /** DayOfWeek enum. */ + type DayOfWeek = + "DAY_OF_WEEK_UNSPECIFIED"| "MONDAY"| "TUESDAY"| "WEDNESDAY"| "THURSDAY"| "FRIDAY"| "SATURDAY"| "SUNDAY"; + /** Properties of a LatLng. */ interface ILatLng { @@ -4683,63 +8590,13 @@ export namespace google { * @returns JSON object */ public toJSON(): { [k: string]: any }; - } - } - - /** Namespace rpc. */ - namespace rpc { - - /** Properties of a Status. */ - interface IStatus { - - /** Status code */ - code?: (number|null); - - /** Status message */ - message?: (string|null); - - /** Status details */ - details?: (google.protobuf.IAny[]|null); - } - - /** Represents a Status. */ - class Status implements IStatus { - - /** - * Constructs a new Status. - * @param [properties] Properties to set - */ - constructor(properties?: google.rpc.IStatus); - - /** Status code. */ - public code: number; - - /** Status message. */ - public message: string; - - /** Status details. */ - public details: google.protobuf.IAny[]; - - /** - * Creates a Status message from a plain object. Also converts values to their respective internal types. - * @param object Plain object - * @returns Status - */ - public static fromObject(object: { [k: string]: any }): google.rpc.Status; - - /** - * Creates a plain object from a Status message. Also converts values to other types if specified. - * @param message Status - * @param [options] Conversion options - * @returns Plain object - */ - public static toObject(message: google.rpc.Status, options?: $protobuf.IConversionOptions): { [k: string]: any }; /** - * Converts this Status to JSON. - * @returns JSON object + * Gets the default type url for LatLng + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url */ - public toJSON(): { [k: string]: any }; + public static getTypeUrl(typeUrlPrefix?: string): string; } } @@ -4932,6 +8789,13 @@ export namespace google { * @returns JSON object */ public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for Operation + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; } /** Properties of a GetOperationRequest. */ @@ -4973,6 +8837,13 @@ export namespace google { * @returns JSON object */ public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for GetOperationRequest + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; } /** Properties of a ListOperationsRequest. */ @@ -5032,6 +8903,13 @@ export namespace google { * @returns JSON object */ public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for ListOperationsRequest + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; } /** Properties of a ListOperationsResponse. */ @@ -5079,6 +8957,13 @@ export namespace google { * @returns JSON object */ public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for ListOperationsResponse + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; } /** Properties of a CancelOperationRequest. */ @@ -5120,6 +9005,13 @@ export namespace google { * @returns JSON object */ public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for CancelOperationRequest + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; } /** Properties of a DeleteOperationRequest. */ @@ -5161,6 +9053,13 @@ export namespace google { * @returns JSON object */ public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for DeleteOperationRequest + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; } /** Properties of a WaitOperationRequest. */ @@ -5208,6 +9107,13 @@ export namespace google { * @returns JSON object */ public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for WaitOperationRequest + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; } /** Properties of an OperationInfo. */ @@ -5255,6 +9161,77 @@ export namespace google { * @returns JSON object */ public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for OperationInfo + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + } + + /** Namespace rpc. */ + namespace rpc { + + /** Properties of a Status. */ + interface IStatus { + + /** Status code */ + code?: (number|null); + + /** Status message */ + message?: (string|null); + + /** Status details */ + details?: (google.protobuf.IAny[]|null); + } + + /** Represents a Status. */ + class Status implements IStatus { + + /** + * Constructs a new Status. + * @param [properties] Properties to set + */ + constructor(properties?: google.rpc.IStatus); + + /** Status code. */ + public code: number; + + /** Status message. */ + public message: string; + + /** Status details. */ + public details: google.protobuf.IAny[]; + + /** + * Creates a Status message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns Status + */ + public static fromObject(object: { [k: string]: any }): google.rpc.Status; + + /** + * Creates a plain object from a Status message. Also converts values to other types if specified. + * @param message Status + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.rpc.Status, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this Status to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for Status + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; } } } diff --git a/types/protos/firestore_v1_proto_api.d.ts b/types/protos/firestore_v1_proto_api.d.ts index b2e0b8d22..c387e89a6 100644 --- a/types/protos/firestore_v1_proto_api.d.ts +++ b/types/protos/firestore_v1_proto_api.d.ts @@ -1,5 +1,5 @@ /*! - * Copyright 2022 Google LLC + * 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. @@ -15,6 +15,7 @@ */ import * as $protobuf from "protobufjs"; +import Long = require("long"); /** Namespace firestore. */ export namespace firestore { @@ -72,6 +73,13 @@ export namespace firestore { * @returns JSON object */ public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for BundledQuery + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; } namespace BundledQuery { @@ -132,6 +140,13 @@ export namespace firestore { * @returns JSON object */ public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for NamedQuery + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; } /** Properties of a BundledDocumentMetadata. */ @@ -191,6 +206,13 @@ export namespace firestore { * @returns JSON object */ public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for BundledDocumentMetadata + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; } /** Properties of a BundleMetadata. */ @@ -256,6 +278,13 @@ export namespace firestore { * @returns JSON object */ public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for BundleMetadata + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; } /** Properties of a BundleElement. */ @@ -318,6192 +347,9405 @@ export namespace firestore { * @returns JSON object */ public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for BundleElement + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; } } /** Namespace google. */ export namespace google { - /** Namespace protobuf. */ - namespace protobuf { + /** Namespace firestore. */ + namespace firestore { - /** Properties of a Timestamp. */ - interface ITimestamp { + /** Namespace v1. */ + namespace v1 { - /** Timestamp seconds */ - seconds?: (number|string|null); + /** Properties of an AggregationResult. */ + interface IAggregationResult { - /** Timestamp nanos */ - nanos?: (number|null); - } + /** AggregationResult aggregateFields */ + aggregateFields?: ({ [k: string]: google.firestore.v1.IValue }|null); + } - /** Represents a Timestamp. */ - class Timestamp implements ITimestamp { + /** Represents an AggregationResult. */ + class AggregationResult implements IAggregationResult { - /** - * Constructs a new Timestamp. - * @param [properties] Properties to set - */ - constructor(properties?: google.protobuf.ITimestamp); + /** + * Constructs a new AggregationResult. + * @param [properties] Properties to set + */ + constructor(properties?: google.firestore.v1.IAggregationResult); - /** Timestamp seconds. */ - public seconds: (number|string); + /** AggregationResult aggregateFields. */ + public aggregateFields: { [k: string]: google.firestore.v1.IValue }; - /** Timestamp nanos. */ - public nanos: number; + /** + * Creates an AggregationResult message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns AggregationResult + */ + public static fromObject(object: { [k: string]: any }): google.firestore.v1.AggregationResult; - /** - * Creates a Timestamp message from a plain object. Also converts values to their respective internal types. - * @param object Plain object - * @returns Timestamp - */ - public static fromObject(object: { [k: string]: any }): google.protobuf.Timestamp; + /** + * Creates a plain object from an AggregationResult message. Also converts values to other types if specified. + * @param message AggregationResult + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.firestore.v1.AggregationResult, options?: $protobuf.IConversionOptions): { [k: string]: any }; - /** - * Creates a plain object from a Timestamp message. Also converts values to other types if specified. - * @param message Timestamp - * @param [options] Conversion options - * @returns Plain object - */ - public static toObject(message: google.protobuf.Timestamp, options?: $protobuf.IConversionOptions): { [k: string]: any }; + /** + * Converts this AggregationResult to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; - /** - * Converts this Timestamp to JSON. - * @returns JSON object - */ - public toJSON(): { [k: string]: any }; - } + /** + * Gets the default type url for AggregationResult + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } - /** Properties of a FileDescriptorSet. */ - interface IFileDescriptorSet { + /** Properties of a Document. */ + interface IDocument { - /** FileDescriptorSet file */ - file?: (google.protobuf.IFileDescriptorProto[]|null); - } + /** Document name */ + name?: (string|null); - /** Represents a FileDescriptorSet. */ - class FileDescriptorSet implements IFileDescriptorSet { + /** Document fields */ + fields?: ({ [k: string]: google.firestore.v1.IValue }|null); - /** - * Constructs a new FileDescriptorSet. - * @param [properties] Properties to set - */ - constructor(properties?: google.protobuf.IFileDescriptorSet); + /** Document createTime */ + createTime?: (google.protobuf.ITimestamp|null); - /** FileDescriptorSet file. */ - public file: google.protobuf.IFileDescriptorProto[]; + /** Document updateTime */ + updateTime?: (google.protobuf.ITimestamp|null); + } - /** - * Creates a FileDescriptorSet message from a plain object. Also converts values to their respective internal types. - * @param object Plain object - * @returns FileDescriptorSet - */ - public static fromObject(object: { [k: string]: any }): google.protobuf.FileDescriptorSet; + /** Represents a Document. */ + class Document implements IDocument { - /** - * Creates a plain object from a FileDescriptorSet message. Also converts values to other types if specified. - * @param message FileDescriptorSet - * @param [options] Conversion options - * @returns Plain object - */ - public static toObject(message: google.protobuf.FileDescriptorSet, options?: $protobuf.IConversionOptions): { [k: string]: any }; + /** + * Constructs a new Document. + * @param [properties] Properties to set + */ + constructor(properties?: google.firestore.v1.IDocument); - /** - * Converts this FileDescriptorSet to JSON. - * @returns JSON object - */ - public toJSON(): { [k: string]: any }; - } + /** Document name. */ + public name: string; - /** Properties of a FileDescriptorProto. */ - interface IFileDescriptorProto { + /** Document fields. */ + public fields: { [k: string]: google.firestore.v1.IValue }; - /** FileDescriptorProto name */ - name?: (string|null); + /** Document createTime. */ + public createTime?: (google.protobuf.ITimestamp|null); - /** FileDescriptorProto package */ - "package"?: (string|null); + /** Document updateTime. */ + public updateTime?: (google.protobuf.ITimestamp|null); - /** FileDescriptorProto dependency */ - dependency?: (string[]|null); + /** + * Creates a Document message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns Document + */ + public static fromObject(object: { [k: string]: any }): google.firestore.v1.Document; - /** FileDescriptorProto publicDependency */ - publicDependency?: (number[]|null); + /** + * Creates a plain object from a Document message. Also converts values to other types if specified. + * @param message Document + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.firestore.v1.Document, options?: $protobuf.IConversionOptions): { [k: string]: any }; - /** FileDescriptorProto weakDependency */ - weakDependency?: (number[]|null); + /** + * Converts this Document to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; - /** FileDescriptorProto messageType */ - messageType?: (google.protobuf.IDescriptorProto[]|null); + /** + * Gets the default type url for Document + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } - /** FileDescriptorProto enumType */ - enumType?: (google.protobuf.IEnumDescriptorProto[]|null); + /** Properties of a Value. */ + interface IValue { - /** FileDescriptorProto service */ - service?: (google.protobuf.IServiceDescriptorProto[]|null); + /** Value nullValue */ + nullValue?: (google.protobuf.NullValue|null); - /** FileDescriptorProto extension */ - extension?: (google.protobuf.IFieldDescriptorProto[]|null); + /** Value booleanValue */ + booleanValue?: (boolean|null); - /** FileDescriptorProto options */ - options?: (google.protobuf.IFileOptions|null); + /** Value integerValue */ + integerValue?: (number|string|null); - /** FileDescriptorProto sourceCodeInfo */ - sourceCodeInfo?: (google.protobuf.ISourceCodeInfo|null); + /** Value doubleValue */ + doubleValue?: (number|null); - /** FileDescriptorProto syntax */ - syntax?: (string|null); - } + /** Value timestampValue */ + timestampValue?: (google.protobuf.ITimestamp|null); - /** Represents a FileDescriptorProto. */ - class FileDescriptorProto implements IFileDescriptorProto { + /** Value stringValue */ + stringValue?: (string|null); - /** - * Constructs a new FileDescriptorProto. - * @param [properties] Properties to set - */ - constructor(properties?: google.protobuf.IFileDescriptorProto); + /** Value bytesValue */ + bytesValue?: (Uint8Array|null); - /** FileDescriptorProto name. */ - public name: string; + /** Value referenceValue */ + referenceValue?: (string|null); - /** FileDescriptorProto package. */ - public package: string; + /** Value geoPointValue */ + geoPointValue?: (google.type.ILatLng|null); - /** FileDescriptorProto dependency. */ - public dependency: string[]; + /** Value arrayValue */ + arrayValue?: (google.firestore.v1.IArrayValue|null); - /** FileDescriptorProto publicDependency. */ - public publicDependency: number[]; + /** Value mapValue */ + mapValue?: (google.firestore.v1.IMapValue|null); + } - /** FileDescriptorProto weakDependency. */ - public weakDependency: number[]; + /** Represents a Value. */ + class Value implements IValue { - /** FileDescriptorProto messageType. */ - public messageType: google.protobuf.IDescriptorProto[]; + /** + * Constructs a new Value. + * @param [properties] Properties to set + */ + constructor(properties?: google.firestore.v1.IValue); - /** FileDescriptorProto enumType. */ - public enumType: google.protobuf.IEnumDescriptorProto[]; + /** Value nullValue. */ + public nullValue?: (google.protobuf.NullValue|null); - /** FileDescriptorProto service. */ - public service: google.protobuf.IServiceDescriptorProto[]; + /** Value booleanValue. */ + public booleanValue?: (boolean|null); - /** FileDescriptorProto extension. */ - public extension: google.protobuf.IFieldDescriptorProto[]; + /** Value integerValue. */ + public integerValue?: (number|string|null); - /** FileDescriptorProto options. */ - public options?: (google.protobuf.IFileOptions|null); + /** Value doubleValue. */ + public doubleValue?: (number|null); - /** FileDescriptorProto sourceCodeInfo. */ - public sourceCodeInfo?: (google.protobuf.ISourceCodeInfo|null); + /** Value timestampValue. */ + public timestampValue?: (google.protobuf.ITimestamp|null); - /** FileDescriptorProto syntax. */ - public syntax: string; - - /** - * Creates a FileDescriptorProto message from a plain object. Also converts values to their respective internal types. - * @param object Plain object - * @returns FileDescriptorProto - */ - public static fromObject(object: { [k: string]: any }): google.protobuf.FileDescriptorProto; - - /** - * Creates a plain object from a FileDescriptorProto message. Also converts values to other types if specified. - * @param message FileDescriptorProto - * @param [options] Conversion options - * @returns Plain object - */ - public static toObject(message: google.protobuf.FileDescriptorProto, options?: $protobuf.IConversionOptions): { [k: string]: any }; + /** Value stringValue. */ + public stringValue?: (string|null); - /** - * Converts this FileDescriptorProto to JSON. - * @returns JSON object - */ - public toJSON(): { [k: string]: any }; - } + /** Value bytesValue. */ + public bytesValue?: (Uint8Array|null); - /** Properties of a DescriptorProto. */ - interface IDescriptorProto { + /** Value referenceValue. */ + public referenceValue?: (string|null); - /** DescriptorProto name */ - name?: (string|null); + /** Value geoPointValue. */ + public geoPointValue?: (google.type.ILatLng|null); - /** DescriptorProto field */ - field?: (google.protobuf.IFieldDescriptorProto[]|null); + /** Value arrayValue. */ + public arrayValue?: (google.firestore.v1.IArrayValue|null); - /** DescriptorProto extension */ - extension?: (google.protobuf.IFieldDescriptorProto[]|null); + /** Value mapValue. */ + public mapValue?: (google.firestore.v1.IMapValue|null); - /** DescriptorProto nestedType */ - nestedType?: (google.protobuf.IDescriptorProto[]|null); + /** Value valueType. */ + public valueType?: ("nullValue"|"booleanValue"|"integerValue"|"doubleValue"|"timestampValue"|"stringValue"|"bytesValue"|"referenceValue"|"geoPointValue"|"arrayValue"|"mapValue"); - /** DescriptorProto enumType */ - enumType?: (google.protobuf.IEnumDescriptorProto[]|null); + /** + * Creates a Value message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns Value + */ + public static fromObject(object: { [k: string]: any }): google.firestore.v1.Value; - /** DescriptorProto extensionRange */ - extensionRange?: (google.protobuf.DescriptorProto.IExtensionRange[]|null); + /** + * Creates a plain object from a Value message. Also converts values to other types if specified. + * @param message Value + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.firestore.v1.Value, options?: $protobuf.IConversionOptions): { [k: string]: any }; - /** DescriptorProto oneofDecl */ - oneofDecl?: (google.protobuf.IOneofDescriptorProto[]|null); + /** + * Converts this Value to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; - /** DescriptorProto options */ - options?: (google.protobuf.IMessageOptions|null); + /** + * Gets the default type url for Value + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } - /** DescriptorProto reservedRange */ - reservedRange?: (google.protobuf.DescriptorProto.IReservedRange[]|null); + /** Properties of an ArrayValue. */ + interface IArrayValue { - /** DescriptorProto reservedName */ - reservedName?: (string[]|null); - } + /** ArrayValue values */ + values?: (google.firestore.v1.IValue[]|null); + } - /** Represents a DescriptorProto. */ - class DescriptorProto implements IDescriptorProto { + /** Represents an ArrayValue. */ + class ArrayValue implements IArrayValue { - /** - * Constructs a new DescriptorProto. - * @param [properties] Properties to set - */ - constructor(properties?: google.protobuf.IDescriptorProto); + /** + * Constructs a new ArrayValue. + * @param [properties] Properties to set + */ + constructor(properties?: google.firestore.v1.IArrayValue); - /** DescriptorProto name. */ - public name: string; + /** ArrayValue values. */ + public values: google.firestore.v1.IValue[]; - /** DescriptorProto field. */ - public field: google.protobuf.IFieldDescriptorProto[]; + /** + * Creates an ArrayValue message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns ArrayValue + */ + public static fromObject(object: { [k: string]: any }): google.firestore.v1.ArrayValue; - /** DescriptorProto extension. */ - public extension: google.protobuf.IFieldDescriptorProto[]; + /** + * Creates a plain object from an ArrayValue message. Also converts values to other types if specified. + * @param message ArrayValue + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.firestore.v1.ArrayValue, options?: $protobuf.IConversionOptions): { [k: string]: any }; - /** DescriptorProto nestedType. */ - public nestedType: google.protobuf.IDescriptorProto[]; + /** + * Converts this ArrayValue to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; - /** DescriptorProto enumType. */ - public enumType: google.protobuf.IEnumDescriptorProto[]; + /** + * Gets the default type url for ArrayValue + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } - /** DescriptorProto extensionRange. */ - public extensionRange: google.protobuf.DescriptorProto.IExtensionRange[]; + /** Properties of a MapValue. */ + interface IMapValue { - /** DescriptorProto oneofDecl. */ - public oneofDecl: google.protobuf.IOneofDescriptorProto[]; + /** MapValue fields */ + fields?: ({ [k: string]: google.firestore.v1.IValue }|null); + } - /** DescriptorProto options. */ - public options?: (google.protobuf.IMessageOptions|null); + /** Represents a MapValue. */ + class MapValue implements IMapValue { - /** DescriptorProto reservedRange. */ - public reservedRange: google.protobuf.DescriptorProto.IReservedRange[]; + /** + * Constructs a new MapValue. + * @param [properties] Properties to set + */ + constructor(properties?: google.firestore.v1.IMapValue); - /** DescriptorProto reservedName. */ - public reservedName: string[]; + /** MapValue fields. */ + public fields: { [k: string]: google.firestore.v1.IValue }; - /** - * Creates a DescriptorProto message from a plain object. Also converts values to their respective internal types. - * @param object Plain object - * @returns DescriptorProto - */ - public static fromObject(object: { [k: string]: any }): google.protobuf.DescriptorProto; + /** + * Creates a MapValue message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns MapValue + */ + public static fromObject(object: { [k: string]: any }): google.firestore.v1.MapValue; - /** - * Creates a plain object from a DescriptorProto message. Also converts values to other types if specified. - * @param message DescriptorProto - * @param [options] Conversion options - * @returns Plain object - */ - public static toObject(message: google.protobuf.DescriptorProto, options?: $protobuf.IConversionOptions): { [k: string]: any }; + /** + * Creates a plain object from a MapValue message. Also converts values to other types if specified. + * @param message MapValue + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.firestore.v1.MapValue, options?: $protobuf.IConversionOptions): { [k: string]: any }; - /** - * Converts this DescriptorProto to JSON. - * @returns JSON object - */ - public toJSON(): { [k: string]: any }; - } + /** + * Converts this MapValue to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; - namespace DescriptorProto { + /** + * Gets the default type url for MapValue + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } - /** Properties of an ExtensionRange. */ - interface IExtensionRange { + /** Properties of a BitSequence. */ + interface IBitSequence { - /** ExtensionRange start */ - start?: (number|null); + /** BitSequence bitmap */ + bitmap?: (Uint8Array|null); - /** ExtensionRange end */ - end?: (number|null); + /** BitSequence padding */ + padding?: (number|null); } - /** Represents an ExtensionRange. */ - class ExtensionRange implements IExtensionRange { + /** Represents a BitSequence. */ + class BitSequence implements IBitSequence { /** - * Constructs a new ExtensionRange. + * Constructs a new BitSequence. * @param [properties] Properties to set */ - constructor(properties?: google.protobuf.DescriptorProto.IExtensionRange); + constructor(properties?: google.firestore.v1.IBitSequence); - /** ExtensionRange start. */ - public start: number; + /** BitSequence bitmap. */ + public bitmap: Uint8Array; - /** ExtensionRange end. */ - public end: number; + /** BitSequence padding. */ + public padding: number; /** - * Creates an ExtensionRange message from a plain object. Also converts values to their respective internal types. + * Creates a BitSequence message from a plain object. Also converts values to their respective internal types. * @param object Plain object - * @returns ExtensionRange + * @returns BitSequence */ - public static fromObject(object: { [k: string]: any }): google.protobuf.DescriptorProto.ExtensionRange; + public static fromObject(object: { [k: string]: any }): google.firestore.v1.BitSequence; /** - * Creates a plain object from an ExtensionRange message. Also converts values to other types if specified. - * @param message ExtensionRange + * Creates a plain object from a BitSequence message. Also converts values to other types if specified. + * @param message BitSequence * @param [options] Conversion options * @returns Plain object */ - public static toObject(message: google.protobuf.DescriptorProto.ExtensionRange, options?: $protobuf.IConversionOptions): { [k: string]: any }; + public static toObject(message: google.firestore.v1.BitSequence, options?: $protobuf.IConversionOptions): { [k: string]: any }; /** - * Converts this ExtensionRange to JSON. + * Converts this BitSequence to JSON. * @returns JSON object */ public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for BitSequence + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; } - /** Properties of a ReservedRange. */ - interface IReservedRange { + /** Properties of a BloomFilter. */ + interface IBloomFilter { - /** ReservedRange start */ - start?: (number|null); + /** BloomFilter bits */ + bits?: (google.firestore.v1.IBitSequence|null); - /** ReservedRange end */ - end?: (number|null); + /** BloomFilter hashCount */ + hashCount?: (number|null); } - /** Represents a ReservedRange. */ - class ReservedRange implements IReservedRange { + /** Represents a BloomFilter. */ + class BloomFilter implements IBloomFilter { /** - * Constructs a new ReservedRange. + * Constructs a new BloomFilter. * @param [properties] Properties to set */ - constructor(properties?: google.protobuf.DescriptorProto.IReservedRange); + constructor(properties?: google.firestore.v1.IBloomFilter); - /** ReservedRange start. */ - public start: number; + /** BloomFilter bits. */ + public bits?: (google.firestore.v1.IBitSequence|null); - /** ReservedRange end. */ - public end: number; + /** BloomFilter hashCount. */ + public hashCount: number; /** - * Creates a ReservedRange message from a plain object. Also converts values to their respective internal types. + * Creates a BloomFilter message from a plain object. Also converts values to their respective internal types. * @param object Plain object - * @returns ReservedRange + * @returns BloomFilter */ - public static fromObject(object: { [k: string]: any }): google.protobuf.DescriptorProto.ReservedRange; + public static fromObject(object: { [k: string]: any }): google.firestore.v1.BloomFilter; /** - * Creates a plain object from a ReservedRange message. Also converts values to other types if specified. - * @param message ReservedRange + * Creates a plain object from a BloomFilter message. Also converts values to other types if specified. + * @param message BloomFilter * @param [options] Conversion options * @returns Plain object */ - public static toObject(message: google.protobuf.DescriptorProto.ReservedRange, options?: $protobuf.IConversionOptions): { [k: string]: any }; + public static toObject(message: google.firestore.v1.BloomFilter, options?: $protobuf.IConversionOptions): { [k: string]: any }; /** - * Converts this ReservedRange to JSON. + * Converts this BloomFilter to JSON. * @returns JSON object */ public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for BloomFilter + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; } - } - /** Properties of a FieldDescriptorProto. */ - interface IFieldDescriptorProto { + /** Properties of a DocumentMask. */ + interface IDocumentMask { - /** FieldDescriptorProto name */ - name?: (string|null); + /** DocumentMask fieldPaths */ + fieldPaths?: (string[]|null); + } - /** FieldDescriptorProto number */ - number?: (number|null); - - /** FieldDescriptorProto label */ - label?: (google.protobuf.FieldDescriptorProto.Label|null); + /** Represents a DocumentMask. */ + class DocumentMask implements IDocumentMask { - /** FieldDescriptorProto type */ - type?: (google.protobuf.FieldDescriptorProto.Type|null); + /** + * Constructs a new DocumentMask. + * @param [properties] Properties to set + */ + constructor(properties?: google.firestore.v1.IDocumentMask); - /** FieldDescriptorProto typeName */ - typeName?: (string|null); + /** DocumentMask fieldPaths. */ + public fieldPaths: string[]; - /** FieldDescriptorProto extendee */ - extendee?: (string|null); + /** + * Creates a DocumentMask message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns DocumentMask + */ + public static fromObject(object: { [k: string]: any }): google.firestore.v1.DocumentMask; - /** FieldDescriptorProto defaultValue */ - defaultValue?: (string|null); + /** + * Creates a plain object from a DocumentMask message. Also converts values to other types if specified. + * @param message DocumentMask + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.firestore.v1.DocumentMask, options?: $protobuf.IConversionOptions): { [k: string]: any }; - /** FieldDescriptorProto oneofIndex */ - oneofIndex?: (number|null); + /** + * Converts this DocumentMask to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; - /** FieldDescriptorProto jsonName */ - jsonName?: (string|null); + /** + * Gets the default type url for DocumentMask + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } - /** FieldDescriptorProto options */ - options?: (google.protobuf.IFieldOptions|null); - } + /** Properties of a Precondition. */ + interface IPrecondition { - /** Represents a FieldDescriptorProto. */ - class FieldDescriptorProto implements IFieldDescriptorProto { + /** Precondition exists */ + exists?: (boolean|null); - /** - * Constructs a new FieldDescriptorProto. - * @param [properties] Properties to set - */ - constructor(properties?: google.protobuf.IFieldDescriptorProto); + /** Precondition updateTime */ + updateTime?: (google.protobuf.ITimestamp|null); + } - /** FieldDescriptorProto name. */ - public name: string; + /** Represents a Precondition. */ + class Precondition implements IPrecondition { - /** FieldDescriptorProto number. */ - public number: number; + /** + * Constructs a new Precondition. + * @param [properties] Properties to set + */ + constructor(properties?: google.firestore.v1.IPrecondition); - /** FieldDescriptorProto label. */ - public label: google.protobuf.FieldDescriptorProto.Label; + /** Precondition exists. */ + public exists?: (boolean|null); - /** FieldDescriptorProto type. */ - public type: google.protobuf.FieldDescriptorProto.Type; + /** Precondition updateTime. */ + public updateTime?: (google.protobuf.ITimestamp|null); - /** FieldDescriptorProto typeName. */ - public typeName: string; + /** Precondition conditionType. */ + public conditionType?: ("exists"|"updateTime"); - /** FieldDescriptorProto extendee. */ - public extendee: string; + /** + * Creates a Precondition message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns Precondition + */ + public static fromObject(object: { [k: string]: any }): google.firestore.v1.Precondition; - /** FieldDescriptorProto defaultValue. */ - public defaultValue: string; + /** + * Creates a plain object from a Precondition message. Also converts values to other types if specified. + * @param message Precondition + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.firestore.v1.Precondition, options?: $protobuf.IConversionOptions): { [k: string]: any }; - /** FieldDescriptorProto oneofIndex. */ - public oneofIndex: number; + /** + * Converts this Precondition to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; - /** FieldDescriptorProto jsonName. */ - public jsonName: string; + /** + * Gets the default type url for Precondition + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } - /** FieldDescriptorProto options. */ - public options?: (google.protobuf.IFieldOptions|null); + /** Properties of a TransactionOptions. */ + interface ITransactionOptions { - /** - * Creates a FieldDescriptorProto message from a plain object. Also converts values to their respective internal types. - * @param object Plain object - * @returns FieldDescriptorProto - */ - public static fromObject(object: { [k: string]: any }): google.protobuf.FieldDescriptorProto; + /** TransactionOptions readOnly */ + readOnly?: (google.firestore.v1.TransactionOptions.IReadOnly|null); - /** - * Creates a plain object from a FieldDescriptorProto message. Also converts values to other types if specified. - * @param message FieldDescriptorProto - * @param [options] Conversion options - * @returns Plain object - */ - public static toObject(message: google.protobuf.FieldDescriptorProto, options?: $protobuf.IConversionOptions): { [k: string]: any }; + /** TransactionOptions readWrite */ + readWrite?: (google.firestore.v1.TransactionOptions.IReadWrite|null); + } - /** - * Converts this FieldDescriptorProto to JSON. - * @returns JSON object - */ - public toJSON(): { [k: string]: any }; - } + /** Represents a TransactionOptions. */ + class TransactionOptions implements ITransactionOptions { - namespace FieldDescriptorProto { + /** + * Constructs a new TransactionOptions. + * @param [properties] Properties to set + */ + constructor(properties?: google.firestore.v1.ITransactionOptions); - /** Type enum. */ - type Type = - "TYPE_DOUBLE"| "TYPE_FLOAT"| "TYPE_INT64"| "TYPE_UINT64"| "TYPE_INT32"| "TYPE_FIXED64"| "TYPE_FIXED32"| "TYPE_BOOL"| "TYPE_STRING"| "TYPE_GROUP"| "TYPE_MESSAGE"| "TYPE_BYTES"| "TYPE_UINT32"| "TYPE_ENUM"| "TYPE_SFIXED32"| "TYPE_SFIXED64"| "TYPE_SINT32"| "TYPE_SINT64"; + /** TransactionOptions readOnly. */ + public readOnly?: (google.firestore.v1.TransactionOptions.IReadOnly|null); - /** Label enum. */ - type Label = - "LABEL_OPTIONAL"| "LABEL_REQUIRED"| "LABEL_REPEATED"; - } + /** TransactionOptions readWrite. */ + public readWrite?: (google.firestore.v1.TransactionOptions.IReadWrite|null); - /** Properties of an OneofDescriptorProto. */ - interface IOneofDescriptorProto { + /** TransactionOptions mode. */ + public mode?: ("readOnly"|"readWrite"); - /** OneofDescriptorProto name */ - name?: (string|null); + /** + * Creates a TransactionOptions message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns TransactionOptions + */ + public static fromObject(object: { [k: string]: any }): google.firestore.v1.TransactionOptions; - /** OneofDescriptorProto options */ - options?: (google.protobuf.IOneofOptions|null); - } + /** + * Creates a plain object from a TransactionOptions message. Also converts values to other types if specified. + * @param message TransactionOptions + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.firestore.v1.TransactionOptions, options?: $protobuf.IConversionOptions): { [k: string]: any }; - /** Represents an OneofDescriptorProto. */ - class OneofDescriptorProto implements IOneofDescriptorProto { + /** + * Converts this TransactionOptions to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; - /** - * Constructs a new OneofDescriptorProto. - * @param [properties] Properties to set - */ - constructor(properties?: google.protobuf.IOneofDescriptorProto); + /** + * Gets the default type url for TransactionOptions + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } - /** OneofDescriptorProto name. */ - public name: string; + namespace TransactionOptions { - /** OneofDescriptorProto options. */ - public options?: (google.protobuf.IOneofOptions|null); + /** Properties of a ReadWrite. */ + interface IReadWrite { - /** - * Creates an OneofDescriptorProto message from a plain object. Also converts values to their respective internal types. - * @param object Plain object - * @returns OneofDescriptorProto - */ - public static fromObject(object: { [k: string]: any }): google.protobuf.OneofDescriptorProto; + /** ReadWrite retryTransaction */ + retryTransaction?: (Uint8Array|null); + } - /** - * Creates a plain object from an OneofDescriptorProto message. Also converts values to other types if specified. - * @param message OneofDescriptorProto - * @param [options] Conversion options - * @returns Plain object - */ - public static toObject(message: google.protobuf.OneofDescriptorProto, options?: $protobuf.IConversionOptions): { [k: string]: any }; + /** Represents a ReadWrite. */ + class ReadWrite implements IReadWrite { - /** - * Converts this OneofDescriptorProto to JSON. - * @returns JSON object - */ - public toJSON(): { [k: string]: any }; - } + /** + * Constructs a new ReadWrite. + * @param [properties] Properties to set + */ + constructor(properties?: google.firestore.v1.TransactionOptions.IReadWrite); - /** Properties of an EnumDescriptorProto. */ - interface IEnumDescriptorProto { + /** ReadWrite retryTransaction. */ + public retryTransaction: Uint8Array; - /** EnumDescriptorProto name */ - name?: (string|null); + /** + * Creates a ReadWrite message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns ReadWrite + */ + public static fromObject(object: { [k: string]: any }): google.firestore.v1.TransactionOptions.ReadWrite; - /** EnumDescriptorProto value */ - value?: (google.protobuf.IEnumValueDescriptorProto[]|null); + /** + * Creates a plain object from a ReadWrite message. Also converts values to other types if specified. + * @param message ReadWrite + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.firestore.v1.TransactionOptions.ReadWrite, options?: $protobuf.IConversionOptions): { [k: string]: any }; - /** EnumDescriptorProto options */ - options?: (google.protobuf.IEnumOptions|null); - } + /** + * Converts this ReadWrite to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for ReadWrite + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a ReadOnly. */ + interface IReadOnly { + + /** ReadOnly readTime */ + readTime?: (google.protobuf.ITimestamp|null); + } + + /** Represents a ReadOnly. */ + class ReadOnly implements IReadOnly { + + /** + * Constructs a new ReadOnly. + * @param [properties] Properties to set + */ + constructor(properties?: google.firestore.v1.TransactionOptions.IReadOnly); + + /** ReadOnly readTime. */ + public readTime?: (google.protobuf.ITimestamp|null); + + /** ReadOnly consistencySelector. */ + public consistencySelector?: "readTime"; + + /** + * Creates a ReadOnly message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns ReadOnly + */ + public static fromObject(object: { [k: string]: any }): google.firestore.v1.TransactionOptions.ReadOnly; + + /** + * Creates a plain object from a ReadOnly message. Also converts values to other types if specified. + * @param message ReadOnly + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.firestore.v1.TransactionOptions.ReadOnly, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this ReadOnly to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for ReadOnly + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + } + + /** Represents a Firestore */ + class Firestore extends $protobuf.rpc.Service { + + /** + * Constructs a new Firestore service. + * @param rpcImpl RPC implementation + * @param [requestDelimited=false] Whether requests are length-delimited + * @param [responseDelimited=false] Whether responses are length-delimited + */ + constructor(rpcImpl: $protobuf.RPCImpl, requestDelimited?: boolean, responseDelimited?: boolean); + + /** + * Calls GetDocument. + * @param request GetDocumentRequest message or plain object + * @param callback Node-style callback called with the error, if any, and Document + */ + public getDocument(request: google.firestore.v1.IGetDocumentRequest, callback: google.firestore.v1.Firestore.GetDocumentCallback): void; + + /** + * Calls GetDocument. + * @param request GetDocumentRequest message or plain object + * @returns Promise + */ + public getDocument(request: google.firestore.v1.IGetDocumentRequest): Promise; + + /** + * Calls ListDocuments. + * @param request ListDocumentsRequest message or plain object + * @param callback Node-style callback called with the error, if any, and ListDocumentsResponse + */ + public listDocuments(request: google.firestore.v1.IListDocumentsRequest, callback: google.firestore.v1.Firestore.ListDocumentsCallback): void; + + /** + * Calls ListDocuments. + * @param request ListDocumentsRequest message or plain object + * @returns Promise + */ + public listDocuments(request: google.firestore.v1.IListDocumentsRequest): Promise; + + /** + * Calls UpdateDocument. + * @param request UpdateDocumentRequest message or plain object + * @param callback Node-style callback called with the error, if any, and Document + */ + public updateDocument(request: google.firestore.v1.IUpdateDocumentRequest, callback: google.firestore.v1.Firestore.UpdateDocumentCallback): void; + + /** + * Calls UpdateDocument. + * @param request UpdateDocumentRequest message or plain object + * @returns Promise + */ + public updateDocument(request: google.firestore.v1.IUpdateDocumentRequest): Promise; + + /** + * Calls DeleteDocument. + * @param request DeleteDocumentRequest message or plain object + * @param callback Node-style callback called with the error, if any, and Empty + */ + public deleteDocument(request: google.firestore.v1.IDeleteDocumentRequest, callback: google.firestore.v1.Firestore.DeleteDocumentCallback): void; + + /** + * Calls DeleteDocument. + * @param request DeleteDocumentRequest message or plain object + * @returns Promise + */ + public deleteDocument(request: google.firestore.v1.IDeleteDocumentRequest): Promise; + + /** + * Calls BatchGetDocuments. + * @param request BatchGetDocumentsRequest message or plain object + * @param callback Node-style callback called with the error, if any, and BatchGetDocumentsResponse + */ + public batchGetDocuments(request: google.firestore.v1.IBatchGetDocumentsRequest, callback: google.firestore.v1.Firestore.BatchGetDocumentsCallback): void; + + /** + * Calls BatchGetDocuments. + * @param request BatchGetDocumentsRequest message or plain object + * @returns Promise + */ + public batchGetDocuments(request: google.firestore.v1.IBatchGetDocumentsRequest): Promise; + + /** + * Calls BeginTransaction. + * @param request BeginTransactionRequest message or plain object + * @param callback Node-style callback called with the error, if any, and BeginTransactionResponse + */ + public beginTransaction(request: google.firestore.v1.IBeginTransactionRequest, callback: google.firestore.v1.Firestore.BeginTransactionCallback): void; + + /** + * Calls BeginTransaction. + * @param request BeginTransactionRequest message or plain object + * @returns Promise + */ + public beginTransaction(request: google.firestore.v1.IBeginTransactionRequest): Promise; + + /** + * Calls Commit. + * @param request CommitRequest message or plain object + * @param callback Node-style callback called with the error, if any, and CommitResponse + */ + public commit(request: google.firestore.v1.ICommitRequest, callback: google.firestore.v1.Firestore.CommitCallback): void; + + /** + * Calls Commit. + * @param request CommitRequest message or plain object + * @returns Promise + */ + public commit(request: google.firestore.v1.ICommitRequest): Promise; + + /** + * Calls Rollback. + * @param request RollbackRequest message or plain object + * @param callback Node-style callback called with the error, if any, and Empty + */ + public rollback(request: google.firestore.v1.IRollbackRequest, callback: google.firestore.v1.Firestore.RollbackCallback): void; + + /** + * Calls Rollback. + * @param request RollbackRequest message or plain object + * @returns Promise + */ + public rollback(request: google.firestore.v1.IRollbackRequest): Promise; + + /** + * Calls RunQuery. + * @param request RunQueryRequest message or plain object + * @param callback Node-style callback called with the error, if any, and RunQueryResponse + */ + public runQuery(request: google.firestore.v1.IRunQueryRequest, callback: google.firestore.v1.Firestore.RunQueryCallback): void; + + /** + * Calls RunQuery. + * @param request RunQueryRequest message or plain object + * @returns Promise + */ + public runQuery(request: google.firestore.v1.IRunQueryRequest): Promise; + + /** + * Calls RunAggregationQuery. + * @param request RunAggregationQueryRequest message or plain object + * @param callback Node-style callback called with the error, if any, and RunAggregationQueryResponse + */ + public runAggregationQuery(request: google.firestore.v1.IRunAggregationQueryRequest, callback: google.firestore.v1.Firestore.RunAggregationQueryCallback): void; + + /** + * Calls RunAggregationQuery. + * @param request RunAggregationQueryRequest message or plain object + * @returns Promise + */ + public runAggregationQuery(request: google.firestore.v1.IRunAggregationQueryRequest): Promise; + + /** + * Calls PartitionQuery. + * @param request PartitionQueryRequest message or plain object + * @param callback Node-style callback called with the error, if any, and PartitionQueryResponse + */ + public partitionQuery(request: google.firestore.v1.IPartitionQueryRequest, callback: google.firestore.v1.Firestore.PartitionQueryCallback): void; + + /** + * Calls PartitionQuery. + * @param request PartitionQueryRequest message or plain object + * @returns Promise + */ + public partitionQuery(request: google.firestore.v1.IPartitionQueryRequest): Promise; + + /** + * Calls Write. + * @param request WriteRequest message or plain object + * @param callback Node-style callback called with the error, if any, and WriteResponse + */ + public write(request: google.firestore.v1.IWriteRequest, callback: google.firestore.v1.Firestore.WriteCallback): void; + + /** + * Calls Write. + * @param request WriteRequest message or plain object + * @returns Promise + */ + public write(request: google.firestore.v1.IWriteRequest): Promise; + + /** + * Calls Listen. + * @param request ListenRequest message or plain object + * @param callback Node-style callback called with the error, if any, and ListenResponse + */ + public listen(request: google.firestore.v1.IListenRequest, callback: google.firestore.v1.Firestore.ListenCallback): void; + + /** + * Calls Listen. + * @param request ListenRequest message or plain object + * @returns Promise + */ + public listen(request: google.firestore.v1.IListenRequest): Promise; + + /** + * Calls ListCollectionIds. + * @param request ListCollectionIdsRequest message or plain object + * @param callback Node-style callback called with the error, if any, and ListCollectionIdsResponse + */ + public listCollectionIds(request: google.firestore.v1.IListCollectionIdsRequest, callback: google.firestore.v1.Firestore.ListCollectionIdsCallback): void; + + /** + * Calls ListCollectionIds. + * @param request ListCollectionIdsRequest message or plain object + * @returns Promise + */ + public listCollectionIds(request: google.firestore.v1.IListCollectionIdsRequest): Promise; + + /** + * Calls BatchWrite. + * @param request BatchWriteRequest message or plain object + * @param callback Node-style callback called with the error, if any, and BatchWriteResponse + */ + public batchWrite(request: google.firestore.v1.IBatchWriteRequest, callback: google.firestore.v1.Firestore.BatchWriteCallback): void; + + /** + * Calls BatchWrite. + * @param request BatchWriteRequest message or plain object + * @returns Promise + */ + public batchWrite(request: google.firestore.v1.IBatchWriteRequest): Promise; + + /** + * Calls CreateDocument. + * @param request CreateDocumentRequest message or plain object + * @param callback Node-style callback called with the error, if any, and Document + */ + public createDocument(request: google.firestore.v1.ICreateDocumentRequest, callback: google.firestore.v1.Firestore.CreateDocumentCallback): void; + + /** + * Calls CreateDocument. + * @param request CreateDocumentRequest message or plain object + * @returns Promise + */ + public createDocument(request: google.firestore.v1.ICreateDocumentRequest): Promise; + } + + namespace Firestore { + + /** + * Callback as used by {@link google.firestore.v1.Firestore#getDocument}. + * @param error Error, if any + * @param [response] Document + */ + type GetDocumentCallback = (error: (Error|null), response?: google.firestore.v1.Document) => void; + + /** + * Callback as used by {@link google.firestore.v1.Firestore#listDocuments}. + * @param error Error, if any + * @param [response] ListDocumentsResponse + */ + type ListDocumentsCallback = (error: (Error|null), response?: google.firestore.v1.ListDocumentsResponse) => void; + + /** + * Callback as used by {@link google.firestore.v1.Firestore#updateDocument}. + * @param error Error, if any + * @param [response] Document + */ + type UpdateDocumentCallback = (error: (Error|null), response?: google.firestore.v1.Document) => void; + + /** + * Callback as used by {@link google.firestore.v1.Firestore#deleteDocument}. + * @param error Error, if any + * @param [response] Empty + */ + type DeleteDocumentCallback = (error: (Error|null), response?: google.protobuf.Empty) => void; + + /** + * Callback as used by {@link google.firestore.v1.Firestore#batchGetDocuments}. + * @param error Error, if any + * @param [response] BatchGetDocumentsResponse + */ + type BatchGetDocumentsCallback = (error: (Error|null), response?: google.firestore.v1.BatchGetDocumentsResponse) => void; + + /** + * Callback as used by {@link google.firestore.v1.Firestore#beginTransaction}. + * @param error Error, if any + * @param [response] BeginTransactionResponse + */ + type BeginTransactionCallback = (error: (Error|null), response?: google.firestore.v1.BeginTransactionResponse) => void; + + /** + * Callback as used by {@link google.firestore.v1.Firestore#commit}. + * @param error Error, if any + * @param [response] CommitResponse + */ + type CommitCallback = (error: (Error|null), response?: google.firestore.v1.CommitResponse) => void; + + /** + * Callback as used by {@link google.firestore.v1.Firestore#rollback}. + * @param error Error, if any + * @param [response] Empty + */ + type RollbackCallback = (error: (Error|null), response?: google.protobuf.Empty) => void; + + /** + * Callback as used by {@link google.firestore.v1.Firestore#runQuery}. + * @param error Error, if any + * @param [response] RunQueryResponse + */ + type RunQueryCallback = (error: (Error|null), response?: google.firestore.v1.RunQueryResponse) => void; + + /** + * Callback as used by {@link google.firestore.v1.Firestore#runAggregationQuery}. + * @param error Error, if any + * @param [response] RunAggregationQueryResponse + */ + type RunAggregationQueryCallback = (error: (Error|null), response?: google.firestore.v1.RunAggregationQueryResponse) => void; + + /** + * Callback as used by {@link google.firestore.v1.Firestore#partitionQuery}. + * @param error Error, if any + * @param [response] PartitionQueryResponse + */ + type PartitionQueryCallback = (error: (Error|null), response?: google.firestore.v1.PartitionQueryResponse) => void; + + /** + * Callback as used by {@link google.firestore.v1.Firestore#write}. + * @param error Error, if any + * @param [response] WriteResponse + */ + type WriteCallback = (error: (Error|null), response?: google.firestore.v1.WriteResponse) => void; + + /** + * Callback as used by {@link google.firestore.v1.Firestore#listen}. + * @param error Error, if any + * @param [response] ListenResponse + */ + type ListenCallback = (error: (Error|null), response?: google.firestore.v1.ListenResponse) => void; + + /** + * Callback as used by {@link google.firestore.v1.Firestore#listCollectionIds}. + * @param error Error, if any + * @param [response] ListCollectionIdsResponse + */ + type ListCollectionIdsCallback = (error: (Error|null), response?: google.firestore.v1.ListCollectionIdsResponse) => void; + + /** + * Callback as used by {@link google.firestore.v1.Firestore#batchWrite}. + * @param error Error, if any + * @param [response] BatchWriteResponse + */ + type BatchWriteCallback = (error: (Error|null), response?: google.firestore.v1.BatchWriteResponse) => void; + + /** + * Callback as used by {@link google.firestore.v1.Firestore#createDocument}. + * @param error Error, if any + * @param [response] Document + */ + type CreateDocumentCallback = (error: (Error|null), response?: google.firestore.v1.Document) => void; + } + + /** Properties of a GetDocumentRequest. */ + interface IGetDocumentRequest { + + /** GetDocumentRequest name */ + name?: (string|null); + + /** GetDocumentRequest mask */ + mask?: (google.firestore.v1.IDocumentMask|null); + + /** GetDocumentRequest transaction */ + transaction?: (Uint8Array|null); + + /** GetDocumentRequest readTime */ + readTime?: (google.protobuf.ITimestamp|null); + } + + /** Represents a GetDocumentRequest. */ + class GetDocumentRequest implements IGetDocumentRequest { + + /** + * Constructs a new GetDocumentRequest. + * @param [properties] Properties to set + */ + constructor(properties?: google.firestore.v1.IGetDocumentRequest); + + /** GetDocumentRequest name. */ + public name: string; + + /** GetDocumentRequest mask. */ + public mask?: (google.firestore.v1.IDocumentMask|null); + + /** GetDocumentRequest transaction. */ + public transaction?: (Uint8Array|null); + + /** GetDocumentRequest readTime. */ + public readTime?: (google.protobuf.ITimestamp|null); + + /** GetDocumentRequest consistencySelector. */ + public consistencySelector?: ("transaction"|"readTime"); + + /** + * Creates a GetDocumentRequest message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns GetDocumentRequest + */ + public static fromObject(object: { [k: string]: any }): google.firestore.v1.GetDocumentRequest; + + /** + * Creates a plain object from a GetDocumentRequest message. Also converts values to other types if specified. + * @param message GetDocumentRequest + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.firestore.v1.GetDocumentRequest, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this GetDocumentRequest to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for GetDocumentRequest + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a ListDocumentsRequest. */ + interface IListDocumentsRequest { + + /** ListDocumentsRequest parent */ + parent?: (string|null); + + /** ListDocumentsRequest collectionId */ + collectionId?: (string|null); + + /** ListDocumentsRequest pageSize */ + pageSize?: (number|null); + + /** ListDocumentsRequest pageToken */ + pageToken?: (string|null); + + /** ListDocumentsRequest orderBy */ + orderBy?: (string|null); + + /** ListDocumentsRequest mask */ + mask?: (google.firestore.v1.IDocumentMask|null); + + /** ListDocumentsRequest transaction */ + transaction?: (Uint8Array|null); + + /** ListDocumentsRequest readTime */ + readTime?: (google.protobuf.ITimestamp|null); + + /** ListDocumentsRequest showMissing */ + showMissing?: (boolean|null); + } + + /** Represents a ListDocumentsRequest. */ + class ListDocumentsRequest implements IListDocumentsRequest { + + /** + * Constructs a new ListDocumentsRequest. + * @param [properties] Properties to set + */ + constructor(properties?: google.firestore.v1.IListDocumentsRequest); + + /** ListDocumentsRequest parent. */ + public parent: string; + + /** ListDocumentsRequest collectionId. */ + public collectionId: string; + + /** ListDocumentsRequest pageSize. */ + public pageSize: number; + + /** ListDocumentsRequest pageToken. */ + public pageToken: string; + + /** ListDocumentsRequest orderBy. */ + public orderBy: string; + + /** ListDocumentsRequest mask. */ + public mask?: (google.firestore.v1.IDocumentMask|null); + + /** ListDocumentsRequest transaction. */ + public transaction?: (Uint8Array|null); + + /** ListDocumentsRequest readTime. */ + public readTime?: (google.protobuf.ITimestamp|null); + + /** ListDocumentsRequest showMissing. */ + public showMissing: boolean; + + /** ListDocumentsRequest consistencySelector. */ + public consistencySelector?: ("transaction"|"readTime"); + + /** + * Creates a ListDocumentsRequest message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns ListDocumentsRequest + */ + public static fromObject(object: { [k: string]: any }): google.firestore.v1.ListDocumentsRequest; + + /** + * Creates a plain object from a ListDocumentsRequest message. Also converts values to other types if specified. + * @param message ListDocumentsRequest + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.firestore.v1.ListDocumentsRequest, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this ListDocumentsRequest to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for ListDocumentsRequest + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a ListDocumentsResponse. */ + interface IListDocumentsResponse { + + /** ListDocumentsResponse documents */ + documents?: (google.firestore.v1.IDocument[]|null); + + /** ListDocumentsResponse nextPageToken */ + nextPageToken?: (string|null); + } + + /** Represents a ListDocumentsResponse. */ + class ListDocumentsResponse implements IListDocumentsResponse { + + /** + * Constructs a new ListDocumentsResponse. + * @param [properties] Properties to set + */ + constructor(properties?: google.firestore.v1.IListDocumentsResponse); + + /** ListDocumentsResponse documents. */ + public documents: google.firestore.v1.IDocument[]; + + /** ListDocumentsResponse nextPageToken. */ + public nextPageToken: string; + + /** + * Creates a ListDocumentsResponse message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns ListDocumentsResponse + */ + public static fromObject(object: { [k: string]: any }): google.firestore.v1.ListDocumentsResponse; + + /** + * Creates a plain object from a ListDocumentsResponse message. Also converts values to other types if specified. + * @param message ListDocumentsResponse + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.firestore.v1.ListDocumentsResponse, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this ListDocumentsResponse to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for ListDocumentsResponse + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a CreateDocumentRequest. */ + interface ICreateDocumentRequest { + + /** CreateDocumentRequest parent */ + parent?: (string|null); + + /** CreateDocumentRequest collectionId */ + collectionId?: (string|null); + + /** CreateDocumentRequest documentId */ + documentId?: (string|null); + + /** CreateDocumentRequest document */ + document?: (google.firestore.v1.IDocument|null); + + /** CreateDocumentRequest mask */ + mask?: (google.firestore.v1.IDocumentMask|null); + } + + /** Represents a CreateDocumentRequest. */ + class CreateDocumentRequest implements ICreateDocumentRequest { + + /** + * Constructs a new CreateDocumentRequest. + * @param [properties] Properties to set + */ + constructor(properties?: google.firestore.v1.ICreateDocumentRequest); + + /** CreateDocumentRequest parent. */ + public parent: string; + + /** CreateDocumentRequest collectionId. */ + public collectionId: string; + + /** CreateDocumentRequest documentId. */ + public documentId: string; + + /** CreateDocumentRequest document. */ + public document?: (google.firestore.v1.IDocument|null); + + /** CreateDocumentRequest mask. */ + public mask?: (google.firestore.v1.IDocumentMask|null); + + /** + * Creates a CreateDocumentRequest message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns CreateDocumentRequest + */ + public static fromObject(object: { [k: string]: any }): google.firestore.v1.CreateDocumentRequest; + + /** + * Creates a plain object from a CreateDocumentRequest message. Also converts values to other types if specified. + * @param message CreateDocumentRequest + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.firestore.v1.CreateDocumentRequest, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this CreateDocumentRequest to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for CreateDocumentRequest + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of an UpdateDocumentRequest. */ + interface IUpdateDocumentRequest { + + /** UpdateDocumentRequest document */ + document?: (google.firestore.v1.IDocument|null); + + /** UpdateDocumentRequest updateMask */ + updateMask?: (google.firestore.v1.IDocumentMask|null); + + /** UpdateDocumentRequest mask */ + mask?: (google.firestore.v1.IDocumentMask|null); + + /** UpdateDocumentRequest currentDocument */ + currentDocument?: (google.firestore.v1.IPrecondition|null); + } + + /** Represents an UpdateDocumentRequest. */ + class UpdateDocumentRequest implements IUpdateDocumentRequest { + + /** + * Constructs a new UpdateDocumentRequest. + * @param [properties] Properties to set + */ + constructor(properties?: google.firestore.v1.IUpdateDocumentRequest); + + /** UpdateDocumentRequest document. */ + public document?: (google.firestore.v1.IDocument|null); + + /** UpdateDocumentRequest updateMask. */ + public updateMask?: (google.firestore.v1.IDocumentMask|null); + + /** UpdateDocumentRequest mask. */ + public mask?: (google.firestore.v1.IDocumentMask|null); + + /** UpdateDocumentRequest currentDocument. */ + public currentDocument?: (google.firestore.v1.IPrecondition|null); + + /** + * Creates an UpdateDocumentRequest message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns UpdateDocumentRequest + */ + public static fromObject(object: { [k: string]: any }): google.firestore.v1.UpdateDocumentRequest; + + /** + * Creates a plain object from an UpdateDocumentRequest message. Also converts values to other types if specified. + * @param message UpdateDocumentRequest + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.firestore.v1.UpdateDocumentRequest, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this UpdateDocumentRequest to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for UpdateDocumentRequest + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a DeleteDocumentRequest. */ + interface IDeleteDocumentRequest { + + /** DeleteDocumentRequest name */ + name?: (string|null); + + /** DeleteDocumentRequest currentDocument */ + currentDocument?: (google.firestore.v1.IPrecondition|null); + } + + /** Represents a DeleteDocumentRequest. */ + class DeleteDocumentRequest implements IDeleteDocumentRequest { + + /** + * Constructs a new DeleteDocumentRequest. + * @param [properties] Properties to set + */ + constructor(properties?: google.firestore.v1.IDeleteDocumentRequest); + + /** DeleteDocumentRequest name. */ + public name: string; + + /** DeleteDocumentRequest currentDocument. */ + public currentDocument?: (google.firestore.v1.IPrecondition|null); + + /** + * Creates a DeleteDocumentRequest message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns DeleteDocumentRequest + */ + public static fromObject(object: { [k: string]: any }): google.firestore.v1.DeleteDocumentRequest; + + /** + * Creates a plain object from a DeleteDocumentRequest message. Also converts values to other types if specified. + * @param message DeleteDocumentRequest + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.firestore.v1.DeleteDocumentRequest, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this DeleteDocumentRequest to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for DeleteDocumentRequest + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a BatchGetDocumentsRequest. */ + interface IBatchGetDocumentsRequest { + + /** BatchGetDocumentsRequest database */ + database?: (string|null); + + /** BatchGetDocumentsRequest documents */ + documents?: (string[]|null); + + /** BatchGetDocumentsRequest mask */ + mask?: (google.firestore.v1.IDocumentMask|null); + + /** BatchGetDocumentsRequest transaction */ + transaction?: (Uint8Array|null); + + /** BatchGetDocumentsRequest newTransaction */ + newTransaction?: (google.firestore.v1.ITransactionOptions|null); + + /** BatchGetDocumentsRequest readTime */ + readTime?: (google.protobuf.ITimestamp|null); + } + + /** Represents a BatchGetDocumentsRequest. */ + class BatchGetDocumentsRequest implements IBatchGetDocumentsRequest { + + /** + * Constructs a new BatchGetDocumentsRequest. + * @param [properties] Properties to set + */ + constructor(properties?: google.firestore.v1.IBatchGetDocumentsRequest); + + /** BatchGetDocumentsRequest database. */ + public database: string; + + /** BatchGetDocumentsRequest documents. */ + public documents: string[]; + + /** BatchGetDocumentsRequest mask. */ + public mask?: (google.firestore.v1.IDocumentMask|null); + + /** BatchGetDocumentsRequest transaction. */ + public transaction?: (Uint8Array|null); + + /** BatchGetDocumentsRequest newTransaction. */ + public newTransaction?: (google.firestore.v1.ITransactionOptions|null); + + /** BatchGetDocumentsRequest readTime. */ + public readTime?: (google.protobuf.ITimestamp|null); + + /** BatchGetDocumentsRequest consistencySelector. */ + public consistencySelector?: ("transaction"|"newTransaction"|"readTime"); + + /** + * Creates a BatchGetDocumentsRequest message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns BatchGetDocumentsRequest + */ + public static fromObject(object: { [k: string]: any }): google.firestore.v1.BatchGetDocumentsRequest; + + /** + * Creates a plain object from a BatchGetDocumentsRequest message. Also converts values to other types if specified. + * @param message BatchGetDocumentsRequest + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.firestore.v1.BatchGetDocumentsRequest, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this BatchGetDocumentsRequest to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for BatchGetDocumentsRequest + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a BatchGetDocumentsResponse. */ + interface IBatchGetDocumentsResponse { + + /** BatchGetDocumentsResponse found */ + found?: (google.firestore.v1.IDocument|null); + + /** BatchGetDocumentsResponse missing */ + missing?: (string|null); + + /** BatchGetDocumentsResponse transaction */ + transaction?: (Uint8Array|null); + + /** BatchGetDocumentsResponse readTime */ + readTime?: (google.protobuf.ITimestamp|null); + } + + /** Represents a BatchGetDocumentsResponse. */ + class BatchGetDocumentsResponse implements IBatchGetDocumentsResponse { + + /** + * Constructs a new BatchGetDocumentsResponse. + * @param [properties] Properties to set + */ + constructor(properties?: google.firestore.v1.IBatchGetDocumentsResponse); + + /** BatchGetDocumentsResponse found. */ + public found?: (google.firestore.v1.IDocument|null); + + /** BatchGetDocumentsResponse missing. */ + public missing?: (string|null); + + /** BatchGetDocumentsResponse transaction. */ + public transaction: Uint8Array; + + /** BatchGetDocumentsResponse readTime. */ + public readTime?: (google.protobuf.ITimestamp|null); + + /** BatchGetDocumentsResponse result. */ + public result?: ("found"|"missing"); + + /** + * Creates a BatchGetDocumentsResponse message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns BatchGetDocumentsResponse + */ + public static fromObject(object: { [k: string]: any }): google.firestore.v1.BatchGetDocumentsResponse; + + /** + * Creates a plain object from a BatchGetDocumentsResponse message. Also converts values to other types if specified. + * @param message BatchGetDocumentsResponse + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.firestore.v1.BatchGetDocumentsResponse, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this BatchGetDocumentsResponse to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for BatchGetDocumentsResponse + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a BeginTransactionRequest. */ + interface IBeginTransactionRequest { + + /** BeginTransactionRequest database */ + database?: (string|null); + + /** BeginTransactionRequest options */ + options?: (google.firestore.v1.ITransactionOptions|null); + } + + /** Represents a BeginTransactionRequest. */ + class BeginTransactionRequest implements IBeginTransactionRequest { + + /** + * Constructs a new BeginTransactionRequest. + * @param [properties] Properties to set + */ + constructor(properties?: google.firestore.v1.IBeginTransactionRequest); + + /** BeginTransactionRequest database. */ + public database: string; + + /** BeginTransactionRequest options. */ + public options?: (google.firestore.v1.ITransactionOptions|null); + + /** + * Creates a BeginTransactionRequest message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns BeginTransactionRequest + */ + public static fromObject(object: { [k: string]: any }): google.firestore.v1.BeginTransactionRequest; + + /** + * Creates a plain object from a BeginTransactionRequest message. Also converts values to other types if specified. + * @param message BeginTransactionRequest + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.firestore.v1.BeginTransactionRequest, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this BeginTransactionRequest to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for BeginTransactionRequest + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a BeginTransactionResponse. */ + interface IBeginTransactionResponse { + + /** BeginTransactionResponse transaction */ + transaction?: (Uint8Array|null); + } + + /** Represents a BeginTransactionResponse. */ + class BeginTransactionResponse implements IBeginTransactionResponse { + + /** + * Constructs a new BeginTransactionResponse. + * @param [properties] Properties to set + */ + constructor(properties?: google.firestore.v1.IBeginTransactionResponse); + + /** BeginTransactionResponse transaction. */ + public transaction: Uint8Array; + + /** + * Creates a BeginTransactionResponse message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns BeginTransactionResponse + */ + public static fromObject(object: { [k: string]: any }): google.firestore.v1.BeginTransactionResponse; + + /** + * Creates a plain object from a BeginTransactionResponse message. Also converts values to other types if specified. + * @param message BeginTransactionResponse + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.firestore.v1.BeginTransactionResponse, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this BeginTransactionResponse to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for BeginTransactionResponse + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a CommitRequest. */ + interface ICommitRequest { + + /** CommitRequest database */ + database?: (string|null); + + /** CommitRequest writes */ + writes?: (google.firestore.v1.IWrite[]|null); + + /** CommitRequest transaction */ + transaction?: (Uint8Array|null); + } + + /** Represents a CommitRequest. */ + class CommitRequest implements ICommitRequest { + + /** + * Constructs a new CommitRequest. + * @param [properties] Properties to set + */ + constructor(properties?: google.firestore.v1.ICommitRequest); + + /** CommitRequest database. */ + public database: string; + + /** CommitRequest writes. */ + public writes: google.firestore.v1.IWrite[]; + + /** CommitRequest transaction. */ + public transaction: Uint8Array; + + /** + * Creates a CommitRequest message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns CommitRequest + */ + public static fromObject(object: { [k: string]: any }): google.firestore.v1.CommitRequest; + + /** + * Creates a plain object from a CommitRequest message. Also converts values to other types if specified. + * @param message CommitRequest + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.firestore.v1.CommitRequest, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this CommitRequest to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for CommitRequest + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a CommitResponse. */ + interface ICommitResponse { + + /** CommitResponse writeResults */ + writeResults?: (google.firestore.v1.IWriteResult[]|null); + + /** CommitResponse commitTime */ + commitTime?: (google.protobuf.ITimestamp|null); + } + + /** Represents a CommitResponse. */ + class CommitResponse implements ICommitResponse { + + /** + * Constructs a new CommitResponse. + * @param [properties] Properties to set + */ + constructor(properties?: google.firestore.v1.ICommitResponse); + + /** CommitResponse writeResults. */ + public writeResults: google.firestore.v1.IWriteResult[]; + + /** CommitResponse commitTime. */ + public commitTime?: (google.protobuf.ITimestamp|null); + + /** + * Creates a CommitResponse message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns CommitResponse + */ + public static fromObject(object: { [k: string]: any }): google.firestore.v1.CommitResponse; + + /** + * Creates a plain object from a CommitResponse message. Also converts values to other types if specified. + * @param message CommitResponse + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.firestore.v1.CommitResponse, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this CommitResponse to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for CommitResponse + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a RollbackRequest. */ + interface IRollbackRequest { + + /** RollbackRequest database */ + database?: (string|null); + + /** RollbackRequest transaction */ + transaction?: (Uint8Array|null); + } + + /** Represents a RollbackRequest. */ + class RollbackRequest implements IRollbackRequest { + + /** + * Constructs a new RollbackRequest. + * @param [properties] Properties to set + */ + constructor(properties?: google.firestore.v1.IRollbackRequest); + + /** RollbackRequest database. */ + public database: string; + + /** RollbackRequest transaction. */ + public transaction: Uint8Array; + + /** + * Creates a RollbackRequest message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns RollbackRequest + */ + public static fromObject(object: { [k: string]: any }): google.firestore.v1.RollbackRequest; + + /** + * Creates a plain object from a RollbackRequest message. Also converts values to other types if specified. + * @param message RollbackRequest + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.firestore.v1.RollbackRequest, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this RollbackRequest to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for RollbackRequest + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a RunQueryRequest. */ + interface IRunQueryRequest { + + /** RunQueryRequest parent */ + parent?: (string|null); + + /** RunQueryRequest structuredQuery */ + structuredQuery?: (google.firestore.v1.IStructuredQuery|null); + + /** RunQueryRequest transaction */ + transaction?: (Uint8Array|null); + + /** RunQueryRequest newTransaction */ + newTransaction?: (google.firestore.v1.ITransactionOptions|null); + + /** RunQueryRequest readTime */ + readTime?: (google.protobuf.ITimestamp|null); + + /** RunQueryRequest explainOptions */ + explainOptions?: (google.firestore.v1.IExplainOptions|null); + } + + /** Represents a RunQueryRequest. */ + class RunQueryRequest implements IRunQueryRequest { + + /** + * Constructs a new RunQueryRequest. + * @param [properties] Properties to set + */ + constructor(properties?: google.firestore.v1.IRunQueryRequest); + + /** RunQueryRequest parent. */ + public parent: string; + + /** RunQueryRequest structuredQuery. */ + public structuredQuery?: (google.firestore.v1.IStructuredQuery|null); + + /** RunQueryRequest transaction. */ + public transaction?: (Uint8Array|null); + + /** RunQueryRequest newTransaction. */ + public newTransaction?: (google.firestore.v1.ITransactionOptions|null); + + /** RunQueryRequest readTime. */ + public readTime?: (google.protobuf.ITimestamp|null); + + /** RunQueryRequest explainOptions. */ + public explainOptions?: (google.firestore.v1.IExplainOptions|null); + + /** RunQueryRequest queryType. */ + public queryType?: "structuredQuery"; + + /** RunQueryRequest consistencySelector. */ + public consistencySelector?: ("transaction"|"newTransaction"|"readTime"); + + /** + * Creates a RunQueryRequest message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns RunQueryRequest + */ + public static fromObject(object: { [k: string]: any }): google.firestore.v1.RunQueryRequest; + + /** + * Creates a plain object from a RunQueryRequest message. Also converts values to other types if specified. + * @param message RunQueryRequest + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.firestore.v1.RunQueryRequest, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this RunQueryRequest to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for RunQueryRequest + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a RunQueryResponse. */ + interface IRunQueryResponse { + + /** RunQueryResponse transaction */ + transaction?: (Uint8Array|null); + + /** RunQueryResponse document */ + document?: (google.firestore.v1.IDocument|null); + + /** RunQueryResponse readTime */ + readTime?: (google.protobuf.ITimestamp|null); + + /** RunQueryResponse skippedResults */ + skippedResults?: (number|null); + + /** RunQueryResponse done */ + done?: (boolean|null); + + /** RunQueryResponse explainMetrics */ + explainMetrics?: (google.firestore.v1.IExplainMetrics|null); + } + + /** Represents a RunQueryResponse. */ + class RunQueryResponse implements IRunQueryResponse { + + /** + * Constructs a new RunQueryResponse. + * @param [properties] Properties to set + */ + constructor(properties?: google.firestore.v1.IRunQueryResponse); + + /** RunQueryResponse transaction. */ + public transaction: Uint8Array; + + /** RunQueryResponse document. */ + public document?: (google.firestore.v1.IDocument|null); + + /** RunQueryResponse readTime. */ + public readTime?: (google.protobuf.ITimestamp|null); + + /** RunQueryResponse skippedResults. */ + public skippedResults: number; + + /** RunQueryResponse done. */ + public done?: (boolean|null); + + /** RunQueryResponse explainMetrics. */ + public explainMetrics?: (google.firestore.v1.IExplainMetrics|null); + + /** RunQueryResponse continuationSelector. */ + public continuationSelector?: "done"; + + /** + * Creates a RunQueryResponse message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns RunQueryResponse + */ + public static fromObject(object: { [k: string]: any }): google.firestore.v1.RunQueryResponse; + + /** + * Creates a plain object from a RunQueryResponse message. Also converts values to other types if specified. + * @param message RunQueryResponse + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.firestore.v1.RunQueryResponse, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this RunQueryResponse to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for RunQueryResponse + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a RunAggregationQueryRequest. */ + interface IRunAggregationQueryRequest { + + /** RunAggregationQueryRequest parent */ + parent?: (string|null); + + /** RunAggregationQueryRequest structuredAggregationQuery */ + structuredAggregationQuery?: (google.firestore.v1.IStructuredAggregationQuery|null); + + /** RunAggregationQueryRequest transaction */ + transaction?: (Uint8Array|null); + + /** RunAggregationQueryRequest newTransaction */ + newTransaction?: (google.firestore.v1.ITransactionOptions|null); + + /** RunAggregationQueryRequest readTime */ + readTime?: (google.protobuf.ITimestamp|null); + + /** RunAggregationQueryRequest explainOptions */ + explainOptions?: (google.firestore.v1.IExplainOptions|null); + } + + /** Represents a RunAggregationQueryRequest. */ + class RunAggregationQueryRequest implements IRunAggregationQueryRequest { + + /** + * Constructs a new RunAggregationQueryRequest. + * @param [properties] Properties to set + */ + constructor(properties?: google.firestore.v1.IRunAggregationQueryRequest); + + /** RunAggregationQueryRequest parent. */ + public parent: string; + + /** RunAggregationQueryRequest structuredAggregationQuery. */ + public structuredAggregationQuery?: (google.firestore.v1.IStructuredAggregationQuery|null); + + /** RunAggregationQueryRequest transaction. */ + public transaction?: (Uint8Array|null); + + /** RunAggregationQueryRequest newTransaction. */ + public newTransaction?: (google.firestore.v1.ITransactionOptions|null); + + /** RunAggregationQueryRequest readTime. */ + public readTime?: (google.protobuf.ITimestamp|null); + + /** RunAggregationQueryRequest explainOptions. */ + public explainOptions?: (google.firestore.v1.IExplainOptions|null); + + /** RunAggregationQueryRequest queryType. */ + public queryType?: "structuredAggregationQuery"; + + /** RunAggregationQueryRequest consistencySelector. */ + public consistencySelector?: ("transaction"|"newTransaction"|"readTime"); + + /** + * Creates a RunAggregationQueryRequest message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns RunAggregationQueryRequest + */ + public static fromObject(object: { [k: string]: any }): google.firestore.v1.RunAggregationQueryRequest; + + /** + * Creates a plain object from a RunAggregationQueryRequest message. Also converts values to other types if specified. + * @param message RunAggregationQueryRequest + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.firestore.v1.RunAggregationQueryRequest, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this RunAggregationQueryRequest to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for RunAggregationQueryRequest + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a RunAggregationQueryResponse. */ + interface IRunAggregationQueryResponse { + + /** RunAggregationQueryResponse result */ + result?: (google.firestore.v1.IAggregationResult|null); + + /** RunAggregationQueryResponse transaction */ + transaction?: (Uint8Array|null); + + /** RunAggregationQueryResponse readTime */ + readTime?: (google.protobuf.ITimestamp|null); + + /** RunAggregationQueryResponse explainMetrics */ + explainMetrics?: (google.firestore.v1.IExplainMetrics|null); + } + + /** Represents a RunAggregationQueryResponse. */ + class RunAggregationQueryResponse implements IRunAggregationQueryResponse { + + /** + * Constructs a new RunAggregationQueryResponse. + * @param [properties] Properties to set + */ + constructor(properties?: google.firestore.v1.IRunAggregationQueryResponse); + + /** RunAggregationQueryResponse result. */ + public result?: (google.firestore.v1.IAggregationResult|null); + + /** RunAggregationQueryResponse transaction. */ + public transaction: Uint8Array; + + /** RunAggregationQueryResponse readTime. */ + public readTime?: (google.protobuf.ITimestamp|null); + + /** RunAggregationQueryResponse explainMetrics. */ + public explainMetrics?: (google.firestore.v1.IExplainMetrics|null); + + /** + * Creates a RunAggregationQueryResponse message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns RunAggregationQueryResponse + */ + public static fromObject(object: { [k: string]: any }): google.firestore.v1.RunAggregationQueryResponse; + + /** + * Creates a plain object from a RunAggregationQueryResponse message. Also converts values to other types if specified. + * @param message RunAggregationQueryResponse + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.firestore.v1.RunAggregationQueryResponse, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this RunAggregationQueryResponse to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for RunAggregationQueryResponse + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a PartitionQueryRequest. */ + interface IPartitionQueryRequest { + + /** PartitionQueryRequest parent */ + parent?: (string|null); + + /** PartitionQueryRequest structuredQuery */ + structuredQuery?: (google.firestore.v1.IStructuredQuery|null); + + /** PartitionQueryRequest partitionCount */ + partitionCount?: (number|string|null); + + /** PartitionQueryRequest pageToken */ + pageToken?: (string|null); + + /** PartitionQueryRequest pageSize */ + pageSize?: (number|null); + + /** PartitionQueryRequest readTime */ + readTime?: (google.protobuf.ITimestamp|null); + } + + /** Represents a PartitionQueryRequest. */ + class PartitionQueryRequest implements IPartitionQueryRequest { + + /** + * Constructs a new PartitionQueryRequest. + * @param [properties] Properties to set + */ + constructor(properties?: google.firestore.v1.IPartitionQueryRequest); + + /** PartitionQueryRequest parent. */ + public parent: string; + + /** PartitionQueryRequest structuredQuery. */ + public structuredQuery?: (google.firestore.v1.IStructuredQuery|null); + + /** PartitionQueryRequest partitionCount. */ + public partitionCount: (number|string); + + /** PartitionQueryRequest pageToken. */ + public pageToken: string; + + /** PartitionQueryRequest pageSize. */ + public pageSize: number; + + /** PartitionQueryRequest readTime. */ + public readTime?: (google.protobuf.ITimestamp|null); + + /** PartitionQueryRequest queryType. */ + public queryType?: "structuredQuery"; + + /** PartitionQueryRequest consistencySelector. */ + public consistencySelector?: "readTime"; + + /** + * Creates a PartitionQueryRequest message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns PartitionQueryRequest + */ + public static fromObject(object: { [k: string]: any }): google.firestore.v1.PartitionQueryRequest; + + /** + * Creates a plain object from a PartitionQueryRequest message. Also converts values to other types if specified. + * @param message PartitionQueryRequest + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.firestore.v1.PartitionQueryRequest, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this PartitionQueryRequest to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for PartitionQueryRequest + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a PartitionQueryResponse. */ + interface IPartitionQueryResponse { + + /** PartitionQueryResponse partitions */ + partitions?: (google.firestore.v1.ICursor[]|null); + + /** PartitionQueryResponse nextPageToken */ + nextPageToken?: (string|null); + } + + /** Represents a PartitionQueryResponse. */ + class PartitionQueryResponse implements IPartitionQueryResponse { + + /** + * Constructs a new PartitionQueryResponse. + * @param [properties] Properties to set + */ + constructor(properties?: google.firestore.v1.IPartitionQueryResponse); + + /** PartitionQueryResponse partitions. */ + public partitions: google.firestore.v1.ICursor[]; + + /** PartitionQueryResponse nextPageToken. */ + public nextPageToken: string; + + /** + * Creates a PartitionQueryResponse message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns PartitionQueryResponse + */ + public static fromObject(object: { [k: string]: any }): google.firestore.v1.PartitionQueryResponse; + + /** + * Creates a plain object from a PartitionQueryResponse message. Also converts values to other types if specified. + * @param message PartitionQueryResponse + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.firestore.v1.PartitionQueryResponse, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this PartitionQueryResponse to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for PartitionQueryResponse + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a WriteRequest. */ + interface IWriteRequest { + + /** WriteRequest database */ + database?: (string|null); + + /** WriteRequest streamId */ + streamId?: (string|null); + + /** WriteRequest writes */ + writes?: (google.firestore.v1.IWrite[]|null); + + /** WriteRequest streamToken */ + streamToken?: (Uint8Array|null); + + /** WriteRequest labels */ + labels?: ({ [k: string]: string }|null); + } + + /** Represents a WriteRequest. */ + class WriteRequest implements IWriteRequest { + + /** + * Constructs a new WriteRequest. + * @param [properties] Properties to set + */ + constructor(properties?: google.firestore.v1.IWriteRequest); + + /** WriteRequest database. */ + public database: string; + + /** WriteRequest streamId. */ + public streamId: string; + + /** WriteRequest writes. */ + public writes: google.firestore.v1.IWrite[]; + + /** WriteRequest streamToken. */ + public streamToken: Uint8Array; + + /** WriteRequest labels. */ + public labels: { [k: string]: string }; + + /** + * Creates a WriteRequest message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns WriteRequest + */ + public static fromObject(object: { [k: string]: any }): google.firestore.v1.WriteRequest; + + /** + * Creates a plain object from a WriteRequest message. Also converts values to other types if specified. + * @param message WriteRequest + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.firestore.v1.WriteRequest, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this WriteRequest to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for WriteRequest + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a WriteResponse. */ + interface IWriteResponse { + + /** WriteResponse streamId */ + streamId?: (string|null); + + /** WriteResponse streamToken */ + streamToken?: (Uint8Array|null); + + /** WriteResponse writeResults */ + writeResults?: (google.firestore.v1.IWriteResult[]|null); + + /** WriteResponse commitTime */ + commitTime?: (google.protobuf.ITimestamp|null); + } + + /** Represents a WriteResponse. */ + class WriteResponse implements IWriteResponse { + + /** + * Constructs a new WriteResponse. + * @param [properties] Properties to set + */ + constructor(properties?: google.firestore.v1.IWriteResponse); + + /** WriteResponse streamId. */ + public streamId: string; + + /** WriteResponse streamToken. */ + public streamToken: Uint8Array; + + /** WriteResponse writeResults. */ + public writeResults: google.firestore.v1.IWriteResult[]; + + /** WriteResponse commitTime. */ + public commitTime?: (google.protobuf.ITimestamp|null); + + /** + * Creates a WriteResponse message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns WriteResponse + */ + public static fromObject(object: { [k: string]: any }): google.firestore.v1.WriteResponse; + + /** + * Creates a plain object from a WriteResponse message. Also converts values to other types if specified. + * @param message WriteResponse + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.firestore.v1.WriteResponse, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this WriteResponse to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for WriteResponse + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a ListenRequest. */ + interface IListenRequest { + + /** ListenRequest database */ + database?: (string|null); + + /** ListenRequest addTarget */ + addTarget?: (google.firestore.v1.ITarget|null); + + /** ListenRequest removeTarget */ + removeTarget?: (number|null); + + /** ListenRequest labels */ + labels?: ({ [k: string]: string }|null); + } + + /** Represents a ListenRequest. */ + class ListenRequest implements IListenRequest { + + /** + * Constructs a new ListenRequest. + * @param [properties] Properties to set + */ + constructor(properties?: google.firestore.v1.IListenRequest); + + /** ListenRequest database. */ + public database: string; + + /** ListenRequest addTarget. */ + public addTarget?: (google.firestore.v1.ITarget|null); + + /** ListenRequest removeTarget. */ + public removeTarget?: (number|null); + + /** ListenRequest labels. */ + public labels: { [k: string]: string }; + + /** ListenRequest targetChange. */ + public targetChange?: ("addTarget"|"removeTarget"); + + /** + * Creates a ListenRequest message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns ListenRequest + */ + public static fromObject(object: { [k: string]: any }): google.firestore.v1.ListenRequest; + + /** + * Creates a plain object from a ListenRequest message. Also converts values to other types if specified. + * @param message ListenRequest + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.firestore.v1.ListenRequest, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this ListenRequest to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for ListenRequest + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a ListenResponse. */ + interface IListenResponse { + + /** ListenResponse targetChange */ + targetChange?: (google.firestore.v1.ITargetChange|null); + + /** ListenResponse documentChange */ + documentChange?: (google.firestore.v1.IDocumentChange|null); + + /** ListenResponse documentDelete */ + documentDelete?: (google.firestore.v1.IDocumentDelete|null); + + /** ListenResponse documentRemove */ + documentRemove?: (google.firestore.v1.IDocumentRemove|null); + + /** ListenResponse filter */ + filter?: (google.firestore.v1.IExistenceFilter|null); + } + + /** Represents a ListenResponse. */ + class ListenResponse implements IListenResponse { + + /** + * Constructs a new ListenResponse. + * @param [properties] Properties to set + */ + constructor(properties?: google.firestore.v1.IListenResponse); + + /** ListenResponse targetChange. */ + public targetChange?: (google.firestore.v1.ITargetChange|null); + + /** ListenResponse documentChange. */ + public documentChange?: (google.firestore.v1.IDocumentChange|null); + + /** ListenResponse documentDelete. */ + public documentDelete?: (google.firestore.v1.IDocumentDelete|null); + + /** ListenResponse documentRemove. */ + public documentRemove?: (google.firestore.v1.IDocumentRemove|null); + + /** ListenResponse filter. */ + public filter?: (google.firestore.v1.IExistenceFilter|null); + + /** ListenResponse responseType. */ + public responseType?: ("targetChange"|"documentChange"|"documentDelete"|"documentRemove"|"filter"); + + /** + * Creates a ListenResponse message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns ListenResponse + */ + public static fromObject(object: { [k: string]: any }): google.firestore.v1.ListenResponse; + + /** + * Creates a plain object from a ListenResponse message. Also converts values to other types if specified. + * @param message ListenResponse + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.firestore.v1.ListenResponse, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this ListenResponse to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for ListenResponse + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a Target. */ + interface ITarget { + + /** Target query */ + query?: (google.firestore.v1.Target.IQueryTarget|null); + + /** Target documents */ + documents?: (google.firestore.v1.Target.IDocumentsTarget|null); + + /** Target resumeToken */ + resumeToken?: (Uint8Array|null); + + /** Target readTime */ + readTime?: (google.protobuf.ITimestamp|null); + + /** Target targetId */ + targetId?: (number|null); + + /** Target once */ + once?: (boolean|null); + + /** Target expectedCount */ + expectedCount?: (google.protobuf.IInt32Value|null); + } + + /** Represents a Target. */ + class Target implements ITarget { + + /** + * Constructs a new Target. + * @param [properties] Properties to set + */ + constructor(properties?: google.firestore.v1.ITarget); + + /** Target query. */ + public query?: (google.firestore.v1.Target.IQueryTarget|null); + + /** Target documents. */ + public documents?: (google.firestore.v1.Target.IDocumentsTarget|null); + + /** Target resumeToken. */ + public resumeToken?: (Uint8Array|null); + + /** Target readTime. */ + public readTime?: (google.protobuf.ITimestamp|null); + + /** Target targetId. */ + public targetId: number; + + /** Target once. */ + public once: boolean; + + /** Target expectedCount. */ + public expectedCount?: (google.protobuf.IInt32Value|null); + + /** Target targetType. */ + public targetType?: ("query"|"documents"); + + /** Target resumeType. */ + public resumeType?: ("resumeToken"|"readTime"); + + /** + * Creates a Target message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns Target + */ + public static fromObject(object: { [k: string]: any }): google.firestore.v1.Target; + + /** + * Creates a plain object from a Target message. Also converts values to other types if specified. + * @param message Target + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.firestore.v1.Target, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this Target to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for Target + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + namespace Target { + + /** Properties of a DocumentsTarget. */ + interface IDocumentsTarget { + + /** DocumentsTarget documents */ + documents?: (string[]|null); + } + + /** Represents a DocumentsTarget. */ + class DocumentsTarget implements IDocumentsTarget { + + /** + * Constructs a new DocumentsTarget. + * @param [properties] Properties to set + */ + constructor(properties?: google.firestore.v1.Target.IDocumentsTarget); + + /** DocumentsTarget documents. */ + public documents: string[]; + + /** + * Creates a DocumentsTarget message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns DocumentsTarget + */ + public static fromObject(object: { [k: string]: any }): google.firestore.v1.Target.DocumentsTarget; + + /** + * Creates a plain object from a DocumentsTarget message. Also converts values to other types if specified. + * @param message DocumentsTarget + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.firestore.v1.Target.DocumentsTarget, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this DocumentsTarget to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for DocumentsTarget + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a QueryTarget. */ + interface IQueryTarget { + + /** QueryTarget parent */ + parent?: (string|null); + + /** QueryTarget structuredQuery */ + structuredQuery?: (google.firestore.v1.IStructuredQuery|null); + } + + /** Represents a QueryTarget. */ + class QueryTarget implements IQueryTarget { + + /** + * Constructs a new QueryTarget. + * @param [properties] Properties to set + */ + constructor(properties?: google.firestore.v1.Target.IQueryTarget); + + /** QueryTarget parent. */ + public parent: string; + + /** QueryTarget structuredQuery. */ + public structuredQuery?: (google.firestore.v1.IStructuredQuery|null); + + /** QueryTarget queryType. */ + public queryType?: "structuredQuery"; + + /** + * Creates a QueryTarget message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns QueryTarget + */ + public static fromObject(object: { [k: string]: any }): google.firestore.v1.Target.QueryTarget; + + /** + * Creates a plain object from a QueryTarget message. Also converts values to other types if specified. + * @param message QueryTarget + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.firestore.v1.Target.QueryTarget, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this QueryTarget to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for QueryTarget + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + } + + /** Properties of a TargetChange. */ + interface ITargetChange { + + /** TargetChange targetChangeType */ + targetChangeType?: (google.firestore.v1.TargetChange.TargetChangeType|null); + + /** TargetChange targetIds */ + targetIds?: (number[]|null); + + /** TargetChange cause */ + cause?: (google.rpc.IStatus|null); + + /** TargetChange resumeToken */ + resumeToken?: (Uint8Array|null); - /** Represents an EnumDescriptorProto. */ - class EnumDescriptorProto implements IEnumDescriptorProto { + /** TargetChange readTime */ + readTime?: (google.protobuf.ITimestamp|null); + } - /** - * Constructs a new EnumDescriptorProto. - * @param [properties] Properties to set - */ - constructor(properties?: google.protobuf.IEnumDescriptorProto); + /** Represents a TargetChange. */ + class TargetChange implements ITargetChange { + + /** + * Constructs a new TargetChange. + * @param [properties] Properties to set + */ + constructor(properties?: google.firestore.v1.ITargetChange); + + /** TargetChange targetChangeType. */ + public targetChangeType: google.firestore.v1.TargetChange.TargetChangeType; + + /** TargetChange targetIds. */ + public targetIds: number[]; + + /** TargetChange cause. */ + public cause?: (google.rpc.IStatus|null); + + /** TargetChange resumeToken. */ + public resumeToken: Uint8Array; + + /** TargetChange readTime. */ + public readTime?: (google.protobuf.ITimestamp|null); + + /** + * Creates a TargetChange message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns TargetChange + */ + public static fromObject(object: { [k: string]: any }): google.firestore.v1.TargetChange; + + /** + * Creates a plain object from a TargetChange message. Also converts values to other types if specified. + * @param message TargetChange + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.firestore.v1.TargetChange, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this TargetChange to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for TargetChange + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + namespace TargetChange { + + /** TargetChangeType enum. */ + type TargetChangeType = + "NO_CHANGE"| "ADD"| "REMOVE"| "CURRENT"| "RESET"; + } + + /** Properties of a ListCollectionIdsRequest. */ + interface IListCollectionIdsRequest { + + /** ListCollectionIdsRequest parent */ + parent?: (string|null); + + /** ListCollectionIdsRequest pageSize */ + pageSize?: (number|null); + + /** ListCollectionIdsRequest pageToken */ + pageToken?: (string|null); + + /** ListCollectionIdsRequest readTime */ + readTime?: (google.protobuf.ITimestamp|null); + } + + /** Represents a ListCollectionIdsRequest. */ + class ListCollectionIdsRequest implements IListCollectionIdsRequest { + + /** + * Constructs a new ListCollectionIdsRequest. + * @param [properties] Properties to set + */ + constructor(properties?: google.firestore.v1.IListCollectionIdsRequest); + + /** ListCollectionIdsRequest parent. */ + public parent: string; + + /** ListCollectionIdsRequest pageSize. */ + public pageSize: number; + + /** ListCollectionIdsRequest pageToken. */ + public pageToken: string; + + /** ListCollectionIdsRequest readTime. */ + public readTime?: (google.protobuf.ITimestamp|null); + + /** ListCollectionIdsRequest consistencySelector. */ + public consistencySelector?: "readTime"; + + /** + * Creates a ListCollectionIdsRequest message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns ListCollectionIdsRequest + */ + public static fromObject(object: { [k: string]: any }): google.firestore.v1.ListCollectionIdsRequest; + + /** + * Creates a plain object from a ListCollectionIdsRequest message. Also converts values to other types if specified. + * @param message ListCollectionIdsRequest + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.firestore.v1.ListCollectionIdsRequest, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this ListCollectionIdsRequest to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for ListCollectionIdsRequest + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a ListCollectionIdsResponse. */ + interface IListCollectionIdsResponse { + + /** ListCollectionIdsResponse collectionIds */ + collectionIds?: (string[]|null); + + /** ListCollectionIdsResponse nextPageToken */ + nextPageToken?: (string|null); + } + + /** Represents a ListCollectionIdsResponse. */ + class ListCollectionIdsResponse implements IListCollectionIdsResponse { + + /** + * Constructs a new ListCollectionIdsResponse. + * @param [properties] Properties to set + */ + constructor(properties?: google.firestore.v1.IListCollectionIdsResponse); + + /** ListCollectionIdsResponse collectionIds. */ + public collectionIds: string[]; + + /** ListCollectionIdsResponse nextPageToken. */ + public nextPageToken: string; + + /** + * Creates a ListCollectionIdsResponse message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns ListCollectionIdsResponse + */ + public static fromObject(object: { [k: string]: any }): google.firestore.v1.ListCollectionIdsResponse; + + /** + * Creates a plain object from a ListCollectionIdsResponse message. Also converts values to other types if specified. + * @param message ListCollectionIdsResponse + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.firestore.v1.ListCollectionIdsResponse, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this ListCollectionIdsResponse to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for ListCollectionIdsResponse + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a BatchWriteRequest. */ + interface IBatchWriteRequest { + + /** BatchWriteRequest database */ + database?: (string|null); + + /** BatchWriteRequest writes */ + writes?: (google.firestore.v1.IWrite[]|null); + + /** BatchWriteRequest labels */ + labels?: ({ [k: string]: string }|null); + } + + /** Represents a BatchWriteRequest. */ + class BatchWriteRequest implements IBatchWriteRequest { + + /** + * Constructs a new BatchWriteRequest. + * @param [properties] Properties to set + */ + constructor(properties?: google.firestore.v1.IBatchWriteRequest); + + /** BatchWriteRequest database. */ + public database: string; + + /** BatchWriteRequest writes. */ + public writes: google.firestore.v1.IWrite[]; + + /** BatchWriteRequest labels. */ + public labels: { [k: string]: string }; + + /** + * Creates a BatchWriteRequest message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns BatchWriteRequest + */ + public static fromObject(object: { [k: string]: any }): google.firestore.v1.BatchWriteRequest; + + /** + * Creates a plain object from a BatchWriteRequest message. Also converts values to other types if specified. + * @param message BatchWriteRequest + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.firestore.v1.BatchWriteRequest, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this BatchWriteRequest to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for BatchWriteRequest + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a BatchWriteResponse. */ + interface IBatchWriteResponse { + + /** BatchWriteResponse writeResults */ + writeResults?: (google.firestore.v1.IWriteResult[]|null); + + /** BatchWriteResponse status */ + status?: (google.rpc.IStatus[]|null); + } + + /** Represents a BatchWriteResponse. */ + class BatchWriteResponse implements IBatchWriteResponse { + + /** + * Constructs a new BatchWriteResponse. + * @param [properties] Properties to set + */ + constructor(properties?: google.firestore.v1.IBatchWriteResponse); + + /** BatchWriteResponse writeResults. */ + public writeResults: google.firestore.v1.IWriteResult[]; + + /** BatchWriteResponse status. */ + public status: google.rpc.IStatus[]; - /** EnumDescriptorProto name. */ - public name: string; + /** + * Creates a BatchWriteResponse message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns BatchWriteResponse + */ + public static fromObject(object: { [k: string]: any }): google.firestore.v1.BatchWriteResponse; - /** EnumDescriptorProto value. */ - public value: google.protobuf.IEnumValueDescriptorProto[]; + /** + * Creates a plain object from a BatchWriteResponse message. Also converts values to other types if specified. + * @param message BatchWriteResponse + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.firestore.v1.BatchWriteResponse, options?: $protobuf.IConversionOptions): { [k: string]: any }; - /** EnumDescriptorProto options. */ - public options?: (google.protobuf.IEnumOptions|null); + /** + * Converts this BatchWriteResponse to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; - /** - * Creates an EnumDescriptorProto message from a plain object. Also converts values to their respective internal types. - * @param object Plain object - * @returns EnumDescriptorProto - */ - public static fromObject(object: { [k: string]: any }): google.protobuf.EnumDescriptorProto; + /** + * Gets the default type url for BatchWriteResponse + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } - /** - * Creates a plain object from an EnumDescriptorProto message. Also converts values to other types if specified. - * @param message EnumDescriptorProto - * @param [options] Conversion options - * @returns Plain object - */ - public static toObject(message: google.protobuf.EnumDescriptorProto, options?: $protobuf.IConversionOptions): { [k: string]: any }; + /** Properties of a StructuredQuery. */ + interface IStructuredQuery { - /** - * Converts this EnumDescriptorProto to JSON. - * @returns JSON object - */ - public toJSON(): { [k: string]: any }; - } + /** StructuredQuery select */ + select?: (google.firestore.v1.StructuredQuery.IProjection|null); - /** Properties of an EnumValueDescriptorProto. */ - interface IEnumValueDescriptorProto { + /** StructuredQuery from */ + from?: (google.firestore.v1.StructuredQuery.ICollectionSelector[]|null); - /** EnumValueDescriptorProto name */ - name?: (string|null); + /** StructuredQuery where */ + where?: (google.firestore.v1.StructuredQuery.IFilter|null); - /** EnumValueDescriptorProto number */ - number?: (number|null); + /** StructuredQuery orderBy */ + orderBy?: (google.firestore.v1.StructuredQuery.IOrder[]|null); - /** EnumValueDescriptorProto options */ - options?: (google.protobuf.IEnumValueOptions|null); - } + /** StructuredQuery startAt */ + startAt?: (google.firestore.v1.ICursor|null); - /** Represents an EnumValueDescriptorProto. */ - class EnumValueDescriptorProto implements IEnumValueDescriptorProto { + /** StructuredQuery endAt */ + endAt?: (google.firestore.v1.ICursor|null); - /** - * Constructs a new EnumValueDescriptorProto. - * @param [properties] Properties to set - */ - constructor(properties?: google.protobuf.IEnumValueDescriptorProto); + /** StructuredQuery offset */ + offset?: (number|null); - /** EnumValueDescriptorProto name. */ - public name: string; + /** StructuredQuery limit */ + limit?: (google.protobuf.IInt32Value|null); - /** EnumValueDescriptorProto number. */ - public number: number; + /** StructuredQuery findNearest */ + findNearest?: (google.firestore.v1.StructuredQuery.IFindNearest|null); + } - /** EnumValueDescriptorProto options. */ - public options?: (google.protobuf.IEnumValueOptions|null); + /** Represents a StructuredQuery. */ + class StructuredQuery implements IStructuredQuery { - /** - * Creates an EnumValueDescriptorProto message from a plain object. Also converts values to their respective internal types. - * @param object Plain object - * @returns EnumValueDescriptorProto - */ - public static fromObject(object: { [k: string]: any }): google.protobuf.EnumValueDescriptorProto; + /** + * Constructs a new StructuredQuery. + * @param [properties] Properties to set + */ + constructor(properties?: google.firestore.v1.IStructuredQuery); - /** - * Creates a plain object from an EnumValueDescriptorProto message. Also converts values to other types if specified. - * @param message EnumValueDescriptorProto - * @param [options] Conversion options - * @returns Plain object - */ - public static toObject(message: google.protobuf.EnumValueDescriptorProto, options?: $protobuf.IConversionOptions): { [k: string]: any }; + /** StructuredQuery select. */ + public select?: (google.firestore.v1.StructuredQuery.IProjection|null); - /** - * Converts this EnumValueDescriptorProto to JSON. - * @returns JSON object - */ - public toJSON(): { [k: string]: any }; - } + /** StructuredQuery from. */ + public from: google.firestore.v1.StructuredQuery.ICollectionSelector[]; - /** Properties of a ServiceDescriptorProto. */ - interface IServiceDescriptorProto { + /** StructuredQuery where. */ + public where?: (google.firestore.v1.StructuredQuery.IFilter|null); - /** ServiceDescriptorProto name */ - name?: (string|null); + /** StructuredQuery orderBy. */ + public orderBy: google.firestore.v1.StructuredQuery.IOrder[]; - /** ServiceDescriptorProto method */ - method?: (google.protobuf.IMethodDescriptorProto[]|null); + /** StructuredQuery startAt. */ + public startAt?: (google.firestore.v1.ICursor|null); - /** ServiceDescriptorProto options */ - options?: (google.protobuf.IServiceOptions|null); - } + /** StructuredQuery endAt. */ + public endAt?: (google.firestore.v1.ICursor|null); - /** Represents a ServiceDescriptorProto. */ - class ServiceDescriptorProto implements IServiceDescriptorProto { + /** StructuredQuery offset. */ + public offset: number; - /** - * Constructs a new ServiceDescriptorProto. - * @param [properties] Properties to set - */ - constructor(properties?: google.protobuf.IServiceDescriptorProto); + /** StructuredQuery limit. */ + public limit?: (google.protobuf.IInt32Value|null); - /** ServiceDescriptorProto name. */ - public name: string; + /** StructuredQuery findNearest. */ + public findNearest?: (google.firestore.v1.StructuredQuery.IFindNearest|null); - /** ServiceDescriptorProto method. */ - public method: google.protobuf.IMethodDescriptorProto[]; + /** + * Creates a StructuredQuery message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns StructuredQuery + */ + public static fromObject(object: { [k: string]: any }): google.firestore.v1.StructuredQuery; - /** ServiceDescriptorProto options. */ - public options?: (google.protobuf.IServiceOptions|null); + /** + * Creates a plain object from a StructuredQuery message. Also converts values to other types if specified. + * @param message StructuredQuery + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.firestore.v1.StructuredQuery, options?: $protobuf.IConversionOptions): { [k: string]: any }; - /** - * Creates a ServiceDescriptorProto message from a plain object. Also converts values to their respective internal types. - * @param object Plain object - * @returns ServiceDescriptorProto - */ - public static fromObject(object: { [k: string]: any }): google.protobuf.ServiceDescriptorProto; + /** + * Converts this StructuredQuery to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; - /** - * Creates a plain object from a ServiceDescriptorProto message. Also converts values to other types if specified. - * @param message ServiceDescriptorProto - * @param [options] Conversion options - * @returns Plain object - */ - public static toObject(message: google.protobuf.ServiceDescriptorProto, options?: $protobuf.IConversionOptions): { [k: string]: any }; + /** + * Gets the default type url for StructuredQuery + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } - /** - * Converts this ServiceDescriptorProto to JSON. - * @returns JSON object - */ - public toJSON(): { [k: string]: any }; - } + namespace StructuredQuery { - /** Properties of a MethodDescriptorProto. */ - interface IMethodDescriptorProto { + /** Properties of a CollectionSelector. */ + interface ICollectionSelector { - /** MethodDescriptorProto name */ - name?: (string|null); + /** CollectionSelector collectionId */ + collectionId?: (string|null); - /** MethodDescriptorProto inputType */ - inputType?: (string|null); + /** CollectionSelector allDescendants */ + allDescendants?: (boolean|null); + } - /** MethodDescriptorProto outputType */ - outputType?: (string|null); + /** Represents a CollectionSelector. */ + class CollectionSelector implements ICollectionSelector { - /** MethodDescriptorProto options */ - options?: (google.protobuf.IMethodOptions|null); + /** + * Constructs a new CollectionSelector. + * @param [properties] Properties to set + */ + constructor(properties?: google.firestore.v1.StructuredQuery.ICollectionSelector); - /** MethodDescriptorProto clientStreaming */ - clientStreaming?: (boolean|null); + /** CollectionSelector collectionId. */ + public collectionId: string; - /** MethodDescriptorProto serverStreaming */ - serverStreaming?: (boolean|null); - } + /** CollectionSelector allDescendants. */ + public allDescendants: boolean; - /** Represents a MethodDescriptorProto. */ - class MethodDescriptorProto implements IMethodDescriptorProto { + /** + * Creates a CollectionSelector message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns CollectionSelector + */ + public static fromObject(object: { [k: string]: any }): google.firestore.v1.StructuredQuery.CollectionSelector; - /** - * Constructs a new MethodDescriptorProto. - * @param [properties] Properties to set - */ - constructor(properties?: google.protobuf.IMethodDescriptorProto); + /** + * Creates a plain object from a CollectionSelector message. Also converts values to other types if specified. + * @param message CollectionSelector + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.firestore.v1.StructuredQuery.CollectionSelector, options?: $protobuf.IConversionOptions): { [k: string]: any }; - /** MethodDescriptorProto name. */ - public name: string; + /** + * Converts this CollectionSelector to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for CollectionSelector + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } - /** MethodDescriptorProto inputType. */ - public inputType: string; + /** Properties of a Filter. */ + interface IFilter { - /** MethodDescriptorProto outputType. */ - public outputType: string; + /** Filter compositeFilter */ + compositeFilter?: (google.firestore.v1.StructuredQuery.ICompositeFilter|null); - /** MethodDescriptorProto options. */ - public options?: (google.protobuf.IMethodOptions|null); + /** Filter fieldFilter */ + fieldFilter?: (google.firestore.v1.StructuredQuery.IFieldFilter|null); - /** MethodDescriptorProto clientStreaming. */ - public clientStreaming: boolean; + /** Filter unaryFilter */ + unaryFilter?: (google.firestore.v1.StructuredQuery.IUnaryFilter|null); + } - /** MethodDescriptorProto serverStreaming. */ - public serverStreaming: boolean; + /** Represents a Filter. */ + class Filter implements IFilter { - /** - * Creates a MethodDescriptorProto message from a plain object. Also converts values to their respective internal types. - * @param object Plain object - * @returns MethodDescriptorProto - */ - public static fromObject(object: { [k: string]: any }): google.protobuf.MethodDescriptorProto; + /** + * Constructs a new Filter. + * @param [properties] Properties to set + */ + constructor(properties?: google.firestore.v1.StructuredQuery.IFilter); - /** - * Creates a plain object from a MethodDescriptorProto message. Also converts values to other types if specified. - * @param message MethodDescriptorProto - * @param [options] Conversion options - * @returns Plain object - */ - public static toObject(message: google.protobuf.MethodDescriptorProto, options?: $protobuf.IConversionOptions): { [k: string]: any }; + /** Filter compositeFilter. */ + public compositeFilter?: (google.firestore.v1.StructuredQuery.ICompositeFilter|null); - /** - * Converts this MethodDescriptorProto to JSON. - * @returns JSON object - */ - public toJSON(): { [k: string]: any }; - } + /** Filter fieldFilter. */ + public fieldFilter?: (google.firestore.v1.StructuredQuery.IFieldFilter|null); - /** Properties of a FileOptions. */ - interface IFileOptions { + /** Filter unaryFilter. */ + public unaryFilter?: (google.firestore.v1.StructuredQuery.IUnaryFilter|null); - /** FileOptions javaPackage */ - javaPackage?: (string|null); + /** Filter filterType. */ + public filterType?: ("compositeFilter"|"fieldFilter"|"unaryFilter"); - /** FileOptions javaOuterClassname */ - javaOuterClassname?: (string|null); + /** + * Creates a Filter message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns Filter + */ + public static fromObject(object: { [k: string]: any }): google.firestore.v1.StructuredQuery.Filter; - /** FileOptions javaMultipleFiles */ - javaMultipleFiles?: (boolean|null); + /** + * Creates a plain object from a Filter message. Also converts values to other types if specified. + * @param message Filter + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.firestore.v1.StructuredQuery.Filter, options?: $protobuf.IConversionOptions): { [k: string]: any }; - /** FileOptions javaGenerateEqualsAndHash */ - javaGenerateEqualsAndHash?: (boolean|null); + /** + * Converts this Filter to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; - /** FileOptions javaStringCheckUtf8 */ - javaStringCheckUtf8?: (boolean|null); + /** + * Gets the default type url for Filter + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } - /** FileOptions optimizeFor */ - optimizeFor?: (google.protobuf.FileOptions.OptimizeMode|null); + /** Properties of a CompositeFilter. */ + interface ICompositeFilter { - /** FileOptions goPackage */ - goPackage?: (string|null); + /** CompositeFilter op */ + op?: (google.firestore.v1.StructuredQuery.CompositeFilter.Operator|null); - /** FileOptions ccGenericServices */ - ccGenericServices?: (boolean|null); + /** CompositeFilter filters */ + filters?: (google.firestore.v1.StructuredQuery.IFilter[]|null); + } - /** FileOptions javaGenericServices */ - javaGenericServices?: (boolean|null); + /** Represents a CompositeFilter. */ + class CompositeFilter implements ICompositeFilter { - /** FileOptions pyGenericServices */ - pyGenericServices?: (boolean|null); + /** + * Constructs a new CompositeFilter. + * @param [properties] Properties to set + */ + constructor(properties?: google.firestore.v1.StructuredQuery.ICompositeFilter); - /** FileOptions deprecated */ - deprecated?: (boolean|null); + /** CompositeFilter op. */ + public op: google.firestore.v1.StructuredQuery.CompositeFilter.Operator; - /** FileOptions ccEnableArenas */ - ccEnableArenas?: (boolean|null); + /** CompositeFilter filters. */ + public filters: google.firestore.v1.StructuredQuery.IFilter[]; - /** FileOptions objcClassPrefix */ - objcClassPrefix?: (string|null); + /** + * Creates a CompositeFilter message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns CompositeFilter + */ + public static fromObject(object: { [k: string]: any }): google.firestore.v1.StructuredQuery.CompositeFilter; - /** FileOptions csharpNamespace */ - csharpNamespace?: (string|null); + /** + * Creates a plain object from a CompositeFilter message. Also converts values to other types if specified. + * @param message CompositeFilter + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.firestore.v1.StructuredQuery.CompositeFilter, options?: $protobuf.IConversionOptions): { [k: string]: any }; - /** FileOptions uninterpretedOption */ - uninterpretedOption?: (google.protobuf.IUninterpretedOption[]|null); + /** + * Converts this CompositeFilter to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; - /** FileOptions .google.api.resourceDefinition */ - ".google.api.resourceDefinition"?: (google.api.IResourceDescriptor[]|null); - } + /** + * Gets the default type url for CompositeFilter + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } - /** Represents a FileOptions. */ - class FileOptions implements IFileOptions { + namespace CompositeFilter { - /** - * Constructs a new FileOptions. - * @param [properties] Properties to set - */ - constructor(properties?: google.protobuf.IFileOptions); + /** Operator enum. */ + type Operator = + "OPERATOR_UNSPECIFIED"| "AND"| "OR"; + } - /** FileOptions javaPackage. */ - public javaPackage: string; + /** Properties of a FieldFilter. */ + interface IFieldFilter { - /** FileOptions javaOuterClassname. */ - public javaOuterClassname: string; + /** FieldFilter field */ + field?: (google.firestore.v1.StructuredQuery.IFieldReference|null); - /** FileOptions javaMultipleFiles. */ - public javaMultipleFiles: boolean; + /** FieldFilter op */ + op?: (google.firestore.v1.StructuredQuery.FieldFilter.Operator|null); - /** FileOptions javaGenerateEqualsAndHash. */ - public javaGenerateEqualsAndHash: boolean; + /** FieldFilter value */ + value?: (google.firestore.v1.IValue|null); + } - /** FileOptions javaStringCheckUtf8. */ - public javaStringCheckUtf8: boolean; + /** Represents a FieldFilter. */ + class FieldFilter implements IFieldFilter { - /** FileOptions optimizeFor. */ - public optimizeFor: google.protobuf.FileOptions.OptimizeMode; + /** + * Constructs a new FieldFilter. + * @param [properties] Properties to set + */ + constructor(properties?: google.firestore.v1.StructuredQuery.IFieldFilter); - /** FileOptions goPackage. */ - public goPackage: string; + /** FieldFilter field. */ + public field?: (google.firestore.v1.StructuredQuery.IFieldReference|null); - /** FileOptions ccGenericServices. */ - public ccGenericServices: boolean; + /** FieldFilter op. */ + public op: google.firestore.v1.StructuredQuery.FieldFilter.Operator; - /** FileOptions javaGenericServices. */ - public javaGenericServices: boolean; + /** FieldFilter value. */ + public value?: (google.firestore.v1.IValue|null); - /** FileOptions pyGenericServices. */ - public pyGenericServices: boolean; + /** + * Creates a FieldFilter message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns FieldFilter + */ + public static fromObject(object: { [k: string]: any }): google.firestore.v1.StructuredQuery.FieldFilter; - /** FileOptions deprecated. */ - public deprecated: boolean; + /** + * Creates a plain object from a FieldFilter message. Also converts values to other types if specified. + * @param message FieldFilter + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.firestore.v1.StructuredQuery.FieldFilter, options?: $protobuf.IConversionOptions): { [k: string]: any }; - /** FileOptions ccEnableArenas. */ - public ccEnableArenas: boolean; + /** + * Converts this FieldFilter to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; - /** FileOptions objcClassPrefix. */ - public objcClassPrefix: string; + /** + * Gets the default type url for FieldFilter + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } - /** FileOptions csharpNamespace. */ - public csharpNamespace: string; + namespace FieldFilter { - /** FileOptions uninterpretedOption. */ - public uninterpretedOption: google.protobuf.IUninterpretedOption[]; + /** Operator enum. */ + type Operator = + "OPERATOR_UNSPECIFIED"| "LESS_THAN"| "LESS_THAN_OR_EQUAL"| "GREATER_THAN"| "GREATER_THAN_OR_EQUAL"| "EQUAL"| "NOT_EQUAL"| "ARRAY_CONTAINS"| "IN"| "ARRAY_CONTAINS_ANY"| "NOT_IN"; + } - /** - * Creates a FileOptions message from a plain object. Also converts values to their respective internal types. - * @param object Plain object - * @returns FileOptions - */ - public static fromObject(object: { [k: string]: any }): google.protobuf.FileOptions; + /** Properties of an UnaryFilter. */ + interface IUnaryFilter { - /** - * Creates a plain object from a FileOptions message. Also converts values to other types if specified. - * @param message FileOptions - * @param [options] Conversion options - * @returns Plain object - */ - public static toObject(message: google.protobuf.FileOptions, options?: $protobuf.IConversionOptions): { [k: string]: any }; + /** UnaryFilter op */ + op?: (google.firestore.v1.StructuredQuery.UnaryFilter.Operator|null); - /** - * Converts this FileOptions to JSON. - * @returns JSON object - */ - public toJSON(): { [k: string]: any }; - } + /** UnaryFilter field */ + field?: (google.firestore.v1.StructuredQuery.IFieldReference|null); + } - namespace FileOptions { + /** Represents an UnaryFilter. */ + class UnaryFilter implements IUnaryFilter { - /** OptimizeMode enum. */ - type OptimizeMode = - "SPEED"| "CODE_SIZE"| "LITE_RUNTIME"; - } + /** + * Constructs a new UnaryFilter. + * @param [properties] Properties to set + */ + constructor(properties?: google.firestore.v1.StructuredQuery.IUnaryFilter); - /** Properties of a MessageOptions. */ - interface IMessageOptions { + /** UnaryFilter op. */ + public op: google.firestore.v1.StructuredQuery.UnaryFilter.Operator; - /** MessageOptions messageSetWireFormat */ - messageSetWireFormat?: (boolean|null); + /** UnaryFilter field. */ + public field?: (google.firestore.v1.StructuredQuery.IFieldReference|null); - /** MessageOptions noStandardDescriptorAccessor */ - noStandardDescriptorAccessor?: (boolean|null); + /** UnaryFilter operandType. */ + public operandType?: "field"; - /** MessageOptions deprecated */ - deprecated?: (boolean|null); + /** + * Creates an UnaryFilter message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns UnaryFilter + */ + public static fromObject(object: { [k: string]: any }): google.firestore.v1.StructuredQuery.UnaryFilter; - /** MessageOptions mapEntry */ - mapEntry?: (boolean|null); + /** + * Creates a plain object from an UnaryFilter message. Also converts values to other types if specified. + * @param message UnaryFilter + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.firestore.v1.StructuredQuery.UnaryFilter, options?: $protobuf.IConversionOptions): { [k: string]: any }; - /** MessageOptions uninterpretedOption */ - uninterpretedOption?: (google.protobuf.IUninterpretedOption[]|null); + /** + * Converts this UnaryFilter to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; - /** MessageOptions .google.api.resource */ - ".google.api.resource"?: (google.api.IResourceDescriptor|null); - } + /** + * Gets the default type url for UnaryFilter + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } - /** Represents a MessageOptions. */ - class MessageOptions implements IMessageOptions { + namespace UnaryFilter { - /** - * Constructs a new MessageOptions. - * @param [properties] Properties to set - */ - constructor(properties?: google.protobuf.IMessageOptions); + /** Operator enum. */ + type Operator = + "OPERATOR_UNSPECIFIED"| "IS_NAN"| "IS_NULL"| "IS_NOT_NAN"| "IS_NOT_NULL"; + } - /** MessageOptions messageSetWireFormat. */ - public messageSetWireFormat: boolean; + /** Properties of an Order. */ + interface IOrder { - /** MessageOptions noStandardDescriptorAccessor. */ - public noStandardDescriptorAccessor: boolean; + /** Order field */ + field?: (google.firestore.v1.StructuredQuery.IFieldReference|null); - /** MessageOptions deprecated. */ - public deprecated: boolean; + /** Order direction */ + direction?: (google.firestore.v1.StructuredQuery.Direction|null); + } - /** MessageOptions mapEntry. */ - public mapEntry: boolean; + /** Represents an Order. */ + class Order implements IOrder { - /** MessageOptions uninterpretedOption. */ - public uninterpretedOption: google.protobuf.IUninterpretedOption[]; + /** + * Constructs a new Order. + * @param [properties] Properties to set + */ + constructor(properties?: google.firestore.v1.StructuredQuery.IOrder); - /** - * Creates a MessageOptions message from a plain object. Also converts values to their respective internal types. - * @param object Plain object - * @returns MessageOptions - */ - public static fromObject(object: { [k: string]: any }): google.protobuf.MessageOptions; + /** Order field. */ + public field?: (google.firestore.v1.StructuredQuery.IFieldReference|null); - /** - * Creates a plain object from a MessageOptions message. Also converts values to other types if specified. - * @param message MessageOptions - * @param [options] Conversion options - * @returns Plain object - */ - public static toObject(message: google.protobuf.MessageOptions, options?: $protobuf.IConversionOptions): { [k: string]: any }; + /** Order direction. */ + public direction: google.firestore.v1.StructuredQuery.Direction; - /** - * Converts this MessageOptions to JSON. - * @returns JSON object - */ - public toJSON(): { [k: string]: any }; - } + /** + * Creates an Order message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns Order + */ + public static fromObject(object: { [k: string]: any }): google.firestore.v1.StructuredQuery.Order; - /** Properties of a FieldOptions. */ - interface IFieldOptions { + /** + * Creates a plain object from an Order message. Also converts values to other types if specified. + * @param message Order + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.firestore.v1.StructuredQuery.Order, options?: $protobuf.IConversionOptions): { [k: string]: any }; - /** FieldOptions ctype */ - ctype?: (google.protobuf.FieldOptions.CType|null); + /** + * Converts this Order to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; - /** FieldOptions packed */ - packed?: (boolean|null); + /** + * Gets the default type url for Order + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } - /** FieldOptions jstype */ - jstype?: (google.protobuf.FieldOptions.JSType|null); + /** Direction enum. */ + type Direction = + "DIRECTION_UNSPECIFIED"| "ASCENDING"| "DESCENDING"; - /** FieldOptions lazy */ - lazy?: (boolean|null); + /** Properties of a FieldReference. */ + interface IFieldReference { - /** FieldOptions deprecated */ - deprecated?: (boolean|null); + /** FieldReference fieldPath */ + fieldPath?: (string|null); + } - /** FieldOptions weak */ - weak?: (boolean|null); + /** Represents a FieldReference. */ + class FieldReference implements IFieldReference { - /** FieldOptions uninterpretedOption */ - uninterpretedOption?: (google.protobuf.IUninterpretedOption[]|null); + /** + * Constructs a new FieldReference. + * @param [properties] Properties to set + */ + constructor(properties?: google.firestore.v1.StructuredQuery.IFieldReference); - /** FieldOptions .google.api.fieldBehavior */ - ".google.api.fieldBehavior"?: (google.api.FieldBehavior[]|null); + /** FieldReference fieldPath. */ + public fieldPath: string; - /** FieldOptions .google.api.resourceReference */ - ".google.api.resourceReference"?: (google.api.IResourceReference|null); - } + /** + * Creates a FieldReference message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns FieldReference + */ + public static fromObject(object: { [k: string]: any }): google.firestore.v1.StructuredQuery.FieldReference; - /** Represents a FieldOptions. */ - class FieldOptions implements IFieldOptions { + /** + * Creates a plain object from a FieldReference message. Also converts values to other types if specified. + * @param message FieldReference + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.firestore.v1.StructuredQuery.FieldReference, options?: $protobuf.IConversionOptions): { [k: string]: any }; - /** - * Constructs a new FieldOptions. - * @param [properties] Properties to set - */ - constructor(properties?: google.protobuf.IFieldOptions); + /** + * Converts this FieldReference to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; - /** FieldOptions ctype. */ - public ctype: google.protobuf.FieldOptions.CType; + /** + * Gets the default type url for FieldReference + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } - /** FieldOptions packed. */ - public packed: boolean; + /** Properties of a Projection. */ + interface IProjection { - /** FieldOptions jstype. */ - public jstype: google.protobuf.FieldOptions.JSType; + /** Projection fields */ + fields?: (google.firestore.v1.StructuredQuery.IFieldReference[]|null); + } - /** FieldOptions lazy. */ - public lazy: boolean; + /** Represents a Projection. */ + class Projection implements IProjection { - /** FieldOptions deprecated. */ - public deprecated: boolean; + /** + * Constructs a new Projection. + * @param [properties] Properties to set + */ + constructor(properties?: google.firestore.v1.StructuredQuery.IProjection); - /** FieldOptions weak. */ - public weak: boolean; + /** Projection fields. */ + public fields: google.firestore.v1.StructuredQuery.IFieldReference[]; - /** FieldOptions uninterpretedOption. */ - public uninterpretedOption: google.protobuf.IUninterpretedOption[]; + /** + * Creates a Projection message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns Projection + */ + public static fromObject(object: { [k: string]: any }): google.firestore.v1.StructuredQuery.Projection; + + /** + * Creates a plain object from a Projection message. Also converts values to other types if specified. + * @param message Projection + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.firestore.v1.StructuredQuery.Projection, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this Projection to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; - /** - * Creates a FieldOptions message from a plain object. Also converts values to their respective internal types. - * @param object Plain object - * @returns FieldOptions - */ - public static fromObject(object: { [k: string]: any }): google.protobuf.FieldOptions; + /** + * Gets the default type url for Projection + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } - /** - * Creates a plain object from a FieldOptions message. Also converts values to other types if specified. - * @param message FieldOptions - * @param [options] Conversion options - * @returns Plain object - */ - public static toObject(message: google.protobuf.FieldOptions, options?: $protobuf.IConversionOptions): { [k: string]: any }; + /** Properties of a FindNearest. */ + interface IFindNearest { - /** - * Converts this FieldOptions to JSON. - * @returns JSON object - */ - public toJSON(): { [k: string]: any }; - } + /** FindNearest vectorField */ + vectorField?: (google.firestore.v1.StructuredQuery.IFieldReference|null); - namespace FieldOptions { + /** FindNearest queryVector */ + queryVector?: (google.firestore.v1.IValue|null); - /** CType enum. */ - type CType = - "STRING"| "CORD"| "STRING_PIECE"; + /** FindNearest distanceMeasure */ + distanceMeasure?: (google.firestore.v1.StructuredQuery.FindNearest.DistanceMeasure|null); - /** JSType enum. */ - type JSType = - "JS_NORMAL"| "JS_STRING"| "JS_NUMBER"; - } + /** FindNearest limit */ + limit?: (google.protobuf.IInt32Value|null); - /** Properties of an OneofOptions. */ - interface IOneofOptions { + /** FindNearest distanceResultField */ + distanceResultField?: (string|null); - /** OneofOptions uninterpretedOption */ - uninterpretedOption?: (google.protobuf.IUninterpretedOption[]|null); - } + /** FindNearest distanceThreshold */ + distanceThreshold?: (google.protobuf.IDoubleValue|null); + } - /** Represents an OneofOptions. */ - class OneofOptions implements IOneofOptions { + /** Represents a FindNearest. */ + class FindNearest implements IFindNearest { - /** - * Constructs a new OneofOptions. - * @param [properties] Properties to set - */ - constructor(properties?: google.protobuf.IOneofOptions); + /** + * Constructs a new FindNearest. + * @param [properties] Properties to set + */ + constructor(properties?: google.firestore.v1.StructuredQuery.IFindNearest); - /** OneofOptions uninterpretedOption. */ - public uninterpretedOption: google.protobuf.IUninterpretedOption[]; + /** FindNearest vectorField. */ + public vectorField?: (google.firestore.v1.StructuredQuery.IFieldReference|null); - /** - * Creates an OneofOptions message from a plain object. Also converts values to their respective internal types. - * @param object Plain object - * @returns OneofOptions - */ - public static fromObject(object: { [k: string]: any }): google.protobuf.OneofOptions; + /** FindNearest queryVector. */ + public queryVector?: (google.firestore.v1.IValue|null); - /** - * Creates a plain object from an OneofOptions message. Also converts values to other types if specified. - * @param message OneofOptions - * @param [options] Conversion options - * @returns Plain object - */ - public static toObject(message: google.protobuf.OneofOptions, options?: $protobuf.IConversionOptions): { [k: string]: any }; + /** FindNearest distanceMeasure. */ + public distanceMeasure: google.firestore.v1.StructuredQuery.FindNearest.DistanceMeasure; - /** - * Converts this OneofOptions to JSON. - * @returns JSON object - */ - public toJSON(): { [k: string]: any }; - } + /** FindNearest limit. */ + public limit?: (google.protobuf.IInt32Value|null); - /** Properties of an EnumOptions. */ - interface IEnumOptions { + /** FindNearest distanceResultField. */ + public distanceResultField: string; - /** EnumOptions allowAlias */ - allowAlias?: (boolean|null); + /** FindNearest distanceThreshold. */ + public distanceThreshold?: (google.protobuf.IDoubleValue|null); - /** EnumOptions deprecated */ - deprecated?: (boolean|null); + /** + * Creates a FindNearest message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns FindNearest + */ + public static fromObject(object: { [k: string]: any }): google.firestore.v1.StructuredQuery.FindNearest; - /** EnumOptions uninterpretedOption */ - uninterpretedOption?: (google.protobuf.IUninterpretedOption[]|null); - } + /** + * Creates a plain object from a FindNearest message. Also converts values to other types if specified. + * @param message FindNearest + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.firestore.v1.StructuredQuery.FindNearest, options?: $protobuf.IConversionOptions): { [k: string]: any }; - /** Represents an EnumOptions. */ - class EnumOptions implements IEnumOptions { + /** + * Converts this FindNearest to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; - /** - * Constructs a new EnumOptions. - * @param [properties] Properties to set - */ - constructor(properties?: google.protobuf.IEnumOptions); + /** + * Gets the default type url for FindNearest + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } - /** EnumOptions allowAlias. */ - public allowAlias: boolean; + namespace FindNearest { - /** EnumOptions deprecated. */ - public deprecated: boolean; + /** DistanceMeasure enum. */ + type DistanceMeasure = + "DISTANCE_MEASURE_UNSPECIFIED"| "EUCLIDEAN"| "COSINE"| "DOT_PRODUCT"; + } + } - /** EnumOptions uninterpretedOption. */ - public uninterpretedOption: google.protobuf.IUninterpretedOption[]; + /** Properties of a StructuredAggregationQuery. */ + interface IStructuredAggregationQuery { - /** - * Creates an EnumOptions message from a plain object. Also converts values to their respective internal types. - * @param object Plain object - * @returns EnumOptions - */ - public static fromObject(object: { [k: string]: any }): google.protobuf.EnumOptions; + /** StructuredAggregationQuery structuredQuery */ + structuredQuery?: (google.firestore.v1.IStructuredQuery|null); - /** - * Creates a plain object from an EnumOptions message. Also converts values to other types if specified. - * @param message EnumOptions - * @param [options] Conversion options - * @returns Plain object - */ - public static toObject(message: google.protobuf.EnumOptions, options?: $protobuf.IConversionOptions): { [k: string]: any }; + /** StructuredAggregationQuery aggregations */ + aggregations?: (google.firestore.v1.StructuredAggregationQuery.IAggregation[]|null); + } - /** - * Converts this EnumOptions to JSON. - * @returns JSON object - */ - public toJSON(): { [k: string]: any }; - } + /** Represents a StructuredAggregationQuery. */ + class StructuredAggregationQuery implements IStructuredAggregationQuery { - /** Properties of an EnumValueOptions. */ - interface IEnumValueOptions { + /** + * Constructs a new StructuredAggregationQuery. + * @param [properties] Properties to set + */ + constructor(properties?: google.firestore.v1.IStructuredAggregationQuery); - /** EnumValueOptions deprecated */ - deprecated?: (boolean|null); + /** StructuredAggregationQuery structuredQuery. */ + public structuredQuery?: (google.firestore.v1.IStructuredQuery|null); - /** EnumValueOptions uninterpretedOption */ - uninterpretedOption?: (google.protobuf.IUninterpretedOption[]|null); - } + /** StructuredAggregationQuery aggregations. */ + public aggregations: google.firestore.v1.StructuredAggregationQuery.IAggregation[]; - /** Represents an EnumValueOptions. */ - class EnumValueOptions implements IEnumValueOptions { + /** StructuredAggregationQuery queryType. */ + public queryType?: "structuredQuery"; - /** - * Constructs a new EnumValueOptions. - * @param [properties] Properties to set - */ - constructor(properties?: google.protobuf.IEnumValueOptions); + /** + * Creates a StructuredAggregationQuery message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns StructuredAggregationQuery + */ + public static fromObject(object: { [k: string]: any }): google.firestore.v1.StructuredAggregationQuery; - /** EnumValueOptions deprecated. */ - public deprecated: boolean; + /** + * Creates a plain object from a StructuredAggregationQuery message. Also converts values to other types if specified. + * @param message StructuredAggregationQuery + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.firestore.v1.StructuredAggregationQuery, options?: $protobuf.IConversionOptions): { [k: string]: any }; - /** EnumValueOptions uninterpretedOption. */ - public uninterpretedOption: google.protobuf.IUninterpretedOption[]; + /** + * Converts this StructuredAggregationQuery to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; - /** - * Creates an EnumValueOptions message from a plain object. Also converts values to their respective internal types. - * @param object Plain object - * @returns EnumValueOptions - */ - public static fromObject(object: { [k: string]: any }): google.protobuf.EnumValueOptions; + /** + * Gets the default type url for StructuredAggregationQuery + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } - /** - * Creates a plain object from an EnumValueOptions message. Also converts values to other types if specified. - * @param message EnumValueOptions - * @param [options] Conversion options - * @returns Plain object - */ - public static toObject(message: google.protobuf.EnumValueOptions, options?: $protobuf.IConversionOptions): { [k: string]: any }; + namespace StructuredAggregationQuery { - /** - * Converts this EnumValueOptions to JSON. - * @returns JSON object - */ - public toJSON(): { [k: string]: any }; - } + /** Properties of an Aggregation. */ + interface IAggregation { - /** Properties of a ServiceOptions. */ - interface IServiceOptions { + /** Aggregation count */ + count?: (google.firestore.v1.StructuredAggregationQuery.Aggregation.ICount|null); - /** ServiceOptions deprecated */ - deprecated?: (boolean|null); + /** Aggregation sum */ + sum?: (google.firestore.v1.StructuredAggregationQuery.Aggregation.ISum|null); - /** ServiceOptions uninterpretedOption */ - uninterpretedOption?: (google.protobuf.IUninterpretedOption[]|null); + /** Aggregation avg */ + avg?: (google.firestore.v1.StructuredAggregationQuery.Aggregation.IAvg|null); - /** ServiceOptions .google.api.defaultHost */ - ".google.api.defaultHost"?: (string|null); + /** Aggregation alias */ + alias?: (string|null); + } - /** ServiceOptions .google.api.oauthScopes */ - ".google.api.oauthScopes"?: (string|null); - } + /** Represents an Aggregation. */ + class Aggregation implements IAggregation { - /** Represents a ServiceOptions. */ - class ServiceOptions implements IServiceOptions { + /** + * Constructs a new Aggregation. + * @param [properties] Properties to set + */ + constructor(properties?: google.firestore.v1.StructuredAggregationQuery.IAggregation); - /** - * Constructs a new ServiceOptions. - * @param [properties] Properties to set - */ - constructor(properties?: google.protobuf.IServiceOptions); + /** Aggregation count. */ + public count?: (google.firestore.v1.StructuredAggregationQuery.Aggregation.ICount|null); - /** ServiceOptions deprecated. */ - public deprecated: boolean; + /** Aggregation sum. */ + public sum?: (google.firestore.v1.StructuredAggregationQuery.Aggregation.ISum|null); - /** ServiceOptions uninterpretedOption. */ - public uninterpretedOption: google.protobuf.IUninterpretedOption[]; + /** Aggregation avg. */ + public avg?: (google.firestore.v1.StructuredAggregationQuery.Aggregation.IAvg|null); - /** - * Creates a ServiceOptions message from a plain object. Also converts values to their respective internal types. - * @param object Plain object - * @returns ServiceOptions - */ - public static fromObject(object: { [k: string]: any }): google.protobuf.ServiceOptions; + /** Aggregation alias. */ + public alias: string; - /** - * Creates a plain object from a ServiceOptions message. Also converts values to other types if specified. - * @param message ServiceOptions - * @param [options] Conversion options - * @returns Plain object - */ - public static toObject(message: google.protobuf.ServiceOptions, options?: $protobuf.IConversionOptions): { [k: string]: any }; + /** Aggregation operator. */ + public operator?: ("count"|"sum"|"avg"); - /** - * Converts this ServiceOptions to JSON. - * @returns JSON object - */ - public toJSON(): { [k: string]: any }; - } + /** + * Creates an Aggregation message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns Aggregation + */ + public static fromObject(object: { [k: string]: any }): google.firestore.v1.StructuredAggregationQuery.Aggregation; - /** Properties of a MethodOptions. */ - interface IMethodOptions { + /** + * Creates a plain object from an Aggregation message. Also converts values to other types if specified. + * @param message Aggregation + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.firestore.v1.StructuredAggregationQuery.Aggregation, options?: $protobuf.IConversionOptions): { [k: string]: any }; - /** MethodOptions deprecated */ - deprecated?: (boolean|null); + /** + * Converts this Aggregation to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; - /** MethodOptions uninterpretedOption */ - uninterpretedOption?: (google.protobuf.IUninterpretedOption[]|null); + /** + * Gets the default type url for Aggregation + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } - /** MethodOptions .google.api.http */ - ".google.api.http"?: (google.api.IHttpRule|null); + namespace Aggregation { + + /** Properties of a Count. */ + interface ICount { + + /** Count upTo */ + upTo?: (google.protobuf.IInt64Value|null); + } + + /** Represents a Count. */ + class Count implements ICount { + + /** + * Constructs a new Count. + * @param [properties] Properties to set + */ + constructor(properties?: google.firestore.v1.StructuredAggregationQuery.Aggregation.ICount); + + /** Count upTo. */ + public upTo?: (google.protobuf.IInt64Value|null); + + /** + * Creates a Count message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns Count + */ + public static fromObject(object: { [k: string]: any }): google.firestore.v1.StructuredAggregationQuery.Aggregation.Count; + + /** + * Creates a plain object from a Count message. Also converts values to other types if specified. + * @param message Count + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.firestore.v1.StructuredAggregationQuery.Aggregation.Count, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this Count to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for Count + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a Sum. */ + interface ISum { + + /** Sum field */ + field?: (google.firestore.v1.StructuredQuery.IFieldReference|null); + } + + /** Represents a Sum. */ + class Sum implements ISum { + + /** + * Constructs a new Sum. + * @param [properties] Properties to set + */ + constructor(properties?: google.firestore.v1.StructuredAggregationQuery.Aggregation.ISum); + + /** Sum field. */ + public field?: (google.firestore.v1.StructuredQuery.IFieldReference|null); + + /** + * Creates a Sum message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns Sum + */ + public static fromObject(object: { [k: string]: any }): google.firestore.v1.StructuredAggregationQuery.Aggregation.Sum; + + /** + * Creates a plain object from a Sum message. Also converts values to other types if specified. + * @param message Sum + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.firestore.v1.StructuredAggregationQuery.Aggregation.Sum, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this Sum to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for Sum + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of an Avg. */ + interface IAvg { + + /** Avg field */ + field?: (google.firestore.v1.StructuredQuery.IFieldReference|null); + } + + /** Represents an Avg. */ + class Avg implements IAvg { + + /** + * Constructs a new Avg. + * @param [properties] Properties to set + */ + constructor(properties?: google.firestore.v1.StructuredAggregationQuery.Aggregation.IAvg); + + /** Avg field. */ + public field?: (google.firestore.v1.StructuredQuery.IFieldReference|null); + + /** + * Creates an Avg message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns Avg + */ + public static fromObject(object: { [k: string]: any }): google.firestore.v1.StructuredAggregationQuery.Aggregation.Avg; + + /** + * Creates a plain object from an Avg message. Also converts values to other types if specified. + * @param message Avg + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.firestore.v1.StructuredAggregationQuery.Aggregation.Avg, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this Avg to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for Avg + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + } + } - /** MethodOptions .google.api.methodSignature */ - ".google.api.methodSignature"?: (string[]|null); + /** Properties of a Cursor. */ + interface ICursor { - /** MethodOptions .google.longrunning.operationInfo */ - ".google.longrunning.operationInfo"?: (google.longrunning.IOperationInfo|null); - } + /** Cursor values */ + values?: (google.firestore.v1.IValue[]|null); - /** Represents a MethodOptions. */ - class MethodOptions implements IMethodOptions { + /** Cursor before */ + before?: (boolean|null); + } - /** - * Constructs a new MethodOptions. - * @param [properties] Properties to set - */ - constructor(properties?: google.protobuf.IMethodOptions); + /** Represents a Cursor. */ + class Cursor implements ICursor { - /** MethodOptions deprecated. */ - public deprecated: boolean; + /** + * Constructs a new Cursor. + * @param [properties] Properties to set + */ + constructor(properties?: google.firestore.v1.ICursor); - /** MethodOptions uninterpretedOption. */ - public uninterpretedOption: google.protobuf.IUninterpretedOption[]; + /** Cursor values. */ + public values: google.firestore.v1.IValue[]; - /** - * Creates a MethodOptions message from a plain object. Also converts values to their respective internal types. - * @param object Plain object - * @returns MethodOptions - */ - public static fromObject(object: { [k: string]: any }): google.protobuf.MethodOptions; + /** Cursor before. */ + public before: boolean; - /** - * Creates a plain object from a MethodOptions message. Also converts values to other types if specified. - * @param message MethodOptions - * @param [options] Conversion options - * @returns Plain object - */ - public static toObject(message: google.protobuf.MethodOptions, options?: $protobuf.IConversionOptions): { [k: string]: any }; + /** + * Creates a Cursor message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns Cursor + */ + public static fromObject(object: { [k: string]: any }): google.firestore.v1.Cursor; - /** - * Converts this MethodOptions to JSON. - * @returns JSON object - */ - public toJSON(): { [k: string]: any }; - } + /** + * Creates a plain object from a Cursor message. Also converts values to other types if specified. + * @param message Cursor + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.firestore.v1.Cursor, options?: $protobuf.IConversionOptions): { [k: string]: any }; - /** Properties of an UninterpretedOption. */ - interface IUninterpretedOption { + /** + * Converts this Cursor to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; - /** UninterpretedOption name */ - name?: (google.protobuf.UninterpretedOption.INamePart[]|null); + /** + * Gets the default type url for Cursor + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } - /** UninterpretedOption identifierValue */ - identifierValue?: (string|null); + /** Properties of an ExplainOptions. */ + interface IExplainOptions { - /** UninterpretedOption positiveIntValue */ - positiveIntValue?: (number|string|null); + /** ExplainOptions analyze */ + analyze?: (boolean|null); + } - /** UninterpretedOption negativeIntValue */ - negativeIntValue?: (number|string|null); + /** Represents an ExplainOptions. */ + class ExplainOptions implements IExplainOptions { - /** UninterpretedOption doubleValue */ - doubleValue?: (number|null); + /** + * Constructs a new ExplainOptions. + * @param [properties] Properties to set + */ + constructor(properties?: google.firestore.v1.IExplainOptions); - /** UninterpretedOption stringValue */ - stringValue?: (Uint8Array|null); + /** ExplainOptions analyze. */ + public analyze: boolean; - /** UninterpretedOption aggregateValue */ - aggregateValue?: (string|null); - } + /** + * Creates an ExplainOptions message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns ExplainOptions + */ + public static fromObject(object: { [k: string]: any }): google.firestore.v1.ExplainOptions; - /** Represents an UninterpretedOption. */ - class UninterpretedOption implements IUninterpretedOption { + /** + * Creates a plain object from an ExplainOptions message. Also converts values to other types if specified. + * @param message ExplainOptions + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.firestore.v1.ExplainOptions, options?: $protobuf.IConversionOptions): { [k: string]: any }; - /** - * Constructs a new UninterpretedOption. - * @param [properties] Properties to set - */ - constructor(properties?: google.protobuf.IUninterpretedOption); + /** + * Converts this ExplainOptions to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; - /** UninterpretedOption name. */ - public name: google.protobuf.UninterpretedOption.INamePart[]; + /** + * Gets the default type url for ExplainOptions + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } - /** UninterpretedOption identifierValue. */ - public identifierValue: string; + /** Properties of an ExplainMetrics. */ + interface IExplainMetrics { - /** UninterpretedOption positiveIntValue. */ - public positiveIntValue: (number|string); + /** ExplainMetrics planSummary */ + planSummary?: (google.firestore.v1.IPlanSummary|null); - /** UninterpretedOption negativeIntValue. */ - public negativeIntValue: (number|string); + /** ExplainMetrics executionStats */ + executionStats?: (google.firestore.v1.IExecutionStats|null); + } - /** UninterpretedOption doubleValue. */ - public doubleValue: number; + /** Represents an ExplainMetrics. */ + class ExplainMetrics implements IExplainMetrics { - /** UninterpretedOption stringValue. */ - public stringValue: Uint8Array; + /** + * Constructs a new ExplainMetrics. + * @param [properties] Properties to set + */ + constructor(properties?: google.firestore.v1.IExplainMetrics); - /** UninterpretedOption aggregateValue. */ - public aggregateValue: string; + /** ExplainMetrics planSummary. */ + public planSummary?: (google.firestore.v1.IPlanSummary|null); - /** - * Creates an UninterpretedOption message from a plain object. Also converts values to their respective internal types. - * @param object Plain object - * @returns UninterpretedOption - */ - public static fromObject(object: { [k: string]: any }): google.protobuf.UninterpretedOption; + /** ExplainMetrics executionStats. */ + public executionStats?: (google.firestore.v1.IExecutionStats|null); - /** - * Creates a plain object from an UninterpretedOption message. Also converts values to other types if specified. - * @param message UninterpretedOption - * @param [options] Conversion options - * @returns Plain object - */ - public static toObject(message: google.protobuf.UninterpretedOption, options?: $protobuf.IConversionOptions): { [k: string]: any }; + /** + * Creates an ExplainMetrics message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns ExplainMetrics + */ + public static fromObject(object: { [k: string]: any }): google.firestore.v1.ExplainMetrics; - /** - * Converts this UninterpretedOption to JSON. - * @returns JSON object - */ - public toJSON(): { [k: string]: any }; - } + /** + * Creates a plain object from an ExplainMetrics message. Also converts values to other types if specified. + * @param message ExplainMetrics + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.firestore.v1.ExplainMetrics, options?: $protobuf.IConversionOptions): { [k: string]: any }; - namespace UninterpretedOption { + /** + * Converts this ExplainMetrics to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; - /** Properties of a NamePart. */ - interface INamePart { + /** + * Gets the default type url for ExplainMetrics + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } - /** NamePart namePart */ - namePart: string; + /** Properties of a PlanSummary. */ + interface IPlanSummary { - /** NamePart isExtension */ - isExtension: boolean; + /** PlanSummary indexesUsed */ + indexesUsed?: (google.protobuf.IStruct[]|null); } - /** Represents a NamePart. */ - class NamePart implements INamePart { + /** Represents a PlanSummary. */ + class PlanSummary implements IPlanSummary { /** - * Constructs a new NamePart. + * Constructs a new PlanSummary. * @param [properties] Properties to set */ - constructor(properties?: google.protobuf.UninterpretedOption.INamePart); - - /** NamePart namePart. */ - public namePart: string; + constructor(properties?: google.firestore.v1.IPlanSummary); - /** NamePart isExtension. */ - public isExtension: boolean; + /** PlanSummary indexesUsed. */ + public indexesUsed: google.protobuf.IStruct[]; /** - * Creates a NamePart message from a plain object. Also converts values to their respective internal types. + * Creates a PlanSummary message from a plain object. Also converts values to their respective internal types. * @param object Plain object - * @returns NamePart + * @returns PlanSummary */ - public static fromObject(object: { [k: string]: any }): google.protobuf.UninterpretedOption.NamePart; + public static fromObject(object: { [k: string]: any }): google.firestore.v1.PlanSummary; /** - * Creates a plain object from a NamePart message. Also converts values to other types if specified. - * @param message NamePart + * Creates a plain object from a PlanSummary message. Also converts values to other types if specified. + * @param message PlanSummary * @param [options] Conversion options * @returns Plain object */ - public static toObject(message: google.protobuf.UninterpretedOption.NamePart, options?: $protobuf.IConversionOptions): { [k: string]: any }; + public static toObject(message: google.firestore.v1.PlanSummary, options?: $protobuf.IConversionOptions): { [k: string]: any }; /** - * Converts this NamePart to JSON. + * Converts this PlanSummary to JSON. * @returns JSON object */ public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for PlanSummary + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; } - } - /** Properties of a SourceCodeInfo. */ - interface ISourceCodeInfo { + /** Properties of an ExecutionStats. */ + interface IExecutionStats { - /** SourceCodeInfo location */ - location?: (google.protobuf.SourceCodeInfo.ILocation[]|null); - } + /** ExecutionStats resultsReturned */ + resultsReturned?: (number|string|null); - /** Represents a SourceCodeInfo. */ - class SourceCodeInfo implements ISourceCodeInfo { + /** ExecutionStats executionDuration */ + executionDuration?: (google.protobuf.IDuration|null); - /** - * Constructs a new SourceCodeInfo. - * @param [properties] Properties to set - */ - constructor(properties?: google.protobuf.ISourceCodeInfo); + /** ExecutionStats readOperations */ + readOperations?: (number|string|null); - /** SourceCodeInfo location. */ - public location: google.protobuf.SourceCodeInfo.ILocation[]; + /** ExecutionStats debugStats */ + debugStats?: (google.protobuf.IStruct|null); + } - /** - * Creates a SourceCodeInfo message from a plain object. Also converts values to their respective internal types. - * @param object Plain object - * @returns SourceCodeInfo - */ - public static fromObject(object: { [k: string]: any }): google.protobuf.SourceCodeInfo; + /** Represents an ExecutionStats. */ + class ExecutionStats implements IExecutionStats { - /** - * Creates a plain object from a SourceCodeInfo message. Also converts values to other types if specified. - * @param message SourceCodeInfo - * @param [options] Conversion options - * @returns Plain object - */ - public static toObject(message: google.protobuf.SourceCodeInfo, options?: $protobuf.IConversionOptions): { [k: string]: any }; + /** + * Constructs a new ExecutionStats. + * @param [properties] Properties to set + */ + constructor(properties?: google.firestore.v1.IExecutionStats); - /** - * Converts this SourceCodeInfo to JSON. - * @returns JSON object - */ - public toJSON(): { [k: string]: any }; - } + /** ExecutionStats resultsReturned. */ + public resultsReturned: (number|string); - namespace SourceCodeInfo { + /** ExecutionStats executionDuration. */ + public executionDuration?: (google.protobuf.IDuration|null); - /** Properties of a Location. */ - interface ILocation { + /** ExecutionStats readOperations. */ + public readOperations: (number|string); - /** Location path */ - path?: (number[]|null); + /** ExecutionStats debugStats. */ + public debugStats?: (google.protobuf.IStruct|null); + + /** + * Creates an ExecutionStats message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns ExecutionStats + */ + public static fromObject(object: { [k: string]: any }): google.firestore.v1.ExecutionStats; + + /** + * Creates a plain object from an ExecutionStats message. Also converts values to other types if specified. + * @param message ExecutionStats + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.firestore.v1.ExecutionStats, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this ExecutionStats to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for ExecutionStats + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a Write. */ + interface IWrite { + + /** Write update */ + update?: (google.firestore.v1.IDocument|null); - /** Location span */ - span?: (number[]|null); + /** Write delete */ + "delete"?: (string|null); - /** Location leadingComments */ - leadingComments?: (string|null); + /** Write transform */ + transform?: (google.firestore.v1.IDocumentTransform|null); - /** Location trailingComments */ - trailingComments?: (string|null); + /** Write updateMask */ + updateMask?: (google.firestore.v1.IDocumentMask|null); - /** Location leadingDetachedComments */ - leadingDetachedComments?: (string[]|null); + /** Write updateTransforms */ + updateTransforms?: (google.firestore.v1.DocumentTransform.IFieldTransform[]|null); + + /** Write currentDocument */ + currentDocument?: (google.firestore.v1.IPrecondition|null); } - /** Represents a Location. */ - class Location implements ILocation { + /** Represents a Write. */ + class Write implements IWrite { /** - * Constructs a new Location. + * Constructs a new Write. * @param [properties] Properties to set */ - constructor(properties?: google.protobuf.SourceCodeInfo.ILocation); + constructor(properties?: google.firestore.v1.IWrite); - /** Location path. */ - public path: number[]; + /** Write update. */ + public update?: (google.firestore.v1.IDocument|null); - /** Location span. */ - public span: number[]; + /** Write delete. */ + public delete?: (string|null); - /** Location leadingComments. */ - public leadingComments: string; + /** Write transform. */ + public transform?: (google.firestore.v1.IDocumentTransform|null); - /** Location trailingComments. */ - public trailingComments: string; + /** Write updateMask. */ + public updateMask?: (google.firestore.v1.IDocumentMask|null); - /** Location leadingDetachedComments. */ - public leadingDetachedComments: string[]; + /** Write updateTransforms. */ + public updateTransforms: google.firestore.v1.DocumentTransform.IFieldTransform[]; + + /** Write currentDocument. */ + public currentDocument?: (google.firestore.v1.IPrecondition|null); + + /** Write operation. */ + public operation?: ("update"|"delete"|"transform"); /** - * Creates a Location message from a plain object. Also converts values to their respective internal types. + * Creates a Write message from a plain object. Also converts values to their respective internal types. * @param object Plain object - * @returns Location + * @returns Write */ - public static fromObject(object: { [k: string]: any }): google.protobuf.SourceCodeInfo.Location; + public static fromObject(object: { [k: string]: any }): google.firestore.v1.Write; /** - * Creates a plain object from a Location message. Also converts values to other types if specified. - * @param message Location + * Creates a plain object from a Write message. Also converts values to other types if specified. + * @param message Write * @param [options] Conversion options * @returns Plain object */ - public static toObject(message: google.protobuf.SourceCodeInfo.Location, options?: $protobuf.IConversionOptions): { [k: string]: any }; + public static toObject(message: google.firestore.v1.Write, options?: $protobuf.IConversionOptions): { [k: string]: any }; /** - * Converts this Location to JSON. + * Converts this Write to JSON. * @returns JSON object */ public toJSON(): { [k: string]: any }; - } - } - - /** Properties of a GeneratedCodeInfo. */ - interface IGeneratedCodeInfo { - - /** GeneratedCodeInfo annotation */ - annotation?: (google.protobuf.GeneratedCodeInfo.IAnnotation[]|null); - } - - /** Represents a GeneratedCodeInfo. */ - class GeneratedCodeInfo implements IGeneratedCodeInfo { - - /** - * Constructs a new GeneratedCodeInfo. - * @param [properties] Properties to set - */ - constructor(properties?: google.protobuf.IGeneratedCodeInfo); - - /** GeneratedCodeInfo annotation. */ - public annotation: google.protobuf.GeneratedCodeInfo.IAnnotation[]; - - /** - * Creates a GeneratedCodeInfo message from a plain object. Also converts values to their respective internal types. - * @param object Plain object - * @returns GeneratedCodeInfo - */ - public static fromObject(object: { [k: string]: any }): google.protobuf.GeneratedCodeInfo; - - /** - * Creates a plain object from a GeneratedCodeInfo message. Also converts values to other types if specified. - * @param message GeneratedCodeInfo - * @param [options] Conversion options - * @returns Plain object - */ - public static toObject(message: google.protobuf.GeneratedCodeInfo, options?: $protobuf.IConversionOptions): { [k: string]: any }; - - /** - * Converts this GeneratedCodeInfo to JSON. - * @returns JSON object - */ - public toJSON(): { [k: string]: any }; - } - - namespace GeneratedCodeInfo { - /** Properties of an Annotation. */ - interface IAnnotation { - - /** Annotation path */ - path?: (number[]|null); + /** + * Gets the default type url for Write + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } - /** Annotation sourceFile */ - sourceFile?: (string|null); + /** Properties of a DocumentTransform. */ + interface IDocumentTransform { - /** Annotation begin */ - begin?: (number|null); + /** DocumentTransform document */ + document?: (string|null); - /** Annotation end */ - end?: (number|null); + /** DocumentTransform fieldTransforms */ + fieldTransforms?: (google.firestore.v1.DocumentTransform.IFieldTransform[]|null); } - /** Represents an Annotation. */ - class Annotation implements IAnnotation { + /** Represents a DocumentTransform. */ + class DocumentTransform implements IDocumentTransform { /** - * Constructs a new Annotation. + * Constructs a new DocumentTransform. * @param [properties] Properties to set */ - constructor(properties?: google.protobuf.GeneratedCodeInfo.IAnnotation); - - /** Annotation path. */ - public path: number[]; - - /** Annotation sourceFile. */ - public sourceFile: string; + constructor(properties?: google.firestore.v1.IDocumentTransform); - /** Annotation begin. */ - public begin: number; + /** DocumentTransform document. */ + public document: string; - /** Annotation end. */ - public end: number; + /** DocumentTransform fieldTransforms. */ + public fieldTransforms: google.firestore.v1.DocumentTransform.IFieldTransform[]; /** - * Creates an Annotation message from a plain object. Also converts values to their respective internal types. + * Creates a DocumentTransform message from a plain object. Also converts values to their respective internal types. * @param object Plain object - * @returns Annotation + * @returns DocumentTransform */ - public static fromObject(object: { [k: string]: any }): google.protobuf.GeneratedCodeInfo.Annotation; + public static fromObject(object: { [k: string]: any }): google.firestore.v1.DocumentTransform; /** - * Creates a plain object from an Annotation message. Also converts values to other types if specified. - * @param message Annotation + * Creates a plain object from a DocumentTransform message. Also converts values to other types if specified. + * @param message DocumentTransform * @param [options] Conversion options * @returns Plain object */ - public static toObject(message: google.protobuf.GeneratedCodeInfo.Annotation, options?: $protobuf.IConversionOptions): { [k: string]: any }; + public static toObject(message: google.firestore.v1.DocumentTransform, options?: $protobuf.IConversionOptions): { [k: string]: any }; /** - * Converts this Annotation to JSON. + * Converts this DocumentTransform to JSON. * @returns JSON object */ public toJSON(): { [k: string]: any }; - } - } - /** Properties of a Struct. */ - interface IStruct { + /** + * Gets the default type url for DocumentTransform + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } - /** Struct fields */ - fields?: ({ [k: string]: google.protobuf.IValue }|null); - } + namespace DocumentTransform { - /** Represents a Struct. */ - class Struct implements IStruct { + /** Properties of a FieldTransform. */ + interface IFieldTransform { - /** - * Constructs a new Struct. - * @param [properties] Properties to set - */ - constructor(properties?: google.protobuf.IStruct); + /** FieldTransform fieldPath */ + fieldPath?: (string|null); - /** Struct fields. */ - public fields: { [k: string]: google.protobuf.IValue }; + /** FieldTransform setToServerValue */ + setToServerValue?: (google.firestore.v1.DocumentTransform.FieldTransform.ServerValue|null); - /** - * Creates a Struct message from a plain object. Also converts values to their respective internal types. - * @param object Plain object - * @returns Struct - */ - public static fromObject(object: { [k: string]: any }): google.protobuf.Struct; + /** FieldTransform increment */ + increment?: (google.firestore.v1.IValue|null); - /** - * Creates a plain object from a Struct message. Also converts values to other types if specified. - * @param message Struct - * @param [options] Conversion options - * @returns Plain object - */ - public static toObject(message: google.protobuf.Struct, options?: $protobuf.IConversionOptions): { [k: string]: any }; + /** FieldTransform maximum */ + maximum?: (google.firestore.v1.IValue|null); - /** - * Converts this Struct to JSON. - * @returns JSON object - */ - public toJSON(): { [k: string]: any }; - } + /** FieldTransform minimum */ + minimum?: (google.firestore.v1.IValue|null); - /** Properties of a Value. */ - interface IValue { + /** FieldTransform appendMissingElements */ + appendMissingElements?: (google.firestore.v1.IArrayValue|null); - /** Value nullValue */ - nullValue?: (google.protobuf.NullValue|null); + /** FieldTransform removeAllFromArray */ + removeAllFromArray?: (google.firestore.v1.IArrayValue|null); + } - /** Value numberValue */ - numberValue?: (number|null); + /** Represents a FieldTransform. */ + class FieldTransform implements IFieldTransform { - /** Value stringValue */ - stringValue?: (string|null); + /** + * Constructs a new FieldTransform. + * @param [properties] Properties to set + */ + constructor(properties?: google.firestore.v1.DocumentTransform.IFieldTransform); - /** Value boolValue */ - boolValue?: (boolean|null); + /** FieldTransform fieldPath. */ + public fieldPath: string; - /** Value structValue */ - structValue?: (google.protobuf.IStruct|null); + /** FieldTransform setToServerValue. */ + public setToServerValue?: (google.firestore.v1.DocumentTransform.FieldTransform.ServerValue|null); - /** Value listValue */ - listValue?: (google.protobuf.IListValue|null); - } + /** FieldTransform increment. */ + public increment?: (google.firestore.v1.IValue|null); - /** Represents a Value. */ - class Value implements IValue { + /** FieldTransform maximum. */ + public maximum?: (google.firestore.v1.IValue|null); - /** - * Constructs a new Value. - * @param [properties] Properties to set - */ - constructor(properties?: google.protobuf.IValue); + /** FieldTransform minimum. */ + public minimum?: (google.firestore.v1.IValue|null); - /** Value nullValue. */ - public nullValue?: (google.protobuf.NullValue|null); + /** FieldTransform appendMissingElements. */ + public appendMissingElements?: (google.firestore.v1.IArrayValue|null); - /** Value numberValue. */ - public numberValue?: (number|null); + /** FieldTransform removeAllFromArray. */ + public removeAllFromArray?: (google.firestore.v1.IArrayValue|null); - /** Value stringValue. */ - public stringValue?: (string|null); + /** FieldTransform transformType. */ + public transformType?: ("setToServerValue"|"increment"|"maximum"|"minimum"|"appendMissingElements"|"removeAllFromArray"); - /** Value boolValue. */ - public boolValue?: (boolean|null); + /** + * Creates a FieldTransform message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns FieldTransform + */ + public static fromObject(object: { [k: string]: any }): google.firestore.v1.DocumentTransform.FieldTransform; - /** Value structValue. */ - public structValue?: (google.protobuf.IStruct|null); + /** + * Creates a plain object from a FieldTransform message. Also converts values to other types if specified. + * @param message FieldTransform + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.firestore.v1.DocumentTransform.FieldTransform, options?: $protobuf.IConversionOptions): { [k: string]: any }; - /** Value listValue. */ - public listValue?: (google.protobuf.IListValue|null); + /** + * Converts this FieldTransform to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; - /** Value kind. */ - public kind?: ("nullValue"|"numberValue"|"stringValue"|"boolValue"|"structValue"|"listValue"); + /** + * Gets the default type url for FieldTransform + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } - /** - * Creates a Value message from a plain object. Also converts values to their respective internal types. - * @param object Plain object - * @returns Value - */ - public static fromObject(object: { [k: string]: any }): google.protobuf.Value; + namespace FieldTransform { - /** - * Creates a plain object from a Value message. Also converts values to other types if specified. - * @param message Value - * @param [options] Conversion options - * @returns Plain object - */ - public static toObject(message: google.protobuf.Value, options?: $protobuf.IConversionOptions): { [k: string]: any }; + /** ServerValue enum. */ + type ServerValue = + "SERVER_VALUE_UNSPECIFIED"| "REQUEST_TIME"; + } + } - /** - * Converts this Value to JSON. - * @returns JSON object - */ - public toJSON(): { [k: string]: any }; - } + /** Properties of a WriteResult. */ + interface IWriteResult { - /** NullValue enum. */ - type NullValue = - "NULL_VALUE"; + /** WriteResult updateTime */ + updateTime?: (google.protobuf.ITimestamp|null); - /** Properties of a ListValue. */ - interface IListValue { + /** WriteResult transformResults */ + transformResults?: (google.firestore.v1.IValue[]|null); + } - /** ListValue values */ - values?: (google.protobuf.IValue[]|null); - } + /** Represents a WriteResult. */ + class WriteResult implements IWriteResult { - /** Represents a ListValue. */ - class ListValue implements IListValue { + /** + * Constructs a new WriteResult. + * @param [properties] Properties to set + */ + constructor(properties?: google.firestore.v1.IWriteResult); - /** - * Constructs a new ListValue. - * @param [properties] Properties to set - */ - constructor(properties?: google.protobuf.IListValue); + /** WriteResult updateTime. */ + public updateTime?: (google.protobuf.ITimestamp|null); - /** ListValue values. */ - public values: google.protobuf.IValue[]; + /** WriteResult transformResults. */ + public transformResults: google.firestore.v1.IValue[]; - /** - * Creates a ListValue message from a plain object. Also converts values to their respective internal types. - * @param object Plain object - * @returns ListValue - */ - public static fromObject(object: { [k: string]: any }): google.protobuf.ListValue; + /** + * Creates a WriteResult message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns WriteResult + */ + public static fromObject(object: { [k: string]: any }): google.firestore.v1.WriteResult; - /** - * Creates a plain object from a ListValue message. Also converts values to other types if specified. - * @param message ListValue - * @param [options] Conversion options - * @returns Plain object - */ - public static toObject(message: google.protobuf.ListValue, options?: $protobuf.IConversionOptions): { [k: string]: any }; + /** + * Creates a plain object from a WriteResult message. Also converts values to other types if specified. + * @param message WriteResult + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.firestore.v1.WriteResult, options?: $protobuf.IConversionOptions): { [k: string]: any }; - /** - * Converts this ListValue to JSON. - * @returns JSON object - */ - public toJSON(): { [k: string]: any }; - } + /** + * Converts this WriteResult to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; - /** Properties of an Empty. */ - interface IEmpty { - } + /** + * Gets the default type url for WriteResult + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } - /** Represents an Empty. */ - class Empty implements IEmpty { + /** Properties of a DocumentChange. */ + interface IDocumentChange { - /** - * Constructs a new Empty. - * @param [properties] Properties to set - */ - constructor(properties?: google.protobuf.IEmpty); + /** DocumentChange document */ + document?: (google.firestore.v1.IDocument|null); - /** - * Creates an Empty message from a plain object. Also converts values to their respective internal types. - * @param object Plain object - * @returns Empty - */ - public static fromObject(object: { [k: string]: any }): google.protobuf.Empty; + /** DocumentChange targetIds */ + targetIds?: (number[]|null); - /** - * Creates a plain object from an Empty message. Also converts values to other types if specified. - * @param message Empty - * @param [options] Conversion options - * @returns Plain object - */ - public static toObject(message: google.protobuf.Empty, options?: $protobuf.IConversionOptions): { [k: string]: any }; + /** DocumentChange removedTargetIds */ + removedTargetIds?: (number[]|null); + } - /** - * Converts this Empty to JSON. - * @returns JSON object - */ - public toJSON(): { [k: string]: any }; - } + /** Represents a DocumentChange. */ + class DocumentChange implements IDocumentChange { - /** Properties of a DoubleValue. */ - interface IDoubleValue { + /** + * Constructs a new DocumentChange. + * @param [properties] Properties to set + */ + constructor(properties?: google.firestore.v1.IDocumentChange); - /** DoubleValue value */ - value?: (number|null); - } + /** DocumentChange document. */ + public document?: (google.firestore.v1.IDocument|null); - /** Represents a DoubleValue. */ - class DoubleValue implements IDoubleValue { + /** DocumentChange targetIds. */ + public targetIds: number[]; - /** - * Constructs a new DoubleValue. - * @param [properties] Properties to set - */ - constructor(properties?: google.protobuf.IDoubleValue); + /** DocumentChange removedTargetIds. */ + public removedTargetIds: number[]; - /** DoubleValue value. */ - public value: number; + /** + * Creates a DocumentChange message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns DocumentChange + */ + public static fromObject(object: { [k: string]: any }): google.firestore.v1.DocumentChange; - /** - * Creates a DoubleValue message from a plain object. Also converts values to their respective internal types. - * @param object Plain object - * @returns DoubleValue - */ - public static fromObject(object: { [k: string]: any }): google.protobuf.DoubleValue; + /** + * Creates a plain object from a DocumentChange message. Also converts values to other types if specified. + * @param message DocumentChange + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.firestore.v1.DocumentChange, options?: $protobuf.IConversionOptions): { [k: string]: any }; - /** - * Creates a plain object from a DoubleValue message. Also converts values to other types if specified. - * @param message DoubleValue - * @param [options] Conversion options - * @returns Plain object - */ - public static toObject(message: google.protobuf.DoubleValue, options?: $protobuf.IConversionOptions): { [k: string]: any }; + /** + * Converts this DocumentChange to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; - /** - * Converts this DoubleValue to JSON. - * @returns JSON object - */ - public toJSON(): { [k: string]: any }; - } + /** + * Gets the default type url for DocumentChange + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a DocumentDelete. */ + interface IDocumentDelete { - /** Properties of a FloatValue. */ - interface IFloatValue { + /** DocumentDelete document */ + document?: (string|null); - /** FloatValue value */ - value?: (number|null); - } + /** DocumentDelete removedTargetIds */ + removedTargetIds?: (number[]|null); - /** Represents a FloatValue. */ - class FloatValue implements IFloatValue { + /** DocumentDelete readTime */ + readTime?: (google.protobuf.ITimestamp|null); + } - /** - * Constructs a new FloatValue. - * @param [properties] Properties to set - */ - constructor(properties?: google.protobuf.IFloatValue); + /** Represents a DocumentDelete. */ + class DocumentDelete implements IDocumentDelete { - /** FloatValue value. */ - public value: number; + /** + * Constructs a new DocumentDelete. + * @param [properties] Properties to set + */ + constructor(properties?: google.firestore.v1.IDocumentDelete); - /** - * Creates a FloatValue message from a plain object. Also converts values to their respective internal types. - * @param object Plain object - * @returns FloatValue - */ - public static fromObject(object: { [k: string]: any }): google.protobuf.FloatValue; + /** DocumentDelete document. */ + public document: string; - /** - * Creates a plain object from a FloatValue message. Also converts values to other types if specified. - * @param message FloatValue - * @param [options] Conversion options - * @returns Plain object - */ - public static toObject(message: google.protobuf.FloatValue, options?: $protobuf.IConversionOptions): { [k: string]: any }; + /** DocumentDelete removedTargetIds. */ + public removedTargetIds: number[]; - /** - * Converts this FloatValue to JSON. - * @returns JSON object - */ - public toJSON(): { [k: string]: any }; - } + /** DocumentDelete readTime. */ + public readTime?: (google.protobuf.ITimestamp|null); - /** Properties of an Int64Value. */ - interface IInt64Value { + /** + * Creates a DocumentDelete message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns DocumentDelete + */ + public static fromObject(object: { [k: string]: any }): google.firestore.v1.DocumentDelete; - /** Int64Value value */ - value?: (number|string|null); - } + /** + * Creates a plain object from a DocumentDelete message. Also converts values to other types if specified. + * @param message DocumentDelete + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.firestore.v1.DocumentDelete, options?: $protobuf.IConversionOptions): { [k: string]: any }; - /** Represents an Int64Value. */ - class Int64Value implements IInt64Value { + /** + * Converts this DocumentDelete to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; - /** - * Constructs a new Int64Value. - * @param [properties] Properties to set - */ - constructor(properties?: google.protobuf.IInt64Value); + /** + * Gets the default type url for DocumentDelete + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } - /** Int64Value value. */ - public value: (number|string); + /** Properties of a DocumentRemove. */ + interface IDocumentRemove { - /** - * Creates an Int64Value message from a plain object. Also converts values to their respective internal types. - * @param object Plain object - * @returns Int64Value - */ - public static fromObject(object: { [k: string]: any }): google.protobuf.Int64Value; + /** DocumentRemove document */ + document?: (string|null); - /** - * Creates a plain object from an Int64Value message. Also converts values to other types if specified. - * @param message Int64Value - * @param [options] Conversion options - * @returns Plain object - */ - public static toObject(message: google.protobuf.Int64Value, options?: $protobuf.IConversionOptions): { [k: string]: any }; + /** DocumentRemove removedTargetIds */ + removedTargetIds?: (number[]|null); - /** - * Converts this Int64Value to JSON. - * @returns JSON object - */ - public toJSON(): { [k: string]: any }; - } + /** DocumentRemove readTime */ + readTime?: (google.protobuf.ITimestamp|null); + } - /** Properties of a UInt64Value. */ - interface IUInt64Value { + /** Represents a DocumentRemove. */ + class DocumentRemove implements IDocumentRemove { - /** UInt64Value value */ - value?: (number|string|null); - } + /** + * Constructs a new DocumentRemove. + * @param [properties] Properties to set + */ + constructor(properties?: google.firestore.v1.IDocumentRemove); - /** Represents a UInt64Value. */ - class UInt64Value implements IUInt64Value { + /** DocumentRemove document. */ + public document: string; - /** - * Constructs a new UInt64Value. - * @param [properties] Properties to set - */ - constructor(properties?: google.protobuf.IUInt64Value); + /** DocumentRemove removedTargetIds. */ + public removedTargetIds: number[]; - /** UInt64Value value. */ - public value: (number|string); + /** DocumentRemove readTime. */ + public readTime?: (google.protobuf.ITimestamp|null); - /** - * Creates a UInt64Value message from a plain object. Also converts values to their respective internal types. - * @param object Plain object - * @returns UInt64Value - */ - public static fromObject(object: { [k: string]: any }): google.protobuf.UInt64Value; + /** + * Creates a DocumentRemove message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns DocumentRemove + */ + public static fromObject(object: { [k: string]: any }): google.firestore.v1.DocumentRemove; - /** - * Creates a plain object from a UInt64Value message. Also converts values to other types if specified. - * @param message UInt64Value - * @param [options] Conversion options - * @returns Plain object - */ - public static toObject(message: google.protobuf.UInt64Value, options?: $protobuf.IConversionOptions): { [k: string]: any }; + /** + * Creates a plain object from a DocumentRemove message. Also converts values to other types if specified. + * @param message DocumentRemove + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.firestore.v1.DocumentRemove, options?: $protobuf.IConversionOptions): { [k: string]: any }; - /** - * Converts this UInt64Value to JSON. - * @returns JSON object - */ - public toJSON(): { [k: string]: any }; - } + /** + * Converts this DocumentRemove to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; - /** Properties of an Int32Value. */ - interface IInt32Value { + /** + * Gets the default type url for DocumentRemove + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } - /** Int32Value value */ - value?: (number|null); - } + /** Properties of an ExistenceFilter. */ + interface IExistenceFilter { - /** Represents an Int32Value. */ - class Int32Value implements IInt32Value { + /** ExistenceFilter targetId */ + targetId?: (number|null); - /** - * Constructs a new Int32Value. - * @param [properties] Properties to set - */ - constructor(properties?: google.protobuf.IInt32Value); + /** ExistenceFilter count */ + count?: (number|null); - /** Int32Value value. */ - public value: number; + /** ExistenceFilter unchangedNames */ + unchangedNames?: (google.firestore.v1.IBloomFilter|null); + } - /** - * Creates an Int32Value message from a plain object. Also converts values to their respective internal types. - * @param object Plain object - * @returns Int32Value - */ - public static fromObject(object: { [k: string]: any }): google.protobuf.Int32Value; + /** Represents an ExistenceFilter. */ + class ExistenceFilter implements IExistenceFilter { - /** - * Creates a plain object from an Int32Value message. Also converts values to other types if specified. - * @param message Int32Value - * @param [options] Conversion options - * @returns Plain object - */ - public static toObject(message: google.protobuf.Int32Value, options?: $protobuf.IConversionOptions): { [k: string]: any }; + /** + * Constructs a new ExistenceFilter. + * @param [properties] Properties to set + */ + constructor(properties?: google.firestore.v1.IExistenceFilter); - /** - * Converts this Int32Value to JSON. - * @returns JSON object - */ - public toJSON(): { [k: string]: any }; - } + /** ExistenceFilter targetId. */ + public targetId: number; - /** Properties of a UInt32Value. */ - interface IUInt32Value { + /** ExistenceFilter count. */ + public count: number; - /** UInt32Value value */ - value?: (number|null); - } + /** ExistenceFilter unchangedNames. */ + public unchangedNames?: (google.firestore.v1.IBloomFilter|null); - /** Represents a UInt32Value. */ - class UInt32Value implements IUInt32Value { + /** + * Creates an ExistenceFilter message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns ExistenceFilter + */ + public static fromObject(object: { [k: string]: any }): google.firestore.v1.ExistenceFilter; - /** - * Constructs a new UInt32Value. - * @param [properties] Properties to set - */ - constructor(properties?: google.protobuf.IUInt32Value); + /** + * Creates a plain object from an ExistenceFilter message. Also converts values to other types if specified. + * @param message ExistenceFilter + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.firestore.v1.ExistenceFilter, options?: $protobuf.IConversionOptions): { [k: string]: any }; - /** UInt32Value value. */ - public value: number; + /** + * Converts this ExistenceFilter to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; - /** - * Creates a UInt32Value message from a plain object. Also converts values to their respective internal types. - * @param object Plain object - * @returns UInt32Value - */ - public static fromObject(object: { [k: string]: any }): google.protobuf.UInt32Value; + /** + * Gets the default type url for ExistenceFilter + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + } + } - /** - * Creates a plain object from a UInt32Value message. Also converts values to other types if specified. - * @param message UInt32Value - * @param [options] Conversion options - * @returns Plain object - */ - public static toObject(message: google.protobuf.UInt32Value, options?: $protobuf.IConversionOptions): { [k: string]: any }; + /** Namespace api. */ + namespace api { - /** - * Converts this UInt32Value to JSON. - * @returns JSON object - */ - public toJSON(): { [k: string]: any }; - } + /** FieldBehavior enum. */ + type FieldBehavior = + "FIELD_BEHAVIOR_UNSPECIFIED"| "OPTIONAL"| "REQUIRED"| "OUTPUT_ONLY"| "INPUT_ONLY"| "IMMUTABLE"| "UNORDERED_LIST"| "NON_EMPTY_DEFAULT"| "IDENTIFIER"; - /** Properties of a BoolValue. */ - interface IBoolValue { + /** Properties of a Http. */ + interface IHttp { - /** BoolValue value */ - value?: (boolean|null); + /** Http rules */ + rules?: (google.api.IHttpRule[]|null); + + /** Http fullyDecodeReservedExpansion */ + fullyDecodeReservedExpansion?: (boolean|null); } - /** Represents a BoolValue. */ - class BoolValue implements IBoolValue { + /** Represents a Http. */ + class Http implements IHttp { /** - * Constructs a new BoolValue. + * Constructs a new Http. * @param [properties] Properties to set */ - constructor(properties?: google.protobuf.IBoolValue); + constructor(properties?: google.api.IHttp); - /** BoolValue value. */ - public value: boolean; + /** Http rules. */ + public rules: google.api.IHttpRule[]; + + /** Http fullyDecodeReservedExpansion. */ + public fullyDecodeReservedExpansion: boolean; /** - * Creates a BoolValue message from a plain object. Also converts values to their respective internal types. + * Creates a Http message from a plain object. Also converts values to their respective internal types. * @param object Plain object - * @returns BoolValue + * @returns Http */ - public static fromObject(object: { [k: string]: any }): google.protobuf.BoolValue; + public static fromObject(object: { [k: string]: any }): google.api.Http; /** - * Creates a plain object from a BoolValue message. Also converts values to other types if specified. - * @param message BoolValue + * Creates a plain object from a Http message. Also converts values to other types if specified. + * @param message Http * @param [options] Conversion options * @returns Plain object */ - public static toObject(message: google.protobuf.BoolValue, options?: $protobuf.IConversionOptions): { [k: string]: any }; + public static toObject(message: google.api.Http, options?: $protobuf.IConversionOptions): { [k: string]: any }; /** - * Converts this BoolValue to JSON. + * Converts this Http to JSON. * @returns JSON object */ public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for Http + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; } - /** Properties of a StringValue. */ - interface IStringValue { + /** Properties of a HttpRule. */ + interface IHttpRule { - /** StringValue value */ - value?: (string|null); - } + /** HttpRule selector */ + selector?: (string|null); - /** Represents a StringValue. */ - class StringValue implements IStringValue { + /** HttpRule get */ + get?: (string|null); - /** - * Constructs a new StringValue. - * @param [properties] Properties to set - */ - constructor(properties?: google.protobuf.IStringValue); + /** HttpRule put */ + put?: (string|null); - /** StringValue value. */ - public value: string; + /** HttpRule post */ + post?: (string|null); - /** - * Creates a StringValue message from a plain object. Also converts values to their respective internal types. - * @param object Plain object - * @returns StringValue - */ - public static fromObject(object: { [k: string]: any }): google.protobuf.StringValue; + /** HttpRule delete */ + "delete"?: (string|null); - /** - * Creates a plain object from a StringValue message. Also converts values to other types if specified. - * @param message StringValue - * @param [options] Conversion options - * @returns Plain object - */ - public static toObject(message: google.protobuf.StringValue, options?: $protobuf.IConversionOptions): { [k: string]: any }; + /** HttpRule patch */ + patch?: (string|null); - /** - * Converts this StringValue to JSON. - * @returns JSON object - */ - public toJSON(): { [k: string]: any }; - } + /** HttpRule custom */ + custom?: (google.api.ICustomHttpPattern|null); - /** Properties of a BytesValue. */ - interface IBytesValue { + /** HttpRule body */ + body?: (string|null); - /** BytesValue value */ - value?: (Uint8Array|null); + /** HttpRule responseBody */ + responseBody?: (string|null); + + /** HttpRule additionalBindings */ + additionalBindings?: (google.api.IHttpRule[]|null); } - /** Represents a BytesValue. */ - class BytesValue implements IBytesValue { + /** Represents a HttpRule. */ + class HttpRule implements IHttpRule { /** - * Constructs a new BytesValue. + * Constructs a new HttpRule. * @param [properties] Properties to set */ - constructor(properties?: google.protobuf.IBytesValue); + constructor(properties?: google.api.IHttpRule); - /** BytesValue value. */ - public value: Uint8Array; + /** HttpRule selector. */ + public selector: string; - /** - * Creates a BytesValue message from a plain object. Also converts values to their respective internal types. - * @param object Plain object - * @returns BytesValue - */ - public static fromObject(object: { [k: string]: any }): google.protobuf.BytesValue; + /** HttpRule get. */ + public get?: (string|null); - /** - * Creates a plain object from a BytesValue message. Also converts values to other types if specified. - * @param message BytesValue - * @param [options] Conversion options - * @returns Plain object - */ - public static toObject(message: google.protobuf.BytesValue, options?: $protobuf.IConversionOptions): { [k: string]: any }; + /** HttpRule put. */ + public put?: (string|null); - /** - * Converts this BytesValue to JSON. - * @returns JSON object - */ - public toJSON(): { [k: string]: any }; - } + /** HttpRule post. */ + public post?: (string|null); - /** Properties of an Any. */ - interface IAny { + /** HttpRule delete. */ + public delete?: (string|null); - /** Any type_url */ - type_url?: (string|null); + /** HttpRule patch. */ + public patch?: (string|null); - /** Any value */ - value?: (Uint8Array|null); - } + /** HttpRule custom. */ + public custom?: (google.api.ICustomHttpPattern|null); - /** Represents an Any. */ - class Any implements IAny { + /** HttpRule body. */ + public body: string; - /** - * Constructs a new Any. - * @param [properties] Properties to set - */ - constructor(properties?: google.protobuf.IAny); + /** HttpRule responseBody. */ + public responseBody: string; - /** Any type_url. */ - public type_url: string; + /** HttpRule additionalBindings. */ + public additionalBindings: google.api.IHttpRule[]; - /** Any value. */ - public value: Uint8Array; + /** HttpRule pattern. */ + public pattern?: ("get"|"put"|"post"|"delete"|"patch"|"custom"); /** - * Creates an Any message from a plain object. Also converts values to their respective internal types. + * Creates a HttpRule message from a plain object. Also converts values to their respective internal types. * @param object Plain object - * @returns Any + * @returns HttpRule */ - public static fromObject(object: { [k: string]: any }): google.protobuf.Any; + public static fromObject(object: { [k: string]: any }): google.api.HttpRule; /** - * Creates a plain object from an Any message. Also converts values to other types if specified. - * @param message Any + * Creates a plain object from a HttpRule message. Also converts values to other types if specified. + * @param message HttpRule * @param [options] Conversion options * @returns Plain object */ - public static toObject(message: google.protobuf.Any, options?: $protobuf.IConversionOptions): { [k: string]: any }; + public static toObject(message: google.api.HttpRule, options?: $protobuf.IConversionOptions): { [k: string]: any }; /** - * Converts this Any to JSON. + * Converts this HttpRule to JSON. * @returns JSON object */ public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for HttpRule + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; } - /** Properties of a FieldMask. */ - interface IFieldMask { + /** Properties of a CustomHttpPattern. */ + interface ICustomHttpPattern { - /** FieldMask paths */ - paths?: (string[]|null); + /** CustomHttpPattern kind */ + kind?: (string|null); + + /** CustomHttpPattern path */ + path?: (string|null); } - /** Represents a FieldMask. */ - class FieldMask implements IFieldMask { + /** Represents a CustomHttpPattern. */ + class CustomHttpPattern implements ICustomHttpPattern { /** - * Constructs a new FieldMask. + * Constructs a new CustomHttpPattern. * @param [properties] Properties to set */ - constructor(properties?: google.protobuf.IFieldMask); + constructor(properties?: google.api.ICustomHttpPattern); - /** FieldMask paths. */ - public paths: string[]; + /** CustomHttpPattern kind. */ + public kind: string; + + /** CustomHttpPattern path. */ + public path: string; /** - * Creates a FieldMask message from a plain object. Also converts values to their respective internal types. + * Creates a CustomHttpPattern message from a plain object. Also converts values to their respective internal types. * @param object Plain object - * @returns FieldMask + * @returns CustomHttpPattern */ - public static fromObject(object: { [k: string]: any }): google.protobuf.FieldMask; + public static fromObject(object: { [k: string]: any }): google.api.CustomHttpPattern; /** - * Creates a plain object from a FieldMask message. Also converts values to other types if specified. - * @param message FieldMask + * Creates a plain object from a CustomHttpPattern message. Also converts values to other types if specified. + * @param message CustomHttpPattern * @param [options] Conversion options * @returns Plain object */ - public static toObject(message: google.protobuf.FieldMask, options?: $protobuf.IConversionOptions): { [k: string]: any }; + public static toObject(message: google.api.CustomHttpPattern, options?: $protobuf.IConversionOptions): { [k: string]: any }; /** - * Converts this FieldMask to JSON. + * Converts this CustomHttpPattern to JSON. * @returns JSON object */ public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for CustomHttpPattern + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; } - /** Properties of a Duration. */ - interface IDuration { + /** Properties of a CommonLanguageSettings. */ + interface ICommonLanguageSettings { - /** Duration seconds */ - seconds?: (number|string|null); + /** CommonLanguageSettings referenceDocsUri */ + referenceDocsUri?: (string|null); - /** Duration nanos */ - nanos?: (number|null); + /** CommonLanguageSettings destinations */ + destinations?: (google.api.ClientLibraryDestination[]|null); } - /** Represents a Duration. */ - class Duration implements IDuration { + /** Represents a CommonLanguageSettings. */ + class CommonLanguageSettings implements ICommonLanguageSettings { /** - * Constructs a new Duration. + * Constructs a new CommonLanguageSettings. * @param [properties] Properties to set */ - constructor(properties?: google.protobuf.IDuration); + constructor(properties?: google.api.ICommonLanguageSettings); - /** Duration seconds. */ - public seconds: (number|string); + /** CommonLanguageSettings referenceDocsUri. */ + public referenceDocsUri: string; - /** Duration nanos. */ - public nanos: number; + /** CommonLanguageSettings destinations. */ + public destinations: google.api.ClientLibraryDestination[]; /** - * Creates a Duration message from a plain object. Also converts values to their respective internal types. + * Creates a CommonLanguageSettings message from a plain object. Also converts values to their respective internal types. * @param object Plain object - * @returns Duration + * @returns CommonLanguageSettings */ - public static fromObject(object: { [k: string]: any }): google.protobuf.Duration; + public static fromObject(object: { [k: string]: any }): google.api.CommonLanguageSettings; /** - * Creates a plain object from a Duration message. Also converts values to other types if specified. - * @param message Duration + * Creates a plain object from a CommonLanguageSettings message. Also converts values to other types if specified. + * @param message CommonLanguageSettings * @param [options] Conversion options * @returns Plain object */ - public static toObject(message: google.protobuf.Duration, options?: $protobuf.IConversionOptions): { [k: string]: any }; + public static toObject(message: google.api.CommonLanguageSettings, options?: $protobuf.IConversionOptions): { [k: string]: any }; /** - * Converts this Duration to JSON. + * Converts this CommonLanguageSettings to JSON. * @returns JSON object */ public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for CommonLanguageSettings + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; } - } - /** Namespace firestore. */ - namespace firestore { + /** Properties of a ClientLibrarySettings. */ + interface IClientLibrarySettings { - /** Namespace v1. */ - namespace v1 { + /** ClientLibrarySettings version */ + version?: (string|null); - /** Properties of a DocumentMask. */ - interface IDocumentMask { + /** ClientLibrarySettings launchStage */ + launchStage?: (google.api.LaunchStage|null); - /** DocumentMask fieldPaths */ - fieldPaths?: (string[]|null); - } + /** ClientLibrarySettings restNumericEnums */ + restNumericEnums?: (boolean|null); - /** Represents a DocumentMask. */ - class DocumentMask implements IDocumentMask { + /** ClientLibrarySettings javaSettings */ + javaSettings?: (google.api.IJavaSettings|null); - /** - * Constructs a new DocumentMask. - * @param [properties] Properties to set - */ - constructor(properties?: google.firestore.v1.IDocumentMask); + /** ClientLibrarySettings cppSettings */ + cppSettings?: (google.api.ICppSettings|null); - /** DocumentMask fieldPaths. */ - public fieldPaths: string[]; + /** ClientLibrarySettings phpSettings */ + phpSettings?: (google.api.IPhpSettings|null); - /** - * Creates a DocumentMask message from a plain object. Also converts values to their respective internal types. - * @param object Plain object - * @returns DocumentMask - */ - public static fromObject(object: { [k: string]: any }): google.firestore.v1.DocumentMask; + /** ClientLibrarySettings pythonSettings */ + pythonSettings?: (google.api.IPythonSettings|null); - /** - * Creates a plain object from a DocumentMask message. Also converts values to other types if specified. - * @param message DocumentMask - * @param [options] Conversion options - * @returns Plain object - */ - public static toObject(message: google.firestore.v1.DocumentMask, options?: $protobuf.IConversionOptions): { [k: string]: any }; + /** ClientLibrarySettings nodeSettings */ + nodeSettings?: (google.api.INodeSettings|null); - /** - * Converts this DocumentMask to JSON. - * @returns JSON object - */ - public toJSON(): { [k: string]: any }; - } + /** ClientLibrarySettings dotnetSettings */ + dotnetSettings?: (google.api.IDotnetSettings|null); - /** Properties of a Precondition. */ - interface IPrecondition { + /** ClientLibrarySettings rubySettings */ + rubySettings?: (google.api.IRubySettings|null); - /** Precondition exists */ - exists?: (boolean|null); + /** ClientLibrarySettings goSettings */ + goSettings?: (google.api.IGoSettings|null); + } - /** Precondition updateTime */ - updateTime?: (google.protobuf.ITimestamp|null); - } + /** Represents a ClientLibrarySettings. */ + class ClientLibrarySettings implements IClientLibrarySettings { - /** Represents a Precondition. */ - class Precondition implements IPrecondition { + /** + * Constructs a new ClientLibrarySettings. + * @param [properties] Properties to set + */ + constructor(properties?: google.api.IClientLibrarySettings); - /** - * Constructs a new Precondition. - * @param [properties] Properties to set - */ - constructor(properties?: google.firestore.v1.IPrecondition); + /** ClientLibrarySettings version. */ + public version: string; - /** Precondition exists. */ - public exists?: (boolean|null); + /** ClientLibrarySettings launchStage. */ + public launchStage: google.api.LaunchStage; - /** Precondition updateTime. */ - public updateTime?: (google.protobuf.ITimestamp|null); + /** ClientLibrarySettings restNumericEnums. */ + public restNumericEnums: boolean; - /** Precondition conditionType. */ - public conditionType?: ("exists"|"updateTime"); + /** ClientLibrarySettings javaSettings. */ + public javaSettings?: (google.api.IJavaSettings|null); - /** - * Creates a Precondition message from a plain object. Also converts values to their respective internal types. - * @param object Plain object - * @returns Precondition - */ - public static fromObject(object: { [k: string]: any }): google.firestore.v1.Precondition; + /** ClientLibrarySettings cppSettings. */ + public cppSettings?: (google.api.ICppSettings|null); - /** - * Creates a plain object from a Precondition message. Also converts values to other types if specified. - * @param message Precondition - * @param [options] Conversion options - * @returns Plain object - */ - public static toObject(message: google.firestore.v1.Precondition, options?: $protobuf.IConversionOptions): { [k: string]: any }; + /** ClientLibrarySettings phpSettings. */ + public phpSettings?: (google.api.IPhpSettings|null); - /** - * Converts this Precondition to JSON. - * @returns JSON object - */ - public toJSON(): { [k: string]: any }; - } + /** ClientLibrarySettings pythonSettings. */ + public pythonSettings?: (google.api.IPythonSettings|null); - /** Properties of a TransactionOptions. */ - interface ITransactionOptions { + /** ClientLibrarySettings nodeSettings. */ + public nodeSettings?: (google.api.INodeSettings|null); - /** TransactionOptions readOnly */ - readOnly?: (google.firestore.v1.TransactionOptions.IReadOnly|null); + /** ClientLibrarySettings dotnetSettings. */ + public dotnetSettings?: (google.api.IDotnetSettings|null); - /** TransactionOptions readWrite */ - readWrite?: (google.firestore.v1.TransactionOptions.IReadWrite|null); - } + /** ClientLibrarySettings rubySettings. */ + public rubySettings?: (google.api.IRubySettings|null); - /** Represents a TransactionOptions. */ - class TransactionOptions implements ITransactionOptions { + /** ClientLibrarySettings goSettings. */ + public goSettings?: (google.api.IGoSettings|null); - /** - * Constructs a new TransactionOptions. - * @param [properties] Properties to set - */ - constructor(properties?: google.firestore.v1.ITransactionOptions); + /** + * Creates a ClientLibrarySettings message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns ClientLibrarySettings + */ + public static fromObject(object: { [k: string]: any }): google.api.ClientLibrarySettings; - /** TransactionOptions readOnly. */ - public readOnly?: (google.firestore.v1.TransactionOptions.IReadOnly|null); + /** + * Creates a plain object from a ClientLibrarySettings message. Also converts values to other types if specified. + * @param message ClientLibrarySettings + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.api.ClientLibrarySettings, options?: $protobuf.IConversionOptions): { [k: string]: any }; - /** TransactionOptions readWrite. */ - public readWrite?: (google.firestore.v1.TransactionOptions.IReadWrite|null); + /** + * Converts this ClientLibrarySettings to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; - /** TransactionOptions mode. */ - public mode?: ("readOnly"|"readWrite"); + /** + * Gets the default type url for ClientLibrarySettings + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } - /** - * Creates a TransactionOptions message from a plain object. Also converts values to their respective internal types. - * @param object Plain object - * @returns TransactionOptions - */ - public static fromObject(object: { [k: string]: any }): google.firestore.v1.TransactionOptions; + /** Properties of a Publishing. */ + interface IPublishing { - /** - * Creates a plain object from a TransactionOptions message. Also converts values to other types if specified. - * @param message TransactionOptions - * @param [options] Conversion options - * @returns Plain object - */ - public static toObject(message: google.firestore.v1.TransactionOptions, options?: $protobuf.IConversionOptions): { [k: string]: any }; + /** Publishing methodSettings */ + methodSettings?: (google.api.IMethodSettings[]|null); - /** - * Converts this TransactionOptions to JSON. - * @returns JSON object - */ - public toJSON(): { [k: string]: any }; - } + /** Publishing newIssueUri */ + newIssueUri?: (string|null); - namespace TransactionOptions { + /** Publishing documentationUri */ + documentationUri?: (string|null); - /** Properties of a ReadWrite. */ - interface IReadWrite { + /** Publishing apiShortName */ + apiShortName?: (string|null); - /** ReadWrite retryTransaction */ - retryTransaction?: (Uint8Array|null); - } + /** Publishing githubLabel */ + githubLabel?: (string|null); - /** Represents a ReadWrite. */ - class ReadWrite implements IReadWrite { + /** Publishing codeownerGithubTeams */ + codeownerGithubTeams?: (string[]|null); - /** - * Constructs a new ReadWrite. - * @param [properties] Properties to set - */ - constructor(properties?: google.firestore.v1.TransactionOptions.IReadWrite); + /** Publishing docTagPrefix */ + docTagPrefix?: (string|null); - /** ReadWrite retryTransaction. */ - public retryTransaction: Uint8Array; + /** Publishing organization */ + organization?: (google.api.ClientLibraryOrganization|null); - /** - * Creates a ReadWrite message from a plain object. Also converts values to their respective internal types. - * @param object Plain object - * @returns ReadWrite - */ - public static fromObject(object: { [k: string]: any }): google.firestore.v1.TransactionOptions.ReadWrite; + /** Publishing librarySettings */ + librarySettings?: (google.api.IClientLibrarySettings[]|null); - /** - * Creates a plain object from a ReadWrite message. Also converts values to other types if specified. - * @param message ReadWrite - * @param [options] Conversion options - * @returns Plain object - */ - public static toObject(message: google.firestore.v1.TransactionOptions.ReadWrite, options?: $protobuf.IConversionOptions): { [k: string]: any }; + /** Publishing protoReferenceDocumentationUri */ + protoReferenceDocumentationUri?: (string|null); - /** - * Converts this ReadWrite to JSON. - * @returns JSON object - */ - public toJSON(): { [k: string]: any }; - } + /** Publishing restReferenceDocumentationUri */ + restReferenceDocumentationUri?: (string|null); + } - /** Properties of a ReadOnly. */ - interface IReadOnly { + /** Represents a Publishing. */ + class Publishing implements IPublishing { - /** ReadOnly readTime */ - readTime?: (google.protobuf.ITimestamp|null); - } + /** + * Constructs a new Publishing. + * @param [properties] Properties to set + */ + constructor(properties?: google.api.IPublishing); - /** Represents a ReadOnly. */ - class ReadOnly implements IReadOnly { + /** Publishing methodSettings. */ + public methodSettings: google.api.IMethodSettings[]; - /** - * Constructs a new ReadOnly. - * @param [properties] Properties to set - */ - constructor(properties?: google.firestore.v1.TransactionOptions.IReadOnly); + /** Publishing newIssueUri. */ + public newIssueUri: string; - /** ReadOnly readTime. */ - public readTime?: (google.protobuf.ITimestamp|null); + /** Publishing documentationUri. */ + public documentationUri: string; - /** ReadOnly consistencySelector. */ - public consistencySelector?: "readTime"; + /** Publishing apiShortName. */ + public apiShortName: string; - /** - * Creates a ReadOnly message from a plain object. Also converts values to their respective internal types. - * @param object Plain object - * @returns ReadOnly - */ - public static fromObject(object: { [k: string]: any }): google.firestore.v1.TransactionOptions.ReadOnly; + /** Publishing githubLabel. */ + public githubLabel: string; - /** - * Creates a plain object from a ReadOnly message. Also converts values to other types if specified. - * @param message ReadOnly - * @param [options] Conversion options - * @returns Plain object - */ - public static toObject(message: google.firestore.v1.TransactionOptions.ReadOnly, options?: $protobuf.IConversionOptions): { [k: string]: any }; + /** Publishing codeownerGithubTeams. */ + public codeownerGithubTeams: string[]; - /** - * Converts this ReadOnly to JSON. - * @returns JSON object - */ - public toJSON(): { [k: string]: any }; - } - } + /** Publishing docTagPrefix. */ + public docTagPrefix: string; - /** Properties of a Document. */ - interface IDocument { + /** Publishing organization. */ + public organization: google.api.ClientLibraryOrganization; - /** Document name */ - name?: (string|null); + /** Publishing librarySettings. */ + public librarySettings: google.api.IClientLibrarySettings[]; - /** Document fields */ - fields?: ({ [k: string]: google.firestore.v1.IValue }|null); + /** Publishing protoReferenceDocumentationUri. */ + public protoReferenceDocumentationUri: string; - /** Document createTime */ - createTime?: (google.protobuf.ITimestamp|null); + /** Publishing restReferenceDocumentationUri. */ + public restReferenceDocumentationUri: string; - /** Document updateTime */ - updateTime?: (google.protobuf.ITimestamp|null); - } + /** + * Creates a Publishing message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns Publishing + */ + public static fromObject(object: { [k: string]: any }): google.api.Publishing; - /** Represents a Document. */ - class Document implements IDocument { + /** + * Creates a plain object from a Publishing message. Also converts values to other types if specified. + * @param message Publishing + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.api.Publishing, options?: $protobuf.IConversionOptions): { [k: string]: any }; - /** - * Constructs a new Document. - * @param [properties] Properties to set - */ - constructor(properties?: google.firestore.v1.IDocument); + /** + * Converts this Publishing to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; - /** Document name. */ - public name: string; + /** + * Gets the default type url for Publishing + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } - /** Document fields. */ - public fields: { [k: string]: google.firestore.v1.IValue }; + /** Properties of a JavaSettings. */ + interface IJavaSettings { - /** Document createTime. */ - public createTime?: (google.protobuf.ITimestamp|null); + /** JavaSettings libraryPackage */ + libraryPackage?: (string|null); - /** Document updateTime. */ - public updateTime?: (google.protobuf.ITimestamp|null); + /** JavaSettings serviceClassNames */ + serviceClassNames?: ({ [k: string]: string }|null); - /** - * Creates a Document message from a plain object. Also converts values to their respective internal types. - * @param object Plain object - * @returns Document - */ - public static fromObject(object: { [k: string]: any }): google.firestore.v1.Document; + /** JavaSettings common */ + common?: (google.api.ICommonLanguageSettings|null); + } - /** - * Creates a plain object from a Document message. Also converts values to other types if specified. - * @param message Document - * @param [options] Conversion options - * @returns Plain object - */ - public static toObject(message: google.firestore.v1.Document, options?: $protobuf.IConversionOptions): { [k: string]: any }; + /** Represents a JavaSettings. */ + class JavaSettings implements IJavaSettings { - /** - * Converts this Document to JSON. - * @returns JSON object - */ - public toJSON(): { [k: string]: any }; - } + /** + * Constructs a new JavaSettings. + * @param [properties] Properties to set + */ + constructor(properties?: google.api.IJavaSettings); - /** Properties of a Value. */ - interface IValue { + /** JavaSettings libraryPackage. */ + public libraryPackage: string; - /** Value nullValue */ - nullValue?: (google.protobuf.NullValue|null); + /** JavaSettings serviceClassNames. */ + public serviceClassNames: { [k: string]: string }; - /** Value booleanValue */ - booleanValue?: (boolean|null); + /** JavaSettings common. */ + public common?: (google.api.ICommonLanguageSettings|null); - /** Value integerValue */ - integerValue?: (number|string|null); + /** + * Creates a JavaSettings message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns JavaSettings + */ + public static fromObject(object: { [k: string]: any }): google.api.JavaSettings; - /** Value doubleValue */ - doubleValue?: (number|null); + /** + * Creates a plain object from a JavaSettings message. Also converts values to other types if specified. + * @param message JavaSettings + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.api.JavaSettings, options?: $protobuf.IConversionOptions): { [k: string]: any }; - /** Value timestampValue */ - timestampValue?: (google.protobuf.ITimestamp|null); + /** + * Converts this JavaSettings to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; - /** Value stringValue */ - stringValue?: (string|null); + /** + * Gets the default type url for JavaSettings + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } - /** Value bytesValue */ - bytesValue?: (Uint8Array|null); + /** Properties of a CppSettings. */ + interface ICppSettings { - /** Value referenceValue */ - referenceValue?: (string|null); + /** CppSettings common */ + common?: (google.api.ICommonLanguageSettings|null); + } - /** Value geoPointValue */ - geoPointValue?: (google.type.ILatLng|null); + /** Represents a CppSettings. */ + class CppSettings implements ICppSettings { - /** Value arrayValue */ - arrayValue?: (google.firestore.v1.IArrayValue|null); + /** + * Constructs a new CppSettings. + * @param [properties] Properties to set + */ + constructor(properties?: google.api.ICppSettings); - /** Value mapValue */ - mapValue?: (google.firestore.v1.IMapValue|null); - } + /** CppSettings common. */ + public common?: (google.api.ICommonLanguageSettings|null); - /** Represents a Value. */ - class Value implements IValue { + /** + * Creates a CppSettings message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns CppSettings + */ + public static fromObject(object: { [k: string]: any }): google.api.CppSettings; - /** - * Constructs a new Value. - * @param [properties] Properties to set - */ - constructor(properties?: google.firestore.v1.IValue); + /** + * Creates a plain object from a CppSettings message. Also converts values to other types if specified. + * @param message CppSettings + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.api.CppSettings, options?: $protobuf.IConversionOptions): { [k: string]: any }; - /** Value nullValue. */ - public nullValue?: (google.protobuf.NullValue|null); + /** + * Converts this CppSettings to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; - /** Value booleanValue. */ - public booleanValue?: (boolean|null); + /** + * Gets the default type url for CppSettings + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } - /** Value integerValue. */ - public integerValue?: (number|string|null); + /** Properties of a PhpSettings. */ + interface IPhpSettings { - /** Value doubleValue. */ - public doubleValue?: (number|null); + /** PhpSettings common */ + common?: (google.api.ICommonLanguageSettings|null); + } - /** Value timestampValue. */ - public timestampValue?: (google.protobuf.ITimestamp|null); + /** Represents a PhpSettings. */ + class PhpSettings implements IPhpSettings { - /** Value stringValue. */ - public stringValue?: (string|null); + /** + * Constructs a new PhpSettings. + * @param [properties] Properties to set + */ + constructor(properties?: google.api.IPhpSettings); - /** Value bytesValue. */ - public bytesValue?: (Uint8Array|null); + /** PhpSettings common. */ + public common?: (google.api.ICommonLanguageSettings|null); - /** Value referenceValue. */ - public referenceValue?: (string|null); + /** + * Creates a PhpSettings message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns PhpSettings + */ + public static fromObject(object: { [k: string]: any }): google.api.PhpSettings; - /** Value geoPointValue. */ - public geoPointValue?: (google.type.ILatLng|null); + /** + * Creates a plain object from a PhpSettings message. Also converts values to other types if specified. + * @param message PhpSettings + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.api.PhpSettings, options?: $protobuf.IConversionOptions): { [k: string]: any }; - /** Value arrayValue. */ - public arrayValue?: (google.firestore.v1.IArrayValue|null); + /** + * Converts this PhpSettings to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; - /** Value mapValue. */ - public mapValue?: (google.firestore.v1.IMapValue|null); + /** + * Gets the default type url for PhpSettings + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } - /** Value valueType. */ - public valueType?: ("nullValue"|"booleanValue"|"integerValue"|"doubleValue"|"timestampValue"|"stringValue"|"bytesValue"|"referenceValue"|"geoPointValue"|"arrayValue"|"mapValue"); + /** Properties of a PythonSettings. */ + interface IPythonSettings { - /** - * Creates a Value message from a plain object. Also converts values to their respective internal types. - * @param object Plain object - * @returns Value - */ - public static fromObject(object: { [k: string]: any }): google.firestore.v1.Value; + /** PythonSettings common */ + common?: (google.api.ICommonLanguageSettings|null); + } - /** - * Creates a plain object from a Value message. Also converts values to other types if specified. - * @param message Value - * @param [options] Conversion options - * @returns Plain object - */ - public static toObject(message: google.firestore.v1.Value, options?: $protobuf.IConversionOptions): { [k: string]: any }; + /** Represents a PythonSettings. */ + class PythonSettings implements IPythonSettings { - /** - * Converts this Value to JSON. - * @returns JSON object - */ - public toJSON(): { [k: string]: any }; - } + /** + * Constructs a new PythonSettings. + * @param [properties] Properties to set + */ + constructor(properties?: google.api.IPythonSettings); - /** Properties of an ArrayValue. */ - interface IArrayValue { + /** PythonSettings common. */ + public common?: (google.api.ICommonLanguageSettings|null); - /** ArrayValue values */ - values?: (google.firestore.v1.IValue[]|null); - } + /** + * Creates a PythonSettings message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns PythonSettings + */ + public static fromObject(object: { [k: string]: any }): google.api.PythonSettings; - /** Represents an ArrayValue. */ - class ArrayValue implements IArrayValue { + /** + * Creates a plain object from a PythonSettings message. Also converts values to other types if specified. + * @param message PythonSettings + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.api.PythonSettings, options?: $protobuf.IConversionOptions): { [k: string]: any }; - /** - * Constructs a new ArrayValue. - * @param [properties] Properties to set - */ - constructor(properties?: google.firestore.v1.IArrayValue); + /** + * Converts this PythonSettings to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; - /** ArrayValue values. */ - public values: google.firestore.v1.IValue[]; + /** + * Gets the default type url for PythonSettings + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } - /** - * Creates an ArrayValue message from a plain object. Also converts values to their respective internal types. - * @param object Plain object - * @returns ArrayValue - */ - public static fromObject(object: { [k: string]: any }): google.firestore.v1.ArrayValue; + /** Properties of a NodeSettings. */ + interface INodeSettings { - /** - * Creates a plain object from an ArrayValue message. Also converts values to other types if specified. - * @param message ArrayValue - * @param [options] Conversion options - * @returns Plain object - */ - public static toObject(message: google.firestore.v1.ArrayValue, options?: $protobuf.IConversionOptions): { [k: string]: any }; + /** NodeSettings common */ + common?: (google.api.ICommonLanguageSettings|null); + } - /** - * Converts this ArrayValue to JSON. - * @returns JSON object - */ - public toJSON(): { [k: string]: any }; - } + /** Represents a NodeSettings. */ + class NodeSettings implements INodeSettings { - /** Properties of a MapValue. */ - interface IMapValue { + /** + * Constructs a new NodeSettings. + * @param [properties] Properties to set + */ + constructor(properties?: google.api.INodeSettings); - /** MapValue fields */ - fields?: ({ [k: string]: google.firestore.v1.IValue }|null); - } + /** NodeSettings common. */ + public common?: (google.api.ICommonLanguageSettings|null); - /** Represents a MapValue. */ - class MapValue implements IMapValue { + /** + * Creates a NodeSettings message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns NodeSettings + */ + public static fromObject(object: { [k: string]: any }): google.api.NodeSettings; - /** - * Constructs a new MapValue. - * @param [properties] Properties to set - */ - constructor(properties?: google.firestore.v1.IMapValue); + /** + * Creates a plain object from a NodeSettings message. Also converts values to other types if specified. + * @param message NodeSettings + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.api.NodeSettings, options?: $protobuf.IConversionOptions): { [k: string]: any }; - /** MapValue fields. */ - public fields: { [k: string]: google.firestore.v1.IValue }; + /** + * Converts this NodeSettings to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; - /** - * Creates a MapValue message from a plain object. Also converts values to their respective internal types. - * @param object Plain object - * @returns MapValue - */ - public static fromObject(object: { [k: string]: any }): google.firestore.v1.MapValue; + /** + * Gets the default type url for NodeSettings + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } - /** - * Creates a plain object from a MapValue message. Also converts values to other types if specified. - * @param message MapValue - * @param [options] Conversion options - * @returns Plain object - */ - public static toObject(message: google.firestore.v1.MapValue, options?: $protobuf.IConversionOptions): { [k: string]: any }; + /** Properties of a DotnetSettings. */ + interface IDotnetSettings { - /** - * Converts this MapValue to JSON. - * @returns JSON object - */ - public toJSON(): { [k: string]: any }; - } + /** DotnetSettings common */ + common?: (google.api.ICommonLanguageSettings|null); - /** Represents a Firestore */ - class Firestore extends $protobuf.rpc.Service { + /** DotnetSettings renamedServices */ + renamedServices?: ({ [k: string]: string }|null); - /** - * Constructs a new Firestore service. - * @param rpcImpl RPC implementation - * @param [requestDelimited=false] Whether requests are length-delimited - * @param [responseDelimited=false] Whether responses are length-delimited - */ - constructor(rpcImpl: $protobuf.RPCImpl, requestDelimited?: boolean, responseDelimited?: boolean); + /** DotnetSettings renamedResources */ + renamedResources?: ({ [k: string]: string }|null); - /** - * Calls GetDocument. - * @param request GetDocumentRequest message or plain object - * @param callback Node-style callback called with the error, if any, and Document - */ - public getDocument(request: google.firestore.v1.IGetDocumentRequest, callback: google.firestore.v1.Firestore.GetDocumentCallback): void; + /** DotnetSettings ignoredResources */ + ignoredResources?: (string[]|null); - /** - * Calls GetDocument. - * @param request GetDocumentRequest message or plain object - * @returns Promise - */ - public getDocument(request: google.firestore.v1.IGetDocumentRequest): Promise; + /** DotnetSettings forcedNamespaceAliases */ + forcedNamespaceAliases?: (string[]|null); - /** - * Calls ListDocuments. - * @param request ListDocumentsRequest message or plain object - * @param callback Node-style callback called with the error, if any, and ListDocumentsResponse - */ - public listDocuments(request: google.firestore.v1.IListDocumentsRequest, callback: google.firestore.v1.Firestore.ListDocumentsCallback): void; + /** DotnetSettings handwrittenSignatures */ + handwrittenSignatures?: (string[]|null); + } - /** - * Calls ListDocuments. - * @param request ListDocumentsRequest message or plain object - * @returns Promise - */ - public listDocuments(request: google.firestore.v1.IListDocumentsRequest): Promise; + /** Represents a DotnetSettings. */ + class DotnetSettings implements IDotnetSettings { - /** - * Calls UpdateDocument. - * @param request UpdateDocumentRequest message or plain object - * @param callback Node-style callback called with the error, if any, and Document - */ - public updateDocument(request: google.firestore.v1.IUpdateDocumentRequest, callback: google.firestore.v1.Firestore.UpdateDocumentCallback): void; + /** + * Constructs a new DotnetSettings. + * @param [properties] Properties to set + */ + constructor(properties?: google.api.IDotnetSettings); - /** - * Calls UpdateDocument. - * @param request UpdateDocumentRequest message or plain object - * @returns Promise - */ - public updateDocument(request: google.firestore.v1.IUpdateDocumentRequest): Promise; + /** DotnetSettings common. */ + public common?: (google.api.ICommonLanguageSettings|null); - /** - * Calls DeleteDocument. - * @param request DeleteDocumentRequest message or plain object - * @param callback Node-style callback called with the error, if any, and Empty - */ - public deleteDocument(request: google.firestore.v1.IDeleteDocumentRequest, callback: google.firestore.v1.Firestore.DeleteDocumentCallback): void; + /** DotnetSettings renamedServices. */ + public renamedServices: { [k: string]: string }; - /** - * Calls DeleteDocument. - * @param request DeleteDocumentRequest message or plain object - * @returns Promise - */ - public deleteDocument(request: google.firestore.v1.IDeleteDocumentRequest): Promise; + /** DotnetSettings renamedResources. */ + public renamedResources: { [k: string]: string }; - /** - * Calls BatchGetDocuments. - * @param request BatchGetDocumentsRequest message or plain object - * @param callback Node-style callback called with the error, if any, and BatchGetDocumentsResponse - */ - public batchGetDocuments(request: google.firestore.v1.IBatchGetDocumentsRequest, callback: google.firestore.v1.Firestore.BatchGetDocumentsCallback): void; + /** DotnetSettings ignoredResources. */ + public ignoredResources: string[]; - /** - * Calls BatchGetDocuments. - * @param request BatchGetDocumentsRequest message or plain object - * @returns Promise - */ - public batchGetDocuments(request: google.firestore.v1.IBatchGetDocumentsRequest): Promise; + /** DotnetSettings forcedNamespaceAliases. */ + public forcedNamespaceAliases: string[]; - /** - * Calls BeginTransaction. - * @param request BeginTransactionRequest message or plain object - * @param callback Node-style callback called with the error, if any, and BeginTransactionResponse - */ - public beginTransaction(request: google.firestore.v1.IBeginTransactionRequest, callback: google.firestore.v1.Firestore.BeginTransactionCallback): void; + /** DotnetSettings handwrittenSignatures. */ + public handwrittenSignatures: string[]; - /** - * Calls BeginTransaction. - * @param request BeginTransactionRequest message or plain object - * @returns Promise - */ - public beginTransaction(request: google.firestore.v1.IBeginTransactionRequest): Promise; + /** + * Creates a DotnetSettings message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns DotnetSettings + */ + public static fromObject(object: { [k: string]: any }): google.api.DotnetSettings; - /** - * Calls Commit. - * @param request CommitRequest message or plain object - * @param callback Node-style callback called with the error, if any, and CommitResponse - */ - public commit(request: google.firestore.v1.ICommitRequest, callback: google.firestore.v1.Firestore.CommitCallback): void; + /** + * Creates a plain object from a DotnetSettings message. Also converts values to other types if specified. + * @param message DotnetSettings + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.api.DotnetSettings, options?: $protobuf.IConversionOptions): { [k: string]: any }; - /** - * Calls Commit. - * @param request CommitRequest message or plain object - * @returns Promise - */ - public commit(request: google.firestore.v1.ICommitRequest): Promise; + /** + * Converts this DotnetSettings to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; - /** - * Calls Rollback. - * @param request RollbackRequest message or plain object - * @param callback Node-style callback called with the error, if any, and Empty - */ - public rollback(request: google.firestore.v1.IRollbackRequest, callback: google.firestore.v1.Firestore.RollbackCallback): void; + /** + * Gets the default type url for DotnetSettings + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } - /** - * Calls Rollback. - * @param request RollbackRequest message or plain object - * @returns Promise - */ - public rollback(request: google.firestore.v1.IRollbackRequest): Promise; + /** Properties of a RubySettings. */ + interface IRubySettings { - /** - * Calls RunQuery. - * @param request RunQueryRequest message or plain object - * @param callback Node-style callback called with the error, if any, and RunQueryResponse - */ - public runQuery(request: google.firestore.v1.IRunQueryRequest, callback: google.firestore.v1.Firestore.RunQueryCallback): void; + /** RubySettings common */ + common?: (google.api.ICommonLanguageSettings|null); + } - /** - * Calls RunQuery. - * @param request RunQueryRequest message or plain object - * @returns Promise - */ - public runQuery(request: google.firestore.v1.IRunQueryRequest): Promise; + /** Represents a RubySettings. */ + class RubySettings implements IRubySettings { - /** - * Calls PartitionQuery. - * @param request PartitionQueryRequest message or plain object - * @param callback Node-style callback called with the error, if any, and PartitionQueryResponse - */ - public partitionQuery(request: google.firestore.v1.IPartitionQueryRequest, callback: google.firestore.v1.Firestore.PartitionQueryCallback): void; + /** + * Constructs a new RubySettings. + * @param [properties] Properties to set + */ + constructor(properties?: google.api.IRubySettings); - /** - * Calls PartitionQuery. - * @param request PartitionQueryRequest message or plain object - * @returns Promise - */ - public partitionQuery(request: google.firestore.v1.IPartitionQueryRequest): Promise; + /** RubySettings common. */ + public common?: (google.api.ICommonLanguageSettings|null); - /** - * Calls Write. - * @param request WriteRequest message or plain object - * @param callback Node-style callback called with the error, if any, and WriteResponse - */ - public write(request: google.firestore.v1.IWriteRequest, callback: google.firestore.v1.Firestore.WriteCallback): void; + /** + * Creates a RubySettings message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns RubySettings + */ + public static fromObject(object: { [k: string]: any }): google.api.RubySettings; - /** - * Calls Write. - * @param request WriteRequest message or plain object - * @returns Promise - */ - public write(request: google.firestore.v1.IWriteRequest): Promise; + /** + * Creates a plain object from a RubySettings message. Also converts values to other types if specified. + * @param message RubySettings + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.api.RubySettings, options?: $protobuf.IConversionOptions): { [k: string]: any }; - /** - * Calls Listen. - * @param request ListenRequest message or plain object - * @param callback Node-style callback called with the error, if any, and ListenResponse - */ - public listen(request: google.firestore.v1.IListenRequest, callback: google.firestore.v1.Firestore.ListenCallback): void; + /** + * Converts this RubySettings to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; - /** - * Calls Listen. - * @param request ListenRequest message or plain object - * @returns Promise - */ - public listen(request: google.firestore.v1.IListenRequest): Promise; + /** + * Gets the default type url for RubySettings + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } - /** - * Calls ListCollectionIds. - * @param request ListCollectionIdsRequest message or plain object - * @param callback Node-style callback called with the error, if any, and ListCollectionIdsResponse - */ - public listCollectionIds(request: google.firestore.v1.IListCollectionIdsRequest, callback: google.firestore.v1.Firestore.ListCollectionIdsCallback): void; + /** Properties of a GoSettings. */ + interface IGoSettings { - /** - * Calls ListCollectionIds. - * @param request ListCollectionIdsRequest message or plain object - * @returns Promise - */ - public listCollectionIds(request: google.firestore.v1.IListCollectionIdsRequest): Promise; + /** GoSettings common */ + common?: (google.api.ICommonLanguageSettings|null); + } - /** - * Calls BatchWrite. - * @param request BatchWriteRequest message or plain object - * @param callback Node-style callback called with the error, if any, and BatchWriteResponse - */ - public batchWrite(request: google.firestore.v1.IBatchWriteRequest, callback: google.firestore.v1.Firestore.BatchWriteCallback): void; + /** Represents a GoSettings. */ + class GoSettings implements IGoSettings { - /** - * Calls BatchWrite. - * @param request BatchWriteRequest message or plain object - * @returns Promise - */ - public batchWrite(request: google.firestore.v1.IBatchWriteRequest): Promise; + /** + * Constructs a new GoSettings. + * @param [properties] Properties to set + */ + constructor(properties?: google.api.IGoSettings); - /** - * Calls CreateDocument. - * @param request CreateDocumentRequest message or plain object - * @param callback Node-style callback called with the error, if any, and Document - */ - public createDocument(request: google.firestore.v1.ICreateDocumentRequest, callback: google.firestore.v1.Firestore.CreateDocumentCallback): void; + /** GoSettings common. */ + public common?: (google.api.ICommonLanguageSettings|null); - /** - * Calls CreateDocument. - * @param request CreateDocumentRequest message or plain object - * @returns Promise - */ - public createDocument(request: google.firestore.v1.ICreateDocumentRequest): Promise; - } + /** + * Creates a GoSettings message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns GoSettings + */ + public static fromObject(object: { [k: string]: any }): google.api.GoSettings; - namespace Firestore { + /** + * Creates a plain object from a GoSettings message. Also converts values to other types if specified. + * @param message GoSettings + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.api.GoSettings, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this GoSettings to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; - /** - * Callback as used by {@link google.firestore.v1.Firestore#getDocument}. - * @param error Error, if any - * @param [response] Document - */ - type GetDocumentCallback = (error: (Error|null), response?: google.firestore.v1.Document) => void; + /** + * Gets the default type url for GoSettings + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } - /** - * Callback as used by {@link google.firestore.v1.Firestore#listDocuments}. - * @param error Error, if any - * @param [response] ListDocumentsResponse - */ - type ListDocumentsCallback = (error: (Error|null), response?: google.firestore.v1.ListDocumentsResponse) => void; + /** Properties of a MethodSettings. */ + interface IMethodSettings { - /** - * Callback as used by {@link google.firestore.v1.Firestore#updateDocument}. - * @param error Error, if any - * @param [response] Document - */ - type UpdateDocumentCallback = (error: (Error|null), response?: google.firestore.v1.Document) => void; + /** MethodSettings selector */ + selector?: (string|null); - /** - * Callback as used by {@link google.firestore.v1.Firestore#deleteDocument}. - * @param error Error, if any - * @param [response] Empty - */ - type DeleteDocumentCallback = (error: (Error|null), response?: google.protobuf.Empty) => void; + /** MethodSettings longRunning */ + longRunning?: (google.api.MethodSettings.ILongRunning|null); - /** - * Callback as used by {@link google.firestore.v1.Firestore#batchGetDocuments}. - * @param error Error, if any - * @param [response] BatchGetDocumentsResponse - */ - type BatchGetDocumentsCallback = (error: (Error|null), response?: google.firestore.v1.BatchGetDocumentsResponse) => void; + /** MethodSettings autoPopulatedFields */ + autoPopulatedFields?: (string[]|null); + } - /** - * Callback as used by {@link google.firestore.v1.Firestore#beginTransaction}. - * @param error Error, if any - * @param [response] BeginTransactionResponse - */ - type BeginTransactionCallback = (error: (Error|null), response?: google.firestore.v1.BeginTransactionResponse) => void; + /** Represents a MethodSettings. */ + class MethodSettings implements IMethodSettings { - /** - * Callback as used by {@link google.firestore.v1.Firestore#commit}. - * @param error Error, if any - * @param [response] CommitResponse - */ - type CommitCallback = (error: (Error|null), response?: google.firestore.v1.CommitResponse) => void; + /** + * Constructs a new MethodSettings. + * @param [properties] Properties to set + */ + constructor(properties?: google.api.IMethodSettings); - /** - * Callback as used by {@link google.firestore.v1.Firestore#rollback}. - * @param error Error, if any - * @param [response] Empty - */ - type RollbackCallback = (error: (Error|null), response?: google.protobuf.Empty) => void; + /** MethodSettings selector. */ + public selector: string; - /** - * Callback as used by {@link google.firestore.v1.Firestore#runQuery}. - * @param error Error, if any - * @param [response] RunQueryResponse - */ - type RunQueryCallback = (error: (Error|null), response?: google.firestore.v1.RunQueryResponse) => void; + /** MethodSettings longRunning. */ + public longRunning?: (google.api.MethodSettings.ILongRunning|null); - /** - * Callback as used by {@link google.firestore.v1.Firestore#partitionQuery}. - * @param error Error, if any - * @param [response] PartitionQueryResponse - */ - type PartitionQueryCallback = (error: (Error|null), response?: google.firestore.v1.PartitionQueryResponse) => void; + /** MethodSettings autoPopulatedFields. */ + public autoPopulatedFields: string[]; - /** - * Callback as used by {@link google.firestore.v1.Firestore#write}. - * @param error Error, if any - * @param [response] WriteResponse - */ - type WriteCallback = (error: (Error|null), response?: google.firestore.v1.WriteResponse) => void; + /** + * Creates a MethodSettings message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns MethodSettings + */ + public static fromObject(object: { [k: string]: any }): google.api.MethodSettings; - /** - * Callback as used by {@link google.firestore.v1.Firestore#listen}. - * @param error Error, if any - * @param [response] ListenResponse - */ - type ListenCallback = (error: (Error|null), response?: google.firestore.v1.ListenResponse) => void; + /** + * Creates a plain object from a MethodSettings message. Also converts values to other types if specified. + * @param message MethodSettings + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.api.MethodSettings, options?: $protobuf.IConversionOptions): { [k: string]: any }; - /** - * Callback as used by {@link google.firestore.v1.Firestore#listCollectionIds}. - * @param error Error, if any - * @param [response] ListCollectionIdsResponse - */ - type ListCollectionIdsCallback = (error: (Error|null), response?: google.firestore.v1.ListCollectionIdsResponse) => void; + /** + * Converts this MethodSettings to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; - /** - * Callback as used by {@link google.firestore.v1.Firestore#batchWrite}. - * @param error Error, if any - * @param [response] BatchWriteResponse - */ - type BatchWriteCallback = (error: (Error|null), response?: google.firestore.v1.BatchWriteResponse) => void; + /** + * Gets the default type url for MethodSettings + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } - /** - * Callback as used by {@link google.firestore.v1.Firestore#createDocument}. - * @param error Error, if any - * @param [response] Document - */ - type CreateDocumentCallback = (error: (Error|null), response?: google.firestore.v1.Document) => void; - } + namespace MethodSettings { - /** Properties of a GetDocumentRequest. */ - interface IGetDocumentRequest { + /** Properties of a LongRunning. */ + interface ILongRunning { - /** GetDocumentRequest name */ - name?: (string|null); + /** LongRunning initialPollDelay */ + initialPollDelay?: (google.protobuf.IDuration|null); - /** GetDocumentRequest mask */ - mask?: (google.firestore.v1.IDocumentMask|null); + /** LongRunning pollDelayMultiplier */ + pollDelayMultiplier?: (number|null); - /** GetDocumentRequest transaction */ - transaction?: (Uint8Array|null); + /** LongRunning maxPollDelay */ + maxPollDelay?: (google.protobuf.IDuration|null); - /** GetDocumentRequest readTime */ - readTime?: (google.protobuf.ITimestamp|null); + /** LongRunning totalPollTimeout */ + totalPollTimeout?: (google.protobuf.IDuration|null); } - /** Represents a GetDocumentRequest. */ - class GetDocumentRequest implements IGetDocumentRequest { + /** Represents a LongRunning. */ + class LongRunning implements ILongRunning { /** - * Constructs a new GetDocumentRequest. + * Constructs a new LongRunning. * @param [properties] Properties to set */ - constructor(properties?: google.firestore.v1.IGetDocumentRequest); - - /** GetDocumentRequest name. */ - public name: string; + constructor(properties?: google.api.MethodSettings.ILongRunning); - /** GetDocumentRequest mask. */ - public mask?: (google.firestore.v1.IDocumentMask|null); + /** LongRunning initialPollDelay. */ + public initialPollDelay?: (google.protobuf.IDuration|null); - /** GetDocumentRequest transaction. */ - public transaction?: (Uint8Array|null); + /** LongRunning pollDelayMultiplier. */ + public pollDelayMultiplier: number; - /** GetDocumentRequest readTime. */ - public readTime?: (google.protobuf.ITimestamp|null); + /** LongRunning maxPollDelay. */ + public maxPollDelay?: (google.protobuf.IDuration|null); - /** GetDocumentRequest consistencySelector. */ - public consistencySelector?: ("transaction"|"readTime"); + /** LongRunning totalPollTimeout. */ + public totalPollTimeout?: (google.protobuf.IDuration|null); /** - * Creates a GetDocumentRequest message from a plain object. Also converts values to their respective internal types. + * Creates a LongRunning message from a plain object. Also converts values to their respective internal types. * @param object Plain object - * @returns GetDocumentRequest + * @returns LongRunning */ - public static fromObject(object: { [k: string]: any }): google.firestore.v1.GetDocumentRequest; + public static fromObject(object: { [k: string]: any }): google.api.MethodSettings.LongRunning; /** - * Creates a plain object from a GetDocumentRequest message. Also converts values to other types if specified. - * @param message GetDocumentRequest + * Creates a plain object from a LongRunning message. Also converts values to other types if specified. + * @param message LongRunning * @param [options] Conversion options * @returns Plain object */ - public static toObject(message: google.firestore.v1.GetDocumentRequest, options?: $protobuf.IConversionOptions): { [k: string]: any }; + public static toObject(message: google.api.MethodSettings.LongRunning, options?: $protobuf.IConversionOptions): { [k: string]: any }; /** - * Converts this GetDocumentRequest to JSON. + * Converts this LongRunning to JSON. * @returns JSON object */ public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for LongRunning + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; } + } - /** Properties of a ListDocumentsRequest. */ - interface IListDocumentsRequest { + /** ClientLibraryOrganization enum. */ + type ClientLibraryOrganization = + "CLIENT_LIBRARY_ORGANIZATION_UNSPECIFIED"| "CLOUD"| "ADS"| "PHOTOS"| "STREET_VIEW"| "SHOPPING"| "GEO"| "GENERATIVE_AI"; - /** ListDocumentsRequest parent */ - parent?: (string|null); + /** ClientLibraryDestination enum. */ + type ClientLibraryDestination = + "CLIENT_LIBRARY_DESTINATION_UNSPECIFIED"| "GITHUB"| "PACKAGE_MANAGER"; - /** ListDocumentsRequest collectionId */ - collectionId?: (string|null); + /** LaunchStage enum. */ + type LaunchStage = + "LAUNCH_STAGE_UNSPECIFIED"| "UNIMPLEMENTED"| "PRELAUNCH"| "EARLY_ACCESS"| "ALPHA"| "BETA"| "GA"| "DEPRECATED"; - /** ListDocumentsRequest pageSize */ - pageSize?: (number|null); + /** Properties of a ResourceDescriptor. */ + interface IResourceDescriptor { - /** ListDocumentsRequest pageToken */ - pageToken?: (string|null); + /** ResourceDescriptor type */ + type?: (string|null); - /** ListDocumentsRequest orderBy */ - orderBy?: (string|null); + /** ResourceDescriptor pattern */ + pattern?: (string[]|null); - /** ListDocumentsRequest mask */ - mask?: (google.firestore.v1.IDocumentMask|null); + /** ResourceDescriptor nameField */ + nameField?: (string|null); - /** ListDocumentsRequest transaction */ - transaction?: (Uint8Array|null); + /** ResourceDescriptor history */ + history?: (google.api.ResourceDescriptor.History|null); - /** ListDocumentsRequest readTime */ - readTime?: (google.protobuf.ITimestamp|null); + /** ResourceDescriptor plural */ + plural?: (string|null); - /** ListDocumentsRequest showMissing */ - showMissing?: (boolean|null); - } + /** ResourceDescriptor singular */ + singular?: (string|null); - /** Represents a ListDocumentsRequest. */ - class ListDocumentsRequest implements IListDocumentsRequest { + /** ResourceDescriptor style */ + style?: (google.api.ResourceDescriptor.Style[]|null); + } - /** - * Constructs a new ListDocumentsRequest. - * @param [properties] Properties to set - */ - constructor(properties?: google.firestore.v1.IListDocumentsRequest); + /** Represents a ResourceDescriptor. */ + class ResourceDescriptor implements IResourceDescriptor { + + /** + * Constructs a new ResourceDescriptor. + * @param [properties] Properties to set + */ + constructor(properties?: google.api.IResourceDescriptor); + + /** ResourceDescriptor type. */ + public type: string; + + /** ResourceDescriptor pattern. */ + public pattern: string[]; + + /** ResourceDescriptor nameField. */ + public nameField: string; + + /** ResourceDescriptor history. */ + public history: google.api.ResourceDescriptor.History; + + /** ResourceDescriptor plural. */ + public plural: string; + + /** ResourceDescriptor singular. */ + public singular: string; + + /** ResourceDescriptor style. */ + public style: google.api.ResourceDescriptor.Style[]; + + /** + * Creates a ResourceDescriptor message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns ResourceDescriptor + */ + public static fromObject(object: { [k: string]: any }): google.api.ResourceDescriptor; + + /** + * Creates a plain object from a ResourceDescriptor message. Also converts values to other types if specified. + * @param message ResourceDescriptor + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.api.ResourceDescriptor, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this ResourceDescriptor to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for ResourceDescriptor + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + namespace ResourceDescriptor { + + /** History enum. */ + type History = + "HISTORY_UNSPECIFIED"| "ORIGINALLY_SINGLE_PATTERN"| "FUTURE_MULTI_PATTERN"; - /** ListDocumentsRequest parent. */ - public parent: string; + /** Style enum. */ + type Style = + "STYLE_UNSPECIFIED"| "DECLARATIVE_FRIENDLY"; + } - /** ListDocumentsRequest collectionId. */ - public collectionId: string; + /** Properties of a ResourceReference. */ + interface IResourceReference { - /** ListDocumentsRequest pageSize. */ - public pageSize: number; + /** ResourceReference type */ + type?: (string|null); - /** ListDocumentsRequest pageToken. */ - public pageToken: string; + /** ResourceReference childType */ + childType?: (string|null); + } - /** ListDocumentsRequest orderBy. */ - public orderBy: string; + /** Represents a ResourceReference. */ + class ResourceReference implements IResourceReference { - /** ListDocumentsRequest mask. */ - public mask?: (google.firestore.v1.IDocumentMask|null); + /** + * Constructs a new ResourceReference. + * @param [properties] Properties to set + */ + constructor(properties?: google.api.IResourceReference); - /** ListDocumentsRequest transaction. */ - public transaction?: (Uint8Array|null); + /** ResourceReference type. */ + public type: string; - /** ListDocumentsRequest readTime. */ - public readTime?: (google.protobuf.ITimestamp|null); + /** ResourceReference childType. */ + public childType: string; - /** ListDocumentsRequest showMissing. */ - public showMissing: boolean; + /** + * Creates a ResourceReference message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns ResourceReference + */ + public static fromObject(object: { [k: string]: any }): google.api.ResourceReference; - /** ListDocumentsRequest consistencySelector. */ - public consistencySelector?: ("transaction"|"readTime"); + /** + * Creates a plain object from a ResourceReference message. Also converts values to other types if specified. + * @param message ResourceReference + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.api.ResourceReference, options?: $protobuf.IConversionOptions): { [k: string]: any }; - /** - * Creates a ListDocumentsRequest message from a plain object. Also converts values to their respective internal types. - * @param object Plain object - * @returns ListDocumentsRequest - */ - public static fromObject(object: { [k: string]: any }): google.firestore.v1.ListDocumentsRequest; + /** + * Converts this ResourceReference to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; - /** - * Creates a plain object from a ListDocumentsRequest message. Also converts values to other types if specified. - * @param message ListDocumentsRequest - * @param [options] Conversion options - * @returns Plain object - */ - public static toObject(message: google.firestore.v1.ListDocumentsRequest, options?: $protobuf.IConversionOptions): { [k: string]: any }; + /** + * Gets the default type url for ResourceReference + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + } - /** - * Converts this ListDocumentsRequest to JSON. - * @returns JSON object - */ - public toJSON(): { [k: string]: any }; - } + /** Namespace protobuf. */ + namespace protobuf { - /** Properties of a ListDocumentsResponse. */ - interface IListDocumentsResponse { + /** Properties of a FileDescriptorSet. */ + interface IFileDescriptorSet { - /** ListDocumentsResponse documents */ - documents?: (google.firestore.v1.IDocument[]|null); + /** FileDescriptorSet file */ + file?: (google.protobuf.IFileDescriptorProto[]|null); + } - /** ListDocumentsResponse nextPageToken */ - nextPageToken?: (string|null); - } + /** Represents a FileDescriptorSet. */ + class FileDescriptorSet implements IFileDescriptorSet { - /** Represents a ListDocumentsResponse. */ - class ListDocumentsResponse implements IListDocumentsResponse { + /** + * Constructs a new FileDescriptorSet. + * @param [properties] Properties to set + */ + constructor(properties?: google.protobuf.IFileDescriptorSet); - /** - * Constructs a new ListDocumentsResponse. - * @param [properties] Properties to set - */ - constructor(properties?: google.firestore.v1.IListDocumentsResponse); + /** FileDescriptorSet file. */ + public file: google.protobuf.IFileDescriptorProto[]; - /** ListDocumentsResponse documents. */ - public documents: google.firestore.v1.IDocument[]; + /** + * Creates a FileDescriptorSet message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns FileDescriptorSet + */ + public static fromObject(object: { [k: string]: any }): google.protobuf.FileDescriptorSet; - /** ListDocumentsResponse nextPageToken. */ - public nextPageToken: string; + /** + * Creates a plain object from a FileDescriptorSet message. Also converts values to other types if specified. + * @param message FileDescriptorSet + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.protobuf.FileDescriptorSet, options?: $protobuf.IConversionOptions): { [k: string]: any }; - /** - * Creates a ListDocumentsResponse message from a plain object. Also converts values to their respective internal types. - * @param object Plain object - * @returns ListDocumentsResponse - */ - public static fromObject(object: { [k: string]: any }): google.firestore.v1.ListDocumentsResponse; + /** + * Converts this FileDescriptorSet to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; - /** - * Creates a plain object from a ListDocumentsResponse message. Also converts values to other types if specified. - * @param message ListDocumentsResponse - * @param [options] Conversion options - * @returns Plain object - */ - public static toObject(message: google.firestore.v1.ListDocumentsResponse, options?: $protobuf.IConversionOptions): { [k: string]: any }; + /** + * Gets the default type url for FileDescriptorSet + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } - /** - * Converts this ListDocumentsResponse to JSON. - * @returns JSON object - */ - public toJSON(): { [k: string]: any }; - } + /** Edition enum. */ + type Edition = + "EDITION_UNKNOWN"| "EDITION_PROTO2"| "EDITION_PROTO3"| "EDITION_2023"| "EDITION_2024"| "EDITION_1_TEST_ONLY"| "EDITION_2_TEST_ONLY"| "EDITION_99997_TEST_ONLY"| "EDITION_99998_TEST_ONLY"| "EDITION_99999_TEST_ONLY"| "EDITION_MAX"; - /** Properties of a CreateDocumentRequest. */ - interface ICreateDocumentRequest { + /** Properties of a FileDescriptorProto. */ + interface IFileDescriptorProto { - /** CreateDocumentRequest parent */ - parent?: (string|null); + /** FileDescriptorProto name */ + name?: (string|null); - /** CreateDocumentRequest collectionId */ - collectionId?: (string|null); + /** FileDescriptorProto package */ + "package"?: (string|null); - /** CreateDocumentRequest documentId */ - documentId?: (string|null); + /** FileDescriptorProto dependency */ + dependency?: (string[]|null); - /** CreateDocumentRequest document */ - document?: (google.firestore.v1.IDocument|null); + /** FileDescriptorProto publicDependency */ + publicDependency?: (number[]|null); - /** CreateDocumentRequest mask */ - mask?: (google.firestore.v1.IDocumentMask|null); - } + /** FileDescriptorProto weakDependency */ + weakDependency?: (number[]|null); - /** Represents a CreateDocumentRequest. */ - class CreateDocumentRequest implements ICreateDocumentRequest { + /** FileDescriptorProto messageType */ + messageType?: (google.protobuf.IDescriptorProto[]|null); - /** - * Constructs a new CreateDocumentRequest. - * @param [properties] Properties to set - */ - constructor(properties?: google.firestore.v1.ICreateDocumentRequest); + /** FileDescriptorProto enumType */ + enumType?: (google.protobuf.IEnumDescriptorProto[]|null); - /** CreateDocumentRequest parent. */ - public parent: string; + /** FileDescriptorProto service */ + service?: (google.protobuf.IServiceDescriptorProto[]|null); - /** CreateDocumentRequest collectionId. */ - public collectionId: string; + /** FileDescriptorProto extension */ + extension?: (google.protobuf.IFieldDescriptorProto[]|null); - /** CreateDocumentRequest documentId. */ - public documentId: string; + /** FileDescriptorProto options */ + options?: (google.protobuf.IFileOptions|null); - /** CreateDocumentRequest document. */ - public document?: (google.firestore.v1.IDocument|null); + /** FileDescriptorProto sourceCodeInfo */ + sourceCodeInfo?: (google.protobuf.ISourceCodeInfo|null); - /** CreateDocumentRequest mask. */ - public mask?: (google.firestore.v1.IDocumentMask|null); + /** FileDescriptorProto syntax */ + syntax?: (string|null); - /** - * Creates a CreateDocumentRequest message from a plain object. Also converts values to their respective internal types. - * @param object Plain object - * @returns CreateDocumentRequest - */ - public static fromObject(object: { [k: string]: any }): google.firestore.v1.CreateDocumentRequest; + /** FileDescriptorProto edition */ + edition?: (google.protobuf.Edition|null); + } - /** - * Creates a plain object from a CreateDocumentRequest message. Also converts values to other types if specified. - * @param message CreateDocumentRequest - * @param [options] Conversion options - * @returns Plain object - */ - public static toObject(message: google.firestore.v1.CreateDocumentRequest, options?: $protobuf.IConversionOptions): { [k: string]: any }; + /** Represents a FileDescriptorProto. */ + class FileDescriptorProto implements IFileDescriptorProto { - /** - * Converts this CreateDocumentRequest to JSON. - * @returns JSON object - */ - public toJSON(): { [k: string]: any }; - } + /** + * Constructs a new FileDescriptorProto. + * @param [properties] Properties to set + */ + constructor(properties?: google.protobuf.IFileDescriptorProto); - /** Properties of an UpdateDocumentRequest. */ - interface IUpdateDocumentRequest { + /** FileDescriptorProto name. */ + public name: string; - /** UpdateDocumentRequest document */ - document?: (google.firestore.v1.IDocument|null); + /** FileDescriptorProto package. */ + public package: string; - /** UpdateDocumentRequest updateMask */ - updateMask?: (google.firestore.v1.IDocumentMask|null); + /** FileDescriptorProto dependency. */ + public dependency: string[]; - /** UpdateDocumentRequest mask */ - mask?: (google.firestore.v1.IDocumentMask|null); + /** FileDescriptorProto publicDependency. */ + public publicDependency: number[]; - /** UpdateDocumentRequest currentDocument */ - currentDocument?: (google.firestore.v1.IPrecondition|null); - } + /** FileDescriptorProto weakDependency. */ + public weakDependency: number[]; - /** Represents an UpdateDocumentRequest. */ - class UpdateDocumentRequest implements IUpdateDocumentRequest { + /** FileDescriptorProto messageType. */ + public messageType: google.protobuf.IDescriptorProto[]; - /** - * Constructs a new UpdateDocumentRequest. - * @param [properties] Properties to set - */ - constructor(properties?: google.firestore.v1.IUpdateDocumentRequest); + /** FileDescriptorProto enumType. */ + public enumType: google.protobuf.IEnumDescriptorProto[]; - /** UpdateDocumentRequest document. */ - public document?: (google.firestore.v1.IDocument|null); + /** FileDescriptorProto service. */ + public service: google.protobuf.IServiceDescriptorProto[]; - /** UpdateDocumentRequest updateMask. */ - public updateMask?: (google.firestore.v1.IDocumentMask|null); + /** FileDescriptorProto extension. */ + public extension: google.protobuf.IFieldDescriptorProto[]; - /** UpdateDocumentRequest mask. */ - public mask?: (google.firestore.v1.IDocumentMask|null); + /** FileDescriptorProto options. */ + public options?: (google.protobuf.IFileOptions|null); - /** UpdateDocumentRequest currentDocument. */ - public currentDocument?: (google.firestore.v1.IPrecondition|null); + /** FileDescriptorProto sourceCodeInfo. */ + public sourceCodeInfo?: (google.protobuf.ISourceCodeInfo|null); - /** - * Creates an UpdateDocumentRequest message from a plain object. Also converts values to their respective internal types. - * @param object Plain object - * @returns UpdateDocumentRequest - */ - public static fromObject(object: { [k: string]: any }): google.firestore.v1.UpdateDocumentRequest; + /** FileDescriptorProto syntax. */ + public syntax: string; - /** - * Creates a plain object from an UpdateDocumentRequest message. Also converts values to other types if specified. - * @param message UpdateDocumentRequest - * @param [options] Conversion options - * @returns Plain object - */ - public static toObject(message: google.firestore.v1.UpdateDocumentRequest, options?: $protobuf.IConversionOptions): { [k: string]: any }; + /** FileDescriptorProto edition. */ + public edition: google.protobuf.Edition; - /** - * Converts this UpdateDocumentRequest to JSON. - * @returns JSON object - */ - public toJSON(): { [k: string]: any }; - } + /** + * Creates a FileDescriptorProto message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns FileDescriptorProto + */ + public static fromObject(object: { [k: string]: any }): google.protobuf.FileDescriptorProto; - /** Properties of a DeleteDocumentRequest. */ - interface IDeleteDocumentRequest { + /** + * Creates a plain object from a FileDescriptorProto message. Also converts values to other types if specified. + * @param message FileDescriptorProto + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.protobuf.FileDescriptorProto, options?: $protobuf.IConversionOptions): { [k: string]: any }; - /** DeleteDocumentRequest name */ - name?: (string|null); + /** + * Converts this FileDescriptorProto to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; - /** DeleteDocumentRequest currentDocument */ - currentDocument?: (google.firestore.v1.IPrecondition|null); - } + /** + * Gets the default type url for FileDescriptorProto + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } - /** Represents a DeleteDocumentRequest. */ - class DeleteDocumentRequest implements IDeleteDocumentRequest { + /** Properties of a DescriptorProto. */ + interface IDescriptorProto { - /** - * Constructs a new DeleteDocumentRequest. - * @param [properties] Properties to set - */ - constructor(properties?: google.firestore.v1.IDeleteDocumentRequest); + /** DescriptorProto name */ + name?: (string|null); - /** DeleteDocumentRequest name. */ - public name: string; + /** DescriptorProto field */ + field?: (google.protobuf.IFieldDescriptorProto[]|null); - /** DeleteDocumentRequest currentDocument. */ - public currentDocument?: (google.firestore.v1.IPrecondition|null); + /** DescriptorProto extension */ + extension?: (google.protobuf.IFieldDescriptorProto[]|null); - /** - * Creates a DeleteDocumentRequest message from a plain object. Also converts values to their respective internal types. - * @param object Plain object - * @returns DeleteDocumentRequest - */ - public static fromObject(object: { [k: string]: any }): google.firestore.v1.DeleteDocumentRequest; + /** DescriptorProto nestedType */ + nestedType?: (google.protobuf.IDescriptorProto[]|null); - /** - * Creates a plain object from a DeleteDocumentRequest message. Also converts values to other types if specified. - * @param message DeleteDocumentRequest - * @param [options] Conversion options - * @returns Plain object - */ - public static toObject(message: google.firestore.v1.DeleteDocumentRequest, options?: $protobuf.IConversionOptions): { [k: string]: any }; + /** DescriptorProto enumType */ + enumType?: (google.protobuf.IEnumDescriptorProto[]|null); - /** - * Converts this DeleteDocumentRequest to JSON. - * @returns JSON object - */ - public toJSON(): { [k: string]: any }; - } + /** DescriptorProto extensionRange */ + extensionRange?: (google.protobuf.DescriptorProto.IExtensionRange[]|null); - /** Properties of a BatchGetDocumentsRequest. */ - interface IBatchGetDocumentsRequest { + /** DescriptorProto oneofDecl */ + oneofDecl?: (google.protobuf.IOneofDescriptorProto[]|null); - /** BatchGetDocumentsRequest database */ - database?: (string|null); + /** DescriptorProto options */ + options?: (google.protobuf.IMessageOptions|null); - /** BatchGetDocumentsRequest documents */ - documents?: (string[]|null); + /** DescriptorProto reservedRange */ + reservedRange?: (google.protobuf.DescriptorProto.IReservedRange[]|null); - /** BatchGetDocumentsRequest mask */ - mask?: (google.firestore.v1.IDocumentMask|null); + /** DescriptorProto reservedName */ + reservedName?: (string[]|null); + } - /** BatchGetDocumentsRequest transaction */ - transaction?: (Uint8Array|null); + /** Represents a DescriptorProto. */ + class DescriptorProto implements IDescriptorProto { - /** BatchGetDocumentsRequest newTransaction */ - newTransaction?: (google.firestore.v1.ITransactionOptions|null); + /** + * Constructs a new DescriptorProto. + * @param [properties] Properties to set + */ + constructor(properties?: google.protobuf.IDescriptorProto); - /** BatchGetDocumentsRequest readTime */ - readTime?: (google.protobuf.ITimestamp|null); - } + /** DescriptorProto name. */ + public name: string; - /** Represents a BatchGetDocumentsRequest. */ - class BatchGetDocumentsRequest implements IBatchGetDocumentsRequest { + /** DescriptorProto field. */ + public field: google.protobuf.IFieldDescriptorProto[]; - /** - * Constructs a new BatchGetDocumentsRequest. - * @param [properties] Properties to set - */ - constructor(properties?: google.firestore.v1.IBatchGetDocumentsRequest); + /** DescriptorProto extension. */ + public extension: google.protobuf.IFieldDescriptorProto[]; - /** BatchGetDocumentsRequest database. */ - public database: string; + /** DescriptorProto nestedType. */ + public nestedType: google.protobuf.IDescriptorProto[]; - /** BatchGetDocumentsRequest documents. */ - public documents: string[]; + /** DescriptorProto enumType. */ + public enumType: google.protobuf.IEnumDescriptorProto[]; - /** BatchGetDocumentsRequest mask. */ - public mask?: (google.firestore.v1.IDocumentMask|null); + /** DescriptorProto extensionRange. */ + public extensionRange: google.protobuf.DescriptorProto.IExtensionRange[]; - /** BatchGetDocumentsRequest transaction. */ - public transaction?: (Uint8Array|null); + /** DescriptorProto oneofDecl. */ + public oneofDecl: google.protobuf.IOneofDescriptorProto[]; - /** BatchGetDocumentsRequest newTransaction. */ - public newTransaction?: (google.firestore.v1.ITransactionOptions|null); + /** DescriptorProto options. */ + public options?: (google.protobuf.IMessageOptions|null); - /** BatchGetDocumentsRequest readTime. */ - public readTime?: (google.protobuf.ITimestamp|null); + /** DescriptorProto reservedRange. */ + public reservedRange: google.protobuf.DescriptorProto.IReservedRange[]; - /** BatchGetDocumentsRequest consistencySelector. */ - public consistencySelector?: ("transaction"|"newTransaction"|"readTime"); + /** DescriptorProto reservedName. */ + public reservedName: string[]; - /** - * Creates a BatchGetDocumentsRequest message from a plain object. Also converts values to their respective internal types. - * @param object Plain object - * @returns BatchGetDocumentsRequest - */ - public static fromObject(object: { [k: string]: any }): google.firestore.v1.BatchGetDocumentsRequest; + /** + * Creates a DescriptorProto message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns DescriptorProto + */ + public static fromObject(object: { [k: string]: any }): google.protobuf.DescriptorProto; - /** - * Creates a plain object from a BatchGetDocumentsRequest message. Also converts values to other types if specified. - * @param message BatchGetDocumentsRequest - * @param [options] Conversion options - * @returns Plain object - */ - public static toObject(message: google.firestore.v1.BatchGetDocumentsRequest, options?: $protobuf.IConversionOptions): { [k: string]: any }; + /** + * Creates a plain object from a DescriptorProto message. Also converts values to other types if specified. + * @param message DescriptorProto + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.protobuf.DescriptorProto, options?: $protobuf.IConversionOptions): { [k: string]: any }; - /** - * Converts this BatchGetDocumentsRequest to JSON. - * @returns JSON object - */ - public toJSON(): { [k: string]: any }; - } + /** + * Converts this DescriptorProto to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; - /** Properties of a BatchGetDocumentsResponse. */ - interface IBatchGetDocumentsResponse { + /** + * Gets the default type url for DescriptorProto + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } - /** BatchGetDocumentsResponse found */ - found?: (google.firestore.v1.IDocument|null); + namespace DescriptorProto { - /** BatchGetDocumentsResponse missing */ - missing?: (string|null); + /** Properties of an ExtensionRange. */ + interface IExtensionRange { - /** BatchGetDocumentsResponse transaction */ - transaction?: (Uint8Array|null); + /** ExtensionRange start */ + start?: (number|null); - /** BatchGetDocumentsResponse readTime */ - readTime?: (google.protobuf.ITimestamp|null); + /** ExtensionRange end */ + end?: (number|null); + + /** ExtensionRange options */ + options?: (google.protobuf.IExtensionRangeOptions|null); } - /** Represents a BatchGetDocumentsResponse. */ - class BatchGetDocumentsResponse implements IBatchGetDocumentsResponse { + /** Represents an ExtensionRange. */ + class ExtensionRange implements IExtensionRange { /** - * Constructs a new BatchGetDocumentsResponse. + * Constructs a new ExtensionRange. * @param [properties] Properties to set */ - constructor(properties?: google.firestore.v1.IBatchGetDocumentsResponse); - - /** BatchGetDocumentsResponse found. */ - public found?: (google.firestore.v1.IDocument|null); - - /** BatchGetDocumentsResponse missing. */ - public missing?: (string|null); + constructor(properties?: google.protobuf.DescriptorProto.IExtensionRange); - /** BatchGetDocumentsResponse transaction. */ - public transaction: Uint8Array; + /** ExtensionRange start. */ + public start: number; - /** BatchGetDocumentsResponse readTime. */ - public readTime?: (google.protobuf.ITimestamp|null); + /** ExtensionRange end. */ + public end: number; - /** BatchGetDocumentsResponse result. */ - public result?: ("found"|"missing"); + /** ExtensionRange options. */ + public options?: (google.protobuf.IExtensionRangeOptions|null); /** - * Creates a BatchGetDocumentsResponse message from a plain object. Also converts values to their respective internal types. + * Creates an ExtensionRange message from a plain object. Also converts values to their respective internal types. * @param object Plain object - * @returns BatchGetDocumentsResponse + * @returns ExtensionRange */ - public static fromObject(object: { [k: string]: any }): google.firestore.v1.BatchGetDocumentsResponse; + public static fromObject(object: { [k: string]: any }): google.protobuf.DescriptorProto.ExtensionRange; /** - * Creates a plain object from a BatchGetDocumentsResponse message. Also converts values to other types if specified. - * @param message BatchGetDocumentsResponse + * Creates a plain object from an ExtensionRange message. Also converts values to other types if specified. + * @param message ExtensionRange * @param [options] Conversion options * @returns Plain object */ - public static toObject(message: google.firestore.v1.BatchGetDocumentsResponse, options?: $protobuf.IConversionOptions): { [k: string]: any }; + public static toObject(message: google.protobuf.DescriptorProto.ExtensionRange, options?: $protobuf.IConversionOptions): { [k: string]: any }; /** - * Converts this BatchGetDocumentsResponse to JSON. + * Converts this ExtensionRange to JSON. * @returns JSON object */ public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for ExtensionRange + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; } - /** Properties of a BeginTransactionRequest. */ - interface IBeginTransactionRequest { + /** Properties of a ReservedRange. */ + interface IReservedRange { - /** BeginTransactionRequest database */ - database?: (string|null); + /** ReservedRange start */ + start?: (number|null); - /** BeginTransactionRequest options */ - options?: (google.firestore.v1.ITransactionOptions|null); + /** ReservedRange end */ + end?: (number|null); } - /** Represents a BeginTransactionRequest. */ - class BeginTransactionRequest implements IBeginTransactionRequest { + /** Represents a ReservedRange. */ + class ReservedRange implements IReservedRange { /** - * Constructs a new BeginTransactionRequest. + * Constructs a new ReservedRange. * @param [properties] Properties to set */ - constructor(properties?: google.firestore.v1.IBeginTransactionRequest); + constructor(properties?: google.protobuf.DescriptorProto.IReservedRange); - /** BeginTransactionRequest database. */ - public database: string; + /** ReservedRange start. */ + public start: number; - /** BeginTransactionRequest options. */ - public options?: (google.firestore.v1.ITransactionOptions|null); + /** ReservedRange end. */ + public end: number; /** - * Creates a BeginTransactionRequest message from a plain object. Also converts values to their respective internal types. + * Creates a ReservedRange message from a plain object. Also converts values to their respective internal types. * @param object Plain object - * @returns BeginTransactionRequest + * @returns ReservedRange */ - public static fromObject(object: { [k: string]: any }): google.firestore.v1.BeginTransactionRequest; + public static fromObject(object: { [k: string]: any }): google.protobuf.DescriptorProto.ReservedRange; /** - * Creates a plain object from a BeginTransactionRequest message. Also converts values to other types if specified. - * @param message BeginTransactionRequest + * Creates a plain object from a ReservedRange message. Also converts values to other types if specified. + * @param message ReservedRange * @param [options] Conversion options * @returns Plain object */ - public static toObject(message: google.firestore.v1.BeginTransactionRequest, options?: $protobuf.IConversionOptions): { [k: string]: any }; + public static toObject(message: google.protobuf.DescriptorProto.ReservedRange, options?: $protobuf.IConversionOptions): { [k: string]: any }; /** - * Converts this BeginTransactionRequest to JSON. + * Converts this ReservedRange to JSON. * @returns JSON object */ public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for ReservedRange + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; } + } - /** Properties of a BeginTransactionResponse. */ - interface IBeginTransactionResponse { + /** Properties of an ExtensionRangeOptions. */ + interface IExtensionRangeOptions { - /** BeginTransactionResponse transaction */ - transaction?: (Uint8Array|null); - } + /** ExtensionRangeOptions uninterpretedOption */ + uninterpretedOption?: (google.protobuf.IUninterpretedOption[]|null); - /** Represents a BeginTransactionResponse. */ - class BeginTransactionResponse implements IBeginTransactionResponse { + /** ExtensionRangeOptions declaration */ + declaration?: (google.protobuf.ExtensionRangeOptions.IDeclaration[]|null); - /** - * Constructs a new BeginTransactionResponse. - * @param [properties] Properties to set - */ - constructor(properties?: google.firestore.v1.IBeginTransactionResponse); + /** ExtensionRangeOptions features */ + features?: (google.protobuf.IFeatureSet|null); - /** BeginTransactionResponse transaction. */ - public transaction: Uint8Array; + /** ExtensionRangeOptions verification */ + verification?: (google.protobuf.ExtensionRangeOptions.VerificationState|null); + } - /** - * Creates a BeginTransactionResponse message from a plain object. Also converts values to their respective internal types. - * @param object Plain object - * @returns BeginTransactionResponse - */ - public static fromObject(object: { [k: string]: any }): google.firestore.v1.BeginTransactionResponse; + /** Represents an ExtensionRangeOptions. */ + class ExtensionRangeOptions implements IExtensionRangeOptions { - /** - * Creates a plain object from a BeginTransactionResponse message. Also converts values to other types if specified. - * @param message BeginTransactionResponse - * @param [options] Conversion options - * @returns Plain object - */ - public static toObject(message: google.firestore.v1.BeginTransactionResponse, options?: $protobuf.IConversionOptions): { [k: string]: any }; + /** + * Constructs a new ExtensionRangeOptions. + * @param [properties] Properties to set + */ + constructor(properties?: google.protobuf.IExtensionRangeOptions); - /** - * Converts this BeginTransactionResponse to JSON. - * @returns JSON object - */ - public toJSON(): { [k: string]: any }; - } + /** ExtensionRangeOptions uninterpretedOption. */ + public uninterpretedOption: google.protobuf.IUninterpretedOption[]; - /** Properties of a CommitRequest. */ - interface ICommitRequest { + /** ExtensionRangeOptions declaration. */ + public declaration: google.protobuf.ExtensionRangeOptions.IDeclaration[]; - /** CommitRequest database */ - database?: (string|null); + /** ExtensionRangeOptions features. */ + public features?: (google.protobuf.IFeatureSet|null); - /** CommitRequest writes */ - writes?: (google.firestore.v1.IWrite[]|null); + /** ExtensionRangeOptions verification. */ + public verification: google.protobuf.ExtensionRangeOptions.VerificationState; - /** CommitRequest transaction */ - transaction?: (Uint8Array|null); + /** + * Creates an ExtensionRangeOptions message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns ExtensionRangeOptions + */ + public static fromObject(object: { [k: string]: any }): google.protobuf.ExtensionRangeOptions; + + /** + * Creates a plain object from an ExtensionRangeOptions message. Also converts values to other types if specified. + * @param message ExtensionRangeOptions + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.protobuf.ExtensionRangeOptions, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this ExtensionRangeOptions to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for ExtensionRangeOptions + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + namespace ExtensionRangeOptions { + + /** Properties of a Declaration. */ + interface IDeclaration { + + /** Declaration number */ + number?: (number|null); + + /** Declaration fullName */ + fullName?: (string|null); + + /** Declaration type */ + type?: (string|null); + + /** Declaration reserved */ + reserved?: (boolean|null); + + /** Declaration repeated */ + repeated?: (boolean|null); } - /** Represents a CommitRequest. */ - class CommitRequest implements ICommitRequest { + /** Represents a Declaration. */ + class Declaration implements IDeclaration { /** - * Constructs a new CommitRequest. + * Constructs a new Declaration. * @param [properties] Properties to set */ - constructor(properties?: google.firestore.v1.ICommitRequest); + constructor(properties?: google.protobuf.ExtensionRangeOptions.IDeclaration); - /** CommitRequest database. */ - public database: string; + /** Declaration number. */ + public number: number; - /** CommitRequest writes. */ - public writes: google.firestore.v1.IWrite[]; + /** Declaration fullName. */ + public fullName: string; - /** CommitRequest transaction. */ - public transaction: Uint8Array; + /** Declaration type. */ + public type: string; + + /** Declaration reserved. */ + public reserved: boolean; + + /** Declaration repeated. */ + public repeated: boolean; /** - * Creates a CommitRequest message from a plain object. Also converts values to their respective internal types. + * Creates a Declaration message from a plain object. Also converts values to their respective internal types. * @param object Plain object - * @returns CommitRequest + * @returns Declaration */ - public static fromObject(object: { [k: string]: any }): google.firestore.v1.CommitRequest; + public static fromObject(object: { [k: string]: any }): google.protobuf.ExtensionRangeOptions.Declaration; /** - * Creates a plain object from a CommitRequest message. Also converts values to other types if specified. - * @param message CommitRequest + * Creates a plain object from a Declaration message. Also converts values to other types if specified. + * @param message Declaration * @param [options] Conversion options * @returns Plain object */ - public static toObject(message: google.firestore.v1.CommitRequest, options?: $protobuf.IConversionOptions): { [k: string]: any }; + public static toObject(message: google.protobuf.ExtensionRangeOptions.Declaration, options?: $protobuf.IConversionOptions): { [k: string]: any }; /** - * Converts this CommitRequest to JSON. + * Converts this Declaration to JSON. * @returns JSON object */ public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for Declaration + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; } - /** Properties of a CommitResponse. */ - interface ICommitResponse { + /** VerificationState enum. */ + type VerificationState = + "DECLARATION"| "UNVERIFIED"; + } - /** CommitResponse writeResults */ - writeResults?: (google.firestore.v1.IWriteResult[]|null); + /** Properties of a FieldDescriptorProto. */ + interface IFieldDescriptorProto { - /** CommitResponse commitTime */ - commitTime?: (google.protobuf.ITimestamp|null); - } + /** FieldDescriptorProto name */ + name?: (string|null); - /** Represents a CommitResponse. */ - class CommitResponse implements ICommitResponse { + /** FieldDescriptorProto number */ + number?: (number|null); + + /** FieldDescriptorProto label */ + label?: (google.protobuf.FieldDescriptorProto.Label|null); + + /** FieldDescriptorProto type */ + type?: (google.protobuf.FieldDescriptorProto.Type|null); + + /** FieldDescriptorProto typeName */ + typeName?: (string|null); + + /** FieldDescriptorProto extendee */ + extendee?: (string|null); + + /** FieldDescriptorProto defaultValue */ + defaultValue?: (string|null); + + /** FieldDescriptorProto oneofIndex */ + oneofIndex?: (number|null); + + /** FieldDescriptorProto jsonName */ + jsonName?: (string|null); + + /** FieldDescriptorProto options */ + options?: (google.protobuf.IFieldOptions|null); + + /** FieldDescriptorProto proto3Optional */ + proto3Optional?: (boolean|null); + } + + /** Represents a FieldDescriptorProto. */ + class FieldDescriptorProto implements IFieldDescriptorProto { + + /** + * Constructs a new FieldDescriptorProto. + * @param [properties] Properties to set + */ + constructor(properties?: google.protobuf.IFieldDescriptorProto); + + /** FieldDescriptorProto name. */ + public name: string; + + /** FieldDescriptorProto number. */ + public number: number; + + /** FieldDescriptorProto label. */ + public label: google.protobuf.FieldDescriptorProto.Label; + + /** FieldDescriptorProto type. */ + public type: google.protobuf.FieldDescriptorProto.Type; + + /** FieldDescriptorProto typeName. */ + public typeName: string; + + /** FieldDescriptorProto extendee. */ + public extendee: string; + + /** FieldDescriptorProto defaultValue. */ + public defaultValue: string; + + /** FieldDescriptorProto oneofIndex. */ + public oneofIndex: number; - /** - * Constructs a new CommitResponse. - * @param [properties] Properties to set - */ - constructor(properties?: google.firestore.v1.ICommitResponse); + /** FieldDescriptorProto jsonName. */ + public jsonName: string; - /** CommitResponse writeResults. */ - public writeResults: google.firestore.v1.IWriteResult[]; + /** FieldDescriptorProto options. */ + public options?: (google.protobuf.IFieldOptions|null); - /** CommitResponse commitTime. */ - public commitTime?: (google.protobuf.ITimestamp|null); + /** FieldDescriptorProto proto3Optional. */ + public proto3Optional: boolean; - /** - * Creates a CommitResponse message from a plain object. Also converts values to their respective internal types. - * @param object Plain object - * @returns CommitResponse - */ - public static fromObject(object: { [k: string]: any }): google.firestore.v1.CommitResponse; + /** + * Creates a FieldDescriptorProto message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns FieldDescriptorProto + */ + public static fromObject(object: { [k: string]: any }): google.protobuf.FieldDescriptorProto; - /** - * Creates a plain object from a CommitResponse message. Also converts values to other types if specified. - * @param message CommitResponse - * @param [options] Conversion options - * @returns Plain object - */ - public static toObject(message: google.firestore.v1.CommitResponse, options?: $protobuf.IConversionOptions): { [k: string]: any }; + /** + * Creates a plain object from a FieldDescriptorProto message. Also converts values to other types if specified. + * @param message FieldDescriptorProto + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.protobuf.FieldDescriptorProto, options?: $protobuf.IConversionOptions): { [k: string]: any }; - /** - * Converts this CommitResponse to JSON. - * @returns JSON object - */ - public toJSON(): { [k: string]: any }; - } + /** + * Converts this FieldDescriptorProto to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; - /** Properties of a RollbackRequest. */ - interface IRollbackRequest { + /** + * Gets the default type url for FieldDescriptorProto + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } - /** RollbackRequest database */ - database?: (string|null); + namespace FieldDescriptorProto { - /** RollbackRequest transaction */ - transaction?: (Uint8Array|null); - } + /** Type enum. */ + type Type = + "TYPE_DOUBLE"| "TYPE_FLOAT"| "TYPE_INT64"| "TYPE_UINT64"| "TYPE_INT32"| "TYPE_FIXED64"| "TYPE_FIXED32"| "TYPE_BOOL"| "TYPE_STRING"| "TYPE_GROUP"| "TYPE_MESSAGE"| "TYPE_BYTES"| "TYPE_UINT32"| "TYPE_ENUM"| "TYPE_SFIXED32"| "TYPE_SFIXED64"| "TYPE_SINT32"| "TYPE_SINT64"; - /** Represents a RollbackRequest. */ - class RollbackRequest implements IRollbackRequest { + /** Label enum. */ + type Label = + "LABEL_OPTIONAL"| "LABEL_REPEATED"| "LABEL_REQUIRED"; + } - /** - * Constructs a new RollbackRequest. - * @param [properties] Properties to set - */ - constructor(properties?: google.firestore.v1.IRollbackRequest); + /** Properties of an OneofDescriptorProto. */ + interface IOneofDescriptorProto { - /** RollbackRequest database. */ - public database: string; + /** OneofDescriptorProto name */ + name?: (string|null); - /** RollbackRequest transaction. */ - public transaction: Uint8Array; + /** OneofDescriptorProto options */ + options?: (google.protobuf.IOneofOptions|null); + } - /** - * Creates a RollbackRequest message from a plain object. Also converts values to their respective internal types. - * @param object Plain object - * @returns RollbackRequest - */ - public static fromObject(object: { [k: string]: any }): google.firestore.v1.RollbackRequest; + /** Represents an OneofDescriptorProto. */ + class OneofDescriptorProto implements IOneofDescriptorProto { - /** - * Creates a plain object from a RollbackRequest message. Also converts values to other types if specified. - * @param message RollbackRequest - * @param [options] Conversion options - * @returns Plain object - */ - public static toObject(message: google.firestore.v1.RollbackRequest, options?: $protobuf.IConversionOptions): { [k: string]: any }; + /** + * Constructs a new OneofDescriptorProto. + * @param [properties] Properties to set + */ + constructor(properties?: google.protobuf.IOneofDescriptorProto); - /** - * Converts this RollbackRequest to JSON. - * @returns JSON object - */ - public toJSON(): { [k: string]: any }; - } + /** OneofDescriptorProto name. */ + public name: string; - /** Properties of a RunQueryRequest. */ - interface IRunQueryRequest { + /** OneofDescriptorProto options. */ + public options?: (google.protobuf.IOneofOptions|null); - /** RunQueryRequest parent */ - parent?: (string|null); + /** + * Creates an OneofDescriptorProto message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns OneofDescriptorProto + */ + public static fromObject(object: { [k: string]: any }): google.protobuf.OneofDescriptorProto; - /** RunQueryRequest structuredQuery */ - structuredQuery?: (google.firestore.v1.IStructuredQuery|null); + /** + * Creates a plain object from an OneofDescriptorProto message. Also converts values to other types if specified. + * @param message OneofDescriptorProto + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.protobuf.OneofDescriptorProto, options?: $protobuf.IConversionOptions): { [k: string]: any }; - /** RunQueryRequest transaction */ - transaction?: (Uint8Array|null); + /** + * Converts this OneofDescriptorProto to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; - /** RunQueryRequest newTransaction */ - newTransaction?: (google.firestore.v1.ITransactionOptions|null); + /** + * Gets the default type url for OneofDescriptorProto + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } - /** RunQueryRequest readTime */ - readTime?: (google.protobuf.ITimestamp|null); - } + /** Properties of an EnumDescriptorProto. */ + interface IEnumDescriptorProto { - /** Represents a RunQueryRequest. */ - class RunQueryRequest implements IRunQueryRequest { + /** EnumDescriptorProto name */ + name?: (string|null); - /** - * Constructs a new RunQueryRequest. - * @param [properties] Properties to set - */ - constructor(properties?: google.firestore.v1.IRunQueryRequest); + /** EnumDescriptorProto value */ + value?: (google.protobuf.IEnumValueDescriptorProto[]|null); - /** RunQueryRequest parent. */ - public parent: string; + /** EnumDescriptorProto options */ + options?: (google.protobuf.IEnumOptions|null); - /** RunQueryRequest structuredQuery. */ - public structuredQuery?: (google.firestore.v1.IStructuredQuery|null); + /** EnumDescriptorProto reservedRange */ + reservedRange?: (google.protobuf.EnumDescriptorProto.IEnumReservedRange[]|null); - /** RunQueryRequest transaction. */ - public transaction?: (Uint8Array|null); + /** EnumDescriptorProto reservedName */ + reservedName?: (string[]|null); + } - /** RunQueryRequest newTransaction. */ - public newTransaction?: (google.firestore.v1.ITransactionOptions|null); + /** Represents an EnumDescriptorProto. */ + class EnumDescriptorProto implements IEnumDescriptorProto { - /** RunQueryRequest readTime. */ - public readTime?: (google.protobuf.ITimestamp|null); + /** + * Constructs a new EnumDescriptorProto. + * @param [properties] Properties to set + */ + constructor(properties?: google.protobuf.IEnumDescriptorProto); - /** RunQueryRequest queryType. */ - public queryType?: "structuredQuery"; + /** EnumDescriptorProto name. */ + public name: string; - /** RunQueryRequest consistencySelector. */ - public consistencySelector?: ("transaction"|"newTransaction"|"readTime"); + /** EnumDescriptorProto value. */ + public value: google.protobuf.IEnumValueDescriptorProto[]; - /** - * Creates a RunQueryRequest message from a plain object. Also converts values to their respective internal types. - * @param object Plain object - * @returns RunQueryRequest - */ - public static fromObject(object: { [k: string]: any }): google.firestore.v1.RunQueryRequest; + /** EnumDescriptorProto options. */ + public options?: (google.protobuf.IEnumOptions|null); - /** - * Creates a plain object from a RunQueryRequest message. Also converts values to other types if specified. - * @param message RunQueryRequest - * @param [options] Conversion options - * @returns Plain object - */ - public static toObject(message: google.firestore.v1.RunQueryRequest, options?: $protobuf.IConversionOptions): { [k: string]: any }; + /** EnumDescriptorProto reservedRange. */ + public reservedRange: google.protobuf.EnumDescriptorProto.IEnumReservedRange[]; - /** - * Converts this RunQueryRequest to JSON. - * @returns JSON object - */ - public toJSON(): { [k: string]: any }; - } + /** EnumDescriptorProto reservedName. */ + public reservedName: string[]; - /** Properties of a RunQueryResponse. */ - interface IRunQueryResponse { + /** + * Creates an EnumDescriptorProto message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns EnumDescriptorProto + */ + public static fromObject(object: { [k: string]: any }): google.protobuf.EnumDescriptorProto; - /** RunQueryResponse transaction */ - transaction?: (Uint8Array|null); + /** + * Creates a plain object from an EnumDescriptorProto message. Also converts values to other types if specified. + * @param message EnumDescriptorProto + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.protobuf.EnumDescriptorProto, options?: $protobuf.IConversionOptions): { [k: string]: any }; - /** RunQueryResponse document */ - document?: (google.firestore.v1.IDocument|null); + /** + * Converts this EnumDescriptorProto to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; - /** RunQueryResponse readTime */ - readTime?: (google.protobuf.ITimestamp|null); + /** + * Gets the default type url for EnumDescriptorProto + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } - /** RunQueryResponse skippedResults */ - skippedResults?: (number|null); - } + namespace EnumDescriptorProto { - /** Represents a RunQueryResponse. */ - class RunQueryResponse implements IRunQueryResponse { + /** Properties of an EnumReservedRange. */ + interface IEnumReservedRange { - /** - * Constructs a new RunQueryResponse. - * @param [properties] Properties to set - */ - constructor(properties?: google.firestore.v1.IRunQueryResponse); + /** EnumReservedRange start */ + start?: (number|null); + + /** EnumReservedRange end */ + end?: (number|null); + } - /** RunQueryResponse transaction. */ - public transaction: Uint8Array; + /** Represents an EnumReservedRange. */ + class EnumReservedRange implements IEnumReservedRange { - /** RunQueryResponse document. */ - public document?: (google.firestore.v1.IDocument|null); + /** + * Constructs a new EnumReservedRange. + * @param [properties] Properties to set + */ + constructor(properties?: google.protobuf.EnumDescriptorProto.IEnumReservedRange); - /** RunQueryResponse readTime. */ - public readTime?: (google.protobuf.ITimestamp|null); + /** EnumReservedRange start. */ + public start: number; - /** RunQueryResponse skippedResults. */ - public skippedResults: number; + /** EnumReservedRange end. */ + public end: number; /** - * Creates a RunQueryResponse message from a plain object. Also converts values to their respective internal types. + * Creates an EnumReservedRange message from a plain object. Also converts values to their respective internal types. * @param object Plain object - * @returns RunQueryResponse + * @returns EnumReservedRange */ - public static fromObject(object: { [k: string]: any }): google.firestore.v1.RunQueryResponse; + public static fromObject(object: { [k: string]: any }): google.protobuf.EnumDescriptorProto.EnumReservedRange; /** - * Creates a plain object from a RunQueryResponse message. Also converts values to other types if specified. - * @param message RunQueryResponse + * Creates a plain object from an EnumReservedRange message. Also converts values to other types if specified. + * @param message EnumReservedRange * @param [options] Conversion options * @returns Plain object */ - public static toObject(message: google.firestore.v1.RunQueryResponse, options?: $protobuf.IConversionOptions): { [k: string]: any }; + public static toObject(message: google.protobuf.EnumDescriptorProto.EnumReservedRange, options?: $protobuf.IConversionOptions): { [k: string]: any }; /** - * Converts this RunQueryResponse to JSON. + * Converts this EnumReservedRange to JSON. * @returns JSON object */ public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for EnumReservedRange + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; } + } - /** Properties of a PartitionQueryRequest. */ - interface IPartitionQueryRequest { + /** Properties of an EnumValueDescriptorProto. */ + interface IEnumValueDescriptorProto { - /** PartitionQueryRequest parent */ - parent?: (string|null); + /** EnumValueDescriptorProto name */ + name?: (string|null); - /** PartitionQueryRequest structuredQuery */ - structuredQuery?: (google.firestore.v1.IStructuredQuery|null); + /** EnumValueDescriptorProto number */ + number?: (number|null); - /** PartitionQueryRequest partitionCount */ - partitionCount?: (number|string|null); + /** EnumValueDescriptorProto options */ + options?: (google.protobuf.IEnumValueOptions|null); + } - /** PartitionQueryRequest pageToken */ - pageToken?: (string|null); + /** Represents an EnumValueDescriptorProto. */ + class EnumValueDescriptorProto implements IEnumValueDescriptorProto { - /** PartitionQueryRequest pageSize */ - pageSize?: (number|null); - } + /** + * Constructs a new EnumValueDescriptorProto. + * @param [properties] Properties to set + */ + constructor(properties?: google.protobuf.IEnumValueDescriptorProto); - /** Represents a PartitionQueryRequest. */ - class PartitionQueryRequest implements IPartitionQueryRequest { + /** EnumValueDescriptorProto name. */ + public name: string; - /** - * Constructs a new PartitionQueryRequest. - * @param [properties] Properties to set - */ - constructor(properties?: google.firestore.v1.IPartitionQueryRequest); + /** EnumValueDescriptorProto number. */ + public number: number; - /** PartitionQueryRequest parent. */ - public parent: string; + /** EnumValueDescriptorProto options. */ + public options?: (google.protobuf.IEnumValueOptions|null); - /** PartitionQueryRequest structuredQuery. */ - public structuredQuery?: (google.firestore.v1.IStructuredQuery|null); + /** + * Creates an EnumValueDescriptorProto message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns EnumValueDescriptorProto + */ + public static fromObject(object: { [k: string]: any }): google.protobuf.EnumValueDescriptorProto; - /** PartitionQueryRequest partitionCount. */ - public partitionCount: (number|string); + /** + * Creates a plain object from an EnumValueDescriptorProto message. Also converts values to other types if specified. + * @param message EnumValueDescriptorProto + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.protobuf.EnumValueDescriptorProto, options?: $protobuf.IConversionOptions): { [k: string]: any }; - /** PartitionQueryRequest pageToken. */ - public pageToken: string; + /** + * Converts this EnumValueDescriptorProto to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; - /** PartitionQueryRequest pageSize. */ - public pageSize: number; + /** + * Gets the default type url for EnumValueDescriptorProto + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } - /** PartitionQueryRequest queryType. */ - public queryType?: "structuredQuery"; + /** Properties of a ServiceDescriptorProto. */ + interface IServiceDescriptorProto { - /** - * Creates a PartitionQueryRequest message from a plain object. Also converts values to their respective internal types. - * @param object Plain object - * @returns PartitionQueryRequest - */ - public static fromObject(object: { [k: string]: any }): google.firestore.v1.PartitionQueryRequest; + /** ServiceDescriptorProto name */ + name?: (string|null); - /** - * Creates a plain object from a PartitionQueryRequest message. Also converts values to other types if specified. - * @param message PartitionQueryRequest - * @param [options] Conversion options - * @returns Plain object - */ - public static toObject(message: google.firestore.v1.PartitionQueryRequest, options?: $protobuf.IConversionOptions): { [k: string]: any }; + /** ServiceDescriptorProto method */ + method?: (google.protobuf.IMethodDescriptorProto[]|null); - /** - * Converts this PartitionQueryRequest to JSON. - * @returns JSON object - */ - public toJSON(): { [k: string]: any }; - } + /** ServiceDescriptorProto options */ + options?: (google.protobuf.IServiceOptions|null); + } - /** Properties of a PartitionQueryResponse. */ - interface IPartitionQueryResponse { + /** Represents a ServiceDescriptorProto. */ + class ServiceDescriptorProto implements IServiceDescriptorProto { - /** PartitionQueryResponse partitions */ - partitions?: (google.firestore.v1.ICursor[]|null); + /** + * Constructs a new ServiceDescriptorProto. + * @param [properties] Properties to set + */ + constructor(properties?: google.protobuf.IServiceDescriptorProto); - /** PartitionQueryResponse nextPageToken */ - nextPageToken?: (string|null); - } + /** ServiceDescriptorProto name. */ + public name: string; - /** Represents a PartitionQueryResponse. */ - class PartitionQueryResponse implements IPartitionQueryResponse { + /** ServiceDescriptorProto method. */ + public method: google.protobuf.IMethodDescriptorProto[]; - /** - * Constructs a new PartitionQueryResponse. - * @param [properties] Properties to set - */ - constructor(properties?: google.firestore.v1.IPartitionQueryResponse); + /** ServiceDescriptorProto options. */ + public options?: (google.protobuf.IServiceOptions|null); + + /** + * Creates a ServiceDescriptorProto message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns ServiceDescriptorProto + */ + public static fromObject(object: { [k: string]: any }): google.protobuf.ServiceDescriptorProto; + + /** + * Creates a plain object from a ServiceDescriptorProto message. Also converts values to other types if specified. + * @param message ServiceDescriptorProto + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.protobuf.ServiceDescriptorProto, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this ServiceDescriptorProto to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for ServiceDescriptorProto + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a MethodDescriptorProto. */ + interface IMethodDescriptorProto { + + /** MethodDescriptorProto name */ + name?: (string|null); + + /** MethodDescriptorProto inputType */ + inputType?: (string|null); + + /** MethodDescriptorProto outputType */ + outputType?: (string|null); + + /** MethodDescriptorProto options */ + options?: (google.protobuf.IMethodOptions|null); + + /** MethodDescriptorProto clientStreaming */ + clientStreaming?: (boolean|null); + + /** MethodDescriptorProto serverStreaming */ + serverStreaming?: (boolean|null); + } + + /** Represents a MethodDescriptorProto. */ + class MethodDescriptorProto implements IMethodDescriptorProto { + + /** + * Constructs a new MethodDescriptorProto. + * @param [properties] Properties to set + */ + constructor(properties?: google.protobuf.IMethodDescriptorProto); + + /** MethodDescriptorProto name. */ + public name: string; + + /** MethodDescriptorProto inputType. */ + public inputType: string; + + /** MethodDescriptorProto outputType. */ + public outputType: string; + + /** MethodDescriptorProto options. */ + public options?: (google.protobuf.IMethodOptions|null); + + /** MethodDescriptorProto clientStreaming. */ + public clientStreaming: boolean; + + /** MethodDescriptorProto serverStreaming. */ + public serverStreaming: boolean; + + /** + * Creates a MethodDescriptorProto message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns MethodDescriptorProto + */ + public static fromObject(object: { [k: string]: any }): google.protobuf.MethodDescriptorProto; + + /** + * Creates a plain object from a MethodDescriptorProto message. Also converts values to other types if specified. + * @param message MethodDescriptorProto + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.protobuf.MethodDescriptorProto, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this MethodDescriptorProto to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for MethodDescriptorProto + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a FileOptions. */ + interface IFileOptions { - /** PartitionQueryResponse partitions. */ - public partitions: google.firestore.v1.ICursor[]; + /** FileOptions javaPackage */ + javaPackage?: (string|null); - /** PartitionQueryResponse nextPageToken. */ - public nextPageToken: string; + /** FileOptions javaOuterClassname */ + javaOuterClassname?: (string|null); - /** - * Creates a PartitionQueryResponse message from a plain object. Also converts values to their respective internal types. - * @param object Plain object - * @returns PartitionQueryResponse - */ - public static fromObject(object: { [k: string]: any }): google.firestore.v1.PartitionQueryResponse; + /** FileOptions javaMultipleFiles */ + javaMultipleFiles?: (boolean|null); - /** - * Creates a plain object from a PartitionQueryResponse message. Also converts values to other types if specified. - * @param message PartitionQueryResponse - * @param [options] Conversion options - * @returns Plain object - */ - public static toObject(message: google.firestore.v1.PartitionQueryResponse, options?: $protobuf.IConversionOptions): { [k: string]: any }; + /** FileOptions javaGenerateEqualsAndHash */ + javaGenerateEqualsAndHash?: (boolean|null); - /** - * Converts this PartitionQueryResponse to JSON. - * @returns JSON object - */ - public toJSON(): { [k: string]: any }; - } + /** FileOptions javaStringCheckUtf8 */ + javaStringCheckUtf8?: (boolean|null); - /** Properties of a WriteRequest. */ - interface IWriteRequest { + /** FileOptions optimizeFor */ + optimizeFor?: (google.protobuf.FileOptions.OptimizeMode|null); - /** WriteRequest database */ - database?: (string|null); + /** FileOptions goPackage */ + goPackage?: (string|null); - /** WriteRequest streamId */ - streamId?: (string|null); + /** FileOptions ccGenericServices */ + ccGenericServices?: (boolean|null); - /** WriteRequest writes */ - writes?: (google.firestore.v1.IWrite[]|null); + /** FileOptions javaGenericServices */ + javaGenericServices?: (boolean|null); - /** WriteRequest streamToken */ - streamToken?: (Uint8Array|null); + /** FileOptions pyGenericServices */ + pyGenericServices?: (boolean|null); - /** WriteRequest labels */ - labels?: ({ [k: string]: string }|null); - } + /** FileOptions deprecated */ + deprecated?: (boolean|null); - /** Represents a WriteRequest. */ - class WriteRequest implements IWriteRequest { + /** FileOptions ccEnableArenas */ + ccEnableArenas?: (boolean|null); - /** - * Constructs a new WriteRequest. - * @param [properties] Properties to set - */ - constructor(properties?: google.firestore.v1.IWriteRequest); + /** FileOptions objcClassPrefix */ + objcClassPrefix?: (string|null); - /** WriteRequest database. */ - public database: string; + /** FileOptions csharpNamespace */ + csharpNamespace?: (string|null); - /** WriteRequest streamId. */ - public streamId: string; + /** FileOptions swiftPrefix */ + swiftPrefix?: (string|null); - /** WriteRequest writes. */ - public writes: google.firestore.v1.IWrite[]; + /** FileOptions phpClassPrefix */ + phpClassPrefix?: (string|null); - /** WriteRequest streamToken. */ - public streamToken: Uint8Array; + /** FileOptions phpNamespace */ + phpNamespace?: (string|null); - /** WriteRequest labels. */ - public labels: { [k: string]: string }; + /** FileOptions phpMetadataNamespace */ + phpMetadataNamespace?: (string|null); - /** - * Creates a WriteRequest message from a plain object. Also converts values to their respective internal types. - * @param object Plain object - * @returns WriteRequest - */ - public static fromObject(object: { [k: string]: any }): google.firestore.v1.WriteRequest; + /** FileOptions rubyPackage */ + rubyPackage?: (string|null); - /** - * Creates a plain object from a WriteRequest message. Also converts values to other types if specified. - * @param message WriteRequest - * @param [options] Conversion options - * @returns Plain object - */ - public static toObject(message: google.firestore.v1.WriteRequest, options?: $protobuf.IConversionOptions): { [k: string]: any }; + /** FileOptions features */ + features?: (google.protobuf.IFeatureSet|null); - /** - * Converts this WriteRequest to JSON. - * @returns JSON object - */ - public toJSON(): { [k: string]: any }; - } + /** FileOptions uninterpretedOption */ + uninterpretedOption?: (google.protobuf.IUninterpretedOption[]|null); - /** Properties of a WriteResponse. */ - interface IWriteResponse { + /** FileOptions .google.api.resourceDefinition */ + ".google.api.resourceDefinition"?: (google.api.IResourceDescriptor[]|null); + } - /** WriteResponse streamId */ - streamId?: (string|null); + /** Represents a FileOptions. */ + class FileOptions implements IFileOptions { - /** WriteResponse streamToken */ - streamToken?: (Uint8Array|null); + /** + * Constructs a new FileOptions. + * @param [properties] Properties to set + */ + constructor(properties?: google.protobuf.IFileOptions); - /** WriteResponse writeResults */ - writeResults?: (google.firestore.v1.IWriteResult[]|null); + /** FileOptions javaPackage. */ + public javaPackage: string; - /** WriteResponse commitTime */ - commitTime?: (google.protobuf.ITimestamp|null); - } + /** FileOptions javaOuterClassname. */ + public javaOuterClassname: string; - /** Represents a WriteResponse. */ - class WriteResponse implements IWriteResponse { + /** FileOptions javaMultipleFiles. */ + public javaMultipleFiles: boolean; - /** - * Constructs a new WriteResponse. - * @param [properties] Properties to set - */ - constructor(properties?: google.firestore.v1.IWriteResponse); + /** FileOptions javaGenerateEqualsAndHash. */ + public javaGenerateEqualsAndHash: boolean; - /** WriteResponse streamId. */ - public streamId: string; + /** FileOptions javaStringCheckUtf8. */ + public javaStringCheckUtf8: boolean; - /** WriteResponse streamToken. */ - public streamToken: Uint8Array; + /** FileOptions optimizeFor. */ + public optimizeFor: google.protobuf.FileOptions.OptimizeMode; - /** WriteResponse writeResults. */ - public writeResults: google.firestore.v1.IWriteResult[]; + /** FileOptions goPackage. */ + public goPackage: string; - /** WriteResponse commitTime. */ - public commitTime?: (google.protobuf.ITimestamp|null); + /** FileOptions ccGenericServices. */ + public ccGenericServices: boolean; - /** - * Creates a WriteResponse message from a plain object. Also converts values to their respective internal types. - * @param object Plain object - * @returns WriteResponse - */ - public static fromObject(object: { [k: string]: any }): google.firestore.v1.WriteResponse; + /** FileOptions javaGenericServices. */ + public javaGenericServices: boolean; - /** - * Creates a plain object from a WriteResponse message. Also converts values to other types if specified. - * @param message WriteResponse - * @param [options] Conversion options - * @returns Plain object - */ - public static toObject(message: google.firestore.v1.WriteResponse, options?: $protobuf.IConversionOptions): { [k: string]: any }; + /** FileOptions pyGenericServices. */ + public pyGenericServices: boolean; - /** - * Converts this WriteResponse to JSON. - * @returns JSON object - */ - public toJSON(): { [k: string]: any }; - } + /** FileOptions deprecated. */ + public deprecated: boolean; - /** Properties of a ListenRequest. */ - interface IListenRequest { + /** FileOptions ccEnableArenas. */ + public ccEnableArenas: boolean; - /** ListenRequest database */ - database?: (string|null); + /** FileOptions objcClassPrefix. */ + public objcClassPrefix: string; - /** ListenRequest addTarget */ - addTarget?: (google.firestore.v1.ITarget|null); + /** FileOptions csharpNamespace. */ + public csharpNamespace: string; - /** ListenRequest removeTarget */ - removeTarget?: (number|null); + /** FileOptions swiftPrefix. */ + public swiftPrefix: string; - /** ListenRequest labels */ - labels?: ({ [k: string]: string }|null); - } + /** FileOptions phpClassPrefix. */ + public phpClassPrefix: string; - /** Represents a ListenRequest. */ - class ListenRequest implements IListenRequest { + /** FileOptions phpNamespace. */ + public phpNamespace: string; - /** - * Constructs a new ListenRequest. - * @param [properties] Properties to set - */ - constructor(properties?: google.firestore.v1.IListenRequest); + /** FileOptions phpMetadataNamespace. */ + public phpMetadataNamespace: string; - /** ListenRequest database. */ - public database: string; + /** FileOptions rubyPackage. */ + public rubyPackage: string; - /** ListenRequest addTarget. */ - public addTarget?: (google.firestore.v1.ITarget|null); + /** FileOptions features. */ + public features?: (google.protobuf.IFeatureSet|null); - /** ListenRequest removeTarget. */ - public removeTarget?: (number|null); + /** FileOptions uninterpretedOption. */ + public uninterpretedOption: google.protobuf.IUninterpretedOption[]; - /** ListenRequest labels. */ - public labels: { [k: string]: string }; + /** + * Creates a FileOptions message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns FileOptions + */ + public static fromObject(object: { [k: string]: any }): google.protobuf.FileOptions; - /** ListenRequest targetChange. */ - public targetChange?: ("addTarget"|"removeTarget"); + /** + * Creates a plain object from a FileOptions message. Also converts values to other types if specified. + * @param message FileOptions + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.protobuf.FileOptions, options?: $protobuf.IConversionOptions): { [k: string]: any }; - /** - * Creates a ListenRequest message from a plain object. Also converts values to their respective internal types. - * @param object Plain object - * @returns ListenRequest - */ - public static fromObject(object: { [k: string]: any }): google.firestore.v1.ListenRequest; + /** + * Converts this FileOptions to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; - /** - * Creates a plain object from a ListenRequest message. Also converts values to other types if specified. - * @param message ListenRequest - * @param [options] Conversion options - * @returns Plain object - */ - public static toObject(message: google.firestore.v1.ListenRequest, options?: $protobuf.IConversionOptions): { [k: string]: any }; + /** + * Gets the default type url for FileOptions + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + namespace FileOptions { + + /** OptimizeMode enum. */ + type OptimizeMode = + "SPEED"| "CODE_SIZE"| "LITE_RUNTIME"; + } - /** - * Converts this ListenRequest to JSON. - * @returns JSON object - */ - public toJSON(): { [k: string]: any }; - } + /** Properties of a MessageOptions. */ + interface IMessageOptions { - /** Properties of a ListenResponse. */ - interface IListenResponse { + /** MessageOptions messageSetWireFormat */ + messageSetWireFormat?: (boolean|null); - /** ListenResponse targetChange */ - targetChange?: (google.firestore.v1.ITargetChange|null); + /** MessageOptions noStandardDescriptorAccessor */ + noStandardDescriptorAccessor?: (boolean|null); - /** ListenResponse documentChange */ - documentChange?: (google.firestore.v1.IDocumentChange|null); + /** MessageOptions deprecated */ + deprecated?: (boolean|null); - /** ListenResponse documentDelete */ - documentDelete?: (google.firestore.v1.IDocumentDelete|null); + /** MessageOptions mapEntry */ + mapEntry?: (boolean|null); - /** ListenResponse documentRemove */ - documentRemove?: (google.firestore.v1.IDocumentRemove|null); + /** MessageOptions deprecatedLegacyJsonFieldConflicts */ + deprecatedLegacyJsonFieldConflicts?: (boolean|null); - /** ListenResponse filter */ - filter?: (google.firestore.v1.IExistenceFilter|null); - } + /** MessageOptions features */ + features?: (google.protobuf.IFeatureSet|null); - /** Represents a ListenResponse. */ - class ListenResponse implements IListenResponse { + /** MessageOptions uninterpretedOption */ + uninterpretedOption?: (google.protobuf.IUninterpretedOption[]|null); - /** - * Constructs a new ListenResponse. - * @param [properties] Properties to set - */ - constructor(properties?: google.firestore.v1.IListenResponse); + /** MessageOptions .google.api.resource */ + ".google.api.resource"?: (google.api.IResourceDescriptor|null); + } - /** ListenResponse targetChange. */ - public targetChange?: (google.firestore.v1.ITargetChange|null); + /** Represents a MessageOptions. */ + class MessageOptions implements IMessageOptions { - /** ListenResponse documentChange. */ - public documentChange?: (google.firestore.v1.IDocumentChange|null); + /** + * Constructs a new MessageOptions. + * @param [properties] Properties to set + */ + constructor(properties?: google.protobuf.IMessageOptions); - /** ListenResponse documentDelete. */ - public documentDelete?: (google.firestore.v1.IDocumentDelete|null); + /** MessageOptions messageSetWireFormat. */ + public messageSetWireFormat: boolean; - /** ListenResponse documentRemove. */ - public documentRemove?: (google.firestore.v1.IDocumentRemove|null); + /** MessageOptions noStandardDescriptorAccessor. */ + public noStandardDescriptorAccessor: boolean; - /** ListenResponse filter. */ - public filter?: (google.firestore.v1.IExistenceFilter|null); + /** MessageOptions deprecated. */ + public deprecated: boolean; - /** ListenResponse responseType. */ - public responseType?: ("targetChange"|"documentChange"|"documentDelete"|"documentRemove"|"filter"); + /** MessageOptions mapEntry. */ + public mapEntry: boolean; - /** - * Creates a ListenResponse message from a plain object. Also converts values to their respective internal types. - * @param object Plain object - * @returns ListenResponse - */ - public static fromObject(object: { [k: string]: any }): google.firestore.v1.ListenResponse; + /** MessageOptions deprecatedLegacyJsonFieldConflicts. */ + public deprecatedLegacyJsonFieldConflicts: boolean; - /** - * Creates a plain object from a ListenResponse message. Also converts values to other types if specified. - * @param message ListenResponse - * @param [options] Conversion options - * @returns Plain object - */ - public static toObject(message: google.firestore.v1.ListenResponse, options?: $protobuf.IConversionOptions): { [k: string]: any }; + /** MessageOptions features. */ + public features?: (google.protobuf.IFeatureSet|null); - /** - * Converts this ListenResponse to JSON. - * @returns JSON object - */ - public toJSON(): { [k: string]: any }; - } + /** MessageOptions uninterpretedOption. */ + public uninterpretedOption: google.protobuf.IUninterpretedOption[]; - /** Properties of a Target. */ - interface ITarget { + /** + * Creates a MessageOptions message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns MessageOptions + */ + public static fromObject(object: { [k: string]: any }): google.protobuf.MessageOptions; - /** Target query */ - query?: (google.firestore.v1.Target.IQueryTarget|null); + /** + * Creates a plain object from a MessageOptions message. Also converts values to other types if specified. + * @param message MessageOptions + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.protobuf.MessageOptions, options?: $protobuf.IConversionOptions): { [k: string]: any }; - /** Target documents */ - documents?: (google.firestore.v1.Target.IDocumentsTarget|null); + /** + * Converts this MessageOptions to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; - /** Target resumeToken */ - resumeToken?: (Uint8Array|null); + /** + * Gets the default type url for MessageOptions + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } - /** Target readTime */ - readTime?: (google.protobuf.ITimestamp|null); + /** Properties of a FieldOptions. */ + interface IFieldOptions { - /** Target targetId */ - targetId?: (number|null); + /** FieldOptions ctype */ + ctype?: (google.protobuf.FieldOptions.CType|null); - /** Target once */ - once?: (boolean|null); - } + /** FieldOptions packed */ + packed?: (boolean|null); - /** Represents a Target. */ - class Target implements ITarget { + /** FieldOptions jstype */ + jstype?: (google.protobuf.FieldOptions.JSType|null); - /** - * Constructs a new Target. - * @param [properties] Properties to set - */ - constructor(properties?: google.firestore.v1.ITarget); + /** FieldOptions lazy */ + lazy?: (boolean|null); - /** Target query. */ - public query?: (google.firestore.v1.Target.IQueryTarget|null); + /** FieldOptions unverifiedLazy */ + unverifiedLazy?: (boolean|null); - /** Target documents. */ - public documents?: (google.firestore.v1.Target.IDocumentsTarget|null); + /** FieldOptions deprecated */ + deprecated?: (boolean|null); - /** Target resumeToken. */ - public resumeToken?: (Uint8Array|null); + /** FieldOptions weak */ + weak?: (boolean|null); - /** Target readTime. */ - public readTime?: (google.protobuf.ITimestamp|null); + /** FieldOptions debugRedact */ + debugRedact?: (boolean|null); - /** Target targetId. */ - public targetId: number; + /** FieldOptions retention */ + retention?: (google.protobuf.FieldOptions.OptionRetention|null); - /** Target once. */ - public once: boolean; + /** FieldOptions targets */ + targets?: (google.protobuf.FieldOptions.OptionTargetType[]|null); - /** Target targetType. */ - public targetType?: ("query"|"documents"); + /** FieldOptions editionDefaults */ + editionDefaults?: (google.protobuf.FieldOptions.IEditionDefault[]|null); - /** Target resumeType. */ - public resumeType?: ("resumeToken"|"readTime"); + /** FieldOptions features */ + features?: (google.protobuf.IFeatureSet|null); - /** - * Creates a Target message from a plain object. Also converts values to their respective internal types. - * @param object Plain object - * @returns Target - */ - public static fromObject(object: { [k: string]: any }): google.firestore.v1.Target; + /** FieldOptions uninterpretedOption */ + uninterpretedOption?: (google.protobuf.IUninterpretedOption[]|null); - /** - * Creates a plain object from a Target message. Also converts values to other types if specified. - * @param message Target - * @param [options] Conversion options - * @returns Plain object - */ - public static toObject(message: google.firestore.v1.Target, options?: $protobuf.IConversionOptions): { [k: string]: any }; + /** FieldOptions .google.api.fieldBehavior */ + ".google.api.fieldBehavior"?: (google.api.FieldBehavior[]|null); - /** - * Converts this Target to JSON. - * @returns JSON object - */ - public toJSON(): { [k: string]: any }; - } + /** FieldOptions .google.api.resourceReference */ + ".google.api.resourceReference"?: (google.api.IResourceReference|null); + } - namespace Target { + /** Represents a FieldOptions. */ + class FieldOptions implements IFieldOptions { - /** Properties of a DocumentsTarget. */ - interface IDocumentsTarget { + /** + * Constructs a new FieldOptions. + * @param [properties] Properties to set + */ + constructor(properties?: google.protobuf.IFieldOptions); - /** DocumentsTarget documents */ - documents?: (string[]|null); - } + /** FieldOptions ctype. */ + public ctype: google.protobuf.FieldOptions.CType; - /** Represents a DocumentsTarget. */ - class DocumentsTarget implements IDocumentsTarget { + /** FieldOptions packed. */ + public packed: boolean; - /** - * Constructs a new DocumentsTarget. - * @param [properties] Properties to set - */ - constructor(properties?: google.firestore.v1.Target.IDocumentsTarget); + /** FieldOptions jstype. */ + public jstype: google.protobuf.FieldOptions.JSType; - /** DocumentsTarget documents. */ - public documents: string[]; + /** FieldOptions lazy. */ + public lazy: boolean; - /** - * Creates a DocumentsTarget message from a plain object. Also converts values to their respective internal types. - * @param object Plain object - * @returns DocumentsTarget - */ - public static fromObject(object: { [k: string]: any }): google.firestore.v1.Target.DocumentsTarget; + /** FieldOptions unverifiedLazy. */ + public unverifiedLazy: boolean; - /** - * Creates a plain object from a DocumentsTarget message. Also converts values to other types if specified. - * @param message DocumentsTarget - * @param [options] Conversion options - * @returns Plain object - */ - public static toObject(message: google.firestore.v1.Target.DocumentsTarget, options?: $protobuf.IConversionOptions): { [k: string]: any }; + /** FieldOptions deprecated. */ + public deprecated: boolean; - /** - * Converts this DocumentsTarget to JSON. - * @returns JSON object - */ - public toJSON(): { [k: string]: any }; - } + /** FieldOptions weak. */ + public weak: boolean; - /** Properties of a QueryTarget. */ - interface IQueryTarget { + /** FieldOptions debugRedact. */ + public debugRedact: boolean; - /** QueryTarget parent */ - parent?: (string|null); + /** FieldOptions retention. */ + public retention: google.protobuf.FieldOptions.OptionRetention; - /** QueryTarget structuredQuery */ - structuredQuery?: (google.firestore.v1.IStructuredQuery|null); - } + /** FieldOptions targets. */ + public targets: google.protobuf.FieldOptions.OptionTargetType[]; - /** Represents a QueryTarget. */ - class QueryTarget implements IQueryTarget { + /** FieldOptions editionDefaults. */ + public editionDefaults: google.protobuf.FieldOptions.IEditionDefault[]; - /** - * Constructs a new QueryTarget. - * @param [properties] Properties to set - */ - constructor(properties?: google.firestore.v1.Target.IQueryTarget); + /** FieldOptions features. */ + public features?: (google.protobuf.IFeatureSet|null); + + /** FieldOptions uninterpretedOption. */ + public uninterpretedOption: google.protobuf.IUninterpretedOption[]; - /** QueryTarget parent. */ - public parent: string; + /** + * Creates a FieldOptions message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns FieldOptions + */ + public static fromObject(object: { [k: string]: any }): google.protobuf.FieldOptions; - /** QueryTarget structuredQuery. */ - public structuredQuery?: (google.firestore.v1.IStructuredQuery|null); + /** + * Creates a plain object from a FieldOptions message. Also converts values to other types if specified. + * @param message FieldOptions + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.protobuf.FieldOptions, options?: $protobuf.IConversionOptions): { [k: string]: any }; - /** QueryTarget queryType. */ - public queryType?: "structuredQuery"; + /** + * Converts this FieldOptions to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; - /** - * Creates a QueryTarget message from a plain object. Also converts values to their respective internal types. - * @param object Plain object - * @returns QueryTarget - */ - public static fromObject(object: { [k: string]: any }): google.firestore.v1.Target.QueryTarget; + /** + * Gets the default type url for FieldOptions + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } - /** - * Creates a plain object from a QueryTarget message. Also converts values to other types if specified. - * @param message QueryTarget - * @param [options] Conversion options - * @returns Plain object - */ - public static toObject(message: google.firestore.v1.Target.QueryTarget, options?: $protobuf.IConversionOptions): { [k: string]: any }; + namespace FieldOptions { - /** - * Converts this QueryTarget to JSON. - * @returns JSON object - */ - public toJSON(): { [k: string]: any }; - } - } + /** CType enum. */ + type CType = + "STRING"| "CORD"| "STRING_PIECE"; - /** Properties of a TargetChange. */ - interface ITargetChange { + /** JSType enum. */ + type JSType = + "JS_NORMAL"| "JS_STRING"| "JS_NUMBER"; - /** TargetChange targetChangeType */ - targetChangeType?: (google.firestore.v1.TargetChange.TargetChangeType|null); + /** OptionRetention enum. */ + type OptionRetention = + "RETENTION_UNKNOWN"| "RETENTION_RUNTIME"| "RETENTION_SOURCE"; - /** TargetChange targetIds */ - targetIds?: (number[]|null); + /** OptionTargetType enum. */ + type OptionTargetType = + "TARGET_TYPE_UNKNOWN"| "TARGET_TYPE_FILE"| "TARGET_TYPE_EXTENSION_RANGE"| "TARGET_TYPE_MESSAGE"| "TARGET_TYPE_FIELD"| "TARGET_TYPE_ONEOF"| "TARGET_TYPE_ENUM"| "TARGET_TYPE_ENUM_ENTRY"| "TARGET_TYPE_SERVICE"| "TARGET_TYPE_METHOD"; - /** TargetChange cause */ - cause?: (google.rpc.IStatus|null); + /** Properties of an EditionDefault. */ + interface IEditionDefault { - /** TargetChange resumeToken */ - resumeToken?: (Uint8Array|null); + /** EditionDefault edition */ + edition?: (google.protobuf.Edition|null); - /** TargetChange readTime */ - readTime?: (google.protobuf.ITimestamp|null); + /** EditionDefault value */ + value?: (string|null); } - /** Represents a TargetChange. */ - class TargetChange implements ITargetChange { + /** Represents an EditionDefault. */ + class EditionDefault implements IEditionDefault { /** - * Constructs a new TargetChange. + * Constructs a new EditionDefault. * @param [properties] Properties to set */ - constructor(properties?: google.firestore.v1.ITargetChange); - - /** TargetChange targetChangeType. */ - public targetChangeType: google.firestore.v1.TargetChange.TargetChangeType; - - /** TargetChange targetIds. */ - public targetIds: number[]; - - /** TargetChange cause. */ - public cause?: (google.rpc.IStatus|null); + constructor(properties?: google.protobuf.FieldOptions.IEditionDefault); - /** TargetChange resumeToken. */ - public resumeToken: Uint8Array; + /** EditionDefault edition. */ + public edition: google.protobuf.Edition; - /** TargetChange readTime. */ - public readTime?: (google.protobuf.ITimestamp|null); + /** EditionDefault value. */ + public value: string; /** - * Creates a TargetChange message from a plain object. Also converts values to their respective internal types. + * Creates an EditionDefault message from a plain object. Also converts values to their respective internal types. * @param object Plain object - * @returns TargetChange + * @returns EditionDefault */ - public static fromObject(object: { [k: string]: any }): google.firestore.v1.TargetChange; + public static fromObject(object: { [k: string]: any }): google.protobuf.FieldOptions.EditionDefault; /** - * Creates a plain object from a TargetChange message. Also converts values to other types if specified. - * @param message TargetChange + * Creates a plain object from an EditionDefault message. Also converts values to other types if specified. + * @param message EditionDefault * @param [options] Conversion options * @returns Plain object */ - public static toObject(message: google.firestore.v1.TargetChange, options?: $protobuf.IConversionOptions): { [k: string]: any }; + public static toObject(message: google.protobuf.FieldOptions.EditionDefault, options?: $protobuf.IConversionOptions): { [k: string]: any }; /** - * Converts this TargetChange to JSON. + * Converts this EditionDefault to JSON. * @returns JSON object */ public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for EditionDefault + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; } + } - namespace TargetChange { + /** Properties of an OneofOptions. */ + interface IOneofOptions { - /** TargetChangeType enum. */ - type TargetChangeType = - "NO_CHANGE"| "ADD"| "REMOVE"| "CURRENT"| "RESET"; - } + /** OneofOptions features */ + features?: (google.protobuf.IFeatureSet|null); - /** Properties of a ListCollectionIdsRequest. */ - interface IListCollectionIdsRequest { + /** OneofOptions uninterpretedOption */ + uninterpretedOption?: (google.protobuf.IUninterpretedOption[]|null); + } - /** ListCollectionIdsRequest parent */ - parent?: (string|null); + /** Represents an OneofOptions. */ + class OneofOptions implements IOneofOptions { - /** ListCollectionIdsRequest pageSize */ - pageSize?: (number|null); + /** + * Constructs a new OneofOptions. + * @param [properties] Properties to set + */ + constructor(properties?: google.protobuf.IOneofOptions); - /** ListCollectionIdsRequest pageToken */ - pageToken?: (string|null); - } + /** OneofOptions features. */ + public features?: (google.protobuf.IFeatureSet|null); - /** Represents a ListCollectionIdsRequest. */ - class ListCollectionIdsRequest implements IListCollectionIdsRequest { + /** OneofOptions uninterpretedOption. */ + public uninterpretedOption: google.protobuf.IUninterpretedOption[]; - /** - * Constructs a new ListCollectionIdsRequest. - * @param [properties] Properties to set - */ - constructor(properties?: google.firestore.v1.IListCollectionIdsRequest); + /** + * Creates an OneofOptions message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns OneofOptions + */ + public static fromObject(object: { [k: string]: any }): google.protobuf.OneofOptions; - /** ListCollectionIdsRequest parent. */ - public parent: string; + /** + * Creates a plain object from an OneofOptions message. Also converts values to other types if specified. + * @param message OneofOptions + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.protobuf.OneofOptions, options?: $protobuf.IConversionOptions): { [k: string]: any }; - /** ListCollectionIdsRequest pageSize. */ - public pageSize: number; + /** + * Converts this OneofOptions to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; - /** ListCollectionIdsRequest pageToken. */ - public pageToken: string; + /** + * Gets the default type url for OneofOptions + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } - /** - * Creates a ListCollectionIdsRequest message from a plain object. Also converts values to their respective internal types. - * @param object Plain object - * @returns ListCollectionIdsRequest - */ - public static fromObject(object: { [k: string]: any }): google.firestore.v1.ListCollectionIdsRequest; + /** Properties of an EnumOptions. */ + interface IEnumOptions { - /** - * Creates a plain object from a ListCollectionIdsRequest message. Also converts values to other types if specified. - * @param message ListCollectionIdsRequest - * @param [options] Conversion options - * @returns Plain object - */ - public static toObject(message: google.firestore.v1.ListCollectionIdsRequest, options?: $protobuf.IConversionOptions): { [k: string]: any }; + /** EnumOptions allowAlias */ + allowAlias?: (boolean|null); - /** - * Converts this ListCollectionIdsRequest to JSON. - * @returns JSON object - */ - public toJSON(): { [k: string]: any }; - } + /** EnumOptions deprecated */ + deprecated?: (boolean|null); - /** Properties of a ListCollectionIdsResponse. */ - interface IListCollectionIdsResponse { + /** EnumOptions deprecatedLegacyJsonFieldConflicts */ + deprecatedLegacyJsonFieldConflicts?: (boolean|null); - /** ListCollectionIdsResponse collectionIds */ - collectionIds?: (string[]|null); + /** EnumOptions features */ + features?: (google.protobuf.IFeatureSet|null); - /** ListCollectionIdsResponse nextPageToken */ - nextPageToken?: (string|null); - } + /** EnumOptions uninterpretedOption */ + uninterpretedOption?: (google.protobuf.IUninterpretedOption[]|null); + } - /** Represents a ListCollectionIdsResponse. */ - class ListCollectionIdsResponse implements IListCollectionIdsResponse { + /** Represents an EnumOptions. */ + class EnumOptions implements IEnumOptions { - /** - * Constructs a new ListCollectionIdsResponse. - * @param [properties] Properties to set - */ - constructor(properties?: google.firestore.v1.IListCollectionIdsResponse); + /** + * Constructs a new EnumOptions. + * @param [properties] Properties to set + */ + constructor(properties?: google.protobuf.IEnumOptions); + + /** EnumOptions allowAlias. */ + public allowAlias: boolean; + + /** EnumOptions deprecated. */ + public deprecated: boolean; + + /** EnumOptions deprecatedLegacyJsonFieldConflicts. */ + public deprecatedLegacyJsonFieldConflicts: boolean; + + /** EnumOptions features. */ + public features?: (google.protobuf.IFeatureSet|null); + + /** EnumOptions uninterpretedOption. */ + public uninterpretedOption: google.protobuf.IUninterpretedOption[]; + + /** + * Creates an EnumOptions message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns EnumOptions + */ + public static fromObject(object: { [k: string]: any }): google.protobuf.EnumOptions; + + /** + * Creates a plain object from an EnumOptions message. Also converts values to other types if specified. + * @param message EnumOptions + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.protobuf.EnumOptions, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this EnumOptions to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for EnumOptions + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of an EnumValueOptions. */ + interface IEnumValueOptions { + + /** EnumValueOptions deprecated */ + deprecated?: (boolean|null); + + /** EnumValueOptions features */ + features?: (google.protobuf.IFeatureSet|null); + + /** EnumValueOptions debugRedact */ + debugRedact?: (boolean|null); + + /** EnumValueOptions uninterpretedOption */ + uninterpretedOption?: (google.protobuf.IUninterpretedOption[]|null); + } + + /** Represents an EnumValueOptions. */ + class EnumValueOptions implements IEnumValueOptions { - /** ListCollectionIdsResponse collectionIds. */ - public collectionIds: string[]; + /** + * Constructs a new EnumValueOptions. + * @param [properties] Properties to set + */ + constructor(properties?: google.protobuf.IEnumValueOptions); - /** ListCollectionIdsResponse nextPageToken. */ - public nextPageToken: string; + /** EnumValueOptions deprecated. */ + public deprecated: boolean; - /** - * Creates a ListCollectionIdsResponse message from a plain object. Also converts values to their respective internal types. - * @param object Plain object - * @returns ListCollectionIdsResponse - */ - public static fromObject(object: { [k: string]: any }): google.firestore.v1.ListCollectionIdsResponse; + /** EnumValueOptions features. */ + public features?: (google.protobuf.IFeatureSet|null); - /** - * Creates a plain object from a ListCollectionIdsResponse message. Also converts values to other types if specified. - * @param message ListCollectionIdsResponse - * @param [options] Conversion options - * @returns Plain object - */ - public static toObject(message: google.firestore.v1.ListCollectionIdsResponse, options?: $protobuf.IConversionOptions): { [k: string]: any }; + /** EnumValueOptions debugRedact. */ + public debugRedact: boolean; - /** - * Converts this ListCollectionIdsResponse to JSON. - * @returns JSON object - */ - public toJSON(): { [k: string]: any }; - } + /** EnumValueOptions uninterpretedOption. */ + public uninterpretedOption: google.protobuf.IUninterpretedOption[]; - /** Properties of a BatchWriteRequest. */ - interface IBatchWriteRequest { + /** + * Creates an EnumValueOptions message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns EnumValueOptions + */ + public static fromObject(object: { [k: string]: any }): google.protobuf.EnumValueOptions; - /** BatchWriteRequest database */ - database?: (string|null); + /** + * Creates a plain object from an EnumValueOptions message. Also converts values to other types if specified. + * @param message EnumValueOptions + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.protobuf.EnumValueOptions, options?: $protobuf.IConversionOptions): { [k: string]: any }; - /** BatchWriteRequest writes */ - writes?: (google.firestore.v1.IWrite[]|null); + /** + * Converts this EnumValueOptions to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; - /** BatchWriteRequest labels */ - labels?: ({ [k: string]: string }|null); - } + /** + * Gets the default type url for EnumValueOptions + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } - /** Represents a BatchWriteRequest. */ - class BatchWriteRequest implements IBatchWriteRequest { + /** Properties of a ServiceOptions. */ + interface IServiceOptions { - /** - * Constructs a new BatchWriteRequest. - * @param [properties] Properties to set - */ - constructor(properties?: google.firestore.v1.IBatchWriteRequest); + /** ServiceOptions features */ + features?: (google.protobuf.IFeatureSet|null); - /** BatchWriteRequest database. */ - public database: string; + /** ServiceOptions deprecated */ + deprecated?: (boolean|null); - /** BatchWriteRequest writes. */ - public writes: google.firestore.v1.IWrite[]; + /** ServiceOptions uninterpretedOption */ + uninterpretedOption?: (google.protobuf.IUninterpretedOption[]|null); - /** BatchWriteRequest labels. */ - public labels: { [k: string]: string }; + /** ServiceOptions .google.api.defaultHost */ + ".google.api.defaultHost"?: (string|null); - /** - * Creates a BatchWriteRequest message from a plain object. Also converts values to their respective internal types. - * @param object Plain object - * @returns BatchWriteRequest - */ - public static fromObject(object: { [k: string]: any }): google.firestore.v1.BatchWriteRequest; + /** ServiceOptions .google.api.oauthScopes */ + ".google.api.oauthScopes"?: (string|null); - /** - * Creates a plain object from a BatchWriteRequest message. Also converts values to other types if specified. - * @param message BatchWriteRequest - * @param [options] Conversion options - * @returns Plain object - */ - public static toObject(message: google.firestore.v1.BatchWriteRequest, options?: $protobuf.IConversionOptions): { [k: string]: any }; + /** ServiceOptions .google.api.apiVersion */ + ".google.api.apiVersion"?: (string|null); + } - /** - * Converts this BatchWriteRequest to JSON. - * @returns JSON object - */ - public toJSON(): { [k: string]: any }; - } + /** Represents a ServiceOptions. */ + class ServiceOptions implements IServiceOptions { - /** Properties of a BatchWriteResponse. */ - interface IBatchWriteResponse { + /** + * Constructs a new ServiceOptions. + * @param [properties] Properties to set + */ + constructor(properties?: google.protobuf.IServiceOptions); - /** BatchWriteResponse writeResults */ - writeResults?: (google.firestore.v1.IWriteResult[]|null); + /** ServiceOptions features. */ + public features?: (google.protobuf.IFeatureSet|null); - /** BatchWriteResponse status */ - status?: (google.rpc.IStatus[]|null); - } + /** ServiceOptions deprecated. */ + public deprecated: boolean; - /** Represents a BatchWriteResponse. */ - class BatchWriteResponse implements IBatchWriteResponse { + /** ServiceOptions uninterpretedOption. */ + public uninterpretedOption: google.protobuf.IUninterpretedOption[]; - /** - * Constructs a new BatchWriteResponse. - * @param [properties] Properties to set - */ - constructor(properties?: google.firestore.v1.IBatchWriteResponse); + /** + * Creates a ServiceOptions message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns ServiceOptions + */ + public static fromObject(object: { [k: string]: any }): google.protobuf.ServiceOptions; - /** BatchWriteResponse writeResults. */ - public writeResults: google.firestore.v1.IWriteResult[]; + /** + * Creates a plain object from a ServiceOptions message. Also converts values to other types if specified. + * @param message ServiceOptions + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.protobuf.ServiceOptions, options?: $protobuf.IConversionOptions): { [k: string]: any }; - /** BatchWriteResponse status. */ - public status: google.rpc.IStatus[]; + /** + * Converts this ServiceOptions to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; - /** - * Creates a BatchWriteResponse message from a plain object. Also converts values to their respective internal types. - * @param object Plain object - * @returns BatchWriteResponse - */ - public static fromObject(object: { [k: string]: any }): google.firestore.v1.BatchWriteResponse; + /** + * Gets the default type url for ServiceOptions + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } - /** - * Creates a plain object from a BatchWriteResponse message. Also converts values to other types if specified. - * @param message BatchWriteResponse - * @param [options] Conversion options - * @returns Plain object - */ - public static toObject(message: google.firestore.v1.BatchWriteResponse, options?: $protobuf.IConversionOptions): { [k: string]: any }; + /** Properties of a MethodOptions. */ + interface IMethodOptions { - /** - * Converts this BatchWriteResponse to JSON. - * @returns JSON object - */ - public toJSON(): { [k: string]: any }; - } + /** MethodOptions deprecated */ + deprecated?: (boolean|null); - /** Properties of a StructuredQuery. */ - interface IStructuredQuery { + /** MethodOptions idempotencyLevel */ + idempotencyLevel?: (google.protobuf.MethodOptions.IdempotencyLevel|null); - /** StructuredQuery select */ - select?: (google.firestore.v1.StructuredQuery.IProjection|null); + /** MethodOptions features */ + features?: (google.protobuf.IFeatureSet|null); - /** StructuredQuery from */ - from?: (google.firestore.v1.StructuredQuery.ICollectionSelector[]|null); + /** MethodOptions uninterpretedOption */ + uninterpretedOption?: (google.protobuf.IUninterpretedOption[]|null); - /** StructuredQuery where */ - where?: (google.firestore.v1.StructuredQuery.IFilter|null); + /** MethodOptions .google.api.http */ + ".google.api.http"?: (google.api.IHttpRule|null); - /** StructuredQuery orderBy */ - orderBy?: (google.firestore.v1.StructuredQuery.IOrder[]|null); + /** MethodOptions .google.api.methodSignature */ + ".google.api.methodSignature"?: (string[]|null); - /** StructuredQuery startAt */ - startAt?: (google.firestore.v1.ICursor|null); + /** MethodOptions .google.longrunning.operationInfo */ + ".google.longrunning.operationInfo"?: (google.longrunning.IOperationInfo|null); + } - /** StructuredQuery endAt */ - endAt?: (google.firestore.v1.ICursor|null); + /** Represents a MethodOptions. */ + class MethodOptions implements IMethodOptions { - /** StructuredQuery offset */ - offset?: (number|null); + /** + * Constructs a new MethodOptions. + * @param [properties] Properties to set + */ + constructor(properties?: google.protobuf.IMethodOptions); - /** StructuredQuery limit */ - limit?: (google.protobuf.IInt32Value|null); - } + /** MethodOptions deprecated. */ + public deprecated: boolean; - /** Represents a StructuredQuery. */ - class StructuredQuery implements IStructuredQuery { + /** MethodOptions idempotencyLevel. */ + public idempotencyLevel: google.protobuf.MethodOptions.IdempotencyLevel; - /** - * Constructs a new StructuredQuery. - * @param [properties] Properties to set - */ - constructor(properties?: google.firestore.v1.IStructuredQuery); + /** MethodOptions features. */ + public features?: (google.protobuf.IFeatureSet|null); - /** StructuredQuery select. */ - public select?: (google.firestore.v1.StructuredQuery.IProjection|null); + /** MethodOptions uninterpretedOption. */ + public uninterpretedOption: google.protobuf.IUninterpretedOption[]; - /** StructuredQuery from. */ - public from: google.firestore.v1.StructuredQuery.ICollectionSelector[]; + /** + * Creates a MethodOptions message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns MethodOptions + */ + public static fromObject(object: { [k: string]: any }): google.protobuf.MethodOptions; - /** StructuredQuery where. */ - public where?: (google.firestore.v1.StructuredQuery.IFilter|null); + /** + * Creates a plain object from a MethodOptions message. Also converts values to other types if specified. + * @param message MethodOptions + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.protobuf.MethodOptions, options?: $protobuf.IConversionOptions): { [k: string]: any }; - /** StructuredQuery orderBy. */ - public orderBy: google.firestore.v1.StructuredQuery.IOrder[]; + /** + * Converts this MethodOptions to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for MethodOptions + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } - /** StructuredQuery startAt. */ - public startAt?: (google.firestore.v1.ICursor|null); + namespace MethodOptions { - /** StructuredQuery endAt. */ - public endAt?: (google.firestore.v1.ICursor|null); + /** IdempotencyLevel enum. */ + type IdempotencyLevel = + "IDEMPOTENCY_UNKNOWN"| "NO_SIDE_EFFECTS"| "IDEMPOTENT"; + } - /** StructuredQuery offset. */ - public offset: number; + /** Properties of an UninterpretedOption. */ + interface IUninterpretedOption { - /** StructuredQuery limit. */ - public limit?: (google.protobuf.IInt32Value|null); + /** UninterpretedOption name */ + name?: (google.protobuf.UninterpretedOption.INamePart[]|null); - /** - * Creates a StructuredQuery message from a plain object. Also converts values to their respective internal types. - * @param object Plain object - * @returns StructuredQuery - */ - public static fromObject(object: { [k: string]: any }): google.firestore.v1.StructuredQuery; + /** UninterpretedOption identifierValue */ + identifierValue?: (string|null); - /** - * Creates a plain object from a StructuredQuery message. Also converts values to other types if specified. - * @param message StructuredQuery - * @param [options] Conversion options - * @returns Plain object - */ - public static toObject(message: google.firestore.v1.StructuredQuery, options?: $protobuf.IConversionOptions): { [k: string]: any }; + /** UninterpretedOption positiveIntValue */ + positiveIntValue?: (number|string|null); - /** - * Converts this StructuredQuery to JSON. - * @returns JSON object - */ - public toJSON(): { [k: string]: any }; - } + /** UninterpretedOption negativeIntValue */ + negativeIntValue?: (number|string|null); - namespace StructuredQuery { + /** UninterpretedOption doubleValue */ + doubleValue?: (number|null); - /** Properties of a CollectionSelector. */ - interface ICollectionSelector { + /** UninterpretedOption stringValue */ + stringValue?: (Uint8Array|null); - /** CollectionSelector collectionId */ - collectionId?: (string|null); + /** UninterpretedOption aggregateValue */ + aggregateValue?: (string|null); + } - /** CollectionSelector allDescendants */ - allDescendants?: (boolean|null); - } + /** Represents an UninterpretedOption. */ + class UninterpretedOption implements IUninterpretedOption { - /** Represents a CollectionSelector. */ - class CollectionSelector implements ICollectionSelector { + /** + * Constructs a new UninterpretedOption. + * @param [properties] Properties to set + */ + constructor(properties?: google.protobuf.IUninterpretedOption); - /** - * Constructs a new CollectionSelector. - * @param [properties] Properties to set - */ - constructor(properties?: google.firestore.v1.StructuredQuery.ICollectionSelector); + /** UninterpretedOption name. */ + public name: google.protobuf.UninterpretedOption.INamePart[]; - /** CollectionSelector collectionId. */ - public collectionId: string; + /** UninterpretedOption identifierValue. */ + public identifierValue: string; - /** CollectionSelector allDescendants. */ - public allDescendants: boolean; + /** UninterpretedOption positiveIntValue. */ + public positiveIntValue: (number|string); - /** - * Creates a CollectionSelector message from a plain object. Also converts values to their respective internal types. - * @param object Plain object - * @returns CollectionSelector - */ - public static fromObject(object: { [k: string]: any }): google.firestore.v1.StructuredQuery.CollectionSelector; + /** UninterpretedOption negativeIntValue. */ + public negativeIntValue: (number|string); - /** - * Creates a plain object from a CollectionSelector message. Also converts values to other types if specified. - * @param message CollectionSelector - * @param [options] Conversion options - * @returns Plain object - */ - public static toObject(message: google.firestore.v1.StructuredQuery.CollectionSelector, options?: $protobuf.IConversionOptions): { [k: string]: any }; + /** UninterpretedOption doubleValue. */ + public doubleValue: number; - /** - * Converts this CollectionSelector to JSON. - * @returns JSON object - */ - public toJSON(): { [k: string]: any }; - } + /** UninterpretedOption stringValue. */ + public stringValue: Uint8Array; - /** Properties of a Filter. */ - interface IFilter { + /** UninterpretedOption aggregateValue. */ + public aggregateValue: string; - /** Filter compositeFilter */ - compositeFilter?: (google.firestore.v1.StructuredQuery.ICompositeFilter|null); + /** + * Creates an UninterpretedOption message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns UninterpretedOption + */ + public static fromObject(object: { [k: string]: any }): google.protobuf.UninterpretedOption; - /** Filter fieldFilter */ - fieldFilter?: (google.firestore.v1.StructuredQuery.IFieldFilter|null); + /** + * Creates a plain object from an UninterpretedOption message. Also converts values to other types if specified. + * @param message UninterpretedOption + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.protobuf.UninterpretedOption, options?: $protobuf.IConversionOptions): { [k: string]: any }; - /** Filter unaryFilter */ - unaryFilter?: (google.firestore.v1.StructuredQuery.IUnaryFilter|null); - } + /** + * Converts this UninterpretedOption to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; - /** Represents a Filter. */ - class Filter implements IFilter { + /** + * Gets the default type url for UninterpretedOption + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } - /** - * Constructs a new Filter. - * @param [properties] Properties to set - */ - constructor(properties?: google.firestore.v1.StructuredQuery.IFilter); + namespace UninterpretedOption { - /** Filter compositeFilter. */ - public compositeFilter?: (google.firestore.v1.StructuredQuery.ICompositeFilter|null); + /** Properties of a NamePart. */ + interface INamePart { - /** Filter fieldFilter. */ - public fieldFilter?: (google.firestore.v1.StructuredQuery.IFieldFilter|null); + /** NamePart namePart */ + namePart: string; - /** Filter unaryFilter. */ - public unaryFilter?: (google.firestore.v1.StructuredQuery.IUnaryFilter|null); + /** NamePart isExtension */ + isExtension: boolean; + } - /** Filter filterType. */ - public filterType?: ("compositeFilter"|"fieldFilter"|"unaryFilter"); + /** Represents a NamePart. */ + class NamePart implements INamePart { - /** - * Creates a Filter message from a plain object. Also converts values to their respective internal types. - * @param object Plain object - * @returns Filter - */ - public static fromObject(object: { [k: string]: any }): google.firestore.v1.StructuredQuery.Filter; + /** + * Constructs a new NamePart. + * @param [properties] Properties to set + */ + constructor(properties?: google.protobuf.UninterpretedOption.INamePart); - /** - * Creates a plain object from a Filter message. Also converts values to other types if specified. - * @param message Filter - * @param [options] Conversion options - * @returns Plain object - */ - public static toObject(message: google.firestore.v1.StructuredQuery.Filter, options?: $protobuf.IConversionOptions): { [k: string]: any }; + /** NamePart namePart. */ + public namePart: string; - /** - * Converts this Filter to JSON. - * @returns JSON object - */ - public toJSON(): { [k: string]: any }; - } + /** NamePart isExtension. */ + public isExtension: boolean; - /** Properties of a CompositeFilter. */ - interface ICompositeFilter { + /** + * Creates a NamePart message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns NamePart + */ + public static fromObject(object: { [k: string]: any }): google.protobuf.UninterpretedOption.NamePart; - /** CompositeFilter op */ - op?: (google.firestore.v1.StructuredQuery.CompositeFilter.Operator|null); + /** + * Creates a plain object from a NamePart message. Also converts values to other types if specified. + * @param message NamePart + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.protobuf.UninterpretedOption.NamePart, options?: $protobuf.IConversionOptions): { [k: string]: any }; - /** CompositeFilter filters */ - filters?: (google.firestore.v1.StructuredQuery.IFilter[]|null); - } + /** + * Converts this NamePart to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; - /** Represents a CompositeFilter. */ - class CompositeFilter implements ICompositeFilter { + /** + * Gets the default type url for NamePart + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + } - /** - * Constructs a new CompositeFilter. - * @param [properties] Properties to set - */ - constructor(properties?: google.firestore.v1.StructuredQuery.ICompositeFilter); + /** Properties of a FeatureSet. */ + interface IFeatureSet { - /** CompositeFilter op. */ - public op: google.firestore.v1.StructuredQuery.CompositeFilter.Operator; + /** FeatureSet fieldPresence */ + fieldPresence?: (google.protobuf.FeatureSet.FieldPresence|null); - /** CompositeFilter filters. */ - public filters: google.firestore.v1.StructuredQuery.IFilter[]; + /** FeatureSet enumType */ + enumType?: (google.protobuf.FeatureSet.EnumType|null); - /** - * Creates a CompositeFilter message from a plain object. Also converts values to their respective internal types. - * @param object Plain object - * @returns CompositeFilter - */ - public static fromObject(object: { [k: string]: any }): google.firestore.v1.StructuredQuery.CompositeFilter; + /** FeatureSet repeatedFieldEncoding */ + repeatedFieldEncoding?: (google.protobuf.FeatureSet.RepeatedFieldEncoding|null); - /** - * Creates a plain object from a CompositeFilter message. Also converts values to other types if specified. - * @param message CompositeFilter - * @param [options] Conversion options - * @returns Plain object - */ - public static toObject(message: google.firestore.v1.StructuredQuery.CompositeFilter, options?: $protobuf.IConversionOptions): { [k: string]: any }; + /** FeatureSet utf8Validation */ + utf8Validation?: (google.protobuf.FeatureSet.Utf8Validation|null); - /** - * Converts this CompositeFilter to JSON. - * @returns JSON object - */ - public toJSON(): { [k: string]: any }; - } + /** FeatureSet messageEncoding */ + messageEncoding?: (google.protobuf.FeatureSet.MessageEncoding|null); - namespace CompositeFilter { + /** FeatureSet jsonFormat */ + jsonFormat?: (google.protobuf.FeatureSet.JsonFormat|null); + } - /** Operator enum. */ - type Operator = - "OPERATOR_UNSPECIFIED"| "AND"| "OR"; - } + /** Represents a FeatureSet. */ + class FeatureSet implements IFeatureSet { + + /** + * Constructs a new FeatureSet. + * @param [properties] Properties to set + */ + constructor(properties?: google.protobuf.IFeatureSet); - /** Properties of a FieldFilter. */ - interface IFieldFilter { + /** FeatureSet fieldPresence. */ + public fieldPresence: google.protobuf.FeatureSet.FieldPresence; - /** FieldFilter field */ - field?: (google.firestore.v1.StructuredQuery.IFieldReference|null); + /** FeatureSet enumType. */ + public enumType: google.protobuf.FeatureSet.EnumType; - /** FieldFilter op */ - op?: (google.firestore.v1.StructuredQuery.FieldFilter.Operator|null); + /** FeatureSet repeatedFieldEncoding. */ + public repeatedFieldEncoding: google.protobuf.FeatureSet.RepeatedFieldEncoding; - /** FieldFilter value */ - value?: (google.firestore.v1.IValue|null); - } + /** FeatureSet utf8Validation. */ + public utf8Validation: google.protobuf.FeatureSet.Utf8Validation; - /** Represents a FieldFilter. */ - class FieldFilter implements IFieldFilter { + /** FeatureSet messageEncoding. */ + public messageEncoding: google.protobuf.FeatureSet.MessageEncoding; - /** - * Constructs a new FieldFilter. - * @param [properties] Properties to set - */ - constructor(properties?: google.firestore.v1.StructuredQuery.IFieldFilter); + /** FeatureSet jsonFormat. */ + public jsonFormat: google.protobuf.FeatureSet.JsonFormat; - /** FieldFilter field. */ - public field?: (google.firestore.v1.StructuredQuery.IFieldReference|null); + /** + * Creates a FeatureSet message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns FeatureSet + */ + public static fromObject(object: { [k: string]: any }): google.protobuf.FeatureSet; - /** FieldFilter op. */ - public op: google.firestore.v1.StructuredQuery.FieldFilter.Operator; + /** + * Creates a plain object from a FeatureSet message. Also converts values to other types if specified. + * @param message FeatureSet + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.protobuf.FeatureSet, options?: $protobuf.IConversionOptions): { [k: string]: any }; - /** FieldFilter value. */ - public value?: (google.firestore.v1.IValue|null); + /** + * Converts this FeatureSet to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; - /** - * Creates a FieldFilter message from a plain object. Also converts values to their respective internal types. - * @param object Plain object - * @returns FieldFilter - */ - public static fromObject(object: { [k: string]: any }): google.firestore.v1.StructuredQuery.FieldFilter; + /** + * Gets the default type url for FeatureSet + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } - /** - * Creates a plain object from a FieldFilter message. Also converts values to other types if specified. - * @param message FieldFilter - * @param [options] Conversion options - * @returns Plain object - */ - public static toObject(message: google.firestore.v1.StructuredQuery.FieldFilter, options?: $protobuf.IConversionOptions): { [k: string]: any }; + namespace FeatureSet { - /** - * Converts this FieldFilter to JSON. - * @returns JSON object - */ - public toJSON(): { [k: string]: any }; - } + /** FieldPresence enum. */ + type FieldPresence = + "FIELD_PRESENCE_UNKNOWN"| "EXPLICIT"| "IMPLICIT"| "LEGACY_REQUIRED"; - namespace FieldFilter { + /** EnumType enum. */ + type EnumType = + "ENUM_TYPE_UNKNOWN"| "OPEN"| "CLOSED"; - /** Operator enum. */ - type Operator = - "OPERATOR_UNSPECIFIED"| "LESS_THAN"| "LESS_THAN_OR_EQUAL"| "GREATER_THAN"| "GREATER_THAN_OR_EQUAL"| "EQUAL"| "NOT_EQUAL"| "ARRAY_CONTAINS"| "IN"| "ARRAY_CONTAINS_ANY"| "NOT_IN"; - } + /** RepeatedFieldEncoding enum. */ + type RepeatedFieldEncoding = + "REPEATED_FIELD_ENCODING_UNKNOWN"| "PACKED"| "EXPANDED"; - /** Properties of an UnaryFilter. */ - interface IUnaryFilter { + /** Utf8Validation enum. */ + type Utf8Validation = + "UTF8_VALIDATION_UNKNOWN"| "VERIFY"| "NONE"; - /** UnaryFilter op */ - op?: (google.firestore.v1.StructuredQuery.UnaryFilter.Operator|null); + /** MessageEncoding enum. */ + type MessageEncoding = + "MESSAGE_ENCODING_UNKNOWN"| "LENGTH_PREFIXED"| "DELIMITED"; - /** UnaryFilter field */ - field?: (google.firestore.v1.StructuredQuery.IFieldReference|null); - } + /** JsonFormat enum. */ + type JsonFormat = + "JSON_FORMAT_UNKNOWN"| "ALLOW"| "LEGACY_BEST_EFFORT"; + } - /** Represents an UnaryFilter. */ - class UnaryFilter implements IUnaryFilter { + /** Properties of a FeatureSetDefaults. */ + interface IFeatureSetDefaults { - /** - * Constructs a new UnaryFilter. - * @param [properties] Properties to set - */ - constructor(properties?: google.firestore.v1.StructuredQuery.IUnaryFilter); + /** FeatureSetDefaults defaults */ + defaults?: (google.protobuf.FeatureSetDefaults.IFeatureSetEditionDefault[]|null); - /** UnaryFilter op. */ - public op: google.firestore.v1.StructuredQuery.UnaryFilter.Operator; + /** FeatureSetDefaults minimumEdition */ + minimumEdition?: (google.protobuf.Edition|null); - /** UnaryFilter field. */ - public field?: (google.firestore.v1.StructuredQuery.IFieldReference|null); + /** FeatureSetDefaults maximumEdition */ + maximumEdition?: (google.protobuf.Edition|null); + } - /** UnaryFilter operandType. */ - public operandType?: "field"; + /** Represents a FeatureSetDefaults. */ + class FeatureSetDefaults implements IFeatureSetDefaults { - /** - * Creates an UnaryFilter message from a plain object. Also converts values to their respective internal types. - * @param object Plain object - * @returns UnaryFilter - */ - public static fromObject(object: { [k: string]: any }): google.firestore.v1.StructuredQuery.UnaryFilter; + /** + * Constructs a new FeatureSetDefaults. + * @param [properties] Properties to set + */ + constructor(properties?: google.protobuf.IFeatureSetDefaults); - /** - * Creates a plain object from an UnaryFilter message. Also converts values to other types if specified. - * @param message UnaryFilter - * @param [options] Conversion options - * @returns Plain object - */ - public static toObject(message: google.firestore.v1.StructuredQuery.UnaryFilter, options?: $protobuf.IConversionOptions): { [k: string]: any }; + /** FeatureSetDefaults defaults. */ + public defaults: google.protobuf.FeatureSetDefaults.IFeatureSetEditionDefault[]; - /** - * Converts this UnaryFilter to JSON. - * @returns JSON object - */ - public toJSON(): { [k: string]: any }; - } + /** FeatureSetDefaults minimumEdition. */ + public minimumEdition: google.protobuf.Edition; - namespace UnaryFilter { + /** FeatureSetDefaults maximumEdition. */ + public maximumEdition: google.protobuf.Edition; - /** Operator enum. */ - type Operator = - "OPERATOR_UNSPECIFIED"| "IS_NAN"| "IS_NULL"| "IS_NOT_NAN"| "IS_NOT_NULL"; - } + /** + * Creates a FeatureSetDefaults message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns FeatureSetDefaults + */ + public static fromObject(object: { [k: string]: any }): google.protobuf.FeatureSetDefaults; - /** Properties of an Order. */ - interface IOrder { + /** + * Creates a plain object from a FeatureSetDefaults message. Also converts values to other types if specified. + * @param message FeatureSetDefaults + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.protobuf.FeatureSetDefaults, options?: $protobuf.IConversionOptions): { [k: string]: any }; - /** Order field */ - field?: (google.firestore.v1.StructuredQuery.IFieldReference|null); + /** + * Converts this FeatureSetDefaults to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; - /** Order direction */ - direction?: (google.firestore.v1.StructuredQuery.Direction|null); - } + /** + * Gets the default type url for FeatureSetDefaults + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } - /** Represents an Order. */ - class Order implements IOrder { + namespace FeatureSetDefaults { - /** - * Constructs a new Order. - * @param [properties] Properties to set - */ - constructor(properties?: google.firestore.v1.StructuredQuery.IOrder); + /** Properties of a FeatureSetEditionDefault. */ + interface IFeatureSetEditionDefault { - /** Order field. */ - public field?: (google.firestore.v1.StructuredQuery.IFieldReference|null); + /** FeatureSetEditionDefault edition */ + edition?: (google.protobuf.Edition|null); - /** Order direction. */ - public direction: google.firestore.v1.StructuredQuery.Direction; + /** FeatureSetEditionDefault features */ + features?: (google.protobuf.IFeatureSet|null); + } - /** - * Creates an Order message from a plain object. Also converts values to their respective internal types. - * @param object Plain object - * @returns Order - */ - public static fromObject(object: { [k: string]: any }): google.firestore.v1.StructuredQuery.Order; + /** Represents a FeatureSetEditionDefault. */ + class FeatureSetEditionDefault implements IFeatureSetEditionDefault { - /** - * Creates a plain object from an Order message. Also converts values to other types if specified. - * @param message Order - * @param [options] Conversion options - * @returns Plain object - */ - public static toObject(message: google.firestore.v1.StructuredQuery.Order, options?: $protobuf.IConversionOptions): { [k: string]: any }; + /** + * Constructs a new FeatureSetEditionDefault. + * @param [properties] Properties to set + */ + constructor(properties?: google.protobuf.FeatureSetDefaults.IFeatureSetEditionDefault); - /** - * Converts this Order to JSON. - * @returns JSON object - */ - public toJSON(): { [k: string]: any }; - } + /** FeatureSetEditionDefault edition. */ + public edition: google.protobuf.Edition; - /** Properties of a FieldReference. */ - interface IFieldReference { + /** FeatureSetEditionDefault features. */ + public features?: (google.protobuf.IFeatureSet|null); - /** FieldReference fieldPath */ - fieldPath?: (string|null); - } + /** + * Creates a FeatureSetEditionDefault message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns FeatureSetEditionDefault + */ + public static fromObject(object: { [k: string]: any }): google.protobuf.FeatureSetDefaults.FeatureSetEditionDefault; - /** Represents a FieldReference. */ - class FieldReference implements IFieldReference { + /** + * Creates a plain object from a FeatureSetEditionDefault message. Also converts values to other types if specified. + * @param message FeatureSetEditionDefault + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.protobuf.FeatureSetDefaults.FeatureSetEditionDefault, options?: $protobuf.IConversionOptions): { [k: string]: any }; - /** - * Constructs a new FieldReference. - * @param [properties] Properties to set - */ - constructor(properties?: google.firestore.v1.StructuredQuery.IFieldReference); + /** + * Converts this FeatureSetEditionDefault to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; - /** FieldReference fieldPath. */ - public fieldPath: string; + /** + * Gets the default type url for FeatureSetEditionDefault + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + } - /** - * Creates a FieldReference message from a plain object. Also converts values to their respective internal types. - * @param object Plain object - * @returns FieldReference - */ - public static fromObject(object: { [k: string]: any }): google.firestore.v1.StructuredQuery.FieldReference; + /** Properties of a SourceCodeInfo. */ + interface ISourceCodeInfo { - /** - * Creates a plain object from a FieldReference message. Also converts values to other types if specified. - * @param message FieldReference - * @param [options] Conversion options - * @returns Plain object - */ - public static toObject(message: google.firestore.v1.StructuredQuery.FieldReference, options?: $protobuf.IConversionOptions): { [k: string]: any }; + /** SourceCodeInfo location */ + location?: (google.protobuf.SourceCodeInfo.ILocation[]|null); + } - /** - * Converts this FieldReference to JSON. - * @returns JSON object - */ - public toJSON(): { [k: string]: any }; - } + /** Represents a SourceCodeInfo. */ + class SourceCodeInfo implements ISourceCodeInfo { - /** Properties of a Projection. */ - interface IProjection { + /** + * Constructs a new SourceCodeInfo. + * @param [properties] Properties to set + */ + constructor(properties?: google.protobuf.ISourceCodeInfo); - /** Projection fields */ - fields?: (google.firestore.v1.StructuredQuery.IFieldReference[]|null); - } + /** SourceCodeInfo location. */ + public location: google.protobuf.SourceCodeInfo.ILocation[]; - /** Represents a Projection. */ - class Projection implements IProjection { + /** + * Creates a SourceCodeInfo message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns SourceCodeInfo + */ + public static fromObject(object: { [k: string]: any }): google.protobuf.SourceCodeInfo; - /** - * Constructs a new Projection. - * @param [properties] Properties to set - */ - constructor(properties?: google.firestore.v1.StructuredQuery.IProjection); + /** + * Creates a plain object from a SourceCodeInfo message. Also converts values to other types if specified. + * @param message SourceCodeInfo + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.protobuf.SourceCodeInfo, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this SourceCodeInfo to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; - /** Projection fields. */ - public fields: google.firestore.v1.StructuredQuery.IFieldReference[]; + /** + * Gets the default type url for SourceCodeInfo + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } - /** - * Creates a Projection message from a plain object. Also converts values to their respective internal types. - * @param object Plain object - * @returns Projection - */ - public static fromObject(object: { [k: string]: any }): google.firestore.v1.StructuredQuery.Projection; + namespace SourceCodeInfo { - /** - * Creates a plain object from a Projection message. Also converts values to other types if specified. - * @param message Projection - * @param [options] Conversion options - * @returns Plain object - */ - public static toObject(message: google.firestore.v1.StructuredQuery.Projection, options?: $protobuf.IConversionOptions): { [k: string]: any }; + /** Properties of a Location. */ + interface ILocation { - /** - * Converts this Projection to JSON. - * @returns JSON object - */ - public toJSON(): { [k: string]: any }; - } + /** Location path */ + path?: (number[]|null); - /** Direction enum. */ - type Direction = - "DIRECTION_UNSPECIFIED"| "ASCENDING"| "DESCENDING"; - } + /** Location span */ + span?: (number[]|null); - /** Properties of a Cursor. */ - interface ICursor { + /** Location leadingComments */ + leadingComments?: (string|null); - /** Cursor values */ - values?: (google.firestore.v1.IValue[]|null); + /** Location trailingComments */ + trailingComments?: (string|null); - /** Cursor before */ - before?: (boolean|null); + /** Location leadingDetachedComments */ + leadingDetachedComments?: (string[]|null); } - /** Represents a Cursor. */ - class Cursor implements ICursor { + /** Represents a Location. */ + class Location implements ILocation { /** - * Constructs a new Cursor. + * Constructs a new Location. * @param [properties] Properties to set */ - constructor(properties?: google.firestore.v1.ICursor); + constructor(properties?: google.protobuf.SourceCodeInfo.ILocation); - /** Cursor values. */ - public values: google.firestore.v1.IValue[]; + /** Location path. */ + public path: number[]; - /** Cursor before. */ - public before: boolean; + /** Location span. */ + public span: number[]; + + /** Location leadingComments. */ + public leadingComments: string; + + /** Location trailingComments. */ + public trailingComments: string; + + /** Location leadingDetachedComments. */ + public leadingDetachedComments: string[]; /** - * Creates a Cursor message from a plain object. Also converts values to their respective internal types. + * Creates a Location message from a plain object. Also converts values to their respective internal types. * @param object Plain object - * @returns Cursor + * @returns Location */ - public static fromObject(object: { [k: string]: any }): google.firestore.v1.Cursor; + public static fromObject(object: { [k: string]: any }): google.protobuf.SourceCodeInfo.Location; /** - * Creates a plain object from a Cursor message. Also converts values to other types if specified. - * @param message Cursor + * Creates a plain object from a Location message. Also converts values to other types if specified. + * @param message Location * @param [options] Conversion options * @returns Plain object */ - public static toObject(message: google.firestore.v1.Cursor, options?: $protobuf.IConversionOptions): { [k: string]: any }; + public static toObject(message: google.protobuf.SourceCodeInfo.Location, options?: $protobuf.IConversionOptions): { [k: string]: any }; /** - * Converts this Cursor to JSON. + * Converts this Location to JSON. * @returns JSON object */ public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for Location + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; } + } - /** Properties of a Write. */ - interface IWrite { + /** Properties of a GeneratedCodeInfo. */ + interface IGeneratedCodeInfo { - /** Write update */ - update?: (google.firestore.v1.IDocument|null); + /** GeneratedCodeInfo annotation */ + annotation?: (google.protobuf.GeneratedCodeInfo.IAnnotation[]|null); + } - /** Write delete */ - "delete"?: (string|null); + /** Represents a GeneratedCodeInfo. */ + class GeneratedCodeInfo implements IGeneratedCodeInfo { - /** Write transform */ - transform?: (google.firestore.v1.IDocumentTransform|null); + /** + * Constructs a new GeneratedCodeInfo. + * @param [properties] Properties to set + */ + constructor(properties?: google.protobuf.IGeneratedCodeInfo); - /** Write updateMask */ - updateMask?: (google.firestore.v1.IDocumentMask|null); + /** GeneratedCodeInfo annotation. */ + public annotation: google.protobuf.GeneratedCodeInfo.IAnnotation[]; - /** Write updateTransforms */ - updateTransforms?: (google.firestore.v1.DocumentTransform.IFieldTransform[]|null); + /** + * Creates a GeneratedCodeInfo message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns GeneratedCodeInfo + */ + public static fromObject(object: { [k: string]: any }): google.protobuf.GeneratedCodeInfo; - /** Write currentDocument */ - currentDocument?: (google.firestore.v1.IPrecondition|null); + /** + * Creates a plain object from a GeneratedCodeInfo message. Also converts values to other types if specified. + * @param message GeneratedCodeInfo + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.protobuf.GeneratedCodeInfo, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this GeneratedCodeInfo to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for GeneratedCodeInfo + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + namespace GeneratedCodeInfo { + + /** Properties of an Annotation. */ + interface IAnnotation { + + /** Annotation path */ + path?: (number[]|null); + + /** Annotation sourceFile */ + sourceFile?: (string|null); + + /** Annotation begin */ + begin?: (number|null); + + /** Annotation end */ + end?: (number|null); + + /** Annotation semantic */ + semantic?: (google.protobuf.GeneratedCodeInfo.Annotation.Semantic|null); } - /** Represents a Write. */ - class Write implements IWrite { + /** Represents an Annotation. */ + class Annotation implements IAnnotation { /** - * Constructs a new Write. + * Constructs a new Annotation. * @param [properties] Properties to set */ - constructor(properties?: google.firestore.v1.IWrite); - - /** Write update. */ - public update?: (google.firestore.v1.IDocument|null); - - /** Write delete. */ - public delete?: (string|null); + constructor(properties?: google.protobuf.GeneratedCodeInfo.IAnnotation); - /** Write transform. */ - public transform?: (google.firestore.v1.IDocumentTransform|null); + /** Annotation path. */ + public path: number[]; - /** Write updateMask. */ - public updateMask?: (google.firestore.v1.IDocumentMask|null); + /** Annotation sourceFile. */ + public sourceFile: string; - /** Write updateTransforms. */ - public updateTransforms: google.firestore.v1.DocumentTransform.IFieldTransform[]; + /** Annotation begin. */ + public begin: number; - /** Write currentDocument. */ - public currentDocument?: (google.firestore.v1.IPrecondition|null); + /** Annotation end. */ + public end: number; - /** Write operation. */ - public operation?: ("update"|"delete"|"transform"); + /** Annotation semantic. */ + public semantic: google.protobuf.GeneratedCodeInfo.Annotation.Semantic; /** - * Creates a Write message from a plain object. Also converts values to their respective internal types. + * Creates an Annotation message from a plain object. Also converts values to their respective internal types. * @param object Plain object - * @returns Write + * @returns Annotation */ - public static fromObject(object: { [k: string]: any }): google.firestore.v1.Write; + public static fromObject(object: { [k: string]: any }): google.protobuf.GeneratedCodeInfo.Annotation; /** - * Creates a plain object from a Write message. Also converts values to other types if specified. - * @param message Write + * Creates a plain object from an Annotation message. Also converts values to other types if specified. + * @param message Annotation * @param [options] Conversion options * @returns Plain object */ - public static toObject(message: google.firestore.v1.Write, options?: $protobuf.IConversionOptions): { [k: string]: any }; + public static toObject(message: google.protobuf.GeneratedCodeInfo.Annotation, options?: $protobuf.IConversionOptions): { [k: string]: any }; /** - * Converts this Write to JSON. + * Converts this Annotation to JSON. * @returns JSON object */ public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for Annotation + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; } - /** Properties of a DocumentTransform. */ - interface IDocumentTransform { + namespace Annotation { - /** DocumentTransform document */ - document?: (string|null); + /** Semantic enum. */ + type Semantic = + "NONE"| "SET"| "ALIAS"; + } + } + + /** Properties of a Struct. */ + interface IStruct { + + /** Struct fields */ + fields?: ({ [k: string]: google.protobuf.IValue }|null); + } + + /** Represents a Struct. */ + class Struct implements IStruct { + + /** + * Constructs a new Struct. + * @param [properties] Properties to set + */ + constructor(properties?: google.protobuf.IStruct); + + /** Struct fields. */ + public fields: { [k: string]: google.protobuf.IValue }; + + /** + * Creates a Struct message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns Struct + */ + public static fromObject(object: { [k: string]: any }): google.protobuf.Struct; + + /** + * Creates a plain object from a Struct message. Also converts values to other types if specified. + * @param message Struct + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.protobuf.Struct, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this Struct to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for Struct + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } - /** DocumentTransform fieldTransforms */ - fieldTransforms?: (google.firestore.v1.DocumentTransform.IFieldTransform[]|null); - } + /** Properties of a Value. */ + interface IValue { - /** Represents a DocumentTransform. */ - class DocumentTransform implements IDocumentTransform { + /** Value nullValue */ + nullValue?: (google.protobuf.NullValue|null); - /** - * Constructs a new DocumentTransform. - * @param [properties] Properties to set - */ - constructor(properties?: google.firestore.v1.IDocumentTransform); + /** Value numberValue */ + numberValue?: (number|null); - /** DocumentTransform document. */ - public document: string; + /** Value stringValue */ + stringValue?: (string|null); - /** DocumentTransform fieldTransforms. */ - public fieldTransforms: google.firestore.v1.DocumentTransform.IFieldTransform[]; + /** Value boolValue */ + boolValue?: (boolean|null); - /** - * Creates a DocumentTransform message from a plain object. Also converts values to their respective internal types. - * @param object Plain object - * @returns DocumentTransform - */ - public static fromObject(object: { [k: string]: any }): google.firestore.v1.DocumentTransform; + /** Value structValue */ + structValue?: (google.protobuf.IStruct|null); - /** - * Creates a plain object from a DocumentTransform message. Also converts values to other types if specified. - * @param message DocumentTransform - * @param [options] Conversion options - * @returns Plain object - */ - public static toObject(message: google.firestore.v1.DocumentTransform, options?: $protobuf.IConversionOptions): { [k: string]: any }; + /** Value listValue */ + listValue?: (google.protobuf.IListValue|null); + } - /** - * Converts this DocumentTransform to JSON. - * @returns JSON object - */ - public toJSON(): { [k: string]: any }; - } + /** Represents a Value. */ + class Value implements IValue { - namespace DocumentTransform { + /** + * Constructs a new Value. + * @param [properties] Properties to set + */ + constructor(properties?: google.protobuf.IValue); - /** Properties of a FieldTransform. */ - interface IFieldTransform { + /** Value nullValue. */ + public nullValue?: (google.protobuf.NullValue|null); - /** FieldTransform fieldPath */ - fieldPath?: (string|null); + /** Value numberValue. */ + public numberValue?: (number|null); - /** FieldTransform setToServerValue */ - setToServerValue?: (google.firestore.v1.DocumentTransform.FieldTransform.ServerValue|null); + /** Value stringValue. */ + public stringValue?: (string|null); - /** FieldTransform increment */ - increment?: (google.firestore.v1.IValue|null); + /** Value boolValue. */ + public boolValue?: (boolean|null); - /** FieldTransform maximum */ - maximum?: (google.firestore.v1.IValue|null); + /** Value structValue. */ + public structValue?: (google.protobuf.IStruct|null); - /** FieldTransform minimum */ - minimum?: (google.firestore.v1.IValue|null); + /** Value listValue. */ + public listValue?: (google.protobuf.IListValue|null); - /** FieldTransform appendMissingElements */ - appendMissingElements?: (google.firestore.v1.IArrayValue|null); + /** Value kind. */ + public kind?: ("nullValue"|"numberValue"|"stringValue"|"boolValue"|"structValue"|"listValue"); - /** FieldTransform removeAllFromArray */ - removeAllFromArray?: (google.firestore.v1.IArrayValue|null); - } + /** + * Creates a Value message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns Value + */ + public static fromObject(object: { [k: string]: any }): google.protobuf.Value; - /** Represents a FieldTransform. */ - class FieldTransform implements IFieldTransform { + /** + * Creates a plain object from a Value message. Also converts values to other types if specified. + * @param message Value + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.protobuf.Value, options?: $protobuf.IConversionOptions): { [k: string]: any }; - /** - * Constructs a new FieldTransform. - * @param [properties] Properties to set - */ - constructor(properties?: google.firestore.v1.DocumentTransform.IFieldTransform); + /** + * Converts this Value to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; - /** FieldTransform fieldPath. */ - public fieldPath: string; + /** + * Gets the default type url for Value + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } - /** FieldTransform setToServerValue. */ - public setToServerValue?: (google.firestore.v1.DocumentTransform.FieldTransform.ServerValue|null); + /** NullValue enum. */ + type NullValue = + "NULL_VALUE"; - /** FieldTransform increment. */ - public increment?: (google.firestore.v1.IValue|null); + /** Properties of a ListValue. */ + interface IListValue { - /** FieldTransform maximum. */ - public maximum?: (google.firestore.v1.IValue|null); + /** ListValue values */ + values?: (google.protobuf.IValue[]|null); + } - /** FieldTransform minimum. */ - public minimum?: (google.firestore.v1.IValue|null); + /** Represents a ListValue. */ + class ListValue implements IListValue { - /** FieldTransform appendMissingElements. */ - public appendMissingElements?: (google.firestore.v1.IArrayValue|null); + /** + * Constructs a new ListValue. + * @param [properties] Properties to set + */ + constructor(properties?: google.protobuf.IListValue); - /** FieldTransform removeAllFromArray. */ - public removeAllFromArray?: (google.firestore.v1.IArrayValue|null); + /** ListValue values. */ + public values: google.protobuf.IValue[]; - /** FieldTransform transformType. */ - public transformType?: ("setToServerValue"|"increment"|"maximum"|"minimum"|"appendMissingElements"|"removeAllFromArray"); + /** + * Creates a ListValue message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns ListValue + */ + public static fromObject(object: { [k: string]: any }): google.protobuf.ListValue; - /** - * Creates a FieldTransform message from a plain object. Also converts values to their respective internal types. - * @param object Plain object - * @returns FieldTransform - */ - public static fromObject(object: { [k: string]: any }): google.firestore.v1.DocumentTransform.FieldTransform; + /** + * Creates a plain object from a ListValue message. Also converts values to other types if specified. + * @param message ListValue + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.protobuf.ListValue, options?: $protobuf.IConversionOptions): { [k: string]: any }; - /** - * Creates a plain object from a FieldTransform message. Also converts values to other types if specified. - * @param message FieldTransform - * @param [options] Conversion options - * @returns Plain object - */ - public static toObject(message: google.firestore.v1.DocumentTransform.FieldTransform, options?: $protobuf.IConversionOptions): { [k: string]: any }; + /** + * Converts this ListValue to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; - /** - * Converts this FieldTransform to JSON. - * @returns JSON object - */ - public toJSON(): { [k: string]: any }; - } + /** + * Gets the default type url for ListValue + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } - namespace FieldTransform { + /** Properties of a Timestamp. */ + interface ITimestamp { - /** ServerValue enum. */ - type ServerValue = - "SERVER_VALUE_UNSPECIFIED"| "REQUEST_TIME"; - } - } + /** Timestamp seconds */ + seconds?: (number|string|null); - /** Properties of a WriteResult. */ - interface IWriteResult { + /** Timestamp nanos */ + nanos?: (number|null); + } - /** WriteResult updateTime */ - updateTime?: (google.protobuf.ITimestamp|null); + /** Represents a Timestamp. */ + class Timestamp implements ITimestamp { - /** WriteResult transformResults */ - transformResults?: (google.firestore.v1.IValue[]|null); - } + /** + * Constructs a new Timestamp. + * @param [properties] Properties to set + */ + constructor(properties?: google.protobuf.ITimestamp); - /** Represents a WriteResult. */ - class WriteResult implements IWriteResult { + /** Timestamp seconds. */ + public seconds: (number|string); - /** - * Constructs a new WriteResult. - * @param [properties] Properties to set - */ - constructor(properties?: google.firestore.v1.IWriteResult); + /** Timestamp nanos. */ + public nanos: number; - /** WriteResult updateTime. */ - public updateTime?: (google.protobuf.ITimestamp|null); + /** + * Creates a Timestamp message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns Timestamp + */ + public static fromObject(object: { [k: string]: any }): google.protobuf.Timestamp; - /** WriteResult transformResults. */ - public transformResults: google.firestore.v1.IValue[]; + /** + * Creates a plain object from a Timestamp message. Also converts values to other types if specified. + * @param message Timestamp + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.protobuf.Timestamp, options?: $protobuf.IConversionOptions): { [k: string]: any }; - /** - * Creates a WriteResult message from a plain object. Also converts values to their respective internal types. - * @param object Plain object - * @returns WriteResult - */ - public static fromObject(object: { [k: string]: any }): google.firestore.v1.WriteResult; + /** + * Converts this Timestamp to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; - /** - * Creates a plain object from a WriteResult message. Also converts values to other types if specified. - * @param message WriteResult - * @param [options] Conversion options - * @returns Plain object - */ - public static toObject(message: google.firestore.v1.WriteResult, options?: $protobuf.IConversionOptions): { [k: string]: any }; + /** + * Gets the default type url for Timestamp + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } - /** - * Converts this WriteResult to JSON. - * @returns JSON object - */ - public toJSON(): { [k: string]: any }; - } + /** Properties of a Duration. */ + interface IDuration { - /** Properties of a DocumentChange. */ - interface IDocumentChange { + /** Duration seconds */ + seconds?: (number|string|null); - /** DocumentChange document */ - document?: (google.firestore.v1.IDocument|null); + /** Duration nanos */ + nanos?: (number|null); + } - /** DocumentChange targetIds */ - targetIds?: (number[]|null); + /** Represents a Duration. */ + class Duration implements IDuration { - /** DocumentChange removedTargetIds */ - removedTargetIds?: (number[]|null); - } + /** + * Constructs a new Duration. + * @param [properties] Properties to set + */ + constructor(properties?: google.protobuf.IDuration); - /** Represents a DocumentChange. */ - class DocumentChange implements IDocumentChange { + /** Duration seconds. */ + public seconds: (number|string); - /** - * Constructs a new DocumentChange. - * @param [properties] Properties to set - */ - constructor(properties?: google.firestore.v1.IDocumentChange); + /** Duration nanos. */ + public nanos: number; - /** DocumentChange document. */ - public document?: (google.firestore.v1.IDocument|null); + /** + * Creates a Duration message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns Duration + */ + public static fromObject(object: { [k: string]: any }): google.protobuf.Duration; - /** DocumentChange targetIds. */ - public targetIds: number[]; + /** + * Creates a plain object from a Duration message. Also converts values to other types if specified. + * @param message Duration + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.protobuf.Duration, options?: $protobuf.IConversionOptions): { [k: string]: any }; - /** DocumentChange removedTargetIds. */ - public removedTargetIds: number[]; + /** + * Converts this Duration to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; - /** - * Creates a DocumentChange message from a plain object. Also converts values to their respective internal types. - * @param object Plain object - * @returns DocumentChange - */ - public static fromObject(object: { [k: string]: any }): google.firestore.v1.DocumentChange; + /** + * Gets the default type url for Duration + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } - /** - * Creates a plain object from a DocumentChange message. Also converts values to other types if specified. - * @param message DocumentChange - * @param [options] Conversion options - * @returns Plain object - */ - public static toObject(message: google.firestore.v1.DocumentChange, options?: $protobuf.IConversionOptions): { [k: string]: any }; + /** Properties of a DoubleValue. */ + interface IDoubleValue { - /** - * Converts this DocumentChange to JSON. - * @returns JSON object - */ - public toJSON(): { [k: string]: any }; - } + /** DoubleValue value */ + value?: (number|null); + } - /** Properties of a DocumentDelete. */ - interface IDocumentDelete { + /** Represents a DoubleValue. */ + class DoubleValue implements IDoubleValue { - /** DocumentDelete document */ - document?: (string|null); + /** + * Constructs a new DoubleValue. + * @param [properties] Properties to set + */ + constructor(properties?: google.protobuf.IDoubleValue); - /** DocumentDelete removedTargetIds */ - removedTargetIds?: (number[]|null); + /** DoubleValue value. */ + public value: number; - /** DocumentDelete readTime */ - readTime?: (google.protobuf.ITimestamp|null); - } + /** + * Creates a DoubleValue message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns DoubleValue + */ + public static fromObject(object: { [k: string]: any }): google.protobuf.DoubleValue; - /** Represents a DocumentDelete. */ - class DocumentDelete implements IDocumentDelete { + /** + * Creates a plain object from a DoubleValue message. Also converts values to other types if specified. + * @param message DoubleValue + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.protobuf.DoubleValue, options?: $protobuf.IConversionOptions): { [k: string]: any }; - /** - * Constructs a new DocumentDelete. - * @param [properties] Properties to set - */ - constructor(properties?: google.firestore.v1.IDocumentDelete); + /** + * Converts this DoubleValue to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; - /** DocumentDelete document. */ - public document: string; + /** + * Gets the default type url for DoubleValue + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } - /** DocumentDelete removedTargetIds. */ - public removedTargetIds: number[]; + /** Properties of a FloatValue. */ + interface IFloatValue { - /** DocumentDelete readTime. */ - public readTime?: (google.protobuf.ITimestamp|null); + /** FloatValue value */ + value?: (number|null); + } - /** - * Creates a DocumentDelete message from a plain object. Also converts values to their respective internal types. - * @param object Plain object - * @returns DocumentDelete - */ - public static fromObject(object: { [k: string]: any }): google.firestore.v1.DocumentDelete; + /** Represents a FloatValue. */ + class FloatValue implements IFloatValue { - /** - * Creates a plain object from a DocumentDelete message. Also converts values to other types if specified. - * @param message DocumentDelete - * @param [options] Conversion options - * @returns Plain object - */ - public static toObject(message: google.firestore.v1.DocumentDelete, options?: $protobuf.IConversionOptions): { [k: string]: any }; + /** + * Constructs a new FloatValue. + * @param [properties] Properties to set + */ + constructor(properties?: google.protobuf.IFloatValue); - /** - * Converts this DocumentDelete to JSON. - * @returns JSON object - */ - public toJSON(): { [k: string]: any }; - } + /** FloatValue value. */ + public value: number; - /** Properties of a DocumentRemove. */ - interface IDocumentRemove { + /** + * Creates a FloatValue message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns FloatValue + */ + public static fromObject(object: { [k: string]: any }): google.protobuf.FloatValue; - /** DocumentRemove document */ - document?: (string|null); + /** + * Creates a plain object from a FloatValue message. Also converts values to other types if specified. + * @param message FloatValue + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.protobuf.FloatValue, options?: $protobuf.IConversionOptions): { [k: string]: any }; - /** DocumentRemove removedTargetIds */ - removedTargetIds?: (number[]|null); + /** + * Converts this FloatValue to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; - /** DocumentRemove readTime */ - readTime?: (google.protobuf.ITimestamp|null); - } + /** + * Gets the default type url for FloatValue + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } - /** Represents a DocumentRemove. */ - class DocumentRemove implements IDocumentRemove { + /** Properties of an Int64Value. */ + interface IInt64Value { - /** - * Constructs a new DocumentRemove. - * @param [properties] Properties to set - */ - constructor(properties?: google.firestore.v1.IDocumentRemove); + /** Int64Value value */ + value?: (number|string|null); + } - /** DocumentRemove document. */ - public document: string; + /** Represents an Int64Value. */ + class Int64Value implements IInt64Value { - /** DocumentRemove removedTargetIds. */ - public removedTargetIds: number[]; + /** + * Constructs a new Int64Value. + * @param [properties] Properties to set + */ + constructor(properties?: google.protobuf.IInt64Value); - /** DocumentRemove readTime. */ - public readTime?: (google.protobuf.ITimestamp|null); + /** Int64Value value. */ + public value: (number|string); - /** - * Creates a DocumentRemove message from a plain object. Also converts values to their respective internal types. - * @param object Plain object - * @returns DocumentRemove - */ - public static fromObject(object: { [k: string]: any }): google.firestore.v1.DocumentRemove; + /** + * Creates an Int64Value message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns Int64Value + */ + public static fromObject(object: { [k: string]: any }): google.protobuf.Int64Value; - /** - * Creates a plain object from a DocumentRemove message. Also converts values to other types if specified. - * @param message DocumentRemove - * @param [options] Conversion options - * @returns Plain object - */ - public static toObject(message: google.firestore.v1.DocumentRemove, options?: $protobuf.IConversionOptions): { [k: string]: any }; + /** + * Creates a plain object from an Int64Value message. Also converts values to other types if specified. + * @param message Int64Value + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.protobuf.Int64Value, options?: $protobuf.IConversionOptions): { [k: string]: any }; - /** - * Converts this DocumentRemove to JSON. - * @returns JSON object - */ - public toJSON(): { [k: string]: any }; - } + /** + * Converts this Int64Value to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; - /** Properties of an ExistenceFilter. */ - interface IExistenceFilter { + /** + * Gets the default type url for Int64Value + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } - /** ExistenceFilter targetId */ - targetId?: (number|null); + /** Properties of a UInt64Value. */ + interface IUInt64Value { - /** ExistenceFilter count */ - count?: (number|null); - } + /** UInt64Value value */ + value?: (number|string|null); + } - /** Represents an ExistenceFilter. */ - class ExistenceFilter implements IExistenceFilter { + /** Represents a UInt64Value. */ + class UInt64Value implements IUInt64Value { - /** - * Constructs a new ExistenceFilter. - * @param [properties] Properties to set - */ - constructor(properties?: google.firestore.v1.IExistenceFilter); + /** + * Constructs a new UInt64Value. + * @param [properties] Properties to set + */ + constructor(properties?: google.protobuf.IUInt64Value); - /** ExistenceFilter targetId. */ - public targetId: number; + /** UInt64Value value. */ + public value: (number|string); - /** ExistenceFilter count. */ - public count: number; + /** + * Creates a UInt64Value message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns UInt64Value + */ + public static fromObject(object: { [k: string]: any }): google.protobuf.UInt64Value; - /** - * Creates an ExistenceFilter message from a plain object. Also converts values to their respective internal types. - * @param object Plain object - * @returns ExistenceFilter - */ - public static fromObject(object: { [k: string]: any }): google.firestore.v1.ExistenceFilter; + /** + * Creates a plain object from a UInt64Value message. Also converts values to other types if specified. + * @param message UInt64Value + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.protobuf.UInt64Value, options?: $protobuf.IConversionOptions): { [k: string]: any }; - /** - * Creates a plain object from an ExistenceFilter message. Also converts values to other types if specified. - * @param message ExistenceFilter - * @param [options] Conversion options - * @returns Plain object - */ - public static toObject(message: google.firestore.v1.ExistenceFilter, options?: $protobuf.IConversionOptions): { [k: string]: any }; + /** + * Converts this UInt64Value to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; - /** - * Converts this ExistenceFilter to JSON. - * @returns JSON object - */ - public toJSON(): { [k: string]: any }; - } + /** + * Gets the default type url for UInt64Value + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; } - } - /** Namespace api. */ - namespace api { - - /** Properties of a Http. */ - interface IHttp { + /** Properties of an Int32Value. */ + interface IInt32Value { - /** Http rules */ - rules?: (google.api.IHttpRule[]|null); + /** Int32Value value */ + value?: (number|null); } - /** Represents a Http. */ - class Http implements IHttp { + /** Represents an Int32Value. */ + class Int32Value implements IInt32Value { /** - * Constructs a new Http. + * Constructs a new Int32Value. * @param [properties] Properties to set */ - constructor(properties?: google.api.IHttp); + constructor(properties?: google.protobuf.IInt32Value); - /** Http rules. */ - public rules: google.api.IHttpRule[]; + /** Int32Value value. */ + public value: number; /** - * Creates a Http message from a plain object. Also converts values to their respective internal types. + * Creates an Int32Value message from a plain object. Also converts values to their respective internal types. * @param object Plain object - * @returns Http + * @returns Int32Value */ - public static fromObject(object: { [k: string]: any }): google.api.Http; + public static fromObject(object: { [k: string]: any }): google.protobuf.Int32Value; /** - * Creates a plain object from a Http message. Also converts values to other types if specified. - * @param message Http + * Creates a plain object from an Int32Value message. Also converts values to other types if specified. + * @param message Int32Value * @param [options] Conversion options * @returns Plain object */ - public static toObject(message: google.api.Http, options?: $protobuf.IConversionOptions): { [k: string]: any }; + public static toObject(message: google.protobuf.Int32Value, options?: $protobuf.IConversionOptions): { [k: string]: any }; /** - * Converts this Http to JSON. + * Converts this Int32Value to JSON. * @returns JSON object */ public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for Int32Value + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; } - /** Properties of a HttpRule. */ - interface IHttpRule { + /** Properties of a UInt32Value. */ + interface IUInt32Value { - /** HttpRule get */ - get?: (string|null); + /** UInt32Value value */ + value?: (number|null); + } - /** HttpRule put */ - put?: (string|null); + /** Represents a UInt32Value. */ + class UInt32Value implements IUInt32Value { - /** HttpRule post */ - post?: (string|null); + /** + * Constructs a new UInt32Value. + * @param [properties] Properties to set + */ + constructor(properties?: google.protobuf.IUInt32Value); - /** HttpRule delete */ - "delete"?: (string|null); + /** UInt32Value value. */ + public value: number; - /** HttpRule patch */ - patch?: (string|null); + /** + * Creates a UInt32Value message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns UInt32Value + */ + public static fromObject(object: { [k: string]: any }): google.protobuf.UInt32Value; - /** HttpRule custom */ - custom?: (google.api.ICustomHttpPattern|null); + /** + * Creates a plain object from a UInt32Value message. Also converts values to other types if specified. + * @param message UInt32Value + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.protobuf.UInt32Value, options?: $protobuf.IConversionOptions): { [k: string]: any }; - /** HttpRule selector */ - selector?: (string|null); + /** + * Converts this UInt32Value to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; - /** HttpRule body */ - body?: (string|null); + /** + * Gets the default type url for UInt32Value + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } - /** HttpRule additionalBindings */ - additionalBindings?: (google.api.IHttpRule[]|null); + /** Properties of a BoolValue. */ + interface IBoolValue { + + /** BoolValue value */ + value?: (boolean|null); } - /** Represents a HttpRule. */ - class HttpRule implements IHttpRule { + /** Represents a BoolValue. */ + class BoolValue implements IBoolValue { /** - * Constructs a new HttpRule. + * Constructs a new BoolValue. * @param [properties] Properties to set */ - constructor(properties?: google.api.IHttpRule); + constructor(properties?: google.protobuf.IBoolValue); - /** HttpRule get. */ - public get?: (string|null); + /** BoolValue value. */ + public value: boolean; - /** HttpRule put. */ - public put?: (string|null); + /** + * Creates a BoolValue message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns BoolValue + */ + public static fromObject(object: { [k: string]: any }): google.protobuf.BoolValue; - /** HttpRule post. */ - public post?: (string|null); + /** + * Creates a plain object from a BoolValue message. Also converts values to other types if specified. + * @param message BoolValue + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.protobuf.BoolValue, options?: $protobuf.IConversionOptions): { [k: string]: any }; - /** HttpRule delete. */ - public delete?: (string|null); + /** + * Converts this BoolValue to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; - /** HttpRule patch. */ - public patch?: (string|null); + /** + * Gets the default type url for BoolValue + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } - /** HttpRule custom. */ - public custom?: (google.api.ICustomHttpPattern|null); + /** Properties of a StringValue. */ + interface IStringValue { - /** HttpRule selector. */ - public selector: string; + /** StringValue value */ + value?: (string|null); + } - /** HttpRule body. */ - public body: string; + /** Represents a StringValue. */ + class StringValue implements IStringValue { - /** HttpRule additionalBindings. */ - public additionalBindings: google.api.IHttpRule[]; + /** + * Constructs a new StringValue. + * @param [properties] Properties to set + */ + constructor(properties?: google.protobuf.IStringValue); - /** HttpRule pattern. */ - public pattern?: ("get"|"put"|"post"|"delete"|"patch"|"custom"); + /** StringValue value. */ + public value: string; /** - * Creates a HttpRule message from a plain object. Also converts values to their respective internal types. + * Creates a StringValue message from a plain object. Also converts values to their respective internal types. * @param object Plain object - * @returns HttpRule + * @returns StringValue */ - public static fromObject(object: { [k: string]: any }): google.api.HttpRule; + public static fromObject(object: { [k: string]: any }): google.protobuf.StringValue; /** - * Creates a plain object from a HttpRule message. Also converts values to other types if specified. - * @param message HttpRule + * Creates a plain object from a StringValue message. Also converts values to other types if specified. + * @param message StringValue * @param [options] Conversion options * @returns Plain object */ - public static toObject(message: google.api.HttpRule, options?: $protobuf.IConversionOptions): { [k: string]: any }; + public static toObject(message: google.protobuf.StringValue, options?: $protobuf.IConversionOptions): { [k: string]: any }; /** - * Converts this HttpRule to JSON. + * Converts this StringValue to JSON. * @returns JSON object */ public toJSON(): { [k: string]: any }; - } - /** Properties of a CustomHttpPattern. */ - interface ICustomHttpPattern { + /** + * Gets the default type url for StringValue + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } - /** CustomHttpPattern kind */ - kind?: (string|null); + /** Properties of a BytesValue. */ + interface IBytesValue { - /** CustomHttpPattern path */ - path?: (string|null); + /** BytesValue value */ + value?: (Uint8Array|null); } - /** Represents a CustomHttpPattern. */ - class CustomHttpPattern implements ICustomHttpPattern { + /** Represents a BytesValue. */ + class BytesValue implements IBytesValue { /** - * Constructs a new CustomHttpPattern. + * Constructs a new BytesValue. * @param [properties] Properties to set */ - constructor(properties?: google.api.ICustomHttpPattern); - - /** CustomHttpPattern kind. */ - public kind: string; + constructor(properties?: google.protobuf.IBytesValue); - /** CustomHttpPattern path. */ - public path: string; + /** BytesValue value. */ + public value: Uint8Array; /** - * Creates a CustomHttpPattern message from a plain object. Also converts values to their respective internal types. + * Creates a BytesValue message from a plain object. Also converts values to their respective internal types. * @param object Plain object - * @returns CustomHttpPattern + * @returns BytesValue */ - public static fromObject(object: { [k: string]: any }): google.api.CustomHttpPattern; + public static fromObject(object: { [k: string]: any }): google.protobuf.BytesValue; /** - * Creates a plain object from a CustomHttpPattern message. Also converts values to other types if specified. - * @param message CustomHttpPattern + * Creates a plain object from a BytesValue message. Also converts values to other types if specified. + * @param message BytesValue * @param [options] Conversion options * @returns Plain object */ - public static toObject(message: google.api.CustomHttpPattern, options?: $protobuf.IConversionOptions): { [k: string]: any }; + public static toObject(message: google.protobuf.BytesValue, options?: $protobuf.IConversionOptions): { [k: string]: any }; /** - * Converts this CustomHttpPattern to JSON. + * Converts this BytesValue to JSON. * @returns JSON object */ public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for BytesValue + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; } - /** FieldBehavior enum. */ - type FieldBehavior = - "FIELD_BEHAVIOR_UNSPECIFIED"| "OPTIONAL"| "REQUIRED"| "OUTPUT_ONLY"| "INPUT_ONLY"| "IMMUTABLE"| "UNORDERED_LIST"| "NON_EMPTY_DEFAULT"; + /** Properties of an Empty. */ + interface IEmpty { + } - /** Properties of a ResourceDescriptor. */ - interface IResourceDescriptor { + /** Represents an Empty. */ + class Empty implements IEmpty { - /** ResourceDescriptor type */ - type?: (string|null); + /** + * Constructs a new Empty. + * @param [properties] Properties to set + */ + constructor(properties?: google.protobuf.IEmpty); - /** ResourceDescriptor pattern */ - pattern?: (string[]|null); + /** + * Creates an Empty message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns Empty + */ + public static fromObject(object: { [k: string]: any }): google.protobuf.Empty; - /** ResourceDescriptor nameField */ - nameField?: (string|null); + /** + * Creates a plain object from an Empty message. Also converts values to other types if specified. + * @param message Empty + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.protobuf.Empty, options?: $protobuf.IConversionOptions): { [k: string]: any }; - /** ResourceDescriptor history */ - history?: (google.api.ResourceDescriptor.History|null); + /** + * Converts this Empty to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; - /** ResourceDescriptor plural */ - plural?: (string|null); + /** + * Gets the default type url for Empty + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } - /** ResourceDescriptor singular */ - singular?: (string|null); + /** Properties of an Any. */ + interface IAny { - /** ResourceDescriptor style */ - style?: (google.api.ResourceDescriptor.Style[]|null); + /** Any type_url */ + type_url?: (string|null); + + /** Any value */ + value?: (Uint8Array|null); } - /** Represents a ResourceDescriptor. */ - class ResourceDescriptor implements IResourceDescriptor { + /** Represents an Any. */ + class Any implements IAny { /** - * Constructs a new ResourceDescriptor. + * Constructs a new Any. * @param [properties] Properties to set */ - constructor(properties?: google.api.IResourceDescriptor); - - /** ResourceDescriptor type. */ - public type: string; - - /** ResourceDescriptor pattern. */ - public pattern: string[]; - - /** ResourceDescriptor nameField. */ - public nameField: string; - - /** ResourceDescriptor history. */ - public history: google.api.ResourceDescriptor.History; - - /** ResourceDescriptor plural. */ - public plural: string; + constructor(properties?: google.protobuf.IAny); - /** ResourceDescriptor singular. */ - public singular: string; + /** Any type_url. */ + public type_url: string; - /** ResourceDescriptor style. */ - public style: google.api.ResourceDescriptor.Style[]; + /** Any value. */ + public value: Uint8Array; /** - * Creates a ResourceDescriptor message from a plain object. Also converts values to their respective internal types. + * Creates an Any message from a plain object. Also converts values to their respective internal types. * @param object Plain object - * @returns ResourceDescriptor + * @returns Any */ - public static fromObject(object: { [k: string]: any }): google.api.ResourceDescriptor; + public static fromObject(object: { [k: string]: any }): google.protobuf.Any; /** - * Creates a plain object from a ResourceDescriptor message. Also converts values to other types if specified. - * @param message ResourceDescriptor + * Creates a plain object from an Any message. Also converts values to other types if specified. + * @param message Any * @param [options] Conversion options * @returns Plain object */ - public static toObject(message: google.api.ResourceDescriptor, options?: $protobuf.IConversionOptions): { [k: string]: any }; + public static toObject(message: google.protobuf.Any, options?: $protobuf.IConversionOptions): { [k: string]: any }; /** - * Converts this ResourceDescriptor to JSON. + * Converts this Any to JSON. * @returns JSON object */ public toJSON(): { [k: string]: any }; - } - - namespace ResourceDescriptor { - - /** History enum. */ - type History = - "HISTORY_UNSPECIFIED"| "ORIGINALLY_SINGLE_PATTERN"| "FUTURE_MULTI_PATTERN"; - /** Style enum. */ - type Style = - "STYLE_UNSPECIFIED"| "DECLARATIVE_FRIENDLY"; + /** + * Gets the default type url for Any + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; } - /** Properties of a ResourceReference. */ - interface IResourceReference { - - /** ResourceReference type */ - type?: (string|null); + /** Properties of a FieldMask. */ + interface IFieldMask { - /** ResourceReference childType */ - childType?: (string|null); + /** FieldMask paths */ + paths?: (string[]|null); } - /** Represents a ResourceReference. */ - class ResourceReference implements IResourceReference { + /** Represents a FieldMask. */ + class FieldMask implements IFieldMask { /** - * Constructs a new ResourceReference. + * Constructs a new FieldMask. * @param [properties] Properties to set */ - constructor(properties?: google.api.IResourceReference); - - /** ResourceReference type. */ - public type: string; + constructor(properties?: google.protobuf.IFieldMask); - /** ResourceReference childType. */ - public childType: string; + /** FieldMask paths. */ + public paths: string[]; /** - * Creates a ResourceReference message from a plain object. Also converts values to their respective internal types. + * Creates a FieldMask message from a plain object. Also converts values to their respective internal types. * @param object Plain object - * @returns ResourceReference + * @returns FieldMask */ - public static fromObject(object: { [k: string]: any }): google.api.ResourceReference; + public static fromObject(object: { [k: string]: any }): google.protobuf.FieldMask; /** - * Creates a plain object from a ResourceReference message. Also converts values to other types if specified. - * @param message ResourceReference + * Creates a plain object from a FieldMask message. Also converts values to other types if specified. + * @param message FieldMask * @param [options] Conversion options * @returns Plain object */ - public static toObject(message: google.api.ResourceReference, options?: $protobuf.IConversionOptions): { [k: string]: any }; + public static toObject(message: google.protobuf.FieldMask, options?: $protobuf.IConversionOptions): { [k: string]: any }; /** - * Converts this ResourceReference to JSON. + * Converts this FieldMask to JSON. * @returns JSON object */ public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for FieldMask + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; } } @@ -6555,7 +9797,18 @@ export namespace google { * @returns JSON object */ public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for LatLng + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; } + + /** DayOfWeek enum. */ + type DayOfWeek = + "DAY_OF_WEEK_UNSPECIFIED"| "MONDAY"| "TUESDAY"| "WEDNESDAY"| "THURSDAY"| "FRIDAY"| "SATURDAY"| "SUNDAY"; } /** Namespace rpc. */ @@ -6612,6 +9865,13 @@ export namespace google { * @returns JSON object */ public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for Status + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; } } @@ -6804,6 +10064,13 @@ export namespace google { * @returns JSON object */ public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for Operation + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; } /** Properties of a GetOperationRequest. */ @@ -6845,6 +10112,13 @@ export namespace google { * @returns JSON object */ public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for GetOperationRequest + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; } /** Properties of a ListOperationsRequest. */ @@ -6904,6 +10178,13 @@ export namespace google { * @returns JSON object */ public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for ListOperationsRequest + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; } /** Properties of a ListOperationsResponse. */ @@ -6951,6 +10232,13 @@ export namespace google { * @returns JSON object */ public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for ListOperationsResponse + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; } /** Properties of a CancelOperationRequest. */ @@ -6992,6 +10280,13 @@ export namespace google { * @returns JSON object */ public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for CancelOperationRequest + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; } /** Properties of a DeleteOperationRequest. */ @@ -7033,6 +10328,13 @@ export namespace google { * @returns JSON object */ public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for DeleteOperationRequest + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; } /** Properties of a WaitOperationRequest. */ @@ -7080,6 +10382,13 @@ export namespace google { * @returns JSON object */ public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for WaitOperationRequest + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; } /** Properties of an OperationInfo. */ @@ -7127,6 +10436,13 @@ export namespace google { * @returns JSON object */ public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for OperationInfo + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; } } } diff --git a/types/protos/firestore_v1beta1_proto_api.d.ts b/types/protos/firestore_v1beta1_proto_api.d.ts index 6cf8959a8..1a37aaa0e 100644 --- a/types/protos/firestore_v1beta1_proto_api.d.ts +++ b/types/protos/firestore_v1beta1_proto_api.d.ts @@ -1,5 +1,5 @@ /*! - * Copyright 2022 Google LLC + * 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. @@ -15,6 +15,7 @@ */ import * as $protobuf from "protobufjs"; +import Long = require("long"); /** Namespace google. */ export namespace google { @@ -66,6 +67,194 @@ export namespace google { * @returns JSON object */ public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for Timestamp + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a Struct. */ + interface IStruct { + + /** Struct fields */ + fields?: ({ [k: string]: google.protobuf.IValue }|null); + } + + /** Represents a Struct. */ + class Struct implements IStruct { + + /** + * Constructs a new Struct. + * @param [properties] Properties to set + */ + constructor(properties?: google.protobuf.IStruct); + + /** Struct fields. */ + public fields: { [k: string]: google.protobuf.IValue }; + + /** + * Creates a Struct message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns Struct + */ + public static fromObject(object: { [k: string]: any }): google.protobuf.Struct; + + /** + * Creates a plain object from a Struct message. Also converts values to other types if specified. + * @param message Struct + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.protobuf.Struct, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this Struct to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for Struct + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a Value. */ + interface IValue { + + /** Value nullValue */ + nullValue?: (google.protobuf.NullValue|null); + + /** Value numberValue */ + numberValue?: (number|null); + + /** Value stringValue */ + stringValue?: (string|null); + + /** Value boolValue */ + boolValue?: (boolean|null); + + /** Value structValue */ + structValue?: (google.protobuf.IStruct|null); + + /** Value listValue */ + listValue?: (google.protobuf.IListValue|null); + } + + /** Represents a Value. */ + class Value implements IValue { + + /** + * Constructs a new Value. + * @param [properties] Properties to set + */ + constructor(properties?: google.protobuf.IValue); + + /** Value nullValue. */ + public nullValue?: (google.protobuf.NullValue|null); + + /** Value numberValue. */ + public numberValue?: (number|null); + + /** Value stringValue. */ + public stringValue?: (string|null); + + /** Value boolValue. */ + public boolValue?: (boolean|null); + + /** Value structValue. */ + public structValue?: (google.protobuf.IStruct|null); + + /** Value listValue. */ + public listValue?: (google.protobuf.IListValue|null); + + /** Value kind. */ + public kind?: ("nullValue"|"numberValue"|"stringValue"|"boolValue"|"structValue"|"listValue"); + + /** + * Creates a Value message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns Value + */ + public static fromObject(object: { [k: string]: any }): google.protobuf.Value; + + /** + * Creates a plain object from a Value message. Also converts values to other types if specified. + * @param message Value + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.protobuf.Value, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this Value to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for Value + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** NullValue enum. */ + type NullValue = + "NULL_VALUE"; + + /** Properties of a ListValue. */ + interface IListValue { + + /** ListValue values */ + values?: (google.protobuf.IValue[]|null); + } + + /** Represents a ListValue. */ + class ListValue implements IListValue { + + /** + * Constructs a new ListValue. + * @param [properties] Properties to set + */ + constructor(properties?: google.protobuf.IListValue); + + /** ListValue values. */ + public values: google.protobuf.IValue[]; + + /** + * Creates a ListValue message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns ListValue + */ + public static fromObject(object: { [k: string]: any }): google.protobuf.ListValue; + + /** + * Creates a plain object from a ListValue message. Also converts values to other types if specified. + * @param message ListValue + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.protobuf.ListValue, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this ListValue to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for ListValue + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; } /** Properties of a FileDescriptorSet. */ @@ -107,8 +296,19 @@ export namespace google { * @returns JSON object */ public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for FileDescriptorSet + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; } + /** Edition enum. */ + type Edition = + "EDITION_UNKNOWN"| "EDITION_PROTO2"| "EDITION_PROTO3"| "EDITION_2023"| "EDITION_2024"| "EDITION_1_TEST_ONLY"| "EDITION_2_TEST_ONLY"| "EDITION_99997_TEST_ONLY"| "EDITION_99998_TEST_ONLY"| "EDITION_99999_TEST_ONLY"| "EDITION_MAX"; + /** Properties of a FileDescriptorProto. */ interface IFileDescriptorProto { @@ -147,6 +347,9 @@ export namespace google { /** FileDescriptorProto syntax */ syntax?: (string|null); + + /** FileDescriptorProto edition */ + edition?: (google.protobuf.Edition|null); } /** Represents a FileDescriptorProto. */ @@ -194,6 +397,9 @@ export namespace google { /** FileDescriptorProto syntax. */ public syntax: string; + /** FileDescriptorProto edition. */ + public edition: google.protobuf.Edition; + /** * Creates a FileDescriptorProto message from a plain object. Also converts values to their respective internal types. * @param object Plain object @@ -214,6 +420,13 @@ export namespace google { * @returns JSON object */ public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for FileDescriptorProto + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; } /** Properties of a DescriptorProto. */ @@ -309,6 +522,13 @@ export namespace google { * @returns JSON object */ public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for DescriptorProto + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; } namespace DescriptorProto { @@ -321,6 +541,9 @@ export namespace google { /** ExtensionRange end */ end?: (number|null); + + /** ExtensionRange options */ + options?: (google.protobuf.IExtensionRangeOptions|null); } /** Represents an ExtensionRange. */ @@ -338,6 +561,9 @@ export namespace google { /** ExtensionRange end. */ public end: number; + /** ExtensionRange options. */ + public options?: (google.protobuf.IExtensionRangeOptions|null); + /** * Creates an ExtensionRange message from a plain object. Also converts values to their respective internal types. * @param object Plain object @@ -358,6 +584,13 @@ export namespace google { * @returns JSON object */ public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for ExtensionRange + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; } /** Properties of a ReservedRange. */ @@ -405,82 +638,240 @@ export namespace google { * @returns JSON object */ public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for ReservedRange + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; } } - /** Properties of a FieldDescriptorProto. */ - interface IFieldDescriptorProto { + /** Properties of an ExtensionRangeOptions. */ + interface IExtensionRangeOptions { - /** FieldDescriptorProto name */ - name?: (string|null); + /** ExtensionRangeOptions uninterpretedOption */ + uninterpretedOption?: (google.protobuf.IUninterpretedOption[]|null); - /** FieldDescriptorProto number */ - number?: (number|null); + /** ExtensionRangeOptions declaration */ + declaration?: (google.protobuf.ExtensionRangeOptions.IDeclaration[]|null); - /** FieldDescriptorProto label */ - label?: (google.protobuf.FieldDescriptorProto.Label|null); + /** ExtensionRangeOptions features */ + features?: (google.protobuf.IFeatureSet|null); - /** FieldDescriptorProto type */ - type?: (google.protobuf.FieldDescriptorProto.Type|null); + /** ExtensionRangeOptions verification */ + verification?: (google.protobuf.ExtensionRangeOptions.VerificationState|null); + } - /** FieldDescriptorProto typeName */ - typeName?: (string|null); + /** Represents an ExtensionRangeOptions. */ + class ExtensionRangeOptions implements IExtensionRangeOptions { - /** FieldDescriptorProto extendee */ - extendee?: (string|null); + /** + * Constructs a new ExtensionRangeOptions. + * @param [properties] Properties to set + */ + constructor(properties?: google.protobuf.IExtensionRangeOptions); - /** FieldDescriptorProto defaultValue */ - defaultValue?: (string|null); + /** ExtensionRangeOptions uninterpretedOption. */ + public uninterpretedOption: google.protobuf.IUninterpretedOption[]; - /** FieldDescriptorProto oneofIndex */ - oneofIndex?: (number|null); + /** ExtensionRangeOptions declaration. */ + public declaration: google.protobuf.ExtensionRangeOptions.IDeclaration[]; - /** FieldDescriptorProto jsonName */ - jsonName?: (string|null); + /** ExtensionRangeOptions features. */ + public features?: (google.protobuf.IFeatureSet|null); - /** FieldDescriptorProto options */ - options?: (google.protobuf.IFieldOptions|null); - } + /** ExtensionRangeOptions verification. */ + public verification: google.protobuf.ExtensionRangeOptions.VerificationState; - /** Represents a FieldDescriptorProto. */ - class FieldDescriptorProto implements IFieldDescriptorProto { + /** + * Creates an ExtensionRangeOptions message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns ExtensionRangeOptions + */ + public static fromObject(object: { [k: string]: any }): google.protobuf.ExtensionRangeOptions; /** - * Constructs a new FieldDescriptorProto. - * @param [properties] Properties to set + * Creates a plain object from an ExtensionRangeOptions message. Also converts values to other types if specified. + * @param message ExtensionRangeOptions + * @param [options] Conversion options + * @returns Plain object */ - constructor(properties?: google.protobuf.IFieldDescriptorProto); + public static toObject(message: google.protobuf.ExtensionRangeOptions, options?: $protobuf.IConversionOptions): { [k: string]: any }; - /** FieldDescriptorProto name. */ - public name: string; + /** + * Converts this ExtensionRangeOptions to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; - /** FieldDescriptorProto number. */ - public number: number; + /** + * Gets the default type url for ExtensionRangeOptions + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } - /** FieldDescriptorProto label. */ - public label: google.protobuf.FieldDescriptorProto.Label; + namespace ExtensionRangeOptions { - /** FieldDescriptorProto type. */ - public type: google.protobuf.FieldDescriptorProto.Type; + /** Properties of a Declaration. */ + interface IDeclaration { - /** FieldDescriptorProto typeName. */ - public typeName: string; + /** Declaration number */ + number?: (number|null); - /** FieldDescriptorProto extendee. */ - public extendee: string; + /** Declaration fullName */ + fullName?: (string|null); - /** FieldDescriptorProto defaultValue. */ - public defaultValue: string; + /** Declaration type */ + type?: (string|null); - /** FieldDescriptorProto oneofIndex. */ - public oneofIndex: number; + /** Declaration reserved */ + reserved?: (boolean|null); - /** FieldDescriptorProto jsonName. */ - public jsonName: string; + /** Declaration repeated */ + repeated?: (boolean|null); + } + + /** Represents a Declaration. */ + class Declaration implements IDeclaration { + + /** + * Constructs a new Declaration. + * @param [properties] Properties to set + */ + constructor(properties?: google.protobuf.ExtensionRangeOptions.IDeclaration); + + /** Declaration number. */ + public number: number; + + /** Declaration fullName. */ + public fullName: string; + + /** Declaration type. */ + public type: string; + + /** Declaration reserved. */ + public reserved: boolean; + + /** Declaration repeated. */ + public repeated: boolean; + + /** + * Creates a Declaration message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns Declaration + */ + public static fromObject(object: { [k: string]: any }): google.protobuf.ExtensionRangeOptions.Declaration; + + /** + * Creates a plain object from a Declaration message. Also converts values to other types if specified. + * @param message Declaration + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.protobuf.ExtensionRangeOptions.Declaration, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this Declaration to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for Declaration + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** VerificationState enum. */ + type VerificationState = + "DECLARATION"| "UNVERIFIED"; + } + + /** Properties of a FieldDescriptorProto. */ + interface IFieldDescriptorProto { + + /** FieldDescriptorProto name */ + name?: (string|null); + + /** FieldDescriptorProto number */ + number?: (number|null); + + /** FieldDescriptorProto label */ + label?: (google.protobuf.FieldDescriptorProto.Label|null); + + /** FieldDescriptorProto type */ + type?: (google.protobuf.FieldDescriptorProto.Type|null); + + /** FieldDescriptorProto typeName */ + typeName?: (string|null); + + /** FieldDescriptorProto extendee */ + extendee?: (string|null); + + /** FieldDescriptorProto defaultValue */ + defaultValue?: (string|null); + + /** FieldDescriptorProto oneofIndex */ + oneofIndex?: (number|null); + + /** FieldDescriptorProto jsonName */ + jsonName?: (string|null); + + /** FieldDescriptorProto options */ + options?: (google.protobuf.IFieldOptions|null); + + /** FieldDescriptorProto proto3Optional */ + proto3Optional?: (boolean|null); + } + + /** Represents a FieldDescriptorProto. */ + class FieldDescriptorProto implements IFieldDescriptorProto { + + /** + * Constructs a new FieldDescriptorProto. + * @param [properties] Properties to set + */ + constructor(properties?: google.protobuf.IFieldDescriptorProto); + + /** FieldDescriptorProto name. */ + public name: string; + + /** FieldDescriptorProto number. */ + public number: number; + + /** FieldDescriptorProto label. */ + public label: google.protobuf.FieldDescriptorProto.Label; + + /** FieldDescriptorProto type. */ + public type: google.protobuf.FieldDescriptorProto.Type; + + /** FieldDescriptorProto typeName. */ + public typeName: string; + + /** FieldDescriptorProto extendee. */ + public extendee: string; + + /** FieldDescriptorProto defaultValue. */ + public defaultValue: string; + + /** FieldDescriptorProto oneofIndex. */ + public oneofIndex: number; + + /** FieldDescriptorProto jsonName. */ + public jsonName: string; /** FieldDescriptorProto options. */ public options?: (google.protobuf.IFieldOptions|null); + /** FieldDescriptorProto proto3Optional. */ + public proto3Optional: boolean; + /** * Creates a FieldDescriptorProto message from a plain object. Also converts values to their respective internal types. * @param object Plain object @@ -501,6 +892,13 @@ export namespace google { * @returns JSON object */ public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for FieldDescriptorProto + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; } namespace FieldDescriptorProto { @@ -511,7 +909,7 @@ export namespace google { /** Label enum. */ type Label = - "LABEL_OPTIONAL"| "LABEL_REQUIRED"| "LABEL_REPEATED"; + "LABEL_OPTIONAL"| "LABEL_REPEATED"| "LABEL_REQUIRED"; } /** Properties of an OneofDescriptorProto. */ @@ -559,6 +957,13 @@ export namespace google { * @returns JSON object */ public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for OneofDescriptorProto + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; } /** Properties of an EnumDescriptorProto. */ @@ -572,6 +977,12 @@ export namespace google { /** EnumDescriptorProto options */ options?: (google.protobuf.IEnumOptions|null); + + /** EnumDescriptorProto reservedRange */ + reservedRange?: (google.protobuf.EnumDescriptorProto.IEnumReservedRange[]|null); + + /** EnumDescriptorProto reservedName */ + reservedName?: (string[]|null); } /** Represents an EnumDescriptorProto. */ @@ -592,6 +1003,12 @@ export namespace google { /** EnumDescriptorProto options. */ public options?: (google.protobuf.IEnumOptions|null); + /** EnumDescriptorProto reservedRange. */ + public reservedRange: google.protobuf.EnumDescriptorProto.IEnumReservedRange[]; + + /** EnumDescriptorProto reservedName. */ + public reservedName: string[]; + /** * Creates an EnumDescriptorProto message from a plain object. Also converts values to their respective internal types. * @param object Plain object @@ -612,6 +1029,70 @@ export namespace google { * @returns JSON object */ public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for EnumDescriptorProto + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + namespace EnumDescriptorProto { + + /** Properties of an EnumReservedRange. */ + interface IEnumReservedRange { + + /** EnumReservedRange start */ + start?: (number|null); + + /** EnumReservedRange end */ + end?: (number|null); + } + + /** Represents an EnumReservedRange. */ + class EnumReservedRange implements IEnumReservedRange { + + /** + * Constructs a new EnumReservedRange. + * @param [properties] Properties to set + */ + constructor(properties?: google.protobuf.EnumDescriptorProto.IEnumReservedRange); + + /** EnumReservedRange start. */ + public start: number; + + /** EnumReservedRange end. */ + public end: number; + + /** + * Creates an EnumReservedRange message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns EnumReservedRange + */ + public static fromObject(object: { [k: string]: any }): google.protobuf.EnumDescriptorProto.EnumReservedRange; + + /** + * Creates a plain object from an EnumReservedRange message. Also converts values to other types if specified. + * @param message EnumReservedRange + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.protobuf.EnumDescriptorProto.EnumReservedRange, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this EnumReservedRange to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for EnumReservedRange + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } } /** Properties of an EnumValueDescriptorProto. */ @@ -665,6 +1146,13 @@ export namespace google { * @returns JSON object */ public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for EnumValueDescriptorProto + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; } /** Properties of a ServiceDescriptorProto. */ @@ -718,6 +1206,13 @@ export namespace google { * @returns JSON object */ public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for ServiceDescriptorProto + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; } /** Properties of a MethodDescriptorProto. */ @@ -789,6 +1284,13 @@ export namespace google { * @returns JSON object */ public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for MethodDescriptorProto + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; } /** Properties of a FileOptions. */ @@ -836,6 +1338,24 @@ export namespace google { /** FileOptions csharpNamespace */ csharpNamespace?: (string|null); + /** FileOptions swiftPrefix */ + swiftPrefix?: (string|null); + + /** FileOptions phpClassPrefix */ + phpClassPrefix?: (string|null); + + /** FileOptions phpNamespace */ + phpNamespace?: (string|null); + + /** FileOptions phpMetadataNamespace */ + phpMetadataNamespace?: (string|null); + + /** FileOptions rubyPackage */ + rubyPackage?: (string|null); + + /** FileOptions features */ + features?: (google.protobuf.IFeatureSet|null); + /** FileOptions uninterpretedOption */ uninterpretedOption?: (google.protobuf.IUninterpretedOption[]|null); @@ -894,6 +1414,24 @@ export namespace google { /** FileOptions csharpNamespace. */ public csharpNamespace: string; + /** FileOptions swiftPrefix. */ + public swiftPrefix: string; + + /** FileOptions phpClassPrefix. */ + public phpClassPrefix: string; + + /** FileOptions phpNamespace. */ + public phpNamespace: string; + + /** FileOptions phpMetadataNamespace. */ + public phpMetadataNamespace: string; + + /** FileOptions rubyPackage. */ + public rubyPackage: string; + + /** FileOptions features. */ + public features?: (google.protobuf.IFeatureSet|null); + /** FileOptions uninterpretedOption. */ public uninterpretedOption: google.protobuf.IUninterpretedOption[]; @@ -917,6 +1455,13 @@ export namespace google { * @returns JSON object */ public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for FileOptions + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; } namespace FileOptions { @@ -941,6 +1486,12 @@ export namespace google { /** MessageOptions mapEntry */ mapEntry?: (boolean|null); + /** MessageOptions deprecatedLegacyJsonFieldConflicts */ + deprecatedLegacyJsonFieldConflicts?: (boolean|null); + + /** MessageOptions features */ + features?: (google.protobuf.IFeatureSet|null); + /** MessageOptions uninterpretedOption */ uninterpretedOption?: (google.protobuf.IUninterpretedOption[]|null); @@ -969,6 +1520,12 @@ export namespace google { /** MessageOptions mapEntry. */ public mapEntry: boolean; + /** MessageOptions deprecatedLegacyJsonFieldConflicts. */ + public deprecatedLegacyJsonFieldConflicts: boolean; + + /** MessageOptions features. */ + public features?: (google.protobuf.IFeatureSet|null); + /** MessageOptions uninterpretedOption. */ public uninterpretedOption: google.protobuf.IUninterpretedOption[]; @@ -992,6 +1549,13 @@ export namespace google { * @returns JSON object */ public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for MessageOptions + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; } /** Properties of a FieldOptions. */ @@ -1009,12 +1573,30 @@ export namespace google { /** FieldOptions lazy */ lazy?: (boolean|null); + /** FieldOptions unverifiedLazy */ + unverifiedLazy?: (boolean|null); + /** FieldOptions deprecated */ deprecated?: (boolean|null); /** FieldOptions weak */ weak?: (boolean|null); + /** FieldOptions debugRedact */ + debugRedact?: (boolean|null); + + /** FieldOptions retention */ + retention?: (google.protobuf.FieldOptions.OptionRetention|null); + + /** FieldOptions targets */ + targets?: (google.protobuf.FieldOptions.OptionTargetType[]|null); + + /** FieldOptions editionDefaults */ + editionDefaults?: (google.protobuf.FieldOptions.IEditionDefault[]|null); + + /** FieldOptions features */ + features?: (google.protobuf.IFeatureSet|null); + /** FieldOptions uninterpretedOption */ uninterpretedOption?: (google.protobuf.IUninterpretedOption[]|null); @@ -1046,12 +1628,30 @@ export namespace google { /** FieldOptions lazy. */ public lazy: boolean; + /** FieldOptions unverifiedLazy. */ + public unverifiedLazy: boolean; + /** FieldOptions deprecated. */ public deprecated: boolean; /** FieldOptions weak. */ public weak: boolean; + /** FieldOptions debugRedact. */ + public debugRedact: boolean; + + /** FieldOptions retention. */ + public retention: google.protobuf.FieldOptions.OptionRetention; + + /** FieldOptions targets. */ + public targets: google.protobuf.FieldOptions.OptionTargetType[]; + + /** FieldOptions editionDefaults. */ + public editionDefaults: google.protobuf.FieldOptions.IEditionDefault[]; + + /** FieldOptions features. */ + public features?: (google.protobuf.IFeatureSet|null); + /** FieldOptions uninterpretedOption. */ public uninterpretedOption: google.protobuf.IUninterpretedOption[]; @@ -1075,6 +1675,13 @@ export namespace google { * @returns JSON object */ public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for FieldOptions + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; } namespace FieldOptions { @@ -1086,11 +1693,76 @@ export namespace google { /** JSType enum. */ type JSType = "JS_NORMAL"| "JS_STRING"| "JS_NUMBER"; + + /** OptionRetention enum. */ + type OptionRetention = + "RETENTION_UNKNOWN"| "RETENTION_RUNTIME"| "RETENTION_SOURCE"; + + /** OptionTargetType enum. */ + type OptionTargetType = + "TARGET_TYPE_UNKNOWN"| "TARGET_TYPE_FILE"| "TARGET_TYPE_EXTENSION_RANGE"| "TARGET_TYPE_MESSAGE"| "TARGET_TYPE_FIELD"| "TARGET_TYPE_ONEOF"| "TARGET_TYPE_ENUM"| "TARGET_TYPE_ENUM_ENTRY"| "TARGET_TYPE_SERVICE"| "TARGET_TYPE_METHOD"; + + /** Properties of an EditionDefault. */ + interface IEditionDefault { + + /** EditionDefault edition */ + edition?: (google.protobuf.Edition|null); + + /** EditionDefault value */ + value?: (string|null); + } + + /** Represents an EditionDefault. */ + class EditionDefault implements IEditionDefault { + + /** + * Constructs a new EditionDefault. + * @param [properties] Properties to set + */ + constructor(properties?: google.protobuf.FieldOptions.IEditionDefault); + + /** EditionDefault edition. */ + public edition: google.protobuf.Edition; + + /** EditionDefault value. */ + public value: string; + + /** + * Creates an EditionDefault message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns EditionDefault + */ + public static fromObject(object: { [k: string]: any }): google.protobuf.FieldOptions.EditionDefault; + + /** + * Creates a plain object from an EditionDefault message. Also converts values to other types if specified. + * @param message EditionDefault + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.protobuf.FieldOptions.EditionDefault, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this EditionDefault to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for EditionDefault + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } } /** Properties of an OneofOptions. */ interface IOneofOptions { + /** OneofOptions features */ + features?: (google.protobuf.IFeatureSet|null); + /** OneofOptions uninterpretedOption */ uninterpretedOption?: (google.protobuf.IUninterpretedOption[]|null); } @@ -1104,6 +1776,9 @@ export namespace google { */ constructor(properties?: google.protobuf.IOneofOptions); + /** OneofOptions features. */ + public features?: (google.protobuf.IFeatureSet|null); + /** OneofOptions uninterpretedOption. */ public uninterpretedOption: google.protobuf.IUninterpretedOption[]; @@ -1127,6 +1802,13 @@ export namespace google { * @returns JSON object */ public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for OneofOptions + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; } /** Properties of an EnumOptions. */ @@ -1138,6 +1820,12 @@ export namespace google { /** EnumOptions deprecated */ deprecated?: (boolean|null); + /** EnumOptions deprecatedLegacyJsonFieldConflicts */ + deprecatedLegacyJsonFieldConflicts?: (boolean|null); + + /** EnumOptions features */ + features?: (google.protobuf.IFeatureSet|null); + /** EnumOptions uninterpretedOption */ uninterpretedOption?: (google.protobuf.IUninterpretedOption[]|null); } @@ -1157,6 +1845,12 @@ export namespace google { /** EnumOptions deprecated. */ public deprecated: boolean; + /** EnumOptions deprecatedLegacyJsonFieldConflicts. */ + public deprecatedLegacyJsonFieldConflicts: boolean; + + /** EnumOptions features. */ + public features?: (google.protobuf.IFeatureSet|null); + /** EnumOptions uninterpretedOption. */ public uninterpretedOption: google.protobuf.IUninterpretedOption[]; @@ -1180,6 +1874,13 @@ export namespace google { * @returns JSON object */ public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for EnumOptions + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; } /** Properties of an EnumValueOptions. */ @@ -1188,6 +1889,12 @@ export namespace google { /** EnumValueOptions deprecated */ deprecated?: (boolean|null); + /** EnumValueOptions features */ + features?: (google.protobuf.IFeatureSet|null); + + /** EnumValueOptions debugRedact */ + debugRedact?: (boolean|null); + /** EnumValueOptions uninterpretedOption */ uninterpretedOption?: (google.protobuf.IUninterpretedOption[]|null); } @@ -1204,6 +1911,12 @@ export namespace google { /** EnumValueOptions deprecated. */ public deprecated: boolean; + /** EnumValueOptions features. */ + public features?: (google.protobuf.IFeatureSet|null); + + /** EnumValueOptions debugRedact. */ + public debugRedact: boolean; + /** EnumValueOptions uninterpretedOption. */ public uninterpretedOption: google.protobuf.IUninterpretedOption[]; @@ -1227,11 +1940,21 @@ export namespace google { * @returns JSON object */ public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for EnumValueOptions + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; } /** Properties of a ServiceOptions. */ interface IServiceOptions { + /** ServiceOptions features */ + features?: (google.protobuf.IFeatureSet|null); + /** ServiceOptions deprecated */ deprecated?: (boolean|null); @@ -1243,6 +1966,9 @@ export namespace google { /** ServiceOptions .google.api.oauthScopes */ ".google.api.oauthScopes"?: (string|null); + + /** ServiceOptions .google.api.apiVersion */ + ".google.api.apiVersion"?: (string|null); } /** Represents a ServiceOptions. */ @@ -1254,6 +1980,9 @@ export namespace google { */ constructor(properties?: google.protobuf.IServiceOptions); + /** ServiceOptions features. */ + public features?: (google.protobuf.IFeatureSet|null); + /** ServiceOptions deprecated. */ public deprecated: boolean; @@ -1280,6 +2009,13 @@ export namespace google { * @returns JSON object */ public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for ServiceOptions + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; } /** Properties of a MethodOptions. */ @@ -1288,7 +2024,13 @@ export namespace google { /** MethodOptions deprecated */ deprecated?: (boolean|null); - /** MethodOptions uninterpretedOption */ + /** MethodOptions idempotencyLevel */ + idempotencyLevel?: (google.protobuf.MethodOptions.IdempotencyLevel|null); + + /** MethodOptions features */ + features?: (google.protobuf.IFeatureSet|null); + + /** MethodOptions uninterpretedOption */ uninterpretedOption?: (google.protobuf.IUninterpretedOption[]|null); /** MethodOptions .google.api.http */ @@ -1313,6 +2055,12 @@ export namespace google { /** MethodOptions deprecated. */ public deprecated: boolean; + /** MethodOptions idempotencyLevel. */ + public idempotencyLevel: google.protobuf.MethodOptions.IdempotencyLevel; + + /** MethodOptions features. */ + public features?: (google.protobuf.IFeatureSet|null); + /** MethodOptions uninterpretedOption. */ public uninterpretedOption: google.protobuf.IUninterpretedOption[]; @@ -1336,6 +2084,20 @@ export namespace google { * @returns JSON object */ public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for MethodOptions + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + namespace MethodOptions { + + /** IdempotencyLevel enum. */ + type IdempotencyLevel = + "IDEMPOTENCY_UNKNOWN"| "NO_SIDE_EFFECTS"| "IDEMPOTENT"; } /** Properties of an UninterpretedOption. */ @@ -1413,6 +2175,13 @@ export namespace google { * @returns JSON object */ public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for UninterpretedOption + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; } namespace UninterpretedOption { @@ -1462,6 +2231,235 @@ export namespace google { * @returns JSON object */ public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for NamePart + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + } + + /** Properties of a FeatureSet. */ + interface IFeatureSet { + + /** FeatureSet fieldPresence */ + fieldPresence?: (google.protobuf.FeatureSet.FieldPresence|null); + + /** FeatureSet enumType */ + enumType?: (google.protobuf.FeatureSet.EnumType|null); + + /** FeatureSet repeatedFieldEncoding */ + repeatedFieldEncoding?: (google.protobuf.FeatureSet.RepeatedFieldEncoding|null); + + /** FeatureSet utf8Validation */ + utf8Validation?: (google.protobuf.FeatureSet.Utf8Validation|null); + + /** FeatureSet messageEncoding */ + messageEncoding?: (google.protobuf.FeatureSet.MessageEncoding|null); + + /** FeatureSet jsonFormat */ + jsonFormat?: (google.protobuf.FeatureSet.JsonFormat|null); + } + + /** Represents a FeatureSet. */ + class FeatureSet implements IFeatureSet { + + /** + * Constructs a new FeatureSet. + * @param [properties] Properties to set + */ + constructor(properties?: google.protobuf.IFeatureSet); + + /** FeatureSet fieldPresence. */ + public fieldPresence: google.protobuf.FeatureSet.FieldPresence; + + /** FeatureSet enumType. */ + public enumType: google.protobuf.FeatureSet.EnumType; + + /** FeatureSet repeatedFieldEncoding. */ + public repeatedFieldEncoding: google.protobuf.FeatureSet.RepeatedFieldEncoding; + + /** FeatureSet utf8Validation. */ + public utf8Validation: google.protobuf.FeatureSet.Utf8Validation; + + /** FeatureSet messageEncoding. */ + public messageEncoding: google.protobuf.FeatureSet.MessageEncoding; + + /** FeatureSet jsonFormat. */ + public jsonFormat: google.protobuf.FeatureSet.JsonFormat; + + /** + * Creates a FeatureSet message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns FeatureSet + */ + public static fromObject(object: { [k: string]: any }): google.protobuf.FeatureSet; + + /** + * Creates a plain object from a FeatureSet message. Also converts values to other types if specified. + * @param message FeatureSet + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.protobuf.FeatureSet, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this FeatureSet to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for FeatureSet + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + namespace FeatureSet { + + /** FieldPresence enum. */ + type FieldPresence = + "FIELD_PRESENCE_UNKNOWN"| "EXPLICIT"| "IMPLICIT"| "LEGACY_REQUIRED"; + + /** EnumType enum. */ + type EnumType = + "ENUM_TYPE_UNKNOWN"| "OPEN"| "CLOSED"; + + /** RepeatedFieldEncoding enum. */ + type RepeatedFieldEncoding = + "REPEATED_FIELD_ENCODING_UNKNOWN"| "PACKED"| "EXPANDED"; + + /** Utf8Validation enum. */ + type Utf8Validation = + "UTF8_VALIDATION_UNKNOWN"| "VERIFY"| "NONE"; + + /** MessageEncoding enum. */ + type MessageEncoding = + "MESSAGE_ENCODING_UNKNOWN"| "LENGTH_PREFIXED"| "DELIMITED"; + + /** JsonFormat enum. */ + type JsonFormat = + "JSON_FORMAT_UNKNOWN"| "ALLOW"| "LEGACY_BEST_EFFORT"; + } + + /** Properties of a FeatureSetDefaults. */ + interface IFeatureSetDefaults { + + /** FeatureSetDefaults defaults */ + defaults?: (google.protobuf.FeatureSetDefaults.IFeatureSetEditionDefault[]|null); + + /** FeatureSetDefaults minimumEdition */ + minimumEdition?: (google.protobuf.Edition|null); + + /** FeatureSetDefaults maximumEdition */ + maximumEdition?: (google.protobuf.Edition|null); + } + + /** Represents a FeatureSetDefaults. */ + class FeatureSetDefaults implements IFeatureSetDefaults { + + /** + * Constructs a new FeatureSetDefaults. + * @param [properties] Properties to set + */ + constructor(properties?: google.protobuf.IFeatureSetDefaults); + + /** FeatureSetDefaults defaults. */ + public defaults: google.protobuf.FeatureSetDefaults.IFeatureSetEditionDefault[]; + + /** FeatureSetDefaults minimumEdition. */ + public minimumEdition: google.protobuf.Edition; + + /** FeatureSetDefaults maximumEdition. */ + public maximumEdition: google.protobuf.Edition; + + /** + * Creates a FeatureSetDefaults message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns FeatureSetDefaults + */ + public static fromObject(object: { [k: string]: any }): google.protobuf.FeatureSetDefaults; + + /** + * Creates a plain object from a FeatureSetDefaults message. Also converts values to other types if specified. + * @param message FeatureSetDefaults + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.protobuf.FeatureSetDefaults, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this FeatureSetDefaults to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for FeatureSetDefaults + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + namespace FeatureSetDefaults { + + /** Properties of a FeatureSetEditionDefault. */ + interface IFeatureSetEditionDefault { + + /** FeatureSetEditionDefault edition */ + edition?: (google.protobuf.Edition|null); + + /** FeatureSetEditionDefault features */ + features?: (google.protobuf.IFeatureSet|null); + } + + /** Represents a FeatureSetEditionDefault. */ + class FeatureSetEditionDefault implements IFeatureSetEditionDefault { + + /** + * Constructs a new FeatureSetEditionDefault. + * @param [properties] Properties to set + */ + constructor(properties?: google.protobuf.FeatureSetDefaults.IFeatureSetEditionDefault); + + /** FeatureSetEditionDefault edition. */ + public edition: google.protobuf.Edition; + + /** FeatureSetEditionDefault features. */ + public features?: (google.protobuf.IFeatureSet|null); + + /** + * Creates a FeatureSetEditionDefault message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns FeatureSetEditionDefault + */ + public static fromObject(object: { [k: string]: any }): google.protobuf.FeatureSetDefaults.FeatureSetEditionDefault; + + /** + * Creates a plain object from a FeatureSetEditionDefault message. Also converts values to other types if specified. + * @param message FeatureSetEditionDefault + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.protobuf.FeatureSetDefaults.FeatureSetEditionDefault, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this FeatureSetEditionDefault to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for FeatureSetEditionDefault + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; } } @@ -1504,6 +2502,13 @@ export namespace google { * @returns JSON object */ public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for SourceCodeInfo + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; } namespace SourceCodeInfo { @@ -1571,6 +2576,13 @@ export namespace google { * @returns JSON object */ public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for Location + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; } } @@ -1613,6 +2625,13 @@ export namespace google { * @returns JSON object */ public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for GeneratedCodeInfo + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; } namespace GeneratedCodeInfo { @@ -1631,6 +2650,9 @@ export namespace google { /** Annotation end */ end?: (number|null); + + /** Annotation semantic */ + semantic?: (google.protobuf.GeneratedCodeInfo.Annotation.Semantic|null); } /** Represents an Annotation. */ @@ -1654,6 +2676,9 @@ export namespace google { /** Annotation end. */ public end: number; + /** Annotation semantic. */ + public semantic: google.protobuf.GeneratedCodeInfo.Annotation.Semantic; + /** * Creates an Annotation message from a plain object. Also converts values to their respective internal types. * @param object Plain object @@ -1674,243 +2699,123 @@ export namespace google { * @returns JSON object */ public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for Annotation + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + namespace Annotation { + + /** Semantic enum. */ + type Semantic = + "NONE"| "SET"| "ALIAS"; } } - /** Properties of a Struct. */ - interface IStruct { + /** Properties of a Duration. */ + interface IDuration { - /** Struct fields */ - fields?: ({ [k: string]: google.protobuf.IValue }|null); + /** Duration seconds */ + seconds?: (number|string|null); + + /** Duration nanos */ + nanos?: (number|null); } - /** Represents a Struct. */ - class Struct implements IStruct { + /** Represents a Duration. */ + class Duration implements IDuration { /** - * Constructs a new Struct. + * Constructs a new Duration. * @param [properties] Properties to set */ - constructor(properties?: google.protobuf.IStruct); + constructor(properties?: google.protobuf.IDuration); - /** Struct fields. */ - public fields: { [k: string]: google.protobuf.IValue }; + /** Duration seconds. */ + public seconds: (number|string); + + /** Duration nanos. */ + public nanos: number; /** - * Creates a Struct message from a plain object. Also converts values to their respective internal types. + * Creates a Duration message from a plain object. Also converts values to their respective internal types. * @param object Plain object - * @returns Struct + * @returns Duration */ - public static fromObject(object: { [k: string]: any }): google.protobuf.Struct; + public static fromObject(object: { [k: string]: any }): google.protobuf.Duration; /** - * Creates a plain object from a Struct message. Also converts values to other types if specified. - * @param message Struct + * Creates a plain object from a Duration message. Also converts values to other types if specified. + * @param message Duration * @param [options] Conversion options * @returns Plain object */ - public static toObject(message: google.protobuf.Struct, options?: $protobuf.IConversionOptions): { [k: string]: any }; + public static toObject(message: google.protobuf.Duration, options?: $protobuf.IConversionOptions): { [k: string]: any }; /** - * Converts this Struct to JSON. + * Converts this Duration to JSON. * @returns JSON object */ public toJSON(): { [k: string]: any }; - } - - /** Properties of a Value. */ - interface IValue { - - /** Value nullValue */ - nullValue?: (google.protobuf.NullValue|null); - - /** Value numberValue */ - numberValue?: (number|null); - - /** Value stringValue */ - stringValue?: (string|null); - /** Value boolValue */ - boolValue?: (boolean|null); + /** + * Gets the default type url for Duration + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } - /** Value structValue */ - structValue?: (google.protobuf.IStruct|null); + /** Properties of a DoubleValue. */ + interface IDoubleValue { - /** Value listValue */ - listValue?: (google.protobuf.IListValue|null); + /** DoubleValue value */ + value?: (number|null); } - /** Represents a Value. */ - class Value implements IValue { + /** Represents a DoubleValue. */ + class DoubleValue implements IDoubleValue { /** - * Constructs a new Value. + * Constructs a new DoubleValue. * @param [properties] Properties to set */ - constructor(properties?: google.protobuf.IValue); - - /** Value nullValue. */ - public nullValue?: (google.protobuf.NullValue|null); - - /** Value numberValue. */ - public numberValue?: (number|null); - - /** Value stringValue. */ - public stringValue?: (string|null); - - /** Value boolValue. */ - public boolValue?: (boolean|null); - - /** Value structValue. */ - public structValue?: (google.protobuf.IStruct|null); - - /** Value listValue. */ - public listValue?: (google.protobuf.IListValue|null); + constructor(properties?: google.protobuf.IDoubleValue); - /** Value kind. */ - public kind?: ("nullValue"|"numberValue"|"stringValue"|"boolValue"|"structValue"|"listValue"); + /** DoubleValue value. */ + public value: number; /** - * Creates a Value message from a plain object. Also converts values to their respective internal types. + * Creates a DoubleValue message from a plain object. Also converts values to their respective internal types. * @param object Plain object - * @returns Value + * @returns DoubleValue */ - public static fromObject(object: { [k: string]: any }): google.protobuf.Value; + public static fromObject(object: { [k: string]: any }): google.protobuf.DoubleValue; /** - * Creates a plain object from a Value message. Also converts values to other types if specified. - * @param message Value + * Creates a plain object from a DoubleValue message. Also converts values to other types if specified. + * @param message DoubleValue * @param [options] Conversion options * @returns Plain object */ - public static toObject(message: google.protobuf.Value, options?: $protobuf.IConversionOptions): { [k: string]: any }; + public static toObject(message: google.protobuf.DoubleValue, options?: $protobuf.IConversionOptions): { [k: string]: any }; /** - * Converts this Value to JSON. - * @returns JSON object - */ - public toJSON(): { [k: string]: any }; - } - - /** NullValue enum. */ - type NullValue = - "NULL_VALUE"; - - /** Properties of a ListValue. */ - interface IListValue { - - /** ListValue values */ - values?: (google.protobuf.IValue[]|null); - } - - /** Represents a ListValue. */ - class ListValue implements IListValue { - - /** - * Constructs a new ListValue. - * @param [properties] Properties to set - */ - constructor(properties?: google.protobuf.IListValue); - - /** ListValue values. */ - public values: google.protobuf.IValue[]; - - /** - * Creates a ListValue message from a plain object. Also converts values to their respective internal types. - * @param object Plain object - * @returns ListValue - */ - public static fromObject(object: { [k: string]: any }): google.protobuf.ListValue; - - /** - * Creates a plain object from a ListValue message. Also converts values to other types if specified. - * @param message ListValue - * @param [options] Conversion options - * @returns Plain object - */ - public static toObject(message: google.protobuf.ListValue, options?: $protobuf.IConversionOptions): { [k: string]: any }; - - /** - * Converts this ListValue to JSON. - * @returns JSON object - */ - public toJSON(): { [k: string]: any }; - } - - /** Properties of an Empty. */ - interface IEmpty { - } - - /** Represents an Empty. */ - class Empty implements IEmpty { - - /** - * Constructs a new Empty. - * @param [properties] Properties to set - */ - constructor(properties?: google.protobuf.IEmpty); - - /** - * Creates an Empty message from a plain object. Also converts values to their respective internal types. - * @param object Plain object - * @returns Empty - */ - public static fromObject(object: { [k: string]: any }): google.protobuf.Empty; - - /** - * Creates a plain object from an Empty message. Also converts values to other types if specified. - * @param message Empty - * @param [options] Conversion options - * @returns Plain object - */ - public static toObject(message: google.protobuf.Empty, options?: $protobuf.IConversionOptions): { [k: string]: any }; - - /** - * Converts this Empty to JSON. - * @returns JSON object - */ - public toJSON(): { [k: string]: any }; - } - - /** Properties of a DoubleValue. */ - interface IDoubleValue { - - /** DoubleValue value */ - value?: (number|null); - } - - /** Represents a DoubleValue. */ - class DoubleValue implements IDoubleValue { - - /** - * Constructs a new DoubleValue. - * @param [properties] Properties to set - */ - constructor(properties?: google.protobuf.IDoubleValue); - - /** DoubleValue value. */ - public value: number; - - /** - * Creates a DoubleValue message from a plain object. Also converts values to their respective internal types. - * @param object Plain object - * @returns DoubleValue - */ - public static fromObject(object: { [k: string]: any }): google.protobuf.DoubleValue; - - /** - * Creates a plain object from a DoubleValue message. Also converts values to other types if specified. - * @param message DoubleValue - * @param [options] Conversion options - * @returns Plain object - */ - public static toObject(message: google.protobuf.DoubleValue, options?: $protobuf.IConversionOptions): { [k: string]: any }; - - /** - * Converts this DoubleValue to JSON. + * Converts this DoubleValue to JSON. * @returns JSON object */ public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for DoubleValue + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; } /** Properties of a FloatValue. */ @@ -1952,6 +2857,13 @@ export namespace google { * @returns JSON object */ public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for FloatValue + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; } /** Properties of an Int64Value. */ @@ -1993,6 +2905,13 @@ export namespace google { * @returns JSON object */ public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for Int64Value + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; } /** Properties of a UInt64Value. */ @@ -2034,6 +2953,13 @@ export namespace google { * @returns JSON object */ public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for UInt64Value + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; } /** Properties of an Int32Value. */ @@ -2075,6 +3001,13 @@ export namespace google { * @returns JSON object */ public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for Int32Value + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; } /** Properties of a UInt32Value. */ @@ -2116,6 +3049,13 @@ export namespace google { * @returns JSON object */ public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for UInt32Value + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; } /** Properties of a BoolValue. */ @@ -2157,6 +3097,13 @@ export namespace google { * @returns JSON object */ public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for BoolValue + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; } /** Properties of a StringValue. */ @@ -2198,6 +3145,13 @@ export namespace google { * @returns JSON object */ public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for StringValue + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; } /** Properties of a BytesValue. */ @@ -2239,6 +3193,55 @@ export namespace google { * @returns JSON object */ public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for BytesValue + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of an Empty. */ + interface IEmpty { + } + + /** Represents an Empty. */ + class Empty implements IEmpty { + + /** + * Constructs a new Empty. + * @param [properties] Properties to set + */ + constructor(properties?: google.protobuf.IEmpty); + + /** + * Creates an Empty message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns Empty + */ + public static fromObject(object: { [k: string]: any }): google.protobuf.Empty; + + /** + * Creates a plain object from an Empty message. Also converts values to other types if specified. + * @param message Empty + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.protobuf.Empty, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this Empty to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for Empty + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; } /** Properties of an Any. */ @@ -2286,6 +3289,13 @@ export namespace google { * @returns JSON object */ public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for Any + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; } /** Properties of a FieldMask. */ @@ -2327,53 +3337,13 @@ export namespace google { * @returns JSON object */ public toJSON(): { [k: string]: any }; - } - - /** Properties of a Duration. */ - interface IDuration { - - /** Duration seconds */ - seconds?: (number|string|null); - - /** Duration nanos */ - nanos?: (number|null); - } - - /** Represents a Duration. */ - class Duration implements IDuration { - - /** - * Constructs a new Duration. - * @param [properties] Properties to set - */ - constructor(properties?: google.protobuf.IDuration); - - /** Duration seconds. */ - public seconds: (number|string); - - /** Duration nanos. */ - public nanos: number; - - /** - * Creates a Duration message from a plain object. Also converts values to their respective internal types. - * @param object Plain object - * @returns Duration - */ - public static fromObject(object: { [k: string]: any }): google.protobuf.Duration; - - /** - * Creates a plain object from a Duration message. Also converts values to other types if specified. - * @param message Duration - * @param [options] Conversion options - * @returns Plain object - */ - public static toObject(message: google.protobuf.Duration, options?: $protobuf.IConversionOptions): { [k: string]: any }; /** - * Converts this Duration to JSON. - * @returns JSON object + * Gets the default type url for FieldMask + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url */ - public toJSON(): { [k: string]: any }; + public static getTypeUrl(typeUrlPrefix?: string): string; } } @@ -2422,6 +3392,13 @@ export namespace google { * @returns JSON object */ public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for DocumentMask + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; } /** Properties of a Precondition. */ @@ -2472,6 +3449,13 @@ export namespace google { * @returns JSON object */ public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for Precondition + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; } /** Properties of a TransactionOptions. */ @@ -2522,6 +3506,13 @@ export namespace google { * @returns JSON object */ public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for TransactionOptions + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; } namespace TransactionOptions { @@ -2565,6 +3556,13 @@ export namespace google { * @returns JSON object */ public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for ReadWrite + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; } /** Properties of a ReadOnly. */ @@ -2609,6 +3607,13 @@ export namespace google { * @returns JSON object */ public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for ReadOnly + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; } } @@ -2669,6 +3674,13 @@ export namespace google { * @returns JSON object */ public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for Document + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; } /** Properties of a Value. */ @@ -2773,6 +3785,13 @@ export namespace google { * @returns JSON object */ public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for Value + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; } /** Properties of an ArrayValue. */ @@ -2814,6 +3833,13 @@ export namespace google { * @returns JSON object */ public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for ArrayValue + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; } /** Properties of a MapValue. */ @@ -2855,6 +3881,13 @@ export namespace google { * @returns JSON object */ public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for MapValue + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; } /** Represents a Firestore */ @@ -3247,7 +4280,14 @@ export namespace google { * @returns JSON object */ public toJSON(): { [k: string]: any }; - } + + /** + * Gets the default type url for GetDocumentRequest + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } /** Properties of a ListDocumentsRequest. */ interface IListDocumentsRequest { @@ -3339,6 +4379,13 @@ export namespace google { * @returns JSON object */ public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for ListDocumentsRequest + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; } /** Properties of a ListDocumentsResponse. */ @@ -3386,6 +4433,13 @@ export namespace google { * @returns JSON object */ public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for ListDocumentsResponse + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; } /** Properties of a CreateDocumentRequest. */ @@ -3451,6 +4505,13 @@ export namespace google { * @returns JSON object */ public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for CreateDocumentRequest + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; } /** Properties of an UpdateDocumentRequest. */ @@ -3510,6 +4571,13 @@ export namespace google { * @returns JSON object */ public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for UpdateDocumentRequest + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; } /** Properties of a DeleteDocumentRequest. */ @@ -3557,6 +4625,13 @@ export namespace google { * @returns JSON object */ public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for DeleteDocumentRequest + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; } /** Properties of a BatchGetDocumentsRequest. */ @@ -3631,6 +4706,13 @@ export namespace google { * @returns JSON object */ public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for BatchGetDocumentsRequest + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; } /** Properties of a BatchGetDocumentsResponse. */ @@ -3693,6 +4775,13 @@ export namespace google { * @returns JSON object */ public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for BatchGetDocumentsResponse + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; } /** Properties of a BeginTransactionRequest. */ @@ -3740,6 +4829,13 @@ export namespace google { * @returns JSON object */ public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for BeginTransactionRequest + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; } /** Properties of a BeginTransactionResponse. */ @@ -3781,6 +4877,13 @@ export namespace google { * @returns JSON object */ public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for BeginTransactionResponse + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; } /** Properties of a CommitRequest. */ @@ -3834,6 +4937,13 @@ export namespace google { * @returns JSON object */ public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for CommitRequest + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; } /** Properties of a CommitResponse. */ @@ -3881,6 +4991,13 @@ export namespace google { * @returns JSON object */ public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for CommitResponse + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; } /** Properties of a RollbackRequest. */ @@ -3928,6 +5045,13 @@ export namespace google { * @returns JSON object */ public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for RollbackRequest + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; } /** Properties of a RunQueryRequest. */ @@ -3999,6 +5123,13 @@ export namespace google { * @returns JSON object */ public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for RunQueryRequest + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; } /** Properties of a RunQueryResponse. */ @@ -4058,6 +5189,13 @@ export namespace google { * @returns JSON object */ public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for RunQueryResponse + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; } /** Properties of a PartitionQueryRequest. */ @@ -4126,6 +5264,13 @@ export namespace google { * @returns JSON object */ public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for PartitionQueryRequest + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; } /** Properties of a PartitionQueryResponse. */ @@ -4173,6 +5318,13 @@ export namespace google { * @returns JSON object */ public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for PartitionQueryResponse + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; } /** Properties of a WriteRequest. */ @@ -4238,6 +5390,13 @@ export namespace google { * @returns JSON object */ public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for WriteRequest + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; } /** Properties of a WriteResponse. */ @@ -4297,6 +5456,13 @@ export namespace google { * @returns JSON object */ public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for WriteResponse + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; } /** Properties of a ListenRequest. */ @@ -4359,6 +5525,13 @@ export namespace google { * @returns JSON object */ public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for ListenRequest + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; } /** Properties of a ListenResponse. */ @@ -4427,6 +5600,13 @@ export namespace google { * @returns JSON object */ public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for ListenResponse + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; } /** Properties of a Target. */ @@ -4504,6 +5684,13 @@ export namespace google { * @returns JSON object */ public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for Target + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; } namespace Target { @@ -4547,6 +5734,13 @@ export namespace google { * @returns JSON object */ public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for DocumentsTarget + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; } /** Properties of a QueryTarget. */ @@ -4597,6 +5791,13 @@ export namespace google { * @returns JSON object */ public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for QueryTarget + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; } } @@ -4663,6 +5864,13 @@ export namespace google { * @returns JSON object */ public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for TargetChange + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; } namespace TargetChange { @@ -4723,6 +5931,13 @@ export namespace google { * @returns JSON object */ public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for ListCollectionIdsRequest + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; } /** Properties of a ListCollectionIdsResponse. */ @@ -4770,6 +5985,13 @@ export namespace google { * @returns JSON object */ public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for ListCollectionIdsResponse + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; } /** Properties of a BatchWriteRequest. */ @@ -4823,6 +6045,13 @@ export namespace google { * @returns JSON object */ public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for BatchWriteRequest + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; } /** Properties of a BatchWriteResponse. */ @@ -4870,6 +6099,13 @@ export namespace google { * @returns JSON object */ public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for BatchWriteResponse + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; } /** Properties of a StructuredQuery. */ @@ -4953,6 +6189,13 @@ export namespace google { * @returns JSON object */ public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for StructuredQuery + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; } namespace StructuredQuery { @@ -5002,6 +6245,13 @@ export namespace google { * @returns JSON object */ public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for CollectionSelector + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; } /** Properties of a Filter. */ @@ -5058,6 +6308,13 @@ export namespace google { * @returns JSON object */ public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for Filter + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; } /** Properties of a CompositeFilter. */ @@ -5105,13 +6362,20 @@ export namespace google { * @returns JSON object */ public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for CompositeFilter + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; } namespace CompositeFilter { /** Operator enum. */ type Operator = - "OPERATOR_UNSPECIFIED"| "AND"| "OR"; + "OPERATOR_UNSPECIFIED"| "AND"; } /** Properties of a FieldFilter. */ @@ -5165,6 +6429,13 @@ export namespace google { * @returns JSON object */ public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for FieldFilter + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; } namespace FieldFilter { @@ -5222,6 +6493,13 @@ export namespace google { * @returns JSON object */ public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for UnaryFilter + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; } namespace UnaryFilter { @@ -5270,6 +6548,13 @@ export namespace google { * @returns JSON object */ public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for FieldReference + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; } /** Properties of an Order. */ @@ -5317,6 +6602,13 @@ export namespace google { * @returns JSON object */ public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for Order + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; } /** Properties of a Projection. */ @@ -5358,6 +6650,13 @@ export namespace google { * @returns JSON object */ public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for Projection + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; } /** Direction enum. */ @@ -5410,6 +6709,13 @@ export namespace google { * @returns JSON object */ public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for Cursor + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; } /** Properties of a Write. */ @@ -5484,6 +6790,13 @@ export namespace google { * @returns JSON object */ public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for Write + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; } /** Properties of a DocumentTransform. */ @@ -5531,6 +6844,13 @@ export namespace google { * @returns JSON object */ public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for DocumentTransform + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; } namespace DocumentTransform { @@ -5613,6 +6933,13 @@ export namespace google { * @returns JSON object */ public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for FieldTransform + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; } namespace FieldTransform { @@ -5668,6 +6995,13 @@ export namespace google { * @returns JSON object */ public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for WriteResult + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; } /** Properties of a DocumentChange. */ @@ -5721,6 +7055,13 @@ export namespace google { * @returns JSON object */ public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for DocumentChange + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; } /** Properties of a DocumentDelete. */ @@ -5774,6 +7115,13 @@ export namespace google { * @returns JSON object */ public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for DocumentDelete + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; } /** Properties of a DocumentRemove. */ @@ -5827,6 +7175,13 @@ export namespace google { * @returns JSON object */ public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for DocumentRemove + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; } /** Properties of an ExistenceFilter. */ @@ -5874,196 +7229,1224 @@ export namespace google { * @returns JSON object */ public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for ExistenceFilter + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of an UndeliverableFirstGenEvent. */ + interface IUndeliverableFirstGenEvent { + + /** UndeliverableFirstGenEvent message */ + message?: (string|null); + + /** UndeliverableFirstGenEvent reason */ + reason?: (google.firestore.v1beta1.UndeliverableFirstGenEvent.Reason|null); + + /** UndeliverableFirstGenEvent documentName */ + documentName?: (string|null); + + /** UndeliverableFirstGenEvent documentChangeType */ + documentChangeType?: (google.firestore.v1beta1.UndeliverableFirstGenEvent.DocumentChangeType|null); + + /** UndeliverableFirstGenEvent functionName */ + functionName?: (string[]|null); + + /** UndeliverableFirstGenEvent triggeredTime */ + triggeredTime?: (google.protobuf.ITimestamp|null); + } + + /** Represents an UndeliverableFirstGenEvent. */ + class UndeliverableFirstGenEvent implements IUndeliverableFirstGenEvent { + + /** + * Constructs a new UndeliverableFirstGenEvent. + * @param [properties] Properties to set + */ + constructor(properties?: google.firestore.v1beta1.IUndeliverableFirstGenEvent); + + /** UndeliverableFirstGenEvent message. */ + public message: string; + + /** UndeliverableFirstGenEvent reason. */ + public reason: google.firestore.v1beta1.UndeliverableFirstGenEvent.Reason; + + /** UndeliverableFirstGenEvent documentName. */ + public documentName: string; + + /** UndeliverableFirstGenEvent documentChangeType. */ + public documentChangeType: google.firestore.v1beta1.UndeliverableFirstGenEvent.DocumentChangeType; + + /** UndeliverableFirstGenEvent functionName. */ + public functionName: string[]; + + /** UndeliverableFirstGenEvent triggeredTime. */ + public triggeredTime?: (google.protobuf.ITimestamp|null); + + /** + * Creates an UndeliverableFirstGenEvent message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns UndeliverableFirstGenEvent + */ + public static fromObject(object: { [k: string]: any }): google.firestore.v1beta1.UndeliverableFirstGenEvent; + + /** + * Creates a plain object from an UndeliverableFirstGenEvent message. Also converts values to other types if specified. + * @param message UndeliverableFirstGenEvent + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.firestore.v1beta1.UndeliverableFirstGenEvent, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this UndeliverableFirstGenEvent to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for UndeliverableFirstGenEvent + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + namespace UndeliverableFirstGenEvent { + + /** Reason enum. */ + type Reason = + "REASON_UNSPECIFIED"| "EXCEEDING_SIZE_LIMIT"; + + /** DocumentChangeType enum. */ + type DocumentChangeType = + "DOCUMENT_CHANGE_TYPE_UNSPECIFIED"| "CREATE"| "DELETE"| "UPDATE"; } } - } + } + + /** Namespace type. */ + namespace type { + + /** Properties of a LatLng. */ + interface ILatLng { + + /** LatLng latitude */ + latitude?: (number|null); + + /** LatLng longitude */ + longitude?: (number|null); + } + + /** Represents a LatLng. */ + class LatLng implements ILatLng { + + /** + * Constructs a new LatLng. + * @param [properties] Properties to set + */ + constructor(properties?: google.type.ILatLng); + + /** LatLng latitude. */ + public latitude: number; + + /** LatLng longitude. */ + public longitude: number; + + /** + * Creates a LatLng message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns LatLng + */ + public static fromObject(object: { [k: string]: any }): google.type.LatLng; + + /** + * Creates a plain object from a LatLng message. Also converts values to other types if specified. + * @param message LatLng + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.type.LatLng, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this LatLng to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for LatLng + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** DayOfWeek enum. */ + type DayOfWeek = + "DAY_OF_WEEK_UNSPECIFIED"| "MONDAY"| "TUESDAY"| "WEDNESDAY"| "THURSDAY"| "FRIDAY"| "SATURDAY"| "SUNDAY"; + } + + /** Namespace api. */ + namespace api { + + /** Properties of a Http. */ + interface IHttp { + + /** Http rules */ + rules?: (google.api.IHttpRule[]|null); + + /** Http fullyDecodeReservedExpansion */ + fullyDecodeReservedExpansion?: (boolean|null); + } + + /** Represents a Http. */ + class Http implements IHttp { + + /** + * Constructs a new Http. + * @param [properties] Properties to set + */ + constructor(properties?: google.api.IHttp); + + /** Http rules. */ + public rules: google.api.IHttpRule[]; + + /** Http fullyDecodeReservedExpansion. */ + public fullyDecodeReservedExpansion: boolean; + + /** + * Creates a Http message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns Http + */ + public static fromObject(object: { [k: string]: any }): google.api.Http; + + /** + * Creates a plain object from a Http message. Also converts values to other types if specified. + * @param message Http + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.api.Http, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this Http to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for Http + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a HttpRule. */ + interface IHttpRule { + + /** HttpRule selector */ + selector?: (string|null); + + /** HttpRule get */ + get?: (string|null); + + /** HttpRule put */ + put?: (string|null); + + /** HttpRule post */ + post?: (string|null); + + /** HttpRule delete */ + "delete"?: (string|null); + + /** HttpRule patch */ + patch?: (string|null); + + /** HttpRule custom */ + custom?: (google.api.ICustomHttpPattern|null); + + /** HttpRule body */ + body?: (string|null); + + /** HttpRule responseBody */ + responseBody?: (string|null); + + /** HttpRule additionalBindings */ + additionalBindings?: (google.api.IHttpRule[]|null); + } + + /** Represents a HttpRule. */ + class HttpRule implements IHttpRule { + + /** + * Constructs a new HttpRule. + * @param [properties] Properties to set + */ + constructor(properties?: google.api.IHttpRule); + + /** HttpRule selector. */ + public selector: string; + + /** HttpRule get. */ + public get?: (string|null); + + /** HttpRule put. */ + public put?: (string|null); + + /** HttpRule post. */ + public post?: (string|null); + + /** HttpRule delete. */ + public delete?: (string|null); + + /** HttpRule patch. */ + public patch?: (string|null); + + /** HttpRule custom. */ + public custom?: (google.api.ICustomHttpPattern|null); + + /** HttpRule body. */ + public body: string; + + /** HttpRule responseBody. */ + public responseBody: string; + + /** HttpRule additionalBindings. */ + public additionalBindings: google.api.IHttpRule[]; + + /** HttpRule pattern. */ + public pattern?: ("get"|"put"|"post"|"delete"|"patch"|"custom"); + + /** + * Creates a HttpRule message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns HttpRule + */ + public static fromObject(object: { [k: string]: any }): google.api.HttpRule; + + /** + * Creates a plain object from a HttpRule message. Also converts values to other types if specified. + * @param message HttpRule + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.api.HttpRule, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this HttpRule to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for HttpRule + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a CustomHttpPattern. */ + interface ICustomHttpPattern { + + /** CustomHttpPattern kind */ + kind?: (string|null); + + /** CustomHttpPattern path */ + path?: (string|null); + } + + /** Represents a CustomHttpPattern. */ + class CustomHttpPattern implements ICustomHttpPattern { + + /** + * Constructs a new CustomHttpPattern. + * @param [properties] Properties to set + */ + constructor(properties?: google.api.ICustomHttpPattern); + + /** CustomHttpPattern kind. */ + public kind: string; + + /** CustomHttpPattern path. */ + public path: string; + + /** + * Creates a CustomHttpPattern message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns CustomHttpPattern + */ + public static fromObject(object: { [k: string]: any }): google.api.CustomHttpPattern; + + /** + * Creates a plain object from a CustomHttpPattern message. Also converts values to other types if specified. + * @param message CustomHttpPattern + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.api.CustomHttpPattern, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this CustomHttpPattern to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for CustomHttpPattern + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a CommonLanguageSettings. */ + interface ICommonLanguageSettings { + + /** CommonLanguageSettings referenceDocsUri */ + referenceDocsUri?: (string|null); + + /** CommonLanguageSettings destinations */ + destinations?: (google.api.ClientLibraryDestination[]|null); + } + + /** Represents a CommonLanguageSettings. */ + class CommonLanguageSettings implements ICommonLanguageSettings { + + /** + * Constructs a new CommonLanguageSettings. + * @param [properties] Properties to set + */ + constructor(properties?: google.api.ICommonLanguageSettings); + + /** CommonLanguageSettings referenceDocsUri. */ + public referenceDocsUri: string; + + /** CommonLanguageSettings destinations. */ + public destinations: google.api.ClientLibraryDestination[]; + + /** + * Creates a CommonLanguageSettings message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns CommonLanguageSettings + */ + public static fromObject(object: { [k: string]: any }): google.api.CommonLanguageSettings; + + /** + * Creates a plain object from a CommonLanguageSettings message. Also converts values to other types if specified. + * @param message CommonLanguageSettings + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.api.CommonLanguageSettings, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this CommonLanguageSettings to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for CommonLanguageSettings + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a ClientLibrarySettings. */ + interface IClientLibrarySettings { + + /** ClientLibrarySettings version */ + version?: (string|null); + + /** ClientLibrarySettings launchStage */ + launchStage?: (google.api.LaunchStage|null); + + /** ClientLibrarySettings restNumericEnums */ + restNumericEnums?: (boolean|null); + + /** ClientLibrarySettings javaSettings */ + javaSettings?: (google.api.IJavaSettings|null); + + /** ClientLibrarySettings cppSettings */ + cppSettings?: (google.api.ICppSettings|null); + + /** ClientLibrarySettings phpSettings */ + phpSettings?: (google.api.IPhpSettings|null); + + /** ClientLibrarySettings pythonSettings */ + pythonSettings?: (google.api.IPythonSettings|null); + + /** ClientLibrarySettings nodeSettings */ + nodeSettings?: (google.api.INodeSettings|null); + + /** ClientLibrarySettings dotnetSettings */ + dotnetSettings?: (google.api.IDotnetSettings|null); + + /** ClientLibrarySettings rubySettings */ + rubySettings?: (google.api.IRubySettings|null); + + /** ClientLibrarySettings goSettings */ + goSettings?: (google.api.IGoSettings|null); + } + + /** Represents a ClientLibrarySettings. */ + class ClientLibrarySettings implements IClientLibrarySettings { + + /** + * Constructs a new ClientLibrarySettings. + * @param [properties] Properties to set + */ + constructor(properties?: google.api.IClientLibrarySettings); + + /** ClientLibrarySettings version. */ + public version: string; + + /** ClientLibrarySettings launchStage. */ + public launchStage: google.api.LaunchStage; + + /** ClientLibrarySettings restNumericEnums. */ + public restNumericEnums: boolean; + + /** ClientLibrarySettings javaSettings. */ + public javaSettings?: (google.api.IJavaSettings|null); + + /** ClientLibrarySettings cppSettings. */ + public cppSettings?: (google.api.ICppSettings|null); + + /** ClientLibrarySettings phpSettings. */ + public phpSettings?: (google.api.IPhpSettings|null); + + /** ClientLibrarySettings pythonSettings. */ + public pythonSettings?: (google.api.IPythonSettings|null); + + /** ClientLibrarySettings nodeSettings. */ + public nodeSettings?: (google.api.INodeSettings|null); + + /** ClientLibrarySettings dotnetSettings. */ + public dotnetSettings?: (google.api.IDotnetSettings|null); + + /** ClientLibrarySettings rubySettings. */ + public rubySettings?: (google.api.IRubySettings|null); + + /** ClientLibrarySettings goSettings. */ + public goSettings?: (google.api.IGoSettings|null); + + /** + * Creates a ClientLibrarySettings message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns ClientLibrarySettings + */ + public static fromObject(object: { [k: string]: any }): google.api.ClientLibrarySettings; + + /** + * Creates a plain object from a ClientLibrarySettings message. Also converts values to other types if specified. + * @param message ClientLibrarySettings + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.api.ClientLibrarySettings, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this ClientLibrarySettings to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for ClientLibrarySettings + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a Publishing. */ + interface IPublishing { + + /** Publishing methodSettings */ + methodSettings?: (google.api.IMethodSettings[]|null); + + /** Publishing newIssueUri */ + newIssueUri?: (string|null); + + /** Publishing documentationUri */ + documentationUri?: (string|null); + + /** Publishing apiShortName */ + apiShortName?: (string|null); + + /** Publishing githubLabel */ + githubLabel?: (string|null); + + /** Publishing codeownerGithubTeams */ + codeownerGithubTeams?: (string[]|null); + + /** Publishing docTagPrefix */ + docTagPrefix?: (string|null); + + /** Publishing organization */ + organization?: (google.api.ClientLibraryOrganization|null); + + /** Publishing librarySettings */ + librarySettings?: (google.api.IClientLibrarySettings[]|null); + + /** Publishing protoReferenceDocumentationUri */ + protoReferenceDocumentationUri?: (string|null); + + /** Publishing restReferenceDocumentationUri */ + restReferenceDocumentationUri?: (string|null); + } + + /** Represents a Publishing. */ + class Publishing implements IPublishing { + + /** + * Constructs a new Publishing. + * @param [properties] Properties to set + */ + constructor(properties?: google.api.IPublishing); + + /** Publishing methodSettings. */ + public methodSettings: google.api.IMethodSettings[]; + + /** Publishing newIssueUri. */ + public newIssueUri: string; + + /** Publishing documentationUri. */ + public documentationUri: string; + + /** Publishing apiShortName. */ + public apiShortName: string; + + /** Publishing githubLabel. */ + public githubLabel: string; + + /** Publishing codeownerGithubTeams. */ + public codeownerGithubTeams: string[]; + + /** Publishing docTagPrefix. */ + public docTagPrefix: string; + + /** Publishing organization. */ + public organization: google.api.ClientLibraryOrganization; + + /** Publishing librarySettings. */ + public librarySettings: google.api.IClientLibrarySettings[]; + + /** Publishing protoReferenceDocumentationUri. */ + public protoReferenceDocumentationUri: string; + + /** Publishing restReferenceDocumentationUri. */ + public restReferenceDocumentationUri: string; + + /** + * Creates a Publishing message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns Publishing + */ + public static fromObject(object: { [k: string]: any }): google.api.Publishing; + + /** + * Creates a plain object from a Publishing message. Also converts values to other types if specified. + * @param message Publishing + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.api.Publishing, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this Publishing to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for Publishing + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a JavaSettings. */ + interface IJavaSettings { + + /** JavaSettings libraryPackage */ + libraryPackage?: (string|null); + + /** JavaSettings serviceClassNames */ + serviceClassNames?: ({ [k: string]: string }|null); + + /** JavaSettings common */ + common?: (google.api.ICommonLanguageSettings|null); + } + + /** Represents a JavaSettings. */ + class JavaSettings implements IJavaSettings { + + /** + * Constructs a new JavaSettings. + * @param [properties] Properties to set + */ + constructor(properties?: google.api.IJavaSettings); + + /** JavaSettings libraryPackage. */ + public libraryPackage: string; + + /** JavaSettings serviceClassNames. */ + public serviceClassNames: { [k: string]: string }; + + /** JavaSettings common. */ + public common?: (google.api.ICommonLanguageSettings|null); + + /** + * Creates a JavaSettings message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns JavaSettings + */ + public static fromObject(object: { [k: string]: any }): google.api.JavaSettings; + + /** + * Creates a plain object from a JavaSettings message. Also converts values to other types if specified. + * @param message JavaSettings + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.api.JavaSettings, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this JavaSettings to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for JavaSettings + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a CppSettings. */ + interface ICppSettings { + + /** CppSettings common */ + common?: (google.api.ICommonLanguageSettings|null); + } + + /** Represents a CppSettings. */ + class CppSettings implements ICppSettings { + + /** + * Constructs a new CppSettings. + * @param [properties] Properties to set + */ + constructor(properties?: google.api.ICppSettings); + + /** CppSettings common. */ + public common?: (google.api.ICommonLanguageSettings|null); + + /** + * Creates a CppSettings message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns CppSettings + */ + public static fromObject(object: { [k: string]: any }): google.api.CppSettings; + + /** + * Creates a plain object from a CppSettings message. Also converts values to other types if specified. + * @param message CppSettings + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.api.CppSettings, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this CppSettings to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for CppSettings + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a PhpSettings. */ + interface IPhpSettings { + + /** PhpSettings common */ + common?: (google.api.ICommonLanguageSettings|null); + } + + /** Represents a PhpSettings. */ + class PhpSettings implements IPhpSettings { + + /** + * Constructs a new PhpSettings. + * @param [properties] Properties to set + */ + constructor(properties?: google.api.IPhpSettings); + + /** PhpSettings common. */ + public common?: (google.api.ICommonLanguageSettings|null); + + /** + * Creates a PhpSettings message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns PhpSettings + */ + public static fromObject(object: { [k: string]: any }): google.api.PhpSettings; + + /** + * Creates a plain object from a PhpSettings message. Also converts values to other types if specified. + * @param message PhpSettings + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.api.PhpSettings, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this PhpSettings to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for PhpSettings + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a PythonSettings. */ + interface IPythonSettings { + + /** PythonSettings common */ + common?: (google.api.ICommonLanguageSettings|null); + } + + /** Represents a PythonSettings. */ + class PythonSettings implements IPythonSettings { + + /** + * Constructs a new PythonSettings. + * @param [properties] Properties to set + */ + constructor(properties?: google.api.IPythonSettings); + + /** PythonSettings common. */ + public common?: (google.api.ICommonLanguageSettings|null); + + /** + * Creates a PythonSettings message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns PythonSettings + */ + public static fromObject(object: { [k: string]: any }): google.api.PythonSettings; + + /** + * Creates a plain object from a PythonSettings message. Also converts values to other types if specified. + * @param message PythonSettings + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.api.PythonSettings, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this PythonSettings to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for PythonSettings + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a NodeSettings. */ + interface INodeSettings { + + /** NodeSettings common */ + common?: (google.api.ICommonLanguageSettings|null); + } + + /** Represents a NodeSettings. */ + class NodeSettings implements INodeSettings { + + /** + * Constructs a new NodeSettings. + * @param [properties] Properties to set + */ + constructor(properties?: google.api.INodeSettings); + + /** NodeSettings common. */ + public common?: (google.api.ICommonLanguageSettings|null); + + /** + * Creates a NodeSettings message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns NodeSettings + */ + public static fromObject(object: { [k: string]: any }): google.api.NodeSettings; + + /** + * Creates a plain object from a NodeSettings message. Also converts values to other types if specified. + * @param message NodeSettings + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.api.NodeSettings, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this NodeSettings to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for NodeSettings + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } - /** Namespace api. */ - namespace api { + /** Properties of a DotnetSettings. */ + interface IDotnetSettings { - /** Properties of a Http. */ - interface IHttp { + /** DotnetSettings common */ + common?: (google.api.ICommonLanguageSettings|null); - /** Http rules */ - rules?: (google.api.IHttpRule[]|null); + /** DotnetSettings renamedServices */ + renamedServices?: ({ [k: string]: string }|null); + + /** DotnetSettings renamedResources */ + renamedResources?: ({ [k: string]: string }|null); + + /** DotnetSettings ignoredResources */ + ignoredResources?: (string[]|null); + + /** DotnetSettings forcedNamespaceAliases */ + forcedNamespaceAliases?: (string[]|null); + + /** DotnetSettings handwrittenSignatures */ + handwrittenSignatures?: (string[]|null); } - /** Represents a Http. */ - class Http implements IHttp { + /** Represents a DotnetSettings. */ + class DotnetSettings implements IDotnetSettings { /** - * Constructs a new Http. + * Constructs a new DotnetSettings. * @param [properties] Properties to set */ - constructor(properties?: google.api.IHttp); + constructor(properties?: google.api.IDotnetSettings); - /** Http rules. */ - public rules: google.api.IHttpRule[]; + /** DotnetSettings common. */ + public common?: (google.api.ICommonLanguageSettings|null); + + /** DotnetSettings renamedServices. */ + public renamedServices: { [k: string]: string }; + + /** DotnetSettings renamedResources. */ + public renamedResources: { [k: string]: string }; + + /** DotnetSettings ignoredResources. */ + public ignoredResources: string[]; + + /** DotnetSettings forcedNamespaceAliases. */ + public forcedNamespaceAliases: string[]; + + /** DotnetSettings handwrittenSignatures. */ + public handwrittenSignatures: string[]; /** - * Creates a Http message from a plain object. Also converts values to their respective internal types. + * Creates a DotnetSettings message from a plain object. Also converts values to their respective internal types. * @param object Plain object - * @returns Http + * @returns DotnetSettings */ - public static fromObject(object: { [k: string]: any }): google.api.Http; + public static fromObject(object: { [k: string]: any }): google.api.DotnetSettings; /** - * Creates a plain object from a Http message. Also converts values to other types if specified. - * @param message Http + * Creates a plain object from a DotnetSettings message. Also converts values to other types if specified. + * @param message DotnetSettings * @param [options] Conversion options * @returns Plain object */ - public static toObject(message: google.api.Http, options?: $protobuf.IConversionOptions): { [k: string]: any }; + public static toObject(message: google.api.DotnetSettings, options?: $protobuf.IConversionOptions): { [k: string]: any }; /** - * Converts this Http to JSON. + * Converts this DotnetSettings to JSON. * @returns JSON object */ public toJSON(): { [k: string]: any }; - } - - /** Properties of a HttpRule. */ - interface IHttpRule { - - /** HttpRule get */ - get?: (string|null); - - /** HttpRule put */ - put?: (string|null); - - /** HttpRule post */ - post?: (string|null); - - /** HttpRule delete */ - "delete"?: (string|null); - - /** HttpRule patch */ - patch?: (string|null); - /** HttpRule custom */ - custom?: (google.api.ICustomHttpPattern|null); - - /** HttpRule selector */ - selector?: (string|null); + /** + * Gets the default type url for DotnetSettings + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } - /** HttpRule body */ - body?: (string|null); + /** Properties of a RubySettings. */ + interface IRubySettings { - /** HttpRule additionalBindings */ - additionalBindings?: (google.api.IHttpRule[]|null); + /** RubySettings common */ + common?: (google.api.ICommonLanguageSettings|null); } - /** Represents a HttpRule. */ - class HttpRule implements IHttpRule { + /** Represents a RubySettings. */ + class RubySettings implements IRubySettings { /** - * Constructs a new HttpRule. + * Constructs a new RubySettings. * @param [properties] Properties to set */ - constructor(properties?: google.api.IHttpRule); + constructor(properties?: google.api.IRubySettings); - /** HttpRule get. */ - public get?: (string|null); + /** RubySettings common. */ + public common?: (google.api.ICommonLanguageSettings|null); - /** HttpRule put. */ - public put?: (string|null); + /** + * Creates a RubySettings message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns RubySettings + */ + public static fromObject(object: { [k: string]: any }): google.api.RubySettings; - /** HttpRule post. */ - public post?: (string|null); + /** + * Creates a plain object from a RubySettings message. Also converts values to other types if specified. + * @param message RubySettings + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.api.RubySettings, options?: $protobuf.IConversionOptions): { [k: string]: any }; - /** HttpRule delete. */ - public delete?: (string|null); + /** + * Converts this RubySettings to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; - /** HttpRule patch. */ - public patch?: (string|null); + /** + * Gets the default type url for RubySettings + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } - /** HttpRule custom. */ - public custom?: (google.api.ICustomHttpPattern|null); + /** Properties of a GoSettings. */ + interface IGoSettings { - /** HttpRule selector. */ - public selector: string; + /** GoSettings common */ + common?: (google.api.ICommonLanguageSettings|null); + } - /** HttpRule body. */ - public body: string; + /** Represents a GoSettings. */ + class GoSettings implements IGoSettings { - /** HttpRule additionalBindings. */ - public additionalBindings: google.api.IHttpRule[]; + /** + * Constructs a new GoSettings. + * @param [properties] Properties to set + */ + constructor(properties?: google.api.IGoSettings); - /** HttpRule pattern. */ - public pattern?: ("get"|"put"|"post"|"delete"|"patch"|"custom"); + /** GoSettings common. */ + public common?: (google.api.ICommonLanguageSettings|null); /** - * Creates a HttpRule message from a plain object. Also converts values to their respective internal types. + * Creates a GoSettings message from a plain object. Also converts values to their respective internal types. * @param object Plain object - * @returns HttpRule + * @returns GoSettings */ - public static fromObject(object: { [k: string]: any }): google.api.HttpRule; + public static fromObject(object: { [k: string]: any }): google.api.GoSettings; /** - * Creates a plain object from a HttpRule message. Also converts values to other types if specified. - * @param message HttpRule + * Creates a plain object from a GoSettings message. Also converts values to other types if specified. + * @param message GoSettings * @param [options] Conversion options * @returns Plain object */ - public static toObject(message: google.api.HttpRule, options?: $protobuf.IConversionOptions): { [k: string]: any }; + public static toObject(message: google.api.GoSettings, options?: $protobuf.IConversionOptions): { [k: string]: any }; /** - * Converts this HttpRule to JSON. + * Converts this GoSettings to JSON. * @returns JSON object */ public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for GoSettings + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; } - /** Properties of a CustomHttpPattern. */ - interface ICustomHttpPattern { + /** Properties of a MethodSettings. */ + interface IMethodSettings { - /** CustomHttpPattern kind */ - kind?: (string|null); + /** MethodSettings selector */ + selector?: (string|null); - /** CustomHttpPattern path */ - path?: (string|null); + /** MethodSettings longRunning */ + longRunning?: (google.api.MethodSettings.ILongRunning|null); + + /** MethodSettings autoPopulatedFields */ + autoPopulatedFields?: (string[]|null); } - /** Represents a CustomHttpPattern. */ - class CustomHttpPattern implements ICustomHttpPattern { + /** Represents a MethodSettings. */ + class MethodSettings implements IMethodSettings { /** - * Constructs a new CustomHttpPattern. + * Constructs a new MethodSettings. * @param [properties] Properties to set */ - constructor(properties?: google.api.ICustomHttpPattern); + constructor(properties?: google.api.IMethodSettings); - /** CustomHttpPattern kind. */ - public kind: string; + /** MethodSettings selector. */ + public selector: string; - /** CustomHttpPattern path. */ - public path: string; + /** MethodSettings longRunning. */ + public longRunning?: (google.api.MethodSettings.ILongRunning|null); + + /** MethodSettings autoPopulatedFields. */ + public autoPopulatedFields: string[]; /** - * Creates a CustomHttpPattern message from a plain object. Also converts values to their respective internal types. + * Creates a MethodSettings message from a plain object. Also converts values to their respective internal types. * @param object Plain object - * @returns CustomHttpPattern + * @returns MethodSettings */ - public static fromObject(object: { [k: string]: any }): google.api.CustomHttpPattern; + public static fromObject(object: { [k: string]: any }): google.api.MethodSettings; /** - * Creates a plain object from a CustomHttpPattern message. Also converts values to other types if specified. - * @param message CustomHttpPattern + * Creates a plain object from a MethodSettings message. Also converts values to other types if specified. + * @param message MethodSettings * @param [options] Conversion options * @returns Plain object */ - public static toObject(message: google.api.CustomHttpPattern, options?: $protobuf.IConversionOptions): { [k: string]: any }; + public static toObject(message: google.api.MethodSettings, options?: $protobuf.IConversionOptions): { [k: string]: any }; /** - * Converts this CustomHttpPattern to JSON. + * Converts this MethodSettings to JSON. * @returns JSON object */ public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for MethodSettings + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + namespace MethodSettings { + + /** Properties of a LongRunning. */ + interface ILongRunning { + + /** LongRunning initialPollDelay */ + initialPollDelay?: (google.protobuf.IDuration|null); + + /** LongRunning pollDelayMultiplier */ + pollDelayMultiplier?: (number|null); + + /** LongRunning maxPollDelay */ + maxPollDelay?: (google.protobuf.IDuration|null); + + /** LongRunning totalPollTimeout */ + totalPollTimeout?: (google.protobuf.IDuration|null); + } + + /** Represents a LongRunning. */ + class LongRunning implements ILongRunning { + + /** + * Constructs a new LongRunning. + * @param [properties] Properties to set + */ + constructor(properties?: google.api.MethodSettings.ILongRunning); + + /** LongRunning initialPollDelay. */ + public initialPollDelay?: (google.protobuf.IDuration|null); + + /** LongRunning pollDelayMultiplier. */ + public pollDelayMultiplier: number; + + /** LongRunning maxPollDelay. */ + public maxPollDelay?: (google.protobuf.IDuration|null); + + /** LongRunning totalPollTimeout. */ + public totalPollTimeout?: (google.protobuf.IDuration|null); + + /** + * Creates a LongRunning message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns LongRunning + */ + public static fromObject(object: { [k: string]: any }): google.api.MethodSettings.LongRunning; + + /** + * Creates a plain object from a LongRunning message. Also converts values to other types if specified. + * @param message LongRunning + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.api.MethodSettings.LongRunning, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this LongRunning to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for LongRunning + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } } + /** ClientLibraryOrganization enum. */ + type ClientLibraryOrganization = + "CLIENT_LIBRARY_ORGANIZATION_UNSPECIFIED"| "CLOUD"| "ADS"| "PHOTOS"| "STREET_VIEW"| "SHOPPING"| "GEO"| "GENERATIVE_AI"; + + /** ClientLibraryDestination enum. */ + type ClientLibraryDestination = + "CLIENT_LIBRARY_DESTINATION_UNSPECIFIED"| "GITHUB"| "PACKAGE_MANAGER"; + + /** LaunchStage enum. */ + type LaunchStage = + "LAUNCH_STAGE_UNSPECIFIED"| "UNIMPLEMENTED"| "PRELAUNCH"| "EARLY_ACCESS"| "ALPHA"| "BETA"| "GA"| "DEPRECATED"; + /** FieldBehavior enum. */ type FieldBehavior = - "FIELD_BEHAVIOR_UNSPECIFIED"| "OPTIONAL"| "REQUIRED"| "OUTPUT_ONLY"| "INPUT_ONLY"| "IMMUTABLE"| "UNORDERED_LIST"| "NON_EMPTY_DEFAULT"; + "FIELD_BEHAVIOR_UNSPECIFIED"| "OPTIONAL"| "REQUIRED"| "OUTPUT_ONLY"| "INPUT_ONLY"| "IMMUTABLE"| "UNORDERED_LIST"| "NON_EMPTY_DEFAULT"| "IDENTIFIER"; /** Properties of a ResourceDescriptor. */ interface IResourceDescriptor { @@ -6140,6 +8523,13 @@ export namespace google { * @returns JSON object */ public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for ResourceDescriptor + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; } namespace ResourceDescriptor { @@ -6198,57 +8588,13 @@ export namespace google { * @returns JSON object */ public toJSON(): { [k: string]: any }; - } - } - - /** Namespace type. */ - namespace type { - - /** Properties of a LatLng. */ - interface ILatLng { - - /** LatLng latitude */ - latitude?: (number|null); - - /** LatLng longitude */ - longitude?: (number|null); - } - - /** Represents a LatLng. */ - class LatLng implements ILatLng { - - /** - * Constructs a new LatLng. - * @param [properties] Properties to set - */ - constructor(properties?: google.type.ILatLng); - - /** LatLng latitude. */ - public latitude: number; - - /** LatLng longitude. */ - public longitude: number; - - /** - * Creates a LatLng message from a plain object. Also converts values to their respective internal types. - * @param object Plain object - * @returns LatLng - */ - public static fromObject(object: { [k: string]: any }): google.type.LatLng; - - /** - * Creates a plain object from a LatLng message. Also converts values to other types if specified. - * @param message LatLng - * @param [options] Conversion options - * @returns Plain object - */ - public static toObject(message: google.type.LatLng, options?: $protobuf.IConversionOptions): { [k: string]: any }; /** - * Converts this LatLng to JSON. - * @returns JSON object + * Gets the default type url for ResourceReference + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url */ - public toJSON(): { [k: string]: any }; + public static getTypeUrl(typeUrlPrefix?: string): string; } } @@ -6306,6 +8652,13 @@ export namespace google { * @returns JSON object */ public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for Status + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; } } @@ -6498,6 +8851,13 @@ export namespace google { * @returns JSON object */ public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for Operation + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; } /** Properties of a GetOperationRequest. */ @@ -6539,6 +8899,13 @@ export namespace google { * @returns JSON object */ public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for GetOperationRequest + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; } /** Properties of a ListOperationsRequest. */ @@ -6598,6 +8965,13 @@ export namespace google { * @returns JSON object */ public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for ListOperationsRequest + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; } /** Properties of a ListOperationsResponse. */ @@ -6645,6 +9019,13 @@ export namespace google { * @returns JSON object */ public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for ListOperationsResponse + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; } /** Properties of a CancelOperationRequest. */ @@ -6686,6 +9067,13 @@ export namespace google { * @returns JSON object */ public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for CancelOperationRequest + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; } /** Properties of a DeleteOperationRequest. */ @@ -6727,6 +9115,13 @@ export namespace google { * @returns JSON object */ public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for DeleteOperationRequest + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; } /** Properties of a WaitOperationRequest. */ @@ -6774,6 +9169,13 @@ export namespace google { * @returns JSON object */ public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for WaitOperationRequest + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; } /** Properties of an OperationInfo. */ @@ -6821,6 +9223,13 @@ export namespace google { * @returns JSON object */ public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for OperationInfo + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; } } } diff --git a/types/v1/firestore_admin_client.d.ts b/types/v1/firestore_admin_client.d.ts index b9b1ac914..778371c00 100644 --- a/types/v1/firestore_admin_client.d.ts +++ b/types/v1/firestore_admin_client.d.ts @@ -1,5 +1,5 @@ /*! - * Copyright 2022 Google LLC + * 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. @@ -14,15 +14,16 @@ * limitations under the License. */ -/// -import * as gax from 'google-gax'; -import { +import type * as gax from 'google-gax'; +import type { Callback, CallOptions, Descriptors, ClientOptions, LROperation, PaginationCallback, + LocationsClient, + LocationProtos, } from 'google-gax'; import {Transform} from 'stream'; import * as protos from '../protos/firestore_admin_v1_proto_api'; @@ -66,12 +67,15 @@ export declare class FirestoreAdminClient { private _gaxGrpc; private _protos; private _defaults; + private _universeDomain; + private _servicePath; auth: gax.GoogleAuth; descriptors: Descriptors; warn: (code: string, message: string, warnType?: string) => void; innerApiCalls: { [name: string]: Function; }; + locationsClient: LocationsClient; pathTemplates: { [name: string]: gax.PathTemplate; }; @@ -84,7 +88,7 @@ export declare class FirestoreAdminClient { * * @param {object} [options] - The configuration object. * The options accepted by the constructor are described in detail - * in [this document](https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#creating-the-client-instance). + * in [this document](https://github.com/googleapis/gax-nodejs/blob/main/client-libraries.md#creating-the-client-instance). * The common options are: * @param {object} [options.credentials] - Credentials object. * @param {string} [options.credentials.client_email] @@ -107,13 +111,21 @@ export declare class FirestoreAdminClient { * API remote host. * @param {gax.ClientConfig} [options.clientConfig] - Client configuration override. * Follows the structure of {@link gapicConfig}. - * @param {boolean} [options.fallback] - Use HTTP fallback mode. - * In fallback mode, a special browser-compatible transport implementation is used - * instead of gRPC transport. In browser context (if the `window` object is defined) - * the fallback mode is enabled automatically; set `options.fallback` to `false` - * if you need to override this behavior. + * @param {boolean} [options.fallback] - Use HTTP/1.1 REST mode. + * For more information, please check the + * {@link https://github.com/googleapis/gax-nodejs/blob/main/client-libraries.md#http11-rest-api-mode documentation}. + * @param {gax} [gaxInstance]: loaded instance of `google-gax`. Useful if you + * need to avoid loading the default gRPC version and want to use the fallback + * HTTP implementation. Load only fallback version and pass it to the constructor: + * ``` + * const gax = require('google-gax/build/src/fallback'); // avoids loading google-gax with gRPC + * const client = new FirestoreAdminClient({fallback: true}, gax); + * ``` */ - constructor(opts?: ClientOptions); + constructor( + opts?: ClientOptions, + gaxInstance?: typeof gax | typeof gax.fallback + ); /** * Initialize the client. * Performs asynchronous operations (such as authentication) and prepares the client. @@ -130,15 +142,22 @@ export declare class FirestoreAdminClient { }>; /** * The DNS address for this API service. + * @deprecated Use the apiEndpoint method of the client instance. * @returns {string} The DNS address for this service. */ static get servicePath(): string; /** - * The DNS address for this API service - same as servicePath(), - * exists for compatibility reasons. + * The DNS address for this API service - same as servicePath. + * @deprecated Use the apiEndpoint method of the client instance. * @returns {string} The DNS address for this service. */ static get apiEndpoint(): string; + /** + * The DNS address for this API service. + * @returns {string} The DNS address for this service. + */ + get apiEndpoint(): string; + get universeDomain(): string; /** * The port for this API service. * @returns {number} The default port for this service. @@ -163,9 +182,8 @@ export declare class FirestoreAdminClient { * @param {object} [options] * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. * @returns {Promise} - The promise which resolves to an array. - * The first element of the array is an object representing [Index]{@link google.firestore.admin.v1.Index}. - * Please see the - * [documentation](https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods) + * The first element of the array is an object representing {@link protos.google.firestore.admin.v1.Index|Index}. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } * for more details and examples. * @example include:samples/generated/v1/firestore_admin.get_index.js * region_tag:firestore_v1_generated_FirestoreAdmin_GetIndex_async @@ -208,9 +226,8 @@ export declare class FirestoreAdminClient { * @param {object} [options] * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. * @returns {Promise} - The promise which resolves to an array. - * The first element of the array is an object representing [Empty]{@link google.protobuf.Empty}. - * Please see the - * [documentation](https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods) + * The first element of the array is an object representing {@link protos.google.protobuf.Empty|Empty}. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } * for more details and examples. * @example include:samples/generated/v1/firestore_admin.delete_index.js * region_tag:firestore_v1_generated_FirestoreAdmin_DeleteIndex_async @@ -253,9 +270,8 @@ export declare class FirestoreAdminClient { * @param {object} [options] * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. * @returns {Promise} - The promise which resolves to an array. - * The first element of the array is an object representing [Field]{@link google.firestore.admin.v1.Field}. - * Please see the - * [documentation](https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods) + * The first element of the array is an object representing {@link protos.google.firestore.admin.v1.Field|Field}. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } * for more details and examples. * @example include:samples/generated/v1/firestore_admin.get_field.js * region_tag:firestore_v1_generated_FirestoreAdmin_GetField_async @@ -298,9 +314,8 @@ export declare class FirestoreAdminClient { * @param {object} [options] * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. * @returns {Promise} - The promise which resolves to an array. - * The first element of the array is an object representing [Database]{@link google.firestore.admin.v1.Database}. - * Please see the - * [documentation](https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods) + * The first element of the array is an object representing {@link protos.google.firestore.admin.v1.Database|Database}. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } * for more details and examples. * @example include:samples/generated/v1/firestore_admin.get_database.js * region_tag:firestore_v1_generated_FirestoreAdmin_GetDatabase_async @@ -340,12 +355,13 @@ export declare class FirestoreAdminClient { * @param {string} request.parent * Required. A parent name of the form * `projects/{project_id}` + * @param {boolean} request.showDeleted + * If true, also returns deleted resources. * @param {object} [options] * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. * @returns {Promise} - The promise which resolves to an array. - * The first element of the array is an object representing [ListDatabasesResponse]{@link google.firestore.admin.v1.ListDatabasesResponse}. - * Please see the - * [documentation](https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods) + * The first element of the array is an object representing {@link protos.google.firestore.admin.v1.ListDatabasesResponse|ListDatabasesResponse}. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } * for more details and examples. * @example include:samples/generated/v1/firestore_admin.list_databases.js * region_tag:firestore_v1_generated_FirestoreAdmin_ListDatabases_async @@ -378,9 +394,400 @@ export declare class FirestoreAdminClient { > ): void; /** - * Creates a composite index. This returns a {@link google.longrunning.Operation|google.longrunning.Operation} - * which may be used to track the status of the creation. The metadata for - * the operation will be the type {@link google.firestore.admin.v1.IndexOperationMetadata|IndexOperationMetadata}. + * Gets information about a backup. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.name + * Required. Name of the backup to fetch. + * + * Format is `projects/{project}/locations/{location}/backups/{backup}`. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is an object representing {@link protos.google.firestore.admin.v1.Backup|Backup}. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } + * for more details and examples. + * @example include:samples/generated/v1/firestore_admin.get_backup.js + * region_tag:firestore_v1_generated_FirestoreAdmin_GetBackup_async + */ + getBackup( + request?: protos.google.firestore.admin.v1.IGetBackupRequest, + options?: CallOptions + ): Promise< + [ + protos.google.firestore.admin.v1.IBackup, + protos.google.firestore.admin.v1.IGetBackupRequest | undefined, + {} | undefined, + ] + >; + getBackup( + request: protos.google.firestore.admin.v1.IGetBackupRequest, + options: CallOptions, + callback: Callback< + protos.google.firestore.admin.v1.IBackup, + protos.google.firestore.admin.v1.IGetBackupRequest | null | undefined, + {} | null | undefined + > + ): void; + getBackup( + request: protos.google.firestore.admin.v1.IGetBackupRequest, + callback: Callback< + protos.google.firestore.admin.v1.IBackup, + protos.google.firestore.admin.v1.IGetBackupRequest | null | undefined, + {} | null | undefined + > + ): void; + /** + * Lists all the backups. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.parent + * Required. The location to list backups from. + * + * Format is `projects/{project}/locations/{location}`. + * Use `{location} = '-'` to list backups from all locations for the given + * project. This allows listing backups from a single location or from all + * locations. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is an object representing {@link protos.google.firestore.admin.v1.ListBackupsResponse|ListBackupsResponse}. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } + * for more details and examples. + * @example include:samples/generated/v1/firestore_admin.list_backups.js + * region_tag:firestore_v1_generated_FirestoreAdmin_ListBackups_async + */ + listBackups( + request?: protos.google.firestore.admin.v1.IListBackupsRequest, + options?: CallOptions + ): Promise< + [ + protos.google.firestore.admin.v1.IListBackupsResponse, + protos.google.firestore.admin.v1.IListBackupsRequest | undefined, + {} | undefined, + ] + >; + listBackups( + request: protos.google.firestore.admin.v1.IListBackupsRequest, + options: CallOptions, + callback: Callback< + protos.google.firestore.admin.v1.IListBackupsResponse, + protos.google.firestore.admin.v1.IListBackupsRequest | null | undefined, + {} | null | undefined + > + ): void; + listBackups( + request: protos.google.firestore.admin.v1.IListBackupsRequest, + callback: Callback< + protos.google.firestore.admin.v1.IListBackupsResponse, + protos.google.firestore.admin.v1.IListBackupsRequest | null | undefined, + {} | null | undefined + > + ): void; + /** + * Deletes a backup. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.name + * Required. Name of the backup to delete. + * + * format is `projects/{project}/locations/{location}/backups/{backup}`. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is an object representing {@link protos.google.protobuf.Empty|Empty}. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } + * for more details and examples. + * @example include:samples/generated/v1/firestore_admin.delete_backup.js + * region_tag:firestore_v1_generated_FirestoreAdmin_DeleteBackup_async + */ + deleteBackup( + request?: protos.google.firestore.admin.v1.IDeleteBackupRequest, + options?: CallOptions + ): Promise< + [ + protos.google.protobuf.IEmpty, + protos.google.firestore.admin.v1.IDeleteBackupRequest | undefined, + {} | undefined, + ] + >; + deleteBackup( + request: protos.google.firestore.admin.v1.IDeleteBackupRequest, + options: CallOptions, + callback: Callback< + protos.google.protobuf.IEmpty, + protos.google.firestore.admin.v1.IDeleteBackupRequest | null | undefined, + {} | null | undefined + > + ): void; + deleteBackup( + request: protos.google.firestore.admin.v1.IDeleteBackupRequest, + callback: Callback< + protos.google.protobuf.IEmpty, + protos.google.firestore.admin.v1.IDeleteBackupRequest | null | undefined, + {} | null | undefined + > + ): void; + /** + * Creates a backup schedule on a database. + * At most two backup schedules can be configured on a database, one daily + * backup schedule and one weekly backup schedule. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.parent + * Required. The parent database. + * + * Format `projects/{project}/databases/{database}` + * @param {google.firestore.admin.v1.BackupSchedule} request.backupSchedule + * Required. The backup schedule to create. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is an object representing {@link protos.google.firestore.admin.v1.BackupSchedule|BackupSchedule}. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } + * for more details and examples. + * @example include:samples/generated/v1/firestore_admin.create_backup_schedule.js + * region_tag:firestore_v1_generated_FirestoreAdmin_CreateBackupSchedule_async + */ + createBackupSchedule( + request?: protos.google.firestore.admin.v1.ICreateBackupScheduleRequest, + options?: CallOptions + ): Promise< + [ + protos.google.firestore.admin.v1.IBackupSchedule, + protos.google.firestore.admin.v1.ICreateBackupScheduleRequest | undefined, + {} | undefined, + ] + >; + createBackupSchedule( + request: protos.google.firestore.admin.v1.ICreateBackupScheduleRequest, + options: CallOptions, + callback: Callback< + protos.google.firestore.admin.v1.IBackupSchedule, + | protos.google.firestore.admin.v1.ICreateBackupScheduleRequest + | null + | undefined, + {} | null | undefined + > + ): void; + createBackupSchedule( + request: protos.google.firestore.admin.v1.ICreateBackupScheduleRequest, + callback: Callback< + protos.google.firestore.admin.v1.IBackupSchedule, + | protos.google.firestore.admin.v1.ICreateBackupScheduleRequest + | null + | undefined, + {} | null | undefined + > + ): void; + /** + * Gets information about a backup schedule. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.name + * Required. The name of the backup schedule. + * + * Format + * `projects/{project}/databases/{database}/backupSchedules/{backup_schedule}` + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is an object representing {@link protos.google.firestore.admin.v1.BackupSchedule|BackupSchedule}. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } + * for more details and examples. + * @example include:samples/generated/v1/firestore_admin.get_backup_schedule.js + * region_tag:firestore_v1_generated_FirestoreAdmin_GetBackupSchedule_async + */ + getBackupSchedule( + request?: protos.google.firestore.admin.v1.IGetBackupScheduleRequest, + options?: CallOptions + ): Promise< + [ + protos.google.firestore.admin.v1.IBackupSchedule, + protos.google.firestore.admin.v1.IGetBackupScheduleRequest | undefined, + {} | undefined, + ] + >; + getBackupSchedule( + request: protos.google.firestore.admin.v1.IGetBackupScheduleRequest, + options: CallOptions, + callback: Callback< + protos.google.firestore.admin.v1.IBackupSchedule, + | protos.google.firestore.admin.v1.IGetBackupScheduleRequest + | null + | undefined, + {} | null | undefined + > + ): void; + getBackupSchedule( + request: protos.google.firestore.admin.v1.IGetBackupScheduleRequest, + callback: Callback< + protos.google.firestore.admin.v1.IBackupSchedule, + | protos.google.firestore.admin.v1.IGetBackupScheduleRequest + | null + | undefined, + {} | null | undefined + > + ): void; + /** + * List backup schedules. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.parent + * Required. The parent database. + * + * Format is `projects/{project}/databases/{database}`. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is an object representing {@link protos.google.firestore.admin.v1.ListBackupSchedulesResponse|ListBackupSchedulesResponse}. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } + * for more details and examples. + * @example include:samples/generated/v1/firestore_admin.list_backup_schedules.js + * region_tag:firestore_v1_generated_FirestoreAdmin_ListBackupSchedules_async + */ + listBackupSchedules( + request?: protos.google.firestore.admin.v1.IListBackupSchedulesRequest, + options?: CallOptions + ): Promise< + [ + protos.google.firestore.admin.v1.IListBackupSchedulesResponse, + protos.google.firestore.admin.v1.IListBackupSchedulesRequest | undefined, + {} | undefined, + ] + >; + listBackupSchedules( + request: protos.google.firestore.admin.v1.IListBackupSchedulesRequest, + options: CallOptions, + callback: Callback< + protos.google.firestore.admin.v1.IListBackupSchedulesResponse, + | protos.google.firestore.admin.v1.IListBackupSchedulesRequest + | null + | undefined, + {} | null | undefined + > + ): void; + listBackupSchedules( + request: protos.google.firestore.admin.v1.IListBackupSchedulesRequest, + callback: Callback< + protos.google.firestore.admin.v1.IListBackupSchedulesResponse, + | protos.google.firestore.admin.v1.IListBackupSchedulesRequest + | null + | undefined, + {} | null | undefined + > + ): void; + /** + * Updates a backup schedule. + * + * @param {Object} request + * The request object that will be sent. + * @param {google.firestore.admin.v1.BackupSchedule} request.backupSchedule + * Required. The backup schedule to update. + * @param {google.protobuf.FieldMask} request.updateMask + * The list of fields to be updated. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is an object representing {@link protos.google.firestore.admin.v1.BackupSchedule|BackupSchedule}. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } + * for more details and examples. + * @example include:samples/generated/v1/firestore_admin.update_backup_schedule.js + * region_tag:firestore_v1_generated_FirestoreAdmin_UpdateBackupSchedule_async + */ + updateBackupSchedule( + request?: protos.google.firestore.admin.v1.IUpdateBackupScheduleRequest, + options?: CallOptions + ): Promise< + [ + protos.google.firestore.admin.v1.IBackupSchedule, + protos.google.firestore.admin.v1.IUpdateBackupScheduleRequest | undefined, + {} | undefined, + ] + >; + updateBackupSchedule( + request: protos.google.firestore.admin.v1.IUpdateBackupScheduleRequest, + options: CallOptions, + callback: Callback< + protos.google.firestore.admin.v1.IBackupSchedule, + | protos.google.firestore.admin.v1.IUpdateBackupScheduleRequest + | null + | undefined, + {} | null | undefined + > + ): void; + updateBackupSchedule( + request: protos.google.firestore.admin.v1.IUpdateBackupScheduleRequest, + callback: Callback< + protos.google.firestore.admin.v1.IBackupSchedule, + | protos.google.firestore.admin.v1.IUpdateBackupScheduleRequest + | null + | undefined, + {} | null | undefined + > + ): void; + /** + * Deletes a backup schedule. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.name + * Required. The name of the backup schedule. + * + * Format + * `projects/{project}/databases/{database}/backupSchedules/{backup_schedule}` + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is an object representing {@link protos.google.protobuf.Empty|Empty}. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } + * for more details and examples. + * @example include:samples/generated/v1/firestore_admin.delete_backup_schedule.js + * region_tag:firestore_v1_generated_FirestoreAdmin_DeleteBackupSchedule_async + */ + deleteBackupSchedule( + request?: protos.google.firestore.admin.v1.IDeleteBackupScheduleRequest, + options?: CallOptions + ): Promise< + [ + protos.google.protobuf.IEmpty, + protos.google.firestore.admin.v1.IDeleteBackupScheduleRequest | undefined, + {} | undefined, + ] + >; + deleteBackupSchedule( + request: protos.google.firestore.admin.v1.IDeleteBackupScheduleRequest, + options: CallOptions, + callback: Callback< + protos.google.protobuf.IEmpty, + | protos.google.firestore.admin.v1.IDeleteBackupScheduleRequest + | null + | undefined, + {} | null | undefined + > + ): void; + deleteBackupSchedule( + request: protos.google.firestore.admin.v1.IDeleteBackupScheduleRequest, + callback: Callback< + protos.google.protobuf.IEmpty, + | protos.google.firestore.admin.v1.IDeleteBackupScheduleRequest + | null + | undefined, + {} | null | undefined + > + ): void; + /** + * Creates a composite index. This returns a + * {@link protos.google.longrunning.Operation|google.longrunning.Operation} which may be + * used to track the status of the creation. The metadata for the operation + * will be the type + * {@link protos.google.firestore.admin.v1.IndexOperationMetadata|IndexOperationMetadata}. * * @param {Object} request * The request object that will be sent. @@ -395,8 +802,7 @@ export declare class FirestoreAdminClient { * The first element of the array is an object representing * a long running operation. Its `promise()` method returns a promise * you can `await` for. - * Please see the - * [documentation](https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#long-running-operations) + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#long-running-operations | documentation } * for more details and examples. * @example include:samples/generated/v1/firestore_admin.create_index.js * region_tag:firestore_v1_generated_FirestoreAdmin_CreateIndex_async @@ -443,8 +849,7 @@ export declare class FirestoreAdminClient { * The operation name that will be passed. * @returns {Promise} - The promise which resolves to an object. * The decoded operation object has result and metadata field to get information from. - * Please see the - * [documentation](https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#long-running-operations) + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#long-running-operations | documentation } * for more details and examples. * @example include:samples/generated/v1/firestore_admin.create_index.js * region_tag:firestore_v1_generated_FirestoreAdmin_CreateIndex_async @@ -460,13 +865,16 @@ export declare class FirestoreAdminClient { /** * Updates a field configuration. Currently, field updates apply only to * single field index configuration. However, calls to - * {@link google.firestore.admin.v1.FirestoreAdmin.UpdateField|FirestoreAdmin.UpdateField} should provide a field mask to avoid - * changing any configuration that the caller isn't aware of. The field mask - * should be specified as: `{ paths: "index_config" }`. + * {@link protos.google.firestore.admin.v1.FirestoreAdmin.UpdateField|FirestoreAdmin.UpdateField} + * should provide a field mask to avoid changing any configuration that the + * caller isn't aware of. The field mask should be specified as: `{ paths: + * "index_config" }`. * - * This call returns a {@link google.longrunning.Operation|google.longrunning.Operation} which may be used to - * track the status of the field update. The metadata for - * the operation will be the type {@link google.firestore.admin.v1.FieldOperationMetadata|FieldOperationMetadata}. + * This call returns a + * {@link protos.google.longrunning.Operation|google.longrunning.Operation} which may be + * used to track the status of the field update. The metadata for the + * operation will be the type + * {@link protos.google.firestore.admin.v1.FieldOperationMetadata|FieldOperationMetadata}. * * To configure the default field settings for the database, use * the special `Field` with resource name: @@ -485,8 +893,7 @@ export declare class FirestoreAdminClient { * The first element of the array is an object representing * a long running operation. Its `promise()` method returns a promise * you can `await` for. - * Please see the - * [documentation](https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#long-running-operations) + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#long-running-operations | documentation } * for more details and examples. * @example include:samples/generated/v1/firestore_admin.update_field.js * region_tag:firestore_v1_generated_FirestoreAdmin_UpdateField_async @@ -533,8 +940,7 @@ export declare class FirestoreAdminClient { * The operation name that will be passed. * @returns {Promise} - The promise which resolves to an object. * The decoded operation object has result and metadata field to get information from. - * Please see the - * [documentation](https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#long-running-operations) + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#long-running-operations | documentation } * for more details and examples. * @example include:samples/generated/v1/firestore_admin.update_field.js * region_tag:firestore_v1_generated_FirestoreAdmin_UpdateField_async @@ -566,7 +972,8 @@ export declare class FirestoreAdminClient { * Required. Database to export. Should be of the form: * `projects/{project_id}/databases/{database_id}`. * @param {string[]} request.collectionIds - * Which collection ids to export. Unspecified means all collections. + * Which collection ids to export. Unspecified means all collections. Each + * collection id in this list must be unique. * @param {string} request.outputUriPrefix * The output URI. Currently only supports Google Cloud Storage URIs of the * form: `gs://BUCKET_NAME[/NAMESPACE_PATH]`, where `BUCKET_NAME` is the name @@ -576,14 +983,28 @@ export declare class FirestoreAdminClient { * guidelines: https://cloud.google.com/storage/docs/naming. * If the URI is a bucket (without a namespace path), a prefix will be * generated based on the start time. + * @param {string[]} request.namespaceIds + * An empty list represents all namespaces. This is the preferred + * usage for databases that don't use namespaces. + * + * An empty string element represents the default namespace. This should be + * used if the database has data in non-default namespaces, but doesn't want + * to include them. Each namespace in this list must be unique. + * @param {google.protobuf.Timestamp} request.snapshotTime + * The timestamp that corresponds to the version of the database to be + * exported. The timestamp must be in the past, rounded to the minute and not + * older than + * {@link protos.google.firestore.admin.v1.Database.earliest_version_time|earliestVersionTime}. + * If specified, then the exported documents will represent a consistent view + * of the database at the provided time. Otherwise, there are no guarantees + * about the consistency of the exported documents. * @param {object} [options] * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. * @returns {Promise} - The promise which resolves to an array. * The first element of the array is an object representing * a long running operation. Its `promise()` method returns a promise * you can `await` for. - * Please see the - * [documentation](https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#long-running-operations) + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#long-running-operations | documentation } * for more details and examples. * @example include:samples/generated/v1/firestore_admin.export_documents.js * region_tag:firestore_v1_generated_FirestoreAdmin_ExportDocuments_async @@ -630,8 +1051,7 @@ export declare class FirestoreAdminClient { * The operation name that will be passed. * @returns {Promise} - The promise which resolves to an object. * The decoded operation object has result and metadata field to get information from. - * Please see the - * [documentation](https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#long-running-operations) + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#long-running-operations | documentation } * for more details and examples. * @example include:samples/generated/v1/firestore_admin.export_documents.js * region_tag:firestore_v1_generated_FirestoreAdmin_ExportDocuments_async @@ -658,21 +1078,27 @@ export declare class FirestoreAdminClient { * `projects/{project_id}/databases/{database_id}`. * @param {string[]} request.collectionIds * Which collection ids to import. Unspecified means all collections included - * in the import. + * in the import. Each collection id in this list must be unique. * @param {string} request.inputUriPrefix * Location of the exported files. * This must match the output_uri_prefix of an ExportDocumentsResponse from * an export that has completed successfully. * See: - * {@link google.firestore.admin.v1.ExportDocumentsResponse.output_uri_prefix|google.firestore.admin.v1.ExportDocumentsResponse.output_uri_prefix}. + * {@link protos.google.firestore.admin.v1.ExportDocumentsResponse.output_uri_prefix|google.firestore.admin.v1.ExportDocumentsResponse.output_uri_prefix}. + * @param {string[]} request.namespaceIds + * An empty list represents all namespaces. This is the preferred + * usage for databases that don't use namespaces. + * + * An empty string element represents the default namespace. This should be + * used if the database has data in non-default namespaces, but doesn't want + * to include them. Each namespace in this list must be unique. * @param {object} [options] * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. * @returns {Promise} - The promise which resolves to an array. * The first element of the array is an object representing * a long running operation. Its `promise()` method returns a promise * you can `await` for. - * Please see the - * [documentation](https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#long-running-operations) + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#long-running-operations | documentation } * for more details and examples. * @example include:samples/generated/v1/firestore_admin.import_documents.js * region_tag:firestore_v1_generated_FirestoreAdmin_ImportDocuments_async @@ -719,8 +1145,7 @@ export declare class FirestoreAdminClient { * The operation name that will be passed. * @returns {Promise} - The promise which resolves to an object. * The decoded operation object has result and metadata field to get information from. - * Please see the - * [documentation](https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#long-running-operations) + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#long-running-operations | documentation } * for more details and examples. * @example include:samples/generated/v1/firestore_admin.import_documents.js * region_tag:firestore_v1_generated_FirestoreAdmin_ImportDocuments_async @@ -734,109 +1159,471 @@ export declare class FirestoreAdminClient { > >; /** - * Updates a database. + * Bulk deletes a subset of documents from Google Cloud Firestore. + * Documents created or updated after the underlying system starts to process + * the request will not be deleted. The bulk delete occurs in the background + * and its progress can be monitored and managed via the Operation resource + * that is created. + * + * For more details on bulk delete behavior, refer to: + * https://cloud.google.com/firestore/docs/manage-data/bulk-delete * * @param {Object} request * The request object that will be sent. - * @param {google.firestore.admin.v1.Database} request.database - * Required. The database to update. - * @param {google.protobuf.FieldMask} request.updateMask - * The list of fields to be updated. + * @param {string} request.name + * Required. Database to operate. Should be of the form: + * `projects/{project_id}/databases/{database_id}`. + * @param {string[]} [request.collectionIds] + * Optional. IDs of the collection groups to delete. Unspecified means all + * collection groups. + * + * Each collection group in this list must be unique. + * @param {string[]} [request.namespaceIds] + * Optional. Namespaces to delete. + * + * An empty list means all namespaces. This is the recommended + * usage for databases that don't use namespaces. + * + * An empty string element represents the default namespace. This should be + * used if the database has data in non-default namespaces, but doesn't want + * to delete from them. + * + * Each namespace in this list must be unique. * @param {object} [options] * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. * @returns {Promise} - The promise which resolves to an array. * The first element of the array is an object representing * a long running operation. Its `promise()` method returns a promise * you can `await` for. - * Please see the - * [documentation](https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#long-running-operations) + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#long-running-operations | documentation } * for more details and examples. - * @example include:samples/generated/v1/firestore_admin.update_database.js - * region_tag:firestore_v1_generated_FirestoreAdmin_UpdateDatabase_async + * @example include:samples/generated/v1/firestore_admin.bulk_delete_documents.js + * region_tag:firestore_v1_generated_FirestoreAdmin_BulkDeleteDocuments_async */ - updateDatabase( - request?: protos.google.firestore.admin.v1.IUpdateDatabaseRequest, + bulkDeleteDocuments( + request?: protos.google.firestore.admin.v1.IBulkDeleteDocumentsRequest, options?: CallOptions ): Promise< [ LROperation< - protos.google.firestore.admin.v1.IDatabase, - protos.google.firestore.admin.v1.IUpdateDatabaseMetadata + protos.google.firestore.admin.v1.IBulkDeleteDocumentsResponse, + protos.google.firestore.admin.v1.IBulkDeleteDocumentsMetadata >, protos.google.longrunning.IOperation | undefined, {} | undefined, ] >; - updateDatabase( - request: protos.google.firestore.admin.v1.IUpdateDatabaseRequest, + bulkDeleteDocuments( + request: protos.google.firestore.admin.v1.IBulkDeleteDocumentsRequest, options: CallOptions, callback: Callback< LROperation< - protos.google.firestore.admin.v1.IDatabase, - protos.google.firestore.admin.v1.IUpdateDatabaseMetadata + protos.google.firestore.admin.v1.IBulkDeleteDocumentsResponse, + protos.google.firestore.admin.v1.IBulkDeleteDocumentsMetadata >, protos.google.longrunning.IOperation | null | undefined, {} | null | undefined > ): void; - updateDatabase( - request: protos.google.firestore.admin.v1.IUpdateDatabaseRequest, + bulkDeleteDocuments( + request: protos.google.firestore.admin.v1.IBulkDeleteDocumentsRequest, callback: Callback< LROperation< - protos.google.firestore.admin.v1.IDatabase, - protos.google.firestore.admin.v1.IUpdateDatabaseMetadata + protos.google.firestore.admin.v1.IBulkDeleteDocumentsResponse, + protos.google.firestore.admin.v1.IBulkDeleteDocumentsMetadata >, protos.google.longrunning.IOperation | null | undefined, {} | null | undefined > ): void; /** - * Check the status of the long running operation returned by `updateDatabase()`. + * Check the status of the long running operation returned by `bulkDeleteDocuments()`. * @param {String} name * The operation name that will be passed. * @returns {Promise} - The promise which resolves to an object. * The decoded operation object has result and metadata field to get information from. - * Please see the - * [documentation](https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#long-running-operations) + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#long-running-operations | documentation } * for more details and examples. - * @example include:samples/generated/v1/firestore_admin.update_database.js - * region_tag:firestore_v1_generated_FirestoreAdmin_UpdateDatabase_async + * @example include:samples/generated/v1/firestore_admin.bulk_delete_documents.js + * region_tag:firestore_v1_generated_FirestoreAdmin_BulkDeleteDocuments_async */ - checkUpdateDatabaseProgress( + checkBulkDeleteDocumentsProgress( name: string ): Promise< LROperation< - protos.google.firestore.admin.v1.Database, - protos.google.firestore.admin.v1.UpdateDatabaseMetadata + protos.google.firestore.admin.v1.BulkDeleteDocumentsResponse, + protos.google.firestore.admin.v1.BulkDeleteDocumentsMetadata > >; /** - * Lists composite indexes. + * Create a database. * * @param {Object} request * The request object that will be sent. * @param {string} request.parent * Required. A parent name of the form - * `projects/{project_id}/databases/{database_id}/collectionGroups/{collection_id}` - * @param {string} request.filter - * The filter to apply to list results. + * `projects/{project_id}` + * @param {google.firestore.admin.v1.Database} request.database + * Required. The Database to create. + * @param {string} request.databaseId + * Required. The ID to use for the database, which will become the final + * component of the database's resource name. + * + * This value should be 4-63 characters. Valid characters are /{@link protos.0-9|a-z}-/ + * with first character a letter and the last a letter or a number. Must not + * be UUID-like /[0-9a-f]{8}(-[0-9a-f]{4}){3}-[0-9a-f]{12}/. + * + * "(default)" database id is also valid. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is an object representing + * a long running operation. Its `promise()` method returns a promise + * you can `await` for. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#long-running-operations | documentation } + * for more details and examples. + * @example include:samples/generated/v1/firestore_admin.create_database.js + * region_tag:firestore_v1_generated_FirestoreAdmin_CreateDatabase_async + */ + createDatabase( + request?: protos.google.firestore.admin.v1.ICreateDatabaseRequest, + options?: CallOptions + ): Promise< + [ + LROperation< + protos.google.firestore.admin.v1.IDatabase, + protos.google.firestore.admin.v1.ICreateDatabaseMetadata + >, + protos.google.longrunning.IOperation | undefined, + {} | undefined, + ] + >; + createDatabase( + request: protos.google.firestore.admin.v1.ICreateDatabaseRequest, + options: CallOptions, + callback: Callback< + LROperation< + protos.google.firestore.admin.v1.IDatabase, + protos.google.firestore.admin.v1.ICreateDatabaseMetadata + >, + protos.google.longrunning.IOperation | null | undefined, + {} | null | undefined + > + ): void; + createDatabase( + request: protos.google.firestore.admin.v1.ICreateDatabaseRequest, + callback: Callback< + LROperation< + protos.google.firestore.admin.v1.IDatabase, + protos.google.firestore.admin.v1.ICreateDatabaseMetadata + >, + protos.google.longrunning.IOperation | null | undefined, + {} | null | undefined + > + ): void; + /** + * Check the status of the long running operation returned by `createDatabase()`. + * @param {String} name + * The operation name that will be passed. + * @returns {Promise} - The promise which resolves to an object. + * The decoded operation object has result and metadata field to get information from. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#long-running-operations | documentation } + * for more details and examples. + * @example include:samples/generated/v1/firestore_admin.create_database.js + * region_tag:firestore_v1_generated_FirestoreAdmin_CreateDatabase_async + */ + checkCreateDatabaseProgress( + name: string + ): Promise< + LROperation< + protos.google.firestore.admin.v1.Database, + protos.google.firestore.admin.v1.CreateDatabaseMetadata + > + >; + /** + * Updates a database. + * + * @param {Object} request + * The request object that will be sent. + * @param {google.firestore.admin.v1.Database} request.database + * Required. The database to update. + * @param {google.protobuf.FieldMask} request.updateMask + * The list of fields to be updated. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is an object representing + * a long running operation. Its `promise()` method returns a promise + * you can `await` for. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#long-running-operations | documentation } + * for more details and examples. + * @example include:samples/generated/v1/firestore_admin.update_database.js + * region_tag:firestore_v1_generated_FirestoreAdmin_UpdateDatabase_async + */ + updateDatabase( + request?: protos.google.firestore.admin.v1.IUpdateDatabaseRequest, + options?: CallOptions + ): Promise< + [ + LROperation< + protos.google.firestore.admin.v1.IDatabase, + protos.google.firestore.admin.v1.IUpdateDatabaseMetadata + >, + protos.google.longrunning.IOperation | undefined, + {} | undefined, + ] + >; + updateDatabase( + request: protos.google.firestore.admin.v1.IUpdateDatabaseRequest, + options: CallOptions, + callback: Callback< + LROperation< + protos.google.firestore.admin.v1.IDatabase, + protos.google.firestore.admin.v1.IUpdateDatabaseMetadata + >, + protos.google.longrunning.IOperation | null | undefined, + {} | null | undefined + > + ): void; + updateDatabase( + request: protos.google.firestore.admin.v1.IUpdateDatabaseRequest, + callback: Callback< + LROperation< + protos.google.firestore.admin.v1.IDatabase, + protos.google.firestore.admin.v1.IUpdateDatabaseMetadata + >, + protos.google.longrunning.IOperation | null | undefined, + {} | null | undefined + > + ): void; + /** + * Check the status of the long running operation returned by `updateDatabase()`. + * @param {String} name + * The operation name that will be passed. + * @returns {Promise} - The promise which resolves to an object. + * The decoded operation object has result and metadata field to get information from. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#long-running-operations | documentation } + * for more details and examples. + * @example include:samples/generated/v1/firestore_admin.update_database.js + * region_tag:firestore_v1_generated_FirestoreAdmin_UpdateDatabase_async + */ + checkUpdateDatabaseProgress( + name: string + ): Promise< + LROperation< + protos.google.firestore.admin.v1.Database, + protos.google.firestore.admin.v1.UpdateDatabaseMetadata + > + >; + /** + * Deletes a database. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.name + * Required. A name of the form + * `projects/{project_id}/databases/{database_id}` + * @param {string} request.etag + * The current etag of the Database. + * If an etag is provided and does not match the current etag of the database, + * deletion will be blocked and a FAILED_PRECONDITION error will be returned. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is an object representing + * a long running operation. Its `promise()` method returns a promise + * you can `await` for. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#long-running-operations | documentation } + * for more details and examples. + * @example include:samples/generated/v1/firestore_admin.delete_database.js + * region_tag:firestore_v1_generated_FirestoreAdmin_DeleteDatabase_async + */ + deleteDatabase( + request?: protos.google.firestore.admin.v1.IDeleteDatabaseRequest, + options?: CallOptions + ): Promise< + [ + LROperation< + protos.google.firestore.admin.v1.IDatabase, + protos.google.firestore.admin.v1.IDeleteDatabaseMetadata + >, + protos.google.longrunning.IOperation | undefined, + {} | undefined, + ] + >; + deleteDatabase( + request: protos.google.firestore.admin.v1.IDeleteDatabaseRequest, + options: CallOptions, + callback: Callback< + LROperation< + protos.google.firestore.admin.v1.IDatabase, + protos.google.firestore.admin.v1.IDeleteDatabaseMetadata + >, + protos.google.longrunning.IOperation | null | undefined, + {} | null | undefined + > + ): void; + deleteDatabase( + request: protos.google.firestore.admin.v1.IDeleteDatabaseRequest, + callback: Callback< + LROperation< + protos.google.firestore.admin.v1.IDatabase, + protos.google.firestore.admin.v1.IDeleteDatabaseMetadata + >, + protos.google.longrunning.IOperation | null | undefined, + {} | null | undefined + > + ): void; + /** + * Check the status of the long running operation returned by `deleteDatabase()`. + * @param {String} name + * The operation name that will be passed. + * @returns {Promise} - The promise which resolves to an object. + * The decoded operation object has result and metadata field to get information from. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#long-running-operations | documentation } + * for more details and examples. + * @example include:samples/generated/v1/firestore_admin.delete_database.js + * region_tag:firestore_v1_generated_FirestoreAdmin_DeleteDatabase_async + */ + checkDeleteDatabaseProgress( + name: string + ): Promise< + LROperation< + protos.google.firestore.admin.v1.Database, + protos.google.firestore.admin.v1.DeleteDatabaseMetadata + > + >; + /** + * Creates a new database by restoring from an existing backup. + * + * The new database must be in the same cloud region or multi-region location + * as the existing backup. This behaves similar to + * {@link protos.google.firestore.admin.v1.FirestoreAdmin.CreateDatabase|FirestoreAdmin.CreateDatabase} + * except instead of creating a new empty database, a new database is created + * with the database type, index configuration, and documents from an existing + * backup. + * + * The {@link protos.google.longrunning.Operation|long-running operation} can be used to + * track the progress of the restore, with the Operation's + * {@link protos.google.longrunning.Operation.metadata|metadata} field type being the + * {@link protos.google.firestore.admin.v1.RestoreDatabaseMetadata|RestoreDatabaseMetadata}. + * The {@link protos.google.longrunning.Operation.response|response} type is the + * {@link protos.google.firestore.admin.v1.Database|Database} if the restore was + * successful. The new database is not readable or writeable until the LRO has + * completed. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.parent + * Required. The project to restore the database in. Format is + * `projects/{project_id}`. + * @param {string} request.databaseId + * Required. The ID to use for the database, which will become the final + * component of the database's resource name. This database id must not be + * associated with an existing database. + * + * This value should be 4-63 characters. Valid characters are /{@link protos.0-9|a-z}-/ + * with first character a letter and the last a letter or a number. Must not + * be UUID-like /[0-9a-f]{8}(-[0-9a-f]{4}){3}-[0-9a-f]{12}/. + * + * "(default)" database id is also valid. + * @param {string} request.backup + * Required. Backup to restore from. Must be from the same project as the + * parent. + * + * Format is: `projects/{project_id}/locations/{location}/backups/{backup}` + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is an object representing + * a long running operation. Its `promise()` method returns a promise + * you can `await` for. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#long-running-operations | documentation } + * for more details and examples. + * @example include:samples/generated/v1/firestore_admin.restore_database.js + * region_tag:firestore_v1_generated_FirestoreAdmin_RestoreDatabase_async + */ + restoreDatabase( + request?: protos.google.firestore.admin.v1.IRestoreDatabaseRequest, + options?: CallOptions + ): Promise< + [ + LROperation< + protos.google.firestore.admin.v1.IDatabase, + protos.google.firestore.admin.v1.IRestoreDatabaseMetadata + >, + protos.google.longrunning.IOperation | undefined, + {} | undefined, + ] + >; + restoreDatabase( + request: protos.google.firestore.admin.v1.IRestoreDatabaseRequest, + options: CallOptions, + callback: Callback< + LROperation< + protos.google.firestore.admin.v1.IDatabase, + protos.google.firestore.admin.v1.IRestoreDatabaseMetadata + >, + protos.google.longrunning.IOperation | null | undefined, + {} | null | undefined + > + ): void; + restoreDatabase( + request: protos.google.firestore.admin.v1.IRestoreDatabaseRequest, + callback: Callback< + LROperation< + protos.google.firestore.admin.v1.IDatabase, + protos.google.firestore.admin.v1.IRestoreDatabaseMetadata + >, + protos.google.longrunning.IOperation | null | undefined, + {} | null | undefined + > + ): void; + /** + * Check the status of the long running operation returned by `restoreDatabase()`. + * @param {String} name + * The operation name that will be passed. + * @returns {Promise} - The promise which resolves to an object. + * The decoded operation object has result and metadata field to get information from. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#long-running-operations | documentation } + * for more details and examples. + * @example include:samples/generated/v1/firestore_admin.restore_database.js + * region_tag:firestore_v1_generated_FirestoreAdmin_RestoreDatabase_async + */ + checkRestoreDatabaseProgress( + name: string + ): Promise< + LROperation< + protos.google.firestore.admin.v1.Database, + protos.google.firestore.admin.v1.RestoreDatabaseMetadata + > + >; + /** + * Lists composite indexes. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.parent + * Required. A parent name of the form + * `projects/{project_id}/databases/{database_id}/collectionGroups/{collection_id}` + * @param {string} request.filter + * The filter to apply to list results. * @param {number} request.pageSize * The number of results to return. * @param {string} request.pageToken * A page token, returned from a previous call to - * {@link google.firestore.admin.v1.FirestoreAdmin.ListIndexes|FirestoreAdmin.ListIndexes}, that may be used to get the next - * page of results. + * {@link protos.google.firestore.admin.v1.FirestoreAdmin.ListIndexes|FirestoreAdmin.ListIndexes}, + * that may be used to get the next page of results. * @param {object} [options] * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. * @returns {Promise} - The promise which resolves to an array. - * The first element of the array is Array of [Index]{@link google.firestore.admin.v1.Index}. + * The first element of the array is Array of {@link protos.google.firestore.admin.v1.Index|Index}. * The client library will perform auto-pagination by default: it will call the API as many * times as needed and will merge results from all the pages into this array. * Note that it can affect your quota. * We recommend using `listIndexesAsync()` * method described below for async iteration which you can stop as needed. - * Please see the - * [documentation](https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#auto-pagination) + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#auto-pagination | documentation } * for more details and examples. */ listIndexes( @@ -879,18 +1666,17 @@ export declare class FirestoreAdminClient { * The number of results to return. * @param {string} request.pageToken * A page token, returned from a previous call to - * {@link google.firestore.admin.v1.FirestoreAdmin.ListIndexes|FirestoreAdmin.ListIndexes}, that may be used to get the next - * page of results. + * {@link protos.google.firestore.admin.v1.FirestoreAdmin.ListIndexes|FirestoreAdmin.ListIndexes}, + * that may be used to get the next page of results. * @param {object} [options] * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. * @returns {Stream} - * An object stream which emits an object representing [Index]{@link google.firestore.admin.v1.Index} on 'data' event. + * An object stream which emits an object representing {@link protos.google.firestore.admin.v1.Index|Index} on 'data' event. * The client library will perform auto-pagination by default: it will call the API as many * times as needed. Note that it can affect your quota. * We recommend using `listIndexesAsync()` * method described below for async iteration which you can stop as needed. - * Please see the - * [documentation](https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#auto-pagination) + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#auto-pagination | documentation } * for more details and examples. */ listIndexesStream( @@ -912,17 +1698,16 @@ export declare class FirestoreAdminClient { * The number of results to return. * @param {string} request.pageToken * A page token, returned from a previous call to - * {@link google.firestore.admin.v1.FirestoreAdmin.ListIndexes|FirestoreAdmin.ListIndexes}, that may be used to get the next - * page of results. + * {@link protos.google.firestore.admin.v1.FirestoreAdmin.ListIndexes|FirestoreAdmin.ListIndexes}, + * that may be used to get the next page of results. * @param {object} [options] * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. * @returns {Object} - * An iterable Object that allows [async iteration](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols). + * An iterable Object that allows {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols | async iteration }. * When you iterate the returned iterable, each element will be an object representing - * [Index]{@link google.firestore.admin.v1.Index}. The API will be called under the hood as needed, once per the page, + * {@link protos.google.firestore.admin.v1.Index|Index}. The API will be called under the hood as needed, once per the page, * so you can stop the iteration when you don't need more results. - * Please see the - * [documentation](https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#auto-pagination) + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#auto-pagination | documentation } * for more details and examples. * @example include:samples/generated/v1/firestore_admin.list_indexes.js * region_tag:firestore_v1_generated_FirestoreAdmin_ListIndexes_async @@ -934,10 +1719,13 @@ export declare class FirestoreAdminClient { /** * Lists the field configuration and metadata for this database. * - * Currently, {@link google.firestore.admin.v1.FirestoreAdmin.ListFields|FirestoreAdmin.ListFields} only supports listing fields - * that have been explicitly overridden. To issue this query, call - * {@link google.firestore.admin.v1.FirestoreAdmin.ListFields|FirestoreAdmin.ListFields} with the filter set to - * `indexConfig.usesAncestorConfig:false` . + * Currently, + * {@link protos.google.firestore.admin.v1.FirestoreAdmin.ListFields|FirestoreAdmin.ListFields} + * only supports listing fields that have been explicitly overridden. To issue + * this query, call + * {@link protos.google.firestore.admin.v1.FirestoreAdmin.ListFields|FirestoreAdmin.ListFields} + * with the filter set to `indexConfig.usesAncestorConfig:false` or + * `ttlConfig:*`. * * @param {Object} request * The request object that will be sent. @@ -946,27 +1734,28 @@ export declare class FirestoreAdminClient { * `projects/{project_id}/databases/{database_id}/collectionGroups/{collection_id}` * @param {string} request.filter * The filter to apply to list results. Currently, - * {@link google.firestore.admin.v1.FirestoreAdmin.ListFields|FirestoreAdmin.ListFields} only supports listing fields - * that have been explicitly overridden. To issue this query, call - * {@link google.firestore.admin.v1.FirestoreAdmin.ListFields|FirestoreAdmin.ListFields} with a filter that includes - * `indexConfig.usesAncestorConfig:false` . + * {@link protos.google.firestore.admin.v1.FirestoreAdmin.ListFields|FirestoreAdmin.ListFields} + * only supports listing fields that have been explicitly overridden. To issue + * this query, call + * {@link protos.google.firestore.admin.v1.FirestoreAdmin.ListFields|FirestoreAdmin.ListFields} + * with a filter that includes `indexConfig.usesAncestorConfig:false` or + * `ttlConfig:*`. * @param {number} request.pageSize * The number of results to return. * @param {string} request.pageToken * A page token, returned from a previous call to - * {@link google.firestore.admin.v1.FirestoreAdmin.ListFields|FirestoreAdmin.ListFields}, that may be used to get the next - * page of results. + * {@link protos.google.firestore.admin.v1.FirestoreAdmin.ListFields|FirestoreAdmin.ListFields}, + * that may be used to get the next page of results. * @param {object} [options] * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. * @returns {Promise} - The promise which resolves to an array. - * The first element of the array is Array of [Field]{@link google.firestore.admin.v1.Field}. + * The first element of the array is Array of {@link protos.google.firestore.admin.v1.Field|Field}. * The client library will perform auto-pagination by default: it will call the API as many * times as needed and will merge results from all the pages into this array. * Note that it can affect your quota. * We recommend using `listFieldsAsync()` * method described below for async iteration which you can stop as needed. - * Please see the - * [documentation](https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#auto-pagination) + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#auto-pagination | documentation } * for more details and examples. */ listFields( @@ -1005,26 +1794,27 @@ export declare class FirestoreAdminClient { * `projects/{project_id}/databases/{database_id}/collectionGroups/{collection_id}` * @param {string} request.filter * The filter to apply to list results. Currently, - * {@link google.firestore.admin.v1.FirestoreAdmin.ListFields|FirestoreAdmin.ListFields} only supports listing fields - * that have been explicitly overridden. To issue this query, call - * {@link google.firestore.admin.v1.FirestoreAdmin.ListFields|FirestoreAdmin.ListFields} with a filter that includes - * `indexConfig.usesAncestorConfig:false` . + * {@link protos.google.firestore.admin.v1.FirestoreAdmin.ListFields|FirestoreAdmin.ListFields} + * only supports listing fields that have been explicitly overridden. To issue + * this query, call + * {@link protos.google.firestore.admin.v1.FirestoreAdmin.ListFields|FirestoreAdmin.ListFields} + * with a filter that includes `indexConfig.usesAncestorConfig:false` or + * `ttlConfig:*`. * @param {number} request.pageSize * The number of results to return. * @param {string} request.pageToken * A page token, returned from a previous call to - * {@link google.firestore.admin.v1.FirestoreAdmin.ListFields|FirestoreAdmin.ListFields}, that may be used to get the next - * page of results. + * {@link protos.google.firestore.admin.v1.FirestoreAdmin.ListFields|FirestoreAdmin.ListFields}, + * that may be used to get the next page of results. * @param {object} [options] * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. * @returns {Stream} - * An object stream which emits an object representing [Field]{@link google.firestore.admin.v1.Field} on 'data' event. + * An object stream which emits an object representing {@link protos.google.firestore.admin.v1.Field|Field} on 'data' event. * The client library will perform auto-pagination by default: it will call the API as many * times as needed. Note that it can affect your quota. * We recommend using `listFieldsAsync()` * method described below for async iteration which you can stop as needed. - * Please see the - * [documentation](https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#auto-pagination) + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#auto-pagination | documentation } * for more details and examples. */ listFieldsStream( @@ -1042,25 +1832,26 @@ export declare class FirestoreAdminClient { * `projects/{project_id}/databases/{database_id}/collectionGroups/{collection_id}` * @param {string} request.filter * The filter to apply to list results. Currently, - * {@link google.firestore.admin.v1.FirestoreAdmin.ListFields|FirestoreAdmin.ListFields} only supports listing fields - * that have been explicitly overridden. To issue this query, call - * {@link google.firestore.admin.v1.FirestoreAdmin.ListFields|FirestoreAdmin.ListFields} with a filter that includes - * `indexConfig.usesAncestorConfig:false` . + * {@link protos.google.firestore.admin.v1.FirestoreAdmin.ListFields|FirestoreAdmin.ListFields} + * only supports listing fields that have been explicitly overridden. To issue + * this query, call + * {@link protos.google.firestore.admin.v1.FirestoreAdmin.ListFields|FirestoreAdmin.ListFields} + * with a filter that includes `indexConfig.usesAncestorConfig:false` or + * `ttlConfig:*`. * @param {number} request.pageSize * The number of results to return. * @param {string} request.pageToken * A page token, returned from a previous call to - * {@link google.firestore.admin.v1.FirestoreAdmin.ListFields|FirestoreAdmin.ListFields}, that may be used to get the next - * page of results. + * {@link protos.google.firestore.admin.v1.FirestoreAdmin.ListFields|FirestoreAdmin.ListFields}, + * that may be used to get the next page of results. * @param {object} [options] * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. * @returns {Object} - * An iterable Object that allows [async iteration](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols). + * An iterable Object that allows {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols | async iteration }. * When you iterate the returned iterable, each element will be an object representing - * [Field]{@link google.firestore.admin.v1.Field}. The API will be called under the hood as needed, once per the page, + * {@link protos.google.firestore.admin.v1.Field|Field}. The API will be called under the hood as needed, once per the page, * so you can stop the iteration when you don't need more results. - * Please see the - * [documentation](https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#auto-pagination) + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#auto-pagination | documentation } * for more details and examples. * @example include:samples/generated/v1/firestore_admin.list_fields.js * region_tag:firestore_v1_generated_FirestoreAdmin_ListFields_async @@ -1069,6 +1860,319 @@ export declare class FirestoreAdminClient { request?: protos.google.firestore.admin.v1.IListFieldsRequest, options?: CallOptions ): AsyncIterable; + /** + * Gets information about a location. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.name + * Resource name for the location. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html | CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is an object representing {@link google.cloud.location.Location | Location}. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } + * for more details and examples. + * @example + * ``` + * const [response] = await client.getLocation(request); + * ``` + */ + getLocation( + request: LocationProtos.google.cloud.location.IGetLocationRequest, + options?: + | gax.CallOptions + | Callback< + LocationProtos.google.cloud.location.ILocation, + | LocationProtos.google.cloud.location.IGetLocationRequest + | null + | undefined, + {} | null | undefined + >, + callback?: Callback< + LocationProtos.google.cloud.location.ILocation, + | LocationProtos.google.cloud.location.IGetLocationRequest + | null + | undefined, + {} | null | undefined + > + ): Promise; + /** + * Lists information about the supported locations for this service. Returns an iterable object. + * + * `for`-`await`-`of` syntax is used with the iterable to get response elements on-demand. + * @param {Object} request + * The request object that will be sent. + * @param {string} request.name + * The resource that owns the locations collection, if applicable. + * @param {string} request.filter + * The standard list filter. + * @param {number} request.pageSize + * The standard list page size. + * @param {string} request.pageToken + * The standard list page token. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Object} + * An iterable Object that allows {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols | async iteration }. + * When you iterate the returned iterable, each element will be an object representing + * {@link google.cloud.location.Location | Location}. The API will be called under the hood as needed, once per the page, + * so you can stop the iteration when you don't need more results. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#auto-pagination | documentation } + * for more details and examples. + * @example + * ``` + * const iterable = client.listLocationsAsync(request); + * for await (const response of iterable) { + * // process response + * } + * ``` + */ + listLocationsAsync( + request: LocationProtos.google.cloud.location.IListLocationsRequest, + options?: CallOptions + ): AsyncIterable; + /** + * Gets the latest state of a long-running operation. Clients can use this + * method to poll the operation result at intervals as recommended by the API + * service. + * + * @param {Object} request - The request object that will be sent. + * @param {string} request.name - The name of the operation resource. + * @param {Object=} options + * Optional parameters. You can override the default settings for this call, + * e.g, timeout, retries, paginations, etc. See {@link + * https://googleapis.github.io/gax-nodejs/global.html#CallOptions | gax.CallOptions} + * for the details. + * @param {function(?Error, ?Object)=} callback + * The function which will be called with the result of the API call. + * + * The second parameter to the callback is an object representing + * {@link google.longrunning.Operation | google.longrunning.Operation}. + * @return {Promise} - The promise which resolves to an array. + * The first element of the array is an object representing + * {@link google.longrunning.Operation | google.longrunning.Operation}. + * The promise has a method named "cancel" which cancels the ongoing API call. + * + * @example + * ``` + * const client = longrunning.operationsClient(); + * const name = ''; + * const [response] = await client.getOperation({name}); + * // doThingsWith(response) + * ``` + */ + getOperation( + request: protos.google.longrunning.GetOperationRequest, + options?: + | gax.CallOptions + | Callback< + protos.google.longrunning.Operation, + protos.google.longrunning.GetOperationRequest, + {} | null | undefined + >, + callback?: Callback< + protos.google.longrunning.Operation, + protos.google.longrunning.GetOperationRequest, + {} | null | undefined + > + ): Promise<[protos.google.longrunning.Operation]>; + /** + * Lists operations that match the specified filter in the request. If the + * server doesn't support this method, it returns `UNIMPLEMENTED`. Returns an iterable object. + * + * For-await-of syntax is used with the iterable to recursively get response element on-demand. + * + * @param {Object} request - The request object that will be sent. + * @param {string} request.name - The name of the operation collection. + * @param {string} request.filter - The standard list filter. + * @param {number=} request.pageSize - + * The maximum number of resources contained in the underlying API + * response. If page streaming is performed per-resource, this + * parameter does not affect the return value. If page streaming is + * performed per-page, this determines the maximum number of + * resources in a page. + * @param {Object=} options + * Optional parameters. You can override the default settings for this call, + * e.g, timeout, retries, paginations, etc. See {@link + * https://googleapis.github.io/gax-nodejs/global.html#CallOptions | gax.CallOptions} for the + * details. + * @returns {Object} + * An iterable Object that conforms to {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols | iteration protocols}. + * + * @example + * ``` + * const client = longrunning.operationsClient(); + * for await (const response of client.listOperationsAsync(request)); + * // doThingsWith(response) + * ``` + */ + listOperationsAsync( + request: protos.google.longrunning.ListOperationsRequest, + options?: gax.CallOptions + ): AsyncIterable; + /** + * Starts asynchronous cancellation on a long-running operation. The server + * makes a best effort to cancel the operation, but success is not + * guaranteed. If the server doesn't support this method, it returns + * `google.rpc.Code.UNIMPLEMENTED`. Clients can use + * {@link Operations.GetOperation} or + * other methods to check whether the cancellation succeeded or whether the + * operation completed despite cancellation. On successful cancellation, + * the operation is not deleted; instead, it becomes an operation with + * an {@link Operation.error} value with a {@link google.rpc.Status.code} of + * 1, corresponding to `Code.CANCELLED`. + * + * @param {Object} request - The request object that will be sent. + * @param {string} request.name - The name of the operation resource to be cancelled. + * @param {Object=} options + * Optional parameters. You can override the default settings for this call, + * e.g, timeout, retries, paginations, etc. See {@link + * https://googleapis.github.io/gax-nodejs/global.html#CallOptions | gax.CallOptions} for the + * details. + * @param {function(?Error)=} callback + * The function which will be called with the result of the API call. + * @return {Promise} - The promise which resolves when API call finishes. + * The promise has a method named "cancel" which cancels the ongoing API + * call. + * + * @example + * ``` + * const client = longrunning.operationsClient(); + * await client.cancelOperation({name: ''}); + * ``` + */ + cancelOperation( + request: protos.google.longrunning.CancelOperationRequest, + options?: + | gax.CallOptions + | Callback< + protos.google.protobuf.Empty, + protos.google.longrunning.CancelOperationRequest, + {} | undefined | null + >, + callback?: Callback< + protos.google.longrunning.CancelOperationRequest, + protos.google.protobuf.Empty, + {} | undefined | null + > + ): Promise; + /** + * Deletes a long-running operation. This method indicates that the client is + * no longer interested in the operation result. It does not cancel the + * operation. If the server doesn't support this method, it returns + * `google.rpc.Code.UNIMPLEMENTED`. + * + * @param {Object} request - The request object that will be sent. + * @param {string} request.name - The name of the operation resource to be deleted. + * @param {Object=} options + * Optional parameters. You can override the default settings for this call, + * e.g, timeout, retries, paginations, etc. See {@link + * https://googleapis.github.io/gax-nodejs/global.html#CallOptions | gax.CallOptions} + * for the details. + * @param {function(?Error)=} callback + * The function which will be called with the result of the API call. + * @return {Promise} - The promise which resolves when API call finishes. + * The promise has a method named "cancel" which cancels the ongoing API + * call. + * + * @example + * ``` + * const client = longrunning.operationsClient(); + * await client.deleteOperation({name: ''}); + * ``` + */ + deleteOperation( + request: protos.google.longrunning.DeleteOperationRequest, + options?: + | gax.CallOptions + | Callback< + protos.google.protobuf.Empty, + protos.google.longrunning.DeleteOperationRequest, + {} | null | undefined + >, + callback?: Callback< + protos.google.protobuf.Empty, + protos.google.longrunning.DeleteOperationRequest, + {} | null | undefined + > + ): Promise; + /** + * Return a fully-qualified backup resource name string. + * + * @param {string} project + * @param {string} location + * @param {string} backup + * @returns {string} Resource name string. + */ + backupPath(project: string, location: string, backup: string): string; + /** + * Parse the project from Backup resource. + * + * @param {string} backupName + * A fully-qualified path representing Backup resource. + * @returns {string} A string representing the project. + */ + matchProjectFromBackupName(backupName: string): string | number; + /** + * Parse the location from Backup resource. + * + * @param {string} backupName + * A fully-qualified path representing Backup resource. + * @returns {string} A string representing the location. + */ + matchLocationFromBackupName(backupName: string): string | number; + /** + * Parse the backup from Backup resource. + * + * @param {string} backupName + * A fully-qualified path representing Backup resource. + * @returns {string} A string representing the backup. + */ + matchBackupFromBackupName(backupName: string): string | number; + /** + * Return a fully-qualified backupSchedule resource name string. + * + * @param {string} project + * @param {string} database + * @param {string} backup_schedule + * @returns {string} Resource name string. + */ + backupSchedulePath( + project: string, + database: string, + backupSchedule: string + ): string; + /** + * Parse the project from BackupSchedule resource. + * + * @param {string} backupScheduleName + * A fully-qualified path representing BackupSchedule resource. + * @returns {string} A string representing the project. + */ + matchProjectFromBackupScheduleName( + backupScheduleName: string + ): string | number; + /** + * Parse the database from BackupSchedule resource. + * + * @param {string} backupScheduleName + * A fully-qualified path representing BackupSchedule resource. + * @returns {string} A string representing the database. + */ + matchDatabaseFromBackupScheduleName( + backupScheduleName: string + ): string | number; + /** + * Parse the backup_schedule from BackupSchedule resource. + * + * @param {string} backupScheduleName + * A fully-qualified path representing BackupSchedule resource. + * @returns {string} A string representing the backup_schedule. + */ + matchBackupScheduleFromBackupScheduleName( + backupScheduleName: string + ): string | number; /** * Return a fully-qualified collectionGroup resource name string. * @@ -1230,6 +2334,30 @@ export declare class FirestoreAdminClient { * @returns {string} A string representing the index. */ matchIndexFromIndexName(indexName: string): string | number; + /** + * Return a fully-qualified location resource name string. + * + * @param {string} project + * @param {string} location + * @returns {string} Resource name string. + */ + locationPath(project: string, location: string): string; + /** + * Parse the project from Location resource. + * + * @param {string} locationName + * A fully-qualified path representing Location resource. + * @returns {string} A string representing the project. + */ + matchProjectFromLocationName(locationName: string): string | number; + /** + * Parse the location from Location resource. + * + * @param {string} locationName + * A fully-qualified path representing Location resource. + * @returns {string} A string representing the location. + */ + matchLocationFromLocationName(locationName: string): string | number; /** * Return a fully-qualified project resource name string. * diff --git a/types/v1/firestore_client.d.ts b/types/v1/firestore_client.d.ts index 2b8cff2f0..dba3ce906 100644 --- a/types/v1/firestore_client.d.ts +++ b/types/v1/firestore_client.d.ts @@ -1,5 +1,5 @@ /*! - * Copyright 2022 Google LLC + * 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. @@ -14,14 +14,15 @@ * limitations under the License. */ -/// -import * as gax from 'google-gax'; -import { +import type * as gax from 'google-gax'; +import type { Callback, CallOptions, Descriptors, ClientOptions, PaginationCallback, + LocationsClient, + LocationProtos, } from 'google-gax'; import {Transform} from 'stream'; import * as protos from '../protos/firestore_v1_proto_api'; @@ -32,8 +33,8 @@ import * as protos from '../protos/firestore_v1_proto_api'; * document database that simplifies storing, syncing, and querying data for * your mobile, web, and IoT apps at global scale. Its client libraries provide * live synchronization and offline support, while its security features and - * integrations with Firebase and Google Cloud Platform (GCP) accelerate - * building truly serverless apps. + * integrations with Firebase and Google Cloud Platform accelerate building + * truly serverless apps. * @class * @memberof v1 */ @@ -45,12 +46,15 @@ export declare class FirestoreClient { private _gaxGrpc; private _protos; private _defaults; + private _universeDomain; + private _servicePath; auth: gax.GoogleAuth; descriptors: Descriptors; warn: (code: string, message: string, warnType?: string) => void; innerApiCalls: { [name: string]: Function; }; + locationsClient: LocationsClient; firestoreStub?: Promise<{ [name: string]: Function; }>; @@ -59,7 +63,7 @@ export declare class FirestoreClient { * * @param {object} [options] - The configuration object. * The options accepted by the constructor are described in detail - * in [this document](https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#creating-the-client-instance). + * in [this document](https://github.com/googleapis/gax-nodejs/blob/main/client-libraries.md#creating-the-client-instance). * The common options are: * @param {object} [options.credentials] - Credentials object. * @param {string} [options.credentials.client_email] @@ -82,13 +86,21 @@ export declare class FirestoreClient { * API remote host. * @param {gax.ClientConfig} [options.clientConfig] - Client configuration override. * Follows the structure of {@link gapicConfig}. - * @param {boolean} [options.fallback] - Use HTTP fallback mode. - * In fallback mode, a special browser-compatible transport implementation is used - * instead of gRPC transport. In browser context (if the `window` object is defined) - * the fallback mode is enabled automatically; set `options.fallback` to `false` - * if you need to override this behavior. + * @param {boolean} [options.fallback] - Use HTTP/1.1 REST mode. + * For more information, please check the + * {@link https://github.com/googleapis/gax-nodejs/blob/main/client-libraries.md#http11-rest-api-mode documentation}. + * @param {gax} [gaxInstance]: loaded instance of `google-gax`. Useful if you + * need to avoid loading the default gRPC version and want to use the fallback + * HTTP implementation. Load only fallback version and pass it to the constructor: + * ``` + * const gax = require('google-gax/build/src/fallback'); // avoids loading google-gax with gRPC + * const client = new FirestoreClient({fallback: true}, gax); + * ``` */ - constructor(opts?: ClientOptions); + constructor( + opts?: ClientOptions, + gaxInstance?: typeof gax | typeof gax.fallback + ); /** * Initialize the client. * Performs asynchronous operations (such as authentication) and prepares the client. @@ -105,15 +117,22 @@ export declare class FirestoreClient { }>; /** * The DNS address for this API service. + * @deprecated Use the apiEndpoint method of the client instance. * @returns {string} The DNS address for this service. */ static get servicePath(): string; /** - * The DNS address for this API service - same as servicePath(), - * exists for compatibility reasons. + * The DNS address for this API service - same as servicePath. + * @deprecated Use the apiEndpoint method of the client instance. * @returns {string} The DNS address for this service. */ static get apiEndpoint(): string; + /** + * The DNS address for this API service. + * @returns {string} The DNS address for this service. + */ + get apiEndpoint(): string; + get universeDomain(): string; /** * The port for this API service. * @returns {number} The default port for this service. @@ -144,13 +163,15 @@ export declare class FirestoreClient { * Reads the document in a transaction. * @param {google.protobuf.Timestamp} request.readTime * Reads the version of the document at the given time. - * This may not be older than 270 seconds. + * + * This must be a microsecond precision timestamp within the past one hour, + * or if Point-in-Time Recovery is enabled, can additionally be a whole + * minute timestamp within the past 7 days. * @param {object} [options] * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. * @returns {Promise} - The promise which resolves to an array. - * The first element of the array is an object representing [Document]{@link google.firestore.v1.Document}. - * Please see the - * [documentation](https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods) + * The first element of the array is an object representing {@link protos.google.firestore.v1.Document|Document}. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } * for more details and examples. * @example include:samples/generated/v1/firestore.get_document.js * region_tag:firestore_v1_generated_Firestore_GetDocument_async @@ -209,9 +230,8 @@ export declare class FirestoreClient { * @param {object} [options] * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. * @returns {Promise} - The promise which resolves to an array. - * The first element of the array is an object representing [Document]{@link google.firestore.v1.Document}. - * Please see the - * [documentation](https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods) + * The first element of the array is an object representing {@link protos.google.firestore.v1.Document|Document}. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } * for more details and examples. * @example include:samples/generated/v1/firestore.update_document.js * region_tag:firestore_v1_generated_Firestore_UpdateDocument_async @@ -257,9 +277,8 @@ export declare class FirestoreClient { * @param {object} [options] * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. * @returns {Promise} - The promise which resolves to an array. - * The first element of the array is an object representing [Empty]{@link google.protobuf.Empty}. - * Please see the - * [documentation](https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods) + * The first element of the array is an object representing {@link protos.google.protobuf.Empty|Empty}. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } * for more details and examples. * @example include:samples/generated/v1/firestore.delete_document.js * region_tag:firestore_v1_generated_Firestore_DeleteDocument_async @@ -305,9 +324,8 @@ export declare class FirestoreClient { * @param {object} [options] * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. * @returns {Promise} - The promise which resolves to an array. - * The first element of the array is an object representing [BeginTransactionResponse]{@link google.firestore.v1.BeginTransactionResponse}. - * Please see the - * [documentation](https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods) + * The first element of the array is an object representing {@link protos.google.firestore.v1.BeginTransactionResponse|BeginTransactionResponse}. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } * for more details and examples. * @example include:samples/generated/v1/firestore.begin_transaction.js * region_tag:firestore_v1_generated_Firestore_BeginTransaction_async @@ -356,9 +374,8 @@ export declare class FirestoreClient { * @param {object} [options] * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. * @returns {Promise} - The promise which resolves to an array. - * The first element of the array is an object representing [CommitResponse]{@link google.firestore.v1.CommitResponse}. - * Please see the - * [documentation](https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods) + * The first element of the array is an object representing {@link protos.google.firestore.v1.CommitResponse|CommitResponse}. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } * for more details and examples. * @example include:samples/generated/v1/firestore.commit.js * region_tag:firestore_v1_generated_Firestore_Commit_async @@ -403,9 +420,8 @@ export declare class FirestoreClient { * @param {object} [options] * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. * @returns {Promise} - The promise which resolves to an array. - * The first element of the array is an object representing [Empty]{@link google.protobuf.Empty}. - * Please see the - * [documentation](https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods) + * The first element of the array is an object representing {@link protos.google.protobuf.Empty|Empty}. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } * for more details and examples. * @example include:samples/generated/v1/firestore.rollback.js * region_tag:firestore_v1_generated_Firestore_Rollback_async @@ -443,10 +459,11 @@ export declare class FirestoreClient { * The BatchWrite method does not apply the write operations atomically * and can apply them out of order. Method does not allow more than one write * per document. Each write succeeds or fails independently. See the - * {@link google.firestore.v1.BatchWriteResponse|BatchWriteResponse} for the success status of each write. + * {@link protos.google.firestore.v1.BatchWriteResponse|BatchWriteResponse} for the + * success status of each write. * * If you require an atomically applied set of writes, use - * {@link google.firestore.v1.Firestore.Commit|Commit} instead. + * {@link protos.google.firestore.v1.Firestore.Commit|Commit} instead. * * @param {Object} request * The request object that will be sent. @@ -464,9 +481,8 @@ export declare class FirestoreClient { * @param {object} [options] * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. * @returns {Promise} - The promise which resolves to an array. - * The first element of the array is an object representing [BatchWriteResponse]{@link google.firestore.v1.BatchWriteResponse}. - * Please see the - * [documentation](https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods) + * The first element of the array is an object representing {@link protos.google.firestore.v1.BatchWriteResponse|BatchWriteResponse}. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } * for more details and examples. * @example include:samples/generated/v1/firestore.batch_write.js * region_tag:firestore_v1_generated_Firestore_BatchWrite_async @@ -508,7 +524,8 @@ export declare class FirestoreClient { * `projects/{project_id}/databases/{database_id}/documents` or * `projects/{project_id}/databases/{database_id}/documents/chatrooms/{chatroom_id}` * @param {string} request.collectionId - * Required. The collection ID, relative to `parent`, to list. For example: `chatrooms`. + * Required. The collection ID, relative to `parent`, to list. For example: + * `chatrooms`. * @param {string} request.documentId * The client-assigned document ID to use for this document. * @@ -523,9 +540,8 @@ export declare class FirestoreClient { * @param {object} [options] * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. * @returns {Promise} - The promise which resolves to an array. - * The first element of the array is an object representing [Document]{@link google.firestore.v1.Document}. - * Please see the - * [documentation](https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods) + * The first element of the array is an object representing {@link protos.google.firestore.v1.Document|Document}. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } * for more details and examples. * @example include:samples/generated/v1/firestore.create_document.js * region_tag:firestore_v1_generated_Firestore_CreateDocument_async @@ -587,13 +603,15 @@ export declare class FirestoreClient { * stream. * @param {google.protobuf.Timestamp} request.readTime * Reads documents as they were at the given time. - * This may not be older than 270 seconds. + * + * This must be a microsecond precision timestamp within the past one hour, + * or if Point-in-Time Recovery is enabled, can additionally be a whole + * minute timestamp within the past 7 days. * @param {object} [options] * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. * @returns {Stream} - * An object stream which emits [BatchGetDocumentsResponse]{@link google.firestore.v1.BatchGetDocumentsResponse} on 'data' event. - * Please see the - * [documentation](https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#server-streaming) + * An object stream which emits {@link protos.google.firestore.v1.BatchGetDocumentsResponse|BatchGetDocumentsResponse} on 'data' event. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#server-streaming | documentation } * for more details and examples. * @example include:samples/generated/v1/firestore.batch_get_documents.js * region_tag:firestore_v1_generated_Firestore_BatchGetDocuments_async @@ -617,7 +635,9 @@ export declare class FirestoreClient { * @param {google.firestore.v1.StructuredQuery} request.structuredQuery * A structured query. * @param {Buffer} request.transaction - * Reads documents in a transaction. + * Run the query within an already active transaction. + * + * The value here is the opaque transaction ID to execute the query in. * @param {google.firestore.v1.TransactionOptions} request.newTransaction * Starts a new transaction and reads the documents. * Defaults to a read-only transaction. @@ -625,13 +645,18 @@ export declare class FirestoreClient { * stream. * @param {google.protobuf.Timestamp} request.readTime * Reads documents as they were at the given time. - * This may not be older than 270 seconds. + * + * This must be a microsecond precision timestamp within the past one hour, + * or if Point-in-Time Recovery is enabled, can additionally be a whole + * minute timestamp within the past 7 days. + * @param {google.firestore.v1.ExplainOptions} [request.explainOptions] + * Optional. Explain options for the query. If set, additional query + * statistics will be returned. If not, only query results will be returned. * @param {object} [options] * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. * @returns {Stream} - * An object stream which emits [RunQueryResponse]{@link google.firestore.v1.RunQueryResponse} on 'data' event. - * Please see the - * [documentation](https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#server-streaming) + * An object stream which emits {@link protos.google.firestore.v1.RunQueryResponse|RunQueryResponse} on 'data' event. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#server-streaming | documentation } * for more details and examples. * @example include:samples/generated/v1/firestore.run_query.js * region_tag:firestore_v1_generated_Firestore_RunQuery_async @@ -641,32 +666,89 @@ export declare class FirestoreClient { options?: CallOptions ): gax.CancellableStream; /** - * Streams batches of document updates and deletes, in order. + * Runs an aggregation query. + * + * Rather than producing {@link protos.google.firestore.v1.Document|Document} results like + * {@link protos.google.firestore.v1.Firestore.RunQuery|Firestore.RunQuery}, this API + * allows running an aggregation to produce a series of + * {@link protos.google.firestore.v1.AggregationResult|AggregationResult} server-side. + * + * High-Level Example: + * + * ``` + * -- Return the number of documents in table given a filter. + * SELECT COUNT(*) FROM ( SELECT * FROM k where a = true ); + * ``` + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.parent + * Required. The parent resource name. In the format: + * `projects/{project_id}/databases/{database_id}/documents` or + * `projects/{project_id}/databases/{database_id}/documents/{document_path}`. + * For example: + * `projects/my-project/databases/my-database/documents` or + * `projects/my-project/databases/my-database/documents/chatrooms/my-chatroom` + * @param {google.firestore.v1.StructuredAggregationQuery} request.structuredAggregationQuery + * An aggregation query. + * @param {Buffer} request.transaction + * Run the aggregation within an already active transaction. + * + * The value here is the opaque transaction ID to execute the query in. + * @param {google.firestore.v1.TransactionOptions} request.newTransaction + * Starts a new transaction as part of the query, defaulting to read-only. + * + * The new transaction ID will be returned as the first response in the + * stream. + * @param {google.protobuf.Timestamp} request.readTime + * Executes the query at the given timestamp. + * + * This must be a microsecond precision timestamp within the past one hour, + * or if Point-in-Time Recovery is enabled, can additionally be a whole + * minute timestamp within the past 7 days. + * @param {google.firestore.v1.ExplainOptions} [request.explainOptions] + * Optional. Explain options for the query. If set, additional query + * statistics will be returned. If not, only query results will be returned. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Stream} + * An object stream which emits {@link protos.google.firestore.v1.RunAggregationQueryResponse|RunAggregationQueryResponse} on 'data' event. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#server-streaming | documentation } + * for more details and examples. + * @example include:samples/generated/v1/firestore.run_aggregation_query.js + * region_tag:firestore_v1_generated_Firestore_RunAggregationQuery_async + */ + runAggregationQuery( + request?: protos.google.firestore.v1.IRunAggregationQueryRequest, + options?: CallOptions + ): gax.CancellableStream; + /** + * Streams batches of document updates and deletes, in order. This method is + * only available via gRPC or WebChannel (not REST). * * @param {object} [options] * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. * @returns {Stream} * An object stream which is both readable and writable. It accepts objects - * representing [WriteRequest]{@link google.firestore.v1.WriteRequest} for write() method, and - * will emit objects representing [WriteResponse]{@link google.firestore.v1.WriteResponse} on 'data' event asynchronously. - * Please see the - * [documentation](https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#bi-directional-streaming) + * representing {@link protos.google.firestore.v1.WriteRequest|WriteRequest} for write() method, and + * will emit objects representing {@link protos.google.firestore.v1.WriteResponse|WriteResponse} on 'data' event asynchronously. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#bi-directional-streaming | documentation } * for more details and examples. * @example include:samples/generated/v1/firestore.write.js * region_tag:firestore_v1_generated_Firestore_Write_async */ write(options?: CallOptions): gax.CancellableStream; /** - * Listens to changes. + * Listens to changes. This method is only available via gRPC or WebChannel + * (not REST). * * @param {object} [options] * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. * @returns {Stream} * An object stream which is both readable and writable. It accepts objects - * representing [ListenRequest]{@link google.firestore.v1.ListenRequest} for write() method, and - * will emit objects representing [ListenResponse]{@link google.firestore.v1.ListenResponse} on 'data' event asynchronously. - * Please see the - * [documentation](https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#bi-directional-streaming) + * representing {@link protos.google.firestore.v1.ListenRequest|ListenRequest} for write() method, and + * will emit objects representing {@link protos.google.firestore.v1.ListenResponse|ListenResponse} on 'data' event asynchronously. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#bi-directional-streaming | documentation } * for more details and examples. * @example include:samples/generated/v1/firestore.listen.js * region_tag:firestore_v1_generated_Firestore_Listen_async @@ -681,47 +763,68 @@ export declare class FirestoreClient { * Required. The parent resource name. In the format: * `projects/{project_id}/databases/{database_id}/documents` or * `projects/{project_id}/databases/{database_id}/documents/{document_path}`. + * * For example: * `projects/my-project/databases/my-database/documents` or * `projects/my-project/databases/my-database/documents/chatrooms/my-chatroom` - * @param {string} request.collectionId - * Required. The collection ID, relative to `parent`, to list. For example: `chatrooms` - * or `messages`. - * @param {number} request.pageSize - * The maximum number of documents to return. - * @param {string} request.pageToken - * The `next_page_token` value returned from a previous List request, if any. - * @param {string} request.orderBy - * The order to sort results by. For example: `priority desc, name`. - * @param {google.firestore.v1.DocumentMask} request.mask - * The fields to return. If not set, returns all fields. + * @param {string} [request.collectionId] + * Optional. The collection ID, relative to `parent`, to list. + * + * For example: `chatrooms` or `messages`. + * + * This is optional, and when not provided, Firestore will list documents + * from all collections under the provided `parent`. + * @param {number} [request.pageSize] + * Optional. The maximum number of documents to return in a single response. + * + * Firestore may return fewer than this value. + * @param {string} [request.pageToken] + * Optional. A page token, received from a previous `ListDocuments` response. + * + * Provide this to retrieve the subsequent page. When paginating, all other + * parameters (with the exception of `page_size`) must match the values set + * in the request that generated the page token. + * @param {string} [request.orderBy] + * Optional. The optional ordering of the documents to return. + * + * For example: `priority desc, __name__ desc`. + * + * This mirrors the {@link protos.google.firestore.v1.StructuredQuery.order_by|`ORDER BY`} + * used in Firestore queries but in a string representation. When absent, + * documents are ordered based on `__name__ ASC`. + * @param {google.firestore.v1.DocumentMask} [request.mask] + * Optional. The fields to return. If not set, returns all fields. * * If a document has a field that is not present in this mask, that field * will not be returned in the response. * @param {Buffer} request.transaction - * Reads documents in a transaction. + * Perform the read as part of an already active transaction. * @param {google.protobuf.Timestamp} request.readTime - * Reads documents as they were at the given time. - * This may not be older than 270 seconds. + * Perform the read at the provided time. + * + * This must be a microsecond precision timestamp within the past one hour, + * or if Point-in-Time Recovery is enabled, can additionally be a whole + * minute timestamp within the past 7 days. * @param {boolean} request.showMissing - * If the list should show missing documents. A missing document is a - * document that does not exist but has sub-documents. These documents will - * be returned with a key but will not have fields, {@link google.firestore.v1.Document.create_time|Document.create_time}, - * or {@link google.firestore.v1.Document.update_time|Document.update_time} set. + * If the list should show missing documents. + * + * A document is missing if it does not exist, but there are sub-documents + * nested underneath it. When true, such missing documents will be returned + * with a key but will not have fields, + * {@link protos.google.firestore.v1.Document.create_time|`create_time`}, or + * {@link protos.google.firestore.v1.Document.update_time|`update_time`} set. * - * Requests with `show_missing` may not specify `where` or - * `order_by`. + * Requests with `show_missing` may not specify `where` or `order_by`. * @param {object} [options] * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. * @returns {Promise} - The promise which resolves to an array. - * The first element of the array is Array of [Document]{@link google.firestore.v1.Document}. + * The first element of the array is Array of {@link protos.google.firestore.v1.Document|Document}. * The client library will perform auto-pagination by default: it will call the API as many * times as needed and will merge results from all the pages into this array. * Note that it can affect your quota. * We recommend using `listDocumentsAsync()` * method described below for async iteration which you can stop as needed. - * Please see the - * [documentation](https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#auto-pagination) + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#auto-pagination | documentation } * for more details and examples. */ listDocuments( @@ -759,46 +862,67 @@ export declare class FirestoreClient { * Required. The parent resource name. In the format: * `projects/{project_id}/databases/{database_id}/documents` or * `projects/{project_id}/databases/{database_id}/documents/{document_path}`. + * * For example: * `projects/my-project/databases/my-database/documents` or * `projects/my-project/databases/my-database/documents/chatrooms/my-chatroom` - * @param {string} request.collectionId - * Required. The collection ID, relative to `parent`, to list. For example: `chatrooms` - * or `messages`. - * @param {number} request.pageSize - * The maximum number of documents to return. - * @param {string} request.pageToken - * The `next_page_token` value returned from a previous List request, if any. - * @param {string} request.orderBy - * The order to sort results by. For example: `priority desc, name`. - * @param {google.firestore.v1.DocumentMask} request.mask - * The fields to return. If not set, returns all fields. + * @param {string} [request.collectionId] + * Optional. The collection ID, relative to `parent`, to list. + * + * For example: `chatrooms` or `messages`. + * + * This is optional, and when not provided, Firestore will list documents + * from all collections under the provided `parent`. + * @param {number} [request.pageSize] + * Optional. The maximum number of documents to return in a single response. + * + * Firestore may return fewer than this value. + * @param {string} [request.pageToken] + * Optional. A page token, received from a previous `ListDocuments` response. + * + * Provide this to retrieve the subsequent page. When paginating, all other + * parameters (with the exception of `page_size`) must match the values set + * in the request that generated the page token. + * @param {string} [request.orderBy] + * Optional. The optional ordering of the documents to return. + * + * For example: `priority desc, __name__ desc`. + * + * This mirrors the {@link protos.google.firestore.v1.StructuredQuery.order_by|`ORDER BY`} + * used in Firestore queries but in a string representation. When absent, + * documents are ordered based on `__name__ ASC`. + * @param {google.firestore.v1.DocumentMask} [request.mask] + * Optional. The fields to return. If not set, returns all fields. * * If a document has a field that is not present in this mask, that field * will not be returned in the response. * @param {Buffer} request.transaction - * Reads documents in a transaction. + * Perform the read as part of an already active transaction. * @param {google.protobuf.Timestamp} request.readTime - * Reads documents as they were at the given time. - * This may not be older than 270 seconds. + * Perform the read at the provided time. + * + * This must be a microsecond precision timestamp within the past one hour, + * or if Point-in-Time Recovery is enabled, can additionally be a whole + * minute timestamp within the past 7 days. * @param {boolean} request.showMissing - * If the list should show missing documents. A missing document is a - * document that does not exist but has sub-documents. These documents will - * be returned with a key but will not have fields, {@link google.firestore.v1.Document.create_time|Document.create_time}, - * or {@link google.firestore.v1.Document.update_time|Document.update_time} set. + * If the list should show missing documents. * - * Requests with `show_missing` may not specify `where` or - * `order_by`. + * A document is missing if it does not exist, but there are sub-documents + * nested underneath it. When true, such missing documents will be returned + * with a key but will not have fields, + * {@link protos.google.firestore.v1.Document.create_time|`create_time`}, or + * {@link protos.google.firestore.v1.Document.update_time|`update_time`} set. + * + * Requests with `show_missing` may not specify `where` or `order_by`. * @param {object} [options] * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. * @returns {Stream} - * An object stream which emits an object representing [Document]{@link google.firestore.v1.Document} on 'data' event. + * An object stream which emits an object representing {@link protos.google.firestore.v1.Document|Document} on 'data' event. * The client library will perform auto-pagination by default: it will call the API as many * times as needed. Note that it can affect your quota. * We recommend using `listDocumentsAsync()` * method described below for async iteration which you can stop as needed. - * Please see the - * [documentation](https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#auto-pagination) + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#auto-pagination | documentation } * for more details and examples. */ listDocumentsStream( @@ -815,45 +939,66 @@ export declare class FirestoreClient { * Required. The parent resource name. In the format: * `projects/{project_id}/databases/{database_id}/documents` or * `projects/{project_id}/databases/{database_id}/documents/{document_path}`. + * * For example: * `projects/my-project/databases/my-database/documents` or * `projects/my-project/databases/my-database/documents/chatrooms/my-chatroom` - * @param {string} request.collectionId - * Required. The collection ID, relative to `parent`, to list. For example: `chatrooms` - * or `messages`. - * @param {number} request.pageSize - * The maximum number of documents to return. - * @param {string} request.pageToken - * The `next_page_token` value returned from a previous List request, if any. - * @param {string} request.orderBy - * The order to sort results by. For example: `priority desc, name`. - * @param {google.firestore.v1.DocumentMask} request.mask - * The fields to return. If not set, returns all fields. + * @param {string} [request.collectionId] + * Optional. The collection ID, relative to `parent`, to list. + * + * For example: `chatrooms` or `messages`. + * + * This is optional, and when not provided, Firestore will list documents + * from all collections under the provided `parent`. + * @param {number} [request.pageSize] + * Optional. The maximum number of documents to return in a single response. + * + * Firestore may return fewer than this value. + * @param {string} [request.pageToken] + * Optional. A page token, received from a previous `ListDocuments` response. + * + * Provide this to retrieve the subsequent page. When paginating, all other + * parameters (with the exception of `page_size`) must match the values set + * in the request that generated the page token. + * @param {string} [request.orderBy] + * Optional. The optional ordering of the documents to return. + * + * For example: `priority desc, __name__ desc`. + * + * This mirrors the {@link protos.google.firestore.v1.StructuredQuery.order_by|`ORDER BY`} + * used in Firestore queries but in a string representation. When absent, + * documents are ordered based on `__name__ ASC`. + * @param {google.firestore.v1.DocumentMask} [request.mask] + * Optional. The fields to return. If not set, returns all fields. * * If a document has a field that is not present in this mask, that field * will not be returned in the response. * @param {Buffer} request.transaction - * Reads documents in a transaction. + * Perform the read as part of an already active transaction. * @param {google.protobuf.Timestamp} request.readTime - * Reads documents as they were at the given time. - * This may not be older than 270 seconds. + * Perform the read at the provided time. + * + * This must be a microsecond precision timestamp within the past one hour, + * or if Point-in-Time Recovery is enabled, can additionally be a whole + * minute timestamp within the past 7 days. * @param {boolean} request.showMissing - * If the list should show missing documents. A missing document is a - * document that does not exist but has sub-documents. These documents will - * be returned with a key but will not have fields, {@link google.firestore.v1.Document.create_time|Document.create_time}, - * or {@link google.firestore.v1.Document.update_time|Document.update_time} set. + * If the list should show missing documents. * - * Requests with `show_missing` may not specify `where` or - * `order_by`. + * A document is missing if it does not exist, but there are sub-documents + * nested underneath it. When true, such missing documents will be returned + * with a key but will not have fields, + * {@link protos.google.firestore.v1.Document.create_time|`create_time`}, or + * {@link protos.google.firestore.v1.Document.update_time|`update_time`} set. + * + * Requests with `show_missing` may not specify `where` or `order_by`. * @param {object} [options] * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. * @returns {Object} - * An iterable Object that allows [async iteration](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols). + * An iterable Object that allows {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols | async iteration }. * When you iterate the returned iterable, each element will be an object representing - * [Document]{@link google.firestore.v1.Document}. The API will be called under the hood as needed, once per the page, + * {@link protos.google.firestore.v1.Document|Document}. The API will be called under the hood as needed, once per the page, * so you can stop the iteration when you don't need more results. - * Please see the - * [documentation](https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#auto-pagination) + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#auto-pagination | documentation } * for more details and examples. * @example include:samples/generated/v1/firestore.list_documents.js * region_tag:firestore_v1_generated_Firestore_ListDocuments_async @@ -910,17 +1055,22 @@ export declare class FirestoreClient { * to PartitionQuery will return up to 8 partitions and a `next_page_token` * if more results exist. A second call to PartitionQuery will return up to * 2 partitions, to complete the total of 10 specified in `partition_count`. + * @param {google.protobuf.Timestamp} request.readTime + * Reads documents as they were at the given time. + * + * This must be a microsecond precision timestamp within the past one hour, + * or if Point-in-Time Recovery is enabled, can additionally be a whole + * minute timestamp within the past 7 days. * @param {object} [options] * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. * @returns {Promise} - The promise which resolves to an array. - * The first element of the array is Array of [Cursor]{@link google.firestore.v1.Cursor}. + * The first element of the array is Array of {@link protos.google.firestore.v1.Cursor|Cursor}. * The client library will perform auto-pagination by default: it will call the API as many * times as needed and will merge results from all the pages into this array. * Note that it can affect your quota. * We recommend using `partitionQueryAsync()` * method described below for async iteration which you can stop as needed. - * Please see the - * [documentation](https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#auto-pagination) + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#auto-pagination | documentation } * for more details and examples. */ partitionQuery( @@ -995,16 +1145,21 @@ export declare class FirestoreClient { * to PartitionQuery will return up to 8 partitions and a `next_page_token` * if more results exist. A second call to PartitionQuery will return up to * 2 partitions, to complete the total of 10 specified in `partition_count`. + * @param {google.protobuf.Timestamp} request.readTime + * Reads documents as they were at the given time. + * + * This must be a microsecond precision timestamp within the past one hour, + * or if Point-in-Time Recovery is enabled, can additionally be a whole + * minute timestamp within the past 7 days. * @param {object} [options] * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. * @returns {Stream} - * An object stream which emits an object representing [Cursor]{@link google.firestore.v1.Cursor} on 'data' event. + * An object stream which emits an object representing {@link protos.google.firestore.v1.Cursor|Cursor} on 'data' event. * The client library will perform auto-pagination by default: it will call the API as many * times as needed. Note that it can affect your quota. * We recommend using `partitionQueryAsync()` * method described below for async iteration which you can stop as needed. - * Please see the - * [documentation](https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#auto-pagination) + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#auto-pagination | documentation } * for more details and examples. */ partitionQueryStream( @@ -1058,15 +1213,20 @@ export declare class FirestoreClient { * to PartitionQuery will return up to 8 partitions and a `next_page_token` * if more results exist. A second call to PartitionQuery will return up to * 2 partitions, to complete the total of 10 specified in `partition_count`. + * @param {google.protobuf.Timestamp} request.readTime + * Reads documents as they were at the given time. + * + * This must be a microsecond precision timestamp within the past one hour, + * or if Point-in-Time Recovery is enabled, can additionally be a whole + * minute timestamp within the past 7 days. * @param {object} [options] * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. * @returns {Object} - * An iterable Object that allows [async iteration](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols). + * An iterable Object that allows {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols | async iteration }. * When you iterate the returned iterable, each element will be an object representing - * [Cursor]{@link google.firestore.v1.Cursor}. The API will be called under the hood as needed, once per the page, + * {@link protos.google.firestore.v1.Cursor|Cursor}. The API will be called under the hood as needed, once per the page, * so you can stop the iteration when you don't need more results. - * Please see the - * [documentation](https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#auto-pagination) + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#auto-pagination | documentation } * for more details and examples. * @example include:samples/generated/v1/firestore.partition_query.js * region_tag:firestore_v1_generated_Firestore_PartitionQuery_async @@ -1089,7 +1249,13 @@ export declare class FirestoreClient { * The maximum number of results to return. * @param {string} request.pageToken * A page token. Must be a value from - * {@link google.firestore.v1.ListCollectionIdsResponse|ListCollectionIdsResponse}. + * {@link protos.google.firestore.v1.ListCollectionIdsResponse|ListCollectionIdsResponse}. + * @param {google.protobuf.Timestamp} request.readTime + * Reads documents as they were at the given time. + * + * This must be a microsecond precision timestamp within the past one hour, + * or if Point-in-Time Recovery is enabled, can additionally be a whole + * minute timestamp within the past 7 days. * @param {object} [options] * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. * @returns {Promise} - The promise which resolves to an array. @@ -1099,8 +1265,7 @@ export declare class FirestoreClient { * Note that it can affect your quota. * We recommend using `listCollectionIdsAsync()` * method described below for async iteration which you can stop as needed. - * Please see the - * [documentation](https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#auto-pagination) + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#auto-pagination | documentation } * for more details and examples. */ listCollectionIds( @@ -1143,7 +1308,13 @@ export declare class FirestoreClient { * The maximum number of results to return. * @param {string} request.pageToken * A page token. Must be a value from - * {@link google.firestore.v1.ListCollectionIdsResponse|ListCollectionIdsResponse}. + * {@link protos.google.firestore.v1.ListCollectionIdsResponse|ListCollectionIdsResponse}. + * @param {google.protobuf.Timestamp} request.readTime + * Reads documents as they were at the given time. + * + * This must be a microsecond precision timestamp within the past one hour, + * or if Point-in-Time Recovery is enabled, can additionally be a whole + * minute timestamp within the past 7 days. * @param {object} [options] * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. * @returns {Stream} @@ -1152,8 +1323,7 @@ export declare class FirestoreClient { * times as needed. Note that it can affect your quota. * We recommend using `listCollectionIdsAsync()` * method described below for async iteration which you can stop as needed. - * Please see the - * [documentation](https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#auto-pagination) + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#auto-pagination | documentation } * for more details and examples. */ listCollectionIdsStream( @@ -1175,16 +1345,21 @@ export declare class FirestoreClient { * The maximum number of results to return. * @param {string} request.pageToken * A page token. Must be a value from - * {@link google.firestore.v1.ListCollectionIdsResponse|ListCollectionIdsResponse}. + * {@link protos.google.firestore.v1.ListCollectionIdsResponse|ListCollectionIdsResponse}. + * @param {google.protobuf.Timestamp} request.readTime + * Reads documents as they were at the given time. + * + * This must be a microsecond precision timestamp within the past one hour, + * or if Point-in-Time Recovery is enabled, can additionally be a whole + * minute timestamp within the past 7 days. * @param {object} [options] * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. * @returns {Object} - * An iterable Object that allows [async iteration](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols). + * An iterable Object that allows {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols | async iteration }. * When you iterate the returned iterable, each element will be an object representing * string. The API will be called under the hood as needed, once per the page, * so you can stop the iteration when you don't need more results. - * Please see the - * [documentation](https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#auto-pagination) + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#auto-pagination | documentation } * for more details and examples. * @example include:samples/generated/v1/firestore.list_collection_ids.js * region_tag:firestore_v1_generated_Firestore_ListCollectionIds_async @@ -1193,6 +1368,78 @@ export declare class FirestoreClient { request?: protos.google.firestore.v1.IListCollectionIdsRequest, options?: CallOptions ): AsyncIterable; + /** + * Gets information about a location. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.name + * Resource name for the location. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html | CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is an object representing {@link google.cloud.location.Location | Location}. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } + * for more details and examples. + * @example + * ``` + * const [response] = await client.getLocation(request); + * ``` + */ + getLocation( + request: LocationProtos.google.cloud.location.IGetLocationRequest, + options?: + | gax.CallOptions + | Callback< + LocationProtos.google.cloud.location.ILocation, + | LocationProtos.google.cloud.location.IGetLocationRequest + | null + | undefined, + {} | null | undefined + >, + callback?: Callback< + LocationProtos.google.cloud.location.ILocation, + | LocationProtos.google.cloud.location.IGetLocationRequest + | null + | undefined, + {} | null | undefined + > + ): Promise; + /** + * Lists information about the supported locations for this service. Returns an iterable object. + * + * `for`-`await`-`of` syntax is used with the iterable to get response elements on-demand. + * @param {Object} request + * The request object that will be sent. + * @param {string} request.name + * The resource that owns the locations collection, if applicable. + * @param {string} request.filter + * The standard list filter. + * @param {number} request.pageSize + * The standard list page size. + * @param {string} request.pageToken + * The standard list page token. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Object} + * An iterable Object that allows {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols | async iteration }. + * When you iterate the returned iterable, each element will be an object representing + * {@link google.cloud.location.Location | Location}. The API will be called under the hood as needed, once per the page, + * so you can stop the iteration when you don't need more results. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#auto-pagination | documentation } + * for more details and examples. + * @example + * ``` + * const iterable = client.listLocationsAsync(request); + * for await (const response of iterable) { + * // process response + * } + * ``` + */ + listLocationsAsync( + request: LocationProtos.google.cloud.location.IListLocationsRequest, + options?: CallOptions + ): AsyncIterable; /** * Terminate the gRPC channel and close the client. * diff --git a/types/v1beta1/firestore_client.d.ts b/types/v1beta1/firestore_client.d.ts index e67468999..5767fe100 100644 --- a/types/v1beta1/firestore_client.d.ts +++ b/types/v1beta1/firestore_client.d.ts @@ -1,5 +1,5 @@ /*! - * Copyright 2022 Google LLC + * 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. @@ -14,9 +14,8 @@ * limitations under the License. */ -/// -import * as gax from 'google-gax'; -import { +import type * as gax from 'google-gax'; +import type { Callback, CallOptions, Descriptors, @@ -46,6 +45,8 @@ export declare class FirestoreClient { private _gaxGrpc; private _protos; private _defaults; + private _universeDomain; + private _servicePath; auth: gax.GoogleAuth; descriptors: Descriptors; warn: (code: string, message: string, warnType?: string) => void; @@ -60,7 +61,7 @@ export declare class FirestoreClient { * * @param {object} [options] - The configuration object. * The options accepted by the constructor are described in detail - * in [this document](https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#creating-the-client-instance). + * in [this document](https://github.com/googleapis/gax-nodejs/blob/main/client-libraries.md#creating-the-client-instance). * The common options are: * @param {object} [options.credentials] - Credentials object. * @param {string} [options.credentials.client_email] @@ -83,13 +84,21 @@ export declare class FirestoreClient { * API remote host. * @param {gax.ClientConfig} [options.clientConfig] - Client configuration override. * Follows the structure of {@link gapicConfig}. - * @param {boolean} [options.fallback] - Use HTTP fallback mode. - * In fallback mode, a special browser-compatible transport implementation is used - * instead of gRPC transport. In browser context (if the `window` object is defined) - * the fallback mode is enabled automatically; set `options.fallback` to `false` - * if you need to override this behavior. + * @param {boolean} [options.fallback] - Use HTTP/1.1 REST mode. + * For more information, please check the + * {@link https://github.com/googleapis/gax-nodejs/blob/main/client-libraries.md#http11-rest-api-mode documentation}. + * @param {gax} [gaxInstance]: loaded instance of `google-gax`. Useful if you + * need to avoid loading the default gRPC version and want to use the fallback + * HTTP implementation. Load only fallback version and pass it to the constructor: + * ``` + * const gax = require('google-gax/build/src/fallback'); // avoids loading google-gax with gRPC + * const client = new FirestoreClient({fallback: true}, gax); + * ``` */ - constructor(opts?: ClientOptions); + constructor( + opts?: ClientOptions, + gaxInstance?: typeof gax | typeof gax.fallback + ); /** * Initialize the client. * Performs asynchronous operations (such as authentication) and prepares the client. @@ -106,15 +115,22 @@ export declare class FirestoreClient { }>; /** * The DNS address for this API service. + * @deprecated Use the apiEndpoint method of the client instance. * @returns {string} The DNS address for this service. */ static get servicePath(): string; /** - * The DNS address for this API service - same as servicePath(), - * exists for compatibility reasons. + * The DNS address for this API service - same as servicePath. + * @deprecated Use the apiEndpoint method of the client instance. * @returns {string} The DNS address for this service. */ static get apiEndpoint(): string; + /** + * The DNS address for this API service. + * @returns {string} The DNS address for this service. + */ + get apiEndpoint(): string; + get universeDomain(): string; /** * The port for this API service. * @returns {number} The default port for this service. @@ -149,9 +165,8 @@ export declare class FirestoreClient { * @param {object} [options] * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. * @returns {Promise} - The promise which resolves to an array. - * The first element of the array is an object representing [Document]{@link google.firestore.v1beta1.Document}. - * Please see the - * [documentation](https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods) + * The first element of the array is an object representing {@link protos.google.firestore.v1beta1.Document|Document}. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } * for more details and examples. * @example include:samples/generated/v1beta1/firestore.get_document.js * region_tag:firestore_v1beta1_generated_Firestore_GetDocument_async @@ -210,9 +225,8 @@ export declare class FirestoreClient { * @param {object} [options] * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. * @returns {Promise} - The promise which resolves to an array. - * The first element of the array is an object representing [Document]{@link google.firestore.v1beta1.Document}. - * Please see the - * [documentation](https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods) + * The first element of the array is an object representing {@link protos.google.firestore.v1beta1.Document|Document}. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } * for more details and examples. * @example include:samples/generated/v1beta1/firestore.update_document.js * region_tag:firestore_v1beta1_generated_Firestore_UpdateDocument_async @@ -258,9 +272,8 @@ export declare class FirestoreClient { * @param {object} [options] * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. * @returns {Promise} - The promise which resolves to an array. - * The first element of the array is an object representing [Empty]{@link google.protobuf.Empty}. - * Please see the - * [documentation](https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods) + * The first element of the array is an object representing {@link protos.google.protobuf.Empty|Empty}. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } * for more details and examples. * @example include:samples/generated/v1beta1/firestore.delete_document.js * region_tag:firestore_v1beta1_generated_Firestore_DeleteDocument_async @@ -306,9 +319,8 @@ export declare class FirestoreClient { * @param {object} [options] * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. * @returns {Promise} - The promise which resolves to an array. - * The first element of the array is an object representing [BeginTransactionResponse]{@link google.firestore.v1beta1.BeginTransactionResponse}. - * Please see the - * [documentation](https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods) + * The first element of the array is an object representing {@link protos.google.firestore.v1beta1.BeginTransactionResponse|BeginTransactionResponse}. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } * for more details and examples. * @example include:samples/generated/v1beta1/firestore.begin_transaction.js * region_tag:firestore_v1beta1_generated_Firestore_BeginTransaction_async @@ -361,9 +373,8 @@ export declare class FirestoreClient { * @param {object} [options] * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. * @returns {Promise} - The promise which resolves to an array. - * The first element of the array is an object representing [CommitResponse]{@link google.firestore.v1beta1.CommitResponse}. - * Please see the - * [documentation](https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods) + * The first element of the array is an object representing {@link protos.google.firestore.v1beta1.CommitResponse|CommitResponse}. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } * for more details and examples. * @example include:samples/generated/v1beta1/firestore.commit.js * region_tag:firestore_v1beta1_generated_Firestore_Commit_async @@ -408,9 +419,8 @@ export declare class FirestoreClient { * @param {object} [options] * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. * @returns {Promise} - The promise which resolves to an array. - * The first element of the array is an object representing [Empty]{@link google.protobuf.Empty}. - * Please see the - * [documentation](https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods) + * The first element of the array is an object representing {@link protos.google.protobuf.Empty|Empty}. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } * for more details and examples. * @example include:samples/generated/v1beta1/firestore.rollback.js * region_tag:firestore_v1beta1_generated_Firestore_Rollback_async @@ -448,10 +458,10 @@ export declare class FirestoreClient { * The BatchWrite method does not apply the write operations atomically * and can apply them out of order. Method does not allow more than one write * per document. Each write succeeds or fails independently. See the - * {@link google.firestore.v1beta1.BatchWriteResponse|BatchWriteResponse} for the success status of each write. + * {@link protos.google.firestore.v1beta1.BatchWriteResponse|BatchWriteResponse} for the success status of each write. * * If you require an atomically applied set of writes, use - * {@link google.firestore.v1beta1.Firestore.Commit|Commit} instead. + * {@link protos.google.firestore.v1beta1.Firestore.Commit|Commit} instead. * * @param {Object} request * The request object that will be sent. @@ -469,9 +479,8 @@ export declare class FirestoreClient { * @param {object} [options] * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. * @returns {Promise} - The promise which resolves to an array. - * The first element of the array is an object representing [BatchWriteResponse]{@link google.firestore.v1beta1.BatchWriteResponse}. - * Please see the - * [documentation](https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods) + * The first element of the array is an object representing {@link protos.google.firestore.v1beta1.BatchWriteResponse|BatchWriteResponse}. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } * for more details and examples. * @example include:samples/generated/v1beta1/firestore.batch_write.js * region_tag:firestore_v1beta1_generated_Firestore_BatchWrite_async @@ -528,9 +537,8 @@ export declare class FirestoreClient { * @param {object} [options] * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. * @returns {Promise} - The promise which resolves to an array. - * The first element of the array is an object representing [Document]{@link google.firestore.v1beta1.Document}. - * Please see the - * [documentation](https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods) + * The first element of the array is an object representing {@link protos.google.firestore.v1beta1.Document|Document}. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } * for more details and examples. * @example include:samples/generated/v1beta1/firestore.create_document.js * region_tag:firestore_v1beta1_generated_Firestore_CreateDocument_async @@ -596,9 +604,8 @@ export declare class FirestoreClient { * @param {object} [options] * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. * @returns {Stream} - * An object stream which emits [BatchGetDocumentsResponse]{@link google.firestore.v1beta1.BatchGetDocumentsResponse} on 'data' event. - * Please see the - * [documentation](https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#server-streaming) + * An object stream which emits {@link protos.google.firestore.v1beta1.BatchGetDocumentsResponse|BatchGetDocumentsResponse} on 'data' event. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#server-streaming | documentation } * for more details and examples. * @example include:samples/generated/v1beta1/firestore.batch_get_documents.js * region_tag:firestore_v1beta1_generated_Firestore_BatchGetDocuments_async @@ -634,9 +641,8 @@ export declare class FirestoreClient { * @param {object} [options] * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. * @returns {Stream} - * An object stream which emits [RunQueryResponse]{@link google.firestore.v1beta1.RunQueryResponse} on 'data' event. - * Please see the - * [documentation](https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#server-streaming) + * An object stream which emits {@link protos.google.firestore.v1beta1.RunQueryResponse|RunQueryResponse} on 'data' event. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#server-streaming | documentation } * for more details and examples. * @example include:samples/generated/v1beta1/firestore.run_query.js * region_tag:firestore_v1beta1_generated_Firestore_RunQuery_async @@ -652,10 +658,9 @@ export declare class FirestoreClient { * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. * @returns {Stream} * An object stream which is both readable and writable. It accepts objects - * representing [WriteRequest]{@link google.firestore.v1beta1.WriteRequest} for write() method, and - * will emit objects representing [WriteResponse]{@link google.firestore.v1beta1.WriteResponse} on 'data' event asynchronously. - * Please see the - * [documentation](https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#bi-directional-streaming) + * representing {@link protos.google.firestore.v1beta1.WriteRequest|WriteRequest} for write() method, and + * will emit objects representing {@link protos.google.firestore.v1beta1.WriteResponse|WriteResponse} on 'data' event asynchronously. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#bi-directional-streaming | documentation } * for more details and examples. * @example include:samples/generated/v1beta1/firestore.write.js * region_tag:firestore_v1beta1_generated_Firestore_Write_async @@ -668,10 +673,9 @@ export declare class FirestoreClient { * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. * @returns {Stream} * An object stream which is both readable and writable. It accepts objects - * representing [ListenRequest]{@link google.firestore.v1beta1.ListenRequest} for write() method, and - * will emit objects representing [ListenResponse]{@link google.firestore.v1beta1.ListenResponse} on 'data' event asynchronously. - * Please see the - * [documentation](https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#bi-directional-streaming) + * representing {@link protos.google.firestore.v1beta1.ListenRequest|ListenRequest} for write() method, and + * will emit objects representing {@link protos.google.firestore.v1beta1.ListenResponse|ListenResponse} on 'data' event asynchronously. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#bi-directional-streaming | documentation } * for more details and examples. * @example include:samples/generated/v1beta1/firestore.listen.js * region_tag:firestore_v1beta1_generated_Firestore_Listen_async @@ -711,22 +715,21 @@ export declare class FirestoreClient { * @param {boolean} request.showMissing * If the list should show missing documents. A missing document is a * document that does not exist but has sub-documents. These documents will - * be returned with a key but will not have fields, {@link google.firestore.v1beta1.Document.create_time|Document.create_time}, - * or {@link google.firestore.v1beta1.Document.update_time|Document.update_time} set. + * be returned with a key but will not have fields, {@link protos.google.firestore.v1beta1.Document.create_time|Document.create_time}, + * or {@link protos.google.firestore.v1beta1.Document.update_time|Document.update_time} set. * * Requests with `show_missing` may not specify `where` or * `order_by`. * @param {object} [options] * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. * @returns {Promise} - The promise which resolves to an array. - * The first element of the array is Array of [Document]{@link google.firestore.v1beta1.Document}. + * The first element of the array is Array of {@link protos.google.firestore.v1beta1.Document|Document}. * The client library will perform auto-pagination by default: it will call the API as many * times as needed and will merge results from all the pages into this array. * Note that it can affect your quota. * We recommend using `listDocumentsAsync()` * method described below for async iteration which you can stop as needed. - * Please see the - * [documentation](https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#auto-pagination) + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#auto-pagination | documentation } * for more details and examples. */ listDocuments( @@ -789,21 +792,20 @@ export declare class FirestoreClient { * @param {boolean} request.showMissing * If the list should show missing documents. A missing document is a * document that does not exist but has sub-documents. These documents will - * be returned with a key but will not have fields, {@link google.firestore.v1beta1.Document.create_time|Document.create_time}, - * or {@link google.firestore.v1beta1.Document.update_time|Document.update_time} set. + * be returned with a key but will not have fields, {@link protos.google.firestore.v1beta1.Document.create_time|Document.create_time}, + * or {@link protos.google.firestore.v1beta1.Document.update_time|Document.update_time} set. * * Requests with `show_missing` may not specify `where` or * `order_by`. * @param {object} [options] * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. * @returns {Stream} - * An object stream which emits an object representing [Document]{@link google.firestore.v1beta1.Document} on 'data' event. + * An object stream which emits an object representing {@link protos.google.firestore.v1beta1.Document|Document} on 'data' event. * The client library will perform auto-pagination by default: it will call the API as many * times as needed. Note that it can affect your quota. * We recommend using `listDocumentsAsync()` * method described below for async iteration which you can stop as needed. - * Please see the - * [documentation](https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#auto-pagination) + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#auto-pagination | documentation } * for more details and examples. */ listDocumentsStream( @@ -845,20 +847,19 @@ export declare class FirestoreClient { * @param {boolean} request.showMissing * If the list should show missing documents. A missing document is a * document that does not exist but has sub-documents. These documents will - * be returned with a key but will not have fields, {@link google.firestore.v1beta1.Document.create_time|Document.create_time}, - * or {@link google.firestore.v1beta1.Document.update_time|Document.update_time} set. + * be returned with a key but will not have fields, {@link protos.google.firestore.v1beta1.Document.create_time|Document.create_time}, + * or {@link protos.google.firestore.v1beta1.Document.update_time|Document.update_time} set. * * Requests with `show_missing` may not specify `where` or * `order_by`. * @param {object} [options] * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. * @returns {Object} - * An iterable Object that allows [async iteration](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols). + * An iterable Object that allows {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols | async iteration }. * When you iterate the returned iterable, each element will be an object representing - * [Document]{@link google.firestore.v1beta1.Document}. The API will be called under the hood as needed, once per the page, + * {@link protos.google.firestore.v1beta1.Document|Document}. The API will be called under the hood as needed, once per the page, * so you can stop the iteration when you don't need more results. - * Please see the - * [documentation](https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#auto-pagination) + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#auto-pagination | documentation } * for more details and examples. * @example include:samples/generated/v1beta1/firestore.list_documents.js * region_tag:firestore_v1beta1_generated_Firestore_ListDocuments_async @@ -918,14 +919,13 @@ export declare class FirestoreClient { * @param {object} [options] * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. * @returns {Promise} - The promise which resolves to an array. - * The first element of the array is Array of [Cursor]{@link google.firestore.v1beta1.Cursor}. + * The first element of the array is Array of {@link protos.google.firestore.v1beta1.Cursor|Cursor}. * The client library will perform auto-pagination by default: it will call the API as many * times as needed and will merge results from all the pages into this array. * Note that it can affect your quota. * We recommend using `partitionQueryAsync()` * method described below for async iteration which you can stop as needed. - * Please see the - * [documentation](https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#auto-pagination) + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#auto-pagination | documentation } * for more details and examples. */ partitionQuery( @@ -1007,13 +1007,12 @@ export declare class FirestoreClient { * @param {object} [options] * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. * @returns {Stream} - * An object stream which emits an object representing [Cursor]{@link google.firestore.v1beta1.Cursor} on 'data' event. + * An object stream which emits an object representing {@link protos.google.firestore.v1beta1.Cursor|Cursor} on 'data' event. * The client library will perform auto-pagination by default: it will call the API as many * times as needed. Note that it can affect your quota. * We recommend using `partitionQueryAsync()` * method described below for async iteration which you can stop as needed. - * Please see the - * [documentation](https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#auto-pagination) + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#auto-pagination | documentation } * for more details and examples. */ partitionQueryStream( @@ -1070,12 +1069,11 @@ export declare class FirestoreClient { * @param {object} [options] * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. * @returns {Object} - * An iterable Object that allows [async iteration](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols). + * An iterable Object that allows {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols | async iteration }. * When you iterate the returned iterable, each element will be an object representing - * [Cursor]{@link google.firestore.v1beta1.Cursor}. The API will be called under the hood as needed, once per the page, + * {@link protos.google.firestore.v1beta1.Cursor|Cursor}. The API will be called under the hood as needed, once per the page, * so you can stop the iteration when you don't need more results. - * Please see the - * [documentation](https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#auto-pagination) + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#auto-pagination | documentation } * for more details and examples. * @example include:samples/generated/v1beta1/firestore.partition_query.js * region_tag:firestore_v1beta1_generated_Firestore_PartitionQuery_async @@ -1098,7 +1096,7 @@ export declare class FirestoreClient { * The maximum number of results to return. * @param {string} request.pageToken * A page token. Must be a value from - * {@link google.firestore.v1beta1.ListCollectionIdsResponse|ListCollectionIdsResponse}. + * {@link protos.google.firestore.v1beta1.ListCollectionIdsResponse|ListCollectionIdsResponse}. * @param {object} [options] * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. * @returns {Promise} - The promise which resolves to an array. @@ -1108,8 +1106,7 @@ export declare class FirestoreClient { * Note that it can affect your quota. * We recommend using `listCollectionIdsAsync()` * method described below for async iteration which you can stop as needed. - * Please see the - * [documentation](https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#auto-pagination) + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#auto-pagination | documentation } * for more details and examples. */ listCollectionIds( @@ -1156,7 +1153,7 @@ export declare class FirestoreClient { * The maximum number of results to return. * @param {string} request.pageToken * A page token. Must be a value from - * {@link google.firestore.v1beta1.ListCollectionIdsResponse|ListCollectionIdsResponse}. + * {@link protos.google.firestore.v1beta1.ListCollectionIdsResponse|ListCollectionIdsResponse}. * @param {object} [options] * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. * @returns {Stream} @@ -1165,8 +1162,7 @@ export declare class FirestoreClient { * times as needed. Note that it can affect your quota. * We recommend using `listCollectionIdsAsync()` * method described below for async iteration which you can stop as needed. - * Please see the - * [documentation](https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#auto-pagination) + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#auto-pagination | documentation } * for more details and examples. */ listCollectionIdsStream( @@ -1188,16 +1184,15 @@ export declare class FirestoreClient { * The maximum number of results to return. * @param {string} request.pageToken * A page token. Must be a value from - * {@link google.firestore.v1beta1.ListCollectionIdsResponse|ListCollectionIdsResponse}. + * {@link protos.google.firestore.v1beta1.ListCollectionIdsResponse|ListCollectionIdsResponse}. * @param {object} [options] * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. * @returns {Object} - * An iterable Object that allows [async iteration](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols). + * An iterable Object that allows {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols | async iteration }. * When you iterate the returned iterable, each element will be an object representing * string. The API will be called under the hood as needed, once per the page, * so you can stop the iteration when you don't need more results. - * Please see the - * [documentation](https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#auto-pagination) + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#auto-pagination | documentation } * for more details and examples. * @example include:samples/generated/v1beta1/firestore.list_collection_ids.js * region_tag:firestore_v1beta1_generated_Firestore_ListCollectionIds_async From db8a43b77dc45437d26f01e8877ef64d7761484d Mon Sep 17 00:00:00 2001 From: Tom Andersen Date: Thu, 16 Jan 2025 20:40:47 -0500 Subject: [PATCH 33/60] feature: New Pipeline Stages (#2236) * new stages * add tests * fix * fix * Fix code examples * Add unnest options to `d.ts` file. * Fix union test * Add test, fix documentation, refactor. * Documentation * Undo --- dev/src/expression.ts | 32 --- dev/src/index.ts | 1 - dev/src/pipeline-util.ts | 37 +++- dev/src/pipeline.ts | 400 ++++++++++++++++++++++++++---------- dev/src/serializer.ts | 23 +++ dev/src/stage.ts | 118 ++++++++++- dev/system-test/pipeline.ts | 143 +++++++++++-- dev/system-test/query.ts | 4 +- types/firestore.d.ts | 232 +++++++++++++++++++-- 9 files changed, 798 insertions(+), 192 deletions(-) diff --git a/dev/src/expression.ts b/dev/src/expression.ts index 399433096..c0f87daf5 100644 --- a/dev/src/expression.ts +++ b/dev/src/expression.ts @@ -1942,38 +1942,6 @@ export class Field extends Expr implements Selectable { } } -/** - * @beta - */ -export class Fields extends Expr implements Selectable { - exprType: ExprType = 'Field'; - selectable = true as const; - - private constructor(private fields: Field[]) { - super(); - } - - static of(name: string, ...others: string[]): Fields { - return new Fields([Field.of(name), ...others.map(Field.of)]); - } - - static ofAll(): Fields { - return new Fields([]); - } - - fieldList(): Field[] { - return this.fields.map(f => f); - } - - _toProto(serializer: Serializer): api.IValue { - return { - arrayValue: { - values: this.fields.map(f => f._toProto(serializer)), - }, - }; - } -} - /** * @beta * diff --git a/dev/src/index.ts b/dev/src/index.ts index 99e15c01a..2783a507c 100644 --- a/dev/src/index.ts +++ b/dev/src/index.ts @@ -147,7 +147,6 @@ export { Expr, ExprWithAlias, Field, - Fields, Constant, Function, Ordering, diff --git a/dev/src/pipeline-util.ts b/dev/src/pipeline-util.ts index 1bb77b482..66cf4c9fa 100644 --- a/dev/src/pipeline-util.ts +++ b/dev/src/pipeline-util.ts @@ -156,7 +156,6 @@ export class ExecutionUtil { enc, callback ) => { - console.log(`Pipeline response: ${JSON.stringify(proto, null, 2)}`); if (proto === NOOP_MESSAGE) { callback(undefined); return; @@ -215,14 +214,20 @@ export class ExecutionUtil { // `toProto()` might throw an exception. We rely on the behavior of an // async function to convert this exception into the rejected Promise we // catch below. - const request = pipeline._toProto( - transactionOrReadTime, - explainOptions - ); - - console.log( - `Executing pipeline: \n ${JSON.stringify(request, null, 2)}` - ); + const request: api.IExecutePipelineRequest = { + database: this._firestore.formattedName, + structuredPipeline: { + pipeline: pipeline._toProto(), + }, + }; + + if (transactionOrReadTime instanceof Uint8Array) { + request.transaction = transactionOrReadTime; + } else if (transactionOrReadTime instanceof Timestamp) { + request.readTime = transactionOrReadTime.toProto().timestampValue; + } else if (transactionOrReadTime) { + request.newTransaction = transactionOrReadTime; + } let streamActive: Deferred; do { @@ -392,6 +397,20 @@ export function isFirestoreValue(obj: any): obj is api.IValue { return false; } +export function selectableToExpr( + selectable: firestore.Selectable | string +): Expr { + if (typeof selectable === 'string') { + return Field.of(selectable); + } else if (selectable instanceof Field) { + return selectable; + } else if (selectable instanceof ExprWithAlias) { + return selectable.expr; + } else { + throw new Error('unexpected selectable: ' + selectable); + } +} + export function toPipelineFilterCondition( f: FilterInternal, serializer: Serializer diff --git a/dev/src/pipeline.ts b/dev/src/pipeline.ts index 4fc32d402..b90e18906 100644 --- a/dev/src/pipeline.ts +++ b/dev/src/pipeline.ts @@ -21,7 +21,6 @@ import { Expr, ExprWithAlias, Field, - Fields, FilterCondition, Function, Ordering, @@ -29,7 +28,7 @@ import { } from './expression'; import Firestore, {FieldPath, QueryDocumentSnapshot, Timestamp} from './index'; import {validateFieldPath} from './path'; -import {ExecutionUtil} from './pipeline-util'; +import {ExecutionUtil, selectableToExpr} from './pipeline-util'; import {DocumentReference} from './reference/document-reference'; import {PipelineResponse} from './reference/types'; import {Serializer} from './serializer'; @@ -51,6 +50,12 @@ import { Stage, Distinct, RemoveFields, + Replace, + Sample, + SampleOptions, + Union, + Unnest, + UnnestOptions, } from './stage'; import {ApiMapValue, defaultPipelineConverter} from './types'; import * as protos from '../protos/firestore_v1_proto_api'; @@ -107,21 +112,21 @@ export class PipelineSource implements firestore.PipelineSource { * * // Example 1: Select specific fields and rename 'rating' to 'bookRating' * const results1 = await db.pipeline() - * .collection("books") - * .select("title", "author", Field.of("rating").as("bookRating")) + * .collection('books') + * .select('title', 'author', Field.of('rating').as('bookRating')) * .execute(); * - * // Example 2: Filter documents where 'genre' is "Science Fiction" and 'published' is after 1950 + * // Example 2: Filter documents where 'genre' is 'Science Fiction' and 'published' is after 1950 * const results2 = await db.pipeline() - * .collection("books") - * .where(and(Field.of("genre").eq("Science Fiction"), Field.of("published").gt(1950))) + * .collection('books') + * .where(and(Field.of('genre').eq('Science Fiction'), Field.of('published').gt(1950))) * .execute(); * * // Example 3: Calculate the average rating of books published after 1980 * const results3 = await db.pipeline() - * .collection("books") - * .where(Field.of("published").gt(1980)) - * .aggregate(avg(Field.of("rating")).as("averageRating")) + * .collection('books') + * .where(Field.of('published').gt(1980)) + * .aggregate(avg(Field.of('rating')).as('averageRating')) * .execute(); * ``` */ @@ -134,6 +139,12 @@ export class Pipeline private converter: firestore.FirestorePipelineConverter = defaultPipelineConverter() ) {} + private _addStage(stage: Stage): Pipeline { + const copy = this.stages.map(s => s); + copy.push(stage); + return new Pipeline(this.db, copy, this.converter); + } + /** * Adds new fields to outputs from previous stages. * @@ -150,10 +161,10 @@ export class Pipeline * Example: * * ```typescript - * firestore.pipeline().collection("books") + * firestore.pipeline().collection('books') * .addFields( - * Field.of("rating").as("bookRating"), // Rename 'rating' to 'bookRating' - * add(5, Field.of("quantity")).as("totalCost") // Calculate 'totalCost' + * Field.of('rating').as('bookRating'), // Rename 'rating' to 'bookRating' + * add(5, Field.of('quantity')).as('totalCost') // Calculate 'totalCost' * ); * ``` * @@ -161,9 +172,7 @@ export class Pipeline * @return A new Pipeline object with this stage appended to the stage list. */ addFields(...fields: firestore.Selectable[]): Pipeline { - const copy = this.stages.map(s => s); - copy.push(new AddFields(this.selectablesToMap(fields))); - return new Pipeline(this.db, copy, this.converter); + return this._addStage(new AddFields(this.selectablesToMap(fields))); } /** @@ -172,11 +181,11 @@ export class Pipeline * Example: * * ```typescript - * firestore.pipeline().collection("books") + * firestore.pipeline().collection('books') * // removes field 'rating' and 'cost' from the previous stage outputs. * .removeFields( - * Field.of("rating"), - * "cost" + * Field.of('rating'), + * 'cost' * ); * ``` * @@ -186,13 +195,11 @@ export class Pipeline removeFields( ...fields: (firestore.Field | string)[] ): Pipeline { - const copy = this.stages.map(s => s); - copy.push( + return this._addStage( new RemoveFields( fields.map(f => (typeof f === 'string' ? Field.of(f) : (f as Field))) ) ); - return new Pipeline(this.db, copy, this.converter); } /** @@ -214,11 +221,11 @@ export class Pipeline *

    Example: * * ```typescript - * firestore.pipeline().collection("books") + * firestore.pipeline().collection('books') * .select( - * "firstName", - * Field.of("lastName"), - * Field.of("address").toUppercase().as("upperAddress"), + * 'firstName', + * Field.of('lastName'), + * Field.of('address').toUppercase().as('upperAddress'), * ); * ``` * @@ -229,9 +236,7 @@ export class Pipeline select( ...selections: (firestore.Selectable | string)[] ): Pipeline { - const copy = this.stages.map(s => s); - copy.push(new Select(this.selectablesToMap(selections))); - return new Pipeline(this.db, copy, this.converter); + return this._addStage(new Select(this.selectablesToMap(selections))); } private selectablesToMap( @@ -243,14 +248,11 @@ export class Pipeline result.set(selectable as string, Field.of(selectable)); } else if (selectable instanceof Field) { result.set((selectable as Field).fieldName(), selectable); - } else if (selectable instanceof Fields) { - const fields = selectable as Fields; - for (const field of fields.fieldList()) { - result.set(field.fieldName(), field); - } } else if (selectable instanceof ExprWithAlias) { const expr = selectable as ExprWithAlias; result.set(expr.alias, expr.expr); + } else { + throw new Error('unexpected selectable: ' + selectable); } } return result; @@ -260,7 +262,7 @@ export class Pipeline * Filters the documents from previous stages to only include those matching the specified {@link * FilterCondition}. * - *

    This stage allows you to apply conditions to the data, similar to a "WHERE" clause in SQL. + *

    This stage allows you to apply conditions to the data, similar to a 'WHERE' clause in SQL. * You can filter documents based on their field values, using implementations of {@link * FilterCondition}, typically including but not limited to: * @@ -275,11 +277,11 @@ export class Pipeline *

    Example: * * ```typescript - * firestore.pipeline().collection("books") + * firestore.pipeline().collection('books') * .where( * and( - * gt(Field.of("rating"), 4.0), // Filter for ratings greater than 4.0 - * Field.of("genre").eq("Science Fiction") // Equivalent to gt("genre", "Science Fiction") + * gt(Field.of('rating'), 4.0), // Filter for ratings greater than 4.0 + * Field.of('genre').eq('Science Fiction') // Equivalent to gt('genre', 'Science Fiction') * ) * ); * ``` @@ -288,9 +290,7 @@ export class Pipeline * @return A new Pipeline object with this stage appended to the stage list. */ where(condition: FilterCondition & firestore.Expr): Pipeline { - const copy = this.stages.map(s => s); - copy.push(new Where(condition)); - return new Pipeline(this.db, copy, this.converter); + return this._addStage(new Where(condition)); } /** @@ -304,8 +304,8 @@ export class Pipeline * * ```typescript * // Retrieve the second page of 20 results - * firestore.pipeline().collection("books") - * .sort(Field.of("published").descending()) + * firestore.pipeline().collection('books') + * .sort(Field.of('published').descending()) * .offset(20) // Skip the first 20 results * .limit(20); // Take the next 20 results * ``` @@ -314,9 +314,7 @@ export class Pipeline * @return A new Pipeline object with this stage appended to the stage list. */ offset(offset: number): Pipeline { - const copy = this.stages.map(s => s); - copy.push(new Offset(offset)); - return new Pipeline(this.db, copy, this.converter); + return this._addStage(new Offset(offset)); } /** @@ -336,8 +334,8 @@ export class Pipeline * * ```typescript * // Limit the results to the top 10 highest-rated books - * firestore.pipeline().collection("books") - * .sort(Field.of("rating").descending()) + * firestore.pipeline().collection('books') + * .sort(Field.of('rating').descending()) * .limit(10); * ``` * @@ -345,9 +343,7 @@ export class Pipeline * @return A new Pipeline object with this stage appended to the stage list. */ limit(limit: number): Pipeline { - const copy = this.stages.map(s => s); - copy.push(new Limit(limit)); - return new Pipeline(this.db, copy, this.converter); + return this._addStage(new Limit(limit)); } /** @@ -369,21 +365,19 @@ export class Pipeline * * ```typescript * // Get a list of unique author names in uppercase and genre combinations. - * firestore.pipeline().collection("books") - * .distinct(toUppercase(Field.of("author")).as("authorName"), Field.of("genre"), "publishedAt") - * .select("authorName"); + * firestore.pipeline().collection('books') + * .distinct(toUppercase(Field.of('author')).as('authorName'), Field.of('genre'), 'publishedAt') + * .select('authorName'); * ``` * - * @param selectables The {@link Selectable} expressions to consider when determining distinct + * @param groups The {@link Selectable} expressions to consider when determining distinct * value combinations or {@code string}s representing field names. * @return A new {@code Pipeline} object with this stage appended to the stage list. */ distinct( ...groups: (string | firestore.Selectable)[] ): Pipeline { - const copy = this.stages.map(s => s); - copy.push(new Distinct(this.selectablesToMap(groups || []))); - return new Pipeline(this.db, copy, this.converter); + return this._addStage(new Distinct(this.selectablesToMap(groups || []))); } /** @@ -397,10 +391,10 @@ export class Pipeline * * ```typescript * // Calculate the average rating and the total number of books - * firestore.pipeline().collection("books") + * firestore.pipeline().collection('books') * .aggregate( - * Field.of("rating").avg().as("averageRating"), - * countAll().as("totalBooks") + * Field.of('rating').avg().as('averageRating'), + * countAll().as('totalBooks') * ); * ``` * @@ -432,10 +426,10 @@ export class Pipeline * * ```typescript * // Calculate the average rating for each genre. - * firestore.pipeline().collection("books") + * firestore.pipeline().collection('books') * .aggregate({ - * accumulators: [avg(Field.of("rating")).as("avg_rating")] - * groups: ["genre"] + * accumulators: [avg(Field.of('rating')).as('avg_rating')], + * groups: ['genre'] * }); * ``` * @@ -456,9 +450,8 @@ export class Pipeline }, ...rest: firestore.AccumulatorTarget[] ): Pipeline { - const copy = this.stages.map(s => s); if ('accumulators' in optionsOrTarget) { - copy.push( + return this._addStage( new Aggregate( new Map( optionsOrTarget.accumulators.map( @@ -472,7 +465,7 @@ export class Pipeline ) ); } else { - copy.push( + return this._addStage( new Aggregate( new Map( [optionsOrTarget, ...rest].map(target => [ @@ -484,14 +477,216 @@ export class Pipeline ) ); } - return new Pipeline(this.db, copy, this.converter); } - findNearest(options: firestore.FindNearestOptions): Pipeline; findNearest(options: firestore.FindNearestOptions): Pipeline { - const copy = this.stages.map(s => s); - copy.push(new FindNearest(options)); - return new Pipeline(this.db, copy); + return this._addStage(new FindNearest(options)); + } + + /** + * Fully overwrites all fields in a document with those coming from a nested map. + * + *

    This stage allows you to emit a map value as a document. Each key of the map becomes a field + * on the document that contains the corresponding value. + * + *

    Example: + * + * ```typescript + * // Input. + * // { + * // 'name': 'John Doe Jr.', + * // 'parents': { + * // 'father': 'John Doe Sr.', + * // 'mother': 'Jane Doe' + * // } + * // } + * + * // Emit parents as document. + * firestore.pipeline().collection('people').replace(Field.of('parents')); + * + * // Output + * // { + * // 'father': 'John Doe Sr.', + * // 'mother': 'Jane Doe' + * // } + * ``` + * + * @param field The {@link Selectable} field containing the nested map. + * @return A new {@code Pipeline} object with this stage appended to the stage list. + */ + replace(field: firestore.Selectable | string): Pipeline { + return this._addStage(new Replace(selectableToExpr(field), 'full_replace')); + } + + /** + * Performs a pseudo-random sampling of the documents from the previous stage. + * + *

    This stage will filter documents pseudo-randomly. The parameter specifies how number of + * documents to be returned. + * + *

    Examples: + * + * ```typescript + * // Sample 25 books, if available. + * firestore.pipeline().collection('books') + * .sample(25); + * ``` + * + * @param documents The number of documents to sample.. + * @return A new {@code Pipeline} object with this stage appended to the stage list. + */ + sample(documents: number): Pipeline; + + /** + * Performs a pseudo-random sampling of the documents from the previous stage. + * + *

    This stage will filter documents pseudo-randomly. The 'options' parameter specifies how + * sampling will be performed. See {@code SampleOptions} for more information. + * + *

    Examples: + * + * // Sample 10 books, if available. + * firestore.pipeline().collection("books") + * .sample({ documents: 10 }); + * + * // Sample 50% of books. + * firestore.pipeline().collection("books") + * .sample({ percentage: 0.5 }); + * } + * + * + * @param options The {@code SampleOptions} specifies how sampling is performed. + * @return A new {@code Pipeline} object with this stage appended to the stage list. + */ + sample( + options: {percentage: number} | {documents: number} + ): Pipeline; + sample( + documentsOrOptions: number | {percentage: number} | {documents: number} + ): Pipeline { + if (typeof documentsOrOptions === 'number') { + return this._addStage( + new Sample({limit: documentsOrOptions, mode: 'documents'}) + ); + } else if ('percentage' in documentsOrOptions) { + return this._addStage( + new Sample({limit: documentsOrOptions.percentage, mode: 'percent'}) + ); + } else { + return this._addStage( + new Sample({limit: documentsOrOptions.documents, mode: 'documents'}) + ); + } + } + + /** + * Performs union of all documents from two pipelines, including duplicates. + * + *

    This stage will pass through documents from previous stage, and also pass through documents + * from previous stage of the `other` {@code Pipeline} given in parameter. The order of documents + * emitted from this stage is undefined. + * + *

    Example: + * + * ```typescript + * // Emit documents from books collection and magazines collection. + * firestore.pipeline().collection('books') + * .union(firestore.pipeline().collection('magazines')); + * ``` + * + * @param other The other {@code Pipeline} that is part of union. + * @return A new {@code Pipeline} object with this stage appended to the stage list. + */ + union(other: Pipeline): Pipeline { + return this._addStage(new Union(other)); + } + + /** + * Produces a document for each element in array found in previous stage document. + * + *

    For each previous stage document, this stage will emit zero or more augmented documents. The + * input array found in the previous stage document field specified by the `fieldName` parameter, + * will emit an augmented document for each input array element. The input array element will + * augment the previous stage document by setting the `alias` field with the array element value. + * + *

    When `fieldName` evaluates to a non-array value (ex: number, null, absent), then the stage becomes a no-op for + * the current input document, returning it as is with the `alias` field absent. + * + *

    No documents are emitted when `fieldName` evaluates to an empty array. + * + *

    Example: + * + * ```typescript + * // Input: + * // { "title": "The Hitchhiker's Guide to the Galaxy", "tags": [ "comedy", "space", "adventure" ], ... } + * + * // Emit a book document for each tag of the book. + * firestore.pipeline().collection("books") + * .unnest("tags"); + * + * // Output: + * // { "title": "The Hitchhiker's Guide to the Galaxy", "tag": "comedy", ... } + * // { "title": "The Hitchhiker's Guide to the Galaxy", "tag": "space", ... } + * // { "title": "The Hitchhiker's Guide to the Galaxy", "tag": "adventure", ... } + * ``` + * + * @param field The name of the field containing the array. + * @param alias The alias field is used as the field name for each element within the output array. The alias does + * not overwrite the original field unless the field names match. + * @return A new {@code Pipeline} object with this stage appended to the stage list. + */ + unnest( + field: firestore.Selectable | string, + alias: Field | string + ): Pipeline; + + /** + * Produces a document for each element in array found in previous stage document. + * + *

    For each previous stage document, this stage will emit zero or more augmented documents. The + * input array found in the previous stage document field specified by the `fieldName` parameter, + * will emit an augmented document for each input array element. The input array element will + * augment the previous stage document by setting the `alias` field with the array element value. + * + *

    When `fieldName` evaluates to a non-array value (ex: number, null, absent), then the stage becomes a no-op for + * the current input document, returning it as is with the `alias` field absent and `indexField` set to null. + * + *

    No documents are emitted when `fieldName` evaluates to an empty array. + * + *

    Example: + * + * ```typescript + * // Input: + * // { 'title': 'The Hitchhiker's Guide to the Galaxy', 'tags': [ 'comedy', 'space', 'adventure' ], ... } + * + * // Emit a book document for each tag of the book. + * firestore.pipeline().collection('books') + * .unnest({ field: 'tags', alias: 'tag', UnnestOptions.indexField('tagIndex')}); + * + * // Output: + * // { 'title': 'The Hitchhiker's Guide to the Galaxy', 'tagIndex': 0, 'tag': 'comedy', ... } + * // { 'title': 'The Hitchhiker's Guide to the Galaxy', 'tagIndex': 1, 'tag': 'space', ... } + * // { 'title': 'The Hitchhiker's Guide to the Galaxy', 'tagIndex': 2, 'tag': 'adventure', ... } + * ``` + * + * @param options The {@code UnnestOptions} options. + * @return A new {@code Pipeline} object with this stage appended to the stage list. + */ + unnest(options: UnnestOptions): Pipeline; + unnest( + fieldOrOptions: firestore.Selectable | string | UnnestOptions, + alias?: Field | string + ): Pipeline { + if (alias) { + return this._addStage( + new Unnest({ + field: fieldOrOptions, + alias: alias, + }) + ); + } else { + return this._addStage(new Unnest(fieldOrOptions)); + } } /** @@ -508,10 +703,10 @@ export class Pipeline * ```typescript * // Sort books by rating in descending order, and then by title in ascending order for books * // with the same rating - * firestore.pipeline().collection("books") + * firestore.pipeline().collection('books') * .sort( - * Field.of("rating").descending(), - * Field.of("title").ascending() + * Field.of('rating').descending(), + * Field.of('title').ascending() * ); * ``` * @@ -528,16 +723,13 @@ export class Pipeline }, ...rest: Ordering[] ): Pipeline { - const copy = this.stages.map(s => s); // Option object if ('orderings' in optionsOrOrderings) { - copy.push(new Sort(optionsOrOrderings.orderings)); + return this._addStage(new Sort(optionsOrOrderings.orderings)); } else { // Ordering object - copy.push(new Sort([optionsOrOrderings, ...rest])); + return this._addStage(new Sort([optionsOrOrderings, ...rest])); } - - return new Pipeline(this.db, copy, this.converter); } /** @@ -547,13 +739,13 @@ export class Pipeline * stages. Each generic stage is defined by a unique `name` and a set of `params` that control its * behavior. * - *

    Example (Assuming there is no "where" stage available in SDK): + *

    Example (Assuming there is no 'where' stage available in SDK): * * ```typescript - * // Assume we don't have a built-in "where" stage - * firestore.pipeline().collection("books") - * .genericStage("where", [Field.of("published").lt(1900)]) // Custom "where" stage - * .select("title", "author"); + * // Assume we don't have a built-in 'where' stage + * firestore.pipeline().collection('books') + * .genericStage('where', [Field.of('published').lt(1900)]) // Custom 'where' stage + * .select('title', 'author'); * ``` * * @param name The unique name of the generic stage to add. @@ -561,9 +753,7 @@ export class Pipeline * @return A new {@code Pipeline} object with this stage appended to the stage list. */ genericStage(name: string, params: any[]): Pipeline { - const copy = this.stages.map(s => s); - copy.push(new GenericStage(name, params)); - return new Pipeline(this.db, copy, this.converter); + return this._addStage(new GenericStage(name, params)); } withConverter(converter: null): Pipeline; @@ -654,9 +844,9 @@ export class Pipeline *

    Example: * * ```typescript - * const futureResults = await firestore.pipeline().collection("books") - * .where(gt(Field.of("rating"), 4.5)) - * .select("title", "author", "rating") + * const futureResults = await firestore.pipeline().collection('books') + * .where(gt(Field.of('rating'), 4.5)) + * .select('title', 'author', 'rating') * .execute(); * ``` * @@ -688,9 +878,9 @@ export class Pipeline * * @example * ```typescript - * firestore.pipeline().collection("books") - * .where(gt(Field.of("rating"), 4.5)) - * .select("title", "author", "rating") + * firestore.pipeline().collection('books') + * .where(gt(Field.of('rating'), 4.5)) + * .select('title', 'author', 'rating') * .stream() * .on('data', (pipelineResult) => {}) * .on('end', () => {}); @@ -705,29 +895,11 @@ export class Pipeline return util.stream(this); } - _toProto( - transactionOrReadTime?: Uint8Array | Timestamp | api.ITransactionOptions, - explainOptions?: FirebaseFirestore.ExplainOptions - ): api.IExecutePipelineRequest { + _toProto(): api.IPipeline { const stages: IStage[] = this.stages.map(stage => stage._toProto(this.db._serializer!) ); - const structuredPipeline: IStructuredPipeline = {pipeline: {stages}}; - const executePipelineRequest: api.IExecutePipelineRequest = { - database: this.db.formattedName, - structuredPipeline, - }; - - if (transactionOrReadTime instanceof Uint8Array) { - executePipelineRequest.transaction = transactionOrReadTime; - } else if (transactionOrReadTime instanceof Timestamp) { - executePipelineRequest.readTime = - transactionOrReadTime.toProto().timestampValue; - } else if (transactionOrReadTime) { - executePipelineRequest.newTransaction = transactionOrReadTime; - } - - return executePipelineRequest; + return {stages}; } } diff --git a/dev/src/serializer.ts b/dev/src/serializer.ts index a66bba1b4..0c3e69607 100644 --- a/dev/src/serializer.ts +++ b/dev/src/serializer.ts @@ -27,6 +27,7 @@ import {Timestamp} from './timestamp'; import {ApiMapValue, ValidationOptions} from './types'; import {isEmpty, isObject, isPlainObject} from './util'; import {customObjectMessage, invalidArgumentMessage} from './validate'; +import {Pipeline} from './pipeline'; import api = proto.google.firestore.v1; import { @@ -105,6 +106,22 @@ export class Serializer { * @param val The object to encode * @returns The Firestore Proto or null if we are deleting a field. */ + encodeValue(val: FieldTransform | undefined): null; + encodeValue( + val: + | string + | boolean + | number + | bigint + | Date + | null + | Buffer + | Uint8Array + | VectorValue + | Map + | Pipeline + ): api.IValue; + encodeValue(val: unknown): api.IValue | null; encodeValue(val: unknown): api.IValue | null { if (val instanceof FieldTransform) { return null; @@ -177,6 +194,12 @@ export class Serializer { return val._toProto(this); } + if (val instanceof Pipeline) { + return { + pipelineValue: val._toProto(), + }; + } + if (isObject(val)) { const toProto = val['toProto']; if (typeof toProto === 'function') { diff --git a/dev/src/stage.ts b/dev/src/stage.ts index 5be9be513..056517804 100644 --- a/dev/src/stage.ts +++ b/dev/src/stage.ts @@ -22,10 +22,13 @@ import { Field, FilterCondition, Ordering, + Selectable, } from './expression'; import {VectorValue} from './field-value'; import {DocumentReference} from './reference/document-reference'; import {Serializer} from './serializer'; +import {Pipeline} from './pipeline'; +import {selectableToExpr} from './pipeline-util'; /** * @beta @@ -196,7 +199,7 @@ export class Where implements Stage { * @beta */ export interface FindNearestOptions { - field: firestore.Field; + field: firestore.Field | string; vectorValue: firestore.VectorValue | number[]; distanceMeasure: 'euclidean' | 'cosine' | 'dot_product'; limit?: number; @@ -224,7 +227,10 @@ export class FindNearest implements Stage { return { name: this.name, args: [ - (this._options.field as unknown as Field)._toProto(serializer), + (typeof this._options.field === 'string' + ? Field.of(this._options.field) + : (this._options.field as unknown as Field) + )._toProto(serializer), this._options.vectorValue instanceof VectorValue ? serializer.encodeValue(this._options.vectorValue)! : serializer.encodeVector(this._options.vectorValue as number[]), @@ -235,6 +241,89 @@ export class FindNearest implements Stage { } } +/** + * @beta + */ +export interface SampleOptions { + limit: number; + mode: 'documents' | 'percent'; +} + +/** + * @beta + */ +export class Sample implements Stage { + name = 'sample'; + + constructor(private _options: SampleOptions) {} + + _toProto(serializer: Serializer): api.Pipeline.IStage { + return { + name: this.name, + args: [ + serializer.encodeValue(this._options.limit)!, + serializer.encodeValue(this._options.mode)!, + ], + }; + } +} + +/** + * @beta + */ +export class Union implements Stage { + name = 'union'; + + constructor(private _other: Pipeline) {} + + _toProto(serializer: Serializer): api.Pipeline.IStage { + return { + name: this.name, + args: [serializer.encodeValue(this._other)], + }; + } +} + +/** + * @beta + */ +export interface UnnestOptions { + field: firestore.Selectable | string; + alias: firestore.Field | string; + indexField?: string; +} + +/** + * @beta + */ +export class Unnest implements Stage { + name = 'unnest'; + + constructor(private options: UnnestOptions) {} + + _toProto(serializer: Serializer): api.Pipeline.IStage { + const args: api.IValue[] = [ + selectableToExpr(this.options.field)._toProto(serializer), + selectableToExpr(this.options.alias)._toProto(serializer), + ]; + const indexField = this.options?.indexField; + if (indexField) { + return { + name: this.name, + args: args, + options: { + indexField: serializer.encodeValue(indexField), + }, + }; + } else { + return { + name: this.name, + args: args, + }; + } + } +} + /** * @beta */ @@ -267,6 +356,31 @@ export class Offset implements Stage { } } +/** + * @beta + */ +export class Replace implements Stage { + name = 'replace'; + + constructor( + private field: Expr, + private mode: + | 'full_replace' + | 'merge_prefer_nest' + | 'merge_prefer_parent' = 'full_replace' + ) {} + + _toProto(serializer: Serializer): api.Pipeline.IStage { + return { + name: this.name, + args: [ + serializer.encodeValue(this.field)!, + serializer.encodeValue(this.mode), + ], + }; + } +} + /** * @beta */ diff --git a/dev/system-test/pipeline.ts b/dev/system-test/pipeline.ts index 317c4e839..852b7d3e6 100644 --- a/dev/system-test/pipeline.ts +++ b/dev/system-test/pipeline.ts @@ -62,9 +62,9 @@ import { } from '../src/expression'; import {PipelineResult} from '../src/pipeline'; import {verifyInstance} from '../test/util/helpers'; -import {DeferredPromise, getTestRoot} from './firestore'; +import {getTestRoot} from './firestore'; -describe.only('Pipeline class', () => { +describe('Pipeline class', () => { let firestore: Firestore; let randomCol: CollectionReference; @@ -104,8 +104,6 @@ describe.only('Pipeline class', () => { result: PipelineResult[], ...data: DocumentData[] | string[] ): void { - expect(result.length).to.equal(data.length); - if (data.length > 0) { if (typeof data[0] === 'string') { const actualIds = result.map(result => result.ref?.id); @@ -115,6 +113,8 @@ describe.only('Pipeline class', () => { expect(r.data()).to.deep.equal(data.shift()); }); } + } else { + expect(result.length).to.equal(data.length); } } @@ -131,7 +131,7 @@ describe.only('Pipeline class', () => { async function setupBookDocs(): Promise> { const bookDocs: {[id: string]: DocumentData} = { - book1: { + book01: { title: "The Hitchhiker's Guide to the Galaxy", author: 'Douglas Adams', genre: 'Science Fiction', @@ -141,7 +141,7 @@ describe.only('Pipeline class', () => { awards: {hugo: true, nebula: false, others: {unknown: {year: 1980}}}, nestedField: {'level.1': {'level.2': true}}, }, - book2: { + book02: { title: 'Pride and Prejudice', author: 'Jane Austen', genre: 'Romance', @@ -150,7 +150,7 @@ describe.only('Pipeline class', () => { tags: ['classic', 'social commentary', 'love'], awards: {none: true}, }, - book3: { + book03: { title: 'One Hundred Years of Solitude', author: 'Gabriel García Márquez', genre: 'Magical Realism', @@ -159,7 +159,7 @@ describe.only('Pipeline class', () => { tags: ['family', 'history', 'fantasy'], awards: {nobel: true, nebula: false}, }, - book4: { + book04: { title: 'The Lord of the Rings', author: 'J.R.R. Tolkien', genre: 'Fantasy', @@ -168,7 +168,7 @@ describe.only('Pipeline class', () => { tags: ['adventure', 'magic', 'epic'], awards: {hugo: false, nebula: false}, }, - book5: { + book05: { title: "The Handmaid's Tale", author: 'Margaret Atwood', genre: 'Dystopian', @@ -177,7 +177,7 @@ describe.only('Pipeline class', () => { tags: ['feminism', 'totalitarianism', 'resistance'], awards: {'arthur c. clarke': true, 'booker prize': false}, }, - book6: { + book06: { title: 'Crime and Punishment', author: 'Fyodor Dostoevsky', genre: 'Psychological Thriller', @@ -186,7 +186,7 @@ describe.only('Pipeline class', () => { tags: ['philosophy', 'crime', 'redemption'], awards: {none: true}, }, - book7: { + book07: { title: 'To Kill a Mockingbird', author: 'Harper Lee', genre: 'Southern Gothic', @@ -195,7 +195,7 @@ describe.only('Pipeline class', () => { tags: ['racism', 'injustice', 'coming-of-age'], awards: {pulitzer: true}, }, - book8: { + book08: { title: '1984', author: 'George Orwell', genre: 'Dystopian', @@ -204,7 +204,7 @@ describe.only('Pipeline class', () => { tags: ['surveillance', 'totalitarianism', 'propaganda'], awards: {prometheus: true}, }, - book9: { + book09: { title: 'The Great Gatsby', author: 'F. Scott Fitzgerald', genre: 'Modernist', @@ -730,7 +730,7 @@ describe.only('Pipeline class', () => { it('testQueryByDocumentReference', async () => { const results = await randomCol .pipeline() - .where(eq(Field.of(FieldPath.documentId()), randomCol.doc('book1'))) + .where(eq(Field.of(FieldPath.documentId()), randomCol.doc('book01'))) .select('title') .execute(); expectResults(results, {title: "The Hitchhiker's Guide to the Galaxy"}); @@ -962,7 +962,7 @@ describe.only('Pipeline class', () => { {title: 'Dune', 'awards.hugo': true} ); - transaction.update(randomCol.doc('book1'), {foo: 'bar'}); + transaction.update(randomCol.doc('book01'), {foo: 'bar'}); }); const result = await randomCol @@ -972,4 +972,117 @@ describe.only('Pipeline class', () => { .execute(); expectResults(result, {title: "The Hitchhiker's Guide to the Galaxy"}); }); + + it('run pipleine with replace', async () => { + const results = await randomCol + .pipeline() + .where(eq('title', "The Hitchhiker's Guide to the Galaxy")) + .replace('awards') + .execute(); + expectResults(results, { + title: "The Hitchhiker's Guide to the Galaxy", + author: 'Douglas Adams', + genre: 'Science Fiction', + published: 1979, + rating: 4.2, + tags: ['comedy', 'space', 'adventure'], + hugo: true, + nebula: false, + others: {unknown: {year: 1980}}, + nestedField: {'level.1': {'level.2': true}}, + }); + }); + + it('run pipeline with sample limit of 3', async () => { + const results = await randomCol.pipeline().sample(3).execute(); + expect(results.length).to.equal(3); + }); + + it('run pipeline with sample limit of {documents: 3}', async () => { + const results = await randomCol.pipeline().sample({documents: 3}).execute(); + expect(results.length).to.equal(3); + }); + + it('run pipeline with sample limit of {percentage: 0.6}', async () => { + const results = await randomCol + .pipeline() + .sample({percentage: 0.6}) + .execute(); + expect(results.length).to.equal(6); + }); + + it('run pipeline with union', async () => { + const results = await randomCol + .pipeline() + .union(randomCol.pipeline()) + .sort(Field.of(FieldPath.documentId()).ascending()) + .execute(); + expectResults( + results, + 'book01', + 'book01', + 'book02', + 'book02', + 'book03', + 'book03', + 'book04', + 'book04', + 'book05', + 'book05', + 'book06', + 'book06', + 'book07', + 'book07', + 'book08', + 'book08', + 'book09', + 'book09', + 'book10', + 'book10' + ); + }); + + it('run pipeline with unnest', async () => { + const results = await randomCol + .pipeline() + .where(eq('title', "The Hitchhiker's Guide to the Galaxy")) + .unnest('tags', 'tag') + .execute(); + expectResults( + results, + { + title: "The Hitchhiker's Guide to the Galaxy", + author: 'Douglas Adams', + genre: 'Science Fiction', + published: 1979, + rating: 4.2, + tags: ['comedy', 'space', 'adventure'], + tag: 'comedy', + awards: {hugo: true, nebula: false, others: {unknown: {year: 1980}}}, + nestedField: {'level.1': {'level.2': true}}, + }, + { + title: "The Hitchhiker's Guide to the Galaxy", + author: 'Douglas Adams', + genre: 'Science Fiction', + published: 1979, + rating: 4.2, + tags: ['comedy', 'space', 'adventure'], + tag: 'space', + awards: {hugo: true, nebula: false, others: {unknown: {year: 1980}}}, + nestedField: {'level.1': {'level.2': true}}, + }, + { + title: "The Hitchhiker's Guide to the Galaxy", + author: 'Douglas Adams', + genre: 'Science Fiction', + published: 1979, + rating: 4.2, + tags: ['comedy', 'space', 'adventure'], + tag: 'adventure', + awards: {hugo: true, nebula: false, others: {unknown: {year: 1980}}}, + nestedField: {'level.1': {'level.2': true}}, + } + ); + }); }); diff --git a/dev/system-test/query.ts b/dev/system-test/query.ts index 84853f79b..e7d800382 100644 --- a/dev/system-test/query.ts +++ b/dev/system-test/query.ts @@ -1803,8 +1803,8 @@ describe('Query class', () => { }); (process.env.FIRESTORE_EMULATOR_HOST === undefined - ? describe - : describe.only)('multiple inequality', () => { + ? describe.skip + : describe)('multiple inequality', () => { it('supports multiple inequality queries', async () => { const collection = await testCollectionWithDocs({ doc1: {key: 'a', sort: 0, v: 0}, diff --git a/types/firestore.d.ts b/types/firestore.d.ts index d6a566b41..60c38588c 100644 --- a/types/firestore.d.ts +++ b/types/firestore.d.ts @@ -4769,22 +4769,6 @@ declare namespace FirebaseFirestore { fieldName(): string; } - /** - * @beta - */ - export class Fields extends Expr implements Selectable { - exprType: ExprType; - selectable: true; - static of(name: string, ...others: string[]): Fields; - static ofAll(): Fields; - /** - * Returns the list of fields. - * - * @return The list of fields. - */ - fieldList(): Field[]; - } - /** * @beta * @@ -8875,7 +8859,7 @@ declare namespace FirebaseFirestore { * @beta */ export interface FindNearestOptions { - field: Field; + field: Field | string; vectorValue: VectorValue | number[]; distanceMeasure: 'euclidean' | 'cosine' | 'dot_product'; limit?: number; @@ -8903,6 +8887,28 @@ declare namespace FirebaseFirestore { name: string; } + /** + * @beta + */ + export class Replace implements Stage { + name: string; + } + + /** + * @beta + */ + export class Sample implements Stage { + name: string; + } + + /** + * @beta + */ + export interface SampleOptions { + limit: number; + mode: 'documents' | 'percent'; + } + /** * @beta */ @@ -8917,6 +8923,29 @@ declare namespace FirebaseFirestore { name: string; } + /** + * @beta + */ + export class Union implements Stage { + name: string; + } + + /** + * @beta + */ + export class Unnest implements Stage { + name: string; + } + + /** + * @beta + */ + export interface UnnestOptions { + field: Selectable | string; + alias: Field | string; + indexField?: string; + } + /** * @beta */ @@ -9258,6 +9287,84 @@ declare namespace FirebaseFirestore { findNearest(options: FindNearestOptions): Pipeline; + /** + * Fully overwrites all fields in a document with those coming from a nested map. + * + *

    This stage allows you to emit a map value as a document. Each key of the map becomes a field + * on the document that contains the corresponding value. + * + *

    Example: + * + * ```typescript + * // Input. + * // { + * // "name": "John Doe Jr.", + * // "parents": { + * // "father": "John Doe Sr.", + * // "mother": "Jane Doe" + * // } + * + * // Emit parents as document. + * firestore.pipeline().collection("people").replace(Field.of("parents")); + * + * // Output + * // { + * // "father": "John Doe Sr.", + * // "mother": "Jane Doe" + * // } + * ``` + * + * @param field The {@link Selectable} field containing the nested map. + * @return A new {@code Pipeline} object with this stage appended to the stage list. + */ + replace(field: Selectable | string): Pipeline; + + /** + * Performs a pseudo-random sampling of the documents from the previous stage. + * + *

    This stage will filter documents pseudo-randomly. The parameter specifies how number of + * documents to be returned. + * + *

    Examples: + * + * ```typescript + * // Sample 25 books, if available. + * firestore.pipeline().collection("books") + * .sample(25); + * } + * ``` + * + * @param documents The number of documents to sample. + * @return A new {@code Pipeline} object with this stage appended to the stage list. + */ + sample(documents: number): Pipeline; + + /** + * Performs a pseudo-random sampling of the documents from the previous stage. + * + *

    This stage will filter documents pseudo-randomly. The 'options' parameter specifies how + * sampling will be performed. See {@code SampleOptions} for more information. + * + *

    Examples: + * + * ```typescript + * // Sample 10 books, if available. + * firestore.pipeline().collection("books") + * .sample({ documents: 10 }); + * + * // Sample 50% of books. + * firestore.pipeline().collection("books") + * .sample({ percentage: 0.5 }); + * } + * ``` + * + * @param options The {@code SampleOptions} specifies how sampling is performed. + * @return A new {@code Pipeline} object with this stage appended to the stage list. + */ + sample( + options: {percentage: number} | {documents: number} + ): Pipeline; + /** * Sorts the documents from previous stages based on one or more {@link Ordering} criteria. * @@ -9285,6 +9392,97 @@ declare namespace FirebaseFirestore { sort(...orderings: Ordering[]): Pipeline; sort(options: {orderings: Ordering[]}): Pipeline; + /** + * Performs union of all documents from two pipelines, including duplicates. + * + *

    This stage will pass through documents from previous stage, and also pass through documents + * from previous stage of the `other` {@code Pipeline} given in parameter. The order of documents + * emitted from this stage is undefined. + * + *

    Example: + * + * ```typescript + * // Emit documents from books collection and magazines collection. + * firestore.pipeline().collection("books") + * .union(firestore.pipeline().collection("magazines")); + * } + * ``` + * + * @param other The other {@code Pipeline} that is part of union. + * @return A new {@code Pipeline} object with this stage appended to the stage list. + */ + union(other: Pipeline): Pipeline; + + /** + * Produces a document for each element in array found in previous stage document. + * + *

    For each previous stage document, this stage will emit zero or more augmented documents. The + * input array found in the previous stage document field specified by the `fieldName` parameter, + * will emit an augmented document for each input array element. The input array element will + * augment the previous stage document by setting the `alias` field with the array element value. + * + *

    When `fieldName` evaluates to a non-array value (ex: number, null, absent), then the stage becomes a no-op for + * the current input document, returning it as is with the `alias` field absent. + * + *

    No documents are emitted when `fieldName` evaluates to an empty array. + * + *

    Example: + * + * ```typescript + * // Input: + * // { "title": "The Hitchhiker's Guide to the Galaxy", "tags": [ "comedy", "space", "adventure" ], ... } + * + * // Emit a book document for each tag of the book. + * firestore.pipeline().collection("books") + * .unnest("tags"); + * + * // Output: + * // { "title": "The Hitchhiker's Guide to the Galaxy", "tag": "comedy", ... } + * // { "title": "The Hitchhiker's Guide to the Galaxy", "tag": "space", ... } + * // { "title": "The Hitchhiker's Guide to the Galaxy", "tag": "adventure", ... } + * ``` + * + * @param field The name of the field containing the array. + * @param alias The alias field is used as the field name for each element within the output array. The alias does + * not overwrite the original field unless the field names match. + * @return A new {@code Pipeline} object with this stage appended to the stage list. + */ + unnest(field: Selectable | string, alias: string): Pipeline; + + /** + * Produces a document for each element in array found in previous stage document. + * + *

    For each previous stage document, this stage will emit zero or more augmented documents. The + * input array found in the previous stage document field specified by the `fieldName` parameter, + * will emit an augmented document for each input array element. The input array element will + * augment the previous stage document by setting the `alias` field with the array element value. + * + *

    When `fieldName` evaluates to a non-array value (ex: number, null, absent), then the stage becomes a no-op for + * the current input document, returning it as is with the `alias` field absent and `indexField` set to null. + * + *

    No documents are emitted when `fieldName` evaluates to an empty array. + * + *

    Example: + * + * ```typescript + * // Input: + * // { 'title': 'The Hitchhiker's Guide to the Galaxy', 'tags': [ 'comedy', 'space', 'adventure' ], ... } + * + * // Emit a book document for each tag of the book. + * firestore.pipeline().collection('books') + * .unnest({ field: 'tags', alias: 'tag', UnnestOptions.indexField('tagIndex')}); + * + * // Output: + * // { 'title': 'The Hitchhiker's Guide to the Galaxy', 'tagIndex': 0, 'tag': 'comedy', ... } + * // { 'title': 'The Hitchhiker's Guide to the Galaxy', 'tagIndex': 1, 'tag': 'space', ... } + * // { 'title': 'The Hitchhiker's Guide to the Galaxy', 'tagIndex': 2, 'tag': 'adventure', ... } + * ``` + * + * @param options The {@code UnnestOptions} options. + * @return A new {@code Pipeline} object with this stage appended to the stage list. + */ + unnest(options: UnnestOptions): Pipeline; + /** * Adds a generic stage to the pipeline. * From 7511ff9e3b7de23e2f03d26886ce96de5132ea7d Mon Sep 17 00:00:00 2001 From: Owl Bot Date: Fri, 17 Jan 2025 01:45:35 +0000 Subject: [PATCH 34/60] =?UTF-8?q?=F0=9F=A6=89=20Updates=20from=20OwlBot=20?= =?UTF-8?q?post-processor?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit See https://github.com/googleapis/repo-automation-bots/blob/main/packages/owl-bot/README.md --- CODE_OF_CONDUCT.md | 2 +- types/firestore.d.ts | 12 ++++++------ 2 files changed, 7 insertions(+), 7 deletions(-) diff --git a/CODE_OF_CONDUCT.md b/CODE_OF_CONDUCT.md index a044123a3..2add2547a 100644 --- a/CODE_OF_CONDUCT.md +++ b/CODE_OF_CONDUCT.md @@ -91,4 +91,4 @@ harassment or threats to anyone's safety, we may take action without notice. This Code of Conduct is adapted from the Contributor Covenant, version 1.4, available at -https://www.contributor-covenant.org/version/1/4/code-of-conduct.html +https://www.contributor-covenant.org/version/1/4/code-of-conduct.html \ No newline at end of file diff --git a/types/firestore.d.ts b/types/firestore.d.ts index 60c38588c..35a98175f 100644 --- a/types/firestore.d.ts +++ b/types/firestore.d.ts @@ -40,8 +40,8 @@ declare namespace FirebaseFirestore { | (T extends Primitive ? T : T extends {} - ? {[K in keyof T]?: PartialWithFieldValue | FieldValue} - : never); + ? {[K in keyof T]?: PartialWithFieldValue | FieldValue} + : never); /** * Allows FieldValues to be passed in as a property value while maintaining @@ -52,8 +52,8 @@ declare namespace FirebaseFirestore { | (T extends Primitive ? T : T extends {} - ? {[K in keyof T]: WithFieldValue | FieldValue} - : never); + ? {[K in keyof T]: WithFieldValue | FieldValue} + : never); /** * Update data (for use with [update]{@link DocumentReference#update}) @@ -72,8 +72,8 @@ declare namespace FirebaseFirestore { export type UpdateData = T extends Primitive ? T : T extends {} - ? {[K in keyof T]?: UpdateData | FieldValue} & NestedUpdateFields - : Partial; + ? {[K in keyof T]?: UpdateData | FieldValue} & NestedUpdateFields + : Partial; /** Primitive types. */ export type Primitive = string | number | boolean | undefined | null; From db0c60fbef4d2568015bd4a80e50bd1a5dfa4754 Mon Sep 17 00:00:00 2001 From: Mark Duckworth <1124037+MarkDuckworth@users.noreply.github.com> Date: Thu, 17 Apr 2025 15:57:10 -0600 Subject: [PATCH 35/60] Building --- dev/src/collection-group.ts | 6 +- dev/src/expression.ts | 6339 +++++++++++---------- dev/src/index.ts | 144 +- dev/src/pipeline-util.ts | 83 +- dev/src/pipeline.ts | 642 +-- dev/src/reference/aggregate-query.ts | 26 +- dev/src/reference/collection-reference.ts | 4 +- dev/src/reference/document-reference.ts | 6 +- dev/src/reference/query.ts | 27 +- dev/src/reference/types.ts | 11 +- dev/src/reference/vector-query.ts | 6 +- dev/src/serializer.ts | 2 +- dev/src/stage.ts | 28 +- dev/src/transaction.ts | 30 +- dev/src/types.ts | 19 - dev/src/util.ts | 13 + dev/system-test/firestore.ts | 9 +- dev/system-test/pipeline.ts | 3401 ++++++++--- dev/system-test/query.ts | 4 +- dev/test/util/helpers.ts | 7 + types/firestore.d.ts | 4856 ++++++++-------- 21 files changed, 8851 insertions(+), 6812 deletions(-) diff --git a/dev/src/collection-group.ts b/dev/src/collection-group.ts index 92ca05879..10e9ac3a0 100644 --- a/dev/src/collection-group.ts +++ b/dev/src/collection-group.ts @@ -201,12 +201,14 @@ export class CollectionGroup< * @return {CollectionGroup} A `CollectionGroup` that uses the provided * converter. */ - withConverter(converter: null): CollectionGroup; withConverter< NewAppModelType, NewDbModelType extends firestore.DocumentData = firestore.DocumentData, >( - converter: firestore.FirestoreDataConverter + converter: firestore.FirestoreDataConverter< + NewAppModelType, + NewDbModelType + > | null ): CollectionGroup; withConverter< NewAppModelType, diff --git a/dev/src/expression.ts b/dev/src/expression.ts index c0f87daf5..385a60af8 100644 --- a/dev/src/expression.ts +++ b/dev/src/expression.ts @@ -22,66 +22,84 @@ import {FieldPath} from './path'; import {Pipeline} from './pipeline'; import {isFirestoreValue} from './pipeline-util'; import {Serializer} from './serializer'; +import {cast} from './util'; -/** - * @beta - * - * An interface that represents a selectable expression. - */ -export interface Selectable { - selectable: true; -} - -/** - * @beta - * - * An interface that represents a filter condition. - */ -export interface FilterCondition { - filterable: true; +function isPlainObject(...args: unknown[]): boolean { + throw 'TODO implement isPlainObject'; } - -/** - * @beta - * - * An interface that represents an accumulator. - */ -export interface Accumulator { - accumulator: true; +function isString(val: unknown): val is string { + throw 'TODO implement isString'; } /** - * @beta + * Converts a value to an Expr, Returning either a Constant, MapFunction, + * ArrayFunction, or the input itself (if it's already an expression). * - * An accumulator target, which is an expression with an alias that also implements the Accumulator interface. + * @private + * @internal + * @param value */ -export type AccumulatorTarget = ExprWithAlias; +function valueToDefaultExpr(value: unknown): Expr { + let result: Expr | undefined; + if (value instanceof Expr) { + return value; + } + if (value instanceof firestore.Expr) { + throw new Error('Unsupported Expr type: ' + typeof value); + } else if (isPlainObject(value)) { + result = map(value as Record); + } else if (value instanceof Array) { + result = array(value); + } else { + result = new Constant(value); + } -/** - * @beta - * - * A filter expression, which is an expression that also implements the FilterCondition interface. - */ -export type FilterExpr = Expr & FilterCondition; + // TODO(pipeline) is this still used? + result._createdFromLiteral = true; + return result; +} /** - * @beta + * Converts a value to an Expr, Returning either a Constant, MapFunction, + * ArrayFunction, or the input itself (if it's already an expression). * - * A selectable expression, which is an expression that also implements the Selectable interface. + * @private + * @internal + * @param value */ -export type SelectableExpr = Expr & Selectable; +function vectorToExpr( + value: firestore.VectorValue | number[] | firestore.Expr +): Expr { + if (value instanceof Expr) { + return value; + } else if (value instanceof VectorValue || Array.isArray(value)) { + const result = constantVector(value); + result._createdFromLiteral = true; + return result; + } else { + throw new Error('Unsupported value: ' + typeof value); + } +} /** - * @beta + * Converts a value to an Expr, 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. * - * An enumeration of the different types of expressions. + * @private + * @internal + * @param value */ -export type ExprType = - | 'Field' - | 'Constant' - | 'Function' - | 'ListOfExprs' - | 'ExprWithAlias'; +export function fieldOrExpression(value: unknown): Expr { + if (isString(value)) { + const result = field(value); + result._createdFromLiteral = true; + return result; + } else { + return valueToDefaultExpr(value); + } +} /** * @beta @@ -95,42 +113,49 @@ export type ExprType = * - **Field references:** Access values from document fields. * - **Literals:** Represent constant values (strings, numbers, booleans). * - **Function calls:** Apply functions to one or more expressions. - * - **Aggregations:** Calculate aggregate values (e.g., sum, average) over a set of documents. * * The `Expr` class provides a fluent API for building expressions. You can chain together * method calls to create complex expressions. */ -export abstract class Expr implements firestore.Expr { +export abstract class Expr extends firestore.Expr { + abstract readonly exprType: firestore.ExprType; + /** - * Creates an expression that adds this expression to another expression. - * - * ```typescript - * // Add the value of the 'quantity' field and the 'reserve' field. - * Field.of("quantity").add(Field.of("reserve")); - * ``` - * - * @param other The expression to add to this expression. - * @return A new `Expr` representing the addition operation. + * @internal + * @private + * Indicates if this expression was created from a literal value passed + * by the caller. + */ + _createdFromLiteral = false; + + /** + * @private + * @internal */ - add(other: firestore.Expr): Add; + abstract _toProto(serializer: Serializer): api.IValue; + _protoValueType = 'ProtoValue' as const; /** - * Creates an expression that adds this expression to a constant value. + * Creates an expression that adds this expression to another expression. * * ```typescript - * // Add 5 to the value of the 'age' field - * Field.of("age").add(5); + * // Add the value of the 'quantity' field and the 'reserve' field. + * field("quantity").add(field("reserve")); * ``` * - * @param other The constant value to add. + * @param second The expression or literal to add to this expression. + * @param others Optional additional expressions or literals to add to this expression. * @return A new `Expr` representing the addition operation. */ - add(other: any): Add; - add(other: any): Add { - if (other instanceof Expr) { - return new Add(this, other); - } - return new Add(this, Constant.of(other)); + add( + second: firestore.Expr | unknown, + ...others: Array + ): FunctionExpr { + const values = [second, ...others]; + return new FunctionExpr('add', [ + this, + ...values.map(value => valueToDefaultExpr(value)), + ]); } /** @@ -138,31 +163,28 @@ export abstract class Expr implements firestore.Expr { * * ```typescript * // Subtract the 'discount' field from the 'price' field - * Field.of("price").subtract(Field.of("discount")); + * field("price").subtract(field("discount")); * ``` * * @param other The expression to subtract from this expression. * @return A new `Expr` representing the subtraction operation. */ - subtract(other: firestore.Expr): Subtract; + subtract(other: firestore.Expr): FunctionExpr; /** * Creates an expression that subtracts a constant value from this expression. * * ```typescript * // Subtract 20 from the value of the 'total' field - * Field.of("total").subtract(20); + * field("total").subtract(20); * ``` * * @param other The constant value to subtract. * @return A new `Expr` representing the subtraction operation. */ - subtract(other: any): Subtract; - subtract(other: any): Subtract { - if (other instanceof Expr) { - return new Subtract(this, other); - } - return new Subtract(this, Constant.of(other)); + subtract(other: number): FunctionExpr; + subtract(other: number | firestore.Expr): FunctionExpr { + return new FunctionExpr('subtract', [this, valueToDefaultExpr(other)]); } /** @@ -170,31 +192,22 @@ export abstract class Expr implements firestore.Expr { * * ```typescript * // Multiply the 'quantity' field by the 'price' field - * Field.of("quantity").multiply(Field.of("price")); - * ``` - * - * @param other The expression to multiply by. - * @return A new `Expr` representing the multiplication operation. - */ - multiply(other: firestore.Expr): Multiply; - - /** - * Creates an expression that multiplies this expression by a constant value. - * - * ```typescript - * // Multiply the 'value' field by 2 - * Field.of("value").multiply(2); + * field("quantity").multiply(field("price")); * ``` * - * @param other The constant value to multiply by. + * @param second The second expression or literal to multiply by. + * @param others Optional additional expressions or literals to multiply by. * @return A new `Expr` representing the multiplication operation. */ - multiply(other: any): Multiply; - multiply(other: any): Multiply { - if (other instanceof Expr) { - return new Multiply(this, other); - } - return new Multiply(this, Constant.of(other)); + multiply( + second: firestore.Expr | number, + ...others: Array + ): FunctionExpr { + return new FunctionExpr('multiply', [ + this, + valueToDefaultExpr(second), + ...others.map(value => valueToDefaultExpr(value)), + ]); } /** @@ -202,31 +215,28 @@ export abstract class Expr implements firestore.Expr { * * ```typescript * // Divide the 'total' field by the 'count' field - * Field.of("total").divide(Field.of("count")); + * field("total").divide(field("count")); * ``` * * @param other The expression to divide by. * @return A new `Expr` representing the division operation. */ - divide(other: firestore.Expr): Divide; + divide(other: firestore.Expr): FunctionExpr; /** * Creates an expression that divides this expression by a constant value. * * ```typescript * // Divide the 'value' field by 10 - * Field.of("value").divide(10); + * field("value").divide(10); * ``` * * @param other The constant value to divide by. * @return A new `Expr` representing the division operation. */ - divide(other: any): Divide; - divide(other: any): Divide { - if (other instanceof Expr) { - return new Divide(this, other); - } - return new Divide(this, Constant.of(other)); + divide(other: number): FunctionExpr; + divide(other: number | firestore.Expr): FunctionExpr { + return new FunctionExpr('divide', [this, valueToDefaultExpr(other)]); } /** @@ -234,237 +244,57 @@ export abstract class Expr implements firestore.Expr { * * ```typescript * // Calculate the remainder of dividing the 'value' field by the 'divisor' field - * Field.of("value").mod(Field.of("divisor")); + * field("value").mod(field("divisor")); * ``` * - * @param other The expression to divide by. + * @param expression The expression to divide by. * @return A new `Expr` representing the modulo operation. */ - mod(other: firestore.Expr): Mod; + mod(expression: firestore.Expr): FunctionExpr; /** * Creates an expression that calculates the modulo (remainder) of dividing this expression by a constant value. * * ```typescript * // Calculate the remainder of dividing the 'value' field by 10 - * Field.of("value").mod(10); + * field("value").mod(10); * ``` * - * @param other The constant value to divide by. + * @param value The constant value to divide by. * @return A new `Expr` representing the modulo operation. */ - mod(other: any): Mod; - mod(other: any): Mod { - if (other instanceof Expr) { - return new Mod(this, other); - } - return new Mod(this, Constant.of(other)); + mod(value: number): FunctionExpr; + mod(other: number | firestore.Expr): FunctionExpr { + return new FunctionExpr('mod', [this, valueToDefaultExpr(other)]); } - // /** - // * Creates an expression that applies a bitwise AND operation between this expression and another expression. - // * - // * ```typescript - // * // Calculate the bitwise AND of 'field1' and 'field2'. - // * Field.of("field1").bitAnd(Field.of("field2")); - // * ``` - // * - // * @param other The right operand expression. - // * @return A new {@code Expr} representing the bitwise AND operation. - // */ - // bitAnd(other: firestore.Expr): BitAnd; - // - // /** - // * Creates an expression that applies a bitwise AND operation between this expression and a constant value. - // * - // * ```typescript - // * // Calculate the bitwise AND of 'field1' and 0xFF. - // * Field.of("field1").bitAnd(0xFF); - // * ``` - // * - // * @param other The right operand constant. - // * @return A new {@code Expr} representing the bitwise AND operation. - // */ - // bitAnd(other: any): BitAnd; - // bitAnd(other: any): BitAnd { - // if (other instanceof Expr) { - // return new BitAnd(this, other); - // } - // return new BitAnd(this, Constant.of(other)); - // } - // - // /** - // * Creates an expression that applies a bitwise OR operation between this expression and another expression. - // * - // * ```typescript - // * // Calculate the bitwise OR of 'field1' and 'field2'. - // * Field.of("field1").bitOr(Field.of("field2")); - // * ``` - // * - // * @param other The right operand expression. - // * @return A new {@code Expr} representing the bitwise OR operation. - // */ - // bitOr(other: firestore.Expr): BitOr; - // - // /** - // * Creates an expression that applies a bitwise OR operation between this expression and a constant value. - // * - // * ```typescript - // * // Calculate the bitwise OR of 'field1' and 0xFF. - // * Field.of("field1").bitOr(0xFF); - // * ``` - // * - // * @param other The right operand constant. - // * @return A new {@code Expr} representing the bitwise OR operation. - // */ - // bitOr(other: any): BitOr; - // bitOr(other: any): BitOr { - // if (other instanceof Expr) { - // return new BitOr(this, other); - // } - // return new BitOr(this, Constant.of(other)); - // } - // - // /** - // * Creates an expression that applies a bitwise XOR operation between this expression and another expression. - // * - // * ```typescript - // * // Calculate the bitwise XOR of 'field1' and 'field2'. - // * Field.of("field1").bitXor(Field.of("field2")); - // * ``` - // * - // * @param other The right operand expression. - // * @return A new {@code Expr} representing the bitwise XOR operation. - // */ - // bitXor(other: firestore.Expr): BitXor; - // - // /** - // * Creates an expression that applies a bitwise XOR operation between this expression and a constant value. - // * - // * ```typescript - // * // Calculate the bitwise XOR of 'field1' and 0xFF. - // * Field.of("field1").bitXor(0xFF); - // * ``` - // * - // * @param other The right operand constant. - // * @return A new {@code Expr} representing the bitwise XOR operation. - // */ - // bitXor(other: any): BitXor; - // bitXor(other: any): BitXor { - // if (other instanceof Expr) { - // return new BitXor(this, other); - // } - // return new BitXor(this, Constant.of(other)); - // } - // - // /** - // * Creates an expression that applies a bitwise NOT operation to this expression. - // * - // * ```typescript - // * // Calculate the bitwise NOT of 'field1'. - // * Field.of("field1").bitNot(); - // * ``` - // * - // * @return A new {@code Expr} representing the bitwise NOT operation. - // */ - // bitNot(): BitNot { - // return new BitNot(this); - // } - // - // /** - // * Creates an expression that applies a bitwise left shift operation between this expression and another expression. - // * - // * ```typescript - // * // Calculate the bitwise left shift of 'field1' by 'field2' bits. - // * Field.of("field1").bitLeftShift(Field.of("field2")); - // * ``` - // * - // * @param other The right operand expression representing the number of bits to shift. - // * @return A new {@code Expr} representing the bitwise left shift operation. - // */ - // bitLeftShift(other: firestore.Expr): BitLeftShift; - // - // /** - // * Creates an expression that applies a bitwise left shift operation between this expression and a constant value. - // * - // * ```typescript - // * // Calculate the bitwise left shift of 'field1' by 2 bits. - // * Field.of("field1").bitLeftShift(2); - // * ``` - // * - // * @param other The right operand constant representing the number of bits to shift. - // * @return A new {@code Expr} representing the bitwise left shift operation. - // */ - // bitLeftShift(other: number): BitLeftShift; - // bitLeftShift(other: firestore.Expr | number): BitLeftShift { - // if (typeof other === 'number') { - // return new BitLeftShift(this, Constant.of(other)); - // } - // return new BitLeftShift(this, other as Expr); - // } - // - // /** - // * Creates an expression that applies a bitwise right shift operation between this expression and another expression. - // * - // * ```typescript - // * // Calculate the bitwise right shift of 'field1' by 'field2' bits. - // * Field.of("field1").bitRightShift(Field.of("field2")); - // * ``` - // * - // * @param other The right operand expression representing the number of bits to shift. - // * @return A new {@code Expr} representing the bitwise right shift operation. - // */ - // bitRightShift(other: firestore.Expr): BitRightShift; - // - // /** - // * Creates an expression that applies a bitwise right shift operation between this expression and a constant value. - // * - // * ```typescript - // * // Calculate the bitwise right shift of 'field1' by 2 bits. - // * Field.of("field1").bitRightShift(2); - // * ``` - // * - // * @param other The right operand constant representing the number of bits to shift. - // * @return A new {@code Expr} representing the bitwise right shift operation. - // */ - // bitRightShift(other: number): BitRightShift; - // bitRightShift(other: firestore.Expr | number): BitRightShift { - // if (typeof other === 'number') { - // return new BitRightShift(this, Constant.of(other)); - // } - // return new BitRightShift(this, other as Expr); - // } - /** * Creates an expression that checks if this expression is equal to another expression. * * ```typescript * // Check if the 'age' field is equal to 21 - * Field.of("age").eq(21); + * field("age").eq(21); * ``` * - * @param other The expression to compare for equality. + * @param expression The expression to compare for equality. * @return A new `Expr` representing the equality comparison. */ - eq(other: firestore.Expr): Eq; + eq(expression: firestore.Expr): BooleanExpr; /** * Creates an expression that checks if this expression is equal to a constant value. * * ```typescript * // Check if the 'city' field is equal to "London" - * Field.of("city").eq("London"); + * field("city").eq("London"); * ``` * - * @param other The constant value to compare for equality. + * @param value The constant value to compare for equality. * @return A new `Expr` representing the equality comparison. */ - eq(other: any): Eq; - eq(other: any): Eq { - if (other instanceof Expr) { - return new Eq(this, other); - } - return new Eq(this, Constant.of(other)); + eq(value: unknown): BooleanExpr; + eq(other: unknown): BooleanExpr { + return new BooleanExpr('eq', [this, valueToDefaultExpr(other)]); } /** @@ -472,31 +302,28 @@ export abstract class Expr implements firestore.Expr { * * ```typescript * // Check if the 'status' field is not equal to "completed" - * Field.of("status").neq("completed"); + * field("status").neq("completed"); * ``` * - * @param other The expression to compare for inequality. + * @param expression The expression to compare for inequality. * @return A new `Expr` representing the inequality comparison. */ - neq(other: firestore.Expr): Neq; + neq(expression: firestore.Expr): BooleanExpr; /** * Creates an expression that checks if this expression is not equal to a constant value. * * ```typescript * // Check if the 'country' field is not equal to "USA" - * Field.of("country").neq("USA"); + * field("country").neq("USA"); * ``` * - * @param other The constant value to compare for inequality. + * @param value The constant value to compare for inequality. * @return A new `Expr` representing the inequality comparison. */ - neq(other: any): Neq; - neq(other: any): Neq { - if (other instanceof Expr) { - return new Neq(this, other); - } - return new Neq(this, Constant.of(other)); + neq(value: unknown): BooleanExpr; + neq(other: unknown): BooleanExpr { + return new BooleanExpr('neq', [this, valueToDefaultExpr(other)]); } /** @@ -504,31 +331,28 @@ export abstract class Expr implements firestore.Expr { * * ```typescript * // Check if the 'age' field is less than 'limit' - * Field.of("age").lt(Field.of('limit')); + * field("age").lt(field('limit')); * ``` * - * @param other The expression to compare for less than. + * @param experession The expression to compare for less than. * @return A new `Expr` representing the less than comparison. */ - lt(other: firestore.Expr): Lt; + lt(experession: firestore.Expr): BooleanExpr; /** * Creates an expression that checks if this expression is less than a constant value. * * ```typescript * // Check if the 'price' field is less than 50 - * Field.of("price").lt(50); + * field("price").lt(50); * ``` * - * @param other The constant value to compare for less than. + * @param value The constant value to compare for less than. * @return A new `Expr` representing the less than comparison. */ - lt(other: any): Lt; - lt(other: any): Lt { - if (other instanceof Expr) { - return new Lt(this, other); - } - return new Lt(this, Constant.of(other)); + lt(value: unknown): BooleanExpr; + lt(other: unknown): BooleanExpr { + return new BooleanExpr('lt', [this, valueToDefaultExpr(other)]); } /** @@ -537,31 +361,28 @@ export abstract class Expr implements firestore.Expr { * * ```typescript * // Check if the 'quantity' field is less than or equal to 20 - * Field.of("quantity").lte(Constant.of(20)); + * field("quantity").lte(constant(20)); * ``` * - * @param other The expression to compare for less than or equal to. + * @param expression The expression to compare for less than or equal to. * @return A new `Expr` representing the less than or equal to comparison. */ - lte(other: firestore.Expr): Lte; + lte(expression: firestore.Expr): BooleanExpr; /** * Creates an expression that checks if this expression is less than or equal to a constant value. * * ```typescript * // Check if the 'score' field is less than or equal to 70 - * Field.of("score").lte(70); + * field("score").lte(70); * ``` * - * @param other The constant value to compare for less than or equal to. + * @param value The constant value to compare for less than or equal to. * @return A new `Expr` representing the less than or equal to comparison. */ - lte(other: any): Lte; - lte(other: any): Lte { - if (other instanceof Expr) { - return new Lte(this, other); - } - return new Lte(this, Constant.of(other)); + lte(value: unknown): BooleanExpr; + lte(other: unknown): BooleanExpr { + return new BooleanExpr('lte', [this, valueToDefaultExpr(other)]); } /** @@ -569,31 +390,28 @@ export abstract class Expr implements firestore.Expr { * * ```typescript * // Check if the 'age' field is greater than the 'limit' field - * Field.of("age").gt(Field.of("limit")); + * field("age").gt(field("limit")); * ``` * - * @param other The expression to compare for greater than. + * @param expression The expression to compare for greater than. * @return A new `Expr` representing the greater than comparison. */ - gt(other: firestore.Expr): Gt; + gt(expression: firestore.Expr): BooleanExpr; /** * Creates an expression that checks if this expression is greater than a constant value. * * ```typescript * // Check if the 'price' field is greater than 100 - * Field.of("price").gt(100); + * field("price").gt(100); * ``` * - * @param other The constant value to compare for greater than. + * @param value The constant value to compare for greater than. * @return A new `Expr` representing the greater than comparison. */ - gt(other: any): Gt; - gt(other: any): Gt { - if (other instanceof Expr) { - return new Gt(this, other); - } - return new Gt(this, Constant.of(other)); + gt(value: unknown): BooleanExpr; + gt(other: unknown): BooleanExpr { + return new BooleanExpr('gt', [this, valueToDefaultExpr(other)]); } /** @@ -602,13 +420,13 @@ export abstract class Expr implements firestore.Expr { * * ```typescript * // Check if the 'quantity' field is greater than or equal to field 'requirement' plus 1 - * Field.of("quantity").gte(Field.of('requirement').add(1)); + * field("quantity").gte(field('requirement').add(1)); * ``` * - * @param other The expression to compare for greater than or equal to. + * @param expression The expression to compare for greater than or equal to. * @return A new `Expr` representing the greater than or equal to comparison. */ - gte(other: firestore.Expr): Gte; + gte(expression: firestore.Expr): BooleanExpr; /** * Creates an expression that checks if this expression is greater than or equal to a constant @@ -616,18 +434,15 @@ export abstract class Expr implements firestore.Expr { * * ```typescript * // Check if the 'score' field is greater than or equal to 80 - * Field.of("score").gte(80); + * field("score").gte(80); * ``` * - * @param other The constant value to compare for greater than or equal to. + * @param value The constant value to compare for greater than or equal to. * @return A new `Expr` representing the greater than or equal to comparison. */ - gte(other: any): Gte; - gte(other: any): Gte { - if (other instanceof Expr) { - return new Gte(this, other); - } - return new Gte(this, Constant.of(other)); + gte(value: unknown): BooleanExpr; + gte(other: unknown): BooleanExpr { + return new BooleanExpr('gte', [this, valueToDefaultExpr(other)]); } /** @@ -635,31 +450,19 @@ export abstract class Expr implements firestore.Expr { * * ```typescript * // Combine the 'items' array with another array field. - * Field.of("items").arrayConcat(Field.of("otherItems")); - * ``` - * - * @param arrays The array expressions to concatenate. - * @return A new `Expr` representing the concatenated array. - */ - arrayConcat(arrays: firestore.Expr[]): ArrayConcat; - - /** - * Creates an expression that concatenates an array expression with one or more other arrays. - * - * ```typescript - * // Combine the 'tags' array with a new array and an array field - * Field.of("tags").arrayConcat(Arrays.asList("newTag1", "newTag2"), Field.of("otherTag")); + * field("items").arrayConcat(field("otherItems")); * ``` - * - * @param arrays The array expressions or values to concatenate. + * @param secondArray Second array expression or array literal to concatenate. + * @param otherArrays Optional additional array expressions or array literals to concatenate. * @return A new `Expr` representing the concatenated array. */ - arrayConcat(arrays: any[]): ArrayConcat; - arrayConcat(arrays: any[]): ArrayConcat { - const exprValues = arrays.map(value => - value instanceof Expr ? value : Constant.of(value) - ); - return new ArrayConcat(this, exprValues); + arrayConcat( + secondArray: firestore.Expr | unknown[], + ...otherArrays: Array + ): FunctionExpr { + const elements = [secondArray, ...otherArrays]; + const exprValues = elements.map(value => valueToDefaultExpr(value)); + return new FunctionExpr('array_concat', [this, ...exprValues]); } /** @@ -667,63 +470,63 @@ export abstract class Expr implements firestore.Expr { * * ```typescript * // Check if the 'sizes' array contains the value from the 'selectedSize' field - * Field.of("sizes").arrayContains(Field.of("selectedSize")); + * field("sizes").arrayContains(field("selectedSize")); * ``` * - * @param element The element to search for in the array. + * @param expression The element to search for in the array. * @return A new `Expr` representing the 'array_contains' comparison. */ - arrayContains(element: firestore.Expr): ArrayContains; + arrayContains(expression: firestore.Expr): BooleanExpr; /** * Creates an expression that checks if an array contains a specific value. * * ```typescript * // Check if the 'colors' array contains "red" - * Field.of("colors").arrayContains("red"); + * field("colors").arrayContains("red"); * ``` * - * @param element The element to search for in the array. + * @param value The element to search for in the array. * @return A new `Expr` representing the 'array_contains' comparison. */ - arrayContains(element: any): ArrayContains; - arrayContains(element: any): ArrayContains { - if (element instanceof Expr) { - return new ArrayContains(this, element); - } - return new ArrayContains(this, Constant.of(element)); + arrayContains(value: unknown): BooleanExpr; + arrayContains(element: unknown): BooleanExpr { + return new BooleanExpr('array_contains', [ + this, + valueToDefaultExpr(element), + ]); } /** * Creates an expression that checks if an array contains all the specified elements. * * ```typescript - * // Check if the 'tags' array contains both "news" and "sports" - * Field.of("tags").arrayContainsAll(Field.of("tag1"), Field.of("tag2")); + * // Check if the 'tags' array contains both the value in field "tag1" and the literal value "tag2" + * field("tags").arrayContainsAll([field("tag1"), "tag2"]); * ``` * * @param values The elements to check for in the array. * @return A new `Expr` representing the 'array_contains_all' comparison. */ - arrayContainsAll(...values: firestore.Expr[]): ArrayContainsAll; + arrayContainsAll(values: Array): BooleanExpr; /** * Creates an expression that checks if an array contains all the specified elements. * * ```typescript - * // Check if the 'tags' array contains both of the values from field 'tag1' and "tag2" - * Field.of("tags").arrayContainsAll(Field.of("tag1"), Field.of("tag2")); + * // Check if the 'tags' array contains both of the values from field "tag1" and the literal value "tag2" + * field("tags").arrayContainsAll(array([field("tag1"), "tag2"])); * ``` * - * @param values The elements to check for in the array. + * @param arrayExpression The elements to check for in the array. * @return A new `Expr` representing the 'array_contains_all' comparison. */ - arrayContainsAll(...values: any[]): ArrayContainsAll; - arrayContainsAll(...values: any[]): ArrayContainsAll { - const exprValues = values.map(value => - value instanceof Expr ? value : Constant.of(value) - ); - return new ArrayContainsAll(this, exprValues); + arrayContainsAll(arrayExpression: firestore.Expr): BooleanExpr; + arrayContainsAll(values: unknown[] | firestore.Expr): BooleanExpr { + const normalizedExpr = Array.isArray(values) + ? new ListOfExprs(values.map(valueToDefaultExpr)) + : values; + return new BooleanExpr('array_contains_all', [this, normalizedExpr]); } /** @@ -731,13 +534,13 @@ export abstract class Expr implements firestore.Expr { * * ```typescript * // Check if the 'categories' array contains either values from field "cate1" or "cate2" - * Field.of("categories").arrayContainsAny(Field.of("cate1"), Field.of("cate2")); + * field("categories").arrayContainsAny([field("cate1"), field("cate2")]); * ``` * * @param values The elements to check for in the array. * @return A new `Expr` representing the 'array_contains_any' comparison. */ - arrayContainsAny(...values: firestore.Expr[]): ArrayContainsAny; + arrayContainsAny(values: Array): BooleanExpr; /** * Creates an expression that checks if an array contains any of the specified elements. @@ -745,18 +548,20 @@ export abstract class Expr implements firestore.Expr { * ```typescript * // Check if the 'groups' array contains either the value from the 'userGroup' field * // or the value "guest" - * Field.of("groups").arrayContainsAny(Field.of("userGroup"), "guest"); + * field("groups").arrayContainsAny(array([field("userGroup"), "guest"])); * ``` * - * @param values The elements to check for in the array. + * @param arrayExpression The elements to check for in the array. * @return A new `Expr` representing the 'array_contains_any' comparison. */ - arrayContainsAny(...values: any[]): ArrayContainsAny; - arrayContainsAny(...values: any[]): ArrayContainsAny { - const exprValues = values.map(value => - value instanceof Expr ? value : Constant.of(value) - ); - return new ArrayContainsAny(this, exprValues); + arrayContainsAny(arrayExpression: firestore.Expr): BooleanExpr; + arrayContainsAny( + values: Array | firestore.Expr + ): BooleanExpr { + const normalizedExpr = Array.isArray(values) + ? new ListOfExprs(values.map(valueToDefaultExpr)) + : values; + return new BooleanExpr('array_contains_any', [this, normalizedExpr]); } /** @@ -764,13 +569,13 @@ export abstract class Expr implements firestore.Expr { * * ```typescript * // Get the number of items in the 'cart' array - * Field.of("cart").arrayLength(); + * field("cart").arrayLength(); * ``` * * @return A new `Expr` representing the length of the array. */ - arrayLength(): ArrayLength { - return new ArrayLength(this); + arrayLength(): FunctionExpr { + return new FunctionExpr('array_length', [this]); } /** @@ -779,13 +584,13 @@ export abstract class Expr implements firestore.Expr { * * ```typescript * // Check if the 'category' field is either "Electronics" or value of field 'primaryType' - * Field.of("category").eqAny("Electronics", Field.of("primaryType")); + * field("category").eqAny("Electronics", field("primaryType")); * ``` * - * @param others The values or expressions to check against. - * @return A new `Expr` representing the 'EqAny' comparison. + * @param values The values or expressions to check against. + * @return A new `Expr` representing the 'IN' comparison. */ - eqAny(...others: firestore.Expr[]): EqAny; + eqAny(values: Array): BooleanExpr; /** * Creates an expression that checks if this expression is equal to any of the provided values or @@ -793,18 +598,18 @@ export abstract class Expr implements firestore.Expr { * * ```typescript * // Check if the 'category' field is either "Electronics" or value of field 'primaryType' - * Field.of("category").eqAny("Electronics", Field.of("primaryType")); + * field("category").eqAny(array(["Electronics", field("primaryType")])); * ``` * - * @param others The values or expressions to check against. - * @return A new `Expr` representing the 'EqAny' comparison. + * @param arrayExpression An expression that evaluates to an array of values to check against. + * @return A new `Expr` representing the 'IN' comparison. */ - eqAny(...others: any[]): EqAny; - eqAny(...others: any[]): EqAny { - const exprOthers = others.map(other => - other instanceof Expr ? other : Constant.of(other) - ); - return new EqAny(this, exprOthers); + eqAny(arrayExpression: firestore.Expr): BooleanExpr; + eqAny(others: unknown[] | firestore.Expr): BooleanExpr { + const exprOthers = Array.isArray(others) + ? new ListOfExprs(others.map(valueToDefaultExpr)) + : others; + return new BooleanExpr('eq_any', [this, exprOthers]); } /** @@ -813,32 +618,31 @@ export abstract class Expr implements firestore.Expr { * * ```typescript * // Check if the 'status' field is neither "pending" nor the value of 'rejectedStatus' - * Field.of("status").notEqAny("pending", Field.of("rejectedStatus")); + * field("status").notEqAny(["pending", field("rejectedStatus")]); * ``` * - * @param others The values or expressions to check against. + * @param values The values or expressions to check against. * @return A new `Expr` representing the 'NotEqAny' comparison. */ - notEqAny(...others: firestore.Expr[]): NotEqAny; + notEqAny(values: Array): BooleanExpr; /** - * Creates an expression that checks if this expression is not equal to any of the provided values or - * expressions. + * Creates an expression that checks if this expression is not equal to any of the values in the evaluated expression. * * ```typescript - * // Check if the 'status' field is neither "pending" nor the value of 'rejectedStatus' - * Field.of("status").notEqAny("pending", Field.of("rejectedStatus")); + * // Check if the 'status' field is not equal to any value in the field 'rejectedStatuses' + * field("status").notEqAny(field('rejectedStatuses')); * ``` * - * @param others The values or expressions to check against. + * @param arrayExpression The values or expressions to check against. * @return A new `Expr` representing the 'NotEqAny' comparison. */ - notEqAny(...others: any[]): NotEqAny; - notEqAny(...others: any[]): NotEqAny { - const exprOthers = others.map(other => - other instanceof Expr ? other : Constant.of(other) - ); - return new NotEqAny(this, exprOthers); + notEqAny(arrayExpression: firestore.Expr): BooleanExpr; + notEqAny(others: unknown[] | firestore.Expr): BooleanExpr { + const exprOthers = Array.isArray(others) + ? new ListOfExprs(others.map(valueToDefaultExpr)) + : others; + return new BooleanExpr('not_eq_any', [this, exprOthers]); } /** @@ -846,13 +650,27 @@ export abstract class Expr implements firestore.Expr { * * ```typescript * // Check if the result of a calculation is NaN - * Field.of("value").divide(0).isNaN(); + * field("value").divide(0).isNan(); + * ``` + * + * @return A new `Expr` representing the 'isNan' check. + */ + isNan(): BooleanExpr { + return new BooleanExpr('is_nan', [this]); + } + + /** + * Creates an expression that checks if this expression evaluates to 'Null'. + * + * ```typescript + * // Check if the result of a calculation is NaN + * field("value").isNull(); * ``` * - * @return A new `Expr` representing the 'isNaN' check. + * @return A new `Expr` representing the 'isNull' check. */ - isNaN(): IsNan { - return new IsNan(this); + isNull(): BooleanExpr { + return new BooleanExpr('is_null', [this]); } /** @@ -860,13 +678,13 @@ export abstract class Expr implements firestore.Expr { * * ```typescript * // Check if the document has a field named "phoneNumber" - * Field.of("phoneNumber").exists(); + * field("phoneNumber").exists(); * ``` * * @return A new `Expr` representing the 'exists' check. */ - exists(): Exists { - return new Exists(this); + exists(): BooleanExpr { + return new BooleanExpr('exists', [this]); } /** @@ -874,13 +692,13 @@ export abstract class Expr implements firestore.Expr { * * ```typescript * // Get the character length of the 'name' field in its UTF-8 form. - * Field.of("name").charLength(); + * field("name").charLength(); * ``` * * @return A new `Expr` representing the length of the string. */ - charLength(): CharLength { - return new CharLength(this); + charLength(): FunctionExpr { + return new FunctionExpr('char_length', [this]); } /** @@ -888,31 +706,28 @@ export abstract class Expr implements firestore.Expr { * * ```typescript * // Check if the 'title' field contains the word "guide" (case-sensitive) - * Field.of("title").like("%guide%"); + * field("title").like("%guide%"); * ``` * * @param pattern The pattern to search for. You can use "%" as a wildcard character. * @return A new `Expr` representing the 'like' comparison. */ - like(pattern: string): Like; + like(pattern: string): FunctionExpr; /** * Creates an expression that performs a case-sensitive string comparison. * * ```typescript * // Check if the 'title' field contains the word "guide" (case-sensitive) - * Field.of("title").like("%guide%"); + * field("title").like("%guide%"); * ``` * * @param pattern The pattern to search for. You can use "%" as a wildcard character. * @return A new `Expr` representing the 'like' comparison. */ - like(pattern: firestore.Expr): Like; - like(stringOrExpr: string | firestore.Expr): Like { - if (typeof stringOrExpr === 'string') { - return new Like(this, Constant.of(stringOrExpr)); - } - return new Like(this, stringOrExpr as Expr); + like(pattern: firestore.Expr): FunctionExpr; + like(stringOrExpr: string | firestore.Expr): FunctionExpr { + return new FunctionExpr('like', [this, valueToDefaultExpr(stringOrExpr)]); } /** @@ -921,13 +736,13 @@ export abstract class Expr implements firestore.Expr { * * ```typescript * // Check if the 'description' field contains "example" (case-insensitive) - * Field.of("description").regexContains("(?i)example"); + * field("description").regexContains("(?i)example"); * ``` * * @param pattern The regular expression to use for the search. * @return A new `Expr` representing the 'contains' comparison. */ - regexContains(pattern: string): RegexContains; + regexContains(pattern: string): BooleanExpr; /** * Creates an expression that checks if a string contains a specified regular expression as a @@ -935,18 +750,18 @@ export abstract class Expr implements firestore.Expr { * * ```typescript * // Check if the 'description' field contains the regular expression stored in field 'regex' - * Field.of("description").regexContains(Field.of("regex")); + * field("description").regexContains(field("regex")); * ``` * * @param pattern The regular expression to use for the search. * @return A new `Expr` representing the 'contains' comparison. */ - regexContains(pattern: firestore.Expr): RegexContains; - regexContains(stringOrExpr: string | firestore.Expr): RegexContains { - if (typeof stringOrExpr === 'string') { - return new RegexContains(this, Constant.of(stringOrExpr)); - } - return new RegexContains(this, stringOrExpr as Expr); + regexContains(pattern: firestore.Expr): BooleanExpr; + regexContains(stringOrExpr: string | firestore.Expr): BooleanExpr { + return new BooleanExpr('regex_contains', [ + this, + valueToDefaultExpr(stringOrExpr), + ]); } /** @@ -954,31 +769,31 @@ export abstract class Expr implements firestore.Expr { * * ```typescript * // Check if the 'email' field matches a valid email pattern - * Field.of("email").regexMatch("[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,}"); + * field("email").regexMatch("[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,}"); * ``` * * @param pattern The regular expression to use for the match. * @return A new `Expr` representing the regular expression match. */ - regexMatch(pattern: string): RegexMatch; + regexMatch(pattern: string): BooleanExpr; /** * Creates an expression that checks if a string matches a specified regular expression. * * ```typescript * // Check if the 'email' field matches a regular expression stored in field 'regex' - * Field.of("email").regexMatch(Field.of("regex")); + * field("email").regexMatch(field("regex")); * ``` * * @param pattern The regular expression to use for the match. * @return A new `Expr` representing the regular expression match. */ - regexMatch(pattern: firestore.Expr): RegexMatch; - regexMatch(stringOrExpr: string | firestore.Expr): RegexMatch { - if (typeof stringOrExpr === 'string') { - return new RegexMatch(this, Constant.of(stringOrExpr)); - } - return new RegexMatch(this, stringOrExpr as Expr); + regexMatch(pattern: firestore.Expr): BooleanExpr; + regexMatch(stringOrExpr: string | firestore.Expr): BooleanExpr { + return new BooleanExpr('regex_match', [ + this, + valueToDefaultExpr(stringOrExpr), + ]); } /** @@ -986,31 +801,31 @@ export abstract class Expr implements firestore.Expr { * * ```typescript * // Check if the 'description' field contains "example". - * Field.of("description").strContains("example"); + * field("description").strContains("example"); * ``` * * @param substring The substring to search for. * @return A new `Expr` representing the 'contains' comparison. */ - strContains(substring: string): StrContains; + strContains(substring: string): BooleanExpr; /** * Creates an expression that checks if a string contains the string represented by another expression. * * ```typescript * // Check if the 'description' field contains the value of the 'keyword' field. - * Field.of("description").strContains(Field.of("keyword")); + * field("description").strContains(field("keyword")); * ``` * * @param expr The expression representing the substring to search for. * @return A new `Expr` representing the 'contains' comparison. */ - strContains(expr: Expr): StrContains; - strContains(stringOrExpr: string | Expr): StrContains { - if (typeof stringOrExpr === 'string') { - return new StrContains(this, Constant.of(stringOrExpr)); - } - return new StrContains(this, stringOrExpr as Expr); + strContains(expr: firestore.Expr): BooleanExpr; + strContains(stringOrExpr: string | firestore.Expr): BooleanExpr { + return new BooleanExpr('str_contains', [ + this, + valueToDefaultExpr(stringOrExpr), + ]); } /** @@ -1018,13 +833,13 @@ export abstract class Expr implements firestore.Expr { * * ```typescript * // Check if the 'name' field starts with "Mr." - * Field.of("name").startsWith("Mr."); + * field("name").startsWith("Mr."); * ``` * * @param prefix The prefix to check for. * @return A new `Expr` representing the 'starts with' comparison. */ - startsWith(prefix: string): StartsWith; + startsWith(prefix: string): BooleanExpr; /** * Creates an expression that checks if a string starts with a given prefix (represented as an @@ -1032,18 +847,18 @@ export abstract class Expr implements firestore.Expr { * * ```typescript * // Check if the 'fullName' field starts with the value of the 'firstName' field - * Field.of("fullName").startsWith(Field.of("firstName")); + * field("fullName").startsWith(field("firstName")); * ``` * * @param prefix The prefix expression to check for. * @return A new `Expr` representing the 'starts with' comparison. */ - startsWith(prefix: firestore.Expr): StartsWith; - startsWith(stringOrExpr: string | firestore.Expr): StartsWith { - if (typeof stringOrExpr === 'string') { - return new StartsWith(this, Constant.of(stringOrExpr)); - } - return new StartsWith(this, stringOrExpr as Expr); + startsWith(prefix: firestore.Expr): BooleanExpr; + startsWith(stringOrExpr: string | firestore.Expr): BooleanExpr { + return new BooleanExpr('starts_with', [ + this, + valueToDefaultExpr(stringOrExpr), + ]); } /** @@ -1051,13 +866,13 @@ export abstract class Expr implements firestore.Expr { * * ```typescript * // Check if the 'filename' field ends with ".txt" - * Field.of("filename").endsWith(".txt"); + * field("filename").endsWith(".txt"); * ``` * * @param suffix The postfix to check for. * @return A new `Expr` representing the 'ends with' comparison. */ - endsWith(suffix: string): EndsWith; + endsWith(suffix: string): BooleanExpr; /** * Creates an expression that checks if a string ends with a given postfix (represented as an @@ -1065,18 +880,18 @@ export abstract class Expr implements firestore.Expr { * * ```typescript * // Check if the 'url' field ends with the value of the 'extension' field - * Field.of("url").endsWith(Field.of("extension")); + * field("url").endsWith(field("extension")); * ``` * * @param suffix The postfix expression to check for. * @return A new `Expr` representing the 'ends with' comparison. */ - endsWith(suffix: firestore.Expr): EndsWith; - endsWith(stringOrExpr: string | firestore.Expr): EndsWith { - if (typeof stringOrExpr === 'string') { - return new EndsWith(this, Constant.of(stringOrExpr)); - } - return new EndsWith(this, stringOrExpr as Expr); + endsWith(suffix: firestore.Expr): BooleanExpr; + endsWith(stringOrExpr: string | firestore.Expr): BooleanExpr { + return new BooleanExpr('ends_with', [ + this, + valueToDefaultExpr(stringOrExpr), + ]); } /** @@ -1084,13 +899,13 @@ export abstract class Expr implements firestore.Expr { * * ```typescript * // Convert the 'name' field to lowercase - * Field.of("name").toLower(); + * field("name").toLower(); * ``` * * @return A new `Expr` representing the lowercase string. */ - toLower(): ToLower { - return new ToLower(this); + toLower(): FunctionExpr { + return new FunctionExpr('to_lower', [this]); } /** @@ -1098,13 +913,13 @@ export abstract class Expr implements firestore.Expr { * * ```typescript * // Convert the 'title' field to uppercase - * Field.of("title").toUpper(); + * field("title").toUpper(); * ``` * * @return A new `Expr` representing the uppercase string. */ - toUpper(): ToUpper { - return new ToUpper(this); + toUpper(): FunctionExpr { + return new FunctionExpr('to_upper', [this]); } /** @@ -1112,13 +927,13 @@ export abstract class Expr implements firestore.Expr { * * ```typescript * // Trim whitespace from the 'userInput' field - * Field.of("userInput").trim(); + * field("userInput").trim(); * ``` * * @return A new `Expr` representing the trimmed string. */ - trim(): Trim { - return new Trim(this); + trim(): FunctionExpr { + return new FunctionExpr('trim', [this]); } /** @@ -1126,17 +941,20 @@ export abstract class Expr implements firestore.Expr { * * ```typescript * // Combine the 'firstName', " ", and 'lastName' fields into a single string - * Field.of("firstName").strConcat(Constant.of(" "), Field.of("lastName")); + * field("firstName").strConcat(constant(" "), field("lastName")); * ``` * - * @param elements The expressions (typically strings) to concatenate. + * @param secondString The additional expression or string literal to concatenate. + * @param otherStrings Optional additional expressions or string literals to concatenate. * @return A new `Expr` representing the concatenated string. */ - strConcat(...elements: (string | firestore.Expr)[]): StrConcat { - const exprs = elements.map(e => - typeof e === 'string' ? Constant.of(e) : (e as Expr) - ); - return new StrConcat(this, exprs); + strConcat( + secondString: firestore.Expr | string, + ...otherStrings: Array + ): FunctionExpr { + const elements = [secondString, ...otherStrings]; + const exprs = elements.map(valueToDefaultExpr); + return new FunctionExpr('str_concat', [this, ...exprs]); } /** @@ -1144,13 +962,13 @@ export abstract class Expr implements firestore.Expr { * * ```typescript * // Reverse the value of the 'myString' field. - * Field.of("myString").reverse(); + * field("myString").reverse(); * ``` * * @return A new {@code Expr} representing the reversed string. */ - reverse(): Reverse { - return new Reverse(this); + reverse(): FunctionExpr { + return new FunctionExpr('reverse', [this]); } /** @@ -1158,14 +976,14 @@ export abstract class Expr implements firestore.Expr { * * ```typescript * // Replace the first occurrence of "hello" with "hi" in the 'message' field - * Field.of("message").replaceFirst("hello", "hi"); + * field("message").replaceFirst("hello", "hi"); * ``` * * @param find The substring to search for. * @param replace The substring to replace the first occurrence of 'find' with. * @return A new {@code Expr} representing the string with the first occurrence replaced. */ - replaceFirst(find: string, replace: string): firestore.ReplaceFirst; + replaceFirst(find: string, replace: string): FunctionExpr; /** * Creates an expression that replaces the first occurrence of a substring within this string expression with another substring, @@ -1173,29 +991,23 @@ export abstract class Expr implements firestore.Expr { * * ```typescript * // Replace the first occurrence of the value in 'findField' with the value in 'replaceField' in the 'message' field - * Field.of("message").replaceFirst(Field.of("findField"), Field.of("replaceField")); + * field("message").replaceFirst(field("findField"), field("replaceField")); * ``` * * @param find The expression representing the substring to search for. * @param replace The expression representing the substring to replace the first occurrence of 'find' with. * @return A new {@code Expr} representing the string with the first occurrence replaced. */ - replaceFirst( - find: firestore.Expr, - replace: firestore.Expr - ): firestore.ReplaceFirst; + replaceFirst(find: firestore.Expr, replace: firestore.Expr): FunctionExpr; replaceFirst( find: firestore.Expr | string, replace: firestore.Expr | string - ): firestore.ReplaceFirst { - const normalizedFind = typeof find === 'string' ? Constant.of(find) : find; - const normalizedReplace = - typeof replace === 'string' ? Constant.of(replace) : replace; - return new ReplaceFirst( + ): FunctionExpr { + return new FunctionExpr('replace_first', [ this, - normalizedFind as Expr, - normalizedReplace as Expr - ); + valueToDefaultExpr(find), + valueToDefaultExpr(replace), + ]); } /** @@ -1203,14 +1015,14 @@ export abstract class Expr implements firestore.Expr { * * ```typescript * // Replace all occurrences of "hello" with "hi" in the 'message' field - * Field.of("message").replaceAll("hello", "hi"); + * field("message").replaceAll("hello", "hi"); * ``` * * @param find The substring to search for. * @param replace The substring to replace all occurrences of 'find' with. * @return A new {@code Expr} representing the string with all occurrences replaced. */ - replaceAll(find: string, replace: string): firestore.ReplaceAll; + replaceAll(find: string, replace: string): FunctionExpr; /** * Creates an expression that replaces all occurrences of a substring within this string expression with another substring, @@ -1218,29 +1030,23 @@ export abstract class Expr implements firestore.Expr { * * ```typescript * // Replace all occurrences of the value in 'findField' with the value in 'replaceField' in the 'message' field - * Field.of("message").replaceAll(Field.of("findField"), Field.of("replaceField")); + * field("message").replaceAll(field("findField"), field("replaceField")); * ``` * * @param find The expression representing the substring to search for. * @param replace The expression representing the substring to replace all occurrences of 'find' with. * @return A new {@code Expr} representing the string with all occurrences replaced. */ - replaceAll( - find: firestore.Expr, - replace: firestore.Expr - ): firestore.ReplaceAll; + replaceAll(find: firestore.Expr, replace: firestore.Expr): FunctionExpr; replaceAll( find: firestore.Expr | string, replace: firestore.Expr | string - ): firestore.ReplaceAll { - const normalizedFind = typeof find === 'string' ? Constant.of(find) : find; - const normalizedReplace = - typeof replace === 'string' ? Constant.of(replace) : replace; - return new ReplaceAll( + ): FunctionExpr { + return new FunctionExpr('replace_all', [ this, - normalizedFind as Expr, - normalizedReplace as Expr - ); + valueToDefaultExpr(find), + valueToDefaultExpr(replace), + ]); } /** @@ -1248,13 +1054,13 @@ export abstract class Expr implements firestore.Expr { * * ```typescript * // Calculate the length of the 'myString' field in bytes. - * Field.of("myString").byteLength(); + * field("myString").byteLength(); * ``` * * @return A new {@code Expr} representing the length of the string in bytes. */ - byteLength(): firestore.ByteLength { - return new ByteLength(this); + byteLength(): FunctionExpr { + return new FunctionExpr('byte_length', [this]); } /** @@ -1262,14 +1068,14 @@ export abstract class Expr implements firestore.Expr { * * ```typescript * // Get the 'city' value from the 'address' map field - * Field.of("address").mapGet("city"); + * field("address").mapGet("city"); * ``` * * @param subfield The key to access in the map. * @return A new `Expr` representing the value associated with the given key in the map. */ - mapGet(subfield: string): MapGet { - return new MapGet(this, subfield); + mapGet(subfield: string): FunctionExpr { + return new FunctionExpr('map_get', [this, constant(subfield)]); } /** @@ -1278,13 +1084,13 @@ export abstract class Expr implements firestore.Expr { * * ```typescript * // Count the total number of products - * Field.of("productId").count().as("totalProducts"); + * field("productId").count().as("totalProducts"); * ``` * - * @return A new `Accumulator` representing the 'count' aggregation. + * @return A new `AggregateFunction` representing the 'count' aggregation. */ - count(): Count { - return new Count(this, false); + count(): AggregateFunction { + return new AggregateFunction('count', [this]); } /** @@ -1292,13 +1098,13 @@ export abstract class Expr implements firestore.Expr { * * ```typescript * // Calculate the total revenue from a set of orders - * Field.of("orderAmount").sum().as("totalRevenue"); + * field("orderAmount").sum().as("totalRevenue"); * ``` * - * @return A new `Accumulator` representing the 'sum' aggregation. + * @return A new `AggregateFunction` representing the 'sum' aggregation. */ - sum(): Sum { - return new Sum(this, false); + sum(): AggregateFunction { + return new AggregateFunction('sum', [this]); } /** @@ -1307,13 +1113,13 @@ export abstract class Expr implements firestore.Expr { * * ```typescript * // Calculate the average age of users - * Field.of("age").avg().as("averageAge"); + * field("age").avg().as("averageAge"); * ``` * - * @return A new `Accumulator` representing the 'avg' aggregation. + * @return A new `AggregateFunction` representing the 'avg' aggregation. */ - avg(): Avg { - return new Avg(this, false); + avg(): AggregateFunction { + return new AggregateFunction('avg', [this]); } /** @@ -1321,13 +1127,13 @@ export abstract class Expr implements firestore.Expr { * * ```typescript * // Find the lowest price of all products - * Field.of("price").minimum().as("lowestPrice"); + * field("price").minimum().as("lowestPrice"); * ``` * - * @return A new `Accumulator` representing the 'minimum' aggregation. + * @return A new `AggregateFunction` representing the 'min' aggregation. */ - minimum(): Minimum { - return new Minimum(this, false); + minimum(): AggregateFunction { + return new AggregateFunction('minimum', [this]); } /** @@ -1335,13 +1141,13 @@ export abstract class Expr implements firestore.Expr { * * ```typescript * // Find the highest score in a leaderboard - * Field.of("score").maximum().as("highestScore"); + * field("score").maximum().as("highestScore"); * ``` * - * @return A new `Accumulator` representing the 'maximum' aggregation. + * @return A new `AggregateFunction` representing the 'max' aggregation. */ - maximum(): Maximum { - return new Maximum(this, false); + maximum(): AggregateFunction { + return new AggregateFunction('maximum', [this]); } /** @@ -1349,31 +1155,22 @@ export abstract class Expr implements firestore.Expr { * * ```typescript * // Returns the larger value between the 'timestamp' field and the current timestamp. - * Field.of("timestamp").logicalMaximum(Function.currentTimestamp()); - * ``` - * - * @param other The expression to compare with. - * @return A new {@code Expr} representing the logical maximum operation. - */ - logicalMaximum(other: firestore.Expr): firestore.LogicalMaximum; - - /** - * Creates an expression that returns the larger value between this expression and a constant value, based on Firestore's value type ordering. - * - * ```typescript - * // Returns the larger value between the 'value' field and 10. - * Field.of("value").logicalMaximum(10); + * field("timestamp").logicalMaximum(Function.currentTimestamp()); * ``` * - * @param other The constant value to compare with. - * @return A new {@code Expr} representing the logical maximum operation. + * @param second The second expression or literal to compare with. + * @param others Optional additional expressions or literals to compare with. + * @return A new {@code Expr} representing the logical max operation. */ - logicalMaximum(other: any): firestore.LogicalMaximum; - logicalMaximum(other: any): firestore.LogicalMaximum { - if (other instanceof Expr) { - return new LogicalMaximum(this, other as Expr); - } - return new LogicalMaximum(this, Constant.of(other)); + logicalMaximum( + second: firestore.Expr | unknown, + ...others: Array + ): FunctionExpr { + const values = [second, ...others]; + return new FunctionExpr('logical_maximum', [ + this, + ...values.map(valueToDefaultExpr), + ]); } /** @@ -1381,31 +1178,22 @@ export abstract class Expr implements firestore.Expr { * * ```typescript * // Returns the smaller value between the 'timestamp' field and the current timestamp. - * Field.of("timestamp").logicalMinimum(Function.currentTimestamp()); - * ``` - * - * @param other The expression to compare with. - * @return A new {@code Expr} representing the logical minimum operation. - */ - logicalMinimum(other: firestore.Expr): firestore.LogicalMinimum; - - /** - * Creates an expression that returns the smaller value between this expression and a constant value, based on Firestore's value type ordering. - * - * ```typescript - * // Returns the smaller value between the 'value' field and 10. - * Field.of("value").logicalMinimum(10); + * field("timestamp").logicalMinimum(Function.currentTimestamp()); * ``` * - * @param other The constant value to compare with. - * @return A new {@code Expr} representing the logical minimum operation. + * @param second The second expression or literal to compare with. + * @param others Optional additional expressions or literals to compare with. + * @return A new {@code Expr} representing the logical min operation. */ - logicalMinimum(other: any): firestore.LogicalMinimum; - logicalMinimum(other: any): firestore.LogicalMinimum { - if (other instanceof Expr) { - return new LogicalMinimum(this, other as Expr); - } - return new LogicalMinimum(this, Constant.of(other)); + logicalMinimum( + second: firestore.Expr | unknown, + ...others: Array + ): FunctionExpr { + const values = [second, ...others]; + return new FunctionExpr('logical_minimum', [ + this, + ...values.map(valueToDefaultExpr), + ]); } /** @@ -1413,13 +1201,13 @@ export abstract class Expr implements firestore.Expr { * * ```typescript * // Get the vector length (dimension) of the field 'embedding'. - * Field.of("embedding").vectorLength(); + * field("embedding").vectorLength(); * ``` * * @return A new {@code Expr} representing the length of the vector. */ - vectorLength(): VectorLength { - return new VectorLength(this); + vectorLength(): FunctionExpr { + return new FunctionExpr('vector_length', [this]); } /** @@ -1427,48 +1215,29 @@ export abstract class Expr implements firestore.Expr { * * ```typescript * // Calculate the cosine distance between the 'userVector' field and the 'itemVector' field - * Field.of("userVector").cosineDistance(Field.of("itemVector")); + * field("userVector").cosineDistance(field("itemVector")); * ``` * - * @param other The other vector (represented as an Expr) to compare against. + * @param vectorExpression The other vector (represented as an Expr) to compare against. * @return A new `Expr` representing the cosine distance between the two vectors. */ - cosineDistance(other: firestore.Expr): CosineDistance; + cosineDistance(vectorExpression: firestore.Expr): FunctionExpr; /** * Calculates the Cosine distance between two vectors. * * ```typescript * // Calculate the Cosine distance between the 'location' field and a target location - * Field.of("location").cosineDistance(new VectorValue([37.7749, -122.4194])); + * field("location").cosineDistance(new VectorValue([37.7749, -122.4194])); * ``` * - * @param other The other vector (as a VectorValue) to compare against. + * @param vector The other vector (as a VectorValue) to compare against. * @return A new `Expr` representing the Cosine* distance between the two vectors. */ - cosineDistance(other: VectorValue): CosineDistance; - /** - * Calculates the Cosine distance between two vectors. - * - * ```typescript - * // Calculate the Cosine distance between the 'location' field and a target location - * Field.of("location").cosineDistance([37.7749, -122.4194]); - * ``` - * - * @param other The other vector (as an array of numbers) to compare against. - * @return A new `Expr` representing the Cosine distance between the two vectors. - */ - cosineDistance(other: number[]): CosineDistance; + cosineDistance(vector: firestore.VectorValue | number[]): FunctionExpr; cosineDistance( other: firestore.Expr | firestore.VectorValue | number[] - ): CosineDistance { - if (other instanceof Expr) { - return new CosineDistance(this, other as Expr); - } else { - return new CosineDistance( - this, - Constant.vector(other as VectorValue | number[]) - ); - } + ): FunctionExpr { + return new FunctionExpr('cosine_distance', [this, vectorToExpr(other)]); } /** @@ -1476,50 +1245,30 @@ export abstract class Expr implements firestore.Expr { * * ```typescript * // Calculate the dot product between a feature vector and a target vector - * Field.of("features").dotProduct([0.5, 0.8, 0.2]); - * ``` - * - * @param other The other vector (as an array of numbers) to calculate with. - * @return A new `Expr` representing the dot product between the two vectors. - */ - dotProduct(other: firestore.Expr): DotProduct; - - /** - * Calculates the dot product between two vectors. - * - * ```typescript - * // Calculate the dot product between a feature vector and a target vector - * Field.of("features").dotProduct(new VectorValue([0.5, 0.8, 0.2])); + * field("features").dotProduct([0.5, 0.8, 0.2]); * ``` * - * @param other The other vector (as an array of numbers) to calculate with. + * @param vectorExpression The other vector (as an array of numbers) to calculate with. * @return A new `Expr` representing the dot product between the two vectors. */ - dotProduct(other: VectorValue): DotProduct; + dotProduct(vectorExpression: firestore.Expr): FunctionExpr; /** * Calculates the dot product between two vectors. * * ```typescript * // Calculate the dot product between a feature vector and a target vector - * Field.of("features").dotProduct([0.5, 0.8, 0.2]); + * field("features").dotProduct(new VectorValue([0.5, 0.8, 0.2])); * ``` * - * @param other The other vector (as an array of numbers) to calculate with. + * @param vector The other vector (as an array of numbers) to calculate with. * @return A new `Expr` representing the dot product between the two vectors. */ - dotProduct(other: number[]): DotProduct; + dotProduct(vector: firestore.VectorValue | number[]): FunctionExpr; dotProduct( other: firestore.Expr | firestore.VectorValue | number[] - ): DotProduct { - if (other instanceof Expr) { - return new DotProduct(this, other as Expr); - } else { - return new DotProduct( - this, - Constant.vector(other as VectorValue | number[]) - ); - } + ): FunctionExpr { + return new FunctionExpr('dot_product', [this, vectorToExpr(other)]); } /** @@ -1527,50 +1276,30 @@ export abstract class Expr implements firestore.Expr { * * ```typescript * // Calculate the Euclidean distance between the 'location' field and a target location - * Field.of("location").euclideanDistance([37.7749, -122.4194]); - * ``` - * - * @param other The other vector (as an array of numbers) to calculate with. - * @return A new `Expr` representing the Euclidean distance between the two vectors. - */ - euclideanDistance(other: firestore.Expr): EuclideanDistance; - - /** - * Calculates the Euclidean distance between two vectors. - * - * ```typescript - * // Calculate the Euclidean distance between the 'location' field and a target location - * Field.of("location").euclideanDistance(new VectorValue([37.7749, -122.4194])); + * field("location").euclideanDistance([37.7749, -122.4194]); * ``` * - * @param other The other vector (as a VectorValue) to compare against. + * @param vectorExpression The other vector (as an array of numbers) to calculate with. * @return A new `Expr` representing the Euclidean distance between the two vectors. */ - euclideanDistance(other: VectorValue): EuclideanDistance; + euclideanDistance(vectorExpression: firestore.Expr): FunctionExpr; /** * Calculates the Euclidean distance between two vectors. * * ```typescript * // Calculate the Euclidean distance between the 'location' field and a target location - * Field.of("location").euclideanDistance([37.7749, -122.4194]); + * field("location").euclideanDistance(new VectorValue([37.7749, -122.4194])); * ``` * - * @param other The other vector (as an array of numbers) to compare against. + * @param vector The other vector (as a VectorValue) to compare against. * @return A new `Expr` representing the Euclidean distance between the two vectors. */ - euclideanDistance(other: number[]): EuclideanDistance; + euclideanDistance(vector: firestore.VectorValue | number[]): FunctionExpr; euclideanDistance( other: firestore.Expr | firestore.VectorValue | number[] - ): EuclideanDistance { - if (other instanceof Expr) { - return new EuclideanDistance(this, other as Expr); - } else { - return new EuclideanDistance( - this, - Constant.vector(other as VectorValue | number[]) - ); - } + ): FunctionExpr { + return new FunctionExpr('euclidean_distance', [this, vectorToExpr(other)]); } /** @@ -1579,13 +1308,13 @@ export abstract class Expr implements firestore.Expr { * * ```typescript * // Interpret the 'microseconds' field as microseconds since epoch. - * Field.of("microseconds").unixMicrosToTimestamp(); + * field("microseconds").unixMicrosToTimestamp(); * ``` * * @return A new {@code Expr} representing the timestamp. */ - unixMicrosToTimestamp(): firestore.UnixMicrosToTimestamp { - return new UnixMicrosToTimestamp(this); + unixMicrosToTimestamp(): FunctionExpr { + return new FunctionExpr('unix_micros_to_timestamp', [this]); } /** @@ -1593,13 +1322,13 @@ export abstract class Expr implements firestore.Expr { * * ```typescript * // Convert the 'timestamp' field to microseconds since epoch. - * Field.of("timestamp").timestampToUnixMicros(); + * field("timestamp").timestampToUnixMicros(); * ``` * * @return A new {@code Expr} representing the number of microseconds since epoch. */ - timestampToUnixMicros(): firestore.TimestampToUnixMicros { - return new TimestampToUnixMicros(this); + timestampToUnixMicros(): FunctionExpr { + return new FunctionExpr('timestamp_to_unix_micros', [this]); } /** @@ -1608,13 +1337,13 @@ export abstract class Expr implements firestore.Expr { * * ```typescript * // Interpret the 'milliseconds' field as milliseconds since epoch. - * Field.of("milliseconds").unixMillisToTimestamp(); + * field("milliseconds").unixMillisToTimestamp(); * ``` * * @return A new {@code Expr} representing the timestamp. */ - unixMillisToTimestamp(): firestore.UnixMillisToTimestamp { - return new UnixMillisToTimestamp(this); + unixMillisToTimestamp(): FunctionExpr { + return new FunctionExpr('unix_millis_to_timestamp', [this]); } /** @@ -1622,13 +1351,13 @@ export abstract class Expr implements firestore.Expr { * * ```typescript * // Convert the 'timestamp' field to milliseconds since epoch. - * Field.of("timestamp").timestampToUnixMillis(); + * field("timestamp").timestampToUnixMillis(); * ``` * * @return A new {@code Expr} representing the number of milliseconds since epoch. */ - timestampToUnixMillis(): firestore.TimestampToUnixMillis { - return new TimestampToUnixMillis(this); + timestampToUnixMillis(): FunctionExpr { + return new FunctionExpr('timestamp_to_unix_millis', [this]); } /** @@ -1637,13 +1366,13 @@ export abstract class Expr implements firestore.Expr { * * ```typescript * // Interpret the 'seconds' field as seconds since epoch. - * Field.of("seconds").unixSecondsToTimestamp(); + * field("seconds").unixSecondsToTimestamp(); * ``` * * @return A new {@code Expr} representing the timestamp. */ - unixSecondsToTimestamp(): firestore.UnixSecondsToTimestamp { - return new UnixSecondsToTimestamp(this); + unixSecondsToTimestamp(): FunctionExpr { + return new FunctionExpr('unix_seconds_to_timestamp', [this]); } /** @@ -1651,13 +1380,13 @@ export abstract class Expr implements firestore.Expr { * * ```typescript * // Convert the 'timestamp' field to seconds since epoch. - * Field.of("timestamp").timestampToUnixSeconds(); + * field("timestamp").timestampToUnixSeconds(); * ``` * * @return A new {@code Expr} representing the number of seconds since epoch. */ - timestampToUnixSeconds(): firestore.TimestampToUnixSeconds { - return new TimestampToUnixSeconds(this); + timestampToUnixSeconds(): FunctionExpr { + return new FunctionExpr('timestamp_to_unix_seconds', [this]); } /** @@ -1665,24 +1394,21 @@ export abstract class Expr implements firestore.Expr { * * ```typescript * // Add some duration determined by field 'unit' and 'amount' to the 'timestamp' field. - * Field.of("timestamp").timestampAdd(Field.of("unit"), Field.of("amount")); + * field("timestamp").timestampAdd(field("unit"), field("amount")); * ``` * * @param unit The expression evaluates to unit of time, must be one of 'microsecond', 'millisecond', 'second', 'minute', 'hour', 'day'. * @param amount The expression evaluates to amount of the unit. * @return A new {@code Expr} representing the resulting timestamp. */ - timestampAdd( - unit: firestore.Expr, - amount: firestore.Expr - ): firestore.TimestampAdd; + timestampAdd(unit: firestore.Expr, amount: firestore.Expr): FunctionExpr; /** * Creates an expression that adds a specified amount of time to this timestamp expression. * * ```typescript * // Add 1 day to the 'timestamp' field. - * Field.of("timestamp").timestampAdd("day", 1); + * field("timestamp").timestampAdd("day", 1); * ``` * * @param unit The unit of time to add (e.g., "day", "hour"). @@ -1692,7 +1418,7 @@ export abstract class Expr implements firestore.Expr { timestampAdd( unit: 'microsecond' | 'millisecond' | 'second' | 'minute' | 'hour' | 'day', amount: number - ): firestore.TimestampAdd; + ): FunctionExpr; timestampAdd( unit: | firestore.Expr @@ -1703,15 +1429,12 @@ export abstract class Expr implements firestore.Expr { | 'hour' | 'day', amount: firestore.Expr | number - ): firestore.TimestampAdd { - const normalizedUnit = typeof unit === 'string' ? Constant.of(unit) : unit; - const normalizedAmount = - typeof amount === 'number' ? Constant.of(amount) : amount; - return new TimestampAdd( + ): FunctionExpr { + return new FunctionExpr('timestamp_add', [ this, - normalizedUnit as Expr, - normalizedAmount as Expr - ); + valueToDefaultExpr(unit), + valueToDefaultExpr(amount), + ]); } /** @@ -1719,24 +1442,21 @@ export abstract class Expr implements firestore.Expr { * * ```typescript * // Subtract some duration determined by field 'unit' and 'amount' from the 'timestamp' field. - * Field.of("timestamp").timestampSub(Field.of("unit"), Field.of("amount")); + * field("timestamp").timestampSub(field("unit"), field("amount")); * ``` * * @param unit The expression evaluates to unit of time, must be one of 'microsecond', 'millisecond', 'second', 'minute', 'hour', 'day'. * @param amount The expression evaluates to amount of the unit. * @return A new {@code Expr} representing the resulting timestamp. */ - timestampSub( - unit: firestore.Expr, - amount: firestore.Expr - ): firestore.TimestampSub; + timestampSub(unit: firestore.Expr, amount: firestore.Expr): FunctionExpr; /** * Creates an expression that subtracts a specified amount of time from this timestamp expression. * * ```typescript * // Subtract 1 day from the 'timestamp' field. - * Field.of("timestamp").timestampSub("day", 1); + * field("timestamp").timestampSub("day", 1); * ``` * * @param unit The unit of time to subtract (e.g., "day", "hour"). @@ -1746,7 +1466,7 @@ export abstract class Expr implements firestore.Expr { timestampSub( unit: 'microsecond' | 'millisecond' | 'second' | 'minute' | 'hour' | 'day', amount: number - ): firestore.TimestampSub; + ): FunctionExpr; timestampSub( unit: | firestore.Expr @@ -1757,1238 +1477,2002 @@ export abstract class Expr implements firestore.Expr { | 'hour' | 'day', amount: firestore.Expr | number - ): firestore.TimestampSub { - const normalizedUnit = typeof unit === 'string' ? Constant.of(unit) : unit; - const normalizedAmount = - typeof amount === 'number' ? Constant.of(amount) : amount; - return new TimestampSub( + ): FunctionExpr { + return new FunctionExpr('timestamp_sub', [ this, - normalizedUnit as Expr, - normalizedAmount as Expr - ); + valueToDefaultExpr(unit), + valueToDefaultExpr(amount), + ]); } /** - * Creates an {@link Ordering} that sorts documents in ascending order based on this expression. + * @beta + * + * Creates an expression that applies a bitwise AND operation between this expression and a constant. * * ```typescript - * // Sort documents by the 'name' field in ascending order - * firestore.pipeline().collection("users") - * .sort(Field.of("name").ascending()); + * // Calculate the bitwise AND of 'field1' and 0xFF. + * field("field1").bitAnd(0xFF); * ``` * - * @return A new `Ordering` for ascending sorting. + * @param otherBits A constant representing bits. + * @return A new {@code Expr} representing the bitwise AND operation. */ - ascending(): Ordering { - return ascending(this); - } - + bitAnd(otherBits: number | Buffer | Uint8Array): FunctionExpr; /** - * Creates an {@link Ordering} that sorts documents in descending order based on this expression. + * @beta + * + * Creates an expression that applies a bitwise AND operation between two expressions. * * ```typescript - * // Sort documents by the 'createdAt' field in descending order - * firestore.pipeline().collection("users") - * .sort(Field.of("createdAt").descending()); + * // Calculate the bitwise AND of 'field1' and 'field2'. + * field("field1").bitAnd(field("field2")); * ``` * - * @return A new `Ordering` for descending sorting. + * @param bitsExpression An expression that returns bits when evaluated. + * @return A new {@code Expr} representing the bitwise AND operation. */ - descending(): Ordering { - return descending(this); + bitAnd(bitsExpression: firestore.Expr): FunctionExpr; + bitAnd( + bitsOrExpression: number | firestore.Expr | Buffer | Uint8Array + ): FunctionExpr { + return new FunctionExpr('bit_and', [ + this, + valueToDefaultExpr(bitsOrExpression), + ]); } /** - * Assigns an alias to this expression. + * @beta * - * Aliases are useful for renaming fields in the output of a stage or for giving meaningful - * names to calculated values. + * Creates an expression that applies a bitwise OR operation between this expression and a constant. * * ```typescript - * // Calculate the total price and assign it the alias "totalPrice" and add it to the output. - * firestore.pipeline().collection("items") - * .addFields(Field.of("price").multiply(Field.of("quantity")).as("totalPrice")); + * // Calculate the bitwise OR of 'field1' and 0xFF. + * field("field1").bitOr(0xFF); * ``` * - * @param name The alias to assign to this expression. - * @return A new {@link ExprWithAlias} that wraps this - * expression and associates it with the provided alias. + * @param otherBits A constant representing bits. + * @return A new {@code Expr} representing the bitwise OR operation. */ - as(name: string): ExprWithAlias { - return new ExprWithAlias(this, name); - } - - abstract _toProto(serializer: Serializer): api.IValue; -} - -/** - * @beta - */ -export class ExprWithAlias extends Expr implements Selectable { - exprType: ExprType = 'ExprWithAlias'; - selectable = true as const; - - constructor( - public expr: T, - public alias: string - ) { - super(); - } - - _toProto(serializer: Serializer): api.IValue { - throw new Error('ExprWithAlias should not be serialized directly.'); - } -} - -/** - * @internal - */ -class ListOfExprs extends Expr { - exprType: ExprType = 'ListOfExprs'; - constructor(private exprs: Expr[]) { - super(); - } - - _toProto(serializer: Serializer): api.IValue { - return { - arrayValue: { - values: this.exprs.map(p => serializer.encodeValue(p)!), - }, - }; - } -} - -/** - * @beta - * - * Represents a reference to a field in a Firestore document, or outputs of a {@link Pipeline} stage. - * - *

    Field references are used to access document field values in expressions and to specify fields - * for sorting, filtering, and projecting data in Firestore pipelines. - * - *

    You can create a `Field` instance using the static {@link #of} method: - * - * ```typescript - * // Create a Field instance for the 'name' field - * const nameField = Field.of("name"); - * - * // Create a Field instance for a nested field 'address.city' - * const cityField = Field.of("address.city"); - * ``` - */ -export class Field extends Expr implements Selectable { - exprType: ExprType = 'Field'; - selectable = true as const; - - private constructor( - private fieldPath: firestore.FieldPath, - private pipeline: Pipeline | null = null - ) { - super(); - } - + bitOr(otherBits: number | Buffer | Uint8Array): FunctionExpr; /** - * Creates a {@code Field} instance representing the field at the given path. + * @beta * - * The path can be a simple field name (e.g., "name") or a dot-separated path to a nested field - * (e.g., "address.city"). + * Creates an expression that applies a bitwise OR operation between two expressions. * * ```typescript - * // Create a Field instance for the 'title' field - * const titleField = Field.of("title"); - * - * // Create a Field instance for a nested field 'author.firstName' - * const authorFirstNameField = Field.of("author.firstName"); + * // Calculate the bitwise OR of 'field1' and 'field2'. + * field("field1").bitOr(field("field2")); * ``` * - * @param name The path to the field. - * @return A new {@code Field} instance representing the specified field. - */ - static of(name: string): Field; - static of(path: firestore.FieldPath): Field; - static of(nameOrPath: string | firestore.FieldPath): Field; - static of(pipeline: firestore.Pipeline, name: string): Field; - static of( - pipelineOrName: firestore.Pipeline | string | firestore.FieldPath, - name?: string - ): Field { - if (typeof pipelineOrName === 'string') { - if (FieldPath.documentId().formattedName === pipelineOrName) { - return new Field(FieldPath.documentId()); - } - - return new Field(FieldPath.fromArgument(pipelineOrName)); - } else if (pipelineOrName instanceof FieldPath) { - if (FieldPath.documentId().isEqual(pipelineOrName)) { - return new Field(FieldPath.documentId()); - } - return new Field(pipelineOrName); - } else { - return new Field( - FieldPath.fromArgument(name!), - pipelineOrName as Pipeline - ); - } + * @param bitsExpression An expression that returns bits when evaluated. + * @return A new {@code Expr} representing the bitwise OR operation. + */ + bitOr(bitsExpression: firestore.Expr): FunctionExpr; + bitOr( + bitsOrExpression: number | firestore.Expr | Buffer | Uint8Array + ): FunctionExpr { + return new FunctionExpr('bit_or', [ + this, + valueToDefaultExpr(bitsOrExpression), + ]); } - fieldName(): string { - return (this.fieldPath as FieldPath).formattedName; + /** + * @beta + * + * Creates an expression that applies a bitwise XOR operation between this expression and a constant. + * + * ```typescript + * // Calculate the bitwise XOR of 'field1' and 0xFF. + * field("field1").bitXor(0xFF); + * ``` + * + * @param otherBits A constant representing bits. + * @return A new {@code Expr} representing the bitwise XOR operation. + */ + bitXor(otherBits: number | Buffer | Uint8Array): FunctionExpr; + /** + * @beta + * + * Creates an expression that applies a bitwise XOR operation between two expressions. + * + * ```typescript + * // Calculate the bitwise XOR of 'field1' and 'field2'. + * field("field1").bitXor(field("field2")); + * ``` + * + * @param bitsExpression An expression that returns bits when evaluated. + * @return A new {@code Expr} representing the bitwise XOR operation. + */ + bitXor(bitsExpression: firestore.Expr): FunctionExpr; + bitXor( + bitsOrExpression: number | firestore.Expr | Buffer | Uint8Array + ): FunctionExpr { + return new FunctionExpr('bit_xor', [ + this, + valueToDefaultExpr(bitsOrExpression), + ]); } - _toProto(serializer: Serializer): api.IValue { - return { - fieldReferenceValue: (this.fieldPath as FieldPath).formattedName, - }; + /** + * @beta + * + * Creates an expression that applies a bitwise NOT operation to this expression. + * + * ```typescript + * // Calculate the bitwise NOT of 'field1'. + * field("field1").bitNot(); + * ``` + * + * @return A new {@code Expr} representing the bitwise NOT operation. + */ + bitNot(): FunctionExpr { + return new FunctionExpr('bit_not', [this]); } -} - -/** - * @beta - * - * Represents a constant value that can be used in a Firestore pipeline expression. - * - * You can create a `Constant` instance using the static {@link #of} method: - * - * ```typescript - * // Create a Constant instance for the number 10 - * const ten = Constant.of(10); - * - * // Create a Constant instance for the string "hello" - * const hello = Constant.of("hello"); - * ``` - */ -export class Constant extends Expr { - exprType: ExprType = 'Constant'; - private constructor(private value: any) { - super(); + /** + * @beta + * + * Creates an expression that applies a bitwise left shift operation to this expression. + * + * ```typescript + * // Calculate the bitwise left shift of 'field1' by 2 bits. + * field("field1").bitLeftShift(2); + * ``` + * + * @param y The operand constant representing the number of bits to shift. + * @return A new {@code Expr} representing the bitwise left shift operation. + */ + bitLeftShift(y: number): FunctionExpr; + /** + * @beta + * + * Creates an expression that applies a bitwise left shift operation to this expression. + * + * ```typescript + * // Calculate the bitwise left shift of 'field1' by 'field2' bits. + * field("field1").bitLeftShift(field("field2")); + * ``` + * + * @param numberExpr The operand expression representing the number of bits to shift. + * @return A new {@code Expr} representing the bitwise left shift operation. + */ + bitLeftShift(numberExpr: firestore.Expr): FunctionExpr; + bitLeftShift(numberExpr: number | firestore.Expr): FunctionExpr { + return new FunctionExpr('bit_left_shift', [ + this, + valueToDefaultExpr(numberExpr), + ]); } /** - * Creates a `Constant` instance for a number value. + * @beta + * + * Creates an expression that applies a bitwise right shift operation to this expression. + * + * ```typescript + * // Calculate the bitwise right shift of 'field1' by 2 bits. + * field("field1").bitRightShift(2); + * ``` * - * @param value The number value. - * @return A new `Constant` instance. + * @param right The operand constant representing the number of bits to shift. + * @return A new {@code Expr} representing the bitwise right shift operation. */ - static of(value: number): Constant; - + bitRightShift(y: number): FunctionExpr; /** - * Creates a `Constant` instance for a string value. + * @beta + * + * Creates an expression that applies a bitwise right shift operation to this expression. + * + * ```typescript + * // Calculate the bitwise right shift of 'field1' by 'field2' bits. + * field("field1").bitRightShift(field("field2")); + * ``` * - * @param value The string value. - * @return A new `Constant` instance. + * @param numberExpr The operand expression representing the number of bits to shift. + * @return A new {@code Expr} representing the bitwise right shift operation. */ - static of(value: string): Constant; + bitRightShift(numberExpr: firestore.Expr): FunctionExpr; + bitRightShift(numberExpr: number | firestore.Expr): FunctionExpr { + return new FunctionExpr('bit_right_shift', [ + this, + valueToDefaultExpr(numberExpr), + ]); + } /** - * Creates a `Constant` instance for a boolean value. + * @beta + * + * Creates an expression that returns the document ID from a path. + * + * ```typescript + * // Get the document ID from a path. + * field("__path__").documentId(); + * ``` * - * @param value The boolean value. - * @return A new `Constant` instance. + * @return A new {@code Expr} representing the documentId operation. */ - static of(value: boolean): Constant; + documentId(): FunctionExpr { + return new FunctionExpr('document_id', [this]); + } /** - * Creates a `Constant` instance for a null value. + * @beta + * + * Creates an expression that returns a substring of the results of this expression. * - * @param value The null value. - * @return A new `Constant` instance. + * @param position Index of the first character of the substring. + * @param length Length of the substring. If not provided, the substring will + * end at the end of the input. */ - static of(value: null): Constant; + substr(position: number, length?: number): FunctionExpr; /** - * Creates a `Constant` instance for an undefined value. + * @beta * - * @param value The undefined value. - * @return A new `Constant` instance. + * Creates an expression that returns a substring of the results of this expression. + * + * @param position An expression returning the index of the first character of the substring. + * @param length An expression returning the length of the substring. If not provided the + * substring will end at the end of the input. */ - static of(value: undefined): Constant; + substr(position: firestore.Expr, length?: firestore.Expr): FunctionExpr; + substr( + position: firestore.Expr | number, + length?: firestore.Expr | number + ): FunctionExpr { + const positionExpr = valueToDefaultExpr(position); + if (length === undefined) { + return new FunctionExpr('substr', [this, positionExpr]); + } else { + return new FunctionExpr('substr', [ + this, + positionExpr, + valueToDefaultExpr(length), + ]); + } + } /** - * Creates a `Constant` instance for a GeoPoint value. + * @beta + * Creates an expression that indexes into an array from the beginning or end + * and returns the element. If the offset exceeds the array length, an error is + * returned. A negative offset, starts from the end. + * + * ```typescript + * // Return the value in the 'tags' field array at index `1`. + * field('tags').arrayOffset(1); + * ``` * - * @param value The GeoPoint value. - * @return A new `Constant` instance. + * @param offset The index of the element to return. + * @return A new Expr representing the 'arrayOffset' operation. */ - static of(value: firestore.GeoPoint): Constant; + arrayOffset(offset: number): FunctionExpr; /** - * Creates a `Constant` instance for a Timestamp value. + * @beta + * Creates an expression that indexes into an array from the beginning or end + * and returns the element. If the offset exceeds the array length, an error is + * returned. A negative offset, starts from the end. + * + * ```typescript + * // Return the value in the tags field array at index specified by field + * // 'favoriteTag'. + * field('tags').arrayOffset(field('favoriteTag')); + * ``` * - * @param value The Timestamp value. - * @return A new `Constant` instance. + * @param offsetExpr An Expr evaluating to the index of the element to return. + * @return A new Expr representing the 'arrayOffset' operation. */ - static of(value: firestore.Timestamp): Constant; + arrayOffset(offsetExpr: firestore.Expr): FunctionExpr; + arrayOffset(offset: firestore.Expr | number): FunctionExpr { + return new FunctionExpr('array_offset', [this, valueToDefaultExpr(offset)]); + } /** - * Creates a `Constant` instance for a Date value. + * @beta + * + * Creates an expression that checks if a given expression produces an error. + * + * ```typescript + * // Check if the result of a calculation is an error + * field("title").arrayContains(1).isError(); + * ``` * - * @param value The Date value. - * @return A new `Constant` instance. + * @return A new {@code BooleanExpr} representing the 'isError' check. */ - static of(value: Date): Constant; + isError(): BooleanExpr { + return new BooleanExpr('is_error', [this]); + } /** - * Creates a `Constant` instance for a Uint8Array value. + * @beta + * + * Creates an expression that returns the result of the `catchExpr` argument + * if there is an error, else return the result of this expression. * - * @param value The Uint8Array value. - * @return A new `Constant` instance. + * ```typescript + * // Returns the first item in the title field arrays, or returns + * // the entire title field if the array is empty or the field is another type. + * field("title").arrayOffset(0).ifError(field("title")); + * ``` + * + * @param catchExpr The catch expression that will be evaluated and + * returned if this expression produces an error. + * @return A new {@code Expr} representing the 'ifError' operation. */ - static of(value: Uint8Array): Constant; + ifError(catchExpr: firestore.Expr): FunctionExpr; /** - * Creates a `Constant` instance for a DocumentReference value. + * @beta + * + * Creates an expression that returns the `catch` argument if there is an + * error, else return the result of this expression. * - * @param value The DocumentReference value. - * @return A new `Constant` instance. + * ```typescript + * // Returns the first item in the title field arrays, or returns + * // "Default Title" + * field("title").arrayOffset(0).ifError("Default Title"); + * ``` + * + * @param catchValue The value that will be returned if this expression + * produces an error. + * @return A new {@code Expr} representing the 'ifError' operation. */ - static of(value: firestore.DocumentReference): Constant; + ifError(catchValue: unknown): FunctionExpr; + ifError(catchValue: unknown): FunctionExpr { + return new FunctionExpr('if_error', [this, valueToDefaultExpr(catchValue)]); + } /** - * Creates a `Constant` instance for a Firestore proto value. + * @beta + * + * Creates an expression that returns `true` if the result of this expression + * is absent. Otherwise, returns `false` even if the value is `null`. + * + * ```typescript + * // Check if the field `value` is absent. + * field("value").isAbsent(); + * ``` * - * @param value The Firestore proto value. - * @return A new `Constant` instance. + * @return A new {@code BooleanExpr} representing the 'isAbsent' check. */ - static of(value: api.IValue): Constant; + isAbsent(): BooleanExpr { + return new BooleanExpr('is_absent', [this]); + } /** - * Creates a `Constant` instance for an array value. + * @beta + * + * Creates an expression that checks if tbe result of an expression is not null. + * + * ```typescript + * // Check if the value of the 'name' field is not null + * field("name").isNotNull(); + * ``` * - * @param value The array value. - * @return A new `Constant` instance. + * @return A new {@code BooleanExpr} representing the 'isNotNull' check. */ - static of(value: Array): Constant; + isNotNull(): BooleanExpr { + return new BooleanExpr('is_not_null', [this]); + } /** - * Creates a `Constant` instance for a map value. + * @beta + * + * Creates an expression that checks if the results of this expression is NOT 'NaN' (Not a Number). + * + * ```typescript + * // Check if the result of a calculation is NOT NaN + * field("value").divide(0).isNotNan(); + * ``` * - * @param value The map value. - * @return A new `Constant` instance. + * @return A new {@code Expr} representing the 'isNan' check. */ - static of(value: Map): Constant; + isNotNan(): BooleanExpr { + return new BooleanExpr('is_not_nan', [this]); + } /** - * Creates a `Constant` instance for a VectorValue value. + * @beta + * + * Creates an expression that removes a key from the map produced by evaluating this expression. + * + * ``` + * // Removes the key 'baz' from the input map. + * map({foo: 'bar', baz: true}).mapRemove('baz'); + * ``` + * + * @param key The name of the key to remove from the input map. + * @returns A new {@code FirestoreFunction} representing the 'mapRemove' operation. + */ + mapRemove(key: string): FunctionExpr; + /** + * @beta + * + * Creates an expression that removes a key from the map produced by evaluating this expression. + * + * ``` + * // Removes the key 'baz' from the input map. + * map({foo: 'bar', baz: true}).mapRemove(constant('baz')); + * ``` * - * @param value The VectorValue value. - * @return A new `Constant` instance. + * @param keyExpr An expression that produces the name of the key to remove from the input map. + * @returns A new {@code FirestoreFunction} representing the 'mapRemove' operation. */ - static of(value: firestore.VectorValue): Constant; + mapRemove(keyExpr: firestore.Expr): FunctionExpr; + mapRemove(stringExpr: firestore.Expr | string): FunctionExpr { + return new FunctionExpr('map_remove', [ + this, + valueToDefaultExpr(stringExpr), + ]); + } /** - * Creates a `Constant` instance for a Firestore proto value. + * @beta * - * @param value The Firestore proto value. - * @return A new `Constant` instance. + * Creates an expression that merges multiple map values. + * + * ``` + * // 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 }, cond(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 {@code FirestoreFunction} representing the 'mapMerge' operation. */ - static of(value: api.IValue): Constant; - static of(value: any): Constant { - return new Constant(value); + mapMerge( + secondMap: Record | firestore.Expr, + ...otherMaps: Array | firestore.Expr> + ): FunctionExpr { + const secondMapExpr = valueToDefaultExpr(secondMap); + const otherMapExprs = otherMaps.map(valueToDefaultExpr); + return new FunctionExpr('map_merge', [ + this, + secondMapExpr, + ...otherMapExprs, + ]); } /** - * Creates a `Constant` instance for a VectorValue value. + * Creates an {@link Ordering} that sorts documents in ascending order based on this expression. * * ```typescript - * // Create a Constant instance for a vector value - * const vectorConstant = Constant.ofVector([1, 2, 3]); + * // Sort documents by the 'name' field in ascending order + * pipeline().collection("users") + * .sort(field("name").ascending()); * ``` * - * @param value The VectorValue value. - * @return A new `Constant` instance. + * @return A new `Ordering` for ascending sorting. */ - static vector(value: Array | firestore.VectorValue): Constant { - if (value instanceof VectorValue) { - return new Constant(value); - } else { - return new Constant(new VectorValue(value as Array)); - } + ascending(): Ordering { + return ascending(this); } - _toProto(serializer: Serializer): api.IValue { - if (isFirestoreValue(this.value)) { - return this.value; - } + /** + * Creates an {@link Ordering} that sorts documents in descending order based on this expression. + * + * ```typescript + * // Sort documents by the 'createdAt' field in descending order + * firestore.pipeline().collection("users") + * .sort(field("createdAt").descending()); + * ``` + * + * @return A new `Ordering` for descending sorting. + */ + descending(): Ordering { + return descending(this); + } - return serializer.encodeValue(this.value)!; + /** + * 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. + * + * ```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. + * @return A new {@link ExprWithAlias} that wraps this + * expression and associates it with the provided alias. + */ + as(name: string): firestore.ExprWithAlias { + return new ExprWithAlias(this, name); } } /** * @beta * - * This class defines the base class for Firestore {@link 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 and}, {@link eq}, - * or the methods on {@link Expr} ({@link Expr#eq}, {@link Expr#lt}, etc) to construct new Function instances. + * A class that represents an aggregate function. */ -export class Function extends Expr { - exprType: ExprType = 'Function'; +export class AggregateFunction extends firestore.AggregateFunction { + exprType: firestore.ExprType = 'AggregateFunction'; + + /** + * @internal + * @private + * Indicates if this expression was created from a literal value passed + * by the caller. + */ + _createdFromLiteral = false; + constructor( private name: string, private params: Expr[] ) { - super(); + super(name, params); + } + + /** + * Assigns an alias to this AggregateFunction. The alias specifies the name that + * the aggregated value will have in the output document. + * + * ```typescript + * // Calculate the average price of all items and assign it the alias "averagePrice". + * firestore.pipeline().collection("items") + * .aggregate(field("price").avg().as("averagePrice")); + * ``` + * + * @param name The alias to assign to this AggregateFunction. + * @return A new {@link AggregateWithAlias} that wraps this + * AggregateFunction and associates it with the provided alias. + */ + as(name: string): AggregateWithAlias { + return new AggregateWithAlias(this, name); } + /** + * @private + * @internal + */ _toProto(serializer: Serializer): api.IValue { return { functionValue: { name: this.name, - args: this.params.map(p => serializer.encodeValue(p)!), + args: this.params.map(p => p._toProto(serializer)), }, }; } -} -/** - * @beta - */ -export class Add extends Function { - constructor( - private left: Expr, - private right: Expr - ) { - super('add', [left, right]); - } + _protoValueType = 'ProtoValue' as const; } /** * @beta + * + * An AggregateFunction with alias. */ -export class Subtract extends Function { +export class AggregateWithAlias extends firestore.AggregateWithAlias { constructor( - private left: Expr, - private right: Expr + readonly aggregate: AggregateFunction, + readonly alias: string ) { - super('subtract', [left, right]); + super(); } -} -/** - * @beta - */ -export class Multiply extends Function { - constructor( - private left: Expr, - private right: Expr - ) { - super('multiply', [left, right]); - } + /** + * @internal + * @private + * Indicates if this expression was created from a literal value passed + * by the caller. + */ + _createdFromLiteral = false; } /** * @beta */ -export class Divide extends Function { - constructor( - private left: Expr, - private right: Expr - ) { - super('divide', [left, right]); - } -} +export class ExprWithAlias implements firestore.Selectable { + exprType: firestore.ExprType = 'ExprWithAlias'; + selectable = true as const; + + /** + * @internal + * @private + * Indicates if this expression was created from a literal value passed + * by the caller. + */ + _createdFromLiteral = false; -/** - * @beta - */ -export class Mod extends Function { constructor( - private left: Expr, - private right: Expr - ) { - super('mod', [left, right]); - } + readonly expr: Expr, + readonly alias: string + ) {} } -// /** -// * @beta -// */ -// export class BitAnd extends Function { -// constructor( -// private left: Expr, -// private right: Expr -// ) { -// super('bit_and', [left, right]); -// } -// } -// -// /** -// * @beta -// */ -// export class BitOr extends Function { -// constructor( -// private left: Expr, -// private right: Expr -// ) { -// super('bit_or', [left, right]); -// } -// } -// -// /** -// * @beta -// */ -// export class BitXor extends Function { -// constructor( -// private left: Expr, -// private right: Expr -// ) { -// super('bit_xor', [left, right]); -// } -// } -// -// /** -// * @beta -// */ -// export class BitNot extends Function { -// constructor(private operand: Expr) { -// super('bit_not', [operand]); -// } -// } -// -// /** -// * @beta -// */ -// export class BitLeftShift extends Function { -// constructor( -// private left: Expr, -// private right: Expr -// ) { -// super('bit_left_shift', [left, right]); -// } -// } -// -// /** -// * @beta -// */ -// export class BitRightShift extends Function { -// constructor( -// private left: Expr, -// private right: Expr -// ) { -// super('bit_right_shift', [left, right]); -// } -// } - /** - * @beta + * @internal */ -export class Eq extends Function implements FilterCondition { - constructor( - private left: Expr, - private right: Expr - ) { - super('eq', [left, right]); +class ListOfExprs extends Expr { + exprType: firestore.ExprType = 'ListOfExprs'; + + constructor(private exprs: Expr[]) { + super(); } - filterable = true as const; -} -/** - * @beta - */ -class Neq extends Function implements FilterCondition { - constructor( - private left: Expr, - private right: Expr - ) { - super('neq', [left, right]); + /** + * @private + * @internal + */ + _toProto(serializer: Serializer): api.IValue { + return { + arrayValue: { + values: this.exprs.map(p => p._toProto(serializer)!), + }, + }; } - filterable = true as const; } /** * @beta - */ -class Lt extends Function implements FilterCondition { - constructor( - private left: Expr, - private right: Expr - ) { - super('lt', [left, right]); + * + * Represents a reference to a field in a Firestore document, or outputs of a {@link Pipeline} stage. + * + *

    Field references are used to access document field values in expressions and to specify fields + * for sorting, filtering, and projecting data in Firestore pipelines. + * + *

    You can create a `Field` instance using the static {@link #of} method: + * + * ```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"); + * ``` + */ +export class Field extends Expr implements firestore.Selectable { + readonly exprType: firestore.ExprType = 'Field'; + selectable = true as const; + + /** + * @internal + * @private + * @hideconstructor + * @param fieldPath + */ + constructor(private fieldPath: FieldPath) { + super(); + } + + fieldName(): string { + return this.fieldPath.formattedName; + } + + get alias(): string { + return this.fieldName(); + } + + get expr(): Expr { + return this; + } + + /** + * @private + * @internal + */ + _toProto(serializer: Serializer): api.IValue { + return { + fieldReferenceValue: this.fieldPath.formattedName, + }; } - filterable = true as const; } /** - * @beta + * Creates a {@code Field} instance representing the field at the given path. + * + * The path can be a simple field name (e.g., "name") or a dot-separated path to a nested field + * (e.g., "address.city"). + * + * ```typescript + * // Create a Field instance for the 'title' field + * const titleField = field("title"); + * + * // Create a Field instance for a nested field 'author.firstName' + * const authorFirstNameField = field("author.firstName"); + * ``` + * + * @param field The path to the field. + * @return A new {@code Field} instance representing the specified field. */ -class Lte extends Function implements FilterCondition { - constructor( - private left: Expr, - private right: Expr - ) { - super('lte', [left, right]); +export function field(field: string | firestore.FieldPath): Field { + if (typeof field === 'string') { + if ('__name__' === field) { + return new Field(FieldPath.documentId()); + } + return new Field(FieldPath.fromArgument(field)); + } else { + return new Field(field as unknown as FieldPath); } - filterable = true as const; } /** * @beta + * + * Represents a constant value that can be used in a Firestore pipeline expression. + * + * You can create a `Constant` instance using the static {@link #of} method: + * + * ```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 Gt extends Function implements FilterCondition { - constructor( - private left: Expr, - private right: Expr - ) { - super('gt', [left, right]); +export class Constant extends Expr { + readonly exprType: firestore.ExprType = 'Constant'; + + private protoValue?: api.IValue; + + /** + * @private + * @internal + * @hideconstructor + * @param value The value of the constant. + */ + constructor(private value: unknown) { + super(); + } + + /** + * @private + * @internal + */ + static _fromProto(value: api.IValue): Constant { + const result = new Constant(value); + result.protoValue = value; + return result; + } + + /** + * @private + * @internal + */ + _toProto(serializer: Serializer): api.IValue { + if (isFirestoreValue(this.value)) { + return this.value; + } + + return serializer.encodeValue(this.value)!; } - filterable = true as const; } /** - * @beta + * Creates a `Constant` instance for a number value. + * + * @param value The number value. + * @return A new `Constant` instance. */ -class Gte extends Function implements FilterCondition { - constructor( - private left: Expr, - private right: Expr - ) { - super('gte', [left, right]); - } - filterable = true as const; -} +export function constant(value: number): Constant; /** - * @beta + * Creates a `Constant` instance for a string value. + * + * @param value The string value. + * @return A new `Constant` instance. */ -class ArrayConcat extends Function { - constructor( - private array: Expr, - private elements: Expr[] - ) { - super('array_concat', [array, ...elements]); - } -} +export function constant(value: string): Constant; /** - * @beta + * Creates a `Constant` instance for a boolean value. + * + * @param value The boolean value. + * @return A new `Constant` instance. */ -class ArrayReverse extends Function { - constructor(private array: Expr) { - super('array_reverse', [array]); - } -} +export function constant(value: boolean): Constant; /** - * @beta + * Creates a `Constant` instance for a null value. + * + * @param value The null value. + * @return A new `Constant` instance. */ -class ArrayContains extends Function implements FilterCondition { - constructor( - private array: Expr, - private element: Expr - ) { - super('array_contains', [array, element]); - } - filterable = true as const; -} +export function constant(value: null): Constant; /** - * @beta + * Creates a `Constant` instance for a GeoPoint value. + * + * @param value The GeoPoint value. + * @return A new `Constant` instance. */ -class ArrayContainsAll extends Function implements FilterCondition { - constructor( - private array: Expr, - private values: Expr[] - ) { - super('array_contains_all', [array, new ListOfExprs(values)]); - } - filterable = true as const; -} +export function constant(value: firestore.GeoPoint): Constant; /** - * @beta + * Creates a `Constant` instance for a Timestamp value. + * + * @param value The Timestamp value. + * @return A new `Constant` instance. */ -class ArrayContainsAny extends Function implements FilterCondition { - constructor( - private array: Expr, - private values: Expr[] - ) { - super('array_contains_any', [array, new ListOfExprs(values)]); - } - filterable = true as const; -} +export function constant(value: firestore.Timestamp): Constant; /** - * @beta + * Creates a `Constant` instance for a Date value. + * + * @param value The Date value. + * @return A new `Constant` instance. */ -class ArrayLength extends Function { - constructor(private array: Expr) { - super('array_length', [array]); - } +export function constant(value: Date): Constant; + +/** + * Creates a `Constant` instance for a Buffer | Uint8Array value. + * + * @param value The Buffer | Uint8Array value. + * @return A new `Constant` instance. + */ +export function constant(value: Buffer | Uint8Array): Constant; + +/** + * Creates a `Constant` instance for a DocumentReference value. + * + * @param value The DocumentReference value. + * @return A new `Constant` instance. + */ +export function constant(value: firestore.DocumentReference): Constant; + +/** + * Creates a `Constant` instance for a Firestore proto value. + * For internal use only. + * @private + * @internal + * @param value The Firestore proto value. + * @return A new `Constant` instance. + */ +export function constant(value: api.IValue): Constant; + +/** + * Creates a `Constant` instance for a VectorValue value. + * + * @param value The VectorValue value. + * @return A new `Constant` instance. + */ +export function constant(value: firestore.VectorValue): Constant; + +export function constant(value: unknown): Constant { + return new Constant(value); } /** - * @beta + * Creates a `Constant` instance for a VectorValue value. + * + * ```typescript + * // Create a Constant instance for a vector value + * const vectorConstant = constantVector([1, 2, 3]); + * ``` + * + * @param value The VectorValue value. + * @return A new `Constant` instance. */ -class ArrayElement extends Function { - constructor() { - super('array_element', []); +export function constantVector( + value: number[] | firestore.VectorValue +): Constant { + if (value instanceof VectorValue) { + return new Constant(value); + } else { + return new Constant(new VectorValue(value as number[])); } } /** - * @beta + * Internal only + * @internal + * @private */ -class EqAny extends Function implements FilterCondition { - constructor( - private left: Expr, - private others: Expr[] - ) { - super('eq_any', [left, new ListOfExprs(others)]); +export class MapValue extends Expr { + constructor(private plainObject: Map) { + super(); + } + + exprType: firestore.ExprType = 'Constant'; + + _toProto(serializer: Serializer): api.IValue { + return serializer.encodeValue(this.plainObject); } - filterable = true as const; } /** * @beta + * + * This class defines the base class for Firestore {@link 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 and}, {@link eq}, + * or the methods on {@link Expr} ({@link Expr#eq}, {@link Expr#lt}, etc.) to construct new Function instances. */ -class NotEqAny extends Function implements FilterCondition { +export class FunctionExpr extends Expr { + readonly exprType: firestore.ExprType = 'Function'; + constructor( - private left: Expr, - private others: Expr[] + private name: string, + private params: firestore.Expr[] ) { - super('not_eq_any', [left, new ListOfExprs(others)]); + super(); + } + + /** + * @private + * @internal + */ + _toProto(serializer: Serializer): api.IValue { + return { + functionValue: { + name: this.name, + args: this.params.map(p => cast(p)._toProto(serializer)), + }, + }; } - filterable = true as const; } /** * @beta + * + * An interface that represents a filter condition. */ -class IsNan extends Function implements FilterCondition { - constructor(private expr: Expr) { - super('is_nan', [expr]); +export class BooleanExpr extends FunctionExpr implements firestore.BooleanExpr { + filterable: true = true as const; + + /** + * Creates an aggregation that finds the count of input documents satisfying + * this boolean expression. + * + * ```typescript + * // Find the count of documents with a score greater than 90 + * field("score").gt(90).countIf().as("highestScore"); + * ``` + * + * @return A new `AggregateFunction` representing the 'countIf' aggregation. + */ + countIf(): AggregateFunction { + return new AggregateFunction('count_if', [this]); + } + + /** + * Creates an expression that negates this boolean expression. + * + * ```typescript + * // Find documents where the 'tags' field does not contain 'completed' + * field("tags").arrayContains("completed").not(); + * ``` + * + * @return A new {@code Expr} representing the negated filter condition. + */ + not(): BooleanExpr { + return new BooleanExpr('not', [this]); } - filterable = true as const; } /** * @beta + * Creates an aggregation that counts the number of stage inputs where the provided + * boolean expression evaluates to true. + * + * ```typescript + * // Count the number of documents where 'is_active' field equals true + * countIf(field("is_active").eq(true)).as("numActiveDocuments"); + * ``` + * + * @param booleanExpr - The boolean expression to evaluate on each input. + * @returns A new `AggregateFunction` representing the 'countIf' aggregation. */ -class Exists extends Function implements FilterCondition { - constructor(private expr: Expr) { - super('exists', [expr]); - } - filterable = true as const; +export function countIf(booleanExpr: firestore.BooleanExpr): AggregateFunction { + return new AggregateFunction('count_if', [cast(booleanExpr)]); } /** * @beta + * Creates an expression that return a pseudo-random value of type double in the + * range of [0, 1), inclusive of 0 and exclusive of 1. + * + * @returns A new `Expr` representing the 'rand' function. */ -class Not extends Function implements FilterCondition { - constructor(private expr: Expr) { - super('not', [expr]); - } - filterable = true as const; +export function rand(): FunctionExpr { + return new FunctionExpr('rand', []); } /** * @beta + * + * Creates an expression that applies a bitwise AND operation between a field and a constant. + * + * ```typescript + * // Calculate the bitwise AND of 'field1' and 0xFF. + * bitAnd("field1", 0xFF); + * ``` + * + * @param field The left operand field name. + * @param otherBits A constant representing bits. + * @return A new {@code Expr} representing the bitwise AND operation. */ -class And extends Function implements FilterCondition { - constructor(private conditions: FilterExpr[]) { - super('and', conditions); - } - - filterable = true as const; -} - +export function bitAnd( + field: string, + otherBits: number | Buffer | Uint8Array +): FunctionExpr; /** * @beta + * + * Creates an expression that applies a bitwise AND operation between a field and an expression. + * + * ```typescript + * // Calculate the bitwise AND of 'field1' and 'field2'. + * bitAnd("field1", field("field2")); + * ``` + * + * @param field The left operand field name. + * @param bitsExpression An expression that returns bits when evaluated. + * @return A new {@code Expr} representing the bitwise AND operation. */ -class Or extends Function implements FilterCondition { - constructor(private conditions: FilterExpr[]) { - super('or', conditions); - } - filterable = true as const; -} - +export function bitAnd( + field: string, + bitsExpression: firestore.Expr +): FunctionExpr; /** * @beta + * + * Creates an expression that applies a bitwise AND operation between an expression and a constant. + * + * ```typescript + * // Calculate the bitwise AND of 'field1' and 0xFF. + * bitAnd(field("field1"), 0xFF); + * ``` + * + * @param bitsExpression An expression returning bits. + * @param otherBits A constant representing bits. + * @return A new {@code Expr} representing the bitwise AND operation. */ -class Xor extends Function implements FilterCondition { - constructor(private conditions: FilterExpr[]) { - super('xor', conditions); - } - filterable = true as const; -} - +export function bitAnd( + bitsExpression: firestore.Expr, + otherBits: number | Buffer | Uint8Array +): FunctionExpr; /** * @beta + * + * Creates an expression that applies a bitwise AND operation between two expressions. + * + * ```typescript + * // Calculate the bitwise AND of 'field1' and 'field2'. + * bitAnd(field("field1"), field("field2")); + * ``` + * + * @param bitsExpression An expression that returns bits when evaluated. + * @param otherBitsExpression An expression that returns bits when evaluated. + * @return A new {@code Expr} representing the bitwise AND operation. */ -class Cond extends Function implements FilterCondition { - constructor( - private condition: FilterExpr, - private thenExpr: Expr, - private elseExpr: Expr - ) { - super('cond', [condition, thenExpr, elseExpr]); - } - filterable = true as const; +export function bitAnd( + bitsExpression: firestore.Expr, + otherBitsExpression: firestore.Expr +): FunctionExpr; +export function bitAnd( + bits: string | firestore.Expr, + bitsOrExpression: number | firestore.Expr | Buffer | Uint8Array +): FunctionExpr { + return fieldOrExpression(bits).bitAnd(valueToDefaultExpr(bitsOrExpression)); } /** * @beta + * + * Creates an expression that applies a bitwise OR operation between a field and a constant. + * + * ```typescript + * // Calculate the bitwise OR of 'field1' and 0xFF. + * bitOr("field1", 0xFF); + * ``` + * + * @param field The left operand field name. + * @param otherBits A constant representing bits. + * @return A new {@code Expr} representing the bitwise OR operation. */ -class LogicalMaximum extends Function { - constructor( - private left: Expr, - private right: Expr - ) { - super('logical_maximum', [left, right]); - } -} - +export function bitOr( + field: string, + otherBits: number | Buffer | Uint8Array +): FunctionExpr; /** * @beta + * + * Creates an expression that applies a bitwise OR operation between a field and an expression. + * + * ```typescript + * // Calculate the bitwise OR of 'field1' and 'field2'. + * bitOr("field1", field("field2")); + * ``` + * + * @param field The left operand field name. + * @param bitsExpression An expression that returns bits when evaluated. + * @return A new {@code Expr} representing the bitwise OR operation. */ -class LogicalMinimum extends Function { - constructor( - private left: Expr, - private right: Expr - ) { - super('logical_minimum', [left, right]); - } -} - +export function bitOr( + field: string, + bitsExpression: firestore.Expr +): FunctionExpr; /** * @beta + * + * Creates an expression that applies a bitwise OR operation between an expression and a constant. + * + * ```typescript + * // Calculate the bitwise OR of 'field1' and 0xFF. + * bitOr(field("field1"), 0xFF); + * ``` + * + * @param bitsExpression An expression returning bits. + * @param otherBits A constant representing bits. + * @return A new {@code Expr} representing the bitwise OR operation. */ -export class Reverse extends Function { - constructor(private value: Expr) { - super('reverse', [value]); - } -} - +export function bitOr( + bitsExpression: firestore.Expr, + otherBits: number | Buffer | Uint8Array +): FunctionExpr; /** * @beta + * + * Creates an expression that applies a bitwise OR operation between two expressions. + * + * ```typescript + * // Calculate the bitwise OR of 'field1' and 'field2'. + * bitOr(field("field1"), field("field2")); + * ``` + * + * @param bitsExpression An expression that returns bits when evaluated. + * @param otherBitsExpression An expression that returns bits when evaluated. + * @return A new {@code Expr} representing the bitwise OR operation. */ -export class ReplaceFirst extends Function { - constructor( - private value: Expr, - private find: Expr, - private replace: Expr - ) { - super('replace_first', [value, find, replace]); - } +export function bitOr( + bitsExpression: firestore.Expr, + otherBitsExpression: firestore.Expr +): FunctionExpr; +export function bitOr( + bits: string | firestore.Expr, + bitsOrExpression: number | firestore.Expr | Buffer | Uint8Array +): FunctionExpr { + return fieldOrExpression(bits).bitOr(valueToDefaultExpr(bitsOrExpression)); } /** * @beta + * + * Creates an expression that applies a bitwise XOR operation between a field and a constant. + * + * ```typescript + * // Calculate the bitwise XOR of 'field1' and 0xFF. + * bitXor("field1", 0xFF); + * ``` + * + * @param field The left operand field name. + * @param otherBits A constant representing bits. + * @return A new {@code Expr} representing the bitwise XOR operation. */ -export class ReplaceAll extends Function { - constructor( - private value: Expr, - private find: Expr, - private replace: Expr - ) { - super('replace_all', [value, find, replace]); - } -} - +export function bitXor( + field: string, + otherBits: number | Buffer | Uint8Array +): FunctionExpr; /** * @beta + * + * Creates an expression that applies a bitwise XOR operation between a field and an expression. + * + * ```typescript + * // Calculate the bitwise XOR of 'field1' and 'field2'. + * bitXor("field1", field("field2")); + * ``` + * + * @param field The left operand field name. + * @param bitsExpression An expression that returns bits when evaluated. + * @return A new {@code Expr} representing the bitwise XOR operation. */ -export class CharLength extends Function { - constructor(private value: Expr) { - super('char_length', [value]); - } -} - +export function bitXor( + field: string, + bitsExpression: firestore.Expr +): FunctionExpr; +/** + * @beta + * + * Creates an expression that applies a bitwise XOR operation between an expression and a constant. + * + * ```typescript + * // Calculate the bitwise XOR of 'field1' and 0xFF. + * bitXor(field("field1"), 0xFF); + * ``` + * + * @param bitsExpression An expression returning bits. + * @param otherBits A constant representing bits. + * @return A new {@code Expr} representing the bitwise XOR operation. + */ +export function bitXor( + bitsExpression: firestore.Expr, + otherBits: number | Buffer | Uint8Array +): FunctionExpr; /** * @beta + * + * Creates an expression that applies a bitwise XOR operation between two expressions. + * + * ```typescript + * // Calculate the bitwise XOR of 'field1' and 'field2'. + * bitXor(field("field1"), field("field2")); + * ``` + * + * @param bitsExpression An expression that returns bits when evaluated. + * @param otherBitsExpression An expression that returns bits when evaluated. + * @return A new {@code Expr} representing the bitwise XOR operation. */ -export class ByteLength extends Function { - constructor(private value: Expr) { - super('byte_length', [value]); - } +export function bitXor( + bitsExpression: firestore.Expr, + otherBitsExpression: firestore.Expr +): FunctionExpr; +export function bitXor( + bits: string | firestore.Expr, + bitsOrExpression: number | firestore.Expr | Buffer | Uint8Array +): FunctionExpr { + return fieldOrExpression(bits).bitXor(valueToDefaultExpr(bitsOrExpression)); } /** * @beta + * + * Creates an expression that applies a bitwise NOT operation to a field. + * + * ```typescript + * // Calculate the bitwise NOT of 'field1'. + * bitNot("field1"); + * ``` + * + * @param field The operand field name. + * @return A new {@code Expr} representing the bitwise NOT operation. */ -class Like extends Function implements FilterCondition { - constructor( - private expr: Expr, - private pattern: Expr - ) { - super('like', [expr, pattern]); - } - filterable = true as const; +export function bitNot(field: string): FunctionExpr; +/** + * @beta + * + * Creates an expression that applies a bitwise NOT operation to an expression. + * + * ```typescript + * // Calculate the bitwise NOT of 'field1'. + * bitNot(field("field1")); + * ``` + * + * @param bitsValueExpression An expression that returns bits when evaluated. + * @return A new {@code Expr} representing the bitwise NOT operation. + */ +export function bitNot(bitsValueExpression: firestore.Expr): FunctionExpr; +export function bitNot(bits: string | firestore.Expr): FunctionExpr { + return fieldOrExpression(bits).bitNot(); } /** * @beta + * + * Creates an expression that applies a bitwise left shift operation between a field and a constant. + * + * ```typescript + * // Calculate the bitwise left shift of 'field1' by 2 bits. + * bitLeftShift("field1", 2); + * ``` + * + * @param field The left operand field name. + * @param y The right operand constant representing the number of bits to shift. + * @return A new {@code Expr} representing the bitwise left shift operation. */ -class RegexContains extends Function implements FilterCondition { - constructor( - private expr: Expr, - private pattern: Expr - ) { - super('regex_contains', [expr, pattern]); - } - filterable = true as const; +export function bitLeftShift(field: string, y: number): FunctionExpr; +/** + * @beta + * + * Creates an expression that applies a bitwise left shift operation between a field and an expression. + * + * ```typescript + * // Calculate the bitwise left shift of 'field1' by 'field2' bits. + * bitLeftShift("field1", field("field2")); + * ``` + * + * @param field The left operand field name. + * @param numberExpr The right operand expression representing the number of bits to shift. + * @return A new {@code Expr} representing the bitwise left shift operation. + */ +export function bitLeftShift( + field: string, + numberExpr: firestore.Expr +): FunctionExpr; +/** + * @beta + * + * Creates an expression that applies a bitwise left shift operation between an expression and a constant. + * + * ```typescript + * // Calculate the bitwise left shift of 'field1' by 2 bits. + * bitLeftShift(field("field1"), 2); + * ``` + * + * @param xValue An expression returning bits. + * @param y The right operand constant representing the number of bits to shift. + * @return A new {@code Expr} representing the bitwise left shift operation. + */ +export function bitLeftShift(xValue: firestore.Expr, y: number): FunctionExpr; +/** + * @beta + * + * Creates an expression that applies a bitwise left shift operation between two expressions. + * + * ```typescript + * // Calculate the bitwise left shift of 'field1' by 'field2' bits. + * bitLeftShift(field("field1"), field("field2")); + * ``` + * + * @param xValue An expression returning bits. + * @param numberExpr The right operand expression representing the number of bits to shift. + * @return A new {@code Expr} representing the bitwise left shift operation. + */ +export function bitLeftShift( + xValue: firestore.Expr, + numberExpr: firestore.Expr +): FunctionExpr; +export function bitLeftShift( + xValue: string | firestore.Expr, + numberExpr: number | firestore.Expr +): FunctionExpr { + return fieldOrExpression(xValue).bitLeftShift(valueToDefaultExpr(numberExpr)); } /** * @beta + * + * Creates an expression that applies a bitwise right shift operation between a field and a constant. + * + * ```typescript + * // Calculate the bitwise right shift of 'field1' by 2 bits. + * bitRightShift("field1", 2); + * ``` + * + * @param field The left operand field name. + * @param y The right operand constant representing the number of bits to shift. + * @return A new {@code Expr} representing the bitwise right shift operation. */ -class RegexMatch extends Function implements FilterCondition { - constructor( - private expr: Expr, - private pattern: Expr - ) { - super('regex_match', [expr, pattern]); - } - filterable = true as const; +export function bitRightShift(field: string, y: number): FunctionExpr; +/** + * @beta + * + * Creates an expression that applies a bitwise right shift operation between a field and an expression. + * + * ```typescript + * // Calculate the bitwise right shift of 'field1' by 'field2' bits. + * bitRightShift("field1", field("field2")); + * ``` + * + * @param field The left operand field name. + * @param numberExpr The right operand expression representing the number of bits to shift. + * @return A new {@code Expr} representing the bitwise right shift operation. + */ +export function bitRightShift( + field: string, + numberExpr: firestore.Expr +): FunctionExpr; +/** + * @beta + * + * Creates an expression that applies a bitwise right shift operation between an expression and a constant. + * + * ```typescript + * // Calculate the bitwise right shift of 'field1' by 2 bits. + * bitRightShift(field("field1"), 2); + * ``` + * + * @param xValue An expression returning bits. + * @param y The right operand constant representing the number of bits to shift. + * @return A new {@code Expr} representing the bitwise right shift operation. + */ +export function bitRightShift(xValue: firestore.Expr, y: number): FunctionExpr; +/** + * @beta + * + * Creates an expression that applies a bitwise right shift operation between two expressions. + * + * ```typescript + * // Calculate the bitwise right shift of 'field1' by 'field2' bits. + * bitRightShift(field("field1"), field("field2")); + * ``` + * + * @param xValue An expression returning bits. + * @param numberExpr The right operand expression representing the number of bits to shift. + * @return A new {@code Expr} representing the bitwise right shift operation. + */ +export function bitRightShift( + xValue: firestore.Expr, + numberExpr: firestore.Expr +): FunctionExpr; +export function bitRightShift( + xValue: string | firestore.Expr, + numberExpr: number | firestore.Expr +): FunctionExpr { + return fieldOrExpression(xValue).bitRightShift( + valueToDefaultExpr(numberExpr) + ); } /** * @beta + * Creates an expression that indexes into an array from the beginning or end + * and return the element. If the offset exceeds the array length, an error is + * returned. A negative offset, starts from the end. + * + * ```typescript + * // Return the value in the tags field array at index 1. + * arrayOffset('tags', 1); + * ``` + * + * @param arrayField The name of the array field. + * @param offset The index of the element to return. + * @return A new Expr representing the 'arrayOffset' operation. */ -class StrContains extends Function implements FilterCondition { - constructor( - private expr: Expr, - private substring: Expr - ) { - super('str_contains', [expr, substring]); - } - filterable = true as const; -} +export function arrayOffset(arrayField: string, offset: number): FunctionExpr; /** * @beta + * Creates an expression that indexes into an array from the beginning or end + * and return the element. If the offset exceeds the array length, an error is + * returned. A negative offset, starts from the end. + * + * ```typescript + * // Return the value in the tags field array at index specified by field + * // 'favoriteTag'. + * arrayOffset('tags', field('favoriteTag')); + * ``` + * + * @param arrayField The name of the array field. + * @param offsetExpr An Expr evaluating to the index of the element to return. + * @return A new Expr representing the 'arrayOffset' operation. */ -class StartsWith extends Function implements FilterCondition { - constructor( - private expr: Expr, - private prefix: Expr - ) { - super('starts_with', [expr, prefix]); - } - filterable = true as const; -} +export function arrayOffset( + arrayField: string, + offsetExpr: firestore.Expr +): FunctionExpr; /** * @beta + * Creates an expression that indexes into an array from the beginning or end + * and return the element. If the offset exceeds the array length, an error is + * returned. A negative offset, starts from the end. + * + * ```typescript + * // Return the value in the tags field array at index 1. + * arrayOffset(field('tags'), 1); + * ``` + * + * @param arrayExpression An Expr evaluating to an array. + * @param offset The index of the element to return. + * @return A new Expr representing the 'arrayOffset' operation. */ -class EndsWith extends Function implements FilterCondition { - constructor( - private expr: Expr, - private suffix: Expr - ) { - super('ends_with', [expr, suffix]); - } - filterable = true as const; -} +export function arrayOffset( + arrayExpression: firestore.Expr, + offset: number +): FunctionExpr; /** * @beta + * Creates an expression that indexes into an array from the beginning or end + * and return the element. If the offset exceeds the array length, an error is + * returned. A negative offset, starts from the end. + * + * ```typescript + * // Return the value in the tags field array at index specified by field + * // 'favoriteTag'. + * arrayOffset(field('tags'), field('favoriteTag')); + * ``` + * + * @param arrayExpression An Expr evaluating to an array. + * @param offsetExpr An Expr evaluating to the index of the element to return. + * @return A new Expr representing the 'arrayOffset' operation. */ -class ToLower extends Function { - constructor(private expr: Expr) { - super('to_lower', [expr]); - } +export function arrayOffset( + arrayExpression: firestore.Expr, + offsetExpr: firestore.Expr +): FunctionExpr; +export function arrayOffset( + array: firestore.Expr | string, + offset: firestore.Expr | number +): FunctionExpr { + return fieldOrExpression(array).arrayOffset(valueToDefaultExpr(offset)); } /** * @beta + * + * Creates an expression that checks if a given expression produces an error. + * + * ```typescript + * // Check if the result of a calculation is an error + * isError(field("title").arrayContains(1)); + * ``` + * + * @param value The expression to check. + * @return A new {@code Expr} representing the 'isError' check. */ -class ToUpper extends Function { - constructor(private expr: Expr) { - super('to_upper', [expr]); - } +export function isError(value: firestore.Expr): BooleanExpr { + const expr: Expr = cast(value); + return expr.isError(); } /** * @beta + * + * Creates an expression that returns the `catch` argument if there is an + * error, else return the result of the `try` argument evaluation. + * + * ```typescript + * // Returns the first item in the title field arrays, or returns + * // the entire title field if the array is empty or the field is another type. + * ifError(field("title").arrayOffset(0), field("title")); + * ``` + * + * @param tryExpr The try expression. + * @param catchExpr The catch expression that will be evaluated and + * returned if the tryExpr produces an error. + * @return A new {@code Expr} representing the 'ifError' operation. */ -class Trim extends Function { - constructor(private expr: Expr) { - super('trim', [expr]); - } -} +export function ifError( + tryExpr: firestore.Expr, + catchExpr: firestore.Expr +): FunctionExpr; /** * @beta + * + * Creates an expression that returns the `catch` argument if there is an + * error, else return the result of the `try` argument evaluation. + * + * ```typescript + * // Returns the first item in the title field arrays, or returns + * // "Default Title" + * ifError(field("title").arrayOffset(0), "Default Title"); + * ``` + * + * @param tryExpr The try expression. + * @param catchValue The value that will be returned if the tryExpr produces an + * error. + * @return A new {@code Expr} representing the 'ifError' operation. */ -class StrConcat extends Function { - constructor( - private first: Expr, - private rest: Expr[] - ) { - super('str_concat', [first, ...rest]); - } +export function ifError( + tryExpr: firestore.Expr, + catchValue: unknown +): FunctionExpr; +export function ifError( + tryExpr: firestore.Expr, + catchValue: unknown +): FunctionExpr { + const expr: Expr = cast(tryExpr); + return expr.ifError(valueToDefaultExpr(catchValue)); } /** * @beta + * + * Creates an expression that returns `true` if a value is absent. Otherwise, + * returns `false` even if the value is `null`. + * + * ```typescript + * // Check if the field `value` is absent. + * isAbsent(field("value")); + * ``` + * + * @param value The expression to check. + * @return A new {@code Expr} representing the 'isAbsent' check. */ -class MapGet extends Function { - constructor(map: Expr, name: string) { - super('map_get', [map, Constant.of(name)]); - } -} +export function isAbsent(value: firestore.Expr): BooleanExpr; /** * @beta + * + * Creates an expression that returns `true` if a field is absent. Otherwise, + * returns `false` even if the field value is `null`. + * + * ```typescript + * // Check if the field `value` is absent. + * isAbsent("value"); + * ``` + * + * @param field The field to check. + * @return A new {@code Expr} representing the 'isAbsent' check. */ -class Count extends Function implements Accumulator { - accumulator = true as const; - constructor( - private value: Expr | undefined, - private distinct: boolean - ) { - super('count', value === undefined ? [] : [value]); - } +export function isAbsent(field: string): BooleanExpr; +export function isAbsent(value: firestore.Expr | string): BooleanExpr { + return fieldOrExpression(value).isAbsent(); } /** * @beta + * + * Creates an expression that checks if an expression evaluates to 'NaN' (Not a Number). + * + * ```typescript + * // Check if the result of a calculation is NaN + * isNull(field("value").divide(0)); + * ``` + * + * @param value The expression to check. + * @return A new {@code Expr} representing the 'isNull' check. */ -class Sum extends Function implements Accumulator { - accumulator = true as const; - constructor( - private value: Expr, - private distinct: boolean - ) { - super('sum', [value]); - } -} +export function isNull(value: firestore.Expr): BooleanExpr; /** * @beta + * + * Creates an expression that checks if a field's value evaluates to 'NaN' (Not a Number). + * + * ```typescript + * // Check if the result of a calculation is NaN + * isNull("value"); + * ``` + * + * @param value The name of the field to check. + * @return A new {@code Expr} representing the 'isNull' check. */ -class Avg extends Function implements Accumulator { - accumulator = true as const; - constructor( - private value: Expr, - private distinct: boolean - ) { - super('avg', [value]); - } +export function isNull(value: string): BooleanExpr; +export function isNull(value: firestore.Expr | string): BooleanExpr { + return fieldOrExpression(value).isNull(); } /** * @beta + * + * Creates an expression that checks if tbe result of an expression is not null. + * + * ```typescript + * // Check if the value of the 'name' field is not null + * isNotNull(field("name")); + * ``` + * + * @param value The expression to check. + * @return A new {@code Expr} representing the 'isNotNull' check. */ -class Minimum extends Function implements Accumulator { - accumulator = true as const; - constructor( - private value: Expr, - private distinct: boolean - ) { - super('minimum', [value]); - } -} +export function isNotNull(value: firestore.Expr): BooleanExpr; /** * @beta + * + * Creates an expression that checks if tbe value of a field is not null. + * + * ```typescript + * // Check if the value of the 'name' field is not null + * isNotNull("name"); + * ``` + * + * @param value The name of the field to check. + * @return A new {@code Expr} representing the 'isNotNull' check. */ -class Maximum extends Function implements Accumulator { - accumulator = true as const; - constructor( - private value: Expr, - private distinct: boolean - ) { - super('maximum', [value]); - } +export function isNotNull(value: string): BooleanExpr; +export function isNotNull(value: firestore.Expr | string): BooleanExpr { + return fieldOrExpression(value).isNotNull(); } /** * @beta + * + * Creates an expression that checks if the results of this expression is NOT 'NaN' (Not a Number). + * + * ```typescript + * // Check if the result of a calculation is NOT NaN + * isNotNaN(field("value").divide(0)); + * ``` + * + * @param value The expression to check. + * @return A new {@code Expr} representing the 'isNotNaN' check. */ -class CosineDistance extends Function { - constructor( - private vector1: Expr, - private vector2: Expr - ) { - super('cosine_distance', [vector1, vector2]); - } -} +export function isNotNan(value: firestore.Expr): BooleanExpr; /** * @beta + * + * Creates an expression that checks if the results of this expression is NOT 'NaN' (Not a Number). + * + * ```typescript + * // Check if the value of a field is NOT NaN + * isNotNaN("value"); + * ``` + * + * @param value The name of the field to check. + * @return A new {@code Expr} representing the 'isNotNaN' check. */ -class DotProduct extends Function { - constructor( - private vector1: Expr, - private vector2: Expr - ) { - super('dot_product', [vector1, vector2]); - } +export function isNotNan(value: string): BooleanExpr; +export function isNotNan(value: firestore.Expr | string): BooleanExpr { + return fieldOrExpression(value).isNotNan(); } /** * @beta + * + * Creates an expression that removes a key from the map at the specified field name. + * + * ``` + * // Removes the key 'city' field from the map in the address field of the input document. + * mapRemove('address', 'city'); + * ``` + * + * @param mapField The name of a field containing a map value. + * @param key The name of the key to remove from the input map. */ -class EuclideanDistance extends Function { - constructor( - private vector1: Expr, - private vector2: Expr - ) { - super('euclidean_distance', [vector1, vector2]); - } -} - +export function mapRemove(mapField: string, key: string): FunctionExpr; /** * @beta + * + * Creates an expression that removes a key from the map produced by evaluating an expression. + * + * ``` + * // Removes the key 'baz' from the input map. + * mapRemove(map({foo: 'bar', baz: true}), 'baz'); + * ``` + * + * @param mapExpr An expression return a map value. + * @param key The name of the key to remove from the input map. */ -export class VectorLength extends Function { - constructor(private value: Expr) { - super('vector_length', [value]); - } -} - +export function mapRemove(mapExpr: firestore.Expr, key: string): FunctionExpr; /** * @beta + * + * Creates an expression that removes a key from the map at the specified field name. + * + * ``` + * // Removes the key 'city' field from the map in the address field of the input document. + * mapRemove('address', constant('city')); + * ``` + * + * @param mapField The name of a field containing a map value. + * @param keyExpr An expression that produces the name of the key to remove from the input map. */ -export class UnixMicrosToTimestamp extends Function { - constructor(private input: Expr) { - super('unix_micros_to_timestamp', [input]); - } -} - +export function mapRemove( + mapField: string, + keyExpr: firestore.Expr +): FunctionExpr; /** * @beta + * + * Creates an expression that removes a key from the map produced by evaluating an expression. + * + * ``` + * // Removes the key 'baz' from the input map. + * mapRemove(map({foo: 'bar', baz: true}), constant('baz')); + * ``` + * + * @param mapExpr An expression return a map value. + * @param keyExpr An expression that produces the name of the key to remove from the input map. */ -export class TimestampToUnixMicros extends Function { - constructor(private input: Expr) { - super('timestamp_to_unix_micros', [input]); - } +export function mapRemove( + mapExpr: firestore.Expr, + keyExpr: firestore.Expr +): FunctionExpr; + +export function mapRemove( + mapExpr: firestore.Expr | string, + stringExpr: firestore.Expr | string +): FunctionExpr { + return fieldOrExpression(mapExpr).mapRemove(valueToDefaultExpr(stringExpr)); } /** * @beta + * + * Creates an expression that merges multiple map values. + * + * ``` + * // Merges the map in the settings field with, a map literal, and a map in + * // that is conditionally returned by another expression + * mapMerge('settings', { enabled: true }, cond(field('isAdmin'), { admin: true}, {}) + * ``` + * + * @param mapField Name of a field containing a map value that will be merged. + * @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. */ -export class UnixMillisToTimestamp extends Function { - constructor(private input: Expr) { - super('unix_millis_to_timestamp', [input]); - } -} +export function mapMerge( + mapField: string, + secondMap: Record | firestore.Expr, + ...otherMaps: Array | firestore.Expr> +): FunctionExpr; /** * @beta + * + * Creates an expression that merges multiple map values. + * + * ``` + * // Merges the map in the settings field with, a map literal, and a map in + * // that is conditionally returned by another expression + * mapMerge(field('settings'), { enabled: true }, cond(field('isAdmin'), { admin: true}, {}) + * ``` + * + * @param firstMap An expression or literal map value that will be merged. + * @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. */ -export class TimestampToUnixMillis extends Function { - constructor(private input: Expr) { - super('timestamp_to_unix_millis', [input]); - } +export function mapMerge( + firstMap: Record | firestore.Expr, + secondMap: Record | firestore.Expr, + ...otherMaps: Array | firestore.Expr> +): FunctionExpr; + +export function mapMerge( + firstMap: string | Record | firestore.Expr, + secondMap: Record | firestore.Expr, + ...otherMaps: Array | firestore.Expr> +): FunctionExpr { + const secondMapExpr = valueToDefaultExpr(secondMap); + const otherMapExprs = otherMaps.map(valueToDefaultExpr); + return fieldOrExpression(firstMap).mapMerge(secondMapExpr, ...otherMapExprs); } /** * @beta + * + * Creates an expression that returns the document ID from a path. + * + * ```typescript + * // Get the document ID from a path. + * documentId(myDocumentReference); + * ``` + * + * @return A new {@code Expr} representing the documentId operation. */ -export class UnixSecondsToTimestamp extends Function { - constructor(private input: Expr) { - super('unix_seconds_to_timestamp', [input]); - } -} +export function documentId( + documentPath: string | firestore.DocumentReference +): FunctionExpr; /** * @beta + * + * Creates an expression that returns the document ID from a path. + * + * ```typescript + * // Get the document ID from a path. + * documentId(field("__path__")); + * ``` + * + * @return A new {@code Expr} representing the documentId operation. */ -export class TimestampToUnixSeconds extends Function { - constructor(private input: Expr) { - super('timestamp_to_unix_seconds', [input]); - } +export function documentId(documentPathExpr: firestore.Expr): FunctionExpr; + +export function documentId( + documentPath: firestore.Expr | string | firestore.DocumentReference +): FunctionExpr { + const documentPathExpr = valueToDefaultExpr(documentPath); + return documentPathExpr.documentId(); } /** * @beta + * + * Creates an expression that returns a substring of a string or byte array. + * + * @param field The name of a field containing a string or byte array to compute the substring from. + * @param position Index of the first character of the substring. + * @param length Length of the substring. */ -export class TimestampAdd extends Function { - constructor( - private timestamp: Expr, - private unit: Expr, - private amount: Expr - ) { - super('timestamp_add', [timestamp, unit, amount]); - } -} +export function substr( + field: string, + position: number, + length?: number +): FunctionExpr; /** * @beta + * + * Creates an expression that returns a substring of a string or byte array. + * + * @param input An expression returning a string or byte array to compute the substring from. + * @param position Index of the first character of the substring. + * @param length Length of the substring. */ -export class TimestampSub extends Function { - constructor( - private timestamp: Expr, - private unit: Expr, - private amount: Expr - ) { - super('timestamp_sub', [timestamp, unit, amount]); - } -} +export function substr( + input: firestore.Expr, + position: number, + length?: number +): FunctionExpr; /** * @beta * - * Creates an expression that adds two expressions together. - * - * ```typescript - * // Add the value of the 'quantity' field and the 'reserve' field. - * add(Field.of("quantity"), Field.of("reserve")); - * ``` + * Creates an expression that returns a substring of a string or byte array. * - * @param left The first expression to add. - * @param right The second expression to add. - * @return A new {@code Expr} representing the addition operation. + * @param field The name of a field containing a string or byte array to compute the substring from. + * @param position An expression that returns the index of the first character of the substring. + * @param length An expression that returns the length of the substring. */ -export function add(left: Expr, right: Expr): Add; +export function substr( + field: string, + position: firestore.Expr, + length?: firestore.Expr +): FunctionExpr; /** * @beta * - * Creates an expression that adds an expression to a constant value. - * - * ```typescript - * // Add 5 to the value of the 'age' field - * add(Field.of("age"), 5); - * ``` + * Creates an expression that returns a substring of a string or byte array. * - * @param left The expression to add to. - * @param right The constant value to add. - * @return A new {@code Expr} representing the addition operation. + * @param input An expression returning a string or byte array to compute the substring from. + * @param position An expression that returns the index of the first character of the substring. + * @param length An expression that returns the length of the substring. */ -export function add(left: Expr, right: any): Add; +export function substr( + input: firestore.Expr, + position: firestore.Expr, + length?: firestore.Expr +): FunctionExpr; + +export function substr( + field: firestore.Expr | string, + position: firestore.Expr | number, + length?: firestore.Expr | number +): FunctionExpr { + const fieldExpr = fieldOrExpression(field); + const positionExpr = valueToDefaultExpr(position); + const lengthExpr = + length === undefined ? undefined : valueToDefaultExpr(length); + return fieldExpr.substr(positionExpr, lengthExpr); +} /** * @beta * - * Creates an expression that adds a field's value to an expression. + * Creates an expression that adds two expressions together. * * ```typescript * // Add the value of the 'quantity' field and the 'reserve' field. - * add("quantity", Field.of("reserve")); + * add(field("quantity"), field("reserve")); * ``` * - * @param left The field name to add to. - * @param right The expression to add. + * @param first The first expression to add. + * @param second The second expression or literal to add. + * @param others Optional other expressions or literals to add. * @return A new {@code Expr} representing the addition operation. */ -export function add(left: string, right: Expr): Add; +export function add( + first: firestore.Expr, + second: firestore.Expr | unknown, + ...others: Array +): FunctionExpr; /** * @beta * - * Creates an expression that adds a field's value to a constant value. + * Creates an expression that adds a field's value to an expression. * * ```typescript - * // Add 5 to the value of the 'age' field - * add("age", 5); + * // Add the value of the 'quantity' field and the 'reserve' field. + * add("quantity", field("reserve")); * ``` * - * @param left The field name to add to. - * @param right The constant value to add. + * @param fieldName The name of the field containing the value to add. + * @param second The second expression or literal to add. + * @param others Optional other expressions or literals to add. * @return A new {@code Expr} representing the addition operation. */ -export function add(left: string, right: any): Add; -export function add(left: Expr | string, right: Expr | any): Add { - const normalizedLeft = typeof left === 'string' ? Field.of(left) : left; - const normalizedRight = right instanceof Expr ? right : Constant.of(right); - return new Add(normalizedLeft, normalizedRight); +export function add( + fieldName: string, + second: firestore.Expr | unknown, + ...others: Array +): FunctionExpr; + +export function add( + first: firestore.Expr | string, + second: firestore.Expr | unknown, + ...others: Array +): FunctionExpr { + return fieldOrExpression(first).add( + valueToDefaultExpr(second), + ...others.map(value => valueToDefaultExpr(value)) + ); } /** @@ -2998,14 +3482,17 @@ export function add(left: Expr | string, right: Expr | any): Add { * * ```typescript * // Subtract the 'discount' field from the 'price' field - * subtract(Field.of("price"), Field.of("discount")); + * subtract(field("price"), field("discount")); * ``` * * @param left The expression to subtract from. * @param right The expression to subtract. * @return A new {@code Expr} representing the subtraction operation. */ -export function subtract(left: Expr, right: Expr): Subtract; +export function subtract( + left: firestore.Expr, + right: firestore.Expr +): FunctionExpr; /** * @beta @@ -3014,14 +3501,17 @@ export function subtract(left: Expr, right: Expr): Subtract; * * ```typescript * // Subtract the constant value 2 from the 'value' field - * subtract(Field.of("value"), 2); + * subtract(field("value"), 2); * ``` * - * @param left The expression to subtract from. - * @param right The constant value to subtract. + * @param expression The expression to subtract from. + * @param value The constant value to subtract. * @return A new {@code Expr} representing the subtraction operation. */ -export function subtract(left: Expr, right: any): Subtract; +export function subtract( + expression: firestore.Expr, + value: unknown +): FunctionExpr; /** * @beta @@ -3030,14 +3520,17 @@ export function subtract(left: Expr, right: any): Subtract; * * ```typescript * // Subtract the 'discount' field from the 'price' field - * subtract("price", Field.of("discount")); + * subtract("price", field("discount")); * ``` * - * @param left The field name to subtract from. - * @param right The expression to subtract. + * @param fieldName The field name to subtract from. + * @param expression The expression to subtract. * @return A new {@code Expr} representing the subtraction operation. */ -export function subtract(left: string, right: Expr): Subtract; +export function subtract( + fieldName: string, + expression: firestore.Expr +): FunctionExpr; /** * @beta @@ -3049,15 +3542,18 @@ export function subtract(left: string, right: Expr): Subtract; * subtract("total", 20); * ``` * - * @param left The field name to subtract from. - * @param right The constant value to subtract. + * @param fieldName The field name to subtract from. + * @param value The constant value to subtract. * @return A new {@code Expr} representing the subtraction operation. */ -export function subtract(left: string, right: any): Subtract; -export function subtract(left: Expr | string, right: Expr | any): Subtract { - const normalizedLeft = typeof left === 'string' ? Field.of(left) : left; - const normalizedRight = right instanceof Expr ? right : Constant.of(right); - return new Subtract(normalizedLeft, normalizedRight); +export function subtract(fieldName: string, value: unknown): FunctionExpr; +export function subtract( + left: firestore.Expr | string, + right: firestore.Expr | unknown +): FunctionExpr { + const normalizedLeft = fieldOrExpression(left); + const normalizedRight = valueToDefaultExpr(right); + return normalizedLeft.subtract(normalizedRight); } /** @@ -3067,30 +3563,19 @@ export function subtract(left: Expr | string, right: Expr | any): Subtract { * * ```typescript * // Multiply the 'quantity' field by the 'price' field - * multiply(Field.of("quantity"), Field.of("price")); - * ``` - * - * @param left The first expression to multiply. - * @param right The second expression to multiply. - * @return A new {@code Expr} representing the multiplication operation. - */ -export function multiply(left: Expr, right: Expr): Multiply; - -/** - * @beta - * - * Creates an expression that multiplies an expression by a constant value. - * - * ```typescript - * // Multiply the value of the 'price' field by 2 - * multiply(Field.of("price"), 2); + * multiply(field("quantity"), field("price")); * ``` * - * @param left The expression to multiply. - * @param right The constant value to multiply by. + * @param first The first expression to multiply. + * @param second The second expression or literal to multiply. + * @param others Optional additional expressions or literals to multiply. * @return A new {@code Expr} representing the multiplication operation. */ -export function multiply(left: Expr, right: any): Multiply; +export function multiply( + first: firestore.Expr, + second: firestore.Expr | unknown, + ...others: Array +): FunctionExpr; /** * @beta @@ -3099,34 +3584,29 @@ export function multiply(left: Expr, right: any): Multiply; * * ```typescript * // Multiply the 'quantity' field by the 'price' field - * multiply("quantity", Field.of("price")); - * ``` - * - * @param left The field name to multiply. - * @param right The expression to multiply by. - * @return A new {@code Expr} representing the multiplication operation. - */ -export function multiply(left: string, right: Expr): Multiply; - -/** - * @beta - * - * Creates an expression that multiplies a field's value by a constant value. - * - * ```typescript - * // Multiply the 'value' field by 2 - * multiply("value", 2); + * multiply("quantity", field("price")); * ``` * - * @param left The field name to multiply. - * @param right The constant value to multiply by. + * @param fieldName The name of the field containing the value to add. + * @param second The second expression or literal to add. + * @param others Optional other expressions or literals to add. * @return A new {@code Expr} representing the multiplication operation. */ -export function multiply(left: string, right: any): Multiply; -export function multiply(left: Expr | string, right: Expr | any): Multiply { - const normalizedLeft = typeof left === 'string' ? Field.of(left) : left; - const normalizedRight = right instanceof Expr ? right : Constant.of(right); - return new Multiply(normalizedLeft, normalizedRight); +export function multiply( + fieldName: string, + second: firestore.Expr | unknown, + ...others: Array +): FunctionExpr; + +export function multiply( + first: firestore.Expr | string, + second: firestore.Expr | unknown, + ...others: Array +): FunctionExpr { + return fieldOrExpression(first).multiply( + valueToDefaultExpr(second), + ...others.map(valueToDefaultExpr) + ); } /** @@ -3136,14 +3616,17 @@ export function multiply(left: Expr | string, right: Expr | any): Multiply { * * ```typescript * // Divide the 'total' field by the 'count' field - * divide(Field.of("total"), Field.of("count")); + * divide(field("total"), field("count")); * ``` * * @param left The expression to be divided. * @param right The expression to divide by. * @return A new {@code Expr} representing the division operation. */ -export function divide(left: Expr, right: Expr): Divide; +export function divide( + left: firestore.Expr, + right: firestore.Expr +): FunctionExpr; /** * @beta @@ -3152,14 +3635,17 @@ export function divide(left: Expr, right: Expr): Divide; * * ```typescript * // Divide the 'value' field by 10 - * divide(Field.of("value"), 10); + * divide(field("value"), 10); * ``` * - * @param left The expression to be divided. - * @param right The constant value to divide by. + * @param expression The expression to be divided. + * @param value The constant value to divide by. * @return A new {@code Expr} representing the division operation. */ -export function divide(left: Expr, right: any): Divide; +export function divide( + expression: firestore.Expr, + value: unknown +): FunctionExpr; /** * @beta @@ -3168,14 +3654,17 @@ export function divide(left: Expr, right: any): Divide; * * ```typescript * // Divide the 'total' field by the 'count' field - * divide("total", Field.of("count")); + * divide("total", field("count")); * ``` * - * @param left The field name to be divided. - * @param right The expression to divide by. + * @param fieldName The field name to be divided. + * @param expressions The expression to divide by. * @return A new {@code Expr} representing the division operation. */ -export function divide(left: string, right: Expr): Divide; +export function divide( + fieldName: string, + expressions: firestore.Expr +): FunctionExpr; /** * @beta @@ -3187,15 +3676,18 @@ export function divide(left: string, right: Expr): Divide; * divide("value", 10); * ``` * - * @param left The field name to be divided. - * @param right The constant value to divide by. + * @param fieldName The field name to be divided. + * @param value The constant value to divide by. * @return A new {@code Expr} representing the division operation. */ -export function divide(left: string, right: any): Divide; -export function divide(left: Expr | string, right: Expr | any): Divide { - const normalizedLeft = typeof left === 'string' ? Field.of(left) : left; - const normalizedRight = right instanceof Expr ? right : Constant.of(right); - return new Divide(normalizedLeft, normalizedRight); +export function divide(fieldName: string, value: unknown): FunctionExpr; +export function divide( + left: firestore.Expr | string, + right: firestore.Expr | unknown +): FunctionExpr { + const normalizedLeft = fieldOrExpression(left); + const normalizedRight = valueToDefaultExpr(right); + return normalizedLeft.divide(normalizedRight); } /** @@ -3205,14 +3697,14 @@ export function divide(left: Expr | string, right: Expr | any): Divide { * * ```typescript * // Calculate the remainder of dividing 'field1' by 'field2'. - * mod(Field.of("field1"), Field.of("field2")); + * mod(field("field1"), field("field2")); * ``` * * @param left The dividend expression. * @param right The divisor expression. * @return A new {@code Expr} representing the modulo operation. */ -export function mod(left: Expr, right: Expr): Mod; +export function mod(left: firestore.Expr, right: firestore.Expr): FunctionExpr; /** * @beta @@ -3221,14 +3713,14 @@ export function mod(left: Expr, right: Expr): Mod; * * ```typescript * // Calculate the remainder of dividing 'field1' by 5. - * mod(Field.of("field1"), 5); + * mod(field("field1"), 5); * ``` * - * @param left The dividend expression. - * @param right The divisor constant. + * @param expression The dividend expression. + * @param value The divisor constant. * @return A new {@code Expr} representing the modulo operation. */ -export function mod(left: Expr, right: any): Mod; +export function mod(expression: firestore.Expr, value: unknown): FunctionExpr; /** * @beta @@ -3237,14 +3729,17 @@ export function mod(left: Expr, right: any): Mod; * * ```typescript * // Calculate the remainder of dividing 'field1' by 'field2'. - * mod("field1", Field.of("field2")); + * mod("field1", field("field2")); * ``` * - * @param left The dividend field name. - * @param right The divisor expression. + * @param fieldName The dividend field name. + * @param expression The divisor expression. * @return A new {@code Expr} representing the modulo operation. */ -export function mod(left: string, right: Expr): Mod; +export function mod( + fieldName: string, + expression: firestore.Expr +): FunctionExpr; /** * @beta @@ -3256,402 +3751,86 @@ export function mod(left: string, right: Expr): Mod; * mod("field1", 5); * ``` * - * @param left The dividend field name. - * @param right The divisor constant. + * @param fieldName The dividend field name. + * @param value The divisor constant. * @return A new {@code Expr} representing the modulo operation. */ -export function mod(left: string, right: any): Mod; -export function mod(left: Expr | string, right: Expr | any): Mod { - const normalizedLeft = typeof left === 'string' ? Field.of(left) : left; - const normalizedRight = right instanceof Expr ? right : Constant.of(right); - return new Mod(normalizedLeft, normalizedRight); +export function mod(fieldName: string, value: unknown): FunctionExpr; +export function mod( + left: firestore.Expr | string, + right: firestore.Expr | unknown +): FunctionExpr { + const normalizedLeft = fieldOrExpression(left); + const normalizedRight = valueToDefaultExpr(right); + return normalizedLeft.mod(normalizedRight); } -// /** -// * @beta -// * -// * Creates an expression that applies a bitwise AND operation between two expressions. -// * -// * ```typescript -// * // Calculate the bitwise AND of 'field1' and 'field2'. -// * bitAnd(Field.of("field1"), Field.of("field2")); -// * ``` -// * -// * @param left The left operand expression. -// * @param right The right operand expression. -// * @return A new {@code Expr} representing the bitwise AND operation. -// */ -// export function bitAnd(left: Expr, right: Expr): BitAnd; -// -// /** -// * @beta -// * -// * Creates an expression that applies a bitwise AND operation between an expression and a constant. -// * -// * ```typescript -// * // Calculate the bitwise AND of 'field1' and 0xFF. -// * bitAnd(Field.of("field1"), 0xFF); -// * ``` -// * -// * @param left The left operand expression. -// * @param right The right operand constant. -// * @return A new {@code Expr} representing the bitwise AND operation. -// */ -// export function bitAnd(left: Expr, right: any): BitAnd; -// -// /** -// * @beta -// * -// * Creates an expression that applies a bitwise AND operation between a field and an expression. -// * -// * ```typescript -// * // Calculate the bitwise AND of 'field1' and 'field2'. -// * bitAnd("field1", Field.of("field2")); -// * ``` -// * -// * @param left The left operand field name. -// * @param right The right operand expression. -// * @return A new {@code Expr} representing the bitwise AND operation. -// */ -// export function bitAnd(left: string, right: Expr): BitAnd; -// -// /** -// * @beta -// * -// * Creates an expression that applies a bitwise AND operation between a field and a constant. -// * -// * ```typescript -// * // Calculate the bitwise AND of 'field1' and 0xFF. -// * bitAnd("field1", 0xFF); -// * ``` -// * -// * @param left The left operand field name. -// * @param right The right operand constant. -// * @return A new {@code Expr} representing the bitwise AND operation. -// */ -// export function bitAnd(left: string, right: any): BitAnd; -// export function bitAnd(left: Expr | string, right: Expr | any): BitAnd { -// const normalizedLeft = typeof left === 'string' ? Field.of(left) : left; -// const normalizedRight = right instanceof Expr ? right : Constant.of(right); -// return new BitAnd(normalizedLeft, normalizedRight); -// } -// -// /** -// * @beta -// * -// * Creates an expression that applies a bitwise OR operation between two expressions. -// * -// * ```typescript -// * // Calculate the bitwise OR of 'field1' and 'field2'. -// * bitOr(Field.of("field1"), Field.of("field2")); -// * ``` -// * -// * @param left The left operand expression. -// * @param right The right operand expression. -// * @return A new {@code Expr} representing the bitwise OR operation. -// */ -// export function bitOr(left: Expr, right: Expr): BitOr; -// -// /** -// * @beta -// * -// * Creates an expression that applies a bitwise OR operation between an expression and a constant. -// * -// * ```typescript -// * // Calculate the bitwise OR of 'field1' and 0xFF. -// * bitOr(Field.of("field1"), 0xFF); -// * ``` -// * -// * @param left The left operand expression. -// * @param right The right operand constant. -// * @return A new {@code Expr} representing the bitwise OR operation. -// */ -// export function bitOr(left: Expr, right: any): BitOr; -// -// /** -// * @beta -// * -// * Creates an expression that applies a bitwise OR operation between a field and an expression. -// * -// * ```typescript -// * // Calculate the bitwise OR of 'field1' and 'field2'. -// * bitOr("field1", Field.of("field2")); -// * ``` -// * -// * @param left The left operand field name. -// * @param right The right operand expression. -// * @return A new {@code Expr} representing the bitwise OR operation. -// */ -// export function bitOr(left: string, right: Expr): BitOr; -// -// /** -// * @beta -// * -// * Creates an expression that applies a bitwise OR operation between a field and a constant. -// * -// * ```typescript -// * // Calculate the bitwise OR of 'field1' and 0xFF. -// * bitOr("field1", 0xFF); -// * ``` -// * -// * @param left The left operand field name. -// * @param right The right operand constant. -// * @return A new {@code Expr} representing the bitwise OR operation. -// */ -// export function bitOr(left: string, right: any): BitOr; -// export function bitOr(left: Expr | string, right: Expr | any): BitOr { -// const normalizedLeft = typeof left === 'string' ? Field.of(left) : left; -// const normalizedRight = right instanceof Expr ? right : Constant.of(right); -// return new BitOr(normalizedLeft, normalizedRight); -// } -// -// /** -// * @beta -// * -// * Creates an expression that applies a bitwise XOR operation between two expressions. -// * -// * ```typescript -// * // Calculate the bitwise XOR of 'field1' and 'field2'. -// * bitXor(Field.of("field1"), Field.of("field2")); -// * ``` -// * -// * @param left The left operand expression. -// * @param right The right operand expression. -// * @return A new {@code Expr} representing the bitwise XOR operation. -// */ -// export function bitXor(left: Expr, right: Expr): BitXor; -// -// /** -// * @beta -// * -// * Creates an expression that applies a bitwise XOR operation between an expression and a constant. -// * -// * ```typescript -// * // Calculate the bitwise XOR of 'field1' and 0xFF. -// * bitXor(Field.of("field1"), 0xFF); -// * ``` -// * -// * @param left The left operand expression. -// * @param right The right operand constant. -// * @return A new {@code Expr} representing the bitwise XOR operation. -// */ -// export function bitXor(left: Expr, right: any): BitXor; -// -// /** -// * @beta -// * -// * Creates an expression that applies a bitwise XOR operation between a field and an expression. -// * -// * ```typescript -// * // Calculate the bitwise XOR of 'field1' and 'field2'. -// * bitXor("field1", Field.of("field2")); -// * ``` -// * -// * @param left The left operand field name. -// * @param right The right operand expression. -// * @return A new {@code Expr} representing the bitwise XOR operation. -// */ -// export function bitXor(left: string, right: Expr): BitXor; -// -// /** -// * @beta -// * -// * Creates an expression that applies a bitwise XOR operation between a field and a constant. -// * -// * ```typescript -// * // Calculate the bitwise XOR of 'field1' and 0xFF. -// * bitXor("field1", 0xFF); -// * ``` -// * -// * @param left The left operand field name. -// * @param right The right operand constant. -// * @return A new {@code Expr} representing the bitwise XOR operation. -// */ -// export function bitXor(left: string, right: any): BitXor; -// export function bitXor(left: Expr | string, right: Expr | any): BitXor { -// const normalizedLeft = typeof left === 'string' ? Field.of(left) : left; -// const normalizedRight = right instanceof Expr ? right : Constant.of(right); -// return new BitXor(normalizedLeft, normalizedRight); -// } -// -// /** -// * @beta -// * -// * Creates an expression that applies a bitwise NOT operation to an expression. -// * -// * ```typescript -// * // Calculate the bitwise NOT of 'field1'. -// * bitNot(Field.of("field1")); -// * ``` -// * -// * @param operand The operand expression. -// * @return A new {@code Expr} representing the bitwise NOT operation. -// */ -// export function bitNot(operand: Expr): BitNot; -// -// /** -// * @beta -// * -// * Creates an expression that applies a bitwise NOT operation to a field. -// * -// * ```typescript -// * // Calculate the bitwise NOT of 'field1'. -// * bitNot("field1"); -// * ``` -// * -// * @param operand The operand field name. -// * @return A new {@code Expr} representing the bitwise NOT operation. -// */ -// export function bitNot(operand: string): BitNot; -// export function bitNot(operand: Expr | string): BitNot { -// const normalizedOperand = -// typeof operand === 'string' ? Field.of(operand) : operand; -// return new BitNot(normalizedOperand); -// } -// -// /** -// * @beta -// * -// * Creates an expression that applies a bitwise left shift operation between two expressions. -// * -// * ```typescript -// * // Calculate the bitwise left shift of 'field1' by 'field2' bits. -// * bitLeftShift(Field.of("field1"), Field.of("field2")); -// * ``` -// * -// * @param left The left operand expression. -// * @param right The right operand expression representing the number of bits to shift. -// * @return A new {@code Expr} representing the bitwise left shift operation. -// */ -// export function bitLeftShift(left: Expr, right: Expr): BitLeftShift; -// -// /** -// * @beta -// * -// * Creates an expression that applies a bitwise left shift operation between an expression and a constant. -// * -// * ```typescript -// * // Calculate the bitwise left shift of 'field1' by 2 bits. -// * bitLeftShift(Field.of("field1"), 2); -// * ``` -// * -// * @param left The left operand expression. -// * @param right The right operand constant representing the number of bits to shift. -// * @return A new {@code Expr} representing the bitwise left shift operation. -// */ -// export function bitLeftShift(left: Expr, right: any): BitLeftShift; -// -// /** -// * @beta -// * -// * Creates an expression that applies a bitwise left shift operation between a field and an expression. -// * -// * ```typescript -// * // Calculate the bitwise left shift of 'field1' by 'field2' bits. -// * bitLeftShift("field1", Field.of("field2")); -// * ``` -// * -// * @param left The left operand field name. -// * @param right The right operand expression representing the number of bits to shift. -// * @return A new {@code Expr} representing the bitwise left shift operation. -// */ -// export function bitLeftShift(left: string, right: Expr): BitLeftShift; -// -// /** -// * @beta -// * -// * Creates an expression that applies a bitwise left shift operation between a field and a constant. -// * -// * ```typescript -// * // Calculate the bitwise left shift of 'field1' by 2 bits. -// * bitLeftShift("field1", 2); -// * ``` -// * -// * @param left The left operand field name. -// * @param right The right operand constant representing the number of bits to shift. -// * @return A new {@code Expr} representing the bitwise left shift operation. -// */ -// export function bitLeftShift(left: string, right: any): BitLeftShift; -// export function bitLeftShift( -// left: Expr | string, -// right: Expr | any -// ): BitLeftShift { -// const normalizedLeft = typeof left === 'string' ? Field.of(left) : left; -// const normalizedRight = right instanceof Expr ? right : Constant.of(right); -// return new BitLeftShift(normalizedLeft, normalizedRight); -// } -// -// /** -// * @beta -// * -// * Creates an expression that applies a bitwise right shift operation between two expressions. -// * -// * ```typescript -// * // Calculate the bitwise right shift of 'field1' by 'field2' bits. -// * bitRightShift(Field.of("field1"), Field.of("field2")); -// * ``` -// * -// * @param left The left operand expression. -// * @param right The right operand expression representing the number of bits to shift. -// * @return A new {@code Expr} representing the bitwise right shift operation. -// */ -// export function bitRightShift(left: Expr, right: Expr): BitRightShift; -// -// /** -// * @beta -// * -// * Creates an expression that applies a bitwise right shift operation between an expression and a constant. -// * -// * ```typescript -// * // Calculate the bitwise right shift of 'field1' by 2 bits. -// * bitRightShift(Field.of("field1"), 2); -// * ``` -// * -// * @param left The left operand expression. -// * @param right The right operand constant representing the number of bits to shift. -// * @return A new {@code Expr} representing the bitwise right shift operation. -// */ -// export function bitRightShift(left: Expr, right: any): BitRightShift; -// -// /** -// * @beta -// * -// * Creates an expression that applies a bitwise right shift operation between a field and an expression. -// * -// * ```typescript -// * // Calculate the bitwise right shift of 'field1' by 'field2' bits. -// * bitRightShift("field1", Field.of("field2")); -// * ``` -// * -// * @param left The left operand field name. -// * @param right The right operand expression representing the number of bits to shift. -// * @return A new {@code Expr} representing the bitwise right shift operation. -// */ -// export function bitRightShift(left: string, right: Expr): BitRightShift; -// -// /** -// * @beta -// * -// * Creates an expression that applies a bitwise right shift operation between a field and a constant. -// * -// * ```typescript -// * // Calculate the bitwise right shift of 'field1' by 2 bits. -// * bitRightShift("field1", 2); -// * ``` -// * -// * @param left The left operand field name. -// * @param right The right operand constant representing the number of bits to shift. -// * @return A new {@code Expr} representing the bitwise right shift operation. -// */ -// export function bitRightShift(left: string, right: any): BitRightShift; -// export function bitRightShift( -// left: Expr | string, -// right: Expr | any -// ): BitRightShift { -// const normalizedLeft = typeof left === 'string' ? Field.of(left) : left; -// const normalizedRight = right instanceof Expr ? right : Constant.of(right); -// return new BitRightShift(normalizedLeft, normalizedRight); -// } +/** + * @beta + * + * Creates an expression that creates a Firestore map value from an input object. + * + * ```typescript + * // Create a map from the input object and reference the 'baz' field value from the input document. + * map({foo: 'bar', baz: field('baz')}).as('data'); + * ``` + * + * @param elements The input map to evaluate in the expression. + * @return A new {@code Expr} representing the map function. + */ +export function map(elements: Record): FunctionExpr { + const result: firestore.Expr[] = []; + for (const key in elements) { + if (Object.prototype.hasOwnProperty.call(elements, key)) { + const value = elements[key]; + result.push(constant(key)); + result.push(valueToDefaultExpr(value)); + } + } + return new FunctionExpr('map', result); +} + +/** + * Internal use only + * Converts a plainObject to a mapValue in the proto representation, + * rather than a functionValue+map that is the result of the map(...) function. + * This behaves different from constant(plainObject) because it + * traverses the input object, converts values in the object to expressions, + * and calls _readUserData on each of these expressions. + * @private + * @internal + * @param plainObject + */ +export function _mapValue(plainObject: Record): MapValue { + const result: Map = new Map(); + for (const key in plainObject) { + if (Object.prototype.hasOwnProperty.call(plainObject, key)) { + const value = plainObject[key]; + result.set(key, valueToDefaultExpr(value)); + } + } + return new MapValue(result); +} + +/** + * @beta + * + * Creates an expression that creates a Firestore array value from an input array. + * + * ```typescript + * // Create an array value from the input array and reference the 'baz' field value from the input document. + * array(['bar', field('baz')]).as('foo'); + * ``` + * + * @param elements The input array to evaluate in the expression. + * @return A new {@code Expr} representing the array function. + */ +export function array(elements: unknown[]): FunctionExpr { + return new FunctionExpr( + 'array', + elements.map(element => valueToDefaultExpr(element)) + ); +} /** * @beta @@ -3660,14 +3839,14 @@ export function mod(left: Expr | string, right: Expr | any): Mod { * * ```typescript * // Check if the 'age' field is equal to an expression - * eq(Field.of("age"), Field.of("minAge").add(10)); + * eq(field("age"), field("minAge").add(10)); * ``` * * @param left The first expression to compare. * @param right The second expression to compare. * @return A new `Expr` representing the equality comparison. */ -export function eq(left: Expr, right: Expr): Eq; +export function eq(left: firestore.Expr, right: firestore.Expr): BooleanExpr; /** * @beta @@ -3676,14 +3855,14 @@ export function eq(left: Expr, right: Expr): Eq; * * ```typescript * // Check if the 'age' field is equal to 21 - * eq(Field.of("age"), 21); + * eq(field("age"), 21); * ``` * - * @param left The expression to compare. - * @param right The constant value to compare to. + * @param expression The expression to compare. + * @param value The constant value to compare to. * @return A new `Expr` representing the equality comparison. */ -export function eq(left: Expr, right: any): Eq; +export function eq(expression: firestore.Expr, value: unknown): BooleanExpr; /** * @beta @@ -3692,14 +3871,14 @@ export function eq(left: Expr, right: any): Eq; * * ```typescript * // Check if the 'age' field is equal to the 'limit' field - * eq("age", Field.of("limit")); + * eq("age", field("limit")); * ``` * - * @param left The field name to compare. - * @param right The expression to compare to. + * @param fieldName The field name to compare. + * @param expression The expression to compare to. * @return A new `Expr` representing the equality comparison. */ -export function eq(left: string, right: Expr): Eq; +export function eq(fieldName: string, expression: firestore.Expr): BooleanExpr; /** * @beta @@ -3711,15 +3890,15 @@ export function eq(left: string, right: Expr): Eq; * eq("city", "London"); * ``` * - * @param left The field name to compare. - * @param right The constant value to compare to. + * @param fieldName The field name to compare. + * @param value The constant value to compare to. * @return A new `Expr` representing the equality comparison. */ -export function eq(left: string, right: any): Eq; -export function eq(left: Expr | string, right: any): Eq { - const leftExpr = left instanceof Expr ? left : Field.of(left); - const rightExpr = right instanceof Expr ? right : Constant.of(right); - return new Eq(leftExpr, rightExpr); +export function eq(fieldName: string, value: unknown): BooleanExpr; +export function eq(left: firestore.Expr | string, right: unknown): BooleanExpr { + const leftExpr = fieldOrExpression(left); + const rightExpr = valueToDefaultExpr(right); + return leftExpr.eq(rightExpr); } /** @@ -3729,14 +3908,14 @@ export function eq(left: Expr | string, right: any): Eq { * * ```typescript * // Check if the 'status' field is not equal to field 'finalState' - * neq(Field.of("status"), Field.of("finalState")); + * neq(field("status"), field("finalState")); * ``` * * @param left The first expression to compare. * @param right The second expression to compare. * @return A new `Expr` representing the inequality comparison. */ -export function neq(left: Expr, right: Expr): Neq; +export function neq(left: firestore.Expr, right: firestore.Expr): BooleanExpr; /** * @beta @@ -3745,14 +3924,14 @@ export function neq(left: Expr, right: Expr): Neq; * * ```typescript * // Check if the 'status' field is not equal to "completed" - * neq(Field.of("status"), "completed"); + * neq(field("status"), "completed"); * ``` * - * @param left The expression to compare. - * @param right The constant value to compare to. + * @param expression The expression to compare. + * @param value The constant value to compare to. * @return A new `Expr` representing the inequality comparison. */ -export function neq(left: Expr, right: any): Neq; +export function neq(expression: firestore.Expr, value: unknown): BooleanExpr; /** * @beta @@ -3761,14 +3940,14 @@ export function neq(left: Expr, right: any): Neq; * * ```typescript * // Check if the 'status' field is not equal to the value of 'expectedStatus' - * neq("status", Field.of("expectedStatus")); + * neq("status", field("expectedStatus")); * ``` * - * @param left The field name to compare. - * @param right The expression to compare to. + * @param fieldName The field name to compare. + * @param expression The expression to compare to. * @return A new `Expr` representing the inequality comparison. */ -export function neq(left: string, right: Expr): Neq; +export function neq(fieldName: string, expression: firestore.Expr): BooleanExpr; /** * @beta @@ -3780,15 +3959,18 @@ export function neq(left: string, right: Expr): Neq; * neq("country", "USA"); * ``` * - * @param left The field name to compare. - * @param right The constant value to compare to. + * @param fieldName The field name to compare. + * @param value The constant value to compare to. * @return A new `Expr` representing the inequality comparison. */ -export function neq(left: string, right: any): Neq; -export function neq(left: Expr | string, right: any): Neq { - const leftExpr = left instanceof Expr ? left : Field.of(left); - const rightExpr = right instanceof Expr ? right : Constant.of(right); - return new Neq(leftExpr, rightExpr); +export function neq(fieldName: string, value: unknown): BooleanExpr; +export function neq( + left: firestore.Expr | string, + right: unknown +): BooleanExpr { + const leftExpr = fieldOrExpression(left); + const rightExpr = valueToDefaultExpr(right); + return leftExpr.neq(rightExpr); } /** @@ -3798,14 +3980,14 @@ export function neq(left: Expr | string, right: any): Neq { * * ```typescript * // Check if the 'age' field is less than 30 - * lt(Field.of("age"), Field.of("limit")); + * lt(field("age"), field("limit")); * ``` * * @param left The first expression to compare. * @param right The second expression to compare. * @return A new `Expr` representing the less than comparison. */ -export function lt(left: Expr, right: Expr): Lt; +export function lt(left: firestore.Expr, right: firestore.Expr): BooleanExpr; /** * @beta @@ -3814,14 +3996,14 @@ export function lt(left: Expr, right: Expr): Lt; * * ```typescript * // Check if the 'age' field is less than 30 - * lt(Field.of("age"), 30); + * lt(field("age"), 30); * ``` * - * @param left The expression to compare. - * @param right The constant value to compare to. + * @param expression The expression to compare. + * @param value The constant value to compare to. * @return A new `Expr` representing the less than comparison. */ -export function lt(left: Expr, right: any): Lt; +export function lt(expression: firestore.Expr, value: unknown): BooleanExpr; /** * @beta @@ -3830,14 +4012,14 @@ export function lt(left: Expr, right: any): Lt; * * ```typescript * // Check if the 'age' field is less than the 'limit' field - * lt("age", Field.of("limit")); + * lt("age", field("limit")); * ``` * - * @param left The field name to compare. - * @param right The expression to compare to. + * @param fieldName The field name to compare. + * @param expression The expression to compare to. * @return A new `Expr` representing the less than comparison. */ -export function lt(left: string, right: Expr): Lt; +export function lt(fieldName: string, expression: firestore.Expr): BooleanExpr; /** * @beta @@ -3849,15 +4031,15 @@ export function lt(left: string, right: Expr): Lt; * lt("price", 50); * ``` * - * @param left The field name to compare. - * @param right The constant value to compare to. + * @param fieldName The field name to compare. + * @param value The constant value to compare to. * @return A new `Expr` representing the less than comparison. */ -export function lt(left: string, right: any): Lt; -export function lt(left: Expr | string, right: any): Lt { - const leftExpr = left instanceof Expr ? left : Field.of(left); - const rightExpr = right instanceof Expr ? right : Constant.of(right); - return new Lt(leftExpr, rightExpr); +export function lt(fieldName: string, value: unknown): BooleanExpr; +export function lt(left: firestore.Expr | string, right: unknown): BooleanExpr { + const leftExpr = fieldOrExpression(left); + const rightExpr = valueToDefaultExpr(right); + return leftExpr.lt(rightExpr); } /** @@ -3868,14 +4050,14 @@ export function lt(left: Expr | string, right: any): Lt { * * ```typescript * // Check if the 'quantity' field is less than or equal to 20 - * lte(Field.of("quantity"), Field.of("limit")); + * lte(field("quantity"), field("limit")); * ``` * * @param left The first expression to compare. * @param right The second expression to compare. * @return A new `Expr` representing the less than or equal to comparison. */ -export function lte(left: Expr, right: Expr): Lte; +export function lte(left: firestore.Expr, right: firestore.Expr): BooleanExpr; /** * @beta @@ -3884,28 +4066,28 @@ export function lte(left: Expr, right: Expr): Lte; * * ```typescript * // Check if the 'quantity' field is less than or equal to 20 - * lte(Field.of("quantity"), 20); + * lte(field("quantity"), 20); * ``` * - * @param left The expression to compare. - * @param right The constant value to compare to. + * @param expression The expression to compare. + * @param value The constant value to compare to. * @return A new `Expr` representing the less than or equal to comparison. */ -export function lte(left: Expr, right: any): Lte; +export function lte(expression: firestore.Expr, value: unknown): BooleanExpr; /** * Creates an expression that checks if a field's value is less than or equal to an expression. * * ```typescript * // Check if the 'quantity' field is less than or equal to the 'limit' field - * lte("quantity", Field.of("limit")); + * lte("quantity", field("limit")); * ``` * - * @param left The field name to compare. - * @param right The expression to compare to. + * @param fieldName The field name to compare. + * @param expression The expression to compare to. * @return A new `Expr` representing the less than or equal to comparison. */ -export function lte(left: string, right: Expr): Lte; +export function lte(fieldName: string, expression: firestore.Expr): BooleanExpr; /** * @beta @@ -3917,15 +4099,18 @@ export function lte(left: string, right: Expr): Lte; * lte("score", 70); * ``` * - * @param left The field name to compare. - * @param right The constant value to compare to. + * @param fieldName The field name to compare. + * @param value The constant value to compare to. * @return A new `Expr` representing the less than or equal to comparison. */ -export function lte(left: string, right: any): Lte; -export function lte(left: Expr | string, right: any): Lte { - const leftExpr = left instanceof Expr ? left : Field.of(left); - const rightExpr = right instanceof Expr ? right : Constant.of(right); - return new Lte(leftExpr, rightExpr); +export function lte(fieldName: string, value: unknown): BooleanExpr; +export function lte( + left: firestore.Expr | string, + right: unknown +): BooleanExpr { + const leftExpr = fieldOrExpression(left); + const rightExpr = valueToDefaultExpr(right); + return leftExpr.lte(rightExpr); } /** @@ -3936,14 +4121,14 @@ export function lte(left: Expr | string, right: any): Lte { * * ```typescript * // Check if the 'age' field is greater than 18 - * gt(Field.of("age"), Constant(9).add(9)); + * gt(field("age"), Constant(9).add(9)); * ``` * * @param left The first expression to compare. * @param right The second expression to compare. * @return A new `Expr` representing the greater than comparison. */ -export function gt(left: Expr, right: Expr): Gt; +export function gt(left: firestore.Expr, right: firestore.Expr): BooleanExpr; /** * @beta @@ -3952,14 +4137,14 @@ export function gt(left: Expr, right: Expr): Gt; * * ```typescript * // Check if the 'age' field is greater than 18 - * gt(Field.of("age"), 18); + * gt(field("age"), 18); * ``` * - * @param left The expression to compare. - * @param right The constant value to compare to. + * @param expression The expression to compare. + * @param value The constant value to compare to. * @return A new `Expr` representing the greater than comparison. */ -export function gt(left: Expr, right: any): Gt; +export function gt(expression: firestore.Expr, value: unknown): BooleanExpr; /** * @beta @@ -3968,14 +4153,14 @@ export function gt(left: Expr, right: any): Gt; * * ```typescript * // Check if the value of field 'age' is greater than the value of field 'limit' - * gt("age", Field.of("limit")); + * gt("age", field("limit")); * ``` * - * @param left The field name to compare. - * @param right The expression to compare to. + * @param fieldName The field name to compare. + * @param expression The expression to compare to. * @return A new `Expr` representing the greater than comparison. */ -export function gt(left: string, right: Expr): Gt; +export function gt(fieldName: string, expression: firestore.Expr): BooleanExpr; /** * @beta @@ -3987,15 +4172,15 @@ export function gt(left: string, right: Expr): Gt; * gt("price", 100); * ``` * - * @param left The field name to compare. - * @param right The constant value to compare to. + * @param fieldName The field name to compare. + * @param value The constant value to compare to. * @return A new `Expr` representing the greater than comparison. */ -export function gt(left: string, right: any): Gt; -export function gt(left: Expr | string, right: any): Gt { - const leftExpr = left instanceof Expr ? left : Field.of(left); - const rightExpr = right instanceof Expr ? right : Constant.of(right); - return new Gt(leftExpr, rightExpr); +export function gt(fieldName: string, value: unknown): BooleanExpr; +export function gt(left: firestore.Expr | string, right: unknown): BooleanExpr { + const leftExpr = fieldOrExpression(left); + const rightExpr = valueToDefaultExpr(right); + return leftExpr.gt(rightExpr); } /** @@ -4006,14 +4191,14 @@ export function gt(left: Expr | string, right: any): Gt { * * ```typescript * // Check if the 'quantity' field is greater than or equal to the field "threshold" - * gte(Field.of("quantity"), Field.of("threshold")); + * gte(field("quantity"), field("threshold")); * ``` * * @param left The first expression to compare. * @param right The second expression to compare. * @return A new `Expr` representing the greater than or equal to comparison. */ -export function gte(left: Expr, right: Expr): Gte; +export function gte(left: firestore.Expr, right: firestore.Expr): BooleanExpr; /** * @beta @@ -4023,14 +4208,14 @@ export function gte(left: Expr, right: Expr): Gte; * * ```typescript * // Check if the 'quantity' field is greater than or equal to 10 - * gte(Field.of("quantity"), 10); + * gte(field("quantity"), 10); * ``` * - * @param left The expression to compare. - * @param right The constant value to compare to. + * @param expression The expression to compare. + * @param value The constant value to compare to. * @return A new `Expr` representing the greater than or equal to comparison. */ -export function gte(left: Expr, right: any): Gte; +export function gte(expression: firestore.Expr, value: unknown): BooleanExpr; /** * @beta @@ -4039,14 +4224,14 @@ export function gte(left: Expr, right: any): Gte; * * ```typescript * // Check if the value of field 'age' is greater than or equal to the value of field 'limit' - * gte("age", Field.of("limit")); + * gte("age", field("limit")); * ``` * - * @param left The field name to compare. - * @param right The expression to compare to. + * @param fieldName The field name to compare. + * @param value The expression to compare to. * @return A new `Expr` representing the greater than or equal to comparison. */ -export function gte(left: string, right: Expr): Gte; +export function gte(fieldName: string, value: firestore.Expr): BooleanExpr; /** * @beta @@ -4059,15 +4244,18 @@ export function gte(left: string, right: Expr): Gte; * gte("score", 80); * ``` * - * @param left The field name to compare. - * @param right The constant value to compare to. + * @param fieldName The field name to compare. + * @param value The constant value to compare to. * @return A new `Expr` representing the greater than or equal to comparison. */ -export function gte(left: string, right: any): Gte; -export function gte(left: Expr | string, right: any): Gte { - const leftExpr = left instanceof Expr ? left : Field.of(left); - const rightExpr = right instanceof Expr ? right : Constant.of(right); - return new Gte(leftExpr, rightExpr); +export function gte(fieldName: string, value: unknown): BooleanExpr; +export function gte( + left: firestore.Expr | string, + right: unknown +): BooleanExpr { + const leftExpr = fieldOrExpression(left); + const rightExpr = valueToDefaultExpr(right); + return leftExpr.gte(rightExpr); } /** @@ -4077,30 +4265,19 @@ export function gte(left: Expr | string, right: any): Gte { * * ```typescript * // Combine the 'items' array with two new item arrays - * arrayConcat(Field.of("items"), [Field.of("newItems"), Field.of("otherItems")]); - * ``` - * - * @param array The array expression to concatenate to. - * @param elements The array expressions to concatenate. - * @return A new {@code Expr} representing the concatenated array. - */ -export function arrayConcat(array: Expr, elements: Expr[]): ArrayConcat; - -/** - * @beta - * - * Creates an expression that concatenates an array expression with other arrays and/or values. - * - * ```typescript - * // Combine the 'tags' array with a new array - * arrayConcat(Field.of("tags"), ["newTag1", "newTag2"]); + * arrayConcat(field("items"), [field("newItems"), field("otherItems")]); * ``` * - * @param array The array expression to concatenate to. - * @param elements The array expressions or single values to concatenate. + * @param firstArray The first array expression to concatenate to. + * @param secondArray The second array expression or array literal to concatenate to. + * @param otherArrays Optional additional array expressions or array literals to concatenate. * @return A new {@code Expr} representing the concatenated array. */ -export function arrayConcat(array: Expr, elements: any[]): ArrayConcat; +export function arrayConcat( + firstArray: firestore.Expr, + secondArray: firestore.Expr | unknown[], + ...otherArrays: Array +): FunctionExpr; /** * @beta @@ -4109,39 +4286,30 @@ export function arrayConcat(array: Expr, elements: any[]): ArrayConcat; * * ```typescript * // Combine the 'items' array with two new item arrays - * arrayConcat("items", [Field.of("newItems"), Field.of("otherItems")]); + * arrayConcat("items", [field("newItems"), field("otherItems")]); * ``` * - * @param array The field name containing array values. - * @param elements The array expressions to concatenate. + * @param firstArrayField The first array to concatenate to. + * @param secondArray The second array expression or array literal to concatenate to. + * @param otherArrays Optional additional array expressions or array literals to concatenate. * @return A new {@code Expr} representing the concatenated array. */ -export function arrayConcat(array: string, elements: Expr[]): ArrayConcat; +export function arrayConcat( + firstArrayField: string, + secondArray: firestore.Expr | unknown[], + ...otherArrays: Array +): FunctionExpr; -/** - * @beta - * - * Creates an expression that concatenates a field's array value with other arrays and/or values. - * - * ```typescript - * // Combine the 'tags' array with a new array - * arrayConcat("tags", ["newTag1", "newTag2"]); - * ``` - * - * @param array The field name containing array values. - * @param elements The array expressions or single values to concatenate. - * @return A new {@code Expr} representing the concatenated array. - */ -export function arrayConcat(array: string, elements: any[]): ArrayConcat; export function arrayConcat( - array: Expr | string, - elements: any[] -): ArrayConcat { - const arrayExpr = array instanceof Expr ? array : Field.of(array); - const exprValues = elements.map(element => - element instanceof Expr ? element : Constant.of(element) + firstArray: firestore.Expr | string, + secondArray: firestore.Expr | unknown[], + ...otherArrays: Array +): FunctionExpr { + const exprValues = otherArrays.map(element => valueToDefaultExpr(element)); + return fieldOrExpression(firstArray).arrayConcat( + fieldOrExpression(secondArray), + ...exprValues ); - return new ArrayConcat(arrayExpr, exprValues); } /** @@ -4151,14 +4319,17 @@ export function arrayConcat( * * ```typescript * // Check if the 'colors' array contains the value of field 'selectedColor' - * arrayContains(Field.of("colors"), Field.of("selectedColor")); + * arrayContains(field("colors"), field("selectedColor")); * ``` * * @param array The array expression to check. * @param element The element to search for in the array. * @return A new {@code Expr} representing the 'array_contains' comparison. */ -export function arrayContains(array: Expr, element: Expr): ArrayContains; +export function arrayContains( + array: firestore.Expr, + element: firestore.Expr +): FunctionExpr; /** * @beta @@ -4167,14 +4338,17 @@ export function arrayContains(array: Expr, element: Expr): ArrayContains; * * ```typescript * // Check if the 'colors' array contains "red" - * arrayContains(Field.of("colors"), "red"); + * arrayContains(field("colors"), "red"); * ``` * * @param array The array expression to check. * @param element The element to search for in the array. * @return A new {@code Expr} representing the 'array_contains' comparison. */ -export function arrayContains(array: Expr, element: any): ArrayContains; +export function arrayContains( + array: firestore.Expr, + element: unknown +): FunctionExpr; /** * @beta @@ -4183,14 +4357,17 @@ export function arrayContains(array: Expr, element: any): ArrayContains; * * ```typescript * // Check if the 'colors' array contains the value of field 'selectedColor' - * arrayContains("colors", Field.of("selectedColor")); + * arrayContains("colors", field("selectedColor")); * ``` * - * @param array The field name to check. + * @param fieldName The field name to check. * @param element The element to search for in the array. * @return A new {@code Expr} representing the 'array_contains' comparison. */ -export function arrayContains(array: string, element: Expr): ArrayContains; +export function arrayContains( + fieldName: string, + element: firestore.Expr +): FunctionExpr; /** * @beta @@ -4202,18 +4379,18 @@ export function arrayContains(array: string, element: Expr): ArrayContains; * arrayContains("colors", "red"); * ``` * - * @param array The field name to check. + * @param fieldName The field name to check. * @param element The element to search for in the array. * @return A new {@code Expr} representing the 'array_contains' comparison. */ -export function arrayContains(array: string, element: any): ArrayContains; +export function arrayContains(fieldName: string, element: unknown): BooleanExpr; export function arrayContains( - array: Expr | string, - element: any -): ArrayContains { - const arrayExpr = array instanceof Expr ? array : Field.of(array); - const elementExpr = element instanceof Expr ? element : Constant.of(element); - return new ArrayContains(arrayExpr, elementExpr); + array: firestore.Expr | string, + element: unknown +): BooleanExpr { + const arrayExpr = fieldOrExpression(array); + const elementExpr = valueToDefaultExpr(element); + return arrayExpr.arrayContains(elementExpr); } /** @@ -4224,52 +4401,58 @@ export function arrayContains( * * ```typescript * // Check if the 'categories' array contains either values from field "cate1" or "Science" - * arrayContainsAny(Field.of("categories"), [Field.of("cate1"), "Science"]); + * arrayContainsAny(field("categories"), [field("cate1"), "Science"]); * ``` * * @param array The array expression to check. * @param values The elements to check for in the array. * @return A new {@code Expr} representing the 'array_contains_any' comparison. */ -export function arrayContainsAny(array: Expr, values: Expr[]): ArrayContainsAny; +export function arrayContainsAny( + array: firestore.Expr, + values: Array +): BooleanExpr; /** * @beta * - * Creates an expression that checks if an array expression contains any of the specified + * Creates an expression that checks if a field's array value contains any of the specified * elements. * * ```typescript - * // Check if the 'categories' array contains either values from field "cate1" or "Science" - * arrayContainsAny(Field.of("categories"), [Field.of("cate1"), "Science"]); + * // Check if the 'groups' array contains either the value from the 'userGroup' field + * // or the value "guest" + * arrayContainsAny("categories", [field("cate1"), "Science"]); * ``` * - * @param array The array expression to check. + * @param fieldName The field name to check. * @param values The elements to check for in the array. * @return A new {@code Expr} representing the 'array_contains_any' comparison. */ -export function arrayContainsAny(array: Expr, values: any[]): ArrayContainsAny; +export function arrayContainsAny( + fieldName: string, + values: Array +): BooleanExpr; /** * @beta * - * Creates an expression that checks if a field's array value contains any of the specified + * Creates an expression that checks if an array expression contains any of the specified * elements. * * ```typescript - * // Check if the 'groups' array contains either the value from the 'userGroup' field - * // or the value "guest" - * arrayContainsAny("categories", [Field.of("cate1"), "Science"]); + * // Check if the 'categories' array contains either values from field "cate1" or "Science" + * arrayContainsAny(field("categories"), array([field("cate1"), "Science"])); * ``` * - * @param array The field name to check. - * @param values The elements to check for in the array. + * @param array The array expression to check. + * @param values An expression that evaluates to an array, whose elements to check for in the array. * @return A new {@code Expr} representing the 'array_contains_any' comparison. */ export function arrayContainsAny( - array: string, - values: Expr[] -): ArrayContainsAny; + array: firestore.Expr, + values: firestore.Expr +): BooleanExpr; /** * @beta @@ -4280,26 +4463,23 @@ export function arrayContainsAny( * ```typescript * // Check if the 'groups' array contains either the value from the 'userGroup' field * // or the value "guest" - * arrayContainsAny("categories", [Field.of("cate1"), "Science"]); + * arrayContainsAny("categories", array([field("cate1"), "Science"])); * ``` * - * @param array The field name to check. - * @param values The elements to check for in the array. + * @param fieldName The field name to check. + * @param values An expression that evaluates to an array, whose elements to check for in the array field. * @return A new {@code Expr} representing the 'array_contains_any' comparison. */ export function arrayContainsAny( - array: string, - values: any[] -): ArrayContainsAny; + fieldName: string, + values: firestore.Expr +): BooleanExpr; export function arrayContainsAny( - array: Expr | string, - values: any[] -): ArrayContainsAny { - const arrayExpr = array instanceof Expr ? array : Field.of(array); - const exprValues = values.map(value => - value instanceof Expr ? value : Constant.of(value) - ); - return new ArrayContainsAny(arrayExpr, exprValues); + array: firestore.Expr | string, + values: unknown[] | firestore.Expr +): BooleanExpr { + // @ts-ignore implementation accepts both types + return fieldOrExpression(array).arrayContainsAny(values); } /** @@ -4308,51 +4488,57 @@ export function arrayContainsAny( * Creates an expression that checks if an array expression contains all the specified elements. * * ```typescript - * // Check if the 'tags' array contains both of the values from field 'tag1', 'tag2' and "tag3" - * arrayContainsAll(Field.of("tags"), [Field.of("tag1"), "SciFi", "Adventure"]); + * // Check if the "tags" array contains all of the values: "SciFi", "Adventure", and the value from field "tag1" + * arrayContainsAll(field("tags"), [field("tag1"), constant("SciFi"), "Adventure"]); * ``` * * @param array The array expression to check. * @param values The elements to check for in the array. * @return A new {@code Expr} representing the 'array_contains_all' comparison. */ -export function arrayContainsAll(array: Expr, values: Expr[]): ArrayContainsAll; +export function arrayContainsAll( + array: firestore.Expr, + values: Array +): BooleanExpr; /** * @beta * - * Creates an expression that checks if an array expression contains all the specified elements. + * Creates an expression that checks if a field's array value contains all the specified values or + * expressions. * * ```typescript - * // Check if the 'tags' array contains both of the values from field 'tag1', 'tag2' and "tag3" - * arrayContainsAll(Field.of("tags"), [Field.of("tag1"), "SciFi", "Adventure"]); + * // Check if the 'tags' array contains both of the values from field 'tag1', the value "SciFi", and "Adventure" + * arrayContainsAll("tags", [field("tag1"), "SciFi", "Adventure"]); * ``` * - * @param array The array expression to check. + * @param fieldName The field name to check. * @param values The elements to check for in the array. * @return A new {@code Expr} representing the 'array_contains_all' comparison. */ -export function arrayContainsAll(array: Expr, values: any[]): ArrayContainsAll; +export function arrayContainsAll( + fieldName: string, + values: Array +): BooleanExpr; /** * @beta * - * Creates an expression that checks if a field's array value contains all the specified values or - * expressions. + * Creates an expression that checks if an array expression contains all the specified elements. * * ```typescript - * // Check if the 'tags' array contains both of the values from field 'tag1' and "tag2" - * arrayContainsAll("tags", [Field.of("tag1"), "SciFi", "Adventure"]); + * // Check if the "tags" array contains all of the values: "SciFi", "Adventure", and the value from field "tag1" + * arrayContainsAll(field("tags"), [field("tag1"), constant("SciFi"), "Adventure"]); * ``` * - * @param array The field name to check. - * @param values The elements to check for in the array. + * @param array The array expression to check. + * @param arrayExpression The elements to check for in the array. * @return A new {@code Expr} representing the 'array_contains_all' comparison. */ export function arrayContainsAll( - array: string, - values: Expr[] -): ArrayContainsAll; + array: firestore.Expr, + arrayExpression: firestore.Expr +): BooleanExpr; /** * @beta @@ -4361,96 +4547,97 @@ export function arrayContainsAll( * expressions. * * ```typescript - * // Check if the 'tags' array contains both of the values from field 'tag1' and "tag2" - * arrayContainsAll("tags", [Field.of("tag1"), "SciFi", "Adventure"]); + * // Check if the 'tags' array contains both of the values from field 'tag1', the value "SciFi", and "Adventure" + * arrayContainsAll("tags", [field("tag1"), "SciFi", "Adventure"]); * ``` * - * @param array The field name to check. - * @param values The elements to check for in the array. + * @param fieldName The field name to check. + * @param arrayExpression The elements to check for in the array. * @return A new {@code Expr} representing the 'array_contains_all' comparison. */ export function arrayContainsAll( - array: string, - values: any[] -): ArrayContainsAll; + fieldName: string, + arrayExpression: firestore.Expr +): BooleanExpr; export function arrayContainsAll( - array: Expr | string, - values: any[] -): ArrayContainsAll { - const arrayExpr = array instanceof Expr ? array : Field.of(array); - const exprValues = values.map(value => - value instanceof Expr ? value : Constant.of(value) - ); - return new ArrayContainsAll(arrayExpr, exprValues); + array: firestore.Expr | string, + values: unknown[] | firestore.Expr +): BooleanExpr { + // @ts-ignore implementation accepts both types + return fieldOrExpression(array).arrayContainsAll(values); } /** * @beta * - * Creates an expression that calculates the length of an array expression. + * Creates an expression that calculates the length of an array in a specified field. * * ```typescript - * // Get the number of items in the 'cart' array - * arrayLength(Field.of("cart")); + * // Get the number of items in field 'cart' + * arrayLength('cart'); * ``` * - * @param array The array expression to calculate the length of. + * @param fieldName The name of the field containing an array to calculate the length of. * @return A new {@code Expr} representing the length of the array. */ -export function arrayLength(array: Expr): ArrayLength { - return new ArrayLength(array); -} +export function arrayLength(fieldName: string): FunctionExpr; /** * @beta * - * Creates an expression that checks if an expression is equal to any of the provided values or - * expressions. + * Creates an expression that calculates the length of an array expression. * * ```typescript - * // Check if the 'category' field is either "Electronics" or value of field 'primaryType' - * eqAny(Field.of("category"), [Constant.of("Electronics"), Field.of("primaryType")]); + * // Get the number of items in the 'cart' array + * arrayLength(field("cart")); * ``` * - * @param element The expression to compare. - * @param others The values to check against. - * @return A new {@code Expr} representing the 'eqAny' comparison. + * @param array The array expression to calculate the length of. + * @return A new {@code Expr} representing the length of the array. */ -export function eqAny(element: Expr, others: Expr[]): EqAny; +export function arrayLength(array: firestore.Expr): FunctionExpr; +export function arrayLength(array: firestore.Expr | string): FunctionExpr { + return fieldOrExpression(array).arrayLength(); +} /** * @beta * - * Creates an expression that checks if an expression is equal to any of the provided values or + * Creates an expression that checks if an expression, when evaluated, is equal to any of the provided values or * expressions. * * ```typescript * // Check if the 'category' field is either "Electronics" or value of field 'primaryType' - * eqAny(Field.of("category"), ["Electronics", Field.of("primaryType")]); + * eqAny(field("category"), [constant("Electronics"), field("primaryType")]); * ``` * - * @param element The expression to compare. - * @param others The values to check against. - * @return A new {@code Expr} representing the 'eqAny' comparison. + * @param expression The expression whose results to compare. + * @param values The values to check against. + * @return A new {@code Expr} representing the 'IN' comparison. */ -export function eqAny(element: Expr, others: any[]): EqAny; +export function eqAny( + expression: firestore.Expr, + values: Array +): BooleanExpr; /** * @beta * - * Creates an expression that checks if a field's value is equal to any of the provided values or - * expressions. + * Creates an expression that checks if an expression is equal to any of the provided values. * * ```typescript - * // Check if the 'category' field is either "Electronics" or value of field 'primaryType' - * eqAny("category", [Constant.of("Electronics"), Field.of("primaryType")]); + * // Check if the 'category' field is set to a value in the disabledCategories field + * eqAny(field("category"), field('disabledCategories')); * ``` * - * @param element The field to compare. - * @param others The values to check against. - * @return A new {@code Expr} representing the 'eqAny' comparison. + * @param expression The expression whose results to compare. + * @param arrayExpression An expression that evaluates to an array, whose elements to check for equality to the input. + * @return A new {@code Expr} representing the 'IN' comparison. */ -export function eqAny(element: string, others: Expr[]): EqAny; +export function eqAny( + expression: firestore.Expr, + arrayExpression: firestore.Expr +): BooleanExpr; /** * @beta @@ -4460,38 +4647,44 @@ export function eqAny(element: string, others: Expr[]): EqAny; * * ```typescript * // Check if the 'category' field is either "Electronics" or value of field 'primaryType' - * eqAny("category", ["Electronics", Field.of("primaryType")]); + * eqAny("category", [constant("Electronics"), field("primaryType")]); * ``` * - * @param element The field to compare. - * @param others The values to check against. - * @return A new {@code Expr} representing the 'eqAny' comparison. + * @param fieldName The field to compare. + * @param values The values to check against. + * @return A new {@code Expr} representing the 'IN' comparison. */ -export function eqAny(element: string, others: any[]): EqAny; -export function eqAny(element: Expr | string, others: any[]): EqAny { - const elementExpr = element instanceof Expr ? element : Field.of(element); - const exprOthers = others.map(other => - other instanceof Expr ? other : Constant.of(other) - ); - return new EqAny(elementExpr, exprOthers); -} +export function eqAny( + fieldName: string, + values: Array +): BooleanExpr; /** * @beta * - * Creates an expression that checks if an expression is not equal to any of the provided values - * or expressions. + * Creates an expression that checks if a field's value is equal to any of the provided values or + * expressions. * * ```typescript - * // Check if the 'status' field is neither "pending" nor the value of 'rejectedStatus' - * notEqAny(Field.of("status"), [Constant.of("pending"), Field.of("rejectedStatus")]); + * // Check if the 'category' field is either "Electronics" or value of field 'primaryType' + * eqAny("category", ["Electronics", field("primaryType")]); * ``` * - * @param element The expression to compare. - * @param others The values to check against. - * @return A new {@code Expr} representing the 'NotEqAny' comparison. + * @param fieldName The field to compare. + * @param arrayExpression An expression that evaluates to an array, whose elements to check for equality to the input field. + * @return A new {@code Expr} representing the 'IN' comparison. */ -export function notEqAny(element: Expr, others: Expr[]): NotEqAny; +export function eqAny( + fieldName: string, + arrayExpression: firestore.Expr +): BooleanExpr; +export function eqAny( + element: firestore.Expr | string, + values: unknown[] | firestore.Expr +): BooleanExpr { + // @ts-ignore implementation accepts both types + return fieldOrExpression(element).eqAny(values); +} /** * @beta @@ -4501,14 +4694,17 @@ export function notEqAny(element: Expr, others: Expr[]): NotEqAny; * * ```typescript * // Check if the 'status' field is neither "pending" nor the value of 'rejectedStatus' - * notEqAny(Field.of("status"), ["pending", Field.of("rejectedStatus")]); + * notEqAny(field("status"), ["pending", field("rejectedStatus")]); * ``` * * @param element The expression to compare. - * @param others The values to check against. - * @return A new {@code Expr} representing the 'NotEqAny' comparison. + * @param values The values to check against. + * @return A new {@code Expr} representing the 'NOT IN' comparison. */ -export function notEqAny(element: Expr, others: any[]): NotEqAny; +export function notEqAny( + element: firestore.Expr, + values: Array +): BooleanExpr; /** * @beta @@ -4518,82 +4714,69 @@ export function notEqAny(element: Expr, others: any[]): NotEqAny; * * ```typescript * // Check if the 'status' field is neither "pending" nor the value of 'rejectedStatus' - * notEqAny("status", ["pending", Field.of("rejectedStatus")]); + * notEqAny("status", [constant("pending"), field("rejectedStatus")]); * ``` * - * @param element The field name to compare. - * @param others The values to check against. - * @return A new {@code Expr} representing the 'NotEqAny' comparison. + * @param fieldName The field name to compare. + * @param values The values to check against. + * @return A new {@code Expr} representing the 'NOT IN' comparison. */ -export function notEqAny(element: string, others: Expr[]): NotEqAny; +export function notEqAny( + fieldName: string, + values: Array +): BooleanExpr; /** * @beta * - * Creates an expression that checks if a field's value is not equal to any of the provided values + * Creates an expression that checks if an expression is not equal to any of the provided values * or expressions. * * ```typescript - * // Check if the 'status' field is neither "pending" nor the value of 'rejectedStatus' - * notEqAny("status", ["pending", Field.of("rejectedStatus")]); + * // Check if the 'status' field is neither "pending" nor the value of the field 'rejectedStatus' + * notEqAny(field("status"), ["pending", field("rejectedStatus")]); * ``` * - * @param element The field name to compare. - * @param others The values to check against. - * @return A new {@code Expr} representing the 'NotEqAny' comparison. + * @param element The expression to compare. + * @param arrayExpression The values to check against. + * @return A new {@code Expr} representing the 'NOT IN' comparison. */ -export function notEqAny(element: string, others: any[]): NotEqAny; -export function notEqAny(element: Expr | string, others: any[]): NotEqAny { - const elementExpr = element instanceof Expr ? element : Field.of(element); - const exprOthers = others.map(other => - other instanceof Expr ? other : Constant.of(other) - ); - return new NotEqAny(elementExpr, exprOthers); -} +export function notEqAny( + element: firestore.Expr, + arrayExpression: firestore.Expr +): BooleanExpr; /** * @beta * - * Creates an expression that performs a logical 'AND' operation on multiple filter conditions. + * Creates an expression that checks if a field's value is not equal to any of the values in the evaluated expression. * * ```typescript - * // Check if the 'age' field is greater than 18 AND the 'city' field is "London" AND - * // the 'status' field is "active" - * const condition = and(gt("age", 18), eq("city", "London"), eq("status", "active")); + * // Check if the 'status' field is not equal to any value in the field 'rejectedStatuses' + * notEqAny("status", field("rejectedStatuses")); * ``` * - * @param left The first filter condition. - * @param right Additional filter conditions to 'AND' together. - * @return A new {@code Expr} representing the logical 'AND' operation. + * @param fieldName The field name to compare. + * @param arrayExpression The values to check against. + * @return A new {@code Expr} representing the 'NOT IN' comparison. */ -export function and(left: FilterExpr, ...right: FilterExpr[]): And { - return new And([left, ...right]); -} +export function notEqAny( + fieldName: string, + arrayExpression: firestore.Expr +): BooleanExpr; -/** - * @beta - * - * Creates an expression that performs a logical 'OR' operation on multiple filter conditions. - * - * ```typescript - * // Check if the 'age' field is greater than 18 OR the 'city' field is "London" OR - * // the 'status' field is "active" - * const condition = or(gt("age", 18), eq("city", "London"), eq("status", "active")); - * ``` - * - * @param left The first filter condition. - * @param right Additional filter conditions to 'OR' together. - * @return A new {@code Expr} representing the logical 'OR' operation. - */ -export function or(left: FilterExpr, ...right: FilterExpr[]): Or { - return new Or([left, ...right]); +export function notEqAny( + element: firestore.Expr | string, + values: unknown[] | firestore.Expr +): BooleanExpr { + // @ts-ignore implementation accepts both types + return fieldOrExpression(element).notEqAny(values); } /** * @beta * - * Creates an expression that performs a logical 'XOR' (exclusive OR) operation on multiple filter - * conditions. + * Creates an expression that performs a logical 'XOR' (exclusive OR) operation on multiple BooleanExprs. * * ```typescript * // Check if only one of the conditions is true: 'age' greater than 18, 'city' is "London", @@ -4604,12 +4787,17 @@ export function or(left: FilterExpr, ...right: FilterExpr[]): Or { * eq("status", "active")); * ``` * - * @param left The first filter condition. - * @param right Additional filter conditions to 'XOR' together. + * @param first The first condition. + * @param second The second condition. + * @param additionalConditions Additional conditions to 'XOR' together. * @return A new {@code Expr} representing the logical 'XOR' operation. */ -export function xor(left: FilterExpr, ...right: FilterExpr[]): Xor { - return new Xor([left, ...right]); +export function xor( + first: BooleanExpr, + second: BooleanExpr, + ...additionalConditions: BooleanExpr[] +): BooleanExpr { + return new BooleanExpr('xor', [first, second, ...additionalConditions]); } /** @@ -4621,7 +4809,7 @@ export function xor(left: FilterExpr, ...right: FilterExpr[]): Xor { * ```typescript * // If 'age' is greater than 18, return "Adult"; otherwise, return "Minor". * cond( - * gt("age", 18), Constant.of("Adult"), Constant.of("Minor")); + * gt("age", 18), constant("Adult"), constant("Minor")); * ``` * * @param condition The condition to evaluate. @@ -4630,11 +4818,11 @@ export function xor(left: FilterExpr, ...right: FilterExpr[]): Xor { * @return A new {@code Expr} representing the conditional expression. */ export function cond( - condition: FilterExpr, - thenExpr: Expr, - elseExpr: Expr -): Cond { - return new Cond(condition, thenExpr, elseExpr); + condition: BooleanExpr, + thenExpr: firestore.Expr, + elseExpr: firestore.Expr +): FunctionExpr { + return new FunctionExpr('cond', [condition, thenExpr, elseExpr]); } /** @@ -4647,155 +4835,126 @@ export function cond( * not(eq("completed", true)); * ``` * - * @param filter The filter condition to negate. + * @param booleanExpr The filter condition to negate. * @return A new {@code Expr} representing the negated filter condition. */ -export function not(filter: FilterExpr): Not { - return new Not(filter); +export function not(booleanExpr: BooleanExpr): BooleanExpr { + return booleanExpr.not(); } /** * @beta * - * Creates an expression that returns the larger value between two expressions, based on Firestore's value type ordering. - * - * ```typescript - * // Returns the larger value between the 'field1' field and the 'field2' field. - * logicalMaximum(Field.of("field1"), Field.of("field2")); - * ``` - * - * @param left The left operand expression. - * @param right The right operand expression. - * @return A new {@code Expr} representing the logical maximum operation. - */ -export function logicalMaximum(left: Expr, right: Expr): LogicalMaximum; - -/** - * @beta - * - * Creates an expression that returns the larger value between an expression and a constant value, based on Firestore's value type ordering. + * Creates an expression that returns the largest value between multiple input + * expressions or literal values. Based on Firestore's value type ordering. * * ```typescript - * // Returns the larger value between the 'value' field and 10. - * logicalMaximum(Field.of("value"), 10); + * // Returns the largest value between the 'field1' field, the 'field2' field, + * // and 1000 + * logicalMaximum(field("field1"), field("field2"), 1000); * ``` * - * @param left The left operand expression. - * @param right The right operand constant. - * @return A new {@code Expr} representing the logical maximum operation. + * @param first The first operand expression. + * @param second The second expression or literal. + * @param others Optional additional expressions or literals. + * @return A new {@code Expr} representing the logical max operation. */ -export function logicalMaximum(left: Expr, right: any): LogicalMaximum; +export function logicalMaximum( + first: firestore.Expr, + second: firestore.Expr | unknown, + ...others: Array +): FunctionExpr; /** * @beta * - * Creates an expression that returns the larger value between a field and an expression, based on Firestore's value type ordering. + * Creates an expression that returns the largest value between multiple input + * expressions or literal values. Based on Firestore's value type ordering. * * ```typescript - * // Returns the larger value between the 'field1' field and the 'field2' field. - * logicalMaximum("field1", Field.of('field2')); + * // Returns the largest value between the 'field1' field, the 'field2' field, + * // and 1000. + * logicalMaximum("field1", field("field2"), 1000); * ``` * - * @param left The left operand field name. - * @param right The right operand expression. - * @return A new {@code Expr} representing the logical maximum operation. + * @param fieldName The first operand field name. + * @param second The second expression or literal. + * @param others Optional additional expressions or literals. + * @return A new {@code Expr} representing the logical max operation. */ -export function logicalMaximum(left: string, right: Expr): LogicalMaximum; +export function logicalMaximum( + fieldName: string, + second: firestore.Expr | unknown, + ...others: Array +): FunctionExpr; -/** - * @beta - * - * Creates an expression that returns the larger value between a field and a constant value, based on Firestore's value type ordering. - * - * ```typescript - * // Returns the larger value between the 'value' field and 10. - * logicalMaximum("value", 10); - * ``` - * - * @param left The left operand field name. - * @param right The right operand constant. - * @return A new {@code Expr} representing the logical maximum operation. - */ -export function logicalMaximum(left: string, right: any): LogicalMaximum; export function logicalMaximum( - left: Expr | string, - right: Expr | any -): LogicalMaximum { - const normalizedLeft = typeof left === 'string' ? Field.of(left) : left; - const normalizedRight = right instanceof Expr ? right : Constant.of(right); - return new LogicalMaximum(normalizedLeft, normalizedRight); + first: firestore.Expr | string, + second: firestore.Expr | unknown, + ...others: Array +): FunctionExpr { + return fieldOrExpression(first).logicalMaximum( + valueToDefaultExpr(second), + ...others.map(value => valueToDefaultExpr(value)) + ); } /** * @beta * - * Creates an expression that returns the smaller value between two expressions, based on Firestore's value type ordering. - * - * ```typescript - * // Returns the smaller value between the 'field1' field and the 'field2' field. - * logicalMinimum(Field.of("field1"), Field.of("field2")); - * ``` - * - * @param left The left operand expression. - * @param right The right operand expression. - * @return A new {@code Expr} representing the logical minimum operation. - */ -export function logicalMinimum(left: Expr, right: Expr): LogicalMinimum; - -/** - * @beta - * - * Creates an expression that returns the smaller value between an expression and a constant value, based on Firestore's value type ordering. + * Creates an expression that returns the smallest value between multiple input + * expressions and literal values. Based on Firestore's value type ordering. * * ```typescript - * // Returns the smaller value between the 'value' field and 10. - * logicalMinimum(Field.of("value"), 10); + * // Returns the smallest value between the 'field1' field, the 'field2' field, + * // and 1000. + * logicalMinimum(field("field1"), field("field2"), 1000); * ``` * - * @param left The left operand expression. - * @param right The right operand constant. - * @return A new {@code Expr} representing the logical minimum operation. + * @param first The first operand expression. + * @param second The second expression or literal. + * @param others Optional additional expressions or literals. + * @return A new {@code Expr} representing the logical min operation. */ -export function logicalMinimum(left: Expr, right: any): LogicalMinimum; +export function logicalMinimum( + first: firestore.Expr, + second: firestore.Expr | unknown, + ...others: Array +): FunctionExpr; /** * @beta * - * Creates an expression that returns the smaller value between a field and an expression, based on Firestore's value type ordering. + * Creates an expression that returns the smallest value between a field's value + * and other input expressions or literal values. + * Based on Firestore's value type ordering. * * ```typescript - * // Returns the smaller value between the 'field1' field and the 'field2' field. - * logicalMinimum("field1", Field.of("field2")); + * // Returns the smallest value between the 'field1' field, the 'field2' field, + * // and 1000. + * logicalMinimum("field1", field("field2"), 1000); * ``` * - * @param left The left operand field name. - * @param right The right operand expression. - * @return A new {@code Expr} representing the logical minimum operation. + * @param fieldName The first operand field name. + * @param second The second expression or literal. + * @param others Optional additional expressions or literals. + * @return A new {@code Expr} representing the logical min operation. */ -export function logicalMinimum(left: string, right: Expr): LogicalMinimum; +export function logicalMinimum( + fieldName: string, + second: firestore.Expr | unknown, + ...others: Array +): FunctionExpr; -/** - * @beta - * - * Creates an expression that returns the smaller value between a field and a constant value, based on Firestore's value type ordering. - * - * ```typescript - * // Returns the smaller value between the 'value' field and 10. - * logicalMinimum("value", 10); - * ``` - * - * @param left The left operand field name. - * @param right The right operand constant. - * @return A new {@code Expr} representing the logical minimum operation. - */ -export function logicalMinimum(left: string, right: any): LogicalMinimum; export function logicalMinimum( - left: Expr | string, - right: Expr | any -): LogicalMinimum { - const normalizedLeft = typeof left === 'string' ? Field.of(left) : left; - const normalizedRight = right instanceof Expr ? right : Constant.of(right); - return new LogicalMinimum(normalizedLeft, normalizedRight); + first: firestore.Expr | string, + second: firestore.Expr | unknown, + ...others: Array +): FunctionExpr { + return fieldOrExpression(first).logicalMinimum( + valueToDefaultExpr(second), + ...others.map(value => valueToDefaultExpr(value)) + ); } /** @@ -4805,13 +4964,13 @@ export function logicalMinimum( * * ```typescript * // Check if the document has a field named "phoneNumber" - * exists(Field.of("phoneNumber")); + * exists(field("phoneNumber")); * ``` * * @param value An expression evaluates to the name of the field to check. * @return A new {@code Expr} representing the 'exists' check. */ -export function exists(value: Expr): Exists; +export function exists(value: firestore.Expr): BooleanExpr; /** * @beta @@ -4823,14 +4982,12 @@ export function exists(value: Expr): Exists; * exists("phoneNumber"); * ``` * - * @param field The field name to check. + * @param fieldName The field name to check. * @return A new {@code Expr} representing the 'exists' check. */ -export function exists(field: string): Exists; -export function exists(valueOrField: Expr | string): Exists { - const valueExpr = - valueOrField instanceof Expr ? valueOrField : Field.of(valueOrField); - return new Exists(valueExpr); +export function exists(fieldName: string): BooleanExpr; +export function exists(valueOrField: firestore.Expr | string): BooleanExpr { + return fieldOrExpression(valueOrField).exists(); } /** @@ -4840,13 +4997,13 @@ export function exists(valueOrField: Expr | string): Exists { * * ```typescript * // Check if the result of a calculation is NaN - * isNaN(Field.of("value").divide(0)); + * isNan(field("value").divide(0)); * ``` * * @param value The expression to check. - * @return A new {@code Expr} representing the 'isNaN' check. + * @return A new {@code Expr} representing the 'isNan' check. */ -export function isNan(value: Expr): IsNan; +export function isNan(value: firestore.Expr): BooleanExpr; /** * @beta @@ -4855,16 +5012,15 @@ export function isNan(value: Expr): IsNan; * * ```typescript * // Check if the result of a calculation is NaN - * isNaN("value"); + * isNan("value"); * ``` * - * @param value The name of the field to check. - * @return A new {@code Expr} representing the 'isNaN' check. + * @param fieldName The name of the field to check. + * @return A new {@code Expr} representing the 'isNan' check. */ -export function isNan(value: string): IsNan; -export function isNan(value: Expr | string): IsNan { - const valueExpr = value instanceof Expr ? value : Field.of(value); - return new IsNan(valueExpr); +export function isNan(fieldName: string): BooleanExpr; +export function isNan(value: firestore.Expr | string): BooleanExpr { + return fieldOrExpression(value).isNan(); } /** @@ -4874,18 +5030,18 @@ export function isNan(value: Expr | string): IsNan { * * ```typescript * // Reverse the value of the 'myString' field. - * reverse(Field.of("myString")); + * reverse(field("myString")); * ``` * - * @param expr The expression representing the string to reverse. + * @param stringExpression An expression evaluating to a string value, which will be reversed. * @return A new {@code Expr} representing the reversed string. */ -export function reverse(expr: Expr): Reverse; +export function reverse(stringExpression: firestore.Expr): FunctionExpr; /** * @beta * - * Creates an expression that reverses a string represented by a field. + * Creates an expression that reverses a string value in the specified field. * * ```typescript * // Reverse the value of the 'myString' field. @@ -4895,10 +5051,9 @@ export function reverse(expr: Expr): Reverse; * @param field The name of the field representing the string to reverse. * @return A new {@code Expr} representing the reversed string. */ -export function reverse(field: string): Reverse; -export function reverse(expr: Expr | string): Reverse { - const normalizedExpr = typeof expr === 'string' ? Field.of(expr) : expr; - return new Reverse(normalizedExpr); +export function reverse(field: string): FunctionExpr; +export function reverse(expr: firestore.Expr | string): FunctionExpr { + return fieldOrExpression(expr).reverse(); } /** @@ -4908,7 +5063,7 @@ export function reverse(expr: Expr | string): Reverse { * * ```typescript * // Replace the first occurrence of "hello" with "hi" in the 'message' field. - * replaceFirst(Field.of("message"), "hello", "hi"); + * replaceFirst(field("message"), "hello", "hi"); * ``` * * @param value The expression representing the string to perform the replacement on. @@ -4917,10 +5072,10 @@ export function reverse(expr: Expr | string): Reverse { * @return A new {@code Expr} representing the string with the first occurrence replaced. */ export function replaceFirst( - value: Expr, + value: firestore.Expr, find: string, replace: string -): ReplaceFirst; +): FunctionExpr; /** * @beta @@ -4930,7 +5085,7 @@ export function replaceFirst( * * ```typescript * // Replace the first occurrence of the value in 'findField' with the value in 'replaceField' in the 'message' field. - * replaceFirst(Field.of("message"), Field.of("findField"), Field.of("replaceField")); + * replaceFirst(field("message"), field("findField"), field("replaceField")); * ``` * * @param value The expression representing the string to perform the replacement on. @@ -4939,10 +5094,10 @@ export function replaceFirst( * @return A new {@code Expr} representing the string with the first occurrence replaced. */ export function replaceFirst( - value: Expr, - find: Expr, - replace: Expr -): ReplaceFirst; + value: firestore.Expr, + find: firestore.Expr, + replace: firestore.Expr +): FunctionExpr; /** * @beta @@ -4954,26 +5109,25 @@ export function replaceFirst( * replaceFirst("message", "hello", "hi"); * ``` * - * @param field The name of the field representing the string to perform the replacement on. + * @param fieldName The name of the field representing the string to perform the replacement on. * @param find The substring to search for. * @param replace The substring to replace the first occurrence of 'find' with. * @return A new {@code Expr} representing the string with the first occurrence replaced. */ export function replaceFirst( - field: string, + fieldName: string, find: string, replace: string -): ReplaceFirst; +): FunctionExpr; export function replaceFirst( - value: Expr | string, - find: Expr | string, - replace: Expr | string -): ReplaceFirst { - const normalizedValue = typeof value === 'string' ? Field.of(value) : value; - const normalizedFind = typeof find === 'string' ? Constant.of(find) : find; - const normalizedReplace = - typeof replace === 'string' ? Constant.of(replace) : replace; - return new ReplaceFirst(normalizedValue, normalizedFind, normalizedReplace); + value: firestore.Expr | string, + find: firestore.Expr | string, + replace: firestore.Expr | string +): FunctionExpr { + const normalizedValue = fieldOrExpression(value); + const normalizedFind = valueToDefaultExpr(find); + const normalizedReplace = valueToDefaultExpr(replace); + return normalizedValue.replaceFirst(normalizedFind, normalizedReplace); } /** @@ -4983,7 +5137,7 @@ export function replaceFirst( * * ```typescript * // Replace all occurrences of "hello" with "hi" in the 'message' field. - * replaceAll(Field.of("message"), "hello", "hi"); + * replaceAll(field("message"), "hello", "hi"); * ``` * * @param value The expression representing the string to perform the replacement on. @@ -4992,10 +5146,10 @@ export function replaceFirst( * @return A new {@code Expr} representing the string with all occurrences replaced. */ export function replaceAll( - value: Expr, + value: firestore.Expr, find: string, replace: string -): ReplaceAll; +): FunctionExpr; /** * @beta @@ -5005,7 +5159,7 @@ export function replaceAll( * * ```typescript * // Replace all occurrences of the value in 'findField' with the value in 'replaceField' in the 'message' field. - * replaceAll(Field.of("message"), Field.of("findField"), Field.of("replaceField")); + * replaceAll(field("message"), field("findField"), field("replaceField")); * ``` * * @param value The expression representing the string to perform the replacement on. @@ -5013,7 +5167,11 @@ export function replaceAll( * @param replace The expression representing the substring to replace all occurrences of 'find' with. * @return A new {@code Expr} representing the string with all occurrences replaced. */ -export function replaceAll(value: Expr, find: Expr, replace: Expr): ReplaceAll; +export function replaceAll( + value: firestore.Expr, + find: firestore.Expr, + replace: firestore.Expr +): FunctionExpr; /** * @beta @@ -5025,26 +5183,25 @@ export function replaceAll(value: Expr, find: Expr, replace: Expr): ReplaceAll; * replaceAll("message", "hello", "hi"); * ``` * - * @param field The name of the field representing the string to perform the replacement on. + * @param fieldName The name of the field representing the string to perform the replacement on. * @param find The substring to search for. * @param replace The substring to replace all occurrences of 'find' with. * @return A new {@code Expr} representing the string with all occurrences replaced. */ export function replaceAll( - field: string, + fieldName: string, find: string, replace: string -): ReplaceAll; +): FunctionExpr; export function replaceAll( - value: Expr | string, - find: Expr | string, - replace: Expr | string -): ReplaceAll { - const normalizedValue = typeof value === 'string' ? Field.of(value) : value; - const normalizedFind = typeof find === 'string' ? Constant.of(find) : find; - const normalizedReplace = - typeof replace === 'string' ? Constant.of(replace) : replace; - return new ReplaceAll(normalizedValue, normalizedFind, normalizedReplace); + value: firestore.Expr | string, + find: firestore.Expr | string, + replace: firestore.Expr | string +): FunctionExpr { + const normalizedValue = fieldOrExpression(value); + const normalizedFind = valueToDefaultExpr(find); + const normalizedReplace = valueToDefaultExpr(replace); + return normalizedValue.replaceAll(normalizedFind, normalizedReplace); } /** @@ -5054,13 +5211,13 @@ export function replaceAll( * * ```typescript * // Calculate the length of the 'myString' field in bytes. - * byteLength(Field.of("myString")); + * byteLength(field("myString")); * ``` * * @param expr The expression representing the string. * @return A new {@code Expr} representing the length of the string in bytes. */ -export function byteLength(expr: Expr): ByteLength; +export function byteLength(expr: firestore.Expr): FunctionExpr; /** * @beta @@ -5072,13 +5229,13 @@ export function byteLength(expr: Expr): ByteLength; * byteLength("myString"); * ``` * - * @param field The name of the field representing the string. + * @param fieldName The name of the field containing the string. * @return A new {@code Expr} representing the length of the string in bytes. */ -export function byteLength(field: string): ByteLength; -export function byteLength(expr: Expr | string): ByteLength { - const normalizedExpr = typeof expr === 'string' ? Field.of(expr) : expr; - return new ByteLength(normalizedExpr); +export function byteLength(fieldName: string): FunctionExpr; +export function byteLength(expr: firestore.Expr | string): FunctionExpr { + const normalizedExpr = fieldOrExpression(expr); + return normalizedExpr.byteLength(); } /** @@ -5091,10 +5248,10 @@ export function byteLength(expr: Expr | string): ByteLength { * strLength("name"); * ``` * - * @param field The name of the field containing the string. + * @param fieldName The name of the field containing the string. * @return A new {@code Expr} representing the length of the string. */ -export function charLength(field: string): CharLength; +export function charLength(fieldName: string): FunctionExpr; /** * @beta @@ -5103,16 +5260,16 @@ export function charLength(field: string): CharLength; * * ```typescript * // Get the character length of the 'name' field in UTF-8. - * strLength(Field.of("name")); + * strLength(field("name")); * ``` * - * @param expr The expression representing the string to calculate the length of. + * @param stringExpression The expression representing the string to calculate the length of. * @return A new {@code Expr} representing the length of the string. */ -export function charLength(expr: Expr): CharLength; -export function charLength(value: Expr | string): CharLength { - const valueExpr = value instanceof Expr ? value : Field.of(value); - return new CharLength(valueExpr); +export function charLength(stringExpression: firestore.Expr): FunctionExpr; +export function charLength(value: firestore.Expr | string): FunctionExpr { + const valueExpr = fieldOrExpression(value); + return valueExpr.charLength(); } /** @@ -5126,11 +5283,11 @@ export function charLength(value: Expr | string): CharLength { * like("title", "%guide%"); * ``` * - * @param left The name of the field containing the string. + * @param fieldName The name of the field containing the string. * @param pattern The pattern to search for. You can use "%" as a wildcard character. * @return A new {@code Expr} representing the 'like' comparison. */ -export function like(left: string, pattern: string): Like; +export function like(fieldName: string, pattern: string): BooleanExpr; /** * @beta @@ -5140,14 +5297,14 @@ export function like(left: string, pattern: string): Like; * * ```typescript * // Check if the 'title' field contains the string "guide" - * like("title", Field.of("pattern")); + * like("title", field("pattern")); * ``` * - * @param left The name of the field containing the string. + * @param fieldName The name of the field containing the string. * @param pattern The pattern to search for. You can use "%" as a wildcard character. * @return A new {@code Expr} representing the 'like' comparison. */ -export function like(left: string, pattern: Expr): Like; +export function like(fieldName: string, pattern: firestore.Expr): BooleanExpr; /** * @beta @@ -5156,14 +5313,17 @@ export function like(left: string, pattern: Expr): Like; * * ```typescript * // Check if the 'title' field contains the string "guide" - * like(Field.of("title"), "%guide%"); + * like(field("title"), "%guide%"); * ``` * - * @param left The expression representing the string to perform the comparison on. + * @param stringExpression The expression representing the string to perform the comparison on. * @param pattern The pattern to search for. You can use "%" as a wildcard character. * @return A new {@code Expr} representing the 'like' comparison. */ -export function like(left: Expr, pattern: string): Like; +export function like( + stringExpression: firestore.Expr, + pattern: string +): BooleanExpr; /** * @beta @@ -5172,18 +5332,24 @@ export function like(left: Expr, pattern: string): Like; * * ```typescript * // Check if the 'title' field contains the string "guide" - * like(Field.of("title"), Field.of("pattern")); + * like(field("title"), field("pattern")); * ``` * - * @param left The expression representing the string to perform the comparison on. + * @param stringExpression The expression representing the string to perform the comparison on. * @param pattern The pattern to search for. You can use "%" as a wildcard character. * @return A new {@code Expr} representing the 'like' comparison. */ -export function like(left: Expr, pattern: Expr): Like; -export function like(left: Expr | string, pattern: Expr | string): Like { - const leftExpr = left instanceof Expr ? left : Field.of(left); - const patternExpr = pattern instanceof Expr ? pattern : Constant.of(pattern); - return new Like(leftExpr, patternExpr); +export function like( + stringExpression: firestore.Expr, + pattern: firestore.Expr +): BooleanExpr; +export function like( + left: firestore.Expr | string, + pattern: firestore.Expr | string +): FunctionExpr { + const leftExpr = fieldOrExpression(left); + const patternExpr = valueToDefaultExpr(pattern); + return leftExpr.like(patternExpr); } /** @@ -5197,11 +5363,11 @@ export function like(left: Expr | string, pattern: Expr | string): Like { * regexContains("description", "(?i)example"); * ``` * - * @param left The name of the field containing the string. + * @param fieldName The name of the field containing the string. * @param pattern The regular expression to use for the search. * @return A new {@code Expr} representing the 'contains' comparison. */ -export function regexContains(left: string, pattern: string): RegexContains; +export function regexContains(fieldName: string, pattern: string): BooleanExpr; /** * @beta @@ -5211,14 +5377,17 @@ export function regexContains(left: string, pattern: string): RegexContains; * * ```typescript * // Check if the 'description' field contains "example" (case-insensitive) - * regexContains("description", Field.of("pattern")); + * regexContains("description", field("pattern")); * ``` * - * @param left The name of the field containing the string. + * @param fieldName The name of the field containing the string. * @param pattern The regular expression to use for the search. * @return A new {@code Expr} representing the 'contains' comparison. */ -export function regexContains(left: string, pattern: Expr): RegexContains; +export function regexContains( + fieldName: string, + pattern: firestore.Expr +): BooleanExpr; /** * @beta @@ -5228,14 +5397,17 @@ export function regexContains(left: string, pattern: Expr): RegexContains; * * ```typescript * // Check if the 'description' field contains "example" (case-insensitive) - * regexContains(Field.of("description"), "(?i)example"); + * regexContains(field("description"), "(?i)example"); * ``` * - * @param left The expression representing the string to perform the comparison on. + * @param stringExpression The expression representing the string to perform the comparison on. * @param pattern The regular expression to use for the search. * @return A new {@code Expr} representing the 'contains' comparison. */ -export function regexContains(left: Expr, pattern: string): RegexContains; +export function regexContains( + stringExpression: firestore.Expr, + pattern: string +): BooleanExpr; /** * @beta @@ -5245,21 +5417,24 @@ export function regexContains(left: Expr, pattern: string): RegexContains; * * ```typescript * // Check if the 'description' field contains "example" (case-insensitive) - * regexContains(Field.of("description"), Field.of("pattern")); + * regexContains(field("description"), field("pattern")); * ``` * - * @param left The expression representing the string to perform the comparison on. + * @param stringExpression The expression representing the string to perform the comparison on. * @param pattern The regular expression to use for the search. * @return A new {@code Expr} representing the 'contains' comparison. */ -export function regexContains(left: Expr, pattern: Expr): RegexContains; export function regexContains( - left: Expr | string, - pattern: Expr | string -): RegexContains { - const leftExpr = left instanceof Expr ? left : Field.of(left); - const patternExpr = pattern instanceof Expr ? pattern : Constant.of(pattern); - return new RegexContains(leftExpr, patternExpr); + stringExpression: firestore.Expr, + pattern: firestore.Expr +): BooleanExpr; +export function regexContains( + left: firestore.Expr | string, + pattern: firestore.Expr | string +): BooleanExpr { + const leftExpr = fieldOrExpression(left); + const patternExpr = valueToDefaultExpr(pattern); + return leftExpr.regexContains(patternExpr); } /** @@ -5272,11 +5447,11 @@ export function regexContains( * regexMatch("email", "[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,}"); * ``` * - * @param left The name of the field containing the string. + * @param fieldName The name of the field containing the string. * @param pattern The regular expression to use for the match. * @return A new {@code Expr} representing the regular expression match. */ -export function regexMatch(left: string, pattern: string): RegexMatch; +export function regexMatch(fieldName: string, pattern: string): BooleanExpr; /** * @beta @@ -5285,14 +5460,17 @@ export function regexMatch(left: string, pattern: string): RegexMatch; * * ```typescript * // Check if the 'email' field matches a valid email pattern - * regexMatch("email", Field.of("pattern")); + * regexMatch("email", field("pattern")); * ``` * - * @param left The name of the field containing the string. + * @param fieldName The name of the field containing the string. * @param pattern The regular expression to use for the match. * @return A new {@code Expr} representing the regular expression match. */ -export function regexMatch(left: string, pattern: Expr): RegexMatch; +export function regexMatch( + fieldName: string, + pattern: firestore.Expr +): BooleanExpr; /** * @beta @@ -5302,14 +5480,17 @@ export function regexMatch(left: string, pattern: Expr): RegexMatch; * * ```typescript * // Check if the 'email' field matches a valid email pattern - * regexMatch(Field.of("email"), "[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,}"); + * regexMatch(field("email"), "[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,}"); * ``` * - * @param left The expression representing the string to match against. + * @param stringExpression The expression representing the string to match against. * @param pattern The regular expression to use for the match. * @return A new {@code Expr} representing the regular expression match. */ -export function regexMatch(left: Expr, pattern: string): RegexMatch; +export function regexMatch( + stringExpression: firestore.Expr, + pattern: string +): BooleanExpr; /** * @beta @@ -5319,21 +5500,24 @@ export function regexMatch(left: Expr, pattern: string): RegexMatch; * * ```typescript * // Check if the 'email' field matches a valid email pattern - * regexMatch(Field.of("email"), Field.of("pattern")); + * regexMatch(field("email"), field("pattern")); * ``` * - * @param left The expression representing the string to match against. + * @param stringExpression The expression representing the string to match against. * @param pattern The regular expression to use for the match. * @return A new {@code Expr} representing the regular expression match. */ -export function regexMatch(left: Expr, pattern: Expr): RegexMatch; export function regexMatch( - left: Expr | string, - pattern: Expr | string -): RegexMatch { - const leftExpr = left instanceof Expr ? left : Field.of(left); - const patternExpr = pattern instanceof Expr ? pattern : Constant.of(pattern); - return new RegexMatch(leftExpr, patternExpr); + stringExpression: firestore.Expr, + pattern: firestore.Expr +): BooleanExpr; +export function regexMatch( + left: firestore.Expr | string, + pattern: firestore.Expr | string +): BooleanExpr { + const leftExpr = fieldOrExpression(left); + const patternExpr = valueToDefaultExpr(pattern); + return leftExpr.regexMatch(patternExpr); } /** @@ -5346,11 +5530,11 @@ export function regexMatch( * strContains("description", "example"); * ``` * - * @param left The name of the field containing the string. + * @param fieldName The name of the field containing the string. * @param substring The substring to search for. * @return A new {@code Expr} representing the 'contains' comparison. */ -export function strContains(left: string, substring: string): StrContains; +export function strContains(fieldName: string, substring: string): BooleanExpr; /** * @beta @@ -5359,14 +5543,17 @@ export function strContains(left: string, substring: string): StrContains; * * ```typescript * // Check if the 'description' field contains the value of the 'keyword' field. - * strContains("description", Field.of("keyword")); + * strContains("description", field("keyword")); * ``` * - * @param left The name of the field containing the string. + * @param fieldName The name of the field containing the string. * @param substring The expression representing the substring to search for. * @return A new {@code Expr} representing the 'contains' comparison. */ -export function strContains(left: string, substring: Expr): StrContains; +export function strContains( + fieldName: string, + substring: firestore.Expr +): BooleanExpr; /** * @beta @@ -5375,14 +5562,17 @@ export function strContains(left: string, substring: Expr): StrContains; * * ```typescript * // Check if the 'description' field contains "example". - * strContains(Field.of("description"), "example"); + * strContains(field("description"), "example"); * ``` * - * @param left The expression representing the string to perform the comparison on. + * @param stringExpression The expression representing the string to perform the comparison on. * @param substring The substring to search for. * @return A new {@code Expr} representing the 'contains' comparison. */ -export function strContains(left: Expr, substring: string): StrContains; +export function strContains( + stringExpression: firestore.Expr, + substring: string +): BooleanExpr; /** * @beta @@ -5391,22 +5581,24 @@ export function strContains(left: Expr, substring: string): StrContains; * * ```typescript * // Check if the 'description' field contains the value of the 'keyword' field. - * strContains(Field.of("description"), Field.of("keyword")); + * strContains(field("description"), field("keyword")); * ``` * - * @param left The expression representing the string to perform the comparison on. + * @param stringExpression The expression representing the string to perform the comparison on. * @param substring The expression representing the substring to search for. * @return A new {@code Expr} representing the 'contains' comparison. */ -export function strContains(left: Expr, substring: Expr): StrContains; export function strContains( - left: Expr | string, - substring: Expr | string -): StrContains { - const leftExpr = left instanceof Expr ? left : Field.of(left); - const substringExpr = - substring instanceof Expr ? substring : Constant.of(substring); - return new StrContains(leftExpr, substringExpr); + stringExpression: firestore.Expr, + substring: firestore.Expr +): BooleanExpr; +export function strContains( + left: firestore.Expr | string, + substring: firestore.Expr | string +): BooleanExpr { + const leftExpr = fieldOrExpression(left); + const substringExpr = valueToDefaultExpr(substring); + return leftExpr.strContains(substringExpr); } /** @@ -5419,11 +5611,11 @@ export function strContains( * startsWith("name", "Mr."); * ``` * - * @param expr The field name to check. + * @param fieldName The field name to check. * @param prefix The prefix to check for. * @return A new {@code Expr} representing the 'starts with' comparison. */ -export function startsWith(expr: string, prefix: string): StartsWith; +export function startsWith(fieldName: string, prefix: string): BooleanExpr; /** * @beta @@ -5432,14 +5624,17 @@ export function startsWith(expr: string, prefix: string): StartsWith; * * ```typescript * // Check if the 'fullName' field starts with the value of the 'firstName' field - * startsWith("fullName", Field.of("firstName")); + * startsWith("fullName", field("firstName")); * ``` * - * @param expr The field name to check. + * @param fieldName The field name to check. * @param prefix The expression representing the prefix. * @return A new {@code Expr} representing the 'starts with' comparison. */ -export function startsWith(expr: string, prefix: Expr): StartsWith; +export function startsWith( + fieldName: string, + prefix: firestore.Expr +): BooleanExpr; /** * @beta @@ -5448,14 +5643,17 @@ export function startsWith(expr: string, prefix: Expr): StartsWith; * * ```typescript * // Check if the result of concatenating 'firstName' and 'lastName' fields starts with "Mr." - * startsWith(Field.of("fullName"), "Mr."); + * startsWith(field("fullName"), "Mr."); * ``` * - * @param expr The expression to check. + * @param stringExpression The expression to check. * @param prefix The prefix to check for. * @return A new {@code Expr} representing the 'starts with' comparison. */ -export function startsWith(expr: Expr, prefix: string): StartsWith; +export function startsWith( + stringExpression: firestore.Expr, + prefix: string +): BooleanExpr; /** * @beta @@ -5464,21 +5662,22 @@ export function startsWith(expr: Expr, prefix: string): StartsWith; * * ```typescript * // Check if the result of concatenating 'firstName' and 'lastName' fields starts with "Mr." - * startsWith(Field.of("fullName"), Field.of("prefix")); + * startsWith(field("fullName"), field("prefix")); * ``` * - * @param expr The expression to check. + * @param stringExpression The expression to check. * @param prefix The prefix to check for. * @return A new {@code Expr} representing the 'starts with' comparison. */ -export function startsWith(expr: Expr, prefix: Expr): StartsWith; export function startsWith( - expr: Expr | string, - prefix: Expr | string -): StartsWith { - const exprLeft = expr instanceof Expr ? expr : Field.of(expr); - const prefixExpr = prefix instanceof Expr ? prefix : Constant.of(prefix); - return new StartsWith(exprLeft, prefixExpr); + stringExpression: firestore.Expr, + prefix: firestore.Expr +): BooleanExpr; +export function startsWith( + expr: firestore.Expr | string, + prefix: firestore.Expr | string +): BooleanExpr { + return fieldOrExpression(expr).startsWith(valueToDefaultExpr(prefix)); } /** @@ -5491,11 +5690,11 @@ export function startsWith( * endsWith("filename", ".txt"); * ``` * - * @param expr The field name to check. + * @param fieldName The field name to check. * @param suffix The postfix to check for. * @return A new {@code Expr} representing the 'ends with' comparison. */ -export function endsWith(expr: string, suffix: string): EndsWith; +export function endsWith(fieldName: string, suffix: string): BooleanExpr; /** * @beta @@ -5504,14 +5703,17 @@ export function endsWith(expr: string, suffix: string): EndsWith; * * ```typescript * // Check if the 'url' field ends with the value of the 'extension' field - * endsWith("url", Field.of("extension")); + * endsWith("url", field("extension")); * ``` * - * @param expr The field name to check. + * @param fieldName The field name to check. * @param suffix The expression representing the postfix. * @return A new {@code Expr} representing the 'ends with' comparison. */ -export function endsWith(expr: string, suffix: Expr): EndsWith; +export function endsWith( + fieldName: string, + suffix: firestore.Expr +): BooleanExpr; /** * @beta @@ -5520,14 +5722,17 @@ export function endsWith(expr: string, suffix: Expr): EndsWith; * * ```typescript * // Check if the result of concatenating 'firstName' and 'lastName' fields ends with "Jr." - * endsWith(Field.of("fullName"), "Jr."); + * endsWith(field("fullName"), "Jr."); * ``` * - * @param expr The expression to check. + * @param stringExpression The expression to check. * @param suffix The postfix to check for. * @return A new {@code Expr} representing the 'ends with' comparison. */ -export function endsWith(expr: Expr, suffix: string): EndsWith; +export function endsWith( + stringExpression: firestore.Expr, + suffix: string +): BooleanExpr; /** * @beta @@ -5536,18 +5741,22 @@ export function endsWith(expr: Expr, suffix: string): EndsWith; * * ```typescript * // Check if the result of concatenating 'firstName' and 'lastName' fields ends with "Jr." - * endsWith(Field.of("fullName"), Constant.of("Jr.")); + * endsWith(field("fullName"), constant("Jr.")); * ``` * - * @param expr The expression to check. + * @param stringExpression The expression to check. * @param suffix The postfix to check for. * @return A new {@code Expr} representing the 'ends with' comparison. */ -export function endsWith(expr: Expr, suffix: Expr): EndsWith; -export function endsWith(expr: Expr | string, suffix: Expr | string): EndsWith { - const exprLeft = expr instanceof Expr ? expr : Field.of(expr); - const suffixExpr = suffix instanceof Expr ? suffix : Constant.of(suffix); - return new EndsWith(exprLeft, suffixExpr); +export function endsWith( + stringExpression: firestore.Expr, + suffix: firestore.Expr +): BooleanExpr; +export function endsWith( + expr: firestore.Expr | string, + suffix: firestore.Expr | string +): BooleanExpr { + return fieldOrExpression(expr).endsWith(valueToDefaultExpr(suffix)); } /** @@ -5560,10 +5769,10 @@ export function endsWith(expr: Expr | string, suffix: Expr | string): EndsWith { * toLower("name"); * ``` * - * @param expr The name of the field containing the string. + * @param fieldName The name of the field containing the string. * @return A new {@code Expr} representing the lowercase string. */ -export function toLower(expr: string): ToLower; +export function toLower(fieldName: string): FunctionExpr; /** * @beta @@ -5572,15 +5781,15 @@ export function toLower(expr: string): ToLower; * * ```typescript * // Convert the 'name' field to lowercase - * toLower(Field.of("name")); + * toLower(field("name")); * ``` * - * @param expr The expression representing the string to convert to lowercase. + * @param stringExpression The expression representing the string to convert to lowercase. * @return A new {@code Expr} representing the lowercase string. */ -export function toLower(expr: Expr): ToLower; -export function toLower(expr: Expr | string): ToLower { - return new ToLower(expr instanceof Expr ? expr : Field.of(expr)); +export function toLower(stringExpression: firestore.Expr): FunctionExpr; +export function toLower(expr: firestore.Expr | string): FunctionExpr { + return fieldOrExpression(expr).toLower(); } /** @@ -5593,10 +5802,10 @@ export function toLower(expr: Expr | string): ToLower { * toUpper("title"); * ``` * - * @param expr The name of the field containing the string. + * @param fieldName The name of the field containing the string. * @return A new {@code Expr} representing the uppercase string. */ -export function toUpper(expr: string): ToUpper; +export function toUpper(fieldName: string): FunctionExpr; /** * @beta @@ -5605,15 +5814,15 @@ export function toUpper(expr: string): ToUpper; * * ```typescript * // Convert the 'title' field to uppercase - * toUppercase(Field.of("title")); + * toUppercase(field("title")); * ``` * - * @param expr The expression representing the string to convert to uppercase. + * @param stringExpression The expression representing the string to convert to uppercase. * @return A new {@code Expr} representing the uppercase string. */ -export function toUpper(expr: Expr): ToUpper; -export function toUpper(expr: Expr | string): ToUpper { - return new ToUpper(expr instanceof Expr ? expr : Field.of(expr)); +export function toUpper(stringExpression: firestore.Expr): FunctionExpr; +export function toUpper(expr: firestore.Expr | string): FunctionExpr { + return fieldOrExpression(expr).toUpper(); } /** @@ -5626,10 +5835,10 @@ export function toUpper(expr: Expr | string): ToUpper { * trim("userInput"); * ``` * - * @param expr The name of the field containing the string. + * @param fieldName The name of the field containing the string. * @return A new {@code Expr} representing the trimmed string. */ -export function trim(expr: string): Trim; +export function trim(fieldName: string): FunctionExpr; /** * @beta @@ -5638,15 +5847,15 @@ export function trim(expr: string): Trim; * * ```typescript * // Trim whitespace from the 'userInput' field - * trim(Field.of("userInput")); + * trim(field("userInput")); * ``` * - * @param expr The expression representing the string to trim. + * @param stringExpression The expression representing the string to trim. * @return A new {@code Expr} representing the trimmed string. */ -export function trim(expr: Expr): Trim; -export function trim(expr: Expr | string): Trim { - return new Trim(expr instanceof Expr ? expr : Field.of(expr)); +export function trim(stringExpression: firestore.Expr): FunctionExpr; +export function trim(expr: firestore.Expr | string): FunctionExpr { + return fieldOrExpression(expr).trim(); } /** @@ -5656,17 +5865,19 @@ export function trim(expr: Expr | string): Trim { * * ```typescript * // Combine the 'firstName', " ", and 'lastName' fields into a single string - * strConcat("firstName", " ", Field.of("lastName")); + * strConcat("firstName", " ", field("lastName")); * ``` * - * @param first The field name containing the initial string value. - * @param elements The expressions (typically strings) to concatenate. + * @param fieldName The field name containing the initial string value. + * @param secondString An expression or string literal to concatenate. + * @param otherStrings Optional additional expressions or literals (typically strings) to concatenate. * @return A new {@code Expr} representing the concatenated string. */ export function strConcat( - first: string, - ...elements: (Expr | string)[] -): StrConcat; + fieldName: string, + secondString: firestore.Expr | string, + ...otherStrings: Array +): FunctionExpr; /** * @beta @@ -5674,23 +5885,28 @@ export function strConcat( * * ```typescript * // Combine the 'firstName', " ", and 'lastName' fields into a single string - * strConcat(Field.of("firstName"), " ", Field.of("lastName")); + * strConcat(field("firstName"), " ", field("lastName")); * ``` * - * @param first The initial string expression to concatenate to. - * @param elements The expressions (typically strings) to concatenate. + * @param firstString The initial string expression to concatenate to. + * @param secondString An expression or string literal to concatenate. + * @param otherStrings Optional additional expressions or literals (typically strings) to concatenate. * @return A new {@code Expr} representing the concatenated string. */ export function strConcat( - first: Expr, - ...elements: (Expr | string)[] -): StrConcat; + firstString: firestore.Expr, + secondString: firestore.Expr | string, + ...otherStrings: Array +): FunctionExpr; export function strConcat( - first: string | Expr, - ...elements: (string | Expr)[] -): StrConcat { - const exprs = elements.map(e => (e instanceof Expr ? e : Constant.of(e))); - return new StrConcat(first instanceof Expr ? first : Field.of(first), exprs); + first: string | firestore.Expr, + second: string | firestore.Expr, + ...elements: Array +): FunctionExpr { + return fieldOrExpression(first).strConcat( + valueToDefaultExpr(second), + ...elements.map(valueToDefaultExpr) + ); } /** @@ -5703,11 +5919,11 @@ export function strConcat( * mapGet("address", "city"); * ``` * - * @param mapField The field name of the map field. + * @param fieldName The field name of the map field. * @param subField The key to access in the map. * @return A new {@code Expr} representing the value associated with the given key in the map. */ -export function mapGet(mapField: string, subField: string): MapGet; +export function mapGet(fieldName: string, subField: string): FunctionExpr; /** * @beta @@ -5716,19 +5932,22 @@ export function mapGet(mapField: string, subField: string): MapGet; * * ```typescript * // Get the 'city' value from the 'address' map field - * mapGet(Field.of("address"), "city"); + * mapGet(field("address"), "city"); * ``` * - * @param mapExpr The expression representing the map. + * @param mapExpression The expression representing the map. * @param subField The key to access in the map. * @return A new {@code Expr} representing the value associated with the given key in the map. */ -export function mapGet(mapExpr: Expr, subField: string): MapGet; -export function mapGet(fieldOrExpr: string | Expr, subField: string): MapGet { - return new MapGet( - typeof fieldOrExpr === 'string' ? Field.of(fieldOrExpr) : fieldOrExpr, - subField - ); +export function mapGet( + mapExpression: firestore.Expr, + subField: string +): FunctionExpr; +export function mapGet( + fieldOrExpr: string | firestore.Expr, + subField: string +): FunctionExpr { + return fieldOrExpression(fieldOrExpr).mapGet(subField); } /** @@ -5737,14 +5956,14 @@ export function mapGet(fieldOrExpr: string | Expr, subField: string): MapGet { * Creates an aggregation that counts the total number of stage inputs. * * ```typescript - * // Count the total number of users - * countAll().as("totalUsers"); + * // Count the total number of input documents + * countAll().as("totalDocument"); * ``` * - * @return A new {@code Accumulator} representing the 'countAll' aggregation. + * @return A new {@code AggregateFunction} representing the 'countAll' aggregation. */ -export function countAll(): Count { - return new Count(undefined, false); +export function countAll(): AggregateFunction { + return new AggregateFunction('count', []); } /** @@ -5755,30 +5974,28 @@ export function countAll(): Count { * * ```typescript * // Count the number of items where the price is greater than 10 - * count(Field.of("price").gt(10)).as("expensiveItemCount"); + * count(field("price").gt(10)).as("expensiveItemCount"); * ``` * - * @param value The expression to count. - * @return A new {@code Accumulator} representing the 'count' aggregation. + * @param expression The expression to count. + * @return A new {@code AggregateFunction} representing the 'count' aggregation. */ -export function count(value: Expr): Count; +export function count(expression: firestore.Expr): AggregateFunction; /** - * Creates an aggregation that counts the number of stage inputs with valid evaluations of the - * provided field. + * Creates an aggregation that counts the number of stage inputs where the input field exists. * * ```typescript * // Count the total number of products * count("productId").as("totalProducts"); * ``` * - * @param value The name of the field to count. - * @return A new {@code Accumulator} representing the 'count' aggregation. + * @param fieldName The name of the field to count. + * @return A new {@code AggregateFunction} representing the 'count' aggregation. */ -export function count(value: string): Count; -export function count(value: Expr | string): Count { - const exprValue = value instanceof Expr ? value : Field.of(value); - return new Count(exprValue, false); +export function count(fieldName: string): AggregateFunction; +export function count(value: firestore.Expr | string): AggregateFunction { + return fieldOrExpression(value).count(); } /** @@ -5789,13 +6006,13 @@ export function count(value: Expr | string): Count { * * ```typescript * // Calculate the total revenue from a set of orders - * sum(Field.of("orderAmount")).as("totalRevenue"); + * sum(field("orderAmount")).as("totalRevenue"); * ``` * - * @param value The expression to sum up. - * @return A new {@code Accumulator} representing the 'sum' aggregation. + * @param expression The expression to sum up. + * @return A new {@code AggregateFunction} representing the 'sum' aggregation. */ -export function sum(value: Expr): Sum; +export function sum(expression: firestore.Expr): AggregateFunction; /** * @beta @@ -5808,13 +6025,12 @@ export function sum(value: Expr): Sum; * sum("orderAmount").as("totalRevenue"); * ``` * - * @param value The name of the field containing numeric values to sum up. - * @return A new {@code Accumulator} representing the 'sum' aggregation. + * @param fieldName The name of the field containing numeric values to sum up. + * @return A new {@code AggregateFunction} representing the 'sum' aggregation. */ -export function sum(value: string): Sum; -export function sum(value: Expr | string): Sum { - const exprValue = value instanceof Expr ? value : Field.of(value); - return new Sum(exprValue, false); +export function sum(fieldName: string): AggregateFunction; +export function sum(value: firestore.Expr | string): AggregateFunction { + return fieldOrExpression(value).sum(); } /** @@ -5825,13 +6041,13 @@ export function sum(value: Expr | string): Sum { * * ```typescript * // Calculate the average age of users - * avg(Field.of("age")).as("averageAge"); + * avg(field("age")).as("averageAge"); * ``` * - * @param value The expression representing the values to average. - * @return A new {@code Accumulator} representing the 'avg' aggregation. + * @param expression The expression representing the values to average. + * @return A new {@code AggregateFunction} representing the 'avg' aggregation. */ -export function avg(value: Expr): Avg; +export function avg(expression: firestore.Expr): AggregateFunction; /** * @beta @@ -5844,13 +6060,12 @@ export function avg(value: Expr): Avg; * avg("age").as("averageAge"); * ``` * - * @param value The name of the field containing numeric values to average. - * @return A new {@code Accumulator} representing the 'avg' aggregation. + * @param fieldName The name of the field containing numeric values to average. + * @return A new {@code AggregateFunction} representing the 'avg' aggregation. */ -export function avg(value: string): Avg; -export function avg(value: Expr | string): Avg { - const exprValue = value instanceof Expr ? value : Field.of(value); - return new Avg(exprValue, false); +export function avg(fieldName: string): AggregateFunction; +export function avg(value: firestore.Expr | string): AggregateFunction { + return fieldOrExpression(value).avg(); } /** @@ -5861,13 +6076,13 @@ export function avg(value: Expr | string): Avg { * * ```typescript * // Find the lowest price of all products - * minimum(Field.of("price")).as("lowestPrice"); + * minimum(field("price")).as("lowestPrice"); * ``` * - * @param value The expression to find the minimum value of. - * @return A new {@code Accumulator} representing the 'minimum' aggregation. + * @param expression The expression to find the minimum value of. + * @return A new {@code AggregateFunction} representing the 'min' aggregation. */ -export function minimum(value: Expr): Minimum; +export function minimum(expression: firestore.Expr): AggregateFunction; /** * @beta @@ -5879,13 +6094,12 @@ export function minimum(value: Expr): Minimum; * minimum("price").as("lowestPrice"); * ``` * - * @param value The name of the field to find the minimum value of. - * @return A new {@code Accumulator} representing the 'minimum' aggregation. + * @param fieldName The name of the field to find the minimum value of. + * @return A new {@code AggregateFunction} representing the 'min' aggregation. */ -export function minimum(value: string): Minimum; -export function minimum(value: Expr | string): Minimum { - const exprValue = value instanceof Expr ? value : Field.of(value); - return new Minimum(exprValue, false); +export function minimum(fieldName: string): AggregateFunction; +export function minimum(value: firestore.Expr | string): AggregateFunction { + return fieldOrExpression(value).minimum(); } /** @@ -5896,13 +6110,13 @@ export function minimum(value: Expr | string): Minimum { * * ```typescript * // Find the highest score in a leaderboard - * maximum(Field.of("score")).as("highestScore"); + * maximum(field("score")).as("highestScore"); * ``` * - * @param value The expression to find the maximum value of. - * @return A new {@code Accumulator} representing the 'maximum' aggregation. + * @param expression The expression to find the maximum value of. + * @return A new {@code AggregateFunction} representing the 'max' aggregation. */ -export function maximum(value: Expr): Maximum; +export function maximum(expression: firestore.Expr): AggregateFunction; /** * @beta @@ -5914,49 +6128,32 @@ export function maximum(value: Expr): Maximum; * maximum("score").as("highestScore"); * ``` * - * @param value The name of the field to find the maximum value of. - * @return A new {@code Accumulator} representing the 'maximum' aggregation. + * @param fieldName The name of the field to find the maximum value of. + * @return A new {@code AggregateFunction} representing the 'max' aggregation. */ -export function maximum(value: string): Maximum; -export function maximum(value: Expr | string): Maximum { - const exprValue = value instanceof Expr ? value : Field.of(value); - return new Maximum(exprValue, false); +export function maximum(fieldName: string): AggregateFunction; +export function maximum(value: firestore.Expr | string): AggregateFunction { + return fieldOrExpression(value).maximum(); } /** * @beta * - * Calculates the Cosine distance between a field's vector value and a double array. + * Calculates the Cosine distance between a field's vector value and a literal vector value. * * ```typescript * // Calculate the Cosine distance between the 'location' field and a target location * cosineDistance("location", [37.7749, -122.4194]); * ``` * - * @param expr The name of the field containing the first vector. - * @param other The other vector (as an array of doubles) to compare against. - * @return A new {@code Expr} representing the Cosine distance between the two vectors. - */ -export function cosineDistance(expr: string, other: number[]): CosineDistance; - -/** - * @beta - * - * Calculates the Cosine distance between a field's vector value and a VectorValue. - * - * ```typescript - * // Calculate the Cosine distance between the 'location' field and a target location - * cosineDistance("location", new VectorValue([37.7749, -122.4194])); - * ``` - * - * @param expr The name of the field containing the first vector. - * @param other The other vector (as a VectorValue) to compare against. + * @param fieldName The name of the field containing the first vector. + * @param vector The other vector (as an array of doubles) or {@link VectorValue} to compare against. * @return A new {@code Expr} representing the Cosine distance between the two vectors. */ export function cosineDistance( - expr: string, - other: VectorValue -): CosineDistance; + fieldName: string, + vector: number[] | VectorValue +): FunctionExpr; /** * @beta @@ -5965,46 +6162,36 @@ export function cosineDistance( * * ```typescript * // Calculate the cosine distance between the 'userVector' field and the 'itemVector' field - * cosineDistance("userVector", Field.of("itemVector")); - * ``` - * - * @param expr The name of the field containing the first vector. - * @param other The other vector (represented as an Expr) to compare against. - * @return A new {@code Expr} representing the cosine distance between the two vectors. - */ -export function cosineDistance(expr: string, other: Expr): CosineDistance; - -/** - * @beta - * - * Calculates the Cosine distance between a vector expression and a double array. - * - * ```typescript - * // Calculate the cosine distance between the 'location' field and a target location - * cosineDistance(Field.of("location"), [37.7749, -122.4194]); + * cosineDistance("userVector", field("itemVector")); * ``` * - * @param expr The first vector (represented as an Expr) to compare against. - * @param other The other vector (as an array of doubles) to compare against. + * @param fieldName The name of the field containing the first vector. + * @param vectorExpression The other vector (represented as an Expr) to compare against. * @return A new {@code Expr} representing the cosine distance between the two vectors. */ -export function cosineDistance(expr: Expr, other: number[]): CosineDistance; +export function cosineDistance( + fieldName: string, + vectorExpression: firestore.Expr +): FunctionExpr; /** * @beta * - * Calculates the Cosine distance between a vector expression and a VectorValue. + * Calculates the Cosine distance between a vector expression and a vector literal. * * ```typescript * // Calculate the cosine distance between the 'location' field and a target location - * cosineDistance(Field.of("location"), new VectorValue([37.7749, -122.4194])); + * cosineDistance(field("location"), [37.7749, -122.4194]); * ``` * - * @param expr The first vector (represented as an Expr) to compare against. - * @param other The other vector (as a VectorValue) to compare against. + * @param vectorExpression The first vector (represented as an Expr) to compare against. + * @param vector The other vector (as an array of doubles or VectorValue) to compare against. * @return A new {@code Expr} representing the cosine distance between the two vectors. */ -export function cosineDistance(expr: Expr, other: VectorValue): CosineDistance; +export function cosineDistance( + vectorExpression: firestore.Expr, + vector: number[] | firestore.Expr +): FunctionExpr; /** * @beta @@ -6013,21 +6200,24 @@ export function cosineDistance(expr: Expr, other: VectorValue): CosineDistance; * * ```typescript * // Calculate the cosine distance between the 'userVector' field and the 'itemVector' field - * cosineDistance(Field.of("userVector"), Field.of("itemVector")); + * cosineDistance(field("userVector"), field("itemVector")); * ``` * - * @param expr The first vector (represented as an Expr) to compare against. - * @param other The other vector (represented as an Expr) to compare against. + * @param vectorExpression The first vector (represented as an Expr) to compare against. + * @param otherVectorExpression The other vector (represented as an Expr) to compare against. * @return A new {@code Expr} representing the cosine distance between the two vectors. */ -export function cosineDistance(expr: Expr, other: Expr): CosineDistance; export function cosineDistance( - expr: Expr | string, - other: Expr | number[] | VectorValue -): CosineDistance { - const expr1 = expr instanceof Expr ? expr : Field.of(expr); - const expr2 = other instanceof Expr ? other : Constant.vector(other); - return new CosineDistance(expr1, expr2); + vectorExpression: firestore.Expr, + otherVectorExpression: firestore.Expr +): FunctionExpr; +export function cosineDistance( + expr: firestore.Expr | string, + other: firestore.Expr | number[] | VectorValue +): FunctionExpr { + const expr1 = fieldOrExpression(expr); + const expr2 = vectorToExpr(other); + return expr1.cosineDistance(expr2); } /** @@ -6040,27 +6230,14 @@ export function cosineDistance( * dotProduct("features", [0.5, 0.8, 0.2]); * ``` * - * @param expr The name of the field containing the first vector. - * @param other The other vector (as an array of doubles) to calculate with. - * @return A new {@code Expr} representing the dot product between the two vectors. - */ -export function dotProduct(expr: string, other: number[]): DotProduct; - -/** - * @beta - * - * Calculates the dot product between a field's vector value and a VectorValue. - * - * ```typescript - * // Calculate the dot product distance between a feature vector and a target vector - * dotProduct("features", new VectorValue([0.5, 0.8, 0.2])); - * ``` - * - * @param expr The name of the field containing the first vector. - * @param other The other vector (as a VectorValue) to calculate with. + * @param fieldName The name of the field containing the first vector. + * @param vector The other vector (as an array of doubles or VectorValue) to calculate with. * @return A new {@code Expr} representing the dot product between the two vectors. */ -export function dotProduct(expr: string, other: VectorValue): DotProduct; +export function dotProduct( + fieldName: string, + vector: number[] | VectorValue +): FunctionExpr; /** * @beta @@ -6069,14 +6246,17 @@ export function dotProduct(expr: string, other: VectorValue): DotProduct; * * ```typescript * // Calculate the dot product distance between two document vectors: 'docVector1' and 'docVector2' - * dotProduct("docVector1", Field.of("docVector2")); + * dotProduct("docVector1", field("docVector2")); * ``` * - * @param expr The name of the field containing the first vector. - * @param other The other vector (represented as an Expr) to calculate with. + * @param fieldName The name of the field containing the first vector. + * @param vectorExpression The other vector (represented as an Expr) to calculate with. * @return A new {@code Expr} representing the dot product between the two vectors. */ -export function dotProduct(expr: string, other: Expr): DotProduct; +export function dotProduct( + fieldName: string, + vectorExpression: firestore.Expr +): FunctionExpr; /** * @beta @@ -6085,30 +6265,17 @@ export function dotProduct(expr: string, other: Expr): DotProduct; * * ```typescript * // Calculate the dot product between a feature vector and a target vector - * dotProduct(Field.of("features"), [0.5, 0.8, 0.2]); - * ``` - * - * @param expr The first vector (represented as an Expr) to calculate with. - * @param other The other vector (as an array of doubles) to calculate with. - * @return A new {@code Expr} representing the dot product between the two vectors. - */ -export function dotProduct(expr: Expr, other: number[]): DotProduct; - -/** - * @beta - * - * Calculates the dot product between a vector expression and a VectorValue. - * - * ```typescript - * // Calculate the dot product between a feature vector and a target vector - * dotProduct(Field.of("features"), new VectorValue([0.5, 0.8, 0.2])); + * dotProduct(field("features"), [0.5, 0.8, 0.2]); * ``` * - * @param expr The first vector (represented as an Expr) to calculate with. - * @param other The other vector (as a VectorValue) to calculate with. + * @param vectorExpression The first vector (represented as an Expr) to calculate with. + * @param vector The other vector (as an array of doubles or VectorValue) to calculate with. * @return A new {@code Expr} representing the dot product between the two vectors. */ -export function dotProduct(expr: Expr, other: VectorValue): DotProduct; +export function dotProduct( + vectorExpression: firestore.Expr, + vector: number[] | VectorValue +): FunctionExpr; /** * @beta @@ -6117,21 +6284,24 @@ export function dotProduct(expr: Expr, other: VectorValue): DotProduct; * * ```typescript * // Calculate the dot product between two document vectors: 'docVector1' and 'docVector2' - * dotProduct(Field.of("docVector1"), Field.of("docVector2")); + * dotProduct(field("docVector1"), field("docVector2")); * ``` * - * @param expr The first vector (represented as an Expr) to calculate with. - * @param other The other vector (represented as an Expr) to calculate with. + * @param vectorExpression The first vector (represented as an Expr) to calculate with. + * @param otherVectorExpression The other vector (represented as an Expr) to calculate with. * @return A new {@code Expr} representing the dot product between the two vectors. */ -export function dotProduct(expr: Expr, other: Expr): DotProduct; export function dotProduct( - expr: Expr | string, - other: Expr | number[] | VectorValue -): DotProduct { - const expr1 = expr instanceof Expr ? expr : Field.of(expr); - const expr2 = other instanceof Expr ? other : Constant.vector(other); - return new DotProduct(expr1, expr2); + vectorExpression: firestore.Expr, + otherVectorExpression: firestore.Expr +): FunctionExpr; +export function dotProduct( + expr: firestore.Expr | string, + other: firestore.Expr | number[] | VectorValue +): FunctionExpr { + const expr1 = fieldOrExpression(expr); + const expr2 = vectorToExpr(other); + return expr1.dotProduct(expr2); } /** @@ -6144,33 +6314,14 @@ export function dotProduct( * euclideanDistance("location", [37.7749, -122.4194]); * ``` * - * @param expr The name of the field containing the first vector. - * @param other The other vector (as an array of doubles) to compare against. + * @param fieldName The name of the field containing the first vector. + * @param vector The other vector (as an array of doubles or VectorValue) to compare against. * @return A new {@code Expr} representing the Euclidean distance between the two vectors. */ export function euclideanDistance( - expr: string, - other: number[] -): EuclideanDistance; - -/** - * @beta - * - * Calculates the Euclidean distance between a field's vector value and a VectorValue. - * - * ```typescript - * // Calculate the Euclidean distance between the 'location' field and a target location - * euclideanDistance("location", new VectorValue([37.7749, -122.4194])); - * ``` - * - * @param expr The name of the field containing the first vector. - * @param other The other vector (as a VectorValue) to compare against. - * @return A new {@code Expr} representing the Euclidean distance between the two vectors. - */ -export function euclideanDistance( - expr: string, - other: VectorValue -): EuclideanDistance; + fieldName: string, + vector: number[] | VectorValue +): FunctionExpr; /** * @beta @@ -6179,14 +6330,17 @@ export function euclideanDistance( * * ```typescript * // Calculate the Euclidean distance between two vector fields: 'pointA' and 'pointB' - * euclideanDistance("pointA", Field.of("pointB")); + * euclideanDistance("pointA", field("pointB")); * ``` * - * @param expr The name of the field containing the first vector. - * @param other The other vector (represented as an Expr) to compare against. + * @param fieldName The name of the field containing the first vector. + * @param vectorExpression The other vector (represented as an Expr) to compare against. * @return A new {@code Expr} representing the Euclidean distance between the two vectors. */ -export function euclideanDistance(expr: string, other: Expr): EuclideanDistance; +export function euclideanDistance( + fieldName: string, + vectorExpression: firestore.Expr +): FunctionExpr; /** * @beta @@ -6196,36 +6350,17 @@ export function euclideanDistance(expr: string, other: Expr): EuclideanDistance; * ```typescript * // Calculate the Euclidean distance between the 'location' field and a target location * - * euclideanDistance(Field.of("location"), [37.7749, -122.4194]); - * ``` - * - * @param expr The first vector (represented as an Expr) to compare against. - * @param other The other vector (as an array of doubles) to compare against. - * @return A new {@code Expr} representing the Euclidean distance between the two vectors. - */ -export function euclideanDistance( - expr: Expr, - other: number[] -): EuclideanDistance; - -/** - * @beta - * - * Calculates the Euclidean distance between a vector expression and a VectorValue. - * - * ```typescript - * // Calculate the Euclidean distance between the 'location' field and a target location - * euclideanDistance(Field.of("location"), new VectorValue([37.7749, -122.4194])); + * euclideanDistance(field("location"), [37.7749, -122.4194]); * ``` * - * @param expr The first vector (represented as an Expr) to compare against. - * @param other The other vector (as a VectorValue) to compare against. + * @param vectorExpression The first vector (represented as an Expr) to compare against. + * @param vector The other vector (as an array of doubles or VectorValue) to compare against. * @return A new {@code Expr} representing the Euclidean distance between the two vectors. */ export function euclideanDistance( - expr: Expr, - other: VectorValue -): EuclideanDistance; + vectorExpression: firestore.Expr, + vector: number[] | VectorValue +): FunctionExpr; /** * @beta @@ -6234,21 +6369,24 @@ export function euclideanDistance( * * ```typescript * // Calculate the Euclidean distance between two vector fields: 'pointA' and 'pointB' - * euclideanDistance(Field.of("pointA"), Field.of("pointB")); + * euclideanDistance(field("pointA"), field("pointB")); * ``` * - * @param expr The first vector (represented as an Expr) to compare against. - * @param other The other vector (represented as an Expr) to compare against. + * @param vectorExpression The first vector (represented as an Expr) to compare against. + * @param otherVectorExpression The other vector (represented as an Expr) to compare against. * @return A new {@code Expr} representing the Euclidean distance between the two vectors. */ -export function euclideanDistance(expr: Expr, other: Expr): EuclideanDistance; export function euclideanDistance( - expr: Expr | string, - other: Expr | number[] | VectorValue -): EuclideanDistance { - const expr1 = expr instanceof Expr ? expr : Field.of(expr); - const expr2 = other instanceof Expr ? other : Constant.vector(other); - return new EuclideanDistance(expr1, expr2); + vectorExpression: firestore.Expr, + otherVectorExpression: firestore.Expr +): FunctionExpr; +export function euclideanDistance( + expr: firestore.Expr | string, + other: firestore.Expr | number[] | VectorValue +): FunctionExpr { + const expr1 = fieldOrExpression(expr); + const expr2 = vectorToExpr(other); + return expr1.euclideanDistance(expr2); } /** @@ -6258,13 +6396,13 @@ export function euclideanDistance( * * ```typescript * // Get the vector length (dimension) of the field 'embedding'. - * vectorLength(Field.of("embedding")); + * vectorLength(field("embedding")); * ``` * - * @param expr The expression representing the Firestore Vector. + * @param vectorExpression The expression representing the Firestore Vector. * @return A new {@code Expr} representing the length of the array. */ -export function vectorLength(expr: Expr): VectorLength; +export function vectorLength(vectorExpression: firestore.Expr): FunctionExpr; /** * @beta @@ -6276,13 +6414,12 @@ export function vectorLength(expr: Expr): VectorLength; * vectorLength("embedding"); * ``` * - * @param field The name of the field representing the Firestore Vector. + * @param fieldName The name of the field representing the Firestore Vector. * @return A new {@code Expr} representing the length of the array. */ -export function vectorLength(field: string): VectorLength; -export function vectorLength(expr: Expr | string): VectorLength { - const normalizedExpr = typeof expr === 'string' ? Field.of(expr) : expr; - return new VectorLength(normalizedExpr); +export function vectorLength(fieldName: string): FunctionExpr; +export function vectorLength(expr: firestore.Expr | string): FunctionExpr { + return fieldOrExpression(expr).vectorLength(); } /** @@ -6293,13 +6430,13 @@ export function vectorLength(expr: Expr | string): VectorLength { * * ```typescript * // Interpret the 'microseconds' field as microseconds since epoch. - * unixMicrosToTimestamp(Field.of("microseconds")); + * unixMicrosToTimestamp(field("microseconds")); * ``` * * @param expr The expression representing the number of microseconds since epoch. * @return A new {@code Expr} representing the timestamp. */ -export function unixMicrosToTimestamp(expr: Expr): UnixMicrosToTimestamp; +export function unixMicrosToTimestamp(expr: firestore.Expr): FunctionExpr; /** * @beta @@ -6312,15 +6449,14 @@ export function unixMicrosToTimestamp(expr: Expr): UnixMicrosToTimestamp; * unixMicrosToTimestamp("microseconds"); * ``` * - * @param field The name of the field representing the number of microseconds since epoch. + * @param fieldName The name of the field representing the number of microseconds since epoch. * @return A new {@code Expr} representing the timestamp. */ -export function unixMicrosToTimestamp(field: string): UnixMicrosToTimestamp; +export function unixMicrosToTimestamp(fieldName: string): FunctionExpr; export function unixMicrosToTimestamp( - expr: Expr | string -): UnixMicrosToTimestamp { - const normalizedExpr = typeof expr === 'string' ? Field.of(expr) : expr; - return new UnixMicrosToTimestamp(normalizedExpr); + expr: firestore.Expr | string +): FunctionExpr { + return fieldOrExpression(expr).unixMicrosToTimestamp(); } /** @@ -6330,13 +6466,13 @@ export function unixMicrosToTimestamp( * * ```typescript * // Convert the 'timestamp' field to microseconds since epoch. - * timestampToUnixMicros(Field.of("timestamp")); + * timestampToUnixMicros(field("timestamp")); * ``` * * @param expr The expression representing the timestamp. * @return A new {@code Expr} representing the number of microseconds since epoch. */ -export function timestampToUnixMicros(expr: Expr): TimestampToUnixMicros; +export function timestampToUnixMicros(expr: firestore.Expr): FunctionExpr; /** * @beta @@ -6348,15 +6484,14 @@ export function timestampToUnixMicros(expr: Expr): TimestampToUnixMicros; * timestampToUnixMicros("timestamp"); * ``` * - * @param field The name of the field representing the timestamp. + * @param fieldName The name of the field representing the timestamp. * @return A new {@code Expr} representing the number of microseconds since epoch. */ -export function timestampToUnixMicros(field: string): TimestampToUnixMicros; +export function timestampToUnixMicros(fieldName: string): FunctionExpr; export function timestampToUnixMicros( - expr: Expr | string -): TimestampToUnixMicros { - const normalizedExpr = typeof expr === 'string' ? Field.of(expr) : expr; - return new TimestampToUnixMicros(normalizedExpr); + expr: firestore.Expr | string +): FunctionExpr { + return fieldOrExpression(expr).timestampToUnixMicros(); } /** @@ -6367,13 +6502,13 @@ export function timestampToUnixMicros( * * ```typescript * // Interpret the 'milliseconds' field as milliseconds since epoch. - * unixMillisToTimestamp(Field.of("milliseconds")); + * unixMillisToTimestamp(field("milliseconds")); * ``` * * @param expr The expression representing the number of milliseconds since epoch. * @return A new {@code Expr} representing the timestamp. */ -export function unixMillisToTimestamp(expr: Expr): UnixMillisToTimestamp; +export function unixMillisToTimestamp(expr: firestore.Expr): FunctionExpr; /** * @beta @@ -6386,15 +6521,15 @@ export function unixMillisToTimestamp(expr: Expr): UnixMillisToTimestamp; * unixMillisToTimestamp("milliseconds"); * ``` * - * @param field The name of the field representing the number of milliseconds since epoch. + * @param fieldName The name of the field representing the number of milliseconds since epoch. * @return A new {@code Expr} representing the timestamp. */ -export function unixMillisToTimestamp(field: string): UnixMillisToTimestamp; +export function unixMillisToTimestamp(fieldName: string): FunctionExpr; export function unixMillisToTimestamp( - expr: Expr | string -): UnixMillisToTimestamp { - const normalizedExpr = typeof expr === 'string' ? Field.of(expr) : expr; - return new UnixMillisToTimestamp(normalizedExpr); + expr: firestore.Expr | string +): FunctionExpr { + const normalizedExpr = fieldOrExpression(expr); + return normalizedExpr.unixMillisToTimestamp(); } /** @@ -6404,13 +6539,13 @@ export function unixMillisToTimestamp( * * ```typescript * // Convert the 'timestamp' field to milliseconds since epoch. - * timestampToUnixMillis(Field.of("timestamp")); + * timestampToUnixMillis(field("timestamp")); * ``` * * @param expr The expression representing the timestamp. * @return A new {@code Expr} representing the number of milliseconds since epoch. */ -export function timestampToUnixMillis(expr: Expr): TimestampToUnixMillis; +export function timestampToUnixMillis(expr: firestore.Expr): FunctionExpr; /** * @beta @@ -6422,15 +6557,15 @@ export function timestampToUnixMillis(expr: Expr): TimestampToUnixMillis; * timestampToUnixMillis("timestamp"); * ``` * - * @param field The name of the field representing the timestamp. + * @param fieldName The name of the field representing the timestamp. * @return A new {@code Expr} representing the number of milliseconds since epoch. */ -export function timestampToUnixMillis(field: string): TimestampToUnixMillis; +export function timestampToUnixMillis(fieldName: string): FunctionExpr; export function timestampToUnixMillis( - expr: Expr | string -): TimestampToUnixMillis { - const normalizedExpr = typeof expr === 'string' ? Field.of(expr) : expr; - return new TimestampToUnixMillis(normalizedExpr); + expr: firestore.Expr | string +): FunctionExpr { + const normalizedExpr = fieldOrExpression(expr); + return normalizedExpr.timestampToUnixMillis(); } /** @@ -6441,13 +6576,13 @@ export function timestampToUnixMillis( * * ```typescript * // Interpret the 'seconds' field as seconds since epoch. - * unixSecondsToTimestamp(Field.of("seconds")); + * unixSecondsToTimestamp(field("seconds")); * ``` * * @param expr The expression representing the number of seconds since epoch. * @return A new {@code Expr} representing the timestamp. */ -export function unixSecondsToTimestamp(expr: Expr): UnixSecondsToTimestamp; +export function unixSecondsToTimestamp(expr: firestore.Expr): FunctionExpr; /** * @beta @@ -6460,15 +6595,15 @@ export function unixSecondsToTimestamp(expr: Expr): UnixSecondsToTimestamp; * unixSecondsToTimestamp("seconds"); * ``` * - * @param field The name of the field representing the number of seconds since epoch. + * @param fieldName The name of the field representing the number of seconds since epoch. * @return A new {@code Expr} representing the timestamp. */ -export function unixSecondsToTimestamp(field: string): UnixSecondsToTimestamp; +export function unixSecondsToTimestamp(fieldName: string): FunctionExpr; export function unixSecondsToTimestamp( - expr: Expr | string -): UnixSecondsToTimestamp { - const normalizedExpr = typeof expr === 'string' ? Field.of(expr) : expr; - return new UnixSecondsToTimestamp(normalizedExpr); + expr: firestore.Expr | string +): FunctionExpr { + const normalizedExpr = fieldOrExpression(expr); + return normalizedExpr.unixSecondsToTimestamp(); } /** @@ -6478,13 +6613,13 @@ export function unixSecondsToTimestamp( * * ```typescript * // Convert the 'timestamp' field to seconds since epoch. - * timestampToUnixSeconds(Field.of("timestamp")); + * timestampToUnixSeconds(field("timestamp")); * ``` * * @param expr The expression representing the timestamp. * @return A new {@code Expr} representing the number of seconds since epoch. */ -export function timestampToUnixSeconds(expr: Expr): TimestampToUnixSeconds; +export function timestampToUnixSeconds(expr: firestore.Expr): FunctionExpr; /** * @beta @@ -6496,15 +6631,15 @@ export function timestampToUnixSeconds(expr: Expr): TimestampToUnixSeconds; * timestampToUnixSeconds("timestamp"); * ``` * - * @param field The name of the field representing the timestamp. + * @param fieldName The name of the field representing the timestamp. * @return A new {@code Expr} representing the number of seconds since epoch. */ -export function timestampToUnixSeconds(field: string): TimestampToUnixSeconds; +export function timestampToUnixSeconds(fieldName: string): FunctionExpr; export function timestampToUnixSeconds( - expr: Expr | string -): TimestampToUnixSeconds { - const normalizedExpr = typeof expr === 'string' ? Field.of(expr) : expr; - return new TimestampToUnixSeconds(normalizedExpr); + expr: firestore.Expr | string +): FunctionExpr { + const normalizedExpr = fieldOrExpression(expr); + return normalizedExpr.timestampToUnixSeconds(); } /** @@ -6514,7 +6649,7 @@ export function timestampToUnixSeconds( * * ```typescript * // Add some duration determined by field 'unit' and 'amount' to the 'timestamp' field. - * timestampAdd(Field.of("timestamp"), Field.of("unit"), Field.of("amount")); + * timestampAdd(field("timestamp"), field("unit"), field("amount")); * ``` * * @param timestamp The expression representing the timestamp. @@ -6523,10 +6658,10 @@ export function timestampToUnixSeconds( * @return A new {@code Expr} representing the resulting timestamp. */ export function timestampAdd( - timestamp: Expr, - unit: Expr, - amount: Expr -): TimestampAdd; + timestamp: firestore.Expr, + unit: firestore.Expr, + amount: firestore.Expr +): FunctionExpr; /** * @beta @@ -6535,7 +6670,7 @@ export function timestampAdd( * * ```typescript * // Add 1 day to the 'timestamp' field. - * timestampAdd(Field.of("timestamp"), "day", 1); + * timestampAdd(field("timestamp"), "day", 1); * ``` * * @param timestamp The expression representing the timestamp. @@ -6544,10 +6679,10 @@ export function timestampAdd( * @return A new {@code Expr} representing the resulting timestamp. */ export function timestampAdd( - timestamp: Expr, + timestamp: firestore.Expr, unit: 'microsecond' | 'millisecond' | 'second' | 'minute' | 'hour' | 'day', amount: number -): TimestampAdd; +): FunctionExpr; /** * @beta @@ -6559,38 +6694,32 @@ export function timestampAdd( * timestampAdd("timestamp", "day", 1); * ``` * - * @param field The name of the field representing the timestamp. + * @param fieldName The name of the field representing the timestamp. * @param unit The unit of time to add (e.g., "day", "hour"). * @param amount The amount of time to add. * @return A new {@code Expr} representing the resulting timestamp. */ export function timestampAdd( - field: string, + fieldName: string, unit: 'microsecond' | 'millisecond' | 'second' | 'minute' | 'hour' | 'day', amount: number -): TimestampAdd; +): FunctionExpr; export function timestampAdd( - timestamp: Expr | string, + timestamp: firestore.Expr | string, unit: - | Expr + | firestore.Expr | 'microsecond' | 'millisecond' | 'second' | 'minute' | 'hour' | 'day', - amount: Expr | number -): TimestampAdd { - const normalizedTimestamp = - typeof timestamp === 'string' ? Field.of(timestamp) : timestamp; - const normalizedUnit = unit instanceof Expr ? unit : Constant.of(unit); - const normalizedAmount = - typeof amount === 'number' ? Constant.of(amount) : amount; - return new TimestampAdd( - normalizedTimestamp, - normalizedUnit, - normalizedAmount - ); + amount: firestore.Expr | number +): FunctionExpr { + const normalizedTimestamp = fieldOrExpression(timestamp); + const normalizedUnit = valueToDefaultExpr(unit); + const normalizedAmount = valueToDefaultExpr(amount); + return normalizedTimestamp.timestampAdd(normalizedUnit, normalizedAmount); } /** @@ -6600,7 +6729,7 @@ export function timestampAdd( * * ```typescript * // Subtract some duration determined by field 'unit' and 'amount' from the 'timestamp' field. - * timestampSub(Field.of("timestamp"), Field.of("unit"), Field.of("amount")); + * timestampSub(field("timestamp"), field("unit"), field("amount")); * ``` * * @param timestamp The expression representing the timestamp. @@ -6609,10 +6738,10 @@ export function timestampAdd( * @return A new {@code Expr} representing the resulting timestamp. */ export function timestampSub( - timestamp: Expr, - unit: Expr, - amount: Expr -): TimestampSub; + timestamp: firestore.Expr, + unit: firestore.Expr, + amount: firestore.Expr +): FunctionExpr; /** * @beta @@ -6621,7 +6750,7 @@ export function timestampSub( * * ```typescript * // Subtract 1 day from the 'timestamp' field. - * timestampSub(Field.of("timestamp"), "day", 1); + * timestampSub(field("timestamp"), "day", 1); * ``` * * @param timestamp The expression representing the timestamp. @@ -6630,10 +6759,10 @@ export function timestampSub( * @return A new {@code Expr} representing the resulting timestamp. */ export function timestampSub( - timestamp: Expr, + timestamp: firestore.Expr, unit: 'microsecond' | 'millisecond' | 'second' | 'minute' | 'hour' | 'day', amount: number -): TimestampSub; +): FunctionExpr; /** * @beta @@ -6645,93 +6774,150 @@ export function timestampSub( * timestampSub("timestamp", "day", 1); * ``` * - * @param field The name of the field representing the timestamp. + * @param fieldName The name of the field representing the timestamp. * @param unit The unit of time to subtract (e.g., "day", "hour"). * @param amount The amount of time to subtract. * @return A new {@code Expr} representing the resulting timestamp. */ export function timestampSub( - field: string, + fieldName: string, unit: 'microsecond' | 'millisecond' | 'second' | 'minute' | 'hour' | 'day', amount: number -): TimestampSub; +): FunctionExpr; export function timestampSub( - timestamp: Expr | string, + timestamp: firestore.Expr | string, unit: - | Expr + | firestore.Expr | 'microsecond' | 'millisecond' | 'second' | 'minute' | 'hour' | 'day', - amount: Expr | number -): TimestampSub { - const normalizedTimestamp = - typeof timestamp === 'string' ? Field.of(timestamp) : timestamp; - const normalizedUnit = unit instanceof Expr ? unit : Constant.of(unit); - const normalizedAmount = - typeof amount === 'number' ? Constant.of(amount) : amount; - return new TimestampSub( - normalizedTimestamp, - normalizedUnit, - normalizedAmount - ); + amount: firestore.Expr | number +): FunctionExpr { + const normalizedTimestamp = fieldOrExpression(timestamp); + const normalizedUnit = valueToDefaultExpr(unit); + const normalizedAmount = valueToDefaultExpr(amount); + return normalizedTimestamp.timestampSub(normalizedUnit, normalizedAmount); } /** * @beta * - * Creates functions that work on the backend but do not exist in the SDK yet. + * Creates an expression that performs a logical 'AND' operation on multiple filter conditions. * * ```typescript - * // Call a user defined function named "myFunc" with the arguments 10 and 20 - * // This is the same of the 'sum(Field.of("price"))', if it did not exist - * genericFunction("sum", [Field.of("price")]); + * // Check if the 'age' field is greater than 18 AND the 'city' field is "London" AND + * // the 'status' field is "active" + * const condition = and(gt("age", 18), eq("city", "London"), eq("status", "active")); * ``` * - * @param name The name of the user defined function. - * @param params The arguments to pass to the function. - * @return A new {@code Function} representing the function call. + * @param first The first filter condition. + * @param second The second filter condition. + * @param more Additional filter conditions to 'AND' together. + * @return A new {@code Expr} representing the logical 'AND' operation. */ -export function genericFunction(name: string, params: Expr[]): Function { - return new Function(name, params); +export function and( + first: BooleanExpr, + second: BooleanExpr, + ...more: BooleanExpr[] +): BooleanExpr { + return new BooleanExpr('and', [first, second, ...more]); } /** * @beta * - * Creates an {@link Ordering} that sorts documents in ascending order based on this expression. + * Creates an expression that performs a logical 'OR' operation on multiple filter conditions. * * ```typescript - * // Sort documents by the 'name' field in ascending order + * // Check if the 'age' field is greater than 18 OR the 'city' field is "London" OR + * // the 'status' field is "active" + * const condition = or(gt("age", 18), eq("city", "London"), eq("status", "active")); + * ``` + * + * @param first The first filter condition. + * @param second The second filter condition. + * @param more Additional filter conditions to 'OR' together. + * @return A new {@code Expr} representing the logical 'OR' operation. + */ +export function or( + first: BooleanExpr, + second: BooleanExpr, + ...more: BooleanExpr[] +): BooleanExpr { + return new BooleanExpr('or', [first, second, ...more]); +} + +/** + * @beta + * + * Creates an {@link Ordering} that sorts documents in ascending order based on an expression. + * + * ```typescript + * // Sort documents by the 'name' field in lowercase in ascending order * firestore.pipeline().collection("users") - * .sort(ascending(Field.of("name"))); + * .sort(ascending(field("name").toLower())); * ``` * * @param expr The expression to create an ascending ordering for. * @return A new `Ordering` for ascending sorting. */ -export function ascending(expr: Expr): Ordering { - return new Ordering(expr, 'ascending'); +export function ascending(expr: firestore.Expr): Ordering; + +/** + * @beta + * + * Creates an {@link Ordering} that sorts documents in ascending order based on a field. + * + * ```typescript + * // Sort documents by the 'name' field in ascending order + * firestore.pipeline().collection("users") + * .sort(ascending("name")); + * ``` + * + * @param fieldName The field to create an ascending ordering for. + * @return A new `Ordering` for ascending sorting. + */ +export function ascending(fieldName: string): Ordering; +export function ascending(field: firestore.Expr | string): Ordering { + return new Ordering(fieldOrExpression(field), 'ascending'); } /** * @beta * - * Creates an {@link Ordering} that sorts documents in descending order based on this expression. + * Creates an {@link Ordering} that sorts documents in descending order based on an expression. * * ```typescript - * // Sort documents by the 'createdAt' field in descending order + * // Sort documents by the 'name' field in lowercase in descending order * firestore.pipeline().collection("users") - * .sort(descending(Field.of("createdAt"))); + * .sort(descending(field("name").toLower())); * ``` * * @param expr The expression to create a descending ordering for. * @return A new `Ordering` for descending sorting. */ -export function descending(expr: Expr): Ordering { - return new Ordering(expr, 'descending'); +export function descending(expr: firestore.Expr): Ordering; + +/** + * @beta + * + * Creates an {@link Ordering} that sorts documents in descending order based on a field. + * + * ```typescript + * // Sort documents by the 'name' field in descending order + * firestore.pipeline().collection("users") + * .sort(descending("name")); + * ``` + * + * @param fieldName The field to create a descending ordering for. + * @return A new `Ordering` for descending sorting. + */ +export function descending(fieldName: string): Ordering; +export function descending(field: firestore.Expr | string): Ordering { + return new Ordering(fieldOrExpression(field), 'descending'); } /** @@ -6743,18 +6929,33 @@ export function descending(expr: Expr): Ordering { */ export class Ordering { constructor( - private expr: Expr, - private direction: 'ascending' | 'descending' + readonly expr: firestore.Expr, + readonly direction: 'ascending' | 'descending' ) {} + /** + * @internal + * @private + * Indicates if this expression was created from a literal value passed + * by the caller. + */ + _createdFromLiteral = false; + + /** + * @private + * @internal + */ _toProto(serializer: Serializer): api.IValue { + const expr = this.expr as Expr; return { mapValue: { fields: { - direction: serializer.encodeValue(this.direction)!, - expression: serializer.encodeValue(this.expr)!, + direction: serializer.encodeValue(this.direction), + expression: expr._toProto(serializer), }, }, }; } + + _protoValueType: 'ProtoValue' = 'ProtoValue' as const; } diff --git a/dev/src/index.ts b/dev/src/index.ts index eaef624ec..5079838a5 100644 --- a/dev/src/index.ts +++ b/dev/src/index.ts @@ -133,93 +133,105 @@ export type { ExplainMetrics, ExplainResults, } from './query-profile'; -export {Pipeline, PipelineResult, PipelineSource} from './pipeline'; +export {Pipeline, PipelineResult, PipelineSource, PipelineSnapshot} from './pipeline'; export type {FindNearestOptions} from './stage'; -export type { - FilterCondition, - FilterExpr, - AccumulatorTarget, - Accumulator, - Selectable, - SelectableExpr, -} from './expression'; export { + Selectable, + BooleanExpr, + AggregateWithAlias, + AggregateFunction, Expr, ExprWithAlias, Field, Constant, - Function, + FunctionExpr, Ordering, - add, - subtract, + constant, + constantVector, + map, + array, + bitNot, + field, + xor, + rand, + arrayOffset, + timestampToUnixMicros, + timestampToUnixSeconds, + unixMicrosToTimestamp, + timestampToUnixMillis, + timestampSub, + timestampAdd, + byteLength, + bitAnd, multiply, + sum, + maximum, + descending, + minimum, + count, + countIf, + arrayLength, + strContains, + charLength, divide, - eq, - neq, - lt, - lte, - gt, - gte, + mod, + reverse, + trim, + toUpper, + toLower, + vectorLength, + isNotNan, + exists, + isNotNull, + isAbsent, + ifError, + isError, + isNan, arrayConcat, - arrayContains, - arrayContainsAny, + substr, + documentId, + isNull, arrayContainsAll, - arrayLength, - eqAny, - notEqAny, + replaceFirst, + replaceAll, + mapRemove, + mapMerge, + unixSecondsToTimestamp, + unixMillisToTimestamp, + bitOr, + bitXor, + bitLeftShift, + bitRightShift, + add, and, - or, - xor, - cond, - not, - exists, - isNan, - charLength, + arrayContains, + arrayContainsAny, + avg, + countAll, + endsWith, + eq, + gt, like, + lt, + neq, + ascending, + not, + or, regexContains, regexMatch, - strContains, startsWith, - endsWith, - toLower, - toUpper, - trim, strConcat, - mapGet, - countAll, - count, - sum, - avg, - minimum, - maximum, + subtract, cosineDistance, dotProduct, euclideanDistance, - genericFunction, - ascending, - descending, - // bitLeftShift, - // bitOr, - // bitRightShift, - // bitXor, - // bitAnd, - // bitNot, - timestampAdd, - timestampSub, - timestampToUnixMicros, - timestampToUnixMillis, - timestampToUnixSeconds, - unixMicrosToTimestamp, - unixMillisToTimestamp, - unixSecondsToTimestamp, - logicalMaximum, + mapGet, + lte, + eqAny, + notEqAny, logicalMinimum, - vectorLength, - byteLength, - reverse, - replaceAll, - replaceFirst, - mod, + logicalMaximum, + cond, } from './expression'; const libVersion = require('../../package.json').version; diff --git a/dev/src/pipeline-util.ts b/dev/src/pipeline-util.ts index 66cf4c9fa..ef9d51239 100644 --- a/dev/src/pipeline-util.ts +++ b/dev/src/pipeline-util.ts @@ -13,24 +13,21 @@ // limitations under the License. import * as firestore from '@google-cloud/firestore'; -import {GoogleError, serializer} from 'google-gax'; -import {converter} from 'protobufjs'; +import {GoogleError} from 'google-gax'; import {Duplex, Transform} from 'stream'; import {google} from '../protos/firestore_v1_proto_api'; import * as protos from '../protos/firestore_v1_proto_api'; import { Expr, - FilterCondition, + BooleanExpr, and, or, - isNan, Field, not, - Constant, - AccumulatorTarget, ExprWithAlias, - Accumulator, + field as createField, + constant, } from './expression'; import Firestore, {DocumentReference, Timestamp} from './index'; import {logger} from './logger'; @@ -40,11 +37,7 @@ import {CompositeFilterInternal} from './reference/composite-filter-internal'; import {NOOP_MESSAGE} from './reference/constants'; import {FieldFilterInternal} from './reference/field-filter-internal'; import {FilterInternal} from './reference/filter-internal'; -import { - PipelineResponse, - PipelineStreamElement, - QueryResponse, -} from './reference/types'; +import {PipelineResponse, PipelineStreamElement} from './reference/types'; import {Serializer} from './serializer'; import { Deferred, @@ -63,32 +56,31 @@ import api = protos.google.firestore.v1; * @private * @internal */ -export class ExecutionUtil { +export class ExecutionUtil { constructor( /** @private */ readonly _firestore: Firestore, /** @private */ - readonly _serializer: Serializer, - readonly _converter: firestore.FirestorePipelineConverter + readonly _serializer: Serializer ) {} _getResponse( - pipeline: Pipeline, + pipeline: Pipeline, transactionOrReadTime?: Uint8Array | Timestamp | api.ITransactionOptions, explainOptions?: firestore.ExplainOptions - ): Promise> { + ): Promise { // Capture the error stack to preserve stack tracing across async calls. const stack = Error().stack!; return new Promise((resolve, reject) => { - const result: Array> = []; - const output: PipelineResponse = {}; + const result: Array = []; + const output: PipelineResponse = {}; this._stream(pipeline, transactionOrReadTime, explainOptions) .on('error', err => { reject(wrapError(err, stack)); }) - .on('data', (data: PipelineStreamElement[]) => { + .on('data', (data: PipelineStreamElement[]) => { for (const element of data) { if (element.transaction) { output.transaction = element.transaction; @@ -125,7 +117,7 @@ export class ExecutionUtil { return Date.now() - startTime >= totalTimeout; } - stream(pipeline: Pipeline): NodeJS.ReadableStream { + stream(pipeline: Pipeline): NodeJS.ReadableStream { const responseStream = this._stream(pipeline); const transform = new Transform({ objectMode: true, @@ -140,13 +132,11 @@ export class ExecutionUtil { } _stream( - pipeline: Pipeline, + pipeline: Pipeline, transactionOrReadTime?: Uint8Array | Timestamp | api.ITransactionOptions, explainOptions?: firestore.ExplainOptions ): NodeJS.ReadableStream { const tag = requestTag(); - const startTime = Date.now(); - const isExplain = explainOptions !== undefined; let backendStream: Duplex; const stream = new Transform({ @@ -162,7 +152,7 @@ export class ExecutionUtil { } if (proto.results && proto.results.length === 0) { - const output: PipelineStreamElement = {}; + const output: PipelineStreamElement = {}; if (proto.transaction?.length) { output.transaction = proto.transaction; } @@ -174,7 +164,7 @@ export class ExecutionUtil { callback( undefined, proto.results.map(result => { - const output: PipelineStreamElement = {}; + const output: PipelineStreamElement = {}; if (proto.transaction?.length) { output.transaction = proto.transaction; } @@ -188,7 +178,7 @@ export class ExecutionUtil { QualifiedResourcePath.fromSlashSeparatedString(result.name) ) : undefined; - output.result = new PipelineResult( + output.result = new PipelineResult( this._serializer, ref, result.fields || undefined, @@ -198,8 +188,7 @@ export class ExecutionUtil { : undefined, result.updateTime ? Timestamp.fromProto(result.updateTime!) - : undefined, - this._converter + : undefined ); return output; }) @@ -401,7 +390,7 @@ export function selectableToExpr( selectable: firestore.Selectable | string ): Expr { if (typeof selectable === 'string') { - return Field.of(selectable); + return createField(selectable); } else if (selectable instanceof Field) { return selectable; } else if (selectable instanceof ExprWithAlias) { @@ -411,17 +400,17 @@ export function selectableToExpr( } } -export function toPipelineFilterCondition( +export function toPipelineBooleanExpr( f: FilterInternal, serializer: Serializer -): FilterCondition & Expr { +): BooleanExpr { if (f instanceof FieldFilterInternal) { - const field = Field.of(f.field); + const field = createField(f.field); if (f.isNanChecking()) { if (f.nanOp() === 'IS_NAN') { - return and(field.exists(), field.isNaN()); + return and(field.exists(), field.isNan()); } else { - return and(field.exists(), not(field.isNaN())); + return and(field.exists(), not(field.isNan())); } } else if (f.isNullChecking()) { if (f.nullOp() === 'IS_NULL') { @@ -450,22 +439,16 @@ export function toPipelineFilterCondition( case 'ARRAY_CONTAINS': return and(field.exists(), field.arrayContains(value)); case 'IN': { - const values = value?.arrayValue?.values?.map(val => - Constant.of(val) - ); - return and(field.exists(), field.eqAny(...values!)); + const values = value?.arrayValue?.values?.map(val => constant(val)); + return and(field.exists(), field.eqAny(values!)); } case 'ARRAY_CONTAINS_ANY': { - const values = value?.arrayValue?.values?.map(val => - Constant.of(val) - ); + const values = value?.arrayValue?.values?.map(val => constant(val)); return and(field.exists(), field.arrayContainsAny(values!)); } case 'NOT_IN': { - const values = value?.arrayValue?.values?.map(val => - Constant.of(val) - ); - return and(field.exists(), field.notEqAny(...values!)); + const values = value?.arrayValue?.values?.map(val => constant(val)); + return and(field.exists(), field.notEqAny(values!)); } } } @@ -474,14 +457,14 @@ export function toPipelineFilterCondition( case 'AND': { const conditions = f .getFilters() - .map(f => toPipelineFilterCondition(f, serializer)); - return and(conditions[0], ...conditions.slice(1)); + .map(f => toPipelineBooleanExpr(f, serializer)); + return and(conditions[0], conditions[1], ...conditions.slice(2)); } case 'OR': { const conditions = f .getFilters() - .map(f => toPipelineFilterCondition(f, serializer)); - return or(conditions[0], ...conditions.slice(1)); + .map(f => toPipelineBooleanExpr(f, serializer)); + return or(conditions[0], conditions[1], ...conditions.slice(2)); } } } diff --git a/dev/src/pipeline.ts b/dev/src/pipeline.ts index b90e18906..16d77fd5e 100644 --- a/dev/src/pipeline.ts +++ b/dev/src/pipeline.ts @@ -16,19 +16,19 @@ import * as firestore from '@google-cloud/firestore'; import * as deepEqual from 'fast-deep-equal'; import {google} from '../protos/firestore_v1_proto_api'; import { - Accumulator, - AccumulatorTarget, + AggregateFunction, + AggregateWithAlias, Expr, ExprWithAlias, Field, - FilterCondition, - Function, + BooleanExpr, Ordering, - Selectable, + field, + fieldOrExpression, } from './expression'; -import Firestore, {FieldPath, QueryDocumentSnapshot, Timestamp} from './index'; +import Firestore, {CollectionReference, FieldPath, Timestamp} from './index'; import {validateFieldPath} from './path'; -import {ExecutionUtil, selectableToExpr} from './pipeline-util'; +import {ExecutionUtil} from './pipeline-util'; import {DocumentReference} from './reference/document-reference'; import {PipelineResponse} from './reference/types'; import {Serializer} from './serializer'; @@ -41,7 +41,6 @@ import { DocumentsSource, Where, FindNearest, - FindNearestOptions, GenericStage, Limit, Offset, @@ -52,17 +51,15 @@ import { RemoveFields, Replace, Sample, - SampleOptions, Union, Unnest, UnnestOptions, } from './stage'; -import {ApiMapValue, defaultPipelineConverter} from './types'; +import {ApiMapValue} from './types'; import * as protos from '../protos/firestore_v1_proto_api'; import api = protos.google.firestore.v1; -import IStructuredPipeline = google.firestore.v1.IStructuredPipeline; import IStage = google.firestore.v1.Pipeline.IStage; -import {isOptionalEqual} from './util'; +import {cast, isOptionalEqual} from './util'; /** * Represents the source of a Firestore {@link Pipeline}. @@ -71,8 +68,15 @@ import {isOptionalEqual} from './util'; export class PipelineSource implements firestore.PipelineSource { constructor(private db: Firestore) {} - collection(collectionPath: string): Pipeline { - return new Pipeline(this.db, [new CollectionSource(collectionPath)]); + collection(collection: string | firestore.CollectionReference): Pipeline { + if (collection instanceof CollectionReference) { + // this._validateReference(collection); + return new Pipeline(this.db, [new CollectionSource(collection.path)]); + } else if (typeof collection === 'string') { + return new Pipeline(this.db, [new CollectionSource(collection)]); + } else { + throw 'Unexpected collection type'; + } } collectionGroup(collectionId: string): Pipeline { @@ -83,8 +87,30 @@ export class PipelineSource implements firestore.PipelineSource { return new Pipeline(this.db, [new DatabaseSource()]); } - documents(docs: DocumentReference[]): Pipeline { - return new Pipeline(this.db, [DocumentsSource.of(docs)]); + /** + * Set the pipeline's source to the documents specified by the given paths and DocumentReferences. + * + * @param docs An array of paths and DocumentReferences specifying the individual documents that will be the source of this pipeline. + * The converters for these DocumentReferences will be ignored and not have an effect on this pipeline. + * + * @throws {@FirestoreError} Thrown if any of the provided DocumentReferences target a different project or database than the pipeline. + */ + documents(docs: Array): Pipeline { + return new Pipeline(this.db, [ + DocumentsSource.of(cast(docs)), + ]); + } + + /** + * Convert the given Query into an equivalent Pipeline. + * + * @param query A Query to be converted into a Pipeline. + * + * @throws {@FirestoreError} Thrown if any of the provided DocumentReferences target a different project or database than the pipeline. + */ + createFrom(query: firestore.Query): Pipeline { + throw 'Not implemented'; + // return query.toPipeline(query._query, query.firestore); } } @@ -113,36 +139,33 @@ export class PipelineSource implements firestore.PipelineSource { * // Example 1: Select specific fields and rename 'rating' to 'bookRating' * const results1 = await db.pipeline() * .collection('books') - * .select('title', 'author', Field.of('rating').as('bookRating')) + * .select('title', 'author', field('rating').as('bookRating')) * .execute(); * * // Example 2: Filter documents where 'genre' is 'Science Fiction' and 'published' is after 1950 * const results2 = await db.pipeline() * .collection('books') - * .where(and(Field.of('genre').eq('Science Fiction'), Field.of('published').gt(1950))) + * .where(and(field('genre').eq('Science Fiction'), field('published').gt(1950))) * .execute(); * * // Example 3: Calculate the average rating of books published after 1980 * const results3 = await db.pipeline() * .collection('books') - * .where(Field.of('published').gt(1980)) - * .aggregate(avg(Field.of('rating')).as('averageRating')) + * .where(field('published').gt(1980)) + * .aggregate(avg(field('rating')).as('averageRating')) * .execute(); * ``` */ -export class Pipeline - implements firestore.Pipeline -{ +export class Pipeline implements firestore.Pipeline { constructor( private db: Firestore, - private stages: Stage[], - private converter: firestore.FirestorePipelineConverter = defaultPipelineConverter() + private stages: Stage[] ) {} - private _addStage(stage: Stage): Pipeline { + private _addStage(stage: Stage): Pipeline { const copy = this.stages.map(s => s); copy.push(stage); - return new Pipeline(this.db, copy, this.converter); + return new Pipeline(this.db, copy); } /** @@ -155,24 +178,30 @@ export class Pipeline * The added fields are defined using {@link Selectable}s, which can be: * * - {@link Field}: References an existing document field. - * - {@link Function}: Performs a calculation using functions like `add`, `multiply` with - * assigned aliases using {@link Expr#as}. + * - {@link Expr}: Either a literal value (see {@link Constant}) or a computed value + * (see {@FunctionExpr}) with an assigned alias using {@link Expr#as}. * * Example: * * ```typescript - * firestore.pipeline().collection('books') + * firestore.pipeline().collection("books") * .addFields( - * Field.of('rating').as('bookRating'), // Rename 'rating' to 'bookRating' - * add(5, Field.of('quantity')).as('totalCost') // Calculate 'totalCost' + * field("rating").as("bookRating"), // Rename 'rating' to 'bookRating' + * add(5, field("quantity")).as("totalCost") // Calculate 'totalCost' * ); * ``` * - * @param fields The fields to add to the documents, specified as {@link Selectable}s. + * @param field The first field to add to the documents, specified as a {@link Selectable}. + * @param additionalFields Optional additional fields to add to the documents, specified as {@link Selectable}s. * @return A new Pipeline object with this stage appended to the stage list. */ - addFields(...fields: firestore.Selectable[]): Pipeline { - return this._addStage(new AddFields(this.selectablesToMap(fields))); + addFields( + field: firestore.Selectable, + ...additionalFields: firestore.Selectable[] + ): Pipeline { + return this._addStage( + new AddFields(this.selectablesToMap([field, ...additionalFields])) + ); } /** @@ -184,20 +213,24 @@ export class Pipeline * firestore.pipeline().collection('books') * // removes field 'rating' and 'cost' from the previous stage outputs. * .removeFields( - * Field.of('rating'), + * field('rating'), * 'cost' * ); * ``` * - * @param fields The fields to remove. + * @param fieldValue The first field to remove. + * @param additionalFields Optional additional fields to remove. * @return A new Pipeline object with this stage appended to the stage list. */ removeFields( - ...fields: (firestore.Field | string)[] - ): Pipeline { + fieldValue: firestore.Field | string, + ...additionalFields: Array + ): Pipeline { return this._addStage( new RemoveFields( - fields.map(f => (typeof f === 'string' ? Field.of(f) : (f as Field))) + [fieldValue, ...additionalFields].map(f => + typeof f === 'string' ? field(f) : (f as Field) + ) ) ); } @@ -215,42 +248,47 @@ export class Pipeline *

* *

If no selections are provided, the output of this stage is empty. Use {@link - * com.google.cloud.firestore.Pipeline#addFields} instead if only additions are + * Pipeline#addFields} instead if only additions are * desired. * *

Example: * * ```typescript - * firestore.pipeline().collection('books') + * firestore.pipeline().collection("books") * .select( - * 'firstName', - * Field.of('lastName'), - * Field.of('address').toUppercase().as('upperAddress'), + * "firstName", + * field("lastName"), + * field("address").toUppercase().as("upperAddress"), * ); * ``` * - * @param selections The fields to include in the output documents, specified as {@link + * @param selection The first field to include in the output documents, specified as {@link + * Selectable} expression or string value representing the field name. + * @param additionalSelections Optional additional fields to include in the output documents, specified as {@link * Selectable} expressions or {@code string} values representing field names. * @return A new Pipeline object with this stage appended to the stage list. */ select( - ...selections: (firestore.Selectable | string)[] - ): Pipeline { - return this._addStage(new Select(this.selectablesToMap(selections))); + selection: firestore.Selectable | string, + ...additionalSelections: Array + ): Pipeline { + return this._addStage( + new Select(this.selectablesToMap([selection, ...additionalSelections])) + ); } private selectablesToMap( - selectables: (Selectable | string)[] + selectables: (firestore.Selectable | string)[] ): Map { const result = new Map(); for (const selectable of selectables) { if (typeof selectable === 'string') { - result.set(selectable as string, Field.of(selectable)); + result.set(selectable as string, field(selectable)); } else if (selectable instanceof Field) { result.set((selectable as Field).fieldName(), selectable); } else if (selectable instanceof ExprWithAlias) { - const expr = selectable as ExprWithAlias; - result.set(expr.alias, expr.expr); + const expr = selectable as ExprWithAlias; + result.set(expr.alias, expr.expr as unknown as Expr); } else { throw new Error('unexpected selectable: ' + selectable); } @@ -260,11 +298,11 @@ export class Pipeline /** * Filters the documents from previous stages to only include those matching the specified {@link - * FilterCondition}. + * BooleanExpr}. * - *

This stage allows you to apply conditions to the data, similar to a 'WHERE' clause in SQL. + *

This stage allows you to apply conditions to the data, similar to a "WHERE" clause in SQL. * You can filter documents based on their field values, using implementations of {@link - * FilterCondition}, typically including but not limited to: + * BooleanExpr}, typically including but not limited to: * *

    *
  • field comparators: {@link Function#eq}, {@link Function#lt} (less than), {@link @@ -277,19 +315,19 @@ export class Pipeline *

    Example: * * ```typescript - * firestore.pipeline().collection('books') + * firestore.pipeline().collection("books") * .where( * and( - * gt(Field.of('rating'), 4.0), // Filter for ratings greater than 4.0 - * Field.of('genre').eq('Science Fiction') // Equivalent to gt('genre', 'Science Fiction') + * gt(field("rating"), 4.0), // Filter for ratings greater than 4.0 + * field("genre").eq("Science Fiction") // Equivalent to gt("genre", "Science Fiction") * ) * ); * ``` * - * @param condition The {@link FilterCondition} to apply. + * @param condition The {@link BooleanExpr} to apply. * @return A new Pipeline object with this stage appended to the stage list. */ - where(condition: FilterCondition & firestore.Expr): Pipeline { + where(condition: firestore.BooleanExpr): Pipeline { return this._addStage(new Where(condition)); } @@ -305,7 +343,7 @@ export class Pipeline * ```typescript * // Retrieve the second page of 20 results * firestore.pipeline().collection('books') - * .sort(Field.of('published').descending()) + * .sort(field('published').descending()) * .offset(20) // Skip the first 20 results * .limit(20); // Take the next 20 results * ``` @@ -313,7 +351,7 @@ export class Pipeline * @param offset The number of documents to skip. * @return A new Pipeline object with this stage appended to the stage list. */ - offset(offset: number): Pipeline { + offset(offset: number): Pipeline { return this._addStage(new Offset(offset)); } @@ -335,76 +373,82 @@ export class Pipeline * ```typescript * // Limit the results to the top 10 highest-rated books * firestore.pipeline().collection('books') - * .sort(Field.of('rating').descending()) + * .sort(field('rating').descending()) * .limit(10); * ``` * * @param limit The maximum number of documents to return. * @return A new Pipeline object with this stage appended to the stage list. */ - limit(limit: number): Pipeline { + limit(limit: number): Pipeline { return this._addStage(new Limit(limit)); } /** - * Returns a set of distinct {@link Expr} values from the inputs to this stage. + * Returns a set of distinct values from the inputs to this stage. * - *

    This stage run through the results from previous stages to include only results with unique - * combinations of {@link Expr} values ({@link Field}, {@link Function}, etc). + * This stage runs through the results from previous stages to include only results with + * unique combinations of {@link Expr} values ({@link Field}, {@link Function}, etc). * - *

    The parameters to this stage are defined using {@link Selectable} expressions or {@code string}s: + * The parameters to this stage are defined using {@link Selectable} expressions or strings: * - *

      - *
    • {@code string}: Name of an existing field
    • - *
    • {@link Field}: References an existing document field.
    • - *
    • {@link Function}: Represents the result of a function with an assigned alias name using - * {@link Expr#as}
    • - *
    + * - {@code string}: Name of an existing field + * - {@link Field}: References an existing document field. + * - {@link ExprWithAlias}: Represents the result of a function with an assigned alias name + * using {@link Expr#as}. * - *

    Example: + * Example: * * ```typescript * // Get a list of unique author names in uppercase and genre combinations. - * firestore.pipeline().collection('books') - * .distinct(toUppercase(Field.of('author')).as('authorName'), Field.of('genre'), 'publishedAt') - * .select('authorName'); + * firestore.pipeline().collection("books") + * .distinct(toUppercase(field("author")).as("authorName"), field("genre"), "publishedAt") + * .select("authorName"); * ``` * - * @param groups The {@link Selectable} expressions to consider when determining distinct - * value combinations or {@code string}s representing field names. + * @param group The {@link Selectable} expression or field name to consider when determining + * distinct value combinations. + * @param additionalGroups Optional additional {@link Selectable} expressions to consider when determining distinct + * value combinations or strings representing field names. * @return A new {@code Pipeline} object with this stage appended to the stage list. */ distinct( - ...groups: (string | firestore.Selectable)[] - ): Pipeline { - return this._addStage(new Distinct(this.selectablesToMap(groups || []))); + group: string | firestore.Selectable, + ...additionalGroups: Array + ): Pipeline { + return this._addStage( + new Distinct(this.selectablesToMap([group, ...additionalGroups])) + ); } /** * Performs aggregation operations on the documents from previous stages. * *

    This stage allows you to calculate aggregate values over a set of documents. You define the - * aggregations to perform using {@link AccumulatorTarget} expressions which are typically results of - * calling {@link Expr#as} on {@link Accumulator} instances. + * aggregations to perform using {@link AggregateWithAlias} expressions which are typically results of + * calling {@link Expr#as} on {@link AggregateFunction} instances. * *

    Example: * * ```typescript * // Calculate the average rating and the total number of books - * firestore.pipeline().collection('books') + * firestore.pipeline().collection("books") * .aggregate( - * Field.of('rating').avg().as('averageRating'), - * countAll().as('totalBooks') + * field("rating").avg().as("averageRating"), + * countAll().as("totalBooks") * ); * ``` * - * @param accumulators The {@link AccumulatorTarget} expressions, each wrapping an {@link Accumulator} - * and provide a name for the accumulated results. + * @param accumulator The first {@link AggregateWithAlias}, wrapping an {@link AggregateFunction} + * and providing a name for the accumulated results. + * @param additionalAccumulators Optional additional {@link AggregateWithAlias}, each wrapping an {@link AggregateFunction} + * and providing a name for the accumulated results. * @return A new Pipeline object with this stage appended to the stage list. */ aggregate( - ...accumulators: firestore.AccumulatorTarget[] - ): Pipeline; + accumulator: firestore.AggregateWithAlias, + ...additionalAccumulators: firestore.AggregateWithAlias[] + ): Pipeline; /** * Performs optionally grouped aggregation operations on the documents from previous stages. * @@ -417,8 +461,8 @@ export class Pipeline * If no grouping fields are provided, a single group containing all documents is used. Not * specifying groups is the same as putting the entire inputs into one group.

  • *
  • **Accumulators:** One or more accumulation operations to perform within each group. These - * are defined using {@link AccumulatorTarget} expressions, which are typically created by - * calling {@link Expr#as} on {@link Accumulator} instances. Each aggregation + * are defined using {@link AggregateWithAlias} expressions, which are typically created by + * calling {@link Expr#as} on {@link AggregateFunction} instances. Each aggregation * calculates a value (e.g., sum, average, count) based on the documents within its group.
  • *
* @@ -426,38 +470,39 @@ export class Pipeline * * ```typescript * // Calculate the average rating for each genre. - * firestore.pipeline().collection('books') + * firestore.pipeline().collection("books") * .aggregate({ - * accumulators: [avg(Field.of('rating')).as('avg_rating')], - * groups: ['genre'] + * accumulators: [avg(field("rating")).as("avg_rating")] + * groups: ["genre"] * }); * ``` * - * @param aggregate An {@link Aggregate} object that specifies the grouping fields (if any) and - * the aggregation operations to perform. - * @return A new {@code Pipeline} object with this stage appended to the stage list. + * @param options An object that specifies the accumulators + * and optional grouping fields to perform. + * @return A new {@code Pipeline} object with this stage appended to the stage + * list. */ aggregate(options: { - accumulators: firestore.AccumulatorTarget[]; - groups?: (string | Selectable)[]; - }): Pipeline; + accumulators: firestore.AggregateWithAlias[]; + groups?: Array; + }): Pipeline; aggregate( optionsOrTarget: - | firestore.AccumulatorTarget + | firestore.AggregateWithAlias | { - accumulators: firestore.AccumulatorTarget[]; - groups?: (string | firestore.Selectable)[]; + accumulators: firestore.AggregateWithAlias[]; + groups?: Array; }, - ...rest: firestore.AccumulatorTarget[] - ): Pipeline { + ...rest: firestore.AggregateWithAlias[] + ): Pipeline { if ('accumulators' in optionsOrTarget) { return this._addStage( new Aggregate( - new Map( + new Map( optionsOrTarget.accumulators.map( - (target: firestore.AccumulatorTarget) => [ - (target as unknown as AccumulatorTarget).alias, - (target as unknown as AccumulatorTarget).expr, + (target: firestore.AggregateWithAlias) => [ + (target as unknown as AggregateWithAlias).alias, + (target as unknown as AggregateWithAlias).aggregate, ] ) ), @@ -467,10 +512,10 @@ export class Pipeline } else { return this._addStage( new Aggregate( - new Map( + new Map( [optionsOrTarget, ...rest].map(target => [ - (target as unknown as AccumulatorTarget).alias, - (target as unknown as AccumulatorTarget).expr, + (target as unknown as AggregateWithAlias).alias, + (target as unknown as AggregateWithAlias).aggregate, ]) ), new Map() @@ -479,7 +524,7 @@ export class Pipeline } } - findNearest(options: firestore.FindNearestOptions): Pipeline { + findNearest(options: firestore.FindNearestOptions): Pipeline { return this._addStage(new FindNearest(options)); } @@ -502,7 +547,7 @@ export class Pipeline * // } * * // Emit parents as document. - * firestore.pipeline().collection('people').replace(Field.of('parents')); + * firestore.pipeline().collection('people').replaceWith('parents'); * * // Output * // { @@ -511,11 +556,52 @@ export class Pipeline * // } * ``` * - * @param field The {@link Selectable} field containing the nested map. + * @param fieldName The {@link Field} field containing the nested map. * @return A new {@code Pipeline} object with this stage appended to the stage list. */ - replace(field: firestore.Selectable | string): Pipeline { - return this._addStage(new Replace(selectableToExpr(field), 'full_replace')); + replaceWith(fieldName: string): Pipeline; + + /** + * Fully overwrites all fields in a document with those coming from a map. + * + *

This stage allows you to emit a map value as a document. Each key of the map becomes a field + * on the document that contains the corresponding value. + * + *

Example: + * + * ```typescript + * // Input. + * // { + * // 'name': 'John Doe Jr.', + * // 'parents': { + * // 'father': 'John Doe Sr.', + * // 'mother': 'Jane Doe' + * // } + * // } + * + * // Emit parents as document. + * firestore.pipeline().collection('people').replaceWith(map({ + * foo: 'bar', + * info: { + * name: field('name') + * } + * })); + * + * // Output + * // { + * // 'father': 'John Doe Sr.', + * // 'mother': 'Jane Doe' + * // } + * ``` + * + * @param expr An {@link Expr} that when returned evaluates to a map. + * @return A new {@code Pipeline} object with this stage appended to the stage list. + */ + replaceWith(expr: firestore.Expr): Pipeline; + replaceWith(value: firestore.Expr | string): Pipeline { + return this._addStage( + new Replace(fieldOrExpression(value), 'full_replace') + ); } /** @@ -532,10 +618,10 @@ export class Pipeline * .sample(25); * ``` * - * @param documents The number of documents to sample.. + * @param documents The number of documents to sample. * @return A new {@code Pipeline} object with this stage appended to the stage list. */ - sample(documents: number): Pipeline; + sample(documents: number): Pipeline; /** * Performs a pseudo-random sampling of the documents from the previous stage. @@ -552,18 +638,14 @@ export class Pipeline * // Sample 50% of books. * firestore.pipeline().collection("books") * .sample({ percentage: 0.5 }); - * } - * * * @param options The {@code SampleOptions} specifies how sampling is performed. * @return A new {@code Pipeline} object with this stage appended to the stage list. */ - sample( - options: {percentage: number} | {documents: number} - ): Pipeline; + sample(options: {percentage: number} | {documents: number}): Pipeline; sample( documentsOrOptions: number | {percentage: number} | {documents: number} - ): Pipeline { + ): Pipeline { if (typeof documentsOrOptions === 'number') { return this._addStage( new Sample({limit: documentsOrOptions, mode: 'documents'}) @@ -597,24 +679,23 @@ export class Pipeline * @param other The other {@code Pipeline} that is part of union. * @return A new {@code Pipeline} object with this stage appended to the stage list. */ - union(other: Pipeline): Pipeline { + union(other: Pipeline): Pipeline { return this._addStage(new Union(other)); } /** - * Produces a document for each element in array found in previous stage document. + * Produces a document for each element in an input array. * - *

For each previous stage document, this stage will emit zero or more augmented documents. The - * input array found in the previous stage document field specified by the `fieldName` parameter, - * will emit an augmented document for each input array element. The input array element will + * For each previous stage document, this stage will emit zero or more augmented documents. The + * input array specified by the `selectable` parameter, will emit an augmented document for each input array element. The input array element will * augment the previous stage document by setting the `alias` field with the array element value. * - *

When `fieldName` evaluates to a non-array value (ex: number, null, absent), then the stage becomes a no-op for + * When `selectable` evaluates to a non-array value (ex: number, null, absent), then the stage becomes a no-op for * the current input document, returning it as is with the `alias` field absent. * - *

No documents are emitted when `fieldName` evaluates to an empty array. + * No documents are emitted when `selectable` evaluates to an empty array. * - *

Example: + * Example: * * ```typescript * // Input: @@ -622,71 +703,26 @@ export class Pipeline * * // Emit a book document for each tag of the book. * firestore.pipeline().collection("books") - * .unnest("tags"); + * .unnest(field("tags").as('tag'), 'tagIndex'); * * // Output: - * // { "title": "The Hitchhiker's Guide to the Galaxy", "tag": "comedy", ... } - * // { "title": "The Hitchhiker's Guide to the Galaxy", "tag": "space", ... } - * // { "title": "The Hitchhiker's Guide to the Galaxy", "tag": "adventure", ... } + * // { "title": "The Hitchhiker's Guide to the Galaxy", "tag": "comedy", "tagIndex": 0, ... } + * // { "title": "The Hitchhiker's Guide to the Galaxy", "tag": "space", "tagIndex": 1, ... } + * // { "title": "The Hitchhiker's Guide to the Galaxy", "tag": "adventure", "tagIndex": 2, ... } * ``` * - * @param field The name of the field containing the array. - * @param alias The alias field is used as the field name for each element within the output array. The alias does - * not overwrite the original field unless the field names match. + * @param selectable A selectable expression defining the field to unnest and the alias to use for each un-nested element in the output documents. + * @param indexField An optional string value specifying the field path to write the offset (starting at zero) into the array the un-nested element is from * @return A new {@code Pipeline} object with this stage appended to the stage list. */ - unnest( - field: firestore.Selectable | string, - alias: Field | string - ): Pipeline; - - /** - * Produces a document for each element in array found in previous stage document. - * - *

For each previous stage document, this stage will emit zero or more augmented documents. The - * input array found in the previous stage document field specified by the `fieldName` parameter, - * will emit an augmented document for each input array element. The input array element will - * augment the previous stage document by setting the `alias` field with the array element value. - * - *

When `fieldName` evaluates to a non-array value (ex: number, null, absent), then the stage becomes a no-op for - * the current input document, returning it as is with the `alias` field absent and `indexField` set to null. - * - *

No documents are emitted when `fieldName` evaluates to an empty array. - * - *

Example: - * - * ```typescript - * // Input: - * // { 'title': 'The Hitchhiker's Guide to the Galaxy', 'tags': [ 'comedy', 'space', 'adventure' ], ... } - * - * // Emit a book document for each tag of the book. - * firestore.pipeline().collection('books') - * .unnest({ field: 'tags', alias: 'tag', UnnestOptions.indexField('tagIndex')}); - * - * // Output: - * // { 'title': 'The Hitchhiker's Guide to the Galaxy', 'tagIndex': 0, 'tag': 'comedy', ... } - * // { 'title': 'The Hitchhiker's Guide to the Galaxy', 'tagIndex': 1, 'tag': 'space', ... } - * // { 'title': 'The Hitchhiker's Guide to the Galaxy', 'tagIndex': 2, 'tag': 'adventure', ... } - * ``` - * - * @param options The {@code UnnestOptions} options. - * @return A new {@code Pipeline} object with this stage appended to the stage list. - */ - unnest(options: UnnestOptions): Pipeline; - unnest( - fieldOrOptions: firestore.Selectable | string | UnnestOptions, - alias?: Field | string - ): Pipeline { - if (alias) { - return this._addStage( - new Unnest({ - field: fieldOrOptions, - alias: alias, - }) - ); - } else { - return this._addStage(new Unnest(fieldOrOptions)); - } + unnest(selectable: firestore.Selectable, indexField?: string): Pipeline { + return this._addStage( + new Unnest({ + expr: cast(selectable.expr), + alias: field(selectable.alias), + indexField: indexField, + }) + ); } /** @@ -703,33 +739,25 @@ export class Pipeline * ```typescript * // Sort books by rating in descending order, and then by title in ascending order for books * // with the same rating - * firestore.pipeline().collection('books') + * firestore.pipeline().collection("books") * .sort( - * Field.of('rating').descending(), - * Field.of('title').ascending() + * Ordering.of(field("rating")).descending(), + * Ordering.of(field("title")) // Ascending order is the default * ); * ``` * - * @param orders One or more {@link Ordering} instances specifying the sorting criteria. + * @param ordering The first {@link Ordering} instance specifying the sorting criteria. + * @param additionalOrderings Optional additional {@link Ordering} instances specifying the additional sorting criteria. * @return A new {@code Pipeline} object with this stage appended to the stage list. */ - sort(...orderings: Ordering[]): Pipeline; - sort(options: {orderings: Ordering[]}): Pipeline; sort( - optionsOrOrderings: - | Ordering - | { - orderings: Ordering[]; - }, - ...rest: Ordering[] - ): Pipeline { - // Option object - if ('orderings' in optionsOrOrderings) { - return this._addStage(new Sort(optionsOrOrderings.orderings)); - } else { - // Ordering object - return this._addStage(new Sort([optionsOrOrderings, ...rest])); - } + ordering: firestore.Ordering, + ...additionalOrderings: firestore.Ordering[] + ): Pipeline { + // Ordering object + return this._addStage( + new Sort([ordering, ...additionalOrderings] as unknown as Ordering[]) + ); } /** @@ -744,7 +772,7 @@ export class Pipeline * ```typescript * // Assume we don't have a built-in 'where' stage * firestore.pipeline().collection('books') - * .genericStage('where', [Field.of('published').lt(1900)]) // Custom 'where' stage + * .genericStage('where', [field('published').lt(1900)]) // Custom 'where' stage * .select('title', 'author'); * ``` * @@ -752,75 +780,10 @@ export class Pipeline * @param params A list of parameters to configure the generic stage's behavior. * @return A new {@code Pipeline} object with this stage appended to the stage list. */ - genericStage(name: string, params: any[]): Pipeline { + genericStage(name: string, params: any[]): Pipeline { return this._addStage(new GenericStage(name, params)); } - withConverter(converter: null): Pipeline; - withConverter( - converter: firestore.FirestorePipelineConverter - ): Pipeline; - /** - * Applies a custom data converter to this Query, allowing you to use your - * own custom model objects with Firestore. When you call get() on the - * returned Query, the provided converter will convert between Firestore - * data of type `NewDbModelType` and your custom type `NewAppModelType`. - * - * Using the converter allows you to specify generic type arguments when - * storing and retrieving objects from Firestore. - * - * Passing in `null` as the converter parameter removes the current - * converter. - * - * @example - * ``` - * class Post { - * constructor(readonly title: string, readonly author: string) {} - * - * toString(): string { - * return this.title + ', by ' + this.author; - * } - * } - * - * const postConverter = { - * toFirestore(post: Post): FirebaseFirestore.DocumentData { - * return {title: post.title, author: post.author}; - * }, - * fromFirestore( - * snapshot: FirebaseFirestore.QueryDocumentSnapshot - * ): Post { - * const data = snapshot.data(); - * return new Post(data.title, data.author); - * } - * }; - * - * const postSnap = await Firestore() - * .collection('posts') - * .withConverter(postConverter) - * .doc().get(); - * const post = postSnap.data(); - * if (post !== undefined) { - * post.title; // string - * post.toString(); // Should be defined - * post.someNonExistentProperty; // TS error - * } - * - * ``` - * @param {FirestoreDataConverter | null} converter Converts objects to and - * from Firestore. Passing in `null` removes the current converter. - * @return A Query that uses the provided converter. - */ - withConverter( - converter: firestore.FirestorePipelineConverter | null - ): Pipeline { - const copy = this.stages.map(s => s); - return new Pipeline( - this.db, - copy, - converter ?? defaultPipelineConverter() - ); - } - /** * Executes this pipeline and returns a Promise to represent the asynchronous operation. * @@ -845,26 +808,27 @@ export class Pipeline * * ```typescript * const futureResults = await firestore.pipeline().collection('books') - * .where(gt(Field.of('rating'), 4.5)) + * .where(gt(field('rating'), 4.5)) * .select('title', 'author', 'rating') * .execute(); * ``` * * @return A Promise representing the asynchronous pipeline execution. */ - execute(): Promise>> { - return this._execute().then(response => response.result || []); + execute(): Promise { + return this._execute().then(response => { + const results = response.result || []; + const executionTime = response.executionTime; + + return new PipelineSnapshot(this, results, executionTime); + }); } _execute( transactionOrReadTime?: Uint8Array | Timestamp | api.ITransactionOptions, - explainOptions?: FirebaseFirestore.ExplainOptions - ): Promise> { - const util = new ExecutionUtil( - this.db, - this.db._serializer!, - this.converter - ); + explainOptions?: firestore.ExplainOptions + ): Promise { + const util = new ExecutionUtil(this.db, this.db._serializer!); return util ._getResponse(this, transactionOrReadTime, explainOptions) .then(result => result!); @@ -879,7 +843,7 @@ export class Pipeline * @example * ```typescript * firestore.pipeline().collection('books') - * .where(gt(Field.of('rating'), 4.5)) + * .where(gt(field('rating'), 4.5)) * .select('title', 'author', 'rating') * .stream() * .on('data', (pipelineResult) => {}) @@ -887,11 +851,7 @@ export class Pipeline * ``` */ stream(): NodeJS.ReadableStream { - const util = new ExecutionUtil( - this.db, - this.db._serializer!, - this.converter - ); + const util = new ExecutionUtil(this.db, this.db._serializer!); return util.stream(this); } @@ -903,6 +863,53 @@ export class Pipeline } } +/** + * TODO(docs) + */ +export class PipelineSnapshot { + private readonly _pipeline: Pipeline; + private readonly _executionTime: Timestamp | undefined; + private readonly _results: PipelineResult[]; + constructor( + pipeline: Pipeline, + results: PipelineResult[], + executionTime?: Timestamp + ) { + this._pipeline = pipeline; + this._executionTime = executionTime; + this._results = results; + } + + /** + * The Pipeline on which you called `execute()` in order to get this + * `PipelineSnapshot`. + */ + get pipeline(): Pipeline { + return this._pipeline; + } + + /** An array of all the results in the `PipelineSnapshot`. */ + get results(): PipelineResult[] { + return this._results; + } + + /** + * The time at which the pipeline producing this result is executed. + * + * @type {Timestamp} + * @readonly + * + */ + get executionTime(): Timestamp { + if (this._executionTime === undefined) { + throw new Error( + "'executionTime' is expected to exist, but it is undefined" + ); + } + return this._executionTime; + } +} + /** * @beta * @@ -912,9 +919,7 @@ export class Pipeline *

If the PipelineResult represents a non-document result, `ref` will return a undefined * value. */ -export class PipelineResult - implements firestore.PipelineResult -{ +export class PipelineResult implements firestore.PipelineResult { private readonly _ref: DocumentReference | undefined; private _serializer: Serializer; public readonly _executionTime: Timestamp | undefined; @@ -944,8 +949,7 @@ export class PipelineResult readonly _fieldsProto?: ApiMapValue, readTime?: Timestamp, createTime?: Timestamp, - updateTime?: Timestamp, - readonly converter: firestore.FirestorePipelineConverter = defaultPipelineConverter() + updateTime?: Timestamp ) { this._ref = ref; this._serializer = serializer; @@ -1026,34 +1030,18 @@ export class PipelineResult * }); * ``` */ - data(): AppModelType | undefined { + data(): firestore.DocumentData | undefined { const fields = this._fieldsProto; if (fields === undefined) { return undefined; } - // We only want to use the converter and create a new QueryDocumentSnapshot - // if a converter has been provided. - if (!!this.converter && this.converter !== defaultPipelineConverter()) { - return this.converter.fromFirestore( - new PipelineResult( - this._serializer, - this.ref, - this._fieldsProto, - this._executionTime, - this.createTime, - this.updateTime, - defaultPipelineConverter() - ) - ); - } else { - const obj: firestore.DocumentData = {}; - for (const prop of Object.keys(fields)) { - obj[prop] = this._serializer.decodeValue(fields[prop]); - } - return obj as AppModelType; + const obj: firestore.DocumentData = {}; + for (const prop of Object.keys(fields)) { + obj[prop] = this._serializer.decodeValue(fields[prop]); } + return obj; } /** @@ -1128,10 +1116,10 @@ export class PipelineResult * @return {boolean} true if this `PipelineResult` is equal to the provided * value. */ - isEqual(other: PipelineResult): boolean { + isEqual(other: PipelineResult): boolean { return ( this === other || - (isOptionalEqual(this._ref, other._ref) && + (isOptionalEqual(this.ref, other.ref) && deepEqual(this._fieldsProto, other._fieldsProto)) ); } diff --git a/dev/src/reference/aggregate-query.ts b/dev/src/reference/aggregate-query.ts index 57e63d671..33478ac1d 100644 --- a/dev/src/reference/aggregate-query.ts +++ b/dev/src/reference/aggregate-query.ts @@ -22,14 +22,7 @@ import * as deepEqual from 'fast-deep-equal'; import * as firestore from '@google-cloud/firestore'; import {Aggregate, AggregateSpec} from '../aggregate'; -import { - AccumulatorTarget, - avg, - count, - countAll, - Field, - sum, -} from '../expression'; +import {avg, count, countAll, field, sum} from '../expression'; import {Pipeline} from '../pipeline'; import {Timestamp} from '../timestamp'; import {mapToArray, requestTag, wrapError} from '../util'; @@ -364,17 +357,26 @@ export class AggregateQuery< if (aggregate._field === undefined) { return countAll().as(clientAlias); } - return count(Field.of(aggregate._field)).as(clientAlias); + return count(field(aggregate._field)).as(clientAlias); } else if (aggregate.aggregateType === 'avg') { - return avg(Field.of(aggregate._field!)).as(clientAlias); + return avg(field(aggregate._field!)).as(clientAlias); } else if (aggregate.aggregateType === 'sum') { - return sum(Field.of(aggregate._field!)).as(clientAlias); + return sum(field(aggregate._field!)).as(clientAlias); } else { throw new Error(`Unknown aggregate type ${aggregate.aggregateType}`); } } ); - return this._query.pipeline().aggregate(...aggregates); + + if (aggregates.length === 0) { + throw new Error( + 'Cannot convert an AggregateQuery with 0 aggregates to a Pipeline' + ); + } + + return this._query + .pipeline() + .aggregate(aggregates[0], ...aggregates.slice(1)); } /** diff --git a/dev/src/reference/collection-reference.ts b/dev/src/reference/collection-reference.ts index 8b065d64b..fb4475dd7 100644 --- a/dev/src/reference/collection-reference.ts +++ b/dev/src/reference/collection-reference.ts @@ -307,13 +307,15 @@ export class CollectionReference< ); } - withConverter(converter: null): CollectionReference; withConverter< NewAppModelType, NewDbModelType extends firestore.DocumentData = firestore.DocumentData, >( converter: firestore.FirestoreDataConverter ): CollectionReference; + withConverter( + converter: null + ): CollectionReference; /** * Applies a custom data converter to this CollectionReference, allowing you * to use your own custom model objects with Firestore. When you call add() on diff --git a/dev/src/reference/document-reference.ts b/dev/src/reference/document-reference.ts index 52f6d8425..ecacde931 100644 --- a/dev/src/reference/document-reference.ts +++ b/dev/src/reference/document-reference.ts @@ -569,12 +569,14 @@ export class DocumentReference< return {referenceValue: this.formattedName}; } - withConverter(converter: null): DocumentReference; withConverter< NewAppModelType, NewDbModelType extends firestore.DocumentData = firestore.DocumentData, >( - converter: firestore.FirestoreDataConverter + converter: firestore.FirestoreDataConverter< + NewAppModelType, + NewDbModelType + > | null ): DocumentReference; /** * Applies a custom data converter to this DocumentReference, allowing you to diff --git a/dev/src/reference/query.ts b/dev/src/reference/query.ts index fec50d4dd..4bde4267e 100644 --- a/dev/src/reference/query.ts +++ b/dev/src/reference/query.ts @@ -19,7 +19,7 @@ import api = protos.google.firestore.v1; import * as firestore from '@google-cloud/firestore'; import {GoogleError} from 'google-gax'; import {Transform} from 'stream'; -import {and, Field, Ordering} from '../expression'; +import {and, field, Ordering} from '../expression'; import {CompositeFilter, UnaryFilter} from '../filter'; import { @@ -35,10 +35,9 @@ import { import {compare} from '../order'; import {validateFieldPath} from '../path'; import {Pipeline} from '../pipeline'; -import {toPipelineFilterCondition} from '../pipeline-util'; +import {toPipelineBooleanExpr} from '../pipeline-util'; import {ExplainResults} from '../query-profile'; import {Serializer} from '../serializer'; -import {Limit} from '../stage'; import {defaultConverter} from '../types'; import { invalidArgumentMessage, @@ -742,24 +741,26 @@ export class Query< // filters for (const f of this._queryOptions.filters) { - pipeline = pipeline.where(toPipelineFilterCondition(f, this._serializer)); + pipeline = pipeline.where(toPipelineBooleanExpr(f, this._serializer)); } // projections const projections = this._queryOptions.projection?.fields || []; if (projections.length > 0) { + const projectionFields = projections.map(p => field(p.fieldPath!)); pipeline = pipeline.select( - ...projections.map(p => Field.of(p.fieldPath!)) + projectionFields[0], + ...projectionFields.slice(1) ); } // orderbys const exists = this.createImplicitOrderBy().map(fieldOrder => { - return Field.of(fieldOrder.field).exists(); + return field(fieldOrder.field).exists(); }); if (exists.length > 1) { - const [first, ...rest] = exists; - pipeline = pipeline.where(and(first, ...rest)); + const [first, second, ...rest] = exists; + pipeline = pipeline.where(and(first, second, ...rest)); } else if (exists.length === 1) { pipeline = pipeline.where(exists[0]); } @@ -776,10 +777,10 @@ export class Query< break; } } - return new Ordering(Field.of(fieldOrder.field), dir || 'ascending'); + return new Ordering(field(fieldOrder.field), dir || 'ascending'); }); if (orderings.length > 0) { - pipeline = pipeline.sort({orderings: orderings}); + pipeline = pipeline.sort(orderings[0], ...orderings.slice(1)); } // Cursors, Limit and Offset @@ -1670,12 +1671,14 @@ export class Query< }; } - withConverter(converter: null): Query; withConverter< NewAppModelType, NewDbModelType extends firestore.DocumentData = firestore.DocumentData, >( - converter: firestore.FirestoreDataConverter + converter: firestore.FirestoreDataConverter< + NewAppModelType, + NewDbModelType + > | null ): Query; /** * Applies a custom data converter to this Query, allowing you to use your diff --git a/dev/src/reference/types.ts b/dev/src/reference/types.ts index d282b507f..081616b74 100644 --- a/dev/src/reference/types.ts +++ b/dev/src/reference/types.ts @@ -60,21 +60,18 @@ export enum LimitType { Last, } -export interface PipelineStreamElement< - AppModelType = firestore.DocumentData, - DbModelType extends firestore.DocumentData = firestore.DocumentData, -> { +export interface PipelineStreamElement { transaction?: Uint8Array; executionTime?: Timestamp; explainMetrics?: ExplainMetrics; - result?: PipelineResult; + result?: PipelineResult; } -export interface PipelineResponse { +export interface PipelineResponse { transaction?: Uint8Array; executionTime?: Timestamp; explainMetrics?: ExplainMetrics; - result?: Array>; + result?: Array; } /** diff --git a/dev/src/reference/vector-query.ts b/dev/src/reference/vector-query.ts index 62553a875..987a5a1b5 100644 --- a/dev/src/reference/vector-query.ts +++ b/dev/src/reference/vector-query.ts @@ -17,7 +17,7 @@ import * as protos from '../../protos/firestore_v1_proto_api'; import api = protos.google.firestore.v1; import * as firestore from '@google-cloud/firestore'; -import {Field} from '../expression'; +import {field} from '../expression'; import {Pipeline} from '../pipeline'; import {FindNearestOptions} from '../stage'; @@ -143,7 +143,7 @@ export class VectorQuery< toPipeline(): Pipeline { const options: FindNearestOptions = { - field: Field.of(this._options.vectorField), + field: field(this._options.vectorField), vectorValue: this._options.queryVector, limit: this._options.limit, distanceMeasure: this._options.distanceMeasure.toLowerCase() as @@ -153,7 +153,7 @@ export class VectorQuery< }; return this.query .pipeline() - .where(Field.of(this._options.vectorField).exists()) + .where(field(this._options.vectorField).exists()) .findNearest(options); } diff --git a/dev/src/serializer.ts b/dev/src/serializer.ts index 0c3e69607..58588512b 100644 --- a/dev/src/serializer.ts +++ b/dev/src/serializer.ts @@ -119,7 +119,7 @@ export class Serializer { | Uint8Array | VectorValue | Map - | Pipeline + | Pipeline ): api.IValue; encodeValue(val: unknown): api.IValue | null; encodeValue(val: unknown): api.IValue | null { diff --git a/dev/src/stage.ts b/dev/src/stage.ts index 056517804..f1a05e57d 100644 --- a/dev/src/stage.ts +++ b/dev/src/stage.ts @@ -16,19 +16,11 @@ import * as firestore from '@google-cloud/firestore'; import * as protos from '../protos/firestore_v1_proto_api'; import api = protos.google.firestore.v1; -import { - Accumulator, - Expr, - Field, - FilterCondition, - Ordering, - Selectable, -} from './expression'; +import {AggregateFunction, Expr, Field, Ordering, field} from './expression'; import {VectorValue} from './field-value'; import {DocumentReference} from './reference/document-reference'; import {Serializer} from './serializer'; import {Pipeline} from './pipeline'; -import {selectableToExpr} from './pipeline-util'; /** * @beta @@ -77,7 +69,7 @@ export class Aggregate implements Stage { name = 'aggregate'; constructor( - private accumulators: Map, + private accumulators: Map, private groups: Map ) {} @@ -185,7 +177,7 @@ export class DocumentsSource implements Stage { export class Where implements Stage { name = 'where'; - constructor(private condition: firestore.FilterCondition & firestore.Expr) {} + constructor(private condition: firestore.BooleanExpr & firestore.Expr) {} _toProto(serializer: Serializer): api.Pipeline.IStage { return { @@ -219,7 +211,7 @@ export class FindNearest implements Stage { limit: serializer.encodeValue(this._options.limit)!, }; if (this._options.distanceField) { - options.distance_field = Field.of(this._options.distanceField)._toProto( + options.distance_field = field(this._options.distanceField)._toProto( serializer ); } @@ -228,7 +220,7 @@ export class FindNearest implements Stage { name: this.name, args: [ (typeof this._options.field === 'string' - ? Field.of(this._options.field) + ? field(this._options.field) : (this._options.field as unknown as Field) )._toProto(serializer), this._options.vectorValue instanceof VectorValue @@ -274,7 +266,7 @@ export class Sample implements Stage { export class Union implements Stage { name = 'union'; - constructor(private _other: Pipeline) {} + constructor(private _other: Pipeline) {} _toProto(serializer: Serializer): api.Pipeline.IStage { return { @@ -288,8 +280,8 @@ export class Union implements Stage { * @beta */ export interface UnnestOptions { - field: firestore.Selectable | string; - alias: firestore.Field | string; + expr: Expr; + alias: Field; indexField?: string; } @@ -303,8 +295,8 @@ export class Unnest implements Stage { _toProto(serializer: Serializer): api.Pipeline.IStage { const args: api.IValue[] = [ - selectableToExpr(this.options.field)._toProto(serializer), - selectableToExpr(this.options.alias)._toProto(serializer), + this.options.expr._toProto(serializer), + this.options.alias._toProto(serializer), ]; const indexField = this.options?.indexField; if (indexField) { diff --git a/dev/src/transaction.ts b/dev/src/transaction.ts index f2b105246..abcdc1060 100644 --- a/dev/src/transaction.ts +++ b/dev/src/transaction.ts @@ -22,7 +22,7 @@ import * as proto from '../protos/firestore_v1_proto_api'; import {ExponentialBackoff} from './backoff'; import {DocumentSnapshot} from './document'; import {DEFAULT_MAX_TRANSACTION_ATTEMPTS, Firestore, WriteBatch} from './index'; -import {Pipeline, PipelineResult} from './pipeline'; +import {Pipeline, PipelineResult, PipelineSnapshot} from './pipeline'; import {Timestamp} from './timestamp'; import {logger} from './logger'; import {FieldPath, validateFieldPath} from './path'; @@ -315,21 +315,30 @@ export class Transaction implements firestore.Transaction { * const futureResults = await transaction * .execute( * firestore.pipeline().collection("books") - * .where(gt(Field.of("rating"), 4.5)) + * .where(gt(field("rating"), 4.5)) * .select("title", "author", "rating")); * ``` * * @return A Promise representing the asynchronous pipeline execution. */ - execute( - pipeline: firestore.Pipeline - ): Promise>> { + execute(pipeline: firestore.Pipeline): Promise { if (this._writeBatch && !this._writeBatch.isEmpty) { throw new Error(READ_AFTER_WRITE_ERROR_MSG); } if (pipeline instanceof Pipeline) { - return this.withLazyStartedTransaction(pipeline, this.executePipelineFn); + return this.withLazyStartedTransaction( + pipeline, + this.executePipelineFn + ).then(results => { + const executionTime = results.reduce((maxTime, result) => { + return result.executionTime.valueOf() > maxTime.valueOf() + ? result.executionTime + : maxTime; + }, Timestamp.fromMillis(0)); + + return new PipelineSnapshot(pipeline, results, executionTime); + }); } throw new Error('Value for argument "pipeline" must be a Pipeline'); @@ -847,15 +856,14 @@ export class Transaction implements firestore.Transaction { return query._get(opts); } - private async executePipelineFn( - pipeline: Pipeline, + private async executePipelineFn( + pipeline: Pipeline, opts: Uint8Array | api.ITransactionOptions | Timestamp ): Promise<{ transaction?: Uint8Array; - result: Array>; + result: Array; }> { - const {transaction, result, explainMetrics, executionTime} = - await pipeline._execute(opts); + const {transaction, result} = await pipeline._execute(opts); return {transaction, result: result || []}; } } diff --git a/dev/src/types.ts b/dev/src/types.ts index e52756272..45d926818 100644 --- a/dev/src/types.ts +++ b/dev/src/types.ts @@ -19,7 +19,6 @@ import { QueryDocumentSnapshot, DocumentData, WithFieldValue, - FirestorePipelineConverter, } from '@google-cloud/firestore'; import {CallOptions} from 'google-gax'; @@ -27,7 +26,6 @@ import {Duplex} from 'stream'; import {google} from '../protos/firestore_v1_proto_api'; import {FieldPath} from './path'; -import {PipelineResult} from './pipeline'; import api = google.firestore.v1; @@ -153,23 +151,6 @@ export function defaultConverter< >; } -const defaultPipelineConverterObj: FirestorePipelineConverter = { - fromFirestore(snapshot: PipelineResult): DocumentData { - return snapshot.data()!; - }, -}; - -/** - * A default converter to use when none is provided. - * @private - * @internal - */ -export function defaultPipelineConverter< - AppModelType, ->(): FirestorePipelineConverter { - return defaultPipelineConverterObj as FirestorePipelineConverter; -} - /** * Update data that has been resolved to a mapping of FieldPaths to values. */ diff --git a/dev/src/util.ts b/dev/src/util.ts index c5a0de214..63430e64a 100644 --- a/dev/src/util.ts +++ b/dev/src/util.ts @@ -365,3 +365,16 @@ export function isPrimitiveArrayEqual( return true; } + +export function cast( + val: unknown, + constructor?: {new (...args: any[]): T} +): T { + if (!constructor) { + return val as T; + } else if (val instanceof constructor) { + return val; + } + + throw new Error(`${val} not instance of ${constructor}`); +} diff --git a/dev/system-test/firestore.ts b/dev/system-test/firestore.ts index 7396bf291..622c43aae 100644 --- a/dev/system-test/firestore.ts +++ b/dev/system-test/firestore.ts @@ -101,7 +101,7 @@ if (process.env.NODE_ENV === 'DEBUG') { setLogFunction(console.log); } -export function getTestRoot(settings: Settings = {}): CollectionReference { +export function getTestDb(settings: Settings = {}): Firestore { const internalSettings: Settings = {}; if (process.env.FIRESTORE_NAMED_DATABASE) { internalSettings.databaseId = process.env.FIRESTORE_NAMED_DATABASE; @@ -126,11 +126,14 @@ export function getTestRoot(settings: Settings = {}): CollectionReference { } } - const firestore = new Firestore({ + return new Firestore({ ...internalSettings, ...settings, // caller settings take precedent over internal settings }); - return firestore.collection(`node_${version}_${autoId()}`); +} + +export function getTestRoot(settings: Settings = {}): CollectionReference { + return getTestDb(settings).collection(`node_${version}_${autoId()}`); } describe('Firestore class', () => { diff --git a/dev/system-test/pipeline.ts b/dev/system-test/pipeline.ts index 852b7d3e6..31868e6fb 100644 --- a/dev/system-test/pipeline.ts +++ b/dev/system-test/pipeline.ts @@ -12,25 +12,73 @@ // See the License for the specific language governing permissions and // limitations under the License. -import { - DocumentData, - FirestorePipelineConverter, - QuerySnapshot, -} from '@google-cloud/firestore'; +import { DocumentData } from '@google-cloud/firestore'; -import {expect} from 'chai'; -import {afterEach, describe, it} from 'mocha'; -import { - CollectionReference, - DocumentReference, - FieldPath, - Firestore, - logicalMinimum, - logicalMaximum, - Query, - cond, -} from '../src'; import { + BooleanExpr, + constant, + constantVector, + map, + GeoPoint, + FieldValue, + array, + Timestamp, + bitNot, + field, + xor, + AggregateFunction, + rand, + arrayOffset, + timestampToUnixMicros, + timestampToUnixSeconds, + unixMicrosToTimestamp, + timestampToUnixMillis, + timestampSub, + timestampAdd, + byteLength, + bitAnd, + multiply, + PipelineSnapshot, + sum, + maximum, + descending, + FunctionExpr, + minimum, + count, + countIf, + arrayLength, + strContains, + charLength, + divide, + mod, + reverse, + trim, + toUpper, + toLower, + vectorLength, + isNotNan, + exists, + isNotNull, + isAbsent, + ifError, + isError, + isNan, + arrayConcat, + substr, + documentId, + isNull, + arrayContainsAll, + FindNearestOptions, + replaceFirst, + replaceAll, + mapRemove, + mapMerge, + unixSecondsToTimestamp, + unixMillisToTimestamp, + bitOr, + bitXor, + bitLeftShift, + bitRightShift, add, and, arrayContains, @@ -39,11 +87,11 @@ import { countAll, endsWith, eq, - Field, gt, like, lt, neq, + ascending, not, or, regexContains, @@ -54,32 +102,34 @@ import { cosineDistance, dotProduct, euclideanDistance, - Constant, mapGet, lte, eqAny, + PipelineResult, notEqAny, -} from '../src/expression'; -import {PipelineResult} from '../src/pipeline'; -import {verifyInstance} from '../test/util/helpers'; -import {getTestRoot} from './firestore'; + logicalMinimum, + logicalMaximum, + cond, + CollectionReference, + FieldPath, + Firestore, +} from '../src'; + +import {expect} from 'chai'; +import {afterEach, describe, it} from 'mocha'; +import {itIf, verifyInstance} from '../test/util/helpers'; +import {getTestDb, getTestRoot} from './firestore'; -describe('Pipeline class', () => { +import {Firestore as InternalFirestore} from '../src'; + +const testUnsupportedFeatures: boolean | 'only' = false; +const timestampDeltaMS = 1000; + +describe.only('Pipeline class', () => { let firestore: Firestore; let randomCol: CollectionReference; - - async function addDocs( - ...docs: DocumentData[] - ): Promise { - let id = 0; // Guarantees consistent ordering for the first documents - const refs: DocumentReference[] = []; - for (const doc of docs) { - const ref = randomCol.doc('doc' + id++); - await ref.set(doc); - refs.push(ref); - } - return refs; - } + const beginDocCreation = 0; + const endDocCreation = 0; async function testCollectionWithDocs(docs: { [id: string]: DocumentData; @@ -91,44 +141,29 @@ describe('Pipeline class', () => { return randomCol; } - function expectResults( - result: PipelineResult[], - ...docs: string[] - ): void; - function expectResults( - result: PipelineResult[], + function expectResults(result: PipelineSnapshot, ...docs: string[]): void; + function expectResults( + result: PipelineSnapshot, ...data: DocumentData[] ): void; - - function expectResults( - result: PipelineResult[], + function expectResults( + result: PipelineSnapshot, ...data: DocumentData[] | string[] ): void { if (data.length > 0) { if (typeof data[0] === 'string') { - const actualIds = result.map(result => result.ref?.id); + const actualIds = result.results.map(result => result.id); expect(actualIds).to.deep.equal(data); } else { - result.forEach(r => { + result.results.forEach(r => { expect(r.data()).to.deep.equal(data.shift()); }); } } else { - expect(result.length).to.equal(data.length); + expect(result.results.length).to.equal(data.length); } } - async function compareQueryAndPipeline(query: Query): Promise { - const queryResults = await query.get(); - const pipeline = query.pipeline(); - const pipelineResults = await pipeline.execute(); - - expect(queryResults.docs.map(s => s._fieldsProto)).to.deep.equal( - pipelineResults.map(r => r._fieldsProto) - ); - return queryResults; - } - async function setupBookDocs(): Promise> { const bookDocs: {[id: string]: DocumentData} = { book01: { @@ -232,856 +267,2570 @@ describe('Pipeline class', () => { firestore = randomCol.firestore; }); - afterEach(() => verifyInstance(firestore)); + afterEach(() => verifyInstance(firestore as unknown as InternalFirestore)); - it('empty results as expected', async () => { - const result = await firestore - .pipeline() - .collection(randomCol.path) - .limit(0) - .execute(); - expect(result).to.be.empty; - }); + describe('pipeline results', () => { + it('empty snapshot as expected', async () => { + const snapshot = await firestore + .pipeline() + .collection(randomCol.path) + .limit(0) + .execute(); + expect(snapshot.results.length).to.equal(0); + }); - it('returns aggregate results as expected', async () => { - let result = await firestore - .pipeline() - .collection(randomCol.path) - .aggregate(countAll().as('count')) - .execute(); - expectResults(result, {count: 10}); - - result = await randomCol - .pipeline() - .where(eq('genre', 'Science Fiction')) - .aggregate( - countAll().as('count'), - avg('rating').as('avg_rating'), - Field.of('rating').maximum().as('max_rating') - ) - .execute(); - expectResults(result, {count: 2, avg_rating: 4.4, max_rating: 4.6}); - }); + it('full snapshot as expected', async () => { + const ppl = firestore + .pipeline() + .collection(randomCol.path) + .sort(ascending('__name__')); + const snapshot = await ppl.execute(); + expect(snapshot.results.length).to.equal(10); + expect(snapshot.pipeline).to.equal(ppl); + expectResults( + snapshot, + 'book1', + 'book10', + 'book2', + 'book3', + 'book4', + 'book5', + 'book6', + 'book7', + 'book8', + 'book9' + ); + }); + + it('result equals works', async () => { + const ppl = firestore + .pipeline() + .collection(randomCol.path) + .sort(ascending('title')) + .limit(1); + const snapshot1 = await ppl.execute(); + const snapshot2 = await ppl.execute(); + expect(snapshot1.results.length).to.equal(1); + expect(snapshot2.results.length).to.equal(1); + expect(snapshot1.results[0].isEqual(snapshot2.results[0])).to.be.true; + }); + + it('returns execution time', async () => { + const start = new Date().valueOf(); + const pipeline = firestore.pipeline().collection(randomCol.path); + + const snapshot = await pipeline.execute(); + const end = new Date().valueOf(); + + expect(snapshot.executionTime.toDate().valueOf()).to.approximately( + (start + end) / 2, + timestampDeltaMS + ); + }); + + it('returns execution time for an empty query', async () => { + const start = new Date().valueOf(); + const pipeline = firestore.pipeline().collection(randomCol.path).limit(0); + + const snapshot = await pipeline.execute(); + const end = new Date().valueOf(); + + expect(snapshot.results.length).to.equal(0); + + expect(snapshot.executionTime.toDate().valueOf()).to.approximately( + (start + end) / 2, + timestampDeltaMS + ); + }); + + it('returns create and update time for each document', async () => { + const pipeline = firestore.pipeline().collection(randomCol.path); + + let snapshot = await pipeline.execute(); + expect(snapshot.results.length).to.equal(10); + snapshot.results.forEach(doc => { + expect(doc.createTime).to.not.be.null; + expect(doc.updateTime).to.not.be.null; + + expect(doc.createTime!.toDate().valueOf()).to.approximately( + (beginDocCreation + endDocCreation) / 2, + timestampDeltaMS + ); + expect(doc.updateTime!.toDate().valueOf()).to.approximately( + (beginDocCreation + endDocCreation) / 2, + timestampDeltaMS + ); + expect(doc.createTime?.valueOf()).to.equal(doc.updateTime?.valueOf()); + }); + + const wb = firestore.batch(); + snapshot.results.forEach(doc => { + wb.update(doc.ref!, {newField: 'value'}); + }); + await wb.commit(); + + snapshot = await pipeline.execute(); + expect(snapshot.results.length).to.equal(10); + snapshot.results.forEach(doc => { + expect(doc.createTime).to.not.be.null; + expect(doc.updateTime).to.not.be.null; + expect(doc.createTime!.toDate().valueOf()).to.be.lessThan( + doc.updateTime!.toDate().valueOf() + ); + }); + }); - it('rejects groups without accumulators', async () => { - await expect( - randomCol + it('returns execution time for an aggregate query', async () => { + const start = new Date().valueOf(); + const pipeline = firestore .pipeline() - .where(lt('published', 1900)) + .collection(randomCol.path) + .aggregate(avg('rating').as('avgRating')); + + const snapshot = await pipeline.execute(); + const end = new Date().valueOf(); + + expect(snapshot.results.length).to.equal(1); + + expect(snapshot.executionTime.toDate().valueOf()).to.approximately( + (start + end) / 2, + timestampDeltaMS + ); + }); + + it('returns undefined create and update time for each result in an aggregate query', async () => { + const pipeline = firestore + .pipeline() + .collection(randomCol.path) .aggregate({ - accumulators: [], + accumulators: [avg('rating').as('avgRating')], groups: ['genre'], - }) - .execute() - ).to.be.rejected; - }); + }); - // toLower not impelemented - it.skip('returns distinct values as expected', async () => { - const results = await randomCol - .pipeline() - .where(lt('published', 1900)) - .distinct(Field.of('genre').toLower().as('lower_genre')) - .execute(); - expectResults( - results, - {lower_genre: 'romance'}, - {lower_genre: 'psychological thriller'} - ); - }); + const snapshot = await pipeline.execute(); - it('returns group and accumulate results', async () => { - const results = await randomCol - .pipeline() - .where(lt(Field.of('published'), 1984)) - .aggregate({ - accumulators: [avg('rating').as('avgRating')], - groups: ['genre'], - }) - .where(gt('avgRating', 4.3)) - .sort(Field.of('avgRating').descending()) - .execute(); - expectResults( - results, - {avgRating: 4.7, genre: 'Fantasy'}, - {avgRating: 4.5, genre: 'Romance'}, - {avgRating: 4.4, genre: 'Science Fiction'} - ); - }); + expect(snapshot.results.length).to.equal(8); - it('returns minimum and maximum accumulations', async () => { - const results = await randomCol - .pipeline() - .aggregate( - countAll().as('count'), - Field.of('rating').maximum().as('max_rating'), - Field.of('published').minimum().as('min_published') - ) - .execute(); - expectResults(results, { - count: 10, - max_rating: 4.7, - min_published: 1813, + snapshot.results.forEach(doc => { + expect(doc.updateTime).to.be.undefined; + expect(doc.createTime).to.be.undefined; + }); }); }); - it('can add and remove fields', async () => { - const results = await firestore - .pipeline() - .collection(randomCol.path) - .addFields( - strConcat(Field.of('author'), '_', Field.of('title')).as( - 'author_title' - ), - strConcat(Field.of('title'), '_', Field.of('author')).as('title_author') - ) - .removeFields( - 'title_author', - 'tags', - 'awards', - 'rating', - 'title', - 'published', - 'genre', - 'nestedField' - ) - .sort(Field.of('author_title').ascending()) - .execute(); - expectResults( - results, - { - author_title: "Douglas Adams_The Hitchhiker's Guide to the Galaxy", - author: 'Douglas Adams', - }, - { - author_title: 'F. Scott Fitzgerald_The Great Gatsby', - author: 'F. Scott Fitzgerald', - }, - {author_title: 'Frank Herbert_Dune', author: 'Frank Herbert'}, - { - author_title: 'Fyodor Dostoevsky_Crime and Punishment', - author: 'Fyodor Dostoevsky', - }, - { - author_title: 'Gabriel García Márquez_One Hundred Years of Solitude', - author: 'Gabriel García Márquez', - }, - {author_title: 'George Orwell_1984', author: 'George Orwell'}, - {author_title: 'Harper Lee_To Kill a Mockingbird', author: 'Harper Lee'}, - { - author_title: 'J.R.R. Tolkien_The Lord of the Rings', - author: 'J.R.R. Tolkien', - }, - {author_title: 'Jane Austen_Pride and Prejudice', author: 'Jane Austen'}, - { - author_title: "Margaret Atwood_The Handmaid's Tale", - author: 'Margaret Atwood', - } - ); - }); + describe('pipeline sources', () => { + it('supports CollectionReference as source', async () => { + const snapshot = await firestore + .pipeline() + .collection(randomCol) + .execute(); + expect(snapshot.results.length).to.equal(10); + }); - it('can select fields', async () => { - const results = await firestore - .pipeline() - .collection(randomCol.path) - .select('title', 'author') - .sort(Field.of('author').ascending()) - .execute(); - expectResults( - results, - {title: "The Hitchhiker's Guide to the Galaxy", author: 'Douglas Adams'}, - {title: 'The Great Gatsby', author: 'F. Scott Fitzgerald'}, - {title: 'Dune', author: 'Frank Herbert'}, - {title: 'Crime and Punishment', author: 'Fyodor Dostoevsky'}, - { - title: 'One Hundred Years of Solitude', - author: 'Gabriel García Márquez', - }, - {title: '1984', author: 'George Orwell'}, - {title: 'To Kill a Mockingbird', author: 'Harper Lee'}, - {title: 'The Lord of the Rings', author: 'J.R.R. Tolkien'}, - {title: 'Pride and Prejudice', author: 'Jane Austen'}, - {title: "The Handmaid's Tale", author: 'Margaret Atwood'} - ); - }); + it('supports list of documents as source', async () => { + const collName = randomCol.id; - it('where with and', async () => { - const results = await randomCol - .pipeline() - .where(and(gt('rating', 4.5), eq('genre', 'Science Fiction'))) - .execute(); - expectResults(results, 'book10'); - }); + const snapshot = await firestore + .pipeline() + .documents([ + `${collName}/book1`, + randomCol.doc('book2'), + randomCol.doc('book3').path, + ]) + .execute(); + expect(snapshot.results.length).to.equal(3); + }); - it('where with or', async () => { - const results = await randomCol - .pipeline() - .where(or(eq('genre', 'Romance'), eq('genre', 'Dystopian'))) - .select('title') - .execute(); - expectResults( - results, - {title: 'Pride and Prejudice'}, - {title: "The Handmaid's Tale"}, - {title: '1984'} - ); - }); + it('reject CollectionReference for another DB', async () => { + const db2 = getTestDb({databaseId: 'notDefault'}); - it('offset and limits', async () => { - const results = await firestore - .pipeline() - .collection(randomCol.path) - .sort(Field.of('author').ascending()) - .offset(5) - .limit(3) - .select('title', 'author') - .execute(); - expectResults( - results, - {title: '1984', author: 'George Orwell'}, - {title: 'To Kill a Mockingbird', author: 'Harper Lee'}, - {title: 'The Lord of the Rings', author: 'J.R.R. Tolkien'} - ); - }); + expect(() => { + firestore.pipeline().collection(db2.collection('foo')); + }).to.throw(/Invalid CollectionReference/); - it('logical min works', async () => { - const results = await randomCol - .pipeline() - .select( - 'title', - logicalMinimum(Constant.of(1960), Field.of('published')).as( - 'published-safe' - ) - ) - .sort(Field.of('title').ascending()) - .limit(3) - .execute(); - expectResults( - results, - {title: '1984', 'published-safe': 1949}, - {title: 'Crime and Punishment', 'published-safe': 1866}, - {title: 'Dune', 'published-safe': 1960} - ); - }); + await db2.terminate(); + }); - it('logical max works', async () => { - const results = await randomCol - .pipeline() - .select( - 'title', - logicalMaximum(Constant.of(1960), Field.of('published')).as( - 'published-safe' - ) - ) - .sort(Field.of('title').ascending()) - .limit(3) - .execute(); - expectResults( - results, - {title: '1984', 'published-safe': 1960}, - {title: 'Crime and Punishment', 'published-safe': 1960}, - {title: 'Dune', 'published-safe': 1965} - ); - }); + it('reject DocumentReference for another DB', async () => { + const db2 = getTestDb({databaseId: 'notDefault'}); - it('cond works', async () => { - const results = await randomCol - .pipeline() - .select( - 'title', - cond( - lt(Field.of('published'), 1960), - Constant.of(1960), - Field.of('published') - ).as('published-safe') - ) - .sort(Field.of('title').ascending()) - .limit(3) - .execute(); - expectResults( - results, - {title: '1984', 'published-safe': 1960}, - {title: 'Crime and Punishment', 'published-safe': 1960}, - {title: 'Dune', 'published-safe': 1965} - ); - }); + expect(() => { + firestore.pipeline().documents([db2.doc('foo/bar')]); + }).to.throw(/Invalid DocumentReference/); + + await db2.terminate(); + }); - it('eqAny works', async () => { - const results = await randomCol - .pipeline() - .where(eqAny('published', [1979, 1999, 1967])) - .select('title') - .execute(); - expectResults( - results, - {title: "The Hitchhiker's Guide to the Galaxy"}, - {title: 'One Hundred Years of Solitude'} + // Subcollections not currently supported in DBE + itIf(testUnsupportedFeatures)( + 'supports collection group as source', + async () => { + const randomSubCollectionId = Math.random().toString(16).slice(2); + const doc1 = await randomCol + .doc('book1') + .collection(randomSubCollectionId) + .add({order: 1}); + const doc2 = await randomCol + .doc('book2') + .collection(randomSubCollectionId) + .add({order: 2}); + const snapshot = await firestore + .pipeline() + .collectionGroup(randomSubCollectionId) + .sort(ascending('order')) + .execute(); + expectResults(snapshot, doc1.id, doc2.id); + } ); + + // subcollections not currently supported in dbe + itIf(testUnsupportedFeatures)('supports database as source', async () => { + const randomId = Math.random().toString(16).slice(2); + const doc1 = await randomCol.doc('book1').collection('sub').add({ + order: 1, + randomId, + }); + const doc2 = await randomCol.doc('book2').collection('sub').add({ + order: 2, + randomId, + }); + const snapshot = await firestore + .pipeline() + .database() + .where(eq('randomId', randomId)) + .sort(ascending('order')) + .execute(); + expectResults(snapshot, doc1.id, doc2.id); + }); }); - it('notEqAny works', async () => { - const results = await randomCol - .pipeline() - .where( - notEqAny( + describe('supported data types', () => { + it('accepts and returns all data types', async () => { + const refDate = new Date(); + const refTimestamp = Timestamp.now(); + const constants = [ + constant(1).as('number'), + constant('a string').as('string'), + constant(true).as('boolean'), + constant(null).as('null'), + constant(new GeoPoint(0.1, 0.2)).as('geoPoint'), + constant(refTimestamp).as('timestamp'), + constant(refDate).as('date'), + constant(new Uint8Array([1, 2, 3, 4, 5, 6, 7, 0])).as('bytes'), + constant(firestore.doc('foo/bar')).as('documentReference'), + constantVector(FieldValue.vector([1, 2, 3])).as('vectorValue'), + constantVector([1, 2, 3]).as('vectorValue2'), + map({ + number: 1, + string: 'a string', + boolean: true, + null: null, + geoPoint: new GeoPoint(0.1, 0.2), + timestamp: refTimestamp, + date: refDate, + uint8Array: new Uint8Array([1, 2, 3, 4, 5, 6, 7, 0]), + documentReference: firestore.doc('foo/bar'), + vectorValue: FieldValue.vector([1, 2, 3]), + map: { + number: 2, + string: 'b string', + }, + array: [1, 'c string'], + }).as('map'), + array([ + 1, + 'a string', + true, + null, + new GeoPoint(0.1, 0.2), + refTimestamp, + refDate, + new Uint8Array([1, 2, 3, 4, 5, 6, 7, 0]), + firestore.doc('foo/bar'), + FieldValue.vector([1, 2, 3]), + { + number: 2, + string: 'b string', + }, + ]).as('array'), + ]; + + const snapshots = await firestore + .pipeline() + .collection(randomCol.path) + .limit(1) + .select(constants[0], ...constants.slice(1)) + .execute(); + + expectResults(snapshots, { + number: 1, + string: 'a string', + boolean: true, + null: null, + geoPoint: new GeoPoint(0.1, 0.2), + timestamp: refTimestamp, + date: Timestamp.fromDate(refDate), + bytes: new Uint8Array([1, 2, 3, 4, 5, 6, 7, 0]), + documentReference: firestore.collection('foo').doc('bar'), + vectorValue: FieldValue.vector([1, 2, 3]), + vectorValue2: FieldValue.vector([1, 2, 3]), + map: { + number: 1, + string: 'a string', + boolean: true, + null: null, + geoPoint: new GeoPoint(0.1, 0.2), + timestamp: refTimestamp, + date: Timestamp.fromDate(refDate), + uint8Array: new Uint8Array([1, 2, 3, 4, 5, 6, 7, 0]), + documentReference: firestore.collection('foo').doc('bar'), + vectorValue: FieldValue.vector([1, 2, 3]), + map: { + number: 2, + string: 'b string', + }, + array: [1, 'c string'], + }, + array: [ + 1, + 'a string', + true, + null, + new GeoPoint(0.1, 0.2), + refTimestamp, + Timestamp.fromDate(refDate), + new Uint8Array([1, 2, 3, 4, 5, 6, 7, 0]), + firestore.collection('foo').doc('bar'), + FieldValue.vector([1, 2, 3]), + { + number: 2, + string: 'b string', + }, + ], + }); + }); + + it('throws on undefined in a map', async () => { + expect(() => { + firestore + .pipeline() + .collection(randomCol.path) + .limit(1) + .select( + map({ + number: 1, + undefined, + }).as('foo') + ); + }).to.throw( + 'Function map() called with invalid data. Unsupported field value: undefined' + ); + }); + + it('throws on undefined in an array', async () => { + expect(() => { + firestore + .pipeline() + .collection(randomCol.path) + .limit(1) + .select(array([1, undefined]).as('foo')); + }).to.throw( + 'Function array() called with invalid data. Unsupported field value: undefined' + ); + }); + + it('converts arrays and plain objects to functionValues if the customer intent is unspecified', async () => { + const snapshot = await firestore + .pipeline() + .collection(randomCol.path) + .sort(field('rating').descending()) + .limit(1) + .select( + 'title', + 'author', + 'genre', + 'rating', 'published', - [1965, 1925, 1949, 1960, 1866, 1985, 1954, 1967, 1979] + 'tags', + 'awards' ) - ) - .select('title') - .execute(); - expectResults(results, {title: 'Pride and Prejudice'}); - }); + .addFields( + array([ + 1, + 2, + field('genre'), + multiply('rating', 10), + [field('title')], + { + published: field('published'), + }, + ]).as('metadataArray'), + map({ + genre: field('genre'), + rating: multiply('rating', 10), + nestedArray: [field('title')], + nestedMap: { + published: field('published'), + }, + }).as('metadata') + ) + .where( + and( + eq('metadataArray', [ + 1, + 2, + field('genre'), + multiply('rating', 10), + [field('title')], + { + published: field('published'), + }, + ]), + eq('metadata', { + genre: field('genre'), + rating: multiply('rating', 10), + nestedArray: [field('title')], + nestedMap: { + published: field('published'), + }, + }) + ) + ) + .execute(); - it('arrayContains works', async () => { - const results = await randomCol - .pipeline() - .where(arrayContains('tags', 'comedy')) - .select('title') - .execute(); - expectResults(results, {title: "The Hitchhiker's Guide to the Galaxy"}); - }); + expect(snapshot.results.length).to.equal(1); - it('arrayContainsAny works', async () => { - const results = await randomCol - .pipeline() - .where(arrayContainsAny('tags', ['comedy', 'classic'])) - .select('title') - .execute(); - expectResults( - results, - {title: "The Hitchhiker's Guide to the Galaxy"}, - {title: 'Pride and Prejudice'} - ); + expectResults(snapshot, { + title: 'The Lord of the Rings', + author: 'J.R.R. Tolkien', + genre: 'Fantasy', + published: 1954, + rating: 4.7, + tags: ['adventure', 'magic', 'epic'], + awards: {hugo: false, nebula: false}, + metadataArray: [ + 1, + 2, + 'Fantasy', + 47, + ['The Lord of the Rings'], + { + published: 1954, + }, + ], + metadata: { + genre: 'Fantasy', + rating: 47, + nestedArray: ['The Lord of the Rings'], + nestedMap: { + published: 1954, + }, + }, + }); + }); }); - it('arrayContainsAll works', async () => { - const results = await randomCol - .pipeline() - .where(Field.of('tags').arrayContainsAll('adventure', 'magic')) - .select('title') - .execute(); - expectResults(results, {title: 'The Lord of the Rings'}); - }); + describe('stages', () => { + describe('aggregate stage', () => { + it('supports aggregate', async () => { + let snapshot = await firestore + .pipeline() + .collection(randomCol.path) + .aggregate(countAll().as('count')) + .execute(); + expectResults(snapshot, {count: 10}); + + snapshot = await firestore + .pipeline() + .collection(randomCol.path) + .where(eq('genre', 'Science Fiction')) + .aggregate( + countAll().as('count'), + avg('rating').as('avgRating'), + maximum('rating').as('maxRating'), + sum('rating').as('sumRating') + ) + .execute(); + expectResults(snapshot, { + count: 2, + avgRating: 4.4, + maxRating: 4.6, + sumRating: 8.8, + }); + }); + + it('rejects groups without accumulators', async () => { + expect( + await firestore + .pipeline() + .collection(randomCol.path) + .where(lt('published', 1900)) + .aggregate({ + accumulators: [], + groups: ['genre'], + }) + .execute() + ).to.be.rejected; + }); + + it('returns group and accumulate results', async () => { + const snapshot = await firestore + .pipeline() + .collection(randomCol.path) + .where(lt(field('published'), 1984)) + .aggregate({ + accumulators: [avg('rating').as('avgRating')], + groups: ['genre'], + }) + .where(gt('avgRating', 4.3)) + .sort(field('avgRating').descending()) + .execute(); + expectResults( + snapshot, + {avgRating: 4.7, genre: 'Fantasy'}, + {avgRating: 4.5, genre: 'Romance'}, + {avgRating: 4.4, genre: 'Science Fiction'} + ); + }); + + it('returns min, max, count, and countAll accumulations', async () => { + const snapshot = await firestore + .pipeline() + .collection(randomCol.path) + .aggregate( + count('cost').as('booksWithCost'), + countAll().as('count'), + maximum('rating').as('maxRating'), + minimum('published').as('minPublished') + ) + .execute(); + expectResults(snapshot, { + booksWithCost: 1, + count: 10, + maxRating: 4.7, + minPublished: 1813, + }); + }); + + it('returns countif accumulation', async () => { + let snapshot = await firestore + .pipeline() + .collection(randomCol.path) + .aggregate(countIf(field('rating').gt(4.3)).as('count')) + .execute(); + const expectedResults = { + count: 3, + }; + expectResults(snapshot, expectedResults); + + snapshot = await firestore + .pipeline() + .collection(randomCol.path) + .aggregate(field('rating').gt(4.3).countIf().as('count')) + .execute(); + expectResults(snapshot, expectedResults); + }); + }); - it('arrayLength works', async () => { - const results = await randomCol - .pipeline() - .select(Field.of('tags').arrayLength().as('tagsCount')) - .where(eq('tagsCount', 3)) - .execute(); - expect(results.length).to.equal(10); - }); + describe('distinct stage', () => { + it('returns distinct values as expected', async () => { + const snapshot = await firestore + .pipeline() + .collection(randomCol.path) + .distinct('genre', 'author') + .sort(field('genre').ascending(), field('author').ascending()) + .execute(); + expectResults( + snapshot, + {genre: 'Dystopian', author: 'George Orwell'}, + {genre: 'Dystopian', author: 'Margaret Atwood'}, + {genre: 'Fantasy', author: 'J.R.R. Tolkien'}, + {genre: 'Magical Realism', author: 'Gabriel García Márquez'}, + {genre: 'Modernist', author: 'F. Scott Fitzgerald'}, + {genre: 'Psychological Thriller', author: 'Fyodor Dostoevsky'}, + {genre: 'Romance', author: 'Jane Austen'}, + {genre: 'Science Fiction', author: 'Douglas Adams'}, + {genre: 'Science Fiction', author: 'Frank Herbert'}, + {genre: 'Southern Gothic', author: 'Harper Lee'} + ); + }); + }); - // array_concat not implemented - it.skip('arrayConcat works', async () => { - const results = await randomCol - .pipeline() - .select( - Field.of('tags').arrayConcat(['newTag1', 'newTag2']).as('modifiedTags') - ) - .limit(1) - .execute(); - expectResults(results, { - modifiedTags: ['comedy', 'space', 'adventure', 'newTag1', 'newTag2'], + describe('select stage', () => { + it('can select fields', async () => { + const snapshot = await firestore + .pipeline() + .collection(randomCol.path) + .select('title', 'author') + .sort(field('author').ascending()) + .execute(); + expectResults( + snapshot, + { + title: "The Hitchhiker's Guide to the Galaxy", + author: 'Douglas Adams', + }, + {title: 'The Great Gatsby', author: 'F. Scott Fitzgerald'}, + {title: 'Dune', author: 'Frank Herbert'}, + {title: 'Crime and Punishment', author: 'Fyodor Dostoevsky'}, + { + title: 'One Hundred Years of Solitude', + author: 'Gabriel García Márquez', + }, + {title: '1984', author: 'George Orwell'}, + {title: 'To Kill a Mockingbird', author: 'Harper Lee'}, + {title: 'The Lord of the Rings', author: 'J.R.R. Tolkien'}, + {title: 'Pride and Prejudice', author: 'Jane Austen'}, + {title: "The Handmaid's Tale", author: 'Margaret Atwood'} + ); + }); }); - }); - it('testStrConcat', async () => { - const results = await randomCol - .pipeline() - .select( - Field.of('author').strConcat(' - ', Field.of('title')).as('bookInfo') - ) - .limit(1) - .execute(); - expectResults(results, { - bookInfo: "Douglas Adams - The Hitchhiker's Guide to the Galaxy", + describe('addField stage', () => { + it('can add fields', async () => { + const snapshot = await firestore + .pipeline() + .collection(randomCol.path) + .select('title', 'author') + .addFields(constant('bar').as('foo')) + .sort(field('author').ascending()) + .execute(); + expectResults( + snapshot, + { + title: "The Hitchhiker's Guide to the Galaxy", + author: 'Douglas Adams', + foo: 'bar', + }, + { + title: 'The Great Gatsby', + author: 'F. Scott Fitzgerald', + foo: 'bar', + }, + {title: 'Dune', author: 'Frank Herbert', foo: 'bar'}, + { + title: 'Crime and Punishment', + author: 'Fyodor Dostoevsky', + foo: 'bar', + }, + { + title: 'One Hundred Years of Solitude', + author: 'Gabriel García Márquez', + foo: 'bar', + }, + {title: '1984', author: 'George Orwell', foo: 'bar'}, + { + title: 'To Kill a Mockingbird', + author: 'Harper Lee', + foo: 'bar', + }, + { + title: 'The Lord of the Rings', + author: 'J.R.R. Tolkien', + foo: 'bar', + }, + {title: 'Pride and Prejudice', author: 'Jane Austen', foo: 'bar'}, + { + title: "The Handmaid's Tale", + author: 'Margaret Atwood', + foo: 'bar', + } + ); + }); }); - }); - it('testStartsWith', async () => { - const results = await randomCol - .pipeline() - .where(startsWith('title', 'The')) - .select('title') - .sort(Field.of('title').ascending()) - .execute(); - expectResults( - results, - {title: 'The Great Gatsby'}, - {title: "The Handmaid's Tale"}, - {title: "The Hitchhiker's Guide to the Galaxy"}, - {title: 'The Lord of the Rings'} - ); - }); + describe('removeFields stage', () => { + it('can remove fields', async () => { + const snapshot = await firestore + .pipeline() + .collection(randomCol.path) + .select('title', 'author') + .sort(field('author').ascending()) + .removeFields(field('author')) + .sort(field('author').ascending()) + .execute(); + expectResults( + snapshot, + { + title: "The Hitchhiker's Guide to the Galaxy", + }, + { + title: 'The Great Gatsby', + }, + {title: 'Dune'}, + { + title: 'Crime and Punishment', + }, + { + title: 'One Hundred Years of Solitude', + }, + {title: '1984'}, + { + title: 'To Kill a Mockingbird', + }, + { + title: 'The Lord of the Rings', + }, + {title: 'Pride and Prejudice'}, + { + title: "The Handmaid's Tale", + } + ); + }); + }); - it('testEndsWith', async () => { - const results = await randomCol - .pipeline() - .where(endsWith('title', 'y')) - .select('title') - .sort(Field.of('title').descending()) - .execute(); - expectResults( - results, - {title: "The Hitchhiker's Guide to the Galaxy"}, - {title: 'The Great Gatsby'} - ); - }); + describe('where stage', () => { + it('where with and (2 conditions)', async () => { + const snapshot = await firestore + .pipeline() + .collection(randomCol.path) + .where( + and( + gt('rating', 4.5), + eqAny('genre', ['Science Fiction', 'Romance', 'Fantasy']) + ) + ) + .execute(); + expectResults(snapshot, 'book10', 'book4'); + }); + it('where with and (3 conditions)', async () => { + const snapshot = await firestore + .pipeline() + .collection(randomCol.path) + .where( + and( + gt('rating', 4.5), + eqAny('genre', ['Science Fiction', 'Romance', 'Fantasy']), + lt('published', 1965) + ) + ) + .execute(); + expectResults(snapshot, 'book4'); + }); + it('where with or', async () => { + const snapshot = await firestore + .pipeline() + .collection(randomCol.path) + .where( + or( + eq('genre', 'Romance'), + eq('genre', 'Dystopian'), + eq('genre', 'Fantasy') + ) + ) + .sort(ascending('title')) + .select('title') + .execute(); + expectResults( + snapshot, + {title: '1984'}, + {title: 'Pride and Prejudice'}, + {title: "The Handmaid's Tale"}, + {title: 'The Lord of the Rings'} + ); + }); + + it('where with xor', async () => { + const snapshot = await firestore + .pipeline() + .collection(randomCol.path) + .where( + xor( + eq('genre', 'Romance'), + eq('genre', 'Dystopian'), + eq('genre', 'Fantasy'), + eq('published', 1949) + ) + ) + .select('title') + .execute(); + expectResults( + snapshot, + {title: 'Pride and Prejudice'}, + {title: 'The Lord of the Rings'}, + {title: "The Handmaid's Tale"} + ); + }); + }); - it('testLength', async () => { - const results = await randomCol - .pipeline() - .select( - Field.of('title').charLength().as('titleLength'), - Field.of('title') - ) - .where(gt('titleLength', 20)) - .sort(Field.of('title').ascending()) - .execute(); - - expectResults( - results, - - { - titleLength: 29, - title: 'One Hundred Years of Solitude', - }, - { - titleLength: 36, - title: "The Hitchhiker's Guide to the Galaxy", - }, - { - titleLength: 21, - title: 'The Lord of the Rings', - }, - { - titleLength: 21, - title: 'To Kill a Mockingbird', - } - ); - }); + describe('sort, offset, and limit stages', () => { + it('supports sort, offset, and limits', async () => { + const snapshot = await firestore + .pipeline() + .collection(randomCol.path) + .sort(field('author').ascending()) + .offset(5) + .limit(3) + .select('title', 'author') + .execute(); + expectResults( + snapshot, + {title: '1984', author: 'George Orwell'}, + {title: 'To Kill a Mockingbird', author: 'Harper Lee'}, + {title: 'The Lord of the Rings', author: 'J.R.R. Tolkien'} + ); + }); + }); - // to_lower not implemented - it.skip('testToLowercase', async () => { - const results = await randomCol - .pipeline() - .select(Field.of('title').toLower().as('lowercaseTitle')) - .limit(1) - .execute(); - expectResults(results, { - lowercaseTitle: "the hitchhiker's guide to the galaxy", + describe('generic stage', () => { + it('can select fields', async () => { + const snapshot = await firestore + .pipeline() + .collection(randomCol.path) + .genericStage('select', [ + { + title: field('title'), + metadata: { + author: field('author'), + }, + }, + ]) + .sort(field('author').ascending()) + .limit(1) + .execute(); + expectResults(snapshot, { + metadata: { + author: 'Frank Herbert', + }, + title: 'Dune', + }); + }); + + it('can add fields', async () => { + const snapshot = await firestore + .pipeline() + .collection(randomCol.path) + .sort(field('author').ascending()) + .limit(1) + .select('title', 'author') + .genericStage('add_fields', [ + { + display: strConcat('title', ' - ', field('author')), + }, + ]) + .execute(); + expectResults(snapshot, { + title: "The Hitchhiker's Guide to the Galaxy", + author: 'Douglas Adams', + display: "The Hitchhiker's Guide to the Galaxy - Douglas Adams", + }); + }); + + it('can filter with where', async () => { + const snapshot = await firestore + .pipeline() + .collection(randomCol.path) + .select('title', 'author') + .genericStage('where', [field('author').eq('Douglas Adams')]) + .execute(); + expectResults(snapshot, { + title: "The Hitchhiker's Guide to the Galaxy", + author: 'Douglas Adams', + }); + }); + + it('can limit, offset, and sort', async () => { + const snapshot = await firestore + .pipeline() + .collection(randomCol.path) + .select('title', 'author') + .genericStage('sort', [ + { + direction: 'ascending', + expression: field('author'), + }, + ]) + .genericStage('offset', [3]) + .genericStage('limit', [1]) + .execute(); + expectResults(snapshot, { + author: 'Fyodor Dostoevsky', + title: 'Crime and Punishment', + }); + }); + + it('can perform aggregate query', async () => { + const snapshot = await firestore + .pipeline() + .collection(randomCol.path) + .select('title', 'author', 'rating') + .genericStage('aggregate', [ + {averageRating: field('rating').avg()}, + {}, + ]) + .execute(); + expectResults(snapshot, { + averageRating: 4.3100000000000005, + }); + }); + + it('can perform distinct query', async () => { + const snapshot = await firestore + .pipeline() + .collection(randomCol.path) + .select('title', 'author', 'rating') + .genericStage('distinct', [{rating: field('rating')}]) + .sort(field('rating').descending()) + .execute(); + expectResults( + snapshot, + { + rating: 4.7, + }, + { + rating: 4.6, + }, + { + rating: 4.5, + }, + { + rating: 4.3, + }, + { + rating: 4.2, + }, + { + rating: 4.1, + }, + { + rating: 4.0, + } + ); + }); }); - }); - // to_upper not implemented - it.skip('testToUppercase', async () => { - const results = await randomCol - .pipeline() - .select(Field.of('author').toUpper().as('uppercaseAuthor')) - .limit(1) - .execute(); - expectResults(results, {uppercaseAuthor: 'DOUGLAS ADAMS'}); - }); + describe('replaceWith stage', () => { + it('run pipeline with replaceWith field name', async () => { + const snapshot = await firestore + .pipeline() + .collection(randomCol.path) + .where(eq('title', "The Hitchhiker's Guide to the Galaxy")) + .replaceWith('awards') + .execute(); + expectResults(snapshot, { + hugo: true, + nebula: false, + others: {unknown: {year: 1980}}, + }); + }); + + it('run pipeline with replaceWith Expr result', async () => { + const snapshot = await firestore + .pipeline() + .collection(randomCol.path) + .where(eq('title', "The Hitchhiker's Guide to the Galaxy")) + .replaceWith( + map({ + foo: 'bar', + baz: { + title: field('title'), + }, + }) + ) + .execute(); + expectResults(snapshot, { + foo: 'bar', + baz: {title: "The Hitchhiker's Guide to the Galaxy"}, + }); + }); + }); - // trim not implemented - it.skip('testTrim', async () => { - const results = await randomCol - .pipeline() - .addFields(strConcat(' ', Field.of('title'), ' ').as('spacedTitle')) - .select( - Field.of('spacedTitle').trim().as('trimmedTitle'), - Field.of('spacedTitle') - ) - .limit(1) - .execute(); - expectResults(results, { - spacedTitle: " The Hitchhiker's Guide to the Galaxy ", - trimmedTitle: "The Hitchhiker's Guide to the Galaxy", + describe('sample stage', () => { + it('run pipeline with sample limit of 3', async () => { + const snapshot = await firestore + .pipeline() + .collection(randomCol.path) + .sample(3) + .execute(); + expect(snapshot.results.length).to.equal(3); + }); + + it('run pipeline with sample limit of {documents: 3}', async () => { + const snapshot = await firestore + .pipeline() + .collection(randomCol.path) + .sample({documents: 3}) + .execute(); + expect(snapshot.results.length).to.equal(3); + }); + + it('run pipeline with sample limit of {percentage: 0.6}', async () => { + let avgSize = 0; + const numIterations = 20; + for (let i = 0; i < numIterations; i++) { + const snapshot = await firestore + .pipeline() + .collection(randomCol.path) + .sample({percentage: 0.6}) + .execute(); + + avgSize += snapshot.results.length; + } + avgSize /= numIterations; + expect(avgSize).to.be.closeTo(6, 1); + }); }); - }); - it('testLike', async () => { - const results = await randomCol - .pipeline() - .where(like('title', '%Guide%')) - .select('title') - .execute(); - expectResults(results, {title: "The Hitchhiker's Guide to the Galaxy"}); - }); + describe('union stage', () => { + it('run pipeline with union', async () => { + const snapshot = await firestore + .pipeline() + .collection(randomCol.path) + .union(firestore.pipeline().collection(randomCol.path)) + .sort(field(FieldPath.documentId()).ascending()) + .execute(); + expectResults( + snapshot, + 'book1', + 'book1', + 'book10', + 'book10', + 'book2', + 'book2', + 'book3', + 'book3', + 'book4', + 'book4', + 'book5', + 'book5', + 'book6', + 'book6', + 'book7', + 'book7', + 'book8', + 'book8', + 'book9', + 'book9' + ); + }); + }); - it('testRegexContains', async () => { - const results = await randomCol - .pipeline() - .where(regexContains('title', '(?i)(the|of)')) - .execute(); - expect(results.length).to.equal(5); - }); + describe('unnest stage', () => { + it('run pipeline with unnest', async () => { + const snapshot = await firestore + .pipeline() + .collection(randomCol.path) + .where(eq('title', "The Hitchhiker's Guide to the Galaxy")) + .unnest(field('tags').as('tag')) + .select( + 'title', + 'author', + 'genre', + 'published', + 'rating', + 'tags', + 'tag', + 'awards', + 'nestedField' + ) + .execute(); + expectResults( + snapshot, + { + title: "The Hitchhiker's Guide to the Galaxy", + author: 'Douglas Adams', + genre: 'Science Fiction', + published: 1979, + rating: 4.2, + tags: ['comedy', 'space', 'adventure'], + tag: 'comedy', + awards: { + hugo: true, + nebula: false, + others: {unknown: {year: 1980}}, + }, + nestedField: {'level.1': {'level.2': true}}, + }, + { + title: "The Hitchhiker's Guide to the Galaxy", + author: 'Douglas Adams', + genre: 'Science Fiction', + published: 1979, + rating: 4.2, + tags: ['comedy', 'space', 'adventure'], + tag: 'space', + awards: { + hugo: true, + nebula: false, + others: {unknown: {year: 1980}}, + }, + nestedField: {'level.1': {'level.2': true}}, + }, + { + title: "The Hitchhiker's Guide to the Galaxy", + author: 'Douglas Adams', + genre: 'Science Fiction', + published: 1979, + rating: 4.2, + tags: ['comedy', 'space', 'adventure'], + tag: 'adventure', + awards: { + hugo: true, + nebula: false, + others: {unknown: {year: 1980}}, + }, + nestedField: {'level.1': {'level.2': true}}, + } + ); + }); + it('unnest an expr', async () => { + const snapshot = await firestore + .pipeline() + .collection(randomCol.path) + .where(eq('title', "The Hitchhiker's Guide to the Galaxy")) + .unnest(array([1, 2, 3]).as('copy')) + .select( + 'title', + 'author', + 'genre', + 'published', + 'rating', + 'tags', + 'copy', + 'awards', + 'nestedField' + ) + .execute(); + expectResults( + snapshot, + { + title: "The Hitchhiker's Guide to the Galaxy", + author: 'Douglas Adams', + genre: 'Science Fiction', + published: 1979, + rating: 4.2, + tags: ['comedy', 'space', 'adventure'], + copy: 1, + awards: { + hugo: true, + nebula: false, + others: {unknown: {year: 1980}}, + }, + nestedField: {'level.1': {'level.2': true}}, + }, + { + title: "The Hitchhiker's Guide to the Galaxy", + author: 'Douglas Adams', + genre: 'Science Fiction', + published: 1979, + rating: 4.2, + tags: ['comedy', 'space', 'adventure'], + copy: 2, + awards: { + hugo: true, + nebula: false, + others: {unknown: {year: 1980}}, + }, + nestedField: {'level.1': {'level.2': true}}, + }, + { + title: "The Hitchhiker's Guide to the Galaxy", + author: 'Douglas Adams', + genre: 'Science Fiction', + published: 1979, + rating: 4.2, + tags: ['comedy', 'space', 'adventure'], + copy: 3, + awards: { + hugo: true, + nebula: false, + others: {unknown: {year: 1980}}, + }, + nestedField: {'level.1': {'level.2': true}}, + } + ); + }); + }); - it('testRegexMatches', async () => { - const results = await randomCol - .pipeline() - .where(regexMatch('title', '.*(?i)(the|of).*')) - .execute(); - expect(results.length).to.equal(5); + describe('findNearest stage', () => { + it('run pipeline with findNearest', async () => { + const measures: Array = [ + 'euclidean', + 'dot_product', + 'cosine', + ]; + for (const measure of measures) { + const snapshot = await firestore + .pipeline() + .collection(randomCol) + .findNearest({ + field: 'embedding', + vectorValue: FieldValue.vector([10, 1, 3, 1, 2, 1, 1, 1, 1, 1]), + limit: 3, + distanceMeasure: measure, + }) + .select('title') + .execute(); + expectResults( + snapshot, + { + title: "The Hitchhiker's Guide to the Galaxy", + }, + { + title: 'One Hundred Years of Solitude', + }, + { + title: "The Handmaid's Tale", + } + ); + } + }); + + it('optionally returns the computed distance', async () => { + const snapshot = await firestore + .pipeline() + .collection(randomCol) + .findNearest({ + field: 'embedding', + vectorValue: FieldValue.vector([10, 1, 2, 1, 1, 1, 1, 1, 1, 1]), + limit: 2, + distanceMeasure: 'euclidean', + distanceField: 'computedDistance', + }) + .select('title', 'computedDistance') + .execute(); + expectResults( + snapshot, + { + title: "The Hitchhiker's Guide to the Galaxy", + computedDistance: 1, + }, + { + title: 'One Hundred Years of Solitude', + computedDistance: 12.041594578792296, + } + ); + }); + }); }); - it('testQueryByDocumentReference', async () => { - const results = await randomCol - .pipeline() - .where(eq(Field.of(FieldPath.documentId()), randomCol.doc('book01'))) - .select('title') - .execute(); - expectResults(results, {title: "The Hitchhiker's Guide to the Galaxy"}); - }); + describe('function expressions', () => { + it('logical max works', async () => { + const snapshot = await firestore + .pipeline() + .collection(randomCol.path) + .select( + 'title', + logicalMaximum(constant(1960), field('published'), 1961).as( + 'published-safe' + ) + ) + .sort(field('title').ascending()) + .limit(3) + .execute(); + expectResults( + snapshot, + {title: '1984', 'published-safe': 1961}, + {title: 'Crime and Punishment', 'published-safe': 1961}, + {title: 'Dune', 'published-safe': 1965} + ); + }); - it('testArithmeticOperations', async () => { - const results = await randomCol - .pipeline() - .select( - add(Field.of('rating'), 1).as('ratingPlusOne'), - subtract(Field.of('published'), 1900).as('yearsSince1900'), - Field.of('rating').multiply(10).as('ratingTimesTen'), - Field.of('rating').divide(2).as('ratingDividedByTwo') - ) - .limit(1) - .execute(); - expectResults(results, { - ratingPlusOne: 5.2, - yearsSince1900: 79, - ratingTimesTen: 42, - ratingDividedByTwo: 2.1, + it('logical min works', async () => { + const snapshot = await firestore + .pipeline() + .collection(randomCol.path) + .select( + 'title', + logicalMinimum(constant(1960), field('published'), 1961).as( + 'published-safe' + ) + ) + .sort(field('title').ascending()) + .limit(3) + .execute(); + expectResults( + snapshot, + {title: '1984', 'published-safe': 1949}, + {title: 'Crime and Punishment', 'published-safe': 1866}, + {title: 'Dune', 'published-safe': 1960} + ); }); - }); - it('testComparisonOperators', async () => { - const results = await randomCol - .pipeline() - .where( - and( - gt('rating', 4.2), - lte(Field.of('rating'), 4.5), - neq('genre', 'Science Fiction') + it('cond works', async () => { + const snapshot = await firestore + .pipeline() + .collection(randomCol.path) + .select( + 'title', + cond( + lt(field('published'), 1960), + constant(1960), + field('published') + ).as('published-safe') ) - ) - .select('rating', 'title') - .sort(Field.of('title').ascending()) - .execute(); - expectResults( - results, - {rating: 4.3, title: 'Crime and Punishment'}, - { - rating: 4.3, - title: 'One Hundred Years of Solitude', - }, - {rating: 4.5, title: 'Pride and Prejudice'} - ); - }); + .sort(field('title').ascending()) + .limit(3) + .execute(); + expectResults( + snapshot, + {title: '1984', 'published-safe': 1960}, + {title: 'Crime and Punishment', 'published-safe': 1960}, + {title: 'Dune', 'published-safe': 1965} + ); + }); - it('testLogicalOperators', async () => { - const results = await randomCol - .pipeline() - .where( - or( - and(gt('rating', 4.5), eq('genre', 'Science Fiction')), - lt('published', 1900) + it('eqAny works', async () => { + const snapshot = await firestore + .pipeline() + .collection(randomCol.path) + .where(eqAny('published', [1979, 1999, 1967])) + .sort(descending('title')) + .select('title') + .execute(); + expectResults( + snapshot, + {title: "The Hitchhiker's Guide to the Galaxy"}, + {title: 'One Hundred Years of Solitude'} + ); + }); + + it('notEqAny works', async () => { + const snapshot = await firestore + .pipeline() + .collection(randomCol.path) + .where( + notEqAny( + 'published', + [1965, 1925, 1949, 1960, 1866, 1985, 1954, 1967, 1979] + ) ) - ) - .select('title') - .sort(Field.of('title').ascending()) - .execute(); - expectResults( - results, - {title: 'Crime and Punishment'}, - {title: 'Dune'}, - {title: 'Pride and Prejudice'} - ); - }); + .select('title') + .execute(); + expectResults(snapshot, {title: 'Pride and Prejudice'}); + }); - it('testChecks', async () => { - const results = await randomCol - .pipeline() - .where(not(Field.of('rating').isNaN())) - .select( - Field.of('rating').eq(null).as('ratingIsNull'), - not(Field.of('rating').isNaN()).as('ratingIsNotNaN') - ) - .limit(1) - .execute(); - expectResults(results, {ratingIsNull: false, ratingIsNotNaN: true}); - }); + it('arrayContains works', async () => { + const snapshot = await firestore + .pipeline() + .collection(randomCol.path) + .where(arrayContains('tags', 'comedy')) + .select('title') + .execute(); + expectResults(snapshot, { + title: "The Hitchhiker's Guide to the Galaxy", + }); + }); - it('testMapGet', async () => { - const results = await randomCol - .pipeline() - .select( - Field.of('awards').mapGet('hugo').as('hugoAward'), - Field.of('awards').mapGet('others').as('others'), - Field.of('title') - ) - .where(eq('hugoAward', true)) - .execute(); - expectResults( - results, - { - hugoAward: true, + it('arrayContainsAny works', async () => { + const snapshot = await firestore + .pipeline() + .collection(randomCol.path) + .where(arrayContainsAny('tags', ['comedy', 'classic'])) + .sort(descending('title')) + .select('title') + .execute(); + expectResults( + snapshot, + {title: "The Hitchhiker's Guide to the Galaxy"}, + {title: 'Pride and Prejudice'} + ); + }); + + it('arrayContainsAll works', async () => { + const snapshot = await firestore + .pipeline() + .collection(randomCol.path) + .where(arrayContainsAll('tags', ['adventure', 'magic'])) + .select('title') + .execute(); + expectResults(snapshot, {title: 'The Lord of the Rings'}); + }); + + it('arrayLength works', async () => { + const snapshot = await firestore + .pipeline() + .collection(randomCol.path) + .select(arrayLength('tags').as('tagsCount')) + .where(eq('tagsCount', 3)) + .execute(); + expect(snapshot.results.length).to.equal(10); + }); + + it('testStrConcat', async () => { + const snapshot = await firestore + .pipeline() + .collection(randomCol.path) + .sort(ascending('author')) + .select(field('author').strConcat(' - ', field('title')).as('bookInfo')) + .limit(1) + .execute(); + expectResults(snapshot, { + bookInfo: "Douglas Adams - The Hitchhiker's Guide to the Galaxy", + }); + }); + + it('testStartsWith', async () => { + const snapshot = await firestore + .pipeline() + .collection(randomCol.path) + .where(startsWith('title', 'The')) + .select('title') + .sort(field('title').ascending()) + .execute(); + expectResults( + snapshot, + {title: 'The Great Gatsby'}, + {title: "The Handmaid's Tale"}, + {title: "The Hitchhiker's Guide to the Galaxy"}, + {title: 'The Lord of the Rings'} + ); + }); + + it('testEndsWith', async () => { + const snapshot = await firestore + .pipeline() + .collection(randomCol.path) + .where(endsWith('title', 'y')) + .select('title') + .sort(field('title').descending()) + .execute(); + expectResults( + snapshot, + {title: "The Hitchhiker's Guide to the Galaxy"}, + {title: 'The Great Gatsby'} + ); + }); + + it('testStrContains', async () => { + const snapshot = await firestore + .pipeline() + .collection(randomCol.path) + .where(strContains('title', "'s")) + .select('title') + .sort(field('title').ascending()) + .execute(); + expectResults( + snapshot, + {title: "The Handmaid's Tale"}, + {title: "The Hitchhiker's Guide to the Galaxy"} + ); + }); + + it('testLength', async () => { + const snapshot = await firestore + .pipeline() + .collection(randomCol.path) + .select(charLength('title').as('titleLength'), field('title')) + .where(gt('titleLength', 20)) + .sort(field('title').ascending()) + .execute(); + + expectResults( + snapshot, + + { + titleLength: 29, + title: 'One Hundred Years of Solitude', + }, + { + titleLength: 36, + title: "The Hitchhiker's Guide to the Galaxy", + }, + { + titleLength: 21, + title: 'The Lord of the Rings', + }, + { + titleLength: 21, + title: 'To Kill a Mockingbird', + } + ); + }); + + it('testLike', async () => { + const snapshot = await firestore + .pipeline() + .collection(randomCol.path) + .where(like('title', '%Guide%')) + .select('title') + .execute(); + expectResults(snapshot, { title: "The Hitchhiker's Guide to the Galaxy", - others: {unknown: {year: 1980}}, - }, - {hugoAward: true, title: 'Dune', others: null} - ); - }); + }); + }); + + it('testRegexContains', async () => { + const snapshot = await firestore + .pipeline() + .collection(randomCol.path) + .where(regexContains('title', '(?i)(the|of)')) + .execute(); + expect(snapshot.results.length).to.equal(5); + }); - // it('testParent', async () => { - // const results = await randomCol - // .pipeline() - // .select( - // parent(randomCol.doc('chile').collection('subCollection').path).as( - // 'parent' - // ) - // ) - // .limit(1) - // .execute(); - // expect(results[0].data().parent.endsWith('/books')).to.be.true; - // }); - // - // it('testCollectionId', async () => { - // const results = await randomCol - // .pipeline() - // .select(collectionId(randomCol.doc('chile')).as('collectionId')) - // .limit(1) - // .execute(); - // expectResults(results, {collectionId: 'books'}); - // }); - - it('testDistanceFunctions', async () => { - const sourceVector = [0.1, 0.1]; - const targetVector = [0.5, 0.8]; - const results = await randomCol - .pipeline() - .select( - cosineDistance(Constant.vector(sourceVector), targetVector).as( - 'cosineDistance' - ), - dotProduct(Constant.vector(sourceVector), targetVector).as( - 'dotProductDistance' - ), - euclideanDistance(Constant.vector(sourceVector), targetVector).as( - 'euclideanDistance' + it('testRegexMatches', async () => { + const snapshot = await firestore + .pipeline() + .collection(randomCol.path) + .where(regexMatch('title', '.*(?i)(the|of).*')) + .execute(); + expect(snapshot.results.length).to.equal(5); + }); + + it('testArithmeticOperations', async () => { + const snapshot = await firestore + .pipeline() + .collection(randomCol.path) + .where(eq('title', 'To Kill a Mockingbird')) + .select( + add(field('rating'), 1).as('ratingPlusOne'), + subtract(field('published'), 1900).as('yearsSince1900'), + field('rating').multiply(10).as('ratingTimesTen'), + divide('rating', 2).as('ratingDividedByTwo'), + multiply('rating', 10, 2).as('ratingTimes20'), + add('rating', 1, 2).as('ratingPlus3'), + mod('rating', 2).as('ratingMod2') ) - ) - .limit(1) - .execute(); + .limit(1) + .execute(); + expectResults(snapshot, { + ratingPlusOne: 5.2, + yearsSince1900: 60, + ratingTimesTen: 42, + ratingDividedByTwo: 2.1, + ratingTimes20: 84, + ratingPlus3: 7.2, + ratingMod2: 0.20000000000000018, + }); + }); - expectResults(results, { - cosineDistance: 0.02560880430538015, - dotProductDistance: 0.13, - euclideanDistance: 0.806225774829855, + it('testComparisonOperators', async () => { + const snapshot = await firestore + .pipeline() + .collection(randomCol.path) + .where( + and( + gt('rating', 4.2), + lte(field('rating'), 4.5), + neq('genre', 'Science Fiction') + ) + ) + .select('rating', 'title') + .sort(field('title').ascending()) + .execute(); + expectResults( + snapshot, + {rating: 4.3, title: 'Crime and Punishment'}, + { + rating: 4.3, + title: 'One Hundred Years of Solitude', + }, + {rating: 4.5, title: 'Pride and Prejudice'} + ); }); - }); - it('testNestedFields', async () => { - const results = await randomCol - .pipeline() - .where(eq('awards.hugo', true)) - .select('title', 'awards.hugo') - .execute(); - expectResults( - results, - {title: "The Hitchhiker's Guide to the Galaxy", 'awards.hugo': true}, - {title: 'Dune', 'awards.hugo': true} - ); - }); + it('testLogicalOperators', async () => { + const snapshot = await firestore + .pipeline() + .collection(randomCol.path) + .where( + or( + and(gt('rating', 4.5), eq('genre', 'Science Fiction')), + lt('published', 1900) + ) + ) + .select('title') + .sort(field('title').ascending()) + .execute(); + expectResults( + snapshot, + {title: 'Crime and Punishment'}, + {title: 'Dune'}, + {title: 'Pride and Prejudice'} + ); + }); - it('test mapGet with field name including . notation', async () => { - const results = await randomCol - .pipeline() - .where(eq('awards.hugo', true)) - .select( - 'title', - Field.of('nestedField.level.1'), - mapGet('nestedField', 'level.1').mapGet('level.2').as('nested') - ) - .execute(); - expectResults( - results, - { - title: "The Hitchhiker's Guide to the Galaxy", - 'nestedField.level.`1`': null, - nested: true, - }, - {title: 'Dune', 'nestedField.level.`1`': null, nested: null} - ); - }); + it('testChecks', async () => { + let snapshot = await firestore + .pipeline() + .collection(randomCol.path) + .sort(field('rating').descending()) + .limit(1) + .select( + isNull('rating').as('ratingIsNull'), + isNan('rating').as('ratingIsNaN'), + isError(arrayOffset('title', 0)).as('isError'), + ifError(arrayOffset('title', 0), constant('was error')).as('ifError'), + isAbsent('foo').as('isAbsent'), + isNotNull('title').as('titleIsNotNull'), + isNotNan('cost').as('costIsNotNan'), + exists('fooBarBaz').as('fooBarBazExists'), + field('title').exists().as('titleExists') + ) + .execute(); + expectResults(snapshot, { + ratingIsNull: false, + ratingIsNaN: false, + isError: true, + ifError: 'was error', + isAbsent: true, + titleIsNotNull: true, + costIsNotNan: false, + fooBarBazExists: false, + titleExists: true, + }); + + snapshot = await firestore + .pipeline() + .collection(randomCol.path) + .sort(field('rating').descending()) + .limit(1) + .select( + field('rating').isNull().as('ratingIsNull'), + field('rating').isNan().as('ratingIsNaN'), + arrayOffset('title', 0).isError().as('isError'), + arrayOffset('title', 0).ifError(constant('was error')).as('ifError'), + field('foo').isAbsent().as('isAbsent'), + field('title').isNotNull().as('titleIsNotNull'), + field('cost').isNotNan().as('costIsNotNan') + ) + .execute(); + expectResults(snapshot, { + ratingIsNull: false, + ratingIsNaN: false, + isError: true, + ifError: 'was error', + isAbsent: true, + titleIsNotNull: true, + costIsNotNan: false, + }); + }); - it('pipeline converter works', async () => { - type AppModel = {myTitle: string; myAuthor: string; myPublished: number}; - const converter: FirestorePipelineConverter = { - fromFirestore(result: FirebaseFirestore.PipelineResult): AppModel { - return { - myTitle: result.data()!.title as string, - myAuthor: result.data()!.author as string, - myPublished: result.data()!.published as number, - }; - }, - }; + it('testMapGet', async () => { + const snapshot = await firestore + .pipeline() + .collection(randomCol.path) + .sort(field('published').descending()) + .select( + field('awards').mapGet('hugo').as('hugoAward'), + field('awards').mapGet('others').as('others'), + field('title') + ) + .where(eq('hugoAward', true)) + .execute(); + expectResults( + snapshot, + { + hugoAward: true, + title: "The Hitchhiker's Guide to the Galaxy", + others: {unknown: {year: 1980}}, + }, + {hugoAward: true, title: 'Dune', others: null} + ); + }); + + it('testDistanceFunctions', async () => { + const sourceVector = [0.1, 0.1]; + const targetVector = [0.5, 0.8]; + let snapshot = await firestore + .pipeline() + .collection(randomCol.path) + .select( + cosineDistance(constantVector(sourceVector), targetVector).as( + 'cosineDistance' + ), + dotProduct(constantVector(sourceVector), targetVector).as( + 'dotProductDistance' + ), + euclideanDistance(constantVector(sourceVector), targetVector).as( + 'euclideanDistance' + ) + ) + .limit(1) + .execute(); - const results = await firestore - .pipeline() - .collection(randomCol.path) - .sort(Field.of('published').ascending()) - .limit(2) - .withConverter(converter) - .execute(); - - const objs = results.map(r => r.data()); - expect(objs[0]).to.deep.equal({ - myAuthor: 'Jane Austen', - myPublished: 1813, - myTitle: 'Pride and Prejudice', - }); - expect(objs[1]).to.deep.equal({ - myAuthor: 'Fyodor Dostoevsky', - myPublished: 1866, - myTitle: 'Crime and Punishment', + expectResults(snapshot, { + cosineDistance: 0.02560880430538015, + dotProductDistance: 0.13, + euclideanDistance: 0.806225774829855, + }); + + snapshot = await firestore + .pipeline() + .collection(randomCol.path) + .select( + constantVector(sourceVector) + .cosineDistance(targetVector) + .as('cosineDistance'), + constantVector(sourceVector) + .dotProduct(targetVector) + .as('dotProductDistance'), + constantVector(sourceVector) + .euclideanDistance(targetVector) + .as('euclideanDistance') + ) + .limit(1) + .execute(); + + expectResults(snapshot, { + cosineDistance: 0.02560880430538015, + dotProductDistance: 0.13, + euclideanDistance: 0.806225774829855, + }); }); - }); - it('run pipeline as part of a transaction', async () => { - const pipeline = randomCol - .pipeline() - .where(eq('awards.hugo', true)) - .select('title', 'awards.hugo'); + it('testVectorLength', async () => { + const snapshot = await firestore + .pipeline() + .collection(randomCol.path) + .limit(1) + .select(vectorLength(constantVector([1, 2, 3])).as('vectorLength')) + .execute(); + expectResults(snapshot, { + vectorLength: 3, + }); + }); - await firestore.runTransaction(async transaction => { - const results = await transaction.execute(pipeline); + it('testNestedFields', async () => { + const snapshot = await firestore + .pipeline() + .collection(randomCol.path) + .where(eq('awards.hugo', true)) + .sort(descending('title')) + .select('title', 'awards.hugo') + .execute(); expectResults( - results, - {title: "The Hitchhiker's Guide to the Galaxy", 'awards.hugo': true}, + snapshot, + { + title: "The Hitchhiker's Guide to the Galaxy", + 'awards.hugo': true, + }, {title: 'Dune', 'awards.hugo': true} ); + }); - transaction.update(randomCol.doc('book01'), {foo: 'bar'}); + it('test mapGet with field name including . notation', async () => { + const snapshot = await firestore + .pipeline() + .collection(randomCol.path) + .where(eq('awards.hugo', true)) + .select( + 'title', + field('nestedField.level.1'), + mapGet('nestedField', 'level.1').mapGet('level.2').as('nested') + ) + .sort(descending('title')) + .execute(); + expectResults( + snapshot, + { + title: "The Hitchhiker's Guide to the Galaxy", + 'nestedField.level.`1`': null, + nested: true, + }, + {title: 'Dune', 'nestedField.level.`1`': null, nested: null} + ); }); - const result = await randomCol - .pipeline() - .where(eq('foo', 'bar')) - .select('title', Field.of(FieldPath.documentId())) - .execute(); - expectResults(result, {title: "The Hitchhiker's Guide to the Galaxy"}); - }); + describe('genericFunction', () => { + it('add selectable', async () => { + const snapshot = await firestore + .pipeline() + .collection(randomCol.path) + .sort(descending('rating')) + .limit(1) + .select( + new FunctionExpr('add', [field('rating'), constant(1)]).as('rating') + ) + .execute(); + expectResults(snapshot, { + rating: 5.7, + }); + }); + + it('and (variadic) selectable', async () => { + const snapshot = await firestore + .pipeline() + .collection(randomCol.path) + .where( + new BooleanExpr('and', [ + field('rating').gt(0), + field('title').charLength().lt(5), + field('tags').arrayContains('propaganda'), + ]) + ) + .select('title') + .execute(); + expectResults(snapshot, { + title: '1984', + }); + }); + + it('array contains any', async () => { + const snapshot = await firestore + .pipeline() + .collection(randomCol.path) + .where( + new BooleanExpr('array_contains_any', [ + field('tags'), + array(['politics']), + ]) + ) + .select('title') + .execute(); + expectResults(snapshot, { + title: 'Dune', + }); + }); + + it('countif aggregate', async () => { + const snapshot = await firestore + .pipeline() + .collection(randomCol.path) + .aggregate( + new AggregateFunction('count_if', [field('rating').gte(4.5)]).as( + 'countOfBest' + ) + ) + .execute(); + expectResults(snapshot, { + countOfBest: 3, + }); + }); + + it('sort by char_len', async () => { + const snapshot = await firestore + .pipeline() + .collection(randomCol.path) + .sort( + new FunctionExpr('char_length', [field('title')]).ascending(), + descending('__name__') + ) + .limit(3) + .select('title') + .execute(); + expectResults( + snapshot, + { + title: '1984', + }, + { + title: 'Dune', + }, + { + title: 'The Great Gatsby', + } + ); + }); + }); - it('run pipleine with replace', async () => { - const results = await randomCol - .pipeline() - .where(eq('title', "The Hitchhiker's Guide to the Galaxy")) - .replace('awards') - .execute(); - expectResults(results, { - title: "The Hitchhiker's Guide to the Galaxy", - author: 'Douglas Adams', - genre: 'Science Fiction', - published: 1979, - rating: 4.2, - tags: ['comedy', 'space', 'adventure'], - hugo: true, - nebula: false, - others: {unknown: {year: 1980}}, - nestedField: {'level.1': {'level.2': true}}, + itIf(testUnsupportedFeatures)('testReplaceFirst', async () => { + const snapshot = await firestore + .pipeline() + .collection(randomCol.path) + .where(eq('title', 'The Lord of the Rings')) + .limit(1) + .select(replaceFirst('title', 'o', '0').as('newName')) + .execute(); + expectResults(snapshot, {newName: 'The L0rd of the Rings'}); }); - }); - it('run pipeline with sample limit of 3', async () => { - const results = await randomCol.pipeline().sample(3).execute(); - expect(results.length).to.equal(3); - }); + itIf(testUnsupportedFeatures)('testReplaceAll', async () => { + const snapshot = await firestore + .pipeline() + .collection(randomCol.path) + .where(eq('title', 'The Lord of the Rings')) + .limit(1) + .select(replaceAll('title', 'o', '0').as('newName')) + .execute(); + expectResults(snapshot, {newName: 'The L0rd 0f the Rings'}); + }); - it('run pipeline with sample limit of {documents: 3}', async () => { - const results = await randomCol.pipeline().sample({documents: 3}).execute(); - expect(results.length).to.equal(3); - }); + it('supports Rand', async () => { + const snapshot = await firestore + .pipeline() + .collection(randomCol.path) + .limit(10) + .select(rand().as('result')) + .execute(); + expect(snapshot.results.length).to.equal(10); + snapshot.results.forEach((d: PipelineResult) => { + expect(d.get('result')).to.be.lt(1); + expect(d.get('result')).to.be.gte(0); + }); + }); + + it('supports array', async () => { + const snapshot = await firestore + .pipeline() + .collection(randomCol.path) + .sort(field('rating').descending()) + .limit(1) + .select(array([1, 2, 3, 4]).as('metadata')) + .execute(); + expect(snapshot.results.length).to.equal(1); + expectResults(snapshot, { + metadata: [1, 2, 3, 4], + }); + }); + + it('evaluates expression in array', async () => { + const snapshot = await firestore + .pipeline() + .collection(randomCol.path) + .sort(field('rating').descending()) + .limit(1) + .select( + array([1, 2, field('genre'), multiply('rating', 10)]).as('metadata') + ) + .execute(); + expect(snapshot.results.length).to.equal(1); + expectResults(snapshot, { + metadata: [1, 2, 'Fantasy', 47], + }); + }); + + it('supports arrayOffset', async () => { + let snapshot = await firestore + .pipeline() + .collection(randomCol.path) + .sort(field('rating').descending()) + .limit(3) + .select(arrayOffset('tags', 0).as('firstTag')) + .execute(); + const expectedResults = [ + { + firstTag: 'adventure', + }, + { + firstTag: 'politics', + }, + { + firstTag: 'classic', + }, + ]; + expectResults(snapshot, ...expectedResults); + + snapshot = await firestore + .pipeline() + .collection(randomCol.path) + .sort(field('rating').descending()) + .limit(3) + .select(field('tags').arrayOffset(0).as('firstTag')) + .execute(); + expectResults(snapshot, ...expectedResults); + }); + + it('supports map', async () => { + const snapshot = await firestore + .pipeline() + .collection(randomCol.path) + .sort(field('rating').descending()) + .limit(1) + .select( + map({ + foo: 'bar', + }).as('metadata') + ) + .execute(); + + expect(snapshot.results.length).to.equal(1); + expectResults(snapshot, { + metadata: { + foo: 'bar', + }, + }); + }); + + it('evaluates expression in map', async () => { + const snapshot = await firestore + .pipeline() + .collection(randomCol.path) + .sort(field('rating').descending()) + .limit(1) + .select( + map({ + genre: field('genre'), + rating: field('rating').multiply(10), + }).as('metadata') + ) + .execute(); + + expect(snapshot.results.length).to.equal(1); + expectResults(snapshot, { + metadata: { + genre: 'Fantasy', + rating: 47, + }, + }); + }); + + it('supports mapRemove', async () => { + let snapshot = await firestore + .pipeline() + .collection(randomCol.path) + .sort(field('rating').descending()) + .limit(1) + .select(mapRemove('awards', 'hugo').as('awards')) + .execute(); + expectResults(snapshot, { + awards: {nebula: false}, + }); + snapshot = await firestore + .pipeline() + .collection(randomCol.path) + .sort(field('rating').descending()) + .limit(1) + .select(field('awards').mapRemove('hugo').as('awards')) + .execute(); + expectResults(snapshot, { + awards: {nebula: false}, + }); + }); + + it('supports mapMerge', async () => { + let snapshot = await firestore + .pipeline() + .collection(randomCol.path) + .sort(field('rating').descending()) + .limit(1) + .select(mapMerge('awards', {fakeAward: true}).as('awards')) + .execute(); + expectResults(snapshot, { + awards: {nebula: false, hugo: false, fakeAward: true}, + }); + snapshot = await firestore + .pipeline() + .collection(randomCol.path) + .sort(field('rating').descending()) + .limit(1) + .select(field('awards').mapMerge({fakeAward: true}).as('awards')) + .execute(); + expectResults(snapshot, { + awards: {nebula: false, hugo: false, fakeAward: true}, + }); + }); + + it('supports timestamp conversions', async () => { + const snapshot = await firestore + .pipeline() + .collection(randomCol.path) + .limit(1) + .select( + unixSecondsToTimestamp(constant(1741380235)).as( + 'unixSecondsToTimestamp' + ), + unixMillisToTimestamp(constant(1741380235123)).as( + 'unixMillisToTimestamp' + ), + unixMicrosToTimestamp(constant(1741380235123456)).as( + 'unixMicrosToTimestamp' + ), + timestampToUnixSeconds( + constant(new Timestamp(1741380235, 123456789)) + ).as('timestampToUnixSeconds'), + timestampToUnixMicros( + constant(new Timestamp(1741380235, 123456789)) + ).as('timestampToUnixMicros'), + timestampToUnixMillis( + constant(new Timestamp(1741380235, 123456789)) + ).as('timestampToUnixMillis') + ) + .execute(); + expectResults(snapshot, { + unixMicrosToTimestamp: new Timestamp(1741380235, 123456000), + unixMillisToTimestamp: new Timestamp(1741380235, 123000000), + unixSecondsToTimestamp: new Timestamp(1741380235, 0), + timestampToUnixSeconds: 1741380235, + timestampToUnixMicros: 1741380235123456, + timestampToUnixMillis: 1741380235123, + }); + }); + + it('supports timestamp math', async () => { + const snapshot = await firestore + .pipeline() + .collection(randomCol.path) + .limit(1) + .select(constant(new Timestamp(1741380235, 0)).as('timestamp')) + .select( + timestampAdd('timestamp', 'day', 10).as('plus10days'), + timestampAdd('timestamp', 'hour', 10).as('plus10hours'), + timestampAdd('timestamp', 'minute', 10).as('plus10minutes'), + timestampAdd('timestamp', 'second', 10).as('plus10seconds'), + timestampAdd('timestamp', 'microsecond', 10).as('plus10micros'), + timestampAdd('timestamp', 'millisecond', 10).as('plus10millis'), + timestampSub('timestamp', 'day', 10).as('minus10days'), + timestampSub('timestamp', 'hour', 10).as('minus10hours'), + timestampSub('timestamp', 'minute', 10).as('minus10minutes'), + timestampSub('timestamp', 'second', 10).as('minus10seconds'), + timestampSub('timestamp', 'microsecond', 10).as('minus10micros'), + timestampSub('timestamp', 'millisecond', 10).as('minus10millis') + ) + .execute(); + expectResults(snapshot, { + plus10days: new Timestamp(1742244235, 0), + plus10hours: new Timestamp(1741416235, 0), + plus10minutes: new Timestamp(1741380835, 0), + plus10seconds: new Timestamp(1741380245, 0), + plus10micros: new Timestamp(1741380235, 10000), + plus10millis: new Timestamp(1741380235, 10000000), + minus10days: new Timestamp(1740516235, 0), + minus10hours: new Timestamp(1741344235, 0), + minus10minutes: new Timestamp(1741379635, 0), + minus10seconds: new Timestamp(1741380225, 0), + minus10micros: new Timestamp(1741380234, 999990000), + minus10millis: new Timestamp(1741380234, 990000000), + }); + }); - it('run pipeline with sample limit of {percentage: 0.6}', async () => { - const results = await randomCol - .pipeline() - .sample({percentage: 0.6}) - .execute(); - expect(results.length).to.equal(6); + it('supports byteLength', async () => { + const snapshot = await firestore + .pipeline() + .collection(randomCol) + .limit(1) + .select(constant(new Uint8Array([1, 2, 3, 4, 5, 6, 7, 0])).as('bytes')) + .select(byteLength('bytes').as('byteLength')) + .execute(); + + expectResults(snapshot, { + byteLength: 8, + }); + }); + + it('supports not', async () => { + const snapshot = await firestore + .pipeline() + .collection(randomCol) + .limit(1) + .select(constant(true).as('trueField')) + .select('trueField', not(eq('trueField', true)).as('falseField')) + .execute(); + + expectResults(snapshot, { + trueField: true, + falseField: false, + }); + }); }); - it('run pipeline with union', async () => { - const results = await randomCol - .pipeline() - .union(randomCol.pipeline()) - .sort(Field.of(FieldPath.documentId()).ascending()) - .execute(); - expectResults( - results, - 'book01', - 'book01', - 'book02', - 'book02', - 'book03', - 'book03', - 'book04', - 'book04', - 'book05', - 'book05', - 'book06', - 'book06', - 'book07', - 'book07', - 'book08', - 'book08', - 'book09', - 'book09', - 'book10', - 'book10' + describe('not yet implemented in backend', () => { + itIf(testUnsupportedFeatures)('supports Bit_and', async () => { + const snapshot = await firestore + .pipeline() + .collection(randomCol.path) + .limit(1) + .select(bitAnd(constant(5), 12).as('result')) + .execute(); + expectResults(snapshot, { + result: 4, + }); + }); + + itIf(testUnsupportedFeatures)('supports Bit_and', async () => { + const snapshot = await firestore + .pipeline() + .collection(randomCol.path) + .limit(1) + .select(constant(5).bitAnd(12).as('result')) + .execute(); + expectResults(snapshot, { + result: 4, + }); + }); + + itIf(testUnsupportedFeatures)('supports Bit_or', async () => { + let snapshot = await firestore + .pipeline() + .collection(randomCol.path) + .limit(1) + .select(bitOr(constant(5), 12).as('result')) + .execute(); + expectResults(snapshot, { + result: 13, + }); + snapshot = await firestore + .pipeline() + .collection(randomCol.path) + .limit(1) + .select(constant(5).bitOr(12).as('result')) + .execute(); + expectResults(snapshot, { + result: 13, + }); + }); + + itIf(testUnsupportedFeatures)('supports Bit_xor', async () => { + let snapshot = await firestore + .pipeline() + .collection(randomCol.path) + .limit(1) + .select(bitXor(constant(5), 12).as('result')) + .execute(); + expectResults(snapshot, { + result: 9, + }); + snapshot = await firestore + .pipeline() + .collection(randomCol.path) + .limit(1) + .select(constant(5).bitXor(12).as('result')) + .execute(); + expectResults(snapshot, { + result: 9, + }); + }); + + itIf(testUnsupportedFeatures)('supports Bit_not', async () => { + let snapshot = await firestore + .pipeline() + .collection(randomCol.path) + .limit(1) + .select(bitNot(constant(Uint8Array.of(0xfd))).as('result')) + .execute(); + expectResults(snapshot, { + result: Uint8Array.of(0x02), + }); + snapshot = await firestore + .pipeline() + .collection(randomCol.path) + .limit(1) + .select(constant(Uint8Array.of(0xfd)).bitNot().as('result')) + .execute(); + expectResults(snapshot, { + result: Uint8Array.of(0x02), + }); + }); + + itIf(testUnsupportedFeatures)('supports Bit_left_shift', async () => { + let snapshot = await firestore + .pipeline() + .collection(randomCol.path) + .limit(1) + .select(bitLeftShift(constant(Uint8Array.of(0x02)), 2).as('result')) + .execute(); + expectResults(snapshot, { + result: Uint8Array.of(0x04), + }); + snapshot = await firestore + .pipeline() + .collection(randomCol.path) + .limit(1) + .select(constant(Uint8Array.of(0x02)).bitLeftShift(2).as('result')) + .execute(); + expectResults(snapshot, { + result: Uint8Array.of(0x04), + }); + }); + + itIf(testUnsupportedFeatures)('supports Bit_right_shift', async () => { + let snapshot = await firestore + .pipeline() + .collection(randomCol.path) + .limit(1) + .select(bitRightShift(constant(Uint8Array.of(0x02)), 2).as('result')) + .execute(); + expectResults(snapshot, { + result: Uint8Array.of(0x01), + }); + snapshot = await firestore + .pipeline() + .collection(randomCol.path) + .limit(1) + .select(constant(Uint8Array.of(0x02)).bitRightShift(2).as('result')) + .execute(); + expectResults(snapshot, { + result: Uint8Array.of(0x01), + }); + }); + + itIf(testUnsupportedFeatures)('supports Document_id', async () => { + let snapshot = await firestore + .pipeline() + .collection(randomCol.path) + .sort(field('rating').descending()) + .limit(1) + .select(documentId(field('__path__')).as('docId')) + .execute(); + expectResults(snapshot, { + docId: 'book4', + }); + snapshot = await firestore + .pipeline() + .collection(randomCol.path) + .sort(field('rating').descending()) + .limit(1) + .select(field('__path__').documentId().as('docId')) + .execute(); + expectResults(snapshot, { + docId: 'book4', + }); + }); + + itIf(testUnsupportedFeatures)('supports Substr', async () => { + let snapshot = await firestore + .pipeline() + .collection(randomCol.path) + .sort(field('rating').descending()) + .limit(1) + .select(substr('title', 9, 2).as('of')) + .execute(); + expectResults(snapshot, { + of: 'of', + }); + snapshot = await firestore + .pipeline() + .collection(randomCol.path) + .sort(field('rating').descending()) + .limit(1) + .select(field('title').substr(9, 2).as('of')) + .execute(); + expectResults(snapshot, { + of: 'of', + }); + }); + + itIf(testUnsupportedFeatures)( + 'supports Substr without length', + async () => { + let snapshot = await firestore + .pipeline() + .collection(randomCol.path) + .sort(field('rating').descending()) + .limit(1) + .select(substr('title', 9).as('of')) + .execute(); + expectResults(snapshot, { + of: 'of the Rings', + }); + snapshot = await firestore + .pipeline() + .collection(randomCol.path) + .sort(field('rating').descending()) + .limit(1) + .select(field('title').substr(9).as('of')) + .execute(); + expectResults(snapshot, { + of: 'of the Rings', + }); + } ); + + itIf(testUnsupportedFeatures)('arrayConcat works', async () => { + const snapshot = await firestore + .pipeline() + .collection(randomCol.path) + .select( + arrayConcat('tags', ['newTag1', 'newTag2'], field('tags'), [null]).as( + 'modifiedTags' + ) + ) + .limit(1) + .execute(); + expectResults(snapshot, { + modifiedTags: [ + 'comedy', + 'space', + 'adventure', + 'newTag1', + 'newTag2', + 'comedy', + 'space', + 'adventure', + null, + ], + }); + }); + + itIf(testUnsupportedFeatures)('testToLowercase', async () => { + const snapshot = await firestore + .pipeline() + .collection(randomCol.path) + .select(toLower('title').as('lowercaseTitle')) + .limit(1) + .execute(); + expectResults(snapshot, { + lowercaseTitle: "the hitchhiker's guide to the galaxy", + }); + }); + + itIf(testUnsupportedFeatures)('testToUppercase', async () => { + const snapshot = await firestore + .pipeline() + .collection(randomCol.path) + .select(toUpper('author').as('uppercaseAuthor')) + .limit(1) + .execute(); + expectResults(snapshot, {uppercaseAuthor: 'DOUGLAS ADAMS'}); + }); + + itIf(testUnsupportedFeatures)('testTrim', async () => { + const snapshot = await firestore + .pipeline() + .collection(randomCol.path) + .addFields( + constant(" The Hitchhiker's Guide to the Galaxy ").as('spacedTitle') + ) + .select(trim('spacedTitle').as('trimmedTitle'), field('spacedTitle')) + .limit(1) + .execute(); + expectResults(snapshot, { + spacedTitle: " The Hitchhiker's Guide to the Galaxy ", + trimmedTitle: "The Hitchhiker's Guide to the Galaxy", + }); + }); + + itIf(testUnsupportedFeatures)('test reverse', async () => { + const snapshot = await firestore + .pipeline() + .collection(randomCol.path) + .where(eq('title', '1984')) + .limit(1) + .select(reverse('title').as('reverseTitle')) + .execute(); + expectResults(snapshot, {title: '4891'}); + }); }); - it('run pipeline with unnest', async () => { - const results = await randomCol - .pipeline() - .where(eq('title', "The Hitchhiker's Guide to the Galaxy")) - .unnest('tags', 'tag') - .execute(); - expectResults( - results, - { - title: "The Hitchhiker's Guide to the Galaxy", - author: 'Douglas Adams', - genre: 'Science Fiction', - published: 1979, - rating: 4.2, - tags: ['comedy', 'space', 'adventure'], - tag: 'comedy', - awards: {hugo: true, nebula: false, others: {unknown: {year: 1980}}}, - nestedField: {'level.1': {'level.2': true}}, - }, - { - title: "The Hitchhiker's Guide to the Galaxy", - author: 'Douglas Adams', - genre: 'Science Fiction', - published: 1979, - rating: 4.2, - tags: ['comedy', 'space', 'adventure'], - tag: 'space', - awards: {hugo: true, nebula: false, others: {unknown: {year: 1980}}}, - nestedField: {'level.1': {'level.2': true}}, - }, - { - title: "The Hitchhiker's Guide to the Galaxy", - author: 'Douglas Adams', + describe('pagination', () => { + /** + * Adds several books to the test collection. These + * additional books support pagination test scenarios + * that would otherwise not be possible with the original + * set of books. + * @param collectionReference + */ + async function addBooks( + collectionReference: CollectionReference + ): Promise { + await collectionReference.doc('book11').set({ + title: 'Jonathan Strange & Mr Norrell', + author: 'Susanna Clarke', + genre: 'Fantasy', + published: 2004, + rating: 4.6, + tags: ['historical fantasy', 'magic', 'alternate history', 'england'], + awards: {hugo: false, nebula: false}, + }); + await collectionReference.doc('book12').set({ + title: 'The Master and Margarita', + author: 'Mikhail Bulgakov', + genre: 'Satire', + published: 1967, // Though written much earlier + rating: 4.6, + tags: [ + 'russian literature', + 'supernatural', + 'philosophy', + 'dark comedy', + ], + awards: {}, + }); + await collectionReference.doc('book13').set({ + title: 'A Long Way to a Small, Angry Planet', + author: 'Becky Chambers', genre: 'Science Fiction', - published: 1979, - rating: 4.2, - tags: ['comedy', 'space', 'adventure'], - tag: 'adventure', - awards: {hugo: true, nebula: false, others: {unknown: {year: 1980}}}, - nestedField: {'level.1': {'level.2': true}}, + published: 2014, + rating: 4.6, + tags: ['space opera', 'found family', 'character-driven', 'optimistic'], + awards: {hugo: false, nebula: false, kitschies: true}, + }); + } + + // sort on __name__ is not working, see b/409358591 + itIf(testUnsupportedFeatures)( + 'supports pagination with filters', + async () => { + await addBooks(randomCol); + const pageSize = 2; + const pipeline = firestore + .pipeline() + .collection(randomCol.path) + .select('title', 'rating', '__name__') + .sort(field('rating').descending(), field('__name__').ascending()); + + let snapshot = await pipeline.limit(pageSize).execute(); + expectResults( + snapshot, + {title: 'The Lord of the Rings', rating: 4.7}, + {title: 'Jonathan Strange & Mr Norrell', rating: 4.6} + ); + + const lastDoc = snapshot.results[snapshot.results.length - 1]; + + snapshot = await pipeline + .where( + or( + and( + field('rating').eq(lastDoc.get('rating')), + field('__path__').gt(lastDoc.ref?.id) + ), + field('rating').lt(lastDoc.get('rating')) + ) + ) + .limit(pageSize) + .execute(); + expectResults( + snapshot, + {title: 'Pride and Prejudice', rating: 4.5}, + {title: 'Crime and Punishment', rating: 4.3} + ); + } + ); + + // sort on __name__ is not working, see b/409358591 + itIf(testUnsupportedFeatures)( + 'supports pagination with offsets', + async () => { + await addBooks(randomCol); + + const secondFilterField = '__path__'; + + const pipeline = firestore + .pipeline() + .collection(randomCol.path) + .select('title', 'rating', secondFilterField) + .sort( + field('rating').descending(), + field(secondFilterField).ascending() + ); + + const pageSize = 2; + let currPage = 0; + + let snapshot = await pipeline + .offset(currPage++ * pageSize) + .limit(pageSize) + .execute(); + + expectResults( + snapshot, + { + title: 'The Lord of the Rings', + rating: 4.7, + }, + {title: 'Dune', rating: 4.6} + ); + + snapshot = await pipeline + .offset(currPage++ * pageSize) + .limit(pageSize) + .execute(); + expectResults( + snapshot, + { + title: 'Jonathan Strange & Mr Norrell', + rating: 4.6, + }, + {title: 'The Master and Margarita', rating: 4.6} + ); + + snapshot = await pipeline + .offset(currPage++ * pageSize) + .limit(pageSize) + .execute(); + expectResults( + snapshot, + { + title: 'A Long Way to a Small, Angry Planet', + rating: 4.6, + }, + { + title: 'Pride and Prejudice', + rating: 4.5, + } + ); } ); }); diff --git a/dev/system-test/query.ts b/dev/system-test/query.ts index e7d800382..0a983756a 100644 --- a/dev/system-test/query.ts +++ b/dev/system-test/query.ts @@ -118,7 +118,7 @@ describe('Query class', () => { const pipeline = query.pipeline(); const pipelineResults = await pipeline.execute(); - expect(pipelineResults.map(r => r._fieldsProto)).to.deep.equal( + expect(pipelineResults.results.map(r => r._fieldsProto)).to.deep.equal( queryResults.docs.map(s => s._fieldsProto) ); return queryResults; @@ -131,7 +131,7 @@ describe('Query class', () => { const pipeline = query.toPipeline(); const pipelineResults = await pipeline.execute(); - expect(pipelineResults.map(r => r._fieldsProto)).to.deep.equal( + expect(pipelineResults.results.map(r => r._fieldsProto)).to.deep.equal( queryResults.docs.map(s => s._fieldsProto) ); return queryResults; diff --git a/dev/test/util/helpers.ts b/dev/test/util/helpers.ts index b16ebf0fe..45c7d3014 100644 --- a/dev/test/util/helpers.ts +++ b/dev/test/util/helpers.ts @@ -467,3 +467,10 @@ export function isPreferRest(): boolean { process.env.FIRESTORE_PREFER_REST === 'true' ); } + +export function itIf( + condition: boolean | 'only' +): Mocha.TestFunction | Mocha.PendingTestFunction { + // eslint-disable-next-line no-restricted-properties + return condition === 'only' ? it.only : condition ? it : it.skip; +} diff --git a/types/firestore.d.ts b/types/firestore.d.ts index d557a2506..74162a873 100644 --- a/types/firestore.d.ts +++ b/types/firestore.d.ts @@ -381,10 +381,6 @@ declare namespace FirebaseFirestore { fromFirestore(snapshot: QueryDocumentSnapshot): AppModelType; } - export interface FirestorePipelineConverter { - fromFirestore(result: PipelineResult): AppModelType; - } - /** * Settings used to directly configure a `Firestore` instance. */ @@ -866,9 +862,7 @@ declare namespace FirebaseFirestore { * * @return A Promise representing the asynchronous pipeline execution. */ - execute( - pipeline: Pipeline - ): Promise>>; + execute(pipeline: Pipeline): Promise; /** * Create the document referred to by the provided `DocumentReference`. @@ -1615,9 +1609,8 @@ declare namespace FirebaseFirestore { NewAppModelType, NewDbModelType extends DocumentData = DocumentData, >( - converter: FirestoreDataConverter + converter: FirestoreDataConverter | null ): DocumentReference; - withConverter(converter: null): DocumentReference; } /** @@ -2219,9 +2212,8 @@ declare namespace FirebaseFirestore { NewAppModelType, NewDbModelType extends DocumentData = DocumentData, >( - converter: FirestoreDataConverter + converter: FirestoreDataConverter | null ): Query; - withConverter(converter: null): Query; } /** @@ -2488,9 +2480,8 @@ declare namespace FirebaseFirestore { NewAppModelType, NewDbModelType extends DocumentData = DocumentData, >( - converter: FirestoreDataConverter + converter: FirestoreDataConverter | null ): CollectionReference; - withConverter(converter: null): CollectionReference; } /** @@ -2567,9 +2558,8 @@ declare namespace FirebaseFirestore { NewAppModelType, NewDbModelType extends DocumentData = DocumentData, >( - converter: FirestoreDataConverter + converter: FirestoreDataConverter | null ): CollectionGroup; - withConverter(converter: null): CollectionGroup; } /** @@ -3328,54 +3318,6 @@ declare namespace FirebaseFirestore { readonly snapshot: T | null; } - /** - * @beta - * - * An interface that represents a selectable expression. - */ - export interface Selectable { - selectable: true; - } - - /** - * @beta - * - * An interface that represents a filter condition. - */ - export interface FilterCondition { - filterable: true; - } - - /** - * @beta - * - * An interface that represents an accumulator. - */ - export interface Accumulator { - accumulator: true; - } - - /** - * @beta - * - * An accumulator target, which is an expression with an alias that also implements the Accumulator interface. - */ - export type AccumulatorTarget = ExprWithAlias; - - /** - * @beta - * - * A filter expression, which is an expression that also implements the FilterCondition interface. - */ - export type FilterExpr = Expr & FilterCondition; - - /** - * @beta - * - * A selectable expression, which is an expression that also implements the Selectable interface. - */ - export type SelectableExpr = Expr & Selectable; - /** * @beta * @@ -3385,6 +3327,7 @@ declare namespace FirebaseFirestore { | 'Field' | 'Constant' | 'Function' + | 'AggregateFunction' | 'ListOfExprs' | 'ExprWithAlias'; @@ -3400,361 +3343,200 @@ declare namespace FirebaseFirestore { * - **Field references:** Access values from document fields. * - **Literals:** Represent constant values (strings, numbers, booleans). * - **Function calls:** Apply functions to one or more expressions. - * - **Aggregations:** Calculate aggregate values (e.g., sum, average) over a set of documents. * * The `Expr` class provides a fluent API for building expressions. You can chain together * method calls to create complex expressions. */ export abstract class Expr { + abstract readonly exprType: ExprType; + /** * Creates an expression that adds this expression to another expression. * * ```typescript * // Add the value of the 'quantity' field and the 'reserve' field. - * Field.of("quantity").add(Field.of("reserve")); - * ``` - * - * @param other The expression to add to this expression. - * @return A new `Expr` representing the addition operation. - */ - add(other: Expr): Add; - - /** - * Creates an expression that adds this expression to a constant value. - * - * ```typescript - * // Add 5 to the value of the 'age' field - * Field.of("age").add(5); + * field("quantity").add(field("reserve")); * ``` * - * @param other The constant value to add. + * @param second The expression or literal to add to this expression. + * @param others Optional additional expressions or literals to add to this expression. * @return A new `Expr` representing the addition operation. */ - add(other: any): Add; + add(second: Expr | unknown, ...others: Array): FunctionExpr; /** * Creates an expression that subtracts another expression from this expression. * * ```typescript * // Subtract the 'discount' field from the 'price' field - * Field.of("price").subtract(Field.of("discount")); + * field("price").subtract(field("discount")); * ``` * * @param other The expression to subtract from this expression. * @return A new `Expr` representing the subtraction operation. */ - subtract(other: Expr): Subtract; + subtract(other: Expr): FunctionExpr; /** * Creates an expression that subtracts a constant value from this expression. * * ```typescript * // Subtract 20 from the value of the 'total' field - * Field.of("total").subtract(20); + * field("total").subtract(20); * ``` * * @param other The constant value to subtract. * @return A new `Expr` representing the subtraction operation. */ - subtract(other: any): Subtract; + subtract(other: number): FunctionExpr; /** * Creates an expression that multiplies this expression by another expression. * * ```typescript * // Multiply the 'quantity' field by the 'price' field - * Field.of("quantity").multiply(Field.of("price")); - * ``` - * - * @param other The expression to multiply by. - * @return A new `Expr` representing the multiplication operation. - */ - multiply(other: Expr): Multiply; - - /** - * Creates an expression that multiplies this expression by a constant value. - * - * ```typescript - * // Multiply the 'value' field by 2 - * Field.of("value").multiply(2); + * field("quantity").multiply(field("price")); * ``` * - * @param other The constant value to multiply by. + * @param second The second expression or literal to multiply by. + * @param others Optional additional expressions or literals to multiply by. * @return A new `Expr` representing the multiplication operation. */ - multiply(other: any): Multiply; + multiply( + second: Expr | number, + ...others: Array + ): FunctionExpr; /** * Creates an expression that divides this expression by another expression. * * ```typescript * // Divide the 'total' field by the 'count' field - * Field.of("total").divide(Field.of("count")); + * field("total").divide(field("count")); * ``` * * @param other The expression to divide by. * @return A new `Expr` representing the division operation. */ - divide(other: Expr): Divide; + divide(other: Expr): FunctionExpr; /** * Creates an expression that divides this expression by a constant value. * * ```typescript * // Divide the 'value' field by 10 - * Field.of("value").divide(10); + * field("value").divide(10); * ``` * * @param other The constant value to divide by. * @return A new `Expr` representing the division operation. */ - divide(other: any): Divide; + divide(other: number): FunctionExpr; + divide(other: number | Expr): FunctionExpr; /** * Creates an expression that calculates the modulo (remainder) of dividing this expression by another expression. * * ```typescript * // Calculate the remainder of dividing the 'value' field by the 'divisor' field - * Field.of("value").mod(Field.of("divisor")); + * field("value").mod(field("divisor")); * ``` * - * @param other The expression to divide by. + * @param expression The expression to divide by. * @return A new `Expr` representing the modulo operation. */ - mod(other: Expr): Mod; + mod(expression: Expr): FunctionExpr; /** * Creates an expression that calculates the modulo (remainder) of dividing this expression by a constant value. * * ```typescript * // Calculate the remainder of dividing the 'value' field by 10 - * Field.of("value").mod(10); + * field("value").mod(10); * ``` * - * @param other The constant value to divide by. + * @param value The constant value to divide by. * @return A new `Expr` representing the modulo operation. */ - mod(other: any): Mod; - - // /** - // * Creates an expression that applies a bitwise AND operation between this expression and another expression. - // * - // * ```typescript - // * // Calculate the bitwise AND of 'field1' and 'field2'. - // * Field.of("field1").bitAnd(Field.of("field2")); - // * ``` - // * - // * @param other The right operand expression. - // * @return A new {@code Expr} representing the bitwise AND operation. - // */ - // bitAnd(other: Expr): BitAnd; - // - // /** - // * Creates an expression that applies a bitwise AND operation between this expression and a constant value. - // * - // * ```typescript - // * // Calculate the bitwise AND of 'field1' and 0xFF. - // * Field.of("field1").bitAnd(0xFF); - // * ``` - // * - // * @param other The right operand constant. - // * @return A new {@code Expr} representing the bitwise AND operation. - // */ - // bitAnd(other: any): BitAnd; - // - // /** - // * Creates an expression that applies a bitwise OR operation between this expression and another expression. - // * - // * ```typescript - // * // Calculate the bitwise OR of 'field1' and 'field2'. - // * Field.of("field1").bitOr(Field.of("field2")); - // * ``` - // * - // * @param other The right operand expression. - // * @return A new {@code Expr} representing the bitwise OR operation. - // */ - // bitOr(other: Expr): BitOr; - // - // /** - // * Creates an expression that applies a bitwise OR operation between this expression and a constant value. - // * - // * ```typescript - // * // Calculate the bitwise OR of 'field1' and 0xFF. - // * Field.of("field1").bitOr(0xFF); - // * ``` - // * - // * @param other The right operand constant. - // * @return A new {@code Expr} representing the bitwise OR operation. - // */ - // bitOr(other: any): BitOr; - // - // /** - // * Creates an expression that applies a bitwise XOR operation between this expression and another expression. - // * - // * ```typescript - // * // Calculate the bitwise XOR of 'field1' and 'field2'. - // * Field.of("field1").bitXor(Field.of("field2")); - // * ``` - // * - // * @param other The right operand expression. - // * @return A new {@code Expr} representing the bitwise XOR operation. - // */ - // bitXor(other: Expr): BitXor; - // - // /** - // * Creates an expression that applies a bitwise XOR operation between this expression and a constant value. - // * - // * ```typescript - // * // Calculate the bitwise XOR of 'field1' and 0xFF. - // * Field.of("field1").bitXor(0xFF); - // * ``` - // * - // * @param other The right operand constant. - // * @return A new {@code Expr} representing the bitwise XOR operation. - // */ - // bitXor(other: any): BitXor; - // - // /** - // * Creates an expression that applies a bitwise NOT operation to this expression. - // * - // * ```typescript - // * // Calculate the bitwise NOT of 'field1'. - // * Field.of("field1").bitNot(); - // * ``` - // * - // * @return A new {@code Expr} representing the bitwise NOT operation. - // */ - // bitNot(): BitNot; - // - // /** - // * Creates an expression that applies a bitwise left shift operation between this expression and another expression. - // * - // * ```typescript - // * // Calculate the bitwise left shift of 'field1' by 'field2' bits. - // * Field.of("field1").bitLeftShift(Field.of("field2")); - // * ``` - // * - // * @param other The right operand expression representing the number of bits to shift. - // * @return A new {@code Expr} representing the bitwise left shift operation. - // */ - // bitLeftShift(other: Expr): BitLeftShift; - // - // /** - // * Creates an expression that applies a bitwise left shift operation between this expression and a constant value. - // * - // * ```typescript - // * // Calculate the bitwise left shift of 'field1' by 2 bits. - // * Field.of("field1").bitLeftShift(2); - // * ``` - // * - // * @param other The right operand constant representing the number of bits to shift. - // * @return A new {@code Expr} representing the bitwise left shift operation. - // */ - // bitLeftShift(other: number): BitLeftShift; - // - // /** - // * Creates an expression that applies a bitwise right shift operation between this expression and another expression. - // * - // * ```typescript - // * // Calculate the bitwise right shift of 'field1' by 'field2' bits. - // * Field.of("field1").bitRightShift(Field.of("field2")); - // * ``` - // * - // * @param other The right operand expression representing the number of bits to shift. - // * @return A new {@code Expr} representing the bitwise right shift operation. - // */ - // bitRightShift(other: Expr): BitRightShift; - // - // /** - // * Creates an expression that applies a bitwise right shift operation between this expression and a constant value. - // * - // * ```typescript - // * // Calculate the bitwise right shift of 'field1' by 2 bits. - // * Field.of("field1").bitRightShift(2); - // * ``` - // * - // * @param other The right operand constant representing the number of bits to shift. - // * @return A new {@code Expr} representing the bitwise right shift operation. - // */ - // bitRightShift(other: number): BitRightShift; + mod(value: number): FunctionExpr; /** * Creates an expression that checks if this expression is equal to another expression. * * ```typescript * // Check if the 'age' field is equal to 21 - * Field.of("age").eq(21); + * field("age").eq(21); * ``` * - * @param other The expression to compare for equality. + * @param expression The expression to compare for equality. * @return A new `Expr` representing the equality comparison. */ - eq(other: Expr): Eq; + eq(expression: Expr): BooleanExpr; /** * Creates an expression that checks if this expression is equal to a constant value. * * ```typescript * // Check if the 'city' field is equal to "London" - * Field.of("city").eq("London"); + * field("city").eq("London"); * ``` * - * @param other The constant value to compare for equality. + * @param value The constant value to compare for equality. * @return A new `Expr` representing the equality comparison. */ - eq(other: any): Eq; + eq(value: unknown): BooleanExpr; /** * Creates an expression that checks if this expression is not equal to another expression. * * ```typescript * // Check if the 'status' field is not equal to "completed" - * Field.of("status").neq("completed"); + * field("status").neq("completed"); * ``` * - * @param other The expression to compare for inequality. + * @param expression The expression to compare for inequality. * @return A new `Expr` representing the inequality comparison. */ - neq(other: Expr): Neq; + neq(expression: Expr): BooleanExpr; /** * Creates an expression that checks if this expression is not equal to a constant value. * * ```typescript * // Check if the 'country' field is not equal to "USA" - * Field.of("country").neq("USA"); + * field("country").neq("USA"); * ``` * - * @param other The constant value to compare for inequality. + * @param value The constant value to compare for inequality. * @return A new `Expr` representing the inequality comparison. */ - neq(other: any): Neq; + neq(value: unknown): BooleanExpr; /** * Creates an expression that checks if this expression is less than another expression. * * ```typescript * // Check if the 'age' field is less than 'limit' - * Field.of("age").lt(Field.of('limit')); + * field("age").lt(field('limit')); * ``` * - * @param other The expression to compare for less than. + * @param experession The expression to compare for less than. * @return A new `Expr` representing the less than comparison. */ - lt(other: Expr): Lt; + lt(experession: Expr): BooleanExpr; /** * Creates an expression that checks if this expression is less than a constant value. * * ```typescript * // Check if the 'price' field is less than 50 - * Field.of("price").lt(50); + * field("price").lt(50); * ``` * - * @param other The constant value to compare for less than. + * @param value The constant value to compare for less than. * @return A new `Expr` representing the less than comparison. */ - lt(other: any): Lt; + lt(value: unknown): BooleanExpr; /** * Creates an expression that checks if this expression is less than or equal to another @@ -3762,52 +3544,52 @@ declare namespace FirebaseFirestore { * * ```typescript * // Check if the 'quantity' field is less than or equal to 20 - * Field.of("quantity").lte(Constant.of(20)); + * field("quantity").lte(constant(20)); * ``` * - * @param other The expression to compare for less than or equal to. + * @param expression The expression to compare for less than or equal to. * @return A new `Expr` representing the less than or equal to comparison. */ - lte(other: Expr): Lte; + lte(expression: Expr): BooleanExpr; /** * Creates an expression that checks if this expression is less than or equal to a constant value. * * ```typescript * // Check if the 'score' field is less than or equal to 70 - * Field.of("score").lte(70); + * field("score").lte(70); * ``` * - * @param other The constant value to compare for less than or equal to. + * @param value The constant value to compare for less than or equal to. * @return A new `Expr` representing the less than or equal to comparison. */ - lte(other: any): Lte; + lte(value: unknown): BooleanExpr; /** * Creates an expression that checks if this expression is greater than another expression. * * ```typescript * // Check if the 'age' field is greater than the 'limit' field - * Field.of("age").gt(Field.of("limit")); + * field("age").gt(field("limit")); * ``` * - * @param other The expression to compare for greater than. + * @param expression The expression to compare for greater than. * @return A new `Expr` representing the greater than comparison. */ - gt(other: Expr): Gt; + gt(expression: Expr): BooleanExpr; /** * Creates an expression that checks if this expression is greater than a constant value. * * ```typescript * // Check if the 'price' field is greater than 100 - * Field.of("price").gt(100); + * field("price").gt(100); * ``` * - * @param other The constant value to compare for greater than. + * @param value The constant value to compare for greater than. * @return A new `Expr` representing the greater than comparison. */ - gt(other: any): Gt; + gt(value: unknown): BooleanExpr; /** * Creates an expression that checks if this expression is greater than or equal to another @@ -3815,13 +3597,13 @@ declare namespace FirebaseFirestore { * * ```typescript * // Check if the 'quantity' field is greater than or equal to field 'requirement' plus 1 - * Field.of("quantity").gte(Field.of('requirement').add(1)); + * field("quantity").gte(field('requirement').add(1)); * ``` * - * @param other The expression to compare for greater than or equal to. + * @param expression The expression to compare for greater than or equal to. * @return A new `Expr` representing the greater than or equal to comparison. */ - gte(other: Expr): Gte; + gte(expression: Expr): BooleanExpr; /** * Creates an expression that checks if this expression is greater than or equal to a constant @@ -3829,104 +3611,94 @@ declare namespace FirebaseFirestore { * * ```typescript * // Check if the 'score' field is greater than or equal to 80 - * Field.of("score").gte(80); + * field("score").gte(80); * ``` * - * @param other The constant value to compare for greater than or equal to. + * @param value The constant value to compare for greater than or equal to. * @return A new `Expr` representing the greater than or equal to comparison. */ - gte(other: any): Gte; + gte(value: unknown): BooleanExpr; /** * Creates an expression that concatenates an array expression with one or more other arrays. * * ```typescript * // Combine the 'items' array with another array field. - * Field.of("items").arrayConcat(Field.of("otherItems")); - * ``` - * - * @param arrays The array expressions to concatenate. - * @return A new `Expr` representing the concatenated array. - */ - arrayConcat(arrays: Expr[]): ArrayConcat; - - /** - * Creates an expression that concatenates an array expression with one or more other arrays. - * - * ```typescript - * // Combine the 'tags' array with a new array and an array field - * Field.of("tags").arrayConcat(Arrays.asList("newTag1", "newTag2"), Field.of("otherTag")); + * field("items").arrayConcat(field("otherItems")); * ``` - * - * @param arrays The array expressions or values to concatenate. + * @param secondArray Second array expression or array literal to concatenate. + * @param otherArrays Optional additional array expressions or array literals to concatenate. * @return A new `Expr` representing the concatenated array. */ - arrayConcat(arrays: any[]): ArrayConcat; + arrayConcat( + secondArray: Expr | unknown[], + ...otherArrays: Array + ): FunctionExpr; /** * Creates an expression that checks if an array contains a specific element. * * ```typescript * // Check if the 'sizes' array contains the value from the 'selectedSize' field - * Field.of("sizes").arrayContains(Field.of("selectedSize")); + * field("sizes").arrayContains(field("selectedSize")); * ``` * - * @param element The element to search for in the array. + * @param expression The element to search for in the array. * @return A new `Expr` representing the 'array_contains' comparison. */ - arrayContains(element: Expr): ArrayContains; + arrayContains(expression: Expr): BooleanExpr; /** * Creates an expression that checks if an array contains a specific value. * * ```typescript * // Check if the 'colors' array contains "red" - * Field.of("colors").arrayContains("red"); + * field("colors").arrayContains("red"); * ``` * - * @param element The element to search for in the array. + * @param value The element to search for in the array. * @return A new `Expr` representing the 'array_contains' comparison. */ - arrayContains(element: any): ArrayContains; + arrayContains(value: unknown): BooleanExpr; /** * Creates an expression that checks if an array contains all the specified elements. * * ```typescript - * // Check if the 'tags' array contains both "news" and "sports" - * Field.of("tags").arrayContainsAll(Field.of("tag1"), Field.of("tag2")); + * // Check if the 'tags' array contains both the value in field "tag1" and the literal value "tag2" + * field("tags").arrayContainsAll([field("tag1"), "tag2"]); * ``` * * @param values The elements to check for in the array. * @return A new `Expr` representing the 'array_contains_all' comparison. */ - arrayContainsAll(...values: Expr[]): ArrayContainsAll; + arrayContainsAll(values: Array): BooleanExpr; /** * Creates an expression that checks if an array contains all the specified elements. * * ```typescript - * // Check if the 'tags' array contains both of the values from field 'tag1' and "tag2" - * Field.of("tags").arrayContainsAll(Field.of("tag1"), Field.of("tag2")); + * // Check if the 'tags' array contains both of the values from field "tag1" and the literal value "tag2" + * field("tags").arrayContainsAll(array([field("tag1"), "tag2"])); * ``` * - * @param values The elements to check for in the array. + * @param arrayExpression The elements to check for in the array. * @return A new `Expr` representing the 'array_contains_all' comparison. */ - arrayContainsAll(...values: any[]): ArrayContainsAll; + arrayContainsAll(arrayExpression: Expr): BooleanExpr; /** * Creates an expression that checks if an array contains any of the specified elements. * * ```typescript * // Check if the 'categories' array contains either values from field "cate1" or "cate2" - * Field.of("categories").arrayContainsAny(Field.of("cate1"), Field.of("cate2")); + * field("categories").arrayContainsAny([field("cate1"), field("cate2")]); * ``` * * @param values The elements to check for in the array. * @return A new `Expr` representing the 'array_contains_any' comparison. */ - arrayContainsAny(...values: Expr[]): ArrayContainsAny; + arrayContainsAny(values: Array): BooleanExpr; /** * Creates an expression that checks if an array contains any of the specified elements. @@ -3934,25 +3706,25 @@ declare namespace FirebaseFirestore { * ```typescript * // Check if the 'groups' array contains either the value from the 'userGroup' field * // or the value "guest" - * Field.of("groups").arrayContainsAny(Field.of("userGroup"), "guest"); + * field("groups").arrayContainsAny(array([field("userGroup"), "guest"])); * ``` * - * @param values The elements to check for in the array. + * @param arrayExpression The elements to check for in the array. * @return A new `Expr` representing the 'array_contains_any' comparison. */ - arrayContainsAny(...values: any[]): ArrayContainsAny; + arrayContainsAny(arrayExpression: Expr): BooleanExpr; /** * Creates an expression that calculates the length of an array. * * ```typescript * // Get the number of items in the 'cart' array - * Field.of("cart").arrayLength(); + * field("cart").arrayLength(); * ``` * * @return A new `Expr` representing the length of the array. */ - arrayLength(): ArrayLength; + arrayLength(): FunctionExpr; /** * Creates an expression that checks if this expression is equal to any of the provided values or @@ -3960,13 +3732,13 @@ declare namespace FirebaseFirestore { * * ```typescript * // Check if the 'category' field is either "Electronics" or value of field 'primaryType' - * Field.of("category").in("Electronics", Field.of("primaryType")); + * field("category").eqAny("Electronics", field("primaryType")); * ``` * - * @param others The values or expressions to check against. + * @param values The values or expressions to check against. * @return A new `Expr` representing the 'IN' comparison. */ - eqAny(...others: Expr[]): EqAny; + eqAny(values: Array): BooleanExpr; /** * Creates an expression that checks if this expression is equal to any of the provided values or @@ -3974,75 +3746,114 @@ declare namespace FirebaseFirestore { * * ```typescript * // Check if the 'category' field is either "Electronics" or value of field 'primaryType' - * Field.of("category").in("Electronics", Field.of("primaryType")); + * field("category").eqAny(array(["Electronics", field("primaryType")])); * ``` * - * @param others The values or expressions to check against. + * @param arrayExpression An expression that evaluates to an array of values to check against. * @return A new `Expr` representing the 'IN' comparison. */ - eqAny(...others: any[]): EqAny; + eqAny(arrayExpression: Expr): BooleanExpr; + + /** + * Creates an expression that checks if this expression is not equal to any of the provided values or + * expressions. + * + * ```typescript + * // Check if the 'status' field is neither "pending" nor the value of 'rejectedStatus' + * field("status").notEqAny(["pending", field("rejectedStatus")]); + * ``` + * + * @param values The values or expressions to check against. + * @return A new `Expr` representing the 'NotEqAny' comparison. + */ + notEqAny(values: Array): BooleanExpr; + + /** + * Creates an expression that checks if this expression is not equal to any of the values in the evaluated expression. + * + * ```typescript + * // Check if the 'status' field is not equal to any value in the field 'rejectedStatuses' + * field("status").notEqAny(field('rejectedStatuses')); + * ``` + * + * @param arrayExpression The values or expressions to check against. + * @return A new `Expr` representing the 'NotEqAny' comparison. + */ + notEqAny(arrayExpression: Expr): BooleanExpr; /** * Creates an expression that checks if this expression evaluates to 'NaN' (Not a Number). * * ```typescript * // Check if the result of a calculation is NaN - * Field.of("value").divide(0).isNaN(); + * field("value").divide(0).isNaN(); * ``` * * @return A new `Expr` representing the 'isNaN' check. */ - isNaN(): IsNan; + isNan(): BooleanExpr; + + /** + * Creates an expression that checks if this expression evaluates to 'Null'. + * + * ```typescript + * // Check if the result of a calculation is NaN + * field("value").isNull(); + * ``` + * + * @return A new `Expr` representing the 'isNull' check. + */ + isNull(): BooleanExpr; /** * Creates an expression that checks if a field exists in the document. * * ```typescript * // Check if the document has a field named "phoneNumber" - * Field.of("phoneNumber").exists(); + * field("phoneNumber").exists(); * ``` * * @return A new `Expr` representing the 'exists' check. */ - exists(): Exists; + exists(): BooleanExpr; /** * Creates an expression that calculates the character length of a string in UTF-8. * * ```typescript - * // Get the character length of the 'name' field of UTF-8. - * Field.of("name").strLength(); + * // Get the character length of the 'name' field in its UTF-8 form. + * field("name").charLength(); * ``` * * @return A new `Expr` representing the length of the string. */ - charLength(): CharLength; + charLength(): FunctionExpr; /** * Creates an expression that performs a case-sensitive string comparison. * * ```typescript * // Check if the 'title' field contains the word "guide" (case-sensitive) - * Field.of("title").like("%guide%"); + * field("title").like("%guide%"); * ``` * * @param pattern The pattern to search for. You can use "%" as a wildcard character. * @return A new `Expr` representing the 'like' comparison. */ - like(pattern: string): Like; + like(pattern: string): FunctionExpr; /** * Creates an expression that performs a case-sensitive string comparison. * * ```typescript * // Check if the 'title' field contains the word "guide" (case-sensitive) - * Field.of("title").like("%guide%"); + * field("title").like("%guide%"); * ``` * * @param pattern The pattern to search for. You can use "%" as a wildcard character. * @return A new `Expr` representing the 'like' comparison. */ - like(pattern: Expr): Like; + like(pattern: Expr): FunctionExpr; /** * Creates an expression that checks if a string contains a specified regular expression as a @@ -4050,13 +3861,13 @@ declare namespace FirebaseFirestore { * * ```typescript * // Check if the 'description' field contains "example" (case-insensitive) - * Field.of("description").regexContains("(?i)example"); + * field("description").regexContains("(?i)example"); * ``` * * @param pattern The regular expression to use for the search. * @return A new `Expr` representing the 'contains' comparison. */ - regexContains(pattern: string): RegexContains; + regexContains(pattern: string): BooleanExpr; /** * Creates an expression that checks if a string contains a specified regular expression as a @@ -4064,78 +3875,78 @@ declare namespace FirebaseFirestore { * * ```typescript * // Check if the 'description' field contains the regular expression stored in field 'regex' - * Field.of("description").regexContains(Field.of("regex")); + * field("description").regexContains(field("regex")); * ``` * * @param pattern The regular expression to use for the search. * @return A new `Expr` representing the 'contains' comparison. */ - regexContains(pattern: Expr): RegexContains; + regexContains(pattern: Expr): BooleanExpr; /** * Creates an expression that checks if a string matches a specified regular expression. * * ```typescript * // Check if the 'email' field matches a valid email pattern - * Field.of("email").regexMatch("[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,}"); + * field("email").regexMatch("[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,}"); * ``` * * @param pattern The regular expression to use for the match. * @return A new `Expr` representing the regular expression match. */ - regexMatch(pattern: string): RegexMatch; + regexMatch(pattern: string): BooleanExpr; /** * Creates an expression that checks if a string matches a specified regular expression. * * ```typescript * // Check if the 'email' field matches a regular expression stored in field 'regex' - * Field.of("email").regexMatch(Field.of("regex")); + * field("email").regexMatch(field("regex")); * ``` * * @param pattern The regular expression to use for the match. * @return A new `Expr` representing the regular expression match. */ - regexMatch(pattern: Expr): RegexMatch; + regexMatch(pattern: Expr): BooleanExpr; /** - * Creates an expression that checks if this string expression contains a specified substring. + * Creates an expression that checks if a string contains a specified substring. * * ```typescript * // Check if the 'description' field contains "example". - * Field.of("description").strContains("example"); + * field("description").strContains("example"); * ``` * * @param substring The substring to search for. - * @return A new {@code Expr} representing the 'contains' comparison. + * @return A new `Expr` representing the 'contains' comparison. */ - strContains(substring: string): StrContains; + strContains(substring: string): BooleanExpr; /** - * Creates an expression that checks if this string expression contains the string represented by another expression. + * Creates an expression that checks if a string contains the string represented by another expression. * * ```typescript * // Check if the 'description' field contains the value of the 'keyword' field. - * Field.of("description").strContains(Field.of("keyword")); + * field("description").strContains(field("keyword")); * ``` * * @param expr The expression representing the substring to search for. - * @return A new {@code Expr} representing the 'contains' comparison. + * @return A new `Expr` representing the 'contains' comparison. */ - strContains(expr: Expr): StrContains; + strContains(expr: Expr): BooleanExpr; /** * Creates an expression that checks if a string starts with a given prefix. * * ```typescript * // Check if the 'name' field starts with "Mr." - * Field.of("name").startsWith("Mr."); + * field("name").startsWith("Mr."); * ``` * * @param prefix The prefix to check for. * @return A new `Expr` representing the 'starts with' comparison. */ - startsWith(prefix: string): StartsWith; + startsWith(prefix: string): BooleanExpr; /** * Creates an expression that checks if a string starts with a given prefix (represented as an @@ -4143,26 +3954,26 @@ declare namespace FirebaseFirestore { * * ```typescript * // Check if the 'fullName' field starts with the value of the 'firstName' field - * Field.of("fullName").startsWith(Field.of("firstName")); + * field("fullName").startsWith(field("firstName")); * ``` * * @param prefix The prefix expression to check for. * @return A new `Expr` representing the 'starts with' comparison. */ - startsWith(prefix: Expr): StartsWith; + startsWith(prefix: Expr): BooleanExpr; /** * Creates an expression that checks if a string ends with a given postfix. * * ```typescript * // Check if the 'filename' field ends with ".txt" - * Field.of("filename").endsWith(".txt"); + * field("filename").endsWith(".txt"); * ``` * * @param suffix The postfix to check for. * @return A new `Expr` representing the 'ends with' comparison. */ - endsWith(suffix: string): EndsWith; + endsWith(suffix: string): BooleanExpr; /** * Creates an expression that checks if a string ends with a given postfix (represented as an @@ -4170,88 +3981,92 @@ declare namespace FirebaseFirestore { * * ```typescript * // Check if the 'url' field ends with the value of the 'extension' field - * Field.of("url").endsWith(Field.of("extension")); + * field("url").endsWith(field("extension")); * ``` * * @param suffix The postfix expression to check for. * @return A new `Expr` representing the 'ends with' comparison. */ - endsWith(suffix: Expr): EndsWith; + endsWith(suffix: Expr): BooleanExpr; /** * Creates an expression that converts a string to lowercase. * * ```typescript * // Convert the 'name' field to lowercase - * Field.of("name").toLower(); + * field("name").toLower(); * ``` * * @return A new `Expr` representing the lowercase string. */ - toLower(): ToLower; + toLower(): FunctionExpr; /** * Creates an expression that converts a string to uppercase. * * ```typescript * // Convert the 'title' field to uppercase - * Field.of("title").toUpper(); + * field("title").toUpper(); * ``` * * @return A new `Expr` representing the uppercase string. */ - toUpper(): ToUpper; + toUpper(): FunctionExpr; /** * Creates an expression that removes leading and trailing whitespace from a string. * * ```typescript * // Trim whitespace from the 'userInput' field - * Field.of("userInput").trim(); + * field("userInput").trim(); * ``` * * @return A new `Expr` representing the trimmed string. */ - trim(): Trim; + trim(): FunctionExpr; /** * Creates an expression that concatenates string expressions together. * * ```typescript * // Combine the 'firstName', " ", and 'lastName' fields into a single string - * Field.of("firstName").strConcat(Constant.of(" "), Field.of("lastName")); + * field("firstName").strConcat(constant(" "), field("lastName")); * ``` * - * @param elements The expressions (typically strings) to concatenate. + * @param secondString The additional expression or string literal to concatenate. + * @param otherStrings Optional additional expressions or string literals to concatenate. * @return A new `Expr` representing the concatenated string. */ - strConcat(...elements: (string | Expr)[]): StrConcat; + strConcat( + secondString: Expr | string, + ...otherStrings: Array + ): FunctionExpr; /** * Creates an expression that reverses this string expression. * * ```typescript * // Reverse the value of the 'myString' field. - * Field.of("myString").reverse(); + * field("myString").reverse(); * ``` * * @return A new {@code Expr} representing the reversed string. */ - reverse(): Reverse; + reverse(): FunctionExpr; /** * Creates an expression that replaces the first occurrence of a substring within this string expression with another substring. * * ```typescript * // Replace the first occurrence of "hello" with "hi" in the 'message' field - * Field.of("message").replaceFirst("hello", "hi"); + * field("message").replaceFirst("hello", "hi"); * ``` * * @param find The substring to search for. * @param replace The substring to replace the first occurrence of 'find' with. * @return A new {@code Expr} representing the string with the first occurrence replaced. */ - replaceFirst(find: string, replace: string): ReplaceFirst; + replaceFirst(find: string, replace: string): FunctionExpr; /** * Creates an expression that replaces the first occurrence of a substring within this string expression with another substring, @@ -4259,28 +4074,28 @@ declare namespace FirebaseFirestore { * * ```typescript * // Replace the first occurrence of the value in 'findField' with the value in 'replaceField' in the 'message' field - * Field.of("message").replaceFirst(Field.of("findField"), Field.of("replaceField")); + * field("message").replaceFirst(field("findField"), field("replaceField")); * ``` * * @param find The expression representing the substring to search for. * @param replace The expression representing the substring to replace the first occurrence of 'find' with. * @return A new {@code Expr} representing the string with the first occurrence replaced. */ - replaceFirst(find: Expr, replace: Expr): ReplaceFirst; + replaceFirst(find: Expr, replace: Expr): FunctionExpr; /** * Creates an expression that replaces all occurrences of a substring within this string expression with another substring. * * ```typescript * // Replace all occurrences of "hello" with "hi" in the 'message' field - * Field.of("message").replaceAll("hello", "hi"); + * field("message").replaceAll("hello", "hi"); * ``` * * @param find The substring to search for. * @param replace The substring to replace all occurrences of 'find' with. * @return A new {@code Expr} representing the string with all occurrences replaced. */ - replaceAll(find: string, replace: string): ReplaceAll; + replaceAll(find: string, replace: string): FunctionExpr; /** * Creates an expression that replaces all occurrences of a substring within this string expression with another substring, @@ -4288,39 +4103,39 @@ declare namespace FirebaseFirestore { * * ```typescript * // Replace all occurrences of the value in 'findField' with the value in 'replaceField' in the 'message' field - * Field.of("message").replaceAll(Field.of("findField"), Field.of("replaceField")); + * field("message").replaceAll(field("findField"), field("replaceField")); * ``` * * @param find The expression representing the substring to search for. * @param replace The expression representing the substring to replace all occurrences of 'find' with. * @return A new {@code Expr} representing the string with all occurrences replaced. */ - replaceAll(find: Expr, replace: Expr): ReplaceAll; + replaceAll(find: Expr, replace: Expr): FunctionExpr; /** * Creates an expression that calculates the length of this string expression in bytes. * * ```typescript * // Calculate the length of the 'myString' field in bytes. - * Field.of("myString").byteLength(); + * field("myString").byteLength(); * ``` * * @return A new {@code Expr} representing the length of the string in bytes. */ - byteLength(): ByteLength; + byteLength(): FunctionExpr; /** * Accesses a value from a map (object) field using the provided key. * * ```typescript * // Get the 'city' value from the 'address' map field - * Field.of("address").mapGet("city"); + * field("address").mapGet("city"); * ``` * * @param subfield The key to access in the map. * @return A new `Expr` representing the value associated with the given key in the map. */ - mapGet(subfield: string): MapGet; + mapGet(subfield: string): FunctionExpr; /** * Creates an aggregation that counts the number of stage inputs with valid evaluations of the @@ -4328,24 +4143,24 @@ declare namespace FirebaseFirestore { * * ```typescript * // Count the total number of products - * Field.of("productId").count().as("totalProducts"); + * field("productId").count().as("totalProducts"); * ``` * - * @return A new `Accumulator` representing the 'count' aggregation. + * @return A new `AggregateFunction` representing the 'count' aggregation. */ - count(): Count; + count(): AggregateFunction; /** * Creates an aggregation that calculates the sum of a numeric field across multiple stage inputs. * * ```typescript * // Calculate the total revenue from a set of orders - * Field.of("orderAmount").sum().as("totalRevenue"); + * field("orderAmount").sum().as("totalRevenue"); * ``` * - * @return A new `Accumulator` representing the 'sum' aggregation. + * @return A new `AggregateFunction` representing the 'sum' aggregation. */ - sum(): Sum; + sum(): AggregateFunction; /** * Creates an aggregation that calculates the average (mean) of a numeric field across multiple @@ -4353,215 +4168,159 @@ declare namespace FirebaseFirestore { * * ```typescript * // Calculate the average age of users - * Field.of("age").avg().as("averageAge"); + * field("age").avg().as("averageAge"); * ``` * - * @return A new `Accumulator` representing the 'avg' aggregation. + * @return A new `AggregateFunction` representing the 'avg' aggregation. */ - avg(): Avg; + avg(): AggregateFunction; /** * Creates an aggregation that finds the minimum value of a field across multiple stage inputs. * * ```typescript * // Find the lowest price of all products - * Field.of("price").minimum().as("lowestPrice"); + * field("price").minimum().as("lowestPrice"); * ``` * - * @return A new `Accumulator` representing the 'minimum' aggregation. + * @return A new `AggregateFunction` representing the 'min' aggregation. */ - minimum(): Minimum; + minimum(): AggregateFunction; /** * Creates an aggregation that finds the maximum value of a field across multiple stage inputs. * * ```typescript * // Find the highest score in a leaderboard - * Field.of("score").maximum().as("highestScore"); + * field("score").maximum().as("highestScore"); * ``` * - * @return A new `Accumulator` representing the 'maximum' aggregation. + * @return A new `AggregateFunction` representing the 'max' aggregation. */ - maximum(): Maximim; + maximum(): AggregateFunction; /** * Creates an expression that returns the larger value between this expression and another expression, based on Firestore's value type ordering. * * ```typescript * // Returns the larger value between the 'timestamp' field and the current timestamp. - * Field.of("timestamp").logicalMaximum(Function.currentTimestamp()); + * field("timestamp").logicalMaximum(Function.currentTimestamp()); * ``` * - * @param other The expression to compare with. - * @return A new {@code Expr} representing the logical maximum operation. + * @param second The second expression or literal to compare with. + * @param others Optional additional expressions or literals to compare with. + * @return A new {@code Expr} representing the logical max operation. */ - logicalMaximum(other: Expr): LogicalMaximum; - - /** - * Creates an expression that returns the larger value between this expression and a constant value, based on Firestore's value type ordering. - * - * ```typescript - * // Returns the larger value between the 'value' field and 10. - * Field.of("value").logicalMaximum(10); - * ``` - * - * @param other The constant value to compare with. - * @return A new {@code Expr} representing the logical maximum operation. - */ - logicalMaximum(other: any): LogicalMaximum; + logicalMaximum( + second: Expr | unknown, + ...others: Array + ): FunctionExpr; /** * Creates an expression that returns the smaller value between this expression and another expression, based on Firestore's value type ordering. * * ```typescript * // Returns the smaller value between the 'timestamp' field and the current timestamp. - * Field.of("timestamp").logicalMinimum(Function.currentTimestamp()); - * ``` - * - * @param other The expression to compare with. - * @return A new {@code Expr} representing the logical minimum operation. - */ - logicalMinimum(other: Expr): LogicalMinimum; - - /** - * Creates an expression that returns the smaller value between this expression and a constant value, based on Firestore's value type ordering. - * - * ```typescript - * // Returns the smaller value between the 'value' field and 10. - * Field.of("value").logicalMinimum(10); + * field("timestamp").logicalMinimum(Function.currentTimestamp()); * ``` * - * @param other The constant value to compare with. - * @return A new {@code Expr} representing the logical minimum operation. + * @param second The second expression or literal to compare with. + * @param others Optional additional expressions or literals to compare with. + * @return A new {@code Expr} representing the logical min operation. */ - logicalMinimum(other: any): LogicalMinimum; + logicalMinimum( + second: Expr | unknown, + ...others: Array + ): FunctionExpr; /** * Creates an expression that calculates the length (number of dimensions) of this Firestore Vector expression. * * ```typescript * // Get the vector length (dimension) of the field 'embedding'. - * Field.of("embedding").vectorLength(); + * field("embedding").vectorLength(); * ``` * * @return A new {@code Expr} representing the length of the vector. */ - vectorLength(): VectorLength; + vectorLength(): FunctionExpr; /** * Calculates the cosine distance between two vectors. * * ```typescript * // Calculate the cosine distance between the 'userVector' field and the 'itemVector' field - * Field.of("userVector").cosineDistance(Field.of("itemVector")); + * field("userVector").cosineDistance(field("itemVector")); * ``` * - * @param other The other vector (represented as an Expr) to compare against. + * @param vectorExpression The other vector (represented as an Expr) to compare against. * @return A new `Expr` representing the cosine distance between the two vectors. */ - cosineDistance(other: Expr): CosineDistance; + cosineDistance(vectorExpression: Expr): FunctionExpr; /** * Calculates the Cosine distance between two vectors. * * ```typescript * // Calculate the Cosine distance between the 'location' field and a target location - * Field.of("location").cosineDistance(new VectorValue([37.7749, -122.4194])); + * field("location").cosineDistance(new VectorValue([37.7749, -122.4194])); * ``` * - * @param other The other vector (as a VectorValue) to compare against. + * @param vector The other vector (as a VectorValue) to compare against. * @return A new `Expr` representing the Cosine* distance between the two vectors. */ - cosineDistance(other: VectorValue): CosineDistance; - /** - * Calculates the Cosine distance between two vectors. - * - * ```typescript - * // Calculate the Cosine distance between the 'location' field and a target location - * Field.of("location").cosineDistance([37.7749, -122.4194]); - * ``` - * - * @param other The other vector (as an array of numbers) to compare against. - * @return A new `Expr` representing the Cosine distance between the two vectors. - */ - cosineDistance(other: number[]): CosineDistance; - - /** - * Calculates the dot product between two vectors. - * - * ```typescript - * // Calculate the dot product between a feature vector and a target vector - * Field.of("features").dotProduct([0.5, 0.8, 0.2]); - * ``` - * - * @param other The other vector (as an array of numbers) to calculate with. - * @return A new `Expr` representing the dot product between the two vectors. - */ - dotProduct(other: Expr): DotProduct; + cosineDistance(vector: VectorValue | number[]): FunctionExpr; /** * Calculates the dot product between two vectors. * * ```typescript * // Calculate the dot product between a feature vector and a target vector - * Field.of("features").dotProduct(new VectorValue([0.5, 0.8, 0.2])); + * field("features").dotProduct([0.5, 0.8, 0.2]); * ``` * - * @param other The other vector (as an array of numbers) to calculate with. + * @param vectorExpression The other vector (as an array of numbers) to calculate with. * @return A new `Expr` representing the dot product between the two vectors. */ - dotProduct(other: VectorValue): DotProduct; + dotProduct(vectorExpression: Expr): FunctionExpr; /** * Calculates the dot product between two vectors. * * ```typescript * // Calculate the dot product between a feature vector and a target vector - * Field.of("features").dotProduct([0.5, 0.8, 0.2]); + * field("features").dotProduct(new VectorValue([0.5, 0.8, 0.2])); * ``` * - * @param other The other vector (as an array of numbers) to calculate with. + * @param vector The other vector (as an array of numbers) to calculate with. * @return A new `Expr` representing the dot product between the two vectors. */ - dotProduct(other: number[]): DotProduct; + dotProduct(vector: VectorValue | number[]): FunctionExpr; /** * Calculates the Euclidean distance between two vectors. * * ```typescript * // Calculate the Euclidean distance between the 'location' field and a target location - * Field.of("location").euclideanDistance([37.7749, -122.4194]); + * field("location").euclideanDistance([37.7749, -122.4194]); * ``` * - * @param other The other vector (as an array of numbers) to calculate with. + * @param vectorExpression The other vector (as an array of numbers) to calculate with. * @return A new `Expr` representing the Euclidean distance between the two vectors. */ - euclideanDistance(other: Expr): EuclideanDistance; + euclideanDistance(vectorExpression: Expr): FunctionExpr; /** * Calculates the Euclidean distance between two vectors. * * ```typescript * // Calculate the Euclidean distance between the 'location' field and a target location - * Field.of("location").euclideanDistance(new VectorValue([37.7749, -122.4194])); + * field("location").euclideanDistance(new VectorValue([37.7749, -122.4194])); * ``` * - * @param other The other vector (as a VectorValue) to compare against. + * @param vector The other vector (as a VectorValue) to compare against. * @return A new `Expr` representing the Euclidean distance between the two vectors. */ - euclideanDistance(other: VectorValue): EuclideanDistance; - - /** - * Calculates the Euclidean distance between two vectors. - * - * ```typescript - * // Calculate the Euclidean distance between the 'location' field and a target location - * Field.of("location").euclideanDistance([37.7749, -122.4194]); - * ``` - * - * @param other The other vector (as an array of numbers) to compare against. - * @return A new `Expr` representing the Euclidean distance between the two vectors. - */ - euclideanDistance(other: number[]): EuclideanDistance; + euclideanDistance(vector: VectorValue | number[]): FunctionExpr; /** * Creates an expression that interprets this expression as the number of microseconds since the Unix epoch (1970-01-01 00:00:00 UTC) @@ -4569,24 +4328,24 @@ declare namespace FirebaseFirestore { * * ```typescript * // Interpret the 'microseconds' field as microseconds since epoch. - * Field.of("microseconds").unixMicrosToTimestamp(); + * field("microseconds").unixMicrosToTimestamp(); * ``` * * @return A new {@code Expr} representing the timestamp. */ - unixMicrosToTimestamp(): UnixMicrosToTimestamp; + unixMicrosToTimestamp(): FunctionExpr; /** * Creates an expression that converts this timestamp expression to the number of microseconds since the Unix epoch (1970-01-01 00:00:00 UTC). * * ```typescript * // Convert the 'timestamp' field to microseconds since epoch. - * Field.of("timestamp").timestampToUnixMicros(); + * field("timestamp").timestampToUnixMicros(); * ``` * * @return A new {@code Expr} representing the number of microseconds since epoch. */ - timestampToUnixMicros(): TimestampToUnixMicros; + timestampToUnixMicros(): FunctionExpr; /** * Creates an expression that interprets this expression as the number of milliseconds since the Unix epoch (1970-01-01 00:00:00 UTC) @@ -4594,24 +4353,24 @@ declare namespace FirebaseFirestore { * * ```typescript * // Interpret the 'milliseconds' field as milliseconds since epoch. - * Field.of("milliseconds").unixMillisToTimestamp(); + * field("milliseconds").unixMillisToTimestamp(); * ``` * * @return A new {@code Expr} representing the timestamp. */ - unixMillisToTimestamp(): UnixMillisToTimestamp; + unixMillisToTimestamp(): FunctionExpr; /** * Creates an expression that converts this timestamp expression to the number of milliseconds since the Unix epoch (1970-01-01 00:00:00 UTC). * * ```typescript * // Convert the 'timestamp' field to milliseconds since epoch. - * Field.of("timestamp").timestampToUnixMillis(); + * field("timestamp").timestampToUnixMillis(); * ``` * * @return A new {@code Expr} representing the number of milliseconds since epoch. */ - timestampToUnixMillis(): TimestampToUnixMillis; + timestampToUnixMillis(): FunctionExpr; /** * Creates an expression that interprets this expression as the number of seconds since the Unix epoch (1970-01-01 00:00:00 UTC) @@ -4619,45 +4378,45 @@ declare namespace FirebaseFirestore { * * ```typescript * // Interpret the 'seconds' field as seconds since epoch. - * Field.of("seconds").unixSecondsToTimestamp(); + * field("seconds").unixSecondsToTimestamp(); * ``` * * @return A new {@code Expr} representing the timestamp. */ - unixSecondsToTimestamp(): UnixSecondsToTimestamp; + unixSecondsToTimestamp(): FunctionExpr; /** * Creates an expression that converts this timestamp expression to the number of seconds since the Unix epoch (1970-01-01 00:00:00 UTC). * * ```typescript * // Convert the 'timestamp' field to seconds since epoch. - * Field.of("timestamp").timestampToUnixSeconds(); + * field("timestamp").timestampToUnixSeconds(); * ``` * * @return A new {@code Expr} representing the number of seconds since epoch. */ - timestampToUnixSeconds(): TimestampToUnixSeconds; + timestampToUnixSeconds(): FunctionExpr; /** * Creates an expression that adds a specified amount of time to this timestamp expression. * * ```typescript * // Add some duration determined by field 'unit' and 'amount' to the 'timestamp' field. - * Field.of("timestamp").timestampAdd(Field.of("unit"), Field.of("amount")); + * field("timestamp").timestampAdd(field("unit"), field("amount")); * ``` * * @param unit The expression evaluates to unit of time, must be one of 'microsecond', 'millisecond', 'second', 'minute', 'hour', 'day'. * @param amount The expression evaluates to amount of the unit. * @return A new {@code Expr} representing the resulting timestamp. */ - timestampAdd(unit: Expr, amount: Expr): TimestampAdd; + timestampAdd(unit: Expr, amount: Expr): FunctionExpr; /** * Creates an expression that adds a specified amount of time to this timestamp expression. * * ```typescript * // Add 1 day to the 'timestamp' field. - * Field.of("timestamp").timestampAdd("day", 1); + * field("timestamp").timestampAdd("day", 1); * ``` * * @param unit The unit of time to add (e.g., "day", "hour"). @@ -4673,28 +4432,28 @@ declare namespace FirebaseFirestore { | 'hour' | 'day', amount: number - ): TimestampAdd; + ): FunctionExpr; /** * Creates an expression that subtracts a specified amount of time from this timestamp expression. * * ```typescript * // Subtract some duration determined by field 'unit' and 'amount' from the 'timestamp' field. - * Field.of("timestamp").timestampSub(Field.of("unit"), Field.of("amount")); + * field("timestamp").timestampSub(field("unit"), field("amount")); * ``` * * @param unit The expression evaluates to unit of time, must be one of 'microsecond', 'millisecond', 'second', 'minute', 'hour', 'day'. * @param amount The expression evaluates to amount of the unit. * @return A new {@code Expr} representing the resulting timestamp. */ - timestampSub(unit: Expr, amount: Expr): TimestampSub; + timestampSub(unit: Expr, amount: Expr): FunctionExpr; /** * Creates an expression that subtracts a specified amount of time from this timestamp expression. * * ```typescript * // Subtract 1 day from the 'timestamp' field. - * Field.of("timestamp").timestampSub("day", 1); + * field("timestamp").timestampSub("day", 1); * ``` * * @param unit The unit of time to subtract (e.g., "day", "hour"). @@ -4710,721 +4469,1567 @@ declare namespace FirebaseFirestore { | 'hour' | 'day', amount: number - ): TimestampSub; + ): FunctionExpr; /** - * Creates an {@link Ordering} that sorts documents in ascending order based on this expression. + * @beta + * + * Creates an expression that applies a bitwise AND operation between this expression and a constant. * * ```typescript - * // Sort documents by the 'name' field in ascending order - * firestore.pipeline().collection("users") - * .sort(Field.of("name").ascending()); + * // Calculate the bitwise AND of 'field1' and 0xFF. + * field("field1").bitAnd(0xFF); * ``` * - * @return A new `Ordering` for ascending sorting. + * @param otherBits A constant representing bits. + * @return A new {@code Expr} representing the bitwise AND operation. */ - ascending(): Ordering; - + bitAnd(otherBits: number | Buffer | Uint8Array): FunctionExpr; /** - * Creates an {@link Ordering} that sorts documents in descending order based on this expression. + * @beta + * + * Creates an expression that applies a bitwise AND operation between two expressions. * * ```typescript - * // Sort documents by the 'createdAt' field in descending order - * firestore.pipeline().collection("users") - * .sort(Field.of("createdAt").descending()); + * // Calculate the bitwise AND of 'field1' and 'field2'. + * field("field1").bitAnd(field("field2")); * ``` * - * @return A new `Ordering` for descending sorting. + * @param bitsExpression An expression that returns bits when evaluated. + * @return A new {@code Expr} representing the bitwise AND operation. */ - descending(): Ordering; + bitAnd(bitsExpression: Expr): FunctionExpr; /** - * Assigns an alias to this expression. + * @beta * - * Aliases are useful for renaming fields in the output of a stage or for giving meaningful - * names to calculated values. + * Creates an expression that applies a bitwise OR operation between this expression and a constant. * * ```typescript - * // Calculate the total price and assign it the alias "totalPrice" and add it to the output. - * firestore.pipeline().collection("items") - * .addFields(Field.of("price").multiply(Field.of("quantity")).as("totalPrice")); + * // Calculate the bitwise OR of 'field1' and 0xFF. + * field("field1").bitOr(0xFF); * ``` * - * @param name The alias to assign to this expression. - * @return A new {@link ExprWithAlias} that wraps this - * expression and associates it with the provided alias. + * @param otherBits A constant representing bits. + * @return A new {@code Expr} representing the bitwise OR operation. */ - as(name: string): ExprWithAlias; - } - - /** - * @beta - */ - export class ExprWithAlias - extends Expr - implements Selectable - { - exprType: ExprType; - selectable: true; + bitOr(otherBits: number | Buffer | Uint8Array): FunctionExpr; /** - * @param expr The expression to alias. - * @param alias The alias to assign to the expression. + * @beta + * + * Creates an expression that applies a bitwise OR operation between two expressions. + * + * ```typescript + * // Calculate the bitwise OR of 'field1' and 'field2'. + * field("field1").bitOr(field("field2")); + * ``` + * + * @param bitsExpression An expression that returns bits when evaluated. + * @return A new {@code Expr} representing the bitwise OR operation. */ - constructor(expr: T, alias: string); - } - - /** - * @beta - * - * Represents a reference to a field in a Firestore document, or outputs of a {@link Pipeline} stage. - * - *

Field references are used to access document field values in expressions and to specify fields - * for sorting, filtering, and projecting data in Firestore pipelines. - * - *

You can create a `Field` instance using the static {@link #of} method: - * - * ```typescript - * // Create a Field instance for the 'name' field - * const nameField = Field.of("name"); - * - * // Create a Field instance for a nested field 'address.city' - * const cityField = Field.of("address.city"); - * ``` - */ - export class Field extends Expr implements Selectable { - exprType: ExprType; - selectable: true; + bitOr(bitsExpression: Expr): FunctionExpr; /** - * Creates a {@code Field} instance representing the field at the given path. + * @beta * - * The path can be a simple field name (e.g., "name") or a dot-separated path to a nested field - * (e.g., "address.city"). + * Creates an expression that applies a bitwise XOR operation between this expression and a constant. * * ```typescript - * // Create a Field instance for the 'title' field - * const titleField = Field.of("title"); - * - * // Create a Field instance for a nested field 'author.firstName' - * const authorFirstNameField = Field.of("author.firstName"); + * // Calculate the bitwise XOR of 'field1' and 0xFF. + * field("field1").bitXor(0xFF); * ``` * - * @param name The path to the field. - * @return A new {@code Field} instance representing the specified field. + * @param otherBits A constant representing bits. + * @return A new {@code Expr} representing the bitwise XOR operation. */ - static of(name: string): Field; - static of(path: FieldPath): Field; - static of(nameOrPath: string | FieldPath): Field; - static of(pipeline: Pipeline, name: string): Field; + bitXor(otherBits: number | Buffer | Uint8Array): FunctionExpr; /** - * Returns the field name. + * @beta * - * @return The field name. - */ - fieldName(): string; - } - - /** - * @beta - * - * Represents a constant value that can be used in a Firestore pipeline expression. - * - * You can create a `Constant` instance using the static {@link #of} method: - * - * ```typescript - * // Create a Constant instance for the number 10 - * const ten = Constant.of(10); - * - * // Create a Constant instance for the string "hello" - * const hello = Constant.of("hello"); - * ``` - */ - export class Constant extends Expr { - exprType: ExprType; - - /** - * Creates a `Constant` instance for a number value. + * Creates an expression that applies a bitwise XOR operation between two expressions. + * + * ```typescript + * // Calculate the bitwise XOR of 'field1' and 'field2'. + * field("field1").bitXor(field("field2")); + * ``` * - * @param value The number value. - * @return A new `Constant` instance. + * @param bitsExpression An expression that returns bits when evaluated. + * @return A new {@code Expr} representing the bitwise XOR operation. */ - static of(value: number): Constant; + bitXor(bitsExpression: Expr): FunctionExpr; /** - * Creates a `Constant` instance for a string value. + * @beta + * + * Creates an expression that applies a bitwise NOT operation to this expression. + * + * ```typescript + * // Calculate the bitwise NOT of 'field1'. + * field("field1").bitNot(); + * ``` * - * @param value The string value. - * @return A new `Constant` instance. + * @return A new {@code Expr} representing the bitwise NOT operation. */ - static of(value: string): Constant; + bitNot(): FunctionExpr; /** - * Creates a `Constant` instance for a boolean value. + * @beta + * + * Creates an expression that applies a bitwise left shift operation to this expression. + * + * ```typescript + * // Calculate the bitwise left shift of 'field1' by 2 bits. + * field("field1").bitLeftShift(2); + * ``` * - * @param value The boolean value. - * @return A new `Constant` instance. + * @param y The operand constant representing the number of bits to shift. + * @return A new {@code Expr} representing the bitwise left shift operation. */ - static of(value: boolean): Constant; - + bitLeftShift(y: number): FunctionExpr; /** - * Creates a `Constant` instance for a null value. + * @beta * - * @param value The null value. - * @return A new `Constant` instance. + * Creates an expression that applies a bitwise left shift operation to this expression. + * + * ```typescript + * // Calculate the bitwise left shift of 'field1' by 'field2' bits. + * field("field1").bitLeftShift(field("field2")); + * ``` + * + * @param numberExpr The operand expression representing the number of bits to shift. + * @return A new {@code Expr} representing the bitwise left shift operation. */ - static of(value: null): Constant; + bitLeftShift(numberExpr: Expr): FunctionExpr; /** - * Creates a `Constant` instance for an undefined value. + * @beta + * + * Creates an expression that applies a bitwise right shift operation to this expression. + * + * ```typescript + * // Calculate the bitwise right shift of 'field1' by 2 bits. + * field("field1").bitRightShift(2); + * ``` * - * @param value The undefined value. - * @return A new `Constant` instance. + * @param right The operand constant representing the number of bits to shift. + * @return A new {@code Expr} representing the bitwise right shift operation. */ - static of(value: undefined): Constant; - + bitRightShift(y: number): FunctionExpr; /** - * Creates a `Constant` instance for a GeoPoint value. + * @beta + * + * Creates an expression that applies a bitwise right shift operation to this expression. * - * @param value The GeoPoint value. - * @return A new `Constant` instance. + * ```typescript + * // Calculate the bitwise right shift of 'field1' by 'field2' bits. + * field("field1").bitRightShift(field("field2")); + * ``` + * + * @param numberExpr The operand expression representing the number of bits to shift. + * @return A new {@code Expr} representing the bitwise right shift operation. */ - static of(value: GeoPoint): Constant; + bitRightShift(numberExpr: Expr): FunctionExpr; /** - * Creates a `Constant` instance for a Timestamp value. + * @beta * - * @param value The Timestamp value. - * @return A new `Constant` instance. + * Creates an expression that returns the document ID from a path. + * + * ```typescript + * // Get the document ID from a path. + * field("__path__").documentId(); + * ``` + * + * @return A new {@code Expr} representing the documentId operation. */ - static of(value: Timestamp): Constant; + documentId(): FunctionExpr; /** - * Creates a `Constant` instance for a Date value. + * @beta + * + * Creates an expression that returns a substring of the results of this expression. * - * @param value The Date value. - * @return A new `Constant` instance. + * @param position Index of the first character of the substring. + * @param length Length of the substring. If not provided, the substring will + * end at the end of the input. */ - static of(value: Date): Constant; + substr(position: number, length?: number): FunctionExpr; /** - * Creates a `Constant` instance for a Uint8Array value. + * @beta + * + * Creates an expression that returns a substring of the results of this expression. * - * @param value The Uint8Array value. - * @return A new `Constant` instance. + * @param position An expression returning the index of the first character of the substring. + * @param length An expression returning the length of the substring. If not provided the + * substring will end at the end of the input. */ - static of(value: Uint8Array): Constant; + substr(position: Expr, length?: Expr): FunctionExpr; /** - * Creates a `Constant` instance for a DocumentReference value. + * @beta + * Creates an expression that indexes into an array from the beginning or end + * and returns the element. If the offset exceeds the array length, an error is + * returned. A negative offset, starts from the end. + * + * ```typescript + * // Return the value in the 'tags' field array at index `1`. + * field('tags').arrayOffset(1); + * ``` + * + * @param offset The index of the element to return. + * @return A new Expr representing the 'arrayOffset' operation. + */ + arrayOffset(offset: number): FunctionExpr; + + /** + * @beta + * Creates an expression that indexes into an array from the beginning or end + * and returns the element. If the offset exceeds the array length, an error is + * returned. A negative offset, starts from the end. + * + * ```typescript + * // Return the value in the tags field array at index specified by field + * // 'favoriteTag'. + * field('tags').arrayOffset(field('favoriteTag')); + * ``` + * + * @param offsetExpr An Expr evaluating to the index of the element to return. + * @return A new Expr representing the 'arrayOffset' operation. + */ + arrayOffset(offsetExpr: Expr): FunctionExpr; + + /** + * @beta + * + * Creates an expression that checks if a given expression produces an error. + * + * ```typescript + * // Check if the result of a calculation is an error + * field("title").arrayContains(1).isError(); + * ``` + * + * @return A new {@code BooleanExpr} representing the 'isError' check. + */ + isError(): BooleanExpr; + + /** + * @beta + * + * Creates an expression that returns the result of the `catchExpr` argument + * if there is an error, else return the result of this expression. + * + * ```typescript + * // Returns the first item in the title field arrays, or returns + * // the entire title field if the array is empty or the field is another type. + * field("title").arrayOffset(0).ifError(field("title")); + * ``` + * + * @param catchExpr The catch expression that will be evaluated and + * returned if this expression produces an error. + * @return A new {@code Expr} representing the 'ifError' operation. + */ + ifError(catchExpr: Expr): FunctionExpr; + + /** + * @beta + * + * Creates an expression that returns the `catch` argument if there is an + * error, else return the result of this expression. + * + * ```typescript + * // Returns the first item in the title field arrays, or returns + * // "Default Title" + * field("title").arrayOffset(0).ifError("Default Title"); + * ``` + * + * @param catchValue The value that will be returned if this expression + * produces an error. + * @return A new {@code Expr} representing the 'ifError' operation. + */ + ifError(catchValue: unknown): FunctionExpr; + + /** + * @beta + * + * Creates an expression that returns `true` if the result of this expression + * is absent. Otherwise, returns `false` even if the value is `null`. + * + * ```typescript + * // Check if the field `value` is absent. + * field("value").isAbsent(); + * ``` * - * @param value The DocumentReference value. - * @return A new `Constant` instance. + * @return A new {@code BooleanExpr} representing the 'isAbsent' check. */ - static of(value: DocumentReference): Constant; + isAbsent(): BooleanExpr; /** - * Creates a `Constant` instance for an array value. + * @beta * - * @param value The array value. - * @return A new `Constant` instance. + * Creates an expression that checks if tbe result of an expression is not null. + * + * ```typescript + * // Check if the value of the 'name' field is not null + * field("name").isNotNull(); + * ``` + * + * @return A new {@code BooleanExpr} representing the 'isNotNull' check. */ - static of(value: Array): Constant; + isNotNull(): BooleanExpr; /** - * Creates a `Constant` instance for a map value. + * @beta * - * @param value The map value. - * @return A new `Constant` instance. + * Creates an expression that checks if the results of this expression is NOT 'NaN' (Not a Number). + * + * ```typescript + * // Check if the result of a calculation is NOT NaN + * field("value").divide(0).isNotNan(); + * ``` + * + * @return A new {@code Expr} representing the 'isNaN' check. */ - static of(value: Map): Constant; + isNotNan(): BooleanExpr; /** - * Creates a `Constant` instance for a VectorValue value. + * @beta + * + * Creates an expression that removes a key from the map produced by evaluating this expression. * - * @param value The VectorValue value. - * @return A new `Constant` instance. + * ``` + * // Removes the key 'baz' from the input map. + * map({foo: 'bar', baz: true}).mapRemove('baz'); + * ``` + * + * @param key The name of the key to remove from the input map. + * @returns A new {@code FirestoreFunction} representing the 'mapRemove' operation. */ - static of(value: VectorValue): Constant; - static of(value: any): Constant; + mapRemove(key: string): FunctionExpr; + /** + * @beta + * + * Creates an expression that removes a key from the map produced by evaluating this expression. + * + * ``` + * // Removes the key 'baz' from the input map. + * map({foo: 'bar', baz: true}).mapRemove(constant('baz')); + * ``` + * + * @param keyExpr An expression that produces the name of the key to remove from the input map. + * @returns A new {@code FirestoreFunction} representing the 'mapRemove' operation. + */ + mapRemove(keyExpr: Expr): FunctionExpr; /** - * Creates a `Constant` instance for a VectorValue value. + * @beta + * + * Creates an expression that merges multiple map values. + * + * ``` + * // 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 }, cond(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 {@code FirestoreFunction} representing the 'mapMerge' operation. + */ + mapMerge( + secondMap: Record | Expr, + ...otherMaps: Array | Expr> + ): FunctionExpr; + + /** + * Creates an {@link Ordering} that sorts documents in ascending order based on this expression. * * ```typescript - * // Create a Constant instance for a vector value - * const vectorConstant = Constant.ofVector([1, 2, 3]); + * // Sort documents by the 'name' field in ascending order + * pipeline().collection("users") + * .sort(field("name").ascending()); * ``` * - * @param value The VectorValue value. - * @return A new `Constant` instance. + * @return A new `Ordering` for ascending sorting. */ - static vector(value: Array | VectorValue): Constant; + ascending(): Ordering; + + /** + * Creates an {@link Ordering} that sorts documents in descending order based on this expression. + * + * ```typescript + * // Sort documents by the 'createdAt' field in descending order + * pipeline().collection("users") + * .sort(field("createdAt").descending()); + * ``` + * + * @return A new `Ordering` for descending sorting. + */ + descending(): Ordering; + + /** + * 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. + * + * ```typescript + * // Calculate the total price and assign it the alias "totalPrice" and add it to the output. + * pipeline().collection("items") + * .addFields(field("price").multiply(field("quantity")).as("totalPrice")); + * ``` + * + * @param name The alias to assign to this expression. + * @return A new {@link ExprWithAlias} that wraps this + * expression and associates it with the provided alias. + */ + as(name: string): ExprWithAlias; } /** * @beta * - * This class defines the base class for Firestore {@link Pipeline} functions, which can be evaluated within pipeline - * execution. + * An interface that represents a selectable expression. + */ + export interface Selectable { + selectable: true; + readonly alias: string; + readonly expr: Expr; + } + + /** + * @beta * - * Typically, you would not use this class or its children directly. Use either the functions like {@link and}, {@link eq}, - * or the methods on {@link Expr} ({@link Expr#eq}, {@link Expr#lt}, etc) to construct new Function instances. + * A class that represents an aggregate function. */ - export class Function extends Expr { + export class AggregateFunction { exprType: ExprType; + constructor(name: string, params: Expr[]); + + /** + * Assigns an alias to this AggregateFunction. The alias specifies the name that + * the aggregated value will have in the output document. + * + * ```typescript + * // Calculate the average price of all items and assign it the alias "averagePrice". + * pipeline().collection("items") + * .aggregate(field("price").avg().as("averagePrice")); + * ``` + * + * @param name The alias to assign to this AggregateFunction. + * @return A new {@link AggregateWithAlias} that wraps this + * AggregateFunction and associates it with the provided alias. + */ + as(name: string): AggregateWithAlias; } /** * @beta + * + * An AggregateFunction with alias. */ - export class Add extends Function {} + export class AggregateWithAlias { + readonly aggregate: AggregateFunction; + readonly alias: string; + } /** * @beta */ - export class Subtract extends Function {} + export class ExprWithAlias implements Selectable { + exprType: ExprType; + selectable: true; + + readonly expr: Expr; + readonly alias: string; + } /** * @beta + * + * Represents a reference to a field in a Firestore document, or outputs of a {@link Pipeline} stage. + * + *

Field references are used to access document field values in expressions and to specify fields + * for sorting, filtering, and projecting data in Firestore pipelines. + * + *

You can create a `Field` instance using the static {@link #of} method: + * + * ```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"); + * ``` */ - export class Multiply extends Function {} + export class Field extends Expr implements Selectable { + readonly exprType: ExprType; + selectable: true; + + fieldName(): string; + + get alias(): string; + + get expr(): Expr; + } /** - * @beta + * Creates a {@code Field} instance representing the field at the given path. + * + * The path can be a simple field name (e.g., "name") or a dot-separated path to a nested field + * (e.g., "address.city"). + * + * ```typescript + * // Create a Field instance for the 'title' field + * const titleField = field("title"); + * + * // Create a Field instance for a nested field 'author.firstName' + * const authorFirstNameField = field("author.firstName"); + * ``` + * + * @param name The path to the field. + * @return A new {@code Field} instance representing the specified field. */ - export class Divide extends Function {} + export function field(name: string): Field; + export function field(path: FieldPath): Field; /** * @beta + * + * Represents a constant value that can be used in a Firestore pipeline expression. + * + * You can create a `Constant` instance using the static {@link #of} method: + * + * ```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"); + * ``` */ - export class Mod extends Function {} + export class Constant extends Expr { + readonly exprType: ExprType; + } - // /** - // * @beta - // */ - // export class BitAnd extends Function {} - // - // /** - // * @beta - // */ - // export class BitOr extends Function {} - // - // /** - // * @beta - // */ - // export class BitXor extends Function {} - // - // /** - // * @beta - // */ - // export class BitNot extends Function {} - // - // /** - // * @beta - // */ - // export class BitLeftShift extends Function {} - // - // /** - // * @beta - // */ - // export class BitRightShift extends Function {} + /** + * Creates a `Constant` instance for a number value. + * + * @param value The number value. + * @return A new `Constant` instance. + */ + export function constant(value: number): Constant; /** - * @beta + * Creates a `Constant` instance for a string value. + * + * @param value The string value. + * @return A new `Constant` instance. */ - export class Eq extends Function implements FilterCondition { - filterable: true; - } + export function constant(value: string): Constant; /** - * @beta + * Creates a `Constant` instance for a boolean value. + * + * @param value The boolean value. + * @return A new `Constant` instance. */ - export class Neq extends Function implements FilterCondition { - filterable: true; - } + export function constant(value: boolean): Constant; /** - * @beta + * Creates a `Constant` instance for a null value. + * + * @param value The null value. + * @return A new `Constant` instance. */ - export class Lt extends Function implements FilterCondition { - filterable: true; - } + export function constant(value: null): Constant; /** - * @beta + * Creates a `Constant` instance for a GeoPoint value. + * + * @param value The GeoPoint value. + * @return A new `Constant` instance. */ - export class Lte extends Function implements FilterCondition { - filterable: true; - } + export function constant(value: GeoPoint): Constant; /** - * @beta + * Creates a `Constant` instance for a Timestamp value. + * + * @param value The Timestamp value. + * @return A new `Constant` instance. */ - export class Gt extends Function implements FilterCondition { - filterable: true; - } + export function constant(value: Timestamp): Constant; /** - * @beta + * Creates a `Constant` instance for a Date value. + * + * @param value The Date value. + * @return A new `Constant` instance. */ - export class Gte extends Function implements FilterCondition { - filterable: true; - } + export function constant(value: Date): Constant; /** - * @beta + * Creates a `Constant` instance for a Buffer | Uint8Array value. + * + * @param value The Buffer | Uint8Array value. + * @return A new `Constant` instance. */ - export class ArrayConcat extends Function {} + export function constant(value: Buffer | Uint8Array): Constant; /** - * @beta + * Creates a `Constant` instance for a DocumentReference value. + * + * @param value The DocumentReference value. + * @return A new `Constant` instance. */ - export class ArrayContains extends Function implements FilterCondition { - filterable: true; - } + export function constant(value: DocumentReference): Constant; + + /** + * Creates a `Constant` instance for a VectorValue value. + * + * @param value The VectorValue value. + * @return A new `Constant` instance. + */ + export function constant(value: VectorValue): Constant; + + /** + * Creates a `Constant` instance for a VectorValue value. + * + * ```typescript + * // Create a Constant instance for a vector value + * const vectorConstant = constantVector([1, 2, 3]); + * ``` + * + * @param value The VectorValue value. + * @return A new `Constant` instance. + */ + export function constantVector(value: number[] | VectorValue): Constant; /** * @beta + * + * This class defines the base class for Firestore {@link 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 and}, {@link eq}, + * or the methods on {@link Expr} ({@link Expr#eq}, {@link Expr#lt}, etc.) to construct new Function instances. */ - export class ArrayContainsAll extends Function implements FilterCondition { - filterable: true; + export class FunctionExpr extends Expr { + readonly exprType: ExprType; + + constructor(name: string, params: Expr[]); } /** * @beta + * + * An interface that represents a filter condition. */ - export class ArrayContainsAny extends Function implements FilterCondition { + export class BooleanExpr extends FunctionExpr { filterable: true; + + /** + * Creates an aggregation that finds the count of input documents satisfying + * this boolean expression. + * + * ```typescript + * // Find the count of documents with a score greater than 90 + * field("score").gt(90).countIf().as("highestScore"); + * ``` + * + * @return A new `AggregateFunction` representing the 'countIf' aggregation. + */ + countIf(): AggregateFunction; + + /** + * Creates an expression that negates this boolean expression. + * + * ```typescript + * // Find documents where the 'tags' field does not contain 'completed' + * field("tags").arrayContains("completed").not(); + * ``` + * + * @return A new {@code Expr} representing the negated filter condition. + */ + not(): BooleanExpr; } /** * @beta + * Creates an aggregation that counts the number of stage inputs where the provided + * boolean expression evaluates to true. + * + * ```typescript + * // Count the number of documents where 'is_active' field equals true + * countIf(field("is_active").eq(true)).as("numActiveDocuments"); + * ``` + * + * @param booleanExpr - The boolean expression to evaluate on each input. + * @returns A new `AggregateFunction` representing the 'countIf' aggregation. */ - export class ArrayLength extends Function {} + export function countIf(booleanExpr: BooleanExpr): AggregateFunction; /** * @beta + * Creates an expression that return a pseudo-random value of type double in the + * range of [0, 1), inclusive of 0 and exclusive of 1. + * + * @returns A new `Expr` representing the 'rand' function. */ - export class EqAny extends Function implements FilterCondition { - filterable: true; - } + export function rand(): FunctionExpr; /** * @beta + * + * Creates an expression that applies a bitwise AND operation between a field and a constant. + * + * ```typescript + * // Calculate the bitwise AND of 'field1' and 0xFF. + * bitAnd("field1", 0xFF); + * ``` + * + * @param field The left operand field name. + * @param otherBits A constant representing bits. + * @return A new {@code Expr} representing the bitwise AND operation. */ - export class NotEqAny extends Function implements FilterCondition { - filterable: true; - } - + export function bitAnd( + field: string, + otherBits: number | Buffer | Uint8Array + ): FunctionExpr; /** * @beta + * + * Creates an expression that applies a bitwise AND operation between a field and an expression. + * + * ```typescript + * // Calculate the bitwise AND of 'field1' and 'field2'. + * bitAnd("field1", field("field2")); + * ``` + * + * @param field The left operand field name. + * @param bitsExpression An expression that returns bits when evaluated. + * @return A new {@code Expr} representing the bitwise AND operation. */ - export class IsNan extends Function implements FilterCondition { - filterable: true; - } - + export function bitAnd(field: string, bitsExpression: Expr): FunctionExpr; /** * @beta + * + * Creates an expression that applies a bitwise AND operation between an expression and a constant. + * + * ```typescript + * // Calculate the bitwise AND of 'field1' and 0xFF. + * bitAnd(field("field1"), 0xFF); + * ``` + * + * @param bitsExpression An expression returning bits. + * @param otherBits A constant representing bits. + * @return A new {@code Expr} representing the bitwise AND operation. */ - export class Exists extends Function implements FilterCondition { - filterable: true; - } - + export function bitAnd( + bitsExpression: Expr, + otherBits: number | Buffer | Uint8Array + ): FunctionExpr; /** * @beta + * + * Creates an expression that applies a bitwise AND operation between two expressions. + * + * ```typescript + * // Calculate the bitwise AND of 'field1' and 'field2'. + * bitAnd(field("field1"), field("field2")); + * ``` + * + * @param bitsExpression An expression that returns bits when evaluated. + * @param otherBitsExpression An expression that returns bits when evaluated. + * @return A new {@code Expr} representing the bitwise AND operation. */ - export class Not extends Function implements FilterCondition { - filterable: true; - } + export function bitAnd( + bitsExpression: Expr, + otherBitsExpression: Expr + ): FunctionExpr; /** * @beta + * + * Creates an expression that applies a bitwise OR operation between a field and a constant. + * + * ```typescript + * // Calculate the bitwise OR of 'field1' and 0xFF. + * bitOr("field1", 0xFF); + * ``` + * + * @param field The left operand field name. + * @param otherBits A constant representing bits. + * @return A new {@code Expr} representing the bitwise OR operation. */ - export class And extends Function implements FilterCondition { - filterable: true; - } - + export function bitOr( + field: string, + otherBits: number | Buffer | Uint8Array + ): FunctionExpr; /** * @beta + * + * Creates an expression that applies a bitwise OR operation between a field and an expression. + * + * ```typescript + * // Calculate the bitwise OR of 'field1' and 'field2'. + * bitOr("field1", field("field2")); + * ``` + * + * @param field The left operand field name. + * @param bitsExpression An expression that returns bits when evaluated. + * @return A new {@code Expr} representing the bitwise OR operation. */ - export class Or extends Function implements FilterCondition { - filterable: true; - } - + export function bitOr(field: string, bitsExpression: Expr): FunctionExpr; /** * @beta + * + * Creates an expression that applies a bitwise OR operation between an expression and a constant. + * + * ```typescript + * // Calculate the bitwise OR of 'field1' and 0xFF. + * bitOr(field("field1"), 0xFF); + * ``` + * + * @param bitsExpression An expression returning bits. + * @param otherBits A constant representing bits. + * @return A new {@code Expr} representing the bitwise OR operation. */ - export class Xor extends Function implements FilterCondition { - filterable: true; - } + export function bitOr( + bitsExpression: Expr, + otherBits: number | Buffer | Uint8Array + ): FunctionExpr; + /** + * @beta + * + * Creates an expression that applies a bitwise OR operation between two expressions. + * + * ```typescript + * // Calculate the bitwise OR of 'field1' and 'field2'. + * bitOr(field("field1"), field("field2")); + * ``` + * + * @param bitsExpression An expression that returns bits when evaluated. + * @param otherBitsExpression An expression that returns bits when evaluated. + * @return A new {@code Expr} representing the bitwise OR operation. + */ + export function bitOr( + bitsExpression: Expr, + otherBitsExpression: Expr + ): FunctionExpr; /** * @beta + * + * Creates an expression that applies a bitwise XOR operation between a field and a constant. + * + * ```typescript + * // Calculate the bitwise XOR of 'field1' and 0xFF. + * bitXor("field1", 0xFF); + * ``` + * + * @param field The left operand field name. + * @param otherBits A constant representing bits. + * @return A new {@code Expr} representing the bitwise XOR operation. + */ + export function bitXor( + field: string, + otherBits: number | Buffer | Uint8Array + ): FunctionExpr; + /** + * @beta + * + * Creates an expression that applies a bitwise XOR operation between a field and an expression. + * + * ```typescript + * // Calculate the bitwise XOR of 'field1' and 'field2'. + * bitXor("field1", field("field2")); + * ``` + * + * @param field The left operand field name. + * @param bitsExpression An expression that returns bits when evaluated. + * @return A new {@code Expr} representing the bitwise XOR operation. + */ + export function bitXor(field: string, bitsExpression: Expr): FunctionExpr; + /** + * @beta + * + * Creates an expression that applies a bitwise XOR operation between an expression and a constant. + * + * ```typescript + * // Calculate the bitwise XOR of 'field1' and 0xFF. + * bitXor(field("field1"), 0xFF); + * ``` + * + * @param bitsExpression An expression returning bits. + * @param otherBits A constant representing bits. + * @return A new {@code Expr} representing the bitwise XOR operation. + */ + export function bitXor( + bitsExpression: Expr, + otherBits: number | Buffer | Uint8Array + ): FunctionExpr; + /** + * @beta + * + * Creates an expression that applies a bitwise XOR operation between two expressions. + * + * ```typescript + * // Calculate the bitwise XOR of 'field1' and 'field2'. + * bitXor(field("field1"), field("field2")); + * ``` + * + * @param bitsExpression An expression that returns bits when evaluated. + * @param otherBitsExpression An expression that returns bits when evaluated. + * @return A new {@code Expr} representing the bitwise XOR operation. */ - export class If extends Function implements FilterCondition { - filterable: true; - } + export function bitXor( + bitsExpression: Expr, + otherBitsExpression: Expr + ): FunctionExpr; /** * @beta + * + * Creates an expression that applies a bitwise NOT operation to a field. + * + * ```typescript + * // Calculate the bitwise NOT of 'field1'. + * bitNot("field1"); + * ``` + * + * @param field The operand field name. + * @return A new {@code Expr} representing the bitwise NOT operation. */ - export class LogicalMaximum extends Function {} - + export function bitNot(field: string): FunctionExpr; /** * @beta + * + * Creates an expression that applies a bitwise NOT operation to an expression. + * + * ```typescript + * // Calculate the bitwise NOT of 'field1'. + * bitNot(field("field1")); + * ``` + * + * @param bitsValueExpression An expression that returns bits when evaluated. + * @return A new {@code Expr} representing the bitwise NOT operation. */ - export class LogicalMinimum extends Function {} + export function bitNot(bitsValueExpression: Expr): FunctionExpr; /** * @beta + * + * Creates an expression that applies a bitwise left shift operation between a field and a constant. + * + * ```typescript + * // Calculate the bitwise left shift of 'field1' by 2 bits. + * bitLeftShift("field1", 2); + * ``` + * + * @param field The left operand field name. + * @param y The right operand constant representing the number of bits to shift. + * @return A new {@code Expr} representing the bitwise left shift operation. */ - export class CharLength extends Function {} - + export function bitLeftShift(field: string, y: number): FunctionExpr; /** * @beta + * + * Creates an expression that applies a bitwise left shift operation between a field and an expression. + * + * ```typescript + * // Calculate the bitwise left shift of 'field1' by 'field2' bits. + * bitLeftShift("field1", field("field2")); + * ``` + * + * @param field The left operand field name. + * @param numberExpr The right operand expression representing the number of bits to shift. + * @return A new {@code Expr} representing the bitwise left shift operation. */ - export class Like extends Function implements FilterCondition { - filterable: true; - } - + export function bitLeftShift(field: string, numberExpr: Expr): FunctionExpr; /** * @beta + * + * Creates an expression that applies a bitwise left shift operation between an expression and a constant. + * + * ```typescript + * // Calculate the bitwise left shift of 'field1' by 2 bits. + * bitLeftShift(field("field1"), 2); + * ``` + * + * @param xValue An expression returning bits. + * @param y The right operand constant representing the number of bits to shift. + * @return A new {@code Expr} representing the bitwise left shift operation. */ - export class RegexContains extends Function implements FilterCondition { - filterable: true; - } - + export function bitLeftShift(xValue: Expr, y: number): FunctionExpr; /** * @beta + * + * Creates an expression that applies a bitwise left shift operation between two expressions. + * + * ```typescript + * // Calculate the bitwise left shift of 'field1' by 'field2' bits. + * bitLeftShift(field("field1"), field("field2")); + * ``` + * + * @param xValue An expression returning bits. + * @param numberExpr The right operand expression representing the number of bits to shift. + * @return A new {@code Expr} representing the bitwise left shift operation. */ - export class RegexMatch extends Function implements FilterCondition { - filterable: true; - } + export function bitLeftShift(xValue: Expr, numberExpr: Expr): FunctionExpr; /** * @beta + * + * Creates an expression that applies a bitwise right shift operation between a field and a constant. + * + * ```typescript + * // Calculate the bitwise right shift of 'field1' by 2 bits. + * bitRightShift("field1", 2); + * ``` + * + * @param field The left operand field name. + * @param y The right operand constant representing the number of bits to shift. + * @return A new {@code Expr} representing the bitwise right shift operation. */ - export class StrContains extends Function implements FilterCondition { - filterable: true; - } - + export function bitRightShift(field: string, y: number): FunctionExpr; /** * @beta + * + * Creates an expression that applies a bitwise right shift operation between a field and an expression. + * + * ```typescript + * // Calculate the bitwise right shift of 'field1' by 'field2' bits. + * bitRightShift("field1", field("field2")); + * ``` + * + * @param field The left operand field name. + * @param numberExpr The right operand expression representing the number of bits to shift. + * @return A new {@code Expr} representing the bitwise right shift operation. */ - export class StartsWith extends Function implements FilterCondition { - filterable: true; - } - + export function bitRightShift(field: string, numberExpr: Expr): FunctionExpr; /** * @beta + * + * Creates an expression that applies a bitwise right shift operation between an expression and a constant. + * + * ```typescript + * // Calculate the bitwise right shift of 'field1' by 2 bits. + * bitRightShift(field("field1"), 2); + * ``` + * + * @param xValue An expression returning bits. + * @param y The right operand constant representing the number of bits to shift. + * @return A new {@code Expr} representing the bitwise right shift operation. */ - export class EndsWith extends Function implements FilterCondition { - filterable: true; - } - + export function bitRightShift(xValue: Expr, y: number): FunctionExpr; /** * @beta + * + * Creates an expression that applies a bitwise right shift operation between two expressions. + * + * ```typescript + * // Calculate the bitwise right shift of 'field1' by 'field2' bits. + * bitRightShift(field("field1"), field("field2")); + * ``` + * + * @param xValue An expression returning bits. + * @param right The right operand expression representing the number of bits to shift. + * @return A new {@code Expr} representing the bitwise right shift operation. */ - export class ToLower extends Function {} + export function bitRightShift(xValue: Expr, numberExpr: Expr): FunctionExpr; /** * @beta + * Creates an expression that indexes into an array from the beginning or end + * and return the element. If the offset exceeds the array length, an error is + * returned. A negative offset, starts from the end. + * + * ```typescript + * // Return the value in the tags field array at index 1. + * arrayOffset('tags', 1); + * ``` + * + * @param arrayField The name of the array field. + * @param offset The index of the element to return. + * @return A new Expr representing the 'arrayOffset' operation. */ - export class ToUpper extends Function {} + export function arrayOffset(arrayField: string, offset: number): FunctionExpr; /** * @beta + * Creates an expression that indexes into an array from the beginning or end + * and return the element. If the offset exceeds the array length, an error is + * returned. A negative offset, starts from the end. + * + * ```typescript + * // Return the value in the tags field array at index specified by field + * // 'favoriteTag'. + * arrayOffset('tags', field('favoriteTag')); + * ``` + * + * @param arrayField The name of the array field. + * @param offsetExpr An Expr evaluating to the index of the element to return. + * @return A new Expr representing the 'arrayOffset' operation. */ - export class Trim extends Function {} + export function arrayOffset( + arrayField: string, + offsetExpr: Expr + ): FunctionExpr; /** * @beta + * Creates an expression that indexes into an array from the beginning or end + * and return the element. If the offset exceeds the array length, an error is + * returned. A negative offset, starts from the end. + * + * ```typescript + * // Return the value in the tags field array at index 1. + * arrayOffset(field('tags'), 1); + * ``` + * + * @param arrayExpression An Expr evaluating to an array. + * @param offset The index of the element to return. + * @return A new Expr representing the 'arrayOffset' operation. */ - export class StrConcat extends Function {} + export function arrayOffset( + arrayExpression: Expr, + offset: number + ): FunctionExpr; /** * @beta + * Creates an expression that indexes into an array from the beginning or end + * and return the element. If the offset exceeds the array length, an error is + * returned. A negative offset, starts from the end. + * + * ```typescript + * // Return the value in the tags field array at index specified by field + * // 'favoriteTag'. + * arrayOffset(field('tags'), field('favoriteTag')); + * ``` + * + * @param arrayExpression An Expr evaluating to an array. + * @param offsetExpr An Expr evaluating to the index of the element to return. + * @return A new Expr representing the 'arrayOffset' operation. */ - export class Reverse extends Function {} + export function arrayOffset( + arrayExpression: Expr, + offsetExpr: Expr + ): FunctionExpr; /** * @beta + * + * Creates an expression that checks if a given expression produces an error. + * + * ```typescript + * // Check if the result of a calculation is an error + * isError(field("title").arrayContains(1)); + * ``` + * + * @param value The expression to check. + * @return A new {@code Expr} representing the 'isError' check. */ - export class ReplaceFirst extends Function {} + export function isError(value: Expr): BooleanExpr; /** * @beta + * + * Creates an expression that returns the `catch` argument if there is an + * error, else return the result of the `try` argument evaluation. + * + * ```typescript + * // Returns the first item in the title field arrays, or returns + * // the entire title field if the array is empty or the field is another type. + * ifError(field("title").arrayOffset(0), field("title")); + * ``` + * + * @param tryExpr The try expression. + * @param catchExpr The catch expression that will be evaluated and + * returned if the tryExpr produces an error. + * @return A new {@code Expr} representing the 'ifError' operation. */ - export class ReplaceAll extends Function {} + export function ifError(tryExpr: Expr, catchExpr: Expr): FunctionExpr; /** * @beta + * + * Creates an expression that returns the `catch` argument if there is an + * error, else return the result of the `try` argument evaluation. + * + * ```typescript + * // Returns the first item in the title field arrays, or returns + * // "Default Title" + * ifError(field("title").arrayOffset(0), "Default Title"); + * ``` + * + * @param tryExpr The try expression. + * @param catchValue The value that will be returned if the tryExpr produces an + * error. + * @return A new {@code Expr} representing the 'ifError' operation. */ - export class ByteLength extends Function {} + export function ifError(tryExpr: Expr, catchValue: unknown): FunctionExpr; /** * @beta + * + * Creates an expression that returns `true` if a value is absent. Otherwise, + * returns `false` even if the value is `null`. + * + * ```typescript + * // Check if the field `value` is absent. + * isAbsent(field("value")); + * ``` + * + * @param value The expression to check. + * @return A new {@code Expr} representing the 'isAbsent' check. */ - export class MapGet extends Function {} + export function isAbsent(value: Expr): BooleanExpr; /** * @beta + * + * Creates an expression that returns `true` if a field is absent. Otherwise, + * returns `false` even if the field value is `null`. + * + * ```typescript + * // Check if the field `value` is absent. + * isAbsent("value"); + * ``` + * + * @param field The field to check. + * @return A new {@code Expr} representing the 'isAbsent' check. */ - export class Count extends Function implements Accumulator { - accumulator: true; - } + export function isAbsent(field: string): BooleanExpr; /** * @beta + * + * Creates an expression that checks if an expression evaluates to 'NaN' (Not a Number). + * + * ```typescript + * // Check if the result of a calculation is NaN + * isNaN(field("value").divide(0)); + * ``` + * + * @param value The expression to check. + * @return A new {@code Expr} representing the 'isNaN' check. */ - export class Sum extends Function implements Accumulator { - accumulator: true; - } + export function isNull(value: Expr): BooleanExpr; /** * @beta + * + * Creates an expression that checks if a field's value evaluates to 'NaN' (Not a Number). + * + * ```typescript + * // Check if the result of a calculation is NaN + * isNaN("value"); + * ``` + * + * @param value The name of the field to check. + * @return A new {@code Expr} representing the 'isNaN' check. */ - export class Avg extends Function implements Accumulator { - accumulator: true; - } + export function isNull(value: string): BooleanExpr; /** * @beta + * + * Creates an expression that checks if tbe result of an expression is not null. + * + * ```typescript + * // Check if the value of the 'name' field is not null + * isNotNull(field("name")); + * ``` + * + * @param value The expression to check. + * @return A new {@code Expr} representing the 'isNaN' check. */ - export class Minimum extends Function implements Accumulator { - accumulator: true; - } + export function isNotNull(value: Expr): BooleanExpr; /** * @beta + * + * Creates an expression that checks if tbe value of a field is not null. + * + * ```typescript + * // Check if the value of the 'name' field is not null + * isNotNull("name"); + * ``` + * + * @param value The name of the field to check. + * @return A new {@code Expr} representing the 'isNaN' check. */ - export class Maximim extends Function implements Accumulator { - accumulator: true; - } + export function isNotNull(value: string): BooleanExpr; /** * @beta + * + * Creates an expression that checks if the results of this expression is NOT 'NaN' (Not a Number). + * + * ```typescript + * // Check if the result of a calculation is NOT NaN + * isNotNaN(field("value").divide(0)); + * ``` + * + * @param value The expression to check. + * @return A new {@code Expr} representing the 'isNotNaN' check. */ - export class CosineDistance extends Function {} + export function isNotNan(value: Expr): BooleanExpr; /** * @beta + * + * Creates an expression that checks if the results of this expression is NOT 'NaN' (Not a Number). + * + * ```typescript + * // Check if the value of a field is NOT NaN + * isNotNaN("value"); + * ``` + * + * @param value The name of the field to check. + * @return A new {@code Expr} representing the 'isNotNaN' check. */ - export class DotProduct extends Function {} + export function isNotNan(value: string): BooleanExpr; /** * @beta + * + * Creates an expression that removes a key from the map at the specified field name. + * + * ``` + * // Removes the key 'city' field from the map in the address field of the input document. + * mapRemove('address', 'city'); + * ``` + * + * @param mapField The name of a field containing a map value. + * @param key The name of the key to remove from the input map. */ - export class EuclideanDistance extends Function {} - + export function mapRemove(mapField: string, key: string): FunctionExpr; /** * @beta + * + * Creates an expression that removes a key from the map produced by evaluating an expression. + * + * ``` + * // Removes the key 'baz' from the input map. + * mapRemove(map({foo: 'bar', baz: true}), 'baz'); + * ``` + * + * @param mapExpr An expression return a map value. + * @param key The name of the key to remove from the input map. */ - export class VectorLength extends Function {} - + export function mapRemove(mapExpr: Expr, key: string): FunctionExpr; /** * @beta + * + * Creates an expression that removes a key from the map at the specified field name. + * + * ``` + * // Removes the key 'city' field from the map in the address field of the input document. + * mapRemove('address', constant('city')); + * ``` + * + * @param mapField The name of a field containing a map value. + * @param keyExpr An expression that produces the name of the key to remove from the input map. */ - export class UnixMicrosToTimestamp extends Function {} - + export function mapRemove(mapField: string, keyExpr: Expr): FunctionExpr; /** * @beta + * + * Creates an expression that removes a key from the map produced by evaluating an expression. + * + * ``` + * // Removes the key 'baz' from the input map. + * mapRemove(map({foo: 'bar', baz: true}), constant('baz')); + * ``` + * + * @param mapExpr An expression return a map value. + * @param keyExpr An expression that produces the name of the key to remove from the input map. */ - export class TimestampToUnixMicros extends Function {} + export function mapRemove(mapExpr: Expr, keyExpr: Expr): FunctionExpr; /** * @beta + * + * Creates an expression that merges multiple map values. + * + * ``` + * // Merges the map in the settings field with, a map literal, and a map in + * // that is conditionally returned by another expression + * mapMerge('settings', { enabled: true }, cond(field('isAdmin'), { admin: true}, {}) + * ``` + * + * @param mapField Name of a field containing a map value that will be merged. + * @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. */ - export class UnixMillisToTimestamp extends Function {} + export function mapMerge( + mapField: string, + secondMap: Record | Expr, + ...otherMaps: Array | Expr> + ): FunctionExpr; /** * @beta + * + * Creates an expression that merges multiple map values. + * + * ``` + * // Merges the map in the settings field with, a map literal, and a map in + * // that is conditionally returned by another expression + * mapMerge(field('settings'), { enabled: true }, cond(field('isAdmin'), { admin: true}, {}) + * ``` + * + * @param firstMap An expression or literal map value that will be merged. + * @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. */ - export class TimestampToUnixMillis extends Function {} + export function mapMerge( + firstMap: Record | Expr, + secondMap: Record | Expr, + ...otherMaps: Array | Expr> + ): FunctionExpr; /** * @beta + * + * Creates an expression that returns the document ID from a path. + * + * ```typescript + * // Get the document ID from a path. + * documentId(myDocumentReference); + * ``` + * + * @return A new {@code Expr} representing the documentId operation. */ - export class UnixSecondsToTimestamp extends Function {} + export function documentId( + documentPath: string | DocumentReference + ): FunctionExpr; /** * @beta + * + * Creates an expression that returns the document ID from a path. + * + * ```typescript + * // Get the document ID from a path. + * documentId(field("__path__")); + * ``` + * + * @return A new {@code Expr} representing the documentId operation. */ - export class TimestampToUnixSeconds extends Function {} + export function documentId(documentPathExpr: Expr): FunctionExpr; /** * @beta + * + * Creates an expression that returns a substring of a string or byte array. + * + * @param field The name of a field containing a string or byte array to compute the substring from. + * @param position Index of the first character of the substring. + * @param length Length of the substring. */ - export class TimestampAdd extends Function {} + export function substr( + field: string, + position: number, + length?: number + ): FunctionExpr; /** * @beta + * + * Creates an expression that returns a substring of a string or byte array. + * + * @param input An expression returning a string or byte array to compute the substring from. + * @param position Index of the first character of the substring. + * @param length Length of the substring. */ - export class TimestampSub extends Function {} + export function substr( + input: Expr, + position: number, + length?: number + ): FunctionExpr; /** * @beta * - * Creates an expression that adds two expressions together. - * - * ```typescript - * // Add the value of the 'quantity' field and the 'reserve' field. - * add(Field.of("quantity"), Field.of("reserve")); - * ``` + * Creates an expression that returns a substring of a string or byte array. * - * @param left The first expression to add. - * @param right The second expression to add. - * @return A new {@code Expr} representing the addition operation. + * @param field The name of a field containing a string or byte array to compute the substring from. + * @param position An expression that returns the index of the first character of the substring. + * @param length An expression that returns the length of the substring. */ - export function add(left: Expr, right: Expr): Add; + export function substr( + field: string, + position: Expr, + length?: Expr + ): FunctionExpr; /** * @beta * - * Creates an expression that adds an expression to a constant value. + * Creates an expression that returns a substring of a string or byte array. * - * ```typescript - * // Add 5 to the value of the 'age' field - * add(Field.of("age"), 5); - * ``` - * - * @param left The expression to add to. - * @param right The constant value to add. - * @return A new {@code Expr} representing the addition operation. + * @param input An expression returning a string or byte array to compute the substring from. + * @param position An expression that returns the index of the first character of the substring. + * @param length An expression that returns the length of the substring. */ - export function add(left: Expr, right: any): Add; + export function substr( + input: Expr, + position: Expr, + length?: Expr + ): FunctionExpr; /** * @beta * - * Creates an expression that adds a field's value to an expression. + * Creates an expression that adds two expressions together. * * ```typescript * // Add the value of the 'quantity' field and the 'reserve' field. - * add("quantity", Field.of("reserve")); + * add(field("quantity"), field("reserve")); * ``` * - * @param left The field name to add to. - * @param right The expression to add. + * @param first The first expression to add. + * @param second The second expression or literal to add. + * @param others Optional other expressions or literals to add. * @return A new {@code Expr} representing the addition operation. */ - export function add(left: string, right: Expr): Add; + export function add( + first: Expr, + second: Expr | unknown, + ...others: Array + ): FunctionExpr; /** * @beta * - * Creates an expression that adds a field's value to a constant value. + * Creates an expression that adds a field's value to an expression. * * ```typescript - * // Add 5 to the value of the 'age' field - * add("age", 5); + * // Add the value of the 'quantity' field and the 'reserve' field. + * add("quantity", field("reserve")); * ``` * - * @param left The field name to add to. - * @param right The constant value to add. + * @param fieldName The name of the field containing the value to add. + * @param second The second expression or literal to add. + * @param others Optional other expressions or literals to add. * @return A new {@code Expr} representing the addition operation. */ - export function add(left: string, right: any): Add; + export function add( + fieldName: string, + second: Expr | unknown, + ...others: Array + ): FunctionExpr; /** * @beta @@ -5433,14 +6038,14 @@ declare namespace FirebaseFirestore { * * ```typescript * // Subtract the 'discount' field from the 'price' field - * subtract(Field.of("price"), Field.of("discount")); + * subtract(field("price"), field("discount")); * ``` * * @param left The expression to subtract from. * @param right The expression to subtract. * @return A new {@code Expr} representing the subtraction operation. */ - export function subtract(left: Expr, right: Expr): Subtract; + export function subtract(left: Expr, right: Expr): FunctionExpr; /** * @beta @@ -5449,14 +6054,14 @@ declare namespace FirebaseFirestore { * * ```typescript * // Subtract the constant value 2 from the 'value' field - * subtract(Field.of("value"), 2); + * subtract(field("value"), 2); * ``` * - * @param left The expression to subtract from. - * @param right The constant value to subtract. + * @param expression The expression to subtract from. + * @param value The constant value to subtract. * @return A new {@code Expr} representing the subtraction operation. */ - export function subtract(left: Expr, right: any): Subtract; + export function subtract(expression: Expr, value: unknown): FunctionExpr; /** * @beta @@ -5465,94 +6070,72 @@ declare namespace FirebaseFirestore { * * ```typescript * // Subtract the 'discount' field from the 'price' field - * subtract("price", Field.of("discount")); - * ``` - * - * @param left The field name to subtract from. - * @param right The expression to subtract. - * @return A new {@code Expr} representing the subtraction operation. - */ - export function subtract(left: string, right: Expr): Subtract; - - /** - * @beta - * - * Creates an expression that subtracts a constant value from a field's value. - * - * ```typescript - * // Subtract 20 from the value of the 'total' field - * subtract("total", 20); - * ``` - * - * @param left The field name to subtract from. - * @param right The constant value to subtract. - * @return A new {@code Expr} representing the subtraction operation. - */ - export function subtract(left: string, right: any): Subtract; - - /** - * @beta - * - * Creates an expression that multiplies two expressions together. - * - * ```typescript - * // Multiply the 'quantity' field by the 'price' field - * multiply(Field.of("quantity"), Field.of("price")); + * subtract("price", field("discount")); * ``` * - * @param left The first expression to multiply. - * @param right The second expression to multiply. - * @return A new {@code Expr} representing the multiplication operation. + * @param fieldName The field name to subtract from. + * @param expression The expression to subtract. + * @return A new {@code Expr} representing the subtraction operation. */ - export function multiply(left: Expr, right: Expr): Multiply; + export function subtract(fieldName: string, expression: Expr): FunctionExpr; /** * @beta * - * Creates an expression that multiplies an expression by a constant value. + * Creates an expression that subtracts a constant value from a field's value. * * ```typescript - * // Multiply the value of the 'price' field by 2 - * multiply(Field.of("price"), 2); + * // Subtract 20 from the value of the 'total' field + * subtract("total", 20); * ``` * - * @param left The expression to multiply. - * @param right The constant value to multiply by. - * @return A new {@code Expr} representing the multiplication operation. + * @param fieldName The field name to subtract from. + * @param value The constant value to subtract. + * @return A new {@code Expr} representing the subtraction operation. */ - export function multiply(left: Expr, right: any): Multiply; + export function subtract(fieldName: string, value: unknown): FunctionExpr; /** * @beta * - * Creates an expression that multiplies a field's value by an expression. + * Creates an expression that multiplies two expressions together. * * ```typescript * // Multiply the 'quantity' field by the 'price' field - * multiply("quantity", Field.of("price")); + * multiply(field("quantity"), field("price")); * ``` * - * @param left The field name to multiply. - * @param right The expression to multiply by. + * @param first The first expression to multiply. + * @param second The second expression or literal to multiply. + * @param others Optional additional expressions or literals to multiply. * @return A new {@code Expr} representing the multiplication operation. */ - export function multiply(left: string, right: Expr): Multiply; + export function multiply( + first: Expr, + second: Expr | unknown, + ...others: Array + ): FunctionExpr; /** * @beta * - * Creates an expression that multiplies a field's value by a constant value. + * Creates an expression that multiplies a field's value by an expression. * * ```typescript - * // Multiply the 'value' field by 2 - * multiply("value", 2); + * // Multiply the 'quantity' field by the 'price' field + * multiply("quantity", field("price")); * ``` * - * @param left The field name to multiply. - * @param right The constant value to multiply by. + * @param fieldName The name of the field containing the value to add. + * @param second The second expression or literal to add. + * @param others Optional other expressions or literals to add. * @return A new {@code Expr} representing the multiplication operation. */ - export function multiply(left: string, right: any): Multiply; + export function multiply( + fieldName: string, + second: Expr | unknown, + ...others: Array + ): FunctionExpr; /** * @beta @@ -5561,14 +6144,14 @@ declare namespace FirebaseFirestore { * * ```typescript * // Divide the 'total' field by the 'count' field - * divide(Field.of("total"), Field.of("count")); + * divide(field("total"), field("count")); * ``` * * @param left The expression to be divided. * @param right The expression to divide by. * @return A new {@code Expr} representing the division operation. */ - export function divide(left: Expr, right: Expr): Divide; + export function divide(left: Expr, right: Expr): FunctionExpr; /** * @beta @@ -5577,14 +6160,14 @@ declare namespace FirebaseFirestore { * * ```typescript * // Divide the 'value' field by 10 - * divide(Field.of("value"), 10); + * divide(field("value"), 10); * ``` * - * @param left The expression to be divided. - * @param right The constant value to divide by. + * @param expression The expression to be divided. + * @param value The constant value to divide by. * @return A new {@code Expr} representing the division operation. */ - export function divide(left: Expr, right: any): Divide; + export function divide(expression: Expr, value: unknown): FunctionExpr; /** * @beta @@ -5593,14 +6176,14 @@ declare namespace FirebaseFirestore { * * ```typescript * // Divide the 'total' field by the 'count' field - * divide("total", Field.of("count")); + * divide("total", field("count")); * ``` * - * @param left The field name to be divided. - * @param right The expression to divide by. + * @param fieldName The field name to be divided. + * @param expressions The expression to divide by. * @return A new {@code Expr} representing the division operation. */ - export function divide(left: string, right: Expr): Divide; + export function divide(fieldName: string, expressions: Expr): FunctionExpr; /** * @beta @@ -5612,11 +6195,11 @@ declare namespace FirebaseFirestore { * divide("value", 10); * ``` * - * @param left The field name to be divided. - * @param right The constant value to divide by. + * @param fieldName The field name to be divided. + * @param value The constant value to divide by. * @return A new {@code Expr} representing the division operation. */ - export function divide(left: string, right: any): Divide; + export function divide(fieldName: string, value: unknown): FunctionExpr; /** * @beta @@ -5625,14 +6208,14 @@ declare namespace FirebaseFirestore { * * ```typescript * // Calculate the remainder of dividing 'field1' by 'field2'. - * mod(Field.of("field1"), Field.of("field2")); + * mod(field("field1"), field("field2")); * ``` * * @param left The dividend expression. * @param right The divisor expression. * @return A new {@code Expr} representing the modulo operation. */ - export function mod(left: Expr, right: Expr): Mod; + export function mod(left: Expr, right: Expr): FunctionExpr; /** * @beta @@ -5641,14 +6224,14 @@ declare namespace FirebaseFirestore { * * ```typescript * // Calculate the remainder of dividing 'field1' by 5. - * mod(Field.of("field1"), 5); + * mod(field("field1"), 5); * ``` * - * @param left The dividend expression. - * @param right The divisor constant. + * @param expression The dividend expression. + * @param value The divisor constant. * @return A new {@code Expr} representing the modulo operation. */ - export function mod(left: Expr, right: any): Mod; + export function mod(expression: Expr, value: unknown): FunctionExpr; /** * @beta @@ -5657,14 +6240,14 @@ declare namespace FirebaseFirestore { * * ```typescript * // Calculate the remainder of dividing 'field1' by 'field2'. - * mod("field1", Field.of("field2")); + * mod("field1", field("field2")); * ``` * - * @param left The dividend field name. - * @param right The divisor expression. + * @param fieldName The dividend field name. + * @param expression The divisor expression. * @return A new {@code Expr} representing the modulo operation. */ - export function mod(left: string, right: Expr): Mod; + export function mod(fieldName: string, expression: Expr): FunctionExpr; /** * @beta @@ -5676,361 +6259,41 @@ declare namespace FirebaseFirestore { * mod("field1", 5); * ``` * - * @param left The dividend field name. - * @param right The divisor constant. + * @param fieldName The dividend field name. + * @param value The divisor constant. * @return A new {@code Expr} representing the modulo operation. */ - export function mod(left: string, right: any): Mod; - - // /** - // * @beta - // * - // * Creates an expression that applies a bitwise AND operation between two expressions. - // * - // * ```typescript - // * // Calculate the bitwise AND of 'field1' and 'field2'. - // * bitAnd(Field.of("field1"), Field.of("field2")); - // * ``` - // * - // * @param left The left operand expression. - // * @param right The right operand expression. - // * @return A new {@code Expr} representing the bitwise AND operation. - // */ - // export function bitAnd(left: Expr, right: Expr): BitAnd; - // - // /** - // * @beta - // * - // * Creates an expression that applies a bitwise AND operation between an expression and a constant. - // * - // * ```typescript - // * // Calculate the bitwise AND of 'field1' and 0xFF. - // * bitAnd(Field.of("field1"), 0xFF); - // * ``` - // * - // * @param left The left operand expression. - // * @param right The right operand constant. - // * @return A new {@code Expr} representing the bitwise AND operation. - // */ - // export function bitAnd(left: Expr, right: any): BitAnd; - // - // /** - // * @beta - // * - // * Creates an expression that applies a bitwise AND operation between a field and an expression. - // * - // * ```typescript - // * // Calculate the bitwise AND of 'field1' and 'field2'. - // * bitAnd("field1", Field.of("field2")); - // * ``` - // * - // * @param left The left operand field name. - // * @param right The right operand expression. - // * @return A new {@code Expr} representing the bitwise AND operation. - // */ - // export function bitAnd(left: string, right: Expr): BitAnd; - // - // /** - // * @beta - // * - // * Creates an expression that applies a bitwise AND operation between a field and a constant. - // * - // * ```typescript - // * // Calculate the bitwise AND of 'field1' and 0xFF. - // * bitAnd("field1", 0xFF); - // * ``` - // * - // * @param left The left operand field name. - // * @param right The right operand constant. - // * @return A new {@code Expr} representing the bitwise AND operation. - // */ - // export function bitAnd(left: string, right: any): BitAnd; - // - // /** - // * @beta - // * - // * Creates an expression that applies a bitwise OR operation between two expressions. - // * - // * ```typescript - // * // Calculate the bitwise OR of 'field1' and 'field2'. - // * bitOr(Field.of("field1"), Field.of("field2")); - // * ``` - // * - // * @param left The left operand expression. - // * @param right The right operand expression. - // * @return A new {@code Expr} representing the bitwise OR operation. - // */ - // export function bitOr(left: Expr, right: Expr): BitOr; - // - // /** - // * @beta - // * - // * Creates an expression that applies a bitwise OR operation between an expression and a constant. - // * - // * ```typescript - // * // Calculate the bitwise OR of 'field1' and 0xFF. - // * bitOr(Field.of("field1"), 0xFF); - // * ``` - // * - // * @param left The left operand expression. - // * @param right The right operand constant. - // * @return A new {@code Expr} representing the bitwise OR operation. - // */ - // export function bitOr(left: Expr, right: any): BitOr; - // - // /** - // * @beta - // * - // * Creates an expression that applies a bitwise OR operation between a field and an expression. - // * - // * ```typescript - // * // Calculate the bitwise OR of 'field1' and 'field2'. - // * bitOr("field1", Field.of("field2")); - // * ``` - // * - // * @param left The left operand field name. - // * @param right The right operand expression. - // * @return A new {@code Expr} representing the bitwise OR operation. - // */ - // export function bitOr(left: string, right: Expr): BitOr; - // - // /** - // * @beta - // * - // * Creates an expression that applies a bitwise OR operation between a field and a constant. - // * - // * ```typescript - // * // Calculate the bitwise OR of 'field1' and 0xFF. - // * bitOr("field1", 0xFF); - // * ``` - // * - // * @param left The left operand field name. - // * @param right The right operand constant. - // * @return A new {@code Expr} representing the bitwise OR operation. - // */ - // export function bitOr(left: string, right: any): BitOr; - // - // /** - // * @beta - // * - // * Creates an expression that applies a bitwise XOR operation between two expressions. - // * - // * ```typescript - // * // Calculate the bitwise XOR of 'field1' and 'field2'. - // * bitXor(Field.of("field1"), Field.of("field2")); - // * ``` - // * - // * @param left The left operand expression. - // * @param right The right operand expression. - // * @return A new {@code Expr} representing the bitwise XOR operation. - // */ - // export function bitXor(left: Expr, right: Expr): BitXor; - // - // /** - // * @beta - // * - // * Creates an expression that applies a bitwise XOR operation between an expression and a constant. - // * - // * ```typescript - // * // Calculate the bitwise XOR of 'field1' and 0xFF. - // * bitXor(Field.of("field1"), 0xFF); - // * ``` - // * - // * @param left The left operand expression. - // * @param right The right operand constant. - // * @return A new {@code Expr} representing the bitwise XOR operation. - // */ - // export function bitXor(left: Expr, right: any): BitXor; - // - // /** - // * @beta - // * - // * Creates an expression that applies a bitwise XOR operation between a field and an expression. - // * - // * ```typescript - // * // Calculate the bitwise XOR of 'field1' and 'field2'. - // * bitXor("field1", Field.of("field2")); - // * ``` - // * - // * @param left The left operand field name. - // * @param right The right operand expression. - // * @return A new {@code Expr} representing the bitwise XOR operation. - // */ - // export function bitXor(left: string, right: Expr): BitXor; - // - // /** - // * @beta - // * - // * Creates an expression that applies a bitwise XOR operation between a field and a constant. - // * - // * ```typescript - // * // Calculate the bitwise XOR of 'field1' and 0xFF. - // * bitXor("field1", 0xFF); - // * ``` - // * - // * @param left The left operand field name. - // * @param right The right operand constant. - // * @return A new {@code Expr} representing the bitwise XOR operation. - // */ - // export function bitXor(left: string, right: any): BitXor; - // - // /** - // * @beta - // * - // * Creates an expression that applies a bitwise NOT operation to an expression. - // * - // * ```typescript - // * // Calculate the bitwise NOT of 'field1'. - // * bitNot(Field.of("field1")); - // * ``` - // * - // * @param operand The operand expression. - // * @return A new {@code Expr} representing the bitwise NOT operation. - // */ - // export function bitNot(operand: Expr): BitNot; - // - // /** - // * @beta - // * - // * Creates an expression that applies a bitwise NOT operation to a field. - // * - // * ```typescript - // * // Calculate the bitwise NOT of 'field1'. - // * bitNot("field1"); - // * ``` - // * - // * @param operand The operand field name. - // * @return A new {@code Expr} representing the bitwise NOT operation. - // */ - // export function bitNot(operand: string): BitNot; - // - // /** - // * @beta - // * - // * Creates an expression that applies a bitwise left shift operation between two expressions. - // * - // * ```typescript - // * // Calculate the bitwise left shift of 'field1' by 'field2' bits. - // * bitLeftShift(Field.of("field1"), Field.of("field2")); - // * ``` - // * - // * @param left The left operand expression. - // * @param right The right operand expression representing the number of bits to shift. - // * @return A new {@code Expr} representing the bitwise left shift operation. - // */ - // export function bitLeftShift(left: Expr, right: Expr): BitLeftShift; - // - // /** - // * @beta - // * - // * Creates an expression that applies a bitwise left shift operation between an expression and a constant. - // * - // * ```typescript - // * // Calculate the bitwise left shift of 'field1' by 2 bits. - // * bitLeftShift(Field.of("field1"), 2); - // * ``` - // * - // * @param left The left operand expression. - // * @param right The right operand constant representing the number of bits to shift. - // * @return A new {@code Expr} representing the bitwise left shift operation. - // */ - // export function bitLeftShift(left: Expr, right: any): BitLeftShift; - // - // /** - // * @beta - // * - // * Creates an expression that applies a bitwise left shift operation between a field and an expression. - // * - // * ```typescript - // * // Calculate the bitwise left shift of 'field1' by 'field2' bits. - // * bitLeftShift("field1", Field.of("field2")); - // * ``` - // * - // * @param left The left operand field name. - // * @param right The right operand expression representing the number of bits to shift. - // * @return A new {@code Expr} representing the bitwise left shift operation. - // */ - // export function bitLeftShift(left: string, right: Expr): BitLeftShift; - // - // /** - // * @beta - // * - // * Creates an expression that applies a bitwise left shift operation between a field and a constant. - // * - // * ```typescript - // * // Calculate the bitwise left shift of 'field1' by 2 bits. - // * bitLeftShift("field1", 2); - // * ``` - // * - // * @param left The left operand field name. - // * @param right The right operand constant representing the number of bits to shift. - // * @return A new {@code Expr} representing the bitwise left shift operation. - // */ - // export function bitLeftShift(left: string, right: any): BitLeftShift; - // - // /** - // * @beta - // * - // * Creates an expression that applies a bitwise right shift operation between two expressions. - // * - // * ```typescript - // * // Calculate the bitwise right shift of 'field1' by 'field2' bits. - // * bitRightShift(Field.of("field1"), Field.of("field2")); - // * ``` - // * - // * @param left The left operand expression. - // * @param right The right operand expression representing the number of bits to shift. - // * @return A new {@code Expr} representing the bitwise right shift operation. - // */ - // export function bitRightShift(left: Expr, right: Expr): BitRightShift; - // - // /** - // * @beta - // * - // * Creates an expression that applies a bitwise right shift operation between an expression and a constant. - // * - // * ```typescript - // * // Calculate the bitwise right shift of 'field1' by 2 bits. - // * bitRightShift(Field.of("field1"), 2); - // * ``` - // * - // * @param left The left operand expression. - // * @param right The right operand constant representing the number of bits to shift. - // * @return A new {@code Expr} representing the bitwise right shift operation. - // */ - // export function bitRightShift(left: Expr, right: any): BitRightShift; - // - // /** - // * @beta - // * - // * Creates an expression that applies a bitwise right shift operation between a field and an expression. - // * - // * ```typescript - // * // Calculate the bitwise right shift of 'field1' by 'field2' bits. - // * bitRightShift("field1", Field.of("field2")); - // * ``` - // * - // * @param left The left operand field name. - // * @param right The right operand expression representing the number of bits to shift. - // * @return A new {@code Expr} representing the bitwise right shift operation. - // */ - // export function bitRightShift(left: string, right: Expr): BitRightShift; - // - // /** - // * @beta - // * - // * Creates an expression that applies a bitwise right shift operation between a field and a constant. - // * - // * ```typescript - // * // Calculate the bitwise right shift of 'field1' by 2 bits. - // * bitRightShift("field1", 2); - // * ``` - // * - // * @param left The left operand field name. - // * @param right The right operand constant representing the number of bits to shift. - // * @return A new {@code Expr} representing the bitwise right shift operation. - // */ - // export function bitRightShift(left: string, right: any): BitRightShift; + export function mod(fieldName: string, value: unknown): FunctionExpr; + + /** + * @beta + * + * Creates an expression that creates a Firestore map value from an input object. + * + * ```typescript + * // Create a map from the input object and reference the 'baz' field value from the input document. + * map({foo: 'bar', baz: Field.of('baz')}).as('data'); + * ``` + * + * @param elements The input map to evaluate in the expression. + * @return A new {@code Expr} representing the map function. + */ + export function map(elements: Record): FunctionExpr; + + /** + * @beta + * + * Creates an expression that creates a Firestore array value from an input array. + * + * ```typescript + * // Create an array value from the input array and reference the 'baz' field value from the input document. + * array(['bar', Field.of('baz')]).as('foo'); + * ``` + * + * @param elements The input array to evaluate in the expression. + * @return A new {@code Expr} representing the array function. + */ + export function array(elements: unknown[]): FunctionExpr; /** * @beta @@ -6039,14 +6302,14 @@ declare namespace FirebaseFirestore { * * ```typescript * // Check if the 'age' field is equal to an expression - * eq(Field.of("age"), Field.of("minAge").add(10)); + * eq(field("age"), field("minAge").add(10)); * ``` * * @param left The first expression to compare. * @param right The second expression to compare. * @return A new `Expr` representing the equality comparison. */ - export function eq(left: Expr, right: Expr): Eq; + export function eq(left: Expr, right: Expr): BooleanExpr; /** * @beta @@ -6055,14 +6318,14 @@ declare namespace FirebaseFirestore { * * ```typescript * // Check if the 'age' field is equal to 21 - * eq(Field.of("age"), 21); + * eq(field("age"), 21); * ``` * - * @param left The expression to compare. - * @param right The constant value to compare to. + * @param expression The expression to compare. + * @param value The constant value to compare to. * @return A new `Expr` representing the equality comparison. */ - export function eq(left: Expr, right: any): Eq; + export function eq(expression: Expr, value: unknown): BooleanExpr; /** * @beta @@ -6071,14 +6334,14 @@ declare namespace FirebaseFirestore { * * ```typescript * // Check if the 'age' field is equal to the 'limit' field - * eq("age", Field.of("limit")); + * eq("age", field("limit")); * ``` * - * @param left The field name to compare. - * @param right The expression to compare to. + * @param fieldName The field name to compare. + * @param expression The expression to compare to. * @return A new `Expr` representing the equality comparison. */ - export function eq(left: string, right: Expr): Eq; + export function eq(fieldName: string, expression: Expr): BooleanExpr; /** * @beta @@ -6090,11 +6353,11 @@ declare namespace FirebaseFirestore { * eq("city", "London"); * ``` * - * @param left The field name to compare. - * @param right The constant value to compare to. + * @param fieldName The field name to compare. + * @param value The constant value to compare to. * @return A new `Expr` representing the equality comparison. */ - export function eq(left: string, right: any): Eq; + export function eq(fieldName: string, value: unknown): BooleanExpr; /** * @beta @@ -6103,14 +6366,14 @@ declare namespace FirebaseFirestore { * * ```typescript * // Check if the 'status' field is not equal to field 'finalState' - * neq(Field.of("status"), Field.of("finalState")); + * neq(field("status"), field("finalState")); * ``` * * @param left The first expression to compare. * @param right The second expression to compare. * @return A new `Expr` representing the inequality comparison. */ - export function neq(left: Expr, right: Expr): Neq; + export function neq(left: Expr, right: Expr): BooleanExpr; /** * @beta @@ -6119,14 +6382,14 @@ declare namespace FirebaseFirestore { * * ```typescript * // Check if the 'status' field is not equal to "completed" - * neq(Field.of("status"), "completed"); + * neq(field("status"), "completed"); * ``` * - * @param left The expression to compare. - * @param right The constant value to compare to. + * @param expression The expression to compare. + * @param value The constant value to compare to. * @return A new `Expr` representing the inequality comparison. */ - export function neq(left: Expr, right: any): Neq; + export function neq(expression: Expr, value: unknown): BooleanExpr; /** * @beta @@ -6135,14 +6398,14 @@ declare namespace FirebaseFirestore { * * ```typescript * // Check if the 'status' field is not equal to the value of 'expectedStatus' - * neq("status", Field.of("expectedStatus")); + * neq("status", field("expectedStatus")); * ``` * - * @param left The field name to compare. - * @param right The expression to compare to. + * @param fieldName The field name to compare. + * @param expression The expression to compare to. * @return A new `Expr` representing the inequality comparison. */ - export function neq(left: string, right: Expr): Neq; + export function neq(fieldName: string, expression: Expr): BooleanExpr; /** * @beta @@ -6154,11 +6417,11 @@ declare namespace FirebaseFirestore { * neq("country", "USA"); * ``` * - * @param left The field name to compare. - * @param right The constant value to compare to. + * @param fieldName The field name to compare. + * @param value The constant value to compare to. * @return A new `Expr` representing the inequality comparison. */ - export function neq(left: string, right: any): Neq; + export function neq(fieldName: string, value: unknown): BooleanExpr; /** * @beta @@ -6167,14 +6430,14 @@ declare namespace FirebaseFirestore { * * ```typescript * // Check if the 'age' field is less than 30 - * lt(Field.of("age"), Field.of("limit")); + * lt(field("age"), field("limit")); * ``` * * @param left The first expression to compare. * @param right The second expression to compare. * @return A new `Expr` representing the less than comparison. */ - export function lt(left: Expr, right: Expr): Lt; + export function lt(left: Expr, right: Expr): BooleanExpr; /** * @beta @@ -6183,14 +6446,14 @@ declare namespace FirebaseFirestore { * * ```typescript * // Check if the 'age' field is less than 30 - * lt(Field.of("age"), 30); + * lt(field("age"), 30); * ``` * - * @param left The expression to compare. - * @param right The constant value to compare to. + * @param expression The expression to compare. + * @param value The constant value to compare to. * @return A new `Expr` representing the less than comparison. */ - export function lt(left: Expr, right: any): Lt; + export function lt(expression: Expr, value: unknown): BooleanExpr; /** * @beta @@ -6199,14 +6462,14 @@ declare namespace FirebaseFirestore { * * ```typescript * // Check if the 'age' field is less than the 'limit' field - * lt("age", Field.of("limit")); + * lt("age", field("limit")); * ``` * - * @param left The field name to compare. - * @param right The expression to compare to. + * @param fieldName The field name to compare. + * @param expression The expression to compare to. * @return A new `Expr` representing the less than comparison. */ - export function lt(left: string, right: Expr): Lt; + export function lt(fieldName: string, expression: Expr): BooleanExpr; /** * @beta @@ -6218,11 +6481,11 @@ declare namespace FirebaseFirestore { * lt("price", 50); * ``` * - * @param left The field name to compare. - * @param right The constant value to compare to. + * @param fieldName The field name to compare. + * @param value The constant value to compare to. * @return A new `Expr` representing the less than comparison. */ - export function lt(left: string, right: any): Lt; + export function lt(fieldName: string, value: unknown): BooleanExpr; /** * @beta @@ -6232,14 +6495,14 @@ declare namespace FirebaseFirestore { * * ```typescript * // Check if the 'quantity' field is less than or equal to 20 - * lte(Field.of("quantity"), Field.of("limit")); + * lte(field("quantity"), field("limit")); * ``` * * @param left The first expression to compare. * @param right The second expression to compare. * @return A new `Expr` representing the less than or equal to comparison. */ - export function lte(left: Expr, right: Expr): Lte; + export function lte(left: Expr, right: Expr): BooleanExpr; /** * @beta @@ -6248,28 +6511,28 @@ declare namespace FirebaseFirestore { * * ```typescript * // Check if the 'quantity' field is less than or equal to 20 - * lte(Field.of("quantity"), 20); + * lte(field("quantity"), 20); * ``` * - * @param left The expression to compare. - * @param right The constant value to compare to. + * @param expression The expression to compare. + * @param value The constant value to compare to. * @return A new `Expr` representing the less than or equal to comparison. */ - export function lte(left: Expr, right: any): Lte; + export function lte(expression: Expr, value: unknown): BooleanExpr; /** * Creates an expression that checks if a field's value is less than or equal to an expression. * * ```typescript * // Check if the 'quantity' field is less than or equal to the 'limit' field - * lte("quantity", Field.of("limit")); + * lte("quantity", field("limit")); * ``` * - * @param left The field name to compare. - * @param right The expression to compare to. + * @param fieldName The field name to compare. + * @param expression The expression to compare to. * @return A new `Expr` representing the less than or equal to comparison. */ - export function lte(left: string, right: Expr): Lte; + export function lte(fieldName: string, expression: Expr): BooleanExpr; /** * @beta @@ -6281,11 +6544,11 @@ declare namespace FirebaseFirestore { * lte("score", 70); * ``` * - * @param left The field name to compare. - * @param right The constant value to compare to. + * @param fieldName The field name to compare. + * @param value The constant value to compare to. * @return A new `Expr` representing the less than or equal to comparison. */ - export function lte(left: string, right: any): Lte; + export function lte(fieldName: string, value: unknown): BooleanExpr; /** * @beta @@ -6295,14 +6558,14 @@ declare namespace FirebaseFirestore { * * ```typescript * // Check if the 'age' field is greater than 18 - * gt(Field.of("age"), Constant(9).add(9)); + * gt(field("age"), Constant(9).add(9)); * ``` * * @param left The first expression to compare. * @param right The second expression to compare. * @return A new `Expr` representing the greater than comparison. */ - export function gt(left: Expr, right: Expr): Gt; + export function gt(left: Expr, right: Expr): BooleanExpr; /** * @beta @@ -6311,14 +6574,14 @@ declare namespace FirebaseFirestore { * * ```typescript * // Check if the 'age' field is greater than 18 - * gt(Field.of("age"), 18); + * gt(field("age"), 18); * ``` * - * @param left The expression to compare. - * @param right The constant value to compare to. + * @param expression The expression to compare. + * @param value The constant value to compare to. * @return A new `Expr` representing the greater than comparison. */ - export function gt(left: Expr, right: any): Gt; + export function gt(expression: Expr, value: unknown): BooleanExpr; /** * @beta @@ -6327,14 +6590,14 @@ declare namespace FirebaseFirestore { * * ```typescript * // Check if the value of field 'age' is greater than the value of field 'limit' - * gt("age", Field.of("limit")); + * gt("age", field("limit")); * ``` * - * @param left The field name to compare. - * @param right The expression to compare to. + * @param fieldName The field name to compare. + * @param expression The expression to compare to. * @return A new `Expr` representing the greater than comparison. */ - export function gt(left: string, right: Expr): Gt; + export function gt(fieldName: string, expression: Expr): BooleanExpr; /** * @beta @@ -6346,11 +6609,11 @@ declare namespace FirebaseFirestore { * gt("price", 100); * ``` * - * @param left The field name to compare. - * @param right The constant value to compare to. + * @param fieldName The field name to compare. + * @param value The constant value to compare to. * @return A new `Expr` representing the greater than comparison. */ - export function gt(left: string, right: any): Gt; + export function gt(fieldName: string, value: unknown): BooleanExpr; /** * @beta @@ -6360,14 +6623,14 @@ declare namespace FirebaseFirestore { * * ```typescript * // Check if the 'quantity' field is greater than or equal to the field "threshold" - * gte(Field.of("quantity"), Field.of("threshold")); + * gte(field("quantity"), field("threshold")); * ``` * * @param left The first expression to compare. * @param right The second expression to compare. * @return A new `Expr` representing the greater than or equal to comparison. */ - export function gte(left: Expr, right: Expr): Gte; + export function gte(left: Expr, right: Expr): BooleanExpr; /** * @beta @@ -6377,14 +6640,14 @@ declare namespace FirebaseFirestore { * * ```typescript * // Check if the 'quantity' field is greater than or equal to 10 - * gte(Field.of("quantity"), 10); + * gte(field("quantity"), 10); * ``` * - * @param left The expression to compare. - * @param right The constant value to compare to. + * @param expression The expression to compare. + * @param value The constant value to compare to. * @return A new `Expr` representing the greater than or equal to comparison. */ - export function gte(left: Expr, right: any): Gte; + export function gte(expression: Expr, value: unknown): BooleanExpr; /** * @beta @@ -6393,14 +6656,14 @@ declare namespace FirebaseFirestore { * * ```typescript * // Check if the value of field 'age' is greater than or equal to the value of field 'limit' - * gte("age", Field.of("limit")); + * gte("age", field("limit")); * ``` * - * @param left The field name to compare. - * @param right The expression to compare to. + * @param fieldName The field name to compare. + * @param value The expression to compare to. * @return A new `Expr` representing the greater than or equal to comparison. */ - export function gte(left: string, right: Expr): Gte; + export function gte(fieldName: string, value: Expr): BooleanExpr; /** * @beta @@ -6413,11 +6676,11 @@ declare namespace FirebaseFirestore { * gte("score", 80); * ``` * - * @param left The field name to compare. - * @param right The constant value to compare to. + * @param fieldName The field name to compare. + * @param value The constant value to compare to. * @return A new `Expr` representing the greater than or equal to comparison. */ - export function gte(left: string, right: any): Gte; + export function gte(fieldName: string, value: unknown): BooleanExpr; /** * @beta @@ -6426,30 +6689,19 @@ declare namespace FirebaseFirestore { * * ```typescript * // Combine the 'items' array with two new item arrays - * arrayConcat(Field.of("items"), [Field.of("newItems"), Field.of("otherItems")]); - * ``` - * - * @param array The array expression to concatenate to. - * @param elements The array expressions to concatenate. - * @return A new {@code Expr} representing the concatenated array. - */ - export function arrayConcat(array: Expr, elements: Expr[]): ArrayConcat; - - /** - * @beta - * - * Creates an expression that concatenates an array expression with other arrays and/or values. - * - * ```typescript - * // Combine the 'tags' array with a new array - * arrayConcat(Field.of("tags"), ["newTag1", "newTag2"]); + * arrayConcat(field("items"), [field("newItems"), field("otherItems")]); * ``` * - * @param array The array expression to concatenate to. - * @param elements The array expressions or single values to concatenate. + * @param firstArray The first array expression to concatenate to. + * @param secondArray The second array expression or array literal to concatenate to. + * @param otherArrays Optional additional array expressions or array literals to concatenate. * @return A new {@code Expr} representing the concatenated array. */ - export function arrayConcat(array: Expr, elements: any[]): ArrayConcat; + export function arrayConcat( + firstArray: Expr, + secondArray: Expr | unknown[], + ...otherArrays: Array + ): FunctionExpr; /** * @beta @@ -6458,30 +6710,19 @@ declare namespace FirebaseFirestore { * * ```typescript * // Combine the 'items' array with two new item arrays - * arrayConcat("items", [Field.of("newItems"), Field.of("otherItems")]); - * ``` - * - * @param array The field name containing array values. - * @param elements The array expressions to concatenate. - * @return A new {@code Expr} representing the concatenated array. - */ - export function arrayConcat(array: string, elements: Expr[]): ArrayConcat; - - /** - * @beta - * - * Creates an expression that concatenates a field's array value with other arrays and/or values. - * - * ```typescript - * // Combine the 'tags' array with a new array - * arrayConcat("tags", ["newTag1", "newTag2"]); + * arrayConcat("items", [field("newItems"), field("otherItems")]); * ``` * - * @param array The field name containing array values. - * @param elements The array expressions or single values to concatenate. + * @param firstArrayField The first array to concatenate to. + * @param secondArray The second array expression or array literal to concatenate to. + * @param otherArrays Optional additional array expressions or array literals to concatenate. * @return A new {@code Expr} representing the concatenated array. */ - export function arrayConcat(array: string, elements: any[]): ArrayConcat; + export function arrayConcat( + firstArrayField: string, + secondArray: Expr | unknown[], + ...otherArrays: Array + ): FunctionExpr; /** * @beta @@ -6490,14 +6731,14 @@ declare namespace FirebaseFirestore { * * ```typescript * // Check if the 'colors' array contains the value of field 'selectedColor' - * arrayContains(Field.of("colors"), Field.of("selectedColor")); + * arrayContains(field("colors"), field("selectedColor")); * ``` * * @param array The array expression to check. * @param element The element to search for in the array. * @return A new {@code Expr} representing the 'array_contains' comparison. */ - export function arrayContains(array: Expr, element: Expr): ArrayContains; + export function arrayContains(array: Expr, element: Expr): FunctionExpr; /** * @beta @@ -6506,14 +6747,14 @@ declare namespace FirebaseFirestore { * * ```typescript * // Check if the 'colors' array contains "red" - * arrayContains(Field.of("colors"), "red"); + * arrayContains(field("colors"), "red"); * ``` * * @param array The array expression to check. * @param element The element to search for in the array. * @return A new {@code Expr} representing the 'array_contains' comparison. */ - export function arrayContains(array: Expr, element: any): ArrayContains; + export function arrayContains(array: Expr, element: unknown): FunctionExpr; /** * @beta @@ -6522,14 +6763,14 @@ declare namespace FirebaseFirestore { * * ```typescript * // Check if the 'colors' array contains the value of field 'selectedColor' - * arrayContains("colors", Field.of("selectedColor")); + * arrayContains("colors", field("selectedColor")); * ``` * - * @param array The field name to check. + * @param fieldName The field name to check. * @param element The element to search for in the array. * @return A new {@code Expr} representing the 'array_contains' comparison. */ - export function arrayContains(array: string, element: Expr): ArrayContains; + export function arrayContains(fieldName: string, element: Expr): FunctionExpr; /** * @beta @@ -6541,11 +6782,14 @@ declare namespace FirebaseFirestore { * arrayContains("colors", "red"); * ``` * - * @param array The field name to check. + * @param fieldName The field name to check. * @param element The element to search for in the array. * @return A new {@code Expr} representing the 'array_contains' comparison. */ - export function arrayContains(array: string, element: any): ArrayContains; + export function arrayContains( + fieldName: string, + element: unknown + ): BooleanExpr; /** * @beta @@ -6555,7 +6799,7 @@ declare namespace FirebaseFirestore { * * ```typescript * // Check if the 'categories' array contains either values from field "cate1" or "Science" - * arrayContainsAny(Field.of("categories"), [Field.of("cate1"), "Science"]); + * arrayContainsAny(field("categories"), [field("cate1"), "Science"]); * ``` * * @param array The array expression to check. @@ -6564,49 +6808,46 @@ declare namespace FirebaseFirestore { */ export function arrayContainsAny( array: Expr, - values: Expr[] - ): ArrayContainsAny; + values: Array + ): BooleanExpr; /** * @beta * - * Creates an expression that checks if an array expression contains any of the specified + * Creates an expression that checks if a field's array value contains any of the specified * elements. * * ```typescript - * // Check if the 'categories' array contains either values from field "cate1" or "Science" - * arrayContainsAny(Field.of("categories"), [Field.of("cate1"), "Science"]); + * // Check if the 'groups' array contains either the value from the 'userGroup' field + * // or the value "guest" + * arrayContainsAny("categories", [field("cate1"), "Science"]); * ``` * - * @param array The array expression to check. + * @param fieldName The field name to check. * @param values The elements to check for in the array. * @return A new {@code Expr} representing the 'array_contains_any' comparison. */ export function arrayContainsAny( - array: Expr, - values: any[] - ): ArrayContainsAny; + fieldName: string, + values: Array + ): BooleanExpr; /** * @beta * - * Creates an expression that checks if a field's array value contains any of the specified + * Creates an expression that checks if an array expression contains any of the specified * elements. * * ```typescript - * // Check if the 'groups' array contains either the value from the 'userGroup' field - * // or the value "guest" - * arrayContainsAny("categories", [Field.of("cate1"), "Science"]); + * // Check if the 'categories' array contains either values from field "cate1" or "Science" + * arrayContainsAny(field("categories"), array([field("cate1"), "Science"])); * ``` * - * @param array The field name to check. - * @param values The elements to check for in the array. + * @param array The array expression to check. + * @param values An expression that evaluates to an array, whose elements to check for in the array. * @return A new {@code Expr} representing the 'array_contains_any' comparison. */ - export function arrayContainsAny( - array: string, - values: Expr[] - ): ArrayContainsAny; + export function arrayContainsAny(array: Expr, values: Expr): BooleanExpr; /** * @beta @@ -6617,17 +6858,17 @@ declare namespace FirebaseFirestore { * ```typescript * // Check if the 'groups' array contains either the value from the 'userGroup' field * // or the value "guest" - * arrayContainsAny("categories", [Field.of("cate1"), "Science"]); + * arrayContainsAny("categories", array([field("cate1"), "Science"])); * ``` * - * @param array The field name to check. - * @param values The elements to check for in the array. + * @param fieldName The field name to check. + * @param values An expression that evaluates to an array, whose elements to check for in the array field. * @return A new {@code Expr} representing the 'array_contains_any' comparison. */ export function arrayContainsAny( - array: string, - values: any[] - ): ArrayContainsAny; + fieldName: string, + values: Expr + ): BooleanExpr; /** * @beta @@ -6635,8 +6876,8 @@ declare namespace FirebaseFirestore { * Creates an expression that checks if an array expression contains all the specified elements. * * ```typescript - * // Check if the 'tags' array contains both of the values from field 'tag1', 'tag2' and "tag3" - * arrayContainsAll(Field.of("tags"), [Field.of("tag1"), "SciFi", "Adventure"]); + * // Check if the "tags" array contains all of the values: "SciFi", "Adventure", and the value from field "tag1" + * arrayContainsAll(field("tags"), [field("tag1"), constant("SciFi"), "Adventure"]); * ``` * * @param array The array expression to check. @@ -6645,47 +6886,47 @@ declare namespace FirebaseFirestore { */ export function arrayContainsAll( array: Expr, - values: Expr[] - ): ArrayContainsAll; + values: Array + ): BooleanExpr; /** * @beta * - * Creates an expression that checks if an array expression contains all the specified elements. + * Creates an expression that checks if a field's array value contains all the specified values or + * expressions. * * ```typescript - * // Check if the 'tags' array contains both of the values from field 'tag1', 'tag2' and "tag3" - * arrayContainsAll(Field.of("tags"), [Field.of("tag1"), "SciFi", "Adventure"]); + * // Check if the 'tags' array contains both of the values from field 'tag1', the value "SciFi", and "Adventure" + * arrayContainsAll("tags", [field("tag1"), "SciFi", "Adventure"]); * ``` * - * @param array The array expression to check. + * @param fieldName The field name to check. * @param values The elements to check for in the array. * @return A new {@code Expr} representing the 'array_contains_all' comparison. */ export function arrayContainsAll( - array: Expr, - values: any[] - ): ArrayContainsAll; + fieldName: string, + values: Array + ): BooleanExpr; /** * @beta * - * Creates an expression that checks if a field's array value contains all the specified values or - * expressions. + * Creates an expression that checks if an array expression contains all the specified elements. * * ```typescript - * // Check if the 'tags' array contains both of the values from field 'tag1' and "tag2" - * arrayContainsAll("tags", [Field.of("tag1"), "SciFi", "Adventure"]); + * // Check if the "tags" array contains all of the values: "SciFi", "Adventure", and the value from field "tag1" + * arrayContainsAll(field("tags"), [field("tag1"), constant("SciFi"), "Adventure"]); * ``` * - * @param array The field name to check. - * @param values The elements to check for in the array. + * @param array The array expression to check. + * @param arrayExpression The elements to check for in the array. * @return A new {@code Expr} representing the 'array_contains_all' comparison. */ export function arrayContainsAll( - array: string, - values: Expr[] - ): ArrayContainsAll; + array: Expr, + arrayExpression: Expr + ): BooleanExpr; /** * @beta @@ -6694,84 +6935,84 @@ declare namespace FirebaseFirestore { * expressions. * * ```typescript - * // Check if the 'tags' array contains both of the values from field 'tag1' and "tag2" - * arrayContainsAll("tags", [Field.of("tag1"), "SciFi", "Adventure"]); + * // Check if the 'tags' array contains both of the values from field 'tag1', the value "SciFi", and "Adventure" + * arrayContainsAll("tags", [field("tag1"), "SciFi", "Adventure"]); * ``` * - * @param array The field name to check. - * @param values The elements to check for in the array. + * @param fieldName The field name to check. + * @param arrayExpression The elements to check for in the array. * @return A new {@code Expr} representing the 'array_contains_all' comparison. */ export function arrayContainsAll( - array: string, - values: any[] - ): ArrayContainsAll; + fieldName: string, + arrayExpression: Expr + ): BooleanExpr; /** * @beta * - * Creates an expression that calculates the length of an array expression. + * Creates an expression that calculates the length of an array in a specified field. * * ```typescript - * // Get the number of items in the 'cart' array - * arrayLength(Field.of("cart")); + * // Get the number of items in field 'cart' + * arrayLength('cart'); * ``` * - * @param array The array expression to calculate the length of. + * @param fieldName The name of the field containing an array to calculate the length of. * @return A new {@code Expr} representing the length of the array. */ - export function arrayLength(array: Expr): ArrayLength; + export function arrayLength(fieldName: string): FunctionExpr; /** * @beta * - * Creates an expression that checks if an expression is equal to any of the provided values or - * expressions. + * Creates an expression that calculates the length of an array expression. * * ```typescript - * // Check if the 'category' field is either "Electronics" or value of field 'primaryType' - * eqAny(Field.of("category"), [Constant.of("Electronics"), Field.of("primaryType")]); + * // Get the number of items in the 'cart' array + * arrayLength(field("cart")); * ``` * - * @param element The expression to compare. - * @param others The values to check against. - * @return A new {@code Expr} representing the 'IN' comparison. + * @param array The array expression to calculate the length of. + * @return A new {@code Expr} representing the length of the array. */ - export function eqAny(element: Expr, others: Expr[]): EqAny; + export function arrayLength(array: Expr): FunctionExpr; /** * @beta * - * Creates an expression that checks if an expression is equal to any of the provided values or + * Creates an expression that checks if an expression, when evaluated, is equal to any of the provided values or * expressions. * * ```typescript * // Check if the 'category' field is either "Electronics" or value of field 'primaryType' - * eqAny(Field.of("category"), ["Electronics", Field.of("primaryType")]); + * eqAny(field("category"), [constant("Electronics"), field("primaryType")]); * ``` * - * @param element The expression to compare. - * @param others The values to check against. + * @param expression The expression whose results to compare. + * @param values The values to check against. * @return A new {@code Expr} representing the 'IN' comparison. */ - export function eqAny(element: Expr, others: any[]): EqAny; + export function eqAny( + expression: Expr, + values: Array + ): BooleanExpr; /** * @beta * - * Creates an expression that checks if a field's value is equal to any of the provided values or - * expressions. + * Creates an expression that checks if an expression is equal to any of the provided values. * * ```typescript - * // Check if the 'category' field is either "Electronics" or value of field 'primaryType' - * eqAny("category", [Constant.of("Electronics"), Field.of("primaryType")]); + * // Check if the 'category' field is set to a value in the disabledCategories field + * eqAny(field("category"), field('disabledCategories')); * ``` * - * @param element The field to compare. - * @param others The values to check against. + * @param expression The expression whose results to compare. + * @param arrayExpression An expression that evaluates to an array, whose elements to check for equality to the input. * @return A new {@code Expr} representing the 'IN' comparison. */ - export function eqAny(element: string, others: Expr[]): EqAny; + export function eqAny(expression: Expr, arrayExpression: Expr): BooleanExpr; /** * @beta @@ -6781,31 +7022,34 @@ declare namespace FirebaseFirestore { * * ```typescript * // Check if the 'category' field is either "Electronics" or value of field 'primaryType' - * eqAny("category", ["Electronics", Field.of("primaryType")]); + * eqAny("category", [constant("Electronics"), field("primaryType")]); * ``` * - * @param element The field to compare. - * @param others The values to check against. + * @param fieldName The field to compare. + * @param values The values to check against. * @return A new {@code Expr} representing the 'IN' comparison. */ - export function eqAny(element: string, others: any[]): EqAny; + export function eqAny( + fieldName: string, + values: Array + ): BooleanExpr; /** * @beta * - * Creates an expression that checks if an expression is not equal to any of the provided values - * or expressions. + * Creates an expression that checks if a field's value is equal to any of the provided values or + * expressions. * * ```typescript - * // Check if the 'status' field is neither "pending" nor the value of 'rejectedStatus' - * notEqAny(Field.of("status"), [Constant.of("pending"), Field.of("rejectedStatus")]); + * // Check if the 'category' field is either "Electronics" or value of field 'primaryType' + * eqAny("category", ["Electronics", field("primaryType")]); * ``` * - * @param element The expression to compare. - * @param others The values to check against. - * @return A new {@code Expr} representing the 'NOT IN' comparison. + * @param fieldName The field to compare. + * @param arrayExpression An expression that evaluates to an array, whose elements to check for equality to the input field. + * @return A new {@code Expr} representing the 'IN' comparison. */ - export function notEqAny(element: Expr, others: Expr[]): NotEqAny; + export function eqAny(fieldName: string, arrayExpression: Expr): BooleanExpr; /** * @beta @@ -6815,14 +7059,17 @@ declare namespace FirebaseFirestore { * * ```typescript * // Check if the 'status' field is neither "pending" nor the value of 'rejectedStatus' - * notEqAny(Field.of("status"), ["pending", Field.of("rejectedStatus")]); + * notEqAny(field("status"), ["pending", field("rejectedStatus")]); * ``` * * @param element The expression to compare. - * @param others The values to check against. + * @param values The values to check against. * @return A new {@code Expr} representing the 'NOT IN' comparison. */ - export function notEqAny(element: Expr, others: any[]): NotEqAny; + export function notEqAny( + element: Expr, + values: Array + ): BooleanExpr; /** * @beta @@ -6832,71 +7079,58 @@ declare namespace FirebaseFirestore { * * ```typescript * // Check if the 'status' field is neither "pending" nor the value of 'rejectedStatus' - * notEqAny("status", [Constant.of("pending"), Field.of("rejectedStatus")]); + * notEqAny("status", [constant("pending"), field("rejectedStatus")]); * ``` * - * @param element The field name to compare. - * @param others The values to check against. + * @param fieldName The field name to compare. + * @param values The values to check against. * @return A new {@code Expr} representing the 'NOT IN' comparison. */ - export function notEqAny(element: string, others: Expr[]): NotEqAny; + export function notEqAny( + fieldName: string, + values: Array + ): BooleanExpr; /** * @beta * - * Creates an expression that checks if a field's value is not equal to any of the provided values + * Creates an expression that checks if an expression is not equal to any of the provided values * or expressions. * * ```typescript - * // Check if the 'status' field is neither "pending" nor the value of 'rejectedStatus' - * notEqAny("status", ["pending", Field.of("rejectedStatus")]); + * // Check if the 'status' field is neither "pending" nor the value of the field 'rejectedStatus' + * notEqAny(field("status"), ["pending", field("rejectedStatus")]); * ``` * - * @param element The field name to compare. - * @param others The values to check against. + * @param element The expression to compare. + * @param arrayExpression The values to check against. * @return A new {@code Expr} representing the 'NOT IN' comparison. */ - export function notEqAny(element: string, others: any[]): NotEqAny; - - /** - * @beta - * - * Creates an expression that performs a logical 'AND' operation on multiple filter conditions. - * - * ```typescript - * // Check if the 'age' field is greater than 18 AND the 'city' field is "London" AND - * // the 'status' field is "active" - * const condition = and(gt("age", 18), eq("city", "London"), eq("status", "active")); - * ``` - * - * @param left The first filter condition. - * @param right Additional filter conditions to 'AND' together. - * @return A new {@code Expr} representing the logical 'AND' operation. - */ - export function and(left: FilterExpr, ...right: FilterExpr[]): And; + export function notEqAny(element: Expr, arrayExpression: Expr): BooleanExpr; /** * @beta * - * Creates an expression that performs a logical 'OR' operation on multiple filter conditions. + * Creates an expression that checks if a field's value is not equal to any of the values in the evaluated expression. * * ```typescript - * // Check if the 'age' field is greater than 18 OR the 'city' field is "London" OR - * // the 'status' field is "active" - * const condition = or(gt("age", 18), eq("city", "London"), eq("status", "active")); + * // Check if the 'status' field is not equal to any value in the field 'rejectedStatuses' + * notEqAny("status", field("rejectedStatuses")); * ``` * - * @param left The first filter condition. - * @param right Additional filter conditions to 'OR' together. - * @return A new {@code Expr} representing the logical 'OR' operation. + * @param fieldName The field name to compare. + * @param arrayExpression The values to check against. + * @return A new {@code Expr} representing the 'NOT IN' comparison. */ - export function or(left: FilterExpr, ...right: FilterExpr[]): Or; + export function notEqAny( + fieldName: string, + arrayExpression: Expr + ): BooleanExpr; /** * @beta * - * Creates an expression that performs a logical 'XOR' (exclusive OR) operation on multiple filter - * conditions. + * Creates an expression that performs a logical 'XOR' (exclusive OR) operation on multiple BooleanExpressions. * * ```typescript * // Check if only one of the conditions is true: 'age' greater than 18, 'city' is "London", @@ -6907,11 +7141,16 @@ declare namespace FirebaseFirestore { * eq("status", "active")); * ``` * - * @param left The first filter condition. - * @param right Additional filter conditions to 'XOR' together. + * @param first The first condition. + * @param second The second condition. + * @param additionalConditions Additional conditions to 'XOR' together. * @return A new {@code Expr} representing the logical 'XOR' operation. */ - export function xor(left: FilterExpr, ...right: FilterExpr[]): Xor; + export function xor( + first: BooleanExpr, + second: BooleanExpr, + ...additionalConditions: BooleanExpr[] + ): BooleanExpr; /** * @beta @@ -6922,7 +7161,7 @@ declare namespace FirebaseFirestore { * ```typescript * // If 'age' is greater than 18, return "Adult"; otherwise, return "Minor". * cond( - * gt("age", 18), Constant.of("Adult"), Constant.of("Minor")); + * gt("age", 18), constant("Adult"), constant("Minor")); * ``` * * @param condition The condition to evaluate. @@ -6930,11 +7169,11 @@ declare namespace FirebaseFirestore { * @param elseExpr The expression to evaluate if the condition is false. * @return A new {@code Expr} representing the conditional expression. */ - export function ifFunction( - condition: FilterExpr, + export function cond( + condition: BooleanExpr, thenExpr: Expr, elseExpr: Expr - ): If; + ): FunctionExpr; /** * @beta @@ -6946,138 +7185,103 @@ declare namespace FirebaseFirestore { * not(eq("completed", true)); * ``` * - * @param filter The filter condition to negate. + * @param booleanExpr The filter condition to negate. * @return A new {@code Expr} representing the negated filter condition. */ - export function not(filter: FilterExpr): Not; - - /** - * @beta - * - * Creates an expression that returns the larger value between two expressions, based on Firestore's value type ordering. - * - * ```typescript - * // Returns the larger value between the 'timestamp' field and the current timestamp. - * logicalMaximum(Field.of("timestamp"), Function.currentTimestamp()); - * ``` - * - * @param left The left operand expression. - * @param right The right operand expression. - * @return A new {@code Expr} representing the logical maximum operation. - */ - export function logicalMaximum(left: Expr, right: Expr): LogicalMaximum; - - /** - * @beta - * - * Creates an expression that returns the larger value between an expression and a constant value, based on Firestore's value type ordering. - * - * ```typescript - * // Returns the larger value between the 'value' field and 10. - * logicalMaximum(Field.of("value"), 10); - * ``` - * - * @param left The left operand expression. - * @param right The right operand constant. - * @return A new {@code Expr} representing the logical maximum operation. - */ - export function logicalMaximum(left: Expr, right: any): LogicalMaximum; - - /** - * @beta - * - * Creates an expression that returns the larger value between a field and an expression, based on Firestore's value type ordering. - * - * ```typescript - * // Returns the larger value between the 'timestamp' field and the current timestamp. - * logicalMaximum("timestamp", Function.currentTimestamp()); - * ``` - * - * @param left The left operand field name. - * @param right The right operand expression. - * @return A new {@code Expr} representing the logical maximum operation. - */ - export function logicalMaximum(left: string, right: Expr): LogicalMaximum; - - /** - * @beta - * - * Creates an expression that returns the larger value between a field and a constant value, based on Firestore's value type ordering. - * - * ```typescript - * // Returns the larger value between the 'value' field and 10. - * logicalMaximum("value", 10); - * ``` - * - * @param left The left operand field name. - * @param right The right operand constant. - * @return A new {@code Expr} representing the logical maximum operation. - */ - export function logicalMaximum(left: string, right: any): LogicalMaximum; + export function not(booleanExpr: BooleanExpr): BooleanExpr; /** * @beta * - * Creates an expression that returns the smaller value between two expressions, based on Firestore's value type ordering. + * Creates an expression that returns the largest value between multiple input + * expressions or literal values. Based on Firestore's value type ordering. * * ```typescript - * // Returns the smaller value between the 'timestamp' field and the current timestamp. - * logicalMinimum(Field.of("timestamp"), Function.currentTimestamp()); + * // Returns the largest value between the 'field1' field, the 'field2' field, + * // and 1000 + * logicalMaximum(field("field1"), field("field2"), 1000); * ``` * - * @param left The left operand expression. - * @param right The right operand expression. - * @return A new {@code Expr} representing the logical minimum operation. + * @param first The first operand expression. + * @param second The second expression or literal. + * @param others Optional additional expressions or literals. + * @return A new {@code Expr} representing the logical max operation. */ - export function logicalMinimum(left: Expr, right: Expr): LogicalMinimum; + export function logicalMaximum( + first: Expr, + second: Expr | unknown, + ...others: Array + ): FunctionExpr; /** * @beta * - * Creates an expression that returns the smaller value between an expression and a constant value, based on Firestore's value type ordering. + * Creates an expression that returns the largest value between multiple input + * expressions or literal values. Based on Firestore's value type ordering. * * ```typescript - * // Returns the smaller value between the 'value' field and 10. - * logicalMinimum(Field.of("value"), 10); + * // Returns the largest value between the 'field1' field, the 'field2' field, + * // and 1000. + * logicalMaximum("field1", field("field2"), 1000); * ``` * - * @param left The left operand expression. - * @param right The right operand constant. - * @return A new {@code Expr} representing the logical minimum operation. + * @param fieldName The first operand field name. + * @param second The second expression or literal. + * @param others Optional additional expressions or literals. + * @return A new {@code Expr} representing the logical max operation. */ - export function logicalMinimum(left: Expr, right: any): LogicalMinimum; + export function logicalMaximum( + fieldName: string, + second: Expr | unknown, + ...others: Array + ): FunctionExpr; /** * @beta * - * Creates an expression that returns the smaller value between a field and an expression, based on Firestore's value type ordering. + * Creates an expression that returns the smallest value between multiple input + * expressions and literal values. Based on Firestore's value type ordering. * * ```typescript - * // Returns the smaller value between the 'timestamp' field and the current timestamp. - * logicalMinimum("timestamp", Function.currentTimestamp()); + * // Returns the smallest value between the 'field1' field, the 'field2' field, + * // and 1000. + * logicalMinimum(field("field1"), field("field2"), 1000); * ``` * - * @param left The left operand field name. - * @param right The right operand expression. - * @return A new {@code Expr} representing the logical minimum operation. + * @param first The first operand expression. + * @param second The second expression or literal. + * @param others Optional additional expressions or literals. + * @return A new {@code Expr} representing the logical min operation. */ - export function logicalMinimum(left: string, right: Expr): LogicalMinimum; + export function logicalMinimum( + first: Expr, + second: Expr | unknown, + ...others: Array + ): FunctionExpr; /** * @beta * - * Creates an expression that returns the smaller value between a field and a constant value, based on Firestore's value type ordering. + * Creates an expression that returns the smallest value between a field's value + * and other input expressions or literal values. + * Based on Firestore's value type ordering. * * ```typescript - * // Returns the smaller value between the 'value' field and 10. - * logicalMinimum("value", 10); + * // Returns the smallest value between the 'field1' field, the 'field2' field, + * // and 1000. + * logicalMinimum("field1", field("field2"), 1000); * ``` * - * @param left The left operand field name. - * @param right The right operand constant. - * @return A new {@code Expr} representing the logical minimum operation. + * @param fieldName The first operand field name. + * @param second The second expression or literal. + * @param others Optional additional expressions or literals. + * @return A new {@code Expr} representing the logical min operation. */ - export function logicalMinimum(left: string, right: any): LogicalMinimum; + export function logicalMinimum( + fieldName: string, + second: Expr | unknown, + ...others: Array + ): FunctionExpr; /** * @beta @@ -7086,13 +7290,13 @@ declare namespace FirebaseFirestore { * * ```typescript * // Check if the document has a field named "phoneNumber" - * exists(Field.of("phoneNumber")); + * exists(field("phoneNumber")); * ``` * * @param value An expression evaluates to the name of the field to check. * @return A new {@code Expr} representing the 'exists' check. */ - export function exists(value: Expr): Exists; + export function exists(value: Expr): BooleanExpr; /** * @beta @@ -7104,10 +7308,10 @@ declare namespace FirebaseFirestore { * exists("phoneNumber"); * ``` * - * @param field The field name to check. + * @param fieldName The field name to check. * @return A new {@code Expr} representing the 'exists' check. */ - export function exists(field: string): Exists; + export function exists(fieldName: string): BooleanExpr; /** * @beta @@ -7116,13 +7320,13 @@ declare namespace FirebaseFirestore { * * ```typescript * // Check if the result of a calculation is NaN - * isNaN(Field.of("value").divide(0)); + * isNaN(field("value").divide(0)); * ``` * * @param value The expression to check. * @return A new {@code Expr} representing the 'isNaN' check. */ - export function isNaN(value: Expr): IsNan; + export function isNan(value: Expr): BooleanExpr; /** * @beta @@ -7134,10 +7338,10 @@ declare namespace FirebaseFirestore { * isNaN("value"); * ``` * - * @param value The name of the field to check. + * @param fieldName The name of the field to check. * @return A new {@code Expr} representing the 'isNaN' check. */ - export function isNaN(value: string): IsNan; + export function isNan(fieldName: string): BooleanExpr; /** * @beta @@ -7146,18 +7350,18 @@ declare namespace FirebaseFirestore { * * ```typescript * // Reverse the value of the 'myString' field. - * reverse(Field.of("myString")); + * reverse(field("myString")); * ``` * - * @param expr The expression representing the string to reverse. + * @param stringExpression An expression evaluating to a string value, which will be reversed. * @return A new {@code Expr} representing the reversed string. */ - export function reverse(expr: Expr): Reverse; + export function reverse(stringExpression: Expr): FunctionExpr; /** * @beta * - * Creates an expression that reverses a string represented by a field. + * Creates an expression that reverses a string value in the specified field. * * ```typescript * // Reverse the value of the 'myString' field. @@ -7167,7 +7371,7 @@ declare namespace FirebaseFirestore { * @param field The name of the field representing the string to reverse. * @return A new {@code Expr} representing the reversed string. */ - export function reverse(field: string): Reverse; + export function reverse(field: string): FunctionExpr; /** * @beta @@ -7176,7 +7380,7 @@ declare namespace FirebaseFirestore { * * ```typescript * // Replace the first occurrence of "hello" with "hi" in the 'message' field. - * replaceFirst(Field.of("message"), "hello", "hi"); + * replaceFirst(field("message"), "hello", "hi"); * ``` * * @param value The expression representing the string to perform the replacement on. @@ -7188,7 +7392,7 @@ declare namespace FirebaseFirestore { value: Expr, find: string, replace: string - ): ReplaceFirst; + ): FunctionExpr; /** * @beta @@ -7198,7 +7402,7 @@ declare namespace FirebaseFirestore { * * ```typescript * // Replace the first occurrence of the value in 'findField' with the value in 'replaceField' in the 'message' field. - * replaceFirst(Field.of("message"), Field.of("findField"), Field.of("replaceField")); + * replaceFirst(field("message"), field("findField"), field("replaceField")); * ``` * * @param value The expression representing the string to perform the replacement on. @@ -7210,7 +7414,7 @@ declare namespace FirebaseFirestore { value: Expr, find: Expr, replace: Expr - ): ReplaceFirst; + ): FunctionExpr; /** * @beta @@ -7222,38 +7426,16 @@ declare namespace FirebaseFirestore { * replaceFirst("message", "hello", "hi"); * ``` * - * @param field The name of the field representing the string to perform the replacement on. + * @param fieldName The name of the field representing the string to perform the replacement on. * @param find The substring to search for. * @param replace The substring to replace the first occurrence of 'find' with. * @return A new {@code Expr} representing the string with the first occurrence replaced. */ export function replaceFirst( - field: string, + fieldName: string, find: string, replace: string - ): ReplaceFirst; - - /** - * @beta - * - * Creates an expression that replaces the first occurrence of a substring within a string represented by a field with another substring, - * where the substring to find and the replacement substring are specified by expressions. - * - * ```typescript - * // Replace the first occurrence of the value in 'findField' with the value in 'replaceField' in the 'message' field. - * replaceFirst("message", Field.of("findField"), Field.of("replaceField")); - * ``` - * - * @param field The name of the field representing the string to perform the replacement on. - * @param find The expression representing the substring to search for. - * @param replace The expression representing the substring to replace the first occurrence of 'find' with. - * @return A new {@code Expr} representing the string with the first occurrence replaced. - */ - export function replaceFirst( - field: string, - find: Expr, - replace: Expr - ): ReplaceFirst; + ): FunctionExpr; /** * @beta @@ -7262,7 +7444,7 @@ declare namespace FirebaseFirestore { * * ```typescript * // Replace all occurrences of "hello" with "hi" in the 'message' field. - * replaceAll(Field.of("message"), "hello", "hi"); + * replaceAll(field("message"), "hello", "hi"); * ``` * * @param value The expression representing the string to perform the replacement on. @@ -7274,7 +7456,7 @@ declare namespace FirebaseFirestore { value: Expr, find: string, replace: string - ): ReplaceAll; + ): FunctionExpr; /** * @beta @@ -7284,7 +7466,7 @@ declare namespace FirebaseFirestore { * * ```typescript * // Replace all occurrences of the value in 'findField' with the value in 'replaceField' in the 'message' field. - * replaceAll(Field.of("message"), Field.of("findField"), Field.of("replaceField")); + * replaceAll(field("message"), field("findField"), field("replaceField")); * ``` * * @param value The expression representing the string to perform the replacement on. @@ -7296,7 +7478,7 @@ declare namespace FirebaseFirestore { value: Expr, find: Expr, replace: Expr - ): ReplaceAll; + ): FunctionExpr; /** * @beta @@ -7308,83 +7490,61 @@ declare namespace FirebaseFirestore { * replaceAll("message", "hello", "hi"); * ``` * - * @param field The name of the field representing the string to perform the replacement on. + * @param fieldName The name of the field representing the string to perform the replacement on. * @param find The substring to search for. * @param replace The substring to replace all occurrences of 'find' with. * @return A new {@code Expr} representing the string with all occurrences replaced. */ export function replaceAll( - field: string, + fieldName: string, find: string, replace: string - ): ReplaceAll; - - /** - * @beta - * - * Creates an expression that replaces all occurrences of a substring within a string represented by a field with another substring, - * where the substring to find and the replacement substring are specified by expressions. - * - * ```typescript - * // Replace all occurrences of the value in 'findField' with the value in 'replaceField' in the 'message' field. - * replaceAll("message", Field.of("findField"), Field.of("replaceField")); - * ``` - * - * @param field The name of the field representing the string to perform the replacement on. - * @param find The expression representing the substring to search for. - * @param replace The expression representing the substring to replace all occurrences of 'find' with. - * @return A new {@code Expr} representing the string with all occurrences replaced. - */ - export function replaceAll( - field: string, - find: Expr, - replace: Expr - ): ReplaceAll; + ): FunctionExpr; /** * @beta * - * Creates an expression that calculates the length of a string in bytes. + * Creates an expression that calculates the byte length of a string in UTF-8, or just the length of a Blob. * * ```typescript * // Calculate the length of the 'myString' field in bytes. - * byteLength(Field.of("myString")); + * byteLength(field("myString")); * ``` * * @param expr The expression representing the string. * @return A new {@code Expr} representing the length of the string in bytes. */ - export function byteLength(expr: Expr): ByteLength; + export function byteLength(expr: Expr): FunctionExpr; /** * @beta * - * Creates an expression that calculates the length of a string represented by a field in bytes. + * Creates an expression that calculates the length of a string represented by a field in UTF-8 bytes, or just the length of a Blob. * * ```typescript * // Calculate the length of the 'myString' field in bytes. * byteLength("myString"); * ``` * - * @param field The name of the field representing the string. + * @param fieldName The name of the field containing the string. * @return A new {@code Expr} representing the length of the string in bytes. */ - export function byteLength(field: string): ByteLength; + export function byteLength(fieldName: string): FunctionExpr; /** * @beta * - * Creates an expression that calculates the character length of a string field in UTF-8. + * Creates an expression that calculates the character length of a string field in UTF8. * * ```typescript * // Get the character length of the 'name' field in UTF-8. * strLength("name"); * ``` * - * @param field The name of the field containing the string. + * @param fieldName The name of the field containing the string. * @return A new {@code Expr} representing the length of the string. */ - export function charLength(field: string): CharLength; + export function charLength(fieldName: string): FunctionExpr; /** * @beta @@ -7393,13 +7553,13 @@ declare namespace FirebaseFirestore { * * ```typescript * // Get the character length of the 'name' field in UTF-8. - * strLength(Field.of("name")); + * strLength(field("name")); * ``` * - * @param expr The expression representing the string to calculate the length of. + * @param stringExpression The expression representing the string to calculate the length of. * @return A new {@code Expr} representing the length of the string. */ - export function charLength(expr: Expr): CharLength; + export function charLength(stringExpression: Expr): FunctionExpr; /** * @beta @@ -7412,11 +7572,11 @@ declare namespace FirebaseFirestore { * like("title", "%guide%"); * ``` * - * @param left The name of the field containing the string. + * @param fieldName The name of the field containing the string. * @param pattern The pattern to search for. You can use "%" as a wildcard character. * @return A new {@code Expr} representing the 'like' comparison. */ - export function like(left: string, pattern: string): Like; + export function like(fieldName: string, pattern: string): BooleanExpr; /** * @beta @@ -7426,14 +7586,14 @@ declare namespace FirebaseFirestore { * * ```typescript * // Check if the 'title' field contains the string "guide" - * like("title", Field.of("pattern")); + * like("title", field("pattern")); * ``` * - * @param left The name of the field containing the string. + * @param fieldName The name of the field containing the string. * @param pattern The pattern to search for. You can use "%" as a wildcard character. * @return A new {@code Expr} representing the 'like' comparison. */ - export function like(left: string, pattern: Expr): Like; + export function like(fieldName: string, pattern: Expr): BooleanExpr; /** * @beta @@ -7442,14 +7602,14 @@ declare namespace FirebaseFirestore { * * ```typescript * // Check if the 'title' field contains the string "guide" - * like(Field.of("title"), "%guide%"); + * like(field("title"), "%guide%"); * ``` * - * @param left The expression representing the string to perform the comparison on. + * @param stringExpression The expression representing the string to perform the comparison on. * @param pattern The pattern to search for. You can use "%" as a wildcard character. * @return A new {@code Expr} representing the 'like' comparison. */ - export function like(left: Expr, pattern: string): Like; + export function like(stringExpression: Expr, pattern: string): BooleanExpr; /** * @beta @@ -7458,14 +7618,14 @@ declare namespace FirebaseFirestore { * * ```typescript * // Check if the 'title' field contains the string "guide" - * like(Field.of("title"), Field.of("pattern")); + * like(field("title"), field("pattern")); * ``` * - * @param left The expression representing the string to perform the comparison on. + * @param stringExpression The expression representing the string to perform the comparison on. * @param pattern The pattern to search for. You can use "%" as a wildcard character. * @return A new {@code Expr} representing the 'like' comparison. */ - export function like(left: Expr, pattern: Expr): Like; + export function like(stringExpression: Expr, pattern: Expr): BooleanExpr; /** * @beta @@ -7478,11 +7638,14 @@ declare namespace FirebaseFirestore { * regexContains("description", "(?i)example"); * ``` * - * @param left The name of the field containing the string. + * @param fieldName The name of the field containing the string. * @param pattern The regular expression to use for the search. * @return A new {@code Expr} representing the 'contains' comparison. */ - export function regexContains(left: string, pattern: string): RegexContains; + export function regexContains( + fieldName: string, + pattern: string + ): BooleanExpr; /** * @beta @@ -7492,14 +7655,14 @@ declare namespace FirebaseFirestore { * * ```typescript * // Check if the 'description' field contains "example" (case-insensitive) - * regexContains("description", Field.of("pattern")); + * regexContains("description", field("pattern")); * ``` * - * @param left The name of the field containing the string. + * @param fieldName The name of the field containing the string. * @param pattern The regular expression to use for the search. * @return A new {@code Expr} representing the 'contains' comparison. */ - export function regexContains(left: string, pattern: Expr): RegexContains; + export function regexContains(fieldName: string, pattern: Expr): BooleanExpr; /** * @beta @@ -7509,14 +7672,17 @@ declare namespace FirebaseFirestore { * * ```typescript * // Check if the 'description' field contains "example" (case-insensitive) - * regexContains(Field.of("description"), "(?i)example"); + * regexContains(field("description"), "(?i)example"); * ``` * - * @param left The expression representing the string to perform the comparison on. + * @param stringExpression The expression representing the string to perform the comparison on. * @param pattern The regular expression to use for the search. * @return A new {@code Expr} representing the 'contains' comparison. */ - export function regexContains(left: Expr, pattern: string): RegexContains; + export function regexContains( + stringExpression: Expr, + pattern: string + ): BooleanExpr; /** * @beta @@ -7526,14 +7692,17 @@ declare namespace FirebaseFirestore { * * ```typescript * // Check if the 'description' field contains "example" (case-insensitive) - * regexContains(Field.of("description"), Field.of("pattern")); + * regexContains(field("description"), field("pattern")); * ``` * - * @param left The expression representing the string to perform the comparison on. + * @param stringExpression The expression representing the string to perform the comparison on. * @param pattern The regular expression to use for the search. * @return A new {@code Expr} representing the 'contains' comparison. */ - export function regexContains(left: Expr, pattern: Expr): RegexContains; + export function regexContains( + stringExpression: Expr, + pattern: Expr + ): BooleanExpr; /** * @beta @@ -7545,11 +7714,11 @@ declare namespace FirebaseFirestore { * regexMatch("email", "[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,}"); * ``` * - * @param left The name of the field containing the string. + * @param fieldName The name of the field containing the string. * @param pattern The regular expression to use for the match. * @return A new {@code Expr} representing the regular expression match. */ - export function regexMatch(left: string, pattern: string): RegexMatch; + export function regexMatch(fieldName: string, pattern: string): BooleanExpr; /** * @beta @@ -7558,14 +7727,14 @@ declare namespace FirebaseFirestore { * * ```typescript * // Check if the 'email' field matches a valid email pattern - * regexMatch("email", Field.of("pattern")); + * regexMatch("email", field("pattern")); * ``` * - * @param left The name of the field containing the string. + * @param fieldName The name of the field containing the string. * @param pattern The regular expression to use for the match. * @return A new {@code Expr} representing the regular expression match. */ - export function regexMatch(left: string, pattern: Expr): RegexMatch; + export function regexMatch(fieldName: string, pattern: Expr): BooleanExpr; /** * @beta @@ -7575,14 +7744,17 @@ declare namespace FirebaseFirestore { * * ```typescript * // Check if the 'email' field matches a valid email pattern - * regexMatch(Field.of("email"), "[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,}"); + * regexMatch(field("email"), "[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,}"); * ``` * - * @param left The expression representing the string to match against. + * @param stringExpression The expression representing the string to match against. * @param pattern The regular expression to use for the match. * @return A new {@code Expr} representing the regular expression match. */ - export function regexMatch(left: Expr, pattern: string): RegexMatch; + export function regexMatch( + stringExpression: Expr, + pattern: string + ): BooleanExpr; /** * @beta @@ -7592,14 +7764,17 @@ declare namespace FirebaseFirestore { * * ```typescript * // Check if the 'email' field matches a valid email pattern - * regexMatch(Field.of("email"), Field.of("pattern")); + * regexMatch(field("email"), field("pattern")); * ``` * - * @param left The expression representing the string to match against. + * @param stringExpression The expression representing the string to match against. * @param pattern The regular expression to use for the match. * @return A new {@code Expr} representing the regular expression match. */ - export function regexMatch(left: Expr, pattern: Expr): RegexMatch; + export function regexMatch( + stringExpression: Expr, + pattern: Expr + ): BooleanExpr; /** * @beta @@ -7611,11 +7786,14 @@ declare namespace FirebaseFirestore { * strContains("description", "example"); * ``` * - * @param left The name of the field containing the string. + * @param fieldName The name of the field containing the string. * @param substring The substring to search for. * @return A new {@code Expr} representing the 'contains' comparison. */ - export function strContains(left: string, substring: string): StrContains; + export function strContains( + fieldName: string, + substring: string + ): BooleanExpr; /** * @beta @@ -7624,14 +7802,14 @@ declare namespace FirebaseFirestore { * * ```typescript * // Check if the 'description' field contains the value of the 'keyword' field. - * strContains("description", Field.of("keyword")); + * strContains("description", field("keyword")); * ``` * - * @param left The name of the field containing the string. + * @param fieldName The name of the field containing the string. * @param substring The expression representing the substring to search for. * @return A new {@code Expr} representing the 'contains' comparison. */ - export function strContains(left: string, substring: Expr): StrContains; + export function strContains(fieldName: string, substring: Expr): BooleanExpr; /** * @beta @@ -7640,14 +7818,17 @@ declare namespace FirebaseFirestore { * * ```typescript * // Check if the 'description' field contains "example". - * strContains(Field.of("description"), "example"); + * strContains(field("description"), "example"); * ``` * - * @param left The expression representing the string to perform the comparison on. + * @param stringExpression The expression representing the string to perform the comparison on. * @param substring The substring to search for. * @return A new {@code Expr} representing the 'contains' comparison. */ - export function strContains(left: Expr, substring: string): StrContains; + export function strContains( + stringExpression: Expr, + substring: string + ): BooleanExpr; /** * @beta @@ -7656,14 +7837,17 @@ declare namespace FirebaseFirestore { * * ```typescript * // Check if the 'description' field contains the value of the 'keyword' field. - * strContains(Field.of("description"), Field.of("keyword")); + * strContains(field("description"), field("keyword")); * ``` * - * @param left The expression representing the string to perform the comparison on. + * @param stringExpression The expression representing the string to perform the comparison on. * @param substring The expression representing the substring to search for. * @return A new {@code Expr} representing the 'contains' comparison. */ - export function strContains(left: Expr, substring: Expr): StrContains; + export function strContains( + stringExpression: Expr, + substring: Expr + ): BooleanExpr; /** * @beta @@ -7675,11 +7859,11 @@ declare namespace FirebaseFirestore { * startsWith("name", "Mr."); * ``` * - * @param expr The field name to check. + * @param fieldName The field name to check. * @param prefix The prefix to check for. * @return A new {@code Expr} representing the 'starts with' comparison. */ - export function startsWith(expr: string, prefix: string): StartsWith; + export function startsWith(fieldName: string, prefix: string): BooleanExpr; /** * @beta @@ -7688,14 +7872,14 @@ declare namespace FirebaseFirestore { * * ```typescript * // Check if the 'fullName' field starts with the value of the 'firstName' field - * startsWith("fullName", Field.of("firstName")); + * startsWith("fullName", field("firstName")); * ``` * - * @param expr The field name to check. + * @param fieldName The field name to check. * @param prefix The expression representing the prefix. * @return A new {@code Expr} representing the 'starts with' comparison. */ - export function startsWith(expr: string, prefix: Expr): StartsWith; + export function startsWith(fieldName: string, prefix: Expr): BooleanExpr; /** * @beta @@ -7704,14 +7888,17 @@ declare namespace FirebaseFirestore { * * ```typescript * // Check if the result of concatenating 'firstName' and 'lastName' fields starts with "Mr." - * startsWith(Field.of("fullName"), "Mr."); + * startsWith(field("fullName"), "Mr."); * ``` * - * @param expr The expression to check. + * @param stringExpression The expression to check. * @param prefix The prefix to check for. * @return A new {@code Expr} representing the 'starts with' comparison. */ - export function startsWith(expr: Expr, prefix: string): StartsWith; + export function startsWith( + stringExpression: Expr, + prefix: string + ): BooleanExpr; /** * @beta @@ -7720,14 +7907,14 @@ declare namespace FirebaseFirestore { * * ```typescript * // Check if the result of concatenating 'firstName' and 'lastName' fields starts with "Mr." - * startsWith(Field.of("fullName"), Field.of("prefix")); + * startsWith(field("fullName"), field("prefix")); * ``` * - * @param expr The expression to check. + * @param stringExpression The expression to check. * @param prefix The prefix to check for. * @return A new {@code Expr} representing the 'starts with' comparison. */ - export function startsWith(expr: Expr, prefix: Expr): StartsWith; + export function startsWith(stringExpression: Expr, prefix: Expr): BooleanExpr; /** * @beta @@ -7739,11 +7926,11 @@ declare namespace FirebaseFirestore { * endsWith("filename", ".txt"); * ``` * - * @param expr The field name to check. + * @param fieldName The field name to check. * @param suffix The postfix to check for. * @return A new {@code Expr} representing the 'ends with' comparison. */ - export function endsWith(expr: string, suffix: string): EndsWith; + export function endsWith(fieldName: string, suffix: string): BooleanExpr; /** * @beta @@ -7752,14 +7939,14 @@ declare namespace FirebaseFirestore { * * ```typescript * // Check if the 'url' field ends with the value of the 'extension' field - * endsWith("url", Field.of("extension")); + * endsWith("url", field("extension")); * ``` * - * @param expr The field name to check. + * @param fieldName The field name to check. * @param suffix The expression representing the postfix. * @return A new {@code Expr} representing the 'ends with' comparison. */ - export function endsWith(expr: string, suffix: Expr): EndsWith; + export function endsWith(fieldName: string, suffix: Expr): BooleanExpr; /** * @beta @@ -7768,14 +7955,14 @@ declare namespace FirebaseFirestore { * * ```typescript * // Check if the result of concatenating 'firstName' and 'lastName' fields ends with "Jr." - * endsWith(Field.of("fullName"), "Jr."); + * endsWith(field("fullName"), "Jr."); * ``` * - * @param expr The expression to check. + * @param stringExpression The expression to check. * @param suffix The postfix to check for. * @return A new {@code Expr} representing the 'ends with' comparison. */ - export function endsWith(expr: Expr, suffix: string): EndsWith; + export function endsWith(stringExpression: Expr, suffix: string): BooleanExpr; /** * @beta @@ -7784,14 +7971,14 @@ declare namespace FirebaseFirestore { * * ```typescript * // Check if the result of concatenating 'firstName' and 'lastName' fields ends with "Jr." - * endsWith(Field.of("fullName"), Constant.of("Jr.")); + * endsWith(field("fullName"), constant("Jr.")); * ``` * - * @param expr The expression to check. + * @param stringExpression The expression to check. * @param suffix The postfix to check for. * @return A new {@code Expr} representing the 'ends with' comparison. */ - export function endsWith(expr: Expr, suffix: Expr): EndsWith; + export function endsWith(stringExpression: Expr, suffix: Expr): BooleanExpr; /** * @beta @@ -7803,10 +7990,10 @@ declare namespace FirebaseFirestore { * toLower("name"); * ``` * - * @param expr The name of the field containing the string. + * @param fieldName The name of the field containing the string. * @return A new {@code Expr} representing the lowercase string. */ - export function toLower(expr: string): ToLower; + export function toLower(fieldName: string): FunctionExpr; /** * @beta @@ -7815,13 +8002,13 @@ declare namespace FirebaseFirestore { * * ```typescript * // Convert the 'name' field to lowercase - * toLower(Field.of("name")); + * toLower(field("name")); * ``` * - * @param expr The expression representing the string to convert to lowercase. + * @param stringExpression The expression representing the string to convert to lowercase. * @return A new {@code Expr} representing the lowercase string. */ - export function toLower(expr: Expr): ToLower; + export function toLower(stringExpression: Expr): FunctionExpr; /** * @beta @@ -7833,10 +8020,10 @@ declare namespace FirebaseFirestore { * toUpper("title"); * ``` * - * @param expr The name of the field containing the string. + * @param fieldName The name of the field containing the string. * @return A new {@code Expr} representing the uppercase string. */ - export function toUpper(expr: string): ToUpper; + export function toUpper(fieldName: string): FunctionExpr; /** * @beta @@ -7845,13 +8032,13 @@ declare namespace FirebaseFirestore { * * ```typescript * // Convert the 'title' field to uppercase - * toUppercase(Field.of("title")); + * toUppercase(field("title")); * ``` * - * @param expr The expression representing the string to convert to uppercase. + * @param stringExpression The expression representing the string to convert to uppercase. * @return A new {@code Expr} representing the uppercase string. */ - export function toUpper(expr: Expr): ToUpper; + export function toUpper(stringExpression: Expr): FunctionExpr; /** * @beta @@ -7863,10 +8050,10 @@ declare namespace FirebaseFirestore { * trim("userInput"); * ``` * - * @param expr The name of the field containing the string. + * @param fieldName The name of the field containing the string. * @return A new {@code Expr} representing the trimmed string. */ - export function trim(expr: string): Trim; + export function trim(fieldName: string): FunctionExpr; /** * @beta @@ -7875,13 +8062,13 @@ declare namespace FirebaseFirestore { * * ```typescript * // Trim whitespace from the 'userInput' field - * trim(Field.of("userInput")); + * trim(field("userInput")); * ``` * - * @param expr The expression representing the string to trim. + * @param stringExpression The expression representing the string to trim. * @return A new {@code Expr} representing the trimmed string. */ - export function trim(expr: Expr): Trim; + export function trim(stringExpression: Expr): FunctionExpr; /** * @beta @@ -7890,17 +8077,19 @@ declare namespace FirebaseFirestore { * * ```typescript * // Combine the 'firstName', " ", and 'lastName' fields into a single string - * strConcat("firstName", " ", Field.of("lastName")); + * strConcat("firstName", " ", field("lastName")); * ``` * - * @param first The field name containing the initial string value. - * @param elements The expressions (typically strings) to concatenate. + * @param fieldName The field name containing the initial string value. + * @param secondString An expression or string literal to concatenate. + * @param otherStrings Optional additional expressions or literals (typically strings) to concatenate. * @return A new {@code Expr} representing the concatenated string. */ export function strConcat( - first: string, - ...elements: (Expr | string)[] - ): StrConcat; + fieldName: string, + secondString: Expr | string, + ...otherStrings: Array + ): FunctionExpr; /** * @beta @@ -7908,17 +8097,19 @@ declare namespace FirebaseFirestore { * * ```typescript * // Combine the 'firstName', " ", and 'lastName' fields into a single string - * strConcat(Field.of("firstName"), " ", Field.of("lastName")); + * strConcat(field("firstName"), " ", field("lastName")); * ``` * - * @param first The initial string expression to concatenate to. - * @param elements The expressions (typically strings) to concatenate. + * @param firstString The initial string expression to concatenate to. + * @param secondString An expression or string literal to concatenate. + * @param otherStrings Optional additional expressions or literals (typically strings) to concatenate. * @return A new {@code Expr} representing the concatenated string. */ export function strConcat( - first: Expr, - ...elements: (Expr | string)[] - ): StrConcat; + firstString: Expr, + secondString: Expr | string, + ...otherStrings: Array + ): FunctionExpr; /** * @beta @@ -7930,11 +8121,11 @@ declare namespace FirebaseFirestore { * mapGet("address", "city"); * ``` * - * @param mapField The field name of the map field. + * @param fieldName The field name of the map field. * @param subField The key to access in the map. * @return A new {@code Expr} representing the value associated with the given key in the map. */ - export function mapGet(mapField: string, subField: string): MapGet; + export function mapGet(fieldName: string, subField: string): FunctionExpr; /** * @beta @@ -7943,14 +8134,14 @@ declare namespace FirebaseFirestore { * * ```typescript * // Get the 'city' value from the 'address' map field - * mapGet(Field.of("address"), "city"); + * mapGet(field("address"), "city"); * ``` * - * @param mapExpr The expression representing the map. + * @param mapExpression The expression representing the map. * @param subField The key to access in the map. * @return A new {@code Expr} representing the value associated with the given key in the map. */ - export function mapGet(mapExpr: Expr, subField: string): MapGet; + export function mapGet(mapExpression: Expr, subField: string): FunctionExpr; /** * @beta @@ -7958,13 +8149,13 @@ declare namespace FirebaseFirestore { * Creates an aggregation that counts the total number of stage inputs. * * ```typescript - * // Count the total number of users - * countAll().as("totalUsers"); + * // Count the total number of input documents + * countAll().as("totalDocument"); * ``` * - * @return A new {@code Accumulator} representing the 'countAll' aggregation. + * @return A new {@code AggregateFunction} representing the 'countAll' aggregation. */ - export function countAll(): Count; + export function countAll(): AggregateFunction; /** * @beta @@ -7974,27 +8165,26 @@ declare namespace FirebaseFirestore { * * ```typescript * // Count the number of items where the price is greater than 10 - * count(Field.of("price").gt(10)).as("expensiveItemCount"); + * count(field("price").gt(10)).as("expensiveItemCount"); * ``` * - * @param value The expression to count. - * @return A new {@code Accumulator} representing the 'count' aggregation. + * @param expression The expression to count. + * @return A new {@code AggregateFunction} representing the 'count' aggregation. */ - export function count(value: Expr): Count; + export function count(expression: Expr): AggregateFunction; /** - * Creates an aggregation that counts the number of stage inputs with valid evaluations of the - * provided field. + * Creates an aggregation that counts the number of stage inputs where the input field exists. * * ```typescript * // Count the total number of products * count("productId").as("totalProducts"); * ``` * - * @param value The name of the field to count. - * @return A new {@code Accumulator} representing the 'count' aggregation. + * @param fieldName The name of the field to count. + * @return A new {@code AggregateFunction} representing the 'count' aggregation. */ - export function count(value: string): Count; + export function count(fieldName: string): AggregateFunction; /** * @beta @@ -8004,13 +8194,13 @@ declare namespace FirebaseFirestore { * * ```typescript * // Calculate the total revenue from a set of orders - * sum(Field.of("orderAmount")).as("totalRevenue"); + * sum(field("orderAmount")).as("totalRevenue"); * ``` * - * @param value The expression to sum up. - * @return A new {@code Accumulator} representing the 'sum' aggregation. + * @param expression The expression to sum up. + * @return A new {@code AggregateFunction} representing the 'sum' aggregation. */ - export function sum(value: Expr): Sum; + export function sum(expression: Expr): AggregateFunction; /** * @beta @@ -8023,10 +8213,10 @@ declare namespace FirebaseFirestore { * sum("orderAmount").as("totalRevenue"); * ``` * - * @param value The name of the field containing numeric values to sum up. - * @return A new {@code Accumulator} representing the 'sum' aggregation. + * @param fieldName The name of the field containing numeric values to sum up. + * @return A new {@code AggregateFunction} representing the 'sum' aggregation. */ - export function sum(value: string): Sum; + export function sum(fieldName: string): AggregateFunction; /** * @beta @@ -8036,13 +8226,13 @@ declare namespace FirebaseFirestore { * * ```typescript * // Calculate the average age of users - * avg(Field.of("age")).as("averageAge"); + * avg(field("age")).as("averageAge"); * ``` * - * @param value The expression representing the values to average. - * @return A new {@code Accumulator} representing the 'avg' aggregation. + * @param expression The expression representing the values to average. + * @return A new {@code AggregateFunction} representing the 'avg' aggregation. */ - export function avg(value: Expr): Avg; + export function avg(expression: Expr): AggregateFunction; /** * @beta @@ -8055,10 +8245,10 @@ declare namespace FirebaseFirestore { * avg("age").as("averageAge"); * ``` * - * @param value The name of the field containing numeric values to average. - * @return A new {@code Accumulator} representing the 'avg' aggregation. + * @param fieldName The name of the field containing numeric values to average. + * @return A new {@code AggregateFunction} representing the 'avg' aggregation. */ - export function avg(value: string): Avg; + export function avg(fieldName: string): AggregateFunction; /** * @beta @@ -8068,13 +8258,13 @@ declare namespace FirebaseFirestore { * * ```typescript * // Find the lowest price of all products - * minimum(Field.of("price")).as("lowestPrice"); + * minimum(field("price")).as("lowestPrice"); * ``` * - * @param value The expression to find the minimum value of. - * @return A new {@code Accumulator} representing the 'minimum' aggregation. + * @param expression The expression to find the minimum value of. + * @return A new {@code AggregateFunction} representing the 'min' aggregation. */ - export function minimum(value: Expr): Minimum; + export function minimum(expression: Expr): AggregateFunction; /** * @beta @@ -8086,10 +8276,10 @@ declare namespace FirebaseFirestore { * minimum("price").as("lowestPrice"); * ``` * - * @param value The name of the field to find the minimum value of. - * @return A new {@code Accumulator} representing the 'minimum' aggregation. + * @param fieldName The name of the field to find the minimum value of. + * @return A new {@code AggregateFunction} representing the 'min' aggregation. */ - export function minimum(value: string): Minimum; + export function minimum(fieldName: string): AggregateFunction; /** * @beta @@ -8099,13 +8289,13 @@ declare namespace FirebaseFirestore { * * ```typescript * // Find the highest score in a leaderboard - * maximum(Field.of("score")).as("highestScore"); + * maximum(field("score")).as("highestScore"); * ``` * - * @param value The expression to find the maximum value of. - * @return A new {@code Accumulator} representing the 'maximum' aggregation. + * @param expression The expression to find the maximum value of. + * @return A new {@code AggregateFunction} representing the 'max' aggregation. */ - export function maximum(value: Expr): Maximim; + export function maximum(expression: Expr): AggregateFunction; /** * @beta @@ -8117,45 +8307,29 @@ declare namespace FirebaseFirestore { * maximum("score").as("highestScore"); * ``` * - * @param value The name of the field to find the maximum value of. - * @return A new {@code Accumulator} representing the 'maximum' aggregation. + * @param fieldName The name of the field to find the maximum value of. + * @return A new {@code AggregateFunction} representing the 'max' aggregation. */ - export function maximum(value: string): Maximim; + export function maximum(fieldName: string): AggregateFunction; /** * @beta * - * Calculates the Cosine distance between a field's vector value and a double array. + * Calculates the Cosine distance between a field's vector value and a literal vector value. * * ```typescript * // Calculate the Cosine distance between the 'location' field and a target location * cosineDistance("location", [37.7749, -122.4194]); * ``` * - * @param expr The name of the field containing the first vector. - * @param other The other vector (as an array of doubles) to compare against. - * @return A new {@code Expr} representing the Cosine distance between the two vectors. - */ - export function cosineDistance(expr: string, other: number[]): CosineDistance; - - /** - * @beta - * - * Calculates the Cosine distance between a field's vector value and a VectorValue. - * - * ```typescript - * // Calculate the Cosine distance between the 'location' field and a target location - * cosineDistance("location", new VectorValue([37.7749, -122.4194])); - * ``` - * - * @param expr The name of the field containing the first vector. - * @param other The other vector (as a VectorValue) to compare against. + * @param fieldName The name of the field containing the first vector. + * @param vector The other vector (as an array of doubles) or {@link VectorValue} to compare against. * @return A new {@code Expr} representing the Cosine distance between the two vectors. */ export function cosineDistance( - expr: string, - other: VectorValue - ): CosineDistance; + fieldName: string, + vector: number[] | VectorValue + ): FunctionExpr; /** * @beta @@ -8164,49 +8338,36 @@ declare namespace FirebaseFirestore { * * ```typescript * // Calculate the cosine distance between the 'userVector' field and the 'itemVector' field - * cosineDistance("userVector", Field.of("itemVector")); - * ``` - * - * @param expr The name of the field containing the first vector. - * @param other The other vector (represented as an Expr) to compare against. - * @return A new {@code Expr} representing the cosine distance between the two vectors. - */ - export function cosineDistance(expr: string, other: Expr): CosineDistance; - - /** - * @beta - * - * Calculates the Cosine distance between a vector expression and a double array. - * - * ```typescript - * // Calculate the cosine distance between the 'location' field and a target location - * cosineDistance(Field.of("location"), [37.7749, -122.4194]); + * cosineDistance("userVector", field("itemVector")); * ``` * - * @param expr The first vector (represented as an Expr) to compare against. - * @param other The other vector (as an array of doubles) to compare against. + * @param fieldName The name of the field containing the first vector. + * @param vectorExpression The other vector (represented as an Expr) to compare against. * @return A new {@code Expr} representing the cosine distance between the two vectors. */ - export function cosineDistance(expr: Expr, other: number[]): CosineDistance; + export function cosineDistance( + fieldName: string, + vectorExpression: Expr + ): FunctionExpr; /** * @beta * - * Calculates the Cosine distance between a vector expression and a VectorValue. + * Calculates the Cosine distance between a vector expression and a vector literal. * * ```typescript * // Calculate the cosine distance between the 'location' field and a target location - * cosineDistance(Field.of("location"), new VectorValue([37.7749, -122.4194])); + * cosineDistance(field("location"), [37.7749, -122.4194]); * ``` * - * @param expr The first vector (represented as an Expr) to compare against. - * @param other The other vector (as a VectorValue) to compare against. + * @param vectorExpression The first vector (represented as an Expr) to compare against. + * @param vector The other vector (as an array of doubles or VectorValue) to compare against. * @return A new {@code Expr} representing the cosine distance between the two vectors. */ export function cosineDistance( - expr: Expr, - other: VectorValue - ): CosineDistance; + vectorExpression: Expr, + vector: number[] | Expr + ): FunctionExpr; /** * @beta @@ -8215,14 +8376,17 @@ declare namespace FirebaseFirestore { * * ```typescript * // Calculate the cosine distance between the 'userVector' field and the 'itemVector' field - * cosineDistance(Field.of("userVector"), Field.of("itemVector")); + * cosineDistance(field("userVector"), field("itemVector")); * ``` * - * @param expr The first vector (represented as an Expr) to compare against. - * @param other The other vector (represented as an Expr) to compare against. + * @param vectorExpression The first vector (represented as an Expr) to compare against. + * @param otherVectorExpression The other vector (represented as an Expr) to compare against. * @return A new {@code Expr} representing the cosine distance between the two vectors. */ - export function cosineDistance(expr: Expr, other: Expr): CosineDistance; + export function cosineDistance( + vectorExpression: Expr, + otherVectorExpression: Expr + ): FunctionExpr; /** * @beta @@ -8234,75 +8398,52 @@ declare namespace FirebaseFirestore { * dotProduct("features", [0.5, 0.8, 0.2]); * ``` * - * @param expr The name of the field containing the first vector. - * @param other The other vector (as an array of doubles) to calculate with. - * @return A new {@code Expr} representing the dot product between the two vectors. - */ - export function dotProduct(expr: string, other: number[]): DotProduct; - - /** - * @beta - * - * Calculates the dot product between a field's vector value and a VectorValue. - * - * ```typescript - * // Calculate the dot product distance between a feature vector and a target vector - * dotProduct("features", new VectorValue([0.5, 0.8, 0.2])); - * ``` - * - * @param expr The name of the field containing the first vector. - * @param other The other vector (as a VectorValue) to calculate with. - * @return A new {@code Expr} representing the dot product between the two vectors. - */ - export function dotProduct(expr: string, other: VectorValue): DotProduct; - - /** - * @beta - * - * Calculates the dot product between a field's vector value and a vector expression. - * - * ```typescript - * // Calculate the dot product distance between two document vectors: 'docVector1' and 'docVector2' - * dotProduct("docVector1", Field.of("docVector2")); - * ``` - * - * @param expr The name of the field containing the first vector. - * @param other The other vector (represented as an Expr) to calculate with. + * @param fieldName The name of the field containing the first vector. + * @param vector The other vector (as an array of doubles or VectorValue) to calculate with. * @return A new {@code Expr} representing the dot product between the two vectors. */ - export function dotProduct(expr: string, other: Expr): DotProduct; + export function dotProduct( + fieldName: string, + vector: number[] | VectorValue + ): FunctionExpr; /** * @beta * - * Calculates the dot product between a vector expression and a double array. + * Calculates the dot product between a field's vector value and a vector expression. * * ```typescript - * // Calculate the dot product between a feature vector and a target vector - * dotProduct(Field.of("features"), [0.5, 0.8, 0.2]); + * // Calculate the dot product distance between two document vectors: 'docVector1' and 'docVector2' + * dotProduct("docVector1", field("docVector2")); * ``` * - * @param expr The first vector (represented as an Expr) to calculate with. - * @param other The other vector (as an array of doubles) to calculate with. + * @param fieldName The name of the field containing the first vector. + * @param vectorExpression The other vector (represented as an Expr) to calculate with. * @return A new {@code Expr} representing the dot product between the two vectors. */ - export function dotProduct(expr: Expr, other: number[]): DotProduct; + export function dotProduct( + fieldName: string, + vectorExpression: Expr + ): FunctionExpr; /** * @beta * - * Calculates the dot product between a vector expression and a VectorValue. + * Calculates the dot product between a vector expression and a double array. * * ```typescript * // Calculate the dot product between a feature vector and a target vector - * dotProduct(Field.of("features"), new VectorValue([0.5, 0.8, 0.2])); + * dotProduct(field("features"), [0.5, 0.8, 0.2]); * ``` * - * @param expr The first vector (represented as an Expr) to calculate with. - * @param other The other vector (as a VectorValue) to calculate with. + * @param vectorExpression The first vector (represented as an Expr) to calculate with. + * @param vector The other vector (as an array of doubles or VectorValue) to calculate with. * @return A new {@code Expr} representing the dot product between the two vectors. */ - export function dotProduct(expr: Expr, other: VectorValue): DotProduct; + export function dotProduct( + vectorExpression: Expr, + vector: number[] | VectorValue + ): FunctionExpr; /** * @beta @@ -8311,14 +8452,17 @@ declare namespace FirebaseFirestore { * * ```typescript * // Calculate the dot product between two document vectors: 'docVector1' and 'docVector2' - * dotProduct(Field.of("docVector1"), Field.of("docVector2")); + * dotProduct(field("docVector1"), field("docVector2")); * ``` * - * @param expr The first vector (represented as an Expr) to calculate with. - * @param other The other vector (represented as an Expr) to calculate with. + * @param vectorExpression The first vector (represented as an Expr) to calculate with. + * @param otherVectorExpression The other vector (represented as an Expr) to calculate with. * @return A new {@code Expr} representing the dot product between the two vectors. */ - export function dotProduct(expr: Expr, other: Expr): DotProduct; + export function dotProduct( + vectorExpression: Expr, + otherVectorExpression: Expr + ): FunctionExpr; /** * @beta @@ -8330,33 +8474,14 @@ declare namespace FirebaseFirestore { * euclideanDistance("location", [37.7749, -122.4194]); * ``` * - * @param expr The name of the field containing the first vector. - * @param other The other vector (as an array of doubles) to compare against. - * @return A new {@code Expr} representing the Euclidean distance between the two vectors. - */ - export function euclideanDistance( - expr: string, - other: number[] - ): EuclideanDistance; - - /** - * @beta - * - * Calculates the Euclidean distance between a field's vector value and a VectorValue. - * - * ```typescript - * // Calculate the Euclidean distance between the 'location' field and a target location - * euclideanDistance("location", new VectorValue([37.7749, -122.4194])); - * ``` - * - * @param expr The name of the field containing the first vector. - * @param other The other vector (as a VectorValue) to compare against. + * @param fieldName The name of the field containing the first vector. + * @param vector The other vector (as an array of doubles or VectorValue) to compare against. * @return A new {@code Expr} representing the Euclidean distance between the two vectors. */ export function euclideanDistance( - expr: string, - other: VectorValue - ): EuclideanDistance; + fieldName: string, + vector: number[] | VectorValue + ): FunctionExpr; /** * @beta @@ -8365,17 +8490,17 @@ declare namespace FirebaseFirestore { * * ```typescript * // Calculate the Euclidean distance between two vector fields: 'pointA' and 'pointB' - * euclideanDistance("pointA", Field.of("pointB")); + * euclideanDistance("pointA", field("pointB")); * ``` * - * @param expr The name of the field containing the first vector. - * @param other The other vector (represented as an Expr) to compare against. + * @param fieldName The name of the field containing the first vector. + * @param vectorExpression The other vector (represented as an Expr) to compare against. * @return A new {@code Expr} representing the Euclidean distance between the two vectors. */ export function euclideanDistance( - expr: string, - other: Expr - ): EuclideanDistance; + fieldName: string, + vectorExpression: Expr + ): FunctionExpr; /** * @beta @@ -8385,36 +8510,17 @@ declare namespace FirebaseFirestore { * ```typescript * // Calculate the Euclidean distance between the 'location' field and a target location * - * euclideanDistance(Field.of("location"), [37.7749, -122.4194]); - * ``` - * - * @param expr The first vector (represented as an Expr) to compare against. - * @param other The other vector (as an array of doubles) to compare against. - * @return A new {@code Expr} representing the Euclidean distance between the two vectors. - */ - export function euclideanDistance( - expr: Expr, - other: number[] - ): EuclideanDistance; - - /** - * @beta - * - * Calculates the Euclidean distance between a vector expression and a VectorValue. - * - * ```typescript - * // Calculate the Euclidean distance between the 'location' field and a target location - * euclideanDistance(Field.of("location"), new VectorValue([37.7749, -122.4194])); + * euclideanDistance(field("location"), [37.7749, -122.4194]); * ``` * - * @param expr The first vector (represented as an Expr) to compare against. - * @param other The other vector (as a VectorValue) to compare against. + * @param vectorExpression The first vector (represented as an Expr) to compare against. + * @param vector The other vector (as an array of doubles or VectorValue) to compare against. * @return A new {@code Expr} representing the Euclidean distance between the two vectors. */ export function euclideanDistance( - expr: Expr, - other: VectorValue - ): EuclideanDistance; + vectorExpression: Expr, + vector: number[] | VectorValue + ): FunctionExpr; /** * @beta @@ -8423,14 +8529,17 @@ declare namespace FirebaseFirestore { * * ```typescript * // Calculate the Euclidean distance between two vector fields: 'pointA' and 'pointB' - * euclideanDistance(Field.of("pointA"), Field.of("pointB")); + * euclideanDistance(field("pointA"), field("pointB")); * ``` * - * @param expr The first vector (represented as an Expr) to compare against. - * @param other The other vector (represented as an Expr) to compare against. + * @param vectorExpression The first vector (represented as an Expr) to compare against. + * @param otherVectorExpression The other vector (represented as an Expr) to compare against. * @return A new {@code Expr} representing the Euclidean distance between the two vectors. */ - export function euclideanDistance(expr: Expr, other: Expr): EuclideanDistance; + export function euclideanDistance( + vectorExpression: Expr, + otherVectorExpression: Expr + ): FunctionExpr; /** * @beta @@ -8439,13 +8548,13 @@ declare namespace FirebaseFirestore { * * ```typescript * // Get the vector length (dimension) of the field 'embedding'. - * vectorLength(Field.of("embedding")); + * vectorLength(field("embedding")); * ``` * - * @param expr The expression representing the Firestore Vector. + * @param vectorExpression The expression representing the Firestore Vector. * @return A new {@code Expr} representing the length of the array. */ - export function vectorLength(expr: Expr): VectorLength; + export function vectorLength(vectorExpression: Expr): FunctionExpr; /** * @beta @@ -8457,10 +8566,10 @@ declare namespace FirebaseFirestore { * vectorLength("embedding"); * ``` * - * @param field The name of the field representing the Firestore Vector. + * @param fieldName The name of the field representing the Firestore Vector. * @return A new {@code Expr} representing the length of the array. */ - export function vectorLength(field: string): VectorLength; + export function vectorLength(fieldName: string): FunctionExpr; /** * @beta @@ -8470,13 +8579,13 @@ declare namespace FirebaseFirestore { * * ```typescript * // Interpret the 'microseconds' field as microseconds since epoch. - * unixMicrosToTimestamp(Field.of("microseconds")); + * unixMicrosToTimestamp(field("microseconds")); * ``` * * @param expr The expression representing the number of microseconds since epoch. * @return A new {@code Expr} representing the timestamp. */ - export function unixMicrosToTimestamp(expr: Expr): UnixMicrosToTimestamp; + export function unixMicrosToTimestamp(expr: Expr): FunctionExpr; /** * @beta @@ -8489,10 +8598,10 @@ declare namespace FirebaseFirestore { * unixMicrosToTimestamp("microseconds"); * ``` * - * @param field The name of the field representing the number of microseconds since epoch. + * @param fieldName The name of the field representing the number of microseconds since epoch. * @return A new {@code Expr} representing the timestamp. */ - export function unixMicrosToTimestamp(field: string): UnixMicrosToTimestamp; + export function unixMicrosToTimestamp(fieldName: string): FunctionExpr; /** * @beta @@ -8501,13 +8610,13 @@ declare namespace FirebaseFirestore { * * ```typescript * // Convert the 'timestamp' field to microseconds since epoch. - * timestampToUnixMicros(Field.of("timestamp")); + * timestampToUnixMicros(field("timestamp")); * ``` * * @param expr The expression representing the timestamp. * @return A new {@code Expr} representing the number of microseconds since epoch. */ - export function timestampToUnixMicros(expr: Expr): TimestampToUnixMicros; + export function timestampToUnixMicros(expr: Expr): FunctionExpr; /** * @beta @@ -8519,10 +8628,10 @@ declare namespace FirebaseFirestore { * timestampToUnixMicros("timestamp"); * ``` * - * @param field The name of the field representing the timestamp. + * @param fieldName The name of the field representing the timestamp. * @return A new {@code Expr} representing the number of microseconds since epoch. */ - export function timestampToUnixMicros(field: string): TimestampToUnixMicros; + export function timestampToUnixMicros(fieldName: string): FunctionExpr; /** * @beta @@ -8532,13 +8641,13 @@ declare namespace FirebaseFirestore { * * ```typescript * // Interpret the 'milliseconds' field as milliseconds since epoch. - * unixMillisToTimestamp(Field.of("milliseconds")); + * unixMillisToTimestamp(field("milliseconds")); * ``` * * @param expr The expression representing the number of milliseconds since epoch. * @return A new {@code Expr} representing the timestamp. */ - export function unixMillisToTimestamp(expr: Expr): UnixMillisToTimestamp; + export function unixMillisToTimestamp(expr: Expr): FunctionExpr; /** * @beta @@ -8551,10 +8660,10 @@ declare namespace FirebaseFirestore { * unixMillisToTimestamp("milliseconds"); * ``` * - * @param field The name of the field representing the number of milliseconds since epoch. + * @param fieldName The name of the field representing the number of milliseconds since epoch. * @return A new {@code Expr} representing the timestamp. */ - export function unixMillisToTimestamp(field: string): UnixMillisToTimestamp; + export function unixMillisToTimestamp(fieldName: string): FunctionExpr; /** * @beta @@ -8563,13 +8672,13 @@ declare namespace FirebaseFirestore { * * ```typescript * // Convert the 'timestamp' field to milliseconds since epoch. - * timestampToUnixMillis(Field.of("timestamp")); + * timestampToUnixMillis(field("timestamp")); * ``` * * @param expr The expression representing the timestamp. * @return A new {@code Expr} representing the number of milliseconds since epoch. */ - export function timestampToUnixMillis(expr: Expr): TimestampToUnixMillis; + export function timestampToUnixMillis(expr: Expr): FunctionExpr; /** * @beta @@ -8581,10 +8690,10 @@ declare namespace FirebaseFirestore { * timestampToUnixMillis("timestamp"); * ``` * - * @param field The name of the field representing the timestamp. + * @param fieldName The name of the field representing the timestamp. * @return A new {@code Expr} representing the number of milliseconds since epoch. */ - export function timestampToUnixMillis(field: string): TimestampToUnixMillis; + export function timestampToUnixMillis(fieldName: string): FunctionExpr; /** * @beta @@ -8594,13 +8703,13 @@ declare namespace FirebaseFirestore { * * ```typescript * // Interpret the 'seconds' field as seconds since epoch. - * unixSecondsToTimestamp(Field.of("seconds")); + * unixSecondsToTimestamp(field("seconds")); * ``` * * @param expr The expression representing the number of seconds since epoch. * @return A new {@code Expr} representing the timestamp. */ - export function unixSecondsToTimestamp(expr: Expr): UnixSecondsToTimestamp; + export function unixSecondsToTimestamp(expr: Expr): FunctionExpr; /** * @beta @@ -8613,10 +8722,10 @@ declare namespace FirebaseFirestore { * unixSecondsToTimestamp("seconds"); * ``` * - * @param field The name of the field representing the number of seconds since epoch. + * @param fieldName The name of the field representing the number of seconds since epoch. * @return A new {@code Expr} representing the timestamp. */ - export function unixSecondsToTimestamp(field: string): UnixSecondsToTimestamp; + export function unixSecondsToTimestamp(fieldName: string): FunctionExpr; /** * @beta @@ -8625,13 +8734,13 @@ declare namespace FirebaseFirestore { * * ```typescript * // Convert the 'timestamp' field to seconds since epoch. - * timestampToUnixSeconds(Field.of("timestamp")); + * timestampToUnixSeconds(field("timestamp")); * ``` * * @param expr The expression representing the timestamp. * @return A new {@code Expr} representing the number of seconds since epoch. */ - export function timestampToUnixSeconds(expr: Expr): TimestampToUnixSeconds; + export function timestampToUnixSeconds(expr: Expr): FunctionExpr; /** * @beta @@ -8643,10 +8752,10 @@ declare namespace FirebaseFirestore { * timestampToUnixSeconds("timestamp"); * ``` * - * @param field The name of the field representing the timestamp. + * @param fieldName The name of the field representing the timestamp. * @return A new {@code Expr} representing the number of seconds since epoch. */ - export function timestampToUnixSeconds(field: string): TimestampToUnixSeconds; + export function timestampToUnixSeconds(fieldName: string): FunctionExpr; /** * @beta @@ -8655,7 +8764,7 @@ declare namespace FirebaseFirestore { * * ```typescript * // Add some duration determined by field 'unit' and 'amount' to the 'timestamp' field. - * timestampAdd(Field.of("timestamp"), Field.of("unit"), Field.of("amount")); + * timestampAdd(field("timestamp"), field("unit"), field("amount")); * ``` * * @param timestamp The expression representing the timestamp. @@ -8667,7 +8776,7 @@ declare namespace FirebaseFirestore { timestamp: Expr, unit: Expr, amount: Expr - ): TimestampAdd; + ): FunctionExpr; /** * @beta @@ -8676,7 +8785,7 @@ declare namespace FirebaseFirestore { * * ```typescript * // Add 1 day to the 'timestamp' field. - * timestampAdd(Field.of("timestamp"), "day", 1); + * timestampAdd(field("timestamp"), "day", 1); * ``` * * @param timestamp The expression representing the timestamp. @@ -8688,7 +8797,7 @@ declare namespace FirebaseFirestore { timestamp: Expr, unit: 'microsecond' | 'millisecond' | 'second' | 'minute' | 'hour' | 'day', amount: number - ): TimestampAdd; + ): FunctionExpr; /** * @beta @@ -8700,16 +8809,16 @@ declare namespace FirebaseFirestore { * timestampAdd("timestamp", "day", 1); * ``` * - * @param field The name of the field representing the timestamp. + * @param fieldName The name of the field representing the timestamp. * @param unit The unit of time to add (e.g., "day", "hour"). * @param amount The amount of time to add. * @return A new {@code Expr} representing the resulting timestamp. */ export function timestampAdd( - field: string, + fieldName: string, unit: 'microsecond' | 'millisecond' | 'second' | 'minute' | 'hour' | 'day', amount: number - ): TimestampAdd; + ): FunctionExpr; /** * @beta @@ -8718,7 +8827,7 @@ declare namespace FirebaseFirestore { * * ```typescript * // Subtract some duration determined by field 'unit' and 'amount' from the 'timestamp' field. - * timestampSub(Field.of("timestamp"), Field.of("unit"), Field.of("amount")); + * timestampSub(field("timestamp"), field("unit"), field("amount")); * ``` * * @param timestamp The expression representing the timestamp. @@ -8730,7 +8839,7 @@ declare namespace FirebaseFirestore { timestamp: Expr, unit: Expr, amount: Expr - ): TimestampSub; + ): FunctionExpr; /** * @beta @@ -8739,7 +8848,7 @@ declare namespace FirebaseFirestore { * * ```typescript * // Subtract 1 day from the 'timestamp' field. - * timestampSub(Field.of("timestamp"), "day", 1); + * timestampSub(field("timestamp"), "day", 1); * ``` * * @param timestamp The expression representing the timestamp. @@ -8751,7 +8860,7 @@ declare namespace FirebaseFirestore { timestamp: Expr, unit: 'microsecond' | 'millisecond' | 'second' | 'minute' | 'hour' | 'day', amount: number - ): TimestampSub; + ): FunctionExpr; /** * @beta @@ -8763,144 +8872,149 @@ declare namespace FirebaseFirestore { * timestampSub("timestamp", "day", 1); * ``` * - * @param field The name of the field representing the timestamp. + * @param fieldName The name of the field representing the timestamp. * @param unit The unit of time to subtract (e.g., "day", "hour"). * @param amount The amount of time to subtract. * @return A new {@code Expr} representing the resulting timestamp. */ export function timestampSub( - field: string, + fieldName: string, unit: 'microsecond' | 'millisecond' | 'second' | 'minute' | 'hour' | 'day', amount: number - ): TimestampSub; + ): FunctionExpr; /** * @beta * - * Creates functions that work on the backend but do not exist in the SDK yet. + * Creates an expression that performs a logical 'AND' operation on multiple filter conditions. * * ```typescript - * // Call a user defined function named "myFunc" with the arguments 10 and 20 - * // This is the same of the 'sum(Field.of("price"))', if it did not exist - * genericFunction("sum", [Field.of("price")]); + * // Check if the 'age' field is greater than 18 AND the 'city' field is "London" AND + * // the 'status' field is "active" + * const condition = and(gt("age", 18), eq("city", "London"), eq("status", "active")); * ``` * - * @param name The name of the user defined function. - * @param params The arguments to pass to the function. - * @return A new {@code Function} representing the function call. + * @param first The first filter condition. + * @param second The second filter condition. + * @param more Additional filter conditions to 'AND' together. + * @return A new {@code Expr} representing the logical 'AND' operation. */ - export function genericFunction(name: string, params: Expr[]): Function; + export function and( + first: BooleanExpr, + second: BooleanExpr, + ...more: BooleanExpr[] + ): BooleanExpr; /** * @beta * - * Creates an {@link Ordering} that sorts documents in ascending order based on this expression. + * Creates an expression that performs a logical 'OR' operation on multiple filter conditions. * * ```typescript - * // Sort documents by the 'name' field in ascending order - * firestore.pipeline().collection("users") - * .sort(ascending(Field.of("name"))); + * // Check if the 'age' field is greater than 18 OR the 'city' field is "London" OR + * // the 'status' field is "active" + * const condition = or(gt("age", 18), eq("city", "London"), eq("status", "active")); * ``` * - * @param expr The expression to create an ascending ordering for. - * @return A new `Ordering` for ascending sorting. + * @param first The first filter condition. + * @param second The second filter condition. + * @param more Additional filter conditions to 'OR' together. + * @return A new {@code Expr} representing the logical 'OR' operation. */ - export function ascending(expr: Expr): Ordering; + export function or( + first: BooleanExpr, + second: BooleanExpr, + ...more: BooleanExpr[] + ): BooleanExpr; /** * @beta * - * Creates an {@link Ordering} that sorts documents in descending order based on this expression. + * Creates an {@link Ordering} that sorts documents in ascending order based on an expression. * * ```typescript - * // Sort documents by the 'createdAt' field in descending order - * firestore.pipeline().collection("users") - * .sort(descending(Field.of("createdAt"))); + * // Sort documents by the 'name' field in lowercase in ascending order + * pipeline().collection("users") + * .sort(ascending(field("name").toLower())); * ``` * - * @param expr The expression to create a descending ordering for. - * @return A new `Ordering` for descending sorting. + * @param expr The expression to create an ascending ordering for. + * @return A new `Ordering` for ascending sorting. */ - export function descending(expr: Expr): Ordering; + export function ascending(expr: Expr): Ordering; /** * @beta * - * Represents an ordering criterion for sorting documents in a Firestore pipeline. + * Creates an {@link Ordering} that sorts documents in ascending order based on a field. * - * You create `Ordering` instances using the `ascending` and `descending` helper functions. - */ - export class Ordering { - /** - * @param expr The expression to order by. - * @param direction The direction to order by. - */ - constructor(expr: Expr, direction: 'ascending' | 'descending'); - } - - /** - * @beta - */ - export interface Stage { - name: string; - } - - /** - * @beta - */ - export class AddFields implements Stage { - name: string; - } - - /** - * @beta - */ - export class RemoveFields implements Stage { - name: string; - } - - /** - * @beta + * ```typescript + * // Sort documents by the 'name' field in ascending order + * pipeline().collection("users") + * .sort(ascending("name")); + * ``` + * + * @param fieldName The field to create an ascending ordering for. + * @return A new `Ordering` for ascending sorting. */ - export class Aggregate implements Stage { - name: string; - } + export function ascending(fieldName: string): Ordering; /** * @beta + * + * Creates an {@link Ordering} that sorts documents in descending order based on an expression. + * + * ```typescript + * // Sort documents by the 'name' field in lowercase in descending order + * pipeline().collection("users") + * .sort(descending(field("name").toLower())); + * ``` + * + * @param expr The expression to create a descending ordering for. + * @return A new `Ordering` for descending sorting. */ - export class Distinct implements Stage { - name: string; - } + export function descending(expr: Expr): Ordering; /** * @beta + * + * Creates an {@link Ordering} that sorts documents in descending order based on a field. + * + * ```typescript + * // Sort documents by the 'name' field in descending order + * pipeline().collection("users") + * .sort(descending("name")); + * ``` + * + * @param fieldName The field to create a descending ordering for. + * @return A new `Ordering` for descending sorting. */ - export class CollectionSource implements Stage { - name: string; - } + export function descending(fieldName: string): Ordering; /** * @beta + * + * Represents an ordering criterion for sorting documents in a Firestore pipeline. + * + * You create `Ordering` instances using the `ascending` and `descending` helper functions. */ - export class CollectionGroupSource implements Stage { - name: string; + export class Ordering { + readonly expr: Expr; + readonly direction: 'ascending' | 'descending'; } /** * @beta */ - export class DatabaseSource implements Stage { + export interface Stage { name: string; } /** * @beta */ - export class DocumentsSource implements Stage { + export class Aggregate implements Stage { name: string; - - static of(refs: DocumentReference[]): DocumentsSource; } /** @@ -8928,20 +9042,6 @@ declare namespace FirebaseFirestore { name: string; } - /** - * @beta - */ - export class Limit implements Stage { - name: string; - } - - /** - * @beta - */ - export class Offset implements Stage { - name: string; - } - /** * @beta */ @@ -8949,49 +9049,6 @@ declare namespace FirebaseFirestore { name: string; } - /** - * @beta - */ - export class Sample implements Stage { - name: string; - } - - /** - * @beta - */ - export interface SampleOptions { - limit: number; - mode: 'documents' | 'percent'; - } - - /** - * @beta - */ - export class Select implements Stage { - name: string; - } - - /** - * @beta - */ - export class Sort implements Stage { - name: string; - } - - /** - * @beta - */ - export class Union implements Stage { - name: string; - } - - /** - * @beta - */ - export class Unnest implements Stage { - name: string; - } - /** * @beta */ @@ -9001,13 +9058,6 @@ declare namespace FirebaseFirestore { indexField?: string; } - /** - * @beta - */ - export class GenericStage implements Stage { - name: string; - } - /** * Represents the source of a Firestore {@link Pipeline}. * @beta @@ -9019,7 +9069,7 @@ declare namespace FirebaseFirestore { * @param collectionPath The path to the collection. * @return A new Pipeline object with the collection as the source. */ - collection(collectionPath: string): Pipeline; + collection(collectionPath: string | CollectionReference): Pipeline; /** * Specifies the source as a collection group. @@ -9042,7 +9092,16 @@ declare namespace FirebaseFirestore { * @param docs The document references. * @return A new Pipeline object with the documents as the source. */ - documents(docs: DocumentReference[]): Pipeline; + documents(docs: Array): Pipeline; + + /** + * Convert the given Query into an equivalent Pipeline. + * + * @param query A Query to be converted into a Pipeline. + * + * @throws {@FirestoreError} Thrown if any of the provided DocumentReferences target a different project or database than the pipeline. + */ + createFrom(query: Query): Pipeline; } /** @@ -9087,7 +9146,7 @@ declare namespace FirebaseFirestore { * .execute(); * ``` */ - export class Pipeline { + export class Pipeline { /** * Adds new fields to outputs from previous stages. * @@ -9098,23 +9157,24 @@ declare namespace FirebaseFirestore { * The added fields are defined using {@link Selectable}s, which can be: * * - {@link Field}: References an existing document field. - * - {@link Function}: Performs a calculation using functions like `add`, `multiply` with - * assigned aliases using {@link Expr#as}. + * - {@link Expr}: Either a literal value (see {@link Constant}) or a computed value + * (see {@FunctionExpr}) with an assigned alias using {@link Expr#as}. * * Example: * * ```typescript * firestore.pipeline().collection("books") * .addFields( - * Field.of("rating").as("bookRating"), // Rename 'rating' to 'bookRating' - * add(5, Field.of("quantity")).as("totalCost") // Calculate 'totalCost' + * field("rating").as("bookRating"), // Rename 'rating' to 'bookRating' + * add(5, field("quantity")).as("totalCost") // Calculate 'totalCost' * ); * ``` * - * @param fields The fields to add to the documents, specified as {@link Selectable}s. + * @param field The first field to add to the documents, specified as a {@link Selectable}. + * @param additionalFields Optional additional fields to add to the documents, specified as {@link Selectable}s. * @return A new Pipeline object with this stage appended to the stage list. */ - addFields(...fields: Selectable[]): Pipeline; + addFields(field: Selectable, ...additionalFields: Selectable[]): Pipeline; /** * Remove fields from outputs of previous stages. @@ -9122,18 +9182,22 @@ declare namespace FirebaseFirestore { * Example: * * ```typescript - * firestore.pipeline().collection("books") + * firestore.pipeline().collection('books') * // removes field 'rating' and 'cost' from the previous stage outputs. * .removeFields( - * Field.of("rating"), - * "cost" + * field('rating'), + * 'cost' * ); * ``` * - * @param fields The fields to remove. + * @param fieldValue The first field to remove. + * @param additionalFields Optional additional fields to remove. * @return A new Pipeline object with this stage appended to the stage list. */ - removeFields(...fields: (Field | string)[]): Pipeline; + removeFields( + fieldValue: Field | string, + ...additionalFields: Array + ): Pipeline; /** * Selects or creates a set of fields from the outputs of previous stages. @@ -9148,7 +9212,7 @@ declare namespace FirebaseFirestore { * * *

If no selections are provided, the output of this stage is empty. Use {@link - * com.google.cloud.firestore.Pipeline#addFields} instead if only additions are + * Pipeline#addFields} instead if only additions are * desired. * *

Example: @@ -9157,24 +9221,29 @@ declare namespace FirebaseFirestore { * firestore.pipeline().collection("books") * .select( * "firstName", - * Field.of("lastName"), - * Field.of("address").toUppercase().as("upperAddress"), + * field("lastName"), + * field("address").toUppercase().as("upperAddress"), * ); * ``` * - * @param selections The fields to include in the output documents, specified as {@link + * @param selection The first field to include in the output documents, specified as {@link + * Selectable} expression or string value representing the field name. + * @param additionalSelections Optional additional fields to include in the output documents, specified as {@link * Selectable} expressions or {@code string} values representing field names. * @return A new Pipeline object with this stage appended to the stage list. */ - select(...fields: (Selectable | string)[]): Pipeline; + select( + selection: Selectable | string, + ...additionalSelections: Array + ): Pipeline; /** * Filters the documents from previous stages to only include those matching the specified {@link - * FilterCondition}. + * BooleanExpr}. * *

This stage allows you to apply conditions to the data, similar to a "WHERE" clause in SQL. * You can filter documents based on their field values, using implementations of {@link - * FilterCondition}, typically including but not limited to: + * BooleanExpr}, typically including but not limited to: * *

    *
  • field comparators: {@link Function#eq}, {@link Function#lt} (less than), {@link @@ -9190,16 +9259,16 @@ declare namespace FirebaseFirestore { * firestore.pipeline().collection("books") * .where( * and( - * gt(Field.of("rating"), 4.0), // Filter for ratings greater than 4.0 - * Field.of("genre").eq("Science Fiction") // Equivalent to gt("genre", "Science Fiction") + * gt(field("rating"), 4.0), // Filter for ratings greater than 4.0 + * field("genre").eq("Science Fiction") // Equivalent to gt("genre", "Science Fiction") * ) * ); * ``` * - * @param condition The {@link FilterCondition} to apply. + * @param condition The {@link BooleanExpr} to apply. * @return A new Pipeline object with this stage appended to the stage list. */ - where(condition: FilterCondition & Expr): Pipeline; + where(condition: BooleanExpr): Pipeline; /** * Skips the first `offset` number of documents from the results of previous stages. @@ -9221,7 +9290,7 @@ declare namespace FirebaseFirestore { * @param offset The number of documents to skip. * @return A new Pipeline object with this stage appended to the stage list. */ - offset(offset: number): Pipeline; + offset(offset: number): Pipeline; /** * Limits the maximum number of documents returned by previous stages to `limit`. @@ -9248,44 +9317,47 @@ declare namespace FirebaseFirestore { * @param limit The maximum number of documents to return. * @return A new Pipeline object with this stage appended to the stage list. */ - limit(limit: number): Pipeline; + limit(limit: number): Pipeline; /** - * Returns a set of distinct {@link Expr} values from the inputs to this stage. + * Returns a set of distinct values from the inputs to this stage. * - *

    This stage run through the results from previous stages to include only results with unique - * combinations of {@link Expr} values ({@link Field}, {@link Function}, etc). + * This stage runs through the results from previous stages to include only results with + * unique combinations of {@link Expr} values ({@link Field}, {@link Function}, etc). * - *

    The parameters to this stage are defined using {@link Selectable} expressions or {@code string}s: + * The parameters to this stage are defined using {@link Selectable} expressions or strings: * - *

      - *
    • {@code string}: Name of an existing field
    • - *
    • {@link Field}: References an existing document field.
    • - *
    • {@link Function}: Represents the result of a function with an assigned alias name using - * {@link Expr#as}
    • - *
    + * - {@code string}: Name of an existing field + * - {@link Field}: References an existing document field. + * - {@link ExprWithAlias}: Represents the result of a function with an assigned alias name + * using {@link Expr#as}. * - *

    Example: + * Example: * * ```typescript * // Get a list of unique author names in uppercase and genre combinations. * firestore.pipeline().collection("books") - * .distinct(toUppercase(Field.of("author")).as("authorName"), Field.of("genre"), "publishedAt") + * .distinct(toUppercase(field("author")).as("authorName"), field("genre"), "publishedAt") * .select("authorName"); * ``` * - * @param selectables The {@link Selectable} expressions to consider when determining distinct - * value combinations or {@code string}s representing field names. + * @param group The {@link Selectable} expression or field name to consider when determining + * distinct value combinations. + * @param additionalGroups Optional additional {@link Selectable} expressions to consider when determining distinct + * value combinations or strings representing field names. * @return A new {@code Pipeline} object with this stage appended to the stage list. */ - distinct(...groups: (string | Selectable)[]): Pipeline; + distinct( + group: string | Selectable, + ...additionalGroups: Array + ): Pipeline; /** * Performs aggregation operations on the documents from previous stages. * *

    This stage allows you to calculate aggregate values over a set of documents. You define the - * aggregations to perform using {@link AccumulatorTarget} expressions which are typically results of - * calling {@link Expr#as} on {@link Accumulator} instances. + * aggregations to perform using {@link AggregateWithAlias} expressions which are typically results of + * calling {@link Expr#as} on {@link AggregateFunction} instances. * *

    Example: * @@ -9293,16 +9365,21 @@ declare namespace FirebaseFirestore { * // Calculate the average rating and the total number of books * firestore.pipeline().collection("books") * .aggregate( - * Field.of("rating").avg().as("averageRating"), + * field("rating").avg().as("averageRating"), * countAll().as("totalBooks") * ); * ``` * - * @param accumulators The {@link AccumulatorTarget} expressions, each wrapping an {@link Accumulator} - * and provide a name for the accumulated results. + * @param accumulator The first {@link AggregateWithAlias}, wrapping an {@link AggregateFunction} + * and providing a name for the accumulated results. + * @param additionalAccumulators Optional additional {@link AggregateWithAlias}, each wrapping an {@link AggregateFunction} + * and providing a name for the accumulated results. * @return A new Pipeline object with this stage appended to the stage list. */ - aggregate(...accumulators: AccumulatorTarget[]): Pipeline; + aggregate( + accumulator: AggregateWithAlias, + ...additionalAccumulators: AggregateWithAlias[] + ): Pipeline; /** * Performs optionally grouped aggregation operations on the documents from previous stages. * @@ -9315,8 +9392,8 @@ declare namespace FirebaseFirestore { * If no grouping fields are provided, a single group containing all documents is used. Not * specifying groups is the same as putting the entire inputs into one group.

  • *
  • **Accumulators:** One or more accumulation operations to perform within each group. These - * are defined using {@link AccumulatorTarget} expressions, which are typically created by - * calling {@link Expr#as} on {@link Accumulator} instances. Each aggregation + * are defined using {@link AggregateWithAlias} expressions, which are typically created by + * calling {@link Expr#as} on {@link AggregateFunction} instances. Each aggregation * calculates a value (e.g., sum, average, count) based on the documents within its group.
  • *
* @@ -9326,21 +9403,22 @@ declare namespace FirebaseFirestore { * // Calculate the average rating for each genre. * firestore.pipeline().collection("books") * .aggregate({ - * accumulators: [avg(Field.of("rating")).as("avg_rating")] + * accumulators: [avg(field("rating")).as("avg_rating")] * groups: ["genre"] * }); * ``` * - * @param aggregate An {@link Aggregate} object that specifies the grouping fields (if any) and - * the aggregation operations to perform. - * @return A new {@code Pipeline} object with this stage appended to the stage list. + * @param options An object that specifies the accumulators + * and optional grouping fields to perform. + * @return A new {@code Pipeline} object with this stage appended to the stage + * list. */ aggregate(options: { - accumulators: AccumulatorTarget[]; - groups?: (string | Selectable)[]; - }): Pipeline; + accumulators: AggregateWithAlias[]; + groups?: Array; + }): Pipeline; - findNearest(options: FindNearestOptions): Pipeline; + findNearest(options: FindNearestOptions): Pipeline; /** * Fully overwrites all fields in a document with those coming from a nested map. @@ -9353,26 +9431,65 @@ declare namespace FirebaseFirestore { * ```typescript * // Input. * // { - * // "name": "John Doe Jr.", - * // "parents": { - * // "father": "John Doe Sr.", - * // "mother": "Jane Doe" + * // 'name': 'John Doe Jr.', + * // 'parents': { + * // 'father': 'John Doe Sr.', + * // 'mother': 'Jane Doe' + * // } + * // } + * + * // Emit parents as document. + * firestore.pipeline().collection('people').replaceWith('parents'); + * + * // Output + * // { + * // 'father': 'John Doe Sr.', + * // 'mother': 'Jane Doe' + * // } + * ``` + * + * @param fieldName The {@link Field} field containing the nested map. + * @return A new {@code Pipeline} object with this stage appended to the stage list. + */ + replaceWith(fieldName: string): Pipeline; + + /** + * Fully overwrites all fields in a document with those coming from a map. + * + *

This stage allows you to emit a map value as a document. Each key of the map becomes a field + * on the document that contains the corresponding value. + * + *

Example: + * + * ```typescript + * // Input. + * // { + * // 'name': 'John Doe Jr.', + * // 'parents': { + * // 'father': 'John Doe Sr.', + * // 'mother': 'Jane Doe' + * // } * // } * * // Emit parents as document. - * firestore.pipeline().collection("people").replace(Field.of("parents")); + * firestore.pipeline().collection('people').replaceWith(map({ + * foo: 'bar', + * info: { + * name: field('name') + * } + * })); * * // Output * // { - * // "father": "John Doe Sr.", - * // "mother": "Jane Doe" + * // 'father': 'John Doe Sr.', + * // 'mother': 'Jane Doe' * // } * ``` * - * @param field The {@link Selectable} field containing the nested map. + * @param expr An {@link Expr} that when returned evaluates to a map. * @return A new {@code Pipeline} object with this stage appended to the stage list. */ - replace(field: Selectable | string): Pipeline; + replaceWith(expr: Expr): Pipeline; /** * Performs a pseudo-random sampling of the documents from the previous stage. @@ -9384,15 +9501,14 @@ declare namespace FirebaseFirestore { * * ```typescript * // Sample 25 books, if available. - * firestore.pipeline().collection("books") + * firestore.pipeline().collection('books') * .sample(25); - * } * ``` * * @param documents The number of documents to sample. * @return A new {@code Pipeline} object with this stage appended to the stage list. */ - sample(documents: number): Pipeline; + sample(documents: number): Pipeline; /** * Performs a pseudo-random sampling of the documents from the previous stage. @@ -9402,7 +9518,6 @@ declare namespace FirebaseFirestore { * *

Examples: * - * ```typescript * // Sample 10 books, if available. * firestore.pipeline().collection("books") * .sample({ documents: 10 }); @@ -9410,15 +9525,11 @@ declare namespace FirebaseFirestore { * // Sample 50% of books. * firestore.pipeline().collection("books") * .sample({ percentage: 0.5 }); - * } - * ``` * * @param options The {@code SampleOptions} specifies how sampling is performed. * @return A new {@code Pipeline} object with this stage appended to the stage list. */ - sample( - options: {percentage: number} | {documents: number} - ): Pipeline; + sample(options: {percentage: number} | {documents: number}): Pipeline; /** * Sorts the documents from previous stages based on one or more {@link Ordering} criteria. @@ -9436,16 +9547,16 @@ declare namespace FirebaseFirestore { * // with the same rating * firestore.pipeline().collection("books") * .sort( - * Field.of("rating").descending(), - * Field.of("title").ascending() + * Ordering.of(field("rating")).descending(), + * Ordering.of(field("title")) // Ascending order is the default * ); * ``` * - * @param orders One or more {@link Ordering} instances specifying the sorting criteria. + * @param ordering The first {@link Ordering} instance specifying the sorting criteria. + * @param additionalOrderings Optional additional {@link Ordering} instances specifying the additional sorting criteria. * @return A new {@code Pipeline} object with this stage appended to the stage list. */ - sort(...orderings: Ordering[]): Pipeline; - sort(options: {orderings: Ordering[]}): Pipeline; + sort(ordering: Ordering, ...additionalOrderings: Ordering[]): Pipeline; /** * Performs union of all documents from two pipelines, including duplicates. @@ -9458,30 +9569,28 @@ declare namespace FirebaseFirestore { * * ```typescript * // Emit documents from books collection and magazines collection. - * firestore.pipeline().collection("books") - * .union(firestore.pipeline().collection("magazines")); - * } + * firestore.pipeline().collection('books') + * .union(firestore.pipeline().collection('magazines')); * ``` * * @param other The other {@code Pipeline} that is part of union. * @return A new {@code Pipeline} object with this stage appended to the stage list. */ - union(other: Pipeline): Pipeline; + union(other: Pipeline): Pipeline; /** - * Produces a document for each element in array found in previous stage document. + * Produces a document for each element in an input array. * - *

For each previous stage document, this stage will emit zero or more augmented documents. The - * input array found in the previous stage document field specified by the `fieldName` parameter, - * will emit an augmented document for each input array element. The input array element will + * For each previous stage document, this stage will emit zero or more augmented documents. The + * input array specified by the `selectable` parameter, will emit an augmented document for each input array element. The input array element will * augment the previous stage document by setting the `alias` field with the array element value. * - *

When `fieldName` evaluates to a non-array value (ex: number, null, absent), then the stage becomes a no-op for + * When `selectable` evaluates to a non-array value (ex: number, null, absent), then the stage becomes a no-op for * the current input document, returning it as is with the `alias` field absent. * - *

No documents are emitted when `fieldName` evaluates to an empty array. + * No documents are emitted when `selectable` evaluates to an empty array. * - *

Example: + * Example: * * ```typescript * // Input: @@ -9489,54 +9598,19 @@ declare namespace FirebaseFirestore { * * // Emit a book document for each tag of the book. * firestore.pipeline().collection("books") - * .unnest("tags"); - * - * // Output: - * // { "title": "The Hitchhiker's Guide to the Galaxy", "tag": "comedy", ... } - * // { "title": "The Hitchhiker's Guide to the Galaxy", "tag": "space", ... } - * // { "title": "The Hitchhiker's Guide to the Galaxy", "tag": "adventure", ... } - * ``` - * - * @param field The name of the field containing the array. - * @param alias The alias field is used as the field name for each element within the output array. The alias does - * not overwrite the original field unless the field names match. - * @return A new {@code Pipeline} object with this stage appended to the stage list. - */ - unnest(field: Selectable | string, alias: string): Pipeline; - - /** - * Produces a document for each element in array found in previous stage document. - * - *

For each previous stage document, this stage will emit zero or more augmented documents. The - * input array found in the previous stage document field specified by the `fieldName` parameter, - * will emit an augmented document for each input array element. The input array element will - * augment the previous stage document by setting the `alias` field with the array element value. - * - *

When `fieldName` evaluates to a non-array value (ex: number, null, absent), then the stage becomes a no-op for - * the current input document, returning it as is with the `alias` field absent and `indexField` set to null. - * - *

No documents are emitted when `fieldName` evaluates to an empty array. - * - *

Example: - * - * ```typescript - * // Input: - * // { 'title': 'The Hitchhiker's Guide to the Galaxy', 'tags': [ 'comedy', 'space', 'adventure' ], ... } - * - * // Emit a book document for each tag of the book. - * firestore.pipeline().collection('books') - * .unnest({ field: 'tags', alias: 'tag', UnnestOptions.indexField('tagIndex')}); + * .unnest(field("tags").as('tag'), 'tagIndex'); * * // Output: - * // { 'title': 'The Hitchhiker's Guide to the Galaxy', 'tagIndex': 0, 'tag': 'comedy', ... } - * // { 'title': 'The Hitchhiker's Guide to the Galaxy', 'tagIndex': 1, 'tag': 'space', ... } - * // { 'title': 'The Hitchhiker's Guide to the Galaxy', 'tagIndex': 2, 'tag': 'adventure', ... } + * // { "title": "The Hitchhiker's Guide to the Galaxy", "tag": "comedy", "tagIndex": 0, ... } + * // { "title": "The Hitchhiker's Guide to the Galaxy", "tag": "space", "tagIndex": 1, ... } + * // { "title": "The Hitchhiker's Guide to the Galaxy", "tag": "adventure", "tagIndex": 2, ... } * ``` * - * @param options The {@code UnnestOptions} options. + * @param selectable A selectable expression defining the field to unnest and the alias to use for each un-nested element in the output documents. + * @param indexField An optional string value specifying the field path to write the offset (starting at zero) into the array the un-nested element is from * @return A new {@code Pipeline} object with this stage appended to the stage list. */ - unnest(options: UnnestOptions): Pipeline; + unnest(selectable: Selectable, indexField?: string): Pipeline; /** * Adds a generic stage to the pipeline. @@ -9558,11 +9632,7 @@ declare namespace FirebaseFirestore { * @param params A list of parameters to configure the generic stage's behavior. * @return A new {@code Pipeline} object with this stage appended to the stage list. */ - genericStage(name: string, params: any[]): Pipeline; - withConverter(converter: null): Pipeline; - withConverter( - converter: FirestorePipelineConverter - ): Pipeline; + genericStage(name: string, params: any[]): Pipeline; /** * Executes this pipeline and returns a Promise to represent the asynchronous operation. * @@ -9594,7 +9664,7 @@ declare namespace FirebaseFirestore { * * @return A Promise representing the asynchronous pipeline execution. */ - execute(): Promise>>; + execute(): Promise; /** * Executes this pipeline and streams the results as {@link PipelineResult}s. @@ -9614,6 +9684,28 @@ declare namespace FirebaseFirestore { */ stream(): NodeJS.ReadableStream; } + /** + * TODO(docs) + */ + export class PipelineSnapshot { + /** + * The Pipeline on which you called `execute()` in order to get this + * `PipelineSnapshot`. + */ + get pipeline(): Pipeline; + + /** An array of all the results in the `PipelineSnapshot`. */ + get results(): PipelineResult[]; + + /** + * The time at which the pipeline producing this result is executed. + * + * @type {Timestamp} + * @readonly + * + */ + get executionTime(): Timestamp; + } /** * @beta @@ -9624,7 +9716,7 @@ declare namespace FirebaseFirestore { *

If the PipelineResult represents a non-document result, `ref` will return a undefined * value. */ - export class PipelineResult { + export class PipelineResult { readonly executionTime: Timestamp; readonly createTime: Timestamp | undefined; readonly updateTime: Timestamp | undefined; @@ -9632,7 +9724,7 @@ declare namespace FirebaseFirestore { /** * The reference of the document, if it is a document; otherwise `undefined`. */ - get ref(): DocumentReference | undefined; + // get ref(): DocumentReference | undefined; /** * The ID of the document for which this PipelineResult contains data, if it is a document; otherwise `undefined`. @@ -9643,6 +9735,8 @@ declare namespace FirebaseFirestore { */ get id(): string | undefined; + get ref(): DocumentReference | undefined; + /** * Retrieves all fields in the result as an object. Returns 'undefined' if * the document doesn't exist. @@ -9660,7 +9754,7 @@ declare namespace FirebaseFirestore { * }); * ``` */ - data(): AppModelType | undefined; + data(): DocumentData | undefined; /** * Retrieves the field specified by `field`. @@ -9693,7 +9787,7 @@ declare namespace FirebaseFirestore { * @return {boolean} true if this `PipelineResult` is equal to the provided * value. */ - isEqual(other: PipelineResult): boolean; + isEqual(other: PipelineResult): boolean; } /** From 1276253e4ace6b09de91303a1255da0b2d1c8b52 Mon Sep 17 00:00:00 2001 From: Mark Duckworth <1124037+MarkDuckworth@users.noreply.github.com> Date: Fri, 18 Apr 2025 15:45:23 -0600 Subject: [PATCH 36/60] Passing main set of integration tests --- dev/src/expression.ts | 341 ++++++++++++++++++++++++------------ dev/src/index.ts | 8 +- dev/src/pipeline-util.ts | 133 +++++++++++--- dev/src/pipeline.ts | 162 +++++++++++++---- dev/src/serializer.ts | 31 +++- dev/src/stage.ts | 48 +++-- dev/system-test/pipeline.ts | 127 ++++++++++---- 7 files changed, 638 insertions(+), 212 deletions(-) diff --git a/dev/src/expression.ts b/dev/src/expression.ts index 385a60af8..4d094c1c8 100644 --- a/dev/src/expression.ts +++ b/dev/src/expression.ts @@ -15,92 +15,20 @@ import * as protos from '../protos/firestore_v1_proto_api'; import api = protos.google.firestore.v1; -import * as firestore from '@google-cloud/firestore'; +import type * as firestore from '@google-cloud/firestore'; import {VectorValue} from './field-value'; import {FieldPath} from './path'; import {Pipeline} from './pipeline'; -import {isFirestoreValue} from './pipeline-util'; -import {Serializer} from './serializer'; +import { + fieldOrExpression, + isFirestoreValue, + valueToDefaultExpr, + vectorToExpr, +} from './pipeline-util'; +import {HasUserData, Serializer, validateUserInput} from './serializer'; import {cast} from './util'; -function isPlainObject(...args: unknown[]): boolean { - throw 'TODO implement isPlainObject'; -} -function isString(val: unknown): val is string { - throw 'TODO implement isString'; -} - -/** - * Converts a value to an Expr, Returning either a Constant, MapFunction, - * ArrayFunction, or the input itself (if it's already an expression). - * - * @private - * @internal - * @param value - */ -function valueToDefaultExpr(value: unknown): Expr { - let result: Expr | undefined; - if (value instanceof Expr) { - return value; - } - if (value instanceof firestore.Expr) { - throw new Error('Unsupported Expr type: ' + typeof value); - } else if (isPlainObject(value)) { - result = map(value as Record); - } else if (value instanceof Array) { - result = array(value); - } else { - result = new Constant(value); - } - - // TODO(pipeline) is this still used? - result._createdFromLiteral = true; - return result; -} - -/** - * Converts a value to an Expr, Returning either a Constant, MapFunction, - * ArrayFunction, or the input itself (if it's already an expression). - * - * @private - * @internal - * @param value - */ -function vectorToExpr( - value: firestore.VectorValue | number[] | firestore.Expr -): Expr { - if (value instanceof Expr) { - return value; - } else if (value instanceof VectorValue || Array.isArray(value)) { - const result = constantVector(value); - result._createdFromLiteral = true; - return result; - } else { - throw new Error('Unsupported value: ' + typeof value); - } -} - -/** - * Converts a value to an Expr, 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 - */ -export function fieldOrExpression(value: unknown): Expr { - if (isString(value)) { - const result = field(value); - result._createdFromLiteral = true; - return result; - } else { - return valueToDefaultExpr(value); - } -} - /** * @beta * @@ -117,7 +45,7 @@ export function fieldOrExpression(value: unknown): Expr { * The `Expr` class provides a fluent API for building expressions. You can chain together * method calls to create complex expressions. */ -export abstract class Expr extends firestore.Expr { +export abstract class Expr implements firestore.Expr, HasUserData { abstract readonly exprType: firestore.ExprType; /** @@ -135,6 +63,12 @@ export abstract class Expr extends firestore.Expr { abstract _toProto(serializer: Serializer): api.IValue; _protoValueType = 'ProtoValue' as const; + /** + * @private + * @internal + */ + abstract _validateUserData(ignoreUndefinedProperties: boolean): void; + /** * Creates an expression that adds this expression to another expression. * @@ -525,7 +459,7 @@ export abstract class Expr extends firestore.Expr { arrayContainsAll(values: unknown[] | firestore.Expr): BooleanExpr { const normalizedExpr = Array.isArray(values) ? new ListOfExprs(values.map(valueToDefaultExpr)) - : values; + : cast(values); return new BooleanExpr('array_contains_all', [this, normalizedExpr]); } @@ -560,7 +494,7 @@ export abstract class Expr extends firestore.Expr { ): BooleanExpr { const normalizedExpr = Array.isArray(values) ? new ListOfExprs(values.map(valueToDefaultExpr)) - : values; + : cast(values); return new BooleanExpr('array_contains_any', [this, normalizedExpr]); } @@ -608,7 +542,7 @@ export abstract class Expr extends firestore.Expr { eqAny(others: unknown[] | firestore.Expr): BooleanExpr { const exprOthers = Array.isArray(others) ? new ListOfExprs(others.map(valueToDefaultExpr)) - : others; + : cast(others); return new BooleanExpr('eq_any', [this, exprOthers]); } @@ -641,7 +575,7 @@ export abstract class Expr extends firestore.Expr { notEqAny(others: unknown[] | firestore.Expr): BooleanExpr { const exprOthers = Array.isArray(others) ? new ListOfExprs(others.map(valueToDefaultExpr)) - : others; + : cast(others); return new BooleanExpr('not_eq_any', [this, exprOthers]); } @@ -1997,7 +1931,9 @@ export abstract class Expr extends firestore.Expr { * * A class that represents an aggregate function. */ -export class AggregateFunction extends firestore.AggregateFunction { +export class AggregateFunction + implements firestore.AggregateFunction, HasUserData +{ exprType: firestore.ExprType = 'AggregateFunction'; /** @@ -2008,12 +1944,20 @@ export class AggregateFunction extends firestore.AggregateFunction { */ _createdFromLiteral = false; + /** + * @private + * @internal + */ + _validateUserData(ignoreUndefinedProperties: boolean): void { + this.params.forEach(expr => { + return expr._validateUserData(ignoreUndefinedProperties); + }); + } + constructor( private name: string, private params: Expr[] - ) { - super(name, params); - } + ) {} /** * Assigns an alias to this AggregateFunction. The alias specifies the name that @@ -2054,13 +1998,13 @@ export class AggregateFunction extends firestore.AggregateFunction { * * An AggregateFunction with alias. */ -export class AggregateWithAlias extends firestore.AggregateWithAlias { +export class AggregateWithAlias + implements firestore.AggregateWithAlias, HasUserData +{ constructor( readonly aggregate: AggregateFunction, readonly alias: string - ) { - super(); - } + ) {} /** * @internal @@ -2069,12 +2013,20 @@ export class AggregateWithAlias extends firestore.AggregateWithAlias { * by the caller. */ _createdFromLiteral = false; + + /** + * @private + * @internal + */ + _validateUserData(ignoreUndefinedProperties: boolean): void { + this.aggregate._validateUserData(ignoreUndefinedProperties); + } } /** * @beta */ -export class ExprWithAlias implements firestore.Selectable { +export class ExprWithAlias implements firestore.Selectable, HasUserData { exprType: firestore.ExprType = 'ExprWithAlias'; selectable = true as const; @@ -2090,6 +2042,14 @@ export class ExprWithAlias implements firestore.Selectable { readonly expr: Expr, readonly alias: string ) {} + + /** + * @private + * @internal + */ + _validateUserData(ignoreUndefinedProperties: boolean): void { + this.expr._validateUserData(ignoreUndefinedProperties); + } } /** @@ -2113,6 +2073,16 @@ class ListOfExprs extends Expr { }, }; } + + /** + * @private + * @internal + */ + _validateUserData(ignoreUndefinedProperties: boolean): void { + this.exprs.forEach(expr => { + return expr._validateUserData(ignoreUndefinedProperties); + }); + } } /** @@ -2168,6 +2138,12 @@ export class Field extends Expr implements firestore.Selectable { fieldReferenceValue: this.fieldPath.formattedName, }; } + + /** + * @private + * @internal + */ + _validateUserData(ignoreUndefinedProperties: boolean): void {} } /** @@ -2249,6 +2225,18 @@ export class Constant extends Expr { return serializer.encodeValue(this.value)!; } + + /** + * @private + * @internal + */ + _validateUserData(ignoreUndefinedProperties: boolean): void { + validateUserInput('value', this.value, 'constant value', { + allowUndefined: ignoreUndefinedProperties, + allowDeletes: 'none', + allowTransforms: false, + }); + } } /** @@ -2341,6 +2329,13 @@ export function constant(value: api.IValue): Constant; */ export function constant(value: firestore.VectorValue): Constant; +/** + * @internal + * @private + * @param value + */ +export function constant(value: unknown): Constant; + export function constant(value: unknown): Constant { return new Constant(value); } @@ -2360,9 +2355,9 @@ export function constantVector( value: number[] | firestore.VectorValue ): Constant { if (value instanceof VectorValue) { - return new Constant(value); + return constant(value); } else { - return new Constant(new VectorValue(value as number[])); + return constant(new VectorValue(value as number[])); } } @@ -2381,6 +2376,16 @@ export class MapValue extends Expr { _toProto(serializer: Serializer): api.IValue { return serializer.encodeValue(this.plainObject); } + + /** + * @private + * @internal + */ + _validateUserData(ignoreUndefinedProperties: boolean): void { + this.plainObject.forEach(expr => { + return expr._validateUserData(ignoreUndefinedProperties); + }); + } } /** @@ -2396,8 +2401,8 @@ export class FunctionExpr extends Expr { readonly exprType: firestore.ExprType = 'Function'; constructor( - private name: string, - private params: firestore.Expr[] + protected name: string, + private params: Expr[] ) { super(); } @@ -2414,6 +2419,111 @@ export class FunctionExpr extends Expr { }, }; } + + /** + * @private + * @internal + */ + _validateUserData(ignoreUndefinedProperties: boolean): void { + this.params.forEach(expr => { + return expr._validateUserData(ignoreUndefinedProperties); + }); + } +} + +/** + * @beta + * + * This class defines the base class for Firestore {@link 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 and}, {@link eq}, + * or the methods on {@link Expr} ({@link Expr#eq}, {@link Expr#lt}, etc.) to construct new Function instances. + */ +class MapFunctionExpr extends FunctionExpr { + readonly exprType: firestore.ExprType = 'Function'; + + constructor(private map: Record) { + super('map', []); + } + + /** + * @private + * @internal + */ + _toProto(serializer: Serializer): api.IValue { + const args: api.IValue[] = []; + for (const key in this.map) { + if (Object.prototype.hasOwnProperty.call(this.map, key)) { + if (this.map[key]) { + args.push(constant(key)._toProto(serializer)); + args.push(this.map[key]._toProto(serializer)); + } + } + } + return { + functionValue: { + name: this.name, + args: args, + }, + }; + } + + /** + * @private + * @internal + */ + _validateUserData(ignoreUndefinedProperties: boolean): void { + validateUserInput('value', this.map, 'map value', { + allowUndefined: ignoreUndefinedProperties, + allowTransforms: false, + allowDeletes: 'none', + }); + } +} + +/** + * @beta + * + * This class defines the base class for Firestore {@link 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 and}, {@link eq}, + * or the methods on {@link Expr} ({@link Expr#eq}, {@link Expr#lt}, etc.) to construct new Function instances. + */ +class ArrayFunctionExpr extends FunctionExpr { + readonly exprType: firestore.ExprType = 'Function'; + + constructor(private values: Array) { + super('array', []); + } + + /** + * @private + * @internal + */ + _toProto(serializer: Serializer): api.IValue { + return { + functionValue: { + name: this.name, + args: this.values + .filter(v => !!v) + .map(value => value._toProto(serializer)), + }, + }; + } + + /** + * @private + * @internal + */ + _validateUserData(ignoreUndefinedProperties: boolean): void { + validateUserInput('value', this.values, 'array value', { + allowUndefined: ignoreUndefinedProperties, + allowTransforms: false, + allowDeletes: 'none', + }); + } } /** @@ -3779,15 +3889,17 @@ export function mod( * @return A new {@code Expr} representing the map function. */ export function map(elements: Record): FunctionExpr { - const result: firestore.Expr[] = []; + const result: Record = {}; + for (const key in elements) { if (Object.prototype.hasOwnProperty.call(elements, key)) { - const value = elements[key]; - result.push(constant(key)); - result.push(valueToDefaultExpr(value)); + result[key] = + elements[key] !== undefined + ? valueToDefaultExpr(elements[key]) + : undefined; } } - return new FunctionExpr('map', result); + return new MapFunctionExpr(result); } /** @@ -3826,9 +3938,10 @@ export function _mapValue(plainObject: Record): MapValue { * @return A new {@code Expr} representing the array function. */ export function array(elements: unknown[]): FunctionExpr { - return new FunctionExpr( - 'array', - elements.map(element => valueToDefaultExpr(element)) + return new ArrayFunctionExpr( + elements.map(element => { + return element !== undefined ? valueToDefaultExpr(element) : undefined; + }) ); } @@ -4822,7 +4935,11 @@ export function cond( thenExpr: firestore.Expr, elseExpr: firestore.Expr ): FunctionExpr { - return new FunctionExpr('cond', [condition, thenExpr, elseExpr]); + return new FunctionExpr('cond', [ + condition, + cast(thenExpr), + cast(elseExpr), + ]); } /** @@ -6927,7 +7044,7 @@ export function descending(field: firestore.Expr | string): Ordering { * * You create `Ordering` instances using the `ascending` and `descending` helper functions. */ -export class Ordering { +export class Ordering implements HasUserData { constructor( readonly expr: firestore.Expr, readonly direction: 'ascending' | 'descending' @@ -6958,4 +7075,12 @@ export class Ordering { } _protoValueType: 'ProtoValue' = 'ProtoValue' as const; + + /** + * @private + * @internal + */ + _validateUserData(ignoreUndefinedProperties: boolean): void { + (this.expr as Expr)._validateUserData(ignoreUndefinedProperties); + } } diff --git a/dev/src/index.ts b/dev/src/index.ts index 5079838a5..184eaa7d2 100644 --- a/dev/src/index.ts +++ b/dev/src/index.ts @@ -133,10 +133,14 @@ export type { ExplainMetrics, ExplainResults, } from './query-profile'; -export {Pipeline, PipelineResult, PipelineSource, PipelineSnapshot} from './pipeline'; +export { + Pipeline, + PipelineResult, + PipelineSource, + PipelineSnapshot, +} from './pipeline'; export type {FindNearestOptions} from './stage'; export { - Selectable, BooleanExpr, AggregateWithAlias, AggregateFunction, diff --git a/dev/src/pipeline-util.ts b/dev/src/pipeline-util.ts index ef9d51239..08ee9805a 100644 --- a/dev/src/pipeline-util.ts +++ b/dev/src/pipeline-util.ts @@ -12,7 +12,7 @@ // See the License for the specific language governing permissions and // limitations under the License. -import * as firestore from '@google-cloud/firestore'; +import type * as firestore from '@google-cloud/firestore'; import {GoogleError} from 'google-gax'; import {Duplex, Transform} from 'stream'; import {google} from '../protos/firestore_v1_proto_api'; @@ -28,8 +28,13 @@ import { ExprWithAlias, field as createField, constant, + map, + array, + Constant, + constantVector, + field, } from './expression'; -import Firestore, {DocumentReference, Timestamp} from './index'; +import Firestore, {DocumentReference, Timestamp, VectorValue} from './index'; import {logger} from './logger'; import {QualifiedResourcePath} from './path'; import {Pipeline, PipelineResult} from './pipeline'; @@ -44,6 +49,7 @@ import { getTotalTimeout, isObject, isPermanentRpcError, + isPlainObject, requestTag, wrapError, } from './util'; @@ -72,34 +78,38 @@ export class ExecutionUtil { // Capture the error stack to preserve stack tracing across async calls. const stack = Error().stack!; - return new Promise((resolve, reject) => { + return new Promise((resolve, reject): void => { const result: Array = []; const output: PipelineResponse = {}; - this._stream(pipeline, transactionOrReadTime, explainOptions) - .on('error', err => { - reject(wrapError(err, stack)); - }) - .on('data', (data: PipelineStreamElement[]) => { - for (const element of data) { - if (element.transaction) { - output.transaction = element.transaction; - } - if (element.executionTime) { - output.executionTime = element.executionTime; - } - if (element.explainMetrics) { - output.explainMetrics = element.explainMetrics; - } - if (element.result) { - result.push(element.result); - } + const stream: NodeJS.EventEmitter = this._stream( + pipeline, + transactionOrReadTime, + explainOptions + ); + stream.on('error', err => { + reject(wrapError(err, stack)); + }); + stream.on('data', (data: PipelineStreamElement[]) => { + for (const element of data) { + if (element.transaction) { + output.transaction = element.transaction; + } + if (element.executionTime) { + output.executionTime = element.executionTime; + } + if (element.explainMetrics) { + output.explainMetrics = element.explainMetrics; } - }) - .on('end', () => { - output.result = result; - resolve(output); - }); + if (element.result) { + result.push(element.result); + } + } + }); + stream.on('end', () => { + output.result = result; + resolve(output); + }); }); } @@ -473,3 +483,74 @@ export function toPipelineBooleanExpr( `Failed to convert filter to pipeline conditions: ${f.toProto()}` ); } + +export function isString(val: unknown): val is string { + return typeof val === 'string'; +} + +/** + * Converts a value to an Expr, Returning either a Constant, MapFunction, + * ArrayFunction, or the input itself (if it's already an expression). + * + * @private + * @internal + * @param value + */ +export function valueToDefaultExpr(value: unknown): Expr { + let result: Expr | undefined; + if (value instanceof Expr) { + return value; + } else if (isPlainObject(value)) { + result = map(value as Record); + } else if (value instanceof Array) { + result = array(value); + } else { + result = constant(value); + } + + // TODO(pipeline) is this still used? + result._createdFromLiteral = true; + return result; +} + +/** + * Converts a value to an Expr, Returning either a Constant, MapFunction, + * ArrayFunction, or the input itself (if it's already an expression). + * + * @private + * @internal + * @param value + */ +export function vectorToExpr( + value: firestore.VectorValue | number[] | firestore.Expr +): Expr { + if (value instanceof Expr) { + return value; + } else if (value instanceof VectorValue || Array.isArray(value)) { + const result = constantVector(value); + result._createdFromLiteral = true; + return result; + } else { + throw new Error('Unsupported value: ' + typeof value); + } +} + +/** + * Converts a value to an Expr, 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 + */ +export function fieldOrExpression(value: unknown): Expr { + if (isString(value)) { + const result = field(value); + result._createdFromLiteral = true; + return result; + } else { + return valueToDefaultExpr(value); + } +} diff --git a/dev/src/pipeline.ts b/dev/src/pipeline.ts index 16d77fd5e..8c030395d 100644 --- a/dev/src/pipeline.ts +++ b/dev/src/pipeline.ts @@ -23,15 +23,16 @@ import { Field, BooleanExpr, Ordering, + constant, + _mapValue, field, - fieldOrExpression, } from './expression'; import Firestore, {CollectionReference, FieldPath, Timestamp} from './index'; import {validateFieldPath} from './path'; -import {ExecutionUtil} from './pipeline-util'; +import {ExecutionUtil, fieldOrExpression} from './pipeline-util'; import {DocumentReference} from './reference/document-reference'; import {PipelineResponse} from './reference/types'; -import {Serializer} from './serializer'; +import {HasUserData, hasUserData, Serializer} from './serializer'; import { AddFields, Aggregate, @@ -49,17 +50,17 @@ import { Stage, Distinct, RemoveFields, - Replace, + ReplaceWith, Sample, Union, Unnest, - UnnestOptions, } from './stage'; import {ApiMapValue} from './types'; import * as protos from '../protos/firestore_v1_proto_api'; import api = protos.google.firestore.v1; import IStage = google.firestore.v1.Pipeline.IStage; -import {cast, isOptionalEqual} from './util'; +import {cast, isOptionalEqual, isPlainObject} from './util'; +import {validateDocumentReference} from './reference/helpers'; /** * Represents the source of a Firestore {@link Pipeline}. @@ -70,7 +71,7 @@ export class PipelineSource implements firestore.PipelineSource { collection(collection: string | firestore.CollectionReference): Pipeline { if (collection instanceof CollectionReference) { - // this._validateReference(collection); + this._validateReference(collection); return new Pipeline(this.db, [new CollectionSource(collection.path)]); } else if (typeof collection === 'string') { return new Pipeline(this.db, [new CollectionSource(collection)]); @@ -96,6 +97,9 @@ export class PipelineSource implements firestore.PipelineSource { * @throws {@FirestoreError} Thrown if any of the provided DocumentReferences target a different project or database than the pipeline. */ documents(docs: Array): Pipeline { + docs + .filter(v => v instanceof DocumentReference) + .forEach(dr => this._validateReference(dr)); return new Pipeline(this.db, [ DocumentsSource.of(cast(docs)), ]); @@ -112,6 +116,21 @@ export class PipelineSource implements firestore.PipelineSource { throw 'Not implemented'; // return query.toPipeline(query._query, query.firestore); } + + _validateReference(reference: CollectionReference | DocumentReference): void { + const refDbId = reference.firestore.formattedName; + if (refDbId !== this.db.formattedName) { + throw new Error( + `Invalid ${ + reference instanceof CollectionReference + ? 'CollectionReference' + : 'DocumentReference' + }. ` + + `The database name ("${refDbId}") of this reference does not match ` + + `the database name ("${this.db.formattedName}") of the target database of this Pipeline.` + ); + } + } } /** @@ -200,7 +219,12 @@ export class Pipeline implements firestore.Pipeline { ...additionalFields: firestore.Selectable[] ): Pipeline { return this._addStage( - new AddFields(this.selectablesToMap([field, ...additionalFields])) + new AddFields( + this.validateUserData( + 'addFields', + this.selectablesToMap([field, ...additionalFields]) + ) + ) ); } @@ -226,13 +250,11 @@ export class Pipeline implements firestore.Pipeline { fieldValue: firestore.Field | string, ...additionalFields: Array ): Pipeline { - return this._addStage( - new RemoveFields( - [fieldValue, ...additionalFields].map(f => - typeof f === 'string' ? field(f) : (f as Field) - ) - ) + const fieldExpressions = [fieldValue, ...additionalFields].map(f => + typeof f === 'string' ? field(f) : (f as Field) ); + this.validateUserData('removeFields', fieldExpressions); + return this._addStage(new RemoveFields(fieldExpressions)); } /** @@ -272,9 +294,12 @@ export class Pipeline implements firestore.Pipeline { selection: firestore.Selectable | string, ...additionalSelections: Array ): Pipeline { - return this._addStage( - new Select(this.selectablesToMap([selection, ...additionalSelections])) - ); + let projections: Map = this.selectablesToMap([ + selection, + ...additionalSelections, + ]); + projections = this.validateUserData('select', projections); + return this._addStage(new Select(projections)); } private selectablesToMap( @@ -283,7 +308,10 @@ export class Pipeline implements firestore.Pipeline { const result = new Map(); for (const selectable of selectables) { if (typeof selectable === 'string') { - result.set(selectable as string, field(selectable)); + result.set( + selectable as string, + new Field(FieldPath.fromArgument(selectable)) + ); } else if (selectable instanceof Field) { result.set((selectable as Field).fieldName(), selectable); } else if (selectable instanceof ExprWithAlias) { @@ -296,6 +324,32 @@ export class Pipeline implements firestore.Pipeline { return result; } + /** + * Validates user data for each expression in the expressionMap. + * @param name Name of the calling function. Used for error messages when invalid user data is encountered. + * @param expressionMap + * @return the expressionMap argument. + * @private + */ + private validateUserData< + T extends Map | HasUserData[] | HasUserData, + >(name: string, expressionMap: T): T { + const ignoreUndefinedProperties = + !!this.db._settings.ignoreUndefinedProperties; + if (hasUserData(expressionMap)) { + expressionMap._validateUserData(ignoreUndefinedProperties); + } else if (Array.isArray(expressionMap)) { + expressionMap.forEach(readableData => + readableData._validateUserData(ignoreUndefinedProperties) + ); + } else { + expressionMap.forEach(expr => + expr._validateUserData(ignoreUndefinedProperties) + ); + } + return expressionMap; + } + /** * Filters the documents from previous stages to only include those matching the specified {@link * BooleanExpr}. @@ -328,7 +382,9 @@ export class Pipeline implements firestore.Pipeline { * @return A new Pipeline object with this stage appended to the stage list. */ where(condition: firestore.BooleanExpr): Pipeline { - return this._addStage(new Where(condition)); + const booleanExpr = condition as BooleanExpr; + this.validateUserData('where', booleanExpr); + return this._addStage(new Where(booleanExpr)); } /** @@ -417,7 +473,12 @@ export class Pipeline implements firestore.Pipeline { ...additionalGroups: Array ): Pipeline { return this._addStage( - new Distinct(this.selectablesToMap([group, ...additionalGroups])) + new Distinct( + this.validateUserData( + 'distinct', + this.selectablesToMap([group, ...additionalGroups]) + ) + ) ); } @@ -500,13 +561,22 @@ export class Pipeline implements firestore.Pipeline { new Aggregate( new Map( optionsOrTarget.accumulators.map( - (target: firestore.AggregateWithAlias) => [ - (target as unknown as AggregateWithAlias).alias, - (target as unknown as AggregateWithAlias).aggregate, - ] + (target: firestore.AggregateWithAlias) => { + this.validateUserData( + 'aggregate', + target as unknown as AggregateWithAlias + ); + return [ + (target as unknown as AggregateWithAlias).alias, + (target as unknown as AggregateWithAlias).aggregate, + ]; + } ) ), - this.selectablesToMap(optionsOrTarget.groups || []) + this.validateUserData( + 'aggregate', + this.selectablesToMap(optionsOrTarget.groups || []) + ) ) ); } else { @@ -515,7 +585,10 @@ export class Pipeline implements firestore.Pipeline { new Map( [optionsOrTarget, ...rest].map(target => [ (target as unknown as AggregateWithAlias).alias, - (target as unknown as AggregateWithAlias).aggregate, + this.validateUserData( + 'aggregate', + (target as unknown as AggregateWithAlias).aggregate + ), ]) ), new Map() @@ -599,9 +672,9 @@ export class Pipeline implements firestore.Pipeline { */ replaceWith(expr: firestore.Expr): Pipeline; replaceWith(value: firestore.Expr | string): Pipeline { - return this._addStage( - new Replace(fieldOrExpression(value), 'full_replace') - ); + const expr = fieldOrExpression(value); + this.validateUserData('replaceWith', expr); + return this._addStage(new ReplaceWith(expr, 'full_replace')); } /** @@ -719,7 +792,7 @@ export class Pipeline implements firestore.Pipeline { return this._addStage( new Unnest({ expr: cast(selectable.expr), - alias: field(selectable.alias), + alias: new Field(FieldPath.fromArgument(selectable.alias)), indexField: indexField, }) ); @@ -755,9 +828,9 @@ export class Pipeline implements firestore.Pipeline { ...additionalOrderings: firestore.Ordering[] ): Pipeline { // Ordering object - return this._addStage( - new Sort([ordering, ...additionalOrderings] as unknown as Ordering[]) - ); + const orderings = [ordering, ...additionalOrderings] as Ordering[]; + this.validateUserData('sort', orderings); + return this._addStage(new Sort(orderings)); } /** @@ -781,7 +854,28 @@ export class Pipeline implements firestore.Pipeline { * @return A new {@code Pipeline} object with this stage appended to the stage list. */ genericStage(name: string, params: any[]): Pipeline { - return this._addStage(new GenericStage(name, params)); + // Convert input values to Expressions. + // We treat objects as mapValues and arrays as arrayValues, + // this is unlike the default conversion for objects and arrays + // passed to an expression. + const expressionParams = params.map((value: unknown) => { + if (value instanceof Expr) { + return value; + } else if (value instanceof AggregateFunction) { + return value; + } else if (isPlainObject(value)) { + return _mapValue(value as Record); + } else { + return constant(value); + } + }); + + expressionParams.forEach(param => { + if (hasUserData(param)) { + param._validateUserData(!!this.db._settings.ignoreUndefinedProperties); + } + }); + return this._addStage(new GenericStage(name, expressionParams)); } /** diff --git a/dev/src/serializer.ts b/dev/src/serializer.ts index 58588512b..880df066b 100644 --- a/dev/src/serializer.ts +++ b/dev/src/serializer.ts @@ -21,7 +21,7 @@ import * as proto from '../protos/firestore_v1_proto_api'; import {DeleteTransform, FieldTransform, VectorValue} from './field-value'; import {detectGoogleProtobufValueType, detectValueType} from './convert'; import {GeoPoint} from './geo-point'; -import {DocumentReference, Firestore} from './index'; +import {DocumentReference, Field, Firestore} from './index'; import {FieldPath, QualifiedResourcePath} from './path'; import {Timestamp} from './timestamp'; import {ApiMapValue, ValidationOptions} from './types'; @@ -591,6 +591,8 @@ export function validateUserInput( // Ok. } else if (value === null) { // Ok. + } else if (isProtoValueSerializable(value)) { + // Ok. } else if (typeof value === 'object') { throw new Error(customObjectMessage(arg, value, path)); } @@ -610,3 +612,30 @@ function isMomentJsType(value: unknown): value is {toDate(): Date} { typeof (value as {toDate: unknown}).toDate === 'function' ); } + +export function isProtoValueSerializable( + value: unknown +): value is ProtoValueSerializable { + return ( + !!value && + typeof (value as ProtoValueSerializable)._toProto === 'function' && + (value as ProtoValueSerializable)._protoValueType === 'ProtoValue' + ); +} + +export interface ProtoSerializable { + _toProto(serializer: Serializer): ProtoType; +} + +export interface ProtoValueSerializable extends ProtoSerializable { + // Supports runtime identification of the ProtoSerializable type. + _protoValueType: 'ProtoValue'; +} + +export interface HasUserData { + _validateUserData(ignoreUndefinedProperties: boolean): void; +} + +export function hasUserData(value: unknown): value is HasUserData { + return typeof (value as HasUserData)._validateUserData === 'function'; +} diff --git a/dev/src/stage.ts b/dev/src/stage.ts index f1a05e57d..58cbe30ce 100644 --- a/dev/src/stage.ts +++ b/dev/src/stage.ts @@ -16,16 +16,23 @@ import * as firestore from '@google-cloud/firestore'; import * as protos from '../protos/firestore_v1_proto_api'; import api = protos.google.firestore.v1; -import {AggregateFunction, Expr, Field, Ordering, field} from './expression'; +import { + AggregateFunction, + Expr, + Field, + Ordering, + field, + BooleanExpr, +} from './expression'; import {VectorValue} from './field-value'; import {DocumentReference} from './reference/document-reference'; -import {Serializer} from './serializer'; +import {ProtoSerializable, Serializer} from './serializer'; import {Pipeline} from './pipeline'; /** * @beta */ -export interface Stage { +export interface Stage extends ProtoSerializable { name: string; _toProto(serializer: Serializer): api.Pipeline.IStage; } @@ -157,8 +164,16 @@ export class DocumentsSource implements Stage { constructor(private docPaths: string[]) {} - static of(refs: DocumentReference[]): DocumentsSource { - return new DocumentsSource(refs.map(ref => '/' + ref.path)); + static of(refs: Array): DocumentsSource { + return new DocumentsSource( + refs.map(ref => + ref instanceof DocumentReference + ? '/' + ref.path + : ref.startsWith('/') + ? ref + : '/' + ref + ) + ); } _toProto(serializer: Serializer): api.Pipeline.IStage { @@ -177,7 +192,7 @@ export class DocumentsSource implements Stage { export class Where implements Stage { name = 'where'; - constructor(private condition: firestore.BooleanExpr & firestore.Expr) {} + constructor(private condition: BooleanExpr) {} _toProto(serializer: Serializer): api.Pipeline.IStage { return { @@ -351,8 +366,8 @@ export class Offset implements Stage { /** * @beta */ -export class Replace implements Stage { - name = 'replace'; +export class ReplaceWith implements Stage { + name = 'replace_with'; constructor( private field: Expr, @@ -409,12 +424,23 @@ export class Sort implements Stage { * @beta */ export class GenericStage implements Stage { + /** + * @private + * @internal + */ constructor( public name: string, - params: any[] + private params: Array ) {} - _toProto(serializer: Serializer): api.Pipeline.Stage { - return new api.Pipeline.Stage(); + /** + * @internal + * @private + */ + _toProto(serializer: Serializer): api.Pipeline.IStage { + return { + name: this.name, + args: this.params.map(o => o._toProto(serializer)), + }; } } diff --git a/dev/system-test/pipeline.ts b/dev/system-test/pipeline.ts index 31868e6fb..1f4ef8289 100644 --- a/dev/system-test/pipeline.ts +++ b/dev/system-test/pipeline.ts @@ -12,7 +12,7 @@ // See the License for the specific language governing permissions and // limitations under the License. -import { DocumentData } from '@google-cloud/firestore'; +import {DocumentData} from '@google-cloud/firestore'; import { BooleanExpr, @@ -128,16 +128,18 @@ const timestampDeltaMS = 1000; describe.only('Pipeline class', () => { let firestore: Firestore; let randomCol: CollectionReference; - const beginDocCreation = 0; - const endDocCreation = 0; + let beginDocCreation = 0; + let endDocCreation = 0; async function testCollectionWithDocs(docs: { [id: string]: DocumentData; }): Promise> { + beginDocCreation = new Date().valueOf(); for (const id in docs) { const ref = randomCol.doc(id); await ref.set(docs[id]); } + endDocCreation = new Date().valueOf(); return randomCol; } @@ -166,17 +168,22 @@ describe.only('Pipeline class', () => { async function setupBookDocs(): Promise> { const bookDocs: {[id: string]: DocumentData} = { - book01: { + book1: { title: "The Hitchhiker's Guide to the Galaxy", author: 'Douglas Adams', genre: 'Science Fiction', published: 1979, rating: 4.2, tags: ['comedy', 'space', 'adventure'], - awards: {hugo: true, nebula: false, others: {unknown: {year: 1980}}}, + awards: { + hugo: true, + nebula: false, + others: {unknown: {year: 1980}}, + }, nestedField: {'level.1': {'level.2': true}}, + embedding: FieldValue.vector([10, 1, 1, 1, 1, 1, 1, 1, 1, 1]), }, - book02: { + book2: { title: 'Pride and Prejudice', author: 'Jane Austen', genre: 'Romance', @@ -184,8 +191,9 @@ describe.only('Pipeline class', () => { rating: 4.5, tags: ['classic', 'social commentary', 'love'], awards: {none: true}, + embedding: FieldValue.vector([1, 10, 1, 1, 1, 1, 1, 1, 1, 1]), }, - book03: { + book3: { title: 'One Hundred Years of Solitude', author: 'Gabriel García Márquez', genre: 'Magical Realism', @@ -193,8 +201,9 @@ describe.only('Pipeline class', () => { rating: 4.3, tags: ['family', 'history', 'fantasy'], awards: {nobel: true, nebula: false}, + embedding: FieldValue.vector([1, 1, 10, 1, 1, 1, 1, 1, 1, 1]), }, - book04: { + book4: { title: 'The Lord of the Rings', author: 'J.R.R. Tolkien', genre: 'Fantasy', @@ -202,8 +211,11 @@ describe.only('Pipeline class', () => { rating: 4.7, tags: ['adventure', 'magic', 'epic'], awards: {hugo: false, nebula: false}, + remarks: null, + cost: NaN, + embedding: FieldValue.vector([1, 1, 1, 10, 1, 1, 1, 1, 1, 1]), }, - book05: { + book5: { title: "The Handmaid's Tale", author: 'Margaret Atwood', genre: 'Dystopian', @@ -211,8 +223,9 @@ describe.only('Pipeline class', () => { rating: 4.1, tags: ['feminism', 'totalitarianism', 'resistance'], awards: {'arthur c. clarke': true, 'booker prize': false}, + embedding: FieldValue.vector([1, 1, 1, 1, 10, 1, 1, 1, 1, 1]), }, - book06: { + book6: { title: 'Crime and Punishment', author: 'Fyodor Dostoevsky', genre: 'Psychological Thriller', @@ -220,8 +233,9 @@ describe.only('Pipeline class', () => { rating: 4.3, tags: ['philosophy', 'crime', 'redemption'], awards: {none: true}, + embedding: FieldValue.vector([1, 1, 1, 1, 1, 10, 1, 1, 1, 1]), }, - book07: { + book7: { title: 'To Kill a Mockingbird', author: 'Harper Lee', genre: 'Southern Gothic', @@ -229,8 +243,9 @@ describe.only('Pipeline class', () => { rating: 4.2, tags: ['racism', 'injustice', 'coming-of-age'], awards: {pulitzer: true}, + embedding: FieldValue.vector([1, 1, 1, 1, 1, 1, 10, 1, 1, 1]), }, - book08: { + book8: { title: '1984', author: 'George Orwell', genre: 'Dystopian', @@ -238,8 +253,9 @@ describe.only('Pipeline class', () => { rating: 4.2, tags: ['surveillance', 'totalitarianism', 'propaganda'], awards: {prometheus: true}, + embedding: FieldValue.vector([1, 1, 1, 1, 1, 1, 1, 10, 1, 1]), }, - book09: { + book9: { title: 'The Great Gatsby', author: 'F. Scott Fitzgerald', genre: 'Modernist', @@ -247,6 +263,7 @@ describe.only('Pipeline class', () => { rating: 4.0, tags: ['wealth', 'american dream', 'love'], awards: {none: true}, + embedding: FieldValue.vector([1, 1, 1, 1, 1, 1, 1, 1, 10, 1]), }, book10: { title: 'Dune', @@ -256,6 +273,7 @@ describe.only('Pipeline class', () => { rating: 4.6, tags: ['politics', 'desert', 'ecology'], awards: {hugo: true, nebula: true}, + embedding: FieldValue.vector([1, 1, 1, 1, 1, 1, 1, 1, 1, 10]), }, }; return testCollectionWithDocs(bookDocs); @@ -442,7 +460,7 @@ describe.only('Pipeline class', () => { }); it('reject CollectionReference for another DB', async () => { - const db2 = getTestDb({databaseId: 'notDefault'}); + const db2 = getTestDb({databaseId: 'notDefault', projectId: 'random'}); expect(() => { firestore.pipeline().collection(db2.collection('foo')); @@ -452,7 +470,7 @@ describe.only('Pipeline class', () => { }); it('reject DocumentReference for another DB', async () => { - const db2 = getTestDb({databaseId: 'notDefault'}); + const db2 = getTestDb({databaseId: 'notDefault', projectId: 'random'}); expect(() => { firestore.pipeline().documents([db2.doc('foo/bar')]); @@ -611,32 +629,81 @@ describe.only('Pipeline class', () => { }); it('throws on undefined in a map', async () => { - expect(() => { - firestore + try { + await firestore .pipeline() .collection(randomCol.path) .limit(1) .select( map({ number: 1, - undefined, + bad: undefined, }).as('foo') - ); - }).to.throw( - 'Function map() called with invalid data. Unsupported field value: undefined' - ); + ) + .execute(); + expect.fail('The statement above was expected to throw.'); + } catch (e: any) { + console.log(e.message); + expect(e.message).to.contain( + 'Value for argument "value" is not a valid map value. Cannot use "undefined" as a Firestore value (found in field "bad").' + ); + } }); it('throws on undefined in an array', async () => { - expect(() => { - firestore + try { + await firestore .pipeline() .collection(randomCol.path) .limit(1) - .select(array([1, undefined]).as('foo')); - }).to.throw( - 'Function array() called with invalid data. Unsupported field value: undefined' - ); + .select(array([1, undefined]).as('foo')) + .execute(); + expect.fail('The statement above was expected to throw.'); + } catch (e: any) { + console.log(e.message); + expect(e.message).to.contain( + 'Value for argument "value" is not a valid array value. Cannot use "undefined" as a Firestore value' + ); + } + }); + + it('ignores undefined in a map if ignoreUndefinedProperties is true', async () => { + const customFirestore = getTestDb({ + ignoreUndefinedProperties: true, + }); + + const snapshot = await customFirestore + .pipeline() + .collection(randomCol.path) + .limit(1) + .select( + map({ + number: 1, + bad: undefined, + }).as('foo') + ) + .execute(); + + const data = snapshot.results[0].data(); + expect(data).to.deep.equal({foo: {number: 1}}); + await customFirestore.terminate(); + }); + + it('ignores undefined in an array if ignoreUndefinedProperties is true', async () => { + const customFirestore = getTestDb({ + ignoreUndefinedProperties: true, + }); + + const snapshot = await customFirestore + .pipeline() + .collection(randomCol.path) + .limit(1) + .select(array([1, undefined, 3]).as('foo')) + .execute(); + + const data = snapshot.results[0].data(); + expect(data).to.deep.equal({foo: [1, 3]}); + await customFirestore.terminate(); }); it('converts arrays and plain objects to functionValues if the customer intent is unspecified', async () => { @@ -761,7 +828,7 @@ describe.only('Pipeline class', () => { it('rejects groups without accumulators', async () => { expect( - await firestore + firestore .pipeline() .collection(randomCol.path) .where(lt('published', 1900)) @@ -1256,7 +1323,7 @@ describe.only('Pipeline class', () => { it('run pipeline with sample limit of {percentage: 0.6}', async () => { let avgSize = 0; - const numIterations = 20; + const numIterations = 30; for (let i = 0; i < numIterations; i++) { const snapshot = await firestore .pipeline() From 628f432c8259bff7de0a4db6a03c5ceb3a91ba32 Mon Sep 17 00:00:00 2001 From: Mark Duckworth <1124037+MarkDuckworth@users.noreply.github.com> Date: Tue, 22 Apr 2025 15:55:57 -0600 Subject: [PATCH 37/60] Ignore unused params named '_', do not generate eslint warning. --- .eslintrc.json | 8 +++++++- 1 file changed, 7 insertions(+), 1 deletion(-) diff --git a/.eslintrc.json b/.eslintrc.json index 84bff2ae8..21dba5c59 100644 --- a/.eslintrc.json +++ b/.eslintrc.json @@ -14,7 +14,13 @@ "allowTypedFunctionExpressions": true } ], - "no-console": ["error", {"allow": ["error"]}] + "no-console": ["error", {"allow": ["error"]}], + "@typescript-eslint/no-unused-vars": [ + "warn", + { + "argsIgnorePattern": "^_$" // Ignore args that are underscore only + } + ] } }, { From 28163d4d9c0ec49cfb3c51ac81fa2254303d16f8 Mon Sep 17 00:00:00 2001 From: Mark Duckworth <1124037+MarkDuckworth@users.noreply.github.com> Date: Tue, 22 Apr 2025 15:59:03 -0600 Subject: [PATCH 38/60] Implement query to pipeline tests and fixes. Also corrected many lint warnings --- dev/src/expression.ts | 33 +- dev/src/pipeline-util.ts | 97 +++- dev/src/pipeline.ts | 13 +- dev/src/reference/aggregate-query.ts | 4 +- dev/src/reference/query.ts | 118 +++-- dev/src/reference/vector-query.ts | 2 +- dev/src/serializer.ts | 2 +- dev/src/stage.ts | 6 +- dev/src/util.ts | 2 +- dev/system-test/pipeline.ts | 751 ++++++++++++++++++++++++++- dev/system-test/query.ts | 2 +- 11 files changed, 940 insertions(+), 90 deletions(-) diff --git a/dev/src/expression.ts b/dev/src/expression.ts index 4d094c1c8..7b5e6dcaa 100644 --- a/dev/src/expression.ts +++ b/dev/src/expression.ts @@ -19,7 +19,6 @@ import type * as firestore from '@google-cloud/firestore'; import {VectorValue} from './field-value'; import {FieldPath} from './path'; -import {Pipeline} from './pipeline'; import { fieldOrExpression, isFirestoreValue, @@ -2133,7 +2132,7 @@ export class Field extends Expr implements firestore.Selectable { * @private * @internal */ - _toProto(serializer: Serializer): api.IValue { + _toProto(_: Serializer): api.IValue { return { fieldReferenceValue: this.fieldPath.formattedName, }; @@ -2143,7 +2142,7 @@ export class Field extends Expr implements firestore.Selectable { * @private * @internal */ - _validateUserData(ignoreUndefinedProperties: boolean): void {} + _validateUserData(_: boolean): void {} } /** @@ -4591,8 +4590,11 @@ export function arrayContainsAny( array: firestore.Expr | string, values: unknown[] | firestore.Expr ): BooleanExpr { - // @ts-ignore implementation accepts both types - return fieldOrExpression(array).arrayContainsAny(values); + if (Array.isArray(values)) { + return fieldOrExpression(array).arrayContainsAny(values); + } else { + return fieldOrExpression(array).arrayContainsAny(values); + } } /** @@ -4676,8 +4678,11 @@ export function arrayContainsAll( array: firestore.Expr | string, values: unknown[] | firestore.Expr ): BooleanExpr { - // @ts-ignore implementation accepts both types - return fieldOrExpression(array).arrayContainsAll(values); + if (Array.isArray(values)) { + return fieldOrExpression(array).arrayContainsAll(values); + } else { + return fieldOrExpression(array).arrayContainsAll(values); + } } /** @@ -4795,8 +4800,11 @@ export function eqAny( element: firestore.Expr | string, values: unknown[] | firestore.Expr ): BooleanExpr { - // @ts-ignore implementation accepts both types - return fieldOrExpression(element).eqAny(values); + if (Array.isArray(values)) { + return fieldOrExpression(element).eqAny(values); + } else { + return fieldOrExpression(element).eqAny(values); + } } /** @@ -4882,8 +4890,11 @@ export function notEqAny( element: firestore.Expr | string, values: unknown[] | firestore.Expr ): BooleanExpr { - // @ts-ignore implementation accepts both types - return fieldOrExpression(element).notEqAny(values); + if (Array.isArray(values)) { + return fieldOrExpression(element).notEqAny(values); + } else { + return fieldOrExpression(element).notEqAny(values); + } } /** diff --git a/dev/src/pipeline-util.ts b/dev/src/pipeline-util.ts index 08ee9805a..136588289 100644 --- a/dev/src/pipeline-util.ts +++ b/dev/src/pipeline-util.ts @@ -23,9 +23,6 @@ import { BooleanExpr, and, or, - Field, - not, - ExprWithAlias, field as createField, constant, map, @@ -33,6 +30,9 @@ import { Constant, constantVector, field, + Ordering, + gt, + lt, } from './expression'; import Firestore, {DocumentReference, Timestamp, VectorValue} from './index'; import {logger} from './logger'; @@ -42,7 +42,11 @@ import {CompositeFilterInternal} from './reference/composite-filter-internal'; import {NOOP_MESSAGE} from './reference/constants'; import {FieldFilterInternal} from './reference/field-filter-internal'; import {FilterInternal} from './reference/filter-internal'; -import {PipelineResponse, PipelineStreamElement} from './reference/types'; +import { + PipelineResponse, + PipelineStreamElement, + QueryCursor, +} from './reference/types'; import {Serializer} from './serializer'; import { Deferred, @@ -144,7 +148,7 @@ export class ExecutionUtil { _stream( pipeline: Pipeline, transactionOrReadTime?: Uint8Array | Timestamp | api.ITransactionOptions, - explainOptions?: firestore.ExplainOptions + _?: firestore.ExplainOptions ): NodeJS.ReadableStream { const tag = requestTag(); @@ -271,7 +275,7 @@ export class ExecutionUtil { } } -function isITimestamp(obj: any): obj is google.protobuf.ITimestamp { +function isITimestamp(obj: unknown): obj is google.protobuf.ITimestamp { if (typeof obj !== 'object' || obj === null) { return false; // Must be a non-null object } @@ -288,7 +292,7 @@ function isITimestamp(obj: any): obj is google.protobuf.ITimestamp { return false; } -function isILatLng(obj: any): obj is google.type.ILatLng { +function isILatLng(obj: unknown): obj is google.type.ILatLng { if (typeof obj !== 'object' || obj === null) { return false; // Must be a non-null object } @@ -303,7 +307,7 @@ function isILatLng(obj: any): obj is google.type.ILatLng { return false; } -function isIArrayValue(obj: any): obj is api.IArrayValue { +function isIArrayValue(obj: unknown): obj is api.IArrayValue { if (typeof obj !== 'object' || obj === null) { return false; // Must be a non-null object } @@ -313,7 +317,7 @@ function isIArrayValue(obj: any): obj is api.IArrayValue { return false; } -function isIMapValue(obj: any): obj is api.IMapValue { +function isIMapValue(obj: unknown): obj is api.IMapValue { if (typeof obj !== 'object' || obj === null) { return false; // Must be a non-null object } @@ -323,7 +327,7 @@ function isIMapValue(obj: any): obj is api.IMapValue { return false; } -function isIFunction(obj: any): obj is api.IFunction { +function isIFunction(obj: unknown): obj is api.IFunction { if (typeof obj !== 'object' || obj === null) { return false; // Must be a non-null object } @@ -339,7 +343,7 @@ function isIFunction(obj: any): obj is api.IFunction { return false; } -function isIPipeline(obj: any): obj is api.IPipeline { +function isIPipeline(obj: unknown): obj is api.IPipeline { if (typeof obj !== 'object' || obj === null) { return false; // Must be a non-null object } @@ -350,7 +354,7 @@ function isIPipeline(obj: any): obj is api.IPipeline { return false; } -export function isFirestoreValue(obj: any): obj is api.IValue { +export function isFirestoreValue(obj: unknown): obj is api.IValue { if (typeof obj !== 'object' || obj === null) { return false; // Must be a non-null object } @@ -396,18 +400,56 @@ export function isFirestoreValue(obj: any): obj is api.IValue { return false; } -export function selectableToExpr( - selectable: firestore.Selectable | string -): Expr { - if (typeof selectable === 'string') { - return createField(selectable); - } else if (selectable instanceof Field) { - return selectable; - } else if (selectable instanceof ExprWithAlias) { - return selectable.expr; - } else { - throw new Error('unexpected selectable: ' + selectable); +export function whereConditionsFromCursor( + cursor: QueryCursor, + orderings: Ordering[], + position: 'before' | 'after' +): BooleanExpr { + // The filterFunc is either greater than or less than + const filterFunc = position === 'before' ? lt : gt; + const cursors = cursor.values.map(value => Constant._fromProto(value)); + const size = cursors.length; + + let field = orderings[size - 1].expr; + let value = cursors[size - 1]; + + // Add condition for last bound + let condition: BooleanExpr = filterFunc(field, value); + if ( + (position === 'after' && cursor.before) || + (position === 'before' && !cursor.before) + ) { + // When the cursor bound is inclusive, then the last bound + // can be equal to the value, otherwise it's not equal + condition = or(condition, field.eq(value) as unknown as BooleanExpr); + } + + // Iterate backwards over the remaining bounds, adding + // a condition for each one + for (let i = size - 2; i >= 0; i--) { + field = orderings[i].expr; + value = cursors[i]; + + // For each field in the orderings, the condition is either + // a) lt|gt the cursor value, + // b) or equal the cursor value and lt|gt the cursor values for other fields + condition = or( + filterFunc(field, value), + and(field.eq(value) as unknown as BooleanExpr, condition) + ); } + + return condition; +} + +export function reverseOrderings(orderings: Ordering[]): Ordering[] { + return orderings.map( + o => + new Ordering( + o.expr, + o.direction === 'ascending' ? 'descending' : 'ascending' + ) + ); } export function toPipelineBooleanExpr( @@ -420,13 +462,13 @@ export function toPipelineBooleanExpr( if (f.nanOp() === 'IS_NAN') { return and(field.exists(), field.isNan()); } else { - return and(field.exists(), not(field.isNan())); + return and(field.exists(), field.isNotNan()); } } else if (f.isNullChecking()) { if (f.nullOp() === 'IS_NULL') { - return and(field.exists(), field.eq(null)); + return and(field.exists(), field.isNull()); } else { - return and(field.exists(), not(field.eq(null))); + return and(field.exists(), field.isNotNull()); } } else { // Comparison filters @@ -498,6 +540,9 @@ export function isString(val: unknown): val is string { */ export function valueToDefaultExpr(value: unknown): Expr { let result: Expr | undefined; + if (isFirestoreValue(value)) { + return constant(value); + } if (value instanceof Expr) { return value; } else if (isPlainObject(value)) { diff --git a/dev/src/pipeline.ts b/dev/src/pipeline.ts index 8c030395d..58c5aad6f 100644 --- a/dev/src/pipeline.ts +++ b/dev/src/pipeline.ts @@ -27,7 +27,12 @@ import { _mapValue, field, } from './expression'; -import Firestore, {CollectionReference, FieldPath, Timestamp} from './index'; +import Firestore, { + CollectionReference, + FieldPath, + Query, + Timestamp, +} from './index'; import {validateFieldPath} from './path'; import {ExecutionUtil, fieldOrExpression} from './pipeline-util'; import {DocumentReference} from './reference/document-reference'; @@ -60,7 +65,6 @@ import * as protos from '../protos/firestore_v1_proto_api'; import api = protos.google.firestore.v1; import IStage = google.firestore.v1.Pipeline.IStage; import {cast, isOptionalEqual, isPlainObject} from './util'; -import {validateDocumentReference} from './reference/helpers'; /** * Represents the source of a Firestore {@link Pipeline}. @@ -113,8 +117,7 @@ export class PipelineSource implements firestore.PipelineSource { * @throws {@FirestoreError} Thrown if any of the provided DocumentReferences target a different project or database than the pipeline. */ createFrom(query: firestore.Query): Pipeline { - throw 'Not implemented'; - // return query.toPipeline(query._query, query.firestore); + return (query as unknown as Query)._pipeline(); } _validateReference(reference: CollectionReference | DocumentReference): void { @@ -853,7 +856,7 @@ export class Pipeline implements firestore.Pipeline { * @param params A list of parameters to configure the generic stage's behavior. * @return A new {@code Pipeline} object with this stage appended to the stage list. */ - genericStage(name: string, params: any[]): Pipeline { + genericStage(name: string, params: unknown[]): Pipeline { // Convert input values to Expressions. // We treat objects as mapValues and arrays as arrayValues, // this is unlike the default conversion for objects and arrays diff --git a/dev/src/reference/aggregate-query.ts b/dev/src/reference/aggregate-query.ts index 33478ac1d..d804c38ae 100644 --- a/dev/src/reference/aggregate-query.ts +++ b/dev/src/reference/aggregate-query.ts @@ -349,7 +349,7 @@ export class AggregateQuery< return runQueryRequest; } - pipeline(): Pipeline { + _pipeline(): Pipeline { const aggregates = mapToArray( this._aggregates, (aggregate, clientAlias) => { @@ -375,7 +375,7 @@ export class AggregateQuery< } return this._query - .pipeline() + ._pipeline() .aggregate(aggregates[0], ...aggregates.slice(1)); } diff --git a/dev/src/reference/query.ts b/dev/src/reference/query.ts index 4bde4267e..99c6609c0 100644 --- a/dev/src/reference/query.ts +++ b/dev/src/reference/query.ts @@ -35,7 +35,11 @@ import { import {compare} from '../order'; import {validateFieldPath} from '../path'; import {Pipeline} from '../pipeline'; -import {toPipelineBooleanExpr} from '../pipeline-util'; +import { + reverseOrderings, + toPipelineBooleanExpr, + whereConditionsFromCursor, +} from '../pipeline-util'; import {ExplainResults} from '../query-profile'; import {Serializer} from '../serializer'; import {defaultConverter} from '../types'; @@ -724,14 +728,22 @@ export class Query< return new VectorQuery(this, options); } - pipeline(): Pipeline { - let pipeline; - if (this._queryOptions.allDescendants) { - pipeline = this.firestore + /** + * Returns a value indicating if this query is a collection group query + */ + _isCollectionGroupQuery(): boolean { + return this._queryOptions.allDescendants; + } + + _pipeline(): Pipeline { + let pipeline: Pipeline; + const db = this.firestore; + if (this._isCollectionGroupQuery()) { + pipeline = db .pipeline() - .collectionGroup(this._queryOptions.collectionId); + .collectionGroup(this._queryOptions.collectionId!); } else { - pipeline = this.firestore + pipeline = db .pipeline() .collection( this._queryOptions.parentPath.append(this._queryOptions.collectionId) @@ -740,8 +752,10 @@ export class Query< } // filters - for (const f of this._queryOptions.filters) { - pipeline = pipeline.where(toPipelineBooleanExpr(f, this._serializer)); + for (const filter of this._queryOptions.filters) { + pipeline = pipeline.where( + toPipelineBooleanExpr(filter, this._serializer) + ); } // projections @@ -754,15 +768,15 @@ export class Query< ); } - // orderbys - const exists = this.createImplicitOrderBy().map(fieldOrder => { + // orders + const existsConditions = this.createImplicitOrderBy().map(fieldOrder => { return field(fieldOrder.field).exists(); }); - if (exists.length > 1) { - const [first, second, ...rest] = exists; + if (existsConditions.length > 1) { + const [first, second, ...rest] = existsConditions; pipeline = pipeline.where(and(first, second, ...rest)); - } else if (exists.length === 1) { - pipeline = pipeline.where(exists[0]); + } else { + pipeline = pipeline.where(existsConditions[0]); } const orderings = this.createImplicitOrderBy().map(fieldOrder => { @@ -779,27 +793,67 @@ export class Query< } return new Ordering(field(fieldOrder.field), dir || 'ascending'); }); + if (orderings.length > 0) { - pipeline = pipeline.sort(orderings[0], ...orderings.slice(1)); - } + if (this._queryOptions.limitType === LimitType.Last) { + const actualOrderings = reverseOrderings(orderings); + pipeline = pipeline.sort( + actualOrderings[0], + ...actualOrderings.slice(1) + ); + // cursors + if (this._queryOptions.startAt !== undefined) { + pipeline = pipeline.where( + whereConditionsFromCursor( + this._queryOptions.startAt, + orderings, + 'after' + ) + ); + } - // Cursors, Limit and Offset - if ( - !!this._queryOptions.startAt || - !!this._queryOptions.endAt || - this._queryOptions.limitType === LimitType.Last - ) { - throw new Error( - 'Query to Pipeline conversion: cursors and limitToLast is not supported yet.' - ); - } else { - if (this._queryOptions.offset) { - pipeline = pipeline.offset(this._queryOptions.offset); - } - if (this._queryOptions.limit) { - pipeline = pipeline.limit(this._queryOptions.limit); + if (this._queryOptions.endAt !== undefined) { + pipeline = pipeline.where( + whereConditionsFromCursor( + this._queryOptions.endAt, + orderings, + 'before' + ) + ); + } + + if (this._queryOptions.limit !== undefined) { + pipeline = pipeline.limit(this._queryOptions.limit!); + } + + pipeline = pipeline.sort(orderings[0], ...orderings.slice(1)); + } else { + pipeline = pipeline.sort(orderings[0], ...orderings.slice(1)); + if (this._queryOptions.startAt !== undefined) { + pipeline = pipeline.where( + whereConditionsFromCursor( + this._queryOptions.startAt, + orderings, + 'after' + ) + ); + } + if (this._queryOptions.endAt !== undefined) { + pipeline = pipeline.where( + whereConditionsFromCursor( + this._queryOptions.endAt, + orderings, + 'before' + ) + ); + } + + if (this._queryOptions.limit !== undefined) { + pipeline = pipeline.limit(this._queryOptions.limit); + } } } + return pipeline; } diff --git a/dev/src/reference/vector-query.ts b/dev/src/reference/vector-query.ts index 987a5a1b5..3536547fc 100644 --- a/dev/src/reference/vector-query.ts +++ b/dev/src/reference/vector-query.ts @@ -152,7 +152,7 @@ export class VectorQuery< | 'dot_product', }; return this.query - .pipeline() + ._pipeline() .where(field(this._options.vectorField).exists()) .findNearest(options); } diff --git a/dev/src/serializer.ts b/dev/src/serializer.ts index 880df066b..048030d0c 100644 --- a/dev/src/serializer.ts +++ b/dev/src/serializer.ts @@ -21,7 +21,7 @@ import * as proto from '../protos/firestore_v1_proto_api'; import {DeleteTransform, FieldTransform, VectorValue} from './field-value'; import {detectGoogleProtobufValueType, detectValueType} from './convert'; import {GeoPoint} from './geo-point'; -import {DocumentReference, Field, Firestore} from './index'; +import {DocumentReference, Firestore} from './index'; import {FieldPath, QualifiedResourcePath} from './path'; import {Timestamp} from './timestamp'; import {ApiMapValue, ValidationOptions} from './types'; diff --git a/dev/src/stage.ts b/dev/src/stage.ts index 58cbe30ce..1b8c41432 100644 --- a/dev/src/stage.ts +++ b/dev/src/stage.ts @@ -119,7 +119,7 @@ export class CollectionSource implements Stage { } } - _toProto(serializer: Serializer): api.Pipeline.IStage { + _toProto(_: Serializer): api.Pipeline.IStage { return { name: this.name, args: [{referenceValue: this.collectionPath}], @@ -149,7 +149,7 @@ export class CollectionGroupSource implements Stage { export class DatabaseSource implements Stage { name = 'database'; - _toProto(serializer: Serializer): api.Pipeline.IStage { + _toProto(_: Serializer): api.Pipeline.IStage { return { name: this.name, }; @@ -176,7 +176,7 @@ export class DocumentsSource implements Stage { ); } - _toProto(serializer: Serializer): api.Pipeline.IStage { + _toProto(_: Serializer): api.Pipeline.IStage { return { name: this.name, args: this.docPaths.map(p => { diff --git a/dev/src/util.ts b/dev/src/util.ts index 63430e64a..a02589b28 100644 --- a/dev/src/util.ts +++ b/dev/src/util.ts @@ -368,7 +368,7 @@ export function isPrimitiveArrayEqual( export function cast( val: unknown, - constructor?: {new (...args: any[]): T} + constructor?: {new (...args: unknown[]): T} ): T { if (!constructor) { return val as T; diff --git a/dev/system-test/pipeline.ts b/dev/system-test/pipeline.ts index 1f4ef8289..4887fb259 100644 --- a/dev/system-test/pipeline.ts +++ b/dev/system-test/pipeline.ts @@ -15,6 +15,8 @@ import {DocumentData} from '@google-cloud/firestore'; import { + Filter, + Pipeline, BooleanExpr, constant, constantVector, @@ -115,13 +117,17 @@ import { Firestore, } from '../src'; -import {expect} from 'chai'; +import {expect, use} from 'chai'; +import * as chaiAsPromised from 'chai-as-promised'; + import {afterEach, describe, it} from 'mocha'; import {itIf, verifyInstance} from '../test/util/helpers'; import {getTestDb, getTestRoot} from './firestore'; import {Firestore as InternalFirestore} from '../src'; +use(chaiAsPromised); + const testUnsupportedFeatures: boolean | 'only' = false; const timestampDeltaMS = 1000; @@ -642,9 +648,10 @@ describe.only('Pipeline class', () => { ) .execute(); expect.fail('The statement above was expected to throw.'); - } catch (e: any) { - console.log(e.message); - expect(e.message).to.contain( + } catch (e: unknown) { + const error = e as Error; + console.log(error.message); + expect(error.message).to.contain( 'Value for argument "value" is not a valid map value. Cannot use "undefined" as a Firestore value (found in field "bad").' ); } @@ -659,9 +666,10 @@ describe.only('Pipeline class', () => { .select(array([1, undefined]).as('foo')) .execute(); expect.fail('The statement above was expected to throw.'); - } catch (e: any) { - console.log(e.message); - expect(e.message).to.contain( + } catch (e: unknown) { + const error = e as Error; + console.log(error.message); + expect(error.message).to.contain( 'Value for argument "value" is not a valid array value. Cannot use "undefined" as a Firestore value' ); } @@ -2902,3 +2910,732 @@ describe.only('Pipeline class', () => { ); }); }); + +/** + * @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. + */ + +// This is the Query integration tests from the lite API (no cache support) +// with some additional test cases added for more complete coverage. +describe.only('Query to Pipeline', () => { + async function execute(ppl: Pipeline): Promise { + return ppl.execute(); + } + + async function testCollectionWithDocs( + docs: { + [id: string]: DocumentData; + }, + callback: (collRef: CollectionReference, db: Firestore) => Promise + ): Promise { + const randomCol = getTestRoot(); + const firestore = randomCol.firestore; + for (const id in docs) { + const ref = randomCol.doc(id); + await ref.set(docs[id]); + } + + try { + await callback(randomCol, firestore); + } finally { + await firestore.terminate(); + } + } + + function verifyResults( + actual: PipelineSnapshot, + ...expected: DocumentData[] + ): void { + const results = actual.results; + expect(results.length).to.equal(expected.length); + + for (let i = 0; i < expected.length; ++i) { + expect(results[i].data()).to.deep.equal(expected[i]); + } + } + + it('supports default query', () => { + return testCollectionWithDocs({1: {foo: 1}}, async (collRef, db) => { + const snapshot = await execute(db.pipeline().createFrom(collRef)); + verifyResults(snapshot, {foo: 1}); + }); + }); + + it('supports filtered query', () => { + return testCollectionWithDocs( + { + 1: {foo: 1}, + 2: {foo: 2}, + }, + async (collRef, db) => { + const query1 = collRef.where('foo', '==', 1); + const snapshot = await execute(db.pipeline().createFrom(query1)); + verifyResults(snapshot, {foo: 1}); + } + ); + }); + + it('supports filtered query (with FieldPath)', () => { + return testCollectionWithDocs( + { + 1: {foo: 1}, + 2: {foo: 2}, + }, + async (collRef, db) => { + const query1 = collRef.where(new FieldPath('foo'), '==', 1); + const snapshot = await execute(db.pipeline().createFrom(query1)); + verifyResults(snapshot, {foo: 1}); + } + ); + }); + + it('supports ordered query (with default order)', () => { + return testCollectionWithDocs( + { + 1: {foo: 1}, + 2: {foo: 2}, + }, + async (collRef, db) => { + const query1 = collRef.orderBy('foo'); + const snapshot = await execute(db.pipeline().createFrom(query1)); + verifyResults(snapshot, {foo: 1}, {foo: 2}); + } + ); + }); + + it('supports ordered query (with asc)', () => { + return testCollectionWithDocs( + { + 1: {foo: 1}, + 2: {foo: 2}, + }, + async (collRef, db) => { + const query1 = collRef.orderBy('foo', 'asc'); + const snapshot = await execute(db.pipeline().createFrom(query1)); + verifyResults(snapshot, {foo: 1}, {foo: 2}); + } + ); + }); + + it('supports ordered query (with desc)', () => { + return testCollectionWithDocs( + { + 1: {foo: 1}, + 2: {foo: 2}, + }, + async (collRef, db) => { + const query1 = collRef.orderBy('foo', 'desc'); + const snapshot = await execute(db.pipeline().createFrom(query1)); + verifyResults(snapshot, {foo: 2}, {foo: 1}); + } + ); + }); + + it('supports limit query', () => { + return testCollectionWithDocs( + { + 1: {foo: 1}, + 2: {foo: 2}, + }, + async (collRef, db) => { + const query1 = collRef.orderBy('foo').limit(1); + const snapshot = await execute(db.pipeline().createFrom(query1)); + verifyResults(snapshot, {foo: 1}); + } + ); + }); + + it('supports limitToLast query', () => { + return testCollectionWithDocs( + { + 1: {foo: 1}, + 2: {foo: 2}, + 3: {foo: 3}, + }, + async (collRef, db) => { + const query1 = collRef.orderBy('foo').limitToLast(2); + const snapshot = await execute(db.pipeline().createFrom(query1)); + verifyResults(snapshot, {foo: 2}, {foo: 3}); + } + ); + }); + + it('supports startAt', () => { + return testCollectionWithDocs( + { + 1: {foo: 1}, + 2: {foo: 2}, + }, + async (collRef, db) => { + const query1 = collRef.orderBy('foo').startAt(2); + const snapshot = await execute(db.pipeline().createFrom(query1)); + verifyResults(snapshot, {foo: 2}); + } + ); + }); + + it('supports startAt with limitToLast', () => { + return testCollectionWithDocs( + { + 1: {foo: 1}, + 2: {foo: 2}, + 3: {foo: 3}, + 4: {foo: 4}, + 5: {foo: 5}, + }, + async (collRef, db) => { + const query1 = collRef.orderBy('foo').startAt(3).limitToLast(4); + const snapshot = await execute(db.pipeline().createFrom(query1)); + verifyResults(snapshot, {foo: 3}, {foo: 4}, {foo: 5}); + } + ); + }); + + it('supports endAt with limitToLast', () => { + return testCollectionWithDocs( + { + 1: {foo: 1}, + 2: {foo: 2}, + 3: {foo: 3}, + 4: {foo: 4}, + 5: {foo: 5}, + }, + async (collRef, db) => { + const query1 = collRef.orderBy('foo').endAt(3).limitToLast(2); + const snapshot = await execute(db.pipeline().createFrom(query1)); + verifyResults(snapshot, {foo: 2}, {foo: 3}); + } + ); + }); + + it('supports startAfter (with DocumentSnapshot)', () => { + return testCollectionWithDocs( + { + 1: {id: 1, foo: 1, bar: 1, baz: 1}, + 2: {id: 2, foo: 1, bar: 1, baz: 2}, + 3: {id: 3, foo: 1, bar: 1, baz: 2}, + 4: {id: 4, foo: 1, bar: 2, baz: 1}, + 5: {id: 5, foo: 1, bar: 2, baz: 2}, + 6: {id: 6, foo: 1, bar: 2, baz: 2}, + 7: {id: 7, foo: 2, bar: 1, baz: 1}, + 8: {id: 8, foo: 2, bar: 1, baz: 2}, + 9: {id: 9, foo: 2, bar: 1, baz: 2}, + 10: {id: 10, foo: 2, bar: 2, baz: 1}, + 11: {id: 11, foo: 2, bar: 2, baz: 2}, + 12: {id: 12, foo: 2, bar: 2, baz: 2}, + }, + async (collRef, db) => { + let docRef = await collRef.doc('2').get(); + let query1 = collRef + .orderBy('foo') + .orderBy('bar') + .orderBy('baz') + .startAfter(docRef); + let snapshot = await execute(db.pipeline().createFrom(query1)); + verifyResults( + snapshot, + {id: 3, foo: 1, bar: 1, baz: 2}, + {id: 4, foo: 1, bar: 2, baz: 1}, + {id: 5, foo: 1, bar: 2, baz: 2}, + {id: 6, foo: 1, bar: 2, baz: 2}, + {id: 7, foo: 2, bar: 1, baz: 1}, + {id: 8, foo: 2, bar: 1, baz: 2}, + {id: 9, foo: 2, bar: 1, baz: 2}, + {id: 10, foo: 2, bar: 2, baz: 1}, + {id: 11, foo: 2, bar: 2, baz: 2}, + {id: 12, foo: 2, bar: 2, baz: 2} + ); + + docRef = await collRef.doc('3').get(); + query1 = collRef + .orderBy('foo') + .orderBy('bar') + .orderBy('baz') + .startAfter(docRef); + snapshot = await execute(db.pipeline().createFrom(query1)); + verifyResults( + snapshot, + {id: 4, foo: 1, bar: 2, baz: 1}, + {id: 5, foo: 1, bar: 2, baz: 2}, + {id: 6, foo: 1, bar: 2, baz: 2}, + {id: 7, foo: 2, bar: 1, baz: 1}, + {id: 8, foo: 2, bar: 1, baz: 2}, + {id: 9, foo: 2, bar: 1, baz: 2}, + {id: 10, foo: 2, bar: 2, baz: 1}, + {id: 11, foo: 2, bar: 2, baz: 2}, + {id: 12, foo: 2, bar: 2, baz: 2} + ); + } + ); + }); + + it('supports startAt (with DocumentSnapshot)', () => { + return testCollectionWithDocs( + { + 1: {id: 1, foo: 1, bar: 1, baz: 1}, + 2: {id: 2, foo: 1, bar: 1, baz: 2}, + 3: {id: 3, foo: 1, bar: 1, baz: 2}, + 4: {id: 4, foo: 1, bar: 2, baz: 1}, + 5: {id: 5, foo: 1, bar: 2, baz: 2}, + 6: {id: 6, foo: 1, bar: 2, baz: 2}, + 7: {id: 7, foo: 2, bar: 1, baz: 1}, + 8: {id: 8, foo: 2, bar: 1, baz: 2}, + 9: {id: 9, foo: 2, bar: 1, baz: 2}, + 10: {id: 10, foo: 2, bar: 2, baz: 1}, + 11: {id: 11, foo: 2, bar: 2, baz: 2}, + 12: {id: 12, foo: 2, bar: 2, baz: 2}, + }, + async (collRef, db) => { + let docRef = await collRef.doc('2').get(); + let query1 = collRef + .orderBy('foo') + .orderBy('bar') + .orderBy('baz') + .startAt(docRef); + let snapshot = await execute(db.pipeline().createFrom(query1)); + verifyResults( + snapshot, + {id: 2, foo: 1, bar: 1, baz: 2}, + {id: 3, foo: 1, bar: 1, baz: 2}, + {id: 4, foo: 1, bar: 2, baz: 1}, + {id: 5, foo: 1, bar: 2, baz: 2}, + {id: 6, foo: 1, bar: 2, baz: 2}, + {id: 7, foo: 2, bar: 1, baz: 1}, + {id: 8, foo: 2, bar: 1, baz: 2}, + {id: 9, foo: 2, bar: 1, baz: 2}, + {id: 10, foo: 2, bar: 2, baz: 1}, + {id: 11, foo: 2, bar: 2, baz: 2}, + {id: 12, foo: 2, bar: 2, baz: 2} + ); + + docRef = await collRef.doc('3').get(); + query1 = collRef + .orderBy('foo') + .orderBy('bar') + .orderBy('baz') + .startAt(docRef); + snapshot = await execute(db.pipeline().createFrom(query1)); + verifyResults( + snapshot, + {id: 3, foo: 1, bar: 1, baz: 2}, + {id: 4, foo: 1, bar: 2, baz: 1}, + {id: 5, foo: 1, bar: 2, baz: 2}, + {id: 6, foo: 1, bar: 2, baz: 2}, + {id: 7, foo: 2, bar: 1, baz: 1}, + {id: 8, foo: 2, bar: 1, baz: 2}, + {id: 9, foo: 2, bar: 1, baz: 2}, + {id: 10, foo: 2, bar: 2, baz: 1}, + {id: 11, foo: 2, bar: 2, baz: 2}, + {id: 12, foo: 2, bar: 2, baz: 2} + ); + } + ); + }); + + it('supports startAfter', () => { + return testCollectionWithDocs( + { + 1: {foo: 1}, + 2: {foo: 2}, + }, + async (collRef, db) => { + const query1 = collRef.orderBy('foo').startAfter(1); + const snapshot = await execute(db.pipeline().createFrom(query1)); + verifyResults(snapshot, {foo: 2}); + } + ); + }); + + it('supports endAt', () => { + return testCollectionWithDocs( + { + 1: {foo: 1}, + 2: {foo: 2}, + }, + async (collRef, db) => { + const query1 = collRef.orderBy('foo').endAt(1); + const snapshot = await execute(db.pipeline().createFrom(query1)); + verifyResults(snapshot, {foo: 1}); + } + ); + }); + + it('supports endBefore', () => { + return testCollectionWithDocs( + { + 1: {foo: 1}, + 2: {foo: 2}, + }, + async (collRef, db) => { + const query1 = collRef.orderBy('foo').endBefore(2); + const snapshot = await execute(db.pipeline().createFrom(query1)); + verifyResults(snapshot, {foo: 1}); + } + ); + }); + + it('supports pagination', () => { + return testCollectionWithDocs( + { + 1: {foo: 1}, + 2: {foo: 2}, + }, + async (collRef, db) => { + let query1 = collRef.orderBy('foo').limit(1); + const pipeline1 = db.pipeline().createFrom(query1); + let snapshot = await execute(pipeline1); + verifyResults(snapshot, {foo: 1}); + + // Pass the document snapshot from the previous snapshot + query1 = query1.startAfter(snapshot.results[0].get('foo')); + snapshot = await execute(db.pipeline().createFrom(query1)); + verifyResults(snapshot, {foo: 2}); + } + ); + }); + + it('supports pagination on DocumentIds', () => { + return testCollectionWithDocs( + { + 1: {foo: 1}, + 2: {foo: 2}, + }, + async (collRef, db) => { + let query1 = collRef + .orderBy('foo') + .orderBy(FieldPath.documentId(), 'asc') + .limit(1); + const pipeline1 = db.pipeline().createFrom(query1); + let snapshot = await execute(pipeline1); + verifyResults(snapshot, {foo: 1}); + + // Pass the document snapshot from the previous snapshot + query1 = query1.startAfter( + snapshot.results[0].get('foo'), + snapshot.results[0].ref?.id + ); + snapshot = await execute(db.pipeline().createFrom(query1)); + verifyResults(snapshot, {foo: 2}); + } + ); + }); + + // needs subcollection support + itIf(testUnsupportedFeatures)('supports collection groups', () => { + return testCollectionWithDocs({}, async (collRef, db) => { + const collectionGroupId = `${collRef.id}group`; + + const fooDoc = collRef.firestore.doc( + `${collRef.id}/foo/${collectionGroupId}/doc1` + ); + const barDoc = collRef.firestore.doc( + `${collRef.id}/bar/baz/boo/${collectionGroupId}/doc2` + ); + await fooDoc.set({foo: 1}); + await barDoc.set({bar: 1}); + + const query1 = collRef.firestore.collectionGroup(collectionGroupId); + const snapshot = await execute(db.pipeline().createFrom(query1)); + + verifyResults(snapshot, {bar: 1}, {foo: 1}); + }); + }); + + // needs subcollection support + itIf(testUnsupportedFeatures)( + 'supports query over collection path with special characters', + () => { + return testCollectionWithDocs({}, async (collRef, db) => { + const docWithSpecials = collRef.doc('so!@#$%^&*()_+special'); + + const collectionWithSpecials = docWithSpecials.collection( + 'so!@#$%^&*()_+special' + ); + await collectionWithSpecials.add({foo: 1}); + await collectionWithSpecials.add({foo: 2}); + + const snapshot = await execute( + db.pipeline().createFrom(collectionWithSpecials.orderBy('foo', 'asc')) + ); + + verifyResults(snapshot, {foo: 1}, {foo: 2}); + }); + } + ); + + it('supports multiple inequality on same field', () => { + return testCollectionWithDocs( + { + '01': {id: 1, foo: 1, bar: 1, baz: 1}, + '02': {id: 2, foo: 1, bar: 1, baz: 2}, + '03': {id: 3, foo: 1, bar: 1, baz: 2}, + '04': {id: 4, foo: 1, bar: 2, baz: 1}, + '05': {id: 5, foo: 1, bar: 2, baz: 2}, + '06': {id: 6, foo: 1, bar: 2, baz: 2}, + '07': {id: 7, foo: 2, bar: 1, baz: 1}, + '08': {id: 8, foo: 2, bar: 1, baz: 2}, + '09': {id: 9, foo: 2, bar: 1, baz: 2}, + '10': {id: 10, foo: 2, bar: 2, baz: 1}, + '11': {id: 11, foo: 2, bar: 2, baz: 2}, + '12': {id: 12, foo: 2, bar: 2, baz: 2}, + }, + async (collRef, db) => { + const query1 = collRef.where( + Filter.and(Filter.where('id', '>', 2), Filter.where('id', '<=', 10)) + ); + const snapshot = await execute(db.pipeline().createFrom(query1)); + verifyResults( + snapshot, + {id: 3, foo: 1, bar: 1, baz: 2}, + {id: 4, foo: 1, bar: 2, baz: 1}, + {id: 5, foo: 1, bar: 2, baz: 2}, + {id: 6, foo: 1, bar: 2, baz: 2}, + {id: 7, foo: 2, bar: 1, baz: 1}, + {id: 8, foo: 2, bar: 1, baz: 2}, + {id: 9, foo: 2, bar: 1, baz: 2}, + {id: 10, foo: 2, bar: 2, baz: 1} + ); + } + ); + }); + + it('supports multiple inequality on different fields', () => { + return testCollectionWithDocs( + { + '01': {id: 1, foo: 1, bar: 1, baz: 1}, + '02': {id: 2, foo: 1, bar: 1, baz: 2}, + '03': {id: 3, foo: 1, bar: 1, baz: 2}, + '04': {id: 4, foo: 1, bar: 2, baz: 1}, + '05': {id: 5, foo: 1, bar: 2, baz: 2}, + '06': {id: 6, foo: 1, bar: 2, baz: 2}, + '07': {id: 7, foo: 2, bar: 1, baz: 1}, + '08': {id: 8, foo: 2, bar: 1, baz: 2}, + '09': {id: 9, foo: 2, bar: 1, baz: 2}, + '10': {id: 10, foo: 2, bar: 2, baz: 1}, + '11': {id: 11, foo: 2, bar: 2, baz: 2}, + '12': {id: 12, foo: 2, bar: 2, baz: 2}, + }, + async (collRef, db) => { + const query1 = collRef.where( + Filter.and(Filter.where('id', '>=', 2), Filter.where('baz', '<', 2)) + ); + const snapshot = await execute(db.pipeline().createFrom(query1)); + verifyResults( + snapshot, + {id: 4, foo: 1, bar: 2, baz: 1}, + {id: 7, foo: 2, bar: 1, baz: 1}, + {id: 10, foo: 2, bar: 2, baz: 1} + ); + } + ); + }); + + it('supports collectionGroup query', () => { + return testCollectionWithDocs({1: {foo: 1}}, async (collRef, db) => { + const snapshot = await execute( + db.pipeline().createFrom(db.collectionGroup(collRef.id)) + ); + verifyResults(snapshot, {foo: 1}); + }); + }); + + it('supports eq nan', () => { + return testCollectionWithDocs( + { + 1: {foo: 1, bar: NaN}, + 2: {foo: 2, bar: 1}, + 3: {foo: 3, bar: 'bar'}, + }, + async (collRef, db) => { + const query1 = collRef.where('bar', '==', NaN); + const snapshot = await execute(db.pipeline().createFrom(query1)); + verifyResults(snapshot, {foo: 1, bar: NaN}); + } + ); + }); + + it('supports neq nan', () => { + return testCollectionWithDocs( + { + 1: {foo: 1, bar: NaN}, + 2: {foo: 2, bar: 1}, + 3: {foo: 3, bar: 'bar'}, + }, + async (collRef, db) => { + const query1 = collRef.where('bar', '!=', NaN); + const snapshot = await execute(db.pipeline().createFrom(query1)); + verifyResults(snapshot, {foo: 2, bar: 1}); + } + ); + }); + + it('supports eq null', () => { + return testCollectionWithDocs( + { + 1: {foo: 1, bar: null}, + 2: {foo: 2, bar: 1}, + }, + async (collRef, db) => { + const query1 = collRef.where('bar', '==', null); + const snapshot = await execute(db.pipeline().createFrom(query1)); + verifyResults(snapshot, {foo: 1, bar: null}); + } + ); + }); + + it('supports neq null', () => { + return testCollectionWithDocs( + { + 1: {foo: 1, bar: null}, + 2: {foo: 2, bar: 1}, + }, + async (collRef, db) => { + const query1 = collRef.where('bar', '!=', null); + const snapshot = await execute(db.pipeline().createFrom(query1)); + verifyResults(snapshot, {foo: 2, bar: 1}); + } + ); + }); + + it('supports neq', () => { + return testCollectionWithDocs( + { + 1: {foo: 1, bar: 0}, + 2: {foo: 2, bar: 1}, + }, + async (collRef, db) => { + const query1 = collRef.where('bar', '!=', 0); + const snapshot = await execute(db.pipeline().createFrom(query1)); + verifyResults(snapshot, {foo: 2, bar: 1}); + } + ); + }); + + it('supports array contains', () => { + return testCollectionWithDocs( + { + 1: {foo: 1, bar: [0, 2, 4, 6]}, + 2: {foo: 2, bar: [1, 3, 5, 7]}, + }, + async (collRef, db) => { + const query1 = collRef.where('bar', 'array-contains', 4); + const snapshot = await execute(db.pipeline().createFrom(query1)); + verifyResults(snapshot, {foo: 1, bar: [0, 2, 4, 6]}); + } + ); + }); + + it('supports array contains any', () => { + return testCollectionWithDocs( + { + 1: {foo: 1, bar: [0, 2, 4, 6]}, + 2: {foo: 2, bar: [1, 3, 5, 7]}, + 3: {foo: 3, bar: [10, 20, 30, 40]}, + }, + async (collRef, db) => { + const query1 = collRef.where('bar', 'array-contains-any', [4, 5]); + const snapshot = await execute(db.pipeline().createFrom(query1)); + verifyResults( + snapshot, + {foo: 1, bar: [0, 2, 4, 6]}, + {foo: 2, bar: [1, 3, 5, 7]} + ); + } + ); + }); + + it('supports in', () => { + return testCollectionWithDocs( + { + 1: {foo: 1, bar: 2}, + 2: {foo: 2}, + 3: {foo: 3, bar: 10}, + }, + async (collRef, db) => { + const query1 = collRef.where('bar', 'in', [0, 10, 20]); + const snapshot = await execute(db.pipeline().createFrom(query1)); + verifyResults(snapshot, {foo: 3, bar: 10}); + } + ); + }); + + it('supports in with 1', () => { + return testCollectionWithDocs( + { + 1: {foo: 1, bar: 2}, + 2: {foo: 2}, + 3: {foo: 3, bar: 10}, + }, + async (collRef, db) => { + const query1 = collRef.where('bar', 'in', [2]); + const snapshot = await execute(db.pipeline().createFrom(query1)); + verifyResults(snapshot, {foo: 1, bar: 2}); + } + ); + }); + + itIf(testUnsupportedFeatures)('supports not in', () => { + return testCollectionWithDocs( + { + 1: {foo: 1, bar: 2}, + 2: {foo: 2, bar: 1}, + 3: {foo: 3, bar: 10}, + }, + async (collRef, db) => { + const query1 = collRef.where('bar', 'not-in', [0, 10, 20]); + const snapshot = await execute(db.pipeline().createFrom(query1)); + verifyResults(snapshot, {foo: 1, bar: 2}, {foo: 2, bar: 1}); + } + ); + }); + + it('supports not in with 1', () => { + return testCollectionWithDocs( + { + 1: {foo: 1, bar: 2}, + 2: {foo: 2}, + 3: {foo: 3, bar: 10}, + }, + async (collRef, db) => { + const query1 = collRef.where('bar', 'not-in', [2]); + const snapshot = await execute(db.pipeline().createFrom(query1)); + verifyResults(snapshot, {foo: 3, bar: 10}); + } + ); + }); + + it('supports or operator', () => { + return testCollectionWithDocs( + { + 1: {foo: 1, bar: 2}, + 2: {foo: 2, bar: 0}, + 3: {foo: 3, bar: 10}, + }, + async (collRef, db) => { + const query1 = collRef + .where( + Filter.or( + Filter.where('bar', '==', 2), + Filter.where('foo', '==', 3) + ) + ) + .orderBy('foo'); + const snapshot = await execute(db.pipeline().createFrom(query1)); + verifyResults(snapshot, {foo: 1, bar: 2}, {foo: 3, bar: 10}); + } + ); + }); +}); diff --git a/dev/system-test/query.ts b/dev/system-test/query.ts index 0a983756a..877016419 100644 --- a/dev/system-test/query.ts +++ b/dev/system-test/query.ts @@ -115,7 +115,7 @@ describe('Query class', () => { async function compareQueryAndPipeline(query: Query): Promise { const queryResults = await query.get(); - const pipeline = query.pipeline(); + const pipeline = query.firestore.pipeline().createFrom(query); const pipelineResults = await pipeline.execute(); expect(pipelineResults.results.map(r => r._fieldsProto)).to.deep.equal( From 7d4277f8b74998c6a11094e4fd197534ab9b29a0 Mon Sep 17 00:00:00 2001 From: Mark Duckworth <1124037+MarkDuckworth@users.noreply.github.com> Date: Tue, 1 Jul 2025 13:44:00 -0600 Subject: [PATCH 39/60] pipelines proto update (#2373) Update to the latest preview protos --- dev/protos/admin_v1.json | 506 +- dev/protos/firestore_admin_v1_proto_api.d.ts | 1065 +- dev/protos/firestore_admin_v1_proto_api.js | 2085 +++- dev/protos/firestore_v1_proto_api.d.ts | 341 +- dev/protos/firestore_v1_proto_api.js | 5040 ++++---- dev/protos/firestore_v1beta1_proto_api.d.ts | 235 +- dev/protos/firestore_v1beta1_proto_api.js | 540 +- dev/protos/google/api/annotations.proto | 2 +- dev/protos/google/api/client.proto | 75 +- dev/protos/google/api/field_behavior.proto | 2 +- dev/protos/google/api/http.proto | 50 +- dev/protos/google/api/launch_stage.proto | 2 +- dev/protos/google/api/resource.proto | 11 +- dev/protos/google/api/routing.proto | 461 + .../google/firestore/admin/v1/backup.proto | 2 +- .../google/firestore/admin/v1/database.proto | 33 +- .../google/firestore/admin/v1/field.proto | 2 +- .../firestore/admin/v1/firestore_admin.proto | 174 +- .../google/firestore/admin/v1/index.proto | 47 +- .../google/firestore/admin/v1/location.proto | 2 +- .../google/firestore/admin/v1/operation.proto | 2 +- .../google/firestore/admin/v1/schedule.proto | 2 +- .../firestore/admin/v1/user_creds.proto | 86 + dev/protos/google/firestore/v1/document.proto | 52 +- .../google/firestore/v1/explain_stats.proto | 38 + .../google/firestore/v1/firestore.proto | 47 +- dev/protos/google/firestore/v1/pipeline.proto | 52 +- dev/protos/google/firestore/v1/query.proto | 5 +- .../google/firestore/v1beta1/common.proto | 2 +- .../google/firestore/v1beta1/document.proto | 2 +- .../google/firestore/v1beta1/firestore.proto | 2 +- .../google/firestore/v1beta1/query.proto | 2 +- .../undeliverable_first_gen_event.proto | 2 +- .../google/firestore/v1beta1/write.proto | 2 +- .../google/longrunning/operations.proto | 37 +- dev/protos/google/rpc/status.proto | 8 +- dev/protos/google/type/dayofweek.proto | 2 +- dev/protos/google/type/latlng.proto | 2 +- dev/protos/update.sh | 19 +- dev/protos/v1.json | 1728 +-- dev/protos/v1beta1.json | 125 +- dev/src/v1/firestore_admin_client.ts | 5950 ++++----- dev/src/v1/firestore_admin_client_config.json | 28 + dev/src/v1/firestore_admin_proto_list.json | 3 +- dev/src/v1/firestore_client.ts | 3427 +++--- dev/src/v1/firestore_client_config.json | 3 +- dev/src/v1/firestore_proto_list.json | 2 + dev/src/v1/gapic_metadata.json | 5 + dev/src/v1beta1/firestore_client.ts | 9 + dev/test/gapic_firestore_admin_v1.ts | 10094 ++++++++-------- dev/test/gapic_firestore_v1.ts | 5636 ++++----- package.json | 2 +- 52 files changed, 19882 insertions(+), 18169 deletions(-) create mode 100644 dev/protos/google/api/routing.proto create mode 100644 dev/protos/google/firestore/admin/v1/user_creds.proto create mode 100644 dev/protos/google/firestore/v1/explain_stats.proto diff --git a/dev/protos/admin_v1.json b/dev/protos/admin_v1.json index a792d6432..fd70d145d 100644 --- a/dev/protos/admin_v1.json +++ b/dev/protos/admin_v1.json @@ -1,7 +1,4 @@ { - "options": { - "syntax": "proto3" - }, "nested": { "google": { "nested": { @@ -122,6 +119,13 @@ "(google.api.resource).pattern": "projects/{project}/databases/{database}", "(google.api.resource).style": "DECLARATIVE_FRIENDLY" }, + "oneofs": { + "_freeTier": { + "oneof": [ + "freeTier" + ] + } + }, "fields": { "name": { "type": "string", @@ -221,9 +225,24 @@ "(google.api.field_behavior)": "OUTPUT_ONLY" } }, + "freeTier": { + "type": "bool", + "id": 30, + "options": { + "(google.api.field_behavior)": "OUTPUT_ONLY", + "proto3_optional": true + } + }, "etag": { "type": "string", "id": 99 + }, + "databaseEdition": { + "type": "DatabaseEdition", + "id": 28, + "options": { + "(google.api.field_behavior)": "IMMUTABLE" + } } }, "nested": { @@ -360,6 +379,13 @@ } } } + }, + "DatabaseEdition": { + "values": { + "DATABASE_EDITION_UNSPECIFIED": 0, + "STANDARD": 1, + "ENTERPRISE": 2 + } } } }, @@ -456,6 +482,27 @@ "state": { "type": "State", "id": 4 + }, + "density": { + "type": "Density", + "id": 6, + "options": { + "(google.api.field_behavior)": "IMMUTABLE" + } + }, + "multikey": { + "type": "bool", + "id": 7, + "options": { + "(google.api.field_behavior)": "OPTIONAL" + } + }, + "shardCount": { + "type": "int32", + "id": 8, + "options": { + "(google.api.field_behavior)": "OPTIONAL" + } } }, "nested": { @@ -470,7 +517,8 @@ "ApiScope": { "values": { "ANY_API": 0, - "DATASTORE_MODE_API": 1 + "DATASTORE_MODE_API": 1, + "MONGODB_COMPATIBLE_API": 2 } }, "IndexField": { @@ -551,6 +599,14 @@ "READY": 2, "NEEDS_REPAIR": 3 } + }, + "Density": { + "values": { + "DENSITY_UNSPECIFIED": 0, + "SPARSE_ALL": 1, + "SPARSE_ANY": 2, + "DENSE": 3 + } } } }, @@ -908,6 +964,140 @@ } ] }, + "CreateUserCreds": { + "requestType": "CreateUserCredsRequest", + "responseType": "UserCreds", + "options": { + "(google.api.http).post": "/v1/{parent=projects/*/databases/*}/userCreds", + "(google.api.http).body": "user_creds", + "(google.api.method_signature)": "parent,user_creds,user_creds_id" + }, + "parsedOptions": [ + { + "(google.api.http)": { + "post": "/v1/{parent=projects/*/databases/*}/userCreds", + "body": "user_creds" + } + }, + { + "(google.api.method_signature)": "parent,user_creds,user_creds_id" + } + ] + }, + "GetUserCreds": { + "requestType": "GetUserCredsRequest", + "responseType": "UserCreds", + "options": { + "(google.api.http).get": "/v1/{name=projects/*/databases/*/userCreds/*}", + "(google.api.method_signature)": "name" + }, + "parsedOptions": [ + { + "(google.api.http)": { + "get": "/v1/{name=projects/*/databases/*/userCreds/*}" + } + }, + { + "(google.api.method_signature)": "name" + } + ] + }, + "ListUserCreds": { + "requestType": "ListUserCredsRequest", + "responseType": "ListUserCredsResponse", + "options": { + "(google.api.http).get": "/v1/{parent=projects/*/databases/*}/userCreds", + "(google.api.method_signature)": "parent" + }, + "parsedOptions": [ + { + "(google.api.http)": { + "get": "/v1/{parent=projects/*/databases/*}/userCreds" + } + }, + { + "(google.api.method_signature)": "parent" + } + ] + }, + "EnableUserCreds": { + "requestType": "EnableUserCredsRequest", + "responseType": "UserCreds", + "options": { + "(google.api.http).post": "/v1/{name=projects/*/databases/*/userCreds/*}:enable", + "(google.api.http).body": "*", + "(google.api.method_signature)": "name" + }, + "parsedOptions": [ + { + "(google.api.http)": { + "post": "/v1/{name=projects/*/databases/*/userCreds/*}:enable", + "body": "*" + } + }, + { + "(google.api.method_signature)": "name" + } + ] + }, + "DisableUserCreds": { + "requestType": "DisableUserCredsRequest", + "responseType": "UserCreds", + "options": { + "(google.api.http).post": "/v1/{name=projects/*/databases/*/userCreds/*}:disable", + "(google.api.http).body": "*", + "(google.api.method_signature)": "name" + }, + "parsedOptions": [ + { + "(google.api.http)": { + "post": "/v1/{name=projects/*/databases/*/userCreds/*}:disable", + "body": "*" + } + }, + { + "(google.api.method_signature)": "name" + } + ] + }, + "ResetUserPassword": { + "requestType": "ResetUserPasswordRequest", + "responseType": "UserCreds", + "options": { + "(google.api.http).post": "/v1/{name=projects/*/databases/*/userCreds/*}:resetPassword", + "(google.api.http).body": "*", + "(google.api.method_signature)": "name" + }, + "parsedOptions": [ + { + "(google.api.http)": { + "post": "/v1/{name=projects/*/databases/*/userCreds/*}:resetPassword", + "body": "*" + } + }, + { + "(google.api.method_signature)": "name" + } + ] + }, + "DeleteUserCreds": { + "requestType": "DeleteUserCredsRequest", + "responseType": "google.protobuf.Empty", + "options": { + "(google.api.http).delete": "/v1/{name=projects/*/databases/*/userCreds/*}", + "(google.api.method_signature)": "name" + }, + "parsedOptions": [ + { + "(google.api.http)": { + "delete": "/v1/{name=projects/*/databases/*/userCreds/*}" + } + }, + { + "(google.api.method_signature)": "name" + } + ] + }, "GetBackup": { "requestType": "GetBackupRequest", "responseType": "Backup", @@ -1190,6 +1380,113 @@ "DeleteDatabaseMetadata": { "fields": {} }, + "CreateUserCredsRequest": { + "fields": { + "parent": { + "type": "string", + "id": 1, + "options": { + "(google.api.field_behavior)": "REQUIRED", + "(google.api.resource_reference).child_type": "firestore.googleapis.com/UserCreds" + } + }, + "userCreds": { + "type": "UserCreds", + "id": 2, + "options": { + "(google.api.field_behavior)": "REQUIRED" + } + }, + "userCredsId": { + "type": "string", + "id": 3, + "options": { + "(google.api.field_behavior)": "REQUIRED" + } + } + } + }, + "GetUserCredsRequest": { + "fields": { + "name": { + "type": "string", + "id": 1, + "options": { + "(google.api.field_behavior)": "REQUIRED", + "(google.api.resource_reference).type": "firestore.googleapis.com/UserCreds" + } + } + } + }, + "ListUserCredsRequest": { + "fields": { + "parent": { + "type": "string", + "id": 1, + "options": { + "(google.api.field_behavior)": "REQUIRED", + "(google.api.resource_reference).child_type": "firestore.googleapis.com/UserCreds" + } + } + } + }, + "ListUserCredsResponse": { + "fields": { + "userCreds": { + "rule": "repeated", + "type": "UserCreds", + "id": 1 + } + } + }, + "EnableUserCredsRequest": { + "fields": { + "name": { + "type": "string", + "id": 1, + "options": { + "(google.api.field_behavior)": "REQUIRED", + "(google.api.resource_reference).type": "firestore.googleapis.com/UserCreds" + } + } + } + }, + "DisableUserCredsRequest": { + "fields": { + "name": { + "type": "string", + "id": 1, + "options": { + "(google.api.field_behavior)": "REQUIRED", + "(google.api.resource_reference).type": "firestore.googleapis.com/UserCreds" + } + } + } + }, + "ResetUserPasswordRequest": { + "fields": { + "name": { + "type": "string", + "id": 1, + "options": { + "(google.api.field_behavior)": "REQUIRED", + "(google.api.resource_reference).type": "firestore.googleapis.com/UserCreds" + } + } + } + }, + "DeleteUserCredsRequest": { + "fields": { + "name": { + "type": "string", + "id": 1, + "options": { + "(google.api.field_behavior)": "REQUIRED", + "(google.api.resource_reference).type": "firestore.googleapis.com/UserCreds" + } + } + } + }, "CreateBackupScheduleRequest": { "fields": { "parent": { @@ -1937,6 +2234,82 @@ } } }, + "UserCreds": { + "options": { + "(google.api.resource).type": "firestore.googleapis.com/UserCreds", + "(google.api.resource).pattern": "projects/{project}/databases/{database}/userCreds/{user_creds}", + "(google.api.resource).plural": "userCreds", + "(google.api.resource).singular": "userCreds" + }, + "oneofs": { + "UserCredsIdentity": { + "oneof": [ + "resourceIdentity" + ] + } + }, + "fields": { + "name": { + "type": "string", + "id": 1, + "options": { + "(google.api.field_behavior)": "IDENTIFIER" + } + }, + "createTime": { + "type": "google.protobuf.Timestamp", + "id": 2, + "options": { + "(google.api.field_behavior)": "OUTPUT_ONLY" + } + }, + "updateTime": { + "type": "google.protobuf.Timestamp", + "id": 3, + "options": { + "(google.api.field_behavior)": "OUTPUT_ONLY" + } + }, + "state": { + "type": "State", + "id": 4, + "options": { + "(google.api.field_behavior)": "OUTPUT_ONLY" + } + }, + "securePassword": { + "type": "string", + "id": 5, + "options": { + "(google.api.field_behavior)": "OUTPUT_ONLY" + } + }, + "resourceIdentity": { + "type": "ResourceIdentity", + "id": 6 + } + }, + "nested": { + "State": { + "values": { + "STATE_UNSPECIFIED": 0, + "ENABLED": 1, + "DISABLED": 2 + } + }, + "ResourceIdentity": { + "fields": { + "principal": { + "type": "string", + "id": 1, + "options": { + "(google.api.field_behavior)": "OUTPUT_ONLY" + } + } + } + } + } + }, "LocationMetadata": { "fields": {} } @@ -1948,9 +2321,9 @@ }, "api": { "options": { - "go_package": "google.golang.org/genproto/googleapis/api;api", + "go_package": "google.golang.org/genproto/googleapis/api/annotations;annotations", "java_multiple_files": true, - "java_outer_classname": "LaunchStageProto", + "java_outer_classname": "RoutingProto", "java_package": "com.google.api", "objc_class_prefix": "GAPI", "cc_enable_arenas": true @@ -2176,10 +2549,6 @@ "rule": "repeated", "type": "ClientLibraryDestination", "id": 2 - }, - "selectiveGapicGeneration": { - "type": "SelectiveGapicGeneration", - "id": 3 } } }, @@ -2320,24 +2689,6 @@ "common": { "type": "CommonLanguageSettings", "id": 1 - }, - "experimentalFeatures": { - "type": "ExperimentalFeatures", - "id": 2 - } - }, - "nested": { - "ExperimentalFeatures": { - "fields": { - "restAsyncIoEnabled": { - "type": "bool", - "id": 1 - }, - "protobufPythonicTypesEnabled": { - "type": "bool", - "id": 2 - } - } } } }, @@ -2395,11 +2746,6 @@ "common": { "type": "CommonLanguageSettings", "id": 1 - }, - "renamedServices": { - "keyType": "string", - "type": "string", - "id": 2 } } }, @@ -2461,19 +2807,6 @@ "PACKAGE_MANAGER": 20 } }, - "SelectiveGapicGeneration": { - "fields": { - "methods": { - "rule": "repeated", - "type": "string", - "id": 1 - }, - "generateOmittedAsInternal": { - "type": "bool", - "id": 2 - } - } - }, "LaunchStage": { "values": { "LAUNCH_STAGE_UNSPECIFIED": 0, @@ -2485,6 +2818,32 @@ "GA": 4, "DEPRECATED": 5 } + }, + "routing": { + "type": "google.api.RoutingRule", + "id": 72295729, + "extend": "google.protobuf.MethodOptions" + }, + "RoutingRule": { + "fields": { + "routingParameters": { + "rule": "repeated", + "type": "RoutingParameter", + "id": 2 + } + } + }, + "RoutingParameter": { + "fields": { + "field": { + "type": "string", + "id": 1 + }, + "pathTemplate": { + "type": "string", + "id": 2 + } + } } } }, @@ -2500,6 +2859,7 @@ }, "nested": { "FileDescriptorSet": { + "edition": "proto2", "fields": { "file": { "rule": "repeated", @@ -2509,6 +2869,7 @@ } }, "Edition": { + "edition": "proto2", "values": { "EDITION_UNKNOWN": 0, "EDITION_PROTO2": 998, @@ -2524,6 +2885,7 @@ } }, "FileDescriptorProto": { + "edition": "proto2", "fields": { "name": { "type": "string", @@ -2541,18 +2903,12 @@ "publicDependency": { "rule": "repeated", "type": "int32", - "id": 10, - "options": { - "packed": false - } + "id": 10 }, "weakDependency": { "rule": "repeated", "type": "int32", - "id": 11, - "options": { - "packed": false - } + "id": 11 }, "messageType": { "rule": "repeated", @@ -2593,6 +2949,7 @@ } }, "DescriptorProto": { + "edition": "proto2", "fields": { "name": { "type": "string", @@ -2675,6 +3032,7 @@ } }, "ExtensionRangeOptions": { + "edition": "proto2", "fields": { "uninterpretedOption": { "rule": "repeated", @@ -2748,6 +3106,7 @@ } }, "FieldDescriptorProto": { + "edition": "proto2", "fields": { "name": { "type": "string", @@ -2827,6 +3186,7 @@ } }, "OneofDescriptorProto": { + "edition": "proto2", "fields": { "name": { "type": "string", @@ -2839,6 +3199,7 @@ } }, "EnumDescriptorProto": { + "edition": "proto2", "fields": { "name": { "type": "string", @@ -2880,6 +3241,7 @@ } }, "EnumValueDescriptorProto": { + "edition": "proto2", "fields": { "name": { "type": "string", @@ -2896,6 +3258,7 @@ } }, "ServiceDescriptorProto": { + "edition": "proto2", "fields": { "name": { "type": "string", @@ -2913,6 +3276,7 @@ } }, "MethodDescriptorProto": { + "edition": "proto2", "fields": { "name": { "type": "string", @@ -2947,6 +3311,7 @@ } }, "FileOptions": { + "edition": "proto2", "fields": { "javaPackage": { "type": "string", @@ -3088,6 +3453,7 @@ } }, "MessageOptions": { + "edition": "proto2", "fields": { "messageSetWireFormat": { "type": "bool", @@ -3161,6 +3527,7 @@ ] }, "FieldOptions": { + "edition": "proto2", "fields": { "ctype": { "type": "CType", @@ -3222,10 +3589,7 @@ "targets": { "rule": "repeated", "type": "OptionTargetType", - "id": 19, - "options": { - "packed": false - } + "id": 19 }, "editionDefaults": { "rule": "repeated", @@ -3309,6 +3673,7 @@ } }, "OneofOptions": { + "edition": "proto2", "fields": { "features": { "type": "FeatureSet", @@ -3328,6 +3693,7 @@ ] }, "EnumOptions": { + "edition": "proto2", "fields": { "allowAlias": { "type": "bool", @@ -3371,6 +3737,7 @@ ] }, "EnumValueOptions": { + "edition": "proto2", "fields": { "deprecated": { "type": "bool", @@ -3404,6 +3771,7 @@ ] }, "ServiceOptions": { + "edition": "proto2", "fields": { "features": { "type": "FeatureSet", @@ -3430,6 +3798,7 @@ ] }, "MethodOptions": { + "edition": "proto2", "fields": { "deprecated": { "type": "bool", @@ -3472,6 +3841,7 @@ } }, "UninterpretedOption": { + "edition": "proto2", "fields": { "name": { "rule": "repeated", @@ -3521,6 +3891,7 @@ } }, "FeatureSet": { + "edition": "proto2", "fields": { "fieldPresence": { "type": "FieldPresence", @@ -3658,6 +4029,7 @@ } }, "FeatureSetDefaults": { + "edition": "proto2", "fields": { "defaults": { "rule": "repeated", @@ -3689,6 +4061,7 @@ } }, "SourceCodeInfo": { + "edition": "proto2", "fields": { "location": { "rule": "repeated", @@ -3702,12 +4075,18 @@ "path": { "rule": "repeated", "type": "int32", - "id": 1 + "id": 1, + "options": { + "packed": true + } }, "span": { "rule": "repeated", "type": "int32", - "id": 2 + "id": 2, + "options": { + "packed": true + } }, "leadingComments": { "type": "string", @@ -3727,6 +4106,7 @@ } }, "GeneratedCodeInfo": { + "edition": "proto2", "fields": { "annotation": { "rule": "repeated", @@ -3740,7 +4120,10 @@ "path": { "rule": "repeated", "type": "int32", - "id": 1 + "id": 1, + "options": { + "packed": true + } }, "sourceFile": { "type": "string", @@ -4000,7 +4383,6 @@ "java_multiple_files": true, "java_outer_classname": "OperationsProto", "java_package": "com.google.longrunning", - "objc_class_prefix": "GLRUN", "php_namespace": "Google\\LongRunning" }, "nested": { diff --git a/dev/protos/firestore_admin_v1_proto_api.d.ts b/dev/protos/firestore_admin_v1_proto_api.d.ts index 4240ac50f..97e0d401b 100644 --- a/dev/protos/firestore_admin_v1_proto_api.d.ts +++ b/dev/protos/firestore_admin_v1_proto_api.d.ts @@ -15,6 +15,7 @@ */ import * as $protobuf from "protobufjs"; +import Long = require("long"); /** Namespace google. */ export namespace google { @@ -232,8 +233,14 @@ export namespace google { /** Database sourceInfo */ sourceInfo?: (google.firestore.admin.v1.Database.ISourceInfo|null); + /** Database freeTier */ + freeTier?: (boolean|null); + /** Database etag */ etag?: (string|null); + + /** Database databaseEdition */ + databaseEdition?: (google.firestore.admin.v1.Database.DatabaseEdition|null); } /** Represents a Database. */ @@ -296,9 +303,18 @@ export namespace google { /** Database sourceInfo. */ public sourceInfo?: (google.firestore.admin.v1.Database.ISourceInfo|null); + /** Database freeTier. */ + public freeTier?: (boolean|null); + /** Database etag. */ public etag: string; + /** Database databaseEdition. */ + public databaseEdition: google.firestore.admin.v1.Database.DatabaseEdition; + + /** Database _freeTier. */ + public _freeTier?: "freeTier"; + /** * Creates a Database message from a plain object. Also converts values to their respective internal types. * @param object Plain object @@ -709,6 +725,10 @@ export namespace google { public static getTypeUrl(typeUrlPrefix?: string): string; } } + + /** DatabaseEdition enum. */ + type DatabaseEdition = + "DATABASE_EDITION_UNSPECIFIED"| "STANDARD"| "ENTERPRISE"; } /** Properties of a Field. */ @@ -912,6 +932,15 @@ export namespace google { /** Index state */ state?: (google.firestore.admin.v1.Index.State|null); + + /** Index density */ + density?: (google.firestore.admin.v1.Index.Density|null); + + /** Index multikey */ + multikey?: (boolean|null); + + /** Index shardCount */ + shardCount?: (number|null); } /** Represents an Index. */ @@ -938,6 +967,15 @@ export namespace google { /** Index state. */ public state: google.firestore.admin.v1.Index.State; + /** Index density. */ + public density: google.firestore.admin.v1.Index.Density; + + /** Index multikey. */ + public multikey: boolean; + + /** Index shardCount. */ + public shardCount: number; + /** * Creates an Index message from a plain object. Also converts values to their respective internal types. * @param object Plain object @@ -975,7 +1013,7 @@ export namespace google { /** ApiScope enum. */ type ApiScope = - "ANY_API"| "DATASTORE_MODE_API"; + "ANY_API"| "DATASTORE_MODE_API"| "MONGODB_COMPATIBLE_API"; /** Properties of an IndexField. */ interface IIndexField { @@ -1162,6 +1200,10 @@ export namespace google { /** State enum. */ type State = "STATE_UNSPECIFIED"| "CREATING"| "READY"| "NEEDS_REPAIR"; + + /** Density enum. */ + type Density = + "DENSITY_UNSPECIFIED"| "SPARSE_ALL"| "SPARSE_ANY"| "DENSE"; } /** Represents a FirestoreAdmin */ @@ -1385,6 +1427,104 @@ export namespace google { */ public deleteDatabase(request: google.firestore.admin.v1.IDeleteDatabaseRequest): Promise; + /** + * Calls CreateUserCreds. + * @param request CreateUserCredsRequest message or plain object + * @param callback Node-style callback called with the error, if any, and UserCreds + */ + public createUserCreds(request: google.firestore.admin.v1.ICreateUserCredsRequest, callback: google.firestore.admin.v1.FirestoreAdmin.CreateUserCredsCallback): void; + + /** + * Calls CreateUserCreds. + * @param request CreateUserCredsRequest message or plain object + * @returns Promise + */ + public createUserCreds(request: google.firestore.admin.v1.ICreateUserCredsRequest): Promise; + + /** + * Calls GetUserCreds. + * @param request GetUserCredsRequest message or plain object + * @param callback Node-style callback called with the error, if any, and UserCreds + */ + public getUserCreds(request: google.firestore.admin.v1.IGetUserCredsRequest, callback: google.firestore.admin.v1.FirestoreAdmin.GetUserCredsCallback): void; + + /** + * Calls GetUserCreds. + * @param request GetUserCredsRequest message or plain object + * @returns Promise + */ + public getUserCreds(request: google.firestore.admin.v1.IGetUserCredsRequest): Promise; + + /** + * Calls ListUserCreds. + * @param request ListUserCredsRequest message or plain object + * @param callback Node-style callback called with the error, if any, and ListUserCredsResponse + */ + public listUserCreds(request: google.firestore.admin.v1.IListUserCredsRequest, callback: google.firestore.admin.v1.FirestoreAdmin.ListUserCredsCallback): void; + + /** + * Calls ListUserCreds. + * @param request ListUserCredsRequest message or plain object + * @returns Promise + */ + public listUserCreds(request: google.firestore.admin.v1.IListUserCredsRequest): Promise; + + /** + * Calls EnableUserCreds. + * @param request EnableUserCredsRequest message or plain object + * @param callback Node-style callback called with the error, if any, and UserCreds + */ + public enableUserCreds(request: google.firestore.admin.v1.IEnableUserCredsRequest, callback: google.firestore.admin.v1.FirestoreAdmin.EnableUserCredsCallback): void; + + /** + * Calls EnableUserCreds. + * @param request EnableUserCredsRequest message or plain object + * @returns Promise + */ + public enableUserCreds(request: google.firestore.admin.v1.IEnableUserCredsRequest): Promise; + + /** + * Calls DisableUserCreds. + * @param request DisableUserCredsRequest message or plain object + * @param callback Node-style callback called with the error, if any, and UserCreds + */ + public disableUserCreds(request: google.firestore.admin.v1.IDisableUserCredsRequest, callback: google.firestore.admin.v1.FirestoreAdmin.DisableUserCredsCallback): void; + + /** + * Calls DisableUserCreds. + * @param request DisableUserCredsRequest message or plain object + * @returns Promise + */ + public disableUserCreds(request: google.firestore.admin.v1.IDisableUserCredsRequest): Promise; + + /** + * Calls ResetUserPassword. + * @param request ResetUserPasswordRequest message or plain object + * @param callback Node-style callback called with the error, if any, and UserCreds + */ + public resetUserPassword(request: google.firestore.admin.v1.IResetUserPasswordRequest, callback: google.firestore.admin.v1.FirestoreAdmin.ResetUserPasswordCallback): void; + + /** + * Calls ResetUserPassword. + * @param request ResetUserPasswordRequest message or plain object + * @returns Promise + */ + public resetUserPassword(request: google.firestore.admin.v1.IResetUserPasswordRequest): Promise; + + /** + * Calls DeleteUserCreds. + * @param request DeleteUserCredsRequest message or plain object + * @param callback Node-style callback called with the error, if any, and Empty + */ + public deleteUserCreds(request: google.firestore.admin.v1.IDeleteUserCredsRequest, callback: google.firestore.admin.v1.FirestoreAdmin.DeleteUserCredsCallback): void; + + /** + * Calls DeleteUserCreds. + * @param request DeleteUserCredsRequest message or plain object + * @returns Promise + */ + public deleteUserCreds(request: google.firestore.admin.v1.IDeleteUserCredsRequest): Promise; + /** * Calls GetBackup. * @param request GetBackupRequest message or plain object @@ -1619,6 +1759,55 @@ export namespace google { */ type DeleteDatabaseCallback = (error: (Error|null), response?: google.longrunning.Operation) => void; + /** + * Callback as used by {@link google.firestore.admin.v1.FirestoreAdmin#createUserCreds}. + * @param error Error, if any + * @param [response] UserCreds + */ + type CreateUserCredsCallback = (error: (Error|null), response?: google.firestore.admin.v1.UserCreds) => void; + + /** + * Callback as used by {@link google.firestore.admin.v1.FirestoreAdmin#getUserCreds}. + * @param error Error, if any + * @param [response] UserCreds + */ + type GetUserCredsCallback = (error: (Error|null), response?: google.firestore.admin.v1.UserCreds) => void; + + /** + * Callback as used by {@link google.firestore.admin.v1.FirestoreAdmin#listUserCreds}. + * @param error Error, if any + * @param [response] ListUserCredsResponse + */ + type ListUserCredsCallback = (error: (Error|null), response?: google.firestore.admin.v1.ListUserCredsResponse) => void; + + /** + * Callback as used by {@link google.firestore.admin.v1.FirestoreAdmin#enableUserCreds}. + * @param error Error, if any + * @param [response] UserCreds + */ + type EnableUserCredsCallback = (error: (Error|null), response?: google.firestore.admin.v1.UserCreds) => void; + + /** + * Callback as used by {@link google.firestore.admin.v1.FirestoreAdmin#disableUserCreds}. + * @param error Error, if any + * @param [response] UserCreds + */ + type DisableUserCredsCallback = (error: (Error|null), response?: google.firestore.admin.v1.UserCreds) => void; + + /** + * Callback as used by {@link google.firestore.admin.v1.FirestoreAdmin#resetUserPassword}. + * @param error Error, if any + * @param [response] UserCreds + */ + type ResetUserPasswordCallback = (error: (Error|null), response?: google.firestore.admin.v1.UserCreds) => void; + + /** + * Callback as used by {@link google.firestore.admin.v1.FirestoreAdmin#deleteUserCreds}. + * @param error Error, if any + * @param [response] Empty + */ + type DeleteUserCredsCallback = (error: (Error|null), response?: google.protobuf.Empty) => void; + /** * Callback as used by {@link google.firestore.admin.v1.FirestoreAdmin#getBackup}. * @param error Error, if any @@ -1913,220 +2102,616 @@ export namespace google { public name: string; /** - * Creates a GetDatabaseRequest message from a plain object. Also converts values to their respective internal types. + * Creates a GetDatabaseRequest message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns GetDatabaseRequest + */ + public static fromObject(object: { [k: string]: any }): google.firestore.admin.v1.GetDatabaseRequest; + + /** + * Creates a plain object from a GetDatabaseRequest message. Also converts values to other types if specified. + * @param message GetDatabaseRequest + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.firestore.admin.v1.GetDatabaseRequest, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this GetDatabaseRequest to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for GetDatabaseRequest + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of an UpdateDatabaseRequest. */ + interface IUpdateDatabaseRequest { + + /** UpdateDatabaseRequest database */ + database?: (google.firestore.admin.v1.IDatabase|null); + + /** UpdateDatabaseRequest updateMask */ + updateMask?: (google.protobuf.IFieldMask|null); + } + + /** Represents an UpdateDatabaseRequest. */ + class UpdateDatabaseRequest implements IUpdateDatabaseRequest { + + /** + * Constructs a new UpdateDatabaseRequest. + * @param [properties] Properties to set + */ + constructor(properties?: google.firestore.admin.v1.IUpdateDatabaseRequest); + + /** UpdateDatabaseRequest database. */ + public database?: (google.firestore.admin.v1.IDatabase|null); + + /** UpdateDatabaseRequest updateMask. */ + public updateMask?: (google.protobuf.IFieldMask|null); + + /** + * Creates an UpdateDatabaseRequest message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns UpdateDatabaseRequest + */ + public static fromObject(object: { [k: string]: any }): google.firestore.admin.v1.UpdateDatabaseRequest; + + /** + * Creates a plain object from an UpdateDatabaseRequest message. Also converts values to other types if specified. + * @param message UpdateDatabaseRequest + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.firestore.admin.v1.UpdateDatabaseRequest, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this UpdateDatabaseRequest to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for UpdateDatabaseRequest + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of an UpdateDatabaseMetadata. */ + interface IUpdateDatabaseMetadata { + } + + /** Represents an UpdateDatabaseMetadata. */ + class UpdateDatabaseMetadata implements IUpdateDatabaseMetadata { + + /** + * Constructs a new UpdateDatabaseMetadata. + * @param [properties] Properties to set + */ + constructor(properties?: google.firestore.admin.v1.IUpdateDatabaseMetadata); + + /** + * Creates an UpdateDatabaseMetadata message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns UpdateDatabaseMetadata + */ + public static fromObject(object: { [k: string]: any }): google.firestore.admin.v1.UpdateDatabaseMetadata; + + /** + * Creates a plain object from an UpdateDatabaseMetadata message. Also converts values to other types if specified. + * @param message UpdateDatabaseMetadata + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.firestore.admin.v1.UpdateDatabaseMetadata, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this UpdateDatabaseMetadata to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for UpdateDatabaseMetadata + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a DeleteDatabaseRequest. */ + interface IDeleteDatabaseRequest { + + /** DeleteDatabaseRequest name */ + name?: (string|null); + + /** DeleteDatabaseRequest etag */ + etag?: (string|null); + } + + /** Represents a DeleteDatabaseRequest. */ + class DeleteDatabaseRequest implements IDeleteDatabaseRequest { + + /** + * Constructs a new DeleteDatabaseRequest. + * @param [properties] Properties to set + */ + constructor(properties?: google.firestore.admin.v1.IDeleteDatabaseRequest); + + /** DeleteDatabaseRequest name. */ + public name: string; + + /** DeleteDatabaseRequest etag. */ + public etag: string; + + /** + * Creates a DeleteDatabaseRequest message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns DeleteDatabaseRequest + */ + public static fromObject(object: { [k: string]: any }): google.firestore.admin.v1.DeleteDatabaseRequest; + + /** + * Creates a plain object from a DeleteDatabaseRequest message. Also converts values to other types if specified. + * @param message DeleteDatabaseRequest + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.firestore.admin.v1.DeleteDatabaseRequest, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this DeleteDatabaseRequest to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for DeleteDatabaseRequest + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a DeleteDatabaseMetadata. */ + interface IDeleteDatabaseMetadata { + } + + /** Represents a DeleteDatabaseMetadata. */ + class DeleteDatabaseMetadata implements IDeleteDatabaseMetadata { + + /** + * Constructs a new DeleteDatabaseMetadata. + * @param [properties] Properties to set + */ + constructor(properties?: google.firestore.admin.v1.IDeleteDatabaseMetadata); + + /** + * Creates a DeleteDatabaseMetadata message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns DeleteDatabaseMetadata + */ + public static fromObject(object: { [k: string]: any }): google.firestore.admin.v1.DeleteDatabaseMetadata; + + /** + * Creates a plain object from a DeleteDatabaseMetadata message. Also converts values to other types if specified. + * @param message DeleteDatabaseMetadata + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.firestore.admin.v1.DeleteDatabaseMetadata, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this DeleteDatabaseMetadata to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for DeleteDatabaseMetadata + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a CreateUserCredsRequest. */ + interface ICreateUserCredsRequest { + + /** CreateUserCredsRequest parent */ + parent?: (string|null); + + /** CreateUserCredsRequest userCreds */ + userCreds?: (google.firestore.admin.v1.IUserCreds|null); + + /** CreateUserCredsRequest userCredsId */ + userCredsId?: (string|null); + } + + /** Represents a CreateUserCredsRequest. */ + class CreateUserCredsRequest implements ICreateUserCredsRequest { + + /** + * Constructs a new CreateUserCredsRequest. + * @param [properties] Properties to set + */ + constructor(properties?: google.firestore.admin.v1.ICreateUserCredsRequest); + + /** CreateUserCredsRequest parent. */ + public parent: string; + + /** CreateUserCredsRequest userCreds. */ + public userCreds?: (google.firestore.admin.v1.IUserCreds|null); + + /** CreateUserCredsRequest userCredsId. */ + public userCredsId: string; + + /** + * Creates a CreateUserCredsRequest message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns CreateUserCredsRequest + */ + public static fromObject(object: { [k: string]: any }): google.firestore.admin.v1.CreateUserCredsRequest; + + /** + * Creates a plain object from a CreateUserCredsRequest message. Also converts values to other types if specified. + * @param message CreateUserCredsRequest + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.firestore.admin.v1.CreateUserCredsRequest, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this CreateUserCredsRequest to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for CreateUserCredsRequest + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a GetUserCredsRequest. */ + interface IGetUserCredsRequest { + + /** GetUserCredsRequest name */ + name?: (string|null); + } + + /** Represents a GetUserCredsRequest. */ + class GetUserCredsRequest implements IGetUserCredsRequest { + + /** + * Constructs a new GetUserCredsRequest. + * @param [properties] Properties to set + */ + constructor(properties?: google.firestore.admin.v1.IGetUserCredsRequest); + + /** GetUserCredsRequest name. */ + public name: string; + + /** + * Creates a GetUserCredsRequest message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns GetUserCredsRequest + */ + public static fromObject(object: { [k: string]: any }): google.firestore.admin.v1.GetUserCredsRequest; + + /** + * Creates a plain object from a GetUserCredsRequest message. Also converts values to other types if specified. + * @param message GetUserCredsRequest + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.firestore.admin.v1.GetUserCredsRequest, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this GetUserCredsRequest to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for GetUserCredsRequest + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a ListUserCredsRequest. */ + interface IListUserCredsRequest { + + /** ListUserCredsRequest parent */ + parent?: (string|null); + } + + /** Represents a ListUserCredsRequest. */ + class ListUserCredsRequest implements IListUserCredsRequest { + + /** + * Constructs a new ListUserCredsRequest. + * @param [properties] Properties to set + */ + constructor(properties?: google.firestore.admin.v1.IListUserCredsRequest); + + /** ListUserCredsRequest parent. */ + public parent: string; + + /** + * Creates a ListUserCredsRequest message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns ListUserCredsRequest + */ + public static fromObject(object: { [k: string]: any }): google.firestore.admin.v1.ListUserCredsRequest; + + /** + * Creates a plain object from a ListUserCredsRequest message. Also converts values to other types if specified. + * @param message ListUserCredsRequest + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.firestore.admin.v1.ListUserCredsRequest, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this ListUserCredsRequest to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for ListUserCredsRequest + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a ListUserCredsResponse. */ + interface IListUserCredsResponse { + + /** ListUserCredsResponse userCreds */ + userCreds?: (google.firestore.admin.v1.IUserCreds[]|null); + } + + /** Represents a ListUserCredsResponse. */ + class ListUserCredsResponse implements IListUserCredsResponse { + + /** + * Constructs a new ListUserCredsResponse. + * @param [properties] Properties to set + */ + constructor(properties?: google.firestore.admin.v1.IListUserCredsResponse); + + /** ListUserCredsResponse userCreds. */ + public userCreds: google.firestore.admin.v1.IUserCreds[]; + + /** + * Creates a ListUserCredsResponse message from a plain object. Also converts values to their respective internal types. * @param object Plain object - * @returns GetDatabaseRequest + * @returns ListUserCredsResponse */ - public static fromObject(object: { [k: string]: any }): google.firestore.admin.v1.GetDatabaseRequest; + public static fromObject(object: { [k: string]: any }): google.firestore.admin.v1.ListUserCredsResponse; /** - * Creates a plain object from a GetDatabaseRequest message. Also converts values to other types if specified. - * @param message GetDatabaseRequest + * Creates a plain object from a ListUserCredsResponse message. Also converts values to other types if specified. + * @param message ListUserCredsResponse * @param [options] Conversion options * @returns Plain object */ - public static toObject(message: google.firestore.admin.v1.GetDatabaseRequest, options?: $protobuf.IConversionOptions): { [k: string]: any }; + public static toObject(message: google.firestore.admin.v1.ListUserCredsResponse, options?: $protobuf.IConversionOptions): { [k: string]: any }; /** - * Converts this GetDatabaseRequest to JSON. + * Converts this ListUserCredsResponse to JSON. * @returns JSON object */ public toJSON(): { [k: string]: any }; /** - * Gets the default type url for GetDatabaseRequest + * Gets the default type url for ListUserCredsResponse * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") * @returns The default type url */ public static getTypeUrl(typeUrlPrefix?: string): string; } - /** Properties of an UpdateDatabaseRequest. */ - interface IUpdateDatabaseRequest { - - /** UpdateDatabaseRequest database */ - database?: (google.firestore.admin.v1.IDatabase|null); + /** Properties of an EnableUserCredsRequest. */ + interface IEnableUserCredsRequest { - /** UpdateDatabaseRequest updateMask */ - updateMask?: (google.protobuf.IFieldMask|null); + /** EnableUserCredsRequest name */ + name?: (string|null); } - /** Represents an UpdateDatabaseRequest. */ - class UpdateDatabaseRequest implements IUpdateDatabaseRequest { + /** Represents an EnableUserCredsRequest. */ + class EnableUserCredsRequest implements IEnableUserCredsRequest { /** - * Constructs a new UpdateDatabaseRequest. + * Constructs a new EnableUserCredsRequest. * @param [properties] Properties to set */ - constructor(properties?: google.firestore.admin.v1.IUpdateDatabaseRequest); - - /** UpdateDatabaseRequest database. */ - public database?: (google.firestore.admin.v1.IDatabase|null); + constructor(properties?: google.firestore.admin.v1.IEnableUserCredsRequest); - /** UpdateDatabaseRequest updateMask. */ - public updateMask?: (google.protobuf.IFieldMask|null); + /** EnableUserCredsRequest name. */ + public name: string; /** - * Creates an UpdateDatabaseRequest message from a plain object. Also converts values to their respective internal types. + * Creates an EnableUserCredsRequest message from a plain object. Also converts values to their respective internal types. * @param object Plain object - * @returns UpdateDatabaseRequest + * @returns EnableUserCredsRequest */ - public static fromObject(object: { [k: string]: any }): google.firestore.admin.v1.UpdateDatabaseRequest; + public static fromObject(object: { [k: string]: any }): google.firestore.admin.v1.EnableUserCredsRequest; /** - * Creates a plain object from an UpdateDatabaseRequest message. Also converts values to other types if specified. - * @param message UpdateDatabaseRequest + * Creates a plain object from an EnableUserCredsRequest message. Also converts values to other types if specified. + * @param message EnableUserCredsRequest * @param [options] Conversion options * @returns Plain object */ - public static toObject(message: google.firestore.admin.v1.UpdateDatabaseRequest, options?: $protobuf.IConversionOptions): { [k: string]: any }; + public static toObject(message: google.firestore.admin.v1.EnableUserCredsRequest, options?: $protobuf.IConversionOptions): { [k: string]: any }; /** - * Converts this UpdateDatabaseRequest to JSON. + * Converts this EnableUserCredsRequest to JSON. * @returns JSON object */ public toJSON(): { [k: string]: any }; /** - * Gets the default type url for UpdateDatabaseRequest + * Gets the default type url for EnableUserCredsRequest * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") * @returns The default type url */ public static getTypeUrl(typeUrlPrefix?: string): string; } - /** Properties of an UpdateDatabaseMetadata. */ - interface IUpdateDatabaseMetadata { + /** Properties of a DisableUserCredsRequest. */ + interface IDisableUserCredsRequest { + + /** DisableUserCredsRequest name */ + name?: (string|null); } - /** Represents an UpdateDatabaseMetadata. */ - class UpdateDatabaseMetadata implements IUpdateDatabaseMetadata { + /** Represents a DisableUserCredsRequest. */ + class DisableUserCredsRequest implements IDisableUserCredsRequest { /** - * Constructs a new UpdateDatabaseMetadata. + * Constructs a new DisableUserCredsRequest. * @param [properties] Properties to set */ - constructor(properties?: google.firestore.admin.v1.IUpdateDatabaseMetadata); + constructor(properties?: google.firestore.admin.v1.IDisableUserCredsRequest); + + /** DisableUserCredsRequest name. */ + public name: string; /** - * Creates an UpdateDatabaseMetadata message from a plain object. Also converts values to their respective internal types. + * Creates a DisableUserCredsRequest message from a plain object. Also converts values to their respective internal types. * @param object Plain object - * @returns UpdateDatabaseMetadata + * @returns DisableUserCredsRequest */ - public static fromObject(object: { [k: string]: any }): google.firestore.admin.v1.UpdateDatabaseMetadata; + public static fromObject(object: { [k: string]: any }): google.firestore.admin.v1.DisableUserCredsRequest; /** - * Creates a plain object from an UpdateDatabaseMetadata message. Also converts values to other types if specified. - * @param message UpdateDatabaseMetadata + * Creates a plain object from a DisableUserCredsRequest message. Also converts values to other types if specified. + * @param message DisableUserCredsRequest * @param [options] Conversion options * @returns Plain object */ - public static toObject(message: google.firestore.admin.v1.UpdateDatabaseMetadata, options?: $protobuf.IConversionOptions): { [k: string]: any }; + public static toObject(message: google.firestore.admin.v1.DisableUserCredsRequest, options?: $protobuf.IConversionOptions): { [k: string]: any }; /** - * Converts this UpdateDatabaseMetadata to JSON. + * Converts this DisableUserCredsRequest to JSON. * @returns JSON object */ public toJSON(): { [k: string]: any }; /** - * Gets the default type url for UpdateDatabaseMetadata + * Gets the default type url for DisableUserCredsRequest * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") * @returns The default type url */ public static getTypeUrl(typeUrlPrefix?: string): string; } - /** Properties of a DeleteDatabaseRequest. */ - interface IDeleteDatabaseRequest { + /** Properties of a ResetUserPasswordRequest. */ + interface IResetUserPasswordRequest { - /** DeleteDatabaseRequest name */ + /** ResetUserPasswordRequest name */ name?: (string|null); - - /** DeleteDatabaseRequest etag */ - etag?: (string|null); } - /** Represents a DeleteDatabaseRequest. */ - class DeleteDatabaseRequest implements IDeleteDatabaseRequest { + /** Represents a ResetUserPasswordRequest. */ + class ResetUserPasswordRequest implements IResetUserPasswordRequest { /** - * Constructs a new DeleteDatabaseRequest. + * Constructs a new ResetUserPasswordRequest. * @param [properties] Properties to set */ - constructor(properties?: google.firestore.admin.v1.IDeleteDatabaseRequest); + constructor(properties?: google.firestore.admin.v1.IResetUserPasswordRequest); - /** DeleteDatabaseRequest name. */ + /** ResetUserPasswordRequest name. */ public name: string; - /** DeleteDatabaseRequest etag. */ - public etag: string; - /** - * Creates a DeleteDatabaseRequest message from a plain object. Also converts values to their respective internal types. + * Creates a ResetUserPasswordRequest message from a plain object. Also converts values to their respective internal types. * @param object Plain object - * @returns DeleteDatabaseRequest + * @returns ResetUserPasswordRequest */ - public static fromObject(object: { [k: string]: any }): google.firestore.admin.v1.DeleteDatabaseRequest; + public static fromObject(object: { [k: string]: any }): google.firestore.admin.v1.ResetUserPasswordRequest; /** - * Creates a plain object from a DeleteDatabaseRequest message. Also converts values to other types if specified. - * @param message DeleteDatabaseRequest + * Creates a plain object from a ResetUserPasswordRequest message. Also converts values to other types if specified. + * @param message ResetUserPasswordRequest * @param [options] Conversion options * @returns Plain object */ - public static toObject(message: google.firestore.admin.v1.DeleteDatabaseRequest, options?: $protobuf.IConversionOptions): { [k: string]: any }; + public static toObject(message: google.firestore.admin.v1.ResetUserPasswordRequest, options?: $protobuf.IConversionOptions): { [k: string]: any }; /** - * Converts this DeleteDatabaseRequest to JSON. + * Converts this ResetUserPasswordRequest to JSON. * @returns JSON object */ public toJSON(): { [k: string]: any }; /** - * Gets the default type url for DeleteDatabaseRequest + * Gets the default type url for ResetUserPasswordRequest * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") * @returns The default type url */ public static getTypeUrl(typeUrlPrefix?: string): string; } - /** Properties of a DeleteDatabaseMetadata. */ - interface IDeleteDatabaseMetadata { + /** Properties of a DeleteUserCredsRequest. */ + interface IDeleteUserCredsRequest { + + /** DeleteUserCredsRequest name */ + name?: (string|null); } - /** Represents a DeleteDatabaseMetadata. */ - class DeleteDatabaseMetadata implements IDeleteDatabaseMetadata { + /** Represents a DeleteUserCredsRequest. */ + class DeleteUserCredsRequest implements IDeleteUserCredsRequest { /** - * Constructs a new DeleteDatabaseMetadata. + * Constructs a new DeleteUserCredsRequest. * @param [properties] Properties to set */ - constructor(properties?: google.firestore.admin.v1.IDeleteDatabaseMetadata); + constructor(properties?: google.firestore.admin.v1.IDeleteUserCredsRequest); + + /** DeleteUserCredsRequest name. */ + public name: string; /** - * Creates a DeleteDatabaseMetadata message from a plain object. Also converts values to their respective internal types. + * Creates a DeleteUserCredsRequest message from a plain object. Also converts values to their respective internal types. * @param object Plain object - * @returns DeleteDatabaseMetadata + * @returns DeleteUserCredsRequest */ - public static fromObject(object: { [k: string]: any }): google.firestore.admin.v1.DeleteDatabaseMetadata; + public static fromObject(object: { [k: string]: any }): google.firestore.admin.v1.DeleteUserCredsRequest; /** - * Creates a plain object from a DeleteDatabaseMetadata message. Also converts values to other types if specified. - * @param message DeleteDatabaseMetadata + * Creates a plain object from a DeleteUserCredsRequest message. Also converts values to other types if specified. + * @param message DeleteUserCredsRequest * @param [options] Conversion options * @returns Plain object */ - public static toObject(message: google.firestore.admin.v1.DeleteDatabaseMetadata, options?: $protobuf.IConversionOptions): { [k: string]: any }; + public static toObject(message: google.firestore.admin.v1.DeleteUserCredsRequest, options?: $protobuf.IConversionOptions): { [k: string]: any }; /** - * Converts this DeleteDatabaseMetadata to JSON. + * Converts this DeleteUserCredsRequest to JSON. * @returns JSON object */ public toJSON(): { [k: string]: any }; /** - * Gets the default type url for DeleteDatabaseMetadata + * Gets the default type url for DeleteUserCredsRequest * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") * @returns The default type url */ @@ -4353,6 +4938,142 @@ export namespace google { public static getTypeUrl(typeUrlPrefix?: string): string; } + /** Properties of a UserCreds. */ + interface IUserCreds { + + /** UserCreds name */ + name?: (string|null); + + /** UserCreds createTime */ + createTime?: (google.protobuf.ITimestamp|null); + + /** UserCreds updateTime */ + updateTime?: (google.protobuf.ITimestamp|null); + + /** UserCreds state */ + state?: (google.firestore.admin.v1.UserCreds.State|null); + + /** UserCreds securePassword */ + securePassword?: (string|null); + + /** UserCreds resourceIdentity */ + resourceIdentity?: (google.firestore.admin.v1.UserCreds.IResourceIdentity|null); + } + + /** Represents a UserCreds. */ + class UserCreds implements IUserCreds { + + /** + * Constructs a new UserCreds. + * @param [properties] Properties to set + */ + constructor(properties?: google.firestore.admin.v1.IUserCreds); + + /** UserCreds name. */ + public name: string; + + /** UserCreds createTime. */ + public createTime?: (google.protobuf.ITimestamp|null); + + /** UserCreds updateTime. */ + public updateTime?: (google.protobuf.ITimestamp|null); + + /** UserCreds state. */ + public state: google.firestore.admin.v1.UserCreds.State; + + /** UserCreds securePassword. */ + public securePassword: string; + + /** UserCreds resourceIdentity. */ + public resourceIdentity?: (google.firestore.admin.v1.UserCreds.IResourceIdentity|null); + + /** UserCreds UserCredsIdentity. */ + public UserCredsIdentity?: "resourceIdentity"; + + /** + * Creates a UserCreds message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns UserCreds + */ + public static fromObject(object: { [k: string]: any }): google.firestore.admin.v1.UserCreds; + + /** + * Creates a plain object from a UserCreds message. Also converts values to other types if specified. + * @param message UserCreds + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.firestore.admin.v1.UserCreds, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this UserCreds to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for UserCreds + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + namespace UserCreds { + + /** State enum. */ + type State = + "STATE_UNSPECIFIED"| "ENABLED"| "DISABLED"; + + /** Properties of a ResourceIdentity. */ + interface IResourceIdentity { + + /** ResourceIdentity principal */ + principal?: (string|null); + } + + /** Represents a ResourceIdentity. */ + class ResourceIdentity implements IResourceIdentity { + + /** + * Constructs a new ResourceIdentity. + * @param [properties] Properties to set + */ + constructor(properties?: google.firestore.admin.v1.UserCreds.IResourceIdentity); + + /** ResourceIdentity principal. */ + public principal: string; + + /** + * Creates a ResourceIdentity message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns ResourceIdentity + */ + public static fromObject(object: { [k: string]: any }): google.firestore.admin.v1.UserCreds.ResourceIdentity; + + /** + * Creates a plain object from a ResourceIdentity message. Also converts values to other types if specified. + * @param message ResourceIdentity + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.firestore.admin.v1.UserCreds.ResourceIdentity, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this ResourceIdentity to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for ResourceIdentity + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + } + /** Properties of a LocationMetadata. */ interface ILocationMetadata { } @@ -4775,9 +5496,6 @@ export namespace google { /** CommonLanguageSettings destinations */ destinations?: (google.api.ClientLibraryDestination[]|null); - - /** CommonLanguageSettings selectiveGapicGeneration */ - selectiveGapicGeneration?: (google.api.ISelectiveGapicGeneration|null); } /** Represents a CommonLanguageSettings. */ @@ -4795,9 +5513,6 @@ export namespace google { /** CommonLanguageSettings destinations. */ public destinations: google.api.ClientLibraryDestination[]; - /** CommonLanguageSettings selectiveGapicGeneration. */ - public selectiveGapicGeneration?: (google.api.ISelectiveGapicGeneration|null); - /** * Creates a CommonLanguageSettings message from a plain object. Also converts values to their respective internal types. * @param object Plain object @@ -5204,9 +5919,6 @@ export namespace google { /** PythonSettings common */ common?: (google.api.ICommonLanguageSettings|null); - - /** PythonSettings experimentalFeatures */ - experimentalFeatures?: (google.api.PythonSettings.IExperimentalFeatures|null); } /** Represents a PythonSettings. */ @@ -5221,9 +5933,6 @@ export namespace google { /** PythonSettings common. */ public common?: (google.api.ICommonLanguageSettings|null); - /** PythonSettings experimentalFeatures. */ - public experimentalFeatures?: (google.api.PythonSettings.IExperimentalFeatures|null); - /** * Creates a PythonSettings message from a plain object. Also converts values to their respective internal types. * @param object Plain object @@ -5253,63 +5962,6 @@ export namespace google { public static getTypeUrl(typeUrlPrefix?: string): string; } - namespace PythonSettings { - - /** Properties of an ExperimentalFeatures. */ - interface IExperimentalFeatures { - - /** ExperimentalFeatures restAsyncIoEnabled */ - restAsyncIoEnabled?: (boolean|null); - - /** ExperimentalFeatures protobufPythonicTypesEnabled */ - protobufPythonicTypesEnabled?: (boolean|null); - } - - /** Represents an ExperimentalFeatures. */ - class ExperimentalFeatures implements IExperimentalFeatures { - - /** - * Constructs a new ExperimentalFeatures. - * @param [properties] Properties to set - */ - constructor(properties?: google.api.PythonSettings.IExperimentalFeatures); - - /** ExperimentalFeatures restAsyncIoEnabled. */ - public restAsyncIoEnabled: boolean; - - /** ExperimentalFeatures protobufPythonicTypesEnabled. */ - public protobufPythonicTypesEnabled: boolean; - - /** - * Creates an ExperimentalFeatures message from a plain object. Also converts values to their respective internal types. - * @param object Plain object - * @returns ExperimentalFeatures - */ - public static fromObject(object: { [k: string]: any }): google.api.PythonSettings.ExperimentalFeatures; - - /** - * Creates a plain object from an ExperimentalFeatures message. Also converts values to other types if specified. - * @param message ExperimentalFeatures - * @param [options] Conversion options - * @returns Plain object - */ - public static toObject(message: google.api.PythonSettings.ExperimentalFeatures, options?: $protobuf.IConversionOptions): { [k: string]: any }; - - /** - * Converts this ExperimentalFeatures to JSON. - * @returns JSON object - */ - public toJSON(): { [k: string]: any }; - - /** - * Gets the default type url for ExperimentalFeatures - * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") - * @returns The default type url - */ - public static getTypeUrl(typeUrlPrefix?: string): string; - } - } - /** Properties of a NodeSettings. */ interface INodeSettings { @@ -5489,9 +6141,6 @@ export namespace google { /** GoSettings common */ common?: (google.api.ICommonLanguageSettings|null); - - /** GoSettings renamedServices */ - renamedServices?: ({ [k: string]: string }|null); } /** Represents a GoSettings. */ @@ -5506,9 +6155,6 @@ export namespace google { /** GoSettings common. */ public common?: (google.api.ICommonLanguageSettings|null); - /** GoSettings renamedServices. */ - public renamedServices: { [k: string]: string }; - /** * Creates a GoSettings message from a plain object. Also converts values to their respective internal types. * @param object Plain object @@ -5675,63 +6321,111 @@ export namespace google { type ClientLibraryDestination = "CLIENT_LIBRARY_DESTINATION_UNSPECIFIED"| "GITHUB"| "PACKAGE_MANAGER"; - /** Properties of a SelectiveGapicGeneration. */ - interface ISelectiveGapicGeneration { + /** LaunchStage enum. */ + type LaunchStage = + "LAUNCH_STAGE_UNSPECIFIED"| "UNIMPLEMENTED"| "PRELAUNCH"| "EARLY_ACCESS"| "ALPHA"| "BETA"| "GA"| "DEPRECATED"; - /** SelectiveGapicGeneration methods */ - methods?: (string[]|null); + /** Properties of a RoutingRule. */ + interface IRoutingRule { - /** SelectiveGapicGeneration generateOmittedAsInternal */ - generateOmittedAsInternal?: (boolean|null); + /** RoutingRule routingParameters */ + routingParameters?: (google.api.IRoutingParameter[]|null); } - /** Represents a SelectiveGapicGeneration. */ - class SelectiveGapicGeneration implements ISelectiveGapicGeneration { + /** Represents a RoutingRule. */ + class RoutingRule implements IRoutingRule { /** - * Constructs a new SelectiveGapicGeneration. + * Constructs a new RoutingRule. * @param [properties] Properties to set */ - constructor(properties?: google.api.ISelectiveGapicGeneration); + constructor(properties?: google.api.IRoutingRule); - /** SelectiveGapicGeneration methods. */ - public methods: string[]; - - /** SelectiveGapicGeneration generateOmittedAsInternal. */ - public generateOmittedAsInternal: boolean; + /** RoutingRule routingParameters. */ + public routingParameters: google.api.IRoutingParameter[]; /** - * Creates a SelectiveGapicGeneration message from a plain object. Also converts values to their respective internal types. + * Creates a RoutingRule message from a plain object. Also converts values to their respective internal types. * @param object Plain object - * @returns SelectiveGapicGeneration + * @returns RoutingRule */ - public static fromObject(object: { [k: string]: any }): google.api.SelectiveGapicGeneration; + public static fromObject(object: { [k: string]: any }): google.api.RoutingRule; /** - * Creates a plain object from a SelectiveGapicGeneration message. Also converts values to other types if specified. - * @param message SelectiveGapicGeneration + * Creates a plain object from a RoutingRule message. Also converts values to other types if specified. + * @param message RoutingRule * @param [options] Conversion options * @returns Plain object */ - public static toObject(message: google.api.SelectiveGapicGeneration, options?: $protobuf.IConversionOptions): { [k: string]: any }; + public static toObject(message: google.api.RoutingRule, options?: $protobuf.IConversionOptions): { [k: string]: any }; /** - * Converts this SelectiveGapicGeneration to JSON. + * Converts this RoutingRule to JSON. * @returns JSON object */ public toJSON(): { [k: string]: any }; /** - * Gets the default type url for SelectiveGapicGeneration + * Gets the default type url for RoutingRule * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") * @returns The default type url */ public static getTypeUrl(typeUrlPrefix?: string): string; } - /** LaunchStage enum. */ - type LaunchStage = - "LAUNCH_STAGE_UNSPECIFIED"| "UNIMPLEMENTED"| "PRELAUNCH"| "EARLY_ACCESS"| "ALPHA"| "BETA"| "GA"| "DEPRECATED"; + /** Properties of a RoutingParameter. */ + interface IRoutingParameter { + + /** RoutingParameter field */ + field?: (string|null); + + /** RoutingParameter pathTemplate */ + pathTemplate?: (string|null); + } + + /** Represents a RoutingParameter. */ + class RoutingParameter implements IRoutingParameter { + + /** + * Constructs a new RoutingParameter. + * @param [properties] Properties to set + */ + constructor(properties?: google.api.IRoutingParameter); + + /** RoutingParameter field. */ + public field: string; + + /** RoutingParameter pathTemplate. */ + public pathTemplate: string; + + /** + * Creates a RoutingParameter message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns RoutingParameter + */ + public static fromObject(object: { [k: string]: any }): google.api.RoutingParameter; + + /** + * Creates a plain object from a RoutingParameter message. Also converts values to other types if specified. + * @param message RoutingParameter + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.api.RoutingParameter, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this RoutingParameter to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for RoutingParameter + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } } /** Namespace protobuf. */ @@ -7521,6 +8215,9 @@ export namespace google { /** MethodOptions .google.longrunning.operationInfo */ ".google.longrunning.operationInfo"?: (google.longrunning.IOperationInfo|null); + + /** MethodOptions .google.api.routing */ + ".google.api.routing"?: (google.api.IRoutingRule|null); } /** Represents a MethodOptions. */ diff --git a/dev/protos/firestore_admin_v1_proto_api.js b/dev/protos/firestore_admin_v1_proto_api.js index 859a2215f..8f115ffca 100644 --- a/dev/protos/firestore_admin_v1_proto_api.js +++ b/dev/protos/firestore_admin_v1_proto_api.js @@ -492,7 +492,9 @@ * @property {google.firestore.admin.v1.Database.ICmekConfig|null} [cmekConfig] Database cmekConfig * @property {string|null} [previousId] Database previousId * @property {google.firestore.admin.v1.Database.ISourceInfo|null} [sourceInfo] Database sourceInfo + * @property {boolean|null} [freeTier] Database freeTier * @property {string|null} [etag] Database etag + * @property {google.firestore.admin.v1.Database.DatabaseEdition|null} [databaseEdition] Database databaseEdition */ /** @@ -646,6 +648,14 @@ */ Database.prototype.sourceInfo = null; + /** + * Database freeTier. + * @member {boolean|null|undefined} freeTier + * @memberof google.firestore.admin.v1.Database + * @instance + */ + Database.prototype.freeTier = null; + /** * Database etag. * @member {string} etag @@ -654,6 +664,28 @@ */ Database.prototype.etag = ""; + /** + * Database databaseEdition. + * @member {google.firestore.admin.v1.Database.DatabaseEdition} databaseEdition + * @memberof google.firestore.admin.v1.Database + * @instance + */ + Database.prototype.databaseEdition = 0; + + // OneOf field names bound to virtual getters and setters + var $oneOfFields; + + /** + * Database _freeTier. + * @member {"freeTier"|undefined} _freeTier + * @memberof google.firestore.admin.v1.Database + * @instance + */ + Object.defineProperty(Database.prototype, "_freeTier", { + get: $util.oneOfGetter($oneOfFields = ["freeTier"]), + set: $util.oneOfSetter($oneOfFields) + }); + /** * Creates a Database message from a plain object. Also converts values to their respective internal types. * @function fromObject @@ -815,8 +847,30 @@ throw TypeError(".google.firestore.admin.v1.Database.sourceInfo: object expected"); message.sourceInfo = $root.google.firestore.admin.v1.Database.SourceInfo.fromObject(object.sourceInfo); } + if (object.freeTier != null) + message.freeTier = Boolean(object.freeTier); if (object.etag != null) message.etag = String(object.etag); + switch (object.databaseEdition) { + default: + if (typeof object.databaseEdition === "number") { + message.databaseEdition = object.databaseEdition; + break; + } + break; + case "DATABASE_EDITION_UNSPECIFIED": + case 0: + message.databaseEdition = 0; + break; + case "STANDARD": + case 1: + message.databaseEdition = 1; + break; + case "ENTERPRISE": + case 2: + message.databaseEdition = 2; + break; + } return message; }; @@ -851,6 +905,7 @@ object.cmekConfig = null; object.previousId = ""; object.sourceInfo = null; + object.databaseEdition = options.enums === String ? "DATABASE_EDITION_UNSPECIFIED" : 0; object.etag = ""; } if (message.name != null && message.hasOwnProperty("name")) @@ -887,6 +942,13 @@ object.previousId = message.previousId; if (message.sourceInfo != null && message.hasOwnProperty("sourceInfo")) object.sourceInfo = $root.google.firestore.admin.v1.Database.SourceInfo.toObject(message.sourceInfo, options); + if (message.databaseEdition != null && message.hasOwnProperty("databaseEdition")) + object.databaseEdition = options.enums === String ? $root.google.firestore.admin.v1.Database.DatabaseEdition[message.databaseEdition] === undefined ? message.databaseEdition : $root.google.firestore.admin.v1.Database.DatabaseEdition[message.databaseEdition] : message.databaseEdition; + if (message.freeTier != null && message.hasOwnProperty("freeTier")) { + object.freeTier = message.freeTier; + if (options.oneofs) + object._freeTier = "freeTier"; + } if (message.etag != null && message.hasOwnProperty("etag")) object.etag = message.etag; return object; @@ -1761,6 +1823,22 @@ return EncryptionConfig; })(); + /** + * DatabaseEdition enum. + * @name google.firestore.admin.v1.Database.DatabaseEdition + * @enum {string} + * @property {string} DATABASE_EDITION_UNSPECIFIED=DATABASE_EDITION_UNSPECIFIED DATABASE_EDITION_UNSPECIFIED value + * @property {string} STANDARD=STANDARD STANDARD value + * @property {string} ENTERPRISE=ENTERPRISE ENTERPRISE value + */ + Database.DatabaseEdition = (function() { + var valuesById = {}, values = Object.create(valuesById); + values[valuesById[0] = "DATABASE_EDITION_UNSPECIFIED"] = "DATABASE_EDITION_UNSPECIFIED"; + values[valuesById[1] = "STANDARD"] = "STANDARD"; + values[valuesById[2] = "ENTERPRISE"] = "ENTERPRISE"; + return values; + })(); + return Database; })(); @@ -2200,6 +2278,9 @@ * @property {google.firestore.admin.v1.Index.ApiScope|null} [apiScope] Index apiScope * @property {Array.|null} [fields] Index fields * @property {google.firestore.admin.v1.Index.State|null} [state] Index state + * @property {google.firestore.admin.v1.Index.Density|null} [density] Index density + * @property {boolean|null} [multikey] Index multikey + * @property {number|null} [shardCount] Index shardCount */ /** @@ -2258,6 +2339,30 @@ */ Index.prototype.state = 0; + /** + * Index density. + * @member {google.firestore.admin.v1.Index.Density} density + * @memberof google.firestore.admin.v1.Index + * @instance + */ + Index.prototype.density = 0; + + /** + * Index multikey. + * @member {boolean} multikey + * @memberof google.firestore.admin.v1.Index + * @instance + */ + Index.prototype.multikey = false; + + /** + * Index shardCount. + * @member {number} shardCount + * @memberof google.firestore.admin.v1.Index + * @instance + */ + Index.prototype.shardCount = 0; + /** * Creates an Index message from a plain object. Also converts values to their respective internal types. * @function fromObject @@ -2311,6 +2416,10 @@ case 1: message.apiScope = 1; break; + case "MONGODB_COMPATIBLE_API": + case 2: + message.apiScope = 2; + break; } if (object.fields) { if (!Array.isArray(object.fields)) @@ -2346,6 +2455,34 @@ message.state = 3; break; } + switch (object.density) { + default: + if (typeof object.density === "number") { + message.density = object.density; + break; + } + break; + case "DENSITY_UNSPECIFIED": + case 0: + message.density = 0; + break; + case "SPARSE_ALL": + case 1: + message.density = 1; + break; + case "SPARSE_ANY": + case 2: + message.density = 2; + break; + case "DENSE": + case 3: + message.density = 3; + break; + } + if (object.multikey != null) + message.multikey = Boolean(object.multikey); + if (object.shardCount != null) + message.shardCount = object.shardCount | 0; return message; }; @@ -2369,6 +2506,9 @@ object.queryScope = options.enums === String ? "QUERY_SCOPE_UNSPECIFIED" : 0; object.state = options.enums === String ? "STATE_UNSPECIFIED" : 0; object.apiScope = options.enums === String ? "ANY_API" : 0; + object.density = options.enums === String ? "DENSITY_UNSPECIFIED" : 0; + object.multikey = false; + object.shardCount = 0; } if (message.name != null && message.hasOwnProperty("name")) object.name = message.name; @@ -2383,6 +2523,12 @@ object.state = options.enums === String ? $root.google.firestore.admin.v1.Index.State[message.state] === undefined ? message.state : $root.google.firestore.admin.v1.Index.State[message.state] : message.state; if (message.apiScope != null && message.hasOwnProperty("apiScope")) object.apiScope = options.enums === String ? $root.google.firestore.admin.v1.Index.ApiScope[message.apiScope] === undefined ? message.apiScope : $root.google.firestore.admin.v1.Index.ApiScope[message.apiScope] : message.apiScope; + if (message.density != null && message.hasOwnProperty("density")) + object.density = options.enums === String ? $root.google.firestore.admin.v1.Index.Density[message.density] === undefined ? message.density : $root.google.firestore.admin.v1.Index.Density[message.density] : message.density; + if (message.multikey != null && message.hasOwnProperty("multikey")) + object.multikey = message.multikey; + if (message.shardCount != null && message.hasOwnProperty("shardCount")) + object.shardCount = message.shardCount; return object; }; @@ -2436,11 +2582,13 @@ * @enum {string} * @property {string} ANY_API=ANY_API ANY_API value * @property {string} DATASTORE_MODE_API=DATASTORE_MODE_API DATASTORE_MODE_API value + * @property {string} MONGODB_COMPATIBLE_API=MONGODB_COMPATIBLE_API MONGODB_COMPATIBLE_API value */ Index.ApiScope = (function() { var valuesById = {}, values = Object.create(valuesById); values[valuesById[0] = "ANY_API"] = "ANY_API"; values[valuesById[1] = "DATASTORE_MODE_API"] = "DATASTORE_MODE_API"; + values[valuesById[2] = "MONGODB_COMPATIBLE_API"] = "MONGODB_COMPATIBLE_API"; return values; })(); @@ -2897,6 +3045,24 @@ return values; })(); + /** + * Density enum. + * @name google.firestore.admin.v1.Index.Density + * @enum {string} + * @property {string} DENSITY_UNSPECIFIED=DENSITY_UNSPECIFIED DENSITY_UNSPECIFIED value + * @property {string} SPARSE_ALL=SPARSE_ALL SPARSE_ALL value + * @property {string} SPARSE_ANY=SPARSE_ANY SPARSE_ANY value + * @property {string} DENSE=DENSE DENSE value + */ + Index.Density = (function() { + var valuesById = {}, values = Object.create(valuesById); + values[valuesById[0] = "DENSITY_UNSPECIFIED"] = "DENSITY_UNSPECIFIED"; + values[valuesById[1] = "SPARSE_ALL"] = "SPARSE_ALL"; + values[valuesById[2] = "SPARSE_ANY"] = "SPARSE_ANY"; + values[valuesById[3] = "DENSE"] = "DENSE"; + return values; + })(); + return Index; })(); @@ -3413,6 +3579,237 @@ * @variation 2 */ + /** + * Callback as used by {@link google.firestore.admin.v1.FirestoreAdmin#createUserCreds}. + * @memberof google.firestore.admin.v1.FirestoreAdmin + * @typedef CreateUserCredsCallback + * @type {function} + * @param {Error|null} error Error, if any + * @param {google.firestore.admin.v1.UserCreds} [response] UserCreds + */ + + /** + * Calls CreateUserCreds. + * @function createUserCreds + * @memberof google.firestore.admin.v1.FirestoreAdmin + * @instance + * @param {google.firestore.admin.v1.ICreateUserCredsRequest} request CreateUserCredsRequest message or plain object + * @param {google.firestore.admin.v1.FirestoreAdmin.CreateUserCredsCallback} callback Node-style callback called with the error, if any, and UserCreds + * @returns {undefined} + * @variation 1 + */ + Object.defineProperty(FirestoreAdmin.prototype.createUserCreds = function createUserCreds(request, callback) { + return this.rpcCall(createUserCreds, $root.google.firestore.admin.v1.CreateUserCredsRequest, $root.google.firestore.admin.v1.UserCreds, request, callback); + }, "name", { value: "CreateUserCreds" }); + + /** + * Calls CreateUserCreds. + * @function createUserCreds + * @memberof google.firestore.admin.v1.FirestoreAdmin + * @instance + * @param {google.firestore.admin.v1.ICreateUserCredsRequest} request CreateUserCredsRequest message or plain object + * @returns {Promise} Promise + * @variation 2 + */ + + /** + * Callback as used by {@link google.firestore.admin.v1.FirestoreAdmin#getUserCreds}. + * @memberof google.firestore.admin.v1.FirestoreAdmin + * @typedef GetUserCredsCallback + * @type {function} + * @param {Error|null} error Error, if any + * @param {google.firestore.admin.v1.UserCreds} [response] UserCreds + */ + + /** + * Calls GetUserCreds. + * @function getUserCreds + * @memberof google.firestore.admin.v1.FirestoreAdmin + * @instance + * @param {google.firestore.admin.v1.IGetUserCredsRequest} request GetUserCredsRequest message or plain object + * @param {google.firestore.admin.v1.FirestoreAdmin.GetUserCredsCallback} callback Node-style callback called with the error, if any, and UserCreds + * @returns {undefined} + * @variation 1 + */ + Object.defineProperty(FirestoreAdmin.prototype.getUserCreds = function getUserCreds(request, callback) { + return this.rpcCall(getUserCreds, $root.google.firestore.admin.v1.GetUserCredsRequest, $root.google.firestore.admin.v1.UserCreds, request, callback); + }, "name", { value: "GetUserCreds" }); + + /** + * Calls GetUserCreds. + * @function getUserCreds + * @memberof google.firestore.admin.v1.FirestoreAdmin + * @instance + * @param {google.firestore.admin.v1.IGetUserCredsRequest} request GetUserCredsRequest message or plain object + * @returns {Promise} Promise + * @variation 2 + */ + + /** + * Callback as used by {@link google.firestore.admin.v1.FirestoreAdmin#listUserCreds}. + * @memberof google.firestore.admin.v1.FirestoreAdmin + * @typedef ListUserCredsCallback + * @type {function} + * @param {Error|null} error Error, if any + * @param {google.firestore.admin.v1.ListUserCredsResponse} [response] ListUserCredsResponse + */ + + /** + * Calls ListUserCreds. + * @function listUserCreds + * @memberof google.firestore.admin.v1.FirestoreAdmin + * @instance + * @param {google.firestore.admin.v1.IListUserCredsRequest} request ListUserCredsRequest message or plain object + * @param {google.firestore.admin.v1.FirestoreAdmin.ListUserCredsCallback} callback Node-style callback called with the error, if any, and ListUserCredsResponse + * @returns {undefined} + * @variation 1 + */ + Object.defineProperty(FirestoreAdmin.prototype.listUserCreds = function listUserCreds(request, callback) { + return this.rpcCall(listUserCreds, $root.google.firestore.admin.v1.ListUserCredsRequest, $root.google.firestore.admin.v1.ListUserCredsResponse, request, callback); + }, "name", { value: "ListUserCreds" }); + + /** + * Calls ListUserCreds. + * @function listUserCreds + * @memberof google.firestore.admin.v1.FirestoreAdmin + * @instance + * @param {google.firestore.admin.v1.IListUserCredsRequest} request ListUserCredsRequest message or plain object + * @returns {Promise} Promise + * @variation 2 + */ + + /** + * Callback as used by {@link google.firestore.admin.v1.FirestoreAdmin#enableUserCreds}. + * @memberof google.firestore.admin.v1.FirestoreAdmin + * @typedef EnableUserCredsCallback + * @type {function} + * @param {Error|null} error Error, if any + * @param {google.firestore.admin.v1.UserCreds} [response] UserCreds + */ + + /** + * Calls EnableUserCreds. + * @function enableUserCreds + * @memberof google.firestore.admin.v1.FirestoreAdmin + * @instance + * @param {google.firestore.admin.v1.IEnableUserCredsRequest} request EnableUserCredsRequest message or plain object + * @param {google.firestore.admin.v1.FirestoreAdmin.EnableUserCredsCallback} callback Node-style callback called with the error, if any, and UserCreds + * @returns {undefined} + * @variation 1 + */ + Object.defineProperty(FirestoreAdmin.prototype.enableUserCreds = function enableUserCreds(request, callback) { + return this.rpcCall(enableUserCreds, $root.google.firestore.admin.v1.EnableUserCredsRequest, $root.google.firestore.admin.v1.UserCreds, request, callback); + }, "name", { value: "EnableUserCreds" }); + + /** + * Calls EnableUserCreds. + * @function enableUserCreds + * @memberof google.firestore.admin.v1.FirestoreAdmin + * @instance + * @param {google.firestore.admin.v1.IEnableUserCredsRequest} request EnableUserCredsRequest message or plain object + * @returns {Promise} Promise + * @variation 2 + */ + + /** + * Callback as used by {@link google.firestore.admin.v1.FirestoreAdmin#disableUserCreds}. + * @memberof google.firestore.admin.v1.FirestoreAdmin + * @typedef DisableUserCredsCallback + * @type {function} + * @param {Error|null} error Error, if any + * @param {google.firestore.admin.v1.UserCreds} [response] UserCreds + */ + + /** + * Calls DisableUserCreds. + * @function disableUserCreds + * @memberof google.firestore.admin.v1.FirestoreAdmin + * @instance + * @param {google.firestore.admin.v1.IDisableUserCredsRequest} request DisableUserCredsRequest message or plain object + * @param {google.firestore.admin.v1.FirestoreAdmin.DisableUserCredsCallback} callback Node-style callback called with the error, if any, and UserCreds + * @returns {undefined} + * @variation 1 + */ + Object.defineProperty(FirestoreAdmin.prototype.disableUserCreds = function disableUserCreds(request, callback) { + return this.rpcCall(disableUserCreds, $root.google.firestore.admin.v1.DisableUserCredsRequest, $root.google.firestore.admin.v1.UserCreds, request, callback); + }, "name", { value: "DisableUserCreds" }); + + /** + * Calls DisableUserCreds. + * @function disableUserCreds + * @memberof google.firestore.admin.v1.FirestoreAdmin + * @instance + * @param {google.firestore.admin.v1.IDisableUserCredsRequest} request DisableUserCredsRequest message or plain object + * @returns {Promise} Promise + * @variation 2 + */ + + /** + * Callback as used by {@link google.firestore.admin.v1.FirestoreAdmin#resetUserPassword}. + * @memberof google.firestore.admin.v1.FirestoreAdmin + * @typedef ResetUserPasswordCallback + * @type {function} + * @param {Error|null} error Error, if any + * @param {google.firestore.admin.v1.UserCreds} [response] UserCreds + */ + + /** + * Calls ResetUserPassword. + * @function resetUserPassword + * @memberof google.firestore.admin.v1.FirestoreAdmin + * @instance + * @param {google.firestore.admin.v1.IResetUserPasswordRequest} request ResetUserPasswordRequest message or plain object + * @param {google.firestore.admin.v1.FirestoreAdmin.ResetUserPasswordCallback} callback Node-style callback called with the error, if any, and UserCreds + * @returns {undefined} + * @variation 1 + */ + Object.defineProperty(FirestoreAdmin.prototype.resetUserPassword = function resetUserPassword(request, callback) { + return this.rpcCall(resetUserPassword, $root.google.firestore.admin.v1.ResetUserPasswordRequest, $root.google.firestore.admin.v1.UserCreds, request, callback); + }, "name", { value: "ResetUserPassword" }); + + /** + * Calls ResetUserPassword. + * @function resetUserPassword + * @memberof google.firestore.admin.v1.FirestoreAdmin + * @instance + * @param {google.firestore.admin.v1.IResetUserPasswordRequest} request ResetUserPasswordRequest message or plain object + * @returns {Promise} Promise + * @variation 2 + */ + + /** + * Callback as used by {@link google.firestore.admin.v1.FirestoreAdmin#deleteUserCreds}. + * @memberof google.firestore.admin.v1.FirestoreAdmin + * @typedef DeleteUserCredsCallback + * @type {function} + * @param {Error|null} error Error, if any + * @param {google.protobuf.Empty} [response] Empty + */ + + /** + * Calls DeleteUserCreds. + * @function deleteUserCreds + * @memberof google.firestore.admin.v1.FirestoreAdmin + * @instance + * @param {google.firestore.admin.v1.IDeleteUserCredsRequest} request DeleteUserCredsRequest message or plain object + * @param {google.firestore.admin.v1.FirestoreAdmin.DeleteUserCredsCallback} callback Node-style callback called with the error, if any, and Empty + * @returns {undefined} + * @variation 1 + */ + Object.defineProperty(FirestoreAdmin.prototype.deleteUserCreds = function deleteUserCreds(request, callback) { + return this.rpcCall(deleteUserCreds, $root.google.firestore.admin.v1.DeleteUserCredsRequest, $root.google.protobuf.Empty, request, callback); + }, "name", { value: "DeleteUserCreds" }); + + /** + * Calls DeleteUserCreds. + * @function deleteUserCreds + * @memberof google.firestore.admin.v1.FirestoreAdmin + * @instance + * @param {google.firestore.admin.v1.IDeleteUserCredsRequest} request DeleteUserCredsRequest message or plain object + * @returns {Promise} Promise + * @variation 2 + */ + /** * Callback as used by {@link google.firestore.admin.v1.FirestoreAdmin#getBackup}. * @memberof google.firestore.admin.v1.FirestoreAdmin @@ -4592,9 +4989,819 @@ * @classdesc Represents a DeleteDatabaseMetadata. * @implements IDeleteDatabaseMetadata * @constructor - * @param {google.firestore.admin.v1.IDeleteDatabaseMetadata=} [properties] Properties to set + * @param {google.firestore.admin.v1.IDeleteDatabaseMetadata=} [properties] Properties to set + */ + function DeleteDatabaseMetadata(properties) { + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } + + /** + * Creates a DeleteDatabaseMetadata message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.firestore.admin.v1.DeleteDatabaseMetadata + * @static + * @param {Object.} object Plain object + * @returns {google.firestore.admin.v1.DeleteDatabaseMetadata} DeleteDatabaseMetadata + */ + DeleteDatabaseMetadata.fromObject = function fromObject(object) { + if (object instanceof $root.google.firestore.admin.v1.DeleteDatabaseMetadata) + return object; + return new $root.google.firestore.admin.v1.DeleteDatabaseMetadata(); + }; + + /** + * Creates a plain object from a DeleteDatabaseMetadata message. Also converts values to other types if specified. + * @function toObject + * @memberof google.firestore.admin.v1.DeleteDatabaseMetadata + * @static + * @param {google.firestore.admin.v1.DeleteDatabaseMetadata} message DeleteDatabaseMetadata + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + DeleteDatabaseMetadata.toObject = function toObject() { + return {}; + }; + + /** + * Converts this DeleteDatabaseMetadata to JSON. + * @function toJSON + * @memberof google.firestore.admin.v1.DeleteDatabaseMetadata + * @instance + * @returns {Object.} JSON object + */ + DeleteDatabaseMetadata.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + + /** + * Gets the default type url for DeleteDatabaseMetadata + * @function getTypeUrl + * @memberof google.firestore.admin.v1.DeleteDatabaseMetadata + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + DeleteDatabaseMetadata.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.firestore.admin.v1.DeleteDatabaseMetadata"; + }; + + return DeleteDatabaseMetadata; + })(); + + v1.CreateUserCredsRequest = (function() { + + /** + * Properties of a CreateUserCredsRequest. + * @memberof google.firestore.admin.v1 + * @interface ICreateUserCredsRequest + * @property {string|null} [parent] CreateUserCredsRequest parent + * @property {google.firestore.admin.v1.IUserCreds|null} [userCreds] CreateUserCredsRequest userCreds + * @property {string|null} [userCredsId] CreateUserCredsRequest userCredsId + */ + + /** + * Constructs a new CreateUserCredsRequest. + * @memberof google.firestore.admin.v1 + * @classdesc Represents a CreateUserCredsRequest. + * @implements ICreateUserCredsRequest + * @constructor + * @param {google.firestore.admin.v1.ICreateUserCredsRequest=} [properties] Properties to set + */ + function CreateUserCredsRequest(properties) { + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } + + /** + * CreateUserCredsRequest parent. + * @member {string} parent + * @memberof google.firestore.admin.v1.CreateUserCredsRequest + * @instance + */ + CreateUserCredsRequest.prototype.parent = ""; + + /** + * CreateUserCredsRequest userCreds. + * @member {google.firestore.admin.v1.IUserCreds|null|undefined} userCreds + * @memberof google.firestore.admin.v1.CreateUserCredsRequest + * @instance + */ + CreateUserCredsRequest.prototype.userCreds = null; + + /** + * CreateUserCredsRequest userCredsId. + * @member {string} userCredsId + * @memberof google.firestore.admin.v1.CreateUserCredsRequest + * @instance + */ + CreateUserCredsRequest.prototype.userCredsId = ""; + + /** + * Creates a CreateUserCredsRequest message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.firestore.admin.v1.CreateUserCredsRequest + * @static + * @param {Object.} object Plain object + * @returns {google.firestore.admin.v1.CreateUserCredsRequest} CreateUserCredsRequest + */ + CreateUserCredsRequest.fromObject = function fromObject(object) { + if (object instanceof $root.google.firestore.admin.v1.CreateUserCredsRequest) + return object; + var message = new $root.google.firestore.admin.v1.CreateUserCredsRequest(); + if (object.parent != null) + message.parent = String(object.parent); + if (object.userCreds != null) { + if (typeof object.userCreds !== "object") + throw TypeError(".google.firestore.admin.v1.CreateUserCredsRequest.userCreds: object expected"); + message.userCreds = $root.google.firestore.admin.v1.UserCreds.fromObject(object.userCreds); + } + if (object.userCredsId != null) + message.userCredsId = String(object.userCredsId); + return message; + }; + + /** + * Creates a plain object from a CreateUserCredsRequest message. Also converts values to other types if specified. + * @function toObject + * @memberof google.firestore.admin.v1.CreateUserCredsRequest + * @static + * @param {google.firestore.admin.v1.CreateUserCredsRequest} message CreateUserCredsRequest + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + CreateUserCredsRequest.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.defaults) { + object.parent = ""; + object.userCreds = null; + object.userCredsId = ""; + } + if (message.parent != null && message.hasOwnProperty("parent")) + object.parent = message.parent; + if (message.userCreds != null && message.hasOwnProperty("userCreds")) + object.userCreds = $root.google.firestore.admin.v1.UserCreds.toObject(message.userCreds, options); + if (message.userCredsId != null && message.hasOwnProperty("userCredsId")) + object.userCredsId = message.userCredsId; + return object; + }; + + /** + * Converts this CreateUserCredsRequest to JSON. + * @function toJSON + * @memberof google.firestore.admin.v1.CreateUserCredsRequest + * @instance + * @returns {Object.} JSON object + */ + CreateUserCredsRequest.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + + /** + * Gets the default type url for CreateUserCredsRequest + * @function getTypeUrl + * @memberof google.firestore.admin.v1.CreateUserCredsRequest + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + CreateUserCredsRequest.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.firestore.admin.v1.CreateUserCredsRequest"; + }; + + return CreateUserCredsRequest; + })(); + + v1.GetUserCredsRequest = (function() { + + /** + * Properties of a GetUserCredsRequest. + * @memberof google.firestore.admin.v1 + * @interface IGetUserCredsRequest + * @property {string|null} [name] GetUserCredsRequest name + */ + + /** + * Constructs a new GetUserCredsRequest. + * @memberof google.firestore.admin.v1 + * @classdesc Represents a GetUserCredsRequest. + * @implements IGetUserCredsRequest + * @constructor + * @param {google.firestore.admin.v1.IGetUserCredsRequest=} [properties] Properties to set + */ + function GetUserCredsRequest(properties) { + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } + + /** + * GetUserCredsRequest name. + * @member {string} name + * @memberof google.firestore.admin.v1.GetUserCredsRequest + * @instance + */ + GetUserCredsRequest.prototype.name = ""; + + /** + * Creates a GetUserCredsRequest message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.firestore.admin.v1.GetUserCredsRequest + * @static + * @param {Object.} object Plain object + * @returns {google.firestore.admin.v1.GetUserCredsRequest} GetUserCredsRequest + */ + GetUserCredsRequest.fromObject = function fromObject(object) { + if (object instanceof $root.google.firestore.admin.v1.GetUserCredsRequest) + return object; + var message = new $root.google.firestore.admin.v1.GetUserCredsRequest(); + if (object.name != null) + message.name = String(object.name); + return message; + }; + + /** + * Creates a plain object from a GetUserCredsRequest message. Also converts values to other types if specified. + * @function toObject + * @memberof google.firestore.admin.v1.GetUserCredsRequest + * @static + * @param {google.firestore.admin.v1.GetUserCredsRequest} message GetUserCredsRequest + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + GetUserCredsRequest.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.defaults) + object.name = ""; + if (message.name != null && message.hasOwnProperty("name")) + object.name = message.name; + return object; + }; + + /** + * Converts this GetUserCredsRequest to JSON. + * @function toJSON + * @memberof google.firestore.admin.v1.GetUserCredsRequest + * @instance + * @returns {Object.} JSON object + */ + GetUserCredsRequest.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + + /** + * Gets the default type url for GetUserCredsRequest + * @function getTypeUrl + * @memberof google.firestore.admin.v1.GetUserCredsRequest + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + GetUserCredsRequest.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.firestore.admin.v1.GetUserCredsRequest"; + }; + + return GetUserCredsRequest; + })(); + + v1.ListUserCredsRequest = (function() { + + /** + * Properties of a ListUserCredsRequest. + * @memberof google.firestore.admin.v1 + * @interface IListUserCredsRequest + * @property {string|null} [parent] ListUserCredsRequest parent + */ + + /** + * Constructs a new ListUserCredsRequest. + * @memberof google.firestore.admin.v1 + * @classdesc Represents a ListUserCredsRequest. + * @implements IListUserCredsRequest + * @constructor + * @param {google.firestore.admin.v1.IListUserCredsRequest=} [properties] Properties to set + */ + function ListUserCredsRequest(properties) { + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } + + /** + * ListUserCredsRequest parent. + * @member {string} parent + * @memberof google.firestore.admin.v1.ListUserCredsRequest + * @instance + */ + ListUserCredsRequest.prototype.parent = ""; + + /** + * Creates a ListUserCredsRequest message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.firestore.admin.v1.ListUserCredsRequest + * @static + * @param {Object.} object Plain object + * @returns {google.firestore.admin.v1.ListUserCredsRequest} ListUserCredsRequest + */ + ListUserCredsRequest.fromObject = function fromObject(object) { + if (object instanceof $root.google.firestore.admin.v1.ListUserCredsRequest) + return object; + var message = new $root.google.firestore.admin.v1.ListUserCredsRequest(); + if (object.parent != null) + message.parent = String(object.parent); + return message; + }; + + /** + * Creates a plain object from a ListUserCredsRequest message. Also converts values to other types if specified. + * @function toObject + * @memberof google.firestore.admin.v1.ListUserCredsRequest + * @static + * @param {google.firestore.admin.v1.ListUserCredsRequest} message ListUserCredsRequest + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + ListUserCredsRequest.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.defaults) + object.parent = ""; + if (message.parent != null && message.hasOwnProperty("parent")) + object.parent = message.parent; + return object; + }; + + /** + * Converts this ListUserCredsRequest to JSON. + * @function toJSON + * @memberof google.firestore.admin.v1.ListUserCredsRequest + * @instance + * @returns {Object.} JSON object + */ + ListUserCredsRequest.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + + /** + * Gets the default type url for ListUserCredsRequest + * @function getTypeUrl + * @memberof google.firestore.admin.v1.ListUserCredsRequest + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + ListUserCredsRequest.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.firestore.admin.v1.ListUserCredsRequest"; + }; + + return ListUserCredsRequest; + })(); + + v1.ListUserCredsResponse = (function() { + + /** + * Properties of a ListUserCredsResponse. + * @memberof google.firestore.admin.v1 + * @interface IListUserCredsResponse + * @property {Array.|null} [userCreds] ListUserCredsResponse userCreds + */ + + /** + * Constructs a new ListUserCredsResponse. + * @memberof google.firestore.admin.v1 + * @classdesc Represents a ListUserCredsResponse. + * @implements IListUserCredsResponse + * @constructor + * @param {google.firestore.admin.v1.IListUserCredsResponse=} [properties] Properties to set + */ + function ListUserCredsResponse(properties) { + this.userCreds = []; + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } + + /** + * ListUserCredsResponse userCreds. + * @member {Array.} userCreds + * @memberof google.firestore.admin.v1.ListUserCredsResponse + * @instance + */ + ListUserCredsResponse.prototype.userCreds = $util.emptyArray; + + /** + * Creates a ListUserCredsResponse message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.firestore.admin.v1.ListUserCredsResponse + * @static + * @param {Object.} object Plain object + * @returns {google.firestore.admin.v1.ListUserCredsResponse} ListUserCredsResponse + */ + ListUserCredsResponse.fromObject = function fromObject(object) { + if (object instanceof $root.google.firestore.admin.v1.ListUserCredsResponse) + return object; + var message = new $root.google.firestore.admin.v1.ListUserCredsResponse(); + if (object.userCreds) { + if (!Array.isArray(object.userCreds)) + throw TypeError(".google.firestore.admin.v1.ListUserCredsResponse.userCreds: array expected"); + message.userCreds = []; + for (var i = 0; i < object.userCreds.length; ++i) { + if (typeof object.userCreds[i] !== "object") + throw TypeError(".google.firestore.admin.v1.ListUserCredsResponse.userCreds: object expected"); + message.userCreds[i] = $root.google.firestore.admin.v1.UserCreds.fromObject(object.userCreds[i]); + } + } + return message; + }; + + /** + * Creates a plain object from a ListUserCredsResponse message. Also converts values to other types if specified. + * @function toObject + * @memberof google.firestore.admin.v1.ListUserCredsResponse + * @static + * @param {google.firestore.admin.v1.ListUserCredsResponse} message ListUserCredsResponse + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + ListUserCredsResponse.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.arrays || options.defaults) + object.userCreds = []; + if (message.userCreds && message.userCreds.length) { + object.userCreds = []; + for (var j = 0; j < message.userCreds.length; ++j) + object.userCreds[j] = $root.google.firestore.admin.v1.UserCreds.toObject(message.userCreds[j], options); + } + return object; + }; + + /** + * Converts this ListUserCredsResponse to JSON. + * @function toJSON + * @memberof google.firestore.admin.v1.ListUserCredsResponse + * @instance + * @returns {Object.} JSON object + */ + ListUserCredsResponse.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + + /** + * Gets the default type url for ListUserCredsResponse + * @function getTypeUrl + * @memberof google.firestore.admin.v1.ListUserCredsResponse + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + ListUserCredsResponse.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.firestore.admin.v1.ListUserCredsResponse"; + }; + + return ListUserCredsResponse; + })(); + + v1.EnableUserCredsRequest = (function() { + + /** + * Properties of an EnableUserCredsRequest. + * @memberof google.firestore.admin.v1 + * @interface IEnableUserCredsRequest + * @property {string|null} [name] EnableUserCredsRequest name + */ + + /** + * Constructs a new EnableUserCredsRequest. + * @memberof google.firestore.admin.v1 + * @classdesc Represents an EnableUserCredsRequest. + * @implements IEnableUserCredsRequest + * @constructor + * @param {google.firestore.admin.v1.IEnableUserCredsRequest=} [properties] Properties to set + */ + function EnableUserCredsRequest(properties) { + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } + + /** + * EnableUserCredsRequest name. + * @member {string} name + * @memberof google.firestore.admin.v1.EnableUserCredsRequest + * @instance + */ + EnableUserCredsRequest.prototype.name = ""; + + /** + * Creates an EnableUserCredsRequest message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.firestore.admin.v1.EnableUserCredsRequest + * @static + * @param {Object.} object Plain object + * @returns {google.firestore.admin.v1.EnableUserCredsRequest} EnableUserCredsRequest + */ + EnableUserCredsRequest.fromObject = function fromObject(object) { + if (object instanceof $root.google.firestore.admin.v1.EnableUserCredsRequest) + return object; + var message = new $root.google.firestore.admin.v1.EnableUserCredsRequest(); + if (object.name != null) + message.name = String(object.name); + return message; + }; + + /** + * Creates a plain object from an EnableUserCredsRequest message. Also converts values to other types if specified. + * @function toObject + * @memberof google.firestore.admin.v1.EnableUserCredsRequest + * @static + * @param {google.firestore.admin.v1.EnableUserCredsRequest} message EnableUserCredsRequest + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + EnableUserCredsRequest.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.defaults) + object.name = ""; + if (message.name != null && message.hasOwnProperty("name")) + object.name = message.name; + return object; + }; + + /** + * Converts this EnableUserCredsRequest to JSON. + * @function toJSON + * @memberof google.firestore.admin.v1.EnableUserCredsRequest + * @instance + * @returns {Object.} JSON object + */ + EnableUserCredsRequest.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + + /** + * Gets the default type url for EnableUserCredsRequest + * @function getTypeUrl + * @memberof google.firestore.admin.v1.EnableUserCredsRequest + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + EnableUserCredsRequest.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.firestore.admin.v1.EnableUserCredsRequest"; + }; + + return EnableUserCredsRequest; + })(); + + v1.DisableUserCredsRequest = (function() { + + /** + * Properties of a DisableUserCredsRequest. + * @memberof google.firestore.admin.v1 + * @interface IDisableUserCredsRequest + * @property {string|null} [name] DisableUserCredsRequest name + */ + + /** + * Constructs a new DisableUserCredsRequest. + * @memberof google.firestore.admin.v1 + * @classdesc Represents a DisableUserCredsRequest. + * @implements IDisableUserCredsRequest + * @constructor + * @param {google.firestore.admin.v1.IDisableUserCredsRequest=} [properties] Properties to set + */ + function DisableUserCredsRequest(properties) { + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } + + /** + * DisableUserCredsRequest name. + * @member {string} name + * @memberof google.firestore.admin.v1.DisableUserCredsRequest + * @instance + */ + DisableUserCredsRequest.prototype.name = ""; + + /** + * Creates a DisableUserCredsRequest message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.firestore.admin.v1.DisableUserCredsRequest + * @static + * @param {Object.} object Plain object + * @returns {google.firestore.admin.v1.DisableUserCredsRequest} DisableUserCredsRequest + */ + DisableUserCredsRequest.fromObject = function fromObject(object) { + if (object instanceof $root.google.firestore.admin.v1.DisableUserCredsRequest) + return object; + var message = new $root.google.firestore.admin.v1.DisableUserCredsRequest(); + if (object.name != null) + message.name = String(object.name); + return message; + }; + + /** + * Creates a plain object from a DisableUserCredsRequest message. Also converts values to other types if specified. + * @function toObject + * @memberof google.firestore.admin.v1.DisableUserCredsRequest + * @static + * @param {google.firestore.admin.v1.DisableUserCredsRequest} message DisableUserCredsRequest + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + DisableUserCredsRequest.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.defaults) + object.name = ""; + if (message.name != null && message.hasOwnProperty("name")) + object.name = message.name; + return object; + }; + + /** + * Converts this DisableUserCredsRequest to JSON. + * @function toJSON + * @memberof google.firestore.admin.v1.DisableUserCredsRequest + * @instance + * @returns {Object.} JSON object + */ + DisableUserCredsRequest.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + + /** + * Gets the default type url for DisableUserCredsRequest + * @function getTypeUrl + * @memberof google.firestore.admin.v1.DisableUserCredsRequest + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + DisableUserCredsRequest.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.firestore.admin.v1.DisableUserCredsRequest"; + }; + + return DisableUserCredsRequest; + })(); + + v1.ResetUserPasswordRequest = (function() { + + /** + * Properties of a ResetUserPasswordRequest. + * @memberof google.firestore.admin.v1 + * @interface IResetUserPasswordRequest + * @property {string|null} [name] ResetUserPasswordRequest name + */ + + /** + * Constructs a new ResetUserPasswordRequest. + * @memberof google.firestore.admin.v1 + * @classdesc Represents a ResetUserPasswordRequest. + * @implements IResetUserPasswordRequest + * @constructor + * @param {google.firestore.admin.v1.IResetUserPasswordRequest=} [properties] Properties to set + */ + function ResetUserPasswordRequest(properties) { + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } + + /** + * ResetUserPasswordRequest name. + * @member {string} name + * @memberof google.firestore.admin.v1.ResetUserPasswordRequest + * @instance + */ + ResetUserPasswordRequest.prototype.name = ""; + + /** + * Creates a ResetUserPasswordRequest message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.firestore.admin.v1.ResetUserPasswordRequest + * @static + * @param {Object.} object Plain object + * @returns {google.firestore.admin.v1.ResetUserPasswordRequest} ResetUserPasswordRequest + */ + ResetUserPasswordRequest.fromObject = function fromObject(object) { + if (object instanceof $root.google.firestore.admin.v1.ResetUserPasswordRequest) + return object; + var message = new $root.google.firestore.admin.v1.ResetUserPasswordRequest(); + if (object.name != null) + message.name = String(object.name); + return message; + }; + + /** + * Creates a plain object from a ResetUserPasswordRequest message. Also converts values to other types if specified. + * @function toObject + * @memberof google.firestore.admin.v1.ResetUserPasswordRequest + * @static + * @param {google.firestore.admin.v1.ResetUserPasswordRequest} message ResetUserPasswordRequest + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + ResetUserPasswordRequest.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.defaults) + object.name = ""; + if (message.name != null && message.hasOwnProperty("name")) + object.name = message.name; + return object; + }; + + /** + * Converts this ResetUserPasswordRequest to JSON. + * @function toJSON + * @memberof google.firestore.admin.v1.ResetUserPasswordRequest + * @instance + * @returns {Object.} JSON object + */ + ResetUserPasswordRequest.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + + /** + * Gets the default type url for ResetUserPasswordRequest + * @function getTypeUrl + * @memberof google.firestore.admin.v1.ResetUserPasswordRequest + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + ResetUserPasswordRequest.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.firestore.admin.v1.ResetUserPasswordRequest"; + }; + + return ResetUserPasswordRequest; + })(); + + v1.DeleteUserCredsRequest = (function() { + + /** + * Properties of a DeleteUserCredsRequest. + * @memberof google.firestore.admin.v1 + * @interface IDeleteUserCredsRequest + * @property {string|null} [name] DeleteUserCredsRequest name + */ + + /** + * Constructs a new DeleteUserCredsRequest. + * @memberof google.firestore.admin.v1 + * @classdesc Represents a DeleteUserCredsRequest. + * @implements IDeleteUserCredsRequest + * @constructor + * @param {google.firestore.admin.v1.IDeleteUserCredsRequest=} [properties] Properties to set */ - function DeleteDatabaseMetadata(properties) { + function DeleteUserCredsRequest(properties) { if (properties) for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) if (properties[keys[i]] != null) @@ -4602,59 +5809,77 @@ } /** - * Creates a DeleteDatabaseMetadata message from a plain object. Also converts values to their respective internal types. + * DeleteUserCredsRequest name. + * @member {string} name + * @memberof google.firestore.admin.v1.DeleteUserCredsRequest + * @instance + */ + DeleteUserCredsRequest.prototype.name = ""; + + /** + * Creates a DeleteUserCredsRequest message from a plain object. Also converts values to their respective internal types. * @function fromObject - * @memberof google.firestore.admin.v1.DeleteDatabaseMetadata + * @memberof google.firestore.admin.v1.DeleteUserCredsRequest * @static * @param {Object.} object Plain object - * @returns {google.firestore.admin.v1.DeleteDatabaseMetadata} DeleteDatabaseMetadata + * @returns {google.firestore.admin.v1.DeleteUserCredsRequest} DeleteUserCredsRequest */ - DeleteDatabaseMetadata.fromObject = function fromObject(object) { - if (object instanceof $root.google.firestore.admin.v1.DeleteDatabaseMetadata) + DeleteUserCredsRequest.fromObject = function fromObject(object) { + if (object instanceof $root.google.firestore.admin.v1.DeleteUserCredsRequest) return object; - return new $root.google.firestore.admin.v1.DeleteDatabaseMetadata(); + var message = new $root.google.firestore.admin.v1.DeleteUserCredsRequest(); + if (object.name != null) + message.name = String(object.name); + return message; }; /** - * Creates a plain object from a DeleteDatabaseMetadata message. Also converts values to other types if specified. + * Creates a plain object from a DeleteUserCredsRequest message. Also converts values to other types if specified. * @function toObject - * @memberof google.firestore.admin.v1.DeleteDatabaseMetadata + * @memberof google.firestore.admin.v1.DeleteUserCredsRequest * @static - * @param {google.firestore.admin.v1.DeleteDatabaseMetadata} message DeleteDatabaseMetadata + * @param {google.firestore.admin.v1.DeleteUserCredsRequest} message DeleteUserCredsRequest * @param {$protobuf.IConversionOptions} [options] Conversion options * @returns {Object.} Plain object */ - DeleteDatabaseMetadata.toObject = function toObject() { - return {}; + DeleteUserCredsRequest.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.defaults) + object.name = ""; + if (message.name != null && message.hasOwnProperty("name")) + object.name = message.name; + return object; }; /** - * Converts this DeleteDatabaseMetadata to JSON. + * Converts this DeleteUserCredsRequest to JSON. * @function toJSON - * @memberof google.firestore.admin.v1.DeleteDatabaseMetadata + * @memberof google.firestore.admin.v1.DeleteUserCredsRequest * @instance * @returns {Object.} JSON object */ - DeleteDatabaseMetadata.prototype.toJSON = function toJSON() { + DeleteUserCredsRequest.prototype.toJSON = function toJSON() { return this.constructor.toObject(this, $protobuf.util.toJSONOptions); }; /** - * Gets the default type url for DeleteDatabaseMetadata + * Gets the default type url for DeleteUserCredsRequest * @function getTypeUrl - * @memberof google.firestore.admin.v1.DeleteDatabaseMetadata + * @memberof google.firestore.admin.v1.DeleteUserCredsRequest * @static * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") * @returns {string} The default type url */ - DeleteDatabaseMetadata.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + DeleteUserCredsRequest.getTypeUrl = function getTypeUrl(typeUrlPrefix) { if (typeUrlPrefix === undefined) { typeUrlPrefix = "type.googleapis.com"; } - return typeUrlPrefix + "/google.firestore.admin.v1.DeleteDatabaseMetadata"; + return typeUrlPrefix + "/google.firestore.admin.v1.DeleteUserCredsRequest"; }; - return DeleteDatabaseMetadata; + return DeleteUserCredsRequest; })(); v1.CreateBackupScheduleRequest = (function() { @@ -9973,22 +11198,348 @@ return this.constructor.toObject(this, $protobuf.util.toJSONOptions); }; - /** - * Gets the default type url for WeeklyRecurrence - * @function getTypeUrl - * @memberof google.firestore.admin.v1.WeeklyRecurrence - * @static - * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") - * @returns {string} The default type url - */ - WeeklyRecurrence.getTypeUrl = function getTypeUrl(typeUrlPrefix) { - if (typeUrlPrefix === undefined) { - typeUrlPrefix = "type.googleapis.com"; - } - return typeUrlPrefix + "/google.firestore.admin.v1.WeeklyRecurrence"; - }; + /** + * Gets the default type url for WeeklyRecurrence + * @function getTypeUrl + * @memberof google.firestore.admin.v1.WeeklyRecurrence + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + WeeklyRecurrence.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.firestore.admin.v1.WeeklyRecurrence"; + }; + + return WeeklyRecurrence; + })(); + + v1.UserCreds = (function() { + + /** + * Properties of a UserCreds. + * @memberof google.firestore.admin.v1 + * @interface IUserCreds + * @property {string|null} [name] UserCreds name + * @property {google.protobuf.ITimestamp|null} [createTime] UserCreds createTime + * @property {google.protobuf.ITimestamp|null} [updateTime] UserCreds updateTime + * @property {google.firestore.admin.v1.UserCreds.State|null} [state] UserCreds state + * @property {string|null} [securePassword] UserCreds securePassword + * @property {google.firestore.admin.v1.UserCreds.IResourceIdentity|null} [resourceIdentity] UserCreds resourceIdentity + */ + + /** + * Constructs a new UserCreds. + * @memberof google.firestore.admin.v1 + * @classdesc Represents a UserCreds. + * @implements IUserCreds + * @constructor + * @param {google.firestore.admin.v1.IUserCreds=} [properties] Properties to set + */ + function UserCreds(properties) { + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } + + /** + * UserCreds name. + * @member {string} name + * @memberof google.firestore.admin.v1.UserCreds + * @instance + */ + UserCreds.prototype.name = ""; + + /** + * UserCreds createTime. + * @member {google.protobuf.ITimestamp|null|undefined} createTime + * @memberof google.firestore.admin.v1.UserCreds + * @instance + */ + UserCreds.prototype.createTime = null; + + /** + * UserCreds updateTime. + * @member {google.protobuf.ITimestamp|null|undefined} updateTime + * @memberof google.firestore.admin.v1.UserCreds + * @instance + */ + UserCreds.prototype.updateTime = null; + + /** + * UserCreds state. + * @member {google.firestore.admin.v1.UserCreds.State} state + * @memberof google.firestore.admin.v1.UserCreds + * @instance + */ + UserCreds.prototype.state = 0; + + /** + * UserCreds securePassword. + * @member {string} securePassword + * @memberof google.firestore.admin.v1.UserCreds + * @instance + */ + UserCreds.prototype.securePassword = ""; + + /** + * UserCreds resourceIdentity. + * @member {google.firestore.admin.v1.UserCreds.IResourceIdentity|null|undefined} resourceIdentity + * @memberof google.firestore.admin.v1.UserCreds + * @instance + */ + UserCreds.prototype.resourceIdentity = null; + + // OneOf field names bound to virtual getters and setters + var $oneOfFields; + + /** + * UserCreds UserCredsIdentity. + * @member {"resourceIdentity"|undefined} UserCredsIdentity + * @memberof google.firestore.admin.v1.UserCreds + * @instance + */ + Object.defineProperty(UserCreds.prototype, "UserCredsIdentity", { + get: $util.oneOfGetter($oneOfFields = ["resourceIdentity"]), + set: $util.oneOfSetter($oneOfFields) + }); + + /** + * Creates a UserCreds message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.firestore.admin.v1.UserCreds + * @static + * @param {Object.} object Plain object + * @returns {google.firestore.admin.v1.UserCreds} UserCreds + */ + UserCreds.fromObject = function fromObject(object) { + if (object instanceof $root.google.firestore.admin.v1.UserCreds) + return object; + var message = new $root.google.firestore.admin.v1.UserCreds(); + if (object.name != null) + message.name = String(object.name); + if (object.createTime != null) { + if (typeof object.createTime !== "object") + throw TypeError(".google.firestore.admin.v1.UserCreds.createTime: object expected"); + message.createTime = $root.google.protobuf.Timestamp.fromObject(object.createTime); + } + if (object.updateTime != null) { + if (typeof object.updateTime !== "object") + throw TypeError(".google.firestore.admin.v1.UserCreds.updateTime: object expected"); + message.updateTime = $root.google.protobuf.Timestamp.fromObject(object.updateTime); + } + switch (object.state) { + default: + if (typeof object.state === "number") { + message.state = object.state; + break; + } + break; + case "STATE_UNSPECIFIED": + case 0: + message.state = 0; + break; + case "ENABLED": + case 1: + message.state = 1; + break; + case "DISABLED": + case 2: + message.state = 2; + break; + } + if (object.securePassword != null) + message.securePassword = String(object.securePassword); + if (object.resourceIdentity != null) { + if (typeof object.resourceIdentity !== "object") + throw TypeError(".google.firestore.admin.v1.UserCreds.resourceIdentity: object expected"); + message.resourceIdentity = $root.google.firestore.admin.v1.UserCreds.ResourceIdentity.fromObject(object.resourceIdentity); + } + return message; + }; + + /** + * Creates a plain object from a UserCreds message. Also converts values to other types if specified. + * @function toObject + * @memberof google.firestore.admin.v1.UserCreds + * @static + * @param {google.firestore.admin.v1.UserCreds} message UserCreds + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + UserCreds.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.defaults) { + object.name = ""; + object.createTime = null; + object.updateTime = null; + object.state = options.enums === String ? "STATE_UNSPECIFIED" : 0; + object.securePassword = ""; + } + if (message.name != null && message.hasOwnProperty("name")) + object.name = message.name; + if (message.createTime != null && message.hasOwnProperty("createTime")) + object.createTime = $root.google.protobuf.Timestamp.toObject(message.createTime, options); + if (message.updateTime != null && message.hasOwnProperty("updateTime")) + object.updateTime = $root.google.protobuf.Timestamp.toObject(message.updateTime, options); + if (message.state != null && message.hasOwnProperty("state")) + object.state = options.enums === String ? $root.google.firestore.admin.v1.UserCreds.State[message.state] === undefined ? message.state : $root.google.firestore.admin.v1.UserCreds.State[message.state] : message.state; + if (message.securePassword != null && message.hasOwnProperty("securePassword")) + object.securePassword = message.securePassword; + if (message.resourceIdentity != null && message.hasOwnProperty("resourceIdentity")) { + object.resourceIdentity = $root.google.firestore.admin.v1.UserCreds.ResourceIdentity.toObject(message.resourceIdentity, options); + if (options.oneofs) + object.UserCredsIdentity = "resourceIdentity"; + } + return object; + }; + + /** + * Converts this UserCreds to JSON. + * @function toJSON + * @memberof google.firestore.admin.v1.UserCreds + * @instance + * @returns {Object.} JSON object + */ + UserCreds.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + + /** + * Gets the default type url for UserCreds + * @function getTypeUrl + * @memberof google.firestore.admin.v1.UserCreds + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + UserCreds.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.firestore.admin.v1.UserCreds"; + }; + + /** + * State enum. + * @name google.firestore.admin.v1.UserCreds.State + * @enum {string} + * @property {string} STATE_UNSPECIFIED=STATE_UNSPECIFIED STATE_UNSPECIFIED value + * @property {string} ENABLED=ENABLED ENABLED value + * @property {string} DISABLED=DISABLED DISABLED value + */ + UserCreds.State = (function() { + var valuesById = {}, values = Object.create(valuesById); + values[valuesById[0] = "STATE_UNSPECIFIED"] = "STATE_UNSPECIFIED"; + values[valuesById[1] = "ENABLED"] = "ENABLED"; + values[valuesById[2] = "DISABLED"] = "DISABLED"; + return values; + })(); + + UserCreds.ResourceIdentity = (function() { + + /** + * Properties of a ResourceIdentity. + * @memberof google.firestore.admin.v1.UserCreds + * @interface IResourceIdentity + * @property {string|null} [principal] ResourceIdentity principal + */ + + /** + * Constructs a new ResourceIdentity. + * @memberof google.firestore.admin.v1.UserCreds + * @classdesc Represents a ResourceIdentity. + * @implements IResourceIdentity + * @constructor + * @param {google.firestore.admin.v1.UserCreds.IResourceIdentity=} [properties] Properties to set + */ + function ResourceIdentity(properties) { + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } + + /** + * ResourceIdentity principal. + * @member {string} principal + * @memberof google.firestore.admin.v1.UserCreds.ResourceIdentity + * @instance + */ + ResourceIdentity.prototype.principal = ""; + + /** + * Creates a ResourceIdentity message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.firestore.admin.v1.UserCreds.ResourceIdentity + * @static + * @param {Object.} object Plain object + * @returns {google.firestore.admin.v1.UserCreds.ResourceIdentity} ResourceIdentity + */ + ResourceIdentity.fromObject = function fromObject(object) { + if (object instanceof $root.google.firestore.admin.v1.UserCreds.ResourceIdentity) + return object; + var message = new $root.google.firestore.admin.v1.UserCreds.ResourceIdentity(); + if (object.principal != null) + message.principal = String(object.principal); + return message; + }; + + /** + * Creates a plain object from a ResourceIdentity message. Also converts values to other types if specified. + * @function toObject + * @memberof google.firestore.admin.v1.UserCreds.ResourceIdentity + * @static + * @param {google.firestore.admin.v1.UserCreds.ResourceIdentity} message ResourceIdentity + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + ResourceIdentity.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.defaults) + object.principal = ""; + if (message.principal != null && message.hasOwnProperty("principal")) + object.principal = message.principal; + return object; + }; + + /** + * Converts this ResourceIdentity to JSON. + * @function toJSON + * @memberof google.firestore.admin.v1.UserCreds.ResourceIdentity + * @instance + * @returns {Object.} JSON object + */ + ResourceIdentity.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + + /** + * Gets the default type url for ResourceIdentity + * @function getTypeUrl + * @memberof google.firestore.admin.v1.UserCreds.ResourceIdentity + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + ResourceIdentity.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.firestore.admin.v1.UserCreds.ResourceIdentity"; + }; + + return ResourceIdentity; + })(); - return WeeklyRecurrence; + return UserCreds; })(); v1.LocationMetadata = (function() { @@ -11007,7 +12558,6 @@ * @interface ICommonLanguageSettings * @property {string|null} [referenceDocsUri] CommonLanguageSettings referenceDocsUri * @property {Array.|null} [destinations] CommonLanguageSettings destinations - * @property {google.api.ISelectiveGapicGeneration|null} [selectiveGapicGeneration] CommonLanguageSettings selectiveGapicGeneration */ /** @@ -11042,14 +12592,6 @@ */ CommonLanguageSettings.prototype.destinations = $util.emptyArray; - /** - * CommonLanguageSettings selectiveGapicGeneration. - * @member {google.api.ISelectiveGapicGeneration|null|undefined} selectiveGapicGeneration - * @memberof google.api.CommonLanguageSettings - * @instance - */ - CommonLanguageSettings.prototype.selectiveGapicGeneration = null; - /** * Creates a CommonLanguageSettings message from a plain object. Also converts values to their respective internal types. * @function fromObject @@ -11089,11 +12631,6 @@ break; } } - if (object.selectiveGapicGeneration != null) { - if (typeof object.selectiveGapicGeneration !== "object") - throw TypeError(".google.api.CommonLanguageSettings.selectiveGapicGeneration: object expected"); - message.selectiveGapicGeneration = $root.google.api.SelectiveGapicGeneration.fromObject(object.selectiveGapicGeneration); - } return message; }; @@ -11112,10 +12649,8 @@ var object = {}; if (options.arrays || options.defaults) object.destinations = []; - if (options.defaults) { + if (options.defaults) object.referenceDocsUri = ""; - object.selectiveGapicGeneration = null; - } if (message.referenceDocsUri != null && message.hasOwnProperty("referenceDocsUri")) object.referenceDocsUri = message.referenceDocsUri; if (message.destinations && message.destinations.length) { @@ -11123,8 +12658,6 @@ for (var j = 0; j < message.destinations.length; ++j) object.destinations[j] = options.enums === String ? $root.google.api.ClientLibraryDestination[message.destinations[j]] === undefined ? message.destinations[j] : $root.google.api.ClientLibraryDestination[message.destinations[j]] : message.destinations[j]; } - if (message.selectiveGapicGeneration != null && message.hasOwnProperty("selectiveGapicGeneration")) - object.selectiveGapicGeneration = $root.google.api.SelectiveGapicGeneration.toObject(message.selectiveGapicGeneration, options); return object; }; @@ -12120,7 +13653,6 @@ * @memberof google.api * @interface IPythonSettings * @property {google.api.ICommonLanguageSettings|null} [common] PythonSettings common - * @property {google.api.PythonSettings.IExperimentalFeatures|null} [experimentalFeatures] PythonSettings experimentalFeatures */ /** @@ -12146,14 +13678,6 @@ */ PythonSettings.prototype.common = null; - /** - * PythonSettings experimentalFeatures. - * @member {google.api.PythonSettings.IExperimentalFeatures|null|undefined} experimentalFeatures - * @memberof google.api.PythonSettings - * @instance - */ - PythonSettings.prototype.experimentalFeatures = null; - /** * Creates a PythonSettings message from a plain object. Also converts values to their respective internal types. * @function fromObject @@ -12171,11 +13695,6 @@ throw TypeError(".google.api.PythonSettings.common: object expected"); message.common = $root.google.api.CommonLanguageSettings.fromObject(object.common); } - if (object.experimentalFeatures != null) { - if (typeof object.experimentalFeatures !== "object") - throw TypeError(".google.api.PythonSettings.experimentalFeatures: object expected"); - message.experimentalFeatures = $root.google.api.PythonSettings.ExperimentalFeatures.fromObject(object.experimentalFeatures); - } return message; }; @@ -12192,14 +13711,10 @@ if (!options) options = {}; var object = {}; - if (options.defaults) { + if (options.defaults) object.common = null; - object.experimentalFeatures = null; - } if (message.common != null && message.hasOwnProperty("common")) object.common = $root.google.api.CommonLanguageSettings.toObject(message.common, options); - if (message.experimentalFeatures != null && message.hasOwnProperty("experimentalFeatures")) - object.experimentalFeatures = $root.google.api.PythonSettings.ExperimentalFeatures.toObject(message.experimentalFeatures, options); return object; }; @@ -12229,119 +13744,6 @@ return typeUrlPrefix + "/google.api.PythonSettings"; }; - PythonSettings.ExperimentalFeatures = (function() { - - /** - * Properties of an ExperimentalFeatures. - * @memberof google.api.PythonSettings - * @interface IExperimentalFeatures - * @property {boolean|null} [restAsyncIoEnabled] ExperimentalFeatures restAsyncIoEnabled - * @property {boolean|null} [protobufPythonicTypesEnabled] ExperimentalFeatures protobufPythonicTypesEnabled - */ - - /** - * Constructs a new ExperimentalFeatures. - * @memberof google.api.PythonSettings - * @classdesc Represents an ExperimentalFeatures. - * @implements IExperimentalFeatures - * @constructor - * @param {google.api.PythonSettings.IExperimentalFeatures=} [properties] Properties to set - */ - function ExperimentalFeatures(properties) { - if (properties) - for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) - if (properties[keys[i]] != null) - this[keys[i]] = properties[keys[i]]; - } - - /** - * ExperimentalFeatures restAsyncIoEnabled. - * @member {boolean} restAsyncIoEnabled - * @memberof google.api.PythonSettings.ExperimentalFeatures - * @instance - */ - ExperimentalFeatures.prototype.restAsyncIoEnabled = false; - - /** - * ExperimentalFeatures protobufPythonicTypesEnabled. - * @member {boolean} protobufPythonicTypesEnabled - * @memberof google.api.PythonSettings.ExperimentalFeatures - * @instance - */ - ExperimentalFeatures.prototype.protobufPythonicTypesEnabled = false; - - /** - * Creates an ExperimentalFeatures message from a plain object. Also converts values to their respective internal types. - * @function fromObject - * @memberof google.api.PythonSettings.ExperimentalFeatures - * @static - * @param {Object.} object Plain object - * @returns {google.api.PythonSettings.ExperimentalFeatures} ExperimentalFeatures - */ - ExperimentalFeatures.fromObject = function fromObject(object) { - if (object instanceof $root.google.api.PythonSettings.ExperimentalFeatures) - return object; - var message = new $root.google.api.PythonSettings.ExperimentalFeatures(); - if (object.restAsyncIoEnabled != null) - message.restAsyncIoEnabled = Boolean(object.restAsyncIoEnabled); - if (object.protobufPythonicTypesEnabled != null) - message.protobufPythonicTypesEnabled = Boolean(object.protobufPythonicTypesEnabled); - return message; - }; - - /** - * Creates a plain object from an ExperimentalFeatures message. Also converts values to other types if specified. - * @function toObject - * @memberof google.api.PythonSettings.ExperimentalFeatures - * @static - * @param {google.api.PythonSettings.ExperimentalFeatures} message ExperimentalFeatures - * @param {$protobuf.IConversionOptions} [options] Conversion options - * @returns {Object.} Plain object - */ - ExperimentalFeatures.toObject = function toObject(message, options) { - if (!options) - options = {}; - var object = {}; - if (options.defaults) { - object.restAsyncIoEnabled = false; - object.protobufPythonicTypesEnabled = false; - } - if (message.restAsyncIoEnabled != null && message.hasOwnProperty("restAsyncIoEnabled")) - object.restAsyncIoEnabled = message.restAsyncIoEnabled; - if (message.protobufPythonicTypesEnabled != null && message.hasOwnProperty("protobufPythonicTypesEnabled")) - object.protobufPythonicTypesEnabled = message.protobufPythonicTypesEnabled; - return object; - }; - - /** - * Converts this ExperimentalFeatures to JSON. - * @function toJSON - * @memberof google.api.PythonSettings.ExperimentalFeatures - * @instance - * @returns {Object.} JSON object - */ - ExperimentalFeatures.prototype.toJSON = function toJSON() { - return this.constructor.toObject(this, $protobuf.util.toJSONOptions); - }; - - /** - * Gets the default type url for ExperimentalFeatures - * @function getTypeUrl - * @memberof google.api.PythonSettings.ExperimentalFeatures - * @static - * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") - * @returns {string} The default type url - */ - ExperimentalFeatures.getTypeUrl = function getTypeUrl(typeUrlPrefix) { - if (typeUrlPrefix === undefined) { - typeUrlPrefix = "type.googleapis.com"; - } - return typeUrlPrefix + "/google.api.PythonSettings.ExperimentalFeatures"; - }; - - return ExperimentalFeatures; - })(); - return PythonSettings; })(); @@ -12775,7 +14177,6 @@ * @memberof google.api * @interface IGoSettings * @property {google.api.ICommonLanguageSettings|null} [common] GoSettings common - * @property {Object.|null} [renamedServices] GoSettings renamedServices */ /** @@ -12787,7 +14188,6 @@ * @param {google.api.IGoSettings=} [properties] Properties to set */ function GoSettings(properties) { - this.renamedServices = {}; if (properties) for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) if (properties[keys[i]] != null) @@ -12802,14 +14202,6 @@ */ GoSettings.prototype.common = null; - /** - * GoSettings renamedServices. - * @member {Object.} renamedServices - * @memberof google.api.GoSettings - * @instance - */ - GoSettings.prototype.renamedServices = $util.emptyObject; - /** * Creates a GoSettings message from a plain object. Also converts values to their respective internal types. * @function fromObject @@ -12827,13 +14219,6 @@ throw TypeError(".google.api.GoSettings.common: object expected"); message.common = $root.google.api.CommonLanguageSettings.fromObject(object.common); } - if (object.renamedServices) { - if (typeof object.renamedServices !== "object") - throw TypeError(".google.api.GoSettings.renamedServices: object expected"); - message.renamedServices = {}; - for (var keys = Object.keys(object.renamedServices), i = 0; i < keys.length; ++i) - message.renamedServices[keys[i]] = String(object.renamedServices[keys[i]]); - } return message; }; @@ -12850,18 +14235,10 @@ if (!options) options = {}; var object = {}; - if (options.objects || options.defaults) - object.renamedServices = {}; if (options.defaults) object.common = null; if (message.common != null && message.hasOwnProperty("common")) object.common = $root.google.api.CommonLanguageSettings.toObject(message.common, options); - var keys2; - if (message.renamedServices && (keys2 = Object.keys(message.renamedServices)).length) { - object.renamedServices = {}; - for (var j = 0; j < keys2.length; ++j) - object.renamedServices[keys2[j]] = message.renamedServices[keys2[j]]; - } return object; }; @@ -13226,26 +14603,161 @@ return values; })(); - api.SelectiveGapicGeneration = (function() { + /** + * LaunchStage enum. + * @name google.api.LaunchStage + * @enum {string} + * @property {string} LAUNCH_STAGE_UNSPECIFIED=LAUNCH_STAGE_UNSPECIFIED LAUNCH_STAGE_UNSPECIFIED value + * @property {string} UNIMPLEMENTED=UNIMPLEMENTED UNIMPLEMENTED value + * @property {string} PRELAUNCH=PRELAUNCH PRELAUNCH value + * @property {string} EARLY_ACCESS=EARLY_ACCESS EARLY_ACCESS value + * @property {string} ALPHA=ALPHA ALPHA value + * @property {string} BETA=BETA BETA value + * @property {string} GA=GA GA value + * @property {string} DEPRECATED=DEPRECATED DEPRECATED value + */ + api.LaunchStage = (function() { + var valuesById = {}, values = Object.create(valuesById); + values[valuesById[0] = "LAUNCH_STAGE_UNSPECIFIED"] = "LAUNCH_STAGE_UNSPECIFIED"; + values[valuesById[6] = "UNIMPLEMENTED"] = "UNIMPLEMENTED"; + values[valuesById[7] = "PRELAUNCH"] = "PRELAUNCH"; + values[valuesById[1] = "EARLY_ACCESS"] = "EARLY_ACCESS"; + values[valuesById[2] = "ALPHA"] = "ALPHA"; + values[valuesById[3] = "BETA"] = "BETA"; + values[valuesById[4] = "GA"] = "GA"; + values[valuesById[5] = "DEPRECATED"] = "DEPRECATED"; + return values; + })(); + + api.RoutingRule = (function() { + + /** + * Properties of a RoutingRule. + * @memberof google.api + * @interface IRoutingRule + * @property {Array.|null} [routingParameters] RoutingRule routingParameters + */ + + /** + * Constructs a new RoutingRule. + * @memberof google.api + * @classdesc Represents a RoutingRule. + * @implements IRoutingRule + * @constructor + * @param {google.api.IRoutingRule=} [properties] Properties to set + */ + function RoutingRule(properties) { + this.routingParameters = []; + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } + + /** + * RoutingRule routingParameters. + * @member {Array.} routingParameters + * @memberof google.api.RoutingRule + * @instance + */ + RoutingRule.prototype.routingParameters = $util.emptyArray; + + /** + * Creates a RoutingRule message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.api.RoutingRule + * @static + * @param {Object.} object Plain object + * @returns {google.api.RoutingRule} RoutingRule + */ + RoutingRule.fromObject = function fromObject(object) { + if (object instanceof $root.google.api.RoutingRule) + return object; + var message = new $root.google.api.RoutingRule(); + if (object.routingParameters) { + if (!Array.isArray(object.routingParameters)) + throw TypeError(".google.api.RoutingRule.routingParameters: array expected"); + message.routingParameters = []; + for (var i = 0; i < object.routingParameters.length; ++i) { + if (typeof object.routingParameters[i] !== "object") + throw TypeError(".google.api.RoutingRule.routingParameters: object expected"); + message.routingParameters[i] = $root.google.api.RoutingParameter.fromObject(object.routingParameters[i]); + } + } + return message; + }; + + /** + * Creates a plain object from a RoutingRule message. Also converts values to other types if specified. + * @function toObject + * @memberof google.api.RoutingRule + * @static + * @param {google.api.RoutingRule} message RoutingRule + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + RoutingRule.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.arrays || options.defaults) + object.routingParameters = []; + if (message.routingParameters && message.routingParameters.length) { + object.routingParameters = []; + for (var j = 0; j < message.routingParameters.length; ++j) + object.routingParameters[j] = $root.google.api.RoutingParameter.toObject(message.routingParameters[j], options); + } + return object; + }; + + /** + * Converts this RoutingRule to JSON. + * @function toJSON + * @memberof google.api.RoutingRule + * @instance + * @returns {Object.} JSON object + */ + RoutingRule.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + + /** + * Gets the default type url for RoutingRule + * @function getTypeUrl + * @memberof google.api.RoutingRule + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + RoutingRule.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.api.RoutingRule"; + }; + + return RoutingRule; + })(); + + api.RoutingParameter = (function() { /** - * Properties of a SelectiveGapicGeneration. + * Properties of a RoutingParameter. * @memberof google.api - * @interface ISelectiveGapicGeneration - * @property {Array.|null} [methods] SelectiveGapicGeneration methods - * @property {boolean|null} [generateOmittedAsInternal] SelectiveGapicGeneration generateOmittedAsInternal + * @interface IRoutingParameter + * @property {string|null} [field] RoutingParameter field + * @property {string|null} [pathTemplate] RoutingParameter pathTemplate */ /** - * Constructs a new SelectiveGapicGeneration. + * Constructs a new RoutingParameter. * @memberof google.api - * @classdesc Represents a SelectiveGapicGeneration. - * @implements ISelectiveGapicGeneration + * @classdesc Represents a RoutingParameter. + * @implements IRoutingParameter * @constructor - * @param {google.api.ISelectiveGapicGeneration=} [properties] Properties to set + * @param {google.api.IRoutingParameter=} [properties] Properties to set */ - function SelectiveGapicGeneration(properties) { - this.methods = []; + function RoutingParameter(properties) { if (properties) for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) if (properties[keys[i]] != null) @@ -13253,125 +14765,91 @@ } /** - * SelectiveGapicGeneration methods. - * @member {Array.} methods - * @memberof google.api.SelectiveGapicGeneration + * RoutingParameter field. + * @member {string} field + * @memberof google.api.RoutingParameter * @instance */ - SelectiveGapicGeneration.prototype.methods = $util.emptyArray; + RoutingParameter.prototype.field = ""; /** - * SelectiveGapicGeneration generateOmittedAsInternal. - * @member {boolean} generateOmittedAsInternal - * @memberof google.api.SelectiveGapicGeneration + * RoutingParameter pathTemplate. + * @member {string} pathTemplate + * @memberof google.api.RoutingParameter * @instance */ - SelectiveGapicGeneration.prototype.generateOmittedAsInternal = false; + RoutingParameter.prototype.pathTemplate = ""; /** - * Creates a SelectiveGapicGeneration message from a plain object. Also converts values to their respective internal types. + * Creates a RoutingParameter message from a plain object. Also converts values to their respective internal types. * @function fromObject - * @memberof google.api.SelectiveGapicGeneration + * @memberof google.api.RoutingParameter * @static * @param {Object.} object Plain object - * @returns {google.api.SelectiveGapicGeneration} SelectiveGapicGeneration + * @returns {google.api.RoutingParameter} RoutingParameter */ - SelectiveGapicGeneration.fromObject = function fromObject(object) { - if (object instanceof $root.google.api.SelectiveGapicGeneration) + RoutingParameter.fromObject = function fromObject(object) { + if (object instanceof $root.google.api.RoutingParameter) return object; - var message = new $root.google.api.SelectiveGapicGeneration(); - if (object.methods) { - if (!Array.isArray(object.methods)) - throw TypeError(".google.api.SelectiveGapicGeneration.methods: array expected"); - message.methods = []; - for (var i = 0; i < object.methods.length; ++i) - message.methods[i] = String(object.methods[i]); - } - if (object.generateOmittedAsInternal != null) - message.generateOmittedAsInternal = Boolean(object.generateOmittedAsInternal); + var message = new $root.google.api.RoutingParameter(); + if (object.field != null) + message.field = String(object.field); + if (object.pathTemplate != null) + message.pathTemplate = String(object.pathTemplate); return message; }; /** - * Creates a plain object from a SelectiveGapicGeneration message. Also converts values to other types if specified. + * Creates a plain object from a RoutingParameter message. Also converts values to other types if specified. * @function toObject - * @memberof google.api.SelectiveGapicGeneration + * @memberof google.api.RoutingParameter * @static - * @param {google.api.SelectiveGapicGeneration} message SelectiveGapicGeneration + * @param {google.api.RoutingParameter} message RoutingParameter * @param {$protobuf.IConversionOptions} [options] Conversion options * @returns {Object.} Plain object */ - SelectiveGapicGeneration.toObject = function toObject(message, options) { + RoutingParameter.toObject = function toObject(message, options) { if (!options) options = {}; var object = {}; - if (options.arrays || options.defaults) - object.methods = []; - if (options.defaults) - object.generateOmittedAsInternal = false; - if (message.methods && message.methods.length) { - object.methods = []; - for (var j = 0; j < message.methods.length; ++j) - object.methods[j] = message.methods[j]; - } - if (message.generateOmittedAsInternal != null && message.hasOwnProperty("generateOmittedAsInternal")) - object.generateOmittedAsInternal = message.generateOmittedAsInternal; + if (options.defaults) { + object.field = ""; + object.pathTemplate = ""; + } + if (message.field != null && message.hasOwnProperty("field")) + object.field = message.field; + if (message.pathTemplate != null && message.hasOwnProperty("pathTemplate")) + object.pathTemplate = message.pathTemplate; return object; }; /** - * Converts this SelectiveGapicGeneration to JSON. + * Converts this RoutingParameter to JSON. * @function toJSON - * @memberof google.api.SelectiveGapicGeneration + * @memberof google.api.RoutingParameter * @instance * @returns {Object.} JSON object */ - SelectiveGapicGeneration.prototype.toJSON = function toJSON() { + RoutingParameter.prototype.toJSON = function toJSON() { return this.constructor.toObject(this, $protobuf.util.toJSONOptions); }; /** - * Gets the default type url for SelectiveGapicGeneration + * Gets the default type url for RoutingParameter * @function getTypeUrl - * @memberof google.api.SelectiveGapicGeneration + * @memberof google.api.RoutingParameter * @static * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") * @returns {string} The default type url */ - SelectiveGapicGeneration.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + RoutingParameter.getTypeUrl = function getTypeUrl(typeUrlPrefix) { if (typeUrlPrefix === undefined) { typeUrlPrefix = "type.googleapis.com"; } - return typeUrlPrefix + "/google.api.SelectiveGapicGeneration"; + return typeUrlPrefix + "/google.api.RoutingParameter"; }; - return SelectiveGapicGeneration; - })(); - - /** - * LaunchStage enum. - * @name google.api.LaunchStage - * @enum {string} - * @property {string} LAUNCH_STAGE_UNSPECIFIED=LAUNCH_STAGE_UNSPECIFIED LAUNCH_STAGE_UNSPECIFIED value - * @property {string} UNIMPLEMENTED=UNIMPLEMENTED UNIMPLEMENTED value - * @property {string} PRELAUNCH=PRELAUNCH PRELAUNCH value - * @property {string} EARLY_ACCESS=EARLY_ACCESS EARLY_ACCESS value - * @property {string} ALPHA=ALPHA ALPHA value - * @property {string} BETA=BETA BETA value - * @property {string} GA=GA GA value - * @property {string} DEPRECATED=DEPRECATED DEPRECATED value - */ - api.LaunchStage = (function() { - var valuesById = {}, values = Object.create(valuesById); - values[valuesById[0] = "LAUNCH_STAGE_UNSPECIFIED"] = "LAUNCH_STAGE_UNSPECIFIED"; - values[valuesById[6] = "UNIMPLEMENTED"] = "UNIMPLEMENTED"; - values[valuesById[7] = "PRELAUNCH"] = "PRELAUNCH"; - values[valuesById[1] = "EARLY_ACCESS"] = "EARLY_ACCESS"; - values[valuesById[2] = "ALPHA"] = "ALPHA"; - values[valuesById[3] = "BETA"] = "BETA"; - values[valuesById[4] = "GA"] = "GA"; - values[valuesById[5] = "DEPRECATED"] = "DEPRECATED"; - return values; + return RoutingParameter; })(); return api; @@ -18168,6 +19646,7 @@ * @property {google.api.IHttpRule|null} [".google.api.http"] MethodOptions .google.api.http * @property {Array.|null} [".google.api.methodSignature"] MethodOptions .google.api.methodSignature * @property {google.longrunning.IOperationInfo|null} [".google.longrunning.operationInfo"] MethodOptions .google.longrunning.operationInfo + * @property {google.api.IRoutingRule|null} [".google.api.routing"] MethodOptions .google.api.routing */ /** @@ -18243,6 +19722,14 @@ */ MethodOptions.prototype[".google.longrunning.operationInfo"] = null; + /** + * MethodOptions .google.api.routing. + * @member {google.api.IRoutingRule|null|undefined} .google.api.routing + * @memberof google.protobuf.MethodOptions + * @instance + */ + MethodOptions.prototype[".google.api.routing"] = null; + /** * Creates a MethodOptions message from a plain object. Also converts values to their respective internal types. * @function fromObject @@ -18309,6 +19796,11 @@ throw TypeError(".google.protobuf.MethodOptions..google.longrunning.operationInfo: object expected"); message[".google.longrunning.operationInfo"] = $root.google.longrunning.OperationInfo.fromObject(object[".google.longrunning.operationInfo"]); } + if (object[".google.api.routing"] != null) { + if (typeof object[".google.api.routing"] !== "object") + throw TypeError(".google.protobuf.MethodOptions..google.api.routing: object expected"); + message[".google.api.routing"] = $root.google.api.RoutingRule.fromObject(object[".google.api.routing"]); + } return message; }; @@ -18335,6 +19827,7 @@ object.features = null; object[".google.longrunning.operationInfo"] = null; object[".google.api.http"] = null; + object[".google.api.routing"] = null; } if (message.deprecated != null && message.hasOwnProperty("deprecated")) object.deprecated = message.deprecated; @@ -18356,6 +19849,8 @@ } if (message[".google.api.http"] != null && message.hasOwnProperty(".google.api.http")) object[".google.api.http"] = $root.google.api.HttpRule.toObject(message[".google.api.http"], options); + if (message[".google.api.routing"] != null && message.hasOwnProperty(".google.api.routing")) + object[".google.api.routing"] = $root.google.api.RoutingRule.toObject(message[".google.api.routing"], options); return object; }; diff --git a/dev/protos/firestore_v1_proto_api.d.ts b/dev/protos/firestore_v1_proto_api.d.ts index 6455ed6ed..03e0f45e1 100644 --- a/dev/protos/firestore_v1_proto_api.d.ts +++ b/dev/protos/firestore_v1_proto_api.d.ts @@ -15,6 +15,7 @@ */ import * as $protobuf from "protobufjs"; +import Long = require("long"); /** Namespace firestore. */ export namespace firestore { @@ -1247,6 +1248,54 @@ export namespace google { } } + /** Properties of an ExplainStats. */ + interface IExplainStats { + + /** ExplainStats data */ + data?: (google.protobuf.IAny|null); + } + + /** Represents an ExplainStats. */ + class ExplainStats implements IExplainStats { + + /** + * Constructs a new ExplainStats. + * @param [properties] Properties to set + */ + constructor(properties?: google.firestore.v1.IExplainStats); + + /** ExplainStats data. */ + public data?: (google.protobuf.IAny|null); + + /** + * Creates an ExplainStats message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns ExplainStats + */ + public static fromObject(object: { [k: string]: any }): google.firestore.v1.ExplainStats; + + /** + * Creates a plain object from an ExplainStats message. Also converts values to other types if specified. + * @param message ExplainStats + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.firestore.v1.ExplainStats, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this ExplainStats to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for ExplainStats + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + /** Represents a Firestore */ class Firestore extends $protobuf.rpc.Service { @@ -2707,6 +2756,9 @@ export namespace google { /** ExecutePipelineResponse executionTime */ executionTime?: (google.protobuf.ITimestamp|null); + + /** ExecutePipelineResponse explainStats */ + explainStats?: (google.firestore.v1.IExplainStats|null); } /** Represents an ExecutePipelineResponse. */ @@ -2727,6 +2779,9 @@ export namespace google { /** ExecutePipelineResponse executionTime. */ public executionTime?: (google.protobuf.ITimestamp|null); + /** ExecutePipelineResponse explainStats. */ + public explainStats?: (google.firestore.v1.IExplainStats|null); + /** * Creates an ExecutePipelineResponse message from a plain object. Also converts values to their respective internal types. * @param object Plain object @@ -5843,9 +5898,6 @@ export namespace google { /** CommonLanguageSettings destinations */ destinations?: (google.api.ClientLibraryDestination[]|null); - - /** CommonLanguageSettings selectiveGapicGeneration */ - selectiveGapicGeneration?: (google.api.ISelectiveGapicGeneration|null); } /** Represents a CommonLanguageSettings. */ @@ -5863,9 +5915,6 @@ export namespace google { /** CommonLanguageSettings destinations. */ public destinations: google.api.ClientLibraryDestination[]; - /** CommonLanguageSettings selectiveGapicGeneration. */ - public selectiveGapicGeneration?: (google.api.ISelectiveGapicGeneration|null); - /** * Creates a CommonLanguageSettings message from a plain object. Also converts values to their respective internal types. * @param object Plain object @@ -6272,9 +6321,6 @@ export namespace google { /** PythonSettings common */ common?: (google.api.ICommonLanguageSettings|null); - - /** PythonSettings experimentalFeatures */ - experimentalFeatures?: (google.api.PythonSettings.IExperimentalFeatures|null); } /** Represents a PythonSettings. */ @@ -6289,9 +6335,6 @@ export namespace google { /** PythonSettings common. */ public common?: (google.api.ICommonLanguageSettings|null); - /** PythonSettings experimentalFeatures. */ - public experimentalFeatures?: (google.api.PythonSettings.IExperimentalFeatures|null); - /** * Creates a PythonSettings message from a plain object. Also converts values to their respective internal types. * @param object Plain object @@ -6321,63 +6364,6 @@ export namespace google { public static getTypeUrl(typeUrlPrefix?: string): string; } - namespace PythonSettings { - - /** Properties of an ExperimentalFeatures. */ - interface IExperimentalFeatures { - - /** ExperimentalFeatures restAsyncIoEnabled */ - restAsyncIoEnabled?: (boolean|null); - - /** ExperimentalFeatures protobufPythonicTypesEnabled */ - protobufPythonicTypesEnabled?: (boolean|null); - } - - /** Represents an ExperimentalFeatures. */ - class ExperimentalFeatures implements IExperimentalFeatures { - - /** - * Constructs a new ExperimentalFeatures. - * @param [properties] Properties to set - */ - constructor(properties?: google.api.PythonSettings.IExperimentalFeatures); - - /** ExperimentalFeatures restAsyncIoEnabled. */ - public restAsyncIoEnabled: boolean; - - /** ExperimentalFeatures protobufPythonicTypesEnabled. */ - public protobufPythonicTypesEnabled: boolean; - - /** - * Creates an ExperimentalFeatures message from a plain object. Also converts values to their respective internal types. - * @param object Plain object - * @returns ExperimentalFeatures - */ - public static fromObject(object: { [k: string]: any }): google.api.PythonSettings.ExperimentalFeatures; - - /** - * Creates a plain object from an ExperimentalFeatures message. Also converts values to other types if specified. - * @param message ExperimentalFeatures - * @param [options] Conversion options - * @returns Plain object - */ - public static toObject(message: google.api.PythonSettings.ExperimentalFeatures, options?: $protobuf.IConversionOptions): { [k: string]: any }; - - /** - * Converts this ExperimentalFeatures to JSON. - * @returns JSON object - */ - public toJSON(): { [k: string]: any }; - - /** - * Gets the default type url for ExperimentalFeatures - * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") - * @returns The default type url - */ - public static getTypeUrl(typeUrlPrefix?: string): string; - } - } - /** Properties of a NodeSettings. */ interface INodeSettings { @@ -6557,9 +6543,6 @@ export namespace google { /** GoSettings common */ common?: (google.api.ICommonLanguageSettings|null); - - /** GoSettings renamedServices */ - renamedServices?: ({ [k: string]: string }|null); } /** Represents a GoSettings. */ @@ -6574,9 +6557,6 @@ export namespace google { /** GoSettings common. */ public common?: (google.api.ICommonLanguageSettings|null); - /** GoSettings renamedServices. */ - public renamedServices: { [k: string]: string }; - /** * Creates a GoSettings message from a plain object. Also converts values to their respective internal types. * @param object Plain object @@ -6743,63 +6723,111 @@ export namespace google { type ClientLibraryDestination = "CLIENT_LIBRARY_DESTINATION_UNSPECIFIED"| "GITHUB"| "PACKAGE_MANAGER"; - /** Properties of a SelectiveGapicGeneration. */ - interface ISelectiveGapicGeneration { + /** LaunchStage enum. */ + type LaunchStage = + "LAUNCH_STAGE_UNSPECIFIED"| "UNIMPLEMENTED"| "PRELAUNCH"| "EARLY_ACCESS"| "ALPHA"| "BETA"| "GA"| "DEPRECATED"; - /** SelectiveGapicGeneration methods */ - methods?: (string[]|null); + /** Properties of a RoutingRule. */ + interface IRoutingRule { - /** SelectiveGapicGeneration generateOmittedAsInternal */ - generateOmittedAsInternal?: (boolean|null); + /** RoutingRule routingParameters */ + routingParameters?: (google.api.IRoutingParameter[]|null); } - /** Represents a SelectiveGapicGeneration. */ - class SelectiveGapicGeneration implements ISelectiveGapicGeneration { + /** Represents a RoutingRule. */ + class RoutingRule implements IRoutingRule { /** - * Constructs a new SelectiveGapicGeneration. + * Constructs a new RoutingRule. * @param [properties] Properties to set */ - constructor(properties?: google.api.ISelectiveGapicGeneration); + constructor(properties?: google.api.IRoutingRule); - /** SelectiveGapicGeneration methods. */ - public methods: string[]; - - /** SelectiveGapicGeneration generateOmittedAsInternal. */ - public generateOmittedAsInternal: boolean; + /** RoutingRule routingParameters. */ + public routingParameters: google.api.IRoutingParameter[]; /** - * Creates a SelectiveGapicGeneration message from a plain object. Also converts values to their respective internal types. + * Creates a RoutingRule message from a plain object. Also converts values to their respective internal types. * @param object Plain object - * @returns SelectiveGapicGeneration + * @returns RoutingRule */ - public static fromObject(object: { [k: string]: any }): google.api.SelectiveGapicGeneration; + public static fromObject(object: { [k: string]: any }): google.api.RoutingRule; /** - * Creates a plain object from a SelectiveGapicGeneration message. Also converts values to other types if specified. - * @param message SelectiveGapicGeneration + * Creates a plain object from a RoutingRule message. Also converts values to other types if specified. + * @param message RoutingRule * @param [options] Conversion options * @returns Plain object */ - public static toObject(message: google.api.SelectiveGapicGeneration, options?: $protobuf.IConversionOptions): { [k: string]: any }; + public static toObject(message: google.api.RoutingRule, options?: $protobuf.IConversionOptions): { [k: string]: any }; /** - * Converts this SelectiveGapicGeneration to JSON. + * Converts this RoutingRule to JSON. * @returns JSON object */ public toJSON(): { [k: string]: any }; /** - * Gets the default type url for SelectiveGapicGeneration + * Gets the default type url for RoutingRule * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") * @returns The default type url */ public static getTypeUrl(typeUrlPrefix?: string): string; } - /** LaunchStage enum. */ - type LaunchStage = - "LAUNCH_STAGE_UNSPECIFIED"| "UNIMPLEMENTED"| "PRELAUNCH"| "EARLY_ACCESS"| "ALPHA"| "BETA"| "GA"| "DEPRECATED"; + /** Properties of a RoutingParameter. */ + interface IRoutingParameter { + + /** RoutingParameter field */ + field?: (string|null); + + /** RoutingParameter pathTemplate */ + pathTemplate?: (string|null); + } + + /** Represents a RoutingParameter. */ + class RoutingParameter implements IRoutingParameter { + + /** + * Constructs a new RoutingParameter. + * @param [properties] Properties to set + */ + constructor(properties?: google.api.IRoutingParameter); + + /** RoutingParameter field. */ + public field: string; + + /** RoutingParameter pathTemplate. */ + public pathTemplate: string; + + /** + * Creates a RoutingParameter message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns RoutingParameter + */ + public static fromObject(object: { [k: string]: any }): google.api.RoutingParameter; + + /** + * Creates a plain object from a RoutingParameter message. Also converts values to other types if specified. + * @param message RoutingParameter + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.api.RoutingParameter, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this RoutingParameter to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for RoutingParameter + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } /** Properties of a ResourceDescriptor. */ interface IResourceDescriptor { @@ -8736,6 +8764,9 @@ export namespace google { /** MethodOptions .google.api.methodSignature */ ".google.api.methodSignature"?: (string[]|null); + /** MethodOptions .google.api.routing */ + ".google.api.routing"?: (google.api.IRoutingRule|null); + /** MethodOptions .google.longrunning.operationInfo */ ".google.longrunning.operationInfo"?: (google.longrunning.IOperationInfo|null); } @@ -9648,6 +9679,60 @@ export namespace google { public static getTypeUrl(typeUrlPrefix?: string): string; } + /** Properties of an Any. */ + interface IAny { + + /** Any type_url */ + type_url?: (string|null); + + /** Any value */ + value?: (Uint8Array|null); + } + + /** Represents an Any. */ + class Any implements IAny { + + /** + * Constructs a new Any. + * @param [properties] Properties to set + */ + constructor(properties?: google.protobuf.IAny); + + /** Any type_url. */ + public type_url: string; + + /** Any value. */ + public value: Uint8Array; + + /** + * Creates an Any message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns Any + */ + public static fromObject(object: { [k: string]: any }): google.protobuf.Any; + + /** + * Creates a plain object from an Any message. Also converts values to other types if specified. + * @param message Any + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.protobuf.Any, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this Any to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for Any + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + /** Properties of a Duration. */ interface IDuration { @@ -10176,60 +10261,6 @@ export namespace google { public static getTypeUrl(typeUrlPrefix?: string): string; } - /** Properties of an Any. */ - interface IAny { - - /** Any type_url */ - type_url?: (string|null); - - /** Any value */ - value?: (Uint8Array|null); - } - - /** Represents an Any. */ - class Any implements IAny { - - /** - * Constructs a new Any. - * @param [properties] Properties to set - */ - constructor(properties?: google.protobuf.IAny); - - /** Any type_url. */ - public type_url: string; - - /** Any value. */ - public value: Uint8Array; - - /** - * Creates an Any message from a plain object. Also converts values to their respective internal types. - * @param object Plain object - * @returns Any - */ - public static fromObject(object: { [k: string]: any }): google.protobuf.Any; - - /** - * Creates a plain object from an Any message. Also converts values to other types if specified. - * @param message Any - * @param [options] Conversion options - * @returns Plain object - */ - public static toObject(message: google.protobuf.Any, options?: $protobuf.IConversionOptions): { [k: string]: any }; - - /** - * Converts this Any to JSON. - * @returns JSON object - */ - public toJSON(): { [k: string]: any }; - - /** - * Gets the default type url for Any - * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") - * @returns The default type url - */ - public static getTypeUrl(typeUrlPrefix?: string): string; - } - /** Properties of a FieldMask. */ interface IFieldMask { diff --git a/dev/protos/firestore_v1_proto_api.js b/dev/protos/firestore_v1_proto_api.js index 4f20fb33b..516afdd1a 100644 --- a/dev/protos/firestore_v1_proto_api.js +++ b/dev/protos/firestore_v1_proto_api.js @@ -28,21 +28,21 @@ // Common aliases var $util = $protobuf.util; - + // Exported root namespace var $root = $protobuf.roots.firestore_v1 || ($protobuf.roots.firestore_v1 = {}); - + $root.firestore = (function() { - + /** * Namespace firestore. * @exports firestore * @namespace */ var firestore = {}; - + firestore.BundledQuery = (function() { - + /** * Properties of a BundledQuery. * @memberof firestore @@ -51,7 +51,7 @@ * @property {google.firestore.v1.IStructuredQuery|null} [structuredQuery] BundledQuery structuredQuery * @property {firestore.BundledQuery.LimitType|null} [limitType] BundledQuery limitType */ - + /** * Constructs a new BundledQuery. * @memberof firestore @@ -66,7 +66,7 @@ if (properties[keys[i]] != null) this[keys[i]] = properties[keys[i]]; } - + /** * BundledQuery parent. * @member {string} parent @@ -74,7 +74,7 @@ * @instance */ BundledQuery.prototype.parent = ""; - + /** * BundledQuery structuredQuery. * @member {google.firestore.v1.IStructuredQuery|null|undefined} structuredQuery @@ -82,7 +82,7 @@ * @instance */ BundledQuery.prototype.structuredQuery = null; - + /** * BundledQuery limitType. * @member {firestore.BundledQuery.LimitType} limitType @@ -90,10 +90,10 @@ * @instance */ BundledQuery.prototype.limitType = 0; - + // OneOf field names bound to virtual getters and setters var $oneOfFields; - + /** * BundledQuery queryType. * @member {"structuredQuery"|undefined} queryType @@ -104,7 +104,7 @@ get: $util.oneOfGetter($oneOfFields = ["structuredQuery"]), set: $util.oneOfSetter($oneOfFields) }); - + /** * Creates a BundledQuery message from a plain object. Also converts values to their respective internal types. * @function fromObject @@ -142,7 +142,7 @@ } return message; }; - + /** * Creates a plain object from a BundledQuery message. Also converts values to other types if specified. * @function toObject @@ -171,7 +171,7 @@ object.limitType = options.enums === String ? $root.firestore.BundledQuery.LimitType[message.limitType] === undefined ? message.limitType : $root.firestore.BundledQuery.LimitType[message.limitType] : message.limitType; return object; }; - + /** * Converts this BundledQuery to JSON. * @function toJSON @@ -182,7 +182,7 @@ BundledQuery.prototype.toJSON = function toJSON() { return this.constructor.toObject(this, $protobuf.util.toJSONOptions); }; - + /** * Gets the default type url for BundledQuery * @function getTypeUrl @@ -197,7 +197,7 @@ } return typeUrlPrefix + "/firestore.BundledQuery"; }; - + /** * LimitType enum. * @name firestore.BundledQuery.LimitType @@ -211,12 +211,12 @@ values[valuesById[1] = "LAST"] = "LAST"; return values; })(); - + return BundledQuery; })(); - + firestore.NamedQuery = (function() { - + /** * Properties of a NamedQuery. * @memberof firestore @@ -225,7 +225,7 @@ * @property {firestore.IBundledQuery|null} [bundledQuery] NamedQuery bundledQuery * @property {google.protobuf.ITimestamp|null} [readTime] NamedQuery readTime */ - + /** * Constructs a new NamedQuery. * @memberof firestore @@ -240,7 +240,7 @@ if (properties[keys[i]] != null) this[keys[i]] = properties[keys[i]]; } - + /** * NamedQuery name. * @member {string} name @@ -248,7 +248,7 @@ * @instance */ NamedQuery.prototype.name = ""; - + /** * NamedQuery bundledQuery. * @member {firestore.IBundledQuery|null|undefined} bundledQuery @@ -256,7 +256,7 @@ * @instance */ NamedQuery.prototype.bundledQuery = null; - + /** * NamedQuery readTime. * @member {google.protobuf.ITimestamp|null|undefined} readTime @@ -264,7 +264,7 @@ * @instance */ NamedQuery.prototype.readTime = null; - + /** * Creates a NamedQuery message from a plain object. Also converts values to their respective internal types. * @function fromObject @@ -291,7 +291,7 @@ } return message; }; - + /** * Creates a plain object from a NamedQuery message. Also converts values to other types if specified. * @function toObject @@ -318,7 +318,7 @@ object.readTime = $root.google.protobuf.Timestamp.toObject(message.readTime, options); return object; }; - + /** * Converts this NamedQuery to JSON. * @function toJSON @@ -329,7 +329,7 @@ NamedQuery.prototype.toJSON = function toJSON() { return this.constructor.toObject(this, $protobuf.util.toJSONOptions); }; - + /** * Gets the default type url for NamedQuery * @function getTypeUrl @@ -344,12 +344,12 @@ } return typeUrlPrefix + "/firestore.NamedQuery"; }; - + return NamedQuery; })(); - + firestore.BundledDocumentMetadata = (function() { - + /** * Properties of a BundledDocumentMetadata. * @memberof firestore @@ -359,7 +359,7 @@ * @property {boolean|null} [exists] BundledDocumentMetadata exists * @property {Array.|null} [queries] BundledDocumentMetadata queries */ - + /** * Constructs a new BundledDocumentMetadata. * @memberof firestore @@ -375,7 +375,7 @@ if (properties[keys[i]] != null) this[keys[i]] = properties[keys[i]]; } - + /** * BundledDocumentMetadata name. * @member {string} name @@ -383,7 +383,7 @@ * @instance */ BundledDocumentMetadata.prototype.name = ""; - + /** * BundledDocumentMetadata readTime. * @member {google.protobuf.ITimestamp|null|undefined} readTime @@ -391,7 +391,7 @@ * @instance */ BundledDocumentMetadata.prototype.readTime = null; - + /** * BundledDocumentMetadata exists. * @member {boolean} exists @@ -399,7 +399,7 @@ * @instance */ BundledDocumentMetadata.prototype.exists = false; - + /** * BundledDocumentMetadata queries. * @member {Array.} queries @@ -407,7 +407,7 @@ * @instance */ BundledDocumentMetadata.prototype.queries = $util.emptyArray; - + /** * Creates a BundledDocumentMetadata message from a plain object. Also converts values to their respective internal types. * @function fromObject @@ -438,7 +438,7 @@ } return message; }; - + /** * Creates a plain object from a BundledDocumentMetadata message. Also converts values to other types if specified. * @function toObject @@ -472,7 +472,7 @@ } return object; }; - + /** * Converts this BundledDocumentMetadata to JSON. * @function toJSON @@ -483,7 +483,7 @@ BundledDocumentMetadata.prototype.toJSON = function toJSON() { return this.constructor.toObject(this, $protobuf.util.toJSONOptions); }; - + /** * Gets the default type url for BundledDocumentMetadata * @function getTypeUrl @@ -498,12 +498,12 @@ } return typeUrlPrefix + "/firestore.BundledDocumentMetadata"; }; - + return BundledDocumentMetadata; })(); - + firestore.BundleMetadata = (function() { - + /** * Properties of a BundleMetadata. * @memberof firestore @@ -514,7 +514,7 @@ * @property {number|null} [totalDocuments] BundleMetadata totalDocuments * @property {number|string|null} [totalBytes] BundleMetadata totalBytes */ - + /** * Constructs a new BundleMetadata. * @memberof firestore @@ -529,7 +529,7 @@ if (properties[keys[i]] != null) this[keys[i]] = properties[keys[i]]; } - + /** * BundleMetadata id. * @member {string} id @@ -537,7 +537,7 @@ * @instance */ BundleMetadata.prototype.id = ""; - + /** * BundleMetadata createTime. * @member {google.protobuf.ITimestamp|null|undefined} createTime @@ -545,7 +545,7 @@ * @instance */ BundleMetadata.prototype.createTime = null; - + /** * BundleMetadata version. * @member {number} version @@ -553,7 +553,7 @@ * @instance */ BundleMetadata.prototype.version = 0; - + /** * BundleMetadata totalDocuments. * @member {number} totalDocuments @@ -561,7 +561,7 @@ * @instance */ BundleMetadata.prototype.totalDocuments = 0; - + /** * BundleMetadata totalBytes. * @member {number|string} totalBytes @@ -569,7 +569,7 @@ * @instance */ BundleMetadata.prototype.totalBytes = $util.Long ? $util.Long.fromBits(0,0,true) : 0; - + /** * Creates a BundleMetadata message from a plain object. Also converts values to their respective internal types. * @function fromObject @@ -604,7 +604,7 @@ message.totalBytes = new $util.LongBits(object.totalBytes.low >>> 0, object.totalBytes.high >>> 0).toNumber(true); return message; }; - + /** * Creates a plain object from a BundleMetadata message. Also converts values to other types if specified. * @function toObject @@ -644,7 +644,7 @@ object.totalBytes = options.longs === String ? $util.Long.prototype.toString.call(message.totalBytes) : options.longs === Number ? new $util.LongBits(message.totalBytes.low >>> 0, message.totalBytes.high >>> 0).toNumber(true) : message.totalBytes; return object; }; - + /** * Converts this BundleMetadata to JSON. * @function toJSON @@ -655,7 +655,7 @@ BundleMetadata.prototype.toJSON = function toJSON() { return this.constructor.toObject(this, $protobuf.util.toJSONOptions); }; - + /** * Gets the default type url for BundleMetadata * @function getTypeUrl @@ -670,12 +670,12 @@ } return typeUrlPrefix + "/firestore.BundleMetadata"; }; - + return BundleMetadata; })(); - + firestore.BundleElement = (function() { - + /** * Properties of a BundleElement. * @memberof firestore @@ -685,7 +685,7 @@ * @property {firestore.IBundledDocumentMetadata|null} [documentMetadata] BundleElement documentMetadata * @property {google.firestore.v1.IDocument|null} [document] BundleElement document */ - + /** * Constructs a new BundleElement. * @memberof firestore @@ -700,7 +700,7 @@ if (properties[keys[i]] != null) this[keys[i]] = properties[keys[i]]; } - + /** * BundleElement metadata. * @member {firestore.IBundleMetadata|null|undefined} metadata @@ -708,7 +708,7 @@ * @instance */ BundleElement.prototype.metadata = null; - + /** * BundleElement namedQuery. * @member {firestore.INamedQuery|null|undefined} namedQuery @@ -716,7 +716,7 @@ * @instance */ BundleElement.prototype.namedQuery = null; - + /** * BundleElement documentMetadata. * @member {firestore.IBundledDocumentMetadata|null|undefined} documentMetadata @@ -724,7 +724,7 @@ * @instance */ BundleElement.prototype.documentMetadata = null; - + /** * BundleElement document. * @member {google.firestore.v1.IDocument|null|undefined} document @@ -732,10 +732,10 @@ * @instance */ BundleElement.prototype.document = null; - + // OneOf field names bound to virtual getters and setters var $oneOfFields; - + /** * BundleElement elementType. * @member {"metadata"|"namedQuery"|"documentMetadata"|"document"|undefined} elementType @@ -746,7 +746,7 @@ get: $util.oneOfGetter($oneOfFields = ["metadata", "namedQuery", "documentMetadata", "document"]), set: $util.oneOfSetter($oneOfFields) }); - + /** * Creates a BundleElement message from a plain object. Also converts values to their respective internal types. * @function fromObject @@ -781,7 +781,7 @@ } return message; }; - + /** * Creates a plain object from a BundleElement message. Also converts values to other types if specified. * @function toObject @@ -817,7 +817,7 @@ } return object; }; - + /** * Converts this BundleElement to JSON. * @function toJSON @@ -828,7 +828,7 @@ BundleElement.prototype.toJSON = function toJSON() { return this.constructor.toObject(this, $protobuf.util.toJSONOptions); }; - + /** * Gets the default type url for BundleElement * @function getTypeUrl @@ -843,49 +843,49 @@ } return typeUrlPrefix + "/firestore.BundleElement"; }; - + return BundleElement; })(); - + return firestore; })(); - + $root.google = (function() { - + /** * Namespace google. * @exports google * @namespace */ var google = {}; - + google.firestore = (function() { - + /** * Namespace firestore. * @memberof google * @namespace */ var firestore = {}; - + firestore.v1 = (function() { - + /** * Namespace v1. * @memberof google.firestore * @namespace */ var v1 = {}; - + v1.AggregationResult = (function() { - + /** * Properties of an AggregationResult. * @memberof google.firestore.v1 * @interface IAggregationResult * @property {Object.|null} [aggregateFields] AggregationResult aggregateFields */ - + /** * Constructs a new AggregationResult. * @memberof google.firestore.v1 @@ -901,7 +901,7 @@ if (properties[keys[i]] != null) this[keys[i]] = properties[keys[i]]; } - + /** * AggregationResult aggregateFields. * @member {Object.} aggregateFields @@ -909,7 +909,7 @@ * @instance */ AggregationResult.prototype.aggregateFields = $util.emptyObject; - + /** * Creates an AggregationResult message from a plain object. Also converts values to their respective internal types. * @function fromObject @@ -934,7 +934,7 @@ } return message; }; - + /** * Creates a plain object from an AggregationResult message. Also converts values to other types if specified. * @function toObject @@ -958,7 +958,7 @@ } return object; }; - + /** * Converts this AggregationResult to JSON. * @function toJSON @@ -969,7 +969,7 @@ AggregationResult.prototype.toJSON = function toJSON() { return this.constructor.toObject(this, $protobuf.util.toJSONOptions); }; - + /** * Gets the default type url for AggregationResult * @function getTypeUrl @@ -984,12 +984,12 @@ } return typeUrlPrefix + "/google.firestore.v1.AggregationResult"; }; - + return AggregationResult; })(); - + v1.Document = (function() { - + /** * Properties of a Document. * @memberof google.firestore.v1 @@ -999,7 +999,7 @@ * @property {google.protobuf.ITimestamp|null} [createTime] Document createTime * @property {google.protobuf.ITimestamp|null} [updateTime] Document updateTime */ - + /** * Constructs a new Document. * @memberof google.firestore.v1 @@ -1015,7 +1015,7 @@ if (properties[keys[i]] != null) this[keys[i]] = properties[keys[i]]; } - + /** * Document name. * @member {string} name @@ -1023,7 +1023,7 @@ * @instance */ Document.prototype.name = ""; - + /** * Document fields. * @member {Object.} fields @@ -1031,7 +1031,7 @@ * @instance */ Document.prototype.fields = $util.emptyObject; - + /** * Document createTime. * @member {google.protobuf.ITimestamp|null|undefined} createTime @@ -1039,7 +1039,7 @@ * @instance */ Document.prototype.createTime = null; - + /** * Document updateTime. * @member {google.protobuf.ITimestamp|null|undefined} updateTime @@ -1047,7 +1047,7 @@ * @instance */ Document.prototype.updateTime = null; - + /** * Creates a Document message from a plain object. Also converts values to their respective internal types. * @function fromObject @@ -1084,7 +1084,7 @@ } return message; }; - + /** * Creates a plain object from a Document message. Also converts values to other types if specified. * @function toObject @@ -1119,7 +1119,7 @@ object.updateTime = $root.google.protobuf.Timestamp.toObject(message.updateTime, options); return object; }; - + /** * Converts this Document to JSON. * @function toJSON @@ -1130,7 +1130,7 @@ Document.prototype.toJSON = function toJSON() { return this.constructor.toObject(this, $protobuf.util.toJSONOptions); }; - + /** * Gets the default type url for Document * @function getTypeUrl @@ -1145,12 +1145,12 @@ } return typeUrlPrefix + "/google.firestore.v1.Document"; }; - + return Document; })(); - + v1.Value = (function() { - + /** * Properties of a Value. * @memberof google.firestore.v1 @@ -1170,7 +1170,7 @@ * @property {google.firestore.v1.IFunction|null} [functionValue] Value functionValue * @property {google.firestore.v1.IPipeline|null} [pipelineValue] Value pipelineValue */ - + /** * Constructs a new Value. * @memberof google.firestore.v1 @@ -1185,7 +1185,7 @@ if (properties[keys[i]] != null) this[keys[i]] = properties[keys[i]]; } - + /** * Value nullValue. * @member {google.protobuf.NullValue|null|undefined} nullValue @@ -1193,7 +1193,7 @@ * @instance */ Value.prototype.nullValue = null; - + /** * Value booleanValue. * @member {boolean|null|undefined} booleanValue @@ -1201,7 +1201,7 @@ * @instance */ Value.prototype.booleanValue = null; - + /** * Value integerValue. * @member {number|string|null|undefined} integerValue @@ -1209,7 +1209,7 @@ * @instance */ Value.prototype.integerValue = null; - + /** * Value doubleValue. * @member {number|null|undefined} doubleValue @@ -1217,7 +1217,7 @@ * @instance */ Value.prototype.doubleValue = null; - + /** * Value timestampValue. * @member {google.protobuf.ITimestamp|null|undefined} timestampValue @@ -1225,7 +1225,7 @@ * @instance */ Value.prototype.timestampValue = null; - + /** * Value stringValue. * @member {string|null|undefined} stringValue @@ -1233,7 +1233,7 @@ * @instance */ Value.prototype.stringValue = null; - + /** * Value bytesValue. * @member {Uint8Array|null|undefined} bytesValue @@ -1241,7 +1241,7 @@ * @instance */ Value.prototype.bytesValue = null; - + /** * Value referenceValue. * @member {string|null|undefined} referenceValue @@ -1249,7 +1249,7 @@ * @instance */ Value.prototype.referenceValue = null; - + /** * Value geoPointValue. * @member {google.type.ILatLng|null|undefined} geoPointValue @@ -1257,7 +1257,7 @@ * @instance */ Value.prototype.geoPointValue = null; - + /** * Value arrayValue. * @member {google.firestore.v1.IArrayValue|null|undefined} arrayValue @@ -1265,7 +1265,7 @@ * @instance */ Value.prototype.arrayValue = null; - + /** * Value mapValue. * @member {google.firestore.v1.IMapValue|null|undefined} mapValue @@ -1273,7 +1273,7 @@ * @instance */ Value.prototype.mapValue = null; - + /** * Value fieldReferenceValue. * @member {string|null|undefined} fieldReferenceValue @@ -1281,7 +1281,7 @@ * @instance */ Value.prototype.fieldReferenceValue = null; - + /** * Value functionValue. * @member {google.firestore.v1.IFunction|null|undefined} functionValue @@ -1289,7 +1289,7 @@ * @instance */ Value.prototype.functionValue = null; - + /** * Value pipelineValue. * @member {google.firestore.v1.IPipeline|null|undefined} pipelineValue @@ -1297,10 +1297,10 @@ * @instance */ Value.prototype.pipelineValue = null; - + // OneOf field names bound to virtual getters and setters var $oneOfFields; - + /** * Value valueType. * @member {"nullValue"|"booleanValue"|"integerValue"|"doubleValue"|"timestampValue"|"stringValue"|"bytesValue"|"referenceValue"|"geoPointValue"|"arrayValue"|"mapValue"|"fieldReferenceValue"|"functionValue"|"pipelineValue"|undefined} valueType @@ -1311,7 +1311,7 @@ get: $util.oneOfGetter($oneOfFields = ["nullValue", "booleanValue", "integerValue", "doubleValue", "timestampValue", "stringValue", "bytesValue", "referenceValue", "geoPointValue", "arrayValue", "mapValue", "fieldReferenceValue", "functionValue", "pipelineValue"]), set: $util.oneOfSetter($oneOfFields) }); - + /** * Creates a Value message from a plain object. Also converts values to their respective internal types. * @function fromObject @@ -1392,7 +1392,7 @@ } return message; }; - + /** * Creates a plain object from a Value message. Also converts values to other types if specified. * @function toObject @@ -1481,7 +1481,7 @@ } return object; }; - + /** * Converts this Value to JSON. * @function toJSON @@ -1492,7 +1492,7 @@ Value.prototype.toJSON = function toJSON() { return this.constructor.toObject(this, $protobuf.util.toJSONOptions); }; - + /** * Gets the default type url for Value * @function getTypeUrl @@ -1507,19 +1507,19 @@ } return typeUrlPrefix + "/google.firestore.v1.Value"; }; - + return Value; })(); - + v1.ArrayValue = (function() { - + /** * Properties of an ArrayValue. * @memberof google.firestore.v1 * @interface IArrayValue * @property {Array.|null} [values] ArrayValue values */ - + /** * Constructs a new ArrayValue. * @memberof google.firestore.v1 @@ -1535,7 +1535,7 @@ if (properties[keys[i]] != null) this[keys[i]] = properties[keys[i]]; } - + /** * ArrayValue values. * @member {Array.} values @@ -1543,7 +1543,7 @@ * @instance */ ArrayValue.prototype.values = $util.emptyArray; - + /** * Creates an ArrayValue message from a plain object. Also converts values to their respective internal types. * @function fromObject @@ -1568,7 +1568,7 @@ } return message; }; - + /** * Creates a plain object from an ArrayValue message. Also converts values to other types if specified. * @function toObject @@ -1591,7 +1591,7 @@ } return object; }; - + /** * Converts this ArrayValue to JSON. * @function toJSON @@ -1602,7 +1602,7 @@ ArrayValue.prototype.toJSON = function toJSON() { return this.constructor.toObject(this, $protobuf.util.toJSONOptions); }; - + /** * Gets the default type url for ArrayValue * @function getTypeUrl @@ -1617,19 +1617,19 @@ } return typeUrlPrefix + "/google.firestore.v1.ArrayValue"; }; - + return ArrayValue; })(); - + v1.MapValue = (function() { - + /** * Properties of a MapValue. * @memberof google.firestore.v1 * @interface IMapValue * @property {Object.|null} [fields] MapValue fields */ - + /** * Constructs a new MapValue. * @memberof google.firestore.v1 @@ -1645,7 +1645,7 @@ if (properties[keys[i]] != null) this[keys[i]] = properties[keys[i]]; } - + /** * MapValue fields. * @member {Object.} fields @@ -1653,7 +1653,7 @@ * @instance */ MapValue.prototype.fields = $util.emptyObject; - + /** * Creates a MapValue message from a plain object. Also converts values to their respective internal types. * @function fromObject @@ -1678,7 +1678,7 @@ } return message; }; - + /** * Creates a plain object from a MapValue message. Also converts values to other types if specified. * @function toObject @@ -1702,7 +1702,7 @@ } return object; }; - + /** * Converts this MapValue to JSON. * @function toJSON @@ -1713,7 +1713,7 @@ MapValue.prototype.toJSON = function toJSON() { return this.constructor.toObject(this, $protobuf.util.toJSONOptions); }; - + /** * Gets the default type url for MapValue * @function getTypeUrl @@ -1728,12 +1728,12 @@ } return typeUrlPrefix + "/google.firestore.v1.MapValue"; }; - + return MapValue; })(); - + v1.Function = (function() { - + /** * Properties of a Function. * @memberof google.firestore.v1 @@ -1742,7 +1742,7 @@ * @property {Array.|null} [args] Function args * @property {Object.|null} [options] Function options */ - + /** * Constructs a new Function. * @memberof google.firestore.v1 @@ -1759,7 +1759,7 @@ if (properties[keys[i]] != null) this[keys[i]] = properties[keys[i]]; } - + /** * Function name. * @member {string} name @@ -1767,7 +1767,7 @@ * @instance */ Function.prototype.name = ""; - + /** * Function args. * @member {Array.} args @@ -1775,7 +1775,7 @@ * @instance */ Function.prototype.args = $util.emptyArray; - + /** * Function options. * @member {Object.} options @@ -1783,7 +1783,7 @@ * @instance */ Function.prototype.options = $util.emptyObject; - + /** * Creates a Function message from a plain object. Also converts values to their respective internal types. * @function fromObject @@ -1820,7 +1820,7 @@ } return message; }; - + /** * Creates a plain object from a Function message. Also converts values to other types if specified. * @function toObject @@ -1855,7 +1855,7 @@ } return object; }; - + /** * Converts this Function to JSON. * @function toJSON @@ -1866,7 +1866,7 @@ Function.prototype.toJSON = function toJSON() { return this.constructor.toObject(this, $protobuf.util.toJSONOptions); }; - + /** * Gets the default type url for Function * @function getTypeUrl @@ -1881,19 +1881,19 @@ } return typeUrlPrefix + "/google.firestore.v1.Function"; }; - + return Function; })(); - + v1.Pipeline = (function() { - + /** * Properties of a Pipeline. * @memberof google.firestore.v1 * @interface IPipeline * @property {Array.|null} [stages] Pipeline stages */ - + /** * Constructs a new Pipeline. * @memberof google.firestore.v1 @@ -1909,7 +1909,7 @@ if (properties[keys[i]] != null) this[keys[i]] = properties[keys[i]]; } - + /** * Pipeline stages. * @member {Array.} stages @@ -1917,7 +1917,7 @@ * @instance */ Pipeline.prototype.stages = $util.emptyArray; - + /** * Creates a Pipeline message from a plain object. Also converts values to their respective internal types. * @function fromObject @@ -1942,7 +1942,7 @@ } return message; }; - + /** * Creates a plain object from a Pipeline message. Also converts values to other types if specified. * @function toObject @@ -1965,7 +1965,7 @@ } return object; }; - + /** * Converts this Pipeline to JSON. * @function toJSON @@ -1976,7 +1976,7 @@ Pipeline.prototype.toJSON = function toJSON() { return this.constructor.toObject(this, $protobuf.util.toJSONOptions); }; - + /** * Gets the default type url for Pipeline * @function getTypeUrl @@ -1991,9 +1991,9 @@ } return typeUrlPrefix + "/google.firestore.v1.Pipeline"; }; - + Pipeline.Stage = (function() { - + /** * Properties of a Stage. * @memberof google.firestore.v1.Pipeline @@ -2002,7 +2002,7 @@ * @property {Array.|null} [args] Stage args * @property {Object.|null} [options] Stage options */ - + /** * Constructs a new Stage. * @memberof google.firestore.v1.Pipeline @@ -2019,7 +2019,7 @@ if (properties[keys[i]] != null) this[keys[i]] = properties[keys[i]]; } - + /** * Stage name. * @member {string} name @@ -2027,7 +2027,7 @@ * @instance */ Stage.prototype.name = ""; - + /** * Stage args. * @member {Array.} args @@ -2035,7 +2035,7 @@ * @instance */ Stage.prototype.args = $util.emptyArray; - + /** * Stage options. * @member {Object.} options @@ -2043,7 +2043,7 @@ * @instance */ Stage.prototype.options = $util.emptyObject; - + /** * Creates a Stage message from a plain object. Also converts values to their respective internal types. * @function fromObject @@ -2080,7 +2080,7 @@ } return message; }; - + /** * Creates a plain object from a Stage message. Also converts values to other types if specified. * @function toObject @@ -2115,7 +2115,7 @@ } return object; }; - + /** * Converts this Stage to JSON. * @function toJSON @@ -2126,7 +2126,7 @@ Stage.prototype.toJSON = function toJSON() { return this.constructor.toObject(this, $protobuf.util.toJSONOptions); }; - + /** * Gets the default type url for Stage * @function getTypeUrl @@ -2141,15 +2141,15 @@ } return typeUrlPrefix + "/google.firestore.v1.Pipeline.Stage"; }; - + return Stage; })(); - + return Pipeline; })(); - + v1.BitSequence = (function() { - + /** * Properties of a BitSequence. * @memberof google.firestore.v1 @@ -2157,7 +2157,7 @@ * @property {Uint8Array|null} [bitmap] BitSequence bitmap * @property {number|null} [padding] BitSequence padding */ - + /** * Constructs a new BitSequence. * @memberof google.firestore.v1 @@ -2172,7 +2172,7 @@ if (properties[keys[i]] != null) this[keys[i]] = properties[keys[i]]; } - + /** * BitSequence bitmap. * @member {Uint8Array} bitmap @@ -2180,7 +2180,7 @@ * @instance */ BitSequence.prototype.bitmap = $util.newBuffer([]); - + /** * BitSequence padding. * @member {number} padding @@ -2188,7 +2188,7 @@ * @instance */ BitSequence.prototype.padding = 0; - + /** * Creates a BitSequence message from a plain object. Also converts values to their respective internal types. * @function fromObject @@ -2210,7 +2210,7 @@ message.padding = object.padding | 0; return message; }; - + /** * Creates a plain object from a BitSequence message. Also converts values to other types if specified. * @function toObject @@ -2240,7 +2240,7 @@ object.padding = message.padding; return object; }; - + /** * Converts this BitSequence to JSON. * @function toJSON @@ -2251,7 +2251,7 @@ BitSequence.prototype.toJSON = function toJSON() { return this.constructor.toObject(this, $protobuf.util.toJSONOptions); }; - + /** * Gets the default type url for BitSequence * @function getTypeUrl @@ -2266,12 +2266,12 @@ } return typeUrlPrefix + "/google.firestore.v1.BitSequence"; }; - + return BitSequence; })(); - + v1.BloomFilter = (function() { - + /** * Properties of a BloomFilter. * @memberof google.firestore.v1 @@ -2279,7 +2279,7 @@ * @property {google.firestore.v1.IBitSequence|null} [bits] BloomFilter bits * @property {number|null} [hashCount] BloomFilter hashCount */ - + /** * Constructs a new BloomFilter. * @memberof google.firestore.v1 @@ -2294,7 +2294,7 @@ if (properties[keys[i]] != null) this[keys[i]] = properties[keys[i]]; } - + /** * BloomFilter bits. * @member {google.firestore.v1.IBitSequence|null|undefined} bits @@ -2302,7 +2302,7 @@ * @instance */ BloomFilter.prototype.bits = null; - + /** * BloomFilter hashCount. * @member {number} hashCount @@ -2310,7 +2310,7 @@ * @instance */ BloomFilter.prototype.hashCount = 0; - + /** * Creates a BloomFilter message from a plain object. Also converts values to their respective internal types. * @function fromObject @@ -2332,7 +2332,7 @@ message.hashCount = object.hashCount | 0; return message; }; - + /** * Creates a plain object from a BloomFilter message. Also converts values to other types if specified. * @function toObject @@ -2356,7 +2356,7 @@ object.hashCount = message.hashCount; return object; }; - + /** * Converts this BloomFilter to JSON. * @function toJSON @@ -2367,7 +2367,7 @@ BloomFilter.prototype.toJSON = function toJSON() { return this.constructor.toObject(this, $protobuf.util.toJSONOptions); }; - + /** * Gets the default type url for BloomFilter * @function getTypeUrl @@ -2382,19 +2382,19 @@ } return typeUrlPrefix + "/google.firestore.v1.BloomFilter"; }; - + return BloomFilter; })(); - + v1.DocumentMask = (function() { - + /** * Properties of a DocumentMask. * @memberof google.firestore.v1 * @interface IDocumentMask * @property {Array.|null} [fieldPaths] DocumentMask fieldPaths */ - + /** * Constructs a new DocumentMask. * @memberof google.firestore.v1 @@ -2410,7 +2410,7 @@ if (properties[keys[i]] != null) this[keys[i]] = properties[keys[i]]; } - + /** * DocumentMask fieldPaths. * @member {Array.} fieldPaths @@ -2418,7 +2418,7 @@ * @instance */ DocumentMask.prototype.fieldPaths = $util.emptyArray; - + /** * Creates a DocumentMask message from a plain object. Also converts values to their respective internal types. * @function fromObject @@ -2440,7 +2440,7 @@ } return message; }; - + /** * Creates a plain object from a DocumentMask message. Also converts values to other types if specified. * @function toObject @@ -2463,7 +2463,7 @@ } return object; }; - + /** * Converts this DocumentMask to JSON. * @function toJSON @@ -2474,7 +2474,7 @@ DocumentMask.prototype.toJSON = function toJSON() { return this.constructor.toObject(this, $protobuf.util.toJSONOptions); }; - + /** * Gets the default type url for DocumentMask * @function getTypeUrl @@ -2489,12 +2489,12 @@ } return typeUrlPrefix + "/google.firestore.v1.DocumentMask"; }; - + return DocumentMask; })(); - + v1.Precondition = (function() { - + /** * Properties of a Precondition. * @memberof google.firestore.v1 @@ -2502,7 +2502,7 @@ * @property {boolean|null} [exists] Precondition exists * @property {google.protobuf.ITimestamp|null} [updateTime] Precondition updateTime */ - + /** * Constructs a new Precondition. * @memberof google.firestore.v1 @@ -2517,7 +2517,7 @@ if (properties[keys[i]] != null) this[keys[i]] = properties[keys[i]]; } - + /** * Precondition exists. * @member {boolean|null|undefined} exists @@ -2525,7 +2525,7 @@ * @instance */ Precondition.prototype.exists = null; - + /** * Precondition updateTime. * @member {google.protobuf.ITimestamp|null|undefined} updateTime @@ -2533,10 +2533,10 @@ * @instance */ Precondition.prototype.updateTime = null; - + // OneOf field names bound to virtual getters and setters var $oneOfFields; - + /** * Precondition conditionType. * @member {"exists"|"updateTime"|undefined} conditionType @@ -2547,7 +2547,7 @@ get: $util.oneOfGetter($oneOfFields = ["exists", "updateTime"]), set: $util.oneOfSetter($oneOfFields) }); - + /** * Creates a Precondition message from a plain object. Also converts values to their respective internal types. * @function fromObject @@ -2569,7 +2569,7 @@ } return message; }; - + /** * Creates a plain object from a Precondition message. Also converts values to other types if specified. * @function toObject @@ -2595,7 +2595,7 @@ } return object; }; - + /** * Converts this Precondition to JSON. * @function toJSON @@ -2606,7 +2606,7 @@ Precondition.prototype.toJSON = function toJSON() { return this.constructor.toObject(this, $protobuf.util.toJSONOptions); }; - + /** * Gets the default type url for Precondition * @function getTypeUrl @@ -2621,12 +2621,12 @@ } return typeUrlPrefix + "/google.firestore.v1.Precondition"; }; - + return Precondition; })(); - + v1.TransactionOptions = (function() { - + /** * Properties of a TransactionOptions. * @memberof google.firestore.v1 @@ -2634,7 +2634,7 @@ * @property {google.firestore.v1.TransactionOptions.IReadOnly|null} [readOnly] TransactionOptions readOnly * @property {google.firestore.v1.TransactionOptions.IReadWrite|null} [readWrite] TransactionOptions readWrite */ - + /** * Constructs a new TransactionOptions. * @memberof google.firestore.v1 @@ -2649,7 +2649,7 @@ if (properties[keys[i]] != null) this[keys[i]] = properties[keys[i]]; } - + /** * TransactionOptions readOnly. * @member {google.firestore.v1.TransactionOptions.IReadOnly|null|undefined} readOnly @@ -2657,7 +2657,7 @@ * @instance */ TransactionOptions.prototype.readOnly = null; - + /** * TransactionOptions readWrite. * @member {google.firestore.v1.TransactionOptions.IReadWrite|null|undefined} readWrite @@ -2665,10 +2665,10 @@ * @instance */ TransactionOptions.prototype.readWrite = null; - + // OneOf field names bound to virtual getters and setters var $oneOfFields; - + /** * TransactionOptions mode. * @member {"readOnly"|"readWrite"|undefined} mode @@ -2679,7 +2679,7 @@ get: $util.oneOfGetter($oneOfFields = ["readOnly", "readWrite"]), set: $util.oneOfSetter($oneOfFields) }); - + /** * Creates a TransactionOptions message from a plain object. Also converts values to their respective internal types. * @function fromObject @@ -2704,7 +2704,7 @@ } return message; }; - + /** * Creates a plain object from a TransactionOptions message. Also converts values to other types if specified. * @function toObject @@ -2730,7 +2730,7 @@ } return object; }; - + /** * Converts this TransactionOptions to JSON. * @function toJSON @@ -2741,7 +2741,7 @@ TransactionOptions.prototype.toJSON = function toJSON() { return this.constructor.toObject(this, $protobuf.util.toJSONOptions); }; - + /** * Gets the default type url for TransactionOptions * @function getTypeUrl @@ -2756,16 +2756,16 @@ } return typeUrlPrefix + "/google.firestore.v1.TransactionOptions"; }; - + TransactionOptions.ReadWrite = (function() { - + /** * Properties of a ReadWrite. * @memberof google.firestore.v1.TransactionOptions * @interface IReadWrite * @property {Uint8Array|null} [retryTransaction] ReadWrite retryTransaction */ - + /** * Constructs a new ReadWrite. * @memberof google.firestore.v1.TransactionOptions @@ -2780,7 +2780,7 @@ if (properties[keys[i]] != null) this[keys[i]] = properties[keys[i]]; } - + /** * ReadWrite retryTransaction. * @member {Uint8Array} retryTransaction @@ -2788,7 +2788,7 @@ * @instance */ ReadWrite.prototype.retryTransaction = $util.newBuffer([]); - + /** * Creates a ReadWrite message from a plain object. Also converts values to their respective internal types. * @function fromObject @@ -2808,7 +2808,7 @@ message.retryTransaction = object.retryTransaction; return message; }; - + /** * Creates a plain object from a ReadWrite message. Also converts values to other types if specified. * @function toObject @@ -2834,7 +2834,7 @@ object.retryTransaction = options.bytes === String ? $util.base64.encode(message.retryTransaction, 0, message.retryTransaction.length) : options.bytes === Array ? Array.prototype.slice.call(message.retryTransaction) : message.retryTransaction; return object; }; - + /** * Converts this ReadWrite to JSON. * @function toJSON @@ -2845,7 +2845,7 @@ ReadWrite.prototype.toJSON = function toJSON() { return this.constructor.toObject(this, $protobuf.util.toJSONOptions); }; - + /** * Gets the default type url for ReadWrite * @function getTypeUrl @@ -2860,19 +2860,19 @@ } return typeUrlPrefix + "/google.firestore.v1.TransactionOptions.ReadWrite"; }; - + return ReadWrite; })(); - + TransactionOptions.ReadOnly = (function() { - + /** * Properties of a ReadOnly. * @memberof google.firestore.v1.TransactionOptions * @interface IReadOnly * @property {google.protobuf.ITimestamp|null} [readTime] ReadOnly readTime */ - + /** * Constructs a new ReadOnly. * @memberof google.firestore.v1.TransactionOptions @@ -2887,7 +2887,7 @@ if (properties[keys[i]] != null) this[keys[i]] = properties[keys[i]]; } - + /** * ReadOnly readTime. * @member {google.protobuf.ITimestamp|null|undefined} readTime @@ -2895,10 +2895,10 @@ * @instance */ ReadOnly.prototype.readTime = null; - + // OneOf field names bound to virtual getters and setters var $oneOfFields; - + /** * ReadOnly consistencySelector. * @member {"readTime"|undefined} consistencySelector @@ -2909,7 +2909,7 @@ get: $util.oneOfGetter($oneOfFields = ["readTime"]), set: $util.oneOfSetter($oneOfFields) }); - + /** * Creates a ReadOnly message from a plain object. Also converts values to their respective internal types. * @function fromObject @@ -2929,7 +2929,7 @@ } return message; }; - + /** * Creates a plain object from a ReadOnly message. Also converts values to other types if specified. * @function toObject @@ -2950,7 +2950,7 @@ } return object; }; - + /** * Converts this ReadOnly to JSON. * @function toJSON @@ -2961,7 +2961,7 @@ ReadOnly.prototype.toJSON = function toJSON() { return this.constructor.toObject(this, $protobuf.util.toJSONOptions); }; - + /** * Gets the default type url for ReadOnly * @function getTypeUrl @@ -2976,31 +2976,132 @@ } return typeUrlPrefix + "/google.firestore.v1.TransactionOptions.ReadOnly"; }; - + return ReadOnly; })(); - + return TransactionOptions; })(); - - v1.Firestore = (function() { - + + v1.ExplainStats = (function() { + /** - * Constructs a new Firestore service. + * Properties of an ExplainStats. * @memberof google.firestore.v1 - * @classdesc Represents a Firestore - * @extends $protobuf.rpc.Service + * @interface IExplainStats + * @property {google.protobuf.IAny|null} [data] ExplainStats data + */ + + /** + * Constructs a new ExplainStats. + * @memberof google.firestore.v1 + * @classdesc Represents an ExplainStats. + * @implements IExplainStats * @constructor - * @param {$protobuf.RPCImpl} rpcImpl RPC implementation - * @param {boolean} [requestDelimited=false] Whether requests are length-delimited - * @param {boolean} [responseDelimited=false] Whether responses are length-delimited + * @param {google.firestore.v1.IExplainStats=} [properties] Properties to set */ - function Firestore(rpcImpl, requestDelimited, responseDelimited) { - $protobuf.rpc.Service.call(this, rpcImpl, requestDelimited, responseDelimited); - } - + function ExplainStats(properties) { + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } + + /** + * ExplainStats data. + * @member {google.protobuf.IAny|null|undefined} data + * @memberof google.firestore.v1.ExplainStats + * @instance + */ + ExplainStats.prototype.data = null; + + /** + * Creates an ExplainStats message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.firestore.v1.ExplainStats + * @static + * @param {Object.} object Plain object + * @returns {google.firestore.v1.ExplainStats} ExplainStats + */ + ExplainStats.fromObject = function fromObject(object) { + if (object instanceof $root.google.firestore.v1.ExplainStats) + return object; + var message = new $root.google.firestore.v1.ExplainStats(); + if (object.data != null) { + if (typeof object.data !== "object") + throw TypeError(".google.firestore.v1.ExplainStats.data: object expected"); + message.data = $root.google.protobuf.Any.fromObject(object.data); + } + return message; + }; + + /** + * Creates a plain object from an ExplainStats message. Also converts values to other types if specified. + * @function toObject + * @memberof google.firestore.v1.ExplainStats + * @static + * @param {google.firestore.v1.ExplainStats} message ExplainStats + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + ExplainStats.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.defaults) + object.data = null; + if (message.data != null && message.hasOwnProperty("data")) + object.data = $root.google.protobuf.Any.toObject(message.data, options); + return object; + }; + + /** + * Converts this ExplainStats to JSON. + * @function toJSON + * @memberof google.firestore.v1.ExplainStats + * @instance + * @returns {Object.} JSON object + */ + ExplainStats.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + + /** + * Gets the default type url for ExplainStats + * @function getTypeUrl + * @memberof google.firestore.v1.ExplainStats + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + ExplainStats.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.firestore.v1.ExplainStats"; + }; + + return ExplainStats; + })(); + + v1.Firestore = (function() { + + /** + * Constructs a new Firestore service. + * @memberof google.firestore.v1 + * @classdesc Represents a Firestore + * @extends $protobuf.rpc.Service + * @constructor + * @param {$protobuf.RPCImpl} rpcImpl RPC implementation + * @param {boolean} [requestDelimited=false] Whether requests are length-delimited + * @param {boolean} [responseDelimited=false] Whether responses are length-delimited + */ + function Firestore(rpcImpl, requestDelimited, responseDelimited) { + $protobuf.rpc.Service.call(this, rpcImpl, requestDelimited, responseDelimited); + } + (Firestore.prototype = Object.create($protobuf.rpc.Service.prototype)).constructor = Firestore; - + /** * Callback as used by {@link google.firestore.v1.Firestore#getDocument}. * @memberof google.firestore.v1.Firestore @@ -3009,7 +3110,7 @@ * @param {Error|null} error Error, if any * @param {google.firestore.v1.Document} [response] Document */ - + /** * Calls GetDocument. * @function getDocument @@ -3023,7 +3124,7 @@ Object.defineProperty(Firestore.prototype.getDocument = function getDocument(request, callback) { return this.rpcCall(getDocument, $root.google.firestore.v1.GetDocumentRequest, $root.google.firestore.v1.Document, request, callback); }, "name", { value: "GetDocument" }); - + /** * Calls GetDocument. * @function getDocument @@ -3033,7 +3134,7 @@ * @returns {Promise} Promise * @variation 2 */ - + /** * Callback as used by {@link google.firestore.v1.Firestore#listDocuments}. * @memberof google.firestore.v1.Firestore @@ -3042,7 +3143,7 @@ * @param {Error|null} error Error, if any * @param {google.firestore.v1.ListDocumentsResponse} [response] ListDocumentsResponse */ - + /** * Calls ListDocuments. * @function listDocuments @@ -3056,7 +3157,7 @@ Object.defineProperty(Firestore.prototype.listDocuments = function listDocuments(request, callback) { return this.rpcCall(listDocuments, $root.google.firestore.v1.ListDocumentsRequest, $root.google.firestore.v1.ListDocumentsResponse, request, callback); }, "name", { value: "ListDocuments" }); - + /** * Calls ListDocuments. * @function listDocuments @@ -3066,7 +3167,7 @@ * @returns {Promise} Promise * @variation 2 */ - + /** * Callback as used by {@link google.firestore.v1.Firestore#updateDocument}. * @memberof google.firestore.v1.Firestore @@ -3075,7 +3176,7 @@ * @param {Error|null} error Error, if any * @param {google.firestore.v1.Document} [response] Document */ - + /** * Calls UpdateDocument. * @function updateDocument @@ -3089,7 +3190,7 @@ Object.defineProperty(Firestore.prototype.updateDocument = function updateDocument(request, callback) { return this.rpcCall(updateDocument, $root.google.firestore.v1.UpdateDocumentRequest, $root.google.firestore.v1.Document, request, callback); }, "name", { value: "UpdateDocument" }); - + /** * Calls UpdateDocument. * @function updateDocument @@ -3099,7 +3200,7 @@ * @returns {Promise} Promise * @variation 2 */ - + /** * Callback as used by {@link google.firestore.v1.Firestore#deleteDocument}. * @memberof google.firestore.v1.Firestore @@ -3108,7 +3209,7 @@ * @param {Error|null} error Error, if any * @param {google.protobuf.Empty} [response] Empty */ - + /** * Calls DeleteDocument. * @function deleteDocument @@ -3122,7 +3223,7 @@ Object.defineProperty(Firestore.prototype.deleteDocument = function deleteDocument(request, callback) { return this.rpcCall(deleteDocument, $root.google.firestore.v1.DeleteDocumentRequest, $root.google.protobuf.Empty, request, callback); }, "name", { value: "DeleteDocument" }); - + /** * Calls DeleteDocument. * @function deleteDocument @@ -3132,7 +3233,7 @@ * @returns {Promise} Promise * @variation 2 */ - + /** * Callback as used by {@link google.firestore.v1.Firestore#batchGetDocuments}. * @memberof google.firestore.v1.Firestore @@ -3141,7 +3242,7 @@ * @param {Error|null} error Error, if any * @param {google.firestore.v1.BatchGetDocumentsResponse} [response] BatchGetDocumentsResponse */ - + /** * Calls BatchGetDocuments. * @function batchGetDocuments @@ -3155,7 +3256,7 @@ Object.defineProperty(Firestore.prototype.batchGetDocuments = function batchGetDocuments(request, callback) { return this.rpcCall(batchGetDocuments, $root.google.firestore.v1.BatchGetDocumentsRequest, $root.google.firestore.v1.BatchGetDocumentsResponse, request, callback); }, "name", { value: "BatchGetDocuments" }); - + /** * Calls BatchGetDocuments. * @function batchGetDocuments @@ -3165,7 +3266,7 @@ * @returns {Promise} Promise * @variation 2 */ - + /** * Callback as used by {@link google.firestore.v1.Firestore#beginTransaction}. * @memberof google.firestore.v1.Firestore @@ -3174,7 +3275,7 @@ * @param {Error|null} error Error, if any * @param {google.firestore.v1.BeginTransactionResponse} [response] BeginTransactionResponse */ - + /** * Calls BeginTransaction. * @function beginTransaction @@ -3188,7 +3289,7 @@ Object.defineProperty(Firestore.prototype.beginTransaction = function beginTransaction(request, callback) { return this.rpcCall(beginTransaction, $root.google.firestore.v1.BeginTransactionRequest, $root.google.firestore.v1.BeginTransactionResponse, request, callback); }, "name", { value: "BeginTransaction" }); - + /** * Calls BeginTransaction. * @function beginTransaction @@ -3198,7 +3299,7 @@ * @returns {Promise} Promise * @variation 2 */ - + /** * Callback as used by {@link google.firestore.v1.Firestore#commit}. * @memberof google.firestore.v1.Firestore @@ -3207,7 +3308,7 @@ * @param {Error|null} error Error, if any * @param {google.firestore.v1.CommitResponse} [response] CommitResponse */ - + /** * Calls Commit. * @function commit @@ -3221,7 +3322,7 @@ Object.defineProperty(Firestore.prototype.commit = function commit(request, callback) { return this.rpcCall(commit, $root.google.firestore.v1.CommitRequest, $root.google.firestore.v1.CommitResponse, request, callback); }, "name", { value: "Commit" }); - + /** * Calls Commit. * @function commit @@ -3231,7 +3332,7 @@ * @returns {Promise} Promise * @variation 2 */ - + /** * Callback as used by {@link google.firestore.v1.Firestore#rollback}. * @memberof google.firestore.v1.Firestore @@ -3240,7 +3341,7 @@ * @param {Error|null} error Error, if any * @param {google.protobuf.Empty} [response] Empty */ - + /** * Calls Rollback. * @function rollback @@ -3254,7 +3355,7 @@ Object.defineProperty(Firestore.prototype.rollback = function rollback(request, callback) { return this.rpcCall(rollback, $root.google.firestore.v1.RollbackRequest, $root.google.protobuf.Empty, request, callback); }, "name", { value: "Rollback" }); - + /** * Calls Rollback. * @function rollback @@ -3264,7 +3365,7 @@ * @returns {Promise} Promise * @variation 2 */ - + /** * Callback as used by {@link google.firestore.v1.Firestore#runQuery}. * @memberof google.firestore.v1.Firestore @@ -3273,7 +3374,7 @@ * @param {Error|null} error Error, if any * @param {google.firestore.v1.RunQueryResponse} [response] RunQueryResponse */ - + /** * Calls RunQuery. * @function runQuery @@ -3287,7 +3388,7 @@ Object.defineProperty(Firestore.prototype.runQuery = function runQuery(request, callback) { return this.rpcCall(runQuery, $root.google.firestore.v1.RunQueryRequest, $root.google.firestore.v1.RunQueryResponse, request, callback); }, "name", { value: "RunQuery" }); - + /** * Calls RunQuery. * @function runQuery @@ -3297,7 +3398,7 @@ * @returns {Promise} Promise * @variation 2 */ - + /** * Callback as used by {@link google.firestore.v1.Firestore#executePipeline}. * @memberof google.firestore.v1.Firestore @@ -3306,7 +3407,7 @@ * @param {Error|null} error Error, if any * @param {google.firestore.v1.ExecutePipelineResponse} [response] ExecutePipelineResponse */ - + /** * Calls ExecutePipeline. * @function executePipeline @@ -3320,7 +3421,7 @@ Object.defineProperty(Firestore.prototype.executePipeline = function executePipeline(request, callback) { return this.rpcCall(executePipeline, $root.google.firestore.v1.ExecutePipelineRequest, $root.google.firestore.v1.ExecutePipelineResponse, request, callback); }, "name", { value: "ExecutePipeline" }); - + /** * Calls ExecutePipeline. * @function executePipeline @@ -3330,7 +3431,7 @@ * @returns {Promise} Promise * @variation 2 */ - + /** * Callback as used by {@link google.firestore.v1.Firestore#runAggregationQuery}. * @memberof google.firestore.v1.Firestore @@ -3339,7 +3440,7 @@ * @param {Error|null} error Error, if any * @param {google.firestore.v1.RunAggregationQueryResponse} [response] RunAggregationQueryResponse */ - + /** * Calls RunAggregationQuery. * @function runAggregationQuery @@ -3353,7 +3454,7 @@ Object.defineProperty(Firestore.prototype.runAggregationQuery = function runAggregationQuery(request, callback) { return this.rpcCall(runAggregationQuery, $root.google.firestore.v1.RunAggregationQueryRequest, $root.google.firestore.v1.RunAggregationQueryResponse, request, callback); }, "name", { value: "RunAggregationQuery" }); - + /** * Calls RunAggregationQuery. * @function runAggregationQuery @@ -3363,7 +3464,7 @@ * @returns {Promise} Promise * @variation 2 */ - + /** * Callback as used by {@link google.firestore.v1.Firestore#partitionQuery}. * @memberof google.firestore.v1.Firestore @@ -3372,7 +3473,7 @@ * @param {Error|null} error Error, if any * @param {google.firestore.v1.PartitionQueryResponse} [response] PartitionQueryResponse */ - + /** * Calls PartitionQuery. * @function partitionQuery @@ -3386,7 +3487,7 @@ Object.defineProperty(Firestore.prototype.partitionQuery = function partitionQuery(request, callback) { return this.rpcCall(partitionQuery, $root.google.firestore.v1.PartitionQueryRequest, $root.google.firestore.v1.PartitionQueryResponse, request, callback); }, "name", { value: "PartitionQuery" }); - + /** * Calls PartitionQuery. * @function partitionQuery @@ -3396,7 +3497,7 @@ * @returns {Promise} Promise * @variation 2 */ - + /** * Callback as used by {@link google.firestore.v1.Firestore#write}. * @memberof google.firestore.v1.Firestore @@ -3405,7 +3506,7 @@ * @param {Error|null} error Error, if any * @param {google.firestore.v1.WriteResponse} [response] WriteResponse */ - + /** * Calls Write. * @function write @@ -3419,7 +3520,7 @@ Object.defineProperty(Firestore.prototype.write = function write(request, callback) { return this.rpcCall(write, $root.google.firestore.v1.WriteRequest, $root.google.firestore.v1.WriteResponse, request, callback); }, "name", { value: "Write" }); - + /** * Calls Write. * @function write @@ -3429,7 +3530,7 @@ * @returns {Promise} Promise * @variation 2 */ - + /** * Callback as used by {@link google.firestore.v1.Firestore#listen}. * @memberof google.firestore.v1.Firestore @@ -3438,7 +3539,7 @@ * @param {Error|null} error Error, if any * @param {google.firestore.v1.ListenResponse} [response] ListenResponse */ - + /** * Calls Listen. * @function listen @@ -3452,7 +3553,7 @@ Object.defineProperty(Firestore.prototype.listen = function listen(request, callback) { return this.rpcCall(listen, $root.google.firestore.v1.ListenRequest, $root.google.firestore.v1.ListenResponse, request, callback); }, "name", { value: "Listen" }); - + /** * Calls Listen. * @function listen @@ -3462,7 +3563,7 @@ * @returns {Promise} Promise * @variation 2 */ - + /** * Callback as used by {@link google.firestore.v1.Firestore#listCollectionIds}. * @memberof google.firestore.v1.Firestore @@ -3471,7 +3572,7 @@ * @param {Error|null} error Error, if any * @param {google.firestore.v1.ListCollectionIdsResponse} [response] ListCollectionIdsResponse */ - + /** * Calls ListCollectionIds. * @function listCollectionIds @@ -3485,7 +3586,7 @@ Object.defineProperty(Firestore.prototype.listCollectionIds = function listCollectionIds(request, callback) { return this.rpcCall(listCollectionIds, $root.google.firestore.v1.ListCollectionIdsRequest, $root.google.firestore.v1.ListCollectionIdsResponse, request, callback); }, "name", { value: "ListCollectionIds" }); - + /** * Calls ListCollectionIds. * @function listCollectionIds @@ -3495,7 +3596,7 @@ * @returns {Promise} Promise * @variation 2 */ - + /** * Callback as used by {@link google.firestore.v1.Firestore#batchWrite}. * @memberof google.firestore.v1.Firestore @@ -3504,7 +3605,7 @@ * @param {Error|null} error Error, if any * @param {google.firestore.v1.BatchWriteResponse} [response] BatchWriteResponse */ - + /** * Calls BatchWrite. * @function batchWrite @@ -3518,7 +3619,7 @@ Object.defineProperty(Firestore.prototype.batchWrite = function batchWrite(request, callback) { return this.rpcCall(batchWrite, $root.google.firestore.v1.BatchWriteRequest, $root.google.firestore.v1.BatchWriteResponse, request, callback); }, "name", { value: "BatchWrite" }); - + /** * Calls BatchWrite. * @function batchWrite @@ -3528,7 +3629,7 @@ * @returns {Promise} Promise * @variation 2 */ - + /** * Callback as used by {@link google.firestore.v1.Firestore#createDocument}. * @memberof google.firestore.v1.Firestore @@ -3537,7 +3638,7 @@ * @param {Error|null} error Error, if any * @param {google.firestore.v1.Document} [response] Document */ - + /** * Calls CreateDocument. * @function createDocument @@ -3551,7 +3652,7 @@ Object.defineProperty(Firestore.prototype.createDocument = function createDocument(request, callback) { return this.rpcCall(createDocument, $root.google.firestore.v1.CreateDocumentRequest, $root.google.firestore.v1.Document, request, callback); }, "name", { value: "CreateDocument" }); - + /** * Calls CreateDocument. * @function createDocument @@ -3561,12 +3662,12 @@ * @returns {Promise} Promise * @variation 2 */ - + return Firestore; })(); - + v1.GetDocumentRequest = (function() { - + /** * Properties of a GetDocumentRequest. * @memberof google.firestore.v1 @@ -3576,7 +3677,7 @@ * @property {Uint8Array|null} [transaction] GetDocumentRequest transaction * @property {google.protobuf.ITimestamp|null} [readTime] GetDocumentRequest readTime */ - + /** * Constructs a new GetDocumentRequest. * @memberof google.firestore.v1 @@ -3591,7 +3692,7 @@ if (properties[keys[i]] != null) this[keys[i]] = properties[keys[i]]; } - + /** * GetDocumentRequest name. * @member {string} name @@ -3599,7 +3700,7 @@ * @instance */ GetDocumentRequest.prototype.name = ""; - + /** * GetDocumentRequest mask. * @member {google.firestore.v1.IDocumentMask|null|undefined} mask @@ -3607,7 +3708,7 @@ * @instance */ GetDocumentRequest.prototype.mask = null; - + /** * GetDocumentRequest transaction. * @member {Uint8Array|null|undefined} transaction @@ -3615,7 +3716,7 @@ * @instance */ GetDocumentRequest.prototype.transaction = null; - + /** * GetDocumentRequest readTime. * @member {google.protobuf.ITimestamp|null|undefined} readTime @@ -3623,10 +3724,10 @@ * @instance */ GetDocumentRequest.prototype.readTime = null; - + // OneOf field names bound to virtual getters and setters var $oneOfFields; - + /** * GetDocumentRequest consistencySelector. * @member {"transaction"|"readTime"|undefined} consistencySelector @@ -3637,7 +3738,7 @@ get: $util.oneOfGetter($oneOfFields = ["transaction", "readTime"]), set: $util.oneOfSetter($oneOfFields) }); - + /** * Creates a GetDocumentRequest message from a plain object. Also converts values to their respective internal types. * @function fromObject @@ -3669,7 +3770,7 @@ } return message; }; - + /** * Creates a plain object from a GetDocumentRequest message. Also converts values to other types if specified. * @function toObject @@ -3703,7 +3804,7 @@ } return object; }; - + /** * Converts this GetDocumentRequest to JSON. * @function toJSON @@ -3714,7 +3815,7 @@ GetDocumentRequest.prototype.toJSON = function toJSON() { return this.constructor.toObject(this, $protobuf.util.toJSONOptions); }; - + /** * Gets the default type url for GetDocumentRequest * @function getTypeUrl @@ -3729,12 +3830,12 @@ } return typeUrlPrefix + "/google.firestore.v1.GetDocumentRequest"; }; - + return GetDocumentRequest; })(); - + v1.ListDocumentsRequest = (function() { - + /** * Properties of a ListDocumentsRequest. * @memberof google.firestore.v1 @@ -3749,7 +3850,7 @@ * @property {google.protobuf.ITimestamp|null} [readTime] ListDocumentsRequest readTime * @property {boolean|null} [showMissing] ListDocumentsRequest showMissing */ - + /** * Constructs a new ListDocumentsRequest. * @memberof google.firestore.v1 @@ -3764,7 +3865,7 @@ if (properties[keys[i]] != null) this[keys[i]] = properties[keys[i]]; } - + /** * ListDocumentsRequest parent. * @member {string} parent @@ -3772,7 +3873,7 @@ * @instance */ ListDocumentsRequest.prototype.parent = ""; - + /** * ListDocumentsRequest collectionId. * @member {string} collectionId @@ -3780,7 +3881,7 @@ * @instance */ ListDocumentsRequest.prototype.collectionId = ""; - + /** * ListDocumentsRequest pageSize. * @member {number} pageSize @@ -3788,7 +3889,7 @@ * @instance */ ListDocumentsRequest.prototype.pageSize = 0; - + /** * ListDocumentsRequest pageToken. * @member {string} pageToken @@ -3796,7 +3897,7 @@ * @instance */ ListDocumentsRequest.prototype.pageToken = ""; - + /** * ListDocumentsRequest orderBy. * @member {string} orderBy @@ -3804,7 +3905,7 @@ * @instance */ ListDocumentsRequest.prototype.orderBy = ""; - + /** * ListDocumentsRequest mask. * @member {google.firestore.v1.IDocumentMask|null|undefined} mask @@ -3812,7 +3913,7 @@ * @instance */ ListDocumentsRequest.prototype.mask = null; - + /** * ListDocumentsRequest transaction. * @member {Uint8Array|null|undefined} transaction @@ -3820,7 +3921,7 @@ * @instance */ ListDocumentsRequest.prototype.transaction = null; - + /** * ListDocumentsRequest readTime. * @member {google.protobuf.ITimestamp|null|undefined} readTime @@ -3828,7 +3929,7 @@ * @instance */ ListDocumentsRequest.prototype.readTime = null; - + /** * ListDocumentsRequest showMissing. * @member {boolean} showMissing @@ -3836,10 +3937,10 @@ * @instance */ ListDocumentsRequest.prototype.showMissing = false; - + // OneOf field names bound to virtual getters and setters var $oneOfFields; - + /** * ListDocumentsRequest consistencySelector. * @member {"transaction"|"readTime"|undefined} consistencySelector @@ -3850,7 +3951,7 @@ get: $util.oneOfGetter($oneOfFields = ["transaction", "readTime"]), set: $util.oneOfSetter($oneOfFields) }); - + /** * Creates a ListDocumentsRequest message from a plain object. Also converts values to their respective internal types. * @function fromObject @@ -3892,7 +3993,7 @@ message.showMissing = Boolean(object.showMissing); return message; }; - + /** * Creates a plain object from a ListDocumentsRequest message. Also converts values to other types if specified. * @function toObject @@ -3941,7 +4042,7 @@ object.showMissing = message.showMissing; return object; }; - + /** * Converts this ListDocumentsRequest to JSON. * @function toJSON @@ -3952,7 +4053,7 @@ ListDocumentsRequest.prototype.toJSON = function toJSON() { return this.constructor.toObject(this, $protobuf.util.toJSONOptions); }; - + /** * Gets the default type url for ListDocumentsRequest * @function getTypeUrl @@ -3967,12 +4068,12 @@ } return typeUrlPrefix + "/google.firestore.v1.ListDocumentsRequest"; }; - + return ListDocumentsRequest; })(); - + v1.ListDocumentsResponse = (function() { - + /** * Properties of a ListDocumentsResponse. * @memberof google.firestore.v1 @@ -3980,7 +4081,7 @@ * @property {Array.|null} [documents] ListDocumentsResponse documents * @property {string|null} [nextPageToken] ListDocumentsResponse nextPageToken */ - + /** * Constructs a new ListDocumentsResponse. * @memberof google.firestore.v1 @@ -3996,7 +4097,7 @@ if (properties[keys[i]] != null) this[keys[i]] = properties[keys[i]]; } - + /** * ListDocumentsResponse documents. * @member {Array.} documents @@ -4004,7 +4105,7 @@ * @instance */ ListDocumentsResponse.prototype.documents = $util.emptyArray; - + /** * ListDocumentsResponse nextPageToken. * @member {string} nextPageToken @@ -4012,7 +4113,7 @@ * @instance */ ListDocumentsResponse.prototype.nextPageToken = ""; - + /** * Creates a ListDocumentsResponse message from a plain object. Also converts values to their respective internal types. * @function fromObject @@ -4039,7 +4140,7 @@ message.nextPageToken = String(object.nextPageToken); return message; }; - + /** * Creates a plain object from a ListDocumentsResponse message. Also converts values to other types if specified. * @function toObject @@ -4066,7 +4167,7 @@ object.nextPageToken = message.nextPageToken; return object; }; - + /** * Converts this ListDocumentsResponse to JSON. * @function toJSON @@ -4077,7 +4178,7 @@ ListDocumentsResponse.prototype.toJSON = function toJSON() { return this.constructor.toObject(this, $protobuf.util.toJSONOptions); }; - + /** * Gets the default type url for ListDocumentsResponse * @function getTypeUrl @@ -4092,12 +4193,12 @@ } return typeUrlPrefix + "/google.firestore.v1.ListDocumentsResponse"; }; - + return ListDocumentsResponse; })(); - + v1.CreateDocumentRequest = (function() { - + /** * Properties of a CreateDocumentRequest. * @memberof google.firestore.v1 @@ -4108,7 +4209,7 @@ * @property {google.firestore.v1.IDocument|null} [document] CreateDocumentRequest document * @property {google.firestore.v1.IDocumentMask|null} [mask] CreateDocumentRequest mask */ - + /** * Constructs a new CreateDocumentRequest. * @memberof google.firestore.v1 @@ -4123,7 +4224,7 @@ if (properties[keys[i]] != null) this[keys[i]] = properties[keys[i]]; } - + /** * CreateDocumentRequest parent. * @member {string} parent @@ -4131,7 +4232,7 @@ * @instance */ CreateDocumentRequest.prototype.parent = ""; - + /** * CreateDocumentRequest collectionId. * @member {string} collectionId @@ -4139,7 +4240,7 @@ * @instance */ CreateDocumentRequest.prototype.collectionId = ""; - + /** * CreateDocumentRequest documentId. * @member {string} documentId @@ -4147,7 +4248,7 @@ * @instance */ CreateDocumentRequest.prototype.documentId = ""; - + /** * CreateDocumentRequest document. * @member {google.firestore.v1.IDocument|null|undefined} document @@ -4155,7 +4256,7 @@ * @instance */ CreateDocumentRequest.prototype.document = null; - + /** * CreateDocumentRequest mask. * @member {google.firestore.v1.IDocumentMask|null|undefined} mask @@ -4163,7 +4264,7 @@ * @instance */ CreateDocumentRequest.prototype.mask = null; - + /** * Creates a CreateDocumentRequest message from a plain object. Also converts values to their respective internal types. * @function fromObject @@ -4194,7 +4295,7 @@ } return message; }; - + /** * Creates a plain object from a CreateDocumentRequest message. Also converts values to other types if specified. * @function toObject @@ -4227,7 +4328,7 @@ object.mask = $root.google.firestore.v1.DocumentMask.toObject(message.mask, options); return object; }; - + /** * Converts this CreateDocumentRequest to JSON. * @function toJSON @@ -4238,7 +4339,7 @@ CreateDocumentRequest.prototype.toJSON = function toJSON() { return this.constructor.toObject(this, $protobuf.util.toJSONOptions); }; - + /** * Gets the default type url for CreateDocumentRequest * @function getTypeUrl @@ -4253,12 +4354,12 @@ } return typeUrlPrefix + "/google.firestore.v1.CreateDocumentRequest"; }; - + return CreateDocumentRequest; })(); - + v1.UpdateDocumentRequest = (function() { - + /** * Properties of an UpdateDocumentRequest. * @memberof google.firestore.v1 @@ -4268,7 +4369,7 @@ * @property {google.firestore.v1.IDocumentMask|null} [mask] UpdateDocumentRequest mask * @property {google.firestore.v1.IPrecondition|null} [currentDocument] UpdateDocumentRequest currentDocument */ - + /** * Constructs a new UpdateDocumentRequest. * @memberof google.firestore.v1 @@ -4283,7 +4384,7 @@ if (properties[keys[i]] != null) this[keys[i]] = properties[keys[i]]; } - + /** * UpdateDocumentRequest document. * @member {google.firestore.v1.IDocument|null|undefined} document @@ -4291,7 +4392,7 @@ * @instance */ UpdateDocumentRequest.prototype.document = null; - + /** * UpdateDocumentRequest updateMask. * @member {google.firestore.v1.IDocumentMask|null|undefined} updateMask @@ -4299,7 +4400,7 @@ * @instance */ UpdateDocumentRequest.prototype.updateMask = null; - + /** * UpdateDocumentRequest mask. * @member {google.firestore.v1.IDocumentMask|null|undefined} mask @@ -4307,7 +4408,7 @@ * @instance */ UpdateDocumentRequest.prototype.mask = null; - + /** * UpdateDocumentRequest currentDocument. * @member {google.firestore.v1.IPrecondition|null|undefined} currentDocument @@ -4315,7 +4416,7 @@ * @instance */ UpdateDocumentRequest.prototype.currentDocument = null; - + /** * Creates an UpdateDocumentRequest message from a plain object. Also converts values to their respective internal types. * @function fromObject @@ -4350,7 +4451,7 @@ } return message; }; - + /** * Creates a plain object from an UpdateDocumentRequest message. Also converts values to other types if specified. * @function toObject @@ -4380,7 +4481,7 @@ object.currentDocument = $root.google.firestore.v1.Precondition.toObject(message.currentDocument, options); return object; }; - + /** * Converts this UpdateDocumentRequest to JSON. * @function toJSON @@ -4391,7 +4492,7 @@ UpdateDocumentRequest.prototype.toJSON = function toJSON() { return this.constructor.toObject(this, $protobuf.util.toJSONOptions); }; - + /** * Gets the default type url for UpdateDocumentRequest * @function getTypeUrl @@ -4406,12 +4507,12 @@ } return typeUrlPrefix + "/google.firestore.v1.UpdateDocumentRequest"; }; - + return UpdateDocumentRequest; })(); - + v1.DeleteDocumentRequest = (function() { - + /** * Properties of a DeleteDocumentRequest. * @memberof google.firestore.v1 @@ -4419,7 +4520,7 @@ * @property {string|null} [name] DeleteDocumentRequest name * @property {google.firestore.v1.IPrecondition|null} [currentDocument] DeleteDocumentRequest currentDocument */ - + /** * Constructs a new DeleteDocumentRequest. * @memberof google.firestore.v1 @@ -4434,7 +4535,7 @@ if (properties[keys[i]] != null) this[keys[i]] = properties[keys[i]]; } - + /** * DeleteDocumentRequest name. * @member {string} name @@ -4442,7 +4543,7 @@ * @instance */ DeleteDocumentRequest.prototype.name = ""; - + /** * DeleteDocumentRequest currentDocument. * @member {google.firestore.v1.IPrecondition|null|undefined} currentDocument @@ -4450,7 +4551,7 @@ * @instance */ DeleteDocumentRequest.prototype.currentDocument = null; - + /** * Creates a DeleteDocumentRequest message from a plain object. Also converts values to their respective internal types. * @function fromObject @@ -4472,7 +4573,7 @@ } return message; }; - + /** * Creates a plain object from a DeleteDocumentRequest message. Also converts values to other types if specified. * @function toObject @@ -4496,7 +4597,7 @@ object.currentDocument = $root.google.firestore.v1.Precondition.toObject(message.currentDocument, options); return object; }; - + /** * Converts this DeleteDocumentRequest to JSON. * @function toJSON @@ -4507,7 +4608,7 @@ DeleteDocumentRequest.prototype.toJSON = function toJSON() { return this.constructor.toObject(this, $protobuf.util.toJSONOptions); }; - + /** * Gets the default type url for DeleteDocumentRequest * @function getTypeUrl @@ -4522,12 +4623,12 @@ } return typeUrlPrefix + "/google.firestore.v1.DeleteDocumentRequest"; }; - + return DeleteDocumentRequest; })(); - + v1.BatchGetDocumentsRequest = (function() { - + /** * Properties of a BatchGetDocumentsRequest. * @memberof google.firestore.v1 @@ -4539,7 +4640,7 @@ * @property {google.firestore.v1.ITransactionOptions|null} [newTransaction] BatchGetDocumentsRequest newTransaction * @property {google.protobuf.ITimestamp|null} [readTime] BatchGetDocumentsRequest readTime */ - + /** * Constructs a new BatchGetDocumentsRequest. * @memberof google.firestore.v1 @@ -4555,7 +4656,7 @@ if (properties[keys[i]] != null) this[keys[i]] = properties[keys[i]]; } - + /** * BatchGetDocumentsRequest database. * @member {string} database @@ -4563,7 +4664,7 @@ * @instance */ BatchGetDocumentsRequest.prototype.database = ""; - + /** * BatchGetDocumentsRequest documents. * @member {Array.} documents @@ -4571,7 +4672,7 @@ * @instance */ BatchGetDocumentsRequest.prototype.documents = $util.emptyArray; - + /** * BatchGetDocumentsRequest mask. * @member {google.firestore.v1.IDocumentMask|null|undefined} mask @@ -4579,7 +4680,7 @@ * @instance */ BatchGetDocumentsRequest.prototype.mask = null; - + /** * BatchGetDocumentsRequest transaction. * @member {Uint8Array|null|undefined} transaction @@ -4587,7 +4688,7 @@ * @instance */ BatchGetDocumentsRequest.prototype.transaction = null; - + /** * BatchGetDocumentsRequest newTransaction. * @member {google.firestore.v1.ITransactionOptions|null|undefined} newTransaction @@ -4595,7 +4696,7 @@ * @instance */ BatchGetDocumentsRequest.prototype.newTransaction = null; - + /** * BatchGetDocumentsRequest readTime. * @member {google.protobuf.ITimestamp|null|undefined} readTime @@ -4603,10 +4704,10 @@ * @instance */ BatchGetDocumentsRequest.prototype.readTime = null; - + // OneOf field names bound to virtual getters and setters var $oneOfFields; - + /** * BatchGetDocumentsRequest consistencySelector. * @member {"transaction"|"newTransaction"|"readTime"|undefined} consistencySelector @@ -4617,7 +4718,7 @@ get: $util.oneOfGetter($oneOfFields = ["transaction", "newTransaction", "readTime"]), set: $util.oneOfSetter($oneOfFields) }); - + /** * Creates a BatchGetDocumentsRequest message from a plain object. Also converts values to their respective internal types. * @function fromObject @@ -4661,7 +4762,7 @@ } return message; }; - + /** * Creates a plain object from a BatchGetDocumentsRequest message. Also converts values to other types if specified. * @function toObject @@ -4707,7 +4808,7 @@ } return object; }; - + /** * Converts this BatchGetDocumentsRequest to JSON. * @function toJSON @@ -4718,7 +4819,7 @@ BatchGetDocumentsRequest.prototype.toJSON = function toJSON() { return this.constructor.toObject(this, $protobuf.util.toJSONOptions); }; - + /** * Gets the default type url for BatchGetDocumentsRequest * @function getTypeUrl @@ -4733,12 +4834,12 @@ } return typeUrlPrefix + "/google.firestore.v1.BatchGetDocumentsRequest"; }; - + return BatchGetDocumentsRequest; })(); - + v1.BatchGetDocumentsResponse = (function() { - + /** * Properties of a BatchGetDocumentsResponse. * @memberof google.firestore.v1 @@ -4748,7 +4849,7 @@ * @property {Uint8Array|null} [transaction] BatchGetDocumentsResponse transaction * @property {google.protobuf.ITimestamp|null} [readTime] BatchGetDocumentsResponse readTime */ - + /** * Constructs a new BatchGetDocumentsResponse. * @memberof google.firestore.v1 @@ -4763,7 +4864,7 @@ if (properties[keys[i]] != null) this[keys[i]] = properties[keys[i]]; } - + /** * BatchGetDocumentsResponse found. * @member {google.firestore.v1.IDocument|null|undefined} found @@ -4771,7 +4872,7 @@ * @instance */ BatchGetDocumentsResponse.prototype.found = null; - + /** * BatchGetDocumentsResponse missing. * @member {string|null|undefined} missing @@ -4779,7 +4880,7 @@ * @instance */ BatchGetDocumentsResponse.prototype.missing = null; - + /** * BatchGetDocumentsResponse transaction. * @member {Uint8Array} transaction @@ -4787,7 +4888,7 @@ * @instance */ BatchGetDocumentsResponse.prototype.transaction = $util.newBuffer([]); - + /** * BatchGetDocumentsResponse readTime. * @member {google.protobuf.ITimestamp|null|undefined} readTime @@ -4795,10 +4896,10 @@ * @instance */ BatchGetDocumentsResponse.prototype.readTime = null; - + // OneOf field names bound to virtual getters and setters var $oneOfFields; - + /** * BatchGetDocumentsResponse result. * @member {"found"|"missing"|undefined} result @@ -4809,7 +4910,7 @@ get: $util.oneOfGetter($oneOfFields = ["found", "missing"]), set: $util.oneOfSetter($oneOfFields) }); - + /** * Creates a BatchGetDocumentsResponse message from a plain object. Also converts values to their respective internal types. * @function fromObject @@ -4841,7 +4942,7 @@ } return message; }; - + /** * Creates a plain object from a BatchGetDocumentsResponse message. Also converts values to other types if specified. * @function toObject @@ -4881,7 +4982,7 @@ object.readTime = $root.google.protobuf.Timestamp.toObject(message.readTime, options); return object; }; - + /** * Converts this BatchGetDocumentsResponse to JSON. * @function toJSON @@ -4892,7 +4993,7 @@ BatchGetDocumentsResponse.prototype.toJSON = function toJSON() { return this.constructor.toObject(this, $protobuf.util.toJSONOptions); }; - + /** * Gets the default type url for BatchGetDocumentsResponse * @function getTypeUrl @@ -4907,12 +5008,12 @@ } return typeUrlPrefix + "/google.firestore.v1.BatchGetDocumentsResponse"; }; - + return BatchGetDocumentsResponse; })(); - + v1.BeginTransactionRequest = (function() { - + /** * Properties of a BeginTransactionRequest. * @memberof google.firestore.v1 @@ -4920,7 +5021,7 @@ * @property {string|null} [database] BeginTransactionRequest database * @property {google.firestore.v1.ITransactionOptions|null} [options] BeginTransactionRequest options */ - + /** * Constructs a new BeginTransactionRequest. * @memberof google.firestore.v1 @@ -4935,7 +5036,7 @@ if (properties[keys[i]] != null) this[keys[i]] = properties[keys[i]]; } - + /** * BeginTransactionRequest database. * @member {string} database @@ -4943,7 +5044,7 @@ * @instance */ BeginTransactionRequest.prototype.database = ""; - + /** * BeginTransactionRequest options. * @member {google.firestore.v1.ITransactionOptions|null|undefined} options @@ -4951,7 +5052,7 @@ * @instance */ BeginTransactionRequest.prototype.options = null; - + /** * Creates a BeginTransactionRequest message from a plain object. Also converts values to their respective internal types. * @function fromObject @@ -4973,7 +5074,7 @@ } return message; }; - + /** * Creates a plain object from a BeginTransactionRequest message. Also converts values to other types if specified. * @function toObject @@ -4997,7 +5098,7 @@ object.options = $root.google.firestore.v1.TransactionOptions.toObject(message.options, options); return object; }; - + /** * Converts this BeginTransactionRequest to JSON. * @function toJSON @@ -5008,7 +5109,7 @@ BeginTransactionRequest.prototype.toJSON = function toJSON() { return this.constructor.toObject(this, $protobuf.util.toJSONOptions); }; - + /** * Gets the default type url for BeginTransactionRequest * @function getTypeUrl @@ -5023,19 +5124,19 @@ } return typeUrlPrefix + "/google.firestore.v1.BeginTransactionRequest"; }; - + return BeginTransactionRequest; })(); - + v1.BeginTransactionResponse = (function() { - + /** * Properties of a BeginTransactionResponse. * @memberof google.firestore.v1 * @interface IBeginTransactionResponse * @property {Uint8Array|null} [transaction] BeginTransactionResponse transaction */ - + /** * Constructs a new BeginTransactionResponse. * @memberof google.firestore.v1 @@ -5050,7 +5151,7 @@ if (properties[keys[i]] != null) this[keys[i]] = properties[keys[i]]; } - + /** * BeginTransactionResponse transaction. * @member {Uint8Array} transaction @@ -5058,7 +5159,7 @@ * @instance */ BeginTransactionResponse.prototype.transaction = $util.newBuffer([]); - + /** * Creates a BeginTransactionResponse message from a plain object. Also converts values to their respective internal types. * @function fromObject @@ -5078,7 +5179,7 @@ message.transaction = object.transaction; return message; }; - + /** * Creates a plain object from a BeginTransactionResponse message. Also converts values to other types if specified. * @function toObject @@ -5104,7 +5205,7 @@ object.transaction = options.bytes === String ? $util.base64.encode(message.transaction, 0, message.transaction.length) : options.bytes === Array ? Array.prototype.slice.call(message.transaction) : message.transaction; return object; }; - + /** * Converts this BeginTransactionResponse to JSON. * @function toJSON @@ -5115,7 +5216,7 @@ BeginTransactionResponse.prototype.toJSON = function toJSON() { return this.constructor.toObject(this, $protobuf.util.toJSONOptions); }; - + /** * Gets the default type url for BeginTransactionResponse * @function getTypeUrl @@ -5130,12 +5231,12 @@ } return typeUrlPrefix + "/google.firestore.v1.BeginTransactionResponse"; }; - + return BeginTransactionResponse; })(); - + v1.CommitRequest = (function() { - + /** * Properties of a CommitRequest. * @memberof google.firestore.v1 @@ -5144,7 +5245,7 @@ * @property {Array.|null} [writes] CommitRequest writes * @property {Uint8Array|null} [transaction] CommitRequest transaction */ - + /** * Constructs a new CommitRequest. * @memberof google.firestore.v1 @@ -5160,7 +5261,7 @@ if (properties[keys[i]] != null) this[keys[i]] = properties[keys[i]]; } - + /** * CommitRequest database. * @member {string} database @@ -5168,7 +5269,7 @@ * @instance */ CommitRequest.prototype.database = ""; - + /** * CommitRequest writes. * @member {Array.} writes @@ -5176,7 +5277,7 @@ * @instance */ CommitRequest.prototype.writes = $util.emptyArray; - + /** * CommitRequest transaction. * @member {Uint8Array} transaction @@ -5184,7 +5285,7 @@ * @instance */ CommitRequest.prototype.transaction = $util.newBuffer([]); - + /** * Creates a CommitRequest message from a plain object. Also converts values to their respective internal types. * @function fromObject @@ -5216,7 +5317,7 @@ message.transaction = object.transaction; return message; }; - + /** * Creates a plain object from a CommitRequest message. Also converts values to other types if specified. * @function toObject @@ -5253,7 +5354,7 @@ object.transaction = options.bytes === String ? $util.base64.encode(message.transaction, 0, message.transaction.length) : options.bytes === Array ? Array.prototype.slice.call(message.transaction) : message.transaction; return object; }; - + /** * Converts this CommitRequest to JSON. * @function toJSON @@ -5264,7 +5365,7 @@ CommitRequest.prototype.toJSON = function toJSON() { return this.constructor.toObject(this, $protobuf.util.toJSONOptions); }; - + /** * Gets the default type url for CommitRequest * @function getTypeUrl @@ -5279,12 +5380,12 @@ } return typeUrlPrefix + "/google.firestore.v1.CommitRequest"; }; - + return CommitRequest; })(); - + v1.CommitResponse = (function() { - + /** * Properties of a CommitResponse. * @memberof google.firestore.v1 @@ -5292,7 +5393,7 @@ * @property {Array.|null} [writeResults] CommitResponse writeResults * @property {google.protobuf.ITimestamp|null} [commitTime] CommitResponse commitTime */ - + /** * Constructs a new CommitResponse. * @memberof google.firestore.v1 @@ -5308,7 +5409,7 @@ if (properties[keys[i]] != null) this[keys[i]] = properties[keys[i]]; } - + /** * CommitResponse writeResults. * @member {Array.} writeResults @@ -5316,7 +5417,7 @@ * @instance */ CommitResponse.prototype.writeResults = $util.emptyArray; - + /** * CommitResponse commitTime. * @member {google.protobuf.ITimestamp|null|undefined} commitTime @@ -5324,7 +5425,7 @@ * @instance */ CommitResponse.prototype.commitTime = null; - + /** * Creates a CommitResponse message from a plain object. Also converts values to their respective internal types. * @function fromObject @@ -5354,7 +5455,7 @@ } return message; }; - + /** * Creates a plain object from a CommitResponse message. Also converts values to other types if specified. * @function toObject @@ -5381,7 +5482,7 @@ object.commitTime = $root.google.protobuf.Timestamp.toObject(message.commitTime, options); return object; }; - + /** * Converts this CommitResponse to JSON. * @function toJSON @@ -5392,7 +5493,7 @@ CommitResponse.prototype.toJSON = function toJSON() { return this.constructor.toObject(this, $protobuf.util.toJSONOptions); }; - + /** * Gets the default type url for CommitResponse * @function getTypeUrl @@ -5407,12 +5508,12 @@ } return typeUrlPrefix + "/google.firestore.v1.CommitResponse"; }; - + return CommitResponse; })(); - + v1.RollbackRequest = (function() { - + /** * Properties of a RollbackRequest. * @memberof google.firestore.v1 @@ -5420,7 +5521,7 @@ * @property {string|null} [database] RollbackRequest database * @property {Uint8Array|null} [transaction] RollbackRequest transaction */ - + /** * Constructs a new RollbackRequest. * @memberof google.firestore.v1 @@ -5435,7 +5536,7 @@ if (properties[keys[i]] != null) this[keys[i]] = properties[keys[i]]; } - + /** * RollbackRequest database. * @member {string} database @@ -5443,7 +5544,7 @@ * @instance */ RollbackRequest.prototype.database = ""; - + /** * RollbackRequest transaction. * @member {Uint8Array} transaction @@ -5451,7 +5552,7 @@ * @instance */ RollbackRequest.prototype.transaction = $util.newBuffer([]); - + /** * Creates a RollbackRequest message from a plain object. Also converts values to their respective internal types. * @function fromObject @@ -5473,7 +5574,7 @@ message.transaction = object.transaction; return message; }; - + /** * Creates a plain object from a RollbackRequest message. Also converts values to other types if specified. * @function toObject @@ -5503,7 +5604,7 @@ object.transaction = options.bytes === String ? $util.base64.encode(message.transaction, 0, message.transaction.length) : options.bytes === Array ? Array.prototype.slice.call(message.transaction) : message.transaction; return object; }; - + /** * Converts this RollbackRequest to JSON. * @function toJSON @@ -5514,7 +5615,7 @@ RollbackRequest.prototype.toJSON = function toJSON() { return this.constructor.toObject(this, $protobuf.util.toJSONOptions); }; - + /** * Gets the default type url for RollbackRequest * @function getTypeUrl @@ -5529,12 +5630,12 @@ } return typeUrlPrefix + "/google.firestore.v1.RollbackRequest"; }; - + return RollbackRequest; })(); - + v1.RunQueryRequest = (function() { - + /** * Properties of a RunQueryRequest. * @memberof google.firestore.v1 @@ -5546,7 +5647,7 @@ * @property {google.protobuf.ITimestamp|null} [readTime] RunQueryRequest readTime * @property {google.firestore.v1.IExplainOptions|null} [explainOptions] RunQueryRequest explainOptions */ - + /** * Constructs a new RunQueryRequest. * @memberof google.firestore.v1 @@ -5561,7 +5662,7 @@ if (properties[keys[i]] != null) this[keys[i]] = properties[keys[i]]; } - + /** * RunQueryRequest parent. * @member {string} parent @@ -5569,7 +5670,7 @@ * @instance */ RunQueryRequest.prototype.parent = ""; - + /** * RunQueryRequest structuredQuery. * @member {google.firestore.v1.IStructuredQuery|null|undefined} structuredQuery @@ -5577,7 +5678,7 @@ * @instance */ RunQueryRequest.prototype.structuredQuery = null; - + /** * RunQueryRequest transaction. * @member {Uint8Array|null|undefined} transaction @@ -5585,7 +5686,7 @@ * @instance */ RunQueryRequest.prototype.transaction = null; - + /** * RunQueryRequest newTransaction. * @member {google.firestore.v1.ITransactionOptions|null|undefined} newTransaction @@ -5593,7 +5694,7 @@ * @instance */ RunQueryRequest.prototype.newTransaction = null; - + /** * RunQueryRequest readTime. * @member {google.protobuf.ITimestamp|null|undefined} readTime @@ -5601,7 +5702,7 @@ * @instance */ RunQueryRequest.prototype.readTime = null; - + /** * RunQueryRequest explainOptions. * @member {google.firestore.v1.IExplainOptions|null|undefined} explainOptions @@ -5609,10 +5710,10 @@ * @instance */ RunQueryRequest.prototype.explainOptions = null; - + // OneOf field names bound to virtual getters and setters var $oneOfFields; - + /** * RunQueryRequest queryType. * @member {"structuredQuery"|undefined} queryType @@ -5623,7 +5724,7 @@ get: $util.oneOfGetter($oneOfFields = ["structuredQuery"]), set: $util.oneOfSetter($oneOfFields) }); - + /** * RunQueryRequest consistencySelector. * @member {"transaction"|"newTransaction"|"readTime"|undefined} consistencySelector @@ -5634,7 +5735,7 @@ get: $util.oneOfGetter($oneOfFields = ["transaction", "newTransaction", "readTime"]), set: $util.oneOfSetter($oneOfFields) }); - + /** * Creates a RunQueryRequest message from a plain object. Also converts values to their respective internal types. * @function fromObject @@ -5676,7 +5777,7 @@ } return message; }; - + /** * Creates a plain object from a RunQueryRequest message. Also converts values to other types if specified. * @function toObject @@ -5720,7 +5821,7 @@ object.explainOptions = $root.google.firestore.v1.ExplainOptions.toObject(message.explainOptions, options); return object; }; - + /** * Converts this RunQueryRequest to JSON. * @function toJSON @@ -5731,7 +5832,7 @@ RunQueryRequest.prototype.toJSON = function toJSON() { return this.constructor.toObject(this, $protobuf.util.toJSONOptions); }; - + /** * Gets the default type url for RunQueryRequest * @function getTypeUrl @@ -5746,12 +5847,12 @@ } return typeUrlPrefix + "/google.firestore.v1.RunQueryRequest"; }; - + return RunQueryRequest; })(); - + v1.RunQueryResponse = (function() { - + /** * Properties of a RunQueryResponse. * @memberof google.firestore.v1 @@ -5763,7 +5864,7 @@ * @property {boolean|null} [done] RunQueryResponse done * @property {google.firestore.v1.IExplainMetrics|null} [explainMetrics] RunQueryResponse explainMetrics */ - + /** * Constructs a new RunQueryResponse. * @memberof google.firestore.v1 @@ -5778,7 +5879,7 @@ if (properties[keys[i]] != null) this[keys[i]] = properties[keys[i]]; } - + /** * RunQueryResponse transaction. * @member {Uint8Array} transaction @@ -5786,7 +5887,7 @@ * @instance */ RunQueryResponse.prototype.transaction = $util.newBuffer([]); - + /** * RunQueryResponse document. * @member {google.firestore.v1.IDocument|null|undefined} document @@ -5794,7 +5895,7 @@ * @instance */ RunQueryResponse.prototype.document = null; - + /** * RunQueryResponse readTime. * @member {google.protobuf.ITimestamp|null|undefined} readTime @@ -5802,7 +5903,7 @@ * @instance */ RunQueryResponse.prototype.readTime = null; - + /** * RunQueryResponse skippedResults. * @member {number} skippedResults @@ -5810,7 +5911,7 @@ * @instance */ RunQueryResponse.prototype.skippedResults = 0; - + /** * RunQueryResponse done. * @member {boolean|null|undefined} done @@ -5818,7 +5919,7 @@ * @instance */ RunQueryResponse.prototype.done = null; - + /** * RunQueryResponse explainMetrics. * @member {google.firestore.v1.IExplainMetrics|null|undefined} explainMetrics @@ -5826,10 +5927,10 @@ * @instance */ RunQueryResponse.prototype.explainMetrics = null; - + // OneOf field names bound to virtual getters and setters var $oneOfFields; - + /** * RunQueryResponse continuationSelector. * @member {"done"|undefined} continuationSelector @@ -5840,7 +5941,7 @@ get: $util.oneOfGetter($oneOfFields = ["done"]), set: $util.oneOfSetter($oneOfFields) }); - + /** * Creates a RunQueryResponse message from a plain object. Also converts values to their respective internal types. * @function fromObject @@ -5879,7 +5980,7 @@ } return message; }; - + /** * Creates a plain object from a RunQueryResponse message. Also converts values to other types if specified. * @function toObject @@ -5923,7 +6024,7 @@ object.explainMetrics = $root.google.firestore.v1.ExplainMetrics.toObject(message.explainMetrics, options); return object; }; - + /** * Converts this RunQueryResponse to JSON. * @function toJSON @@ -5934,7 +6035,7 @@ RunQueryResponse.prototype.toJSON = function toJSON() { return this.constructor.toObject(this, $protobuf.util.toJSONOptions); }; - + /** * Gets the default type url for RunQueryResponse * @function getTypeUrl @@ -5949,12 +6050,12 @@ } return typeUrlPrefix + "/google.firestore.v1.RunQueryResponse"; }; - + return RunQueryResponse; })(); - + v1.ExecutePipelineRequest = (function() { - + /** * Properties of an ExecutePipelineRequest. * @memberof google.firestore.v1 @@ -5965,7 +6066,7 @@ * @property {google.firestore.v1.ITransactionOptions|null} [newTransaction] ExecutePipelineRequest newTransaction * @property {google.protobuf.ITimestamp|null} [readTime] ExecutePipelineRequest readTime */ - + /** * Constructs a new ExecutePipelineRequest. * @memberof google.firestore.v1 @@ -5980,7 +6081,7 @@ if (properties[keys[i]] != null) this[keys[i]] = properties[keys[i]]; } - + /** * ExecutePipelineRequest database. * @member {string} database @@ -5988,7 +6089,7 @@ * @instance */ ExecutePipelineRequest.prototype.database = ""; - + /** * ExecutePipelineRequest structuredPipeline. * @member {google.firestore.v1.IStructuredPipeline|null|undefined} structuredPipeline @@ -5996,7 +6097,7 @@ * @instance */ ExecutePipelineRequest.prototype.structuredPipeline = null; - + /** * ExecutePipelineRequest transaction. * @member {Uint8Array|null|undefined} transaction @@ -6004,7 +6105,7 @@ * @instance */ ExecutePipelineRequest.prototype.transaction = null; - + /** * ExecutePipelineRequest newTransaction. * @member {google.firestore.v1.ITransactionOptions|null|undefined} newTransaction @@ -6012,7 +6113,7 @@ * @instance */ ExecutePipelineRequest.prototype.newTransaction = null; - + /** * ExecutePipelineRequest readTime. * @member {google.protobuf.ITimestamp|null|undefined} readTime @@ -6020,10 +6121,10 @@ * @instance */ ExecutePipelineRequest.prototype.readTime = null; - + // OneOf field names bound to virtual getters and setters var $oneOfFields; - + /** * ExecutePipelineRequest pipelineType. * @member {"structuredPipeline"|undefined} pipelineType @@ -6034,7 +6135,7 @@ get: $util.oneOfGetter($oneOfFields = ["structuredPipeline"]), set: $util.oneOfSetter($oneOfFields) }); - + /** * ExecutePipelineRequest consistencySelector. * @member {"transaction"|"newTransaction"|"readTime"|undefined} consistencySelector @@ -6045,7 +6146,7 @@ get: $util.oneOfGetter($oneOfFields = ["transaction", "newTransaction", "readTime"]), set: $util.oneOfSetter($oneOfFields) }); - + /** * Creates an ExecutePipelineRequest message from a plain object. Also converts values to their respective internal types. * @function fromObject @@ -6082,7 +6183,7 @@ } return message; }; - + /** * Creates a plain object from an ExecutePipelineRequest message. Also converts values to other types if specified. * @function toObject @@ -6122,7 +6223,7 @@ } return object; }; - + /** * Converts this ExecutePipelineRequest to JSON. * @function toJSON @@ -6133,7 +6234,7 @@ ExecutePipelineRequest.prototype.toJSON = function toJSON() { return this.constructor.toObject(this, $protobuf.util.toJSONOptions); }; - + /** * Gets the default type url for ExecutePipelineRequest * @function getTypeUrl @@ -6148,12 +6249,12 @@ } return typeUrlPrefix + "/google.firestore.v1.ExecutePipelineRequest"; }; - + return ExecutePipelineRequest; })(); - + v1.ExecutePipelineResponse = (function() { - + /** * Properties of an ExecutePipelineResponse. * @memberof google.firestore.v1 @@ -6161,8 +6262,9 @@ * @property {Uint8Array|null} [transaction] ExecutePipelineResponse transaction * @property {Array.|null} [results] ExecutePipelineResponse results * @property {google.protobuf.ITimestamp|null} [executionTime] ExecutePipelineResponse executionTime + * @property {google.firestore.v1.IExplainStats|null} [explainStats] ExecutePipelineResponse explainStats */ - + /** * Constructs a new ExecutePipelineResponse. * @memberof google.firestore.v1 @@ -6178,7 +6280,7 @@ if (properties[keys[i]] != null) this[keys[i]] = properties[keys[i]]; } - + /** * ExecutePipelineResponse transaction. * @member {Uint8Array} transaction @@ -6186,7 +6288,7 @@ * @instance */ ExecutePipelineResponse.prototype.transaction = $util.newBuffer([]); - + /** * ExecutePipelineResponse results. * @member {Array.} results @@ -6194,7 +6296,7 @@ * @instance */ ExecutePipelineResponse.prototype.results = $util.emptyArray; - + /** * ExecutePipelineResponse executionTime. * @member {google.protobuf.ITimestamp|null|undefined} executionTime @@ -6202,7 +6304,15 @@ * @instance */ ExecutePipelineResponse.prototype.executionTime = null; - + + /** + * ExecutePipelineResponse explainStats. + * @member {google.firestore.v1.IExplainStats|null|undefined} explainStats + * @memberof google.firestore.v1.ExecutePipelineResponse + * @instance + */ + ExecutePipelineResponse.prototype.explainStats = null; + /** * Creates an ExecutePipelineResponse message from a plain object. Also converts values to their respective internal types. * @function fromObject @@ -6235,9 +6345,14 @@ throw TypeError(".google.firestore.v1.ExecutePipelineResponse.executionTime: object expected"); message.executionTime = $root.google.protobuf.Timestamp.fromObject(object.executionTime); } + if (object.explainStats != null) { + if (typeof object.explainStats !== "object") + throw TypeError(".google.firestore.v1.ExecutePipelineResponse.explainStats: object expected"); + message.explainStats = $root.google.firestore.v1.ExplainStats.fromObject(object.explainStats); + } return message; }; - + /** * Creates a plain object from an ExecutePipelineResponse message. Also converts values to other types if specified. * @function toObject @@ -6262,6 +6377,7 @@ object.transaction = $util.newBuffer(object.transaction); } object.executionTime = null; + object.explainStats = null; } if (message.transaction != null && message.hasOwnProperty("transaction")) object.transaction = options.bytes === String ? $util.base64.encode(message.transaction, 0, message.transaction.length) : options.bytes === Array ? Array.prototype.slice.call(message.transaction) : message.transaction; @@ -6272,9 +6388,11 @@ } if (message.executionTime != null && message.hasOwnProperty("executionTime")) object.executionTime = $root.google.protobuf.Timestamp.toObject(message.executionTime, options); + if (message.explainStats != null && message.hasOwnProperty("explainStats")) + object.explainStats = $root.google.firestore.v1.ExplainStats.toObject(message.explainStats, options); return object; }; - + /** * Converts this ExecutePipelineResponse to JSON. * @function toJSON @@ -6285,7 +6403,7 @@ ExecutePipelineResponse.prototype.toJSON = function toJSON() { return this.constructor.toObject(this, $protobuf.util.toJSONOptions); }; - + /** * Gets the default type url for ExecutePipelineResponse * @function getTypeUrl @@ -6300,12 +6418,12 @@ } return typeUrlPrefix + "/google.firestore.v1.ExecutePipelineResponse"; }; - + return ExecutePipelineResponse; })(); - + v1.RunAggregationQueryRequest = (function() { - + /** * Properties of a RunAggregationQueryRequest. * @memberof google.firestore.v1 @@ -6317,7 +6435,7 @@ * @property {google.protobuf.ITimestamp|null} [readTime] RunAggregationQueryRequest readTime * @property {google.firestore.v1.IExplainOptions|null} [explainOptions] RunAggregationQueryRequest explainOptions */ - + /** * Constructs a new RunAggregationQueryRequest. * @memberof google.firestore.v1 @@ -6332,7 +6450,7 @@ if (properties[keys[i]] != null) this[keys[i]] = properties[keys[i]]; } - + /** * RunAggregationQueryRequest parent. * @member {string} parent @@ -6340,7 +6458,7 @@ * @instance */ RunAggregationQueryRequest.prototype.parent = ""; - + /** * RunAggregationQueryRequest structuredAggregationQuery. * @member {google.firestore.v1.IStructuredAggregationQuery|null|undefined} structuredAggregationQuery @@ -6348,7 +6466,7 @@ * @instance */ RunAggregationQueryRequest.prototype.structuredAggregationQuery = null; - + /** * RunAggregationQueryRequest transaction. * @member {Uint8Array|null|undefined} transaction @@ -6356,7 +6474,7 @@ * @instance */ RunAggregationQueryRequest.prototype.transaction = null; - + /** * RunAggregationQueryRequest newTransaction. * @member {google.firestore.v1.ITransactionOptions|null|undefined} newTransaction @@ -6364,7 +6482,7 @@ * @instance */ RunAggregationQueryRequest.prototype.newTransaction = null; - + /** * RunAggregationQueryRequest readTime. * @member {google.protobuf.ITimestamp|null|undefined} readTime @@ -6372,7 +6490,7 @@ * @instance */ RunAggregationQueryRequest.prototype.readTime = null; - + /** * RunAggregationQueryRequest explainOptions. * @member {google.firestore.v1.IExplainOptions|null|undefined} explainOptions @@ -6380,10 +6498,10 @@ * @instance */ RunAggregationQueryRequest.prototype.explainOptions = null; - + // OneOf field names bound to virtual getters and setters var $oneOfFields; - + /** * RunAggregationQueryRequest queryType. * @member {"structuredAggregationQuery"|undefined} queryType @@ -6394,7 +6512,7 @@ get: $util.oneOfGetter($oneOfFields = ["structuredAggregationQuery"]), set: $util.oneOfSetter($oneOfFields) }); - + /** * RunAggregationQueryRequest consistencySelector. * @member {"transaction"|"newTransaction"|"readTime"|undefined} consistencySelector @@ -6405,7 +6523,7 @@ get: $util.oneOfGetter($oneOfFields = ["transaction", "newTransaction", "readTime"]), set: $util.oneOfSetter($oneOfFields) }); - + /** * Creates a RunAggregationQueryRequest message from a plain object. Also converts values to their respective internal types. * @function fromObject @@ -6447,7 +6565,7 @@ } return message; }; - + /** * Creates a plain object from a RunAggregationQueryRequest message. Also converts values to other types if specified. * @function toObject @@ -6491,7 +6609,7 @@ object.explainOptions = $root.google.firestore.v1.ExplainOptions.toObject(message.explainOptions, options); return object; }; - + /** * Converts this RunAggregationQueryRequest to JSON. * @function toJSON @@ -6502,7 +6620,7 @@ RunAggregationQueryRequest.prototype.toJSON = function toJSON() { return this.constructor.toObject(this, $protobuf.util.toJSONOptions); }; - + /** * Gets the default type url for RunAggregationQueryRequest * @function getTypeUrl @@ -6517,12 +6635,12 @@ } return typeUrlPrefix + "/google.firestore.v1.RunAggregationQueryRequest"; }; - + return RunAggregationQueryRequest; })(); - + v1.RunAggregationQueryResponse = (function() { - + /** * Properties of a RunAggregationQueryResponse. * @memberof google.firestore.v1 @@ -6532,7 +6650,7 @@ * @property {google.protobuf.ITimestamp|null} [readTime] RunAggregationQueryResponse readTime * @property {google.firestore.v1.IExplainMetrics|null} [explainMetrics] RunAggregationQueryResponse explainMetrics */ - + /** * Constructs a new RunAggregationQueryResponse. * @memberof google.firestore.v1 @@ -6547,7 +6665,7 @@ if (properties[keys[i]] != null) this[keys[i]] = properties[keys[i]]; } - + /** * RunAggregationQueryResponse result. * @member {google.firestore.v1.IAggregationResult|null|undefined} result @@ -6555,7 +6673,7 @@ * @instance */ RunAggregationQueryResponse.prototype.result = null; - + /** * RunAggregationQueryResponse transaction. * @member {Uint8Array} transaction @@ -6563,7 +6681,7 @@ * @instance */ RunAggregationQueryResponse.prototype.transaction = $util.newBuffer([]); - + /** * RunAggregationQueryResponse readTime. * @member {google.protobuf.ITimestamp|null|undefined} readTime @@ -6571,7 +6689,7 @@ * @instance */ RunAggregationQueryResponse.prototype.readTime = null; - + /** * RunAggregationQueryResponse explainMetrics. * @member {google.firestore.v1.IExplainMetrics|null|undefined} explainMetrics @@ -6579,7 +6697,7 @@ * @instance */ RunAggregationQueryResponse.prototype.explainMetrics = null; - + /** * Creates a RunAggregationQueryResponse message from a plain object. Also converts values to their respective internal types. * @function fromObject @@ -6614,7 +6732,7 @@ } return message; }; - + /** * Creates a plain object from a RunAggregationQueryResponse message. Also converts values to other types if specified. * @function toObject @@ -6650,7 +6768,7 @@ object.explainMetrics = $root.google.firestore.v1.ExplainMetrics.toObject(message.explainMetrics, options); return object; }; - + /** * Converts this RunAggregationQueryResponse to JSON. * @function toJSON @@ -6661,7 +6779,7 @@ RunAggregationQueryResponse.prototype.toJSON = function toJSON() { return this.constructor.toObject(this, $protobuf.util.toJSONOptions); }; - + /** * Gets the default type url for RunAggregationQueryResponse * @function getTypeUrl @@ -6676,12 +6794,12 @@ } return typeUrlPrefix + "/google.firestore.v1.RunAggregationQueryResponse"; }; - + return RunAggregationQueryResponse; })(); - + v1.PartitionQueryRequest = (function() { - + /** * Properties of a PartitionQueryRequest. * @memberof google.firestore.v1 @@ -6693,7 +6811,7 @@ * @property {number|null} [pageSize] PartitionQueryRequest pageSize * @property {google.protobuf.ITimestamp|null} [readTime] PartitionQueryRequest readTime */ - + /** * Constructs a new PartitionQueryRequest. * @memberof google.firestore.v1 @@ -6708,7 +6826,7 @@ if (properties[keys[i]] != null) this[keys[i]] = properties[keys[i]]; } - + /** * PartitionQueryRequest parent. * @member {string} parent @@ -6716,7 +6834,7 @@ * @instance */ PartitionQueryRequest.prototype.parent = ""; - + /** * PartitionQueryRequest structuredQuery. * @member {google.firestore.v1.IStructuredQuery|null|undefined} structuredQuery @@ -6724,7 +6842,7 @@ * @instance */ PartitionQueryRequest.prototype.structuredQuery = null; - + /** * PartitionQueryRequest partitionCount. * @member {number|string} partitionCount @@ -6732,7 +6850,7 @@ * @instance */ PartitionQueryRequest.prototype.partitionCount = $util.Long ? $util.Long.fromBits(0,0,false) : 0; - + /** * PartitionQueryRequest pageToken. * @member {string} pageToken @@ -6740,7 +6858,7 @@ * @instance */ PartitionQueryRequest.prototype.pageToken = ""; - + /** * PartitionQueryRequest pageSize. * @member {number} pageSize @@ -6748,7 +6866,7 @@ * @instance */ PartitionQueryRequest.prototype.pageSize = 0; - + /** * PartitionQueryRequest readTime. * @member {google.protobuf.ITimestamp|null|undefined} readTime @@ -6756,10 +6874,10 @@ * @instance */ PartitionQueryRequest.prototype.readTime = null; - + // OneOf field names bound to virtual getters and setters var $oneOfFields; - + /** * PartitionQueryRequest queryType. * @member {"structuredQuery"|undefined} queryType @@ -6770,7 +6888,7 @@ get: $util.oneOfGetter($oneOfFields = ["structuredQuery"]), set: $util.oneOfSetter($oneOfFields) }); - + /** * PartitionQueryRequest consistencySelector. * @member {"readTime"|undefined} consistencySelector @@ -6781,7 +6899,7 @@ get: $util.oneOfGetter($oneOfFields = ["readTime"]), set: $util.oneOfSetter($oneOfFields) }); - + /** * Creates a PartitionQueryRequest message from a plain object. Also converts values to their respective internal types. * @function fromObject @@ -6821,7 +6939,7 @@ } return message; }; - + /** * Creates a plain object from a PartitionQueryRequest message. Also converts values to other types if specified. * @function toObject @@ -6868,7 +6986,7 @@ } return object; }; - + /** * Converts this PartitionQueryRequest to JSON. * @function toJSON @@ -6879,7 +6997,7 @@ PartitionQueryRequest.prototype.toJSON = function toJSON() { return this.constructor.toObject(this, $protobuf.util.toJSONOptions); }; - + /** * Gets the default type url for PartitionQueryRequest * @function getTypeUrl @@ -6894,12 +7012,12 @@ } return typeUrlPrefix + "/google.firestore.v1.PartitionQueryRequest"; }; - + return PartitionQueryRequest; })(); - + v1.PartitionQueryResponse = (function() { - + /** * Properties of a PartitionQueryResponse. * @memberof google.firestore.v1 @@ -6907,7 +7025,7 @@ * @property {Array.|null} [partitions] PartitionQueryResponse partitions * @property {string|null} [nextPageToken] PartitionQueryResponse nextPageToken */ - + /** * Constructs a new PartitionQueryResponse. * @memberof google.firestore.v1 @@ -6923,7 +7041,7 @@ if (properties[keys[i]] != null) this[keys[i]] = properties[keys[i]]; } - + /** * PartitionQueryResponse partitions. * @member {Array.} partitions @@ -6931,7 +7049,7 @@ * @instance */ PartitionQueryResponse.prototype.partitions = $util.emptyArray; - + /** * PartitionQueryResponse nextPageToken. * @member {string} nextPageToken @@ -6939,7 +7057,7 @@ * @instance */ PartitionQueryResponse.prototype.nextPageToken = ""; - + /** * Creates a PartitionQueryResponse message from a plain object. Also converts values to their respective internal types. * @function fromObject @@ -6966,7 +7084,7 @@ message.nextPageToken = String(object.nextPageToken); return message; }; - + /** * Creates a plain object from a PartitionQueryResponse message. Also converts values to other types if specified. * @function toObject @@ -6993,7 +7111,7 @@ object.nextPageToken = message.nextPageToken; return object; }; - + /** * Converts this PartitionQueryResponse to JSON. * @function toJSON @@ -7004,7 +7122,7 @@ PartitionQueryResponse.prototype.toJSON = function toJSON() { return this.constructor.toObject(this, $protobuf.util.toJSONOptions); }; - + /** * Gets the default type url for PartitionQueryResponse * @function getTypeUrl @@ -7019,12 +7137,12 @@ } return typeUrlPrefix + "/google.firestore.v1.PartitionQueryResponse"; }; - + return PartitionQueryResponse; })(); - + v1.WriteRequest = (function() { - + /** * Properties of a WriteRequest. * @memberof google.firestore.v1 @@ -7035,7 +7153,7 @@ * @property {Uint8Array|null} [streamToken] WriteRequest streamToken * @property {Object.|null} [labels] WriteRequest labels */ - + /** * Constructs a new WriteRequest. * @memberof google.firestore.v1 @@ -7052,7 +7170,7 @@ if (properties[keys[i]] != null) this[keys[i]] = properties[keys[i]]; } - + /** * WriteRequest database. * @member {string} database @@ -7060,7 +7178,7 @@ * @instance */ WriteRequest.prototype.database = ""; - + /** * WriteRequest streamId. * @member {string} streamId @@ -7068,7 +7186,7 @@ * @instance */ WriteRequest.prototype.streamId = ""; - + /** * WriteRequest writes. * @member {Array.} writes @@ -7076,7 +7194,7 @@ * @instance */ WriteRequest.prototype.writes = $util.emptyArray; - + /** * WriteRequest streamToken. * @member {Uint8Array} streamToken @@ -7084,7 +7202,7 @@ * @instance */ WriteRequest.prototype.streamToken = $util.newBuffer([]); - + /** * WriteRequest labels. * @member {Object.} labels @@ -7092,7 +7210,7 @@ * @instance */ WriteRequest.prototype.labels = $util.emptyObject; - + /** * Creates a WriteRequest message from a plain object. Also converts values to their respective internal types. * @function fromObject @@ -7133,7 +7251,7 @@ } return message; }; - + /** * Creates a plain object from a WriteRequest message. Also converts values to other types if specified. * @function toObject @@ -7181,7 +7299,7 @@ } return object; }; - + /** * Converts this WriteRequest to JSON. * @function toJSON @@ -7192,7 +7310,7 @@ WriteRequest.prototype.toJSON = function toJSON() { return this.constructor.toObject(this, $protobuf.util.toJSONOptions); }; - + /** * Gets the default type url for WriteRequest * @function getTypeUrl @@ -7207,12 +7325,12 @@ } return typeUrlPrefix + "/google.firestore.v1.WriteRequest"; }; - + return WriteRequest; })(); - + v1.WriteResponse = (function() { - + /** * Properties of a WriteResponse. * @memberof google.firestore.v1 @@ -7222,7 +7340,7 @@ * @property {Array.|null} [writeResults] WriteResponse writeResults * @property {google.protobuf.ITimestamp|null} [commitTime] WriteResponse commitTime */ - + /** * Constructs a new WriteResponse. * @memberof google.firestore.v1 @@ -7238,7 +7356,7 @@ if (properties[keys[i]] != null) this[keys[i]] = properties[keys[i]]; } - + /** * WriteResponse streamId. * @member {string} streamId @@ -7246,7 +7364,7 @@ * @instance */ WriteResponse.prototype.streamId = ""; - + /** * WriteResponse streamToken. * @member {Uint8Array} streamToken @@ -7254,7 +7372,7 @@ * @instance */ WriteResponse.prototype.streamToken = $util.newBuffer([]); - + /** * WriteResponse writeResults. * @member {Array.} writeResults @@ -7262,7 +7380,7 @@ * @instance */ WriteResponse.prototype.writeResults = $util.emptyArray; - + /** * WriteResponse commitTime. * @member {google.protobuf.ITimestamp|null|undefined} commitTime @@ -7270,7 +7388,7 @@ * @instance */ WriteResponse.prototype.commitTime = null; - + /** * Creates a WriteResponse message from a plain object. Also converts values to their respective internal types. * @function fromObject @@ -7307,7 +7425,7 @@ } return message; }; - + /** * Creates a plain object from a WriteResponse message. Also converts values to other types if specified. * @function toObject @@ -7347,7 +7465,7 @@ object.commitTime = $root.google.protobuf.Timestamp.toObject(message.commitTime, options); return object; }; - + /** * Converts this WriteResponse to JSON. * @function toJSON @@ -7358,7 +7476,7 @@ WriteResponse.prototype.toJSON = function toJSON() { return this.constructor.toObject(this, $protobuf.util.toJSONOptions); }; - + /** * Gets the default type url for WriteResponse * @function getTypeUrl @@ -7373,12 +7491,12 @@ } return typeUrlPrefix + "/google.firestore.v1.WriteResponse"; }; - + return WriteResponse; })(); - + v1.ListenRequest = (function() { - + /** * Properties of a ListenRequest. * @memberof google.firestore.v1 @@ -7388,7 +7506,7 @@ * @property {number|null} [removeTarget] ListenRequest removeTarget * @property {Object.|null} [labels] ListenRequest labels */ - + /** * Constructs a new ListenRequest. * @memberof google.firestore.v1 @@ -7404,7 +7522,7 @@ if (properties[keys[i]] != null) this[keys[i]] = properties[keys[i]]; } - + /** * ListenRequest database. * @member {string} database @@ -7412,7 +7530,7 @@ * @instance */ ListenRequest.prototype.database = ""; - + /** * ListenRequest addTarget. * @member {google.firestore.v1.ITarget|null|undefined} addTarget @@ -7420,7 +7538,7 @@ * @instance */ ListenRequest.prototype.addTarget = null; - + /** * ListenRequest removeTarget. * @member {number|null|undefined} removeTarget @@ -7428,7 +7546,7 @@ * @instance */ ListenRequest.prototype.removeTarget = null; - + /** * ListenRequest labels. * @member {Object.} labels @@ -7436,10 +7554,10 @@ * @instance */ ListenRequest.prototype.labels = $util.emptyObject; - + // OneOf field names bound to virtual getters and setters var $oneOfFields; - + /** * ListenRequest targetChange. * @member {"addTarget"|"removeTarget"|undefined} targetChange @@ -7450,7 +7568,7 @@ get: $util.oneOfGetter($oneOfFields = ["addTarget", "removeTarget"]), set: $util.oneOfSetter($oneOfFields) }); - + /** * Creates a ListenRequest message from a plain object. Also converts values to their respective internal types. * @function fromObject @@ -7481,7 +7599,7 @@ } return message; }; - + /** * Creates a plain object from a ListenRequest message. Also converts values to other types if specified. * @function toObject @@ -7519,7 +7637,7 @@ } return object; }; - + /** * Converts this ListenRequest to JSON. * @function toJSON @@ -7530,7 +7648,7 @@ ListenRequest.prototype.toJSON = function toJSON() { return this.constructor.toObject(this, $protobuf.util.toJSONOptions); }; - + /** * Gets the default type url for ListenRequest * @function getTypeUrl @@ -7545,12 +7663,12 @@ } return typeUrlPrefix + "/google.firestore.v1.ListenRequest"; }; - + return ListenRequest; })(); - + v1.ListenResponse = (function() { - + /** * Properties of a ListenResponse. * @memberof google.firestore.v1 @@ -7561,7 +7679,7 @@ * @property {google.firestore.v1.IDocumentRemove|null} [documentRemove] ListenResponse documentRemove * @property {google.firestore.v1.IExistenceFilter|null} [filter] ListenResponse filter */ - + /** * Constructs a new ListenResponse. * @memberof google.firestore.v1 @@ -7576,7 +7694,7 @@ if (properties[keys[i]] != null) this[keys[i]] = properties[keys[i]]; } - + /** * ListenResponse targetChange. * @member {google.firestore.v1.ITargetChange|null|undefined} targetChange @@ -7584,7 +7702,7 @@ * @instance */ ListenResponse.prototype.targetChange = null; - + /** * ListenResponse documentChange. * @member {google.firestore.v1.IDocumentChange|null|undefined} documentChange @@ -7592,7 +7710,7 @@ * @instance */ ListenResponse.prototype.documentChange = null; - + /** * ListenResponse documentDelete. * @member {google.firestore.v1.IDocumentDelete|null|undefined} documentDelete @@ -7600,7 +7718,7 @@ * @instance */ ListenResponse.prototype.documentDelete = null; - + /** * ListenResponse documentRemove. * @member {google.firestore.v1.IDocumentRemove|null|undefined} documentRemove @@ -7608,7 +7726,7 @@ * @instance */ ListenResponse.prototype.documentRemove = null; - + /** * ListenResponse filter. * @member {google.firestore.v1.IExistenceFilter|null|undefined} filter @@ -7616,10 +7734,10 @@ * @instance */ ListenResponse.prototype.filter = null; - + // OneOf field names bound to virtual getters and setters var $oneOfFields; - + /** * ListenResponse responseType. * @member {"targetChange"|"documentChange"|"documentDelete"|"documentRemove"|"filter"|undefined} responseType @@ -7630,7 +7748,7 @@ get: $util.oneOfGetter($oneOfFields = ["targetChange", "documentChange", "documentDelete", "documentRemove", "filter"]), set: $util.oneOfSetter($oneOfFields) }); - + /** * Creates a ListenResponse message from a plain object. Also converts values to their respective internal types. * @function fromObject @@ -7670,7 +7788,7 @@ } return message; }; - + /** * Creates a plain object from a ListenResponse message. Also converts values to other types if specified. * @function toObject @@ -7711,7 +7829,7 @@ } return object; }; - + /** * Converts this ListenResponse to JSON. * @function toJSON @@ -7722,7 +7840,7 @@ ListenResponse.prototype.toJSON = function toJSON() { return this.constructor.toObject(this, $protobuf.util.toJSONOptions); }; - + /** * Gets the default type url for ListenResponse * @function getTypeUrl @@ -7737,12 +7855,12 @@ } return typeUrlPrefix + "/google.firestore.v1.ListenResponse"; }; - + return ListenResponse; })(); - + v1.Target = (function() { - + /** * Properties of a Target. * @memberof google.firestore.v1 @@ -7755,7 +7873,7 @@ * @property {boolean|null} [once] Target once * @property {google.protobuf.IInt32Value|null} [expectedCount] Target expectedCount */ - + /** * Constructs a new Target. * @memberof google.firestore.v1 @@ -7770,7 +7888,7 @@ if (properties[keys[i]] != null) this[keys[i]] = properties[keys[i]]; } - + /** * Target query. * @member {google.firestore.v1.Target.IQueryTarget|null|undefined} query @@ -7778,7 +7896,7 @@ * @instance */ Target.prototype.query = null; - + /** * Target documents. * @member {google.firestore.v1.Target.IDocumentsTarget|null|undefined} documents @@ -7786,7 +7904,7 @@ * @instance */ Target.prototype.documents = null; - + /** * Target resumeToken. * @member {Uint8Array|null|undefined} resumeToken @@ -7794,7 +7912,7 @@ * @instance */ Target.prototype.resumeToken = null; - + /** * Target readTime. * @member {google.protobuf.ITimestamp|null|undefined} readTime @@ -7802,7 +7920,7 @@ * @instance */ Target.prototype.readTime = null; - + /** * Target targetId. * @member {number} targetId @@ -7810,7 +7928,7 @@ * @instance */ Target.prototype.targetId = 0; - + /** * Target once. * @member {boolean} once @@ -7818,7 +7936,7 @@ * @instance */ Target.prototype.once = false; - + /** * Target expectedCount. * @member {google.protobuf.IInt32Value|null|undefined} expectedCount @@ -7826,10 +7944,10 @@ * @instance */ Target.prototype.expectedCount = null; - + // OneOf field names bound to virtual getters and setters var $oneOfFields; - + /** * Target targetType. * @member {"query"|"documents"|undefined} targetType @@ -7840,7 +7958,7 @@ get: $util.oneOfGetter($oneOfFields = ["query", "documents"]), set: $util.oneOfSetter($oneOfFields) }); - + /** * Target resumeType. * @member {"resumeToken"|"readTime"|undefined} resumeType @@ -7851,7 +7969,7 @@ get: $util.oneOfGetter($oneOfFields = ["resumeToken", "readTime"]), set: $util.oneOfSetter($oneOfFields) }); - + /** * Creates a Target message from a plain object. Also converts values to their respective internal types. * @function fromObject @@ -7895,7 +8013,7 @@ } return message; }; - + /** * Creates a plain object from a Target message. Also converts values to other types if specified. * @function toObject @@ -7942,7 +8060,7 @@ object.expectedCount = $root.google.protobuf.Int32Value.toObject(message.expectedCount, options); return object; }; - + /** * Converts this Target to JSON. * @function toJSON @@ -7953,7 +8071,7 @@ Target.prototype.toJSON = function toJSON() { return this.constructor.toObject(this, $protobuf.util.toJSONOptions); }; - + /** * Gets the default type url for Target * @function getTypeUrl @@ -7968,16 +8086,16 @@ } return typeUrlPrefix + "/google.firestore.v1.Target"; }; - + Target.DocumentsTarget = (function() { - + /** * Properties of a DocumentsTarget. * @memberof google.firestore.v1.Target * @interface IDocumentsTarget * @property {Array.|null} [documents] DocumentsTarget documents */ - + /** * Constructs a new DocumentsTarget. * @memberof google.firestore.v1.Target @@ -7993,7 +8111,7 @@ if (properties[keys[i]] != null) this[keys[i]] = properties[keys[i]]; } - + /** * DocumentsTarget documents. * @member {Array.} documents @@ -8001,7 +8119,7 @@ * @instance */ DocumentsTarget.prototype.documents = $util.emptyArray; - + /** * Creates a DocumentsTarget message from a plain object. Also converts values to their respective internal types. * @function fromObject @@ -8023,7 +8141,7 @@ } return message; }; - + /** * Creates a plain object from a DocumentsTarget message. Also converts values to other types if specified. * @function toObject @@ -8046,7 +8164,7 @@ } return object; }; - + /** * Converts this DocumentsTarget to JSON. * @function toJSON @@ -8057,7 +8175,7 @@ DocumentsTarget.prototype.toJSON = function toJSON() { return this.constructor.toObject(this, $protobuf.util.toJSONOptions); }; - + /** * Gets the default type url for DocumentsTarget * @function getTypeUrl @@ -8072,12 +8190,12 @@ } return typeUrlPrefix + "/google.firestore.v1.Target.DocumentsTarget"; }; - + return DocumentsTarget; })(); - + Target.QueryTarget = (function() { - + /** * Properties of a QueryTarget. * @memberof google.firestore.v1.Target @@ -8085,7 +8203,7 @@ * @property {string|null} [parent] QueryTarget parent * @property {google.firestore.v1.IStructuredQuery|null} [structuredQuery] QueryTarget structuredQuery */ - + /** * Constructs a new QueryTarget. * @memberof google.firestore.v1.Target @@ -8100,7 +8218,7 @@ if (properties[keys[i]] != null) this[keys[i]] = properties[keys[i]]; } - + /** * QueryTarget parent. * @member {string} parent @@ -8108,7 +8226,7 @@ * @instance */ QueryTarget.prototype.parent = ""; - + /** * QueryTarget structuredQuery. * @member {google.firestore.v1.IStructuredQuery|null|undefined} structuredQuery @@ -8116,10 +8234,10 @@ * @instance */ QueryTarget.prototype.structuredQuery = null; - + // OneOf field names bound to virtual getters and setters var $oneOfFields; - + /** * QueryTarget queryType. * @member {"structuredQuery"|undefined} queryType @@ -8130,7 +8248,7 @@ get: $util.oneOfGetter($oneOfFields = ["structuredQuery"]), set: $util.oneOfSetter($oneOfFields) }); - + /** * Creates a QueryTarget message from a plain object. Also converts values to their respective internal types. * @function fromObject @@ -8152,7 +8270,7 @@ } return message; }; - + /** * Creates a plain object from a QueryTarget message. Also converts values to other types if specified. * @function toObject @@ -8177,7 +8295,7 @@ } return object; }; - + /** * Converts this QueryTarget to JSON. * @function toJSON @@ -8188,7 +8306,7 @@ QueryTarget.prototype.toJSON = function toJSON() { return this.constructor.toObject(this, $protobuf.util.toJSONOptions); }; - + /** * Gets the default type url for QueryTarget * @function getTypeUrl @@ -8203,15 +8321,15 @@ } return typeUrlPrefix + "/google.firestore.v1.Target.QueryTarget"; }; - + return QueryTarget; })(); - + return Target; })(); - + v1.TargetChange = (function() { - + /** * Properties of a TargetChange. * @memberof google.firestore.v1 @@ -8222,7 +8340,7 @@ * @property {Uint8Array|null} [resumeToken] TargetChange resumeToken * @property {google.protobuf.ITimestamp|null} [readTime] TargetChange readTime */ - + /** * Constructs a new TargetChange. * @memberof google.firestore.v1 @@ -8238,7 +8356,7 @@ if (properties[keys[i]] != null) this[keys[i]] = properties[keys[i]]; } - + /** * TargetChange targetChangeType. * @member {google.firestore.v1.TargetChange.TargetChangeType} targetChangeType @@ -8246,7 +8364,7 @@ * @instance */ TargetChange.prototype.targetChangeType = 0; - + /** * TargetChange targetIds. * @member {Array.} targetIds @@ -8254,7 +8372,7 @@ * @instance */ TargetChange.prototype.targetIds = $util.emptyArray; - + /** * TargetChange cause. * @member {google.rpc.IStatus|null|undefined} cause @@ -8262,7 +8380,7 @@ * @instance */ TargetChange.prototype.cause = null; - + /** * TargetChange resumeToken. * @member {Uint8Array} resumeToken @@ -8270,7 +8388,7 @@ * @instance */ TargetChange.prototype.resumeToken = $util.newBuffer([]); - + /** * TargetChange readTime. * @member {google.protobuf.ITimestamp|null|undefined} readTime @@ -8278,7 +8396,7 @@ * @instance */ TargetChange.prototype.readTime = null; - + /** * Creates a TargetChange message from a plain object. Also converts values to their respective internal types. * @function fromObject @@ -8343,7 +8461,7 @@ } return message; }; - + /** * Creates a plain object from a TargetChange message. Also converts values to other types if specified. * @function toObject @@ -8386,7 +8504,7 @@ object.readTime = $root.google.protobuf.Timestamp.toObject(message.readTime, options); return object; }; - + /** * Converts this TargetChange to JSON. * @function toJSON @@ -8397,7 +8515,7 @@ TargetChange.prototype.toJSON = function toJSON() { return this.constructor.toObject(this, $protobuf.util.toJSONOptions); }; - + /** * Gets the default type url for TargetChange * @function getTypeUrl @@ -8412,7 +8530,7 @@ } return typeUrlPrefix + "/google.firestore.v1.TargetChange"; }; - + /** * TargetChangeType enum. * @name google.firestore.v1.TargetChange.TargetChangeType @@ -8432,12 +8550,12 @@ values[valuesById[4] = "RESET"] = "RESET"; return values; })(); - + return TargetChange; })(); - + v1.ListCollectionIdsRequest = (function() { - + /** * Properties of a ListCollectionIdsRequest. * @memberof google.firestore.v1 @@ -8447,7 +8565,7 @@ * @property {string|null} [pageToken] ListCollectionIdsRequest pageToken * @property {google.protobuf.ITimestamp|null} [readTime] ListCollectionIdsRequest readTime */ - + /** * Constructs a new ListCollectionIdsRequest. * @memberof google.firestore.v1 @@ -8462,7 +8580,7 @@ if (properties[keys[i]] != null) this[keys[i]] = properties[keys[i]]; } - + /** * ListCollectionIdsRequest parent. * @member {string} parent @@ -8470,7 +8588,7 @@ * @instance */ ListCollectionIdsRequest.prototype.parent = ""; - + /** * ListCollectionIdsRequest pageSize. * @member {number} pageSize @@ -8478,7 +8596,7 @@ * @instance */ ListCollectionIdsRequest.prototype.pageSize = 0; - + /** * ListCollectionIdsRequest pageToken. * @member {string} pageToken @@ -8486,7 +8604,7 @@ * @instance */ ListCollectionIdsRequest.prototype.pageToken = ""; - + /** * ListCollectionIdsRequest readTime. * @member {google.protobuf.ITimestamp|null|undefined} readTime @@ -8494,10 +8612,10 @@ * @instance */ ListCollectionIdsRequest.prototype.readTime = null; - + // OneOf field names bound to virtual getters and setters var $oneOfFields; - + /** * ListCollectionIdsRequest consistencySelector. * @member {"readTime"|undefined} consistencySelector @@ -8508,7 +8626,7 @@ get: $util.oneOfGetter($oneOfFields = ["readTime"]), set: $util.oneOfSetter($oneOfFields) }); - + /** * Creates a ListCollectionIdsRequest message from a plain object. Also converts values to their respective internal types. * @function fromObject @@ -8534,7 +8652,7 @@ } return message; }; - + /** * Creates a plain object from a ListCollectionIdsRequest message. Also converts values to other types if specified. * @function toObject @@ -8566,7 +8684,7 @@ } return object; }; - + /** * Converts this ListCollectionIdsRequest to JSON. * @function toJSON @@ -8577,7 +8695,7 @@ ListCollectionIdsRequest.prototype.toJSON = function toJSON() { return this.constructor.toObject(this, $protobuf.util.toJSONOptions); }; - + /** * Gets the default type url for ListCollectionIdsRequest * @function getTypeUrl @@ -8592,12 +8710,12 @@ } return typeUrlPrefix + "/google.firestore.v1.ListCollectionIdsRequest"; }; - + return ListCollectionIdsRequest; })(); - + v1.ListCollectionIdsResponse = (function() { - + /** * Properties of a ListCollectionIdsResponse. * @memberof google.firestore.v1 @@ -8605,7 +8723,7 @@ * @property {Array.|null} [collectionIds] ListCollectionIdsResponse collectionIds * @property {string|null} [nextPageToken] ListCollectionIdsResponse nextPageToken */ - + /** * Constructs a new ListCollectionIdsResponse. * @memberof google.firestore.v1 @@ -8621,7 +8739,7 @@ if (properties[keys[i]] != null) this[keys[i]] = properties[keys[i]]; } - + /** * ListCollectionIdsResponse collectionIds. * @member {Array.} collectionIds @@ -8629,7 +8747,7 @@ * @instance */ ListCollectionIdsResponse.prototype.collectionIds = $util.emptyArray; - + /** * ListCollectionIdsResponse nextPageToken. * @member {string} nextPageToken @@ -8637,7 +8755,7 @@ * @instance */ ListCollectionIdsResponse.prototype.nextPageToken = ""; - + /** * Creates a ListCollectionIdsResponse message from a plain object. Also converts values to their respective internal types. * @function fromObject @@ -8661,7 +8779,7 @@ message.nextPageToken = String(object.nextPageToken); return message; }; - + /** * Creates a plain object from a ListCollectionIdsResponse message. Also converts values to other types if specified. * @function toObject @@ -8688,7 +8806,7 @@ object.nextPageToken = message.nextPageToken; return object; }; - + /** * Converts this ListCollectionIdsResponse to JSON. * @function toJSON @@ -8699,7 +8817,7 @@ ListCollectionIdsResponse.prototype.toJSON = function toJSON() { return this.constructor.toObject(this, $protobuf.util.toJSONOptions); }; - + /** * Gets the default type url for ListCollectionIdsResponse * @function getTypeUrl @@ -8714,12 +8832,12 @@ } return typeUrlPrefix + "/google.firestore.v1.ListCollectionIdsResponse"; }; - + return ListCollectionIdsResponse; })(); - + v1.BatchWriteRequest = (function() { - + /** * Properties of a BatchWriteRequest. * @memberof google.firestore.v1 @@ -8728,7 +8846,7 @@ * @property {Array.|null} [writes] BatchWriteRequest writes * @property {Object.|null} [labels] BatchWriteRequest labels */ - + /** * Constructs a new BatchWriteRequest. * @memberof google.firestore.v1 @@ -8745,7 +8863,7 @@ if (properties[keys[i]] != null) this[keys[i]] = properties[keys[i]]; } - + /** * BatchWriteRequest database. * @member {string} database @@ -8753,7 +8871,7 @@ * @instance */ BatchWriteRequest.prototype.database = ""; - + /** * BatchWriteRequest writes. * @member {Array.} writes @@ -8761,7 +8879,7 @@ * @instance */ BatchWriteRequest.prototype.writes = $util.emptyArray; - + /** * BatchWriteRequest labels. * @member {Object.} labels @@ -8769,7 +8887,7 @@ * @instance */ BatchWriteRequest.prototype.labels = $util.emptyObject; - + /** * Creates a BatchWriteRequest message from a plain object. Also converts values to their respective internal types. * @function fromObject @@ -8803,7 +8921,7 @@ } return message; }; - + /** * Creates a plain object from a BatchWriteRequest message. Also converts values to other types if specified. * @function toObject @@ -8838,7 +8956,7 @@ } return object; }; - + /** * Converts this BatchWriteRequest to JSON. * @function toJSON @@ -8849,7 +8967,7 @@ BatchWriteRequest.prototype.toJSON = function toJSON() { return this.constructor.toObject(this, $protobuf.util.toJSONOptions); }; - + /** * Gets the default type url for BatchWriteRequest * @function getTypeUrl @@ -8864,12 +8982,12 @@ } return typeUrlPrefix + "/google.firestore.v1.BatchWriteRequest"; }; - + return BatchWriteRequest; })(); - + v1.BatchWriteResponse = (function() { - + /** * Properties of a BatchWriteResponse. * @memberof google.firestore.v1 @@ -8877,7 +8995,7 @@ * @property {Array.|null} [writeResults] BatchWriteResponse writeResults * @property {Array.|null} [status] BatchWriteResponse status */ - + /** * Constructs a new BatchWriteResponse. * @memberof google.firestore.v1 @@ -8894,7 +9012,7 @@ if (properties[keys[i]] != null) this[keys[i]] = properties[keys[i]]; } - + /** * BatchWriteResponse writeResults. * @member {Array.} writeResults @@ -8902,7 +9020,7 @@ * @instance */ BatchWriteResponse.prototype.writeResults = $util.emptyArray; - + /** * BatchWriteResponse status. * @member {Array.} status @@ -8910,7 +9028,7 @@ * @instance */ BatchWriteResponse.prototype.status = $util.emptyArray; - + /** * Creates a BatchWriteResponse message from a plain object. Also converts values to their respective internal types. * @function fromObject @@ -8945,7 +9063,7 @@ } return message; }; - + /** * Creates a plain object from a BatchWriteResponse message. Also converts values to other types if specified. * @function toObject @@ -8975,7 +9093,7 @@ } return object; }; - + /** * Converts this BatchWriteResponse to JSON. * @function toJSON @@ -8986,7 +9104,7 @@ BatchWriteResponse.prototype.toJSON = function toJSON() { return this.constructor.toObject(this, $protobuf.util.toJSONOptions); }; - + /** * Gets the default type url for BatchWriteResponse * @function getTypeUrl @@ -9001,12 +9119,12 @@ } return typeUrlPrefix + "/google.firestore.v1.BatchWriteResponse"; }; - + return BatchWriteResponse; })(); - + v1.StructuredPipeline = (function() { - + /** * Properties of a StructuredPipeline. * @memberof google.firestore.v1 @@ -9014,7 +9132,7 @@ * @property {google.firestore.v1.IPipeline|null} [pipeline] StructuredPipeline pipeline * @property {Object.|null} [options] StructuredPipeline options */ - + /** * Constructs a new StructuredPipeline. * @memberof google.firestore.v1 @@ -9030,7 +9148,7 @@ if (properties[keys[i]] != null) this[keys[i]] = properties[keys[i]]; } - + /** * StructuredPipeline pipeline. * @member {google.firestore.v1.IPipeline|null|undefined} pipeline @@ -9038,7 +9156,7 @@ * @instance */ StructuredPipeline.prototype.pipeline = null; - + /** * StructuredPipeline options. * @member {Object.} options @@ -9046,7 +9164,7 @@ * @instance */ StructuredPipeline.prototype.options = $util.emptyObject; - + /** * Creates a StructuredPipeline message from a plain object. Also converts values to their respective internal types. * @function fromObject @@ -9076,7 +9194,7 @@ } return message; }; - + /** * Creates a plain object from a StructuredPipeline message. Also converts values to other types if specified. * @function toObject @@ -9104,7 +9222,7 @@ } return object; }; - + /** * Converts this StructuredPipeline to JSON. * @function toJSON @@ -9115,7 +9233,7 @@ StructuredPipeline.prototype.toJSON = function toJSON() { return this.constructor.toObject(this, $protobuf.util.toJSONOptions); }; - + /** * Gets the default type url for StructuredPipeline * @function getTypeUrl @@ -9130,12 +9248,12 @@ } return typeUrlPrefix + "/google.firestore.v1.StructuredPipeline"; }; - + return StructuredPipeline; })(); - + v1.StructuredQuery = (function() { - + /** * Properties of a StructuredQuery. * @memberof google.firestore.v1 @@ -9150,7 +9268,7 @@ * @property {google.protobuf.IInt32Value|null} [limit] StructuredQuery limit * @property {google.firestore.v1.StructuredQuery.IFindNearest|null} [findNearest] StructuredQuery findNearest */ - + /** * Constructs a new StructuredQuery. * @memberof google.firestore.v1 @@ -9167,7 +9285,7 @@ if (properties[keys[i]] != null) this[keys[i]] = properties[keys[i]]; } - + /** * StructuredQuery select. * @member {google.firestore.v1.StructuredQuery.IProjection|null|undefined} select @@ -9175,7 +9293,7 @@ * @instance */ StructuredQuery.prototype.select = null; - + /** * StructuredQuery from. * @member {Array.} from @@ -9183,7 +9301,7 @@ * @instance */ StructuredQuery.prototype.from = $util.emptyArray; - + /** * StructuredQuery where. * @member {google.firestore.v1.StructuredQuery.IFilter|null|undefined} where @@ -9191,7 +9309,7 @@ * @instance */ StructuredQuery.prototype.where = null; - + /** * StructuredQuery orderBy. * @member {Array.} orderBy @@ -9199,7 +9317,7 @@ * @instance */ StructuredQuery.prototype.orderBy = $util.emptyArray; - + /** * StructuredQuery startAt. * @member {google.firestore.v1.ICursor|null|undefined} startAt @@ -9207,7 +9325,7 @@ * @instance */ StructuredQuery.prototype.startAt = null; - + /** * StructuredQuery endAt. * @member {google.firestore.v1.ICursor|null|undefined} endAt @@ -9215,7 +9333,7 @@ * @instance */ StructuredQuery.prototype.endAt = null; - + /** * StructuredQuery offset. * @member {number} offset @@ -9223,7 +9341,7 @@ * @instance */ StructuredQuery.prototype.offset = 0; - + /** * StructuredQuery limit. * @member {google.protobuf.IInt32Value|null|undefined} limit @@ -9231,7 +9349,7 @@ * @instance */ StructuredQuery.prototype.limit = null; - + /** * StructuredQuery findNearest. * @member {google.firestore.v1.StructuredQuery.IFindNearest|null|undefined} findNearest @@ -9239,7 +9357,7 @@ * @instance */ StructuredQuery.prototype.findNearest = null; - + /** * Creates a StructuredQuery message from a plain object. Also converts values to their respective internal types. * @function fromObject @@ -9306,7 +9424,7 @@ } return message; }; - + /** * Creates a plain object from a StructuredQuery message. Also converts values to other types if specified. * @function toObject @@ -9359,7 +9477,7 @@ object.findNearest = $root.google.firestore.v1.StructuredQuery.FindNearest.toObject(message.findNearest, options); return object; }; - + /** * Converts this StructuredQuery to JSON. * @function toJSON @@ -9370,7 +9488,7 @@ StructuredQuery.prototype.toJSON = function toJSON() { return this.constructor.toObject(this, $protobuf.util.toJSONOptions); }; - + /** * Gets the default type url for StructuredQuery * @function getTypeUrl @@ -9385,9 +9503,9 @@ } return typeUrlPrefix + "/google.firestore.v1.StructuredQuery"; }; - + StructuredQuery.CollectionSelector = (function() { - + /** * Properties of a CollectionSelector. * @memberof google.firestore.v1.StructuredQuery @@ -9395,7 +9513,7 @@ * @property {string|null} [collectionId] CollectionSelector collectionId * @property {boolean|null} [allDescendants] CollectionSelector allDescendants */ - + /** * Constructs a new CollectionSelector. * @memberof google.firestore.v1.StructuredQuery @@ -9410,7 +9528,7 @@ if (properties[keys[i]] != null) this[keys[i]] = properties[keys[i]]; } - + /** * CollectionSelector collectionId. * @member {string} collectionId @@ -9418,7 +9536,7 @@ * @instance */ CollectionSelector.prototype.collectionId = ""; - + /** * CollectionSelector allDescendants. * @member {boolean} allDescendants @@ -9426,7 +9544,7 @@ * @instance */ CollectionSelector.prototype.allDescendants = false; - + /** * Creates a CollectionSelector message from a plain object. Also converts values to their respective internal types. * @function fromObject @@ -9445,7 +9563,7 @@ message.allDescendants = Boolean(object.allDescendants); return message; }; - + /** * Creates a plain object from a CollectionSelector message. Also converts values to other types if specified. * @function toObject @@ -9469,7 +9587,7 @@ object.allDescendants = message.allDescendants; return object; }; - + /** * Converts this CollectionSelector to JSON. * @function toJSON @@ -9480,7 +9598,7 @@ CollectionSelector.prototype.toJSON = function toJSON() { return this.constructor.toObject(this, $protobuf.util.toJSONOptions); }; - + /** * Gets the default type url for CollectionSelector * @function getTypeUrl @@ -9495,12 +9613,12 @@ } return typeUrlPrefix + "/google.firestore.v1.StructuredQuery.CollectionSelector"; }; - + return CollectionSelector; })(); - + StructuredQuery.Filter = (function() { - + /** * Properties of a Filter. * @memberof google.firestore.v1.StructuredQuery @@ -9509,7 +9627,7 @@ * @property {google.firestore.v1.StructuredQuery.IFieldFilter|null} [fieldFilter] Filter fieldFilter * @property {google.firestore.v1.StructuredQuery.IUnaryFilter|null} [unaryFilter] Filter unaryFilter */ - + /** * Constructs a new Filter. * @memberof google.firestore.v1.StructuredQuery @@ -9524,7 +9642,7 @@ if (properties[keys[i]] != null) this[keys[i]] = properties[keys[i]]; } - + /** * Filter compositeFilter. * @member {google.firestore.v1.StructuredQuery.ICompositeFilter|null|undefined} compositeFilter @@ -9532,7 +9650,7 @@ * @instance */ Filter.prototype.compositeFilter = null; - + /** * Filter fieldFilter. * @member {google.firestore.v1.StructuredQuery.IFieldFilter|null|undefined} fieldFilter @@ -9540,7 +9658,7 @@ * @instance */ Filter.prototype.fieldFilter = null; - + /** * Filter unaryFilter. * @member {google.firestore.v1.StructuredQuery.IUnaryFilter|null|undefined} unaryFilter @@ -9548,10 +9666,10 @@ * @instance */ Filter.prototype.unaryFilter = null; - + // OneOf field names bound to virtual getters and setters var $oneOfFields; - + /** * Filter filterType. * @member {"compositeFilter"|"fieldFilter"|"unaryFilter"|undefined} filterType @@ -9562,7 +9680,7 @@ get: $util.oneOfGetter($oneOfFields = ["compositeFilter", "fieldFilter", "unaryFilter"]), set: $util.oneOfSetter($oneOfFields) }); - + /** * Creates a Filter message from a plain object. Also converts values to their respective internal types. * @function fromObject @@ -9592,7 +9710,7 @@ } return message; }; - + /** * Creates a plain object from a Filter message. Also converts values to other types if specified. * @function toObject @@ -9623,7 +9741,7 @@ } return object; }; - + /** * Converts this Filter to JSON. * @function toJSON @@ -9634,7 +9752,7 @@ Filter.prototype.toJSON = function toJSON() { return this.constructor.toObject(this, $protobuf.util.toJSONOptions); }; - + /** * Gets the default type url for Filter * @function getTypeUrl @@ -9649,12 +9767,12 @@ } return typeUrlPrefix + "/google.firestore.v1.StructuredQuery.Filter"; }; - + return Filter; })(); - + StructuredQuery.CompositeFilter = (function() { - + /** * Properties of a CompositeFilter. * @memberof google.firestore.v1.StructuredQuery @@ -9662,7 +9780,7 @@ * @property {google.firestore.v1.StructuredQuery.CompositeFilter.Operator|null} [op] CompositeFilter op * @property {Array.|null} [filters] CompositeFilter filters */ - + /** * Constructs a new CompositeFilter. * @memberof google.firestore.v1.StructuredQuery @@ -9678,7 +9796,7 @@ if (properties[keys[i]] != null) this[keys[i]] = properties[keys[i]]; } - + /** * CompositeFilter op. * @member {google.firestore.v1.StructuredQuery.CompositeFilter.Operator} op @@ -9686,7 +9804,7 @@ * @instance */ CompositeFilter.prototype.op = 0; - + /** * CompositeFilter filters. * @member {Array.} filters @@ -9694,7 +9812,7 @@ * @instance */ CompositeFilter.prototype.filters = $util.emptyArray; - + /** * Creates a CompositeFilter message from a plain object. Also converts values to their respective internal types. * @function fromObject @@ -9739,7 +9857,7 @@ } return message; }; - + /** * Creates a plain object from a CompositeFilter message. Also converts values to other types if specified. * @function toObject @@ -9766,7 +9884,7 @@ } return object; }; - + /** * Converts this CompositeFilter to JSON. * @function toJSON @@ -9777,7 +9895,7 @@ CompositeFilter.prototype.toJSON = function toJSON() { return this.constructor.toObject(this, $protobuf.util.toJSONOptions); }; - + /** * Gets the default type url for CompositeFilter * @function getTypeUrl @@ -9792,7 +9910,7 @@ } return typeUrlPrefix + "/google.firestore.v1.StructuredQuery.CompositeFilter"; }; - + /** * Operator enum. * @name google.firestore.v1.StructuredQuery.CompositeFilter.Operator @@ -9808,12 +9926,12 @@ values[valuesById[2] = "OR"] = "OR"; return values; })(); - + return CompositeFilter; })(); - + StructuredQuery.FieldFilter = (function() { - + /** * Properties of a FieldFilter. * @memberof google.firestore.v1.StructuredQuery @@ -9822,7 +9940,7 @@ * @property {google.firestore.v1.StructuredQuery.FieldFilter.Operator|null} [op] FieldFilter op * @property {google.firestore.v1.IValue|null} [value] FieldFilter value */ - + /** * Constructs a new FieldFilter. * @memberof google.firestore.v1.StructuredQuery @@ -9837,7 +9955,7 @@ if (properties[keys[i]] != null) this[keys[i]] = properties[keys[i]]; } - + /** * FieldFilter field. * @member {google.firestore.v1.StructuredQuery.IFieldReference|null|undefined} field @@ -9845,7 +9963,7 @@ * @instance */ FieldFilter.prototype.field = null; - + /** * FieldFilter op. * @member {google.firestore.v1.StructuredQuery.FieldFilter.Operator} op @@ -9853,7 +9971,7 @@ * @instance */ FieldFilter.prototype.op = 0; - + /** * FieldFilter value. * @member {google.firestore.v1.IValue|null|undefined} value @@ -9861,7 +9979,7 @@ * @instance */ FieldFilter.prototype.value = null; - + /** * Creates a FieldFilter message from a plain object. Also converts values to their respective internal types. * @function fromObject @@ -9938,7 +10056,7 @@ } return message; }; - + /** * Creates a plain object from a FieldFilter message. Also converts values to other types if specified. * @function toObject @@ -9965,7 +10083,7 @@ object.value = $root.google.firestore.v1.Value.toObject(message.value, options); return object; }; - + /** * Converts this FieldFilter to JSON. * @function toJSON @@ -9976,7 +10094,7 @@ FieldFilter.prototype.toJSON = function toJSON() { return this.constructor.toObject(this, $protobuf.util.toJSONOptions); }; - + /** * Gets the default type url for FieldFilter * @function getTypeUrl @@ -9991,7 +10109,7 @@ } return typeUrlPrefix + "/google.firestore.v1.StructuredQuery.FieldFilter"; }; - + /** * Operator enum. * @name google.firestore.v1.StructuredQuery.FieldFilter.Operator @@ -10023,12 +10141,12 @@ values[valuesById[10] = "NOT_IN"] = "NOT_IN"; return values; })(); - + return FieldFilter; })(); - + StructuredQuery.UnaryFilter = (function() { - + /** * Properties of an UnaryFilter. * @memberof google.firestore.v1.StructuredQuery @@ -10036,7 +10154,7 @@ * @property {google.firestore.v1.StructuredQuery.UnaryFilter.Operator|null} [op] UnaryFilter op * @property {google.firestore.v1.StructuredQuery.IFieldReference|null} [field] UnaryFilter field */ - + /** * Constructs a new UnaryFilter. * @memberof google.firestore.v1.StructuredQuery @@ -10051,7 +10169,7 @@ if (properties[keys[i]] != null) this[keys[i]] = properties[keys[i]]; } - + /** * UnaryFilter op. * @member {google.firestore.v1.StructuredQuery.UnaryFilter.Operator} op @@ -10059,7 +10177,7 @@ * @instance */ UnaryFilter.prototype.op = 0; - + /** * UnaryFilter field. * @member {google.firestore.v1.StructuredQuery.IFieldReference|null|undefined} field @@ -10067,10 +10185,10 @@ * @instance */ UnaryFilter.prototype.field = null; - + // OneOf field names bound to virtual getters and setters var $oneOfFields; - + /** * UnaryFilter operandType. * @member {"field"|undefined} operandType @@ -10081,7 +10199,7 @@ get: $util.oneOfGetter($oneOfFields = ["field"]), set: $util.oneOfSetter($oneOfFields) }); - + /** * Creates an UnaryFilter message from a plain object. Also converts values to their respective internal types. * @function fromObject @@ -10129,7 +10247,7 @@ } return message; }; - + /** * Creates a plain object from an UnaryFilter message. Also converts values to other types if specified. * @function toObject @@ -10154,7 +10272,7 @@ } return object; }; - + /** * Converts this UnaryFilter to JSON. * @function toJSON @@ -10165,7 +10283,7 @@ UnaryFilter.prototype.toJSON = function toJSON() { return this.constructor.toObject(this, $protobuf.util.toJSONOptions); }; - + /** * Gets the default type url for UnaryFilter * @function getTypeUrl @@ -10180,7 +10298,7 @@ } return typeUrlPrefix + "/google.firestore.v1.StructuredQuery.UnaryFilter"; }; - + /** * Operator enum. * @name google.firestore.v1.StructuredQuery.UnaryFilter.Operator @@ -10200,12 +10318,12 @@ values[valuesById[5] = "IS_NOT_NULL"] = "IS_NOT_NULL"; return values; })(); - + return UnaryFilter; })(); - + StructuredQuery.Order = (function() { - + /** * Properties of an Order. * @memberof google.firestore.v1.StructuredQuery @@ -10213,7 +10331,7 @@ * @property {google.firestore.v1.StructuredQuery.IFieldReference|null} [field] Order field * @property {google.firestore.v1.StructuredQuery.Direction|null} [direction] Order direction */ - + /** * Constructs a new Order. * @memberof google.firestore.v1.StructuredQuery @@ -10228,7 +10346,7 @@ if (properties[keys[i]] != null) this[keys[i]] = properties[keys[i]]; } - + /** * Order field. * @member {google.firestore.v1.StructuredQuery.IFieldReference|null|undefined} field @@ -10236,7 +10354,7 @@ * @instance */ Order.prototype.field = null; - + /** * Order direction. * @member {google.firestore.v1.StructuredQuery.Direction} direction @@ -10244,7 +10362,7 @@ * @instance */ Order.prototype.direction = 0; - + /** * Creates an Order message from a plain object. Also converts values to their respective internal types. * @function fromObject @@ -10284,7 +10402,7 @@ } return message; }; - + /** * Creates a plain object from an Order message. Also converts values to other types if specified. * @function toObject @@ -10308,7 +10426,7 @@ object.direction = options.enums === String ? $root.google.firestore.v1.StructuredQuery.Direction[message.direction] === undefined ? message.direction : $root.google.firestore.v1.StructuredQuery.Direction[message.direction] : message.direction; return object; }; - + /** * Converts this Order to JSON. * @function toJSON @@ -10319,7 +10437,7 @@ Order.prototype.toJSON = function toJSON() { return this.constructor.toObject(this, $protobuf.util.toJSONOptions); }; - + /** * Gets the default type url for Order * @function getTypeUrl @@ -10334,10 +10452,10 @@ } return typeUrlPrefix + "/google.firestore.v1.StructuredQuery.Order"; }; - + return Order; })(); - + /** * Direction enum. * @name google.firestore.v1.StructuredQuery.Direction @@ -10353,16 +10471,16 @@ values[valuesById[2] = "DESCENDING"] = "DESCENDING"; return values; })(); - + StructuredQuery.FieldReference = (function() { - + /** * Properties of a FieldReference. * @memberof google.firestore.v1.StructuredQuery * @interface IFieldReference * @property {string|null} [fieldPath] FieldReference fieldPath */ - + /** * Constructs a new FieldReference. * @memberof google.firestore.v1.StructuredQuery @@ -10377,7 +10495,7 @@ if (properties[keys[i]] != null) this[keys[i]] = properties[keys[i]]; } - + /** * FieldReference fieldPath. * @member {string} fieldPath @@ -10385,7 +10503,7 @@ * @instance */ FieldReference.prototype.fieldPath = ""; - + /** * Creates a FieldReference message from a plain object. Also converts values to their respective internal types. * @function fromObject @@ -10402,7 +10520,7 @@ message.fieldPath = String(object.fieldPath); return message; }; - + /** * Creates a plain object from a FieldReference message. Also converts values to other types if specified. * @function toObject @@ -10422,7 +10540,7 @@ object.fieldPath = message.fieldPath; return object; }; - + /** * Converts this FieldReference to JSON. * @function toJSON @@ -10433,7 +10551,7 @@ FieldReference.prototype.toJSON = function toJSON() { return this.constructor.toObject(this, $protobuf.util.toJSONOptions); }; - + /** * Gets the default type url for FieldReference * @function getTypeUrl @@ -10448,19 +10566,19 @@ } return typeUrlPrefix + "/google.firestore.v1.StructuredQuery.FieldReference"; }; - + return FieldReference; })(); - + StructuredQuery.Projection = (function() { - + /** * Properties of a Projection. * @memberof google.firestore.v1.StructuredQuery * @interface IProjection * @property {Array.|null} [fields] Projection fields */ - + /** * Constructs a new Projection. * @memberof google.firestore.v1.StructuredQuery @@ -10476,7 +10594,7 @@ if (properties[keys[i]] != null) this[keys[i]] = properties[keys[i]]; } - + /** * Projection fields. * @member {Array.} fields @@ -10484,7 +10602,7 @@ * @instance */ Projection.prototype.fields = $util.emptyArray; - + /** * Creates a Projection message from a plain object. Also converts values to their respective internal types. * @function fromObject @@ -10509,7 +10627,7 @@ } return message; }; - + /** * Creates a plain object from a Projection message. Also converts values to other types if specified. * @function toObject @@ -10532,7 +10650,7 @@ } return object; }; - + /** * Converts this Projection to JSON. * @function toJSON @@ -10543,7 +10661,7 @@ Projection.prototype.toJSON = function toJSON() { return this.constructor.toObject(this, $protobuf.util.toJSONOptions); }; - + /** * Gets the default type url for Projection * @function getTypeUrl @@ -10558,12 +10676,12 @@ } return typeUrlPrefix + "/google.firestore.v1.StructuredQuery.Projection"; }; - + return Projection; })(); - + StructuredQuery.FindNearest = (function() { - + /** * Properties of a FindNearest. * @memberof google.firestore.v1.StructuredQuery @@ -10575,7 +10693,7 @@ * @property {string|null} [distanceResultField] FindNearest distanceResultField * @property {google.protobuf.IDoubleValue|null} [distanceThreshold] FindNearest distanceThreshold */ - + /** * Constructs a new FindNearest. * @memberof google.firestore.v1.StructuredQuery @@ -10590,7 +10708,7 @@ if (properties[keys[i]] != null) this[keys[i]] = properties[keys[i]]; } - + /** * FindNearest vectorField. * @member {google.firestore.v1.StructuredQuery.IFieldReference|null|undefined} vectorField @@ -10598,7 +10716,7 @@ * @instance */ FindNearest.prototype.vectorField = null; - + /** * FindNearest queryVector. * @member {google.firestore.v1.IValue|null|undefined} queryVector @@ -10606,7 +10724,7 @@ * @instance */ FindNearest.prototype.queryVector = null; - + /** * FindNearest distanceMeasure. * @member {google.firestore.v1.StructuredQuery.FindNearest.DistanceMeasure} distanceMeasure @@ -10614,7 +10732,7 @@ * @instance */ FindNearest.prototype.distanceMeasure = 0; - + /** * FindNearest limit. * @member {google.protobuf.IInt32Value|null|undefined} limit @@ -10622,7 +10740,7 @@ * @instance */ FindNearest.prototype.limit = null; - + /** * FindNearest distanceResultField. * @member {string} distanceResultField @@ -10630,7 +10748,7 @@ * @instance */ FindNearest.prototype.distanceResultField = ""; - + /** * FindNearest distanceThreshold. * @member {google.protobuf.IDoubleValue|null|undefined} distanceThreshold @@ -10638,7 +10756,7 @@ * @instance */ FindNearest.prototype.distanceThreshold = null; - + /** * Creates a FindNearest message from a plain object. Also converts values to their respective internal types. * @function fromObject @@ -10699,7 +10817,7 @@ } return message; }; - + /** * Creates a plain object from a FindNearest message. Also converts values to other types if specified. * @function toObject @@ -10735,7 +10853,7 @@ object.distanceThreshold = $root.google.protobuf.DoubleValue.toObject(message.distanceThreshold, options); return object; }; - + /** * Converts this FindNearest to JSON. * @function toJSON @@ -10746,7 +10864,7 @@ FindNearest.prototype.toJSON = function toJSON() { return this.constructor.toObject(this, $protobuf.util.toJSONOptions); }; - + /** * Gets the default type url for FindNearest * @function getTypeUrl @@ -10761,7 +10879,7 @@ } return typeUrlPrefix + "/google.firestore.v1.StructuredQuery.FindNearest"; }; - + /** * DistanceMeasure enum. * @name google.firestore.v1.StructuredQuery.FindNearest.DistanceMeasure @@ -10779,15 +10897,15 @@ values[valuesById[3] = "DOT_PRODUCT"] = "DOT_PRODUCT"; return values; })(); - + return FindNearest; })(); - + return StructuredQuery; })(); - + v1.StructuredAggregationQuery = (function() { - + /** * Properties of a StructuredAggregationQuery. * @memberof google.firestore.v1 @@ -10795,7 +10913,7 @@ * @property {google.firestore.v1.IStructuredQuery|null} [structuredQuery] StructuredAggregationQuery structuredQuery * @property {Array.|null} [aggregations] StructuredAggregationQuery aggregations */ - + /** * Constructs a new StructuredAggregationQuery. * @memberof google.firestore.v1 @@ -10811,7 +10929,7 @@ if (properties[keys[i]] != null) this[keys[i]] = properties[keys[i]]; } - + /** * StructuredAggregationQuery structuredQuery. * @member {google.firestore.v1.IStructuredQuery|null|undefined} structuredQuery @@ -10819,7 +10937,7 @@ * @instance */ StructuredAggregationQuery.prototype.structuredQuery = null; - + /** * StructuredAggregationQuery aggregations. * @member {Array.} aggregations @@ -10827,10 +10945,10 @@ * @instance */ StructuredAggregationQuery.prototype.aggregations = $util.emptyArray; - + // OneOf field names bound to virtual getters and setters var $oneOfFields; - + /** * StructuredAggregationQuery queryType. * @member {"structuredQuery"|undefined} queryType @@ -10841,7 +10959,7 @@ get: $util.oneOfGetter($oneOfFields = ["structuredQuery"]), set: $util.oneOfSetter($oneOfFields) }); - + /** * Creates a StructuredAggregationQuery message from a plain object. Also converts values to their respective internal types. * @function fromObject @@ -10871,7 +10989,7 @@ } return message; }; - + /** * Creates a plain object from a StructuredAggregationQuery message. Also converts values to other types if specified. * @function toObject @@ -10899,7 +11017,7 @@ } return object; }; - + /** * Converts this StructuredAggregationQuery to JSON. * @function toJSON @@ -10910,7 +11028,7 @@ StructuredAggregationQuery.prototype.toJSON = function toJSON() { return this.constructor.toObject(this, $protobuf.util.toJSONOptions); }; - + /** * Gets the default type url for StructuredAggregationQuery * @function getTypeUrl @@ -10925,9 +11043,9 @@ } return typeUrlPrefix + "/google.firestore.v1.StructuredAggregationQuery"; }; - + StructuredAggregationQuery.Aggregation = (function() { - + /** * Properties of an Aggregation. * @memberof google.firestore.v1.StructuredAggregationQuery @@ -10937,7 +11055,7 @@ * @property {google.firestore.v1.StructuredAggregationQuery.Aggregation.IAvg|null} [avg] Aggregation avg * @property {string|null} [alias] Aggregation alias */ - + /** * Constructs a new Aggregation. * @memberof google.firestore.v1.StructuredAggregationQuery @@ -10952,7 +11070,7 @@ if (properties[keys[i]] != null) this[keys[i]] = properties[keys[i]]; } - + /** * Aggregation count. * @member {google.firestore.v1.StructuredAggregationQuery.Aggregation.ICount|null|undefined} count @@ -10960,7 +11078,7 @@ * @instance */ Aggregation.prototype.count = null; - + /** * Aggregation sum. * @member {google.firestore.v1.StructuredAggregationQuery.Aggregation.ISum|null|undefined} sum @@ -10968,7 +11086,7 @@ * @instance */ Aggregation.prototype.sum = null; - + /** * Aggregation avg. * @member {google.firestore.v1.StructuredAggregationQuery.Aggregation.IAvg|null|undefined} avg @@ -10976,7 +11094,7 @@ * @instance */ Aggregation.prototype.avg = null; - + /** * Aggregation alias. * @member {string} alias @@ -10984,10 +11102,10 @@ * @instance */ Aggregation.prototype.alias = ""; - + // OneOf field names bound to virtual getters and setters var $oneOfFields; - + /** * Aggregation operator. * @member {"count"|"sum"|"avg"|undefined} operator @@ -10998,7 +11116,7 @@ get: $util.oneOfGetter($oneOfFields = ["count", "sum", "avg"]), set: $util.oneOfSetter($oneOfFields) }); - + /** * Creates an Aggregation message from a plain object. Also converts values to their respective internal types. * @function fromObject @@ -11030,7 +11148,7 @@ message.alias = String(object.alias); return message; }; - + /** * Creates a plain object from an Aggregation message. Also converts values to other types if specified. * @function toObject @@ -11065,7 +11183,7 @@ object.alias = message.alias; return object; }; - + /** * Converts this Aggregation to JSON. * @function toJSON @@ -11076,7 +11194,7 @@ Aggregation.prototype.toJSON = function toJSON() { return this.constructor.toObject(this, $protobuf.util.toJSONOptions); }; - + /** * Gets the default type url for Aggregation * @function getTypeUrl @@ -11091,16 +11209,16 @@ } return typeUrlPrefix + "/google.firestore.v1.StructuredAggregationQuery.Aggregation"; }; - + Aggregation.Count = (function() { - + /** * Properties of a Count. * @memberof google.firestore.v1.StructuredAggregationQuery.Aggregation * @interface ICount * @property {google.protobuf.IInt64Value|null} [upTo] Count upTo */ - + /** * Constructs a new Count. * @memberof google.firestore.v1.StructuredAggregationQuery.Aggregation @@ -11115,7 +11233,7 @@ if (properties[keys[i]] != null) this[keys[i]] = properties[keys[i]]; } - + /** * Count upTo. * @member {google.protobuf.IInt64Value|null|undefined} upTo @@ -11123,7 +11241,7 @@ * @instance */ Count.prototype.upTo = null; - + /** * Creates a Count message from a plain object. Also converts values to their respective internal types. * @function fromObject @@ -11143,7 +11261,7 @@ } return message; }; - + /** * Creates a plain object from a Count message. Also converts values to other types if specified. * @function toObject @@ -11163,7 +11281,7 @@ object.upTo = $root.google.protobuf.Int64Value.toObject(message.upTo, options); return object; }; - + /** * Converts this Count to JSON. * @function toJSON @@ -11174,7 +11292,7 @@ Count.prototype.toJSON = function toJSON() { return this.constructor.toObject(this, $protobuf.util.toJSONOptions); }; - + /** * Gets the default type url for Count * @function getTypeUrl @@ -11189,19 +11307,19 @@ } return typeUrlPrefix + "/google.firestore.v1.StructuredAggregationQuery.Aggregation.Count"; }; - + return Count; })(); - + Aggregation.Sum = (function() { - + /** * Properties of a Sum. * @memberof google.firestore.v1.StructuredAggregationQuery.Aggregation * @interface ISum * @property {google.firestore.v1.StructuredQuery.IFieldReference|null} [field] Sum field */ - + /** * Constructs a new Sum. * @memberof google.firestore.v1.StructuredAggregationQuery.Aggregation @@ -11216,7 +11334,7 @@ if (properties[keys[i]] != null) this[keys[i]] = properties[keys[i]]; } - + /** * Sum field. * @member {google.firestore.v1.StructuredQuery.IFieldReference|null|undefined} field @@ -11224,7 +11342,7 @@ * @instance */ Sum.prototype.field = null; - + /** * Creates a Sum message from a plain object. Also converts values to their respective internal types. * @function fromObject @@ -11244,7 +11362,7 @@ } return message; }; - + /** * Creates a plain object from a Sum message. Also converts values to other types if specified. * @function toObject @@ -11264,7 +11382,7 @@ object.field = $root.google.firestore.v1.StructuredQuery.FieldReference.toObject(message.field, options); return object; }; - + /** * Converts this Sum to JSON. * @function toJSON @@ -11275,7 +11393,7 @@ Sum.prototype.toJSON = function toJSON() { return this.constructor.toObject(this, $protobuf.util.toJSONOptions); }; - + /** * Gets the default type url for Sum * @function getTypeUrl @@ -11290,19 +11408,19 @@ } return typeUrlPrefix + "/google.firestore.v1.StructuredAggregationQuery.Aggregation.Sum"; }; - + return Sum; })(); - + Aggregation.Avg = (function() { - + /** * Properties of an Avg. * @memberof google.firestore.v1.StructuredAggregationQuery.Aggregation * @interface IAvg * @property {google.firestore.v1.StructuredQuery.IFieldReference|null} [field] Avg field */ - + /** * Constructs a new Avg. * @memberof google.firestore.v1.StructuredAggregationQuery.Aggregation @@ -11317,7 +11435,7 @@ if (properties[keys[i]] != null) this[keys[i]] = properties[keys[i]]; } - + /** * Avg field. * @member {google.firestore.v1.StructuredQuery.IFieldReference|null|undefined} field @@ -11325,7 +11443,7 @@ * @instance */ Avg.prototype.field = null; - + /** * Creates an Avg message from a plain object. Also converts values to their respective internal types. * @function fromObject @@ -11345,7 +11463,7 @@ } return message; }; - + /** * Creates a plain object from an Avg message. Also converts values to other types if specified. * @function toObject @@ -11365,7 +11483,7 @@ object.field = $root.google.firestore.v1.StructuredQuery.FieldReference.toObject(message.field, options); return object; }; - + /** * Converts this Avg to JSON. * @function toJSON @@ -11376,7 +11494,7 @@ Avg.prototype.toJSON = function toJSON() { return this.constructor.toObject(this, $protobuf.util.toJSONOptions); }; - + /** * Gets the default type url for Avg * @function getTypeUrl @@ -11391,18 +11509,18 @@ } return typeUrlPrefix + "/google.firestore.v1.StructuredAggregationQuery.Aggregation.Avg"; }; - + return Avg; })(); - + return Aggregation; })(); - + return StructuredAggregationQuery; })(); - + v1.Cursor = (function() { - + /** * Properties of a Cursor. * @memberof google.firestore.v1 @@ -11410,7 +11528,7 @@ * @property {Array.|null} [values] Cursor values * @property {boolean|null} [before] Cursor before */ - + /** * Constructs a new Cursor. * @memberof google.firestore.v1 @@ -11426,7 +11544,7 @@ if (properties[keys[i]] != null) this[keys[i]] = properties[keys[i]]; } - + /** * Cursor values. * @member {Array.} values @@ -11434,7 +11552,7 @@ * @instance */ Cursor.prototype.values = $util.emptyArray; - + /** * Cursor before. * @member {boolean} before @@ -11442,7 +11560,7 @@ * @instance */ Cursor.prototype.before = false; - + /** * Creates a Cursor message from a plain object. Also converts values to their respective internal types. * @function fromObject @@ -11469,7 +11587,7 @@ message.before = Boolean(object.before); return message; }; - + /** * Creates a plain object from a Cursor message. Also converts values to other types if specified. * @function toObject @@ -11496,7 +11614,7 @@ object.before = message.before; return object; }; - + /** * Converts this Cursor to JSON. * @function toJSON @@ -11507,7 +11625,7 @@ Cursor.prototype.toJSON = function toJSON() { return this.constructor.toObject(this, $protobuf.util.toJSONOptions); }; - + /** * Gets the default type url for Cursor * @function getTypeUrl @@ -11522,19 +11640,19 @@ } return typeUrlPrefix + "/google.firestore.v1.Cursor"; }; - + return Cursor; })(); - + v1.ExplainOptions = (function() { - + /** * Properties of an ExplainOptions. * @memberof google.firestore.v1 * @interface IExplainOptions * @property {boolean|null} [analyze] ExplainOptions analyze */ - + /** * Constructs a new ExplainOptions. * @memberof google.firestore.v1 @@ -11549,7 +11667,7 @@ if (properties[keys[i]] != null) this[keys[i]] = properties[keys[i]]; } - + /** * ExplainOptions analyze. * @member {boolean} analyze @@ -11557,7 +11675,7 @@ * @instance */ ExplainOptions.prototype.analyze = false; - + /** * Creates an ExplainOptions message from a plain object. Also converts values to their respective internal types. * @function fromObject @@ -11574,7 +11692,7 @@ message.analyze = Boolean(object.analyze); return message; }; - + /** * Creates a plain object from an ExplainOptions message. Also converts values to other types if specified. * @function toObject @@ -11594,7 +11712,7 @@ object.analyze = message.analyze; return object; }; - + /** * Converts this ExplainOptions to JSON. * @function toJSON @@ -11605,7 +11723,7 @@ ExplainOptions.prototype.toJSON = function toJSON() { return this.constructor.toObject(this, $protobuf.util.toJSONOptions); }; - + /** * Gets the default type url for ExplainOptions * @function getTypeUrl @@ -11620,12 +11738,12 @@ } return typeUrlPrefix + "/google.firestore.v1.ExplainOptions"; }; - + return ExplainOptions; })(); - + v1.ExplainMetrics = (function() { - + /** * Properties of an ExplainMetrics. * @memberof google.firestore.v1 @@ -11633,7 +11751,7 @@ * @property {google.firestore.v1.IPlanSummary|null} [planSummary] ExplainMetrics planSummary * @property {google.firestore.v1.IExecutionStats|null} [executionStats] ExplainMetrics executionStats */ - + /** * Constructs a new ExplainMetrics. * @memberof google.firestore.v1 @@ -11648,7 +11766,7 @@ if (properties[keys[i]] != null) this[keys[i]] = properties[keys[i]]; } - + /** * ExplainMetrics planSummary. * @member {google.firestore.v1.IPlanSummary|null|undefined} planSummary @@ -11656,7 +11774,7 @@ * @instance */ ExplainMetrics.prototype.planSummary = null; - + /** * ExplainMetrics executionStats. * @member {google.firestore.v1.IExecutionStats|null|undefined} executionStats @@ -11664,7 +11782,7 @@ * @instance */ ExplainMetrics.prototype.executionStats = null; - + /** * Creates an ExplainMetrics message from a plain object. Also converts values to their respective internal types. * @function fromObject @@ -11689,7 +11807,7 @@ } return message; }; - + /** * Creates a plain object from an ExplainMetrics message. Also converts values to other types if specified. * @function toObject @@ -11713,7 +11831,7 @@ object.executionStats = $root.google.firestore.v1.ExecutionStats.toObject(message.executionStats, options); return object; }; - + /** * Converts this ExplainMetrics to JSON. * @function toJSON @@ -11724,7 +11842,7 @@ ExplainMetrics.prototype.toJSON = function toJSON() { return this.constructor.toObject(this, $protobuf.util.toJSONOptions); }; - + /** * Gets the default type url for ExplainMetrics * @function getTypeUrl @@ -11739,19 +11857,19 @@ } return typeUrlPrefix + "/google.firestore.v1.ExplainMetrics"; }; - + return ExplainMetrics; })(); - + v1.PlanSummary = (function() { - + /** * Properties of a PlanSummary. * @memberof google.firestore.v1 * @interface IPlanSummary * @property {Array.|null} [indexesUsed] PlanSummary indexesUsed */ - + /** * Constructs a new PlanSummary. * @memberof google.firestore.v1 @@ -11767,7 +11885,7 @@ if (properties[keys[i]] != null) this[keys[i]] = properties[keys[i]]; } - + /** * PlanSummary indexesUsed. * @member {Array.} indexesUsed @@ -11775,7 +11893,7 @@ * @instance */ PlanSummary.prototype.indexesUsed = $util.emptyArray; - + /** * Creates a PlanSummary message from a plain object. Also converts values to their respective internal types. * @function fromObject @@ -11800,7 +11918,7 @@ } return message; }; - + /** * Creates a plain object from a PlanSummary message. Also converts values to other types if specified. * @function toObject @@ -11823,7 +11941,7 @@ } return object; }; - + /** * Converts this PlanSummary to JSON. * @function toJSON @@ -11834,7 +11952,7 @@ PlanSummary.prototype.toJSON = function toJSON() { return this.constructor.toObject(this, $protobuf.util.toJSONOptions); }; - + /** * Gets the default type url for PlanSummary * @function getTypeUrl @@ -11849,12 +11967,12 @@ } return typeUrlPrefix + "/google.firestore.v1.PlanSummary"; }; - + return PlanSummary; })(); - + v1.ExecutionStats = (function() { - + /** * Properties of an ExecutionStats. * @memberof google.firestore.v1 @@ -11864,7 +11982,7 @@ * @property {number|string|null} [readOperations] ExecutionStats readOperations * @property {google.protobuf.IStruct|null} [debugStats] ExecutionStats debugStats */ - + /** * Constructs a new ExecutionStats. * @memberof google.firestore.v1 @@ -11879,7 +11997,7 @@ if (properties[keys[i]] != null) this[keys[i]] = properties[keys[i]]; } - + /** * ExecutionStats resultsReturned. * @member {number|string} resultsReturned @@ -11887,7 +12005,7 @@ * @instance */ ExecutionStats.prototype.resultsReturned = $util.Long ? $util.Long.fromBits(0,0,false) : 0; - + /** * ExecutionStats executionDuration. * @member {google.protobuf.IDuration|null|undefined} executionDuration @@ -11895,7 +12013,7 @@ * @instance */ ExecutionStats.prototype.executionDuration = null; - + /** * ExecutionStats readOperations. * @member {number|string} readOperations @@ -11903,7 +12021,7 @@ * @instance */ ExecutionStats.prototype.readOperations = $util.Long ? $util.Long.fromBits(0,0,false) : 0; - + /** * ExecutionStats debugStats. * @member {google.protobuf.IStruct|null|undefined} debugStats @@ -11911,7 +12029,7 @@ * @instance */ ExecutionStats.prototype.debugStats = null; - + /** * Creates an ExecutionStats message from a plain object. Also converts values to their respective internal types. * @function fromObject @@ -11954,7 +12072,7 @@ } return message; }; - + /** * Creates a plain object from an ExecutionStats message. Also converts values to other types if specified. * @function toObject @@ -11998,7 +12116,7 @@ object.debugStats = $root.google.protobuf.Struct.toObject(message.debugStats, options); return object; }; - + /** * Converts this ExecutionStats to JSON. * @function toJSON @@ -12009,7 +12127,7 @@ ExecutionStats.prototype.toJSON = function toJSON() { return this.constructor.toObject(this, $protobuf.util.toJSONOptions); }; - + /** * Gets the default type url for ExecutionStats * @function getTypeUrl @@ -12024,12 +12142,12 @@ } return typeUrlPrefix + "/google.firestore.v1.ExecutionStats"; }; - + return ExecutionStats; })(); - + v1.Write = (function() { - + /** * Properties of a Write. * @memberof google.firestore.v1 @@ -12041,7 +12159,7 @@ * @property {Array.|null} [updateTransforms] Write updateTransforms * @property {google.firestore.v1.IPrecondition|null} [currentDocument] Write currentDocument */ - + /** * Constructs a new Write. * @memberof google.firestore.v1 @@ -12057,7 +12175,7 @@ if (properties[keys[i]] != null) this[keys[i]] = properties[keys[i]]; } - + /** * Write update. * @member {google.firestore.v1.IDocument|null|undefined} update @@ -12065,7 +12183,7 @@ * @instance */ Write.prototype.update = null; - + /** * Write delete. * @member {string|null|undefined} delete @@ -12073,7 +12191,7 @@ * @instance */ Write.prototype["delete"] = null; - + /** * Write transform. * @member {google.firestore.v1.IDocumentTransform|null|undefined} transform @@ -12081,7 +12199,7 @@ * @instance */ Write.prototype.transform = null; - + /** * Write updateMask. * @member {google.firestore.v1.IDocumentMask|null|undefined} updateMask @@ -12089,7 +12207,7 @@ * @instance */ Write.prototype.updateMask = null; - + /** * Write updateTransforms. * @member {Array.} updateTransforms @@ -12097,7 +12215,7 @@ * @instance */ Write.prototype.updateTransforms = $util.emptyArray; - + /** * Write currentDocument. * @member {google.firestore.v1.IPrecondition|null|undefined} currentDocument @@ -12105,10 +12223,10 @@ * @instance */ Write.prototype.currentDocument = null; - + // OneOf field names bound to virtual getters and setters var $oneOfFields; - + /** * Write operation. * @member {"update"|"delete"|"transform"|undefined} operation @@ -12119,7 +12237,7 @@ get: $util.oneOfGetter($oneOfFields = ["update", "delete", "transform"]), set: $util.oneOfSetter($oneOfFields) }); - + /** * Creates a Write message from a plain object. Also converts values to their respective internal types. * @function fromObject @@ -12166,7 +12284,7 @@ } return message; }; - + /** * Creates a plain object from a Write message. Also converts values to other types if specified. * @function toObject @@ -12212,7 +12330,7 @@ } return object; }; - + /** * Converts this Write to JSON. * @function toJSON @@ -12223,7 +12341,7 @@ Write.prototype.toJSON = function toJSON() { return this.constructor.toObject(this, $protobuf.util.toJSONOptions); }; - + /** * Gets the default type url for Write * @function getTypeUrl @@ -12238,12 +12356,12 @@ } return typeUrlPrefix + "/google.firestore.v1.Write"; }; - + return Write; })(); - + v1.DocumentTransform = (function() { - + /** * Properties of a DocumentTransform. * @memberof google.firestore.v1 @@ -12251,7 +12369,7 @@ * @property {string|null} [document] DocumentTransform document * @property {Array.|null} [fieldTransforms] DocumentTransform fieldTransforms */ - + /** * Constructs a new DocumentTransform. * @memberof google.firestore.v1 @@ -12267,7 +12385,7 @@ if (properties[keys[i]] != null) this[keys[i]] = properties[keys[i]]; } - + /** * DocumentTransform document. * @member {string} document @@ -12275,7 +12393,7 @@ * @instance */ DocumentTransform.prototype.document = ""; - + /** * DocumentTransform fieldTransforms. * @member {Array.} fieldTransforms @@ -12283,7 +12401,7 @@ * @instance */ DocumentTransform.prototype.fieldTransforms = $util.emptyArray; - + /** * Creates a DocumentTransform message from a plain object. Also converts values to their respective internal types. * @function fromObject @@ -12310,7 +12428,7 @@ } return message; }; - + /** * Creates a plain object from a DocumentTransform message. Also converts values to other types if specified. * @function toObject @@ -12337,7 +12455,7 @@ } return object; }; - + /** * Converts this DocumentTransform to JSON. * @function toJSON @@ -12348,7 +12466,7 @@ DocumentTransform.prototype.toJSON = function toJSON() { return this.constructor.toObject(this, $protobuf.util.toJSONOptions); }; - + /** * Gets the default type url for DocumentTransform * @function getTypeUrl @@ -12363,9 +12481,9 @@ } return typeUrlPrefix + "/google.firestore.v1.DocumentTransform"; }; - + DocumentTransform.FieldTransform = (function() { - + /** * Properties of a FieldTransform. * @memberof google.firestore.v1.DocumentTransform @@ -12378,7 +12496,7 @@ * @property {google.firestore.v1.IArrayValue|null} [appendMissingElements] FieldTransform appendMissingElements * @property {google.firestore.v1.IArrayValue|null} [removeAllFromArray] FieldTransform removeAllFromArray */ - + /** * Constructs a new FieldTransform. * @memberof google.firestore.v1.DocumentTransform @@ -12393,7 +12511,7 @@ if (properties[keys[i]] != null) this[keys[i]] = properties[keys[i]]; } - + /** * FieldTransform fieldPath. * @member {string} fieldPath @@ -12401,7 +12519,7 @@ * @instance */ FieldTransform.prototype.fieldPath = ""; - + /** * FieldTransform setToServerValue. * @member {google.firestore.v1.DocumentTransform.FieldTransform.ServerValue|null|undefined} setToServerValue @@ -12409,7 +12527,7 @@ * @instance */ FieldTransform.prototype.setToServerValue = null; - + /** * FieldTransform increment. * @member {google.firestore.v1.IValue|null|undefined} increment @@ -12417,7 +12535,7 @@ * @instance */ FieldTransform.prototype.increment = null; - + /** * FieldTransform maximum. * @member {google.firestore.v1.IValue|null|undefined} maximum @@ -12425,7 +12543,7 @@ * @instance */ FieldTransform.prototype.maximum = null; - + /** * FieldTransform minimum. * @member {google.firestore.v1.IValue|null|undefined} minimum @@ -12433,7 +12551,7 @@ * @instance */ FieldTransform.prototype.minimum = null; - + /** * FieldTransform appendMissingElements. * @member {google.firestore.v1.IArrayValue|null|undefined} appendMissingElements @@ -12441,7 +12559,7 @@ * @instance */ FieldTransform.prototype.appendMissingElements = null; - + /** * FieldTransform removeAllFromArray. * @member {google.firestore.v1.IArrayValue|null|undefined} removeAllFromArray @@ -12449,10 +12567,10 @@ * @instance */ FieldTransform.prototype.removeAllFromArray = null; - + // OneOf field names bound to virtual getters and setters var $oneOfFields; - + /** * FieldTransform transformType. * @member {"setToServerValue"|"increment"|"maximum"|"minimum"|"appendMissingElements"|"removeAllFromArray"|undefined} transformType @@ -12463,7 +12581,7 @@ get: $util.oneOfGetter($oneOfFields = ["setToServerValue", "increment", "maximum", "minimum", "appendMissingElements", "removeAllFromArray"]), set: $util.oneOfSetter($oneOfFields) }); - + /** * Creates a FieldTransform message from a plain object. Also converts values to their respective internal types. * @function fromObject @@ -12521,7 +12639,7 @@ } return message; }; - + /** * Creates a plain object from a FieldTransform message. Also converts values to other types if specified. * @function toObject @@ -12571,7 +12689,7 @@ } return object; }; - + /** * Converts this FieldTransform to JSON. * @function toJSON @@ -12582,7 +12700,7 @@ FieldTransform.prototype.toJSON = function toJSON() { return this.constructor.toObject(this, $protobuf.util.toJSONOptions); }; - + /** * Gets the default type url for FieldTransform * @function getTypeUrl @@ -12597,7 +12715,7 @@ } return typeUrlPrefix + "/google.firestore.v1.DocumentTransform.FieldTransform"; }; - + /** * ServerValue enum. * @name google.firestore.v1.DocumentTransform.FieldTransform.ServerValue @@ -12611,15 +12729,15 @@ values[valuesById[1] = "REQUEST_TIME"] = "REQUEST_TIME"; return values; })(); - + return FieldTransform; })(); - + return DocumentTransform; })(); - + v1.WriteResult = (function() { - + /** * Properties of a WriteResult. * @memberof google.firestore.v1 @@ -12627,7 +12745,7 @@ * @property {google.protobuf.ITimestamp|null} [updateTime] WriteResult updateTime * @property {Array.|null} [transformResults] WriteResult transformResults */ - + /** * Constructs a new WriteResult. * @memberof google.firestore.v1 @@ -12643,7 +12761,7 @@ if (properties[keys[i]] != null) this[keys[i]] = properties[keys[i]]; } - + /** * WriteResult updateTime. * @member {google.protobuf.ITimestamp|null|undefined} updateTime @@ -12651,7 +12769,7 @@ * @instance */ WriteResult.prototype.updateTime = null; - + /** * WriteResult transformResults. * @member {Array.} transformResults @@ -12659,7 +12777,7 @@ * @instance */ WriteResult.prototype.transformResults = $util.emptyArray; - + /** * Creates a WriteResult message from a plain object. Also converts values to their respective internal types. * @function fromObject @@ -12689,7 +12807,7 @@ } return message; }; - + /** * Creates a plain object from a WriteResult message. Also converts values to other types if specified. * @function toObject @@ -12716,7 +12834,7 @@ } return object; }; - + /** * Converts this WriteResult to JSON. * @function toJSON @@ -12727,7 +12845,7 @@ WriteResult.prototype.toJSON = function toJSON() { return this.constructor.toObject(this, $protobuf.util.toJSONOptions); }; - + /** * Gets the default type url for WriteResult * @function getTypeUrl @@ -12742,12 +12860,12 @@ } return typeUrlPrefix + "/google.firestore.v1.WriteResult"; }; - + return WriteResult; })(); - + v1.DocumentChange = (function() { - + /** * Properties of a DocumentChange. * @memberof google.firestore.v1 @@ -12756,7 +12874,7 @@ * @property {Array.|null} [targetIds] DocumentChange targetIds * @property {Array.|null} [removedTargetIds] DocumentChange removedTargetIds */ - + /** * Constructs a new DocumentChange. * @memberof google.firestore.v1 @@ -12773,7 +12891,7 @@ if (properties[keys[i]] != null) this[keys[i]] = properties[keys[i]]; } - + /** * DocumentChange document. * @member {google.firestore.v1.IDocument|null|undefined} document @@ -12781,7 +12899,7 @@ * @instance */ DocumentChange.prototype.document = null; - + /** * DocumentChange targetIds. * @member {Array.} targetIds @@ -12789,7 +12907,7 @@ * @instance */ DocumentChange.prototype.targetIds = $util.emptyArray; - + /** * DocumentChange removedTargetIds. * @member {Array.} removedTargetIds @@ -12797,7 +12915,7 @@ * @instance */ DocumentChange.prototype.removedTargetIds = $util.emptyArray; - + /** * Creates a DocumentChange message from a plain object. Also converts values to their respective internal types. * @function fromObject @@ -12831,7 +12949,7 @@ } return message; }; - + /** * Creates a plain object from a DocumentChange message. Also converts values to other types if specified. * @function toObject @@ -12865,7 +12983,7 @@ } return object; }; - + /** * Converts this DocumentChange to JSON. * @function toJSON @@ -12876,7 +12994,7 @@ DocumentChange.prototype.toJSON = function toJSON() { return this.constructor.toObject(this, $protobuf.util.toJSONOptions); }; - + /** * Gets the default type url for DocumentChange * @function getTypeUrl @@ -12891,12 +13009,12 @@ } return typeUrlPrefix + "/google.firestore.v1.DocumentChange"; }; - + return DocumentChange; })(); - + v1.DocumentDelete = (function() { - + /** * Properties of a DocumentDelete. * @memberof google.firestore.v1 @@ -12905,7 +13023,7 @@ * @property {Array.|null} [removedTargetIds] DocumentDelete removedTargetIds * @property {google.protobuf.ITimestamp|null} [readTime] DocumentDelete readTime */ - + /** * Constructs a new DocumentDelete. * @memberof google.firestore.v1 @@ -12921,7 +13039,7 @@ if (properties[keys[i]] != null) this[keys[i]] = properties[keys[i]]; } - + /** * DocumentDelete document. * @member {string} document @@ -12929,7 +13047,7 @@ * @instance */ DocumentDelete.prototype.document = ""; - + /** * DocumentDelete removedTargetIds. * @member {Array.} removedTargetIds @@ -12937,7 +13055,7 @@ * @instance */ DocumentDelete.prototype.removedTargetIds = $util.emptyArray; - + /** * DocumentDelete readTime. * @member {google.protobuf.ITimestamp|null|undefined} readTime @@ -12945,7 +13063,7 @@ * @instance */ DocumentDelete.prototype.readTime = null; - + /** * Creates a DocumentDelete message from a plain object. Also converts values to their respective internal types. * @function fromObject @@ -12974,7 +13092,7 @@ } return message; }; - + /** * Creates a plain object from a DocumentDelete message. Also converts values to other types if specified. * @function toObject @@ -13005,7 +13123,7 @@ } return object; }; - + /** * Converts this DocumentDelete to JSON. * @function toJSON @@ -13016,7 +13134,7 @@ DocumentDelete.prototype.toJSON = function toJSON() { return this.constructor.toObject(this, $protobuf.util.toJSONOptions); }; - + /** * Gets the default type url for DocumentDelete * @function getTypeUrl @@ -13031,12 +13149,12 @@ } return typeUrlPrefix + "/google.firestore.v1.DocumentDelete"; }; - + return DocumentDelete; })(); - + v1.DocumentRemove = (function() { - + /** * Properties of a DocumentRemove. * @memberof google.firestore.v1 @@ -13045,7 +13163,7 @@ * @property {Array.|null} [removedTargetIds] DocumentRemove removedTargetIds * @property {google.protobuf.ITimestamp|null} [readTime] DocumentRemove readTime */ - + /** * Constructs a new DocumentRemove. * @memberof google.firestore.v1 @@ -13061,7 +13179,7 @@ if (properties[keys[i]] != null) this[keys[i]] = properties[keys[i]]; } - + /** * DocumentRemove document. * @member {string} document @@ -13069,7 +13187,7 @@ * @instance */ DocumentRemove.prototype.document = ""; - + /** * DocumentRemove removedTargetIds. * @member {Array.} removedTargetIds @@ -13077,7 +13195,7 @@ * @instance */ DocumentRemove.prototype.removedTargetIds = $util.emptyArray; - + /** * DocumentRemove readTime. * @member {google.protobuf.ITimestamp|null|undefined} readTime @@ -13085,7 +13203,7 @@ * @instance */ DocumentRemove.prototype.readTime = null; - + /** * Creates a DocumentRemove message from a plain object. Also converts values to their respective internal types. * @function fromObject @@ -13114,7 +13232,7 @@ } return message; }; - + /** * Creates a plain object from a DocumentRemove message. Also converts values to other types if specified. * @function toObject @@ -13145,7 +13263,7 @@ object.readTime = $root.google.protobuf.Timestamp.toObject(message.readTime, options); return object; }; - + /** * Converts this DocumentRemove to JSON. * @function toJSON @@ -13156,7 +13274,7 @@ DocumentRemove.prototype.toJSON = function toJSON() { return this.constructor.toObject(this, $protobuf.util.toJSONOptions); }; - + /** * Gets the default type url for DocumentRemove * @function getTypeUrl @@ -13171,12 +13289,12 @@ } return typeUrlPrefix + "/google.firestore.v1.DocumentRemove"; }; - + return DocumentRemove; })(); - + v1.ExistenceFilter = (function() { - + /** * Properties of an ExistenceFilter. * @memberof google.firestore.v1 @@ -13185,7 +13303,7 @@ * @property {number|null} [count] ExistenceFilter count * @property {google.firestore.v1.IBloomFilter|null} [unchangedNames] ExistenceFilter unchangedNames */ - + /** * Constructs a new ExistenceFilter. * @memberof google.firestore.v1 @@ -13200,7 +13318,7 @@ if (properties[keys[i]] != null) this[keys[i]] = properties[keys[i]]; } - + /** * ExistenceFilter targetId. * @member {number} targetId @@ -13208,7 +13326,7 @@ * @instance */ ExistenceFilter.prototype.targetId = 0; - + /** * ExistenceFilter count. * @member {number} count @@ -13216,7 +13334,7 @@ * @instance */ ExistenceFilter.prototype.count = 0; - + /** * ExistenceFilter unchangedNames. * @member {google.firestore.v1.IBloomFilter|null|undefined} unchangedNames @@ -13224,7 +13342,7 @@ * @instance */ ExistenceFilter.prototype.unchangedNames = null; - + /** * Creates an ExistenceFilter message from a plain object. Also converts values to their respective internal types. * @function fromObject @@ -13248,7 +13366,7 @@ } return message; }; - + /** * Creates a plain object from an ExistenceFilter message. Also converts values to other types if specified. * @function toObject @@ -13275,7 +13393,7 @@ object.unchangedNames = $root.google.firestore.v1.BloomFilter.toObject(message.unchangedNames, options); return object; }; - + /** * Converts this ExistenceFilter to JSON. * @function toJSON @@ -13286,7 +13404,7 @@ ExistenceFilter.prototype.toJSON = function toJSON() { return this.constructor.toObject(this, $protobuf.util.toJSONOptions); }; - + /** * Gets the default type url for ExistenceFilter * @function getTypeUrl @@ -13301,25 +13419,25 @@ } return typeUrlPrefix + "/google.firestore.v1.ExistenceFilter"; }; - + return ExistenceFilter; })(); - + return v1; })(); - + return firestore; })(); - + google.api = (function() { - + /** * Namespace api. * @memberof google * @namespace */ var api = {}; - + /** * FieldBehavior enum. * @name google.api.FieldBehavior @@ -13347,9 +13465,9 @@ values[valuesById[8] = "IDENTIFIER"] = "IDENTIFIER"; return values; })(); - + api.Http = (function() { - + /** * Properties of a Http. * @memberof google.api @@ -13357,7 +13475,7 @@ * @property {Array.|null} [rules] Http rules * @property {boolean|null} [fullyDecodeReservedExpansion] Http fullyDecodeReservedExpansion */ - + /** * Constructs a new Http. * @memberof google.api @@ -13373,7 +13491,7 @@ if (properties[keys[i]] != null) this[keys[i]] = properties[keys[i]]; } - + /** * Http rules. * @member {Array.} rules @@ -13381,7 +13499,7 @@ * @instance */ Http.prototype.rules = $util.emptyArray; - + /** * Http fullyDecodeReservedExpansion. * @member {boolean} fullyDecodeReservedExpansion @@ -13389,7 +13507,7 @@ * @instance */ Http.prototype.fullyDecodeReservedExpansion = false; - + /** * Creates a Http message from a plain object. Also converts values to their respective internal types. * @function fromObject @@ -13416,7 +13534,7 @@ message.fullyDecodeReservedExpansion = Boolean(object.fullyDecodeReservedExpansion); return message; }; - + /** * Creates a plain object from a Http message. Also converts values to other types if specified. * @function toObject @@ -13443,7 +13561,7 @@ object.fullyDecodeReservedExpansion = message.fullyDecodeReservedExpansion; return object; }; - + /** * Converts this Http to JSON. * @function toJSON @@ -13454,7 +13572,7 @@ Http.prototype.toJSON = function toJSON() { return this.constructor.toObject(this, $protobuf.util.toJSONOptions); }; - + /** * Gets the default type url for Http * @function getTypeUrl @@ -13469,12 +13587,12 @@ } return typeUrlPrefix + "/google.api.Http"; }; - + return Http; })(); - + api.HttpRule = (function() { - + /** * Properties of a HttpRule. * @memberof google.api @@ -13490,7 +13608,7 @@ * @property {string|null} [responseBody] HttpRule responseBody * @property {Array.|null} [additionalBindings] HttpRule additionalBindings */ - + /** * Constructs a new HttpRule. * @memberof google.api @@ -13506,7 +13624,7 @@ if (properties[keys[i]] != null) this[keys[i]] = properties[keys[i]]; } - + /** * HttpRule selector. * @member {string} selector @@ -13514,7 +13632,7 @@ * @instance */ HttpRule.prototype.selector = ""; - + /** * HttpRule get. * @member {string|null|undefined} get @@ -13522,7 +13640,7 @@ * @instance */ HttpRule.prototype.get = null; - + /** * HttpRule put. * @member {string|null|undefined} put @@ -13530,7 +13648,7 @@ * @instance */ HttpRule.prototype.put = null; - + /** * HttpRule post. * @member {string|null|undefined} post @@ -13538,7 +13656,7 @@ * @instance */ HttpRule.prototype.post = null; - + /** * HttpRule delete. * @member {string|null|undefined} delete @@ -13546,7 +13664,7 @@ * @instance */ HttpRule.prototype["delete"] = null; - + /** * HttpRule patch. * @member {string|null|undefined} patch @@ -13554,7 +13672,7 @@ * @instance */ HttpRule.prototype.patch = null; - + /** * HttpRule custom. * @member {google.api.ICustomHttpPattern|null|undefined} custom @@ -13562,7 +13680,7 @@ * @instance */ HttpRule.prototype.custom = null; - + /** * HttpRule body. * @member {string} body @@ -13570,7 +13688,7 @@ * @instance */ HttpRule.prototype.body = ""; - + /** * HttpRule responseBody. * @member {string} responseBody @@ -13578,7 +13696,7 @@ * @instance */ HttpRule.prototype.responseBody = ""; - + /** * HttpRule additionalBindings. * @member {Array.} additionalBindings @@ -13586,10 +13704,10 @@ * @instance */ HttpRule.prototype.additionalBindings = $util.emptyArray; - + // OneOf field names bound to virtual getters and setters var $oneOfFields; - + /** * HttpRule pattern. * @member {"get"|"put"|"post"|"delete"|"patch"|"custom"|undefined} pattern @@ -13600,7 +13718,7 @@ get: $util.oneOfGetter($oneOfFields = ["get", "put", "post", "delete", "patch", "custom"]), set: $util.oneOfSetter($oneOfFields) }); - + /** * Creates a HttpRule message from a plain object. Also converts values to their respective internal types. * @function fromObject @@ -13646,7 +13764,7 @@ } return message; }; - + /** * Creates a plain object from a HttpRule message. Also converts values to other types if specified. * @function toObject @@ -13710,7 +13828,7 @@ object.responseBody = message.responseBody; return object; }; - + /** * Converts this HttpRule to JSON. * @function toJSON @@ -13721,7 +13839,7 @@ HttpRule.prototype.toJSON = function toJSON() { return this.constructor.toObject(this, $protobuf.util.toJSONOptions); }; - + /** * Gets the default type url for HttpRule * @function getTypeUrl @@ -13736,12 +13854,12 @@ } return typeUrlPrefix + "/google.api.HttpRule"; }; - + return HttpRule; })(); - + api.CustomHttpPattern = (function() { - + /** * Properties of a CustomHttpPattern. * @memberof google.api @@ -13749,7 +13867,7 @@ * @property {string|null} [kind] CustomHttpPattern kind * @property {string|null} [path] CustomHttpPattern path */ - + /** * Constructs a new CustomHttpPattern. * @memberof google.api @@ -13764,7 +13882,7 @@ if (properties[keys[i]] != null) this[keys[i]] = properties[keys[i]]; } - + /** * CustomHttpPattern kind. * @member {string} kind @@ -13772,7 +13890,7 @@ * @instance */ CustomHttpPattern.prototype.kind = ""; - + /** * CustomHttpPattern path. * @member {string} path @@ -13780,7 +13898,7 @@ * @instance */ CustomHttpPattern.prototype.path = ""; - + /** * Creates a CustomHttpPattern message from a plain object. Also converts values to their respective internal types. * @function fromObject @@ -13799,7 +13917,7 @@ message.path = String(object.path); return message; }; - + /** * Creates a plain object from a CustomHttpPattern message. Also converts values to other types if specified. * @function toObject @@ -13823,7 +13941,7 @@ object.path = message.path; return object; }; - + /** * Converts this CustomHttpPattern to JSON. * @function toJSON @@ -13834,7 +13952,7 @@ CustomHttpPattern.prototype.toJSON = function toJSON() { return this.constructor.toObject(this, $protobuf.util.toJSONOptions); }; - + /** * Gets the default type url for CustomHttpPattern * @function getTypeUrl @@ -13849,21 +13967,20 @@ } return typeUrlPrefix + "/google.api.CustomHttpPattern"; }; - + return CustomHttpPattern; })(); - + api.CommonLanguageSettings = (function() { - + /** * Properties of a CommonLanguageSettings. * @memberof google.api * @interface ICommonLanguageSettings * @property {string|null} [referenceDocsUri] CommonLanguageSettings referenceDocsUri * @property {Array.|null} [destinations] CommonLanguageSettings destinations - * @property {google.api.ISelectiveGapicGeneration|null} [selectiveGapicGeneration] CommonLanguageSettings selectiveGapicGeneration */ - + /** * Constructs a new CommonLanguageSettings. * @memberof google.api @@ -13879,7 +13996,7 @@ if (properties[keys[i]] != null) this[keys[i]] = properties[keys[i]]; } - + /** * CommonLanguageSettings referenceDocsUri. * @member {string} referenceDocsUri @@ -13887,7 +14004,7 @@ * @instance */ CommonLanguageSettings.prototype.referenceDocsUri = ""; - + /** * CommonLanguageSettings destinations. * @member {Array.} destinations @@ -13895,15 +14012,7 @@ * @instance */ CommonLanguageSettings.prototype.destinations = $util.emptyArray; - - /** - * CommonLanguageSettings selectiveGapicGeneration. - * @member {google.api.ISelectiveGapicGeneration|null|undefined} selectiveGapicGeneration - * @memberof google.api.CommonLanguageSettings - * @instance - */ - CommonLanguageSettings.prototype.selectiveGapicGeneration = null; - + /** * Creates a CommonLanguageSettings message from a plain object. Also converts values to their respective internal types. * @function fromObject @@ -13943,14 +14052,9 @@ break; } } - if (object.selectiveGapicGeneration != null) { - if (typeof object.selectiveGapicGeneration !== "object") - throw TypeError(".google.api.CommonLanguageSettings.selectiveGapicGeneration: object expected"); - message.selectiveGapicGeneration = $root.google.api.SelectiveGapicGeneration.fromObject(object.selectiveGapicGeneration); - } return message; }; - + /** * Creates a plain object from a CommonLanguageSettings message. Also converts values to other types if specified. * @function toObject @@ -13966,10 +14070,8 @@ var object = {}; if (options.arrays || options.defaults) object.destinations = []; - if (options.defaults) { + if (options.defaults) object.referenceDocsUri = ""; - object.selectiveGapicGeneration = null; - } if (message.referenceDocsUri != null && message.hasOwnProperty("referenceDocsUri")) object.referenceDocsUri = message.referenceDocsUri; if (message.destinations && message.destinations.length) { @@ -13977,11 +14079,9 @@ for (var j = 0; j < message.destinations.length; ++j) object.destinations[j] = options.enums === String ? $root.google.api.ClientLibraryDestination[message.destinations[j]] === undefined ? message.destinations[j] : $root.google.api.ClientLibraryDestination[message.destinations[j]] : message.destinations[j]; } - if (message.selectiveGapicGeneration != null && message.hasOwnProperty("selectiveGapicGeneration")) - object.selectiveGapicGeneration = $root.google.api.SelectiveGapicGeneration.toObject(message.selectiveGapicGeneration, options); return object; }; - + /** * Converts this CommonLanguageSettings to JSON. * @function toJSON @@ -13992,7 +14092,7 @@ CommonLanguageSettings.prototype.toJSON = function toJSON() { return this.constructor.toObject(this, $protobuf.util.toJSONOptions); }; - + /** * Gets the default type url for CommonLanguageSettings * @function getTypeUrl @@ -14007,12 +14107,12 @@ } return typeUrlPrefix + "/google.api.CommonLanguageSettings"; }; - + return CommonLanguageSettings; })(); - + api.ClientLibrarySettings = (function() { - + /** * Properties of a ClientLibrarySettings. * @memberof google.api @@ -14029,7 +14129,7 @@ * @property {google.api.IRubySettings|null} [rubySettings] ClientLibrarySettings rubySettings * @property {google.api.IGoSettings|null} [goSettings] ClientLibrarySettings goSettings */ - + /** * Constructs a new ClientLibrarySettings. * @memberof google.api @@ -14044,7 +14144,7 @@ if (properties[keys[i]] != null) this[keys[i]] = properties[keys[i]]; } - + /** * ClientLibrarySettings version. * @member {string} version @@ -14052,7 +14152,7 @@ * @instance */ ClientLibrarySettings.prototype.version = ""; - + /** * ClientLibrarySettings launchStage. * @member {google.api.LaunchStage} launchStage @@ -14060,7 +14160,7 @@ * @instance */ ClientLibrarySettings.prototype.launchStage = 0; - + /** * ClientLibrarySettings restNumericEnums. * @member {boolean} restNumericEnums @@ -14068,7 +14168,7 @@ * @instance */ ClientLibrarySettings.prototype.restNumericEnums = false; - + /** * ClientLibrarySettings javaSettings. * @member {google.api.IJavaSettings|null|undefined} javaSettings @@ -14076,7 +14176,7 @@ * @instance */ ClientLibrarySettings.prototype.javaSettings = null; - + /** * ClientLibrarySettings cppSettings. * @member {google.api.ICppSettings|null|undefined} cppSettings @@ -14084,7 +14184,7 @@ * @instance */ ClientLibrarySettings.prototype.cppSettings = null; - + /** * ClientLibrarySettings phpSettings. * @member {google.api.IPhpSettings|null|undefined} phpSettings @@ -14092,7 +14192,7 @@ * @instance */ ClientLibrarySettings.prototype.phpSettings = null; - + /** * ClientLibrarySettings pythonSettings. * @member {google.api.IPythonSettings|null|undefined} pythonSettings @@ -14100,7 +14200,7 @@ * @instance */ ClientLibrarySettings.prototype.pythonSettings = null; - + /** * ClientLibrarySettings nodeSettings. * @member {google.api.INodeSettings|null|undefined} nodeSettings @@ -14108,7 +14208,7 @@ * @instance */ ClientLibrarySettings.prototype.nodeSettings = null; - + /** * ClientLibrarySettings dotnetSettings. * @member {google.api.IDotnetSettings|null|undefined} dotnetSettings @@ -14116,7 +14216,7 @@ * @instance */ ClientLibrarySettings.prototype.dotnetSettings = null; - + /** * ClientLibrarySettings rubySettings. * @member {google.api.IRubySettings|null|undefined} rubySettings @@ -14124,7 +14224,7 @@ * @instance */ ClientLibrarySettings.prototype.rubySettings = null; - + /** * ClientLibrarySettings goSettings. * @member {google.api.IGoSettings|null|undefined} goSettings @@ -14132,7 +14232,7 @@ * @instance */ ClientLibrarySettings.prototype.goSettings = null; - + /** * Creates a ClientLibrarySettings message from a plain object. Also converts values to their respective internal types. * @function fromObject @@ -14231,7 +14331,7 @@ } return message; }; - + /** * Creates a plain object from a ClientLibrarySettings message. Also converts values to other types if specified. * @function toObject @@ -14282,7 +14382,7 @@ object.goSettings = $root.google.api.GoSettings.toObject(message.goSettings, options); return object; }; - + /** * Converts this ClientLibrarySettings to JSON. * @function toJSON @@ -14293,7 +14393,7 @@ ClientLibrarySettings.prototype.toJSON = function toJSON() { return this.constructor.toObject(this, $protobuf.util.toJSONOptions); }; - + /** * Gets the default type url for ClientLibrarySettings * @function getTypeUrl @@ -14308,12 +14408,12 @@ } return typeUrlPrefix + "/google.api.ClientLibrarySettings"; }; - + return ClientLibrarySettings; })(); - + api.Publishing = (function() { - + /** * Properties of a Publishing. * @memberof google.api @@ -14330,7 +14430,7 @@ * @property {string|null} [protoReferenceDocumentationUri] Publishing protoReferenceDocumentationUri * @property {string|null} [restReferenceDocumentationUri] Publishing restReferenceDocumentationUri */ - + /** * Constructs a new Publishing. * @memberof google.api @@ -14348,7 +14448,7 @@ if (properties[keys[i]] != null) this[keys[i]] = properties[keys[i]]; } - + /** * Publishing methodSettings. * @member {Array.} methodSettings @@ -14356,7 +14456,7 @@ * @instance */ Publishing.prototype.methodSettings = $util.emptyArray; - + /** * Publishing newIssueUri. * @member {string} newIssueUri @@ -14364,7 +14464,7 @@ * @instance */ Publishing.prototype.newIssueUri = ""; - + /** * Publishing documentationUri. * @member {string} documentationUri @@ -14372,7 +14472,7 @@ * @instance */ Publishing.prototype.documentationUri = ""; - + /** * Publishing apiShortName. * @member {string} apiShortName @@ -14380,7 +14480,7 @@ * @instance */ Publishing.prototype.apiShortName = ""; - + /** * Publishing githubLabel. * @member {string} githubLabel @@ -14388,7 +14488,7 @@ * @instance */ Publishing.prototype.githubLabel = ""; - + /** * Publishing codeownerGithubTeams. * @member {Array.} codeownerGithubTeams @@ -14396,7 +14496,7 @@ * @instance */ Publishing.prototype.codeownerGithubTeams = $util.emptyArray; - + /** * Publishing docTagPrefix. * @member {string} docTagPrefix @@ -14404,7 +14504,7 @@ * @instance */ Publishing.prototype.docTagPrefix = ""; - + /** * Publishing organization. * @member {google.api.ClientLibraryOrganization} organization @@ -14412,7 +14512,7 @@ * @instance */ Publishing.prototype.organization = 0; - + /** * Publishing librarySettings. * @member {Array.} librarySettings @@ -14420,7 +14520,7 @@ * @instance */ Publishing.prototype.librarySettings = $util.emptyArray; - + /** * Publishing protoReferenceDocumentationUri. * @member {string} protoReferenceDocumentationUri @@ -14428,7 +14528,7 @@ * @instance */ Publishing.prototype.protoReferenceDocumentationUri = ""; - + /** * Publishing restReferenceDocumentationUri. * @member {string} restReferenceDocumentationUri @@ -14436,7 +14536,7 @@ * @instance */ Publishing.prototype.restReferenceDocumentationUri = ""; - + /** * Creates a Publishing message from a plain object. Also converts values to their respective internal types. * @function fromObject @@ -14532,7 +14632,7 @@ message.restReferenceDocumentationUri = String(object.restReferenceDocumentationUri); return message; }; - + /** * Creates a plain object from a Publishing message. Also converts values to other types if specified. * @function toObject @@ -14594,7 +14694,7 @@ object.restReferenceDocumentationUri = message.restReferenceDocumentationUri; return object; }; - + /** * Converts this Publishing to JSON. * @function toJSON @@ -14605,7 +14705,7 @@ Publishing.prototype.toJSON = function toJSON() { return this.constructor.toObject(this, $protobuf.util.toJSONOptions); }; - + /** * Gets the default type url for Publishing * @function getTypeUrl @@ -14620,12 +14720,12 @@ } return typeUrlPrefix + "/google.api.Publishing"; }; - + return Publishing; })(); - + api.JavaSettings = (function() { - + /** * Properties of a JavaSettings. * @memberof google.api @@ -14634,7 +14734,7 @@ * @property {Object.|null} [serviceClassNames] JavaSettings serviceClassNames * @property {google.api.ICommonLanguageSettings|null} [common] JavaSettings common */ - + /** * Constructs a new JavaSettings. * @memberof google.api @@ -14650,7 +14750,7 @@ if (properties[keys[i]] != null) this[keys[i]] = properties[keys[i]]; } - + /** * JavaSettings libraryPackage. * @member {string} libraryPackage @@ -14658,7 +14758,7 @@ * @instance */ JavaSettings.prototype.libraryPackage = ""; - + /** * JavaSettings serviceClassNames. * @member {Object.} serviceClassNames @@ -14666,7 +14766,7 @@ * @instance */ JavaSettings.prototype.serviceClassNames = $util.emptyObject; - + /** * JavaSettings common. * @member {google.api.ICommonLanguageSettings|null|undefined} common @@ -14674,7 +14774,7 @@ * @instance */ JavaSettings.prototype.common = null; - + /** * Creates a JavaSettings message from a plain object. Also converts values to their respective internal types. * @function fromObject @@ -14703,7 +14803,7 @@ } return message; }; - + /** * Creates a plain object from a JavaSettings message. Also converts values to other types if specified. * @function toObject @@ -14735,7 +14835,7 @@ object.common = $root.google.api.CommonLanguageSettings.toObject(message.common, options); return object; }; - + /** * Converts this JavaSettings to JSON. * @function toJSON @@ -14746,7 +14846,7 @@ JavaSettings.prototype.toJSON = function toJSON() { return this.constructor.toObject(this, $protobuf.util.toJSONOptions); }; - + /** * Gets the default type url for JavaSettings * @function getTypeUrl @@ -14761,19 +14861,19 @@ } return typeUrlPrefix + "/google.api.JavaSettings"; }; - + return JavaSettings; })(); - + api.CppSettings = (function() { - + /** * Properties of a CppSettings. * @memberof google.api * @interface ICppSettings * @property {google.api.ICommonLanguageSettings|null} [common] CppSettings common */ - + /** * Constructs a new CppSettings. * @memberof google.api @@ -14788,7 +14888,7 @@ if (properties[keys[i]] != null) this[keys[i]] = properties[keys[i]]; } - + /** * CppSettings common. * @member {google.api.ICommonLanguageSettings|null|undefined} common @@ -14796,7 +14896,7 @@ * @instance */ CppSettings.prototype.common = null; - + /** * Creates a CppSettings message from a plain object. Also converts values to their respective internal types. * @function fromObject @@ -14816,7 +14916,7 @@ } return message; }; - + /** * Creates a plain object from a CppSettings message. Also converts values to other types if specified. * @function toObject @@ -14836,7 +14936,7 @@ object.common = $root.google.api.CommonLanguageSettings.toObject(message.common, options); return object; }; - + /** * Converts this CppSettings to JSON. * @function toJSON @@ -14847,7 +14947,7 @@ CppSettings.prototype.toJSON = function toJSON() { return this.constructor.toObject(this, $protobuf.util.toJSONOptions); }; - + /** * Gets the default type url for CppSettings * @function getTypeUrl @@ -14862,19 +14962,19 @@ } return typeUrlPrefix + "/google.api.CppSettings"; }; - + return CppSettings; })(); - + api.PhpSettings = (function() { - + /** * Properties of a PhpSettings. * @memberof google.api * @interface IPhpSettings * @property {google.api.ICommonLanguageSettings|null} [common] PhpSettings common */ - + /** * Constructs a new PhpSettings. * @memberof google.api @@ -14889,7 +14989,7 @@ if (properties[keys[i]] != null) this[keys[i]] = properties[keys[i]]; } - + /** * PhpSettings common. * @member {google.api.ICommonLanguageSettings|null|undefined} common @@ -14897,7 +14997,7 @@ * @instance */ PhpSettings.prototype.common = null; - + /** * Creates a PhpSettings message from a plain object. Also converts values to their respective internal types. * @function fromObject @@ -14917,7 +15017,7 @@ } return message; }; - + /** * Creates a plain object from a PhpSettings message. Also converts values to other types if specified. * @function toObject @@ -14937,7 +15037,7 @@ object.common = $root.google.api.CommonLanguageSettings.toObject(message.common, options); return object; }; - + /** * Converts this PhpSettings to JSON. * @function toJSON @@ -14948,7 +15048,7 @@ PhpSettings.prototype.toJSON = function toJSON() { return this.constructor.toObject(this, $protobuf.util.toJSONOptions); }; - + /** * Gets the default type url for PhpSettings * @function getTypeUrl @@ -14963,20 +15063,19 @@ } return typeUrlPrefix + "/google.api.PhpSettings"; }; - + return PhpSettings; })(); - + api.PythonSettings = (function() { - + /** * Properties of a PythonSettings. * @memberof google.api * @interface IPythonSettings * @property {google.api.ICommonLanguageSettings|null} [common] PythonSettings common - * @property {google.api.PythonSettings.IExperimentalFeatures|null} [experimentalFeatures] PythonSettings experimentalFeatures */ - + /** * Constructs a new PythonSettings. * @memberof google.api @@ -14991,7 +15090,7 @@ if (properties[keys[i]] != null) this[keys[i]] = properties[keys[i]]; } - + /** * PythonSettings common. * @member {google.api.ICommonLanguageSettings|null|undefined} common @@ -14999,15 +15098,7 @@ * @instance */ PythonSettings.prototype.common = null; - - /** - * PythonSettings experimentalFeatures. - * @member {google.api.PythonSettings.IExperimentalFeatures|null|undefined} experimentalFeatures - * @memberof google.api.PythonSettings - * @instance - */ - PythonSettings.prototype.experimentalFeatures = null; - + /** * Creates a PythonSettings message from a plain object. Also converts values to their respective internal types. * @function fromObject @@ -15025,14 +15116,9 @@ throw TypeError(".google.api.PythonSettings.common: object expected"); message.common = $root.google.api.CommonLanguageSettings.fromObject(object.common); } - if (object.experimentalFeatures != null) { - if (typeof object.experimentalFeatures !== "object") - throw TypeError(".google.api.PythonSettings.experimentalFeatures: object expected"); - message.experimentalFeatures = $root.google.api.PythonSettings.ExperimentalFeatures.fromObject(object.experimentalFeatures); - } return message; }; - + /** * Creates a plain object from a PythonSettings message. Also converts values to other types if specified. * @function toObject @@ -15046,17 +15132,13 @@ if (!options) options = {}; var object = {}; - if (options.defaults) { + if (options.defaults) object.common = null; - object.experimentalFeatures = null; - } if (message.common != null && message.hasOwnProperty("common")) object.common = $root.google.api.CommonLanguageSettings.toObject(message.common, options); - if (message.experimentalFeatures != null && message.hasOwnProperty("experimentalFeatures")) - object.experimentalFeatures = $root.google.api.PythonSettings.ExperimentalFeatures.toObject(message.experimentalFeatures, options); return object; }; - + /** * Converts this PythonSettings to JSON. * @function toJSON @@ -15067,7 +15149,7 @@ PythonSettings.prototype.toJSON = function toJSON() { return this.constructor.toObject(this, $protobuf.util.toJSONOptions); }; - + /** * Gets the default type url for PythonSettings * @function getTypeUrl @@ -15082,132 +15164,19 @@ } return typeUrlPrefix + "/google.api.PythonSettings"; }; - - PythonSettings.ExperimentalFeatures = (function() { - - /** - * Properties of an ExperimentalFeatures. - * @memberof google.api.PythonSettings - * @interface IExperimentalFeatures - * @property {boolean|null} [restAsyncIoEnabled] ExperimentalFeatures restAsyncIoEnabled - * @property {boolean|null} [protobufPythonicTypesEnabled] ExperimentalFeatures protobufPythonicTypesEnabled - */ - - /** - * Constructs a new ExperimentalFeatures. - * @memberof google.api.PythonSettings - * @classdesc Represents an ExperimentalFeatures. - * @implements IExperimentalFeatures - * @constructor - * @param {google.api.PythonSettings.IExperimentalFeatures=} [properties] Properties to set - */ - function ExperimentalFeatures(properties) { - if (properties) - for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) - if (properties[keys[i]] != null) - this[keys[i]] = properties[keys[i]]; - } - - /** - * ExperimentalFeatures restAsyncIoEnabled. - * @member {boolean} restAsyncIoEnabled - * @memberof google.api.PythonSettings.ExperimentalFeatures - * @instance - */ - ExperimentalFeatures.prototype.restAsyncIoEnabled = false; - - /** - * ExperimentalFeatures protobufPythonicTypesEnabled. - * @member {boolean} protobufPythonicTypesEnabled - * @memberof google.api.PythonSettings.ExperimentalFeatures - * @instance - */ - ExperimentalFeatures.prototype.protobufPythonicTypesEnabled = false; - - /** - * Creates an ExperimentalFeatures message from a plain object. Also converts values to their respective internal types. - * @function fromObject - * @memberof google.api.PythonSettings.ExperimentalFeatures - * @static - * @param {Object.} object Plain object - * @returns {google.api.PythonSettings.ExperimentalFeatures} ExperimentalFeatures - */ - ExperimentalFeatures.fromObject = function fromObject(object) { - if (object instanceof $root.google.api.PythonSettings.ExperimentalFeatures) - return object; - var message = new $root.google.api.PythonSettings.ExperimentalFeatures(); - if (object.restAsyncIoEnabled != null) - message.restAsyncIoEnabled = Boolean(object.restAsyncIoEnabled); - if (object.protobufPythonicTypesEnabled != null) - message.protobufPythonicTypesEnabled = Boolean(object.protobufPythonicTypesEnabled); - return message; - }; - - /** - * Creates a plain object from an ExperimentalFeatures message. Also converts values to other types if specified. - * @function toObject - * @memberof google.api.PythonSettings.ExperimentalFeatures - * @static - * @param {google.api.PythonSettings.ExperimentalFeatures} message ExperimentalFeatures - * @param {$protobuf.IConversionOptions} [options] Conversion options - * @returns {Object.} Plain object - */ - ExperimentalFeatures.toObject = function toObject(message, options) { - if (!options) - options = {}; - var object = {}; - if (options.defaults) { - object.restAsyncIoEnabled = false; - object.protobufPythonicTypesEnabled = false; - } - if (message.restAsyncIoEnabled != null && message.hasOwnProperty("restAsyncIoEnabled")) - object.restAsyncIoEnabled = message.restAsyncIoEnabled; - if (message.protobufPythonicTypesEnabled != null && message.hasOwnProperty("protobufPythonicTypesEnabled")) - object.protobufPythonicTypesEnabled = message.protobufPythonicTypesEnabled; - return object; - }; - - /** - * Converts this ExperimentalFeatures to JSON. - * @function toJSON - * @memberof google.api.PythonSettings.ExperimentalFeatures - * @instance - * @returns {Object.} JSON object - */ - ExperimentalFeatures.prototype.toJSON = function toJSON() { - return this.constructor.toObject(this, $protobuf.util.toJSONOptions); - }; - - /** - * Gets the default type url for ExperimentalFeatures - * @function getTypeUrl - * @memberof google.api.PythonSettings.ExperimentalFeatures - * @static - * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") - * @returns {string} The default type url - */ - ExperimentalFeatures.getTypeUrl = function getTypeUrl(typeUrlPrefix) { - if (typeUrlPrefix === undefined) { - typeUrlPrefix = "type.googleapis.com"; - } - return typeUrlPrefix + "/google.api.PythonSettings.ExperimentalFeatures"; - }; - - return ExperimentalFeatures; - })(); - + return PythonSettings; })(); - + api.NodeSettings = (function() { - + /** * Properties of a NodeSettings. * @memberof google.api * @interface INodeSettings * @property {google.api.ICommonLanguageSettings|null} [common] NodeSettings common */ - + /** * Constructs a new NodeSettings. * @memberof google.api @@ -15222,7 +15191,7 @@ if (properties[keys[i]] != null) this[keys[i]] = properties[keys[i]]; } - + /** * NodeSettings common. * @member {google.api.ICommonLanguageSettings|null|undefined} common @@ -15230,7 +15199,7 @@ * @instance */ NodeSettings.prototype.common = null; - + /** * Creates a NodeSettings message from a plain object. Also converts values to their respective internal types. * @function fromObject @@ -15250,7 +15219,7 @@ } return message; }; - + /** * Creates a plain object from a NodeSettings message. Also converts values to other types if specified. * @function toObject @@ -15270,7 +15239,7 @@ object.common = $root.google.api.CommonLanguageSettings.toObject(message.common, options); return object; }; - + /** * Converts this NodeSettings to JSON. * @function toJSON @@ -15281,7 +15250,7 @@ NodeSettings.prototype.toJSON = function toJSON() { return this.constructor.toObject(this, $protobuf.util.toJSONOptions); }; - + /** * Gets the default type url for NodeSettings * @function getTypeUrl @@ -15296,12 +15265,12 @@ } return typeUrlPrefix + "/google.api.NodeSettings"; }; - + return NodeSettings; })(); - + api.DotnetSettings = (function() { - + /** * Properties of a DotnetSettings. * @memberof google.api @@ -15313,7 +15282,7 @@ * @property {Array.|null} [forcedNamespaceAliases] DotnetSettings forcedNamespaceAliases * @property {Array.|null} [handwrittenSignatures] DotnetSettings handwrittenSignatures */ - + /** * Constructs a new DotnetSettings. * @memberof google.api @@ -15333,7 +15302,7 @@ if (properties[keys[i]] != null) this[keys[i]] = properties[keys[i]]; } - + /** * DotnetSettings common. * @member {google.api.ICommonLanguageSettings|null|undefined} common @@ -15341,7 +15310,7 @@ * @instance */ DotnetSettings.prototype.common = null; - + /** * DotnetSettings renamedServices. * @member {Object.} renamedServices @@ -15349,7 +15318,7 @@ * @instance */ DotnetSettings.prototype.renamedServices = $util.emptyObject; - + /** * DotnetSettings renamedResources. * @member {Object.} renamedResources @@ -15357,7 +15326,7 @@ * @instance */ DotnetSettings.prototype.renamedResources = $util.emptyObject; - + /** * DotnetSettings ignoredResources. * @member {Array.} ignoredResources @@ -15365,7 +15334,7 @@ * @instance */ DotnetSettings.prototype.ignoredResources = $util.emptyArray; - + /** * DotnetSettings forcedNamespaceAliases. * @member {Array.} forcedNamespaceAliases @@ -15373,7 +15342,7 @@ * @instance */ DotnetSettings.prototype.forcedNamespaceAliases = $util.emptyArray; - + /** * DotnetSettings handwrittenSignatures. * @member {Array.} handwrittenSignatures @@ -15381,7 +15350,7 @@ * @instance */ DotnetSettings.prototype.handwrittenSignatures = $util.emptyArray; - + /** * Creates a DotnetSettings message from a plain object. Also converts values to their respective internal types. * @function fromObject @@ -15436,7 +15405,7 @@ } return message; }; - + /** * Creates a plain object from a DotnetSettings message. Also converts values to other types if specified. * @function toObject @@ -15491,7 +15460,7 @@ } return object; }; - + /** * Converts this DotnetSettings to JSON. * @function toJSON @@ -15502,7 +15471,7 @@ DotnetSettings.prototype.toJSON = function toJSON() { return this.constructor.toObject(this, $protobuf.util.toJSONOptions); }; - + /** * Gets the default type url for DotnetSettings * @function getTypeUrl @@ -15517,19 +15486,19 @@ } return typeUrlPrefix + "/google.api.DotnetSettings"; }; - + return DotnetSettings; })(); - + api.RubySettings = (function() { - + /** * Properties of a RubySettings. * @memberof google.api * @interface IRubySettings * @property {google.api.ICommonLanguageSettings|null} [common] RubySettings common */ - + /** * Constructs a new RubySettings. * @memberof google.api @@ -15544,7 +15513,7 @@ if (properties[keys[i]] != null) this[keys[i]] = properties[keys[i]]; } - + /** * RubySettings common. * @member {google.api.ICommonLanguageSettings|null|undefined} common @@ -15552,7 +15521,7 @@ * @instance */ RubySettings.prototype.common = null; - + /** * Creates a RubySettings message from a plain object. Also converts values to their respective internal types. * @function fromObject @@ -15572,7 +15541,7 @@ } return message; }; - + /** * Creates a plain object from a RubySettings message. Also converts values to other types if specified. * @function toObject @@ -15592,7 +15561,7 @@ object.common = $root.google.api.CommonLanguageSettings.toObject(message.common, options); return object; }; - + /** * Converts this RubySettings to JSON. * @function toJSON @@ -15603,7 +15572,7 @@ RubySettings.prototype.toJSON = function toJSON() { return this.constructor.toObject(this, $protobuf.util.toJSONOptions); }; - + /** * Gets the default type url for RubySettings * @function getTypeUrl @@ -15618,20 +15587,19 @@ } return typeUrlPrefix + "/google.api.RubySettings"; }; - + return RubySettings; })(); - + api.GoSettings = (function() { - + /** * Properties of a GoSettings. * @memberof google.api * @interface IGoSettings * @property {google.api.ICommonLanguageSettings|null} [common] GoSettings common - * @property {Object.|null} [renamedServices] GoSettings renamedServices */ - + /** * Constructs a new GoSettings. * @memberof google.api @@ -15641,13 +15609,12 @@ * @param {google.api.IGoSettings=} [properties] Properties to set */ function GoSettings(properties) { - this.renamedServices = {}; if (properties) for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) if (properties[keys[i]] != null) this[keys[i]] = properties[keys[i]]; } - + /** * GoSettings common. * @member {google.api.ICommonLanguageSettings|null|undefined} common @@ -15655,15 +15622,7 @@ * @instance */ GoSettings.prototype.common = null; - - /** - * GoSettings renamedServices. - * @member {Object.} renamedServices - * @memberof google.api.GoSettings - * @instance - */ - GoSettings.prototype.renamedServices = $util.emptyObject; - + /** * Creates a GoSettings message from a plain object. Also converts values to their respective internal types. * @function fromObject @@ -15681,16 +15640,9 @@ throw TypeError(".google.api.GoSettings.common: object expected"); message.common = $root.google.api.CommonLanguageSettings.fromObject(object.common); } - if (object.renamedServices) { - if (typeof object.renamedServices !== "object") - throw TypeError(".google.api.GoSettings.renamedServices: object expected"); - message.renamedServices = {}; - for (var keys = Object.keys(object.renamedServices), i = 0; i < keys.length; ++i) - message.renamedServices[keys[i]] = String(object.renamedServices[keys[i]]); - } return message; }; - + /** * Creates a plain object from a GoSettings message. Also converts values to other types if specified. * @function toObject @@ -15704,21 +15656,13 @@ if (!options) options = {}; var object = {}; - if (options.objects || options.defaults) - object.renamedServices = {}; if (options.defaults) object.common = null; if (message.common != null && message.hasOwnProperty("common")) object.common = $root.google.api.CommonLanguageSettings.toObject(message.common, options); - var keys2; - if (message.renamedServices && (keys2 = Object.keys(message.renamedServices)).length) { - object.renamedServices = {}; - for (var j = 0; j < keys2.length; ++j) - object.renamedServices[keys2[j]] = message.renamedServices[keys2[j]]; - } return object; }; - + /** * Converts this GoSettings to JSON. * @function toJSON @@ -15729,7 +15673,7 @@ GoSettings.prototype.toJSON = function toJSON() { return this.constructor.toObject(this, $protobuf.util.toJSONOptions); }; - + /** * Gets the default type url for GoSettings * @function getTypeUrl @@ -15744,12 +15688,12 @@ } return typeUrlPrefix + "/google.api.GoSettings"; }; - + return GoSettings; })(); - + api.MethodSettings = (function() { - + /** * Properties of a MethodSettings. * @memberof google.api @@ -15758,7 +15702,7 @@ * @property {google.api.MethodSettings.ILongRunning|null} [longRunning] MethodSettings longRunning * @property {Array.|null} [autoPopulatedFields] MethodSettings autoPopulatedFields */ - + /** * Constructs a new MethodSettings. * @memberof google.api @@ -15774,7 +15718,7 @@ if (properties[keys[i]] != null) this[keys[i]] = properties[keys[i]]; } - + /** * MethodSettings selector. * @member {string} selector @@ -15782,7 +15726,7 @@ * @instance */ MethodSettings.prototype.selector = ""; - + /** * MethodSettings longRunning. * @member {google.api.MethodSettings.ILongRunning|null|undefined} longRunning @@ -15790,7 +15734,7 @@ * @instance */ MethodSettings.prototype.longRunning = null; - + /** * MethodSettings autoPopulatedFields. * @member {Array.} autoPopulatedFields @@ -15798,7 +15742,7 @@ * @instance */ MethodSettings.prototype.autoPopulatedFields = $util.emptyArray; - + /** * Creates a MethodSettings message from a plain object. Also converts values to their respective internal types. * @function fromObject @@ -15827,7 +15771,7 @@ } return message; }; - + /** * Creates a plain object from a MethodSettings message. Also converts values to other types if specified. * @function toObject @@ -15858,7 +15802,7 @@ } return object; }; - + /** * Converts this MethodSettings to JSON. * @function toJSON @@ -15869,7 +15813,7 @@ MethodSettings.prototype.toJSON = function toJSON() { return this.constructor.toObject(this, $protobuf.util.toJSONOptions); }; - + /** * Gets the default type url for MethodSettings * @function getTypeUrl @@ -15884,9 +15828,9 @@ } return typeUrlPrefix + "/google.api.MethodSettings"; }; - + MethodSettings.LongRunning = (function() { - + /** * Properties of a LongRunning. * @memberof google.api.MethodSettings @@ -15896,7 +15840,7 @@ * @property {google.protobuf.IDuration|null} [maxPollDelay] LongRunning maxPollDelay * @property {google.protobuf.IDuration|null} [totalPollTimeout] LongRunning totalPollTimeout */ - + /** * Constructs a new LongRunning. * @memberof google.api.MethodSettings @@ -15911,7 +15855,7 @@ if (properties[keys[i]] != null) this[keys[i]] = properties[keys[i]]; } - + /** * LongRunning initialPollDelay. * @member {google.protobuf.IDuration|null|undefined} initialPollDelay @@ -15919,7 +15863,7 @@ * @instance */ LongRunning.prototype.initialPollDelay = null; - + /** * LongRunning pollDelayMultiplier. * @member {number} pollDelayMultiplier @@ -15927,7 +15871,7 @@ * @instance */ LongRunning.prototype.pollDelayMultiplier = 0; - + /** * LongRunning maxPollDelay. * @member {google.protobuf.IDuration|null|undefined} maxPollDelay @@ -15935,7 +15879,7 @@ * @instance */ LongRunning.prototype.maxPollDelay = null; - + /** * LongRunning totalPollTimeout. * @member {google.protobuf.IDuration|null|undefined} totalPollTimeout @@ -15943,7 +15887,7 @@ * @instance */ LongRunning.prototype.totalPollTimeout = null; - + /** * Creates a LongRunning message from a plain object. Also converts values to their respective internal types. * @function fromObject @@ -15975,7 +15919,7 @@ } return message; }; - + /** * Creates a plain object from a LongRunning message. Also converts values to other types if specified. * @function toObject @@ -16005,7 +15949,7 @@ object.totalPollTimeout = $root.google.protobuf.Duration.toObject(message.totalPollTimeout, options); return object; }; - + /** * Converts this LongRunning to JSON. * @function toJSON @@ -16016,7 +15960,7 @@ LongRunning.prototype.toJSON = function toJSON() { return this.constructor.toObject(this, $protobuf.util.toJSONOptions); }; - + /** * Gets the default type url for LongRunning * @function getTypeUrl @@ -16031,13 +15975,13 @@ } return typeUrlPrefix + "/google.api.MethodSettings.LongRunning"; }; - + return LongRunning; })(); - + return MethodSettings; })(); - + /** * ClientLibraryOrganization enum. * @name google.api.ClientLibraryOrganization @@ -16063,7 +16007,7 @@ values[valuesById[7] = "GENERATIVE_AI"] = "GENERATIVE_AI"; return values; })(); - + /** * ClientLibraryDestination enum. * @name google.api.ClientLibraryDestination @@ -16079,157 +16023,258 @@ values[valuesById[20] = "PACKAGE_MANAGER"] = "PACKAGE_MANAGER"; return values; })(); - - api.SelectiveGapicGeneration = (function() { - + + /** + * LaunchStage enum. + * @name google.api.LaunchStage + * @enum {string} + * @property {string} LAUNCH_STAGE_UNSPECIFIED=LAUNCH_STAGE_UNSPECIFIED LAUNCH_STAGE_UNSPECIFIED value + * @property {string} UNIMPLEMENTED=UNIMPLEMENTED UNIMPLEMENTED value + * @property {string} PRELAUNCH=PRELAUNCH PRELAUNCH value + * @property {string} EARLY_ACCESS=EARLY_ACCESS EARLY_ACCESS value + * @property {string} ALPHA=ALPHA ALPHA value + * @property {string} BETA=BETA BETA value + * @property {string} GA=GA GA value + * @property {string} DEPRECATED=DEPRECATED DEPRECATED value + */ + api.LaunchStage = (function() { + var valuesById = {}, values = Object.create(valuesById); + values[valuesById[0] = "LAUNCH_STAGE_UNSPECIFIED"] = "LAUNCH_STAGE_UNSPECIFIED"; + values[valuesById[6] = "UNIMPLEMENTED"] = "UNIMPLEMENTED"; + values[valuesById[7] = "PRELAUNCH"] = "PRELAUNCH"; + values[valuesById[1] = "EARLY_ACCESS"] = "EARLY_ACCESS"; + values[valuesById[2] = "ALPHA"] = "ALPHA"; + values[valuesById[3] = "BETA"] = "BETA"; + values[valuesById[4] = "GA"] = "GA"; + values[valuesById[5] = "DEPRECATED"] = "DEPRECATED"; + return values; + })(); + + api.RoutingRule = (function() { + /** - * Properties of a SelectiveGapicGeneration. + * Properties of a RoutingRule. * @memberof google.api - * @interface ISelectiveGapicGeneration - * @property {Array.|null} [methods] SelectiveGapicGeneration methods - * @property {boolean|null} [generateOmittedAsInternal] SelectiveGapicGeneration generateOmittedAsInternal + * @interface IRoutingRule + * @property {Array.|null} [routingParameters] RoutingRule routingParameters */ - + /** - * Constructs a new SelectiveGapicGeneration. + * Constructs a new RoutingRule. * @memberof google.api - * @classdesc Represents a SelectiveGapicGeneration. - * @implements ISelectiveGapicGeneration + * @classdesc Represents a RoutingRule. + * @implements IRoutingRule * @constructor - * @param {google.api.ISelectiveGapicGeneration=} [properties] Properties to set + * @param {google.api.IRoutingRule=} [properties] Properties to set */ - function SelectiveGapicGeneration(properties) { - this.methods = []; + function RoutingRule(properties) { + this.routingParameters = []; if (properties) for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) if (properties[keys[i]] != null) this[keys[i]] = properties[keys[i]]; } - + /** - * SelectiveGapicGeneration methods. - * @member {Array.} methods - * @memberof google.api.SelectiveGapicGeneration + * RoutingRule routingParameters. + * @member {Array.} routingParameters + * @memberof google.api.RoutingRule * @instance */ - SelectiveGapicGeneration.prototype.methods = $util.emptyArray; - + RoutingRule.prototype.routingParameters = $util.emptyArray; + + /** + * Creates a RoutingRule message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.api.RoutingRule + * @static + * @param {Object.} object Plain object + * @returns {google.api.RoutingRule} RoutingRule + */ + RoutingRule.fromObject = function fromObject(object) { + if (object instanceof $root.google.api.RoutingRule) + return object; + var message = new $root.google.api.RoutingRule(); + if (object.routingParameters) { + if (!Array.isArray(object.routingParameters)) + throw TypeError(".google.api.RoutingRule.routingParameters: array expected"); + message.routingParameters = []; + for (var i = 0; i < object.routingParameters.length; ++i) { + if (typeof object.routingParameters[i] !== "object") + throw TypeError(".google.api.RoutingRule.routingParameters: object expected"); + message.routingParameters[i] = $root.google.api.RoutingParameter.fromObject(object.routingParameters[i]); + } + } + return message; + }; + + /** + * Creates a plain object from a RoutingRule message. Also converts values to other types if specified. + * @function toObject + * @memberof google.api.RoutingRule + * @static + * @param {google.api.RoutingRule} message RoutingRule + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + RoutingRule.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.arrays || options.defaults) + object.routingParameters = []; + if (message.routingParameters && message.routingParameters.length) { + object.routingParameters = []; + for (var j = 0; j < message.routingParameters.length; ++j) + object.routingParameters[j] = $root.google.api.RoutingParameter.toObject(message.routingParameters[j], options); + } + return object; + }; + /** - * SelectiveGapicGeneration generateOmittedAsInternal. - * @member {boolean} generateOmittedAsInternal - * @memberof google.api.SelectiveGapicGeneration + * Converts this RoutingRule to JSON. + * @function toJSON + * @memberof google.api.RoutingRule * @instance + * @returns {Object.} JSON object */ - SelectiveGapicGeneration.prototype.generateOmittedAsInternal = false; - + RoutingRule.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + + /** + * Gets the default type url for RoutingRule + * @function getTypeUrl + * @memberof google.api.RoutingRule + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + RoutingRule.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.api.RoutingRule"; + }; + + return RoutingRule; + })(); + + api.RoutingParameter = (function() { + + /** + * Properties of a RoutingParameter. + * @memberof google.api + * @interface IRoutingParameter + * @property {string|null} [field] RoutingParameter field + * @property {string|null} [pathTemplate] RoutingParameter pathTemplate + */ + /** - * Creates a SelectiveGapicGeneration message from a plain object. Also converts values to their respective internal types. + * Constructs a new RoutingParameter. + * @memberof google.api + * @classdesc Represents a RoutingParameter. + * @implements IRoutingParameter + * @constructor + * @param {google.api.IRoutingParameter=} [properties] Properties to set + */ + function RoutingParameter(properties) { + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } + + /** + * RoutingParameter field. + * @member {string} field + * @memberof google.api.RoutingParameter + * @instance + */ + RoutingParameter.prototype.field = ""; + + /** + * RoutingParameter pathTemplate. + * @member {string} pathTemplate + * @memberof google.api.RoutingParameter + * @instance + */ + RoutingParameter.prototype.pathTemplate = ""; + + /** + * Creates a RoutingParameter message from a plain object. Also converts values to their respective internal types. * @function fromObject - * @memberof google.api.SelectiveGapicGeneration + * @memberof google.api.RoutingParameter * @static * @param {Object.} object Plain object - * @returns {google.api.SelectiveGapicGeneration} SelectiveGapicGeneration + * @returns {google.api.RoutingParameter} RoutingParameter */ - SelectiveGapicGeneration.fromObject = function fromObject(object) { - if (object instanceof $root.google.api.SelectiveGapicGeneration) + RoutingParameter.fromObject = function fromObject(object) { + if (object instanceof $root.google.api.RoutingParameter) return object; - var message = new $root.google.api.SelectiveGapicGeneration(); - if (object.methods) { - if (!Array.isArray(object.methods)) - throw TypeError(".google.api.SelectiveGapicGeneration.methods: array expected"); - message.methods = []; - for (var i = 0; i < object.methods.length; ++i) - message.methods[i] = String(object.methods[i]); - } - if (object.generateOmittedAsInternal != null) - message.generateOmittedAsInternal = Boolean(object.generateOmittedAsInternal); + var message = new $root.google.api.RoutingParameter(); + if (object.field != null) + message.field = String(object.field); + if (object.pathTemplate != null) + message.pathTemplate = String(object.pathTemplate); return message; }; - + /** - * Creates a plain object from a SelectiveGapicGeneration message. Also converts values to other types if specified. + * Creates a plain object from a RoutingParameter message. Also converts values to other types if specified. * @function toObject - * @memberof google.api.SelectiveGapicGeneration + * @memberof google.api.RoutingParameter * @static - * @param {google.api.SelectiveGapicGeneration} message SelectiveGapicGeneration + * @param {google.api.RoutingParameter} message RoutingParameter * @param {$protobuf.IConversionOptions} [options] Conversion options * @returns {Object.} Plain object */ - SelectiveGapicGeneration.toObject = function toObject(message, options) { + RoutingParameter.toObject = function toObject(message, options) { if (!options) options = {}; var object = {}; - if (options.arrays || options.defaults) - object.methods = []; - if (options.defaults) - object.generateOmittedAsInternal = false; - if (message.methods && message.methods.length) { - object.methods = []; - for (var j = 0; j < message.methods.length; ++j) - object.methods[j] = message.methods[j]; - } - if (message.generateOmittedAsInternal != null && message.hasOwnProperty("generateOmittedAsInternal")) - object.generateOmittedAsInternal = message.generateOmittedAsInternal; + if (options.defaults) { + object.field = ""; + object.pathTemplate = ""; + } + if (message.field != null && message.hasOwnProperty("field")) + object.field = message.field; + if (message.pathTemplate != null && message.hasOwnProperty("pathTemplate")) + object.pathTemplate = message.pathTemplate; return object; }; - + /** - * Converts this SelectiveGapicGeneration to JSON. + * Converts this RoutingParameter to JSON. * @function toJSON - * @memberof google.api.SelectiveGapicGeneration + * @memberof google.api.RoutingParameter * @instance * @returns {Object.} JSON object */ - SelectiveGapicGeneration.prototype.toJSON = function toJSON() { + RoutingParameter.prototype.toJSON = function toJSON() { return this.constructor.toObject(this, $protobuf.util.toJSONOptions); }; - + /** - * Gets the default type url for SelectiveGapicGeneration + * Gets the default type url for RoutingParameter * @function getTypeUrl - * @memberof google.api.SelectiveGapicGeneration + * @memberof google.api.RoutingParameter * @static * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") * @returns {string} The default type url */ - SelectiveGapicGeneration.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + RoutingParameter.getTypeUrl = function getTypeUrl(typeUrlPrefix) { if (typeUrlPrefix === undefined) { typeUrlPrefix = "type.googleapis.com"; } - return typeUrlPrefix + "/google.api.SelectiveGapicGeneration"; + return typeUrlPrefix + "/google.api.RoutingParameter"; }; - - return SelectiveGapicGeneration; - })(); - - /** - * LaunchStage enum. - * @name google.api.LaunchStage - * @enum {string} - * @property {string} LAUNCH_STAGE_UNSPECIFIED=LAUNCH_STAGE_UNSPECIFIED LAUNCH_STAGE_UNSPECIFIED value - * @property {string} UNIMPLEMENTED=UNIMPLEMENTED UNIMPLEMENTED value - * @property {string} PRELAUNCH=PRELAUNCH PRELAUNCH value - * @property {string} EARLY_ACCESS=EARLY_ACCESS EARLY_ACCESS value - * @property {string} ALPHA=ALPHA ALPHA value - * @property {string} BETA=BETA BETA value - * @property {string} GA=GA GA value - * @property {string} DEPRECATED=DEPRECATED DEPRECATED value - */ - api.LaunchStage = (function() { - var valuesById = {}, values = Object.create(valuesById); - values[valuesById[0] = "LAUNCH_STAGE_UNSPECIFIED"] = "LAUNCH_STAGE_UNSPECIFIED"; - values[valuesById[6] = "UNIMPLEMENTED"] = "UNIMPLEMENTED"; - values[valuesById[7] = "PRELAUNCH"] = "PRELAUNCH"; - values[valuesById[1] = "EARLY_ACCESS"] = "EARLY_ACCESS"; - values[valuesById[2] = "ALPHA"] = "ALPHA"; - values[valuesById[3] = "BETA"] = "BETA"; - values[valuesById[4] = "GA"] = "GA"; - values[valuesById[5] = "DEPRECATED"] = "DEPRECATED"; - return values; + + return RoutingParameter; })(); - + api.ResourceDescriptor = (function() { - + /** * Properties of a ResourceDescriptor. * @memberof google.api @@ -16242,7 +16287,7 @@ * @property {string|null} [singular] ResourceDescriptor singular * @property {Array.|null} [style] ResourceDescriptor style */ - + /** * Constructs a new ResourceDescriptor. * @memberof google.api @@ -16259,7 +16304,7 @@ if (properties[keys[i]] != null) this[keys[i]] = properties[keys[i]]; } - + /** * ResourceDescriptor type. * @member {string} type @@ -16267,7 +16312,7 @@ * @instance */ ResourceDescriptor.prototype.type = ""; - + /** * ResourceDescriptor pattern. * @member {Array.} pattern @@ -16275,7 +16320,7 @@ * @instance */ ResourceDescriptor.prototype.pattern = $util.emptyArray; - + /** * ResourceDescriptor nameField. * @member {string} nameField @@ -16283,7 +16328,7 @@ * @instance */ ResourceDescriptor.prototype.nameField = ""; - + /** * ResourceDescriptor history. * @member {google.api.ResourceDescriptor.History} history @@ -16291,7 +16336,7 @@ * @instance */ ResourceDescriptor.prototype.history = 0; - + /** * ResourceDescriptor plural. * @member {string} plural @@ -16299,7 +16344,7 @@ * @instance */ ResourceDescriptor.prototype.plural = ""; - + /** * ResourceDescriptor singular. * @member {string} singular @@ -16307,7 +16352,7 @@ * @instance */ ResourceDescriptor.prototype.singular = ""; - + /** * ResourceDescriptor style. * @member {Array.} style @@ -16315,7 +16360,7 @@ * @instance */ ResourceDescriptor.prototype.style = $util.emptyArray; - + /** * Creates a ResourceDescriptor message from a plain object. Also converts values to their respective internal types. * @function fromObject @@ -16386,7 +16431,7 @@ } return message; }; - + /** * Creates a plain object from a ResourceDescriptor message. Also converts values to other types if specified. * @function toObject @@ -16433,7 +16478,7 @@ } return object; }; - + /** * Converts this ResourceDescriptor to JSON. * @function toJSON @@ -16444,7 +16489,7 @@ ResourceDescriptor.prototype.toJSON = function toJSON() { return this.constructor.toObject(this, $protobuf.util.toJSONOptions); }; - + /** * Gets the default type url for ResourceDescriptor * @function getTypeUrl @@ -16459,7 +16504,7 @@ } return typeUrlPrefix + "/google.api.ResourceDescriptor"; }; - + /** * History enum. * @name google.api.ResourceDescriptor.History @@ -16475,7 +16520,7 @@ values[valuesById[2] = "FUTURE_MULTI_PATTERN"] = "FUTURE_MULTI_PATTERN"; return values; })(); - + /** * Style enum. * @name google.api.ResourceDescriptor.Style @@ -16489,12 +16534,12 @@ values[valuesById[1] = "DECLARATIVE_FRIENDLY"] = "DECLARATIVE_FRIENDLY"; return values; })(); - + return ResourceDescriptor; })(); - + api.ResourceReference = (function() { - + /** * Properties of a ResourceReference. * @memberof google.api @@ -16502,7 +16547,7 @@ * @property {string|null} [type] ResourceReference type * @property {string|null} [childType] ResourceReference childType */ - + /** * Constructs a new ResourceReference. * @memberof google.api @@ -16517,7 +16562,7 @@ if (properties[keys[i]] != null) this[keys[i]] = properties[keys[i]]; } - + /** * ResourceReference type. * @member {string} type @@ -16525,7 +16570,7 @@ * @instance */ ResourceReference.prototype.type = ""; - + /** * ResourceReference childType. * @member {string} childType @@ -16533,7 +16578,7 @@ * @instance */ ResourceReference.prototype.childType = ""; - + /** * Creates a ResourceReference message from a plain object. Also converts values to their respective internal types. * @function fromObject @@ -16552,7 +16597,7 @@ message.childType = String(object.childType); return message; }; - + /** * Creates a plain object from a ResourceReference message. Also converts values to other types if specified. * @function toObject @@ -16576,7 +16621,7 @@ object.childType = message.childType; return object; }; - + /** * Converts this ResourceReference to JSON. * @function toJSON @@ -16587,7 +16632,7 @@ ResourceReference.prototype.toJSON = function toJSON() { return this.constructor.toObject(this, $protobuf.util.toJSONOptions); }; - + /** * Gets the default type url for ResourceReference * @function getTypeUrl @@ -16602,31 +16647,31 @@ } return typeUrlPrefix + "/google.api.ResourceReference"; }; - + return ResourceReference; })(); - + return api; })(); - + google.protobuf = (function() { - + /** * Namespace protobuf. * @memberof google * @namespace */ var protobuf = {}; - + protobuf.FileDescriptorSet = (function() { - + /** * Properties of a FileDescriptorSet. * @memberof google.protobuf * @interface IFileDescriptorSet * @property {Array.|null} [file] FileDescriptorSet file */ - + /** * Constructs a new FileDescriptorSet. * @memberof google.protobuf @@ -16642,7 +16687,7 @@ if (properties[keys[i]] != null) this[keys[i]] = properties[keys[i]]; } - + /** * FileDescriptorSet file. * @member {Array.} file @@ -16650,7 +16695,7 @@ * @instance */ FileDescriptorSet.prototype.file = $util.emptyArray; - + /** * Creates a FileDescriptorSet message from a plain object. Also converts values to their respective internal types. * @function fromObject @@ -16675,7 +16720,7 @@ } return message; }; - + /** * Creates a plain object from a FileDescriptorSet message. Also converts values to other types if specified. * @function toObject @@ -16698,7 +16743,7 @@ } return object; }; - + /** * Converts this FileDescriptorSet to JSON. * @function toJSON @@ -16709,7 +16754,7 @@ FileDescriptorSet.prototype.toJSON = function toJSON() { return this.constructor.toObject(this, $protobuf.util.toJSONOptions); }; - + /** * Gets the default type url for FileDescriptorSet * @function getTypeUrl @@ -16724,10 +16769,10 @@ } return typeUrlPrefix + "/google.protobuf.FileDescriptorSet"; }; - + return FileDescriptorSet; })(); - + /** * Edition enum. * @name google.protobuf.Edition @@ -16759,9 +16804,9 @@ values[valuesById[2147483647] = "EDITION_MAX"] = "EDITION_MAX"; return values; })(); - + protobuf.FileDescriptorProto = (function() { - + /** * Properties of a FileDescriptorProto. * @memberof google.protobuf @@ -16780,7 +16825,7 @@ * @property {string|null} [syntax] FileDescriptorProto syntax * @property {google.protobuf.Edition|null} [edition] FileDescriptorProto edition */ - + /** * Constructs a new FileDescriptorProto. * @memberof google.protobuf @@ -16802,7 +16847,7 @@ if (properties[keys[i]] != null) this[keys[i]] = properties[keys[i]]; } - + /** * FileDescriptorProto name. * @member {string} name @@ -16810,7 +16855,7 @@ * @instance */ FileDescriptorProto.prototype.name = ""; - + /** * FileDescriptorProto package. * @member {string} package @@ -16818,7 +16863,7 @@ * @instance */ FileDescriptorProto.prototype["package"] = ""; - + /** * FileDescriptorProto dependency. * @member {Array.} dependency @@ -16826,7 +16871,7 @@ * @instance */ FileDescriptorProto.prototype.dependency = $util.emptyArray; - + /** * FileDescriptorProto publicDependency. * @member {Array.} publicDependency @@ -16834,7 +16879,7 @@ * @instance */ FileDescriptorProto.prototype.publicDependency = $util.emptyArray; - + /** * FileDescriptorProto weakDependency. * @member {Array.} weakDependency @@ -16842,7 +16887,7 @@ * @instance */ FileDescriptorProto.prototype.weakDependency = $util.emptyArray; - + /** * FileDescriptorProto messageType. * @member {Array.} messageType @@ -16850,7 +16895,7 @@ * @instance */ FileDescriptorProto.prototype.messageType = $util.emptyArray; - + /** * FileDescriptorProto enumType. * @member {Array.} enumType @@ -16858,7 +16903,7 @@ * @instance */ FileDescriptorProto.prototype.enumType = $util.emptyArray; - + /** * FileDescriptorProto service. * @member {Array.} service @@ -16866,7 +16911,7 @@ * @instance */ FileDescriptorProto.prototype.service = $util.emptyArray; - + /** * FileDescriptorProto extension. * @member {Array.} extension @@ -16874,7 +16919,7 @@ * @instance */ FileDescriptorProto.prototype.extension = $util.emptyArray; - + /** * FileDescriptorProto options. * @member {google.protobuf.IFileOptions|null|undefined} options @@ -16882,7 +16927,7 @@ * @instance */ FileDescriptorProto.prototype.options = null; - + /** * FileDescriptorProto sourceCodeInfo. * @member {google.protobuf.ISourceCodeInfo|null|undefined} sourceCodeInfo @@ -16890,7 +16935,7 @@ * @instance */ FileDescriptorProto.prototype.sourceCodeInfo = null; - + /** * FileDescriptorProto syntax. * @member {string} syntax @@ -16898,7 +16943,7 @@ * @instance */ FileDescriptorProto.prototype.syntax = ""; - + /** * FileDescriptorProto edition. * @member {google.protobuf.Edition} edition @@ -16906,7 +16951,7 @@ * @instance */ FileDescriptorProto.prototype.edition = 0; - + /** * Creates a FileDescriptorProto message from a plain object. Also converts values to their respective internal types. * @function fromObject @@ -17050,7 +17095,7 @@ } return message; }; - + /** * Creates a plain object from a FileDescriptorProto message. Also converts values to other types if specified. * @function toObject @@ -17130,7 +17175,7 @@ object.edition = options.enums === String ? $root.google.protobuf.Edition[message.edition] === undefined ? message.edition : $root.google.protobuf.Edition[message.edition] : message.edition; return object; }; - + /** * Converts this FileDescriptorProto to JSON. * @function toJSON @@ -17141,7 +17186,7 @@ FileDescriptorProto.prototype.toJSON = function toJSON() { return this.constructor.toObject(this, $protobuf.util.toJSONOptions); }; - + /** * Gets the default type url for FileDescriptorProto * @function getTypeUrl @@ -17156,12 +17201,12 @@ } return typeUrlPrefix + "/google.protobuf.FileDescriptorProto"; }; - + return FileDescriptorProto; })(); - + protobuf.DescriptorProto = (function() { - + /** * Properties of a DescriptorProto. * @memberof google.protobuf @@ -17177,7 +17222,7 @@ * @property {Array.|null} [reservedRange] DescriptorProto reservedRange * @property {Array.|null} [reservedName] DescriptorProto reservedName */ - + /** * Constructs a new DescriptorProto. * @memberof google.protobuf @@ -17200,7 +17245,7 @@ if (properties[keys[i]] != null) this[keys[i]] = properties[keys[i]]; } - + /** * DescriptorProto name. * @member {string} name @@ -17208,7 +17253,7 @@ * @instance */ DescriptorProto.prototype.name = ""; - + /** * DescriptorProto field. * @member {Array.} field @@ -17216,7 +17261,7 @@ * @instance */ DescriptorProto.prototype.field = $util.emptyArray; - + /** * DescriptorProto extension. * @member {Array.} extension @@ -17224,7 +17269,7 @@ * @instance */ DescriptorProto.prototype.extension = $util.emptyArray; - + /** * DescriptorProto nestedType. * @member {Array.} nestedType @@ -17232,7 +17277,7 @@ * @instance */ DescriptorProto.prototype.nestedType = $util.emptyArray; - + /** * DescriptorProto enumType. * @member {Array.} enumType @@ -17240,7 +17285,7 @@ * @instance */ DescriptorProto.prototype.enumType = $util.emptyArray; - + /** * DescriptorProto extensionRange. * @member {Array.} extensionRange @@ -17248,7 +17293,7 @@ * @instance */ DescriptorProto.prototype.extensionRange = $util.emptyArray; - + /** * DescriptorProto oneofDecl. * @member {Array.} oneofDecl @@ -17256,7 +17301,7 @@ * @instance */ DescriptorProto.prototype.oneofDecl = $util.emptyArray; - + /** * DescriptorProto options. * @member {google.protobuf.IMessageOptions|null|undefined} options @@ -17264,7 +17309,7 @@ * @instance */ DescriptorProto.prototype.options = null; - + /** * DescriptorProto reservedRange. * @member {Array.} reservedRange @@ -17272,7 +17317,7 @@ * @instance */ DescriptorProto.prototype.reservedRange = $util.emptyArray; - + /** * DescriptorProto reservedName. * @member {Array.} reservedName @@ -17280,7 +17325,7 @@ * @instance */ DescriptorProto.prototype.reservedName = $util.emptyArray; - + /** * Creates a DescriptorProto message from a plain object. Also converts values to their respective internal types. * @function fromObject @@ -17379,7 +17424,7 @@ } return message; }; - + /** * Creates a plain object from a DescriptorProto message. Also converts values to other types if specified. * @function toObject @@ -17453,7 +17498,7 @@ } return object; }; - + /** * Converts this DescriptorProto to JSON. * @function toJSON @@ -17464,7 +17509,7 @@ DescriptorProto.prototype.toJSON = function toJSON() { return this.constructor.toObject(this, $protobuf.util.toJSONOptions); }; - + /** * Gets the default type url for DescriptorProto * @function getTypeUrl @@ -17479,9 +17524,9 @@ } return typeUrlPrefix + "/google.protobuf.DescriptorProto"; }; - + DescriptorProto.ExtensionRange = (function() { - + /** * Properties of an ExtensionRange. * @memberof google.protobuf.DescriptorProto @@ -17490,7 +17535,7 @@ * @property {number|null} [end] ExtensionRange end * @property {google.protobuf.IExtensionRangeOptions|null} [options] ExtensionRange options */ - + /** * Constructs a new ExtensionRange. * @memberof google.protobuf.DescriptorProto @@ -17505,7 +17550,7 @@ if (properties[keys[i]] != null) this[keys[i]] = properties[keys[i]]; } - + /** * ExtensionRange start. * @member {number} start @@ -17513,7 +17558,7 @@ * @instance */ ExtensionRange.prototype.start = 0; - + /** * ExtensionRange end. * @member {number} end @@ -17521,7 +17566,7 @@ * @instance */ ExtensionRange.prototype.end = 0; - + /** * ExtensionRange options. * @member {google.protobuf.IExtensionRangeOptions|null|undefined} options @@ -17529,7 +17574,7 @@ * @instance */ ExtensionRange.prototype.options = null; - + /** * Creates an ExtensionRange message from a plain object. Also converts values to their respective internal types. * @function fromObject @@ -17553,7 +17598,7 @@ } return message; }; - + /** * Creates a plain object from an ExtensionRange message. Also converts values to other types if specified. * @function toObject @@ -17580,7 +17625,7 @@ object.options = $root.google.protobuf.ExtensionRangeOptions.toObject(message.options, options); return object; }; - + /** * Converts this ExtensionRange to JSON. * @function toJSON @@ -17591,7 +17636,7 @@ ExtensionRange.prototype.toJSON = function toJSON() { return this.constructor.toObject(this, $protobuf.util.toJSONOptions); }; - + /** * Gets the default type url for ExtensionRange * @function getTypeUrl @@ -17606,12 +17651,12 @@ } return typeUrlPrefix + "/google.protobuf.DescriptorProto.ExtensionRange"; }; - + return ExtensionRange; })(); - + DescriptorProto.ReservedRange = (function() { - + /** * Properties of a ReservedRange. * @memberof google.protobuf.DescriptorProto @@ -17619,7 +17664,7 @@ * @property {number|null} [start] ReservedRange start * @property {number|null} [end] ReservedRange end */ - + /** * Constructs a new ReservedRange. * @memberof google.protobuf.DescriptorProto @@ -17634,7 +17679,7 @@ if (properties[keys[i]] != null) this[keys[i]] = properties[keys[i]]; } - + /** * ReservedRange start. * @member {number} start @@ -17642,7 +17687,7 @@ * @instance */ ReservedRange.prototype.start = 0; - + /** * ReservedRange end. * @member {number} end @@ -17650,7 +17695,7 @@ * @instance */ ReservedRange.prototype.end = 0; - + /** * Creates a ReservedRange message from a plain object. Also converts values to their respective internal types. * @function fromObject @@ -17669,7 +17714,7 @@ message.end = object.end | 0; return message; }; - + /** * Creates a plain object from a ReservedRange message. Also converts values to other types if specified. * @function toObject @@ -17693,7 +17738,7 @@ object.end = message.end; return object; }; - + /** * Converts this ReservedRange to JSON. * @function toJSON @@ -17704,7 +17749,7 @@ ReservedRange.prototype.toJSON = function toJSON() { return this.constructor.toObject(this, $protobuf.util.toJSONOptions); }; - + /** * Gets the default type url for ReservedRange * @function getTypeUrl @@ -17719,15 +17764,15 @@ } return typeUrlPrefix + "/google.protobuf.DescriptorProto.ReservedRange"; }; - + return ReservedRange; })(); - + return DescriptorProto; })(); - + protobuf.ExtensionRangeOptions = (function() { - + /** * Properties of an ExtensionRangeOptions. * @memberof google.protobuf @@ -17737,7 +17782,7 @@ * @property {google.protobuf.IFeatureSet|null} [features] ExtensionRangeOptions features * @property {google.protobuf.ExtensionRangeOptions.VerificationState|null} [verification] ExtensionRangeOptions verification */ - + /** * Constructs a new ExtensionRangeOptions. * @memberof google.protobuf @@ -17754,7 +17799,7 @@ if (properties[keys[i]] != null) this[keys[i]] = properties[keys[i]]; } - + /** * ExtensionRangeOptions uninterpretedOption. * @member {Array.} uninterpretedOption @@ -17762,7 +17807,7 @@ * @instance */ ExtensionRangeOptions.prototype.uninterpretedOption = $util.emptyArray; - + /** * ExtensionRangeOptions declaration. * @member {Array.} declaration @@ -17770,7 +17815,7 @@ * @instance */ ExtensionRangeOptions.prototype.declaration = $util.emptyArray; - + /** * ExtensionRangeOptions features. * @member {google.protobuf.IFeatureSet|null|undefined} features @@ -17778,7 +17823,7 @@ * @instance */ ExtensionRangeOptions.prototype.features = null; - + /** * ExtensionRangeOptions verification. * @member {google.protobuf.ExtensionRangeOptions.VerificationState} verification @@ -17786,7 +17831,7 @@ * @instance */ ExtensionRangeOptions.prototype.verification = 1; - + /** * Creates an ExtensionRangeOptions message from a plain object. Also converts values to their respective internal types. * @function fromObject @@ -17842,7 +17887,7 @@ } return message; }; - + /** * Creates a plain object from an ExtensionRangeOptions message. Also converts values to other types if specified. * @function toObject @@ -17880,7 +17925,7 @@ } return object; }; - + /** * Converts this ExtensionRangeOptions to JSON. * @function toJSON @@ -17891,7 +17936,7 @@ ExtensionRangeOptions.prototype.toJSON = function toJSON() { return this.constructor.toObject(this, $protobuf.util.toJSONOptions); }; - + /** * Gets the default type url for ExtensionRangeOptions * @function getTypeUrl @@ -17906,9 +17951,9 @@ } return typeUrlPrefix + "/google.protobuf.ExtensionRangeOptions"; }; - + ExtensionRangeOptions.Declaration = (function() { - + /** * Properties of a Declaration. * @memberof google.protobuf.ExtensionRangeOptions @@ -17919,7 +17964,7 @@ * @property {boolean|null} [reserved] Declaration reserved * @property {boolean|null} [repeated] Declaration repeated */ - + /** * Constructs a new Declaration. * @memberof google.protobuf.ExtensionRangeOptions @@ -17934,7 +17979,7 @@ if (properties[keys[i]] != null) this[keys[i]] = properties[keys[i]]; } - + /** * Declaration number. * @member {number} number @@ -17942,7 +17987,7 @@ * @instance */ Declaration.prototype.number = 0; - + /** * Declaration fullName. * @member {string} fullName @@ -17950,7 +17995,7 @@ * @instance */ Declaration.prototype.fullName = ""; - + /** * Declaration type. * @member {string} type @@ -17958,7 +18003,7 @@ * @instance */ Declaration.prototype.type = ""; - + /** * Declaration reserved. * @member {boolean} reserved @@ -17966,7 +18011,7 @@ * @instance */ Declaration.prototype.reserved = false; - + /** * Declaration repeated. * @member {boolean} repeated @@ -17974,7 +18019,7 @@ * @instance */ Declaration.prototype.repeated = false; - + /** * Creates a Declaration message from a plain object. Also converts values to their respective internal types. * @function fromObject @@ -17999,7 +18044,7 @@ message.repeated = Boolean(object.repeated); return message; }; - + /** * Creates a plain object from a Declaration message. Also converts values to other types if specified. * @function toObject @@ -18032,7 +18077,7 @@ object.repeated = message.repeated; return object; }; - + /** * Converts this Declaration to JSON. * @function toJSON @@ -18043,7 +18088,7 @@ Declaration.prototype.toJSON = function toJSON() { return this.constructor.toObject(this, $protobuf.util.toJSONOptions); }; - + /** * Gets the default type url for Declaration * @function getTypeUrl @@ -18058,10 +18103,10 @@ } return typeUrlPrefix + "/google.protobuf.ExtensionRangeOptions.Declaration"; }; - + return Declaration; })(); - + /** * VerificationState enum. * @name google.protobuf.ExtensionRangeOptions.VerificationState @@ -18075,12 +18120,12 @@ values[valuesById[1] = "UNVERIFIED"] = "UNVERIFIED"; return values; })(); - + return ExtensionRangeOptions; })(); - + protobuf.FieldDescriptorProto = (function() { - + /** * Properties of a FieldDescriptorProto. * @memberof google.protobuf @@ -18097,7 +18142,7 @@ * @property {google.protobuf.IFieldOptions|null} [options] FieldDescriptorProto options * @property {boolean|null} [proto3Optional] FieldDescriptorProto proto3Optional */ - + /** * Constructs a new FieldDescriptorProto. * @memberof google.protobuf @@ -18112,7 +18157,7 @@ if (properties[keys[i]] != null) this[keys[i]] = properties[keys[i]]; } - + /** * FieldDescriptorProto name. * @member {string} name @@ -18120,7 +18165,7 @@ * @instance */ FieldDescriptorProto.prototype.name = ""; - + /** * FieldDescriptorProto number. * @member {number} number @@ -18128,7 +18173,7 @@ * @instance */ FieldDescriptorProto.prototype.number = 0; - + /** * FieldDescriptorProto label. * @member {google.protobuf.FieldDescriptorProto.Label} label @@ -18136,7 +18181,7 @@ * @instance */ FieldDescriptorProto.prototype.label = 1; - + /** * FieldDescriptorProto type. * @member {google.protobuf.FieldDescriptorProto.Type} type @@ -18144,7 +18189,7 @@ * @instance */ FieldDescriptorProto.prototype.type = 1; - + /** * FieldDescriptorProto typeName. * @member {string} typeName @@ -18152,7 +18197,7 @@ * @instance */ FieldDescriptorProto.prototype.typeName = ""; - + /** * FieldDescriptorProto extendee. * @member {string} extendee @@ -18160,7 +18205,7 @@ * @instance */ FieldDescriptorProto.prototype.extendee = ""; - + /** * FieldDescriptorProto defaultValue. * @member {string} defaultValue @@ -18168,7 +18213,7 @@ * @instance */ FieldDescriptorProto.prototype.defaultValue = ""; - + /** * FieldDescriptorProto oneofIndex. * @member {number} oneofIndex @@ -18176,7 +18221,7 @@ * @instance */ FieldDescriptorProto.prototype.oneofIndex = 0; - + /** * FieldDescriptorProto jsonName. * @member {string} jsonName @@ -18184,7 +18229,7 @@ * @instance */ FieldDescriptorProto.prototype.jsonName = ""; - + /** * FieldDescriptorProto options. * @member {google.protobuf.IFieldOptions|null|undefined} options @@ -18192,7 +18237,7 @@ * @instance */ FieldDescriptorProto.prototype.options = null; - + /** * FieldDescriptorProto proto3Optional. * @member {boolean} proto3Optional @@ -18200,7 +18245,7 @@ * @instance */ FieldDescriptorProto.prototype.proto3Optional = false; - + /** * Creates a FieldDescriptorProto message from a plain object. Also converts values to their respective internal types. * @function fromObject @@ -18336,7 +18381,7 @@ message.proto3Optional = Boolean(object.proto3Optional); return message; }; - + /** * Creates a plain object from a FieldDescriptorProto message. Also converts values to other types if specified. * @function toObject @@ -18387,7 +18432,7 @@ object.proto3Optional = message.proto3Optional; return object; }; - + /** * Converts this FieldDescriptorProto to JSON. * @function toJSON @@ -18398,7 +18443,7 @@ FieldDescriptorProto.prototype.toJSON = function toJSON() { return this.constructor.toObject(this, $protobuf.util.toJSONOptions); }; - + /** * Gets the default type url for FieldDescriptorProto * @function getTypeUrl @@ -18413,7 +18458,7 @@ } return typeUrlPrefix + "/google.protobuf.FieldDescriptorProto"; }; - + /** * Type enum. * @name google.protobuf.FieldDescriptorProto.Type @@ -18459,7 +18504,7 @@ values[valuesById[18] = "TYPE_SINT64"] = "TYPE_SINT64"; return values; })(); - + /** * Label enum. * @name google.protobuf.FieldDescriptorProto.Label @@ -18475,12 +18520,12 @@ values[valuesById[2] = "LABEL_REQUIRED"] = "LABEL_REQUIRED"; return values; })(); - + return FieldDescriptorProto; })(); - + protobuf.OneofDescriptorProto = (function() { - + /** * Properties of an OneofDescriptorProto. * @memberof google.protobuf @@ -18488,7 +18533,7 @@ * @property {string|null} [name] OneofDescriptorProto name * @property {google.protobuf.IOneofOptions|null} [options] OneofDescriptorProto options */ - + /** * Constructs a new OneofDescriptorProto. * @memberof google.protobuf @@ -18503,7 +18548,7 @@ if (properties[keys[i]] != null) this[keys[i]] = properties[keys[i]]; } - + /** * OneofDescriptorProto name. * @member {string} name @@ -18511,7 +18556,7 @@ * @instance */ OneofDescriptorProto.prototype.name = ""; - + /** * OneofDescriptorProto options. * @member {google.protobuf.IOneofOptions|null|undefined} options @@ -18519,7 +18564,7 @@ * @instance */ OneofDescriptorProto.prototype.options = null; - + /** * Creates an OneofDescriptorProto message from a plain object. Also converts values to their respective internal types. * @function fromObject @@ -18541,7 +18586,7 @@ } return message; }; - + /** * Creates a plain object from an OneofDescriptorProto message. Also converts values to other types if specified. * @function toObject @@ -18565,7 +18610,7 @@ object.options = $root.google.protobuf.OneofOptions.toObject(message.options, options); return object; }; - + /** * Converts this OneofDescriptorProto to JSON. * @function toJSON @@ -18576,7 +18621,7 @@ OneofDescriptorProto.prototype.toJSON = function toJSON() { return this.constructor.toObject(this, $protobuf.util.toJSONOptions); }; - + /** * Gets the default type url for OneofDescriptorProto * @function getTypeUrl @@ -18591,12 +18636,12 @@ } return typeUrlPrefix + "/google.protobuf.OneofDescriptorProto"; }; - + return OneofDescriptorProto; })(); - + protobuf.EnumDescriptorProto = (function() { - + /** * Properties of an EnumDescriptorProto. * @memberof google.protobuf @@ -18607,7 +18652,7 @@ * @property {Array.|null} [reservedRange] EnumDescriptorProto reservedRange * @property {Array.|null} [reservedName] EnumDescriptorProto reservedName */ - + /** * Constructs a new EnumDescriptorProto. * @memberof google.protobuf @@ -18625,7 +18670,7 @@ if (properties[keys[i]] != null) this[keys[i]] = properties[keys[i]]; } - + /** * EnumDescriptorProto name. * @member {string} name @@ -18633,7 +18678,7 @@ * @instance */ EnumDescriptorProto.prototype.name = ""; - + /** * EnumDescriptorProto value. * @member {Array.} value @@ -18641,7 +18686,7 @@ * @instance */ EnumDescriptorProto.prototype.value = $util.emptyArray; - + /** * EnumDescriptorProto options. * @member {google.protobuf.IEnumOptions|null|undefined} options @@ -18649,7 +18694,7 @@ * @instance */ EnumDescriptorProto.prototype.options = null; - + /** * EnumDescriptorProto reservedRange. * @member {Array.} reservedRange @@ -18657,7 +18702,7 @@ * @instance */ EnumDescriptorProto.prototype.reservedRange = $util.emptyArray; - + /** * EnumDescriptorProto reservedName. * @member {Array.} reservedName @@ -18665,7 +18710,7 @@ * @instance */ EnumDescriptorProto.prototype.reservedName = $util.emptyArray; - + /** * Creates an EnumDescriptorProto message from a plain object. Also converts values to their respective internal types. * @function fromObject @@ -18714,7 +18759,7 @@ } return message; }; - + /** * Creates a plain object from an EnumDescriptorProto message. Also converts values to other types if specified. * @function toObject @@ -18758,7 +18803,7 @@ } return object; }; - + /** * Converts this EnumDescriptorProto to JSON. * @function toJSON @@ -18769,7 +18814,7 @@ EnumDescriptorProto.prototype.toJSON = function toJSON() { return this.constructor.toObject(this, $protobuf.util.toJSONOptions); }; - + /** * Gets the default type url for EnumDescriptorProto * @function getTypeUrl @@ -18784,9 +18829,9 @@ } return typeUrlPrefix + "/google.protobuf.EnumDescriptorProto"; }; - + EnumDescriptorProto.EnumReservedRange = (function() { - + /** * Properties of an EnumReservedRange. * @memberof google.protobuf.EnumDescriptorProto @@ -18794,7 +18839,7 @@ * @property {number|null} [start] EnumReservedRange start * @property {number|null} [end] EnumReservedRange end */ - + /** * Constructs a new EnumReservedRange. * @memberof google.protobuf.EnumDescriptorProto @@ -18809,7 +18854,7 @@ if (properties[keys[i]] != null) this[keys[i]] = properties[keys[i]]; } - + /** * EnumReservedRange start. * @member {number} start @@ -18817,7 +18862,7 @@ * @instance */ EnumReservedRange.prototype.start = 0; - + /** * EnumReservedRange end. * @member {number} end @@ -18825,7 +18870,7 @@ * @instance */ EnumReservedRange.prototype.end = 0; - + /** * Creates an EnumReservedRange message from a plain object. Also converts values to their respective internal types. * @function fromObject @@ -18844,7 +18889,7 @@ message.end = object.end | 0; return message; }; - + /** * Creates a plain object from an EnumReservedRange message. Also converts values to other types if specified. * @function toObject @@ -18868,7 +18913,7 @@ object.end = message.end; return object; }; - + /** * Converts this EnumReservedRange to JSON. * @function toJSON @@ -18879,7 +18924,7 @@ EnumReservedRange.prototype.toJSON = function toJSON() { return this.constructor.toObject(this, $protobuf.util.toJSONOptions); }; - + /** * Gets the default type url for EnumReservedRange * @function getTypeUrl @@ -18894,15 +18939,15 @@ } return typeUrlPrefix + "/google.protobuf.EnumDescriptorProto.EnumReservedRange"; }; - + return EnumReservedRange; })(); - + return EnumDescriptorProto; })(); - + protobuf.EnumValueDescriptorProto = (function() { - + /** * Properties of an EnumValueDescriptorProto. * @memberof google.protobuf @@ -18911,7 +18956,7 @@ * @property {number|null} [number] EnumValueDescriptorProto number * @property {google.protobuf.IEnumValueOptions|null} [options] EnumValueDescriptorProto options */ - + /** * Constructs a new EnumValueDescriptorProto. * @memberof google.protobuf @@ -18926,7 +18971,7 @@ if (properties[keys[i]] != null) this[keys[i]] = properties[keys[i]]; } - + /** * EnumValueDescriptorProto name. * @member {string} name @@ -18934,7 +18979,7 @@ * @instance */ EnumValueDescriptorProto.prototype.name = ""; - + /** * EnumValueDescriptorProto number. * @member {number} number @@ -18942,7 +18987,7 @@ * @instance */ EnumValueDescriptorProto.prototype.number = 0; - + /** * EnumValueDescriptorProto options. * @member {google.protobuf.IEnumValueOptions|null|undefined} options @@ -18950,7 +18995,7 @@ * @instance */ EnumValueDescriptorProto.prototype.options = null; - + /** * Creates an EnumValueDescriptorProto message from a plain object. Also converts values to their respective internal types. * @function fromObject @@ -18974,7 +19019,7 @@ } return message; }; - + /** * Creates a plain object from an EnumValueDescriptorProto message. Also converts values to other types if specified. * @function toObject @@ -19001,7 +19046,7 @@ object.options = $root.google.protobuf.EnumValueOptions.toObject(message.options, options); return object; }; - + /** * Converts this EnumValueDescriptorProto to JSON. * @function toJSON @@ -19012,7 +19057,7 @@ EnumValueDescriptorProto.prototype.toJSON = function toJSON() { return this.constructor.toObject(this, $protobuf.util.toJSONOptions); }; - + /** * Gets the default type url for EnumValueDescriptorProto * @function getTypeUrl @@ -19027,12 +19072,12 @@ } return typeUrlPrefix + "/google.protobuf.EnumValueDescriptorProto"; }; - + return EnumValueDescriptorProto; })(); - + protobuf.ServiceDescriptorProto = (function() { - + /** * Properties of a ServiceDescriptorProto. * @memberof google.protobuf @@ -19041,7 +19086,7 @@ * @property {Array.|null} [method] ServiceDescriptorProto method * @property {google.protobuf.IServiceOptions|null} [options] ServiceDescriptorProto options */ - + /** * Constructs a new ServiceDescriptorProto. * @memberof google.protobuf @@ -19057,7 +19102,7 @@ if (properties[keys[i]] != null) this[keys[i]] = properties[keys[i]]; } - + /** * ServiceDescriptorProto name. * @member {string} name @@ -19065,7 +19110,7 @@ * @instance */ ServiceDescriptorProto.prototype.name = ""; - + /** * ServiceDescriptorProto method. * @member {Array.} method @@ -19073,7 +19118,7 @@ * @instance */ ServiceDescriptorProto.prototype.method = $util.emptyArray; - + /** * ServiceDescriptorProto options. * @member {google.protobuf.IServiceOptions|null|undefined} options @@ -19081,7 +19126,7 @@ * @instance */ ServiceDescriptorProto.prototype.options = null; - + /** * Creates a ServiceDescriptorProto message from a plain object. Also converts values to their respective internal types. * @function fromObject @@ -19113,7 +19158,7 @@ } return message; }; - + /** * Creates a plain object from a ServiceDescriptorProto message. Also converts values to other types if specified. * @function toObject @@ -19144,7 +19189,7 @@ object.options = $root.google.protobuf.ServiceOptions.toObject(message.options, options); return object; }; - + /** * Converts this ServiceDescriptorProto to JSON. * @function toJSON @@ -19155,7 +19200,7 @@ ServiceDescriptorProto.prototype.toJSON = function toJSON() { return this.constructor.toObject(this, $protobuf.util.toJSONOptions); }; - + /** * Gets the default type url for ServiceDescriptorProto * @function getTypeUrl @@ -19170,12 +19215,12 @@ } return typeUrlPrefix + "/google.protobuf.ServiceDescriptorProto"; }; - + return ServiceDescriptorProto; })(); - + protobuf.MethodDescriptorProto = (function() { - + /** * Properties of a MethodDescriptorProto. * @memberof google.protobuf @@ -19187,7 +19232,7 @@ * @property {boolean|null} [clientStreaming] MethodDescriptorProto clientStreaming * @property {boolean|null} [serverStreaming] MethodDescriptorProto serverStreaming */ - + /** * Constructs a new MethodDescriptorProto. * @memberof google.protobuf @@ -19202,7 +19247,7 @@ if (properties[keys[i]] != null) this[keys[i]] = properties[keys[i]]; } - + /** * MethodDescriptorProto name. * @member {string} name @@ -19210,7 +19255,7 @@ * @instance */ MethodDescriptorProto.prototype.name = ""; - + /** * MethodDescriptorProto inputType. * @member {string} inputType @@ -19218,7 +19263,7 @@ * @instance */ MethodDescriptorProto.prototype.inputType = ""; - + /** * MethodDescriptorProto outputType. * @member {string} outputType @@ -19226,7 +19271,7 @@ * @instance */ MethodDescriptorProto.prototype.outputType = ""; - + /** * MethodDescriptorProto options. * @member {google.protobuf.IMethodOptions|null|undefined} options @@ -19234,7 +19279,7 @@ * @instance */ MethodDescriptorProto.prototype.options = null; - + /** * MethodDescriptorProto clientStreaming. * @member {boolean} clientStreaming @@ -19242,7 +19287,7 @@ * @instance */ MethodDescriptorProto.prototype.clientStreaming = false; - + /** * MethodDescriptorProto serverStreaming. * @member {boolean} serverStreaming @@ -19250,7 +19295,7 @@ * @instance */ MethodDescriptorProto.prototype.serverStreaming = false; - + /** * Creates a MethodDescriptorProto message from a plain object. Also converts values to their respective internal types. * @function fromObject @@ -19280,7 +19325,7 @@ message.serverStreaming = Boolean(object.serverStreaming); return message; }; - + /** * Creates a plain object from a MethodDescriptorProto message. Also converts values to other types if specified. * @function toObject @@ -19316,7 +19361,7 @@ object.serverStreaming = message.serverStreaming; return object; }; - + /** * Converts this MethodDescriptorProto to JSON. * @function toJSON @@ -19327,7 +19372,7 @@ MethodDescriptorProto.prototype.toJSON = function toJSON() { return this.constructor.toObject(this, $protobuf.util.toJSONOptions); }; - + /** * Gets the default type url for MethodDescriptorProto * @function getTypeUrl @@ -19342,12 +19387,12 @@ } return typeUrlPrefix + "/google.protobuf.MethodDescriptorProto"; }; - + return MethodDescriptorProto; })(); - + protobuf.FileOptions = (function() { - + /** * Properties of a FileOptions. * @memberof google.protobuf @@ -19375,7 +19420,7 @@ * @property {Array.|null} [uninterpretedOption] FileOptions uninterpretedOption * @property {Array.|null} [".google.api.resourceDefinition"] FileOptions .google.api.resourceDefinition */ - + /** * Constructs a new FileOptions. * @memberof google.protobuf @@ -19392,7 +19437,7 @@ if (properties[keys[i]] != null) this[keys[i]] = properties[keys[i]]; } - + /** * FileOptions javaPackage. * @member {string} javaPackage @@ -19400,7 +19445,7 @@ * @instance */ FileOptions.prototype.javaPackage = ""; - + /** * FileOptions javaOuterClassname. * @member {string} javaOuterClassname @@ -19408,7 +19453,7 @@ * @instance */ FileOptions.prototype.javaOuterClassname = ""; - + /** * FileOptions javaMultipleFiles. * @member {boolean} javaMultipleFiles @@ -19416,7 +19461,7 @@ * @instance */ FileOptions.prototype.javaMultipleFiles = false; - + /** * FileOptions javaGenerateEqualsAndHash. * @member {boolean} javaGenerateEqualsAndHash @@ -19424,7 +19469,7 @@ * @instance */ FileOptions.prototype.javaGenerateEqualsAndHash = false; - + /** * FileOptions javaStringCheckUtf8. * @member {boolean} javaStringCheckUtf8 @@ -19432,7 +19477,7 @@ * @instance */ FileOptions.prototype.javaStringCheckUtf8 = false; - + /** * FileOptions optimizeFor. * @member {google.protobuf.FileOptions.OptimizeMode} optimizeFor @@ -19440,7 +19485,7 @@ * @instance */ FileOptions.prototype.optimizeFor = 1; - + /** * FileOptions goPackage. * @member {string} goPackage @@ -19448,7 +19493,7 @@ * @instance */ FileOptions.prototype.goPackage = ""; - + /** * FileOptions ccGenericServices. * @member {boolean} ccGenericServices @@ -19456,7 +19501,7 @@ * @instance */ FileOptions.prototype.ccGenericServices = false; - + /** * FileOptions javaGenericServices. * @member {boolean} javaGenericServices @@ -19464,7 +19509,7 @@ * @instance */ FileOptions.prototype.javaGenericServices = false; - + /** * FileOptions pyGenericServices. * @member {boolean} pyGenericServices @@ -19472,7 +19517,7 @@ * @instance */ FileOptions.prototype.pyGenericServices = false; - + /** * FileOptions deprecated. * @member {boolean} deprecated @@ -19480,7 +19525,7 @@ * @instance */ FileOptions.prototype.deprecated = false; - + /** * FileOptions ccEnableArenas. * @member {boolean} ccEnableArenas @@ -19488,7 +19533,7 @@ * @instance */ FileOptions.prototype.ccEnableArenas = true; - + /** * FileOptions objcClassPrefix. * @member {string} objcClassPrefix @@ -19496,7 +19541,7 @@ * @instance */ FileOptions.prototype.objcClassPrefix = ""; - + /** * FileOptions csharpNamespace. * @member {string} csharpNamespace @@ -19504,7 +19549,7 @@ * @instance */ FileOptions.prototype.csharpNamespace = ""; - + /** * FileOptions swiftPrefix. * @member {string} swiftPrefix @@ -19512,7 +19557,7 @@ * @instance */ FileOptions.prototype.swiftPrefix = ""; - + /** * FileOptions phpClassPrefix. * @member {string} phpClassPrefix @@ -19520,7 +19565,7 @@ * @instance */ FileOptions.prototype.phpClassPrefix = ""; - + /** * FileOptions phpNamespace. * @member {string} phpNamespace @@ -19528,7 +19573,7 @@ * @instance */ FileOptions.prototype.phpNamespace = ""; - + /** * FileOptions phpMetadataNamespace. * @member {string} phpMetadataNamespace @@ -19536,7 +19581,7 @@ * @instance */ FileOptions.prototype.phpMetadataNamespace = ""; - + /** * FileOptions rubyPackage. * @member {string} rubyPackage @@ -19544,7 +19589,7 @@ * @instance */ FileOptions.prototype.rubyPackage = ""; - + /** * FileOptions features. * @member {google.protobuf.IFeatureSet|null|undefined} features @@ -19552,7 +19597,7 @@ * @instance */ FileOptions.prototype.features = null; - + /** * FileOptions uninterpretedOption. * @member {Array.} uninterpretedOption @@ -19560,7 +19605,7 @@ * @instance */ FileOptions.prototype.uninterpretedOption = $util.emptyArray; - + /** * FileOptions .google.api.resourceDefinition. * @member {Array.} .google.api.resourceDefinition @@ -19568,7 +19613,7 @@ * @instance */ FileOptions.prototype[".google.api.resourceDefinition"] = $util.emptyArray; - + /** * Creates a FileOptions message from a plain object. Also converts values to their respective internal types. * @function fromObject @@ -19664,7 +19709,7 @@ } return message; }; - + /** * Creates a plain object from a FileOptions message. Also converts values to other types if specified. * @function toObject @@ -19756,7 +19801,7 @@ } return object; }; - + /** * Converts this FileOptions to JSON. * @function toJSON @@ -19767,7 +19812,7 @@ FileOptions.prototype.toJSON = function toJSON() { return this.constructor.toObject(this, $protobuf.util.toJSONOptions); }; - + /** * Gets the default type url for FileOptions * @function getTypeUrl @@ -19782,7 +19827,7 @@ } return typeUrlPrefix + "/google.protobuf.FileOptions"; }; - + /** * OptimizeMode enum. * @name google.protobuf.FileOptions.OptimizeMode @@ -19798,12 +19843,12 @@ values[valuesById[3] = "LITE_RUNTIME"] = "LITE_RUNTIME"; return values; })(); - + return FileOptions; })(); - + protobuf.MessageOptions = (function() { - + /** * Properties of a MessageOptions. * @memberof google.protobuf @@ -19817,7 +19862,7 @@ * @property {Array.|null} [uninterpretedOption] MessageOptions uninterpretedOption * @property {google.api.IResourceDescriptor|null} [".google.api.resource"] MessageOptions .google.api.resource */ - + /** * Constructs a new MessageOptions. * @memberof google.protobuf @@ -19833,7 +19878,7 @@ if (properties[keys[i]] != null) this[keys[i]] = properties[keys[i]]; } - + /** * MessageOptions messageSetWireFormat. * @member {boolean} messageSetWireFormat @@ -19841,7 +19886,7 @@ * @instance */ MessageOptions.prototype.messageSetWireFormat = false; - + /** * MessageOptions noStandardDescriptorAccessor. * @member {boolean} noStandardDescriptorAccessor @@ -19849,7 +19894,7 @@ * @instance */ MessageOptions.prototype.noStandardDescriptorAccessor = false; - + /** * MessageOptions deprecated. * @member {boolean} deprecated @@ -19857,7 +19902,7 @@ * @instance */ MessageOptions.prototype.deprecated = false; - + /** * MessageOptions mapEntry. * @member {boolean} mapEntry @@ -19865,7 +19910,7 @@ * @instance */ MessageOptions.prototype.mapEntry = false; - + /** * MessageOptions deprecatedLegacyJsonFieldConflicts. * @member {boolean} deprecatedLegacyJsonFieldConflicts @@ -19873,7 +19918,7 @@ * @instance */ MessageOptions.prototype.deprecatedLegacyJsonFieldConflicts = false; - + /** * MessageOptions features. * @member {google.protobuf.IFeatureSet|null|undefined} features @@ -19881,7 +19926,7 @@ * @instance */ MessageOptions.prototype.features = null; - + /** * MessageOptions uninterpretedOption. * @member {Array.} uninterpretedOption @@ -19889,7 +19934,7 @@ * @instance */ MessageOptions.prototype.uninterpretedOption = $util.emptyArray; - + /** * MessageOptions .google.api.resource. * @member {google.api.IResourceDescriptor|null|undefined} .google.api.resource @@ -19897,7 +19942,7 @@ * @instance */ MessageOptions.prototype[".google.api.resource"] = null; - + /** * Creates a MessageOptions message from a plain object. Also converts values to their respective internal types. * @function fromObject @@ -19942,7 +19987,7 @@ } return message; }; - + /** * Creates a plain object from a MessageOptions message. Also converts values to other types if specified. * @function toObject @@ -19988,7 +20033,7 @@ object[".google.api.resource"] = $root.google.api.ResourceDescriptor.toObject(message[".google.api.resource"], options); return object; }; - + /** * Converts this MessageOptions to JSON. * @function toJSON @@ -19999,7 +20044,7 @@ MessageOptions.prototype.toJSON = function toJSON() { return this.constructor.toObject(this, $protobuf.util.toJSONOptions); }; - + /** * Gets the default type url for MessageOptions * @function getTypeUrl @@ -20014,12 +20059,12 @@ } return typeUrlPrefix + "/google.protobuf.MessageOptions"; }; - + return MessageOptions; })(); - + protobuf.FieldOptions = (function() { - + /** * Properties of a FieldOptions. * @memberof google.protobuf @@ -20040,7 +20085,7 @@ * @property {Array.|null} [".google.api.fieldBehavior"] FieldOptions .google.api.fieldBehavior * @property {google.api.IResourceReference|null} [".google.api.resourceReference"] FieldOptions .google.api.resourceReference */ - + /** * Constructs a new FieldOptions. * @memberof google.protobuf @@ -20059,7 +20104,7 @@ if (properties[keys[i]] != null) this[keys[i]] = properties[keys[i]]; } - + /** * FieldOptions ctype. * @member {google.protobuf.FieldOptions.CType} ctype @@ -20067,7 +20112,7 @@ * @instance */ FieldOptions.prototype.ctype = 0; - + /** * FieldOptions packed. * @member {boolean} packed @@ -20075,7 +20120,7 @@ * @instance */ FieldOptions.prototype.packed = false; - + /** * FieldOptions jstype. * @member {google.protobuf.FieldOptions.JSType} jstype @@ -20083,7 +20128,7 @@ * @instance */ FieldOptions.prototype.jstype = 0; - + /** * FieldOptions lazy. * @member {boolean} lazy @@ -20091,7 +20136,7 @@ * @instance */ FieldOptions.prototype.lazy = false; - + /** * FieldOptions unverifiedLazy. * @member {boolean} unverifiedLazy @@ -20099,7 +20144,7 @@ * @instance */ FieldOptions.prototype.unverifiedLazy = false; - + /** * FieldOptions deprecated. * @member {boolean} deprecated @@ -20107,7 +20152,7 @@ * @instance */ FieldOptions.prototype.deprecated = false; - + /** * FieldOptions weak. * @member {boolean} weak @@ -20115,7 +20160,7 @@ * @instance */ FieldOptions.prototype.weak = false; - + /** * FieldOptions debugRedact. * @member {boolean} debugRedact @@ -20123,7 +20168,7 @@ * @instance */ FieldOptions.prototype.debugRedact = false; - + /** * FieldOptions retention. * @member {google.protobuf.FieldOptions.OptionRetention} retention @@ -20131,7 +20176,7 @@ * @instance */ FieldOptions.prototype.retention = 0; - + /** * FieldOptions targets. * @member {Array.} targets @@ -20139,7 +20184,7 @@ * @instance */ FieldOptions.prototype.targets = $util.emptyArray; - + /** * FieldOptions editionDefaults. * @member {Array.} editionDefaults @@ -20147,7 +20192,7 @@ * @instance */ FieldOptions.prototype.editionDefaults = $util.emptyArray; - + /** * FieldOptions features. * @member {google.protobuf.IFeatureSet|null|undefined} features @@ -20155,7 +20200,7 @@ * @instance */ FieldOptions.prototype.features = null; - + /** * FieldOptions uninterpretedOption. * @member {Array.} uninterpretedOption @@ -20163,7 +20208,7 @@ * @instance */ FieldOptions.prototype.uninterpretedOption = $util.emptyArray; - + /** * FieldOptions .google.api.fieldBehavior. * @member {Array.} .google.api.fieldBehavior @@ -20171,7 +20216,7 @@ * @instance */ FieldOptions.prototype[".google.api.fieldBehavior"] = $util.emptyArray; - + /** * FieldOptions .google.api.resourceReference. * @member {google.api.IResourceReference|null|undefined} .google.api.resourceReference @@ -20179,7 +20224,7 @@ * @instance */ FieldOptions.prototype[".google.api.resourceReference"] = null; - + /** * Creates a FieldOptions message from a plain object. Also converts values to their respective internal types. * @function fromObject @@ -20398,7 +20443,7 @@ } return message; }; - + /** * Creates a plain object from a FieldOptions message. Also converts values to other types if specified. * @function toObject @@ -20475,7 +20520,7 @@ object[".google.api.resourceReference"] = $root.google.api.ResourceReference.toObject(message[".google.api.resourceReference"], options); return object; }; - + /** * Converts this FieldOptions to JSON. * @function toJSON @@ -20486,7 +20531,7 @@ FieldOptions.prototype.toJSON = function toJSON() { return this.constructor.toObject(this, $protobuf.util.toJSONOptions); }; - + /** * Gets the default type url for FieldOptions * @function getTypeUrl @@ -20501,7 +20546,7 @@ } return typeUrlPrefix + "/google.protobuf.FieldOptions"; }; - + /** * CType enum. * @name google.protobuf.FieldOptions.CType @@ -20517,7 +20562,7 @@ values[valuesById[2] = "STRING_PIECE"] = "STRING_PIECE"; return values; })(); - + /** * JSType enum. * @name google.protobuf.FieldOptions.JSType @@ -20533,7 +20578,7 @@ values[valuesById[2] = "JS_NUMBER"] = "JS_NUMBER"; return values; })(); - + /** * OptionRetention enum. * @name google.protobuf.FieldOptions.OptionRetention @@ -20549,7 +20594,7 @@ values[valuesById[2] = "RETENTION_SOURCE"] = "RETENTION_SOURCE"; return values; })(); - + /** * OptionTargetType enum. * @name google.protobuf.FieldOptions.OptionTargetType @@ -20579,9 +20624,9 @@ values[valuesById[9] = "TARGET_TYPE_METHOD"] = "TARGET_TYPE_METHOD"; return values; })(); - + FieldOptions.EditionDefault = (function() { - + /** * Properties of an EditionDefault. * @memberof google.protobuf.FieldOptions @@ -20589,7 +20634,7 @@ * @property {google.protobuf.Edition|null} [edition] EditionDefault edition * @property {string|null} [value] EditionDefault value */ - + /** * Constructs a new EditionDefault. * @memberof google.protobuf.FieldOptions @@ -20604,7 +20649,7 @@ if (properties[keys[i]] != null) this[keys[i]] = properties[keys[i]]; } - + /** * EditionDefault edition. * @member {google.protobuf.Edition} edition @@ -20612,7 +20657,7 @@ * @instance */ EditionDefault.prototype.edition = 0; - + /** * EditionDefault value. * @member {string} value @@ -20620,7 +20665,7 @@ * @instance */ EditionDefault.prototype.value = ""; - + /** * Creates an EditionDefault message from a plain object. Also converts values to their respective internal types. * @function fromObject @@ -20689,7 +20734,7 @@ message.value = String(object.value); return message; }; - + /** * Creates a plain object from an EditionDefault message. Also converts values to other types if specified. * @function toObject @@ -20713,7 +20758,7 @@ object.edition = options.enums === String ? $root.google.protobuf.Edition[message.edition] === undefined ? message.edition : $root.google.protobuf.Edition[message.edition] : message.edition; return object; }; - + /** * Converts this EditionDefault to JSON. * @function toJSON @@ -20724,7 +20769,7 @@ EditionDefault.prototype.toJSON = function toJSON() { return this.constructor.toObject(this, $protobuf.util.toJSONOptions); }; - + /** * Gets the default type url for EditionDefault * @function getTypeUrl @@ -20739,15 +20784,15 @@ } return typeUrlPrefix + "/google.protobuf.FieldOptions.EditionDefault"; }; - + return EditionDefault; })(); - + return FieldOptions; })(); - + protobuf.OneofOptions = (function() { - + /** * Properties of an OneofOptions. * @memberof google.protobuf @@ -20755,7 +20800,7 @@ * @property {google.protobuf.IFeatureSet|null} [features] OneofOptions features * @property {Array.|null} [uninterpretedOption] OneofOptions uninterpretedOption */ - + /** * Constructs a new OneofOptions. * @memberof google.protobuf @@ -20771,7 +20816,7 @@ if (properties[keys[i]] != null) this[keys[i]] = properties[keys[i]]; } - + /** * OneofOptions features. * @member {google.protobuf.IFeatureSet|null|undefined} features @@ -20779,7 +20824,7 @@ * @instance */ OneofOptions.prototype.features = null; - + /** * OneofOptions uninterpretedOption. * @member {Array.} uninterpretedOption @@ -20787,7 +20832,7 @@ * @instance */ OneofOptions.prototype.uninterpretedOption = $util.emptyArray; - + /** * Creates an OneofOptions message from a plain object. Also converts values to their respective internal types. * @function fromObject @@ -20817,7 +20862,7 @@ } return message; }; - + /** * Creates a plain object from an OneofOptions message. Also converts values to other types if specified. * @function toObject @@ -20844,7 +20889,7 @@ } return object; }; - + /** * Converts this OneofOptions to JSON. * @function toJSON @@ -20855,7 +20900,7 @@ OneofOptions.prototype.toJSON = function toJSON() { return this.constructor.toObject(this, $protobuf.util.toJSONOptions); }; - + /** * Gets the default type url for OneofOptions * @function getTypeUrl @@ -20870,12 +20915,12 @@ } return typeUrlPrefix + "/google.protobuf.OneofOptions"; }; - + return OneofOptions; })(); - + protobuf.EnumOptions = (function() { - + /** * Properties of an EnumOptions. * @memberof google.protobuf @@ -20886,7 +20931,7 @@ * @property {google.protobuf.IFeatureSet|null} [features] EnumOptions features * @property {Array.|null} [uninterpretedOption] EnumOptions uninterpretedOption */ - + /** * Constructs a new EnumOptions. * @memberof google.protobuf @@ -20902,7 +20947,7 @@ if (properties[keys[i]] != null) this[keys[i]] = properties[keys[i]]; } - + /** * EnumOptions allowAlias. * @member {boolean} allowAlias @@ -20910,7 +20955,7 @@ * @instance */ EnumOptions.prototype.allowAlias = false; - + /** * EnumOptions deprecated. * @member {boolean} deprecated @@ -20918,7 +20963,7 @@ * @instance */ EnumOptions.prototype.deprecated = false; - + /** * EnumOptions deprecatedLegacyJsonFieldConflicts. * @member {boolean} deprecatedLegacyJsonFieldConflicts @@ -20926,7 +20971,7 @@ * @instance */ EnumOptions.prototype.deprecatedLegacyJsonFieldConflicts = false; - + /** * EnumOptions features. * @member {google.protobuf.IFeatureSet|null|undefined} features @@ -20934,7 +20979,7 @@ * @instance */ EnumOptions.prototype.features = null; - + /** * EnumOptions uninterpretedOption. * @member {Array.} uninterpretedOption @@ -20942,7 +20987,7 @@ * @instance */ EnumOptions.prototype.uninterpretedOption = $util.emptyArray; - + /** * Creates an EnumOptions message from a plain object. Also converts values to their respective internal types. * @function fromObject @@ -20978,7 +21023,7 @@ } return message; }; - + /** * Creates a plain object from an EnumOptions message. Also converts values to other types if specified. * @function toObject @@ -21015,7 +21060,7 @@ } return object; }; - + /** * Converts this EnumOptions to JSON. * @function toJSON @@ -21026,7 +21071,7 @@ EnumOptions.prototype.toJSON = function toJSON() { return this.constructor.toObject(this, $protobuf.util.toJSONOptions); }; - + /** * Gets the default type url for EnumOptions * @function getTypeUrl @@ -21041,12 +21086,12 @@ } return typeUrlPrefix + "/google.protobuf.EnumOptions"; }; - + return EnumOptions; })(); - + protobuf.EnumValueOptions = (function() { - + /** * Properties of an EnumValueOptions. * @memberof google.protobuf @@ -21056,7 +21101,7 @@ * @property {boolean|null} [debugRedact] EnumValueOptions debugRedact * @property {Array.|null} [uninterpretedOption] EnumValueOptions uninterpretedOption */ - + /** * Constructs a new EnumValueOptions. * @memberof google.protobuf @@ -21072,7 +21117,7 @@ if (properties[keys[i]] != null) this[keys[i]] = properties[keys[i]]; } - + /** * EnumValueOptions deprecated. * @member {boolean} deprecated @@ -21080,7 +21125,7 @@ * @instance */ EnumValueOptions.prototype.deprecated = false; - + /** * EnumValueOptions features. * @member {google.protobuf.IFeatureSet|null|undefined} features @@ -21088,7 +21133,7 @@ * @instance */ EnumValueOptions.prototype.features = null; - + /** * EnumValueOptions debugRedact. * @member {boolean} debugRedact @@ -21096,7 +21141,7 @@ * @instance */ EnumValueOptions.prototype.debugRedact = false; - + /** * EnumValueOptions uninterpretedOption. * @member {Array.} uninterpretedOption @@ -21104,7 +21149,7 @@ * @instance */ EnumValueOptions.prototype.uninterpretedOption = $util.emptyArray; - + /** * Creates an EnumValueOptions message from a plain object. Also converts values to their respective internal types. * @function fromObject @@ -21138,7 +21183,7 @@ } return message; }; - + /** * Creates a plain object from an EnumValueOptions message. Also converts values to other types if specified. * @function toObject @@ -21172,7 +21217,7 @@ } return object; }; - + /** * Converts this EnumValueOptions to JSON. * @function toJSON @@ -21183,7 +21228,7 @@ EnumValueOptions.prototype.toJSON = function toJSON() { return this.constructor.toObject(this, $protobuf.util.toJSONOptions); }; - + /** * Gets the default type url for EnumValueOptions * @function getTypeUrl @@ -21198,12 +21243,12 @@ } return typeUrlPrefix + "/google.protobuf.EnumValueOptions"; }; - + return EnumValueOptions; })(); - + protobuf.ServiceOptions = (function() { - + /** * Properties of a ServiceOptions. * @memberof google.protobuf @@ -21215,7 +21260,7 @@ * @property {string|null} [".google.api.oauthScopes"] ServiceOptions .google.api.oauthScopes * @property {string|null} [".google.api.apiVersion"] ServiceOptions .google.api.apiVersion */ - + /** * Constructs a new ServiceOptions. * @memberof google.protobuf @@ -21231,7 +21276,7 @@ if (properties[keys[i]] != null) this[keys[i]] = properties[keys[i]]; } - + /** * ServiceOptions features. * @member {google.protobuf.IFeatureSet|null|undefined} features @@ -21239,7 +21284,7 @@ * @instance */ ServiceOptions.prototype.features = null; - + /** * ServiceOptions deprecated. * @member {boolean} deprecated @@ -21247,7 +21292,7 @@ * @instance */ ServiceOptions.prototype.deprecated = false; - + /** * ServiceOptions uninterpretedOption. * @member {Array.} uninterpretedOption @@ -21255,7 +21300,7 @@ * @instance */ ServiceOptions.prototype.uninterpretedOption = $util.emptyArray; - + /** * ServiceOptions .google.api.defaultHost. * @member {string} .google.api.defaultHost @@ -21263,7 +21308,7 @@ * @instance */ ServiceOptions.prototype[".google.api.defaultHost"] = ""; - + /** * ServiceOptions .google.api.oauthScopes. * @member {string} .google.api.oauthScopes @@ -21271,7 +21316,7 @@ * @instance */ ServiceOptions.prototype[".google.api.oauthScopes"] = ""; - + /** * ServiceOptions .google.api.apiVersion. * @member {string} .google.api.apiVersion @@ -21279,7 +21324,7 @@ * @instance */ ServiceOptions.prototype[".google.api.apiVersion"] = ""; - + /** * Creates a ServiceOptions message from a plain object. Also converts values to their respective internal types. * @function fromObject @@ -21317,7 +21362,7 @@ message[".google.api.apiVersion"] = String(object[".google.api.apiVersion"]); return message; }; - + /** * Creates a plain object from a ServiceOptions message. Also converts values to other types if specified. * @function toObject @@ -21357,7 +21402,7 @@ object[".google.api.apiVersion"] = message[".google.api.apiVersion"]; return object; }; - + /** * Converts this ServiceOptions to JSON. * @function toJSON @@ -21368,7 +21413,7 @@ ServiceOptions.prototype.toJSON = function toJSON() { return this.constructor.toObject(this, $protobuf.util.toJSONOptions); }; - + /** * Gets the default type url for ServiceOptions * @function getTypeUrl @@ -21383,12 +21428,12 @@ } return typeUrlPrefix + "/google.protobuf.ServiceOptions"; }; - + return ServiceOptions; })(); - + protobuf.MethodOptions = (function() { - + /** * Properties of a MethodOptions. * @memberof google.protobuf @@ -21399,9 +21444,10 @@ * @property {Array.|null} [uninterpretedOption] MethodOptions uninterpretedOption * @property {google.api.IHttpRule|null} [".google.api.http"] MethodOptions .google.api.http * @property {Array.|null} [".google.api.methodSignature"] MethodOptions .google.api.methodSignature + * @property {google.api.IRoutingRule|null} [".google.api.routing"] MethodOptions .google.api.routing * @property {google.longrunning.IOperationInfo|null} [".google.longrunning.operationInfo"] MethodOptions .google.longrunning.operationInfo */ - + /** * Constructs a new MethodOptions. * @memberof google.protobuf @@ -21418,7 +21464,7 @@ if (properties[keys[i]] != null) this[keys[i]] = properties[keys[i]]; } - + /** * MethodOptions deprecated. * @member {boolean} deprecated @@ -21426,7 +21472,7 @@ * @instance */ MethodOptions.prototype.deprecated = false; - + /** * MethodOptions idempotencyLevel. * @member {google.protobuf.MethodOptions.IdempotencyLevel} idempotencyLevel @@ -21434,7 +21480,7 @@ * @instance */ MethodOptions.prototype.idempotencyLevel = 0; - + /** * MethodOptions features. * @member {google.protobuf.IFeatureSet|null|undefined} features @@ -21442,7 +21488,7 @@ * @instance */ MethodOptions.prototype.features = null; - + /** * MethodOptions uninterpretedOption. * @member {Array.} uninterpretedOption @@ -21450,7 +21496,7 @@ * @instance */ MethodOptions.prototype.uninterpretedOption = $util.emptyArray; - + /** * MethodOptions .google.api.http. * @member {google.api.IHttpRule|null|undefined} .google.api.http @@ -21458,7 +21504,7 @@ * @instance */ MethodOptions.prototype[".google.api.http"] = null; - + /** * MethodOptions .google.api.methodSignature. * @member {Array.} .google.api.methodSignature @@ -21466,7 +21512,15 @@ * @instance */ MethodOptions.prototype[".google.api.methodSignature"] = $util.emptyArray; - + + /** + * MethodOptions .google.api.routing. + * @member {google.api.IRoutingRule|null|undefined} .google.api.routing + * @memberof google.protobuf.MethodOptions + * @instance + */ + MethodOptions.prototype[".google.api.routing"] = null; + /** * MethodOptions .google.longrunning.operationInfo. * @member {google.longrunning.IOperationInfo|null|undefined} .google.longrunning.operationInfo @@ -21474,7 +21528,7 @@ * @instance */ MethodOptions.prototype[".google.longrunning.operationInfo"] = null; - + /** * Creates a MethodOptions message from a plain object. Also converts values to their respective internal types. * @function fromObject @@ -21536,6 +21590,11 @@ for (var i = 0; i < object[".google.api.methodSignature"].length; ++i) message[".google.api.methodSignature"][i] = String(object[".google.api.methodSignature"][i]); } + if (object[".google.api.routing"] != null) { + if (typeof object[".google.api.routing"] !== "object") + throw TypeError(".google.protobuf.MethodOptions..google.api.routing: object expected"); + message[".google.api.routing"] = $root.google.api.RoutingRule.fromObject(object[".google.api.routing"]); + } if (object[".google.longrunning.operationInfo"] != null) { if (typeof object[".google.longrunning.operationInfo"] !== "object") throw TypeError(".google.protobuf.MethodOptions..google.longrunning.operationInfo: object expected"); @@ -21543,7 +21602,7 @@ } return message; }; - + /** * Creates a plain object from a MethodOptions message. Also converts values to other types if specified. * @function toObject @@ -21567,6 +21626,7 @@ object.features = null; object[".google.longrunning.operationInfo"] = null; object[".google.api.http"] = null; + object[".google.api.routing"] = null; } if (message.deprecated != null && message.hasOwnProperty("deprecated")) object.deprecated = message.deprecated; @@ -21588,9 +21648,11 @@ } if (message[".google.api.http"] != null && message.hasOwnProperty(".google.api.http")) object[".google.api.http"] = $root.google.api.HttpRule.toObject(message[".google.api.http"], options); + if (message[".google.api.routing"] != null && message.hasOwnProperty(".google.api.routing")) + object[".google.api.routing"] = $root.google.api.RoutingRule.toObject(message[".google.api.routing"], options); return object; }; - + /** * Converts this MethodOptions to JSON. * @function toJSON @@ -21601,7 +21663,7 @@ MethodOptions.prototype.toJSON = function toJSON() { return this.constructor.toObject(this, $protobuf.util.toJSONOptions); }; - + /** * Gets the default type url for MethodOptions * @function getTypeUrl @@ -21616,7 +21678,7 @@ } return typeUrlPrefix + "/google.protobuf.MethodOptions"; }; - + /** * IdempotencyLevel enum. * @name google.protobuf.MethodOptions.IdempotencyLevel @@ -21632,12 +21694,12 @@ values[valuesById[2] = "IDEMPOTENT"] = "IDEMPOTENT"; return values; })(); - + return MethodOptions; })(); - + protobuf.UninterpretedOption = (function() { - + /** * Properties of an UninterpretedOption. * @memberof google.protobuf @@ -21650,7 +21712,7 @@ * @property {Uint8Array|null} [stringValue] UninterpretedOption stringValue * @property {string|null} [aggregateValue] UninterpretedOption aggregateValue */ - + /** * Constructs a new UninterpretedOption. * @memberof google.protobuf @@ -21666,7 +21728,7 @@ if (properties[keys[i]] != null) this[keys[i]] = properties[keys[i]]; } - + /** * UninterpretedOption name. * @member {Array.} name @@ -21674,7 +21736,7 @@ * @instance */ UninterpretedOption.prototype.name = $util.emptyArray; - + /** * UninterpretedOption identifierValue. * @member {string} identifierValue @@ -21682,7 +21744,7 @@ * @instance */ UninterpretedOption.prototype.identifierValue = ""; - + /** * UninterpretedOption positiveIntValue. * @member {number|string} positiveIntValue @@ -21690,7 +21752,7 @@ * @instance */ UninterpretedOption.prototype.positiveIntValue = $util.Long ? $util.Long.fromBits(0,0,true) : 0; - + /** * UninterpretedOption negativeIntValue. * @member {number|string} negativeIntValue @@ -21698,7 +21760,7 @@ * @instance */ UninterpretedOption.prototype.negativeIntValue = $util.Long ? $util.Long.fromBits(0,0,false) : 0; - + /** * UninterpretedOption doubleValue. * @member {number} doubleValue @@ -21706,7 +21768,7 @@ * @instance */ UninterpretedOption.prototype.doubleValue = 0; - + /** * UninterpretedOption stringValue. * @member {Uint8Array} stringValue @@ -21714,7 +21776,7 @@ * @instance */ UninterpretedOption.prototype.stringValue = $util.newBuffer([]); - + /** * UninterpretedOption aggregateValue. * @member {string} aggregateValue @@ -21722,7 +21784,7 @@ * @instance */ UninterpretedOption.prototype.aggregateValue = ""; - + /** * Creates an UninterpretedOption message from a plain object. Also converts values to their respective internal types. * @function fromObject @@ -21776,7 +21838,7 @@ message.aggregateValue = String(object.aggregateValue); return message; }; - + /** * Creates a plain object from an UninterpretedOption message. Also converts values to other types if specified. * @function toObject @@ -21839,7 +21901,7 @@ object.aggregateValue = message.aggregateValue; return object; }; - + /** * Converts this UninterpretedOption to JSON. * @function toJSON @@ -21850,7 +21912,7 @@ UninterpretedOption.prototype.toJSON = function toJSON() { return this.constructor.toObject(this, $protobuf.util.toJSONOptions); }; - + /** * Gets the default type url for UninterpretedOption * @function getTypeUrl @@ -21865,9 +21927,9 @@ } return typeUrlPrefix + "/google.protobuf.UninterpretedOption"; }; - + UninterpretedOption.NamePart = (function() { - + /** * Properties of a NamePart. * @memberof google.protobuf.UninterpretedOption @@ -21875,7 +21937,7 @@ * @property {string} namePart NamePart namePart * @property {boolean} isExtension NamePart isExtension */ - + /** * Constructs a new NamePart. * @memberof google.protobuf.UninterpretedOption @@ -21890,7 +21952,7 @@ if (properties[keys[i]] != null) this[keys[i]] = properties[keys[i]]; } - + /** * NamePart namePart. * @member {string} namePart @@ -21898,7 +21960,7 @@ * @instance */ NamePart.prototype.namePart = ""; - + /** * NamePart isExtension. * @member {boolean} isExtension @@ -21906,7 +21968,7 @@ * @instance */ NamePart.prototype.isExtension = false; - + /** * Creates a NamePart message from a plain object. Also converts values to their respective internal types. * @function fromObject @@ -21925,7 +21987,7 @@ message.isExtension = Boolean(object.isExtension); return message; }; - + /** * Creates a plain object from a NamePart message. Also converts values to other types if specified. * @function toObject @@ -21949,7 +22011,7 @@ object.isExtension = message.isExtension; return object; }; - + /** * Converts this NamePart to JSON. * @function toJSON @@ -21960,7 +22022,7 @@ NamePart.prototype.toJSON = function toJSON() { return this.constructor.toObject(this, $protobuf.util.toJSONOptions); }; - + /** * Gets the default type url for NamePart * @function getTypeUrl @@ -21975,15 +22037,15 @@ } return typeUrlPrefix + "/google.protobuf.UninterpretedOption.NamePart"; }; - + return NamePart; })(); - + return UninterpretedOption; })(); - + protobuf.FeatureSet = (function() { - + /** * Properties of a FeatureSet. * @memberof google.protobuf @@ -21995,7 +22057,7 @@ * @property {google.protobuf.FeatureSet.MessageEncoding|null} [messageEncoding] FeatureSet messageEncoding * @property {google.protobuf.FeatureSet.JsonFormat|null} [jsonFormat] FeatureSet jsonFormat */ - + /** * Constructs a new FeatureSet. * @memberof google.protobuf @@ -22010,7 +22072,7 @@ if (properties[keys[i]] != null) this[keys[i]] = properties[keys[i]]; } - + /** * FeatureSet fieldPresence. * @member {google.protobuf.FeatureSet.FieldPresence} fieldPresence @@ -22018,7 +22080,7 @@ * @instance */ FeatureSet.prototype.fieldPresence = 0; - + /** * FeatureSet enumType. * @member {google.protobuf.FeatureSet.EnumType} enumType @@ -22026,7 +22088,7 @@ * @instance */ FeatureSet.prototype.enumType = 0; - + /** * FeatureSet repeatedFieldEncoding. * @member {google.protobuf.FeatureSet.RepeatedFieldEncoding} repeatedFieldEncoding @@ -22034,7 +22096,7 @@ * @instance */ FeatureSet.prototype.repeatedFieldEncoding = 0; - + /** * FeatureSet utf8Validation. * @member {google.protobuf.FeatureSet.Utf8Validation} utf8Validation @@ -22042,7 +22104,7 @@ * @instance */ FeatureSet.prototype.utf8Validation = 0; - + /** * FeatureSet messageEncoding. * @member {google.protobuf.FeatureSet.MessageEncoding} messageEncoding @@ -22050,7 +22112,7 @@ * @instance */ FeatureSet.prototype.messageEncoding = 0; - + /** * FeatureSet jsonFormat. * @member {google.protobuf.FeatureSet.JsonFormat} jsonFormat @@ -22058,7 +22120,7 @@ * @instance */ FeatureSet.prototype.jsonFormat = 0; - + /** * Creates a FeatureSet message from a plain object. Also converts values to their respective internal types. * @function fromObject @@ -22197,7 +22259,7 @@ } return message; }; - + /** * Creates a plain object from a FeatureSet message. Also converts values to other types if specified. * @function toObject @@ -22233,7 +22295,7 @@ object.jsonFormat = options.enums === String ? $root.google.protobuf.FeatureSet.JsonFormat[message.jsonFormat] === undefined ? message.jsonFormat : $root.google.protobuf.FeatureSet.JsonFormat[message.jsonFormat] : message.jsonFormat; return object; }; - + /** * Converts this FeatureSet to JSON. * @function toJSON @@ -22244,7 +22306,7 @@ FeatureSet.prototype.toJSON = function toJSON() { return this.constructor.toObject(this, $protobuf.util.toJSONOptions); }; - + /** * Gets the default type url for FeatureSet * @function getTypeUrl @@ -22259,7 +22321,7 @@ } return typeUrlPrefix + "/google.protobuf.FeatureSet"; }; - + /** * FieldPresence enum. * @name google.protobuf.FeatureSet.FieldPresence @@ -22277,7 +22339,7 @@ values[valuesById[3] = "LEGACY_REQUIRED"] = "LEGACY_REQUIRED"; return values; })(); - + /** * EnumType enum. * @name google.protobuf.FeatureSet.EnumType @@ -22293,7 +22355,7 @@ values[valuesById[2] = "CLOSED"] = "CLOSED"; return values; })(); - + /** * RepeatedFieldEncoding enum. * @name google.protobuf.FeatureSet.RepeatedFieldEncoding @@ -22309,7 +22371,7 @@ values[valuesById[2] = "EXPANDED"] = "EXPANDED"; return values; })(); - + /** * Utf8Validation enum. * @name google.protobuf.FeatureSet.Utf8Validation @@ -22325,7 +22387,7 @@ values[valuesById[3] = "NONE"] = "NONE"; return values; })(); - + /** * MessageEncoding enum. * @name google.protobuf.FeatureSet.MessageEncoding @@ -22341,7 +22403,7 @@ values[valuesById[2] = "DELIMITED"] = "DELIMITED"; return values; })(); - + /** * JsonFormat enum. * @name google.protobuf.FeatureSet.JsonFormat @@ -22357,12 +22419,12 @@ values[valuesById[2] = "LEGACY_BEST_EFFORT"] = "LEGACY_BEST_EFFORT"; return values; })(); - + return FeatureSet; })(); - + protobuf.FeatureSetDefaults = (function() { - + /** * Properties of a FeatureSetDefaults. * @memberof google.protobuf @@ -22371,7 +22433,7 @@ * @property {google.protobuf.Edition|null} [minimumEdition] FeatureSetDefaults minimumEdition * @property {google.protobuf.Edition|null} [maximumEdition] FeatureSetDefaults maximumEdition */ - + /** * Constructs a new FeatureSetDefaults. * @memberof google.protobuf @@ -22387,7 +22449,7 @@ if (properties[keys[i]] != null) this[keys[i]] = properties[keys[i]]; } - + /** * FeatureSetDefaults defaults. * @member {Array.} defaults @@ -22395,7 +22457,7 @@ * @instance */ FeatureSetDefaults.prototype.defaults = $util.emptyArray; - + /** * FeatureSetDefaults minimumEdition. * @member {google.protobuf.Edition} minimumEdition @@ -22403,7 +22465,7 @@ * @instance */ FeatureSetDefaults.prototype.minimumEdition = 0; - + /** * FeatureSetDefaults maximumEdition. * @member {google.protobuf.Edition} maximumEdition @@ -22411,7 +22473,7 @@ * @instance */ FeatureSetDefaults.prototype.maximumEdition = 0; - + /** * Creates a FeatureSetDefaults message from a plain object. Also converts values to their respective internal types. * @function fromObject @@ -22540,7 +22602,7 @@ } return message; }; - + /** * Creates a plain object from a FeatureSetDefaults message. Also converts values to other types if specified. * @function toObject @@ -22571,7 +22633,7 @@ object.maximumEdition = options.enums === String ? $root.google.protobuf.Edition[message.maximumEdition] === undefined ? message.maximumEdition : $root.google.protobuf.Edition[message.maximumEdition] : message.maximumEdition; return object; }; - + /** * Converts this FeatureSetDefaults to JSON. * @function toJSON @@ -22582,7 +22644,7 @@ FeatureSetDefaults.prototype.toJSON = function toJSON() { return this.constructor.toObject(this, $protobuf.util.toJSONOptions); }; - + /** * Gets the default type url for FeatureSetDefaults * @function getTypeUrl @@ -22597,9 +22659,9 @@ } return typeUrlPrefix + "/google.protobuf.FeatureSetDefaults"; }; - + FeatureSetDefaults.FeatureSetEditionDefault = (function() { - + /** * Properties of a FeatureSetEditionDefault. * @memberof google.protobuf.FeatureSetDefaults @@ -22607,7 +22669,7 @@ * @property {google.protobuf.Edition|null} [edition] FeatureSetEditionDefault edition * @property {google.protobuf.IFeatureSet|null} [features] FeatureSetEditionDefault features */ - + /** * Constructs a new FeatureSetEditionDefault. * @memberof google.protobuf.FeatureSetDefaults @@ -22622,7 +22684,7 @@ if (properties[keys[i]] != null) this[keys[i]] = properties[keys[i]]; } - + /** * FeatureSetEditionDefault edition. * @member {google.protobuf.Edition} edition @@ -22630,7 +22692,7 @@ * @instance */ FeatureSetEditionDefault.prototype.edition = 0; - + /** * FeatureSetEditionDefault features. * @member {google.protobuf.IFeatureSet|null|undefined} features @@ -22638,7 +22700,7 @@ * @instance */ FeatureSetEditionDefault.prototype.features = null; - + /** * Creates a FeatureSetEditionDefault message from a plain object. Also converts values to their respective internal types. * @function fromObject @@ -22710,7 +22772,7 @@ } return message; }; - + /** * Creates a plain object from a FeatureSetEditionDefault message. Also converts values to other types if specified. * @function toObject @@ -22734,7 +22796,7 @@ object.edition = options.enums === String ? $root.google.protobuf.Edition[message.edition] === undefined ? message.edition : $root.google.protobuf.Edition[message.edition] : message.edition; return object; }; - + /** * Converts this FeatureSetEditionDefault to JSON. * @function toJSON @@ -22745,7 +22807,7 @@ FeatureSetEditionDefault.prototype.toJSON = function toJSON() { return this.constructor.toObject(this, $protobuf.util.toJSONOptions); }; - + /** * Gets the default type url for FeatureSetEditionDefault * @function getTypeUrl @@ -22760,22 +22822,22 @@ } return typeUrlPrefix + "/google.protobuf.FeatureSetDefaults.FeatureSetEditionDefault"; }; - + return FeatureSetEditionDefault; })(); - + return FeatureSetDefaults; })(); - + protobuf.SourceCodeInfo = (function() { - + /** * Properties of a SourceCodeInfo. * @memberof google.protobuf * @interface ISourceCodeInfo * @property {Array.|null} [location] SourceCodeInfo location */ - + /** * Constructs a new SourceCodeInfo. * @memberof google.protobuf @@ -22791,7 +22853,7 @@ if (properties[keys[i]] != null) this[keys[i]] = properties[keys[i]]; } - + /** * SourceCodeInfo location. * @member {Array.} location @@ -22799,7 +22861,7 @@ * @instance */ SourceCodeInfo.prototype.location = $util.emptyArray; - + /** * Creates a SourceCodeInfo message from a plain object. Also converts values to their respective internal types. * @function fromObject @@ -22824,7 +22886,7 @@ } return message; }; - + /** * Creates a plain object from a SourceCodeInfo message. Also converts values to other types if specified. * @function toObject @@ -22847,7 +22909,7 @@ } return object; }; - + /** * Converts this SourceCodeInfo to JSON. * @function toJSON @@ -22858,7 +22920,7 @@ SourceCodeInfo.prototype.toJSON = function toJSON() { return this.constructor.toObject(this, $protobuf.util.toJSONOptions); }; - + /** * Gets the default type url for SourceCodeInfo * @function getTypeUrl @@ -22873,9 +22935,9 @@ } return typeUrlPrefix + "/google.protobuf.SourceCodeInfo"; }; - + SourceCodeInfo.Location = (function() { - + /** * Properties of a Location. * @memberof google.protobuf.SourceCodeInfo @@ -22886,7 +22948,7 @@ * @property {string|null} [trailingComments] Location trailingComments * @property {Array.|null} [leadingDetachedComments] Location leadingDetachedComments */ - + /** * Constructs a new Location. * @memberof google.protobuf.SourceCodeInfo @@ -22904,7 +22966,7 @@ if (properties[keys[i]] != null) this[keys[i]] = properties[keys[i]]; } - + /** * Location path. * @member {Array.} path @@ -22912,7 +22974,7 @@ * @instance */ Location.prototype.path = $util.emptyArray; - + /** * Location span. * @member {Array.} span @@ -22920,7 +22982,7 @@ * @instance */ Location.prototype.span = $util.emptyArray; - + /** * Location leadingComments. * @member {string} leadingComments @@ -22928,7 +22990,7 @@ * @instance */ Location.prototype.leadingComments = ""; - + /** * Location trailingComments. * @member {string} trailingComments @@ -22936,7 +22998,7 @@ * @instance */ Location.prototype.trailingComments = ""; - + /** * Location leadingDetachedComments. * @member {Array.} leadingDetachedComments @@ -22944,7 +23006,7 @@ * @instance */ Location.prototype.leadingDetachedComments = $util.emptyArray; - + /** * Creates a Location message from a plain object. Also converts values to their respective internal types. * @function fromObject @@ -22984,7 +23046,7 @@ } return message; }; - + /** * Creates a plain object from a Location message. Also converts values to other types if specified. * @function toObject @@ -23028,7 +23090,7 @@ } return object; }; - + /** * Converts this Location to JSON. * @function toJSON @@ -23039,7 +23101,7 @@ Location.prototype.toJSON = function toJSON() { return this.constructor.toObject(this, $protobuf.util.toJSONOptions); }; - + /** * Gets the default type url for Location * @function getTypeUrl @@ -23054,22 +23116,22 @@ } return typeUrlPrefix + "/google.protobuf.SourceCodeInfo.Location"; }; - + return Location; })(); - + return SourceCodeInfo; })(); - + protobuf.GeneratedCodeInfo = (function() { - + /** * Properties of a GeneratedCodeInfo. * @memberof google.protobuf * @interface IGeneratedCodeInfo * @property {Array.|null} [annotation] GeneratedCodeInfo annotation */ - + /** * Constructs a new GeneratedCodeInfo. * @memberof google.protobuf @@ -23085,7 +23147,7 @@ if (properties[keys[i]] != null) this[keys[i]] = properties[keys[i]]; } - + /** * GeneratedCodeInfo annotation. * @member {Array.} annotation @@ -23093,7 +23155,7 @@ * @instance */ GeneratedCodeInfo.prototype.annotation = $util.emptyArray; - + /** * Creates a GeneratedCodeInfo message from a plain object. Also converts values to their respective internal types. * @function fromObject @@ -23118,7 +23180,7 @@ } return message; }; - + /** * Creates a plain object from a GeneratedCodeInfo message. Also converts values to other types if specified. * @function toObject @@ -23141,7 +23203,7 @@ } return object; }; - + /** * Converts this GeneratedCodeInfo to JSON. * @function toJSON @@ -23152,7 +23214,7 @@ GeneratedCodeInfo.prototype.toJSON = function toJSON() { return this.constructor.toObject(this, $protobuf.util.toJSONOptions); }; - + /** * Gets the default type url for GeneratedCodeInfo * @function getTypeUrl @@ -23167,9 +23229,9 @@ } return typeUrlPrefix + "/google.protobuf.GeneratedCodeInfo"; }; - + GeneratedCodeInfo.Annotation = (function() { - + /** * Properties of an Annotation. * @memberof google.protobuf.GeneratedCodeInfo @@ -23180,7 +23242,7 @@ * @property {number|null} [end] Annotation end * @property {google.protobuf.GeneratedCodeInfo.Annotation.Semantic|null} [semantic] Annotation semantic */ - + /** * Constructs a new Annotation. * @memberof google.protobuf.GeneratedCodeInfo @@ -23196,7 +23258,7 @@ if (properties[keys[i]] != null) this[keys[i]] = properties[keys[i]]; } - + /** * Annotation path. * @member {Array.} path @@ -23204,7 +23266,7 @@ * @instance */ Annotation.prototype.path = $util.emptyArray; - + /** * Annotation sourceFile. * @member {string} sourceFile @@ -23212,7 +23274,7 @@ * @instance */ Annotation.prototype.sourceFile = ""; - + /** * Annotation begin. * @member {number} begin @@ -23220,7 +23282,7 @@ * @instance */ Annotation.prototype.begin = 0; - + /** * Annotation end. * @member {number} end @@ -23228,7 +23290,7 @@ * @instance */ Annotation.prototype.end = 0; - + /** * Annotation semantic. * @member {google.protobuf.GeneratedCodeInfo.Annotation.Semantic} semantic @@ -23236,7 +23298,7 @@ * @instance */ Annotation.prototype.semantic = 0; - + /** * Creates an Annotation message from a plain object. Also converts values to their respective internal types. * @function fromObject @@ -23284,7 +23346,7 @@ } return message; }; - + /** * Creates a plain object from an Annotation message. Also converts values to other types if specified. * @function toObject @@ -23321,7 +23383,7 @@ object.semantic = options.enums === String ? $root.google.protobuf.GeneratedCodeInfo.Annotation.Semantic[message.semantic] === undefined ? message.semantic : $root.google.protobuf.GeneratedCodeInfo.Annotation.Semantic[message.semantic] : message.semantic; return object; }; - + /** * Converts this Annotation to JSON. * @function toJSON @@ -23332,7 +23394,7 @@ Annotation.prototype.toJSON = function toJSON() { return this.constructor.toObject(this, $protobuf.util.toJSONOptions); }; - + /** * Gets the default type url for Annotation * @function getTypeUrl @@ -23347,7 +23409,7 @@ } return typeUrlPrefix + "/google.protobuf.GeneratedCodeInfo.Annotation"; }; - + /** * Semantic enum. * @name google.protobuf.GeneratedCodeInfo.Annotation.Semantic @@ -23363,22 +23425,22 @@ values[valuesById[2] = "ALIAS"] = "ALIAS"; return values; })(); - + return Annotation; })(); - + return GeneratedCodeInfo; })(); - + protobuf.Struct = (function() { - + /** * Properties of a Struct. * @memberof google.protobuf * @interface IStruct * @property {Object.|null} [fields] Struct fields */ - + /** * Constructs a new Struct. * @memberof google.protobuf @@ -23394,7 +23456,7 @@ if (properties[keys[i]] != null) this[keys[i]] = properties[keys[i]]; } - + /** * Struct fields. * @member {Object.} fields @@ -23402,7 +23464,7 @@ * @instance */ Struct.prototype.fields = $util.emptyObject; - + /** * Creates a Struct message from a plain object. Also converts values to their respective internal types. * @function fromObject @@ -23427,7 +23489,7 @@ } return message; }; - + /** * Creates a plain object from a Struct message. Also converts values to other types if specified. * @function toObject @@ -23451,7 +23513,7 @@ } return object; }; - + /** * Converts this Struct to JSON. * @function toJSON @@ -23462,7 +23524,7 @@ Struct.prototype.toJSON = function toJSON() { return this.constructor.toObject(this, $protobuf.util.toJSONOptions); }; - + /** * Gets the default type url for Struct * @function getTypeUrl @@ -23477,12 +23539,12 @@ } return typeUrlPrefix + "/google.protobuf.Struct"; }; - + return Struct; })(); - + protobuf.Value = (function() { - + /** * Properties of a Value. * @memberof google.protobuf @@ -23494,7 +23556,7 @@ * @property {google.protobuf.IStruct|null} [structValue] Value structValue * @property {google.protobuf.IListValue|null} [listValue] Value listValue */ - + /** * Constructs a new Value. * @memberof google.protobuf @@ -23509,7 +23571,7 @@ if (properties[keys[i]] != null) this[keys[i]] = properties[keys[i]]; } - + /** * Value nullValue. * @member {google.protobuf.NullValue|null|undefined} nullValue @@ -23517,7 +23579,7 @@ * @instance */ Value.prototype.nullValue = null; - + /** * Value numberValue. * @member {number|null|undefined} numberValue @@ -23525,7 +23587,7 @@ * @instance */ Value.prototype.numberValue = null; - + /** * Value stringValue. * @member {string|null|undefined} stringValue @@ -23533,7 +23595,7 @@ * @instance */ Value.prototype.stringValue = null; - + /** * Value boolValue. * @member {boolean|null|undefined} boolValue @@ -23541,7 +23603,7 @@ * @instance */ Value.prototype.boolValue = null; - + /** * Value structValue. * @member {google.protobuf.IStruct|null|undefined} structValue @@ -23549,7 +23611,7 @@ * @instance */ Value.prototype.structValue = null; - + /** * Value listValue. * @member {google.protobuf.IListValue|null|undefined} listValue @@ -23557,10 +23619,10 @@ * @instance */ Value.prototype.listValue = null; - + // OneOf field names bound to virtual getters and setters var $oneOfFields; - + /** * Value kind. * @member {"nullValue"|"numberValue"|"stringValue"|"boolValue"|"structValue"|"listValue"|undefined} kind @@ -23571,7 +23633,7 @@ get: $util.oneOfGetter($oneOfFields = ["nullValue", "numberValue", "stringValue", "boolValue", "structValue", "listValue"]), set: $util.oneOfSetter($oneOfFields) }); - + /** * Creates a Value message from a plain object. Also converts values to their respective internal types. * @function fromObject @@ -23614,7 +23676,7 @@ } return message; }; - + /** * Creates a plain object from a Value message. Also converts values to other types if specified. * @function toObject @@ -23660,7 +23722,7 @@ } return object; }; - + /** * Converts this Value to JSON. * @function toJSON @@ -23671,7 +23733,7 @@ Value.prototype.toJSON = function toJSON() { return this.constructor.toObject(this, $protobuf.util.toJSONOptions); }; - + /** * Gets the default type url for Value * @function getTypeUrl @@ -23686,10 +23748,10 @@ } return typeUrlPrefix + "/google.protobuf.Value"; }; - + return Value; })(); - + /** * NullValue enum. * @name google.protobuf.NullValue @@ -23701,16 +23763,16 @@ values[valuesById[0] = "NULL_VALUE"] = "NULL_VALUE"; return values; })(); - + protobuf.ListValue = (function() { - + /** * Properties of a ListValue. * @memberof google.protobuf * @interface IListValue * @property {Array.|null} [values] ListValue values */ - + /** * Constructs a new ListValue. * @memberof google.protobuf @@ -23726,7 +23788,7 @@ if (properties[keys[i]] != null) this[keys[i]] = properties[keys[i]]; } - + /** * ListValue values. * @member {Array.} values @@ -23734,7 +23796,7 @@ * @instance */ ListValue.prototype.values = $util.emptyArray; - + /** * Creates a ListValue message from a plain object. Also converts values to their respective internal types. * @function fromObject @@ -23759,7 +23821,7 @@ } return message; }; - + /** * Creates a plain object from a ListValue message. Also converts values to other types if specified. * @function toObject @@ -23782,7 +23844,7 @@ } return object; }; - + /** * Converts this ListValue to JSON. * @function toJSON @@ -23793,7 +23855,7 @@ ListValue.prototype.toJSON = function toJSON() { return this.constructor.toObject(this, $protobuf.util.toJSONOptions); }; - + /** * Gets the default type url for ListValue * @function getTypeUrl @@ -23808,12 +23870,12 @@ } return typeUrlPrefix + "/google.protobuf.ListValue"; }; - + return ListValue; })(); - + protobuf.Timestamp = (function() { - + /** * Properties of a Timestamp. * @memberof google.protobuf @@ -23821,7 +23883,7 @@ * @property {number|string|null} [seconds] Timestamp seconds * @property {number|null} [nanos] Timestamp nanos */ - + /** * Constructs a new Timestamp. * @memberof google.protobuf @@ -23836,7 +23898,7 @@ if (properties[keys[i]] != null) this[keys[i]] = properties[keys[i]]; } - + /** * Timestamp seconds. * @member {number|string} seconds @@ -23844,103 +23906,225 @@ * @instance */ Timestamp.prototype.seconds = $util.Long ? $util.Long.fromBits(0,0,false) : 0; - + /** * Timestamp nanos. * @member {number} nanos * @memberof google.protobuf.Timestamp * @instance */ - Timestamp.prototype.nanos = 0; - + Timestamp.prototype.nanos = 0; + + /** + * Creates a Timestamp message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.protobuf.Timestamp + * @static + * @param {Object.} object Plain object + * @returns {google.protobuf.Timestamp} Timestamp + */ + Timestamp.fromObject = function fromObject(object) { + if (object instanceof $root.google.protobuf.Timestamp) + return object; + var message = new $root.google.protobuf.Timestamp(); + if (object.seconds != null) + if ($util.Long) + (message.seconds = $util.Long.fromValue(object.seconds)).unsigned = false; + else if (typeof object.seconds === "string") + message.seconds = parseInt(object.seconds, 10); + else if (typeof object.seconds === "number") + message.seconds = object.seconds; + else if (typeof object.seconds === "object") + message.seconds = new $util.LongBits(object.seconds.low >>> 0, object.seconds.high >>> 0).toNumber(); + if (object.nanos != null) + message.nanos = object.nanos | 0; + return message; + }; + + /** + * Creates a plain object from a Timestamp message. Also converts values to other types if specified. + * @function toObject + * @memberof google.protobuf.Timestamp + * @static + * @param {google.protobuf.Timestamp} message Timestamp + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + Timestamp.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.defaults) { + if ($util.Long) { + var long = new $util.Long(0, 0, false); + object.seconds = options.longs === String ? long.toString() : options.longs === Number ? long.toNumber() : long; + } else + object.seconds = options.longs === String ? "0" : 0; + object.nanos = 0; + } + if (message.seconds != null && message.hasOwnProperty("seconds")) + if (typeof message.seconds === "number") + object.seconds = options.longs === String ? String(message.seconds) : message.seconds; + else + object.seconds = options.longs === String ? $util.Long.prototype.toString.call(message.seconds) : options.longs === Number ? new $util.LongBits(message.seconds.low >>> 0, message.seconds.high >>> 0).toNumber() : message.seconds; + if (message.nanos != null && message.hasOwnProperty("nanos")) + object.nanos = message.nanos; + return object; + }; + + /** + * Converts this Timestamp to JSON. + * @function toJSON + * @memberof google.protobuf.Timestamp + * @instance + * @returns {Object.} JSON object + */ + Timestamp.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + + /** + * Gets the default type url for Timestamp + * @function getTypeUrl + * @memberof google.protobuf.Timestamp + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + Timestamp.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.protobuf.Timestamp"; + }; + + return Timestamp; + })(); + + protobuf.Any = (function() { + + /** + * Properties of an Any. + * @memberof google.protobuf + * @interface IAny + * @property {string|null} [type_url] Any type_url + * @property {Uint8Array|null} [value] Any value + */ + + /** + * Constructs a new Any. + * @memberof google.protobuf + * @classdesc Represents an Any. + * @implements IAny + * @constructor + * @param {google.protobuf.IAny=} [properties] Properties to set + */ + function Any(properties) { + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } + + /** + * Any type_url. + * @member {string} type_url + * @memberof google.protobuf.Any + * @instance + */ + Any.prototype.type_url = ""; + + /** + * Any value. + * @member {Uint8Array} value + * @memberof google.protobuf.Any + * @instance + */ + Any.prototype.value = $util.newBuffer([]); + /** - * Creates a Timestamp message from a plain object. Also converts values to their respective internal types. + * Creates an Any message from a plain object. Also converts values to their respective internal types. * @function fromObject - * @memberof google.protobuf.Timestamp + * @memberof google.protobuf.Any * @static * @param {Object.} object Plain object - * @returns {google.protobuf.Timestamp} Timestamp + * @returns {google.protobuf.Any} Any */ - Timestamp.fromObject = function fromObject(object) { - if (object instanceof $root.google.protobuf.Timestamp) + Any.fromObject = function fromObject(object) { + if (object instanceof $root.google.protobuf.Any) return object; - var message = new $root.google.protobuf.Timestamp(); - if (object.seconds != null) - if ($util.Long) - (message.seconds = $util.Long.fromValue(object.seconds)).unsigned = false; - else if (typeof object.seconds === "string") - message.seconds = parseInt(object.seconds, 10); - else if (typeof object.seconds === "number") - message.seconds = object.seconds; - else if (typeof object.seconds === "object") - message.seconds = new $util.LongBits(object.seconds.low >>> 0, object.seconds.high >>> 0).toNumber(); - if (object.nanos != null) - message.nanos = object.nanos | 0; + var message = new $root.google.protobuf.Any(); + if (object.type_url != null) + message.type_url = String(object.type_url); + if (object.value != null) + if (typeof object.value === "string") + $util.base64.decode(object.value, message.value = $util.newBuffer($util.base64.length(object.value)), 0); + else if (object.value.length >= 0) + message.value = object.value; return message; }; - + /** - * Creates a plain object from a Timestamp message. Also converts values to other types if specified. + * Creates a plain object from an Any message. Also converts values to other types if specified. * @function toObject - * @memberof google.protobuf.Timestamp + * @memberof google.protobuf.Any * @static - * @param {google.protobuf.Timestamp} message Timestamp + * @param {google.protobuf.Any} message Any * @param {$protobuf.IConversionOptions} [options] Conversion options * @returns {Object.} Plain object */ - Timestamp.toObject = function toObject(message, options) { + Any.toObject = function toObject(message, options) { if (!options) options = {}; var object = {}; if (options.defaults) { - if ($util.Long) { - var long = new $util.Long(0, 0, false); - object.seconds = options.longs === String ? long.toString() : options.longs === Number ? long.toNumber() : long; - } else - object.seconds = options.longs === String ? "0" : 0; - object.nanos = 0; + object.type_url = ""; + if (options.bytes === String) + object.value = ""; + else { + object.value = []; + if (options.bytes !== Array) + object.value = $util.newBuffer(object.value); + } } - if (message.seconds != null && message.hasOwnProperty("seconds")) - if (typeof message.seconds === "number") - object.seconds = options.longs === String ? String(message.seconds) : message.seconds; - else - object.seconds = options.longs === String ? $util.Long.prototype.toString.call(message.seconds) : options.longs === Number ? new $util.LongBits(message.seconds.low >>> 0, message.seconds.high >>> 0).toNumber() : message.seconds; - if (message.nanos != null && message.hasOwnProperty("nanos")) - object.nanos = message.nanos; + if (message.type_url != null && message.hasOwnProperty("type_url")) + object.type_url = message.type_url; + if (message.value != null && message.hasOwnProperty("value")) + object.value = options.bytes === String ? $util.base64.encode(message.value, 0, message.value.length) : options.bytes === Array ? Array.prototype.slice.call(message.value) : message.value; return object; }; - + /** - * Converts this Timestamp to JSON. + * Converts this Any to JSON. * @function toJSON - * @memberof google.protobuf.Timestamp + * @memberof google.protobuf.Any * @instance * @returns {Object.} JSON object */ - Timestamp.prototype.toJSON = function toJSON() { + Any.prototype.toJSON = function toJSON() { return this.constructor.toObject(this, $protobuf.util.toJSONOptions); }; - + /** - * Gets the default type url for Timestamp + * Gets the default type url for Any * @function getTypeUrl - * @memberof google.protobuf.Timestamp + * @memberof google.protobuf.Any * @static * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") * @returns {string} The default type url */ - Timestamp.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + Any.getTypeUrl = function getTypeUrl(typeUrlPrefix) { if (typeUrlPrefix === undefined) { typeUrlPrefix = "type.googleapis.com"; } - return typeUrlPrefix + "/google.protobuf.Timestamp"; + return typeUrlPrefix + "/google.protobuf.Any"; }; - - return Timestamp; + + return Any; })(); - + protobuf.Duration = (function() { - + /** * Properties of a Duration. * @memberof google.protobuf @@ -23948,7 +24132,7 @@ * @property {number|string|null} [seconds] Duration seconds * @property {number|null} [nanos] Duration nanos */ - + /** * Constructs a new Duration. * @memberof google.protobuf @@ -23963,7 +24147,7 @@ if (properties[keys[i]] != null) this[keys[i]] = properties[keys[i]]; } - + /** * Duration seconds. * @member {number|string} seconds @@ -23971,7 +24155,7 @@ * @instance */ Duration.prototype.seconds = $util.Long ? $util.Long.fromBits(0,0,false) : 0; - + /** * Duration nanos. * @member {number} nanos @@ -23979,7 +24163,7 @@ * @instance */ Duration.prototype.nanos = 0; - + /** * Creates a Duration message from a plain object. Also converts values to their respective internal types. * @function fromObject @@ -24005,7 +24189,7 @@ message.nanos = object.nanos | 0; return message; }; - + /** * Creates a plain object from a Duration message. Also converts values to other types if specified. * @function toObject @@ -24036,7 +24220,7 @@ object.nanos = message.nanos; return object; }; - + /** * Converts this Duration to JSON. * @function toJSON @@ -24047,7 +24231,7 @@ Duration.prototype.toJSON = function toJSON() { return this.constructor.toObject(this, $protobuf.util.toJSONOptions); }; - + /** * Gets the default type url for Duration * @function getTypeUrl @@ -24062,19 +24246,19 @@ } return typeUrlPrefix + "/google.protobuf.Duration"; }; - + return Duration; })(); - + protobuf.DoubleValue = (function() { - + /** * Properties of a DoubleValue. * @memberof google.protobuf * @interface IDoubleValue * @property {number|null} [value] DoubleValue value */ - + /** * Constructs a new DoubleValue. * @memberof google.protobuf @@ -24089,7 +24273,7 @@ if (properties[keys[i]] != null) this[keys[i]] = properties[keys[i]]; } - + /** * DoubleValue value. * @member {number} value @@ -24097,7 +24281,7 @@ * @instance */ DoubleValue.prototype.value = 0; - + /** * Creates a DoubleValue message from a plain object. Also converts values to their respective internal types. * @function fromObject @@ -24114,7 +24298,7 @@ message.value = Number(object.value); return message; }; - + /** * Creates a plain object from a DoubleValue message. Also converts values to other types if specified. * @function toObject @@ -24134,7 +24318,7 @@ object.value = options.json && !isFinite(message.value) ? String(message.value) : message.value; return object; }; - + /** * Converts this DoubleValue to JSON. * @function toJSON @@ -24145,7 +24329,7 @@ DoubleValue.prototype.toJSON = function toJSON() { return this.constructor.toObject(this, $protobuf.util.toJSONOptions); }; - + /** * Gets the default type url for DoubleValue * @function getTypeUrl @@ -24160,19 +24344,19 @@ } return typeUrlPrefix + "/google.protobuf.DoubleValue"; }; - + return DoubleValue; })(); - + protobuf.FloatValue = (function() { - + /** * Properties of a FloatValue. * @memberof google.protobuf * @interface IFloatValue * @property {number|null} [value] FloatValue value */ - + /** * Constructs a new FloatValue. * @memberof google.protobuf @@ -24187,7 +24371,7 @@ if (properties[keys[i]] != null) this[keys[i]] = properties[keys[i]]; } - + /** * FloatValue value. * @member {number} value @@ -24195,7 +24379,7 @@ * @instance */ FloatValue.prototype.value = 0; - + /** * Creates a FloatValue message from a plain object. Also converts values to their respective internal types. * @function fromObject @@ -24212,7 +24396,7 @@ message.value = Number(object.value); return message; }; - + /** * Creates a plain object from a FloatValue message. Also converts values to other types if specified. * @function toObject @@ -24232,7 +24416,7 @@ object.value = options.json && !isFinite(message.value) ? String(message.value) : message.value; return object; }; - + /** * Converts this FloatValue to JSON. * @function toJSON @@ -24243,7 +24427,7 @@ FloatValue.prototype.toJSON = function toJSON() { return this.constructor.toObject(this, $protobuf.util.toJSONOptions); }; - + /** * Gets the default type url for FloatValue * @function getTypeUrl @@ -24258,19 +24442,19 @@ } return typeUrlPrefix + "/google.protobuf.FloatValue"; }; - + return FloatValue; })(); - + protobuf.Int64Value = (function() { - + /** * Properties of an Int64Value. * @memberof google.protobuf * @interface IInt64Value * @property {number|string|null} [value] Int64Value value */ - + /** * Constructs a new Int64Value. * @memberof google.protobuf @@ -24285,7 +24469,7 @@ if (properties[keys[i]] != null) this[keys[i]] = properties[keys[i]]; } - + /** * Int64Value value. * @member {number|string} value @@ -24293,7 +24477,7 @@ * @instance */ Int64Value.prototype.value = $util.Long ? $util.Long.fromBits(0,0,false) : 0; - + /** * Creates an Int64Value message from a plain object. Also converts values to their respective internal types. * @function fromObject @@ -24317,7 +24501,7 @@ message.value = new $util.LongBits(object.value.low >>> 0, object.value.high >>> 0).toNumber(); return message; }; - + /** * Creates a plain object from an Int64Value message. Also converts values to other types if specified. * @function toObject @@ -24344,7 +24528,7 @@ object.value = options.longs === String ? $util.Long.prototype.toString.call(message.value) : options.longs === Number ? new $util.LongBits(message.value.low >>> 0, message.value.high >>> 0).toNumber() : message.value; return object; }; - + /** * Converts this Int64Value to JSON. * @function toJSON @@ -24355,7 +24539,7 @@ Int64Value.prototype.toJSON = function toJSON() { return this.constructor.toObject(this, $protobuf.util.toJSONOptions); }; - + /** * Gets the default type url for Int64Value * @function getTypeUrl @@ -24370,19 +24554,19 @@ } return typeUrlPrefix + "/google.protobuf.Int64Value"; }; - + return Int64Value; })(); - + protobuf.UInt64Value = (function() { - + /** * Properties of a UInt64Value. * @memberof google.protobuf * @interface IUInt64Value * @property {number|string|null} [value] UInt64Value value */ - + /** * Constructs a new UInt64Value. * @memberof google.protobuf @@ -24397,7 +24581,7 @@ if (properties[keys[i]] != null) this[keys[i]] = properties[keys[i]]; } - + /** * UInt64Value value. * @member {number|string} value @@ -24405,7 +24589,7 @@ * @instance */ UInt64Value.prototype.value = $util.Long ? $util.Long.fromBits(0,0,true) : 0; - + /** * Creates a UInt64Value message from a plain object. Also converts values to their respective internal types. * @function fromObject @@ -24429,7 +24613,7 @@ message.value = new $util.LongBits(object.value.low >>> 0, object.value.high >>> 0).toNumber(true); return message; }; - + /** * Creates a plain object from a UInt64Value message. Also converts values to other types if specified. * @function toObject @@ -24456,7 +24640,7 @@ object.value = options.longs === String ? $util.Long.prototype.toString.call(message.value) : options.longs === Number ? new $util.LongBits(message.value.low >>> 0, message.value.high >>> 0).toNumber(true) : message.value; return object; }; - + /** * Converts this UInt64Value to JSON. * @function toJSON @@ -24467,7 +24651,7 @@ UInt64Value.prototype.toJSON = function toJSON() { return this.constructor.toObject(this, $protobuf.util.toJSONOptions); }; - + /** * Gets the default type url for UInt64Value * @function getTypeUrl @@ -24482,19 +24666,19 @@ } return typeUrlPrefix + "/google.protobuf.UInt64Value"; }; - + return UInt64Value; })(); - + protobuf.Int32Value = (function() { - + /** * Properties of an Int32Value. * @memberof google.protobuf * @interface IInt32Value * @property {number|null} [value] Int32Value value */ - + /** * Constructs a new Int32Value. * @memberof google.protobuf @@ -24509,7 +24693,7 @@ if (properties[keys[i]] != null) this[keys[i]] = properties[keys[i]]; } - + /** * Int32Value value. * @member {number} value @@ -24517,7 +24701,7 @@ * @instance */ Int32Value.prototype.value = 0; - + /** * Creates an Int32Value message from a plain object. Also converts values to their respective internal types. * @function fromObject @@ -24534,7 +24718,7 @@ message.value = object.value | 0; return message; }; - + /** * Creates a plain object from an Int32Value message. Also converts values to other types if specified. * @function toObject @@ -24554,7 +24738,7 @@ object.value = message.value; return object; }; - + /** * Converts this Int32Value to JSON. * @function toJSON @@ -24565,7 +24749,7 @@ Int32Value.prototype.toJSON = function toJSON() { return this.constructor.toObject(this, $protobuf.util.toJSONOptions); }; - + /** * Gets the default type url for Int32Value * @function getTypeUrl @@ -24580,19 +24764,19 @@ } return typeUrlPrefix + "/google.protobuf.Int32Value"; }; - + return Int32Value; })(); - + protobuf.UInt32Value = (function() { - + /** * Properties of a UInt32Value. * @memberof google.protobuf * @interface IUInt32Value * @property {number|null} [value] UInt32Value value */ - + /** * Constructs a new UInt32Value. * @memberof google.protobuf @@ -24607,7 +24791,7 @@ if (properties[keys[i]] != null) this[keys[i]] = properties[keys[i]]; } - + /** * UInt32Value value. * @member {number} value @@ -24615,7 +24799,7 @@ * @instance */ UInt32Value.prototype.value = 0; - + /** * Creates a UInt32Value message from a plain object. Also converts values to their respective internal types. * @function fromObject @@ -24632,7 +24816,7 @@ message.value = object.value >>> 0; return message; }; - + /** * Creates a plain object from a UInt32Value message. Also converts values to other types if specified. * @function toObject @@ -24652,7 +24836,7 @@ object.value = message.value; return object; }; - + /** * Converts this UInt32Value to JSON. * @function toJSON @@ -24663,7 +24847,7 @@ UInt32Value.prototype.toJSON = function toJSON() { return this.constructor.toObject(this, $protobuf.util.toJSONOptions); }; - + /** * Gets the default type url for UInt32Value * @function getTypeUrl @@ -24678,19 +24862,19 @@ } return typeUrlPrefix + "/google.protobuf.UInt32Value"; }; - + return UInt32Value; })(); - + protobuf.BoolValue = (function() { - + /** * Properties of a BoolValue. * @memberof google.protobuf * @interface IBoolValue * @property {boolean|null} [value] BoolValue value */ - + /** * Constructs a new BoolValue. * @memberof google.protobuf @@ -24705,7 +24889,7 @@ if (properties[keys[i]] != null) this[keys[i]] = properties[keys[i]]; } - + /** * BoolValue value. * @member {boolean} value @@ -24713,7 +24897,7 @@ * @instance */ BoolValue.prototype.value = false; - + /** * Creates a BoolValue message from a plain object. Also converts values to their respective internal types. * @function fromObject @@ -24730,7 +24914,7 @@ message.value = Boolean(object.value); return message; }; - + /** * Creates a plain object from a BoolValue message. Also converts values to other types if specified. * @function toObject @@ -24750,7 +24934,7 @@ object.value = message.value; return object; }; - + /** * Converts this BoolValue to JSON. * @function toJSON @@ -24761,7 +24945,7 @@ BoolValue.prototype.toJSON = function toJSON() { return this.constructor.toObject(this, $protobuf.util.toJSONOptions); }; - + /** * Gets the default type url for BoolValue * @function getTypeUrl @@ -24776,19 +24960,19 @@ } return typeUrlPrefix + "/google.protobuf.BoolValue"; }; - + return BoolValue; })(); - + protobuf.StringValue = (function() { - + /** * Properties of a StringValue. * @memberof google.protobuf * @interface IStringValue * @property {string|null} [value] StringValue value */ - + /** * Constructs a new StringValue. * @memberof google.protobuf @@ -24803,7 +24987,7 @@ if (properties[keys[i]] != null) this[keys[i]] = properties[keys[i]]; } - + /** * StringValue value. * @member {string} value @@ -24811,7 +24995,7 @@ * @instance */ StringValue.prototype.value = ""; - + /** * Creates a StringValue message from a plain object. Also converts values to their respective internal types. * @function fromObject @@ -24828,7 +25012,7 @@ message.value = String(object.value); return message; }; - + /** * Creates a plain object from a StringValue message. Also converts values to other types if specified. * @function toObject @@ -24848,7 +25032,7 @@ object.value = message.value; return object; }; - + /** * Converts this StringValue to JSON. * @function toJSON @@ -24859,7 +25043,7 @@ StringValue.prototype.toJSON = function toJSON() { return this.constructor.toObject(this, $protobuf.util.toJSONOptions); }; - + /** * Gets the default type url for StringValue * @function getTypeUrl @@ -24874,19 +25058,19 @@ } return typeUrlPrefix + "/google.protobuf.StringValue"; }; - + return StringValue; })(); - + protobuf.BytesValue = (function() { - + /** * Properties of a BytesValue. * @memberof google.protobuf * @interface IBytesValue * @property {Uint8Array|null} [value] BytesValue value */ - + /** * Constructs a new BytesValue. * @memberof google.protobuf @@ -24901,7 +25085,7 @@ if (properties[keys[i]] != null) this[keys[i]] = properties[keys[i]]; } - + /** * BytesValue value. * @member {Uint8Array} value @@ -24909,7 +25093,7 @@ * @instance */ BytesValue.prototype.value = $util.newBuffer([]); - + /** * Creates a BytesValue message from a plain object. Also converts values to their respective internal types. * @function fromObject @@ -24929,7 +25113,7 @@ message.value = object.value; return message; }; - + /** * Creates a plain object from a BytesValue message. Also converts values to other types if specified. * @function toObject @@ -24955,7 +25139,7 @@ object.value = options.bytes === String ? $util.base64.encode(message.value, 0, message.value.length) : options.bytes === Array ? Array.prototype.slice.call(message.value) : message.value; return object; }; - + /** * Converts this BytesValue to JSON. * @function toJSON @@ -24966,7 +25150,7 @@ BytesValue.prototype.toJSON = function toJSON() { return this.constructor.toObject(this, $protobuf.util.toJSONOptions); }; - + /** * Gets the default type url for BytesValue * @function getTypeUrl @@ -24975,226 +25159,104 @@ * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") * @returns {string} The default type url */ - BytesValue.getTypeUrl = function getTypeUrl(typeUrlPrefix) { - if (typeUrlPrefix === undefined) { - typeUrlPrefix = "type.googleapis.com"; - } - return typeUrlPrefix + "/google.protobuf.BytesValue"; - }; - - return BytesValue; - })(); - - protobuf.Empty = (function() { - - /** - * Properties of an Empty. - * @memberof google.protobuf - * @interface IEmpty - */ - - /** - * Constructs a new Empty. - * @memberof google.protobuf - * @classdesc Represents an Empty. - * @implements IEmpty - * @constructor - * @param {google.protobuf.IEmpty=} [properties] Properties to set - */ - function Empty(properties) { - if (properties) - for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) - if (properties[keys[i]] != null) - this[keys[i]] = properties[keys[i]]; - } - - /** - * Creates an Empty message from a plain object. Also converts values to their respective internal types. - * @function fromObject - * @memberof google.protobuf.Empty - * @static - * @param {Object.} object Plain object - * @returns {google.protobuf.Empty} Empty - */ - Empty.fromObject = function fromObject(object) { - if (object instanceof $root.google.protobuf.Empty) - return object; - return new $root.google.protobuf.Empty(); - }; - - /** - * Creates a plain object from an Empty message. Also converts values to other types if specified. - * @function toObject - * @memberof google.protobuf.Empty - * @static - * @param {google.protobuf.Empty} message Empty - * @param {$protobuf.IConversionOptions} [options] Conversion options - * @returns {Object.} Plain object - */ - Empty.toObject = function toObject() { - return {}; - }; - - /** - * Converts this Empty to JSON. - * @function toJSON - * @memberof google.protobuf.Empty - * @instance - * @returns {Object.} JSON object - */ - Empty.prototype.toJSON = function toJSON() { - return this.constructor.toObject(this, $protobuf.util.toJSONOptions); - }; - - /** - * Gets the default type url for Empty - * @function getTypeUrl - * @memberof google.protobuf.Empty - * @static - * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") - * @returns {string} The default type url - */ - Empty.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + BytesValue.getTypeUrl = function getTypeUrl(typeUrlPrefix) { if (typeUrlPrefix === undefined) { typeUrlPrefix = "type.googleapis.com"; } - return typeUrlPrefix + "/google.protobuf.Empty"; + return typeUrlPrefix + "/google.protobuf.BytesValue"; }; - - return Empty; + + return BytesValue; })(); - - protobuf.Any = (function() { - + + protobuf.Empty = (function() { + /** - * Properties of an Any. + * Properties of an Empty. * @memberof google.protobuf - * @interface IAny - * @property {string|null} [type_url] Any type_url - * @property {Uint8Array|null} [value] Any value + * @interface IEmpty */ - + /** - * Constructs a new Any. + * Constructs a new Empty. * @memberof google.protobuf - * @classdesc Represents an Any. - * @implements IAny + * @classdesc Represents an Empty. + * @implements IEmpty * @constructor - * @param {google.protobuf.IAny=} [properties] Properties to set + * @param {google.protobuf.IEmpty=} [properties] Properties to set */ - function Any(properties) { + function Empty(properties) { if (properties) for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) if (properties[keys[i]] != null) this[keys[i]] = properties[keys[i]]; } - - /** - * Any type_url. - * @member {string} type_url - * @memberof google.protobuf.Any - * @instance - */ - Any.prototype.type_url = ""; - - /** - * Any value. - * @member {Uint8Array} value - * @memberof google.protobuf.Any - * @instance - */ - Any.prototype.value = $util.newBuffer([]); - + /** - * Creates an Any message from a plain object. Also converts values to their respective internal types. + * Creates an Empty message from a plain object. Also converts values to their respective internal types. * @function fromObject - * @memberof google.protobuf.Any + * @memberof google.protobuf.Empty * @static * @param {Object.} object Plain object - * @returns {google.protobuf.Any} Any + * @returns {google.protobuf.Empty} Empty */ - Any.fromObject = function fromObject(object) { - if (object instanceof $root.google.protobuf.Any) + Empty.fromObject = function fromObject(object) { + if (object instanceof $root.google.protobuf.Empty) return object; - var message = new $root.google.protobuf.Any(); - if (object.type_url != null) - message.type_url = String(object.type_url); - if (object.value != null) - if (typeof object.value === "string") - $util.base64.decode(object.value, message.value = $util.newBuffer($util.base64.length(object.value)), 0); - else if (object.value.length >= 0) - message.value = object.value; - return message; + return new $root.google.protobuf.Empty(); }; - + /** - * Creates a plain object from an Any message. Also converts values to other types if specified. + * Creates a plain object from an Empty message. Also converts values to other types if specified. * @function toObject - * @memberof google.protobuf.Any + * @memberof google.protobuf.Empty * @static - * @param {google.protobuf.Any} message Any + * @param {google.protobuf.Empty} message Empty * @param {$protobuf.IConversionOptions} [options] Conversion options * @returns {Object.} Plain object */ - Any.toObject = function toObject(message, options) { - if (!options) - options = {}; - var object = {}; - if (options.defaults) { - object.type_url = ""; - if (options.bytes === String) - object.value = ""; - else { - object.value = []; - if (options.bytes !== Array) - object.value = $util.newBuffer(object.value); - } - } - if (message.type_url != null && message.hasOwnProperty("type_url")) - object.type_url = message.type_url; - if (message.value != null && message.hasOwnProperty("value")) - object.value = options.bytes === String ? $util.base64.encode(message.value, 0, message.value.length) : options.bytes === Array ? Array.prototype.slice.call(message.value) : message.value; - return object; + Empty.toObject = function toObject() { + return {}; }; - + /** - * Converts this Any to JSON. + * Converts this Empty to JSON. * @function toJSON - * @memberof google.protobuf.Any + * @memberof google.protobuf.Empty * @instance * @returns {Object.} JSON object */ - Any.prototype.toJSON = function toJSON() { + Empty.prototype.toJSON = function toJSON() { return this.constructor.toObject(this, $protobuf.util.toJSONOptions); }; - + /** - * Gets the default type url for Any + * Gets the default type url for Empty * @function getTypeUrl - * @memberof google.protobuf.Any + * @memberof google.protobuf.Empty * @static * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") * @returns {string} The default type url */ - Any.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + Empty.getTypeUrl = function getTypeUrl(typeUrlPrefix) { if (typeUrlPrefix === undefined) { typeUrlPrefix = "type.googleapis.com"; } - return typeUrlPrefix + "/google.protobuf.Any"; + return typeUrlPrefix + "/google.protobuf.Empty"; }; - - return Any; + + return Empty; })(); - + protobuf.FieldMask = (function() { - + /** * Properties of a FieldMask. * @memberof google.protobuf * @interface IFieldMask * @property {Array.|null} [paths] FieldMask paths */ - + /** * Constructs a new FieldMask. * @memberof google.protobuf @@ -25210,7 +25272,7 @@ if (properties[keys[i]] != null) this[keys[i]] = properties[keys[i]]; } - + /** * FieldMask paths. * @member {Array.} paths @@ -25218,7 +25280,7 @@ * @instance */ FieldMask.prototype.paths = $util.emptyArray; - + /** * Creates a FieldMask message from a plain object. Also converts values to their respective internal types. * @function fromObject @@ -25240,7 +25302,7 @@ } return message; }; - + /** * Creates a plain object from a FieldMask message. Also converts values to other types if specified. * @function toObject @@ -25263,7 +25325,7 @@ } return object; }; - + /** * Converts this FieldMask to JSON. * @function toJSON @@ -25274,7 +25336,7 @@ FieldMask.prototype.toJSON = function toJSON() { return this.constructor.toObject(this, $protobuf.util.toJSONOptions); }; - + /** * Gets the default type url for FieldMask * @function getTypeUrl @@ -25289,24 +25351,24 @@ } return typeUrlPrefix + "/google.protobuf.FieldMask"; }; - + return FieldMask; })(); - + return protobuf; })(); - + google.type = (function() { - + /** * Namespace type. * @memberof google * @namespace */ var type = {}; - + type.LatLng = (function() { - + /** * Properties of a LatLng. * @memberof google.type @@ -25314,7 +25376,7 @@ * @property {number|null} [latitude] LatLng latitude * @property {number|null} [longitude] LatLng longitude */ - + /** * Constructs a new LatLng. * @memberof google.type @@ -25329,7 +25391,7 @@ if (properties[keys[i]] != null) this[keys[i]] = properties[keys[i]]; } - + /** * LatLng latitude. * @member {number} latitude @@ -25337,7 +25399,7 @@ * @instance */ LatLng.prototype.latitude = 0; - + /** * LatLng longitude. * @member {number} longitude @@ -25345,7 +25407,7 @@ * @instance */ LatLng.prototype.longitude = 0; - + /** * Creates a LatLng message from a plain object. Also converts values to their respective internal types. * @function fromObject @@ -25364,7 +25426,7 @@ message.longitude = Number(object.longitude); return message; }; - + /** * Creates a plain object from a LatLng message. Also converts values to other types if specified. * @function toObject @@ -25388,7 +25450,7 @@ object.longitude = options.json && !isFinite(message.longitude) ? String(message.longitude) : message.longitude; return object; }; - + /** * Converts this LatLng to JSON. * @function toJSON @@ -25399,7 +25461,7 @@ LatLng.prototype.toJSON = function toJSON() { return this.constructor.toObject(this, $protobuf.util.toJSONOptions); }; - + /** * Gets the default type url for LatLng * @function getTypeUrl @@ -25414,10 +25476,10 @@ } return typeUrlPrefix + "/google.type.LatLng"; }; - + return LatLng; })(); - + /** * DayOfWeek enum. * @name google.type.DayOfWeek @@ -25443,21 +25505,21 @@ values[valuesById[7] = "SUNDAY"] = "SUNDAY"; return values; })(); - + return type; })(); - + google.rpc = (function() { - + /** * Namespace rpc. * @memberof google * @namespace */ var rpc = {}; - + rpc.Status = (function() { - + /** * Properties of a Status. * @memberof google.rpc @@ -25466,7 +25528,7 @@ * @property {string|null} [message] Status message * @property {Array.|null} [details] Status details */ - + /** * Constructs a new Status. * @memberof google.rpc @@ -25482,7 +25544,7 @@ if (properties[keys[i]] != null) this[keys[i]] = properties[keys[i]]; } - + /** * Status code. * @member {number} code @@ -25490,7 +25552,7 @@ * @instance */ Status.prototype.code = 0; - + /** * Status message. * @member {string} message @@ -25498,7 +25560,7 @@ * @instance */ Status.prototype.message = ""; - + /** * Status details. * @member {Array.} details @@ -25506,7 +25568,7 @@ * @instance */ Status.prototype.details = $util.emptyArray; - + /** * Creates a Status message from a plain object. Also converts values to their respective internal types. * @function fromObject @@ -25535,7 +25597,7 @@ } return message; }; - + /** * Creates a plain object from a Status message. Also converts values to other types if specified. * @function toObject @@ -25566,7 +25628,7 @@ } return object; }; - + /** * Converts this Status to JSON. * @function toJSON @@ -25577,7 +25639,7 @@ Status.prototype.toJSON = function toJSON() { return this.constructor.toObject(this, $protobuf.util.toJSONOptions); }; - + /** * Gets the default type url for Status * @function getTypeUrl @@ -25592,24 +25654,24 @@ } return typeUrlPrefix + "/google.rpc.Status"; }; - + return Status; })(); - + return rpc; })(); - + google.longrunning = (function() { - + /** * Namespace longrunning. * @memberof google * @namespace */ var longrunning = {}; - + longrunning.Operations = (function() { - + /** * Constructs a new Operations service. * @memberof google.longrunning @@ -25623,9 +25685,9 @@ function Operations(rpcImpl, requestDelimited, responseDelimited) { $protobuf.rpc.Service.call(this, rpcImpl, requestDelimited, responseDelimited); } - + (Operations.prototype = Object.create($protobuf.rpc.Service.prototype)).constructor = Operations; - + /** * Callback as used by {@link google.longrunning.Operations#listOperations}. * @memberof google.longrunning.Operations @@ -25634,7 +25696,7 @@ * @param {Error|null} error Error, if any * @param {google.longrunning.ListOperationsResponse} [response] ListOperationsResponse */ - + /** * Calls ListOperations. * @function listOperations @@ -25648,7 +25710,7 @@ Object.defineProperty(Operations.prototype.listOperations = function listOperations(request, callback) { return this.rpcCall(listOperations, $root.google.longrunning.ListOperationsRequest, $root.google.longrunning.ListOperationsResponse, request, callback); }, "name", { value: "ListOperations" }); - + /** * Calls ListOperations. * @function listOperations @@ -25658,7 +25720,7 @@ * @returns {Promise} Promise * @variation 2 */ - + /** * Callback as used by {@link google.longrunning.Operations#getOperation}. * @memberof google.longrunning.Operations @@ -25667,7 +25729,7 @@ * @param {Error|null} error Error, if any * @param {google.longrunning.Operation} [response] Operation */ - + /** * Calls GetOperation. * @function getOperation @@ -25681,7 +25743,7 @@ Object.defineProperty(Operations.prototype.getOperation = function getOperation(request, callback) { return this.rpcCall(getOperation, $root.google.longrunning.GetOperationRequest, $root.google.longrunning.Operation, request, callback); }, "name", { value: "GetOperation" }); - + /** * Calls GetOperation. * @function getOperation @@ -25691,7 +25753,7 @@ * @returns {Promise} Promise * @variation 2 */ - + /** * Callback as used by {@link google.longrunning.Operations#deleteOperation}. * @memberof google.longrunning.Operations @@ -25700,7 +25762,7 @@ * @param {Error|null} error Error, if any * @param {google.protobuf.Empty} [response] Empty */ - + /** * Calls DeleteOperation. * @function deleteOperation @@ -25714,7 +25776,7 @@ Object.defineProperty(Operations.prototype.deleteOperation = function deleteOperation(request, callback) { return this.rpcCall(deleteOperation, $root.google.longrunning.DeleteOperationRequest, $root.google.protobuf.Empty, request, callback); }, "name", { value: "DeleteOperation" }); - + /** * Calls DeleteOperation. * @function deleteOperation @@ -25724,7 +25786,7 @@ * @returns {Promise} Promise * @variation 2 */ - + /** * Callback as used by {@link google.longrunning.Operations#cancelOperation}. * @memberof google.longrunning.Operations @@ -25733,7 +25795,7 @@ * @param {Error|null} error Error, if any * @param {google.protobuf.Empty} [response] Empty */ - + /** * Calls CancelOperation. * @function cancelOperation @@ -25747,7 +25809,7 @@ Object.defineProperty(Operations.prototype.cancelOperation = function cancelOperation(request, callback) { return this.rpcCall(cancelOperation, $root.google.longrunning.CancelOperationRequest, $root.google.protobuf.Empty, request, callback); }, "name", { value: "CancelOperation" }); - + /** * Calls CancelOperation. * @function cancelOperation @@ -25757,7 +25819,7 @@ * @returns {Promise} Promise * @variation 2 */ - + /** * Callback as used by {@link google.longrunning.Operations#waitOperation}. * @memberof google.longrunning.Operations @@ -25766,7 +25828,7 @@ * @param {Error|null} error Error, if any * @param {google.longrunning.Operation} [response] Operation */ - + /** * Calls WaitOperation. * @function waitOperation @@ -25780,7 +25842,7 @@ Object.defineProperty(Operations.prototype.waitOperation = function waitOperation(request, callback) { return this.rpcCall(waitOperation, $root.google.longrunning.WaitOperationRequest, $root.google.longrunning.Operation, request, callback); }, "name", { value: "WaitOperation" }); - + /** * Calls WaitOperation. * @function waitOperation @@ -25790,12 +25852,12 @@ * @returns {Promise} Promise * @variation 2 */ - + return Operations; })(); - + longrunning.Operation = (function() { - + /** * Properties of an Operation. * @memberof google.longrunning @@ -25806,7 +25868,7 @@ * @property {google.rpc.IStatus|null} [error] Operation error * @property {google.protobuf.IAny|null} [response] Operation response */ - + /** * Constructs a new Operation. * @memberof google.longrunning @@ -25821,7 +25883,7 @@ if (properties[keys[i]] != null) this[keys[i]] = properties[keys[i]]; } - + /** * Operation name. * @member {string} name @@ -25829,7 +25891,7 @@ * @instance */ Operation.prototype.name = ""; - + /** * Operation metadata. * @member {google.protobuf.IAny|null|undefined} metadata @@ -25837,7 +25899,7 @@ * @instance */ Operation.prototype.metadata = null; - + /** * Operation done. * @member {boolean} done @@ -25845,7 +25907,7 @@ * @instance */ Operation.prototype.done = false; - + /** * Operation error. * @member {google.rpc.IStatus|null|undefined} error @@ -25853,7 +25915,7 @@ * @instance */ Operation.prototype.error = null; - + /** * Operation response. * @member {google.protobuf.IAny|null|undefined} response @@ -25861,10 +25923,10 @@ * @instance */ Operation.prototype.response = null; - + // OneOf field names bound to virtual getters and setters var $oneOfFields; - + /** * Operation result. * @member {"error"|"response"|undefined} result @@ -25875,7 +25937,7 @@ get: $util.oneOfGetter($oneOfFields = ["error", "response"]), set: $util.oneOfSetter($oneOfFields) }); - + /** * Creates an Operation message from a plain object. Also converts values to their respective internal types. * @function fromObject @@ -25909,7 +25971,7 @@ } return message; }; - + /** * Creates a plain object from an Operation message. Also converts values to other types if specified. * @function toObject @@ -25946,7 +26008,7 @@ } return object; }; - + /** * Converts this Operation to JSON. * @function toJSON @@ -25957,7 +26019,7 @@ Operation.prototype.toJSON = function toJSON() { return this.constructor.toObject(this, $protobuf.util.toJSONOptions); }; - + /** * Gets the default type url for Operation * @function getTypeUrl @@ -25972,19 +26034,19 @@ } return typeUrlPrefix + "/google.longrunning.Operation"; }; - + return Operation; })(); - + longrunning.GetOperationRequest = (function() { - + /** * Properties of a GetOperationRequest. * @memberof google.longrunning * @interface IGetOperationRequest * @property {string|null} [name] GetOperationRequest name */ - + /** * Constructs a new GetOperationRequest. * @memberof google.longrunning @@ -25999,7 +26061,7 @@ if (properties[keys[i]] != null) this[keys[i]] = properties[keys[i]]; } - + /** * GetOperationRequest name. * @member {string} name @@ -26007,7 +26069,7 @@ * @instance */ GetOperationRequest.prototype.name = ""; - + /** * Creates a GetOperationRequest message from a plain object. Also converts values to their respective internal types. * @function fromObject @@ -26024,7 +26086,7 @@ message.name = String(object.name); return message; }; - + /** * Creates a plain object from a GetOperationRequest message. Also converts values to other types if specified. * @function toObject @@ -26044,7 +26106,7 @@ object.name = message.name; return object; }; - + /** * Converts this GetOperationRequest to JSON. * @function toJSON @@ -26055,7 +26117,7 @@ GetOperationRequest.prototype.toJSON = function toJSON() { return this.constructor.toObject(this, $protobuf.util.toJSONOptions); }; - + /** * Gets the default type url for GetOperationRequest * @function getTypeUrl @@ -26070,12 +26132,12 @@ } return typeUrlPrefix + "/google.longrunning.GetOperationRequest"; }; - + return GetOperationRequest; })(); - + longrunning.ListOperationsRequest = (function() { - + /** * Properties of a ListOperationsRequest. * @memberof google.longrunning @@ -26085,7 +26147,7 @@ * @property {number|null} [pageSize] ListOperationsRequest pageSize * @property {string|null} [pageToken] ListOperationsRequest pageToken */ - + /** * Constructs a new ListOperationsRequest. * @memberof google.longrunning @@ -26100,7 +26162,7 @@ if (properties[keys[i]] != null) this[keys[i]] = properties[keys[i]]; } - + /** * ListOperationsRequest name. * @member {string} name @@ -26108,7 +26170,7 @@ * @instance */ ListOperationsRequest.prototype.name = ""; - + /** * ListOperationsRequest filter. * @member {string} filter @@ -26116,7 +26178,7 @@ * @instance */ ListOperationsRequest.prototype.filter = ""; - + /** * ListOperationsRequest pageSize. * @member {number} pageSize @@ -26124,7 +26186,7 @@ * @instance */ ListOperationsRequest.prototype.pageSize = 0; - + /** * ListOperationsRequest pageToken. * @member {string} pageToken @@ -26132,7 +26194,7 @@ * @instance */ ListOperationsRequest.prototype.pageToken = ""; - + /** * Creates a ListOperationsRequest message from a plain object. Also converts values to their respective internal types. * @function fromObject @@ -26155,7 +26217,7 @@ message.pageToken = String(object.pageToken); return message; }; - + /** * Creates a plain object from a ListOperationsRequest message. Also converts values to other types if specified. * @function toObject @@ -26185,7 +26247,7 @@ object.name = message.name; return object; }; - + /** * Converts this ListOperationsRequest to JSON. * @function toJSON @@ -26196,7 +26258,7 @@ ListOperationsRequest.prototype.toJSON = function toJSON() { return this.constructor.toObject(this, $protobuf.util.toJSONOptions); }; - + /** * Gets the default type url for ListOperationsRequest * @function getTypeUrl @@ -26211,12 +26273,12 @@ } return typeUrlPrefix + "/google.longrunning.ListOperationsRequest"; }; - + return ListOperationsRequest; })(); - + longrunning.ListOperationsResponse = (function() { - + /** * Properties of a ListOperationsResponse. * @memberof google.longrunning @@ -26224,7 +26286,7 @@ * @property {Array.|null} [operations] ListOperationsResponse operations * @property {string|null} [nextPageToken] ListOperationsResponse nextPageToken */ - + /** * Constructs a new ListOperationsResponse. * @memberof google.longrunning @@ -26240,7 +26302,7 @@ if (properties[keys[i]] != null) this[keys[i]] = properties[keys[i]]; } - + /** * ListOperationsResponse operations. * @member {Array.} operations @@ -26248,7 +26310,7 @@ * @instance */ ListOperationsResponse.prototype.operations = $util.emptyArray; - + /** * ListOperationsResponse nextPageToken. * @member {string} nextPageToken @@ -26256,7 +26318,7 @@ * @instance */ ListOperationsResponse.prototype.nextPageToken = ""; - + /** * Creates a ListOperationsResponse message from a plain object. Also converts values to their respective internal types. * @function fromObject @@ -26283,7 +26345,7 @@ message.nextPageToken = String(object.nextPageToken); return message; }; - + /** * Creates a plain object from a ListOperationsResponse message. Also converts values to other types if specified. * @function toObject @@ -26310,7 +26372,7 @@ object.nextPageToken = message.nextPageToken; return object; }; - + /** * Converts this ListOperationsResponse to JSON. * @function toJSON @@ -26321,7 +26383,7 @@ ListOperationsResponse.prototype.toJSON = function toJSON() { return this.constructor.toObject(this, $protobuf.util.toJSONOptions); }; - + /** * Gets the default type url for ListOperationsResponse * @function getTypeUrl @@ -26336,19 +26398,19 @@ } return typeUrlPrefix + "/google.longrunning.ListOperationsResponse"; }; - + return ListOperationsResponse; })(); - + longrunning.CancelOperationRequest = (function() { - + /** * Properties of a CancelOperationRequest. * @memberof google.longrunning * @interface ICancelOperationRequest * @property {string|null} [name] CancelOperationRequest name */ - + /** * Constructs a new CancelOperationRequest. * @memberof google.longrunning @@ -26363,7 +26425,7 @@ if (properties[keys[i]] != null) this[keys[i]] = properties[keys[i]]; } - + /** * CancelOperationRequest name. * @member {string} name @@ -26371,7 +26433,7 @@ * @instance */ CancelOperationRequest.prototype.name = ""; - + /** * Creates a CancelOperationRequest message from a plain object. Also converts values to their respective internal types. * @function fromObject @@ -26388,7 +26450,7 @@ message.name = String(object.name); return message; }; - + /** * Creates a plain object from a CancelOperationRequest message. Also converts values to other types if specified. * @function toObject @@ -26408,7 +26470,7 @@ object.name = message.name; return object; }; - + /** * Converts this CancelOperationRequest to JSON. * @function toJSON @@ -26419,7 +26481,7 @@ CancelOperationRequest.prototype.toJSON = function toJSON() { return this.constructor.toObject(this, $protobuf.util.toJSONOptions); }; - + /** * Gets the default type url for CancelOperationRequest * @function getTypeUrl @@ -26434,19 +26496,19 @@ } return typeUrlPrefix + "/google.longrunning.CancelOperationRequest"; }; - + return CancelOperationRequest; })(); - + longrunning.DeleteOperationRequest = (function() { - + /** * Properties of a DeleteOperationRequest. * @memberof google.longrunning * @interface IDeleteOperationRequest * @property {string|null} [name] DeleteOperationRequest name */ - + /** * Constructs a new DeleteOperationRequest. * @memberof google.longrunning @@ -26461,7 +26523,7 @@ if (properties[keys[i]] != null) this[keys[i]] = properties[keys[i]]; } - + /** * DeleteOperationRequest name. * @member {string} name @@ -26469,7 +26531,7 @@ * @instance */ DeleteOperationRequest.prototype.name = ""; - + /** * Creates a DeleteOperationRequest message from a plain object. Also converts values to their respective internal types. * @function fromObject @@ -26486,7 +26548,7 @@ message.name = String(object.name); return message; }; - + /** * Creates a plain object from a DeleteOperationRequest message. Also converts values to other types if specified. * @function toObject @@ -26506,7 +26568,7 @@ object.name = message.name; return object; }; - + /** * Converts this DeleteOperationRequest to JSON. * @function toJSON @@ -26517,7 +26579,7 @@ DeleteOperationRequest.prototype.toJSON = function toJSON() { return this.constructor.toObject(this, $protobuf.util.toJSONOptions); }; - + /** * Gets the default type url for DeleteOperationRequest * @function getTypeUrl @@ -26532,12 +26594,12 @@ } return typeUrlPrefix + "/google.longrunning.DeleteOperationRequest"; }; - + return DeleteOperationRequest; })(); - + longrunning.WaitOperationRequest = (function() { - + /** * Properties of a WaitOperationRequest. * @memberof google.longrunning @@ -26545,7 +26607,7 @@ * @property {string|null} [name] WaitOperationRequest name * @property {google.protobuf.IDuration|null} [timeout] WaitOperationRequest timeout */ - + /** * Constructs a new WaitOperationRequest. * @memberof google.longrunning @@ -26560,7 +26622,7 @@ if (properties[keys[i]] != null) this[keys[i]] = properties[keys[i]]; } - + /** * WaitOperationRequest name. * @member {string} name @@ -26568,7 +26630,7 @@ * @instance */ WaitOperationRequest.prototype.name = ""; - + /** * WaitOperationRequest timeout. * @member {google.protobuf.IDuration|null|undefined} timeout @@ -26576,7 +26638,7 @@ * @instance */ WaitOperationRequest.prototype.timeout = null; - + /** * Creates a WaitOperationRequest message from a plain object. Also converts values to their respective internal types. * @function fromObject @@ -26598,7 +26660,7 @@ } return message; }; - + /** * Creates a plain object from a WaitOperationRequest message. Also converts values to other types if specified. * @function toObject @@ -26622,7 +26684,7 @@ object.timeout = $root.google.protobuf.Duration.toObject(message.timeout, options); return object; }; - + /** * Converts this WaitOperationRequest to JSON. * @function toJSON @@ -26633,7 +26695,7 @@ WaitOperationRequest.prototype.toJSON = function toJSON() { return this.constructor.toObject(this, $protobuf.util.toJSONOptions); }; - + /** * Gets the default type url for WaitOperationRequest * @function getTypeUrl @@ -26648,12 +26710,12 @@ } return typeUrlPrefix + "/google.longrunning.WaitOperationRequest"; }; - + return WaitOperationRequest; })(); - + longrunning.OperationInfo = (function() { - + /** * Properties of an OperationInfo. * @memberof google.longrunning @@ -26661,7 +26723,7 @@ * @property {string|null} [responseType] OperationInfo responseType * @property {string|null} [metadataType] OperationInfo metadataType */ - + /** * Constructs a new OperationInfo. * @memberof google.longrunning @@ -26676,7 +26738,7 @@ if (properties[keys[i]] != null) this[keys[i]] = properties[keys[i]]; } - + /** * OperationInfo responseType. * @member {string} responseType @@ -26684,7 +26746,7 @@ * @instance */ OperationInfo.prototype.responseType = ""; - + /** * OperationInfo metadataType. * @member {string} metadataType @@ -26692,7 +26754,7 @@ * @instance */ OperationInfo.prototype.metadataType = ""; - + /** * Creates an OperationInfo message from a plain object. Also converts values to their respective internal types. * @function fromObject @@ -26711,7 +26773,7 @@ message.metadataType = String(object.metadataType); return message; }; - + /** * Creates a plain object from an OperationInfo message. Also converts values to other types if specified. * @function toObject @@ -26735,7 +26797,7 @@ object.metadataType = message.metadataType; return object; }; - + /** * Converts this OperationInfo to JSON. * @function toJSON @@ -26746,7 +26808,7 @@ OperationInfo.prototype.toJSON = function toJSON() { return this.constructor.toObject(this, $protobuf.util.toJSONOptions); }; - + /** * Gets the default type url for OperationInfo * @function getTypeUrl @@ -26761,13 +26823,13 @@ } return typeUrlPrefix + "/google.longrunning.OperationInfo"; }; - + return OperationInfo; })(); - + return longrunning; })(); - + return google; })(); diff --git a/dev/protos/firestore_v1beta1_proto_api.d.ts b/dev/protos/firestore_v1beta1_proto_api.d.ts index 242849587..1c26c5a42 100644 --- a/dev/protos/firestore_v1beta1_proto_api.d.ts +++ b/dev/protos/firestore_v1beta1_proto_api.d.ts @@ -15,6 +15,7 @@ */ import * as $protobuf from "protobufjs"; +import Long = require("long"); /** Namespace google. */ export namespace google { @@ -2038,6 +2039,9 @@ export namespace google { /** MethodOptions .google.api.methodSignature */ ".google.api.methodSignature"?: (string[]|null); + /** MethodOptions .google.api.routing */ + ".google.api.routing"?: (google.api.IRoutingRule|null); + /** MethodOptions .google.longrunning.operationInfo */ ".google.longrunning.operationInfo"?: (google.longrunning.IOperationInfo|null); } @@ -7614,9 +7618,6 @@ export namespace google { /** CommonLanguageSettings destinations */ destinations?: (google.api.ClientLibraryDestination[]|null); - - /** CommonLanguageSettings selectiveGapicGeneration */ - selectiveGapicGeneration?: (google.api.ISelectiveGapicGeneration|null); } /** Represents a CommonLanguageSettings. */ @@ -7634,9 +7635,6 @@ export namespace google { /** CommonLanguageSettings destinations. */ public destinations: google.api.ClientLibraryDestination[]; - /** CommonLanguageSettings selectiveGapicGeneration. */ - public selectiveGapicGeneration?: (google.api.ISelectiveGapicGeneration|null); - /** * Creates a CommonLanguageSettings message from a plain object. Also converts values to their respective internal types. * @param object Plain object @@ -8043,9 +8041,6 @@ export namespace google { /** PythonSettings common */ common?: (google.api.ICommonLanguageSettings|null); - - /** PythonSettings experimentalFeatures */ - experimentalFeatures?: (google.api.PythonSettings.IExperimentalFeatures|null); } /** Represents a PythonSettings. */ @@ -8060,9 +8055,6 @@ export namespace google { /** PythonSettings common. */ public common?: (google.api.ICommonLanguageSettings|null); - /** PythonSettings experimentalFeatures. */ - public experimentalFeatures?: (google.api.PythonSettings.IExperimentalFeatures|null); - /** * Creates a PythonSettings message from a plain object. Also converts values to their respective internal types. * @param object Plain object @@ -8092,63 +8084,6 @@ export namespace google { public static getTypeUrl(typeUrlPrefix?: string): string; } - namespace PythonSettings { - - /** Properties of an ExperimentalFeatures. */ - interface IExperimentalFeatures { - - /** ExperimentalFeatures restAsyncIoEnabled */ - restAsyncIoEnabled?: (boolean|null); - - /** ExperimentalFeatures protobufPythonicTypesEnabled */ - protobufPythonicTypesEnabled?: (boolean|null); - } - - /** Represents an ExperimentalFeatures. */ - class ExperimentalFeatures implements IExperimentalFeatures { - - /** - * Constructs a new ExperimentalFeatures. - * @param [properties] Properties to set - */ - constructor(properties?: google.api.PythonSettings.IExperimentalFeatures); - - /** ExperimentalFeatures restAsyncIoEnabled. */ - public restAsyncIoEnabled: boolean; - - /** ExperimentalFeatures protobufPythonicTypesEnabled. */ - public protobufPythonicTypesEnabled: boolean; - - /** - * Creates an ExperimentalFeatures message from a plain object. Also converts values to their respective internal types. - * @param object Plain object - * @returns ExperimentalFeatures - */ - public static fromObject(object: { [k: string]: any }): google.api.PythonSettings.ExperimentalFeatures; - - /** - * Creates a plain object from an ExperimentalFeatures message. Also converts values to other types if specified. - * @param message ExperimentalFeatures - * @param [options] Conversion options - * @returns Plain object - */ - public static toObject(message: google.api.PythonSettings.ExperimentalFeatures, options?: $protobuf.IConversionOptions): { [k: string]: any }; - - /** - * Converts this ExperimentalFeatures to JSON. - * @returns JSON object - */ - public toJSON(): { [k: string]: any }; - - /** - * Gets the default type url for ExperimentalFeatures - * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") - * @returns The default type url - */ - public static getTypeUrl(typeUrlPrefix?: string): string; - } - } - /** Properties of a NodeSettings. */ interface INodeSettings { @@ -8328,9 +8263,6 @@ export namespace google { /** GoSettings common */ common?: (google.api.ICommonLanguageSettings|null); - - /** GoSettings renamedServices */ - renamedServices?: ({ [k: string]: string }|null); } /** Represents a GoSettings. */ @@ -8345,9 +8277,6 @@ export namespace google { /** GoSettings common. */ public common?: (google.api.ICommonLanguageSettings|null); - /** GoSettings renamedServices. */ - public renamedServices: { [k: string]: string }; - /** * Creates a GoSettings message from a plain object. Also converts values to their respective internal types. * @param object Plain object @@ -8514,60 +8443,6 @@ export namespace google { type ClientLibraryDestination = "CLIENT_LIBRARY_DESTINATION_UNSPECIFIED"| "GITHUB"| "PACKAGE_MANAGER"; - /** Properties of a SelectiveGapicGeneration. */ - interface ISelectiveGapicGeneration { - - /** SelectiveGapicGeneration methods */ - methods?: (string[]|null); - - /** SelectiveGapicGeneration generateOmittedAsInternal */ - generateOmittedAsInternal?: (boolean|null); - } - - /** Represents a SelectiveGapicGeneration. */ - class SelectiveGapicGeneration implements ISelectiveGapicGeneration { - - /** - * Constructs a new SelectiveGapicGeneration. - * @param [properties] Properties to set - */ - constructor(properties?: google.api.ISelectiveGapicGeneration); - - /** SelectiveGapicGeneration methods. */ - public methods: string[]; - - /** SelectiveGapicGeneration generateOmittedAsInternal. */ - public generateOmittedAsInternal: boolean; - - /** - * Creates a SelectiveGapicGeneration message from a plain object. Also converts values to their respective internal types. - * @param object Plain object - * @returns SelectiveGapicGeneration - */ - public static fromObject(object: { [k: string]: any }): google.api.SelectiveGapicGeneration; - - /** - * Creates a plain object from a SelectiveGapicGeneration message. Also converts values to other types if specified. - * @param message SelectiveGapicGeneration - * @param [options] Conversion options - * @returns Plain object - */ - public static toObject(message: google.api.SelectiveGapicGeneration, options?: $protobuf.IConversionOptions): { [k: string]: any }; - - /** - * Converts this SelectiveGapicGeneration to JSON. - * @returns JSON object - */ - public toJSON(): { [k: string]: any }; - - /** - * Gets the default type url for SelectiveGapicGeneration - * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") - * @returns The default type url - */ - public static getTypeUrl(typeUrlPrefix?: string): string; - } - /** LaunchStage enum. */ type LaunchStage = "LAUNCH_STAGE_UNSPECIFIED"| "UNIMPLEMENTED"| "PRELAUNCH"| "EARLY_ACCESS"| "ALPHA"| "BETA"| "GA"| "DEPRECATED"; @@ -8724,6 +8599,108 @@ export namespace google { */ public static getTypeUrl(typeUrlPrefix?: string): string; } + + /** Properties of a RoutingRule. */ + interface IRoutingRule { + + /** RoutingRule routingParameters */ + routingParameters?: (google.api.IRoutingParameter[]|null); + } + + /** Represents a RoutingRule. */ + class RoutingRule implements IRoutingRule { + + /** + * Constructs a new RoutingRule. + * @param [properties] Properties to set + */ + constructor(properties?: google.api.IRoutingRule); + + /** RoutingRule routingParameters. */ + public routingParameters: google.api.IRoutingParameter[]; + + /** + * Creates a RoutingRule message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns RoutingRule + */ + public static fromObject(object: { [k: string]: any }): google.api.RoutingRule; + + /** + * Creates a plain object from a RoutingRule message. Also converts values to other types if specified. + * @param message RoutingRule + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.api.RoutingRule, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this RoutingRule to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for RoutingRule + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } + + /** Properties of a RoutingParameter. */ + interface IRoutingParameter { + + /** RoutingParameter field */ + field?: (string|null); + + /** RoutingParameter pathTemplate */ + pathTemplate?: (string|null); + } + + /** Represents a RoutingParameter. */ + class RoutingParameter implements IRoutingParameter { + + /** + * Constructs a new RoutingParameter. + * @param [properties] Properties to set + */ + constructor(properties?: google.api.IRoutingParameter); + + /** RoutingParameter field. */ + public field: string; + + /** RoutingParameter pathTemplate. */ + public pathTemplate: string; + + /** + * Creates a RoutingParameter message from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns RoutingParameter + */ + public static fromObject(object: { [k: string]: any }): google.api.RoutingParameter; + + /** + * Creates a plain object from a RoutingParameter message. Also converts values to other types if specified. + * @param message RoutingParameter + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject(message: google.api.RoutingParameter, options?: $protobuf.IConversionOptions): { [k: string]: any }; + + /** + * Converts this RoutingParameter to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; + + /** + * Gets the default type url for RoutingParameter + * @param [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns The default type url + */ + public static getTypeUrl(typeUrlPrefix?: string): string; + } } /** Namespace rpc. */ diff --git a/dev/protos/firestore_v1beta1_proto_api.js b/dev/protos/firestore_v1beta1_proto_api.js index de9ec31c7..fb7536527 100644 --- a/dev/protos/firestore_v1beta1_proto_api.js +++ b/dev/protos/firestore_v1beta1_proto_api.js @@ -5400,6 +5400,7 @@ * @property {Array.|null} [uninterpretedOption] MethodOptions uninterpretedOption * @property {google.api.IHttpRule|null} [".google.api.http"] MethodOptions .google.api.http * @property {Array.|null} [".google.api.methodSignature"] MethodOptions .google.api.methodSignature + * @property {google.api.IRoutingRule|null} [".google.api.routing"] MethodOptions .google.api.routing * @property {google.longrunning.IOperationInfo|null} [".google.longrunning.operationInfo"] MethodOptions .google.longrunning.operationInfo */ @@ -5468,6 +5469,14 @@ */ MethodOptions.prototype[".google.api.methodSignature"] = $util.emptyArray; + /** + * MethodOptions .google.api.routing. + * @member {google.api.IRoutingRule|null|undefined} .google.api.routing + * @memberof google.protobuf.MethodOptions + * @instance + */ + MethodOptions.prototype[".google.api.routing"] = null; + /** * MethodOptions .google.longrunning.operationInfo. * @member {google.longrunning.IOperationInfo|null|undefined} .google.longrunning.operationInfo @@ -5537,6 +5546,11 @@ for (var i = 0; i < object[".google.api.methodSignature"].length; ++i) message[".google.api.methodSignature"][i] = String(object[".google.api.methodSignature"][i]); } + if (object[".google.api.routing"] != null) { + if (typeof object[".google.api.routing"] !== "object") + throw TypeError(".google.protobuf.MethodOptions..google.api.routing: object expected"); + message[".google.api.routing"] = $root.google.api.RoutingRule.fromObject(object[".google.api.routing"]); + } if (object[".google.longrunning.operationInfo"] != null) { if (typeof object[".google.longrunning.operationInfo"] !== "object") throw TypeError(".google.protobuf.MethodOptions..google.longrunning.operationInfo: object expected"); @@ -5568,6 +5582,7 @@ object.features = null; object[".google.longrunning.operationInfo"] = null; object[".google.api.http"] = null; + object[".google.api.routing"] = null; } if (message.deprecated != null && message.hasOwnProperty("deprecated")) object.deprecated = message.deprecated; @@ -5589,6 +5604,8 @@ } if (message[".google.api.http"] != null && message.hasOwnProperty(".google.api.http")) object[".google.api.http"] = $root.google.api.HttpRule.toObject(message[".google.api.http"], options); + if (message[".google.api.routing"] != null && message.hasOwnProperty(".google.api.routing")) + object[".google.api.routing"] = $root.google.api.RoutingRule.toObject(message[".google.api.routing"], options); return object; }; @@ -18839,7 +18856,6 @@ * @interface ICommonLanguageSettings * @property {string|null} [referenceDocsUri] CommonLanguageSettings referenceDocsUri * @property {Array.|null} [destinations] CommonLanguageSettings destinations - * @property {google.api.ISelectiveGapicGeneration|null} [selectiveGapicGeneration] CommonLanguageSettings selectiveGapicGeneration */ /** @@ -18874,14 +18890,6 @@ */ CommonLanguageSettings.prototype.destinations = $util.emptyArray; - /** - * CommonLanguageSettings selectiveGapicGeneration. - * @member {google.api.ISelectiveGapicGeneration|null|undefined} selectiveGapicGeneration - * @memberof google.api.CommonLanguageSettings - * @instance - */ - CommonLanguageSettings.prototype.selectiveGapicGeneration = null; - /** * Creates a CommonLanguageSettings message from a plain object. Also converts values to their respective internal types. * @function fromObject @@ -18921,11 +18929,6 @@ break; } } - if (object.selectiveGapicGeneration != null) { - if (typeof object.selectiveGapicGeneration !== "object") - throw TypeError(".google.api.CommonLanguageSettings.selectiveGapicGeneration: object expected"); - message.selectiveGapicGeneration = $root.google.api.SelectiveGapicGeneration.fromObject(object.selectiveGapicGeneration); - } return message; }; @@ -18944,10 +18947,8 @@ var object = {}; if (options.arrays || options.defaults) object.destinations = []; - if (options.defaults) { + if (options.defaults) object.referenceDocsUri = ""; - object.selectiveGapicGeneration = null; - } if (message.referenceDocsUri != null && message.hasOwnProperty("referenceDocsUri")) object.referenceDocsUri = message.referenceDocsUri; if (message.destinations && message.destinations.length) { @@ -18955,8 +18956,6 @@ for (var j = 0; j < message.destinations.length; ++j) object.destinations[j] = options.enums === String ? $root.google.api.ClientLibraryDestination[message.destinations[j]] === undefined ? message.destinations[j] : $root.google.api.ClientLibraryDestination[message.destinations[j]] : message.destinations[j]; } - if (message.selectiveGapicGeneration != null && message.hasOwnProperty("selectiveGapicGeneration")) - object.selectiveGapicGeneration = $root.google.api.SelectiveGapicGeneration.toObject(message.selectiveGapicGeneration, options); return object; }; @@ -19952,7 +19951,6 @@ * @memberof google.api * @interface IPythonSettings * @property {google.api.ICommonLanguageSettings|null} [common] PythonSettings common - * @property {google.api.PythonSettings.IExperimentalFeatures|null} [experimentalFeatures] PythonSettings experimentalFeatures */ /** @@ -19978,14 +19976,6 @@ */ PythonSettings.prototype.common = null; - /** - * PythonSettings experimentalFeatures. - * @member {google.api.PythonSettings.IExperimentalFeatures|null|undefined} experimentalFeatures - * @memberof google.api.PythonSettings - * @instance - */ - PythonSettings.prototype.experimentalFeatures = null; - /** * Creates a PythonSettings message from a plain object. Also converts values to their respective internal types. * @function fromObject @@ -20003,11 +19993,6 @@ throw TypeError(".google.api.PythonSettings.common: object expected"); message.common = $root.google.api.CommonLanguageSettings.fromObject(object.common); } - if (object.experimentalFeatures != null) { - if (typeof object.experimentalFeatures !== "object") - throw TypeError(".google.api.PythonSettings.experimentalFeatures: object expected"); - message.experimentalFeatures = $root.google.api.PythonSettings.ExperimentalFeatures.fromObject(object.experimentalFeatures); - } return message; }; @@ -20024,14 +20009,10 @@ if (!options) options = {}; var object = {}; - if (options.defaults) { + if (options.defaults) object.common = null; - object.experimentalFeatures = null; - } if (message.common != null && message.hasOwnProperty("common")) object.common = $root.google.api.CommonLanguageSettings.toObject(message.common, options); - if (message.experimentalFeatures != null && message.hasOwnProperty("experimentalFeatures")) - object.experimentalFeatures = $root.google.api.PythonSettings.ExperimentalFeatures.toObject(message.experimentalFeatures, options); return object; }; @@ -20061,119 +20042,6 @@ return typeUrlPrefix + "/google.api.PythonSettings"; }; - PythonSettings.ExperimentalFeatures = (function() { - - /** - * Properties of an ExperimentalFeatures. - * @memberof google.api.PythonSettings - * @interface IExperimentalFeatures - * @property {boolean|null} [restAsyncIoEnabled] ExperimentalFeatures restAsyncIoEnabled - * @property {boolean|null} [protobufPythonicTypesEnabled] ExperimentalFeatures protobufPythonicTypesEnabled - */ - - /** - * Constructs a new ExperimentalFeatures. - * @memberof google.api.PythonSettings - * @classdesc Represents an ExperimentalFeatures. - * @implements IExperimentalFeatures - * @constructor - * @param {google.api.PythonSettings.IExperimentalFeatures=} [properties] Properties to set - */ - function ExperimentalFeatures(properties) { - if (properties) - for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) - if (properties[keys[i]] != null) - this[keys[i]] = properties[keys[i]]; - } - - /** - * ExperimentalFeatures restAsyncIoEnabled. - * @member {boolean} restAsyncIoEnabled - * @memberof google.api.PythonSettings.ExperimentalFeatures - * @instance - */ - ExperimentalFeatures.prototype.restAsyncIoEnabled = false; - - /** - * ExperimentalFeatures protobufPythonicTypesEnabled. - * @member {boolean} protobufPythonicTypesEnabled - * @memberof google.api.PythonSettings.ExperimentalFeatures - * @instance - */ - ExperimentalFeatures.prototype.protobufPythonicTypesEnabled = false; - - /** - * Creates an ExperimentalFeatures message from a plain object. Also converts values to their respective internal types. - * @function fromObject - * @memberof google.api.PythonSettings.ExperimentalFeatures - * @static - * @param {Object.} object Plain object - * @returns {google.api.PythonSettings.ExperimentalFeatures} ExperimentalFeatures - */ - ExperimentalFeatures.fromObject = function fromObject(object) { - if (object instanceof $root.google.api.PythonSettings.ExperimentalFeatures) - return object; - var message = new $root.google.api.PythonSettings.ExperimentalFeatures(); - if (object.restAsyncIoEnabled != null) - message.restAsyncIoEnabled = Boolean(object.restAsyncIoEnabled); - if (object.protobufPythonicTypesEnabled != null) - message.protobufPythonicTypesEnabled = Boolean(object.protobufPythonicTypesEnabled); - return message; - }; - - /** - * Creates a plain object from an ExperimentalFeatures message. Also converts values to other types if specified. - * @function toObject - * @memberof google.api.PythonSettings.ExperimentalFeatures - * @static - * @param {google.api.PythonSettings.ExperimentalFeatures} message ExperimentalFeatures - * @param {$protobuf.IConversionOptions} [options] Conversion options - * @returns {Object.} Plain object - */ - ExperimentalFeatures.toObject = function toObject(message, options) { - if (!options) - options = {}; - var object = {}; - if (options.defaults) { - object.restAsyncIoEnabled = false; - object.protobufPythonicTypesEnabled = false; - } - if (message.restAsyncIoEnabled != null && message.hasOwnProperty("restAsyncIoEnabled")) - object.restAsyncIoEnabled = message.restAsyncIoEnabled; - if (message.protobufPythonicTypesEnabled != null && message.hasOwnProperty("protobufPythonicTypesEnabled")) - object.protobufPythonicTypesEnabled = message.protobufPythonicTypesEnabled; - return object; - }; - - /** - * Converts this ExperimentalFeatures to JSON. - * @function toJSON - * @memberof google.api.PythonSettings.ExperimentalFeatures - * @instance - * @returns {Object.} JSON object - */ - ExperimentalFeatures.prototype.toJSON = function toJSON() { - return this.constructor.toObject(this, $protobuf.util.toJSONOptions); - }; - - /** - * Gets the default type url for ExperimentalFeatures - * @function getTypeUrl - * @memberof google.api.PythonSettings.ExperimentalFeatures - * @static - * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") - * @returns {string} The default type url - */ - ExperimentalFeatures.getTypeUrl = function getTypeUrl(typeUrlPrefix) { - if (typeUrlPrefix === undefined) { - typeUrlPrefix = "type.googleapis.com"; - } - return typeUrlPrefix + "/google.api.PythonSettings.ExperimentalFeatures"; - }; - - return ExperimentalFeatures; - })(); - return PythonSettings; })(); @@ -20607,7 +20475,6 @@ * @memberof google.api * @interface IGoSettings * @property {google.api.ICommonLanguageSettings|null} [common] GoSettings common - * @property {Object.|null} [renamedServices] GoSettings renamedServices */ /** @@ -20619,7 +20486,6 @@ * @param {google.api.IGoSettings=} [properties] Properties to set */ function GoSettings(properties) { - this.renamedServices = {}; if (properties) for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) if (properties[keys[i]] != null) @@ -20634,14 +20500,6 @@ */ GoSettings.prototype.common = null; - /** - * GoSettings renamedServices. - * @member {Object.} renamedServices - * @memberof google.api.GoSettings - * @instance - */ - GoSettings.prototype.renamedServices = $util.emptyObject; - /** * Creates a GoSettings message from a plain object. Also converts values to their respective internal types. * @function fromObject @@ -20659,13 +20517,6 @@ throw TypeError(".google.api.GoSettings.common: object expected"); message.common = $root.google.api.CommonLanguageSettings.fromObject(object.common); } - if (object.renamedServices) { - if (typeof object.renamedServices !== "object") - throw TypeError(".google.api.GoSettings.renamedServices: object expected"); - message.renamedServices = {}; - for (var keys = Object.keys(object.renamedServices), i = 0; i < keys.length; ++i) - message.renamedServices[keys[i]] = String(object.renamedServices[keys[i]]); - } return message; }; @@ -20682,18 +20533,10 @@ if (!options) options = {}; var object = {}; - if (options.objects || options.defaults) - object.renamedServices = {}; if (options.defaults) object.common = null; if (message.common != null && message.hasOwnProperty("common")) object.common = $root.google.api.CommonLanguageSettings.toObject(message.common, options); - var keys2; - if (message.renamedServices && (keys2 = Object.keys(message.renamedServices)).length) { - object.renamedServices = {}; - for (var j = 0; j < keys2.length; ++j) - object.renamedServices[keys2[j]] = message.renamedServices[keys2[j]]; - } return object; }; @@ -21058,128 +20901,6 @@ return values; })(); - api.SelectiveGapicGeneration = (function() { - - /** - * Properties of a SelectiveGapicGeneration. - * @memberof google.api - * @interface ISelectiveGapicGeneration - * @property {Array.|null} [methods] SelectiveGapicGeneration methods - * @property {boolean|null} [generateOmittedAsInternal] SelectiveGapicGeneration generateOmittedAsInternal - */ - - /** - * Constructs a new SelectiveGapicGeneration. - * @memberof google.api - * @classdesc Represents a SelectiveGapicGeneration. - * @implements ISelectiveGapicGeneration - * @constructor - * @param {google.api.ISelectiveGapicGeneration=} [properties] Properties to set - */ - function SelectiveGapicGeneration(properties) { - this.methods = []; - if (properties) - for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) - if (properties[keys[i]] != null) - this[keys[i]] = properties[keys[i]]; - } - - /** - * SelectiveGapicGeneration methods. - * @member {Array.} methods - * @memberof google.api.SelectiveGapicGeneration - * @instance - */ - SelectiveGapicGeneration.prototype.methods = $util.emptyArray; - - /** - * SelectiveGapicGeneration generateOmittedAsInternal. - * @member {boolean} generateOmittedAsInternal - * @memberof google.api.SelectiveGapicGeneration - * @instance - */ - SelectiveGapicGeneration.prototype.generateOmittedAsInternal = false; - - /** - * Creates a SelectiveGapicGeneration message from a plain object. Also converts values to their respective internal types. - * @function fromObject - * @memberof google.api.SelectiveGapicGeneration - * @static - * @param {Object.} object Plain object - * @returns {google.api.SelectiveGapicGeneration} SelectiveGapicGeneration - */ - SelectiveGapicGeneration.fromObject = function fromObject(object) { - if (object instanceof $root.google.api.SelectiveGapicGeneration) - return object; - var message = new $root.google.api.SelectiveGapicGeneration(); - if (object.methods) { - if (!Array.isArray(object.methods)) - throw TypeError(".google.api.SelectiveGapicGeneration.methods: array expected"); - message.methods = []; - for (var i = 0; i < object.methods.length; ++i) - message.methods[i] = String(object.methods[i]); - } - if (object.generateOmittedAsInternal != null) - message.generateOmittedAsInternal = Boolean(object.generateOmittedAsInternal); - return message; - }; - - /** - * Creates a plain object from a SelectiveGapicGeneration message. Also converts values to other types if specified. - * @function toObject - * @memberof google.api.SelectiveGapicGeneration - * @static - * @param {google.api.SelectiveGapicGeneration} message SelectiveGapicGeneration - * @param {$protobuf.IConversionOptions} [options] Conversion options - * @returns {Object.} Plain object - */ - SelectiveGapicGeneration.toObject = function toObject(message, options) { - if (!options) - options = {}; - var object = {}; - if (options.arrays || options.defaults) - object.methods = []; - if (options.defaults) - object.generateOmittedAsInternal = false; - if (message.methods && message.methods.length) { - object.methods = []; - for (var j = 0; j < message.methods.length; ++j) - object.methods[j] = message.methods[j]; - } - if (message.generateOmittedAsInternal != null && message.hasOwnProperty("generateOmittedAsInternal")) - object.generateOmittedAsInternal = message.generateOmittedAsInternal; - return object; - }; - - /** - * Converts this SelectiveGapicGeneration to JSON. - * @function toJSON - * @memberof google.api.SelectiveGapicGeneration - * @instance - * @returns {Object.} JSON object - */ - SelectiveGapicGeneration.prototype.toJSON = function toJSON() { - return this.constructor.toObject(this, $protobuf.util.toJSONOptions); - }; - - /** - * Gets the default type url for SelectiveGapicGeneration - * @function getTypeUrl - * @memberof google.api.SelectiveGapicGeneration - * @static - * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") - * @returns {string} The default type url - */ - SelectiveGapicGeneration.getTypeUrl = function getTypeUrl(typeUrlPrefix) { - if (typeUrlPrefix === undefined) { - typeUrlPrefix = "type.googleapis.com"; - } - return typeUrlPrefix + "/google.api.SelectiveGapicGeneration"; - }; - - return SelectiveGapicGeneration; - })(); - /** * LaunchStage enum. * @name google.api.LaunchStage @@ -21612,6 +21333,229 @@ return ResourceReference; })(); + api.RoutingRule = (function() { + + /** + * Properties of a RoutingRule. + * @memberof google.api + * @interface IRoutingRule + * @property {Array.|null} [routingParameters] RoutingRule routingParameters + */ + + /** + * Constructs a new RoutingRule. + * @memberof google.api + * @classdesc Represents a RoutingRule. + * @implements IRoutingRule + * @constructor + * @param {google.api.IRoutingRule=} [properties] Properties to set + */ + function RoutingRule(properties) { + this.routingParameters = []; + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } + + /** + * RoutingRule routingParameters. + * @member {Array.} routingParameters + * @memberof google.api.RoutingRule + * @instance + */ + RoutingRule.prototype.routingParameters = $util.emptyArray; + + /** + * Creates a RoutingRule message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.api.RoutingRule + * @static + * @param {Object.} object Plain object + * @returns {google.api.RoutingRule} RoutingRule + */ + RoutingRule.fromObject = function fromObject(object) { + if (object instanceof $root.google.api.RoutingRule) + return object; + var message = new $root.google.api.RoutingRule(); + if (object.routingParameters) { + if (!Array.isArray(object.routingParameters)) + throw TypeError(".google.api.RoutingRule.routingParameters: array expected"); + message.routingParameters = []; + for (var i = 0; i < object.routingParameters.length; ++i) { + if (typeof object.routingParameters[i] !== "object") + throw TypeError(".google.api.RoutingRule.routingParameters: object expected"); + message.routingParameters[i] = $root.google.api.RoutingParameter.fromObject(object.routingParameters[i]); + } + } + return message; + }; + + /** + * Creates a plain object from a RoutingRule message. Also converts values to other types if specified. + * @function toObject + * @memberof google.api.RoutingRule + * @static + * @param {google.api.RoutingRule} message RoutingRule + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + RoutingRule.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.arrays || options.defaults) + object.routingParameters = []; + if (message.routingParameters && message.routingParameters.length) { + object.routingParameters = []; + for (var j = 0; j < message.routingParameters.length; ++j) + object.routingParameters[j] = $root.google.api.RoutingParameter.toObject(message.routingParameters[j], options); + } + return object; + }; + + /** + * Converts this RoutingRule to JSON. + * @function toJSON + * @memberof google.api.RoutingRule + * @instance + * @returns {Object.} JSON object + */ + RoutingRule.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + + /** + * Gets the default type url for RoutingRule + * @function getTypeUrl + * @memberof google.api.RoutingRule + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + RoutingRule.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.api.RoutingRule"; + }; + + return RoutingRule; + })(); + + api.RoutingParameter = (function() { + + /** + * Properties of a RoutingParameter. + * @memberof google.api + * @interface IRoutingParameter + * @property {string|null} [field] RoutingParameter field + * @property {string|null} [pathTemplate] RoutingParameter pathTemplate + */ + + /** + * Constructs a new RoutingParameter. + * @memberof google.api + * @classdesc Represents a RoutingParameter. + * @implements IRoutingParameter + * @constructor + * @param {google.api.IRoutingParameter=} [properties] Properties to set + */ + function RoutingParameter(properties) { + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + if (properties[keys[i]] != null) + this[keys[i]] = properties[keys[i]]; + } + + /** + * RoutingParameter field. + * @member {string} field + * @memberof google.api.RoutingParameter + * @instance + */ + RoutingParameter.prototype.field = ""; + + /** + * RoutingParameter pathTemplate. + * @member {string} pathTemplate + * @memberof google.api.RoutingParameter + * @instance + */ + RoutingParameter.prototype.pathTemplate = ""; + + /** + * Creates a RoutingParameter message from a plain object. Also converts values to their respective internal types. + * @function fromObject + * @memberof google.api.RoutingParameter + * @static + * @param {Object.} object Plain object + * @returns {google.api.RoutingParameter} RoutingParameter + */ + RoutingParameter.fromObject = function fromObject(object) { + if (object instanceof $root.google.api.RoutingParameter) + return object; + var message = new $root.google.api.RoutingParameter(); + if (object.field != null) + message.field = String(object.field); + if (object.pathTemplate != null) + message.pathTemplate = String(object.pathTemplate); + return message; + }; + + /** + * Creates a plain object from a RoutingParameter message. Also converts values to other types if specified. + * @function toObject + * @memberof google.api.RoutingParameter + * @static + * @param {google.api.RoutingParameter} message RoutingParameter + * @param {$protobuf.IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + RoutingParameter.toObject = function toObject(message, options) { + if (!options) + options = {}; + var object = {}; + if (options.defaults) { + object.field = ""; + object.pathTemplate = ""; + } + if (message.field != null && message.hasOwnProperty("field")) + object.field = message.field; + if (message.pathTemplate != null && message.hasOwnProperty("pathTemplate")) + object.pathTemplate = message.pathTemplate; + return object; + }; + + /** + * Converts this RoutingParameter to JSON. + * @function toJSON + * @memberof google.api.RoutingParameter + * @instance + * @returns {Object.} JSON object + */ + RoutingParameter.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions); + }; + + /** + * Gets the default type url for RoutingParameter + * @function getTypeUrl + * @memberof google.api.RoutingParameter + * @static + * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") + * @returns {string} The default type url + */ + RoutingParameter.getTypeUrl = function getTypeUrl(typeUrlPrefix) { + if (typeUrlPrefix === undefined) { + typeUrlPrefix = "type.googleapis.com"; + } + return typeUrlPrefix + "/google.api.RoutingParameter"; + }; + + return RoutingParameter; + })(); + return api; })(); diff --git a/dev/protos/google/api/annotations.proto b/dev/protos/google/api/annotations.proto index 84c48164a..efdab3db6 100644 --- a/dev/protos/google/api/annotations.proto +++ b/dev/protos/google/api/annotations.proto @@ -1,4 +1,4 @@ -// Copyright 2024 Google LLC +// Copyright 2015 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. diff --git a/dev/protos/google/api/client.proto b/dev/protos/google/api/client.proto index 5bb9f9110..0952e8373 100644 --- a/dev/protos/google/api/client.proto +++ b/dev/protos/google/api/client.proto @@ -1,4 +1,4 @@ -// Copyright 2024 Google LLC +// Copyright 2023 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. @@ -124,9 +124,6 @@ message CommonLanguageSettings { // The destination where API teams want this client library to be published. repeated ClientLibraryDestination destinations = 2; - - // Configuration for which RPCs should be generated in the GAPIC client. - SelectiveGapicGeneration selective_gapic_generation = 3; } // Details about how and where to publish client libraries. @@ -266,28 +263,8 @@ message PhpSettings { // Settings for Python client libraries. message PythonSettings { - // Experimental features to be included during client library generation. - // These fields will be deprecated once the feature graduates and is enabled - // by default. - message ExperimentalFeatures { - // Enables generation of asynchronous REST clients if `rest` transport is - // enabled. By default, asynchronous REST clients will not be generated. - // This feature will be enabled by default 1 month after launching the - // feature in preview packages. - bool rest_async_io_enabled = 1; - - // Enables generation of protobuf code using new types that are more - // Pythonic which are included in `protobuf>=5.29.x`. This feature will be - // enabled by default 1 month after launching the feature in preview - // packages. - bool protobuf_pythonic_types_enabled = 2; - } - // Some settings. CommonLanguageSettings common = 1; - - // Experimental features to be included during client library generation. - ExperimentalFeatures experimental_features = 2; } // Settings for Node client libraries. @@ -342,16 +319,6 @@ message RubySettings { message GoSettings { // Some settings. CommonLanguageSettings common = 1; - - // Map of service names to renamed services. Keys are the package relative - // service names and values are the name to be used for the service client - // and call options. - // - // publishing: - // go_settings: - // renamed_services: - // Publisher: TopicAdmin - map renamed_services = 2; } // Describes the generator configuration for a method. @@ -382,13 +349,6 @@ message MethodSettings { // The fully qualified name of the method, for which the options below apply. // This is used to find the method to apply the options. - // - // Example: - // - // publishing: - // method_settings: - // - selector: google.storage.control.v2.StorageControl.CreateFolder - // # method settings for CreateFolder... string selector = 1; // Describes settings to use for long-running operations when generating @@ -397,14 +357,17 @@ message MethodSettings { // // Example of a YAML configuration:: // - // publishing: - // method_settings: + // publishing: + // method_settings: // - selector: google.cloud.speech.v2.Speech.BatchRecognize // long_running: - // initial_poll_delay: 60s # 1 minute + // initial_poll_delay: + // seconds: 60 # 1 minute // poll_delay_multiplier: 1.5 - // max_poll_delay: 360s # 6 minutes - // total_poll_timeout: 54000s # 90 minutes + // max_poll_delay: + // seconds: 360 # 6 minutes + // total_poll_timeout: + // seconds: 54000 # 90 minutes LongRunning long_running = 2; // List of top-level fields of the request message, that should be @@ -413,8 +376,8 @@ message MethodSettings { // // Example of a YAML configuration: // - // publishing: - // method_settings: + // publishing: + // method_settings: // - selector: google.example.v1.ExampleService.CreateExample // auto_populated_fields: // - request_id @@ -462,19 +425,3 @@ enum ClientLibraryDestination { // Publish the library to package managers like nuget.org and npmjs.com. PACKAGE_MANAGER = 20; } - -// This message is used to configure the generation of a subset of the RPCs in -// a service for client libraries. -message SelectiveGapicGeneration { - // An allowlist of the fully qualified names of RPCs that should be included - // on public client surfaces. - repeated string methods = 1; - - // Setting this to true indicates to the client generators that methods - // that would be excluded from the generation should instead be generated - // in a way that indicates these methods should not be consumed by - // end users. How this is expressed is up to individual language - // implementations to decide. Some examples may be: added annotations, - // obfuscated identifiers, or other language idiomatic patterns. - bool generate_omitted_as_internal = 2; -} diff --git a/dev/protos/google/api/field_behavior.proto b/dev/protos/google/api/field_behavior.proto index 2865ba053..21895bf55 100644 --- a/dev/protos/google/api/field_behavior.proto +++ b/dev/protos/google/api/field_behavior.proto @@ -1,4 +1,4 @@ -// Copyright 2024 Google LLC +// Copyright 2023 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. diff --git a/dev/protos/google/api/http.proto b/dev/protos/google/api/http.proto index e3270371d..31d867a27 100644 --- a/dev/protos/google/api/http.proto +++ b/dev/protos/google/api/http.proto @@ -1,4 +1,4 @@ -// Copyright 2024 Google LLC +// Copyright 2023 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. @@ -41,7 +41,7 @@ message Http { bool fully_decode_reserved_expansion = 2; } -// gRPC Transcoding +// # gRPC Transcoding // // gRPC Transcoding is a feature for mapping between a gRPC method and one or // more HTTP REST endpoints. It allows developers to build a single API service @@ -82,8 +82,9 @@ message Http { // // This enables an HTTP REST to gRPC mapping as below: // -// - HTTP: `GET /v1/messages/123456` -// - gRPC: `GetMessage(name: "messages/123456")` +// HTTP | gRPC +// -----|----- +// `GET /v1/messages/123456` | `GetMessage(name: "messages/123456")` // // Any fields in the request message which are not bound by the path template // automatically become HTTP query parameters if there is no HTTP request body. @@ -107,9 +108,11 @@ message Http { // // This enables a HTTP JSON to RPC mapping as below: // -// - HTTP: `GET /v1/messages/123456?revision=2&sub.subfield=foo` -// - gRPC: `GetMessage(message_id: "123456" revision: 2 sub: -// SubMessage(subfield: "foo"))` +// HTTP | gRPC +// -----|----- +// `GET /v1/messages/123456?revision=2&sub.subfield=foo` | +// `GetMessage(message_id: "123456" revision: 2 sub: SubMessage(subfield: +// "foo"))` // // Note that fields which are mapped to URL query parameters must have a // primitive type or a repeated primitive type or a non-repeated message type. @@ -139,8 +142,10 @@ message Http { // representation of the JSON in the request body is determined by // protos JSON encoding: // -// - HTTP: `PATCH /v1/messages/123456 { "text": "Hi!" }` -// - gRPC: `UpdateMessage(message_id: "123456" message { text: "Hi!" })` +// HTTP | gRPC +// -----|----- +// `PATCH /v1/messages/123456 { "text": "Hi!" }` | `UpdateMessage(message_id: +// "123456" message { text: "Hi!" })` // // The special name `*` can be used in the body mapping to define that // every field not bound by the path template should be mapped to the @@ -163,8 +168,10 @@ message Http { // // The following HTTP JSON to RPC mapping is enabled: // -// - HTTP: `PATCH /v1/messages/123456 { "text": "Hi!" }` -// - gRPC: `UpdateMessage(message_id: "123456" text: "Hi!")` +// HTTP | gRPC +// -----|----- +// `PATCH /v1/messages/123456 { "text": "Hi!" }` | `UpdateMessage(message_id: +// "123456" text: "Hi!")` // // Note that when using `*` in the body mapping, it is not possible to // have HTTP parameters, as all fields not bound by the path end in @@ -192,13 +199,13 @@ message Http { // // This enables the following two alternative HTTP JSON to RPC mappings: // -// - HTTP: `GET /v1/messages/123456` -// - gRPC: `GetMessage(message_id: "123456")` +// HTTP | gRPC +// -----|----- +// `GET /v1/messages/123456` | `GetMessage(message_id: "123456")` +// `GET /v1/users/me/messages/123456` | `GetMessage(user_id: "me" message_id: +// "123456")` // -// - HTTP: `GET /v1/users/me/messages/123456` -// - gRPC: `GetMessage(user_id: "me" message_id: "123456")` -// -// Rules for HTTP mapping +// ## Rules for HTTP mapping // // 1. Leaf request fields (recursive expansion nested messages in the request // message) are classified into three categories: @@ -217,7 +224,7 @@ message Http { // request body, all // fields are passed via URL path and URL query parameters. // -// Path template syntax +// ### Path template syntax // // Template = "/" Segments [ Verb ] ; // Segments = Segment { "/" Segment } ; @@ -256,7 +263,7 @@ message Http { // Document](https://developers.google.com/discovery/v1/reference/apis) as // `{+var}`. // -// Using gRPC API Service Configuration +// ## Using gRPC API Service Configuration // // gRPC API Service Configuration (service config) is a configuration language // for configuring a gRPC service to become a user-facing product. The @@ -271,14 +278,15 @@ message Http { // specified in the service config will override any matching transcoding // configuration in the proto. // -// The following example selects a gRPC method and applies an `HttpRule` to it: +// Example: // // http: // rules: +// # Selects a gRPC method and applies HttpRule to it. // - selector: example.v1.Messaging.GetMessage // get: /v1/messages/{message_id}/{sub.subfield} // -// Special notes +// ## Special notes // // When gRPC Transcoding is used to map a gRPC to JSON REST endpoints, the // proto to JSON conversion must follow the [proto3 diff --git a/dev/protos/google/api/launch_stage.proto b/dev/protos/google/api/launch_stage.proto index 9863fc23d..9802de795 100644 --- a/dev/protos/google/api/launch_stage.proto +++ b/dev/protos/google/api/launch_stage.proto @@ -1,4 +1,4 @@ -// Copyright 2024 Google LLC +// Copyright 2023 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. diff --git a/dev/protos/google/api/resource.proto b/dev/protos/google/api/resource.proto index 3762af84a..bf0cbec5d 100644 --- a/dev/protos/google/api/resource.proto +++ b/dev/protos/google/api/resource.proto @@ -1,4 +1,4 @@ -// Copyright 2024 Google LLC +// Copyright 2023 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. @@ -179,13 +179,8 @@ message ResourceDescriptor { // The plural name used in the resource name and permission names, such as // 'projects' for the resource name of 'projects/{project}' and the permission - // name of 'cloudresourcemanager.googleapis.com/projects.get'. One exception - // to this is for Nested Collections that have stuttering names, as defined - // in [AIP-122](https://google.aip.dev/122#nested-collections), where the - // collection ID in the resource name pattern does not necessarily directly - // match the `plural` value. - // - // It is the same concept of the `plural` field in k8s CRD spec + // name of 'cloudresourcemanager.googleapis.com/projects.get'. It is the same + // concept of the `plural` field in k8s CRD spec // https://kubernetes.io/docs/tasks/access-kubernetes-api/custom-resources/custom-resource-definitions/ // // Note: The plural form is required even for singleton resources. See diff --git a/dev/protos/google/api/routing.proto b/dev/protos/google/api/routing.proto new file mode 100644 index 000000000..b35289be8 --- /dev/null +++ b/dev/protos/google/api/routing.proto @@ -0,0 +1,461 @@ +// Copyright 2023 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. + +syntax = "proto3"; + +package google.api; + +import "google/protobuf/descriptor.proto"; + +option go_package = "google.golang.org/genproto/googleapis/api/annotations;annotations"; +option java_multiple_files = true; +option java_outer_classname = "RoutingProto"; +option java_package = "com.google.api"; +option objc_class_prefix = "GAPI"; + +extend google.protobuf.MethodOptions { + // See RoutingRule. + google.api.RoutingRule routing = 72295729; +} + +// Specifies the routing information that should be sent along with the request +// in the form of routing header. +// **NOTE:** All service configuration rules follow the "last one wins" order. +// +// The examples below will apply to an RPC which has the following request type: +// +// Message Definition: +// +// message Request { +// // The name of the Table +// // Values can be of the following formats: +// // - `projects//tables/` +// // - `projects//instances//tables/
` +// // - `region//zones//tables/
` +// string table_name = 1; +// +// // This value specifies routing for replication. +// // It can be in the following formats: +// // - `profiles/` +// // - a legacy `profile_id` that can be any string +// string app_profile_id = 2; +// } +// +// Example message: +// +// { +// table_name: projects/proj_foo/instances/instance_bar/table/table_baz, +// app_profile_id: profiles/prof_qux +// } +// +// The routing header consists of one or multiple key-value pairs. Every key +// and value must be percent-encoded, and joined together in the format of +// `key1=value1&key2=value2`. +// In the examples below I am skipping the percent-encoding for readablity. +// +// Example 1 +// +// Extracting a field from the request to put into the routing header +// unchanged, with the key equal to the field name. +// +// annotation: +// +// option (google.api.routing) = { +// // Take the `app_profile_id`. +// routing_parameters { +// field: "app_profile_id" +// } +// }; +// +// result: +// +// x-goog-request-params: app_profile_id=profiles/prof_qux +// +// Example 2 +// +// Extracting a field from the request to put into the routing header +// unchanged, with the key different from the field name. +// +// annotation: +// +// option (google.api.routing) = { +// // Take the `app_profile_id`, but name it `routing_id` in the header. +// routing_parameters { +// field: "app_profile_id" +// path_template: "{routing_id=**}" +// } +// }; +// +// result: +// +// x-goog-request-params: routing_id=profiles/prof_qux +// +// Example 3 +// +// Extracting a field from the request to put into the routing +// header, while matching a path template syntax on the field's value. +// +// NB: it is more useful to send nothing than to send garbage for the purpose +// of dynamic routing, since garbage pollutes cache. Thus the matching. +// +// Sub-example 3a +// +// The field matches the template. +// +// annotation: +// +// option (google.api.routing) = { +// // Take the `table_name`, if it's well-formed (with project-based +// // syntax). +// routing_parameters { +// field: "table_name" +// path_template: "{table_name=projects/*/instances/*/**}" +// } +// }; +// +// result: +// +// x-goog-request-params: +// table_name=projects/proj_foo/instances/instance_bar/table/table_baz +// +// Sub-example 3b +// +// The field does not match the template. +// +// annotation: +// +// option (google.api.routing) = { +// // Take the `table_name`, if it's well-formed (with region-based +// // syntax). +// routing_parameters { +// field: "table_name" +// path_template: "{table_name=regions/*/zones/*/**}" +// } +// }; +// +// result: +// +// +// +// Sub-example 3c +// +// Multiple alternative conflictingly named path templates are +// specified. The one that matches is used to construct the header. +// +// annotation: +// +// option (google.api.routing) = { +// // Take the `table_name`, if it's well-formed, whether +// // using the region- or projects-based syntax. +// +// routing_parameters { +// field: "table_name" +// path_template: "{table_name=regions/*/zones/*/**}" +// } +// routing_parameters { +// field: "table_name" +// path_template: "{table_name=projects/*/instances/*/**}" +// } +// }; +// +// result: +// +// x-goog-request-params: +// table_name=projects/proj_foo/instances/instance_bar/table/table_baz +// +// Example 4 +// +// Extracting a single routing header key-value pair by matching a +// template syntax on (a part of) a single request field. +// +// annotation: +// +// option (google.api.routing) = { +// // Take just the project id from the `table_name` field. +// routing_parameters { +// field: "table_name" +// path_template: "{routing_id=projects/*}/**" +// } +// }; +// +// result: +// +// x-goog-request-params: routing_id=projects/proj_foo +// +// Example 5 +// +// Extracting a single routing header key-value pair by matching +// several conflictingly named path templates on (parts of) a single request +// field. The last template to match "wins" the conflict. +// +// annotation: +// +// option (google.api.routing) = { +// // If the `table_name` does not have instances information, +// // take just the project id for routing. +// // Otherwise take project + instance. +// +// routing_parameters { +// field: "table_name" +// path_template: "{routing_id=projects/*}/**" +// } +// routing_parameters { +// field: "table_name" +// path_template: "{routing_id=projects/*/instances/*}/**" +// } +// }; +// +// result: +// +// x-goog-request-params: +// routing_id=projects/proj_foo/instances/instance_bar +// +// Example 6 +// +// Extracting multiple routing header key-value pairs by matching +// several non-conflicting path templates on (parts of) a single request field. +// +// Sub-example 6a +// +// Make the templates strict, so that if the `table_name` does not +// have an instance information, nothing is sent. +// +// annotation: +// +// option (google.api.routing) = { +// // The routing code needs two keys instead of one composite +// // but works only for the tables with the "project-instance" name +// // syntax. +// +// routing_parameters { +// field: "table_name" +// path_template: "{project_id=projects/*}/instances/*/**" +// } +// routing_parameters { +// field: "table_name" +// path_template: "projects/*/{instance_id=instances/*}/**" +// } +// }; +// +// result: +// +// x-goog-request-params: +// project_id=projects/proj_foo&instance_id=instances/instance_bar +// +// Sub-example 6b +// +// Make the templates loose, so that if the `table_name` does not +// have an instance information, just the project id part is sent. +// +// annotation: +// +// option (google.api.routing) = { +// // The routing code wants two keys instead of one composite +// // but will work with just the `project_id` for tables without +// // an instance in the `table_name`. +// +// routing_parameters { +// field: "table_name" +// path_template: "{project_id=projects/*}/**" +// } +// routing_parameters { +// field: "table_name" +// path_template: "projects/*/{instance_id=instances/*}/**" +// } +// }; +// +// result (is the same as 6a for our example message because it has the instance +// information): +// +// x-goog-request-params: +// project_id=projects/proj_foo&instance_id=instances/instance_bar +// +// Example 7 +// +// Extracting multiple routing header key-value pairs by matching +// several path templates on multiple request fields. +// +// NB: note that here there is no way to specify sending nothing if one of the +// fields does not match its template. E.g. if the `table_name` is in the wrong +// format, the `project_id` will not be sent, but the `routing_id` will be. +// The backend routing code has to be aware of that and be prepared to not +// receive a full complement of keys if it expects multiple. +// +// annotation: +// +// option (google.api.routing) = { +// // The routing needs both `project_id` and `routing_id` +// // (from the `app_profile_id` field) for routing. +// +// routing_parameters { +// field: "table_name" +// path_template: "{project_id=projects/*}/**" +// } +// routing_parameters { +// field: "app_profile_id" +// path_template: "{routing_id=**}" +// } +// }; +// +// result: +// +// x-goog-request-params: +// project_id=projects/proj_foo&routing_id=profiles/prof_qux +// +// Example 8 +// +// Extracting a single routing header key-value pair by matching +// several conflictingly named path templates on several request fields. The +// last template to match "wins" the conflict. +// +// annotation: +// +// option (google.api.routing) = { +// // The `routing_id` can be a project id or a region id depending on +// // the table name format, but only if the `app_profile_id` is not set. +// // If `app_profile_id` is set it should be used instead. +// +// routing_parameters { +// field: "table_name" +// path_template: "{routing_id=projects/*}/**" +// } +// routing_parameters { +// field: "table_name" +// path_template: "{routing_id=regions/*}/**" +// } +// routing_parameters { +// field: "app_profile_id" +// path_template: "{routing_id=**}" +// } +// }; +// +// result: +// +// x-goog-request-params: routing_id=profiles/prof_qux +// +// Example 9 +// +// Bringing it all together. +// +// annotation: +// +// option (google.api.routing) = { +// // For routing both `table_location` and a `routing_id` are needed. +// // +// // table_location can be either an instance id or a region+zone id. +// // +// // For `routing_id`, take the value of `app_profile_id` +// // - If it's in the format `profiles/`, send +// // just the `` part. +// // - If it's any other literal, send it as is. +// // If the `app_profile_id` is empty, and the `table_name` starts with +// // the project_id, send that instead. +// +// routing_parameters { +// field: "table_name" +// path_template: "projects/*/{table_location=instances/*}/tables/*" +// } +// routing_parameters { +// field: "table_name" +// path_template: "{table_location=regions/*/zones/*}/tables/*" +// } +// routing_parameters { +// field: "table_name" +// path_template: "{routing_id=projects/*}/**" +// } +// routing_parameters { +// field: "app_profile_id" +// path_template: "{routing_id=**}" +// } +// routing_parameters { +// field: "app_profile_id" +// path_template: "profiles/{routing_id=*}" +// } +// }; +// +// result: +// +// x-goog-request-params: +// table_location=instances/instance_bar&routing_id=prof_qux +message RoutingRule { + // A collection of Routing Parameter specifications. + // **NOTE:** If multiple Routing Parameters describe the same key + // (via the `path_template` field or via the `field` field when + // `path_template` is not provided), "last one wins" rule + // determines which Parameter gets used. + // See the examples for more details. + repeated RoutingParameter routing_parameters = 2; +} + +// A projection from an input message to the GRPC or REST header. +message RoutingParameter { + // A request field to extract the header key-value pair from. + string field = 1; + + // A pattern matching the key-value field. Optional. + // If not specified, the whole field specified in the `field` field will be + // taken as value, and its name used as key. If specified, it MUST contain + // exactly one named segment (along with any number of unnamed segments) The + // pattern will be matched over the field specified in the `field` field, then + // if the match is successful: + // - the name of the single named segment will be used as a header name, + // - the match value of the segment will be used as a header value; + // if the match is NOT successful, nothing will be sent. + // + // Example: + // + // -- This is a field in the request message + // | that the header value will be extracted from. + // | + // | -- This is the key name in the + // | | routing header. + // V | + // field: "table_name" v + // path_template: "projects/*/{table_location=instances/*}/tables/*" + // ^ ^ + // | | + // In the {} brackets is the pattern that -- | + // specifies what to extract from the | + // field as a value to be sent. | + // | + // The string in the field must match the whole pattern -- + // before brackets, inside brackets, after brackets. + // + // When looking at this specific example, we can see that: + // - A key-value pair with the key `table_location` + // and the value matching `instances/*` should be added + // to the x-goog-request-params routing header. + // - The value is extracted from the request message's `table_name` field + // if it matches the full pattern specified: + // `projects/*/instances/*/tables/*`. + // + // **NB:** If the `path_template` field is not provided, the key name is + // equal to the field name, and the whole field should be sent as a value. + // This makes the pattern for the field and the value functionally equivalent + // to `**`, and the configuration + // + // { + // field: "table_name" + // } + // + // is a functionally equivalent shorthand to: + // + // { + // field: "table_name" + // path_template: "{table_name=**}" + // } + // + // See Example 1 for more details. + string path_template = 2; +} diff --git a/dev/protos/google/firestore/admin/v1/backup.proto b/dev/protos/google/firestore/admin/v1/backup.proto index 45f3adc8e..bed41ff66 100644 --- a/dev/protos/google/firestore/admin/v1/backup.proto +++ b/dev/protos/google/firestore/admin/v1/backup.proto @@ -1,4 +1,4 @@ -// Copyright 2024 Google LLC +// Copyright 2025 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. diff --git a/dev/protos/google/firestore/admin/v1/database.proto b/dev/protos/google/firestore/admin/v1/database.proto index 848e2ec76..923b2169d 100644 --- a/dev/protos/google/firestore/admin/v1/database.proto +++ b/dev/protos/google/firestore/admin/v1/database.proto @@ -1,4 +1,4 @@ -// Copyright 2024 Google LLC +// Copyright 2025 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. @@ -227,6 +227,20 @@ message Database { } } + // The edition of the database. + enum DatabaseEdition { + // Not used. + DATABASE_EDITION_UNSPECIFIED = 0; + + // Standard edition. + // + // This is the default setting if not specified. + STANDARD = 1; + + // Enterprise edition. + ENTERPRISE = 2; + } + // The resource name of the Database. // Format: `projects/{project}/databases/{database}` string name = 1; @@ -314,8 +328,25 @@ message Database { // Output only. Information about the provenance of this database. SourceInfo source_info = 26 [(google.api.field_behavior) = OUTPUT_ONLY]; + // Output only. Background: Free tier is the ability of a Firestore database + // to use a small amount of resources every day without being charged. Once + // usage exceeds the free tier limit further usage is charged. + // + // Whether this database can make use of the free tier. Only one database + // per project can be eligible for the free tier. + // + // The first (or next) database that is created in a project without a free + // tier database will be marked as eligible for the free tier. Databases that + // are created while there is a free tier database will not be eligible for + // the free tier. + optional bool free_tier = 30 [(google.api.field_behavior) = OUTPUT_ONLY]; + // This checksum is computed by the server based on the value of other // fields, and may be sent on update and delete requests to ensure the // client has an up-to-date value before proceeding. string etag = 99; + + // Immutable. The edition of the database. + DatabaseEdition database_edition = 28 + [(google.api.field_behavior) = IMMUTABLE]; } diff --git a/dev/protos/google/firestore/admin/v1/field.proto b/dev/protos/google/firestore/admin/v1/field.proto index e187b45d4..d899bdb5c 100644 --- a/dev/protos/google/firestore/admin/v1/field.proto +++ b/dev/protos/google/firestore/admin/v1/field.proto @@ -1,4 +1,4 @@ -// Copyright 2024 Google LLC +// Copyright 2025 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. diff --git a/dev/protos/google/firestore/admin/v1/firestore_admin.proto b/dev/protos/google/firestore/admin/v1/firestore_admin.proto index 84026cea9..8ddcc7a3a 100644 --- a/dev/protos/google/firestore/admin/v1/firestore_admin.proto +++ b/dev/protos/google/firestore/admin/v1/firestore_admin.proto @@ -1,4 +1,4 @@ -// Copyright 2024 Google LLC +// Copyright 2025 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. @@ -26,6 +26,7 @@ import "google/firestore/admin/v1/field.proto"; import "google/firestore/admin/v1/index.proto"; import "google/firestore/admin/v1/operation.proto"; import "google/firestore/admin/v1/schedule.proto"; +import "google/firestore/admin/v1/user_creds.proto"; import "google/longrunning/operations.proto"; import "google/protobuf/empty.proto"; import "google/protobuf/field_mask.proto"; @@ -295,6 +296,68 @@ service FirestoreAdmin { }; } + // Create a user creds. + rpc CreateUserCreds(CreateUserCredsRequest) returns (UserCreds) { + option (google.api.http) = { + post: "/v1/{parent=projects/*/databases/*}/userCreds" + body: "user_creds" + }; + option (google.api.method_signature) = "parent,user_creds,user_creds_id"; + } + + // Gets a user creds resource. Note that the returned resource does not + // contain the secret value itself. + rpc GetUserCreds(GetUserCredsRequest) returns (UserCreds) { + option (google.api.http) = { + get: "/v1/{name=projects/*/databases/*/userCreds/*}" + }; + option (google.api.method_signature) = "name"; + } + + // List all user creds in the database. Note that the returned resource + // does not contain the secret value itself. + rpc ListUserCreds(ListUserCredsRequest) returns (ListUserCredsResponse) { + option (google.api.http) = { + get: "/v1/{parent=projects/*/databases/*}/userCreds" + }; + option (google.api.method_signature) = "parent"; + } + + // Enables a user creds. No-op if the user creds are already enabled. + rpc EnableUserCreds(EnableUserCredsRequest) returns (UserCreds) { + option (google.api.http) = { + post: "/v1/{name=projects/*/databases/*/userCreds/*}:enable" + body: "*" + }; + option (google.api.method_signature) = "name"; + } + + // Disables a user creds. No-op if the user creds are already disabled. + rpc DisableUserCreds(DisableUserCredsRequest) returns (UserCreds) { + option (google.api.http) = { + post: "/v1/{name=projects/*/databases/*/userCreds/*}:disable" + body: "*" + }; + option (google.api.method_signature) = "name"; + } + + // Resets the password of a user creds. + rpc ResetUserPassword(ResetUserPasswordRequest) returns (UserCreds) { + option (google.api.http) = { + post: "/v1/{name=projects/*/databases/*/userCreds/*}:resetPassword" + body: "*" + }; + option (google.api.method_signature) = "name"; + } + + // Deletes a user creds. + rpc DeleteUserCreds(DeleteUserCredsRequest) returns (google.protobuf.Empty) { + option (google.api.http) = { + delete: "/v1/{name=projects/*/databases/*/userCreds/*}" + }; + option (google.api.method_signature) = "name"; + } + // Gets information about a backup. rpc GetBackup(GetBackupRequest) returns (Backup) { option (google.api.http) = { @@ -505,6 +568,115 @@ message DeleteDatabaseRequest { // Metadata related to the delete database operation. message DeleteDatabaseMetadata {} +// The request for +// [FirestoreAdmin.CreateUserCreds][google.firestore.admin.v1.FirestoreAdmin.CreateUserCreds]. +message CreateUserCredsRequest { + // Required. A parent name of the form + // `projects/{project_id}/databases/{database_id}` + string parent = 1 [ + (google.api.field_behavior) = REQUIRED, + (google.api.resource_reference) = { + child_type: "firestore.googleapis.com/UserCreds" + } + ]; + + // Required. The user creds to create. + UserCreds user_creds = 2 [(google.api.field_behavior) = REQUIRED]; + + // Required. The ID to use for the user creds, which will become the final + // component of the user creds's resource name. + // + // This value should be 4-63 characters. Valid characters are /[a-z][0-9]-/ + // with first character a letter and the last a letter or a number. Must not + // be UUID-like /[0-9a-f]{8}(-[0-9a-f]{4}){3}-[0-9a-f]{12}/. + string user_creds_id = 3 [(google.api.field_behavior) = REQUIRED]; +} + +// The request for +// [FirestoreAdmin.GetUserCreds][google.firestore.admin.v1.FirestoreAdmin.GetUserCreds]. +message GetUserCredsRequest { + // Required. A name of the form + // `projects/{project_id}/databases/{database_id}/userCreds/{user_creds_id}` + string name = 1 [ + (google.api.field_behavior) = REQUIRED, + (google.api.resource_reference) = { + type: "firestore.googleapis.com/UserCreds" + } + ]; +} + +// The request for +// [FirestoreAdmin.ListUserCreds][google.firestore.admin.v1.FirestoreAdmin.ListUserCreds]. +message ListUserCredsRequest { + // Required. A parent database name of the form + // `projects/{project_id}/databases/{database_id}` + string parent = 1 [ + (google.api.field_behavior) = REQUIRED, + (google.api.resource_reference) = { + child_type: "firestore.googleapis.com/UserCreds" + } + ]; +} + +// The response for +// [FirestoreAdmin.ListUserCreds][google.firestore.admin.v1.FirestoreAdmin.ListUserCreds]. +message ListUserCredsResponse { + // The user creds for the database. + repeated UserCreds user_creds = 1; +} + +// The request for +// [FirestoreAdmin.EnableUserCreds][google.firestore.admin.v1.FirestoreAdmin.EnableUserCreds]. +message EnableUserCredsRequest { + // Required. A name of the form + // `projects/{project_id}/databases/{database_id}/userCreds/{user_creds_id}` + string name = 1 [ + (google.api.field_behavior) = REQUIRED, + (google.api.resource_reference) = { + type: "firestore.googleapis.com/UserCreds" + } + ]; +} + +// The request for +// [FirestoreAdmin.DisableUserCreds][google.firestore.admin.v1.FirestoreAdmin.DisableUserCreds]. +message DisableUserCredsRequest { + // Required. A name of the form + // `projects/{project_id}/databases/{database_id}/userCreds/{user_creds_id}` + string name = 1 [ + (google.api.field_behavior) = REQUIRED, + (google.api.resource_reference) = { + type: "firestore.googleapis.com/UserCreds" + } + ]; +} + +// The request for +// [FirestoreAdmin.ResetUserPassword][google.firestore.admin.v1.FirestoreAdmin.ResetUserPassword]. +message ResetUserPasswordRequest { + // Required. A name of the form + // `projects/{project_id}/databases/{database_id}/userCreds/{user_creds_id}` + string name = 1 [ + (google.api.field_behavior) = REQUIRED, + (google.api.resource_reference) = { + type: "firestore.googleapis.com/UserCreds" + } + ]; +} + +// The request for +// [FirestoreAdmin.DeleteUserCreds][google.firestore.admin.v1.FirestoreAdmin.DeleteUserCreds]. +message DeleteUserCredsRequest { + // Required. A name of the form + // `projects/{project_id}/databases/{database_id}/userCreds/{user_creds_id}` + string name = 1 [ + (google.api.field_behavior) = REQUIRED, + (google.api.resource_reference) = { + type: "firestore.googleapis.com/UserCreds" + } + ]; +} + // The request for // [FirestoreAdmin.CreateBackupSchedule][google.firestore.admin.v1.FirestoreAdmin.CreateBackupSchedule]. message CreateBackupScheduleRequest { diff --git a/dev/protos/google/firestore/admin/v1/index.proto b/dev/protos/google/firestore/admin/v1/index.proto index 1b8b0a48a..5dd4dc9fb 100644 --- a/dev/protos/google/firestore/admin/v1/index.proto +++ b/dev/protos/google/firestore/admin/v1/index.proto @@ -1,4 +1,4 @@ -// Copyright 2024 Google LLC +// Copyright 2025 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. @@ -66,6 +66,9 @@ message Index { // The index can only be used by the Firestore in Datastore Mode query API. DATASTORE_MODE_API = 1; + + // The index can only be used by the MONGODB_COMPATIBLE_API. + MONGODB_COMPATIBLE_API = 2; } // A field in an index. @@ -162,6 +165,32 @@ message Index { NEEDS_REPAIR = 3; } + // The density configuration for the index. + enum Density { + // Unspecified. It will use database default setting. This value is input + // only. + DENSITY_UNSPECIFIED = 0; + + // In order for an index entry to be added, the document must + // contain all fields specified in the index. + // + // This is the only allowed value for indexes having ApiScope `ANY_API` and + // `DATASTORE_MODE_API`. + SPARSE_ALL = 1; + + // In order for an index entry to be added, the document must + // contain at least one of the fields specified in the index. + // Non-existent fields are treated as having a NULL value when generating + // index entries. + SPARSE_ANY = 2; + + // An index entry will be added regardless of whether the + // document contains any of the fields specified in the index. + // Non-existent fields are treated as having a NULL value when generating + // index entries. + DENSE = 3; + } + // Output only. A server defined name for this index. // The form of this name for composite indexes will be: // `projects/{project_id}/databases/{database_id}/collectionGroups/{collection_id}/indexes/{composite_index_id}` @@ -195,4 +224,20 @@ message Index { // Output only. The serving state of the index. State state = 4; + + // Immutable. The density configuration of the index. + Density density = 6 [(google.api.field_behavior) = IMMUTABLE]; + + // Optional. Whether the index is multikey. By default, the index is not + // multikey. For non-multikey indexes, none of the paths in the index + // definition reach or traverse an array, except via an explicit array index. + // For multikey indexes, at most one of the paths in the index definition + // reach or traverse an array, except via an explicit array index. Violations + // will result in errors. + // + // Note this field only applies to index with MONGODB_COMPATIBLE_API ApiScope. + bool multikey = 7 [(google.api.field_behavior) = OPTIONAL]; + + // Optional. The number of shards for the index. + int32 shard_count = 8 [(google.api.field_behavior) = OPTIONAL]; } diff --git a/dev/protos/google/firestore/admin/v1/location.proto b/dev/protos/google/firestore/admin/v1/location.proto index 4a1154f8c..1eaa5df33 100644 --- a/dev/protos/google/firestore/admin/v1/location.proto +++ b/dev/protos/google/firestore/admin/v1/location.proto @@ -1,4 +1,4 @@ -// Copyright 2024 Google LLC +// Copyright 2025 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. diff --git a/dev/protos/google/firestore/admin/v1/operation.proto b/dev/protos/google/firestore/admin/v1/operation.proto index 39a20ecfd..b92ae2d4d 100644 --- a/dev/protos/google/firestore/admin/v1/operation.proto +++ b/dev/protos/google/firestore/admin/v1/operation.proto @@ -1,4 +1,4 @@ -// Copyright 2024 Google LLC +// Copyright 2025 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. diff --git a/dev/protos/google/firestore/admin/v1/schedule.proto b/dev/protos/google/firestore/admin/v1/schedule.proto index 46bc03920..0f1798247 100644 --- a/dev/protos/google/firestore/admin/v1/schedule.proto +++ b/dev/protos/google/firestore/admin/v1/schedule.proto @@ -1,4 +1,4 @@ -// Copyright 2024 Google LLC +// Copyright 2025 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. diff --git a/dev/protos/google/firestore/admin/v1/user_creds.proto b/dev/protos/google/firestore/admin/v1/user_creds.proto new file mode 100644 index 000000000..ae4db3e46 --- /dev/null +++ b/dev/protos/google/firestore/admin/v1/user_creds.proto @@ -0,0 +1,86 @@ +// Copyright 2025 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. + +syntax = "proto3"; + +package google.firestore.admin.v1; + +import "google/api/field_behavior.proto"; +import "google/api/resource.proto"; +import "google/protobuf/timestamp.proto"; + +option csharp_namespace = "Google.Cloud.Firestore.Admin.V1"; +option go_package = "cloud.google.com/go/firestore/apiv1/admin/adminpb;adminpb"; +option java_multiple_files = true; +option java_outer_classname = "UserCredsProto"; +option java_package = "com.google.firestore.admin.v1"; +option objc_class_prefix = "GCFS"; +option php_namespace = "Google\\Cloud\\Firestore\\Admin\\V1"; +option ruby_package = "Google::Cloud::Firestore::Admin::V1"; + +// A Cloud Firestore User Creds. +message UserCreds { + option (google.api.resource) = { + type: "firestore.googleapis.com/UserCreds" + pattern: "projects/{project}/databases/{database}/userCreds/{user_creds}" + plural: "userCreds" + singular: "userCreds" + }; + + // The state of the user creds (ENABLED or DISABLED). + enum State { + // The default value. Should not be used. + STATE_UNSPECIFIED = 0; + + // The user creds are enabled. + ENABLED = 1; + + // The user creds are disabled. + DISABLED = 2; + } + + // Describes a Resource Identity principal. + message ResourceIdentity { + // Output only. Principal identifier string. + // See: https://cloud.google.com/iam/docs/principal-identifiers + string principal = 1 [(google.api.field_behavior) = OUTPUT_ONLY]; + } + + // Identifier. The resource name of the UserCreds. + // Format: + // `projects/{project}/databases/{database}/userCreds/{user_creds}` + string name = 1 [(google.api.field_behavior) = IDENTIFIER]; + + // Output only. The time the user creds were created. + google.protobuf.Timestamp create_time = 2 + [(google.api.field_behavior) = OUTPUT_ONLY]; + + // Output only. The time the user creds were last updated. + google.protobuf.Timestamp update_time = 3 + [(google.api.field_behavior) = OUTPUT_ONLY]; + + // Output only. Whether the user creds are enabled or disabled. Defaults to + // ENABLED on creation. + State state = 4 [(google.api.field_behavior) = OUTPUT_ONLY]; + + // Output only. The plaintext server-generated password for the user creds. + // Only populated in responses for CreateUserCreds and ResetUserPassword. + string secure_password = 5 [(google.api.field_behavior) = OUTPUT_ONLY]; + + // Identity associated with this User Creds. + oneof UserCredsIdentity { + // Resource Identity descriptor. + ResourceIdentity resource_identity = 6; + } +} diff --git a/dev/protos/google/firestore/v1/document.proto b/dev/protos/google/firestore/v1/document.proto index 9947a289a..44ac35e2f 100644 --- a/dev/protos/google/firestore/v1/document.proto +++ b/dev/protos/google/firestore/v1/document.proto @@ -130,7 +130,6 @@ message Value { // A map value. MapValue map_value = 6; - // Value which references a field. // // This is considered relative (vs absolute) since it only refers to a field @@ -141,9 +140,6 @@ message Value { // * Must follow [field reference][FieldReference.field_path] limitations. // // * Not allowed to be used when writing documents. - // - // (-- NOTE(batchik): long term, there is no reason this type should not be - // allowed to be used on the write path. --) string field_reference_value = 19; // A value that represents an unevaluated expression. @@ -151,13 +147,6 @@ message Value { // **Requires:** // // * Not allowed to be used when writing documents. - // - // (-- NOTE(batchik): similar to above, there is no reason to not allow - // storing expressions into the database, just no plan to support in - // the near term. - // - // This would actually be an interesting way to represent user-defined - // functions or more expressive rules-based systems. --) Function function_value = 20; // A value that represents an unevaluated pipeline. @@ -165,13 +154,6 @@ message Value { // **Requires:** // // * Not allowed to be used when writing documents. - // - // (-- NOTE(batchik): similar to above, there is no reason to not allow - // storing expressions into the database, just no plan to support in - // the near term. - // - // This would actually be an interesting way to represent user-defined - // functions or more expressive rules-based systems. --) Pipeline pipeline_value = 21; } } @@ -202,23 +184,19 @@ message MapValue { // args { field_reference: "user_name" } // args { string_value: "%alice%" } // ``` -// -// (-- api-linter: core::0123::resource-annotation=disabled -// aip.dev/not-precedent: this is not a One Platform API resource. --) message Function { - // The name of the function to evaluate. + // Required. The name of the function to evaluate. // // **Requires:** // // * must be in snake case (lower case with underscore separator). - // - string name = 1; + string name = 1 [(google.api.field_behavior) = REQUIRED]; - // Ordered list of arguments the given function expects. - repeated Value args = 2; + // Optional. Ordered list of arguments the given function expects. + repeated Value args = 2 [(google.api.field_behavior) = OPTIONAL]; - // Optional named arguments that certain functions may support. - map options = 3; + // Optional. Optional named arguments that certain functions may support. + map options = 3 [(google.api.field_behavior) = OPTIONAL]; } // A Firestore query represented as an ordered list of operations / stages. @@ -243,22 +221,20 @@ message Pipeline { // // See public documentation for the full list. message Stage { - // The name of the stage to evaluate. + // Required. The name of the stage to evaluate. // // **Requires:** // // * must be in snake case (lower case with underscore separator). - // - string name = 1; + string name = 1 [(google.api.field_behavior) = REQUIRED]; - // Ordered list of arguments the given stage expects. - repeated Value args = 2; + // Optional. Ordered list of arguments the given stage expects. + repeated Value args = 2 [(google.api.field_behavior) = OPTIONAL]; - // Optional named arguments that certain functions may support. - map options = 3; + // Optional. Optional named arguments that certain functions may support. + map options = 3 [(google.api.field_behavior) = OPTIONAL]; } - // Ordered list of stages to evaluate. - repeated Stage stages = 1; + // Required. Ordered list of stages to evaluate. + repeated Stage stages = 1 [(google.api.field_behavior) = REQUIRED]; } - diff --git a/dev/protos/google/firestore/v1/explain_stats.proto b/dev/protos/google/firestore/v1/explain_stats.proto new file mode 100644 index 000000000..6a3e5fb37 --- /dev/null +++ b/dev/protos/google/firestore/v1/explain_stats.proto @@ -0,0 +1,38 @@ +// 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. + +syntax = "proto3"; + +package google.firestore.v1; + +import "google/protobuf/any.proto"; + +option csharp_namespace = "Google.Cloud.Firestore.V1"; +option go_package = "cloud.google.com/go/firestore/apiv1/firestorepb;firestorepb"; +option java_multiple_files = true; +option java_outer_classname = "ExplainStatsProto"; +option java_package = "com.google.firestore.v1"; +option php_namespace = "Google\\Cloud\\Firestore\\V1"; +option ruby_package = "Google::Cloud::Firestore::V1"; + +// Specification of Firestore Explain Stats fields. + +// Explain stats for an RPC request, includes both the optimized plan and +// execution stats. +message ExplainStats { + // The format depends on the `output_format` options in the request. + // + // The only option today is `TEXT`, which is a `google.protobuf.StringValue`. + google.protobuf.Any data = 1; +} diff --git a/dev/protos/google/firestore/v1/firestore.proto b/dev/protos/google/firestore/v1/firestore.proto index 8479e7779..182b4c07c 100644 --- a/dev/protos/google/firestore/v1/firestore.proto +++ b/dev/protos/google/firestore/v1/firestore.proto @@ -19,9 +19,11 @@ package google.firestore.v1; import "google/api/annotations.proto"; import "google/api/client.proto"; import "google/api/field_behavior.proto"; +import "google/api/routing.proto"; import "google/firestore/v1/aggregation_result.proto"; import "google/firestore/v1/common.proto"; import "google/firestore/v1/document.proto"; +import "google/firestore/v1/explain_stats.proto"; import "google/firestore/v1/pipeline.proto"; import "google/firestore/v1/query.proto"; import "google/firestore/v1/query_profile.proto"; @@ -148,6 +150,16 @@ service Firestore { post: "/v1/{database=projects/*/databases/*}/documents:executePipeline" body: "*" }; + option (google.api.routing) = { + routing_parameters { + field: "database" + path_template: "projects/{project_id=*}/**" + } + routing_parameters { + field: "database" + path_template: "projects/*/databases/{database_id=*}/**" + } + }; } // Runs an aggregation query. @@ -634,12 +646,12 @@ message RunQueryResponse { ExplainMetrics explain_metrics = 11; } -// The request for [Firestore.ExecutePipeline][]. +// The request for +// [Firestore.ExecutePipeline][google.firestore.v1.Firestore.ExecutePipeline]. message ExecutePipelineRequest { - // Database identifier, in the form `projects/{project}/databases/{database}`. - string database = 1 [ - (google.api.field_behavior) = REQUIRED - ]; + // Required. Database identifier, in the form + // `projects/{project}/databases/{database}`. + string database = 1 [(google.api.field_behavior) = REQUIRED]; oneof pipeline_type { // A pipelined operation. @@ -666,17 +678,15 @@ message ExecutePipelineRequest { // minute timestamp within the past 7 days. google.protobuf.Timestamp read_time = 7; } - - // Explain / analyze options for the pipeline. - // ExplainOptions explain_options = 8 [(google.api.field_behavior) = OPTIONAL]; } // The response for [Firestore.Execute][]. message ExecutePipelineResponse { // Newly created transaction identifier. // - // This field is only specified on the first response from the server when - // the request specified [ExecuteRequest.new_transaction][]. + // This field is only specified as part of the first response from the server, + // alongside the `results` field when the original request specified + // [ExecuteRequest.new_transaction][]. bytes transaction = 1; // An ordered batch of results returned executing a pipeline. @@ -686,10 +696,11 @@ message ExecutePipelineResponse { // // The fields present in the returned documents are only those that were // explicitly requested in the pipeline, this include those like - // [`__name__`][Document.name] & [`__update_time__`][Document.update_time]. - // This is explicitly a divergence from `Firestore.RunQuery` / - // `Firestore.GetDocument` RPCs which always return such fields even when they - // are not specified in the [`mask`][DocumentMask]. + // [`__name__`][google.firestore.v1.Document.name] & + // [`__update_time__`][google.firestore.v1.Document.update_time]. This is + // explicitly a divergence from `Firestore.RunQuery` / `Firestore.GetDocument` + // RPCs which always return such fields even when they are not specified in + // the [`mask`][google.firestore.v1.DocumentMask]. repeated Document results = 2; // The time at which the document(s) were read. @@ -703,11 +714,11 @@ message ExecutePipelineResponse { // was run. google.protobuf.Timestamp execution_time = 3; - // Query explain metrics. + // Query explain stats. // - // Set on the last response when [ExecutePipelineRequest.explain_options][] - // was specified on the request. - // ExplainMetrics explain_metrics = 4; + // Contains all metadata related to pipeline planning and execution, specific + // contents depend on the supplied pipeline options. + ExplainStats explain_stats = 4; } // The request for diff --git a/dev/protos/google/firestore/v1/pipeline.proto b/dev/protos/google/firestore/v1/pipeline.proto index ea5b23093..0fde1c65e 100644 --- a/dev/protos/google/firestore/v1/pipeline.proto +++ b/dev/protos/google/firestore/v1/pipeline.proto @@ -1,41 +1,43 @@ -/*! - * 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. - */ +// 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. syntax = "proto3"; + package google.firestore.v1; + +import "google/api/field_behavior.proto"; import "google/firestore/v1/document.proto"; + option csharp_namespace = "Google.Cloud.Firestore.V1"; -option php_namespace = "Google\\Cloud\\Firestore\\V1"; -option ruby_package = "Google::Cloud::Firestore::V1"; +option go_package = "cloud.google.com/go/firestore/apiv1/firestorepb;firestorepb"; option java_multiple_files = true; -option java_package = "com.google.firestore.v1"; option java_outer_classname = "PipelineProto"; +option java_package = "com.google.firestore.v1"; option objc_class_prefix = "GCFS"; +option php_namespace = "Google\\Cloud\\Firestore\\V1"; +option ruby_package = "Google::Cloud::Firestore::V1"; + // A Firestore query represented as an ordered list of operations / stages. // // This is considered the top-level function which plans & executes a query. // It is logically equivalent to `query(stages, options)`, but prevents the // client from having to build a function wrapper. message StructuredPipeline { - // The pipeline query to execute. - Pipeline pipeline = 1; - // Optional query-level arguments. - // - // (-- Think query statement hints. --) + // Required. The pipeline query to execute. + Pipeline pipeline = 1 [(google.api.field_behavior) = REQUIRED]; + + // Optional. Optional query-level arguments. // - // (-- TODO(batchik): define the api contract of using an unsupported hint --) - map options = 2; + map options = 2 [(google.api.field_behavior) = OPTIONAL]; } diff --git a/dev/protos/google/firestore/v1/query.proto b/dev/protos/google/firestore/v1/query.proto index 3b2280076..f260bad08 100644 --- a/dev/protos/google/firestore/v1/query.proto +++ b/dev/protos/google/firestore/v1/query.proto @@ -38,6 +38,7 @@ option ruby_package = "Google::Cloud::Firestore::V1"; // 4. order_by + start_at + end_at // 5. offset // 6. limit +// 7. find_nearest message StructuredQuery { // A selection of a collection, such as `messages as m1`. message CollectionSelector { @@ -324,8 +325,8 @@ message StructuredQuery { // Since DOT_PRODUCT distances increase when the vectors are more similar, // the comparison is inverted. // - // For EUCLIDEAN, COSINE: WHERE distance <= distance_threshold - // For DOT_PRODUCT: WHERE distance >= distance_threshold + // * For EUCLIDEAN, COSINE: WHERE distance <= distance_threshold + // * For DOT_PRODUCT: WHERE distance >= distance_threshold google.protobuf.DoubleValue distance_threshold = 6 [(google.api.field_behavior) = OPTIONAL]; } diff --git a/dev/protos/google/firestore/v1beta1/common.proto b/dev/protos/google/firestore/v1beta1/common.proto index 0418e82d9..b18e53398 100644 --- a/dev/protos/google/firestore/v1beta1/common.proto +++ b/dev/protos/google/firestore/v1beta1/common.proto @@ -1,4 +1,4 @@ -// Copyright 2024 Google LLC +// Copyright 2025 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. diff --git a/dev/protos/google/firestore/v1beta1/document.proto b/dev/protos/google/firestore/v1beta1/document.proto index 962d95c53..36b30151c 100644 --- a/dev/protos/google/firestore/v1beta1/document.proto +++ b/dev/protos/google/firestore/v1beta1/document.proto @@ -1,4 +1,4 @@ -// Copyright 2024 Google LLC +// Copyright 2025 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. diff --git a/dev/protos/google/firestore/v1beta1/firestore.proto b/dev/protos/google/firestore/v1beta1/firestore.proto index 674193913..07d4b3fe9 100644 --- a/dev/protos/google/firestore/v1beta1/firestore.proto +++ b/dev/protos/google/firestore/v1beta1/firestore.proto @@ -1,4 +1,4 @@ -// Copyright 2024 Google LLC +// Copyright 2025 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. diff --git a/dev/protos/google/firestore/v1beta1/query.proto b/dev/protos/google/firestore/v1beta1/query.proto index 868c8ef2a..f107ab721 100644 --- a/dev/protos/google/firestore/v1beta1/query.proto +++ b/dev/protos/google/firestore/v1beta1/query.proto @@ -1,4 +1,4 @@ -// Copyright 2024 Google LLC +// Copyright 2025 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. diff --git a/dev/protos/google/firestore/v1beta1/undeliverable_first_gen_event.proto b/dev/protos/google/firestore/v1beta1/undeliverable_first_gen_event.proto index e0e9b17e0..0f7841eb9 100644 --- a/dev/protos/google/firestore/v1beta1/undeliverable_first_gen_event.proto +++ b/dev/protos/google/firestore/v1beta1/undeliverable_first_gen_event.proto @@ -1,4 +1,4 @@ -// Copyright 2024 Google LLC +// Copyright 2025 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. diff --git a/dev/protos/google/firestore/v1beta1/write.proto b/dev/protos/google/firestore/v1beta1/write.proto index 00ba29a90..2fbe127eb 100644 --- a/dev/protos/google/firestore/v1beta1/write.proto +++ b/dev/protos/google/firestore/v1beta1/write.proto @@ -1,4 +1,4 @@ -// Copyright 2024 Google LLC +// Copyright 2025 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. diff --git a/dev/protos/google/longrunning/operations.proto b/dev/protos/google/longrunning/operations.proto index bb42620b7..bc312bd50 100644 --- a/dev/protos/google/longrunning/operations.proto +++ b/dev/protos/google/longrunning/operations.proto @@ -1,4 +1,4 @@ -// Copyright 2024 Google LLC +// Copyright 2020 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. @@ -30,7 +30,6 @@ option go_package = "cloud.google.com/go/longrunning/autogen/longrunningpb;longr option java_multiple_files = true; option java_outer_classname = "OperationsProto"; option java_package = "com.google.longrunning"; -option objc_class_prefix = "GLRUN"; option php_namespace = "Google\\LongRunning"; extend google.protobuf.MethodOptions { @@ -49,14 +48,22 @@ extend google.protobuf.MethodOptions { // to return [Operation][google.longrunning.Operation] to the client, and the // client can use this interface to receive the real response asynchronously by // polling the operation resource, or pass the operation resource to another API -// (such as Pub/Sub API) to receive the response. Any API service that returns -// long-running operations should implement the `Operations` interface so -// developers can have a consistent client experience. +// (such as Google Cloud Pub/Sub API) to receive the response. Any API service +// that returns long-running operations should implement the `Operations` +// interface so developers can have a consistent client experience. service Operations { option (google.api.default_host) = "longrunning.googleapis.com"; // Lists operations that match the specified filter in the request. If the // server doesn't support this method, it returns `UNIMPLEMENTED`. + // + // NOTE: the `name` binding allows API services to override the binding + // to use different resource name schemes, such as `users/*/operations`. To + // override the binding, API services can add a binding such as + // `"/v1/{name=users/*}/operations"` to their service configuration. + // For backwards compatibility, the default name includes the operations + // collection id, however overriding users must ensure the name binding + // is the parent resource, without the operations collection id. rpc ListOperations(ListOperationsRequest) returns (ListOperationsResponse) { option (google.api.http) = { get: "/v1/{name=operations}" @@ -94,7 +101,7 @@ service Operations { // operation completed despite cancellation. On successful cancellation, // the operation is not deleted; instead, it becomes an operation with // an [Operation.error][google.longrunning.Operation.error] value with a - // [google.rpc.Status.code][google.rpc.Status.code] of `1`, corresponding to + // [google.rpc.Status.code][google.rpc.Status.code] of 1, corresponding to // `Code.CANCELLED`. rpc CancelOperation(CancelOperationRequest) returns (google.protobuf.Empty) { option (google.api.http) = { @@ -137,13 +144,12 @@ message Operation { // The operation result, which can be either an `error` or a valid `response`. // If `done` == `false`, neither `error` nor `response` is set. - // If `done` == `true`, exactly one of `error` or `response` can be set. - // Some services might not provide the result. + // If `done` == `true`, exactly one of `error` or `response` is set. oneof result { // The error result of the operation in case of failure or cancellation. google.rpc.Status error = 4; - // The normal, successful response of the operation. If the original + // The normal response of the operation in case of success. If the original // method returns no data on success, such as `Delete`, the response is // `google.protobuf.Empty`. If the original method is standard // `Get`/`Create`/`Update`, the response should be the resource. For other @@ -218,12 +224,13 @@ message WaitOperationRequest { // // Example: // -// rpc Export(ExportRequest) returns (google.longrunning.Operation) { -// option (google.longrunning.operation_info) = { -// response_type: "ExportResponse" -// metadata_type: "ExportMetadata" -// }; -// } +// rpc LongRunningRecognize(LongRunningRecognizeRequest) +// returns (google.longrunning.Operation) { +// option (google.longrunning.operation_info) = { +// response_type: "LongRunningRecognizeResponse" +// metadata_type: "LongRunningRecognizeMetadata" +// }; +// } message OperationInfo { // Required. The message name of the primary return type for this // long-running operation. diff --git a/dev/protos/google/rpc/status.proto b/dev/protos/google/rpc/status.proto index 90b70ddf9..3b1f7a932 100644 --- a/dev/protos/google/rpc/status.proto +++ b/dev/protos/google/rpc/status.proto @@ -1,4 +1,4 @@ -// Copyright 2024 Google LLC +// Copyright 2020 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. @@ -33,14 +33,12 @@ option objc_class_prefix = "RPC"; // You can find out more about this error model and how to work with it in the // [API Design Guide](https://cloud.google.com/apis/design/errors). message Status { - // The status code, which should be an enum value of - // [google.rpc.Code][google.rpc.Code]. + // The status code, which should be an enum value of [google.rpc.Code][google.rpc.Code]. int32 code = 1; // A developer-facing error message, which should be in English. Any // user-facing error message should be localized and sent in the - // [google.rpc.Status.details][google.rpc.Status.details] field, or localized - // by the client. + // [google.rpc.Status.details][google.rpc.Status.details] field, or localized by the client. string message = 2; // A list of messages that carry the error details. There is a common set of diff --git a/dev/protos/google/type/dayofweek.proto b/dev/protos/google/type/dayofweek.proto index e16c19469..4c80c62ec 100644 --- a/dev/protos/google/type/dayofweek.proto +++ b/dev/protos/google/type/dayofweek.proto @@ -1,4 +1,4 @@ -// Copyright 2024 Google LLC +// Copyright 2021 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. diff --git a/dev/protos/google/type/latlng.proto b/dev/protos/google/type/latlng.proto index daeba48b4..9231456e3 100644 --- a/dev/protos/google/type/latlng.proto +++ b/dev/protos/google/type/latlng.proto @@ -1,4 +1,4 @@ -// Copyright 2024 Google LLC +// Copyright 2021 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. diff --git a/dev/protos/update.sh b/dev/protos/update.sh index 028d8fdd0..74a21233b 100755 --- a/dev/protos/update.sh +++ b/dev/protos/update.sh @@ -41,23 +41,36 @@ PBTS="$(npm root)/.bin/pbts" pushd "$WORK_DIR" # Clone necessary git repos. -git clone --depth 1 https://github.com/googleapis/googleapis.git +# If the USE_PREVIEW_BRANCH environment variable is set, clone the 'preview' branch. +if [[ -n "${USE_PREVIEW_BRANCH-}" ]]; then + echo "Cloning 'preview' branch of googleapis.git..." + git clone --depth 1 --branch preview https://github.com/googleapis/googleapis.git +else + echo "Cloning default branch of googleapis.git..." + git clone --depth 1 https://github.com/googleapis/googleapis.git +fi # Protobuf may have breaking changes, so it will be pinned to a specific release. # TODO(version) nodejs-firestore should maintain the version number of protobuf manually git clone --single-branch --branch v26.1 --depth 1 https://github.com/google/protobuf.git # Copy necessary protos. mkdir -p "${PROTOS_DIR}/google/api" -cp googleapis/google/api/{annotations,client,field_behavior,http,launch_stage,resource}.proto \ +cp googleapis/google/api/{annotations,client,field_behavior,http,launch_stage,resource,routing}.proto \ "${PROTOS_DIR}/google/api/" mkdir -p "${PROTOS_DIR}/google/firestore/v1" cp googleapis/google/firestore/v1/*.proto \ "${PROTOS_DIR}/google/firestore/v1/" +# If the USE_PREVIEW_BRANCH environment variable is set, skip v1beta1. +# v1beta1/ does not exist in the 'preview' branch mkdir -p "${PROTOS_DIR}/google/firestore/v1beta1" -cp googleapis/google/firestore/v1beta1/*.proto \ +if [[ -n "${USE_PREVIEW_BRANCH-}" ]]; then + echo "Skipping v1beta1 for 'preview' branch" +else + cp googleapis/google/firestore/v1beta1/*.proto \ "${PROTOS_DIR}/google/firestore/v1beta1/" +fi mkdir -p "${PROTOS_DIR}/google/firestore/admin/v1" cp googleapis/google/firestore/admin/v1/*.proto \ diff --git a/dev/protos/v1.json b/dev/protos/v1.json index 565f24044..43669ff22 100644 --- a/dev/protos/v1.json +++ b/dev/protos/v1.json @@ -1,7 +1,4 @@ { - "options": { - "syntax": "proto3" - }, "nested": { "google": { "nested": { @@ -151,17 +148,26 @@ "fields": { "name": { "type": "string", - "id": 1 + "id": 1, + "options": { + "(google.api.field_behavior)": "REQUIRED" + } }, "args": { "rule": "repeated", "type": "Value", - "id": 2 + "id": 2, + "options": { + "(google.api.field_behavior)": "OPTIONAL" + } }, "options": { "keyType": "string", "type": "Value", - "id": 3 + "id": 3, + "options": { + "(google.api.field_behavior)": "OPTIONAL" + } } } }, @@ -170,7 +176,10 @@ "stages": { "rule": "repeated", "type": "Stage", - "id": 1 + "id": 1, + "options": { + "(google.api.field_behavior)": "REQUIRED" + } } }, "nested": { @@ -178,17 +187,26 @@ "fields": { "name": { "type": "string", - "id": 1 + "id": 1, + "options": { + "(google.api.field_behavior)": "REQUIRED" + } }, "args": { "rule": "repeated", "type": "Value", - "id": 2 + "id": 2, + "options": { + "(google.api.field_behavior)": "OPTIONAL" + } }, "options": { "keyType": "string", "type": "Value", - "id": 3 + "id": 3, + "options": { + "(google.api.field_behavior)": "OPTIONAL" + } } } } @@ -292,6 +310,14 @@ } } }, + "ExplainStats": { + "fields": { + "data": { + "type": "google.protobuf.Any", + "id": 1 + } + } + }, "Firestore": { "options": { "(google.api.default_host)": "firestore.googleapis.com", @@ -474,7 +500,9 @@ "responseStream": true, "options": { "(google.api.http).post": "/v1/{database=projects/*/databases/*}/documents:executePipeline", - "(google.api.http).body": "*" + "(google.api.http).body": "*", + "(google.api.routing).routing_parameters.field": "database", + "(google.api.routing).routing_parameters.path_template": "projects/*/databases/{database_id=*}/**" }, "parsedOptions": [ { @@ -482,6 +510,20 @@ "post": "/v1/{database=projects/*/databases/*}/documents:executePipeline", "body": "*" } + }, + { + "(google.api.routing)": { + "routing_parameters": [ + { + "field": "database", + "path_template": "projects/{project_id=*}/**" + }, + { + "field": "database", + "path_template": "projects/*/databases/{database_id=*}/**" + } + ] + } } ] }, @@ -1088,6 +1130,10 @@ "executionTime": { "type": "google.protobuf.Timestamp", "id": 3 + }, + "explainStats": { + "type": "ExplainStats", + "id": 4 } } }, @@ -1526,12 +1572,18 @@ "fields": { "pipeline": { "type": "Pipeline", - "id": 1 + "id": 1, + "options": { + "(google.api.field_behavior)": "REQUIRED" + } }, "options": { "keyType": "string", "type": "Value", - "id": 2 + "id": 2, + "options": { + "(google.api.field_behavior)": "OPTIONAL" + } } } }, @@ -2290,10 +2342,6 @@ "rule": "repeated", "type": "ClientLibraryDestination", "id": 2 - }, - "selectiveGapicGeneration": { - "type": "SelectiveGapicGeneration", - "id": 3 } } }, @@ -2434,24 +2482,6 @@ "common": { "type": "CommonLanguageSettings", "id": 1 - }, - "experimentalFeatures": { - "type": "ExperimentalFeatures", - "id": 2 - } - }, - "nested": { - "ExperimentalFeatures": { - "fields": { - "restAsyncIoEnabled": { - "type": "bool", - "id": 1 - }, - "protobufPythonicTypesEnabled": { - "type": "bool", - "id": 2 - } - } } } }, @@ -2509,11 +2539,6 @@ "common": { "type": "CommonLanguageSettings", "id": 1 - }, - "renamedServices": { - "keyType": "string", - "type": "string", - "id": 2 } } }, @@ -2575,19 +2600,6 @@ "PACKAGE_MANAGER": 20 } }, - "SelectiveGapicGeneration": { - "fields": { - "methods": { - "rule": "repeated", - "type": "string", - "id": 1 - }, - "generateOmittedAsInternal": { - "type": "bool", - "id": 2 - } - } - }, "LaunchStage": { "values": { "LAUNCH_STAGE_UNSPECIFIED": 0, @@ -2600,6 +2612,32 @@ "DEPRECATED": 5 } }, + "routing": { + "type": "google.api.RoutingRule", + "id": 72295729, + "extend": "google.protobuf.MethodOptions" + }, + "RoutingRule": { + "fields": { + "routingParameters": { + "rule": "repeated", + "type": "RoutingParameter", + "id": 2 + } + } + }, + "RoutingParameter": { + "fields": { + "field": { + "type": "string", + "id": 1 + }, + "pathTemplate": { + "type": "string", + "id": 2 + } + } + }, "resourceReference": { "type": "google.api.ResourceReference", "id": 1055, @@ -2691,6 +2729,7 @@ }, "nested": { "FileDescriptorSet": { + "edition": "proto2", "fields": { "file": { "rule": "repeated", @@ -2700,6 +2739,7 @@ } }, "Edition": { + "edition": "proto2", "values": { "EDITION_UNKNOWN": 0, "EDITION_PROTO2": 998, @@ -2715,6 +2755,7 @@ } }, "FileDescriptorProto": { + "edition": "proto2", "fields": { "name": { "type": "string", @@ -2732,18 +2773,12 @@ "publicDependency": { "rule": "repeated", "type": "int32", - "id": 10, - "options": { - "packed": false - } + "id": 10 }, "weakDependency": { "rule": "repeated", "type": "int32", - "id": 11, - "options": { - "packed": false - } + "id": 11 }, "messageType": { "rule": "repeated", @@ -2784,6 +2819,7 @@ } }, "DescriptorProto": { + "edition": "proto2", "fields": { "name": { "type": "string", @@ -2866,6 +2902,7 @@ } }, "ExtensionRangeOptions": { + "edition": "proto2", "fields": { "uninterpretedOption": { "rule": "repeated", @@ -2939,6 +2976,7 @@ } }, "FieldDescriptorProto": { + "edition": "proto2", "fields": { "name": { "type": "string", @@ -3018,6 +3056,7 @@ } }, "OneofDescriptorProto": { + "edition": "proto2", "fields": { "name": { "type": "string", @@ -3030,6 +3069,7 @@ } }, "EnumDescriptorProto": { + "edition": "proto2", "fields": { "name": { "type": "string", @@ -3071,6 +3111,7 @@ } }, "EnumValueDescriptorProto": { + "edition": "proto2", "fields": { "name": { "type": "string", @@ -3087,6 +3128,7 @@ } }, "ServiceDescriptorProto": { + "edition": "proto2", "fields": { "name": { "type": "string", @@ -3104,6 +3146,7 @@ } }, "MethodDescriptorProto": { + "edition": "proto2", "fields": { "name": { "type": "string", @@ -3138,6 +3181,7 @@ } }, "FileOptions": { + "edition": "proto2", "fields": { "javaPackage": { "type": "string", @@ -3279,6 +3323,7 @@ } }, "MessageOptions": { + "edition": "proto2", "fields": { "messageSetWireFormat": { "type": "bool", @@ -3352,6 +3397,7 @@ ] }, "FieldOptions": { + "edition": "proto2", "fields": { "ctype": { "type": "CType", @@ -3413,10 +3459,7 @@ "targets": { "rule": "repeated", "type": "OptionTargetType", - "id": 19, - "options": { - "packed": false - } + "id": 19 }, "editionDefaults": { "rule": "repeated", @@ -3500,6 +3543,7 @@ } }, "OneofOptions": { + "edition": "proto2", "fields": { "features": { "type": "FeatureSet", @@ -3519,6 +3563,7 @@ ] }, "EnumOptions": { + "edition": "proto2", "fields": { "allowAlias": { "type": "bool", @@ -3562,6 +3607,7 @@ ] }, "EnumValueOptions": { + "edition": "proto2", "fields": { "deprecated": { "type": "bool", @@ -3595,6 +3641,7 @@ ] }, "ServiceOptions": { + "edition": "proto2", "fields": { "features": { "type": "FeatureSet", @@ -3621,6 +3668,7 @@ ] }, "MethodOptions": { + "edition": "proto2", "fields": { "deprecated": { "type": "bool", @@ -3663,6 +3711,7 @@ } }, "UninterpretedOption": { + "edition": "proto2", "fields": { "name": { "rule": "repeated", @@ -3712,6 +3761,7 @@ } }, "FeatureSet": { + "edition": "proto2", "fields": { "fieldPresence": { "type": "FieldPresence", @@ -3849,6 +3899,7 @@ } }, "FeatureSetDefaults": { + "edition": "proto2", "fields": { "defaults": { "rule": "repeated", @@ -3880,6 +3931,7 @@ } }, "SourceCodeInfo": { + "edition": "proto2", "fields": { "location": { "rule": "repeated", @@ -3893,12 +3945,18 @@ "path": { "rule": "repeated", "type": "int32", - "id": 1 + "id": 1, + "options": { + "packed": true + } }, "span": { "rule": "repeated", "type": "int32", - "id": 2 + "id": 2, + "options": { + "packed": true + } }, "leadingComments": { "type": "string", @@ -3918,6 +3976,7 @@ } }, "GeneratedCodeInfo": { + "edition": "proto2", "fields": { "annotation": { "rule": "repeated", @@ -3931,7 +3990,10 @@ "path": { "rule": "repeated", "type": "int32", - "id": 1 + "id": 1, + "options": { + "packed": true + } }, "sourceFile": { "type": "string", @@ -4037,6 +4099,18 @@ } } }, + "Any": { + "fields": { + "type_url": { + "type": "string", + "id": 1 + }, + "value": { + "type": "bytes", + "id": 2 + } + } + }, "Duration": { "fields": { "seconds": { @@ -4124,1522 +4198,6 @@ "Empty": { "fields": {} }, - "Any": { - "fields": { - "type_url": { - "type": "string", - "id": 1 - }, - "value": { - "type": "bytes", - "id": 2 - } - } - }, - "FieldMask": { - "fields": { - "paths": { - "rule": "repeated", - "type": "string", - "id": 1 - } - } - } - } - }, - "type": { - "options": { - "cc_enable_arenas": true, - "go_package": "google.golang.org/genproto/googleapis/type/dayofweek;dayofweek", - "java_multiple_files": true, - "java_outer_classname": "DayOfWeekProto", - "java_package": "com.google.type", - "objc_class_prefix": "GTP" - }, - "nested": { - "LatLng": { - "fields": { - "latitude": { - "type": "double", - "id": 1 - }, - "longitude": { - "type": "double", - "id": 2 - } - } - }, - "DayOfWeek": { - "values": { - "DAY_OF_WEEK_UNSPECIFIED": 0, - "MONDAY": 1, - "TUESDAY": 2, - "WEDNESDAY": 3, - "THURSDAY": 4, - "FRIDAY": 5, - "SATURDAY": 6, - "SUNDAY": 7 - } - } - } - }, - "protobuf": { - "options": { - "go_package": "google.golang.org/protobuf/types/descriptorpb", - "java_package": "com.google.protobuf", - "java_outer_classname": "DescriptorProtos", - "csharp_namespace": "Google.Protobuf.Reflection", - "objc_class_prefix": "GPB", - "cc_enable_arenas": true, - "optimize_for": "SPEED" - }, - "nested": { - "FileDescriptorSet": { - "fields": { - "file": { - "rule": "repeated", - "type": "FileDescriptorProto", - "id": 1 - } - } - }, - "Edition": { - "values": { - "EDITION_UNKNOWN": 0, - "EDITION_PROTO2": 998, - "EDITION_PROTO3": 999, - "EDITION_2023": 1000, - "EDITION_2024": 1001, - "EDITION_1_TEST_ONLY": 1, - "EDITION_2_TEST_ONLY": 2, - "EDITION_99997_TEST_ONLY": 99997, - "EDITION_99998_TEST_ONLY": 99998, - "EDITION_99999_TEST_ONLY": 99999, - "EDITION_MAX": 2147483647 - } - }, - "FileDescriptorProto": { - "fields": { - "name": { - "type": "string", - "id": 1 - }, - "package": { - "type": "string", - "id": 2 - }, - "dependency": { - "rule": "repeated", - "type": "string", - "id": 3 - }, - "publicDependency": { - "rule": "repeated", - "type": "int32", - "id": 10, - "options": { - "packed": false - } - }, - "weakDependency": { - "rule": "repeated", - "type": "int32", - "id": 11, - "options": { - "packed": false - } - }, - "messageType": { - "rule": "repeated", - "type": "DescriptorProto", - "id": 4 - }, - "enumType": { - "rule": "repeated", - "type": "EnumDescriptorProto", - "id": 5 - }, - "service": { - "rule": "repeated", - "type": "ServiceDescriptorProto", - "id": 6 - }, - "extension": { - "rule": "repeated", - "type": "FieldDescriptorProto", - "id": 7 - }, - "options": { - "type": "FileOptions", - "id": 8 - }, - "sourceCodeInfo": { - "type": "SourceCodeInfo", - "id": 9 - }, - "syntax": { - "type": "string", - "id": 12 - }, - "edition": { - "type": "Edition", - "id": 14 - } - } - }, - "DescriptorProto": { - "fields": { - "name": { - "type": "string", - "id": 1 - }, - "field": { - "rule": "repeated", - "type": "FieldDescriptorProto", - "id": 2 - }, - "extension": { - "rule": "repeated", - "type": "FieldDescriptorProto", - "id": 6 - }, - "nestedType": { - "rule": "repeated", - "type": "DescriptorProto", - "id": 3 - }, - "enumType": { - "rule": "repeated", - "type": "EnumDescriptorProto", - "id": 4 - }, - "extensionRange": { - "rule": "repeated", - "type": "ExtensionRange", - "id": 5 - }, - "oneofDecl": { - "rule": "repeated", - "type": "OneofDescriptorProto", - "id": 8 - }, - "options": { - "type": "MessageOptions", - "id": 7 - }, - "reservedRange": { - "rule": "repeated", - "type": "ReservedRange", - "id": 9 - }, - "reservedName": { - "rule": "repeated", - "type": "string", - "id": 10 - } - }, - "nested": { - "ExtensionRange": { - "fields": { - "start": { - "type": "int32", - "id": 1 - }, - "end": { - "type": "int32", - "id": 2 - }, - "options": { - "type": "ExtensionRangeOptions", - "id": 3 - } - } - }, - "ReservedRange": { - "fields": { - "start": { - "type": "int32", - "id": 1 - }, - "end": { - "type": "int32", - "id": 2 - } - } - } - } - }, - "ExtensionRangeOptions": { - "fields": { - "uninterpretedOption": { - "rule": "repeated", - "type": "UninterpretedOption", - "id": 999 - }, - "declaration": { - "rule": "repeated", - "type": "Declaration", - "id": 2, - "options": { - "retention": "RETENTION_SOURCE" - } - }, - "features": { - "type": "FeatureSet", - "id": 50 - }, - "verification": { - "type": "VerificationState", - "id": 3, - "options": { - "default": "UNVERIFIED", - "retention": "RETENTION_SOURCE" - } - } - }, - "extensions": [ - [ - 1000, - 536870911 - ] - ], - "nested": { - "Declaration": { - "fields": { - "number": { - "type": "int32", - "id": 1 - }, - "fullName": { - "type": "string", - "id": 2 - }, - "type": { - "type": "string", - "id": 3 - }, - "reserved": { - "type": "bool", - "id": 5 - }, - "repeated": { - "type": "bool", - "id": 6 - } - }, - "reserved": [ - [ - 4, - 4 - ] - ] - }, - "VerificationState": { - "values": { - "DECLARATION": 0, - "UNVERIFIED": 1 - } - } - } - }, - "FieldDescriptorProto": { - "fields": { - "name": { - "type": "string", - "id": 1 - }, - "number": { - "type": "int32", - "id": 3 - }, - "label": { - "type": "Label", - "id": 4 - }, - "type": { - "type": "Type", - "id": 5 - }, - "typeName": { - "type": "string", - "id": 6 - }, - "extendee": { - "type": "string", - "id": 2 - }, - "defaultValue": { - "type": "string", - "id": 7 - }, - "oneofIndex": { - "type": "int32", - "id": 9 - }, - "jsonName": { - "type": "string", - "id": 10 - }, - "options": { - "type": "FieldOptions", - "id": 8 - }, - "proto3Optional": { - "type": "bool", - "id": 17 - } - }, - "nested": { - "Type": { - "values": { - "TYPE_DOUBLE": 1, - "TYPE_FLOAT": 2, - "TYPE_INT64": 3, - "TYPE_UINT64": 4, - "TYPE_INT32": 5, - "TYPE_FIXED64": 6, - "TYPE_FIXED32": 7, - "TYPE_BOOL": 8, - "TYPE_STRING": 9, - "TYPE_GROUP": 10, - "TYPE_MESSAGE": 11, - "TYPE_BYTES": 12, - "TYPE_UINT32": 13, - "TYPE_ENUM": 14, - "TYPE_SFIXED32": 15, - "TYPE_SFIXED64": 16, - "TYPE_SINT32": 17, - "TYPE_SINT64": 18 - } - }, - "Label": { - "values": { - "LABEL_OPTIONAL": 1, - "LABEL_REPEATED": 3, - "LABEL_REQUIRED": 2 - } - } - } - }, - "OneofDescriptorProto": { - "fields": { - "name": { - "type": "string", - "id": 1 - }, - "options": { - "type": "OneofOptions", - "id": 2 - } - } - }, - "EnumDescriptorProto": { - "fields": { - "name": { - "type": "string", - "id": 1 - }, - "value": { - "rule": "repeated", - "type": "EnumValueDescriptorProto", - "id": 2 - }, - "options": { - "type": "EnumOptions", - "id": 3 - }, - "reservedRange": { - "rule": "repeated", - "type": "EnumReservedRange", - "id": 4 - }, - "reservedName": { - "rule": "repeated", - "type": "string", - "id": 5 - } - }, - "nested": { - "EnumReservedRange": { - "fields": { - "start": { - "type": "int32", - "id": 1 - }, - "end": { - "type": "int32", - "id": 2 - } - } - } - } - }, - "EnumValueDescriptorProto": { - "fields": { - "name": { - "type": "string", - "id": 1 - }, - "number": { - "type": "int32", - "id": 2 - }, - "options": { - "type": "EnumValueOptions", - "id": 3 - } - } - }, - "ServiceDescriptorProto": { - "fields": { - "name": { - "type": "string", - "id": 1 - }, - "method": { - "rule": "repeated", - "type": "MethodDescriptorProto", - "id": 2 - }, - "options": { - "type": "ServiceOptions", - "id": 3 - } - } - }, - "MethodDescriptorProto": { - "fields": { - "name": { - "type": "string", - "id": 1 - }, - "inputType": { - "type": "string", - "id": 2 - }, - "outputType": { - "type": "string", - "id": 3 - }, - "options": { - "type": "MethodOptions", - "id": 4 - }, - "clientStreaming": { - "type": "bool", - "id": 5, - "options": { - "default": false - } - }, - "serverStreaming": { - "type": "bool", - "id": 6, - "options": { - "default": false - } - } - } - }, - "FileOptions": { - "fields": { - "javaPackage": { - "type": "string", - "id": 1 - }, - "javaOuterClassname": { - "type": "string", - "id": 8 - }, - "javaMultipleFiles": { - "type": "bool", - "id": 10, - "options": { - "default": false - } - }, - "javaGenerateEqualsAndHash": { - "type": "bool", - "id": 20, - "options": { - "deprecated": true - } - }, - "javaStringCheckUtf8": { - "type": "bool", - "id": 27, - "options": { - "default": false - } - }, - "optimizeFor": { - "type": "OptimizeMode", - "id": 9, - "options": { - "default": "SPEED" - } - }, - "goPackage": { - "type": "string", - "id": 11 - }, - "ccGenericServices": { - "type": "bool", - "id": 16, - "options": { - "default": false - } - }, - "javaGenericServices": { - "type": "bool", - "id": 17, - "options": { - "default": false - } - }, - "pyGenericServices": { - "type": "bool", - "id": 18, - "options": { - "default": false - } - }, - "deprecated": { - "type": "bool", - "id": 23, - "options": { - "default": false - } - }, - "ccEnableArenas": { - "type": "bool", - "id": 31, - "options": { - "default": true - } - }, - "objcClassPrefix": { - "type": "string", - "id": 36 - }, - "csharpNamespace": { - "type": "string", - "id": 37 - }, - "swiftPrefix": { - "type": "string", - "id": 39 - }, - "phpClassPrefix": { - "type": "string", - "id": 40 - }, - "phpNamespace": { - "type": "string", - "id": 41 - }, - "phpMetadataNamespace": { - "type": "string", - "id": 44 - }, - "rubyPackage": { - "type": "string", - "id": 45 - }, - "features": { - "type": "FeatureSet", - "id": 50 - }, - "uninterpretedOption": { - "rule": "repeated", - "type": "UninterpretedOption", - "id": 999 - } - }, - "extensions": [ - [ - 1000, - 536870911 - ] - ], - "reserved": [ - [ - 42, - 42 - ], - [ - 38, - 38 - ] - ], - "nested": { - "OptimizeMode": { - "values": { - "SPEED": 1, - "CODE_SIZE": 2, - "LITE_RUNTIME": 3 - } - } - } - }, - "MessageOptions": { - "fields": { - "messageSetWireFormat": { - "type": "bool", - "id": 1, - "options": { - "default": false - } - }, - "noStandardDescriptorAccessor": { - "type": "bool", - "id": 2, - "options": { - "default": false - } - }, - "deprecated": { - "type": "bool", - "id": 3, - "options": { - "default": false - } - }, - "mapEntry": { - "type": "bool", - "id": 7 - }, - "deprecatedLegacyJsonFieldConflicts": { - "type": "bool", - "id": 11, - "options": { - "deprecated": true - } - }, - "features": { - "type": "FeatureSet", - "id": 12 - }, - "uninterpretedOption": { - "rule": "repeated", - "type": "UninterpretedOption", - "id": 999 - } - }, - "extensions": [ - [ - 1000, - 536870911 - ] - ], - "reserved": [ - [ - 4, - 4 - ], - [ - 5, - 5 - ], - [ - 6, - 6 - ], - [ - 8, - 8 - ], - [ - 9, - 9 - ] - ] - }, - "FieldOptions": { - "fields": { - "ctype": { - "type": "CType", - "id": 1, - "options": { - "default": "STRING" - } - }, - "packed": { - "type": "bool", - "id": 2 - }, - "jstype": { - "type": "JSType", - "id": 6, - "options": { - "default": "JS_NORMAL" - } - }, - "lazy": { - "type": "bool", - "id": 5, - "options": { - "default": false - } - }, - "unverifiedLazy": { - "type": "bool", - "id": 15, - "options": { - "default": false - } - }, - "deprecated": { - "type": "bool", - "id": 3, - "options": { - "default": false - } - }, - "weak": { - "type": "bool", - "id": 10, - "options": { - "default": false - } - }, - "debugRedact": { - "type": "bool", - "id": 16, - "options": { - "default": false - } - }, - "retention": { - "type": "OptionRetention", - "id": 17 - }, - "targets": { - "rule": "repeated", - "type": "OptionTargetType", - "id": 19, - "options": { - "packed": false - } - }, - "editionDefaults": { - "rule": "repeated", - "type": "EditionDefault", - "id": 20 - }, - "features": { - "type": "FeatureSet", - "id": 21 - }, - "uninterpretedOption": { - "rule": "repeated", - "type": "UninterpretedOption", - "id": 999 - } - }, - "extensions": [ - [ - 1000, - 536870911 - ] - ], - "reserved": [ - [ - 4, - 4 - ], - [ - 18, - 18 - ] - ], - "nested": { - "CType": { - "values": { - "STRING": 0, - "CORD": 1, - "STRING_PIECE": 2 - } - }, - "JSType": { - "values": { - "JS_NORMAL": 0, - "JS_STRING": 1, - "JS_NUMBER": 2 - } - }, - "OptionRetention": { - "values": { - "RETENTION_UNKNOWN": 0, - "RETENTION_RUNTIME": 1, - "RETENTION_SOURCE": 2 - } - }, - "OptionTargetType": { - "values": { - "TARGET_TYPE_UNKNOWN": 0, - "TARGET_TYPE_FILE": 1, - "TARGET_TYPE_EXTENSION_RANGE": 2, - "TARGET_TYPE_MESSAGE": 3, - "TARGET_TYPE_FIELD": 4, - "TARGET_TYPE_ONEOF": 5, - "TARGET_TYPE_ENUM": 6, - "TARGET_TYPE_ENUM_ENTRY": 7, - "TARGET_TYPE_SERVICE": 8, - "TARGET_TYPE_METHOD": 9 - } - }, - "EditionDefault": { - "fields": { - "edition": { - "type": "Edition", - "id": 3 - }, - "value": { - "type": "string", - "id": 2 - } - } - } - } - }, - "OneofOptions": { - "fields": { - "features": { - "type": "FeatureSet", - "id": 1 - }, - "uninterpretedOption": { - "rule": "repeated", - "type": "UninterpretedOption", - "id": 999 - } - }, - "extensions": [ - [ - 1000, - 536870911 - ] - ] - }, - "EnumOptions": { - "fields": { - "allowAlias": { - "type": "bool", - "id": 2 - }, - "deprecated": { - "type": "bool", - "id": 3, - "options": { - "default": false - } - }, - "deprecatedLegacyJsonFieldConflicts": { - "type": "bool", - "id": 6, - "options": { - "deprecated": true - } - }, - "features": { - "type": "FeatureSet", - "id": 7 - }, - "uninterpretedOption": { - "rule": "repeated", - "type": "UninterpretedOption", - "id": 999 - } - }, - "extensions": [ - [ - 1000, - 536870911 - ] - ], - "reserved": [ - [ - 5, - 5 - ] - ] - }, - "EnumValueOptions": { - "fields": { - "deprecated": { - "type": "bool", - "id": 1, - "options": { - "default": false - } - }, - "features": { - "type": "FeatureSet", - "id": 2 - }, - "debugRedact": { - "type": "bool", - "id": 3, - "options": { - "default": false - } - }, - "uninterpretedOption": { - "rule": "repeated", - "type": "UninterpretedOption", - "id": 999 - } - }, - "extensions": [ - [ - 1000, - 536870911 - ] - ] - }, - "ServiceOptions": { - "fields": { - "features": { - "type": "FeatureSet", - "id": 34 - }, - "deprecated": { - "type": "bool", - "id": 33, - "options": { - "default": false - } - }, - "uninterpretedOption": { - "rule": "repeated", - "type": "UninterpretedOption", - "id": 999 - } - }, - "extensions": [ - [ - 1000, - 536870911 - ] - ] - }, - "MethodOptions": { - "fields": { - "deprecated": { - "type": "bool", - "id": 33, - "options": { - "default": false - } - }, - "idempotencyLevel": { - "type": "IdempotencyLevel", - "id": 34, - "options": { - "default": "IDEMPOTENCY_UNKNOWN" - } - }, - "features": { - "type": "FeatureSet", - "id": 35 - }, - "uninterpretedOption": { - "rule": "repeated", - "type": "UninterpretedOption", - "id": 999 - } - }, - "extensions": [ - [ - 1000, - 536870911 - ] - ], - "nested": { - "IdempotencyLevel": { - "values": { - "IDEMPOTENCY_UNKNOWN": 0, - "NO_SIDE_EFFECTS": 1, - "IDEMPOTENT": 2 - } - } - } - }, - "UninterpretedOption": { - "fields": { - "name": { - "rule": "repeated", - "type": "NamePart", - "id": 2 - }, - "identifierValue": { - "type": "string", - "id": 3 - }, - "positiveIntValue": { - "type": "uint64", - "id": 4 - }, - "negativeIntValue": { - "type": "int64", - "id": 5 - }, - "doubleValue": { - "type": "double", - "id": 6 - }, - "stringValue": { - "type": "bytes", - "id": 7 - }, - "aggregateValue": { - "type": "string", - "id": 8 - } - }, - "nested": { - "NamePart": { - "fields": { - "namePart": { - "rule": "required", - "type": "string", - "id": 1 - }, - "isExtension": { - "rule": "required", - "type": "bool", - "id": 2 - } - } - } - } - }, - "FeatureSet": { - "fields": { - "fieldPresence": { - "type": "FieldPresence", - "id": 1, - "options": { - "retention": "RETENTION_RUNTIME", - "targets": "TARGET_TYPE_FILE", - "edition_defaults.edition": "EDITION_2023", - "edition_defaults.value": "EXPLICIT" - } - }, - "enumType": { - "type": "EnumType", - "id": 2, - "options": { - "retention": "RETENTION_RUNTIME", - "targets": "TARGET_TYPE_FILE", - "edition_defaults.edition": "EDITION_PROTO3", - "edition_defaults.value": "OPEN" - } - }, - "repeatedFieldEncoding": { - "type": "RepeatedFieldEncoding", - "id": 3, - "options": { - "retention": "RETENTION_RUNTIME", - "targets": "TARGET_TYPE_FILE", - "edition_defaults.edition": "EDITION_PROTO3", - "edition_defaults.value": "PACKED" - } - }, - "utf8Validation": { - "type": "Utf8Validation", - "id": 4, - "options": { - "retention": "RETENTION_RUNTIME", - "targets": "TARGET_TYPE_FILE", - "edition_defaults.edition": "EDITION_PROTO3", - "edition_defaults.value": "VERIFY" - } - }, - "messageEncoding": { - "type": "MessageEncoding", - "id": 5, - "options": { - "retention": "RETENTION_RUNTIME", - "targets": "TARGET_TYPE_FILE", - "edition_defaults.edition": "EDITION_PROTO2", - "edition_defaults.value": "LENGTH_PREFIXED" - } - }, - "jsonFormat": { - "type": "JsonFormat", - "id": 6, - "options": { - "retention": "RETENTION_RUNTIME", - "targets": "TARGET_TYPE_FILE", - "edition_defaults.edition": "EDITION_PROTO3", - "edition_defaults.value": "ALLOW" - } - } - }, - "extensions": [ - [ - 1000, - 1000 - ], - [ - 1001, - 1001 - ], - [ - 1002, - 1002 - ], - [ - 9995, - 9999 - ], - [ - 10000, - 10000 - ] - ], - "reserved": [ - [ - 999, - 999 - ] - ], - "nested": { - "FieldPresence": { - "values": { - "FIELD_PRESENCE_UNKNOWN": 0, - "EXPLICIT": 1, - "IMPLICIT": 2, - "LEGACY_REQUIRED": 3 - } - }, - "EnumType": { - "values": { - "ENUM_TYPE_UNKNOWN": 0, - "OPEN": 1, - "CLOSED": 2 - } - }, - "RepeatedFieldEncoding": { - "values": { - "REPEATED_FIELD_ENCODING_UNKNOWN": 0, - "PACKED": 1, - "EXPANDED": 2 - } - }, - "Utf8Validation": { - "values": { - "UTF8_VALIDATION_UNKNOWN": 0, - "VERIFY": 2, - "NONE": 3 - } - }, - "MessageEncoding": { - "values": { - "MESSAGE_ENCODING_UNKNOWN": 0, - "LENGTH_PREFIXED": 1, - "DELIMITED": 2 - } - }, - "JsonFormat": { - "values": { - "JSON_FORMAT_UNKNOWN": 0, - "ALLOW": 1, - "LEGACY_BEST_EFFORT": 2 - } - } - } - }, - "FeatureSetDefaults": { - "fields": { - "defaults": { - "rule": "repeated", - "type": "FeatureSetEditionDefault", - "id": 1 - }, - "minimumEdition": { - "type": "Edition", - "id": 4 - }, - "maximumEdition": { - "type": "Edition", - "id": 5 - } - }, - "nested": { - "FeatureSetEditionDefault": { - "fields": { - "edition": { - "type": "Edition", - "id": 3 - }, - "features": { - "type": "FeatureSet", - "id": 2 - } - } - } - } - }, - "SourceCodeInfo": { - "fields": { - "location": { - "rule": "repeated", - "type": "Location", - "id": 1 - } - }, - "nested": { - "Location": { - "fields": { - "path": { - "rule": "repeated", - "type": "int32", - "id": 1 - }, - "span": { - "rule": "repeated", - "type": "int32", - "id": 2 - }, - "leadingComments": { - "type": "string", - "id": 3 - }, - "trailingComments": { - "type": "string", - "id": 4 - }, - "leadingDetachedComments": { - "rule": "repeated", - "type": "string", - "id": 6 - } - } - } - } - }, - "GeneratedCodeInfo": { - "fields": { - "annotation": { - "rule": "repeated", - "type": "Annotation", - "id": 1 - } - }, - "nested": { - "Annotation": { - "fields": { - "path": { - "rule": "repeated", - "type": "int32", - "id": 1 - }, - "sourceFile": { - "type": "string", - "id": 2 - }, - "begin": { - "type": "int32", - "id": 3 - }, - "end": { - "type": "int32", - "id": 4 - }, - "semantic": { - "type": "Semantic", - "id": 5 - } - }, - "nested": { - "Semantic": { - "values": { - "NONE": 0, - "SET": 1, - "ALIAS": 2 - } - } - } - } - } - }, - "Struct": { - "fields": { - "fields": { - "keyType": "string", - "type": "Value", - "id": 1 - } - } - }, - "Value": { - "oneofs": { - "kind": { - "oneof": [ - "nullValue", - "numberValue", - "stringValue", - "boolValue", - "structValue", - "listValue" - ] - } - }, - "fields": { - "nullValue": { - "type": "NullValue", - "id": 1 - }, - "numberValue": { - "type": "double", - "id": 2 - }, - "stringValue": { - "type": "string", - "id": 3 - }, - "boolValue": { - "type": "bool", - "id": 4 - }, - "structValue": { - "type": "Struct", - "id": 5 - }, - "listValue": { - "type": "ListValue", - "id": 6 - } - } - }, - "NullValue": { - "values": { - "NULL_VALUE": 0 - } - }, - "ListValue": { - "fields": { - "values": { - "rule": "repeated", - "type": "Value", - "id": 1 - } - } - }, - "Timestamp": { - "fields": { - "seconds": { - "type": "int64", - "id": 1 - }, - "nanos": { - "type": "int32", - "id": 2 - } - } - }, - "Duration": { - "fields": { - "seconds": { - "type": "int64", - "id": 1 - }, - "nanos": { - "type": "int32", - "id": 2 - } - } - }, - "DoubleValue": { - "fields": { - "value": { - "type": "double", - "id": 1 - } - } - }, - "FloatValue": { - "fields": { - "value": { - "type": "float", - "id": 1 - } - } - }, - "Int64Value": { - "fields": { - "value": { - "type": "int64", - "id": 1 - } - } - }, - "UInt64Value": { - "fields": { - "value": { - "type": "uint64", - "id": 1 - } - } - }, - "Int32Value": { - "fields": { - "value": { - "type": "int32", - "id": 1 - } - } - }, - "UInt32Value": { - "fields": { - "value": { - "type": "uint32", - "id": 1 - } - } - }, - "BoolValue": { - "fields": { - "value": { - "type": "bool", - "id": 1 - } - } - }, - "StringValue": { - "fields": { - "value": { - "type": "string", - "id": 1 - } - } - }, - "BytesValue": { - "fields": { - "value": { - "type": "bytes", - "id": 1 - } - } - }, - "Empty": { - "fields": {} - }, - "Any": { - "fields": { - "type_url": { - "type": "string", - "id": 1 - }, - "value": { - "type": "bytes", - "id": 2 - } - } - }, "FieldMask": { "fields": { "paths": { @@ -5719,4 +4277,4 @@ } } } -} +} \ No newline at end of file diff --git a/dev/protos/v1beta1.json b/dev/protos/v1beta1.json index 626ccd8f9..784b3abbb 100644 --- a/dev/protos/v1beta1.json +++ b/dev/protos/v1beta1.json @@ -1,7 +1,4 @@ { - "options": { - "syntax": "proto3" - }, "nested": { "google": { "nested": { @@ -92,6 +89,7 @@ } }, "FileDescriptorSet": { + "edition": "proto2", "fields": { "file": { "rule": "repeated", @@ -101,6 +99,7 @@ } }, "Edition": { + "edition": "proto2", "values": { "EDITION_UNKNOWN": 0, "EDITION_PROTO2": 998, @@ -116,6 +115,7 @@ } }, "FileDescriptorProto": { + "edition": "proto2", "fields": { "name": { "type": "string", @@ -133,18 +133,12 @@ "publicDependency": { "rule": "repeated", "type": "int32", - "id": 10, - "options": { - "packed": false - } + "id": 10 }, "weakDependency": { "rule": "repeated", "type": "int32", - "id": 11, - "options": { - "packed": false - } + "id": 11 }, "messageType": { "rule": "repeated", @@ -185,6 +179,7 @@ } }, "DescriptorProto": { + "edition": "proto2", "fields": { "name": { "type": "string", @@ -267,6 +262,7 @@ } }, "ExtensionRangeOptions": { + "edition": "proto2", "fields": { "uninterpretedOption": { "rule": "repeated", @@ -340,6 +336,7 @@ } }, "FieldDescriptorProto": { + "edition": "proto2", "fields": { "name": { "type": "string", @@ -419,6 +416,7 @@ } }, "OneofDescriptorProto": { + "edition": "proto2", "fields": { "name": { "type": "string", @@ -431,6 +429,7 @@ } }, "EnumDescriptorProto": { + "edition": "proto2", "fields": { "name": { "type": "string", @@ -472,6 +471,7 @@ } }, "EnumValueDescriptorProto": { + "edition": "proto2", "fields": { "name": { "type": "string", @@ -488,6 +488,7 @@ } }, "ServiceDescriptorProto": { + "edition": "proto2", "fields": { "name": { "type": "string", @@ -505,6 +506,7 @@ } }, "MethodDescriptorProto": { + "edition": "proto2", "fields": { "name": { "type": "string", @@ -539,6 +541,7 @@ } }, "FileOptions": { + "edition": "proto2", "fields": { "javaPackage": { "type": "string", @@ -680,6 +683,7 @@ } }, "MessageOptions": { + "edition": "proto2", "fields": { "messageSetWireFormat": { "type": "bool", @@ -753,6 +757,7 @@ ] }, "FieldOptions": { + "edition": "proto2", "fields": { "ctype": { "type": "CType", @@ -814,10 +819,7 @@ "targets": { "rule": "repeated", "type": "OptionTargetType", - "id": 19, - "options": { - "packed": false - } + "id": 19 }, "editionDefaults": { "rule": "repeated", @@ -901,6 +903,7 @@ } }, "OneofOptions": { + "edition": "proto2", "fields": { "features": { "type": "FeatureSet", @@ -920,6 +923,7 @@ ] }, "EnumOptions": { + "edition": "proto2", "fields": { "allowAlias": { "type": "bool", @@ -963,6 +967,7 @@ ] }, "EnumValueOptions": { + "edition": "proto2", "fields": { "deprecated": { "type": "bool", @@ -996,6 +1001,7 @@ ] }, "ServiceOptions": { + "edition": "proto2", "fields": { "features": { "type": "FeatureSet", @@ -1022,6 +1028,7 @@ ] }, "MethodOptions": { + "edition": "proto2", "fields": { "deprecated": { "type": "bool", @@ -1064,6 +1071,7 @@ } }, "UninterpretedOption": { + "edition": "proto2", "fields": { "name": { "rule": "repeated", @@ -1113,6 +1121,7 @@ } }, "FeatureSet": { + "edition": "proto2", "fields": { "fieldPresence": { "type": "FieldPresence", @@ -1250,6 +1259,7 @@ } }, "FeatureSetDefaults": { + "edition": "proto2", "fields": { "defaults": { "rule": "repeated", @@ -1281,6 +1291,7 @@ } }, "SourceCodeInfo": { + "edition": "proto2", "fields": { "location": { "rule": "repeated", @@ -1294,12 +1305,18 @@ "path": { "rule": "repeated", "type": "int32", - "id": 1 + "id": 1, + "options": { + "packed": true + } }, "span": { "rule": "repeated", "type": "int32", - "id": 2 + "id": 2, + "options": { + "packed": true + } }, "leadingComments": { "type": "string", @@ -1319,6 +1336,7 @@ } }, "GeneratedCodeInfo": { + "edition": "proto2", "fields": { "annotation": { "rule": "repeated", @@ -1332,7 +1350,10 @@ "path": { "rule": "repeated", "type": "int32", - "id": 1 + "id": 1, + "options": { + "packed": true + } }, "sourceFile": { "type": "string", @@ -3148,7 +3169,7 @@ "options": { "go_package": "google.golang.org/genproto/googleapis/api/annotations;annotations", "java_multiple_files": true, - "java_outer_classname": "ResourceProto", + "java_outer_classname": "RoutingProto", "java_package": "com.google.api", "objc_class_prefix": "GAPI", "cc_enable_arenas": true @@ -3275,10 +3296,6 @@ "rule": "repeated", "type": "ClientLibraryDestination", "id": 2 - }, - "selectiveGapicGeneration": { - "type": "SelectiveGapicGeneration", - "id": 3 } } }, @@ -3419,24 +3436,6 @@ "common": { "type": "CommonLanguageSettings", "id": 1 - }, - "experimentalFeatures": { - "type": "ExperimentalFeatures", - "id": 2 - } - }, - "nested": { - "ExperimentalFeatures": { - "fields": { - "restAsyncIoEnabled": { - "type": "bool", - "id": 1 - }, - "protobufPythonicTypesEnabled": { - "type": "bool", - "id": 2 - } - } } } }, @@ -3494,11 +3493,6 @@ "common": { "type": "CommonLanguageSettings", "id": 1 - }, - "renamedServices": { - "keyType": "string", - "type": "string", - "id": 2 } } }, @@ -3560,19 +3554,6 @@ "PACKAGE_MANAGER": 20 } }, - "SelectiveGapicGeneration": { - "fields": { - "methods": { - "rule": "repeated", - "type": "string", - "id": 1 - }, - "generateOmittedAsInternal": { - "type": "bool", - "id": 2 - } - } - }, "LaunchStage": { "values": { "LAUNCH_STAGE_UNSPECIFIED": 0, @@ -3683,6 +3664,32 @@ "id": 2 } } + }, + "routing": { + "type": "google.api.RoutingRule", + "id": 72295729, + "extend": "google.protobuf.MethodOptions" + }, + "RoutingRule": { + "fields": { + "routingParameters": { + "rule": "repeated", + "type": "RoutingParameter", + "id": 2 + } + } + }, + "RoutingParameter": { + "fields": { + "field": { + "type": "string", + "id": 1 + }, + "pathTemplate": { + "type": "string", + "id": 2 + } + } } } }, diff --git a/dev/src/v1/firestore_admin_client.ts b/dev/src/v1/firestore_admin_client.ts index 5143c3e2c..dfddc415c 100644 --- a/dev/src/v1/firestore_admin_client.ts +++ b/dev/src/v1/firestore_admin_client.ts @@ -18,21 +18,11 @@ /* global window */ import type * as gax from 'google-gax'; -import type { - Callback, - CallOptions, - Descriptors, - ClientOptions, - GrpcClientOptions, - LROperation, - PaginationCallback, - GaxCall, - LocationsClient, - LocationProtos, -} from 'google-gax'; +import type {Callback, CallOptions, Descriptors, ClientOptions, GrpcClientOptions, LROperation, PaginationCallback, GaxCall, LocationsClient, LocationProtos} from 'google-gax'; import {Transform} from 'stream'; import * as protos from '../../protos/firestore_admin_v1_proto_api'; import jsonProtos = require('../../protos/admin_v1.json'); +import {loggingUtils as logging} from 'google-gax'; /** * Client JSON configuration object, loaded from @@ -84,6 +74,8 @@ export class FirestoreAdminClient { private _defaults: {[method: string]: gax.CallSettings}; private _universeDomain: string; private _servicePath: string; + private _log = logging.log('firestore-admin'); + auth: gax.GoogleAuth; descriptors: Descriptors = { page: {}, @@ -120,7 +112,7 @@ export class FirestoreAdminClient { * Developer's Console, e.g. 'grape-spaceship-123'. We will also check * the environment variable GCLOUD_PROJECT for your project ID. If your * app is running in an environment which supports - * {@link https://developers.google.com/identity/protocols/application-default-credentials Application Default Credentials}, + * {@link https://cloud.google.com/docs/authentication/application-default-credentials Application Default Credentials}, * your project ID will be detected automatically. * @param {string} [options.apiEndpoint] - The domain name of the * API remote host. @@ -137,41 +129,20 @@ export class FirestoreAdminClient { * const client = new FirestoreAdminClient({fallback: true}, gax); * ``` */ - constructor( - opts?: ClientOptions, - gaxInstance?: typeof gax | typeof gax.fallback - ) { + constructor(opts?: ClientOptions, gaxInstance?: typeof gax | typeof gax.fallback) { // Ensure that options include all the required fields. const staticMembers = this.constructor as typeof FirestoreAdminClient; - if ( - opts?.universe_domain && - opts?.universeDomain && - opts?.universe_domain !== opts?.universeDomain - ) { - throw new Error( - 'Please set either universe_domain or universeDomain, but not both.' - ); + if (opts?.universe_domain && opts?.universeDomain && opts?.universe_domain !== opts?.universeDomain) { + throw new Error('Please set either universe_domain or universeDomain, but not both.'); } - const universeDomainEnvVar = - typeof process === 'object' && typeof process.env === 'object' - ? process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] - : undefined; - this._universeDomain = - opts?.universeDomain ?? - opts?.universe_domain ?? - universeDomainEnvVar ?? - 'googleapis.com'; + const universeDomainEnvVar = (typeof process === 'object' && typeof process.env === 'object') ? process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] : undefined; + this._universeDomain = opts?.universeDomain ?? opts?.universe_domain ?? universeDomainEnvVar ?? 'googleapis.com'; this._servicePath = 'firestore.' + this._universeDomain; - const servicePath = - opts?.servicePath || opts?.apiEndpoint || this._servicePath; - this._providedCustomServicePath = !!( - opts?.servicePath || opts?.apiEndpoint - ); + const servicePath = opts?.servicePath || opts?.apiEndpoint || this._servicePath; + this._providedCustomServicePath = !!(opts?.servicePath || opts?.apiEndpoint); const port = opts?.port || staticMembers.port; const clientConfig = opts?.clientConfig ?? {}; - const fallback = - opts?.fallback ?? - (typeof window !== 'undefined' && typeof window?.fetch === 'function'); + const fallback = opts?.fallback ?? (typeof window !== 'undefined' && typeof window?.fetch === 'function'); opts = Object.assign({servicePath, port, clientConfig, fallback}, opts); // Request numeric enum values if REST transport is used. @@ -197,7 +168,7 @@ export class FirestoreAdminClient { this._opts = opts; // Save the auth object to the client, for use by other methods. - this.auth = this._gaxGrpc.auth as gax.GoogleAuth; + this.auth = (this._gaxGrpc.auth as gax.GoogleAuth); // Set useJWTAccessWithScope on the auth object. this.auth.useJWTAccessWithScope = true; @@ -213,9 +184,13 @@ export class FirestoreAdminClient { this._gaxGrpc, opts ); + // Determine the client header string. - const clientHeader = [`gax/${this._gaxModule.version}`, `gapic/${version}`]; + const clientHeader = [ + `gax/${this._gaxModule.version}`, + `gapic/${version}`, + ]; if (typeof process === 'object' && 'versions' in process) { clientHeader.push(`gl-node/${process.versions.node}`); } else { @@ -260,22 +235,19 @@ export class FirestoreAdminClient { projectPathTemplate: new this._gaxModule.PathTemplate( 'projects/{project}' ), + userCredsPathTemplate: new this._gaxModule.PathTemplate( + 'projects/{project}/databases/{database}/userCreds/{user_creds}' + ), }; // Some of the methods on this service return "paged" results, // (e.g. 50 results at a time, with tokens to get subsequent // pages). Denote the keys used for pagination and results. this.descriptors.page = { - listIndexes: new this._gaxModule.PageDescriptor( - 'pageToken', - 'nextPageToken', - 'indexes' - ), - listFields: new this._gaxModule.PageDescriptor( - 'pageToken', - 'nextPageToken', - 'fields' - ), + listIndexes: + new this._gaxModule.PageDescriptor('pageToken', 'nextPageToken', 'indexes'), + listFields: + new this._gaxModule.PageDescriptor('pageToken', 'nextPageToken', 'fields') }; const protoFilesRoot = this._gaxModule.protobuf.Root.fromJSON(jsonProtos); @@ -284,143 +256,93 @@ export class FirestoreAdminClient { // rather than holding a request open. const lroOptions: GrpcClientOptions = { auth: this.auth, - grpc: 'grpc' in this._gaxGrpc ? this._gaxGrpc.grpc : undefined, + grpc: 'grpc' in this._gaxGrpc ? this._gaxGrpc.grpc : undefined }; if (opts.fallback) { lroOptions.protoJson = protoFilesRoot; - lroOptions.httpRules = [ - { - selector: 'google.longrunning.Operations.CancelOperation', - post: '/v1/{name=projects/*/databases/*/operations/*}:cancel', - body: '*', - }, - { - selector: 'google.longrunning.Operations.DeleteOperation', - delete: '/v1/{name=projects/*/databases/*/operations/*}', - }, - { - selector: 'google.longrunning.Operations.GetOperation', - get: '/v1/{name=projects/*/databases/*/operations/*}', - }, - { - selector: 'google.longrunning.Operations.ListOperations', - get: '/v1/{name=projects/*/databases/*}/operations', - }, - ]; + lroOptions.httpRules = [{selector: 'google.longrunning.Operations.CancelOperation',post: '/v1/{name=projects/*/databases/*/operations/*}:cancel',body: '*',},{selector: 'google.longrunning.Operations.DeleteOperation',delete: '/v1/{name=projects/*/databases/*/operations/*}',},{selector: 'google.longrunning.Operations.GetOperation',get: '/v1/{name=projects/*/databases/*/operations/*}',},{selector: 'google.longrunning.Operations.ListOperations',get: '/v1/{name=projects/*/databases/*}/operations',}]; } - this.operationsClient = this._gaxModule - .lro(lroOptions) - .operationsClient(opts); + this.operationsClient = this._gaxModule.lro(lroOptions).operationsClient(opts); const createIndexResponse = protoFilesRoot.lookup( - '.google.firestore.admin.v1.Index' - ) as gax.protobuf.Type; + '.google.firestore.admin.v1.Index') as gax.protobuf.Type; const createIndexMetadata = protoFilesRoot.lookup( - '.google.firestore.admin.v1.IndexOperationMetadata' - ) as gax.protobuf.Type; + '.google.firestore.admin.v1.IndexOperationMetadata') as gax.protobuf.Type; const updateFieldResponse = protoFilesRoot.lookup( - '.google.firestore.admin.v1.Field' - ) as gax.protobuf.Type; + '.google.firestore.admin.v1.Field') as gax.protobuf.Type; const updateFieldMetadata = protoFilesRoot.lookup( - '.google.firestore.admin.v1.FieldOperationMetadata' - ) as gax.protobuf.Type; + '.google.firestore.admin.v1.FieldOperationMetadata') as gax.protobuf.Type; const exportDocumentsResponse = protoFilesRoot.lookup( - '.google.firestore.admin.v1.ExportDocumentsResponse' - ) as gax.protobuf.Type; + '.google.firestore.admin.v1.ExportDocumentsResponse') as gax.protobuf.Type; const exportDocumentsMetadata = protoFilesRoot.lookup( - '.google.firestore.admin.v1.ExportDocumentsMetadata' - ) as gax.protobuf.Type; + '.google.firestore.admin.v1.ExportDocumentsMetadata') as gax.protobuf.Type; const importDocumentsResponse = protoFilesRoot.lookup( - '.google.protobuf.Empty' - ) as gax.protobuf.Type; + '.google.protobuf.Empty') as gax.protobuf.Type; const importDocumentsMetadata = protoFilesRoot.lookup( - '.google.firestore.admin.v1.ImportDocumentsMetadata' - ) as gax.protobuf.Type; + '.google.firestore.admin.v1.ImportDocumentsMetadata') as gax.protobuf.Type; const bulkDeleteDocumentsResponse = protoFilesRoot.lookup( - '.google.firestore.admin.v1.BulkDeleteDocumentsResponse' - ) as gax.protobuf.Type; + '.google.firestore.admin.v1.BulkDeleteDocumentsResponse') as gax.protobuf.Type; const bulkDeleteDocumentsMetadata = protoFilesRoot.lookup( - '.google.firestore.admin.v1.BulkDeleteDocumentsMetadata' - ) as gax.protobuf.Type; + '.google.firestore.admin.v1.BulkDeleteDocumentsMetadata') as gax.protobuf.Type; const createDatabaseResponse = protoFilesRoot.lookup( - '.google.firestore.admin.v1.Database' - ) as gax.protobuf.Type; + '.google.firestore.admin.v1.Database') as gax.protobuf.Type; const createDatabaseMetadata = protoFilesRoot.lookup( - '.google.firestore.admin.v1.CreateDatabaseMetadata' - ) as gax.protobuf.Type; + '.google.firestore.admin.v1.CreateDatabaseMetadata') as gax.protobuf.Type; const updateDatabaseResponse = protoFilesRoot.lookup( - '.google.firestore.admin.v1.Database' - ) as gax.protobuf.Type; + '.google.firestore.admin.v1.Database') as gax.protobuf.Type; const updateDatabaseMetadata = protoFilesRoot.lookup( - '.google.firestore.admin.v1.UpdateDatabaseMetadata' - ) as gax.protobuf.Type; + '.google.firestore.admin.v1.UpdateDatabaseMetadata') as gax.protobuf.Type; const deleteDatabaseResponse = protoFilesRoot.lookup( - '.google.firestore.admin.v1.Database' - ) as gax.protobuf.Type; + '.google.firestore.admin.v1.Database') as gax.protobuf.Type; const deleteDatabaseMetadata = protoFilesRoot.lookup( - '.google.firestore.admin.v1.DeleteDatabaseMetadata' - ) as gax.protobuf.Type; + '.google.firestore.admin.v1.DeleteDatabaseMetadata') as gax.protobuf.Type; const restoreDatabaseResponse = protoFilesRoot.lookup( - '.google.firestore.admin.v1.Database' - ) as gax.protobuf.Type; + '.google.firestore.admin.v1.Database') as gax.protobuf.Type; const restoreDatabaseMetadata = protoFilesRoot.lookup( - '.google.firestore.admin.v1.RestoreDatabaseMetadata' - ) as gax.protobuf.Type; + '.google.firestore.admin.v1.RestoreDatabaseMetadata') as gax.protobuf.Type; this.descriptors.longrunning = { createIndex: new this._gaxModule.LongrunningDescriptor( this.operationsClient, createIndexResponse.decode.bind(createIndexResponse), - createIndexMetadata.decode.bind(createIndexMetadata) - ), + createIndexMetadata.decode.bind(createIndexMetadata)), updateField: new this._gaxModule.LongrunningDescriptor( this.operationsClient, updateFieldResponse.decode.bind(updateFieldResponse), - updateFieldMetadata.decode.bind(updateFieldMetadata) - ), + updateFieldMetadata.decode.bind(updateFieldMetadata)), exportDocuments: new this._gaxModule.LongrunningDescriptor( this.operationsClient, exportDocumentsResponse.decode.bind(exportDocumentsResponse), - exportDocumentsMetadata.decode.bind(exportDocumentsMetadata) - ), + exportDocumentsMetadata.decode.bind(exportDocumentsMetadata)), importDocuments: new this._gaxModule.LongrunningDescriptor( this.operationsClient, importDocumentsResponse.decode.bind(importDocumentsResponse), - importDocumentsMetadata.decode.bind(importDocumentsMetadata) - ), + importDocumentsMetadata.decode.bind(importDocumentsMetadata)), bulkDeleteDocuments: new this._gaxModule.LongrunningDescriptor( this.operationsClient, bulkDeleteDocumentsResponse.decode.bind(bulkDeleteDocumentsResponse), - bulkDeleteDocumentsMetadata.decode.bind(bulkDeleteDocumentsMetadata) - ), + bulkDeleteDocumentsMetadata.decode.bind(bulkDeleteDocumentsMetadata)), createDatabase: new this._gaxModule.LongrunningDescriptor( this.operationsClient, createDatabaseResponse.decode.bind(createDatabaseResponse), - createDatabaseMetadata.decode.bind(createDatabaseMetadata) - ), + createDatabaseMetadata.decode.bind(createDatabaseMetadata)), updateDatabase: new this._gaxModule.LongrunningDescriptor( this.operationsClient, updateDatabaseResponse.decode.bind(updateDatabaseResponse), - updateDatabaseMetadata.decode.bind(updateDatabaseMetadata) - ), + updateDatabaseMetadata.decode.bind(updateDatabaseMetadata)), deleteDatabase: new this._gaxModule.LongrunningDescriptor( this.operationsClient, deleteDatabaseResponse.decode.bind(deleteDatabaseResponse), - deleteDatabaseMetadata.decode.bind(deleteDatabaseMetadata) - ), + deleteDatabaseMetadata.decode.bind(deleteDatabaseMetadata)), restoreDatabase: new this._gaxModule.LongrunningDescriptor( this.operationsClient, restoreDatabaseResponse.decode.bind(restoreDatabaseResponse), - restoreDatabaseMetadata.decode.bind(restoreDatabaseMetadata) - ), + restoreDatabaseMetadata.decode.bind(restoreDatabaseMetadata)) }; // Put together the default options sent with requests. this._defaults = this._gaxGrpc.constructSettings( - 'google.firestore.admin.v1.FirestoreAdmin', - gapicConfig as gax.ClientConfig, - opts.clientConfig || {}, - {'x-goog-api-client': clientHeader.join(' ')} - ); + 'google.firestore.admin.v1.FirestoreAdmin', gapicConfig as gax.ClientConfig, + opts.clientConfig || {}, {'x-goog-api-client': clientHeader.join(' ')}); // Set up a dictionary of "inner API calls"; the core implementation // of calling the API is handled in `google-gax`, with this code @@ -451,58 +373,28 @@ export class FirestoreAdminClient { // Put together the "service stub" for // google.firestore.admin.v1.FirestoreAdmin. this.firestoreAdminStub = this._gaxGrpc.createStub( - this._opts.fallback - ? (this._protos as protobuf.Root).lookupService( - 'google.firestore.admin.v1.FirestoreAdmin' - ) - : // eslint-disable-next-line @typescript-eslint/no-explicit-any + this._opts.fallback ? + (this._protos as protobuf.Root).lookupService('google.firestore.admin.v1.FirestoreAdmin') : + // eslint-disable-next-line @typescript-eslint/no-explicit-any (this._protos as any).google.firestore.admin.v1.FirestoreAdmin, - this._opts, - this._providedCustomServicePath - ) as Promise<{[method: string]: Function}>; + this._opts, this._providedCustomServicePath) as Promise<{[method: string]: Function}>; // Iterate over each of the methods that the service provides // and create an API call method for each. - const firestoreAdminStubMethods = [ - 'createIndex', - 'listIndexes', - 'getIndex', - 'deleteIndex', - 'getField', - 'updateField', - 'listFields', - 'exportDocuments', - 'importDocuments', - 'bulkDeleteDocuments', - 'createDatabase', - 'getDatabase', - 'listDatabases', - 'updateDatabase', - 'deleteDatabase', - 'getBackup', - 'listBackups', - 'deleteBackup', - 'restoreDatabase', - 'createBackupSchedule', - 'getBackupSchedule', - 'listBackupSchedules', - 'updateBackupSchedule', - 'deleteBackupSchedule', - ]; + const firestoreAdminStubMethods = + ['createIndex', 'listIndexes', 'getIndex', 'deleteIndex', 'getField', 'updateField', 'listFields', 'exportDocuments', 'importDocuments', 'bulkDeleteDocuments', 'createDatabase', 'getDatabase', 'listDatabases', 'updateDatabase', 'deleteDatabase', 'createUserCreds', 'getUserCreds', 'listUserCreds', 'enableUserCreds', 'disableUserCreds', 'resetUserPassword', 'deleteUserCreds', 'getBackup', 'listBackups', 'deleteBackup', 'restoreDatabase', 'createBackupSchedule', 'getBackupSchedule', 'listBackupSchedules', 'updateBackupSchedule', 'deleteBackupSchedule']; for (const methodName of firestoreAdminStubMethods) { const callPromise = this.firestoreAdminStub.then( - stub => - (...args: Array<{}>) => { - if (this._terminated) { - return Promise.reject('The client has already been closed.'); - } - const func = stub[methodName]; - return func.apply(stub, args); - }, - (err: Error | null | undefined) => () => { + stub => (...args: Array<{}>) => { + if (this._terminated) { + return Promise.reject('The client has already been closed.'); + } + const func = stub[methodName]; + return func.apply(stub, args); + }, + (err: Error|null|undefined) => () => { throw err; - } - ); + }); const descriptor = this.descriptors.page[methodName] || @@ -527,14 +419,8 @@ export class FirestoreAdminClient { * @returns {string} The DNS address for this service. */ static get servicePath() { - if ( - typeof process === 'object' && - typeof process.emitWarning === 'function' - ) { - process.emitWarning( - 'Static servicePath is deprecated, please use the instance method instead.', - 'DeprecationWarning' - ); + if (typeof process === 'object' && typeof process.emitWarning === 'function') { + process.emitWarning('Static servicePath is deprecated, please use the instance method instead.', 'DeprecationWarning'); } return 'firestore.googleapis.com'; } @@ -545,14 +431,8 @@ export class FirestoreAdminClient { * @returns {string} The DNS address for this service. */ static get apiEndpoint() { - if ( - typeof process === 'object' && - typeof process.emitWarning === 'function' - ) { - process.emitWarning( - 'Static apiEndpoint is deprecated, please use the instance method instead.', - 'DeprecationWarning' - ); + if (typeof process === 'object' && typeof process.emitWarning === 'function') { + process.emitWarning('Static apiEndpoint is deprecated, please use the instance method instead.', 'DeprecationWarning'); } return 'firestore.googleapis.com'; } @@ -585,7 +465,7 @@ export class FirestoreAdminClient { static get scopes() { return [ 'https://www.googleapis.com/auth/cloud-platform', - 'https://www.googleapis.com/auth/datastore', + 'https://www.googleapis.com/auth/datastore' ]; } @@ -595,9 +475,8 @@ export class FirestoreAdminClient { * Return the project ID used by this class. * @returns {Promise} A promise that resolves to string containing the project ID. */ - getProjectId( - callback?: Callback - ): Promise | void { + getProjectId(callback?: Callback): + Promise|void { if (callback) { this.auth.getProjectId(callback); return; @@ -608,2698 +487,3108 @@ export class FirestoreAdminClient { // ------------------- // -- Service calls -- // ------------------- - /** - * Gets a composite index. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.name - * Required. A name of the form - * `projects/{project_id}/databases/{database_id}/collectionGroups/{collection_id}/indexes/{index_id}` - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Promise} - The promise which resolves to an array. - * The first element of the array is an object representing {@link protos.google.firestore.admin.v1.Index|Index}. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } - * for more details and examples. - * @example - * region_tag:firestore_v1_generated_FirestoreAdmin_GetIndex_async - */ +/** + * Gets a composite index. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.name + * Required. A name of the form + * `projects/{project_id}/databases/{database_id}/collectionGroups/{collection_id}/indexes/{index_id}` + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is an object representing {@link protos.google.firestore.admin.v1.Index|Index}. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } + * for more details and examples. + * @example + * region_tag:firestore_v1_generated_FirestoreAdmin_GetIndex_async + */ getIndex( - request?: protos.google.firestore.admin.v1.IGetIndexRequest, - options?: CallOptions - ): Promise< - [ - protos.google.firestore.admin.v1.IIndex, - protos.google.firestore.admin.v1.IGetIndexRequest | undefined, - {} | undefined, - ] - >; + request?: protos.google.firestore.admin.v1.IGetIndexRequest, + options?: CallOptions): + Promise<[ + protos.google.firestore.admin.v1.IIndex, + protos.google.firestore.admin.v1.IGetIndexRequest|undefined, {}|undefined + ]>; getIndex( - request: protos.google.firestore.admin.v1.IGetIndexRequest, - options: CallOptions, - callback: Callback< - protos.google.firestore.admin.v1.IIndex, - protos.google.firestore.admin.v1.IGetIndexRequest | null | undefined, - {} | null | undefined - > - ): void; + request: protos.google.firestore.admin.v1.IGetIndexRequest, + options: CallOptions, + callback: Callback< + protos.google.firestore.admin.v1.IIndex, + protos.google.firestore.admin.v1.IGetIndexRequest|null|undefined, + {}|null|undefined>): void; getIndex( - request: protos.google.firestore.admin.v1.IGetIndexRequest, - callback: Callback< - protos.google.firestore.admin.v1.IIndex, - protos.google.firestore.admin.v1.IGetIndexRequest | null | undefined, - {} | null | undefined - > - ): void; + request: protos.google.firestore.admin.v1.IGetIndexRequest, + callback: Callback< + protos.google.firestore.admin.v1.IIndex, + protos.google.firestore.admin.v1.IGetIndexRequest|null|undefined, + {}|null|undefined>): void; getIndex( - request?: protos.google.firestore.admin.v1.IGetIndexRequest, - optionsOrCallback?: - | CallOptions - | Callback< + request?: protos.google.firestore.admin.v1.IGetIndexRequest, + optionsOrCallback?: CallOptions|Callback< protos.google.firestore.admin.v1.IIndex, - protos.google.firestore.admin.v1.IGetIndexRequest | null | undefined, - {} | null | undefined - >, - callback?: Callback< - protos.google.firestore.admin.v1.IIndex, - protos.google.firestore.admin.v1.IGetIndexRequest | null | undefined, - {} | null | undefined - > - ): Promise< - [ - protos.google.firestore.admin.v1.IIndex, - protos.google.firestore.admin.v1.IGetIndexRequest | undefined, - {} | undefined, - ] - > | void { + protos.google.firestore.admin.v1.IGetIndexRequest|null|undefined, + {}|null|undefined>, + callback?: Callback< + protos.google.firestore.admin.v1.IIndex, + protos.google.firestore.admin.v1.IGetIndexRequest|null|undefined, + {}|null|undefined>): + Promise<[ + protos.google.firestore.admin.v1.IIndex, + protos.google.firestore.admin.v1.IGetIndexRequest|undefined, {}|undefined + ]>|void { request = request || {}; let options: CallOptions; if (typeof optionsOrCallback === 'function' && callback === undefined) { callback = optionsOrCallback; options = {}; - } else { + } + else { options = optionsOrCallback as CallOptions; } options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - options.otherArgs.headers['x-goog-request-params'] = - this._gaxModule.routingHeader.fromParams({ - name: request.name ?? '', + options.otherArgs.headers[ + 'x-goog-request-params' + ] = this._gaxModule.routingHeader.fromParams({ + 'name': request.name ?? '', + }); + this.initialize().catch(err => {throw err}); + this._log.info('getIndex request %j', request); + const wrappedCallback: Callback< + protos.google.firestore.admin.v1.IIndex, + protos.google.firestore.admin.v1.IGetIndexRequest|null|undefined, + {}|null|undefined>|undefined = callback + ? (error, response, options, rawResponse) => { + this._log.info('getIndex response %j', response); + callback!(error, response, options, rawResponse); // We verified callback above. + } + : undefined; + return this.innerApiCalls.getIndex(request, options, wrappedCallback) + ?.then(([response, options, rawResponse]: [ + protos.google.firestore.admin.v1.IIndex, + protos.google.firestore.admin.v1.IGetIndexRequest|undefined, + {}|undefined + ]) => { + this._log.info('getIndex response %j', response); + return [response, options, rawResponse]; }); - this.initialize(); - return this.innerApiCalls.getIndex(request, options, callback); } - /** - * Deletes a composite index. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.name - * Required. A name of the form - * `projects/{project_id}/databases/{database_id}/collectionGroups/{collection_id}/indexes/{index_id}` - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Promise} - The promise which resolves to an array. - * The first element of the array is an object representing {@link protos.google.protobuf.Empty|Empty}. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } - * for more details and examples. - * @example - * region_tag:firestore_v1_generated_FirestoreAdmin_DeleteIndex_async - */ +/** + * Deletes a composite index. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.name + * Required. A name of the form + * `projects/{project_id}/databases/{database_id}/collectionGroups/{collection_id}/indexes/{index_id}` + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is an object representing {@link protos.google.protobuf.Empty|Empty}. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } + * for more details and examples. + * @example + * region_tag:firestore_v1_generated_FirestoreAdmin_DeleteIndex_async + */ deleteIndex( - request?: protos.google.firestore.admin.v1.IDeleteIndexRequest, - options?: CallOptions - ): Promise< - [ - protos.google.protobuf.IEmpty, - protos.google.firestore.admin.v1.IDeleteIndexRequest | undefined, - {} | undefined, - ] - >; + request?: protos.google.firestore.admin.v1.IDeleteIndexRequest, + options?: CallOptions): + Promise<[ + protos.google.protobuf.IEmpty, + protos.google.firestore.admin.v1.IDeleteIndexRequest|undefined, {}|undefined + ]>; deleteIndex( - request: protos.google.firestore.admin.v1.IDeleteIndexRequest, - options: CallOptions, - callback: Callback< - protos.google.protobuf.IEmpty, - protos.google.firestore.admin.v1.IDeleteIndexRequest | null | undefined, - {} | null | undefined - > - ): void; + request: protos.google.firestore.admin.v1.IDeleteIndexRequest, + options: CallOptions, + callback: Callback< + protos.google.protobuf.IEmpty, + protos.google.firestore.admin.v1.IDeleteIndexRequest|null|undefined, + {}|null|undefined>): void; deleteIndex( - request: protos.google.firestore.admin.v1.IDeleteIndexRequest, - callback: Callback< - protos.google.protobuf.IEmpty, - protos.google.firestore.admin.v1.IDeleteIndexRequest | null | undefined, - {} | null | undefined - > - ): void; + request: protos.google.firestore.admin.v1.IDeleteIndexRequest, + callback: Callback< + protos.google.protobuf.IEmpty, + protos.google.firestore.admin.v1.IDeleteIndexRequest|null|undefined, + {}|null|undefined>): void; deleteIndex( - request?: protos.google.firestore.admin.v1.IDeleteIndexRequest, - optionsOrCallback?: - | CallOptions - | Callback< + request?: protos.google.firestore.admin.v1.IDeleteIndexRequest, + optionsOrCallback?: CallOptions|Callback< protos.google.protobuf.IEmpty, - | protos.google.firestore.admin.v1.IDeleteIndexRequest - | null - | undefined, - {} | null | undefined - >, - callback?: Callback< - protos.google.protobuf.IEmpty, - protos.google.firestore.admin.v1.IDeleteIndexRequest | null | undefined, - {} | null | undefined - > - ): Promise< - [ - protos.google.protobuf.IEmpty, - protos.google.firestore.admin.v1.IDeleteIndexRequest | undefined, - {} | undefined, - ] - > | void { + protos.google.firestore.admin.v1.IDeleteIndexRequest|null|undefined, + {}|null|undefined>, + callback?: Callback< + protos.google.protobuf.IEmpty, + protos.google.firestore.admin.v1.IDeleteIndexRequest|null|undefined, + {}|null|undefined>): + Promise<[ + protos.google.protobuf.IEmpty, + protos.google.firestore.admin.v1.IDeleteIndexRequest|undefined, {}|undefined + ]>|void { request = request || {}; let options: CallOptions; if (typeof optionsOrCallback === 'function' && callback === undefined) { callback = optionsOrCallback; options = {}; - } else { + } + else { options = optionsOrCallback as CallOptions; } options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - options.otherArgs.headers['x-goog-request-params'] = - this._gaxModule.routingHeader.fromParams({ - name: request.name ?? '', + options.otherArgs.headers[ + 'x-goog-request-params' + ] = this._gaxModule.routingHeader.fromParams({ + 'name': request.name ?? '', + }); + this.initialize().catch(err => {throw err}); + this._log.info('deleteIndex request %j', request); + const wrappedCallback: Callback< + protos.google.protobuf.IEmpty, + protos.google.firestore.admin.v1.IDeleteIndexRequest|null|undefined, + {}|null|undefined>|undefined = callback + ? (error, response, options, rawResponse) => { + this._log.info('deleteIndex response %j', response); + callback!(error, response, options, rawResponse); // We verified callback above. + } + : undefined; + return this.innerApiCalls.deleteIndex(request, options, wrappedCallback) + ?.then(([response, options, rawResponse]: [ + protos.google.protobuf.IEmpty, + protos.google.firestore.admin.v1.IDeleteIndexRequest|undefined, + {}|undefined + ]) => { + this._log.info('deleteIndex response %j', response); + return [response, options, rawResponse]; }); - this.initialize(); - return this.innerApiCalls.deleteIndex(request, options, callback); } - /** - * Gets the metadata and configuration for a Field. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.name - * Required. A name of the form - * `projects/{project_id}/databases/{database_id}/collectionGroups/{collection_id}/fields/{field_id}` - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Promise} - The promise which resolves to an array. - * The first element of the array is an object representing {@link protos.google.firestore.admin.v1.Field|Field}. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } - * for more details and examples. - * @example - * region_tag:firestore_v1_generated_FirestoreAdmin_GetField_async - */ +/** + * Gets the metadata and configuration for a Field. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.name + * Required. A name of the form + * `projects/{project_id}/databases/{database_id}/collectionGroups/{collection_id}/fields/{field_id}` + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is an object representing {@link protos.google.firestore.admin.v1.Field|Field}. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } + * for more details and examples. + * @example + * region_tag:firestore_v1_generated_FirestoreAdmin_GetField_async + */ getField( - request?: protos.google.firestore.admin.v1.IGetFieldRequest, - options?: CallOptions - ): Promise< - [ - protos.google.firestore.admin.v1.IField, - protos.google.firestore.admin.v1.IGetFieldRequest | undefined, - {} | undefined, - ] - >; + request?: protos.google.firestore.admin.v1.IGetFieldRequest, + options?: CallOptions): + Promise<[ + protos.google.firestore.admin.v1.IField, + protos.google.firestore.admin.v1.IGetFieldRequest|undefined, {}|undefined + ]>; getField( - request: protos.google.firestore.admin.v1.IGetFieldRequest, - options: CallOptions, - callback: Callback< - protos.google.firestore.admin.v1.IField, - protos.google.firestore.admin.v1.IGetFieldRequest | null | undefined, - {} | null | undefined - > - ): void; + request: protos.google.firestore.admin.v1.IGetFieldRequest, + options: CallOptions, + callback: Callback< + protos.google.firestore.admin.v1.IField, + protos.google.firestore.admin.v1.IGetFieldRequest|null|undefined, + {}|null|undefined>): void; getField( - request: protos.google.firestore.admin.v1.IGetFieldRequest, - callback: Callback< - protos.google.firestore.admin.v1.IField, - protos.google.firestore.admin.v1.IGetFieldRequest | null | undefined, - {} | null | undefined - > - ): void; + request: protos.google.firestore.admin.v1.IGetFieldRequest, + callback: Callback< + protos.google.firestore.admin.v1.IField, + protos.google.firestore.admin.v1.IGetFieldRequest|null|undefined, + {}|null|undefined>): void; getField( - request?: protos.google.firestore.admin.v1.IGetFieldRequest, - optionsOrCallback?: - | CallOptions - | Callback< + request?: protos.google.firestore.admin.v1.IGetFieldRequest, + optionsOrCallback?: CallOptions|Callback< protos.google.firestore.admin.v1.IField, - protos.google.firestore.admin.v1.IGetFieldRequest | null | undefined, - {} | null | undefined - >, - callback?: Callback< - protos.google.firestore.admin.v1.IField, - protos.google.firestore.admin.v1.IGetFieldRequest | null | undefined, - {} | null | undefined - > - ): Promise< - [ - protos.google.firestore.admin.v1.IField, - protos.google.firestore.admin.v1.IGetFieldRequest | undefined, - {} | undefined, - ] - > | void { + protos.google.firestore.admin.v1.IGetFieldRequest|null|undefined, + {}|null|undefined>, + callback?: Callback< + protos.google.firestore.admin.v1.IField, + protos.google.firestore.admin.v1.IGetFieldRequest|null|undefined, + {}|null|undefined>): + Promise<[ + protos.google.firestore.admin.v1.IField, + protos.google.firestore.admin.v1.IGetFieldRequest|undefined, {}|undefined + ]>|void { request = request || {}; let options: CallOptions; if (typeof optionsOrCallback === 'function' && callback === undefined) { callback = optionsOrCallback; options = {}; - } else { + } + else { options = optionsOrCallback as CallOptions; } options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - options.otherArgs.headers['x-goog-request-params'] = - this._gaxModule.routingHeader.fromParams({ - name: request.name ?? '', + options.otherArgs.headers[ + 'x-goog-request-params' + ] = this._gaxModule.routingHeader.fromParams({ + 'name': request.name ?? '', + }); + this.initialize().catch(err => {throw err}); + this._log.info('getField request %j', request); + const wrappedCallback: Callback< + protos.google.firestore.admin.v1.IField, + protos.google.firestore.admin.v1.IGetFieldRequest|null|undefined, + {}|null|undefined>|undefined = callback + ? (error, response, options, rawResponse) => { + this._log.info('getField response %j', response); + callback!(error, response, options, rawResponse); // We verified callback above. + } + : undefined; + return this.innerApiCalls.getField(request, options, wrappedCallback) + ?.then(([response, options, rawResponse]: [ + protos.google.firestore.admin.v1.IField, + protos.google.firestore.admin.v1.IGetFieldRequest|undefined, + {}|undefined + ]) => { + this._log.info('getField response %j', response); + return [response, options, rawResponse]; }); - this.initialize(); - return this.innerApiCalls.getField(request, options, callback); } - /** - * Gets information about a database. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.name - * Required. A name of the form - * `projects/{project_id}/databases/{database_id}` - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Promise} - The promise which resolves to an array. - * The first element of the array is an object representing {@link protos.google.firestore.admin.v1.Database|Database}. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } - * for more details and examples. - * @example - * region_tag:firestore_v1_generated_FirestoreAdmin_GetDatabase_async - */ +/** + * Gets information about a database. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.name + * Required. A name of the form + * `projects/{project_id}/databases/{database_id}` + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is an object representing {@link protos.google.firestore.admin.v1.Database|Database}. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } + * for more details and examples. + * @example + * region_tag:firestore_v1_generated_FirestoreAdmin_GetDatabase_async + */ getDatabase( - request?: protos.google.firestore.admin.v1.IGetDatabaseRequest, - options?: CallOptions - ): Promise< - [ - protos.google.firestore.admin.v1.IDatabase, - protos.google.firestore.admin.v1.IGetDatabaseRequest | undefined, - {} | undefined, - ] - >; + request?: protos.google.firestore.admin.v1.IGetDatabaseRequest, + options?: CallOptions): + Promise<[ + protos.google.firestore.admin.v1.IDatabase, + protos.google.firestore.admin.v1.IGetDatabaseRequest|undefined, {}|undefined + ]>; getDatabase( - request: protos.google.firestore.admin.v1.IGetDatabaseRequest, - options: CallOptions, - callback: Callback< - protos.google.firestore.admin.v1.IDatabase, - protos.google.firestore.admin.v1.IGetDatabaseRequest | null | undefined, - {} | null | undefined - > - ): void; + request: protos.google.firestore.admin.v1.IGetDatabaseRequest, + options: CallOptions, + callback: Callback< + protos.google.firestore.admin.v1.IDatabase, + protos.google.firestore.admin.v1.IGetDatabaseRequest|null|undefined, + {}|null|undefined>): void; getDatabase( - request: protos.google.firestore.admin.v1.IGetDatabaseRequest, - callback: Callback< - protos.google.firestore.admin.v1.IDatabase, - protos.google.firestore.admin.v1.IGetDatabaseRequest | null | undefined, - {} | null | undefined - > - ): void; + request: protos.google.firestore.admin.v1.IGetDatabaseRequest, + callback: Callback< + protos.google.firestore.admin.v1.IDatabase, + protos.google.firestore.admin.v1.IGetDatabaseRequest|null|undefined, + {}|null|undefined>): void; getDatabase( - request?: protos.google.firestore.admin.v1.IGetDatabaseRequest, - optionsOrCallback?: - | CallOptions - | Callback< + request?: protos.google.firestore.admin.v1.IGetDatabaseRequest, + optionsOrCallback?: CallOptions|Callback< protos.google.firestore.admin.v1.IDatabase, - | protos.google.firestore.admin.v1.IGetDatabaseRequest - | null - | undefined, - {} | null | undefined - >, - callback?: Callback< - protos.google.firestore.admin.v1.IDatabase, - protos.google.firestore.admin.v1.IGetDatabaseRequest | null | undefined, - {} | null | undefined - > - ): Promise< - [ - protos.google.firestore.admin.v1.IDatabase, - protos.google.firestore.admin.v1.IGetDatabaseRequest | undefined, - {} | undefined, - ] - > | void { + protos.google.firestore.admin.v1.IGetDatabaseRequest|null|undefined, + {}|null|undefined>, + callback?: Callback< + protos.google.firestore.admin.v1.IDatabase, + protos.google.firestore.admin.v1.IGetDatabaseRequest|null|undefined, + {}|null|undefined>): + Promise<[ + protos.google.firestore.admin.v1.IDatabase, + protos.google.firestore.admin.v1.IGetDatabaseRequest|undefined, {}|undefined + ]>|void { request = request || {}; let options: CallOptions; if (typeof optionsOrCallback === 'function' && callback === undefined) { callback = optionsOrCallback; options = {}; - } else { + } + else { options = optionsOrCallback as CallOptions; } options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - options.otherArgs.headers['x-goog-request-params'] = - this._gaxModule.routingHeader.fromParams({ - name: request.name ?? '', + options.otherArgs.headers[ + 'x-goog-request-params' + ] = this._gaxModule.routingHeader.fromParams({ + 'name': request.name ?? '', + }); + this.initialize().catch(err => {throw err}); + this._log.info('getDatabase request %j', request); + const wrappedCallback: Callback< + protos.google.firestore.admin.v1.IDatabase, + protos.google.firestore.admin.v1.IGetDatabaseRequest|null|undefined, + {}|null|undefined>|undefined = callback + ? (error, response, options, rawResponse) => { + this._log.info('getDatabase response %j', response); + callback!(error, response, options, rawResponse); // We verified callback above. + } + : undefined; + return this.innerApiCalls.getDatabase(request, options, wrappedCallback) + ?.then(([response, options, rawResponse]: [ + protos.google.firestore.admin.v1.IDatabase, + protos.google.firestore.admin.v1.IGetDatabaseRequest|undefined, + {}|undefined + ]) => { + this._log.info('getDatabase response %j', response); + return [response, options, rawResponse]; }); - this.initialize(); - return this.innerApiCalls.getDatabase(request, options, callback); } - /** - * List all the databases in the project. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.parent - * Required. A parent name of the form - * `projects/{project_id}` - * @param {boolean} request.showDeleted - * If true, also returns deleted resources. - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Promise} - The promise which resolves to an array. - * The first element of the array is an object representing {@link protos.google.firestore.admin.v1.ListDatabasesResponse|ListDatabasesResponse}. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } - * for more details and examples. - * @example - * region_tag:firestore_v1_generated_FirestoreAdmin_ListDatabases_async - */ +/** + * List all the databases in the project. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.parent + * Required. A parent name of the form + * `projects/{project_id}` + * @param {boolean} request.showDeleted + * If true, also returns deleted resources. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is an object representing {@link protos.google.firestore.admin.v1.ListDatabasesResponse|ListDatabasesResponse}. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } + * for more details and examples. + * @example + * region_tag:firestore_v1_generated_FirestoreAdmin_ListDatabases_async + */ listDatabases( - request?: protos.google.firestore.admin.v1.IListDatabasesRequest, - options?: CallOptions - ): Promise< - [ - protos.google.firestore.admin.v1.IListDatabasesResponse, - protos.google.firestore.admin.v1.IListDatabasesRequest | undefined, - {} | undefined, - ] - >; + request?: protos.google.firestore.admin.v1.IListDatabasesRequest, + options?: CallOptions): + Promise<[ + protos.google.firestore.admin.v1.IListDatabasesResponse, + protos.google.firestore.admin.v1.IListDatabasesRequest|undefined, {}|undefined + ]>; listDatabases( - request: protos.google.firestore.admin.v1.IListDatabasesRequest, - options: CallOptions, - callback: Callback< - protos.google.firestore.admin.v1.IListDatabasesResponse, - protos.google.firestore.admin.v1.IListDatabasesRequest | null | undefined, - {} | null | undefined - > - ): void; + request: protos.google.firestore.admin.v1.IListDatabasesRequest, + options: CallOptions, + callback: Callback< + protos.google.firestore.admin.v1.IListDatabasesResponse, + protos.google.firestore.admin.v1.IListDatabasesRequest|null|undefined, + {}|null|undefined>): void; listDatabases( - request: protos.google.firestore.admin.v1.IListDatabasesRequest, - callback: Callback< - protos.google.firestore.admin.v1.IListDatabasesResponse, - protos.google.firestore.admin.v1.IListDatabasesRequest | null | undefined, - {} | null | undefined - > - ): void; + request: protos.google.firestore.admin.v1.IListDatabasesRequest, + callback: Callback< + protos.google.firestore.admin.v1.IListDatabasesResponse, + protos.google.firestore.admin.v1.IListDatabasesRequest|null|undefined, + {}|null|undefined>): void; listDatabases( - request?: protos.google.firestore.admin.v1.IListDatabasesRequest, - optionsOrCallback?: - | CallOptions - | Callback< + request?: protos.google.firestore.admin.v1.IListDatabasesRequest, + optionsOrCallback?: CallOptions|Callback< protos.google.firestore.admin.v1.IListDatabasesResponse, - | protos.google.firestore.admin.v1.IListDatabasesRequest - | null - | undefined, - {} | null | undefined - >, - callback?: Callback< - protos.google.firestore.admin.v1.IListDatabasesResponse, - protos.google.firestore.admin.v1.IListDatabasesRequest | null | undefined, - {} | null | undefined - > - ): Promise< - [ - protos.google.firestore.admin.v1.IListDatabasesResponse, - protos.google.firestore.admin.v1.IListDatabasesRequest | undefined, - {} | undefined, - ] - > | void { + protos.google.firestore.admin.v1.IListDatabasesRequest|null|undefined, + {}|null|undefined>, + callback?: Callback< + protos.google.firestore.admin.v1.IListDatabasesResponse, + protos.google.firestore.admin.v1.IListDatabasesRequest|null|undefined, + {}|null|undefined>): + Promise<[ + protos.google.firestore.admin.v1.IListDatabasesResponse, + protos.google.firestore.admin.v1.IListDatabasesRequest|undefined, {}|undefined + ]>|void { request = request || {}; let options: CallOptions; if (typeof optionsOrCallback === 'function' && callback === undefined) { callback = optionsOrCallback; options = {}; - } else { + } + else { options = optionsOrCallback as CallOptions; } options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - options.otherArgs.headers['x-goog-request-params'] = - this._gaxModule.routingHeader.fromParams({ - parent: request.parent ?? '', + options.otherArgs.headers[ + 'x-goog-request-params' + ] = this._gaxModule.routingHeader.fromParams({ + 'parent': request.parent ?? '', + }); + this.initialize().catch(err => {throw err}); + this._log.info('listDatabases request %j', request); + const wrappedCallback: Callback< + protos.google.firestore.admin.v1.IListDatabasesResponse, + protos.google.firestore.admin.v1.IListDatabasesRequest|null|undefined, + {}|null|undefined>|undefined = callback + ? (error, response, options, rawResponse) => { + this._log.info('listDatabases response %j', response); + callback!(error, response, options, rawResponse); // We verified callback above. + } + : undefined; + return this.innerApiCalls.listDatabases(request, options, wrappedCallback) + ?.then(([response, options, rawResponse]: [ + protos.google.firestore.admin.v1.IListDatabasesResponse, + protos.google.firestore.admin.v1.IListDatabasesRequest|undefined, + {}|undefined + ]) => { + this._log.info('listDatabases response %j', response); + return [response, options, rawResponse]; }); - this.initialize(); - return this.innerApiCalls.listDatabases(request, options, callback); } - /** - * Gets information about a backup. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.name - * Required. Name of the backup to fetch. - * - * Format is `projects/{project}/locations/{location}/backups/{backup}`. - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Promise} - The promise which resolves to an array. - * The first element of the array is an object representing {@link protos.google.firestore.admin.v1.Backup|Backup}. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } - * for more details and examples. - * @example - * region_tag:firestore_v1_generated_FirestoreAdmin_GetBackup_async - */ - getBackup( - request?: protos.google.firestore.admin.v1.IGetBackupRequest, - options?: CallOptions - ): Promise< - [ - protos.google.firestore.admin.v1.IBackup, - protos.google.firestore.admin.v1.IGetBackupRequest | undefined, - {} | undefined, - ] - >; - getBackup( - request: protos.google.firestore.admin.v1.IGetBackupRequest, - options: CallOptions, - callback: Callback< - protos.google.firestore.admin.v1.IBackup, - protos.google.firestore.admin.v1.IGetBackupRequest | null | undefined, - {} | null | undefined - > - ): void; - getBackup( - request: protos.google.firestore.admin.v1.IGetBackupRequest, - callback: Callback< - protos.google.firestore.admin.v1.IBackup, - protos.google.firestore.admin.v1.IGetBackupRequest | null | undefined, - {} | null | undefined - > - ): void; - getBackup( - request?: protos.google.firestore.admin.v1.IGetBackupRequest, - optionsOrCallback?: - | CallOptions - | Callback< - protos.google.firestore.admin.v1.IBackup, - protos.google.firestore.admin.v1.IGetBackupRequest | null | undefined, - {} | null | undefined - >, - callback?: Callback< - protos.google.firestore.admin.v1.IBackup, - protos.google.firestore.admin.v1.IGetBackupRequest | null | undefined, - {} | null | undefined - > - ): Promise< - [ - protos.google.firestore.admin.v1.IBackup, - protos.google.firestore.admin.v1.IGetBackupRequest | undefined, - {} | undefined, - ] - > | void { +/** + * Create a user creds. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.parent + * Required. A parent name of the form + * `projects/{project_id}/databases/{database_id}` + * @param {google.firestore.admin.v1.UserCreds} request.userCreds + * Required. The user creds to create. + * @param {string} request.userCredsId + * Required. The ID to use for the user creds, which will become the final + * component of the user creds's resource name. + * + * This value should be 4-63 characters. Valid characters are /{@link protos.0-9|a-z}-/ + * with first character a letter and the last a letter or a number. Must not + * be UUID-like /[0-9a-f]{8}(-[0-9a-f]{4}){3}-[0-9a-f]{12}/. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is an object representing {@link protos.google.firestore.admin.v1.UserCreds|UserCreds}. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } + * for more details and examples. + * @example + * region_tag:firestore_v1_generated_FirestoreAdmin_CreateUserCreds_async + */ + createUserCreds( + request?: protos.google.firestore.admin.v1.ICreateUserCredsRequest, + options?: CallOptions): + Promise<[ + protos.google.firestore.admin.v1.IUserCreds, + protos.google.firestore.admin.v1.ICreateUserCredsRequest|undefined, {}|undefined + ]>; + createUserCreds( + request: protos.google.firestore.admin.v1.ICreateUserCredsRequest, + options: CallOptions, + callback: Callback< + protos.google.firestore.admin.v1.IUserCreds, + protos.google.firestore.admin.v1.ICreateUserCredsRequest|null|undefined, + {}|null|undefined>): void; + createUserCreds( + request: protos.google.firestore.admin.v1.ICreateUserCredsRequest, + callback: Callback< + protos.google.firestore.admin.v1.IUserCreds, + protos.google.firestore.admin.v1.ICreateUserCredsRequest|null|undefined, + {}|null|undefined>): void; + createUserCreds( + request?: protos.google.firestore.admin.v1.ICreateUserCredsRequest, + optionsOrCallback?: CallOptions|Callback< + protos.google.firestore.admin.v1.IUserCreds, + protos.google.firestore.admin.v1.ICreateUserCredsRequest|null|undefined, + {}|null|undefined>, + callback?: Callback< + protos.google.firestore.admin.v1.IUserCreds, + protos.google.firestore.admin.v1.ICreateUserCredsRequest|null|undefined, + {}|null|undefined>): + Promise<[ + protos.google.firestore.admin.v1.IUserCreds, + protos.google.firestore.admin.v1.ICreateUserCredsRequest|undefined, {}|undefined + ]>|void { request = request || {}; let options: CallOptions; if (typeof optionsOrCallback === 'function' && callback === undefined) { callback = optionsOrCallback; options = {}; - } else { + } + else { options = optionsOrCallback as CallOptions; } options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - options.otherArgs.headers['x-goog-request-params'] = - this._gaxModule.routingHeader.fromParams({ - name: request.name ?? '', + options.otherArgs.headers[ + 'x-goog-request-params' + ] = this._gaxModule.routingHeader.fromParams({ + 'parent': request.parent ?? '', + }); + this.initialize().catch(err => {throw err}); + this._log.info('createUserCreds request %j', request); + const wrappedCallback: Callback< + protos.google.firestore.admin.v1.IUserCreds, + protos.google.firestore.admin.v1.ICreateUserCredsRequest|null|undefined, + {}|null|undefined>|undefined = callback + ? (error, response, options, rawResponse) => { + this._log.info('createUserCreds response %j', response); + callback!(error, response, options, rawResponse); // We verified callback above. + } + : undefined; + return this.innerApiCalls.createUserCreds(request, options, wrappedCallback) + ?.then(([response, options, rawResponse]: [ + protos.google.firestore.admin.v1.IUserCreds, + protos.google.firestore.admin.v1.ICreateUserCredsRequest|undefined, + {}|undefined + ]) => { + this._log.info('createUserCreds response %j', response); + return [response, options, rawResponse]; }); - this.initialize(); - return this.innerApiCalls.getBackup(request, options, callback); } - /** - * Lists all the backups. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.parent - * Required. The location to list backups from. - * - * Format is `projects/{project}/locations/{location}`. - * Use `{location} = '-'` to list backups from all locations for the given - * project. This allows listing backups from a single location or from all - * locations. - * @param {string} request.filter - * An expression that filters the list of returned backups. - * - * A filter expression consists of a field name, a comparison operator, and a - * value for filtering. - * The value must be a string, a number, or a boolean. The comparison operator - * must be one of: `<`, `>`, `<=`, `>=`, `!=`, `=`, or `:`. - * Colon `:` is the contains operator. Filter rules are not case sensitive. - * - * The following fields in the {@link protos.google.firestore.admin.v1.Backup|Backup} are - * eligible for filtering: - * - * * `database_uid` (supports `=` only) - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Promise} - The promise which resolves to an array. - * The first element of the array is an object representing {@link protos.google.firestore.admin.v1.ListBackupsResponse|ListBackupsResponse}. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } - * for more details and examples. - * @example - * region_tag:firestore_v1_generated_FirestoreAdmin_ListBackups_async - */ +/** + * Gets a user creds resource. Note that the returned resource does not + * contain the secret value itself. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.name + * Required. A name of the form + * `projects/{project_id}/databases/{database_id}/userCreds/{user_creds_id}` + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is an object representing {@link protos.google.firestore.admin.v1.UserCreds|UserCreds}. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } + * for more details and examples. + * @example + * region_tag:firestore_v1_generated_FirestoreAdmin_GetUserCreds_async + */ + getUserCreds( + request?: protos.google.firestore.admin.v1.IGetUserCredsRequest, + options?: CallOptions): + Promise<[ + protos.google.firestore.admin.v1.IUserCreds, + protos.google.firestore.admin.v1.IGetUserCredsRequest|undefined, {}|undefined + ]>; + getUserCreds( + request: protos.google.firestore.admin.v1.IGetUserCredsRequest, + options: CallOptions, + callback: Callback< + protos.google.firestore.admin.v1.IUserCreds, + protos.google.firestore.admin.v1.IGetUserCredsRequest|null|undefined, + {}|null|undefined>): void; + getUserCreds( + request: protos.google.firestore.admin.v1.IGetUserCredsRequest, + callback: Callback< + protos.google.firestore.admin.v1.IUserCreds, + protos.google.firestore.admin.v1.IGetUserCredsRequest|null|undefined, + {}|null|undefined>): void; + getUserCreds( + request?: protos.google.firestore.admin.v1.IGetUserCredsRequest, + optionsOrCallback?: CallOptions|Callback< + protos.google.firestore.admin.v1.IUserCreds, + protos.google.firestore.admin.v1.IGetUserCredsRequest|null|undefined, + {}|null|undefined>, + callback?: Callback< + protos.google.firestore.admin.v1.IUserCreds, + protos.google.firestore.admin.v1.IGetUserCredsRequest|null|undefined, + {}|null|undefined>): + Promise<[ + protos.google.firestore.admin.v1.IUserCreds, + protos.google.firestore.admin.v1.IGetUserCredsRequest|undefined, {}|undefined + ]>|void { + request = request || {}; + let options: CallOptions; + if (typeof optionsOrCallback === 'function' && callback === undefined) { + callback = optionsOrCallback; + options = {}; + } + else { + options = optionsOrCallback as CallOptions; + } + options = options || {}; + options.otherArgs = options.otherArgs || {}; + options.otherArgs.headers = options.otherArgs.headers || {}; + options.otherArgs.headers[ + 'x-goog-request-params' + ] = this._gaxModule.routingHeader.fromParams({ + 'name': request.name ?? '', + }); + this.initialize().catch(err => {throw err}); + this._log.info('getUserCreds request %j', request); + const wrappedCallback: Callback< + protos.google.firestore.admin.v1.IUserCreds, + protos.google.firestore.admin.v1.IGetUserCredsRequest|null|undefined, + {}|null|undefined>|undefined = callback + ? (error, response, options, rawResponse) => { + this._log.info('getUserCreds response %j', response); + callback!(error, response, options, rawResponse); // We verified callback above. + } + : undefined; + return this.innerApiCalls.getUserCreds(request, options, wrappedCallback) + ?.then(([response, options, rawResponse]: [ + protos.google.firestore.admin.v1.IUserCreds, + protos.google.firestore.admin.v1.IGetUserCredsRequest|undefined, + {}|undefined + ]) => { + this._log.info('getUserCreds response %j', response); + return [response, options, rawResponse]; + }); + } +/** + * List all user creds in the database. Note that the returned resource + * does not contain the secret value itself. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.parent + * Required. A parent database name of the form + * `projects/{project_id}/databases/{database_id}` + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is an object representing {@link protos.google.firestore.admin.v1.ListUserCredsResponse|ListUserCredsResponse}. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } + * for more details and examples. + * @example + * region_tag:firestore_v1_generated_FirestoreAdmin_ListUserCreds_async + */ + listUserCreds( + request?: protos.google.firestore.admin.v1.IListUserCredsRequest, + options?: CallOptions): + Promise<[ + protos.google.firestore.admin.v1.IListUserCredsResponse, + protos.google.firestore.admin.v1.IListUserCredsRequest|undefined, {}|undefined + ]>; + listUserCreds( + request: protos.google.firestore.admin.v1.IListUserCredsRequest, + options: CallOptions, + callback: Callback< + protos.google.firestore.admin.v1.IListUserCredsResponse, + protos.google.firestore.admin.v1.IListUserCredsRequest|null|undefined, + {}|null|undefined>): void; + listUserCreds( + request: protos.google.firestore.admin.v1.IListUserCredsRequest, + callback: Callback< + protos.google.firestore.admin.v1.IListUserCredsResponse, + protos.google.firestore.admin.v1.IListUserCredsRequest|null|undefined, + {}|null|undefined>): void; + listUserCreds( + request?: protos.google.firestore.admin.v1.IListUserCredsRequest, + optionsOrCallback?: CallOptions|Callback< + protos.google.firestore.admin.v1.IListUserCredsResponse, + protos.google.firestore.admin.v1.IListUserCredsRequest|null|undefined, + {}|null|undefined>, + callback?: Callback< + protos.google.firestore.admin.v1.IListUserCredsResponse, + protos.google.firestore.admin.v1.IListUserCredsRequest|null|undefined, + {}|null|undefined>): + Promise<[ + protos.google.firestore.admin.v1.IListUserCredsResponse, + protos.google.firestore.admin.v1.IListUserCredsRequest|undefined, {}|undefined + ]>|void { + request = request || {}; + let options: CallOptions; + if (typeof optionsOrCallback === 'function' && callback === undefined) { + callback = optionsOrCallback; + options = {}; + } + else { + options = optionsOrCallback as CallOptions; + } + options = options || {}; + options.otherArgs = options.otherArgs || {}; + options.otherArgs.headers = options.otherArgs.headers || {}; + options.otherArgs.headers[ + 'x-goog-request-params' + ] = this._gaxModule.routingHeader.fromParams({ + 'parent': request.parent ?? '', + }); + this.initialize().catch(err => {throw err}); + this._log.info('listUserCreds request %j', request); + const wrappedCallback: Callback< + protos.google.firestore.admin.v1.IListUserCredsResponse, + protos.google.firestore.admin.v1.IListUserCredsRequest|null|undefined, + {}|null|undefined>|undefined = callback + ? (error, response, options, rawResponse) => { + this._log.info('listUserCreds response %j', response); + callback!(error, response, options, rawResponse); // We verified callback above. + } + : undefined; + return this.innerApiCalls.listUserCreds(request, options, wrappedCallback) + ?.then(([response, options, rawResponse]: [ + protos.google.firestore.admin.v1.IListUserCredsResponse, + protos.google.firestore.admin.v1.IListUserCredsRequest|undefined, + {}|undefined + ]) => { + this._log.info('listUserCreds response %j', response); + return [response, options, rawResponse]; + }); + } +/** + * Enables a user creds. No-op if the user creds are already enabled. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.name + * Required. A name of the form + * `projects/{project_id}/databases/{database_id}/userCreds/{user_creds_id}` + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is an object representing {@link protos.google.firestore.admin.v1.UserCreds|UserCreds}. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } + * for more details and examples. + * @example + * region_tag:firestore_v1_generated_FirestoreAdmin_EnableUserCreds_async + */ + enableUserCreds( + request?: protos.google.firestore.admin.v1.IEnableUserCredsRequest, + options?: CallOptions): + Promise<[ + protos.google.firestore.admin.v1.IUserCreds, + protos.google.firestore.admin.v1.IEnableUserCredsRequest|undefined, {}|undefined + ]>; + enableUserCreds( + request: protos.google.firestore.admin.v1.IEnableUserCredsRequest, + options: CallOptions, + callback: Callback< + protos.google.firestore.admin.v1.IUserCreds, + protos.google.firestore.admin.v1.IEnableUserCredsRequest|null|undefined, + {}|null|undefined>): void; + enableUserCreds( + request: protos.google.firestore.admin.v1.IEnableUserCredsRequest, + callback: Callback< + protos.google.firestore.admin.v1.IUserCreds, + protos.google.firestore.admin.v1.IEnableUserCredsRequest|null|undefined, + {}|null|undefined>): void; + enableUserCreds( + request?: protos.google.firestore.admin.v1.IEnableUserCredsRequest, + optionsOrCallback?: CallOptions|Callback< + protos.google.firestore.admin.v1.IUserCreds, + protos.google.firestore.admin.v1.IEnableUserCredsRequest|null|undefined, + {}|null|undefined>, + callback?: Callback< + protos.google.firestore.admin.v1.IUserCreds, + protos.google.firestore.admin.v1.IEnableUserCredsRequest|null|undefined, + {}|null|undefined>): + Promise<[ + protos.google.firestore.admin.v1.IUserCreds, + protos.google.firestore.admin.v1.IEnableUserCredsRequest|undefined, {}|undefined + ]>|void { + request = request || {}; + let options: CallOptions; + if (typeof optionsOrCallback === 'function' && callback === undefined) { + callback = optionsOrCallback; + options = {}; + } + else { + options = optionsOrCallback as CallOptions; + } + options = options || {}; + options.otherArgs = options.otherArgs || {}; + options.otherArgs.headers = options.otherArgs.headers || {}; + options.otherArgs.headers[ + 'x-goog-request-params' + ] = this._gaxModule.routingHeader.fromParams({ + 'name': request.name ?? '', + }); + this.initialize().catch(err => {throw err}); + this._log.info('enableUserCreds request %j', request); + const wrappedCallback: Callback< + protos.google.firestore.admin.v1.IUserCreds, + protos.google.firestore.admin.v1.IEnableUserCredsRequest|null|undefined, + {}|null|undefined>|undefined = callback + ? (error, response, options, rawResponse) => { + this._log.info('enableUserCreds response %j', response); + callback!(error, response, options, rawResponse); // We verified callback above. + } + : undefined; + return this.innerApiCalls.enableUserCreds(request, options, wrappedCallback) + ?.then(([response, options, rawResponse]: [ + protos.google.firestore.admin.v1.IUserCreds, + protos.google.firestore.admin.v1.IEnableUserCredsRequest|undefined, + {}|undefined + ]) => { + this._log.info('enableUserCreds response %j', response); + return [response, options, rawResponse]; + }); + } +/** + * Disables a user creds. No-op if the user creds are already disabled. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.name + * Required. A name of the form + * `projects/{project_id}/databases/{database_id}/userCreds/{user_creds_id}` + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is an object representing {@link protos.google.firestore.admin.v1.UserCreds|UserCreds}. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } + * for more details and examples. + * @example + * region_tag:firestore_v1_generated_FirestoreAdmin_DisableUserCreds_async + */ + disableUserCreds( + request?: protos.google.firestore.admin.v1.IDisableUserCredsRequest, + options?: CallOptions): + Promise<[ + protos.google.firestore.admin.v1.IUserCreds, + protos.google.firestore.admin.v1.IDisableUserCredsRequest|undefined, {}|undefined + ]>; + disableUserCreds( + request: protos.google.firestore.admin.v1.IDisableUserCredsRequest, + options: CallOptions, + callback: Callback< + protos.google.firestore.admin.v1.IUserCreds, + protos.google.firestore.admin.v1.IDisableUserCredsRequest|null|undefined, + {}|null|undefined>): void; + disableUserCreds( + request: protos.google.firestore.admin.v1.IDisableUserCredsRequest, + callback: Callback< + protos.google.firestore.admin.v1.IUserCreds, + protos.google.firestore.admin.v1.IDisableUserCredsRequest|null|undefined, + {}|null|undefined>): void; + disableUserCreds( + request?: protos.google.firestore.admin.v1.IDisableUserCredsRequest, + optionsOrCallback?: CallOptions|Callback< + protos.google.firestore.admin.v1.IUserCreds, + protos.google.firestore.admin.v1.IDisableUserCredsRequest|null|undefined, + {}|null|undefined>, + callback?: Callback< + protos.google.firestore.admin.v1.IUserCreds, + protos.google.firestore.admin.v1.IDisableUserCredsRequest|null|undefined, + {}|null|undefined>): + Promise<[ + protos.google.firestore.admin.v1.IUserCreds, + protos.google.firestore.admin.v1.IDisableUserCredsRequest|undefined, {}|undefined + ]>|void { + request = request || {}; + let options: CallOptions; + if (typeof optionsOrCallback === 'function' && callback === undefined) { + callback = optionsOrCallback; + options = {}; + } + else { + options = optionsOrCallback as CallOptions; + } + options = options || {}; + options.otherArgs = options.otherArgs || {}; + options.otherArgs.headers = options.otherArgs.headers || {}; + options.otherArgs.headers[ + 'x-goog-request-params' + ] = this._gaxModule.routingHeader.fromParams({ + 'name': request.name ?? '', + }); + this.initialize().catch(err => {throw err}); + this._log.info('disableUserCreds request %j', request); + const wrappedCallback: Callback< + protos.google.firestore.admin.v1.IUserCreds, + protos.google.firestore.admin.v1.IDisableUserCredsRequest|null|undefined, + {}|null|undefined>|undefined = callback + ? (error, response, options, rawResponse) => { + this._log.info('disableUserCreds response %j', response); + callback!(error, response, options, rawResponse); // We verified callback above. + } + : undefined; + return this.innerApiCalls.disableUserCreds(request, options, wrappedCallback) + ?.then(([response, options, rawResponse]: [ + protos.google.firestore.admin.v1.IUserCreds, + protos.google.firestore.admin.v1.IDisableUserCredsRequest|undefined, + {}|undefined + ]) => { + this._log.info('disableUserCreds response %j', response); + return [response, options, rawResponse]; + }); + } +/** + * Resets the password of a user creds. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.name + * Required. A name of the form + * `projects/{project_id}/databases/{database_id}/userCreds/{user_creds_id}` + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is an object representing {@link protos.google.firestore.admin.v1.UserCreds|UserCreds}. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } + * for more details and examples. + * @example + * region_tag:firestore_v1_generated_FirestoreAdmin_ResetUserPassword_async + */ + resetUserPassword( + request?: protos.google.firestore.admin.v1.IResetUserPasswordRequest, + options?: CallOptions): + Promise<[ + protos.google.firestore.admin.v1.IUserCreds, + protos.google.firestore.admin.v1.IResetUserPasswordRequest|undefined, {}|undefined + ]>; + resetUserPassword( + request: protos.google.firestore.admin.v1.IResetUserPasswordRequest, + options: CallOptions, + callback: Callback< + protos.google.firestore.admin.v1.IUserCreds, + protos.google.firestore.admin.v1.IResetUserPasswordRequest|null|undefined, + {}|null|undefined>): void; + resetUserPassword( + request: protos.google.firestore.admin.v1.IResetUserPasswordRequest, + callback: Callback< + protos.google.firestore.admin.v1.IUserCreds, + protos.google.firestore.admin.v1.IResetUserPasswordRequest|null|undefined, + {}|null|undefined>): void; + resetUserPassword( + request?: protos.google.firestore.admin.v1.IResetUserPasswordRequest, + optionsOrCallback?: CallOptions|Callback< + protos.google.firestore.admin.v1.IUserCreds, + protos.google.firestore.admin.v1.IResetUserPasswordRequest|null|undefined, + {}|null|undefined>, + callback?: Callback< + protos.google.firestore.admin.v1.IUserCreds, + protos.google.firestore.admin.v1.IResetUserPasswordRequest|null|undefined, + {}|null|undefined>): + Promise<[ + protos.google.firestore.admin.v1.IUserCreds, + protos.google.firestore.admin.v1.IResetUserPasswordRequest|undefined, {}|undefined + ]>|void { + request = request || {}; + let options: CallOptions; + if (typeof optionsOrCallback === 'function' && callback === undefined) { + callback = optionsOrCallback; + options = {}; + } + else { + options = optionsOrCallback as CallOptions; + } + options = options || {}; + options.otherArgs = options.otherArgs || {}; + options.otherArgs.headers = options.otherArgs.headers || {}; + options.otherArgs.headers[ + 'x-goog-request-params' + ] = this._gaxModule.routingHeader.fromParams({ + 'name': request.name ?? '', + }); + this.initialize().catch(err => {throw err}); + this._log.info('resetUserPassword request %j', request); + const wrappedCallback: Callback< + protos.google.firestore.admin.v1.IUserCreds, + protos.google.firestore.admin.v1.IResetUserPasswordRequest|null|undefined, + {}|null|undefined>|undefined = callback + ? (error, response, options, rawResponse) => { + this._log.info('resetUserPassword response %j', response); + callback!(error, response, options, rawResponse); // We verified callback above. + } + : undefined; + return this.innerApiCalls.resetUserPassword(request, options, wrappedCallback) + ?.then(([response, options, rawResponse]: [ + protos.google.firestore.admin.v1.IUserCreds, + protos.google.firestore.admin.v1.IResetUserPasswordRequest|undefined, + {}|undefined + ]) => { + this._log.info('resetUserPassword response %j', response); + return [response, options, rawResponse]; + }); + } +/** + * Deletes a user creds. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.name + * Required. A name of the form + * `projects/{project_id}/databases/{database_id}/userCreds/{user_creds_id}` + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is an object representing {@link protos.google.protobuf.Empty|Empty}. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } + * for more details and examples. + * @example + * region_tag:firestore_v1_generated_FirestoreAdmin_DeleteUserCreds_async + */ + deleteUserCreds( + request?: protos.google.firestore.admin.v1.IDeleteUserCredsRequest, + options?: CallOptions): + Promise<[ + protos.google.protobuf.IEmpty, + protos.google.firestore.admin.v1.IDeleteUserCredsRequest|undefined, {}|undefined + ]>; + deleteUserCreds( + request: protos.google.firestore.admin.v1.IDeleteUserCredsRequest, + options: CallOptions, + callback: Callback< + protos.google.protobuf.IEmpty, + protos.google.firestore.admin.v1.IDeleteUserCredsRequest|null|undefined, + {}|null|undefined>): void; + deleteUserCreds( + request: protos.google.firestore.admin.v1.IDeleteUserCredsRequest, + callback: Callback< + protos.google.protobuf.IEmpty, + protos.google.firestore.admin.v1.IDeleteUserCredsRequest|null|undefined, + {}|null|undefined>): void; + deleteUserCreds( + request?: protos.google.firestore.admin.v1.IDeleteUserCredsRequest, + optionsOrCallback?: CallOptions|Callback< + protos.google.protobuf.IEmpty, + protos.google.firestore.admin.v1.IDeleteUserCredsRequest|null|undefined, + {}|null|undefined>, + callback?: Callback< + protos.google.protobuf.IEmpty, + protos.google.firestore.admin.v1.IDeleteUserCredsRequest|null|undefined, + {}|null|undefined>): + Promise<[ + protos.google.protobuf.IEmpty, + protos.google.firestore.admin.v1.IDeleteUserCredsRequest|undefined, {}|undefined + ]>|void { + request = request || {}; + let options: CallOptions; + if (typeof optionsOrCallback === 'function' && callback === undefined) { + callback = optionsOrCallback; + options = {}; + } + else { + options = optionsOrCallback as CallOptions; + } + options = options || {}; + options.otherArgs = options.otherArgs || {}; + options.otherArgs.headers = options.otherArgs.headers || {}; + options.otherArgs.headers[ + 'x-goog-request-params' + ] = this._gaxModule.routingHeader.fromParams({ + 'name': request.name ?? '', + }); + this.initialize().catch(err => {throw err}); + this._log.info('deleteUserCreds request %j', request); + const wrappedCallback: Callback< + protos.google.protobuf.IEmpty, + protos.google.firestore.admin.v1.IDeleteUserCredsRequest|null|undefined, + {}|null|undefined>|undefined = callback + ? (error, response, options, rawResponse) => { + this._log.info('deleteUserCreds response %j', response); + callback!(error, response, options, rawResponse); // We verified callback above. + } + : undefined; + return this.innerApiCalls.deleteUserCreds(request, options, wrappedCallback) + ?.then(([response, options, rawResponse]: [ + protos.google.protobuf.IEmpty, + protos.google.firestore.admin.v1.IDeleteUserCredsRequest|undefined, + {}|undefined + ]) => { + this._log.info('deleteUserCreds response %j', response); + return [response, options, rawResponse]; + }); + } +/** + * Gets information about a backup. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.name + * Required. Name of the backup to fetch. + * + * Format is `projects/{project}/locations/{location}/backups/{backup}`. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is an object representing {@link protos.google.firestore.admin.v1.Backup|Backup}. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } + * for more details and examples. + * @example + * region_tag:firestore_v1_generated_FirestoreAdmin_GetBackup_async + */ + getBackup( + request?: protos.google.firestore.admin.v1.IGetBackupRequest, + options?: CallOptions): + Promise<[ + protos.google.firestore.admin.v1.IBackup, + protos.google.firestore.admin.v1.IGetBackupRequest|undefined, {}|undefined + ]>; + getBackup( + request: protos.google.firestore.admin.v1.IGetBackupRequest, + options: CallOptions, + callback: Callback< + protos.google.firestore.admin.v1.IBackup, + protos.google.firestore.admin.v1.IGetBackupRequest|null|undefined, + {}|null|undefined>): void; + getBackup( + request: protos.google.firestore.admin.v1.IGetBackupRequest, + callback: Callback< + protos.google.firestore.admin.v1.IBackup, + protos.google.firestore.admin.v1.IGetBackupRequest|null|undefined, + {}|null|undefined>): void; + getBackup( + request?: protos.google.firestore.admin.v1.IGetBackupRequest, + optionsOrCallback?: CallOptions|Callback< + protos.google.firestore.admin.v1.IBackup, + protos.google.firestore.admin.v1.IGetBackupRequest|null|undefined, + {}|null|undefined>, + callback?: Callback< + protos.google.firestore.admin.v1.IBackup, + protos.google.firestore.admin.v1.IGetBackupRequest|null|undefined, + {}|null|undefined>): + Promise<[ + protos.google.firestore.admin.v1.IBackup, + protos.google.firestore.admin.v1.IGetBackupRequest|undefined, {}|undefined + ]>|void { + request = request || {}; + let options: CallOptions; + if (typeof optionsOrCallback === 'function' && callback === undefined) { + callback = optionsOrCallback; + options = {}; + } + else { + options = optionsOrCallback as CallOptions; + } + options = options || {}; + options.otherArgs = options.otherArgs || {}; + options.otherArgs.headers = options.otherArgs.headers || {}; + options.otherArgs.headers[ + 'x-goog-request-params' + ] = this._gaxModule.routingHeader.fromParams({ + 'name': request.name ?? '', + }); + this.initialize().catch(err => {throw err}); + this._log.info('getBackup request %j', request); + const wrappedCallback: Callback< + protos.google.firestore.admin.v1.IBackup, + protos.google.firestore.admin.v1.IGetBackupRequest|null|undefined, + {}|null|undefined>|undefined = callback + ? (error, response, options, rawResponse) => { + this._log.info('getBackup response %j', response); + callback!(error, response, options, rawResponse); // We verified callback above. + } + : undefined; + return this.innerApiCalls.getBackup(request, options, wrappedCallback) + ?.then(([response, options, rawResponse]: [ + protos.google.firestore.admin.v1.IBackup, + protos.google.firestore.admin.v1.IGetBackupRequest|undefined, + {}|undefined + ]) => { + this._log.info('getBackup response %j', response); + return [response, options, rawResponse]; + }); + } +/** + * Lists all the backups. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.parent + * Required. The location to list backups from. + * + * Format is `projects/{project}/locations/{location}`. + * Use `{location} = '-'` to list backups from all locations for the given + * project. This allows listing backups from a single location or from all + * locations. + * @param {string} request.filter + * An expression that filters the list of returned backups. + * + * A filter expression consists of a field name, a comparison operator, and a + * value for filtering. + * The value must be a string, a number, or a boolean. The comparison operator + * must be one of: `<`, `>`, `<=`, `>=`, `!=`, `=`, or `:`. + * Colon `:` is the contains operator. Filter rules are not case sensitive. + * + * The following fields in the {@link protos.google.firestore.admin.v1.Backup|Backup} are + * eligible for filtering: + * + * * `database_uid` (supports `=` only) + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is an object representing {@link protos.google.firestore.admin.v1.ListBackupsResponse|ListBackupsResponse}. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } + * for more details and examples. + * @example + * region_tag:firestore_v1_generated_FirestoreAdmin_ListBackups_async + */ listBackups( - request?: protos.google.firestore.admin.v1.IListBackupsRequest, - options?: CallOptions - ): Promise< - [ - protos.google.firestore.admin.v1.IListBackupsResponse, - protos.google.firestore.admin.v1.IListBackupsRequest | undefined, - {} | undefined, - ] - >; + request?: protos.google.firestore.admin.v1.IListBackupsRequest, + options?: CallOptions): + Promise<[ + protos.google.firestore.admin.v1.IListBackupsResponse, + protos.google.firestore.admin.v1.IListBackupsRequest|undefined, {}|undefined + ]>; listBackups( - request: protos.google.firestore.admin.v1.IListBackupsRequest, - options: CallOptions, - callback: Callback< - protos.google.firestore.admin.v1.IListBackupsResponse, - protos.google.firestore.admin.v1.IListBackupsRequest | null | undefined, - {} | null | undefined - > - ): void; + request: protos.google.firestore.admin.v1.IListBackupsRequest, + options: CallOptions, + callback: Callback< + protos.google.firestore.admin.v1.IListBackupsResponse, + protos.google.firestore.admin.v1.IListBackupsRequest|null|undefined, + {}|null|undefined>): void; listBackups( - request: protos.google.firestore.admin.v1.IListBackupsRequest, - callback: Callback< - protos.google.firestore.admin.v1.IListBackupsResponse, - protos.google.firestore.admin.v1.IListBackupsRequest | null | undefined, - {} | null | undefined - > - ): void; + request: protos.google.firestore.admin.v1.IListBackupsRequest, + callback: Callback< + protos.google.firestore.admin.v1.IListBackupsResponse, + protos.google.firestore.admin.v1.IListBackupsRequest|null|undefined, + {}|null|undefined>): void; listBackups( - request?: protos.google.firestore.admin.v1.IListBackupsRequest, - optionsOrCallback?: - | CallOptions - | Callback< + request?: protos.google.firestore.admin.v1.IListBackupsRequest, + optionsOrCallback?: CallOptions|Callback< protos.google.firestore.admin.v1.IListBackupsResponse, - | protos.google.firestore.admin.v1.IListBackupsRequest - | null - | undefined, - {} | null | undefined - >, - callback?: Callback< - protos.google.firestore.admin.v1.IListBackupsResponse, - protos.google.firestore.admin.v1.IListBackupsRequest | null | undefined, - {} | null | undefined - > - ): Promise< - [ - protos.google.firestore.admin.v1.IListBackupsResponse, - protos.google.firestore.admin.v1.IListBackupsRequest | undefined, - {} | undefined, - ] - > | void { + protos.google.firestore.admin.v1.IListBackupsRequest|null|undefined, + {}|null|undefined>, + callback?: Callback< + protos.google.firestore.admin.v1.IListBackupsResponse, + protos.google.firestore.admin.v1.IListBackupsRequest|null|undefined, + {}|null|undefined>): + Promise<[ + protos.google.firestore.admin.v1.IListBackupsResponse, + protos.google.firestore.admin.v1.IListBackupsRequest|undefined, {}|undefined + ]>|void { request = request || {}; let options: CallOptions; if (typeof optionsOrCallback === 'function' && callback === undefined) { callback = optionsOrCallback; options = {}; - } else { + } + else { options = optionsOrCallback as CallOptions; } options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - options.otherArgs.headers['x-goog-request-params'] = - this._gaxModule.routingHeader.fromParams({ - parent: request.parent ?? '', + options.otherArgs.headers[ + 'x-goog-request-params' + ] = this._gaxModule.routingHeader.fromParams({ + 'parent': request.parent ?? '', + }); + this.initialize().catch(err => {throw err}); + this._log.info('listBackups request %j', request); + const wrappedCallback: Callback< + protos.google.firestore.admin.v1.IListBackupsResponse, + protos.google.firestore.admin.v1.IListBackupsRequest|null|undefined, + {}|null|undefined>|undefined = callback + ? (error, response, options, rawResponse) => { + this._log.info('listBackups response %j', response); + callback!(error, response, options, rawResponse); // We verified callback above. + } + : undefined; + return this.innerApiCalls.listBackups(request, options, wrappedCallback) + ?.then(([response, options, rawResponse]: [ + protos.google.firestore.admin.v1.IListBackupsResponse, + protos.google.firestore.admin.v1.IListBackupsRequest|undefined, + {}|undefined + ]) => { + this._log.info('listBackups response %j', response); + return [response, options, rawResponse]; }); - this.initialize(); - return this.innerApiCalls.listBackups(request, options, callback); } - /** - * Deletes a backup. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.name - * Required. Name of the backup to delete. - * - * format is `projects/{project}/locations/{location}/backups/{backup}`. - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Promise} - The promise which resolves to an array. - * The first element of the array is an object representing {@link protos.google.protobuf.Empty|Empty}. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } - * for more details and examples. - * @example - * region_tag:firestore_v1_generated_FirestoreAdmin_DeleteBackup_async - */ +/** + * Deletes a backup. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.name + * Required. Name of the backup to delete. + * + * format is `projects/{project}/locations/{location}/backups/{backup}`. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is an object representing {@link protos.google.protobuf.Empty|Empty}. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } + * for more details and examples. + * @example + * region_tag:firestore_v1_generated_FirestoreAdmin_DeleteBackup_async + */ deleteBackup( - request?: protos.google.firestore.admin.v1.IDeleteBackupRequest, - options?: CallOptions - ): Promise< - [ - protos.google.protobuf.IEmpty, - protos.google.firestore.admin.v1.IDeleteBackupRequest | undefined, - {} | undefined, - ] - >; + request?: protos.google.firestore.admin.v1.IDeleteBackupRequest, + options?: CallOptions): + Promise<[ + protos.google.protobuf.IEmpty, + protos.google.firestore.admin.v1.IDeleteBackupRequest|undefined, {}|undefined + ]>; deleteBackup( - request: protos.google.firestore.admin.v1.IDeleteBackupRequest, - options: CallOptions, - callback: Callback< - protos.google.protobuf.IEmpty, - protos.google.firestore.admin.v1.IDeleteBackupRequest | null | undefined, - {} | null | undefined - > - ): void; + request: protos.google.firestore.admin.v1.IDeleteBackupRequest, + options: CallOptions, + callback: Callback< + protos.google.protobuf.IEmpty, + protos.google.firestore.admin.v1.IDeleteBackupRequest|null|undefined, + {}|null|undefined>): void; deleteBackup( - request: protos.google.firestore.admin.v1.IDeleteBackupRequest, - callback: Callback< - protos.google.protobuf.IEmpty, - protos.google.firestore.admin.v1.IDeleteBackupRequest | null | undefined, - {} | null | undefined - > - ): void; + request: protos.google.firestore.admin.v1.IDeleteBackupRequest, + callback: Callback< + protos.google.protobuf.IEmpty, + protos.google.firestore.admin.v1.IDeleteBackupRequest|null|undefined, + {}|null|undefined>): void; deleteBackup( - request?: protos.google.firestore.admin.v1.IDeleteBackupRequest, - optionsOrCallback?: - | CallOptions - | Callback< + request?: protos.google.firestore.admin.v1.IDeleteBackupRequest, + optionsOrCallback?: CallOptions|Callback< protos.google.protobuf.IEmpty, - | protos.google.firestore.admin.v1.IDeleteBackupRequest - | null - | undefined, - {} | null | undefined - >, - callback?: Callback< - protos.google.protobuf.IEmpty, - protos.google.firestore.admin.v1.IDeleteBackupRequest | null | undefined, - {} | null | undefined - > - ): Promise< - [ - protos.google.protobuf.IEmpty, - protos.google.firestore.admin.v1.IDeleteBackupRequest | undefined, - {} | undefined, - ] - > | void { + protos.google.firestore.admin.v1.IDeleteBackupRequest|null|undefined, + {}|null|undefined>, + callback?: Callback< + protos.google.protobuf.IEmpty, + protos.google.firestore.admin.v1.IDeleteBackupRequest|null|undefined, + {}|null|undefined>): + Promise<[ + protos.google.protobuf.IEmpty, + protos.google.firestore.admin.v1.IDeleteBackupRequest|undefined, {}|undefined + ]>|void { request = request || {}; let options: CallOptions; if (typeof optionsOrCallback === 'function' && callback === undefined) { callback = optionsOrCallback; options = {}; - } else { + } + else { options = optionsOrCallback as CallOptions; } options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - options.otherArgs.headers['x-goog-request-params'] = - this._gaxModule.routingHeader.fromParams({ - name: request.name ?? '', + options.otherArgs.headers[ + 'x-goog-request-params' + ] = this._gaxModule.routingHeader.fromParams({ + 'name': request.name ?? '', + }); + this.initialize().catch(err => {throw err}); + this._log.info('deleteBackup request %j', request); + const wrappedCallback: Callback< + protos.google.protobuf.IEmpty, + protos.google.firestore.admin.v1.IDeleteBackupRequest|null|undefined, + {}|null|undefined>|undefined = callback + ? (error, response, options, rawResponse) => { + this._log.info('deleteBackup response %j', response); + callback!(error, response, options, rawResponse); // We verified callback above. + } + : undefined; + return this.innerApiCalls.deleteBackup(request, options, wrappedCallback) + ?.then(([response, options, rawResponse]: [ + protos.google.protobuf.IEmpty, + protos.google.firestore.admin.v1.IDeleteBackupRequest|undefined, + {}|undefined + ]) => { + this._log.info('deleteBackup response %j', response); + return [response, options, rawResponse]; }); - this.initialize(); - return this.innerApiCalls.deleteBackup(request, options, callback); } - /** - * Creates a backup schedule on a database. - * At most two backup schedules can be configured on a database, one daily - * backup schedule and one weekly backup schedule. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.parent - * Required. The parent database. - * - * Format `projects/{project}/databases/{database}` - * @param {google.firestore.admin.v1.BackupSchedule} request.backupSchedule - * Required. The backup schedule to create. - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Promise} - The promise which resolves to an array. - * The first element of the array is an object representing {@link protos.google.firestore.admin.v1.BackupSchedule|BackupSchedule}. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } - * for more details and examples. - * @example - * region_tag:firestore_v1_generated_FirestoreAdmin_CreateBackupSchedule_async - */ +/** + * Creates a backup schedule on a database. + * At most two backup schedules can be configured on a database, one daily + * backup schedule and one weekly backup schedule. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.parent + * Required. The parent database. + * + * Format `projects/{project}/databases/{database}` + * @param {google.firestore.admin.v1.BackupSchedule} request.backupSchedule + * Required. The backup schedule to create. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is an object representing {@link protos.google.firestore.admin.v1.BackupSchedule|BackupSchedule}. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } + * for more details and examples. + * @example + * region_tag:firestore_v1_generated_FirestoreAdmin_CreateBackupSchedule_async + */ createBackupSchedule( - request?: protos.google.firestore.admin.v1.ICreateBackupScheduleRequest, - options?: CallOptions - ): Promise< - [ - protos.google.firestore.admin.v1.IBackupSchedule, - protos.google.firestore.admin.v1.ICreateBackupScheduleRequest | undefined, - {} | undefined, - ] - >; + request?: protos.google.firestore.admin.v1.ICreateBackupScheduleRequest, + options?: CallOptions): + Promise<[ + protos.google.firestore.admin.v1.IBackupSchedule, + protos.google.firestore.admin.v1.ICreateBackupScheduleRequest|undefined, {}|undefined + ]>; createBackupSchedule( - request: protos.google.firestore.admin.v1.ICreateBackupScheduleRequest, - options: CallOptions, - callback: Callback< - protos.google.firestore.admin.v1.IBackupSchedule, - | protos.google.firestore.admin.v1.ICreateBackupScheduleRequest - | null - | undefined, - {} | null | undefined - > - ): void; + request: protos.google.firestore.admin.v1.ICreateBackupScheduleRequest, + options: CallOptions, + callback: Callback< + protos.google.firestore.admin.v1.IBackupSchedule, + protos.google.firestore.admin.v1.ICreateBackupScheduleRequest|null|undefined, + {}|null|undefined>): void; createBackupSchedule( - request: protos.google.firestore.admin.v1.ICreateBackupScheduleRequest, - callback: Callback< - protos.google.firestore.admin.v1.IBackupSchedule, - | protos.google.firestore.admin.v1.ICreateBackupScheduleRequest - | null - | undefined, - {} | null | undefined - > - ): void; + request: protos.google.firestore.admin.v1.ICreateBackupScheduleRequest, + callback: Callback< + protos.google.firestore.admin.v1.IBackupSchedule, + protos.google.firestore.admin.v1.ICreateBackupScheduleRequest|null|undefined, + {}|null|undefined>): void; createBackupSchedule( - request?: protos.google.firestore.admin.v1.ICreateBackupScheduleRequest, - optionsOrCallback?: - | CallOptions - | Callback< + request?: protos.google.firestore.admin.v1.ICreateBackupScheduleRequest, + optionsOrCallback?: CallOptions|Callback< protos.google.firestore.admin.v1.IBackupSchedule, - | protos.google.firestore.admin.v1.ICreateBackupScheduleRequest - | null - | undefined, - {} | null | undefined - >, - callback?: Callback< - protos.google.firestore.admin.v1.IBackupSchedule, - | protos.google.firestore.admin.v1.ICreateBackupScheduleRequest - | null - | undefined, - {} | null | undefined - > - ): Promise< - [ - protos.google.firestore.admin.v1.IBackupSchedule, - protos.google.firestore.admin.v1.ICreateBackupScheduleRequest | undefined, - {} | undefined, - ] - > | void { + protos.google.firestore.admin.v1.ICreateBackupScheduleRequest|null|undefined, + {}|null|undefined>, + callback?: Callback< + protos.google.firestore.admin.v1.IBackupSchedule, + protos.google.firestore.admin.v1.ICreateBackupScheduleRequest|null|undefined, + {}|null|undefined>): + Promise<[ + protos.google.firestore.admin.v1.IBackupSchedule, + protos.google.firestore.admin.v1.ICreateBackupScheduleRequest|undefined, {}|undefined + ]>|void { request = request || {}; let options: CallOptions; if (typeof optionsOrCallback === 'function' && callback === undefined) { callback = optionsOrCallback; options = {}; - } else { + } + else { options = optionsOrCallback as CallOptions; } options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - options.otherArgs.headers['x-goog-request-params'] = - this._gaxModule.routingHeader.fromParams({ - parent: request.parent ?? '', + options.otherArgs.headers[ + 'x-goog-request-params' + ] = this._gaxModule.routingHeader.fromParams({ + 'parent': request.parent ?? '', + }); + this.initialize().catch(err => {throw err}); + this._log.info('createBackupSchedule request %j', request); + const wrappedCallback: Callback< + protos.google.firestore.admin.v1.IBackupSchedule, + protos.google.firestore.admin.v1.ICreateBackupScheduleRequest|null|undefined, + {}|null|undefined>|undefined = callback + ? (error, response, options, rawResponse) => { + this._log.info('createBackupSchedule response %j', response); + callback!(error, response, options, rawResponse); // We verified callback above. + } + : undefined; + return this.innerApiCalls.createBackupSchedule(request, options, wrappedCallback) + ?.then(([response, options, rawResponse]: [ + protos.google.firestore.admin.v1.IBackupSchedule, + protos.google.firestore.admin.v1.ICreateBackupScheduleRequest|undefined, + {}|undefined + ]) => { + this._log.info('createBackupSchedule response %j', response); + return [response, options, rawResponse]; }); - this.initialize(); - return this.innerApiCalls.createBackupSchedule(request, options, callback); } - /** - * Gets information about a backup schedule. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.name - * Required. The name of the backup schedule. - * - * Format - * `projects/{project}/databases/{database}/backupSchedules/{backup_schedule}` - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Promise} - The promise which resolves to an array. - * The first element of the array is an object representing {@link protos.google.firestore.admin.v1.BackupSchedule|BackupSchedule}. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } - * for more details and examples. - * @example - * region_tag:firestore_v1_generated_FirestoreAdmin_GetBackupSchedule_async - */ +/** + * Gets information about a backup schedule. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.name + * Required. The name of the backup schedule. + * + * Format + * `projects/{project}/databases/{database}/backupSchedules/{backup_schedule}` + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is an object representing {@link protos.google.firestore.admin.v1.BackupSchedule|BackupSchedule}. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } + * for more details and examples. + * @example + * region_tag:firestore_v1_generated_FirestoreAdmin_GetBackupSchedule_async + */ getBackupSchedule( - request?: protos.google.firestore.admin.v1.IGetBackupScheduleRequest, - options?: CallOptions - ): Promise< - [ - protos.google.firestore.admin.v1.IBackupSchedule, - protos.google.firestore.admin.v1.IGetBackupScheduleRequest | undefined, - {} | undefined, - ] - >; + request?: protos.google.firestore.admin.v1.IGetBackupScheduleRequest, + options?: CallOptions): + Promise<[ + protos.google.firestore.admin.v1.IBackupSchedule, + protos.google.firestore.admin.v1.IGetBackupScheduleRequest|undefined, {}|undefined + ]>; getBackupSchedule( - request: protos.google.firestore.admin.v1.IGetBackupScheduleRequest, - options: CallOptions, - callback: Callback< - protos.google.firestore.admin.v1.IBackupSchedule, - | protos.google.firestore.admin.v1.IGetBackupScheduleRequest - | null - | undefined, - {} | null | undefined - > - ): void; + request: protos.google.firestore.admin.v1.IGetBackupScheduleRequest, + options: CallOptions, + callback: Callback< + protos.google.firestore.admin.v1.IBackupSchedule, + protos.google.firestore.admin.v1.IGetBackupScheduleRequest|null|undefined, + {}|null|undefined>): void; getBackupSchedule( - request: protos.google.firestore.admin.v1.IGetBackupScheduleRequest, - callback: Callback< - protos.google.firestore.admin.v1.IBackupSchedule, - | protos.google.firestore.admin.v1.IGetBackupScheduleRequest - | null - | undefined, - {} | null | undefined - > - ): void; + request: protos.google.firestore.admin.v1.IGetBackupScheduleRequest, + callback: Callback< + protos.google.firestore.admin.v1.IBackupSchedule, + protos.google.firestore.admin.v1.IGetBackupScheduleRequest|null|undefined, + {}|null|undefined>): void; getBackupSchedule( - request?: protos.google.firestore.admin.v1.IGetBackupScheduleRequest, - optionsOrCallback?: - | CallOptions - | Callback< + request?: protos.google.firestore.admin.v1.IGetBackupScheduleRequest, + optionsOrCallback?: CallOptions|Callback< protos.google.firestore.admin.v1.IBackupSchedule, - | protos.google.firestore.admin.v1.IGetBackupScheduleRequest - | null - | undefined, - {} | null | undefined - >, - callback?: Callback< - protos.google.firestore.admin.v1.IBackupSchedule, - | protos.google.firestore.admin.v1.IGetBackupScheduleRequest - | null - | undefined, - {} | null | undefined - > - ): Promise< - [ - protos.google.firestore.admin.v1.IBackupSchedule, - protos.google.firestore.admin.v1.IGetBackupScheduleRequest | undefined, - {} | undefined, - ] - > | void { + protos.google.firestore.admin.v1.IGetBackupScheduleRequest|null|undefined, + {}|null|undefined>, + callback?: Callback< + protos.google.firestore.admin.v1.IBackupSchedule, + protos.google.firestore.admin.v1.IGetBackupScheduleRequest|null|undefined, + {}|null|undefined>): + Promise<[ + protos.google.firestore.admin.v1.IBackupSchedule, + protos.google.firestore.admin.v1.IGetBackupScheduleRequest|undefined, {}|undefined + ]>|void { request = request || {}; let options: CallOptions; if (typeof optionsOrCallback === 'function' && callback === undefined) { callback = optionsOrCallback; options = {}; - } else { + } + else { options = optionsOrCallback as CallOptions; } options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - options.otherArgs.headers['x-goog-request-params'] = - this._gaxModule.routingHeader.fromParams({ - name: request.name ?? '', - }); - this.initialize(); - return this.innerApiCalls.getBackupSchedule(request, options, callback); - } - /** - * List backup schedules. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.parent - * Required. The parent database. - * - * Format is `projects/{project}/databases/{database}`. - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Promise} - The promise which resolves to an array. - * The first element of the array is an object representing {@link protos.google.firestore.admin.v1.ListBackupSchedulesResponse|ListBackupSchedulesResponse}. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } - * for more details and examples. - * @example - * region_tag:firestore_v1_generated_FirestoreAdmin_ListBackupSchedules_async - */ + options.otherArgs.headers[ + 'x-goog-request-params' + ] = this._gaxModule.routingHeader.fromParams({ + 'name': request.name ?? '', + }); + this.initialize().catch(err => {throw err}); + this._log.info('getBackupSchedule request %j', request); + const wrappedCallback: Callback< + protos.google.firestore.admin.v1.IBackupSchedule, + protos.google.firestore.admin.v1.IGetBackupScheduleRequest|null|undefined, + {}|null|undefined>|undefined = callback + ? (error, response, options, rawResponse) => { + this._log.info('getBackupSchedule response %j', response); + callback!(error, response, options, rawResponse); // We verified callback above. + } + : undefined; + return this.innerApiCalls.getBackupSchedule(request, options, wrappedCallback) + ?.then(([response, options, rawResponse]: [ + protos.google.firestore.admin.v1.IBackupSchedule, + protos.google.firestore.admin.v1.IGetBackupScheduleRequest|undefined, + {}|undefined + ]) => { + this._log.info('getBackupSchedule response %j', response); + return [response, options, rawResponse]; + }); + } +/** + * List backup schedules. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.parent + * Required. The parent database. + * + * Format is `projects/{project}/databases/{database}`. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is an object representing {@link protos.google.firestore.admin.v1.ListBackupSchedulesResponse|ListBackupSchedulesResponse}. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } + * for more details and examples. + * @example + * region_tag:firestore_v1_generated_FirestoreAdmin_ListBackupSchedules_async + */ listBackupSchedules( - request?: protos.google.firestore.admin.v1.IListBackupSchedulesRequest, - options?: CallOptions - ): Promise< - [ - protos.google.firestore.admin.v1.IListBackupSchedulesResponse, - protos.google.firestore.admin.v1.IListBackupSchedulesRequest | undefined, - {} | undefined, - ] - >; + request?: protos.google.firestore.admin.v1.IListBackupSchedulesRequest, + options?: CallOptions): + Promise<[ + protos.google.firestore.admin.v1.IListBackupSchedulesResponse, + protos.google.firestore.admin.v1.IListBackupSchedulesRequest|undefined, {}|undefined + ]>; listBackupSchedules( - request: protos.google.firestore.admin.v1.IListBackupSchedulesRequest, - options: CallOptions, - callback: Callback< - protos.google.firestore.admin.v1.IListBackupSchedulesResponse, - | protos.google.firestore.admin.v1.IListBackupSchedulesRequest - | null - | undefined, - {} | null | undefined - > - ): void; + request: protos.google.firestore.admin.v1.IListBackupSchedulesRequest, + options: CallOptions, + callback: Callback< + protos.google.firestore.admin.v1.IListBackupSchedulesResponse, + protos.google.firestore.admin.v1.IListBackupSchedulesRequest|null|undefined, + {}|null|undefined>): void; listBackupSchedules( - request: protos.google.firestore.admin.v1.IListBackupSchedulesRequest, - callback: Callback< - protos.google.firestore.admin.v1.IListBackupSchedulesResponse, - | protos.google.firestore.admin.v1.IListBackupSchedulesRequest - | null - | undefined, - {} | null | undefined - > - ): void; + request: protos.google.firestore.admin.v1.IListBackupSchedulesRequest, + callback: Callback< + protos.google.firestore.admin.v1.IListBackupSchedulesResponse, + protos.google.firestore.admin.v1.IListBackupSchedulesRequest|null|undefined, + {}|null|undefined>): void; listBackupSchedules( - request?: protos.google.firestore.admin.v1.IListBackupSchedulesRequest, - optionsOrCallback?: - | CallOptions - | Callback< + request?: protos.google.firestore.admin.v1.IListBackupSchedulesRequest, + optionsOrCallback?: CallOptions|Callback< protos.google.firestore.admin.v1.IListBackupSchedulesResponse, - | protos.google.firestore.admin.v1.IListBackupSchedulesRequest - | null - | undefined, - {} | null | undefined - >, - callback?: Callback< - protos.google.firestore.admin.v1.IListBackupSchedulesResponse, - | protos.google.firestore.admin.v1.IListBackupSchedulesRequest - | null - | undefined, - {} | null | undefined - > - ): Promise< - [ - protos.google.firestore.admin.v1.IListBackupSchedulesResponse, - protos.google.firestore.admin.v1.IListBackupSchedulesRequest | undefined, - {} | undefined, - ] - > | void { + protos.google.firestore.admin.v1.IListBackupSchedulesRequest|null|undefined, + {}|null|undefined>, + callback?: Callback< + protos.google.firestore.admin.v1.IListBackupSchedulesResponse, + protos.google.firestore.admin.v1.IListBackupSchedulesRequest|null|undefined, + {}|null|undefined>): + Promise<[ + protos.google.firestore.admin.v1.IListBackupSchedulesResponse, + protos.google.firestore.admin.v1.IListBackupSchedulesRequest|undefined, {}|undefined + ]>|void { request = request || {}; let options: CallOptions; if (typeof optionsOrCallback === 'function' && callback === undefined) { callback = optionsOrCallback; options = {}; - } else { + } + else { options = optionsOrCallback as CallOptions; } options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - options.otherArgs.headers['x-goog-request-params'] = - this._gaxModule.routingHeader.fromParams({ - parent: request.parent ?? '', + options.otherArgs.headers[ + 'x-goog-request-params' + ] = this._gaxModule.routingHeader.fromParams({ + 'parent': request.parent ?? '', + }); + this.initialize().catch(err => {throw err}); + this._log.info('listBackupSchedules request %j', request); + const wrappedCallback: Callback< + protos.google.firestore.admin.v1.IListBackupSchedulesResponse, + protos.google.firestore.admin.v1.IListBackupSchedulesRequest|null|undefined, + {}|null|undefined>|undefined = callback + ? (error, response, options, rawResponse) => { + this._log.info('listBackupSchedules response %j', response); + callback!(error, response, options, rawResponse); // We verified callback above. + } + : undefined; + return this.innerApiCalls.listBackupSchedules(request, options, wrappedCallback) + ?.then(([response, options, rawResponse]: [ + protos.google.firestore.admin.v1.IListBackupSchedulesResponse, + protos.google.firestore.admin.v1.IListBackupSchedulesRequest|undefined, + {}|undefined + ]) => { + this._log.info('listBackupSchedules response %j', response); + return [response, options, rawResponse]; }); - this.initialize(); - return this.innerApiCalls.listBackupSchedules(request, options, callback); } - /** - * Updates a backup schedule. - * - * @param {Object} request - * The request object that will be sent. - * @param {google.firestore.admin.v1.BackupSchedule} request.backupSchedule - * Required. The backup schedule to update. - * @param {google.protobuf.FieldMask} request.updateMask - * The list of fields to be updated. - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Promise} - The promise which resolves to an array. - * The first element of the array is an object representing {@link protos.google.firestore.admin.v1.BackupSchedule|BackupSchedule}. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } - * for more details and examples. - * @example - * region_tag:firestore_v1_generated_FirestoreAdmin_UpdateBackupSchedule_async - */ +/** + * Updates a backup schedule. + * + * @param {Object} request + * The request object that will be sent. + * @param {google.firestore.admin.v1.BackupSchedule} request.backupSchedule + * Required. The backup schedule to update. + * @param {google.protobuf.FieldMask} request.updateMask + * The list of fields to be updated. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is an object representing {@link protos.google.firestore.admin.v1.BackupSchedule|BackupSchedule}. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } + * for more details and examples. + * @example + * region_tag:firestore_v1_generated_FirestoreAdmin_UpdateBackupSchedule_async + */ updateBackupSchedule( - request?: protos.google.firestore.admin.v1.IUpdateBackupScheduleRequest, - options?: CallOptions - ): Promise< - [ - protos.google.firestore.admin.v1.IBackupSchedule, - protos.google.firestore.admin.v1.IUpdateBackupScheduleRequest | undefined, - {} | undefined, - ] - >; + request?: protos.google.firestore.admin.v1.IUpdateBackupScheduleRequest, + options?: CallOptions): + Promise<[ + protos.google.firestore.admin.v1.IBackupSchedule, + protos.google.firestore.admin.v1.IUpdateBackupScheduleRequest|undefined, {}|undefined + ]>; updateBackupSchedule( - request: protos.google.firestore.admin.v1.IUpdateBackupScheduleRequest, - options: CallOptions, - callback: Callback< - protos.google.firestore.admin.v1.IBackupSchedule, - | protos.google.firestore.admin.v1.IUpdateBackupScheduleRequest - | null - | undefined, - {} | null | undefined - > - ): void; + request: protos.google.firestore.admin.v1.IUpdateBackupScheduleRequest, + options: CallOptions, + callback: Callback< + protos.google.firestore.admin.v1.IBackupSchedule, + protos.google.firestore.admin.v1.IUpdateBackupScheduleRequest|null|undefined, + {}|null|undefined>): void; updateBackupSchedule( - request: protos.google.firestore.admin.v1.IUpdateBackupScheduleRequest, - callback: Callback< - protos.google.firestore.admin.v1.IBackupSchedule, - | protos.google.firestore.admin.v1.IUpdateBackupScheduleRequest - | null - | undefined, - {} | null | undefined - > - ): void; + request: protos.google.firestore.admin.v1.IUpdateBackupScheduleRequest, + callback: Callback< + protos.google.firestore.admin.v1.IBackupSchedule, + protos.google.firestore.admin.v1.IUpdateBackupScheduleRequest|null|undefined, + {}|null|undefined>): void; updateBackupSchedule( - request?: protos.google.firestore.admin.v1.IUpdateBackupScheduleRequest, - optionsOrCallback?: - | CallOptions - | Callback< + request?: protos.google.firestore.admin.v1.IUpdateBackupScheduleRequest, + optionsOrCallback?: CallOptions|Callback< protos.google.firestore.admin.v1.IBackupSchedule, - | protos.google.firestore.admin.v1.IUpdateBackupScheduleRequest - | null - | undefined, - {} | null | undefined - >, - callback?: Callback< - protos.google.firestore.admin.v1.IBackupSchedule, - | protos.google.firestore.admin.v1.IUpdateBackupScheduleRequest - | null - | undefined, - {} | null | undefined - > - ): Promise< - [ - protos.google.firestore.admin.v1.IBackupSchedule, - protos.google.firestore.admin.v1.IUpdateBackupScheduleRequest | undefined, - {} | undefined, - ] - > | void { + protos.google.firestore.admin.v1.IUpdateBackupScheduleRequest|null|undefined, + {}|null|undefined>, + callback?: Callback< + protos.google.firestore.admin.v1.IBackupSchedule, + protos.google.firestore.admin.v1.IUpdateBackupScheduleRequest|null|undefined, + {}|null|undefined>): + Promise<[ + protos.google.firestore.admin.v1.IBackupSchedule, + protos.google.firestore.admin.v1.IUpdateBackupScheduleRequest|undefined, {}|undefined + ]>|void { request = request || {}; let options: CallOptions; if (typeof optionsOrCallback === 'function' && callback === undefined) { callback = optionsOrCallback; options = {}; - } else { + } + else { options = optionsOrCallback as CallOptions; } options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - options.otherArgs.headers['x-goog-request-params'] = - this._gaxModule.routingHeader.fromParams({ - 'backup_schedule.name': request.backupSchedule!.name ?? '', + options.otherArgs.headers[ + 'x-goog-request-params' + ] = this._gaxModule.routingHeader.fromParams({ + 'backup_schedule.name': request.backupSchedule!.name ?? '', + }); + this.initialize().catch(err => {throw err}); + this._log.info('updateBackupSchedule request %j', request); + const wrappedCallback: Callback< + protos.google.firestore.admin.v1.IBackupSchedule, + protos.google.firestore.admin.v1.IUpdateBackupScheduleRequest|null|undefined, + {}|null|undefined>|undefined = callback + ? (error, response, options, rawResponse) => { + this._log.info('updateBackupSchedule response %j', response); + callback!(error, response, options, rawResponse); // We verified callback above. + } + : undefined; + return this.innerApiCalls.updateBackupSchedule(request, options, wrappedCallback) + ?.then(([response, options, rawResponse]: [ + protos.google.firestore.admin.v1.IBackupSchedule, + protos.google.firestore.admin.v1.IUpdateBackupScheduleRequest|undefined, + {}|undefined + ]) => { + this._log.info('updateBackupSchedule response %j', response); + return [response, options, rawResponse]; }); - this.initialize(); - return this.innerApiCalls.updateBackupSchedule(request, options, callback); } - /** - * Deletes a backup schedule. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.name - * Required. The name of the backup schedule. - * - * Format - * `projects/{project}/databases/{database}/backupSchedules/{backup_schedule}` - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Promise} - The promise which resolves to an array. - * The first element of the array is an object representing {@link protos.google.protobuf.Empty|Empty}. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } - * for more details and examples. - * @example - * region_tag:firestore_v1_generated_FirestoreAdmin_DeleteBackupSchedule_async - */ +/** + * Deletes a backup schedule. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.name + * Required. The name of the backup schedule. + * + * Format + * `projects/{project}/databases/{database}/backupSchedules/{backup_schedule}` + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is an object representing {@link protos.google.protobuf.Empty|Empty}. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } + * for more details and examples. + * @example + * region_tag:firestore_v1_generated_FirestoreAdmin_DeleteBackupSchedule_async + */ deleteBackupSchedule( - request?: protos.google.firestore.admin.v1.IDeleteBackupScheduleRequest, - options?: CallOptions - ): Promise< - [ - protos.google.protobuf.IEmpty, - protos.google.firestore.admin.v1.IDeleteBackupScheduleRequest | undefined, - {} | undefined, - ] - >; + request?: protos.google.firestore.admin.v1.IDeleteBackupScheduleRequest, + options?: CallOptions): + Promise<[ + protos.google.protobuf.IEmpty, + protos.google.firestore.admin.v1.IDeleteBackupScheduleRequest|undefined, {}|undefined + ]>; deleteBackupSchedule( - request: protos.google.firestore.admin.v1.IDeleteBackupScheduleRequest, - options: CallOptions, - callback: Callback< - protos.google.protobuf.IEmpty, - | protos.google.firestore.admin.v1.IDeleteBackupScheduleRequest - | null - | undefined, - {} | null | undefined - > - ): void; + request: protos.google.firestore.admin.v1.IDeleteBackupScheduleRequest, + options: CallOptions, + callback: Callback< + protos.google.protobuf.IEmpty, + protos.google.firestore.admin.v1.IDeleteBackupScheduleRequest|null|undefined, + {}|null|undefined>): void; deleteBackupSchedule( - request: protos.google.firestore.admin.v1.IDeleteBackupScheduleRequest, - callback: Callback< - protos.google.protobuf.IEmpty, - | protos.google.firestore.admin.v1.IDeleteBackupScheduleRequest - | null - | undefined, - {} | null | undefined - > - ): void; + request: protos.google.firestore.admin.v1.IDeleteBackupScheduleRequest, + callback: Callback< + protos.google.protobuf.IEmpty, + protos.google.firestore.admin.v1.IDeleteBackupScheduleRequest|null|undefined, + {}|null|undefined>): void; deleteBackupSchedule( - request?: protos.google.firestore.admin.v1.IDeleteBackupScheduleRequest, - optionsOrCallback?: - | CallOptions - | Callback< + request?: protos.google.firestore.admin.v1.IDeleteBackupScheduleRequest, + optionsOrCallback?: CallOptions|Callback< protos.google.protobuf.IEmpty, - | protos.google.firestore.admin.v1.IDeleteBackupScheduleRequest - | null - | undefined, - {} | null | undefined - >, - callback?: Callback< - protos.google.protobuf.IEmpty, - | protos.google.firestore.admin.v1.IDeleteBackupScheduleRequest - | null - | undefined, - {} | null | undefined - > - ): Promise< - [ - protos.google.protobuf.IEmpty, - protos.google.firestore.admin.v1.IDeleteBackupScheduleRequest | undefined, - {} | undefined, - ] - > | void { + protos.google.firestore.admin.v1.IDeleteBackupScheduleRequest|null|undefined, + {}|null|undefined>, + callback?: Callback< + protos.google.protobuf.IEmpty, + protos.google.firestore.admin.v1.IDeleteBackupScheduleRequest|null|undefined, + {}|null|undefined>): + Promise<[ + protos.google.protobuf.IEmpty, + protos.google.firestore.admin.v1.IDeleteBackupScheduleRequest|undefined, {}|undefined + ]>|void { request = request || {}; let options: CallOptions; if (typeof optionsOrCallback === 'function' && callback === undefined) { callback = optionsOrCallback; options = {}; - } else { + } + else { options = optionsOrCallback as CallOptions; } options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - options.otherArgs.headers['x-goog-request-params'] = - this._gaxModule.routingHeader.fromParams({ - name: request.name ?? '', + options.otherArgs.headers[ + 'x-goog-request-params' + ] = this._gaxModule.routingHeader.fromParams({ + 'name': request.name ?? '', + }); + this.initialize().catch(err => {throw err}); + this._log.info('deleteBackupSchedule request %j', request); + const wrappedCallback: Callback< + protos.google.protobuf.IEmpty, + protos.google.firestore.admin.v1.IDeleteBackupScheduleRequest|null|undefined, + {}|null|undefined>|undefined = callback + ? (error, response, options, rawResponse) => { + this._log.info('deleteBackupSchedule response %j', response); + callback!(error, response, options, rawResponse); // We verified callback above. + } + : undefined; + return this.innerApiCalls.deleteBackupSchedule(request, options, wrappedCallback) + ?.then(([response, options, rawResponse]: [ + protos.google.protobuf.IEmpty, + protos.google.firestore.admin.v1.IDeleteBackupScheduleRequest|undefined, + {}|undefined + ]) => { + this._log.info('deleteBackupSchedule response %j', response); + return [response, options, rawResponse]; }); - this.initialize(); - return this.innerApiCalls.deleteBackupSchedule(request, options, callback); } - /** - * Creates a composite index. This returns a - * {@link protos.google.longrunning.Operation|google.longrunning.Operation} which may be - * used to track the status of the creation. The metadata for the operation - * will be the type - * {@link protos.google.firestore.admin.v1.IndexOperationMetadata|IndexOperationMetadata}. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.parent - * Required. A parent name of the form - * `projects/{project_id}/databases/{database_id}/collectionGroups/{collection_id}` - * @param {google.firestore.admin.v1.Index} request.index - * Required. The composite index to create. - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Promise} - The promise which resolves to an array. - * The first element of the array is an object representing - * a long running operation. Its `promise()` method returns a promise - * you can `await` for. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#long-running-operations | documentation } - * for more details and examples. - * @example - * region_tag:firestore_v1_generated_FirestoreAdmin_CreateIndex_async - */ +/** + * Creates a composite index. This returns a + * {@link protos.google.longrunning.Operation|google.longrunning.Operation} which may be + * used to track the status of the creation. The metadata for the operation + * will be the type + * {@link protos.google.firestore.admin.v1.IndexOperationMetadata|IndexOperationMetadata}. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.parent + * Required. A parent name of the form + * `projects/{project_id}/databases/{database_id}/collectionGroups/{collection_id}` + * @param {google.firestore.admin.v1.Index} request.index + * Required. The composite index to create. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is an object representing + * a long running operation. Its `promise()` method returns a promise + * you can `await` for. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#long-running-operations | documentation } + * for more details and examples. + * @example + * region_tag:firestore_v1_generated_FirestoreAdmin_CreateIndex_async + */ createIndex( - request?: protos.google.firestore.admin.v1.ICreateIndexRequest, - options?: CallOptions - ): Promise< - [ - LROperation< - protos.google.firestore.admin.v1.IIndex, - protos.google.firestore.admin.v1.IIndexOperationMetadata - >, - protos.google.longrunning.IOperation | undefined, - {} | undefined, - ] - >; + request?: protos.google.firestore.admin.v1.ICreateIndexRequest, + options?: CallOptions): + Promise<[ + LROperation, + protos.google.longrunning.IOperation|undefined, {}|undefined + ]>; createIndex( - request: protos.google.firestore.admin.v1.ICreateIndexRequest, - options: CallOptions, - callback: Callback< - LROperation< - protos.google.firestore.admin.v1.IIndex, - protos.google.firestore.admin.v1.IIndexOperationMetadata - >, - protos.google.longrunning.IOperation | null | undefined, - {} | null | undefined - > - ): void; + request: protos.google.firestore.admin.v1.ICreateIndexRequest, + options: CallOptions, + callback: Callback< + LROperation, + protos.google.longrunning.IOperation|null|undefined, + {}|null|undefined>): void; createIndex( - request: protos.google.firestore.admin.v1.ICreateIndexRequest, - callback: Callback< - LROperation< - protos.google.firestore.admin.v1.IIndex, - protos.google.firestore.admin.v1.IIndexOperationMetadata - >, - protos.google.longrunning.IOperation | null | undefined, - {} | null | undefined - > - ): void; + request: protos.google.firestore.admin.v1.ICreateIndexRequest, + callback: Callback< + LROperation, + protos.google.longrunning.IOperation|null|undefined, + {}|null|undefined>): void; createIndex( - request?: protos.google.firestore.admin.v1.ICreateIndexRequest, - optionsOrCallback?: - | CallOptions - | Callback< - LROperation< - protos.google.firestore.admin.v1.IIndex, - protos.google.firestore.admin.v1.IIndexOperationMetadata - >, - protos.google.longrunning.IOperation | null | undefined, - {} | null | undefined - >, - callback?: Callback< - LROperation< - protos.google.firestore.admin.v1.IIndex, - protos.google.firestore.admin.v1.IIndexOperationMetadata - >, - protos.google.longrunning.IOperation | null | undefined, - {} | null | undefined - > - ): Promise< - [ - LROperation< - protos.google.firestore.admin.v1.IIndex, - protos.google.firestore.admin.v1.IIndexOperationMetadata - >, - protos.google.longrunning.IOperation | undefined, - {} | undefined, - ] - > | void { + request?: protos.google.firestore.admin.v1.ICreateIndexRequest, + optionsOrCallback?: CallOptions|Callback< + LROperation, + protos.google.longrunning.IOperation|null|undefined, + {}|null|undefined>, + callback?: Callback< + LROperation, + protos.google.longrunning.IOperation|null|undefined, + {}|null|undefined>): + Promise<[ + LROperation, + protos.google.longrunning.IOperation|undefined, {}|undefined + ]>|void { request = request || {}; let options: CallOptions; if (typeof optionsOrCallback === 'function' && callback === undefined) { callback = optionsOrCallback; options = {}; - } else { + } + else { options = optionsOrCallback as CallOptions; } options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - options.otherArgs.headers['x-goog-request-params'] = - this._gaxModule.routingHeader.fromParams({ - parent: request.parent ?? '', - }); - this.initialize(); - return this.innerApiCalls.createIndex(request, options, callback); + options.otherArgs.headers[ + 'x-goog-request-params' + ] = this._gaxModule.routingHeader.fromParams({ + 'parent': request.parent ?? '', + }); + this.initialize().catch(err => {throw err}); + const wrappedCallback: Callback< + LROperation, + protos.google.longrunning.IOperation|null|undefined, + {}|null|undefined>|undefined = callback + ? (error, response, rawResponse, _) => { + this._log.info('createIndex response %j', rawResponse); + callback!(error, response, rawResponse, _); // We verified callback above. + } + : undefined; + this._log.info('createIndex request %j', request); + return this.innerApiCalls.createIndex(request, options, wrappedCallback) + ?.then(([response, rawResponse, _]: [ + LROperation, + protos.google.longrunning.IOperation|undefined, {}|undefined + ]) => { + this._log.info('createIndex response %j', rawResponse); + return [response, rawResponse, _]; + }); } - /** - * Check the status of the long running operation returned by `createIndex()`. - * @param {String} name - * The operation name that will be passed. - * @returns {Promise} - The promise which resolves to an object. - * The decoded operation object has result and metadata field to get information from. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#long-running-operations | documentation } - * for more details and examples. - * @example - * region_tag:firestore_v1_generated_FirestoreAdmin_CreateIndex_async - */ - async checkCreateIndexProgress( - name: string - ): Promise< - LROperation< - protos.google.firestore.admin.v1.Index, - protos.google.firestore.admin.v1.IndexOperationMetadata - > - > { - const request = - new this._gaxModule.operationsProtos.google.longrunning.GetOperationRequest( - {name} - ); +/** + * Check the status of the long running operation returned by `createIndex()`. + * @param {String} name + * The operation name that will be passed. + * @returns {Promise} - The promise which resolves to an object. + * The decoded operation object has result and metadata field to get information from. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#long-running-operations | documentation } + * for more details and examples. + * @example + * region_tag:firestore_v1_generated_FirestoreAdmin_CreateIndex_async + */ + async checkCreateIndexProgress(name: string): Promise>{ + this._log.info('createIndex long-running'); + const request = new this._gaxModule.operationsProtos.google.longrunning.GetOperationRequest({name}); const [operation] = await this.operationsClient.getOperation(request); - const decodeOperation = new this._gaxModule.Operation( - operation, - this.descriptors.longrunning.createIndex, - this._gaxModule.createDefaultBackoffSettings() - ); - return decodeOperation as LROperation< - protos.google.firestore.admin.v1.Index, - protos.google.firestore.admin.v1.IndexOperationMetadata - >; + const decodeOperation = new this._gaxModule.Operation(operation, this.descriptors.longrunning.createIndex, this._gaxModule.createDefaultBackoffSettings()); + return decodeOperation as LROperation; } - /** - * Updates a field configuration. Currently, field updates apply only to - * single field index configuration. However, calls to - * {@link protos.google.firestore.admin.v1.FirestoreAdmin.UpdateField|FirestoreAdmin.UpdateField} - * should provide a field mask to avoid changing any configuration that the - * caller isn't aware of. The field mask should be specified as: `{ paths: - * "index_config" }`. - * - * This call returns a - * {@link protos.google.longrunning.Operation|google.longrunning.Operation} which may be - * used to track the status of the field update. The metadata for the - * operation will be the type - * {@link protos.google.firestore.admin.v1.FieldOperationMetadata|FieldOperationMetadata}. - * - * To configure the default field settings for the database, use - * the special `Field` with resource name: - * `projects/{project_id}/databases/{database_id}/collectionGroups/__default__/fields/*`. - * - * @param {Object} request - * The request object that will be sent. - * @param {google.firestore.admin.v1.Field} request.field - * Required. The field to be updated. - * @param {google.protobuf.FieldMask} request.updateMask - * A mask, relative to the field. If specified, only configuration specified - * by this field_mask will be updated in the field. - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Promise} - The promise which resolves to an array. - * The first element of the array is an object representing - * a long running operation. Its `promise()` method returns a promise - * you can `await` for. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#long-running-operations | documentation } - * for more details and examples. - * @example - * region_tag:firestore_v1_generated_FirestoreAdmin_UpdateField_async - */ +/** + * Updates a field configuration. Currently, field updates apply only to + * single field index configuration. However, calls to + * {@link protos.google.firestore.admin.v1.FirestoreAdmin.UpdateField|FirestoreAdmin.UpdateField} + * should provide a field mask to avoid changing any configuration that the + * caller isn't aware of. The field mask should be specified as: `{ paths: + * "index_config" }`. + * + * This call returns a + * {@link protos.google.longrunning.Operation|google.longrunning.Operation} which may be + * used to track the status of the field update. The metadata for the + * operation will be the type + * {@link protos.google.firestore.admin.v1.FieldOperationMetadata|FieldOperationMetadata}. + * + * To configure the default field settings for the database, use + * the special `Field` with resource name: + * `projects/{project_id}/databases/{database_id}/collectionGroups/__default__/fields/*`. + * + * @param {Object} request + * The request object that will be sent. + * @param {google.firestore.admin.v1.Field} request.field + * Required. The field to be updated. + * @param {google.protobuf.FieldMask} request.updateMask + * A mask, relative to the field. If specified, only configuration specified + * by this field_mask will be updated in the field. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is an object representing + * a long running operation. Its `promise()` method returns a promise + * you can `await` for. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#long-running-operations | documentation } + * for more details and examples. + * @example + * region_tag:firestore_v1_generated_FirestoreAdmin_UpdateField_async + */ updateField( - request?: protos.google.firestore.admin.v1.IUpdateFieldRequest, - options?: CallOptions - ): Promise< - [ - LROperation< - protos.google.firestore.admin.v1.IField, - protos.google.firestore.admin.v1.IFieldOperationMetadata - >, - protos.google.longrunning.IOperation | undefined, - {} | undefined, - ] - >; + request?: protos.google.firestore.admin.v1.IUpdateFieldRequest, + options?: CallOptions): + Promise<[ + LROperation, + protos.google.longrunning.IOperation|undefined, {}|undefined + ]>; updateField( - request: protos.google.firestore.admin.v1.IUpdateFieldRequest, - options: CallOptions, - callback: Callback< - LROperation< - protos.google.firestore.admin.v1.IField, - protos.google.firestore.admin.v1.IFieldOperationMetadata - >, - protos.google.longrunning.IOperation | null | undefined, - {} | null | undefined - > - ): void; + request: protos.google.firestore.admin.v1.IUpdateFieldRequest, + options: CallOptions, + callback: Callback< + LROperation, + protos.google.longrunning.IOperation|null|undefined, + {}|null|undefined>): void; updateField( - request: protos.google.firestore.admin.v1.IUpdateFieldRequest, - callback: Callback< - LROperation< - protos.google.firestore.admin.v1.IField, - protos.google.firestore.admin.v1.IFieldOperationMetadata - >, - protos.google.longrunning.IOperation | null | undefined, - {} | null | undefined - > - ): void; + request: protos.google.firestore.admin.v1.IUpdateFieldRequest, + callback: Callback< + LROperation, + protos.google.longrunning.IOperation|null|undefined, + {}|null|undefined>): void; updateField( - request?: protos.google.firestore.admin.v1.IUpdateFieldRequest, - optionsOrCallback?: - | CallOptions - | Callback< - LROperation< - protos.google.firestore.admin.v1.IField, - protos.google.firestore.admin.v1.IFieldOperationMetadata - >, - protos.google.longrunning.IOperation | null | undefined, - {} | null | undefined - >, - callback?: Callback< - LROperation< - protos.google.firestore.admin.v1.IField, - protos.google.firestore.admin.v1.IFieldOperationMetadata - >, - protos.google.longrunning.IOperation | null | undefined, - {} | null | undefined - > - ): Promise< - [ - LROperation< - protos.google.firestore.admin.v1.IField, - protos.google.firestore.admin.v1.IFieldOperationMetadata - >, - protos.google.longrunning.IOperation | undefined, - {} | undefined, - ] - > | void { + request?: protos.google.firestore.admin.v1.IUpdateFieldRequest, + optionsOrCallback?: CallOptions|Callback< + LROperation, + protos.google.longrunning.IOperation|null|undefined, + {}|null|undefined>, + callback?: Callback< + LROperation, + protos.google.longrunning.IOperation|null|undefined, + {}|null|undefined>): + Promise<[ + LROperation, + protos.google.longrunning.IOperation|undefined, {}|undefined + ]>|void { request = request || {}; let options: CallOptions; if (typeof optionsOrCallback === 'function' && callback === undefined) { callback = optionsOrCallback; options = {}; - } else { + } + else { options = optionsOrCallback as CallOptions; } options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - options.otherArgs.headers['x-goog-request-params'] = - this._gaxModule.routingHeader.fromParams({ - 'field.name': request.field!.name ?? '', - }); - this.initialize(); - return this.innerApiCalls.updateField(request, options, callback); + options.otherArgs.headers[ + 'x-goog-request-params' + ] = this._gaxModule.routingHeader.fromParams({ + 'field.name': request.field!.name ?? '', + }); + this.initialize().catch(err => {throw err}); + const wrappedCallback: Callback< + LROperation, + protos.google.longrunning.IOperation|null|undefined, + {}|null|undefined>|undefined = callback + ? (error, response, rawResponse, _) => { + this._log.info('updateField response %j', rawResponse); + callback!(error, response, rawResponse, _); // We verified callback above. + } + : undefined; + this._log.info('updateField request %j', request); + return this.innerApiCalls.updateField(request, options, wrappedCallback) + ?.then(([response, rawResponse, _]: [ + LROperation, + protos.google.longrunning.IOperation|undefined, {}|undefined + ]) => { + this._log.info('updateField response %j', rawResponse); + return [response, rawResponse, _]; + }); } - /** - * Check the status of the long running operation returned by `updateField()`. - * @param {String} name - * The operation name that will be passed. - * @returns {Promise} - The promise which resolves to an object. - * The decoded operation object has result and metadata field to get information from. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#long-running-operations | documentation } - * for more details and examples. - * @example - * region_tag:firestore_v1_generated_FirestoreAdmin_UpdateField_async - */ - async checkUpdateFieldProgress( - name: string - ): Promise< - LROperation< - protos.google.firestore.admin.v1.Field, - protos.google.firestore.admin.v1.FieldOperationMetadata - > - > { - const request = - new this._gaxModule.operationsProtos.google.longrunning.GetOperationRequest( - {name} - ); +/** + * Check the status of the long running operation returned by `updateField()`. + * @param {String} name + * The operation name that will be passed. + * @returns {Promise} - The promise which resolves to an object. + * The decoded operation object has result and metadata field to get information from. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#long-running-operations | documentation } + * for more details and examples. + * @example + * region_tag:firestore_v1_generated_FirestoreAdmin_UpdateField_async + */ + async checkUpdateFieldProgress(name: string): Promise>{ + this._log.info('updateField long-running'); + const request = new this._gaxModule.operationsProtos.google.longrunning.GetOperationRequest({name}); const [operation] = await this.operationsClient.getOperation(request); - const decodeOperation = new this._gaxModule.Operation( - operation, - this.descriptors.longrunning.updateField, - this._gaxModule.createDefaultBackoffSettings() - ); - return decodeOperation as LROperation< - protos.google.firestore.admin.v1.Field, - protos.google.firestore.admin.v1.FieldOperationMetadata - >; + const decodeOperation = new this._gaxModule.Operation(operation, this.descriptors.longrunning.updateField, this._gaxModule.createDefaultBackoffSettings()); + return decodeOperation as LROperation; } - /** - * Exports a copy of all or a subset of documents from Google Cloud Firestore - * to another storage system, such as Google Cloud Storage. Recent updates to - * documents may not be reflected in the export. The export occurs in the - * background and its progress can be monitored and managed via the - * Operation resource that is created. The output of an export may only be - * used once the associated operation is done. If an export operation is - * cancelled before completion it may leave partial data behind in Google - * Cloud Storage. - * - * For more details on export behavior and output format, refer to: - * https://cloud.google.com/firestore/docs/manage-data/export-import - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.name - * Required. Database to export. Should be of the form: - * `projects/{project_id}/databases/{database_id}`. - * @param {string[]} request.collectionIds - * Which collection IDs to export. Unspecified means all collections. Each - * collection ID in this list must be unique. - * @param {string} request.outputUriPrefix - * The output URI. Currently only supports Google Cloud Storage URIs of the - * form: `gs://BUCKET_NAME[/NAMESPACE_PATH]`, where `BUCKET_NAME` is the name - * of the Google Cloud Storage bucket and `NAMESPACE_PATH` is an optional - * Google Cloud Storage namespace path. When - * choosing a name, be sure to consider Google Cloud Storage naming - * guidelines: https://cloud.google.com/storage/docs/naming. - * If the URI is a bucket (without a namespace path), a prefix will be - * generated based on the start time. - * @param {string[]} request.namespaceIds - * An empty list represents all namespaces. This is the preferred - * usage for databases that don't use namespaces. - * - * An empty string element represents the default namespace. This should be - * used if the database has data in non-default namespaces, but doesn't want - * to include them. Each namespace in this list must be unique. - * @param {google.protobuf.Timestamp} request.snapshotTime - * The timestamp that corresponds to the version of the database to be - * exported. The timestamp must be in the past, rounded to the minute and not - * older than - * {@link protos.google.firestore.admin.v1.Database.earliest_version_time|earliestVersionTime}. - * If specified, then the exported documents will represent a consistent view - * of the database at the provided time. Otherwise, there are no guarantees - * about the consistency of the exported documents. - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Promise} - The promise which resolves to an array. - * The first element of the array is an object representing - * a long running operation. Its `promise()` method returns a promise - * you can `await` for. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#long-running-operations | documentation } - * for more details and examples. - * @example - * region_tag:firestore_v1_generated_FirestoreAdmin_ExportDocuments_async - */ +/** + * Exports a copy of all or a subset of documents from Google Cloud Firestore + * to another storage system, such as Google Cloud Storage. Recent updates to + * documents may not be reflected in the export. The export occurs in the + * background and its progress can be monitored and managed via the + * Operation resource that is created. The output of an export may only be + * used once the associated operation is done. If an export operation is + * cancelled before completion it may leave partial data behind in Google + * Cloud Storage. + * + * For more details on export behavior and output format, refer to: + * https://cloud.google.com/firestore/docs/manage-data/export-import + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.name + * Required. Database to export. Should be of the form: + * `projects/{project_id}/databases/{database_id}`. + * @param {string[]} request.collectionIds + * Which collection IDs to export. Unspecified means all collections. Each + * collection ID in this list must be unique. + * @param {string} request.outputUriPrefix + * The output URI. Currently only supports Google Cloud Storage URIs of the + * form: `gs://BUCKET_NAME[/NAMESPACE_PATH]`, where `BUCKET_NAME` is the name + * of the Google Cloud Storage bucket and `NAMESPACE_PATH` is an optional + * Google Cloud Storage namespace path. When + * choosing a name, be sure to consider Google Cloud Storage naming + * guidelines: https://cloud.google.com/storage/docs/naming. + * If the URI is a bucket (without a namespace path), a prefix will be + * generated based on the start time. + * @param {string[]} request.namespaceIds + * An empty list represents all namespaces. This is the preferred + * usage for databases that don't use namespaces. + * + * An empty string element represents the default namespace. This should be + * used if the database has data in non-default namespaces, but doesn't want + * to include them. Each namespace in this list must be unique. + * @param {google.protobuf.Timestamp} request.snapshotTime + * The timestamp that corresponds to the version of the database to be + * exported. The timestamp must be in the past, rounded to the minute and not + * older than + * {@link protos.google.firestore.admin.v1.Database.earliest_version_time|earliestVersionTime}. + * If specified, then the exported documents will represent a consistent view + * of the database at the provided time. Otherwise, there are no guarantees + * about the consistency of the exported documents. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is an object representing + * a long running operation. Its `promise()` method returns a promise + * you can `await` for. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#long-running-operations | documentation } + * for more details and examples. + * @example + * region_tag:firestore_v1_generated_FirestoreAdmin_ExportDocuments_async + */ exportDocuments( - request?: protos.google.firestore.admin.v1.IExportDocumentsRequest, - options?: CallOptions - ): Promise< - [ - LROperation< - protos.google.firestore.admin.v1.IExportDocumentsResponse, - protos.google.firestore.admin.v1.IExportDocumentsMetadata - >, - protos.google.longrunning.IOperation | undefined, - {} | undefined, - ] - >; + request?: protos.google.firestore.admin.v1.IExportDocumentsRequest, + options?: CallOptions): + Promise<[ + LROperation, + protos.google.longrunning.IOperation|undefined, {}|undefined + ]>; exportDocuments( - request: protos.google.firestore.admin.v1.IExportDocumentsRequest, - options: CallOptions, - callback: Callback< - LROperation< - protos.google.firestore.admin.v1.IExportDocumentsResponse, - protos.google.firestore.admin.v1.IExportDocumentsMetadata - >, - protos.google.longrunning.IOperation | null | undefined, - {} | null | undefined - > - ): void; + request: protos.google.firestore.admin.v1.IExportDocumentsRequest, + options: CallOptions, + callback: Callback< + LROperation, + protos.google.longrunning.IOperation|null|undefined, + {}|null|undefined>): void; exportDocuments( - request: protos.google.firestore.admin.v1.IExportDocumentsRequest, - callback: Callback< - LROperation< - protos.google.firestore.admin.v1.IExportDocumentsResponse, - protos.google.firestore.admin.v1.IExportDocumentsMetadata - >, - protos.google.longrunning.IOperation | null | undefined, - {} | null | undefined - > - ): void; + request: protos.google.firestore.admin.v1.IExportDocumentsRequest, + callback: Callback< + LROperation, + protos.google.longrunning.IOperation|null|undefined, + {}|null|undefined>): void; exportDocuments( - request?: protos.google.firestore.admin.v1.IExportDocumentsRequest, - optionsOrCallback?: - | CallOptions - | Callback< - LROperation< - protos.google.firestore.admin.v1.IExportDocumentsResponse, - protos.google.firestore.admin.v1.IExportDocumentsMetadata - >, - protos.google.longrunning.IOperation | null | undefined, - {} | null | undefined - >, - callback?: Callback< - LROperation< - protos.google.firestore.admin.v1.IExportDocumentsResponse, - protos.google.firestore.admin.v1.IExportDocumentsMetadata - >, - protos.google.longrunning.IOperation | null | undefined, - {} | null | undefined - > - ): Promise< - [ - LROperation< - protos.google.firestore.admin.v1.IExportDocumentsResponse, - protos.google.firestore.admin.v1.IExportDocumentsMetadata - >, - protos.google.longrunning.IOperation | undefined, - {} | undefined, - ] - > | void { + request?: protos.google.firestore.admin.v1.IExportDocumentsRequest, + optionsOrCallback?: CallOptions|Callback< + LROperation, + protos.google.longrunning.IOperation|null|undefined, + {}|null|undefined>, + callback?: Callback< + LROperation, + protos.google.longrunning.IOperation|null|undefined, + {}|null|undefined>): + Promise<[ + LROperation, + protos.google.longrunning.IOperation|undefined, {}|undefined + ]>|void { request = request || {}; let options: CallOptions; if (typeof optionsOrCallback === 'function' && callback === undefined) { callback = optionsOrCallback; options = {}; - } else { + } + else { options = optionsOrCallback as CallOptions; } options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - options.otherArgs.headers['x-goog-request-params'] = - this._gaxModule.routingHeader.fromParams({ - name: request.name ?? '', - }); - this.initialize(); - return this.innerApiCalls.exportDocuments(request, options, callback); + options.otherArgs.headers[ + 'x-goog-request-params' + ] = this._gaxModule.routingHeader.fromParams({ + 'name': request.name ?? '', + }); + this.initialize().catch(err => {throw err}); + const wrappedCallback: Callback< + LROperation, + protos.google.longrunning.IOperation|null|undefined, + {}|null|undefined>|undefined = callback + ? (error, response, rawResponse, _) => { + this._log.info('exportDocuments response %j', rawResponse); + callback!(error, response, rawResponse, _); // We verified callback above. + } + : undefined; + this._log.info('exportDocuments request %j', request); + return this.innerApiCalls.exportDocuments(request, options, wrappedCallback) + ?.then(([response, rawResponse, _]: [ + LROperation, + protos.google.longrunning.IOperation|undefined, {}|undefined + ]) => { + this._log.info('exportDocuments response %j', rawResponse); + return [response, rawResponse, _]; + }); } - /** - * Check the status of the long running operation returned by `exportDocuments()`. - * @param {String} name - * The operation name that will be passed. - * @returns {Promise} - The promise which resolves to an object. - * The decoded operation object has result and metadata field to get information from. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#long-running-operations | documentation } - * for more details and examples. - * @example - * region_tag:firestore_v1_generated_FirestoreAdmin_ExportDocuments_async - */ - async checkExportDocumentsProgress( - name: string - ): Promise< - LROperation< - protos.google.firestore.admin.v1.ExportDocumentsResponse, - protos.google.firestore.admin.v1.ExportDocumentsMetadata - > - > { - const request = - new this._gaxModule.operationsProtos.google.longrunning.GetOperationRequest( - {name} - ); +/** + * Check the status of the long running operation returned by `exportDocuments()`. + * @param {String} name + * The operation name that will be passed. + * @returns {Promise} - The promise which resolves to an object. + * The decoded operation object has result and metadata field to get information from. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#long-running-operations | documentation } + * for more details and examples. + * @example + * region_tag:firestore_v1_generated_FirestoreAdmin_ExportDocuments_async + */ + async checkExportDocumentsProgress(name: string): Promise>{ + this._log.info('exportDocuments long-running'); + const request = new this._gaxModule.operationsProtos.google.longrunning.GetOperationRequest({name}); const [operation] = await this.operationsClient.getOperation(request); - const decodeOperation = new this._gaxModule.Operation( - operation, - this.descriptors.longrunning.exportDocuments, - this._gaxModule.createDefaultBackoffSettings() - ); - return decodeOperation as LROperation< - protos.google.firestore.admin.v1.ExportDocumentsResponse, - protos.google.firestore.admin.v1.ExportDocumentsMetadata - >; + const decodeOperation = new this._gaxModule.Operation(operation, this.descriptors.longrunning.exportDocuments, this._gaxModule.createDefaultBackoffSettings()); + return decodeOperation as LROperation; } - /** - * Imports documents into Google Cloud Firestore. Existing documents with the - * same name are overwritten. The import occurs in the background and its - * progress can be monitored and managed via the Operation resource that is - * created. If an ImportDocuments operation is cancelled, it is possible - * that a subset of the data has already been imported to Cloud Firestore. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.name - * Required. Database to import into. Should be of the form: - * `projects/{project_id}/databases/{database_id}`. - * @param {string[]} request.collectionIds - * Which collection IDs to import. Unspecified means all collections included - * in the import. Each collection ID in this list must be unique. - * @param {string} request.inputUriPrefix - * Location of the exported files. - * This must match the output_uri_prefix of an ExportDocumentsResponse from - * an export that has completed successfully. - * See: - * {@link protos.google.firestore.admin.v1.ExportDocumentsResponse.output_uri_prefix|google.firestore.admin.v1.ExportDocumentsResponse.output_uri_prefix}. - * @param {string[]} request.namespaceIds - * An empty list represents all namespaces. This is the preferred - * usage for databases that don't use namespaces. - * - * An empty string element represents the default namespace. This should be - * used if the database has data in non-default namespaces, but doesn't want - * to include them. Each namespace in this list must be unique. - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Promise} - The promise which resolves to an array. - * The first element of the array is an object representing - * a long running operation. Its `promise()` method returns a promise - * you can `await` for. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#long-running-operations | documentation } - * for more details and examples. - * @example - * region_tag:firestore_v1_generated_FirestoreAdmin_ImportDocuments_async - */ +/** + * Imports documents into Google Cloud Firestore. Existing documents with the + * same name are overwritten. The import occurs in the background and its + * progress can be monitored and managed via the Operation resource that is + * created. If an ImportDocuments operation is cancelled, it is possible + * that a subset of the data has already been imported to Cloud Firestore. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.name + * Required. Database to import into. Should be of the form: + * `projects/{project_id}/databases/{database_id}`. + * @param {string[]} request.collectionIds + * Which collection IDs to import. Unspecified means all collections included + * in the import. Each collection ID in this list must be unique. + * @param {string} request.inputUriPrefix + * Location of the exported files. + * This must match the output_uri_prefix of an ExportDocumentsResponse from + * an export that has completed successfully. + * See: + * {@link protos.google.firestore.admin.v1.ExportDocumentsResponse.output_uri_prefix|google.firestore.admin.v1.ExportDocumentsResponse.output_uri_prefix}. + * @param {string[]} request.namespaceIds + * An empty list represents all namespaces. This is the preferred + * usage for databases that don't use namespaces. + * + * An empty string element represents the default namespace. This should be + * used if the database has data in non-default namespaces, but doesn't want + * to include them. Each namespace in this list must be unique. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is an object representing + * a long running operation. Its `promise()` method returns a promise + * you can `await` for. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#long-running-operations | documentation } + * for more details and examples. + * @example + * region_tag:firestore_v1_generated_FirestoreAdmin_ImportDocuments_async + */ importDocuments( - request?: protos.google.firestore.admin.v1.IImportDocumentsRequest, - options?: CallOptions - ): Promise< - [ - LROperation< - protos.google.protobuf.IEmpty, - protos.google.firestore.admin.v1.IImportDocumentsMetadata - >, - protos.google.longrunning.IOperation | undefined, - {} | undefined, - ] - >; + request?: protos.google.firestore.admin.v1.IImportDocumentsRequest, + options?: CallOptions): + Promise<[ + LROperation, + protos.google.longrunning.IOperation|undefined, {}|undefined + ]>; importDocuments( - request: protos.google.firestore.admin.v1.IImportDocumentsRequest, - options: CallOptions, - callback: Callback< - LROperation< - protos.google.protobuf.IEmpty, - protos.google.firestore.admin.v1.IImportDocumentsMetadata - >, - protos.google.longrunning.IOperation | null | undefined, - {} | null | undefined - > - ): void; + request: protos.google.firestore.admin.v1.IImportDocumentsRequest, + options: CallOptions, + callback: Callback< + LROperation, + protos.google.longrunning.IOperation|null|undefined, + {}|null|undefined>): void; importDocuments( - request: protos.google.firestore.admin.v1.IImportDocumentsRequest, - callback: Callback< - LROperation< - protos.google.protobuf.IEmpty, - protos.google.firestore.admin.v1.IImportDocumentsMetadata - >, - protos.google.longrunning.IOperation | null | undefined, - {} | null | undefined - > - ): void; + request: protos.google.firestore.admin.v1.IImportDocumentsRequest, + callback: Callback< + LROperation, + protos.google.longrunning.IOperation|null|undefined, + {}|null|undefined>): void; importDocuments( - request?: protos.google.firestore.admin.v1.IImportDocumentsRequest, - optionsOrCallback?: - | CallOptions - | Callback< - LROperation< - protos.google.protobuf.IEmpty, - protos.google.firestore.admin.v1.IImportDocumentsMetadata - >, - protos.google.longrunning.IOperation | null | undefined, - {} | null | undefined - >, - callback?: Callback< - LROperation< - protos.google.protobuf.IEmpty, - protos.google.firestore.admin.v1.IImportDocumentsMetadata - >, - protos.google.longrunning.IOperation | null | undefined, - {} | null | undefined - > - ): Promise< - [ - LROperation< - protos.google.protobuf.IEmpty, - protos.google.firestore.admin.v1.IImportDocumentsMetadata - >, - protos.google.longrunning.IOperation | undefined, - {} | undefined, - ] - > | void { + request?: protos.google.firestore.admin.v1.IImportDocumentsRequest, + optionsOrCallback?: CallOptions|Callback< + LROperation, + protos.google.longrunning.IOperation|null|undefined, + {}|null|undefined>, + callback?: Callback< + LROperation, + protos.google.longrunning.IOperation|null|undefined, + {}|null|undefined>): + Promise<[ + LROperation, + protos.google.longrunning.IOperation|undefined, {}|undefined + ]>|void { request = request || {}; let options: CallOptions; if (typeof optionsOrCallback === 'function' && callback === undefined) { callback = optionsOrCallback; options = {}; - } else { + } + else { options = optionsOrCallback as CallOptions; } options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - options.otherArgs.headers['x-goog-request-params'] = - this._gaxModule.routingHeader.fromParams({ - name: request.name ?? '', - }); - this.initialize(); - return this.innerApiCalls.importDocuments(request, options, callback); + options.otherArgs.headers[ + 'x-goog-request-params' + ] = this._gaxModule.routingHeader.fromParams({ + 'name': request.name ?? '', + }); + this.initialize().catch(err => {throw err}); + const wrappedCallback: Callback< + LROperation, + protos.google.longrunning.IOperation|null|undefined, + {}|null|undefined>|undefined = callback + ? (error, response, rawResponse, _) => { + this._log.info('importDocuments response %j', rawResponse); + callback!(error, response, rawResponse, _); // We verified callback above. + } + : undefined; + this._log.info('importDocuments request %j', request); + return this.innerApiCalls.importDocuments(request, options, wrappedCallback) + ?.then(([response, rawResponse, _]: [ + LROperation, + protos.google.longrunning.IOperation|undefined, {}|undefined + ]) => { + this._log.info('importDocuments response %j', rawResponse); + return [response, rawResponse, _]; + }); } - /** - * Check the status of the long running operation returned by `importDocuments()`. - * @param {String} name - * The operation name that will be passed. - * @returns {Promise} - The promise which resolves to an object. - * The decoded operation object has result and metadata field to get information from. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#long-running-operations | documentation } - * for more details and examples. - * @example - * region_tag:firestore_v1_generated_FirestoreAdmin_ImportDocuments_async - */ - async checkImportDocumentsProgress( - name: string - ): Promise< - LROperation< - protos.google.protobuf.Empty, - protos.google.firestore.admin.v1.ImportDocumentsMetadata - > - > { - const request = - new this._gaxModule.operationsProtos.google.longrunning.GetOperationRequest( - {name} - ); +/** + * Check the status of the long running operation returned by `importDocuments()`. + * @param {String} name + * The operation name that will be passed. + * @returns {Promise} - The promise which resolves to an object. + * The decoded operation object has result and metadata field to get information from. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#long-running-operations | documentation } + * for more details and examples. + * @example + * region_tag:firestore_v1_generated_FirestoreAdmin_ImportDocuments_async + */ + async checkImportDocumentsProgress(name: string): Promise>{ + this._log.info('importDocuments long-running'); + const request = new this._gaxModule.operationsProtos.google.longrunning.GetOperationRequest({name}); const [operation] = await this.operationsClient.getOperation(request); - const decodeOperation = new this._gaxModule.Operation( - operation, - this.descriptors.longrunning.importDocuments, - this._gaxModule.createDefaultBackoffSettings() - ); - return decodeOperation as LROperation< - protos.google.protobuf.Empty, - protos.google.firestore.admin.v1.ImportDocumentsMetadata - >; + const decodeOperation = new this._gaxModule.Operation(operation, this.descriptors.longrunning.importDocuments, this._gaxModule.createDefaultBackoffSettings()); + return decodeOperation as LROperation; } - /** - * Bulk deletes a subset of documents from Google Cloud Firestore. - * Documents created or updated after the underlying system starts to process - * the request will not be deleted. The bulk delete occurs in the background - * and its progress can be monitored and managed via the Operation resource - * that is created. - * - * For more details on bulk delete behavior, refer to: - * https://cloud.google.com/firestore/docs/manage-data/bulk-delete - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.name - * Required. Database to operate. Should be of the form: - * `projects/{project_id}/databases/{database_id}`. - * @param {string[]} [request.collectionIds] - * Optional. IDs of the collection groups to delete. Unspecified means all - * collection groups. - * - * Each collection group in this list must be unique. - * @param {string[]} [request.namespaceIds] - * Optional. Namespaces to delete. - * - * An empty list means all namespaces. This is the recommended - * usage for databases that don't use namespaces. - * - * An empty string element represents the default namespace. This should be - * used if the database has data in non-default namespaces, but doesn't want - * to delete from them. - * - * Each namespace in this list must be unique. - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Promise} - The promise which resolves to an array. - * The first element of the array is an object representing - * a long running operation. Its `promise()` method returns a promise - * you can `await` for. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#long-running-operations | documentation } - * for more details and examples. - * @example - * region_tag:firestore_v1_generated_FirestoreAdmin_BulkDeleteDocuments_async - */ +/** + * Bulk deletes a subset of documents from Google Cloud Firestore. + * Documents created or updated after the underlying system starts to process + * the request will not be deleted. The bulk delete occurs in the background + * and its progress can be monitored and managed via the Operation resource + * that is created. + * + * For more details on bulk delete behavior, refer to: + * https://cloud.google.com/firestore/docs/manage-data/bulk-delete + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.name + * Required. Database to operate. Should be of the form: + * `projects/{project_id}/databases/{database_id}`. + * @param {string[]} [request.collectionIds] + * Optional. IDs of the collection groups to delete. Unspecified means all + * collection groups. + * + * Each collection group in this list must be unique. + * @param {string[]} [request.namespaceIds] + * Optional. Namespaces to delete. + * + * An empty list means all namespaces. This is the recommended + * usage for databases that don't use namespaces. + * + * An empty string element represents the default namespace. This should be + * used if the database has data in non-default namespaces, but doesn't want + * to delete from them. + * + * Each namespace in this list must be unique. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is an object representing + * a long running operation. Its `promise()` method returns a promise + * you can `await` for. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#long-running-operations | documentation } + * for more details and examples. + * @example + * region_tag:firestore_v1_generated_FirestoreAdmin_BulkDeleteDocuments_async + */ bulkDeleteDocuments( - request?: protos.google.firestore.admin.v1.IBulkDeleteDocumentsRequest, - options?: CallOptions - ): Promise< - [ - LROperation< - protos.google.firestore.admin.v1.IBulkDeleteDocumentsResponse, - protos.google.firestore.admin.v1.IBulkDeleteDocumentsMetadata - >, - protos.google.longrunning.IOperation | undefined, - {} | undefined, - ] - >; + request?: protos.google.firestore.admin.v1.IBulkDeleteDocumentsRequest, + options?: CallOptions): + Promise<[ + LROperation, + protos.google.longrunning.IOperation|undefined, {}|undefined + ]>; bulkDeleteDocuments( - request: protos.google.firestore.admin.v1.IBulkDeleteDocumentsRequest, - options: CallOptions, - callback: Callback< - LROperation< - protos.google.firestore.admin.v1.IBulkDeleteDocumentsResponse, - protos.google.firestore.admin.v1.IBulkDeleteDocumentsMetadata - >, - protos.google.longrunning.IOperation | null | undefined, - {} | null | undefined - > - ): void; + request: protos.google.firestore.admin.v1.IBulkDeleteDocumentsRequest, + options: CallOptions, + callback: Callback< + LROperation, + protos.google.longrunning.IOperation|null|undefined, + {}|null|undefined>): void; bulkDeleteDocuments( - request: protos.google.firestore.admin.v1.IBulkDeleteDocumentsRequest, - callback: Callback< - LROperation< - protos.google.firestore.admin.v1.IBulkDeleteDocumentsResponse, - protos.google.firestore.admin.v1.IBulkDeleteDocumentsMetadata - >, - protos.google.longrunning.IOperation | null | undefined, - {} | null | undefined - > - ): void; + request: protos.google.firestore.admin.v1.IBulkDeleteDocumentsRequest, + callback: Callback< + LROperation, + protos.google.longrunning.IOperation|null|undefined, + {}|null|undefined>): void; bulkDeleteDocuments( - request?: protos.google.firestore.admin.v1.IBulkDeleteDocumentsRequest, - optionsOrCallback?: - | CallOptions - | Callback< - LROperation< - protos.google.firestore.admin.v1.IBulkDeleteDocumentsResponse, - protos.google.firestore.admin.v1.IBulkDeleteDocumentsMetadata - >, - protos.google.longrunning.IOperation | null | undefined, - {} | null | undefined - >, - callback?: Callback< - LROperation< - protos.google.firestore.admin.v1.IBulkDeleteDocumentsResponse, - protos.google.firestore.admin.v1.IBulkDeleteDocumentsMetadata - >, - protos.google.longrunning.IOperation | null | undefined, - {} | null | undefined - > - ): Promise< - [ - LROperation< - protos.google.firestore.admin.v1.IBulkDeleteDocumentsResponse, - protos.google.firestore.admin.v1.IBulkDeleteDocumentsMetadata - >, - protos.google.longrunning.IOperation | undefined, - {} | undefined, - ] - > | void { + request?: protos.google.firestore.admin.v1.IBulkDeleteDocumentsRequest, + optionsOrCallback?: CallOptions|Callback< + LROperation, + protos.google.longrunning.IOperation|null|undefined, + {}|null|undefined>, + callback?: Callback< + LROperation, + protos.google.longrunning.IOperation|null|undefined, + {}|null|undefined>): + Promise<[ + LROperation, + protos.google.longrunning.IOperation|undefined, {}|undefined + ]>|void { request = request || {}; let options: CallOptions; if (typeof optionsOrCallback === 'function' && callback === undefined) { callback = optionsOrCallback; options = {}; - } else { + } + else { options = optionsOrCallback as CallOptions; } options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - options.otherArgs.headers['x-goog-request-params'] = - this._gaxModule.routingHeader.fromParams({ - name: request.name ?? '', - }); - this.initialize(); - return this.innerApiCalls.bulkDeleteDocuments(request, options, callback); + options.otherArgs.headers[ + 'x-goog-request-params' + ] = this._gaxModule.routingHeader.fromParams({ + 'name': request.name ?? '', + }); + this.initialize().catch(err => {throw err}); + const wrappedCallback: Callback< + LROperation, + protos.google.longrunning.IOperation|null|undefined, + {}|null|undefined>|undefined = callback + ? (error, response, rawResponse, _) => { + this._log.info('bulkDeleteDocuments response %j', rawResponse); + callback!(error, response, rawResponse, _); // We verified callback above. + } + : undefined; + this._log.info('bulkDeleteDocuments request %j', request); + return this.innerApiCalls.bulkDeleteDocuments(request, options, wrappedCallback) + ?.then(([response, rawResponse, _]: [ + LROperation, + protos.google.longrunning.IOperation|undefined, {}|undefined + ]) => { + this._log.info('bulkDeleteDocuments response %j', rawResponse); + return [response, rawResponse, _]; + }); } - /** - * Check the status of the long running operation returned by `bulkDeleteDocuments()`. - * @param {String} name - * The operation name that will be passed. - * @returns {Promise} - The promise which resolves to an object. - * The decoded operation object has result and metadata field to get information from. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#long-running-operations | documentation } - * for more details and examples. - * @example - * region_tag:firestore_v1_generated_FirestoreAdmin_BulkDeleteDocuments_async - */ - async checkBulkDeleteDocumentsProgress( - name: string - ): Promise< - LROperation< - protos.google.firestore.admin.v1.BulkDeleteDocumentsResponse, - protos.google.firestore.admin.v1.BulkDeleteDocumentsMetadata - > - > { - const request = - new this._gaxModule.operationsProtos.google.longrunning.GetOperationRequest( - {name} - ); +/** + * Check the status of the long running operation returned by `bulkDeleteDocuments()`. + * @param {String} name + * The operation name that will be passed. + * @returns {Promise} - The promise which resolves to an object. + * The decoded operation object has result and metadata field to get information from. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#long-running-operations | documentation } + * for more details and examples. + * @example + * region_tag:firestore_v1_generated_FirestoreAdmin_BulkDeleteDocuments_async + */ + async checkBulkDeleteDocumentsProgress(name: string): Promise>{ + this._log.info('bulkDeleteDocuments long-running'); + const request = new this._gaxModule.operationsProtos.google.longrunning.GetOperationRequest({name}); const [operation] = await this.operationsClient.getOperation(request); - const decodeOperation = new this._gaxModule.Operation( - operation, - this.descriptors.longrunning.bulkDeleteDocuments, - this._gaxModule.createDefaultBackoffSettings() - ); - return decodeOperation as LROperation< - protos.google.firestore.admin.v1.BulkDeleteDocumentsResponse, - protos.google.firestore.admin.v1.BulkDeleteDocumentsMetadata - >; + const decodeOperation = new this._gaxModule.Operation(operation, this.descriptors.longrunning.bulkDeleteDocuments, this._gaxModule.createDefaultBackoffSettings()); + return decodeOperation as LROperation; } - /** - * Create a database. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.parent - * Required. A parent name of the form - * `projects/{project_id}` - * @param {google.firestore.admin.v1.Database} request.database - * Required. The Database to create. - * @param {string} request.databaseId - * Required. The ID to use for the database, which will become the final - * component of the database's resource name. - * - * This value should be 4-63 characters. Valid characters are /{@link protos.0-9|a-z}-/ - * with first character a letter and the last a letter or a number. Must not - * be UUID-like /[0-9a-f]{8}(-[0-9a-f]{4}){3}-[0-9a-f]{12}/. - * - * "(default)" database ID is also valid. - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Promise} - The promise which resolves to an array. - * The first element of the array is an object representing - * a long running operation. Its `promise()` method returns a promise - * you can `await` for. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#long-running-operations | documentation } - * for more details and examples. - * @example - * region_tag:firestore_v1_generated_FirestoreAdmin_CreateDatabase_async - */ +/** + * Create a database. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.parent + * Required. A parent name of the form + * `projects/{project_id}` + * @param {google.firestore.admin.v1.Database} request.database + * Required. The Database to create. + * @param {string} request.databaseId + * Required. The ID to use for the database, which will become the final + * component of the database's resource name. + * + * This value should be 4-63 characters. Valid characters are /{@link protos.0-9|a-z}-/ + * with first character a letter and the last a letter or a number. Must not + * be UUID-like /[0-9a-f]{8}(-[0-9a-f]{4}){3}-[0-9a-f]{12}/. + * + * "(default)" database ID is also valid. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is an object representing + * a long running operation. Its `promise()` method returns a promise + * you can `await` for. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#long-running-operations | documentation } + * for more details and examples. + * @example + * region_tag:firestore_v1_generated_FirestoreAdmin_CreateDatabase_async + */ createDatabase( - request?: protos.google.firestore.admin.v1.ICreateDatabaseRequest, - options?: CallOptions - ): Promise< - [ - LROperation< - protos.google.firestore.admin.v1.IDatabase, - protos.google.firestore.admin.v1.ICreateDatabaseMetadata - >, - protos.google.longrunning.IOperation | undefined, - {} | undefined, - ] - >; + request?: protos.google.firestore.admin.v1.ICreateDatabaseRequest, + options?: CallOptions): + Promise<[ + LROperation, + protos.google.longrunning.IOperation|undefined, {}|undefined + ]>; createDatabase( - request: protos.google.firestore.admin.v1.ICreateDatabaseRequest, - options: CallOptions, - callback: Callback< - LROperation< - protos.google.firestore.admin.v1.IDatabase, - protos.google.firestore.admin.v1.ICreateDatabaseMetadata - >, - protos.google.longrunning.IOperation | null | undefined, - {} | null | undefined - > - ): void; + request: protos.google.firestore.admin.v1.ICreateDatabaseRequest, + options: CallOptions, + callback: Callback< + LROperation, + protos.google.longrunning.IOperation|null|undefined, + {}|null|undefined>): void; createDatabase( - request: protos.google.firestore.admin.v1.ICreateDatabaseRequest, - callback: Callback< - LROperation< - protos.google.firestore.admin.v1.IDatabase, - protos.google.firestore.admin.v1.ICreateDatabaseMetadata - >, - protos.google.longrunning.IOperation | null | undefined, - {} | null | undefined - > - ): void; + request: protos.google.firestore.admin.v1.ICreateDatabaseRequest, + callback: Callback< + LROperation, + protos.google.longrunning.IOperation|null|undefined, + {}|null|undefined>): void; createDatabase( - request?: protos.google.firestore.admin.v1.ICreateDatabaseRequest, - optionsOrCallback?: - | CallOptions - | Callback< - LROperation< - protos.google.firestore.admin.v1.IDatabase, - protos.google.firestore.admin.v1.ICreateDatabaseMetadata - >, - protos.google.longrunning.IOperation | null | undefined, - {} | null | undefined - >, - callback?: Callback< - LROperation< - protos.google.firestore.admin.v1.IDatabase, - protos.google.firestore.admin.v1.ICreateDatabaseMetadata - >, - protos.google.longrunning.IOperation | null | undefined, - {} | null | undefined - > - ): Promise< - [ - LROperation< - protos.google.firestore.admin.v1.IDatabase, - protos.google.firestore.admin.v1.ICreateDatabaseMetadata - >, - protos.google.longrunning.IOperation | undefined, - {} | undefined, - ] - > | void { + request?: protos.google.firestore.admin.v1.ICreateDatabaseRequest, + optionsOrCallback?: CallOptions|Callback< + LROperation, + protos.google.longrunning.IOperation|null|undefined, + {}|null|undefined>, + callback?: Callback< + LROperation, + protos.google.longrunning.IOperation|null|undefined, + {}|null|undefined>): + Promise<[ + LROperation, + protos.google.longrunning.IOperation|undefined, {}|undefined + ]>|void { request = request || {}; let options: CallOptions; if (typeof optionsOrCallback === 'function' && callback === undefined) { callback = optionsOrCallback; options = {}; - } else { + } + else { options = optionsOrCallback as CallOptions; } options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - options.otherArgs.headers['x-goog-request-params'] = - this._gaxModule.routingHeader.fromParams({ - parent: request.parent ?? '', - }); - this.initialize(); - return this.innerApiCalls.createDatabase(request, options, callback); + options.otherArgs.headers[ + 'x-goog-request-params' + ] = this._gaxModule.routingHeader.fromParams({ + 'parent': request.parent ?? '', + }); + this.initialize().catch(err => {throw err}); + const wrappedCallback: Callback< + LROperation, + protos.google.longrunning.IOperation|null|undefined, + {}|null|undefined>|undefined = callback + ? (error, response, rawResponse, _) => { + this._log.info('createDatabase response %j', rawResponse); + callback!(error, response, rawResponse, _); // We verified callback above. + } + : undefined; + this._log.info('createDatabase request %j', request); + return this.innerApiCalls.createDatabase(request, options, wrappedCallback) + ?.then(([response, rawResponse, _]: [ + LROperation, + protos.google.longrunning.IOperation|undefined, {}|undefined + ]) => { + this._log.info('createDatabase response %j', rawResponse); + return [response, rawResponse, _]; + }); } - /** - * Check the status of the long running operation returned by `createDatabase()`. - * @param {String} name - * The operation name that will be passed. - * @returns {Promise} - The promise which resolves to an object. - * The decoded operation object has result and metadata field to get information from. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#long-running-operations | documentation } - * for more details and examples. - * @example - * region_tag:firestore_v1_generated_FirestoreAdmin_CreateDatabase_async - */ - async checkCreateDatabaseProgress( - name: string - ): Promise< - LROperation< - protos.google.firestore.admin.v1.Database, - protos.google.firestore.admin.v1.CreateDatabaseMetadata - > - > { - const request = - new this._gaxModule.operationsProtos.google.longrunning.GetOperationRequest( - {name} - ); +/** + * Check the status of the long running operation returned by `createDatabase()`. + * @param {String} name + * The operation name that will be passed. + * @returns {Promise} - The promise which resolves to an object. + * The decoded operation object has result and metadata field to get information from. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#long-running-operations | documentation } + * for more details and examples. + * @example + * region_tag:firestore_v1_generated_FirestoreAdmin_CreateDatabase_async + */ + async checkCreateDatabaseProgress(name: string): Promise>{ + this._log.info('createDatabase long-running'); + const request = new this._gaxModule.operationsProtos.google.longrunning.GetOperationRequest({name}); const [operation] = await this.operationsClient.getOperation(request); - const decodeOperation = new this._gaxModule.Operation( - operation, - this.descriptors.longrunning.createDatabase, - this._gaxModule.createDefaultBackoffSettings() - ); - return decodeOperation as LROperation< - protos.google.firestore.admin.v1.Database, - protos.google.firestore.admin.v1.CreateDatabaseMetadata - >; + const decodeOperation = new this._gaxModule.Operation(operation, this.descriptors.longrunning.createDatabase, this._gaxModule.createDefaultBackoffSettings()); + return decodeOperation as LROperation; } - /** - * Updates a database. - * - * @param {Object} request - * The request object that will be sent. - * @param {google.firestore.admin.v1.Database} request.database - * Required. The database to update. - * @param {google.protobuf.FieldMask} request.updateMask - * The list of fields to be updated. - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Promise} - The promise which resolves to an array. - * The first element of the array is an object representing - * a long running operation. Its `promise()` method returns a promise - * you can `await` for. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#long-running-operations | documentation } - * for more details and examples. - * @example - * region_tag:firestore_v1_generated_FirestoreAdmin_UpdateDatabase_async - */ +/** + * Updates a database. + * + * @param {Object} request + * The request object that will be sent. + * @param {google.firestore.admin.v1.Database} request.database + * Required. The database to update. + * @param {google.protobuf.FieldMask} request.updateMask + * The list of fields to be updated. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is an object representing + * a long running operation. Its `promise()` method returns a promise + * you can `await` for. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#long-running-operations | documentation } + * for more details and examples. + * @example + * region_tag:firestore_v1_generated_FirestoreAdmin_UpdateDatabase_async + */ updateDatabase( - request?: protos.google.firestore.admin.v1.IUpdateDatabaseRequest, - options?: CallOptions - ): Promise< - [ - LROperation< - protos.google.firestore.admin.v1.IDatabase, - protos.google.firestore.admin.v1.IUpdateDatabaseMetadata - >, - protos.google.longrunning.IOperation | undefined, - {} | undefined, - ] - >; + request?: protos.google.firestore.admin.v1.IUpdateDatabaseRequest, + options?: CallOptions): + Promise<[ + LROperation, + protos.google.longrunning.IOperation|undefined, {}|undefined + ]>; updateDatabase( - request: protos.google.firestore.admin.v1.IUpdateDatabaseRequest, - options: CallOptions, - callback: Callback< - LROperation< - protos.google.firestore.admin.v1.IDatabase, - protos.google.firestore.admin.v1.IUpdateDatabaseMetadata - >, - protos.google.longrunning.IOperation | null | undefined, - {} | null | undefined - > - ): void; + request: protos.google.firestore.admin.v1.IUpdateDatabaseRequest, + options: CallOptions, + callback: Callback< + LROperation, + protos.google.longrunning.IOperation|null|undefined, + {}|null|undefined>): void; updateDatabase( - request: protos.google.firestore.admin.v1.IUpdateDatabaseRequest, - callback: Callback< - LROperation< - protos.google.firestore.admin.v1.IDatabase, - protos.google.firestore.admin.v1.IUpdateDatabaseMetadata - >, - protos.google.longrunning.IOperation | null | undefined, - {} | null | undefined - > - ): void; + request: protos.google.firestore.admin.v1.IUpdateDatabaseRequest, + callback: Callback< + LROperation, + protos.google.longrunning.IOperation|null|undefined, + {}|null|undefined>): void; updateDatabase( - request?: protos.google.firestore.admin.v1.IUpdateDatabaseRequest, - optionsOrCallback?: - | CallOptions - | Callback< - LROperation< - protos.google.firestore.admin.v1.IDatabase, - protos.google.firestore.admin.v1.IUpdateDatabaseMetadata - >, - protos.google.longrunning.IOperation | null | undefined, - {} | null | undefined - >, - callback?: Callback< - LROperation< - protos.google.firestore.admin.v1.IDatabase, - protos.google.firestore.admin.v1.IUpdateDatabaseMetadata - >, - protos.google.longrunning.IOperation | null | undefined, - {} | null | undefined - > - ): Promise< - [ - LROperation< - protos.google.firestore.admin.v1.IDatabase, - protos.google.firestore.admin.v1.IUpdateDatabaseMetadata - >, - protos.google.longrunning.IOperation | undefined, - {} | undefined, - ] - > | void { + request?: protos.google.firestore.admin.v1.IUpdateDatabaseRequest, + optionsOrCallback?: CallOptions|Callback< + LROperation, + protos.google.longrunning.IOperation|null|undefined, + {}|null|undefined>, + callback?: Callback< + LROperation, + protos.google.longrunning.IOperation|null|undefined, + {}|null|undefined>): + Promise<[ + LROperation, + protos.google.longrunning.IOperation|undefined, {}|undefined + ]>|void { request = request || {}; let options: CallOptions; if (typeof optionsOrCallback === 'function' && callback === undefined) { callback = optionsOrCallback; options = {}; - } else { + } + else { options = optionsOrCallback as CallOptions; } options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - options.otherArgs.headers['x-goog-request-params'] = - this._gaxModule.routingHeader.fromParams({ - 'database.name': request.database!.name ?? '', - }); - this.initialize(); - return this.innerApiCalls.updateDatabase(request, options, callback); + options.otherArgs.headers[ + 'x-goog-request-params' + ] = this._gaxModule.routingHeader.fromParams({ + 'database.name': request.database!.name ?? '', + }); + this.initialize().catch(err => {throw err}); + const wrappedCallback: Callback< + LROperation, + protos.google.longrunning.IOperation|null|undefined, + {}|null|undefined>|undefined = callback + ? (error, response, rawResponse, _) => { + this._log.info('updateDatabase response %j', rawResponse); + callback!(error, response, rawResponse, _); // We verified callback above. + } + : undefined; + this._log.info('updateDatabase request %j', request); + return this.innerApiCalls.updateDatabase(request, options, wrappedCallback) + ?.then(([response, rawResponse, _]: [ + LROperation, + protos.google.longrunning.IOperation|undefined, {}|undefined + ]) => { + this._log.info('updateDatabase response %j', rawResponse); + return [response, rawResponse, _]; + }); } - /** - * Check the status of the long running operation returned by `updateDatabase()`. - * @param {String} name - * The operation name that will be passed. - * @returns {Promise} - The promise which resolves to an object. - * The decoded operation object has result and metadata field to get information from. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#long-running-operations | documentation } - * for more details and examples. - * @example - * region_tag:firestore_v1_generated_FirestoreAdmin_UpdateDatabase_async - */ - async checkUpdateDatabaseProgress( - name: string - ): Promise< - LROperation< - protos.google.firestore.admin.v1.Database, - protos.google.firestore.admin.v1.UpdateDatabaseMetadata - > - > { - const request = - new this._gaxModule.operationsProtos.google.longrunning.GetOperationRequest( - {name} - ); +/** + * Check the status of the long running operation returned by `updateDatabase()`. + * @param {String} name + * The operation name that will be passed. + * @returns {Promise} - The promise which resolves to an object. + * The decoded operation object has result and metadata field to get information from. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#long-running-operations | documentation } + * for more details and examples. + * @example + * region_tag:firestore_v1_generated_FirestoreAdmin_UpdateDatabase_async + */ + async checkUpdateDatabaseProgress(name: string): Promise>{ + this._log.info('updateDatabase long-running'); + const request = new this._gaxModule.operationsProtos.google.longrunning.GetOperationRequest({name}); const [operation] = await this.operationsClient.getOperation(request); - const decodeOperation = new this._gaxModule.Operation( - operation, - this.descriptors.longrunning.updateDatabase, - this._gaxModule.createDefaultBackoffSettings() - ); - return decodeOperation as LROperation< - protos.google.firestore.admin.v1.Database, - protos.google.firestore.admin.v1.UpdateDatabaseMetadata - >; + const decodeOperation = new this._gaxModule.Operation(operation, this.descriptors.longrunning.updateDatabase, this._gaxModule.createDefaultBackoffSettings()); + return decodeOperation as LROperation; } - /** - * Deletes a database. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.name - * Required. A name of the form - * `projects/{project_id}/databases/{database_id}` - * @param {string} request.etag - * The current etag of the Database. - * If an etag is provided and does not match the current etag of the database, - * deletion will be blocked and a FAILED_PRECONDITION error will be returned. - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Promise} - The promise which resolves to an array. - * The first element of the array is an object representing - * a long running operation. Its `promise()` method returns a promise - * you can `await` for. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#long-running-operations | documentation } - * for more details and examples. - * @example - * region_tag:firestore_v1_generated_FirestoreAdmin_DeleteDatabase_async - */ +/** + * Deletes a database. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.name + * Required. A name of the form + * `projects/{project_id}/databases/{database_id}` + * @param {string} request.etag + * The current etag of the Database. + * If an etag is provided and does not match the current etag of the database, + * deletion will be blocked and a FAILED_PRECONDITION error will be returned. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is an object representing + * a long running operation. Its `promise()` method returns a promise + * you can `await` for. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#long-running-operations | documentation } + * for more details and examples. + * @example + * region_tag:firestore_v1_generated_FirestoreAdmin_DeleteDatabase_async + */ deleteDatabase( - request?: protos.google.firestore.admin.v1.IDeleteDatabaseRequest, - options?: CallOptions - ): Promise< - [ - LROperation< - protos.google.firestore.admin.v1.IDatabase, - protos.google.firestore.admin.v1.IDeleteDatabaseMetadata - >, - protos.google.longrunning.IOperation | undefined, - {} | undefined, - ] - >; + request?: protos.google.firestore.admin.v1.IDeleteDatabaseRequest, + options?: CallOptions): + Promise<[ + LROperation, + protos.google.longrunning.IOperation|undefined, {}|undefined + ]>; deleteDatabase( - request: protos.google.firestore.admin.v1.IDeleteDatabaseRequest, - options: CallOptions, - callback: Callback< - LROperation< - protos.google.firestore.admin.v1.IDatabase, - protos.google.firestore.admin.v1.IDeleteDatabaseMetadata - >, - protos.google.longrunning.IOperation | null | undefined, - {} | null | undefined - > - ): void; + request: protos.google.firestore.admin.v1.IDeleteDatabaseRequest, + options: CallOptions, + callback: Callback< + LROperation, + protos.google.longrunning.IOperation|null|undefined, + {}|null|undefined>): void; deleteDatabase( - request: protos.google.firestore.admin.v1.IDeleteDatabaseRequest, - callback: Callback< - LROperation< - protos.google.firestore.admin.v1.IDatabase, - protos.google.firestore.admin.v1.IDeleteDatabaseMetadata - >, - protos.google.longrunning.IOperation | null | undefined, - {} | null | undefined - > - ): void; + request: protos.google.firestore.admin.v1.IDeleteDatabaseRequest, + callback: Callback< + LROperation, + protos.google.longrunning.IOperation|null|undefined, + {}|null|undefined>): void; deleteDatabase( - request?: protos.google.firestore.admin.v1.IDeleteDatabaseRequest, - optionsOrCallback?: - | CallOptions - | Callback< - LROperation< - protos.google.firestore.admin.v1.IDatabase, - protos.google.firestore.admin.v1.IDeleteDatabaseMetadata - >, - protos.google.longrunning.IOperation | null | undefined, - {} | null | undefined - >, - callback?: Callback< - LROperation< - protos.google.firestore.admin.v1.IDatabase, - protos.google.firestore.admin.v1.IDeleteDatabaseMetadata - >, - protos.google.longrunning.IOperation | null | undefined, - {} | null | undefined - > - ): Promise< - [ - LROperation< - protos.google.firestore.admin.v1.IDatabase, - protos.google.firestore.admin.v1.IDeleteDatabaseMetadata - >, - protos.google.longrunning.IOperation | undefined, - {} | undefined, - ] - > | void { + request?: protos.google.firestore.admin.v1.IDeleteDatabaseRequest, + optionsOrCallback?: CallOptions|Callback< + LROperation, + protos.google.longrunning.IOperation|null|undefined, + {}|null|undefined>, + callback?: Callback< + LROperation, + protos.google.longrunning.IOperation|null|undefined, + {}|null|undefined>): + Promise<[ + LROperation, + protos.google.longrunning.IOperation|undefined, {}|undefined + ]>|void { request = request || {}; let options: CallOptions; if (typeof optionsOrCallback === 'function' && callback === undefined) { callback = optionsOrCallback; options = {}; - } else { + } + else { options = optionsOrCallback as CallOptions; } options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - options.otherArgs.headers['x-goog-request-params'] = - this._gaxModule.routingHeader.fromParams({ - name: request.name ?? '', - }); - this.initialize(); - return this.innerApiCalls.deleteDatabase(request, options, callback); - } - /** - * Check the status of the long running operation returned by `deleteDatabase()`. - * @param {String} name - * The operation name that will be passed. - * @returns {Promise} - The promise which resolves to an object. - * The decoded operation object has result and metadata field to get information from. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#long-running-operations | documentation } - * for more details and examples. - * @example - * region_tag:firestore_v1_generated_FirestoreAdmin_DeleteDatabase_async - */ - async checkDeleteDatabaseProgress( - name: string - ): Promise< - LROperation< - protos.google.firestore.admin.v1.Database, - protos.google.firestore.admin.v1.DeleteDatabaseMetadata - > - > { - const request = - new this._gaxModule.operationsProtos.google.longrunning.GetOperationRequest( - {name} - ); - const [operation] = await this.operationsClient.getOperation(request); - const decodeOperation = new this._gaxModule.Operation( - operation, - this.descriptors.longrunning.deleteDatabase, - this._gaxModule.createDefaultBackoffSettings() - ); - return decodeOperation as LROperation< - protos.google.firestore.admin.v1.Database, - protos.google.firestore.admin.v1.DeleteDatabaseMetadata - >; + options.otherArgs.headers[ + 'x-goog-request-params' + ] = this._gaxModule.routingHeader.fromParams({ + 'name': request.name ?? '', + }); + this.initialize().catch(err => {throw err}); + const wrappedCallback: Callback< + LROperation, + protos.google.longrunning.IOperation|null|undefined, + {}|null|undefined>|undefined = callback + ? (error, response, rawResponse, _) => { + this._log.info('deleteDatabase response %j', rawResponse); + callback!(error, response, rawResponse, _); // We verified callback above. + } + : undefined; + this._log.info('deleteDatabase request %j', request); + return this.innerApiCalls.deleteDatabase(request, options, wrappedCallback) + ?.then(([response, rawResponse, _]: [ + LROperation, + protos.google.longrunning.IOperation|undefined, {}|undefined + ]) => { + this._log.info('deleteDatabase response %j', rawResponse); + return [response, rawResponse, _]; + }); } - /** - * Creates a new database by restoring from an existing backup. - * - * The new database must be in the same cloud region or multi-region location - * as the existing backup. This behaves similar to - * {@link protos.google.firestore.admin.v1.FirestoreAdmin.CreateDatabase|FirestoreAdmin.CreateDatabase} - * except instead of creating a new empty database, a new database is created - * with the database type, index configuration, and documents from an existing - * backup. - * - * The {@link protos.google.longrunning.Operation|long-running operation} can be used to - * track the progress of the restore, with the Operation's - * {@link protos.google.longrunning.Operation.metadata|metadata} field type being the - * {@link protos.google.firestore.admin.v1.RestoreDatabaseMetadata|RestoreDatabaseMetadata}. - * The {@link protos.google.longrunning.Operation.response|response} type is the - * {@link protos.google.firestore.admin.v1.Database|Database} if the restore was - * successful. The new database is not readable or writeable until the LRO has - * completed. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.parent - * Required. The project to restore the database in. Format is - * `projects/{project_id}`. - * @param {string} request.databaseId - * Required. The ID to use for the database, which will become the final - * component of the database's resource name. This database ID must not be - * associated with an existing database. - * - * This value should be 4-63 characters. Valid characters are /{@link protos.0-9|a-z}-/ - * with first character a letter and the last a letter or a number. Must not - * be UUID-like /[0-9a-f]{8}(-[0-9a-f]{4}){3}-[0-9a-f]{12}/. - * - * "(default)" database ID is also valid. - * @param {string} request.backup - * Required. Backup to restore from. Must be from the same project as the - * parent. - * - * The restored database will be created in the same location as the source - * backup. - * - * Format is: `projects/{project_id}/locations/{location}/backups/{backup}` - * @param {google.firestore.admin.v1.Database.EncryptionConfig} [request.encryptionConfig] - * Optional. Encryption configuration for the restored database. - * - * If this field is not specified, the restored database will use - * the same encryption configuration as the backup, namely - * {@link protos.google.firestore.admin.v1.Database.EncryptionConfig.use_source_encryption|use_source_encryption}. - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Promise} - The promise which resolves to an array. - * The first element of the array is an object representing - * a long running operation. Its `promise()` method returns a promise - * you can `await` for. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#long-running-operations | documentation } - * for more details and examples. - * @example - * region_tag:firestore_v1_generated_FirestoreAdmin_RestoreDatabase_async - */ +/** + * Check the status of the long running operation returned by `deleteDatabase()`. + * @param {String} name + * The operation name that will be passed. + * @returns {Promise} - The promise which resolves to an object. + * The decoded operation object has result and metadata field to get information from. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#long-running-operations | documentation } + * for more details and examples. + * @example + * region_tag:firestore_v1_generated_FirestoreAdmin_DeleteDatabase_async + */ + async checkDeleteDatabaseProgress(name: string): Promise>{ + this._log.info('deleteDatabase long-running'); + const request = new this._gaxModule.operationsProtos.google.longrunning.GetOperationRequest({name}); + const [operation] = await this.operationsClient.getOperation(request); + const decodeOperation = new this._gaxModule.Operation(operation, this.descriptors.longrunning.deleteDatabase, this._gaxModule.createDefaultBackoffSettings()); + return decodeOperation as LROperation; + } +/** + * Creates a new database by restoring from an existing backup. + * + * The new database must be in the same cloud region or multi-region location + * as the existing backup. This behaves similar to + * {@link protos.google.firestore.admin.v1.FirestoreAdmin.CreateDatabase|FirestoreAdmin.CreateDatabase} + * except instead of creating a new empty database, a new database is created + * with the database type, index configuration, and documents from an existing + * backup. + * + * The {@link protos.google.longrunning.Operation|long-running operation} can be used to + * track the progress of the restore, with the Operation's + * {@link protos.google.longrunning.Operation.metadata|metadata} field type being the + * {@link protos.google.firestore.admin.v1.RestoreDatabaseMetadata|RestoreDatabaseMetadata}. + * The {@link protos.google.longrunning.Operation.response|response} type is the + * {@link protos.google.firestore.admin.v1.Database|Database} if the restore was + * successful. The new database is not readable or writeable until the LRO has + * completed. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.parent + * Required. The project to restore the database in. Format is + * `projects/{project_id}`. + * @param {string} request.databaseId + * Required. The ID to use for the database, which will become the final + * component of the database's resource name. This database ID must not be + * associated with an existing database. + * + * This value should be 4-63 characters. Valid characters are /{@link protos.0-9|a-z}-/ + * with first character a letter and the last a letter or a number. Must not + * be UUID-like /[0-9a-f]{8}(-[0-9a-f]{4}){3}-[0-9a-f]{12}/. + * + * "(default)" database ID is also valid. + * @param {string} request.backup + * Required. Backup to restore from. Must be from the same project as the + * parent. + * + * The restored database will be created in the same location as the source + * backup. + * + * Format is: `projects/{project_id}/locations/{location}/backups/{backup}` + * @param {google.firestore.admin.v1.Database.EncryptionConfig} [request.encryptionConfig] + * Optional. Encryption configuration for the restored database. + * + * If this field is not specified, the restored database will use + * the same encryption configuration as the backup, namely + * {@link protos.google.firestore.admin.v1.Database.EncryptionConfig.use_source_encryption|use_source_encryption}. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is an object representing + * a long running operation. Its `promise()` method returns a promise + * you can `await` for. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#long-running-operations | documentation } + * for more details and examples. + * @example + * region_tag:firestore_v1_generated_FirestoreAdmin_RestoreDatabase_async + */ restoreDatabase( - request?: protos.google.firestore.admin.v1.IRestoreDatabaseRequest, - options?: CallOptions - ): Promise< - [ - LROperation< - protos.google.firestore.admin.v1.IDatabase, - protos.google.firestore.admin.v1.IRestoreDatabaseMetadata - >, - protos.google.longrunning.IOperation | undefined, - {} | undefined, - ] - >; + request?: protos.google.firestore.admin.v1.IRestoreDatabaseRequest, + options?: CallOptions): + Promise<[ + LROperation, + protos.google.longrunning.IOperation|undefined, {}|undefined + ]>; restoreDatabase( - request: protos.google.firestore.admin.v1.IRestoreDatabaseRequest, - options: CallOptions, - callback: Callback< - LROperation< - protos.google.firestore.admin.v1.IDatabase, - protos.google.firestore.admin.v1.IRestoreDatabaseMetadata - >, - protos.google.longrunning.IOperation | null | undefined, - {} | null | undefined - > - ): void; + request: protos.google.firestore.admin.v1.IRestoreDatabaseRequest, + options: CallOptions, + callback: Callback< + LROperation, + protos.google.longrunning.IOperation|null|undefined, + {}|null|undefined>): void; restoreDatabase( - request: protos.google.firestore.admin.v1.IRestoreDatabaseRequest, - callback: Callback< - LROperation< - protos.google.firestore.admin.v1.IDatabase, - protos.google.firestore.admin.v1.IRestoreDatabaseMetadata - >, - protos.google.longrunning.IOperation | null | undefined, - {} | null | undefined - > - ): void; + request: protos.google.firestore.admin.v1.IRestoreDatabaseRequest, + callback: Callback< + LROperation, + protos.google.longrunning.IOperation|null|undefined, + {}|null|undefined>): void; restoreDatabase( - request?: protos.google.firestore.admin.v1.IRestoreDatabaseRequest, - optionsOrCallback?: - | CallOptions - | Callback< - LROperation< - protos.google.firestore.admin.v1.IDatabase, - protos.google.firestore.admin.v1.IRestoreDatabaseMetadata - >, - protos.google.longrunning.IOperation | null | undefined, - {} | null | undefined - >, - callback?: Callback< - LROperation< - protos.google.firestore.admin.v1.IDatabase, - protos.google.firestore.admin.v1.IRestoreDatabaseMetadata - >, - protos.google.longrunning.IOperation | null | undefined, - {} | null | undefined - > - ): Promise< - [ - LROperation< - protos.google.firestore.admin.v1.IDatabase, - protos.google.firestore.admin.v1.IRestoreDatabaseMetadata - >, - protos.google.longrunning.IOperation | undefined, - {} | undefined, - ] - > | void { + request?: protos.google.firestore.admin.v1.IRestoreDatabaseRequest, + optionsOrCallback?: CallOptions|Callback< + LROperation, + protos.google.longrunning.IOperation|null|undefined, + {}|null|undefined>, + callback?: Callback< + LROperation, + protos.google.longrunning.IOperation|null|undefined, + {}|null|undefined>): + Promise<[ + LROperation, + protos.google.longrunning.IOperation|undefined, {}|undefined + ]>|void { request = request || {}; let options: CallOptions; if (typeof optionsOrCallback === 'function' && callback === undefined) { callback = optionsOrCallback; options = {}; - } else { + } + else { options = optionsOrCallback as CallOptions; } options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - options.otherArgs.headers['x-goog-request-params'] = - this._gaxModule.routingHeader.fromParams({ - parent: request.parent ?? '', - }); - this.initialize(); - return this.innerApiCalls.restoreDatabase(request, options, callback); + options.otherArgs.headers[ + 'x-goog-request-params' + ] = this._gaxModule.routingHeader.fromParams({ + 'parent': request.parent ?? '', + }); + this.initialize().catch(err => {throw err}); + const wrappedCallback: Callback< + LROperation, + protos.google.longrunning.IOperation|null|undefined, + {}|null|undefined>|undefined = callback + ? (error, response, rawResponse, _) => { + this._log.info('restoreDatabase response %j', rawResponse); + callback!(error, response, rawResponse, _); // We verified callback above. + } + : undefined; + this._log.info('restoreDatabase request %j', request); + return this.innerApiCalls.restoreDatabase(request, options, wrappedCallback) + ?.then(([response, rawResponse, _]: [ + LROperation, + protos.google.longrunning.IOperation|undefined, {}|undefined + ]) => { + this._log.info('restoreDatabase response %j', rawResponse); + return [response, rawResponse, _]; + }); } - /** - * Check the status of the long running operation returned by `restoreDatabase()`. - * @param {String} name - * The operation name that will be passed. - * @returns {Promise} - The promise which resolves to an object. - * The decoded operation object has result and metadata field to get information from. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#long-running-operations | documentation } - * for more details and examples. - * @example - * region_tag:firestore_v1_generated_FirestoreAdmin_RestoreDatabase_async - */ - async checkRestoreDatabaseProgress( - name: string - ): Promise< - LROperation< - protos.google.firestore.admin.v1.Database, - protos.google.firestore.admin.v1.RestoreDatabaseMetadata - > - > { - const request = - new this._gaxModule.operationsProtos.google.longrunning.GetOperationRequest( - {name} - ); +/** + * Check the status of the long running operation returned by `restoreDatabase()`. + * @param {String} name + * The operation name that will be passed. + * @returns {Promise} - The promise which resolves to an object. + * The decoded operation object has result and metadata field to get information from. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#long-running-operations | documentation } + * for more details and examples. + * @example + * region_tag:firestore_v1_generated_FirestoreAdmin_RestoreDatabase_async + */ + async checkRestoreDatabaseProgress(name: string): Promise>{ + this._log.info('restoreDatabase long-running'); + const request = new this._gaxModule.operationsProtos.google.longrunning.GetOperationRequest({name}); const [operation] = await this.operationsClient.getOperation(request); - const decodeOperation = new this._gaxModule.Operation( - operation, - this.descriptors.longrunning.restoreDatabase, - this._gaxModule.createDefaultBackoffSettings() - ); - return decodeOperation as LROperation< - protos.google.firestore.admin.v1.Database, - protos.google.firestore.admin.v1.RestoreDatabaseMetadata - >; + const decodeOperation = new this._gaxModule.Operation(operation, this.descriptors.longrunning.restoreDatabase, this._gaxModule.createDefaultBackoffSettings()); + return decodeOperation as LROperation; } - /** - * Lists composite indexes. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.parent - * Required. A parent name of the form - * `projects/{project_id}/databases/{database_id}/collectionGroups/{collection_id}` - * @param {string} request.filter - * The filter to apply to list results. - * @param {number} request.pageSize - * The number of results to return. - * @param {string} request.pageToken - * A page token, returned from a previous call to - * {@link protos.google.firestore.admin.v1.FirestoreAdmin.ListIndexes|FirestoreAdmin.ListIndexes}, - * that may be used to get the next page of results. - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Promise} - The promise which resolves to an array. - * The first element of the array is Array of {@link protos.google.firestore.admin.v1.Index|Index}. - * The client library will perform auto-pagination by default: it will call the API as many - * times as needed and will merge results from all the pages into this array. - * Note that it can affect your quota. - * We recommend using `listIndexesAsync()` - * method described below for async iteration which you can stop as needed. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#auto-pagination | documentation } - * for more details and examples. - */ + /** + * Lists composite indexes. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.parent + * Required. A parent name of the form + * `projects/{project_id}/databases/{database_id}/collectionGroups/{collection_id}` + * @param {string} request.filter + * The filter to apply to list results. + * @param {number} request.pageSize + * The number of results to return. + * @param {string} request.pageToken + * A page token, returned from a previous call to + * {@link protos.google.firestore.admin.v1.FirestoreAdmin.ListIndexes|FirestoreAdmin.ListIndexes}, + * that may be used to get the next page of results. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is Array of {@link protos.google.firestore.admin.v1.Index|Index}. + * The client library will perform auto-pagination by default: it will call the API as many + * times as needed and will merge results from all the pages into this array. + * Note that it can affect your quota. + * We recommend using `listIndexesAsync()` + * method described below for async iteration which you can stop as needed. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#auto-pagination | documentation } + * for more details and examples. + */ listIndexes( - request?: protos.google.firestore.admin.v1.IListIndexesRequest, - options?: CallOptions - ): Promise< - [ - protos.google.firestore.admin.v1.IIndex[], - protos.google.firestore.admin.v1.IListIndexesRequest | null, - protos.google.firestore.admin.v1.IListIndexesResponse, - ] - >; + request?: protos.google.firestore.admin.v1.IListIndexesRequest, + options?: CallOptions): + Promise<[ + protos.google.firestore.admin.v1.IIndex[], + protos.google.firestore.admin.v1.IListIndexesRequest|null, + protos.google.firestore.admin.v1.IListIndexesResponse + ]>; listIndexes( - request: protos.google.firestore.admin.v1.IListIndexesRequest, - options: CallOptions, - callback: PaginationCallback< - protos.google.firestore.admin.v1.IListIndexesRequest, - protos.google.firestore.admin.v1.IListIndexesResponse | null | undefined, - protos.google.firestore.admin.v1.IIndex - > - ): void; + request: protos.google.firestore.admin.v1.IListIndexesRequest, + options: CallOptions, + callback: PaginationCallback< + protos.google.firestore.admin.v1.IListIndexesRequest, + protos.google.firestore.admin.v1.IListIndexesResponse|null|undefined, + protos.google.firestore.admin.v1.IIndex>): void; listIndexes( - request: protos.google.firestore.admin.v1.IListIndexesRequest, - callback: PaginationCallback< - protos.google.firestore.admin.v1.IListIndexesRequest, - protos.google.firestore.admin.v1.IListIndexesResponse | null | undefined, - protos.google.firestore.admin.v1.IIndex - > - ): void; + request: protos.google.firestore.admin.v1.IListIndexesRequest, + callback: PaginationCallback< + protos.google.firestore.admin.v1.IListIndexesRequest, + protos.google.firestore.admin.v1.IListIndexesResponse|null|undefined, + protos.google.firestore.admin.v1.IIndex>): void; listIndexes( - request?: protos.google.firestore.admin.v1.IListIndexesRequest, - optionsOrCallback?: - | CallOptions - | PaginationCallback< + request?: protos.google.firestore.admin.v1.IListIndexesRequest, + optionsOrCallback?: CallOptions|PaginationCallback< protos.google.firestore.admin.v1.IListIndexesRequest, - | protos.google.firestore.admin.v1.IListIndexesResponse - | null - | undefined, - protos.google.firestore.admin.v1.IIndex - >, - callback?: PaginationCallback< - protos.google.firestore.admin.v1.IListIndexesRequest, - protos.google.firestore.admin.v1.IListIndexesResponse | null | undefined, - protos.google.firestore.admin.v1.IIndex - > - ): Promise< - [ - protos.google.firestore.admin.v1.IIndex[], - protos.google.firestore.admin.v1.IListIndexesRequest | null, - protos.google.firestore.admin.v1.IListIndexesResponse, - ] - > | void { + protos.google.firestore.admin.v1.IListIndexesResponse|null|undefined, + protos.google.firestore.admin.v1.IIndex>, + callback?: PaginationCallback< + protos.google.firestore.admin.v1.IListIndexesRequest, + protos.google.firestore.admin.v1.IListIndexesResponse|null|undefined, + protos.google.firestore.admin.v1.IIndex>): + Promise<[ + protos.google.firestore.admin.v1.IIndex[], + protos.google.firestore.admin.v1.IListIndexesRequest|null, + protos.google.firestore.admin.v1.IListIndexesResponse + ]>|void { request = request || {}; let options: CallOptions; if (typeof optionsOrCallback === 'function' && callback === undefined) { callback = optionsOrCallback; options = {}; - } else { + } + else { options = optionsOrCallback as CallOptions; } options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - options.otherArgs.headers['x-goog-request-params'] = - this._gaxModule.routingHeader.fromParams({ - parent: request.parent ?? '', + options.otherArgs.headers[ + 'x-goog-request-params' + ] = this._gaxModule.routingHeader.fromParams({ + 'parent': request.parent ?? '', + }); + this.initialize().catch(err => {throw err}); + const wrappedCallback: PaginationCallback< + protos.google.firestore.admin.v1.IListIndexesRequest, + protos.google.firestore.admin.v1.IListIndexesResponse|null|undefined, + protos.google.firestore.admin.v1.IIndex>|undefined = callback + ? (error, values, nextPageRequest, rawResponse) => { + this._log.info('listIndexes values %j', values); + callback!(error, values, nextPageRequest, rawResponse); // We verified callback above. + } + : undefined; + this._log.info('listIndexes request %j', request); + return this.innerApiCalls + .listIndexes(request, options, wrappedCallback) + ?.then(([response, input, output]: [ + protos.google.firestore.admin.v1.IIndex[], + protos.google.firestore.admin.v1.IListIndexesRequest|null, + protos.google.firestore.admin.v1.IListIndexesResponse + ]) => { + this._log.info('listIndexes values %j', response); + return [response, input, output]; }); - this.initialize(); - return this.innerApiCalls.listIndexes(request, options, callback); } - /** - * Equivalent to `listIndexes`, but returns a NodeJS Stream object. - * @param {Object} request - * The request object that will be sent. - * @param {string} request.parent - * Required. A parent name of the form - * `projects/{project_id}/databases/{database_id}/collectionGroups/{collection_id}` - * @param {string} request.filter - * The filter to apply to list results. - * @param {number} request.pageSize - * The number of results to return. - * @param {string} request.pageToken - * A page token, returned from a previous call to - * {@link protos.google.firestore.admin.v1.FirestoreAdmin.ListIndexes|FirestoreAdmin.ListIndexes}, - * that may be used to get the next page of results. - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Stream} - * An object stream which emits an object representing {@link protos.google.firestore.admin.v1.Index|Index} on 'data' event. - * The client library will perform auto-pagination by default: it will call the API as many - * times as needed. Note that it can affect your quota. - * We recommend using `listIndexesAsync()` - * method described below for async iteration which you can stop as needed. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#auto-pagination | documentation } - * for more details and examples. - */ +/** + * Equivalent to `listIndexes`, but returns a NodeJS Stream object. + * @param {Object} request + * The request object that will be sent. + * @param {string} request.parent + * Required. A parent name of the form + * `projects/{project_id}/databases/{database_id}/collectionGroups/{collection_id}` + * @param {string} request.filter + * The filter to apply to list results. + * @param {number} request.pageSize + * The number of results to return. + * @param {string} request.pageToken + * A page token, returned from a previous call to + * {@link protos.google.firestore.admin.v1.FirestoreAdmin.ListIndexes|FirestoreAdmin.ListIndexes}, + * that may be used to get the next page of results. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Stream} + * An object stream which emits an object representing {@link protos.google.firestore.admin.v1.Index|Index} on 'data' event. + * The client library will perform auto-pagination by default: it will call the API as many + * times as needed. Note that it can affect your quota. + * We recommend using `listIndexesAsync()` + * method described below for async iteration which you can stop as needed. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#auto-pagination | documentation } + * for more details and examples. + */ listIndexesStream( - request?: protos.google.firestore.admin.v1.IListIndexesRequest, - options?: CallOptions - ): Transform { + request?: protos.google.firestore.admin.v1.IListIndexesRequest, + options?: CallOptions): + Transform{ request = request || {}; options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - options.otherArgs.headers['x-goog-request-params'] = - this._gaxModule.routingHeader.fromParams({ - parent: request.parent ?? '', - }); + options.otherArgs.headers[ + 'x-goog-request-params' + ] = this._gaxModule.routingHeader.fromParams({ + 'parent': request.parent ?? '', + }); const defaultCallSettings = this._defaults['listIndexes']; const callSettings = defaultCallSettings.merge(options); - this.initialize(); + this.initialize().catch(err => {throw err}); + this._log.info('listIndexes stream %j', request); return this.descriptors.page.listIndexes.createStream( this.innerApiCalls.listIndexes as GaxCall, request, @@ -3307,214 +3596,225 @@ export class FirestoreAdminClient { ); } - /** - * Equivalent to `listIndexes`, but returns an iterable object. - * - * `for`-`await`-`of` syntax is used with the iterable to get response elements on-demand. - * @param {Object} request - * The request object that will be sent. - * @param {string} request.parent - * Required. A parent name of the form - * `projects/{project_id}/databases/{database_id}/collectionGroups/{collection_id}` - * @param {string} request.filter - * The filter to apply to list results. - * @param {number} request.pageSize - * The number of results to return. - * @param {string} request.pageToken - * A page token, returned from a previous call to - * {@link protos.google.firestore.admin.v1.FirestoreAdmin.ListIndexes|FirestoreAdmin.ListIndexes}, - * that may be used to get the next page of results. - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Object} - * An iterable Object that allows {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols | async iteration }. - * When you iterate the returned iterable, each element will be an object representing - * {@link protos.google.firestore.admin.v1.Index|Index}. The API will be called under the hood as needed, once per the page, - * so you can stop the iteration when you don't need more results. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#auto-pagination | documentation } - * for more details and examples. - * @example - * region_tag:firestore_v1_generated_FirestoreAdmin_ListIndexes_async - */ +/** + * Equivalent to `listIndexes`, but returns an iterable object. + * + * `for`-`await`-`of` syntax is used with the iterable to get response elements on-demand. + * @param {Object} request + * The request object that will be sent. + * @param {string} request.parent + * Required. A parent name of the form + * `projects/{project_id}/databases/{database_id}/collectionGroups/{collection_id}` + * @param {string} request.filter + * The filter to apply to list results. + * @param {number} request.pageSize + * The number of results to return. + * @param {string} request.pageToken + * A page token, returned from a previous call to + * {@link protos.google.firestore.admin.v1.FirestoreAdmin.ListIndexes|FirestoreAdmin.ListIndexes}, + * that may be used to get the next page of results. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Object} + * An iterable Object that allows {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols | async iteration }. + * When you iterate the returned iterable, each element will be an object representing + * {@link protos.google.firestore.admin.v1.Index|Index}. The API will be called under the hood as needed, once per the page, + * so you can stop the iteration when you don't need more results. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#auto-pagination | documentation } + * for more details and examples. + * @example + * region_tag:firestore_v1_generated_FirestoreAdmin_ListIndexes_async + */ listIndexesAsync( - request?: protos.google.firestore.admin.v1.IListIndexesRequest, - options?: CallOptions - ): AsyncIterable { + request?: protos.google.firestore.admin.v1.IListIndexesRequest, + options?: CallOptions): + AsyncIterable{ request = request || {}; options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - options.otherArgs.headers['x-goog-request-params'] = - this._gaxModule.routingHeader.fromParams({ - parent: request.parent ?? '', - }); + options.otherArgs.headers[ + 'x-goog-request-params' + ] = this._gaxModule.routingHeader.fromParams({ + 'parent': request.parent ?? '', + }); const defaultCallSettings = this._defaults['listIndexes']; const callSettings = defaultCallSettings.merge(options); - this.initialize(); + this.initialize().catch(err => {throw err}); + this._log.info('listIndexes iterate %j', request); return this.descriptors.page.listIndexes.asyncIterate( this.innerApiCalls['listIndexes'] as GaxCall, request as {}, callSettings ) as AsyncIterable; } - /** - * Lists the field configuration and metadata for this database. - * - * Currently, - * {@link protos.google.firestore.admin.v1.FirestoreAdmin.ListFields|FirestoreAdmin.ListFields} - * only supports listing fields that have been explicitly overridden. To issue - * this query, call - * {@link protos.google.firestore.admin.v1.FirestoreAdmin.ListFields|FirestoreAdmin.ListFields} - * with the filter set to `indexConfig.usesAncestorConfig:false` or - * `ttlConfig:*`. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.parent - * Required. A parent name of the form - * `projects/{project_id}/databases/{database_id}/collectionGroups/{collection_id}` - * @param {string} request.filter - * The filter to apply to list results. Currently, - * {@link protos.google.firestore.admin.v1.FirestoreAdmin.ListFields|FirestoreAdmin.ListFields} - * only supports listing fields that have been explicitly overridden. To issue - * this query, call - * {@link protos.google.firestore.admin.v1.FirestoreAdmin.ListFields|FirestoreAdmin.ListFields} - * with a filter that includes `indexConfig.usesAncestorConfig:false` or - * `ttlConfig:*`. - * @param {number} request.pageSize - * The number of results to return. - * @param {string} request.pageToken - * A page token, returned from a previous call to - * {@link protos.google.firestore.admin.v1.FirestoreAdmin.ListFields|FirestoreAdmin.ListFields}, - * that may be used to get the next page of results. - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Promise} - The promise which resolves to an array. - * The first element of the array is Array of {@link protos.google.firestore.admin.v1.Field|Field}. - * The client library will perform auto-pagination by default: it will call the API as many - * times as needed and will merge results from all the pages into this array. - * Note that it can affect your quota. - * We recommend using `listFieldsAsync()` - * method described below for async iteration which you can stop as needed. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#auto-pagination | documentation } - * for more details and examples. - */ + /** + * Lists the field configuration and metadata for this database. + * + * Currently, + * {@link protos.google.firestore.admin.v1.FirestoreAdmin.ListFields|FirestoreAdmin.ListFields} + * only supports listing fields that have been explicitly overridden. To issue + * this query, call + * {@link protos.google.firestore.admin.v1.FirestoreAdmin.ListFields|FirestoreAdmin.ListFields} + * with the filter set to `indexConfig.usesAncestorConfig:false` or + * `ttlConfig:*`. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.parent + * Required. A parent name of the form + * `projects/{project_id}/databases/{database_id}/collectionGroups/{collection_id}` + * @param {string} request.filter + * The filter to apply to list results. Currently, + * {@link protos.google.firestore.admin.v1.FirestoreAdmin.ListFields|FirestoreAdmin.ListFields} + * only supports listing fields that have been explicitly overridden. To issue + * this query, call + * {@link protos.google.firestore.admin.v1.FirestoreAdmin.ListFields|FirestoreAdmin.ListFields} + * with a filter that includes `indexConfig.usesAncestorConfig:false` or + * `ttlConfig:*`. + * @param {number} request.pageSize + * The number of results to return. + * @param {string} request.pageToken + * A page token, returned from a previous call to + * {@link protos.google.firestore.admin.v1.FirestoreAdmin.ListFields|FirestoreAdmin.ListFields}, + * that may be used to get the next page of results. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is Array of {@link protos.google.firestore.admin.v1.Field|Field}. + * The client library will perform auto-pagination by default: it will call the API as many + * times as needed and will merge results from all the pages into this array. + * Note that it can affect your quota. + * We recommend using `listFieldsAsync()` + * method described below for async iteration which you can stop as needed. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#auto-pagination | documentation } + * for more details and examples. + */ listFields( - request?: protos.google.firestore.admin.v1.IListFieldsRequest, - options?: CallOptions - ): Promise< - [ - protos.google.firestore.admin.v1.IField[], - protos.google.firestore.admin.v1.IListFieldsRequest | null, - protos.google.firestore.admin.v1.IListFieldsResponse, - ] - >; + request?: protos.google.firestore.admin.v1.IListFieldsRequest, + options?: CallOptions): + Promise<[ + protos.google.firestore.admin.v1.IField[], + protos.google.firestore.admin.v1.IListFieldsRequest|null, + protos.google.firestore.admin.v1.IListFieldsResponse + ]>; listFields( - request: protos.google.firestore.admin.v1.IListFieldsRequest, - options: CallOptions, - callback: PaginationCallback< - protos.google.firestore.admin.v1.IListFieldsRequest, - protos.google.firestore.admin.v1.IListFieldsResponse | null | undefined, - protos.google.firestore.admin.v1.IField - > - ): void; + request: protos.google.firestore.admin.v1.IListFieldsRequest, + options: CallOptions, + callback: PaginationCallback< + protos.google.firestore.admin.v1.IListFieldsRequest, + protos.google.firestore.admin.v1.IListFieldsResponse|null|undefined, + protos.google.firestore.admin.v1.IField>): void; listFields( - request: protos.google.firestore.admin.v1.IListFieldsRequest, - callback: PaginationCallback< - protos.google.firestore.admin.v1.IListFieldsRequest, - protos.google.firestore.admin.v1.IListFieldsResponse | null | undefined, - protos.google.firestore.admin.v1.IField - > - ): void; + request: protos.google.firestore.admin.v1.IListFieldsRequest, + callback: PaginationCallback< + protos.google.firestore.admin.v1.IListFieldsRequest, + protos.google.firestore.admin.v1.IListFieldsResponse|null|undefined, + protos.google.firestore.admin.v1.IField>): void; listFields( - request?: protos.google.firestore.admin.v1.IListFieldsRequest, - optionsOrCallback?: - | CallOptions - | PaginationCallback< + request?: protos.google.firestore.admin.v1.IListFieldsRequest, + optionsOrCallback?: CallOptions|PaginationCallback< protos.google.firestore.admin.v1.IListFieldsRequest, - | protos.google.firestore.admin.v1.IListFieldsResponse - | null - | undefined, - protos.google.firestore.admin.v1.IField - >, - callback?: PaginationCallback< - protos.google.firestore.admin.v1.IListFieldsRequest, - protos.google.firestore.admin.v1.IListFieldsResponse | null | undefined, - protos.google.firestore.admin.v1.IField - > - ): Promise< - [ - protos.google.firestore.admin.v1.IField[], - protos.google.firestore.admin.v1.IListFieldsRequest | null, - protos.google.firestore.admin.v1.IListFieldsResponse, - ] - > | void { + protos.google.firestore.admin.v1.IListFieldsResponse|null|undefined, + protos.google.firestore.admin.v1.IField>, + callback?: PaginationCallback< + protos.google.firestore.admin.v1.IListFieldsRequest, + protos.google.firestore.admin.v1.IListFieldsResponse|null|undefined, + protos.google.firestore.admin.v1.IField>): + Promise<[ + protos.google.firestore.admin.v1.IField[], + protos.google.firestore.admin.v1.IListFieldsRequest|null, + protos.google.firestore.admin.v1.IListFieldsResponse + ]>|void { request = request || {}; let options: CallOptions; if (typeof optionsOrCallback === 'function' && callback === undefined) { callback = optionsOrCallback; options = {}; - } else { + } + else { options = optionsOrCallback as CallOptions; } options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - options.otherArgs.headers['x-goog-request-params'] = - this._gaxModule.routingHeader.fromParams({ - parent: request.parent ?? '', + options.otherArgs.headers[ + 'x-goog-request-params' + ] = this._gaxModule.routingHeader.fromParams({ + 'parent': request.parent ?? '', + }); + this.initialize().catch(err => {throw err}); + const wrappedCallback: PaginationCallback< + protos.google.firestore.admin.v1.IListFieldsRequest, + protos.google.firestore.admin.v1.IListFieldsResponse|null|undefined, + protos.google.firestore.admin.v1.IField>|undefined = callback + ? (error, values, nextPageRequest, rawResponse) => { + this._log.info('listFields values %j', values); + callback!(error, values, nextPageRequest, rawResponse); // We verified callback above. + } + : undefined; + this._log.info('listFields request %j', request); + return this.innerApiCalls + .listFields(request, options, wrappedCallback) + ?.then(([response, input, output]: [ + protos.google.firestore.admin.v1.IField[], + protos.google.firestore.admin.v1.IListFieldsRequest|null, + protos.google.firestore.admin.v1.IListFieldsResponse + ]) => { + this._log.info('listFields values %j', response); + return [response, input, output]; }); - this.initialize(); - return this.innerApiCalls.listFields(request, options, callback); } - /** - * Equivalent to `listFields`, but returns a NodeJS Stream object. - * @param {Object} request - * The request object that will be sent. - * @param {string} request.parent - * Required. A parent name of the form - * `projects/{project_id}/databases/{database_id}/collectionGroups/{collection_id}` - * @param {string} request.filter - * The filter to apply to list results. Currently, - * {@link protos.google.firestore.admin.v1.FirestoreAdmin.ListFields|FirestoreAdmin.ListFields} - * only supports listing fields that have been explicitly overridden. To issue - * this query, call - * {@link protos.google.firestore.admin.v1.FirestoreAdmin.ListFields|FirestoreAdmin.ListFields} - * with a filter that includes `indexConfig.usesAncestorConfig:false` or - * `ttlConfig:*`. - * @param {number} request.pageSize - * The number of results to return. - * @param {string} request.pageToken - * A page token, returned from a previous call to - * {@link protos.google.firestore.admin.v1.FirestoreAdmin.ListFields|FirestoreAdmin.ListFields}, - * that may be used to get the next page of results. - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Stream} - * An object stream which emits an object representing {@link protos.google.firestore.admin.v1.Field|Field} on 'data' event. - * The client library will perform auto-pagination by default: it will call the API as many - * times as needed. Note that it can affect your quota. - * We recommend using `listFieldsAsync()` - * method described below for async iteration which you can stop as needed. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#auto-pagination | documentation } - * for more details and examples. - */ +/** + * Equivalent to `listFields`, but returns a NodeJS Stream object. + * @param {Object} request + * The request object that will be sent. + * @param {string} request.parent + * Required. A parent name of the form + * `projects/{project_id}/databases/{database_id}/collectionGroups/{collection_id}` + * @param {string} request.filter + * The filter to apply to list results. Currently, + * {@link protos.google.firestore.admin.v1.FirestoreAdmin.ListFields|FirestoreAdmin.ListFields} + * only supports listing fields that have been explicitly overridden. To issue + * this query, call + * {@link protos.google.firestore.admin.v1.FirestoreAdmin.ListFields|FirestoreAdmin.ListFields} + * with a filter that includes `indexConfig.usesAncestorConfig:false` or + * `ttlConfig:*`. + * @param {number} request.pageSize + * The number of results to return. + * @param {string} request.pageToken + * A page token, returned from a previous call to + * {@link protos.google.firestore.admin.v1.FirestoreAdmin.ListFields|FirestoreAdmin.ListFields}, + * that may be used to get the next page of results. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Stream} + * An object stream which emits an object representing {@link protos.google.firestore.admin.v1.Field|Field} on 'data' event. + * The client library will perform auto-pagination by default: it will call the API as many + * times as needed. Note that it can affect your quota. + * We recommend using `listFieldsAsync()` + * method described below for async iteration which you can stop as needed. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#auto-pagination | documentation } + * for more details and examples. + */ listFieldsStream( - request?: protos.google.firestore.admin.v1.IListFieldsRequest, - options?: CallOptions - ): Transform { + request?: protos.google.firestore.admin.v1.IListFieldsRequest, + options?: CallOptions): + Transform{ request = request || {}; options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - options.otherArgs.headers['x-goog-request-params'] = - this._gaxModule.routingHeader.fromParams({ - parent: request.parent ?? '', - }); + options.otherArgs.headers[ + 'x-goog-request-params' + ] = this._gaxModule.routingHeader.fromParams({ + 'parent': request.parent ?? '', + }); const defaultCallSettings = this._defaults['listFields']; const callSettings = defaultCallSettings.merge(options); - this.initialize(); + this.initialize().catch(err => {throw err}); + this._log.info('listFields stream %j', request); return this.descriptors.page.listFields.createStream( this.innerApiCalls.listFields as GaxCall, request, @@ -3522,63 +3822,65 @@ export class FirestoreAdminClient { ); } - /** - * Equivalent to `listFields`, but returns an iterable object. - * - * `for`-`await`-`of` syntax is used with the iterable to get response elements on-demand. - * @param {Object} request - * The request object that will be sent. - * @param {string} request.parent - * Required. A parent name of the form - * `projects/{project_id}/databases/{database_id}/collectionGroups/{collection_id}` - * @param {string} request.filter - * The filter to apply to list results. Currently, - * {@link protos.google.firestore.admin.v1.FirestoreAdmin.ListFields|FirestoreAdmin.ListFields} - * only supports listing fields that have been explicitly overridden. To issue - * this query, call - * {@link protos.google.firestore.admin.v1.FirestoreAdmin.ListFields|FirestoreAdmin.ListFields} - * with a filter that includes `indexConfig.usesAncestorConfig:false` or - * `ttlConfig:*`. - * @param {number} request.pageSize - * The number of results to return. - * @param {string} request.pageToken - * A page token, returned from a previous call to - * {@link protos.google.firestore.admin.v1.FirestoreAdmin.ListFields|FirestoreAdmin.ListFields}, - * that may be used to get the next page of results. - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Object} - * An iterable Object that allows {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols | async iteration }. - * When you iterate the returned iterable, each element will be an object representing - * {@link protos.google.firestore.admin.v1.Field|Field}. The API will be called under the hood as needed, once per the page, - * so you can stop the iteration when you don't need more results. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#auto-pagination | documentation } - * for more details and examples. - * @example - * region_tag:firestore_v1_generated_FirestoreAdmin_ListFields_async - */ +/** + * Equivalent to `listFields`, but returns an iterable object. + * + * `for`-`await`-`of` syntax is used with the iterable to get response elements on-demand. + * @param {Object} request + * The request object that will be sent. + * @param {string} request.parent + * Required. A parent name of the form + * `projects/{project_id}/databases/{database_id}/collectionGroups/{collection_id}` + * @param {string} request.filter + * The filter to apply to list results. Currently, + * {@link protos.google.firestore.admin.v1.FirestoreAdmin.ListFields|FirestoreAdmin.ListFields} + * only supports listing fields that have been explicitly overridden. To issue + * this query, call + * {@link protos.google.firestore.admin.v1.FirestoreAdmin.ListFields|FirestoreAdmin.ListFields} + * with a filter that includes `indexConfig.usesAncestorConfig:false` or + * `ttlConfig:*`. + * @param {number} request.pageSize + * The number of results to return. + * @param {string} request.pageToken + * A page token, returned from a previous call to + * {@link protos.google.firestore.admin.v1.FirestoreAdmin.ListFields|FirestoreAdmin.ListFields}, + * that may be used to get the next page of results. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Object} + * An iterable Object that allows {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols | async iteration }. + * When you iterate the returned iterable, each element will be an object representing + * {@link protos.google.firestore.admin.v1.Field|Field}. The API will be called under the hood as needed, once per the page, + * so you can stop the iteration when you don't need more results. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#auto-pagination | documentation } + * for more details and examples. + * @example + * region_tag:firestore_v1_generated_FirestoreAdmin_ListFields_async + */ listFieldsAsync( - request?: protos.google.firestore.admin.v1.IListFieldsRequest, - options?: CallOptions - ): AsyncIterable { + request?: protos.google.firestore.admin.v1.IListFieldsRequest, + options?: CallOptions): + AsyncIterable{ request = request || {}; options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - options.otherArgs.headers['x-goog-request-params'] = - this._gaxModule.routingHeader.fromParams({ - parent: request.parent ?? '', - }); + options.otherArgs.headers[ + 'x-goog-request-params' + ] = this._gaxModule.routingHeader.fromParams({ + 'parent': request.parent ?? '', + }); const defaultCallSettings = this._defaults['listFields']; const callSettings = defaultCallSettings.merge(options); - this.initialize(); + this.initialize().catch(err => {throw err}); + this._log.info('listFields iterate %j', request); return this.descriptors.page.listFields.asyncIterate( this.innerApiCalls['listFields'] as GaxCall, request as {}, callSettings ) as AsyncIterable; } - /** +/** * Gets information about a location. * * @param {Object} request @@ -3618,7 +3920,7 @@ export class FirestoreAdminClient { return this.locationsClient.getLocation(request, options, callback); } - /** +/** * Lists information about the supported locations for this service. Returns an iterable object. * * `for`-`await`-`of` syntax is used with the iterable to get response elements on-demand. @@ -3656,7 +3958,7 @@ export class FirestoreAdminClient { return this.locationsClient.listLocationsAsync(request, options); } - /** +/** * Gets the latest state of a long-running operation. Clients can use this * method to poll the operation result at intervals as recommended by the API * service. @@ -3701,20 +4003,20 @@ export class FirestoreAdminClient { {} | null | undefined > ): Promise<[protos.google.longrunning.Operation]> { - let options: gax.CallOptions; - if (typeof optionsOrCallback === 'function' && callback === undefined) { - callback = optionsOrCallback; - options = {}; - } else { - options = optionsOrCallback as gax.CallOptions; - } - options = options || {}; - options.otherArgs = options.otherArgs || {}; - options.otherArgs.headers = options.otherArgs.headers || {}; - options.otherArgs.headers['x-goog-request-params'] = - this._gaxModule.routingHeader.fromParams({ - name: request.name ?? '', - }); + let options: gax.CallOptions; + if (typeof optionsOrCallback === 'function' && callback === undefined) { + callback = optionsOrCallback; + options = {}; + } else { + options = optionsOrCallback as gax.CallOptions; + } + options = options || {}; + options.otherArgs = options.otherArgs || {}; + options.otherArgs.headers = options.otherArgs.headers || {}; + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + name: request.name ?? '', + }); return this.operationsClient.getOperation(request, options, callback); } /** @@ -3750,14 +4052,14 @@ export class FirestoreAdminClient { listOperationsAsync( request: protos.google.longrunning.ListOperationsRequest, options?: gax.CallOptions - ): AsyncIterable { - options = options || {}; - options.otherArgs = options.otherArgs || {}; - options.otherArgs.headers = options.otherArgs.headers || {}; - options.otherArgs.headers['x-goog-request-params'] = - this._gaxModule.routingHeader.fromParams({ - name: request.name ?? '', - }); + ): AsyncIterable { + options = options || {}; + options.otherArgs = options.otherArgs || {}; + options.otherArgs.headers = options.otherArgs.headers || {}; + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + name: request.name ?? '', + }); return this.operationsClient.listOperationsAsync(request, options); } /** @@ -3791,7 +4093,7 @@ export class FirestoreAdminClient { * await client.cancelOperation({name: ''}); * ``` */ - cancelOperation( + cancelOperation( request: protos.google.longrunning.CancelOperationRequest, optionsOrCallback?: | gax.CallOptions @@ -3806,20 +4108,20 @@ export class FirestoreAdminClient { {} | undefined | null > ): Promise { - let options: gax.CallOptions; - if (typeof optionsOrCallback === 'function' && callback === undefined) { - callback = optionsOrCallback; - options = {}; - } else { - options = optionsOrCallback as gax.CallOptions; - } - options = options || {}; - options.otherArgs = options.otherArgs || {}; - options.otherArgs.headers = options.otherArgs.headers || {}; - options.otherArgs.headers['x-goog-request-params'] = - this._gaxModule.routingHeader.fromParams({ - name: request.name ?? '', - }); + let options: gax.CallOptions; + if (typeof optionsOrCallback === 'function' && callback === undefined) { + callback = optionsOrCallback; + options = {}; + } else { + options = optionsOrCallback as gax.CallOptions; + } + options = options || {}; + options.otherArgs = options.otherArgs || {}; + options.otherArgs.headers = options.otherArgs.headers || {}; + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + name: request.name ?? '', + }); return this.operationsClient.cancelOperation(request, options, callback); } @@ -3863,20 +4165,20 @@ export class FirestoreAdminClient { {} | null | undefined > ): Promise { - let options: gax.CallOptions; - if (typeof optionsOrCallback === 'function' && callback === undefined) { - callback = optionsOrCallback; - options = {}; - } else { - options = optionsOrCallback as gax.CallOptions; - } - options = options || {}; - options.otherArgs = options.otherArgs || {}; - options.otherArgs.headers = options.otherArgs.headers || {}; - options.otherArgs.headers['x-goog-request-params'] = - this._gaxModule.routingHeader.fromParams({ - name: request.name ?? '', - }); + let options: gax.CallOptions; + if (typeof optionsOrCallback === 'function' && callback === undefined) { + callback = optionsOrCallback; + options = {}; + } else { + options = optionsOrCallback as gax.CallOptions; + } + options = options || {}; + options.otherArgs = options.otherArgs || {}; + options.otherArgs.headers = options.otherArgs.headers || {}; + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + name: request.name ?? '', + }); return this.operationsClient.deleteOperation(request, options, callback); } @@ -3892,7 +4194,7 @@ export class FirestoreAdminClient { * @param {string} backup * @returns {string} Resource name string. */ - backupPath(project: string, location: string, backup: string) { + backupPath(project:string,location:string,backup:string) { return this.pathTemplates.backupPathTemplate.render({ project: project, location: location, @@ -3941,11 +4243,7 @@ export class FirestoreAdminClient { * @param {string} backup_schedule * @returns {string} Resource name string. */ - backupSchedulePath( - project: string, - database: string, - backupSchedule: string - ) { + backupSchedulePath(project:string,database:string,backupSchedule:string) { return this.pathTemplates.backupSchedulePathTemplate.render({ project: project, database: database, @@ -3961,9 +4259,7 @@ export class FirestoreAdminClient { * @returns {string} A string representing the project. */ matchProjectFromBackupScheduleName(backupScheduleName: string) { - return this.pathTemplates.backupSchedulePathTemplate.match( - backupScheduleName - ).project; + return this.pathTemplates.backupSchedulePathTemplate.match(backupScheduleName).project; } /** @@ -3974,9 +4270,7 @@ export class FirestoreAdminClient { * @returns {string} A string representing the database. */ matchDatabaseFromBackupScheduleName(backupScheduleName: string) { - return this.pathTemplates.backupSchedulePathTemplate.match( - backupScheduleName - ).database; + return this.pathTemplates.backupSchedulePathTemplate.match(backupScheduleName).database; } /** @@ -3987,9 +4281,7 @@ export class FirestoreAdminClient { * @returns {string} A string representing the backup_schedule. */ matchBackupScheduleFromBackupScheduleName(backupScheduleName: string) { - return this.pathTemplates.backupSchedulePathTemplate.match( - backupScheduleName - ).backup_schedule; + return this.pathTemplates.backupSchedulePathTemplate.match(backupScheduleName).backup_schedule; } /** @@ -4000,7 +4292,7 @@ export class FirestoreAdminClient { * @param {string} collection * @returns {string} Resource name string. */ - collectionGroupPath(project: string, database: string, collection: string) { + collectionGroupPath(project:string,database:string,collection:string) { return this.pathTemplates.collectionGroupPathTemplate.render({ project: project, database: database, @@ -4016,9 +4308,7 @@ export class FirestoreAdminClient { * @returns {string} A string representing the project. */ matchProjectFromCollectionGroupName(collectionGroupName: string) { - return this.pathTemplates.collectionGroupPathTemplate.match( - collectionGroupName - ).project; + return this.pathTemplates.collectionGroupPathTemplate.match(collectionGroupName).project; } /** @@ -4029,9 +4319,7 @@ export class FirestoreAdminClient { * @returns {string} A string representing the database. */ matchDatabaseFromCollectionGroupName(collectionGroupName: string) { - return this.pathTemplates.collectionGroupPathTemplate.match( - collectionGroupName - ).database; + return this.pathTemplates.collectionGroupPathTemplate.match(collectionGroupName).database; } /** @@ -4042,9 +4330,7 @@ export class FirestoreAdminClient { * @returns {string} A string representing the collection. */ matchCollectionFromCollectionGroupName(collectionGroupName: string) { - return this.pathTemplates.collectionGroupPathTemplate.match( - collectionGroupName - ).collection; + return this.pathTemplates.collectionGroupPathTemplate.match(collectionGroupName).collection; } /** @@ -4054,7 +4340,7 @@ export class FirestoreAdminClient { * @param {string} database * @returns {string} Resource name string. */ - databasePath(project: string, database: string) { + databasePath(project:string,database:string) { return this.pathTemplates.databasePathTemplate.render({ project: project, database: database, @@ -4092,12 +4378,7 @@ export class FirestoreAdminClient { * @param {string} field * @returns {string} Resource name string. */ - fieldPath( - project: string, - database: string, - collection: string, - field: string - ) { + fieldPath(project:string,database:string,collection:string,field:string) { return this.pathTemplates.fieldPathTemplate.render({ project: project, database: database, @@ -4159,12 +4440,7 @@ export class FirestoreAdminClient { * @param {string} index * @returns {string} Resource name string. */ - indexPath( - project: string, - database: string, - collection: string, - index: string - ) { + indexPath(project:string,database:string,collection:string,index:string) { return this.pathTemplates.indexPathTemplate.render({ project: project, database: database, @@ -4224,7 +4500,7 @@ export class FirestoreAdminClient { * @param {string} location * @returns {string} Resource name string. */ - locationPath(project: string, location: string) { + locationPath(project:string,location:string) { return this.pathTemplates.locationPathTemplate.render({ project: project, location: location, @@ -4259,7 +4535,7 @@ export class FirestoreAdminClient { * @param {string} project * @returns {string} Resource name string. */ - projectPath(project: string) { + projectPath(project:string) { return this.pathTemplates.projectPathTemplate.render({ project: project, }); @@ -4276,6 +4552,55 @@ export class FirestoreAdminClient { return this.pathTemplates.projectPathTemplate.match(projectName).project; } + /** + * Return a fully-qualified userCreds resource name string. + * + * @param {string} project + * @param {string} database + * @param {string} user_creds + * @returns {string} Resource name string. + */ + userCredsPath(project:string,database:string,userCreds:string) { + return this.pathTemplates.userCredsPathTemplate.render({ + project: project, + database: database, + user_creds: userCreds, + }); + } + + /** + * Parse the project from UserCreds resource. + * + * @param {string} userCredsName + * A fully-qualified path representing UserCreds resource. + * @returns {string} A string representing the project. + */ + matchProjectFromUserCredsName(userCredsName: string) { + return this.pathTemplates.userCredsPathTemplate.match(userCredsName).project; + } + + /** + * Parse the database from UserCreds resource. + * + * @param {string} userCredsName + * A fully-qualified path representing UserCreds resource. + * @returns {string} A string representing the database. + */ + matchDatabaseFromUserCredsName(userCredsName: string) { + return this.pathTemplates.userCredsPathTemplate.match(userCredsName).database; + } + + /** + * Parse the user_creds from UserCreds resource. + * + * @param {string} userCredsName + * A fully-qualified path representing UserCreds resource. + * @returns {string} A string representing the user_creds. + */ + matchUserCredsFromUserCredsName(userCredsName: string) { + return this.pathTemplates.userCredsPathTemplate.match(userCredsName).user_creds; + } + /** * Terminate the gRPC channel and close the client. * @@ -4285,12 +4610,13 @@ export class FirestoreAdminClient { close(): Promise { if (this.firestoreAdminStub && !this._terminated) { return this.firestoreAdminStub.then(stub => { + this._log.info('ending gRPC channel'); this._terminated = true; stub.close(); - this.locationsClient.close(); - this.operationsClient.close(); + this.locationsClient.close().catch(err => {throw err}); + void this.operationsClient.close(); }); } return Promise.resolve(); } -} +} \ No newline at end of file diff --git a/dev/src/v1/firestore_admin_client_config.json b/dev/src/v1/firestore_admin_client_config.json index 874c4b61c..1b5e0812d 100644 --- a/dev/src/v1/firestore_admin_client_config.json +++ b/dev/src/v1/firestore_admin_client_config.json @@ -96,6 +96,34 @@ "retry_codes_name": "non_idempotent", "retry_params_name": "default" }, + "CreateUserCreds": { + "retry_codes_name": "non_idempotent", + "retry_params_name": "default" + }, + "GetUserCreds": { + "retry_codes_name": "non_idempotent", + "retry_params_name": "default" + }, + "ListUserCreds": { + "retry_codes_name": "non_idempotent", + "retry_params_name": "default" + }, + "EnableUserCreds": { + "retry_codes_name": "non_idempotent", + "retry_params_name": "default" + }, + "DisableUserCreds": { + "retry_codes_name": "non_idempotent", + "retry_params_name": "default" + }, + "ResetUserPassword": { + "retry_codes_name": "non_idempotent", + "retry_params_name": "default" + }, + "DeleteUserCreds": { + "retry_codes_name": "non_idempotent", + "retry_params_name": "default" + }, "GetBackup": { "retry_codes_name": "non_idempotent", "retry_params_name": "default" diff --git a/dev/src/v1/firestore_admin_proto_list.json b/dev/src/v1/firestore_admin_proto_list.json index eaf3273a7..4eefad030 100644 --- a/dev/src/v1/firestore_admin_proto_list.json +++ b/dev/src/v1/firestore_admin_proto_list.json @@ -6,5 +6,6 @@ "../../protos/google/firestore/admin/v1/index.proto", "../../protos/google/firestore/admin/v1/location.proto", "../../protos/google/firestore/admin/v1/operation.proto", - "../../protos/google/firestore/admin/v1/schedule.proto" + "../../protos/google/firestore/admin/v1/schedule.proto", + "../../protos/google/firestore/admin/v1/user_creds.proto" ] diff --git a/dev/src/v1/firestore_client.ts b/dev/src/v1/firestore_client.ts index 6b259c45f..b3296bf05 100644 --- a/dev/src/v1/firestore_client.ts +++ b/dev/src/v1/firestore_client.ts @@ -18,19 +18,11 @@ /* global window */ import type * as gax from 'google-gax'; -import type { - Callback, - CallOptions, - Descriptors, - ClientOptions, - PaginationCallback, - GaxCall, - LocationsClient, - LocationProtos, -} from 'google-gax'; +import type {Callback, CallOptions, Descriptors, ClientOptions, PaginationCallback, GaxCall, LocationsClient, LocationProtos} from 'google-gax'; import {Transform, PassThrough} from 'stream'; import * as protos from '../../protos/firestore_v1_proto_api'; import jsonProtos = require('../../protos/v1.json'); +import {loggingUtils as logging} from 'google-gax'; /** * Client JSON configuration object, loaded from @@ -62,6 +54,8 @@ export class FirestoreClient { private _defaults: {[method: string]: gax.CallSettings}; private _universeDomain: string; private _servicePath: string; + private _log = logging.log('firestore'); + auth: gax.GoogleAuth; descriptors: Descriptors = { page: {}, @@ -96,7 +90,7 @@ export class FirestoreClient { * Developer's Console, e.g. 'grape-spaceship-123'. We will also check * the environment variable GCLOUD_PROJECT for your project ID. If your * app is running in an environment which supports - * {@link https://developers.google.com/identity/protocols/application-default-credentials Application Default Credentials}, + * {@link https://cloud.google.com/docs/authentication/application-default-credentials Application Default Credentials}, * your project ID will be detected automatically. * @param {string} [options.apiEndpoint] - The domain name of the * API remote host. @@ -113,46 +107,22 @@ export class FirestoreClient { * const client = new FirestoreClient({fallback: true}, gax); * ``` */ - constructor( - opts?: ClientOptions, - gaxInstance?: typeof gax | typeof gax.fallback - ) { + constructor(opts?: ClientOptions, gaxInstance?: typeof gax | typeof gax.fallback) { // Ensure that options include all the required fields. const staticMembers = this.constructor as typeof FirestoreClient; - if ( - opts?.universe_domain && - opts?.universeDomain && - opts?.universe_domain !== opts?.universeDomain - ) { - throw new Error( - 'Please set either universe_domain or universeDomain, but not both.' - ); + if (opts?.universe_domain && opts?.universeDomain && opts?.universe_domain !== opts?.universeDomain) { + throw new Error('Please set either universe_domain or universeDomain, but not both.'); } - const universeDomainEnvVar = - typeof process === 'object' && typeof process.env === 'object' - ? process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] - : undefined; - this._universeDomain = - opts?.universeDomain ?? - opts?.universe_domain ?? - universeDomainEnvVar ?? - 'googleapis.com'; + const universeDomainEnvVar = (typeof process === 'object' && typeof process.env === 'object') ? process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] : undefined; + this._universeDomain = opts?.universeDomain ?? opts?.universe_domain ?? universeDomainEnvVar ?? 'googleapis.com'; this._servicePath = 'firestore.' + this._universeDomain; - const servicePath = - opts?.servicePath || opts?.apiEndpoint || this._servicePath; - this._providedCustomServicePath = !!( - opts?.servicePath || opts?.apiEndpoint - ); + const servicePath = opts?.servicePath || opts?.apiEndpoint || this._servicePath; + this._providedCustomServicePath = !!(opts?.servicePath || opts?.apiEndpoint); const port = opts?.port || staticMembers.port; const clientConfig = opts?.clientConfig ?? {}; - const fallback = - opts?.fallback ?? - (typeof window !== 'undefined' && typeof window?.fetch === 'function'); + const fallback = opts?.fallback ?? (typeof window !== 'undefined' && typeof window?.fetch === 'function'); opts = Object.assign({servicePath, port, clientConfig, fallback}, opts); - // Request numeric enum values if REST transport is used. - opts.numericEnums = true; - // If scopes are unset in options and we're connecting to a non-default endpoint, set scopes just in case. if (servicePath !== this._servicePath && !('scopes' in opts)) { opts['scopes'] = staticMembers.scopes; @@ -173,7 +143,7 @@ export class FirestoreClient { this._opts = opts; // Save the auth object to the client, for use by other methods. - this.auth = this._gaxGrpc.auth as gax.GoogleAuth; + this.auth = (this._gaxGrpc.auth as gax.GoogleAuth); // Set useJWTAccessWithScope on the auth object. this.auth.useJWTAccessWithScope = true; @@ -189,9 +159,13 @@ export class FirestoreClient { this._gaxGrpc, opts ); + // Determine the client header string. - const clientHeader = [`gax/${this._gaxModule.version}`, `gapic/${version}`]; + const clientHeader = [ + `gax/${this._gaxModule.version}`, + `gapic/${version}`, + ]; if (typeof process === 'object' && 'versions' in process) { clientHeader.push(`gl-node/${process.versions.node}`); } else { @@ -212,65 +186,29 @@ export class FirestoreClient { // (e.g. 50 results at a time, with tokens to get subsequent // pages). Denote the keys used for pagination and results. this.descriptors.page = { - listDocuments: new this._gaxModule.PageDescriptor( - 'pageToken', - 'nextPageToken', - 'documents' - ), - partitionQuery: new this._gaxModule.PageDescriptor( - 'pageToken', - 'nextPageToken', - 'partitions' - ), - listCollectionIds: new this._gaxModule.PageDescriptor( - 'pageToken', - 'nextPageToken', - 'collectionIds' - ), + listDocuments: + new this._gaxModule.PageDescriptor('pageToken', 'nextPageToken', 'documents'), + partitionQuery: + new this._gaxModule.PageDescriptor('pageToken', 'nextPageToken', 'partitions'), + listCollectionIds: + new this._gaxModule.PageDescriptor('pageToken', 'nextPageToken', 'collectionIds') }; // Some of the methods on this service provide streaming responses. // Provide descriptors for these. this.descriptors.stream = { - batchGetDocuments: new this._gaxModule.StreamDescriptor( - this._gaxModule.StreamType.SERVER_STREAMING, - !!opts.fallback, - !!opts.gaxServerStreamingRetries - ), - runQuery: new this._gaxModule.StreamDescriptor( - this._gaxModule.StreamType.SERVER_STREAMING, - !!opts.fallback, - !!opts.gaxServerStreamingRetries - ), - executePipeline: new this._gaxModule.StreamDescriptor( - this._gaxModule.StreamType.SERVER_STREAMING, - !!opts.fallback, - !!opts.gaxServerStreamingRetries - ), - runAggregationQuery: new this._gaxModule.StreamDescriptor( - this._gaxModule.StreamType.SERVER_STREAMING, - !!opts.fallback, - !!opts.gaxServerStreamingRetries - ), - write: new this._gaxModule.StreamDescriptor( - this._gaxModule.StreamType.BIDI_STREAMING, - !!opts.fallback, - !!opts.gaxServerStreamingRetries - ), - listen: new this._gaxModule.StreamDescriptor( - this._gaxModule.StreamType.BIDI_STREAMING, - !!opts.fallback, - !!opts.gaxServerStreamingRetries - ), + batchGetDocuments: new this._gaxModule.StreamDescriptor(this._gaxModule.StreamType.SERVER_STREAMING, !!opts.fallback, !!opts.gaxServerStreamingRetries), + runQuery: new this._gaxModule.StreamDescriptor(this._gaxModule.StreamType.SERVER_STREAMING, !!opts.fallback, !!opts.gaxServerStreamingRetries), + executePipeline: new this._gaxModule.StreamDescriptor(this._gaxModule.StreamType.SERVER_STREAMING, !!opts.fallback, !!opts.gaxServerStreamingRetries), + runAggregationQuery: new this._gaxModule.StreamDescriptor(this._gaxModule.StreamType.SERVER_STREAMING, !!opts.fallback, !!opts.gaxServerStreamingRetries), + write: new this._gaxModule.StreamDescriptor(this._gaxModule.StreamType.BIDI_STREAMING, !!opts.fallback, !!opts.gaxServerStreamingRetries), + listen: new this._gaxModule.StreamDescriptor(this._gaxModule.StreamType.BIDI_STREAMING, !!opts.fallback, !!opts.gaxServerStreamingRetries) }; // Put together the default options sent with requests. this._defaults = this._gaxGrpc.constructSettings( - 'google.firestore.v1.Firestore', - gapicConfig as gax.ClientConfig, - opts.clientConfig || {}, - {'x-goog-api-client': clientHeader.join(' ')} - ); + 'google.firestore.v1.Firestore', gapicConfig as gax.ClientConfig, + opts.clientConfig || {}, {'x-goog-api-client': clientHeader.join(' ')}); // Set up a dictionary of "inner API calls"; the core implementation // of calling the API is handled in `google-gax`, with this code @@ -301,63 +239,35 @@ export class FirestoreClient { // Put together the "service stub" for // google.firestore.v1.Firestore. this.firestoreStub = this._gaxGrpc.createStub( - this._opts.fallback - ? (this._protos as protobuf.Root).lookupService( - 'google.firestore.v1.Firestore' - ) - : // eslint-disable-next-line @typescript-eslint/no-explicit-any + this._opts.fallback ? + (this._protos as protobuf.Root).lookupService('google.firestore.v1.Firestore') : + // eslint-disable-next-line @typescript-eslint/no-explicit-any (this._protos as any).google.firestore.v1.Firestore, - this._opts, - this._providedCustomServicePath - ) as Promise<{[method: string]: Function}>; + this._opts, this._providedCustomServicePath) as Promise<{[method: string]: Function}>; // Iterate over each of the methods that the service provides // and create an API call method for each. - const firestoreStubMethods = [ - 'getDocument', - 'listDocuments', - 'updateDocument', - 'deleteDocument', - 'batchGetDocuments', - 'beginTransaction', - 'commit', - 'rollback', - 'executePipeline', - 'runQuery', - 'runAggregationQuery', - 'partitionQuery', - 'write', - 'listen', - 'listCollectionIds', - 'batchWrite', - 'createDocument', - ]; + const firestoreStubMethods = + ['getDocument', 'listDocuments', 'updateDocument', 'deleteDocument', 'batchGetDocuments', 'beginTransaction', 'commit', 'rollback', 'runQuery', 'executePipeline', 'runAggregationQuery', 'partitionQuery', 'write', 'listen', 'listCollectionIds', 'batchWrite', 'createDocument']; for (const methodName of firestoreStubMethods) { const callPromise = this.firestoreStub.then( - stub => - (...args: Array<{}>) => { - if (this._terminated) { - if (methodName in this.descriptors.stream) { - const stream = new PassThrough({objectMode: true}); - setImmediate(() => { - stream.emit( - 'error', - new this._gaxModule.GoogleError( - 'The client has already been closed.' - ) - ); - }); - return stream; - } - return Promise.reject('The client has already been closed.'); + stub => (...args: Array<{}>) => { + if (this._terminated) { + if (methodName in this.descriptors.stream) { + const stream = new PassThrough({objectMode: true}); + setImmediate(() => { + stream.emit('error', new this._gaxModule.GoogleError('The client has already been closed.')); + }); + return stream; } - const func = stub[methodName]; - return func.apply(stub, args); - }, - (err: Error | null | undefined) => () => { + return Promise.reject('The client has already been closed.'); + } + const func = stub[methodName]; + return func.apply(stub, args); + }, + (err: Error|null|undefined) => () => { throw err; - } - ); + }); const descriptor = this.descriptors.page[methodName] || @@ -382,14 +292,8 @@ export class FirestoreClient { * @returns {string} The DNS address for this service. */ static get servicePath() { - if ( - typeof process === 'object' && - typeof process.emitWarning === 'function' - ) { - process.emitWarning( - 'Static servicePath is deprecated, please use the instance method instead.', - 'DeprecationWarning' - ); + if (typeof process === 'object' && typeof process.emitWarning === 'function') { + process.emitWarning('Static servicePath is deprecated, please use the instance method instead.', 'DeprecationWarning'); } return 'firestore.googleapis.com'; } @@ -400,14 +304,8 @@ export class FirestoreClient { * @returns {string} The DNS address for this service. */ static get apiEndpoint() { - if ( - typeof process === 'object' && - typeof process.emitWarning === 'function' - ) { - process.emitWarning( - 'Static apiEndpoint is deprecated, please use the instance method instead.', - 'DeprecationWarning' - ); + if (typeof process === 'object' && typeof process.emitWarning === 'function') { + process.emitWarning('Static apiEndpoint is deprecated, please use the instance method instead.', 'DeprecationWarning'); } return 'firestore.googleapis.com'; } @@ -440,7 +338,7 @@ export class FirestoreClient { static get scopes() { return [ 'https://www.googleapis.com/auth/cloud-platform', - 'https://www.googleapis.com/auth/datastore', + 'https://www.googleapis.com/auth/datastore' ]; } @@ -450,9 +348,8 @@ export class FirestoreClient { * Return the project ID used by this class. * @returns {Promise} A promise that resolves to string containing the project ID. */ - getProjectId( - callback?: Callback - ): Promise | void { + getProjectId(callback?: Callback): + Promise|void { if (callback) { this.auth.getProjectId(callback); return; @@ -463,1218 +360,1344 @@ export class FirestoreClient { // ------------------- // -- Service calls -- // ------------------- - /** - * Gets a single document. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.name - * Required. The resource name of the Document to get. In the format: - * `projects/{project_id}/databases/{database_id}/documents/{document_path}`. - * @param {google.firestore.v1.DocumentMask} request.mask - * The fields to return. If not set, returns all fields. - * - * If the document has a field that is not present in this mask, that field - * will not be returned in the response. - * @param {Buffer} request.transaction - * Reads the document in a transaction. - * @param {google.protobuf.Timestamp} request.readTime - * Reads the version of the document at the given time. - * - * This must be a microsecond precision timestamp within the past one hour, - * or if Point-in-Time Recovery is enabled, can additionally be a whole - * minute timestamp within the past 7 days. - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Promise} - The promise which resolves to an array. - * The first element of the array is an object representing {@link protos.google.firestore.v1.Document|Document}. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } - * for more details and examples. - * @example - * region_tag:firestore_v1_generated_Firestore_GetDocument_async - */ +/** + * Gets a single document. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.name + * Required. The resource name of the Document to get. In the format: + * `projects/{project_id}/databases/{database_id}/documents/{document_path}`. + * @param {google.firestore.v1.DocumentMask} request.mask + * The fields to return. If not set, returns all fields. + * + * If the document has a field that is not present in this mask, that field + * will not be returned in the response. + * @param {Buffer} request.transaction + * Reads the document in a transaction. + * @param {google.protobuf.Timestamp} request.readTime + * Reads the version of the document at the given time. + * + * This must be a microsecond precision timestamp within the past one hour, + * or if Point-in-Time Recovery is enabled, can additionally be a whole + * minute timestamp within the past 7 days. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is an object representing {@link protos.google.firestore.v1.Document|Document}. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } + * for more details and examples. + * @example + * region_tag:firestore_v1_generated_Firestore_GetDocument_async + */ getDocument( - request?: protos.google.firestore.v1.IGetDocumentRequest, - options?: CallOptions - ): Promise< - [ - protos.google.firestore.v1.IDocument, - protos.google.firestore.v1.IGetDocumentRequest | undefined, - {} | undefined, - ] - >; + request?: protos.google.firestore.v1.IGetDocumentRequest, + options?: CallOptions): + Promise<[ + protos.google.firestore.v1.IDocument, + protos.google.firestore.v1.IGetDocumentRequest|undefined, {}|undefined + ]>; getDocument( - request: protos.google.firestore.v1.IGetDocumentRequest, - options: CallOptions, - callback: Callback< - protos.google.firestore.v1.IDocument, - protos.google.firestore.v1.IGetDocumentRequest | null | undefined, - {} | null | undefined - > - ): void; + request: protos.google.firestore.v1.IGetDocumentRequest, + options: CallOptions, + callback: Callback< + protos.google.firestore.v1.IDocument, + protos.google.firestore.v1.IGetDocumentRequest|null|undefined, + {}|null|undefined>): void; getDocument( - request: protos.google.firestore.v1.IGetDocumentRequest, - callback: Callback< - protos.google.firestore.v1.IDocument, - protos.google.firestore.v1.IGetDocumentRequest | null | undefined, - {} | null | undefined - > - ): void; + request: protos.google.firestore.v1.IGetDocumentRequest, + callback: Callback< + protos.google.firestore.v1.IDocument, + protos.google.firestore.v1.IGetDocumentRequest|null|undefined, + {}|null|undefined>): void; getDocument( - request?: protos.google.firestore.v1.IGetDocumentRequest, - optionsOrCallback?: - | CallOptions - | Callback< + request?: protos.google.firestore.v1.IGetDocumentRequest, + optionsOrCallback?: CallOptions|Callback< protos.google.firestore.v1.IDocument, - protos.google.firestore.v1.IGetDocumentRequest | null | undefined, - {} | null | undefined - >, - callback?: Callback< - protos.google.firestore.v1.IDocument, - protos.google.firestore.v1.IGetDocumentRequest | null | undefined, - {} | null | undefined - > - ): Promise< - [ - protos.google.firestore.v1.IDocument, - protos.google.firestore.v1.IGetDocumentRequest | undefined, - {} | undefined, - ] - > | void { + protos.google.firestore.v1.IGetDocumentRequest|null|undefined, + {}|null|undefined>, + callback?: Callback< + protos.google.firestore.v1.IDocument, + protos.google.firestore.v1.IGetDocumentRequest|null|undefined, + {}|null|undefined>): + Promise<[ + protos.google.firestore.v1.IDocument, + protos.google.firestore.v1.IGetDocumentRequest|undefined, {}|undefined + ]>|void { request = request || {}; let options: CallOptions; if (typeof optionsOrCallback === 'function' && callback === undefined) { callback = optionsOrCallback; options = {}; - } else { + } + else { options = optionsOrCallback as CallOptions; } options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - options.otherArgs.headers['x-goog-request-params'] = - this._gaxModule.routingHeader.fromParams({ - name: request.name ?? '', + options.otherArgs.headers[ + 'x-goog-request-params' + ] = this._gaxModule.routingHeader.fromParams({ + 'name': request.name ?? '', + }); + this.initialize().catch(err => {throw err}); + this._log.info('getDocument request %j', request); + const wrappedCallback: Callback< + protos.google.firestore.v1.IDocument, + protos.google.firestore.v1.IGetDocumentRequest|null|undefined, + {}|null|undefined>|undefined = callback + ? (error, response, options, rawResponse) => { + this._log.info('getDocument response %j', response); + callback!(error, response, options, rawResponse); // We verified callback above. + } + : undefined; + return this.innerApiCalls.getDocument(request, options, wrappedCallback) + ?.then(([response, options, rawResponse]: [ + protos.google.firestore.v1.IDocument, + protos.google.firestore.v1.IGetDocumentRequest|undefined, + {}|undefined + ]) => { + this._log.info('getDocument response %j', response); + return [response, options, rawResponse]; }); - this.initialize(); - return this.innerApiCalls.getDocument(request, options, callback); } - /** - * Updates or inserts a document. - * - * @param {Object} request - * The request object that will be sent. - * @param {google.firestore.v1.Document} request.document - * Required. The updated document. - * Creates the document if it does not already exist. - * @param {google.firestore.v1.DocumentMask} request.updateMask - * The fields to update. - * None of the field paths in the mask may contain a reserved name. - * - * If the document exists on the server and has fields not referenced in the - * mask, they are left unchanged. - * Fields referenced in the mask, but not present in the input document, are - * deleted from the document on the server. - * @param {google.firestore.v1.DocumentMask} request.mask - * The fields to return. If not set, returns all fields. - * - * If the document has a field that is not present in this mask, that field - * will not be returned in the response. - * @param {google.firestore.v1.Precondition} request.currentDocument - * An optional precondition on the document. - * The request will fail if this is set and not met by the target document. - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Promise} - The promise which resolves to an array. - * The first element of the array is an object representing {@link protos.google.firestore.v1.Document|Document}. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } - * for more details and examples. - * @example - * region_tag:firestore_v1_generated_Firestore_UpdateDocument_async - */ +/** + * Updates or inserts a document. + * + * @param {Object} request + * The request object that will be sent. + * @param {google.firestore.v1.Document} request.document + * Required. The updated document. + * Creates the document if it does not already exist. + * @param {google.firestore.v1.DocumentMask} request.updateMask + * The fields to update. + * None of the field paths in the mask may contain a reserved name. + * + * If the document exists on the server and has fields not referenced in the + * mask, they are left unchanged. + * Fields referenced in the mask, but not present in the input document, are + * deleted from the document on the server. + * @param {google.firestore.v1.DocumentMask} request.mask + * The fields to return. If not set, returns all fields. + * + * If the document has a field that is not present in this mask, that field + * will not be returned in the response. + * @param {google.firestore.v1.Precondition} request.currentDocument + * An optional precondition on the document. + * The request will fail if this is set and not met by the target document. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is an object representing {@link protos.google.firestore.v1.Document|Document}. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } + * for more details and examples. + * @example + * region_tag:firestore_v1_generated_Firestore_UpdateDocument_async + */ updateDocument( - request?: protos.google.firestore.v1.IUpdateDocumentRequest, - options?: CallOptions - ): Promise< - [ - protos.google.firestore.v1.IDocument, - protos.google.firestore.v1.IUpdateDocumentRequest | undefined, - {} | undefined, - ] - >; + request?: protos.google.firestore.v1.IUpdateDocumentRequest, + options?: CallOptions): + Promise<[ + protos.google.firestore.v1.IDocument, + protos.google.firestore.v1.IUpdateDocumentRequest|undefined, {}|undefined + ]>; updateDocument( - request: protos.google.firestore.v1.IUpdateDocumentRequest, - options: CallOptions, - callback: Callback< - protos.google.firestore.v1.IDocument, - protos.google.firestore.v1.IUpdateDocumentRequest | null | undefined, - {} | null | undefined - > - ): void; + request: protos.google.firestore.v1.IUpdateDocumentRequest, + options: CallOptions, + callback: Callback< + protos.google.firestore.v1.IDocument, + protos.google.firestore.v1.IUpdateDocumentRequest|null|undefined, + {}|null|undefined>): void; updateDocument( - request: protos.google.firestore.v1.IUpdateDocumentRequest, - callback: Callback< - protos.google.firestore.v1.IDocument, - protos.google.firestore.v1.IUpdateDocumentRequest | null | undefined, - {} | null | undefined - > - ): void; + request: protos.google.firestore.v1.IUpdateDocumentRequest, + callback: Callback< + protos.google.firestore.v1.IDocument, + protos.google.firestore.v1.IUpdateDocumentRequest|null|undefined, + {}|null|undefined>): void; updateDocument( - request?: protos.google.firestore.v1.IUpdateDocumentRequest, - optionsOrCallback?: - | CallOptions - | Callback< + request?: protos.google.firestore.v1.IUpdateDocumentRequest, + optionsOrCallback?: CallOptions|Callback< protos.google.firestore.v1.IDocument, - protos.google.firestore.v1.IUpdateDocumentRequest | null | undefined, - {} | null | undefined - >, - callback?: Callback< - protos.google.firestore.v1.IDocument, - protos.google.firestore.v1.IUpdateDocumentRequest | null | undefined, - {} | null | undefined - > - ): Promise< - [ - protos.google.firestore.v1.IDocument, - protos.google.firestore.v1.IUpdateDocumentRequest | undefined, - {} | undefined, - ] - > | void { + protos.google.firestore.v1.IUpdateDocumentRequest|null|undefined, + {}|null|undefined>, + callback?: Callback< + protos.google.firestore.v1.IDocument, + protos.google.firestore.v1.IUpdateDocumentRequest|null|undefined, + {}|null|undefined>): + Promise<[ + protos.google.firestore.v1.IDocument, + protos.google.firestore.v1.IUpdateDocumentRequest|undefined, {}|undefined + ]>|void { request = request || {}; let options: CallOptions; if (typeof optionsOrCallback === 'function' && callback === undefined) { callback = optionsOrCallback; options = {}; - } else { + } + else { options = optionsOrCallback as CallOptions; } options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - options.otherArgs.headers['x-goog-request-params'] = - this._gaxModule.routingHeader.fromParams({ - 'document.name': request.document!.name ?? '', + options.otherArgs.headers[ + 'x-goog-request-params' + ] = this._gaxModule.routingHeader.fromParams({ + 'document.name': request.document!.name ?? '', + }); + this.initialize().catch(err => {throw err}); + this._log.info('updateDocument request %j', request); + const wrappedCallback: Callback< + protos.google.firestore.v1.IDocument, + protos.google.firestore.v1.IUpdateDocumentRequest|null|undefined, + {}|null|undefined>|undefined = callback + ? (error, response, options, rawResponse) => { + this._log.info('updateDocument response %j', response); + callback!(error, response, options, rawResponse); // We verified callback above. + } + : undefined; + return this.innerApiCalls.updateDocument(request, options, wrappedCallback) + ?.then(([response, options, rawResponse]: [ + protos.google.firestore.v1.IDocument, + protos.google.firestore.v1.IUpdateDocumentRequest|undefined, + {}|undefined + ]) => { + this._log.info('updateDocument response %j', response); + return [response, options, rawResponse]; }); - this.initialize(); - return this.innerApiCalls.updateDocument(request, options, callback); } - /** - * Deletes a document. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.name - * Required. The resource name of the Document to delete. In the format: - * `projects/{project_id}/databases/{database_id}/documents/{document_path}`. - * @param {google.firestore.v1.Precondition} request.currentDocument - * An optional precondition on the document. - * The request will fail if this is set and not met by the target document. - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Promise} - The promise which resolves to an array. - * The first element of the array is an object representing {@link protos.google.protobuf.Empty|Empty}. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } - * for more details and examples. - * @example - * region_tag:firestore_v1_generated_Firestore_DeleteDocument_async - */ +/** + * Deletes a document. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.name + * Required. The resource name of the Document to delete. In the format: + * `projects/{project_id}/databases/{database_id}/documents/{document_path}`. + * @param {google.firestore.v1.Precondition} request.currentDocument + * An optional precondition on the document. + * The request will fail if this is set and not met by the target document. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is an object representing {@link protos.google.protobuf.Empty|Empty}. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } + * for more details and examples. + * @example + * region_tag:firestore_v1_generated_Firestore_DeleteDocument_async + */ deleteDocument( - request?: protos.google.firestore.v1.IDeleteDocumentRequest, - options?: CallOptions - ): Promise< - [ - protos.google.protobuf.IEmpty, - protos.google.firestore.v1.IDeleteDocumentRequest | undefined, - {} | undefined, - ] - >; + request?: protos.google.firestore.v1.IDeleteDocumentRequest, + options?: CallOptions): + Promise<[ + protos.google.protobuf.IEmpty, + protos.google.firestore.v1.IDeleteDocumentRequest|undefined, {}|undefined + ]>; deleteDocument( - request: protos.google.firestore.v1.IDeleteDocumentRequest, - options: CallOptions, - callback: Callback< - protos.google.protobuf.IEmpty, - protos.google.firestore.v1.IDeleteDocumentRequest | null | undefined, - {} | null | undefined - > - ): void; + request: protos.google.firestore.v1.IDeleteDocumentRequest, + options: CallOptions, + callback: Callback< + protos.google.protobuf.IEmpty, + protos.google.firestore.v1.IDeleteDocumentRequest|null|undefined, + {}|null|undefined>): void; deleteDocument( - request: protos.google.firestore.v1.IDeleteDocumentRequest, - callback: Callback< - protos.google.protobuf.IEmpty, - protos.google.firestore.v1.IDeleteDocumentRequest | null | undefined, - {} | null | undefined - > - ): void; + request: protos.google.firestore.v1.IDeleteDocumentRequest, + callback: Callback< + protos.google.protobuf.IEmpty, + protos.google.firestore.v1.IDeleteDocumentRequest|null|undefined, + {}|null|undefined>): void; deleteDocument( - request?: protos.google.firestore.v1.IDeleteDocumentRequest, - optionsOrCallback?: - | CallOptions - | Callback< + request?: protos.google.firestore.v1.IDeleteDocumentRequest, + optionsOrCallback?: CallOptions|Callback< protos.google.protobuf.IEmpty, - protos.google.firestore.v1.IDeleteDocumentRequest | null | undefined, - {} | null | undefined - >, - callback?: Callback< - protos.google.protobuf.IEmpty, - protos.google.firestore.v1.IDeleteDocumentRequest | null | undefined, - {} | null | undefined - > - ): Promise< - [ - protos.google.protobuf.IEmpty, - protos.google.firestore.v1.IDeleteDocumentRequest | undefined, - {} | undefined, - ] - > | void { + protos.google.firestore.v1.IDeleteDocumentRequest|null|undefined, + {}|null|undefined>, + callback?: Callback< + protos.google.protobuf.IEmpty, + protos.google.firestore.v1.IDeleteDocumentRequest|null|undefined, + {}|null|undefined>): + Promise<[ + protos.google.protobuf.IEmpty, + protos.google.firestore.v1.IDeleteDocumentRequest|undefined, {}|undefined + ]>|void { request = request || {}; let options: CallOptions; if (typeof optionsOrCallback === 'function' && callback === undefined) { callback = optionsOrCallback; options = {}; - } else { + } + else { options = optionsOrCallback as CallOptions; } options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - options.otherArgs.headers['x-goog-request-params'] = - this._gaxModule.routingHeader.fromParams({ - name: request.name ?? '', + options.otherArgs.headers[ + 'x-goog-request-params' + ] = this._gaxModule.routingHeader.fromParams({ + 'name': request.name ?? '', + }); + this.initialize().catch(err => {throw err}); + this._log.info('deleteDocument request %j', request); + const wrappedCallback: Callback< + protos.google.protobuf.IEmpty, + protos.google.firestore.v1.IDeleteDocumentRequest|null|undefined, + {}|null|undefined>|undefined = callback + ? (error, response, options, rawResponse) => { + this._log.info('deleteDocument response %j', response); + callback!(error, response, options, rawResponse); // We verified callback above. + } + : undefined; + return this.innerApiCalls.deleteDocument(request, options, wrappedCallback) + ?.then(([response, options, rawResponse]: [ + protos.google.protobuf.IEmpty, + protos.google.firestore.v1.IDeleteDocumentRequest|undefined, + {}|undefined + ]) => { + this._log.info('deleteDocument response %j', response); + return [response, options, rawResponse]; }); - this.initialize(); - return this.innerApiCalls.deleteDocument(request, options, callback); } - /** - * Starts a new transaction. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.database - * Required. The database name. In the format: - * `projects/{project_id}/databases/{database_id}`. - * @param {google.firestore.v1.TransactionOptions} request.options - * The options for the transaction. - * Defaults to a read-write transaction. - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Promise} - The promise which resolves to an array. - * The first element of the array is an object representing {@link protos.google.firestore.v1.BeginTransactionResponse|BeginTransactionResponse}. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } - * for more details and examples. - * @example - * region_tag:firestore_v1_generated_Firestore_BeginTransaction_async - */ +/** + * Starts a new transaction. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.database + * Required. The database name. In the format: + * `projects/{project_id}/databases/{database_id}`. + * @param {google.firestore.v1.TransactionOptions} request.options + * The options for the transaction. + * Defaults to a read-write transaction. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is an object representing {@link protos.google.firestore.v1.BeginTransactionResponse|BeginTransactionResponse}. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } + * for more details and examples. + * @example + * region_tag:firestore_v1_generated_Firestore_BeginTransaction_async + */ beginTransaction( - request?: protos.google.firestore.v1.IBeginTransactionRequest, - options?: CallOptions - ): Promise< - [ - protos.google.firestore.v1.IBeginTransactionResponse, - protos.google.firestore.v1.IBeginTransactionRequest | undefined, - {} | undefined, - ] - >; + request?: protos.google.firestore.v1.IBeginTransactionRequest, + options?: CallOptions): + Promise<[ + protos.google.firestore.v1.IBeginTransactionResponse, + protos.google.firestore.v1.IBeginTransactionRequest|undefined, {}|undefined + ]>; beginTransaction( - request: protos.google.firestore.v1.IBeginTransactionRequest, - options: CallOptions, - callback: Callback< - protos.google.firestore.v1.IBeginTransactionResponse, - protos.google.firestore.v1.IBeginTransactionRequest | null | undefined, - {} | null | undefined - > - ): void; + request: protos.google.firestore.v1.IBeginTransactionRequest, + options: CallOptions, + callback: Callback< + protos.google.firestore.v1.IBeginTransactionResponse, + protos.google.firestore.v1.IBeginTransactionRequest|null|undefined, + {}|null|undefined>): void; beginTransaction( - request: protos.google.firestore.v1.IBeginTransactionRequest, - callback: Callback< - protos.google.firestore.v1.IBeginTransactionResponse, - protos.google.firestore.v1.IBeginTransactionRequest | null | undefined, - {} | null | undefined - > - ): void; + request: protos.google.firestore.v1.IBeginTransactionRequest, + callback: Callback< + protos.google.firestore.v1.IBeginTransactionResponse, + protos.google.firestore.v1.IBeginTransactionRequest|null|undefined, + {}|null|undefined>): void; beginTransaction( - request?: protos.google.firestore.v1.IBeginTransactionRequest, - optionsOrCallback?: - | CallOptions - | Callback< + request?: protos.google.firestore.v1.IBeginTransactionRequest, + optionsOrCallback?: CallOptions|Callback< protos.google.firestore.v1.IBeginTransactionResponse, - | protos.google.firestore.v1.IBeginTransactionRequest - | null - | undefined, - {} | null | undefined - >, - callback?: Callback< - protos.google.firestore.v1.IBeginTransactionResponse, - protos.google.firestore.v1.IBeginTransactionRequest | null | undefined, - {} | null | undefined - > - ): Promise< - [ - protos.google.firestore.v1.IBeginTransactionResponse, - protos.google.firestore.v1.IBeginTransactionRequest | undefined, - {} | undefined, - ] - > | void { + protos.google.firestore.v1.IBeginTransactionRequest|null|undefined, + {}|null|undefined>, + callback?: Callback< + protos.google.firestore.v1.IBeginTransactionResponse, + protos.google.firestore.v1.IBeginTransactionRequest|null|undefined, + {}|null|undefined>): + Promise<[ + protos.google.firestore.v1.IBeginTransactionResponse, + protos.google.firestore.v1.IBeginTransactionRequest|undefined, {}|undefined + ]>|void { request = request || {}; let options: CallOptions; if (typeof optionsOrCallback === 'function' && callback === undefined) { callback = optionsOrCallback; options = {}; - } else { + } + else { options = optionsOrCallback as CallOptions; } options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - options.otherArgs.headers['x-goog-request-params'] = - this._gaxModule.routingHeader.fromParams({ - database: request.database ?? '', + options.otherArgs.headers[ + 'x-goog-request-params' + ] = this._gaxModule.routingHeader.fromParams({ + 'database': request.database ?? '', + }); + this.initialize().catch(err => {throw err}); + this._log.info('beginTransaction request %j', request); + const wrappedCallback: Callback< + protos.google.firestore.v1.IBeginTransactionResponse, + protos.google.firestore.v1.IBeginTransactionRequest|null|undefined, + {}|null|undefined>|undefined = callback + ? (error, response, options, rawResponse) => { + this._log.info('beginTransaction response %j', response); + callback!(error, response, options, rawResponse); // We verified callback above. + } + : undefined; + return this.innerApiCalls.beginTransaction(request, options, wrappedCallback) + ?.then(([response, options, rawResponse]: [ + protos.google.firestore.v1.IBeginTransactionResponse, + protos.google.firestore.v1.IBeginTransactionRequest|undefined, + {}|undefined + ]) => { + this._log.info('beginTransaction response %j', response); + return [response, options, rawResponse]; }); - this.initialize(); - return this.innerApiCalls.beginTransaction(request, options, callback); } - /** - * Commits a transaction, while optionally updating documents. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.database - * Required. The database name. In the format: - * `projects/{project_id}/databases/{database_id}`. - * @param {number[]} request.writes - * The writes to apply. - * - * Always executed atomically and in order. - * @param {Buffer} request.transaction - * If set, applies all writes in this transaction, and commits it. - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Promise} - The promise which resolves to an array. - * The first element of the array is an object representing {@link protos.google.firestore.v1.CommitResponse|CommitResponse}. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } - * for more details and examples. - * @example - * region_tag:firestore_v1_generated_Firestore_Commit_async - */ +/** + * Commits a transaction, while optionally updating documents. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.database + * Required. The database name. In the format: + * `projects/{project_id}/databases/{database_id}`. + * @param {number[]} request.writes + * The writes to apply. + * + * Always executed atomically and in order. + * @param {Buffer} request.transaction + * If set, applies all writes in this transaction, and commits it. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is an object representing {@link protos.google.firestore.v1.CommitResponse|CommitResponse}. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } + * for more details and examples. + * @example + * region_tag:firestore_v1_generated_Firestore_Commit_async + */ commit( - request?: protos.google.firestore.v1.ICommitRequest, - options?: CallOptions - ): Promise< - [ - protos.google.firestore.v1.ICommitResponse, - protos.google.firestore.v1.ICommitRequest | undefined, - {} | undefined, - ] - >; + request?: protos.google.firestore.v1.ICommitRequest, + options?: CallOptions): + Promise<[ + protos.google.firestore.v1.ICommitResponse, + protos.google.firestore.v1.ICommitRequest|undefined, {}|undefined + ]>; commit( - request: protos.google.firestore.v1.ICommitRequest, - options: CallOptions, - callback: Callback< - protos.google.firestore.v1.ICommitResponse, - protos.google.firestore.v1.ICommitRequest | null | undefined, - {} | null | undefined - > - ): void; + request: protos.google.firestore.v1.ICommitRequest, + options: CallOptions, + callback: Callback< + protos.google.firestore.v1.ICommitResponse, + protos.google.firestore.v1.ICommitRequest|null|undefined, + {}|null|undefined>): void; commit( - request: protos.google.firestore.v1.ICommitRequest, - callback: Callback< - protos.google.firestore.v1.ICommitResponse, - protos.google.firestore.v1.ICommitRequest | null | undefined, - {} | null | undefined - > - ): void; + request: protos.google.firestore.v1.ICommitRequest, + callback: Callback< + protos.google.firestore.v1.ICommitResponse, + protos.google.firestore.v1.ICommitRequest|null|undefined, + {}|null|undefined>): void; commit( - request?: protos.google.firestore.v1.ICommitRequest, - optionsOrCallback?: - | CallOptions - | Callback< + request?: protos.google.firestore.v1.ICommitRequest, + optionsOrCallback?: CallOptions|Callback< protos.google.firestore.v1.ICommitResponse, - protos.google.firestore.v1.ICommitRequest | null | undefined, - {} | null | undefined - >, - callback?: Callback< - protos.google.firestore.v1.ICommitResponse, - protos.google.firestore.v1.ICommitRequest | null | undefined, - {} | null | undefined - > - ): Promise< - [ - protos.google.firestore.v1.ICommitResponse, - protos.google.firestore.v1.ICommitRequest | undefined, - {} | undefined, - ] - > | void { + protos.google.firestore.v1.ICommitRequest|null|undefined, + {}|null|undefined>, + callback?: Callback< + protos.google.firestore.v1.ICommitResponse, + protos.google.firestore.v1.ICommitRequest|null|undefined, + {}|null|undefined>): + Promise<[ + protos.google.firestore.v1.ICommitResponse, + protos.google.firestore.v1.ICommitRequest|undefined, {}|undefined + ]>|void { request = request || {}; let options: CallOptions; if (typeof optionsOrCallback === 'function' && callback === undefined) { callback = optionsOrCallback; options = {}; - } else { + } + else { options = optionsOrCallback as CallOptions; } options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - options.otherArgs.headers['x-goog-request-params'] = - this._gaxModule.routingHeader.fromParams({ - database: request.database ?? '', + options.otherArgs.headers[ + 'x-goog-request-params' + ] = this._gaxModule.routingHeader.fromParams({ + 'database': request.database ?? '', + }); + this.initialize().catch(err => {throw err}); + this._log.info('commit request %j', request); + const wrappedCallback: Callback< + protos.google.firestore.v1.ICommitResponse, + protos.google.firestore.v1.ICommitRequest|null|undefined, + {}|null|undefined>|undefined = callback + ? (error, response, options, rawResponse) => { + this._log.info('commit response %j', response); + callback!(error, response, options, rawResponse); // We verified callback above. + } + : undefined; + return this.innerApiCalls.commit(request, options, wrappedCallback) + ?.then(([response, options, rawResponse]: [ + protos.google.firestore.v1.ICommitResponse, + protos.google.firestore.v1.ICommitRequest|undefined, + {}|undefined + ]) => { + this._log.info('commit response %j', response); + return [response, options, rawResponse]; }); - this.initialize(); - return this.innerApiCalls.commit(request, options, callback); } - /** - * Rolls back a transaction. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.database - * Required. The database name. In the format: - * `projects/{project_id}/databases/{database_id}`. - * @param {Buffer} request.transaction - * Required. The transaction to roll back. - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Promise} - The promise which resolves to an array. - * The first element of the array is an object representing {@link protos.google.protobuf.Empty|Empty}. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } - * for more details and examples. - * @example - * region_tag:firestore_v1_generated_Firestore_Rollback_async - */ +/** + * Rolls back a transaction. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.database + * Required. The database name. In the format: + * `projects/{project_id}/databases/{database_id}`. + * @param {Buffer} request.transaction + * Required. The transaction to roll back. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is an object representing {@link protos.google.protobuf.Empty|Empty}. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } + * for more details and examples. + * @example + * region_tag:firestore_v1_generated_Firestore_Rollback_async + */ rollback( - request?: protos.google.firestore.v1.IRollbackRequest, - options?: CallOptions - ): Promise< - [ - protos.google.protobuf.IEmpty, - protos.google.firestore.v1.IRollbackRequest | undefined, - {} | undefined, - ] - >; + request?: protos.google.firestore.v1.IRollbackRequest, + options?: CallOptions): + Promise<[ + protos.google.protobuf.IEmpty, + protos.google.firestore.v1.IRollbackRequest|undefined, {}|undefined + ]>; rollback( - request: protos.google.firestore.v1.IRollbackRequest, - options: CallOptions, - callback: Callback< - protos.google.protobuf.IEmpty, - protos.google.firestore.v1.IRollbackRequest | null | undefined, - {} | null | undefined - > - ): void; + request: protos.google.firestore.v1.IRollbackRequest, + options: CallOptions, + callback: Callback< + protos.google.protobuf.IEmpty, + protos.google.firestore.v1.IRollbackRequest|null|undefined, + {}|null|undefined>): void; rollback( - request: protos.google.firestore.v1.IRollbackRequest, - callback: Callback< - protos.google.protobuf.IEmpty, - protos.google.firestore.v1.IRollbackRequest | null | undefined, - {} | null | undefined - > - ): void; + request: protos.google.firestore.v1.IRollbackRequest, + callback: Callback< + protos.google.protobuf.IEmpty, + protos.google.firestore.v1.IRollbackRequest|null|undefined, + {}|null|undefined>): void; rollback( - request?: protos.google.firestore.v1.IRollbackRequest, - optionsOrCallback?: - | CallOptions - | Callback< + request?: protos.google.firestore.v1.IRollbackRequest, + optionsOrCallback?: CallOptions|Callback< protos.google.protobuf.IEmpty, - protos.google.firestore.v1.IRollbackRequest | null | undefined, - {} | null | undefined - >, - callback?: Callback< - protos.google.protobuf.IEmpty, - protos.google.firestore.v1.IRollbackRequest | null | undefined, - {} | null | undefined - > - ): Promise< - [ - protos.google.protobuf.IEmpty, - protos.google.firestore.v1.IRollbackRequest | undefined, - {} | undefined, - ] - > | void { + protos.google.firestore.v1.IRollbackRequest|null|undefined, + {}|null|undefined>, + callback?: Callback< + protos.google.protobuf.IEmpty, + protos.google.firestore.v1.IRollbackRequest|null|undefined, + {}|null|undefined>): + Promise<[ + protos.google.protobuf.IEmpty, + protos.google.firestore.v1.IRollbackRequest|undefined, {}|undefined + ]>|void { request = request || {}; let options: CallOptions; if (typeof optionsOrCallback === 'function' && callback === undefined) { callback = optionsOrCallback; options = {}; - } else { + } + else { options = optionsOrCallback as CallOptions; } options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - options.otherArgs.headers['x-goog-request-params'] = - this._gaxModule.routingHeader.fromParams({ - database: request.database ?? '', + options.otherArgs.headers[ + 'x-goog-request-params' + ] = this._gaxModule.routingHeader.fromParams({ + 'database': request.database ?? '', + }); + this.initialize().catch(err => {throw err}); + this._log.info('rollback request %j', request); + const wrappedCallback: Callback< + protos.google.protobuf.IEmpty, + protos.google.firestore.v1.IRollbackRequest|null|undefined, + {}|null|undefined>|undefined = callback + ? (error, response, options, rawResponse) => { + this._log.info('rollback response %j', response); + callback!(error, response, options, rawResponse); // We verified callback above. + } + : undefined; + return this.innerApiCalls.rollback(request, options, wrappedCallback) + ?.then(([response, options, rawResponse]: [ + protos.google.protobuf.IEmpty, + protos.google.firestore.v1.IRollbackRequest|undefined, + {}|undefined + ]) => { + this._log.info('rollback response %j', response); + return [response, options, rawResponse]; }); - this.initialize(); - return this.innerApiCalls.rollback(request, options, callback); } - /** - * Applies a batch of write operations. - * - * The BatchWrite method does not apply the write operations atomically - * and can apply them out of order. Method does not allow more than one write - * per document. Each write succeeds or fails independently. See the - * {@link protos.google.firestore.v1.BatchWriteResponse|BatchWriteResponse} for the - * success status of each write. - * - * If you require an atomically applied set of writes, use - * {@link protos.google.firestore.v1.Firestore.Commit|Commit} instead. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.database - * Required. The database name. In the format: - * `projects/{project_id}/databases/{database_id}`. - * @param {number[]} request.writes - * The writes to apply. - * - * Method does not apply writes atomically and does not guarantee ordering. - * Each write succeeds or fails independently. You cannot write to the same - * document more than once per request. - * @param {number[]} request.labels - * Labels associated with this batch write. - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Promise} - The promise which resolves to an array. - * The first element of the array is an object representing {@link protos.google.firestore.v1.BatchWriteResponse|BatchWriteResponse}. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } - * for more details and examples. - * @example - * region_tag:firestore_v1_generated_Firestore_BatchWrite_async - */ +/** + * Applies a batch of write operations. + * + * The BatchWrite method does not apply the write operations atomically + * and can apply them out of order. Method does not allow more than one write + * per document. Each write succeeds or fails independently. See the + * {@link protos.google.firestore.v1.BatchWriteResponse|BatchWriteResponse} for the + * success status of each write. + * + * If you require an atomically applied set of writes, use + * {@link protos.google.firestore.v1.Firestore.Commit|Commit} instead. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.database + * Required. The database name. In the format: + * `projects/{project_id}/databases/{database_id}`. + * @param {number[]} request.writes + * The writes to apply. + * + * Method does not apply writes atomically and does not guarantee ordering. + * Each write succeeds or fails independently. You cannot write to the same + * document more than once per request. + * @param {number[]} request.labels + * Labels associated with this batch write. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is an object representing {@link protos.google.firestore.v1.BatchWriteResponse|BatchWriteResponse}. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } + * for more details and examples. + * @example + * region_tag:firestore_v1_generated_Firestore_BatchWrite_async + */ batchWrite( - request?: protos.google.firestore.v1.IBatchWriteRequest, - options?: CallOptions - ): Promise< - [ - protos.google.firestore.v1.IBatchWriteResponse, - protos.google.firestore.v1.IBatchWriteRequest | undefined, - {} | undefined, - ] - >; + request?: protos.google.firestore.v1.IBatchWriteRequest, + options?: CallOptions): + Promise<[ + protos.google.firestore.v1.IBatchWriteResponse, + protos.google.firestore.v1.IBatchWriteRequest|undefined, {}|undefined + ]>; batchWrite( - request: protos.google.firestore.v1.IBatchWriteRequest, - options: CallOptions, - callback: Callback< - protos.google.firestore.v1.IBatchWriteResponse, - protos.google.firestore.v1.IBatchWriteRequest | null | undefined, - {} | null | undefined - > - ): void; + request: protos.google.firestore.v1.IBatchWriteRequest, + options: CallOptions, + callback: Callback< + protos.google.firestore.v1.IBatchWriteResponse, + protos.google.firestore.v1.IBatchWriteRequest|null|undefined, + {}|null|undefined>): void; batchWrite( - request: protos.google.firestore.v1.IBatchWriteRequest, - callback: Callback< - protos.google.firestore.v1.IBatchWriteResponse, - protos.google.firestore.v1.IBatchWriteRequest | null | undefined, - {} | null | undefined - > - ): void; + request: protos.google.firestore.v1.IBatchWriteRequest, + callback: Callback< + protos.google.firestore.v1.IBatchWriteResponse, + protos.google.firestore.v1.IBatchWriteRequest|null|undefined, + {}|null|undefined>): void; batchWrite( - request?: protos.google.firestore.v1.IBatchWriteRequest, - optionsOrCallback?: - | CallOptions - | Callback< + request?: protos.google.firestore.v1.IBatchWriteRequest, + optionsOrCallback?: CallOptions|Callback< protos.google.firestore.v1.IBatchWriteResponse, - protos.google.firestore.v1.IBatchWriteRequest | null | undefined, - {} | null | undefined - >, - callback?: Callback< - protos.google.firestore.v1.IBatchWriteResponse, - protos.google.firestore.v1.IBatchWriteRequest | null | undefined, - {} | null | undefined - > - ): Promise< - [ - protos.google.firestore.v1.IBatchWriteResponse, - protos.google.firestore.v1.IBatchWriteRequest | undefined, - {} | undefined, - ] - > | void { + protos.google.firestore.v1.IBatchWriteRequest|null|undefined, + {}|null|undefined>, + callback?: Callback< + protos.google.firestore.v1.IBatchWriteResponse, + protos.google.firestore.v1.IBatchWriteRequest|null|undefined, + {}|null|undefined>): + Promise<[ + protos.google.firestore.v1.IBatchWriteResponse, + protos.google.firestore.v1.IBatchWriteRequest|undefined, {}|undefined + ]>|void { request = request || {}; let options: CallOptions; if (typeof optionsOrCallback === 'function' && callback === undefined) { callback = optionsOrCallback; options = {}; - } else { + } + else { options = optionsOrCallback as CallOptions; } options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - options.otherArgs.headers['x-goog-request-params'] = - this._gaxModule.routingHeader.fromParams({ - database: request.database ?? '', + options.otherArgs.headers[ + 'x-goog-request-params' + ] = this._gaxModule.routingHeader.fromParams({ + 'database': request.database ?? '', + }); + this.initialize().catch(err => {throw err}); + this._log.info('batchWrite request %j', request); + const wrappedCallback: Callback< + protos.google.firestore.v1.IBatchWriteResponse, + protos.google.firestore.v1.IBatchWriteRequest|null|undefined, + {}|null|undefined>|undefined = callback + ? (error, response, options, rawResponse) => { + this._log.info('batchWrite response %j', response); + callback!(error, response, options, rawResponse); // We verified callback above. + } + : undefined; + return this.innerApiCalls.batchWrite(request, options, wrappedCallback) + ?.then(([response, options, rawResponse]: [ + protos.google.firestore.v1.IBatchWriteResponse, + protos.google.firestore.v1.IBatchWriteRequest|undefined, + {}|undefined + ]) => { + this._log.info('batchWrite response %j', response); + return [response, options, rawResponse]; }); - this.initialize(); - return this.innerApiCalls.batchWrite(request, options, callback); } - /** - * Creates a new document. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.parent - * Required. The parent resource. For example: - * `projects/{project_id}/databases/{database_id}/documents` or - * `projects/{project_id}/databases/{database_id}/documents/chatrooms/{chatroom_id}` - * @param {string} request.collectionId - * Required. The collection ID, relative to `parent`, to list. For example: - * `chatrooms`. - * @param {string} request.documentId - * The client-assigned document ID to use for this document. - * - * Optional. If not specified, an ID will be assigned by the service. - * @param {google.firestore.v1.Document} request.document - * Required. The document to create. `name` must not be set. - * @param {google.firestore.v1.DocumentMask} request.mask - * The fields to return. If not set, returns all fields. - * - * If the document has a field that is not present in this mask, that field - * will not be returned in the response. - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Promise} - The promise which resolves to an array. - * The first element of the array is an object representing {@link protos.google.firestore.v1.Document|Document}. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } - * for more details and examples. - * @example - * region_tag:firestore_v1_generated_Firestore_CreateDocument_async - */ - createDocument( - request?: protos.google.firestore.v1.ICreateDocumentRequest, - options?: CallOptions - ): Promise< - [ - protos.google.firestore.v1.IDocument, - protos.google.firestore.v1.ICreateDocumentRequest | undefined, - {} | undefined, - ] - >; - createDocument( - request: protos.google.firestore.v1.ICreateDocumentRequest, - options: CallOptions, - callback: Callback< - protos.google.firestore.v1.IDocument, - protos.google.firestore.v1.ICreateDocumentRequest | null | undefined, - {} | null | undefined - > - ): void; +/** + * Creates a new document. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.parent + * Required. The parent resource. For example: + * `projects/{project_id}/databases/{database_id}/documents` or + * `projects/{project_id}/databases/{database_id}/documents/chatrooms/{chatroom_id}` + * @param {string} request.collectionId + * Required. The collection ID, relative to `parent`, to list. For example: + * `chatrooms`. + * @param {string} request.documentId + * The client-assigned document ID to use for this document. + * + * Optional. If not specified, an ID will be assigned by the service. + * @param {google.firestore.v1.Document} request.document + * Required. The document to create. `name` must not be set. + * @param {google.firestore.v1.DocumentMask} request.mask + * The fields to return. If not set, returns all fields. + * + * If the document has a field that is not present in this mask, that field + * will not be returned in the response. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is an object representing {@link protos.google.firestore.v1.Document|Document}. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } + * for more details and examples. + * @example + * region_tag:firestore_v1_generated_Firestore_CreateDocument_async + */ createDocument( - request: protos.google.firestore.v1.ICreateDocumentRequest, - callback: Callback< - protos.google.firestore.v1.IDocument, - protos.google.firestore.v1.ICreateDocumentRequest | null | undefined, - {} | null | undefined - > - ): void; + request?: protos.google.firestore.v1.ICreateDocumentRequest, + options?: CallOptions): + Promise<[ + protos.google.firestore.v1.IDocument, + protos.google.firestore.v1.ICreateDocumentRequest|undefined, {}|undefined + ]>; createDocument( - request?: protos.google.firestore.v1.ICreateDocumentRequest, - optionsOrCallback?: - | CallOptions - | Callback< + request: protos.google.firestore.v1.ICreateDocumentRequest, + options: CallOptions, + callback: Callback< protos.google.firestore.v1.IDocument, - protos.google.firestore.v1.ICreateDocumentRequest | null | undefined, - {} | null | undefined - >, - callback?: Callback< - protos.google.firestore.v1.IDocument, - protos.google.firestore.v1.ICreateDocumentRequest | null | undefined, - {} | null | undefined - > - ): Promise< - [ - protos.google.firestore.v1.IDocument, - protos.google.firestore.v1.ICreateDocumentRequest | undefined, - {} | undefined, - ] - > | void { + protos.google.firestore.v1.ICreateDocumentRequest|null|undefined, + {}|null|undefined>): void; + createDocument( + request: protos.google.firestore.v1.ICreateDocumentRequest, + callback: Callback< + protos.google.firestore.v1.IDocument, + protos.google.firestore.v1.ICreateDocumentRequest|null|undefined, + {}|null|undefined>): void; + createDocument( + request?: protos.google.firestore.v1.ICreateDocumentRequest, + optionsOrCallback?: CallOptions|Callback< + protos.google.firestore.v1.IDocument, + protos.google.firestore.v1.ICreateDocumentRequest|null|undefined, + {}|null|undefined>, + callback?: Callback< + protos.google.firestore.v1.IDocument, + protos.google.firestore.v1.ICreateDocumentRequest|null|undefined, + {}|null|undefined>): + Promise<[ + protos.google.firestore.v1.IDocument, + protos.google.firestore.v1.ICreateDocumentRequest|undefined, {}|undefined + ]>|void { request = request || {}; let options: CallOptions; if (typeof optionsOrCallback === 'function' && callback === undefined) { callback = optionsOrCallback; options = {}; - } else { + } + else { options = optionsOrCallback as CallOptions; } options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - options.otherArgs.headers['x-goog-request-params'] = - this._gaxModule.routingHeader.fromParams({ - parent: request.parent ?? '', - collection_id: request.collectionId ?? '', + options.otherArgs.headers[ + 'x-goog-request-params' + ] = this._gaxModule.routingHeader.fromParams({ + 'parent': request.parent ?? '', + 'collection_id': request.collectionId ?? '', + }); + this.initialize().catch(err => {throw err}); + this._log.info('createDocument request %j', request); + const wrappedCallback: Callback< + protos.google.firestore.v1.IDocument, + protos.google.firestore.v1.ICreateDocumentRequest|null|undefined, + {}|null|undefined>|undefined = callback + ? (error, response, options, rawResponse) => { + this._log.info('createDocument response %j', response); + callback!(error, response, options, rawResponse); // We verified callback above. + } + : undefined; + return this.innerApiCalls.createDocument(request, options, wrappedCallback) + ?.then(([response, options, rawResponse]: [ + protos.google.firestore.v1.IDocument, + protos.google.firestore.v1.ICreateDocumentRequest|undefined, + {}|undefined + ]) => { + this._log.info('createDocument response %j', response); + return [response, options, rawResponse]; }); - this.initialize(); - return this.innerApiCalls.createDocument(request, options, callback); } - /** - * Gets multiple documents. - * - * Documents returned by this method are not guaranteed to be returned in the - * same order that they were requested. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.database - * Required. The database name. In the format: - * `projects/{project_id}/databases/{database_id}`. - * @param {string[]} request.documents - * The names of the documents to retrieve. In the format: - * `projects/{project_id}/databases/{database_id}/documents/{document_path}`. - * The request will fail if any of the document is not a child resource of the - * given `database`. Duplicate names will be elided. - * @param {google.firestore.v1.DocumentMask} request.mask - * The fields to return. If not set, returns all fields. - * - * If a document has a field that is not present in this mask, that field will - * not be returned in the response. - * @param {Buffer} request.transaction - * Reads documents in a transaction. - * @param {google.firestore.v1.TransactionOptions} request.newTransaction - * Starts a new transaction and reads the documents. - * Defaults to a read-only transaction. - * The new transaction ID will be returned as the first response in the - * stream. - * @param {google.protobuf.Timestamp} request.readTime - * Reads documents as they were at the given time. - * - * This must be a microsecond precision timestamp within the past one hour, - * or if Point-in-Time Recovery is enabled, can additionally be a whole - * minute timestamp within the past 7 days. - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Stream} - * An object stream which emits {@link protos.google.firestore.v1.BatchGetDocumentsResponse|BatchGetDocumentsResponse} on 'data' event. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#server-streaming | documentation } - * for more details and examples. - * @example - * region_tag:firestore_v1_generated_Firestore_BatchGetDocuments_async - */ +/** + * Gets multiple documents. + * + * Documents returned by this method are not guaranteed to be returned in the + * same order that they were requested. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.database + * Required. The database name. In the format: + * `projects/{project_id}/databases/{database_id}`. + * @param {string[]} request.documents + * The names of the documents to retrieve. In the format: + * `projects/{project_id}/databases/{database_id}/documents/{document_path}`. + * The request will fail if any of the document is not a child resource of the + * given `database`. Duplicate names will be elided. + * @param {google.firestore.v1.DocumentMask} request.mask + * The fields to return. If not set, returns all fields. + * + * If a document has a field that is not present in this mask, that field will + * not be returned in the response. + * @param {Buffer} request.transaction + * Reads documents in a transaction. + * @param {google.firestore.v1.TransactionOptions} request.newTransaction + * Starts a new transaction and reads the documents. + * Defaults to a read-only transaction. + * The new transaction ID will be returned as the first response in the + * stream. + * @param {google.protobuf.Timestamp} request.readTime + * Reads documents as they were at the given time. + * + * This must be a microsecond precision timestamp within the past one hour, + * or if Point-in-Time Recovery is enabled, can additionally be a whole + * minute timestamp within the past 7 days. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Stream} + * An object stream which emits {@link protos.google.firestore.v1.BatchGetDocumentsResponse|BatchGetDocumentsResponse} on 'data' event. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#server-streaming | documentation } + * for more details and examples. + * @example + * region_tag:firestore_v1_generated_Firestore_BatchGetDocuments_async + */ batchGetDocuments( - request?: protos.google.firestore.v1.IBatchGetDocumentsRequest, - options?: CallOptions - ): gax.CancellableStream { + request?: protos.google.firestore.v1.IBatchGetDocumentsRequest, + options?: CallOptions): + gax.CancellableStream{ request = request || {}; options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - options.otherArgs.headers['x-goog-request-params'] = - this._gaxModule.routingHeader.fromParams({ - database: request.database ?? '', - }); - this.initialize(); + options.otherArgs.headers[ + 'x-goog-request-params' + ] = this._gaxModule.routingHeader.fromParams({ + 'database': request.database ?? '', + }); + this.initialize().catch(err => {throw err}); + this._log.info('batchGetDocuments stream %j', options); return this.innerApiCalls.batchGetDocuments(request, options); } - /** - * Runs a query. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.parent - * Required. The parent resource name. In the format: - * `projects/{project_id}/databases/{database_id}/documents` or - * `projects/{project_id}/databases/{database_id}/documents/{document_path}`. - * For example: - * `projects/my-project/databases/my-database/documents` or - * `projects/my-project/databases/my-database/documents/chatrooms/my-chatroom` - * @param {google.firestore.v1.StructuredQuery} request.structuredQuery - * A structured query. - * @param {Buffer} request.transaction - * Run the query within an already active transaction. - * - * The value here is the opaque transaction ID to execute the query in. - * @param {google.firestore.v1.TransactionOptions} request.newTransaction - * Starts a new transaction and reads the documents. - * Defaults to a read-only transaction. - * The new transaction ID will be returned as the first response in the - * stream. - * @param {google.protobuf.Timestamp} request.readTime - * Reads documents as they were at the given time. - * - * This must be a microsecond precision timestamp within the past one hour, - * or if Point-in-Time Recovery is enabled, can additionally be a whole - * minute timestamp within the past 7 days. - * @param {google.firestore.v1.ExplainOptions} [request.explainOptions] - * Optional. Explain options for the query. If set, additional query - * statistics will be returned. If not, only query results will be returned. - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Stream} - * An object stream which emits {@link protos.google.firestore.v1.RunQueryResponse|RunQueryResponse} on 'data' event. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#server-streaming | documentation } - * for more details and examples. - * @example - * region_tag:firestore_v1_generated_Firestore_RunQuery_async - */ +/** + * Runs a query. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.parent + * Required. The parent resource name. In the format: + * `projects/{project_id}/databases/{database_id}/documents` or + * `projects/{project_id}/databases/{database_id}/documents/{document_path}`. + * For example: + * `projects/my-project/databases/my-database/documents` or + * `projects/my-project/databases/my-database/documents/chatrooms/my-chatroom` + * @param {google.firestore.v1.StructuredQuery} request.structuredQuery + * A structured query. + * @param {Buffer} request.transaction + * Run the query within an already active transaction. + * + * The value here is the opaque transaction ID to execute the query in. + * @param {google.firestore.v1.TransactionOptions} request.newTransaction + * Starts a new transaction and reads the documents. + * Defaults to a read-only transaction. + * The new transaction ID will be returned as the first response in the + * stream. + * @param {google.protobuf.Timestamp} request.readTime + * Reads documents as they were at the given time. + * + * This must be a microsecond precision timestamp within the past one hour, + * or if Point-in-Time Recovery is enabled, can additionally be a whole + * minute timestamp within the past 7 days. + * @param {google.firestore.v1.ExplainOptions} [request.explainOptions] + * Optional. Explain options for the query. If set, additional query + * statistics will be returned. If not, only query results will be returned. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Stream} + * An object stream which emits {@link protos.google.firestore.v1.RunQueryResponse|RunQueryResponse} on 'data' event. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#server-streaming | documentation } + * for more details and examples. + * @example + * region_tag:firestore_v1_generated_Firestore_RunQuery_async + */ runQuery( - request?: protos.google.firestore.v1.IRunQueryRequest, - options?: CallOptions - ): gax.CancellableStream { + request?: protos.google.firestore.v1.IRunQueryRequest, + options?: CallOptions): + gax.CancellableStream{ request = request || {}; options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - options.otherArgs.headers['x-goog-request-params'] = - this._gaxModule.routingHeader.fromParams({ - parent: request.parent ?? '', - }); - this.initialize(); + options.otherArgs.headers[ + 'x-goog-request-params' + ] = this._gaxModule.routingHeader.fromParams({ + 'parent': request.parent ?? '', + }); + this.initialize().catch(err => {throw err}); + this._log.info('runQuery stream %j', options); return this.innerApiCalls.runQuery(request, options); } +/** + * Executes a pipeline query. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.database + * Required. Database identifier, in the form + * `projects/{project}/databases/{database}`. + * @param {google.firestore.v1.StructuredPipeline} request.structuredPipeline + * A pipelined operation. + * @param {Buffer} request.transaction + * Run the query within an already active transaction. + * + * The value here is the opaque transaction ID to execute the query in. + * @param {google.firestore.v1.TransactionOptions} request.newTransaction + * Execute the pipeline in a new transaction. + * + * The identifier of the newly created transaction will be returned in the + * first response on the stream. This defaults to a read-only transaction. + * @param {google.protobuf.Timestamp} request.readTime + * Execute the pipeline in a snapshot transaction at the given time. + * + * This must be a microsecond precision timestamp within the past one hour, + * or if Point-in-Time Recovery is enabled, can additionally be a whole + * minute timestamp within the past 7 days. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Stream} + * An object stream which emits {@link protos.google.firestore.v1.ExecutePipelineResponse|ExecutePipelineResponse} on 'data' event. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#server-streaming | documentation } + * for more details and examples. + * @example + * region_tag:firestore_v1_generated_Firestore_ExecutePipeline_async + */ executePipeline( - request?: protos.google.firestore.v1.IExecutePipelineRequest, - options?: CallOptions - ): gax.CancellableStream { + request?: protos.google.firestore.v1.IExecutePipelineRequest, + options?: CallOptions): + gax.CancellableStream{ request = request || {}; options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - options.otherArgs.headers['x-goog-request-params'] = - this._gaxModule.routingHeader.fromParams({ - parent: request.database ? `${request.database}/documents` : '', - }); - this.initialize(); + let routingParameter = {}; + { + const fieldValue = request.database; + if (fieldValue !== undefined && fieldValue !== null) { + const match = fieldValue.toString().match(RegExp('projects/(?[^/]+)(?:/.*)?')); + if (match) { + const parameterValue = match.groups?.['project_id'] ?? fieldValue; + Object.assign(routingParameter, { project_id: parameterValue }); + } + } + } + { + const fieldValue = request.database; + if (fieldValue !== undefined && fieldValue !== null) { + const match = fieldValue.toString().match(RegExp('projects/[^/]+/databases/(?[^/]+)(?:/.*)?')); + if (match) { + const parameterValue = match.groups?.['database_id'] ?? fieldValue; + Object.assign(routingParameter, { database_id: parameterValue }); + } + } + } + options.otherArgs.headers[ + 'x-goog-request-params' + ] = this._gaxModule.routingHeader.fromParams( + routingParameter + ); + this.initialize().catch(err => {throw err}); + this._log.info('executePipeline stream %j', options); return this.innerApiCalls.executePipeline(request, options); } - /** - * Runs an aggregation query. - * - * Rather than producing {@link protos.google.firestore.v1.Document|Document} results like - * {@link protos.google.firestore.v1.Firestore.RunQuery|Firestore.RunQuery}, this API - * allows running an aggregation to produce a series of - * {@link protos.google.firestore.v1.AggregationResult|AggregationResult} server-side. - * - * High-Level Example: - * - * ``` - * -- Return the number of documents in table given a filter. - * SELECT COUNT(*) FROM ( SELECT * FROM k where a = true ); - * ``` - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.parent - * Required. The parent resource name. In the format: - * `projects/{project_id}/databases/{database_id}/documents` or - * `projects/{project_id}/databases/{database_id}/documents/{document_path}`. - * For example: - * `projects/my-project/databases/my-database/documents` or - * `projects/my-project/databases/my-database/documents/chatrooms/my-chatroom` - * @param {google.firestore.v1.StructuredAggregationQuery} request.structuredAggregationQuery - * An aggregation query. - * @param {Buffer} request.transaction - * Run the aggregation within an already active transaction. - * - * The value here is the opaque transaction ID to execute the query in. - * @param {google.firestore.v1.TransactionOptions} request.newTransaction - * Starts a new transaction as part of the query, defaulting to read-only. - * - * The new transaction ID will be returned as the first response in the - * stream. - * @param {google.protobuf.Timestamp} request.readTime - * Executes the query at the given timestamp. - * - * This must be a microsecond precision timestamp within the past one hour, - * or if Point-in-Time Recovery is enabled, can additionally be a whole - * minute timestamp within the past 7 days. - * @param {google.firestore.v1.ExplainOptions} [request.explainOptions] - * Optional. Explain options for the query. If set, additional query - * statistics will be returned. If not, only query results will be returned. - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Stream} - * An object stream which emits {@link protos.google.firestore.v1.RunAggregationQueryResponse|RunAggregationQueryResponse} on 'data' event. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#server-streaming | documentation } - * for more details and examples. - * @example - * region_tag:firestore_v1_generated_Firestore_RunAggregationQuery_async - */ +/** + * Runs an aggregation query. + * + * Rather than producing {@link protos.google.firestore.v1.Document|Document} results like + * {@link protos.google.firestore.v1.Firestore.RunQuery|Firestore.RunQuery}, this API + * allows running an aggregation to produce a series of + * {@link protos.google.firestore.v1.AggregationResult|AggregationResult} server-side. + * + * High-Level Example: + * + * ``` + * -- Return the number of documents in table given a filter. + * SELECT COUNT(*) FROM ( SELECT * FROM k where a = true ); + * ``` + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.parent + * Required. The parent resource name. In the format: + * `projects/{project_id}/databases/{database_id}/documents` or + * `projects/{project_id}/databases/{database_id}/documents/{document_path}`. + * For example: + * `projects/my-project/databases/my-database/documents` or + * `projects/my-project/databases/my-database/documents/chatrooms/my-chatroom` + * @param {google.firestore.v1.StructuredAggregationQuery} request.structuredAggregationQuery + * An aggregation query. + * @param {Buffer} request.transaction + * Run the aggregation within an already active transaction. + * + * The value here is the opaque transaction ID to execute the query in. + * @param {google.firestore.v1.TransactionOptions} request.newTransaction + * Starts a new transaction as part of the query, defaulting to read-only. + * + * The new transaction ID will be returned as the first response in the + * stream. + * @param {google.protobuf.Timestamp} request.readTime + * Executes the query at the given timestamp. + * + * This must be a microsecond precision timestamp within the past one hour, + * or if Point-in-Time Recovery is enabled, can additionally be a whole + * minute timestamp within the past 7 days. + * @param {google.firestore.v1.ExplainOptions} [request.explainOptions] + * Optional. Explain options for the query. If set, additional query + * statistics will be returned. If not, only query results will be returned. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Stream} + * An object stream which emits {@link protos.google.firestore.v1.RunAggregationQueryResponse|RunAggregationQueryResponse} on 'data' event. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#server-streaming | documentation } + * for more details and examples. + * @example + * region_tag:firestore_v1_generated_Firestore_RunAggregationQuery_async + */ runAggregationQuery( - request?: protos.google.firestore.v1.IRunAggregationQueryRequest, - options?: CallOptions - ): gax.CancellableStream { + request?: protos.google.firestore.v1.IRunAggregationQueryRequest, + options?: CallOptions): + gax.CancellableStream{ request = request || {}; options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - options.otherArgs.headers['x-goog-request-params'] = - this._gaxModule.routingHeader.fromParams({ - parent: request.parent ?? '', - }); - this.initialize(); + options.otherArgs.headers[ + 'x-goog-request-params' + ] = this._gaxModule.routingHeader.fromParams({ + 'parent': request.parent ?? '', + }); + this.initialize().catch(err => {throw err}); + this._log.info('runAggregationQuery stream %j', options); return this.innerApiCalls.runAggregationQuery(request, options); } - /** - * Streams batches of document updates and deletes, in order. This method is - * only available via gRPC or WebChannel (not REST). - * - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Stream} - * An object stream which is both readable and writable. It accepts objects - * representing {@link protos.google.firestore.v1.WriteRequest|WriteRequest} for write() method, and - * will emit objects representing {@link protos.google.firestore.v1.WriteResponse|WriteResponse} on 'data' event asynchronously. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#bi-directional-streaming | documentation } - * for more details and examples. - * @example - * region_tag:firestore_v1_generated_Firestore_Write_async - */ - write(options?: CallOptions): gax.CancellableStream { - this.initialize(); +/** + * Streams batches of document updates and deletes, in order. This method is + * only available via gRPC or WebChannel (not REST). + * + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Stream} + * An object stream which is both readable and writable. It accepts objects + * representing {@link protos.google.firestore.v1.WriteRequest|WriteRequest} for write() method, and + * will emit objects representing {@link protos.google.firestore.v1.WriteResponse|WriteResponse} on 'data' event asynchronously. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#bi-directional-streaming | documentation } + * for more details and examples. + * @example + * region_tag:firestore_v1_generated_Firestore_Write_async + */ + write( + options?: CallOptions): + gax.CancellableStream { + this.initialize().catch(err => {throw err}); + this._log.info('write stream %j', options); return this.innerApiCalls.write(null, options); } - /** - * Listens to changes. This method is only available via gRPC or WebChannel - * (not REST). - * - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Stream} - * An object stream which is both readable and writable. It accepts objects - * representing {@link protos.google.firestore.v1.ListenRequest|ListenRequest} for write() method, and - * will emit objects representing {@link protos.google.firestore.v1.ListenResponse|ListenResponse} on 'data' event asynchronously. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#bi-directional-streaming | documentation } - * for more details and examples. - * @example - * region_tag:firestore_v1_generated_Firestore_Listen_async - */ - listen(options?: CallOptions): gax.CancellableStream { - this.initialize(); +/** + * Listens to changes. This method is only available via gRPC or WebChannel + * (not REST). + * + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Stream} + * An object stream which is both readable and writable. It accepts objects + * representing {@link protos.google.firestore.v1.ListenRequest|ListenRequest} for write() method, and + * will emit objects representing {@link protos.google.firestore.v1.ListenResponse|ListenResponse} on 'data' event asynchronously. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#bi-directional-streaming | documentation } + * for more details and examples. + * @example + * region_tag:firestore_v1_generated_Firestore_Listen_async + */ + listen( + options?: CallOptions): + gax.CancellableStream { + this.initialize().catch(err => {throw err}); + this._log.info('listen stream %j', options); return this.innerApiCalls.listen(null, options); } - /** - * Lists documents. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.parent - * Required. The parent resource name. In the format: - * `projects/{project_id}/databases/{database_id}/documents` or - * `projects/{project_id}/databases/{database_id}/documents/{document_path}`. - * - * For example: - * `projects/my-project/databases/my-database/documents` or - * `projects/my-project/databases/my-database/documents/chatrooms/my-chatroom` - * @param {string} [request.collectionId] - * Optional. The collection ID, relative to `parent`, to list. - * - * For example: `chatrooms` or `messages`. - * - * This is optional, and when not provided, Firestore will list documents - * from all collections under the provided `parent`. - * @param {number} [request.pageSize] - * Optional. The maximum number of documents to return in a single response. - * - * Firestore may return fewer than this value. - * @param {string} [request.pageToken] - * Optional. A page token, received from a previous `ListDocuments` response. - * - * Provide this to retrieve the subsequent page. When paginating, all other - * parameters (with the exception of `page_size`) must match the values set - * in the request that generated the page token. - * @param {string} [request.orderBy] - * Optional. The optional ordering of the documents to return. - * - * For example: `priority desc, __name__ desc`. - * - * This mirrors the {@link protos.google.firestore.v1.StructuredQuery.order_by|`ORDER BY`} - * used in Firestore queries but in a string representation. When absent, - * documents are ordered based on `__name__ ASC`. - * @param {google.firestore.v1.DocumentMask} [request.mask] - * Optional. The fields to return. If not set, returns all fields. - * - * If a document has a field that is not present in this mask, that field - * will not be returned in the response. - * @param {Buffer} request.transaction - * Perform the read as part of an already active transaction. - * @param {google.protobuf.Timestamp} request.readTime - * Perform the read at the provided time. - * - * This must be a microsecond precision timestamp within the past one hour, - * or if Point-in-Time Recovery is enabled, can additionally be a whole - * minute timestamp within the past 7 days. - * @param {boolean} request.showMissing - * If the list should show missing documents. - * - * A document is missing if it does not exist, but there are sub-documents - * nested underneath it. When true, such missing documents will be returned - * with a key but will not have fields, - * {@link protos.google.firestore.v1.Document.create_time|`create_time`}, or - * {@link protos.google.firestore.v1.Document.update_time|`update_time`} set. - * - * Requests with `show_missing` may not specify `where` or `order_by`. - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Promise} - The promise which resolves to an array. - * The first element of the array is Array of {@link protos.google.firestore.v1.Document|Document}. - * The client library will perform auto-pagination by default: it will call the API as many - * times as needed and will merge results from all the pages into this array. - * Note that it can affect your quota. - * We recommend using `listDocumentsAsync()` - * method described below for async iteration which you can stop as needed. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#auto-pagination | documentation } - * for more details and examples. - */ + /** + * Lists documents. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.parent + * Required. The parent resource name. In the format: + * `projects/{project_id}/databases/{database_id}/documents` or + * `projects/{project_id}/databases/{database_id}/documents/{document_path}`. + * + * For example: + * `projects/my-project/databases/my-database/documents` or + * `projects/my-project/databases/my-database/documents/chatrooms/my-chatroom` + * @param {string} [request.collectionId] + * Optional. The collection ID, relative to `parent`, to list. + * + * For example: `chatrooms` or `messages`. + * + * This is optional, and when not provided, Firestore will list documents + * from all collections under the provided `parent`. + * @param {number} [request.pageSize] + * Optional. The maximum number of documents to return in a single response. + * + * Firestore may return fewer than this value. + * @param {string} [request.pageToken] + * Optional. A page token, received from a previous `ListDocuments` response. + * + * Provide this to retrieve the subsequent page. When paginating, all other + * parameters (with the exception of `page_size`) must match the values set + * in the request that generated the page token. + * @param {string} [request.orderBy] + * Optional. The optional ordering of the documents to return. + * + * For example: `priority desc, __name__ desc`. + * + * This mirrors the {@link protos.google.firestore.v1.StructuredQuery.order_by|`ORDER BY`} + * used in Firestore queries but in a string representation. When absent, + * documents are ordered based on `__name__ ASC`. + * @param {google.firestore.v1.DocumentMask} [request.mask] + * Optional. The fields to return. If not set, returns all fields. + * + * If a document has a field that is not present in this mask, that field + * will not be returned in the response. + * @param {Buffer} request.transaction + * Perform the read as part of an already active transaction. + * @param {google.protobuf.Timestamp} request.readTime + * Perform the read at the provided time. + * + * This must be a microsecond precision timestamp within the past one hour, + * or if Point-in-Time Recovery is enabled, can additionally be a whole + * minute timestamp within the past 7 days. + * @param {boolean} request.showMissing + * If the list should show missing documents. + * + * A document is missing if it does not exist, but there are sub-documents + * nested underneath it. When true, such missing documents will be returned + * with a key but will not have fields, + * {@link protos.google.firestore.v1.Document.create_time|`create_time`}, or + * {@link protos.google.firestore.v1.Document.update_time|`update_time`} set. + * + * Requests with `show_missing` may not specify `where` or `order_by`. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is Array of {@link protos.google.firestore.v1.Document|Document}. + * The client library will perform auto-pagination by default: it will call the API as many + * times as needed and will merge results from all the pages into this array. + * Note that it can affect your quota. + * We recommend using `listDocumentsAsync()` + * method described below for async iteration which you can stop as needed. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#auto-pagination | documentation } + * for more details and examples. + */ listDocuments( - request?: protos.google.firestore.v1.IListDocumentsRequest, - options?: CallOptions - ): Promise< - [ - protos.google.firestore.v1.IDocument[], - protos.google.firestore.v1.IListDocumentsRequest | null, - protos.google.firestore.v1.IListDocumentsResponse, - ] - >; + request?: protos.google.firestore.v1.IListDocumentsRequest, + options?: CallOptions): + Promise<[ + protos.google.firestore.v1.IDocument[], + protos.google.firestore.v1.IListDocumentsRequest|null, + protos.google.firestore.v1.IListDocumentsResponse + ]>; listDocuments( - request: protos.google.firestore.v1.IListDocumentsRequest, - options: CallOptions, - callback: PaginationCallback< - protos.google.firestore.v1.IListDocumentsRequest, - protos.google.firestore.v1.IListDocumentsResponse | null | undefined, - protos.google.firestore.v1.IDocument - > - ): void; + request: protos.google.firestore.v1.IListDocumentsRequest, + options: CallOptions, + callback: PaginationCallback< + protos.google.firestore.v1.IListDocumentsRequest, + protos.google.firestore.v1.IListDocumentsResponse|null|undefined, + protos.google.firestore.v1.IDocument>): void; listDocuments( - request: protos.google.firestore.v1.IListDocumentsRequest, - callback: PaginationCallback< - protos.google.firestore.v1.IListDocumentsRequest, - protos.google.firestore.v1.IListDocumentsResponse | null | undefined, - protos.google.firestore.v1.IDocument - > - ): void; + request: protos.google.firestore.v1.IListDocumentsRequest, + callback: PaginationCallback< + protos.google.firestore.v1.IListDocumentsRequest, + protos.google.firestore.v1.IListDocumentsResponse|null|undefined, + protos.google.firestore.v1.IDocument>): void; listDocuments( - request?: protos.google.firestore.v1.IListDocumentsRequest, - optionsOrCallback?: - | CallOptions - | PaginationCallback< + request?: protos.google.firestore.v1.IListDocumentsRequest, + optionsOrCallback?: CallOptions|PaginationCallback< protos.google.firestore.v1.IListDocumentsRequest, - protos.google.firestore.v1.IListDocumentsResponse | null | undefined, - protos.google.firestore.v1.IDocument - >, - callback?: PaginationCallback< - protos.google.firestore.v1.IListDocumentsRequest, - protos.google.firestore.v1.IListDocumentsResponse | null | undefined, - protos.google.firestore.v1.IDocument - > - ): Promise< - [ - protos.google.firestore.v1.IDocument[], - protos.google.firestore.v1.IListDocumentsRequest | null, - protos.google.firestore.v1.IListDocumentsResponse, - ] - > | void { + protos.google.firestore.v1.IListDocumentsResponse|null|undefined, + protos.google.firestore.v1.IDocument>, + callback?: PaginationCallback< + protos.google.firestore.v1.IListDocumentsRequest, + protos.google.firestore.v1.IListDocumentsResponse|null|undefined, + protos.google.firestore.v1.IDocument>): + Promise<[ + protos.google.firestore.v1.IDocument[], + protos.google.firestore.v1.IListDocumentsRequest|null, + protos.google.firestore.v1.IListDocumentsResponse + ]>|void { request = request || {}; let options: CallOptions; if (typeof optionsOrCallback === 'function' && callback === undefined) { callback = optionsOrCallback; options = {}; - } else { + } + else { options = optionsOrCallback as CallOptions; } options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - options.otherArgs.headers['x-goog-request-params'] = - this._gaxModule.routingHeader.fromParams({ - parent: request.parent ?? '', - collection_id: request.collectionId ?? '', + options.otherArgs.headers[ + 'x-goog-request-params' + ] = this._gaxModule.routingHeader.fromParams({ + 'parent': request.parent ?? '', + 'collection_id': request.collectionId ?? '', + }); + this.initialize().catch(err => {throw err}); + const wrappedCallback: PaginationCallback< + protos.google.firestore.v1.IListDocumentsRequest, + protos.google.firestore.v1.IListDocumentsResponse|null|undefined, + protos.google.firestore.v1.IDocument>|undefined = callback + ? (error, values, nextPageRequest, rawResponse) => { + this._log.info('listDocuments values %j', values); + callback!(error, values, nextPageRequest, rawResponse); // We verified callback above. + } + : undefined; + this._log.info('listDocuments request %j', request); + return this.innerApiCalls + .listDocuments(request, options, wrappedCallback) + ?.then(([response, input, output]: [ + protos.google.firestore.v1.IDocument[], + protos.google.firestore.v1.IListDocumentsRequest|null, + protos.google.firestore.v1.IListDocumentsResponse + ]) => { + this._log.info('listDocuments values %j', response); + return [response, input, output]; }); - this.initialize(); - return this.innerApiCalls.listDocuments(request, options, callback); } - /** - * Equivalent to `listDocuments`, but returns a NodeJS Stream object. - * @param {Object} request - * The request object that will be sent. - * @param {string} request.parent - * Required. The parent resource name. In the format: - * `projects/{project_id}/databases/{database_id}/documents` or - * `projects/{project_id}/databases/{database_id}/documents/{document_path}`. - * - * For example: - * `projects/my-project/databases/my-database/documents` or - * `projects/my-project/databases/my-database/documents/chatrooms/my-chatroom` - * @param {string} [request.collectionId] - * Optional. The collection ID, relative to `parent`, to list. - * - * For example: `chatrooms` or `messages`. - * - * This is optional, and when not provided, Firestore will list documents - * from all collections under the provided `parent`. - * @param {number} [request.pageSize] - * Optional. The maximum number of documents to return in a single response. - * - * Firestore may return fewer than this value. - * @param {string} [request.pageToken] - * Optional. A page token, received from a previous `ListDocuments` response. - * - * Provide this to retrieve the subsequent page. When paginating, all other - * parameters (with the exception of `page_size`) must match the values set - * in the request that generated the page token. - * @param {string} [request.orderBy] - * Optional. The optional ordering of the documents to return. - * - * For example: `priority desc, __name__ desc`. - * - * This mirrors the {@link protos.google.firestore.v1.StructuredQuery.order_by|`ORDER BY`} - * used in Firestore queries but in a string representation. When absent, - * documents are ordered based on `__name__ ASC`. - * @param {google.firestore.v1.DocumentMask} [request.mask] - * Optional. The fields to return. If not set, returns all fields. - * - * If a document has a field that is not present in this mask, that field - * will not be returned in the response. - * @param {Buffer} request.transaction - * Perform the read as part of an already active transaction. - * @param {google.protobuf.Timestamp} request.readTime - * Perform the read at the provided time. - * - * This must be a microsecond precision timestamp within the past one hour, - * or if Point-in-Time Recovery is enabled, can additionally be a whole - * minute timestamp within the past 7 days. - * @param {boolean} request.showMissing - * If the list should show missing documents. - * - * A document is missing if it does not exist, but there are sub-documents - * nested underneath it. When true, such missing documents will be returned - * with a key but will not have fields, - * {@link protos.google.firestore.v1.Document.create_time|`create_time`}, or - * {@link protos.google.firestore.v1.Document.update_time|`update_time`} set. - * - * Requests with `show_missing` may not specify `where` or `order_by`. - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Stream} - * An object stream which emits an object representing {@link protos.google.firestore.v1.Document|Document} on 'data' event. - * The client library will perform auto-pagination by default: it will call the API as many - * times as needed. Note that it can affect your quota. - * We recommend using `listDocumentsAsync()` - * method described below for async iteration which you can stop as needed. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#auto-pagination | documentation } - * for more details and examples. - */ +/** + * Equivalent to `listDocuments`, but returns a NodeJS Stream object. + * @param {Object} request + * The request object that will be sent. + * @param {string} request.parent + * Required. The parent resource name. In the format: + * `projects/{project_id}/databases/{database_id}/documents` or + * `projects/{project_id}/databases/{database_id}/documents/{document_path}`. + * + * For example: + * `projects/my-project/databases/my-database/documents` or + * `projects/my-project/databases/my-database/documents/chatrooms/my-chatroom` + * @param {string} [request.collectionId] + * Optional. The collection ID, relative to `parent`, to list. + * + * For example: `chatrooms` or `messages`. + * + * This is optional, and when not provided, Firestore will list documents + * from all collections under the provided `parent`. + * @param {number} [request.pageSize] + * Optional. The maximum number of documents to return in a single response. + * + * Firestore may return fewer than this value. + * @param {string} [request.pageToken] + * Optional. A page token, received from a previous `ListDocuments` response. + * + * Provide this to retrieve the subsequent page. When paginating, all other + * parameters (with the exception of `page_size`) must match the values set + * in the request that generated the page token. + * @param {string} [request.orderBy] + * Optional. The optional ordering of the documents to return. + * + * For example: `priority desc, __name__ desc`. + * + * This mirrors the {@link protos.google.firestore.v1.StructuredQuery.order_by|`ORDER BY`} + * used in Firestore queries but in a string representation. When absent, + * documents are ordered based on `__name__ ASC`. + * @param {google.firestore.v1.DocumentMask} [request.mask] + * Optional. The fields to return. If not set, returns all fields. + * + * If a document has a field that is not present in this mask, that field + * will not be returned in the response. + * @param {Buffer} request.transaction + * Perform the read as part of an already active transaction. + * @param {google.protobuf.Timestamp} request.readTime + * Perform the read at the provided time. + * + * This must be a microsecond precision timestamp within the past one hour, + * or if Point-in-Time Recovery is enabled, can additionally be a whole + * minute timestamp within the past 7 days. + * @param {boolean} request.showMissing + * If the list should show missing documents. + * + * A document is missing if it does not exist, but there are sub-documents + * nested underneath it. When true, such missing documents will be returned + * with a key but will not have fields, + * {@link protos.google.firestore.v1.Document.create_time|`create_time`}, or + * {@link protos.google.firestore.v1.Document.update_time|`update_time`} set. + * + * Requests with `show_missing` may not specify `where` or `order_by`. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Stream} + * An object stream which emits an object representing {@link protos.google.firestore.v1.Document|Document} on 'data' event. + * The client library will perform auto-pagination by default: it will call the API as many + * times as needed. Note that it can affect your quota. + * We recommend using `listDocumentsAsync()` + * method described below for async iteration which you can stop as needed. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#auto-pagination | documentation } + * for more details and examples. + */ listDocumentsStream( - request?: protos.google.firestore.v1.IListDocumentsRequest, - options?: CallOptions - ): Transform { + request?: protos.google.firestore.v1.IListDocumentsRequest, + options?: CallOptions): + Transform{ request = request || {}; options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - options.otherArgs.headers['x-goog-request-params'] = - this._gaxModule.routingHeader.fromParams({ - parent: request.parent ?? '', - collection_id: request.collectionId ?? '', - }); + options.otherArgs.headers[ + 'x-goog-request-params' + ] = this._gaxModule.routingHeader.fromParams({ + 'parent': request.parent ?? '', + 'collection_id': request.collectionId ?? '', + }); const defaultCallSettings = this._defaults['listDocuments']; const callSettings = defaultCallSettings.merge(options); - this.initialize(); + this.initialize().catch(err => {throw err}); + this._log.info('listDocuments stream %j', request); return this.descriptors.page.listDocuments.createStream( this.innerApiCalls.listDocuments as GaxCall, request, @@ -1682,312 +1705,325 @@ export class FirestoreClient { ); } - /** - * Equivalent to `listDocuments`, but returns an iterable object. - * - * `for`-`await`-`of` syntax is used with the iterable to get response elements on-demand. - * @param {Object} request - * The request object that will be sent. - * @param {string} request.parent - * Required. The parent resource name. In the format: - * `projects/{project_id}/databases/{database_id}/documents` or - * `projects/{project_id}/databases/{database_id}/documents/{document_path}`. - * - * For example: - * `projects/my-project/databases/my-database/documents` or - * `projects/my-project/databases/my-database/documents/chatrooms/my-chatroom` - * @param {string} [request.collectionId] - * Optional. The collection ID, relative to `parent`, to list. - * - * For example: `chatrooms` or `messages`. - * - * This is optional, and when not provided, Firestore will list documents - * from all collections under the provided `parent`. - * @param {number} [request.pageSize] - * Optional. The maximum number of documents to return in a single response. - * - * Firestore may return fewer than this value. - * @param {string} [request.pageToken] - * Optional. A page token, received from a previous `ListDocuments` response. - * - * Provide this to retrieve the subsequent page. When paginating, all other - * parameters (with the exception of `page_size`) must match the values set - * in the request that generated the page token. - * @param {string} [request.orderBy] - * Optional. The optional ordering of the documents to return. - * - * For example: `priority desc, __name__ desc`. - * - * This mirrors the {@link protos.google.firestore.v1.StructuredQuery.order_by|`ORDER BY`} - * used in Firestore queries but in a string representation. When absent, - * documents are ordered based on `__name__ ASC`. - * @param {google.firestore.v1.DocumentMask} [request.mask] - * Optional. The fields to return. If not set, returns all fields. - * - * If a document has a field that is not present in this mask, that field - * will not be returned in the response. - * @param {Buffer} request.transaction - * Perform the read as part of an already active transaction. - * @param {google.protobuf.Timestamp} request.readTime - * Perform the read at the provided time. - * - * This must be a microsecond precision timestamp within the past one hour, - * or if Point-in-Time Recovery is enabled, can additionally be a whole - * minute timestamp within the past 7 days. - * @param {boolean} request.showMissing - * If the list should show missing documents. - * - * A document is missing if it does not exist, but there are sub-documents - * nested underneath it. When true, such missing documents will be returned - * with a key but will not have fields, - * {@link protos.google.firestore.v1.Document.create_time|`create_time`}, or - * {@link protos.google.firestore.v1.Document.update_time|`update_time`} set. - * - * Requests with `show_missing` may not specify `where` or `order_by`. - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Object} - * An iterable Object that allows {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols | async iteration }. - * When you iterate the returned iterable, each element will be an object representing - * {@link protos.google.firestore.v1.Document|Document}. The API will be called under the hood as needed, once per the page, - * so you can stop the iteration when you don't need more results. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#auto-pagination | documentation } - * for more details and examples. - * @example - * region_tag:firestore_v1_generated_Firestore_ListDocuments_async - */ +/** + * Equivalent to `listDocuments`, but returns an iterable object. + * + * `for`-`await`-`of` syntax is used with the iterable to get response elements on-demand. + * @param {Object} request + * The request object that will be sent. + * @param {string} request.parent + * Required. The parent resource name. In the format: + * `projects/{project_id}/databases/{database_id}/documents` or + * `projects/{project_id}/databases/{database_id}/documents/{document_path}`. + * + * For example: + * `projects/my-project/databases/my-database/documents` or + * `projects/my-project/databases/my-database/documents/chatrooms/my-chatroom` + * @param {string} [request.collectionId] + * Optional. The collection ID, relative to `parent`, to list. + * + * For example: `chatrooms` or `messages`. + * + * This is optional, and when not provided, Firestore will list documents + * from all collections under the provided `parent`. + * @param {number} [request.pageSize] + * Optional. The maximum number of documents to return in a single response. + * + * Firestore may return fewer than this value. + * @param {string} [request.pageToken] + * Optional. A page token, received from a previous `ListDocuments` response. + * + * Provide this to retrieve the subsequent page. When paginating, all other + * parameters (with the exception of `page_size`) must match the values set + * in the request that generated the page token. + * @param {string} [request.orderBy] + * Optional. The optional ordering of the documents to return. + * + * For example: `priority desc, __name__ desc`. + * + * This mirrors the {@link protos.google.firestore.v1.StructuredQuery.order_by|`ORDER BY`} + * used in Firestore queries but in a string representation. When absent, + * documents are ordered based on `__name__ ASC`. + * @param {google.firestore.v1.DocumentMask} [request.mask] + * Optional. The fields to return. If not set, returns all fields. + * + * If a document has a field that is not present in this mask, that field + * will not be returned in the response. + * @param {Buffer} request.transaction + * Perform the read as part of an already active transaction. + * @param {google.protobuf.Timestamp} request.readTime + * Perform the read at the provided time. + * + * This must be a microsecond precision timestamp within the past one hour, + * or if Point-in-Time Recovery is enabled, can additionally be a whole + * minute timestamp within the past 7 days. + * @param {boolean} request.showMissing + * If the list should show missing documents. + * + * A document is missing if it does not exist, but there are sub-documents + * nested underneath it. When true, such missing documents will be returned + * with a key but will not have fields, + * {@link protos.google.firestore.v1.Document.create_time|`create_time`}, or + * {@link protos.google.firestore.v1.Document.update_time|`update_time`} set. + * + * Requests with `show_missing` may not specify `where` or `order_by`. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Object} + * An iterable Object that allows {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols | async iteration }. + * When you iterate the returned iterable, each element will be an object representing + * {@link protos.google.firestore.v1.Document|Document}. The API will be called under the hood as needed, once per the page, + * so you can stop the iteration when you don't need more results. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#auto-pagination | documentation } + * for more details and examples. + * @example + * region_tag:firestore_v1_generated_Firestore_ListDocuments_async + */ listDocumentsAsync( - request?: protos.google.firestore.v1.IListDocumentsRequest, - options?: CallOptions - ): AsyncIterable { + request?: protos.google.firestore.v1.IListDocumentsRequest, + options?: CallOptions): + AsyncIterable{ request = request || {}; options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - options.otherArgs.headers['x-goog-request-params'] = - this._gaxModule.routingHeader.fromParams({ - parent: request.parent ?? '', - collection_id: request.collectionId ?? '', - }); + options.otherArgs.headers[ + 'x-goog-request-params' + ] = this._gaxModule.routingHeader.fromParams({ + 'parent': request.parent ?? '', + 'collection_id': request.collectionId ?? '', + }); const defaultCallSettings = this._defaults['listDocuments']; const callSettings = defaultCallSettings.merge(options); - this.initialize(); + this.initialize().catch(err => {throw err}); + this._log.info('listDocuments iterate %j', request); return this.descriptors.page.listDocuments.asyncIterate( this.innerApiCalls['listDocuments'] as GaxCall, request as {}, callSettings ) as AsyncIterable; } - /** - * Partitions a query by returning partition cursors that can be used to run - * the query in parallel. The returned partition cursors are split points that - * can be used by RunQuery as starting/end points for the query results. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.parent - * Required. The parent resource name. In the format: - * `projects/{project_id}/databases/{database_id}/documents`. - * Document resource names are not supported; only database resource names - * can be specified. - * @param {google.firestore.v1.StructuredQuery} request.structuredQuery - * A structured query. - * Query must specify collection with all descendants and be ordered by name - * ascending. Other filters, order bys, limits, offsets, and start/end - * cursors are not supported. - * @param {number} request.partitionCount - * The desired maximum number of partition points. - * The partitions may be returned across multiple pages of results. - * The number must be positive. The actual number of partitions - * returned may be fewer. - * - * For example, this may be set to one fewer than the number of parallel - * queries to be run, or in running a data pipeline job, one fewer than the - * number of workers or compute instances available. - * @param {string} request.pageToken - * The `next_page_token` value returned from a previous call to - * PartitionQuery that may be used to get an additional set of results. - * There are no ordering guarantees between sets of results. Thus, using - * multiple sets of results will require merging the different result sets. - * - * For example, two subsequent calls using a page_token may return: - * - * * cursor B, cursor M, cursor Q - * * cursor A, cursor U, cursor W - * - * To obtain a complete result set ordered with respect to the results of the - * query supplied to PartitionQuery, the results sets should be merged: - * cursor A, cursor B, cursor M, cursor Q, cursor U, cursor W - * @param {number} request.pageSize - * The maximum number of partitions to return in this call, subject to - * `partition_count`. - * - * For example, if `partition_count` = 10 and `page_size` = 8, the first call - * to PartitionQuery will return up to 8 partitions and a `next_page_token` - * if more results exist. A second call to PartitionQuery will return up to - * 2 partitions, to complete the total of 10 specified in `partition_count`. - * @param {google.protobuf.Timestamp} request.readTime - * Reads documents as they were at the given time. - * - * This must be a microsecond precision timestamp within the past one hour, - * or if Point-in-Time Recovery is enabled, can additionally be a whole - * minute timestamp within the past 7 days. - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Promise} - The promise which resolves to an array. - * The first element of the array is Array of {@link protos.google.firestore.v1.Cursor|Cursor}. - * The client library will perform auto-pagination by default: it will call the API as many - * times as needed and will merge results from all the pages into this array. - * Note that it can affect your quota. - * We recommend using `partitionQueryAsync()` - * method described below for async iteration which you can stop as needed. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#auto-pagination | documentation } - * for more details and examples. - */ + /** + * Partitions a query by returning partition cursors that can be used to run + * the query in parallel. The returned partition cursors are split points that + * can be used by RunQuery as starting/end points for the query results. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.parent + * Required. The parent resource name. In the format: + * `projects/{project_id}/databases/{database_id}/documents`. + * Document resource names are not supported; only database resource names + * can be specified. + * @param {google.firestore.v1.StructuredQuery} request.structuredQuery + * A structured query. + * Query must specify collection with all descendants and be ordered by name + * ascending. Other filters, order bys, limits, offsets, and start/end + * cursors are not supported. + * @param {number} request.partitionCount + * The desired maximum number of partition points. + * The partitions may be returned across multiple pages of results. + * The number must be positive. The actual number of partitions + * returned may be fewer. + * + * For example, this may be set to one fewer than the number of parallel + * queries to be run, or in running a data pipeline job, one fewer than the + * number of workers or compute instances available. + * @param {string} request.pageToken + * The `next_page_token` value returned from a previous call to + * PartitionQuery that may be used to get an additional set of results. + * There are no ordering guarantees between sets of results. Thus, using + * multiple sets of results will require merging the different result sets. + * + * For example, two subsequent calls using a page_token may return: + * + * * cursor B, cursor M, cursor Q + * * cursor A, cursor U, cursor W + * + * To obtain a complete result set ordered with respect to the results of the + * query supplied to PartitionQuery, the results sets should be merged: + * cursor A, cursor B, cursor M, cursor Q, cursor U, cursor W + * @param {number} request.pageSize + * The maximum number of partitions to return in this call, subject to + * `partition_count`. + * + * For example, if `partition_count` = 10 and `page_size` = 8, the first call + * to PartitionQuery will return up to 8 partitions and a `next_page_token` + * if more results exist. A second call to PartitionQuery will return up to + * 2 partitions, to complete the total of 10 specified in `partition_count`. + * @param {google.protobuf.Timestamp} request.readTime + * Reads documents as they were at the given time. + * + * This must be a microsecond precision timestamp within the past one hour, + * or if Point-in-Time Recovery is enabled, can additionally be a whole + * minute timestamp within the past 7 days. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is Array of {@link protos.google.firestore.v1.Cursor|Cursor}. + * The client library will perform auto-pagination by default: it will call the API as many + * times as needed and will merge results from all the pages into this array. + * Note that it can affect your quota. + * We recommend using `partitionQueryAsync()` + * method described below for async iteration which you can stop as needed. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#auto-pagination | documentation } + * for more details and examples. + */ partitionQuery( - request?: protos.google.firestore.v1.IPartitionQueryRequest, - options?: CallOptions - ): Promise< - [ - protos.google.firestore.v1.ICursor[], - protos.google.firestore.v1.IPartitionQueryRequest | null, - protos.google.firestore.v1.IPartitionQueryResponse, - ] - >; + request?: protos.google.firestore.v1.IPartitionQueryRequest, + options?: CallOptions): + Promise<[ + protos.google.firestore.v1.ICursor[], + protos.google.firestore.v1.IPartitionQueryRequest|null, + protos.google.firestore.v1.IPartitionQueryResponse + ]>; partitionQuery( - request: protos.google.firestore.v1.IPartitionQueryRequest, - options: CallOptions, - callback: PaginationCallback< - protos.google.firestore.v1.IPartitionQueryRequest, - protos.google.firestore.v1.IPartitionQueryResponse | null | undefined, - protos.google.firestore.v1.ICursor - > - ): void; + request: protos.google.firestore.v1.IPartitionQueryRequest, + options: CallOptions, + callback: PaginationCallback< + protos.google.firestore.v1.IPartitionQueryRequest, + protos.google.firestore.v1.IPartitionQueryResponse|null|undefined, + protos.google.firestore.v1.ICursor>): void; partitionQuery( - request: protos.google.firestore.v1.IPartitionQueryRequest, - callback: PaginationCallback< - protos.google.firestore.v1.IPartitionQueryRequest, - protos.google.firestore.v1.IPartitionQueryResponse | null | undefined, - protos.google.firestore.v1.ICursor - > - ): void; + request: protos.google.firestore.v1.IPartitionQueryRequest, + callback: PaginationCallback< + protos.google.firestore.v1.IPartitionQueryRequest, + protos.google.firestore.v1.IPartitionQueryResponse|null|undefined, + protos.google.firestore.v1.ICursor>): void; partitionQuery( - request?: protos.google.firestore.v1.IPartitionQueryRequest, - optionsOrCallback?: - | CallOptions - | PaginationCallback< + request?: protos.google.firestore.v1.IPartitionQueryRequest, + optionsOrCallback?: CallOptions|PaginationCallback< protos.google.firestore.v1.IPartitionQueryRequest, - protos.google.firestore.v1.IPartitionQueryResponse | null | undefined, - protos.google.firestore.v1.ICursor - >, - callback?: PaginationCallback< - protos.google.firestore.v1.IPartitionQueryRequest, - protos.google.firestore.v1.IPartitionQueryResponse | null | undefined, - protos.google.firestore.v1.ICursor - > - ): Promise< - [ - protos.google.firestore.v1.ICursor[], - protos.google.firestore.v1.IPartitionQueryRequest | null, - protos.google.firestore.v1.IPartitionQueryResponse, - ] - > | void { + protos.google.firestore.v1.IPartitionQueryResponse|null|undefined, + protos.google.firestore.v1.ICursor>, + callback?: PaginationCallback< + protos.google.firestore.v1.IPartitionQueryRequest, + protos.google.firestore.v1.IPartitionQueryResponse|null|undefined, + protos.google.firestore.v1.ICursor>): + Promise<[ + protos.google.firestore.v1.ICursor[], + protos.google.firestore.v1.IPartitionQueryRequest|null, + protos.google.firestore.v1.IPartitionQueryResponse + ]>|void { request = request || {}; let options: CallOptions; if (typeof optionsOrCallback === 'function' && callback === undefined) { callback = optionsOrCallback; options = {}; - } else { + } + else { options = optionsOrCallback as CallOptions; } options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - options.otherArgs.headers['x-goog-request-params'] = - this._gaxModule.routingHeader.fromParams({ - parent: request.parent ?? '', + options.otherArgs.headers[ + 'x-goog-request-params' + ] = this._gaxModule.routingHeader.fromParams({ + 'parent': request.parent ?? '', + }); + this.initialize().catch(err => {throw err}); + const wrappedCallback: PaginationCallback< + protos.google.firestore.v1.IPartitionQueryRequest, + protos.google.firestore.v1.IPartitionQueryResponse|null|undefined, + protos.google.firestore.v1.ICursor>|undefined = callback + ? (error, values, nextPageRequest, rawResponse) => { + this._log.info('partitionQuery values %j', values); + callback!(error, values, nextPageRequest, rawResponse); // We verified callback above. + } + : undefined; + this._log.info('partitionQuery request %j', request); + return this.innerApiCalls + .partitionQuery(request, options, wrappedCallback) + ?.then(([response, input, output]: [ + protos.google.firestore.v1.ICursor[], + protos.google.firestore.v1.IPartitionQueryRequest|null, + protos.google.firestore.v1.IPartitionQueryResponse + ]) => { + this._log.info('partitionQuery values %j', response); + return [response, input, output]; }); - this.initialize(); - return this.innerApiCalls.partitionQuery(request, options, callback); } - /** - * Equivalent to `partitionQuery`, but returns a NodeJS Stream object. - * @param {Object} request - * The request object that will be sent. - * @param {string} request.parent - * Required. The parent resource name. In the format: - * `projects/{project_id}/databases/{database_id}/documents`. - * Document resource names are not supported; only database resource names - * can be specified. - * @param {google.firestore.v1.StructuredQuery} request.structuredQuery - * A structured query. - * Query must specify collection with all descendants and be ordered by name - * ascending. Other filters, order bys, limits, offsets, and start/end - * cursors are not supported. - * @param {number} request.partitionCount - * The desired maximum number of partition points. - * The partitions may be returned across multiple pages of results. - * The number must be positive. The actual number of partitions - * returned may be fewer. - * - * For example, this may be set to one fewer than the number of parallel - * queries to be run, or in running a data pipeline job, one fewer than the - * number of workers or compute instances available. - * @param {string} request.pageToken - * The `next_page_token` value returned from a previous call to - * PartitionQuery that may be used to get an additional set of results. - * There are no ordering guarantees between sets of results. Thus, using - * multiple sets of results will require merging the different result sets. - * - * For example, two subsequent calls using a page_token may return: - * - * * cursor B, cursor M, cursor Q - * * cursor A, cursor U, cursor W - * - * To obtain a complete result set ordered with respect to the results of the - * query supplied to PartitionQuery, the results sets should be merged: - * cursor A, cursor B, cursor M, cursor Q, cursor U, cursor W - * @param {number} request.pageSize - * The maximum number of partitions to return in this call, subject to - * `partition_count`. - * - * For example, if `partition_count` = 10 and `page_size` = 8, the first call - * to PartitionQuery will return up to 8 partitions and a `next_page_token` - * if more results exist. A second call to PartitionQuery will return up to - * 2 partitions, to complete the total of 10 specified in `partition_count`. - * @param {google.protobuf.Timestamp} request.readTime - * Reads documents as they were at the given time. - * - * This must be a microsecond precision timestamp within the past one hour, - * or if Point-in-Time Recovery is enabled, can additionally be a whole - * minute timestamp within the past 7 days. - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Stream} - * An object stream which emits an object representing {@link protos.google.firestore.v1.Cursor|Cursor} on 'data' event. - * The client library will perform auto-pagination by default: it will call the API as many - * times as needed. Note that it can affect your quota. - * We recommend using `partitionQueryAsync()` - * method described below for async iteration which you can stop as needed. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#auto-pagination | documentation } - * for more details and examples. - */ +/** + * Equivalent to `partitionQuery`, but returns a NodeJS Stream object. + * @param {Object} request + * The request object that will be sent. + * @param {string} request.parent + * Required. The parent resource name. In the format: + * `projects/{project_id}/databases/{database_id}/documents`. + * Document resource names are not supported; only database resource names + * can be specified. + * @param {google.firestore.v1.StructuredQuery} request.structuredQuery + * A structured query. + * Query must specify collection with all descendants and be ordered by name + * ascending. Other filters, order bys, limits, offsets, and start/end + * cursors are not supported. + * @param {number} request.partitionCount + * The desired maximum number of partition points. + * The partitions may be returned across multiple pages of results. + * The number must be positive. The actual number of partitions + * returned may be fewer. + * + * For example, this may be set to one fewer than the number of parallel + * queries to be run, or in running a data pipeline job, one fewer than the + * number of workers or compute instances available. + * @param {string} request.pageToken + * The `next_page_token` value returned from a previous call to + * PartitionQuery that may be used to get an additional set of results. + * There are no ordering guarantees between sets of results. Thus, using + * multiple sets of results will require merging the different result sets. + * + * For example, two subsequent calls using a page_token may return: + * + * * cursor B, cursor M, cursor Q + * * cursor A, cursor U, cursor W + * + * To obtain a complete result set ordered with respect to the results of the + * query supplied to PartitionQuery, the results sets should be merged: + * cursor A, cursor B, cursor M, cursor Q, cursor U, cursor W + * @param {number} request.pageSize + * The maximum number of partitions to return in this call, subject to + * `partition_count`. + * + * For example, if `partition_count` = 10 and `page_size` = 8, the first call + * to PartitionQuery will return up to 8 partitions and a `next_page_token` + * if more results exist. A second call to PartitionQuery will return up to + * 2 partitions, to complete the total of 10 specified in `partition_count`. + * @param {google.protobuf.Timestamp} request.readTime + * Reads documents as they were at the given time. + * + * This must be a microsecond precision timestamp within the past one hour, + * or if Point-in-Time Recovery is enabled, can additionally be a whole + * minute timestamp within the past 7 days. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Stream} + * An object stream which emits an object representing {@link protos.google.firestore.v1.Cursor|Cursor} on 'data' event. + * The client library will perform auto-pagination by default: it will call the API as many + * times as needed. Note that it can affect your quota. + * We recommend using `partitionQueryAsync()` + * method described below for async iteration which you can stop as needed. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#auto-pagination | documentation } + * for more details and examples. + */ partitionQueryStream( - request?: protos.google.firestore.v1.IPartitionQueryRequest, - options?: CallOptions - ): Transform { + request?: protos.google.firestore.v1.IPartitionQueryRequest, + options?: CallOptions): + Transform{ request = request || {}; options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - options.otherArgs.headers['x-goog-request-params'] = - this._gaxModule.routingHeader.fromParams({ - parent: request.parent ?? '', - }); + options.otherArgs.headers[ + 'x-goog-request-params' + ] = this._gaxModule.routingHeader.fromParams({ + 'parent': request.parent ?? '', + }); const defaultCallSettings = this._defaults['partitionQuery']; const callSettings = defaultCallSettings.merge(options); - this.initialize(); + this.initialize().catch(err => {throw err}); + this._log.info('partitionQuery stream %j', request); return this.descriptors.page.partitionQuery.createStream( this.innerApiCalls.partitionQuery as GaxCall, request, @@ -1995,240 +2031,251 @@ export class FirestoreClient { ); } - /** - * Equivalent to `partitionQuery`, but returns an iterable object. - * - * `for`-`await`-`of` syntax is used with the iterable to get response elements on-demand. - * @param {Object} request - * The request object that will be sent. - * @param {string} request.parent - * Required. The parent resource name. In the format: - * `projects/{project_id}/databases/{database_id}/documents`. - * Document resource names are not supported; only database resource names - * can be specified. - * @param {google.firestore.v1.StructuredQuery} request.structuredQuery - * A structured query. - * Query must specify collection with all descendants and be ordered by name - * ascending. Other filters, order bys, limits, offsets, and start/end - * cursors are not supported. - * @param {number} request.partitionCount - * The desired maximum number of partition points. - * The partitions may be returned across multiple pages of results. - * The number must be positive. The actual number of partitions - * returned may be fewer. - * - * For example, this may be set to one fewer than the number of parallel - * queries to be run, or in running a data pipeline job, one fewer than the - * number of workers or compute instances available. - * @param {string} request.pageToken - * The `next_page_token` value returned from a previous call to - * PartitionQuery that may be used to get an additional set of results. - * There are no ordering guarantees between sets of results. Thus, using - * multiple sets of results will require merging the different result sets. - * - * For example, two subsequent calls using a page_token may return: - * - * * cursor B, cursor M, cursor Q - * * cursor A, cursor U, cursor W - * - * To obtain a complete result set ordered with respect to the results of the - * query supplied to PartitionQuery, the results sets should be merged: - * cursor A, cursor B, cursor M, cursor Q, cursor U, cursor W - * @param {number} request.pageSize - * The maximum number of partitions to return in this call, subject to - * `partition_count`. - * - * For example, if `partition_count` = 10 and `page_size` = 8, the first call - * to PartitionQuery will return up to 8 partitions and a `next_page_token` - * if more results exist. A second call to PartitionQuery will return up to - * 2 partitions, to complete the total of 10 specified in `partition_count`. - * @param {google.protobuf.Timestamp} request.readTime - * Reads documents as they were at the given time. - * - * This must be a microsecond precision timestamp within the past one hour, - * or if Point-in-Time Recovery is enabled, can additionally be a whole - * minute timestamp within the past 7 days. - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Object} - * An iterable Object that allows {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols | async iteration }. - * When you iterate the returned iterable, each element will be an object representing - * {@link protos.google.firestore.v1.Cursor|Cursor}. The API will be called under the hood as needed, once per the page, - * so you can stop the iteration when you don't need more results. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#auto-pagination | documentation } - * for more details and examples. - * @example - * region_tag:firestore_v1_generated_Firestore_PartitionQuery_async - */ +/** + * Equivalent to `partitionQuery`, but returns an iterable object. + * + * `for`-`await`-`of` syntax is used with the iterable to get response elements on-demand. + * @param {Object} request + * The request object that will be sent. + * @param {string} request.parent + * Required. The parent resource name. In the format: + * `projects/{project_id}/databases/{database_id}/documents`. + * Document resource names are not supported; only database resource names + * can be specified. + * @param {google.firestore.v1.StructuredQuery} request.structuredQuery + * A structured query. + * Query must specify collection with all descendants and be ordered by name + * ascending. Other filters, order bys, limits, offsets, and start/end + * cursors are not supported. + * @param {number} request.partitionCount + * The desired maximum number of partition points. + * The partitions may be returned across multiple pages of results. + * The number must be positive. The actual number of partitions + * returned may be fewer. + * + * For example, this may be set to one fewer than the number of parallel + * queries to be run, or in running a data pipeline job, one fewer than the + * number of workers or compute instances available. + * @param {string} request.pageToken + * The `next_page_token` value returned from a previous call to + * PartitionQuery that may be used to get an additional set of results. + * There are no ordering guarantees between sets of results. Thus, using + * multiple sets of results will require merging the different result sets. + * + * For example, two subsequent calls using a page_token may return: + * + * * cursor B, cursor M, cursor Q + * * cursor A, cursor U, cursor W + * + * To obtain a complete result set ordered with respect to the results of the + * query supplied to PartitionQuery, the results sets should be merged: + * cursor A, cursor B, cursor M, cursor Q, cursor U, cursor W + * @param {number} request.pageSize + * The maximum number of partitions to return in this call, subject to + * `partition_count`. + * + * For example, if `partition_count` = 10 and `page_size` = 8, the first call + * to PartitionQuery will return up to 8 partitions and a `next_page_token` + * if more results exist. A second call to PartitionQuery will return up to + * 2 partitions, to complete the total of 10 specified in `partition_count`. + * @param {google.protobuf.Timestamp} request.readTime + * Reads documents as they were at the given time. + * + * This must be a microsecond precision timestamp within the past one hour, + * or if Point-in-Time Recovery is enabled, can additionally be a whole + * minute timestamp within the past 7 days. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Object} + * An iterable Object that allows {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols | async iteration }. + * When you iterate the returned iterable, each element will be an object representing + * {@link protos.google.firestore.v1.Cursor|Cursor}. The API will be called under the hood as needed, once per the page, + * so you can stop the iteration when you don't need more results. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#auto-pagination | documentation } + * for more details and examples. + * @example + * region_tag:firestore_v1_generated_Firestore_PartitionQuery_async + */ partitionQueryAsync( - request?: protos.google.firestore.v1.IPartitionQueryRequest, - options?: CallOptions - ): AsyncIterable { + request?: protos.google.firestore.v1.IPartitionQueryRequest, + options?: CallOptions): + AsyncIterable{ request = request || {}; options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - options.otherArgs.headers['x-goog-request-params'] = - this._gaxModule.routingHeader.fromParams({ - parent: request.parent ?? '', - }); + options.otherArgs.headers[ + 'x-goog-request-params' + ] = this._gaxModule.routingHeader.fromParams({ + 'parent': request.parent ?? '', + }); const defaultCallSettings = this._defaults['partitionQuery']; const callSettings = defaultCallSettings.merge(options); - this.initialize(); + this.initialize().catch(err => {throw err}); + this._log.info('partitionQuery iterate %j', request); return this.descriptors.page.partitionQuery.asyncIterate( this.innerApiCalls['partitionQuery'] as GaxCall, request as {}, callSettings ) as AsyncIterable; } - /** - * Lists all the collection IDs underneath a document. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.parent - * Required. The parent document. In the format: - * `projects/{project_id}/databases/{database_id}/documents/{document_path}`. - * For example: - * `projects/my-project/databases/my-database/documents/chatrooms/my-chatroom` - * @param {number} request.pageSize - * The maximum number of results to return. - * @param {string} request.pageToken - * A page token. Must be a value from - * {@link protos.google.firestore.v1.ListCollectionIdsResponse|ListCollectionIdsResponse}. - * @param {google.protobuf.Timestamp} request.readTime - * Reads documents as they were at the given time. - * - * This must be a microsecond precision timestamp within the past one hour, - * or if Point-in-Time Recovery is enabled, can additionally be a whole - * minute timestamp within the past 7 days. - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Promise} - The promise which resolves to an array. - * The first element of the array is Array of string. - * The client library will perform auto-pagination by default: it will call the API as many - * times as needed and will merge results from all the pages into this array. - * Note that it can affect your quota. - * We recommend using `listCollectionIdsAsync()` - * method described below for async iteration which you can stop as needed. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#auto-pagination | documentation } - * for more details and examples. - */ + /** + * Lists all the collection IDs underneath a document. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.parent + * Required. The parent document. In the format: + * `projects/{project_id}/databases/{database_id}/documents/{document_path}`. + * For example: + * `projects/my-project/databases/my-database/documents/chatrooms/my-chatroom` + * @param {number} request.pageSize + * The maximum number of results to return. + * @param {string} request.pageToken + * A page token. Must be a value from + * {@link protos.google.firestore.v1.ListCollectionIdsResponse|ListCollectionIdsResponse}. + * @param {google.protobuf.Timestamp} request.readTime + * Reads documents as they were at the given time. + * + * This must be a microsecond precision timestamp within the past one hour, + * or if Point-in-Time Recovery is enabled, can additionally be a whole + * minute timestamp within the past 7 days. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is Array of string. + * The client library will perform auto-pagination by default: it will call the API as many + * times as needed and will merge results from all the pages into this array. + * Note that it can affect your quota. + * We recommend using `listCollectionIdsAsync()` + * method described below for async iteration which you can stop as needed. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#auto-pagination | documentation } + * for more details and examples. + */ listCollectionIds( - request?: protos.google.firestore.v1.IListCollectionIdsRequest, - options?: CallOptions - ): Promise< - [ - string[], - protos.google.firestore.v1.IListCollectionIdsRequest | null, - protos.google.firestore.v1.IListCollectionIdsResponse, - ] - >; + request?: protos.google.firestore.v1.IListCollectionIdsRequest, + options?: CallOptions): + Promise<[ + string[], + protos.google.firestore.v1.IListCollectionIdsRequest|null, + protos.google.firestore.v1.IListCollectionIdsResponse + ]>; listCollectionIds( - request: protos.google.firestore.v1.IListCollectionIdsRequest, - options: CallOptions, - callback: PaginationCallback< - protos.google.firestore.v1.IListCollectionIdsRequest, - protos.google.firestore.v1.IListCollectionIdsResponse | null | undefined, - string - > - ): void; + request: protos.google.firestore.v1.IListCollectionIdsRequest, + options: CallOptions, + callback: PaginationCallback< + protos.google.firestore.v1.IListCollectionIdsRequest, + protos.google.firestore.v1.IListCollectionIdsResponse|null|undefined, + string>): void; listCollectionIds( - request: protos.google.firestore.v1.IListCollectionIdsRequest, - callback: PaginationCallback< - protos.google.firestore.v1.IListCollectionIdsRequest, - protos.google.firestore.v1.IListCollectionIdsResponse | null | undefined, - string - > - ): void; + request: protos.google.firestore.v1.IListCollectionIdsRequest, + callback: PaginationCallback< + protos.google.firestore.v1.IListCollectionIdsRequest, + protos.google.firestore.v1.IListCollectionIdsResponse|null|undefined, + string>): void; listCollectionIds( - request?: protos.google.firestore.v1.IListCollectionIdsRequest, - optionsOrCallback?: - | CallOptions - | PaginationCallback< + request?: protos.google.firestore.v1.IListCollectionIdsRequest, + optionsOrCallback?: CallOptions|PaginationCallback< protos.google.firestore.v1.IListCollectionIdsRequest, - | protos.google.firestore.v1.IListCollectionIdsResponse - | null - | undefined, - string - >, - callback?: PaginationCallback< - protos.google.firestore.v1.IListCollectionIdsRequest, - protos.google.firestore.v1.IListCollectionIdsResponse | null | undefined, - string - > - ): Promise< - [ - string[], - protos.google.firestore.v1.IListCollectionIdsRequest | null, - protos.google.firestore.v1.IListCollectionIdsResponse, - ] - > | void { + protos.google.firestore.v1.IListCollectionIdsResponse|null|undefined, + string>, + callback?: PaginationCallback< + protos.google.firestore.v1.IListCollectionIdsRequest, + protos.google.firestore.v1.IListCollectionIdsResponse|null|undefined, + string>): + Promise<[ + string[], + protos.google.firestore.v1.IListCollectionIdsRequest|null, + protos.google.firestore.v1.IListCollectionIdsResponse + ]>|void { request = request || {}; let options: CallOptions; if (typeof optionsOrCallback === 'function' && callback === undefined) { callback = optionsOrCallback; options = {}; - } else { + } + else { options = optionsOrCallback as CallOptions; } options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - options.otherArgs.headers['x-goog-request-params'] = - this._gaxModule.routingHeader.fromParams({ - parent: request.parent ?? '', + options.otherArgs.headers[ + 'x-goog-request-params' + ] = this._gaxModule.routingHeader.fromParams({ + 'parent': request.parent ?? '', + }); + this.initialize().catch(err => {throw err}); + const wrappedCallback: PaginationCallback< + protos.google.firestore.v1.IListCollectionIdsRequest, + protos.google.firestore.v1.IListCollectionIdsResponse|null|undefined, + string>|undefined = callback + ? (error, values, nextPageRequest, rawResponse) => { + this._log.info('listCollectionIds values %j', values); + callback!(error, values, nextPageRequest, rawResponse); // We verified callback above. + } + : undefined; + this._log.info('listCollectionIds request %j', request); + return this.innerApiCalls + .listCollectionIds(request, options, wrappedCallback) + ?.then(([response, input, output]: [ + string[], + protos.google.firestore.v1.IListCollectionIdsRequest|null, + protos.google.firestore.v1.IListCollectionIdsResponse + ]) => { + this._log.info('listCollectionIds values %j', response); + return [response, input, output]; }); - this.initialize(); - return this.innerApiCalls.listCollectionIds(request, options, callback); } - /** - * Equivalent to `listCollectionIds`, but returns a NodeJS Stream object. - * @param {Object} request - * The request object that will be sent. - * @param {string} request.parent - * Required. The parent document. In the format: - * `projects/{project_id}/databases/{database_id}/documents/{document_path}`. - * For example: - * `projects/my-project/databases/my-database/documents/chatrooms/my-chatroom` - * @param {number} request.pageSize - * The maximum number of results to return. - * @param {string} request.pageToken - * A page token. Must be a value from - * {@link protos.google.firestore.v1.ListCollectionIdsResponse|ListCollectionIdsResponse}. - * @param {google.protobuf.Timestamp} request.readTime - * Reads documents as they were at the given time. - * - * This must be a microsecond precision timestamp within the past one hour, - * or if Point-in-Time Recovery is enabled, can additionally be a whole - * minute timestamp within the past 7 days. - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Stream} - * An object stream which emits an object representing string on 'data' event. - * The client library will perform auto-pagination by default: it will call the API as many - * times as needed. Note that it can affect your quota. - * We recommend using `listCollectionIdsAsync()` - * method described below for async iteration which you can stop as needed. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#auto-pagination | documentation } - * for more details and examples. - */ +/** + * Equivalent to `listCollectionIds`, but returns a NodeJS Stream object. + * @param {Object} request + * The request object that will be sent. + * @param {string} request.parent + * Required. The parent document. In the format: + * `projects/{project_id}/databases/{database_id}/documents/{document_path}`. + * For example: + * `projects/my-project/databases/my-database/documents/chatrooms/my-chatroom` + * @param {number} request.pageSize + * The maximum number of results to return. + * @param {string} request.pageToken + * A page token. Must be a value from + * {@link protos.google.firestore.v1.ListCollectionIdsResponse|ListCollectionIdsResponse}. + * @param {google.protobuf.Timestamp} request.readTime + * Reads documents as they were at the given time. + * + * This must be a microsecond precision timestamp within the past one hour, + * or if Point-in-Time Recovery is enabled, can additionally be a whole + * minute timestamp within the past 7 days. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Stream} + * An object stream which emits an object representing string on 'data' event. + * The client library will perform auto-pagination by default: it will call the API as many + * times as needed. Note that it can affect your quota. + * We recommend using `listCollectionIdsAsync()` + * method described below for async iteration which you can stop as needed. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#auto-pagination | documentation } + * for more details and examples. + */ listCollectionIdsStream( - request?: protos.google.firestore.v1.IListCollectionIdsRequest, - options?: CallOptions - ): Transform { + request?: protos.google.firestore.v1.IListCollectionIdsRequest, + options?: CallOptions): + Transform{ request = request || {}; options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - options.otherArgs.headers['x-goog-request-params'] = - this._gaxModule.routingHeader.fromParams({ - parent: request.parent ?? '', - }); + options.otherArgs.headers[ + 'x-goog-request-params' + ] = this._gaxModule.routingHeader.fromParams({ + 'parent': request.parent ?? '', + }); const defaultCallSettings = this._defaults['listCollectionIds']; const callSettings = defaultCallSettings.merge(options); - this.initialize(); + this.initialize().catch(err => {throw err}); + this._log.info('listCollectionIds stream %j', request); return this.descriptors.page.listCollectionIds.createStream( this.innerApiCalls.listCollectionIds as GaxCall, request, @@ -2236,62 +2283,64 @@ export class FirestoreClient { ); } - /** - * Equivalent to `listCollectionIds`, but returns an iterable object. - * - * `for`-`await`-`of` syntax is used with the iterable to get response elements on-demand. - * @param {Object} request - * The request object that will be sent. - * @param {string} request.parent - * Required. The parent document. In the format: - * `projects/{project_id}/databases/{database_id}/documents/{document_path}`. - * For example: - * `projects/my-project/databases/my-database/documents/chatrooms/my-chatroom` - * @param {number} request.pageSize - * The maximum number of results to return. - * @param {string} request.pageToken - * A page token. Must be a value from - * {@link protos.google.firestore.v1.ListCollectionIdsResponse|ListCollectionIdsResponse}. - * @param {google.protobuf.Timestamp} request.readTime - * Reads documents as they were at the given time. - * - * This must be a microsecond precision timestamp within the past one hour, - * or if Point-in-Time Recovery is enabled, can additionally be a whole - * minute timestamp within the past 7 days. - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Object} - * An iterable Object that allows {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols | async iteration }. - * When you iterate the returned iterable, each element will be an object representing - * string. The API will be called under the hood as needed, once per the page, - * so you can stop the iteration when you don't need more results. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#auto-pagination | documentation } - * for more details and examples. - * @example - * region_tag:firestore_v1_generated_Firestore_ListCollectionIds_async - */ +/** + * Equivalent to `listCollectionIds`, but returns an iterable object. + * + * `for`-`await`-`of` syntax is used with the iterable to get response elements on-demand. + * @param {Object} request + * The request object that will be sent. + * @param {string} request.parent + * Required. The parent document. In the format: + * `projects/{project_id}/databases/{database_id}/documents/{document_path}`. + * For example: + * `projects/my-project/databases/my-database/documents/chatrooms/my-chatroom` + * @param {number} request.pageSize + * The maximum number of results to return. + * @param {string} request.pageToken + * A page token. Must be a value from + * {@link protos.google.firestore.v1.ListCollectionIdsResponse|ListCollectionIdsResponse}. + * @param {google.protobuf.Timestamp} request.readTime + * Reads documents as they were at the given time. + * + * This must be a microsecond precision timestamp within the past one hour, + * or if Point-in-Time Recovery is enabled, can additionally be a whole + * minute timestamp within the past 7 days. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Object} + * An iterable Object that allows {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols | async iteration }. + * When you iterate the returned iterable, each element will be an object representing + * string. The API will be called under the hood as needed, once per the page, + * so you can stop the iteration when you don't need more results. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#auto-pagination | documentation } + * for more details and examples. + * @example + * region_tag:firestore_v1_generated_Firestore_ListCollectionIds_async + */ listCollectionIdsAsync( - request?: protos.google.firestore.v1.IListCollectionIdsRequest, - options?: CallOptions - ): AsyncIterable { + request?: protos.google.firestore.v1.IListCollectionIdsRequest, + options?: CallOptions): + AsyncIterable{ request = request || {}; options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - options.otherArgs.headers['x-goog-request-params'] = - this._gaxModule.routingHeader.fromParams({ - parent: request.parent ?? '', - }); + options.otherArgs.headers[ + 'x-goog-request-params' + ] = this._gaxModule.routingHeader.fromParams({ + 'parent': request.parent ?? '', + }); const defaultCallSettings = this._defaults['listCollectionIds']; const callSettings = defaultCallSettings.merge(options); - this.initialize(); + this.initialize().catch(err => {throw err}); + this._log.info('listCollectionIds iterate %j', request); return this.descriptors.page.listCollectionIds.asyncIterate( this.innerApiCalls['listCollectionIds'] as GaxCall, request as {}, callSettings ) as AsyncIterable; } - /** +/** * Gets information about a location. * * @param {Object} request @@ -2331,7 +2380,7 @@ export class FirestoreClient { return this.locationsClient.getLocation(request, options, callback); } - /** +/** * Lists information about the supported locations for this service. Returns an iterable object. * * `for`-`await`-`of` syntax is used with the iterable to get response elements on-demand. @@ -2369,6 +2418,7 @@ export class FirestoreClient { return this.locationsClient.listLocationsAsync(request, options); } + /** * Terminate the gRPC channel and close the client. * @@ -2378,11 +2428,12 @@ export class FirestoreClient { close(): Promise { if (this.firestoreStub && !this._terminated) { return this.firestoreStub.then(stub => { + this._log.info('ending gRPC channel'); this._terminated = true; stub.close(); - this.locationsClient.close(); + this.locationsClient.close().catch(err => {throw err}); }); } return Promise.resolve(); } -} +} \ No newline at end of file diff --git a/dev/src/v1/firestore_client_config.json b/dev/src/v1/firestore_client_config.json index 47cbabb90..40e9a132e 100644 --- a/dev/src/v1/firestore_client_config.json +++ b/dev/src/v1/firestore_client_config.json @@ -81,8 +81,7 @@ "retry_params_name": "default" }, "ExecutePipeline": { - "timeout_millis": 300000, - "retry_codes_name": "deadline_exceeded_resource_exhausted_internal_unavailable", + "retry_codes_name": "non_idempotent", "retry_params_name": "default" }, "RunAggregationQuery": { diff --git a/dev/src/v1/firestore_proto_list.json b/dev/src/v1/firestore_proto_list.json index 318c636c1..6b67f4f49 100644 --- a/dev/src/v1/firestore_proto_list.json +++ b/dev/src/v1/firestore_proto_list.json @@ -3,7 +3,9 @@ "../../protos/google/firestore/v1/bloom_filter.proto", "../../protos/google/firestore/v1/common.proto", "../../protos/google/firestore/v1/document.proto", + "../../protos/google/firestore/v1/explain_stats.proto", "../../protos/google/firestore/v1/firestore.proto", + "../../protos/google/firestore/v1/pipeline.proto", "../../protos/google/firestore/v1/query.proto", "../../protos/google/firestore/v1/query_profile.proto", "../../protos/google/firestore/v1/write.proto" diff --git a/dev/src/v1/gapic_metadata.json b/dev/src/v1/gapic_metadata.json index 4fce00187..700dcb2c4 100644 --- a/dev/src/v1/gapic_metadata.json +++ b/dev/src/v1/gapic_metadata.json @@ -60,6 +60,11 @@ "runQuery" ] }, + "ExecutePipeline": { + "methods": [ + "executePipeline" + ] + }, "RunAggregationQuery": { "methods": [ "runAggregationQuery" diff --git a/dev/src/v1beta1/firestore_client.ts b/dev/src/v1beta1/firestore_client.ts index 65a87e466..7d8340955 100644 --- a/dev/src/v1beta1/firestore_client.ts +++ b/dev/src/v1beta1/firestore_client.ts @@ -38,6 +38,12 @@ import jsonProtos = require('../../protos/v1beta1.json'); import * as gapicConfig from './firestore_client_config.json'; // tslint:disable deprecation +// tslint:disable deprecation + +// tslint:disable deprecation + +// tslint:disable deprecation + const version = require('../../../package.json').version; /** @@ -51,6 +57,9 @@ const version = require('../../../package.json').version; * building truly serverless apps. * @class * @deprecated Use v1/firestore_client instead. + * @deprecated Use v1/firestore_client instead. + * @deprecated Use v1/firestore_client instead. + * @deprecated Use v1/firestore_client instead. * @memberof v1beta1 */ export class FirestoreClient { diff --git a/dev/test/gapic_firestore_admin_v1.ts b/dev/test/gapic_firestore_admin_v1.ts index 8bdc602c6..156f249f0 100644 --- a/dev/test/gapic_firestore_admin_v1.ts +++ b/dev/test/gapic_firestore_admin_v1.ts @@ -25,5351 +25,5123 @@ import * as firestoreadminModule from '../src/v1'; import {PassThrough} from 'stream'; -import { - protobuf, - LROperation, - operationsProtos, - LocationProtos, -} from 'google-gax'; +import {protobuf, LROperation, operationsProtos, LocationProtos} from 'google-gax'; // Dynamically loaded proto JSON is needed to get the type information // to fill in default values for request objects -const root = protobuf.Root.fromJSON( - require('../protos/admin_v1.json') -).resolveAll(); +const root = protobuf.Root.fromJSON(require('../protos/admin_v1.json')).resolveAll(); // eslint-disable-next-line @typescript-eslint/no-unused-vars function getTypeDefaultValue(typeName: string, fields: string[]) { - let type = root.lookupType(typeName) as protobuf.Type; - for (const field of fields.slice(0, -1)) { - type = type.fields[field]?.resolvedType as protobuf.Type; - } - return type.fields[fields[fields.length - 1]]?.defaultValue; + let type = root.lookupType(typeName) as protobuf.Type; + for (const field of fields.slice(0, -1)) { + type = type.fields[field]?.resolvedType as protobuf.Type; + } + return type.fields[fields[fields.length - 1]]?.defaultValue; } function generateSampleMessage(instance: T) { - const filledObject = ( - instance.constructor as typeof protobuf.Message - ).toObject(instance as protobuf.Message, {defaults: true}); - return (instance.constructor as typeof protobuf.Message).fromObject( - filledObject - ) as T; + const filledObject = (instance.constructor as typeof protobuf.Message) + .toObject(instance as protobuf.Message, {defaults: true}); + return (instance.constructor as typeof protobuf.Message).fromObject(filledObject) as T; } function stubSimpleCall(response?: ResponseType, error?: Error) { - return error - ? sinon.stub().rejects(error) - : sinon.stub().resolves([response]); + return error ? sinon.stub().rejects(error) : sinon.stub().resolves([response]); } -function stubSimpleCallWithCallback( - response?: ResponseType, - error?: Error -) { - return error - ? sinon.stub().callsArgWith(2, error) - : sinon.stub().callsArgWith(2, null, response); +function stubSimpleCallWithCallback(response?: ResponseType, error?: Error) { + return error ? sinon.stub().callsArgWith(2, error) : sinon.stub().callsArgWith(2, null, response); } -function stubLongRunningCall( - response?: ResponseType, - callError?: Error, - lroError?: Error -) { - const innerStub = lroError - ? sinon.stub().rejects(lroError) - : sinon.stub().resolves([response]); - const mockOperation = { - promise: innerStub, - }; - return callError - ? sinon.stub().rejects(callError) - : sinon.stub().resolves([mockOperation]); +function stubLongRunningCall(response?: ResponseType, callError?: Error, lroError?: Error) { + const innerStub = lroError ? sinon.stub().rejects(lroError) : sinon.stub().resolves([response]); + const mockOperation = { + promise: innerStub, + }; + return callError ? sinon.stub().rejects(callError) : sinon.stub().resolves([mockOperation]); } -function stubLongRunningCallWithCallback( - response?: ResponseType, - callError?: Error, - lroError?: Error -) { - const innerStub = lroError - ? sinon.stub().rejects(lroError) - : sinon.stub().resolves([response]); - const mockOperation = { - promise: innerStub, - }; - return callError - ? sinon.stub().callsArgWith(2, callError) - : sinon.stub().callsArgWith(2, null, mockOperation); +function stubLongRunningCallWithCallback(response?: ResponseType, callError?: Error, lroError?: Error) { + const innerStub = lroError ? sinon.stub().rejects(lroError) : sinon.stub().resolves([response]); + const mockOperation = { + promise: innerStub, + }; + return callError ? sinon.stub().callsArgWith(2, callError) : sinon.stub().callsArgWith(2, null, mockOperation); } -function stubPageStreamingCall( - responses?: ResponseType[], - error?: Error -) { - const pagingStub = sinon.stub(); - if (responses) { - for (let i = 0; i < responses.length; ++i) { - pagingStub.onCall(i).callsArgWith(2, null, responses[i]); +function stubPageStreamingCall(responses?: ResponseType[], error?: Error) { + const pagingStub = sinon.stub(); + if (responses) { + for (let i = 0; i < responses.length; ++i) { + pagingStub.onCall(i).callsArgWith(2, null, responses[i]); + } } - } - const transformStub = error - ? sinon.stub().callsArgWith(2, error) - : pagingStub; - const mockStream = new PassThrough({ - objectMode: true, - transform: transformStub, - }); - // trigger as many responses as needed - if (responses) { - for (let i = 0; i < responses.length; ++i) { - setImmediate(() => { - mockStream.write({}); - }); + const transformStub = error ? sinon.stub().callsArgWith(2, error) : pagingStub; + const mockStream = new PassThrough({ + objectMode: true, + transform: transformStub, + }); + // trigger as many responses as needed + if (responses) { + for (let i = 0; i < responses.length; ++i) { + setImmediate(() => { mockStream.write({}); }); + } + setImmediate(() => { mockStream.end(); }); + } else { + setImmediate(() => { mockStream.write({}); }); + setImmediate(() => { mockStream.end(); }); } - setImmediate(() => { - mockStream.end(); - }); - } else { - setImmediate(() => { - mockStream.write({}); - }); - setImmediate(() => { - mockStream.end(); - }); - } - return sinon.stub().returns(mockStream); + return sinon.stub().returns(mockStream); } -function stubAsyncIterationCall( - responses?: ResponseType[], - error?: Error -) { - let counter = 0; - const asyncIterable = { - [Symbol.asyncIterator]() { - return { - async next() { - if (error) { - return Promise.reject(error); - } - if (counter >= responses!.length) { - return Promise.resolve({done: true, value: undefined}); - } - return Promise.resolve({done: false, value: responses![counter++]}); - }, - }; - }, - }; - return sinon.stub().returns(asyncIterable); +function stubAsyncIterationCall(responses?: ResponseType[], error?: Error) { + let counter = 0; + const asyncIterable = { + [Symbol.asyncIterator]() { + return { + async next() { + if (error) { + return Promise.reject(error); + } + if (counter >= responses!.length) { + return Promise.resolve({done: true, value: undefined}); + } + return Promise.resolve({done: false, value: responses![counter++]}); + } + }; + } + }; + return sinon.stub().returns(asyncIterable); } describe('v1.FirestoreAdminClient', () => { - describe('Common methods', () => { - it('has apiEndpoint', () => { - const client = new firestoreadminModule.FirestoreAdminClient(); - const apiEndpoint = client.apiEndpoint; - assert.strictEqual(apiEndpoint, 'firestore.googleapis.com'); - }); + describe('Common methods', () => { + it('has apiEndpoint', () => { + const client = new firestoreadminModule.FirestoreAdminClient(); + const apiEndpoint = client.apiEndpoint; + assert.strictEqual(apiEndpoint, 'firestore.googleapis.com'); + }); - it('has universeDomain', () => { - const client = new firestoreadminModule.FirestoreAdminClient(); - const universeDomain = client.universeDomain; - assert.strictEqual(universeDomain, 'googleapis.com'); - }); + it('has universeDomain', () => { + const client = new firestoreadminModule.FirestoreAdminClient(); + const universeDomain = client.universeDomain; + assert.strictEqual(universeDomain, "googleapis.com"); + }); - if ( - typeof process === 'object' && - typeof process.emitWarning === 'function' - ) { - it('throws DeprecationWarning if static servicePath is used', () => { - const stub = sinon.stub(process, 'emitWarning'); - const servicePath = - firestoreadminModule.FirestoreAdminClient.servicePath; - assert.strictEqual(servicePath, 'firestore.googleapis.com'); - assert(stub.called); - stub.restore(); - }); - - it('throws DeprecationWarning if static apiEndpoint is used', () => { - const stub = sinon.stub(process, 'emitWarning'); - const apiEndpoint = - firestoreadminModule.FirestoreAdminClient.apiEndpoint; - assert.strictEqual(apiEndpoint, 'firestore.googleapis.com'); - assert(stub.called); - stub.restore(); - }); - } - it('sets apiEndpoint according to universe domain camelCase', () => { - const client = new firestoreadminModule.FirestoreAdminClient({ - universeDomain: 'example.com', - }); - const servicePath = client.apiEndpoint; - assert.strictEqual(servicePath, 'firestore.example.com'); - }); + if (typeof process === 'object' && typeof process.emitWarning === 'function') { + it('throws DeprecationWarning if static servicePath is used', () => { + const stub = sinon.stub(process, 'emitWarning'); + const servicePath = firestoreadminModule.FirestoreAdminClient.servicePath; + assert.strictEqual(servicePath, 'firestore.googleapis.com'); + assert(stub.called); + stub.restore(); + }); + + it('throws DeprecationWarning if static apiEndpoint is used', () => { + const stub = sinon.stub(process, 'emitWarning'); + const apiEndpoint = firestoreadminModule.FirestoreAdminClient.apiEndpoint; + assert.strictEqual(apiEndpoint, 'firestore.googleapis.com'); + assert(stub.called); + stub.restore(); + }); + } + it('sets apiEndpoint according to universe domain camelCase', () => { + const client = new firestoreadminModule.FirestoreAdminClient({universeDomain: 'example.com'}); + const servicePath = client.apiEndpoint; + assert.strictEqual(servicePath, 'firestore.example.com'); + }); - it('sets apiEndpoint according to universe domain snakeCase', () => { - const client = new firestoreadminModule.FirestoreAdminClient({ - universe_domain: 'example.com', - }); - const servicePath = client.apiEndpoint; - assert.strictEqual(servicePath, 'firestore.example.com'); - }); + it('sets apiEndpoint according to universe domain snakeCase', () => { + const client = new firestoreadminModule.FirestoreAdminClient({universe_domain: 'example.com'}); + const servicePath = client.apiEndpoint; + assert.strictEqual(servicePath, 'firestore.example.com'); + }); - if (typeof process === 'object' && 'env' in process) { - describe('GOOGLE_CLOUD_UNIVERSE_DOMAIN environment variable', () => { - it('sets apiEndpoint from environment variable', () => { - const saved = process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN']; - process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] = 'example.com'; - const client = new firestoreadminModule.FirestoreAdminClient(); - const servicePath = client.apiEndpoint; - assert.strictEqual(servicePath, 'firestore.example.com'); - if (saved) { - process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] = saved; - } else { - delete process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN']; - } - }); - - it('value configured in code has priority over environment variable', () => { - const saved = process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN']; - process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] = 'example.com'; - const client = new firestoreadminModule.FirestoreAdminClient({ - universeDomain: 'configured.example.com', - }); - const servicePath = client.apiEndpoint; - assert.strictEqual(servicePath, 'firestore.configured.example.com'); - if (saved) { - process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] = saved; - } else { - delete process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN']; - } - }); - }); - } - it('does not allow setting both universeDomain and universe_domain', () => { - assert.throws(() => { - new firestoreadminModule.FirestoreAdminClient({ - universe_domain: 'example.com', - universeDomain: 'example.net', + if (typeof process === 'object' && 'env' in process) { + describe('GOOGLE_CLOUD_UNIVERSE_DOMAIN environment variable', () => { + it('sets apiEndpoint from environment variable', () => { + const saved = process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN']; + process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] = 'example.com'; + const client = new firestoreadminModule.FirestoreAdminClient(); + const servicePath = client.apiEndpoint; + assert.strictEqual(servicePath, 'firestore.example.com'); + if (saved) { + process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] = saved; + } else { + delete process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN']; + } + }); + + it('value configured in code has priority over environment variable', () => { + const saved = process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN']; + process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] = 'example.com'; + const client = new firestoreadminModule.FirestoreAdminClient({universeDomain: 'configured.example.com'}); + const servicePath = client.apiEndpoint; + assert.strictEqual(servicePath, 'firestore.configured.example.com'); + if (saved) { + process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] = saved; + } else { + delete process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN']; + } + }); + }); + } + it('does not allow setting both universeDomain and universe_domain', () => { + assert.throws(() => { new firestoreadminModule.FirestoreAdminClient({universe_domain: 'example.com', universeDomain: 'example.net'}); }); }); - }); - }); - it('has port', () => { - const port = firestoreadminModule.FirestoreAdminClient.port; - assert(port); - assert(typeof port === 'number'); - }); + it('has port', () => { + const port = firestoreadminModule.FirestoreAdminClient.port; + assert(port); + assert(typeof port === 'number'); + }); - it('should create a client with no option', () => { - const client = new firestoreadminModule.FirestoreAdminClient(); - assert(client); - }); + it('should create a client with no option', () => { + const client = new firestoreadminModule.FirestoreAdminClient(); + assert(client); + }); - it('should create a client with gRPC fallback', () => { - const client = new firestoreadminModule.FirestoreAdminClient({ - fallback: true, - }); - assert(client); - }); + it('should create a client with gRPC fallback', () => { + const client = new firestoreadminModule.FirestoreAdminClient({ + fallback: true, + }); + assert(client); + }); - it('has initialize method and supports deferred initialization', async () => { - const client = new firestoreadminModule.FirestoreAdminClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - assert.strictEqual(client.firestoreAdminStub, undefined); - await client.initialize(); - assert(client.firestoreAdminStub); - }); + it('has initialize method and supports deferred initialization', async () => { + const client = new firestoreadminModule.FirestoreAdminClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + assert.strictEqual(client.firestoreAdminStub, undefined); + await client.initialize(); + assert(client.firestoreAdminStub); + }); - it('has close method for the initialized client', done => { - const client = new firestoreadminModule.FirestoreAdminClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.initialize(); - assert(client.firestoreAdminStub); - client.close().then(() => { - done(); - }); - }); + it('has close method for the initialized client', done => { + const client = new firestoreadminModule.FirestoreAdminClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + client.initialize().catch(err => {throw err}); + assert(client.firestoreAdminStub); + client.close().then(() => { + done(); + }).catch(err => {throw err}); + }); - it('has close method for the non-initialized client', done => { - const client = new firestoreadminModule.FirestoreAdminClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - assert.strictEqual(client.firestoreAdminStub, undefined); - client.close().then(() => { - done(); - }); - }); + it('has close method for the non-initialized client', done => { + const client = new firestoreadminModule.FirestoreAdminClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + assert.strictEqual(client.firestoreAdminStub, undefined); + client.close().then(() => { + done(); + }).catch(err => {throw err}); + }); - it('has getProjectId method', async () => { - const fakeProjectId = 'fake-project-id'; - const client = new firestoreadminModule.FirestoreAdminClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.auth.getProjectId = sinon.stub().resolves(fakeProjectId); - const result = await client.getProjectId(); - assert.strictEqual(result, fakeProjectId); - assert((client.auth.getProjectId as SinonStub).calledWithExactly()); - }); + it('has getProjectId method', async () => { + const fakeProjectId = 'fake-project-id'; + const client = new firestoreadminModule.FirestoreAdminClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + client.auth.getProjectId = sinon.stub().resolves(fakeProjectId); + const result = await client.getProjectId(); + assert.strictEqual(result, fakeProjectId); + assert((client.auth.getProjectId as SinonStub).calledWithExactly()); + }); - it('has getProjectId method with callback', async () => { - const fakeProjectId = 'fake-project-id'; - const client = new firestoreadminModule.FirestoreAdminClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.auth.getProjectId = sinon - .stub() - .callsArgWith(0, null, fakeProjectId); - const promise = new Promise((resolve, reject) => { - client.getProjectId((err?: Error | null, projectId?: string | null) => { - if (err) { - reject(err); - } else { - resolve(projectId); - } - }); - }); - const result = await promise; - assert.strictEqual(result, fakeProjectId); - }); - }); - - describe('getIndex', () => { - it('invokes getIndex without error', async () => { - const client = new firestoreadminModule.FirestoreAdminClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.initialize(); - const request = generateSampleMessage( - new protos.google.firestore.admin.v1.GetIndexRequest() - ); - const defaultValue1 = getTypeDefaultValue( - '.google.firestore.admin.v1.GetIndexRequest', - ['name'] - ); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; - const expectedResponse = generateSampleMessage( - new protos.google.firestore.admin.v1.Index() - ); - client.innerApiCalls.getIndex = stubSimpleCall(expectedResponse); - const [response] = await client.getIndex(request); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = ( - client.innerApiCalls.getIndex as SinonStub - ).getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = ( - client.innerApiCalls.getIndex as SinonStub - ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + it('has getProjectId method with callback', async () => { + const fakeProjectId = 'fake-project-id'; + const client = new firestoreadminModule.FirestoreAdminClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + client.auth.getProjectId = sinon.stub().callsArgWith(0, null, fakeProjectId); + const promise = new Promise((resolve, reject) => { + client.getProjectId((err?: Error|null, projectId?: string|null) => { + if (err) { + reject(err); + } else { + resolve(projectId); + } + }); + }); + const result = await promise; + assert.strictEqual(result, fakeProjectId); + }); }); - it('invokes getIndex without error using callback', async () => { - const client = new firestoreadminModule.FirestoreAdminClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.initialize(); - const request = generateSampleMessage( - new protos.google.firestore.admin.v1.GetIndexRequest() - ); - const defaultValue1 = getTypeDefaultValue( - '.google.firestore.admin.v1.GetIndexRequest', - ['name'] - ); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; - const expectedResponse = generateSampleMessage( - new protos.google.firestore.admin.v1.Index() - ); - client.innerApiCalls.getIndex = - stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.getIndex( - request, - ( - err?: Error | null, - result?: protos.google.firestore.admin.v1.IIndex | null - ) => { - if (err) { - reject(err); - } else { - resolve(result); - } - } - ); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = ( - client.innerApiCalls.getIndex as SinonStub - ).getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = ( - client.innerApiCalls.getIndex as SinonStub - ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + describe('getIndex', () => { + it('invokes getIndex without error', async () => { + const client = new firestoreadminModule.FirestoreAdminClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.firestore.admin.v1.GetIndexRequest() + ); + const defaultValue1 = + getTypeDefaultValue('.google.firestore.admin.v1.GetIndexRequest', ['name']); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; + const expectedResponse = generateSampleMessage( + new protos.google.firestore.admin.v1.Index() + ); + client.innerApiCalls.getIndex = stubSimpleCall(expectedResponse); + const [response] = await client.getIndex(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = (client.innerApiCalls.getIndex as SinonStub) + .getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = (client.innerApiCalls.getIndex as SinonStub) + .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes getIndex with error', async () => { - const client = new firestoreadminModule.FirestoreAdminClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.initialize(); - const request = generateSampleMessage( - new protos.google.firestore.admin.v1.GetIndexRequest() - ); - const defaultValue1 = getTypeDefaultValue( - '.google.firestore.admin.v1.GetIndexRequest', - ['name'] - ); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; - const expectedError = new Error('expected'); - client.innerApiCalls.getIndex = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.getIndex(request), expectedError); - const actualRequest = ( - client.innerApiCalls.getIndex as SinonStub - ).getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = ( - client.innerApiCalls.getIndex as SinonStub - ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes getIndex without error using callback', async () => { + const client = new firestoreadminModule.FirestoreAdminClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.firestore.admin.v1.GetIndexRequest() + ); + const defaultValue1 = + getTypeDefaultValue('.google.firestore.admin.v1.GetIndexRequest', ['name']); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; + const expectedResponse = generateSampleMessage( + new protos.google.firestore.admin.v1.Index() + ); + client.innerApiCalls.getIndex = stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.getIndex( + request, + (err?: Error|null, result?: protos.google.firestore.admin.v1.IIndex|null) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = (client.innerApiCalls.getIndex as SinonStub) + .getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = (client.innerApiCalls.getIndex as SinonStub) + .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes getIndex with closed client', async () => { - const client = new firestoreadminModule.FirestoreAdminClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.initialize(); - const request = generateSampleMessage( - new protos.google.firestore.admin.v1.GetIndexRequest() - ); - const defaultValue1 = getTypeDefaultValue( - '.google.firestore.admin.v1.GetIndexRequest', - ['name'] - ); - request.name = defaultValue1; - const expectedError = new Error('The client has already been closed.'); - client.close(); - await assert.rejects(client.getIndex(request), expectedError); - }); - }); - - describe('deleteIndex', () => { - it('invokes deleteIndex without error', async () => { - const client = new firestoreadminModule.FirestoreAdminClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.initialize(); - const request = generateSampleMessage( - new protos.google.firestore.admin.v1.DeleteIndexRequest() - ); - const defaultValue1 = getTypeDefaultValue( - '.google.firestore.admin.v1.DeleteIndexRequest', - ['name'] - ); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; - const expectedResponse = generateSampleMessage( - new protos.google.protobuf.Empty() - ); - client.innerApiCalls.deleteIndex = stubSimpleCall(expectedResponse); - const [response] = await client.deleteIndex(request); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = ( - client.innerApiCalls.deleteIndex as SinonStub - ).getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = ( - client.innerApiCalls.deleteIndex as SinonStub - ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes getIndex with error', async () => { + const client = new firestoreadminModule.FirestoreAdminClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.firestore.admin.v1.GetIndexRequest() + ); + const defaultValue1 = + getTypeDefaultValue('.google.firestore.admin.v1.GetIndexRequest', ['name']); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; + const expectedError = new Error('expected'); + client.innerApiCalls.getIndex = stubSimpleCall(undefined, expectedError); + await assert.rejects(client.getIndex(request), expectedError); + const actualRequest = (client.innerApiCalls.getIndex as SinonStub) + .getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = (client.innerApiCalls.getIndex as SinonStub) + .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes deleteIndex without error using callback', async () => { - const client = new firestoreadminModule.FirestoreAdminClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.initialize(); - const request = generateSampleMessage( - new protos.google.firestore.admin.v1.DeleteIndexRequest() - ); - const defaultValue1 = getTypeDefaultValue( - '.google.firestore.admin.v1.DeleteIndexRequest', - ['name'] - ); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; - const expectedResponse = generateSampleMessage( - new protos.google.protobuf.Empty() - ); - client.innerApiCalls.deleteIndex = - stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.deleteIndex( - request, - ( - err?: Error | null, - result?: protos.google.protobuf.IEmpty | null - ) => { - if (err) { - reject(err); - } else { - resolve(result); - } - } - ); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = ( - client.innerApiCalls.deleteIndex as SinonStub - ).getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = ( - client.innerApiCalls.deleteIndex as SinonStub - ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + it('invokes getIndex with closed client', async () => { + const client = new firestoreadminModule.FirestoreAdminClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.firestore.admin.v1.GetIndexRequest() + ); + const defaultValue1 = + getTypeDefaultValue('.google.firestore.admin.v1.GetIndexRequest', ['name']); + request.name = defaultValue1; + const expectedError = new Error('The client has already been closed.'); + client.close().catch(err => {throw err}); + await assert.rejects(client.getIndex(request), expectedError); + }); }); - it('invokes deleteIndex with error', async () => { - const client = new firestoreadminModule.FirestoreAdminClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.initialize(); - const request = generateSampleMessage( - new protos.google.firestore.admin.v1.DeleteIndexRequest() - ); - const defaultValue1 = getTypeDefaultValue( - '.google.firestore.admin.v1.DeleteIndexRequest', - ['name'] - ); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; - const expectedError = new Error('expected'); - client.innerApiCalls.deleteIndex = stubSimpleCall( - undefined, - expectedError - ); - await assert.rejects(client.deleteIndex(request), expectedError); - const actualRequest = ( - client.innerApiCalls.deleteIndex as SinonStub - ).getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = ( - client.innerApiCalls.deleteIndex as SinonStub - ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + describe('deleteIndex', () => { + it('invokes deleteIndex without error', async () => { + const client = new firestoreadminModule.FirestoreAdminClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.firestore.admin.v1.DeleteIndexRequest() + ); + const defaultValue1 = + getTypeDefaultValue('.google.firestore.admin.v1.DeleteIndexRequest', ['name']); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; + const expectedResponse = generateSampleMessage( + new protos.google.protobuf.Empty() + ); + client.innerApiCalls.deleteIndex = stubSimpleCall(expectedResponse); + const [response] = await client.deleteIndex(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = (client.innerApiCalls.deleteIndex as SinonStub) + .getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = (client.innerApiCalls.deleteIndex as SinonStub) + .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes deleteIndex with closed client', async () => { - const client = new firestoreadminModule.FirestoreAdminClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.initialize(); - const request = generateSampleMessage( - new protos.google.firestore.admin.v1.DeleteIndexRequest() - ); - const defaultValue1 = getTypeDefaultValue( - '.google.firestore.admin.v1.DeleteIndexRequest', - ['name'] - ); - request.name = defaultValue1; - const expectedError = new Error('The client has already been closed.'); - client.close(); - await assert.rejects(client.deleteIndex(request), expectedError); - }); - }); - - describe('getField', () => { - it('invokes getField without error', async () => { - const client = new firestoreadminModule.FirestoreAdminClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.initialize(); - const request = generateSampleMessage( - new protos.google.firestore.admin.v1.GetFieldRequest() - ); - const defaultValue1 = getTypeDefaultValue( - '.google.firestore.admin.v1.GetFieldRequest', - ['name'] - ); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; - const expectedResponse = generateSampleMessage( - new protos.google.firestore.admin.v1.Field() - ); - client.innerApiCalls.getField = stubSimpleCall(expectedResponse); - const [response] = await client.getField(request); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = ( - client.innerApiCalls.getField as SinonStub - ).getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = ( - client.innerApiCalls.getField as SinonStub - ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes deleteIndex without error using callback', async () => { + const client = new firestoreadminModule.FirestoreAdminClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.firestore.admin.v1.DeleteIndexRequest() + ); + const defaultValue1 = + getTypeDefaultValue('.google.firestore.admin.v1.DeleteIndexRequest', ['name']); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; + const expectedResponse = generateSampleMessage( + new protos.google.protobuf.Empty() + ); + client.innerApiCalls.deleteIndex = stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.deleteIndex( + request, + (err?: Error|null, result?: protos.google.protobuf.IEmpty|null) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = (client.innerApiCalls.deleteIndex as SinonStub) + .getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = (client.innerApiCalls.deleteIndex as SinonStub) + .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes getField without error using callback', async () => { - const client = new firestoreadminModule.FirestoreAdminClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.initialize(); - const request = generateSampleMessage( - new protos.google.firestore.admin.v1.GetFieldRequest() - ); - const defaultValue1 = getTypeDefaultValue( - '.google.firestore.admin.v1.GetFieldRequest', - ['name'] - ); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; - const expectedResponse = generateSampleMessage( - new protos.google.firestore.admin.v1.Field() - ); - client.innerApiCalls.getField = - stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.getField( - request, - ( - err?: Error | null, - result?: protos.google.firestore.admin.v1.IField | null - ) => { - if (err) { - reject(err); - } else { - resolve(result); - } - } - ); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = ( - client.innerApiCalls.getField as SinonStub - ).getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = ( - client.innerApiCalls.getField as SinonStub - ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes deleteIndex with error', async () => { + const client = new firestoreadminModule.FirestoreAdminClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.firestore.admin.v1.DeleteIndexRequest() + ); + const defaultValue1 = + getTypeDefaultValue('.google.firestore.admin.v1.DeleteIndexRequest', ['name']); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; + const expectedError = new Error('expected'); + client.innerApiCalls.deleteIndex = stubSimpleCall(undefined, expectedError); + await assert.rejects(client.deleteIndex(request), expectedError); + const actualRequest = (client.innerApiCalls.deleteIndex as SinonStub) + .getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = (client.innerApiCalls.deleteIndex as SinonStub) + .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes getField with error', async () => { - const client = new firestoreadminModule.FirestoreAdminClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.initialize(); - const request = generateSampleMessage( - new protos.google.firestore.admin.v1.GetFieldRequest() - ); - const defaultValue1 = getTypeDefaultValue( - '.google.firestore.admin.v1.GetFieldRequest', - ['name'] - ); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; - const expectedError = new Error('expected'); - client.innerApiCalls.getField = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.getField(request), expectedError); - const actualRequest = ( - client.innerApiCalls.getField as SinonStub - ).getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = ( - client.innerApiCalls.getField as SinonStub - ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + it('invokes deleteIndex with closed client', async () => { + const client = new firestoreadminModule.FirestoreAdminClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.firestore.admin.v1.DeleteIndexRequest() + ); + const defaultValue1 = + getTypeDefaultValue('.google.firestore.admin.v1.DeleteIndexRequest', ['name']); + request.name = defaultValue1; + const expectedError = new Error('The client has already been closed.'); + client.close().catch(err => {throw err}); + await assert.rejects(client.deleteIndex(request), expectedError); + }); }); - it('invokes getField with closed client', async () => { - const client = new firestoreadminModule.FirestoreAdminClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.initialize(); - const request = generateSampleMessage( - new protos.google.firestore.admin.v1.GetFieldRequest() - ); - const defaultValue1 = getTypeDefaultValue( - '.google.firestore.admin.v1.GetFieldRequest', - ['name'] - ); - request.name = defaultValue1; - const expectedError = new Error('The client has already been closed.'); - client.close(); - await assert.rejects(client.getField(request), expectedError); - }); - }); - - describe('getDatabase', () => { - it('invokes getDatabase without error', async () => { - const client = new firestoreadminModule.FirestoreAdminClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.initialize(); - const request = generateSampleMessage( - new protos.google.firestore.admin.v1.GetDatabaseRequest() - ); - const defaultValue1 = getTypeDefaultValue( - '.google.firestore.admin.v1.GetDatabaseRequest', - ['name'] - ); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; - const expectedResponse = generateSampleMessage( - new protos.google.firestore.admin.v1.Database() - ); - client.innerApiCalls.getDatabase = stubSimpleCall(expectedResponse); - const [response] = await client.getDatabase(request); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = ( - client.innerApiCalls.getDatabase as SinonStub - ).getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = ( - client.innerApiCalls.getDatabase as SinonStub - ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + describe('getField', () => { + it('invokes getField without error', async () => { + const client = new firestoreadminModule.FirestoreAdminClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.firestore.admin.v1.GetFieldRequest() + ); + const defaultValue1 = + getTypeDefaultValue('.google.firestore.admin.v1.GetFieldRequest', ['name']); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; + const expectedResponse = generateSampleMessage( + new protos.google.firestore.admin.v1.Field() + ); + client.innerApiCalls.getField = stubSimpleCall(expectedResponse); + const [response] = await client.getField(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = (client.innerApiCalls.getField as SinonStub) + .getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = (client.innerApiCalls.getField as SinonStub) + .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes getDatabase without error using callback', async () => { - const client = new firestoreadminModule.FirestoreAdminClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.initialize(); - const request = generateSampleMessage( - new protos.google.firestore.admin.v1.GetDatabaseRequest() - ); - const defaultValue1 = getTypeDefaultValue( - '.google.firestore.admin.v1.GetDatabaseRequest', - ['name'] - ); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; - const expectedResponse = generateSampleMessage( - new protos.google.firestore.admin.v1.Database() - ); - client.innerApiCalls.getDatabase = - stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.getDatabase( - request, - ( - err?: Error | null, - result?: protos.google.firestore.admin.v1.IDatabase | null - ) => { - if (err) { - reject(err); - } else { - resolve(result); - } - } - ); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = ( - client.innerApiCalls.getDatabase as SinonStub - ).getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = ( - client.innerApiCalls.getDatabase as SinonStub - ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes getField without error using callback', async () => { + const client = new firestoreadminModule.FirestoreAdminClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.firestore.admin.v1.GetFieldRequest() + ); + const defaultValue1 = + getTypeDefaultValue('.google.firestore.admin.v1.GetFieldRequest', ['name']); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; + const expectedResponse = generateSampleMessage( + new protos.google.firestore.admin.v1.Field() + ); + client.innerApiCalls.getField = stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.getField( + request, + (err?: Error|null, result?: protos.google.firestore.admin.v1.IField|null) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = (client.innerApiCalls.getField as SinonStub) + .getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = (client.innerApiCalls.getField as SinonStub) + .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes getDatabase with error', async () => { - const client = new firestoreadminModule.FirestoreAdminClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.initialize(); - const request = generateSampleMessage( - new protos.google.firestore.admin.v1.GetDatabaseRequest() - ); - const defaultValue1 = getTypeDefaultValue( - '.google.firestore.admin.v1.GetDatabaseRequest', - ['name'] - ); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; - const expectedError = new Error('expected'); - client.innerApiCalls.getDatabase = stubSimpleCall( - undefined, - expectedError - ); - await assert.rejects(client.getDatabase(request), expectedError); - const actualRequest = ( - client.innerApiCalls.getDatabase as SinonStub - ).getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = ( - client.innerApiCalls.getDatabase as SinonStub - ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes getField with error', async () => { + const client = new firestoreadminModule.FirestoreAdminClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.firestore.admin.v1.GetFieldRequest() + ); + const defaultValue1 = + getTypeDefaultValue('.google.firestore.admin.v1.GetFieldRequest', ['name']); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; + const expectedError = new Error('expected'); + client.innerApiCalls.getField = stubSimpleCall(undefined, expectedError); + await assert.rejects(client.getField(request), expectedError); + const actualRequest = (client.innerApiCalls.getField as SinonStub) + .getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = (client.innerApiCalls.getField as SinonStub) + .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes getDatabase with closed client', async () => { - const client = new firestoreadminModule.FirestoreAdminClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.initialize(); - const request = generateSampleMessage( - new protos.google.firestore.admin.v1.GetDatabaseRequest() - ); - const defaultValue1 = getTypeDefaultValue( - '.google.firestore.admin.v1.GetDatabaseRequest', - ['name'] - ); - request.name = defaultValue1; - const expectedError = new Error('The client has already been closed.'); - client.close(); - await assert.rejects(client.getDatabase(request), expectedError); - }); - }); - - describe('listDatabases', () => { - it('invokes listDatabases without error', async () => { - const client = new firestoreadminModule.FirestoreAdminClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.initialize(); - const request = generateSampleMessage( - new protos.google.firestore.admin.v1.ListDatabasesRequest() - ); - const defaultValue1 = getTypeDefaultValue( - '.google.firestore.admin.v1.ListDatabasesRequest', - ['parent'] - ); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; - const expectedResponse = generateSampleMessage( - new protos.google.firestore.admin.v1.ListDatabasesResponse() - ); - client.innerApiCalls.listDatabases = stubSimpleCall(expectedResponse); - const [response] = await client.listDatabases(request); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = ( - client.innerApiCalls.listDatabases as SinonStub - ).getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = ( - client.innerApiCalls.listDatabases as SinonStub - ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + it('invokes getField with closed client', async () => { + const client = new firestoreadminModule.FirestoreAdminClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.firestore.admin.v1.GetFieldRequest() + ); + const defaultValue1 = + getTypeDefaultValue('.google.firestore.admin.v1.GetFieldRequest', ['name']); + request.name = defaultValue1; + const expectedError = new Error('The client has already been closed.'); + client.close().catch(err => {throw err}); + await assert.rejects(client.getField(request), expectedError); + }); }); - it('invokes listDatabases without error using callback', async () => { - const client = new firestoreadminModule.FirestoreAdminClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.initialize(); - const request = generateSampleMessage( - new protos.google.firestore.admin.v1.ListDatabasesRequest() - ); - const defaultValue1 = getTypeDefaultValue( - '.google.firestore.admin.v1.ListDatabasesRequest', - ['parent'] - ); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; - const expectedResponse = generateSampleMessage( - new protos.google.firestore.admin.v1.ListDatabasesResponse() - ); - client.innerApiCalls.listDatabases = - stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.listDatabases( - request, - ( - err?: Error | null, - result?: protos.google.firestore.admin.v1.IListDatabasesResponse | null - ) => { - if (err) { - reject(err); - } else { - resolve(result); - } - } - ); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = ( - client.innerApiCalls.listDatabases as SinonStub - ).getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = ( - client.innerApiCalls.listDatabases as SinonStub - ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + describe('getDatabase', () => { + it('invokes getDatabase without error', async () => { + const client = new firestoreadminModule.FirestoreAdminClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.firestore.admin.v1.GetDatabaseRequest() + ); + const defaultValue1 = + getTypeDefaultValue('.google.firestore.admin.v1.GetDatabaseRequest', ['name']); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; + const expectedResponse = generateSampleMessage( + new protos.google.firestore.admin.v1.Database() + ); + client.innerApiCalls.getDatabase = stubSimpleCall(expectedResponse); + const [response] = await client.getDatabase(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = (client.innerApiCalls.getDatabase as SinonStub) + .getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = (client.innerApiCalls.getDatabase as SinonStub) + .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes listDatabases with error', async () => { - const client = new firestoreadminModule.FirestoreAdminClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.initialize(); - const request = generateSampleMessage( - new protos.google.firestore.admin.v1.ListDatabasesRequest() - ); - const defaultValue1 = getTypeDefaultValue( - '.google.firestore.admin.v1.ListDatabasesRequest', - ['parent'] - ); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; - const expectedError = new Error('expected'); - client.innerApiCalls.listDatabases = stubSimpleCall( - undefined, - expectedError - ); - await assert.rejects(client.listDatabases(request), expectedError); - const actualRequest = ( - client.innerApiCalls.listDatabases as SinonStub - ).getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = ( - client.innerApiCalls.listDatabases as SinonStub - ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes getDatabase without error using callback', async () => { + const client = new firestoreadminModule.FirestoreAdminClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.firestore.admin.v1.GetDatabaseRequest() + ); + const defaultValue1 = + getTypeDefaultValue('.google.firestore.admin.v1.GetDatabaseRequest', ['name']); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; + const expectedResponse = generateSampleMessage( + new protos.google.firestore.admin.v1.Database() + ); + client.innerApiCalls.getDatabase = stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.getDatabase( + request, + (err?: Error|null, result?: protos.google.firestore.admin.v1.IDatabase|null) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = (client.innerApiCalls.getDatabase as SinonStub) + .getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = (client.innerApiCalls.getDatabase as SinonStub) + .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes listDatabases with closed client', async () => { - const client = new firestoreadminModule.FirestoreAdminClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.initialize(); - const request = generateSampleMessage( - new protos.google.firestore.admin.v1.ListDatabasesRequest() - ); - const defaultValue1 = getTypeDefaultValue( - '.google.firestore.admin.v1.ListDatabasesRequest', - ['parent'] - ); - request.parent = defaultValue1; - const expectedError = new Error('The client has already been closed.'); - client.close(); - await assert.rejects(client.listDatabases(request), expectedError); - }); - }); - - describe('getBackup', () => { - it('invokes getBackup without error', async () => { - const client = new firestoreadminModule.FirestoreAdminClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.initialize(); - const request = generateSampleMessage( - new protos.google.firestore.admin.v1.GetBackupRequest() - ); - const defaultValue1 = getTypeDefaultValue( - '.google.firestore.admin.v1.GetBackupRequest', - ['name'] - ); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; - const expectedResponse = generateSampleMessage( - new protos.google.firestore.admin.v1.Backup() - ); - client.innerApiCalls.getBackup = stubSimpleCall(expectedResponse); - const [response] = await client.getBackup(request); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = ( - client.innerApiCalls.getBackup as SinonStub - ).getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = ( - client.innerApiCalls.getBackup as SinonStub - ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes getDatabase with error', async () => { + const client = new firestoreadminModule.FirestoreAdminClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.firestore.admin.v1.GetDatabaseRequest() + ); + const defaultValue1 = + getTypeDefaultValue('.google.firestore.admin.v1.GetDatabaseRequest', ['name']); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; + const expectedError = new Error('expected'); + client.innerApiCalls.getDatabase = stubSimpleCall(undefined, expectedError); + await assert.rejects(client.getDatabase(request), expectedError); + const actualRequest = (client.innerApiCalls.getDatabase as SinonStub) + .getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = (client.innerApiCalls.getDatabase as SinonStub) + .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes getBackup without error using callback', async () => { - const client = new firestoreadminModule.FirestoreAdminClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.initialize(); - const request = generateSampleMessage( - new protos.google.firestore.admin.v1.GetBackupRequest() - ); - const defaultValue1 = getTypeDefaultValue( - '.google.firestore.admin.v1.GetBackupRequest', - ['name'] - ); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; - const expectedResponse = generateSampleMessage( - new protos.google.firestore.admin.v1.Backup() - ); - client.innerApiCalls.getBackup = - stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.getBackup( - request, - ( - err?: Error | null, - result?: protos.google.firestore.admin.v1.IBackup | null - ) => { - if (err) { - reject(err); - } else { - resolve(result); - } - } - ); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = ( - client.innerApiCalls.getBackup as SinonStub - ).getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = ( - client.innerApiCalls.getBackup as SinonStub - ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + it('invokes getDatabase with closed client', async () => { + const client = new firestoreadminModule.FirestoreAdminClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.firestore.admin.v1.GetDatabaseRequest() + ); + const defaultValue1 = + getTypeDefaultValue('.google.firestore.admin.v1.GetDatabaseRequest', ['name']); + request.name = defaultValue1; + const expectedError = new Error('The client has already been closed.'); + client.close().catch(err => {throw err}); + await assert.rejects(client.getDatabase(request), expectedError); + }); }); - it('invokes getBackup with error', async () => { - const client = new firestoreadminModule.FirestoreAdminClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.initialize(); - const request = generateSampleMessage( - new protos.google.firestore.admin.v1.GetBackupRequest() - ); - const defaultValue1 = getTypeDefaultValue( - '.google.firestore.admin.v1.GetBackupRequest', - ['name'] - ); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; - const expectedError = new Error('expected'); - client.innerApiCalls.getBackup = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.getBackup(request), expectedError); - const actualRequest = ( - client.innerApiCalls.getBackup as SinonStub - ).getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = ( - client.innerApiCalls.getBackup as SinonStub - ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + describe('listDatabases', () => { + it('invokes listDatabases without error', async () => { + const client = new firestoreadminModule.FirestoreAdminClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.firestore.admin.v1.ListDatabasesRequest() + ); + const defaultValue1 = + getTypeDefaultValue('.google.firestore.admin.v1.ListDatabasesRequest', ['parent']); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; + const expectedResponse = generateSampleMessage( + new protos.google.firestore.admin.v1.ListDatabasesResponse() + ); + client.innerApiCalls.listDatabases = stubSimpleCall(expectedResponse); + const [response] = await client.listDatabases(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = (client.innerApiCalls.listDatabases as SinonStub) + .getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = (client.innerApiCalls.listDatabases as SinonStub) + .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes getBackup with closed client', async () => { - const client = new firestoreadminModule.FirestoreAdminClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.initialize(); - const request = generateSampleMessage( - new protos.google.firestore.admin.v1.GetBackupRequest() - ); - const defaultValue1 = getTypeDefaultValue( - '.google.firestore.admin.v1.GetBackupRequest', - ['name'] - ); - request.name = defaultValue1; - const expectedError = new Error('The client has already been closed.'); - client.close(); - await assert.rejects(client.getBackup(request), expectedError); - }); - }); - - describe('listBackups', () => { - it('invokes listBackups without error', async () => { - const client = new firestoreadminModule.FirestoreAdminClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.initialize(); - const request = generateSampleMessage( - new protos.google.firestore.admin.v1.ListBackupsRequest() - ); - const defaultValue1 = getTypeDefaultValue( - '.google.firestore.admin.v1.ListBackupsRequest', - ['parent'] - ); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; - const expectedResponse = generateSampleMessage( - new protos.google.firestore.admin.v1.ListBackupsResponse() - ); - client.innerApiCalls.listBackups = stubSimpleCall(expectedResponse); - const [response] = await client.listBackups(request); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = ( - client.innerApiCalls.listBackups as SinonStub - ).getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = ( - client.innerApiCalls.listBackups as SinonStub - ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes listDatabases without error using callback', async () => { + const client = new firestoreadminModule.FirestoreAdminClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.firestore.admin.v1.ListDatabasesRequest() + ); + const defaultValue1 = + getTypeDefaultValue('.google.firestore.admin.v1.ListDatabasesRequest', ['parent']); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; + const expectedResponse = generateSampleMessage( + new protos.google.firestore.admin.v1.ListDatabasesResponse() + ); + client.innerApiCalls.listDatabases = stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.listDatabases( + request, + (err?: Error|null, result?: protos.google.firestore.admin.v1.IListDatabasesResponse|null) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = (client.innerApiCalls.listDatabases as SinonStub) + .getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = (client.innerApiCalls.listDatabases as SinonStub) + .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes listBackups without error using callback', async () => { - const client = new firestoreadminModule.FirestoreAdminClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.initialize(); - const request = generateSampleMessage( - new protos.google.firestore.admin.v1.ListBackupsRequest() - ); - const defaultValue1 = getTypeDefaultValue( - '.google.firestore.admin.v1.ListBackupsRequest', - ['parent'] - ); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; - const expectedResponse = generateSampleMessage( - new protos.google.firestore.admin.v1.ListBackupsResponse() - ); - client.innerApiCalls.listBackups = - stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.listBackups( - request, - ( - err?: Error | null, - result?: protos.google.firestore.admin.v1.IListBackupsResponse | null - ) => { - if (err) { - reject(err); - } else { - resolve(result); - } - } - ); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = ( - client.innerApiCalls.listBackups as SinonStub - ).getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = ( - client.innerApiCalls.listBackups as SinonStub - ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes listDatabases with error', async () => { + const client = new firestoreadminModule.FirestoreAdminClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.firestore.admin.v1.ListDatabasesRequest() + ); + const defaultValue1 = + getTypeDefaultValue('.google.firestore.admin.v1.ListDatabasesRequest', ['parent']); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; + const expectedError = new Error('expected'); + client.innerApiCalls.listDatabases = stubSimpleCall(undefined, expectedError); + await assert.rejects(client.listDatabases(request), expectedError); + const actualRequest = (client.innerApiCalls.listDatabases as SinonStub) + .getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = (client.innerApiCalls.listDatabases as SinonStub) + .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes listBackups with error', async () => { - const client = new firestoreadminModule.FirestoreAdminClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.initialize(); - const request = generateSampleMessage( - new protos.google.firestore.admin.v1.ListBackupsRequest() - ); - const defaultValue1 = getTypeDefaultValue( - '.google.firestore.admin.v1.ListBackupsRequest', - ['parent'] - ); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; - const expectedError = new Error('expected'); - client.innerApiCalls.listBackups = stubSimpleCall( - undefined, - expectedError - ); - await assert.rejects(client.listBackups(request), expectedError); - const actualRequest = ( - client.innerApiCalls.listBackups as SinonStub - ).getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = ( - client.innerApiCalls.listBackups as SinonStub - ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + it('invokes listDatabases with closed client', async () => { + const client = new firestoreadminModule.FirestoreAdminClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.firestore.admin.v1.ListDatabasesRequest() + ); + const defaultValue1 = + getTypeDefaultValue('.google.firestore.admin.v1.ListDatabasesRequest', ['parent']); + request.parent = defaultValue1; + const expectedError = new Error('The client has already been closed.'); + client.close().catch(err => {throw err}); + await assert.rejects(client.listDatabases(request), expectedError); + }); }); - it('invokes listBackups with closed client', async () => { - const client = new firestoreadminModule.FirestoreAdminClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.initialize(); - const request = generateSampleMessage( - new protos.google.firestore.admin.v1.ListBackupsRequest() - ); - const defaultValue1 = getTypeDefaultValue( - '.google.firestore.admin.v1.ListBackupsRequest', - ['parent'] - ); - request.parent = defaultValue1; - const expectedError = new Error('The client has already been closed.'); - client.close(); - await assert.rejects(client.listBackups(request), expectedError); - }); - }); - - describe('deleteBackup', () => { - it('invokes deleteBackup without error', async () => { - const client = new firestoreadminModule.FirestoreAdminClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.initialize(); - const request = generateSampleMessage( - new protos.google.firestore.admin.v1.DeleteBackupRequest() - ); - const defaultValue1 = getTypeDefaultValue( - '.google.firestore.admin.v1.DeleteBackupRequest', - ['name'] - ); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; - const expectedResponse = generateSampleMessage( - new protos.google.protobuf.Empty() - ); - client.innerApiCalls.deleteBackup = stubSimpleCall(expectedResponse); - const [response] = await client.deleteBackup(request); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = ( - client.innerApiCalls.deleteBackup as SinonStub - ).getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = ( - client.innerApiCalls.deleteBackup as SinonStub - ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + describe('createUserCreds', () => { + it('invokes createUserCreds without error', async () => { + const client = new firestoreadminModule.FirestoreAdminClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.firestore.admin.v1.CreateUserCredsRequest() + ); + const defaultValue1 = + getTypeDefaultValue('.google.firestore.admin.v1.CreateUserCredsRequest', ['parent']); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; + const expectedResponse = generateSampleMessage( + new protos.google.firestore.admin.v1.UserCreds() + ); + client.innerApiCalls.createUserCreds = stubSimpleCall(expectedResponse); + const [response] = await client.createUserCreds(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = (client.innerApiCalls.createUserCreds as SinonStub) + .getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = (client.innerApiCalls.createUserCreds as SinonStub) + .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes deleteBackup without error using callback', async () => { - const client = new firestoreadminModule.FirestoreAdminClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.initialize(); - const request = generateSampleMessage( - new protos.google.firestore.admin.v1.DeleteBackupRequest() - ); - const defaultValue1 = getTypeDefaultValue( - '.google.firestore.admin.v1.DeleteBackupRequest', - ['name'] - ); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; - const expectedResponse = generateSampleMessage( - new protos.google.protobuf.Empty() - ); - client.innerApiCalls.deleteBackup = - stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.deleteBackup( - request, - ( - err?: Error | null, - result?: protos.google.protobuf.IEmpty | null - ) => { - if (err) { - reject(err); - } else { - resolve(result); - } - } - ); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = ( - client.innerApiCalls.deleteBackup as SinonStub - ).getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = ( - client.innerApiCalls.deleteBackup as SinonStub - ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes createUserCreds without error using callback', async () => { + const client = new firestoreadminModule.FirestoreAdminClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.firestore.admin.v1.CreateUserCredsRequest() + ); + const defaultValue1 = + getTypeDefaultValue('.google.firestore.admin.v1.CreateUserCredsRequest', ['parent']); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; + const expectedResponse = generateSampleMessage( + new protos.google.firestore.admin.v1.UserCreds() + ); + client.innerApiCalls.createUserCreds = stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.createUserCreds( + request, + (err?: Error|null, result?: protos.google.firestore.admin.v1.IUserCreds|null) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = (client.innerApiCalls.createUserCreds as SinonStub) + .getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = (client.innerApiCalls.createUserCreds as SinonStub) + .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes deleteBackup with error', async () => { - const client = new firestoreadminModule.FirestoreAdminClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.initialize(); - const request = generateSampleMessage( - new protos.google.firestore.admin.v1.DeleteBackupRequest() - ); - const defaultValue1 = getTypeDefaultValue( - '.google.firestore.admin.v1.DeleteBackupRequest', - ['name'] - ); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; - const expectedError = new Error('expected'); - client.innerApiCalls.deleteBackup = stubSimpleCall( - undefined, - expectedError - ); - await assert.rejects(client.deleteBackup(request), expectedError); - const actualRequest = ( - client.innerApiCalls.deleteBackup as SinonStub - ).getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = ( - client.innerApiCalls.deleteBackup as SinonStub - ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes createUserCreds with error', async () => { + const client = new firestoreadminModule.FirestoreAdminClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.firestore.admin.v1.CreateUserCredsRequest() + ); + const defaultValue1 = + getTypeDefaultValue('.google.firestore.admin.v1.CreateUserCredsRequest', ['parent']); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; + const expectedError = new Error('expected'); + client.innerApiCalls.createUserCreds = stubSimpleCall(undefined, expectedError); + await assert.rejects(client.createUserCreds(request), expectedError); + const actualRequest = (client.innerApiCalls.createUserCreds as SinonStub) + .getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = (client.innerApiCalls.createUserCreds as SinonStub) + .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes deleteBackup with closed client', async () => { - const client = new firestoreadminModule.FirestoreAdminClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.initialize(); - const request = generateSampleMessage( - new protos.google.firestore.admin.v1.DeleteBackupRequest() - ); - const defaultValue1 = getTypeDefaultValue( - '.google.firestore.admin.v1.DeleteBackupRequest', - ['name'] - ); - request.name = defaultValue1; - const expectedError = new Error('The client has already been closed.'); - client.close(); - await assert.rejects(client.deleteBackup(request), expectedError); - }); - }); - - describe('createBackupSchedule', () => { - it('invokes createBackupSchedule without error', async () => { - const client = new firestoreadminModule.FirestoreAdminClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.initialize(); - const request = generateSampleMessage( - new protos.google.firestore.admin.v1.CreateBackupScheduleRequest() - ); - const defaultValue1 = getTypeDefaultValue( - '.google.firestore.admin.v1.CreateBackupScheduleRequest', - ['parent'] - ); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; - const expectedResponse = generateSampleMessage( - new protos.google.firestore.admin.v1.BackupSchedule() - ); - client.innerApiCalls.createBackupSchedule = - stubSimpleCall(expectedResponse); - const [response] = await client.createBackupSchedule(request); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = ( - client.innerApiCalls.createBackupSchedule as SinonStub - ).getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = ( - client.innerApiCalls.createBackupSchedule as SinonStub - ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + it('invokes createUserCreds with closed client', async () => { + const client = new firestoreadminModule.FirestoreAdminClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.firestore.admin.v1.CreateUserCredsRequest() + ); + const defaultValue1 = + getTypeDefaultValue('.google.firestore.admin.v1.CreateUserCredsRequest', ['parent']); + request.parent = defaultValue1; + const expectedError = new Error('The client has already been closed.'); + client.close().catch(err => {throw err}); + await assert.rejects(client.createUserCreds(request), expectedError); + }); }); - it('invokes createBackupSchedule without error using callback', async () => { - const client = new firestoreadminModule.FirestoreAdminClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.initialize(); - const request = generateSampleMessage( - new protos.google.firestore.admin.v1.CreateBackupScheduleRequest() - ); - const defaultValue1 = getTypeDefaultValue( - '.google.firestore.admin.v1.CreateBackupScheduleRequest', - ['parent'] - ); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; - const expectedResponse = generateSampleMessage( - new protos.google.firestore.admin.v1.BackupSchedule() - ); - client.innerApiCalls.createBackupSchedule = - stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.createBackupSchedule( - request, - ( - err?: Error | null, - result?: protos.google.firestore.admin.v1.IBackupSchedule | null - ) => { - if (err) { - reject(err); - } else { - resolve(result); - } - } - ); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = ( - client.innerApiCalls.createBackupSchedule as SinonStub - ).getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = ( - client.innerApiCalls.createBackupSchedule as SinonStub - ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + describe('getUserCreds', () => { + it('invokes getUserCreds without error', async () => { + const client = new firestoreadminModule.FirestoreAdminClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.firestore.admin.v1.GetUserCredsRequest() + ); + const defaultValue1 = + getTypeDefaultValue('.google.firestore.admin.v1.GetUserCredsRequest', ['name']); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; + const expectedResponse = generateSampleMessage( + new protos.google.firestore.admin.v1.UserCreds() + ); + client.innerApiCalls.getUserCreds = stubSimpleCall(expectedResponse); + const [response] = await client.getUserCreds(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = (client.innerApiCalls.getUserCreds as SinonStub) + .getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = (client.innerApiCalls.getUserCreds as SinonStub) + .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes createBackupSchedule with error', async () => { - const client = new firestoreadminModule.FirestoreAdminClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.initialize(); - const request = generateSampleMessage( - new protos.google.firestore.admin.v1.CreateBackupScheduleRequest() - ); - const defaultValue1 = getTypeDefaultValue( - '.google.firestore.admin.v1.CreateBackupScheduleRequest', - ['parent'] - ); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; - const expectedError = new Error('expected'); - client.innerApiCalls.createBackupSchedule = stubSimpleCall( - undefined, - expectedError - ); - await assert.rejects(client.createBackupSchedule(request), expectedError); - const actualRequest = ( - client.innerApiCalls.createBackupSchedule as SinonStub - ).getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = ( - client.innerApiCalls.createBackupSchedule as SinonStub - ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes getUserCreds without error using callback', async () => { + const client = new firestoreadminModule.FirestoreAdminClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.firestore.admin.v1.GetUserCredsRequest() + ); + const defaultValue1 = + getTypeDefaultValue('.google.firestore.admin.v1.GetUserCredsRequest', ['name']); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; + const expectedResponse = generateSampleMessage( + new protos.google.firestore.admin.v1.UserCreds() + ); + client.innerApiCalls.getUserCreds = stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.getUserCreds( + request, + (err?: Error|null, result?: protos.google.firestore.admin.v1.IUserCreds|null) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = (client.innerApiCalls.getUserCreds as SinonStub) + .getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = (client.innerApiCalls.getUserCreds as SinonStub) + .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes createBackupSchedule with closed client', async () => { - const client = new firestoreadminModule.FirestoreAdminClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.initialize(); - const request = generateSampleMessage( - new protos.google.firestore.admin.v1.CreateBackupScheduleRequest() - ); - const defaultValue1 = getTypeDefaultValue( - '.google.firestore.admin.v1.CreateBackupScheduleRequest', - ['parent'] - ); - request.parent = defaultValue1; - const expectedError = new Error('The client has already been closed.'); - client.close(); - await assert.rejects(client.createBackupSchedule(request), expectedError); - }); - }); - - describe('getBackupSchedule', () => { - it('invokes getBackupSchedule without error', async () => { - const client = new firestoreadminModule.FirestoreAdminClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.initialize(); - const request = generateSampleMessage( - new protos.google.firestore.admin.v1.GetBackupScheduleRequest() - ); - const defaultValue1 = getTypeDefaultValue( - '.google.firestore.admin.v1.GetBackupScheduleRequest', - ['name'] - ); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; - const expectedResponse = generateSampleMessage( - new protos.google.firestore.admin.v1.BackupSchedule() - ); - client.innerApiCalls.getBackupSchedule = stubSimpleCall(expectedResponse); - const [response] = await client.getBackupSchedule(request); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = ( - client.innerApiCalls.getBackupSchedule as SinonStub - ).getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = ( - client.innerApiCalls.getBackupSchedule as SinonStub - ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes getUserCreds with error', async () => { + const client = new firestoreadminModule.FirestoreAdminClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.firestore.admin.v1.GetUserCredsRequest() + ); + const defaultValue1 = + getTypeDefaultValue('.google.firestore.admin.v1.GetUserCredsRequest', ['name']); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; + const expectedError = new Error('expected'); + client.innerApiCalls.getUserCreds = stubSimpleCall(undefined, expectedError); + await assert.rejects(client.getUserCreds(request), expectedError); + const actualRequest = (client.innerApiCalls.getUserCreds as SinonStub) + .getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = (client.innerApiCalls.getUserCreds as SinonStub) + .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes getBackupSchedule without error using callback', async () => { - const client = new firestoreadminModule.FirestoreAdminClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.initialize(); - const request = generateSampleMessage( - new protos.google.firestore.admin.v1.GetBackupScheduleRequest() - ); - const defaultValue1 = getTypeDefaultValue( - '.google.firestore.admin.v1.GetBackupScheduleRequest', - ['name'] - ); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; - const expectedResponse = generateSampleMessage( - new protos.google.firestore.admin.v1.BackupSchedule() - ); - client.innerApiCalls.getBackupSchedule = - stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.getBackupSchedule( - request, - ( - err?: Error | null, - result?: protos.google.firestore.admin.v1.IBackupSchedule | null - ) => { - if (err) { - reject(err); - } else { - resolve(result); - } - } - ); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = ( - client.innerApiCalls.getBackupSchedule as SinonStub - ).getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = ( - client.innerApiCalls.getBackupSchedule as SinonStub - ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + it('invokes getUserCreds with closed client', async () => { + const client = new firestoreadminModule.FirestoreAdminClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.firestore.admin.v1.GetUserCredsRequest() + ); + const defaultValue1 = + getTypeDefaultValue('.google.firestore.admin.v1.GetUserCredsRequest', ['name']); + request.name = defaultValue1; + const expectedError = new Error('The client has already been closed.'); + client.close().catch(err => {throw err}); + await assert.rejects(client.getUserCreds(request), expectedError); + }); }); - it('invokes getBackupSchedule with error', async () => { - const client = new firestoreadminModule.FirestoreAdminClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.initialize(); - const request = generateSampleMessage( - new protos.google.firestore.admin.v1.GetBackupScheduleRequest() - ); - const defaultValue1 = getTypeDefaultValue( - '.google.firestore.admin.v1.GetBackupScheduleRequest', - ['name'] - ); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; - const expectedError = new Error('expected'); - client.innerApiCalls.getBackupSchedule = stubSimpleCall( - undefined, - expectedError - ); - await assert.rejects(client.getBackupSchedule(request), expectedError); - const actualRequest = ( - client.innerApiCalls.getBackupSchedule as SinonStub - ).getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = ( - client.innerApiCalls.getBackupSchedule as SinonStub - ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + describe('listUserCreds', () => { + it('invokes listUserCreds without error', async () => { + const client = new firestoreadminModule.FirestoreAdminClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.firestore.admin.v1.ListUserCredsRequest() + ); + const defaultValue1 = + getTypeDefaultValue('.google.firestore.admin.v1.ListUserCredsRequest', ['parent']); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; + const expectedResponse = generateSampleMessage( + new protos.google.firestore.admin.v1.ListUserCredsResponse() + ); + client.innerApiCalls.listUserCreds = stubSimpleCall(expectedResponse); + const [response] = await client.listUserCreds(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = (client.innerApiCalls.listUserCreds as SinonStub) + .getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = (client.innerApiCalls.listUserCreds as SinonStub) + .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes getBackupSchedule with closed client', async () => { - const client = new firestoreadminModule.FirestoreAdminClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.initialize(); - const request = generateSampleMessage( - new protos.google.firestore.admin.v1.GetBackupScheduleRequest() - ); - const defaultValue1 = getTypeDefaultValue( - '.google.firestore.admin.v1.GetBackupScheduleRequest', - ['name'] - ); - request.name = defaultValue1; - const expectedError = new Error('The client has already been closed.'); - client.close(); - await assert.rejects(client.getBackupSchedule(request), expectedError); - }); - }); - - describe('listBackupSchedules', () => { - it('invokes listBackupSchedules without error', async () => { - const client = new firestoreadminModule.FirestoreAdminClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.initialize(); - const request = generateSampleMessage( - new protos.google.firestore.admin.v1.ListBackupSchedulesRequest() - ); - const defaultValue1 = getTypeDefaultValue( - '.google.firestore.admin.v1.ListBackupSchedulesRequest', - ['parent'] - ); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; - const expectedResponse = generateSampleMessage( - new protos.google.firestore.admin.v1.ListBackupSchedulesResponse() - ); - client.innerApiCalls.listBackupSchedules = - stubSimpleCall(expectedResponse); - const [response] = await client.listBackupSchedules(request); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = ( - client.innerApiCalls.listBackupSchedules as SinonStub - ).getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = ( - client.innerApiCalls.listBackupSchedules as SinonStub - ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes listUserCreds without error using callback', async () => { + const client = new firestoreadminModule.FirestoreAdminClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.firestore.admin.v1.ListUserCredsRequest() + ); + const defaultValue1 = + getTypeDefaultValue('.google.firestore.admin.v1.ListUserCredsRequest', ['parent']); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; + const expectedResponse = generateSampleMessage( + new protos.google.firestore.admin.v1.ListUserCredsResponse() + ); + client.innerApiCalls.listUserCreds = stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.listUserCreds( + request, + (err?: Error|null, result?: protos.google.firestore.admin.v1.IListUserCredsResponse|null) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = (client.innerApiCalls.listUserCreds as SinonStub) + .getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = (client.innerApiCalls.listUserCreds as SinonStub) + .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes listBackupSchedules without error using callback', async () => { - const client = new firestoreadminModule.FirestoreAdminClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.initialize(); - const request = generateSampleMessage( - new protos.google.firestore.admin.v1.ListBackupSchedulesRequest() - ); - const defaultValue1 = getTypeDefaultValue( - '.google.firestore.admin.v1.ListBackupSchedulesRequest', - ['parent'] - ); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; - const expectedResponse = generateSampleMessage( - new protos.google.firestore.admin.v1.ListBackupSchedulesResponse() - ); - client.innerApiCalls.listBackupSchedules = - stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.listBackupSchedules( - request, - ( - err?: Error | null, - result?: protos.google.firestore.admin.v1.IListBackupSchedulesResponse | null - ) => { - if (err) { - reject(err); - } else { - resolve(result); - } - } - ); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = ( - client.innerApiCalls.listBackupSchedules as SinonStub - ).getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = ( - client.innerApiCalls.listBackupSchedules as SinonStub - ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes listUserCreds with error', async () => { + const client = new firestoreadminModule.FirestoreAdminClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.firestore.admin.v1.ListUserCredsRequest() + ); + const defaultValue1 = + getTypeDefaultValue('.google.firestore.admin.v1.ListUserCredsRequest', ['parent']); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; + const expectedError = new Error('expected'); + client.innerApiCalls.listUserCreds = stubSimpleCall(undefined, expectedError); + await assert.rejects(client.listUserCreds(request), expectedError); + const actualRequest = (client.innerApiCalls.listUserCreds as SinonStub) + .getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = (client.innerApiCalls.listUserCreds as SinonStub) + .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes listBackupSchedules with error', async () => { - const client = new firestoreadminModule.FirestoreAdminClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.initialize(); - const request = generateSampleMessage( - new protos.google.firestore.admin.v1.ListBackupSchedulesRequest() - ); - const defaultValue1 = getTypeDefaultValue( - '.google.firestore.admin.v1.ListBackupSchedulesRequest', - ['parent'] - ); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; - const expectedError = new Error('expected'); - client.innerApiCalls.listBackupSchedules = stubSimpleCall( - undefined, - expectedError - ); - await assert.rejects(client.listBackupSchedules(request), expectedError); - const actualRequest = ( - client.innerApiCalls.listBackupSchedules as SinonStub - ).getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = ( - client.innerApiCalls.listBackupSchedules as SinonStub - ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + it('invokes listUserCreds with closed client', async () => { + const client = new firestoreadminModule.FirestoreAdminClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.firestore.admin.v1.ListUserCredsRequest() + ); + const defaultValue1 = + getTypeDefaultValue('.google.firestore.admin.v1.ListUserCredsRequest', ['parent']); + request.parent = defaultValue1; + const expectedError = new Error('The client has already been closed.'); + client.close().catch(err => {throw err}); + await assert.rejects(client.listUserCreds(request), expectedError); + }); }); - it('invokes listBackupSchedules with closed client', async () => { - const client = new firestoreadminModule.FirestoreAdminClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.initialize(); - const request = generateSampleMessage( - new protos.google.firestore.admin.v1.ListBackupSchedulesRequest() - ); - const defaultValue1 = getTypeDefaultValue( - '.google.firestore.admin.v1.ListBackupSchedulesRequest', - ['parent'] - ); - request.parent = defaultValue1; - const expectedError = new Error('The client has already been closed.'); - client.close(); - await assert.rejects(client.listBackupSchedules(request), expectedError); - }); - }); - - describe('updateBackupSchedule', () => { - it('invokes updateBackupSchedule without error', async () => { - const client = new firestoreadminModule.FirestoreAdminClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.initialize(); - const request = generateSampleMessage( - new protos.google.firestore.admin.v1.UpdateBackupScheduleRequest() - ); - request.backupSchedule ??= {}; - const defaultValue1 = getTypeDefaultValue( - '.google.firestore.admin.v1.UpdateBackupScheduleRequest', - ['backupSchedule', 'name'] - ); - request.backupSchedule.name = defaultValue1; - const expectedHeaderRequestParams = `backup_schedule.name=${defaultValue1 ?? ''}`; - const expectedResponse = generateSampleMessage( - new protos.google.firestore.admin.v1.BackupSchedule() - ); - client.innerApiCalls.updateBackupSchedule = - stubSimpleCall(expectedResponse); - const [response] = await client.updateBackupSchedule(request); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = ( - client.innerApiCalls.updateBackupSchedule as SinonStub - ).getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = ( - client.innerApiCalls.updateBackupSchedule as SinonStub - ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + describe('enableUserCreds', () => { + it('invokes enableUserCreds without error', async () => { + const client = new firestoreadminModule.FirestoreAdminClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.firestore.admin.v1.EnableUserCredsRequest() + ); + const defaultValue1 = + getTypeDefaultValue('.google.firestore.admin.v1.EnableUserCredsRequest', ['name']); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; + const expectedResponse = generateSampleMessage( + new protos.google.firestore.admin.v1.UserCreds() + ); + client.innerApiCalls.enableUserCreds = stubSimpleCall(expectedResponse); + const [response] = await client.enableUserCreds(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = (client.innerApiCalls.enableUserCreds as SinonStub) + .getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = (client.innerApiCalls.enableUserCreds as SinonStub) + .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes updateBackupSchedule without error using callback', async () => { - const client = new firestoreadminModule.FirestoreAdminClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.initialize(); - const request = generateSampleMessage( - new protos.google.firestore.admin.v1.UpdateBackupScheduleRequest() - ); - request.backupSchedule ??= {}; - const defaultValue1 = getTypeDefaultValue( - '.google.firestore.admin.v1.UpdateBackupScheduleRequest', - ['backupSchedule', 'name'] - ); - request.backupSchedule.name = defaultValue1; - const expectedHeaderRequestParams = `backup_schedule.name=${defaultValue1 ?? ''}`; - const expectedResponse = generateSampleMessage( - new protos.google.firestore.admin.v1.BackupSchedule() - ); - client.innerApiCalls.updateBackupSchedule = - stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.updateBackupSchedule( - request, - ( - err?: Error | null, - result?: protos.google.firestore.admin.v1.IBackupSchedule | null - ) => { - if (err) { - reject(err); - } else { - resolve(result); - } - } - ); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = ( - client.innerApiCalls.updateBackupSchedule as SinonStub - ).getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = ( - client.innerApiCalls.updateBackupSchedule as SinonStub - ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes enableUserCreds without error using callback', async () => { + const client = new firestoreadminModule.FirestoreAdminClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.firestore.admin.v1.EnableUserCredsRequest() + ); + const defaultValue1 = + getTypeDefaultValue('.google.firestore.admin.v1.EnableUserCredsRequest', ['name']); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; + const expectedResponse = generateSampleMessage( + new protos.google.firestore.admin.v1.UserCreds() + ); + client.innerApiCalls.enableUserCreds = stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.enableUserCreds( + request, + (err?: Error|null, result?: protos.google.firestore.admin.v1.IUserCreds|null) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = (client.innerApiCalls.enableUserCreds as SinonStub) + .getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = (client.innerApiCalls.enableUserCreds as SinonStub) + .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes updateBackupSchedule with error', async () => { - const client = new firestoreadminModule.FirestoreAdminClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.initialize(); - const request = generateSampleMessage( - new protos.google.firestore.admin.v1.UpdateBackupScheduleRequest() - ); - request.backupSchedule ??= {}; - const defaultValue1 = getTypeDefaultValue( - '.google.firestore.admin.v1.UpdateBackupScheduleRequest', - ['backupSchedule', 'name'] - ); - request.backupSchedule.name = defaultValue1; - const expectedHeaderRequestParams = `backup_schedule.name=${defaultValue1 ?? ''}`; - const expectedError = new Error('expected'); - client.innerApiCalls.updateBackupSchedule = stubSimpleCall( - undefined, - expectedError - ); - await assert.rejects(client.updateBackupSchedule(request), expectedError); - const actualRequest = ( - client.innerApiCalls.updateBackupSchedule as SinonStub - ).getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = ( - client.innerApiCalls.updateBackupSchedule as SinonStub - ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes enableUserCreds with error', async () => { + const client = new firestoreadminModule.FirestoreAdminClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.firestore.admin.v1.EnableUserCredsRequest() + ); + const defaultValue1 = + getTypeDefaultValue('.google.firestore.admin.v1.EnableUserCredsRequest', ['name']); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; + const expectedError = new Error('expected'); + client.innerApiCalls.enableUserCreds = stubSimpleCall(undefined, expectedError); + await assert.rejects(client.enableUserCreds(request), expectedError); + const actualRequest = (client.innerApiCalls.enableUserCreds as SinonStub) + .getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = (client.innerApiCalls.enableUserCreds as SinonStub) + .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes updateBackupSchedule with closed client', async () => { - const client = new firestoreadminModule.FirestoreAdminClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.initialize(); - const request = generateSampleMessage( - new protos.google.firestore.admin.v1.UpdateBackupScheduleRequest() - ); - request.backupSchedule ??= {}; - const defaultValue1 = getTypeDefaultValue( - '.google.firestore.admin.v1.UpdateBackupScheduleRequest', - ['backupSchedule', 'name'] - ); - request.backupSchedule.name = defaultValue1; - const expectedError = new Error('The client has already been closed.'); - client.close(); - await assert.rejects(client.updateBackupSchedule(request), expectedError); - }); - }); - - describe('deleteBackupSchedule', () => { - it('invokes deleteBackupSchedule without error', async () => { - const client = new firestoreadminModule.FirestoreAdminClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.initialize(); - const request = generateSampleMessage( - new protos.google.firestore.admin.v1.DeleteBackupScheduleRequest() - ); - const defaultValue1 = getTypeDefaultValue( - '.google.firestore.admin.v1.DeleteBackupScheduleRequest', - ['name'] - ); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; - const expectedResponse = generateSampleMessage( - new protos.google.protobuf.Empty() - ); - client.innerApiCalls.deleteBackupSchedule = - stubSimpleCall(expectedResponse); - const [response] = await client.deleteBackupSchedule(request); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = ( - client.innerApiCalls.deleteBackupSchedule as SinonStub - ).getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = ( - client.innerApiCalls.deleteBackupSchedule as SinonStub - ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + it('invokes enableUserCreds with closed client', async () => { + const client = new firestoreadminModule.FirestoreAdminClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.firestore.admin.v1.EnableUserCredsRequest() + ); + const defaultValue1 = + getTypeDefaultValue('.google.firestore.admin.v1.EnableUserCredsRequest', ['name']); + request.name = defaultValue1; + const expectedError = new Error('The client has already been closed.'); + client.close().catch(err => {throw err}); + await assert.rejects(client.enableUserCreds(request), expectedError); + }); }); - it('invokes deleteBackupSchedule without error using callback', async () => { - const client = new firestoreadminModule.FirestoreAdminClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.initialize(); - const request = generateSampleMessage( - new protos.google.firestore.admin.v1.DeleteBackupScheduleRequest() - ); - const defaultValue1 = getTypeDefaultValue( - '.google.firestore.admin.v1.DeleteBackupScheduleRequest', - ['name'] - ); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; - const expectedResponse = generateSampleMessage( - new protos.google.protobuf.Empty() - ); - client.innerApiCalls.deleteBackupSchedule = - stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.deleteBackupSchedule( - request, - ( - err?: Error | null, - result?: protos.google.protobuf.IEmpty | null - ) => { - if (err) { - reject(err); - } else { - resolve(result); - } - } - ); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = ( - client.innerApiCalls.deleteBackupSchedule as SinonStub - ).getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = ( - client.innerApiCalls.deleteBackupSchedule as SinonStub - ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + describe('disableUserCreds', () => { + it('invokes disableUserCreds without error', async () => { + const client = new firestoreadminModule.FirestoreAdminClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.firestore.admin.v1.DisableUserCredsRequest() + ); + const defaultValue1 = + getTypeDefaultValue('.google.firestore.admin.v1.DisableUserCredsRequest', ['name']); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; + const expectedResponse = generateSampleMessage( + new protos.google.firestore.admin.v1.UserCreds() + ); + client.innerApiCalls.disableUserCreds = stubSimpleCall(expectedResponse); + const [response] = await client.disableUserCreds(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = (client.innerApiCalls.disableUserCreds as SinonStub) + .getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = (client.innerApiCalls.disableUserCreds as SinonStub) + .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes deleteBackupSchedule with error', async () => { - const client = new firestoreadminModule.FirestoreAdminClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.initialize(); - const request = generateSampleMessage( - new protos.google.firestore.admin.v1.DeleteBackupScheduleRequest() - ); - const defaultValue1 = getTypeDefaultValue( - '.google.firestore.admin.v1.DeleteBackupScheduleRequest', - ['name'] - ); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; - const expectedError = new Error('expected'); - client.innerApiCalls.deleteBackupSchedule = stubSimpleCall( - undefined, - expectedError - ); - await assert.rejects(client.deleteBackupSchedule(request), expectedError); - const actualRequest = ( - client.innerApiCalls.deleteBackupSchedule as SinonStub - ).getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = ( - client.innerApiCalls.deleteBackupSchedule as SinonStub - ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes disableUserCreds without error using callback', async () => { + const client = new firestoreadminModule.FirestoreAdminClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.firestore.admin.v1.DisableUserCredsRequest() + ); + const defaultValue1 = + getTypeDefaultValue('.google.firestore.admin.v1.DisableUserCredsRequest', ['name']); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; + const expectedResponse = generateSampleMessage( + new protos.google.firestore.admin.v1.UserCreds() + ); + client.innerApiCalls.disableUserCreds = stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.disableUserCreds( + request, + (err?: Error|null, result?: protos.google.firestore.admin.v1.IUserCreds|null) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = (client.innerApiCalls.disableUserCreds as SinonStub) + .getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = (client.innerApiCalls.disableUserCreds as SinonStub) + .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes deleteBackupSchedule with closed client', async () => { - const client = new firestoreadminModule.FirestoreAdminClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.initialize(); - const request = generateSampleMessage( - new protos.google.firestore.admin.v1.DeleteBackupScheduleRequest() - ); - const defaultValue1 = getTypeDefaultValue( - '.google.firestore.admin.v1.DeleteBackupScheduleRequest', - ['name'] - ); - request.name = defaultValue1; - const expectedError = new Error('The client has already been closed.'); - client.close(); - await assert.rejects(client.deleteBackupSchedule(request), expectedError); - }); - }); - - describe('createIndex', () => { - it('invokes createIndex without error', async () => { - const client = new firestoreadminModule.FirestoreAdminClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.initialize(); - const request = generateSampleMessage( - new protos.google.firestore.admin.v1.CreateIndexRequest() - ); - const defaultValue1 = getTypeDefaultValue( - '.google.firestore.admin.v1.CreateIndexRequest', - ['parent'] - ); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; - const expectedResponse = generateSampleMessage( - new protos.google.longrunning.Operation() - ); - client.innerApiCalls.createIndex = stubLongRunningCall(expectedResponse); - const [operation] = await client.createIndex(request); - const [response] = await operation.promise(); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = ( - client.innerApiCalls.createIndex as SinonStub - ).getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = ( - client.innerApiCalls.createIndex as SinonStub - ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes disableUserCreds with error', async () => { + const client = new firestoreadminModule.FirestoreAdminClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.firestore.admin.v1.DisableUserCredsRequest() + ); + const defaultValue1 = + getTypeDefaultValue('.google.firestore.admin.v1.DisableUserCredsRequest', ['name']); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; + const expectedError = new Error('expected'); + client.innerApiCalls.disableUserCreds = stubSimpleCall(undefined, expectedError); + await assert.rejects(client.disableUserCreds(request), expectedError); + const actualRequest = (client.innerApiCalls.disableUserCreds as SinonStub) + .getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = (client.innerApiCalls.disableUserCreds as SinonStub) + .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes createIndex without error using callback', async () => { - const client = new firestoreadminModule.FirestoreAdminClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.initialize(); - const request = generateSampleMessage( - new protos.google.firestore.admin.v1.CreateIndexRequest() - ); - const defaultValue1 = getTypeDefaultValue( - '.google.firestore.admin.v1.CreateIndexRequest', - ['parent'] - ); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; - const expectedResponse = generateSampleMessage( - new protos.google.longrunning.Operation() - ); - client.innerApiCalls.createIndex = - stubLongRunningCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.createIndex( - request, - ( - err?: Error | null, - result?: LROperation< - protos.google.firestore.admin.v1.IIndex, - protos.google.firestore.admin.v1.IIndexOperationMetadata - > | null - ) => { - if (err) { - reject(err); - } else { - resolve(result); - } - } - ); - }); - const operation = (await promise) as LROperation< - protos.google.firestore.admin.v1.IIndex, - protos.google.firestore.admin.v1.IIndexOperationMetadata - >; - const [response] = await operation.promise(); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = ( - client.innerApiCalls.createIndex as SinonStub - ).getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = ( - client.innerApiCalls.createIndex as SinonStub - ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + it('invokes disableUserCreds with closed client', async () => { + const client = new firestoreadminModule.FirestoreAdminClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.firestore.admin.v1.DisableUserCredsRequest() + ); + const defaultValue1 = + getTypeDefaultValue('.google.firestore.admin.v1.DisableUserCredsRequest', ['name']); + request.name = defaultValue1; + const expectedError = new Error('The client has already been closed.'); + client.close().catch(err => {throw err}); + await assert.rejects(client.disableUserCreds(request), expectedError); + }); }); - it('invokes createIndex with call error', async () => { - const client = new firestoreadminModule.FirestoreAdminClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.initialize(); - const request = generateSampleMessage( - new protos.google.firestore.admin.v1.CreateIndexRequest() - ); - const defaultValue1 = getTypeDefaultValue( - '.google.firestore.admin.v1.CreateIndexRequest', - ['parent'] - ); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; - const expectedError = new Error('expected'); - client.innerApiCalls.createIndex = stubLongRunningCall( - undefined, - expectedError - ); - await assert.rejects(client.createIndex(request), expectedError); - const actualRequest = ( - client.innerApiCalls.createIndex as SinonStub - ).getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = ( - client.innerApiCalls.createIndex as SinonStub - ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + describe('resetUserPassword', () => { + it('invokes resetUserPassword without error', async () => { + const client = new firestoreadminModule.FirestoreAdminClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.firestore.admin.v1.ResetUserPasswordRequest() + ); + const defaultValue1 = + getTypeDefaultValue('.google.firestore.admin.v1.ResetUserPasswordRequest', ['name']); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; + const expectedResponse = generateSampleMessage( + new protos.google.firestore.admin.v1.UserCreds() + ); + client.innerApiCalls.resetUserPassword = stubSimpleCall(expectedResponse); + const [response] = await client.resetUserPassword(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = (client.innerApiCalls.resetUserPassword as SinonStub) + .getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = (client.innerApiCalls.resetUserPassword as SinonStub) + .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes createIndex with LRO error', async () => { - const client = new firestoreadminModule.FirestoreAdminClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.initialize(); - const request = generateSampleMessage( - new protos.google.firestore.admin.v1.CreateIndexRequest() - ); - const defaultValue1 = getTypeDefaultValue( - '.google.firestore.admin.v1.CreateIndexRequest', - ['parent'] - ); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; - const expectedError = new Error('expected'); - client.innerApiCalls.createIndex = stubLongRunningCall( - undefined, - undefined, - expectedError - ); - const [operation] = await client.createIndex(request); - await assert.rejects(operation.promise(), expectedError); - const actualRequest = ( - client.innerApiCalls.createIndex as SinonStub - ).getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = ( - client.innerApiCalls.createIndex as SinonStub - ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes resetUserPassword without error using callback', async () => { + const client = new firestoreadminModule.FirestoreAdminClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.firestore.admin.v1.ResetUserPasswordRequest() + ); + const defaultValue1 = + getTypeDefaultValue('.google.firestore.admin.v1.ResetUserPasswordRequest', ['name']); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; + const expectedResponse = generateSampleMessage( + new protos.google.firestore.admin.v1.UserCreds() + ); + client.innerApiCalls.resetUserPassword = stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.resetUserPassword( + request, + (err?: Error|null, result?: protos.google.firestore.admin.v1.IUserCreds|null) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = (client.innerApiCalls.resetUserPassword as SinonStub) + .getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = (client.innerApiCalls.resetUserPassword as SinonStub) + .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes checkCreateIndexProgress without error', async () => { - const client = new firestoreadminModule.FirestoreAdminClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.initialize(); - const expectedResponse = generateSampleMessage( - new operationsProtos.google.longrunning.Operation() - ); - expectedResponse.name = 'test'; - expectedResponse.response = {type_url: 'url', value: Buffer.from('')}; - expectedResponse.metadata = {type_url: 'url', value: Buffer.from('')}; - - client.operationsClient.getOperation = stubSimpleCall(expectedResponse); - const decodedOperation = await client.checkCreateIndexProgress( - expectedResponse.name - ); - assert.deepStrictEqual(decodedOperation.name, expectedResponse.name); - assert(decodedOperation.metadata); - assert((client.operationsClient.getOperation as SinonStub).getCall(0)); - }); + it('invokes resetUserPassword with error', async () => { + const client = new firestoreadminModule.FirestoreAdminClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.firestore.admin.v1.ResetUserPasswordRequest() + ); + const defaultValue1 = + getTypeDefaultValue('.google.firestore.admin.v1.ResetUserPasswordRequest', ['name']); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; + const expectedError = new Error('expected'); + client.innerApiCalls.resetUserPassword = stubSimpleCall(undefined, expectedError); + await assert.rejects(client.resetUserPassword(request), expectedError); + const actualRequest = (client.innerApiCalls.resetUserPassword as SinonStub) + .getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = (client.innerApiCalls.resetUserPassword as SinonStub) + .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes checkCreateIndexProgress with error', async () => { - const client = new firestoreadminModule.FirestoreAdminClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.initialize(); - const expectedError = new Error('expected'); - - client.operationsClient.getOperation = stubSimpleCall( - undefined, - expectedError - ); - await assert.rejects(client.checkCreateIndexProgress(''), expectedError); - assert((client.operationsClient.getOperation as SinonStub).getCall(0)); - }); - }); - - describe('updateField', () => { - it('invokes updateField without error', async () => { - const client = new firestoreadminModule.FirestoreAdminClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.initialize(); - const request = generateSampleMessage( - new protos.google.firestore.admin.v1.UpdateFieldRequest() - ); - request.field ??= {}; - const defaultValue1 = getTypeDefaultValue( - '.google.firestore.admin.v1.UpdateFieldRequest', - ['field', 'name'] - ); - request.field.name = defaultValue1; - const expectedHeaderRequestParams = `field.name=${defaultValue1 ?? ''}`; - const expectedResponse = generateSampleMessage( - new protos.google.longrunning.Operation() - ); - client.innerApiCalls.updateField = stubLongRunningCall(expectedResponse); - const [operation] = await client.updateField(request); - const [response] = await operation.promise(); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = ( - client.innerApiCalls.updateField as SinonStub - ).getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = ( - client.innerApiCalls.updateField as SinonStub - ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + it('invokes resetUserPassword with closed client', async () => { + const client = new firestoreadminModule.FirestoreAdminClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.firestore.admin.v1.ResetUserPasswordRequest() + ); + const defaultValue1 = + getTypeDefaultValue('.google.firestore.admin.v1.ResetUserPasswordRequest', ['name']); + request.name = defaultValue1; + const expectedError = new Error('The client has already been closed.'); + client.close().catch(err => {throw err}); + await assert.rejects(client.resetUserPassword(request), expectedError); + }); }); - it('invokes updateField without error using callback', async () => { - const client = new firestoreadminModule.FirestoreAdminClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.initialize(); - const request = generateSampleMessage( - new protos.google.firestore.admin.v1.UpdateFieldRequest() - ); - request.field ??= {}; - const defaultValue1 = getTypeDefaultValue( - '.google.firestore.admin.v1.UpdateFieldRequest', - ['field', 'name'] - ); - request.field.name = defaultValue1; - const expectedHeaderRequestParams = `field.name=${defaultValue1 ?? ''}`; - const expectedResponse = generateSampleMessage( - new protos.google.longrunning.Operation() - ); - client.innerApiCalls.updateField = - stubLongRunningCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.updateField( - request, - ( - err?: Error | null, - result?: LROperation< - protos.google.firestore.admin.v1.IField, - protos.google.firestore.admin.v1.IFieldOperationMetadata - > | null - ) => { - if (err) { - reject(err); - } else { - resolve(result); - } - } - ); - }); - const operation = (await promise) as LROperation< - protos.google.firestore.admin.v1.IField, - protos.google.firestore.admin.v1.IFieldOperationMetadata - >; - const [response] = await operation.promise(); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = ( - client.innerApiCalls.updateField as SinonStub - ).getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = ( - client.innerApiCalls.updateField as SinonStub - ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + describe('deleteUserCreds', () => { + it('invokes deleteUserCreds without error', async () => { + const client = new firestoreadminModule.FirestoreAdminClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.firestore.admin.v1.DeleteUserCredsRequest() + ); + const defaultValue1 = + getTypeDefaultValue('.google.firestore.admin.v1.DeleteUserCredsRequest', ['name']); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; + const expectedResponse = generateSampleMessage( + new protos.google.protobuf.Empty() + ); + client.innerApiCalls.deleteUserCreds = stubSimpleCall(expectedResponse); + const [response] = await client.deleteUserCreds(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = (client.innerApiCalls.deleteUserCreds as SinonStub) + .getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = (client.innerApiCalls.deleteUserCreds as SinonStub) + .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes updateField with call error', async () => { - const client = new firestoreadminModule.FirestoreAdminClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.initialize(); - const request = generateSampleMessage( - new protos.google.firestore.admin.v1.UpdateFieldRequest() - ); - request.field ??= {}; - const defaultValue1 = getTypeDefaultValue( - '.google.firestore.admin.v1.UpdateFieldRequest', - ['field', 'name'] - ); - request.field.name = defaultValue1; - const expectedHeaderRequestParams = `field.name=${defaultValue1 ?? ''}`; - const expectedError = new Error('expected'); - client.innerApiCalls.updateField = stubLongRunningCall( - undefined, - expectedError - ); - await assert.rejects(client.updateField(request), expectedError); - const actualRequest = ( - client.innerApiCalls.updateField as SinonStub - ).getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = ( - client.innerApiCalls.updateField as SinonStub - ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes deleteUserCreds without error using callback', async () => { + const client = new firestoreadminModule.FirestoreAdminClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.firestore.admin.v1.DeleteUserCredsRequest() + ); + const defaultValue1 = + getTypeDefaultValue('.google.firestore.admin.v1.DeleteUserCredsRequest', ['name']); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; + const expectedResponse = generateSampleMessage( + new protos.google.protobuf.Empty() + ); + client.innerApiCalls.deleteUserCreds = stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.deleteUserCreds( + request, + (err?: Error|null, result?: protos.google.protobuf.IEmpty|null) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = (client.innerApiCalls.deleteUserCreds as SinonStub) + .getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = (client.innerApiCalls.deleteUserCreds as SinonStub) + .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes updateField with LRO error', async () => { - const client = new firestoreadminModule.FirestoreAdminClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.initialize(); - const request = generateSampleMessage( - new protos.google.firestore.admin.v1.UpdateFieldRequest() - ); - request.field ??= {}; - const defaultValue1 = getTypeDefaultValue( - '.google.firestore.admin.v1.UpdateFieldRequest', - ['field', 'name'] - ); - request.field.name = defaultValue1; - const expectedHeaderRequestParams = `field.name=${defaultValue1 ?? ''}`; - const expectedError = new Error('expected'); - client.innerApiCalls.updateField = stubLongRunningCall( - undefined, - undefined, - expectedError - ); - const [operation] = await client.updateField(request); - await assert.rejects(operation.promise(), expectedError); - const actualRequest = ( - client.innerApiCalls.updateField as SinonStub - ).getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = ( - client.innerApiCalls.updateField as SinonStub - ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes deleteUserCreds with error', async () => { + const client = new firestoreadminModule.FirestoreAdminClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.firestore.admin.v1.DeleteUserCredsRequest() + ); + const defaultValue1 = + getTypeDefaultValue('.google.firestore.admin.v1.DeleteUserCredsRequest', ['name']); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; + const expectedError = new Error('expected'); + client.innerApiCalls.deleteUserCreds = stubSimpleCall(undefined, expectedError); + await assert.rejects(client.deleteUserCreds(request), expectedError); + const actualRequest = (client.innerApiCalls.deleteUserCreds as SinonStub) + .getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = (client.innerApiCalls.deleteUserCreds as SinonStub) + .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes checkUpdateFieldProgress without error', async () => { - const client = new firestoreadminModule.FirestoreAdminClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.initialize(); - const expectedResponse = generateSampleMessage( - new operationsProtos.google.longrunning.Operation() - ); - expectedResponse.name = 'test'; - expectedResponse.response = {type_url: 'url', value: Buffer.from('')}; - expectedResponse.metadata = {type_url: 'url', value: Buffer.from('')}; - - client.operationsClient.getOperation = stubSimpleCall(expectedResponse); - const decodedOperation = await client.checkUpdateFieldProgress( - expectedResponse.name - ); - assert.deepStrictEqual(decodedOperation.name, expectedResponse.name); - assert(decodedOperation.metadata); - assert((client.operationsClient.getOperation as SinonStub).getCall(0)); + it('invokes deleteUserCreds with closed client', async () => { + const client = new firestoreadminModule.FirestoreAdminClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.firestore.admin.v1.DeleteUserCredsRequest() + ); + const defaultValue1 = + getTypeDefaultValue('.google.firestore.admin.v1.DeleteUserCredsRequest', ['name']); + request.name = defaultValue1; + const expectedError = new Error('The client has already been closed.'); + client.close().catch(err => {throw err}); + await assert.rejects(client.deleteUserCreds(request), expectedError); + }); }); - it('invokes checkUpdateFieldProgress with error', async () => { - const client = new firestoreadminModule.FirestoreAdminClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.initialize(); - const expectedError = new Error('expected'); - - client.operationsClient.getOperation = stubSimpleCall( - undefined, - expectedError - ); - await assert.rejects(client.checkUpdateFieldProgress(''), expectedError); - assert((client.operationsClient.getOperation as SinonStub).getCall(0)); - }); - }); - - describe('exportDocuments', () => { - it('invokes exportDocuments without error', async () => { - const client = new firestoreadminModule.FirestoreAdminClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.initialize(); - const request = generateSampleMessage( - new protos.google.firestore.admin.v1.ExportDocumentsRequest() - ); - const defaultValue1 = getTypeDefaultValue( - '.google.firestore.admin.v1.ExportDocumentsRequest', - ['name'] - ); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; - const expectedResponse = generateSampleMessage( - new protos.google.longrunning.Operation() - ); - client.innerApiCalls.exportDocuments = - stubLongRunningCall(expectedResponse); - const [operation] = await client.exportDocuments(request); - const [response] = await operation.promise(); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = ( - client.innerApiCalls.exportDocuments as SinonStub - ).getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = ( - client.innerApiCalls.exportDocuments as SinonStub - ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + describe('getBackup', () => { + it('invokes getBackup without error', async () => { + const client = new firestoreadminModule.FirestoreAdminClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.firestore.admin.v1.GetBackupRequest() + ); + const defaultValue1 = + getTypeDefaultValue('.google.firestore.admin.v1.GetBackupRequest', ['name']); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; + const expectedResponse = generateSampleMessage( + new protos.google.firestore.admin.v1.Backup() + ); + client.innerApiCalls.getBackup = stubSimpleCall(expectedResponse); + const [response] = await client.getBackup(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = (client.innerApiCalls.getBackup as SinonStub) + .getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = (client.innerApiCalls.getBackup as SinonStub) + .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes exportDocuments without error using callback', async () => { - const client = new firestoreadminModule.FirestoreAdminClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.initialize(); - const request = generateSampleMessage( - new protos.google.firestore.admin.v1.ExportDocumentsRequest() - ); - const defaultValue1 = getTypeDefaultValue( - '.google.firestore.admin.v1.ExportDocumentsRequest', - ['name'] - ); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; - const expectedResponse = generateSampleMessage( - new protos.google.longrunning.Operation() - ); - client.innerApiCalls.exportDocuments = - stubLongRunningCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.exportDocuments( - request, - ( - err?: Error | null, - result?: LROperation< - protos.google.firestore.admin.v1.IExportDocumentsResponse, - protos.google.firestore.admin.v1.IExportDocumentsMetadata - > | null - ) => { - if (err) { - reject(err); - } else { - resolve(result); - } - } - ); - }); - const operation = (await promise) as LROperation< - protos.google.firestore.admin.v1.IExportDocumentsResponse, - protos.google.firestore.admin.v1.IExportDocumentsMetadata - >; - const [response] = await operation.promise(); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = ( - client.innerApiCalls.exportDocuments as SinonStub - ).getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = ( - client.innerApiCalls.exportDocuments as SinonStub - ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes getBackup without error using callback', async () => { + const client = new firestoreadminModule.FirestoreAdminClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.firestore.admin.v1.GetBackupRequest() + ); + const defaultValue1 = + getTypeDefaultValue('.google.firestore.admin.v1.GetBackupRequest', ['name']); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; + const expectedResponse = generateSampleMessage( + new protos.google.firestore.admin.v1.Backup() + ); + client.innerApiCalls.getBackup = stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.getBackup( + request, + (err?: Error|null, result?: protos.google.firestore.admin.v1.IBackup|null) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = (client.innerApiCalls.getBackup as SinonStub) + .getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = (client.innerApiCalls.getBackup as SinonStub) + .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes exportDocuments with call error', async () => { - const client = new firestoreadminModule.FirestoreAdminClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.initialize(); - const request = generateSampleMessage( - new protos.google.firestore.admin.v1.ExportDocumentsRequest() - ); - const defaultValue1 = getTypeDefaultValue( - '.google.firestore.admin.v1.ExportDocumentsRequest', - ['name'] - ); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; - const expectedError = new Error('expected'); - client.innerApiCalls.exportDocuments = stubLongRunningCall( - undefined, - expectedError - ); - await assert.rejects(client.exportDocuments(request), expectedError); - const actualRequest = ( - client.innerApiCalls.exportDocuments as SinonStub - ).getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = ( - client.innerApiCalls.exportDocuments as SinonStub - ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes getBackup with error', async () => { + const client = new firestoreadminModule.FirestoreAdminClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.firestore.admin.v1.GetBackupRequest() + ); + const defaultValue1 = + getTypeDefaultValue('.google.firestore.admin.v1.GetBackupRequest', ['name']); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; + const expectedError = new Error('expected'); + client.innerApiCalls.getBackup = stubSimpleCall(undefined, expectedError); + await assert.rejects(client.getBackup(request), expectedError); + const actualRequest = (client.innerApiCalls.getBackup as SinonStub) + .getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = (client.innerApiCalls.getBackup as SinonStub) + .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes exportDocuments with LRO error', async () => { - const client = new firestoreadminModule.FirestoreAdminClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.initialize(); - const request = generateSampleMessage( - new protos.google.firestore.admin.v1.ExportDocumentsRequest() - ); - const defaultValue1 = getTypeDefaultValue( - '.google.firestore.admin.v1.ExportDocumentsRequest', - ['name'] - ); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; - const expectedError = new Error('expected'); - client.innerApiCalls.exportDocuments = stubLongRunningCall( - undefined, - undefined, - expectedError - ); - const [operation] = await client.exportDocuments(request); - await assert.rejects(operation.promise(), expectedError); - const actualRequest = ( - client.innerApiCalls.exportDocuments as SinonStub - ).getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = ( - client.innerApiCalls.exportDocuments as SinonStub - ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + it('invokes getBackup with closed client', async () => { + const client = new firestoreadminModule.FirestoreAdminClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.firestore.admin.v1.GetBackupRequest() + ); + const defaultValue1 = + getTypeDefaultValue('.google.firestore.admin.v1.GetBackupRequest', ['name']); + request.name = defaultValue1; + const expectedError = new Error('The client has already been closed.'); + client.close().catch(err => {throw err}); + await assert.rejects(client.getBackup(request), expectedError); + }); }); - it('invokes checkExportDocumentsProgress without error', async () => { - const client = new firestoreadminModule.FirestoreAdminClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.initialize(); - const expectedResponse = generateSampleMessage( - new operationsProtos.google.longrunning.Operation() - ); - expectedResponse.name = 'test'; - expectedResponse.response = {type_url: 'url', value: Buffer.from('')}; - expectedResponse.metadata = {type_url: 'url', value: Buffer.from('')}; - - client.operationsClient.getOperation = stubSimpleCall(expectedResponse); - const decodedOperation = await client.checkExportDocumentsProgress( - expectedResponse.name - ); - assert.deepStrictEqual(decodedOperation.name, expectedResponse.name); - assert(decodedOperation.metadata); - assert((client.operationsClient.getOperation as SinonStub).getCall(0)); - }); + describe('listBackups', () => { + it('invokes listBackups without error', async () => { + const client = new firestoreadminModule.FirestoreAdminClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.firestore.admin.v1.ListBackupsRequest() + ); + const defaultValue1 = + getTypeDefaultValue('.google.firestore.admin.v1.ListBackupsRequest', ['parent']); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; + const expectedResponse = generateSampleMessage( + new protos.google.firestore.admin.v1.ListBackupsResponse() + ); + client.innerApiCalls.listBackups = stubSimpleCall(expectedResponse); + const [response] = await client.listBackups(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = (client.innerApiCalls.listBackups as SinonStub) + .getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = (client.innerApiCalls.listBackups as SinonStub) + .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes checkExportDocumentsProgress with error', async () => { - const client = new firestoreadminModule.FirestoreAdminClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.initialize(); - const expectedError = new Error('expected'); - - client.operationsClient.getOperation = stubSimpleCall( - undefined, - expectedError - ); - await assert.rejects( - client.checkExportDocumentsProgress(''), - expectedError - ); - assert((client.operationsClient.getOperation as SinonStub).getCall(0)); - }); - }); - - describe('importDocuments', () => { - it('invokes importDocuments without error', async () => { - const client = new firestoreadminModule.FirestoreAdminClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.initialize(); - const request = generateSampleMessage( - new protos.google.firestore.admin.v1.ImportDocumentsRequest() - ); - const defaultValue1 = getTypeDefaultValue( - '.google.firestore.admin.v1.ImportDocumentsRequest', - ['name'] - ); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; - const expectedResponse = generateSampleMessage( - new protos.google.longrunning.Operation() - ); - client.innerApiCalls.importDocuments = - stubLongRunningCall(expectedResponse); - const [operation] = await client.importDocuments(request); - const [response] = await operation.promise(); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = ( - client.innerApiCalls.importDocuments as SinonStub - ).getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = ( - client.innerApiCalls.importDocuments as SinonStub - ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes listBackups without error using callback', async () => { + const client = new firestoreadminModule.FirestoreAdminClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.firestore.admin.v1.ListBackupsRequest() + ); + const defaultValue1 = + getTypeDefaultValue('.google.firestore.admin.v1.ListBackupsRequest', ['parent']); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; + const expectedResponse = generateSampleMessage( + new protos.google.firestore.admin.v1.ListBackupsResponse() + ); + client.innerApiCalls.listBackups = stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.listBackups( + request, + (err?: Error|null, result?: protos.google.firestore.admin.v1.IListBackupsResponse|null) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = (client.innerApiCalls.listBackups as SinonStub) + .getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = (client.innerApiCalls.listBackups as SinonStub) + .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes importDocuments without error using callback', async () => { - const client = new firestoreadminModule.FirestoreAdminClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.initialize(); - const request = generateSampleMessage( - new protos.google.firestore.admin.v1.ImportDocumentsRequest() - ); - const defaultValue1 = getTypeDefaultValue( - '.google.firestore.admin.v1.ImportDocumentsRequest', - ['name'] - ); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; - const expectedResponse = generateSampleMessage( - new protos.google.longrunning.Operation() - ); - client.innerApiCalls.importDocuments = - stubLongRunningCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.importDocuments( - request, - ( - err?: Error | null, - result?: LROperation< - protos.google.protobuf.IEmpty, - protos.google.firestore.admin.v1.IImportDocumentsMetadata - > | null - ) => { - if (err) { - reject(err); - } else { - resolve(result); - } - } - ); - }); - const operation = (await promise) as LROperation< - protos.google.protobuf.IEmpty, - protos.google.firestore.admin.v1.IImportDocumentsMetadata - >; - const [response] = await operation.promise(); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = ( - client.innerApiCalls.importDocuments as SinonStub - ).getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = ( - client.innerApiCalls.importDocuments as SinonStub - ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes listBackups with error', async () => { + const client = new firestoreadminModule.FirestoreAdminClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.firestore.admin.v1.ListBackupsRequest() + ); + const defaultValue1 = + getTypeDefaultValue('.google.firestore.admin.v1.ListBackupsRequest', ['parent']); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; + const expectedError = new Error('expected'); + client.innerApiCalls.listBackups = stubSimpleCall(undefined, expectedError); + await assert.rejects(client.listBackups(request), expectedError); + const actualRequest = (client.innerApiCalls.listBackups as SinonStub) + .getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = (client.innerApiCalls.listBackups as SinonStub) + .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes importDocuments with call error', async () => { - const client = new firestoreadminModule.FirestoreAdminClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.initialize(); - const request = generateSampleMessage( - new protos.google.firestore.admin.v1.ImportDocumentsRequest() - ); - const defaultValue1 = getTypeDefaultValue( - '.google.firestore.admin.v1.ImportDocumentsRequest', - ['name'] - ); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; - const expectedError = new Error('expected'); - client.innerApiCalls.importDocuments = stubLongRunningCall( - undefined, - expectedError - ); - await assert.rejects(client.importDocuments(request), expectedError); - const actualRequest = ( - client.innerApiCalls.importDocuments as SinonStub - ).getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = ( - client.innerApiCalls.importDocuments as SinonStub - ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + it('invokes listBackups with closed client', async () => { + const client = new firestoreadminModule.FirestoreAdminClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.firestore.admin.v1.ListBackupsRequest() + ); + const defaultValue1 = + getTypeDefaultValue('.google.firestore.admin.v1.ListBackupsRequest', ['parent']); + request.parent = defaultValue1; + const expectedError = new Error('The client has already been closed.'); + client.close().catch(err => {throw err}); + await assert.rejects(client.listBackups(request), expectedError); + }); }); - it('invokes importDocuments with LRO error', async () => { - const client = new firestoreadminModule.FirestoreAdminClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.initialize(); - const request = generateSampleMessage( - new protos.google.firestore.admin.v1.ImportDocumentsRequest() - ); - const defaultValue1 = getTypeDefaultValue( - '.google.firestore.admin.v1.ImportDocumentsRequest', - ['name'] - ); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; - const expectedError = new Error('expected'); - client.innerApiCalls.importDocuments = stubLongRunningCall( - undefined, - undefined, - expectedError - ); - const [operation] = await client.importDocuments(request); - await assert.rejects(operation.promise(), expectedError); - const actualRequest = ( - client.innerApiCalls.importDocuments as SinonStub - ).getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = ( - client.innerApiCalls.importDocuments as SinonStub - ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + describe('deleteBackup', () => { + it('invokes deleteBackup without error', async () => { + const client = new firestoreadminModule.FirestoreAdminClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.firestore.admin.v1.DeleteBackupRequest() + ); + const defaultValue1 = + getTypeDefaultValue('.google.firestore.admin.v1.DeleteBackupRequest', ['name']); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; + const expectedResponse = generateSampleMessage( + new protos.google.protobuf.Empty() + ); + client.innerApiCalls.deleteBackup = stubSimpleCall(expectedResponse); + const [response] = await client.deleteBackup(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = (client.innerApiCalls.deleteBackup as SinonStub) + .getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = (client.innerApiCalls.deleteBackup as SinonStub) + .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes checkImportDocumentsProgress without error', async () => { - const client = new firestoreadminModule.FirestoreAdminClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.initialize(); - const expectedResponse = generateSampleMessage( - new operationsProtos.google.longrunning.Operation() - ); - expectedResponse.name = 'test'; - expectedResponse.response = {type_url: 'url', value: Buffer.from('')}; - expectedResponse.metadata = {type_url: 'url', value: Buffer.from('')}; - - client.operationsClient.getOperation = stubSimpleCall(expectedResponse); - const decodedOperation = await client.checkImportDocumentsProgress( - expectedResponse.name - ); - assert.deepStrictEqual(decodedOperation.name, expectedResponse.name); - assert(decodedOperation.metadata); - assert((client.operationsClient.getOperation as SinonStub).getCall(0)); - }); + it('invokes deleteBackup without error using callback', async () => { + const client = new firestoreadminModule.FirestoreAdminClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.firestore.admin.v1.DeleteBackupRequest() + ); + const defaultValue1 = + getTypeDefaultValue('.google.firestore.admin.v1.DeleteBackupRequest', ['name']); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; + const expectedResponse = generateSampleMessage( + new protos.google.protobuf.Empty() + ); + client.innerApiCalls.deleteBackup = stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.deleteBackup( + request, + (err?: Error|null, result?: protos.google.protobuf.IEmpty|null) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = (client.innerApiCalls.deleteBackup as SinonStub) + .getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = (client.innerApiCalls.deleteBackup as SinonStub) + .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes checkImportDocumentsProgress with error', async () => { - const client = new firestoreadminModule.FirestoreAdminClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.initialize(); - const expectedError = new Error('expected'); - - client.operationsClient.getOperation = stubSimpleCall( - undefined, - expectedError - ); - await assert.rejects( - client.checkImportDocumentsProgress(''), - expectedError - ); - assert((client.operationsClient.getOperation as SinonStub).getCall(0)); - }); - }); - - describe('bulkDeleteDocuments', () => { - it('invokes bulkDeleteDocuments without error', async () => { - const client = new firestoreadminModule.FirestoreAdminClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.initialize(); - const request = generateSampleMessage( - new protos.google.firestore.admin.v1.BulkDeleteDocumentsRequest() - ); - const defaultValue1 = getTypeDefaultValue( - '.google.firestore.admin.v1.BulkDeleteDocumentsRequest', - ['name'] - ); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; - const expectedResponse = generateSampleMessage( - new protos.google.longrunning.Operation() - ); - client.innerApiCalls.bulkDeleteDocuments = - stubLongRunningCall(expectedResponse); - const [operation] = await client.bulkDeleteDocuments(request); - const [response] = await operation.promise(); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = ( - client.innerApiCalls.bulkDeleteDocuments as SinonStub - ).getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = ( - client.innerApiCalls.bulkDeleteDocuments as SinonStub - ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes deleteBackup with error', async () => { + const client = new firestoreadminModule.FirestoreAdminClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.firestore.admin.v1.DeleteBackupRequest() + ); + const defaultValue1 = + getTypeDefaultValue('.google.firestore.admin.v1.DeleteBackupRequest', ['name']); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; + const expectedError = new Error('expected'); + client.innerApiCalls.deleteBackup = stubSimpleCall(undefined, expectedError); + await assert.rejects(client.deleteBackup(request), expectedError); + const actualRequest = (client.innerApiCalls.deleteBackup as SinonStub) + .getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = (client.innerApiCalls.deleteBackup as SinonStub) + .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes bulkDeleteDocuments without error using callback', async () => { - const client = new firestoreadminModule.FirestoreAdminClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.initialize(); - const request = generateSampleMessage( - new protos.google.firestore.admin.v1.BulkDeleteDocumentsRequest() - ); - const defaultValue1 = getTypeDefaultValue( - '.google.firestore.admin.v1.BulkDeleteDocumentsRequest', - ['name'] - ); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; - const expectedResponse = generateSampleMessage( - new protos.google.longrunning.Operation() - ); - client.innerApiCalls.bulkDeleteDocuments = - stubLongRunningCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.bulkDeleteDocuments( - request, - ( - err?: Error | null, - result?: LROperation< - protos.google.firestore.admin.v1.IBulkDeleteDocumentsResponse, - protos.google.firestore.admin.v1.IBulkDeleteDocumentsMetadata - > | null - ) => { - if (err) { - reject(err); - } else { - resolve(result); - } - } - ); - }); - const operation = (await promise) as LROperation< - protos.google.firestore.admin.v1.IBulkDeleteDocumentsResponse, - protos.google.firestore.admin.v1.IBulkDeleteDocumentsMetadata - >; - const [response] = await operation.promise(); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = ( - client.innerApiCalls.bulkDeleteDocuments as SinonStub - ).getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = ( - client.innerApiCalls.bulkDeleteDocuments as SinonStub - ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + it('invokes deleteBackup with closed client', async () => { + const client = new firestoreadminModule.FirestoreAdminClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.firestore.admin.v1.DeleteBackupRequest() + ); + const defaultValue1 = + getTypeDefaultValue('.google.firestore.admin.v1.DeleteBackupRequest', ['name']); + request.name = defaultValue1; + const expectedError = new Error('The client has already been closed.'); + client.close().catch(err => {throw err}); + await assert.rejects(client.deleteBackup(request), expectedError); + }); }); - it('invokes bulkDeleteDocuments with call error', async () => { - const client = new firestoreadminModule.FirestoreAdminClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.initialize(); - const request = generateSampleMessage( - new protos.google.firestore.admin.v1.BulkDeleteDocumentsRequest() - ); - const defaultValue1 = getTypeDefaultValue( - '.google.firestore.admin.v1.BulkDeleteDocumentsRequest', - ['name'] - ); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; - const expectedError = new Error('expected'); - client.innerApiCalls.bulkDeleteDocuments = stubLongRunningCall( - undefined, - expectedError - ); - await assert.rejects(client.bulkDeleteDocuments(request), expectedError); - const actualRequest = ( - client.innerApiCalls.bulkDeleteDocuments as SinonStub - ).getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = ( - client.innerApiCalls.bulkDeleteDocuments as SinonStub - ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + describe('createBackupSchedule', () => { + it('invokes createBackupSchedule without error', async () => { + const client = new firestoreadminModule.FirestoreAdminClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.firestore.admin.v1.CreateBackupScheduleRequest() + ); + const defaultValue1 = + getTypeDefaultValue('.google.firestore.admin.v1.CreateBackupScheduleRequest', ['parent']); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; + const expectedResponse = generateSampleMessage( + new protos.google.firestore.admin.v1.BackupSchedule() + ); + client.innerApiCalls.createBackupSchedule = stubSimpleCall(expectedResponse); + const [response] = await client.createBackupSchedule(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = (client.innerApiCalls.createBackupSchedule as SinonStub) + .getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = (client.innerApiCalls.createBackupSchedule as SinonStub) + .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes bulkDeleteDocuments with LRO error', async () => { - const client = new firestoreadminModule.FirestoreAdminClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.initialize(); - const request = generateSampleMessage( - new protos.google.firestore.admin.v1.BulkDeleteDocumentsRequest() - ); - const defaultValue1 = getTypeDefaultValue( - '.google.firestore.admin.v1.BulkDeleteDocumentsRequest', - ['name'] - ); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; - const expectedError = new Error('expected'); - client.innerApiCalls.bulkDeleteDocuments = stubLongRunningCall( - undefined, - undefined, - expectedError - ); - const [operation] = await client.bulkDeleteDocuments(request); - await assert.rejects(operation.promise(), expectedError); - const actualRequest = ( - client.innerApiCalls.bulkDeleteDocuments as SinonStub - ).getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = ( - client.innerApiCalls.bulkDeleteDocuments as SinonStub - ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes createBackupSchedule without error using callback', async () => { + const client = new firestoreadminModule.FirestoreAdminClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.firestore.admin.v1.CreateBackupScheduleRequest() + ); + const defaultValue1 = + getTypeDefaultValue('.google.firestore.admin.v1.CreateBackupScheduleRequest', ['parent']); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; + const expectedResponse = generateSampleMessage( + new protos.google.firestore.admin.v1.BackupSchedule() + ); + client.innerApiCalls.createBackupSchedule = stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.createBackupSchedule( + request, + (err?: Error|null, result?: protos.google.firestore.admin.v1.IBackupSchedule|null) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = (client.innerApiCalls.createBackupSchedule as SinonStub) + .getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = (client.innerApiCalls.createBackupSchedule as SinonStub) + .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes checkBulkDeleteDocumentsProgress without error', async () => { - const client = new firestoreadminModule.FirestoreAdminClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.initialize(); - const expectedResponse = generateSampleMessage( - new operationsProtos.google.longrunning.Operation() - ); - expectedResponse.name = 'test'; - expectedResponse.response = {type_url: 'url', value: Buffer.from('')}; - expectedResponse.metadata = {type_url: 'url', value: Buffer.from('')}; - - client.operationsClient.getOperation = stubSimpleCall(expectedResponse); - const decodedOperation = await client.checkBulkDeleteDocumentsProgress( - expectedResponse.name - ); - assert.deepStrictEqual(decodedOperation.name, expectedResponse.name); - assert(decodedOperation.metadata); - assert((client.operationsClient.getOperation as SinonStub).getCall(0)); - }); + it('invokes createBackupSchedule with error', async () => { + const client = new firestoreadminModule.FirestoreAdminClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.firestore.admin.v1.CreateBackupScheduleRequest() + ); + const defaultValue1 = + getTypeDefaultValue('.google.firestore.admin.v1.CreateBackupScheduleRequest', ['parent']); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; + const expectedError = new Error('expected'); + client.innerApiCalls.createBackupSchedule = stubSimpleCall(undefined, expectedError); + await assert.rejects(client.createBackupSchedule(request), expectedError); + const actualRequest = (client.innerApiCalls.createBackupSchedule as SinonStub) + .getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = (client.innerApiCalls.createBackupSchedule as SinonStub) + .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes checkBulkDeleteDocumentsProgress with error', async () => { - const client = new firestoreadminModule.FirestoreAdminClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.initialize(); - const expectedError = new Error('expected'); - - client.operationsClient.getOperation = stubSimpleCall( - undefined, - expectedError - ); - await assert.rejects( - client.checkBulkDeleteDocumentsProgress(''), - expectedError - ); - assert((client.operationsClient.getOperation as SinonStub).getCall(0)); - }); - }); - - describe('createDatabase', () => { - it('invokes createDatabase without error', async () => { - const client = new firestoreadminModule.FirestoreAdminClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.initialize(); - const request = generateSampleMessage( - new protos.google.firestore.admin.v1.CreateDatabaseRequest() - ); - const defaultValue1 = getTypeDefaultValue( - '.google.firestore.admin.v1.CreateDatabaseRequest', - ['parent'] - ); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; - const expectedResponse = generateSampleMessage( - new protos.google.longrunning.Operation() - ); - client.innerApiCalls.createDatabase = - stubLongRunningCall(expectedResponse); - const [operation] = await client.createDatabase(request); - const [response] = await operation.promise(); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = ( - client.innerApiCalls.createDatabase as SinonStub - ).getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = ( - client.innerApiCalls.createDatabase as SinonStub - ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + it('invokes createBackupSchedule with closed client', async () => { + const client = new firestoreadminModule.FirestoreAdminClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.firestore.admin.v1.CreateBackupScheduleRequest() + ); + const defaultValue1 = + getTypeDefaultValue('.google.firestore.admin.v1.CreateBackupScheduleRequest', ['parent']); + request.parent = defaultValue1; + const expectedError = new Error('The client has already been closed.'); + client.close().catch(err => {throw err}); + await assert.rejects(client.createBackupSchedule(request), expectedError); + }); }); - it('invokes createDatabase without error using callback', async () => { - const client = new firestoreadminModule.FirestoreAdminClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.initialize(); - const request = generateSampleMessage( - new protos.google.firestore.admin.v1.CreateDatabaseRequest() - ); - const defaultValue1 = getTypeDefaultValue( - '.google.firestore.admin.v1.CreateDatabaseRequest', - ['parent'] - ); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; - const expectedResponse = generateSampleMessage( - new protos.google.longrunning.Operation() - ); - client.innerApiCalls.createDatabase = - stubLongRunningCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.createDatabase( - request, - ( - err?: Error | null, - result?: LROperation< - protos.google.firestore.admin.v1.IDatabase, - protos.google.firestore.admin.v1.ICreateDatabaseMetadata - > | null - ) => { - if (err) { - reject(err); - } else { - resolve(result); - } - } - ); - }); - const operation = (await promise) as LROperation< - protos.google.firestore.admin.v1.IDatabase, - protos.google.firestore.admin.v1.ICreateDatabaseMetadata - >; - const [response] = await operation.promise(); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = ( - client.innerApiCalls.createDatabase as SinonStub - ).getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = ( - client.innerApiCalls.createDatabase as SinonStub - ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + describe('getBackupSchedule', () => { + it('invokes getBackupSchedule without error', async () => { + const client = new firestoreadminModule.FirestoreAdminClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.firestore.admin.v1.GetBackupScheduleRequest() + ); + const defaultValue1 = + getTypeDefaultValue('.google.firestore.admin.v1.GetBackupScheduleRequest', ['name']); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; + const expectedResponse = generateSampleMessage( + new protos.google.firestore.admin.v1.BackupSchedule() + ); + client.innerApiCalls.getBackupSchedule = stubSimpleCall(expectedResponse); + const [response] = await client.getBackupSchedule(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = (client.innerApiCalls.getBackupSchedule as SinonStub) + .getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = (client.innerApiCalls.getBackupSchedule as SinonStub) + .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes createDatabase with call error', async () => { - const client = new firestoreadminModule.FirestoreAdminClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.initialize(); - const request = generateSampleMessage( - new protos.google.firestore.admin.v1.CreateDatabaseRequest() - ); - const defaultValue1 = getTypeDefaultValue( - '.google.firestore.admin.v1.CreateDatabaseRequest', - ['parent'] - ); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; - const expectedError = new Error('expected'); - client.innerApiCalls.createDatabase = stubLongRunningCall( - undefined, - expectedError - ); - await assert.rejects(client.createDatabase(request), expectedError); - const actualRequest = ( - client.innerApiCalls.createDatabase as SinonStub - ).getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = ( - client.innerApiCalls.createDatabase as SinonStub - ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes getBackupSchedule without error using callback', async () => { + const client = new firestoreadminModule.FirestoreAdminClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.firestore.admin.v1.GetBackupScheduleRequest() + ); + const defaultValue1 = + getTypeDefaultValue('.google.firestore.admin.v1.GetBackupScheduleRequest', ['name']); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; + const expectedResponse = generateSampleMessage( + new protos.google.firestore.admin.v1.BackupSchedule() + ); + client.innerApiCalls.getBackupSchedule = stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.getBackupSchedule( + request, + (err?: Error|null, result?: protos.google.firestore.admin.v1.IBackupSchedule|null) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = (client.innerApiCalls.getBackupSchedule as SinonStub) + .getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = (client.innerApiCalls.getBackupSchedule as SinonStub) + .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes createDatabase with LRO error', async () => { - const client = new firestoreadminModule.FirestoreAdminClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.initialize(); - const request = generateSampleMessage( - new protos.google.firestore.admin.v1.CreateDatabaseRequest() - ); - const defaultValue1 = getTypeDefaultValue( - '.google.firestore.admin.v1.CreateDatabaseRequest', - ['parent'] - ); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; - const expectedError = new Error('expected'); - client.innerApiCalls.createDatabase = stubLongRunningCall( - undefined, - undefined, - expectedError - ); - const [operation] = await client.createDatabase(request); - await assert.rejects(operation.promise(), expectedError); - const actualRequest = ( - client.innerApiCalls.createDatabase as SinonStub - ).getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = ( - client.innerApiCalls.createDatabase as SinonStub - ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes getBackupSchedule with error', async () => { + const client = new firestoreadminModule.FirestoreAdminClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.firestore.admin.v1.GetBackupScheduleRequest() + ); + const defaultValue1 = + getTypeDefaultValue('.google.firestore.admin.v1.GetBackupScheduleRequest', ['name']); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; + const expectedError = new Error('expected'); + client.innerApiCalls.getBackupSchedule = stubSimpleCall(undefined, expectedError); + await assert.rejects(client.getBackupSchedule(request), expectedError); + const actualRequest = (client.innerApiCalls.getBackupSchedule as SinonStub) + .getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = (client.innerApiCalls.getBackupSchedule as SinonStub) + .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes checkCreateDatabaseProgress without error', async () => { - const client = new firestoreadminModule.FirestoreAdminClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.initialize(); - const expectedResponse = generateSampleMessage( - new operationsProtos.google.longrunning.Operation() - ); - expectedResponse.name = 'test'; - expectedResponse.response = {type_url: 'url', value: Buffer.from('')}; - expectedResponse.metadata = {type_url: 'url', value: Buffer.from('')}; - - client.operationsClient.getOperation = stubSimpleCall(expectedResponse); - const decodedOperation = await client.checkCreateDatabaseProgress( - expectedResponse.name - ); - assert.deepStrictEqual(decodedOperation.name, expectedResponse.name); - assert(decodedOperation.metadata); - assert((client.operationsClient.getOperation as SinonStub).getCall(0)); + it('invokes getBackupSchedule with closed client', async () => { + const client = new firestoreadminModule.FirestoreAdminClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.firestore.admin.v1.GetBackupScheduleRequest() + ); + const defaultValue1 = + getTypeDefaultValue('.google.firestore.admin.v1.GetBackupScheduleRequest', ['name']); + request.name = defaultValue1; + const expectedError = new Error('The client has already been closed.'); + client.close().catch(err => {throw err}); + await assert.rejects(client.getBackupSchedule(request), expectedError); + }); }); - it('invokes checkCreateDatabaseProgress with error', async () => { - const client = new firestoreadminModule.FirestoreAdminClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.initialize(); - const expectedError = new Error('expected'); - - client.operationsClient.getOperation = stubSimpleCall( - undefined, - expectedError - ); - await assert.rejects( - client.checkCreateDatabaseProgress(''), - expectedError - ); - assert((client.operationsClient.getOperation as SinonStub).getCall(0)); - }); - }); - - describe('updateDatabase', () => { - it('invokes updateDatabase without error', async () => { - const client = new firestoreadminModule.FirestoreAdminClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.initialize(); - const request = generateSampleMessage( - new protos.google.firestore.admin.v1.UpdateDatabaseRequest() - ); - request.database ??= {}; - const defaultValue1 = getTypeDefaultValue( - '.google.firestore.admin.v1.UpdateDatabaseRequest', - ['database', 'name'] - ); - request.database.name = defaultValue1; - const expectedHeaderRequestParams = `database.name=${defaultValue1 ?? ''}`; - const expectedResponse = generateSampleMessage( - new protos.google.longrunning.Operation() - ); - client.innerApiCalls.updateDatabase = - stubLongRunningCall(expectedResponse); - const [operation] = await client.updateDatabase(request); - const [response] = await operation.promise(); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = ( - client.innerApiCalls.updateDatabase as SinonStub - ).getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = ( - client.innerApiCalls.updateDatabase as SinonStub - ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + describe('listBackupSchedules', () => { + it('invokes listBackupSchedules without error', async () => { + const client = new firestoreadminModule.FirestoreAdminClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.firestore.admin.v1.ListBackupSchedulesRequest() + ); + const defaultValue1 = + getTypeDefaultValue('.google.firestore.admin.v1.ListBackupSchedulesRequest', ['parent']); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; + const expectedResponse = generateSampleMessage( + new protos.google.firestore.admin.v1.ListBackupSchedulesResponse() + ); + client.innerApiCalls.listBackupSchedules = stubSimpleCall(expectedResponse); + const [response] = await client.listBackupSchedules(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = (client.innerApiCalls.listBackupSchedules as SinonStub) + .getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = (client.innerApiCalls.listBackupSchedules as SinonStub) + .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes updateDatabase without error using callback', async () => { - const client = new firestoreadminModule.FirestoreAdminClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.initialize(); - const request = generateSampleMessage( - new protos.google.firestore.admin.v1.UpdateDatabaseRequest() - ); - request.database ??= {}; - const defaultValue1 = getTypeDefaultValue( - '.google.firestore.admin.v1.UpdateDatabaseRequest', - ['database', 'name'] - ); - request.database.name = defaultValue1; - const expectedHeaderRequestParams = `database.name=${defaultValue1 ?? ''}`; - const expectedResponse = generateSampleMessage( - new protos.google.longrunning.Operation() - ); - client.innerApiCalls.updateDatabase = - stubLongRunningCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.updateDatabase( - request, - ( - err?: Error | null, - result?: LROperation< - protos.google.firestore.admin.v1.IDatabase, - protos.google.firestore.admin.v1.IUpdateDatabaseMetadata - > | null - ) => { - if (err) { - reject(err); - } else { - resolve(result); - } - } - ); - }); - const operation = (await promise) as LROperation< - protos.google.firestore.admin.v1.IDatabase, - protos.google.firestore.admin.v1.IUpdateDatabaseMetadata - >; - const [response] = await operation.promise(); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = ( - client.innerApiCalls.updateDatabase as SinonStub - ).getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = ( - client.innerApiCalls.updateDatabase as SinonStub - ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes listBackupSchedules without error using callback', async () => { + const client = new firestoreadminModule.FirestoreAdminClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.firestore.admin.v1.ListBackupSchedulesRequest() + ); + const defaultValue1 = + getTypeDefaultValue('.google.firestore.admin.v1.ListBackupSchedulesRequest', ['parent']); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; + const expectedResponse = generateSampleMessage( + new protos.google.firestore.admin.v1.ListBackupSchedulesResponse() + ); + client.innerApiCalls.listBackupSchedules = stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.listBackupSchedules( + request, + (err?: Error|null, result?: protos.google.firestore.admin.v1.IListBackupSchedulesResponse|null) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = (client.innerApiCalls.listBackupSchedules as SinonStub) + .getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = (client.innerApiCalls.listBackupSchedules as SinonStub) + .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes updateDatabase with call error', async () => { - const client = new firestoreadminModule.FirestoreAdminClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.initialize(); - const request = generateSampleMessage( - new protos.google.firestore.admin.v1.UpdateDatabaseRequest() - ); - request.database ??= {}; - const defaultValue1 = getTypeDefaultValue( - '.google.firestore.admin.v1.UpdateDatabaseRequest', - ['database', 'name'] - ); - request.database.name = defaultValue1; - const expectedHeaderRequestParams = `database.name=${defaultValue1 ?? ''}`; - const expectedError = new Error('expected'); - client.innerApiCalls.updateDatabase = stubLongRunningCall( - undefined, - expectedError - ); - await assert.rejects(client.updateDatabase(request), expectedError); - const actualRequest = ( - client.innerApiCalls.updateDatabase as SinonStub - ).getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = ( - client.innerApiCalls.updateDatabase as SinonStub - ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes listBackupSchedules with error', async () => { + const client = new firestoreadminModule.FirestoreAdminClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.firestore.admin.v1.ListBackupSchedulesRequest() + ); + const defaultValue1 = + getTypeDefaultValue('.google.firestore.admin.v1.ListBackupSchedulesRequest', ['parent']); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; + const expectedError = new Error('expected'); + client.innerApiCalls.listBackupSchedules = stubSimpleCall(undefined, expectedError); + await assert.rejects(client.listBackupSchedules(request), expectedError); + const actualRequest = (client.innerApiCalls.listBackupSchedules as SinonStub) + .getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = (client.innerApiCalls.listBackupSchedules as SinonStub) + .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes updateDatabase with LRO error', async () => { - const client = new firestoreadminModule.FirestoreAdminClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.initialize(); - const request = generateSampleMessage( - new protos.google.firestore.admin.v1.UpdateDatabaseRequest() - ); - request.database ??= {}; - const defaultValue1 = getTypeDefaultValue( - '.google.firestore.admin.v1.UpdateDatabaseRequest', - ['database', 'name'] - ); - request.database.name = defaultValue1; - const expectedHeaderRequestParams = `database.name=${defaultValue1 ?? ''}`; - const expectedError = new Error('expected'); - client.innerApiCalls.updateDatabase = stubLongRunningCall( - undefined, - undefined, - expectedError - ); - const [operation] = await client.updateDatabase(request); - await assert.rejects(operation.promise(), expectedError); - const actualRequest = ( - client.innerApiCalls.updateDatabase as SinonStub - ).getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = ( - client.innerApiCalls.updateDatabase as SinonStub - ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + it('invokes listBackupSchedules with closed client', async () => { + const client = new firestoreadminModule.FirestoreAdminClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.firestore.admin.v1.ListBackupSchedulesRequest() + ); + const defaultValue1 = + getTypeDefaultValue('.google.firestore.admin.v1.ListBackupSchedulesRequest', ['parent']); + request.parent = defaultValue1; + const expectedError = new Error('The client has already been closed.'); + client.close().catch(err => {throw err}); + await assert.rejects(client.listBackupSchedules(request), expectedError); + }); }); - it('invokes checkUpdateDatabaseProgress without error', async () => { - const client = new firestoreadminModule.FirestoreAdminClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.initialize(); - const expectedResponse = generateSampleMessage( - new operationsProtos.google.longrunning.Operation() - ); - expectedResponse.name = 'test'; - expectedResponse.response = {type_url: 'url', value: Buffer.from('')}; - expectedResponse.metadata = {type_url: 'url', value: Buffer.from('')}; - - client.operationsClient.getOperation = stubSimpleCall(expectedResponse); - const decodedOperation = await client.checkUpdateDatabaseProgress( - expectedResponse.name - ); - assert.deepStrictEqual(decodedOperation.name, expectedResponse.name); - assert(decodedOperation.metadata); - assert((client.operationsClient.getOperation as SinonStub).getCall(0)); - }); + describe('updateBackupSchedule', () => { + it('invokes updateBackupSchedule without error', async () => { + const client = new firestoreadminModule.FirestoreAdminClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.firestore.admin.v1.UpdateBackupScheduleRequest() + ); + request.backupSchedule ??= {}; + const defaultValue1 = + getTypeDefaultValue('.google.firestore.admin.v1.UpdateBackupScheduleRequest', ['backupSchedule', 'name']); + request.backupSchedule.name = defaultValue1; + const expectedHeaderRequestParams = `backup_schedule.name=${defaultValue1 ?? '' }`; + const expectedResponse = generateSampleMessage( + new protos.google.firestore.admin.v1.BackupSchedule() + ); + client.innerApiCalls.updateBackupSchedule = stubSimpleCall(expectedResponse); + const [response] = await client.updateBackupSchedule(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = (client.innerApiCalls.updateBackupSchedule as SinonStub) + .getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = (client.innerApiCalls.updateBackupSchedule as SinonStub) + .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes checkUpdateDatabaseProgress with error', async () => { - const client = new firestoreadminModule.FirestoreAdminClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.initialize(); - const expectedError = new Error('expected'); - - client.operationsClient.getOperation = stubSimpleCall( - undefined, - expectedError - ); - await assert.rejects( - client.checkUpdateDatabaseProgress(''), - expectedError - ); - assert((client.operationsClient.getOperation as SinonStub).getCall(0)); - }); - }); - - describe('deleteDatabase', () => { - it('invokes deleteDatabase without error', async () => { - const client = new firestoreadminModule.FirestoreAdminClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.initialize(); - const request = generateSampleMessage( - new protos.google.firestore.admin.v1.DeleteDatabaseRequest() - ); - const defaultValue1 = getTypeDefaultValue( - '.google.firestore.admin.v1.DeleteDatabaseRequest', - ['name'] - ); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; - const expectedResponse = generateSampleMessage( - new protos.google.longrunning.Operation() - ); - client.innerApiCalls.deleteDatabase = - stubLongRunningCall(expectedResponse); - const [operation] = await client.deleteDatabase(request); - const [response] = await operation.promise(); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = ( - client.innerApiCalls.deleteDatabase as SinonStub - ).getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = ( - client.innerApiCalls.deleteDatabase as SinonStub - ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes updateBackupSchedule without error using callback', async () => { + const client = new firestoreadminModule.FirestoreAdminClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.firestore.admin.v1.UpdateBackupScheduleRequest() + ); + request.backupSchedule ??= {}; + const defaultValue1 = + getTypeDefaultValue('.google.firestore.admin.v1.UpdateBackupScheduleRequest', ['backupSchedule', 'name']); + request.backupSchedule.name = defaultValue1; + const expectedHeaderRequestParams = `backup_schedule.name=${defaultValue1 ?? '' }`; + const expectedResponse = generateSampleMessage( + new protos.google.firestore.admin.v1.BackupSchedule() + ); + client.innerApiCalls.updateBackupSchedule = stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.updateBackupSchedule( + request, + (err?: Error|null, result?: protos.google.firestore.admin.v1.IBackupSchedule|null) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = (client.innerApiCalls.updateBackupSchedule as SinonStub) + .getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = (client.innerApiCalls.updateBackupSchedule as SinonStub) + .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes deleteDatabase without error using callback', async () => { - const client = new firestoreadminModule.FirestoreAdminClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.initialize(); - const request = generateSampleMessage( - new protos.google.firestore.admin.v1.DeleteDatabaseRequest() - ); - const defaultValue1 = getTypeDefaultValue( - '.google.firestore.admin.v1.DeleteDatabaseRequest', - ['name'] - ); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; - const expectedResponse = generateSampleMessage( - new protos.google.longrunning.Operation() - ); - client.innerApiCalls.deleteDatabase = - stubLongRunningCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.deleteDatabase( - request, - ( - err?: Error | null, - result?: LROperation< - protos.google.firestore.admin.v1.IDatabase, - protos.google.firestore.admin.v1.IDeleteDatabaseMetadata - > | null - ) => { - if (err) { - reject(err); - } else { - resolve(result); - } - } - ); - }); - const operation = (await promise) as LROperation< - protos.google.firestore.admin.v1.IDatabase, - protos.google.firestore.admin.v1.IDeleteDatabaseMetadata - >; - const [response] = await operation.promise(); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = ( - client.innerApiCalls.deleteDatabase as SinonStub - ).getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = ( - client.innerApiCalls.deleteDatabase as SinonStub - ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes updateBackupSchedule with error', async () => { + const client = new firestoreadminModule.FirestoreAdminClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.firestore.admin.v1.UpdateBackupScheduleRequest() + ); + request.backupSchedule ??= {}; + const defaultValue1 = + getTypeDefaultValue('.google.firestore.admin.v1.UpdateBackupScheduleRequest', ['backupSchedule', 'name']); + request.backupSchedule.name = defaultValue1; + const expectedHeaderRequestParams = `backup_schedule.name=${defaultValue1 ?? '' }`; + const expectedError = new Error('expected'); + client.innerApiCalls.updateBackupSchedule = stubSimpleCall(undefined, expectedError); + await assert.rejects(client.updateBackupSchedule(request), expectedError); + const actualRequest = (client.innerApiCalls.updateBackupSchedule as SinonStub) + .getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = (client.innerApiCalls.updateBackupSchedule as SinonStub) + .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes deleteDatabase with call error', async () => { - const client = new firestoreadminModule.FirestoreAdminClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.initialize(); - const request = generateSampleMessage( - new protos.google.firestore.admin.v1.DeleteDatabaseRequest() - ); - const defaultValue1 = getTypeDefaultValue( - '.google.firestore.admin.v1.DeleteDatabaseRequest', - ['name'] - ); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; - const expectedError = new Error('expected'); - client.innerApiCalls.deleteDatabase = stubLongRunningCall( - undefined, - expectedError - ); - await assert.rejects(client.deleteDatabase(request), expectedError); - const actualRequest = ( - client.innerApiCalls.deleteDatabase as SinonStub - ).getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = ( - client.innerApiCalls.deleteDatabase as SinonStub - ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + it('invokes updateBackupSchedule with closed client', async () => { + const client = new firestoreadminModule.FirestoreAdminClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.firestore.admin.v1.UpdateBackupScheduleRequest() + ); + request.backupSchedule ??= {}; + const defaultValue1 = + getTypeDefaultValue('.google.firestore.admin.v1.UpdateBackupScheduleRequest', ['backupSchedule', 'name']); + request.backupSchedule.name = defaultValue1; + const expectedError = new Error('The client has already been closed.'); + client.close().catch(err => {throw err}); + await assert.rejects(client.updateBackupSchedule(request), expectedError); + }); }); - it('invokes deleteDatabase with LRO error', async () => { - const client = new firestoreadminModule.FirestoreAdminClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.initialize(); - const request = generateSampleMessage( - new protos.google.firestore.admin.v1.DeleteDatabaseRequest() - ); - const defaultValue1 = getTypeDefaultValue( - '.google.firestore.admin.v1.DeleteDatabaseRequest', - ['name'] - ); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; - const expectedError = new Error('expected'); - client.innerApiCalls.deleteDatabase = stubLongRunningCall( - undefined, - undefined, - expectedError - ); - const [operation] = await client.deleteDatabase(request); - await assert.rejects(operation.promise(), expectedError); - const actualRequest = ( - client.innerApiCalls.deleteDatabase as SinonStub - ).getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = ( - client.innerApiCalls.deleteDatabase as SinonStub - ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + describe('deleteBackupSchedule', () => { + it('invokes deleteBackupSchedule without error', async () => { + const client = new firestoreadminModule.FirestoreAdminClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.firestore.admin.v1.DeleteBackupScheduleRequest() + ); + const defaultValue1 = + getTypeDefaultValue('.google.firestore.admin.v1.DeleteBackupScheduleRequest', ['name']); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; + const expectedResponse = generateSampleMessage( + new protos.google.protobuf.Empty() + ); + client.innerApiCalls.deleteBackupSchedule = stubSimpleCall(expectedResponse); + const [response] = await client.deleteBackupSchedule(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = (client.innerApiCalls.deleteBackupSchedule as SinonStub) + .getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = (client.innerApiCalls.deleteBackupSchedule as SinonStub) + .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes checkDeleteDatabaseProgress without error', async () => { - const client = new firestoreadminModule.FirestoreAdminClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.initialize(); - const expectedResponse = generateSampleMessage( - new operationsProtos.google.longrunning.Operation() - ); - expectedResponse.name = 'test'; - expectedResponse.response = {type_url: 'url', value: Buffer.from('')}; - expectedResponse.metadata = {type_url: 'url', value: Buffer.from('')}; - - client.operationsClient.getOperation = stubSimpleCall(expectedResponse); - const decodedOperation = await client.checkDeleteDatabaseProgress( - expectedResponse.name - ); - assert.deepStrictEqual(decodedOperation.name, expectedResponse.name); - assert(decodedOperation.metadata); - assert((client.operationsClient.getOperation as SinonStub).getCall(0)); - }); + it('invokes deleteBackupSchedule without error using callback', async () => { + const client = new firestoreadminModule.FirestoreAdminClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.firestore.admin.v1.DeleteBackupScheduleRequest() + ); + const defaultValue1 = + getTypeDefaultValue('.google.firestore.admin.v1.DeleteBackupScheduleRequest', ['name']); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; + const expectedResponse = generateSampleMessage( + new protos.google.protobuf.Empty() + ); + client.innerApiCalls.deleteBackupSchedule = stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.deleteBackupSchedule( + request, + (err?: Error|null, result?: protos.google.protobuf.IEmpty|null) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = (client.innerApiCalls.deleteBackupSchedule as SinonStub) + .getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = (client.innerApiCalls.deleteBackupSchedule as SinonStub) + .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes checkDeleteDatabaseProgress with error', async () => { - const client = new firestoreadminModule.FirestoreAdminClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.initialize(); - const expectedError = new Error('expected'); - - client.operationsClient.getOperation = stubSimpleCall( - undefined, - expectedError - ); - await assert.rejects( - client.checkDeleteDatabaseProgress(''), - expectedError - ); - assert((client.operationsClient.getOperation as SinonStub).getCall(0)); - }); - }); - - describe('restoreDatabase', () => { - it('invokes restoreDatabase without error', async () => { - const client = new firestoreadminModule.FirestoreAdminClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.initialize(); - const request = generateSampleMessage( - new protos.google.firestore.admin.v1.RestoreDatabaseRequest() - ); - const defaultValue1 = getTypeDefaultValue( - '.google.firestore.admin.v1.RestoreDatabaseRequest', - ['parent'] - ); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; - const expectedResponse = generateSampleMessage( - new protos.google.longrunning.Operation() - ); - client.innerApiCalls.restoreDatabase = - stubLongRunningCall(expectedResponse); - const [operation] = await client.restoreDatabase(request); - const [response] = await operation.promise(); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = ( - client.innerApiCalls.restoreDatabase as SinonStub - ).getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = ( - client.innerApiCalls.restoreDatabase as SinonStub - ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes deleteBackupSchedule with error', async () => { + const client = new firestoreadminModule.FirestoreAdminClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.firestore.admin.v1.DeleteBackupScheduleRequest() + ); + const defaultValue1 = + getTypeDefaultValue('.google.firestore.admin.v1.DeleteBackupScheduleRequest', ['name']); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; + const expectedError = new Error('expected'); + client.innerApiCalls.deleteBackupSchedule = stubSimpleCall(undefined, expectedError); + await assert.rejects(client.deleteBackupSchedule(request), expectedError); + const actualRequest = (client.innerApiCalls.deleteBackupSchedule as SinonStub) + .getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = (client.innerApiCalls.deleteBackupSchedule as SinonStub) + .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes restoreDatabase without error using callback', async () => { - const client = new firestoreadminModule.FirestoreAdminClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.initialize(); - const request = generateSampleMessage( - new protos.google.firestore.admin.v1.RestoreDatabaseRequest() - ); - const defaultValue1 = getTypeDefaultValue( - '.google.firestore.admin.v1.RestoreDatabaseRequest', - ['parent'] - ); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; - const expectedResponse = generateSampleMessage( - new protos.google.longrunning.Operation() - ); - client.innerApiCalls.restoreDatabase = - stubLongRunningCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.restoreDatabase( - request, - ( - err?: Error | null, - result?: LROperation< - protos.google.firestore.admin.v1.IDatabase, - protos.google.firestore.admin.v1.IRestoreDatabaseMetadata - > | null - ) => { - if (err) { - reject(err); - } else { - resolve(result); - } - } - ); - }); - const operation = (await promise) as LROperation< - protos.google.firestore.admin.v1.IDatabase, - protos.google.firestore.admin.v1.IRestoreDatabaseMetadata - >; - const [response] = await operation.promise(); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = ( - client.innerApiCalls.restoreDatabase as SinonStub - ).getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = ( - client.innerApiCalls.restoreDatabase as SinonStub - ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + it('invokes deleteBackupSchedule with closed client', async () => { + const client = new firestoreadminModule.FirestoreAdminClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.firestore.admin.v1.DeleteBackupScheduleRequest() + ); + const defaultValue1 = + getTypeDefaultValue('.google.firestore.admin.v1.DeleteBackupScheduleRequest', ['name']); + request.name = defaultValue1; + const expectedError = new Error('The client has already been closed.'); + client.close().catch(err => {throw err}); + await assert.rejects(client.deleteBackupSchedule(request), expectedError); + }); }); - it('invokes restoreDatabase with call error', async () => { - const client = new firestoreadminModule.FirestoreAdminClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.initialize(); - const request = generateSampleMessage( - new protos.google.firestore.admin.v1.RestoreDatabaseRequest() - ); - const defaultValue1 = getTypeDefaultValue( - '.google.firestore.admin.v1.RestoreDatabaseRequest', - ['parent'] - ); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; - const expectedError = new Error('expected'); - client.innerApiCalls.restoreDatabase = stubLongRunningCall( - undefined, - expectedError - ); - await assert.rejects(client.restoreDatabase(request), expectedError); - const actualRequest = ( - client.innerApiCalls.restoreDatabase as SinonStub - ).getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = ( - client.innerApiCalls.restoreDatabase as SinonStub - ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + describe('createIndex', () => { + it('invokes createIndex without error', async () => { + const client = new firestoreadminModule.FirestoreAdminClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.firestore.admin.v1.CreateIndexRequest() + ); + const defaultValue1 = + getTypeDefaultValue('.google.firestore.admin.v1.CreateIndexRequest', ['parent']); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; + const expectedResponse = generateSampleMessage( + new protos.google.longrunning.Operation() + ); + client.innerApiCalls.createIndex = stubLongRunningCall(expectedResponse); + const [operation] = await client.createIndex(request); + const [response] = await operation.promise(); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = (client.innerApiCalls.createIndex as SinonStub) + .getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = (client.innerApiCalls.createIndex as SinonStub) + .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes restoreDatabase with LRO error', async () => { - const client = new firestoreadminModule.FirestoreAdminClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.initialize(); - const request = generateSampleMessage( - new protos.google.firestore.admin.v1.RestoreDatabaseRequest() - ); - const defaultValue1 = getTypeDefaultValue( - '.google.firestore.admin.v1.RestoreDatabaseRequest', - ['parent'] - ); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; - const expectedError = new Error('expected'); - client.innerApiCalls.restoreDatabase = stubLongRunningCall( - undefined, - undefined, - expectedError - ); - const [operation] = await client.restoreDatabase(request); - await assert.rejects(operation.promise(), expectedError); - const actualRequest = ( - client.innerApiCalls.restoreDatabase as SinonStub - ).getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = ( - client.innerApiCalls.restoreDatabase as SinonStub - ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes createIndex without error using callback', async () => { + const client = new firestoreadminModule.FirestoreAdminClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.firestore.admin.v1.CreateIndexRequest() + ); + const defaultValue1 = + getTypeDefaultValue('.google.firestore.admin.v1.CreateIndexRequest', ['parent']); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; + const expectedResponse = generateSampleMessage( + new protos.google.longrunning.Operation() + ); + client.innerApiCalls.createIndex = stubLongRunningCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.createIndex( + request, + (err?: Error|null, + result?: LROperation|null + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }); + }); + const operation = await promise as LROperation; + const [response] = await operation.promise(); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = (client.innerApiCalls.createIndex as SinonStub) + .getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = (client.innerApiCalls.createIndex as SinonStub) + .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes checkRestoreDatabaseProgress without error', async () => { - const client = new firestoreadminModule.FirestoreAdminClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.initialize(); - const expectedResponse = generateSampleMessage( - new operationsProtos.google.longrunning.Operation() - ); - expectedResponse.name = 'test'; - expectedResponse.response = {type_url: 'url', value: Buffer.from('')}; - expectedResponse.metadata = {type_url: 'url', value: Buffer.from('')}; - - client.operationsClient.getOperation = stubSimpleCall(expectedResponse); - const decodedOperation = await client.checkRestoreDatabaseProgress( - expectedResponse.name - ); - assert.deepStrictEqual(decodedOperation.name, expectedResponse.name); - assert(decodedOperation.metadata); - assert((client.operationsClient.getOperation as SinonStub).getCall(0)); - }); + it('invokes createIndex with call error', async () => { + const client = new firestoreadminModule.FirestoreAdminClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.firestore.admin.v1.CreateIndexRequest() + ); + const defaultValue1 = + getTypeDefaultValue('.google.firestore.admin.v1.CreateIndexRequest', ['parent']); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; + const expectedError = new Error('expected'); + client.innerApiCalls.createIndex = stubLongRunningCall(undefined, expectedError); + await assert.rejects(client.createIndex(request), expectedError); + const actualRequest = (client.innerApiCalls.createIndex as SinonStub) + .getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = (client.innerApiCalls.createIndex as SinonStub) + .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes createIndex with LRO error', async () => { + const client = new firestoreadminModule.FirestoreAdminClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.firestore.admin.v1.CreateIndexRequest() + ); + const defaultValue1 = + getTypeDefaultValue('.google.firestore.admin.v1.CreateIndexRequest', ['parent']); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; + const expectedError = new Error('expected'); + client.innerApiCalls.createIndex = stubLongRunningCall(undefined, undefined, expectedError); + const [operation] = await client.createIndex(request); + await assert.rejects(operation.promise(), expectedError); + const actualRequest = (client.innerApiCalls.createIndex as SinonStub) + .getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = (client.innerApiCalls.createIndex as SinonStub) + .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes checkRestoreDatabaseProgress with error', async () => { - const client = new firestoreadminModule.FirestoreAdminClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.initialize(); - const expectedError = new Error('expected'); - - client.operationsClient.getOperation = stubSimpleCall( - undefined, - expectedError - ); - await assert.rejects( - client.checkRestoreDatabaseProgress(''), - expectedError - ); - assert((client.operationsClient.getOperation as SinonStub).getCall(0)); + it('invokes checkCreateIndexProgress without error', async () => { + const client = new firestoreadminModule.FirestoreAdminClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const expectedResponse = generateSampleMessage( + new operationsProtos.google.longrunning.Operation() + ); + expectedResponse.name = 'test'; + expectedResponse.response = {type_url: 'url', value: Buffer.from('')}; + expectedResponse.metadata = {type_url: 'url', value: Buffer.from('')} + + client.operationsClient.getOperation = stubSimpleCall(expectedResponse); + const decodedOperation = await client.checkCreateIndexProgress(expectedResponse.name); + assert.deepStrictEqual(decodedOperation.name, expectedResponse.name); + assert(decodedOperation.metadata); + assert((client.operationsClient.getOperation as SinonStub).getCall(0)); + }); + + it('invokes checkCreateIndexProgress with error', async () => { + const client = new firestoreadminModule.FirestoreAdminClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const expectedError = new Error('expected'); + + client.operationsClient.getOperation = stubSimpleCall(undefined, expectedError); + await assert.rejects(client.checkCreateIndexProgress(''), expectedError); + assert((client.operationsClient.getOperation as SinonStub) + .getCall(0)); + }); }); - }); - - describe('listIndexes', () => { - it('invokes listIndexes without error', async () => { - const client = new firestoreadminModule.FirestoreAdminClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.initialize(); - const request = generateSampleMessage( - new protos.google.firestore.admin.v1.ListIndexesRequest() - ); - const defaultValue1 = getTypeDefaultValue( - '.google.firestore.admin.v1.ListIndexesRequest', - ['parent'] - ); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; - const expectedResponse = [ - generateSampleMessage(new protos.google.firestore.admin.v1.Index()), - generateSampleMessage(new protos.google.firestore.admin.v1.Index()), - generateSampleMessage(new protos.google.firestore.admin.v1.Index()), - ]; - client.innerApiCalls.listIndexes = stubSimpleCall(expectedResponse); - const [response] = await client.listIndexes(request); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = ( - client.innerApiCalls.listIndexes as SinonStub - ).getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = ( - client.innerApiCalls.listIndexes as SinonStub - ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + + describe('updateField', () => { + it('invokes updateField without error', async () => { + const client = new firestoreadminModule.FirestoreAdminClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.firestore.admin.v1.UpdateFieldRequest() + ); + request.field ??= {}; + const defaultValue1 = + getTypeDefaultValue('.google.firestore.admin.v1.UpdateFieldRequest', ['field', 'name']); + request.field.name = defaultValue1; + const expectedHeaderRequestParams = `field.name=${defaultValue1 ?? '' }`; + const expectedResponse = generateSampleMessage( + new protos.google.longrunning.Operation() + ); + client.innerApiCalls.updateField = stubLongRunningCall(expectedResponse); + const [operation] = await client.updateField(request); + const [response] = await operation.promise(); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = (client.innerApiCalls.updateField as SinonStub) + .getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = (client.innerApiCalls.updateField as SinonStub) + .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes updateField without error using callback', async () => { + const client = new firestoreadminModule.FirestoreAdminClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.firestore.admin.v1.UpdateFieldRequest() + ); + request.field ??= {}; + const defaultValue1 = + getTypeDefaultValue('.google.firestore.admin.v1.UpdateFieldRequest', ['field', 'name']); + request.field.name = defaultValue1; + const expectedHeaderRequestParams = `field.name=${defaultValue1 ?? '' }`; + const expectedResponse = generateSampleMessage( + new protos.google.longrunning.Operation() + ); + client.innerApiCalls.updateField = stubLongRunningCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.updateField( + request, + (err?: Error|null, + result?: LROperation|null + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }); + }); + const operation = await promise as LROperation; + const [response] = await operation.promise(); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = (client.innerApiCalls.updateField as SinonStub) + .getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = (client.innerApiCalls.updateField as SinonStub) + .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes updateField with call error', async () => { + const client = new firestoreadminModule.FirestoreAdminClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.firestore.admin.v1.UpdateFieldRequest() + ); + request.field ??= {}; + const defaultValue1 = + getTypeDefaultValue('.google.firestore.admin.v1.UpdateFieldRequest', ['field', 'name']); + request.field.name = defaultValue1; + const expectedHeaderRequestParams = `field.name=${defaultValue1 ?? '' }`; + const expectedError = new Error('expected'); + client.innerApiCalls.updateField = stubLongRunningCall(undefined, expectedError); + await assert.rejects(client.updateField(request), expectedError); + const actualRequest = (client.innerApiCalls.updateField as SinonStub) + .getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = (client.innerApiCalls.updateField as SinonStub) + .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes updateField with LRO error', async () => { + const client = new firestoreadminModule.FirestoreAdminClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.firestore.admin.v1.UpdateFieldRequest() + ); + request.field ??= {}; + const defaultValue1 = + getTypeDefaultValue('.google.firestore.admin.v1.UpdateFieldRequest', ['field', 'name']); + request.field.name = defaultValue1; + const expectedHeaderRequestParams = `field.name=${defaultValue1 ?? '' }`; + const expectedError = new Error('expected'); + client.innerApiCalls.updateField = stubLongRunningCall(undefined, undefined, expectedError); + const [operation] = await client.updateField(request); + await assert.rejects(operation.promise(), expectedError); + const actualRequest = (client.innerApiCalls.updateField as SinonStub) + .getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = (client.innerApiCalls.updateField as SinonStub) + .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes checkUpdateFieldProgress without error', async () => { + const client = new firestoreadminModule.FirestoreAdminClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const expectedResponse = generateSampleMessage( + new operationsProtos.google.longrunning.Operation() + ); + expectedResponse.name = 'test'; + expectedResponse.response = {type_url: 'url', value: Buffer.from('')}; + expectedResponse.metadata = {type_url: 'url', value: Buffer.from('')} + + client.operationsClient.getOperation = stubSimpleCall(expectedResponse); + const decodedOperation = await client.checkUpdateFieldProgress(expectedResponse.name); + assert.deepStrictEqual(decodedOperation.name, expectedResponse.name); + assert(decodedOperation.metadata); + assert((client.operationsClient.getOperation as SinonStub).getCall(0)); + }); + + it('invokes checkUpdateFieldProgress with error', async () => { + const client = new firestoreadminModule.FirestoreAdminClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const expectedError = new Error('expected'); + + client.operationsClient.getOperation = stubSimpleCall(undefined, expectedError); + await assert.rejects(client.checkUpdateFieldProgress(''), expectedError); + assert((client.operationsClient.getOperation as SinonStub) + .getCall(0)); + }); }); - it('invokes listIndexes without error using callback', async () => { - const client = new firestoreadminModule.FirestoreAdminClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.initialize(); - const request = generateSampleMessage( - new protos.google.firestore.admin.v1.ListIndexesRequest() - ); - const defaultValue1 = getTypeDefaultValue( - '.google.firestore.admin.v1.ListIndexesRequest', - ['parent'] - ); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; - const expectedResponse = [ - generateSampleMessage(new protos.google.firestore.admin.v1.Index()), - generateSampleMessage(new protos.google.firestore.admin.v1.Index()), - generateSampleMessage(new protos.google.firestore.admin.v1.Index()), - ]; - client.innerApiCalls.listIndexes = - stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.listIndexes( - request, - ( - err?: Error | null, - result?: protos.google.firestore.admin.v1.IIndex[] | null - ) => { - if (err) { - reject(err); - } else { - resolve(result); - } - } - ); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = ( - client.innerApiCalls.listIndexes as SinonStub - ).getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = ( - client.innerApiCalls.listIndexes as SinonStub - ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + describe('exportDocuments', () => { + it('invokes exportDocuments without error', async () => { + const client = new firestoreadminModule.FirestoreAdminClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.firestore.admin.v1.ExportDocumentsRequest() + ); + const defaultValue1 = + getTypeDefaultValue('.google.firestore.admin.v1.ExportDocumentsRequest', ['name']); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; + const expectedResponse = generateSampleMessage( + new protos.google.longrunning.Operation() + ); + client.innerApiCalls.exportDocuments = stubLongRunningCall(expectedResponse); + const [operation] = await client.exportDocuments(request); + const [response] = await operation.promise(); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = (client.innerApiCalls.exportDocuments as SinonStub) + .getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = (client.innerApiCalls.exportDocuments as SinonStub) + .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes exportDocuments without error using callback', async () => { + const client = new firestoreadminModule.FirestoreAdminClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.firestore.admin.v1.ExportDocumentsRequest() + ); + const defaultValue1 = + getTypeDefaultValue('.google.firestore.admin.v1.ExportDocumentsRequest', ['name']); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; + const expectedResponse = generateSampleMessage( + new protos.google.longrunning.Operation() + ); + client.innerApiCalls.exportDocuments = stubLongRunningCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.exportDocuments( + request, + (err?: Error|null, + result?: LROperation|null + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }); + }); + const operation = await promise as LROperation; + const [response] = await operation.promise(); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = (client.innerApiCalls.exportDocuments as SinonStub) + .getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = (client.innerApiCalls.exportDocuments as SinonStub) + .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes exportDocuments with call error', async () => { + const client = new firestoreadminModule.FirestoreAdminClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.firestore.admin.v1.ExportDocumentsRequest() + ); + const defaultValue1 = + getTypeDefaultValue('.google.firestore.admin.v1.ExportDocumentsRequest', ['name']); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; + const expectedError = new Error('expected'); + client.innerApiCalls.exportDocuments = stubLongRunningCall(undefined, expectedError); + await assert.rejects(client.exportDocuments(request), expectedError); + const actualRequest = (client.innerApiCalls.exportDocuments as SinonStub) + .getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = (client.innerApiCalls.exportDocuments as SinonStub) + .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes exportDocuments with LRO error', async () => { + const client = new firestoreadminModule.FirestoreAdminClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.firestore.admin.v1.ExportDocumentsRequest() + ); + const defaultValue1 = + getTypeDefaultValue('.google.firestore.admin.v1.ExportDocumentsRequest', ['name']); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; + const expectedError = new Error('expected'); + client.innerApiCalls.exportDocuments = stubLongRunningCall(undefined, undefined, expectedError); + const [operation] = await client.exportDocuments(request); + await assert.rejects(operation.promise(), expectedError); + const actualRequest = (client.innerApiCalls.exportDocuments as SinonStub) + .getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = (client.innerApiCalls.exportDocuments as SinonStub) + .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes checkExportDocumentsProgress without error', async () => { + const client = new firestoreadminModule.FirestoreAdminClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const expectedResponse = generateSampleMessage( + new operationsProtos.google.longrunning.Operation() + ); + expectedResponse.name = 'test'; + expectedResponse.response = {type_url: 'url', value: Buffer.from('')}; + expectedResponse.metadata = {type_url: 'url', value: Buffer.from('')} + + client.operationsClient.getOperation = stubSimpleCall(expectedResponse); + const decodedOperation = await client.checkExportDocumentsProgress(expectedResponse.name); + assert.deepStrictEqual(decodedOperation.name, expectedResponse.name); + assert(decodedOperation.metadata); + assert((client.operationsClient.getOperation as SinonStub).getCall(0)); + }); + + it('invokes checkExportDocumentsProgress with error', async () => { + const client = new firestoreadminModule.FirestoreAdminClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const expectedError = new Error('expected'); + + client.operationsClient.getOperation = stubSimpleCall(undefined, expectedError); + await assert.rejects(client.checkExportDocumentsProgress(''), expectedError); + assert((client.operationsClient.getOperation as SinonStub) + .getCall(0)); + }); }); - it('invokes listIndexes with error', async () => { - const client = new firestoreadminModule.FirestoreAdminClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.initialize(); - const request = generateSampleMessage( - new protos.google.firestore.admin.v1.ListIndexesRequest() - ); - const defaultValue1 = getTypeDefaultValue( - '.google.firestore.admin.v1.ListIndexesRequest', - ['parent'] - ); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; - const expectedError = new Error('expected'); - client.innerApiCalls.listIndexes = stubSimpleCall( - undefined, - expectedError - ); - await assert.rejects(client.listIndexes(request), expectedError); - const actualRequest = ( - client.innerApiCalls.listIndexes as SinonStub - ).getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = ( - client.innerApiCalls.listIndexes as SinonStub - ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + describe('importDocuments', () => { + it('invokes importDocuments without error', async () => { + const client = new firestoreadminModule.FirestoreAdminClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.firestore.admin.v1.ImportDocumentsRequest() + ); + const defaultValue1 = + getTypeDefaultValue('.google.firestore.admin.v1.ImportDocumentsRequest', ['name']); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; + const expectedResponse = generateSampleMessage( + new protos.google.longrunning.Operation() + ); + client.innerApiCalls.importDocuments = stubLongRunningCall(expectedResponse); + const [operation] = await client.importDocuments(request); + const [response] = await operation.promise(); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = (client.innerApiCalls.importDocuments as SinonStub) + .getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = (client.innerApiCalls.importDocuments as SinonStub) + .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes importDocuments without error using callback', async () => { + const client = new firestoreadminModule.FirestoreAdminClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.firestore.admin.v1.ImportDocumentsRequest() + ); + const defaultValue1 = + getTypeDefaultValue('.google.firestore.admin.v1.ImportDocumentsRequest', ['name']); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; + const expectedResponse = generateSampleMessage( + new protos.google.longrunning.Operation() + ); + client.innerApiCalls.importDocuments = stubLongRunningCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.importDocuments( + request, + (err?: Error|null, + result?: LROperation|null + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }); + }); + const operation = await promise as LROperation; + const [response] = await operation.promise(); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = (client.innerApiCalls.importDocuments as SinonStub) + .getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = (client.innerApiCalls.importDocuments as SinonStub) + .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes importDocuments with call error', async () => { + const client = new firestoreadminModule.FirestoreAdminClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.firestore.admin.v1.ImportDocumentsRequest() + ); + const defaultValue1 = + getTypeDefaultValue('.google.firestore.admin.v1.ImportDocumentsRequest', ['name']); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; + const expectedError = new Error('expected'); + client.innerApiCalls.importDocuments = stubLongRunningCall(undefined, expectedError); + await assert.rejects(client.importDocuments(request), expectedError); + const actualRequest = (client.innerApiCalls.importDocuments as SinonStub) + .getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = (client.innerApiCalls.importDocuments as SinonStub) + .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes importDocuments with LRO error', async () => { + const client = new firestoreadminModule.FirestoreAdminClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.firestore.admin.v1.ImportDocumentsRequest() + ); + const defaultValue1 = + getTypeDefaultValue('.google.firestore.admin.v1.ImportDocumentsRequest', ['name']); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; + const expectedError = new Error('expected'); + client.innerApiCalls.importDocuments = stubLongRunningCall(undefined, undefined, expectedError); + const [operation] = await client.importDocuments(request); + await assert.rejects(operation.promise(), expectedError); + const actualRequest = (client.innerApiCalls.importDocuments as SinonStub) + .getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = (client.innerApiCalls.importDocuments as SinonStub) + .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes checkImportDocumentsProgress without error', async () => { + const client = new firestoreadminModule.FirestoreAdminClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const expectedResponse = generateSampleMessage( + new operationsProtos.google.longrunning.Operation() + ); + expectedResponse.name = 'test'; + expectedResponse.response = {type_url: 'url', value: Buffer.from('')}; + expectedResponse.metadata = {type_url: 'url', value: Buffer.from('')} + + client.operationsClient.getOperation = stubSimpleCall(expectedResponse); + const decodedOperation = await client.checkImportDocumentsProgress(expectedResponse.name); + assert.deepStrictEqual(decodedOperation.name, expectedResponse.name); + assert(decodedOperation.metadata); + assert((client.operationsClient.getOperation as SinonStub).getCall(0)); + }); + + it('invokes checkImportDocumentsProgress with error', async () => { + const client = new firestoreadminModule.FirestoreAdminClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const expectedError = new Error('expected'); + + client.operationsClient.getOperation = stubSimpleCall(undefined, expectedError); + await assert.rejects(client.checkImportDocumentsProgress(''), expectedError); + assert((client.operationsClient.getOperation as SinonStub) + .getCall(0)); + }); }); - it('invokes listIndexesStream without error', async () => { - const client = new firestoreadminModule.FirestoreAdminClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.initialize(); - const request = generateSampleMessage( - new protos.google.firestore.admin.v1.ListIndexesRequest() - ); - const defaultValue1 = getTypeDefaultValue( - '.google.firestore.admin.v1.ListIndexesRequest', - ['parent'] - ); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; - const expectedResponse = [ - generateSampleMessage(new protos.google.firestore.admin.v1.Index()), - generateSampleMessage(new protos.google.firestore.admin.v1.Index()), - generateSampleMessage(new protos.google.firestore.admin.v1.Index()), - ]; - client.descriptors.page.listIndexes.createStream = - stubPageStreamingCall(expectedResponse); - const stream = client.listIndexesStream(request); - const promise = new Promise((resolve, reject) => { - const responses: protos.google.firestore.admin.v1.Index[] = []; - stream.on( - 'data', - (response: protos.google.firestore.admin.v1.Index) => { - responses.push(response); - } - ); - stream.on('end', () => { - resolve(responses); - }); - stream.on('error', (err: Error) => { - reject(err); - }); - }); - const responses = await promise; - assert.deepStrictEqual(responses, expectedResponse); - assert( - (client.descriptors.page.listIndexes.createStream as SinonStub) - .getCall(0) - .calledWith(client.innerApiCalls.listIndexes, request) - ); - assert( - (client.descriptors.page.listIndexes.createStream as SinonStub) - .getCall(0) - .args[2].otherArgs.headers[ - 'x-goog-request-params' - ].includes(expectedHeaderRequestParams) - ); + describe('bulkDeleteDocuments', () => { + it('invokes bulkDeleteDocuments without error', async () => { + const client = new firestoreadminModule.FirestoreAdminClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.firestore.admin.v1.BulkDeleteDocumentsRequest() + ); + const defaultValue1 = + getTypeDefaultValue('.google.firestore.admin.v1.BulkDeleteDocumentsRequest', ['name']); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; + const expectedResponse = generateSampleMessage( + new protos.google.longrunning.Operation() + ); + client.innerApiCalls.bulkDeleteDocuments = stubLongRunningCall(expectedResponse); + const [operation] = await client.bulkDeleteDocuments(request); + const [response] = await operation.promise(); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = (client.innerApiCalls.bulkDeleteDocuments as SinonStub) + .getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = (client.innerApiCalls.bulkDeleteDocuments as SinonStub) + .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes bulkDeleteDocuments without error using callback', async () => { + const client = new firestoreadminModule.FirestoreAdminClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.firestore.admin.v1.BulkDeleteDocumentsRequest() + ); + const defaultValue1 = + getTypeDefaultValue('.google.firestore.admin.v1.BulkDeleteDocumentsRequest', ['name']); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; + const expectedResponse = generateSampleMessage( + new protos.google.longrunning.Operation() + ); + client.innerApiCalls.bulkDeleteDocuments = stubLongRunningCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.bulkDeleteDocuments( + request, + (err?: Error|null, + result?: LROperation|null + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }); + }); + const operation = await promise as LROperation; + const [response] = await operation.promise(); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = (client.innerApiCalls.bulkDeleteDocuments as SinonStub) + .getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = (client.innerApiCalls.bulkDeleteDocuments as SinonStub) + .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes bulkDeleteDocuments with call error', async () => { + const client = new firestoreadminModule.FirestoreAdminClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.firestore.admin.v1.BulkDeleteDocumentsRequest() + ); + const defaultValue1 = + getTypeDefaultValue('.google.firestore.admin.v1.BulkDeleteDocumentsRequest', ['name']); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; + const expectedError = new Error('expected'); + client.innerApiCalls.bulkDeleteDocuments = stubLongRunningCall(undefined, expectedError); + await assert.rejects(client.bulkDeleteDocuments(request), expectedError); + const actualRequest = (client.innerApiCalls.bulkDeleteDocuments as SinonStub) + .getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = (client.innerApiCalls.bulkDeleteDocuments as SinonStub) + .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes bulkDeleteDocuments with LRO error', async () => { + const client = new firestoreadminModule.FirestoreAdminClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.firestore.admin.v1.BulkDeleteDocumentsRequest() + ); + const defaultValue1 = + getTypeDefaultValue('.google.firestore.admin.v1.BulkDeleteDocumentsRequest', ['name']); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; + const expectedError = new Error('expected'); + client.innerApiCalls.bulkDeleteDocuments = stubLongRunningCall(undefined, undefined, expectedError); + const [operation] = await client.bulkDeleteDocuments(request); + await assert.rejects(operation.promise(), expectedError); + const actualRequest = (client.innerApiCalls.bulkDeleteDocuments as SinonStub) + .getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = (client.innerApiCalls.bulkDeleteDocuments as SinonStub) + .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes checkBulkDeleteDocumentsProgress without error', async () => { + const client = new firestoreadminModule.FirestoreAdminClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const expectedResponse = generateSampleMessage( + new operationsProtos.google.longrunning.Operation() + ); + expectedResponse.name = 'test'; + expectedResponse.response = {type_url: 'url', value: Buffer.from('')}; + expectedResponse.metadata = {type_url: 'url', value: Buffer.from('')} + + client.operationsClient.getOperation = stubSimpleCall(expectedResponse); + const decodedOperation = await client.checkBulkDeleteDocumentsProgress(expectedResponse.name); + assert.deepStrictEqual(decodedOperation.name, expectedResponse.name); + assert(decodedOperation.metadata); + assert((client.operationsClient.getOperation as SinonStub).getCall(0)); + }); + + it('invokes checkBulkDeleteDocumentsProgress with error', async () => { + const client = new firestoreadminModule.FirestoreAdminClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const expectedError = new Error('expected'); + + client.operationsClient.getOperation = stubSimpleCall(undefined, expectedError); + await assert.rejects(client.checkBulkDeleteDocumentsProgress(''), expectedError); + assert((client.operationsClient.getOperation as SinonStub) + .getCall(0)); + }); }); - it('invokes listIndexesStream with error', async () => { - const client = new firestoreadminModule.FirestoreAdminClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.initialize(); - const request = generateSampleMessage( - new protos.google.firestore.admin.v1.ListIndexesRequest() - ); - const defaultValue1 = getTypeDefaultValue( - '.google.firestore.admin.v1.ListIndexesRequest', - ['parent'] - ); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; - const expectedError = new Error('expected'); - client.descriptors.page.listIndexes.createStream = stubPageStreamingCall( - undefined, - expectedError - ); - const stream = client.listIndexesStream(request); - const promise = new Promise((resolve, reject) => { - const responses: protos.google.firestore.admin.v1.Index[] = []; - stream.on( - 'data', - (response: protos.google.firestore.admin.v1.Index) => { - responses.push(response); - } - ); - stream.on('end', () => { - resolve(responses); - }); - stream.on('error', (err: Error) => { - reject(err); - }); - }); - await assert.rejects(promise, expectedError); - assert( - (client.descriptors.page.listIndexes.createStream as SinonStub) - .getCall(0) - .calledWith(client.innerApiCalls.listIndexes, request) - ); - assert( - (client.descriptors.page.listIndexes.createStream as SinonStub) - .getCall(0) - .args[2].otherArgs.headers[ - 'x-goog-request-params' - ].includes(expectedHeaderRequestParams) - ); + describe('createDatabase', () => { + it('invokes createDatabase without error', async () => { + const client = new firestoreadminModule.FirestoreAdminClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.firestore.admin.v1.CreateDatabaseRequest() + ); + const defaultValue1 = + getTypeDefaultValue('.google.firestore.admin.v1.CreateDatabaseRequest', ['parent']); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; + const expectedResponse = generateSampleMessage( + new protos.google.longrunning.Operation() + ); + client.innerApiCalls.createDatabase = stubLongRunningCall(expectedResponse); + const [operation] = await client.createDatabase(request); + const [response] = await operation.promise(); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = (client.innerApiCalls.createDatabase as SinonStub) + .getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = (client.innerApiCalls.createDatabase as SinonStub) + .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes createDatabase without error using callback', async () => { + const client = new firestoreadminModule.FirestoreAdminClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.firestore.admin.v1.CreateDatabaseRequest() + ); + const defaultValue1 = + getTypeDefaultValue('.google.firestore.admin.v1.CreateDatabaseRequest', ['parent']); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; + const expectedResponse = generateSampleMessage( + new protos.google.longrunning.Operation() + ); + client.innerApiCalls.createDatabase = stubLongRunningCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.createDatabase( + request, + (err?: Error|null, + result?: LROperation|null + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }); + }); + const operation = await promise as LROperation; + const [response] = await operation.promise(); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = (client.innerApiCalls.createDatabase as SinonStub) + .getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = (client.innerApiCalls.createDatabase as SinonStub) + .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes createDatabase with call error', async () => { + const client = new firestoreadminModule.FirestoreAdminClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.firestore.admin.v1.CreateDatabaseRequest() + ); + const defaultValue1 = + getTypeDefaultValue('.google.firestore.admin.v1.CreateDatabaseRequest', ['parent']); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; + const expectedError = new Error('expected'); + client.innerApiCalls.createDatabase = stubLongRunningCall(undefined, expectedError); + await assert.rejects(client.createDatabase(request), expectedError); + const actualRequest = (client.innerApiCalls.createDatabase as SinonStub) + .getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = (client.innerApiCalls.createDatabase as SinonStub) + .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes createDatabase with LRO error', async () => { + const client = new firestoreadminModule.FirestoreAdminClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.firestore.admin.v1.CreateDatabaseRequest() + ); + const defaultValue1 = + getTypeDefaultValue('.google.firestore.admin.v1.CreateDatabaseRequest', ['parent']); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; + const expectedError = new Error('expected'); + client.innerApiCalls.createDatabase = stubLongRunningCall(undefined, undefined, expectedError); + const [operation] = await client.createDatabase(request); + await assert.rejects(operation.promise(), expectedError); + const actualRequest = (client.innerApiCalls.createDatabase as SinonStub) + .getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = (client.innerApiCalls.createDatabase as SinonStub) + .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes checkCreateDatabaseProgress without error', async () => { + const client = new firestoreadminModule.FirestoreAdminClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const expectedResponse = generateSampleMessage( + new operationsProtos.google.longrunning.Operation() + ); + expectedResponse.name = 'test'; + expectedResponse.response = {type_url: 'url', value: Buffer.from('')}; + expectedResponse.metadata = {type_url: 'url', value: Buffer.from('')} + + client.operationsClient.getOperation = stubSimpleCall(expectedResponse); + const decodedOperation = await client.checkCreateDatabaseProgress(expectedResponse.name); + assert.deepStrictEqual(decodedOperation.name, expectedResponse.name); + assert(decodedOperation.metadata); + assert((client.operationsClient.getOperation as SinonStub).getCall(0)); + }); + + it('invokes checkCreateDatabaseProgress with error', async () => { + const client = new firestoreadminModule.FirestoreAdminClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const expectedError = new Error('expected'); + + client.operationsClient.getOperation = stubSimpleCall(undefined, expectedError); + await assert.rejects(client.checkCreateDatabaseProgress(''), expectedError); + assert((client.operationsClient.getOperation as SinonStub) + .getCall(0)); + }); }); - it('uses async iteration with listIndexes without error', async () => { - const client = new firestoreadminModule.FirestoreAdminClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.initialize(); - const request = generateSampleMessage( - new protos.google.firestore.admin.v1.ListIndexesRequest() - ); - const defaultValue1 = getTypeDefaultValue( - '.google.firestore.admin.v1.ListIndexesRequest', - ['parent'] - ); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; - const expectedResponse = [ - generateSampleMessage(new protos.google.firestore.admin.v1.Index()), - generateSampleMessage(new protos.google.firestore.admin.v1.Index()), - generateSampleMessage(new protos.google.firestore.admin.v1.Index()), - ]; - client.descriptors.page.listIndexes.asyncIterate = - stubAsyncIterationCall(expectedResponse); - const responses: protos.google.firestore.admin.v1.IIndex[] = []; - const iterable = client.listIndexesAsync(request); - for await (const resource of iterable) { - responses.push(resource!); - } - assert.deepStrictEqual(responses, expectedResponse); - assert.deepStrictEqual( - (client.descriptors.page.listIndexes.asyncIterate as SinonStub).getCall( - 0 - ).args[1], - request - ); - assert( - (client.descriptors.page.listIndexes.asyncIterate as SinonStub) - .getCall(0) - .args[2].otherArgs.headers[ - 'x-goog-request-params' - ].includes(expectedHeaderRequestParams) - ); + describe('updateDatabase', () => { + it('invokes updateDatabase without error', async () => { + const client = new firestoreadminModule.FirestoreAdminClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.firestore.admin.v1.UpdateDatabaseRequest() + ); + request.database ??= {}; + const defaultValue1 = + getTypeDefaultValue('.google.firestore.admin.v1.UpdateDatabaseRequest', ['database', 'name']); + request.database.name = defaultValue1; + const expectedHeaderRequestParams = `database.name=${defaultValue1 ?? '' }`; + const expectedResponse = generateSampleMessage( + new protos.google.longrunning.Operation() + ); + client.innerApiCalls.updateDatabase = stubLongRunningCall(expectedResponse); + const [operation] = await client.updateDatabase(request); + const [response] = await operation.promise(); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = (client.innerApiCalls.updateDatabase as SinonStub) + .getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = (client.innerApiCalls.updateDatabase as SinonStub) + .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes updateDatabase without error using callback', async () => { + const client = new firestoreadminModule.FirestoreAdminClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.firestore.admin.v1.UpdateDatabaseRequest() + ); + request.database ??= {}; + const defaultValue1 = + getTypeDefaultValue('.google.firestore.admin.v1.UpdateDatabaseRequest', ['database', 'name']); + request.database.name = defaultValue1; + const expectedHeaderRequestParams = `database.name=${defaultValue1 ?? '' }`; + const expectedResponse = generateSampleMessage( + new protos.google.longrunning.Operation() + ); + client.innerApiCalls.updateDatabase = stubLongRunningCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.updateDatabase( + request, + (err?: Error|null, + result?: LROperation|null + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }); + }); + const operation = await promise as LROperation; + const [response] = await operation.promise(); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = (client.innerApiCalls.updateDatabase as SinonStub) + .getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = (client.innerApiCalls.updateDatabase as SinonStub) + .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes updateDatabase with call error', async () => { + const client = new firestoreadminModule.FirestoreAdminClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.firestore.admin.v1.UpdateDatabaseRequest() + ); + request.database ??= {}; + const defaultValue1 = + getTypeDefaultValue('.google.firestore.admin.v1.UpdateDatabaseRequest', ['database', 'name']); + request.database.name = defaultValue1; + const expectedHeaderRequestParams = `database.name=${defaultValue1 ?? '' }`; + const expectedError = new Error('expected'); + client.innerApiCalls.updateDatabase = stubLongRunningCall(undefined, expectedError); + await assert.rejects(client.updateDatabase(request), expectedError); + const actualRequest = (client.innerApiCalls.updateDatabase as SinonStub) + .getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = (client.innerApiCalls.updateDatabase as SinonStub) + .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes updateDatabase with LRO error', async () => { + const client = new firestoreadminModule.FirestoreAdminClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.firestore.admin.v1.UpdateDatabaseRequest() + ); + request.database ??= {}; + const defaultValue1 = + getTypeDefaultValue('.google.firestore.admin.v1.UpdateDatabaseRequest', ['database', 'name']); + request.database.name = defaultValue1; + const expectedHeaderRequestParams = `database.name=${defaultValue1 ?? '' }`; + const expectedError = new Error('expected'); + client.innerApiCalls.updateDatabase = stubLongRunningCall(undefined, undefined, expectedError); + const [operation] = await client.updateDatabase(request); + await assert.rejects(operation.promise(), expectedError); + const actualRequest = (client.innerApiCalls.updateDatabase as SinonStub) + .getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = (client.innerApiCalls.updateDatabase as SinonStub) + .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes checkUpdateDatabaseProgress without error', async () => { + const client = new firestoreadminModule.FirestoreAdminClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const expectedResponse = generateSampleMessage( + new operationsProtos.google.longrunning.Operation() + ); + expectedResponse.name = 'test'; + expectedResponse.response = {type_url: 'url', value: Buffer.from('')}; + expectedResponse.metadata = {type_url: 'url', value: Buffer.from('')} + + client.operationsClient.getOperation = stubSimpleCall(expectedResponse); + const decodedOperation = await client.checkUpdateDatabaseProgress(expectedResponse.name); + assert.deepStrictEqual(decodedOperation.name, expectedResponse.name); + assert(decodedOperation.metadata); + assert((client.operationsClient.getOperation as SinonStub).getCall(0)); + }); + + it('invokes checkUpdateDatabaseProgress with error', async () => { + const client = new firestoreadminModule.FirestoreAdminClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const expectedError = new Error('expected'); + + client.operationsClient.getOperation = stubSimpleCall(undefined, expectedError); + await assert.rejects(client.checkUpdateDatabaseProgress(''), expectedError); + assert((client.operationsClient.getOperation as SinonStub) + .getCall(0)); + }); }); - it('uses async iteration with listIndexes with error', async () => { - const client = new firestoreadminModule.FirestoreAdminClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.initialize(); - const request = generateSampleMessage( - new protos.google.firestore.admin.v1.ListIndexesRequest() - ); - const defaultValue1 = getTypeDefaultValue( - '.google.firestore.admin.v1.ListIndexesRequest', - ['parent'] - ); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; - const expectedError = new Error('expected'); - client.descriptors.page.listIndexes.asyncIterate = stubAsyncIterationCall( - undefined, - expectedError - ); - const iterable = client.listIndexesAsync(request); - await assert.rejects(async () => { - const responses: protos.google.firestore.admin.v1.IIndex[] = []; - for await (const resource of iterable) { - responses.push(resource!); - } - }); - assert.deepStrictEqual( - (client.descriptors.page.listIndexes.asyncIterate as SinonStub).getCall( - 0 - ).args[1], - request - ); - assert( - (client.descriptors.page.listIndexes.asyncIterate as SinonStub) - .getCall(0) - .args[2].otherArgs.headers[ - 'x-goog-request-params' - ].includes(expectedHeaderRequestParams) - ); + describe('deleteDatabase', () => { + it('invokes deleteDatabase without error', async () => { + const client = new firestoreadminModule.FirestoreAdminClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.firestore.admin.v1.DeleteDatabaseRequest() + ); + const defaultValue1 = + getTypeDefaultValue('.google.firestore.admin.v1.DeleteDatabaseRequest', ['name']); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; + const expectedResponse = generateSampleMessage( + new protos.google.longrunning.Operation() + ); + client.innerApiCalls.deleteDatabase = stubLongRunningCall(expectedResponse); + const [operation] = await client.deleteDatabase(request); + const [response] = await operation.promise(); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = (client.innerApiCalls.deleteDatabase as SinonStub) + .getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = (client.innerApiCalls.deleteDatabase as SinonStub) + .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes deleteDatabase without error using callback', async () => { + const client = new firestoreadminModule.FirestoreAdminClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.firestore.admin.v1.DeleteDatabaseRequest() + ); + const defaultValue1 = + getTypeDefaultValue('.google.firestore.admin.v1.DeleteDatabaseRequest', ['name']); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; + const expectedResponse = generateSampleMessage( + new protos.google.longrunning.Operation() + ); + client.innerApiCalls.deleteDatabase = stubLongRunningCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.deleteDatabase( + request, + (err?: Error|null, + result?: LROperation|null + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }); + }); + const operation = await promise as LROperation; + const [response] = await operation.promise(); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = (client.innerApiCalls.deleteDatabase as SinonStub) + .getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = (client.innerApiCalls.deleteDatabase as SinonStub) + .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes deleteDatabase with call error', async () => { + const client = new firestoreadminModule.FirestoreAdminClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.firestore.admin.v1.DeleteDatabaseRequest() + ); + const defaultValue1 = + getTypeDefaultValue('.google.firestore.admin.v1.DeleteDatabaseRequest', ['name']); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; + const expectedError = new Error('expected'); + client.innerApiCalls.deleteDatabase = stubLongRunningCall(undefined, expectedError); + await assert.rejects(client.deleteDatabase(request), expectedError); + const actualRequest = (client.innerApiCalls.deleteDatabase as SinonStub) + .getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = (client.innerApiCalls.deleteDatabase as SinonStub) + .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes deleteDatabase with LRO error', async () => { + const client = new firestoreadminModule.FirestoreAdminClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.firestore.admin.v1.DeleteDatabaseRequest() + ); + const defaultValue1 = + getTypeDefaultValue('.google.firestore.admin.v1.DeleteDatabaseRequest', ['name']); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; + const expectedError = new Error('expected'); + client.innerApiCalls.deleteDatabase = stubLongRunningCall(undefined, undefined, expectedError); + const [operation] = await client.deleteDatabase(request); + await assert.rejects(operation.promise(), expectedError); + const actualRequest = (client.innerApiCalls.deleteDatabase as SinonStub) + .getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = (client.innerApiCalls.deleteDatabase as SinonStub) + .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes checkDeleteDatabaseProgress without error', async () => { + const client = new firestoreadminModule.FirestoreAdminClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const expectedResponse = generateSampleMessage( + new operationsProtos.google.longrunning.Operation() + ); + expectedResponse.name = 'test'; + expectedResponse.response = {type_url: 'url', value: Buffer.from('')}; + expectedResponse.metadata = {type_url: 'url', value: Buffer.from('')} + + client.operationsClient.getOperation = stubSimpleCall(expectedResponse); + const decodedOperation = await client.checkDeleteDatabaseProgress(expectedResponse.name); + assert.deepStrictEqual(decodedOperation.name, expectedResponse.name); + assert(decodedOperation.metadata); + assert((client.operationsClient.getOperation as SinonStub).getCall(0)); + }); + + it('invokes checkDeleteDatabaseProgress with error', async () => { + const client = new firestoreadminModule.FirestoreAdminClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const expectedError = new Error('expected'); + + client.operationsClient.getOperation = stubSimpleCall(undefined, expectedError); + await assert.rejects(client.checkDeleteDatabaseProgress(''), expectedError); + assert((client.operationsClient.getOperation as SinonStub) + .getCall(0)); + }); }); - }); - - describe('listFields', () => { - it('invokes listFields without error', async () => { - const client = new firestoreadminModule.FirestoreAdminClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.initialize(); - const request = generateSampleMessage( - new protos.google.firestore.admin.v1.ListFieldsRequest() - ); - const defaultValue1 = getTypeDefaultValue( - '.google.firestore.admin.v1.ListFieldsRequest', - ['parent'] - ); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; - const expectedResponse = [ - generateSampleMessage(new protos.google.firestore.admin.v1.Field()), - generateSampleMessage(new protos.google.firestore.admin.v1.Field()), - generateSampleMessage(new protos.google.firestore.admin.v1.Field()), - ]; - client.innerApiCalls.listFields = stubSimpleCall(expectedResponse); - const [response] = await client.listFields(request); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = ( - client.innerApiCalls.listFields as SinonStub - ).getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = ( - client.innerApiCalls.listFields as SinonStub - ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + + describe('restoreDatabase', () => { + it('invokes restoreDatabase without error', async () => { + const client = new firestoreadminModule.FirestoreAdminClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.firestore.admin.v1.RestoreDatabaseRequest() + ); + const defaultValue1 = + getTypeDefaultValue('.google.firestore.admin.v1.RestoreDatabaseRequest', ['parent']); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; + const expectedResponse = generateSampleMessage( + new protos.google.longrunning.Operation() + ); + client.innerApiCalls.restoreDatabase = stubLongRunningCall(expectedResponse); + const [operation] = await client.restoreDatabase(request); + const [response] = await operation.promise(); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = (client.innerApiCalls.restoreDatabase as SinonStub) + .getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = (client.innerApiCalls.restoreDatabase as SinonStub) + .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes restoreDatabase without error using callback', async () => { + const client = new firestoreadminModule.FirestoreAdminClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.firestore.admin.v1.RestoreDatabaseRequest() + ); + const defaultValue1 = + getTypeDefaultValue('.google.firestore.admin.v1.RestoreDatabaseRequest', ['parent']); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; + const expectedResponse = generateSampleMessage( + new protos.google.longrunning.Operation() + ); + client.innerApiCalls.restoreDatabase = stubLongRunningCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.restoreDatabase( + request, + (err?: Error|null, + result?: LROperation|null + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }); + }); + const operation = await promise as LROperation; + const [response] = await operation.promise(); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = (client.innerApiCalls.restoreDatabase as SinonStub) + .getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = (client.innerApiCalls.restoreDatabase as SinonStub) + .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes restoreDatabase with call error', async () => { + const client = new firestoreadminModule.FirestoreAdminClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.firestore.admin.v1.RestoreDatabaseRequest() + ); + const defaultValue1 = + getTypeDefaultValue('.google.firestore.admin.v1.RestoreDatabaseRequest', ['parent']); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; + const expectedError = new Error('expected'); + client.innerApiCalls.restoreDatabase = stubLongRunningCall(undefined, expectedError); + await assert.rejects(client.restoreDatabase(request), expectedError); + const actualRequest = (client.innerApiCalls.restoreDatabase as SinonStub) + .getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = (client.innerApiCalls.restoreDatabase as SinonStub) + .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes restoreDatabase with LRO error', async () => { + const client = new firestoreadminModule.FirestoreAdminClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.firestore.admin.v1.RestoreDatabaseRequest() + ); + const defaultValue1 = + getTypeDefaultValue('.google.firestore.admin.v1.RestoreDatabaseRequest', ['parent']); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; + const expectedError = new Error('expected'); + client.innerApiCalls.restoreDatabase = stubLongRunningCall(undefined, undefined, expectedError); + const [operation] = await client.restoreDatabase(request); + await assert.rejects(operation.promise(), expectedError); + const actualRequest = (client.innerApiCalls.restoreDatabase as SinonStub) + .getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = (client.innerApiCalls.restoreDatabase as SinonStub) + .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes checkRestoreDatabaseProgress without error', async () => { + const client = new firestoreadminModule.FirestoreAdminClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const expectedResponse = generateSampleMessage( + new operationsProtos.google.longrunning.Operation() + ); + expectedResponse.name = 'test'; + expectedResponse.response = {type_url: 'url', value: Buffer.from('')}; + expectedResponse.metadata = {type_url: 'url', value: Buffer.from('')} + + client.operationsClient.getOperation = stubSimpleCall(expectedResponse); + const decodedOperation = await client.checkRestoreDatabaseProgress(expectedResponse.name); + assert.deepStrictEqual(decodedOperation.name, expectedResponse.name); + assert(decodedOperation.metadata); + assert((client.operationsClient.getOperation as SinonStub).getCall(0)); + }); + + it('invokes checkRestoreDatabaseProgress with error', async () => { + const client = new firestoreadminModule.FirestoreAdminClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const expectedError = new Error('expected'); + + client.operationsClient.getOperation = stubSimpleCall(undefined, expectedError); + await assert.rejects(client.checkRestoreDatabaseProgress(''), expectedError); + assert((client.operationsClient.getOperation as SinonStub) + .getCall(0)); + }); }); - it('invokes listFields without error using callback', async () => { - const client = new firestoreadminModule.FirestoreAdminClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.initialize(); - const request = generateSampleMessage( - new protos.google.firestore.admin.v1.ListFieldsRequest() - ); - const defaultValue1 = getTypeDefaultValue( - '.google.firestore.admin.v1.ListFieldsRequest', - ['parent'] - ); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; - const expectedResponse = [ - generateSampleMessage(new protos.google.firestore.admin.v1.Field()), - generateSampleMessage(new protos.google.firestore.admin.v1.Field()), - generateSampleMessage(new protos.google.firestore.admin.v1.Field()), - ]; - client.innerApiCalls.listFields = - stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.listFields( - request, - ( - err?: Error | null, - result?: protos.google.firestore.admin.v1.IField[] | null - ) => { - if (err) { - reject(err); - } else { - resolve(result); + describe('listIndexes', () => { + it('invokes listIndexes without error', async () => { + const client = new firestoreadminModule.FirestoreAdminClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.firestore.admin.v1.ListIndexesRequest() + ); + const defaultValue1 = + getTypeDefaultValue('.google.firestore.admin.v1.ListIndexesRequest', ['parent']); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`;const expectedResponse = [ + generateSampleMessage(new protos.google.firestore.admin.v1.Index()), + generateSampleMessage(new protos.google.firestore.admin.v1.Index()), + generateSampleMessage(new protos.google.firestore.admin.v1.Index()), + ]; + client.innerApiCalls.listIndexes = stubSimpleCall(expectedResponse); + const [response] = await client.listIndexes(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = (client.innerApiCalls.listIndexes as SinonStub) + .getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = (client.innerApiCalls.listIndexes as SinonStub) + .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes listIndexes without error using callback', async () => { + const client = new firestoreadminModule.FirestoreAdminClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.firestore.admin.v1.ListIndexesRequest() + ); + const defaultValue1 = + getTypeDefaultValue('.google.firestore.admin.v1.ListIndexesRequest', ['parent']); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`;const expectedResponse = [ + generateSampleMessage(new protos.google.firestore.admin.v1.Index()), + generateSampleMessage(new protos.google.firestore.admin.v1.Index()), + generateSampleMessage(new protos.google.firestore.admin.v1.Index()), + ]; + client.innerApiCalls.listIndexes = stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.listIndexes( + request, + (err?: Error|null, result?: protos.google.firestore.admin.v1.IIndex[]|null) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = (client.innerApiCalls.listIndexes as SinonStub) + .getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = (client.innerApiCalls.listIndexes as SinonStub) + .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes listIndexes with error', async () => { + const client = new firestoreadminModule.FirestoreAdminClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.firestore.admin.v1.ListIndexesRequest() + ); + const defaultValue1 = + getTypeDefaultValue('.google.firestore.admin.v1.ListIndexesRequest', ['parent']); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; + const expectedError = new Error('expected'); + client.innerApiCalls.listIndexes = stubSimpleCall(undefined, expectedError); + await assert.rejects(client.listIndexes(request), expectedError); + const actualRequest = (client.innerApiCalls.listIndexes as SinonStub) + .getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = (client.innerApiCalls.listIndexes as SinonStub) + .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes listIndexesStream without error', async () => { + const client = new firestoreadminModule.FirestoreAdminClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.firestore.admin.v1.ListIndexesRequest() + ); + const defaultValue1 = + getTypeDefaultValue('.google.firestore.admin.v1.ListIndexesRequest', ['parent']); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; + const expectedResponse = [ + generateSampleMessage(new protos.google.firestore.admin.v1.Index()), + generateSampleMessage(new protos.google.firestore.admin.v1.Index()), + generateSampleMessage(new protos.google.firestore.admin.v1.Index()), + ]; + client.descriptors.page.listIndexes.createStream = stubPageStreamingCall(expectedResponse); + const stream = client.listIndexesStream(request); + const promise = new Promise((resolve, reject) => { + const responses: protos.google.firestore.admin.v1.Index[] = []; + stream.on('data', (response: protos.google.firestore.admin.v1.Index) => { + responses.push(response); + }); + stream.on('end', () => { + resolve(responses); + }); + stream.on('error', (err: Error) => { + reject(err); + }); + }); + const responses = await promise; + assert.deepStrictEqual(responses, expectedResponse); + assert((client.descriptors.page.listIndexes.createStream as SinonStub) + .getCall(0).calledWith(client.innerApiCalls.listIndexes, request)); + assert( + (client.descriptors.page.listIndexes.createStream as SinonStub) + .getCall(0).args[2].otherArgs.headers['x-goog-request-params'].includes( + expectedHeaderRequestParams + ) + ); + }); + + it('invokes listIndexesStream with error', async () => { + const client = new firestoreadminModule.FirestoreAdminClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.firestore.admin.v1.ListIndexesRequest() + ); + const defaultValue1 = + getTypeDefaultValue('.google.firestore.admin.v1.ListIndexesRequest', ['parent']); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; + const expectedError = new Error('expected'); + client.descriptors.page.listIndexes.createStream = stubPageStreamingCall(undefined, expectedError); + const stream = client.listIndexesStream(request); + const promise = new Promise((resolve, reject) => { + const responses: protos.google.firestore.admin.v1.Index[] = []; + stream.on('data', (response: protos.google.firestore.admin.v1.Index) => { + responses.push(response); + }); + stream.on('end', () => { + resolve(responses); + }); + stream.on('error', (err: Error) => { + reject(err); + }); + }); + await assert.rejects(promise, expectedError); + assert((client.descriptors.page.listIndexes.createStream as SinonStub) + .getCall(0).calledWith(client.innerApiCalls.listIndexes, request)); + assert( + (client.descriptors.page.listIndexes.createStream as SinonStub) + .getCall(0).args[2].otherArgs.headers['x-goog-request-params'].includes( + expectedHeaderRequestParams + ) + ); + }); + + it('uses async iteration with listIndexes without error', async () => { + const client = new firestoreadminModule.FirestoreAdminClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.firestore.admin.v1.ListIndexesRequest() + ); + const defaultValue1 = + getTypeDefaultValue('.google.firestore.admin.v1.ListIndexesRequest', ['parent']); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; + const expectedResponse = [ + generateSampleMessage(new protos.google.firestore.admin.v1.Index()), + generateSampleMessage(new protos.google.firestore.admin.v1.Index()), + generateSampleMessage(new protos.google.firestore.admin.v1.Index()), + ]; + client.descriptors.page.listIndexes.asyncIterate = stubAsyncIterationCall(expectedResponse); + const responses: protos.google.firestore.admin.v1.IIndex[] = []; + const iterable = client.listIndexesAsync(request); + for await (const resource of iterable) { + responses.push(resource!); } - } - ); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = ( - client.innerApiCalls.listFields as SinonStub - ).getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = ( - client.innerApiCalls.listFields as SinonStub - ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + assert.deepStrictEqual(responses, expectedResponse); + assert.deepStrictEqual( + (client.descriptors.page.listIndexes.asyncIterate as SinonStub) + .getCall(0).args[1], request); + assert( + (client.descriptors.page.listIndexes.asyncIterate as SinonStub) + .getCall(0).args[2].otherArgs.headers['x-goog-request-params'].includes( + expectedHeaderRequestParams + ) + ); + }); - it('invokes listFields with error', async () => { - const client = new firestoreadminModule.FirestoreAdminClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.initialize(); - const request = generateSampleMessage( - new protos.google.firestore.admin.v1.ListFieldsRequest() - ); - const defaultValue1 = getTypeDefaultValue( - '.google.firestore.admin.v1.ListFieldsRequest', - ['parent'] - ); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; - const expectedError = new Error('expected'); - client.innerApiCalls.listFields = stubSimpleCall( - undefined, - expectedError - ); - await assert.rejects(client.listFields(request), expectedError); - const actualRequest = ( - client.innerApiCalls.listFields as SinonStub - ).getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = ( - client.innerApiCalls.listFields as SinonStub - ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + it('uses async iteration with listIndexes with error', async () => { + const client = new firestoreadminModule.FirestoreAdminClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.firestore.admin.v1.ListIndexesRequest() + ); + const defaultValue1 = + getTypeDefaultValue('.google.firestore.admin.v1.ListIndexesRequest', ['parent']); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; + const expectedError = new Error('expected'); + client.descriptors.page.listIndexes.asyncIterate = stubAsyncIterationCall(undefined, expectedError); + const iterable = client.listIndexesAsync(request); + await assert.rejects(async () => { + const responses: protos.google.firestore.admin.v1.IIndex[] = []; + for await (const resource of iterable) { + responses.push(resource!); + } + }); + assert.deepStrictEqual( + (client.descriptors.page.listIndexes.asyncIterate as SinonStub) + .getCall(0).args[1], request); + assert( + (client.descriptors.page.listIndexes.asyncIterate as SinonStub) + .getCall(0).args[2].otherArgs.headers['x-goog-request-params'].includes( + expectedHeaderRequestParams + ) + ); + }); }); - it('invokes listFieldsStream without error', async () => { - const client = new firestoreadminModule.FirestoreAdminClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.initialize(); - const request = generateSampleMessage( - new protos.google.firestore.admin.v1.ListFieldsRequest() - ); - const defaultValue1 = getTypeDefaultValue( - '.google.firestore.admin.v1.ListFieldsRequest', - ['parent'] - ); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; - const expectedResponse = [ - generateSampleMessage(new protos.google.firestore.admin.v1.Field()), - generateSampleMessage(new protos.google.firestore.admin.v1.Field()), - generateSampleMessage(new protos.google.firestore.admin.v1.Field()), - ]; - client.descriptors.page.listFields.createStream = - stubPageStreamingCall(expectedResponse); - const stream = client.listFieldsStream(request); - const promise = new Promise((resolve, reject) => { - const responses: protos.google.firestore.admin.v1.Field[] = []; - stream.on( - 'data', - (response: protos.google.firestore.admin.v1.Field) => { - responses.push(response); - } - ); - stream.on('end', () => { - resolve(responses); - }); - stream.on('error', (err: Error) => { - reject(err); - }); - }); - const responses = await promise; - assert.deepStrictEqual(responses, expectedResponse); - assert( - (client.descriptors.page.listFields.createStream as SinonStub) - .getCall(0) - .calledWith(client.innerApiCalls.listFields, request) - ); - assert( - (client.descriptors.page.listFields.createStream as SinonStub) - .getCall(0) - .args[2].otherArgs.headers[ - 'x-goog-request-params' - ].includes(expectedHeaderRequestParams) - ); - }); + describe('listFields', () => { + it('invokes listFields without error', async () => { + const client = new firestoreadminModule.FirestoreAdminClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.firestore.admin.v1.ListFieldsRequest() + ); + const defaultValue1 = + getTypeDefaultValue('.google.firestore.admin.v1.ListFieldsRequest', ['parent']); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`;const expectedResponse = [ + generateSampleMessage(new protos.google.firestore.admin.v1.Field()), + generateSampleMessage(new protos.google.firestore.admin.v1.Field()), + generateSampleMessage(new protos.google.firestore.admin.v1.Field()), + ]; + client.innerApiCalls.listFields = stubSimpleCall(expectedResponse); + const [response] = await client.listFields(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = (client.innerApiCalls.listFields as SinonStub) + .getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = (client.innerApiCalls.listFields as SinonStub) + .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes listFieldsStream with error', async () => { - const client = new firestoreadminModule.FirestoreAdminClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.initialize(); - const request = generateSampleMessage( - new protos.google.firestore.admin.v1.ListFieldsRequest() - ); - const defaultValue1 = getTypeDefaultValue( - '.google.firestore.admin.v1.ListFieldsRequest', - ['parent'] - ); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; - const expectedError = new Error('expected'); - client.descriptors.page.listFields.createStream = stubPageStreamingCall( - undefined, - expectedError - ); - const stream = client.listFieldsStream(request); - const promise = new Promise((resolve, reject) => { - const responses: protos.google.firestore.admin.v1.Field[] = []; - stream.on( - 'data', - (response: protos.google.firestore.admin.v1.Field) => { - responses.push(response); - } - ); - stream.on('end', () => { - resolve(responses); - }); - stream.on('error', (err: Error) => { - reject(err); - }); - }); - await assert.rejects(promise, expectedError); - assert( - (client.descriptors.page.listFields.createStream as SinonStub) - .getCall(0) - .calledWith(client.innerApiCalls.listFields, request) - ); - assert( - (client.descriptors.page.listFields.createStream as SinonStub) - .getCall(0) - .args[2].otherArgs.headers[ - 'x-goog-request-params' - ].includes(expectedHeaderRequestParams) - ); - }); + it('invokes listFields without error using callback', async () => { + const client = new firestoreadminModule.FirestoreAdminClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.firestore.admin.v1.ListFieldsRequest() + ); + const defaultValue1 = + getTypeDefaultValue('.google.firestore.admin.v1.ListFieldsRequest', ['parent']); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`;const expectedResponse = [ + generateSampleMessage(new protos.google.firestore.admin.v1.Field()), + generateSampleMessage(new protos.google.firestore.admin.v1.Field()), + generateSampleMessage(new protos.google.firestore.admin.v1.Field()), + ]; + client.innerApiCalls.listFields = stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.listFields( + request, + (err?: Error|null, result?: protos.google.firestore.admin.v1.IField[]|null) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = (client.innerApiCalls.listFields as SinonStub) + .getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = (client.innerApiCalls.listFields as SinonStub) + .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('uses async iteration with listFields without error', async () => { - const client = new firestoreadminModule.FirestoreAdminClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.initialize(); - const request = generateSampleMessage( - new protos.google.firestore.admin.v1.ListFieldsRequest() - ); - const defaultValue1 = getTypeDefaultValue( - '.google.firestore.admin.v1.ListFieldsRequest', - ['parent'] - ); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; - const expectedResponse = [ - generateSampleMessage(new protos.google.firestore.admin.v1.Field()), - generateSampleMessage(new protos.google.firestore.admin.v1.Field()), - generateSampleMessage(new protos.google.firestore.admin.v1.Field()), - ]; - client.descriptors.page.listFields.asyncIterate = - stubAsyncIterationCall(expectedResponse); - const responses: protos.google.firestore.admin.v1.IField[] = []; - const iterable = client.listFieldsAsync(request); - for await (const resource of iterable) { - responses.push(resource!); - } - assert.deepStrictEqual(responses, expectedResponse); - assert.deepStrictEqual( - (client.descriptors.page.listFields.asyncIterate as SinonStub).getCall( - 0 - ).args[1], - request - ); - assert( - (client.descriptors.page.listFields.asyncIterate as SinonStub) - .getCall(0) - .args[2].otherArgs.headers[ - 'x-goog-request-params' - ].includes(expectedHeaderRequestParams) - ); - }); + it('invokes listFields with error', async () => { + const client = new firestoreadminModule.FirestoreAdminClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.firestore.admin.v1.ListFieldsRequest() + ); + const defaultValue1 = + getTypeDefaultValue('.google.firestore.admin.v1.ListFieldsRequest', ['parent']); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; + const expectedError = new Error('expected'); + client.innerApiCalls.listFields = stubSimpleCall(undefined, expectedError); + await assert.rejects(client.listFields(request), expectedError); + const actualRequest = (client.innerApiCalls.listFields as SinonStub) + .getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = (client.innerApiCalls.listFields as SinonStub) + .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('uses async iteration with listFields with error', async () => { - const client = new firestoreadminModule.FirestoreAdminClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.initialize(); - const request = generateSampleMessage( - new protos.google.firestore.admin.v1.ListFieldsRequest() - ); - const defaultValue1 = getTypeDefaultValue( - '.google.firestore.admin.v1.ListFieldsRequest', - ['parent'] - ); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; - const expectedError = new Error('expected'); - client.descriptors.page.listFields.asyncIterate = stubAsyncIterationCall( - undefined, - expectedError - ); - const iterable = client.listFieldsAsync(request); - await assert.rejects(async () => { - const responses: protos.google.firestore.admin.v1.IField[] = []; - for await (const resource of iterable) { - responses.push(resource!); - } - }); - assert.deepStrictEqual( - (client.descriptors.page.listFields.asyncIterate as SinonStub).getCall( - 0 - ).args[1], - request - ); - assert( - (client.descriptors.page.listFields.asyncIterate as SinonStub) - .getCall(0) - .args[2].otherArgs.headers[ - 'x-goog-request-params' - ].includes(expectedHeaderRequestParams) - ); - }); - }); - describe('getLocation', () => { - it('invokes getLocation without error', async () => { - const client = new firestoreadminModule.FirestoreAdminClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.initialize(); - const request = generateSampleMessage( - new LocationProtos.google.cloud.location.GetLocationRequest() - ); - request.name = ''; - const expectedHeaderRequestParams = 'name='; - const expectedOptions = { - otherArgs: { - headers: { - 'x-goog-request-params': expectedHeaderRequestParams, - }, - }, - }; - const expectedResponse = generateSampleMessage( - new LocationProtos.google.cloud.location.Location() - ); - client.locationsClient.getLocation = stubSimpleCall(expectedResponse); - const response = await client.getLocation(request, expectedOptions); - assert.deepStrictEqual(response, [expectedResponse]); - assert( - (client.locationsClient.getLocation as SinonStub) - .getCall(0) - .calledWith(request, expectedOptions, undefined) - ); - }); - it('invokes getLocation without error using callback', async () => { - const client = new firestoreadminModule.FirestoreAdminClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.initialize(); - const request = generateSampleMessage( - new LocationProtos.google.cloud.location.GetLocationRequest() - ); - request.name = ''; - const expectedHeaderRequestParams = 'name='; - const expectedOptions = { - otherArgs: { - headers: { - 'x-goog-request-params': expectedHeaderRequestParams, - }, - }, - }; - const expectedResponse = generateSampleMessage( - new LocationProtos.google.cloud.location.Location() - ); - client.locationsClient.getLocation = sinon - .stub() - .callsArgWith(2, null, expectedResponse); - const promise = new Promise((resolve, reject) => { - client.getLocation( - request, - expectedOptions, - ( - err?: Error | null, - result?: LocationProtos.google.cloud.location.ILocation | null - ) => { - if (err) { - reject(err); - } else { - resolve(result); + it('invokes listFieldsStream without error', async () => { + const client = new firestoreadminModule.FirestoreAdminClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.firestore.admin.v1.ListFieldsRequest() + ); + const defaultValue1 = + getTypeDefaultValue('.google.firestore.admin.v1.ListFieldsRequest', ['parent']); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; + const expectedResponse = [ + generateSampleMessage(new protos.google.firestore.admin.v1.Field()), + generateSampleMessage(new protos.google.firestore.admin.v1.Field()), + generateSampleMessage(new protos.google.firestore.admin.v1.Field()), + ]; + client.descriptors.page.listFields.createStream = stubPageStreamingCall(expectedResponse); + const stream = client.listFieldsStream(request); + const promise = new Promise((resolve, reject) => { + const responses: protos.google.firestore.admin.v1.Field[] = []; + stream.on('data', (response: protos.google.firestore.admin.v1.Field) => { + responses.push(response); + }); + stream.on('end', () => { + resolve(responses); + }); + stream.on('error', (err: Error) => { + reject(err); + }); + }); + const responses = await promise; + assert.deepStrictEqual(responses, expectedResponse); + assert((client.descriptors.page.listFields.createStream as SinonStub) + .getCall(0).calledWith(client.innerApiCalls.listFields, request)); + assert( + (client.descriptors.page.listFields.createStream as SinonStub) + .getCall(0).args[2].otherArgs.headers['x-goog-request-params'].includes( + expectedHeaderRequestParams + ) + ); + }); + + it('invokes listFieldsStream with error', async () => { + const client = new firestoreadminModule.FirestoreAdminClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.firestore.admin.v1.ListFieldsRequest() + ); + const defaultValue1 = + getTypeDefaultValue('.google.firestore.admin.v1.ListFieldsRequest', ['parent']); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; + const expectedError = new Error('expected'); + client.descriptors.page.listFields.createStream = stubPageStreamingCall(undefined, expectedError); + const stream = client.listFieldsStream(request); + const promise = new Promise((resolve, reject) => { + const responses: protos.google.firestore.admin.v1.Field[] = []; + stream.on('data', (response: protos.google.firestore.admin.v1.Field) => { + responses.push(response); + }); + stream.on('end', () => { + resolve(responses); + }); + stream.on('error', (err: Error) => { + reject(err); + }); + }); + await assert.rejects(promise, expectedError); + assert((client.descriptors.page.listFields.createStream as SinonStub) + .getCall(0).calledWith(client.innerApiCalls.listFields, request)); + assert( + (client.descriptors.page.listFields.createStream as SinonStub) + .getCall(0).args[2].otherArgs.headers['x-goog-request-params'].includes( + expectedHeaderRequestParams + ) + ); + }); + + it('uses async iteration with listFields without error', async () => { + const client = new firestoreadminModule.FirestoreAdminClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.firestore.admin.v1.ListFieldsRequest() + ); + const defaultValue1 = + getTypeDefaultValue('.google.firestore.admin.v1.ListFieldsRequest', ['parent']); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; + const expectedResponse = [ + generateSampleMessage(new protos.google.firestore.admin.v1.Field()), + generateSampleMessage(new protos.google.firestore.admin.v1.Field()), + generateSampleMessage(new protos.google.firestore.admin.v1.Field()), + ]; + client.descriptors.page.listFields.asyncIterate = stubAsyncIterationCall(expectedResponse); + const responses: protos.google.firestore.admin.v1.IField[] = []; + const iterable = client.listFieldsAsync(request); + for await (const resource of iterable) { + responses.push(resource!); } - } - ); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - assert((client.locationsClient.getLocation as SinonStub).getCall(0)); - }); - it('invokes getLocation with error', async () => { - const client = new firestoreadminModule.FirestoreAdminClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.initialize(); - const request = generateSampleMessage( - new LocationProtos.google.cloud.location.GetLocationRequest() - ); - request.name = ''; - const expectedHeaderRequestParams = 'name='; - const expectedOptions = { - otherArgs: { - headers: { - 'x-goog-request-params': expectedHeaderRequestParams, - }, - }, - }; - const expectedError = new Error('expected'); - client.locationsClient.getLocation = stubSimpleCall( - undefined, - expectedError - ); - await assert.rejects( - client.getLocation(request, expectedOptions), - expectedError - ); - assert( - (client.locationsClient.getLocation as SinonStub) - .getCall(0) - .calledWith(request, expectedOptions, undefined) - ); - }); - }); - describe('listLocationsAsync', () => { - it('uses async iteration with listLocations without error', async () => { - const client = new firestoreadminModule.FirestoreAdminClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.initialize(); - const request = generateSampleMessage( - new LocationProtos.google.cloud.location.ListLocationsRequest() - ); - request.name = ''; - const expectedHeaderRequestParams = 'name='; - const expectedResponse = [ - generateSampleMessage( - new LocationProtos.google.cloud.location.Location() - ), - generateSampleMessage( - new LocationProtos.google.cloud.location.Location() - ), - generateSampleMessage( - new LocationProtos.google.cloud.location.Location() - ), - ]; - client.locationsClient.descriptors.page.listLocations.asyncIterate = - stubAsyncIterationCall(expectedResponse); - const responses: LocationProtos.google.cloud.location.ILocation[] = []; - const iterable = client.listLocationsAsync(request); - for await (const resource of iterable) { - responses.push(resource!); - } - assert.deepStrictEqual(responses, expectedResponse); - assert.deepStrictEqual( - ( - client.locationsClient.descriptors.page.listLocations - .asyncIterate as SinonStub - ).getCall(0).args[1], - request - ); - assert( - ( - client.locationsClient.descriptors.page.listLocations - .asyncIterate as SinonStub - ) - .getCall(0) - .args[2].otherArgs.headers['x-goog-request-params'].includes( - expectedHeaderRequestParams - ) - ); - }); - it('uses async iteration with listLocations with error', async () => { - const client = new firestoreadminModule.FirestoreAdminClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.initialize(); - const request = generateSampleMessage( - new LocationProtos.google.cloud.location.ListLocationsRequest() - ); - request.name = ''; - const expectedHeaderRequestParams = 'name='; - const expectedError = new Error('expected'); - client.locationsClient.descriptors.page.listLocations.asyncIterate = - stubAsyncIterationCall(undefined, expectedError); - const iterable = client.listLocationsAsync(request); - await assert.rejects(async () => { - const responses: LocationProtos.google.cloud.location.ILocation[] = []; - for await (const resource of iterable) { - responses.push(resource!); - } - }); - assert.deepStrictEqual( - ( - client.locationsClient.descriptors.page.listLocations - .asyncIterate as SinonStub - ).getCall(0).args[1], - request - ); - assert( - ( - client.locationsClient.descriptors.page.listLocations - .asyncIterate as SinonStub - ) - .getCall(0) - .args[2].otherArgs.headers['x-goog-request-params'].includes( - expectedHeaderRequestParams - ) - ); + assert.deepStrictEqual(responses, expectedResponse); + assert.deepStrictEqual( + (client.descriptors.page.listFields.asyncIterate as SinonStub) + .getCall(0).args[1], request); + assert( + (client.descriptors.page.listFields.asyncIterate as SinonStub) + .getCall(0).args[2].otherArgs.headers['x-goog-request-params'].includes( + expectedHeaderRequestParams + ) + ); + }); + + it('uses async iteration with listFields with error', async () => { + const client = new firestoreadminModule.FirestoreAdminClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.firestore.admin.v1.ListFieldsRequest() + ); + const defaultValue1 = + getTypeDefaultValue('.google.firestore.admin.v1.ListFieldsRequest', ['parent']); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; + const expectedError = new Error('expected'); + client.descriptors.page.listFields.asyncIterate = stubAsyncIterationCall(undefined, expectedError); + const iterable = client.listFieldsAsync(request); + await assert.rejects(async () => { + const responses: protos.google.firestore.admin.v1.IField[] = []; + for await (const resource of iterable) { + responses.push(resource!); + } + }); + assert.deepStrictEqual( + (client.descriptors.page.listFields.asyncIterate as SinonStub) + .getCall(0).args[1], request); + assert( + (client.descriptors.page.listFields.asyncIterate as SinonStub) + .getCall(0).args[2].otherArgs.headers['x-goog-request-params'].includes( + expectedHeaderRequestParams + ) + ); + }); }); - }); - describe('getOperation', () => { - it('invokes getOperation without error', async () => { - const client = new firestoreadminModule.FirestoreAdminClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.initialize(); - const request = generateSampleMessage( - new operationsProtos.google.longrunning.GetOperationRequest() - ); - const expectedResponse = generateSampleMessage( - new operationsProtos.google.longrunning.Operation() - ); - client.operationsClient.getOperation = stubSimpleCall(expectedResponse); - const response = await client.getOperation(request); - assert.deepStrictEqual(response, [expectedResponse]); - assert( - (client.operationsClient.getOperation as SinonStub) - .getCall(0) - .calledWith(request) - ); + describe('getLocation', () => { + it('invokes getLocation without error', async () => { + const client = new firestoreadminModule.FirestoreAdminClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new LocationProtos.google.cloud.location.GetLocationRequest() + ); + request.name = ''; + const expectedHeaderRequestParams = 'name='; + const expectedOptions = { + otherArgs: { + headers: { + 'x-goog-request-params': expectedHeaderRequestParams, + }, + }, + }; + const expectedResponse = generateSampleMessage( + new LocationProtos.google.cloud.location.Location() + ); + client.locationsClient.getLocation = stubSimpleCall(expectedResponse); + const response = await client.getLocation(request, expectedOptions); + assert.deepStrictEqual(response, [expectedResponse]); + assert((client.locationsClient.getLocation as SinonStub) + .getCall(0).calledWith(request, expectedOptions, undefined)); + }); + it('invokes getLocation without error using callback', async () => { + const client = new firestoreadminModule.FirestoreAdminClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new LocationProtos.google.cloud.location.GetLocationRequest() + ); + request.name = ''; + const expectedHeaderRequestParams = 'name='; + const expectedOptions = { + otherArgs: { + headers: { + 'x-goog-request-params': expectedHeaderRequestParams, + }, + }, + }; + const expectedResponse = generateSampleMessage( + new LocationProtos.google.cloud.location.Location() + ); + client.locationsClient.getLocation = sinon.stub().callsArgWith(2, null, expectedResponse); + const promise = new Promise((resolve, reject) => { + client.getLocation( + request, + expectedOptions, + ( + err?: Error | null, + result?: LocationProtos.google.cloud.location.ILocation | null + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + assert((client.locationsClient.getLocation as SinonStub) + .getCall(0)); + }); + it('invokes getLocation with error', async () => { + const client = new firestoreadminModule.FirestoreAdminClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new LocationProtos.google.cloud.location.GetLocationRequest() + ); + request.name = ''; + const expectedHeaderRequestParams = 'name='; + const expectedOptions = { + otherArgs: { + headers: { + 'x-goog-request-params': expectedHeaderRequestParams, + }, + }, + }; + const expectedError = new Error('expected'); + client.locationsClient.getLocation = stubSimpleCall(undefined, expectedError); + await assert.rejects(client.getLocation(request, expectedOptions), expectedError); + assert((client.locationsClient.getLocation as SinonStub) + .getCall(0).calledWith(request, expectedOptions, undefined)); + }); }); - it('invokes getOperation without error using callback', async () => { - const client = new firestoreadminModule.FirestoreAdminClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - const request = generateSampleMessage( - new operationsProtos.google.longrunning.GetOperationRequest() - ); - const expectedResponse = generateSampleMessage( - new operationsProtos.google.longrunning.Operation() - ); - client.operationsClient.getOperation = sinon - .stub() - .callsArgWith(2, null, expectedResponse); - const promise = new Promise((resolve, reject) => { - client.operationsClient.getOperation( - request, - undefined, - ( - err?: Error | null, - result?: operationsProtos.google.longrunning.Operation | null - ) => { - if (err) { - reject(err); - } else { - resolve(result); + describe('listLocationsAsync', () => { + it('uses async iteration with listLocations without error', async () => { + const client = new firestoreadminModule.FirestoreAdminClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new LocationProtos.google.cloud.location.ListLocationsRequest() + ); + request.name = ''; + const expectedHeaderRequestParams = 'name='; + const expectedResponse = [ + generateSampleMessage( + new LocationProtos.google.cloud.location.Location() + ), + generateSampleMessage( + new LocationProtos.google.cloud.location.Location() + ), + generateSampleMessage( + new LocationProtos.google.cloud.location.Location() + ), + ]; + client.locationsClient.descriptors.page.listLocations.asyncIterate = stubAsyncIterationCall(expectedResponse); + const responses: LocationProtos.google.cloud.location.ILocation[] = []; + const iterable = client.listLocationsAsync(request); + for await (const resource of iterable) { + responses.push(resource!); } - } - ); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - assert((client.operationsClient.getOperation as SinonStub).getCall(0)); - }); - it('invokes getOperation with error', async () => { - const client = new firestoreadminModule.FirestoreAdminClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - const request = generateSampleMessage( - new operationsProtos.google.longrunning.GetOperationRequest() - ); - const expectedError = new Error('expected'); - client.operationsClient.getOperation = stubSimpleCall( - undefined, - expectedError - ); - await assert.rejects(async () => { - await client.getOperation(request); - }, expectedError); - assert( - (client.operationsClient.getOperation as SinonStub) - .getCall(0) - .calledWith(request) - ); - }); - }); - describe('cancelOperation', () => { - it('invokes cancelOperation without error', async () => { - const client = new firestoreadminModule.FirestoreAdminClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.initialize(); - const request = generateSampleMessage( - new operationsProtos.google.longrunning.CancelOperationRequest() - ); - const expectedResponse = generateSampleMessage( - new protos.google.protobuf.Empty() - ); - client.operationsClient.cancelOperation = - stubSimpleCall(expectedResponse); - const response = await client.cancelOperation(request); - assert.deepStrictEqual(response, [expectedResponse]); - assert( - (client.operationsClient.cancelOperation as SinonStub) - .getCall(0) - .calledWith(request) - ); + assert.deepStrictEqual(responses, expectedResponse); + assert.deepStrictEqual( + (client.locationsClient.descriptors.page.listLocations.asyncIterate as SinonStub) + .getCall(0).args[1], request); + assert( + (client.locationsClient.descriptors.page.listLocations.asyncIterate as SinonStub) + .getCall(0).args[2].otherArgs.headers['x-goog-request-params'].includes( + expectedHeaderRequestParams + ) + ); + }); + it('uses async iteration with listLocations with error', async () => { + const client = new firestoreadminModule.FirestoreAdminClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new LocationProtos.google.cloud.location.ListLocationsRequest() + ); + request.name = ''; + const expectedHeaderRequestParams = 'name='; + const expectedError = new Error('expected'); + client.locationsClient.descriptors.page.listLocations.asyncIterate = stubAsyncIterationCall(undefined, expectedError); + const iterable = client.listLocationsAsync(request); + await assert.rejects(async () => { + const responses: LocationProtos.google.cloud.location.ILocation[] = []; + for await (const resource of iterable) { + responses.push(resource!); + } + }); + assert.deepStrictEqual( + (client.locationsClient.descriptors.page.listLocations.asyncIterate as SinonStub) + .getCall(0).args[1], request); + assert( + (client.locationsClient.descriptors.page.listLocations.asyncIterate as SinonStub) + .getCall(0).args[2].otherArgs.headers['x-goog-request-params'].includes( + expectedHeaderRequestParams + ) + ); + }); }); - it('invokes cancelOperation without error using callback', async () => { - const client = new firestoreadminModule.FirestoreAdminClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - const request = generateSampleMessage( - new operationsProtos.google.longrunning.CancelOperationRequest() - ); - const expectedResponse = generateSampleMessage( - new protos.google.protobuf.Empty() - ); - client.operationsClient.cancelOperation = sinon - .stub() - .callsArgWith(2, null, expectedResponse); - const promise = new Promise((resolve, reject) => { - client.operationsClient.cancelOperation( - request, - undefined, - ( - err?: Error | null, - result?: protos.google.protobuf.Empty | null - ) => { - if (err) { - reject(err); - } else { - resolve(result); - } - } - ); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - assert((client.operationsClient.cancelOperation as SinonStub).getCall(0)); + describe('getOperation', () => { + it('invokes getOperation without error', async () => { + const client = new firestoreadminModule.FirestoreAdminClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new operationsProtos.google.longrunning.GetOperationRequest() + ); + const expectedResponse = generateSampleMessage( + new operationsProtos.google.longrunning.Operation() + ); + client.operationsClient.getOperation = stubSimpleCall(expectedResponse); + const response = await client.getOperation(request); + assert.deepStrictEqual(response, [expectedResponse]); + assert((client.operationsClient.getOperation as SinonStub) + .getCall(0).calledWith(request) + ); + }); + it('invokes getOperation without error using callback', async () => { + const client = new firestoreadminModule.FirestoreAdminClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + const request = generateSampleMessage( + new operationsProtos.google.longrunning.GetOperationRequest() + ); + const expectedResponse = generateSampleMessage( + new operationsProtos.google.longrunning.Operation() + ); + client.operationsClient.getOperation = sinon.stub().callsArgWith(2, null, expectedResponse); + const promise = new Promise((resolve, reject) => { + client.operationsClient.getOperation( + request, + undefined, + ( + err?: Error | null, + result?: operationsProtos.google.longrunning.Operation | null + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }).catch(err => {throw err}); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + assert((client.operationsClient.getOperation as SinonStub) + .getCall(0)); + }); + it('invokes getOperation with error', async () => { + const client = new firestoreadminModule.FirestoreAdminClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + const request = generateSampleMessage( + new operationsProtos.google.longrunning.GetOperationRequest() + ); + const expectedError = new Error('expected'); + client.operationsClient.getOperation = stubSimpleCall(undefined, expectedError); + await assert.rejects(async () => {await client.getOperation(request)}, expectedError); + assert((client.operationsClient.getOperation as SinonStub) + .getCall(0).calledWith(request)); + }); }); - it('invokes cancelOperation with error', async () => { - const client = new firestoreadminModule.FirestoreAdminClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - const request = generateSampleMessage( - new operationsProtos.google.longrunning.CancelOperationRequest() - ); - const expectedError = new Error('expected'); - client.operationsClient.cancelOperation = stubSimpleCall( - undefined, - expectedError - ); - await assert.rejects(async () => { - await client.cancelOperation(request); - }, expectedError); - assert( - (client.operationsClient.cancelOperation as SinonStub) - .getCall(0) - .calledWith(request) - ); + describe('cancelOperation', () => { + it('invokes cancelOperation without error', async () => { + const client = new firestoreadminModule.FirestoreAdminClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new operationsProtos.google.longrunning.CancelOperationRequest() + ); + const expectedResponse = generateSampleMessage( + new protos.google.protobuf.Empty() + ); + client.operationsClient.cancelOperation = stubSimpleCall(expectedResponse); + const response = await client.cancelOperation(request); + assert.deepStrictEqual(response, [expectedResponse]); + assert((client.operationsClient.cancelOperation as SinonStub) + .getCall(0).calledWith(request) + ); + }); + it('invokes cancelOperation without error using callback', async () => { + const client = new firestoreadminModule.FirestoreAdminClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + const request = generateSampleMessage( + new operationsProtos.google.longrunning.CancelOperationRequest() + ); + const expectedResponse = generateSampleMessage( + new protos.google.protobuf.Empty() + ); + client.operationsClient.cancelOperation = sinon.stub().callsArgWith(2, null, expectedResponse); + const promise = new Promise((resolve, reject) => { + client.operationsClient.cancelOperation( + request, + undefined, + ( + err?: Error | null, + result?: protos.google.protobuf.Empty | null + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }).catch(err => {throw err}); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + assert((client.operationsClient.cancelOperation as SinonStub) + .getCall(0)); + }); + it('invokes cancelOperation with error', async () => { + const client = new firestoreadminModule.FirestoreAdminClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + const request = generateSampleMessage( + new operationsProtos.google.longrunning.CancelOperationRequest() + ); + const expectedError = new Error('expected'); + client.operationsClient.cancelOperation = stubSimpleCall(undefined, expectedError); + await assert.rejects(async () => {await client.cancelOperation(request)}, expectedError); + assert((client.operationsClient.cancelOperation as SinonStub) + .getCall(0).calledWith(request)); + }); }); - }); - describe('deleteOperation', () => { - it('invokes deleteOperation without error', async () => { - const client = new firestoreadminModule.FirestoreAdminClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.initialize(); - const request = generateSampleMessage( - new operationsProtos.google.longrunning.DeleteOperationRequest() - ); - const expectedResponse = generateSampleMessage( - new protos.google.protobuf.Empty() - ); - client.operationsClient.deleteOperation = - stubSimpleCall(expectedResponse); - const response = await client.deleteOperation(request); - assert.deepStrictEqual(response, [expectedResponse]); - assert( - (client.operationsClient.deleteOperation as SinonStub) - .getCall(0) - .calledWith(request) - ); + describe('deleteOperation', () => { + it('invokes deleteOperation without error', async () => { + const client = new firestoreadminModule.FirestoreAdminClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new operationsProtos.google.longrunning.DeleteOperationRequest() + ); + const expectedResponse = generateSampleMessage( + new protos.google.protobuf.Empty() + ); + client.operationsClient.deleteOperation = stubSimpleCall(expectedResponse); + const response = await client.deleteOperation(request); + assert.deepStrictEqual(response, [expectedResponse]); + assert((client.operationsClient.deleteOperation as SinonStub) + .getCall(0).calledWith(request) + ); + }); + it('invokes deleteOperation without error using callback', async () => { + const client = new firestoreadminModule.FirestoreAdminClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + const request = generateSampleMessage( + new operationsProtos.google.longrunning.DeleteOperationRequest() + ); + const expectedResponse = generateSampleMessage( + new protos.google.protobuf.Empty() + ); + client.operationsClient.deleteOperation = sinon.stub().callsArgWith(2, null, expectedResponse); + const promise = new Promise((resolve, reject) => { + client.operationsClient.deleteOperation( + request, + undefined, + ( + err?: Error | null, + result?: protos.google.protobuf.Empty | null + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }).catch(err => {throw err}); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + assert((client.operationsClient.deleteOperation as SinonStub) + .getCall(0)); + }); + it('invokes deleteOperation with error', async () => { + const client = new firestoreadminModule.FirestoreAdminClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + const request = generateSampleMessage( + new operationsProtos.google.longrunning.DeleteOperationRequest() + ); + const expectedError = new Error('expected'); + client.operationsClient.deleteOperation = stubSimpleCall(undefined, expectedError); + await assert.rejects(async () => {await client.deleteOperation(request)}, expectedError); + assert((client.operationsClient.deleteOperation as SinonStub) + .getCall(0).calledWith(request)); + }); }); - it('invokes deleteOperation without error using callback', async () => { - const client = new firestoreadminModule.FirestoreAdminClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - const request = generateSampleMessage( - new operationsProtos.google.longrunning.DeleteOperationRequest() - ); - const expectedResponse = generateSampleMessage( - new protos.google.protobuf.Empty() - ); - client.operationsClient.deleteOperation = sinon - .stub() - .callsArgWith(2, null, expectedResponse); - const promise = new Promise((resolve, reject) => { - client.operationsClient.deleteOperation( - request, - undefined, - ( - err?: Error | null, - result?: protos.google.protobuf.Empty | null - ) => { - if (err) { - reject(err); - } else { - resolve(result); + describe('listOperationsAsync', () => { + it('uses async iteration with listOperations without error', async () => { + const client = new firestoreadminModule.FirestoreAdminClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + const request = generateSampleMessage( + new operationsProtos.google.longrunning.ListOperationsRequest() + ); + const expectedResponse = [ + generateSampleMessage( + new operationsProtos.google.longrunning.ListOperationsResponse() + ), + generateSampleMessage( + new operationsProtos.google.longrunning.ListOperationsResponse() + ), + generateSampleMessage( + new operationsProtos.google.longrunning.ListOperationsResponse() + ), + ]; + client.operationsClient.descriptor.listOperations.asyncIterate = stubAsyncIterationCall(expectedResponse); + const responses: operationsProtos.google.longrunning.IOperation[] = []; + const iterable = client.operationsClient.listOperationsAsync(request); + for await (const resource of iterable) { + responses.push(resource!); } - } - ); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - assert((client.operationsClient.deleteOperation as SinonStub).getCall(0)); - }); - it('invokes deleteOperation with error', async () => { - const client = new firestoreadminModule.FirestoreAdminClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - const request = generateSampleMessage( - new operationsProtos.google.longrunning.DeleteOperationRequest() - ); - const expectedError = new Error('expected'); - client.operationsClient.deleteOperation = stubSimpleCall( - undefined, - expectedError - ); - await assert.rejects(async () => { - await client.deleteOperation(request); - }, expectedError); - assert( - (client.operationsClient.deleteOperation as SinonStub) - .getCall(0) - .calledWith(request) - ); - }); - }); - describe('listOperationsAsync', () => { - it('uses async iteration with listOperations without error', async () => { - const client = new firestoreadminModule.FirestoreAdminClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - const request = generateSampleMessage( - new operationsProtos.google.longrunning.ListOperationsRequest() - ); - const expectedResponse = [ - generateSampleMessage( - new operationsProtos.google.longrunning.ListOperationsResponse() - ), - generateSampleMessage( - new operationsProtos.google.longrunning.ListOperationsResponse() - ), - generateSampleMessage( - new operationsProtos.google.longrunning.ListOperationsResponse() - ), - ]; - client.operationsClient.descriptor.listOperations.asyncIterate = - stubAsyncIterationCall(expectedResponse); - const responses: operationsProtos.google.longrunning.ListOperationsResponse[] = - []; - const iterable = client.operationsClient.listOperationsAsync(request); - for await (const resource of iterable) { - responses.push(resource!); - } - assert.deepStrictEqual(responses, expectedResponse); - assert.deepStrictEqual( - ( - client.operationsClient.descriptor.listOperations - .asyncIterate as SinonStub - ).getCall(0).args[1], - request - ); - }); - it('uses async iteration with listOperations with error', async () => { - const client = new firestoreadminModule.FirestoreAdminClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.initialize(); - const request = generateSampleMessage( - new operationsProtos.google.longrunning.ListOperationsRequest() - ); - const expectedError = new Error('expected'); - client.operationsClient.descriptor.listOperations.asyncIterate = - stubAsyncIterationCall(undefined, expectedError); - const iterable = client.operationsClient.listOperationsAsync(request); - await assert.rejects(async () => { - const responses: operationsProtos.google.longrunning.ListOperationsResponse[] = - []; - for await (const resource of iterable) { - responses.push(resource!); - } - }); - assert.deepStrictEqual( - ( - client.operationsClient.descriptor.listOperations - .asyncIterate as SinonStub - ).getCall(0).args[1], - request - ); - }); - }); - - describe('Path templates', () => { - describe('backup', () => { - const fakePath = '/rendered/path/backup'; - const expectedParameters = { - project: 'projectValue', - location: 'locationValue', - backup: 'backupValue', - }; - const client = new firestoreadminModule.FirestoreAdminClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.initialize(); - client.pathTemplates.backupPathTemplate.render = sinon - .stub() - .returns(fakePath); - client.pathTemplates.backupPathTemplate.match = sinon - .stub() - .returns(expectedParameters); - - it('backupPath', () => { - const result = client.backupPath( - 'projectValue', - 'locationValue', - 'backupValue' - ); - assert.strictEqual(result, fakePath); - assert( - (client.pathTemplates.backupPathTemplate.render as SinonStub) - .getCall(-1) - .calledWith(expectedParameters) - ); - }); - - it('matchProjectFromBackupName', () => { - const result = client.matchProjectFromBackupName(fakePath); - assert.strictEqual(result, 'projectValue'); - assert( - (client.pathTemplates.backupPathTemplate.match as SinonStub) - .getCall(-1) - .calledWith(fakePath) - ); - }); - - it('matchLocationFromBackupName', () => { - const result = client.matchLocationFromBackupName(fakePath); - assert.strictEqual(result, 'locationValue'); - assert( - (client.pathTemplates.backupPathTemplate.match as SinonStub) - .getCall(-1) - .calledWith(fakePath) - ); - }); - - it('matchBackupFromBackupName', () => { - const result = client.matchBackupFromBackupName(fakePath); - assert.strictEqual(result, 'backupValue'); - assert( - (client.pathTemplates.backupPathTemplate.match as SinonStub) - .getCall(-1) - .calledWith(fakePath) - ); - }); + assert.deepStrictEqual(responses, expectedResponse); + assert.deepStrictEqual( + (client.operationsClient.descriptor.listOperations.asyncIterate as SinonStub) + .getCall(0).args[1], request); + }); + it('uses async iteration with listOperations with error', async () => { + const client = new firestoreadminModule.FirestoreAdminClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new operationsProtos.google.longrunning.ListOperationsRequest() + ); + const expectedError = new Error('expected'); + client.operationsClient.descriptor.listOperations.asyncIterate = stubAsyncIterationCall(undefined, expectedError); + const iterable = client.operationsClient.listOperationsAsync(request); + await assert.rejects(async () => { + const responses: operationsProtos.google.longrunning.IOperation[] = []; + for await (const resource of iterable) { + responses.push(resource!); + } + }); + assert.deepStrictEqual( + (client.operationsClient.descriptor.listOperations.asyncIterate as SinonStub) + .getCall(0).args[1], request); + }); }); - describe('backupSchedule', () => { - const fakePath = '/rendered/path/backupSchedule'; - const expectedParameters = { - project: 'projectValue', - database: 'databaseValue', - backup_schedule: 'backupScheduleValue', - }; - const client = new firestoreadminModule.FirestoreAdminClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.initialize(); - client.pathTemplates.backupSchedulePathTemplate.render = sinon - .stub() - .returns(fakePath); - client.pathTemplates.backupSchedulePathTemplate.match = sinon - .stub() - .returns(expectedParameters); - - it('backupSchedulePath', () => { - const result = client.backupSchedulePath( - 'projectValue', - 'databaseValue', - 'backupScheduleValue' - ); - assert.strictEqual(result, fakePath); - assert( - (client.pathTemplates.backupSchedulePathTemplate.render as SinonStub) - .getCall(-1) - .calledWith(expectedParameters) - ); - }); - - it('matchProjectFromBackupScheduleName', () => { - const result = client.matchProjectFromBackupScheduleName(fakePath); - assert.strictEqual(result, 'projectValue'); - assert( - (client.pathTemplates.backupSchedulePathTemplate.match as SinonStub) - .getCall(-1) - .calledWith(fakePath) - ); - }); - - it('matchDatabaseFromBackupScheduleName', () => { - const result = client.matchDatabaseFromBackupScheduleName(fakePath); - assert.strictEqual(result, 'databaseValue'); - assert( - (client.pathTemplates.backupSchedulePathTemplate.match as SinonStub) - .getCall(-1) - .calledWith(fakePath) - ); - }); - - it('matchBackupScheduleFromBackupScheduleName', () => { - const result = - client.matchBackupScheduleFromBackupScheduleName(fakePath); - assert.strictEqual(result, 'backupScheduleValue'); - assert( - (client.pathTemplates.backupSchedulePathTemplate.match as SinonStub) - .getCall(-1) - .calledWith(fakePath) - ); - }); - }); + describe('Path templates', () => { + + describe('backup', async () => { + const fakePath = "/rendered/path/backup"; + const expectedParameters = { + project: "projectValue", + location: "locationValue", + backup: "backupValue", + }; + const client = new firestoreadminModule.FirestoreAdminClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + client.pathTemplates.backupPathTemplate.render = + sinon.stub().returns(fakePath); + client.pathTemplates.backupPathTemplate.match = + sinon.stub().returns(expectedParameters); + + it('backupPath', () => { + const result = client.backupPath("projectValue", "locationValue", "backupValue"); + assert.strictEqual(result, fakePath); + assert((client.pathTemplates.backupPathTemplate.render as SinonStub) + .getCall(-1).calledWith(expectedParameters)); + }); + + it('matchProjectFromBackupName', () => { + const result = client.matchProjectFromBackupName(fakePath); + assert.strictEqual(result, "projectValue"); + assert((client.pathTemplates.backupPathTemplate.match as SinonStub) + .getCall(-1).calledWith(fakePath)); + }); + + it('matchLocationFromBackupName', () => { + const result = client.matchLocationFromBackupName(fakePath); + assert.strictEqual(result, "locationValue"); + assert((client.pathTemplates.backupPathTemplate.match as SinonStub) + .getCall(-1).calledWith(fakePath)); + }); + + it('matchBackupFromBackupName', () => { + const result = client.matchBackupFromBackupName(fakePath); + assert.strictEqual(result, "backupValue"); + assert((client.pathTemplates.backupPathTemplate.match as SinonStub) + .getCall(-1).calledWith(fakePath)); + }); + }); - describe('collectionGroup', () => { - const fakePath = '/rendered/path/collectionGroup'; - const expectedParameters = { - project: 'projectValue', - database: 'databaseValue', - collection: 'collectionValue', - }; - const client = new firestoreadminModule.FirestoreAdminClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.initialize(); - client.pathTemplates.collectionGroupPathTemplate.render = sinon - .stub() - .returns(fakePath); - client.pathTemplates.collectionGroupPathTemplate.match = sinon - .stub() - .returns(expectedParameters); - - it('collectionGroupPath', () => { - const result = client.collectionGroupPath( - 'projectValue', - 'databaseValue', - 'collectionValue' - ); - assert.strictEqual(result, fakePath); - assert( - (client.pathTemplates.collectionGroupPathTemplate.render as SinonStub) - .getCall(-1) - .calledWith(expectedParameters) - ); - }); - - it('matchProjectFromCollectionGroupName', () => { - const result = client.matchProjectFromCollectionGroupName(fakePath); - assert.strictEqual(result, 'projectValue'); - assert( - (client.pathTemplates.collectionGroupPathTemplate.match as SinonStub) - .getCall(-1) - .calledWith(fakePath) - ); - }); - - it('matchDatabaseFromCollectionGroupName', () => { - const result = client.matchDatabaseFromCollectionGroupName(fakePath); - assert.strictEqual(result, 'databaseValue'); - assert( - (client.pathTemplates.collectionGroupPathTemplate.match as SinonStub) - .getCall(-1) - .calledWith(fakePath) - ); - }); - - it('matchCollectionFromCollectionGroupName', () => { - const result = client.matchCollectionFromCollectionGroupName(fakePath); - assert.strictEqual(result, 'collectionValue'); - assert( - (client.pathTemplates.collectionGroupPathTemplate.match as SinonStub) - .getCall(-1) - .calledWith(fakePath) - ); - }); - }); + describe('backupSchedule', async () => { + const fakePath = "/rendered/path/backupSchedule"; + const expectedParameters = { + project: "projectValue", + database: "databaseValue", + backup_schedule: "backupScheduleValue", + }; + const client = new firestoreadminModule.FirestoreAdminClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + client.pathTemplates.backupSchedulePathTemplate.render = + sinon.stub().returns(fakePath); + client.pathTemplates.backupSchedulePathTemplate.match = + sinon.stub().returns(expectedParameters); + + it('backupSchedulePath', () => { + const result = client.backupSchedulePath("projectValue", "databaseValue", "backupScheduleValue"); + assert.strictEqual(result, fakePath); + assert((client.pathTemplates.backupSchedulePathTemplate.render as SinonStub) + .getCall(-1).calledWith(expectedParameters)); + }); + + it('matchProjectFromBackupScheduleName', () => { + const result = client.matchProjectFromBackupScheduleName(fakePath); + assert.strictEqual(result, "projectValue"); + assert((client.pathTemplates.backupSchedulePathTemplate.match as SinonStub) + .getCall(-1).calledWith(fakePath)); + }); + + it('matchDatabaseFromBackupScheduleName', () => { + const result = client.matchDatabaseFromBackupScheduleName(fakePath); + assert.strictEqual(result, "databaseValue"); + assert((client.pathTemplates.backupSchedulePathTemplate.match as SinonStub) + .getCall(-1).calledWith(fakePath)); + }); + + it('matchBackupScheduleFromBackupScheduleName', () => { + const result = client.matchBackupScheduleFromBackupScheduleName(fakePath); + assert.strictEqual(result, "backupScheduleValue"); + assert((client.pathTemplates.backupSchedulePathTemplate.match as SinonStub) + .getCall(-1).calledWith(fakePath)); + }); + }); - describe('database', () => { - const fakePath = '/rendered/path/database'; - const expectedParameters = { - project: 'projectValue', - database: 'databaseValue', - }; - const client = new firestoreadminModule.FirestoreAdminClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.initialize(); - client.pathTemplates.databasePathTemplate.render = sinon - .stub() - .returns(fakePath); - client.pathTemplates.databasePathTemplate.match = sinon - .stub() - .returns(expectedParameters); - - it('databasePath', () => { - const result = client.databasePath('projectValue', 'databaseValue'); - assert.strictEqual(result, fakePath); - assert( - (client.pathTemplates.databasePathTemplate.render as SinonStub) - .getCall(-1) - .calledWith(expectedParameters) - ); - }); - - it('matchProjectFromDatabaseName', () => { - const result = client.matchProjectFromDatabaseName(fakePath); - assert.strictEqual(result, 'projectValue'); - assert( - (client.pathTemplates.databasePathTemplate.match as SinonStub) - .getCall(-1) - .calledWith(fakePath) - ); - }); - - it('matchDatabaseFromDatabaseName', () => { - const result = client.matchDatabaseFromDatabaseName(fakePath); - assert.strictEqual(result, 'databaseValue'); - assert( - (client.pathTemplates.databasePathTemplate.match as SinonStub) - .getCall(-1) - .calledWith(fakePath) - ); - }); - }); + describe('collectionGroup', async () => { + const fakePath = "/rendered/path/collectionGroup"; + const expectedParameters = { + project: "projectValue", + database: "databaseValue", + collection: "collectionValue", + }; + const client = new firestoreadminModule.FirestoreAdminClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + client.pathTemplates.collectionGroupPathTemplate.render = + sinon.stub().returns(fakePath); + client.pathTemplates.collectionGroupPathTemplate.match = + sinon.stub().returns(expectedParameters); + + it('collectionGroupPath', () => { + const result = client.collectionGroupPath("projectValue", "databaseValue", "collectionValue"); + assert.strictEqual(result, fakePath); + assert((client.pathTemplates.collectionGroupPathTemplate.render as SinonStub) + .getCall(-1).calledWith(expectedParameters)); + }); + + it('matchProjectFromCollectionGroupName', () => { + const result = client.matchProjectFromCollectionGroupName(fakePath); + assert.strictEqual(result, "projectValue"); + assert((client.pathTemplates.collectionGroupPathTemplate.match as SinonStub) + .getCall(-1).calledWith(fakePath)); + }); + + it('matchDatabaseFromCollectionGroupName', () => { + const result = client.matchDatabaseFromCollectionGroupName(fakePath); + assert.strictEqual(result, "databaseValue"); + assert((client.pathTemplates.collectionGroupPathTemplate.match as SinonStub) + .getCall(-1).calledWith(fakePath)); + }); + + it('matchCollectionFromCollectionGroupName', () => { + const result = client.matchCollectionFromCollectionGroupName(fakePath); + assert.strictEqual(result, "collectionValue"); + assert((client.pathTemplates.collectionGroupPathTemplate.match as SinonStub) + .getCall(-1).calledWith(fakePath)); + }); + }); - describe('field', () => { - const fakePath = '/rendered/path/field'; - const expectedParameters = { - project: 'projectValue', - database: 'databaseValue', - collection: 'collectionValue', - field: 'fieldValue', - }; - const client = new firestoreadminModule.FirestoreAdminClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.initialize(); - client.pathTemplates.fieldPathTemplate.render = sinon - .stub() - .returns(fakePath); - client.pathTemplates.fieldPathTemplate.match = sinon - .stub() - .returns(expectedParameters); - - it('fieldPath', () => { - const result = client.fieldPath( - 'projectValue', - 'databaseValue', - 'collectionValue', - 'fieldValue' - ); - assert.strictEqual(result, fakePath); - assert( - (client.pathTemplates.fieldPathTemplate.render as SinonStub) - .getCall(-1) - .calledWith(expectedParameters) - ); - }); - - it('matchProjectFromFieldName', () => { - const result = client.matchProjectFromFieldName(fakePath); - assert.strictEqual(result, 'projectValue'); - assert( - (client.pathTemplates.fieldPathTemplate.match as SinonStub) - .getCall(-1) - .calledWith(fakePath) - ); - }); - - it('matchDatabaseFromFieldName', () => { - const result = client.matchDatabaseFromFieldName(fakePath); - assert.strictEqual(result, 'databaseValue'); - assert( - (client.pathTemplates.fieldPathTemplate.match as SinonStub) - .getCall(-1) - .calledWith(fakePath) - ); - }); - - it('matchCollectionFromFieldName', () => { - const result = client.matchCollectionFromFieldName(fakePath); - assert.strictEqual(result, 'collectionValue'); - assert( - (client.pathTemplates.fieldPathTemplate.match as SinonStub) - .getCall(-1) - .calledWith(fakePath) - ); - }); - - it('matchFieldFromFieldName', () => { - const result = client.matchFieldFromFieldName(fakePath); - assert.strictEqual(result, 'fieldValue'); - assert( - (client.pathTemplates.fieldPathTemplate.match as SinonStub) - .getCall(-1) - .calledWith(fakePath) - ); - }); - }); + describe('database', async () => { + const fakePath = "/rendered/path/database"; + const expectedParameters = { + project: "projectValue", + database: "databaseValue", + }; + const client = new firestoreadminModule.FirestoreAdminClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + client.pathTemplates.databasePathTemplate.render = + sinon.stub().returns(fakePath); + client.pathTemplates.databasePathTemplate.match = + sinon.stub().returns(expectedParameters); + + it('databasePath', () => { + const result = client.databasePath("projectValue", "databaseValue"); + assert.strictEqual(result, fakePath); + assert((client.pathTemplates.databasePathTemplate.render as SinonStub) + .getCall(-1).calledWith(expectedParameters)); + }); + + it('matchProjectFromDatabaseName', () => { + const result = client.matchProjectFromDatabaseName(fakePath); + assert.strictEqual(result, "projectValue"); + assert((client.pathTemplates.databasePathTemplate.match as SinonStub) + .getCall(-1).calledWith(fakePath)); + }); + + it('matchDatabaseFromDatabaseName', () => { + const result = client.matchDatabaseFromDatabaseName(fakePath); + assert.strictEqual(result, "databaseValue"); + assert((client.pathTemplates.databasePathTemplate.match as SinonStub) + .getCall(-1).calledWith(fakePath)); + }); + }); - describe('index', () => { - const fakePath = '/rendered/path/index'; - const expectedParameters = { - project: 'projectValue', - database: 'databaseValue', - collection: 'collectionValue', - index: 'indexValue', - }; - const client = new firestoreadminModule.FirestoreAdminClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.initialize(); - client.pathTemplates.indexPathTemplate.render = sinon - .stub() - .returns(fakePath); - client.pathTemplates.indexPathTemplate.match = sinon - .stub() - .returns(expectedParameters); - - it('indexPath', () => { - const result = client.indexPath( - 'projectValue', - 'databaseValue', - 'collectionValue', - 'indexValue' - ); - assert.strictEqual(result, fakePath); - assert( - (client.pathTemplates.indexPathTemplate.render as SinonStub) - .getCall(-1) - .calledWith(expectedParameters) - ); - }); - - it('matchProjectFromIndexName', () => { - const result = client.matchProjectFromIndexName(fakePath); - assert.strictEqual(result, 'projectValue'); - assert( - (client.pathTemplates.indexPathTemplate.match as SinonStub) - .getCall(-1) - .calledWith(fakePath) - ); - }); - - it('matchDatabaseFromIndexName', () => { - const result = client.matchDatabaseFromIndexName(fakePath); - assert.strictEqual(result, 'databaseValue'); - assert( - (client.pathTemplates.indexPathTemplate.match as SinonStub) - .getCall(-1) - .calledWith(fakePath) - ); - }); - - it('matchCollectionFromIndexName', () => { - const result = client.matchCollectionFromIndexName(fakePath); - assert.strictEqual(result, 'collectionValue'); - assert( - (client.pathTemplates.indexPathTemplate.match as SinonStub) - .getCall(-1) - .calledWith(fakePath) - ); - }); - - it('matchIndexFromIndexName', () => { - const result = client.matchIndexFromIndexName(fakePath); - assert.strictEqual(result, 'indexValue'); - assert( - (client.pathTemplates.indexPathTemplate.match as SinonStub) - .getCall(-1) - .calledWith(fakePath) - ); - }); - }); + describe('field', async () => { + const fakePath = "/rendered/path/field"; + const expectedParameters = { + project: "projectValue", + database: "databaseValue", + collection: "collectionValue", + field: "fieldValue", + }; + const client = new firestoreadminModule.FirestoreAdminClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + client.pathTemplates.fieldPathTemplate.render = + sinon.stub().returns(fakePath); + client.pathTemplates.fieldPathTemplate.match = + sinon.stub().returns(expectedParameters); + + it('fieldPath', () => { + const result = client.fieldPath("projectValue", "databaseValue", "collectionValue", "fieldValue"); + assert.strictEqual(result, fakePath); + assert((client.pathTemplates.fieldPathTemplate.render as SinonStub) + .getCall(-1).calledWith(expectedParameters)); + }); + + it('matchProjectFromFieldName', () => { + const result = client.matchProjectFromFieldName(fakePath); + assert.strictEqual(result, "projectValue"); + assert((client.pathTemplates.fieldPathTemplate.match as SinonStub) + .getCall(-1).calledWith(fakePath)); + }); + + it('matchDatabaseFromFieldName', () => { + const result = client.matchDatabaseFromFieldName(fakePath); + assert.strictEqual(result, "databaseValue"); + assert((client.pathTemplates.fieldPathTemplate.match as SinonStub) + .getCall(-1).calledWith(fakePath)); + }); + + it('matchCollectionFromFieldName', () => { + const result = client.matchCollectionFromFieldName(fakePath); + assert.strictEqual(result, "collectionValue"); + assert((client.pathTemplates.fieldPathTemplate.match as SinonStub) + .getCall(-1).calledWith(fakePath)); + }); + + it('matchFieldFromFieldName', () => { + const result = client.matchFieldFromFieldName(fakePath); + assert.strictEqual(result, "fieldValue"); + assert((client.pathTemplates.fieldPathTemplate.match as SinonStub) + .getCall(-1).calledWith(fakePath)); + }); + }); - describe('location', () => { - const fakePath = '/rendered/path/location'; - const expectedParameters = { - project: 'projectValue', - location: 'locationValue', - }; - const client = new firestoreadminModule.FirestoreAdminClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.initialize(); - client.pathTemplates.locationPathTemplate.render = sinon - .stub() - .returns(fakePath); - client.pathTemplates.locationPathTemplate.match = sinon - .stub() - .returns(expectedParameters); - - it('locationPath', () => { - const result = client.locationPath('projectValue', 'locationValue'); - assert.strictEqual(result, fakePath); - assert( - (client.pathTemplates.locationPathTemplate.render as SinonStub) - .getCall(-1) - .calledWith(expectedParameters) - ); - }); - - it('matchProjectFromLocationName', () => { - const result = client.matchProjectFromLocationName(fakePath); - assert.strictEqual(result, 'projectValue'); - assert( - (client.pathTemplates.locationPathTemplate.match as SinonStub) - .getCall(-1) - .calledWith(fakePath) - ); - }); - - it('matchLocationFromLocationName', () => { - const result = client.matchLocationFromLocationName(fakePath); - assert.strictEqual(result, 'locationValue'); - assert( - (client.pathTemplates.locationPathTemplate.match as SinonStub) - .getCall(-1) - .calledWith(fakePath) - ); - }); - }); + describe('index', async () => { + const fakePath = "/rendered/path/index"; + const expectedParameters = { + project: "projectValue", + database: "databaseValue", + collection: "collectionValue", + index: "indexValue", + }; + const client = new firestoreadminModule.FirestoreAdminClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + client.pathTemplates.indexPathTemplate.render = + sinon.stub().returns(fakePath); + client.pathTemplates.indexPathTemplate.match = + sinon.stub().returns(expectedParameters); + + it('indexPath', () => { + const result = client.indexPath("projectValue", "databaseValue", "collectionValue", "indexValue"); + assert.strictEqual(result, fakePath); + assert((client.pathTemplates.indexPathTemplate.render as SinonStub) + .getCall(-1).calledWith(expectedParameters)); + }); + + it('matchProjectFromIndexName', () => { + const result = client.matchProjectFromIndexName(fakePath); + assert.strictEqual(result, "projectValue"); + assert((client.pathTemplates.indexPathTemplate.match as SinonStub) + .getCall(-1).calledWith(fakePath)); + }); + + it('matchDatabaseFromIndexName', () => { + const result = client.matchDatabaseFromIndexName(fakePath); + assert.strictEqual(result, "databaseValue"); + assert((client.pathTemplates.indexPathTemplate.match as SinonStub) + .getCall(-1).calledWith(fakePath)); + }); + + it('matchCollectionFromIndexName', () => { + const result = client.matchCollectionFromIndexName(fakePath); + assert.strictEqual(result, "collectionValue"); + assert((client.pathTemplates.indexPathTemplate.match as SinonStub) + .getCall(-1).calledWith(fakePath)); + }); + + it('matchIndexFromIndexName', () => { + const result = client.matchIndexFromIndexName(fakePath); + assert.strictEqual(result, "indexValue"); + assert((client.pathTemplates.indexPathTemplate.match as SinonStub) + .getCall(-1).calledWith(fakePath)); + }); + }); + + describe('location', async () => { + const fakePath = "/rendered/path/location"; + const expectedParameters = { + project: "projectValue", + location: "locationValue", + }; + const client = new firestoreadminModule.FirestoreAdminClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + client.pathTemplates.locationPathTemplate.render = + sinon.stub().returns(fakePath); + client.pathTemplates.locationPathTemplate.match = + sinon.stub().returns(expectedParameters); + + it('locationPath', () => { + const result = client.locationPath("projectValue", "locationValue"); + assert.strictEqual(result, fakePath); + assert((client.pathTemplates.locationPathTemplate.render as SinonStub) + .getCall(-1).calledWith(expectedParameters)); + }); + + it('matchProjectFromLocationName', () => { + const result = client.matchProjectFromLocationName(fakePath); + assert.strictEqual(result, "projectValue"); + assert((client.pathTemplates.locationPathTemplate.match as SinonStub) + .getCall(-1).calledWith(fakePath)); + }); + + it('matchLocationFromLocationName', () => { + const result = client.matchLocationFromLocationName(fakePath); + assert.strictEqual(result, "locationValue"); + assert((client.pathTemplates.locationPathTemplate.match as SinonStub) + .getCall(-1).calledWith(fakePath)); + }); + }); - describe('project', () => { - const fakePath = '/rendered/path/project'; - const expectedParameters = { - project: 'projectValue', - }; - const client = new firestoreadminModule.FirestoreAdminClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.initialize(); - client.pathTemplates.projectPathTemplate.render = sinon - .stub() - .returns(fakePath); - client.pathTemplates.projectPathTemplate.match = sinon - .stub() - .returns(expectedParameters); - - it('projectPath', () => { - const result = client.projectPath('projectValue'); - assert.strictEqual(result, fakePath); - assert( - (client.pathTemplates.projectPathTemplate.render as SinonStub) - .getCall(-1) - .calledWith(expectedParameters) - ); - }); - - it('matchProjectFromProjectName', () => { - const result = client.matchProjectFromProjectName(fakePath); - assert.strictEqual(result, 'projectValue'); - assert( - (client.pathTemplates.projectPathTemplate.match as SinonStub) - .getCall(-1) - .calledWith(fakePath) - ); - }); + describe('project', async () => { + const fakePath = "/rendered/path/project"; + const expectedParameters = { + project: "projectValue", + }; + const client = new firestoreadminModule.FirestoreAdminClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + client.pathTemplates.projectPathTemplate.render = + sinon.stub().returns(fakePath); + client.pathTemplates.projectPathTemplate.match = + sinon.stub().returns(expectedParameters); + + it('projectPath', () => { + const result = client.projectPath("projectValue"); + assert.strictEqual(result, fakePath); + assert((client.pathTemplates.projectPathTemplate.render as SinonStub) + .getCall(-1).calledWith(expectedParameters)); + }); + + it('matchProjectFromProjectName', () => { + const result = client.matchProjectFromProjectName(fakePath); + assert.strictEqual(result, "projectValue"); + assert((client.pathTemplates.projectPathTemplate.match as SinonStub) + .getCall(-1).calledWith(fakePath)); + }); + }); + + describe('userCreds', async () => { + const fakePath = "/rendered/path/userCreds"; + const expectedParameters = { + project: "projectValue", + database: "databaseValue", + user_creds: "userCredsValue", + }; + const client = new firestoreadminModule.FirestoreAdminClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + client.pathTemplates.userCredsPathTemplate.render = + sinon.stub().returns(fakePath); + client.pathTemplates.userCredsPathTemplate.match = + sinon.stub().returns(expectedParameters); + + it('userCredsPath', () => { + const result = client.userCredsPath("projectValue", "databaseValue", "userCredsValue"); + assert.strictEqual(result, fakePath); + assert((client.pathTemplates.userCredsPathTemplate.render as SinonStub) + .getCall(-1).calledWith(expectedParameters)); + }); + + it('matchProjectFromUserCredsName', () => { + const result = client.matchProjectFromUserCredsName(fakePath); + assert.strictEqual(result, "projectValue"); + assert((client.pathTemplates.userCredsPathTemplate.match as SinonStub) + .getCall(-1).calledWith(fakePath)); + }); + + it('matchDatabaseFromUserCredsName', () => { + const result = client.matchDatabaseFromUserCredsName(fakePath); + assert.strictEqual(result, "databaseValue"); + assert((client.pathTemplates.userCredsPathTemplate.match as SinonStub) + .getCall(-1).calledWith(fakePath)); + }); + + it('matchUserCredsFromUserCredsName', () => { + const result = client.matchUserCredsFromUserCredsName(fakePath); + assert.strictEqual(result, "userCredsValue"); + assert((client.pathTemplates.userCredsPathTemplate.match as SinonStub) + .getCall(-1).calledWith(fakePath)); + }); + }); }); - }); }); diff --git a/dev/test/gapic_firestore_v1.ts b/dev/test/gapic_firestore_v1.ts index 0f00db1a6..78879baf3 100644 --- a/dev/test/gapic_firestore_v1.ts +++ b/dev/test/gapic_firestore_v1.ts @@ -33,3144 +33,2720 @@ const root = protobuf.Root.fromJSON(require('../protos/v1.json')).resolveAll(); // eslint-disable-next-line @typescript-eslint/no-unused-vars function getTypeDefaultValue(typeName: string, fields: string[]) { - let type = root.lookupType(typeName) as protobuf.Type; - for (const field of fields.slice(0, -1)) { - type = type.fields[field]?.resolvedType as protobuf.Type; - } - return type.fields[fields[fields.length - 1]]?.defaultValue; + let type = root.lookupType(typeName) as protobuf.Type; + for (const field of fields.slice(0, -1)) { + type = type.fields[field]?.resolvedType as protobuf.Type; + } + return type.fields[fields[fields.length - 1]]?.defaultValue; } function generateSampleMessage(instance: T) { - const filledObject = ( - instance.constructor as typeof protobuf.Message - ).toObject(instance as protobuf.Message, {defaults: true}); - return (instance.constructor as typeof protobuf.Message).fromObject( - filledObject - ) as T; + const filledObject = (instance.constructor as typeof protobuf.Message) + .toObject(instance as protobuf.Message, {defaults: true}); + return (instance.constructor as typeof protobuf.Message).fromObject(filledObject) as T; } function stubSimpleCall(response?: ResponseType, error?: Error) { - return error - ? sinon.stub().rejects(error) - : sinon.stub().resolves([response]); + return error ? sinon.stub().rejects(error) : sinon.stub().resolves([response]); } -function stubSimpleCallWithCallback( - response?: ResponseType, - error?: Error -) { - return error - ? sinon.stub().callsArgWith(2, error) - : sinon.stub().callsArgWith(2, null, response); +function stubSimpleCallWithCallback(response?: ResponseType, error?: Error) { + return error ? sinon.stub().callsArgWith(2, error) : sinon.stub().callsArgWith(2, null, response); } -function stubServerStreamingCall( - response?: ResponseType, - error?: Error -) { - const transformStub = error - ? sinon.stub().callsArgWith(2, error) - : sinon.stub().callsArgWith(2, null, response); - const mockStream = new PassThrough({ - objectMode: true, - transform: transformStub, - }); - // write something to the stream to trigger transformStub and send the response back to the client - setImmediate(() => { - mockStream.write({}); - }); - setImmediate(() => { - mockStream.end(); - }); - return sinon.stub().returns(mockStream); +function stubServerStreamingCall(response?: ResponseType, error?: Error) { + const transformStub = error ? sinon.stub().callsArgWith(2, error) : sinon.stub().callsArgWith(2, null, response); + const mockStream = new PassThrough({ + objectMode: true, + transform: transformStub, + }); + // write something to the stream to trigger transformStub and send the response back to the client + setImmediate(() => { mockStream.write({}); }); + setImmediate(() => { mockStream.end(); }); + return sinon.stub().returns(mockStream); } -function stubBidiStreamingCall( - response?: ResponseType, - error?: Error -) { - const transformStub = error - ? sinon.stub().callsArgWith(2, error) - : sinon.stub().callsArgWith(2, null, response); - const mockStream = new PassThrough({ - objectMode: true, - transform: transformStub, - }); - return sinon.stub().returns(mockStream); +function stubBidiStreamingCall(response?: ResponseType, error?: Error) { + const transformStub = error ? sinon.stub().callsArgWith(2, error) : sinon.stub().callsArgWith(2, null, response); + const mockStream = new PassThrough({ + objectMode: true, + transform: transformStub, + }); + return sinon.stub().returns(mockStream); } -function stubPageStreamingCall( - responses?: ResponseType[], - error?: Error -) { - const pagingStub = sinon.stub(); - if (responses) { - for (let i = 0; i < responses.length; ++i) { - pagingStub.onCall(i).callsArgWith(2, null, responses[i]); +function stubPageStreamingCall(responses?: ResponseType[], error?: Error) { + const pagingStub = sinon.stub(); + if (responses) { + for (let i = 0; i < responses.length; ++i) { + pagingStub.onCall(i).callsArgWith(2, null, responses[i]); + } } - } - const transformStub = error - ? sinon.stub().callsArgWith(2, error) - : pagingStub; - const mockStream = new PassThrough({ - objectMode: true, - transform: transformStub, - }); - // trigger as many responses as needed - if (responses) { - for (let i = 0; i < responses.length; ++i) { - setImmediate(() => { - mockStream.write({}); - }); + const transformStub = error ? sinon.stub().callsArgWith(2, error) : pagingStub; + const mockStream = new PassThrough({ + objectMode: true, + transform: transformStub, + }); + // trigger as many responses as needed + if (responses) { + for (let i = 0; i < responses.length; ++i) { + setImmediate(() => { mockStream.write({}); }); + } + setImmediate(() => { mockStream.end(); }); + } else { + setImmediate(() => { mockStream.write({}); }); + setImmediate(() => { mockStream.end(); }); } - setImmediate(() => { - mockStream.end(); - }); - } else { - setImmediate(() => { - mockStream.write({}); - }); - setImmediate(() => { - mockStream.end(); - }); - } - return sinon.stub().returns(mockStream); + return sinon.stub().returns(mockStream); } -function stubAsyncIterationCall( - responses?: ResponseType[], - error?: Error -) { - let counter = 0; - const asyncIterable = { - [Symbol.asyncIterator]() { - return { - async next() { - if (error) { - return Promise.reject(error); - } - if (counter >= responses!.length) { - return Promise.resolve({done: true, value: undefined}); - } - return Promise.resolve({done: false, value: responses![counter++]}); - }, - }; - }, - }; - return sinon.stub().returns(asyncIterable); +function stubAsyncIterationCall(responses?: ResponseType[], error?: Error) { + let counter = 0; + const asyncIterable = { + [Symbol.asyncIterator]() { + return { + async next() { + if (error) { + return Promise.reject(error); + } + if (counter >= responses!.length) { + return Promise.resolve({done: true, value: undefined}); + } + return Promise.resolve({done: false, value: responses![counter++]}); + } + }; + } + }; + return sinon.stub().returns(asyncIterable); } describe('v1.FirestoreClient', () => { - describe('Common methods', () => { - it('has apiEndpoint', () => { - const client = new firestoreModule.FirestoreClient(); - const apiEndpoint = client.apiEndpoint; - assert.strictEqual(apiEndpoint, 'firestore.googleapis.com'); - }); + describe('Common methods', () => { + it('has apiEndpoint', () => { + const client = new firestoreModule.FirestoreClient(); + const apiEndpoint = client.apiEndpoint; + assert.strictEqual(apiEndpoint, 'firestore.googleapis.com'); + }); - it('has universeDomain', () => { - const client = new firestoreModule.FirestoreClient(); - const universeDomain = client.universeDomain; - assert.strictEqual(universeDomain, 'googleapis.com'); - }); + it('has universeDomain', () => { + const client = new firestoreModule.FirestoreClient(); + const universeDomain = client.universeDomain; + assert.strictEqual(universeDomain, "googleapis.com"); + }); - if ( - typeof process === 'object' && - typeof process.emitWarning === 'function' - ) { - it('throws DeprecationWarning if static servicePath is used', () => { - const stub = sinon.stub(process, 'emitWarning'); - const servicePath = firestoreModule.FirestoreClient.servicePath; - assert.strictEqual(servicePath, 'firestore.googleapis.com'); - assert(stub.called); - stub.restore(); - }); - - it('throws DeprecationWarning if static apiEndpoint is used', () => { - const stub = sinon.stub(process, 'emitWarning'); - const apiEndpoint = firestoreModule.FirestoreClient.apiEndpoint; - assert.strictEqual(apiEndpoint, 'firestore.googleapis.com'); - assert(stub.called); - stub.restore(); - }); - } - it('sets apiEndpoint according to universe domain camelCase', () => { - const client = new firestoreModule.FirestoreClient({ - universeDomain: 'example.com', - }); - const servicePath = client.apiEndpoint; - assert.strictEqual(servicePath, 'firestore.example.com'); - }); + if (typeof process === 'object' && typeof process.emitWarning === 'function') { + it('throws DeprecationWarning if static servicePath is used', () => { + const stub = sinon.stub(process, 'emitWarning'); + const servicePath = firestoreModule.FirestoreClient.servicePath; + assert.strictEqual(servicePath, 'firestore.googleapis.com'); + assert(stub.called); + stub.restore(); + }); + + it('throws DeprecationWarning if static apiEndpoint is used', () => { + const stub = sinon.stub(process, 'emitWarning'); + const apiEndpoint = firestoreModule.FirestoreClient.apiEndpoint; + assert.strictEqual(apiEndpoint, 'firestore.googleapis.com'); + assert(stub.called); + stub.restore(); + }); + } + it('sets apiEndpoint according to universe domain camelCase', () => { + const client = new firestoreModule.FirestoreClient({universeDomain: 'example.com'}); + const servicePath = client.apiEndpoint; + assert.strictEqual(servicePath, 'firestore.example.com'); + }); - it('sets apiEndpoint according to universe domain snakeCase', () => { - const client = new firestoreModule.FirestoreClient({ - universe_domain: 'example.com', - }); - const servicePath = client.apiEndpoint; - assert.strictEqual(servicePath, 'firestore.example.com'); - }); + it('sets apiEndpoint according to universe domain snakeCase', () => { + const client = new firestoreModule.FirestoreClient({universe_domain: 'example.com'}); + const servicePath = client.apiEndpoint; + assert.strictEqual(servicePath, 'firestore.example.com'); + }); - if (typeof process === 'object' && 'env' in process) { - describe('GOOGLE_CLOUD_UNIVERSE_DOMAIN environment variable', () => { - it('sets apiEndpoint from environment variable', () => { - const saved = process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN']; - process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] = 'example.com'; - const client = new firestoreModule.FirestoreClient(); - const servicePath = client.apiEndpoint; - assert.strictEqual(servicePath, 'firestore.example.com'); - if (saved) { - process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] = saved; - } else { - delete process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN']; - } - }); - - it('value configured in code has priority over environment variable', () => { - const saved = process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN']; - process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] = 'example.com'; - const client = new firestoreModule.FirestoreClient({ - universeDomain: 'configured.example.com', - }); - const servicePath = client.apiEndpoint; - assert.strictEqual(servicePath, 'firestore.configured.example.com'); - if (saved) { - process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] = saved; - } else { - delete process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN']; - } - }); - }); - } - it('does not allow setting both universeDomain and universe_domain', () => { - assert.throws(() => { - new firestoreModule.FirestoreClient({ - universe_domain: 'example.com', - universeDomain: 'example.net', + if (typeof process === 'object' && 'env' in process) { + describe('GOOGLE_CLOUD_UNIVERSE_DOMAIN environment variable', () => { + it('sets apiEndpoint from environment variable', () => { + const saved = process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN']; + process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] = 'example.com'; + const client = new firestoreModule.FirestoreClient(); + const servicePath = client.apiEndpoint; + assert.strictEqual(servicePath, 'firestore.example.com'); + if (saved) { + process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] = saved; + } else { + delete process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN']; + } + }); + + it('value configured in code has priority over environment variable', () => { + const saved = process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN']; + process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] = 'example.com'; + const client = new firestoreModule.FirestoreClient({universeDomain: 'configured.example.com'}); + const servicePath = client.apiEndpoint; + assert.strictEqual(servicePath, 'firestore.configured.example.com'); + if (saved) { + process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] = saved; + } else { + delete process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN']; + } + }); + }); + } + it('does not allow setting both universeDomain and universe_domain', () => { + assert.throws(() => { new firestoreModule.FirestoreClient({universe_domain: 'example.com', universeDomain: 'example.net'}); }); }); - }); - }); - it('has port', () => { - const port = firestoreModule.FirestoreClient.port; - assert(port); - assert(typeof port === 'number'); - }); + it('has port', () => { + const port = firestoreModule.FirestoreClient.port; + assert(port); + assert(typeof port === 'number'); + }); - it('should create a client with no option', () => { - const client = new firestoreModule.FirestoreClient(); - assert(client); - }); + it('should create a client with no option', () => { + const client = new firestoreModule.FirestoreClient(); + assert(client); + }); - it('should create a client with gRPC fallback', () => { - const client = new firestoreModule.FirestoreClient({ - fallback: true, - }); - assert(client); - }); + it('should create a client with gRPC fallback', () => { + const client = new firestoreModule.FirestoreClient({ + fallback: true, + }); + assert(client); + }); - it('has initialize method and supports deferred initialization', async () => { - const client = new firestoreModule.FirestoreClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - assert.strictEqual(client.firestoreStub, undefined); - await client.initialize(); - assert(client.firestoreStub); - }); + it('has initialize method and supports deferred initialization', async () => { + const client = new firestoreModule.FirestoreClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + assert.strictEqual(client.firestoreStub, undefined); + await client.initialize(); + assert(client.firestoreStub); + }); - it('has close method for the initialized client', done => { - const client = new firestoreModule.FirestoreClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.initialize(); - assert(client.firestoreStub); - client.close().then(() => { - done(); - }); - }); + it('has close method for the initialized client', done => { + const client = new firestoreModule.FirestoreClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + client.initialize().catch(err => {throw err}); + assert(client.firestoreStub); + client.close().then(() => { + done(); + }).catch(err => {throw err}); + }); - it('has close method for the non-initialized client', done => { - const client = new firestoreModule.FirestoreClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - assert.strictEqual(client.firestoreStub, undefined); - client.close().then(() => { - done(); - }); - }); + it('has close method for the non-initialized client', done => { + const client = new firestoreModule.FirestoreClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + assert.strictEqual(client.firestoreStub, undefined); + client.close().then(() => { + done(); + }).catch(err => {throw err}); + }); - it('has getProjectId method', async () => { - const fakeProjectId = 'fake-project-id'; - const client = new firestoreModule.FirestoreClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.auth.getProjectId = sinon.stub().resolves(fakeProjectId); - const result = await client.getProjectId(); - assert.strictEqual(result, fakeProjectId); - assert((client.auth.getProjectId as SinonStub).calledWithExactly()); - }); + it('has getProjectId method', async () => { + const fakeProjectId = 'fake-project-id'; + const client = new firestoreModule.FirestoreClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + client.auth.getProjectId = sinon.stub().resolves(fakeProjectId); + const result = await client.getProjectId(); + assert.strictEqual(result, fakeProjectId); + assert((client.auth.getProjectId as SinonStub).calledWithExactly()); + }); - it('has getProjectId method with callback', async () => { - const fakeProjectId = 'fake-project-id'; - const client = new firestoreModule.FirestoreClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.auth.getProjectId = sinon - .stub() - .callsArgWith(0, null, fakeProjectId); - const promise = new Promise((resolve, reject) => { - client.getProjectId((err?: Error | null, projectId?: string | null) => { - if (err) { - reject(err); - } else { - resolve(projectId); - } - }); - }); - const result = await promise; - assert.strictEqual(result, fakeProjectId); - }); - }); - - describe('getDocument', () => { - it('invokes getDocument without error', async () => { - const client = new firestoreModule.FirestoreClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.initialize(); - const request = generateSampleMessage( - new protos.google.firestore.v1.GetDocumentRequest() - ); - const defaultValue1 = getTypeDefaultValue( - '.google.firestore.v1.GetDocumentRequest', - ['name'] - ); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; - const expectedResponse = generateSampleMessage( - new protos.google.firestore.v1.Document() - ); - client.innerApiCalls.getDocument = stubSimpleCall(expectedResponse); - const [response] = await client.getDocument(request); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = ( - client.innerApiCalls.getDocument as SinonStub - ).getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = ( - client.innerApiCalls.getDocument as SinonStub - ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + it('has getProjectId method with callback', async () => { + const fakeProjectId = 'fake-project-id'; + const client = new firestoreModule.FirestoreClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + client.auth.getProjectId = sinon.stub().callsArgWith(0, null, fakeProjectId); + const promise = new Promise((resolve, reject) => { + client.getProjectId((err?: Error|null, projectId?: string|null) => { + if (err) { + reject(err); + } else { + resolve(projectId); + } + }); + }); + const result = await promise; + assert.strictEqual(result, fakeProjectId); + }); }); - it('invokes getDocument without error using callback', async () => { - const client = new firestoreModule.FirestoreClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.initialize(); - const request = generateSampleMessage( - new protos.google.firestore.v1.GetDocumentRequest() - ); - const defaultValue1 = getTypeDefaultValue( - '.google.firestore.v1.GetDocumentRequest', - ['name'] - ); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; - const expectedResponse = generateSampleMessage( - new protos.google.firestore.v1.Document() - ); - client.innerApiCalls.getDocument = - stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.getDocument( - request, - ( - err?: Error | null, - result?: protos.google.firestore.v1.IDocument | null - ) => { - if (err) { - reject(err); - } else { - resolve(result); - } - } - ); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = ( - client.innerApiCalls.getDocument as SinonStub - ).getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = ( - client.innerApiCalls.getDocument as SinonStub - ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + describe('getDocument', () => { + it('invokes getDocument without error', async () => { + const client = new firestoreModule.FirestoreClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.firestore.v1.GetDocumentRequest() + ); + const defaultValue1 = + getTypeDefaultValue('.google.firestore.v1.GetDocumentRequest', ['name']); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; + const expectedResponse = generateSampleMessage( + new protos.google.firestore.v1.Document() + ); + client.innerApiCalls.getDocument = stubSimpleCall(expectedResponse); + const [response] = await client.getDocument(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = (client.innerApiCalls.getDocument as SinonStub) + .getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = (client.innerApiCalls.getDocument as SinonStub) + .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes getDocument with error', async () => { - const client = new firestoreModule.FirestoreClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.initialize(); - const request = generateSampleMessage( - new protos.google.firestore.v1.GetDocumentRequest() - ); - const defaultValue1 = getTypeDefaultValue( - '.google.firestore.v1.GetDocumentRequest', - ['name'] - ); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; - const expectedError = new Error('expected'); - client.innerApiCalls.getDocument = stubSimpleCall( - undefined, - expectedError - ); - await assert.rejects(client.getDocument(request), expectedError); - const actualRequest = ( - client.innerApiCalls.getDocument as SinonStub - ).getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = ( - client.innerApiCalls.getDocument as SinonStub - ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes getDocument without error using callback', async () => { + const client = new firestoreModule.FirestoreClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.firestore.v1.GetDocumentRequest() + ); + const defaultValue1 = + getTypeDefaultValue('.google.firestore.v1.GetDocumentRequest', ['name']); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; + const expectedResponse = generateSampleMessage( + new protos.google.firestore.v1.Document() + ); + client.innerApiCalls.getDocument = stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.getDocument( + request, + (err?: Error|null, result?: protos.google.firestore.v1.IDocument|null) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = (client.innerApiCalls.getDocument as SinonStub) + .getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = (client.innerApiCalls.getDocument as SinonStub) + .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes getDocument with closed client', async () => { - const client = new firestoreModule.FirestoreClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.initialize(); - const request = generateSampleMessage( - new protos.google.firestore.v1.GetDocumentRequest() - ); - const defaultValue1 = getTypeDefaultValue( - '.google.firestore.v1.GetDocumentRequest', - ['name'] - ); - request.name = defaultValue1; - const expectedError = new Error('The client has already been closed.'); - client.close(); - await assert.rejects(client.getDocument(request), expectedError); - }); - }); - - describe('updateDocument', () => { - it('invokes updateDocument without error', async () => { - const client = new firestoreModule.FirestoreClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.initialize(); - const request = generateSampleMessage( - new protos.google.firestore.v1.UpdateDocumentRequest() - ); - request.document ??= {}; - const defaultValue1 = getTypeDefaultValue( - '.google.firestore.v1.UpdateDocumentRequest', - ['document', 'name'] - ); - request.document.name = defaultValue1; - const expectedHeaderRequestParams = `document.name=${defaultValue1 ?? ''}`; - const expectedResponse = generateSampleMessage( - new protos.google.firestore.v1.Document() - ); - client.innerApiCalls.updateDocument = stubSimpleCall(expectedResponse); - const [response] = await client.updateDocument(request); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = ( - client.innerApiCalls.updateDocument as SinonStub - ).getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = ( - client.innerApiCalls.updateDocument as SinonStub - ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes getDocument with error', async () => { + const client = new firestoreModule.FirestoreClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.firestore.v1.GetDocumentRequest() + ); + const defaultValue1 = + getTypeDefaultValue('.google.firestore.v1.GetDocumentRequest', ['name']); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; + const expectedError = new Error('expected'); + client.innerApiCalls.getDocument = stubSimpleCall(undefined, expectedError); + await assert.rejects(client.getDocument(request), expectedError); + const actualRequest = (client.innerApiCalls.getDocument as SinonStub) + .getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = (client.innerApiCalls.getDocument as SinonStub) + .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes updateDocument without error using callback', async () => { - const client = new firestoreModule.FirestoreClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.initialize(); - const request = generateSampleMessage( - new protos.google.firestore.v1.UpdateDocumentRequest() - ); - request.document ??= {}; - const defaultValue1 = getTypeDefaultValue( - '.google.firestore.v1.UpdateDocumentRequest', - ['document', 'name'] - ); - request.document.name = defaultValue1; - const expectedHeaderRequestParams = `document.name=${defaultValue1 ?? ''}`; - const expectedResponse = generateSampleMessage( - new protos.google.firestore.v1.Document() - ); - client.innerApiCalls.updateDocument = - stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.updateDocument( - request, - ( - err?: Error | null, - result?: protos.google.firestore.v1.IDocument | null - ) => { - if (err) { - reject(err); - } else { - resolve(result); - } - } - ); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = ( - client.innerApiCalls.updateDocument as SinonStub - ).getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = ( - client.innerApiCalls.updateDocument as SinonStub - ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + it('invokes getDocument with closed client', async () => { + const client = new firestoreModule.FirestoreClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.firestore.v1.GetDocumentRequest() + ); + const defaultValue1 = + getTypeDefaultValue('.google.firestore.v1.GetDocumentRequest', ['name']); + request.name = defaultValue1; + const expectedError = new Error('The client has already been closed.'); + client.close().catch(err => {throw err}); + await assert.rejects(client.getDocument(request), expectedError); + }); }); - it('invokes updateDocument with error', async () => { - const client = new firestoreModule.FirestoreClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.initialize(); - const request = generateSampleMessage( - new protos.google.firestore.v1.UpdateDocumentRequest() - ); - request.document ??= {}; - const defaultValue1 = getTypeDefaultValue( - '.google.firestore.v1.UpdateDocumentRequest', - ['document', 'name'] - ); - request.document.name = defaultValue1; - const expectedHeaderRequestParams = `document.name=${defaultValue1 ?? ''}`; - const expectedError = new Error('expected'); - client.innerApiCalls.updateDocument = stubSimpleCall( - undefined, - expectedError - ); - await assert.rejects(client.updateDocument(request), expectedError); - const actualRequest = ( - client.innerApiCalls.updateDocument as SinonStub - ).getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = ( - client.innerApiCalls.updateDocument as SinonStub - ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + describe('updateDocument', () => { + it('invokes updateDocument without error', async () => { + const client = new firestoreModule.FirestoreClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.firestore.v1.UpdateDocumentRequest() + ); + request.document ??= {}; + const defaultValue1 = + getTypeDefaultValue('.google.firestore.v1.UpdateDocumentRequest', ['document', 'name']); + request.document.name = defaultValue1; + const expectedHeaderRequestParams = `document.name=${defaultValue1 ?? '' }`; + const expectedResponse = generateSampleMessage( + new protos.google.firestore.v1.Document() + ); + client.innerApiCalls.updateDocument = stubSimpleCall(expectedResponse); + const [response] = await client.updateDocument(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = (client.innerApiCalls.updateDocument as SinonStub) + .getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = (client.innerApiCalls.updateDocument as SinonStub) + .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes updateDocument with closed client', async () => { - const client = new firestoreModule.FirestoreClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.initialize(); - const request = generateSampleMessage( - new protos.google.firestore.v1.UpdateDocumentRequest() - ); - request.document ??= {}; - const defaultValue1 = getTypeDefaultValue( - '.google.firestore.v1.UpdateDocumentRequest', - ['document', 'name'] - ); - request.document.name = defaultValue1; - const expectedError = new Error('The client has already been closed.'); - client.close(); - await assert.rejects(client.updateDocument(request), expectedError); - }); - }); - - describe('deleteDocument', () => { - it('invokes deleteDocument without error', async () => { - const client = new firestoreModule.FirestoreClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.initialize(); - const request = generateSampleMessage( - new protos.google.firestore.v1.DeleteDocumentRequest() - ); - const defaultValue1 = getTypeDefaultValue( - '.google.firestore.v1.DeleteDocumentRequest', - ['name'] - ); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; - const expectedResponse = generateSampleMessage( - new protos.google.protobuf.Empty() - ); - client.innerApiCalls.deleteDocument = stubSimpleCall(expectedResponse); - const [response] = await client.deleteDocument(request); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = ( - client.innerApiCalls.deleteDocument as SinonStub - ).getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = ( - client.innerApiCalls.deleteDocument as SinonStub - ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes updateDocument without error using callback', async () => { + const client = new firestoreModule.FirestoreClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.firestore.v1.UpdateDocumentRequest() + ); + request.document ??= {}; + const defaultValue1 = + getTypeDefaultValue('.google.firestore.v1.UpdateDocumentRequest', ['document', 'name']); + request.document.name = defaultValue1; + const expectedHeaderRequestParams = `document.name=${defaultValue1 ?? '' }`; + const expectedResponse = generateSampleMessage( + new protos.google.firestore.v1.Document() + ); + client.innerApiCalls.updateDocument = stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.updateDocument( + request, + (err?: Error|null, result?: protos.google.firestore.v1.IDocument|null) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = (client.innerApiCalls.updateDocument as SinonStub) + .getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = (client.innerApiCalls.updateDocument as SinonStub) + .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes deleteDocument without error using callback', async () => { - const client = new firestoreModule.FirestoreClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.initialize(); - const request = generateSampleMessage( - new protos.google.firestore.v1.DeleteDocumentRequest() - ); - const defaultValue1 = getTypeDefaultValue( - '.google.firestore.v1.DeleteDocumentRequest', - ['name'] - ); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; - const expectedResponse = generateSampleMessage( - new protos.google.protobuf.Empty() - ); - client.innerApiCalls.deleteDocument = - stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.deleteDocument( - request, - ( - err?: Error | null, - result?: protos.google.protobuf.IEmpty | null - ) => { - if (err) { - reject(err); - } else { - resolve(result); - } - } - ); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = ( - client.innerApiCalls.deleteDocument as SinonStub - ).getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = ( - client.innerApiCalls.deleteDocument as SinonStub - ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes updateDocument with error', async () => { + const client = new firestoreModule.FirestoreClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.firestore.v1.UpdateDocumentRequest() + ); + request.document ??= {}; + const defaultValue1 = + getTypeDefaultValue('.google.firestore.v1.UpdateDocumentRequest', ['document', 'name']); + request.document.name = defaultValue1; + const expectedHeaderRequestParams = `document.name=${defaultValue1 ?? '' }`; + const expectedError = new Error('expected'); + client.innerApiCalls.updateDocument = stubSimpleCall(undefined, expectedError); + await assert.rejects(client.updateDocument(request), expectedError); + const actualRequest = (client.innerApiCalls.updateDocument as SinonStub) + .getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = (client.innerApiCalls.updateDocument as SinonStub) + .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes deleteDocument with error', async () => { - const client = new firestoreModule.FirestoreClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.initialize(); - const request = generateSampleMessage( - new protos.google.firestore.v1.DeleteDocumentRequest() - ); - const defaultValue1 = getTypeDefaultValue( - '.google.firestore.v1.DeleteDocumentRequest', - ['name'] - ); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; - const expectedError = new Error('expected'); - client.innerApiCalls.deleteDocument = stubSimpleCall( - undefined, - expectedError - ); - await assert.rejects(client.deleteDocument(request), expectedError); - const actualRequest = ( - client.innerApiCalls.deleteDocument as SinonStub - ).getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = ( - client.innerApiCalls.deleteDocument as SinonStub - ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + it('invokes updateDocument with closed client', async () => { + const client = new firestoreModule.FirestoreClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.firestore.v1.UpdateDocumentRequest() + ); + request.document ??= {}; + const defaultValue1 = + getTypeDefaultValue('.google.firestore.v1.UpdateDocumentRequest', ['document', 'name']); + request.document.name = defaultValue1; + const expectedError = new Error('The client has already been closed.'); + client.close().catch(err => {throw err}); + await assert.rejects(client.updateDocument(request), expectedError); + }); }); - it('invokes deleteDocument with closed client', async () => { - const client = new firestoreModule.FirestoreClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.initialize(); - const request = generateSampleMessage( - new protos.google.firestore.v1.DeleteDocumentRequest() - ); - const defaultValue1 = getTypeDefaultValue( - '.google.firestore.v1.DeleteDocumentRequest', - ['name'] - ); - request.name = defaultValue1; - const expectedError = new Error('The client has already been closed.'); - client.close(); - await assert.rejects(client.deleteDocument(request), expectedError); - }); - }); - - describe('beginTransaction', () => { - it('invokes beginTransaction without error', async () => { - const client = new firestoreModule.FirestoreClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.initialize(); - const request = generateSampleMessage( - new protos.google.firestore.v1.BeginTransactionRequest() - ); - const defaultValue1 = getTypeDefaultValue( - '.google.firestore.v1.BeginTransactionRequest', - ['database'] - ); - request.database = defaultValue1; - const expectedHeaderRequestParams = `database=${defaultValue1 ?? ''}`; - const expectedResponse = generateSampleMessage( - new protos.google.firestore.v1.BeginTransactionResponse() - ); - client.innerApiCalls.beginTransaction = stubSimpleCall(expectedResponse); - const [response] = await client.beginTransaction(request); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = ( - client.innerApiCalls.beginTransaction as SinonStub - ).getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = ( - client.innerApiCalls.beginTransaction as SinonStub - ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + describe('deleteDocument', () => { + it('invokes deleteDocument without error', async () => { + const client = new firestoreModule.FirestoreClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.firestore.v1.DeleteDocumentRequest() + ); + const defaultValue1 = + getTypeDefaultValue('.google.firestore.v1.DeleteDocumentRequest', ['name']); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; + const expectedResponse = generateSampleMessage( + new protos.google.protobuf.Empty() + ); + client.innerApiCalls.deleteDocument = stubSimpleCall(expectedResponse); + const [response] = await client.deleteDocument(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = (client.innerApiCalls.deleteDocument as SinonStub) + .getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = (client.innerApiCalls.deleteDocument as SinonStub) + .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes beginTransaction without error using callback', async () => { - const client = new firestoreModule.FirestoreClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.initialize(); - const request = generateSampleMessage( - new protos.google.firestore.v1.BeginTransactionRequest() - ); - const defaultValue1 = getTypeDefaultValue( - '.google.firestore.v1.BeginTransactionRequest', - ['database'] - ); - request.database = defaultValue1; - const expectedHeaderRequestParams = `database=${defaultValue1 ?? ''}`; - const expectedResponse = generateSampleMessage( - new protos.google.firestore.v1.BeginTransactionResponse() - ); - client.innerApiCalls.beginTransaction = - stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.beginTransaction( - request, - ( - err?: Error | null, - result?: protos.google.firestore.v1.IBeginTransactionResponse | null - ) => { - if (err) { - reject(err); - } else { - resolve(result); - } - } - ); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = ( - client.innerApiCalls.beginTransaction as SinonStub - ).getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = ( - client.innerApiCalls.beginTransaction as SinonStub - ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes deleteDocument without error using callback', async () => { + const client = new firestoreModule.FirestoreClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.firestore.v1.DeleteDocumentRequest() + ); + const defaultValue1 = + getTypeDefaultValue('.google.firestore.v1.DeleteDocumentRequest', ['name']); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; + const expectedResponse = generateSampleMessage( + new protos.google.protobuf.Empty() + ); + client.innerApiCalls.deleteDocument = stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.deleteDocument( + request, + (err?: Error|null, result?: protos.google.protobuf.IEmpty|null) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = (client.innerApiCalls.deleteDocument as SinonStub) + .getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = (client.innerApiCalls.deleteDocument as SinonStub) + .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes beginTransaction with error', async () => { - const client = new firestoreModule.FirestoreClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.initialize(); - const request = generateSampleMessage( - new protos.google.firestore.v1.BeginTransactionRequest() - ); - const defaultValue1 = getTypeDefaultValue( - '.google.firestore.v1.BeginTransactionRequest', - ['database'] - ); - request.database = defaultValue1; - const expectedHeaderRequestParams = `database=${defaultValue1 ?? ''}`; - const expectedError = new Error('expected'); - client.innerApiCalls.beginTransaction = stubSimpleCall( - undefined, - expectedError - ); - await assert.rejects(client.beginTransaction(request), expectedError); - const actualRequest = ( - client.innerApiCalls.beginTransaction as SinonStub - ).getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = ( - client.innerApiCalls.beginTransaction as SinonStub - ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes deleteDocument with error', async () => { + const client = new firestoreModule.FirestoreClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.firestore.v1.DeleteDocumentRequest() + ); + const defaultValue1 = + getTypeDefaultValue('.google.firestore.v1.DeleteDocumentRequest', ['name']); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; + const expectedError = new Error('expected'); + client.innerApiCalls.deleteDocument = stubSimpleCall(undefined, expectedError); + await assert.rejects(client.deleteDocument(request), expectedError); + const actualRequest = (client.innerApiCalls.deleteDocument as SinonStub) + .getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = (client.innerApiCalls.deleteDocument as SinonStub) + .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes beginTransaction with closed client', async () => { - const client = new firestoreModule.FirestoreClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.initialize(); - const request = generateSampleMessage( - new protos.google.firestore.v1.BeginTransactionRequest() - ); - const defaultValue1 = getTypeDefaultValue( - '.google.firestore.v1.BeginTransactionRequest', - ['database'] - ); - request.database = defaultValue1; - const expectedError = new Error('The client has already been closed.'); - client.close(); - await assert.rejects(client.beginTransaction(request), expectedError); - }); - }); - - describe('commit', () => { - it('invokes commit without error', async () => { - const client = new firestoreModule.FirestoreClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.initialize(); - const request = generateSampleMessage( - new protos.google.firestore.v1.CommitRequest() - ); - const defaultValue1 = getTypeDefaultValue( - '.google.firestore.v1.CommitRequest', - ['database'] - ); - request.database = defaultValue1; - const expectedHeaderRequestParams = `database=${defaultValue1 ?? ''}`; - const expectedResponse = generateSampleMessage( - new protos.google.firestore.v1.CommitResponse() - ); - client.innerApiCalls.commit = stubSimpleCall(expectedResponse); - const [response] = await client.commit(request); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.commit as SinonStub).getCall( - 0 - ).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = ( - client.innerApiCalls.commit as SinonStub - ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + it('invokes deleteDocument with closed client', async () => { + const client = new firestoreModule.FirestoreClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.firestore.v1.DeleteDocumentRequest() + ); + const defaultValue1 = + getTypeDefaultValue('.google.firestore.v1.DeleteDocumentRequest', ['name']); + request.name = defaultValue1; + const expectedError = new Error('The client has already been closed.'); + client.close().catch(err => {throw err}); + await assert.rejects(client.deleteDocument(request), expectedError); + }); }); - it('invokes commit without error using callback', async () => { - const client = new firestoreModule.FirestoreClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.initialize(); - const request = generateSampleMessage( - new protos.google.firestore.v1.CommitRequest() - ); - const defaultValue1 = getTypeDefaultValue( - '.google.firestore.v1.CommitRequest', - ['database'] - ); - request.database = defaultValue1; - const expectedHeaderRequestParams = `database=${defaultValue1 ?? ''}`; - const expectedResponse = generateSampleMessage( - new protos.google.firestore.v1.CommitResponse() - ); - client.innerApiCalls.commit = - stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.commit( - request, - ( - err?: Error | null, - result?: protos.google.firestore.v1.ICommitResponse | null - ) => { - if (err) { - reject(err); - } else { - resolve(result); - } - } - ); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.commit as SinonStub).getCall( - 0 - ).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = ( - client.innerApiCalls.commit as SinonStub - ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + describe('beginTransaction', () => { + it('invokes beginTransaction without error', async () => { + const client = new firestoreModule.FirestoreClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.firestore.v1.BeginTransactionRequest() + ); + const defaultValue1 = + getTypeDefaultValue('.google.firestore.v1.BeginTransactionRequest', ['database']); + request.database = defaultValue1; + const expectedHeaderRequestParams = `database=${defaultValue1 ?? '' }`; + const expectedResponse = generateSampleMessage( + new protos.google.firestore.v1.BeginTransactionResponse() + ); + client.innerApiCalls.beginTransaction = stubSimpleCall(expectedResponse); + const [response] = await client.beginTransaction(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = (client.innerApiCalls.beginTransaction as SinonStub) + .getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = (client.innerApiCalls.beginTransaction as SinonStub) + .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes commit with error', async () => { - const client = new firestoreModule.FirestoreClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.initialize(); - const request = generateSampleMessage( - new protos.google.firestore.v1.CommitRequest() - ); - const defaultValue1 = getTypeDefaultValue( - '.google.firestore.v1.CommitRequest', - ['database'] - ); - request.database = defaultValue1; - const expectedHeaderRequestParams = `database=${defaultValue1 ?? ''}`; - const expectedError = new Error('expected'); - client.innerApiCalls.commit = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.commit(request), expectedError); - const actualRequest = (client.innerApiCalls.commit as SinonStub).getCall( - 0 - ).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = ( - client.innerApiCalls.commit as SinonStub - ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes beginTransaction without error using callback', async () => { + const client = new firestoreModule.FirestoreClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.firestore.v1.BeginTransactionRequest() + ); + const defaultValue1 = + getTypeDefaultValue('.google.firestore.v1.BeginTransactionRequest', ['database']); + request.database = defaultValue1; + const expectedHeaderRequestParams = `database=${defaultValue1 ?? '' }`; + const expectedResponse = generateSampleMessage( + new protos.google.firestore.v1.BeginTransactionResponse() + ); + client.innerApiCalls.beginTransaction = stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.beginTransaction( + request, + (err?: Error|null, result?: protos.google.firestore.v1.IBeginTransactionResponse|null) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = (client.innerApiCalls.beginTransaction as SinonStub) + .getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = (client.innerApiCalls.beginTransaction as SinonStub) + .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes commit with closed client', async () => { - const client = new firestoreModule.FirestoreClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.initialize(); - const request = generateSampleMessage( - new protos.google.firestore.v1.CommitRequest() - ); - const defaultValue1 = getTypeDefaultValue( - '.google.firestore.v1.CommitRequest', - ['database'] - ); - request.database = defaultValue1; - const expectedError = new Error('The client has already been closed.'); - client.close(); - await assert.rejects(client.commit(request), expectedError); - }); - }); - - describe('rollback', () => { - it('invokes rollback without error', async () => { - const client = new firestoreModule.FirestoreClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.initialize(); - const request = generateSampleMessage( - new protos.google.firestore.v1.RollbackRequest() - ); - const defaultValue1 = getTypeDefaultValue( - '.google.firestore.v1.RollbackRequest', - ['database'] - ); - request.database = defaultValue1; - const expectedHeaderRequestParams = `database=${defaultValue1 ?? ''}`; - const expectedResponse = generateSampleMessage( - new protos.google.protobuf.Empty() - ); - client.innerApiCalls.rollback = stubSimpleCall(expectedResponse); - const [response] = await client.rollback(request); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = ( - client.innerApiCalls.rollback as SinonStub - ).getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = ( - client.innerApiCalls.rollback as SinonStub - ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes beginTransaction with error', async () => { + const client = new firestoreModule.FirestoreClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.firestore.v1.BeginTransactionRequest() + ); + const defaultValue1 = + getTypeDefaultValue('.google.firestore.v1.BeginTransactionRequest', ['database']); + request.database = defaultValue1; + const expectedHeaderRequestParams = `database=${defaultValue1 ?? '' }`; + const expectedError = new Error('expected'); + client.innerApiCalls.beginTransaction = stubSimpleCall(undefined, expectedError); + await assert.rejects(client.beginTransaction(request), expectedError); + const actualRequest = (client.innerApiCalls.beginTransaction as SinonStub) + .getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = (client.innerApiCalls.beginTransaction as SinonStub) + .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes rollback without error using callback', async () => { - const client = new firestoreModule.FirestoreClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.initialize(); - const request = generateSampleMessage( - new protos.google.firestore.v1.RollbackRequest() - ); - const defaultValue1 = getTypeDefaultValue( - '.google.firestore.v1.RollbackRequest', - ['database'] - ); - request.database = defaultValue1; - const expectedHeaderRequestParams = `database=${defaultValue1 ?? ''}`; - const expectedResponse = generateSampleMessage( - new protos.google.protobuf.Empty() - ); - client.innerApiCalls.rollback = - stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.rollback( - request, - ( - err?: Error | null, - result?: protos.google.protobuf.IEmpty | null - ) => { - if (err) { - reject(err); - } else { - resolve(result); - } - } - ); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = ( - client.innerApiCalls.rollback as SinonStub - ).getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = ( - client.innerApiCalls.rollback as SinonStub - ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + it('invokes beginTransaction with closed client', async () => { + const client = new firestoreModule.FirestoreClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.firestore.v1.BeginTransactionRequest() + ); + const defaultValue1 = + getTypeDefaultValue('.google.firestore.v1.BeginTransactionRequest', ['database']); + request.database = defaultValue1; + const expectedError = new Error('The client has already been closed.'); + client.close().catch(err => {throw err}); + await assert.rejects(client.beginTransaction(request), expectedError); + }); }); - it('invokes rollback with error', async () => { - const client = new firestoreModule.FirestoreClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.initialize(); - const request = generateSampleMessage( - new protos.google.firestore.v1.RollbackRequest() - ); - const defaultValue1 = getTypeDefaultValue( - '.google.firestore.v1.RollbackRequest', - ['database'] - ); - request.database = defaultValue1; - const expectedHeaderRequestParams = `database=${defaultValue1 ?? ''}`; - const expectedError = new Error('expected'); - client.innerApiCalls.rollback = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.rollback(request), expectedError); - const actualRequest = ( - client.innerApiCalls.rollback as SinonStub - ).getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = ( - client.innerApiCalls.rollback as SinonStub - ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + describe('commit', () => { + it('invokes commit without error', async () => { + const client = new firestoreModule.FirestoreClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.firestore.v1.CommitRequest() + ); + const defaultValue1 = + getTypeDefaultValue('.google.firestore.v1.CommitRequest', ['database']); + request.database = defaultValue1; + const expectedHeaderRequestParams = `database=${defaultValue1 ?? '' }`; + const expectedResponse = generateSampleMessage( + new protos.google.firestore.v1.CommitResponse() + ); + client.innerApiCalls.commit = stubSimpleCall(expectedResponse); + const [response] = await client.commit(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = (client.innerApiCalls.commit as SinonStub) + .getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = (client.innerApiCalls.commit as SinonStub) + .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes rollback with closed client', async () => { - const client = new firestoreModule.FirestoreClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.initialize(); - const request = generateSampleMessage( - new protos.google.firestore.v1.RollbackRequest() - ); - const defaultValue1 = getTypeDefaultValue( - '.google.firestore.v1.RollbackRequest', - ['database'] - ); - request.database = defaultValue1; - const expectedError = new Error('The client has already been closed.'); - client.close(); - await assert.rejects(client.rollback(request), expectedError); - }); - }); - - describe('batchWrite', () => { - it('invokes batchWrite without error', async () => { - const client = new firestoreModule.FirestoreClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.initialize(); - const request = generateSampleMessage( - new protos.google.firestore.v1.BatchWriteRequest() - ); - const defaultValue1 = getTypeDefaultValue( - '.google.firestore.v1.BatchWriteRequest', - ['database'] - ); - request.database = defaultValue1; - const expectedHeaderRequestParams = `database=${defaultValue1 ?? ''}`; - const expectedResponse = generateSampleMessage( - new protos.google.firestore.v1.BatchWriteResponse() - ); - client.innerApiCalls.batchWrite = stubSimpleCall(expectedResponse); - const [response] = await client.batchWrite(request); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = ( - client.innerApiCalls.batchWrite as SinonStub - ).getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = ( - client.innerApiCalls.batchWrite as SinonStub - ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes commit without error using callback', async () => { + const client = new firestoreModule.FirestoreClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.firestore.v1.CommitRequest() + ); + const defaultValue1 = + getTypeDefaultValue('.google.firestore.v1.CommitRequest', ['database']); + request.database = defaultValue1; + const expectedHeaderRequestParams = `database=${defaultValue1 ?? '' }`; + const expectedResponse = generateSampleMessage( + new protos.google.firestore.v1.CommitResponse() + ); + client.innerApiCalls.commit = stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.commit( + request, + (err?: Error|null, result?: protos.google.firestore.v1.ICommitResponse|null) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = (client.innerApiCalls.commit as SinonStub) + .getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = (client.innerApiCalls.commit as SinonStub) + .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes batchWrite without error using callback', async () => { - const client = new firestoreModule.FirestoreClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.initialize(); - const request = generateSampleMessage( - new protos.google.firestore.v1.BatchWriteRequest() - ); - const defaultValue1 = getTypeDefaultValue( - '.google.firestore.v1.BatchWriteRequest', - ['database'] - ); - request.database = defaultValue1; - const expectedHeaderRequestParams = `database=${defaultValue1 ?? ''}`; - const expectedResponse = generateSampleMessage( - new protos.google.firestore.v1.BatchWriteResponse() - ); - client.innerApiCalls.batchWrite = - stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.batchWrite( - request, - ( - err?: Error | null, - result?: protos.google.firestore.v1.IBatchWriteResponse | null - ) => { - if (err) { - reject(err); - } else { - resolve(result); - } - } - ); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = ( - client.innerApiCalls.batchWrite as SinonStub - ).getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = ( - client.innerApiCalls.batchWrite as SinonStub - ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes commit with error', async () => { + const client = new firestoreModule.FirestoreClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.firestore.v1.CommitRequest() + ); + const defaultValue1 = + getTypeDefaultValue('.google.firestore.v1.CommitRequest', ['database']); + request.database = defaultValue1; + const expectedHeaderRequestParams = `database=${defaultValue1 ?? '' }`; + const expectedError = new Error('expected'); + client.innerApiCalls.commit = stubSimpleCall(undefined, expectedError); + await assert.rejects(client.commit(request), expectedError); + const actualRequest = (client.innerApiCalls.commit as SinonStub) + .getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = (client.innerApiCalls.commit as SinonStub) + .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes batchWrite with error', async () => { - const client = new firestoreModule.FirestoreClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.initialize(); - const request = generateSampleMessage( - new protos.google.firestore.v1.BatchWriteRequest() - ); - const defaultValue1 = getTypeDefaultValue( - '.google.firestore.v1.BatchWriteRequest', - ['database'] - ); - request.database = defaultValue1; - const expectedHeaderRequestParams = `database=${defaultValue1 ?? ''}`; - const expectedError = new Error('expected'); - client.innerApiCalls.batchWrite = stubSimpleCall( - undefined, - expectedError - ); - await assert.rejects(client.batchWrite(request), expectedError); - const actualRequest = ( - client.innerApiCalls.batchWrite as SinonStub - ).getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = ( - client.innerApiCalls.batchWrite as SinonStub - ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + it('invokes commit with closed client', async () => { + const client = new firestoreModule.FirestoreClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.firestore.v1.CommitRequest() + ); + const defaultValue1 = + getTypeDefaultValue('.google.firestore.v1.CommitRequest', ['database']); + request.database = defaultValue1; + const expectedError = new Error('The client has already been closed.'); + client.close().catch(err => {throw err}); + await assert.rejects(client.commit(request), expectedError); + }); }); - it('invokes batchWrite with closed client', async () => { - const client = new firestoreModule.FirestoreClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.initialize(); - const request = generateSampleMessage( - new protos.google.firestore.v1.BatchWriteRequest() - ); - const defaultValue1 = getTypeDefaultValue( - '.google.firestore.v1.BatchWriteRequest', - ['database'] - ); - request.database = defaultValue1; - const expectedError = new Error('The client has already been closed.'); - client.close(); - await assert.rejects(client.batchWrite(request), expectedError); - }); - }); - - describe('createDocument', () => { - it('invokes createDocument without error', async () => { - const client = new firestoreModule.FirestoreClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.initialize(); - const request = generateSampleMessage( - new protos.google.firestore.v1.CreateDocumentRequest() - ); - const defaultValue1 = getTypeDefaultValue( - '.google.firestore.v1.CreateDocumentRequest', - ['parent'] - ); - request.parent = defaultValue1; - const defaultValue2 = getTypeDefaultValue( - '.google.firestore.v1.CreateDocumentRequest', - ['collectionId'] - ); - request.collectionId = defaultValue2; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}&collection_id=${defaultValue2 ?? ''}`; - const expectedResponse = generateSampleMessage( - new protos.google.firestore.v1.Document() - ); - client.innerApiCalls.createDocument = stubSimpleCall(expectedResponse); - const [response] = await client.createDocument(request); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = ( - client.innerApiCalls.createDocument as SinonStub - ).getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = ( - client.innerApiCalls.createDocument as SinonStub - ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + describe('rollback', () => { + it('invokes rollback without error', async () => { + const client = new firestoreModule.FirestoreClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.firestore.v1.RollbackRequest() + ); + const defaultValue1 = + getTypeDefaultValue('.google.firestore.v1.RollbackRequest', ['database']); + request.database = defaultValue1; + const expectedHeaderRequestParams = `database=${defaultValue1 ?? '' }`; + const expectedResponse = generateSampleMessage( + new protos.google.protobuf.Empty() + ); + client.innerApiCalls.rollback = stubSimpleCall(expectedResponse); + const [response] = await client.rollback(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = (client.innerApiCalls.rollback as SinonStub) + .getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = (client.innerApiCalls.rollback as SinonStub) + .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes createDocument without error using callback', async () => { - const client = new firestoreModule.FirestoreClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.initialize(); - const request = generateSampleMessage( - new protos.google.firestore.v1.CreateDocumentRequest() - ); - const defaultValue1 = getTypeDefaultValue( - '.google.firestore.v1.CreateDocumentRequest', - ['parent'] - ); - request.parent = defaultValue1; - const defaultValue2 = getTypeDefaultValue( - '.google.firestore.v1.CreateDocumentRequest', - ['collectionId'] - ); - request.collectionId = defaultValue2; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}&collection_id=${defaultValue2 ?? ''}`; - const expectedResponse = generateSampleMessage( - new protos.google.firestore.v1.Document() - ); - client.innerApiCalls.createDocument = - stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.createDocument( - request, - ( - err?: Error | null, - result?: protos.google.firestore.v1.IDocument | null - ) => { - if (err) { - reject(err); - } else { - resolve(result); - } - } - ); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = ( - client.innerApiCalls.createDocument as SinonStub - ).getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = ( - client.innerApiCalls.createDocument as SinonStub - ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes rollback without error using callback', async () => { + const client = new firestoreModule.FirestoreClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.firestore.v1.RollbackRequest() + ); + const defaultValue1 = + getTypeDefaultValue('.google.firestore.v1.RollbackRequest', ['database']); + request.database = defaultValue1; + const expectedHeaderRequestParams = `database=${defaultValue1 ?? '' }`; + const expectedResponse = generateSampleMessage( + new protos.google.protobuf.Empty() + ); + client.innerApiCalls.rollback = stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.rollback( + request, + (err?: Error|null, result?: protos.google.protobuf.IEmpty|null) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = (client.innerApiCalls.rollback as SinonStub) + .getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = (client.innerApiCalls.rollback as SinonStub) + .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes createDocument with error', async () => { - const client = new firestoreModule.FirestoreClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.initialize(); - const request = generateSampleMessage( - new protos.google.firestore.v1.CreateDocumentRequest() - ); - const defaultValue1 = getTypeDefaultValue( - '.google.firestore.v1.CreateDocumentRequest', - ['parent'] - ); - request.parent = defaultValue1; - const defaultValue2 = getTypeDefaultValue( - '.google.firestore.v1.CreateDocumentRequest', - ['collectionId'] - ); - request.collectionId = defaultValue2; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}&collection_id=${defaultValue2 ?? ''}`; - const expectedError = new Error('expected'); - client.innerApiCalls.createDocument = stubSimpleCall( - undefined, - expectedError - ); - await assert.rejects(client.createDocument(request), expectedError); - const actualRequest = ( - client.innerApiCalls.createDocument as SinonStub - ).getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = ( - client.innerApiCalls.createDocument as SinonStub - ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes rollback with error', async () => { + const client = new firestoreModule.FirestoreClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.firestore.v1.RollbackRequest() + ); + const defaultValue1 = + getTypeDefaultValue('.google.firestore.v1.RollbackRequest', ['database']); + request.database = defaultValue1; + const expectedHeaderRequestParams = `database=${defaultValue1 ?? '' }`; + const expectedError = new Error('expected'); + client.innerApiCalls.rollback = stubSimpleCall(undefined, expectedError); + await assert.rejects(client.rollback(request), expectedError); + const actualRequest = (client.innerApiCalls.rollback as SinonStub) + .getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = (client.innerApiCalls.rollback as SinonStub) + .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes createDocument with closed client', async () => { - const client = new firestoreModule.FirestoreClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.initialize(); - const request = generateSampleMessage( - new protos.google.firestore.v1.CreateDocumentRequest() - ); - const defaultValue1 = getTypeDefaultValue( - '.google.firestore.v1.CreateDocumentRequest', - ['parent'] - ); - request.parent = defaultValue1; - const defaultValue2 = getTypeDefaultValue( - '.google.firestore.v1.CreateDocumentRequest', - ['collectionId'] - ); - request.collectionId = defaultValue2; - const expectedError = new Error('The client has already been closed.'); - client.close(); - await assert.rejects(client.createDocument(request), expectedError); - }); - }); - - describe('batchGetDocuments', () => { - it('invokes batchGetDocuments without error', async () => { - const client = new firestoreModule.FirestoreClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.initialize(); - const request = generateSampleMessage( - new protos.google.firestore.v1.BatchGetDocumentsRequest() - ); - const defaultValue1 = getTypeDefaultValue( - '.google.firestore.v1.BatchGetDocumentsRequest', - ['database'] - ); - request.database = defaultValue1; - const expectedHeaderRequestParams = `database=${defaultValue1 ?? ''}`; - const expectedResponse = generateSampleMessage( - new protos.google.firestore.v1.BatchGetDocumentsResponse() - ); - client.innerApiCalls.batchGetDocuments = - stubServerStreamingCall(expectedResponse); - const stream = client.batchGetDocuments(request); - const promise = new Promise((resolve, reject) => { - stream.on( - 'data', - (response: protos.google.firestore.v1.BatchGetDocumentsResponse) => { - resolve(response); - } - ); - stream.on('error', (err: Error) => { - reject(err); - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = ( - client.innerApiCalls.batchGetDocuments as SinonStub - ).getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = ( - client.innerApiCalls.batchGetDocuments as SinonStub - ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + it('invokes rollback with closed client', async () => { + const client = new firestoreModule.FirestoreClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.firestore.v1.RollbackRequest() + ); + const defaultValue1 = + getTypeDefaultValue('.google.firestore.v1.RollbackRequest', ['database']); + request.database = defaultValue1; + const expectedError = new Error('The client has already been closed.'); + client.close().catch(err => {throw err}); + await assert.rejects(client.rollback(request), expectedError); + }); }); - it('invokes batchGetDocuments without error and gaxServerStreamingRetries enabled', async () => { - const client = new firestoreModule.FirestoreClient({ - gaxServerStreamingRetries: true, - }); - client.initialize(); - const request = generateSampleMessage( - new protos.google.firestore.v1.BatchGetDocumentsRequest() - ); - const defaultValue1 = getTypeDefaultValue( - '.google.firestore.v1.BatchGetDocumentsRequest', - ['database'] - ); - request.database = defaultValue1; - const expectedHeaderRequestParams = `database=${defaultValue1 ?? ''}`; - const expectedResponse = generateSampleMessage( - new protos.google.firestore.v1.BatchGetDocumentsResponse() - ); - client.innerApiCalls.batchGetDocuments = - stubServerStreamingCall(expectedResponse); - const stream = client.batchGetDocuments(request); - const promise = new Promise((resolve, reject) => { - stream.on( - 'data', - (response: protos.google.firestore.v1.BatchGetDocumentsResponse) => { - resolve(response); - } - ); - stream.on('error', (err: Error) => { - reject(err); - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = ( - client.innerApiCalls.batchGetDocuments as SinonStub - ).getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = ( - client.innerApiCalls.batchGetDocuments as SinonStub - ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + describe('batchWrite', () => { + it('invokes batchWrite without error', async () => { + const client = new firestoreModule.FirestoreClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.firestore.v1.BatchWriteRequest() + ); + const defaultValue1 = + getTypeDefaultValue('.google.firestore.v1.BatchWriteRequest', ['database']); + request.database = defaultValue1; + const expectedHeaderRequestParams = `database=${defaultValue1 ?? '' }`; + const expectedResponse = generateSampleMessage( + new protos.google.firestore.v1.BatchWriteResponse() + ); + client.innerApiCalls.batchWrite = stubSimpleCall(expectedResponse); + const [response] = await client.batchWrite(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = (client.innerApiCalls.batchWrite as SinonStub) + .getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = (client.innerApiCalls.batchWrite as SinonStub) + .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes batchGetDocuments with error', async () => { - const client = new firestoreModule.FirestoreClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.initialize(); - const request = generateSampleMessage( - new protos.google.firestore.v1.BatchGetDocumentsRequest() - ); - const defaultValue1 = getTypeDefaultValue( - '.google.firestore.v1.BatchGetDocumentsRequest', - ['database'] - ); - request.database = defaultValue1; - const expectedHeaderRequestParams = `database=${defaultValue1 ?? ''}`; - const expectedError = new Error('expected'); - client.innerApiCalls.batchGetDocuments = stubServerStreamingCall( - undefined, - expectedError - ); - const stream = client.batchGetDocuments(request); - const promise = new Promise((resolve, reject) => { - stream.on( - 'data', - (response: protos.google.firestore.v1.BatchGetDocumentsResponse) => { - resolve(response); - } - ); - stream.on('error', (err: Error) => { - reject(err); - }); - }); - await assert.rejects(promise, expectedError); - const actualRequest = ( - client.innerApiCalls.batchGetDocuments as SinonStub - ).getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = ( - client.innerApiCalls.batchGetDocuments as SinonStub - ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes batchWrite without error using callback', async () => { + const client = new firestoreModule.FirestoreClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.firestore.v1.BatchWriteRequest() + ); + const defaultValue1 = + getTypeDefaultValue('.google.firestore.v1.BatchWriteRequest', ['database']); + request.database = defaultValue1; + const expectedHeaderRequestParams = `database=${defaultValue1 ?? '' }`; + const expectedResponse = generateSampleMessage( + new protos.google.firestore.v1.BatchWriteResponse() + ); + client.innerApiCalls.batchWrite = stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.batchWrite( + request, + (err?: Error|null, result?: protos.google.firestore.v1.IBatchWriteResponse|null) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = (client.innerApiCalls.batchWrite as SinonStub) + .getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = (client.innerApiCalls.batchWrite as SinonStub) + .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes batchGetDocuments with closed client', async () => { - const client = new firestoreModule.FirestoreClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.initialize(); - const request = generateSampleMessage( - new protos.google.firestore.v1.BatchGetDocumentsRequest() - ); - const defaultValue1 = getTypeDefaultValue( - '.google.firestore.v1.BatchGetDocumentsRequest', - ['database'] - ); - request.database = defaultValue1; - const expectedError = new Error('The client has already been closed.'); - client.close(); - const stream = client.batchGetDocuments(request, { - retryRequestOptions: {noResponseRetries: 0}, - }); - const promise = new Promise((resolve, reject) => { - stream.on( - 'data', - (response: protos.google.firestore.v1.BatchGetDocumentsResponse) => { - resolve(response); - } - ); - stream.on('error', (err: Error) => { - reject(err); - }); - }); - await assert.rejects(promise, expectedError); - }); - it('should create a client with gaxServerStreamingRetries enabled', () => { - const client = new firestoreModule.FirestoreClient({ - gaxServerStreamingRetries: true, - }); - assert(client); - }); - }); - - describe('runQuery', () => { - it('invokes runQuery without error', async () => { - const client = new firestoreModule.FirestoreClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.initialize(); - const request = generateSampleMessage( - new protos.google.firestore.v1.RunQueryRequest() - ); - const defaultValue1 = getTypeDefaultValue( - '.google.firestore.v1.RunQueryRequest', - ['parent'] - ); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; - const expectedResponse = generateSampleMessage( - new protos.google.firestore.v1.RunQueryResponse() - ); - client.innerApiCalls.runQuery = stubServerStreamingCall(expectedResponse); - const stream = client.runQuery(request); - const promise = new Promise((resolve, reject) => { - stream.on( - 'data', - (response: protos.google.firestore.v1.RunQueryResponse) => { - resolve(response); - } - ); - stream.on('error', (err: Error) => { - reject(err); - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = ( - client.innerApiCalls.runQuery as SinonStub - ).getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = ( - client.innerApiCalls.runQuery as SinonStub - ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes batchWrite with error', async () => { + const client = new firestoreModule.FirestoreClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.firestore.v1.BatchWriteRequest() + ); + const defaultValue1 = + getTypeDefaultValue('.google.firestore.v1.BatchWriteRequest', ['database']); + request.database = defaultValue1; + const expectedHeaderRequestParams = `database=${defaultValue1 ?? '' }`; + const expectedError = new Error('expected'); + client.innerApiCalls.batchWrite = stubSimpleCall(undefined, expectedError); + await assert.rejects(client.batchWrite(request), expectedError); + const actualRequest = (client.innerApiCalls.batchWrite as SinonStub) + .getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = (client.innerApiCalls.batchWrite as SinonStub) + .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes runQuery without error and gaxServerStreamingRetries enabled', async () => { - const client = new firestoreModule.FirestoreClient({ - gaxServerStreamingRetries: true, - }); - client.initialize(); - const request = generateSampleMessage( - new protos.google.firestore.v1.RunQueryRequest() - ); - const defaultValue1 = getTypeDefaultValue( - '.google.firestore.v1.RunQueryRequest', - ['parent'] - ); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; - const expectedResponse = generateSampleMessage( - new protos.google.firestore.v1.RunQueryResponse() - ); - client.innerApiCalls.runQuery = stubServerStreamingCall(expectedResponse); - const stream = client.runQuery(request); - const promise = new Promise((resolve, reject) => { - stream.on( - 'data', - (response: protos.google.firestore.v1.RunQueryResponse) => { - resolve(response); - } - ); - stream.on('error', (err: Error) => { - reject(err); - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = ( - client.innerApiCalls.runQuery as SinonStub - ).getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = ( - client.innerApiCalls.runQuery as SinonStub - ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + it('invokes batchWrite with closed client', async () => { + const client = new firestoreModule.FirestoreClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.firestore.v1.BatchWriteRequest() + ); + const defaultValue1 = + getTypeDefaultValue('.google.firestore.v1.BatchWriteRequest', ['database']); + request.database = defaultValue1; + const expectedError = new Error('The client has already been closed.'); + client.close().catch(err => {throw err}); + await assert.rejects(client.batchWrite(request), expectedError); + }); }); - it('invokes runQuery with error', async () => { - const client = new firestoreModule.FirestoreClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.initialize(); - const request = generateSampleMessage( - new protos.google.firestore.v1.RunQueryRequest() - ); - const defaultValue1 = getTypeDefaultValue( - '.google.firestore.v1.RunQueryRequest', - ['parent'] - ); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; - const expectedError = new Error('expected'); - client.innerApiCalls.runQuery = stubServerStreamingCall( - undefined, - expectedError - ); - const stream = client.runQuery(request); - const promise = new Promise((resolve, reject) => { - stream.on( - 'data', - (response: protos.google.firestore.v1.RunQueryResponse) => { - resolve(response); - } - ); - stream.on('error', (err: Error) => { - reject(err); - }); - }); - await assert.rejects(promise, expectedError); - const actualRequest = ( - client.innerApiCalls.runQuery as SinonStub - ).getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = ( - client.innerApiCalls.runQuery as SinonStub - ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + describe('createDocument', () => { + it('invokes createDocument without error', async () => { + const client = new firestoreModule.FirestoreClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.firestore.v1.CreateDocumentRequest() + ); + const defaultValue1 = + getTypeDefaultValue('.google.firestore.v1.CreateDocumentRequest', ['parent']); + request.parent = defaultValue1; + const defaultValue2 = + getTypeDefaultValue('.google.firestore.v1.CreateDocumentRequest', ['collectionId']); + request.collectionId = defaultValue2; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }&collection_id=${defaultValue2 ?? '' }`; + const expectedResponse = generateSampleMessage( + new protos.google.firestore.v1.Document() + ); + client.innerApiCalls.createDocument = stubSimpleCall(expectedResponse); + const [response] = await client.createDocument(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = (client.innerApiCalls.createDocument as SinonStub) + .getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = (client.innerApiCalls.createDocument as SinonStub) + .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes runQuery with closed client', async () => { - const client = new firestoreModule.FirestoreClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.initialize(); - const request = generateSampleMessage( - new protos.google.firestore.v1.RunQueryRequest() - ); - const defaultValue1 = getTypeDefaultValue( - '.google.firestore.v1.RunQueryRequest', - ['parent'] - ); - request.parent = defaultValue1; - const expectedError = new Error('The client has already been closed.'); - client.close(); - const stream = client.runQuery(request, { - retryRequestOptions: {noResponseRetries: 0}, - }); - const promise = new Promise((resolve, reject) => { - stream.on( - 'data', - (response: protos.google.firestore.v1.RunQueryResponse) => { - resolve(response); - } - ); - stream.on('error', (err: Error) => { - reject(err); - }); - }); - await assert.rejects(promise, expectedError); - }); - it('should create a client with gaxServerStreamingRetries enabled', () => { - const client = new firestoreModule.FirestoreClient({ - gaxServerStreamingRetries: true, - }); - assert(client); - }); - }); - - describe('runAggregationQuery', () => { - it('invokes runAggregationQuery without error', async () => { - const client = new firestoreModule.FirestoreClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.initialize(); - const request = generateSampleMessage( - new protos.google.firestore.v1.RunAggregationQueryRequest() - ); - const defaultValue1 = getTypeDefaultValue( - '.google.firestore.v1.RunAggregationQueryRequest', - ['parent'] - ); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; - const expectedResponse = generateSampleMessage( - new protos.google.firestore.v1.RunAggregationQueryResponse() - ); - client.innerApiCalls.runAggregationQuery = - stubServerStreamingCall(expectedResponse); - const stream = client.runAggregationQuery(request); - const promise = new Promise((resolve, reject) => { - stream.on( - 'data', - ( - response: protos.google.firestore.v1.RunAggregationQueryResponse - ) => { - resolve(response); - } - ); - stream.on('error', (err: Error) => { - reject(err); - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = ( - client.innerApiCalls.runAggregationQuery as SinonStub - ).getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = ( - client.innerApiCalls.runAggregationQuery as SinonStub - ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes createDocument without error using callback', async () => { + const client = new firestoreModule.FirestoreClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.firestore.v1.CreateDocumentRequest() + ); + const defaultValue1 = + getTypeDefaultValue('.google.firestore.v1.CreateDocumentRequest', ['parent']); + request.parent = defaultValue1; + const defaultValue2 = + getTypeDefaultValue('.google.firestore.v1.CreateDocumentRequest', ['collectionId']); + request.collectionId = defaultValue2; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }&collection_id=${defaultValue2 ?? '' }`; + const expectedResponse = generateSampleMessage( + new protos.google.firestore.v1.Document() + ); + client.innerApiCalls.createDocument = stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.createDocument( + request, + (err?: Error|null, result?: protos.google.firestore.v1.IDocument|null) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = (client.innerApiCalls.createDocument as SinonStub) + .getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = (client.innerApiCalls.createDocument as SinonStub) + .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes runAggregationQuery without error and gaxServerStreamingRetries enabled', async () => { - const client = new firestoreModule.FirestoreClient({ - gaxServerStreamingRetries: true, - }); - client.initialize(); - const request = generateSampleMessage( - new protos.google.firestore.v1.RunAggregationQueryRequest() - ); - const defaultValue1 = getTypeDefaultValue( - '.google.firestore.v1.RunAggregationQueryRequest', - ['parent'] - ); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; - const expectedResponse = generateSampleMessage( - new protos.google.firestore.v1.RunAggregationQueryResponse() - ); - client.innerApiCalls.runAggregationQuery = - stubServerStreamingCall(expectedResponse); - const stream = client.runAggregationQuery(request); - const promise = new Promise((resolve, reject) => { - stream.on( - 'data', - ( - response: protos.google.firestore.v1.RunAggregationQueryResponse - ) => { - resolve(response); - } - ); - stream.on('error', (err: Error) => { - reject(err); - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = ( - client.innerApiCalls.runAggregationQuery as SinonStub - ).getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = ( - client.innerApiCalls.runAggregationQuery as SinonStub - ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes createDocument with error', async () => { + const client = new firestoreModule.FirestoreClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.firestore.v1.CreateDocumentRequest() + ); + const defaultValue1 = + getTypeDefaultValue('.google.firestore.v1.CreateDocumentRequest', ['parent']); + request.parent = defaultValue1; + const defaultValue2 = + getTypeDefaultValue('.google.firestore.v1.CreateDocumentRequest', ['collectionId']); + request.collectionId = defaultValue2; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }&collection_id=${defaultValue2 ?? '' }`; + const expectedError = new Error('expected'); + client.innerApiCalls.createDocument = stubSimpleCall(undefined, expectedError); + await assert.rejects(client.createDocument(request), expectedError); + const actualRequest = (client.innerApiCalls.createDocument as SinonStub) + .getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = (client.innerApiCalls.createDocument as SinonStub) + .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes runAggregationQuery with error', async () => { - const client = new firestoreModule.FirestoreClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.initialize(); - const request = generateSampleMessage( - new protos.google.firestore.v1.RunAggregationQueryRequest() - ); - const defaultValue1 = getTypeDefaultValue( - '.google.firestore.v1.RunAggregationQueryRequest', - ['parent'] - ); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; - const expectedError = new Error('expected'); - client.innerApiCalls.runAggregationQuery = stubServerStreamingCall( - undefined, - expectedError - ); - const stream = client.runAggregationQuery(request); - const promise = new Promise((resolve, reject) => { - stream.on( - 'data', - ( - response: protos.google.firestore.v1.RunAggregationQueryResponse - ) => { - resolve(response); - } - ); - stream.on('error', (err: Error) => { - reject(err); - }); - }); - await assert.rejects(promise, expectedError); - const actualRequest = ( - client.innerApiCalls.runAggregationQuery as SinonStub - ).getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = ( - client.innerApiCalls.runAggregationQuery as SinonStub - ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + it('invokes createDocument with closed client', async () => { + const client = new firestoreModule.FirestoreClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.firestore.v1.CreateDocumentRequest() + ); + const defaultValue1 = + getTypeDefaultValue('.google.firestore.v1.CreateDocumentRequest', ['parent']); + request.parent = defaultValue1; + const defaultValue2 = + getTypeDefaultValue('.google.firestore.v1.CreateDocumentRequest', ['collectionId']); + request.collectionId = defaultValue2; + const expectedError = new Error('The client has already been closed.'); + client.close().catch(err => {throw err}); + await assert.rejects(client.createDocument(request), expectedError); + }); }); - it('invokes runAggregationQuery with closed client', async () => { - const client = new firestoreModule.FirestoreClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.initialize(); - const request = generateSampleMessage( - new protos.google.firestore.v1.RunAggregationQueryRequest() - ); - const defaultValue1 = getTypeDefaultValue( - '.google.firestore.v1.RunAggregationQueryRequest', - ['parent'] - ); - request.parent = defaultValue1; - const expectedError = new Error('The client has already been closed.'); - client.close(); - const stream = client.runAggregationQuery(request, { - retryRequestOptions: {noResponseRetries: 0}, - }); - const promise = new Promise((resolve, reject) => { - stream.on( - 'data', - ( - response: protos.google.firestore.v1.RunAggregationQueryResponse - ) => { - resolve(response); - } - ); - stream.on('error', (err: Error) => { - reject(err); - }); - }); - await assert.rejects(promise, expectedError); - }); - it('should create a client with gaxServerStreamingRetries enabled', () => { - const client = new firestoreModule.FirestoreClient({ - gaxServerStreamingRetries: true, - }); - assert(client); - }); - }); - - describe('write', () => { - it('invokes write without error', async () => { - const client = new firestoreModule.FirestoreClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.initialize(); - const request = generateSampleMessage( - new protos.google.firestore.v1.WriteRequest() - ); - - const expectedResponse = generateSampleMessage( - new protos.google.firestore.v1.WriteResponse() - ); - client.innerApiCalls.write = stubBidiStreamingCall(expectedResponse); - const stream = client.write(); - const promise = new Promise((resolve, reject) => { - stream.on( - 'data', - (response: protos.google.firestore.v1.WriteResponse) => { - resolve(response); - } - ); - stream.on('error', (err: Error) => { - reject(err); - }); - stream.write(request); - stream.end(); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - assert( - (client.innerApiCalls.write as SinonStub).getCall(0).calledWith(null) - ); - assert.deepStrictEqual( - ((stream as unknown as PassThrough)._transform as SinonStub).getCall(0) - .args[0], - request - ); - }); + describe('batchGetDocuments', () => { + it('invokes batchGetDocuments without error', async () => { + const client = new firestoreModule.FirestoreClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.firestore.v1.BatchGetDocumentsRequest() + ); + const defaultValue1 = + getTypeDefaultValue('.google.firestore.v1.BatchGetDocumentsRequest', ['database']); + request.database = defaultValue1; + const expectedHeaderRequestParams = `database=${defaultValue1 ?? '' }`; + const expectedResponse = generateSampleMessage( + new protos.google.firestore.v1.BatchGetDocumentsResponse() + ); + client.innerApiCalls.batchGetDocuments = stubServerStreamingCall(expectedResponse); + const stream = client.batchGetDocuments(request); + const promise = new Promise((resolve, reject) => { + stream.on('data', (response: protos.google.firestore.v1.BatchGetDocumentsResponse) => { + resolve(response); + }); + stream.on('error', (err: Error) => { + reject(err); + }); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = (client.innerApiCalls.batchGetDocuments as SinonStub) + .getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = (client.innerApiCalls.batchGetDocuments as SinonStub) + .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes write with error', async () => { - const client = new firestoreModule.FirestoreClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.initialize(); - const request = generateSampleMessage( - new protos.google.firestore.v1.WriteRequest() - ); - const expectedError = new Error('expected'); - client.innerApiCalls.write = stubBidiStreamingCall( - undefined, - expectedError - ); - const stream = client.write(); - const promise = new Promise((resolve, reject) => { - stream.on( - 'data', - (response: protos.google.firestore.v1.WriteResponse) => { - resolve(response); - } - ); - stream.on('error', (err: Error) => { - reject(err); - }); - stream.write(request); - stream.end(); - }); - await assert.rejects(promise, expectedError); - assert( - (client.innerApiCalls.write as SinonStub).getCall(0).calledWith(null) - ); - assert.deepStrictEqual( - ((stream as unknown as PassThrough)._transform as SinonStub).getCall(0) - .args[0], - request - ); - }); - }); - - describe('listen', () => { - it('invokes listen without error', async () => { - const client = new firestoreModule.FirestoreClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.initialize(); - const request = generateSampleMessage( - new protos.google.firestore.v1.ListenRequest() - ); - - const expectedResponse = generateSampleMessage( - new protos.google.firestore.v1.ListenResponse() - ); - client.innerApiCalls.listen = stubBidiStreamingCall(expectedResponse); - const stream = client.listen(); - const promise = new Promise((resolve, reject) => { - stream.on( - 'data', - (response: protos.google.firestore.v1.ListenResponse) => { - resolve(response); - } - ); - stream.on('error', (err: Error) => { - reject(err); - }); - stream.write(request); - stream.end(); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - assert( - (client.innerApiCalls.listen as SinonStub).getCall(0).calledWith(null) - ); - assert.deepStrictEqual( - ((stream as unknown as PassThrough)._transform as SinonStub).getCall(0) - .args[0], - request - ); - }); + it('invokes batchGetDocuments without error and gaxServerStreamingRetries enabled', async () => { + const client = new firestoreModule.FirestoreClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + gaxServerStreamingRetries: true + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.firestore.v1.BatchGetDocumentsRequest() + ); + const defaultValue1 = + getTypeDefaultValue('.google.firestore.v1.BatchGetDocumentsRequest', ['database']); + request.database = defaultValue1; + const expectedHeaderRequestParams = `database=${defaultValue1 ?? '' }`; + const expectedResponse = generateSampleMessage( + new protos.google.firestore.v1.BatchGetDocumentsResponse() + ); + client.innerApiCalls.batchGetDocuments = stubServerStreamingCall(expectedResponse); + const stream = client.batchGetDocuments(request); + const promise = new Promise((resolve, reject) => { + stream.on('data', (response: protos.google.firestore.v1.BatchGetDocumentsResponse) => { + resolve(response); + }); + stream.on('error', (err: Error) => { + reject(err); + }); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = (client.innerApiCalls.batchGetDocuments as SinonStub) + .getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = (client.innerApiCalls.batchGetDocuments as SinonStub) + .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes listen with error', async () => { - const client = new firestoreModule.FirestoreClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.initialize(); - const request = generateSampleMessage( - new protos.google.firestore.v1.ListenRequest() - ); - const expectedError = new Error('expected'); - client.innerApiCalls.listen = stubBidiStreamingCall( - undefined, - expectedError - ); - const stream = client.listen(); - const promise = new Promise((resolve, reject) => { - stream.on( - 'data', - (response: protos.google.firestore.v1.ListenResponse) => { - resolve(response); - } - ); - stream.on('error', (err: Error) => { - reject(err); - }); - stream.write(request); - stream.end(); - }); - await assert.rejects(promise, expectedError); - assert( - (client.innerApiCalls.listen as SinonStub).getCall(0).calledWith(null) - ); - assert.deepStrictEqual( - ((stream as unknown as PassThrough)._transform as SinonStub).getCall(0) - .args[0], - request - ); - }); - }); - - describe('listDocuments', () => { - it('invokes listDocuments without error', async () => { - const client = new firestoreModule.FirestoreClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.initialize(); - const request = generateSampleMessage( - new protos.google.firestore.v1.ListDocumentsRequest() - ); - const defaultValue1 = getTypeDefaultValue( - '.google.firestore.v1.ListDocumentsRequest', - ['parent'] - ); - request.parent = defaultValue1; - const defaultValue2 = getTypeDefaultValue( - '.google.firestore.v1.ListDocumentsRequest', - ['collectionId'] - ); - request.collectionId = defaultValue2; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}&collection_id=${defaultValue2 ?? ''}`; - const expectedResponse = [ - generateSampleMessage(new protos.google.firestore.v1.Document()), - generateSampleMessage(new protos.google.firestore.v1.Document()), - generateSampleMessage(new protos.google.firestore.v1.Document()), - ]; - client.innerApiCalls.listDocuments = stubSimpleCall(expectedResponse); - const [response] = await client.listDocuments(request); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = ( - client.innerApiCalls.listDocuments as SinonStub - ).getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = ( - client.innerApiCalls.listDocuments as SinonStub - ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes batchGetDocuments with error', async () => { + const client = new firestoreModule.FirestoreClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.firestore.v1.BatchGetDocumentsRequest() + ); + const defaultValue1 = + getTypeDefaultValue('.google.firestore.v1.BatchGetDocumentsRequest', ['database']); + request.database = defaultValue1; + const expectedHeaderRequestParams = `database=${defaultValue1 ?? '' }`; + const expectedError = new Error('expected'); + client.innerApiCalls.batchGetDocuments = stubServerStreamingCall(undefined, expectedError); + const stream = client.batchGetDocuments(request); + const promise = new Promise((resolve, reject) => { + stream.on('data', (response: protos.google.firestore.v1.BatchGetDocumentsResponse) => { + resolve(response); + }); + stream.on('error', (err: Error) => { + reject(err); + }); + }); + await assert.rejects(promise, expectedError); + const actualRequest = (client.innerApiCalls.batchGetDocuments as SinonStub) + .getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = (client.innerApiCalls.batchGetDocuments as SinonStub) + .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes listDocuments without error using callback', async () => { - const client = new firestoreModule.FirestoreClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.initialize(); - const request = generateSampleMessage( - new protos.google.firestore.v1.ListDocumentsRequest() - ); - const defaultValue1 = getTypeDefaultValue( - '.google.firestore.v1.ListDocumentsRequest', - ['parent'] - ); - request.parent = defaultValue1; - const defaultValue2 = getTypeDefaultValue( - '.google.firestore.v1.ListDocumentsRequest', - ['collectionId'] - ); - request.collectionId = defaultValue2; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}&collection_id=${defaultValue2 ?? ''}`; - const expectedResponse = [ - generateSampleMessage(new protos.google.firestore.v1.Document()), - generateSampleMessage(new protos.google.firestore.v1.Document()), - generateSampleMessage(new protos.google.firestore.v1.Document()), - ]; - client.innerApiCalls.listDocuments = - stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.listDocuments( - request, - ( - err?: Error | null, - result?: protos.google.firestore.v1.IDocument[] | null - ) => { - if (err) { - reject(err); - } else { - resolve(result); - } - } - ); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = ( - client.innerApiCalls.listDocuments as SinonStub - ).getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = ( - client.innerApiCalls.listDocuments as SinonStub - ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + it('invokes batchGetDocuments with closed client', async () => { + const client = new firestoreModule.FirestoreClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.firestore.v1.BatchGetDocumentsRequest() + ); + const defaultValue1 = + getTypeDefaultValue('.google.firestore.v1.BatchGetDocumentsRequest', ['database']); + request.database = defaultValue1; + const expectedError = new Error('The client has already been closed.'); + client.close().catch(err => {throw err}); + const stream = client.batchGetDocuments(request, {retryRequestOptions: {noResponseRetries: 0}}); + const promise = new Promise((resolve, reject) => { + stream.on('data', (response: protos.google.firestore.v1.BatchGetDocumentsResponse) => { + resolve(response); + }); + stream.on('error', (err: Error) => { + reject(err); + }); + }); + await assert.rejects(promise, expectedError); + }); + it('should create a client with gaxServerStreamingRetries enabled', () => { + const client = new firestoreModule.FirestoreClient({ + gaxServerStreamingRetries: true, + }); + assert(client); + }); }); - it('invokes listDocuments with error', async () => { - const client = new firestoreModule.FirestoreClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.initialize(); - const request = generateSampleMessage( - new protos.google.firestore.v1.ListDocumentsRequest() - ); - const defaultValue1 = getTypeDefaultValue( - '.google.firestore.v1.ListDocumentsRequest', - ['parent'] - ); - request.parent = defaultValue1; - const defaultValue2 = getTypeDefaultValue( - '.google.firestore.v1.ListDocumentsRequest', - ['collectionId'] - ); - request.collectionId = defaultValue2; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}&collection_id=${defaultValue2 ?? ''}`; - const expectedError = new Error('expected'); - client.innerApiCalls.listDocuments = stubSimpleCall( - undefined, - expectedError - ); - await assert.rejects(client.listDocuments(request), expectedError); - const actualRequest = ( - client.innerApiCalls.listDocuments as SinonStub - ).getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = ( - client.innerApiCalls.listDocuments as SinonStub - ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + describe('runQuery', () => { + it('invokes runQuery without error', async () => { + const client = new firestoreModule.FirestoreClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.firestore.v1.RunQueryRequest() + ); + const defaultValue1 = + getTypeDefaultValue('.google.firestore.v1.RunQueryRequest', ['parent']); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; + const expectedResponse = generateSampleMessage( + new protos.google.firestore.v1.RunQueryResponse() + ); + client.innerApiCalls.runQuery = stubServerStreamingCall(expectedResponse); + const stream = client.runQuery(request); + const promise = new Promise((resolve, reject) => { + stream.on('data', (response: protos.google.firestore.v1.RunQueryResponse) => { + resolve(response); + }); + stream.on('error', (err: Error) => { + reject(err); + }); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = (client.innerApiCalls.runQuery as SinonStub) + .getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = (client.innerApiCalls.runQuery as SinonStub) + .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes runQuery without error and gaxServerStreamingRetries enabled', async () => { + const client = new firestoreModule.FirestoreClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + gaxServerStreamingRetries: true + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.firestore.v1.RunQueryRequest() + ); + const defaultValue1 = + getTypeDefaultValue('.google.firestore.v1.RunQueryRequest', ['parent']); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; + const expectedResponse = generateSampleMessage( + new protos.google.firestore.v1.RunQueryResponse() + ); + client.innerApiCalls.runQuery = stubServerStreamingCall(expectedResponse); + const stream = client.runQuery(request); + const promise = new Promise((resolve, reject) => { + stream.on('data', (response: protos.google.firestore.v1.RunQueryResponse) => { + resolve(response); + }); + stream.on('error', (err: Error) => { + reject(err); + }); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = (client.innerApiCalls.runQuery as SinonStub) + .getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = (client.innerApiCalls.runQuery as SinonStub) + .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes runQuery with error', async () => { + const client = new firestoreModule.FirestoreClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.firestore.v1.RunQueryRequest() + ); + const defaultValue1 = + getTypeDefaultValue('.google.firestore.v1.RunQueryRequest', ['parent']); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; + const expectedError = new Error('expected'); + client.innerApiCalls.runQuery = stubServerStreamingCall(undefined, expectedError); + const stream = client.runQuery(request); + const promise = new Promise((resolve, reject) => { + stream.on('data', (response: protos.google.firestore.v1.RunQueryResponse) => { + resolve(response); + }); + stream.on('error', (err: Error) => { + reject(err); + }); + }); + await assert.rejects(promise, expectedError); + const actualRequest = (client.innerApiCalls.runQuery as SinonStub) + .getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = (client.innerApiCalls.runQuery as SinonStub) + .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes listDocumentsStream without error', async () => { - const client = new firestoreModule.FirestoreClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.initialize(); - const request = generateSampleMessage( - new protos.google.firestore.v1.ListDocumentsRequest() - ); - const defaultValue1 = getTypeDefaultValue( - '.google.firestore.v1.ListDocumentsRequest', - ['parent'] - ); - request.parent = defaultValue1; - const defaultValue2 = getTypeDefaultValue( - '.google.firestore.v1.ListDocumentsRequest', - ['collectionId'] - ); - request.collectionId = defaultValue2; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}&collection_id=${defaultValue2 ?? ''}`; - const expectedResponse = [ - generateSampleMessage(new protos.google.firestore.v1.Document()), - generateSampleMessage(new protos.google.firestore.v1.Document()), - generateSampleMessage(new protos.google.firestore.v1.Document()), - ]; - client.descriptors.page.listDocuments.createStream = - stubPageStreamingCall(expectedResponse); - const stream = client.listDocumentsStream(request); - const promise = new Promise((resolve, reject) => { - const responses: protos.google.firestore.v1.Document[] = []; - stream.on('data', (response: protos.google.firestore.v1.Document) => { - responses.push(response); - }); - stream.on('end', () => { - resolve(responses); - }); - stream.on('error', (err: Error) => { - reject(err); - }); - }); - const responses = await promise; - assert.deepStrictEqual(responses, expectedResponse); - assert( - (client.descriptors.page.listDocuments.createStream as SinonStub) - .getCall(0) - .calledWith(client.innerApiCalls.listDocuments, request) - ); - assert( - (client.descriptors.page.listDocuments.createStream as SinonStub) - .getCall(0) - .args[2].otherArgs.headers[ - 'x-goog-request-params' - ].includes(expectedHeaderRequestParams) - ); + it('invokes runQuery with closed client', async () => { + const client = new firestoreModule.FirestoreClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.firestore.v1.RunQueryRequest() + ); + const defaultValue1 = + getTypeDefaultValue('.google.firestore.v1.RunQueryRequest', ['parent']); + request.parent = defaultValue1; + const expectedError = new Error('The client has already been closed.'); + client.close().catch(err => {throw err}); + const stream = client.runQuery(request, {retryRequestOptions: {noResponseRetries: 0}}); + const promise = new Promise((resolve, reject) => { + stream.on('data', (response: protos.google.firestore.v1.RunQueryResponse) => { + resolve(response); + }); + stream.on('error', (err: Error) => { + reject(err); + }); + }); + await assert.rejects(promise, expectedError); + }); + it('should create a client with gaxServerStreamingRetries enabled', () => { + const client = new firestoreModule.FirestoreClient({ + gaxServerStreamingRetries: true, + }); + assert(client); + }); }); - it('invokes listDocumentsStream with error', async () => { - const client = new firestoreModule.FirestoreClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.initialize(); - const request = generateSampleMessage( - new protos.google.firestore.v1.ListDocumentsRequest() - ); - const defaultValue1 = getTypeDefaultValue( - '.google.firestore.v1.ListDocumentsRequest', - ['parent'] - ); - request.parent = defaultValue1; - const defaultValue2 = getTypeDefaultValue( - '.google.firestore.v1.ListDocumentsRequest', - ['collectionId'] - ); - request.collectionId = defaultValue2; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}&collection_id=${defaultValue2 ?? ''}`; - const expectedError = new Error('expected'); - client.descriptors.page.listDocuments.createStream = - stubPageStreamingCall(undefined, expectedError); - const stream = client.listDocumentsStream(request); - const promise = new Promise((resolve, reject) => { - const responses: protos.google.firestore.v1.Document[] = []; - stream.on('data', (response: protos.google.firestore.v1.Document) => { - responses.push(response); - }); - stream.on('end', () => { - resolve(responses); - }); - stream.on('error', (err: Error) => { - reject(err); - }); - }); - await assert.rejects(promise, expectedError); - assert( - (client.descriptors.page.listDocuments.createStream as SinonStub) - .getCall(0) - .calledWith(client.innerApiCalls.listDocuments, request) - ); - assert( - (client.descriptors.page.listDocuments.createStream as SinonStub) - .getCall(0) - .args[2].otherArgs.headers[ - 'x-goog-request-params' - ].includes(expectedHeaderRequestParams) - ); + describe('executePipeline', () => { + it('invokes executePipeline without error', async () => { + const client = new firestoreModule.FirestoreClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.firestore.v1.ExecutePipelineRequest() + ); + // path template: projects/*/databases/{database_id=*}/** + request.database = 'projects/value/databases/value/value'; + const expectedHeaderRequestParams = 'database_id=value'; + const expectedResponse = generateSampleMessage( + new protos.google.firestore.v1.ExecutePipelineResponse() + ); + client.innerApiCalls.executePipeline = stubServerStreamingCall(expectedResponse); + const stream = client.executePipeline(request); + const promise = new Promise((resolve, reject) => { + stream.on('data', (response: protos.google.firestore.v1.ExecutePipelineResponse) => { + resolve(response); + }); + stream.on('error', (err: Error) => { + reject(err); + }); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = (client.innerApiCalls.executePipeline as SinonStub) + .getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = (client.innerApiCalls.executePipeline as SinonStub) + .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes executePipeline without error and gaxServerStreamingRetries enabled', async () => { + const client = new firestoreModule.FirestoreClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + gaxServerStreamingRetries: true + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.firestore.v1.ExecutePipelineRequest() + ); + // path template: projects/*/databases/{database_id=*}/** + request.database = 'projects/value/databases/value/value'; + const expectedHeaderRequestParams = 'database_id=value'; + const expectedResponse = generateSampleMessage( + new protos.google.firestore.v1.ExecutePipelineResponse() + ); + client.innerApiCalls.executePipeline = stubServerStreamingCall(expectedResponse); + const stream = client.executePipeline(request); + const promise = new Promise((resolve, reject) => { + stream.on('data', (response: protos.google.firestore.v1.ExecutePipelineResponse) => { + resolve(response); + }); + stream.on('error', (err: Error) => { + reject(err); + }); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = (client.innerApiCalls.executePipeline as SinonStub) + .getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = (client.innerApiCalls.executePipeline as SinonStub) + .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes executePipeline with error', async () => { + const client = new firestoreModule.FirestoreClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.firestore.v1.ExecutePipelineRequest() + ); + // path template: projects/*/databases/{database_id=*}/** + request.database = 'projects/value/databases/value/value'; + const expectedHeaderRequestParams = 'database_id=value'; + const expectedError = new Error('expected'); + client.innerApiCalls.executePipeline = stubServerStreamingCall(undefined, expectedError); + const stream = client.executePipeline(request); + const promise = new Promise((resolve, reject) => { + stream.on('data', (response: protos.google.firestore.v1.ExecutePipelineResponse) => { + resolve(response); + }); + stream.on('error', (err: Error) => { + reject(err); + }); + }); + await assert.rejects(promise, expectedError); + const actualRequest = (client.innerApiCalls.executePipeline as SinonStub) + .getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = (client.innerApiCalls.executePipeline as SinonStub) + .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes executePipeline with closed client', async () => { + const client = new firestoreModule.FirestoreClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.firestore.v1.ExecutePipelineRequest() + ); + // path template: projects/*/databases/{database_id=*}/** + request.database = 'projects/value/databases/value/value'; + const expectedError = new Error('The client has already been closed.'); + client.close().catch(err => {throw err}); + const stream = client.executePipeline(request, {retryRequestOptions: {noResponseRetries: 0}}); + const promise = new Promise((resolve, reject) => { + stream.on('data', (response: protos.google.firestore.v1.ExecutePipelineResponse) => { + resolve(response); + }); + stream.on('error', (err: Error) => { + reject(err); + }); + }); + await assert.rejects(promise, expectedError); + }); + it('should create a client with gaxServerStreamingRetries enabled', () => { + const client = new firestoreModule.FirestoreClient({ + gaxServerStreamingRetries: true, + }); + assert(client); + }); }); - it('uses async iteration with listDocuments without error', async () => { - const client = new firestoreModule.FirestoreClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.initialize(); - const request = generateSampleMessage( - new protos.google.firestore.v1.ListDocumentsRequest() - ); - const defaultValue1 = getTypeDefaultValue( - '.google.firestore.v1.ListDocumentsRequest', - ['parent'] - ); - request.parent = defaultValue1; - const defaultValue2 = getTypeDefaultValue( - '.google.firestore.v1.ListDocumentsRequest', - ['collectionId'] - ); - request.collectionId = defaultValue2; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}&collection_id=${defaultValue2 ?? ''}`; - const expectedResponse = [ - generateSampleMessage(new protos.google.firestore.v1.Document()), - generateSampleMessage(new protos.google.firestore.v1.Document()), - generateSampleMessage(new protos.google.firestore.v1.Document()), - ]; - client.descriptors.page.listDocuments.asyncIterate = - stubAsyncIterationCall(expectedResponse); - const responses: protos.google.firestore.v1.IDocument[] = []; - const iterable = client.listDocumentsAsync(request); - for await (const resource of iterable) { - responses.push(resource!); - } - assert.deepStrictEqual(responses, expectedResponse); - assert.deepStrictEqual( - ( - client.descriptors.page.listDocuments.asyncIterate as SinonStub - ).getCall(0).args[1], - request - ); - assert( - (client.descriptors.page.listDocuments.asyncIterate as SinonStub) - .getCall(0) - .args[2].otherArgs.headers[ - 'x-goog-request-params' - ].includes(expectedHeaderRequestParams) - ); + describe('runAggregationQuery', () => { + it('invokes runAggregationQuery without error', async () => { + const client = new firestoreModule.FirestoreClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.firestore.v1.RunAggregationQueryRequest() + ); + const defaultValue1 = + getTypeDefaultValue('.google.firestore.v1.RunAggregationQueryRequest', ['parent']); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; + const expectedResponse = generateSampleMessage( + new protos.google.firestore.v1.RunAggregationQueryResponse() + ); + client.innerApiCalls.runAggregationQuery = stubServerStreamingCall(expectedResponse); + const stream = client.runAggregationQuery(request); + const promise = new Promise((resolve, reject) => { + stream.on('data', (response: protos.google.firestore.v1.RunAggregationQueryResponse) => { + resolve(response); + }); + stream.on('error', (err: Error) => { + reject(err); + }); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = (client.innerApiCalls.runAggregationQuery as SinonStub) + .getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = (client.innerApiCalls.runAggregationQuery as SinonStub) + .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes runAggregationQuery without error and gaxServerStreamingRetries enabled', async () => { + const client = new firestoreModule.FirestoreClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + gaxServerStreamingRetries: true + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.firestore.v1.RunAggregationQueryRequest() + ); + const defaultValue1 = + getTypeDefaultValue('.google.firestore.v1.RunAggregationQueryRequest', ['parent']); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; + const expectedResponse = generateSampleMessage( + new protos.google.firestore.v1.RunAggregationQueryResponse() + ); + client.innerApiCalls.runAggregationQuery = stubServerStreamingCall(expectedResponse); + const stream = client.runAggregationQuery(request); + const promise = new Promise((resolve, reject) => { + stream.on('data', (response: protos.google.firestore.v1.RunAggregationQueryResponse) => { + resolve(response); + }); + stream.on('error', (err: Error) => { + reject(err); + }); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = (client.innerApiCalls.runAggregationQuery as SinonStub) + .getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = (client.innerApiCalls.runAggregationQuery as SinonStub) + .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes runAggregationQuery with error', async () => { + const client = new firestoreModule.FirestoreClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.firestore.v1.RunAggregationQueryRequest() + ); + const defaultValue1 = + getTypeDefaultValue('.google.firestore.v1.RunAggregationQueryRequest', ['parent']); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; + const expectedError = new Error('expected'); + client.innerApiCalls.runAggregationQuery = stubServerStreamingCall(undefined, expectedError); + const stream = client.runAggregationQuery(request); + const promise = new Promise((resolve, reject) => { + stream.on('data', (response: protos.google.firestore.v1.RunAggregationQueryResponse) => { + resolve(response); + }); + stream.on('error', (err: Error) => { + reject(err); + }); + }); + await assert.rejects(promise, expectedError); + const actualRequest = (client.innerApiCalls.runAggregationQuery as SinonStub) + .getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = (client.innerApiCalls.runAggregationQuery as SinonStub) + .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes runAggregationQuery with closed client', async () => { + const client = new firestoreModule.FirestoreClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.firestore.v1.RunAggregationQueryRequest() + ); + const defaultValue1 = + getTypeDefaultValue('.google.firestore.v1.RunAggregationQueryRequest', ['parent']); + request.parent = defaultValue1; + const expectedError = new Error('The client has already been closed.'); + client.close().catch(err => {throw err}); + const stream = client.runAggregationQuery(request, {retryRequestOptions: {noResponseRetries: 0}}); + const promise = new Promise((resolve, reject) => { + stream.on('data', (response: protos.google.firestore.v1.RunAggregationQueryResponse) => { + resolve(response); + }); + stream.on('error', (err: Error) => { + reject(err); + }); + }); + await assert.rejects(promise, expectedError); + }); + it('should create a client with gaxServerStreamingRetries enabled', () => { + const client = new firestoreModule.FirestoreClient({ + gaxServerStreamingRetries: true, + }); + assert(client); + }); }); - it('uses async iteration with listDocuments with error', async () => { - const client = new firestoreModule.FirestoreClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.initialize(); - const request = generateSampleMessage( - new protos.google.firestore.v1.ListDocumentsRequest() - ); - const defaultValue1 = getTypeDefaultValue( - '.google.firestore.v1.ListDocumentsRequest', - ['parent'] - ); - request.parent = defaultValue1; - const defaultValue2 = getTypeDefaultValue( - '.google.firestore.v1.ListDocumentsRequest', - ['collectionId'] - ); - request.collectionId = defaultValue2; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}&collection_id=${defaultValue2 ?? ''}`; - const expectedError = new Error('expected'); - client.descriptors.page.listDocuments.asyncIterate = - stubAsyncIterationCall(undefined, expectedError); - const iterable = client.listDocumentsAsync(request); - await assert.rejects(async () => { - const responses: protos.google.firestore.v1.IDocument[] = []; - for await (const resource of iterable) { - responses.push(resource!); - } - }); - assert.deepStrictEqual( - ( - client.descriptors.page.listDocuments.asyncIterate as SinonStub - ).getCall(0).args[1], - request - ); - assert( - (client.descriptors.page.listDocuments.asyncIterate as SinonStub) - .getCall(0) - .args[2].otherArgs.headers[ - 'x-goog-request-params' - ].includes(expectedHeaderRequestParams) - ); + describe('write', () => { + it('invokes write without error', async () => { + const client = new firestoreModule.FirestoreClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.firestore.v1.WriteRequest() + ); + + const expectedResponse = generateSampleMessage( + new protos.google.firestore.v1.WriteResponse() + ); + client.innerApiCalls.write = stubBidiStreamingCall(expectedResponse); + const stream = client.write(); + const promise = new Promise((resolve, reject) => { + stream.on('data', (response: protos.google.firestore.v1.WriteResponse) => { + resolve(response); + }); + stream.on('error', (err: Error) => { + reject(err); + }); + stream.write(request); + stream.end(); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + assert((client.innerApiCalls.write as SinonStub) + .getCall(0).calledWith(null)); + assert.deepStrictEqual(((stream as unknown as PassThrough) + ._transform as SinonStub).getCall(0).args[0], request); + }); + + it('invokes write with error', async () => { + const client = new firestoreModule.FirestoreClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.firestore.v1.WriteRequest() + ); + const expectedError = new Error('expected'); + client.innerApiCalls.write = stubBidiStreamingCall(undefined, expectedError); + const stream = client.write(); + const promise = new Promise((resolve, reject) => { + stream.on('data', (response: protos.google.firestore.v1.WriteResponse) => { + resolve(response); + }); + stream.on('error', (err: Error) => { + reject(err); + }); + stream.write(request); + stream.end(); + }); + await assert.rejects(promise, expectedError); + assert((client.innerApiCalls.write as SinonStub) + .getCall(0).calledWith(null)); + assert.deepStrictEqual(((stream as unknown as PassThrough) + ._transform as SinonStub).getCall(0).args[0], request); + }); }); - }); - - describe('partitionQuery', () => { - it('invokes partitionQuery without error', async () => { - const client = new firestoreModule.FirestoreClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.initialize(); - const request = generateSampleMessage( - new protos.google.firestore.v1.PartitionQueryRequest() - ); - const defaultValue1 = getTypeDefaultValue( - '.google.firestore.v1.PartitionQueryRequest', - ['parent'] - ); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; - const expectedResponse = [ - generateSampleMessage(new protos.google.firestore.v1.Cursor()), - generateSampleMessage(new protos.google.firestore.v1.Cursor()), - generateSampleMessage(new protos.google.firestore.v1.Cursor()), - ]; - client.innerApiCalls.partitionQuery = stubSimpleCall(expectedResponse); - const [response] = await client.partitionQuery(request); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = ( - client.innerApiCalls.partitionQuery as SinonStub - ).getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = ( - client.innerApiCalls.partitionQuery as SinonStub - ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + + describe('listen', () => { + it('invokes listen without error', async () => { + const client = new firestoreModule.FirestoreClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.firestore.v1.ListenRequest() + ); + + const expectedResponse = generateSampleMessage( + new protos.google.firestore.v1.ListenResponse() + ); + client.innerApiCalls.listen = stubBidiStreamingCall(expectedResponse); + const stream = client.listen(); + const promise = new Promise((resolve, reject) => { + stream.on('data', (response: protos.google.firestore.v1.ListenResponse) => { + resolve(response); + }); + stream.on('error', (err: Error) => { + reject(err); + }); + stream.write(request); + stream.end(); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + assert((client.innerApiCalls.listen as SinonStub) + .getCall(0).calledWith(null)); + assert.deepStrictEqual(((stream as unknown as PassThrough) + ._transform as SinonStub).getCall(0).args[0], request); + }); + + it('invokes listen with error', async () => { + const client = new firestoreModule.FirestoreClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.firestore.v1.ListenRequest() + ); + const expectedError = new Error('expected'); + client.innerApiCalls.listen = stubBidiStreamingCall(undefined, expectedError); + const stream = client.listen(); + const promise = new Promise((resolve, reject) => { + stream.on('data', (response: protos.google.firestore.v1.ListenResponse) => { + resolve(response); + }); + stream.on('error', (err: Error) => { + reject(err); + }); + stream.write(request); + stream.end(); + }); + await assert.rejects(promise, expectedError); + assert((client.innerApiCalls.listen as SinonStub) + .getCall(0).calledWith(null)); + assert.deepStrictEqual(((stream as unknown as PassThrough) + ._transform as SinonStub).getCall(0).args[0], request); + }); }); - it('invokes partitionQuery without error using callback', async () => { - const client = new firestoreModule.FirestoreClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.initialize(); - const request = generateSampleMessage( - new protos.google.firestore.v1.PartitionQueryRequest() - ); - const defaultValue1 = getTypeDefaultValue( - '.google.firestore.v1.PartitionQueryRequest', - ['parent'] - ); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; - const expectedResponse = [ - generateSampleMessage(new protos.google.firestore.v1.Cursor()), - generateSampleMessage(new protos.google.firestore.v1.Cursor()), - generateSampleMessage(new protos.google.firestore.v1.Cursor()), - ]; - client.innerApiCalls.partitionQuery = - stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.partitionQuery( - request, - ( - err?: Error | null, - result?: protos.google.firestore.v1.ICursor[] | null - ) => { - if (err) { - reject(err); - } else { - resolve(result); + describe('listDocuments', () => { + it('invokes listDocuments without error', async () => { + const client = new firestoreModule.FirestoreClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.firestore.v1.ListDocumentsRequest() + ); + const defaultValue1 = + getTypeDefaultValue('.google.firestore.v1.ListDocumentsRequest', ['parent']); + request.parent = defaultValue1; + const defaultValue2 = + getTypeDefaultValue('.google.firestore.v1.ListDocumentsRequest', ['collectionId']); + request.collectionId = defaultValue2; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }&collection_id=${defaultValue2 ?? '' }`;const expectedResponse = [ + generateSampleMessage(new protos.google.firestore.v1.Document()), + generateSampleMessage(new protos.google.firestore.v1.Document()), + generateSampleMessage(new protos.google.firestore.v1.Document()), + ]; + client.innerApiCalls.listDocuments = stubSimpleCall(expectedResponse); + const [response] = await client.listDocuments(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = (client.innerApiCalls.listDocuments as SinonStub) + .getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = (client.innerApiCalls.listDocuments as SinonStub) + .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes listDocuments without error using callback', async () => { + const client = new firestoreModule.FirestoreClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.firestore.v1.ListDocumentsRequest() + ); + const defaultValue1 = + getTypeDefaultValue('.google.firestore.v1.ListDocumentsRequest', ['parent']); + request.parent = defaultValue1; + const defaultValue2 = + getTypeDefaultValue('.google.firestore.v1.ListDocumentsRequest', ['collectionId']); + request.collectionId = defaultValue2; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }&collection_id=${defaultValue2 ?? '' }`;const expectedResponse = [ + generateSampleMessage(new protos.google.firestore.v1.Document()), + generateSampleMessage(new protos.google.firestore.v1.Document()), + generateSampleMessage(new protos.google.firestore.v1.Document()), + ]; + client.innerApiCalls.listDocuments = stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.listDocuments( + request, + (err?: Error|null, result?: protos.google.firestore.v1.IDocument[]|null) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = (client.innerApiCalls.listDocuments as SinonStub) + .getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = (client.innerApiCalls.listDocuments as SinonStub) + .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes listDocuments with error', async () => { + const client = new firestoreModule.FirestoreClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.firestore.v1.ListDocumentsRequest() + ); + const defaultValue1 = + getTypeDefaultValue('.google.firestore.v1.ListDocumentsRequest', ['parent']); + request.parent = defaultValue1; + const defaultValue2 = + getTypeDefaultValue('.google.firestore.v1.ListDocumentsRequest', ['collectionId']); + request.collectionId = defaultValue2; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }&collection_id=${defaultValue2 ?? '' }`; + const expectedError = new Error('expected'); + client.innerApiCalls.listDocuments = stubSimpleCall(undefined, expectedError); + await assert.rejects(client.listDocuments(request), expectedError); + const actualRequest = (client.innerApiCalls.listDocuments as SinonStub) + .getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = (client.innerApiCalls.listDocuments as SinonStub) + .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); + + it('invokes listDocumentsStream without error', async () => { + const client = new firestoreModule.FirestoreClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.firestore.v1.ListDocumentsRequest() + ); + const defaultValue1 = + getTypeDefaultValue('.google.firestore.v1.ListDocumentsRequest', ['parent']); + request.parent = defaultValue1; + const defaultValue2 = + getTypeDefaultValue('.google.firestore.v1.ListDocumentsRequest', ['collectionId']); + request.collectionId = defaultValue2; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }&collection_id=${defaultValue2 ?? '' }`; + const expectedResponse = [ + generateSampleMessage(new protos.google.firestore.v1.Document()), + generateSampleMessage(new protos.google.firestore.v1.Document()), + generateSampleMessage(new protos.google.firestore.v1.Document()), + ]; + client.descriptors.page.listDocuments.createStream = stubPageStreamingCall(expectedResponse); + const stream = client.listDocumentsStream(request); + const promise = new Promise((resolve, reject) => { + const responses: protos.google.firestore.v1.Document[] = []; + stream.on('data', (response: protos.google.firestore.v1.Document) => { + responses.push(response); + }); + stream.on('end', () => { + resolve(responses); + }); + stream.on('error', (err: Error) => { + reject(err); + }); + }); + const responses = await promise; + assert.deepStrictEqual(responses, expectedResponse); + assert((client.descriptors.page.listDocuments.createStream as SinonStub) + .getCall(0).calledWith(client.innerApiCalls.listDocuments, request)); + assert( + (client.descriptors.page.listDocuments.createStream as SinonStub) + .getCall(0).args[2].otherArgs.headers['x-goog-request-params'].includes( + expectedHeaderRequestParams + ) + ); + }); + + it('invokes listDocumentsStream with error', async () => { + const client = new firestoreModule.FirestoreClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.firestore.v1.ListDocumentsRequest() + ); + const defaultValue1 = + getTypeDefaultValue('.google.firestore.v1.ListDocumentsRequest', ['parent']); + request.parent = defaultValue1; + const defaultValue2 = + getTypeDefaultValue('.google.firestore.v1.ListDocumentsRequest', ['collectionId']); + request.collectionId = defaultValue2; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }&collection_id=${defaultValue2 ?? '' }`; + const expectedError = new Error('expected'); + client.descriptors.page.listDocuments.createStream = stubPageStreamingCall(undefined, expectedError); + const stream = client.listDocumentsStream(request); + const promise = new Promise((resolve, reject) => { + const responses: protos.google.firestore.v1.Document[] = []; + stream.on('data', (response: protos.google.firestore.v1.Document) => { + responses.push(response); + }); + stream.on('end', () => { + resolve(responses); + }); + stream.on('error', (err: Error) => { + reject(err); + }); + }); + await assert.rejects(promise, expectedError); + assert((client.descriptors.page.listDocuments.createStream as SinonStub) + .getCall(0).calledWith(client.innerApiCalls.listDocuments, request)); + assert( + (client.descriptors.page.listDocuments.createStream as SinonStub) + .getCall(0).args[2].otherArgs.headers['x-goog-request-params'].includes( + expectedHeaderRequestParams + ) + ); + }); + + it('uses async iteration with listDocuments without error', async () => { + const client = new firestoreModule.FirestoreClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.firestore.v1.ListDocumentsRequest() + ); + const defaultValue1 = + getTypeDefaultValue('.google.firestore.v1.ListDocumentsRequest', ['parent']); + request.parent = defaultValue1; + const defaultValue2 = + getTypeDefaultValue('.google.firestore.v1.ListDocumentsRequest', ['collectionId']); + request.collectionId = defaultValue2; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }&collection_id=${defaultValue2 ?? '' }`; + const expectedResponse = [ + generateSampleMessage(new protos.google.firestore.v1.Document()), + generateSampleMessage(new protos.google.firestore.v1.Document()), + generateSampleMessage(new protos.google.firestore.v1.Document()), + ]; + client.descriptors.page.listDocuments.asyncIterate = stubAsyncIterationCall(expectedResponse); + const responses: protos.google.firestore.v1.IDocument[] = []; + const iterable = client.listDocumentsAsync(request); + for await (const resource of iterable) { + responses.push(resource!); } - } - ); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = ( - client.innerApiCalls.partitionQuery as SinonStub - ).getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = ( - client.innerApiCalls.partitionQuery as SinonStub - ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + assert.deepStrictEqual(responses, expectedResponse); + assert.deepStrictEqual( + (client.descriptors.page.listDocuments.asyncIterate as SinonStub) + .getCall(0).args[1], request); + assert( + (client.descriptors.page.listDocuments.asyncIterate as SinonStub) + .getCall(0).args[2].otherArgs.headers['x-goog-request-params'].includes( + expectedHeaderRequestParams + ) + ); + }); - it('invokes partitionQuery with error', async () => { - const client = new firestoreModule.FirestoreClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.initialize(); - const request = generateSampleMessage( - new protos.google.firestore.v1.PartitionQueryRequest() - ); - const defaultValue1 = getTypeDefaultValue( - '.google.firestore.v1.PartitionQueryRequest', - ['parent'] - ); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; - const expectedError = new Error('expected'); - client.innerApiCalls.partitionQuery = stubSimpleCall( - undefined, - expectedError - ); - await assert.rejects(client.partitionQuery(request), expectedError); - const actualRequest = ( - client.innerApiCalls.partitionQuery as SinonStub - ).getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = ( - client.innerApiCalls.partitionQuery as SinonStub - ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + it('uses async iteration with listDocuments with error', async () => { + const client = new firestoreModule.FirestoreClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.firestore.v1.ListDocumentsRequest() + ); + const defaultValue1 = + getTypeDefaultValue('.google.firestore.v1.ListDocumentsRequest', ['parent']); + request.parent = defaultValue1; + const defaultValue2 = + getTypeDefaultValue('.google.firestore.v1.ListDocumentsRequest', ['collectionId']); + request.collectionId = defaultValue2; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }&collection_id=${defaultValue2 ?? '' }`; + const expectedError = new Error('expected'); + client.descriptors.page.listDocuments.asyncIterate = stubAsyncIterationCall(undefined, expectedError); + const iterable = client.listDocumentsAsync(request); + await assert.rejects(async () => { + const responses: protos.google.firestore.v1.IDocument[] = []; + for await (const resource of iterable) { + responses.push(resource!); + } + }); + assert.deepStrictEqual( + (client.descriptors.page.listDocuments.asyncIterate as SinonStub) + .getCall(0).args[1], request); + assert( + (client.descriptors.page.listDocuments.asyncIterate as SinonStub) + .getCall(0).args[2].otherArgs.headers['x-goog-request-params'].includes( + expectedHeaderRequestParams + ) + ); + }); }); - it('invokes partitionQueryStream without error', async () => { - const client = new firestoreModule.FirestoreClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.initialize(); - const request = generateSampleMessage( - new protos.google.firestore.v1.PartitionQueryRequest() - ); - const defaultValue1 = getTypeDefaultValue( - '.google.firestore.v1.PartitionQueryRequest', - ['parent'] - ); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; - const expectedResponse = [ - generateSampleMessage(new protos.google.firestore.v1.Cursor()), - generateSampleMessage(new protos.google.firestore.v1.Cursor()), - generateSampleMessage(new protos.google.firestore.v1.Cursor()), - ]; - client.descriptors.page.partitionQuery.createStream = - stubPageStreamingCall(expectedResponse); - const stream = client.partitionQueryStream(request); - const promise = new Promise((resolve, reject) => { - const responses: protos.google.firestore.v1.Cursor[] = []; - stream.on('data', (response: protos.google.firestore.v1.Cursor) => { - responses.push(response); - }); - stream.on('end', () => { - resolve(responses); - }); - stream.on('error', (err: Error) => { - reject(err); - }); - }); - const responses = await promise; - assert.deepStrictEqual(responses, expectedResponse); - assert( - (client.descriptors.page.partitionQuery.createStream as SinonStub) - .getCall(0) - .calledWith(client.innerApiCalls.partitionQuery, request) - ); - assert( - (client.descriptors.page.partitionQuery.createStream as SinonStub) - .getCall(0) - .args[2].otherArgs.headers[ - 'x-goog-request-params' - ].includes(expectedHeaderRequestParams) - ); - }); + describe('partitionQuery', () => { + it('invokes partitionQuery without error', async () => { + const client = new firestoreModule.FirestoreClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.firestore.v1.PartitionQueryRequest() + ); + const defaultValue1 = + getTypeDefaultValue('.google.firestore.v1.PartitionQueryRequest', ['parent']); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`;const expectedResponse = [ + generateSampleMessage(new protos.google.firestore.v1.Cursor()), + generateSampleMessage(new protos.google.firestore.v1.Cursor()), + generateSampleMessage(new protos.google.firestore.v1.Cursor()), + ]; + client.innerApiCalls.partitionQuery = stubSimpleCall(expectedResponse); + const [response] = await client.partitionQuery(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = (client.innerApiCalls.partitionQuery as SinonStub) + .getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = (client.innerApiCalls.partitionQuery as SinonStub) + .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes partitionQueryStream with error', async () => { - const client = new firestoreModule.FirestoreClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.initialize(); - const request = generateSampleMessage( - new protos.google.firestore.v1.PartitionQueryRequest() - ); - const defaultValue1 = getTypeDefaultValue( - '.google.firestore.v1.PartitionQueryRequest', - ['parent'] - ); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; - const expectedError = new Error('expected'); - client.descriptors.page.partitionQuery.createStream = - stubPageStreamingCall(undefined, expectedError); - const stream = client.partitionQueryStream(request); - const promise = new Promise((resolve, reject) => { - const responses: protos.google.firestore.v1.Cursor[] = []; - stream.on('data', (response: protos.google.firestore.v1.Cursor) => { - responses.push(response); - }); - stream.on('end', () => { - resolve(responses); - }); - stream.on('error', (err: Error) => { - reject(err); - }); - }); - await assert.rejects(promise, expectedError); - assert( - (client.descriptors.page.partitionQuery.createStream as SinonStub) - .getCall(0) - .calledWith(client.innerApiCalls.partitionQuery, request) - ); - assert( - (client.descriptors.page.partitionQuery.createStream as SinonStub) - .getCall(0) - .args[2].otherArgs.headers[ - 'x-goog-request-params' - ].includes(expectedHeaderRequestParams) - ); - }); + it('invokes partitionQuery without error using callback', async () => { + const client = new firestoreModule.FirestoreClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.firestore.v1.PartitionQueryRequest() + ); + const defaultValue1 = + getTypeDefaultValue('.google.firestore.v1.PartitionQueryRequest', ['parent']); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`;const expectedResponse = [ + generateSampleMessage(new protos.google.firestore.v1.Cursor()), + generateSampleMessage(new protos.google.firestore.v1.Cursor()), + generateSampleMessage(new protos.google.firestore.v1.Cursor()), + ]; + client.innerApiCalls.partitionQuery = stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.partitionQuery( + request, + (err?: Error|null, result?: protos.google.firestore.v1.ICursor[]|null) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = (client.innerApiCalls.partitionQuery as SinonStub) + .getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = (client.innerApiCalls.partitionQuery as SinonStub) + .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('uses async iteration with partitionQuery without error', async () => { - const client = new firestoreModule.FirestoreClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.initialize(); - const request = generateSampleMessage( - new protos.google.firestore.v1.PartitionQueryRequest() - ); - const defaultValue1 = getTypeDefaultValue( - '.google.firestore.v1.PartitionQueryRequest', - ['parent'] - ); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; - const expectedResponse = [ - generateSampleMessage(new protos.google.firestore.v1.Cursor()), - generateSampleMessage(new protos.google.firestore.v1.Cursor()), - generateSampleMessage(new protos.google.firestore.v1.Cursor()), - ]; - client.descriptors.page.partitionQuery.asyncIterate = - stubAsyncIterationCall(expectedResponse); - const responses: protos.google.firestore.v1.ICursor[] = []; - const iterable = client.partitionQueryAsync(request); - for await (const resource of iterable) { - responses.push(resource!); - } - assert.deepStrictEqual(responses, expectedResponse); - assert.deepStrictEqual( - ( - client.descriptors.page.partitionQuery.asyncIterate as SinonStub - ).getCall(0).args[1], - request - ); - assert( - (client.descriptors.page.partitionQuery.asyncIterate as SinonStub) - .getCall(0) - .args[2].otherArgs.headers[ - 'x-goog-request-params' - ].includes(expectedHeaderRequestParams) - ); - }); + it('invokes partitionQuery with error', async () => { + const client = new firestoreModule.FirestoreClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.firestore.v1.PartitionQueryRequest() + ); + const defaultValue1 = + getTypeDefaultValue('.google.firestore.v1.PartitionQueryRequest', ['parent']); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; + const expectedError = new Error('expected'); + client.innerApiCalls.partitionQuery = stubSimpleCall(undefined, expectedError); + await assert.rejects(client.partitionQuery(request), expectedError); + const actualRequest = (client.innerApiCalls.partitionQuery as SinonStub) + .getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = (client.innerApiCalls.partitionQuery as SinonStub) + .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('uses async iteration with partitionQuery with error', async () => { - const client = new firestoreModule.FirestoreClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.initialize(); - const request = generateSampleMessage( - new protos.google.firestore.v1.PartitionQueryRequest() - ); - const defaultValue1 = getTypeDefaultValue( - '.google.firestore.v1.PartitionQueryRequest', - ['parent'] - ); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; - const expectedError = new Error('expected'); - client.descriptors.page.partitionQuery.asyncIterate = - stubAsyncIterationCall(undefined, expectedError); - const iterable = client.partitionQueryAsync(request); - await assert.rejects(async () => { - const responses: protos.google.firestore.v1.ICursor[] = []; - for await (const resource of iterable) { - responses.push(resource!); - } - }); - assert.deepStrictEqual( - ( - client.descriptors.page.partitionQuery.asyncIterate as SinonStub - ).getCall(0).args[1], - request - ); - assert( - (client.descriptors.page.partitionQuery.asyncIterate as SinonStub) - .getCall(0) - .args[2].otherArgs.headers[ - 'x-goog-request-params' - ].includes(expectedHeaderRequestParams) - ); - }); - }); - - describe('listCollectionIds', () => { - it('invokes listCollectionIds without error', async () => { - const client = new firestoreModule.FirestoreClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.initialize(); - const request = generateSampleMessage( - new protos.google.firestore.v1.ListCollectionIdsRequest() - ); - const defaultValue1 = getTypeDefaultValue( - '.google.firestore.v1.ListCollectionIdsRequest', - ['parent'] - ); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; - const expectedResponse = [new String(), new String(), new String()]; - client.innerApiCalls.listCollectionIds = stubSimpleCall(expectedResponse); - const [response] = await client.listCollectionIds(request); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = ( - client.innerApiCalls.listCollectionIds as SinonStub - ).getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = ( - client.innerApiCalls.listCollectionIds as SinonStub - ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes partitionQueryStream without error', async () => { + const client = new firestoreModule.FirestoreClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.firestore.v1.PartitionQueryRequest() + ); + const defaultValue1 = + getTypeDefaultValue('.google.firestore.v1.PartitionQueryRequest', ['parent']); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; + const expectedResponse = [ + generateSampleMessage(new protos.google.firestore.v1.Cursor()), + generateSampleMessage(new protos.google.firestore.v1.Cursor()), + generateSampleMessage(new protos.google.firestore.v1.Cursor()), + ]; + client.descriptors.page.partitionQuery.createStream = stubPageStreamingCall(expectedResponse); + const stream = client.partitionQueryStream(request); + const promise = new Promise((resolve, reject) => { + const responses: protos.google.firestore.v1.Cursor[] = []; + stream.on('data', (response: protos.google.firestore.v1.Cursor) => { + responses.push(response); + }); + stream.on('end', () => { + resolve(responses); + }); + stream.on('error', (err: Error) => { + reject(err); + }); + }); + const responses = await promise; + assert.deepStrictEqual(responses, expectedResponse); + assert((client.descriptors.page.partitionQuery.createStream as SinonStub) + .getCall(0).calledWith(client.innerApiCalls.partitionQuery, request)); + assert( + (client.descriptors.page.partitionQuery.createStream as SinonStub) + .getCall(0).args[2].otherArgs.headers['x-goog-request-params'].includes( + expectedHeaderRequestParams + ) + ); + }); - it('invokes listCollectionIds without error using callback', async () => { - const client = new firestoreModule.FirestoreClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.initialize(); - const request = generateSampleMessage( - new protos.google.firestore.v1.ListCollectionIdsRequest() - ); - const defaultValue1 = getTypeDefaultValue( - '.google.firestore.v1.ListCollectionIdsRequest', - ['parent'] - ); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; - const expectedResponse = [new String(), new String(), new String()]; - client.innerApiCalls.listCollectionIds = - stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.listCollectionIds( - request, - (err?: Error | null, result?: string[] | null) => { - if (err) { - reject(err); - } else { - resolve(result); + it('invokes partitionQueryStream with error', async () => { + const client = new firestoreModule.FirestoreClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.firestore.v1.PartitionQueryRequest() + ); + const defaultValue1 = + getTypeDefaultValue('.google.firestore.v1.PartitionQueryRequest', ['parent']); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; + const expectedError = new Error('expected'); + client.descriptors.page.partitionQuery.createStream = stubPageStreamingCall(undefined, expectedError); + const stream = client.partitionQueryStream(request); + const promise = new Promise((resolve, reject) => { + const responses: protos.google.firestore.v1.Cursor[] = []; + stream.on('data', (response: protos.google.firestore.v1.Cursor) => { + responses.push(response); + }); + stream.on('end', () => { + resolve(responses); + }); + stream.on('error', (err: Error) => { + reject(err); + }); + }); + await assert.rejects(promise, expectedError); + assert((client.descriptors.page.partitionQuery.createStream as SinonStub) + .getCall(0).calledWith(client.innerApiCalls.partitionQuery, request)); + assert( + (client.descriptors.page.partitionQuery.createStream as SinonStub) + .getCall(0).args[2].otherArgs.headers['x-goog-request-params'].includes( + expectedHeaderRequestParams + ) + ); + }); + + it('uses async iteration with partitionQuery without error', async () => { + const client = new firestoreModule.FirestoreClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.firestore.v1.PartitionQueryRequest() + ); + const defaultValue1 = + getTypeDefaultValue('.google.firestore.v1.PartitionQueryRequest', ['parent']); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; + const expectedResponse = [ + generateSampleMessage(new protos.google.firestore.v1.Cursor()), + generateSampleMessage(new protos.google.firestore.v1.Cursor()), + generateSampleMessage(new protos.google.firestore.v1.Cursor()), + ]; + client.descriptors.page.partitionQuery.asyncIterate = stubAsyncIterationCall(expectedResponse); + const responses: protos.google.firestore.v1.ICursor[] = []; + const iterable = client.partitionQueryAsync(request); + for await (const resource of iterable) { + responses.push(resource!); } - } - ); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = ( - client.innerApiCalls.listCollectionIds as SinonStub - ).getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = ( - client.innerApiCalls.listCollectionIds as SinonStub - ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + assert.deepStrictEqual(responses, expectedResponse); + assert.deepStrictEqual( + (client.descriptors.page.partitionQuery.asyncIterate as SinonStub) + .getCall(0).args[1], request); + assert( + (client.descriptors.page.partitionQuery.asyncIterate as SinonStub) + .getCall(0).args[2].otherArgs.headers['x-goog-request-params'].includes( + expectedHeaderRequestParams + ) + ); + }); - it('invokes listCollectionIds with error', async () => { - const client = new firestoreModule.FirestoreClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.initialize(); - const request = generateSampleMessage( - new protos.google.firestore.v1.ListCollectionIdsRequest() - ); - const defaultValue1 = getTypeDefaultValue( - '.google.firestore.v1.ListCollectionIdsRequest', - ['parent'] - ); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; - const expectedError = new Error('expected'); - client.innerApiCalls.listCollectionIds = stubSimpleCall( - undefined, - expectedError - ); - await assert.rejects(client.listCollectionIds(request), expectedError); - const actualRequest = ( - client.innerApiCalls.listCollectionIds as SinonStub - ).getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = ( - client.innerApiCalls.listCollectionIds as SinonStub - ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + it('uses async iteration with partitionQuery with error', async () => { + const client = new firestoreModule.FirestoreClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.firestore.v1.PartitionQueryRequest() + ); + const defaultValue1 = + getTypeDefaultValue('.google.firestore.v1.PartitionQueryRequest', ['parent']); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; + const expectedError = new Error('expected'); + client.descriptors.page.partitionQuery.asyncIterate = stubAsyncIterationCall(undefined, expectedError); + const iterable = client.partitionQueryAsync(request); + await assert.rejects(async () => { + const responses: protos.google.firestore.v1.ICursor[] = []; + for await (const resource of iterable) { + responses.push(resource!); + } + }); + assert.deepStrictEqual( + (client.descriptors.page.partitionQuery.asyncIterate as SinonStub) + .getCall(0).args[1], request); + assert( + (client.descriptors.page.partitionQuery.asyncIterate as SinonStub) + .getCall(0).args[2].otherArgs.headers['x-goog-request-params'].includes( + expectedHeaderRequestParams + ) + ); + }); }); - it('invokes listCollectionIdsStream without error', async () => { - const client = new firestoreModule.FirestoreClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.initialize(); - const request = generateSampleMessage( - new protos.google.firestore.v1.ListCollectionIdsRequest() - ); - const defaultValue1 = getTypeDefaultValue( - '.google.firestore.v1.ListCollectionIdsRequest', - ['parent'] - ); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; - const expectedResponse = [new String(), new String(), new String()]; - client.descriptors.page.listCollectionIds.createStream = - stubPageStreamingCall(expectedResponse); - const stream = client.listCollectionIdsStream(request); - const promise = new Promise((resolve, reject) => { - const responses: string[] = []; - stream.on('data', (response: string) => { - responses.push(response); - }); - stream.on('end', () => { - resolve(responses); - }); - stream.on('error', (err: Error) => { - reject(err); - }); - }); - const responses = await promise; - assert.deepStrictEqual(responses, expectedResponse); - assert( - (client.descriptors.page.listCollectionIds.createStream as SinonStub) - .getCall(0) - .calledWith(client.innerApiCalls.listCollectionIds, request) - ); - assert( - (client.descriptors.page.listCollectionIds.createStream as SinonStub) - .getCall(0) - .args[2].otherArgs.headers[ - 'x-goog-request-params' - ].includes(expectedHeaderRequestParams) - ); - }); + describe('listCollectionIds', () => { + it('invokes listCollectionIds without error', async () => { + const client = new firestoreModule.FirestoreClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.firestore.v1.ListCollectionIdsRequest() + ); + const defaultValue1 = + getTypeDefaultValue('.google.firestore.v1.ListCollectionIdsRequest', ['parent']); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`;const expectedResponse = [new String(), new String(), new String()]; + client.innerApiCalls.listCollectionIds = stubSimpleCall(expectedResponse); + const [response] = await client.listCollectionIds(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = (client.innerApiCalls.listCollectionIds as SinonStub) + .getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = (client.innerApiCalls.listCollectionIds as SinonStub) + .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes listCollectionIdsStream with error', async () => { - const client = new firestoreModule.FirestoreClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.initialize(); - const request = generateSampleMessage( - new protos.google.firestore.v1.ListCollectionIdsRequest() - ); - const defaultValue1 = getTypeDefaultValue( - '.google.firestore.v1.ListCollectionIdsRequest', - ['parent'] - ); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; - const expectedError = new Error('expected'); - client.descriptors.page.listCollectionIds.createStream = - stubPageStreamingCall(undefined, expectedError); - const stream = client.listCollectionIdsStream(request); - const promise = new Promise((resolve, reject) => { - const responses: string[] = []; - stream.on('data', (response: string) => { - responses.push(response); - }); - stream.on('end', () => { - resolve(responses); - }); - stream.on('error', (err: Error) => { - reject(err); - }); - }); - await assert.rejects(promise, expectedError); - assert( - (client.descriptors.page.listCollectionIds.createStream as SinonStub) - .getCall(0) - .calledWith(client.innerApiCalls.listCollectionIds, request) - ); - assert( - (client.descriptors.page.listCollectionIds.createStream as SinonStub) - .getCall(0) - .args[2].otherArgs.headers[ - 'x-goog-request-params' - ].includes(expectedHeaderRequestParams) - ); - }); + it('invokes listCollectionIds without error using callback', async () => { + const client = new firestoreModule.FirestoreClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.firestore.v1.ListCollectionIdsRequest() + ); + const defaultValue1 = + getTypeDefaultValue('.google.firestore.v1.ListCollectionIdsRequest', ['parent']); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`;const expectedResponse = [new String(), new String(), new String()]; + client.innerApiCalls.listCollectionIds = stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.listCollectionIds( + request, + (err?: Error|null, result?: string[]|null) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = (client.innerApiCalls.listCollectionIds as SinonStub) + .getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = (client.innerApiCalls.listCollectionIds as SinonStub) + .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('uses async iteration with listCollectionIds without error', async () => { - const client = new firestoreModule.FirestoreClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.initialize(); - const request = generateSampleMessage( - new protos.google.firestore.v1.ListCollectionIdsRequest() - ); - const defaultValue1 = getTypeDefaultValue( - '.google.firestore.v1.ListCollectionIdsRequest', - ['parent'] - ); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; - const expectedResponse = [new String(), new String(), new String()]; - client.descriptors.page.listCollectionIds.asyncIterate = - stubAsyncIterationCall(expectedResponse); - const responses: string[] = []; - const iterable = client.listCollectionIdsAsync(request); - for await (const resource of iterable) { - responses.push(resource!); - } - assert.deepStrictEqual(responses, expectedResponse); - assert.deepStrictEqual( - ( - client.descriptors.page.listCollectionIds.asyncIterate as SinonStub - ).getCall(0).args[1], - request - ); - assert( - (client.descriptors.page.listCollectionIds.asyncIterate as SinonStub) - .getCall(0) - .args[2].otherArgs.headers[ - 'x-goog-request-params' - ].includes(expectedHeaderRequestParams) - ); - }); + it('invokes listCollectionIds with error', async () => { + const client = new firestoreModule.FirestoreClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.firestore.v1.ListCollectionIdsRequest() + ); + const defaultValue1 = + getTypeDefaultValue('.google.firestore.v1.ListCollectionIdsRequest', ['parent']); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; + const expectedError = new Error('expected'); + client.innerApiCalls.listCollectionIds = stubSimpleCall(undefined, expectedError); + await assert.rejects(client.listCollectionIds(request), expectedError); + const actualRequest = (client.innerApiCalls.listCollectionIds as SinonStub) + .getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = (client.innerApiCalls.listCollectionIds as SinonStub) + .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('uses async iteration with listCollectionIds with error', async () => { - const client = new firestoreModule.FirestoreClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.initialize(); - const request = generateSampleMessage( - new protos.google.firestore.v1.ListCollectionIdsRequest() - ); - const defaultValue1 = getTypeDefaultValue( - '.google.firestore.v1.ListCollectionIdsRequest', - ['parent'] - ); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; - const expectedError = new Error('expected'); - client.descriptors.page.listCollectionIds.asyncIterate = - stubAsyncIterationCall(undefined, expectedError); - const iterable = client.listCollectionIdsAsync(request); - await assert.rejects(async () => { - const responses: string[] = []; - for await (const resource of iterable) { - responses.push(resource!); - } - }); - assert.deepStrictEqual( - ( - client.descriptors.page.listCollectionIds.asyncIterate as SinonStub - ).getCall(0).args[1], - request - ); - assert( - (client.descriptors.page.listCollectionIds.asyncIterate as SinonStub) - .getCall(0) - .args[2].otherArgs.headers[ - 'x-goog-request-params' - ].includes(expectedHeaderRequestParams) - ); - }); - }); - describe('getLocation', () => { - it('invokes getLocation without error', async () => { - const client = new firestoreModule.FirestoreClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.initialize(); - const request = generateSampleMessage( - new LocationProtos.google.cloud.location.GetLocationRequest() - ); - request.name = ''; - const expectedHeaderRequestParams = 'name='; - const expectedOptions = { - otherArgs: { - headers: { - 'x-goog-request-params': expectedHeaderRequestParams, - }, - }, - }; - const expectedResponse = generateSampleMessage( - new LocationProtos.google.cloud.location.Location() - ); - client.locationsClient.getLocation = stubSimpleCall(expectedResponse); - const response = await client.getLocation(request, expectedOptions); - assert.deepStrictEqual(response, [expectedResponse]); - assert( - (client.locationsClient.getLocation as SinonStub) - .getCall(0) - .calledWith(request, expectedOptions, undefined) - ); - }); - it('invokes getLocation without error using callback', async () => { - const client = new firestoreModule.FirestoreClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.initialize(); - const request = generateSampleMessage( - new LocationProtos.google.cloud.location.GetLocationRequest() - ); - request.name = ''; - const expectedHeaderRequestParams = 'name='; - const expectedOptions = { - otherArgs: { - headers: { - 'x-goog-request-params': expectedHeaderRequestParams, - }, - }, - }; - const expectedResponse = generateSampleMessage( - new LocationProtos.google.cloud.location.Location() - ); - client.locationsClient.getLocation = sinon - .stub() - .callsArgWith(2, null, expectedResponse); - const promise = new Promise((resolve, reject) => { - client.getLocation( - request, - expectedOptions, - ( - err?: Error | null, - result?: LocationProtos.google.cloud.location.ILocation | null - ) => { - if (err) { - reject(err); - } else { - resolve(result); + it('invokes listCollectionIdsStream without error', async () => { + const client = new firestoreModule.FirestoreClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.firestore.v1.ListCollectionIdsRequest() + ); + const defaultValue1 = + getTypeDefaultValue('.google.firestore.v1.ListCollectionIdsRequest', ['parent']); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; + const expectedResponse = [new String(), new String(), new String()]; + client.descriptors.page.listCollectionIds.createStream = stubPageStreamingCall(expectedResponse); + const stream = client.listCollectionIdsStream(request); + const promise = new Promise((resolve, reject) => { + const responses: string[] = []; + stream.on('data', (response: string) => { + responses.push(response); + }); + stream.on('end', () => { + resolve(responses); + }); + stream.on('error', (err: Error) => { + reject(err); + }); + }); + const responses = await promise; + assert.deepStrictEqual(responses, expectedResponse); + assert((client.descriptors.page.listCollectionIds.createStream as SinonStub) + .getCall(0).calledWith(client.innerApiCalls.listCollectionIds, request)); + assert( + (client.descriptors.page.listCollectionIds.createStream as SinonStub) + .getCall(0).args[2].otherArgs.headers['x-goog-request-params'].includes( + expectedHeaderRequestParams + ) + ); + }); + + it('invokes listCollectionIdsStream with error', async () => { + const client = new firestoreModule.FirestoreClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.firestore.v1.ListCollectionIdsRequest() + ); + const defaultValue1 = + getTypeDefaultValue('.google.firestore.v1.ListCollectionIdsRequest', ['parent']); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; + const expectedError = new Error('expected'); + client.descriptors.page.listCollectionIds.createStream = stubPageStreamingCall(undefined, expectedError); + const stream = client.listCollectionIdsStream(request); + const promise = new Promise((resolve, reject) => { + const responses: string[] = []; + stream.on('data', (response: string) => { + responses.push(response); + }); + stream.on('end', () => { + resolve(responses); + }); + stream.on('error', (err: Error) => { + reject(err); + }); + }); + await assert.rejects(promise, expectedError); + assert((client.descriptors.page.listCollectionIds.createStream as SinonStub) + .getCall(0).calledWith(client.innerApiCalls.listCollectionIds, request)); + assert( + (client.descriptors.page.listCollectionIds.createStream as SinonStub) + .getCall(0).args[2].otherArgs.headers['x-goog-request-params'].includes( + expectedHeaderRequestParams + ) + ); + }); + + it('uses async iteration with listCollectionIds without error', async () => { + const client = new firestoreModule.FirestoreClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.firestore.v1.ListCollectionIdsRequest() + ); + const defaultValue1 = + getTypeDefaultValue('.google.firestore.v1.ListCollectionIdsRequest', ['parent']); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; + const expectedResponse = [new String(), new String(), new String()]; + client.descriptors.page.listCollectionIds.asyncIterate = stubAsyncIterationCall(expectedResponse); + const responses: string[] = []; + const iterable = client.listCollectionIdsAsync(request); + for await (const resource of iterable) { + responses.push(resource!); } - } - ); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - assert((client.locationsClient.getLocation as SinonStub).getCall(0)); - }); - it('invokes getLocation with error', async () => { - const client = new firestoreModule.FirestoreClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.initialize(); - const request = generateSampleMessage( - new LocationProtos.google.cloud.location.GetLocationRequest() - ); - request.name = ''; - const expectedHeaderRequestParams = 'name='; - const expectedOptions = { - otherArgs: { - headers: { - 'x-goog-request-params': expectedHeaderRequestParams, - }, - }, - }; - const expectedError = new Error('expected'); - client.locationsClient.getLocation = stubSimpleCall( - undefined, - expectedError - ); - await assert.rejects( - client.getLocation(request, expectedOptions), - expectedError - ); - assert( - (client.locationsClient.getLocation as SinonStub) - .getCall(0) - .calledWith(request, expectedOptions, undefined) - ); + assert.deepStrictEqual(responses, expectedResponse); + assert.deepStrictEqual( + (client.descriptors.page.listCollectionIds.asyncIterate as SinonStub) + .getCall(0).args[1], request); + assert( + (client.descriptors.page.listCollectionIds.asyncIterate as SinonStub) + .getCall(0).args[2].otherArgs.headers['x-goog-request-params'].includes( + expectedHeaderRequestParams + ) + ); + }); + + it('uses async iteration with listCollectionIds with error', async () => { + const client = new firestoreModule.FirestoreClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.firestore.v1.ListCollectionIdsRequest() + ); + const defaultValue1 = + getTypeDefaultValue('.google.firestore.v1.ListCollectionIdsRequest', ['parent']); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; + const expectedError = new Error('expected'); + client.descriptors.page.listCollectionIds.asyncIterate = stubAsyncIterationCall(undefined, expectedError); + const iterable = client.listCollectionIdsAsync(request); + await assert.rejects(async () => { + const responses: string[] = []; + for await (const resource of iterable) { + responses.push(resource!); + } + }); + assert.deepStrictEqual( + (client.descriptors.page.listCollectionIds.asyncIterate as SinonStub) + .getCall(0).args[1], request); + assert( + (client.descriptors.page.listCollectionIds.asyncIterate as SinonStub) + .getCall(0).args[2].otherArgs.headers['x-goog-request-params'].includes( + expectedHeaderRequestParams + ) + ); + }); }); - }); - describe('listLocationsAsync', () => { - it('uses async iteration with listLocations without error', async () => { - const client = new firestoreModule.FirestoreClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.initialize(); - const request = generateSampleMessage( - new LocationProtos.google.cloud.location.ListLocationsRequest() - ); - request.name = ''; - const expectedHeaderRequestParams = 'name='; - const expectedResponse = [ - generateSampleMessage( - new LocationProtos.google.cloud.location.Location() - ), - generateSampleMessage( - new LocationProtos.google.cloud.location.Location() - ), - generateSampleMessage( - new LocationProtos.google.cloud.location.Location() - ), - ]; - client.locationsClient.descriptors.page.listLocations.asyncIterate = - stubAsyncIterationCall(expectedResponse); - const responses: LocationProtos.google.cloud.location.ILocation[] = []; - const iterable = client.listLocationsAsync(request); - for await (const resource of iterable) { - responses.push(resource!); - } - assert.deepStrictEqual(responses, expectedResponse); - assert.deepStrictEqual( - ( - client.locationsClient.descriptors.page.listLocations - .asyncIterate as SinonStub - ).getCall(0).args[1], - request - ); - assert( - ( - client.locationsClient.descriptors.page.listLocations - .asyncIterate as SinonStub - ) - .getCall(0) - .args[2].otherArgs.headers['x-goog-request-params'].includes( - expectedHeaderRequestParams - ) - ); + describe('getLocation', () => { + it('invokes getLocation without error', async () => { + const client = new firestoreModule.FirestoreClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new LocationProtos.google.cloud.location.GetLocationRequest() + ); + request.name = ''; + const expectedHeaderRequestParams = 'name='; + const expectedOptions = { + otherArgs: { + headers: { + 'x-goog-request-params': expectedHeaderRequestParams, + }, + }, + }; + const expectedResponse = generateSampleMessage( + new LocationProtos.google.cloud.location.Location() + ); + client.locationsClient.getLocation = stubSimpleCall(expectedResponse); + const response = await client.getLocation(request, expectedOptions); + assert.deepStrictEqual(response, [expectedResponse]); + assert((client.locationsClient.getLocation as SinonStub) + .getCall(0).calledWith(request, expectedOptions, undefined)); + }); + it('invokes getLocation without error using callback', async () => { + const client = new firestoreModule.FirestoreClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new LocationProtos.google.cloud.location.GetLocationRequest() + ); + request.name = ''; + const expectedHeaderRequestParams = 'name='; + const expectedOptions = { + otherArgs: { + headers: { + 'x-goog-request-params': expectedHeaderRequestParams, + }, + }, + }; + const expectedResponse = generateSampleMessage( + new LocationProtos.google.cloud.location.Location() + ); + client.locationsClient.getLocation = sinon.stub().callsArgWith(2, null, expectedResponse); + const promise = new Promise((resolve, reject) => { + client.getLocation( + request, + expectedOptions, + ( + err?: Error | null, + result?: LocationProtos.google.cloud.location.ILocation | null + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + }); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + assert((client.locationsClient.getLocation as SinonStub) + .getCall(0)); + }); + it('invokes getLocation with error', async () => { + const client = new firestoreModule.FirestoreClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new LocationProtos.google.cloud.location.GetLocationRequest() + ); + request.name = ''; + const expectedHeaderRequestParams = 'name='; + const expectedOptions = { + otherArgs: { + headers: { + 'x-goog-request-params': expectedHeaderRequestParams, + }, + }, + }; + const expectedError = new Error('expected'); + client.locationsClient.getLocation = stubSimpleCall(undefined, expectedError); + await assert.rejects(client.getLocation(request, expectedOptions), expectedError); + assert((client.locationsClient.getLocation as SinonStub) + .getCall(0).calledWith(request, expectedOptions, undefined)); + }); }); - it('uses async iteration with listLocations with error', async () => { - const client = new firestoreModule.FirestoreClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.initialize(); - const request = generateSampleMessage( - new LocationProtos.google.cloud.location.ListLocationsRequest() - ); - request.name = ''; - const expectedHeaderRequestParams = 'name='; - const expectedError = new Error('expected'); - client.locationsClient.descriptors.page.listLocations.asyncIterate = - stubAsyncIterationCall(undefined, expectedError); - const iterable = client.listLocationsAsync(request); - await assert.rejects(async () => { - const responses: LocationProtos.google.cloud.location.ILocation[] = []; - for await (const resource of iterable) { - responses.push(resource!); - } - }); - assert.deepStrictEqual( - ( - client.locationsClient.descriptors.page.listLocations - .asyncIterate as SinonStub - ).getCall(0).args[1], - request - ); - assert( - ( - client.locationsClient.descriptors.page.listLocations - .asyncIterate as SinonStub - ) - .getCall(0) - .args[2].otherArgs.headers['x-goog-request-params'].includes( - expectedHeaderRequestParams - ) - ); + describe('listLocationsAsync', () => { + it('uses async iteration with listLocations without error', async () => { + const client = new firestoreModule.FirestoreClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new LocationProtos.google.cloud.location.ListLocationsRequest() + ); + request.name = ''; + const expectedHeaderRequestParams = 'name='; + const expectedResponse = [ + generateSampleMessage( + new LocationProtos.google.cloud.location.Location() + ), + generateSampleMessage( + new LocationProtos.google.cloud.location.Location() + ), + generateSampleMessage( + new LocationProtos.google.cloud.location.Location() + ), + ]; + client.locationsClient.descriptors.page.listLocations.asyncIterate = stubAsyncIterationCall(expectedResponse); + const responses: LocationProtos.google.cloud.location.ILocation[] = []; + const iterable = client.listLocationsAsync(request); + for await (const resource of iterable) { + responses.push(resource!); + } + assert.deepStrictEqual(responses, expectedResponse); + assert.deepStrictEqual( + (client.locationsClient.descriptors.page.listLocations.asyncIterate as SinonStub) + .getCall(0).args[1], request); + assert( + (client.locationsClient.descriptors.page.listLocations.asyncIterate as SinonStub) + .getCall(0).args[2].otherArgs.headers['x-goog-request-params'].includes( + expectedHeaderRequestParams + ) + ); + }); + it('uses async iteration with listLocations with error', async () => { + const client = new firestoreModule.FirestoreClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new LocationProtos.google.cloud.location.ListLocationsRequest() + ); + request.name = ''; + const expectedHeaderRequestParams = 'name='; + const expectedError = new Error('expected'); + client.locationsClient.descriptors.page.listLocations.asyncIterate = stubAsyncIterationCall(undefined, expectedError); + const iterable = client.listLocationsAsync(request); + await assert.rejects(async () => { + const responses: LocationProtos.google.cloud.location.ILocation[] = []; + for await (const resource of iterable) { + responses.push(resource!); + } + }); + assert.deepStrictEqual( + (client.locationsClient.descriptors.page.listLocations.asyncIterate as SinonStub) + .getCall(0).args[1], request); + assert( + (client.locationsClient.descriptors.page.listLocations.asyncIterate as SinonStub) + .getCall(0).args[2].otherArgs.headers['x-goog-request-params'].includes( + expectedHeaderRequestParams + ) + ); + }); }); - }); }); diff --git a/package.json b/package.json index ec15eaa4e..301fc1156 100644 --- a/package.json +++ b/package.json @@ -66,7 +66,7 @@ "@opentelemetry/api": "^1.3.0", "fast-deep-equal": "^3.1.1", "functional-red-black-tree": "^1.0.1", - "google-gax": "^4.3.3", + "google-gax": "^5.0.0", "protobufjs": "^7.2.6" }, "devDependencies": { From 8f9d6365323a74cc84bfe9c112d7bf9e5011c6b4 Mon Sep 17 00:00:00 2001 From: Mark Duckworth <1124037+MarkDuckworth@users.noreply.github.com> Date: Wed, 23 Jul 2025 14:42:19 -0600 Subject: [PATCH 40/60] feat: separate pipelines API into a subpackage '@google-cloud/firestore/pipelines' (#2332) * Separate pipelines API into a subpackages * Finish refactoring Pipelines to namespace of the main module export. Also include @google-cloud/firestore/pipelines as an alternative submodule import * Updated samples and added placeholder in readme partials, for pipelines * Update signatures of add and multiply to take exactly 2 args * Correct the copyright pipelines-quickstart.js --- .readme-partials.yaml | 3 + dev/src/index.ts | 112 +- dev/src/{ => pipelines}/expression.ts | 1212 +- dev/src/pipelines/index.ts | 121 + dev/src/{ => pipelines}/pipeline-util.ts | 58 +- .../{pipeline.ts => pipelines/pipelines.ts} | 114 +- dev/src/{ => pipelines}/stage.ts | 23 +- dev/src/reference/aggregate-query.ts | 8 +- dev/src/reference/query.ts | 10 +- dev/src/reference/types.ts | 2 +- dev/src/reference/vector-query.ts | 6 +- dev/src/serializer.ts | 2 +- dev/src/transaction.ts | 14 +- dev/system-test/pipeline.ts | 27 +- package.json | 14 +- pipelines/package.json | 10 + samples/pipelines-quickstart.js | 56 + types/firestore.d.ts | 11058 ++++++++-------- types/pipelines.d.ts | 28 + 19 files changed, 6371 insertions(+), 6507 deletions(-) rename dev/src/{ => pipelines}/expression.ts (88%) create mode 100644 dev/src/pipelines/index.ts rename dev/src/{ => pipelines}/pipeline-util.ts (96%) rename dev/src/{pipeline.ts => pipelines/pipelines.ts} (93%) rename dev/src/{ => pipelines}/stage.ts (95%) create mode 100644 pipelines/package.json create mode 100644 samples/pipelines-quickstart.js create mode 100644 types/pipelines.d.ts diff --git a/.readme-partials.yaml b/.readme-partials.yaml index bebbd9745..af7282e76 100644 --- a/.readme-partials.yaml +++ b/.readme-partials.yaml @@ -8,3 +8,6 @@ introduction: |- Applications that use Google's Server SDKs should not be used in end-user environments, such as on phones or on publicly hosted websites. If you are developing a Web or Node.js application that accesses Cloud Firestore on behalf of end users, use the firebase Client SDK. **Note:** This Cloud Firestore Server SDK does not support Firestore databases created in [Datastore mode](https://cloud.google.com/datastore/docs/firestore-or-datastore#in_datastore_mode). To access these databases, use the [Datastore SDK](https://www.npmjs.com/package/@google-cloud/datastore). + +body: |- + TODO (piplines) - cover Piplines getting started content diff --git a/dev/src/index.ts b/dev/src/index.ts index 184eaa7d2..9a13346be 100644 --- a/dev/src/index.ts +++ b/dev/src/index.ts @@ -41,7 +41,6 @@ import { ResourcePath, validateResourcePath, } from './path'; -import {PipelineSource} from './pipeline'; import {ClientPool} from './pool'; import {CollectionReference} from './reference/collection-reference'; import {DocumentReference} from './reference/document-reference'; @@ -95,6 +94,10 @@ import { } from './telemetry/trace-util'; import {DisabledTraceUtil} from './telemetry/disabled-trace-util'; import {EnabledTraceUtil} from './telemetry/enabled-trace-util'; +import {PipelineSource} from './pipelines'; + +import * as Pipelines from './pipelines'; +export {Pipelines}; export {CollectionReference} from './reference/collection-reference'; export {DocumentReference} from './reference/document-reference'; @@ -133,110 +136,6 @@ export type { ExplainMetrics, ExplainResults, } from './query-profile'; -export { - Pipeline, - PipelineResult, - PipelineSource, - PipelineSnapshot, -} from './pipeline'; -export type {FindNearestOptions} from './stage'; -export { - BooleanExpr, - AggregateWithAlias, - AggregateFunction, - Expr, - ExprWithAlias, - Field, - Constant, - FunctionExpr, - Ordering, - constant, - constantVector, - map, - array, - bitNot, - field, - xor, - rand, - arrayOffset, - timestampToUnixMicros, - timestampToUnixSeconds, - unixMicrosToTimestamp, - timestampToUnixMillis, - timestampSub, - timestampAdd, - byteLength, - bitAnd, - multiply, - sum, - maximum, - descending, - minimum, - count, - countIf, - arrayLength, - strContains, - charLength, - divide, - mod, - reverse, - trim, - toUpper, - toLower, - vectorLength, - isNotNan, - exists, - isNotNull, - isAbsent, - ifError, - isError, - isNan, - arrayConcat, - substr, - documentId, - isNull, - arrayContainsAll, - replaceFirst, - replaceAll, - mapRemove, - mapMerge, - unixSecondsToTimestamp, - unixMillisToTimestamp, - bitOr, - bitXor, - bitLeftShift, - bitRightShift, - add, - and, - arrayContains, - arrayContainsAny, - avg, - countAll, - endsWith, - eq, - gt, - like, - lt, - neq, - ascending, - not, - or, - regexContains, - regexMatch, - startsWith, - strConcat, - subtract, - cosineDistance, - dotProduct, - euclideanDistance, - mapGet, - lte, - eqAny, - notEqAny, - logicalMinimum, - logicalMaximum, - cond, -} from './expression'; const libVersion = require('../../package.json').version; setLibVersion(libVersion); @@ -1049,6 +948,9 @@ export class Firestore implements firestore.Firestore { return new CollectionGroup(this, collectionId, /* converter= */ undefined); } + /** + * TODO + */ pipeline(): PipelineSource { return new PipelineSource(this); } diff --git a/dev/src/expression.ts b/dev/src/pipelines/expression.ts similarity index 88% rename from dev/src/expression.ts rename to dev/src/pipelines/expression.ts index 7b5e6dcaa..a08f4467e 100644 --- a/dev/src/expression.ts +++ b/dev/src/pipelines/expression.ts @@ -1,4 +1,4 @@ -// Copyright 2024 Google LLC +// Copyright 2025 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. @@ -12,25 +12,23 @@ // See the License for the specific language governing permissions and // limitations under the License. -import * as protos from '../protos/firestore_v1_proto_api'; +import * as protos from '../../protos/firestore_v1_proto_api'; import api = protos.google.firestore.v1; import type * as firestore from '@google-cloud/firestore'; -import {VectorValue} from './field-value'; -import {FieldPath} from './path'; +import {VectorValue} from '../field-value'; +import {FieldPath} from '../path'; import { fieldOrExpression, isFirestoreValue, valueToDefaultExpr, vectorToExpr, } from './pipeline-util'; -import {HasUserData, Serializer, validateUserInput} from './serializer'; -import {cast} from './util'; +import {HasUserData, Serializer, validateUserInput} from '../serializer'; +import {cast} from '../util'; /** - * @beta - * * Represents an expression that can be evaluated to a value within the execution of a {@link * Pipeline}. * @@ -44,8 +42,8 @@ import {cast} from './util'; * The `Expr` class provides a fluent API for building expressions. You can chain together * method calls to create complex expressions. */ -export abstract class Expr implements firestore.Expr, HasUserData { - abstract readonly exprType: firestore.ExprType; +export abstract class Expr implements firestore.Pipelines.Expr, HasUserData { + abstract exprType: firestore.Pipelines.ExprType; /** * @internal @@ -81,8 +79,8 @@ export abstract class Expr implements firestore.Expr, HasUserData { * @return A new `Expr` representing the addition operation. */ add( - second: firestore.Expr | unknown, - ...others: Array + second: firestore.Pipelines.Expr | unknown, + ...others: Array ): FunctionExpr { const values = [second, ...others]; return new FunctionExpr('add', [ @@ -102,7 +100,7 @@ export abstract class Expr implements firestore.Expr, HasUserData { * @param other The expression to subtract from this expression. * @return A new `Expr` representing the subtraction operation. */ - subtract(other: firestore.Expr): FunctionExpr; + subtract(other: firestore.Pipelines.Expr): FunctionExpr; /** * Creates an expression that subtracts a constant value from this expression. @@ -116,7 +114,7 @@ export abstract class Expr implements firestore.Expr, HasUserData { * @return A new `Expr` representing the subtraction operation. */ subtract(other: number): FunctionExpr; - subtract(other: number | firestore.Expr): FunctionExpr { + subtract(other: number | firestore.Pipelines.Expr): FunctionExpr { return new FunctionExpr('subtract', [this, valueToDefaultExpr(other)]); } @@ -133,8 +131,8 @@ export abstract class Expr implements firestore.Expr, HasUserData { * @return A new `Expr` representing the multiplication operation. */ multiply( - second: firestore.Expr | number, - ...others: Array + second: Expr | number, + ...others: Array ): FunctionExpr { return new FunctionExpr('multiply', [ this, @@ -154,7 +152,7 @@ export abstract class Expr implements firestore.Expr, HasUserData { * @param other The expression to divide by. * @return A new `Expr` representing the division operation. */ - divide(other: firestore.Expr): FunctionExpr; + divide(other: Expr): FunctionExpr; /** * Creates an expression that divides this expression by a constant value. @@ -168,7 +166,7 @@ export abstract class Expr implements firestore.Expr, HasUserData { * @return A new `Expr` representing the division operation. */ divide(other: number): FunctionExpr; - divide(other: number | firestore.Expr): FunctionExpr { + divide(other: number | Expr): FunctionExpr { return new FunctionExpr('divide', [this, valueToDefaultExpr(other)]); } @@ -183,7 +181,7 @@ export abstract class Expr implements firestore.Expr, HasUserData { * @param expression The expression to divide by. * @return A new `Expr` representing the modulo operation. */ - mod(expression: firestore.Expr): FunctionExpr; + mod(expression: Expr): FunctionExpr; /** * Creates an expression that calculates the modulo (remainder) of dividing this expression by a constant value. @@ -197,7 +195,7 @@ export abstract class Expr implements firestore.Expr, HasUserData { * @return A new `Expr` representing the modulo operation. */ mod(value: number): FunctionExpr; - mod(other: number | firestore.Expr): FunctionExpr { + mod(other: number | Expr): FunctionExpr { return new FunctionExpr('mod', [this, valueToDefaultExpr(other)]); } @@ -212,7 +210,7 @@ export abstract class Expr implements firestore.Expr, HasUserData { * @param expression The expression to compare for equality. * @return A new `Expr` representing the equality comparison. */ - eq(expression: firestore.Expr): BooleanExpr; + eq(expression: Expr): BooleanExpr; /** * Creates an expression that checks if this expression is equal to a constant value. @@ -241,7 +239,7 @@ export abstract class Expr implements firestore.Expr, HasUserData { * @param expression The expression to compare for inequality. * @return A new `Expr` representing the inequality comparison. */ - neq(expression: firestore.Expr): BooleanExpr; + neq(expression: Expr): BooleanExpr; /** * Creates an expression that checks if this expression is not equal to a constant value. @@ -270,7 +268,7 @@ export abstract class Expr implements firestore.Expr, HasUserData { * @param experession The expression to compare for less than. * @return A new `Expr` representing the less than comparison. */ - lt(experession: firestore.Expr): BooleanExpr; + lt(experession: Expr): BooleanExpr; /** * Creates an expression that checks if this expression is less than a constant value. @@ -300,7 +298,7 @@ export abstract class Expr implements firestore.Expr, HasUserData { * @param expression The expression to compare for less than or equal to. * @return A new `Expr` representing the less than or equal to comparison. */ - lte(expression: firestore.Expr): BooleanExpr; + lte(expression: Expr): BooleanExpr; /** * Creates an expression that checks if this expression is less than or equal to a constant value. @@ -329,7 +327,7 @@ export abstract class Expr implements firestore.Expr, HasUserData { * @param expression The expression to compare for greater than. * @return A new `Expr` representing the greater than comparison. */ - gt(expression: firestore.Expr): BooleanExpr; + gt(expression: Expr): BooleanExpr; /** * Creates an expression that checks if this expression is greater than a constant value. @@ -359,7 +357,7 @@ export abstract class Expr implements firestore.Expr, HasUserData { * @param expression The expression to compare for greater than or equal to. * @return A new `Expr` representing the greater than or equal to comparison. */ - gte(expression: firestore.Expr): BooleanExpr; + gte(expression: Expr): BooleanExpr; /** * Creates an expression that checks if this expression is greater than or equal to a constant @@ -390,8 +388,8 @@ export abstract class Expr implements firestore.Expr, HasUserData { * @return A new `Expr` representing the concatenated array. */ arrayConcat( - secondArray: firestore.Expr | unknown[], - ...otherArrays: Array + secondArray: Expr | unknown[], + ...otherArrays: Array ): FunctionExpr { const elements = [secondArray, ...otherArrays]; const exprValues = elements.map(value => valueToDefaultExpr(value)); @@ -409,7 +407,7 @@ export abstract class Expr implements firestore.Expr, HasUserData { * @param expression The element to search for in the array. * @return A new `Expr` representing the 'array_contains' comparison. */ - arrayContains(expression: firestore.Expr): BooleanExpr; + arrayContains(expression: Expr): BooleanExpr; /** * Creates an expression that checks if an array contains a specific value. @@ -441,7 +439,7 @@ export abstract class Expr implements firestore.Expr, HasUserData { * @param values The elements to check for in the array. * @return A new `Expr` representing the 'array_contains_all' comparison. */ - arrayContainsAll(values: Array): BooleanExpr; + arrayContainsAll(values: Array): BooleanExpr; /** * Creates an expression that checks if an array contains all the specified elements. @@ -454,8 +452,8 @@ export abstract class Expr implements firestore.Expr, HasUserData { * @param arrayExpression The elements to check for in the array. * @return A new `Expr` representing the 'array_contains_all' comparison. */ - arrayContainsAll(arrayExpression: firestore.Expr): BooleanExpr; - arrayContainsAll(values: unknown[] | firestore.Expr): BooleanExpr { + arrayContainsAll(arrayExpression: Expr): BooleanExpr; + arrayContainsAll(values: unknown[] | Expr): BooleanExpr { const normalizedExpr = Array.isArray(values) ? new ListOfExprs(values.map(valueToDefaultExpr)) : cast(values); @@ -473,7 +471,7 @@ export abstract class Expr implements firestore.Expr, HasUserData { * @param values The elements to check for in the array. * @return A new `Expr` representing the 'array_contains_any' comparison. */ - arrayContainsAny(values: Array): BooleanExpr; + arrayContainsAny(values: Array): BooleanExpr; /** * Creates an expression that checks if an array contains any of the specified elements. @@ -487,10 +485,8 @@ export abstract class Expr implements firestore.Expr, HasUserData { * @param arrayExpression The elements to check for in the array. * @return A new `Expr` representing the 'array_contains_any' comparison. */ - arrayContainsAny(arrayExpression: firestore.Expr): BooleanExpr; - arrayContainsAny( - values: Array | firestore.Expr - ): BooleanExpr { + arrayContainsAny(arrayExpression: Expr): BooleanExpr; + arrayContainsAny(values: Array | Expr): BooleanExpr { const normalizedExpr = Array.isArray(values) ? new ListOfExprs(values.map(valueToDefaultExpr)) : cast(values); @@ -523,7 +519,7 @@ export abstract class Expr implements firestore.Expr, HasUserData { * @param values The values or expressions to check against. * @return A new `Expr` representing the 'IN' comparison. */ - eqAny(values: Array): BooleanExpr; + eqAny(values: Array): BooleanExpr; /** * Creates an expression that checks if this expression is equal to any of the provided values or @@ -537,8 +533,8 @@ export abstract class Expr implements firestore.Expr, HasUserData { * @param arrayExpression An expression that evaluates to an array of values to check against. * @return A new `Expr` representing the 'IN' comparison. */ - eqAny(arrayExpression: firestore.Expr): BooleanExpr; - eqAny(others: unknown[] | firestore.Expr): BooleanExpr { + eqAny(arrayExpression: Expr): BooleanExpr; + eqAny(others: unknown[] | Expr): BooleanExpr { const exprOthers = Array.isArray(others) ? new ListOfExprs(others.map(valueToDefaultExpr)) : cast(others); @@ -557,7 +553,7 @@ export abstract class Expr implements firestore.Expr, HasUserData { * @param values The values or expressions to check against. * @return A new `Expr` representing the 'NotEqAny' comparison. */ - notEqAny(values: Array): BooleanExpr; + notEqAny(values: Array): BooleanExpr; /** * Creates an expression that checks if this expression is not equal to any of the values in the evaluated expression. @@ -570,8 +566,8 @@ export abstract class Expr implements firestore.Expr, HasUserData { * @param arrayExpression The values or expressions to check against. * @return A new `Expr` representing the 'NotEqAny' comparison. */ - notEqAny(arrayExpression: firestore.Expr): BooleanExpr; - notEqAny(others: unknown[] | firestore.Expr): BooleanExpr { + notEqAny(arrayExpression: Expr): BooleanExpr; + notEqAny(others: unknown[] | Expr): BooleanExpr { const exprOthers = Array.isArray(others) ? new ListOfExprs(others.map(valueToDefaultExpr)) : cast(others); @@ -658,8 +654,8 @@ export abstract class Expr implements firestore.Expr, HasUserData { * @param pattern The pattern to search for. You can use "%" as a wildcard character. * @return A new `Expr` representing the 'like' comparison. */ - like(pattern: firestore.Expr): FunctionExpr; - like(stringOrExpr: string | firestore.Expr): FunctionExpr { + like(pattern: Expr): FunctionExpr; + like(stringOrExpr: string | Expr): FunctionExpr { return new FunctionExpr('like', [this, valueToDefaultExpr(stringOrExpr)]); } @@ -689,8 +685,8 @@ export abstract class Expr implements firestore.Expr, HasUserData { * @param pattern The regular expression to use for the search. * @return A new `Expr` representing the 'contains' comparison. */ - regexContains(pattern: firestore.Expr): BooleanExpr; - regexContains(stringOrExpr: string | firestore.Expr): BooleanExpr { + regexContains(pattern: Expr): BooleanExpr; + regexContains(stringOrExpr: string | Expr): BooleanExpr { return new BooleanExpr('regex_contains', [ this, valueToDefaultExpr(stringOrExpr), @@ -721,8 +717,8 @@ export abstract class Expr implements firestore.Expr, HasUserData { * @param pattern The regular expression to use for the match. * @return A new `Expr` representing the regular expression match. */ - regexMatch(pattern: firestore.Expr): BooleanExpr; - regexMatch(stringOrExpr: string | firestore.Expr): BooleanExpr { + regexMatch(pattern: Expr): BooleanExpr; + regexMatch(stringOrExpr: string | Expr): BooleanExpr { return new BooleanExpr('regex_match', [ this, valueToDefaultExpr(stringOrExpr), @@ -753,8 +749,8 @@ export abstract class Expr implements firestore.Expr, HasUserData { * @param expr The expression representing the substring to search for. * @return A new `Expr` representing the 'contains' comparison. */ - strContains(expr: firestore.Expr): BooleanExpr; - strContains(stringOrExpr: string | firestore.Expr): BooleanExpr { + strContains(expr: Expr): BooleanExpr; + strContains(stringOrExpr: string | Expr): BooleanExpr { return new BooleanExpr('str_contains', [ this, valueToDefaultExpr(stringOrExpr), @@ -786,8 +782,8 @@ export abstract class Expr implements firestore.Expr, HasUserData { * @param prefix The prefix expression to check for. * @return A new `Expr` representing the 'starts with' comparison. */ - startsWith(prefix: firestore.Expr): BooleanExpr; - startsWith(stringOrExpr: string | firestore.Expr): BooleanExpr { + startsWith(prefix: Expr): BooleanExpr; + startsWith(stringOrExpr: string | Expr): BooleanExpr { return new BooleanExpr('starts_with', [ this, valueToDefaultExpr(stringOrExpr), @@ -819,8 +815,8 @@ export abstract class Expr implements firestore.Expr, HasUserData { * @param suffix The postfix expression to check for. * @return A new `Expr` representing the 'ends with' comparison. */ - endsWith(suffix: firestore.Expr): BooleanExpr; - endsWith(stringOrExpr: string | firestore.Expr): BooleanExpr { + endsWith(suffix: Expr): BooleanExpr; + endsWith(stringOrExpr: string | Expr): BooleanExpr { return new BooleanExpr('ends_with', [ this, valueToDefaultExpr(stringOrExpr), @@ -882,8 +878,8 @@ export abstract class Expr implements firestore.Expr, HasUserData { * @return A new `Expr` representing the concatenated string. */ strConcat( - secondString: firestore.Expr | string, - ...otherStrings: Array + secondString: Expr | string, + ...otherStrings: Array ): FunctionExpr { const elements = [secondString, ...otherStrings]; const exprs = elements.map(valueToDefaultExpr); @@ -931,11 +927,8 @@ export abstract class Expr implements firestore.Expr, HasUserData { * @param replace The expression representing the substring to replace the first occurrence of 'find' with. * @return A new {@code Expr} representing the string with the first occurrence replaced. */ - replaceFirst(find: firestore.Expr, replace: firestore.Expr): FunctionExpr; - replaceFirst( - find: firestore.Expr | string, - replace: firestore.Expr | string - ): FunctionExpr { + replaceFirst(find: Expr, replace: Expr): FunctionExpr; + replaceFirst(find: Expr | string, replace: Expr | string): FunctionExpr { return new FunctionExpr('replace_first', [ this, valueToDefaultExpr(find), @@ -970,11 +963,8 @@ export abstract class Expr implements firestore.Expr, HasUserData { * @param replace The expression representing the substring to replace all occurrences of 'find' with. * @return A new {@code Expr} representing the string with all occurrences replaced. */ - replaceAll(find: firestore.Expr, replace: firestore.Expr): FunctionExpr; - replaceAll( - find: firestore.Expr | string, - replace: firestore.Expr | string - ): FunctionExpr { + replaceAll(find: Expr, replace: Expr): FunctionExpr; + replaceAll(find: Expr | string, replace: Expr | string): FunctionExpr { return new FunctionExpr('replace_all', [ this, valueToDefaultExpr(find), @@ -1096,8 +1086,8 @@ export abstract class Expr implements firestore.Expr, HasUserData { * @return A new {@code Expr} representing the logical max operation. */ logicalMaximum( - second: firestore.Expr | unknown, - ...others: Array + second: Expr | unknown, + ...others: Array ): FunctionExpr { const values = [second, ...others]; return new FunctionExpr('logical_maximum', [ @@ -1119,8 +1109,8 @@ export abstract class Expr implements firestore.Expr, HasUserData { * @return A new {@code Expr} representing the logical min operation. */ logicalMinimum( - second: firestore.Expr | unknown, - ...others: Array + second: Expr | unknown, + ...others: Array ): FunctionExpr { const values = [second, ...others]; return new FunctionExpr('logical_minimum', [ @@ -1154,7 +1144,7 @@ export abstract class Expr implements firestore.Expr, HasUserData { * @param vectorExpression The other vector (represented as an Expr) to compare against. * @return A new `Expr` representing the cosine distance between the two vectors. */ - cosineDistance(vectorExpression: firestore.Expr): FunctionExpr; + cosineDistance(vectorExpression: Expr): FunctionExpr; /** * Calculates the Cosine distance between two vectors. * @@ -1167,9 +1157,7 @@ export abstract class Expr implements firestore.Expr, HasUserData { * @return A new `Expr` representing the Cosine* distance between the two vectors. */ cosineDistance(vector: firestore.VectorValue | number[]): FunctionExpr; - cosineDistance( - other: firestore.Expr | firestore.VectorValue | number[] - ): FunctionExpr { + cosineDistance(other: Expr | firestore.VectorValue | number[]): FunctionExpr { return new FunctionExpr('cosine_distance', [this, vectorToExpr(other)]); } @@ -1184,7 +1172,7 @@ export abstract class Expr implements firestore.Expr, HasUserData { * @param vectorExpression The other vector (as an array of numbers) to calculate with. * @return A new `Expr` representing the dot product between the two vectors. */ - dotProduct(vectorExpression: firestore.Expr): FunctionExpr; + dotProduct(vectorExpression: Expr): FunctionExpr; /** * Calculates the dot product between two vectors. @@ -1198,9 +1186,7 @@ export abstract class Expr implements firestore.Expr, HasUserData { * @return A new `Expr` representing the dot product between the two vectors. */ dotProduct(vector: firestore.VectorValue | number[]): FunctionExpr; - dotProduct( - other: firestore.Expr | firestore.VectorValue | number[] - ): FunctionExpr { + dotProduct(other: Expr | firestore.VectorValue | number[]): FunctionExpr { return new FunctionExpr('dot_product', [this, vectorToExpr(other)]); } @@ -1215,7 +1201,7 @@ export abstract class Expr implements firestore.Expr, HasUserData { * @param vectorExpression The other vector (as an array of numbers) to calculate with. * @return A new `Expr` representing the Euclidean distance between the two vectors. */ - euclideanDistance(vectorExpression: firestore.Expr): FunctionExpr; + euclideanDistance(vectorExpression: Expr): FunctionExpr; /** * Calculates the Euclidean distance between two vectors. @@ -1230,7 +1216,7 @@ export abstract class Expr implements firestore.Expr, HasUserData { */ euclideanDistance(vector: firestore.VectorValue | number[]): FunctionExpr; euclideanDistance( - other: firestore.Expr | firestore.VectorValue | number[] + other: Expr | firestore.VectorValue | number[] ): FunctionExpr { return new FunctionExpr('euclidean_distance', [this, vectorToExpr(other)]); } @@ -1334,7 +1320,7 @@ export abstract class Expr implements firestore.Expr, HasUserData { * @param amount The expression evaluates to amount of the unit. * @return A new {@code Expr} representing the resulting timestamp. */ - timestampAdd(unit: firestore.Expr, amount: firestore.Expr): FunctionExpr; + timestampAdd(unit: Expr, amount: Expr): FunctionExpr; /** * Creates an expression that adds a specified amount of time to this timestamp expression. @@ -1354,14 +1340,14 @@ export abstract class Expr implements firestore.Expr, HasUserData { ): FunctionExpr; timestampAdd( unit: - | firestore.Expr + | Expr | 'microsecond' | 'millisecond' | 'second' | 'minute' | 'hour' | 'day', - amount: firestore.Expr | number + amount: Expr | number ): FunctionExpr { return new FunctionExpr('timestamp_add', [ this, @@ -1382,7 +1368,7 @@ export abstract class Expr implements firestore.Expr, HasUserData { * @param amount The expression evaluates to amount of the unit. * @return A new {@code Expr} representing the resulting timestamp. */ - timestampSub(unit: firestore.Expr, amount: firestore.Expr): FunctionExpr; + timestampSub(unit: Expr, amount: Expr): FunctionExpr; /** * Creates an expression that subtracts a specified amount of time from this timestamp expression. @@ -1402,14 +1388,14 @@ export abstract class Expr implements firestore.Expr, HasUserData { ): FunctionExpr; timestampSub( unit: - | firestore.Expr + | Expr | 'microsecond' | 'millisecond' | 'second' | 'minute' | 'hour' | 'day', - amount: firestore.Expr | number + amount: Expr | number ): FunctionExpr { return new FunctionExpr('timestamp_sub', [ this, @@ -1419,8 +1405,6 @@ export abstract class Expr implements firestore.Expr, HasUserData { } /** - * @beta - * * Creates an expression that applies a bitwise AND operation between this expression and a constant. * * ```typescript @@ -1433,8 +1417,6 @@ export abstract class Expr implements firestore.Expr, HasUserData { */ bitAnd(otherBits: number | Buffer | Uint8Array): FunctionExpr; /** - * @beta - * * Creates an expression that applies a bitwise AND operation between two expressions. * * ```typescript @@ -1445,10 +1427,8 @@ export abstract class Expr implements firestore.Expr, HasUserData { * @param bitsExpression An expression that returns bits when evaluated. * @return A new {@code Expr} representing the bitwise AND operation. */ - bitAnd(bitsExpression: firestore.Expr): FunctionExpr; - bitAnd( - bitsOrExpression: number | firestore.Expr | Buffer | Uint8Array - ): FunctionExpr { + bitAnd(bitsExpression: Expr): FunctionExpr; + bitAnd(bitsOrExpression: number | Expr | Buffer | Uint8Array): FunctionExpr { return new FunctionExpr('bit_and', [ this, valueToDefaultExpr(bitsOrExpression), @@ -1456,8 +1436,6 @@ export abstract class Expr implements firestore.Expr, HasUserData { } /** - * @beta - * * Creates an expression that applies a bitwise OR operation between this expression and a constant. * * ```typescript @@ -1470,8 +1448,6 @@ export abstract class Expr implements firestore.Expr, HasUserData { */ bitOr(otherBits: number | Buffer | Uint8Array): FunctionExpr; /** - * @beta - * * Creates an expression that applies a bitwise OR operation between two expressions. * * ```typescript @@ -1482,10 +1458,8 @@ export abstract class Expr implements firestore.Expr, HasUserData { * @param bitsExpression An expression that returns bits when evaluated. * @return A new {@code Expr} representing the bitwise OR operation. */ - bitOr(bitsExpression: firestore.Expr): FunctionExpr; - bitOr( - bitsOrExpression: number | firestore.Expr | Buffer | Uint8Array - ): FunctionExpr { + bitOr(bitsExpression: Expr): FunctionExpr; + bitOr(bitsOrExpression: number | Expr | Buffer | Uint8Array): FunctionExpr { return new FunctionExpr('bit_or', [ this, valueToDefaultExpr(bitsOrExpression), @@ -1493,8 +1467,6 @@ export abstract class Expr implements firestore.Expr, HasUserData { } /** - * @beta - * * Creates an expression that applies a bitwise XOR operation between this expression and a constant. * * ```typescript @@ -1507,8 +1479,6 @@ export abstract class Expr implements firestore.Expr, HasUserData { */ bitXor(otherBits: number | Buffer | Uint8Array): FunctionExpr; /** - * @beta - * * Creates an expression that applies a bitwise XOR operation between two expressions. * * ```typescript @@ -1519,10 +1489,8 @@ export abstract class Expr implements firestore.Expr, HasUserData { * @param bitsExpression An expression that returns bits when evaluated. * @return A new {@code Expr} representing the bitwise XOR operation. */ - bitXor(bitsExpression: firestore.Expr): FunctionExpr; - bitXor( - bitsOrExpression: number | firestore.Expr | Buffer | Uint8Array - ): FunctionExpr { + bitXor(bitsExpression: Expr): FunctionExpr; + bitXor(bitsOrExpression: number | Expr | Buffer | Uint8Array): FunctionExpr { return new FunctionExpr('bit_xor', [ this, valueToDefaultExpr(bitsOrExpression), @@ -1530,8 +1498,6 @@ export abstract class Expr implements firestore.Expr, HasUserData { } /** - * @beta - * * Creates an expression that applies a bitwise NOT operation to this expression. * * ```typescript @@ -1546,8 +1512,6 @@ export abstract class Expr implements firestore.Expr, HasUserData { } /** - * @beta - * * Creates an expression that applies a bitwise left shift operation to this expression. * * ```typescript @@ -1560,8 +1524,6 @@ export abstract class Expr implements firestore.Expr, HasUserData { */ bitLeftShift(y: number): FunctionExpr; /** - * @beta - * * Creates an expression that applies a bitwise left shift operation to this expression. * * ```typescript @@ -1572,8 +1534,8 @@ export abstract class Expr implements firestore.Expr, HasUserData { * @param numberExpr The operand expression representing the number of bits to shift. * @return A new {@code Expr} representing the bitwise left shift operation. */ - bitLeftShift(numberExpr: firestore.Expr): FunctionExpr; - bitLeftShift(numberExpr: number | firestore.Expr): FunctionExpr { + bitLeftShift(numberExpr: Expr): FunctionExpr; + bitLeftShift(numberExpr: number | Expr): FunctionExpr { return new FunctionExpr('bit_left_shift', [ this, valueToDefaultExpr(numberExpr), @@ -1581,8 +1543,6 @@ export abstract class Expr implements firestore.Expr, HasUserData { } /** - * @beta - * * Creates an expression that applies a bitwise right shift operation to this expression. * * ```typescript @@ -1595,8 +1555,6 @@ export abstract class Expr implements firestore.Expr, HasUserData { */ bitRightShift(y: number): FunctionExpr; /** - * @beta - * * Creates an expression that applies a bitwise right shift operation to this expression. * * ```typescript @@ -1607,8 +1565,8 @@ export abstract class Expr implements firestore.Expr, HasUserData { * @param numberExpr The operand expression representing the number of bits to shift. * @return A new {@code Expr} representing the bitwise right shift operation. */ - bitRightShift(numberExpr: firestore.Expr): FunctionExpr; - bitRightShift(numberExpr: number | firestore.Expr): FunctionExpr { + bitRightShift(numberExpr: Expr): FunctionExpr; + bitRightShift(numberExpr: number | Expr): FunctionExpr { return new FunctionExpr('bit_right_shift', [ this, valueToDefaultExpr(numberExpr), @@ -1616,8 +1574,6 @@ export abstract class Expr implements firestore.Expr, HasUserData { } /** - * @beta - * * Creates an expression that returns the document ID from a path. * * ```typescript @@ -1632,8 +1588,6 @@ export abstract class Expr implements firestore.Expr, HasUserData { } /** - * @beta - * * Creates an expression that returns a substring of the results of this expression. * * @param position Index of the first character of the substring. @@ -1643,19 +1597,14 @@ export abstract class Expr implements firestore.Expr, HasUserData { substr(position: number, length?: number): FunctionExpr; /** - * @beta - * * Creates an expression that returns a substring of the results of this expression. * * @param position An expression returning the index of the first character of the substring. * @param length An expression returning the length of the substring. If not provided the * substring will end at the end of the input. */ - substr(position: firestore.Expr, length?: firestore.Expr): FunctionExpr; - substr( - position: firestore.Expr | number, - length?: firestore.Expr | number - ): FunctionExpr { + substr(position: Expr, length?: Expr): FunctionExpr; + substr(position: Expr | number, length?: Expr | number): FunctionExpr { const positionExpr = valueToDefaultExpr(position); if (length === undefined) { return new FunctionExpr('substr', [this, positionExpr]); @@ -1669,7 +1618,6 @@ export abstract class Expr implements firestore.Expr, HasUserData { } /** - * @beta * Creates an expression that indexes into an array from the beginning or end * and returns the element. If the offset exceeds the array length, an error is * returned. A negative offset, starts from the end. @@ -1685,7 +1633,6 @@ export abstract class Expr implements firestore.Expr, HasUserData { arrayOffset(offset: number): FunctionExpr; /** - * @beta * Creates an expression that indexes into an array from the beginning or end * and returns the element. If the offset exceeds the array length, an error is * returned. A negative offset, starts from the end. @@ -1699,14 +1646,12 @@ export abstract class Expr implements firestore.Expr, HasUserData { * @param offsetExpr An Expr evaluating to the index of the element to return. * @return A new Expr representing the 'arrayOffset' operation. */ - arrayOffset(offsetExpr: firestore.Expr): FunctionExpr; - arrayOffset(offset: firestore.Expr | number): FunctionExpr { + arrayOffset(offsetExpr: Expr): FunctionExpr; + arrayOffset(offset: Expr | number): FunctionExpr { return new FunctionExpr('array_offset', [this, valueToDefaultExpr(offset)]); } /** - * @beta - * * Creates an expression that checks if a given expression produces an error. * * ```typescript @@ -1721,8 +1666,6 @@ export abstract class Expr implements firestore.Expr, HasUserData { } /** - * @beta - * * Creates an expression that returns the result of the `catchExpr` argument * if there is an error, else return the result of this expression. * @@ -1736,11 +1679,9 @@ export abstract class Expr implements firestore.Expr, HasUserData { * returned if this expression produces an error. * @return A new {@code Expr} representing the 'ifError' operation. */ - ifError(catchExpr: firestore.Expr): FunctionExpr; + ifError(catchExpr: Expr): FunctionExpr; /** - * @beta - * * Creates an expression that returns the `catch` argument if there is an * error, else return the result of this expression. * @@ -1760,8 +1701,6 @@ export abstract class Expr implements firestore.Expr, HasUserData { } /** - * @beta - * * Creates an expression that returns `true` if the result of this expression * is absent. Otherwise, returns `false` even if the value is `null`. * @@ -1777,8 +1716,6 @@ export abstract class Expr implements firestore.Expr, HasUserData { } /** - * @beta - * * Creates an expression that checks if tbe result of an expression is not null. * * ```typescript @@ -1793,8 +1730,6 @@ export abstract class Expr implements firestore.Expr, HasUserData { } /** - * @beta - * * Creates an expression that checks if the results of this expression is NOT 'NaN' (Not a Number). * * ```typescript @@ -1809,8 +1744,6 @@ export abstract class Expr implements firestore.Expr, HasUserData { } /** - * @beta - * * Creates an expression that removes a key from the map produced by evaluating this expression. * * ``` @@ -1823,8 +1756,6 @@ export abstract class Expr implements firestore.Expr, HasUserData { */ mapRemove(key: string): FunctionExpr; /** - * @beta - * * Creates an expression that removes a key from the map produced by evaluating this expression. * * ``` @@ -1835,8 +1766,8 @@ export abstract class Expr implements firestore.Expr, HasUserData { * @param keyExpr An expression that produces the name of the key to remove from the input map. * @returns A new {@code FirestoreFunction} representing the 'mapRemove' operation. */ - mapRemove(keyExpr: firestore.Expr): FunctionExpr; - mapRemove(stringExpr: firestore.Expr | string): FunctionExpr { + mapRemove(keyExpr: Expr): FunctionExpr; + mapRemove(stringExpr: Expr | string): FunctionExpr { return new FunctionExpr('map_remove', [ this, valueToDefaultExpr(stringExpr), @@ -1844,8 +1775,6 @@ export abstract class Expr implements firestore.Expr, HasUserData { } /** - * @beta - * * Creates an expression that merges multiple map values. * * ``` @@ -1862,8 +1791,8 @@ export abstract class Expr implements firestore.Expr, HasUserData { * @returns A new {@code FirestoreFunction} representing the 'mapMerge' operation. */ mapMerge( - secondMap: Record | firestore.Expr, - ...otherMaps: Array | firestore.Expr> + secondMap: Record | Expr, + ...otherMaps: Array | Expr> ): FunctionExpr { const secondMapExpr = valueToDefaultExpr(secondMap); const otherMapExprs = otherMaps.map(valueToDefaultExpr); @@ -1920,20 +1849,16 @@ export abstract class Expr implements firestore.Expr, HasUserData { * @return A new {@link ExprWithAlias} that wraps this * expression and associates it with the provided alias. */ - as(name: string): firestore.ExprWithAlias { + as(name: string): ExprWithAlias { return new ExprWithAlias(this, name); } } /** - * @beta - * * A class that represents an aggregate function. */ -export class AggregateFunction - implements firestore.AggregateFunction, HasUserData -{ - exprType: firestore.ExprType = 'AggregateFunction'; +export class AggregateFunction implements AggregateFunction, HasUserData { + exprType: firestore.Pipelines.ExprType = 'AggregateFunction'; /** * @internal @@ -1993,13 +1918,9 @@ export class AggregateFunction } /** - * @beta - * * An AggregateFunction with alias. */ -export class AggregateWithAlias - implements firestore.AggregateWithAlias, HasUserData -{ +export class AggregateWithAlias implements AggregateWithAlias, HasUserData { constructor( readonly aggregate: AggregateFunction, readonly alias: string @@ -2023,10 +1944,12 @@ export class AggregateWithAlias } /** - * @beta + * TODO */ -export class ExprWithAlias implements firestore.Selectable, HasUserData { - exprType: firestore.ExprType = 'ExprWithAlias'; +export class ExprWithAlias + implements firestore.Pipelines.Selectable, HasUserData +{ + exprType: firestore.Pipelines.ExprType = 'ExprWithAlias'; selectable = true as const; /** @@ -2055,7 +1978,7 @@ export class ExprWithAlias implements firestore.Selectable, HasUserData { * @internal */ class ListOfExprs extends Expr { - exprType: firestore.ExprType = 'ListOfExprs'; + exprType: firestore.Pipelines.ExprType = 'ListOfExprs'; constructor(private exprs: Expr[]) { super(); @@ -2085,8 +2008,6 @@ class ListOfExprs extends Expr { } /** - * @beta - * * Represents a reference to a field in a Firestore document, or outputs of a {@link Pipeline} stage. * *

Field references are used to access document field values in expressions and to specify fields @@ -2102,8 +2023,8 @@ class ListOfExprs extends Expr { * const cityField = field("address.city"); * ``` */ -export class Field extends Expr implements firestore.Selectable { - readonly exprType: firestore.ExprType = 'Field'; +export class Field extends Expr implements firestore.Pipelines.Selectable { + readonly exprType: firestore.Pipelines.ExprType = 'Field'; selectable = true as const; /** @@ -2174,8 +2095,6 @@ export function field(field: string | firestore.FieldPath): Field { } /** - * @beta - * * Represents a constant value that can be used in a Firestore pipeline expression. * * You can create a `Constant` instance using the static {@link #of} method: @@ -2189,7 +2108,7 @@ export function field(field: string | firestore.FieldPath): Field { * ``` */ export class Constant extends Expr { - readonly exprType: firestore.ExprType = 'Constant'; + readonly exprType: firestore.Pipelines.ExprType = 'Constant'; private protoValue?: api.IValue; @@ -2353,10 +2272,10 @@ export function constant(value: unknown): Constant { export function constantVector( value: number[] | firestore.VectorValue ): Constant { - if (value instanceof VectorValue) { - return constant(value); - } else { + if (Array.isArray(value)) { return constant(new VectorValue(value as number[])); + } else { + return constant(value); } } @@ -2370,7 +2289,7 @@ export class MapValue extends Expr { super(); } - exprType: firestore.ExprType = 'Constant'; + exprType: firestore.Pipelines.ExprType = 'Constant'; _toProto(serializer: Serializer): api.IValue { return serializer.encodeValue(this.plainObject); @@ -2388,8 +2307,6 @@ export class MapValue extends Expr { } /** - * @beta - * * This class defines the base class for Firestore {@link Pipeline} functions, which can be evaluated within pipeline * execution. * @@ -2397,7 +2314,7 @@ export class MapValue extends Expr { * or the methods on {@link Expr} ({@link Expr#eq}, {@link Expr#lt}, etc.) to construct new Function instances. */ export class FunctionExpr extends Expr { - readonly exprType: firestore.ExprType = 'Function'; + readonly exprType: firestore.Pipelines.ExprType = 'Function'; constructor( protected name: string, @@ -2431,8 +2348,6 @@ export class FunctionExpr extends Expr { } /** - * @beta - * * This class defines the base class for Firestore {@link Pipeline} functions, which can be evaluated within pipeline * execution. * @@ -2440,7 +2355,7 @@ export class FunctionExpr extends Expr { * or the methods on {@link Expr} ({@link Expr#eq}, {@link Expr#lt}, etc.) to construct new Function instances. */ class MapFunctionExpr extends FunctionExpr { - readonly exprType: firestore.ExprType = 'Function'; + readonly exprType: firestore.Pipelines.ExprType = 'Function'; constructor(private map: Record) { super('map', []); @@ -2482,8 +2397,6 @@ class MapFunctionExpr extends FunctionExpr { } /** - * @beta - * * This class defines the base class for Firestore {@link Pipeline} functions, which can be evaluated within pipeline * execution. * @@ -2491,7 +2404,7 @@ class MapFunctionExpr extends FunctionExpr { * or the methods on {@link Expr} ({@link Expr#eq}, {@link Expr#lt}, etc.) to construct new Function instances. */ class ArrayFunctionExpr extends FunctionExpr { - readonly exprType: firestore.ExprType = 'Function'; + readonly exprType: firestore.Pipelines.ExprType = 'Function'; constructor(private values: Array) { super('array', []); @@ -2526,11 +2439,9 @@ class ArrayFunctionExpr extends FunctionExpr { } /** - * @beta - * * An interface that represents a filter condition. */ -export class BooleanExpr extends FunctionExpr implements firestore.BooleanExpr { +export class BooleanExpr extends FunctionExpr implements BooleanExpr { filterable: true = true as const; /** @@ -2564,7 +2475,6 @@ export class BooleanExpr extends FunctionExpr implements firestore.BooleanExpr { } /** - * @beta * Creates an aggregation that counts the number of stage inputs where the provided * boolean expression evaluates to true. * @@ -2576,12 +2486,11 @@ export class BooleanExpr extends FunctionExpr implements firestore.BooleanExpr { * @param booleanExpr - The boolean expression to evaluate on each input. * @returns A new `AggregateFunction` representing the 'countIf' aggregation. */ -export function countIf(booleanExpr: firestore.BooleanExpr): AggregateFunction { +export function countIf(booleanExpr: BooleanExpr): AggregateFunction { return new AggregateFunction('count_if', [cast(booleanExpr)]); } /** - * @beta * Creates an expression that return a pseudo-random value of type double in the * range of [0, 1), inclusive of 0 and exclusive of 1. * @@ -2592,8 +2501,6 @@ export function rand(): FunctionExpr { } /** - * @beta - * * Creates an expression that applies a bitwise AND operation between a field and a constant. * * ```typescript @@ -2610,8 +2517,6 @@ export function bitAnd( otherBits: number | Buffer | Uint8Array ): FunctionExpr; /** - * @beta - * * Creates an expression that applies a bitwise AND operation between a field and an expression. * * ```typescript @@ -2623,13 +2528,8 @@ export function bitAnd( * @param bitsExpression An expression that returns bits when evaluated. * @return A new {@code Expr} representing the bitwise AND operation. */ -export function bitAnd( - field: string, - bitsExpression: firestore.Expr -): FunctionExpr; +export function bitAnd(field: string, bitsExpression: Expr): FunctionExpr; /** - * @beta - * * Creates an expression that applies a bitwise AND operation between an expression and a constant. * * ```typescript @@ -2642,12 +2542,10 @@ export function bitAnd( * @return A new {@code Expr} representing the bitwise AND operation. */ export function bitAnd( - bitsExpression: firestore.Expr, + bitsExpression: Expr, otherBits: number | Buffer | Uint8Array ): FunctionExpr; /** - * @beta - * * Creates an expression that applies a bitwise AND operation between two expressions. * * ```typescript @@ -2660,19 +2558,17 @@ export function bitAnd( * @return A new {@code Expr} representing the bitwise AND operation. */ export function bitAnd( - bitsExpression: firestore.Expr, - otherBitsExpression: firestore.Expr + bitsExpression: Expr, + otherBitsExpression: Expr ): FunctionExpr; export function bitAnd( - bits: string | firestore.Expr, - bitsOrExpression: number | firestore.Expr | Buffer | Uint8Array + bits: string | Expr, + bitsOrExpression: number | Expr | Buffer | Uint8Array ): FunctionExpr { return fieldOrExpression(bits).bitAnd(valueToDefaultExpr(bitsOrExpression)); } /** - * @beta - * * Creates an expression that applies a bitwise OR operation between a field and a constant. * * ```typescript @@ -2689,8 +2585,6 @@ export function bitOr( otherBits: number | Buffer | Uint8Array ): FunctionExpr; /** - * @beta - * * Creates an expression that applies a bitwise OR operation between a field and an expression. * * ```typescript @@ -2702,13 +2596,8 @@ export function bitOr( * @param bitsExpression An expression that returns bits when evaluated. * @return A new {@code Expr} representing the bitwise OR operation. */ -export function bitOr( - field: string, - bitsExpression: firestore.Expr -): FunctionExpr; +export function bitOr(field: string, bitsExpression: Expr): FunctionExpr; /** - * @beta - * * Creates an expression that applies a bitwise OR operation between an expression and a constant. * * ```typescript @@ -2721,12 +2610,10 @@ export function bitOr( * @return A new {@code Expr} representing the bitwise OR operation. */ export function bitOr( - bitsExpression: firestore.Expr, + bitsExpression: Expr, otherBits: number | Buffer | Uint8Array ): FunctionExpr; /** - * @beta - * * Creates an expression that applies a bitwise OR operation between two expressions. * * ```typescript @@ -2739,19 +2626,17 @@ export function bitOr( * @return A new {@code Expr} representing the bitwise OR operation. */ export function bitOr( - bitsExpression: firestore.Expr, - otherBitsExpression: firestore.Expr + bitsExpression: Expr, + otherBitsExpression: Expr ): FunctionExpr; export function bitOr( - bits: string | firestore.Expr, - bitsOrExpression: number | firestore.Expr | Buffer | Uint8Array + bits: string | Expr, + bitsOrExpression: number | Expr | Buffer | Uint8Array ): FunctionExpr { return fieldOrExpression(bits).bitOr(valueToDefaultExpr(bitsOrExpression)); } /** - * @beta - * * Creates an expression that applies a bitwise XOR operation between a field and a constant. * * ```typescript @@ -2768,8 +2653,6 @@ export function bitXor( otherBits: number | Buffer | Uint8Array ): FunctionExpr; /** - * @beta - * * Creates an expression that applies a bitwise XOR operation between a field and an expression. * * ```typescript @@ -2781,13 +2664,8 @@ export function bitXor( * @param bitsExpression An expression that returns bits when evaluated. * @return A new {@code Expr} representing the bitwise XOR operation. */ -export function bitXor( - field: string, - bitsExpression: firestore.Expr -): FunctionExpr; +export function bitXor(field: string, bitsExpression: Expr): FunctionExpr; /** - * @beta - * * Creates an expression that applies a bitwise XOR operation between an expression and a constant. * * ```typescript @@ -2800,12 +2678,10 @@ export function bitXor( * @return A new {@code Expr} representing the bitwise XOR operation. */ export function bitXor( - bitsExpression: firestore.Expr, + bitsExpression: Expr, otherBits: number | Buffer | Uint8Array ): FunctionExpr; /** - * @beta - * * Creates an expression that applies a bitwise XOR operation between two expressions. * * ```typescript @@ -2818,19 +2694,17 @@ export function bitXor( * @return A new {@code Expr} representing the bitwise XOR operation. */ export function bitXor( - bitsExpression: firestore.Expr, - otherBitsExpression: firestore.Expr + bitsExpression: Expr, + otherBitsExpression: Expr ): FunctionExpr; export function bitXor( - bits: string | firestore.Expr, - bitsOrExpression: number | firestore.Expr | Buffer | Uint8Array + bits: string | Expr, + bitsOrExpression: number | Expr | Buffer | Uint8Array ): FunctionExpr { return fieldOrExpression(bits).bitXor(valueToDefaultExpr(bitsOrExpression)); } /** - * @beta - * * Creates an expression that applies a bitwise NOT operation to a field. * * ```typescript @@ -2843,8 +2717,6 @@ export function bitXor( */ export function bitNot(field: string): FunctionExpr; /** - * @beta - * * Creates an expression that applies a bitwise NOT operation to an expression. * * ```typescript @@ -2855,14 +2727,12 @@ export function bitNot(field: string): FunctionExpr; * @param bitsValueExpression An expression that returns bits when evaluated. * @return A new {@code Expr} representing the bitwise NOT operation. */ -export function bitNot(bitsValueExpression: firestore.Expr): FunctionExpr; -export function bitNot(bits: string | firestore.Expr): FunctionExpr { +export function bitNot(bitsValueExpression: Expr): FunctionExpr; +export function bitNot(bits: string | Expr): FunctionExpr { return fieldOrExpression(bits).bitNot(); } /** - * @beta - * * Creates an expression that applies a bitwise left shift operation between a field and a constant. * * ```typescript @@ -2876,8 +2746,6 @@ export function bitNot(bits: string | firestore.Expr): FunctionExpr { */ export function bitLeftShift(field: string, y: number): FunctionExpr; /** - * @beta - * * Creates an expression that applies a bitwise left shift operation between a field and an expression. * * ```typescript @@ -2889,13 +2757,8 @@ export function bitLeftShift(field: string, y: number): FunctionExpr; * @param numberExpr The right operand expression representing the number of bits to shift. * @return A new {@code Expr} representing the bitwise left shift operation. */ -export function bitLeftShift( - field: string, - numberExpr: firestore.Expr -): FunctionExpr; +export function bitLeftShift(field: string, numberExpr: Expr): FunctionExpr; /** - * @beta - * * Creates an expression that applies a bitwise left shift operation between an expression and a constant. * * ```typescript @@ -2907,10 +2770,8 @@ export function bitLeftShift( * @param y The right operand constant representing the number of bits to shift. * @return A new {@code Expr} representing the bitwise left shift operation. */ -export function bitLeftShift(xValue: firestore.Expr, y: number): FunctionExpr; +export function bitLeftShift(xValue: Expr, y: number): FunctionExpr; /** - * @beta - * * Creates an expression that applies a bitwise left shift operation between two expressions. * * ```typescript @@ -2922,20 +2783,15 @@ export function bitLeftShift(xValue: firestore.Expr, y: number): FunctionExpr; * @param numberExpr The right operand expression representing the number of bits to shift. * @return A new {@code Expr} representing the bitwise left shift operation. */ +export function bitLeftShift(xValue: Expr, numberExpr: Expr): FunctionExpr; export function bitLeftShift( - xValue: firestore.Expr, - numberExpr: firestore.Expr -): FunctionExpr; -export function bitLeftShift( - xValue: string | firestore.Expr, - numberExpr: number | firestore.Expr + xValue: string | Expr, + numberExpr: number | Expr ): FunctionExpr { return fieldOrExpression(xValue).bitLeftShift(valueToDefaultExpr(numberExpr)); } /** - * @beta - * * Creates an expression that applies a bitwise right shift operation between a field and a constant. * * ```typescript @@ -2949,8 +2805,6 @@ export function bitLeftShift( */ export function bitRightShift(field: string, y: number): FunctionExpr; /** - * @beta - * * Creates an expression that applies a bitwise right shift operation between a field and an expression. * * ```typescript @@ -2962,13 +2816,8 @@ export function bitRightShift(field: string, y: number): FunctionExpr; * @param numberExpr The right operand expression representing the number of bits to shift. * @return A new {@code Expr} representing the bitwise right shift operation. */ -export function bitRightShift( - field: string, - numberExpr: firestore.Expr -): FunctionExpr; +export function bitRightShift(field: string, numberExpr: Expr): FunctionExpr; /** - * @beta - * * Creates an expression that applies a bitwise right shift operation between an expression and a constant. * * ```typescript @@ -2980,10 +2829,8 @@ export function bitRightShift( * @param y The right operand constant representing the number of bits to shift. * @return A new {@code Expr} representing the bitwise right shift operation. */ -export function bitRightShift(xValue: firestore.Expr, y: number): FunctionExpr; +export function bitRightShift(xValue: Expr, y: number): FunctionExpr; /** - * @beta - * * Creates an expression that applies a bitwise right shift operation between two expressions. * * ```typescript @@ -2995,13 +2842,10 @@ export function bitRightShift(xValue: firestore.Expr, y: number): FunctionExpr; * @param numberExpr The right operand expression representing the number of bits to shift. * @return A new {@code Expr} representing the bitwise right shift operation. */ +export function bitRightShift(xValue: Expr, numberExpr: Expr): FunctionExpr; export function bitRightShift( - xValue: firestore.Expr, - numberExpr: firestore.Expr -): FunctionExpr; -export function bitRightShift( - xValue: string | firestore.Expr, - numberExpr: number | firestore.Expr + xValue: string | Expr, + numberExpr: number | Expr ): FunctionExpr { return fieldOrExpression(xValue).bitRightShift( valueToDefaultExpr(numberExpr) @@ -3009,7 +2853,6 @@ export function bitRightShift( } /** - * @beta * Creates an expression that indexes into an array from the beginning or end * and return the element. If the offset exceeds the array length, an error is * returned. A negative offset, starts from the end. @@ -3026,7 +2869,6 @@ export function bitRightShift( export function arrayOffset(arrayField: string, offset: number): FunctionExpr; /** - * @beta * Creates an expression that indexes into an array from the beginning or end * and return the element. If the offset exceeds the array length, an error is * returned. A negative offset, starts from the end. @@ -3041,13 +2883,9 @@ export function arrayOffset(arrayField: string, offset: number): FunctionExpr; * @param offsetExpr An Expr evaluating to the index of the element to return. * @return A new Expr representing the 'arrayOffset' operation. */ -export function arrayOffset( - arrayField: string, - offsetExpr: firestore.Expr -): FunctionExpr; +export function arrayOffset(arrayField: string, offsetExpr: Expr): FunctionExpr; /** - * @beta * Creates an expression that indexes into an array from the beginning or end * and return the element. If the offset exceeds the array length, an error is * returned. A negative offset, starts from the end. @@ -3062,12 +2900,11 @@ export function arrayOffset( * @return A new Expr representing the 'arrayOffset' operation. */ export function arrayOffset( - arrayExpression: firestore.Expr, + arrayExpression: Expr, offset: number ): FunctionExpr; /** - * @beta * Creates an expression that indexes into an array from the beginning or end * and return the element. If the offset exceeds the array length, an error is * returned. A negative offset, starts from the end. @@ -3083,19 +2920,17 @@ export function arrayOffset( * @return A new Expr representing the 'arrayOffset' operation. */ export function arrayOffset( - arrayExpression: firestore.Expr, - offsetExpr: firestore.Expr + arrayExpression: Expr, + offsetExpr: Expr ): FunctionExpr; export function arrayOffset( - array: firestore.Expr | string, - offset: firestore.Expr | number + array: Expr | string, + offset: Expr | number ): FunctionExpr { return fieldOrExpression(array).arrayOffset(valueToDefaultExpr(offset)); } /** - * @beta - * * Creates an expression that checks if a given expression produces an error. * * ```typescript @@ -3106,14 +2941,12 @@ export function arrayOffset( * @param value The expression to check. * @return A new {@code Expr} representing the 'isError' check. */ -export function isError(value: firestore.Expr): BooleanExpr { +export function isError(value: Expr): BooleanExpr { const expr: Expr = cast(value); return expr.isError(); } /** - * @beta - * * Creates an expression that returns the `catch` argument if there is an * error, else return the result of the `try` argument evaluation. * @@ -3128,14 +2961,9 @@ export function isError(value: firestore.Expr): BooleanExpr { * returned if the tryExpr produces an error. * @return A new {@code Expr} representing the 'ifError' operation. */ -export function ifError( - tryExpr: firestore.Expr, - catchExpr: firestore.Expr -): FunctionExpr; +export function ifError(tryExpr: Expr, catchExpr: Expr): FunctionExpr; /** - * @beta - * * Creates an expression that returns the `catch` argument if there is an * error, else return the result of the `try` argument evaluation. * @@ -3150,21 +2978,13 @@ export function ifError( * error. * @return A new {@code Expr} representing the 'ifError' operation. */ -export function ifError( - tryExpr: firestore.Expr, - catchValue: unknown -): FunctionExpr; -export function ifError( - tryExpr: firestore.Expr, - catchValue: unknown -): FunctionExpr { +export function ifError(tryExpr: Expr, catchValue: unknown): FunctionExpr; +export function ifError(tryExpr: Expr, catchValue: unknown): FunctionExpr { const expr: Expr = cast(tryExpr); return expr.ifError(valueToDefaultExpr(catchValue)); } /** - * @beta - * * Creates an expression that returns `true` if a value is absent. Otherwise, * returns `false` even if the value is `null`. * @@ -3176,11 +2996,9 @@ export function ifError( * @param value The expression to check. * @return A new {@code Expr} representing the 'isAbsent' check. */ -export function isAbsent(value: firestore.Expr): BooleanExpr; +export function isAbsent(value: Expr): BooleanExpr; /** - * @beta - * * Creates an expression that returns `true` if a field is absent. Otherwise, * returns `false` even if the field value is `null`. * @@ -3193,13 +3011,11 @@ export function isAbsent(value: firestore.Expr): BooleanExpr; * @return A new {@code Expr} representing the 'isAbsent' check. */ export function isAbsent(field: string): BooleanExpr; -export function isAbsent(value: firestore.Expr | string): BooleanExpr { +export function isAbsent(value: Expr | string): BooleanExpr { return fieldOrExpression(value).isAbsent(); } /** - * @beta - * * Creates an expression that checks if an expression evaluates to 'NaN' (Not a Number). * * ```typescript @@ -3210,11 +3026,9 @@ export function isAbsent(value: firestore.Expr | string): BooleanExpr { * @param value The expression to check. * @return A new {@code Expr} representing the 'isNull' check. */ -export function isNull(value: firestore.Expr): BooleanExpr; +export function isNull(value: Expr): BooleanExpr; /** - * @beta - * * Creates an expression that checks if a field's value evaluates to 'NaN' (Not a Number). * * ```typescript @@ -3226,13 +3040,11 @@ export function isNull(value: firestore.Expr): BooleanExpr; * @return A new {@code Expr} representing the 'isNull' check. */ export function isNull(value: string): BooleanExpr; -export function isNull(value: firestore.Expr | string): BooleanExpr { +export function isNull(value: Expr | string): BooleanExpr { return fieldOrExpression(value).isNull(); } /** - * @beta - * * Creates an expression that checks if tbe result of an expression is not null. * * ```typescript @@ -3243,11 +3055,9 @@ export function isNull(value: firestore.Expr | string): BooleanExpr { * @param value The expression to check. * @return A new {@code Expr} representing the 'isNotNull' check. */ -export function isNotNull(value: firestore.Expr): BooleanExpr; +export function isNotNull(value: Expr): BooleanExpr; /** - * @beta - * * Creates an expression that checks if tbe value of a field is not null. * * ```typescript @@ -3259,13 +3069,11 @@ export function isNotNull(value: firestore.Expr): BooleanExpr; * @return A new {@code Expr} representing the 'isNotNull' check. */ export function isNotNull(value: string): BooleanExpr; -export function isNotNull(value: firestore.Expr | string): BooleanExpr { +export function isNotNull(value: Expr | string): BooleanExpr { return fieldOrExpression(value).isNotNull(); } /** - * @beta - * * Creates an expression that checks if the results of this expression is NOT 'NaN' (Not a Number). * * ```typescript @@ -3276,7 +3084,7 @@ export function isNotNull(value: firestore.Expr | string): BooleanExpr { * @param value The expression to check. * @return A new {@code Expr} representing the 'isNotNaN' check. */ -export function isNotNan(value: firestore.Expr): BooleanExpr; +export function isNotNan(value: Expr): BooleanExpr; /** * @beta @@ -3292,7 +3100,7 @@ export function isNotNan(value: firestore.Expr): BooleanExpr; * @return A new {@code Expr} representing the 'isNotNaN' check. */ export function isNotNan(value: string): BooleanExpr; -export function isNotNan(value: firestore.Expr | string): BooleanExpr { +export function isNotNan(value: Expr | string): BooleanExpr { return fieldOrExpression(value).isNotNan(); } @@ -3323,7 +3131,7 @@ export function mapRemove(mapField: string, key: string): FunctionExpr; * @param mapExpr An expression return a map value. * @param key The name of the key to remove from the input map. */ -export function mapRemove(mapExpr: firestore.Expr, key: string): FunctionExpr; +export function mapRemove(mapExpr: Expr, key: string): FunctionExpr; /** * @beta * @@ -3337,10 +3145,7 @@ export function mapRemove(mapExpr: firestore.Expr, key: string): FunctionExpr; * @param mapField The name of a field containing a map value. * @param keyExpr An expression that produces the name of the key to remove from the input map. */ -export function mapRemove( - mapField: string, - keyExpr: firestore.Expr -): FunctionExpr; +export function mapRemove(mapField: string, keyExpr: Expr): FunctionExpr; /** * @beta * @@ -3354,14 +3159,11 @@ export function mapRemove( * @param mapExpr An expression return a map value. * @param keyExpr An expression that produces the name of the key to remove from the input map. */ -export function mapRemove( - mapExpr: firestore.Expr, - keyExpr: firestore.Expr -): FunctionExpr; +export function mapRemove(mapExpr: Expr, keyExpr: Expr): FunctionExpr; export function mapRemove( - mapExpr: firestore.Expr | string, - stringExpr: firestore.Expr | string + mapExpr: Expr | string, + stringExpr: Expr | string ): FunctionExpr { return fieldOrExpression(mapExpr).mapRemove(valueToDefaultExpr(stringExpr)); } @@ -3385,8 +3187,8 @@ export function mapRemove( */ export function mapMerge( mapField: string, - secondMap: Record | firestore.Expr, - ...otherMaps: Array | firestore.Expr> + secondMap: Record | Expr, + ...otherMaps: Array | Expr> ): FunctionExpr; /** @@ -3407,15 +3209,15 @@ export function mapMerge( * as a literal or an expression that returns a map. */ export function mapMerge( - firstMap: Record | firestore.Expr, - secondMap: Record | firestore.Expr, - ...otherMaps: Array | firestore.Expr> + firstMap: Record | Expr, + secondMap: Record | Expr, + ...otherMaps: Array | Expr> ): FunctionExpr; export function mapMerge( - firstMap: string | Record | firestore.Expr, - secondMap: Record | firestore.Expr, - ...otherMaps: Array | firestore.Expr> + firstMap: string | Record | Expr, + secondMap: Record | Expr, + ...otherMaps: Array | Expr> ): FunctionExpr { const secondMapExpr = valueToDefaultExpr(secondMap); const otherMapExprs = otherMaps.map(valueToDefaultExpr); @@ -3450,10 +3252,10 @@ export function documentId( * * @return A new {@code Expr} representing the documentId operation. */ -export function documentId(documentPathExpr: firestore.Expr): FunctionExpr; +export function documentId(documentPathExpr: Expr): FunctionExpr; export function documentId( - documentPath: firestore.Expr | string | firestore.DocumentReference + documentPath: Expr | string | firestore.DocumentReference ): FunctionExpr { const documentPathExpr = valueToDefaultExpr(documentPath); return documentPathExpr.documentId(); @@ -3484,7 +3286,7 @@ export function substr( * @param length Length of the substring. */ export function substr( - input: firestore.Expr, + input: Expr, position: number, length?: number ): FunctionExpr; @@ -3500,8 +3302,8 @@ export function substr( */ export function substr( field: string, - position: firestore.Expr, - length?: firestore.Expr + position: Expr, + length?: Expr ): FunctionExpr; /** @@ -3514,15 +3316,15 @@ export function substr( * @param length An expression that returns the length of the substring. */ export function substr( - input: firestore.Expr, - position: firestore.Expr, - length?: firestore.Expr + input: Expr, + position: Expr, + length?: Expr ): FunctionExpr; export function substr( - field: firestore.Expr | string, - position: firestore.Expr | number, - length?: firestore.Expr | number + field: Expr | string, + position: Expr | number, + length?: Expr | number ): FunctionExpr { const fieldExpr = fieldOrExpression(field); const positionExpr = valueToDefaultExpr(position); @@ -3534,7 +3336,7 @@ export function substr( /** * @beta * - * Creates an expression that adds two expressions together. + * Creates an expression that adds the result of two expressions together. * * ```typescript * // Add the value of the 'quantity' field and the 'reserve' field. @@ -3543,19 +3345,14 @@ export function substr( * * @param first The first expression to add. * @param second The second expression or literal to add. - * @param others Optional other expressions or literals to add. * @return A new {@code Expr} representing the addition operation. */ -export function add( - first: firestore.Expr, - second: firestore.Expr | unknown, - ...others: Array -): FunctionExpr; +export function add(first: Expr, second: Expr | unknown): FunctionExpr; /** * @beta * - * Creates an expression that adds a field's value to an expression. + * Creates an expression that adds a field's value to the result of an expression. * * ```typescript * // Add the value of the 'quantity' field and the 'reserve' field. @@ -3564,24 +3361,15 @@ export function add( * * @param fieldName The name of the field containing the value to add. * @param second The second expression or literal to add. - * @param others Optional other expressions or literals to add. * @return A new {@code Expr} representing the addition operation. */ -export function add( - fieldName: string, - second: firestore.Expr | unknown, - ...others: Array -): FunctionExpr; +export function add(fieldName: string, second: Expr | unknown): FunctionExpr; export function add( - first: firestore.Expr | string, - second: firestore.Expr | unknown, - ...others: Array + first: Expr | string, + second: Expr | unknown ): FunctionExpr { - return fieldOrExpression(first).add( - valueToDefaultExpr(second), - ...others.map(value => valueToDefaultExpr(value)) - ); + return fieldOrExpression(first).add(valueToDefaultExpr(second)); } /** @@ -3598,10 +3386,7 @@ export function add( * @param right The expression to subtract. * @return A new {@code Expr} representing the subtraction operation. */ -export function subtract( - left: firestore.Expr, - right: firestore.Expr -): FunctionExpr; +export function subtract(left: Expr, right: Expr): FunctionExpr; /** * @beta @@ -3617,10 +3402,7 @@ export function subtract( * @param value The constant value to subtract. * @return A new {@code Expr} representing the subtraction operation. */ -export function subtract( - expression: firestore.Expr, - value: unknown -): FunctionExpr; +export function subtract(expression: Expr, value: unknown): FunctionExpr; /** * @beta @@ -3636,10 +3418,7 @@ export function subtract( * @param expression The expression to subtract. * @return A new {@code Expr} representing the subtraction operation. */ -export function subtract( - fieldName: string, - expression: firestore.Expr -): FunctionExpr; +export function subtract(fieldName: string, expression: Expr): FunctionExpr; /** * @beta @@ -3657,8 +3436,8 @@ export function subtract( */ export function subtract(fieldName: string, value: unknown): FunctionExpr; export function subtract( - left: firestore.Expr | string, - right: firestore.Expr | unknown + left: Expr | string, + right: Expr | unknown ): FunctionExpr { const normalizedLeft = fieldOrExpression(left); const normalizedRight = valueToDefaultExpr(right); @@ -3668,7 +3447,7 @@ export function subtract( /** * @beta * - * Creates an expression that multiplies two expressions together. + * Creates an expression that multiplies the result of two expressions together. * * ```typescript * // Multiply the 'quantity' field by the 'price' field @@ -3677,45 +3456,34 @@ export function subtract( * * @param first The first expression to multiply. * @param second The second expression or literal to multiply. - * @param others Optional additional expressions or literals to multiply. * @return A new {@code Expr} representing the multiplication operation. */ -export function multiply( - first: firestore.Expr, - second: firestore.Expr | unknown, - ...others: Array -): FunctionExpr; +export function multiply(first: Expr, second: Expr | unknown): FunctionExpr; /** * @beta * - * Creates an expression that multiplies a field's value by an expression. + * Creates an expression that multiplies a field's value by the result of an expression. * * ```typescript * // Multiply the 'quantity' field by the 'price' field * multiply("quantity", field("price")); * ``` * - * @param fieldName The name of the field containing the value to add. - * @param second The second expression or literal to add. - * @param others Optional other expressions or literals to add. + * @param fieldName The name of the field containing the value to multiply. + * @param second The second expression or literal to multiply. * @return A new {@code Expr} representing the multiplication operation. */ export function multiply( fieldName: string, - second: firestore.Expr | unknown, - ...others: Array + second: Expr | unknown ): FunctionExpr; export function multiply( - first: firestore.Expr | string, - second: firestore.Expr | unknown, - ...others: Array + first: Expr | string, + second: Expr | unknown ): FunctionExpr { - return fieldOrExpression(first).multiply( - valueToDefaultExpr(second), - ...others.map(valueToDefaultExpr) - ); + return fieldOrExpression(first).multiply(valueToDefaultExpr(second)); } /** @@ -3732,10 +3500,7 @@ export function multiply( * @param right The expression to divide by. * @return A new {@code Expr} representing the division operation. */ -export function divide( - left: firestore.Expr, - right: firestore.Expr -): FunctionExpr; +export function divide(left: Expr, right: Expr): FunctionExpr; /** * @beta @@ -3751,10 +3516,7 @@ export function divide( * @param value The constant value to divide by. * @return A new {@code Expr} representing the division operation. */ -export function divide( - expression: firestore.Expr, - value: unknown -): FunctionExpr; +export function divide(expression: Expr, value: unknown): FunctionExpr; /** * @beta @@ -3770,10 +3532,7 @@ export function divide( * @param expressions The expression to divide by. * @return A new {@code Expr} representing the division operation. */ -export function divide( - fieldName: string, - expressions: firestore.Expr -): FunctionExpr; +export function divide(fieldName: string, expressions: Expr): FunctionExpr; /** * @beta @@ -3791,8 +3550,8 @@ export function divide( */ export function divide(fieldName: string, value: unknown): FunctionExpr; export function divide( - left: firestore.Expr | string, - right: firestore.Expr | unknown + left: Expr | string, + right: Expr | unknown ): FunctionExpr { const normalizedLeft = fieldOrExpression(left); const normalizedRight = valueToDefaultExpr(right); @@ -3813,7 +3572,7 @@ export function divide( * @param right The divisor expression. * @return A new {@code Expr} representing the modulo operation. */ -export function mod(left: firestore.Expr, right: firestore.Expr): FunctionExpr; +export function mod(left: Expr, right: Expr): FunctionExpr; /** * @beta @@ -3829,7 +3588,7 @@ export function mod(left: firestore.Expr, right: firestore.Expr): FunctionExpr; * @param value The divisor constant. * @return A new {@code Expr} representing the modulo operation. */ -export function mod(expression: firestore.Expr, value: unknown): FunctionExpr; +export function mod(expression: Expr, value: unknown): FunctionExpr; /** * @beta @@ -3845,10 +3604,7 @@ export function mod(expression: firestore.Expr, value: unknown): FunctionExpr; * @param expression The divisor expression. * @return A new {@code Expr} representing the modulo operation. */ -export function mod( - fieldName: string, - expression: firestore.Expr -): FunctionExpr; +export function mod(fieldName: string, expression: Expr): FunctionExpr; /** * @beta @@ -3865,10 +3621,7 @@ export function mod( * @return A new {@code Expr} representing the modulo operation. */ export function mod(fieldName: string, value: unknown): FunctionExpr; -export function mod( - left: firestore.Expr | string, - right: firestore.Expr | unknown -): FunctionExpr { +export function mod(left: Expr | string, right: Expr | unknown): FunctionExpr { const normalizedLeft = fieldOrExpression(left); const normalizedRight = valueToDefaultExpr(right); return normalizedLeft.mod(normalizedRight); @@ -3958,7 +3711,7 @@ export function array(elements: unknown[]): FunctionExpr { * @param right The second expression to compare. * @return A new `Expr` representing the equality comparison. */ -export function eq(left: firestore.Expr, right: firestore.Expr): BooleanExpr; +export function eq(left: Expr, right: Expr): BooleanExpr; /** * @beta @@ -3974,7 +3727,7 @@ export function eq(left: firestore.Expr, right: firestore.Expr): BooleanExpr; * @param value The constant value to compare to. * @return A new `Expr` representing the equality comparison. */ -export function eq(expression: firestore.Expr, value: unknown): BooleanExpr; +export function eq(expression: Expr, value: unknown): BooleanExpr; /** * @beta @@ -3990,7 +3743,7 @@ export function eq(expression: firestore.Expr, value: unknown): BooleanExpr; * @param expression The expression to compare to. * @return A new `Expr` representing the equality comparison. */ -export function eq(fieldName: string, expression: firestore.Expr): BooleanExpr; +export function eq(fieldName: string, expression: Expr): BooleanExpr; /** * @beta @@ -4007,7 +3760,7 @@ export function eq(fieldName: string, expression: firestore.Expr): BooleanExpr; * @return A new `Expr` representing the equality comparison. */ export function eq(fieldName: string, value: unknown): BooleanExpr; -export function eq(left: firestore.Expr | string, right: unknown): BooleanExpr { +export function eq(left: Expr | string, right: unknown): BooleanExpr { const leftExpr = fieldOrExpression(left); const rightExpr = valueToDefaultExpr(right); return leftExpr.eq(rightExpr); @@ -4027,7 +3780,7 @@ export function eq(left: firestore.Expr | string, right: unknown): BooleanExpr { * @param right The second expression to compare. * @return A new `Expr` representing the inequality comparison. */ -export function neq(left: firestore.Expr, right: firestore.Expr): BooleanExpr; +export function neq(left: Expr, right: Expr): BooleanExpr; /** * @beta @@ -4043,7 +3796,7 @@ export function neq(left: firestore.Expr, right: firestore.Expr): BooleanExpr; * @param value The constant value to compare to. * @return A new `Expr` representing the inequality comparison. */ -export function neq(expression: firestore.Expr, value: unknown): BooleanExpr; +export function neq(expression: Expr, value: unknown): BooleanExpr; /** * @beta @@ -4059,7 +3812,7 @@ export function neq(expression: firestore.Expr, value: unknown): BooleanExpr; * @param expression The expression to compare to. * @return A new `Expr` representing the inequality comparison. */ -export function neq(fieldName: string, expression: firestore.Expr): BooleanExpr; +export function neq(fieldName: string, expression: Expr): BooleanExpr; /** * @beta @@ -4076,10 +3829,7 @@ export function neq(fieldName: string, expression: firestore.Expr): BooleanExpr; * @return A new `Expr` representing the inequality comparison. */ export function neq(fieldName: string, value: unknown): BooleanExpr; -export function neq( - left: firestore.Expr | string, - right: unknown -): BooleanExpr { +export function neq(left: Expr | string, right: unknown): BooleanExpr { const leftExpr = fieldOrExpression(left); const rightExpr = valueToDefaultExpr(right); return leftExpr.neq(rightExpr); @@ -4099,7 +3849,7 @@ export function neq( * @param right The second expression to compare. * @return A new `Expr` representing the less than comparison. */ -export function lt(left: firestore.Expr, right: firestore.Expr): BooleanExpr; +export function lt(left: Expr, right: Expr): BooleanExpr; /** * @beta @@ -4115,7 +3865,7 @@ export function lt(left: firestore.Expr, right: firestore.Expr): BooleanExpr; * @param value The constant value to compare to. * @return A new `Expr` representing the less than comparison. */ -export function lt(expression: firestore.Expr, value: unknown): BooleanExpr; +export function lt(expression: Expr, value: unknown): BooleanExpr; /** * @beta @@ -4131,7 +3881,7 @@ export function lt(expression: firestore.Expr, value: unknown): BooleanExpr; * @param expression The expression to compare to. * @return A new `Expr` representing the less than comparison. */ -export function lt(fieldName: string, expression: firestore.Expr): BooleanExpr; +export function lt(fieldName: string, expression: Expr): BooleanExpr; /** * @beta @@ -4148,7 +3898,7 @@ export function lt(fieldName: string, expression: firestore.Expr): BooleanExpr; * @return A new `Expr` representing the less than comparison. */ export function lt(fieldName: string, value: unknown): BooleanExpr; -export function lt(left: firestore.Expr | string, right: unknown): BooleanExpr { +export function lt(left: Expr | string, right: unknown): BooleanExpr { const leftExpr = fieldOrExpression(left); const rightExpr = valueToDefaultExpr(right); return leftExpr.lt(rightExpr); @@ -4169,7 +3919,7 @@ export function lt(left: firestore.Expr | string, right: unknown): BooleanExpr { * @param right The second expression to compare. * @return A new `Expr` representing the less than or equal to comparison. */ -export function lte(left: firestore.Expr, right: firestore.Expr): BooleanExpr; +export function lte(left: Expr, right: Expr): BooleanExpr; /** * @beta @@ -4185,7 +3935,7 @@ export function lte(left: firestore.Expr, right: firestore.Expr): BooleanExpr; * @param value The constant value to compare to. * @return A new `Expr` representing the less than or equal to comparison. */ -export function lte(expression: firestore.Expr, value: unknown): BooleanExpr; +export function lte(expression: Expr, value: unknown): BooleanExpr; /** * Creates an expression that checks if a field's value is less than or equal to an expression. @@ -4199,7 +3949,7 @@ export function lte(expression: firestore.Expr, value: unknown): BooleanExpr; * @param expression The expression to compare to. * @return A new `Expr` representing the less than or equal to comparison. */ -export function lte(fieldName: string, expression: firestore.Expr): BooleanExpr; +export function lte(fieldName: string, expression: Expr): BooleanExpr; /** * @beta @@ -4216,10 +3966,7 @@ export function lte(fieldName: string, expression: firestore.Expr): BooleanExpr; * @return A new `Expr` representing the less than or equal to comparison. */ export function lte(fieldName: string, value: unknown): BooleanExpr; -export function lte( - left: firestore.Expr | string, - right: unknown -): BooleanExpr { +export function lte(left: Expr | string, right: unknown): BooleanExpr { const leftExpr = fieldOrExpression(left); const rightExpr = valueToDefaultExpr(right); return leftExpr.lte(rightExpr); @@ -4240,7 +3987,7 @@ export function lte( * @param right The second expression to compare. * @return A new `Expr` representing the greater than comparison. */ -export function gt(left: firestore.Expr, right: firestore.Expr): BooleanExpr; +export function gt(left: Expr, right: Expr): BooleanExpr; /** * @beta @@ -4256,7 +4003,7 @@ export function gt(left: firestore.Expr, right: firestore.Expr): BooleanExpr; * @param value The constant value to compare to. * @return A new `Expr` representing the greater than comparison. */ -export function gt(expression: firestore.Expr, value: unknown): BooleanExpr; +export function gt(expression: Expr, value: unknown): BooleanExpr; /** * @beta @@ -4272,7 +4019,7 @@ export function gt(expression: firestore.Expr, value: unknown): BooleanExpr; * @param expression The expression to compare to. * @return A new `Expr` representing the greater than comparison. */ -export function gt(fieldName: string, expression: firestore.Expr): BooleanExpr; +export function gt(fieldName: string, expression: Expr): BooleanExpr; /** * @beta @@ -4289,7 +4036,7 @@ export function gt(fieldName: string, expression: firestore.Expr): BooleanExpr; * @return A new `Expr` representing the greater than comparison. */ export function gt(fieldName: string, value: unknown): BooleanExpr; -export function gt(left: firestore.Expr | string, right: unknown): BooleanExpr { +export function gt(left: Expr | string, right: unknown): BooleanExpr { const leftExpr = fieldOrExpression(left); const rightExpr = valueToDefaultExpr(right); return leftExpr.gt(rightExpr); @@ -4310,7 +4057,7 @@ export function gt(left: firestore.Expr | string, right: unknown): BooleanExpr { * @param right The second expression to compare. * @return A new `Expr` representing the greater than or equal to comparison. */ -export function gte(left: firestore.Expr, right: firestore.Expr): BooleanExpr; +export function gte(left: Expr, right: Expr): BooleanExpr; /** * @beta @@ -4327,7 +4074,7 @@ export function gte(left: firestore.Expr, right: firestore.Expr): BooleanExpr; * @param value The constant value to compare to. * @return A new `Expr` representing the greater than or equal to comparison. */ -export function gte(expression: firestore.Expr, value: unknown): BooleanExpr; +export function gte(expression: Expr, value: unknown): BooleanExpr; /** * @beta @@ -4343,7 +4090,7 @@ export function gte(expression: firestore.Expr, value: unknown): BooleanExpr; * @param value The expression to compare to. * @return A new `Expr` representing the greater than or equal to comparison. */ -export function gte(fieldName: string, value: firestore.Expr): BooleanExpr; +export function gte(fieldName: string, value: Expr): BooleanExpr; /** * @beta @@ -4361,10 +4108,7 @@ export function gte(fieldName: string, value: firestore.Expr): BooleanExpr; * @return A new `Expr` representing the greater than or equal to comparison. */ export function gte(fieldName: string, value: unknown): BooleanExpr; -export function gte( - left: firestore.Expr | string, - right: unknown -): BooleanExpr { +export function gte(left: Expr | string, right: unknown): BooleanExpr { const leftExpr = fieldOrExpression(left); const rightExpr = valueToDefaultExpr(right); return leftExpr.gte(rightExpr); @@ -4386,9 +4130,9 @@ export function gte( * @return A new {@code Expr} representing the concatenated array. */ export function arrayConcat( - firstArray: firestore.Expr, - secondArray: firestore.Expr | unknown[], - ...otherArrays: Array + firstArray: Expr, + secondArray: Expr | unknown[], + ...otherArrays: Array ): FunctionExpr; /** @@ -4408,14 +4152,14 @@ export function arrayConcat( */ export function arrayConcat( firstArrayField: string, - secondArray: firestore.Expr | unknown[], - ...otherArrays: Array + secondArray: Expr | unknown[], + ...otherArrays: Array ): FunctionExpr; export function arrayConcat( - firstArray: firestore.Expr | string, - secondArray: firestore.Expr | unknown[], - ...otherArrays: Array + firstArray: Expr | string, + secondArray: Expr | unknown[], + ...otherArrays: Array ): FunctionExpr { const exprValues = otherArrays.map(element => valueToDefaultExpr(element)); return fieldOrExpression(firstArray).arrayConcat( @@ -4438,10 +4182,7 @@ export function arrayConcat( * @param element The element to search for in the array. * @return A new {@code Expr} representing the 'array_contains' comparison. */ -export function arrayContains( - array: firestore.Expr, - element: firestore.Expr -): FunctionExpr; +export function arrayContains(array: Expr, element: Expr): FunctionExpr; /** * @beta @@ -4457,10 +4198,7 @@ export function arrayContains( * @param element The element to search for in the array. * @return A new {@code Expr} representing the 'array_contains' comparison. */ -export function arrayContains( - array: firestore.Expr, - element: unknown -): FunctionExpr; +export function arrayContains(array: Expr, element: unknown): FunctionExpr; /** * @beta @@ -4476,10 +4214,7 @@ export function arrayContains( * @param element The element to search for in the array. * @return A new {@code Expr} representing the 'array_contains' comparison. */ -export function arrayContains( - fieldName: string, - element: firestore.Expr -): FunctionExpr; +export function arrayContains(fieldName: string, element: Expr): FunctionExpr; /** * @beta @@ -4497,7 +4232,7 @@ export function arrayContains( */ export function arrayContains(fieldName: string, element: unknown): BooleanExpr; export function arrayContains( - array: firestore.Expr | string, + array: Expr | string, element: unknown ): BooleanExpr { const arrayExpr = fieldOrExpression(array); @@ -4521,8 +4256,8 @@ export function arrayContains( * @return A new {@code Expr} representing the 'array_contains_any' comparison. */ export function arrayContainsAny( - array: firestore.Expr, - values: Array + array: Expr, + values: Array ): BooleanExpr; /** @@ -4543,7 +4278,7 @@ export function arrayContainsAny( */ export function arrayContainsAny( fieldName: string, - values: Array + values: Array ): BooleanExpr; /** @@ -4561,10 +4296,7 @@ export function arrayContainsAny( * @param values An expression that evaluates to an array, whose elements to check for in the array. * @return A new {@code Expr} representing the 'array_contains_any' comparison. */ -export function arrayContainsAny( - array: firestore.Expr, - values: firestore.Expr -): BooleanExpr; +export function arrayContainsAny(array: Expr, values: Expr): BooleanExpr; /** * @beta @@ -4582,13 +4314,10 @@ export function arrayContainsAny( * @param values An expression that evaluates to an array, whose elements to check for in the array field. * @return A new {@code Expr} representing the 'array_contains_any' comparison. */ +export function arrayContainsAny(fieldName: string, values: Expr): BooleanExpr; export function arrayContainsAny( - fieldName: string, - values: firestore.Expr -): BooleanExpr; -export function arrayContainsAny( - array: firestore.Expr | string, - values: unknown[] | firestore.Expr + array: Expr | string, + values: unknown[] | Expr ): BooleanExpr { if (Array.isArray(values)) { return fieldOrExpression(array).arrayContainsAny(values); @@ -4612,8 +4341,8 @@ export function arrayContainsAny( * @return A new {@code Expr} representing the 'array_contains_all' comparison. */ export function arrayContainsAll( - array: firestore.Expr, - values: Array + array: Expr, + values: Array ): BooleanExpr; /** @@ -4633,7 +4362,7 @@ export function arrayContainsAll( */ export function arrayContainsAll( fieldName: string, - values: Array + values: Array ): BooleanExpr; /** @@ -4651,8 +4380,8 @@ export function arrayContainsAll( * @return A new {@code Expr} representing the 'array_contains_all' comparison. */ export function arrayContainsAll( - array: firestore.Expr, - arrayExpression: firestore.Expr + array: Expr, + arrayExpression: Expr ): BooleanExpr; /** @@ -4672,11 +4401,11 @@ export function arrayContainsAll( */ export function arrayContainsAll( fieldName: string, - arrayExpression: firestore.Expr + arrayExpression: Expr ): BooleanExpr; export function arrayContainsAll( - array: firestore.Expr | string, - values: unknown[] | firestore.Expr + array: Expr | string, + values: unknown[] | Expr ): BooleanExpr { if (Array.isArray(values)) { return fieldOrExpression(array).arrayContainsAll(values); @@ -4713,8 +4442,8 @@ export function arrayLength(fieldName: string): FunctionExpr; * @param array The array expression to calculate the length of. * @return A new {@code Expr} representing the length of the array. */ -export function arrayLength(array: firestore.Expr): FunctionExpr; -export function arrayLength(array: firestore.Expr | string): FunctionExpr { +export function arrayLength(array: Expr): FunctionExpr; +export function arrayLength(array: Expr | string): FunctionExpr { return fieldOrExpression(array).arrayLength(); } @@ -4734,8 +4463,8 @@ export function arrayLength(array: firestore.Expr | string): FunctionExpr { * @return A new {@code Expr} representing the 'IN' comparison. */ export function eqAny( - expression: firestore.Expr, - values: Array + expression: Expr, + values: Array ): BooleanExpr; /** @@ -4752,10 +4481,7 @@ export function eqAny( * @param arrayExpression An expression that evaluates to an array, whose elements to check for equality to the input. * @return A new {@code Expr} representing the 'IN' comparison. */ -export function eqAny( - expression: firestore.Expr, - arrayExpression: firestore.Expr -): BooleanExpr; +export function eqAny(expression: Expr, arrayExpression: Expr): BooleanExpr; /** * @beta @@ -4774,7 +4500,7 @@ export function eqAny( */ export function eqAny( fieldName: string, - values: Array + values: Array ): BooleanExpr; /** @@ -4792,13 +4518,10 @@ export function eqAny( * @param arrayExpression An expression that evaluates to an array, whose elements to check for equality to the input field. * @return A new {@code Expr} representing the 'IN' comparison. */ +export function eqAny(fieldName: string, arrayExpression: Expr): BooleanExpr; export function eqAny( - fieldName: string, - arrayExpression: firestore.Expr -): BooleanExpr; -export function eqAny( - element: firestore.Expr | string, - values: unknown[] | firestore.Expr + element: Expr | string, + values: unknown[] | Expr ): BooleanExpr { if (Array.isArray(values)) { return fieldOrExpression(element).eqAny(values); @@ -4823,8 +4546,8 @@ export function eqAny( * @return A new {@code Expr} representing the 'NOT IN' comparison. */ export function notEqAny( - element: firestore.Expr, - values: Array + element: Expr, + values: Array ): BooleanExpr; /** @@ -4844,7 +4567,7 @@ export function notEqAny( */ export function notEqAny( fieldName: string, - values: Array + values: Array ): BooleanExpr; /** @@ -4862,10 +4585,7 @@ export function notEqAny( * @param arrayExpression The values to check against. * @return A new {@code Expr} representing the 'NOT IN' comparison. */ -export function notEqAny( - element: firestore.Expr, - arrayExpression: firestore.Expr -): BooleanExpr; +export function notEqAny(element: Expr, arrayExpression: Expr): BooleanExpr; /** * @beta @@ -4881,14 +4601,11 @@ export function notEqAny( * @param arrayExpression The values to check against. * @return A new {@code Expr} representing the 'NOT IN' comparison. */ -export function notEqAny( - fieldName: string, - arrayExpression: firestore.Expr -): BooleanExpr; +export function notEqAny(fieldName: string, arrayExpression: Expr): BooleanExpr; export function notEqAny( - element: firestore.Expr | string, - values: unknown[] | firestore.Expr + element: Expr | string, + values: unknown[] | Expr ): BooleanExpr { if (Array.isArray(values)) { return fieldOrExpression(element).notEqAny(values); @@ -4943,8 +4660,8 @@ export function xor( */ export function cond( condition: BooleanExpr, - thenExpr: firestore.Expr, - elseExpr: firestore.Expr + thenExpr: Expr, + elseExpr: Expr ): FunctionExpr { return new FunctionExpr('cond', [ condition, @@ -4988,9 +4705,9 @@ export function not(booleanExpr: BooleanExpr): BooleanExpr { * @return A new {@code Expr} representing the logical max operation. */ export function logicalMaximum( - first: firestore.Expr, - second: firestore.Expr | unknown, - ...others: Array + first: Expr, + second: Expr | unknown, + ...others: Array ): FunctionExpr; /** @@ -5012,14 +4729,14 @@ export function logicalMaximum( */ export function logicalMaximum( fieldName: string, - second: firestore.Expr | unknown, - ...others: Array + second: Expr | unknown, + ...others: Array ): FunctionExpr; export function logicalMaximum( - first: firestore.Expr | string, - second: firestore.Expr | unknown, - ...others: Array + first: Expr | string, + second: Expr | unknown, + ...others: Array ): FunctionExpr { return fieldOrExpression(first).logicalMaximum( valueToDefaultExpr(second), @@ -5045,9 +4762,9 @@ export function logicalMaximum( * @return A new {@code Expr} representing the logical min operation. */ export function logicalMinimum( - first: firestore.Expr, - second: firestore.Expr | unknown, - ...others: Array + first: Expr, + second: Expr | unknown, + ...others: Array ): FunctionExpr; /** @@ -5070,14 +4787,14 @@ export function logicalMinimum( */ export function logicalMinimum( fieldName: string, - second: firestore.Expr | unknown, - ...others: Array + second: Expr | unknown, + ...others: Array ): FunctionExpr; export function logicalMinimum( - first: firestore.Expr | string, - second: firestore.Expr | unknown, - ...others: Array + first: Expr | string, + second: Expr | unknown, + ...others: Array ): FunctionExpr { return fieldOrExpression(first).logicalMinimum( valueToDefaultExpr(second), @@ -5098,7 +4815,7 @@ export function logicalMinimum( * @param value An expression evaluates to the name of the field to check. * @return A new {@code Expr} representing the 'exists' check. */ -export function exists(value: firestore.Expr): BooleanExpr; +export function exists(value: Expr): BooleanExpr; /** * @beta @@ -5114,7 +4831,7 @@ export function exists(value: firestore.Expr): BooleanExpr; * @return A new {@code Expr} representing the 'exists' check. */ export function exists(fieldName: string): BooleanExpr; -export function exists(valueOrField: firestore.Expr | string): BooleanExpr { +export function exists(valueOrField: Expr | string): BooleanExpr { return fieldOrExpression(valueOrField).exists(); } @@ -5131,7 +4848,7 @@ export function exists(valueOrField: firestore.Expr | string): BooleanExpr { * @param value The expression to check. * @return A new {@code Expr} representing the 'isNan' check. */ -export function isNan(value: firestore.Expr): BooleanExpr; +export function isNan(value: Expr): BooleanExpr; /** * @beta @@ -5147,7 +4864,7 @@ export function isNan(value: firestore.Expr): BooleanExpr; * @return A new {@code Expr} representing the 'isNan' check. */ export function isNan(fieldName: string): BooleanExpr; -export function isNan(value: firestore.Expr | string): BooleanExpr { +export function isNan(value: Expr | string): BooleanExpr { return fieldOrExpression(value).isNan(); } @@ -5164,7 +4881,7 @@ export function isNan(value: firestore.Expr | string): BooleanExpr { * @param stringExpression An expression evaluating to a string value, which will be reversed. * @return A new {@code Expr} representing the reversed string. */ -export function reverse(stringExpression: firestore.Expr): FunctionExpr; +export function reverse(stringExpression: Expr): FunctionExpr; /** * @beta @@ -5180,7 +4897,7 @@ export function reverse(stringExpression: firestore.Expr): FunctionExpr; * @return A new {@code Expr} representing the reversed string. */ export function reverse(field: string): FunctionExpr; -export function reverse(expr: firestore.Expr | string): FunctionExpr { +export function reverse(expr: Expr | string): FunctionExpr { return fieldOrExpression(expr).reverse(); } @@ -5200,7 +4917,7 @@ export function reverse(expr: firestore.Expr | string): FunctionExpr { * @return A new {@code Expr} representing the string with the first occurrence replaced. */ export function replaceFirst( - value: firestore.Expr, + value: Expr, find: string, replace: string ): FunctionExpr; @@ -5222,9 +4939,9 @@ export function replaceFirst( * @return A new {@code Expr} representing the string with the first occurrence replaced. */ export function replaceFirst( - value: firestore.Expr, - find: firestore.Expr, - replace: firestore.Expr + value: Expr, + find: Expr, + replace: Expr ): FunctionExpr; /** @@ -5248,9 +4965,9 @@ export function replaceFirst( replace: string ): FunctionExpr; export function replaceFirst( - value: firestore.Expr | string, - find: firestore.Expr | string, - replace: firestore.Expr | string + value: Expr | string, + find: Expr | string, + replace: Expr | string ): FunctionExpr { const normalizedValue = fieldOrExpression(value); const normalizedFind = valueToDefaultExpr(find); @@ -5274,7 +4991,7 @@ export function replaceFirst( * @return A new {@code Expr} representing the string with all occurrences replaced. */ export function replaceAll( - value: firestore.Expr, + value: Expr, find: string, replace: string ): FunctionExpr; @@ -5296,9 +5013,9 @@ export function replaceAll( * @return A new {@code Expr} representing the string with all occurrences replaced. */ export function replaceAll( - value: firestore.Expr, - find: firestore.Expr, - replace: firestore.Expr + value: Expr, + find: Expr, + replace: Expr ): FunctionExpr; /** @@ -5322,9 +5039,9 @@ export function replaceAll( replace: string ): FunctionExpr; export function replaceAll( - value: firestore.Expr | string, - find: firestore.Expr | string, - replace: firestore.Expr | string + value: Expr | string, + find: Expr | string, + replace: Expr | string ): FunctionExpr { const normalizedValue = fieldOrExpression(value); const normalizedFind = valueToDefaultExpr(find); @@ -5345,7 +5062,7 @@ export function replaceAll( * @param expr The expression representing the string. * @return A new {@code Expr} representing the length of the string in bytes. */ -export function byteLength(expr: firestore.Expr): FunctionExpr; +export function byteLength(expr: Expr): FunctionExpr; /** * @beta @@ -5361,7 +5078,7 @@ export function byteLength(expr: firestore.Expr): FunctionExpr; * @return A new {@code Expr} representing the length of the string in bytes. */ export function byteLength(fieldName: string): FunctionExpr; -export function byteLength(expr: firestore.Expr | string): FunctionExpr { +export function byteLength(expr: Expr | string): FunctionExpr { const normalizedExpr = fieldOrExpression(expr); return normalizedExpr.byteLength(); } @@ -5394,8 +5111,8 @@ export function charLength(fieldName: string): FunctionExpr; * @param stringExpression The expression representing the string to calculate the length of. * @return A new {@code Expr} representing the length of the string. */ -export function charLength(stringExpression: firestore.Expr): FunctionExpr; -export function charLength(value: firestore.Expr | string): FunctionExpr { +export function charLength(stringExpression: Expr): FunctionExpr; +export function charLength(value: Expr | string): FunctionExpr { const valueExpr = fieldOrExpression(value); return valueExpr.charLength(); } @@ -5432,7 +5149,7 @@ export function like(fieldName: string, pattern: string): BooleanExpr; * @param pattern The pattern to search for. You can use "%" as a wildcard character. * @return A new {@code Expr} representing the 'like' comparison. */ -export function like(fieldName: string, pattern: firestore.Expr): BooleanExpr; +export function like(fieldName: string, pattern: Expr): BooleanExpr; /** * @beta @@ -5448,10 +5165,7 @@ export function like(fieldName: string, pattern: firestore.Expr): BooleanExpr; * @param pattern The pattern to search for. You can use "%" as a wildcard character. * @return A new {@code Expr} representing the 'like' comparison. */ -export function like( - stringExpression: firestore.Expr, - pattern: string -): BooleanExpr; +export function like(stringExpression: Expr, pattern: string): BooleanExpr; /** * @beta @@ -5467,13 +5181,10 @@ export function like( * @param pattern The pattern to search for. You can use "%" as a wildcard character. * @return A new {@code Expr} representing the 'like' comparison. */ +export function like(stringExpression: Expr, pattern: Expr): BooleanExpr; export function like( - stringExpression: firestore.Expr, - pattern: firestore.Expr -): BooleanExpr; -export function like( - left: firestore.Expr | string, - pattern: firestore.Expr | string + left: Expr | string, + pattern: Expr | string ): FunctionExpr { const leftExpr = fieldOrExpression(left); const patternExpr = valueToDefaultExpr(pattern); @@ -5512,10 +5223,7 @@ export function regexContains(fieldName: string, pattern: string): BooleanExpr; * @param pattern The regular expression to use for the search. * @return A new {@code Expr} representing the 'contains' comparison. */ -export function regexContains( - fieldName: string, - pattern: firestore.Expr -): BooleanExpr; +export function regexContains(fieldName: string, pattern: Expr): BooleanExpr; /** * @beta @@ -5533,7 +5241,7 @@ export function regexContains( * @return A new {@code Expr} representing the 'contains' comparison. */ export function regexContains( - stringExpression: firestore.Expr, + stringExpression: Expr, pattern: string ): BooleanExpr; @@ -5553,12 +5261,12 @@ export function regexContains( * @return A new {@code Expr} representing the 'contains' comparison. */ export function regexContains( - stringExpression: firestore.Expr, - pattern: firestore.Expr + stringExpression: Expr, + pattern: Expr ): BooleanExpr; export function regexContains( - left: firestore.Expr | string, - pattern: firestore.Expr | string + left: Expr | string, + pattern: Expr | string ): BooleanExpr { const leftExpr = fieldOrExpression(left); const patternExpr = valueToDefaultExpr(pattern); @@ -5595,10 +5303,7 @@ export function regexMatch(fieldName: string, pattern: string): BooleanExpr; * @param pattern The regular expression to use for the match. * @return A new {@code Expr} representing the regular expression match. */ -export function regexMatch( - fieldName: string, - pattern: firestore.Expr -): BooleanExpr; +export function regexMatch(fieldName: string, pattern: Expr): BooleanExpr; /** * @beta @@ -5616,7 +5321,7 @@ export function regexMatch( * @return A new {@code Expr} representing the regular expression match. */ export function regexMatch( - stringExpression: firestore.Expr, + stringExpression: Expr, pattern: string ): BooleanExpr; @@ -5635,13 +5340,10 @@ export function regexMatch( * @param pattern The regular expression to use for the match. * @return A new {@code Expr} representing the regular expression match. */ +export function regexMatch(stringExpression: Expr, pattern: Expr): BooleanExpr; export function regexMatch( - stringExpression: firestore.Expr, - pattern: firestore.Expr -): BooleanExpr; -export function regexMatch( - left: firestore.Expr | string, - pattern: firestore.Expr | string + left: Expr | string, + pattern: Expr | string ): BooleanExpr { const leftExpr = fieldOrExpression(left); const patternExpr = valueToDefaultExpr(pattern); @@ -5678,10 +5380,7 @@ export function strContains(fieldName: string, substring: string): BooleanExpr; * @param substring The expression representing the substring to search for. * @return A new {@code Expr} representing the 'contains' comparison. */ -export function strContains( - fieldName: string, - substring: firestore.Expr -): BooleanExpr; +export function strContains(fieldName: string, substring: Expr): BooleanExpr; /** * @beta @@ -5698,7 +5397,7 @@ export function strContains( * @return A new {@code Expr} representing the 'contains' comparison. */ export function strContains( - stringExpression: firestore.Expr, + stringExpression: Expr, substring: string ): BooleanExpr; @@ -5717,12 +5416,12 @@ export function strContains( * @return A new {@code Expr} representing the 'contains' comparison. */ export function strContains( - stringExpression: firestore.Expr, - substring: firestore.Expr + stringExpression: Expr, + substring: Expr ): BooleanExpr; export function strContains( - left: firestore.Expr | string, - substring: firestore.Expr | string + left: Expr | string, + substring: Expr | string ): BooleanExpr { const leftExpr = fieldOrExpression(left); const substringExpr = valueToDefaultExpr(substring); @@ -5759,10 +5458,7 @@ export function startsWith(fieldName: string, prefix: string): BooleanExpr; * @param prefix The expression representing the prefix. * @return A new {@code Expr} representing the 'starts with' comparison. */ -export function startsWith( - fieldName: string, - prefix: firestore.Expr -): BooleanExpr; +export function startsWith(fieldName: string, prefix: Expr): BooleanExpr; /** * @beta @@ -5778,10 +5474,7 @@ export function startsWith( * @param prefix The prefix to check for. * @return A new {@code Expr} representing the 'starts with' comparison. */ -export function startsWith( - stringExpression: firestore.Expr, - prefix: string -): BooleanExpr; +export function startsWith(stringExpression: Expr, prefix: string): BooleanExpr; /** * @beta @@ -5797,13 +5490,10 @@ export function startsWith( * @param prefix The prefix to check for. * @return A new {@code Expr} representing the 'starts with' comparison. */ +export function startsWith(stringExpression: Expr, prefix: Expr): BooleanExpr; export function startsWith( - stringExpression: firestore.Expr, - prefix: firestore.Expr -): BooleanExpr; -export function startsWith( - expr: firestore.Expr | string, - prefix: firestore.Expr | string + expr: Expr | string, + prefix: Expr | string ): BooleanExpr { return fieldOrExpression(expr).startsWith(valueToDefaultExpr(prefix)); } @@ -5838,10 +5528,7 @@ export function endsWith(fieldName: string, suffix: string): BooleanExpr; * @param suffix The expression representing the postfix. * @return A new {@code Expr} representing the 'ends with' comparison. */ -export function endsWith( - fieldName: string, - suffix: firestore.Expr -): BooleanExpr; +export function endsWith(fieldName: string, suffix: Expr): BooleanExpr; /** * @beta @@ -5857,10 +5544,7 @@ export function endsWith( * @param suffix The postfix to check for. * @return A new {@code Expr} representing the 'ends with' comparison. */ -export function endsWith( - stringExpression: firestore.Expr, - suffix: string -): BooleanExpr; +export function endsWith(stringExpression: Expr, suffix: string): BooleanExpr; /** * @beta @@ -5876,13 +5560,10 @@ export function endsWith( * @param suffix The postfix to check for. * @return A new {@code Expr} representing the 'ends with' comparison. */ +export function endsWith(stringExpression: Expr, suffix: Expr): BooleanExpr; export function endsWith( - stringExpression: firestore.Expr, - suffix: firestore.Expr -): BooleanExpr; -export function endsWith( - expr: firestore.Expr | string, - suffix: firestore.Expr | string + expr: Expr | string, + suffix: Expr | string ): BooleanExpr { return fieldOrExpression(expr).endsWith(valueToDefaultExpr(suffix)); } @@ -5915,8 +5596,8 @@ export function toLower(fieldName: string): FunctionExpr; * @param stringExpression The expression representing the string to convert to lowercase. * @return A new {@code Expr} representing the lowercase string. */ -export function toLower(stringExpression: firestore.Expr): FunctionExpr; -export function toLower(expr: firestore.Expr | string): FunctionExpr { +export function toLower(stringExpression: Expr): FunctionExpr; +export function toLower(expr: Expr | string): FunctionExpr { return fieldOrExpression(expr).toLower(); } @@ -5948,8 +5629,8 @@ export function toUpper(fieldName: string): FunctionExpr; * @param stringExpression The expression representing the string to convert to uppercase. * @return A new {@code Expr} representing the uppercase string. */ -export function toUpper(stringExpression: firestore.Expr): FunctionExpr; -export function toUpper(expr: firestore.Expr | string): FunctionExpr { +export function toUpper(stringExpression: Expr): FunctionExpr; +export function toUpper(expr: Expr | string): FunctionExpr { return fieldOrExpression(expr).toUpper(); } @@ -5981,8 +5662,8 @@ export function trim(fieldName: string): FunctionExpr; * @param stringExpression The expression representing the string to trim. * @return A new {@code Expr} representing the trimmed string. */ -export function trim(stringExpression: firestore.Expr): FunctionExpr; -export function trim(expr: firestore.Expr | string): FunctionExpr { +export function trim(stringExpression: Expr): FunctionExpr; +export function trim(expr: Expr | string): FunctionExpr { return fieldOrExpression(expr).trim(); } @@ -6003,8 +5684,8 @@ export function trim(expr: firestore.Expr | string): FunctionExpr { */ export function strConcat( fieldName: string, - secondString: firestore.Expr | string, - ...otherStrings: Array + secondString: Expr | string, + ...otherStrings: Array ): FunctionExpr; /** @@ -6022,14 +5703,14 @@ export function strConcat( * @return A new {@code Expr} representing the concatenated string. */ export function strConcat( - firstString: firestore.Expr, - secondString: firestore.Expr | string, - ...otherStrings: Array + firstString: Expr, + secondString: Expr | string, + ...otherStrings: Array ): FunctionExpr; export function strConcat( - first: string | firestore.Expr, - second: string | firestore.Expr, - ...elements: Array + first: string | Expr, + second: string | Expr, + ...elements: Array ): FunctionExpr { return fieldOrExpression(first).strConcat( valueToDefaultExpr(second), @@ -6067,12 +5748,9 @@ export function mapGet(fieldName: string, subField: string): FunctionExpr; * @param subField The key to access in the map. * @return A new {@code Expr} representing the value associated with the given key in the map. */ +export function mapGet(mapExpression: Expr, subField: string): FunctionExpr; export function mapGet( - mapExpression: firestore.Expr, - subField: string -): FunctionExpr; -export function mapGet( - fieldOrExpr: string | firestore.Expr, + fieldOrExpr: string | Expr, subField: string ): FunctionExpr { return fieldOrExpression(fieldOrExpr).mapGet(subField); @@ -6108,7 +5786,7 @@ export function countAll(): AggregateFunction { * @param expression The expression to count. * @return A new {@code AggregateFunction} representing the 'count' aggregation. */ -export function count(expression: firestore.Expr): AggregateFunction; +export function count(expression: Expr): AggregateFunction; /** * Creates an aggregation that counts the number of stage inputs where the input field exists. @@ -6122,7 +5800,7 @@ export function count(expression: firestore.Expr): AggregateFunction; * @return A new {@code AggregateFunction} representing the 'count' aggregation. */ export function count(fieldName: string): AggregateFunction; -export function count(value: firestore.Expr | string): AggregateFunction { +export function count(value: Expr | string): AggregateFunction { return fieldOrExpression(value).count(); } @@ -6140,7 +5818,7 @@ export function count(value: firestore.Expr | string): AggregateFunction { * @param expression The expression to sum up. * @return A new {@code AggregateFunction} representing the 'sum' aggregation. */ -export function sum(expression: firestore.Expr): AggregateFunction; +export function sum(expression: Expr): AggregateFunction; /** * @beta @@ -6157,7 +5835,7 @@ export function sum(expression: firestore.Expr): AggregateFunction; * @return A new {@code AggregateFunction} representing the 'sum' aggregation. */ export function sum(fieldName: string): AggregateFunction; -export function sum(value: firestore.Expr | string): AggregateFunction { +export function sum(value: Expr | string): AggregateFunction { return fieldOrExpression(value).sum(); } @@ -6175,7 +5853,7 @@ export function sum(value: firestore.Expr | string): AggregateFunction { * @param expression The expression representing the values to average. * @return A new {@code AggregateFunction} representing the 'avg' aggregation. */ -export function avg(expression: firestore.Expr): AggregateFunction; +export function avg(expression: Expr): AggregateFunction; /** * @beta @@ -6192,7 +5870,7 @@ export function avg(expression: firestore.Expr): AggregateFunction; * @return A new {@code AggregateFunction} representing the 'avg' aggregation. */ export function avg(fieldName: string): AggregateFunction; -export function avg(value: firestore.Expr | string): AggregateFunction { +export function avg(value: Expr | string): AggregateFunction { return fieldOrExpression(value).avg(); } @@ -6210,7 +5888,7 @@ export function avg(value: firestore.Expr | string): AggregateFunction { * @param expression The expression to find the minimum value of. * @return A new {@code AggregateFunction} representing the 'min' aggregation. */ -export function minimum(expression: firestore.Expr): AggregateFunction; +export function minimum(expression: Expr): AggregateFunction; /** * @beta @@ -6226,7 +5904,7 @@ export function minimum(expression: firestore.Expr): AggregateFunction; * @return A new {@code AggregateFunction} representing the 'min' aggregation. */ export function minimum(fieldName: string): AggregateFunction; -export function minimum(value: firestore.Expr | string): AggregateFunction { +export function minimum(value: Expr | string): AggregateFunction { return fieldOrExpression(value).minimum(); } @@ -6244,7 +5922,7 @@ export function minimum(value: firestore.Expr | string): AggregateFunction { * @param expression The expression to find the maximum value of. * @return A new {@code AggregateFunction} representing the 'max' aggregation. */ -export function maximum(expression: firestore.Expr): AggregateFunction; +export function maximum(expression: Expr): AggregateFunction; /** * @beta @@ -6260,7 +5938,7 @@ export function maximum(expression: firestore.Expr): AggregateFunction; * @return A new {@code AggregateFunction} representing the 'max' aggregation. */ export function maximum(fieldName: string): AggregateFunction; -export function maximum(value: firestore.Expr | string): AggregateFunction { +export function maximum(value: Expr | string): AggregateFunction { return fieldOrExpression(value).maximum(); } @@ -6299,7 +5977,7 @@ export function cosineDistance( */ export function cosineDistance( fieldName: string, - vectorExpression: firestore.Expr + vectorExpression: Expr ): FunctionExpr; /** @@ -6317,8 +5995,8 @@ export function cosineDistance( * @return A new {@code Expr} representing the cosine distance between the two vectors. */ export function cosineDistance( - vectorExpression: firestore.Expr, - vector: number[] | firestore.Expr + vectorExpression: Expr, + vector: number[] | Expr ): FunctionExpr; /** @@ -6336,12 +6014,12 @@ export function cosineDistance( * @return A new {@code Expr} representing the cosine distance between the two vectors. */ export function cosineDistance( - vectorExpression: firestore.Expr, - otherVectorExpression: firestore.Expr + vectorExpression: Expr, + otherVectorExpression: Expr ): FunctionExpr; export function cosineDistance( - expr: firestore.Expr | string, - other: firestore.Expr | number[] | VectorValue + expr: Expr | string, + other: Expr | number[] | VectorValue ): FunctionExpr { const expr1 = fieldOrExpression(expr); const expr2 = vectorToExpr(other); @@ -6383,7 +6061,7 @@ export function dotProduct( */ export function dotProduct( fieldName: string, - vectorExpression: firestore.Expr + vectorExpression: Expr ): FunctionExpr; /** @@ -6401,7 +6079,7 @@ export function dotProduct( * @return A new {@code Expr} representing the dot product between the two vectors. */ export function dotProduct( - vectorExpression: firestore.Expr, + vectorExpression: Expr, vector: number[] | VectorValue ): FunctionExpr; @@ -6420,12 +6098,12 @@ export function dotProduct( * @return A new {@code Expr} representing the dot product between the two vectors. */ export function dotProduct( - vectorExpression: firestore.Expr, - otherVectorExpression: firestore.Expr + vectorExpression: Expr, + otherVectorExpression: Expr ): FunctionExpr; export function dotProduct( - expr: firestore.Expr | string, - other: firestore.Expr | number[] | VectorValue + expr: Expr | string, + other: Expr | number[] | VectorValue ): FunctionExpr { const expr1 = fieldOrExpression(expr); const expr2 = vectorToExpr(other); @@ -6467,7 +6145,7 @@ export function euclideanDistance( */ export function euclideanDistance( fieldName: string, - vectorExpression: firestore.Expr + vectorExpression: Expr ): FunctionExpr; /** @@ -6486,7 +6164,7 @@ export function euclideanDistance( * @return A new {@code Expr} representing the Euclidean distance between the two vectors. */ export function euclideanDistance( - vectorExpression: firestore.Expr, + vectorExpression: Expr, vector: number[] | VectorValue ): FunctionExpr; @@ -6505,12 +6183,12 @@ export function euclideanDistance( * @return A new {@code Expr} representing the Euclidean distance between the two vectors. */ export function euclideanDistance( - vectorExpression: firestore.Expr, - otherVectorExpression: firestore.Expr + vectorExpression: Expr, + otherVectorExpression: Expr ): FunctionExpr; export function euclideanDistance( - expr: firestore.Expr | string, - other: firestore.Expr | number[] | VectorValue + expr: Expr | string, + other: Expr | number[] | VectorValue ): FunctionExpr { const expr1 = fieldOrExpression(expr); const expr2 = vectorToExpr(other); @@ -6530,7 +6208,7 @@ export function euclideanDistance( * @param vectorExpression The expression representing the Firestore Vector. * @return A new {@code Expr} representing the length of the array. */ -export function vectorLength(vectorExpression: firestore.Expr): FunctionExpr; +export function vectorLength(vectorExpression: Expr): FunctionExpr; /** * @beta @@ -6546,7 +6224,7 @@ export function vectorLength(vectorExpression: firestore.Expr): FunctionExpr; * @return A new {@code Expr} representing the length of the array. */ export function vectorLength(fieldName: string): FunctionExpr; -export function vectorLength(expr: firestore.Expr | string): FunctionExpr { +export function vectorLength(expr: Expr | string): FunctionExpr { return fieldOrExpression(expr).vectorLength(); } @@ -6564,7 +6242,7 @@ export function vectorLength(expr: firestore.Expr | string): FunctionExpr { * @param expr The expression representing the number of microseconds since epoch. * @return A new {@code Expr} representing the timestamp. */ -export function unixMicrosToTimestamp(expr: firestore.Expr): FunctionExpr; +export function unixMicrosToTimestamp(expr: Expr): FunctionExpr; /** * @beta @@ -6581,9 +6259,7 @@ export function unixMicrosToTimestamp(expr: firestore.Expr): FunctionExpr; * @return A new {@code Expr} representing the timestamp. */ export function unixMicrosToTimestamp(fieldName: string): FunctionExpr; -export function unixMicrosToTimestamp( - expr: firestore.Expr | string -): FunctionExpr { +export function unixMicrosToTimestamp(expr: Expr | string): FunctionExpr { return fieldOrExpression(expr).unixMicrosToTimestamp(); } @@ -6600,7 +6276,7 @@ export function unixMicrosToTimestamp( * @param expr The expression representing the timestamp. * @return A new {@code Expr} representing the number of microseconds since epoch. */ -export function timestampToUnixMicros(expr: firestore.Expr): FunctionExpr; +export function timestampToUnixMicros(expr: Expr): FunctionExpr; /** * @beta @@ -6616,9 +6292,7 @@ export function timestampToUnixMicros(expr: firestore.Expr): FunctionExpr; * @return A new {@code Expr} representing the number of microseconds since epoch. */ export function timestampToUnixMicros(fieldName: string): FunctionExpr; -export function timestampToUnixMicros( - expr: firestore.Expr | string -): FunctionExpr { +export function timestampToUnixMicros(expr: Expr | string): FunctionExpr { return fieldOrExpression(expr).timestampToUnixMicros(); } @@ -6636,7 +6310,7 @@ export function timestampToUnixMicros( * @param expr The expression representing the number of milliseconds since epoch. * @return A new {@code Expr} representing the timestamp. */ -export function unixMillisToTimestamp(expr: firestore.Expr): FunctionExpr; +export function unixMillisToTimestamp(expr: Expr): FunctionExpr; /** * @beta @@ -6653,9 +6327,7 @@ export function unixMillisToTimestamp(expr: firestore.Expr): FunctionExpr; * @return A new {@code Expr} representing the timestamp. */ export function unixMillisToTimestamp(fieldName: string): FunctionExpr; -export function unixMillisToTimestamp( - expr: firestore.Expr | string -): FunctionExpr { +export function unixMillisToTimestamp(expr: Expr | string): FunctionExpr { const normalizedExpr = fieldOrExpression(expr); return normalizedExpr.unixMillisToTimestamp(); } @@ -6673,7 +6345,7 @@ export function unixMillisToTimestamp( * @param expr The expression representing the timestamp. * @return A new {@code Expr} representing the number of milliseconds since epoch. */ -export function timestampToUnixMillis(expr: firestore.Expr): FunctionExpr; +export function timestampToUnixMillis(expr: Expr): FunctionExpr; /** * @beta @@ -6689,9 +6361,7 @@ export function timestampToUnixMillis(expr: firestore.Expr): FunctionExpr; * @return A new {@code Expr} representing the number of milliseconds since epoch. */ export function timestampToUnixMillis(fieldName: string): FunctionExpr; -export function timestampToUnixMillis( - expr: firestore.Expr | string -): FunctionExpr { +export function timestampToUnixMillis(expr: Expr | string): FunctionExpr { const normalizedExpr = fieldOrExpression(expr); return normalizedExpr.timestampToUnixMillis(); } @@ -6710,7 +6380,7 @@ export function timestampToUnixMillis( * @param expr The expression representing the number of seconds since epoch. * @return A new {@code Expr} representing the timestamp. */ -export function unixSecondsToTimestamp(expr: firestore.Expr): FunctionExpr; +export function unixSecondsToTimestamp(expr: Expr): FunctionExpr; /** * @beta @@ -6727,9 +6397,7 @@ export function unixSecondsToTimestamp(expr: firestore.Expr): FunctionExpr; * @return A new {@code Expr} representing the timestamp. */ export function unixSecondsToTimestamp(fieldName: string): FunctionExpr; -export function unixSecondsToTimestamp( - expr: firestore.Expr | string -): FunctionExpr { +export function unixSecondsToTimestamp(expr: Expr | string): FunctionExpr { const normalizedExpr = fieldOrExpression(expr); return normalizedExpr.unixSecondsToTimestamp(); } @@ -6747,7 +6415,7 @@ export function unixSecondsToTimestamp( * @param expr The expression representing the timestamp. * @return A new {@code Expr} representing the number of seconds since epoch. */ -export function timestampToUnixSeconds(expr: firestore.Expr): FunctionExpr; +export function timestampToUnixSeconds(expr: Expr): FunctionExpr; /** * @beta @@ -6763,9 +6431,7 @@ export function timestampToUnixSeconds(expr: firestore.Expr): FunctionExpr; * @return A new {@code Expr} representing the number of seconds since epoch. */ export function timestampToUnixSeconds(fieldName: string): FunctionExpr; -export function timestampToUnixSeconds( - expr: firestore.Expr | string -): FunctionExpr { +export function timestampToUnixSeconds(expr: Expr | string): FunctionExpr { const normalizedExpr = fieldOrExpression(expr); return normalizedExpr.timestampToUnixSeconds(); } @@ -6786,9 +6452,9 @@ export function timestampToUnixSeconds( * @return A new {@code Expr} representing the resulting timestamp. */ export function timestampAdd( - timestamp: firestore.Expr, - unit: firestore.Expr, - amount: firestore.Expr + timestamp: Expr, + unit: Expr, + amount: Expr ): FunctionExpr; /** @@ -6807,7 +6473,7 @@ export function timestampAdd( * @return A new {@code Expr} representing the resulting timestamp. */ export function timestampAdd( - timestamp: firestore.Expr, + timestamp: Expr, unit: 'microsecond' | 'millisecond' | 'second' | 'minute' | 'hour' | 'day', amount: number ): FunctionExpr; @@ -6833,16 +6499,16 @@ export function timestampAdd( amount: number ): FunctionExpr; export function timestampAdd( - timestamp: firestore.Expr | string, + timestamp: Expr | string, unit: - | firestore.Expr + | Expr | 'microsecond' | 'millisecond' | 'second' | 'minute' | 'hour' | 'day', - amount: firestore.Expr | number + amount: Expr | number ): FunctionExpr { const normalizedTimestamp = fieldOrExpression(timestamp); const normalizedUnit = valueToDefaultExpr(unit); @@ -6866,9 +6532,9 @@ export function timestampAdd( * @return A new {@code Expr} representing the resulting timestamp. */ export function timestampSub( - timestamp: firestore.Expr, - unit: firestore.Expr, - amount: firestore.Expr + timestamp: Expr, + unit: Expr, + amount: Expr ): FunctionExpr; /** @@ -6887,7 +6553,7 @@ export function timestampSub( * @return A new {@code Expr} representing the resulting timestamp. */ export function timestampSub( - timestamp: firestore.Expr, + timestamp: Expr, unit: 'microsecond' | 'millisecond' | 'second' | 'minute' | 'hour' | 'day', amount: number ): FunctionExpr; @@ -6913,16 +6579,16 @@ export function timestampSub( amount: number ): FunctionExpr; export function timestampSub( - timestamp: firestore.Expr | string, + timestamp: Expr | string, unit: - | firestore.Expr + | Expr | 'microsecond' | 'millisecond' | 'second' | 'minute' | 'hour' | 'day', - amount: firestore.Expr | number + amount: Expr | number ): FunctionExpr { const normalizedTimestamp = fieldOrExpression(timestamp); const normalizedUnit = valueToDefaultExpr(unit); @@ -6985,14 +6651,14 @@ export function or( * * ```typescript * // Sort documents by the 'name' field in lowercase in ascending order - * firestore.pipeline().collection("users") + * db.pipeline().collection("users") * .sort(ascending(field("name").toLower())); * ``` * * @param expr The expression to create an ascending ordering for. * @return A new `Ordering` for ascending sorting. */ -export function ascending(expr: firestore.Expr): Ordering; +export function ascending(expr: Expr): Ordering; /** * @beta @@ -7001,7 +6667,7 @@ export function ascending(expr: firestore.Expr): Ordering; * * ```typescript * // Sort documents by the 'name' field in ascending order - * firestore.pipeline().collection("users") + * db.pipeline().collection("users") * .sort(ascending("name")); * ``` * @@ -7009,7 +6675,7 @@ export function ascending(expr: firestore.Expr): Ordering; * @return A new `Ordering` for ascending sorting. */ export function ascending(fieldName: string): Ordering; -export function ascending(field: firestore.Expr | string): Ordering { +export function ascending(field: Expr | string): Ordering { return new Ordering(fieldOrExpression(field), 'ascending'); } @@ -7020,14 +6686,14 @@ export function ascending(field: firestore.Expr | string): Ordering { * * ```typescript * // Sort documents by the 'name' field in lowercase in descending order - * firestore.pipeline().collection("users") + * db.pipeline().collection("users") * .sort(descending(field("name").toLower())); * ``` * * @param expr The expression to create a descending ordering for. * @return A new `Ordering` for descending sorting. */ -export function descending(expr: firestore.Expr): Ordering; +export function descending(expr: Expr): Ordering; /** * @beta @@ -7036,7 +6702,7 @@ export function descending(expr: firestore.Expr): Ordering; * * ```typescript * // Sort documents by the 'name' field in descending order - * firestore.pipeline().collection("users") + * db.pipeline().collection("users") * .sort(descending("name")); * ``` * @@ -7044,7 +6710,7 @@ export function descending(expr: firestore.Expr): Ordering; * @return A new `Ordering` for descending sorting. */ export function descending(fieldName: string): Ordering; -export function descending(field: firestore.Expr | string): Ordering { +export function descending(field: Expr | string): Ordering { return new Ordering(fieldOrExpression(field), 'descending'); } @@ -7057,7 +6723,7 @@ export function descending(field: firestore.Expr | string): Ordering { */ export class Ordering implements HasUserData { constructor( - readonly expr: firestore.Expr, + readonly expr: Expr, readonly direction: 'ascending' | 'descending' ) {} diff --git a/dev/src/pipelines/index.ts b/dev/src/pipelines/index.ts new file mode 100644 index 000000000..98aab7464 --- /dev/null +++ b/dev/src/pipelines/index.ts @@ -0,0 +1,121 @@ +// Copyright 2025 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. + +export { + Pipeline, + PipelineResult, + PipelineSnapshot, + PipelineSource, +} from './pipelines'; + +export { + and, + arrayContains, + arrayContainsAny, + avg, + eq, + gt, + like, + lt, + neq, + ascending, + not, + or, + regexContains, + regexMatch, + startsWith, + strConcat, + subtract, + cosineDistance, + dotProduct, + euclideanDistance, + mapGet, + lte, + eqAny, + map, + array, + bitNot, + field, + xor, + AggregateFunction, + rand, + arrayOffset, + add, + BooleanExpr, + Expr, + FunctionExpr, + minimum, + count, + countIf, + arrayLength, + strContains, + charLength, + divide, + mod, + reverse, + trim, + toUpper, + toLower, + vectorLength, + isNotNan, + exists, + isNotNull, + isAbsent, + ifError, + isError, + isNan, + arrayConcat, + substr, + documentId, + isNull, + arrayContainsAll, + constant, + constantVector, + Field, + Constant, + sum, + maximum, + descending, + gte, + bitOr, + bitXor, + bitLeftShift, + bitRightShift, + bitAnd, + multiply, + cond, + Ordering, + AggregateWithAlias, + endsWith, + ExprWithAlias, + mapMerge, + mapRemove, + byteLength, + logicalMaximum, + logicalMinimum, + notEqAny, + countAll, + replaceAll, + replaceFirst, + timestampAdd, + timestampSub, + timestampToUnixMicros, + timestampToUnixSeconds, + unixMicrosToTimestamp, + timestampToUnixMillis, + unixSecondsToTimestamp, + unixMillisToTimestamp, +} from './expression'; + +export {FindNearestOptions} from './stage'; diff --git a/dev/src/pipeline-util.ts b/dev/src/pipelines/pipeline-util.ts similarity index 96% rename from dev/src/pipeline-util.ts rename to dev/src/pipelines/pipeline-util.ts index 136588289..36246aa46 100644 --- a/dev/src/pipeline-util.ts +++ b/dev/src/pipelines/pipeline-util.ts @@ -1,4 +1,4 @@ -// Copyright 2024 Google LLC +// Copyright 2025 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. @@ -15,9 +15,34 @@ import type * as firestore from '@google-cloud/firestore'; import {GoogleError} from 'google-gax'; import {Duplex, Transform} from 'stream'; -import {google} from '../protos/firestore_v1_proto_api'; +import {google} from '../../protos/firestore_v1_proto_api'; + +import * as protos from '../../protos/firestore_v1_proto_api'; +import './expression'; +import Firestore, {DocumentReference, Timestamp, VectorValue} from '../index'; +import {logger} from '../logger'; +import {QualifiedResourcePath} from '../path'; +import {CompositeFilterInternal} from '../reference/composite-filter-internal'; +import {NOOP_MESSAGE} from '../reference/constants'; +import {FieldFilterInternal} from '../reference/field-filter-internal'; +import {FilterInternal} from '../reference/filter-internal'; +import { + PipelineResponse, + PipelineStreamElement, + QueryCursor, +} from '../reference/types'; +import {Serializer} from '../serializer'; +import { + Deferred, + getTotalTimeout, + isObject, + isPermanentRpcError, + isPlainObject, + requestTag, + wrapError, +} from '../util'; +import api = protos.google.firestore.v1; -import * as protos from '../protos/firestore_v1_proto_api'; import { Expr, BooleanExpr, @@ -34,30 +59,7 @@ import { gt, lt, } from './expression'; -import Firestore, {DocumentReference, Timestamp, VectorValue} from './index'; -import {logger} from './logger'; -import {QualifiedResourcePath} from './path'; -import {Pipeline, PipelineResult} from './pipeline'; -import {CompositeFilterInternal} from './reference/composite-filter-internal'; -import {NOOP_MESSAGE} from './reference/constants'; -import {FieldFilterInternal} from './reference/field-filter-internal'; -import {FilterInternal} from './reference/filter-internal'; -import { - PipelineResponse, - PipelineStreamElement, - QueryCursor, -} from './reference/types'; -import {Serializer} from './serializer'; -import { - Deferred, - getTotalTimeout, - isObject, - isPermanentRpcError, - isPlainObject, - requestTag, - wrapError, -} from './util'; -import api = protos.google.firestore.v1; +import {Pipeline, PipelineResult} from './pipelines'; /** * Returns a builder for DocumentSnapshot and QueryDocumentSnapshot instances. @@ -567,7 +569,7 @@ export function valueToDefaultExpr(value: unknown): Expr { * @param value */ export function vectorToExpr( - value: firestore.VectorValue | number[] | firestore.Expr + value: firestore.VectorValue | number[] | Expr ): Expr { if (value instanceof Expr) { return value; diff --git a/dev/src/pipeline.ts b/dev/src/pipelines/pipelines.ts similarity index 93% rename from dev/src/pipeline.ts rename to dev/src/pipelines/pipelines.ts index 58c5aad6f..1d24d8743 100644 --- a/dev/src/pipeline.ts +++ b/dev/src/pipelines/pipelines.ts @@ -1,4 +1,4 @@ -// Copyright 2024 Google LLC +// Copyright 2025 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. @@ -14,7 +14,24 @@ import * as firestore from '@google-cloud/firestore'; import * as deepEqual from 'fast-deep-equal'; -import {google} from '../protos/firestore_v1_proto_api'; +import {google} from '../../protos/firestore_v1_proto_api'; +import Firestore, { + CollectionReference, + FieldPath, + Query, + Timestamp, +} from '../index'; +import {validateFieldPath} from '../path'; +import {ExecutionUtil, fieldOrExpression} from './pipeline-util'; +import {DocumentReference} from '../reference/document-reference'; +import {PipelineResponse} from '../reference/types'; +import {HasUserData, hasUserData, Serializer} from '../serializer'; +import {ApiMapValue} from '../types'; +import * as protos from '../../protos/firestore_v1_proto_api'; +import api = protos.google.firestore.v1; +import IStage = google.firestore.v1.Pipeline.IStage; +import {cast, isOptionalEqual, isPlainObject} from '../util'; + import { AggregateFunction, AggregateWithAlias, @@ -27,17 +44,6 @@ import { _mapValue, field, } from './expression'; -import Firestore, { - CollectionReference, - FieldPath, - Query, - Timestamp, -} from './index'; -import {validateFieldPath} from './path'; -import {ExecutionUtil, fieldOrExpression} from './pipeline-util'; -import {DocumentReference} from './reference/document-reference'; -import {PipelineResponse} from './reference/types'; -import {HasUserData, hasUserData, Serializer} from './serializer'; import { AddFields, Aggregate, @@ -60,17 +66,11 @@ import { Union, Unnest, } from './stage'; -import {ApiMapValue} from './types'; -import * as protos from '../protos/firestore_v1_proto_api'; -import api = protos.google.firestore.v1; -import IStage = google.firestore.v1.Pipeline.IStage; -import {cast, isOptionalEqual, isPlainObject} from './util'; /** * Represents the source of a Firestore {@link Pipeline}. - * @beta */ -export class PipelineSource implements firestore.PipelineSource { +export class PipelineSource implements firestore.Pipelines.PipelineSource { constructor(private db: Firestore) {} collection(collection: string | firestore.CollectionReference): Pipeline { @@ -137,8 +137,6 @@ export class PipelineSource implements firestore.PipelineSource { } /** - * @beta - * * The Pipeline class provides a flexible and expressive framework for building complex data * transformation and query pipelines for Firestore. * @@ -178,7 +176,7 @@ export class PipelineSource implements firestore.PipelineSource { * .execute(); * ``` */ -export class Pipeline implements firestore.Pipeline { +export class Pipeline implements firestore.Pipelines.Pipeline { constructor( private db: Firestore, private stages: Stage[] @@ -218,8 +216,8 @@ export class Pipeline implements firestore.Pipeline { * @return A new Pipeline object with this stage appended to the stage list. */ addFields( - field: firestore.Selectable, - ...additionalFields: firestore.Selectable[] + field: firestore.Pipelines.Selectable, + ...additionalFields: firestore.Pipelines.Selectable[] ): Pipeline { return this._addStage( new AddFields( @@ -250,8 +248,8 @@ export class Pipeline implements firestore.Pipeline { * @return A new Pipeline object with this stage appended to the stage list. */ removeFields( - fieldValue: firestore.Field | string, - ...additionalFields: Array + fieldValue: firestore.Pipelines.Field | string, + ...additionalFields: Array ): Pipeline { const fieldExpressions = [fieldValue, ...additionalFields].map(f => typeof f === 'string' ? field(f) : (f as Field) @@ -279,7 +277,7 @@ export class Pipeline implements firestore.Pipeline { *

Example: * * ```typescript - * firestore.pipeline().collection("books") + * db.pipeline().collection("books") * .select( * "firstName", * field("lastName"), @@ -294,8 +292,8 @@ export class Pipeline implements firestore.Pipeline { * @return A new Pipeline object with this stage appended to the stage list. */ select( - selection: firestore.Selectable | string, - ...additionalSelections: Array + selection: firestore.Pipelines.Selectable | string, + ...additionalSelections: Array ): Pipeline { let projections: Map = this.selectablesToMap([ selection, @@ -306,7 +304,7 @@ export class Pipeline implements firestore.Pipeline { } private selectablesToMap( - selectables: (firestore.Selectable | string)[] + selectables: (firestore.Pipelines.Selectable | string)[] ): Map { const result = new Map(); for (const selectable of selectables) { @@ -321,7 +319,7 @@ export class Pipeline implements firestore.Pipeline { const expr = selectable as ExprWithAlias; result.set(expr.alias, expr.expr as unknown as Expr); } else { - throw new Error('unexpected selectable: ' + selectable); + throw new Error('unexpected selectable: ' + JSON.stringify(selectable)); } } return result; @@ -384,7 +382,7 @@ export class Pipeline implements firestore.Pipeline { * @param condition The {@link BooleanExpr} to apply. * @return A new Pipeline object with this stage appended to the stage list. */ - where(condition: firestore.BooleanExpr): Pipeline { + where(condition: firestore.Pipelines.BooleanExpr): Pipeline { const booleanExpr = condition as BooleanExpr; this.validateUserData('where', booleanExpr); return this._addStage(new Where(booleanExpr)); @@ -472,8 +470,8 @@ export class Pipeline implements firestore.Pipeline { * @return A new {@code Pipeline} object with this stage appended to the stage list. */ distinct( - group: string | firestore.Selectable, - ...additionalGroups: Array + group: string | firestore.Pipelines.Selectable, + ...additionalGroups: Array ): Pipeline { return this._addStage( new Distinct( @@ -510,8 +508,8 @@ export class Pipeline implements firestore.Pipeline { * @return A new Pipeline object with this stage appended to the stage list. */ aggregate( - accumulator: firestore.AggregateWithAlias, - ...additionalAccumulators: firestore.AggregateWithAlias[] + accumulator: firestore.Pipelines.AggregateWithAlias, + ...additionalAccumulators: firestore.Pipelines.AggregateWithAlias[] ): Pipeline; /** * Performs optionally grouped aggregation operations on the documents from previous stages. @@ -547,24 +545,24 @@ export class Pipeline implements firestore.Pipeline { * list. */ aggregate(options: { - accumulators: firestore.AggregateWithAlias[]; - groups?: Array; + accumulators: firestore.Pipelines.AggregateWithAlias[]; + groups?: Array; }): Pipeline; aggregate( optionsOrTarget: - | firestore.AggregateWithAlias + | firestore.Pipelines.AggregateWithAlias | { - accumulators: firestore.AggregateWithAlias[]; - groups?: Array; + accumulators: firestore.Pipelines.AggregateWithAlias[]; + groups?: Array; }, - ...rest: firestore.AggregateWithAlias[] + ...rest: firestore.Pipelines.AggregateWithAlias[] ): Pipeline { if ('accumulators' in optionsOrTarget) { return this._addStage( new Aggregate( new Map( optionsOrTarget.accumulators.map( - (target: firestore.AggregateWithAlias) => { + (target: firestore.Pipelines.AggregateWithAlias) => { this.validateUserData( 'aggregate', target as unknown as AggregateWithAlias @@ -600,7 +598,7 @@ export class Pipeline implements firestore.Pipeline { } } - findNearest(options: firestore.FindNearestOptions): Pipeline { + findNearest(options: firestore.Pipelines.FindNearestOptions): Pipeline { return this._addStage(new FindNearest(options)); } @@ -673,8 +671,8 @@ export class Pipeline implements firestore.Pipeline { * @param expr An {@link Expr} that when returned evaluates to a map. * @return A new {@code Pipeline} object with this stage appended to the stage list. */ - replaceWith(expr: firestore.Expr): Pipeline; - replaceWith(value: firestore.Expr | string): Pipeline { + replaceWith(expr: firestore.Pipelines.Expr): Pipeline; + replaceWith(value: firestore.Pipelines.Expr | string): Pipeline { const expr = fieldOrExpression(value); this.validateUserData('replaceWith', expr); return this._addStage(new ReplaceWith(expr, 'full_replace')); @@ -791,7 +789,10 @@ export class Pipeline implements firestore.Pipeline { * @param indexField An optional string value specifying the field path to write the offset (starting at zero) into the array the un-nested element is from * @return A new {@code Pipeline} object with this stage appended to the stage list. */ - unnest(selectable: firestore.Selectable, indexField?: string): Pipeline { + unnest( + selectable: firestore.Pipelines.Selectable, + indexField?: string + ): Pipeline { return this._addStage( new Unnest({ expr: cast(selectable.expr), @@ -827,8 +828,8 @@ export class Pipeline implements firestore.Pipeline { * @return A new {@code Pipeline} object with this stage appended to the stage list. */ sort( - ordering: firestore.Ordering, - ...additionalOrderings: firestore.Ordering[] + ordering: firestore.Pipelines.Ordering, + ...additionalOrderings: firestore.Pipelines.Ordering[] ): Pipeline { // Ordering object const orderings = [ordering, ...additionalOrderings] as Ordering[]; @@ -887,10 +888,10 @@ export class Pipeline implements firestore.Pipeline { *

The returned Promise can be used to track the progress of the pipeline execution * and retrieve the results (or handle any errors) asynchronously. * - *

The pipeline results are returned as a list of {@link PipelineResult} objects. Each {@link - * PipelineResult} typically represents a single key/value map that has passed through all the - * stages of the pipeline, however this might differ depending on the stages involved in the - * pipeline. For example: + *

The pipeline results are returned in a {@link PipelineSnapshot} object, which contains a list of + * {@link PipelineResult} objects. Each {@link PipelineResult} typically represents a single key/value map that + * has passed through all the stages of the pipeline, however this might differ depending on the stages involved + * in the pipeline. For example: * *

    *
  • If there are no stages or only transformation stages, each {@link PipelineResult} @@ -967,6 +968,7 @@ export class PipelineSnapshot { private readonly _pipeline: Pipeline; private readonly _executionTime: Timestamp | undefined; private readonly _results: PipelineResult[]; + constructor( pipeline: Pipeline, results: PipelineResult[], @@ -1008,15 +1010,13 @@ export class PipelineSnapshot { } /** - * @beta - * * A PipelineResult contains data read from a Firestore Pipeline. The data can be extracted with the * {@link #data()} or {@link #get(String)} methods. * *

    If the PipelineResult represents a non-document result, `ref` will return a undefined * value. */ -export class PipelineResult implements firestore.PipelineResult { +export class PipelineResult implements firestore.Pipelines.PipelineResult { private readonly _ref: DocumentReference | undefined; private _serializer: Serializer; public readonly _executionTime: Timestamp | undefined; diff --git a/dev/src/stage.ts b/dev/src/pipelines/stage.ts similarity index 95% rename from dev/src/stage.ts rename to dev/src/pipelines/stage.ts index 1b8c41432..26f6fb2e9 100644 --- a/dev/src/stage.ts +++ b/dev/src/pipelines/stage.ts @@ -1,4 +1,4 @@ -// Copyright 2024 Google LLC +// Copyright 2025 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. @@ -13,9 +13,13 @@ // limitations under the License. import * as firestore from '@google-cloud/firestore'; -import * as protos from '../protos/firestore_v1_proto_api'; +import * as protos from '../../protos/firestore_v1_proto_api'; import api = protos.google.firestore.v1; +import {VectorValue} from '../field-value'; +import {DocumentReference} from '../reference/document-reference'; +import {ProtoSerializable, Serializer} from '../serializer'; + import { AggregateFunction, Expr, @@ -24,21 +28,19 @@ import { field, BooleanExpr, } from './expression'; -import {VectorValue} from './field-value'; -import {DocumentReference} from './reference/document-reference'; -import {ProtoSerializable, Serializer} from './serializer'; -import {Pipeline} from './pipeline'; +import {Pipeline} from './pipelines'; /** - * @beta + * */ export interface Stage extends ProtoSerializable { name: string; + _toProto(serializer: Serializer): api.Pipeline.IStage; } /** - * @beta + * */ export class AddFields implements Stage { name = 'add_fields'; @@ -54,7 +56,7 @@ export class AddFields implements Stage { } /** - * @beta + * */ export class RemoveFields implements Stage { name = 'remove_fields'; @@ -70,7 +72,6 @@ export class RemoveFields implements Stage { } /** - * @beta */ export class Aggregate implements Stage { name = 'aggregate'; @@ -206,7 +207,7 @@ export class Where implements Stage { * @beta */ export interface FindNearestOptions { - field: firestore.Field | string; + field: firestore.Pipelines.Field | string; vectorValue: firestore.VectorValue | number[]; distanceMeasure: 'euclidean' | 'cosine' | 'dot_product'; limit?: number; diff --git a/dev/src/reference/aggregate-query.ts b/dev/src/reference/aggregate-query.ts index d804c38ae..e075dcc2f 100644 --- a/dev/src/reference/aggregate-query.ts +++ b/dev/src/reference/aggregate-query.ts @@ -22,8 +22,8 @@ import * as deepEqual from 'fast-deep-equal'; import * as firestore from '@google-cloud/firestore'; import {Aggregate, AggregateSpec} from '../aggregate'; -import {avg, count, countAll, field, sum} from '../expression'; -import {Pipeline} from '../pipeline'; +import {avg, count, countAll, field, sum} from '../pipelines'; +import {Pipeline} from '../pipelines'; import {Timestamp} from '../timestamp'; import {mapToArray, requestTag, wrapError} from '../util'; import {ExplainMetrics, ExplainResults} from '../query-profile'; @@ -349,6 +349,10 @@ export class AggregateQuery< return runQueryRequest; } + /** + * @private + * @internal + */ _pipeline(): Pipeline { const aggregates = mapToArray( this._aggregates, diff --git a/dev/src/reference/query.ts b/dev/src/reference/query.ts index 99c6609c0..849a99ad5 100644 --- a/dev/src/reference/query.ts +++ b/dev/src/reference/query.ts @@ -19,7 +19,7 @@ import api = protos.google.firestore.v1; import * as firestore from '@google-cloud/firestore'; import {GoogleError} from 'google-gax'; import {Transform} from 'stream'; -import {and, field, Ordering} from '../expression'; +import {and, field, Ordering} from '../pipelines'; import {CompositeFilter, UnaryFilter} from '../filter'; import { @@ -34,12 +34,12 @@ import { } from '../index'; import {compare} from '../order'; import {validateFieldPath} from '../path'; -import {Pipeline} from '../pipeline'; +import {Pipeline} from '../pipelines'; import { reverseOrderings, toPipelineBooleanExpr, whereConditionsFromCursor, -} from '../pipeline-util'; +} from '../pipelines/pipeline-util'; import {ExplainResults} from '../query-profile'; import {Serializer} from '../serializer'; import {defaultConverter} from '../types'; @@ -735,6 +735,10 @@ export class Query< return this._queryOptions.allDescendants; } + /** + * @private + * @internal + */ _pipeline(): Pipeline { let pipeline: Pipeline; const db = this.firestore; diff --git a/dev/src/reference/types.ts b/dev/src/reference/types.ts index 081616b74..9d56a3890 100644 --- a/dev/src/reference/types.ts +++ b/dev/src/reference/types.ts @@ -15,7 +15,7 @@ */ import * as protos from '../../protos/firestore_v1_proto_api'; -import {PipelineResult} from '../pipeline'; +import {PipelineResult} from '../pipelines'; import api = protos.google.firestore.v1; import {Timestamp} from '../timestamp'; diff --git a/dev/src/reference/vector-query.ts b/dev/src/reference/vector-query.ts index 3536547fc..3f06a88ee 100644 --- a/dev/src/reference/vector-query.ts +++ b/dev/src/reference/vector-query.ts @@ -17,9 +17,9 @@ import * as protos from '../../protos/firestore_v1_proto_api'; import api = protos.google.firestore.v1; import * as firestore from '@google-cloud/firestore'; -import {field} from '../expression'; -import {Pipeline} from '../pipeline'; -import {FindNearestOptions} from '../stage'; +import {field} from '../pipelines'; +import {Pipeline} from '../pipelines'; +import {FindNearestOptions} from '../pipelines'; import {Timestamp} from '../timestamp'; import {VectorValue} from '../field-value'; diff --git a/dev/src/serializer.ts b/dev/src/serializer.ts index 048030d0c..01d0a79d3 100644 --- a/dev/src/serializer.ts +++ b/dev/src/serializer.ts @@ -27,7 +27,7 @@ import {Timestamp} from './timestamp'; import {ApiMapValue, ValidationOptions} from './types'; import {isEmpty, isObject, isPlainObject} from './util'; import {customObjectMessage, invalidArgumentMessage} from './validate'; -import {Pipeline} from './pipeline'; +import {Pipeline} from './pipelines'; import api = proto.google.firestore.v1; import { diff --git a/dev/src/transaction.ts b/dev/src/transaction.ts index abcdc1060..3d754d8bf 100644 --- a/dev/src/transaction.ts +++ b/dev/src/transaction.ts @@ -22,7 +22,7 @@ import * as proto from '../protos/firestore_v1_proto_api'; import {ExponentialBackoff} from './backoff'; import {DocumentSnapshot} from './document'; import {DEFAULT_MAX_TRANSACTION_ATTEMPTS, Firestore, WriteBatch} from './index'; -import {Pipeline, PipelineResult, PipelineSnapshot} from './pipeline'; +import {Pipeline, PipelineResult, PipelineSnapshot} from './pipelines'; import {Timestamp} from './timestamp'; import {logger} from './logger'; import {FieldPath, validateFieldPath} from './path'; @@ -288,17 +288,15 @@ export class Transaction implements firestore.Transaction { } /** - * @beta - * * Executes this pipeline and returns a Promise to represent the asynchronous operation. * *

    The returned Promise can be used to track the progress of the pipeline execution * and retrieve the results (or handle any errors) asynchronously. * - *

    The pipeline results are returned as a list of {@link PipelineResult} objects. Each {@link - * PipelineResult} typically represents a single key/value map that has passed through all the - * stages of the pipeline, however this might differ depending on the stages involved in the - * pipeline. For example: + *

    The pipeline results are returned in a {@link PipelineSnapshot} object, which contains a list of + * {@link PipelineResult} objects. Each {@link PipelineResult} typically represents a single key/value map that + * has passed through all the stages of the pipeline, however this might differ depending on the stages involved + * in the pipeline. For example: * *

      *
    • If there are no stages or only transformation stages, each {@link PipelineResult} @@ -321,7 +319,7 @@ export class Transaction implements firestore.Transaction { * * @return A Promise representing the asynchronous pipeline execution. */ - execute(pipeline: firestore.Pipeline): Promise { + execute(pipeline: Pipeline): Promise { if (this._writeBatch && !this._writeBatch.isEmpty) { throw new Error(READ_AFTER_WRITE_ERROR_MSG); } diff --git a/dev/system-test/pipeline.ts b/dev/system-test/pipeline.ts index 4887fb259..1983e74ec 100644 --- a/dev/system-test/pipeline.ts +++ b/dev/system-test/pipeline.ts @@ -15,16 +15,10 @@ import {DocumentData} from '@google-cloud/firestore'; import { - Filter, - Pipeline, BooleanExpr, - constant, constantVector, map, - GeoPoint, - FieldValue, array, - Timestamp, bitNot, field, xor, @@ -40,7 +34,6 @@ import { byteLength, bitAnd, multiply, - PipelineSnapshot, sum, maximum, descending, @@ -70,7 +63,6 @@ import { documentId, isNull, arrayContainsAll, - FindNearestOptions, replaceFirst, replaceAll, mapRemove, @@ -107,11 +99,22 @@ import { mapGet, lte, eqAny, - PipelineResult, notEqAny, logicalMinimum, logicalMaximum, cond, + constant, + PipelineResult, + PipelineSnapshot, + Pipeline, + FindNearestOptions, +} from '../src/pipelines'; + +import { + Timestamp, + GeoPoint, + Filter, + FieldValue, CollectionReference, FieldPath, Firestore, @@ -129,7 +132,7 @@ import {Firestore as InternalFirestore} from '../src'; use(chaiAsPromised); const testUnsupportedFeatures: boolean | 'only' = false; -const timestampDeltaMS = 1000; +const timestampDeltaMS = 3000; describe.only('Pipeline class', () => { let firestore: Firestore; @@ -1853,8 +1856,8 @@ describe.only('Pipeline class', () => { subtract(field('published'), 1900).as('yearsSince1900'), field('rating').multiply(10).as('ratingTimesTen'), divide('rating', 2).as('ratingDividedByTwo'), - multiply('rating', 10, 2).as('ratingTimes20'), - add('rating', 1, 2).as('ratingPlus3'), + multiply('rating', 20).as('ratingTimes20'), + add('rating', 3).as('ratingPlus3'), mod('rating', 2).as('ratingMod2') ) .limit(1) diff --git a/package.json b/package.json index 301fc1156..d080af86e 100644 --- a/package.json +++ b/package.json @@ -14,7 +14,8 @@ "build/protos", "build/src", "!build/src/**/*.map", - "types" + "types", + "pipelines" ], "keywords": [ "google apis client", @@ -111,5 +112,16 @@ "through2": "^4.0.0", "ts-node": "^10.0.0", "typescript": "^5.2.2" + }, + "exports": { + ".": { + "types": "./types/firestore.d.ts", + "default": "./build/src/index.js" + }, + "./pipelines": { + "types": "./types/pipelines.d.ts", + "default": "./build/src/pipelines/index.js" + }, + "./package.json": "./package.json" } } diff --git a/pipelines/package.json b/pipelines/package.json new file mode 100644 index 000000000..1515c5eb2 --- /dev/null +++ b/pipelines/package.json @@ -0,0 +1,10 @@ +{ + "name": "@google-cloud/firestore/pipelines", + "description": "pipelines", + "main": "../build/src/pipelines/index.js", + "typings": "../types/pipelines.d.ts", + "private": true, + "engines": { + "node": ">=14.0.0" + } +} diff --git a/samples/pipelines-quickstart.js b/samples/pipelines-quickstart.js new file mode 100644 index 000000000..174a19a0c --- /dev/null +++ b/samples/pipelines-quickstart.js @@ -0,0 +1,56 @@ +// Copyright 2025 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. + +'use strict'; + +// [START firestore_pipelines_quickstart] +const {Firestore} = require('@google-cloud/firestore'); +const {field} = require('@google-cloud/firestore/pipelines'); + +// Create a new client +const firestore = new Firestore(); + +async function quickstartPipelines() { + // Obtain a collection reference. + const collection = firestore.collection('posts'); + + // Create a few new posts + for (let i = 0; i < 5; i++) { + await collection.add({ + title: `Post ${i}`, + rating: Math.random() * 10, // random rating on a 10 point scale + }); + } + console.log('Entered new data into the collection'); + + // Create a Pipeline that queries the 'posts' collection. + // Select the fields 'rating' and 'title', and convert the title to uppercase. + // Filter the results to only include posts with rating > 5. + const myPipeline = firestore + .pipeline() + .collection('posts') + .select('rating', field('title').toUpper().as('lowercaseTitle')) + .where(field('rating').gt(5)); + + // Execute the Pipeline against the Firestore server. + const pipelineSnapshot = await myPipeline.execute(); + + // Iterate over each result in the PipelineSnapshot, printing the + // post to the console. + pipelineSnapshot.results.forEach(pipelineResult => { + console.log(pipelineResult.data()); + }); +} +quickstartPipelines(); +// [END firestore_pipelines_quickstart] diff --git a/types/firestore.d.ts b/types/firestore.d.ts index 74162a873..53133967d 100644 --- a/types/firestore.d.ts +++ b/types/firestore.d.ts @@ -569,8 +569,6 @@ declare namespace FirebaseFirestore { */ collectionGroup(collectionId: string): CollectionGroup; - pipeline(): PipelineSource; - /** * Retrieves multiple documents from Firestore. * @@ -726,6 +724,11 @@ declare namespace FirebaseFirestore { * // Save `bundleBuffer` to CDN or stream it to clients. */ bundle(bundleId?: string): BundleBuilder; + + /** + * TODO(pipelines) + */ + pipeline(): Pipelines.PipelineSource; } /** @@ -828,42 +831,6 @@ declare namespace FirebaseFirestore { > ): Promise>>; - /** - * @beta - * - * Executes this pipeline and returns a Promise to represent the asynchronous operation. - * - *

      The returned Promise can be used to track the progress of the pipeline execution - * and retrieve the results (or handle any errors) asynchronously. - * - *

      The pipeline results are returned as a list of {@link PipelineResult} objects. Each {@link - * PipelineResult} typically represents a single key/value map that has passed through all the - * stages of the pipeline, however this might differ depending on the stages involved in the - * pipeline. For example: - * - *

        - *
      • If there are no stages or only transformation stages, each {@link PipelineResult} - * represents a single document.
      • - *
      • If there is an aggregation, only a single {@link PipelineResult} is returned, - * representing the aggregated results over the entire dataset .
      • - *
      • If there is an aggregation stage with grouping, each {@link PipelineResult} represents a - * distinct group and its associated aggregated values.
      • - *
      - * - *

      Example: - * - * ```typescript - * const futureResults = await transaction - * .execute( - * firestore.pipeline().collection("books") - * .where(gt(Field.of("rating"), 4.5)) - * .select("title", "author", "rating")); - * ``` - * - * @return A Promise representing the asynchronous pipeline execution. - */ - execute(pipeline: Pipeline): Promise; - /** * Create the document referred to by the provided `DocumentReference`. * The operation will fail the transaction if a document exists at the @@ -967,6 +934,40 @@ declare namespace FirebaseFirestore { documentRef: DocumentReference, precondition?: Precondition ): Transaction; + + /** + * Executes this pipeline and returns a Promise to represent the asynchronous operation. + * + * The returned Promise can be used to track the progress of the pipeline execution + * and retrieve the results (or handle any errors) asynchronously. + * + *

      The pipeline results are returned in a {@link PipelineSnapshot} object, which contains a list of + * {@link PipelineResult} objects. Each {@link PipelineResult} typically represents a single key/value map that + * has passed through all the stages of the pipeline, however this might differ depending on the stages involved + * in the pipeline. For example: + * + *

        + *
      • If there are no stages or only transformation stages, each {@link PipelineResult} + * represents a single document.
      • + *
      • If there is an aggregation, only a single {@link PipelineResult} is returned, + * representing the aggregated results over the entire dataset .
      • + *
      • If there is an aggregation stage with grouping, each {@link PipelineResult} represents a + * distinct group and its associated aggregated values.
      • + *
      + * + *

      Example: + * + * ```typescript + * const futureResults = await transaction + * .execute( + * firestore.pipeline().collection("books") + * .where(gt(Field.of("rating"), 4.5)) + * .select("title", "author", "rating")); + * ``` + * + * @return A Promise representing the asynchronous pipeline execution. + */ + execute(pipeline: Pipelines.Pipeline): Promise; } /** @@ -3319,6519 +3320,6572 @@ declare namespace FirebaseFirestore { } /** - * @beta - * - * An enumeration of the different types of expressions. + * Specifies the behavior of the {@link VectorQuery} generated by a call to {@link Query.findNearest}. */ - export type ExprType = - | 'Field' - | 'Constant' - | 'Function' - | 'AggregateFunction' - | 'ListOfExprs' - | 'ExprWithAlias'; + export interface VectorQueryOptions { + /** + * A string or {@link FieldPath} specifying the vector field to search on. + */ + vectorField: string | FieldPath; - /** - * @beta - * - * Represents an expression that can be evaluated to a value within the execution of a {@link - * 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 `Expr` class provides a fluent API for building expressions. You can chain together - * method calls to create complex expressions. - */ - export abstract class Expr { - abstract readonly exprType: ExprType; + /** + * The {@link VectorValue} used to measure the distance from `vectorField` values in the documents. + */ + queryVector: VectorValue | Array; /** - * Creates an expression that adds this expression to another expression. - * - * ```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. - * @return A new `Expr` representing the addition operation. + * Specifies the upper bound of documents to return, must be a positive integer with a maximum value of 1000. */ - add(second: Expr | unknown, ...others: Array): FunctionExpr; + limit: number; /** - * Creates an expression that subtracts another expression from this expression. - * - * ```typescript - * // Subtract the 'discount' field from the 'price' field - * field("price").subtract(field("discount")); - * ``` - * - * @param other The expression to subtract from this expression. - * @return A new `Expr` representing the subtraction operation. + * Specifies what type of distance is calculated when performing the query. */ - subtract(other: Expr): FunctionExpr; + distanceMeasure: 'EUCLIDEAN' | 'COSINE' | 'DOT_PRODUCT'; /** - * Creates an expression that subtracts a constant value from this expression. - * - * ```typescript - * // Subtract 20 from the value of the 'total' field - * field("total").subtract(20); - * ``` - * - * @param other The constant value to subtract. - * @return A new `Expr` representing the subtraction operation. + * Optionally specifies the name of a field that will be set on each returned DocumentSnapshot, + * which will contain the computed distance for the document. */ - subtract(other: number): FunctionExpr; + distanceResultField?: string | FieldPath; /** - * Creates an expression that multiplies this expression by another expression. - * - * ```typescript - * // Multiply the 'quantity' field by the 'price' field - * field("quantity").multiply(field("price")); - * ``` + * Specifies a threshold for which no less similar documents will be returned. The behavior + * of the specified `distanceMeasure` will affect the meaning of the distance threshold. * - * @param second The second expression or literal to multiply by. - * @param others Optional additional expressions or literals to multiply by. - * @return A new `Expr` representing the multiplication operation. + * - For `distanceMeasure: "EUCLIDEAN"`, the meaning of `distanceThreshold` is: + * SELECT docs WHERE euclidean_distance <= distanceThreshold + * - For `distanceMeasure: "COSINE"`, the meaning of `distanceThreshold` is: + * SELECT docs WHERE cosine_distance <= distanceThreshold + * - For `distanceMeasure: "DOT_PRODUCT"`, the meaning of `distanceThreshold` is: + * SELECT docs WHERE dot_product_distance >= distanceThreshold */ - multiply( - second: Expr | number, - ...others: Array - ): FunctionExpr; + distanceThreshold?: number; + } + export namespace Pipelines { /** - * Creates an expression that divides this expression by another expression. - * - * ```typescript - * // Divide the 'total' field by the 'count' field - * field("total").divide(field("count")); - * ``` + * @beta * - * @param other The expression to divide by. - * @return A new `Expr` representing the division operation. + * An enumeration of the different types of expressions. */ - divide(other: Expr): FunctionExpr; + export type ExprType = + | 'Field' + | 'Constant' + | 'Function' + | 'AggregateFunction' + | 'ListOfExprs' + | 'ExprWithAlias'; /** - * Creates an expression that divides this expression by a constant value. + * @beta * - * ```typescript - * // Divide the 'value' field by 10 - * field("value").divide(10); - * ``` + * Represents an expression that can be evaluated to a value within the execution of a {@link + * 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 `Expr` class provides a fluent API for building expressions. You can chain together + * method calls to create complex expressions. + */ + export abstract class Expr { + abstract readonly exprType: ExprType; + + /** + * Creates an expression that adds this expression to another expression. + * + * ```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. + * @return A new `Expr` representing the addition operation. + */ + add( + second: Expr | unknown, + ...others: Array + ): FunctionExpr; + + /** + * Creates an expression that subtracts another expression from this expression. + * + * ```typescript + * // Subtract the 'discount' field from the 'price' field + * field("price").subtract(field("discount")); + * ``` + * + * @param other The expression to subtract from this expression. + * @return A new `Expr` representing the subtraction operation. + */ + subtract(other: Expr): FunctionExpr; + + /** + * Creates an expression that subtracts a constant value from this expression. + * + * ```typescript + * // Subtract 20 from the value of the 'total' field + * field("total").subtract(20); + * ``` + * + * @param other The constant value to subtract. + * @return A new `Expr` representing the subtraction operation. + */ + subtract(other: number): FunctionExpr; + + /** + * Creates an expression that multiplies this expression by another expression. + * + * ```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. + * @return A new `Expr` representing the multiplication operation. + */ + multiply( + second: Expr | number, + ...others: Array + ): FunctionExpr; + + /** + * Creates an expression that divides this expression by another expression. + * + * ```typescript + * // Divide the 'total' field by the 'count' field + * field("total").divide(field("count")); + * ``` + * + * @param other The expression to divide by. + * @return A new `Expr` representing the division operation. + */ + divide(other: Expr): FunctionExpr; + + /** + * Creates an expression that divides this expression by a constant value. + * + * ```typescript + * // Divide the 'value' field by 10 + * field("value").divide(10); + * ``` + * + * @param other The constant value to divide by. + * @return A new `Expr` representing the division operation. + */ + divide(other: number): FunctionExpr; + divide(other: number | Expr): FunctionExpr; + + /** + * Creates an expression that calculates the modulo (remainder) of dividing this expression by another expression. + * + * ```typescript + * // Calculate the remainder of dividing the 'value' field by the 'divisor' field + * field("value").mod(field("divisor")); + * ``` + * + * @param expression The expression to divide by. + * @return A new `Expr` representing the modulo operation. + */ + mod(expression: Expr): FunctionExpr; + + /** + * Creates an expression that calculates the modulo (remainder) of dividing this expression by a constant value. + * + * ```typescript + * // Calculate the remainder of dividing the 'value' field by 10 + * field("value").mod(10); + * ``` + * + * @param value The constant value to divide by. + * @return A new `Expr` representing the modulo operation. + */ + mod(value: number): FunctionExpr; + + /** + * Creates an expression that checks if this expression is equal to another expression. + * + * ```typescript + * // Check if the 'age' field is equal to 21 + * field("age").eq(21); + * ``` + * + * @param expression The expression to compare for equality. + * @return A new `Expr` representing the equality comparison. + */ + eq(expression: Expr): BooleanExpr; + + /** + * Creates an expression that checks if this expression is equal to a constant value. + * + * ```typescript + * // Check if the 'city' field is equal to "London" + * field("city").eq("London"); + * ``` + * + * @param value The constant value to compare for equality. + * @return A new `Expr` representing the equality comparison. + */ + eq(value: unknown): BooleanExpr; + + /** + * Creates an expression that checks if this expression is not equal to another expression. + * + * ```typescript + * // Check if the 'status' field is not equal to "completed" + * field("status").neq("completed"); + * ``` + * + * @param expression The expression to compare for inequality. + * @return A new `Expr` representing the inequality comparison. + */ + neq(expression: Expr): BooleanExpr; + + /** + * Creates an expression that checks if this expression is not equal to a constant value. + * + * ```typescript + * // Check if the 'country' field is not equal to "USA" + * field("country").neq("USA"); + * ``` + * + * @param value The constant value to compare for inequality. + * @return A new `Expr` representing the inequality comparison. + */ + neq(value: unknown): BooleanExpr; + + /** + * Creates an expression that checks if this expression is less than another expression. + * + * ```typescript + * // Check if the 'age' field is less than 'limit' + * field("age").lt(field('limit')); + * ``` + * + * @param experession The expression to compare for less than. + * @return A new `Expr` representing the less than comparison. + */ + lt(experession: Expr): BooleanExpr; + + /** + * Creates an expression that checks if this expression is less than a constant value. + * + * ```typescript + * // Check if the 'price' field is less than 50 + * field("price").lt(50); + * ``` + * + * @param value The constant value to compare for less than. + * @return A new `Expr` representing the less than comparison. + */ + lt(value: unknown): BooleanExpr; + + /** + * Creates an expression that checks if this expression is less than or equal to another + * expression. + * + * ```typescript + * // Check if the 'quantity' field is less than or equal to 20 + * field("quantity").lte(constant(20)); + * ``` + * + * @param expression The expression to compare for less than or equal to. + * @return A new `Expr` representing the less than or equal to comparison. + */ + lte(expression: Expr): BooleanExpr; + + /** + * Creates an expression that checks if this expression is less than or equal to a constant value. + * + * ```typescript + * // Check if the 'score' field is less than or equal to 70 + * field("score").lte(70); + * ``` + * + * @param value The constant value to compare for less than or equal to. + * @return A new `Expr` representing the less than or equal to comparison. + */ + lte(value: unknown): BooleanExpr; + + /** + * Creates an expression that checks if this expression is greater than another expression. + * + * ```typescript + * // Check if the 'age' field is greater than the 'limit' field + * field("age").gt(field("limit")); + * ``` + * + * @param expression The expression to compare for greater than. + * @return A new `Expr` representing the greater than comparison. + */ + gt(expression: Expr): BooleanExpr; + + /** + * Creates an expression that checks if this expression is greater than a constant value. + * + * ```typescript + * // Check if the 'price' field is greater than 100 + * field("price").gt(100); + * ``` + * + * @param value The constant value to compare for greater than. + * @return A new `Expr` representing the greater than comparison. + */ + gt(value: unknown): BooleanExpr; + + /** + * Creates an expression that checks if this expression is greater than or equal to another + * expression. + * + * ```typescript + * // Check if the 'quantity' field is greater than or equal to field 'requirement' plus 1 + * field("quantity").gte(field('requirement').add(1)); + * ``` + * + * @param expression The expression to compare for greater than or equal to. + * @return A new `Expr` representing the greater than or equal to comparison. + */ + gte(expression: Expr): BooleanExpr; + + /** + * Creates an expression that checks if this expression is greater than or equal to a constant + * value. + * + * ```typescript + * // Check if the 'score' field is greater than or equal to 80 + * field("score").gte(80); + * ``` + * + * @param value The constant value to compare for greater than or equal to. + * @return A new `Expr` representing the greater than or equal to comparison. + */ + gte(value: unknown): BooleanExpr; + + /** + * Creates an expression that concatenates an array expression with one or more other arrays. + * + * ```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. + * @return A new `Expr` representing the concatenated array. + */ + arrayConcat( + secondArray: Expr | unknown[], + ...otherArrays: Array + ): FunctionExpr; + + /** + * Creates an expression that checks if an array contains a specific element. + * + * ```typescript + * // Check if the 'sizes' array contains the value from the 'selectedSize' field + * field("sizes").arrayContains(field("selectedSize")); + * ``` + * + * @param expression The element to search for in the array. + * @return A new `Expr` representing the 'array_contains' comparison. + */ + arrayContains(expression: Expr): BooleanExpr; + + /** + * Creates an expression that checks if an array contains a specific value. + * + * ```typescript + * // Check if the 'colors' array contains "red" + * field("colors").arrayContains("red"); + * ``` + * + * @param value The element to search for in the array. + * @return A new `Expr` representing the 'array_contains' comparison. + */ + arrayContains(value: unknown): BooleanExpr; + + /** + * Creates an expression that checks if an array contains all the specified elements. + * + * ```typescript + * // Check if the 'tags' array contains both the value in field "tag1" and the literal value "tag2" + * field("tags").arrayContainsAll([field("tag1"), "tag2"]); + * ``` + * + * @param values The elements to check for in the array. + * @return A new `Expr` representing the 'array_contains_all' comparison. + */ + arrayContainsAll(values: Array): BooleanExpr; + + /** + * Creates an expression that checks if an array contains all the specified elements. + * + * ```typescript + * // Check if the 'tags' array contains both of the values from field "tag1" and the literal value "tag2" + * field("tags").arrayContainsAll(array([field("tag1"), "tag2"])); + * ``` + * + * @param arrayExpression The elements to check for in the array. + * @return A new `Expr` representing the 'array_contains_all' comparison. + */ + arrayContainsAll(arrayExpression: Expr): BooleanExpr; + + /** + * Creates an expression that checks if an array contains any of the specified elements. + * + * ```typescript + * // Check if the 'categories' array contains either values from field "cate1" or "cate2" + * field("categories").arrayContainsAny([field("cate1"), field("cate2")]); + * ``` + * + * @param values The elements to check for in the array. + * @return A new `Expr` representing the 'array_contains_any' comparison. + */ + arrayContainsAny(values: Array): BooleanExpr; + + /** + * Creates an expression that checks if an array contains any of the specified elements. + * + * ```typescript + * // Check if the 'groups' array contains either the value from the 'userGroup' field + * // or the value "guest" + * field("groups").arrayContainsAny(array([field("userGroup"), "guest"])); + * ``` + * + * @param arrayExpression The elements to check for in the array. + * @return A new `Expr` representing the 'array_contains_any' comparison. + */ + arrayContainsAny(arrayExpression: Expr): BooleanExpr; + + /** + * Creates an expression that calculates the length of an array. + * + * ```typescript + * // Get the number of items in the 'cart' array + * field("cart").arrayLength(); + * ``` + * + * @return A new `Expr` representing the length of the array. + */ + arrayLength(): FunctionExpr; + + /** + * Creates an expression that checks if this expression is equal to any of the provided values or + * expressions. + * + * ```typescript + * // Check if the 'category' field is either "Electronics" or value of field 'primaryType' + * field("category").eqAny("Electronics", field("primaryType")); + * ``` + * + * @param values The values or expressions to check against. + * @return A new `Expr` representing the 'IN' comparison. + */ + eqAny(values: Array): BooleanExpr; + + /** + * Creates an expression that checks if this expression is equal to any of the provided values or + * expressions. + * + * ```typescript + * // Check if the 'category' field is either "Electronics" or value of field 'primaryType' + * field("category").eqAny(array(["Electronics", field("primaryType")])); + * ``` + * + * @param arrayExpression An expression that evaluates to an array of values to check against. + * @return A new `Expr` representing the 'IN' comparison. + */ + eqAny(arrayExpression: Expr): BooleanExpr; + + /** + * Creates an expression that checks if this expression is not equal to any of the provided values or + * expressions. + * + * ```typescript + * // Check if the 'status' field is neither "pending" nor the value of 'rejectedStatus' + * field("status").notEqAny(["pending", field("rejectedStatus")]); + * ``` + * + * @param values The values or expressions to check against. + * @return A new `Expr` representing the 'NotEqAny' comparison. + */ + notEqAny(values: Array): BooleanExpr; + + /** + * Creates an expression that checks if this expression is not equal to any of the values in the evaluated expression. + * + * ```typescript + * // Check if the 'status' field is not equal to any value in the field 'rejectedStatuses' + * field("status").notEqAny(field('rejectedStatuses')); + * ``` + * + * @param arrayExpression The values or expressions to check against. + * @return A new `Expr` representing the 'NotEqAny' comparison. + */ + notEqAny(arrayExpression: Expr): BooleanExpr; + + /** + * Creates an expression that checks if this expression evaluates to 'NaN' (Not a Number). + * + * ```typescript + * // Check if the result of a calculation is NaN + * field("value").divide(0).isNaN(); + * ``` + * + * @return A new `Expr` representing the 'isNaN' check. + */ + isNan(): BooleanExpr; + + /** + * Creates an expression that checks if this expression evaluates to 'Null'. + * + * ```typescript + * // Check if the result of a calculation is NaN + * field("value").isNull(); + * ``` + * + * @return A new `Expr` representing the 'isNull' check. + */ + isNull(): BooleanExpr; + + /** + * Creates an expression that checks if a field exists in the document. + * + * ```typescript + * // Check if the document has a field named "phoneNumber" + * field("phoneNumber").exists(); + * ``` + * + * @return A new `Expr` representing the 'exists' check. + */ + exists(): BooleanExpr; + + /** + * Creates an expression that calculates the character length of a string in UTF-8. + * + * ```typescript + * // Get the character length of the 'name' field in its UTF-8 form. + * field("name").charLength(); + * ``` + * + * @return A new `Expr` representing the length of the string. + */ + charLength(): FunctionExpr; + + /** + * Creates an expression that performs a case-sensitive string comparison. + * + * ```typescript + * // Check if the 'title' field contains the word "guide" (case-sensitive) + * field("title").like("%guide%"); + * ``` + * + * @param pattern The pattern to search for. You can use "%" as a wildcard character. + * @return A new `Expr` representing the 'like' comparison. + */ + like(pattern: string): FunctionExpr; + + /** + * Creates an expression that performs a case-sensitive string comparison. + * + * ```typescript + * // Check if the 'title' field contains the word "guide" (case-sensitive) + * field("title").like("%guide%"); + * ``` + * + * @param pattern The pattern to search for. You can use "%" as a wildcard character. + * @return A new `Expr` representing the 'like' comparison. + */ + like(pattern: Expr): FunctionExpr; + + /** + * Creates an expression that checks if a string contains a specified regular expression as a + * substring. + * + * ```typescript + * // Check if the 'description' field contains "example" (case-insensitive) + * field("description").regexContains("(?i)example"); + * ``` + * + * @param pattern The regular expression to use for the search. + * @return A new `Expr` representing the 'contains' comparison. + */ + regexContains(pattern: string): BooleanExpr; + + /** + * Creates an expression that checks if a string contains a specified regular expression as a + * substring. + * + * ```typescript + * // Check if the 'description' field contains the regular expression stored in field 'regex' + * field("description").regexContains(field("regex")); + * ``` + * + * @param pattern The regular expression to use for the search. + * @return A new `Expr` representing the 'contains' comparison. + */ + regexContains(pattern: Expr): BooleanExpr; + + /** + * Creates an expression that checks if a string matches a specified regular expression. + * + * ```typescript + * // Check if the 'email' field matches a valid email pattern + * field("email").regexMatch("[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,}"); + * ``` + * + * @param pattern The regular expression to use for the match. + * @return A new `Expr` representing the regular expression match. + */ + regexMatch(pattern: string): BooleanExpr; + + /** + * Creates an expression that checks if a string matches a specified regular expression. + * + * ```typescript + * // Check if the 'email' field matches a regular expression stored in field 'regex' + * field("email").regexMatch(field("regex")); + * ``` + * + * @param pattern The regular expression to use for the match. + * @return A new `Expr` representing the regular expression match. + */ + regexMatch(pattern: Expr): BooleanExpr; + + /** + * Creates an expression that checks if a string contains a specified substring. + * + * ```typescript + * // Check if the 'description' field contains "example". + * field("description").strContains("example"); + * ``` + * + * @param substring The substring to search for. + * @return A new `Expr` representing the 'contains' comparison. + */ + strContains(substring: string): BooleanExpr; + + /** + * Creates an expression that checks if a string contains the string represented by another expression. + * + * ```typescript + * // Check if the 'description' field contains the value of the 'keyword' field. + * field("description").strContains(field("keyword")); + * ``` + * + * @param expr The expression representing the substring to search for. + * @return A new `Expr` representing the 'contains' comparison. + */ + strContains(expr: Expr): BooleanExpr; + + /** + * Creates an expression that checks if a string starts with a given prefix. + * + * ```typescript + * // Check if the 'name' field starts with "Mr." + * field("name").startsWith("Mr."); + * ``` + * + * @param prefix The prefix to check for. + * @return A new `Expr` representing the 'starts with' comparison. + */ + startsWith(prefix: string): BooleanExpr; + + /** + * Creates an expression that checks if a string starts with a given prefix (represented as an + * expression). + * + * ```typescript + * // Check if the 'fullName' field starts with the value of the 'firstName' field + * field("fullName").startsWith(field("firstName")); + * ``` + * + * @param prefix The prefix expression to check for. + * @return A new `Expr` representing the 'starts with' comparison. + */ + startsWith(prefix: Expr): BooleanExpr; + + /** + * Creates an expression that checks if a string ends with a given postfix. + * + * ```typescript + * // Check if the 'filename' field ends with ".txt" + * field("filename").endsWith(".txt"); + * ``` + * + * @param suffix The postfix to check for. + * @return A new `Expr` representing the 'ends with' comparison. + */ + endsWith(suffix: string): BooleanExpr; + + /** + * Creates an expression that checks if a string ends with a given postfix (represented as an + * expression). + * + * ```typescript + * // Check if the 'url' field ends with the value of the 'extension' field + * field("url").endsWith(field("extension")); + * ``` + * + * @param suffix The postfix expression to check for. + * @return A new `Expr` representing the 'ends with' comparison. + */ + endsWith(suffix: Expr): BooleanExpr; + + /** + * Creates an expression that converts a string to lowercase. + * + * ```typescript + * // Convert the 'name' field to lowercase + * field("name").toLower(); + * ``` + * + * @return A new `Expr` representing the lowercase string. + */ + toLower(): FunctionExpr; + + /** + * Creates an expression that converts a string to uppercase. + * + * ```typescript + * // Convert the 'title' field to uppercase + * field("title").toUpper(); + * ``` + * + * @return A new `Expr` representing the uppercase string. + */ + toUpper(): FunctionExpr; + + /** + * Creates an expression that removes leading and trailing whitespace from a string. + * + * ```typescript + * // Trim whitespace from the 'userInput' field + * field("userInput").trim(); + * ``` + * + * @return A new `Expr` representing the trimmed string. + */ + trim(): FunctionExpr; + + /** + * Creates an expression that concatenates string expressions together. + * + * ```typescript + * // Combine the 'firstName', " ", and 'lastName' fields into a single string + * field("firstName").strConcat(constant(" "), field("lastName")); + * ``` + * + * @param secondString The additional expression or string literal to concatenate. + * @param otherStrings Optional additional expressions or string literals to concatenate. + * @return A new `Expr` representing the concatenated string. + */ + strConcat( + secondString: Expr | string, + ...otherStrings: Array + ): FunctionExpr; + + /** + * Creates an expression that reverses this string expression. + * + * ```typescript + * // Reverse the value of the 'myString' field. + * field("myString").reverse(); + * ``` + * + * @return A new {@code Expr} representing the reversed string. + */ + reverse(): FunctionExpr; + + /** + * Creates an expression that replaces the first occurrence of a substring within this string expression with another substring. + * + * ```typescript + * // Replace the first occurrence of "hello" with "hi" in the 'message' field + * field("message").replaceFirst("hello", "hi"); + * ``` + * + * @param find The substring to search for. + * @param replace The substring to replace the first occurrence of 'find' with. + * @return A new {@code Expr} representing the string with the first occurrence replaced. + */ + replaceFirst(find: string, replace: string): FunctionExpr; + + /** + * Creates an expression that replaces the first occurrence of a substring within this string expression with another substring, + * where the substring to find and the replacement substring are specified by expressions. + * + * ```typescript + * // Replace the first occurrence of the value in 'findField' with the value in 'replaceField' in the 'message' field + * field("message").replaceFirst(field("findField"), field("replaceField")); + * ``` + * + * @param find The expression representing the substring to search for. + * @param replace The expression representing the substring to replace the first occurrence of 'find' with. + * @return A new {@code Expr} representing the string with the first occurrence replaced. + */ + replaceFirst(find: Expr, replace: Expr): FunctionExpr; + + /** + * Creates an expression that replaces all occurrences of a substring within this string expression with another substring. + * + * ```typescript + * // Replace all occurrences of "hello" with "hi" in the 'message' field + * field("message").replaceAll("hello", "hi"); + * ``` + * + * @param find The substring to search for. + * @param replace The substring to replace all occurrences of 'find' with. + * @return A new {@code Expr} representing the string with all occurrences replaced. + */ + replaceAll(find: string, replace: string): FunctionExpr; + + /** + * Creates an expression that replaces all occurrences of a substring within this string expression with another substring, + * where the substring to find and the replacement substring are specified by expressions. + * + * ```typescript + * // Replace all occurrences of the value in 'findField' with the value in 'replaceField' in the 'message' field + * field("message").replaceAll(field("findField"), field("replaceField")); + * ``` + * + * @param find The expression representing the substring to search for. + * @param replace The expression representing the substring to replace all occurrences of 'find' with. + * @return A new {@code Expr} representing the string with all occurrences replaced. + */ + replaceAll(find: Expr, replace: Expr): FunctionExpr; + + /** + * Creates an expression that calculates the length of this string expression in bytes. + * + * ```typescript + * // Calculate the length of the 'myString' field in bytes. + * field("myString").byteLength(); + * ``` + * + * @return A new {@code Expr} representing the length of the string in bytes. + */ + byteLength(): FunctionExpr; + + /** + * Accesses a value from a map (object) field using the provided key. + * + * ```typescript + * // Get the 'city' value from the 'address' map field + * field("address").mapGet("city"); + * ``` + * + * @param subfield The key to access in the map. + * @return A new `Expr` representing the value associated with the given key in the map. + */ + mapGet(subfield: string): FunctionExpr; + + /** + * Creates an aggregation that counts the number of stage inputs with valid evaluations of the + * expression or field. + * + * ```typescript + * // Count the total number of products + * field("productId").count().as("totalProducts"); + * ``` + * + * @return A new `AggregateFunction` representing the 'count' aggregation. + */ + count(): AggregateFunction; + + /** + * Creates an aggregation that calculates the sum of a numeric field across multiple stage inputs. + * + * ```typescript + * // Calculate the total revenue from a set of orders + * field("orderAmount").sum().as("totalRevenue"); + * ``` + * + * @return A new `AggregateFunction` representing the 'sum' aggregation. + */ + sum(): AggregateFunction; + + /** + * Creates an aggregation that calculates the average (mean) of a numeric field across multiple + * stage inputs. + * + * ```typescript + * // Calculate the average age of users + * field("age").avg().as("averageAge"); + * ``` + * + * @return A new `AggregateFunction` representing the 'avg' aggregation. + */ + avg(): AggregateFunction; + + /** + * Creates an aggregation that finds the minimum value of a field across multiple stage inputs. + * + * ```typescript + * // Find the lowest price of all products + * field("price").minimum().as("lowestPrice"); + * ``` + * + * @return A new `AggregateFunction` representing the 'min' aggregation. + */ + minimum(): AggregateFunction; + + /** + * Creates an aggregation that finds the maximum value of a field across multiple stage inputs. + * + * ```typescript + * // Find the highest score in a leaderboard + * field("score").maximum().as("highestScore"); + * ``` + * + * @return A new `AggregateFunction` representing the 'max' aggregation. + */ + maximum(): AggregateFunction; + + /** + * Creates an expression that returns the larger value between this expression and another expression, based on Firestore's value type ordering. + * + * ```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. + * @return A new {@code Expr} representing the logical max operation. + */ + logicalMaximum( + second: Expr | unknown, + ...others: Array + ): FunctionExpr; + + /** + * Creates an expression that returns the smaller value between this expression and another expression, based on Firestore's value type ordering. + * + * ```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. + * @return A new {@code Expr} representing the logical min operation. + */ + logicalMinimum( + second: Expr | unknown, + ...others: Array + ): FunctionExpr; + + /** + * Creates an expression that calculates the length (number of dimensions) of this Firestore Vector expression. + * + * ```typescript + * // Get the vector length (dimension) of the field 'embedding'. + * field("embedding").vectorLength(); + * ``` + * + * @return A new {@code Expr} representing the length of the vector. + */ + vectorLength(): FunctionExpr; + + /** + * Calculates the cosine distance between two vectors. + * + * ```typescript + * // Calculate the cosine distance between the 'userVector' field and the 'itemVector' field + * field("userVector").cosineDistance(field("itemVector")); + * ``` + * + * @param vectorExpression The other vector (represented as an Expr) to compare against. + * @return A new `Expr` representing the cosine distance between the two vectors. + */ + cosineDistance(vectorExpression: Expr): FunctionExpr; + /** + * Calculates the Cosine distance between two vectors. + * + * ```typescript + * // Calculate the Cosine distance between the 'location' field and a target location + * field("location").cosineDistance(new VectorValue([37.7749, -122.4194])); + * ``` + * + * @param vector The other vector (as a VectorValue) to compare against. + * @return A new `Expr` representing the Cosine* distance between the two vectors. + */ + cosineDistance(vector: VectorValue | number[]): FunctionExpr; + + /** + * Calculates the dot product between two vectors. + * + * ```typescript + * // Calculate the dot product between a feature vector and a target vector + * field("features").dotProduct([0.5, 0.8, 0.2]); + * ``` + * + * @param vectorExpression The other vector (as an array of numbers) to calculate with. + * @return A new `Expr` representing the dot product between the two vectors. + */ + dotProduct(vectorExpression: Expr): FunctionExpr; + + /** + * Calculates the dot product between two vectors. + * + * ```typescript + * // Calculate the dot product between a feature vector and a target vector + * field("features").dotProduct(new VectorValue([0.5, 0.8, 0.2])); + * ``` + * + * @param vector The other vector (as an array of numbers) to calculate with. + * @return A new `Expr` representing the dot product between the two vectors. + */ + dotProduct(vector: VectorValue | number[]): FunctionExpr; + + /** + * Calculates the Euclidean distance between two vectors. + * + * ```typescript + * // Calculate the Euclidean distance between the 'location' field and a target location + * field("location").euclideanDistance([37.7749, -122.4194]); + * ``` + * + * @param vectorExpression The other vector (as an array of numbers) to calculate with. + * @return A new `Expr` representing the Euclidean distance between the two vectors. + */ + euclideanDistance(vectorExpression: Expr): FunctionExpr; + + /** + * Calculates the Euclidean distance between two vectors. + * + * ```typescript + * // Calculate the Euclidean distance between the 'location' field and a target location + * field("location").euclideanDistance(new VectorValue([37.7749, -122.4194])); + * ``` + * + * @param vector The other vector (as a VectorValue) to compare against. + * @return A new `Expr` representing the Euclidean distance between the two vectors. + */ + euclideanDistance(vector: VectorValue | number[]): FunctionExpr; + + /** + * 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. + * + * ```typescript + * // Interpret the 'microseconds' field as microseconds since epoch. + * field("microseconds").unixMicrosToTimestamp(); + * ``` + * + * @return A new {@code Expr} representing the timestamp. + */ + unixMicrosToTimestamp(): FunctionExpr; + + /** + * Creates an expression that converts this timestamp expression to the number of microseconds since the Unix epoch (1970-01-01 00:00:00 UTC). + * + * ```typescript + * // Convert the 'timestamp' field to microseconds since epoch. + * field("timestamp").timestampToUnixMicros(); + * ``` + * + * @return A new {@code Expr} representing the number of microseconds since epoch. + */ + timestampToUnixMicros(): FunctionExpr; + + /** + * 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. + * + * ```typescript + * // Interpret the 'milliseconds' field as milliseconds since epoch. + * field("milliseconds").unixMillisToTimestamp(); + * ``` + * + * @return A new {@code Expr} representing the timestamp. + */ + unixMillisToTimestamp(): FunctionExpr; + + /** + * Creates an expression that converts this timestamp expression to the number of milliseconds since the Unix epoch (1970-01-01 00:00:00 UTC). + * + * ```typescript + * // Convert the 'timestamp' field to milliseconds since epoch. + * field("timestamp").timestampToUnixMillis(); + * ``` + * + * @return A new {@code Expr} representing the number of milliseconds since epoch. + */ + timestampToUnixMillis(): FunctionExpr; + + /** + * 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. + * + * ```typescript + * // Interpret the 'seconds' field as seconds since epoch. + * field("seconds").unixSecondsToTimestamp(); + * ``` + * + * @return A new {@code Expr} representing the timestamp. + */ + unixSecondsToTimestamp(): FunctionExpr; + + /** + * Creates an expression that converts this timestamp expression to the number of seconds since the Unix epoch (1970-01-01 00:00:00 UTC). + * + * ```typescript + * // Convert the 'timestamp' field to seconds since epoch. + * field("timestamp").timestampToUnixSeconds(); + * ``` + * + * @return A new {@code Expr} representing the number of seconds since epoch. + */ + timestampToUnixSeconds(): FunctionExpr; + + /** + * Creates an expression that adds a specified amount of time to this timestamp expression. + * + * ```typescript + * // Add some duration determined by field 'unit' and 'amount' to the 'timestamp' field. + * field("timestamp").timestampAdd(field("unit"), field("amount")); + * ``` + * + * @param unit The expression evaluates to unit of time, must be one of 'microsecond', 'millisecond', 'second', 'minute', 'hour', 'day'. + * @param amount The expression evaluates to amount of the unit. + * @return A new {@code Expr} representing the resulting timestamp. + */ + timestampAdd(unit: Expr, amount: Expr): FunctionExpr; + + /** + * Creates an expression that adds a specified amount of time to this timestamp expression. + * + * ```typescript + * // Add 1 day to the 'timestamp' field. + * field("timestamp").timestampAdd("day", 1); + * ``` + * + * @param unit The unit of time to add (e.g., "day", "hour"). + * @param amount The amount of time to add. + * @return A new {@code Expr} representing the resulting timestamp. + */ + timestampAdd( + unit: + | 'microsecond' + | 'millisecond' + | 'second' + | 'minute' + | 'hour' + | 'day', + amount: number + ): FunctionExpr; + + /** + * Creates an expression that subtracts a specified amount of time from this timestamp expression. + * + * ```typescript + * // Subtract some duration determined by field 'unit' and 'amount' from the 'timestamp' field. + * field("timestamp").timestampSub(field("unit"), field("amount")); + * ``` + * + * @param unit The expression evaluates to unit of time, must be one of 'microsecond', 'millisecond', 'second', 'minute', 'hour', 'day'. + * @param amount The expression evaluates to amount of the unit. + * @return A new {@code Expr} representing the resulting timestamp. + */ + timestampSub(unit: Expr, amount: Expr): FunctionExpr; + + /** + * Creates an expression that subtracts a specified amount of time from this timestamp expression. + * + * ```typescript + * // Subtract 1 day from the 'timestamp' field. + * field("timestamp").timestampSub("day", 1); + * ``` + * + * @param unit The unit of time to subtract (e.g., "day", "hour"). + * @param amount The amount of time to subtract. + * @return A new {@code Expr} representing the resulting timestamp. + */ + timestampSub( + unit: + | 'microsecond' + | 'millisecond' + | 'second' + | 'minute' + | 'hour' + | 'day', + amount: number + ): FunctionExpr; + + /** + * @beta + * + * Creates an expression that applies a bitwise AND operation between this expression and a constant. + * + * ```typescript + * // Calculate the bitwise AND of 'field1' and 0xFF. + * field("field1").bitAnd(0xFF); + * ``` + * + * @param otherBits A constant representing bits. + * @return A new {@code Expr} representing the bitwise AND operation. + */ + bitAnd(otherBits: number | Buffer | Uint8Array): FunctionExpr; + /** + * @beta + * + * Creates an expression that applies a bitwise AND operation between two expressions. + * + * ```typescript + * // Calculate the bitwise AND of 'field1' and 'field2'. + * field("field1").bitAnd(field("field2")); + * ``` + * + * @param bitsExpression An expression that returns bits when evaluated. + * @return A new {@code Expr} representing the bitwise AND operation. + */ + bitAnd(bitsExpression: Expr): FunctionExpr; + + /** + * @beta + * + * Creates an expression that applies a bitwise OR operation between this expression and a constant. + * + * ```typescript + * // Calculate the bitwise OR of 'field1' and 0xFF. + * field("field1").bitOr(0xFF); + * ``` + * + * @param otherBits A constant representing bits. + * @return A new {@code Expr} representing the bitwise OR operation. + */ + bitOr(otherBits: number | Buffer | Uint8Array): FunctionExpr; + /** + * @beta + * + * Creates an expression that applies a bitwise OR operation between two expressions. + * + * ```typescript + * // Calculate the bitwise OR of 'field1' and 'field2'. + * field("field1").bitOr(field("field2")); + * ``` + * + * @param bitsExpression An expression that returns bits when evaluated. + * @return A new {@code Expr} representing the bitwise OR operation. + */ + bitOr(bitsExpression: Expr): FunctionExpr; + + /** + * @beta + * + * Creates an expression that applies a bitwise XOR operation between this expression and a constant. + * + * ```typescript + * // Calculate the bitwise XOR of 'field1' and 0xFF. + * field("field1").bitXor(0xFF); + * ``` + * + * @param otherBits A constant representing bits. + * @return A new {@code Expr} representing the bitwise XOR operation. + */ + bitXor(otherBits: number | Buffer | Uint8Array): FunctionExpr; + /** + * @beta + * + * Creates an expression that applies a bitwise XOR operation between two expressions. + * + * ```typescript + * // Calculate the bitwise XOR of 'field1' and 'field2'. + * field("field1").bitXor(field("field2")); + * ``` + * + * @param bitsExpression An expression that returns bits when evaluated. + * @return A new {@code Expr} representing the bitwise XOR operation. + */ + bitXor(bitsExpression: Expr): FunctionExpr; + + /** + * @beta + * + * Creates an expression that applies a bitwise NOT operation to this expression. + * + * ```typescript + * // Calculate the bitwise NOT of 'field1'. + * field("field1").bitNot(); + * ``` + * + * @return A new {@code Expr} representing the bitwise NOT operation. + */ + bitNot(): FunctionExpr; + + /** + * @beta + * + * Creates an expression that applies a bitwise left shift operation to this expression. + * + * ```typescript + * // Calculate the bitwise left shift of 'field1' by 2 bits. + * field("field1").bitLeftShift(2); + * ``` + * + * @param y The operand constant representing the number of bits to shift. + * @return A new {@code Expr} representing the bitwise left shift operation. + */ + bitLeftShift(y: number): FunctionExpr; + /** + * @beta + * + * Creates an expression that applies a bitwise left shift operation to this expression. + * + * ```typescript + * // Calculate the bitwise left shift of 'field1' by 'field2' bits. + * field("field1").bitLeftShift(field("field2")); + * ``` + * + * @param numberExpr The operand expression representing the number of bits to shift. + * @return A new {@code Expr} representing the bitwise left shift operation. + */ + bitLeftShift(numberExpr: Expr): FunctionExpr; + + /** + * @beta + * + * Creates an expression that applies a bitwise right shift operation to this expression. + * + * ```typescript + * // Calculate the bitwise right shift of 'field1' by 2 bits. + * field("field1").bitRightShift(2); + * ``` + * + * @param right The operand constant representing the number of bits to shift. + * @return A new {@code Expr} representing the bitwise right shift operation. + */ + bitRightShift(y: number): FunctionExpr; + /** + * @beta + * + * Creates an expression that applies a bitwise right shift operation to this expression. + * + * ```typescript + * // Calculate the bitwise right shift of 'field1' by 'field2' bits. + * field("field1").bitRightShift(field("field2")); + * ``` + * + * @param numberExpr The operand expression representing the number of bits to shift. + * @return A new {@code Expr} representing the bitwise right shift operation. + */ + bitRightShift(numberExpr: Expr): FunctionExpr; + + /** + * @beta + * + * Creates an expression that returns the document ID from a path. + * + * ```typescript + * // Get the document ID from a path. + * field("__path__").documentId(); + * ``` + * + * @return A new {@code Expr} representing the documentId operation. + */ + documentId(): FunctionExpr; + + /** + * @beta + * + * Creates an expression that returns a substring of the results of this expression. + * + * @param position Index of the first character of the substring. + * @param length Length of the substring. If not provided, the substring will + * end at the end of the input. + */ + substr(position: number, length?: number): FunctionExpr; + + /** + * @beta + * + * Creates an expression that returns a substring of the results of this expression. + * + * @param position An expression returning the index of the first character of the substring. + * @param length An expression returning the length of the substring. If not provided the + * substring will end at the end of the input. + */ + substr(position: Expr, length?: Expr): FunctionExpr; + + /** + * @beta + * Creates an expression that indexes into an array from the beginning or end + * and returns the element. If the offset exceeds the array length, an error is + * returned. A negative offset, starts from the end. + * + * ```typescript + * // Return the value in the 'tags' field array at index `1`. + * field('tags').arrayOffset(1); + * ``` + * + * @param offset The index of the element to return. + * @return A new Expr representing the 'arrayOffset' operation. + */ + arrayOffset(offset: number): FunctionExpr; + + /** + * @beta + * Creates an expression that indexes into an array from the beginning or end + * and returns the element. If the offset exceeds the array length, an error is + * returned. A negative offset, starts from the end. + * + * ```typescript + * // Return the value in the tags field array at index specified by field + * // 'favoriteTag'. + * field('tags').arrayOffset(field('favoriteTag')); + * ``` + * + * @param offsetExpr An Expr evaluating to the index of the element to return. + * @return A new Expr representing the 'arrayOffset' operation. + */ + arrayOffset(offsetExpr: Expr): FunctionExpr; + + /** + * @beta + * + * Creates an expression that checks if a given expression produces an error. + * + * ```typescript + * // Check if the result of a calculation is an error + * field("title").arrayContains(1).isError(); + * ``` + * + * @return A new {@code BooleanExpr} representing the 'isError' check. + */ + isError(): BooleanExpr; + + /** + * @beta + * + * Creates an expression that returns the result of the `catchExpr` argument + * if there is an error, else return the result of this expression. + * + * ```typescript + * // Returns the first item in the title field arrays, or returns + * // the entire title field if the array is empty or the field is another type. + * field("title").arrayOffset(0).ifError(field("title")); + * ``` + * + * @param catchExpr The catch expression that will be evaluated and + * returned if this expression produces an error. + * @return A new {@code Expr} representing the 'ifError' operation. + */ + ifError(catchExpr: Expr): FunctionExpr; + + /** + * @beta + * + * Creates an expression that returns the `catch` argument if there is an + * error, else return the result of this expression. + * + * ```typescript + * // Returns the first item in the title field arrays, or returns + * // "Default Title" + * field("title").arrayOffset(0).ifError("Default Title"); + * ``` + * + * @param catchValue The value that will be returned if this expression + * produces an error. + * @return A new {@code Expr} representing the 'ifError' operation. + */ + ifError(catchValue: unknown): FunctionExpr; + + /** + * @beta + * + * Creates an expression that returns `true` if the result of this expression + * is absent. Otherwise, returns `false` even if the value is `null`. + * + * ```typescript + * // Check if the field `value` is absent. + * field("value").isAbsent(); + * ``` + * + * @return A new {@code BooleanExpr} representing the 'isAbsent' check. + */ + isAbsent(): BooleanExpr; + + /** + * @beta + * + * Creates an expression that checks if tbe result of an expression is not null. + * + * ```typescript + * // Check if the value of the 'name' field is not null + * field("name").isNotNull(); + * ``` + * + * @return A new {@code BooleanExpr} representing the 'isNotNull' check. + */ + isNotNull(): BooleanExpr; + + /** + * @beta + * + * Creates an expression that checks if the results of this expression is NOT 'NaN' (Not a Number). + * + * ```typescript + * // Check if the result of a calculation is NOT NaN + * field("value").divide(0).isNotNan(); + * ``` + * + * @return A new {@code Expr} representing the 'isNaN' check. + */ + isNotNan(): BooleanExpr; + + /** + * @beta + * + * Creates an expression that removes a key from the map produced by evaluating this expression. + * + * ``` + * // Removes the key 'baz' from the input map. + * map({foo: 'bar', baz: true}).mapRemove('baz'); + * ``` + * + * @param key The name of the key to remove from the input map. + * @returns A new {@code FirestoreFunction} representing the 'mapRemove' operation. + */ + mapRemove(key: string): FunctionExpr; + /** + * @beta + * + * Creates an expression that removes a key from the map produced by evaluating this expression. + * + * ``` + * // Removes the key 'baz' from the input map. + * map({foo: 'bar', baz: true}).mapRemove(constant('baz')); + * ``` + * + * @param keyExpr An expression that produces the name of the key to remove from the input map. + * @returns A new {@code FirestoreFunction} representing the 'mapRemove' operation. + */ + mapRemove(keyExpr: Expr): FunctionExpr; + + /** + * @beta + * + * Creates an expression that merges multiple map values. + * + * ``` + * // 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 }, cond(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 {@code FirestoreFunction} representing the 'mapMerge' operation. + */ + mapMerge( + secondMap: Record | Expr, + ...otherMaps: Array | Expr> + ): FunctionExpr; + + /** + * Creates an {@link Ordering} that sorts documents in ascending order based on this expression. + * + * ```typescript + * // Sort documents by the 'name' field in ascending order + * pipeline().collection("users") + * .sort(field("name").ascending()); + * ``` + * + * @return A new `Ordering` for ascending sorting. + */ + ascending(): Ordering; + + /** + * Creates an {@link Ordering} that sorts documents in descending order based on this expression. + * + * ```typescript + * // Sort documents by the 'createdAt' field in descending order + * pipeline().collection("users") + * .sort(field("createdAt").descending()); + * ``` + * + * @return A new `Ordering` for descending sorting. + */ + descending(): Ordering; + + /** + * 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. + * + * ```typescript + * // Calculate the total price and assign it the alias "totalPrice" and add it to the output. + * pipeline().collection("items") + * .addFields(field("price").multiply(field("quantity")).as("totalPrice")); + * ``` + * + * @param name The alias to assign to this expression. + * @return A new {@link ExprWithAlias} that wraps this + * expression and associates it with the provided alias. + */ + as(name: string): ExprWithAlias; + } + + /** + * @beta * - * @param other The constant value to divide by. - * @return A new `Expr` representing the division operation. + * An interface that represents a selectable expression. */ - divide(other: number): FunctionExpr; - divide(other: number | Expr): FunctionExpr; + export interface Selectable { + selectable: true; + readonly alias: string; + readonly expr: Expr; + } /** - * Creates an expression that calculates the modulo (remainder) of dividing this expression by another expression. + * @beta * - * ```typescript - * // Calculate the remainder of dividing the 'value' field by the 'divisor' field - * field("value").mod(field("divisor")); - * ``` + * A class that represents an aggregate function. + */ + export class AggregateFunction { + exprType: ExprType; + constructor(name: string, params: Expr[]); + + /** + * Assigns an alias to this AggregateFunction. The alias specifies the name that + * the aggregated value will have in the output document. + * + * ```typescript + * // Calculate the average price of all items and assign it the alias "averagePrice". + * pipeline().collection("items") + * .aggregate(field("price").avg().as("averagePrice")); + * ``` + * + * @param name The alias to assign to this AggregateFunction. + * @return A new {@link AggregateWithAlias} that wraps this + * AggregateFunction and associates it with the provided alias. + */ + as(name: string): AggregateWithAlias; + } + + /** + * @beta * - * @param expression The expression to divide by. - * @return A new `Expr` representing the modulo operation. + * An AggregateFunction with alias. */ - mod(expression: Expr): FunctionExpr; + export class AggregateWithAlias { + readonly aggregate: AggregateFunction; + readonly alias: string; + } /** - * Creates an expression that calculates the modulo (remainder) of dividing this expression by a constant value. - * - * ```typescript - * // Calculate the remainder of dividing the 'value' field by 10 - * field("value").mod(10); - * ``` - * - * @param value The constant value to divide by. - * @return A new `Expr` representing the modulo operation. + * @beta */ - mod(value: number): FunctionExpr; + export class ExprWithAlias implements Selectable { + exprType: ExprType; + selectable: true; + + readonly expr: Expr; + readonly alias: string; + } /** - * Creates an expression that checks if this expression is equal to another expression. + * @beta + * + * Represents a reference to a field in a Firestore document, or outputs of a {@link Pipeline} stage. + * + *

      Field references are used to access document field values in expressions and to specify fields + * for sorting, filtering, and projecting data in Firestore pipelines. + * + *

      You can create a `Field` instance using the static {@link #of} method: * * ```typescript - * // Check if the 'age' field is equal to 21 - * field("age").eq(21); - * ``` + * // Create a Field instance for the 'name' field + * const nameField = field("name"); * - * @param expression The expression to compare for equality. - * @return A new `Expr` representing the equality comparison. + * // Create a Field instance for a nested field 'address.city' + * const cityField = field("address.city"); + * ``` */ - eq(expression: Expr): BooleanExpr; + export class Field extends Expr implements Selectable { + readonly exprType: ExprType; + selectable: true; + + fieldName(): string; + + get alias(): string; + + get expr(): Expr; + } /** - * Creates an expression that checks if this expression is equal to a constant value. + * Creates a {@code Field} instance representing the field at the given path. + * + * The path can be a simple field name (e.g., "name") or a dot-separated path to a nested field + * (e.g., "address.city"). * * ```typescript - * // Check if the 'city' field is equal to "London" - * field("city").eq("London"); + * // Create a Field instance for the 'title' field + * const titleField = field("title"); + * + * // Create a Field instance for a nested field 'author.firstName' + * const authorFirstNameField = field("author.firstName"); * ``` * - * @param value The constant value to compare for equality. - * @return A new `Expr` representing the equality comparison. + * @param name The path to the field. + * @return A new {@code Field} instance representing the specified field. */ - eq(value: unknown): BooleanExpr; + export function field(name: string): Field; + export function field(path: FieldPath): Field; /** - * Creates an expression that checks if this expression is not equal to another expression. + * @beta + * + * Represents a constant value that can be used in a Firestore pipeline expression. + * + * You can create a `Constant` instance using the static {@link #of} method: * * ```typescript - * // Check if the 'status' field is not equal to "completed" - * field("status").neq("completed"); - * ``` + * // Create a Constant instance for the number 10 + * const ten = constant(10); * - * @param expression The expression to compare for inequality. - * @return A new `Expr` representing the inequality comparison. + * // Create a Constant instance for the string "hello" + * const hello = constant("hello"); + * ``` */ - neq(expression: Expr): BooleanExpr; + export class Constant extends Expr { + readonly exprType: ExprType; + } /** - * Creates an expression that checks if this expression is not equal to a constant value. - * - * ```typescript - * // Check if the 'country' field is not equal to "USA" - * field("country").neq("USA"); - * ``` + * Creates a `Constant` instance for a number value. * - * @param value The constant value to compare for inequality. - * @return A new `Expr` representing the inequality comparison. + * @param value The number value. + * @return A new `Constant` instance. */ - neq(value: unknown): BooleanExpr; + export function constant(value: number): Constant; /** - * Creates an expression that checks if this expression is less than another expression. - * - * ```typescript - * // Check if the 'age' field is less than 'limit' - * field("age").lt(field('limit')); - * ``` + * Creates a `Constant` instance for a string value. * - * @param experession The expression to compare for less than. - * @return A new `Expr` representing the less than comparison. + * @param value The string value. + * @return A new `Constant` instance. */ - lt(experession: Expr): BooleanExpr; + export function constant(value: string): Constant; /** - * Creates an expression that checks if this expression is less than a constant value. - * - * ```typescript - * // Check if the 'price' field is less than 50 - * field("price").lt(50); - * ``` + * Creates a `Constant` instance for a boolean value. * - * @param value The constant value to compare for less than. - * @return A new `Expr` representing the less than comparison. + * @param value The boolean value. + * @return A new `Constant` instance. */ - lt(value: unknown): BooleanExpr; + export function constant(value: boolean): Constant; /** - * Creates an expression that checks if this expression is less than or equal to another - * expression. - * - * ```typescript - * // Check if the 'quantity' field is less than or equal to 20 - * field("quantity").lte(constant(20)); - * ``` + * Creates a `Constant` instance for a null value. * - * @param expression The expression to compare for less than or equal to. - * @return A new `Expr` representing the less than or equal to comparison. + * @param value The null value. + * @return A new `Constant` instance. */ - lte(expression: Expr): BooleanExpr; + export function constant(value: null): Constant; /** - * Creates an expression that checks if this expression is less than or equal to a constant value. + * Creates a `Constant` instance for a GeoPoint value. * - * ```typescript - * // Check if the 'score' field is less than or equal to 70 - * field("score").lte(70); - * ``` - * - * @param value The constant value to compare for less than or equal to. - * @return A new `Expr` representing the less than or equal to comparison. + * @param value The GeoPoint value. + * @return A new `Constant` instance. */ - lte(value: unknown): BooleanExpr; + export function constant(value: GeoPoint): Constant; /** - * Creates an expression that checks if this expression is greater than another expression. - * - * ```typescript - * // Check if the 'age' field is greater than the 'limit' field - * field("age").gt(field("limit")); - * ``` + * Creates a `Constant` instance for a Timestamp value. * - * @param expression The expression to compare for greater than. - * @return A new `Expr` representing the greater than comparison. + * @param value The Timestamp value. + * @return A new `Constant` instance. */ - gt(expression: Expr): BooleanExpr; + export function constant(value: Timestamp): Constant; /** - * Creates an expression that checks if this expression is greater than a constant value. - * - * ```typescript - * // Check if the 'price' field is greater than 100 - * field("price").gt(100); - * ``` + * Creates a `Constant` instance for a Date value. * - * @param value The constant value to compare for greater than. - * @return A new `Expr` representing the greater than comparison. + * @param value The Date value. + * @return A new `Constant` instance. */ - gt(value: unknown): BooleanExpr; + export function constant(value: Date): Constant; /** - * Creates an expression that checks if this expression is greater than or equal to another - * expression. - * - * ```typescript - * // Check if the 'quantity' field is greater than or equal to field 'requirement' plus 1 - * field("quantity").gte(field('requirement').add(1)); - * ``` + * Creates a `Constant` instance for a Buffer | Uint8Array value. * - * @param expression The expression to compare for greater than or equal to. - * @return A new `Expr` representing the greater than or equal to comparison. + * @param value The Buffer | Uint8Array value. + * @return A new `Constant` instance. */ - gte(expression: Expr): BooleanExpr; + export function constant(value: Buffer | Uint8Array): Constant; /** - * Creates an expression that checks if this expression is greater than or equal to a constant - * value. - * - * ```typescript - * // Check if the 'score' field is greater than or equal to 80 - * field("score").gte(80); - * ``` + * Creates a `Constant` instance for a DocumentReference value. * - * @param value The constant value to compare for greater than or equal to. - * @return A new `Expr` representing the greater than or equal to comparison. + * @param value The DocumentReference value. + * @return A new `Constant` instance. */ - gte(value: unknown): BooleanExpr; + export function constant(value: DocumentReference): Constant; /** - * Creates an expression that concatenates an array expression with one or more other arrays. + * Creates a `Constant` instance for a VectorValue value. * - * ```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. - * @return A new `Expr` representing the concatenated array. + * @param value The VectorValue value. + * @return A new `Constant` instance. */ - arrayConcat( - secondArray: Expr | unknown[], - ...otherArrays: Array - ): FunctionExpr; + export function constant(value: VectorValue): Constant; /** - * Creates an expression that checks if an array contains a specific element. + * Creates a `Constant` instance for a VectorValue value. * * ```typescript - * // Check if the 'sizes' array contains the value from the 'selectedSize' field - * field("sizes").arrayContains(field("selectedSize")); + * // Create a Constant instance for a vector value + * const vectorConstant = constantVector([1, 2, 3]); * ``` * - * @param expression The element to search for in the array. - * @return A new `Expr` representing the 'array_contains' comparison. + * @param value The VectorValue value. + * @return A new `Constant` instance. */ - arrayContains(expression: Expr): BooleanExpr; + export function constantVector(value: number[] | VectorValue): Constant; /** - * Creates an expression that checks if an array contains a specific value. + * @beta * - * ```typescript - * // Check if the 'colors' array contains "red" - * field("colors").arrayContains("red"); - * ``` + * This class defines the base class for Firestore {@link Pipeline} functions, which can be evaluated within pipeline + * execution. * - * @param value The element to search for in the array. - * @return A new `Expr` representing the 'array_contains' comparison. + * Typically, you would not use this class or its children directly. Use either the functions like {@link and}, {@link eq}, + * or the methods on {@link Expr} ({@link Expr#eq}, {@link Expr#lt}, etc.) to construct new Function instances. */ - arrayContains(value: unknown): BooleanExpr; + export class FunctionExpr extends Expr { + readonly exprType: ExprType; + + constructor(name: string, params: Expr[]); + } /** - * Creates an expression that checks if an array contains all the specified elements. - * - * ```typescript - * // Check if the 'tags' array contains both the value in field "tag1" and the literal value "tag2" - * field("tags").arrayContainsAll([field("tag1"), "tag2"]); - * ``` + * @beta * - * @param values The elements to check for in the array. - * @return A new `Expr` representing the 'array_contains_all' comparison. - */ - arrayContainsAll(values: Array): BooleanExpr; + * An interface that represents a filter condition. + */ + export class BooleanExpr extends FunctionExpr { + filterable: true; + + /** + * Creates an aggregation that finds the count of input documents satisfying + * this boolean expression. + * + * ```typescript + * // Find the count of documents with a score greater than 90 + * field("score").gt(90).countIf().as("highestScore"); + * ``` + * + * @return A new `AggregateFunction` representing the 'countIf' aggregation. + */ + countIf(): AggregateFunction; + + /** + * Creates an expression that negates this boolean expression. + * + * ```typescript + * // Find documents where the 'tags' field does not contain 'completed' + * field("tags").arrayContains("completed").not(); + * ``` + * + * @return A new {@code Expr} representing the negated filter condition. + */ + not(): BooleanExpr; + } /** - * Creates an expression that checks if an array contains all the specified elements. + * @beta + * Creates an aggregation that counts the number of stage inputs where the provided + * boolean expression evaluates to true. * * ```typescript - * // Check if the 'tags' array contains both of the values from field "tag1" and the literal value "tag2" - * field("tags").arrayContainsAll(array([field("tag1"), "tag2"])); + * // Count the number of documents where 'is_active' field equals true + * countIf(field("is_active").eq(true)).as("numActiveDocuments"); * ``` * - * @param arrayExpression The elements to check for in the array. - * @return A new `Expr` representing the 'array_contains_all' comparison. + * @param booleanExpr - The boolean expression to evaluate on each input. + * @returns A new `AggregateFunction` representing the 'countIf' aggregation. */ - arrayContainsAll(arrayExpression: Expr): BooleanExpr; + export function countIf(booleanExpr: BooleanExpr): AggregateFunction; /** - * Creates an expression that checks if an array contains any of the specified elements. - * - * ```typescript - * // Check if the 'categories' array contains either values from field "cate1" or "cate2" - * field("categories").arrayContainsAny([field("cate1"), field("cate2")]); - * ``` + * @beta + * Creates an expression that return a pseudo-random value of type double in the + * range of [0, 1), inclusive of 0 and exclusive of 1. * - * @param values The elements to check for in the array. - * @return A new `Expr` representing the 'array_contains_any' comparison. + * @returns A new `Expr` representing the 'rand' function. */ - arrayContainsAny(values: Array): BooleanExpr; + export function rand(): FunctionExpr; /** - * Creates an expression that checks if an array contains any of the specified elements. + * @beta + * + * Creates an expression that applies a bitwise AND operation between a field and a constant. * * ```typescript - * // Check if the 'groups' array contains either the value from the 'userGroup' field - * // or the value "guest" - * field("groups").arrayContainsAny(array([field("userGroup"), "guest"])); + * // Calculate the bitwise AND of 'field1' and 0xFF. + * bitAnd("field1", 0xFF); * ``` * - * @param arrayExpression The elements to check for in the array. - * @return A new `Expr` representing the 'array_contains_any' comparison. + * @param field The left operand field name. + * @param otherBits A constant representing bits. + * @return A new {@code Expr} representing the bitwise AND operation. */ - arrayContainsAny(arrayExpression: Expr): BooleanExpr; - + export function bitAnd( + field: string, + otherBits: number | Buffer | Uint8Array + ): FunctionExpr; /** - * Creates an expression that calculates the length of an array. + * @beta + * + * Creates an expression that applies a bitwise AND operation between a field and an expression. * * ```typescript - * // Get the number of items in the 'cart' array - * field("cart").arrayLength(); + * // Calculate the bitwise AND of 'field1' and 'field2'. + * bitAnd("field1", field("field2")); * ``` * - * @return A new `Expr` representing the length of the array. + * @param field The left operand field name. + * @param bitsExpression An expression that returns bits when evaluated. + * @return A new {@code Expr} representing the bitwise AND operation. */ - arrayLength(): FunctionExpr; - + export function bitAnd(field: string, bitsExpression: Expr): FunctionExpr; /** - * Creates an expression that checks if this expression is equal to any of the provided values or - * expressions. + * @beta + * + * Creates an expression that applies a bitwise AND operation between an expression and a constant. * * ```typescript - * // Check if the 'category' field is either "Electronics" or value of field 'primaryType' - * field("category").eqAny("Electronics", field("primaryType")); + * // Calculate the bitwise AND of 'field1' and 0xFF. + * bitAnd(field("field1"), 0xFF); * ``` * - * @param values The values or expressions to check against. - * @return A new `Expr` representing the 'IN' comparison. - */ - eqAny(values: Array): BooleanExpr; - + * @param bitsExpression An expression returning bits. + * @param otherBits A constant representing bits. + * @return A new {@code Expr} representing the bitwise AND operation. + */ + export function bitAnd( + bitsExpression: Expr, + otherBits: number | Buffer | Uint8Array + ): FunctionExpr; /** - * Creates an expression that checks if this expression is equal to any of the provided values or - * expressions. + * @beta + * + * Creates an expression that applies a bitwise AND operation between two expressions. * * ```typescript - * // Check if the 'category' field is either "Electronics" or value of field 'primaryType' - * field("category").eqAny(array(["Electronics", field("primaryType")])); + * // Calculate the bitwise AND of 'field1' and 'field2'. + * bitAnd(field("field1"), field("field2")); * ``` * - * @param arrayExpression An expression that evaluates to an array of values to check against. - * @return A new `Expr` representing the 'IN' comparison. + * @param bitsExpression An expression that returns bits when evaluated. + * @param otherBitsExpression An expression that returns bits when evaluated. + * @return A new {@code Expr} representing the bitwise AND operation. */ - eqAny(arrayExpression: Expr): BooleanExpr; + export function bitAnd( + bitsExpression: Expr, + otherBitsExpression: Expr + ): FunctionExpr; /** - * Creates an expression that checks if this expression is not equal to any of the provided values or - * expressions. + * @beta + * + * Creates an expression that applies a bitwise OR operation between a field and a constant. * * ```typescript - * // Check if the 'status' field is neither "pending" nor the value of 'rejectedStatus' - * field("status").notEqAny(["pending", field("rejectedStatus")]); + * // Calculate the bitwise OR of 'field1' and 0xFF. + * bitOr("field1", 0xFF); * ``` * - * @param values The values or expressions to check against. - * @return A new `Expr` representing the 'NotEqAny' comparison. + * @param field The left operand field name. + * @param otherBits A constant representing bits. + * @return A new {@code Expr} representing the bitwise OR operation. */ - notEqAny(values: Array): BooleanExpr; - + export function bitOr( + field: string, + otherBits: number | Buffer | Uint8Array + ): FunctionExpr; /** - * Creates an expression that checks if this expression is not equal to any of the values in the evaluated expression. + * @beta + * + * Creates an expression that applies a bitwise OR operation between a field and an expression. * * ```typescript - * // Check if the 'status' field is not equal to any value in the field 'rejectedStatuses' - * field("status").notEqAny(field('rejectedStatuses')); + * // Calculate the bitwise OR of 'field1' and 'field2'. + * bitOr("field1", field("field2")); * ``` * - * @param arrayExpression The values or expressions to check against. - * @return A new `Expr` representing the 'NotEqAny' comparison. + * @param field The left operand field name. + * @param bitsExpression An expression that returns bits when evaluated. + * @return A new {@code Expr} representing the bitwise OR operation. */ - notEqAny(arrayExpression: Expr): BooleanExpr; - + export function bitOr(field: string, bitsExpression: Expr): FunctionExpr; /** - * Creates an expression that checks if this expression evaluates to 'NaN' (Not a Number). + * @beta + * + * Creates an expression that applies a bitwise OR operation between an expression and a constant. * * ```typescript - * // Check if the result of a calculation is NaN - * field("value").divide(0).isNaN(); + * // Calculate the bitwise OR of 'field1' and 0xFF. + * bitOr(field("field1"), 0xFF); * ``` * - * @return A new `Expr` representing the 'isNaN' check. + * @param bitsExpression An expression returning bits. + * @param otherBits A constant representing bits. + * @return A new {@code Expr} representing the bitwise OR operation. */ - isNan(): BooleanExpr; - + export function bitOr( + bitsExpression: Expr, + otherBits: number | Buffer | Uint8Array + ): FunctionExpr; /** - * Creates an expression that checks if this expression evaluates to 'Null'. + * @beta + * + * Creates an expression that applies a bitwise OR operation between two expressions. * * ```typescript - * // Check if the result of a calculation is NaN - * field("value").isNull(); + * // Calculate the bitwise OR of 'field1' and 'field2'. + * bitOr(field("field1"), field("field2")); * ``` * - * @return A new `Expr` representing the 'isNull' check. + * @param bitsExpression An expression that returns bits when evaluated. + * @param otherBitsExpression An expression that returns bits when evaluated. + * @return A new {@code Expr} representing the bitwise OR operation. */ - isNull(): BooleanExpr; + export function bitOr( + bitsExpression: Expr, + otherBitsExpression: Expr + ): FunctionExpr; /** - * Creates an expression that checks if a field exists in the document. + * @beta + * + * Creates an expression that applies a bitwise XOR operation between a field and a constant. * * ```typescript - * // Check if the document has a field named "phoneNumber" - * field("phoneNumber").exists(); + * // Calculate the bitwise XOR of 'field1' and 0xFF. + * bitXor("field1", 0xFF); * ``` * - * @return A new `Expr` representing the 'exists' check. + * @param field The left operand field name. + * @param otherBits A constant representing bits. + * @return A new {@code Expr} representing the bitwise XOR operation. */ - exists(): BooleanExpr; - + export function bitXor( + field: string, + otherBits: number | Buffer | Uint8Array + ): FunctionExpr; /** - * Creates an expression that calculates the character length of a string in UTF-8. + * @beta + * + * Creates an expression that applies a bitwise XOR operation between a field and an expression. * * ```typescript - * // Get the character length of the 'name' field in its UTF-8 form. - * field("name").charLength(); + * // Calculate the bitwise XOR of 'field1' and 'field2'. + * bitXor("field1", field("field2")); * ``` * - * @return A new `Expr` representing the length of the string. + * @param field The left operand field name. + * @param bitsExpression An expression that returns bits when evaluated. + * @return A new {@code Expr} representing the bitwise XOR operation. */ - charLength(): FunctionExpr; - + export function bitXor(field: string, bitsExpression: Expr): FunctionExpr; /** - * Creates an expression that performs a case-sensitive string comparison. + * @beta + * + * Creates an expression that applies a bitwise XOR operation between an expression and a constant. * * ```typescript - * // Check if the 'title' field contains the word "guide" (case-sensitive) - * field("title").like("%guide%"); + * // Calculate the bitwise XOR of 'field1' and 0xFF. + * bitXor(field("field1"), 0xFF); * ``` * - * @param pattern The pattern to search for. You can use "%" as a wildcard character. - * @return A new `Expr` representing the 'like' comparison. + * @param bitsExpression An expression returning bits. + * @param otherBits A constant representing bits. + * @return A new {@code Expr} representing the bitwise XOR operation. */ - like(pattern: string): FunctionExpr; - + export function bitXor( + bitsExpression: Expr, + otherBits: number | Buffer | Uint8Array + ): FunctionExpr; /** - * Creates an expression that performs a case-sensitive string comparison. + * @beta + * + * Creates an expression that applies a bitwise XOR operation between two expressions. * * ```typescript - * // Check if the 'title' field contains the word "guide" (case-sensitive) - * field("title").like("%guide%"); + * // Calculate the bitwise XOR of 'field1' and 'field2'. + * bitXor(field("field1"), field("field2")); * ``` * - * @param pattern The pattern to search for. You can use "%" as a wildcard character. - * @return A new `Expr` representing the 'like' comparison. + * @param bitsExpression An expression that returns bits when evaluated. + * @param otherBitsExpression An expression that returns bits when evaluated. + * @return A new {@code Expr} representing the bitwise XOR operation. */ - like(pattern: Expr): FunctionExpr; + export function bitXor( + bitsExpression: Expr, + otherBitsExpression: Expr + ): FunctionExpr; /** - * Creates an expression that checks if a string contains a specified regular expression as a - * substring. + * @beta + * + * Creates an expression that applies a bitwise NOT operation to a field. * * ```typescript - * // Check if the 'description' field contains "example" (case-insensitive) - * field("description").regexContains("(?i)example"); + * // Calculate the bitwise NOT of 'field1'. + * bitNot("field1"); * ``` * - * @param pattern The regular expression to use for the search. - * @return A new `Expr` representing the 'contains' comparison. + * @param field The operand field name. + * @return A new {@code Expr} representing the bitwise NOT operation. */ - regexContains(pattern: string): BooleanExpr; - + export function bitNot(field: string): FunctionExpr; /** - * Creates an expression that checks if a string contains a specified regular expression as a - * substring. + * @beta + * + * Creates an expression that applies a bitwise NOT operation to an expression. * * ```typescript - * // Check if the 'description' field contains the regular expression stored in field 'regex' - * field("description").regexContains(field("regex")); + * // Calculate the bitwise NOT of 'field1'. + * bitNot(field("field1")); * ``` * - * @param pattern The regular expression to use for the search. - * @return A new `Expr` representing the 'contains' comparison. + * @param bitsValueExpression An expression that returns bits when evaluated. + * @return A new {@code Expr} representing the bitwise NOT operation. */ - regexContains(pattern: Expr): BooleanExpr; + export function bitNot(bitsValueExpression: Expr): FunctionExpr; /** - * Creates an expression that checks if a string matches a specified regular expression. + * @beta + * + * Creates an expression that applies a bitwise left shift operation between a field and a constant. * * ```typescript - * // Check if the 'email' field matches a valid email pattern - * field("email").regexMatch("[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,}"); + * // Calculate the bitwise left shift of 'field1' by 2 bits. + * bitLeftShift("field1", 2); * ``` * - * @param pattern The regular expression to use for the match. - * @return A new `Expr` representing the regular expression match. + * @param field The left operand field name. + * @param y The right operand constant representing the number of bits to shift. + * @return A new {@code Expr} representing the bitwise left shift operation. */ - regexMatch(pattern: string): BooleanExpr; - + export function bitLeftShift(field: string, y: number): FunctionExpr; /** - * Creates an expression that checks if a string matches a specified regular expression. + * @beta + * + * Creates an expression that applies a bitwise left shift operation between a field and an expression. * * ```typescript - * // Check if the 'email' field matches a regular expression stored in field 'regex' - * field("email").regexMatch(field("regex")); + * // Calculate the bitwise left shift of 'field1' by 'field2' bits. + * bitLeftShift("field1", field("field2")); * ``` * - * @param pattern The regular expression to use for the match. - * @return A new `Expr` representing the regular expression match. + * @param field The left operand field name. + * @param numberExpr The right operand expression representing the number of bits to shift. + * @return A new {@code Expr} representing the bitwise left shift operation. */ - regexMatch(pattern: Expr): BooleanExpr; - + export function bitLeftShift(field: string, numberExpr: Expr): FunctionExpr; /** - * Creates an expression that checks if a string contains a specified substring. + * @beta + * + * Creates an expression that applies a bitwise left shift operation between an expression and a constant. * * ```typescript - * // Check if the 'description' field contains "example". - * field("description").strContains("example"); + * // Calculate the bitwise left shift of 'field1' by 2 bits. + * bitLeftShift(field("field1"), 2); * ``` * - * @param substring The substring to search for. - * @return A new `Expr` representing the 'contains' comparison. + * @param xValue An expression returning bits. + * @param y The right operand constant representing the number of bits to shift. + * @return A new {@code Expr} representing the bitwise left shift operation. */ - strContains(substring: string): BooleanExpr; - + export function bitLeftShift(xValue: Expr, y: number): FunctionExpr; /** - * Creates an expression that checks if a string contains the string represented by another expression. + * @beta + * + * Creates an expression that applies a bitwise left shift operation between two expressions. * * ```typescript - * // Check if the 'description' field contains the value of the 'keyword' field. - * field("description").strContains(field("keyword")); + * // Calculate the bitwise left shift of 'field1' by 'field2' bits. + * bitLeftShift(field("field1"), field("field2")); * ``` * - * @param expr The expression representing the substring to search for. - * @return A new `Expr` representing the 'contains' comparison. + * @param xValue An expression returning bits. + * @param numberExpr The right operand expression representing the number of bits to shift. + * @return A new {@code Expr} representing the bitwise left shift operation. */ - strContains(expr: Expr): BooleanExpr; + export function bitLeftShift(xValue: Expr, numberExpr: Expr): FunctionExpr; /** - * Creates an expression that checks if a string starts with a given prefix. + * @beta + * + * Creates an expression that applies a bitwise right shift operation between a field and a constant. * * ```typescript - * // Check if the 'name' field starts with "Mr." - * field("name").startsWith("Mr."); + * // Calculate the bitwise right shift of 'field1' by 2 bits. + * bitRightShift("field1", 2); * ``` * - * @param prefix The prefix to check for. - * @return A new `Expr` representing the 'starts with' comparison. + * @param field The left operand field name. + * @param y The right operand constant representing the number of bits to shift. + * @return A new {@code Expr} representing the bitwise right shift operation. */ - startsWith(prefix: string): BooleanExpr; - + export function bitRightShift(field: string, y: number): FunctionExpr; /** - * Creates an expression that checks if a string starts with a given prefix (represented as an - * expression). + * @beta + * + * Creates an expression that applies a bitwise right shift operation between a field and an expression. * * ```typescript - * // Check if the 'fullName' field starts with the value of the 'firstName' field - * field("fullName").startsWith(field("firstName")); + * // Calculate the bitwise right shift of 'field1' by 'field2' bits. + * bitRightShift("field1", field("field2")); * ``` * - * @param prefix The prefix expression to check for. - * @return A new `Expr` representing the 'starts with' comparison. + * @param field The left operand field name. + * @param numberExpr The right operand expression representing the number of bits to shift. + * @return A new {@code Expr} representing the bitwise right shift operation. */ - startsWith(prefix: Expr): BooleanExpr; - + export function bitRightShift( + field: string, + numberExpr: Expr + ): FunctionExpr; /** - * Creates an expression that checks if a string ends with a given postfix. + * @beta + * + * Creates an expression that applies a bitwise right shift operation between an expression and a constant. * * ```typescript - * // Check if the 'filename' field ends with ".txt" - * field("filename").endsWith(".txt"); + * // Calculate the bitwise right shift of 'field1' by 2 bits. + * bitRightShift(field("field1"), 2); * ``` * - * @param suffix The postfix to check for. - * @return A new `Expr` representing the 'ends with' comparison. + * @param xValue An expression returning bits. + * @param y The right operand constant representing the number of bits to shift. + * @return A new {@code Expr} representing the bitwise right shift operation. */ - endsWith(suffix: string): BooleanExpr; - + export function bitRightShift(xValue: Expr, y: number): FunctionExpr; /** - * Creates an expression that checks if a string ends with a given postfix (represented as an - * expression). + * @beta + * + * Creates an expression that applies a bitwise right shift operation between two expressions. * * ```typescript - * // Check if the 'url' field ends with the value of the 'extension' field - * field("url").endsWith(field("extension")); + * // Calculate the bitwise right shift of 'field1' by 'field2' bits. + * bitRightShift(field("field1"), field("field2")); * ``` * - * @param suffix The postfix expression to check for. - * @return A new `Expr` representing the 'ends with' comparison. + * @param xValue An expression returning bits. + * @param right The right operand expression representing the number of bits to shift. + * @return A new {@code Expr} representing the bitwise right shift operation. */ - endsWith(suffix: Expr): BooleanExpr; + export function bitRightShift(xValue: Expr, numberExpr: Expr): FunctionExpr; /** - * Creates an expression that converts a string to lowercase. + * @beta + * Creates an expression that indexes into an array from the beginning or end + * and return the element. If the offset exceeds the array length, an error is + * returned. A negative offset, starts from the end. * * ```typescript - * // Convert the 'name' field to lowercase - * field("name").toLower(); + * // Return the value in the tags field array at index 1. + * arrayOffset('tags', 1); * ``` * - * @return A new `Expr` representing the lowercase string. + * @param arrayField The name of the array field. + * @param offset The index of the element to return. + * @return A new Expr representing the 'arrayOffset' operation. */ - toLower(): FunctionExpr; + export function arrayOffset( + arrayField: string, + offset: number + ): FunctionExpr; /** - * Creates an expression that converts a string to uppercase. + * @beta + * Creates an expression that indexes into an array from the beginning or end + * and return the element. If the offset exceeds the array length, an error is + * returned. A negative offset, starts from the end. * * ```typescript - * // Convert the 'title' field to uppercase - * field("title").toUpper(); + * // Return the value in the tags field array at index specified by field + * // 'favoriteTag'. + * arrayOffset('tags', field('favoriteTag')); * ``` * - * @return A new `Expr` representing the uppercase string. + * @param arrayField The name of the array field. + * @param offsetExpr An Expr evaluating to the index of the element to return. + * @return A new Expr representing the 'arrayOffset' operation. */ - toUpper(): FunctionExpr; + export function arrayOffset( + arrayField: string, + offsetExpr: Expr + ): FunctionExpr; /** - * Creates an expression that removes leading and trailing whitespace from a string. + * @beta + * Creates an expression that indexes into an array from the beginning or end + * and return the element. If the offset exceeds the array length, an error is + * returned. A negative offset, starts from the end. * * ```typescript - * // Trim whitespace from the 'userInput' field - * field("userInput").trim(); + * // Return the value in the tags field array at index 1. + * arrayOffset(field('tags'), 1); * ``` * - * @return A new `Expr` representing the trimmed string. + * @param arrayExpression An Expr evaluating to an array. + * @param offset The index of the element to return. + * @return A new Expr representing the 'arrayOffset' operation. */ - trim(): FunctionExpr; + export function arrayOffset( + arrayExpression: Expr, + offset: number + ): FunctionExpr; /** - * Creates an expression that concatenates string expressions together. + * @beta + * Creates an expression that indexes into an array from the beginning or end + * and return the element. If the offset exceeds the array length, an error is + * returned. A negative offset, starts from the end. * * ```typescript - * // Combine the 'firstName', " ", and 'lastName' fields into a single string - * field("firstName").strConcat(constant(" "), field("lastName")); + * // Return the value in the tags field array at index specified by field + * // 'favoriteTag'. + * arrayOffset(field('tags'), field('favoriteTag')); * ``` * - * @param secondString The additional expression or string literal to concatenate. - * @param otherStrings Optional additional expressions or string literals to concatenate. - * @return A new `Expr` representing the concatenated string. + * @param arrayExpression An Expr evaluating to an array. + * @param offsetExpr An Expr evaluating to the index of the element to return. + * @return A new Expr representing the 'arrayOffset' operation. */ - strConcat( - secondString: Expr | string, - ...otherStrings: Array + export function arrayOffset( + arrayExpression: Expr, + offsetExpr: Expr ): FunctionExpr; /** - * Creates an expression that reverses this string expression. + * @beta + * + * Creates an expression that checks if a given expression produces an error. * * ```typescript - * // Reverse the value of the 'myString' field. - * field("myString").reverse(); + * // Check if the result of a calculation is an error + * isError(field("title").arrayContains(1)); * ``` * - * @return A new {@code Expr} representing the reversed string. + * @param value The expression to check. + * @return A new {@code Expr} representing the 'isError' check. */ - reverse(): FunctionExpr; + export function isError(value: Expr): BooleanExpr; /** - * Creates an expression that replaces the first occurrence of a substring within this string expression with another substring. + * @beta + * + * Creates an expression that returns the `catch` argument if there is an + * error, else return the result of the `try` argument evaluation. * * ```typescript - * // Replace the first occurrence of "hello" with "hi" in the 'message' field - * field("message").replaceFirst("hello", "hi"); + * // Returns the first item in the title field arrays, or returns + * // the entire title field if the array is empty or the field is another type. + * ifError(field("title").arrayOffset(0), field("title")); * ``` * - * @param find The substring to search for. - * @param replace The substring to replace the first occurrence of 'find' with. - * @return A new {@code Expr} representing the string with the first occurrence replaced. + * @param tryExpr The try expression. + * @param catchExpr The catch expression that will be evaluated and + * returned if the tryExpr produces an error. + * @return A new {@code Expr} representing the 'ifError' operation. */ - replaceFirst(find: string, replace: string): FunctionExpr; + export function ifError(tryExpr: Expr, catchExpr: Expr): FunctionExpr; /** - * Creates an expression that replaces the first occurrence of a substring within this string expression with another substring, - * where the substring to find and the replacement substring are specified by expressions. + * @beta + * + * Creates an expression that returns the `catch` argument if there is an + * error, else return the result of the `try` argument evaluation. * * ```typescript - * // Replace the first occurrence of the value in 'findField' with the value in 'replaceField' in the 'message' field - * field("message").replaceFirst(field("findField"), field("replaceField")); + * // Returns the first item in the title field arrays, or returns + * // "Default Title" + * ifError(field("title").arrayOffset(0), "Default Title"); * ``` * - * @param find The expression representing the substring to search for. - * @param replace The expression representing the substring to replace the first occurrence of 'find' with. - * @return A new {@code Expr} representing the string with the first occurrence replaced. + * @param tryExpr The try expression. + * @param catchValue The value that will be returned if the tryExpr produces an + * error. + * @return A new {@code Expr} representing the 'ifError' operation. */ - replaceFirst(find: Expr, replace: Expr): FunctionExpr; + export function ifError(tryExpr: Expr, catchValue: unknown): FunctionExpr; /** - * Creates an expression that replaces all occurrences of a substring within this string expression with another substring. + * @beta + * + * Creates an expression that returns `true` if a value is absent. Otherwise, + * returns `false` even if the value is `null`. * * ```typescript - * // Replace all occurrences of "hello" with "hi" in the 'message' field - * field("message").replaceAll("hello", "hi"); + * // Check if the field `value` is absent. + * isAbsent(field("value")); * ``` * - * @param find The substring to search for. - * @param replace The substring to replace all occurrences of 'find' with. - * @return A new {@code Expr} representing the string with all occurrences replaced. + * @param value The expression to check. + * @return A new {@code Expr} representing the 'isAbsent' check. */ - replaceAll(find: string, replace: string): FunctionExpr; + export function isAbsent(value: Expr): BooleanExpr; /** - * Creates an expression that replaces all occurrences of a substring within this string expression with another substring, - * where the substring to find and the replacement substring are specified by expressions. + * @beta + * + * Creates an expression that returns `true` if a field is absent. Otherwise, + * returns `false` even if the field value is `null`. * * ```typescript - * // Replace all occurrences of the value in 'findField' with the value in 'replaceField' in the 'message' field - * field("message").replaceAll(field("findField"), field("replaceField")); + * // Check if the field `value` is absent. + * isAbsent("value"); * ``` * - * @param find The expression representing the substring to search for. - * @param replace The expression representing the substring to replace all occurrences of 'find' with. - * @return A new {@code Expr} representing the string with all occurrences replaced. + * @param field The field to check. + * @return A new {@code Expr} representing the 'isAbsent' check. */ - replaceAll(find: Expr, replace: Expr): FunctionExpr; + export function isAbsent(field: string): BooleanExpr; /** - * Creates an expression that calculates the length of this string expression in bytes. + * @beta + * + * Creates an expression that checks if an expression evaluates to 'NaN' (Not a Number). * * ```typescript - * // Calculate the length of the 'myString' field in bytes. - * field("myString").byteLength(); + * // Check if the result of a calculation is NaN + * isNaN(field("value").divide(0)); * ``` * - * @return A new {@code Expr} representing the length of the string in bytes. + * @param value The expression to check. + * @return A new {@code Expr} representing the 'isNaN' check. */ - byteLength(): FunctionExpr; + export function isNull(value: Expr): BooleanExpr; /** - * Accesses a value from a map (object) field using the provided key. + * @beta + * + * Creates an expression that checks if a field's value evaluates to 'NaN' (Not a Number). * * ```typescript - * // Get the 'city' value from the 'address' map field - * field("address").mapGet("city"); + * // Check if the result of a calculation is NaN + * isNaN("value"); * ``` * - * @param subfield The key to access in the map. - * @return A new `Expr` representing the value associated with the given key in the map. + * @param value The name of the field to check. + * @return A new {@code Expr} representing the 'isNaN' check. */ - mapGet(subfield: string): FunctionExpr; + export function isNull(value: string): BooleanExpr; /** - * Creates an aggregation that counts the number of stage inputs with valid evaluations of the - * expression or field. + * @beta + * + * Creates an expression that checks if tbe result of an expression is not null. * * ```typescript - * // Count the total number of products - * field("productId").count().as("totalProducts"); + * // Check if the value of the 'name' field is not null + * isNotNull(field("name")); * ``` * - * @return A new `AggregateFunction` representing the 'count' aggregation. + * @param value The expression to check. + * @return A new {@code Expr} representing the 'isNaN' check. */ - count(): AggregateFunction; + export function isNotNull(value: Expr): BooleanExpr; /** - * Creates an aggregation that calculates the sum of a numeric field across multiple stage inputs. + * @beta + * + * Creates an expression that checks if tbe value of a field is not null. * * ```typescript - * // Calculate the total revenue from a set of orders - * field("orderAmount").sum().as("totalRevenue"); + * // Check if the value of the 'name' field is not null + * isNotNull("name"); * ``` * - * @return A new `AggregateFunction` representing the 'sum' aggregation. + * @param value The name of the field to check. + * @return A new {@code Expr} representing the 'isNaN' check. */ - sum(): AggregateFunction; + export function isNotNull(value: string): BooleanExpr; /** - * Creates an aggregation that calculates the average (mean) of a numeric field across multiple - * stage inputs. + * @beta + * + * Creates an expression that checks if the results of this expression is NOT 'NaN' (Not a Number). * * ```typescript - * // Calculate the average age of users - * field("age").avg().as("averageAge"); + * // Check if the result of a calculation is NOT NaN + * isNotNaN(field("value").divide(0)); * ``` * - * @return A new `AggregateFunction` representing the 'avg' aggregation. + * @param value The expression to check. + * @return A new {@code Expr} representing the 'isNotNaN' check. */ - avg(): AggregateFunction; + export function isNotNan(value: Expr): BooleanExpr; /** - * Creates an aggregation that finds the minimum value of a field across multiple stage inputs. + * @beta + * + * Creates an expression that checks if the results of this expression is NOT 'NaN' (Not a Number). * * ```typescript - * // Find the lowest price of all products - * field("price").minimum().as("lowestPrice"); + * // Check if the value of a field is NOT NaN + * isNotNaN("value"); * ``` * - * @return A new `AggregateFunction` representing the 'min' aggregation. + * @param value The name of the field to check. + * @return A new {@code Expr} representing the 'isNotNaN' check. */ - minimum(): AggregateFunction; + export function isNotNan(value: string): BooleanExpr; /** - * Creates an aggregation that finds the maximum value of a field across multiple stage inputs. + * @beta + * + * Creates an expression that removes a key from the map at the specified field name. * - * ```typescript - * // Find the highest score in a leaderboard - * field("score").maximum().as("highestScore"); + * ``` + * // Removes the key 'city' field from the map in the address field of the input document. + * mapRemove('address', 'city'); * ``` * - * @return A new `AggregateFunction` representing the 'max' aggregation. + * @param mapField The name of a field containing a map value. + * @param key The name of the key to remove from the input map. */ - maximum(): AggregateFunction; - + export function mapRemove(mapField: string, key: string): FunctionExpr; /** - * Creates an expression that returns the larger value between this expression and another expression, based on Firestore's value type ordering. + * @beta * - * ```typescript - * // Returns the larger value between the 'timestamp' field and the current timestamp. - * field("timestamp").logicalMaximum(Function.currentTimestamp()); + * Creates an expression that removes a key from the map produced by evaluating an expression. + * + * ``` + * // Removes the key 'baz' from the input map. + * mapRemove(map({foo: 'bar', baz: true}), 'baz'); * ``` * - * @param second The second expression or literal to compare with. - * @param others Optional additional expressions or literals to compare with. - * @return A new {@code Expr} representing the logical max operation. + * @param mapExpr An expression return a map value. + * @param key The name of the key to remove from the input map. */ - logicalMaximum( - second: Expr | unknown, - ...others: Array - ): FunctionExpr; - + export function mapRemove(mapExpr: Expr, key: string): FunctionExpr; /** - * Creates an expression that returns the smaller value between this expression and another expression, based on Firestore's value type ordering. + * @beta * - * ```typescript - * // Returns the smaller value between the 'timestamp' field and the current timestamp. - * field("timestamp").logicalMinimum(Function.currentTimestamp()); + * Creates an expression that removes a key from the map at the specified field name. + * + * ``` + * // Removes the key 'city' field from the map in the address field of the input document. + * mapRemove('address', constant('city')); * ``` * - * @param second The second expression or literal to compare with. - * @param others Optional additional expressions or literals to compare with. - * @return A new {@code Expr} representing the logical min operation. + * @param mapField The name of a field containing a map value. + * @param keyExpr An expression that produces the name of the key to remove from the input map. */ - logicalMinimum( - second: Expr | unknown, - ...others: Array - ): FunctionExpr; - + export function mapRemove(mapField: string, keyExpr: Expr): FunctionExpr; /** - * Creates an expression that calculates the length (number of dimensions) of this Firestore Vector expression. + * @beta + * + * Creates an expression that removes a key from the map produced by evaluating an expression. * - * ```typescript - * // Get the vector length (dimension) of the field 'embedding'. - * field("embedding").vectorLength(); + * ``` + * // Removes the key 'baz' from the input map. + * mapRemove(map({foo: 'bar', baz: true}), constant('baz')); * ``` * - * @return A new {@code Expr} representing the length of the vector. + * @param mapExpr An expression return a map value. + * @param keyExpr An expression that produces the name of the key to remove from the input map. */ - vectorLength(): FunctionExpr; + export function mapRemove(mapExpr: Expr, keyExpr: Expr): FunctionExpr; /** - * Calculates the cosine distance between two vectors. + * @beta + * + * Creates an expression that merges multiple map values. * - * ```typescript - * // Calculate the cosine distance between the 'userVector' field and the 'itemVector' field - * field("userVector").cosineDistance(field("itemVector")); + * ``` + * // Merges the map in the settings field with, a map literal, and a map in + * // that is conditionally returned by another expression + * mapMerge('settings', { enabled: true }, cond(field('isAdmin'), { admin: true}, {}) * ``` * - * @param vectorExpression The other vector (represented as an Expr) to compare against. - * @return A new `Expr` representing the cosine distance between the two vectors. + * @param mapField Name of a field containing a map value that will be merged. + * @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. */ - cosineDistance(vectorExpression: Expr): FunctionExpr; + export function mapMerge( + mapField: string, + secondMap: Record | Expr, + ...otherMaps: Array | Expr> + ): FunctionExpr; + /** - * Calculates the Cosine distance between two vectors. + * @beta * - * ```typescript - * // Calculate the Cosine distance between the 'location' field and a target location - * field("location").cosineDistance(new VectorValue([37.7749, -122.4194])); + * Creates an expression that merges multiple map values. + * + * ``` + * // Merges the map in the settings field with, a map literal, and a map in + * // that is conditionally returned by another expression + * mapMerge(field('settings'), { enabled: true }, cond(field('isAdmin'), { admin: true}, {}) * ``` * - * @param vector The other vector (as a VectorValue) to compare against. - * @return A new `Expr` representing the Cosine* distance between the two vectors. + * @param firstMap An expression or literal map value that will be merged. + * @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. */ - cosineDistance(vector: VectorValue | number[]): FunctionExpr; + export function mapMerge( + firstMap: Record | Expr, + secondMap: Record | Expr, + ...otherMaps: Array | Expr> + ): FunctionExpr; /** - * Calculates the dot product between two vectors. + * @beta + * + * Creates an expression that returns the document ID from a path. * * ```typescript - * // Calculate the dot product between a feature vector and a target vector - * field("features").dotProduct([0.5, 0.8, 0.2]); + * // Get the document ID from a path. + * documentId(myDocumentReference); * ``` * - * @param vectorExpression The other vector (as an array of numbers) to calculate with. - * @return A new `Expr` representing the dot product between the two vectors. + * @return A new {@code Expr} representing the documentId operation. */ - dotProduct(vectorExpression: Expr): FunctionExpr; + export function documentId( + documentPath: string | DocumentReference + ): FunctionExpr; /** - * Calculates the dot product between two vectors. + * @beta + * + * Creates an expression that returns the document ID from a path. * * ```typescript - * // Calculate the dot product between a feature vector and a target vector - * field("features").dotProduct(new VectorValue([0.5, 0.8, 0.2])); + * // Get the document ID from a path. + * documentId(field("__path__")); * ``` * - * @param vector The other vector (as an array of numbers) to calculate with. - * @return A new `Expr` representing the dot product between the two vectors. + * @return A new {@code Expr} representing the documentId operation. */ - dotProduct(vector: VectorValue | number[]): FunctionExpr; + export function documentId(documentPathExpr: Expr): FunctionExpr; /** - * Calculates the Euclidean distance between two vectors. + * @beta * - * ```typescript - * // Calculate the Euclidean distance between the 'location' field and a target location - * field("location").euclideanDistance([37.7749, -122.4194]); - * ``` + * Creates an expression that returns a substring of a string or byte array. * - * @param vectorExpression The other vector (as an array of numbers) to calculate with. - * @return A new `Expr` representing the Euclidean distance between the two vectors. + * @param field The name of a field containing a string or byte array to compute the substring from. + * @param position Index of the first character of the substring. + * @param length Length of the substring. */ - euclideanDistance(vectorExpression: Expr): FunctionExpr; + export function substr( + field: string, + position: number, + length?: number + ): FunctionExpr; /** - * Calculates the Euclidean distance between two vectors. + * @beta * - * ```typescript - * // Calculate the Euclidean distance between the 'location' field and a target location - * field("location").euclideanDistance(new VectorValue([37.7749, -122.4194])); - * ``` + * Creates an expression that returns a substring of a string or byte array. * - * @param vector The other vector (as a VectorValue) to compare against. - * @return A new `Expr` representing the Euclidean distance between the two vectors. + * @param input An expression returning a string or byte array to compute the substring from. + * @param position Index of the first character of the substring. + * @param length Length of the substring. */ - euclideanDistance(vector: VectorValue | number[]): FunctionExpr; + export function substr( + input: Expr, + position: number, + length?: number + ): FunctionExpr; /** - * 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. + * @beta * - * ```typescript - * // Interpret the 'microseconds' field as microseconds since epoch. - * field("microseconds").unixMicrosToTimestamp(); - * ``` + * Creates an expression that returns a substring of a string or byte array. * - * @return A new {@code Expr} representing the timestamp. + * @param field The name of a field containing a string or byte array to compute the substring from. + * @param position An expression that returns the index of the first character of the substring. + * @param length An expression that returns the length of the substring. */ - unixMicrosToTimestamp(): FunctionExpr; + export function substr( + field: string, + position: Expr, + length?: Expr + ): FunctionExpr; /** - * Creates an expression that converts this timestamp expression to the number of microseconds since the Unix epoch (1970-01-01 00:00:00 UTC). + * @beta * - * ```typescript - * // Convert the 'timestamp' field to microseconds since epoch. - * field("timestamp").timestampToUnixMicros(); - * ``` + * Creates an expression that returns a substring of a string or byte array. * - * @return A new {@code Expr} representing the number of microseconds since epoch. + * @param input An expression returning a string or byte array to compute the substring from. + * @param position An expression that returns the index of the first character of the substring. + * @param length An expression that returns the length of the substring. */ - timestampToUnixMicros(): FunctionExpr; + export function substr( + input: Expr, + position: Expr, + length?: Expr + ): FunctionExpr; /** - * 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. + * @beta + * + * Creates an expression that adds two expressions together. * * ```typescript - * // Interpret the 'milliseconds' field as milliseconds since epoch. - * field("milliseconds").unixMillisToTimestamp(); + * // Add the value of the 'quantity' field and the 'reserve' field. + * add(field("quantity"), field("reserve")); * ``` * - * @return A new {@code Expr} representing the timestamp. + * @param first The first expression to add. + * @param second The second expression or literal to add. + * @param others Optional other expressions or literals to add. + * @return A new {@code Expr} representing the addition operation. */ - unixMillisToTimestamp(): FunctionExpr; + export function add( + first: Expr, + second: Expr | unknown, + ...others: Array + ): FunctionExpr; /** - * Creates an expression that converts this timestamp expression to the number of milliseconds since the Unix epoch (1970-01-01 00:00:00 UTC). + * @beta + * + * Creates an expression that adds a field's value to an expression. * * ```typescript - * // Convert the 'timestamp' field to milliseconds since epoch. - * field("timestamp").timestampToUnixMillis(); + * // Add the value of the 'quantity' field and the 'reserve' field. + * add("quantity", field("reserve")); * ``` * - * @return A new {@code Expr} representing the number of milliseconds since epoch. + * @param fieldName The name of the field containing the value to add. + * @param second The second expression or literal to add. + * @param others Optional other expressions or literals to add. + * @return A new {@code Expr} representing the addition operation. */ - timestampToUnixMillis(): FunctionExpr; + export function add( + fieldName: string, + second: Expr | unknown, + ...others: Array + ): FunctionExpr; /** - * 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. + * @beta + * + * Creates an expression that subtracts two expressions. * * ```typescript - * // Interpret the 'seconds' field as seconds since epoch. - * field("seconds").unixSecondsToTimestamp(); + * // Subtract the 'discount' field from the 'price' field + * subtract(field("price"), field("discount")); * ``` * - * @return A new {@code Expr} representing the timestamp. + * @param left The expression to subtract from. + * @param right The expression to subtract. + * @return A new {@code Expr} representing the subtraction operation. */ - unixSecondsToTimestamp(): FunctionExpr; + export function subtract(left: Expr, right: Expr): FunctionExpr; /** - * Creates an expression that converts this timestamp expression to the number of seconds since the Unix epoch (1970-01-01 00:00:00 UTC). + * @beta + * + * Creates an expression that subtracts a constant value from an expression. * * ```typescript - * // Convert the 'timestamp' field to seconds since epoch. - * field("timestamp").timestampToUnixSeconds(); + * // Subtract the constant value 2 from the 'value' field + * subtract(field("value"), 2); * ``` * - * @return A new {@code Expr} representing the number of seconds since epoch. + * @param expression The expression to subtract from. + * @param value The constant value to subtract. + * @return A new {@code Expr} representing the subtraction operation. */ - timestampToUnixSeconds(): FunctionExpr; + export function subtract(expression: Expr, value: unknown): FunctionExpr; /** - * Creates an expression that adds a specified amount of time to this timestamp expression. + * @beta + * + * Creates an expression that subtracts an expression from a field's value. * * ```typescript - * // Add some duration determined by field 'unit' and 'amount' to the 'timestamp' field. - * field("timestamp").timestampAdd(field("unit"), field("amount")); + * // Subtract the 'discount' field from the 'price' field + * subtract("price", field("discount")); * ``` * - * @param unit The expression evaluates to unit of time, must be one of 'microsecond', 'millisecond', 'second', 'minute', 'hour', 'day'. - * @param amount The expression evaluates to amount of the unit. - * @return A new {@code Expr} representing the resulting timestamp. + * @param fieldName The field name to subtract from. + * @param expression The expression to subtract. + * @return A new {@code Expr} representing the subtraction operation. */ - timestampAdd(unit: Expr, amount: Expr): FunctionExpr; + export function subtract(fieldName: string, expression: Expr): FunctionExpr; /** - * Creates an expression that adds a specified amount of time to this timestamp expression. + * @beta + * + * Creates an expression that subtracts a constant value from a field's value. * * ```typescript - * // Add 1 day to the 'timestamp' field. - * field("timestamp").timestampAdd("day", 1); + * // Subtract 20 from the value of the 'total' field + * subtract("total", 20); * ``` * - * @param unit The unit of time to add (e.g., "day", "hour"). - * @param amount The amount of time to add. - * @return A new {@code Expr} representing the resulting timestamp. + * @param fieldName The field name to subtract from. + * @param value The constant value to subtract. + * @return A new {@code Expr} representing the subtraction operation. */ - timestampAdd( - unit: - | 'microsecond' - | 'millisecond' - | 'second' - | 'minute' - | 'hour' - | 'day', - amount: number - ): FunctionExpr; + export function subtract(fieldName: string, value: unknown): FunctionExpr; /** - * Creates an expression that subtracts a specified amount of time from this timestamp expression. + * @beta + * + * Creates an expression that multiplies two expressions together. * * ```typescript - * // Subtract some duration determined by field 'unit' and 'amount' from the 'timestamp' field. - * field("timestamp").timestampSub(field("unit"), field("amount")); + * // Multiply the 'quantity' field by the 'price' field + * multiply(field("quantity"), field("price")); * ``` * - * @param unit The expression evaluates to unit of time, must be one of 'microsecond', 'millisecond', 'second', 'minute', 'hour', 'day'. - * @param amount The expression evaluates to amount of the unit. - * @return A new {@code Expr} representing the resulting timestamp. + * @param first The first expression to multiply. + * @param second The second expression or literal to multiply. + * @param others Optional additional expressions or literals to multiply. + * @return A new {@code Expr} representing the multiplication operation. */ - timestampSub(unit: Expr, amount: Expr): FunctionExpr; + export function multiply( + first: Expr, + second: Expr | unknown, + ...others: Array + ): FunctionExpr; /** - * Creates an expression that subtracts a specified amount of time from this timestamp expression. + * @beta + * + * Creates an expression that multiplies a field's value by an expression. * * ```typescript - * // Subtract 1 day from the 'timestamp' field. - * field("timestamp").timestampSub("day", 1); + * // Multiply the 'quantity' field by the 'price' field + * multiply("quantity", field("price")); * ``` * - * @param unit The unit of time to subtract (e.g., "day", "hour"). - * @param amount The amount of time to subtract. - * @return A new {@code Expr} representing the resulting timestamp. + * @param fieldName The name of the field containing the value to add. + * @param second The second expression or literal to add. + * @param others Optional other expressions or literals to add. + * @return A new {@code Expr} representing the multiplication operation. */ - timestampSub( - unit: - | 'microsecond' - | 'millisecond' - | 'second' - | 'minute' - | 'hour' - | 'day', - amount: number + export function multiply( + fieldName: string, + second: Expr | unknown, + ...others: Array ): FunctionExpr; /** * @beta * - * Creates an expression that applies a bitwise AND operation between this expression and a constant. + * Creates an expression that divides two expressions. * * ```typescript - * // Calculate the bitwise AND of 'field1' and 0xFF. - * field("field1").bitAnd(0xFF); + * // Divide the 'total' field by the 'count' field + * divide(field("total"), field("count")); * ``` * - * @param otherBits A constant representing bits. - * @return A new {@code Expr} representing the bitwise AND operation. + * @param left The expression to be divided. + * @param right The expression to divide by. + * @return A new {@code Expr} representing the division operation. */ - bitAnd(otherBits: number | Buffer | Uint8Array): FunctionExpr; + export function divide(left: Expr, right: Expr): FunctionExpr; + /** * @beta * - * Creates an expression that applies a bitwise AND operation between two expressions. + * Creates an expression that divides an expression by a constant value. * * ```typescript - * // Calculate the bitwise AND of 'field1' and 'field2'. - * field("field1").bitAnd(field("field2")); + * // Divide the 'value' field by 10 + * divide(field("value"), 10); * ``` * - * @param bitsExpression An expression that returns bits when evaluated. - * @return A new {@code Expr} representing the bitwise AND operation. + * @param expression The expression to be divided. + * @param value The constant value to divide by. + * @return A new {@code Expr} representing the division operation. */ - bitAnd(bitsExpression: Expr): FunctionExpr; + export function divide(expression: Expr, value: unknown): FunctionExpr; /** * @beta * - * Creates an expression that applies a bitwise OR operation between this expression and a constant. + * Creates an expression that divides a field's value by an expression. * * ```typescript - * // Calculate the bitwise OR of 'field1' and 0xFF. - * field("field1").bitOr(0xFF); + * // Divide the 'total' field by the 'count' field + * divide("total", field("count")); * ``` * - * @param otherBits A constant representing bits. - * @return A new {@code Expr} representing the bitwise OR operation. + * @param fieldName The field name to be divided. + * @param expressions The expression to divide by. + * @return A new {@code Expr} representing the division operation. */ - bitOr(otherBits: number | Buffer | Uint8Array): FunctionExpr; + export function divide(fieldName: string, expressions: Expr): FunctionExpr; + /** * @beta * - * Creates an expression that applies a bitwise OR operation between two expressions. + * Creates an expression that divides a field's value by a constant value. * * ```typescript - * // Calculate the bitwise OR of 'field1' and 'field2'. - * field("field1").bitOr(field("field2")); + * // Divide the 'value' field by 10 + * divide("value", 10); * ``` * - * @param bitsExpression An expression that returns bits when evaluated. - * @return A new {@code Expr} representing the bitwise OR operation. + * @param fieldName The field name to be divided. + * @param value The constant value to divide by. + * @return A new {@code Expr} representing the division operation. */ - bitOr(bitsExpression: Expr): FunctionExpr; + export function divide(fieldName: string, value: unknown): FunctionExpr; /** * @beta * - * Creates an expression that applies a bitwise XOR operation between this expression and a constant. + * Creates an expression that calculates the modulo (remainder) of dividing two expressions. * * ```typescript - * // Calculate the bitwise XOR of 'field1' and 0xFF. - * field("field1").bitXor(0xFF); + * // Calculate the remainder of dividing 'field1' by 'field2'. + * mod(field("field1"), field("field2")); * ``` * - * @param otherBits A constant representing bits. - * @return A new {@code Expr} representing the bitwise XOR operation. + * @param left The dividend expression. + * @param right The divisor expression. + * @return A new {@code Expr} representing the modulo operation. */ - bitXor(otherBits: number | Buffer | Uint8Array): FunctionExpr; + export function mod(left: Expr, right: Expr): FunctionExpr; + /** * @beta * - * Creates an expression that applies a bitwise XOR operation between two expressions. + * Creates an expression that calculates the modulo (remainder) of dividing an expression by a constant. * * ```typescript - * // Calculate the bitwise XOR of 'field1' and 'field2'. - * field("field1").bitXor(field("field2")); + * // Calculate the remainder of dividing 'field1' by 5. + * mod(field("field1"), 5); * ``` * - * @param bitsExpression An expression that returns bits when evaluated. - * @return A new {@code Expr} representing the bitwise XOR operation. + * @param expression The dividend expression. + * @param value The divisor constant. + * @return A new {@code Expr} representing the modulo operation. */ - bitXor(bitsExpression: Expr): FunctionExpr; + export function mod(expression: Expr, value: unknown): FunctionExpr; /** * @beta * - * Creates an expression that applies a bitwise NOT operation to this expression. + * Creates an expression that calculates the modulo (remainder) of dividing a field's value by an expression. * * ```typescript - * // Calculate the bitwise NOT of 'field1'. - * field("field1").bitNot(); + * // Calculate the remainder of dividing 'field1' by 'field2'. + * mod("field1", field("field2")); * ``` * - * @return A new {@code Expr} representing the bitwise NOT operation. + * @param fieldName The dividend field name. + * @param expression The divisor expression. + * @return A new {@code Expr} representing the modulo operation. */ - bitNot(): FunctionExpr; + export function mod(fieldName: string, expression: Expr): FunctionExpr; /** * @beta * - * Creates an expression that applies a bitwise left shift operation to this expression. + * Creates an expression that calculates the modulo (remainder) of dividing a field's value by a constant. * * ```typescript - * // Calculate the bitwise left shift of 'field1' by 2 bits. - * field("field1").bitLeftShift(2); + * // Calculate the remainder of dividing 'field1' by 5. + * mod("field1", 5); * ``` * - * @param y The operand constant representing the number of bits to shift. - * @return A new {@code Expr} representing the bitwise left shift operation. + * @param fieldName The dividend field name. + * @param value The divisor constant. + * @return A new {@code Expr} representing the modulo operation. */ - bitLeftShift(y: number): FunctionExpr; + export function mod(fieldName: string, value: unknown): FunctionExpr; + /** * @beta * - * Creates an expression that applies a bitwise left shift operation to this expression. + * Creates an expression that creates a Firestore map value from an input object. * * ```typescript - * // Calculate the bitwise left shift of 'field1' by 'field2' bits. - * field("field1").bitLeftShift(field("field2")); + * // Create a map from the input object and reference the 'baz' field value from the input document. + * map({foo: 'bar', baz: Field.of('baz')}).as('data'); * ``` * - * @param numberExpr The operand expression representing the number of bits to shift. - * @return A new {@code Expr} representing the bitwise left shift operation. + * @param elements The input map to evaluate in the expression. + * @return A new {@code Expr} representing the map function. */ - bitLeftShift(numberExpr: Expr): FunctionExpr; + export function map(elements: Record): FunctionExpr; /** * @beta * - * Creates an expression that applies a bitwise right shift operation to this expression. + * Creates an expression that creates a Firestore array value from an input array. * * ```typescript - * // Calculate the bitwise right shift of 'field1' by 2 bits. - * field("field1").bitRightShift(2); + * // Create an array value from the input array and reference the 'baz' field value from the input document. + * array(['bar', Field.of('baz')]).as('foo'); * ``` * - * @param right The operand constant representing the number of bits to shift. - * @return A new {@code Expr} representing the bitwise right shift operation. + * @param elements The input array to evaluate in the expression. + * @return A new {@code Expr} representing the array function. */ - bitRightShift(y: number): FunctionExpr; + export function array(elements: unknown[]): FunctionExpr; + /** * @beta * - * Creates an expression that applies a bitwise right shift operation to this expression. + * Creates an expression that checks if two expressions are equal. * * ```typescript - * // Calculate the bitwise right shift of 'field1' by 'field2' bits. - * field("field1").bitRightShift(field("field2")); + * // Check if the 'age' field is equal to an expression + * eq(field("age"), field("minAge").add(10)); * ``` * - * @param numberExpr The operand expression representing the number of bits to shift. - * @return A new {@code Expr} representing the bitwise right shift operation. + * @param left The first expression to compare. + * @param right The second expression to compare. + * @return A new `Expr` representing the equality comparison. */ - bitRightShift(numberExpr: Expr): FunctionExpr; + export function eq(left: Expr, right: Expr): BooleanExpr; /** * @beta * - * Creates an expression that returns the document ID from a path. + * Creates an expression that checks if an expression is equal to a constant value. * * ```typescript - * // Get the document ID from a path. - * field("__path__").documentId(); + * // Check if the 'age' field is equal to 21 + * eq(field("age"), 21); * ``` * - * @return A new {@code Expr} representing the documentId operation. + * @param expression The expression to compare. + * @param value The constant value to compare to. + * @return A new `Expr` representing the equality comparison. */ - documentId(): FunctionExpr; + export function eq(expression: Expr, value: unknown): BooleanExpr; /** * @beta * - * Creates an expression that returns a substring of the results of this expression. + * Creates an expression that checks if a field's value is equal to an expression. * - * @param position Index of the first character of the substring. - * @param length Length of the substring. If not provided, the substring will - * end at the end of the input. + * ```typescript + * // Check if the 'age' field is equal to the 'limit' field + * eq("age", field("limit")); + * ``` + * + * @param fieldName The field name to compare. + * @param expression The expression to compare to. + * @return A new `Expr` representing the equality comparison. */ - substr(position: number, length?: number): FunctionExpr; + export function eq(fieldName: string, expression: Expr): BooleanExpr; /** * @beta * - * Creates an expression that returns a substring of the results of this expression. + * Creates an expression that checks if a field's value is equal to a constant value. + * + * ```typescript + * // Check if the 'city' field is equal to string constant "London" + * eq("city", "London"); + * ``` * - * @param position An expression returning the index of the first character of the substring. - * @param length An expression returning the length of the substring. If not provided the - * substring will end at the end of the input. + * @param fieldName The field name to compare. + * @param value The constant value to compare to. + * @return A new `Expr` representing the equality comparison. */ - substr(position: Expr, length?: Expr): FunctionExpr; + export function eq(fieldName: string, value: unknown): BooleanExpr; /** * @beta - * Creates an expression that indexes into an array from the beginning or end - * and returns the element. If the offset exceeds the array length, an error is - * returned. A negative offset, starts from the end. + * + * Creates an expression that checks if two expressions are not equal. * * ```typescript - * // Return the value in the 'tags' field array at index `1`. - * field('tags').arrayOffset(1); + * // Check if the 'status' field is not equal to field 'finalState' + * neq(field("status"), field("finalState")); * ``` * - * @param offset The index of the element to return. - * @return A new Expr representing the 'arrayOffset' operation. + * @param left The first expression to compare. + * @param right The second expression to compare. + * @return A new `Expr` representing the inequality comparison. */ - arrayOffset(offset: number): FunctionExpr; + export function neq(left: Expr, right: Expr): BooleanExpr; /** * @beta - * Creates an expression that indexes into an array from the beginning or end - * and returns the element. If the offset exceeds the array length, an error is - * returned. A negative offset, starts from the end. + * + * Creates an expression that checks if an expression is not equal to a constant value. * * ```typescript - * // Return the value in the tags field array at index specified by field - * // 'favoriteTag'. - * field('tags').arrayOffset(field('favoriteTag')); + * // Check if the 'status' field is not equal to "completed" + * neq(field("status"), "completed"); * ``` * - * @param offsetExpr An Expr evaluating to the index of the element to return. - * @return A new Expr representing the 'arrayOffset' operation. + * @param expression The expression to compare. + * @param value The constant value to compare to. + * @return A new `Expr` representing the inequality comparison. */ - arrayOffset(offsetExpr: Expr): FunctionExpr; + export function neq(expression: Expr, value: unknown): BooleanExpr; /** * @beta * - * Creates an expression that checks if a given expression produces an error. + * Creates an expression that checks if a field's value is not equal to an expression. * * ```typescript - * // Check if the result of a calculation is an error - * field("title").arrayContains(1).isError(); + * // Check if the 'status' field is not equal to the value of 'expectedStatus' + * neq("status", field("expectedStatus")); * ``` * - * @return A new {@code BooleanExpr} representing the 'isError' check. + * @param fieldName The field name to compare. + * @param expression The expression to compare to. + * @return A new `Expr` representing the inequality comparison. */ - isError(): BooleanExpr; + export function neq(fieldName: string, expression: Expr): BooleanExpr; /** * @beta * - * Creates an expression that returns the result of the `catchExpr` argument - * if there is an error, else return the result of this expression. + * Creates an expression that checks if a field's value is not equal to a constant value. * * ```typescript - * // Returns the first item in the title field arrays, or returns - * // the entire title field if the array is empty or the field is another type. - * field("title").arrayOffset(0).ifError(field("title")); + * // Check if the 'country' field is not equal to "USA" + * neq("country", "USA"); * ``` * - * @param catchExpr The catch expression that will be evaluated and - * returned if this expression produces an error. - * @return A new {@code Expr} representing the 'ifError' operation. + * @param fieldName The field name to compare. + * @param value The constant value to compare to. + * @return A new `Expr` representing the inequality comparison. */ - ifError(catchExpr: Expr): FunctionExpr; + export function neq(fieldName: string, value: unknown): BooleanExpr; /** * @beta * - * Creates an expression that returns the `catch` argument if there is an - * error, else return the result of this expression. + * Creates an expression that checks if the first expression is less than the second expression. * * ```typescript - * // Returns the first item in the title field arrays, or returns - * // "Default Title" - * field("title").arrayOffset(0).ifError("Default Title"); + * // Check if the 'age' field is less than 30 + * lt(field("age"), field("limit")); * ``` * - * @param catchValue The value that will be returned if this expression - * produces an error. - * @return A new {@code Expr} representing the 'ifError' operation. + * @param left The first expression to compare. + * @param right The second expression to compare. + * @return A new `Expr` representing the less than comparison. */ - ifError(catchValue: unknown): FunctionExpr; + export function lt(left: Expr, right: Expr): BooleanExpr; /** * @beta * - * Creates an expression that returns `true` if the result of this expression - * is absent. Otherwise, returns `false` even if the value is `null`. + * Creates an expression that checks if an expression is less than a constant value. * * ```typescript - * // Check if the field `value` is absent. - * field("value").isAbsent(); + * // Check if the 'age' field is less than 30 + * lt(field("age"), 30); * ``` * - * @return A new {@code BooleanExpr} representing the 'isAbsent' check. + * @param expression The expression to compare. + * @param value The constant value to compare to. + * @return A new `Expr` representing the less than comparison. */ - isAbsent(): BooleanExpr; + export function lt(expression: Expr, value: unknown): BooleanExpr; /** * @beta * - * Creates an expression that checks if tbe result of an expression is not null. + * Creates an expression that checks if a field's value is less than an expression. * * ```typescript - * // Check if the value of the 'name' field is not null - * field("name").isNotNull(); + * // Check if the 'age' field is less than the 'limit' field + * lt("age", field("limit")); * ``` * - * @return A new {@code BooleanExpr} representing the 'isNotNull' check. + * @param fieldName The field name to compare. + * @param expression The expression to compare to. + * @return A new `Expr` representing the less than comparison. */ - isNotNull(): BooleanExpr; + export function lt(fieldName: string, expression: Expr): BooleanExpr; /** * @beta * - * Creates an expression that checks if the results of this expression is NOT 'NaN' (Not a Number). + * Creates an expression that checks if a field's value is less than a constant value. * * ```typescript - * // Check if the result of a calculation is NOT NaN - * field("value").divide(0).isNotNan(); + * // Check if the 'price' field is less than 50 + * lt("price", 50); * ``` * - * @return A new {@code Expr} representing the 'isNaN' check. + * @param fieldName The field name to compare. + * @param value The constant value to compare to. + * @return A new `Expr` representing the less than comparison. */ - isNotNan(): BooleanExpr; + export function lt(fieldName: string, value: unknown): BooleanExpr; /** * @beta * - * Creates an expression that removes a key from the map produced by evaluating this expression. + * Creates an expression that checks if the first expression is less than or equal to the second + * expression. * - * ``` - * // Removes the key 'baz' from the input map. - * map({foo: 'bar', baz: true}).mapRemove('baz'); + * ```typescript + * // Check if the 'quantity' field is less than or equal to 20 + * lte(field("quantity"), field("limit")); * ``` * - * @param key The name of the key to remove from the input map. - * @returns A new {@code FirestoreFunction} representing the 'mapRemove' operation. + * @param left The first expression to compare. + * @param right The second expression to compare. + * @return A new `Expr` representing the less than or equal to comparison. */ - mapRemove(key: string): FunctionExpr; + export function lte(left: Expr, right: Expr): BooleanExpr; + /** * @beta * - * Creates an expression that removes a key from the map produced by evaluating this expression. + * Creates an expression that checks if an expression is less than or equal to a constant value. * + * ```typescript + * // Check if the 'quantity' field is less than or equal to 20 + * lte(field("quantity"), 20); * ``` - * // Removes the key 'baz' from the input map. - * map({foo: 'bar', baz: true}).mapRemove(constant('baz')); + * + * @param expression The expression to compare. + * @param value The constant value to compare to. + * @return A new `Expr` representing the less than or equal to comparison. + */ + export function lte(expression: Expr, value: unknown): BooleanExpr; + + /** + * Creates an expression that checks if a field's value is less than or equal to an expression. + * + * ```typescript + * // Check if the 'quantity' field is less than or equal to the 'limit' field + * lte("quantity", field("limit")); * ``` * - * @param keyExpr An expression that produces the name of the key to remove from the input map. - * @returns A new {@code FirestoreFunction} representing the 'mapRemove' operation. + * @param fieldName The field name to compare. + * @param expression The expression to compare to. + * @return A new `Expr` representing the less than or equal to comparison. */ - mapRemove(keyExpr: Expr): FunctionExpr; + export function lte(fieldName: string, expression: Expr): BooleanExpr; /** * @beta * - * Creates an expression that merges multiple map values. + * Creates an expression that checks if a field's value is less than or equal to a constant value. * - * ``` - * // 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 }, cond(field('isAdmin'), { admin: true}, {}) + * ```typescript + * // Check if the 'score' field is less than or equal to 70 + * lte("score", 70); * ``` * - * @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 {@code FirestoreFunction} representing the 'mapMerge' operation. + * @param fieldName The field name to compare. + * @param value The constant value to compare to. + * @return A new `Expr` representing the less than or equal to comparison. */ - mapMerge( - secondMap: Record | Expr, - ...otherMaps: Array | Expr> - ): FunctionExpr; + export function lte(fieldName: string, value: unknown): BooleanExpr; /** - * Creates an {@link Ordering} that sorts documents in ascending order based on this expression. + * @beta + * + * Creates an expression that checks if the first expression is greater than the second + * expression. * * ```typescript - * // Sort documents by the 'name' field in ascending order - * pipeline().collection("users") - * .sort(field("name").ascending()); + * // Check if the 'age' field is greater than 18 + * gt(field("age"), Constant(9).add(9)); * ``` * - * @return A new `Ordering` for ascending sorting. + * @param left The first expression to compare. + * @param right The second expression to compare. + * @return A new `Expr` representing the greater than comparison. */ - ascending(): Ordering; + export function gt(left: Expr, right: Expr): BooleanExpr; /** - * Creates an {@link Ordering} that sorts documents in descending order based on this expression. + * @beta + * + * Creates an expression that checks if an expression is greater than a constant value. * * ```typescript - * // Sort documents by the 'createdAt' field in descending order - * pipeline().collection("users") - * .sort(field("createdAt").descending()); + * // Check if the 'age' field is greater than 18 + * gt(field("age"), 18); * ``` * - * @return A new `Ordering` for descending sorting. + * @param expression The expression to compare. + * @param value The constant value to compare to. + * @return A new `Expr` representing the greater than comparison. */ - descending(): Ordering; + export function gt(expression: Expr, value: unknown): BooleanExpr; /** - * Assigns an alias to this expression. + * @beta * - * Aliases are useful for renaming fields in the output of a stage or for giving meaningful - * names to calculated values. + * Creates an expression that checks if a field's value is greater than an expression. * * ```typescript - * // Calculate the total price and assign it the alias "totalPrice" and add it to the output. - * pipeline().collection("items") - * .addFields(field("price").multiply(field("quantity")).as("totalPrice")); + * // Check if the value of field 'age' is greater than the value of field 'limit' + * gt("age", field("limit")); * ``` * - * @param name The alias to assign to this expression. - * @return A new {@link ExprWithAlias} that wraps this - * expression and associates it with the provided alias. + * @param fieldName The field name to compare. + * @param expression The expression to compare to. + * @return A new `Expr` representing the greater than comparison. */ - as(name: string): ExprWithAlias; - } - - /** - * @beta - * - * An interface that represents a selectable expression. - */ - export interface Selectable { - selectable: true; - readonly alias: string; - readonly expr: Expr; - } - - /** - * @beta - * - * A class that represents an aggregate function. - */ - export class AggregateFunction { - exprType: ExprType; - constructor(name: string, params: Expr[]); + export function gt(fieldName: string, expression: Expr): BooleanExpr; /** - * Assigns an alias to this AggregateFunction. The alias specifies the name that - * the aggregated value will have in the output document. + * @beta + * + * Creates an expression that checks if a field's value is greater than a constant value. * * ```typescript - * // Calculate the average price of all items and assign it the alias "averagePrice". - * pipeline().collection("items") - * .aggregate(field("price").avg().as("averagePrice")); + * // Check if the 'price' field is greater than 100 + * gt("price", 100); * ``` * - * @param name The alias to assign to this AggregateFunction. - * @return A new {@link AggregateWithAlias} that wraps this - * AggregateFunction and associates it with the provided alias. + * @param fieldName The field name to compare. + * @param value The constant value to compare to. + * @return A new `Expr` representing the greater than comparison. */ - as(name: string): AggregateWithAlias; - } - - /** - * @beta - * - * An AggregateFunction with alias. - */ - export class AggregateWithAlias { - readonly aggregate: AggregateFunction; - readonly alias: string; - } - - /** - * @beta - */ - export class ExprWithAlias implements Selectable { - exprType: ExprType; - selectable: true; - - readonly expr: Expr; - readonly alias: string; - } - - /** - * @beta - * - * Represents a reference to a field in a Firestore document, or outputs of a {@link Pipeline} stage. - * - *

      Field references are used to access document field values in expressions and to specify fields - * for sorting, filtering, and projecting data in Firestore pipelines. - * - *

      You can create a `Field` instance using the static {@link #of} method: - * - * ```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"); - * ``` - */ - export class Field extends Expr implements Selectable { - readonly exprType: ExprType; - selectable: true; - - fieldName(): string; - - get alias(): string; - - get expr(): Expr; - } - - /** - * Creates a {@code Field} instance representing the field at the given path. - * - * The path can be a simple field name (e.g., "name") or a dot-separated path to a nested field - * (e.g., "address.city"). - * - * ```typescript - * // Create a Field instance for the 'title' field - * const titleField = field("title"); - * - * // Create a Field instance for a nested field 'author.firstName' - * const authorFirstNameField = field("author.firstName"); - * ``` - * - * @param name The path to the field. - * @return A new {@code Field} instance representing the specified field. - */ - export function field(name: string): Field; - export function field(path: FieldPath): Field; - - /** - * @beta - * - * Represents a constant value that can be used in a Firestore pipeline expression. - * - * You can create a `Constant` instance using the static {@link #of} method: - * - * ```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"); - * ``` - */ - export class Constant extends Expr { - readonly exprType: ExprType; - } - - /** - * Creates a `Constant` instance for a number value. - * - * @param value The number value. - * @return A new `Constant` instance. - */ - export function constant(value: number): Constant; - - /** - * Creates a `Constant` instance for a string value. - * - * @param value The string value. - * @return A new `Constant` instance. - */ - export function constant(value: string): Constant; - - /** - * Creates a `Constant` instance for a boolean value. - * - * @param value The boolean value. - * @return A new `Constant` instance. - */ - export function constant(value: boolean): Constant; - - /** - * Creates a `Constant` instance for a null value. - * - * @param value The null value. - * @return A new `Constant` instance. - */ - export function constant(value: null): Constant; - - /** - * Creates a `Constant` instance for a GeoPoint value. - * - * @param value The GeoPoint value. - * @return A new `Constant` instance. - */ - export function constant(value: GeoPoint): Constant; - - /** - * Creates a `Constant` instance for a Timestamp value. - * - * @param value The Timestamp value. - * @return A new `Constant` instance. - */ - export function constant(value: Timestamp): Constant; - - /** - * Creates a `Constant` instance for a Date value. - * - * @param value The Date value. - * @return A new `Constant` instance. - */ - export function constant(value: Date): Constant; + export function gt(fieldName: string, value: unknown): BooleanExpr; - /** - * Creates a `Constant` instance for a Buffer | Uint8Array value. - * - * @param value The Buffer | Uint8Array value. - * @return A new `Constant` instance. - */ - export function constant(value: Buffer | Uint8Array): Constant; + /** + * @beta + * + * Creates an expression that checks if the first expression is greater than or equal to the + * second expression. + * + * ```typescript + * // Check if the 'quantity' field is greater than or equal to the field "threshold" + * gte(field("quantity"), field("threshold")); + * ``` + * + * @param left The first expression to compare. + * @param right The second expression to compare. + * @return A new `Expr` representing the greater than or equal to comparison. + */ + export function gte(left: Expr, right: Expr): BooleanExpr; - /** - * Creates a `Constant` instance for a DocumentReference value. - * - * @param value The DocumentReference value. - * @return A new `Constant` instance. - */ - export function constant(value: DocumentReference): Constant; + /** + * @beta + * + * Creates an expression that checks if an expression is greater than or equal to a constant + * value. + * + * ```typescript + * // Check if the 'quantity' field is greater than or equal to 10 + * gte(field("quantity"), 10); + * ``` + * + * @param expression The expression to compare. + * @param value The constant value to compare to. + * @return A new `Expr` representing the greater than or equal to comparison. + */ + export function gte(expression: Expr, value: unknown): BooleanExpr; - /** - * Creates a `Constant` instance for a VectorValue value. - * - * @param value The VectorValue value. - * @return A new `Constant` instance. - */ - export function constant(value: VectorValue): Constant; + /** + * @beta + * + * Creates an expression that checks if a field's value is greater than or equal to an expression. + * + * ```typescript + * // Check if the value of field 'age' is greater than or equal to the value of field 'limit' + * gte("age", field("limit")); + * ``` + * + * @param fieldName The field name to compare. + * @param value The expression to compare to. + * @return A new `Expr` representing the greater than or equal to comparison. + */ + export function gte(fieldName: string, value: Expr): BooleanExpr; - /** - * Creates a `Constant` instance for a VectorValue value. - * - * ```typescript - * // Create a Constant instance for a vector value - * const vectorConstant = constantVector([1, 2, 3]); - * ``` - * - * @param value The VectorValue value. - * @return A new `Constant` instance. - */ - export function constantVector(value: number[] | VectorValue): Constant; + /** + * @beta + * + * Creates an expression that checks if a field's value is greater than or equal to a constant + * value. + * + * ```typescript + * // Check if the 'score' field is greater than or equal to 80 + * gte("score", 80); + * ``` + * + * @param fieldName The field name to compare. + * @param value The constant value to compare to. + * @return A new `Expr` representing the greater than or equal to comparison. + */ + export function gte(fieldName: string, value: unknown): BooleanExpr; - /** - * @beta - * - * This class defines the base class for Firestore {@link 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 and}, {@link eq}, - * or the methods on {@link Expr} ({@link Expr#eq}, {@link Expr#lt}, etc.) to construct new Function instances. - */ - export class FunctionExpr extends Expr { - readonly exprType: ExprType; + /** + * @beta + * + * Creates an expression that concatenates an array expression with other arrays. + * + * ```typescript + * // Combine the 'items' array with two new item arrays + * arrayConcat(field("items"), [field("newItems"), field("otherItems")]); + * ``` + * + * @param firstArray The first array expression to concatenate to. + * @param secondArray The second array expression or array literal to concatenate to. + * @param otherArrays Optional additional array expressions or array literals to concatenate. + * @return A new {@code Expr} representing the concatenated array. + */ + export function arrayConcat( + firstArray: Expr, + secondArray: Expr | unknown[], + ...otherArrays: Array + ): FunctionExpr; - constructor(name: string, params: Expr[]); - } + /** + * @beta + * + * Creates an expression that concatenates a field's array value with other arrays. + * + * ```typescript + * // Combine the 'items' array with two new item arrays + * arrayConcat("items", [field("newItems"), field("otherItems")]); + * ``` + * + * @param firstArrayField The first array to concatenate to. + * @param secondArray The second array expression or array literal to concatenate to. + * @param otherArrays Optional additional array expressions or array literals to concatenate. + * @return A new {@code Expr} representing the concatenated array. + */ + export function arrayConcat( + firstArrayField: string, + secondArray: Expr | unknown[], + ...otherArrays: Array + ): FunctionExpr; - /** - * @beta - * - * An interface that represents a filter condition. - */ - export class BooleanExpr extends FunctionExpr { - filterable: true; + /** + * @beta + * + * Creates an expression that checks if an array expression contains a specific element. + * + * ```typescript + * // Check if the 'colors' array contains the value of field 'selectedColor' + * arrayContains(field("colors"), field("selectedColor")); + * ``` + * + * @param array The array expression to check. + * @param element The element to search for in the array. + * @return A new {@code Expr} representing the 'array_contains' comparison. + */ + export function arrayContains(array: Expr, element: Expr): FunctionExpr; /** - * Creates an aggregation that finds the count of input documents satisfying - * this boolean expression. + * @beta + * + * Creates an expression that checks if an array expression contains a specific element. * * ```typescript - * // Find the count of documents with a score greater than 90 - * field("score").gt(90).countIf().as("highestScore"); + * // Check if the 'colors' array contains "red" + * arrayContains(field("colors"), "red"); * ``` * - * @return A new `AggregateFunction` representing the 'countIf' aggregation. + * @param array The array expression to check. + * @param element The element to search for in the array. + * @return A new {@code Expr} representing the 'array_contains' comparison. */ - countIf(): AggregateFunction; + export function arrayContains(array: Expr, element: unknown): FunctionExpr; /** - * Creates an expression that negates this boolean expression. + * @beta + * + * Creates an expression that checks if a field's array value contains a specific element. * * ```typescript - * // Find documents where the 'tags' field does not contain 'completed' - * field("tags").arrayContains("completed").not(); + * // Check if the 'colors' array contains the value of field 'selectedColor' + * arrayContains("colors", field("selectedColor")); * ``` * - * @return A new {@code Expr} representing the negated filter condition. + * @param fieldName The field name to check. + * @param element The element to search for in the array. + * @return A new {@code Expr} representing the 'array_contains' comparison. */ - not(): BooleanExpr; - } + export function arrayContains( + fieldName: string, + element: Expr + ): FunctionExpr; - /** - * @beta - * Creates an aggregation that counts the number of stage inputs where the provided - * boolean expression evaluates to true. - * - * ```typescript - * // Count the number of documents where 'is_active' field equals true - * countIf(field("is_active").eq(true)).as("numActiveDocuments"); - * ``` - * - * @param booleanExpr - The boolean expression to evaluate on each input. - * @returns A new `AggregateFunction` representing the 'countIf' aggregation. - */ - export function countIf(booleanExpr: BooleanExpr): AggregateFunction; - - /** - * @beta - * Creates an expression that return a pseudo-random value of type double in the - * range of [0, 1), inclusive of 0 and exclusive of 1. - * - * @returns A new `Expr` representing the 'rand' function. - */ - export function rand(): FunctionExpr; - - /** - * @beta - * - * Creates an expression that applies a bitwise AND operation between a field and a constant. - * - * ```typescript - * // Calculate the bitwise AND of 'field1' and 0xFF. - * bitAnd("field1", 0xFF); - * ``` - * - * @param field The left operand field name. - * @param otherBits A constant representing bits. - * @return A new {@code Expr} representing the bitwise AND operation. - */ - export function bitAnd( - field: string, - otherBits: number | Buffer | Uint8Array - ): FunctionExpr; - /** - * @beta - * - * Creates an expression that applies a bitwise AND operation between a field and an expression. - * - * ```typescript - * // Calculate the bitwise AND of 'field1' and 'field2'. - * bitAnd("field1", field("field2")); - * ``` - * - * @param field The left operand field name. - * @param bitsExpression An expression that returns bits when evaluated. - * @return A new {@code Expr} representing the bitwise AND operation. - */ - export function bitAnd(field: string, bitsExpression: Expr): FunctionExpr; - /** - * @beta - * - * Creates an expression that applies a bitwise AND operation between an expression and a constant. - * - * ```typescript - * // Calculate the bitwise AND of 'field1' and 0xFF. - * bitAnd(field("field1"), 0xFF); - * ``` - * - * @param bitsExpression An expression returning bits. - * @param otherBits A constant representing bits. - * @return A new {@code Expr} representing the bitwise AND operation. - */ - export function bitAnd( - bitsExpression: Expr, - otherBits: number | Buffer | Uint8Array - ): FunctionExpr; - /** - * @beta - * - * Creates an expression that applies a bitwise AND operation between two expressions. - * - * ```typescript - * // Calculate the bitwise AND of 'field1' and 'field2'. - * bitAnd(field("field1"), field("field2")); - * ``` - * - * @param bitsExpression An expression that returns bits when evaluated. - * @param otherBitsExpression An expression that returns bits when evaluated. - * @return A new {@code Expr} representing the bitwise AND operation. - */ - export function bitAnd( - bitsExpression: Expr, - otherBitsExpression: Expr - ): FunctionExpr; - - /** - * @beta - * - * Creates an expression that applies a bitwise OR operation between a field and a constant. - * - * ```typescript - * // Calculate the bitwise OR of 'field1' and 0xFF. - * bitOr("field1", 0xFF); - * ``` - * - * @param field The left operand field name. - * @param otherBits A constant representing bits. - * @return A new {@code Expr} representing the bitwise OR operation. - */ - export function bitOr( - field: string, - otherBits: number | Buffer | Uint8Array - ): FunctionExpr; - /** - * @beta - * - * Creates an expression that applies a bitwise OR operation between a field and an expression. - * - * ```typescript - * // Calculate the bitwise OR of 'field1' and 'field2'. - * bitOr("field1", field("field2")); - * ``` - * - * @param field The left operand field name. - * @param bitsExpression An expression that returns bits when evaluated. - * @return A new {@code Expr} representing the bitwise OR operation. - */ - export function bitOr(field: string, bitsExpression: Expr): FunctionExpr; - /** - * @beta - * - * Creates an expression that applies a bitwise OR operation between an expression and a constant. - * - * ```typescript - * // Calculate the bitwise OR of 'field1' and 0xFF. - * bitOr(field("field1"), 0xFF); - * ``` - * - * @param bitsExpression An expression returning bits. - * @param otherBits A constant representing bits. - * @return A new {@code Expr} representing the bitwise OR operation. - */ - export function bitOr( - bitsExpression: Expr, - otherBits: number | Buffer | Uint8Array - ): FunctionExpr; - /** - * @beta - * - * Creates an expression that applies a bitwise OR operation between two expressions. - * - * ```typescript - * // Calculate the bitwise OR of 'field1' and 'field2'. - * bitOr(field("field1"), field("field2")); - * ``` - * - * @param bitsExpression An expression that returns bits when evaluated. - * @param otherBitsExpression An expression that returns bits when evaluated. - * @return A new {@code Expr} representing the bitwise OR operation. - */ - export function bitOr( - bitsExpression: Expr, - otherBitsExpression: Expr - ): FunctionExpr; - - /** - * @beta - * - * Creates an expression that applies a bitwise XOR operation between a field and a constant. - * - * ```typescript - * // Calculate the bitwise XOR of 'field1' and 0xFF. - * bitXor("field1", 0xFF); - * ``` - * - * @param field The left operand field name. - * @param otherBits A constant representing bits. - * @return A new {@code Expr} representing the bitwise XOR operation. - */ - export function bitXor( - field: string, - otherBits: number | Buffer | Uint8Array - ): FunctionExpr; - /** - * @beta - * - * Creates an expression that applies a bitwise XOR operation between a field and an expression. - * - * ```typescript - * // Calculate the bitwise XOR of 'field1' and 'field2'. - * bitXor("field1", field("field2")); - * ``` - * - * @param field The left operand field name. - * @param bitsExpression An expression that returns bits when evaluated. - * @return A new {@code Expr} representing the bitwise XOR operation. - */ - export function bitXor(field: string, bitsExpression: Expr): FunctionExpr; - /** - * @beta - * - * Creates an expression that applies a bitwise XOR operation between an expression and a constant. - * - * ```typescript - * // Calculate the bitwise XOR of 'field1' and 0xFF. - * bitXor(field("field1"), 0xFF); - * ``` - * - * @param bitsExpression An expression returning bits. - * @param otherBits A constant representing bits. - * @return A new {@code Expr} representing the bitwise XOR operation. - */ - export function bitXor( - bitsExpression: Expr, - otherBits: number | Buffer | Uint8Array - ): FunctionExpr; - /** - * @beta - * - * Creates an expression that applies a bitwise XOR operation between two expressions. - * - * ```typescript - * // Calculate the bitwise XOR of 'field1' and 'field2'. - * bitXor(field("field1"), field("field2")); - * ``` - * - * @param bitsExpression An expression that returns bits when evaluated. - * @param otherBitsExpression An expression that returns bits when evaluated. - * @return A new {@code Expr} representing the bitwise XOR operation. - */ - export function bitXor( - bitsExpression: Expr, - otherBitsExpression: Expr - ): FunctionExpr; - - /** - * @beta - * - * Creates an expression that applies a bitwise NOT operation to a field. - * - * ```typescript - * // Calculate the bitwise NOT of 'field1'. - * bitNot("field1"); - * ``` - * - * @param field The operand field name. - * @return A new {@code Expr} representing the bitwise NOT operation. - */ - export function bitNot(field: string): FunctionExpr; - /** - * @beta - * - * Creates an expression that applies a bitwise NOT operation to an expression. - * - * ```typescript - * // Calculate the bitwise NOT of 'field1'. - * bitNot(field("field1")); - * ``` - * - * @param bitsValueExpression An expression that returns bits when evaluated. - * @return A new {@code Expr} representing the bitwise NOT operation. - */ - export function bitNot(bitsValueExpression: Expr): FunctionExpr; - - /** - * @beta - * - * Creates an expression that applies a bitwise left shift operation between a field and a constant. - * - * ```typescript - * // Calculate the bitwise left shift of 'field1' by 2 bits. - * bitLeftShift("field1", 2); - * ``` - * - * @param field The left operand field name. - * @param y The right operand constant representing the number of bits to shift. - * @return A new {@code Expr} representing the bitwise left shift operation. - */ - export function bitLeftShift(field: string, y: number): FunctionExpr; - /** - * @beta - * - * Creates an expression that applies a bitwise left shift operation between a field and an expression. - * - * ```typescript - * // Calculate the bitwise left shift of 'field1' by 'field2' bits. - * bitLeftShift("field1", field("field2")); - * ``` - * - * @param field The left operand field name. - * @param numberExpr The right operand expression representing the number of bits to shift. - * @return A new {@code Expr} representing the bitwise left shift operation. - */ - export function bitLeftShift(field: string, numberExpr: Expr): FunctionExpr; - /** - * @beta - * - * Creates an expression that applies a bitwise left shift operation between an expression and a constant. - * - * ```typescript - * // Calculate the bitwise left shift of 'field1' by 2 bits. - * bitLeftShift(field("field1"), 2); - * ``` - * - * @param xValue An expression returning bits. - * @param y The right operand constant representing the number of bits to shift. - * @return A new {@code Expr} representing the bitwise left shift operation. - */ - export function bitLeftShift(xValue: Expr, y: number): FunctionExpr; - /** - * @beta - * - * Creates an expression that applies a bitwise left shift operation between two expressions. - * - * ```typescript - * // Calculate the bitwise left shift of 'field1' by 'field2' bits. - * bitLeftShift(field("field1"), field("field2")); - * ``` - * - * @param xValue An expression returning bits. - * @param numberExpr The right operand expression representing the number of bits to shift. - * @return A new {@code Expr} representing the bitwise left shift operation. - */ - export function bitLeftShift(xValue: Expr, numberExpr: Expr): FunctionExpr; - - /** - * @beta - * - * Creates an expression that applies a bitwise right shift operation between a field and a constant. - * - * ```typescript - * // Calculate the bitwise right shift of 'field1' by 2 bits. - * bitRightShift("field1", 2); - * ``` - * - * @param field The left operand field name. - * @param y The right operand constant representing the number of bits to shift. - * @return A new {@code Expr} representing the bitwise right shift operation. - */ - export function bitRightShift(field: string, y: number): FunctionExpr; - /** - * @beta - * - * Creates an expression that applies a bitwise right shift operation between a field and an expression. - * - * ```typescript - * // Calculate the bitwise right shift of 'field1' by 'field2' bits. - * bitRightShift("field1", field("field2")); - * ``` - * - * @param field The left operand field name. - * @param numberExpr The right operand expression representing the number of bits to shift. - * @return A new {@code Expr} representing the bitwise right shift operation. - */ - export function bitRightShift(field: string, numberExpr: Expr): FunctionExpr; - /** - * @beta - * - * Creates an expression that applies a bitwise right shift operation between an expression and a constant. - * - * ```typescript - * // Calculate the bitwise right shift of 'field1' by 2 bits. - * bitRightShift(field("field1"), 2); - * ``` - * - * @param xValue An expression returning bits. - * @param y The right operand constant representing the number of bits to shift. - * @return A new {@code Expr} representing the bitwise right shift operation. - */ - export function bitRightShift(xValue: Expr, y: number): FunctionExpr; - /** - * @beta - * - * Creates an expression that applies a bitwise right shift operation between two expressions. - * - * ```typescript - * // Calculate the bitwise right shift of 'field1' by 'field2' bits. - * bitRightShift(field("field1"), field("field2")); - * ``` - * - * @param xValue An expression returning bits. - * @param right The right operand expression representing the number of bits to shift. - * @return A new {@code Expr} representing the bitwise right shift operation. - */ - export function bitRightShift(xValue: Expr, numberExpr: Expr): FunctionExpr; - - /** - * @beta - * Creates an expression that indexes into an array from the beginning or end - * and return the element. If the offset exceeds the array length, an error is - * returned. A negative offset, starts from the end. - * - * ```typescript - * // Return the value in the tags field array at index 1. - * arrayOffset('tags', 1); - * ``` - * - * @param arrayField The name of the array field. - * @param offset The index of the element to return. - * @return A new Expr representing the 'arrayOffset' operation. - */ - export function arrayOffset(arrayField: string, offset: number): FunctionExpr; - - /** - * @beta - * Creates an expression that indexes into an array from the beginning or end - * and return the element. If the offset exceeds the array length, an error is - * returned. A negative offset, starts from the end. - * - * ```typescript - * // Return the value in the tags field array at index specified by field - * // 'favoriteTag'. - * arrayOffset('tags', field('favoriteTag')); - * ``` - * - * @param arrayField The name of the array field. - * @param offsetExpr An Expr evaluating to the index of the element to return. - * @return A new Expr representing the 'arrayOffset' operation. - */ - export function arrayOffset( - arrayField: string, - offsetExpr: Expr - ): FunctionExpr; - - /** - * @beta - * Creates an expression that indexes into an array from the beginning or end - * and return the element. If the offset exceeds the array length, an error is - * returned. A negative offset, starts from the end. - * - * ```typescript - * // Return the value in the tags field array at index 1. - * arrayOffset(field('tags'), 1); - * ``` - * - * @param arrayExpression An Expr evaluating to an array. - * @param offset The index of the element to return. - * @return A new Expr representing the 'arrayOffset' operation. - */ - export function arrayOffset( - arrayExpression: Expr, - offset: number - ): FunctionExpr; - - /** - * @beta - * Creates an expression that indexes into an array from the beginning or end - * and return the element. If the offset exceeds the array length, an error is - * returned. A negative offset, starts from the end. - * - * ```typescript - * // Return the value in the tags field array at index specified by field - * // 'favoriteTag'. - * arrayOffset(field('tags'), field('favoriteTag')); - * ``` - * - * @param arrayExpression An Expr evaluating to an array. - * @param offsetExpr An Expr evaluating to the index of the element to return. - * @return A new Expr representing the 'arrayOffset' operation. - */ - export function arrayOffset( - arrayExpression: Expr, - offsetExpr: Expr - ): FunctionExpr; - - /** - * @beta - * - * Creates an expression that checks if a given expression produces an error. - * - * ```typescript - * // Check if the result of a calculation is an error - * isError(field("title").arrayContains(1)); - * ``` - * - * @param value The expression to check. - * @return A new {@code Expr} representing the 'isError' check. - */ - export function isError(value: Expr): BooleanExpr; - - /** - * @beta - * - * Creates an expression that returns the `catch` argument if there is an - * error, else return the result of the `try` argument evaluation. - * - * ```typescript - * // Returns the first item in the title field arrays, or returns - * // the entire title field if the array is empty or the field is another type. - * ifError(field("title").arrayOffset(0), field("title")); - * ``` - * - * @param tryExpr The try expression. - * @param catchExpr The catch expression that will be evaluated and - * returned if the tryExpr produces an error. - * @return A new {@code Expr} representing the 'ifError' operation. - */ - export function ifError(tryExpr: Expr, catchExpr: Expr): FunctionExpr; - - /** - * @beta - * - * Creates an expression that returns the `catch` argument if there is an - * error, else return the result of the `try` argument evaluation. - * - * ```typescript - * // Returns the first item in the title field arrays, or returns - * // "Default Title" - * ifError(field("title").arrayOffset(0), "Default Title"); - * ``` - * - * @param tryExpr The try expression. - * @param catchValue The value that will be returned if the tryExpr produces an - * error. - * @return A new {@code Expr} representing the 'ifError' operation. - */ - export function ifError(tryExpr: Expr, catchValue: unknown): FunctionExpr; - - /** - * @beta - * - * Creates an expression that returns `true` if a value is absent. Otherwise, - * returns `false` even if the value is `null`. - * - * ```typescript - * // Check if the field `value` is absent. - * isAbsent(field("value")); - * ``` - * - * @param value The expression to check. - * @return A new {@code Expr} representing the 'isAbsent' check. - */ - export function isAbsent(value: Expr): BooleanExpr; - - /** - * @beta - * - * Creates an expression that returns `true` if a field is absent. Otherwise, - * returns `false` even if the field value is `null`. - * - * ```typescript - * // Check if the field `value` is absent. - * isAbsent("value"); - * ``` - * - * @param field The field to check. - * @return A new {@code Expr} representing the 'isAbsent' check. - */ - export function isAbsent(field: string): BooleanExpr; - - /** - * @beta - * - * Creates an expression that checks if an expression evaluates to 'NaN' (Not a Number). - * - * ```typescript - * // Check if the result of a calculation is NaN - * isNaN(field("value").divide(0)); - * ``` - * - * @param value The expression to check. - * @return A new {@code Expr} representing the 'isNaN' check. - */ - export function isNull(value: Expr): BooleanExpr; - - /** - * @beta - * - * Creates an expression that checks if a field's value evaluates to 'NaN' (Not a Number). - * - * ```typescript - * // Check if the result of a calculation is NaN - * isNaN("value"); - * ``` - * - * @param value The name of the field to check. - * @return A new {@code Expr} representing the 'isNaN' check. - */ - export function isNull(value: string): BooleanExpr; - - /** - * @beta - * - * Creates an expression that checks if tbe result of an expression is not null. - * - * ```typescript - * // Check if the value of the 'name' field is not null - * isNotNull(field("name")); - * ``` - * - * @param value The expression to check. - * @return A new {@code Expr} representing the 'isNaN' check. - */ - export function isNotNull(value: Expr): BooleanExpr; - - /** - * @beta - * - * Creates an expression that checks if tbe value of a field is not null. - * - * ```typescript - * // Check if the value of the 'name' field is not null - * isNotNull("name"); - * ``` - * - * @param value The name of the field to check. - * @return A new {@code Expr} representing the 'isNaN' check. - */ - export function isNotNull(value: string): BooleanExpr; - - /** - * @beta - * - * Creates an expression that checks if the results of this expression is NOT 'NaN' (Not a Number). - * - * ```typescript - * // Check if the result of a calculation is NOT NaN - * isNotNaN(field("value").divide(0)); - * ``` - * - * @param value The expression to check. - * @return A new {@code Expr} representing the 'isNotNaN' check. - */ - export function isNotNan(value: Expr): BooleanExpr; - - /** - * @beta - * - * Creates an expression that checks if the results of this expression is NOT 'NaN' (Not a Number). - * - * ```typescript - * // Check if the value of a field is NOT NaN - * isNotNaN("value"); - * ``` - * - * @param value The name of the field to check. - * @return A new {@code Expr} representing the 'isNotNaN' check. - */ - export function isNotNan(value: string): BooleanExpr; - - /** - * @beta - * - * Creates an expression that removes a key from the map at the specified field name. - * - * ``` - * // Removes the key 'city' field from the map in the address field of the input document. - * mapRemove('address', 'city'); - * ``` - * - * @param mapField The name of a field containing a map value. - * @param key The name of the key to remove from the input map. - */ - export function mapRemove(mapField: string, key: string): FunctionExpr; - /** - * @beta - * - * Creates an expression that removes a key from the map produced by evaluating an expression. - * - * ``` - * // Removes the key 'baz' from the input map. - * mapRemove(map({foo: 'bar', baz: true}), 'baz'); - * ``` - * - * @param mapExpr An expression return a map value. - * @param key The name of the key to remove from the input map. - */ - export function mapRemove(mapExpr: Expr, key: string): FunctionExpr; - /** - * @beta - * - * Creates an expression that removes a key from the map at the specified field name. - * - * ``` - * // Removes the key 'city' field from the map in the address field of the input document. - * mapRemove('address', constant('city')); - * ``` - * - * @param mapField The name of a field containing a map value. - * @param keyExpr An expression that produces the name of the key to remove from the input map. - */ - export function mapRemove(mapField: string, keyExpr: Expr): FunctionExpr; - /** - * @beta - * - * Creates an expression that removes a key from the map produced by evaluating an expression. - * - * ``` - * // Removes the key 'baz' from the input map. - * mapRemove(map({foo: 'bar', baz: true}), constant('baz')); - * ``` - * - * @param mapExpr An expression return a map value. - * @param keyExpr An expression that produces the name of the key to remove from the input map. - */ - export function mapRemove(mapExpr: Expr, keyExpr: Expr): FunctionExpr; - - /** - * @beta - * - * Creates an expression that merges multiple map values. - * - * ``` - * // Merges the map in the settings field with, a map literal, and a map in - * // that is conditionally returned by another expression - * mapMerge('settings', { enabled: true }, cond(field('isAdmin'), { admin: true}, {}) - * ``` - * - * @param mapField Name of a field containing a map value that will be merged. - * @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. - */ - export function mapMerge( - mapField: string, - secondMap: Record | Expr, - ...otherMaps: Array | Expr> - ): FunctionExpr; - - /** - * @beta - * - * Creates an expression that merges multiple map values. - * - * ``` - * // Merges the map in the settings field with, a map literal, and a map in - * // that is conditionally returned by another expression - * mapMerge(field('settings'), { enabled: true }, cond(field('isAdmin'), { admin: true}, {}) - * ``` - * - * @param firstMap An expression or literal map value that will be merged. - * @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. - */ - export function mapMerge( - firstMap: Record | Expr, - secondMap: Record | Expr, - ...otherMaps: Array | Expr> - ): FunctionExpr; - - /** - * @beta - * - * Creates an expression that returns the document ID from a path. - * - * ```typescript - * // Get the document ID from a path. - * documentId(myDocumentReference); - * ``` - * - * @return A new {@code Expr} representing the documentId operation. - */ - export function documentId( - documentPath: string | DocumentReference - ): FunctionExpr; - - /** - * @beta - * - * Creates an expression that returns the document ID from a path. - * - * ```typescript - * // Get the document ID from a path. - * documentId(field("__path__")); - * ``` - * - * @return A new {@code Expr} representing the documentId operation. - */ - export function documentId(documentPathExpr: Expr): FunctionExpr; - - /** - * @beta - * - * Creates an expression that returns a substring of a string or byte array. - * - * @param field The name of a field containing a string or byte array to compute the substring from. - * @param position Index of the first character of the substring. - * @param length Length of the substring. - */ - export function substr( - field: string, - position: number, - length?: number - ): FunctionExpr; - - /** - * @beta - * - * Creates an expression that returns a substring of a string or byte array. - * - * @param input An expression returning a string or byte array to compute the substring from. - * @param position Index of the first character of the substring. - * @param length Length of the substring. - */ - export function substr( - input: Expr, - position: number, - length?: number - ): FunctionExpr; - - /** - * @beta - * - * Creates an expression that returns a substring of a string or byte array. - * - * @param field The name of a field containing a string or byte array to compute the substring from. - * @param position An expression that returns the index of the first character of the substring. - * @param length An expression that returns the length of the substring. - */ - export function substr( - field: string, - position: Expr, - length?: Expr - ): FunctionExpr; - - /** - * @beta - * - * Creates an expression that returns a substring of a string or byte array. - * - * @param input An expression returning a string or byte array to compute the substring from. - * @param position An expression that returns the index of the first character of the substring. - * @param length An expression that returns the length of the substring. - */ - export function substr( - input: Expr, - position: Expr, - length?: Expr - ): FunctionExpr; - - /** - * @beta - * - * Creates an expression that adds two expressions together. - * - * ```typescript - * // Add the value of the 'quantity' field and the 'reserve' field. - * add(field("quantity"), field("reserve")); - * ``` - * - * @param first The first expression to add. - * @param second The second expression or literal to add. - * @param others Optional other expressions or literals to add. - * @return A new {@code Expr} representing the addition operation. - */ - export function add( - first: Expr, - second: Expr | unknown, - ...others: Array - ): FunctionExpr; - - /** - * @beta - * - * Creates an expression that adds a field's value to an expression. - * - * ```typescript - * // Add the value of the 'quantity' field and the 'reserve' field. - * add("quantity", field("reserve")); - * ``` - * - * @param fieldName The name of the field containing the value to add. - * @param second The second expression or literal to add. - * @param others Optional other expressions or literals to add. - * @return A new {@code Expr} representing the addition operation. - */ - export function add( - fieldName: string, - second: Expr | unknown, - ...others: Array - ): FunctionExpr; - - /** - * @beta - * - * Creates an expression that subtracts two expressions. - * - * ```typescript - * // Subtract the 'discount' field from the 'price' field - * subtract(field("price"), field("discount")); - * ``` - * - * @param left The expression to subtract from. - * @param right The expression to subtract. - * @return A new {@code Expr} representing the subtraction operation. - */ - export function subtract(left: Expr, right: Expr): FunctionExpr; - - /** - * @beta - * - * Creates an expression that subtracts a constant value from an expression. - * - * ```typescript - * // Subtract the constant value 2 from the 'value' field - * subtract(field("value"), 2); - * ``` - * - * @param expression The expression to subtract from. - * @param value The constant value to subtract. - * @return A new {@code Expr} representing the subtraction operation. - */ - export function subtract(expression: Expr, value: unknown): FunctionExpr; - - /** - * @beta - * - * Creates an expression that subtracts an expression from a field's value. - * - * ```typescript - * // Subtract the 'discount' field from the 'price' field - * subtract("price", field("discount")); - * ``` - * - * @param fieldName The field name to subtract from. - * @param expression The expression to subtract. - * @return A new {@code Expr} representing the subtraction operation. - */ - export function subtract(fieldName: string, expression: Expr): FunctionExpr; - - /** - * @beta - * - * Creates an expression that subtracts a constant value from a field's value. - * - * ```typescript - * // Subtract 20 from the value of the 'total' field - * subtract("total", 20); - * ``` - * - * @param fieldName The field name to subtract from. - * @param value The constant value to subtract. - * @return A new {@code Expr} representing the subtraction operation. - */ - export function subtract(fieldName: string, value: unknown): FunctionExpr; - - /** - * @beta - * - * Creates an expression that multiplies two expressions together. - * - * ```typescript - * // Multiply the 'quantity' field by the 'price' field - * multiply(field("quantity"), field("price")); - * ``` - * - * @param first The first expression to multiply. - * @param second The second expression or literal to multiply. - * @param others Optional additional expressions or literals to multiply. - * @return A new {@code Expr} representing the multiplication operation. - */ - export function multiply( - first: Expr, - second: Expr | unknown, - ...others: Array - ): FunctionExpr; - - /** - * @beta - * - * Creates an expression that multiplies a field's value by an expression. - * - * ```typescript - * // Multiply the 'quantity' field by the 'price' field - * multiply("quantity", field("price")); - * ``` - * - * @param fieldName The name of the field containing the value to add. - * @param second The second expression or literal to add. - * @param others Optional other expressions or literals to add. - * @return A new {@code Expr} representing the multiplication operation. - */ - export function multiply( - fieldName: string, - second: Expr | unknown, - ...others: Array - ): FunctionExpr; - - /** - * @beta - * - * Creates an expression that divides two expressions. - * - * ```typescript - * // Divide the 'total' field by the 'count' field - * divide(field("total"), field("count")); - * ``` - * - * @param left The expression to be divided. - * @param right The expression to divide by. - * @return A new {@code Expr} representing the division operation. - */ - export function divide(left: Expr, right: Expr): FunctionExpr; - - /** - * @beta - * - * Creates an expression that divides an expression by a constant value. - * - * ```typescript - * // Divide the 'value' field by 10 - * divide(field("value"), 10); - * ``` - * - * @param expression The expression to be divided. - * @param value The constant value to divide by. - * @return A new {@code Expr} representing the division operation. - */ - export function divide(expression: Expr, value: unknown): FunctionExpr; - - /** - * @beta - * - * Creates an expression that divides a field's value by an expression. - * - * ```typescript - * // Divide the 'total' field by the 'count' field - * divide("total", field("count")); - * ``` - * - * @param fieldName The field name to be divided. - * @param expressions The expression to divide by. - * @return A new {@code Expr} representing the division operation. - */ - export function divide(fieldName: string, expressions: Expr): FunctionExpr; - - /** - * @beta - * - * Creates an expression that divides a field's value by a constant value. - * - * ```typescript - * // Divide the 'value' field by 10 - * divide("value", 10); - * ``` - * - * @param fieldName The field name to be divided. - * @param value The constant value to divide by. - * @return A new {@code Expr} representing the division operation. - */ - export function divide(fieldName: string, value: unknown): FunctionExpr; - - /** - * @beta - * - * Creates an expression that calculates the modulo (remainder) of dividing two expressions. - * - * ```typescript - * // Calculate the remainder of dividing 'field1' by 'field2'. - * mod(field("field1"), field("field2")); - * ``` - * - * @param left The dividend expression. - * @param right The divisor expression. - * @return A new {@code Expr} representing the modulo operation. - */ - export function mod(left: Expr, right: Expr): FunctionExpr; - - /** - * @beta - * - * Creates an expression that calculates the modulo (remainder) of dividing an expression by a constant. - * - * ```typescript - * // Calculate the remainder of dividing 'field1' by 5. - * mod(field("field1"), 5); - * ``` - * - * @param expression The dividend expression. - * @param value The divisor constant. - * @return A new {@code Expr} representing the modulo operation. - */ - export function mod(expression: Expr, value: unknown): FunctionExpr; - - /** - * @beta - * - * Creates an expression that calculates the modulo (remainder) of dividing a field's value by an expression. - * - * ```typescript - * // Calculate the remainder of dividing 'field1' by 'field2'. - * mod("field1", field("field2")); - * ``` - * - * @param fieldName The dividend field name. - * @param expression The divisor expression. - * @return A new {@code Expr} representing the modulo operation. - */ - export function mod(fieldName: string, expression: Expr): FunctionExpr; - - /** - * @beta - * - * Creates an expression that calculates the modulo (remainder) of dividing a field's value by a constant. - * - * ```typescript - * // Calculate the remainder of dividing 'field1' by 5. - * mod("field1", 5); - * ``` - * - * @param fieldName The dividend field name. - * @param value The divisor constant. - * @return A new {@code Expr} representing the modulo operation. - */ - export function mod(fieldName: string, value: unknown): FunctionExpr; - - /** - * @beta - * - * Creates an expression that creates a Firestore map value from an input object. - * - * ```typescript - * // Create a map from the input object and reference the 'baz' field value from the input document. - * map({foo: 'bar', baz: Field.of('baz')}).as('data'); - * ``` - * - * @param elements The input map to evaluate in the expression. - * @return A new {@code Expr} representing the map function. - */ - export function map(elements: Record): FunctionExpr; - - /** - * @beta - * - * Creates an expression that creates a Firestore array value from an input array. - * - * ```typescript - * // Create an array value from the input array and reference the 'baz' field value from the input document. - * array(['bar', Field.of('baz')]).as('foo'); - * ``` - * - * @param elements The input array to evaluate in the expression. - * @return A new {@code Expr} representing the array function. - */ - export function array(elements: unknown[]): FunctionExpr; - - /** - * @beta - * - * Creates an expression that checks if two expressions are equal. - * - * ```typescript - * // Check if the 'age' field is equal to an expression - * eq(field("age"), field("minAge").add(10)); - * ``` - * - * @param left The first expression to compare. - * @param right The second expression to compare. - * @return A new `Expr` representing the equality comparison. - */ - export function eq(left: Expr, right: Expr): BooleanExpr; - - /** - * @beta - * - * Creates an expression that checks if an expression is equal to a constant value. - * - * ```typescript - * // Check if the 'age' field is equal to 21 - * eq(field("age"), 21); - * ``` - * - * @param expression The expression to compare. - * @param value The constant value to compare to. - * @return A new `Expr` representing the equality comparison. - */ - export function eq(expression: Expr, value: unknown): BooleanExpr; - - /** - * @beta - * - * Creates an expression that checks if a field's value is equal to an expression. - * - * ```typescript - * // Check if the 'age' field is equal to the 'limit' field - * eq("age", field("limit")); - * ``` - * - * @param fieldName The field name to compare. - * @param expression The expression to compare to. - * @return A new `Expr` representing the equality comparison. - */ - export function eq(fieldName: string, expression: Expr): BooleanExpr; - - /** - * @beta - * - * Creates an expression that checks if a field's value is equal to a constant value. - * - * ```typescript - * // Check if the 'city' field is equal to string constant "London" - * eq("city", "London"); - * ``` - * - * @param fieldName The field name to compare. - * @param value The constant value to compare to. - * @return A new `Expr` representing the equality comparison. - */ - export function eq(fieldName: string, value: unknown): BooleanExpr; - - /** - * @beta - * - * Creates an expression that checks if two expressions are not equal. - * - * ```typescript - * // Check if the 'status' field is not equal to field 'finalState' - * neq(field("status"), field("finalState")); - * ``` - * - * @param left The first expression to compare. - * @param right The second expression to compare. - * @return A new `Expr` representing the inequality comparison. - */ - export function neq(left: Expr, right: Expr): BooleanExpr; - - /** - * @beta - * - * Creates an expression that checks if an expression is not equal to a constant value. - * - * ```typescript - * // Check if the 'status' field is not equal to "completed" - * neq(field("status"), "completed"); - * ``` - * - * @param expression The expression to compare. - * @param value The constant value to compare to. - * @return A new `Expr` representing the inequality comparison. - */ - export function neq(expression: Expr, value: unknown): BooleanExpr; - - /** - * @beta - * - * Creates an expression that checks if a field's value is not equal to an expression. - * - * ```typescript - * // Check if the 'status' field is not equal to the value of 'expectedStatus' - * neq("status", field("expectedStatus")); - * ``` - * - * @param fieldName The field name to compare. - * @param expression The expression to compare to. - * @return A new `Expr` representing the inequality comparison. - */ - export function neq(fieldName: string, expression: Expr): BooleanExpr; - - /** - * @beta - * - * Creates an expression that checks if a field's value is not equal to a constant value. - * - * ```typescript - * // Check if the 'country' field is not equal to "USA" - * neq("country", "USA"); - * ``` - * - * @param fieldName The field name to compare. - * @param value The constant value to compare to. - * @return A new `Expr` representing the inequality comparison. - */ - export function neq(fieldName: string, value: unknown): BooleanExpr; - - /** - * @beta - * - * Creates an expression that checks if the first expression is less than the second expression. - * - * ```typescript - * // Check if the 'age' field is less than 30 - * lt(field("age"), field("limit")); - * ``` - * - * @param left The first expression to compare. - * @param right The second expression to compare. - * @return A new `Expr` representing the less than comparison. - */ - export function lt(left: Expr, right: Expr): BooleanExpr; - - /** - * @beta - * - * Creates an expression that checks if an expression is less than a constant value. - * - * ```typescript - * // Check if the 'age' field is less than 30 - * lt(field("age"), 30); - * ``` - * - * @param expression The expression to compare. - * @param value The constant value to compare to. - * @return A new `Expr` representing the less than comparison. - */ - export function lt(expression: Expr, value: unknown): BooleanExpr; - - /** - * @beta - * - * Creates an expression that checks if a field's value is less than an expression. - * - * ```typescript - * // Check if the 'age' field is less than the 'limit' field - * lt("age", field("limit")); - * ``` - * - * @param fieldName The field name to compare. - * @param expression The expression to compare to. - * @return A new `Expr` representing the less than comparison. - */ - export function lt(fieldName: string, expression: Expr): BooleanExpr; - - /** - * @beta - * - * Creates an expression that checks if a field's value is less than a constant value. - * - * ```typescript - * // Check if the 'price' field is less than 50 - * lt("price", 50); - * ``` - * - * @param fieldName The field name to compare. - * @param value The constant value to compare to. - * @return A new `Expr` representing the less than comparison. - */ - export function lt(fieldName: string, value: unknown): BooleanExpr; - - /** - * @beta - * - * Creates an expression that checks if the first expression is less than or equal to the second - * expression. - * - * ```typescript - * // Check if the 'quantity' field is less than or equal to 20 - * lte(field("quantity"), field("limit")); - * ``` - * - * @param left The first expression to compare. - * @param right The second expression to compare. - * @return A new `Expr` representing the less than or equal to comparison. - */ - export function lte(left: Expr, right: Expr): BooleanExpr; - - /** - * @beta - * - * Creates an expression that checks if an expression is less than or equal to a constant value. - * - * ```typescript - * // Check if the 'quantity' field is less than or equal to 20 - * lte(field("quantity"), 20); - * ``` - * - * @param expression The expression to compare. - * @param value The constant value to compare to. - * @return A new `Expr` representing the less than or equal to comparison. - */ - export function lte(expression: Expr, value: unknown): BooleanExpr; - - /** - * Creates an expression that checks if a field's value is less than or equal to an expression. - * - * ```typescript - * // Check if the 'quantity' field is less than or equal to the 'limit' field - * lte("quantity", field("limit")); - * ``` - * - * @param fieldName The field name to compare. - * @param expression The expression to compare to. - * @return A new `Expr` representing the less than or equal to comparison. - */ - export function lte(fieldName: string, expression: Expr): BooleanExpr; - - /** - * @beta - * - * Creates an expression that checks if a field's value is less than or equal to a constant value. - * - * ```typescript - * // Check if the 'score' field is less than or equal to 70 - * lte("score", 70); - * ``` - * - * @param fieldName The field name to compare. - * @param value The constant value to compare to. - * @return A new `Expr` representing the less than or equal to comparison. - */ - export function lte(fieldName: string, value: unknown): BooleanExpr; - - /** - * @beta - * - * Creates an expression that checks if the first expression is greater than the second - * expression. - * - * ```typescript - * // Check if the 'age' field is greater than 18 - * gt(field("age"), Constant(9).add(9)); - * ``` - * - * @param left The first expression to compare. - * @param right The second expression to compare. - * @return A new `Expr` representing the greater than comparison. - */ - export function gt(left: Expr, right: Expr): BooleanExpr; - - /** - * @beta - * - * Creates an expression that checks if an expression is greater than a constant value. - * - * ```typescript - * // Check if the 'age' field is greater than 18 - * gt(field("age"), 18); - * ``` - * - * @param expression The expression to compare. - * @param value The constant value to compare to. - * @return A new `Expr` representing the greater than comparison. - */ - export function gt(expression: Expr, value: unknown): BooleanExpr; - - /** - * @beta - * - * Creates an expression that checks if a field's value is greater than an expression. - * - * ```typescript - * // Check if the value of field 'age' is greater than the value of field 'limit' - * gt("age", field("limit")); - * ``` - * - * @param fieldName The field name to compare. - * @param expression The expression to compare to. - * @return A new `Expr` representing the greater than comparison. - */ - export function gt(fieldName: string, expression: Expr): BooleanExpr; - - /** - * @beta - * - * Creates an expression that checks if a field's value is greater than a constant value. - * - * ```typescript - * // Check if the 'price' field is greater than 100 - * gt("price", 100); - * ``` - * - * @param fieldName The field name to compare. - * @param value The constant value to compare to. - * @return A new `Expr` representing the greater than comparison. - */ - export function gt(fieldName: string, value: unknown): BooleanExpr; - - /** - * @beta - * - * Creates an expression that checks if the first expression is greater than or equal to the - * second expression. - * - * ```typescript - * // Check if the 'quantity' field is greater than or equal to the field "threshold" - * gte(field("quantity"), field("threshold")); - * ``` - * - * @param left The first expression to compare. - * @param right The second expression to compare. - * @return A new `Expr` representing the greater than or equal to comparison. - */ - export function gte(left: Expr, right: Expr): BooleanExpr; - - /** - * @beta - * - * Creates an expression that checks if an expression is greater than or equal to a constant - * value. - * - * ```typescript - * // Check if the 'quantity' field is greater than or equal to 10 - * gte(field("quantity"), 10); - * ``` - * - * @param expression The expression to compare. - * @param value The constant value to compare to. - * @return A new `Expr` representing the greater than or equal to comparison. - */ - export function gte(expression: Expr, value: unknown): BooleanExpr; - - /** - * @beta - * - * Creates an expression that checks if a field's value is greater than or equal to an expression. - * - * ```typescript - * // Check if the value of field 'age' is greater than or equal to the value of field 'limit' - * gte("age", field("limit")); - * ``` - * - * @param fieldName The field name to compare. - * @param value The expression to compare to. - * @return A new `Expr` representing the greater than or equal to comparison. - */ - export function gte(fieldName: string, value: Expr): BooleanExpr; - - /** - * @beta - * - * Creates an expression that checks if a field's value is greater than or equal to a constant - * value. - * - * ```typescript - * // Check if the 'score' field is greater than or equal to 80 - * gte("score", 80); - * ``` - * - * @param fieldName The field name to compare. - * @param value The constant value to compare to. - * @return A new `Expr` representing the greater than or equal to comparison. - */ - export function gte(fieldName: string, value: unknown): BooleanExpr; - - /** - * @beta - * - * Creates an expression that concatenates an array expression with other arrays. - * - * ```typescript - * // Combine the 'items' array with two new item arrays - * arrayConcat(field("items"), [field("newItems"), field("otherItems")]); - * ``` - * - * @param firstArray The first array expression to concatenate to. - * @param secondArray The second array expression or array literal to concatenate to. - * @param otherArrays Optional additional array expressions or array literals to concatenate. - * @return A new {@code Expr} representing the concatenated array. - */ - export function arrayConcat( - firstArray: Expr, - secondArray: Expr | unknown[], - ...otherArrays: Array - ): FunctionExpr; - - /** - * @beta - * - * Creates an expression that concatenates a field's array value with other arrays. - * - * ```typescript - * // Combine the 'items' array with two new item arrays - * arrayConcat("items", [field("newItems"), field("otherItems")]); - * ``` - * - * @param firstArrayField The first array to concatenate to. - * @param secondArray The second array expression or array literal to concatenate to. - * @param otherArrays Optional additional array expressions or array literals to concatenate. - * @return A new {@code Expr} representing the concatenated array. - */ - export function arrayConcat( - firstArrayField: string, - secondArray: Expr | unknown[], - ...otherArrays: Array - ): FunctionExpr; - - /** - * @beta - * - * Creates an expression that checks if an array expression contains a specific element. - * - * ```typescript - * // Check if the 'colors' array contains the value of field 'selectedColor' - * arrayContains(field("colors"), field("selectedColor")); - * ``` - * - * @param array The array expression to check. - * @param element The element to search for in the array. - * @return A new {@code Expr} representing the 'array_contains' comparison. - */ - export function arrayContains(array: Expr, element: Expr): FunctionExpr; - - /** - * @beta - * - * Creates an expression that checks if an array expression contains a specific element. - * - * ```typescript - * // Check if the 'colors' array contains "red" - * arrayContains(field("colors"), "red"); - * ``` - * - * @param array The array expression to check. - * @param element The element to search for in the array. - * @return A new {@code Expr} representing the 'array_contains' comparison. - */ - export function arrayContains(array: Expr, element: unknown): FunctionExpr; - - /** - * @beta - * - * Creates an expression that checks if a field's array value contains a specific element. - * - * ```typescript - * // Check if the 'colors' array contains the value of field 'selectedColor' - * arrayContains("colors", field("selectedColor")); - * ``` - * - * @param fieldName The field name to check. - * @param element The element to search for in the array. - * @return A new {@code Expr} representing the 'array_contains' comparison. - */ - export function arrayContains(fieldName: string, element: Expr): FunctionExpr; - - /** - * @beta - * - * Creates an expression that checks if a field's array value contains a specific value. - * - * ```typescript - * // Check if the 'colors' array contains "red" - * arrayContains("colors", "red"); - * ``` - * - * @param fieldName The field name to check. - * @param element The element to search for in the array. - * @return A new {@code Expr} representing the 'array_contains' comparison. - */ - export function arrayContains( - fieldName: string, - element: unknown - ): BooleanExpr; - - /** - * @beta - * - * Creates an expression that checks if an array expression contains any of the specified - * elements. - * - * ```typescript - * // Check if the 'categories' array contains either values from field "cate1" or "Science" - * arrayContainsAny(field("categories"), [field("cate1"), "Science"]); - * ``` - * - * @param array The array expression to check. - * @param values The elements to check for in the array. - * @return A new {@code Expr} representing the 'array_contains_any' comparison. - */ - export function arrayContainsAny( - array: Expr, - values: Array - ): BooleanExpr; - - /** - * @beta - * - * Creates an expression that checks if a field's array value contains any of the specified - * elements. - * - * ```typescript - * // Check if the 'groups' array contains either the value from the 'userGroup' field - * // or the value "guest" - * arrayContainsAny("categories", [field("cate1"), "Science"]); - * ``` - * - * @param fieldName The field name to check. - * @param values The elements to check for in the array. - * @return A new {@code Expr} representing the 'array_contains_any' comparison. - */ - export function arrayContainsAny( - fieldName: string, - values: Array - ): BooleanExpr; - - /** - * @beta - * - * Creates an expression that checks if an array expression contains any of the specified - * elements. - * - * ```typescript - * // Check if the 'categories' array contains either values from field "cate1" or "Science" - * arrayContainsAny(field("categories"), array([field("cate1"), "Science"])); - * ``` - * - * @param array The array expression to check. - * @param values An expression that evaluates to an array, whose elements to check for in the array. - * @return A new {@code Expr} representing the 'array_contains_any' comparison. - */ - export function arrayContainsAny(array: Expr, values: Expr): BooleanExpr; - - /** - * @beta - * - * Creates an expression that checks if a field's array value contains any of the specified - * elements. - * - * ```typescript - * // Check if the 'groups' array contains either the value from the 'userGroup' field - * // or the value "guest" - * arrayContainsAny("categories", array([field("cate1"), "Science"])); - * ``` - * - * @param fieldName The field name to check. - * @param values An expression that evaluates to an array, whose elements to check for in the array field. - * @return A new {@code Expr} representing the 'array_contains_any' comparison. - */ - export function arrayContainsAny( - fieldName: string, - values: Expr - ): BooleanExpr; - - /** - * @beta - * - * Creates an expression that checks if an array expression contains all the specified elements. - * - * ```typescript - * // Check if the "tags" array contains all of the values: "SciFi", "Adventure", and the value from field "tag1" - * arrayContainsAll(field("tags"), [field("tag1"), constant("SciFi"), "Adventure"]); - * ``` - * - * @param array The array expression to check. - * @param values The elements to check for in the array. - * @return A new {@code Expr} representing the 'array_contains_all' comparison. - */ - export function arrayContainsAll( - array: Expr, - values: Array - ): BooleanExpr; - - /** - * @beta - * - * Creates an expression that checks if a field's array value contains all the specified values or - * expressions. - * - * ```typescript - * // Check if the 'tags' array contains both of the values from field 'tag1', the value "SciFi", and "Adventure" - * arrayContainsAll("tags", [field("tag1"), "SciFi", "Adventure"]); - * ``` - * - * @param fieldName The field name to check. - * @param values The elements to check for in the array. - * @return A new {@code Expr} representing the 'array_contains_all' comparison. - */ - export function arrayContainsAll( - fieldName: string, - values: Array - ): BooleanExpr; - - /** - * @beta - * - * Creates an expression that checks if an array expression contains all the specified elements. - * - * ```typescript - * // Check if the "tags" array contains all of the values: "SciFi", "Adventure", and the value from field "tag1" - * arrayContainsAll(field("tags"), [field("tag1"), constant("SciFi"), "Adventure"]); - * ``` - * - * @param array The array expression to check. - * @param arrayExpression The elements to check for in the array. - * @return A new {@code Expr} representing the 'array_contains_all' comparison. - */ - export function arrayContainsAll( - array: Expr, - arrayExpression: Expr - ): BooleanExpr; - - /** - * @beta - * - * Creates an expression that checks if a field's array value contains all the specified values or - * expressions. - * - * ```typescript - * // Check if the 'tags' array contains both of the values from field 'tag1', the value "SciFi", and "Adventure" - * arrayContainsAll("tags", [field("tag1"), "SciFi", "Adventure"]); - * ``` - * - * @param fieldName The field name to check. - * @param arrayExpression The elements to check for in the array. - * @return A new {@code Expr} representing the 'array_contains_all' comparison. - */ - export function arrayContainsAll( - fieldName: string, - arrayExpression: Expr - ): BooleanExpr; - - /** - * @beta - * - * Creates an expression that calculates the length of an array in a specified field. - * - * ```typescript - * // Get the number of items in field 'cart' - * arrayLength('cart'); - * ``` - * - * @param fieldName The name of the field containing an array to calculate the length of. - * @return A new {@code Expr} representing the length of the array. - */ - export function arrayLength(fieldName: string): FunctionExpr; - - /** - * @beta - * - * Creates an expression that calculates the length of an array expression. - * - * ```typescript - * // Get the number of items in the 'cart' array - * arrayLength(field("cart")); - * ``` - * - * @param array The array expression to calculate the length of. - * @return A new {@code Expr} representing the length of the array. - */ - export function arrayLength(array: Expr): FunctionExpr; - - /** - * @beta - * - * Creates an expression that checks if an expression, when evaluated, is equal to any of the provided values or - * expressions. - * - * ```typescript - * // Check if the 'category' field is either "Electronics" or value of field 'primaryType' - * eqAny(field("category"), [constant("Electronics"), field("primaryType")]); - * ``` - * - * @param expression The expression whose results to compare. - * @param values The values to check against. - * @return A new {@code Expr} representing the 'IN' comparison. - */ - export function eqAny( - expression: Expr, - values: Array - ): BooleanExpr; - - /** - * @beta - * - * Creates an expression that checks if an expression is equal to any of the provided values. - * - * ```typescript - * // Check if the 'category' field is set to a value in the disabledCategories field - * eqAny(field("category"), field('disabledCategories')); - * ``` - * - * @param expression The expression whose results to compare. - * @param arrayExpression An expression that evaluates to an array, whose elements to check for equality to the input. - * @return A new {@code Expr} representing the 'IN' comparison. - */ - export function eqAny(expression: Expr, arrayExpression: Expr): BooleanExpr; - - /** - * @beta - * - * Creates an expression that checks if a field's value is equal to any of the provided values or - * expressions. - * - * ```typescript - * // Check if the 'category' field is either "Electronics" or value of field 'primaryType' - * eqAny("category", [constant("Electronics"), field("primaryType")]); - * ``` - * - * @param fieldName The field to compare. - * @param values The values to check against. - * @return A new {@code Expr} representing the 'IN' comparison. - */ - export function eqAny( - fieldName: string, - values: Array - ): BooleanExpr; - - /** - * @beta - * - * Creates an expression that checks if a field's value is equal to any of the provided values or - * expressions. - * - * ```typescript - * // Check if the 'category' field is either "Electronics" or value of field 'primaryType' - * eqAny("category", ["Electronics", field("primaryType")]); - * ``` - * - * @param fieldName The field to compare. - * @param arrayExpression An expression that evaluates to an array, whose elements to check for equality to the input field. - * @return A new {@code Expr} representing the 'IN' comparison. - */ - export function eqAny(fieldName: string, arrayExpression: Expr): BooleanExpr; - - /** - * @beta - * - * Creates an expression that checks if an expression is not equal to any of the provided values - * or expressions. - * - * ```typescript - * // Check if the 'status' field is neither "pending" nor the value of 'rejectedStatus' - * notEqAny(field("status"), ["pending", field("rejectedStatus")]); - * ``` - * - * @param element The expression to compare. - * @param values The values to check against. - * @return A new {@code Expr} representing the 'NOT IN' comparison. - */ - export function notEqAny( - element: Expr, - values: Array - ): BooleanExpr; - - /** - * @beta - * - * Creates an expression that checks if a field's value is not equal to any of the provided values - * or expressions. - * - * ```typescript - * // Check if the 'status' field is neither "pending" nor the value of 'rejectedStatus' - * notEqAny("status", [constant("pending"), field("rejectedStatus")]); - * ``` - * - * @param fieldName The field name to compare. - * @param values The values to check against. - * @return A new {@code Expr} representing the 'NOT IN' comparison. - */ - export function notEqAny( - fieldName: string, - values: Array - ): BooleanExpr; - - /** - * @beta - * - * Creates an expression that checks if an expression is not equal to any of the provided values - * or expressions. - * - * ```typescript - * // Check if the 'status' field is neither "pending" nor the value of the field 'rejectedStatus' - * notEqAny(field("status"), ["pending", field("rejectedStatus")]); - * ``` - * - * @param element The expression to compare. - * @param arrayExpression The values to check against. - * @return A new {@code Expr} representing the 'NOT IN' comparison. - */ - export function notEqAny(element: Expr, arrayExpression: Expr): BooleanExpr; - - /** - * @beta - * - * Creates an expression that checks if a field's value is not equal to any of the values in the evaluated expression. - * - * ```typescript - * // Check if the 'status' field is not equal to any value in the field 'rejectedStatuses' - * notEqAny("status", field("rejectedStatuses")); - * ``` - * - * @param fieldName The field name to compare. - * @param arrayExpression The values to check against. - * @return A new {@code Expr} representing the 'NOT IN' comparison. - */ - export function notEqAny( - fieldName: string, - arrayExpression: Expr - ): BooleanExpr; - - /** - * @beta - * - * Creates an expression that performs a logical 'XOR' (exclusive OR) operation on multiple BooleanExpressions. - * - * ```typescript - * // Check if only one of the conditions is true: 'age' greater than 18, 'city' is "London", - * // or 'status' is "active". - * const condition = xor( - * gt("age", 18), - * eq("city", "London"), - * eq("status", "active")); - * ``` - * - * @param first The first condition. - * @param second The second condition. - * @param additionalConditions Additional conditions to 'XOR' together. - * @return A new {@code Expr} representing the logical 'XOR' operation. - */ - export function xor( - first: BooleanExpr, - second: BooleanExpr, - ...additionalConditions: BooleanExpr[] - ): BooleanExpr; - - /** - * @beta - * - * Creates a conditional expression that evaluates to a 'then' expression if a condition is true - * and an 'else' expression if the condition is false. - * - * ```typescript - * // If 'age' is greater than 18, return "Adult"; otherwise, return "Minor". - * cond( - * gt("age", 18), constant("Adult"), constant("Minor")); - * ``` - * - * @param condition The condition to evaluate. - * @param thenExpr The expression to evaluate if the condition is true. - * @param elseExpr The expression to evaluate if the condition is false. - * @return A new {@code Expr} representing the conditional expression. - */ - export function cond( - condition: BooleanExpr, - thenExpr: Expr, - elseExpr: Expr - ): FunctionExpr; - - /** - * @beta - * - * Creates an expression that negates a filter condition. - * - * ```typescript - * // Find documents where the 'completed' field is NOT true - * not(eq("completed", true)); - * ``` - * - * @param booleanExpr The filter condition to negate. - * @return A new {@code Expr} representing the negated filter condition. - */ - export function not(booleanExpr: BooleanExpr): BooleanExpr; - - /** - * @beta - * - * Creates an expression that returns the largest value between multiple input - * expressions or literal values. Based on Firestore's value type ordering. - * - * ```typescript - * // Returns the largest value between the 'field1' field, the 'field2' field, - * // and 1000 - * logicalMaximum(field("field1"), field("field2"), 1000); - * ``` - * - * @param first The first operand expression. - * @param second The second expression or literal. - * @param others Optional additional expressions or literals. - * @return A new {@code Expr} representing the logical max operation. - */ - export function logicalMaximum( - first: Expr, - second: Expr | unknown, - ...others: Array - ): FunctionExpr; - - /** - * @beta - * - * Creates an expression that returns the largest value between multiple input - * expressions or literal values. Based on Firestore's value type ordering. - * - * ```typescript - * // Returns the largest value between the 'field1' field, the 'field2' field, - * // and 1000. - * logicalMaximum("field1", field("field2"), 1000); - * ``` - * - * @param fieldName The first operand field name. - * @param second The second expression or literal. - * @param others Optional additional expressions or literals. - * @return A new {@code Expr} representing the logical max operation. - */ - export function logicalMaximum( - fieldName: string, - second: Expr | unknown, - ...others: Array - ): FunctionExpr; - - /** - * @beta - * - * Creates an expression that returns the smallest value between multiple input - * expressions and literal values. Based on Firestore's value type ordering. - * - * ```typescript - * // Returns the smallest value between the 'field1' field, the 'field2' field, - * // and 1000. - * logicalMinimum(field("field1"), field("field2"), 1000); - * ``` - * - * @param first The first operand expression. - * @param second The second expression or literal. - * @param others Optional additional expressions or literals. - * @return A new {@code Expr} representing the logical min operation. - */ - export function logicalMinimum( - first: Expr, - second: Expr | unknown, - ...others: Array - ): FunctionExpr; - - /** - * @beta - * - * Creates an expression that returns the smallest value between a field's value - * and other input expressions or literal values. - * Based on Firestore's value type ordering. - * - * ```typescript - * // Returns the smallest value between the 'field1' field, the 'field2' field, - * // and 1000. - * logicalMinimum("field1", field("field2"), 1000); - * ``` - * - * @param fieldName The first operand field name. - * @param second The second expression or literal. - * @param others Optional additional expressions or literals. - * @return A new {@code Expr} representing the logical min operation. - */ - export function logicalMinimum( - fieldName: string, - second: Expr | unknown, - ...others: Array - ): FunctionExpr; - - /** - * @beta - * - * Creates an expression that checks if a field exists. - * - * ```typescript - * // Check if the document has a field named "phoneNumber" - * exists(field("phoneNumber")); - * ``` - * - * @param value An expression evaluates to the name of the field to check. - * @return A new {@code Expr} representing the 'exists' check. - */ - export function exists(value: Expr): BooleanExpr; - - /** - * @beta - * - * Creates an expression that checks if a field exists. - * - * ```typescript - * // Check if the document has a field named "phoneNumber" - * exists("phoneNumber"); - * ``` - * - * @param fieldName The field name to check. - * @return A new {@code Expr} representing the 'exists' check. - */ - export function exists(fieldName: string): BooleanExpr; - - /** - * @beta - * - * Creates an expression that checks if an expression evaluates to 'NaN' (Not a Number). - * - * ```typescript - * // Check if the result of a calculation is NaN - * isNaN(field("value").divide(0)); - * ``` - * - * @param value The expression to check. - * @return A new {@code Expr} representing the 'isNaN' check. - */ - export function isNan(value: Expr): BooleanExpr; - - /** - * @beta - * - * Creates an expression that checks if a field's value evaluates to 'NaN' (Not a Number). - * - * ```typescript - * // Check if the result of a calculation is NaN - * isNaN("value"); - * ``` - * - * @param fieldName The name of the field to check. - * @return A new {@code Expr} representing the 'isNaN' check. - */ - export function isNan(fieldName: string): BooleanExpr; - - /** - * @beta - * - * Creates an expression that reverses a string. - * - * ```typescript - * // Reverse the value of the 'myString' field. - * reverse(field("myString")); - * ``` - * - * @param stringExpression An expression evaluating to a string value, which will be reversed. - * @return A new {@code Expr} representing the reversed string. - */ - export function reverse(stringExpression: Expr): FunctionExpr; - - /** - * @beta - * - * Creates an expression that reverses a string value in the specified field. - * - * ```typescript - * // Reverse the value of the 'myString' field. - * reverse("myString"); - * ``` - * - * @param field The name of the field representing the string to reverse. - * @return A new {@code Expr} representing the reversed string. - */ - export function reverse(field: string): FunctionExpr; - - /** - * @beta - * - * Creates an expression that replaces the first occurrence of a substring within a string with another substring. - * - * ```typescript - * // Replace the first occurrence of "hello" with "hi" in the 'message' field. - * replaceFirst(field("message"), "hello", "hi"); - * ``` - * - * @param value The expression representing the string to perform the replacement on. - * @param find The substring to search for. - * @param replace The substring to replace the first occurrence of 'find' with. - * @return A new {@code Expr} representing the string with the first occurrence replaced. - */ - export function replaceFirst( - value: Expr, - find: string, - replace: string - ): FunctionExpr; - - /** - * @beta - * - * Creates an expression that replaces the first occurrence of a substring within a string with another substring, - * where the substring to find and the replacement substring are specified by expressions. - * - * ```typescript - * // Replace the first occurrence of the value in 'findField' with the value in 'replaceField' in the 'message' field. - * replaceFirst(field("message"), field("findField"), field("replaceField")); - * ``` - * - * @param value The expression representing the string to perform the replacement on. - * @param find The expression representing the substring to search for. - * @param replace The expression representing the substring to replace the first occurrence of 'find' with. - * @return A new {@code Expr} representing the string with the first occurrence replaced. - */ - export function replaceFirst( - value: Expr, - find: Expr, - replace: Expr - ): FunctionExpr; - - /** - * @beta - * - * Creates an expression that replaces the first occurrence of a substring within a string represented by a field with another substring. - * - * ```typescript - * // Replace the first occurrence of "hello" with "hi" in the 'message' field. - * replaceFirst("message", "hello", "hi"); - * ``` - * - * @param fieldName The name of the field representing the string to perform the replacement on. - * @param find The substring to search for. - * @param replace The substring to replace the first occurrence of 'find' with. - * @return A new {@code Expr} representing the string with the first occurrence replaced. - */ - export function replaceFirst( - fieldName: string, - find: string, - replace: string - ): FunctionExpr; - - /** - * @beta - * - * Creates an expression that replaces all occurrences of a substring within a string with another substring. - * - * ```typescript - * // Replace all occurrences of "hello" with "hi" in the 'message' field. - * replaceAll(field("message"), "hello", "hi"); - * ``` - * - * @param value The expression representing the string to perform the replacement on. - * @param find The substring to search for. - * @param replace The substring to replace all occurrences of 'find' with. - * @return A new {@code Expr} representing the string with all occurrences replaced. - */ - export function replaceAll( - value: Expr, - find: string, - replace: string - ): FunctionExpr; - - /** - * @beta - * - * Creates an expression that replaces all occurrences of a substring within a string with another substring, - * where the substring to find and the replacement substring are specified by expressions. - * - * ```typescript - * // Replace all occurrences of the value in 'findField' with the value in 'replaceField' in the 'message' field. - * replaceAll(field("message"), field("findField"), field("replaceField")); - * ``` - * - * @param value The expression representing the string to perform the replacement on. - * @param find The expression representing the substring to search for. - * @param replace The expression representing the substring to replace all occurrences of 'find' with. - * @return A new {@code Expr} representing the string with all occurrences replaced. - */ - export function replaceAll( - value: Expr, - find: Expr, - replace: Expr - ): FunctionExpr; + /** + * @beta + * + * Creates an expression that checks if a field's array value contains a specific value. + * + * ```typescript + * // Check if the 'colors' array contains "red" + * arrayContains("colors", "red"); + * ``` + * + * @param fieldName The field name to check. + * @param element The element to search for in the array. + * @return A new {@code Expr} representing the 'array_contains' comparison. + */ + export function arrayContains( + fieldName: string, + element: unknown + ): BooleanExpr; - /** - * @beta - * - * Creates an expression that replaces all occurrences of a substring within a string represented by a field with another substring. - * - * ```typescript - * // Replace all occurrences of "hello" with "hi" in the 'message' field. - * replaceAll("message", "hello", "hi"); - * ``` - * - * @param fieldName The name of the field representing the string to perform the replacement on. - * @param find The substring to search for. - * @param replace The substring to replace all occurrences of 'find' with. - * @return A new {@code Expr} representing the string with all occurrences replaced. - */ - export function replaceAll( - fieldName: string, - find: string, - replace: string - ): FunctionExpr; + /** + * @beta + * + * Creates an expression that checks if an array expression contains any of the specified + * elements. + * + * ```typescript + * // Check if the 'categories' array contains either values from field "cate1" or "Science" + * arrayContainsAny(field("categories"), [field("cate1"), "Science"]); + * ``` + * + * @param array The array expression to check. + * @param values The elements to check for in the array. + * @return A new {@code Expr} representing the 'array_contains_any' comparison. + */ + export function arrayContainsAny( + array: Expr, + values: Array + ): BooleanExpr; - /** - * @beta - * - * Creates an expression that calculates the byte length of a string in UTF-8, or just the length of a Blob. - * - * ```typescript - * // Calculate the length of the 'myString' field in bytes. - * byteLength(field("myString")); - * ``` - * - * @param expr The expression representing the string. - * @return A new {@code Expr} representing the length of the string in bytes. - */ - export function byteLength(expr: Expr): FunctionExpr; + /** + * @beta + * + * Creates an expression that checks if a field's array value contains any of the specified + * elements. + * + * ```typescript + * // Check if the 'groups' array contains either the value from the 'userGroup' field + * // or the value "guest" + * arrayContainsAny("categories", [field("cate1"), "Science"]); + * ``` + * + * @param fieldName The field name to check. + * @param values The elements to check for in the array. + * @return A new {@code Expr} representing the 'array_contains_any' comparison. + */ + export function arrayContainsAny( + fieldName: string, + values: Array + ): BooleanExpr; - /** - * @beta - * - * Creates an expression that calculates the length of a string represented by a field in UTF-8 bytes, or just the length of a Blob. - * - * ```typescript - * // Calculate the length of the 'myString' field in bytes. - * byteLength("myString"); - * ``` - * - * @param fieldName The name of the field containing the string. - * @return A new {@code Expr} representing the length of the string in bytes. - */ - export function byteLength(fieldName: string): FunctionExpr; + /** + * @beta + * + * Creates an expression that checks if an array expression contains any of the specified + * elements. + * + * ```typescript + * // Check if the 'categories' array contains either values from field "cate1" or "Science" + * arrayContainsAny(field("categories"), array([field("cate1"), "Science"])); + * ``` + * + * @param array The array expression to check. + * @param values An expression that evaluates to an array, whose elements to check for in the array. + * @return A new {@code Expr} representing the 'array_contains_any' comparison. + */ + export function arrayContainsAny(array: Expr, values: Expr): BooleanExpr; - /** - * @beta - * - * Creates an expression that calculates the character length of a string field in UTF8. - * - * ```typescript - * // Get the character length of the 'name' field in UTF-8. - * strLength("name"); - * ``` - * - * @param fieldName The name of the field containing the string. - * @return A new {@code Expr} representing the length of the string. - */ - export function charLength(fieldName: string): FunctionExpr; + /** + * @beta + * + * Creates an expression that checks if a field's array value contains any of the specified + * elements. + * + * ```typescript + * // Check if the 'groups' array contains either the value from the 'userGroup' field + * // or the value "guest" + * arrayContainsAny("categories", array([field("cate1"), "Science"])); + * ``` + * + * @param fieldName The field name to check. + * @param values An expression that evaluates to an array, whose elements to check for in the array field. + * @return A new {@code Expr} representing the 'array_contains_any' comparison. + */ + export function arrayContainsAny( + fieldName: string, + values: Expr + ): BooleanExpr; - /** - * @beta - * - * Creates an expression that calculates the character length of a string expression in UTF-8. - * - * ```typescript - * // Get the character length of the 'name' field in UTF-8. - * strLength(field("name")); - * ``` - * - * @param stringExpression The expression representing the string to calculate the length of. - * @return A new {@code Expr} representing the length of the string. - */ - export function charLength(stringExpression: Expr): FunctionExpr; + /** + * @beta + * + * Creates an expression that checks if an array expression contains all the specified elements. + * + * ```typescript + * // Check if the "tags" array contains all of the values: "SciFi", "Adventure", and the value from field "tag1" + * arrayContainsAll(field("tags"), [field("tag1"), constant("SciFi"), "Adventure"]); + * ``` + * + * @param array The array expression to check. + * @param values The elements to check for in the array. + * @return A new {@code Expr} representing the 'array_contains_all' comparison. + */ + export function arrayContainsAll( + array: Expr, + values: Array + ): BooleanExpr; - /** - * @beta - * - * Creates an expression that performs a case-sensitive wildcard string comparison against a - * field. - * - * ```typescript - * // Check if the 'title' field contains the string "guide" - * like("title", "%guide%"); - * ``` - * - * @param fieldName The name of the field containing the string. - * @param pattern The pattern to search for. You can use "%" as a wildcard character. - * @return A new {@code Expr} representing the 'like' comparison. - */ - export function like(fieldName: string, pattern: string): BooleanExpr; + /** + * @beta + * + * Creates an expression that checks if a field's array value contains all the specified values or + * expressions. + * + * ```typescript + * // Check if the 'tags' array contains both of the values from field 'tag1', the value "SciFi", and "Adventure" + * arrayContainsAll("tags", [field("tag1"), "SciFi", "Adventure"]); + * ``` + * + * @param fieldName The field name to check. + * @param values The elements to check for in the array. + * @return A new {@code Expr} representing the 'array_contains_all' comparison. + */ + export function arrayContainsAll( + fieldName: string, + values: Array + ): BooleanExpr; - /** - * @beta - * - * Creates an expression that performs a case-sensitive wildcard string comparison against a - * field. - * - * ```typescript - * // Check if the 'title' field contains the string "guide" - * like("title", field("pattern")); - * ``` - * - * @param fieldName The name of the field containing the string. - * @param pattern The pattern to search for. You can use "%" as a wildcard character. - * @return A new {@code Expr} representing the 'like' comparison. - */ - export function like(fieldName: string, pattern: Expr): BooleanExpr; + /** + * @beta + * + * Creates an expression that checks if an array expression contains all the specified elements. + * + * ```typescript + * // Check if the "tags" array contains all of the values: "SciFi", "Adventure", and the value from field "tag1" + * arrayContainsAll(field("tags"), [field("tag1"), constant("SciFi"), "Adventure"]); + * ``` + * + * @param array The array expression to check. + * @param arrayExpression The elements to check for in the array. + * @return A new {@code Expr} representing the 'array_contains_all' comparison. + */ + export function arrayContainsAll( + array: Expr, + arrayExpression: Expr + ): BooleanExpr; - /** - * @beta - * - * Creates an expression that performs a case-sensitive wildcard string comparison. - * - * ```typescript - * // Check if the 'title' field contains the string "guide" - * like(field("title"), "%guide%"); - * ``` - * - * @param stringExpression The expression representing the string to perform the comparison on. - * @param pattern The pattern to search for. You can use "%" as a wildcard character. - * @return A new {@code Expr} representing the 'like' comparison. - */ - export function like(stringExpression: Expr, pattern: string): BooleanExpr; + /** + * @beta + * + * Creates an expression that checks if a field's array value contains all the specified values or + * expressions. + * + * ```typescript + * // Check if the 'tags' array contains both of the values from field 'tag1', the value "SciFi", and "Adventure" + * arrayContainsAll("tags", [field("tag1"), "SciFi", "Adventure"]); + * ``` + * + * @param fieldName The field name to check. + * @param arrayExpression The elements to check for in the array. + * @return A new {@code Expr} representing the 'array_contains_all' comparison. + */ + export function arrayContainsAll( + fieldName: string, + arrayExpression: Expr + ): BooleanExpr; - /** - * @beta - * - * Creates an expression that performs a case-sensitive wildcard string comparison. - * - * ```typescript - * // Check if the 'title' field contains the string "guide" - * like(field("title"), field("pattern")); - * ``` - * - * @param stringExpression The expression representing the string to perform the comparison on. - * @param pattern The pattern to search for. You can use "%" as a wildcard character. - * @return A new {@code Expr} representing the 'like' comparison. - */ - export function like(stringExpression: Expr, pattern: Expr): BooleanExpr; + /** + * @beta + * + * Creates an expression that calculates the length of an array in a specified field. + * + * ```typescript + * // Get the number of items in field 'cart' + * arrayLength('cart'); + * ``` + * + * @param fieldName The name of the field containing an array to calculate the length of. + * @return A new {@code Expr} representing the length of the array. + */ + export function arrayLength(fieldName: string): FunctionExpr; - /** - * @beta - * - * Creates an expression that checks if a string field contains a specified regular expression as - * a substring. - * - * ```typescript - * // Check if the 'description' field contains "example" (case-insensitive) - * regexContains("description", "(?i)example"); - * ``` - * - * @param fieldName The name of the field containing the string. - * @param pattern The regular expression to use for the search. - * @return A new {@code Expr} representing the 'contains' comparison. - */ - export function regexContains( - fieldName: string, - pattern: string - ): BooleanExpr; + /** + * @beta + * + * Creates an expression that calculates the length of an array expression. + * + * ```typescript + * // Get the number of items in the 'cart' array + * arrayLength(field("cart")); + * ``` + * + * @param array The array expression to calculate the length of. + * @return A new {@code Expr} representing the length of the array. + */ + export function arrayLength(array: Expr): FunctionExpr; - /** - * @beta - * - * Creates an expression that checks if a string field contains a specified regular expression as - * a substring. - * - * ```typescript - * // Check if the 'description' field contains "example" (case-insensitive) - * regexContains("description", field("pattern")); - * ``` - * - * @param fieldName The name of the field containing the string. - * @param pattern The regular expression to use for the search. - * @return A new {@code Expr} representing the 'contains' comparison. - */ - export function regexContains(fieldName: string, pattern: Expr): BooleanExpr; + /** + * @beta + * + * Creates an expression that checks if an expression, when evaluated, is equal to any of the provided values or + * expressions. + * + * ```typescript + * // Check if the 'category' field is either "Electronics" or value of field 'primaryType' + * eqAny(field("category"), [constant("Electronics"), field("primaryType")]); + * ``` + * + * @param expression The expression whose results to compare. + * @param values The values to check against. + * @return A new {@code Expr} representing the 'IN' comparison. + */ + export function eqAny( + expression: Expr, + values: Array + ): BooleanExpr; - /** - * @beta - * - * Creates an expression that checks if a string expression contains a specified regular - * expression as a substring. - * - * ```typescript - * // Check if the 'description' field contains "example" (case-insensitive) - * regexContains(field("description"), "(?i)example"); - * ``` - * - * @param stringExpression The expression representing the string to perform the comparison on. - * @param pattern The regular expression to use for the search. - * @return A new {@code Expr} representing the 'contains' comparison. - */ - export function regexContains( - stringExpression: Expr, - pattern: string - ): BooleanExpr; + /** + * @beta + * + * Creates an expression that checks if an expression is equal to any of the provided values. + * + * ```typescript + * // Check if the 'category' field is set to a value in the disabledCategories field + * eqAny(field("category"), field('disabledCategories')); + * ``` + * + * @param expression The expression whose results to compare. + * @param arrayExpression An expression that evaluates to an array, whose elements to check for equality to the input. + * @return A new {@code Expr} representing the 'IN' comparison. + */ + export function eqAny(expression: Expr, arrayExpression: Expr): BooleanExpr; - /** - * @beta - * - * Creates an expression that checks if a string expression contains a specified regular - * expression as a substring. - * - * ```typescript - * // Check if the 'description' field contains "example" (case-insensitive) - * regexContains(field("description"), field("pattern")); - * ``` - * - * @param stringExpression The expression representing the string to perform the comparison on. - * @param pattern The regular expression to use for the search. - * @return A new {@code Expr} representing the 'contains' comparison. - */ - export function regexContains( - stringExpression: Expr, - pattern: Expr - ): BooleanExpr; + /** + * @beta + * + * Creates an expression that checks if a field's value is equal to any of the provided values or + * expressions. + * + * ```typescript + * // Check if the 'category' field is either "Electronics" or value of field 'primaryType' + * eqAny("category", [constant("Electronics"), field("primaryType")]); + * ``` + * + * @param fieldName The field to compare. + * @param values The values to check against. + * @return A new {@code Expr} representing the 'IN' comparison. + */ + export function eqAny( + fieldName: string, + values: Array + ): BooleanExpr; - /** - * @beta - * - * Creates an expression that checks if a string field matches a specified regular expression. - * - * ```typescript - * // Check if the 'email' field matches a valid email pattern - * regexMatch("email", "[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,}"); - * ``` - * - * @param fieldName The name of the field containing the string. - * @param pattern The regular expression to use for the match. - * @return A new {@code Expr} representing the regular expression match. - */ - export function regexMatch(fieldName: string, pattern: string): BooleanExpr; + /** + * @beta + * + * Creates an expression that checks if a field's value is equal to any of the provided values or + * expressions. + * + * ```typescript + * // Check if the 'category' field is either "Electronics" or value of field 'primaryType' + * eqAny("category", ["Electronics", field("primaryType")]); + * ``` + * + * @param fieldName The field to compare. + * @param arrayExpression An expression that evaluates to an array, whose elements to check for equality to the input field. + * @return A new {@code Expr} representing the 'IN' comparison. + */ + export function eqAny( + fieldName: string, + arrayExpression: Expr + ): BooleanExpr; - /** - * @beta - * - * Creates an expression that checks if a string field matches a specified regular expression. - * - * ```typescript - * // Check if the 'email' field matches a valid email pattern - * regexMatch("email", field("pattern")); - * ``` - * - * @param fieldName The name of the field containing the string. - * @param pattern The regular expression to use for the match. - * @return A new {@code Expr} representing the regular expression match. - */ - export function regexMatch(fieldName: string, pattern: Expr): BooleanExpr; + /** + * @beta + * + * Creates an expression that checks if an expression is not equal to any of the provided values + * or expressions. + * + * ```typescript + * // Check if the 'status' field is neither "pending" nor the value of 'rejectedStatus' + * notEqAny(field("status"), ["pending", field("rejectedStatus")]); + * ``` + * + * @param element The expression to compare. + * @param values The values to check against. + * @return A new {@code Expr} representing the 'NOT IN' comparison. + */ + export function notEqAny( + element: Expr, + values: Array + ): BooleanExpr; - /** - * @beta - * - * Creates an expression that checks if a string expression matches a specified regular - * expression. - * - * ```typescript - * // Check if the 'email' field matches a valid email pattern - * regexMatch(field("email"), "[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,}"); - * ``` - * - * @param stringExpression The expression representing the string to match against. - * @param pattern The regular expression to use for the match. - * @return A new {@code Expr} representing the regular expression match. - */ - export function regexMatch( - stringExpression: Expr, - pattern: string - ): BooleanExpr; + /** + * @beta + * + * Creates an expression that checks if a field's value is not equal to any of the provided values + * or expressions. + * + * ```typescript + * // Check if the 'status' field is neither "pending" nor the value of 'rejectedStatus' + * notEqAny("status", [constant("pending"), field("rejectedStatus")]); + * ``` + * + * @param fieldName The field name to compare. + * @param values The values to check against. + * @return A new {@code Expr} representing the 'NOT IN' comparison. + */ + export function notEqAny( + fieldName: string, + values: Array + ): BooleanExpr; - /** - * @beta - * - * Creates an expression that checks if a string expression matches a specified regular - * expression. - * - * ```typescript - * // Check if the 'email' field matches a valid email pattern - * regexMatch(field("email"), field("pattern")); - * ``` - * - * @param stringExpression The expression representing the string to match against. - * @param pattern The regular expression to use for the match. - * @return A new {@code Expr} representing the regular expression match. - */ - export function regexMatch( - stringExpression: Expr, - pattern: Expr - ): BooleanExpr; + /** + * @beta + * + * Creates an expression that checks if an expression is not equal to any of the provided values + * or expressions. + * + * ```typescript + * // Check if the 'status' field is neither "pending" nor the value of the field 'rejectedStatus' + * notEqAny(field("status"), ["pending", field("rejectedStatus")]); + * ``` + * + * @param element The expression to compare. + * @param arrayExpression The values to check against. + * @return A new {@code Expr} representing the 'NOT IN' comparison. + */ + export function notEqAny(element: Expr, arrayExpression: Expr): BooleanExpr; - /** - * @beta - * - * Creates an expression that checks if a string field contains a specified substring. - * - * ```typescript - * // Check if the 'description' field contains "example". - * strContains("description", "example"); - * ``` - * - * @param fieldName The name of the field containing the string. - * @param substring The substring to search for. - * @return A new {@code Expr} representing the 'contains' comparison. - */ - export function strContains( - fieldName: string, - substring: string - ): BooleanExpr; + /** + * @beta + * + * Creates an expression that checks if a field's value is not equal to any of the values in the evaluated expression. + * + * ```typescript + * // Check if the 'status' field is not equal to any value in the field 'rejectedStatuses' + * notEqAny("status", field("rejectedStatuses")); + * ``` + * + * @param fieldName The field name to compare. + * @param arrayExpression The values to check against. + * @return A new {@code Expr} representing the 'NOT IN' comparison. + */ + export function notEqAny( + fieldName: string, + arrayExpression: Expr + ): BooleanExpr; - /** - * @beta - * - * Creates an expression that checks if a string field contains a substring specified by an expression. - * - * ```typescript - * // Check if the 'description' field contains the value of the 'keyword' field. - * strContains("description", field("keyword")); - * ``` - * - * @param fieldName The name of the field containing the string. - * @param substring The expression representing the substring to search for. - * @return A new {@code Expr} representing the 'contains' comparison. - */ - export function strContains(fieldName: string, substring: Expr): BooleanExpr; + /** + * @beta + * + * Creates an expression that performs a logical 'XOR' (exclusive OR) operation on multiple BooleanExpressions. + * + * ```typescript + * // Check if only one of the conditions is true: 'age' greater than 18, 'city' is "London", + * // or 'status' is "active". + * const condition = xor( + * gt("age", 18), + * eq("city", "London"), + * eq("status", "active")); + * ``` + * + * @param first The first condition. + * @param second The second condition. + * @param additionalConditions Additional conditions to 'XOR' together. + * @return A new {@code Expr} representing the logical 'XOR' operation. + */ + export function xor( + first: BooleanExpr, + second: BooleanExpr, + ...additionalConditions: BooleanExpr[] + ): BooleanExpr; - /** - * @beta - * - * Creates an expression that checks if a string expression contains a specified substring. - * - * ```typescript - * // Check if the 'description' field contains "example". - * strContains(field("description"), "example"); - * ``` - * - * @param stringExpression The expression representing the string to perform the comparison on. - * @param substring The substring to search for. - * @return A new {@code Expr} representing the 'contains' comparison. - */ - export function strContains( - stringExpression: Expr, - substring: string - ): BooleanExpr; + /** + * @beta + * + * Creates a conditional expression that evaluates to a 'then' expression if a condition is true + * and an 'else' expression if the condition is false. + * + * ```typescript + * // If 'age' is greater than 18, return "Adult"; otherwise, return "Minor". + * cond( + * gt("age", 18), constant("Adult"), constant("Minor")); + * ``` + * + * @param condition The condition to evaluate. + * @param thenExpr The expression to evaluate if the condition is true. + * @param elseExpr The expression to evaluate if the condition is false. + * @return A new {@code Expr} representing the conditional expression. + */ + export function cond( + condition: BooleanExpr, + thenExpr: Expr, + elseExpr: Expr + ): FunctionExpr; - /** - * @beta - * - * Creates an expression that checks if a string expression contains a substring specified by another expression. - * - * ```typescript - * // Check if the 'description' field contains the value of the 'keyword' field. - * strContains(field("description"), field("keyword")); - * ``` - * - * @param stringExpression The expression representing the string to perform the comparison on. - * @param substring The expression representing the substring to search for. - * @return A new {@code Expr} representing the 'contains' comparison. - */ - export function strContains( - stringExpression: Expr, - substring: Expr - ): BooleanExpr; + /** + * @beta + * + * Creates an expression that negates a filter condition. + * + * ```typescript + * // Find documents where the 'completed' field is NOT true + * not(eq("completed", true)); + * ``` + * + * @param booleanExpr The filter condition to negate. + * @return A new {@code Expr} representing the negated filter condition. + */ + export function not(booleanExpr: BooleanExpr): BooleanExpr; - /** - * @beta - * - * Creates an expression that checks if a field's value starts with a given prefix. - * - * ```typescript - * // Check if the 'name' field starts with "Mr." - * startsWith("name", "Mr."); - * ``` - * - * @param fieldName The field name to check. - * @param prefix The prefix to check for. - * @return A new {@code Expr} representing the 'starts with' comparison. - */ - export function startsWith(fieldName: string, prefix: string): BooleanExpr; + /** + * @beta + * + * Creates an expression that returns the largest value between multiple input + * expressions or literal values. Based on Firestore's value type ordering. + * + * ```typescript + * // Returns the largest value between the 'field1' field, the 'field2' field, + * // and 1000 + * logicalMaximum(field("field1"), field("field2"), 1000); + * ``` + * + * @param first The first operand expression. + * @param second The second expression or literal. + * @param others Optional additional expressions or literals. + * @return A new {@code Expr} representing the logical max operation. + */ + export function logicalMaximum( + first: Expr, + second: Expr | unknown, + ...others: Array + ): FunctionExpr; - /** - * @beta - * - * Creates an expression that checks if a field's value starts with a given prefix. - * - * ```typescript - * // Check if the 'fullName' field starts with the value of the 'firstName' field - * startsWith("fullName", field("firstName")); - * ``` - * - * @param fieldName The field name to check. - * @param prefix The expression representing the prefix. - * @return A new {@code Expr} representing the 'starts with' comparison. - */ - export function startsWith(fieldName: string, prefix: Expr): BooleanExpr; + /** + * @beta + * + * Creates an expression that returns the largest value between multiple input + * expressions or literal values. Based on Firestore's value type ordering. + * + * ```typescript + * // Returns the largest value between the 'field1' field, the 'field2' field, + * // and 1000. + * logicalMaximum("field1", field("field2"), 1000); + * ``` + * + * @param fieldName The first operand field name. + * @param second The second expression or literal. + * @param others Optional additional expressions or literals. + * @return A new {@code Expr} representing the logical max operation. + */ + export function logicalMaximum( + fieldName: string, + second: Expr | unknown, + ...others: Array + ): FunctionExpr; - /** - * @beta - * - * Creates an expression that checks if a string expression starts with a given prefix. - * - * ```typescript - * // Check if the result of concatenating 'firstName' and 'lastName' fields starts with "Mr." - * startsWith(field("fullName"), "Mr."); - * ``` - * - * @param stringExpression The expression to check. - * @param prefix The prefix to check for. - * @return A new {@code Expr} representing the 'starts with' comparison. - */ - export function startsWith( - stringExpression: Expr, - prefix: string - ): BooleanExpr; + /** + * @beta + * + * Creates an expression that returns the smallest value between multiple input + * expressions and literal values. Based on Firestore's value type ordering. + * + * ```typescript + * // Returns the smallest value between the 'field1' field, the 'field2' field, + * // and 1000. + * logicalMinimum(field("field1"), field("field2"), 1000); + * ``` + * + * @param first The first operand expression. + * @param second The second expression or literal. + * @param others Optional additional expressions or literals. + * @return A new {@code Expr} representing the logical min operation. + */ + export function logicalMinimum( + first: Expr, + second: Expr | unknown, + ...others: Array + ): FunctionExpr; - /** - * @beta - * - * Creates an expression that checks if a string expression starts with a given prefix. - * - * ```typescript - * // Check if the result of concatenating 'firstName' and 'lastName' fields starts with "Mr." - * startsWith(field("fullName"), field("prefix")); - * ``` - * - * @param stringExpression The expression to check. - * @param prefix The prefix to check for. - * @return A new {@code Expr} representing the 'starts with' comparison. - */ - export function startsWith(stringExpression: Expr, prefix: Expr): BooleanExpr; + /** + * @beta + * + * Creates an expression that returns the smallest value between a field's value + * and other input expressions or literal values. + * Based on Firestore's value type ordering. + * + * ```typescript + * // Returns the smallest value between the 'field1' field, the 'field2' field, + * // and 1000. + * logicalMinimum("field1", field("field2"), 1000); + * ``` + * + * @param fieldName The first operand field name. + * @param second The second expression or literal. + * @param others Optional additional expressions or literals. + * @return A new {@code Expr} representing the logical min operation. + */ + export function logicalMinimum( + fieldName: string, + second: Expr | unknown, + ...others: Array + ): FunctionExpr; - /** - * @beta - * - * Creates an expression that checks if a field's value ends with a given postfix. - * - * ```typescript - * // Check if the 'filename' field ends with ".txt" - * endsWith("filename", ".txt"); - * ``` - * - * @param fieldName The field name to check. - * @param suffix The postfix to check for. - * @return A new {@code Expr} representing the 'ends with' comparison. - */ - export function endsWith(fieldName: string, suffix: string): BooleanExpr; + /** + * @beta + * + * Creates an expression that checks if a field exists. + * + * ```typescript + * // Check if the document has a field named "phoneNumber" + * exists(field("phoneNumber")); + * ``` + * + * @param value An expression evaluates to the name of the field to check. + * @return A new {@code Expr} representing the 'exists' check. + */ + export function exists(value: Expr): BooleanExpr; - /** - * @beta - * - * Creates an expression that checks if a field's value ends with a given postfix. - * - * ```typescript - * // Check if the 'url' field ends with the value of the 'extension' field - * endsWith("url", field("extension")); - * ``` - * - * @param fieldName The field name to check. - * @param suffix The expression representing the postfix. - * @return A new {@code Expr} representing the 'ends with' comparison. - */ - export function endsWith(fieldName: string, suffix: Expr): BooleanExpr; + /** + * @beta + * + * Creates an expression that checks if a field exists. + * + * ```typescript + * // Check if the document has a field named "phoneNumber" + * exists("phoneNumber"); + * ``` + * + * @param fieldName The field name to check. + * @return A new {@code Expr} representing the 'exists' check. + */ + export function exists(fieldName: string): BooleanExpr; - /** - * @beta - * - * Creates an expression that checks if a string expression ends with a given postfix. - * - * ```typescript - * // Check if the result of concatenating 'firstName' and 'lastName' fields ends with "Jr." - * endsWith(field("fullName"), "Jr."); - * ``` - * - * @param stringExpression The expression to check. - * @param suffix The postfix to check for. - * @return A new {@code Expr} representing the 'ends with' comparison. - */ - export function endsWith(stringExpression: Expr, suffix: string): BooleanExpr; + /** + * @beta + * + * Creates an expression that checks if an expression evaluates to 'NaN' (Not a Number). + * + * ```typescript + * // Check if the result of a calculation is NaN + * isNaN(field("value").divide(0)); + * ``` + * + * @param value The expression to check. + * @return A new {@code Expr} representing the 'isNaN' check. + */ + export function isNan(value: Expr): BooleanExpr; - /** - * @beta - * - * Creates an expression that checks if a string expression ends with a given postfix. - * - * ```typescript - * // Check if the result of concatenating 'firstName' and 'lastName' fields ends with "Jr." - * endsWith(field("fullName"), constant("Jr.")); - * ``` - * - * @param stringExpression The expression to check. - * @param suffix The postfix to check for. - * @return A new {@code Expr} representing the 'ends with' comparison. - */ - export function endsWith(stringExpression: Expr, suffix: Expr): BooleanExpr; + /** + * @beta + * + * Creates an expression that checks if a field's value evaluates to 'NaN' (Not a Number). + * + * ```typescript + * // Check if the result of a calculation is NaN + * isNaN("value"); + * ``` + * + * @param fieldName The name of the field to check. + * @return A new {@code Expr} representing the 'isNaN' check. + */ + export function isNan(fieldName: string): BooleanExpr; - /** - * @beta - * - * Creates an expression that converts a string field to lowercase. - * - * ```typescript - * // Convert the 'name' field to lowercase - * toLower("name"); - * ``` - * - * @param fieldName The name of the field containing the string. - * @return A new {@code Expr} representing the lowercase string. - */ - export function toLower(fieldName: string): FunctionExpr; + /** + * @beta + * + * Creates an expression that reverses a string. + * + * ```typescript + * // Reverse the value of the 'myString' field. + * reverse(field("myString")); + * ``` + * + * @param stringExpression An expression evaluating to a string value, which will be reversed. + * @return A new {@code Expr} representing the reversed string. + */ + export function reverse(stringExpression: Expr): FunctionExpr; - /** - * @beta - * - * Creates an expression that converts a string expression to lowercase. - * - * ```typescript - * // Convert the 'name' field to lowercase - * toLower(field("name")); - * ``` - * - * @param stringExpression The expression representing the string to convert to lowercase. - * @return A new {@code Expr} representing the lowercase string. - */ - export function toLower(stringExpression: Expr): FunctionExpr; + /** + * @beta + * + * Creates an expression that reverses a string value in the specified field. + * + * ```typescript + * // Reverse the value of the 'myString' field. + * reverse("myString"); + * ``` + * + * @param field The name of the field representing the string to reverse. + * @return A new {@code Expr} representing the reversed string. + */ + export function reverse(field: string): FunctionExpr; - /** - * @beta - * - * Creates an expression that converts a string field to uppercase. - * - * ```typescript - * // Convert the 'title' field to uppercase - * toUpper("title"); - * ``` - * - * @param fieldName The name of the field containing the string. - * @return A new {@code Expr} representing the uppercase string. - */ - export function toUpper(fieldName: string): FunctionExpr; + /** + * @beta + * + * Creates an expression that replaces the first occurrence of a substring within a string with another substring. + * + * ```typescript + * // Replace the first occurrence of "hello" with "hi" in the 'message' field. + * replaceFirst(field("message"), "hello", "hi"); + * ``` + * + * @param value The expression representing the string to perform the replacement on. + * @param find The substring to search for. + * @param replace The substring to replace the first occurrence of 'find' with. + * @return A new {@code Expr} representing the string with the first occurrence replaced. + */ + export function replaceFirst( + value: Expr, + find: string, + replace: string + ): FunctionExpr; - /** - * @beta - * - * Creates an expression that converts a string expression to uppercase. - * - * ```typescript - * // Convert the 'title' field to uppercase - * toUppercase(field("title")); - * ``` - * - * @param stringExpression The expression representing the string to convert to uppercase. - * @return A new {@code Expr} representing the uppercase string. - */ - export function toUpper(stringExpression: Expr): FunctionExpr; + /** + * @beta + * + * Creates an expression that replaces the first occurrence of a substring within a string with another substring, + * where the substring to find and the replacement substring are specified by expressions. + * + * ```typescript + * // Replace the first occurrence of the value in 'findField' with the value in 'replaceField' in the 'message' field. + * replaceFirst(field("message"), field("findField"), field("replaceField")); + * ``` + * + * @param value The expression representing the string to perform the replacement on. + * @param find The expression representing the substring to search for. + * @param replace The expression representing the substring to replace the first occurrence of 'find' with. + * @return A new {@code Expr} representing the string with the first occurrence replaced. + */ + export function replaceFirst( + value: Expr, + find: Expr, + replace: Expr + ): FunctionExpr; - /** - * @beta - * - * Creates an expression that removes leading and trailing whitespace from a string field. - * - * ```typescript - * // Trim whitespace from the 'userInput' field - * trim("userInput"); - * ``` - * - * @param fieldName The name of the field containing the string. - * @return A new {@code Expr} representing the trimmed string. - */ - export function trim(fieldName: string): FunctionExpr; + /** + * @beta + * + * Creates an expression that replaces the first occurrence of a substring within a string represented by a field with another substring. + * + * ```typescript + * // Replace the first occurrence of "hello" with "hi" in the 'message' field. + * replaceFirst("message", "hello", "hi"); + * ``` + * + * @param fieldName The name of the field representing the string to perform the replacement on. + * @param find The substring to search for. + * @param replace The substring to replace the first occurrence of 'find' with. + * @return A new {@code Expr} representing the string with the first occurrence replaced. + */ + export function replaceFirst( + fieldName: string, + find: string, + replace: string + ): FunctionExpr; - /** - * @beta - * - * Creates an expression that removes leading and trailing whitespace from a string expression. - * - * ```typescript - * // Trim whitespace from the 'userInput' field - * trim(field("userInput")); - * ``` - * - * @param stringExpression The expression representing the string to trim. - * @return A new {@code Expr} representing the trimmed string. - */ - export function trim(stringExpression: Expr): FunctionExpr; + /** + * @beta + * + * Creates an expression that replaces all occurrences of a substring within a string with another substring. + * + * ```typescript + * // Replace all occurrences of "hello" with "hi" in the 'message' field. + * replaceAll(field("message"), "hello", "hi"); + * ``` + * + * @param value The expression representing the string to perform the replacement on. + * @param find The substring to search for. + * @param replace The substring to replace all occurrences of 'find' with. + * @return A new {@code Expr} representing the string with all occurrences replaced. + */ + export function replaceAll( + value: Expr, + find: string, + replace: string + ): FunctionExpr; - /** - * @beta - * - * Creates an expression that concatenates string functions, fields or constants together. - * - * ```typescript - * // Combine the 'firstName', " ", and 'lastName' fields into a single string - * strConcat("firstName", " ", field("lastName")); - * ``` - * - * @param fieldName The field name containing the initial string value. - * @param secondString An expression or string literal to concatenate. - * @param otherStrings Optional additional expressions or literals (typically strings) to concatenate. - * @return A new {@code Expr} representing the concatenated string. - */ - export function strConcat( - fieldName: string, - secondString: Expr | string, - ...otherStrings: Array - ): FunctionExpr; + /** + * @beta + * + * Creates an expression that replaces all occurrences of a substring within a string with another substring, + * where the substring to find and the replacement substring are specified by expressions. + * + * ```typescript + * // Replace all occurrences of the value in 'findField' with the value in 'replaceField' in the 'message' field. + * replaceAll(field("message"), field("findField"), field("replaceField")); + * ``` + * + * @param value The expression representing the string to perform the replacement on. + * @param find The expression representing the substring to search for. + * @param replace The expression representing the substring to replace all occurrences of 'find' with. + * @return A new {@code Expr} representing the string with all occurrences replaced. + */ + export function replaceAll( + value: Expr, + find: Expr, + replace: Expr + ): FunctionExpr; - /** - * @beta - * Creates an expression that concatenates string expressions together. - * - * ```typescript - * // Combine the 'firstName', " ", and 'lastName' fields into a single string - * strConcat(field("firstName"), " ", field("lastName")); - * ``` - * - * @param firstString The initial string expression to concatenate to. - * @param secondString An expression or string literal to concatenate. - * @param otherStrings Optional additional expressions or literals (typically strings) to concatenate. - * @return A new {@code Expr} representing the concatenated string. - */ - export function strConcat( - firstString: Expr, - secondString: Expr | string, - ...otherStrings: Array - ): FunctionExpr; + /** + * @beta + * + * Creates an expression that replaces all occurrences of a substring within a string represented by a field with another substring. + * + * ```typescript + * // Replace all occurrences of "hello" with "hi" in the 'message' field. + * replaceAll("message", "hello", "hi"); + * ``` + * + * @param fieldName The name of the field representing the string to perform the replacement on. + * @param find The substring to search for. + * @param replace The substring to replace all occurrences of 'find' with. + * @return A new {@code Expr} representing the string with all occurrences replaced. + */ + export function replaceAll( + fieldName: string, + find: string, + replace: string + ): FunctionExpr; - /** - * @beta - * - * Accesses a value from a map (object) field using the provided key. - * - * ```typescript - * // Get the 'city' value from the 'address' map field - * mapGet("address", "city"); - * ``` - * - * @param fieldName The field name of the map field. - * @param subField The key to access in the map. - * @return A new {@code Expr} representing the value associated with the given key in the map. - */ - export function mapGet(fieldName: string, subField: string): FunctionExpr; + /** + * @beta + * + * Creates an expression that calculates the byte length of a string in UTF-8, or just the length of a Blob. + * + * ```typescript + * // Calculate the length of the 'myString' field in bytes. + * byteLength(field("myString")); + * ``` + * + * @param expr The expression representing the string. + * @return A new {@code Expr} representing the length of the string in bytes. + */ + export function byteLength(expr: Expr): FunctionExpr; - /** - * @beta - * - * Accesses a value from a map (object) expression using the provided key. - * - * ```typescript - * // Get the 'city' value from the 'address' map field - * mapGet(field("address"), "city"); - * ``` - * - * @param mapExpression The expression representing the map. - * @param subField The key to access in the map. - * @return A new {@code Expr} representing the value associated with the given key in the map. - */ - export function mapGet(mapExpression: Expr, subField: string): FunctionExpr; + /** + * @beta + * + * Creates an expression that calculates the length of a string represented by a field in UTF-8 bytes, or just the length of a Blob. + * + * ```typescript + * // Calculate the length of the 'myString' field in bytes. + * byteLength("myString"); + * ``` + * + * @param fieldName The name of the field containing the string. + * @return A new {@code Expr} representing the length of the string in bytes. + */ + export function byteLength(fieldName: string): FunctionExpr; - /** - * @beta - * - * Creates an aggregation that counts the total number of stage inputs. - * - * ```typescript - * // Count the total number of input documents - * countAll().as("totalDocument"); - * ``` - * - * @return A new {@code AggregateFunction} representing the 'countAll' aggregation. - */ - export function countAll(): AggregateFunction; + /** + * @beta + * + * Creates an expression that calculates the character length of a string field in UTF8. + * + * ```typescript + * // Get the character length of the 'name' field in UTF-8. + * strLength("name"); + * ``` + * + * @param fieldName The name of the field containing the string. + * @return A new {@code Expr} representing the length of the string. + */ + export function charLength(fieldName: string): FunctionExpr; - /** - * @beta - * - * Creates an aggregation that counts the number of stage inputs with valid evaluations of the - * provided expression. - * - * ```typescript - * // Count the number of items where the price is greater than 10 - * count(field("price").gt(10)).as("expensiveItemCount"); - * ``` - * - * @param expression The expression to count. - * @return A new {@code AggregateFunction} representing the 'count' aggregation. - */ - export function count(expression: Expr): AggregateFunction; + /** + * @beta + * + * Creates an expression that calculates the character length of a string expression in UTF-8. + * + * ```typescript + * // Get the character length of the 'name' field in UTF-8. + * strLength(field("name")); + * ``` + * + * @param stringExpression The expression representing the string to calculate the length of. + * @return A new {@code Expr} representing the length of the string. + */ + export function charLength(stringExpression: Expr): FunctionExpr; - /** - * Creates an aggregation that counts the number of stage inputs where the input field exists. - * - * ```typescript - * // Count the total number of products - * count("productId").as("totalProducts"); - * ``` - * - * @param fieldName The name of the field to count. - * @return A new {@code AggregateFunction} representing the 'count' aggregation. - */ - export function count(fieldName: string): AggregateFunction; + /** + * @beta + * + * Creates an expression that performs a case-sensitive wildcard string comparison against a + * field. + * + * ```typescript + * // Check if the 'title' field contains the string "guide" + * like("title", "%guide%"); + * ``` + * + * @param fieldName The name of the field containing the string. + * @param pattern The pattern to search for. You can use "%" as a wildcard character. + * @return A new {@code Expr} representing the 'like' comparison. + */ + export function like(fieldName: string, pattern: string): BooleanExpr; - /** - * @beta - * - * Creates an aggregation that calculates the sum of values from an expression across multiple - * stage inputs. - * - * ```typescript - * // Calculate the total revenue from a set of orders - * sum(field("orderAmount")).as("totalRevenue"); - * ``` - * - * @param expression The expression to sum up. - * @return A new {@code AggregateFunction} representing the 'sum' aggregation. - */ - export function sum(expression: Expr): AggregateFunction; + /** + * @beta + * + * Creates an expression that performs a case-sensitive wildcard string comparison against a + * field. + * + * ```typescript + * // Check if the 'title' field contains the string "guide" + * like("title", field("pattern")); + * ``` + * + * @param fieldName The name of the field containing the string. + * @param pattern The pattern to search for. You can use "%" as a wildcard character. + * @return A new {@code Expr} representing the 'like' comparison. + */ + export function like(fieldName: string, pattern: Expr): BooleanExpr; - /** - * @beta - * - * Creates an aggregation that calculates the sum of a field's values across multiple stage - * inputs. - * - * ```typescript - * // Calculate the total revenue from a set of orders - * sum("orderAmount").as("totalRevenue"); - * ``` - * - * @param fieldName The name of the field containing numeric values to sum up. - * @return A new {@code AggregateFunction} representing the 'sum' aggregation. - */ - export function sum(fieldName: string): AggregateFunction; + /** + * @beta + * + * Creates an expression that performs a case-sensitive wildcard string comparison. + * + * ```typescript + * // Check if the 'title' field contains the string "guide" + * like(field("title"), "%guide%"); + * ``` + * + * @param stringExpression The expression representing the string to perform the comparison on. + * @param pattern The pattern to search for. You can use "%" as a wildcard character. + * @return A new {@code Expr} representing the 'like' comparison. + */ + export function like(stringExpression: Expr, pattern: string): BooleanExpr; - /** - * @beta - * - * Creates an aggregation that calculates the average (mean) of values from an expression across - * multiple stage inputs. - * - * ```typescript - * // Calculate the average age of users - * avg(field("age")).as("averageAge"); - * ``` - * - * @param expression The expression representing the values to average. - * @return A new {@code AggregateFunction} representing the 'avg' aggregation. - */ - export function avg(expression: Expr): AggregateFunction; + /** + * @beta + * + * Creates an expression that performs a case-sensitive wildcard string comparison. + * + * ```typescript + * // Check if the 'title' field contains the string "guide" + * like(field("title"), field("pattern")); + * ``` + * + * @param stringExpression The expression representing the string to perform the comparison on. + * @param pattern The pattern to search for. You can use "%" as a wildcard character. + * @return A new {@code Expr} representing the 'like' comparison. + */ + export function like(stringExpression: Expr, pattern: Expr): BooleanExpr; - /** - * @beta - * - * Creates an aggregation that calculates the average (mean) of a field's values across multiple - * stage inputs. - * - * ```typescript - * // Calculate the average age of users - * avg("age").as("averageAge"); - * ``` - * - * @param fieldName The name of the field containing numeric values to average. - * @return A new {@code AggregateFunction} representing the 'avg' aggregation. - */ - export function avg(fieldName: string): AggregateFunction; + /** + * @beta + * + * Creates an expression that checks if a string field contains a specified regular expression as + * a substring. + * + * ```typescript + * // Check if the 'description' field contains "example" (case-insensitive) + * regexContains("description", "(?i)example"); + * ``` + * + * @param fieldName The name of the field containing the string. + * @param pattern The regular expression to use for the search. + * @return A new {@code Expr} representing the 'contains' comparison. + */ + export function regexContains( + fieldName: string, + pattern: string + ): BooleanExpr; - /** - * @beta - * - * Creates an aggregation that finds the minimum value of an expression across multiple stage - * inputs. - * - * ```typescript - * // Find the lowest price of all products - * minimum(field("price")).as("lowestPrice"); - * ``` - * - * @param expression The expression to find the minimum value of. - * @return A new {@code AggregateFunction} representing the 'min' aggregation. - */ - export function minimum(expression: Expr): AggregateFunction; + /** + * @beta + * + * Creates an expression that checks if a string field contains a specified regular expression as + * a substring. + * + * ```typescript + * // Check if the 'description' field contains "example" (case-insensitive) + * regexContains("description", field("pattern")); + * ``` + * + * @param fieldName The name of the field containing the string. + * @param pattern The regular expression to use for the search. + * @return A new {@code Expr} representing the 'contains' comparison. + */ + export function regexContains( + fieldName: string, + pattern: Expr + ): BooleanExpr; - /** - * @beta - * - * Creates an aggregation that finds the minimum value of a field across multiple stage inputs. - * - * ```typescript - * // Find the lowest price of all products - * minimum("price").as("lowestPrice"); - * ``` - * - * @param fieldName The name of the field to find the minimum value of. - * @return A new {@code AggregateFunction} representing the 'min' aggregation. - */ - export function minimum(fieldName: string): AggregateFunction; + /** + * @beta + * + * Creates an expression that checks if a string expression contains a specified regular + * expression as a substring. + * + * ```typescript + * // Check if the 'description' field contains "example" (case-insensitive) + * regexContains(field("description"), "(?i)example"); + * ``` + * + * @param stringExpression The expression representing the string to perform the comparison on. + * @param pattern The regular expression to use for the search. + * @return A new {@code Expr} representing the 'contains' comparison. + */ + export function regexContains( + stringExpression: Expr, + pattern: string + ): BooleanExpr; - /** - * @beta - * - * Creates an aggregation that finds the maximum value of an expression across multiple stage - * inputs. - * - * ```typescript - * // Find the highest score in a leaderboard - * maximum(field("score")).as("highestScore"); - * ``` - * - * @param expression The expression to find the maximum value of. - * @return A new {@code AggregateFunction} representing the 'max' aggregation. - */ - export function maximum(expression: Expr): AggregateFunction; + /** + * @beta + * + * Creates an expression that checks if a string expression contains a specified regular + * expression as a substring. + * + * ```typescript + * // Check if the 'description' field contains "example" (case-insensitive) + * regexContains(field("description"), field("pattern")); + * ``` + * + * @param stringExpression The expression representing the string to perform the comparison on. + * @param pattern The regular expression to use for the search. + * @return A new {@code Expr} representing the 'contains' comparison. + */ + export function regexContains( + stringExpression: Expr, + pattern: Expr + ): BooleanExpr; - /** - * @beta - * - * Creates an aggregation that finds the maximum value of a field across multiple stage inputs. - * - * ```typescript - * // Find the highest score in a leaderboard - * maximum("score").as("highestScore"); - * ``` - * - * @param fieldName The name of the field to find the maximum value of. - * @return A new {@code AggregateFunction} representing the 'max' aggregation. - */ - export function maximum(fieldName: string): AggregateFunction; + /** + * @beta + * + * Creates an expression that checks if a string field matches a specified regular expression. + * + * ```typescript + * // Check if the 'email' field matches a valid email pattern + * regexMatch("email", "[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,}"); + * ``` + * + * @param fieldName The name of the field containing the string. + * @param pattern The regular expression to use for the match. + * @return A new {@code Expr} representing the regular expression match. + */ + export function regexMatch(fieldName: string, pattern: string): BooleanExpr; - /** - * @beta - * - * Calculates the Cosine distance between a field's vector value and a literal vector value. - * - * ```typescript - * // Calculate the Cosine distance between the 'location' field and a target location - * cosineDistance("location", [37.7749, -122.4194]); - * ``` - * - * @param fieldName The name of the field containing the first vector. - * @param vector The other vector (as an array of doubles) or {@link VectorValue} to compare against. - * @return A new {@code Expr} representing the Cosine distance between the two vectors. - */ - export function cosineDistance( - fieldName: string, - vector: number[] | VectorValue - ): FunctionExpr; + /** + * @beta + * + * Creates an expression that checks if a string field matches a specified regular expression. + * + * ```typescript + * // Check if the 'email' field matches a valid email pattern + * regexMatch("email", field("pattern")); + * ``` + * + * @param fieldName The name of the field containing the string. + * @param pattern The regular expression to use for the match. + * @return A new {@code Expr} representing the regular expression match. + */ + export function regexMatch(fieldName: string, pattern: Expr): BooleanExpr; - /** - * @beta - * - * Calculates the Cosine distance between a field's vector value and a vector expression. - * - * ```typescript - * // Calculate the cosine distance between the 'userVector' field and the 'itemVector' field - * cosineDistance("userVector", field("itemVector")); - * ``` - * - * @param fieldName The name of the field containing the first vector. - * @param vectorExpression The other vector (represented as an Expr) to compare against. - * @return A new {@code Expr} representing the cosine distance between the two vectors. - */ - export function cosineDistance( - fieldName: string, - vectorExpression: Expr - ): FunctionExpr; + /** + * @beta + * + * Creates an expression that checks if a string expression matches a specified regular + * expression. + * + * ```typescript + * // Check if the 'email' field matches a valid email pattern + * regexMatch(field("email"), "[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,}"); + * ``` + * + * @param stringExpression The expression representing the string to match against. + * @param pattern The regular expression to use for the match. + * @return A new {@code Expr} representing the regular expression match. + */ + export function regexMatch( + stringExpression: Expr, + pattern: string + ): BooleanExpr; - /** - * @beta - * - * Calculates the Cosine distance between a vector expression and a vector literal. - * - * ```typescript - * // Calculate the cosine distance between the 'location' field and a target location - * cosineDistance(field("location"), [37.7749, -122.4194]); - * ``` - * - * @param vectorExpression The first vector (represented as an Expr) to compare against. - * @param vector The other vector (as an array of doubles or VectorValue) to compare against. - * @return A new {@code Expr} representing the cosine distance between the two vectors. - */ - export function cosineDistance( - vectorExpression: Expr, - vector: number[] | Expr - ): FunctionExpr; + /** + * @beta + * + * Creates an expression that checks if a string expression matches a specified regular + * expression. + * + * ```typescript + * // Check if the 'email' field matches a valid email pattern + * regexMatch(field("email"), field("pattern")); + * ``` + * + * @param stringExpression The expression representing the string to match against. + * @param pattern The regular expression to use for the match. + * @return A new {@code Expr} representing the regular expression match. + */ + export function regexMatch( + stringExpression: Expr, + pattern: Expr + ): BooleanExpr; - /** - * @beta - * - * Calculates the Cosine distance between two vector expressions. - * - * ```typescript - * // Calculate the cosine distance between the 'userVector' field and the 'itemVector' field - * cosineDistance(field("userVector"), field("itemVector")); - * ``` - * - * @param vectorExpression The first vector (represented as an Expr) to compare against. - * @param otherVectorExpression The other vector (represented as an Expr) to compare against. - * @return A new {@code Expr} representing the cosine distance between the two vectors. - */ - export function cosineDistance( - vectorExpression: Expr, - otherVectorExpression: Expr - ): FunctionExpr; + /** + * @beta + * + * Creates an expression that checks if a string field contains a specified substring. + * + * ```typescript + * // Check if the 'description' field contains "example". + * strContains("description", "example"); + * ``` + * + * @param fieldName The name of the field containing the string. + * @param substring The substring to search for. + * @return A new {@code Expr} representing the 'contains' comparison. + */ + export function strContains( + fieldName: string, + substring: string + ): BooleanExpr; - /** - * @beta - * - * Calculates the dot product between a field's vector value and a double array. - * - * ```typescript - * // Calculate the dot product distance between a feature vector and a target vector - * dotProduct("features", [0.5, 0.8, 0.2]); - * ``` - * - * @param fieldName The name of the field containing the first vector. - * @param vector The other vector (as an array of doubles or VectorValue) to calculate with. - * @return A new {@code Expr} representing the dot product between the two vectors. - */ - export function dotProduct( - fieldName: string, - vector: number[] | VectorValue - ): FunctionExpr; + /** + * @beta + * + * Creates an expression that checks if a string field contains a substring specified by an expression. + * + * ```typescript + * // Check if the 'description' field contains the value of the 'keyword' field. + * strContains("description", field("keyword")); + * ``` + * + * @param fieldName The name of the field containing the string. + * @param substring The expression representing the substring to search for. + * @return A new {@code Expr} representing the 'contains' comparison. + */ + export function strContains( + fieldName: string, + substring: Expr + ): BooleanExpr; - /** - * @beta - * - * Calculates the dot product between a field's vector value and a vector expression. - * - * ```typescript - * // Calculate the dot product distance between two document vectors: 'docVector1' and 'docVector2' - * dotProduct("docVector1", field("docVector2")); - * ``` - * - * @param fieldName The name of the field containing the first vector. - * @param vectorExpression The other vector (represented as an Expr) to calculate with. - * @return A new {@code Expr} representing the dot product between the two vectors. - */ - export function dotProduct( - fieldName: string, - vectorExpression: Expr - ): FunctionExpr; + /** + * @beta + * + * Creates an expression that checks if a string expression contains a specified substring. + * + * ```typescript + * // Check if the 'description' field contains "example". + * strContains(field("description"), "example"); + * ``` + * + * @param stringExpression The expression representing the string to perform the comparison on. + * @param substring The substring to search for. + * @return A new {@code Expr} representing the 'contains' comparison. + */ + export function strContains( + stringExpression: Expr, + substring: string + ): BooleanExpr; - /** - * @beta - * - * Calculates the dot product between a vector expression and a double array. - * - * ```typescript - * // Calculate the dot product between a feature vector and a target vector - * dotProduct(field("features"), [0.5, 0.8, 0.2]); - * ``` - * - * @param vectorExpression The first vector (represented as an Expr) to calculate with. - * @param vector The other vector (as an array of doubles or VectorValue) to calculate with. - * @return A new {@code Expr} representing the dot product between the two vectors. - */ - export function dotProduct( - vectorExpression: Expr, - vector: number[] | VectorValue - ): FunctionExpr; + /** + * @beta + * + * Creates an expression that checks if a string expression contains a substring specified by another expression. + * + * ```typescript + * // Check if the 'description' field contains the value of the 'keyword' field. + * strContains(field("description"), field("keyword")); + * ``` + * + * @param stringExpression The expression representing the string to perform the comparison on. + * @param substring The expression representing the substring to search for. + * @return A new {@code Expr} representing the 'contains' comparison. + */ + export function strContains( + stringExpression: Expr, + substring: Expr + ): BooleanExpr; - /** - * @beta - * - * Calculates the dot product between two vector expressions. - * - * ```typescript - * // Calculate the dot product between two document vectors: 'docVector1' and 'docVector2' - * dotProduct(field("docVector1"), field("docVector2")); - * ``` - * - * @param vectorExpression The first vector (represented as an Expr) to calculate with. - * @param otherVectorExpression The other vector (represented as an Expr) to calculate with. - * @return A new {@code Expr} representing the dot product between the two vectors. - */ - export function dotProduct( - vectorExpression: Expr, - otherVectorExpression: Expr - ): FunctionExpr; + /** + * @beta + * + * Creates an expression that checks if a field's value starts with a given prefix. + * + * ```typescript + * // Check if the 'name' field starts with "Mr." + * startsWith("name", "Mr."); + * ``` + * + * @param fieldName The field name to check. + * @param prefix The prefix to check for. + * @return A new {@code Expr} representing the 'starts with' comparison. + */ + export function startsWith(fieldName: string, prefix: string): BooleanExpr; - /** - * @beta - * - * Calculates the Euclidean distance between a field's vector value and a double array. - * - * ```typescript - * // Calculate the Euclidean distance between the 'location' field and a target location - * euclideanDistance("location", [37.7749, -122.4194]); - * ``` - * - * @param fieldName The name of the field containing the first vector. - * @param vector The other vector (as an array of doubles or VectorValue) to compare against. - * @return A new {@code Expr} representing the Euclidean distance between the two vectors. - */ - export function euclideanDistance( - fieldName: string, - vector: number[] | VectorValue - ): FunctionExpr; + /** + * @beta + * + * Creates an expression that checks if a field's value starts with a given prefix. + * + * ```typescript + * // Check if the 'fullName' field starts with the value of the 'firstName' field + * startsWith("fullName", field("firstName")); + * ``` + * + * @param fieldName The field name to check. + * @param prefix The expression representing the prefix. + * @return A new {@code Expr} representing the 'starts with' comparison. + */ + export function startsWith(fieldName: string, prefix: Expr): BooleanExpr; - /** - * @beta - * - * Calculates the Euclidean distance between a field's vector value and a vector expression. - * - * ```typescript - * // Calculate the Euclidean distance between two vector fields: 'pointA' and 'pointB' - * euclideanDistance("pointA", field("pointB")); - * ``` - * - * @param fieldName The name of the field containing the first vector. - * @param vectorExpression The other vector (represented as an Expr) to compare against. - * @return A new {@code Expr} representing the Euclidean distance between the two vectors. - */ - export function euclideanDistance( - fieldName: string, - vectorExpression: Expr - ): FunctionExpr; + /** + * @beta + * + * Creates an expression that checks if a string expression starts with a given prefix. + * + * ```typescript + * // Check if the result of concatenating 'firstName' and 'lastName' fields starts with "Mr." + * startsWith(field("fullName"), "Mr."); + * ``` + * + * @param stringExpression The expression to check. + * @param prefix The prefix to check for. + * @return A new {@code Expr} representing the 'starts with' comparison. + */ + export function startsWith( + stringExpression: Expr, + prefix: string + ): BooleanExpr; - /** - * @beta - * - * Calculates the Euclidean distance between a vector expression and a double array. - * - * ```typescript - * // Calculate the Euclidean distance between the 'location' field and a target location - * - * euclideanDistance(field("location"), [37.7749, -122.4194]); - * ``` - * - * @param vectorExpression The first vector (represented as an Expr) to compare against. - * @param vector The other vector (as an array of doubles or VectorValue) to compare against. - * @return A new {@code Expr} representing the Euclidean distance between the two vectors. - */ - export function euclideanDistance( - vectorExpression: Expr, - vector: number[] | VectorValue - ): FunctionExpr; + /** + * @beta + * + * Creates an expression that checks if a string expression starts with a given prefix. + * + * ```typescript + * // Check if the result of concatenating 'firstName' and 'lastName' fields starts with "Mr." + * startsWith(field("fullName"), field("prefix")); + * ``` + * + * @param stringExpression The expression to check. + * @param prefix The prefix to check for. + * @return A new {@code Expr} representing the 'starts with' comparison. + */ + export function startsWith( + stringExpression: Expr, + prefix: Expr + ): BooleanExpr; - /** - * @beta - * - * Calculates the Euclidean distance between two vector expressions. - * - * ```typescript - * // Calculate the Euclidean distance between two vector fields: 'pointA' and 'pointB' - * euclideanDistance(field("pointA"), field("pointB")); - * ``` - * - * @param vectorExpression The first vector (represented as an Expr) to compare against. - * @param otherVectorExpression The other vector (represented as an Expr) to compare against. - * @return A new {@code Expr} representing the Euclidean distance between the two vectors. - */ - export function euclideanDistance( - vectorExpression: Expr, - otherVectorExpression: Expr - ): FunctionExpr; + /** + * @beta + * + * Creates an expression that checks if a field's value ends with a given postfix. + * + * ```typescript + * // Check if the 'filename' field ends with ".txt" + * endsWith("filename", ".txt"); + * ``` + * + * @param fieldName The field name to check. + * @param suffix The postfix to check for. + * @return A new {@code Expr} representing the 'ends with' comparison. + */ + export function endsWith(fieldName: string, suffix: string): BooleanExpr; - /** - * @beta - * - * Creates an expression that calculates the length of a Firestore Vector. - * - * ```typescript - * // Get the vector length (dimension) of the field 'embedding'. - * vectorLength(field("embedding")); - * ``` - * - * @param vectorExpression The expression representing the Firestore Vector. - * @return A new {@code Expr} representing the length of the array. - */ - export function vectorLength(vectorExpression: Expr): FunctionExpr; + /** + * @beta + * + * Creates an expression that checks if a field's value ends with a given postfix. + * + * ```typescript + * // Check if the 'url' field ends with the value of the 'extension' field + * endsWith("url", field("extension")); + * ``` + * + * @param fieldName The field name to check. + * @param suffix The expression representing the postfix. + * @return A new {@code Expr} representing the 'ends with' comparison. + */ + export function endsWith(fieldName: string, suffix: Expr): BooleanExpr; - /** - * @beta - * - * Creates an expression that calculates the length of a Firestore Vector represented by a field. - * - * ```typescript - * // Get the vector length (dimension) of the field 'embedding'. - * vectorLength("embedding"); - * ``` - * - * @param fieldName The name of the field representing the Firestore Vector. - * @return A new {@code Expr} representing the length of the array. - */ - export function vectorLength(fieldName: string): FunctionExpr; + /** + * @beta + * + * Creates an expression that checks if a string expression ends with a given postfix. + * + * ```typescript + * // Check if the result of concatenating 'firstName' and 'lastName' fields ends with "Jr." + * endsWith(field("fullName"), "Jr."); + * ``` + * + * @param stringExpression The expression to check. + * @param suffix The postfix to check for. + * @return A new {@code Expr} representing the 'ends with' comparison. + */ + export function endsWith( + stringExpression: Expr, + suffix: string + ): BooleanExpr; - /** - * @beta - * - * Creates an expression that interprets an expression as the number of microseconds since the Unix epoch (1970-01-01 00:00:00 UTC) - * and returns a timestamp. - * - * ```typescript - * // Interpret the 'microseconds' field as microseconds since epoch. - * unixMicrosToTimestamp(field("microseconds")); - * ``` - * - * @param expr The expression representing the number of microseconds since epoch. - * @return A new {@code Expr} representing the timestamp. - */ - export function unixMicrosToTimestamp(expr: Expr): FunctionExpr; + /** + * @beta + * + * Creates an expression that checks if a string expression ends with a given postfix. + * + * ```typescript + * // Check if the result of concatenating 'firstName' and 'lastName' fields ends with "Jr." + * endsWith(field("fullName"), constant("Jr.")); + * ``` + * + * @param stringExpression The expression to check. + * @param suffix The postfix to check for. + * @return A new {@code Expr} representing the 'ends with' comparison. + */ + export function endsWith(stringExpression: Expr, suffix: Expr): BooleanExpr; - /** - * @beta - * - * Creates an expression that interprets a field's value as the number of microseconds since the Unix epoch (1970-01-01 00:00:00 UTC) - * and returns a timestamp. - * - * ```typescript - * // Interpret the 'microseconds' field as microseconds since epoch. - * unixMicrosToTimestamp("microseconds"); - * ``` - * - * @param fieldName The name of the field representing the number of microseconds since epoch. - * @return A new {@code Expr} representing the timestamp. - */ - export function unixMicrosToTimestamp(fieldName: string): FunctionExpr; + /** + * @beta + * + * Creates an expression that converts a string field to lowercase. + * + * ```typescript + * // Convert the 'name' field to lowercase + * toLower("name"); + * ``` + * + * @param fieldName The name of the field containing the string. + * @return A new {@code Expr} representing the lowercase string. + */ + export function toLower(fieldName: string): FunctionExpr; - /** - * @beta - * - * Creates an expression that converts a timestamp expression to the number of microseconds since the Unix epoch (1970-01-01 00:00:00 UTC). - * - * ```typescript - * // Convert the 'timestamp' field to microseconds since epoch. - * timestampToUnixMicros(field("timestamp")); - * ``` - * - * @param expr The expression representing the timestamp. - * @return A new {@code Expr} representing the number of microseconds since epoch. - */ - export function timestampToUnixMicros(expr: Expr): FunctionExpr; + /** + * @beta + * + * Creates an expression that converts a string expression to lowercase. + * + * ```typescript + * // Convert the 'name' field to lowercase + * toLower(field("name")); + * ``` + * + * @param stringExpression The expression representing the string to convert to lowercase. + * @return A new {@code Expr} representing the lowercase string. + */ + export function toLower(stringExpression: Expr): FunctionExpr; - /** - * @beta - * - * Creates an expression that converts a timestamp field to the number of microseconds since the Unix epoch (1970-01-01 00:00:00 UTC). - * - * ```typescript - * // Convert the 'timestamp' field to microseconds since epoch. - * timestampToUnixMicros("timestamp"); - * ``` - * - * @param fieldName The name of the field representing the timestamp. - * @return A new {@code Expr} representing the number of microseconds since epoch. - */ - export function timestampToUnixMicros(fieldName: string): FunctionExpr; + /** + * @beta + * + * Creates an expression that converts a string field to uppercase. + * + * ```typescript + * // Convert the 'title' field to uppercase + * toUpper("title"); + * ``` + * + * @param fieldName The name of the field containing the string. + * @return A new {@code Expr} representing the uppercase string. + */ + export function toUpper(fieldName: string): FunctionExpr; + + /** + * @beta + * + * Creates an expression that converts a string expression to uppercase. + * + * ```typescript + * // Convert the 'title' field to uppercase + * toUppercase(field("title")); + * ``` + * + * @param stringExpression The expression representing the string to convert to uppercase. + * @return A new {@code Expr} representing the uppercase string. + */ + export function toUpper(stringExpression: Expr): FunctionExpr; - /** - * @beta - * - * Creates an expression that interprets an expression as the number of milliseconds since the Unix epoch (1970-01-01 00:00:00 UTC) - * and returns a timestamp. - * - * ```typescript - * // Interpret the 'milliseconds' field as milliseconds since epoch. - * unixMillisToTimestamp(field("milliseconds")); - * ``` - * - * @param expr The expression representing the number of milliseconds since epoch. - * @return A new {@code Expr} representing the timestamp. - */ - export function unixMillisToTimestamp(expr: Expr): FunctionExpr; + /** + * @beta + * + * Creates an expression that removes leading and trailing whitespace from a string field. + * + * ```typescript + * // Trim whitespace from the 'userInput' field + * trim("userInput"); + * ``` + * + * @param fieldName The name of the field containing the string. + * @return A new {@code Expr} representing the trimmed string. + */ + export function trim(fieldName: string): FunctionExpr; - /** - * @beta - * - * Creates an expression that interprets a field's value as the number of milliseconds since the Unix epoch (1970-01-01 00:00:00 UTC) - * and returns a timestamp. - * - * ```typescript - * // Interpret the 'milliseconds' field as milliseconds since epoch. - * unixMillisToTimestamp("milliseconds"); - * ``` - * - * @param fieldName The name of the field representing the number of milliseconds since epoch. - * @return A new {@code Expr} representing the timestamp. - */ - export function unixMillisToTimestamp(fieldName: string): FunctionExpr; + /** + * @beta + * + * Creates an expression that removes leading and trailing whitespace from a string expression. + * + * ```typescript + * // Trim whitespace from the 'userInput' field + * trim(field("userInput")); + * ``` + * + * @param stringExpression The expression representing the string to trim. + * @return A new {@code Expr} representing the trimmed string. + */ + export function trim(stringExpression: Expr): FunctionExpr; - /** - * @beta - * - * Creates an expression that converts a timestamp expression to the number of milliseconds since the Unix epoch (1970-01-01 00:00:00 UTC). - * - * ```typescript - * // Convert the 'timestamp' field to milliseconds since epoch. - * timestampToUnixMillis(field("timestamp")); - * ``` - * - * @param expr The expression representing the timestamp. - * @return A new {@code Expr} representing the number of milliseconds since epoch. - */ - export function timestampToUnixMillis(expr: Expr): FunctionExpr; + /** + * @beta + * + * Creates an expression that concatenates string functions, fields or constants together. + * + * ```typescript + * // Combine the 'firstName', " ", and 'lastName' fields into a single string + * strConcat("firstName", " ", field("lastName")); + * ``` + * + * @param fieldName The field name containing the initial string value. + * @param secondString An expression or string literal to concatenate. + * @param otherStrings Optional additional expressions or literals (typically strings) to concatenate. + * @return A new {@code Expr} representing the concatenated string. + */ + export function strConcat( + fieldName: string, + secondString: Expr | string, + ...otherStrings: Array + ): FunctionExpr; - /** - * @beta - * - * Creates an expression that converts a timestamp field to the number of milliseconds since the Unix epoch (1970-01-01 00:00:00 UTC). - * - * ```typescript - * // Convert the 'timestamp' field to milliseconds since epoch. - * timestampToUnixMillis("timestamp"); - * ``` - * - * @param fieldName The name of the field representing the timestamp. - * @return A new {@code Expr} representing the number of milliseconds since epoch. - */ - export function timestampToUnixMillis(fieldName: string): FunctionExpr; + /** + * @beta + * Creates an expression that concatenates string expressions together. + * + * ```typescript + * // Combine the 'firstName', " ", and 'lastName' fields into a single string + * strConcat(field("firstName"), " ", field("lastName")); + * ``` + * + * @param firstString The initial string expression to concatenate to. + * @param secondString An expression or string literal to concatenate. + * @param otherStrings Optional additional expressions or literals (typically strings) to concatenate. + * @return A new {@code Expr} representing the concatenated string. + */ + export function strConcat( + firstString: Expr, + secondString: Expr | string, + ...otherStrings: Array + ): FunctionExpr; - /** - * @beta - * - * Creates an expression that interprets an expression as the number of seconds since the Unix epoch (1970-01-01 00:00:00 UTC) - * and returns a timestamp. - * - * ```typescript - * // Interpret the 'seconds' field as seconds since epoch. - * unixSecondsToTimestamp(field("seconds")); - * ``` - * - * @param expr The expression representing the number of seconds since epoch. - * @return A new {@code Expr} representing the timestamp. - */ - export function unixSecondsToTimestamp(expr: Expr): FunctionExpr; + /** + * @beta + * + * Accesses a value from a map (object) field using the provided key. + * + * ```typescript + * // Get the 'city' value from the 'address' map field + * mapGet("address", "city"); + * ``` + * + * @param fieldName The field name of the map field. + * @param subField The key to access in the map. + * @return A new {@code Expr} representing the value associated with the given key in the map. + */ + export function mapGet(fieldName: string, subField: string): FunctionExpr; - /** - * @beta - * - * Creates an expression that interprets a field's value as the number of seconds since the Unix epoch (1970-01-01 00:00:00 UTC) - * and returns a timestamp. - * - * ```typescript - * // Interpret the 'seconds' field as seconds since epoch. - * unixSecondsToTimestamp("seconds"); - * ``` - * - * @param fieldName The name of the field representing the number of seconds since epoch. - * @return A new {@code Expr} representing the timestamp. - */ - export function unixSecondsToTimestamp(fieldName: string): FunctionExpr; + /** + * @beta + * + * Accesses a value from a map (object) expression using the provided key. + * + * ```typescript + * // Get the 'city' value from the 'address' map field + * mapGet(field("address"), "city"); + * ``` + * + * @param mapExpression The expression representing the map. + * @param subField The key to access in the map. + * @return A new {@code Expr} representing the value associated with the given key in the map. + */ + export function mapGet(mapExpression: Expr, subField: string): FunctionExpr; - /** - * @beta - * - * Creates an expression that converts a timestamp expression to the number of seconds since the Unix epoch (1970-01-01 00:00:00 UTC). - * - * ```typescript - * // Convert the 'timestamp' field to seconds since epoch. - * timestampToUnixSeconds(field("timestamp")); - * ``` - * - * @param expr The expression representing the timestamp. - * @return A new {@code Expr} representing the number of seconds since epoch. - */ - export function timestampToUnixSeconds(expr: Expr): FunctionExpr; + /** + * @beta + * + * Creates an aggregation that counts the total number of stage inputs. + * + * ```typescript + * // Count the total number of input documents + * countAll().as("totalDocument"); + * ``` + * + * @return A new {@code AggregateFunction} representing the 'countAll' aggregation. + */ + export function countAll(): AggregateFunction; - /** - * @beta - * - * Creates an expression that converts a timestamp field to the number of seconds since the Unix epoch (1970-01-01 00:00:00 UTC). - * - * ```typescript - * // Convert the 'timestamp' field to seconds since epoch. - * timestampToUnixSeconds("timestamp"); - * ``` - * - * @param fieldName The name of the field representing the timestamp. - * @return A new {@code Expr} representing the number of seconds since epoch. - */ - export function timestampToUnixSeconds(fieldName: string): FunctionExpr; + /** + * @beta + * + * Creates an aggregation that counts the number of stage inputs with valid evaluations of the + * provided expression. + * + * ```typescript + * // Count the number of items where the price is greater than 10 + * count(field("price").gt(10)).as("expensiveItemCount"); + * ``` + * + * @param expression The expression to count. + * @return A new {@code AggregateFunction} representing the 'count' aggregation. + */ + export function count(expression: Expr): AggregateFunction; - /** - * @beta - * - * Creates an expression that adds a specified amount of time to a timestamp. - * - * ```typescript - * // Add some duration determined by field 'unit' and 'amount' to the 'timestamp' field. - * timestampAdd(field("timestamp"), field("unit"), field("amount")); - * ``` - * - * @param timestamp The expression representing the timestamp. - * @param unit The expression evaluates to unit of time, must be one of 'microsecond', 'millisecond', 'second', 'minute', 'hour', 'day'. - * @param amount The expression evaluates to amount of the unit. - * @return A new {@code Expr} representing the resulting timestamp. - */ - export function timestampAdd( - timestamp: Expr, - unit: Expr, - amount: Expr - ): FunctionExpr; + /** + * Creates an aggregation that counts the number of stage inputs where the input field exists. + * + * ```typescript + * // Count the total number of products + * count("productId").as("totalProducts"); + * ``` + * + * @param fieldName The name of the field to count. + * @return A new {@code AggregateFunction} representing the 'count' aggregation. + */ + export function count(fieldName: string): AggregateFunction; - /** - * @beta - * - * Creates an expression that adds a specified amount of time to a timestamp. - * - * ```typescript - * // Add 1 day to the 'timestamp' field. - * timestampAdd(field("timestamp"), "day", 1); - * ``` - * - * @param timestamp The expression representing the timestamp. - * @param unit The unit of time to add (e.g., "day", "hour"). - * @param amount The amount of time to add. - * @return A new {@code Expr} representing the resulting timestamp. - */ - export function timestampAdd( - timestamp: Expr, - unit: 'microsecond' | 'millisecond' | 'second' | 'minute' | 'hour' | 'day', - amount: number - ): FunctionExpr; + /** + * @beta + * + * Creates an aggregation that calculates the sum of values from an expression across multiple + * stage inputs. + * + * ```typescript + * // Calculate the total revenue from a set of orders + * sum(field("orderAmount")).as("totalRevenue"); + * ``` + * + * @param expression The expression to sum up. + * @return A new {@code AggregateFunction} representing the 'sum' aggregation. + */ + export function sum(expression: Expr): AggregateFunction; - /** - * @beta - * - * Creates an expression that adds a specified amount of time to a timestamp represented by a field. - * - * ```typescript - * // Add 1 day to the 'timestamp' field. - * timestampAdd("timestamp", "day", 1); - * ``` - * - * @param fieldName The name of the field representing the timestamp. - * @param unit The unit of time to add (e.g., "day", "hour"). - * @param amount The amount of time to add. - * @return A new {@code Expr} representing the resulting timestamp. - */ - export function timestampAdd( - fieldName: string, - unit: 'microsecond' | 'millisecond' | 'second' | 'minute' | 'hour' | 'day', - amount: number - ): FunctionExpr; + /** + * @beta + * + * Creates an aggregation that calculates the sum of a field's values across multiple stage + * inputs. + * + * ```typescript + * // Calculate the total revenue from a set of orders + * sum("orderAmount").as("totalRevenue"); + * ``` + * + * @param fieldName The name of the field containing numeric values to sum up. + * @return A new {@code AggregateFunction} representing the 'sum' aggregation. + */ + export function sum(fieldName: string): AggregateFunction; - /** - * @beta - * - * Creates an expression that subtracts a specified amount of time from a timestamp. - * - * ```typescript - * // Subtract some duration determined by field 'unit' and 'amount' from the 'timestamp' field. - * timestampSub(field("timestamp"), field("unit"), field("amount")); - * ``` - * - * @param timestamp The expression representing the timestamp. - * @param unit The expression evaluates to unit of time, must be one of 'microsecond', 'millisecond', 'second', 'minute', 'hour', 'day'. - * @param amount The expression evaluates to amount of the unit. - * @return A new {@code Expr} representing the resulting timestamp. - */ - export function timestampSub( - timestamp: Expr, - unit: Expr, - amount: Expr - ): FunctionExpr; + /** + * @beta + * + * Creates an aggregation that calculates the average (mean) of values from an expression across + * multiple stage inputs. + * + * ```typescript + * // Calculate the average age of users + * avg(field("age")).as("averageAge"); + * ``` + * + * @param expression The expression representing the values to average. + * @return A new {@code AggregateFunction} representing the 'avg' aggregation. + */ + export function avg(expression: Expr): AggregateFunction; - /** - * @beta - * - * Creates an expression that subtracts a specified amount of time from a timestamp. - * - * ```typescript - * // Subtract 1 day from the 'timestamp' field. - * timestampSub(field("timestamp"), "day", 1); - * ``` - * - * @param timestamp The expression representing the timestamp. - * @param unit The unit of time to subtract (e.g., "day", "hour"). - * @param amount The amount of time to subtract. - * @return A new {@code Expr} representing the resulting timestamp. - */ - export function timestampSub( - timestamp: Expr, - unit: 'microsecond' | 'millisecond' | 'second' | 'minute' | 'hour' | 'day', - amount: number - ): FunctionExpr; + /** + * @beta + * + * Creates an aggregation that calculates the average (mean) of a field's values across multiple + * stage inputs. + * + * ```typescript + * // Calculate the average age of users + * avg("age").as("averageAge"); + * ``` + * + * @param fieldName The name of the field containing numeric values to average. + * @return A new {@code AggregateFunction} representing the 'avg' aggregation. + */ + export function avg(fieldName: string): AggregateFunction; - /** - * @beta - * - * Creates an expression that subtracts a specified amount of time from a timestamp represented by a field. - * - * ```typescript - * // Subtract 1 day from the 'timestamp' field. - * timestampSub("timestamp", "day", 1); - * ``` - * - * @param fieldName The name of the field representing the timestamp. - * @param unit The unit of time to subtract (e.g., "day", "hour"). - * @param amount The amount of time to subtract. - * @return A new {@code Expr} representing the resulting timestamp. - */ - export function timestampSub( - fieldName: string, - unit: 'microsecond' | 'millisecond' | 'second' | 'minute' | 'hour' | 'day', - amount: number - ): FunctionExpr; + /** + * @beta + * + * Creates an aggregation that finds the minimum value of an expression across multiple stage + * inputs. + * + * ```typescript + * // Find the lowest price of all products + * minimum(field("price")).as("lowestPrice"); + * ``` + * + * @param expression The expression to find the minimum value of. + * @return A new {@code AggregateFunction} representing the 'min' aggregation. + */ + export function minimum(expression: Expr): AggregateFunction; - /** - * @beta - * - * Creates an expression that performs a logical 'AND' operation on multiple filter conditions. - * - * ```typescript - * // Check if the 'age' field is greater than 18 AND the 'city' field is "London" AND - * // the 'status' field is "active" - * const condition = and(gt("age", 18), eq("city", "London"), eq("status", "active")); - * ``` - * - * @param first The first filter condition. - * @param second The second filter condition. - * @param more Additional filter conditions to 'AND' together. - * @return A new {@code Expr} representing the logical 'AND' operation. - */ - export function and( - first: BooleanExpr, - second: BooleanExpr, - ...more: BooleanExpr[] - ): BooleanExpr; + /** + * @beta + * + * Creates an aggregation that finds the minimum value of a field across multiple stage inputs. + * + * ```typescript + * // Find the lowest price of all products + * minimum("price").as("lowestPrice"); + * ``` + * + * @param fieldName The name of the field to find the minimum value of. + * @return A new {@code AggregateFunction} representing the 'min' aggregation. + */ + export function minimum(fieldName: string): AggregateFunction; - /** - * @beta - * - * Creates an expression that performs a logical 'OR' operation on multiple filter conditions. - * - * ```typescript - * // Check if the 'age' field is greater than 18 OR the 'city' field is "London" OR - * // the 'status' field is "active" - * const condition = or(gt("age", 18), eq("city", "London"), eq("status", "active")); - * ``` - * - * @param first The first filter condition. - * @param second The second filter condition. - * @param more Additional filter conditions to 'OR' together. - * @return A new {@code Expr} representing the logical 'OR' operation. - */ - export function or( - first: BooleanExpr, - second: BooleanExpr, - ...more: BooleanExpr[] - ): BooleanExpr; + /** + * @beta + * + * Creates an aggregation that finds the maximum value of an expression across multiple stage + * inputs. + * + * ```typescript + * // Find the highest score in a leaderboard + * maximum(field("score")).as("highestScore"); + * ``` + * + * @param expression The expression to find the maximum value of. + * @return A new {@code AggregateFunction} representing the 'max' aggregation. + */ + export function maximum(expression: Expr): AggregateFunction; + + /** + * @beta + * + * Creates an aggregation that finds the maximum value of a field across multiple stage inputs. + * + * ```typescript + * // Find the highest score in a leaderboard + * maximum("score").as("highestScore"); + * ``` + * + * @param fieldName The name of the field to find the maximum value of. + * @return A new {@code AggregateFunction} representing the 'max' aggregation. + */ + export function maximum(fieldName: string): AggregateFunction; - /** - * @beta - * - * Creates an {@link Ordering} that sorts documents in ascending order based on an expression. - * - * ```typescript - * // Sort documents by the 'name' field in lowercase in ascending order - * pipeline().collection("users") - * .sort(ascending(field("name").toLower())); - * ``` - * - * @param expr The expression to create an ascending ordering for. - * @return A new `Ordering` for ascending sorting. - */ - export function ascending(expr: Expr): Ordering; + /** + * @beta + * + * Calculates the Cosine distance between a field's vector value and a literal vector value. + * + * ```typescript + * // Calculate the Cosine distance between the 'location' field and a target location + * cosineDistance("location", [37.7749, -122.4194]); + * ``` + * + * @param fieldName The name of the field containing the first vector. + * @param vector The other vector (as an array of doubles) or {@link VectorValue} to compare against. + * @return A new {@code Expr} representing the Cosine distance between the two vectors. + */ + export function cosineDistance( + fieldName: string, + vector: number[] | VectorValue + ): FunctionExpr; - /** - * @beta - * - * Creates an {@link Ordering} that sorts documents in ascending order based on a field. - * - * ```typescript - * // Sort documents by the 'name' field in ascending order - * pipeline().collection("users") - * .sort(ascending("name")); - * ``` - * - * @param fieldName The field to create an ascending ordering for. - * @return A new `Ordering` for ascending sorting. - */ - export function ascending(fieldName: string): Ordering; + /** + * @beta + * + * Calculates the Cosine distance between a field's vector value and a vector expression. + * + * ```typescript + * // Calculate the cosine distance between the 'userVector' field and the 'itemVector' field + * cosineDistance("userVector", field("itemVector")); + * ``` + * + * @param fieldName The name of the field containing the first vector. + * @param vectorExpression The other vector (represented as an Expr) to compare against. + * @return A new {@code Expr} representing the cosine distance between the two vectors. + */ + export function cosineDistance( + fieldName: string, + vectorExpression: Expr + ): FunctionExpr; - /** - * @beta - * - * Creates an {@link Ordering} that sorts documents in descending order based on an expression. - * - * ```typescript - * // Sort documents by the 'name' field in lowercase in descending order - * pipeline().collection("users") - * .sort(descending(field("name").toLower())); - * ``` - * - * @param expr The expression to create a descending ordering for. - * @return A new `Ordering` for descending sorting. - */ - export function descending(expr: Expr): Ordering; + /** + * @beta + * + * Calculates the Cosine distance between a vector expression and a vector literal. + * + * ```typescript + * // Calculate the cosine distance between the 'location' field and a target location + * cosineDistance(field("location"), [37.7749, -122.4194]); + * ``` + * + * @param vectorExpression The first vector (represented as an Expr) to compare against. + * @param vector The other vector (as an array of doubles or VectorValue) to compare against. + * @return A new {@code Expr} representing the cosine distance between the two vectors. + */ + export function cosineDistance( + vectorExpression: Expr, + vector: number[] | Expr + ): FunctionExpr; - /** - * @beta - * - * Creates an {@link Ordering} that sorts documents in descending order based on a field. - * - * ```typescript - * // Sort documents by the 'name' field in descending order - * pipeline().collection("users") - * .sort(descending("name")); - * ``` - * - * @param fieldName The field to create a descending ordering for. - * @return A new `Ordering` for descending sorting. - */ - export function descending(fieldName: string): Ordering; + /** + * @beta + * + * Calculates the Cosine distance between two vector expressions. + * + * ```typescript + * // Calculate the cosine distance between the 'userVector' field and the 'itemVector' field + * cosineDistance(field("userVector"), field("itemVector")); + * ``` + * + * @param vectorExpression The first vector (represented as an Expr) to compare against. + * @param otherVectorExpression The other vector (represented as an Expr) to compare against. + * @return A new {@code Expr} representing the cosine distance between the two vectors. + */ + export function cosineDistance( + vectorExpression: Expr, + otherVectorExpression: Expr + ): FunctionExpr; - /** - * @beta - * - * Represents an ordering criterion for sorting documents in a Firestore pipeline. - * - * You create `Ordering` instances using the `ascending` and `descending` helper functions. - */ - export class Ordering { - readonly expr: Expr; - readonly direction: 'ascending' | 'descending'; - } + /** + * @beta + * + * Calculates the dot product between a field's vector value and a double array. + * + * ```typescript + * // Calculate the dot product distance between a feature vector and a target vector + * dotProduct("features", [0.5, 0.8, 0.2]); + * ``` + * + * @param fieldName The name of the field containing the first vector. + * @param vector The other vector (as an array of doubles or VectorValue) to calculate with. + * @return A new {@code Expr} representing the dot product between the two vectors. + */ + export function dotProduct( + fieldName: string, + vector: number[] | VectorValue + ): FunctionExpr; - /** - * @beta - */ - export interface Stage { - name: string; - } + /** + * @beta + * + * Calculates the dot product between a field's vector value and a vector expression. + * + * ```typescript + * // Calculate the dot product distance between two document vectors: 'docVector1' and 'docVector2' + * dotProduct("docVector1", field("docVector2")); + * ``` + * + * @param fieldName The name of the field containing the first vector. + * @param vectorExpression The other vector (represented as an Expr) to calculate with. + * @return A new {@code Expr} representing the dot product between the two vectors. + */ + export function dotProduct( + fieldName: string, + vectorExpression: Expr + ): FunctionExpr; - /** - * @beta - */ - export class Aggregate implements Stage { - name: string; - } + /** + * @beta + * + * Calculates the dot product between a vector expression and a double array. + * + * ```typescript + * // Calculate the dot product between a feature vector and a target vector + * dotProduct(field("features"), [0.5, 0.8, 0.2]); + * ``` + * + * @param vectorExpression The first vector (represented as an Expr) to calculate with. + * @param vector The other vector (as an array of doubles or VectorValue) to calculate with. + * @return A new {@code Expr} representing the dot product between the two vectors. + */ + export function dotProduct( + vectorExpression: Expr, + vector: number[] | VectorValue + ): FunctionExpr; - /** - * @beta - */ - export class Where implements Stage { - name: string; - } + /** + * @beta + * + * Calculates the dot product between two vector expressions. + * + * ```typescript + * // Calculate the dot product between two document vectors: 'docVector1' and 'docVector2' + * dotProduct(field("docVector1"), field("docVector2")); + * ``` + * + * @param vectorExpression The first vector (represented as an Expr) to calculate with. + * @param otherVectorExpression The other vector (represented as an Expr) to calculate with. + * @return A new {@code Expr} representing the dot product between the two vectors. + */ + export function dotProduct( + vectorExpression: Expr, + otherVectorExpression: Expr + ): FunctionExpr; - /** - * @beta - */ - export interface FindNearestOptions { - field: Field | string; - vectorValue: VectorValue | number[]; - distanceMeasure: 'euclidean' | 'cosine' | 'dot_product'; - limit?: number; - distanceField?: string; - } + /** + * @beta + * + * Calculates the Euclidean distance between a field's vector value and a double array. + * + * ```typescript + * // Calculate the Euclidean distance between the 'location' field and a target location + * euclideanDistance("location", [37.7749, -122.4194]); + * ``` + * + * @param fieldName The name of the field containing the first vector. + * @param vector The other vector (as an array of doubles or VectorValue) to compare against. + * @return A new {@code Expr} representing the Euclidean distance between the two vectors. + */ + export function euclideanDistance( + fieldName: string, + vector: number[] | VectorValue + ): FunctionExpr; - /** - * @beta - */ - export class FindNearest implements Stage { - name: string; - } + /** + * @beta + * + * Calculates the Euclidean distance between a field's vector value and a vector expression. + * + * ```typescript + * // Calculate the Euclidean distance between two vector fields: 'pointA' and 'pointB' + * euclideanDistance("pointA", field("pointB")); + * ``` + * + * @param fieldName The name of the field containing the first vector. + * @param vectorExpression The other vector (represented as an Expr) to compare against. + * @return A new {@code Expr} representing the Euclidean distance between the two vectors. + */ + export function euclideanDistance( + fieldName: string, + vectorExpression: Expr + ): FunctionExpr; - /** - * @beta - */ - export class Replace implements Stage { - name: string; - } + /** + * @beta + * + * Calculates the Euclidean distance between a vector expression and a double array. + * + * ```typescript + * // Calculate the Euclidean distance between the 'location' field and a target location + * + * euclideanDistance(field("location"), [37.7749, -122.4194]); + * ``` + * + * @param vectorExpression The first vector (represented as an Expr) to compare against. + * @param vector The other vector (as an array of doubles or VectorValue) to compare against. + * @return A new {@code Expr} representing the Euclidean distance between the two vectors. + */ + export function euclideanDistance( + vectorExpression: Expr, + vector: number[] | VectorValue + ): FunctionExpr; - /** - * @beta - */ - export interface UnnestOptions { - field: Selectable | string; - alias: Field | string; - indexField?: string; - } + /** + * @beta + * + * Calculates the Euclidean distance between two vector expressions. + * + * ```typescript + * // Calculate the Euclidean distance between two vector fields: 'pointA' and 'pointB' + * euclideanDistance(field("pointA"), field("pointB")); + * ``` + * + * @param vectorExpression The first vector (represented as an Expr) to compare against. + * @param otherVectorExpression The other vector (represented as an Expr) to compare against. + * @return A new {@code Expr} representing the Euclidean distance between the two vectors. + */ + export function euclideanDistance( + vectorExpression: Expr, + otherVectorExpression: Expr + ): FunctionExpr; - /** - * Represents the source of a Firestore {@link Pipeline}. - * @beta - */ - export class PipelineSource { /** - * Specifies the source as a collection. + * @beta * - * @param collectionPath The path to the collection. - * @return A new Pipeline object with the collection as the source. + * Creates an expression that calculates the length of a Firestore Vector. + * + * ```typescript + * // Get the vector length (dimension) of the field 'embedding'. + * vectorLength(field("embedding")); + * ``` + * + * @param vectorExpression The expression representing the Firestore Vector. + * @return A new {@code Expr} representing the length of the array. */ - collection(collectionPath: string | CollectionReference): Pipeline; + export function vectorLength(vectorExpression: Expr): FunctionExpr; /** - * Specifies the source as a collection group. + * @beta + * + * Creates an expression that calculates the length of a Firestore Vector represented by a field. + * + * ```typescript + * // Get the vector length (dimension) of the field 'embedding'. + * vectorLength("embedding"); + * ``` * - * @param collectionId The ID of the collection group. - * @return A new Pipeline object with the collection group as the source. + * @param fieldName The name of the field representing the Firestore Vector. + * @return A new {@code Expr} representing the length of the array. */ - collectionGroup(collectionId: string): Pipeline; + export function vectorLength(fieldName: string): FunctionExpr; /** - * Specifies the source as a database. + * @beta + * + * Creates an expression that interprets an expression as the number of microseconds since the Unix epoch (1970-01-01 00:00:00 UTC) + * and returns a timestamp. + * + * ```typescript + * // Interpret the 'microseconds' field as microseconds since epoch. + * unixMicrosToTimestamp(field("microseconds")); + * ``` * - * @return A new Pipeline object with the database as the source. + * @param expr The expression representing the number of microseconds since epoch. + * @return A new {@code Expr} representing the timestamp. */ - database(): Pipeline; + export function unixMicrosToTimestamp(expr: Expr): FunctionExpr; /** - * Specifies the source as a set of documents. + * @beta + * + * Creates an expression that interprets a field's value as the number of microseconds since the Unix epoch (1970-01-01 00:00:00 UTC) + * and returns a timestamp. + * + * ```typescript + * // Interpret the 'microseconds' field as microseconds since epoch. + * unixMicrosToTimestamp("microseconds"); + * ``` * - * @param docs The document references. - * @return A new Pipeline object with the documents as the source. + * @param fieldName The name of the field representing the number of microseconds since epoch. + * @return A new {@code Expr} representing the timestamp. */ - documents(docs: Array): Pipeline; + export function unixMicrosToTimestamp(fieldName: string): FunctionExpr; /** - * Convert the given Query into an equivalent Pipeline. + * @beta * - * @param query A Query to be converted into a Pipeline. + * Creates an expression that converts a timestamp expression to the number of microseconds since the Unix epoch (1970-01-01 00:00:00 UTC). + * + * ```typescript + * // Convert the 'timestamp' field to microseconds since epoch. + * timestampToUnixMicros(field("timestamp")); + * ``` * - * @throws {@FirestoreError} Thrown if any of the provided DocumentReferences target a different project or database than the pipeline. + * @param expr The expression representing the timestamp. + * @return A new {@code Expr} representing the number of microseconds since epoch. */ - createFrom(query: Query): Pipeline; - } + export function timestampToUnixMicros(expr: Expr): FunctionExpr; - /** - * @beta - * - * The Pipeline class provides a flexible and expressive framework for building complex data - * transformation and query pipelines for Firestore. - * - * A pipeline takes data sources, such as Firestore collections or collection groups, and applies - * a series of stages that are chained together. Each stage takes the output from the previous stage - * (or the data source) and produces an output for the next stage (or as the final output of the - * pipeline). - * - * Expressions can be used within each stage to filter and transform data through the stage. - * - * NOTE: The chained stages do not prescribe exactly how Firestore will execute the pipeline. - * Instead, Firestore only guarantees that the result is the same as if the chained stages were - * executed in order. - * - * Usage Examples: - * - * ```typescript - * const db: Firestore; // Assumes a valid firestore instance. - * - * // Example 1: Select specific fields and rename 'rating' to 'bookRating' - * const results1 = await db.pipeline() - * .collection("books") - * .select("title", "author", Field.of("rating").as("bookRating")) - * .execute(); - * - * // Example 2: Filter documents where 'genre' is "Science Fiction" and 'published' is after 1950 - * const results2 = await db.pipeline() - * .collection("books") - * .where(and(Field.of("genre").eq("Science Fiction"), Field.of("published").gt(1950))) - * .execute(); - * - * // Example 3: Calculate the average rating of books published after 1980 - * const results3 = await db.pipeline() - * .collection("books") - * .where(Field.of("published").gt(1980)) - * .aggregate(avg(Field.of("rating")).as("averageRating")) - * .execute(); - * ``` - */ - export class Pipeline { /** - * Adds new fields to outputs from previous stages. + * @beta * - * This stage allows you to compute values on-the-fly based on existing data from previous - * stages or constants. You can use this to create new fields or overwrite existing ones (if there - * is name overlaps). + * Creates an expression that converts a timestamp field to the number of microseconds since the Unix epoch (1970-01-01 00:00:00 UTC). * - * The added fields are defined using {@link Selectable}s, which can be: + * ```typescript + * // Convert the 'timestamp' field to microseconds since epoch. + * timestampToUnixMicros("timestamp"); + * ``` * - * - {@link Field}: References an existing document field. - * - {@link Expr}: Either a literal value (see {@link Constant}) or a computed value - * (see {@FunctionExpr}) with an assigned alias using {@link Expr#as}. + * @param fieldName The name of the field representing the timestamp. + * @return A new {@code Expr} representing the number of microseconds since epoch. + */ + export function timestampToUnixMicros(fieldName: string): FunctionExpr; + + /** + * @beta * - * Example: + * Creates an expression that interprets an expression as the number of milliseconds since the Unix epoch (1970-01-01 00:00:00 UTC) + * and returns a timestamp. * * ```typescript - * firestore.pipeline().collection("books") - * .addFields( - * field("rating").as("bookRating"), // Rename 'rating' to 'bookRating' - * add(5, field("quantity")).as("totalCost") // Calculate 'totalCost' - * ); + * // Interpret the 'milliseconds' field as milliseconds since epoch. + * unixMillisToTimestamp(field("milliseconds")); * ``` * - * @param field The first field to add to the documents, specified as a {@link Selectable}. - * @param additionalFields Optional additional fields to add to the documents, specified as {@link Selectable}s. - * @return A new Pipeline object with this stage appended to the stage list. + * @param expr The expression representing the number of milliseconds since epoch. + * @return A new {@code Expr} representing the timestamp. */ - addFields(field: Selectable, ...additionalFields: Selectable[]): Pipeline; + export function unixMillisToTimestamp(expr: Expr): FunctionExpr; /** - * Remove fields from outputs of previous stages. + * @beta * - * Example: + * Creates an expression that interprets a field's value as the number of milliseconds since the Unix epoch (1970-01-01 00:00:00 UTC) + * and returns a timestamp. * * ```typescript - * firestore.pipeline().collection('books') - * // removes field 'rating' and 'cost' from the previous stage outputs. - * .removeFields( - * field('rating'), - * 'cost' - * ); + * // Interpret the 'milliseconds' field as milliseconds since epoch. + * unixMillisToTimestamp("milliseconds"); * ``` * - * @param fieldValue The first field to remove. - * @param additionalFields Optional additional fields to remove. - * @return A new Pipeline object with this stage appended to the stage list. + * @param fieldName The name of the field representing the number of milliseconds since epoch. + * @return A new {@code Expr} representing the timestamp. */ - removeFields( - fieldValue: Field | string, - ...additionalFields: Array - ): Pipeline; + export function unixMillisToTimestamp(fieldName: string): FunctionExpr; /** - * Selects or creates a set of fields from the outputs of previous stages. + * @beta * - *

      The selected fields are defined using {@link Selectable} expressions, which can be: + * Creates an expression that converts a timestamp expression to the number of milliseconds since the Unix epoch (1970-01-01 00:00:00 UTC). * - *

        - *
      • {@code string}: Name of an existing field
      • - *
      • {@link Field}: References an existing field.
      • - *
      • {@link Function}: Represents the result of a function with an assigned alias name using - * {@link Expr#as}
      • - *
      + * ```typescript + * // Convert the 'timestamp' field to milliseconds since epoch. + * timestampToUnixMillis(field("timestamp")); + * ``` * - *

      If no selections are provided, the output of this stage is empty. Use {@link - * Pipeline#addFields} instead if only additions are - * desired. + * @param expr The expression representing the timestamp. + * @return A new {@code Expr} representing the number of milliseconds since epoch. + */ + export function timestampToUnixMillis(expr: Expr): FunctionExpr; + + /** + * @beta * - *

      Example: + * Creates an expression that converts a timestamp field to the number of milliseconds since the Unix epoch (1970-01-01 00:00:00 UTC). * * ```typescript - * firestore.pipeline().collection("books") - * .select( - * "firstName", - * field("lastName"), - * field("address").toUppercase().as("upperAddress"), - * ); + * // Convert the 'timestamp' field to milliseconds since epoch. + * timestampToUnixMillis("timestamp"); * ``` * - * @param selection The first field to include in the output documents, specified as {@link - * Selectable} expression or string value representing the field name. - * @param additionalSelections Optional additional fields to include in the output documents, specified as {@link - * Selectable} expressions or {@code string} values representing field names. - * @return A new Pipeline object with this stage appended to the stage list. + * @param fieldName The name of the field representing the timestamp. + * @return A new {@code Expr} representing the number of milliseconds since epoch. */ - select( - selection: Selectable | string, - ...additionalSelections: Array - ): Pipeline; + export function timestampToUnixMillis(fieldName: string): FunctionExpr; /** - * Filters the documents from previous stages to only include those matching the specified {@link - * BooleanExpr}. - * - *

      This stage allows you to apply conditions to the data, similar to a "WHERE" clause in SQL. - * You can filter documents based on their field values, using implementations of {@link - * BooleanExpr}, typically including but not limited to: - * - *

        - *
      • field comparators: {@link Function#eq}, {@link Function#lt} (less than), {@link - * Function#gt} (greater than), etc.
      • - *
      • logical operators: {@link Function#and}, {@link Function#or}, {@link Function#not}, etc.
      • - *
      • advanced functions: {@link Function#regexMatch}, {@link - * Function#arrayContains}, etc.
      • - *
      + * @beta * - *

      Example: + * Creates an expression that interprets an expression as the number of seconds since the Unix epoch (1970-01-01 00:00:00 UTC) + * and returns a timestamp. * * ```typescript - * firestore.pipeline().collection("books") - * .where( - * and( - * gt(field("rating"), 4.0), // Filter for ratings greater than 4.0 - * field("genre").eq("Science Fiction") // Equivalent to gt("genre", "Science Fiction") - * ) - * ); + * // Interpret the 'seconds' field as seconds since epoch. + * unixSecondsToTimestamp(field("seconds")); * ``` * - * @param condition The {@link BooleanExpr} to apply. - * @return A new Pipeline object with this stage appended to the stage list. + * @param expr The expression representing the number of seconds since epoch. + * @return A new {@code Expr} representing the timestamp. */ - where(condition: BooleanExpr): Pipeline; + export function unixSecondsToTimestamp(expr: Expr): FunctionExpr; /** - * Skips the first `offset` number of documents from the results of previous stages. - * - *

      This stage is useful for implementing pagination in your pipelines, allowing you to retrieve - * results in chunks. It is typically used in conjunction with {@link #limit} to control the - * size of each page. + * @beta * - *

      Example: + * Creates an expression that interprets a field's value as the number of seconds since the Unix epoch (1970-01-01 00:00:00 UTC) + * and returns a timestamp. * * ```typescript - * // Retrieve the second page of 20 results - * firestore.pipeline().collection("books") - * .sort(Field.of("published").descending()) - * .offset(20) // Skip the first 20 results - * .limit(20); // Take the next 20 results + * // Interpret the 'seconds' field as seconds since epoch. + * unixSecondsToTimestamp("seconds"); * ``` * - * @param offset The number of documents to skip. - * @return A new Pipeline object with this stage appended to the stage list. + * @param fieldName The name of the field representing the number of seconds since epoch. + * @return A new {@code Expr} representing the timestamp. */ - offset(offset: number): Pipeline; + export function unixSecondsToTimestamp(fieldName: string): FunctionExpr; /** - * Limits the maximum number of documents returned by previous stages to `limit`. - * - *

      This stage is particularly useful when you want to retrieve a controlled subset of data from - * a potentially large result set. It's often used for: - * - *

        - *
      • **Pagination:** In combination with {@link #offset} to retrieve specific pages of - * results.
      • - *
      • **Limiting Data Retrieval:** To prevent excessive data transfer and improve performance, - * especially when dealing with large collections.
      • - *
      + * @beta * - *

      Example: + * Creates an expression that converts a timestamp expression to the number of seconds since the Unix epoch (1970-01-01 00:00:00 UTC). * * ```typescript - * // Limit the results to the top 10 highest-rated books - * firestore.pipeline().collection("books") - * .sort(Field.of("rating").descending()) - * .limit(10); + * // Convert the 'timestamp' field to seconds since epoch. + * timestampToUnixSeconds(field("timestamp")); * ``` * - * @param limit The maximum number of documents to return. - * @return A new Pipeline object with this stage appended to the stage list. + * @param expr The expression representing the timestamp. + * @return A new {@code Expr} representing the number of seconds since epoch. */ - limit(limit: number): Pipeline; + export function timestampToUnixSeconds(expr: Expr): FunctionExpr; /** - * Returns a set of distinct values from the inputs to this stage. - * - * This stage runs through the results from previous stages to include only results with - * unique combinations of {@link Expr} values ({@link Field}, {@link Function}, etc). - * - * The parameters to this stage are defined using {@link Selectable} expressions or strings: - * - * - {@code string}: Name of an existing field - * - {@link Field}: References an existing document field. - * - {@link ExprWithAlias}: Represents the result of a function with an assigned alias name - * using {@link Expr#as}. + * @beta * - * Example: + * Creates an expression that converts a timestamp field to the number of seconds since the Unix epoch (1970-01-01 00:00:00 UTC). * * ```typescript - * // Get a list of unique author names in uppercase and genre combinations. - * firestore.pipeline().collection("books") - * .distinct(toUppercase(field("author")).as("authorName"), field("genre"), "publishedAt") - * .select("authorName"); + * // Convert the 'timestamp' field to seconds since epoch. + * timestampToUnixSeconds("timestamp"); * ``` * - * @param group The {@link Selectable} expression or field name to consider when determining - * distinct value combinations. - * @param additionalGroups Optional additional {@link Selectable} expressions to consider when determining distinct - * value combinations or strings representing field names. - * @return A new {@code Pipeline} object with this stage appended to the stage list. + * @param fieldName The name of the field representing the timestamp. + * @return A new {@code Expr} representing the number of seconds since epoch. */ - distinct( - group: string | Selectable, - ...additionalGroups: Array - ): Pipeline; + export function timestampToUnixSeconds(fieldName: string): FunctionExpr; /** - * Performs aggregation operations on the documents from previous stages. - * - *

      This stage allows you to calculate aggregate values over a set of documents. You define the - * aggregations to perform using {@link AggregateWithAlias} expressions which are typically results of - * calling {@link Expr#as} on {@link AggregateFunction} instances. + * @beta * - *

      Example: + * Creates an expression that adds a specified amount of time to a timestamp. * * ```typescript - * // Calculate the average rating and the total number of books - * firestore.pipeline().collection("books") - * .aggregate( - * field("rating").avg().as("averageRating"), - * countAll().as("totalBooks") - * ); + * // Add some duration determined by field 'unit' and 'amount' to the 'timestamp' field. + * timestampAdd(field("timestamp"), field("unit"), field("amount")); * ``` * - * @param accumulator The first {@link AggregateWithAlias}, wrapping an {@link AggregateFunction} - * and providing a name for the accumulated results. - * @param additionalAccumulators Optional additional {@link AggregateWithAlias}, each wrapping an {@link AggregateFunction} - * and providing a name for the accumulated results. - * @return A new Pipeline object with this stage appended to the stage list. + * @param timestamp The expression representing the timestamp. + * @param unit The expression evaluates to unit of time, must be one of 'microsecond', 'millisecond', 'second', 'minute', 'hour', 'day'. + * @param amount The expression evaluates to amount of the unit. + * @return A new {@code Expr} representing the resulting timestamp. */ - aggregate( - accumulator: AggregateWithAlias, - ...additionalAccumulators: AggregateWithAlias[] - ): Pipeline; + export function timestampAdd( + timestamp: Expr, + unit: Expr, + amount: Expr + ): FunctionExpr; + /** - * Performs optionally grouped aggregation operations on the documents from previous stages. - * - *

      This stage allows you to calculate aggregate values over a set of documents, optionally - * grouped by one or more fields or functions. You can specify: - * - *

        - *
      • **Grouping Fields or Functions:** One or more fields or functions to group the documents - * by. For each distinct combination of values in these fields, a separate group is created. - * If no grouping fields are provided, a single group containing all documents is used. Not - * specifying groups is the same as putting the entire inputs into one group.
      • - *
      • **Accumulators:** One or more accumulation operations to perform within each group. These - * are defined using {@link AggregateWithAlias} expressions, which are typically created by - * calling {@link Expr#as} on {@link AggregateFunction} instances. Each aggregation - * calculates a value (e.g., sum, average, count) based on the documents within its group.
      • - *
      + * @beta * - *

      Example: + * Creates an expression that adds a specified amount of time to a timestamp. * * ```typescript - * // Calculate the average rating for each genre. - * firestore.pipeline().collection("books") - * .aggregate({ - * accumulators: [avg(field("rating")).as("avg_rating")] - * groups: ["genre"] - * }); + * // Add 1 day to the 'timestamp' field. + * timestampAdd(field("timestamp"), "day", 1); * ``` * - * @param options An object that specifies the accumulators - * and optional grouping fields to perform. - * @return A new {@code Pipeline} object with this stage appended to the stage - * list. + * @param timestamp The expression representing the timestamp. + * @param unit The unit of time to add (e.g., "day", "hour"). + * @param amount The amount of time to add. + * @return A new {@code Expr} representing the resulting timestamp. */ - aggregate(options: { - accumulators: AggregateWithAlias[]; - groups?: Array; - }): Pipeline; - - findNearest(options: FindNearestOptions): Pipeline; + export function timestampAdd( + timestamp: Expr, + unit: + | 'microsecond' + | 'millisecond' + | 'second' + | 'minute' + | 'hour' + | 'day', + amount: number + ): FunctionExpr; /** - * Fully overwrites all fields in a document with those coming from a nested map. - * - *

      This stage allows you to emit a map value as a document. Each key of the map becomes a field - * on the document that contains the corresponding value. + * @beta * - *

      Example: + * Creates an expression that adds a specified amount of time to a timestamp represented by a field. * * ```typescript - * // Input. - * // { - * // 'name': 'John Doe Jr.', - * // 'parents': { - * // 'father': 'John Doe Sr.', - * // 'mother': 'Jane Doe' - * // } - * // } - * - * // Emit parents as document. - * firestore.pipeline().collection('people').replaceWith('parents'); - * - * // Output - * // { - * // 'father': 'John Doe Sr.', - * // 'mother': 'Jane Doe' - * // } + * // Add 1 day to the 'timestamp' field. + * timestampAdd("timestamp", "day", 1); * ``` * - * @param fieldName The {@link Field} field containing the nested map. - * @return A new {@code Pipeline} object with this stage appended to the stage list. + * @param fieldName The name of the field representing the timestamp. + * @param unit The unit of time to add (e.g., "day", "hour"). + * @param amount The amount of time to add. + * @return A new {@code Expr} representing the resulting timestamp. */ - replaceWith(fieldName: string): Pipeline; + export function timestampAdd( + fieldName: string, + unit: + | 'microsecond' + | 'millisecond' + | 'second' + | 'minute' + | 'hour' + | 'day', + amount: number + ): FunctionExpr; /** - * Fully overwrites all fields in a document with those coming from a map. - * - *

      This stage allows you to emit a map value as a document. Each key of the map becomes a field - * on the document that contains the corresponding value. + * @beta * - *

      Example: + * Creates an expression that subtracts a specified amount of time from a timestamp. * * ```typescript - * // Input. - * // { - * // 'name': 'John Doe Jr.', - * // 'parents': { - * // 'father': 'John Doe Sr.', - * // 'mother': 'Jane Doe' - * // } - * // } - * - * // Emit parents as document. - * firestore.pipeline().collection('people').replaceWith(map({ - * foo: 'bar', - * info: { - * name: field('name') - * } - * })); - * - * // Output - * // { - * // 'father': 'John Doe Sr.', - * // 'mother': 'Jane Doe' - * // } + * // Subtract some duration determined by field 'unit' and 'amount' from the 'timestamp' field. + * timestampSub(field("timestamp"), field("unit"), field("amount")); * ``` * - * @param expr An {@link Expr} that when returned evaluates to a map. - * @return A new {@code Pipeline} object with this stage appended to the stage list. + * @param timestamp The expression representing the timestamp. + * @param unit The expression evaluates to unit of time, must be one of 'microsecond', 'millisecond', 'second', 'minute', 'hour', 'day'. + * @param amount The expression evaluates to amount of the unit. + * @return A new {@code Expr} representing the resulting timestamp. */ - replaceWith(expr: Expr): Pipeline; + export function timestampSub( + timestamp: Expr, + unit: Expr, + amount: Expr + ): FunctionExpr; /** - * Performs a pseudo-random sampling of the documents from the previous stage. - * - *

      This stage will filter documents pseudo-randomly. The parameter specifies how number of - * documents to be returned. + * @beta * - *

      Examples: + * Creates an expression that subtracts a specified amount of time from a timestamp. * * ```typescript - * // Sample 25 books, if available. - * firestore.pipeline().collection('books') - * .sample(25); + * // Subtract 1 day from the 'timestamp' field. + * timestampSub(field("timestamp"), "day", 1); * ``` * - * @param documents The number of documents to sample. - * @return A new {@code Pipeline} object with this stage appended to the stage list. + * @param timestamp The expression representing the timestamp. + * @param unit The unit of time to subtract (e.g., "day", "hour"). + * @param amount The amount of time to subtract. + * @return A new {@code Expr} representing the resulting timestamp. */ - sample(documents: number): Pipeline; + export function timestampSub( + timestamp: Expr, + unit: + | 'microsecond' + | 'millisecond' + | 'second' + | 'minute' + | 'hour' + | 'day', + amount: number + ): FunctionExpr; /** - * Performs a pseudo-random sampling of the documents from the previous stage. - * - *

      This stage will filter documents pseudo-randomly. The 'options' parameter specifies how - * sampling will be performed. See {@code SampleOptions} for more information. - * - *

      Examples: + * @beta * - * // Sample 10 books, if available. - * firestore.pipeline().collection("books") - * .sample({ documents: 10 }); + * Creates an expression that subtracts a specified amount of time from a timestamp represented by a field. * - * // Sample 50% of books. - * firestore.pipeline().collection("books") - * .sample({ percentage: 0.5 }); + * ```typescript + * // Subtract 1 day from the 'timestamp' field. + * timestampSub("timestamp", "day", 1); + * ``` * - * @param options The {@code SampleOptions} specifies how sampling is performed. - * @return A new {@code Pipeline} object with this stage appended to the stage list. + * @param fieldName The name of the field representing the timestamp. + * @param unit The unit of time to subtract (e.g., "day", "hour"). + * @param amount The amount of time to subtract. + * @return A new {@code Expr} representing the resulting timestamp. */ - sample(options: {percentage: number} | {documents: number}): Pipeline; + export function timestampSub( + fieldName: string, + unit: + | 'microsecond' + | 'millisecond' + | 'second' + | 'minute' + | 'hour' + | 'day', + amount: number + ): FunctionExpr; /** - * Sorts the documents from previous stages based on one or more {@link Ordering} criteria. - * - *

      This stage allows you to order the results of your pipeline. You can specify multiple {@link - * Ordering} instances to sort by multiple fields in ascending or descending order. If documents - * have the same value for a field used for sorting, the next specified ordering will be used. If - * all orderings result in equal comparison, the documents are considered equal and the order is - * unspecified. + * @beta * - *

      Example: + * Creates an expression that performs a logical 'AND' operation on multiple filter conditions. * * ```typescript - * // Sort books by rating in descending order, and then by title in ascending order for books - * // with the same rating - * firestore.pipeline().collection("books") - * .sort( - * Ordering.of(field("rating")).descending(), - * Ordering.of(field("title")) // Ascending order is the default - * ); + * // Check if the 'age' field is greater than 18 AND the 'city' field is "London" AND + * // the 'status' field is "active" + * const condition = and(gt("age", 18), eq("city", "London"), eq("status", "active")); * ``` * - * @param ordering The first {@link Ordering} instance specifying the sorting criteria. - * @param additionalOrderings Optional additional {@link Ordering} instances specifying the additional sorting criteria. - * @return A new {@code Pipeline} object with this stage appended to the stage list. + * @param first The first filter condition. + * @param second The second filter condition. + * @param more Additional filter conditions to 'AND' together. + * @return A new {@code Expr} representing the logical 'AND' operation. */ - sort(ordering: Ordering, ...additionalOrderings: Ordering[]): Pipeline; + export function and( + first: BooleanExpr, + second: BooleanExpr, + ...more: BooleanExpr[] + ): BooleanExpr; /** - * Performs union of all documents from two pipelines, including duplicates. - * - *

      This stage will pass through documents from previous stage, and also pass through documents - * from previous stage of the `other` {@code Pipeline} given in parameter. The order of documents - * emitted from this stage is undefined. + * @beta * - *

      Example: + * Creates an expression that performs a logical 'OR' operation on multiple filter conditions. * * ```typescript - * // Emit documents from books collection and magazines collection. - * firestore.pipeline().collection('books') - * .union(firestore.pipeline().collection('magazines')); + * // Check if the 'age' field is greater than 18 OR the 'city' field is "London" OR + * // the 'status' field is "active" + * const condition = or(gt("age", 18), eq("city", "London"), eq("status", "active")); * ``` * - * @param other The other {@code Pipeline} that is part of union. - * @return A new {@code Pipeline} object with this stage appended to the stage list. + * @param first The first filter condition. + * @param second The second filter condition. + * @param more Additional filter conditions to 'OR' together. + * @return A new {@code Expr} representing the logical 'OR' operation. */ - union(other: Pipeline): Pipeline; + export function or( + first: BooleanExpr, + second: BooleanExpr, + ...more: BooleanExpr[] + ): BooleanExpr; /** - * Produces a document for each element in an input array. - * - * For each previous stage document, this stage will emit zero or more augmented documents. The - * input array specified by the `selectable` parameter, will emit an augmented document for each input array element. The input array element will - * augment the previous stage document by setting the `alias` field with the array element value. - * - * When `selectable` evaluates to a non-array value (ex: number, null, absent), then the stage becomes a no-op for - * the current input document, returning it as is with the `alias` field absent. - * - * No documents are emitted when `selectable` evaluates to an empty array. + * @beta * - * Example: + * Creates an {@link Ordering} that sorts documents in ascending order based on an expression. * * ```typescript - * // Input: - * // { "title": "The Hitchhiker's Guide to the Galaxy", "tags": [ "comedy", "space", "adventure" ], ... } - * - * // Emit a book document for each tag of the book. - * firestore.pipeline().collection("books") - * .unnest(field("tags").as('tag'), 'tagIndex'); - * - * // Output: - * // { "title": "The Hitchhiker's Guide to the Galaxy", "tag": "comedy", "tagIndex": 0, ... } - * // { "title": "The Hitchhiker's Guide to the Galaxy", "tag": "space", "tagIndex": 1, ... } - * // { "title": "The Hitchhiker's Guide to the Galaxy", "tag": "adventure", "tagIndex": 2, ... } + * // Sort documents by the 'name' field in lowercase in ascending order + * pipeline().collection("users") + * .sort(ascending(field("name").toLower())); * ``` * - * @param selectable A selectable expression defining the field to unnest and the alias to use for each un-nested element in the output documents. - * @param indexField An optional string value specifying the field path to write the offset (starting at zero) into the array the un-nested element is from - * @return A new {@code Pipeline} object with this stage appended to the stage list. + * @param expr The expression to create an ascending ordering for. + * @return A new `Ordering` for ascending sorting. */ - unnest(selectable: Selectable, indexField?: string): Pipeline; + export function ascending(expr: Expr): Ordering; /** - * Adds a generic stage to the pipeline. - * - *

      This method provides a flexible way to extend the pipeline's functionality by adding custom - * stages. Each generic stage is defined by a unique `name` and a set of `params` that control its - * behavior. + * @beta * - *

      Example (Assuming there is no "where" stage available in SDK): + * Creates an {@link Ordering} that sorts documents in ascending order based on a field. * * ```typescript - * // Assume we don't have a built-in "where" stage - * firestore.pipeline().collection("books") - * .genericStage("where", [Field.of("published").lt(1900)]) // Custom "where" stage - * .select("title", "author"); + * // Sort documents by the 'name' field in ascending order + * pipeline().collection("users") + * .sort(ascending("name")); * ``` * - * @param name The unique name of the generic stage to add. - * @param params A list of parameters to configure the generic stage's behavior. - * @return A new {@code Pipeline} object with this stage appended to the stage list. + * @param fieldName The field to create an ascending ordering for. + * @return A new `Ordering` for ascending sorting. */ - genericStage(name: string, params: any[]): Pipeline; + export function ascending(fieldName: string): Ordering; + /** - * Executes this pipeline and returns a Promise to represent the asynchronous operation. - * - *

      The returned Promise can be used to track the progress of the pipeline execution - * and retrieve the results (or handle any errors) asynchronously. - * - *

      The pipeline results are returned as a list of {@link PipelineResult} objects. Each {@link - * PipelineResult} typically represents a single key/value map that has passed through all the - * stages of the pipeline, however this might differ depending on the stages involved in the - * pipeline. For example: - * - *

        - *
      • If there are no stages or only transformation stages, each {@link PipelineResult} - * represents a single document.
      • - *
      • If there is an aggregation, only a single {@link PipelineResult} is returned, - * representing the aggregated results over the entire dataset .
      • - *
      • If there is an aggregation stage with grouping, each {@link PipelineResult} represents a - * distinct group and its associated aggregated values.
      • - *
      + * @beta * - *

      Example: + * Creates an {@link Ordering} that sorts documents in descending order based on an expression. * * ```typescript - * const futureResults = await firestore.pipeline().collection("books") - * .where(gt(Field.of("rating"), 4.5)) - * .select("title", "author", "rating") - * .execute(); + * // Sort documents by the 'name' field in lowercase in descending order + * pipeline().collection("users") + * .sort(descending(field("name").toLower())); * ``` * - * @return A Promise representing the asynchronous pipeline execution. + * @param expr The expression to create a descending ordering for. + * @return A new `Ordering` for descending sorting. */ - execute(): Promise; + export function descending(expr: Expr): Ordering; /** - * Executes this pipeline and streams the results as {@link PipelineResult}s. + * @beta * - * @returns {Stream.} A stream of - * PipelineResult. + * Creates an {@link Ordering} that sorts documents in descending order based on a field. * - * @example * ```typescript - * firestore.pipeline().collection("books") - * .where(gt(Field.of("rating"), 4.5)) - * .select("title", "author", "rating") - * .stream() - * .on('data', (pipelineResult) => {}) - * .on('end', () => {}); + * // Sort documents by the 'name' field in descending order + * pipeline().collection("users") + * .sort(descending("name")); * ``` + * + * @param fieldName The field to create a descending ordering for. + * @return A new `Ordering` for descending sorting. */ - stream(): NodeJS.ReadableStream; - } - /** - * TODO(docs) - */ - export class PipelineSnapshot { - /** - * The Pipeline on which you called `execute()` in order to get this - * `PipelineSnapshot`. - */ - get pipeline(): Pipeline; - - /** An array of all the results in the `PipelineSnapshot`. */ - get results(): PipelineResult[]; + export function descending(fieldName: string): Ordering; /** - * The time at which the pipeline producing this result is executed. + * @beta * - * @type {Timestamp} - * @readonly + * Represents an ordering criterion for sorting documents in a Firestore pipeline. * + * You create `Ordering` instances using the `ascending` and `descending` helper functions. */ - get executionTime(): Timestamp; - } - - /** - * @beta - * - * A PipelineResult contains data read from a Firestore Pipeline. The data can be extracted with the - * {@link #data()} or {@link #get(String)} methods. - * - *

      If the PipelineResult represents a non-document result, `ref` will return a undefined - * value. - */ - export class PipelineResult { - readonly executionTime: Timestamp; - readonly createTime: Timestamp | undefined; - readonly updateTime: Timestamp | undefined; - - /** - * The reference of the document, if it is a document; otherwise `undefined`. - */ - // get ref(): DocumentReference | undefined; + export class Ordering { + readonly expr: Expr; + readonly direction: 'ascending' | 'descending'; + } /** - * The ID of the document for which this PipelineResult contains data, if it is a document; otherwise `undefined`. - * - * @type {string} - * @readonly - * + * @beta */ - get id(): string | undefined; - - get ref(): DocumentReference | undefined; + export interface Stage { + name: string; + } /** - * Retrieves all fields in the result as an object. Returns 'undefined' if - * the document doesn't exist. - * - * @returns {T|undefined} An object containing all fields in the document or - * 'undefined' if the document doesn't exist. - * - * @example - * ``` - * let p = firestore.pipeline().collection('col'); - * - * p.execute().then(results => { - * let data = results[0].data(); - * console.log(`Retrieved data: ${JSON.stringify(data)}`); - * }); - * ``` + * @beta */ - data(): DocumentData | undefined; + export class Aggregate implements Stage { + name: string; + } /** - * Retrieves the field specified by `field`. - * - * @param {string|FieldPath} field The field path - * (e.g. 'foo' or 'foo.bar') to a specific field. - * @returns {*} The data at the specified field location or undefined if no - * such field exists. - * - * @example - * ``` - * let p = firestore.pipeline().collection('col'); - * - * p.execute().then(results => { - * let field = results[0].get('a.b'); - * console.log(`Retrieved field value: ${field}`); - * }); - * ``` + * @beta */ - // We deliberately use `any` in the external API to not impose type-checking - // on end users. - // eslint-disable-next-line @typescript-eslint/no-explicit-any - get(field: string | FieldPath): any; + export class Where implements Stage { + name: string; + } /** - * Returns true if the document's data and path in this `PipelineResult` is - * equal to the provided value. - * - * @param {*} other The value to compare against. - * @return {boolean} true if this `PipelineResult` is equal to the provided - * value. + * @beta */ - isEqual(other: PipelineResult): boolean; - } + export type FindNearestOptions = { + field: Field | string; + vectorValue: VectorValue | number[]; + distanceMeasure: 'euclidean' | 'cosine' | 'dot_product'; + limit?: number; + distanceField?: string; + }; - /** - * Specifies the behavior of the {@link VectorQuery} generated by a call to {@link Query.findNearest}. - */ - export interface VectorQueryOptions { /** - * A string or {@link FieldPath} specifying the vector field to search on. + * @beta */ - vectorField: string | FieldPath; + export class FindNearest implements Stage { + name: string; + } /** - * The {@link VectorValue} used to measure the distance from `vectorField` values in the documents. + * @beta */ - queryVector: VectorValue | Array; + export class Replace implements Stage { + name: string; + } /** - * Specifies the upper bound of documents to return, must be a positive integer with a maximum value of 1000. + * @beta */ - limit: number; + export interface UnnestOptions { + field: Selectable | string; + alias: Field | string; + indexField?: string; + } /** - * Specifies what type of distance is calculated when performing the query. + * Represents the source of a Firestore {@link Pipeline}. + * @beta */ - distanceMeasure: 'EUCLIDEAN' | 'COSINE' | 'DOT_PRODUCT'; + export class PipelineSource { + /** + * Specifies the source as a collection. + * + * @param collectionPath The path to the collection. + * @return A new Pipeline object with the collection as the source. + */ + collection(collectionPath: string | CollectionReference): Pipeline; + + /** + * Specifies the source as a collection group. + * + * @param collectionId The ID of the collection group. + * @return A new Pipeline object with the collection group as the source. + */ + collectionGroup(collectionId: string): Pipeline; + + /** + * Specifies the source as a database. + * + * @return A new Pipeline object with the database as the source. + */ + database(): Pipeline; + + /** + * Specifies the source as a set of documents. + * + * @param docs The document references. + * @return A new Pipeline object with the documents as the source. + */ + documents(docs: Array): Pipeline; + + /** + * Convert the given Query into an equivalent Pipeline. + * + * @param query A Query to be converted into a Pipeline. + * + * @throws {@FirestoreError} Thrown if any of the provided DocumentReferences target a different project or database than the pipeline. + */ + createFrom(query: Query): Pipeline; + } /** - * Optionally specifies the name of a field that will be set on each returned DocumentSnapshot, - * which will contain the computed distance for the document. + * @beta + * + * The Pipeline class provides a flexible and expressive framework for building complex data + * transformation and query pipelines for Firestore. + * + * A pipeline takes data sources, such as Firestore collections or collection groups, and applies + * a series of stages that are chained together. Each stage takes the output from the previous stage + * (or the data source) and produces an output for the next stage (or as the final output of the + * pipeline). + * + * Expressions can be used within each stage to filter and transform data through the stage. + * + * NOTE: The chained stages do not prescribe exactly how Firestore will execute the pipeline. + * Instead, Firestore only guarantees that the result is the same as if the chained stages were + * executed in order. + * + * Usage Examples: + * + * ```typescript + * const db: Firestore; // Assumes a valid firestore instance. + * + * // Example 1: Select specific fields and rename 'rating' to 'bookRating' + * const results1 = await db.pipeline() + * .collection("books") + * .select("title", "author", Field.of("rating").as("bookRating")) + * .execute(); + * + * // Example 2: Filter documents where 'genre' is "Science Fiction" and 'published' is after 1950 + * const results2 = await db.pipeline() + * .collection("books") + * .where(and(Field.of("genre").eq("Science Fiction"), Field.of("published").gt(1950))) + * .execute(); + * + * // Example 3: Calculate the average rating of books published after 1980 + * const results3 = await db.pipeline() + * .collection("books") + * .where(Field.of("published").gt(1980)) + * .aggregate(avg(Field.of("rating")).as("averageRating")) + * .execute(); + * ``` */ - distanceResultField?: string | FieldPath; + export class Pipeline { + /** + * Adds new fields to outputs from previous stages. + * + * This stage allows you to compute values on-the-fly based on existing data from previous + * stages or constants. You can use this to create new fields or overwrite existing ones (if there + * is name overlaps). + * + * The added fields are defined using {@link Selectable}s, which can be: + * + * - {@link Field}: References an existing document field. + * - {@link Expr}: Either a literal value (see {@link Constant}) or a computed value + * (see {@FunctionExpr}) with an assigned alias using {@link Expr#as}. + * + * Example: + * + * ```typescript + * firestore.pipeline().collection("books") + * .addFields( + * field("rating").as("bookRating"), // Rename 'rating' to 'bookRating' + * add(5, field("quantity")).as("totalCost") // Calculate 'totalCost' + * ); + * ``` + * + * @param field The first field to add to the documents, specified as a {@link Selectable}. + * @param additionalFields Optional additional fields to add to the documents, specified as {@link Selectable}s. + * @return A new Pipeline object with this stage appended to the stage list. + */ + addFields(field: Selectable, ...additionalFields: Selectable[]): Pipeline; + + /** + * Remove fields from outputs of previous stages. + * + * Example: + * + * ```typescript + * firestore.pipeline().collection('books') + * // removes field 'rating' and 'cost' from the previous stage outputs. + * .removeFields( + * field('rating'), + * 'cost' + * ); + * ``` + * + * @param fieldValue The first field to remove. + * @param additionalFields Optional additional fields to remove. + * @return A new Pipeline object with this stage appended to the stage list. + */ + removeFields( + fieldValue: Field | string, + ...additionalFields: Array + ): Pipeline; + + /** + * Selects or creates a set of fields from the outputs of previous stages. + * + *

      The selected fields are defined using {@link Selectable} expressions, which can be: + * + *

        + *
      • {@code string}: Name of an existing field
      • + *
      • {@link Field}: References an existing field.
      • + *
      • {@link Function}: Represents the result of a function with an assigned alias name using + * {@link Expr#as}
      • + *
      + * + *

      If no selections are provided, the output of this stage is empty. Use {@link + * Pipeline#addFields} instead if only additions are + * desired. + * + *

      Example: + * + * ```typescript + * firestore.pipeline().collection("books") + * .select( + * "firstName", + * field("lastName"), + * field("address").toUppercase().as("upperAddress"), + * ); + * ``` + * + * @param selection The first field to include in the output documents, specified as {@link + * Selectable} expression or string value representing the field name. + * @param additionalSelections Optional additional fields to include in the output documents, specified as {@link + * Selectable} expressions or {@code string} values representing field names. + * @return A new Pipeline object with this stage appended to the stage list. + */ + select( + selection: Selectable | string, + ...additionalSelections: Array + ): Pipeline; + + /** + * Filters the documents from previous stages to only include those matching the specified {@link + * BooleanExpr}. + * + *

      This stage allows you to apply conditions to the data, similar to a "WHERE" clause in SQL. + * You can filter documents based on their field values, using implementations of {@link + * BooleanExpr}, typically including but not limited to: + * + *

        + *
      • field comparators: {@link Function#eq}, {@link Function#lt} (less than), {@link + * Function#gt} (greater than), etc.
      • + *
      • logical operators: {@link Function#and}, {@link Function#or}, {@link Function#not}, etc.
      • + *
      • advanced functions: {@link Function#regexMatch}, {@link + * Function#arrayContains}, etc.
      • + *
      + * + *

      Example: + * + * ```typescript + * firestore.pipeline().collection("books") + * .where( + * and( + * gt(field("rating"), 4.0), // Filter for ratings greater than 4.0 + * field("genre").eq("Science Fiction") // Equivalent to gt("genre", "Science Fiction") + * ) + * ); + * ``` + * + * @param condition The {@link BooleanExpr} to apply. + * @return A new Pipeline object with this stage appended to the stage list. + */ + where(condition: BooleanExpr): Pipeline; + + /** + * Skips the first `offset` number of documents from the results of previous stages. + * + *

      This stage is useful for implementing pagination in your pipelines, allowing you to retrieve + * results in chunks. It is typically used in conjunction with {@link #limit} to control the + * size of each page. + * + *

      Example: + * + * ```typescript + * // Retrieve the second page of 20 results + * firestore.pipeline().collection("books") + * .sort(Field.of("published").descending()) + * .offset(20) // Skip the first 20 results + * .limit(20); // Take the next 20 results + * ``` + * + * @param offset The number of documents to skip. + * @return A new Pipeline object with this stage appended to the stage list. + */ + offset(offset: number): Pipeline; + + /** + * Limits the maximum number of documents returned by previous stages to `limit`. + * + *

      This stage is particularly useful when you want to retrieve a controlled subset of data from + * a potentially large result set. It's often used for: + * + *

        + *
      • **Pagination:** In combination with {@link #offset} to retrieve specific pages of + * results.
      • + *
      • **Limiting Data Retrieval:** To prevent excessive data transfer and improve performance, + * especially when dealing with large collections.
      • + *
      + * + *

      Example: + * + * ```typescript + * // Limit the results to the top 10 highest-rated books + * firestore.pipeline().collection("books") + * .sort(Field.of("rating").descending()) + * .limit(10); + * ``` + * + * @param limit The maximum number of documents to return. + * @return A new Pipeline object with this stage appended to the stage list. + */ + limit(limit: number): Pipeline; + + /** + * Returns a set of distinct values from the inputs to this stage. + * + * This stage runs through the results from previous stages to include only results with + * unique combinations of {@link Expr} values ({@link Field}, {@link Function}, etc). + * + * The parameters to this stage are defined using {@link Selectable} expressions or strings: + * + * - {@code string}: Name of an existing field + * - {@link Field}: References an existing document field. + * - {@link ExprWithAlias}: Represents the result of a function with an assigned alias name + * using {@link Expr#as}. + * + * Example: + * + * ```typescript + * // Get a list of unique author names in uppercase and genre combinations. + * firestore.pipeline().collection("books") + * .distinct(toUppercase(field("author")).as("authorName"), field("genre"), "publishedAt") + * .select("authorName"); + * ``` + * + * @param group The {@link Selectable} expression or field name to consider when determining + * distinct value combinations. + * @param additionalGroups Optional additional {@link Selectable} expressions to consider when determining distinct + * value combinations or strings representing field names. + * @return A new {@code Pipeline} object with this stage appended to the stage list. + */ + distinct( + group: string | Selectable, + ...additionalGroups: Array + ): Pipeline; + + /** + * Performs aggregation operations on the documents from previous stages. + * + *

      This stage allows you to calculate aggregate values over a set of documents. You define the + * aggregations to perform using {@link AggregateWithAlias} expressions which are typically results of + * calling {@link Expr#as} on {@link AggregateFunction} instances. + * + *

      Example: + * + * ```typescript + * // Calculate the average rating and the total number of books + * firestore.pipeline().collection("books") + * .aggregate( + * field("rating").avg().as("averageRating"), + * countAll().as("totalBooks") + * ); + * ``` + * + * @param accumulator The first {@link AggregateWithAlias}, wrapping an {@link AggregateFunction} + * and providing a name for the accumulated results. + * @param additionalAccumulators Optional additional {@link AggregateWithAlias}, each wrapping an {@link AggregateFunction} + * and providing a name for the accumulated results. + * @return A new Pipeline object with this stage appended to the stage list. + */ + aggregate( + accumulator: AggregateWithAlias, + ...additionalAccumulators: AggregateWithAlias[] + ): Pipeline; + /** + * Performs optionally grouped aggregation operations on the documents from previous stages. + * + *

      This stage allows you to calculate aggregate values over a set of documents, optionally + * grouped by one or more fields or functions. You can specify: + * + *

        + *
      • **Grouping Fields or Functions:** One or more fields or functions to group the documents + * by. For each distinct combination of values in these fields, a separate group is created. + * If no grouping fields are provided, a single group containing all documents is used. Not + * specifying groups is the same as putting the entire inputs into one group.
      • + *
      • **Accumulators:** One or more accumulation operations to perform within each group. These + * are defined using {@link AggregateWithAlias} expressions, which are typically created by + * calling {@link Expr#as} on {@link AggregateFunction} instances. Each aggregation + * calculates a value (e.g., sum, average, count) based on the documents within its group.
      • + *
      + * + *

      Example: + * + * ```typescript + * // Calculate the average rating for each genre. + * firestore.pipeline().collection("books") + * .aggregate({ + * accumulators: [avg(field("rating")).as("avg_rating")] + * groups: ["genre"] + * }); + * ``` + * + * @param options An object that specifies the accumulators + * and optional grouping fields to perform. + * @return A new {@code Pipeline} object with this stage appended to the stage + * list. + */ + aggregate(options: { + accumulators: AggregateWithAlias[]; + groups?: Array; + }): Pipeline; + + findNearest(options: FindNearestOptions): Pipeline; + + /** + * Fully overwrites all fields in a document with those coming from a nested map. + * + *

      This stage allows you to emit a map value as a document. Each key of the map becomes a field + * on the document that contains the corresponding value. + * + *

      Example: + * + * ```typescript + * // Input. + * // { + * // 'name': 'John Doe Jr.', + * // 'parents': { + * // 'father': 'John Doe Sr.', + * // 'mother': 'Jane Doe' + * // } + * // } + * + * // Emit parents as document. + * firestore.pipeline().collection('people').replaceWith('parents'); + * + * // Output + * // { + * // 'father': 'John Doe Sr.', + * // 'mother': 'Jane Doe' + * // } + * ``` + * + * @param fieldName The {@link Field} field containing the nested map. + * @return A new {@code Pipeline} object with this stage appended to the stage list. + */ + replaceWith(fieldName: string): Pipeline; + + /** + * Fully overwrites all fields in a document with those coming from a map. + * + *

      This stage allows you to emit a map value as a document. Each key of the map becomes a field + * on the document that contains the corresponding value. + * + *

      Example: + * + * ```typescript + * // Input. + * // { + * // 'name': 'John Doe Jr.', + * // 'parents': { + * // 'father': 'John Doe Sr.', + * // 'mother': 'Jane Doe' + * // } + * // } + * + * // Emit parents as document. + * firestore.pipeline().collection('people').replaceWith(map({ + * foo: 'bar', + * info: { + * name: field('name') + * } + * })); + * + * // Output + * // { + * // 'father': 'John Doe Sr.', + * // 'mother': 'Jane Doe' + * // } + * ``` + * + * @param expr An {@link Expr} that when returned evaluates to a map. + * @return A new {@code Pipeline} object with this stage appended to the stage list. + */ + replaceWith(expr: Expr): Pipeline; + + /** + * Performs a pseudo-random sampling of the documents from the previous stage. + * + *

      This stage will filter documents pseudo-randomly. The parameter specifies how number of + * documents to be returned. + * + *

      Examples: + * + * ```typescript + * // Sample 25 books, if available. + * firestore.pipeline().collection('books') + * .sample(25); + * ``` + * + * @param documents The number of documents to sample. + * @return A new {@code Pipeline} object with this stage appended to the stage list. + */ + sample(documents: number): Pipeline; + + /** + * Performs a pseudo-random sampling of the documents from the previous stage. + * + *

      This stage will filter documents pseudo-randomly. The 'options' parameter specifies how + * sampling will be performed. See {@code SampleOptions} for more information. + * + *

      Examples: + * + * // Sample 10 books, if available. + * firestore.pipeline().collection("books") + * .sample({ documents: 10 }); + * + * // Sample 50% of books. + * firestore.pipeline().collection("books") + * .sample({ percentage: 0.5 }); + * + * @param options The {@code SampleOptions} specifies how sampling is performed. + * @return A new {@code Pipeline} object with this stage appended to the stage list. + */ + sample(options: {percentage: number} | {documents: number}): Pipeline; + + /** + * Sorts the documents from previous stages based on one or more {@link Ordering} criteria. + * + *

      This stage allows you to order the results of your pipeline. You can specify multiple {@link + * Ordering} instances to sort by multiple fields in ascending or descending order. If documents + * have the same value for a field used for sorting, the next specified ordering will be used. If + * all orderings result in equal comparison, the documents are considered equal and the order is + * unspecified. + * + *

      Example: + * + * ```typescript + * // Sort books by rating in descending order, and then by title in ascending order for books + * // with the same rating + * firestore.pipeline().collection("books") + * .sort( + * Ordering.of(field("rating")).descending(), + * Ordering.of(field("title")) // Ascending order is the default + * ); + * ``` + * + * @param ordering The first {@link Ordering} instance specifying the sorting criteria. + * @param additionalOrderings Optional additional {@link Ordering} instances specifying the additional sorting criteria. + * @return A new {@code Pipeline} object with this stage appended to the stage list. + */ + sort(ordering: Ordering, ...additionalOrderings: Ordering[]): Pipeline; + + /** + * Performs union of all documents from two pipelines, including duplicates. + * + *

      This stage will pass through documents from previous stage, and also pass through documents + * from previous stage of the `other` {@code Pipeline} given in parameter. The order of documents + * emitted from this stage is undefined. + * + *

      Example: + * + * ```typescript + * // Emit documents from books collection and magazines collection. + * firestore.pipeline().collection('books') + * .union(firestore.pipeline().collection('magazines')); + * ``` + * + * @param other The other {@code Pipeline} that is part of union. + * @return A new {@code Pipeline} object with this stage appended to the stage list. + */ + union(other: Pipeline): Pipeline; + + /** + * Produces a document for each element in an input array. + * + * For each previous stage document, this stage will emit zero or more augmented documents. The + * input array specified by the `selectable` parameter, will emit an augmented document for each input array element. The input array element will + * augment the previous stage document by setting the `alias` field with the array element value. + * + * When `selectable` evaluates to a non-array value (ex: number, null, absent), then the stage becomes a no-op for + * the current input document, returning it as is with the `alias` field absent. + * + * No documents are emitted when `selectable` evaluates to an empty array. + * + * Example: + * + * ```typescript + * // Input: + * // { "title": "The Hitchhiker's Guide to the Galaxy", "tags": [ "comedy", "space", "adventure" ], ... } + * + * // Emit a book document for each tag of the book. + * firestore.pipeline().collection("books") + * .unnest(field("tags").as('tag'), 'tagIndex'); + * + * // Output: + * // { "title": "The Hitchhiker's Guide to the Galaxy", "tag": "comedy", "tagIndex": 0, ... } + * // { "title": "The Hitchhiker's Guide to the Galaxy", "tag": "space", "tagIndex": 1, ... } + * // { "title": "The Hitchhiker's Guide to the Galaxy", "tag": "adventure", "tagIndex": 2, ... } + * ``` + * + * @param selectable A selectable expression defining the field to unnest and the alias to use for each un-nested element in the output documents. + * @param indexField An optional string value specifying the field path to write the offset (starting at zero) into the array the un-nested element is from + * @return A new {@code Pipeline} object with this stage appended to the stage list. + */ + unnest(selectable: Selectable, indexField?: string): Pipeline; + + /** + * Adds a generic stage to the pipeline. + * + *

      This method provides a flexible way to extend the pipeline's functionality by adding custom + * stages. Each generic stage is defined by a unique `name` and a set of `params` that control its + * behavior. + * + *

      Example (Assuming there is no "where" stage available in SDK): + * + * ```typescript + * // Assume we don't have a built-in "where" stage + * firestore.pipeline().collection("books") + * .genericStage("where", [Field.of("published").lt(1900)]) // Custom "where" stage + * .select("title", "author"); + * ``` + * + * @param name The unique name of the generic stage to add. + * @param params A list of parameters to configure the generic stage's behavior. + * @return A new {@code Pipeline} object with this stage appended to the stage list. + */ + genericStage(name: string, params: any[]): Pipeline; + /** + * Executes this pipeline and returns a Promise to represent the asynchronous operation. + * + *

      The returned Promise can be used to track the progress of the pipeline execution + * and retrieve the results (or handle any errors) asynchronously. + * + *

      The pipeline results are returned in a {@link PipelineSnapshot} object, which contains a list of + * {@link PipelineResult} objects. Each {@link PipelineResult} typically represents a single key/value map that + * has passed through all the stages of the pipeline, however this might differ depending on the stages involved + * in the pipeline. For example: + * + *

        + *
      • If there are no stages or only transformation stages, each {@link PipelineResult} + * represents a single document.
      • + *
      • If there is an aggregation, only a single {@link PipelineResult} is returned, + * representing the aggregated results over the entire dataset .
      • + *
      • If there is an aggregation stage with grouping, each {@link PipelineResult} represents a + * distinct group and its associated aggregated values.
      • + *
      + * + *

      Example: + * + * ```typescript + * const futureResults = await firestore.pipeline().collection("books") + * .where(gt(Field.of("rating"), 4.5)) + * .select("title", "author", "rating") + * .execute(); + * ``` + * + * @return A Promise representing the asynchronous pipeline execution. + */ + execute(): Promise; + + /** + * Executes this pipeline and streams the results as {@link PipelineResult}s. + * + * @returns {Stream.} A stream of + * PipelineResult. + * + * @example + * ```typescript + * firestore.pipeline().collection("books") + * .where(gt(Field.of("rating"), 4.5)) + * .select("title", "author", "rating") + * .stream() + * .on('data', (pipelineResult) => {}) + * .on('end', () => {}); + * ``` + */ + stream(): NodeJS.ReadableStream; + } + /** + * TODO(docs) + */ + export class PipelineSnapshot { + /** + * The Pipeline on which you called `execute()` in order to get this + * `PipelineSnapshot`. + */ + get pipeline(): Pipeline; + + /** An array of all the results in the `PipelineSnapshot`. */ + get results(): PipelineResult[]; + + /** + * The time at which the pipeline producing this result is executed. + * + * @type {Timestamp} + * @readonly + * + */ + get executionTime(): Timestamp; + } /** - * Specifies a threshold for which no less similar documents will be returned. The behavior - * of the specified `distanceMeasure` will affect the meaning of the distance threshold. + * @beta * - * - For `distanceMeasure: "EUCLIDEAN"`, the meaning of `distanceThreshold` is: - * SELECT docs WHERE euclidean_distance <= distanceThreshold - * - For `distanceMeasure: "COSINE"`, the meaning of `distanceThreshold` is: - * SELECT docs WHERE cosine_distance <= distanceThreshold - * - For `distanceMeasure: "DOT_PRODUCT"`, the meaning of `distanceThreshold` is: - * SELECT docs WHERE dot_product_distance >= distanceThreshold + * A PipelineResult contains data read from a Firestore Pipeline. The data can be extracted with the + * {@link #data()} or {@link #get(String)} methods. + * + *

      If the PipelineResult represents a non-document result, `ref` will return a undefined + * value. */ - distanceThreshold?: number; + export class PipelineResult { + readonly executionTime: Timestamp; + readonly createTime: Timestamp | undefined; + readonly updateTime: Timestamp | undefined; + + /** + * The reference of the document, if it is a document; otherwise `undefined`. + */ + // get ref(): DocumentReference | undefined; + + /** + * The ID of the document for which this PipelineResult contains data, if it is a document; otherwise `undefined`. + * + * @type {string} + * @readonly + * + */ + get id(): string | undefined; + + get ref(): DocumentReference | undefined; + + /** + * Retrieves all fields in the result as an object. Returns 'undefined' if + * the document doesn't exist. + * + * @returns {T|undefined} An object containing all fields in the document or + * 'undefined' if the document doesn't exist. + * + * @example + * ``` + * let p = firestore.pipeline().collection('col'); + * + * p.execute().then(results => { + * let data = results[0].data(); + * console.log(`Retrieved data: ${JSON.stringify(data)}`); + * }); + * ``` + */ + data(): DocumentData | undefined; + + /** + * Retrieves the field specified by `field`. + * + * @param {string|FieldPath} field The field path + * (e.g. 'foo' or 'foo.bar') to a specific field. + * @returns {*} The data at the specified field location or undefined if no + * such field exists. + * + * @example + * ``` + * let p = firestore.pipeline().collection('col'); + * + * p.execute().then(results => { + * let field = results[0].get('a.b'); + * console.log(`Retrieved field value: ${field}`); + * }); + * ``` + */ + // We deliberately use `any` in the external API to not impose type-checking + // on end users. + // eslint-disable-next-line @typescript-eslint/no-explicit-any + get(field: string | FieldPath): any; + + /** + * Returns true if the document's data and path in this `PipelineResult` is + * equal to the provided value. + * + * @param {*} other The value to compare against. + * @return {boolean} true if this `PipelineResult` is equal to the provided + * value. + */ + isEqual(other: PipelineResult): boolean; + } } } diff --git a/types/pipelines.d.ts b/types/pipelines.d.ts new file mode 100644 index 000000000..afca919a5 --- /dev/null +++ b/types/pipelines.d.ts @@ -0,0 +1,28 @@ +/*! + * Copyright 2025 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. + */ + +// We deliberately use `any` in the external API to not impose type-checking +// on end users. +/* eslint-disable @typescript-eslint/no-explicit-any */ + +// Declare a global (ambient) namespace +// (used when not using import statement, but just script include). + +import './firestore'; + +declare module '@google-cloud/firestore/pipelines' { + export = FirebaseFirestore.Pipelines; +} From 08b0682d834841ff7dd2c86ae2fb559362300266 Mon Sep 17 00:00:00 2001 From: Mark Duckworth <1124037+MarkDuckworth@users.noreply.github.com> Date: Wed, 23 Jul 2025 15:43:44 -0600 Subject: [PATCH 41/60] pipeline options with explain-analyze (#2372) --- .idea/runConfigurations/Unit_Tests.xml | 2 +- CHANGELOG.md | 17 + dev/src/bulk-writer.ts | 7 +- dev/src/index.ts | 9 +- dev/src/path.ts | 107 +- dev/src/pipelines/expression.ts | 2 +- dev/src/pipelines/index.ts | 2 - dev/src/pipelines/options-util.ts | 89 + dev/src/pipelines/pipeline-options.ts | 86 + dev/src/pipelines/pipeline-util.ts | 207 +- dev/src/pipelines/pipelines.ts | 1220 ++- dev/src/pipelines/stage.ts | 455 +- dev/src/pipelines/structured-pipeline.ts | 68 + dev/src/recursive-delete.ts | 2 +- dev/src/reference/aggregate-query.ts | 2 +- dev/src/reference/collection-reference.ts | 4 - dev/src/reference/document-reference.ts | 4 - dev/src/reference/types.ts | 5 +- dev/src/reference/vector-query.ts | 3 +- dev/src/serializer.ts | 123 +- dev/src/util.ts | 17 +- dev/src/v1/firestore_admin_client.ts | 6807 +++++++----- dev/src/v1/firestore_client.ts | 3597 ++++--- dev/system-test/firestore.ts | 47 +- dev/system-test/pipeline.ts | 773 +- dev/test/collection.ts | 1 - dev/test/document.ts | 1 - dev/test/gapic_firestore_admin_v1.ts | 11082 +++++++++++--------- dev/test/gapic_firestore_v1.ts | 5829 +++++----- dev/test/index.ts | 1 - dev/test/options-util.ts | 227 + dev/test/pipelines/pipeline.ts | 433 + dev/test/structured-pipeline.ts | 183 + package.json | 2 +- samples/package.json | 2 +- types/firestore.d.ts | 878 +- 36 files changed, 19846 insertions(+), 12448 deletions(-) create mode 100644 dev/src/pipelines/options-util.ts create mode 100644 dev/src/pipelines/pipeline-options.ts create mode 100644 dev/src/pipelines/structured-pipeline.ts create mode 100644 dev/test/options-util.ts create mode 100644 dev/test/pipelines/pipeline.ts create mode 100644 dev/test/structured-pipeline.ts diff --git a/.idea/runConfigurations/Unit_Tests.xml b/.idea/runConfigurations/Unit_Tests.xml index 43fc6f798..3a84e9d10 100644 --- a/.idea/runConfigurations/Unit_Tests.xml +++ b/.idea/runConfigurations/Unit_Tests.xml @@ -11,7 +11,7 @@ bdd --require ts-node/register/type-check --no-cache --no-timeout PATTERN - $PROJECT_DIR$/dev/test/*.js $PROJECT_DIR$/dev/test/*.ts + $PROJECT_DIR$/dev/test/*.js $PROJECT_DIR$/dev/test/**/*.ts \ No newline at end of file diff --git a/CHANGELOG.md b/CHANGELOG.md index 9f16c3073..3ca725f0d 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -4,6 +4,23 @@ [1]: https://www.npmjs.com/package/@google-cloud/firestore?activeTab=versions +## [7.11.1](https://github.com/googleapis/nodejs-firestore/compare/v7.11.0...v7.11.1) (2025-05-02) + + +### Bug Fixes + +* Aggregate query readtime bug ([#2331](https://github.com/googleapis/nodejs-firestore/issues/2331)) ([9ac0394](https://github.com/googleapis/nodejs-firestore/commit/9ac0394df78619bf1d6b7907a364342796a4f0fb)) +* Bump default deadline on CreateDatabase and RestoreDatabase to 2 minutes ([#2274](https://github.com/googleapis/nodejs-firestore/issues/2274)) ([d559080](https://github.com/googleapis/nodejs-firestore/commit/d559080a0f436927108ec69c2910af4e8246a8b0)) +* Close default BulkWriter upon terminate. ([#2276](https://github.com/googleapis/nodejs-firestore/issues/2276)) ([1e714a8](https://github.com/googleapis/nodejs-firestore/commit/1e714a8b7952b65872e65533cfe74d303dfabe20)) +* Correctly escape field paths with multiple backslashes or backticks ([#2259](https://github.com/googleapis/nodejs-firestore/issues/2259)) ([#2261](https://github.com/googleapis/nodejs-firestore/issues/2261)) ([7056ba7](https://github.com/googleapis/nodejs-firestore/commit/7056ba76040b9369d86c57838ef938c9d9ef73d8)) +* Do not send page size with auto-paginate. Fixes warnings in listCollections and listDocuments. ([#2336](https://github.com/googleapis/nodejs-firestore/issues/2336)) ([844b4ca](https://github.com/googleapis/nodejs-firestore/commit/844b4ca9c209e649565d122940858409d808baa6)) +* Finalize fixing typings for headers in generator ([#2287](https://github.com/googleapis/nodejs-firestore/issues/2287)) ([c6c85b6](https://github.com/googleapis/nodejs-firestore/commit/c6c85b66a25b56bd23c19285302a740b0ca85d25)) +* Prevent crashes if an inactive stream receives an error. ([#2283](https://github.com/googleapis/nodejs-firestore/issues/2283)) ([f58fe79](https://github.com/googleapis/nodejs-firestore/commit/f58fe791c7afc59087e2555f7208cdb611470d80)) +* Remove unused "long" dependency from firestore proto ([#2324](https://github.com/googleapis/nodejs-firestore/issues/2324)) ([5937b93](https://github.com/googleapis/nodejs-firestore/commit/5937b93aa1aacd2f63bf1678ec569c504cf0b186)) +* Sort document reference by long type id ([#2257](https://github.com/googleapis/nodejs-firestore/issues/2257)) ([3fd0de9](https://github.com/googleapis/nodejs-firestore/commit/3fd0de93076adfe17aaae9e0a9b732bcae52d594)) +* Sort strings in UTF-8 encoded byte order ([#2275](https://github.com/googleapis/nodejs-firestore/issues/2275)) ([a2950e0](https://github.com/googleapis/nodejs-firestore/commit/a2950e0b6464012f0e6c5703d0d28c2175cd35a2)) +* Use lazy encoding for utf-8 encoded string comparison ([#2299](https://github.com/googleapis/nodejs-firestore/issues/2299)) ([e8777e1](https://github.com/googleapis/nodejs-firestore/commit/e8777e12db41096c3945afd3be7905c1c029493c)) + ## [7.11.0](https://github.com/googleapis/nodejs-firestore/compare/v7.10.0...v7.11.0) (2024-12-05) diff --git a/dev/src/bulk-writer.ts b/dev/src/bulk-writer.ts index 1f8371624..6bab2a6ee 100644 --- a/dev/src/bulk-writer.ts +++ b/dev/src/bulk-writer.ts @@ -291,10 +291,9 @@ class BulkCommitBatch extends WriteBatch { ); this.pendingOps[i].onSuccess(new WriteResult(updateTime)); } else { - const error = - new (require('google-gax/build/src/fallback').GoogleError)( - status.message || undefined - ); + const error = new (require('google-gax/fallback').GoogleError)( + status.message || undefined + ); error.code = status.code as number; this.pendingOps[i].onError(wrapError(error, stack)); } diff --git a/dev/src/index.ts b/dev/src/index.ts index 9a13346be..e50013c36 100644 --- a/dev/src/index.ts +++ b/dev/src/index.ts @@ -1601,11 +1601,10 @@ export class Firestore implements firestore.Firestore { if (retryCodes) { const retryParams = getRetryParams(methodName); - callOptions.retry = - new (require('google-gax/build/src/fallback').RetryOptions)( - retryCodes, - retryParams - ); + callOptions.retry = new (require('google-gax/fallback').RetryOptions)( + retryCodes, + retryParams + ); } return callOptions; diff --git a/dev/src/path.ts b/dev/src/path.ts index 03c2b6116..5b49887ba 100644 --- a/dev/src/path.ts +++ b/dev/src/path.ts @@ -236,8 +236,45 @@ abstract class Path { * @returns The newly created Path. */ popLast(): T { - this.segments.pop(); - return this.construct(this.segments); + return this.construct(this.segments.slice(0, -1)); + } + + /** + * Returns the last segment from this `Path`; + * + * @private + * @internal + * @returns The last segment of this Path. + */ + lastSegment(): string { + return this.get(this.size - 1); + } + + /** + * Returns the path segment at the specified index. + * @param index + */ + get(index: number): string { + return this.segments[index]; + } + + /** + * Returns `true` if this path is the immediate + * parent of the given `potentialChild` path. + * @param potentialChild + */ + isImmediateParentOf(potentialChild: this): boolean { + if (this.size + 1 !== potentialChild.size) { + return false; + } + + for (let i = 0; i < this.size; i++) { + if (this.get(i) !== potentialChild.get(i)) { + return false; + } + } + + return true; } /** @@ -585,6 +622,15 @@ export class FieldPath extends Path implements firestore.FieldPath { */ private static _DOCUMENT_ID = new FieldPath('__name__'); + /** + * @private + * @internal + * Defines the minimum number of segments allowed in a FieldPath + */ + get _minNumSegments(): number { + return 1; + } + /** * Constructs a Firestore Field Path. * @@ -610,8 +656,6 @@ export class FieldPath extends Path implements firestore.FieldPath { ); } - validateMinNumberOfArguments('FieldPath', segments, 1); - for (let i = 0; i < segments.length; ++i) { validateString(i, segments[i]); if (segments[i].length === 0) { @@ -620,6 +664,8 @@ export class FieldPath extends Path implements firestore.FieldPath { } super(segments); + + validateMinNumberOfArguments('FieldPath', segments, this._minNumSegments); } /** @@ -632,6 +678,19 @@ export class FieldPath extends Path implements firestore.FieldPath { return FieldPath._DOCUMENT_ID; } + /** + * Create an empty FieldPath. + * @private + * @internal + * + * @returns {FieldPath} + */ + static _emptyPath(): FieldPath { + const result = new FieldPath('empty'); + result.segments.pop(); + return result; + } + /** * Turns a field path argument into a [FieldPath]{@link FieldPath}. * Supports FieldPaths as input (which are passed through) and dot-separated @@ -717,6 +776,46 @@ export class FieldPath extends Path implements firestore.FieldPath { return super.isEqual(other); } } +/** + * A dot-separated path for navigating ObjectValues. + * This type is like its parent, FieldPath, except + * it allows for zero length segments. + * + * @private + * @internal + * @class + */ +export class ObjectValueFieldPath extends FieldPath { + /** + * Zero length field paths are allowed in object value traverse. + */ + get _minNumSegments(): number { + return 0; + } + + constructor(...segments: string[]) { + super(...segments); + } + + static fromDotNotation(path: string): ObjectValueFieldPath { + return new ObjectValueFieldPath(...path.split('.')); + } + + /** + * Constructs a new instance of FieldPath. We need this instead of using + * the normal constructor because polymorphic 'this' doesn't work on static + * methods. + * + * @private + * @internal + * @override + * @param segments Sequence of field names. + * @returns The newly created FieldPath. + */ + construct(segments: string[]): FieldPath { + return new ObjectValueFieldPath(...segments); + } +} /** * Validates that the provided value can be used as a field path argument. diff --git a/dev/src/pipelines/expression.ts b/dev/src/pipelines/expression.ts index a08f4467e..aebb76436 100644 --- a/dev/src/pipelines/expression.ts +++ b/dev/src/pipelines/expression.ts @@ -656,7 +656,7 @@ export abstract class Expr implements firestore.Pipelines.Expr, HasUserData { */ like(pattern: Expr): FunctionExpr; like(stringOrExpr: string | Expr): FunctionExpr { - return new FunctionExpr('like', [this, valueToDefaultExpr(stringOrExpr)]); + return new BooleanExpr('like', [this, valueToDefaultExpr(stringOrExpr)]); } /** diff --git a/dev/src/pipelines/index.ts b/dev/src/pipelines/index.ts index 98aab7464..fc7006e3c 100644 --- a/dev/src/pipelines/index.ts +++ b/dev/src/pipelines/index.ts @@ -117,5 +117,3 @@ export { unixSecondsToTimestamp, unixMillisToTimestamp, } from './expression'; - -export {FindNearestOptions} from './stage'; diff --git a/dev/src/pipelines/options-util.ts b/dev/src/pipelines/options-util.ts new file mode 100644 index 000000000..fe2520c95 --- /dev/null +++ b/dev/src/pipelines/options-util.ts @@ -0,0 +1,89 @@ +// Copyright 2025 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. + +import {ObjectValue, Serializer} from '../serializer'; +import {ObjectValueFieldPath} from '../path'; +import {ApiMapValue} from '../types'; +import {isPlainObject, mapToArray} from '../util'; +import {google} from '../../protos/firestore_v1_proto_api'; +import IValue = google.firestore.v1.IValue; +export type OptionsDefinitions = Record; +export type OptionDefinition = { + serverName: string; + nestedOptions?: OptionsDefinitions; +}; + +export class OptionsUtil { + constructor(private optionDefinitions: OptionsDefinitions) {} + + private _getKnownOptions( + options: Record, + serializer: Serializer + ): ObjectValue { + const knownOptions: ObjectValue = ObjectValue.empty(); + + // SERIALIZE KNOWN OPTIONS + for (const knownOptionKey in this.optionDefinitions) { + const optionDefinition: OptionDefinition = + this.optionDefinitions[knownOptionKey]; + + if (knownOptionKey in options) { + const optionValue: unknown = options[knownOptionKey]; + let protoValue: IValue | undefined = undefined; + + if (optionDefinition.nestedOptions && isPlainObject(optionValue)) { + const nestedUtil = new OptionsUtil(optionDefinition.nestedOptions); + protoValue = { + mapValue: { + fields: nestedUtil.getOptionsProto(serializer, optionValue), + }, + }; + } else if (optionValue) { + protoValue = serializer.encodeValue(optionValue) ?? undefined; + } + + if (protoValue) { + knownOptions.set( + new ObjectValueFieldPath(optionDefinition.serverName), + protoValue + ); + } + } + } + + return knownOptions; + } + + getOptionsProto( + serializer: Serializer, + knownOptions: Record, + optionsOverride?: Record + ): ApiMapValue | undefined { + const result: ObjectValue = this._getKnownOptions(knownOptions, serializer); + + // APPLY OPTIONS OVERRIDES + if (optionsOverride) { + const optionsMap = new Map( + mapToArray(optionsOverride, (value, key) => [ + ObjectValueFieldPath.fromDotNotation(key), + value !== undefined ? serializer.encodeValue(value) : null, + ]) + ); + result.setAll(optionsMap); + } + + // Return IMapValue from `result` + return result.value.mapValue.fields ?? {}; + } +} diff --git a/dev/src/pipelines/pipeline-options.ts b/dev/src/pipelines/pipeline-options.ts new file mode 100644 index 000000000..3717a9dd3 --- /dev/null +++ b/dev/src/pipelines/pipeline-options.ts @@ -0,0 +1,86 @@ +// Copyright 2025 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. + +/** + * Options defining how a Pipeline is evaluated. + */ +export interface PipelineOptions { + /** + * Specify the index mode. + */ + indexMode?: 'recommended'; + + /** Options used to configure explain queries. */ + explainOptions?: { + /** + * The explain mode configures what explain data + * and query results are returned from the Pipeline query. + * + * `"execute"` - [DEFAULT] Execute the Pipeline and return results + * `"analyze"` - Plan the query and execute, returning both the planner + * information and the Pipeline query results. + */ + mode?: 'execute' | 'analyze'; + + /** + * Specifies the output format of the query planner information. + */ + outputFormat?: 'text' | 'json'; + }; + + /** + * An escape hatch to set options not known at SDK build time. These values + * will be passed directly to the Firestore backend and not used by the SDK. + * + * The option name will be used as provided. And must match the name + * format used by the backend (hint: use a snake_case_name). + * + * Custom option values can be any type supported + * by Firestore (for example: string, boolean, number, map, …). Value types + * not known to the SDK will be rejected. + * + * Values specified in customOptions will take precedence over any options + * with the same name set by the SDK. + * + * Override the `example_option`: + * ``` + * execute({ + * pipeline: myPipeline, + * customOptions: { + * // Override `example_option`. This will not + * // merge with the existing `example_option` object. + * "example_option": { + * foo: "bar" + * } + * } + * } + * ``` + * + * `customOptions` supports dot notation, if you want to override + * a nested option. + * ``` + * execute({ + * pipeline: myPipeline, + * customOptions: { + * // Override `example_option.foo` and do not override + * // any other properties of `example_option`. + * "example_option.foo": "bar" + * } + * } + * ``` + */ + customOptions?: { + [name: string]: unknown; + }; +} diff --git a/dev/src/pipelines/pipeline-util.ts b/dev/src/pipelines/pipeline-util.ts index 36246aa46..c44d886bf 100644 --- a/dev/src/pipelines/pipeline-util.ts +++ b/dev/src/pipelines/pipeline-util.ts @@ -19,7 +19,12 @@ import {google} from '../../protos/firestore_v1_proto_api'; import * as protos from '../../protos/firestore_v1_proto_api'; import './expression'; -import Firestore, {DocumentReference, Timestamp, VectorValue} from '../index'; +import Firestore, { + CollectionReference, + DocumentReference, + Timestamp, + VectorValue, +} from '../index'; import {logger} from '../logger'; import {QualifiedResourcePath} from '../path'; import {CompositeFilterInternal} from '../reference/composite-filter-internal'; @@ -58,8 +63,12 @@ import { Ordering, gt, lt, + Field, + AggregateFunction, } from './expression'; -import {Pipeline, PipelineResult} from './pipelines'; +import {Pipeline, PipelineResult, ExplainStats} from './pipelines'; +import {StructuredPipeline} from './structured-pipeline'; +import Selectable = FirebaseFirestore.Pipelines.Selectable; /** * Returns a builder for DocumentSnapshot and QueryDocumentSnapshot instances. @@ -77,9 +86,8 @@ export class ExecutionUtil { ) {} _getResponse( - pipeline: Pipeline, - transactionOrReadTime?: Uint8Array | Timestamp | api.ITransactionOptions, - explainOptions?: firestore.ExplainOptions + structuredPipeline: StructuredPipeline, + transactionOrReadTime?: Uint8Array | Timestamp | api.ITransactionOptions ): Promise { // Capture the error stack to preserve stack tracing across async calls. const stack = Error().stack!; @@ -89,9 +97,8 @@ export class ExecutionUtil { const output: PipelineResponse = {}; const stream: NodeJS.EventEmitter = this._stream( - pipeline, - transactionOrReadTime, - explainOptions + structuredPipeline, + transactionOrReadTime ); stream.on('error', err => { reject(wrapError(err, stack)); @@ -104,8 +111,8 @@ export class ExecutionUtil { if (element.executionTime) { output.executionTime = element.executionTime; } - if (element.explainMetrics) { - output.explainMetrics = element.explainMetrics; + if (element.explainStats) { + output.explainStats = element.explainStats; } if (element.result) { result.push(element.result); @@ -134,7 +141,9 @@ export class ExecutionUtil { } stream(pipeline: Pipeline): NodeJS.ReadableStream { - const responseStream = this._stream(pipeline); + // TODO(pipeline) implement options for stream + const structuredPipeline = new StructuredPipeline(pipeline, {}, {}); + const responseStream = this._stream(structuredPipeline); const transform = new Transform({ objectMode: true, transform(chunk, encoding, callback) { @@ -148,9 +157,8 @@ export class ExecutionUtil { } _stream( - pipeline: Pipeline, - transactionOrReadTime?: Uint8Array | Timestamp | api.ITransactionOptions, - _?: firestore.ExplainOptions + structuredPipeline: StructuredPipeline, + transactionOrReadTime?: Uint8Array | Timestamp | api.ITransactionOptions ): NodeJS.ReadableStream { const tag = requestTag(); @@ -175,55 +183,66 @@ export class ExecutionUtil { if (proto.executionTime) { output.executionTime = Timestamp.fromProto(proto.executionTime); } + if (proto.explainStats) { + console.log(proto.explainStats.data); + } callback(undefined, [output]); } else { - callback( - undefined, - proto.results.map(result => { - const output: PipelineStreamElement = {}; - if (proto.transaction?.length) { - output.transaction = proto.transaction; - } - if (proto.executionTime) { - output.executionTime = Timestamp.fromProto(proto.executionTime); - } - - const ref = result.name - ? new DocumentReference( - this._firestore, - QualifiedResourcePath.fromSlashSeparatedString(result.name) - ) - : undefined; - output.result = new PipelineResult( - this._serializer, - ref, - result.fields || undefined, - Timestamp.fromProto(proto.executionTime!), - result.createTime - ? Timestamp.fromProto(result.createTime!) - : undefined, - result.updateTime - ? Timestamp.fromProto(result.updateTime!) - : undefined - ); - return output; - }) - ); + let output: PipelineStreamElement[] = proto.results.map(result => { + const output: PipelineStreamElement = {}; + if (proto.transaction?.length) { + output.transaction = proto.transaction; + } + if (proto.executionTime) { + output.executionTime = Timestamp.fromProto(proto.executionTime); + } + + const ref = result.name + ? new DocumentReference( + this._firestore, + QualifiedResourcePath.fromSlashSeparatedString(result.name) + ) + : undefined; + output.result = new PipelineResult( + this._serializer, + ref, + result.fields || undefined, + Timestamp.fromProto(proto.executionTime!), + result.createTime + ? Timestamp.fromProto(result.createTime!) + : undefined, + result.updateTime + ? Timestamp.fromProto(result.updateTime!) + : undefined + ); + return output; + }); + if (proto.explainStats?.data?.value) { + const explainStats = new ExplainStats(proto.explainStats.data); + + output = [ + ...output, + { + explainStats, + } as PipelineStreamElement, + ]; + } + callback(undefined, output); } }, }); - this._firestore - .initializeIfNeeded(tag) + Promise.all([ + this._firestore.initializeIfNeeded(tag), + ExplainStats._ensureMessageTypesLoaded(), + ]) .then(async () => { // `toProto()` might throw an exception. We rely on the behavior of an // async function to convert this exception into the rejected Promise we // catch below. const request: api.IExecutePipelineRequest = { database: this._firestore.formattedName, - structuredPipeline: { - pipeline: pipeline._toProto(), - }, + structuredPipeline: structuredPipeline._toProto(this._serializer), }; if (transactionOrReadTime instanceof Uint8Array) { @@ -532,6 +551,62 @@ export function isString(val: unknown): val is string { return typeof val === 'string'; } +export function isNumber(val: unknown): val is number { + return typeof val === 'number'; +} + +export function isSelectable( + val: unknown +): val is firestore.Pipelines.Selectable { + const candidate = val as firestore.Pipelines.Selectable; + return ( + candidate.selectable && isString(candidate.alias) && isExpr(candidate.expr) + ); +} + +export function isOrdering(val: unknown): val is firestore.Pipelines.Ordering { + const candidate = val as firestore.Pipelines.Ordering; + return ( + isExpr(candidate.expr) && + (candidate.direction === 'ascending' || + candidate.direction === 'descending') + ); +} + +export function isAggregateWithAlias( + val: unknown +): val is firestore.Pipelines.AggregateWithAlias { + const candidate = val as firestore.Pipelines.AggregateWithAlias; + return ( + isString(candidate.alias) && + candidate.aggregate instanceof AggregateFunction + ); +} + +export function isExpr(val: unknown): val is firestore.Pipelines.Expr { + return val instanceof Expr; +} + +export function isBooleanExpr( + val: unknown +): val is firestore.Pipelines.BooleanExpr { + return val instanceof BooleanExpr; +} + +export function isField(val: unknown): val is firestore.Pipelines.Field { + return val instanceof Field; +} + +export function isPipeline(val: unknown): val is firestore.Pipelines.Pipeline { + return val instanceof Pipeline; +} + +export function isCollectionReference( + val: unknown +): val is firestore.CollectionReference { + return val instanceof CollectionReference; +} + /** * Converts a value to an Expr, Returning either a Constant, MapFunction, * ArrayFunction, or the input itself (if it's already an expression). @@ -601,3 +676,33 @@ export function fieldOrExpression(value: unknown): Expr { return valueToDefaultExpr(value); } } + +export function toField(value: string | firestore.Pipelines.Field): Field { + if (isString(value)) { + const result = field(value); + result._createdFromLiteral = true; + return result; + } else { + return value as Field; + } +} + +/** + * Converts a value to a Selectable, returning either a + * Field, or the input itself (if it's already a Selectable). + * If the input is a string, it is assumed to be a field name, and a + * field(value) is returned. + * + * @private + * @internal + * @param value + */ +export function fieldOrSelectable(value: string | Selectable): Selectable { + if (isString(value)) { + const result = field(value); + result._createdFromLiteral = true; + return result; + } else { + return value; + } +} diff --git a/dev/src/pipelines/pipelines.ts b/dev/src/pipelines/pipelines.ts index 1d24d8743..8941071bc 100644 --- a/dev/src/pipelines/pipelines.ts +++ b/dev/src/pipelines/pipelines.ts @@ -22,7 +22,23 @@ import Firestore, { Timestamp, } from '../index'; import {validateFieldPath} from '../path'; -import {ExecutionUtil, fieldOrExpression} from './pipeline-util'; +import { + ExecutionUtil, + fieldOrExpression, + isAggregateWithAlias, + isBooleanExpr, + isCollectionReference, + isExpr, + isField, + isNumber, + isOrdering, + isPipeline, + isSelectable, + isString, + toField, + vectorToExpr, +} from './pipeline-util'; +import {PipelineOptions} from './pipeline-options'; import {DocumentReference} from '../reference/document-reference'; import {PipelineResponse} from '../reference/types'; import {HasUserData, hasUserData, Serializer} from '../serializer'; @@ -30,7 +46,7 @@ import {ApiMapValue} from '../types'; import * as protos from '../../protos/firestore_v1_proto_api'; import api = protos.google.firestore.v1; import IStage = google.firestore.v1.Pipeline.IStage; -import {cast, isOptionalEqual, isPlainObject} from '../util'; +import {isOptionalEqual, isPlainObject} from '../util'; import { AggregateFunction, @@ -65,7 +81,31 @@ import { Sample, Union, Unnest, + InternalWhereStageOptions, + InternalOffsetStageOptions, + InternalLimitStageOptions, + InternalDistinctStageOptions, + InternalAggregateStageOptions, + InternalFindNearestStageOptions, + InternalReplaceWithStageOptions, + InternalSampleStageOptions, + InternalUnionStageOptions, + InternalUnnestStageOptions, + InternalSortStageOptions, + InternalDocumentsStageOptions, + InternalCollectionGroupStageOptions, + InternalCollectionStageOptions, } from './stage'; +import {StructuredPipeline} from './structured-pipeline'; +import Selectable = FirebaseFirestore.Pipelines.Selectable; + +import { + load as loadProtos, + Root as ProtoRoot, + Type as MessageType, + ReflectionObject, +} from 'protobufjs'; +import {logger} from '../logger'; /** * Represents the source of a Firestore {@link Pipeline}. @@ -73,23 +113,88 @@ import { export class PipelineSource implements firestore.Pipelines.PipelineSource { constructor(private db: Firestore) {} - collection(collection: string | firestore.CollectionReference): Pipeline { - if (collection instanceof CollectionReference) { + /** + * Returns all documents from the entire collection. The collection can be nested. + * @param collection - Name or reference to the collection that will be used as the Pipeline source. + */ + collection(collection: string | firestore.CollectionReference): Pipeline; + /** + * Returns all documents from the entire collection. The collection can be nested. + * @param options - Options defining how this CollectionStage is evaluated. + */ + collection(options: firestore.Pipelines.CollectionStageOptions): Pipeline; + collection( + collectionOrOptions: + | string + | firestore.CollectionReference + | firestore.Pipelines.CollectionStageOptions + ): Pipeline { + const options = + isString(collectionOrOptions) || + isCollectionReference(collectionOrOptions) + ? {} + : collectionOrOptions; + + const collection = + isString(collectionOrOptions) || + isCollectionReference(collectionOrOptions) + ? collectionOrOptions + : collectionOrOptions.collection; + + // Validate that a user provided reference is for the same Firestore DB + if (isCollectionReference(collection)) { this._validateReference(collection); - return new Pipeline(this.db, [new CollectionSource(collection.path)]); - } else if (typeof collection === 'string') { - return new Pipeline(this.db, [new CollectionSource(collection)]); - } else { - throw 'Unexpected collection type'; } + + const normalizedCollection = isString(collection) + ? this.db.collection(collection) + : (collection as CollectionReference); + + const internalOptions: InternalCollectionStageOptions = { + ...options, + collection: normalizedCollection, + }; + + return new Pipeline(this.db, [new CollectionSource(internalOptions)]); } - collectionGroup(collectionId: string): Pipeline { - return new Pipeline(this.db, [new CollectionGroupSource(collectionId)]); + /** + * Returns all documents from a collection ID regardless of the parent. + * @param collectionId - ID of the collection group to use as the Pipeline source. + */ + collectionGroup(collectionId: string): Pipeline; + + /** + * Returns all documents from a collection ID regardless of the parent. + * @param options - Options defining how this CollectionGroupStage is evaluated. + */ + collectionGroup( + options: firestore.Pipelines.CollectionGroupStageOptions + ): Pipeline; + collectionGroup( + collectionIdOrOptions: + | string + | firestore.Pipelines.CollectionGroupStageOptions + ): Pipeline { + const options: InternalCollectionGroupStageOptions = isString( + collectionIdOrOptions + ) + ? {collectionId: collectionIdOrOptions} + : {...collectionIdOrOptions}; + return new Pipeline(this.db, [new CollectionGroupSource(options)]); } - database(): Pipeline { - return new Pipeline(this.db, [new DatabaseSource()]); + /** + * Returns all documents from the entire database. + */ + database(): Pipeline; + /** + * Returns all documents from the entire database. + * @param options - Options defining how a DatabaseStage is evaluated. + */ + database(options: firestore.Pipelines.DatabaseStageOptions): Pipeline; + database(options?: firestore.Pipelines.DatabaseStageOptions): Pipeline { + return new Pipeline(this.db, [new DatabaseSource(options ?? {})]); } /** @@ -100,13 +205,42 @@ export class PipelineSource implements firestore.Pipelines.PipelineSource { * * @throws {@FirestoreError} Thrown if any of the provided DocumentReferences target a different project or database than the pipeline. */ - documents(docs: Array): Pipeline { + documents(docs: Array): Pipeline; + + /** + * Set the pipeline's source to the documents specified by the given paths and DocumentReferences. + * + * @param options - Options defining how this DocumentsStage is evaluated. + * + * @throws {@FirestoreError} Thrown if any of the provided DocumentReferences target a different project or database than the pipeline. + */ + documents(options: firestore.Pipelines.DocumentsStageOptions): Pipeline; + documents( + docsOrOptions: + | Array + | firestore.Pipelines.DocumentsStageOptions + ): Pipeline { + const options = Array.isArray(docsOrOptions) ? {} : docsOrOptions; + const docs = Array.isArray(docsOrOptions) + ? docsOrOptions + : docsOrOptions.docs; + + // Validate that all user provided references are for the same Firestore DB docs .filter(v => v instanceof DocumentReference) - .forEach(dr => this._validateReference(dr)); - return new Pipeline(this.db, [ - DocumentsSource.of(cast(docs)), - ]); + .forEach(dr => + this._validateReference(dr as firestore.DocumentReference) + ); + + const normalizedDocs: Array = docs.map(doc => + isString(doc) ? this.db.doc(doc) : (doc as DocumentReference) + ); + + const internalOptions: InternalDocumentsStageOptions = { + ...options, + docs: normalizedDocs, + }; + return new Pipeline(this.db, [new DocumentsSource(internalOptions)]); } /** @@ -120,7 +254,20 @@ export class PipelineSource implements firestore.Pipelines.PipelineSource { return (query as unknown as Query)._pipeline(); } - _validateReference(reference: CollectionReference | DocumentReference): void { + _validateReference( + reference: firestore.CollectionReference | firestore.DocumentReference + ): reference is CollectionReference | DocumentReference { + if ( + !( + reference instanceof CollectionReference || + reference instanceof DocumentReference + ) + ) { + throw new Error( + 'Invalid reference. The value may not be a CollectionReference or DocumentReference. Or, it may be an object from a different SDK build.' + ); + } + const refDbId = reference.firestore.formattedName; if (refDbId !== this.db.formattedName) { throw new Error( @@ -133,6 +280,8 @@ export class PipelineSource implements firestore.Pipelines.PipelineSource { `the database name ("${this.db.formattedName}") of the target database of this Pipeline.` ); } + + return true; } } @@ -218,15 +367,55 @@ export class Pipeline implements firestore.Pipelines.Pipeline { addFields( field: firestore.Pipelines.Selectable, ...additionalFields: firestore.Pipelines.Selectable[] + ): Pipeline; + /** + * Adds new fields to outputs from previous stages. + * + * This stage allows you to compute values on-the-fly based on existing data from previous + * stages or constants. You can use this to create new fields or overwrite existing ones (if there + * is name overlaps). + * + * The added fields are defined using {@link Selectable}s, which can be: + * + * - {@link Field}: References an existing document field. + * - {@link Expr}: Either a literal value (see {@link Constant}) or a computed value + * (see {@FunctionExpr}) with an assigned alias using {@link Expr#as}. + * + * Example: + * + * ```typescript + * firestore.pipeline().collection("books") + * .addFields( + * field("rating").as("bookRating"), // Rename 'rating' to 'bookRating' + * add(5, field("quantity")).as("totalCost") // Calculate 'totalCost' + * ); + * ``` + * + * @param options - An object that specifies required and optional parameters for the stage. + * @return A new Pipeline object with this stage appended to the stage list. + */ + addFields(options: firestore.Pipelines.AddFieldsStageOptions): Pipeline; + addFields( + fieldOrOptions: + | firestore.Pipelines.Selectable + | firestore.Pipelines.AddFieldsStageOptions, + ...additionalFields: firestore.Pipelines.Selectable[] ): Pipeline { - return this._addStage( - new AddFields( - this.validateUserData( - 'addFields', - this.selectablesToMap([field, ...additionalFields]) - ) - ) - ); + const options = isSelectable(fieldOrOptions) ? {} : fieldOrOptions; + const fields: firestore.Pipelines.Selectable[] = isSelectable( + fieldOrOptions + ) + ? [fieldOrOptions, ...additionalFields] + : fieldOrOptions.fields; + const normalizedFields: Map = selectablesToMap(fields); + + this._validateUserData('select', normalizedFields); + + const internalOptions = { + ...options, + fields: normalizedFields, + }; + return this._addStage(new AddFields(internalOptions)); } /** @@ -250,12 +439,52 @@ export class Pipeline implements firestore.Pipelines.Pipeline { removeFields( fieldValue: firestore.Pipelines.Field | string, ...additionalFields: Array + ): Pipeline; + /** + * Remove fields from outputs of previous stages. + * + * Example: + * + * ```typescript + * firestore.pipeline().collection('books') + * // removes field 'rating' and 'cost' from the previous stage outputs. + * .removeFields( + * field('rating'), + * 'cost' + * ); + * ``` + * + * @param options - An object that specifies required and optional parameters for the stage. + * @return A new Pipeline object with this stage appended to the stage list. + */ + removeFields(options: firestore.Pipelines.RemoveFieldsStageOptions): Pipeline; + removeFields( + fieldValueOrOptions: + | firestore.Pipelines.Field + | string + | firestore.Pipelines.RemoveFieldsStageOptions, + ...additionalFields: Array ): Pipeline { - const fieldExpressions = [fieldValue, ...additionalFields].map(f => - typeof f === 'string' ? field(f) : (f as Field) + const options = + isField(fieldValueOrOptions) || isString(fieldValueOrOptions) + ? {} + : fieldValueOrOptions; + + const fields: Array = + isField(fieldValueOrOptions) || isString(fieldValueOrOptions) + ? [fieldValueOrOptions, ...additionalFields] + : fieldValueOrOptions.fields; + const convertedFields: Array = fields.map(f => + isString(f) ? field(f) : (f as Field) ); - this.validateUserData('removeFields', fieldExpressions); - return this._addStage(new RemoveFields(fieldExpressions)); + this._validateUserData('removeFields', convertedFields); + + const innerOptions = { + ...options, + fields: convertedFields, + }; + + return this._addStage(new RemoveFields(innerOptions)); } /** @@ -294,61 +523,64 @@ export class Pipeline implements firestore.Pipelines.Pipeline { select( selection: firestore.Pipelines.Selectable | string, ...additionalSelections: Array + ): Pipeline; + /** + * Selects or creates a set of fields from the outputs of previous stages. + * + *

      The selected fields are defined using {@link Selectable} expressions, which can be: + * + *

        + *
      • {@code string}: Name of an existing field
      • + *
      • {@link Field}: References an existing field.
      • + *
      • {@link Function}: Represents the result of a function with an assigned alias name using + * {@link Expr#as}
      • + *
      + * + *

      If no selections are provided, the output of this stage is empty. Use {@link + * Pipeline#addFields} instead if only additions are + * desired. + * + *

      Example: + * + * ```typescript + * db.pipeline().collection("books") + * .select( + * "firstName", + * field("lastName"), + * field("address").toUppercase().as("upperAddress"), + * ); + * ``` + * + * @param options - An object that specifies required and optional parameters for the stage. + * @return A new Pipeline object with this stage appended to the stage list. + */ + select(options: firestore.Pipelines.SelectStageOptions): Pipeline; + select( + selectionOrOptions: + | firestore.Pipelines.Selectable + | string + | firestore.Pipelines.SelectStageOptions, + ...additionalSelections: Array ): Pipeline { - let projections: Map = this.selectablesToMap([ - selection, - ...additionalSelections, - ]); - projections = this.validateUserData('select', projections); - return this._addStage(new Select(projections)); - } + const options = + isSelectable(selectionOrOptions) || isString(selectionOrOptions) + ? {} + : selectionOrOptions; - private selectablesToMap( - selectables: (firestore.Pipelines.Selectable | string)[] - ): Map { - const result = new Map(); - for (const selectable of selectables) { - if (typeof selectable === 'string') { - result.set( - selectable as string, - new Field(FieldPath.fromArgument(selectable)) - ); - } else if (selectable instanceof Field) { - result.set((selectable as Field).fieldName(), selectable); - } else if (selectable instanceof ExprWithAlias) { - const expr = selectable as ExprWithAlias; - result.set(expr.alias, expr.expr as unknown as Expr); - } else { - throw new Error('unexpected selectable: ' + JSON.stringify(selectable)); - } - } - return result; - } + const selections: Array = + isSelectable(selectionOrOptions) || isString(selectionOrOptions) + ? [selectionOrOptions, ...additionalSelections] + : selectionOrOptions.selections; + const normalizedSelections: Map = + selectablesToMap(selections); - /** - * Validates user data for each expression in the expressionMap. - * @param name Name of the calling function. Used for error messages when invalid user data is encountered. - * @param expressionMap - * @return the expressionMap argument. - * @private - */ - private validateUserData< - T extends Map | HasUserData[] | HasUserData, - >(name: string, expressionMap: T): T { - const ignoreUndefinedProperties = - !!this.db._settings.ignoreUndefinedProperties; - if (hasUserData(expressionMap)) { - expressionMap._validateUserData(ignoreUndefinedProperties); - } else if (Array.isArray(expressionMap)) { - expressionMap.forEach(readableData => - readableData._validateUserData(ignoreUndefinedProperties) - ); - } else { - expressionMap.forEach(expr => - expr._validateUserData(ignoreUndefinedProperties) - ); - } - return expressionMap; + this._validateUserData('select', normalizedSelections); + + const internalOptions = { + ...options, + selections: normalizedSelections, + }; + return this._addStage(new Select(internalOptions)); } /** @@ -382,10 +614,60 @@ export class Pipeline implements firestore.Pipelines.Pipeline { * @param condition The {@link BooleanExpr} to apply. * @return A new Pipeline object with this stage appended to the stage list. */ - where(condition: firestore.Pipelines.BooleanExpr): Pipeline { - const booleanExpr = condition as BooleanExpr; - this.validateUserData('where', booleanExpr); - return this._addStage(new Where(booleanExpr)); + where(condition: firestore.Pipelines.BooleanExpr): Pipeline; + /** + * Filters the documents from previous stages to only include those matching the specified {@link + * BooleanExpr}. + * + *

      This stage allows you to apply conditions to the data, similar to a "WHERE" clause in SQL. + * You can filter documents based on their field values, using implementations of {@link + * BooleanExpr}, typically including but not limited to: + * + *

        + *
      • field comparators: {@link Function#eq}, {@link Function#lt} (less than), {@link + * Function#gt} (greater than), etc.
      • + *
      • logical operators: {@link Function#and}, {@link Function#or}, {@link Function#not}, etc.
      • + *
      • advanced functions: {@link Function#regexMatch}, {@link + * Function#arrayContains}, etc.
      • + *
      + * + *

      Example: + * + * ```typescript + * firestore.pipeline().collection("books") + * .where( + * and( + * gt(field("rating"), 4.0), // Filter for ratings greater than 4.0 + * field("genre").eq("Science Fiction") // Equivalent to gt("genre", "Science Fiction") + * ) + * ); + * ``` + * + * @param options - An object that specifies required and optional parameters for the stage. + * @return A new Pipeline object with this stage appended to the stage list. + */ + where(options: firestore.Pipelines.WhereStageOptions): Pipeline; + where( + conditionOrOptions: + | firestore.Pipelines.BooleanExpr + | firestore.Pipelines.WhereStageOptions + ): Pipeline { + const options = isBooleanExpr(conditionOrOptions) ? {} : conditionOrOptions; + + const condition: firestore.Pipelines.BooleanExpr = isBooleanExpr( + conditionOrOptions + ) + ? conditionOrOptions + : conditionOrOptions.condition; + const convertedCondition: BooleanExpr = condition as BooleanExpr; + this._validateUserData('where', convertedCondition); + + const internalOptions: InternalWhereStageOptions = { + ...options, + condition: convertedCondition, + }; + + return this._addStage(new Where(internalOptions)); } /** @@ -408,8 +690,42 @@ export class Pipeline implements firestore.Pipelines.Pipeline { * @param offset The number of documents to skip. * @return A new Pipeline object with this stage appended to the stage list. */ - offset(offset: number): Pipeline { - return this._addStage(new Offset(offset)); + offset(offset: number): Pipeline; + /** + * Skips the first `offset` number of documents from the results of previous stages. + * + *

      This stage is useful for implementing pagination in your pipelines, allowing you to retrieve + * results in chunks. It is typically used in conjunction with {@link #limit} to control the + * size of each page. + * + *

      Example: + * + * ```typescript + * // Retrieve the second page of 20 results + * firestore.pipeline().collection('books') + * .sort(field('published').descending()) + * .offset(20) // Skip the first 20 results + * .limit(20); // Take the next 20 results + * ``` + * + * @param options - An object that specifies required and optional parameters for the stage. + * @return A new Pipeline object with this stage appended to the stage list. + */ + offset(options: firestore.Pipelines.OffsetStageOptions): Pipeline; + offset( + offsetOrOptions: number | firestore.Pipelines.OffsetStageOptions + ): Pipeline { + const options = isNumber(offsetOrOptions) ? {} : offsetOrOptions; + + const offset: number = isNumber(offsetOrOptions) + ? offsetOrOptions + : offsetOrOptions.offset; + + const internalOptions: InternalOffsetStageOptions = { + ...options, + offset, + }; + return this._addStage(new Offset(internalOptions)); } /** @@ -437,8 +753,47 @@ export class Pipeline implements firestore.Pipelines.Pipeline { * @param limit The maximum number of documents to return. * @return A new Pipeline object with this stage appended to the stage list. */ - limit(limit: number): Pipeline { - return this._addStage(new Limit(limit)); + limit(limit: number): Pipeline; + /** + * Limits the maximum number of documents returned by previous stages to `limit`. + * + *

      This stage is particularly useful when you want to retrieve a controlled subset of data from + * a potentially large result set. It's often used for: + * + *

        + *
      • **Pagination:** In combination with {@link #offset} to retrieve specific pages of + * results.
      • + *
      • **Limiting Data Retrieval:** To prevent excessive data transfer and improve performance, + * especially when dealing with large collections.
      • + *
      + * + *

      Example: + * + * ```typescript + * // Limit the results to the top 10 highest-rated books + * firestore.pipeline().collection('books') + * .sort(field('rating').descending()) + * .limit(10); + * ``` + * + * @param options - An object that specifies required and optional parameters for the stage. + * @return A new Pipeline object with this stage appended to the stage list. + */ + limit(options: firestore.Pipelines.LimitStageOptions): Pipeline; + limit( + limitOrOptions: number | firestore.Pipelines.LimitStageOptions + ): Pipeline { + const options = isNumber(limitOrOptions) ? {} : limitOrOptions; + + const limit: number = isNumber(limitOrOptions) + ? limitOrOptions + : limitOrOptions.limit; + + const internalOptions: InternalLimitStageOptions = { + ...options, + limit, + }; + return this._addStage(new Limit(internalOptions)); } /** @@ -472,15 +827,58 @@ export class Pipeline implements firestore.Pipelines.Pipeline { distinct( group: string | firestore.Pipelines.Selectable, ...additionalGroups: Array + ): Pipeline; + /** + * Returns a set of distinct values from the inputs to this stage. + * + * This stage runs through the results from previous stages to include only results with + * unique combinations of {@link Expr} values ({@link Field}, {@link Function}, etc). + * + * The parameters to this stage are defined using {@link Selectable} expressions or strings: + * + * - {@code string}: Name of an existing field + * - {@link Field}: References an existing document field. + * - {@link ExprWithAlias}: Represents the result of a function with an assigned alias name + * using {@link Expr#as}. + * + * Example: + * + * ```typescript + * // Get a list of unique author names in uppercase and genre combinations. + * firestore.pipeline().collection("books") + * .distinct(toUppercase(field("author")).as("authorName"), field("genre"), "publishedAt") + * .select("authorName"); + * ``` + * + * @param options - An object that specifies required and optional parameters for the stage. + * @return A new {@code Pipeline} object with this stage appended to the stage list. + */ + distinct(options: firestore.Pipelines.DistinctStageOptions): Pipeline; + distinct( + groupOrOptions: + | string + | firestore.Pipelines.Selectable + | firestore.Pipelines.DistinctStageOptions, + ...additionalGroups: Array ): Pipeline { - return this._addStage( - new Distinct( - this.validateUserData( - 'distinct', - this.selectablesToMap([group, ...additionalGroups]) - ) - ) - ); + const options = + isString(groupOrOptions) || isSelectable(groupOrOptions) + ? {} + : groupOrOptions; + + const groups: Array = + isString(groupOrOptions) || isSelectable(groupOrOptions) + ? [groupOrOptions, ...additionalGroups] + : groupOrOptions.groups; + const convertedGroups: Map = selectablesToMap(groups); + this._validateUserData('distinct', convertedGroups); + + const internalOptions: InternalDistinctStageOptions = { + ...options, + groups: convertedGroups, + }; + + return this._addStage(new Distinct(internalOptions)); } /** @@ -539,67 +937,85 @@ export class Pipeline implements firestore.Pipelines.Pipeline { * }); * ``` * - * @param options An object that specifies the accumulators - * and optional grouping fields to perform. + * @param options - An object that specifies required and optional parameters for the stage. * @return A new {@code Pipeline} object with this stage appended to the stage * list. */ - aggregate(options: { - accumulators: firestore.Pipelines.AggregateWithAlias[]; - groups?: Array; - }): Pipeline; + aggregate(options: firestore.Pipelines.AggregateStageOptions): Pipeline; aggregate( - optionsOrTarget: + targetOrOptions: | firestore.Pipelines.AggregateWithAlias - | { - accumulators: firestore.Pipelines.AggregateWithAlias[]; - groups?: Array; - }, + | firestore.Pipelines.AggregateStageOptions, ...rest: firestore.Pipelines.AggregateWithAlias[] ): Pipeline { - if ('accumulators' in optionsOrTarget) { - return this._addStage( - new Aggregate( - new Map( - optionsOrTarget.accumulators.map( - (target: firestore.Pipelines.AggregateWithAlias) => { - this.validateUserData( - 'aggregate', - target as unknown as AggregateWithAlias - ); - return [ - (target as unknown as AggregateWithAlias).alias, - (target as unknown as AggregateWithAlias).aggregate, - ]; - } - ) - ), - this.validateUserData( - 'aggregate', - this.selectablesToMap(optionsOrTarget.groups || []) - ) - ) - ); - } else { - return this._addStage( - new Aggregate( - new Map( - [optionsOrTarget, ...rest].map(target => [ - (target as unknown as AggregateWithAlias).alias, - this.validateUserData( - 'aggregate', - (target as unknown as AggregateWithAlias).aggregate - ), - ]) - ), - new Map() - ) - ); - } + const options = isAggregateWithAlias(targetOrOptions) + ? {} + : targetOrOptions; + + const accumulators: Array = + isAggregateWithAlias(targetOrOptions) + ? [targetOrOptions, ...rest] + : targetOrOptions.accumulators; + const convertedAccumulators: Map = + aggregateWithAliasToMap(accumulators); + const groups: Array = + isAggregateWithAlias(targetOrOptions) ? [] : targetOrOptions.groups ?? []; + const convertedGroups: Map = selectablesToMap(groups); + this._validateUserData('aggregate', convertedGroups); + + const internalOptions: InternalAggregateStageOptions = { + ...options, + accumulators: convertedAccumulators, + groups: convertedGroups, + }; + + return this._addStage(new Aggregate(internalOptions)); } - findNearest(options: firestore.Pipelines.FindNearestOptions): Pipeline { - return this._addStage(new FindNearest(options)); + /** + * Performs a vector proximity search on the documents from the previous stage, returning the + * K-nearest documents based on the specified query `vectorValue` and `distanceMeasure`. The + * returned documents will be sorted in order from nearest to furthest from the query `vectorValue`. + * + *

      Example: + * + * ```typescript + * // Find the 10 most similar books based on the book description. + * const bookDescription = "Lorem ipsum..."; + * const queryVector: number[] = ...; // compute embedding of `bookDescription` + * + * firestore.pipeline().collection("books") + * .findNearest({ + * field: 'embedding', + * vectorValue: queryVector, + * distanceMeasure: 'euclidean', + * limit: 10, // optional + * distanceField: 'computedDistance' // optional + * }); + * ``` + * + * @param options - An object that specifies required and optional parameters for the stage. + * @return A new {@code Pipeline} object with this stage appended to the stage list. + */ + findNearest(options: firestore.Pipelines.FindNearestStageOptions): Pipeline { + const field = toField(options.field); + const vectorValue = vectorToExpr(options.vectorValue); + const distanceField = options.distanceField + ? toField(options.distanceField) + : undefined; + + this._validateUserData('findNearest', field); + + this._validateUserData('findNearest', vectorValue); + + const internalOptions: InternalFindNearestStageOptions = { + ...options, + field, + vectorValue, + distanceField, + }; + + return this._addStage(new FindNearest(internalOptions)); } /** @@ -634,7 +1050,6 @@ export class Pipeline implements firestore.Pipelines.Pipeline { * @return A new {@code Pipeline} object with this stage appended to the stage list. */ replaceWith(fieldName: string): Pipeline; - /** * Fully overwrites all fields in a document with those coming from a map. * @@ -672,10 +1087,64 @@ export class Pipeline implements firestore.Pipelines.Pipeline { * @return A new {@code Pipeline} object with this stage appended to the stage list. */ replaceWith(expr: firestore.Pipelines.Expr): Pipeline; - replaceWith(value: firestore.Pipelines.Expr | string): Pipeline { - const expr = fieldOrExpression(value); - this.validateUserData('replaceWith', expr); - return this._addStage(new ReplaceWith(expr, 'full_replace')); + /** + * Fully overwrites all fields in a document with those coming from a map. + * + *

      This stage allows you to emit a map value as a document. Each key of the map becomes a field + * on the document that contains the corresponding value. + * + *

      Example: + * + * ```typescript + * // Input. + * // { + * // 'name': 'John Doe Jr.', + * // 'parents': { + * // 'father': 'John Doe Sr.', + * // 'mother': 'Jane Doe' + * // } + * // } + * + * // Emit parents as document. + * firestore.pipeline().collection('people').replaceWith(map({ + * foo: 'bar', + * info: { + * name: field('name') + * } + * })); + * + * // Output + * // { + * // 'father': 'John Doe Sr.', + * // 'mother': 'Jane Doe' + * // } + * ``` + * + * @param options - An object that specifies required and optional parameters for the stage. + * @return A new {@code Pipeline} object with this stage appended to the stage list. + */ + replaceWith(options: firestore.Pipelines.ReplaceWithStageOptions): Pipeline; + replaceWith( + valueOrOptions: + | firestore.Pipelines.Expr + | string + | firestore.Pipelines.ReplaceWithStageOptions + ): Pipeline { + const options = + isString(valueOrOptions) || isExpr(valueOrOptions) ? {} : valueOrOptions; + + const fieldNameOrExpr: string | firestore.Pipelines.Expr = + isString(valueOrOptions) || isExpr(valueOrOptions) + ? valueOrOptions + : valueOrOptions.map; + const mapExpr = fieldOrExpression(fieldNameOrExpr); + this._validateUserData('replaceWith', mapExpr); + + const internalOptions: InternalReplaceWithStageOptions = { + ...options, + map: mapExpr, + }; + return this._addStage(new ReplaceWith(internalOptions)); } /** @@ -713,26 +1182,35 @@ export class Pipeline implements firestore.Pipelines.Pipeline { * firestore.pipeline().collection("books") * .sample({ percentage: 0.5 }); * - * @param options The {@code SampleOptions} specifies how sampling is performed. + * @param options - An object that specifies required and optional parameters for the stage. * @return A new {@code Pipeline} object with this stage appended to the stage list. */ - sample(options: {percentage: number} | {documents: number}): Pipeline; + sample(options: firestore.Pipelines.SampleStageOptions): Pipeline; sample( - documentsOrOptions: number | {percentage: number} | {documents: number} + documentsOrOptions: number | firestore.Pipelines.SampleStageOptions ): Pipeline { - if (typeof documentsOrOptions === 'number') { - return this._addStage( - new Sample({limit: documentsOrOptions, mode: 'documents'}) - ); - } else if ('percentage' in documentsOrOptions) { - return this._addStage( - new Sample({limit: documentsOrOptions.percentage, mode: 'percent'}) - ); + const options = isNumber(documentsOrOptions) ? {} : documentsOrOptions; + + let rate: number; + let mode: 'documents' | 'percent'; + if (isNumber(documentsOrOptions)) { + rate = documentsOrOptions; + mode = 'documents'; + } else if (isNumber(documentsOrOptions.documents)) { + rate = documentsOrOptions.documents; + mode = 'documents'; } else { - return this._addStage( - new Sample({limit: documentsOrOptions.documents, mode: 'documents'}) - ); + rate = documentsOrOptions.percentage!; + mode = 'percent'; } + + const internalOptions: InternalSampleStageOptions = { + ...options, + rate, + mode, + }; + + return this._addStage(new Sample(internalOptions)); } /** @@ -753,8 +1231,45 @@ export class Pipeline implements firestore.Pipelines.Pipeline { * @param other The other {@code Pipeline} that is part of union. * @return A new {@code Pipeline} object with this stage appended to the stage list. */ - union(other: Pipeline): Pipeline { - return this._addStage(new Union(other)); + union(other: firestore.Pipelines.Pipeline): Pipeline; + /** + * Performs union of all documents from two pipelines, including duplicates. + * + *

      This stage will pass through documents from previous stage, and also pass through documents + * from previous stage of the `other` {@code Pipeline} given in parameter. The order of documents + * emitted from this stage is undefined. + * + *

      Example: + * + * ```typescript + * // Emit documents from books collection and magazines collection. + * firestore.pipeline().collection('books') + * .union(firestore.pipeline().collection('magazines')); + * ``` + * + * @param options - An object that specifies required and optional parameters for the stage. + * @return A new {@code Pipeline} object with this stage appended to the stage list. + */ + union(options: firestore.Pipelines.UnionStageOptions): Pipeline; + union( + otherOrOptions: + | firestore.Pipelines.Pipeline + | firestore.Pipelines.UnionStageOptions + ): Pipeline { + const options = isPipeline(otherOrOptions) ? {} : otherOrOptions; + + const otherPipeline: firestore.Pipelines.Pipeline = isPipeline( + otherOrOptions + ) + ? otherOrOptions + : otherOrOptions.other; + const normalizedOtherPipeline = otherPipeline as Pipeline; + + const internalOptions: InternalUnionStageOptions = { + ...options, + other: normalizedOtherPipeline, + }; + return this._addStage(new Union(internalOptions)); } /** @@ -792,14 +1307,71 @@ export class Pipeline implements firestore.Pipelines.Pipeline { unnest( selectable: firestore.Pipelines.Selectable, indexField?: string + ): Pipeline; + /** + * Produces a document for each element in an input array. + * + * For each previous stage document, this stage will emit zero or more augmented documents. The + * input array specified by the `selectable` parameter, will emit an augmented document for each input array element. The input array element will + * augment the previous stage document by setting the `alias` field with the array element value. + * + * When `selectable` evaluates to a non-array value (ex: number, null, absent), then the stage becomes a no-op for + * the current input document, returning it as is with the `alias` field absent. + * + * No documents are emitted when `selectable` evaluates to an empty array. + * + * Example: + * + * ```typescript + * // Input: + * // { "title": "The Hitchhiker's Guide to the Galaxy", "tags": [ "comedy", "space", "adventure" ], ... } + * + * // Emit a book document for each tag of the book. + * firestore.pipeline().collection("books") + * .unnest(field("tags").as('tag'), 'tagIndex'); + * + * // Output: + * // { "title": "The Hitchhiker's Guide to the Galaxy", "tag": "comedy", "tagIndex": 0, ... } + * // { "title": "The Hitchhiker's Guide to the Galaxy", "tag": "space", "tagIndex": 1, ... } + * // { "title": "The Hitchhiker's Guide to the Galaxy", "tag": "adventure", "tagIndex": 2, ... } + * ``` + * + * @param options - An object that specifies required and optional parameters for the stage. + * @return A new {@code Pipeline} object with this stage appended to the stage list. + */ + unnest(options: firestore.Pipelines.UnnestStageOptions): Pipeline; + unnest( + selectableOrOptions: + | firestore.Pipelines.Selectable + | firestore.Pipelines.UnnestStageOptions, + indexField?: string ): Pipeline { - return this._addStage( - new Unnest({ - expr: cast(selectable.expr), - alias: new Field(FieldPath.fromArgument(selectable.alias)), - indexField: indexField, - }) - ); + const options = isSelectable(selectableOrOptions) + ? {} + : selectableOrOptions; + + const selectable: firestore.Pipelines.Selectable = isSelectable( + selectableOrOptions + ) + ? selectableOrOptions + : selectableOrOptions.selectable; + const alias = selectable.alias; + const expr = selectable.expr as Expr; + + const indexFieldName = isSelectable(selectableOrOptions) + ? indexField + : selectableOrOptions.indexField; + const normalizedIndexField = indexFieldName + ? field(indexFieldName) + : undefined; + + const internalOptions: InternalUnnestStageOptions = { + ...options, + alias, + expr, + indexField: normalizedIndexField, + }; + return this._addStage(new Unnest(internalOptions)); } /** @@ -830,11 +1402,54 @@ export class Pipeline implements firestore.Pipelines.Pipeline { sort( ordering: firestore.Pipelines.Ordering, ...additionalOrderings: firestore.Pipelines.Ordering[] + ): Pipeline; + /** + * Sorts the documents from previous stages based on one or more {@link Ordering} criteria. + * + *

      This stage allows you to order the results of your pipeline. You can specify multiple {@link + * Ordering} instances to sort by multiple fields in ascending or descending order. If documents + * have the same value for a field used for sorting, the next specified ordering will be used. If + * all orderings result in equal comparison, the documents are considered equal and the order is + * unspecified. + * + *

      Example: + * + * ```typescript + * // Sort books by rating in descending order, and then by title in ascending order for books + * // with the same rating + * firestore.pipeline().collection("books") + * .sort( + * Ordering.of(field("rating")).descending(), + * Ordering.of(field("title")) // Ascending order is the default + * ); + * ``` + * + * @param options - An object that specifies required and optional parameters for the stage. + * @return A new {@code Pipeline} object with this stage appended to the stage list. + */ + sort(options: firestore.Pipelines.SortStageOptions): Pipeline; + sort( + orderingOrOptions: + | firestore.Pipelines.Ordering + | firestore.Pipelines.SortStageOptions, + ...additionalOrderings: firestore.Pipelines.Ordering[] ): Pipeline { - // Ordering object - const orderings = [ordering, ...additionalOrderings] as Ordering[]; - this.validateUserData('sort', orderings); - return this._addStage(new Sort(orderings)); + const options = isOrdering(orderingOrOptions) ? {} : orderingOrOptions; + + const orderings: Array = isOrdering( + orderingOrOptions + ) + ? [orderingOrOptions, ...additionalOrderings] + : orderingOrOptions.orderings; + const normalizedOrderings = orderings as Array; + this._validateUserData('sort', normalizedOrderings); + + const internalOptions: InternalSortStageOptions = { + ...options, + orderings: normalizedOrderings, + }; + + return this._addStage(new Sort(internalOptions)); } /** @@ -853,11 +1468,16 @@ export class Pipeline implements firestore.Pipelines.Pipeline { * .select('title', 'author'); * ``` * - * @param name The unique name of the generic stage to add. - * @param params A list of parameters to configure the generic stage's behavior. + * @param name - The unique name of the generic stage to add. + * @param params - A list of parameters to configure the generic stage's behavior. + * @param options - An object of key value pairs that specifies optional parameters for the stage. * @return A new {@code Pipeline} object with this stage appended to the stage list. */ - genericStage(name: string, params: unknown[]): Pipeline { + genericStage( + name: string, + params: unknown[], + options?: {[key: string]: Expr | unknown} + ): Pipeline { // Convert input values to Expressions. // We treat objects as mapValues and arrays as arrayValues, // this is unlike the default conversion for objects and arrays @@ -879,7 +1499,9 @@ export class Pipeline implements firestore.Pipelines.Pipeline { param._validateUserData(!!this.db._settings.ignoreUndefinedProperties); } }); - return this._addStage(new GenericStage(name, expressionParams)); + return this._addStage( + new GenericStage(name, expressionParams, options ?? {}) + ); } /** @@ -911,27 +1533,40 @@ export class Pipeline implements firestore.Pipelines.Pipeline { * .execute(); * ``` * + * @param pipelineOptions - Optionally specify pipeline execution behavior. * @return A Promise representing the asynchronous pipeline execution. */ - execute(): Promise { - return this._execute().then(response => { + execute(pipelineOptions?: PipelineOptions): Promise { + return this._execute(undefined, pipelineOptions).then(response => { const results = response.result || []; const executionTime = response.executionTime; + const stats = response.explainStats; - return new PipelineSnapshot(this, results, executionTime); + return new PipelineSnapshot(this, results, executionTime, stats); }); } _execute( transactionOrReadTime?: Uint8Array | Timestamp | api.ITransactionOptions, - explainOptions?: firestore.ExplainOptions + pipelineOptions?: PipelineOptions ): Promise { const util = new ExecutionUtil(this.db, this.db._serializer!); + const structuredPipeline = this._toStructuredPipeline(pipelineOptions); return util - ._getResponse(this, transactionOrReadTime, explainOptions) + ._getResponse(structuredPipeline, transactionOrReadTime) .then(result => result!); } + _toStructuredPipeline(pipelineOptions?: PipelineOptions): StructuredPipeline { + const structuredPipelineOptions = pipelineOptions ?? {}; + const optionsOverride = pipelineOptions?.customOptions ?? {}; + return new StructuredPipeline( + this, + structuredPipelineOptions, + optionsOverride + ); + } + /** * Executes this pipeline and streams the results as {@link PipelineResult}s. * @@ -959,24 +1594,212 @@ export class Pipeline implements firestore.Pipelines.Pipeline { ); return {stages}; } + + /** + * Validates user data for each expression in the expressionMap. + * @param name Name of the calling function. Used for error messages when invalid user data is encountered. + * @param val + * @return the expressionMap argument. + * @private + */ + _validateUserData< + T extends Map | HasUserData[] | HasUserData, + >(name: string, val: T): T { + const ignoreUndefinedProperties = + !!this.db._settings.ignoreUndefinedProperties; + if (hasUserData(val)) { + val._validateUserData(ignoreUndefinedProperties); + } else if (Array.isArray(val)) { + val.forEach(readableData => { + readableData._validateUserData(ignoreUndefinedProperties); + }); + } else { + val.forEach(expr => expr._validateUserData(ignoreUndefinedProperties)); + } + return val; + } +} + +function selectablesToMap( + selectables: (firestore.Pipelines.Selectable | string)[] +): Map { + const result = new Map(); + for (const selectable of selectables) { + if (typeof selectable === 'string') { + result.set( + selectable as string, + new Field(FieldPath.fromArgument(selectable)) + ); + } else if (selectable instanceof Field) { + result.set((selectable as Field).fieldName(), selectable); + } else if (selectable instanceof ExprWithAlias) { + const expr = selectable as ExprWithAlias; + result.set(expr.alias, expr.expr as unknown as Expr); + } else { + throw new Error('unexpected selectable: ' + JSON.stringify(selectable)); + } + } + return result; +} + +function aggregateWithAliasToMap( + aggregateWithAliases: firestore.Pipelines.AggregateWithAlias[] +): Map { + return aggregateWithAliases.reduce( + ( + map: Map, + selectable: firestore.Pipelines.AggregateWithAlias + ) => { + map.set(selectable.alias, selectable.aggregate as AggregateFunction); + return map; + }, + new Map() as Map + ); +} + +/** + * A wrapper object to access explain stats if explain or analyze + * was enabled for the Pipeline query execution. + */ +export class ExplainStats implements firestore.Pipelines.ExplainStats { + private static protoRoot: ProtoRoot | undefined = undefined; + + /** + * @private + * @internal + */ + static async _ensureMessageTypesLoaded(): Promise { + if (ExplainStats.protoRoot) { + return; + } + this.protoRoot = await loadProtos( + '../protos/google/protobuf/wrappers.proto' + ); + } + + /** + * @private + * @internal + * @hideconstructor + * @param _value + */ + constructor(private readonly explainStatsData: google.protobuf.IAny) {} + + /** + * Decode an ExplainStats proto message into a value. + * @private + * @internal + * @param explainStatsMessage + */ + _decode(): unknown { + if (!ExplainStats.protoRoot) { + throw new Error( + 'Ensure message types are loaded before attempting to decode ExplainStats' + ); + } + + if (!this.explainStatsData.value) { + throw new Error('Unexpected explainStatsMessage without data'); + } + + if (!this.explainStatsData.type_url) { + throw new Error('Unexpected explainStatsMessage without type_url'); + } + + const typeUrl = this.explainStatsData.type_url; + let reflectionObject: ReflectionObject | null = null; + const NAMESPACE = 'type.googleapis.com/'; + + if ( + !typeUrl.startsWith(NAMESPACE) || + !(reflectionObject = ExplainStats.protoRoot.lookup( + typeUrl.slice(NAMESPACE.length) + )) || + !(reflectionObject instanceof MessageType) + ) { + throw new Error( + `Unsupported explainStatsMessage type_url "${this.explainStatsData.type_url}". Use \`.rawMessage\` to get access to the encoded explainStats message and perform the protobuf parsing in your application.` + ); + } + + const messageType = reflectionObject as MessageType; + + return messageType.toObject(messageType.decode(this.explainStatsData.value)) + .value; + } + + /** + * When explain stats were requested with `outputFormat = 'json'`, this returns + * the explain stats object parsed from the JSON string returned from the Firestore + * backend. + * + * If explain stats were not requested with `outputFormat = 'json'`, the behavior + * of this method is not guaranteed and is expected to throw. + */ + get json(): {[key: string]: firestore.Pipelines.ExplainStatsFieldValue} { + const value = this._decode(); + if (isString(value)) { + try { + return JSON.parse(value); + } catch (error: unknown) { + logger('json', null, 'Error parsing explain stats to JSON.', error); + } + } + + throw new Error( + "Unable to convert explain stats to an object, ensure you requested `explainOptions.outputFormat = 'json'`" + ); + } + + /** + * When explain stats were requested with `outputFormat = 'text'`, this returns + * the explain stats string verbatium as returned from the Firestore backend. + * + * If explain stats were requested with `outputFormat = 'json'`, this returns + * the explain stats as stringified JSON, which was returned from the Firestore backend. + */ + get text(): string { + const value = this._decode(); + if (isString(value)) { + return value; + } + + throw new Error( + "Explain stats is not in a string format, ensure you requested an `explainOptions.outputFormat` that returns a string value, such as 'text'." + ); + } + + /** + * Returns the explain stats in an encoded proto format, as returned from the Firestore backend. + * The caller is responsible for unpacking this proto message. + */ + get rawData(): { + type_url?: string | null; + value?: Uint8Array | null; + } { + return this.explainStatsData; + } } /** * TODO(docs) */ -export class PipelineSnapshot { +export class PipelineSnapshot implements firestore.Pipelines.PipelineSnapshot { private readonly _pipeline: Pipeline; private readonly _executionTime: Timestamp | undefined; private readonly _results: PipelineResult[]; + private readonly _explainStats: ExplainStats | undefined; constructor( pipeline: Pipeline, results: PipelineResult[], - executionTime?: Timestamp + executionTime?: Timestamp, + explainStats?: ExplainStats ) { this._pipeline = pipeline; this._executionTime = executionTime; this._results = results; + this._explainStats = explainStats; } /** @@ -1007,6 +1830,15 @@ export class PipelineSnapshot { } return this._executionTime; } + + /** + * Return stats from query explain. + * + * If `explainOptions.mode` was set to `execute` or left unset, then this returns `undefined`. + */ + get explainStats(): ExplainStats | undefined { + return this._explainStats; + } } /** diff --git a/dev/src/pipelines/stage.ts b/dev/src/pipelines/stage.ts index 26f6fb2e9..378cb7223 100644 --- a/dev/src/pipelines/stage.ts +++ b/dev/src/pipelines/stage.ts @@ -16,19 +16,19 @@ import * as firestore from '@google-cloud/firestore'; import * as protos from '../../protos/firestore_v1_proto_api'; import api = protos.google.firestore.v1; -import {VectorValue} from '../field-value'; import {DocumentReference} from '../reference/document-reference'; import {ProtoSerializable, Serializer} from '../serializer'; import { AggregateFunction, + BooleanExpr, Expr, Field, - Ordering, field, - BooleanExpr, + Ordering, } from './expression'; -import {Pipeline} from './pipelines'; +import {OptionsUtil} from './options-util'; +import {CollectionReference} from '../reference/collection-reference'; /** * @@ -39,384 +39,553 @@ export interface Stage extends ProtoSerializable { _toProto(serializer: Serializer): api.Pipeline.IStage; } -/** - * - */ -export class AddFields implements Stage { - name = 'add_fields'; - - constructor(private fields: Map) {} - - _toProto(serializer: Serializer): api.Pipeline.IStage { - return { - name: this.name, - args: [serializer.encodeValue(this.fields)!], - }; - } -} +export type InternalRemoveFieldsStageOptions = Omit< + firestore.Pipelines.RemoveFieldsStageOptions, + 'fields' +> & { + fields: Array; +}; /** * */ export class RemoveFields implements Stage { name = 'remove_fields'; + readonly optionsUtil = new OptionsUtil({}); - constructor(private fields: Field[]) {} + constructor(private options: InternalRemoveFieldsStageOptions) {} _toProto(serializer: Serializer): api.Pipeline.IStage { return { name: this.name, - args: this.fields.map(f => serializer.encodeValue(f)!), + args: this.options.fields.map(f => serializer.encodeValue(f)!), + options: this.optionsUtil.getOptionsProto( + serializer, + this.options, + this.options.customOptions + ), }; } } +export type InternalAggregateStageOptions = Omit< + firestore.Pipelines.AggregateStageOptions, + 'groups' | 'accumulators' +> & { + groups: Map; + accumulators: Map; +}; + /** */ export class Aggregate implements Stage { name = 'aggregate'; + readonly optionsUtil = new OptionsUtil({}); - constructor( - private accumulators: Map, - private groups: Map - ) {} + constructor(private options: InternalAggregateStageOptions) {} _toProto(serializer: Serializer): api.Pipeline.IStage { return { name: this.name, args: [ - serializer.encodeValue(this.accumulators)!, - serializer.encodeValue(this.groups)!, + serializer.encodeValue(this.options.accumulators)!, + serializer.encodeValue(this.options.groups)!, ], + options: this.optionsUtil.getOptionsProto( + serializer, + this.options, + this.options.customOptions + ), }; } } +export type InternalDistinctStageOptions = Omit< + firestore.Pipelines.DistinctStageOptions, + 'groups' +> & { + groups: Map; +}; + /** * @beta */ export class Distinct implements Stage { name = 'distinct'; + readonly optionsUtil = new OptionsUtil({}); - constructor(private groups: Map) {} + constructor(private options: InternalDistinctStageOptions) {} _toProto(serializer: Serializer): api.Pipeline.IStage { return { name: this.name, - args: [serializer.encodeValue(this.groups)!], + args: [serializer.encodeValue(this.options.groups)!], + options: this.optionsUtil.getOptionsProto( + serializer, + this.options, + this.options.customOptions + ), }; } } +export type InternalCollectionStageOptions = Omit< + firestore.Pipelines.CollectionStageOptions, + 'collection' +> & { + collection: CollectionReference; +}; + /** * @beta */ export class CollectionSource implements Stage { name = 'collection'; - - constructor(private collectionPath: string) { + readonly optionsUtil = new OptionsUtil({ + forceIndex: { + serverName: 'force_index', + }, + }); + readonly collectionPath: string; + + constructor(private options: InternalCollectionStageOptions) { + this.collectionPath = this.options.collection.path; + // prepend slash to collection string if (!this.collectionPath.startsWith('/')) { this.collectionPath = '/' + this.collectionPath; } } - _toProto(_: Serializer): api.Pipeline.IStage { + _toProto(serializer: Serializer): api.Pipeline.IStage { return { name: this.name, - args: [{referenceValue: this.collectionPath}], + args: [serializer.encodeReference(this.collectionPath)], + options: this.optionsUtil.getOptionsProto( + serializer, + this.options, + this.options.customOptions + ), }; } } +export type InternalCollectionGroupStageOptions = + firestore.Pipelines.CollectionGroupStageOptions; + /** * @beta */ export class CollectionGroupSource implements Stage { name = 'collection_group'; + readonly optionsUtil = new OptionsUtil({ + forceIndex: { + serverName: 'force_index', + }, + }); - constructor(private collectionId: string) {} + constructor(private options: InternalCollectionGroupStageOptions) {} _toProto(serializer: Serializer): api.Pipeline.IStage { return { name: this.name, - args: [{referenceValue: ''}, serializer.encodeValue(this.collectionId)!], + args: [ + serializer.encodeReference(''), + serializer.encodeValue(this.options.collectionId)!, + ], + options: this.optionsUtil.getOptionsProto( + serializer, + this.options, + this.options.customOptions + ), }; } } +export type InternalDatabaseStageOptions = + firestore.Pipelines.DatabaseStageOptions; + /** * @beta */ export class DatabaseSource implements Stage { name = 'database'; + readonly optionsUtil = new OptionsUtil({}); - _toProto(_: Serializer): api.Pipeline.IStage { + constructor(private options: InternalDatabaseStageOptions) {} + + _toProto(serializer: Serializer): api.Pipeline.IStage { return { name: this.name, + options: this.optionsUtil.getOptionsProto( + serializer, + this.options, + this.options.customOptions + ), }; } } +export type InternalDocumentsStageOptions = Omit< + firestore.Pipelines.DocumentsStageOptions, + 'docs' +> & { + docs: Array; +}; + /** * @beta */ export class DocumentsSource implements Stage { name = 'documents'; + readonly optionsUtil = new OptionsUtil({}); + readonly formattedPaths: string[]; - constructor(private docPaths: string[]) {} - - static of(refs: Array): DocumentsSource { - return new DocumentsSource( - refs.map(ref => - ref instanceof DocumentReference - ? '/' + ref.path - : ref.startsWith('/') - ? ref - : '/' + ref - ) - ); + constructor(private options: InternalDocumentsStageOptions) { + this.formattedPaths = options.docs.map(ref => '/' + ref.path); } - _toProto(_: Serializer): api.Pipeline.IStage { + _toProto(serializer: Serializer): api.Pipeline.IStage { return { name: this.name, - args: this.docPaths.map(p => { - return {referenceValue: p}; - }), + args: this.formattedPaths.map(p => serializer.encodeReference(p)!), + options: this.optionsUtil.getOptionsProto( + serializer, + this.options, + this.options.customOptions + ), }; } } +export type InternalWhereStageOptions = Omit< + firestore.Pipelines.WhereStageOptions, + 'condition' +> & { + condition: BooleanExpr; +}; + /** * @beta */ export class Where implements Stage { name = 'where'; + readonly optionsUtil = new OptionsUtil({}); - constructor(private condition: BooleanExpr) {} + constructor(private options: InternalWhereStageOptions) {} _toProto(serializer: Serializer): api.Pipeline.IStage { return { name: this.name, - args: [(this.condition as unknown as Expr)._toProto(serializer)], + args: [this.options.condition._toProto(serializer)], + options: this.optionsUtil.getOptionsProto( + serializer, + this.options, + this.options.customOptions + ), }; } } -/** - * @beta - */ -export interface FindNearestOptions { - field: firestore.Pipelines.Field | string; - vectorValue: firestore.VectorValue | number[]; - distanceMeasure: 'euclidean' | 'cosine' | 'dot_product'; - limit?: number; - distanceField?: string; -} +export type InternalFindNearestStageOptions = Omit< + firestore.Pipelines.FindNearestStageOptions, + 'vectorValue' | 'field' | 'distanceField' +> & { + vectorValue: Expr; + field: Field; + distanceField?: Field; +}; /** * @beta */ export class FindNearest implements Stage { name = 'find_nearest'; + readonly optionsUtil = new OptionsUtil({ + limit: { + serverName: 'limit', + }, + distanceField: { + serverName: 'distance_field', + }, + }); - constructor(private _options: FindNearestOptions) {} + constructor(private _options: InternalFindNearestStageOptions) {} _toProto(serializer: Serializer): api.Pipeline.IStage { - const options: {[k: string]: api.IValue} = { - limit: serializer.encodeValue(this._options.limit)!, - }; - if (this._options.distanceField) { - options.distance_field = field(this._options.distanceField)._toProto( - serializer - ); - } - return { name: this.name, args: [ - (typeof this._options.field === 'string' - ? field(this._options.field) - : (this._options.field as unknown as Field) - )._toProto(serializer), - this._options.vectorValue instanceof VectorValue - ? serializer.encodeValue(this._options.vectorValue)! - : serializer.encodeVector(this._options.vectorValue as number[]), + serializer.encodeValue(this._options.field)!, + serializer.encodeValue(this._options.vectorValue)!, serializer.encodeValue(this._options.distanceMeasure)!, ], - options, + options: this.optionsUtil.getOptionsProto( + serializer, + this._options, + this._options.customOptions + ), }; } } -/** - * @beta - */ -export interface SampleOptions { - limit: number; - mode: 'documents' | 'percent'; -} +export type InternalSampleStageOptions = Omit< + firestore.Pipelines.SampleStageOptions, + 'percentage' | 'documents' +> & { + rate: number; + mode: 'percent' | 'documents'; +}; /** * @beta */ export class Sample implements Stage { name = 'sample'; + readonly optionsUtil = new OptionsUtil({}); - constructor(private _options: SampleOptions) {} + constructor(private options: InternalSampleStageOptions) {} _toProto(serializer: Serializer): api.Pipeline.IStage { return { name: this.name, args: [ - serializer.encodeValue(this._options.limit)!, - serializer.encodeValue(this._options.mode)!, + serializer.encodeValue(this.options.rate)!, + serializer.encodeValue(this.options.mode)!, ], + options: this.optionsUtil.getOptionsProto( + serializer, + this.options, + this.options.customOptions + ), }; } } +export type InternalUnionStageOptions = firestore.Pipelines.UnionStageOptions; + /** * @beta */ export class Union implements Stage { name = 'union'; + readonly optionsUtil = new OptionsUtil({}); - constructor(private _other: Pipeline) {} + constructor(private options: InternalUnionStageOptions) {} _toProto(serializer: Serializer): api.Pipeline.IStage { return { name: this.name, - args: [serializer.encodeValue(this._other)], + args: [serializer.encodeValue(this.options.other)!], + options: this.optionsUtil.getOptionsProto( + serializer, + this.options, + this.options.customOptions + ), }; } } -/** - * @beta - */ -export interface UnnestOptions { +export type InternalUnnestStageOptions = Omit< + firestore.Pipelines.UnnestStageOptions, + 'selectable' | 'indexField' +> & { + alias: string; expr: Expr; - alias: Field; - indexField?: string; -} + indexField?: Field; +}; /** * @beta */ export class Unnest implements Stage { name = 'unnest'; + readonly optionsUtil = new OptionsUtil({ + indexField: { + serverName: 'index_field', + }, + }); - constructor(private options: UnnestOptions) {} + constructor(private options: InternalUnnestStageOptions) {} _toProto(serializer: Serializer): api.Pipeline.IStage { - const args: api.IValue[] = [ - this.options.expr._toProto(serializer), - this.options.alias._toProto(serializer), - ]; - const indexField = this.options?.indexField; - if (indexField) { - return { - name: this.name, - args: args, - options: { - indexField: serializer.encodeValue(indexField), - }, - }; - } else { - return { - name: this.name, - args: args, - }; - } + return { + name: this.name, + args: [ + serializer.encodeValue(this.options.expr)!, + serializer.encodeValue(field(this.options.alias))!, + ], + options: this.optionsUtil.getOptionsProto( + serializer, + this.options, + this.options.customOptions + ), + }; } } +export type InternalLimitStageOptions = firestore.Pipelines.LimitStageOptions; + /** * @beta */ export class Limit implements Stage { name = 'limit'; + readonly optionsUtil = new OptionsUtil({}); - constructor(private limit: number) {} + constructor(private options: InternalLimitStageOptions) {} _toProto(serializer: Serializer): api.Pipeline.IStage { return { name: this.name, - args: [serializer.encodeValue(this.limit)!], + args: [serializer.encodeValue(this.options.limit)!], + options: this.optionsUtil.getOptionsProto( + serializer, + this.options, + this.options.customOptions + ), }; } } +export type InternalOffsetStageOptions = firestore.Pipelines.OffsetStageOptions; + /** * @beta */ export class Offset implements Stage { name = 'offset'; + readonly optionsUtil = new OptionsUtil({}); - constructor(private offset: number) {} + constructor(private options: InternalOffsetStageOptions) {} _toProto(serializer: Serializer): api.Pipeline.IStage { return { name: this.name, - args: [serializer.encodeValue(this.offset)!], + args: [serializer.encodeValue(this.options.offset)!], + options: this.optionsUtil.getOptionsProto( + serializer, + this.options, + this.options.customOptions + ), }; } } +export type InternalReplaceWithStageOptions = Omit< + firestore.Pipelines.ReplaceWithStageOptions, + 'map' +> & { + map: Expr; +}; + /** * @beta */ export class ReplaceWith implements Stage { name = 'replace_with'; + readonly optionsUtil = new OptionsUtil({}); - constructor( - private field: Expr, - private mode: - | 'full_replace' - | 'merge_prefer_nest' - | 'merge_prefer_parent' = 'full_replace' - ) {} + constructor(private options: InternalReplaceWithStageOptions) {} _toProto(serializer: Serializer): api.Pipeline.IStage { return { name: this.name, args: [ - serializer.encodeValue(this.field)!, - serializer.encodeValue(this.mode), + serializer.encodeValue(this.options.map)!, + serializer.encodeValue('full_replace'), ], + options: this.optionsUtil.getOptionsProto( + serializer, + this.options, + this.options.customOptions + ), }; } } +export type InternalSelectStageOptions = Omit< + firestore.Pipelines.SelectStageOptions, + 'selections' +> & { + selections: Map; +}; + /** * @beta */ export class Select implements Stage { name = 'select'; + readonly optionsUtil = new OptionsUtil({}); - constructor(private projections: Map) {} + constructor(private options: InternalSelectStageOptions) {} _toProto(serializer: Serializer): api.Pipeline.IStage { return { name: this.name, - args: [serializer.encodeValue(this.projections)!], + args: [serializer.encodeValue(this.options.selections)!], + options: this.optionsUtil.getOptionsProto( + serializer, + this.options, + this.options.customOptions + ), }; } } +export type InternalAddFieldsStageOptions = Omit< + firestore.Pipelines.AddFieldsStageOptions, + 'fields' +> & { + fields: Map; +}; + +/** + * + */ +export class AddFields implements Stage { + name = 'add_fields'; + readonly optionsUtil = new OptionsUtil({}); + + constructor(private options: InternalAddFieldsStageOptions) {} + + _toProto(serializer: Serializer): api.Pipeline.IStage { + return { + name: this.name, + args: [serializer.encodeValue(this.options.fields)!], + options: this.optionsUtil.getOptionsProto( + serializer, + this.options, + this.options.customOptions + ), + }; + } +} + +export type InternalSortStageOptions = Omit< + firestore.Pipelines.SortStageOptions, + 'orderings' +> & { + orderings: Array; +}; + /** * @beta */ export class Sort implements Stage { name = 'sort'; + readonly optionsUtil = new OptionsUtil({}); - constructor(private orders: Ordering[]) {} + constructor(private options: InternalSortStageOptions) {} _toProto(serializer: Serializer): api.Pipeline.IStage { return { name: this.name, - args: this.orders.map(o => o._toProto(serializer)), + args: this.options.orderings.map(o => serializer.encodeValue(o)!), + options: this.optionsUtil.getOptionsProto( + serializer, + this.options, + this.options.customOptions + ), }; } } @@ -425,13 +594,16 @@ export class Sort implements Stage { * @beta */ export class GenericStage implements Stage { + readonly optionsUtil = new OptionsUtil({}); + /** * @private * @internal */ constructor( public name: string, - private params: Array + private params: Array, + private rawOptions: Record ) {} /** @@ -442,6 +614,11 @@ export class GenericStage implements Stage { return { name: this.name, args: this.params.map(o => o._toProto(serializer)), + options: this.optionsUtil.getOptionsProto( + serializer, + {}, + this.rawOptions + ), }; } } diff --git a/dev/src/pipelines/structured-pipeline.ts b/dev/src/pipelines/structured-pipeline.ts new file mode 100644 index 000000000..69e9192de --- /dev/null +++ b/dev/src/pipelines/structured-pipeline.ts @@ -0,0 +1,68 @@ +/** + * @license + * Copyright 2025 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. + */ + +import {ProtoSerializable, Serializer} from '../serializer'; +import {google} from '../../protos/firestore_v1_proto_api'; +import IStructuredPipeline = google.firestore.v1.IStructuredPipeline; +import IPipeline = google.firestore.v1.IPipeline; +import {OptionsUtil} from './options-util'; + +export type StructuredPipelineOptions = { + indexMode?: 'recommended'; + explainOptions?: { + mode?: 'execute' | 'explain' | 'analyze'; + outputFormat?: 'text' | 'json'; + }; +}; + +export class StructuredPipeline + implements ProtoSerializable +{ + readonly optionsUtil = new OptionsUtil({ + indexMode: { + serverName: 'index_mode', + }, + explainOptions: { + serverName: 'explain_options', + nestedOptions: { + mode: { + serverName: 'mode', + }, + outputFormat: { + serverName: 'output_format', + }, + }, + }, + }); + + constructor( + private pipeline: ProtoSerializable, + private options: StructuredPipelineOptions, + private optionsOverride: Record + ) {} + + _toProto(serializer: Serializer): IStructuredPipeline { + return { + pipeline: this.pipeline._toProto(serializer), + options: this.optionsUtil.getOptionsProto( + serializer, + this.options, + this.optionsOverride + ), + }; + } +} diff --git a/dev/src/recursive-delete.ts b/dev/src/recursive-delete.ts index 676875087..713bd165a 100644 --- a/dev/src/recursive-delete.ts +++ b/dev/src/recursive-delete.ts @@ -291,7 +291,7 @@ export class RecursiveDelete { if (this.lastError === undefined) { this.completionDeferred.resolve(); } else { - let error = new (require('google-gax/build/src/fallback').GoogleError)( + let error = new (require('google-gax/fallback').GoogleError)( `${this.errorCount} ` + `${this.errorCount !== 1 ? 'deletes' : 'delete'} ` + 'failed. The last delete failed with: ' diff --git a/dev/src/reference/aggregate-query.ts b/dev/src/reference/aggregate-query.ts index e075dcc2f..8143a9c37 100644 --- a/dev/src/reference/aggregate-query.ts +++ b/dev/src/reference/aggregate-query.ts @@ -337,7 +337,7 @@ export class AggregateQuery< if (transactionOrReadTime instanceof Uint8Array) { runQueryRequest.transaction = transactionOrReadTime; } else if (transactionOrReadTime instanceof Timestamp) { - runQueryRequest.readTime = transactionOrReadTime; + runQueryRequest.readTime = transactionOrReadTime.toProto().timestampValue; } else if (transactionOrReadTime) { runQueryRequest.newTransaction = transactionOrReadTime; } diff --git a/dev/src/reference/collection-reference.ts b/dev/src/reference/collection-reference.ts index fb4475dd7..bf857f2e7 100644 --- a/dev/src/reference/collection-reference.ts +++ b/dev/src/reference/collection-reference.ts @@ -183,10 +183,6 @@ export class CollectionReference< parent: parentPath.formattedName, collectionId: this.id, showMissing: true, - // Setting `pageSize` to an arbitrarily large value lets the backend cap - // the page size (currently to 300). Note that the backend rejects - // MAX_INT32 (b/146883794). - pageSize: Math.pow(2, 16) - 1, mask: {fieldPaths: []}, }; diff --git a/dev/src/reference/document-reference.ts b/dev/src/reference/document-reference.ts index ecacde931..40ed72788 100644 --- a/dev/src/reference/document-reference.ts +++ b/dev/src/reference/document-reference.ts @@ -267,10 +267,6 @@ export class DocumentReference< return this.firestore.initializeIfNeeded(tag).then(() => { const request: api.IListCollectionIdsRequest = { parent: this.formattedName, - // Setting `pageSize` to an arbitrarily large value lets the backend cap - // the page size (currently to 300). Note that the backend rejects - // MAX_INT32 (b/146883794). - pageSize: Math.pow(2, 16) - 1, }; return this._firestore .request< diff --git a/dev/src/reference/types.ts b/dev/src/reference/types.ts index 9d56a3890..884eb8bc2 100644 --- a/dev/src/reference/types.ts +++ b/dev/src/reference/types.ts @@ -23,6 +23,7 @@ import {ExplainMetrics} from '../query-profile'; import {QueryDocumentSnapshot} from '../document'; import * as firestore from '@google-cloud/firestore'; +import {ExplainStats} from '../pipelines/pipelines'; export interface QueryStreamElement< AppModelType = firestore.DocumentData, @@ -63,15 +64,15 @@ export enum LimitType { export interface PipelineStreamElement { transaction?: Uint8Array; executionTime?: Timestamp; - explainMetrics?: ExplainMetrics; + explainStats?: ExplainStats; result?: PipelineResult; } export interface PipelineResponse { transaction?: Uint8Array; executionTime?: Timestamp; - explainMetrics?: ExplainMetrics; result?: Array; + explainStats?: ExplainStats; } /** diff --git a/dev/src/reference/vector-query.ts b/dev/src/reference/vector-query.ts index 3f06a88ee..6f6abfff0 100644 --- a/dev/src/reference/vector-query.ts +++ b/dev/src/reference/vector-query.ts @@ -19,7 +19,6 @@ import api = protos.google.firestore.v1; import * as firestore from '@google-cloud/firestore'; import {field} from '../pipelines'; import {Pipeline} from '../pipelines'; -import {FindNearestOptions} from '../pipelines'; import {Timestamp} from '../timestamp'; import {VectorValue} from '../field-value'; @@ -142,7 +141,7 @@ export class VectorQuery< } toPipeline(): Pipeline { - const options: FindNearestOptions = { + const options: firestore.Pipelines.FindNearestStageOptions = { field: field(this._options.vectorField), vectorValue: this._options.queryVector, limit: this._options.limit, diff --git a/dev/src/serializer.ts b/dev/src/serializer.ts index 01d0a79d3..b92fadfcb 100644 --- a/dev/src/serializer.ts +++ b/dev/src/serializer.ts @@ -14,7 +14,7 @@ * limitations under the License. */ -import {DocumentData} from '@google-cloud/firestore'; +import * as firestore from '@google-cloud/firestore'; import * as proto from '../protos/firestore_v1_proto_api'; @@ -22,10 +22,10 @@ import {DeleteTransform, FieldTransform, VectorValue} from './field-value'; import {detectGoogleProtobufValueType, detectValueType} from './convert'; import {GeoPoint} from './geo-point'; import {DocumentReference, Firestore} from './index'; -import {FieldPath, QualifiedResourcePath} from './path'; +import {FieldPath, ObjectValueFieldPath, QualifiedResourcePath} from './path'; import {Timestamp} from './timestamp'; import {ApiMapValue, ValidationOptions} from './types'; -import {isEmpty, isObject, isPlainObject} from './util'; +import {forEach, isEmpty, isObject, isPlainObject} from './util'; import {customObjectMessage, invalidArgumentMessage} from './validate'; import {Pipeline} from './pipelines'; @@ -35,6 +35,11 @@ import { RESERVED_MAP_KEY_VECTOR_VALUE, VECTOR_MAP_VECTORS_KEY, } from './map-type'; +import {google} from '../protos/firestore_v1_proto_api'; +import IMapValue = google.firestore.v1.IMapValue; +import IValue = google.firestore.v1.IValue; +import Value = google.firestore.v1.Value; +import {isString} from './pipelines/pipeline-util'; /** * The maximum depth of a Firestore object. @@ -84,7 +89,7 @@ export class Serializer { * @param obj The object to encode. * @returns The Firestore 'Fields' representation */ - encodeFields(obj: DocumentData): ApiMapValue { + encodeFields(obj: firestore.DocumentData): ApiMapValue { const fields: ApiMapValue = {}; for (const prop of Object.keys(obj)) { @@ -271,6 +276,14 @@ export class Serializer { throw new Error(`Cannot encode value: ${val}`); } + encodeReference( + path: string | firestore.DocumentReference | firestore.CollectionReference + ): api.IValue { + return { + referenceValue: isString(path) ? path : path.path, + }; + } + /** * @private */ @@ -344,7 +357,7 @@ export class Serializer { case 'mapValue': { const fields = proto.mapValue!.fields; if (fields) { - const obj: DocumentData = {}; + const obj: firestore.DocumentData = {}; for (const prop of Object.keys(fields)) { obj[prop] = this.decodeValue(fields[prop]); } @@ -639,3 +652,103 @@ export interface HasUserData { export function hasUserData(value: unknown): value is HasUserData { return typeof (value as HasUserData)._validateUserData === 'function'; } + +/** + * An ObjectValue represents a MapValue in the Firestore Proto and offers the + * ability to add and remove fields. + */ +export class ObjectValue { + constructor(readonly value: {mapValue: IMapValue}) {} + + static empty(): ObjectValue { + return new ObjectValue({mapValue: {}}); + } + + /** + * Sets the field to the provided value. + * + * @param path - The field path to set. + * @param value - The value to set. + */ + set(path: ObjectValueFieldPath, value: IValue): void { + const fieldsMap = this.getFieldsMap(path.popLast()); + fieldsMap[path.lastSegment()] = Value.fromObject(value).toJSON(); + } + + /** + * Sets the provided fields to the provided values. + * + * @param data - A map of fields to values (or null for deletes). + */ + setAll(data: Map): void { + let parent = new ObjectValueFieldPath(); + + let upserts: {[key: string]: IValue} = {}; + let deletes: string[] = []; + + data.forEach((value, path) => { + if (!parent.isImmediateParentOf(path)) { + // Insert the accumulated changes at this parent location + const fieldsMap = this.getFieldsMap(parent); + this.applyChanges(fieldsMap, upserts, deletes); + upserts = {}; + deletes = []; + parent = path.popLast(); + } + + if (value) { + upserts[path.lastSegment()] = Value.fromObject(value).toJSON(); + } else { + deletes.push(path.lastSegment()); + } + }); + + const fieldsMap = this.getFieldsMap(parent); + this.applyChanges(fieldsMap, upserts, deletes); + } + + /** + * Returns the map that contains the leaf element of `path`. If the parent + * entry does not yet exist, or if it is not a map, a new map will be created. + */ + private getFieldsMap(path: ObjectValueFieldPath): Record { + let current = this.value; + + if (!current.mapValue!.fields) { + current.mapValue = {fields: {}}; + } + + for (let i = 0; i < path.size; ++i) { + let next = current.mapValue!.fields![path.get(i)]; + if (!isMapValue(next) || !next.mapValue.fields) { + next = {mapValue: {fields: {}}}; + current.mapValue!.fields![path.get(i)] = next; + } + current = next as {mapValue: IMapValue}; + } + + return current.mapValue!.fields!; + } + + /** + * Modifies `fieldsMap` by adding, replacing or deleting the specified + * entries. + */ + private applyChanges( + fieldsMap: Record, + inserts: {[key: string]: IValue}, + deletes: string[] + ): void { + forEach(inserts, (key, val) => (fieldsMap[key] = val)); + for (const field of deletes) { + delete fieldsMap[field]; + } + } +} + +/** Returns true if `value` is a MapValue. */ +export function isMapValue( + value?: IValue | null +): value is {mapValue: IMapValue} { + return !!value && 'mapValue' in value; +} diff --git a/dev/src/util.ts b/dev/src/util.ts index a02589b28..2e55e69b2 100644 --- a/dev/src/util.ts +++ b/dev/src/util.ts @@ -162,11 +162,11 @@ let serviceConfig: Record | undefined; **/ function getServiceConfig(methodName: string): CallSettings | undefined { if (!serviceConfig) { - serviceConfig = require('google-gax/build/src/fallback').constructSettings( + serviceConfig = require('google-gax/fallback').constructSettings( 'google.firestore.v1.Firestore', gapicConfig as ClientConfig, {}, - require('google-gax/build/src/status').Status + require('google-gax').Status ) as {[k: string]: CallSettings}; } return serviceConfig[methodName]; @@ -205,7 +205,7 @@ export function getTotalTimeout(methodName: string): number { export function getRetryParams(methodName: string): BackoffSettings { return ( getServiceConfig(methodName)?.retry?.backoffSettings ?? - require('google-gax/build/src/fallback').createDefaultBackoffSettings() + require('google-gax/fallback').createDefaultBackoffSettings() ); } @@ -378,3 +378,14 @@ export function cast( throw new Error(`${val} not instance of ${constructor}`); } + +export function forEach( + obj: Record | undefined, + fn: (key: string, val: V) => void +): void { + for (const key in obj) { + if (Object.prototype.hasOwnProperty.call(obj, key)) { + fn(key, obj[key]); + } + } +} diff --git a/dev/src/v1/firestore_admin_client.ts b/dev/src/v1/firestore_admin_client.ts index dfddc415c..5440bff09 100644 --- a/dev/src/v1/firestore_admin_client.ts +++ b/dev/src/v1/firestore_admin_client.ts @@ -18,7 +18,18 @@ /* global window */ import type * as gax from 'google-gax'; -import type {Callback, CallOptions, Descriptors, ClientOptions, GrpcClientOptions, LROperation, PaginationCallback, GaxCall, LocationsClient, LocationProtos} from 'google-gax'; +import type { + Callback, + CallOptions, + Descriptors, + ClientOptions, + GrpcClientOptions, + LROperation, + PaginationCallback, + GaxCall, + LocationsClient, + LocationProtos, +} from 'google-gax'; import {Transform} from 'stream'; import * as protos from '../../protos/firestore_admin_v1_proto_api'; import jsonProtos = require('../../protos/admin_v1.json'); @@ -129,20 +140,41 @@ export class FirestoreAdminClient { * const client = new FirestoreAdminClient({fallback: true}, gax); * ``` */ - constructor(opts?: ClientOptions, gaxInstance?: typeof gax | typeof gax.fallback) { + constructor( + opts?: ClientOptions, + gaxInstance?: typeof gax | typeof gax.fallback + ) { // Ensure that options include all the required fields. const staticMembers = this.constructor as typeof FirestoreAdminClient; - if (opts?.universe_domain && opts?.universeDomain && opts?.universe_domain !== opts?.universeDomain) { - throw new Error('Please set either universe_domain or universeDomain, but not both.'); + if ( + opts?.universe_domain && + opts?.universeDomain && + opts?.universe_domain !== opts?.universeDomain + ) { + throw new Error( + 'Please set either universe_domain or universeDomain, but not both.' + ); } - const universeDomainEnvVar = (typeof process === 'object' && typeof process.env === 'object') ? process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] : undefined; - this._universeDomain = opts?.universeDomain ?? opts?.universe_domain ?? universeDomainEnvVar ?? 'googleapis.com'; + const universeDomainEnvVar = + typeof process === 'object' && typeof process.env === 'object' + ? process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] + : undefined; + this._universeDomain = + opts?.universeDomain ?? + opts?.universe_domain ?? + universeDomainEnvVar ?? + 'googleapis.com'; this._servicePath = 'firestore.' + this._universeDomain; - const servicePath = opts?.servicePath || opts?.apiEndpoint || this._servicePath; - this._providedCustomServicePath = !!(opts?.servicePath || opts?.apiEndpoint); + const servicePath = + opts?.servicePath || opts?.apiEndpoint || this._servicePath; + this._providedCustomServicePath = !!( + opts?.servicePath || opts?.apiEndpoint + ); const port = opts?.port || staticMembers.port; const clientConfig = opts?.clientConfig ?? {}; - const fallback = opts?.fallback ?? (typeof window !== 'undefined' && typeof window?.fetch === 'function'); + const fallback = + opts?.fallback ?? + (typeof window !== 'undefined' && typeof window?.fetch === 'function'); opts = Object.assign({servicePath, port, clientConfig, fallback}, opts); // Request numeric enum values if REST transport is used. @@ -168,7 +200,7 @@ export class FirestoreAdminClient { this._opts = opts; // Save the auth object to the client, for use by other methods. - this.auth = (this._gaxGrpc.auth as gax.GoogleAuth); + this.auth = this._gaxGrpc.auth as gax.GoogleAuth; // Set useJWTAccessWithScope on the auth object. this.auth.useJWTAccessWithScope = true; @@ -184,13 +216,9 @@ export class FirestoreAdminClient { this._gaxGrpc, opts ); - // Determine the client header string. - const clientHeader = [ - `gax/${this._gaxModule.version}`, - `gapic/${version}`, - ]; + const clientHeader = [`gax/${this._gaxModule.version}`, `gapic/${version}`]; if (typeof process === 'object' && 'versions' in process) { clientHeader.push(`gl-node/${process.versions.node}`); } else { @@ -244,10 +272,16 @@ export class FirestoreAdminClient { // (e.g. 50 results at a time, with tokens to get subsequent // pages). Denote the keys used for pagination and results. this.descriptors.page = { - listIndexes: - new this._gaxModule.PageDescriptor('pageToken', 'nextPageToken', 'indexes'), - listFields: - new this._gaxModule.PageDescriptor('pageToken', 'nextPageToken', 'fields') + listIndexes: new this._gaxModule.PageDescriptor( + 'pageToken', + 'nextPageToken', + 'indexes' + ), + listFields: new this._gaxModule.PageDescriptor( + 'pageToken', + 'nextPageToken', + 'fields' + ), }; const protoFilesRoot = this._gaxModule.protobuf.Root.fromJSON(jsonProtos); @@ -256,93 +290,143 @@ export class FirestoreAdminClient { // rather than holding a request open. const lroOptions: GrpcClientOptions = { auth: this.auth, - grpc: 'grpc' in this._gaxGrpc ? this._gaxGrpc.grpc : undefined + grpc: 'grpc' in this._gaxGrpc ? this._gaxGrpc.grpc : undefined, }; if (opts.fallback) { lroOptions.protoJson = protoFilesRoot; - lroOptions.httpRules = [{selector: 'google.longrunning.Operations.CancelOperation',post: '/v1/{name=projects/*/databases/*/operations/*}:cancel',body: '*',},{selector: 'google.longrunning.Operations.DeleteOperation',delete: '/v1/{name=projects/*/databases/*/operations/*}',},{selector: 'google.longrunning.Operations.GetOperation',get: '/v1/{name=projects/*/databases/*/operations/*}',},{selector: 'google.longrunning.Operations.ListOperations',get: '/v1/{name=projects/*/databases/*}/operations',}]; + lroOptions.httpRules = [ + { + selector: 'google.longrunning.Operations.CancelOperation', + post: '/v1/{name=projects/*/databases/*/operations/*}:cancel', + body: '*', + }, + { + selector: 'google.longrunning.Operations.DeleteOperation', + delete: '/v1/{name=projects/*/databases/*/operations/*}', + }, + { + selector: 'google.longrunning.Operations.GetOperation', + get: '/v1/{name=projects/*/databases/*/operations/*}', + }, + { + selector: 'google.longrunning.Operations.ListOperations', + get: '/v1/{name=projects/*/databases/*}/operations', + }, + ]; } - this.operationsClient = this._gaxModule.lro(lroOptions).operationsClient(opts); + this.operationsClient = this._gaxModule + .lro(lroOptions) + .operationsClient(opts); const createIndexResponse = protoFilesRoot.lookup( - '.google.firestore.admin.v1.Index') as gax.protobuf.Type; + '.google.firestore.admin.v1.Index' + ) as gax.protobuf.Type; const createIndexMetadata = protoFilesRoot.lookup( - '.google.firestore.admin.v1.IndexOperationMetadata') as gax.protobuf.Type; + '.google.firestore.admin.v1.IndexOperationMetadata' + ) as gax.protobuf.Type; const updateFieldResponse = protoFilesRoot.lookup( - '.google.firestore.admin.v1.Field') as gax.protobuf.Type; + '.google.firestore.admin.v1.Field' + ) as gax.protobuf.Type; const updateFieldMetadata = protoFilesRoot.lookup( - '.google.firestore.admin.v1.FieldOperationMetadata') as gax.protobuf.Type; + '.google.firestore.admin.v1.FieldOperationMetadata' + ) as gax.protobuf.Type; const exportDocumentsResponse = protoFilesRoot.lookup( - '.google.firestore.admin.v1.ExportDocumentsResponse') as gax.protobuf.Type; + '.google.firestore.admin.v1.ExportDocumentsResponse' + ) as gax.protobuf.Type; const exportDocumentsMetadata = protoFilesRoot.lookup( - '.google.firestore.admin.v1.ExportDocumentsMetadata') as gax.protobuf.Type; + '.google.firestore.admin.v1.ExportDocumentsMetadata' + ) as gax.protobuf.Type; const importDocumentsResponse = protoFilesRoot.lookup( - '.google.protobuf.Empty') as gax.protobuf.Type; + '.google.protobuf.Empty' + ) as gax.protobuf.Type; const importDocumentsMetadata = protoFilesRoot.lookup( - '.google.firestore.admin.v1.ImportDocumentsMetadata') as gax.protobuf.Type; + '.google.firestore.admin.v1.ImportDocumentsMetadata' + ) as gax.protobuf.Type; const bulkDeleteDocumentsResponse = protoFilesRoot.lookup( - '.google.firestore.admin.v1.BulkDeleteDocumentsResponse') as gax.protobuf.Type; + '.google.firestore.admin.v1.BulkDeleteDocumentsResponse' + ) as gax.protobuf.Type; const bulkDeleteDocumentsMetadata = protoFilesRoot.lookup( - '.google.firestore.admin.v1.BulkDeleteDocumentsMetadata') as gax.protobuf.Type; + '.google.firestore.admin.v1.BulkDeleteDocumentsMetadata' + ) as gax.protobuf.Type; const createDatabaseResponse = protoFilesRoot.lookup( - '.google.firestore.admin.v1.Database') as gax.protobuf.Type; + '.google.firestore.admin.v1.Database' + ) as gax.protobuf.Type; const createDatabaseMetadata = protoFilesRoot.lookup( - '.google.firestore.admin.v1.CreateDatabaseMetadata') as gax.protobuf.Type; + '.google.firestore.admin.v1.CreateDatabaseMetadata' + ) as gax.protobuf.Type; const updateDatabaseResponse = protoFilesRoot.lookup( - '.google.firestore.admin.v1.Database') as gax.protobuf.Type; + '.google.firestore.admin.v1.Database' + ) as gax.protobuf.Type; const updateDatabaseMetadata = protoFilesRoot.lookup( - '.google.firestore.admin.v1.UpdateDatabaseMetadata') as gax.protobuf.Type; + '.google.firestore.admin.v1.UpdateDatabaseMetadata' + ) as gax.protobuf.Type; const deleteDatabaseResponse = protoFilesRoot.lookup( - '.google.firestore.admin.v1.Database') as gax.protobuf.Type; + '.google.firestore.admin.v1.Database' + ) as gax.protobuf.Type; const deleteDatabaseMetadata = protoFilesRoot.lookup( - '.google.firestore.admin.v1.DeleteDatabaseMetadata') as gax.protobuf.Type; + '.google.firestore.admin.v1.DeleteDatabaseMetadata' + ) as gax.protobuf.Type; const restoreDatabaseResponse = protoFilesRoot.lookup( - '.google.firestore.admin.v1.Database') as gax.protobuf.Type; + '.google.firestore.admin.v1.Database' + ) as gax.protobuf.Type; const restoreDatabaseMetadata = protoFilesRoot.lookup( - '.google.firestore.admin.v1.RestoreDatabaseMetadata') as gax.protobuf.Type; + '.google.firestore.admin.v1.RestoreDatabaseMetadata' + ) as gax.protobuf.Type; this.descriptors.longrunning = { createIndex: new this._gaxModule.LongrunningDescriptor( this.operationsClient, createIndexResponse.decode.bind(createIndexResponse), - createIndexMetadata.decode.bind(createIndexMetadata)), + createIndexMetadata.decode.bind(createIndexMetadata) + ), updateField: new this._gaxModule.LongrunningDescriptor( this.operationsClient, updateFieldResponse.decode.bind(updateFieldResponse), - updateFieldMetadata.decode.bind(updateFieldMetadata)), + updateFieldMetadata.decode.bind(updateFieldMetadata) + ), exportDocuments: new this._gaxModule.LongrunningDescriptor( this.operationsClient, exportDocumentsResponse.decode.bind(exportDocumentsResponse), - exportDocumentsMetadata.decode.bind(exportDocumentsMetadata)), + exportDocumentsMetadata.decode.bind(exportDocumentsMetadata) + ), importDocuments: new this._gaxModule.LongrunningDescriptor( this.operationsClient, importDocumentsResponse.decode.bind(importDocumentsResponse), - importDocumentsMetadata.decode.bind(importDocumentsMetadata)), + importDocumentsMetadata.decode.bind(importDocumentsMetadata) + ), bulkDeleteDocuments: new this._gaxModule.LongrunningDescriptor( this.operationsClient, bulkDeleteDocumentsResponse.decode.bind(bulkDeleteDocumentsResponse), - bulkDeleteDocumentsMetadata.decode.bind(bulkDeleteDocumentsMetadata)), + bulkDeleteDocumentsMetadata.decode.bind(bulkDeleteDocumentsMetadata) + ), createDatabase: new this._gaxModule.LongrunningDescriptor( this.operationsClient, createDatabaseResponse.decode.bind(createDatabaseResponse), - createDatabaseMetadata.decode.bind(createDatabaseMetadata)), + createDatabaseMetadata.decode.bind(createDatabaseMetadata) + ), updateDatabase: new this._gaxModule.LongrunningDescriptor( this.operationsClient, updateDatabaseResponse.decode.bind(updateDatabaseResponse), - updateDatabaseMetadata.decode.bind(updateDatabaseMetadata)), + updateDatabaseMetadata.decode.bind(updateDatabaseMetadata) + ), deleteDatabase: new this._gaxModule.LongrunningDescriptor( this.operationsClient, deleteDatabaseResponse.decode.bind(deleteDatabaseResponse), - deleteDatabaseMetadata.decode.bind(deleteDatabaseMetadata)), + deleteDatabaseMetadata.decode.bind(deleteDatabaseMetadata) + ), restoreDatabase: new this._gaxModule.LongrunningDescriptor( this.operationsClient, restoreDatabaseResponse.decode.bind(restoreDatabaseResponse), - restoreDatabaseMetadata.decode.bind(restoreDatabaseMetadata)) + restoreDatabaseMetadata.decode.bind(restoreDatabaseMetadata) + ), }; // Put together the default options sent with requests. this._defaults = this._gaxGrpc.constructSettings( - 'google.firestore.admin.v1.FirestoreAdmin', gapicConfig as gax.ClientConfig, - opts.clientConfig || {}, {'x-goog-api-client': clientHeader.join(' ')}); + 'google.firestore.admin.v1.FirestoreAdmin', + gapicConfig as gax.ClientConfig, + opts.clientConfig || {}, + {'x-goog-api-client': clientHeader.join(' ')} + ); // Set up a dictionary of "inner API calls"; the core implementation // of calling the API is handled in `google-gax`, with this code @@ -373,28 +457,65 @@ export class FirestoreAdminClient { // Put together the "service stub" for // google.firestore.admin.v1.FirestoreAdmin. this.firestoreAdminStub = this._gaxGrpc.createStub( - this._opts.fallback ? - (this._protos as protobuf.Root).lookupService('google.firestore.admin.v1.FirestoreAdmin') : - // eslint-disable-next-line @typescript-eslint/no-explicit-any + this._opts.fallback + ? (this._protos as protobuf.Root).lookupService( + 'google.firestore.admin.v1.FirestoreAdmin' + ) + : // eslint-disable-next-line @typescript-eslint/no-explicit-any (this._protos as any).google.firestore.admin.v1.FirestoreAdmin, - this._opts, this._providedCustomServicePath) as Promise<{[method: string]: Function}>; + this._opts, + this._providedCustomServicePath + ) as Promise<{[method: string]: Function}>; // Iterate over each of the methods that the service provides // and create an API call method for each. - const firestoreAdminStubMethods = - ['createIndex', 'listIndexes', 'getIndex', 'deleteIndex', 'getField', 'updateField', 'listFields', 'exportDocuments', 'importDocuments', 'bulkDeleteDocuments', 'createDatabase', 'getDatabase', 'listDatabases', 'updateDatabase', 'deleteDatabase', 'createUserCreds', 'getUserCreds', 'listUserCreds', 'enableUserCreds', 'disableUserCreds', 'resetUserPassword', 'deleteUserCreds', 'getBackup', 'listBackups', 'deleteBackup', 'restoreDatabase', 'createBackupSchedule', 'getBackupSchedule', 'listBackupSchedules', 'updateBackupSchedule', 'deleteBackupSchedule']; + const firestoreAdminStubMethods = [ + 'createIndex', + 'listIndexes', + 'getIndex', + 'deleteIndex', + 'getField', + 'updateField', + 'listFields', + 'exportDocuments', + 'importDocuments', + 'bulkDeleteDocuments', + 'createDatabase', + 'getDatabase', + 'listDatabases', + 'updateDatabase', + 'deleteDatabase', + 'createUserCreds', + 'getUserCreds', + 'listUserCreds', + 'enableUserCreds', + 'disableUserCreds', + 'resetUserPassword', + 'deleteUserCreds', + 'getBackup', + 'listBackups', + 'deleteBackup', + 'restoreDatabase', + 'createBackupSchedule', + 'getBackupSchedule', + 'listBackupSchedules', + 'updateBackupSchedule', + 'deleteBackupSchedule', + ]; for (const methodName of firestoreAdminStubMethods) { const callPromise = this.firestoreAdminStub.then( - stub => (...args: Array<{}>) => { - if (this._terminated) { - return Promise.reject('The client has already been closed.'); - } - const func = stub[methodName]; - return func.apply(stub, args); - }, - (err: Error|null|undefined) => () => { + stub => + (...args: Array<{}>) => { + if (this._terminated) { + return Promise.reject('The client has already been closed.'); + } + const func = stub[methodName]; + return func.apply(stub, args); + }, + (err: Error | null | undefined) => () => { throw err; - }); + } + ); const descriptor = this.descriptors.page[methodName] || @@ -419,8 +540,14 @@ export class FirestoreAdminClient { * @returns {string} The DNS address for this service. */ static get servicePath() { - if (typeof process === 'object' && typeof process.emitWarning === 'function') { - process.emitWarning('Static servicePath is deprecated, please use the instance method instead.', 'DeprecationWarning'); + if ( + typeof process === 'object' && + typeof process.emitWarning === 'function' + ) { + process.emitWarning( + 'Static servicePath is deprecated, please use the instance method instead.', + 'DeprecationWarning' + ); } return 'firestore.googleapis.com'; } @@ -431,8 +558,14 @@ export class FirestoreAdminClient { * @returns {string} The DNS address for this service. */ static get apiEndpoint() { - if (typeof process === 'object' && typeof process.emitWarning === 'function') { - process.emitWarning('Static apiEndpoint is deprecated, please use the instance method instead.', 'DeprecationWarning'); + if ( + typeof process === 'object' && + typeof process.emitWarning === 'function' + ) { + process.emitWarning( + 'Static apiEndpoint is deprecated, please use the instance method instead.', + 'DeprecationWarning' + ); } return 'firestore.googleapis.com'; } @@ -465,7 +598,7 @@ export class FirestoreAdminClient { static get scopes() { return [ 'https://www.googleapis.com/auth/cloud-platform', - 'https://www.googleapis.com/auth/datastore' + 'https://www.googleapis.com/auth/datastore', ]; } @@ -475,8 +608,9 @@ export class FirestoreAdminClient { * Return the project ID used by this class. * @returns {Promise} A promise that resolves to string containing the project ID. */ - getProjectId(callback?: Callback): - Promise|void { + getProjectId( + callback?: Callback + ): Promise | void { if (callback) { this.auth.getProjectId(callback); return; @@ -487,3047 +621,4170 @@ export class FirestoreAdminClient { // ------------------- // -- Service calls -- // ------------------- -/** - * Gets a composite index. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.name - * Required. A name of the form - * `projects/{project_id}/databases/{database_id}/collectionGroups/{collection_id}/indexes/{index_id}` - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Promise} - The promise which resolves to an array. - * The first element of the array is an object representing {@link protos.google.firestore.admin.v1.Index|Index}. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } - * for more details and examples. - * @example

- * region_tag:firestore_v1_generated_FirestoreAdmin_GetIndex_async - */ + /** + * Gets a composite index. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.name + * Required. A name of the form + * `projects/{project_id}/databases/{database_id}/collectionGroups/{collection_id}/indexes/{index_id}` + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is an object representing {@link protos.google.firestore.admin.v1.Index|Index}. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } + * for more details and examples. + * @example + * region_tag:firestore_v1_generated_FirestoreAdmin_GetIndex_async + */ getIndex( - request?: protos.google.firestore.admin.v1.IGetIndexRequest, - options?: CallOptions): - Promise<[ - protos.google.firestore.admin.v1.IIndex, - protos.google.firestore.admin.v1.IGetIndexRequest|undefined, {}|undefined - ]>; + request?: protos.google.firestore.admin.v1.IGetIndexRequest, + options?: CallOptions + ): Promise< + [ + protos.google.firestore.admin.v1.IIndex, + protos.google.firestore.admin.v1.IGetIndexRequest | undefined, + {} | undefined, + ] + >; getIndex( - request: protos.google.firestore.admin.v1.IGetIndexRequest, - options: CallOptions, - callback: Callback< - protos.google.firestore.admin.v1.IIndex, - protos.google.firestore.admin.v1.IGetIndexRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.firestore.admin.v1.IGetIndexRequest, + options: CallOptions, + callback: Callback< + protos.google.firestore.admin.v1.IIndex, + protos.google.firestore.admin.v1.IGetIndexRequest | null | undefined, + {} | null | undefined + > + ): void; getIndex( - request: protos.google.firestore.admin.v1.IGetIndexRequest, - callback: Callback< - protos.google.firestore.admin.v1.IIndex, - protos.google.firestore.admin.v1.IGetIndexRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.firestore.admin.v1.IGetIndexRequest, + callback: Callback< + protos.google.firestore.admin.v1.IIndex, + protos.google.firestore.admin.v1.IGetIndexRequest | null | undefined, + {} | null | undefined + > + ): void; getIndex( - request?: protos.google.firestore.admin.v1.IGetIndexRequest, - optionsOrCallback?: CallOptions|Callback< - protos.google.firestore.admin.v1.IIndex, - protos.google.firestore.admin.v1.IGetIndexRequest|null|undefined, - {}|null|undefined>, - callback?: Callback< + request?: protos.google.firestore.admin.v1.IGetIndexRequest, + optionsOrCallback?: + | CallOptions + | Callback< protos.google.firestore.admin.v1.IIndex, - protos.google.firestore.admin.v1.IGetIndexRequest|null|undefined, - {}|null|undefined>): - Promise<[ - protos.google.firestore.admin.v1.IIndex, - protos.google.firestore.admin.v1.IGetIndexRequest|undefined, {}|undefined - ]>|void { + protos.google.firestore.admin.v1.IGetIndexRequest | null | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.firestore.admin.v1.IIndex, + protos.google.firestore.admin.v1.IGetIndexRequest | null | undefined, + {} | null | undefined + > + ): Promise< + [ + protos.google.firestore.admin.v1.IIndex, + protos.google.firestore.admin.v1.IGetIndexRequest | undefined, + {} | undefined, + ] + > | void { request = request || {}; let options: CallOptions; if (typeof optionsOrCallback === 'function' && callback === undefined) { callback = optionsOrCallback; options = {}; - } - else { + } else { options = optionsOrCallback as CallOptions; } options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - options.otherArgs.headers[ - 'x-goog-request-params' - ] = this._gaxModule.routingHeader.fromParams({ - 'name': request.name ?? '', + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + name: request.name ?? '', + }); + this.initialize().catch(err => { + throw err; }); - this.initialize().catch(err => {throw err}); this._log.info('getIndex request %j', request); - const wrappedCallback: Callback< - protos.google.firestore.admin.v1.IIndex, - protos.google.firestore.admin.v1.IGetIndexRequest|null|undefined, - {}|null|undefined>|undefined = callback + const wrappedCallback: + | Callback< + protos.google.firestore.admin.v1.IIndex, + protos.google.firestore.admin.v1.IGetIndexRequest | null | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, options, rawResponse) => { this._log.info('getIndex response %j', response); callback!(error, response, options, rawResponse); // We verified callback above. } : undefined; - return this.innerApiCalls.getIndex(request, options, wrappedCallback) - ?.then(([response, options, rawResponse]: [ - protos.google.firestore.admin.v1.IIndex, - protos.google.firestore.admin.v1.IGetIndexRequest|undefined, - {}|undefined - ]) => { - this._log.info('getIndex response %j', response); - return [response, options, rawResponse]; - }); + return this.innerApiCalls + .getIndex(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.firestore.admin.v1.IIndex, + protos.google.firestore.admin.v1.IGetIndexRequest | undefined, + {} | undefined, + ]) => { + this._log.info('getIndex response %j', response); + return [response, options, rawResponse]; + } + ); } -/** - * Deletes a composite index. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.name - * Required. A name of the form - * `projects/{project_id}/databases/{database_id}/collectionGroups/{collection_id}/indexes/{index_id}` - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Promise} - The promise which resolves to an array. - * The first element of the array is an object representing {@link protos.google.protobuf.Empty|Empty}. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } - * for more details and examples. - * @example - * region_tag:firestore_v1_generated_FirestoreAdmin_DeleteIndex_async - */ + /** + * Deletes a composite index. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.name + * Required. A name of the form + * `projects/{project_id}/databases/{database_id}/collectionGroups/{collection_id}/indexes/{index_id}` + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is an object representing {@link protos.google.protobuf.Empty|Empty}. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } + * for more details and examples. + * @example + * region_tag:firestore_v1_generated_FirestoreAdmin_DeleteIndex_async + */ deleteIndex( - request?: protos.google.firestore.admin.v1.IDeleteIndexRequest, - options?: CallOptions): - Promise<[ - protos.google.protobuf.IEmpty, - protos.google.firestore.admin.v1.IDeleteIndexRequest|undefined, {}|undefined - ]>; + request?: protos.google.firestore.admin.v1.IDeleteIndexRequest, + options?: CallOptions + ): Promise< + [ + protos.google.protobuf.IEmpty, + protos.google.firestore.admin.v1.IDeleteIndexRequest | undefined, + {} | undefined, + ] + >; deleteIndex( - request: protos.google.firestore.admin.v1.IDeleteIndexRequest, - options: CallOptions, - callback: Callback< - protos.google.protobuf.IEmpty, - protos.google.firestore.admin.v1.IDeleteIndexRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.firestore.admin.v1.IDeleteIndexRequest, + options: CallOptions, + callback: Callback< + protos.google.protobuf.IEmpty, + protos.google.firestore.admin.v1.IDeleteIndexRequest | null | undefined, + {} | null | undefined + > + ): void; deleteIndex( - request: protos.google.firestore.admin.v1.IDeleteIndexRequest, - callback: Callback< - protos.google.protobuf.IEmpty, - protos.google.firestore.admin.v1.IDeleteIndexRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.firestore.admin.v1.IDeleteIndexRequest, + callback: Callback< + protos.google.protobuf.IEmpty, + protos.google.firestore.admin.v1.IDeleteIndexRequest | null | undefined, + {} | null | undefined + > + ): void; deleteIndex( - request?: protos.google.firestore.admin.v1.IDeleteIndexRequest, - optionsOrCallback?: CallOptions|Callback< - protos.google.protobuf.IEmpty, - protos.google.firestore.admin.v1.IDeleteIndexRequest|null|undefined, - {}|null|undefined>, - callback?: Callback< + request?: protos.google.firestore.admin.v1.IDeleteIndexRequest, + optionsOrCallback?: + | CallOptions + | Callback< protos.google.protobuf.IEmpty, - protos.google.firestore.admin.v1.IDeleteIndexRequest|null|undefined, - {}|null|undefined>): - Promise<[ - protos.google.protobuf.IEmpty, - protos.google.firestore.admin.v1.IDeleteIndexRequest|undefined, {}|undefined - ]>|void { + | protos.google.firestore.admin.v1.IDeleteIndexRequest + | null + | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.protobuf.IEmpty, + protos.google.firestore.admin.v1.IDeleteIndexRequest | null | undefined, + {} | null | undefined + > + ): Promise< + [ + protos.google.protobuf.IEmpty, + protos.google.firestore.admin.v1.IDeleteIndexRequest | undefined, + {} | undefined, + ] + > | void { request = request || {}; let options: CallOptions; if (typeof optionsOrCallback === 'function' && callback === undefined) { callback = optionsOrCallback; options = {}; - } - else { + } else { options = optionsOrCallback as CallOptions; } options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - options.otherArgs.headers[ - 'x-goog-request-params' - ] = this._gaxModule.routingHeader.fromParams({ - 'name': request.name ?? '', + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + name: request.name ?? '', + }); + this.initialize().catch(err => { + throw err; }); - this.initialize().catch(err => {throw err}); this._log.info('deleteIndex request %j', request); - const wrappedCallback: Callback< - protos.google.protobuf.IEmpty, - protos.google.firestore.admin.v1.IDeleteIndexRequest|null|undefined, - {}|null|undefined>|undefined = callback + const wrappedCallback: + | Callback< + protos.google.protobuf.IEmpty, + | protos.google.firestore.admin.v1.IDeleteIndexRequest + | null + | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, options, rawResponse) => { this._log.info('deleteIndex response %j', response); callback!(error, response, options, rawResponse); // We verified callback above. } : undefined; - return this.innerApiCalls.deleteIndex(request, options, wrappedCallback) - ?.then(([response, options, rawResponse]: [ - protos.google.protobuf.IEmpty, - protos.google.firestore.admin.v1.IDeleteIndexRequest|undefined, - {}|undefined - ]) => { - this._log.info('deleteIndex response %j', response); - return [response, options, rawResponse]; - }); + return this.innerApiCalls + .deleteIndex(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.protobuf.IEmpty, + protos.google.firestore.admin.v1.IDeleteIndexRequest | undefined, + {} | undefined, + ]) => { + this._log.info('deleteIndex response %j', response); + return [response, options, rawResponse]; + } + ); } -/** - * Gets the metadata and configuration for a Field. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.name - * Required. A name of the form - * `projects/{project_id}/databases/{database_id}/collectionGroups/{collection_id}/fields/{field_id}` - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Promise} - The promise which resolves to an array. - * The first element of the array is an object representing {@link protos.google.firestore.admin.v1.Field|Field}. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } - * for more details and examples. - * @example - * region_tag:firestore_v1_generated_FirestoreAdmin_GetField_async - */ + /** + * Gets the metadata and configuration for a Field. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.name + * Required. A name of the form + * `projects/{project_id}/databases/{database_id}/collectionGroups/{collection_id}/fields/{field_id}` + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is an object representing {@link protos.google.firestore.admin.v1.Field|Field}. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } + * for more details and examples. + * @example + * region_tag:firestore_v1_generated_FirestoreAdmin_GetField_async + */ getField( - request?: protos.google.firestore.admin.v1.IGetFieldRequest, - options?: CallOptions): - Promise<[ - protos.google.firestore.admin.v1.IField, - protos.google.firestore.admin.v1.IGetFieldRequest|undefined, {}|undefined - ]>; + request?: protos.google.firestore.admin.v1.IGetFieldRequest, + options?: CallOptions + ): Promise< + [ + protos.google.firestore.admin.v1.IField, + protos.google.firestore.admin.v1.IGetFieldRequest | undefined, + {} | undefined, + ] + >; getField( - request: protos.google.firestore.admin.v1.IGetFieldRequest, - options: CallOptions, - callback: Callback< - protos.google.firestore.admin.v1.IField, - protos.google.firestore.admin.v1.IGetFieldRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.firestore.admin.v1.IGetFieldRequest, + options: CallOptions, + callback: Callback< + protos.google.firestore.admin.v1.IField, + protos.google.firestore.admin.v1.IGetFieldRequest | null | undefined, + {} | null | undefined + > + ): void; getField( - request: protos.google.firestore.admin.v1.IGetFieldRequest, - callback: Callback< - protos.google.firestore.admin.v1.IField, - protos.google.firestore.admin.v1.IGetFieldRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.firestore.admin.v1.IGetFieldRequest, + callback: Callback< + protos.google.firestore.admin.v1.IField, + protos.google.firestore.admin.v1.IGetFieldRequest | null | undefined, + {} | null | undefined + > + ): void; getField( - request?: protos.google.firestore.admin.v1.IGetFieldRequest, - optionsOrCallback?: CallOptions|Callback< - protos.google.firestore.admin.v1.IField, - protos.google.firestore.admin.v1.IGetFieldRequest|null|undefined, - {}|null|undefined>, - callback?: Callback< + request?: protos.google.firestore.admin.v1.IGetFieldRequest, + optionsOrCallback?: + | CallOptions + | Callback< protos.google.firestore.admin.v1.IField, - protos.google.firestore.admin.v1.IGetFieldRequest|null|undefined, - {}|null|undefined>): - Promise<[ - protos.google.firestore.admin.v1.IField, - protos.google.firestore.admin.v1.IGetFieldRequest|undefined, {}|undefined - ]>|void { + protos.google.firestore.admin.v1.IGetFieldRequest | null | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.firestore.admin.v1.IField, + protos.google.firestore.admin.v1.IGetFieldRequest | null | undefined, + {} | null | undefined + > + ): Promise< + [ + protos.google.firestore.admin.v1.IField, + protos.google.firestore.admin.v1.IGetFieldRequest | undefined, + {} | undefined, + ] + > | void { request = request || {}; let options: CallOptions; if (typeof optionsOrCallback === 'function' && callback === undefined) { callback = optionsOrCallback; options = {}; - } - else { + } else { options = optionsOrCallback as CallOptions; } options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - options.otherArgs.headers[ - 'x-goog-request-params' - ] = this._gaxModule.routingHeader.fromParams({ - 'name': request.name ?? '', + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + name: request.name ?? '', + }); + this.initialize().catch(err => { + throw err; }); - this.initialize().catch(err => {throw err}); this._log.info('getField request %j', request); - const wrappedCallback: Callback< - protos.google.firestore.admin.v1.IField, - protos.google.firestore.admin.v1.IGetFieldRequest|null|undefined, - {}|null|undefined>|undefined = callback + const wrappedCallback: + | Callback< + protos.google.firestore.admin.v1.IField, + protos.google.firestore.admin.v1.IGetFieldRequest | null | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, options, rawResponse) => { this._log.info('getField response %j', response); callback!(error, response, options, rawResponse); // We verified callback above. } : undefined; - return this.innerApiCalls.getField(request, options, wrappedCallback) - ?.then(([response, options, rawResponse]: [ - protos.google.firestore.admin.v1.IField, - protos.google.firestore.admin.v1.IGetFieldRequest|undefined, - {}|undefined - ]) => { - this._log.info('getField response %j', response); - return [response, options, rawResponse]; - }); + return this.innerApiCalls + .getField(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.firestore.admin.v1.IField, + protos.google.firestore.admin.v1.IGetFieldRequest | undefined, + {} | undefined, + ]) => { + this._log.info('getField response %j', response); + return [response, options, rawResponse]; + } + ); } -/** - * Gets information about a database. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.name - * Required. A name of the form - * `projects/{project_id}/databases/{database_id}` - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Promise} - The promise which resolves to an array. - * The first element of the array is an object representing {@link protos.google.firestore.admin.v1.Database|Database}. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } - * for more details and examples. - * @example - * region_tag:firestore_v1_generated_FirestoreAdmin_GetDatabase_async - */ + /** + * Gets information about a database. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.name + * Required. A name of the form + * `projects/{project_id}/databases/{database_id}` + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is an object representing {@link protos.google.firestore.admin.v1.Database|Database}. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } + * for more details and examples. + * @example + * region_tag:firestore_v1_generated_FirestoreAdmin_GetDatabase_async + */ getDatabase( - request?: protos.google.firestore.admin.v1.IGetDatabaseRequest, - options?: CallOptions): - Promise<[ - protos.google.firestore.admin.v1.IDatabase, - protos.google.firestore.admin.v1.IGetDatabaseRequest|undefined, {}|undefined - ]>; + request?: protos.google.firestore.admin.v1.IGetDatabaseRequest, + options?: CallOptions + ): Promise< + [ + protos.google.firestore.admin.v1.IDatabase, + protos.google.firestore.admin.v1.IGetDatabaseRequest | undefined, + {} | undefined, + ] + >; getDatabase( - request: protos.google.firestore.admin.v1.IGetDatabaseRequest, - options: CallOptions, - callback: Callback< - protos.google.firestore.admin.v1.IDatabase, - protos.google.firestore.admin.v1.IGetDatabaseRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.firestore.admin.v1.IGetDatabaseRequest, + options: CallOptions, + callback: Callback< + protos.google.firestore.admin.v1.IDatabase, + protos.google.firestore.admin.v1.IGetDatabaseRequest | null | undefined, + {} | null | undefined + > + ): void; getDatabase( - request: protos.google.firestore.admin.v1.IGetDatabaseRequest, - callback: Callback< - protos.google.firestore.admin.v1.IDatabase, - protos.google.firestore.admin.v1.IGetDatabaseRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.firestore.admin.v1.IGetDatabaseRequest, + callback: Callback< + protos.google.firestore.admin.v1.IDatabase, + protos.google.firestore.admin.v1.IGetDatabaseRequest | null | undefined, + {} | null | undefined + > + ): void; getDatabase( - request?: protos.google.firestore.admin.v1.IGetDatabaseRequest, - optionsOrCallback?: CallOptions|Callback< - protos.google.firestore.admin.v1.IDatabase, - protos.google.firestore.admin.v1.IGetDatabaseRequest|null|undefined, - {}|null|undefined>, - callback?: Callback< + request?: protos.google.firestore.admin.v1.IGetDatabaseRequest, + optionsOrCallback?: + | CallOptions + | Callback< protos.google.firestore.admin.v1.IDatabase, - protos.google.firestore.admin.v1.IGetDatabaseRequest|null|undefined, - {}|null|undefined>): - Promise<[ - protos.google.firestore.admin.v1.IDatabase, - protos.google.firestore.admin.v1.IGetDatabaseRequest|undefined, {}|undefined - ]>|void { + | protos.google.firestore.admin.v1.IGetDatabaseRequest + | null + | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.firestore.admin.v1.IDatabase, + protos.google.firestore.admin.v1.IGetDatabaseRequest | null | undefined, + {} | null | undefined + > + ): Promise< + [ + protos.google.firestore.admin.v1.IDatabase, + protos.google.firestore.admin.v1.IGetDatabaseRequest | undefined, + {} | undefined, + ] + > | void { request = request || {}; let options: CallOptions; if (typeof optionsOrCallback === 'function' && callback === undefined) { callback = optionsOrCallback; options = {}; - } - else { + } else { options = optionsOrCallback as CallOptions; } options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - options.otherArgs.headers[ - 'x-goog-request-params' - ] = this._gaxModule.routingHeader.fromParams({ - 'name': request.name ?? '', + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + name: request.name ?? '', + }); + this.initialize().catch(err => { + throw err; }); - this.initialize().catch(err => {throw err}); this._log.info('getDatabase request %j', request); - const wrappedCallback: Callback< - protos.google.firestore.admin.v1.IDatabase, - protos.google.firestore.admin.v1.IGetDatabaseRequest|null|undefined, - {}|null|undefined>|undefined = callback + const wrappedCallback: + | Callback< + protos.google.firestore.admin.v1.IDatabase, + | protos.google.firestore.admin.v1.IGetDatabaseRequest + | null + | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, options, rawResponse) => { this._log.info('getDatabase response %j', response); callback!(error, response, options, rawResponse); // We verified callback above. } : undefined; - return this.innerApiCalls.getDatabase(request, options, wrappedCallback) - ?.then(([response, options, rawResponse]: [ - protos.google.firestore.admin.v1.IDatabase, - protos.google.firestore.admin.v1.IGetDatabaseRequest|undefined, - {}|undefined - ]) => { - this._log.info('getDatabase response %j', response); - return [response, options, rawResponse]; - }); + return this.innerApiCalls + .getDatabase(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.firestore.admin.v1.IDatabase, + protos.google.firestore.admin.v1.IGetDatabaseRequest | undefined, + {} | undefined, + ]) => { + this._log.info('getDatabase response %j', response); + return [response, options, rawResponse]; + } + ); } -/** - * List all the databases in the project. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.parent - * Required. A parent name of the form - * `projects/{project_id}` - * @param {boolean} request.showDeleted - * If true, also returns deleted resources. - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Promise} - The promise which resolves to an array. - * The first element of the array is an object representing {@link protos.google.firestore.admin.v1.ListDatabasesResponse|ListDatabasesResponse}. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } - * for more details and examples. - * @example - * region_tag:firestore_v1_generated_FirestoreAdmin_ListDatabases_async - */ + /** + * List all the databases in the project. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.parent + * Required. A parent name of the form + * `projects/{project_id}` + * @param {boolean} request.showDeleted + * If true, also returns deleted resources. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is an object representing {@link protos.google.firestore.admin.v1.ListDatabasesResponse|ListDatabasesResponse}. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } + * for more details and examples. + * @example + * region_tag:firestore_v1_generated_FirestoreAdmin_ListDatabases_async + */ listDatabases( - request?: protos.google.firestore.admin.v1.IListDatabasesRequest, - options?: CallOptions): - Promise<[ - protos.google.firestore.admin.v1.IListDatabasesResponse, - protos.google.firestore.admin.v1.IListDatabasesRequest|undefined, {}|undefined - ]>; + request?: protos.google.firestore.admin.v1.IListDatabasesRequest, + options?: CallOptions + ): Promise< + [ + protos.google.firestore.admin.v1.IListDatabasesResponse, + protos.google.firestore.admin.v1.IListDatabasesRequest | undefined, + {} | undefined, + ] + >; listDatabases( - request: protos.google.firestore.admin.v1.IListDatabasesRequest, - options: CallOptions, - callback: Callback< - protos.google.firestore.admin.v1.IListDatabasesResponse, - protos.google.firestore.admin.v1.IListDatabasesRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.firestore.admin.v1.IListDatabasesRequest, + options: CallOptions, + callback: Callback< + protos.google.firestore.admin.v1.IListDatabasesResponse, + protos.google.firestore.admin.v1.IListDatabasesRequest | null | undefined, + {} | null | undefined + > + ): void; listDatabases( - request: protos.google.firestore.admin.v1.IListDatabasesRequest, - callback: Callback< - protos.google.firestore.admin.v1.IListDatabasesResponse, - protos.google.firestore.admin.v1.IListDatabasesRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.firestore.admin.v1.IListDatabasesRequest, + callback: Callback< + protos.google.firestore.admin.v1.IListDatabasesResponse, + protos.google.firestore.admin.v1.IListDatabasesRequest | null | undefined, + {} | null | undefined + > + ): void; listDatabases( - request?: protos.google.firestore.admin.v1.IListDatabasesRequest, - optionsOrCallback?: CallOptions|Callback< - protos.google.firestore.admin.v1.IListDatabasesResponse, - protos.google.firestore.admin.v1.IListDatabasesRequest|null|undefined, - {}|null|undefined>, - callback?: Callback< + request?: protos.google.firestore.admin.v1.IListDatabasesRequest, + optionsOrCallback?: + | CallOptions + | Callback< protos.google.firestore.admin.v1.IListDatabasesResponse, - protos.google.firestore.admin.v1.IListDatabasesRequest|null|undefined, - {}|null|undefined>): - Promise<[ - protos.google.firestore.admin.v1.IListDatabasesResponse, - protos.google.firestore.admin.v1.IListDatabasesRequest|undefined, {}|undefined - ]>|void { + | protos.google.firestore.admin.v1.IListDatabasesRequest + | null + | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.firestore.admin.v1.IListDatabasesResponse, + protos.google.firestore.admin.v1.IListDatabasesRequest | null | undefined, + {} | null | undefined + > + ): Promise< + [ + protos.google.firestore.admin.v1.IListDatabasesResponse, + protos.google.firestore.admin.v1.IListDatabasesRequest | undefined, + {} | undefined, + ] + > | void { request = request || {}; let options: CallOptions; if (typeof optionsOrCallback === 'function' && callback === undefined) { callback = optionsOrCallback; options = {}; - } - else { + } else { options = optionsOrCallback as CallOptions; } options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - options.otherArgs.headers[ - 'x-goog-request-params' - ] = this._gaxModule.routingHeader.fromParams({ - 'parent': request.parent ?? '', + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + parent: request.parent ?? '', + }); + this.initialize().catch(err => { + throw err; }); - this.initialize().catch(err => {throw err}); this._log.info('listDatabases request %j', request); - const wrappedCallback: Callback< - protos.google.firestore.admin.v1.IListDatabasesResponse, - protos.google.firestore.admin.v1.IListDatabasesRequest|null|undefined, - {}|null|undefined>|undefined = callback + const wrappedCallback: + | Callback< + protos.google.firestore.admin.v1.IListDatabasesResponse, + | protos.google.firestore.admin.v1.IListDatabasesRequest + | null + | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, options, rawResponse) => { this._log.info('listDatabases response %j', response); callback!(error, response, options, rawResponse); // We verified callback above. } : undefined; - return this.innerApiCalls.listDatabases(request, options, wrappedCallback) - ?.then(([response, options, rawResponse]: [ - protos.google.firestore.admin.v1.IListDatabasesResponse, - protos.google.firestore.admin.v1.IListDatabasesRequest|undefined, - {}|undefined - ]) => { - this._log.info('listDatabases response %j', response); - return [response, options, rawResponse]; - }); - } -/** - * Create a user creds. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.parent - * Required. A parent name of the form - * `projects/{project_id}/databases/{database_id}` - * @param {google.firestore.admin.v1.UserCreds} request.userCreds - * Required. The user creds to create. - * @param {string} request.userCredsId - * Required. The ID to use for the user creds, which will become the final - * component of the user creds's resource name. - * - * This value should be 4-63 characters. Valid characters are /{@link protos.0-9|a-z}-/ - * with first character a letter and the last a letter or a number. Must not - * be UUID-like /[0-9a-f]{8}(-[0-9a-f]{4}){3}-[0-9a-f]{12}/. - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Promise} - The promise which resolves to an array. - * The first element of the array is an object representing {@link protos.google.firestore.admin.v1.UserCreds|UserCreds}. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } - * for more details and examples. - * @example - * region_tag:firestore_v1_generated_FirestoreAdmin_CreateUserCreds_async - */ + return this.innerApiCalls + .listDatabases(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.firestore.admin.v1.IListDatabasesResponse, + protos.google.firestore.admin.v1.IListDatabasesRequest | undefined, + {} | undefined, + ]) => { + this._log.info('listDatabases response %j', response); + return [response, options, rawResponse]; + } + ); + } + /** + * Create a user creds. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.parent + * Required. A parent name of the form + * `projects/{project_id}/databases/{database_id}` + * @param {google.firestore.admin.v1.UserCreds} request.userCreds + * Required. The user creds to create. + * @param {string} request.userCredsId + * Required. The ID to use for the user creds, which will become the final + * component of the user creds's resource name. + * + * This value should be 4-63 characters. Valid characters are /{@link protos.0-9|a-z}-/ + * with first character a letter and the last a letter or a number. Must not + * be UUID-like /[0-9a-f]{8}(-[0-9a-f]{4}){3}-[0-9a-f]{12}/. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is an object representing {@link protos.google.firestore.admin.v1.UserCreds|UserCreds}. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } + * for more details and examples. + * @example + * region_tag:firestore_v1_generated_FirestoreAdmin_CreateUserCreds_async + */ createUserCreds( - request?: protos.google.firestore.admin.v1.ICreateUserCredsRequest, - options?: CallOptions): - Promise<[ - protos.google.firestore.admin.v1.IUserCreds, - protos.google.firestore.admin.v1.ICreateUserCredsRequest|undefined, {}|undefined - ]>; + request?: protos.google.firestore.admin.v1.ICreateUserCredsRequest, + options?: CallOptions + ): Promise< + [ + protos.google.firestore.admin.v1.IUserCreds, + protos.google.firestore.admin.v1.ICreateUserCredsRequest | undefined, + {} | undefined, + ] + >; createUserCreds( - request: protos.google.firestore.admin.v1.ICreateUserCredsRequest, - options: CallOptions, - callback: Callback< - protos.google.firestore.admin.v1.IUserCreds, - protos.google.firestore.admin.v1.ICreateUserCredsRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.firestore.admin.v1.ICreateUserCredsRequest, + options: CallOptions, + callback: Callback< + protos.google.firestore.admin.v1.IUserCreds, + | protos.google.firestore.admin.v1.ICreateUserCredsRequest + | null + | undefined, + {} | null | undefined + > + ): void; createUserCreds( - request: protos.google.firestore.admin.v1.ICreateUserCredsRequest, - callback: Callback< - protos.google.firestore.admin.v1.IUserCreds, - protos.google.firestore.admin.v1.ICreateUserCredsRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.firestore.admin.v1.ICreateUserCredsRequest, + callback: Callback< + protos.google.firestore.admin.v1.IUserCreds, + | protos.google.firestore.admin.v1.ICreateUserCredsRequest + | null + | undefined, + {} | null | undefined + > + ): void; createUserCreds( - request?: protos.google.firestore.admin.v1.ICreateUserCredsRequest, - optionsOrCallback?: CallOptions|Callback< - protos.google.firestore.admin.v1.IUserCreds, - protos.google.firestore.admin.v1.ICreateUserCredsRequest|null|undefined, - {}|null|undefined>, - callback?: Callback< + request?: protos.google.firestore.admin.v1.ICreateUserCredsRequest, + optionsOrCallback?: + | CallOptions + | Callback< protos.google.firestore.admin.v1.IUserCreds, - protos.google.firestore.admin.v1.ICreateUserCredsRequest|null|undefined, - {}|null|undefined>): - Promise<[ - protos.google.firestore.admin.v1.IUserCreds, - protos.google.firestore.admin.v1.ICreateUserCredsRequest|undefined, {}|undefined - ]>|void { + | protos.google.firestore.admin.v1.ICreateUserCredsRequest + | null + | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.firestore.admin.v1.IUserCreds, + | protos.google.firestore.admin.v1.ICreateUserCredsRequest + | null + | undefined, + {} | null | undefined + > + ): Promise< + [ + protos.google.firestore.admin.v1.IUserCreds, + protos.google.firestore.admin.v1.ICreateUserCredsRequest | undefined, + {} | undefined, + ] + > | void { request = request || {}; let options: CallOptions; if (typeof optionsOrCallback === 'function' && callback === undefined) { callback = optionsOrCallback; options = {}; - } - else { + } else { options = optionsOrCallback as CallOptions; } options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - options.otherArgs.headers[ - 'x-goog-request-params' - ] = this._gaxModule.routingHeader.fromParams({ - 'parent': request.parent ?? '', + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + parent: request.parent ?? '', + }); + this.initialize().catch(err => { + throw err; }); - this.initialize().catch(err => {throw err}); this._log.info('createUserCreds request %j', request); - const wrappedCallback: Callback< - protos.google.firestore.admin.v1.IUserCreds, - protos.google.firestore.admin.v1.ICreateUserCredsRequest|null|undefined, - {}|null|undefined>|undefined = callback + const wrappedCallback: + | Callback< + protos.google.firestore.admin.v1.IUserCreds, + | protos.google.firestore.admin.v1.ICreateUserCredsRequest + | null + | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, options, rawResponse) => { this._log.info('createUserCreds response %j', response); callback!(error, response, options, rawResponse); // We verified callback above. } : undefined; - return this.innerApiCalls.createUserCreds(request, options, wrappedCallback) - ?.then(([response, options, rawResponse]: [ - protos.google.firestore.admin.v1.IUserCreds, - protos.google.firestore.admin.v1.ICreateUserCredsRequest|undefined, - {}|undefined - ]) => { - this._log.info('createUserCreds response %j', response); - return [response, options, rawResponse]; - }); + return this.innerApiCalls + .createUserCreds(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.firestore.admin.v1.IUserCreds, + protos.google.firestore.admin.v1.ICreateUserCredsRequest | undefined, + {} | undefined, + ]) => { + this._log.info('createUserCreds response %j', response); + return [response, options, rawResponse]; + } + ); } -/** - * Gets a user creds resource. Note that the returned resource does not - * contain the secret value itself. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.name - * Required. A name of the form - * `projects/{project_id}/databases/{database_id}/userCreds/{user_creds_id}` - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Promise} - The promise which resolves to an array. - * The first element of the array is an object representing {@link protos.google.firestore.admin.v1.UserCreds|UserCreds}. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } - * for more details and examples. - * @example - * region_tag:firestore_v1_generated_FirestoreAdmin_GetUserCreds_async - */ + /** + * Gets a user creds resource. Note that the returned resource does not + * contain the secret value itself. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.name + * Required. A name of the form + * `projects/{project_id}/databases/{database_id}/userCreds/{user_creds_id}` + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is an object representing {@link protos.google.firestore.admin.v1.UserCreds|UserCreds}. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } + * for more details and examples. + * @example + * region_tag:firestore_v1_generated_FirestoreAdmin_GetUserCreds_async + */ getUserCreds( - request?: protos.google.firestore.admin.v1.IGetUserCredsRequest, - options?: CallOptions): - Promise<[ - protos.google.firestore.admin.v1.IUserCreds, - protos.google.firestore.admin.v1.IGetUserCredsRequest|undefined, {}|undefined - ]>; + request?: protos.google.firestore.admin.v1.IGetUserCredsRequest, + options?: CallOptions + ): Promise< + [ + protos.google.firestore.admin.v1.IUserCreds, + protos.google.firestore.admin.v1.IGetUserCredsRequest | undefined, + {} | undefined, + ] + >; getUserCreds( - request: protos.google.firestore.admin.v1.IGetUserCredsRequest, - options: CallOptions, - callback: Callback< - protos.google.firestore.admin.v1.IUserCreds, - protos.google.firestore.admin.v1.IGetUserCredsRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.firestore.admin.v1.IGetUserCredsRequest, + options: CallOptions, + callback: Callback< + protos.google.firestore.admin.v1.IUserCreds, + protos.google.firestore.admin.v1.IGetUserCredsRequest | null | undefined, + {} | null | undefined + > + ): void; getUserCreds( - request: protos.google.firestore.admin.v1.IGetUserCredsRequest, - callback: Callback< - protos.google.firestore.admin.v1.IUserCreds, - protos.google.firestore.admin.v1.IGetUserCredsRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.firestore.admin.v1.IGetUserCredsRequest, + callback: Callback< + protos.google.firestore.admin.v1.IUserCreds, + protos.google.firestore.admin.v1.IGetUserCredsRequest | null | undefined, + {} | null | undefined + > + ): void; getUserCreds( - request?: protos.google.firestore.admin.v1.IGetUserCredsRequest, - optionsOrCallback?: CallOptions|Callback< - protos.google.firestore.admin.v1.IUserCreds, - protos.google.firestore.admin.v1.IGetUserCredsRequest|null|undefined, - {}|null|undefined>, - callback?: Callback< + request?: protos.google.firestore.admin.v1.IGetUserCredsRequest, + optionsOrCallback?: + | CallOptions + | Callback< protos.google.firestore.admin.v1.IUserCreds, - protos.google.firestore.admin.v1.IGetUserCredsRequest|null|undefined, - {}|null|undefined>): - Promise<[ - protos.google.firestore.admin.v1.IUserCreds, - protos.google.firestore.admin.v1.IGetUserCredsRequest|undefined, {}|undefined - ]>|void { + | protos.google.firestore.admin.v1.IGetUserCredsRequest + | null + | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.firestore.admin.v1.IUserCreds, + protos.google.firestore.admin.v1.IGetUserCredsRequest | null | undefined, + {} | null | undefined + > + ): Promise< + [ + protos.google.firestore.admin.v1.IUserCreds, + protos.google.firestore.admin.v1.IGetUserCredsRequest | undefined, + {} | undefined, + ] + > | void { request = request || {}; let options: CallOptions; if (typeof optionsOrCallback === 'function' && callback === undefined) { callback = optionsOrCallback; options = {}; - } - else { + } else { options = optionsOrCallback as CallOptions; } options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - options.otherArgs.headers[ - 'x-goog-request-params' - ] = this._gaxModule.routingHeader.fromParams({ - 'name': request.name ?? '', + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + name: request.name ?? '', + }); + this.initialize().catch(err => { + throw err; }); - this.initialize().catch(err => {throw err}); this._log.info('getUserCreds request %j', request); - const wrappedCallback: Callback< - protos.google.firestore.admin.v1.IUserCreds, - protos.google.firestore.admin.v1.IGetUserCredsRequest|null|undefined, - {}|null|undefined>|undefined = callback + const wrappedCallback: + | Callback< + protos.google.firestore.admin.v1.IUserCreds, + | protos.google.firestore.admin.v1.IGetUserCredsRequest + | null + | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, options, rawResponse) => { this._log.info('getUserCreds response %j', response); callback!(error, response, options, rawResponse); // We verified callback above. } : undefined; - return this.innerApiCalls.getUserCreds(request, options, wrappedCallback) - ?.then(([response, options, rawResponse]: [ - protos.google.firestore.admin.v1.IUserCreds, - protos.google.firestore.admin.v1.IGetUserCredsRequest|undefined, - {}|undefined - ]) => { - this._log.info('getUserCreds response %j', response); - return [response, options, rawResponse]; - }); + return this.innerApiCalls + .getUserCreds(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.firestore.admin.v1.IUserCreds, + protos.google.firestore.admin.v1.IGetUserCredsRequest | undefined, + {} | undefined, + ]) => { + this._log.info('getUserCreds response %j', response); + return [response, options, rawResponse]; + } + ); } -/** - * List all user creds in the database. Note that the returned resource - * does not contain the secret value itself. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.parent - * Required. A parent database name of the form - * `projects/{project_id}/databases/{database_id}` - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Promise} - The promise which resolves to an array. - * The first element of the array is an object representing {@link protos.google.firestore.admin.v1.ListUserCredsResponse|ListUserCredsResponse}. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } - * for more details and examples. - * @example - * region_tag:firestore_v1_generated_FirestoreAdmin_ListUserCreds_async - */ + /** + * List all user creds in the database. Note that the returned resource + * does not contain the secret value itself. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.parent + * Required. A parent database name of the form + * `projects/{project_id}/databases/{database_id}` + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is an object representing {@link protos.google.firestore.admin.v1.ListUserCredsResponse|ListUserCredsResponse}. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } + * for more details and examples. + * @example + * region_tag:firestore_v1_generated_FirestoreAdmin_ListUserCreds_async + */ listUserCreds( - request?: protos.google.firestore.admin.v1.IListUserCredsRequest, - options?: CallOptions): - Promise<[ - protos.google.firestore.admin.v1.IListUserCredsResponse, - protos.google.firestore.admin.v1.IListUserCredsRequest|undefined, {}|undefined - ]>; + request?: protos.google.firestore.admin.v1.IListUserCredsRequest, + options?: CallOptions + ): Promise< + [ + protos.google.firestore.admin.v1.IListUserCredsResponse, + protos.google.firestore.admin.v1.IListUserCredsRequest | undefined, + {} | undefined, + ] + >; listUserCreds( - request: protos.google.firestore.admin.v1.IListUserCredsRequest, - options: CallOptions, - callback: Callback< - protos.google.firestore.admin.v1.IListUserCredsResponse, - protos.google.firestore.admin.v1.IListUserCredsRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.firestore.admin.v1.IListUserCredsRequest, + options: CallOptions, + callback: Callback< + protos.google.firestore.admin.v1.IListUserCredsResponse, + protos.google.firestore.admin.v1.IListUserCredsRequest | null | undefined, + {} | null | undefined + > + ): void; listUserCreds( - request: protos.google.firestore.admin.v1.IListUserCredsRequest, - callback: Callback< - protos.google.firestore.admin.v1.IListUserCredsResponse, - protos.google.firestore.admin.v1.IListUserCredsRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.firestore.admin.v1.IListUserCredsRequest, + callback: Callback< + protos.google.firestore.admin.v1.IListUserCredsResponse, + protos.google.firestore.admin.v1.IListUserCredsRequest | null | undefined, + {} | null | undefined + > + ): void; listUserCreds( - request?: protos.google.firestore.admin.v1.IListUserCredsRequest, - optionsOrCallback?: CallOptions|Callback< - protos.google.firestore.admin.v1.IListUserCredsResponse, - protos.google.firestore.admin.v1.IListUserCredsRequest|null|undefined, - {}|null|undefined>, - callback?: Callback< + request?: protos.google.firestore.admin.v1.IListUserCredsRequest, + optionsOrCallback?: + | CallOptions + | Callback< protos.google.firestore.admin.v1.IListUserCredsResponse, - protos.google.firestore.admin.v1.IListUserCredsRequest|null|undefined, - {}|null|undefined>): - Promise<[ - protos.google.firestore.admin.v1.IListUserCredsResponse, - protos.google.firestore.admin.v1.IListUserCredsRequest|undefined, {}|undefined - ]>|void { + | protos.google.firestore.admin.v1.IListUserCredsRequest + | null + | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.firestore.admin.v1.IListUserCredsResponse, + protos.google.firestore.admin.v1.IListUserCredsRequest | null | undefined, + {} | null | undefined + > + ): Promise< + [ + protos.google.firestore.admin.v1.IListUserCredsResponse, + protos.google.firestore.admin.v1.IListUserCredsRequest | undefined, + {} | undefined, + ] + > | void { request = request || {}; let options: CallOptions; if (typeof optionsOrCallback === 'function' && callback === undefined) { callback = optionsOrCallback; options = {}; - } - else { + } else { options = optionsOrCallback as CallOptions; } options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - options.otherArgs.headers[ - 'x-goog-request-params' - ] = this._gaxModule.routingHeader.fromParams({ - 'parent': request.parent ?? '', + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + parent: request.parent ?? '', + }); + this.initialize().catch(err => { + throw err; }); - this.initialize().catch(err => {throw err}); this._log.info('listUserCreds request %j', request); - const wrappedCallback: Callback< - protos.google.firestore.admin.v1.IListUserCredsResponse, - protos.google.firestore.admin.v1.IListUserCredsRequest|null|undefined, - {}|null|undefined>|undefined = callback + const wrappedCallback: + | Callback< + protos.google.firestore.admin.v1.IListUserCredsResponse, + | protos.google.firestore.admin.v1.IListUserCredsRequest + | null + | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, options, rawResponse) => { this._log.info('listUserCreds response %j', response); callback!(error, response, options, rawResponse); // We verified callback above. } : undefined; - return this.innerApiCalls.listUserCreds(request, options, wrappedCallback) - ?.then(([response, options, rawResponse]: [ - protos.google.firestore.admin.v1.IListUserCredsResponse, - protos.google.firestore.admin.v1.IListUserCredsRequest|undefined, - {}|undefined - ]) => { - this._log.info('listUserCreds response %j', response); - return [response, options, rawResponse]; - }); + return this.innerApiCalls + .listUserCreds(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.firestore.admin.v1.IListUserCredsResponse, + protos.google.firestore.admin.v1.IListUserCredsRequest | undefined, + {} | undefined, + ]) => { + this._log.info('listUserCreds response %j', response); + return [response, options, rawResponse]; + } + ); } -/** - * Enables a user creds. No-op if the user creds are already enabled. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.name - * Required. A name of the form - * `projects/{project_id}/databases/{database_id}/userCreds/{user_creds_id}` - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Promise} - The promise which resolves to an array. - * The first element of the array is an object representing {@link protos.google.firestore.admin.v1.UserCreds|UserCreds}. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } - * for more details and examples. - * @example - * region_tag:firestore_v1_generated_FirestoreAdmin_EnableUserCreds_async - */ + /** + * Enables a user creds. No-op if the user creds are already enabled. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.name + * Required. A name of the form + * `projects/{project_id}/databases/{database_id}/userCreds/{user_creds_id}` + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is an object representing {@link protos.google.firestore.admin.v1.UserCreds|UserCreds}. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } + * for more details and examples. + * @example + * region_tag:firestore_v1_generated_FirestoreAdmin_EnableUserCreds_async + */ enableUserCreds( - request?: protos.google.firestore.admin.v1.IEnableUserCredsRequest, - options?: CallOptions): - Promise<[ - protos.google.firestore.admin.v1.IUserCreds, - protos.google.firestore.admin.v1.IEnableUserCredsRequest|undefined, {}|undefined - ]>; + request?: protos.google.firestore.admin.v1.IEnableUserCredsRequest, + options?: CallOptions + ): Promise< + [ + protos.google.firestore.admin.v1.IUserCreds, + protos.google.firestore.admin.v1.IEnableUserCredsRequest | undefined, + {} | undefined, + ] + >; enableUserCreds( - request: protos.google.firestore.admin.v1.IEnableUserCredsRequest, - options: CallOptions, - callback: Callback< - protos.google.firestore.admin.v1.IUserCreds, - protos.google.firestore.admin.v1.IEnableUserCredsRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.firestore.admin.v1.IEnableUserCredsRequest, + options: CallOptions, + callback: Callback< + protos.google.firestore.admin.v1.IUserCreds, + | protos.google.firestore.admin.v1.IEnableUserCredsRequest + | null + | undefined, + {} | null | undefined + > + ): void; enableUserCreds( - request: protos.google.firestore.admin.v1.IEnableUserCredsRequest, - callback: Callback< - protos.google.firestore.admin.v1.IUserCreds, - protos.google.firestore.admin.v1.IEnableUserCredsRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.firestore.admin.v1.IEnableUserCredsRequest, + callback: Callback< + protos.google.firestore.admin.v1.IUserCreds, + | protos.google.firestore.admin.v1.IEnableUserCredsRequest + | null + | undefined, + {} | null | undefined + > + ): void; enableUserCreds( - request?: protos.google.firestore.admin.v1.IEnableUserCredsRequest, - optionsOrCallback?: CallOptions|Callback< - protos.google.firestore.admin.v1.IUserCreds, - protos.google.firestore.admin.v1.IEnableUserCredsRequest|null|undefined, - {}|null|undefined>, - callback?: Callback< + request?: protos.google.firestore.admin.v1.IEnableUserCredsRequest, + optionsOrCallback?: + | CallOptions + | Callback< protos.google.firestore.admin.v1.IUserCreds, - protos.google.firestore.admin.v1.IEnableUserCredsRequest|null|undefined, - {}|null|undefined>): - Promise<[ - protos.google.firestore.admin.v1.IUserCreds, - protos.google.firestore.admin.v1.IEnableUserCredsRequest|undefined, {}|undefined - ]>|void { + | protos.google.firestore.admin.v1.IEnableUserCredsRequest + | null + | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.firestore.admin.v1.IUserCreds, + | protos.google.firestore.admin.v1.IEnableUserCredsRequest + | null + | undefined, + {} | null | undefined + > + ): Promise< + [ + protos.google.firestore.admin.v1.IUserCreds, + protos.google.firestore.admin.v1.IEnableUserCredsRequest | undefined, + {} | undefined, + ] + > | void { request = request || {}; let options: CallOptions; if (typeof optionsOrCallback === 'function' && callback === undefined) { callback = optionsOrCallback; options = {}; - } - else { + } else { options = optionsOrCallback as CallOptions; } options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - options.otherArgs.headers[ - 'x-goog-request-params' - ] = this._gaxModule.routingHeader.fromParams({ - 'name': request.name ?? '', + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + name: request.name ?? '', + }); + this.initialize().catch(err => { + throw err; }); - this.initialize().catch(err => {throw err}); this._log.info('enableUserCreds request %j', request); - const wrappedCallback: Callback< - protos.google.firestore.admin.v1.IUserCreds, - protos.google.firestore.admin.v1.IEnableUserCredsRequest|null|undefined, - {}|null|undefined>|undefined = callback + const wrappedCallback: + | Callback< + protos.google.firestore.admin.v1.IUserCreds, + | protos.google.firestore.admin.v1.IEnableUserCredsRequest + | null + | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, options, rawResponse) => { this._log.info('enableUserCreds response %j', response); callback!(error, response, options, rawResponse); // We verified callback above. } : undefined; - return this.innerApiCalls.enableUserCreds(request, options, wrappedCallback) - ?.then(([response, options, rawResponse]: [ - protos.google.firestore.admin.v1.IUserCreds, - protos.google.firestore.admin.v1.IEnableUserCredsRequest|undefined, - {}|undefined - ]) => { - this._log.info('enableUserCreds response %j', response); - return [response, options, rawResponse]; - }); + return this.innerApiCalls + .enableUserCreds(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.firestore.admin.v1.IUserCreds, + protos.google.firestore.admin.v1.IEnableUserCredsRequest | undefined, + {} | undefined, + ]) => { + this._log.info('enableUserCreds response %j', response); + return [response, options, rawResponse]; + } + ); } -/** - * Disables a user creds. No-op if the user creds are already disabled. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.name - * Required. A name of the form - * `projects/{project_id}/databases/{database_id}/userCreds/{user_creds_id}` - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Promise} - The promise which resolves to an array. - * The first element of the array is an object representing {@link protos.google.firestore.admin.v1.UserCreds|UserCreds}. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } - * for more details and examples. - * @example - * region_tag:firestore_v1_generated_FirestoreAdmin_DisableUserCreds_async - */ + /** + * Disables a user creds. No-op if the user creds are already disabled. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.name + * Required. A name of the form + * `projects/{project_id}/databases/{database_id}/userCreds/{user_creds_id}` + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is an object representing {@link protos.google.firestore.admin.v1.UserCreds|UserCreds}. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } + * for more details and examples. + * @example + * region_tag:firestore_v1_generated_FirestoreAdmin_DisableUserCreds_async + */ disableUserCreds( - request?: protos.google.firestore.admin.v1.IDisableUserCredsRequest, - options?: CallOptions): - Promise<[ - protos.google.firestore.admin.v1.IUserCreds, - protos.google.firestore.admin.v1.IDisableUserCredsRequest|undefined, {}|undefined - ]>; + request?: protos.google.firestore.admin.v1.IDisableUserCredsRequest, + options?: CallOptions + ): Promise< + [ + protos.google.firestore.admin.v1.IUserCreds, + protos.google.firestore.admin.v1.IDisableUserCredsRequest | undefined, + {} | undefined, + ] + >; disableUserCreds( - request: protos.google.firestore.admin.v1.IDisableUserCredsRequest, - options: CallOptions, - callback: Callback< - protos.google.firestore.admin.v1.IUserCreds, - protos.google.firestore.admin.v1.IDisableUserCredsRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.firestore.admin.v1.IDisableUserCredsRequest, + options: CallOptions, + callback: Callback< + protos.google.firestore.admin.v1.IUserCreds, + | protos.google.firestore.admin.v1.IDisableUserCredsRequest + | null + | undefined, + {} | null | undefined + > + ): void; disableUserCreds( - request: protos.google.firestore.admin.v1.IDisableUserCredsRequest, - callback: Callback< - protos.google.firestore.admin.v1.IUserCreds, - protos.google.firestore.admin.v1.IDisableUserCredsRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.firestore.admin.v1.IDisableUserCredsRequest, + callback: Callback< + protos.google.firestore.admin.v1.IUserCreds, + | protos.google.firestore.admin.v1.IDisableUserCredsRequest + | null + | undefined, + {} | null | undefined + > + ): void; disableUserCreds( - request?: protos.google.firestore.admin.v1.IDisableUserCredsRequest, - optionsOrCallback?: CallOptions|Callback< - protos.google.firestore.admin.v1.IUserCreds, - protos.google.firestore.admin.v1.IDisableUserCredsRequest|null|undefined, - {}|null|undefined>, - callback?: Callback< + request?: protos.google.firestore.admin.v1.IDisableUserCredsRequest, + optionsOrCallback?: + | CallOptions + | Callback< protos.google.firestore.admin.v1.IUserCreds, - protos.google.firestore.admin.v1.IDisableUserCredsRequest|null|undefined, - {}|null|undefined>): - Promise<[ - protos.google.firestore.admin.v1.IUserCreds, - protos.google.firestore.admin.v1.IDisableUserCredsRequest|undefined, {}|undefined - ]>|void { + | protos.google.firestore.admin.v1.IDisableUserCredsRequest + | null + | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.firestore.admin.v1.IUserCreds, + | protos.google.firestore.admin.v1.IDisableUserCredsRequest + | null + | undefined, + {} | null | undefined + > + ): Promise< + [ + protos.google.firestore.admin.v1.IUserCreds, + protos.google.firestore.admin.v1.IDisableUserCredsRequest | undefined, + {} | undefined, + ] + > | void { request = request || {}; let options: CallOptions; if (typeof optionsOrCallback === 'function' && callback === undefined) { callback = optionsOrCallback; options = {}; - } - else { + } else { options = optionsOrCallback as CallOptions; } options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - options.otherArgs.headers[ - 'x-goog-request-params' - ] = this._gaxModule.routingHeader.fromParams({ - 'name': request.name ?? '', + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + name: request.name ?? '', + }); + this.initialize().catch(err => { + throw err; }); - this.initialize().catch(err => {throw err}); this._log.info('disableUserCreds request %j', request); - const wrappedCallback: Callback< - protos.google.firestore.admin.v1.IUserCreds, - protos.google.firestore.admin.v1.IDisableUserCredsRequest|null|undefined, - {}|null|undefined>|undefined = callback + const wrappedCallback: + | Callback< + protos.google.firestore.admin.v1.IUserCreds, + | protos.google.firestore.admin.v1.IDisableUserCredsRequest + | null + | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, options, rawResponse) => { this._log.info('disableUserCreds response %j', response); callback!(error, response, options, rawResponse); // We verified callback above. } : undefined; - return this.innerApiCalls.disableUserCreds(request, options, wrappedCallback) - ?.then(([response, options, rawResponse]: [ - protos.google.firestore.admin.v1.IUserCreds, - protos.google.firestore.admin.v1.IDisableUserCredsRequest|undefined, - {}|undefined - ]) => { - this._log.info('disableUserCreds response %j', response); - return [response, options, rawResponse]; - }); + return this.innerApiCalls + .disableUserCreds(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.firestore.admin.v1.IUserCreds, + protos.google.firestore.admin.v1.IDisableUserCredsRequest | undefined, + {} | undefined, + ]) => { + this._log.info('disableUserCreds response %j', response); + return [response, options, rawResponse]; + } + ); } -/** - * Resets the password of a user creds. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.name - * Required. A name of the form - * `projects/{project_id}/databases/{database_id}/userCreds/{user_creds_id}` - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Promise} - The promise which resolves to an array. - * The first element of the array is an object representing {@link protos.google.firestore.admin.v1.UserCreds|UserCreds}. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } - * for more details and examples. - * @example - * region_tag:firestore_v1_generated_FirestoreAdmin_ResetUserPassword_async - */ + /** + * Resets the password of a user creds. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.name + * Required. A name of the form + * `projects/{project_id}/databases/{database_id}/userCreds/{user_creds_id}` + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is an object representing {@link protos.google.firestore.admin.v1.UserCreds|UserCreds}. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } + * for more details and examples. + * @example + * region_tag:firestore_v1_generated_FirestoreAdmin_ResetUserPassword_async + */ resetUserPassword( - request?: protos.google.firestore.admin.v1.IResetUserPasswordRequest, - options?: CallOptions): - Promise<[ - protos.google.firestore.admin.v1.IUserCreds, - protos.google.firestore.admin.v1.IResetUserPasswordRequest|undefined, {}|undefined - ]>; + request?: protos.google.firestore.admin.v1.IResetUserPasswordRequest, + options?: CallOptions + ): Promise< + [ + protos.google.firestore.admin.v1.IUserCreds, + protos.google.firestore.admin.v1.IResetUserPasswordRequest | undefined, + {} | undefined, + ] + >; resetUserPassword( - request: protos.google.firestore.admin.v1.IResetUserPasswordRequest, - options: CallOptions, - callback: Callback< - protos.google.firestore.admin.v1.IUserCreds, - protos.google.firestore.admin.v1.IResetUserPasswordRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.firestore.admin.v1.IResetUserPasswordRequest, + options: CallOptions, + callback: Callback< + protos.google.firestore.admin.v1.IUserCreds, + | protos.google.firestore.admin.v1.IResetUserPasswordRequest + | null + | undefined, + {} | null | undefined + > + ): void; resetUserPassword( - request: protos.google.firestore.admin.v1.IResetUserPasswordRequest, - callback: Callback< - protos.google.firestore.admin.v1.IUserCreds, - protos.google.firestore.admin.v1.IResetUserPasswordRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.firestore.admin.v1.IResetUserPasswordRequest, + callback: Callback< + protos.google.firestore.admin.v1.IUserCreds, + | protos.google.firestore.admin.v1.IResetUserPasswordRequest + | null + | undefined, + {} | null | undefined + > + ): void; resetUserPassword( - request?: protos.google.firestore.admin.v1.IResetUserPasswordRequest, - optionsOrCallback?: CallOptions|Callback< - protos.google.firestore.admin.v1.IUserCreds, - protos.google.firestore.admin.v1.IResetUserPasswordRequest|null|undefined, - {}|null|undefined>, - callback?: Callback< + request?: protos.google.firestore.admin.v1.IResetUserPasswordRequest, + optionsOrCallback?: + | CallOptions + | Callback< protos.google.firestore.admin.v1.IUserCreds, - protos.google.firestore.admin.v1.IResetUserPasswordRequest|null|undefined, - {}|null|undefined>): - Promise<[ - protos.google.firestore.admin.v1.IUserCreds, - protos.google.firestore.admin.v1.IResetUserPasswordRequest|undefined, {}|undefined - ]>|void { + | protos.google.firestore.admin.v1.IResetUserPasswordRequest + | null + | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.firestore.admin.v1.IUserCreds, + | protos.google.firestore.admin.v1.IResetUserPasswordRequest + | null + | undefined, + {} | null | undefined + > + ): Promise< + [ + protos.google.firestore.admin.v1.IUserCreds, + protos.google.firestore.admin.v1.IResetUserPasswordRequest | undefined, + {} | undefined, + ] + > | void { request = request || {}; let options: CallOptions; if (typeof optionsOrCallback === 'function' && callback === undefined) { callback = optionsOrCallback; options = {}; - } - else { + } else { options = optionsOrCallback as CallOptions; } options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - options.otherArgs.headers[ - 'x-goog-request-params' - ] = this._gaxModule.routingHeader.fromParams({ - 'name': request.name ?? '', + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + name: request.name ?? '', + }); + this.initialize().catch(err => { + throw err; }); - this.initialize().catch(err => {throw err}); this._log.info('resetUserPassword request %j', request); - const wrappedCallback: Callback< - protos.google.firestore.admin.v1.IUserCreds, - protos.google.firestore.admin.v1.IResetUserPasswordRequest|null|undefined, - {}|null|undefined>|undefined = callback + const wrappedCallback: + | Callback< + protos.google.firestore.admin.v1.IUserCreds, + | protos.google.firestore.admin.v1.IResetUserPasswordRequest + | null + | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, options, rawResponse) => { this._log.info('resetUserPassword response %j', response); callback!(error, response, options, rawResponse); // We verified callback above. } : undefined; - return this.innerApiCalls.resetUserPassword(request, options, wrappedCallback) - ?.then(([response, options, rawResponse]: [ - protos.google.firestore.admin.v1.IUserCreds, - protos.google.firestore.admin.v1.IResetUserPasswordRequest|undefined, - {}|undefined - ]) => { - this._log.info('resetUserPassword response %j', response); - return [response, options, rawResponse]; - }); + return this.innerApiCalls + .resetUserPassword(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.firestore.admin.v1.IUserCreds, + ( + | protos.google.firestore.admin.v1.IResetUserPasswordRequest + | undefined + ), + {} | undefined, + ]) => { + this._log.info('resetUserPassword response %j', response); + return [response, options, rawResponse]; + } + ); } -/** - * Deletes a user creds. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.name - * Required. A name of the form - * `projects/{project_id}/databases/{database_id}/userCreds/{user_creds_id}` - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Promise} - The promise which resolves to an array. - * The first element of the array is an object representing {@link protos.google.protobuf.Empty|Empty}. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } - * for more details and examples. - * @example - * region_tag:firestore_v1_generated_FirestoreAdmin_DeleteUserCreds_async - */ + /** + * Deletes a user creds. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.name + * Required. A name of the form + * `projects/{project_id}/databases/{database_id}/userCreds/{user_creds_id}` + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is an object representing {@link protos.google.protobuf.Empty|Empty}. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } + * for more details and examples. + * @example + * region_tag:firestore_v1_generated_FirestoreAdmin_DeleteUserCreds_async + */ deleteUserCreds( - request?: protos.google.firestore.admin.v1.IDeleteUserCredsRequest, - options?: CallOptions): - Promise<[ - protos.google.protobuf.IEmpty, - protos.google.firestore.admin.v1.IDeleteUserCredsRequest|undefined, {}|undefined - ]>; + request?: protos.google.firestore.admin.v1.IDeleteUserCredsRequest, + options?: CallOptions + ): Promise< + [ + protos.google.protobuf.IEmpty, + protos.google.firestore.admin.v1.IDeleteUserCredsRequest | undefined, + {} | undefined, + ] + >; deleteUserCreds( - request: protos.google.firestore.admin.v1.IDeleteUserCredsRequest, - options: CallOptions, - callback: Callback< - protos.google.protobuf.IEmpty, - protos.google.firestore.admin.v1.IDeleteUserCredsRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.firestore.admin.v1.IDeleteUserCredsRequest, + options: CallOptions, + callback: Callback< + protos.google.protobuf.IEmpty, + | protos.google.firestore.admin.v1.IDeleteUserCredsRequest + | null + | undefined, + {} | null | undefined + > + ): void; deleteUserCreds( - request: protos.google.firestore.admin.v1.IDeleteUserCredsRequest, - callback: Callback< - protos.google.protobuf.IEmpty, - protos.google.firestore.admin.v1.IDeleteUserCredsRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.firestore.admin.v1.IDeleteUserCredsRequest, + callback: Callback< + protos.google.protobuf.IEmpty, + | protos.google.firestore.admin.v1.IDeleteUserCredsRequest + | null + | undefined, + {} | null | undefined + > + ): void; deleteUserCreds( - request?: protos.google.firestore.admin.v1.IDeleteUserCredsRequest, - optionsOrCallback?: CallOptions|Callback< - protos.google.protobuf.IEmpty, - protos.google.firestore.admin.v1.IDeleteUserCredsRequest|null|undefined, - {}|null|undefined>, - callback?: Callback< + request?: protos.google.firestore.admin.v1.IDeleteUserCredsRequest, + optionsOrCallback?: + | CallOptions + | Callback< protos.google.protobuf.IEmpty, - protos.google.firestore.admin.v1.IDeleteUserCredsRequest|null|undefined, - {}|null|undefined>): - Promise<[ - protos.google.protobuf.IEmpty, - protos.google.firestore.admin.v1.IDeleteUserCredsRequest|undefined, {}|undefined - ]>|void { + | protos.google.firestore.admin.v1.IDeleteUserCredsRequest + | null + | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.protobuf.IEmpty, + | protos.google.firestore.admin.v1.IDeleteUserCredsRequest + | null + | undefined, + {} | null | undefined + > + ): Promise< + [ + protos.google.protobuf.IEmpty, + protos.google.firestore.admin.v1.IDeleteUserCredsRequest | undefined, + {} | undefined, + ] + > | void { request = request || {}; let options: CallOptions; if (typeof optionsOrCallback === 'function' && callback === undefined) { callback = optionsOrCallback; options = {}; - } - else { + } else { options = optionsOrCallback as CallOptions; } options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - options.otherArgs.headers[ - 'x-goog-request-params' - ] = this._gaxModule.routingHeader.fromParams({ - 'name': request.name ?? '', + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + name: request.name ?? '', + }); + this.initialize().catch(err => { + throw err; }); - this.initialize().catch(err => {throw err}); this._log.info('deleteUserCreds request %j', request); - const wrappedCallback: Callback< - protos.google.protobuf.IEmpty, - protos.google.firestore.admin.v1.IDeleteUserCredsRequest|null|undefined, - {}|null|undefined>|undefined = callback + const wrappedCallback: + | Callback< + protos.google.protobuf.IEmpty, + | protos.google.firestore.admin.v1.IDeleteUserCredsRequest + | null + | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, options, rawResponse) => { this._log.info('deleteUserCreds response %j', response); callback!(error, response, options, rawResponse); // We verified callback above. } : undefined; - return this.innerApiCalls.deleteUserCreds(request, options, wrappedCallback) - ?.then(([response, options, rawResponse]: [ - protos.google.protobuf.IEmpty, - protos.google.firestore.admin.v1.IDeleteUserCredsRequest|undefined, - {}|undefined - ]) => { - this._log.info('deleteUserCreds response %j', response); - return [response, options, rawResponse]; - }); + return this.innerApiCalls + .deleteUserCreds(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.protobuf.IEmpty, + protos.google.firestore.admin.v1.IDeleteUserCredsRequest | undefined, + {} | undefined, + ]) => { + this._log.info('deleteUserCreds response %j', response); + return [response, options, rawResponse]; + } + ); } -/** - * Gets information about a backup. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.name - * Required. Name of the backup to fetch. - * - * Format is `projects/{project}/locations/{location}/backups/{backup}`. - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Promise} - The promise which resolves to an array. - * The first element of the array is an object representing {@link protos.google.firestore.admin.v1.Backup|Backup}. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } - * for more details and examples. - * @example - * region_tag:firestore_v1_generated_FirestoreAdmin_GetBackup_async - */ + /** + * Gets information about a backup. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.name + * Required. Name of the backup to fetch. + * + * Format is `projects/{project}/locations/{location}/backups/{backup}`. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is an object representing {@link protos.google.firestore.admin.v1.Backup|Backup}. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } + * for more details and examples. + * @example + * region_tag:firestore_v1_generated_FirestoreAdmin_GetBackup_async + */ getBackup( - request?: protos.google.firestore.admin.v1.IGetBackupRequest, - options?: CallOptions): - Promise<[ - protos.google.firestore.admin.v1.IBackup, - protos.google.firestore.admin.v1.IGetBackupRequest|undefined, {}|undefined - ]>; + request?: protos.google.firestore.admin.v1.IGetBackupRequest, + options?: CallOptions + ): Promise< + [ + protos.google.firestore.admin.v1.IBackup, + protos.google.firestore.admin.v1.IGetBackupRequest | undefined, + {} | undefined, + ] + >; getBackup( - request: protos.google.firestore.admin.v1.IGetBackupRequest, - options: CallOptions, - callback: Callback< - protos.google.firestore.admin.v1.IBackup, - protos.google.firestore.admin.v1.IGetBackupRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.firestore.admin.v1.IGetBackupRequest, + options: CallOptions, + callback: Callback< + protos.google.firestore.admin.v1.IBackup, + protos.google.firestore.admin.v1.IGetBackupRequest | null | undefined, + {} | null | undefined + > + ): void; getBackup( - request: protos.google.firestore.admin.v1.IGetBackupRequest, - callback: Callback< - protos.google.firestore.admin.v1.IBackup, - protos.google.firestore.admin.v1.IGetBackupRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.firestore.admin.v1.IGetBackupRequest, + callback: Callback< + protos.google.firestore.admin.v1.IBackup, + protos.google.firestore.admin.v1.IGetBackupRequest | null | undefined, + {} | null | undefined + > + ): void; getBackup( - request?: protos.google.firestore.admin.v1.IGetBackupRequest, - optionsOrCallback?: CallOptions|Callback< - protos.google.firestore.admin.v1.IBackup, - protos.google.firestore.admin.v1.IGetBackupRequest|null|undefined, - {}|null|undefined>, - callback?: Callback< + request?: protos.google.firestore.admin.v1.IGetBackupRequest, + optionsOrCallback?: + | CallOptions + | Callback< protos.google.firestore.admin.v1.IBackup, - protos.google.firestore.admin.v1.IGetBackupRequest|null|undefined, - {}|null|undefined>): - Promise<[ - protos.google.firestore.admin.v1.IBackup, - protos.google.firestore.admin.v1.IGetBackupRequest|undefined, {}|undefined - ]>|void { + protos.google.firestore.admin.v1.IGetBackupRequest | null | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.firestore.admin.v1.IBackup, + protos.google.firestore.admin.v1.IGetBackupRequest | null | undefined, + {} | null | undefined + > + ): Promise< + [ + protos.google.firestore.admin.v1.IBackup, + protos.google.firestore.admin.v1.IGetBackupRequest | undefined, + {} | undefined, + ] + > | void { request = request || {}; let options: CallOptions; if (typeof optionsOrCallback === 'function' && callback === undefined) { callback = optionsOrCallback; options = {}; - } - else { + } else { options = optionsOrCallback as CallOptions; } options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - options.otherArgs.headers[ - 'x-goog-request-params' - ] = this._gaxModule.routingHeader.fromParams({ - 'name': request.name ?? '', + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + name: request.name ?? '', + }); + this.initialize().catch(err => { + throw err; }); - this.initialize().catch(err => {throw err}); this._log.info('getBackup request %j', request); - const wrappedCallback: Callback< - protos.google.firestore.admin.v1.IBackup, - protos.google.firestore.admin.v1.IGetBackupRequest|null|undefined, - {}|null|undefined>|undefined = callback + const wrappedCallback: + | Callback< + protos.google.firestore.admin.v1.IBackup, + protos.google.firestore.admin.v1.IGetBackupRequest | null | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, options, rawResponse) => { this._log.info('getBackup response %j', response); callback!(error, response, options, rawResponse); // We verified callback above. } : undefined; - return this.innerApiCalls.getBackup(request, options, wrappedCallback) - ?.then(([response, options, rawResponse]: [ - protos.google.firestore.admin.v1.IBackup, - protos.google.firestore.admin.v1.IGetBackupRequest|undefined, - {}|undefined - ]) => { - this._log.info('getBackup response %j', response); - return [response, options, rawResponse]; - }); + return this.innerApiCalls + .getBackup(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.firestore.admin.v1.IBackup, + protos.google.firestore.admin.v1.IGetBackupRequest | undefined, + {} | undefined, + ]) => { + this._log.info('getBackup response %j', response); + return [response, options, rawResponse]; + } + ); } -/** - * Lists all the backups. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.parent - * Required. The location to list backups from. - * - * Format is `projects/{project}/locations/{location}`. - * Use `{location} = '-'` to list backups from all locations for the given - * project. This allows listing backups from a single location or from all - * locations. - * @param {string} request.filter - * An expression that filters the list of returned backups. - * - * A filter expression consists of a field name, a comparison operator, and a - * value for filtering. - * The value must be a string, a number, or a boolean. The comparison operator - * must be one of: `<`, `>`, `<=`, `>=`, `!=`, `=`, or `:`. - * Colon `:` is the contains operator. Filter rules are not case sensitive. - * - * The following fields in the {@link protos.google.firestore.admin.v1.Backup|Backup} are - * eligible for filtering: - * - * * `database_uid` (supports `=` only) - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Promise} - The promise which resolves to an array. - * The first element of the array is an object representing {@link protos.google.firestore.admin.v1.ListBackupsResponse|ListBackupsResponse}. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } - * for more details and examples. - * @example - * region_tag:firestore_v1_generated_FirestoreAdmin_ListBackups_async - */ + /** + * Lists all the backups. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.parent + * Required. The location to list backups from. + * + * Format is `projects/{project}/locations/{location}`. + * Use `{location} = '-'` to list backups from all locations for the given + * project. This allows listing backups from a single location or from all + * locations. + * @param {string} request.filter + * An expression that filters the list of returned backups. + * + * A filter expression consists of a field name, a comparison operator, and a + * value for filtering. + * The value must be a string, a number, or a boolean. The comparison operator + * must be one of: `<`, `>`, `<=`, `>=`, `!=`, `=`, or `:`. + * Colon `:` is the contains operator. Filter rules are not case sensitive. + * + * The following fields in the {@link protos.google.firestore.admin.v1.Backup|Backup} are + * eligible for filtering: + * + * * `database_uid` (supports `=` only) + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is an object representing {@link protos.google.firestore.admin.v1.ListBackupsResponse|ListBackupsResponse}. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } + * for more details and examples. + * @example + * region_tag:firestore_v1_generated_FirestoreAdmin_ListBackups_async + */ listBackups( - request?: protos.google.firestore.admin.v1.IListBackupsRequest, - options?: CallOptions): - Promise<[ - protos.google.firestore.admin.v1.IListBackupsResponse, - protos.google.firestore.admin.v1.IListBackupsRequest|undefined, {}|undefined - ]>; + request?: protos.google.firestore.admin.v1.IListBackupsRequest, + options?: CallOptions + ): Promise< + [ + protos.google.firestore.admin.v1.IListBackupsResponse, + protos.google.firestore.admin.v1.IListBackupsRequest | undefined, + {} | undefined, + ] + >; listBackups( - request: protos.google.firestore.admin.v1.IListBackupsRequest, - options: CallOptions, - callback: Callback< - protos.google.firestore.admin.v1.IListBackupsResponse, - protos.google.firestore.admin.v1.IListBackupsRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.firestore.admin.v1.IListBackupsRequest, + options: CallOptions, + callback: Callback< + protos.google.firestore.admin.v1.IListBackupsResponse, + protos.google.firestore.admin.v1.IListBackupsRequest | null | undefined, + {} | null | undefined + > + ): void; listBackups( - request: protos.google.firestore.admin.v1.IListBackupsRequest, - callback: Callback< - protos.google.firestore.admin.v1.IListBackupsResponse, - protos.google.firestore.admin.v1.IListBackupsRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.firestore.admin.v1.IListBackupsRequest, + callback: Callback< + protos.google.firestore.admin.v1.IListBackupsResponse, + protos.google.firestore.admin.v1.IListBackupsRequest | null | undefined, + {} | null | undefined + > + ): void; listBackups( - request?: protos.google.firestore.admin.v1.IListBackupsRequest, - optionsOrCallback?: CallOptions|Callback< - protos.google.firestore.admin.v1.IListBackupsResponse, - protos.google.firestore.admin.v1.IListBackupsRequest|null|undefined, - {}|null|undefined>, - callback?: Callback< + request?: protos.google.firestore.admin.v1.IListBackupsRequest, + optionsOrCallback?: + | CallOptions + | Callback< protos.google.firestore.admin.v1.IListBackupsResponse, - protos.google.firestore.admin.v1.IListBackupsRequest|null|undefined, - {}|null|undefined>): - Promise<[ - protos.google.firestore.admin.v1.IListBackupsResponse, - protos.google.firestore.admin.v1.IListBackupsRequest|undefined, {}|undefined - ]>|void { + | protos.google.firestore.admin.v1.IListBackupsRequest + | null + | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.firestore.admin.v1.IListBackupsResponse, + protos.google.firestore.admin.v1.IListBackupsRequest | null | undefined, + {} | null | undefined + > + ): Promise< + [ + protos.google.firestore.admin.v1.IListBackupsResponse, + protos.google.firestore.admin.v1.IListBackupsRequest | undefined, + {} | undefined, + ] + > | void { request = request || {}; let options: CallOptions; if (typeof optionsOrCallback === 'function' && callback === undefined) { callback = optionsOrCallback; options = {}; - } - else { + } else { options = optionsOrCallback as CallOptions; } options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - options.otherArgs.headers[ - 'x-goog-request-params' - ] = this._gaxModule.routingHeader.fromParams({ - 'parent': request.parent ?? '', + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + parent: request.parent ?? '', + }); + this.initialize().catch(err => { + throw err; }); - this.initialize().catch(err => {throw err}); this._log.info('listBackups request %j', request); - const wrappedCallback: Callback< - protos.google.firestore.admin.v1.IListBackupsResponse, - protos.google.firestore.admin.v1.IListBackupsRequest|null|undefined, - {}|null|undefined>|undefined = callback + const wrappedCallback: + | Callback< + protos.google.firestore.admin.v1.IListBackupsResponse, + | protos.google.firestore.admin.v1.IListBackupsRequest + | null + | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, options, rawResponse) => { this._log.info('listBackups response %j', response); callback!(error, response, options, rawResponse); // We verified callback above. } : undefined; - return this.innerApiCalls.listBackups(request, options, wrappedCallback) - ?.then(([response, options, rawResponse]: [ - protos.google.firestore.admin.v1.IListBackupsResponse, - protos.google.firestore.admin.v1.IListBackupsRequest|undefined, - {}|undefined - ]) => { - this._log.info('listBackups response %j', response); - return [response, options, rawResponse]; - }); + return this.innerApiCalls + .listBackups(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.firestore.admin.v1.IListBackupsResponse, + protos.google.firestore.admin.v1.IListBackupsRequest | undefined, + {} | undefined, + ]) => { + this._log.info('listBackups response %j', response); + return [response, options, rawResponse]; + } + ); } -/** - * Deletes a backup. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.name - * Required. Name of the backup to delete. - * - * format is `projects/{project}/locations/{location}/backups/{backup}`. - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Promise} - The promise which resolves to an array. - * The first element of the array is an object representing {@link protos.google.protobuf.Empty|Empty}. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } - * for more details and examples. - * @example - * region_tag:firestore_v1_generated_FirestoreAdmin_DeleteBackup_async - */ + /** + * Deletes a backup. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.name + * Required. Name of the backup to delete. + * + * format is `projects/{project}/locations/{location}/backups/{backup}`. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is an object representing {@link protos.google.protobuf.Empty|Empty}. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } + * for more details and examples. + * @example + * region_tag:firestore_v1_generated_FirestoreAdmin_DeleteBackup_async + */ deleteBackup( - request?: protos.google.firestore.admin.v1.IDeleteBackupRequest, - options?: CallOptions): - Promise<[ - protos.google.protobuf.IEmpty, - protos.google.firestore.admin.v1.IDeleteBackupRequest|undefined, {}|undefined - ]>; + request?: protos.google.firestore.admin.v1.IDeleteBackupRequest, + options?: CallOptions + ): Promise< + [ + protos.google.protobuf.IEmpty, + protos.google.firestore.admin.v1.IDeleteBackupRequest | undefined, + {} | undefined, + ] + >; deleteBackup( - request: protos.google.firestore.admin.v1.IDeleteBackupRequest, - options: CallOptions, - callback: Callback< - protos.google.protobuf.IEmpty, - protos.google.firestore.admin.v1.IDeleteBackupRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.firestore.admin.v1.IDeleteBackupRequest, + options: CallOptions, + callback: Callback< + protos.google.protobuf.IEmpty, + protos.google.firestore.admin.v1.IDeleteBackupRequest | null | undefined, + {} | null | undefined + > + ): void; deleteBackup( - request: protos.google.firestore.admin.v1.IDeleteBackupRequest, - callback: Callback< - protos.google.protobuf.IEmpty, - protos.google.firestore.admin.v1.IDeleteBackupRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.firestore.admin.v1.IDeleteBackupRequest, + callback: Callback< + protos.google.protobuf.IEmpty, + protos.google.firestore.admin.v1.IDeleteBackupRequest | null | undefined, + {} | null | undefined + > + ): void; deleteBackup( - request?: protos.google.firestore.admin.v1.IDeleteBackupRequest, - optionsOrCallback?: CallOptions|Callback< - protos.google.protobuf.IEmpty, - protos.google.firestore.admin.v1.IDeleteBackupRequest|null|undefined, - {}|null|undefined>, - callback?: Callback< + request?: protos.google.firestore.admin.v1.IDeleteBackupRequest, + optionsOrCallback?: + | CallOptions + | Callback< protos.google.protobuf.IEmpty, - protos.google.firestore.admin.v1.IDeleteBackupRequest|null|undefined, - {}|null|undefined>): - Promise<[ - protos.google.protobuf.IEmpty, - protos.google.firestore.admin.v1.IDeleteBackupRequest|undefined, {}|undefined - ]>|void { + | protos.google.firestore.admin.v1.IDeleteBackupRequest + | null + | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.protobuf.IEmpty, + protos.google.firestore.admin.v1.IDeleteBackupRequest | null | undefined, + {} | null | undefined + > + ): Promise< + [ + protos.google.protobuf.IEmpty, + protos.google.firestore.admin.v1.IDeleteBackupRequest | undefined, + {} | undefined, + ] + > | void { request = request || {}; let options: CallOptions; if (typeof optionsOrCallback === 'function' && callback === undefined) { callback = optionsOrCallback; options = {}; - } - else { + } else { options = optionsOrCallback as CallOptions; } options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - options.otherArgs.headers[ - 'x-goog-request-params' - ] = this._gaxModule.routingHeader.fromParams({ - 'name': request.name ?? '', + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + name: request.name ?? '', + }); + this.initialize().catch(err => { + throw err; }); - this.initialize().catch(err => {throw err}); this._log.info('deleteBackup request %j', request); - const wrappedCallback: Callback< - protos.google.protobuf.IEmpty, - protos.google.firestore.admin.v1.IDeleteBackupRequest|null|undefined, - {}|null|undefined>|undefined = callback + const wrappedCallback: + | Callback< + protos.google.protobuf.IEmpty, + | protos.google.firestore.admin.v1.IDeleteBackupRequest + | null + | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, options, rawResponse) => { this._log.info('deleteBackup response %j', response); callback!(error, response, options, rawResponse); // We verified callback above. } : undefined; - return this.innerApiCalls.deleteBackup(request, options, wrappedCallback) - ?.then(([response, options, rawResponse]: [ - protos.google.protobuf.IEmpty, - protos.google.firestore.admin.v1.IDeleteBackupRequest|undefined, - {}|undefined - ]) => { - this._log.info('deleteBackup response %j', response); - return [response, options, rawResponse]; - }); + return this.innerApiCalls + .deleteBackup(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.protobuf.IEmpty, + protos.google.firestore.admin.v1.IDeleteBackupRequest | undefined, + {} | undefined, + ]) => { + this._log.info('deleteBackup response %j', response); + return [response, options, rawResponse]; + } + ); } -/** - * Creates a backup schedule on a database. - * At most two backup schedules can be configured on a database, one daily - * backup schedule and one weekly backup schedule. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.parent - * Required. The parent database. - * - * Format `projects/{project}/databases/{database}` - * @param {google.firestore.admin.v1.BackupSchedule} request.backupSchedule - * Required. The backup schedule to create. - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Promise} - The promise which resolves to an array. - * The first element of the array is an object representing {@link protos.google.firestore.admin.v1.BackupSchedule|BackupSchedule}. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } - * for more details and examples. - * @example - * region_tag:firestore_v1_generated_FirestoreAdmin_CreateBackupSchedule_async - */ + /** + * Creates a backup schedule on a database. + * At most two backup schedules can be configured on a database, one daily + * backup schedule and one weekly backup schedule. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.parent + * Required. The parent database. + * + * Format `projects/{project}/databases/{database}` + * @param {google.firestore.admin.v1.BackupSchedule} request.backupSchedule + * Required. The backup schedule to create. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is an object representing {@link protos.google.firestore.admin.v1.BackupSchedule|BackupSchedule}. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } + * for more details and examples. + * @example + * region_tag:firestore_v1_generated_FirestoreAdmin_CreateBackupSchedule_async + */ createBackupSchedule( - request?: protos.google.firestore.admin.v1.ICreateBackupScheduleRequest, - options?: CallOptions): - Promise<[ - protos.google.firestore.admin.v1.IBackupSchedule, - protos.google.firestore.admin.v1.ICreateBackupScheduleRequest|undefined, {}|undefined - ]>; + request?: protos.google.firestore.admin.v1.ICreateBackupScheduleRequest, + options?: CallOptions + ): Promise< + [ + protos.google.firestore.admin.v1.IBackupSchedule, + protos.google.firestore.admin.v1.ICreateBackupScheduleRequest | undefined, + {} | undefined, + ] + >; createBackupSchedule( - request: protos.google.firestore.admin.v1.ICreateBackupScheduleRequest, - options: CallOptions, - callback: Callback< - protos.google.firestore.admin.v1.IBackupSchedule, - protos.google.firestore.admin.v1.ICreateBackupScheduleRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.firestore.admin.v1.ICreateBackupScheduleRequest, + options: CallOptions, + callback: Callback< + protos.google.firestore.admin.v1.IBackupSchedule, + | protos.google.firestore.admin.v1.ICreateBackupScheduleRequest + | null + | undefined, + {} | null | undefined + > + ): void; createBackupSchedule( - request: protos.google.firestore.admin.v1.ICreateBackupScheduleRequest, - callback: Callback< - protos.google.firestore.admin.v1.IBackupSchedule, - protos.google.firestore.admin.v1.ICreateBackupScheduleRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.firestore.admin.v1.ICreateBackupScheduleRequest, + callback: Callback< + protos.google.firestore.admin.v1.IBackupSchedule, + | protos.google.firestore.admin.v1.ICreateBackupScheduleRequest + | null + | undefined, + {} | null | undefined + > + ): void; createBackupSchedule( - request?: protos.google.firestore.admin.v1.ICreateBackupScheduleRequest, - optionsOrCallback?: CallOptions|Callback< - protos.google.firestore.admin.v1.IBackupSchedule, - protos.google.firestore.admin.v1.ICreateBackupScheduleRequest|null|undefined, - {}|null|undefined>, - callback?: Callback< + request?: protos.google.firestore.admin.v1.ICreateBackupScheduleRequest, + optionsOrCallback?: + | CallOptions + | Callback< protos.google.firestore.admin.v1.IBackupSchedule, - protos.google.firestore.admin.v1.ICreateBackupScheduleRequest|null|undefined, - {}|null|undefined>): - Promise<[ - protos.google.firestore.admin.v1.IBackupSchedule, - protos.google.firestore.admin.v1.ICreateBackupScheduleRequest|undefined, {}|undefined - ]>|void { + | protos.google.firestore.admin.v1.ICreateBackupScheduleRequest + | null + | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.firestore.admin.v1.IBackupSchedule, + | protos.google.firestore.admin.v1.ICreateBackupScheduleRequest + | null + | undefined, + {} | null | undefined + > + ): Promise< + [ + protos.google.firestore.admin.v1.IBackupSchedule, + protos.google.firestore.admin.v1.ICreateBackupScheduleRequest | undefined, + {} | undefined, + ] + > | void { request = request || {}; let options: CallOptions; if (typeof optionsOrCallback === 'function' && callback === undefined) { callback = optionsOrCallback; options = {}; - } - else { + } else { options = optionsOrCallback as CallOptions; } options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - options.otherArgs.headers[ - 'x-goog-request-params' - ] = this._gaxModule.routingHeader.fromParams({ - 'parent': request.parent ?? '', + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + parent: request.parent ?? '', + }); + this.initialize().catch(err => { + throw err; }); - this.initialize().catch(err => {throw err}); this._log.info('createBackupSchedule request %j', request); - const wrappedCallback: Callback< - protos.google.firestore.admin.v1.IBackupSchedule, - protos.google.firestore.admin.v1.ICreateBackupScheduleRequest|null|undefined, - {}|null|undefined>|undefined = callback + const wrappedCallback: + | Callback< + protos.google.firestore.admin.v1.IBackupSchedule, + | protos.google.firestore.admin.v1.ICreateBackupScheduleRequest + | null + | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, options, rawResponse) => { this._log.info('createBackupSchedule response %j', response); callback!(error, response, options, rawResponse); // We verified callback above. } : undefined; - return this.innerApiCalls.createBackupSchedule(request, options, wrappedCallback) - ?.then(([response, options, rawResponse]: [ - protos.google.firestore.admin.v1.IBackupSchedule, - protos.google.firestore.admin.v1.ICreateBackupScheduleRequest|undefined, - {}|undefined - ]) => { - this._log.info('createBackupSchedule response %j', response); - return [response, options, rawResponse]; - }); + return this.innerApiCalls + .createBackupSchedule(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.firestore.admin.v1.IBackupSchedule, + ( + | protos.google.firestore.admin.v1.ICreateBackupScheduleRequest + | undefined + ), + {} | undefined, + ]) => { + this._log.info('createBackupSchedule response %j', response); + return [response, options, rawResponse]; + } + ); } -/** - * Gets information about a backup schedule. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.name - * Required. The name of the backup schedule. - * - * Format - * `projects/{project}/databases/{database}/backupSchedules/{backup_schedule}` - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Promise} - The promise which resolves to an array. - * The first element of the array is an object representing {@link protos.google.firestore.admin.v1.BackupSchedule|BackupSchedule}. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } - * for more details and examples. - * @example - * region_tag:firestore_v1_generated_FirestoreAdmin_GetBackupSchedule_async - */ + /** + * Gets information about a backup schedule. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.name + * Required. The name of the backup schedule. + * + * Format + * `projects/{project}/databases/{database}/backupSchedules/{backup_schedule}` + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is an object representing {@link protos.google.firestore.admin.v1.BackupSchedule|BackupSchedule}. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } + * for more details and examples. + * @example + * region_tag:firestore_v1_generated_FirestoreAdmin_GetBackupSchedule_async + */ getBackupSchedule( - request?: protos.google.firestore.admin.v1.IGetBackupScheduleRequest, - options?: CallOptions): - Promise<[ - protos.google.firestore.admin.v1.IBackupSchedule, - protos.google.firestore.admin.v1.IGetBackupScheduleRequest|undefined, {}|undefined - ]>; + request?: protos.google.firestore.admin.v1.IGetBackupScheduleRequest, + options?: CallOptions + ): Promise< + [ + protos.google.firestore.admin.v1.IBackupSchedule, + protos.google.firestore.admin.v1.IGetBackupScheduleRequest | undefined, + {} | undefined, + ] + >; getBackupSchedule( - request: protos.google.firestore.admin.v1.IGetBackupScheduleRequest, - options: CallOptions, - callback: Callback< - protos.google.firestore.admin.v1.IBackupSchedule, - protos.google.firestore.admin.v1.IGetBackupScheduleRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.firestore.admin.v1.IGetBackupScheduleRequest, + options: CallOptions, + callback: Callback< + protos.google.firestore.admin.v1.IBackupSchedule, + | protos.google.firestore.admin.v1.IGetBackupScheduleRequest + | null + | undefined, + {} | null | undefined + > + ): void; getBackupSchedule( - request: protos.google.firestore.admin.v1.IGetBackupScheduleRequest, - callback: Callback< - protos.google.firestore.admin.v1.IBackupSchedule, - protos.google.firestore.admin.v1.IGetBackupScheduleRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.firestore.admin.v1.IGetBackupScheduleRequest, + callback: Callback< + protos.google.firestore.admin.v1.IBackupSchedule, + | protos.google.firestore.admin.v1.IGetBackupScheduleRequest + | null + | undefined, + {} | null | undefined + > + ): void; getBackupSchedule( - request?: protos.google.firestore.admin.v1.IGetBackupScheduleRequest, - optionsOrCallback?: CallOptions|Callback< - protos.google.firestore.admin.v1.IBackupSchedule, - protos.google.firestore.admin.v1.IGetBackupScheduleRequest|null|undefined, - {}|null|undefined>, - callback?: Callback< + request?: protos.google.firestore.admin.v1.IGetBackupScheduleRequest, + optionsOrCallback?: + | CallOptions + | Callback< protos.google.firestore.admin.v1.IBackupSchedule, - protos.google.firestore.admin.v1.IGetBackupScheduleRequest|null|undefined, - {}|null|undefined>): - Promise<[ - protos.google.firestore.admin.v1.IBackupSchedule, - protos.google.firestore.admin.v1.IGetBackupScheduleRequest|undefined, {}|undefined - ]>|void { + | protos.google.firestore.admin.v1.IGetBackupScheduleRequest + | null + | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.firestore.admin.v1.IBackupSchedule, + | protos.google.firestore.admin.v1.IGetBackupScheduleRequest + | null + | undefined, + {} | null | undefined + > + ): Promise< + [ + protos.google.firestore.admin.v1.IBackupSchedule, + protos.google.firestore.admin.v1.IGetBackupScheduleRequest | undefined, + {} | undefined, + ] + > | void { request = request || {}; let options: CallOptions; if (typeof optionsOrCallback === 'function' && callback === undefined) { callback = optionsOrCallback; options = {}; - } - else { + } else { options = optionsOrCallback as CallOptions; } options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - options.otherArgs.headers[ - 'x-goog-request-params' - ] = this._gaxModule.routingHeader.fromParams({ - 'name': request.name ?? '', + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + name: request.name ?? '', + }); + this.initialize().catch(err => { + throw err; }); - this.initialize().catch(err => {throw err}); this._log.info('getBackupSchedule request %j', request); - const wrappedCallback: Callback< - protos.google.firestore.admin.v1.IBackupSchedule, - protos.google.firestore.admin.v1.IGetBackupScheduleRequest|null|undefined, - {}|null|undefined>|undefined = callback + const wrappedCallback: + | Callback< + protos.google.firestore.admin.v1.IBackupSchedule, + | protos.google.firestore.admin.v1.IGetBackupScheduleRequest + | null + | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, options, rawResponse) => { this._log.info('getBackupSchedule response %j', response); callback!(error, response, options, rawResponse); // We verified callback above. } : undefined; - return this.innerApiCalls.getBackupSchedule(request, options, wrappedCallback) - ?.then(([response, options, rawResponse]: [ - protos.google.firestore.admin.v1.IBackupSchedule, - protos.google.firestore.admin.v1.IGetBackupScheduleRequest|undefined, - {}|undefined - ]) => { - this._log.info('getBackupSchedule response %j', response); - return [response, options, rawResponse]; - }); + return this.innerApiCalls + .getBackupSchedule(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.firestore.admin.v1.IBackupSchedule, + ( + | protos.google.firestore.admin.v1.IGetBackupScheduleRequest + | undefined + ), + {} | undefined, + ]) => { + this._log.info('getBackupSchedule response %j', response); + return [response, options, rawResponse]; + } + ); } -/** - * List backup schedules. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.parent - * Required. The parent database. - * - * Format is `projects/{project}/databases/{database}`. - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Promise} - The promise which resolves to an array. - * The first element of the array is an object representing {@link protos.google.firestore.admin.v1.ListBackupSchedulesResponse|ListBackupSchedulesResponse}. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } - * for more details and examples. - * @example - * region_tag:firestore_v1_generated_FirestoreAdmin_ListBackupSchedules_async - */ + /** + * List backup schedules. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.parent + * Required. The parent database. + * + * Format is `projects/{project}/databases/{database}`. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is an object representing {@link protos.google.firestore.admin.v1.ListBackupSchedulesResponse|ListBackupSchedulesResponse}. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } + * for more details and examples. + * @example + * region_tag:firestore_v1_generated_FirestoreAdmin_ListBackupSchedules_async + */ listBackupSchedules( - request?: protos.google.firestore.admin.v1.IListBackupSchedulesRequest, - options?: CallOptions): - Promise<[ - protos.google.firestore.admin.v1.IListBackupSchedulesResponse, - protos.google.firestore.admin.v1.IListBackupSchedulesRequest|undefined, {}|undefined - ]>; + request?: protos.google.firestore.admin.v1.IListBackupSchedulesRequest, + options?: CallOptions + ): Promise< + [ + protos.google.firestore.admin.v1.IListBackupSchedulesResponse, + protos.google.firestore.admin.v1.IListBackupSchedulesRequest | undefined, + {} | undefined, + ] + >; listBackupSchedules( - request: protos.google.firestore.admin.v1.IListBackupSchedulesRequest, - options: CallOptions, - callback: Callback< - protos.google.firestore.admin.v1.IListBackupSchedulesResponse, - protos.google.firestore.admin.v1.IListBackupSchedulesRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.firestore.admin.v1.IListBackupSchedulesRequest, + options: CallOptions, + callback: Callback< + protos.google.firestore.admin.v1.IListBackupSchedulesResponse, + | protos.google.firestore.admin.v1.IListBackupSchedulesRequest + | null + | undefined, + {} | null | undefined + > + ): void; listBackupSchedules( - request: protos.google.firestore.admin.v1.IListBackupSchedulesRequest, - callback: Callback< - protos.google.firestore.admin.v1.IListBackupSchedulesResponse, - protos.google.firestore.admin.v1.IListBackupSchedulesRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.firestore.admin.v1.IListBackupSchedulesRequest, + callback: Callback< + protos.google.firestore.admin.v1.IListBackupSchedulesResponse, + | protos.google.firestore.admin.v1.IListBackupSchedulesRequest + | null + | undefined, + {} | null | undefined + > + ): void; listBackupSchedules( - request?: protos.google.firestore.admin.v1.IListBackupSchedulesRequest, - optionsOrCallback?: CallOptions|Callback< - protos.google.firestore.admin.v1.IListBackupSchedulesResponse, - protos.google.firestore.admin.v1.IListBackupSchedulesRequest|null|undefined, - {}|null|undefined>, - callback?: Callback< + request?: protos.google.firestore.admin.v1.IListBackupSchedulesRequest, + optionsOrCallback?: + | CallOptions + | Callback< protos.google.firestore.admin.v1.IListBackupSchedulesResponse, - protos.google.firestore.admin.v1.IListBackupSchedulesRequest|null|undefined, - {}|null|undefined>): - Promise<[ - protos.google.firestore.admin.v1.IListBackupSchedulesResponse, - protos.google.firestore.admin.v1.IListBackupSchedulesRequest|undefined, {}|undefined - ]>|void { + | protos.google.firestore.admin.v1.IListBackupSchedulesRequest + | null + | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.firestore.admin.v1.IListBackupSchedulesResponse, + | protos.google.firestore.admin.v1.IListBackupSchedulesRequest + | null + | undefined, + {} | null | undefined + > + ): Promise< + [ + protos.google.firestore.admin.v1.IListBackupSchedulesResponse, + protos.google.firestore.admin.v1.IListBackupSchedulesRequest | undefined, + {} | undefined, + ] + > | void { request = request || {}; let options: CallOptions; if (typeof optionsOrCallback === 'function' && callback === undefined) { callback = optionsOrCallback; options = {}; - } - else { + } else { options = optionsOrCallback as CallOptions; } options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - options.otherArgs.headers[ - 'x-goog-request-params' - ] = this._gaxModule.routingHeader.fromParams({ - 'parent': request.parent ?? '', + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + parent: request.parent ?? '', + }); + this.initialize().catch(err => { + throw err; }); - this.initialize().catch(err => {throw err}); this._log.info('listBackupSchedules request %j', request); - const wrappedCallback: Callback< - protos.google.firestore.admin.v1.IListBackupSchedulesResponse, - protos.google.firestore.admin.v1.IListBackupSchedulesRequest|null|undefined, - {}|null|undefined>|undefined = callback + const wrappedCallback: + | Callback< + protos.google.firestore.admin.v1.IListBackupSchedulesResponse, + | protos.google.firestore.admin.v1.IListBackupSchedulesRequest + | null + | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, options, rawResponse) => { this._log.info('listBackupSchedules response %j', response); callback!(error, response, options, rawResponse); // We verified callback above. } : undefined; - return this.innerApiCalls.listBackupSchedules(request, options, wrappedCallback) - ?.then(([response, options, rawResponse]: [ - protos.google.firestore.admin.v1.IListBackupSchedulesResponse, - protos.google.firestore.admin.v1.IListBackupSchedulesRequest|undefined, - {}|undefined - ]) => { - this._log.info('listBackupSchedules response %j', response); - return [response, options, rawResponse]; - }); + return this.innerApiCalls + .listBackupSchedules(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.firestore.admin.v1.IListBackupSchedulesResponse, + ( + | protos.google.firestore.admin.v1.IListBackupSchedulesRequest + | undefined + ), + {} | undefined, + ]) => { + this._log.info('listBackupSchedules response %j', response); + return [response, options, rawResponse]; + } + ); } -/** - * Updates a backup schedule. - * - * @param {Object} request - * The request object that will be sent. - * @param {google.firestore.admin.v1.BackupSchedule} request.backupSchedule - * Required. The backup schedule to update. - * @param {google.protobuf.FieldMask} request.updateMask - * The list of fields to be updated. - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Promise} - The promise which resolves to an array. - * The first element of the array is an object representing {@link protos.google.firestore.admin.v1.BackupSchedule|BackupSchedule}. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } - * for more details and examples. - * @example - * region_tag:firestore_v1_generated_FirestoreAdmin_UpdateBackupSchedule_async - */ + /** + * Updates a backup schedule. + * + * @param {Object} request + * The request object that will be sent. + * @param {google.firestore.admin.v1.BackupSchedule} request.backupSchedule + * Required. The backup schedule to update. + * @param {google.protobuf.FieldMask} request.updateMask + * The list of fields to be updated. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is an object representing {@link protos.google.firestore.admin.v1.BackupSchedule|BackupSchedule}. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } + * for more details and examples. + * @example + * region_tag:firestore_v1_generated_FirestoreAdmin_UpdateBackupSchedule_async + */ updateBackupSchedule( - request?: protos.google.firestore.admin.v1.IUpdateBackupScheduleRequest, - options?: CallOptions): - Promise<[ - protos.google.firestore.admin.v1.IBackupSchedule, - protos.google.firestore.admin.v1.IUpdateBackupScheduleRequest|undefined, {}|undefined - ]>; + request?: protos.google.firestore.admin.v1.IUpdateBackupScheduleRequest, + options?: CallOptions + ): Promise< + [ + protos.google.firestore.admin.v1.IBackupSchedule, + protos.google.firestore.admin.v1.IUpdateBackupScheduleRequest | undefined, + {} | undefined, + ] + >; updateBackupSchedule( - request: protos.google.firestore.admin.v1.IUpdateBackupScheduleRequest, - options: CallOptions, - callback: Callback< - protos.google.firestore.admin.v1.IBackupSchedule, - protos.google.firestore.admin.v1.IUpdateBackupScheduleRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.firestore.admin.v1.IUpdateBackupScheduleRequest, + options: CallOptions, + callback: Callback< + protos.google.firestore.admin.v1.IBackupSchedule, + | protos.google.firestore.admin.v1.IUpdateBackupScheduleRequest + | null + | undefined, + {} | null | undefined + > + ): void; updateBackupSchedule( - request: protos.google.firestore.admin.v1.IUpdateBackupScheduleRequest, - callback: Callback< - protos.google.firestore.admin.v1.IBackupSchedule, - protos.google.firestore.admin.v1.IUpdateBackupScheduleRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.firestore.admin.v1.IUpdateBackupScheduleRequest, + callback: Callback< + protos.google.firestore.admin.v1.IBackupSchedule, + | protos.google.firestore.admin.v1.IUpdateBackupScheduleRequest + | null + | undefined, + {} | null | undefined + > + ): void; updateBackupSchedule( - request?: protos.google.firestore.admin.v1.IUpdateBackupScheduleRequest, - optionsOrCallback?: CallOptions|Callback< - protos.google.firestore.admin.v1.IBackupSchedule, - protos.google.firestore.admin.v1.IUpdateBackupScheduleRequest|null|undefined, - {}|null|undefined>, - callback?: Callback< + request?: protos.google.firestore.admin.v1.IUpdateBackupScheduleRequest, + optionsOrCallback?: + | CallOptions + | Callback< protos.google.firestore.admin.v1.IBackupSchedule, - protos.google.firestore.admin.v1.IUpdateBackupScheduleRequest|null|undefined, - {}|null|undefined>): - Promise<[ - protos.google.firestore.admin.v1.IBackupSchedule, - protos.google.firestore.admin.v1.IUpdateBackupScheduleRequest|undefined, {}|undefined - ]>|void { + | protos.google.firestore.admin.v1.IUpdateBackupScheduleRequest + | null + | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.firestore.admin.v1.IBackupSchedule, + | protos.google.firestore.admin.v1.IUpdateBackupScheduleRequest + | null + | undefined, + {} | null | undefined + > + ): Promise< + [ + protos.google.firestore.admin.v1.IBackupSchedule, + protos.google.firestore.admin.v1.IUpdateBackupScheduleRequest | undefined, + {} | undefined, + ] + > | void { request = request || {}; let options: CallOptions; if (typeof optionsOrCallback === 'function' && callback === undefined) { callback = optionsOrCallback; options = {}; - } - else { + } else { options = optionsOrCallback as CallOptions; } options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - options.otherArgs.headers[ - 'x-goog-request-params' - ] = this._gaxModule.routingHeader.fromParams({ - 'backup_schedule.name': request.backupSchedule!.name ?? '', + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + 'backup_schedule.name': request.backupSchedule!.name ?? '', + }); + this.initialize().catch(err => { + throw err; }); - this.initialize().catch(err => {throw err}); this._log.info('updateBackupSchedule request %j', request); - const wrappedCallback: Callback< - protos.google.firestore.admin.v1.IBackupSchedule, - protos.google.firestore.admin.v1.IUpdateBackupScheduleRequest|null|undefined, - {}|null|undefined>|undefined = callback + const wrappedCallback: + | Callback< + protos.google.firestore.admin.v1.IBackupSchedule, + | protos.google.firestore.admin.v1.IUpdateBackupScheduleRequest + | null + | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, options, rawResponse) => { this._log.info('updateBackupSchedule response %j', response); callback!(error, response, options, rawResponse); // We verified callback above. } : undefined; - return this.innerApiCalls.updateBackupSchedule(request, options, wrappedCallback) - ?.then(([response, options, rawResponse]: [ - protos.google.firestore.admin.v1.IBackupSchedule, - protos.google.firestore.admin.v1.IUpdateBackupScheduleRequest|undefined, - {}|undefined - ]) => { - this._log.info('updateBackupSchedule response %j', response); - return [response, options, rawResponse]; - }); + return this.innerApiCalls + .updateBackupSchedule(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.firestore.admin.v1.IBackupSchedule, + ( + | protos.google.firestore.admin.v1.IUpdateBackupScheduleRequest + | undefined + ), + {} | undefined, + ]) => { + this._log.info('updateBackupSchedule response %j', response); + return [response, options, rawResponse]; + } + ); } -/** - * Deletes a backup schedule. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.name - * Required. The name of the backup schedule. - * - * Format - * `projects/{project}/databases/{database}/backupSchedules/{backup_schedule}` - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Promise} - The promise which resolves to an array. - * The first element of the array is an object representing {@link protos.google.protobuf.Empty|Empty}. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } - * for more details and examples. - * @example - * region_tag:firestore_v1_generated_FirestoreAdmin_DeleteBackupSchedule_async - */ + /** + * Deletes a backup schedule. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.name + * Required. The name of the backup schedule. + * + * Format + * `projects/{project}/databases/{database}/backupSchedules/{backup_schedule}` + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is an object representing {@link protos.google.protobuf.Empty|Empty}. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } + * for more details and examples. + * @example + * region_tag:firestore_v1_generated_FirestoreAdmin_DeleteBackupSchedule_async + */ deleteBackupSchedule( - request?: protos.google.firestore.admin.v1.IDeleteBackupScheduleRequest, - options?: CallOptions): - Promise<[ - protos.google.protobuf.IEmpty, - protos.google.firestore.admin.v1.IDeleteBackupScheduleRequest|undefined, {}|undefined - ]>; + request?: protos.google.firestore.admin.v1.IDeleteBackupScheduleRequest, + options?: CallOptions + ): Promise< + [ + protos.google.protobuf.IEmpty, + protos.google.firestore.admin.v1.IDeleteBackupScheduleRequest | undefined, + {} | undefined, + ] + >; deleteBackupSchedule( - request: protos.google.firestore.admin.v1.IDeleteBackupScheduleRequest, - options: CallOptions, - callback: Callback< - protos.google.protobuf.IEmpty, - protos.google.firestore.admin.v1.IDeleteBackupScheduleRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.firestore.admin.v1.IDeleteBackupScheduleRequest, + options: CallOptions, + callback: Callback< + protos.google.protobuf.IEmpty, + | protos.google.firestore.admin.v1.IDeleteBackupScheduleRequest + | null + | undefined, + {} | null | undefined + > + ): void; deleteBackupSchedule( - request: protos.google.firestore.admin.v1.IDeleteBackupScheduleRequest, - callback: Callback< - protos.google.protobuf.IEmpty, - protos.google.firestore.admin.v1.IDeleteBackupScheduleRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.firestore.admin.v1.IDeleteBackupScheduleRequest, + callback: Callback< + protos.google.protobuf.IEmpty, + | protos.google.firestore.admin.v1.IDeleteBackupScheduleRequest + | null + | undefined, + {} | null | undefined + > + ): void; deleteBackupSchedule( - request?: protos.google.firestore.admin.v1.IDeleteBackupScheduleRequest, - optionsOrCallback?: CallOptions|Callback< - protos.google.protobuf.IEmpty, - protos.google.firestore.admin.v1.IDeleteBackupScheduleRequest|null|undefined, - {}|null|undefined>, - callback?: Callback< + request?: protos.google.firestore.admin.v1.IDeleteBackupScheduleRequest, + optionsOrCallback?: + | CallOptions + | Callback< protos.google.protobuf.IEmpty, - protos.google.firestore.admin.v1.IDeleteBackupScheduleRequest|null|undefined, - {}|null|undefined>): - Promise<[ - protos.google.protobuf.IEmpty, - protos.google.firestore.admin.v1.IDeleteBackupScheduleRequest|undefined, {}|undefined - ]>|void { + | protos.google.firestore.admin.v1.IDeleteBackupScheduleRequest + | null + | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.protobuf.IEmpty, + | protos.google.firestore.admin.v1.IDeleteBackupScheduleRequest + | null + | undefined, + {} | null | undefined + > + ): Promise< + [ + protos.google.protobuf.IEmpty, + protos.google.firestore.admin.v1.IDeleteBackupScheduleRequest | undefined, + {} | undefined, + ] + > | void { request = request || {}; let options: CallOptions; if (typeof optionsOrCallback === 'function' && callback === undefined) { callback = optionsOrCallback; options = {}; - } - else { + } else { options = optionsOrCallback as CallOptions; } options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - options.otherArgs.headers[ - 'x-goog-request-params' - ] = this._gaxModule.routingHeader.fromParams({ - 'name': request.name ?? '', + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + name: request.name ?? '', + }); + this.initialize().catch(err => { + throw err; }); - this.initialize().catch(err => {throw err}); this._log.info('deleteBackupSchedule request %j', request); - const wrappedCallback: Callback< - protos.google.protobuf.IEmpty, - protos.google.firestore.admin.v1.IDeleteBackupScheduleRequest|null|undefined, - {}|null|undefined>|undefined = callback + const wrappedCallback: + | Callback< + protos.google.protobuf.IEmpty, + | protos.google.firestore.admin.v1.IDeleteBackupScheduleRequest + | null + | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, options, rawResponse) => { this._log.info('deleteBackupSchedule response %j', response); callback!(error, response, options, rawResponse); // We verified callback above. } : undefined; - return this.innerApiCalls.deleteBackupSchedule(request, options, wrappedCallback) - ?.then(([response, options, rawResponse]: [ - protos.google.protobuf.IEmpty, - protos.google.firestore.admin.v1.IDeleteBackupScheduleRequest|undefined, - {}|undefined - ]) => { - this._log.info('deleteBackupSchedule response %j', response); - return [response, options, rawResponse]; - }); + return this.innerApiCalls + .deleteBackupSchedule(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.protobuf.IEmpty, + ( + | protos.google.firestore.admin.v1.IDeleteBackupScheduleRequest + | undefined + ), + {} | undefined, + ]) => { + this._log.info('deleteBackupSchedule response %j', response); + return [response, options, rawResponse]; + } + ); } -/** - * Creates a composite index. This returns a - * {@link protos.google.longrunning.Operation|google.longrunning.Operation} which may be - * used to track the status of the creation. The metadata for the operation - * will be the type - * {@link protos.google.firestore.admin.v1.IndexOperationMetadata|IndexOperationMetadata}. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.parent - * Required. A parent name of the form - * `projects/{project_id}/databases/{database_id}/collectionGroups/{collection_id}` - * @param {google.firestore.admin.v1.Index} request.index - * Required. The composite index to create. - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Promise} - The promise which resolves to an array. - * The first element of the array is an object representing - * a long running operation. Its `promise()` method returns a promise - * you can `await` for. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#long-running-operations | documentation } - * for more details and examples. - * @example - * region_tag:firestore_v1_generated_FirestoreAdmin_CreateIndex_async - */ + /** + * Creates a composite index. This returns a + * {@link protos.google.longrunning.Operation|google.longrunning.Operation} which may be + * used to track the status of the creation. The metadata for the operation + * will be the type + * {@link protos.google.firestore.admin.v1.IndexOperationMetadata|IndexOperationMetadata}. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.parent + * Required. A parent name of the form + * `projects/{project_id}/databases/{database_id}/collectionGroups/{collection_id}` + * @param {google.firestore.admin.v1.Index} request.index + * Required. The composite index to create. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is an object representing + * a long running operation. Its `promise()` method returns a promise + * you can `await` for. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#long-running-operations | documentation } + * for more details and examples. + * @example + * region_tag:firestore_v1_generated_FirestoreAdmin_CreateIndex_async + */ createIndex( - request?: protos.google.firestore.admin.v1.ICreateIndexRequest, - options?: CallOptions): - Promise<[ - LROperation, - protos.google.longrunning.IOperation|undefined, {}|undefined - ]>; + request?: protos.google.firestore.admin.v1.ICreateIndexRequest, + options?: CallOptions + ): Promise< + [ + LROperation< + protos.google.firestore.admin.v1.IIndex, + protos.google.firestore.admin.v1.IIndexOperationMetadata + >, + protos.google.longrunning.IOperation | undefined, + {} | undefined, + ] + >; createIndex( - request: protos.google.firestore.admin.v1.ICreateIndexRequest, - options: CallOptions, - callback: Callback< - LROperation, - protos.google.longrunning.IOperation|null|undefined, - {}|null|undefined>): void; + request: protos.google.firestore.admin.v1.ICreateIndexRequest, + options: CallOptions, + callback: Callback< + LROperation< + protos.google.firestore.admin.v1.IIndex, + protos.google.firestore.admin.v1.IIndexOperationMetadata + >, + protos.google.longrunning.IOperation | null | undefined, + {} | null | undefined + > + ): void; createIndex( - request: protos.google.firestore.admin.v1.ICreateIndexRequest, - callback: Callback< - LROperation, - protos.google.longrunning.IOperation|null|undefined, - {}|null|undefined>): void; + request: protos.google.firestore.admin.v1.ICreateIndexRequest, + callback: Callback< + LROperation< + protos.google.firestore.admin.v1.IIndex, + protos.google.firestore.admin.v1.IIndexOperationMetadata + >, + protos.google.longrunning.IOperation | null | undefined, + {} | null | undefined + > + ): void; createIndex( - request?: protos.google.firestore.admin.v1.ICreateIndexRequest, - optionsOrCallback?: CallOptions|Callback< - LROperation, - protos.google.longrunning.IOperation|null|undefined, - {}|null|undefined>, - callback?: Callback< - LROperation, - protos.google.longrunning.IOperation|null|undefined, - {}|null|undefined>): - Promise<[ - LROperation, - protos.google.longrunning.IOperation|undefined, {}|undefined - ]>|void { + request?: protos.google.firestore.admin.v1.ICreateIndexRequest, + optionsOrCallback?: + | CallOptions + | Callback< + LROperation< + protos.google.firestore.admin.v1.IIndex, + protos.google.firestore.admin.v1.IIndexOperationMetadata + >, + protos.google.longrunning.IOperation | null | undefined, + {} | null | undefined + >, + callback?: Callback< + LROperation< + protos.google.firestore.admin.v1.IIndex, + protos.google.firestore.admin.v1.IIndexOperationMetadata + >, + protos.google.longrunning.IOperation | null | undefined, + {} | null | undefined + > + ): Promise< + [ + LROperation< + protos.google.firestore.admin.v1.IIndex, + protos.google.firestore.admin.v1.IIndexOperationMetadata + >, + protos.google.longrunning.IOperation | undefined, + {} | undefined, + ] + > | void { request = request || {}; let options: CallOptions; if (typeof optionsOrCallback === 'function' && callback === undefined) { callback = optionsOrCallback; options = {}; - } - else { + } else { options = optionsOrCallback as CallOptions; } options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - options.otherArgs.headers[ - 'x-goog-request-params' - ] = this._gaxModule.routingHeader.fromParams({ - 'parent': request.parent ?? '', + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + parent: request.parent ?? '', + }); + this.initialize().catch(err => { + throw err; }); - this.initialize().catch(err => {throw err}); - const wrappedCallback: Callback< - LROperation, - protos.google.longrunning.IOperation|null|undefined, - {}|null|undefined>|undefined = callback + const wrappedCallback: + | Callback< + LROperation< + protos.google.firestore.admin.v1.IIndex, + protos.google.firestore.admin.v1.IIndexOperationMetadata + >, + protos.google.longrunning.IOperation | null | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, rawResponse, _) => { this._log.info('createIndex response %j', rawResponse); callback!(error, response, rawResponse, _); // We verified callback above. } : undefined; this._log.info('createIndex request %j', request); - return this.innerApiCalls.createIndex(request, options, wrappedCallback) - ?.then(([response, rawResponse, _]: [ - LROperation, - protos.google.longrunning.IOperation|undefined, {}|undefined - ]) => { - this._log.info('createIndex response %j', rawResponse); - return [response, rawResponse, _]; - }); + return this.innerApiCalls + .createIndex(request, options, wrappedCallback) + ?.then( + ([response, rawResponse, _]: [ + LROperation< + protos.google.firestore.admin.v1.IIndex, + protos.google.firestore.admin.v1.IIndexOperationMetadata + >, + protos.google.longrunning.IOperation | undefined, + {} | undefined, + ]) => { + this._log.info('createIndex response %j', rawResponse); + return [response, rawResponse, _]; + } + ); } -/** - * Check the status of the long running operation returned by `createIndex()`. - * @param {String} name - * The operation name that will be passed. - * @returns {Promise} - The promise which resolves to an object. - * The decoded operation object has result and metadata field to get information from. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#long-running-operations | documentation } - * for more details and examples. - * @example - * region_tag:firestore_v1_generated_FirestoreAdmin_CreateIndex_async - */ - async checkCreateIndexProgress(name: string): Promise>{ + /** + * Check the status of the long running operation returned by `createIndex()`. + * @param {String} name + * The operation name that will be passed. + * @returns {Promise} - The promise which resolves to an object. + * The decoded operation object has result and metadata field to get information from. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#long-running-operations | documentation } + * for more details and examples. + * @example + * region_tag:firestore_v1_generated_FirestoreAdmin_CreateIndex_async + */ + async checkCreateIndexProgress( + name: string + ): Promise< + LROperation< + protos.google.firestore.admin.v1.Index, + protos.google.firestore.admin.v1.IndexOperationMetadata + > + > { this._log.info('createIndex long-running'); - const request = new this._gaxModule.operationsProtos.google.longrunning.GetOperationRequest({name}); + const request = + new this._gaxModule.operationsProtos.google.longrunning.GetOperationRequest( + {name} + ); const [operation] = await this.operationsClient.getOperation(request); - const decodeOperation = new this._gaxModule.Operation(operation, this.descriptors.longrunning.createIndex, this._gaxModule.createDefaultBackoffSettings()); - return decodeOperation as LROperation; + const decodeOperation = new this._gaxModule.Operation( + operation, + this.descriptors.longrunning.createIndex, + this._gaxModule.createDefaultBackoffSettings() + ); + return decodeOperation as LROperation< + protos.google.firestore.admin.v1.Index, + protos.google.firestore.admin.v1.IndexOperationMetadata + >; } -/** - * Updates a field configuration. Currently, field updates apply only to - * single field index configuration. However, calls to - * {@link protos.google.firestore.admin.v1.FirestoreAdmin.UpdateField|FirestoreAdmin.UpdateField} - * should provide a field mask to avoid changing any configuration that the - * caller isn't aware of. The field mask should be specified as: `{ paths: - * "index_config" }`. - * - * This call returns a - * {@link protos.google.longrunning.Operation|google.longrunning.Operation} which may be - * used to track the status of the field update. The metadata for the - * operation will be the type - * {@link protos.google.firestore.admin.v1.FieldOperationMetadata|FieldOperationMetadata}. - * - * To configure the default field settings for the database, use - * the special `Field` with resource name: - * `projects/{project_id}/databases/{database_id}/collectionGroups/__default__/fields/*`. - * - * @param {Object} request - * The request object that will be sent. - * @param {google.firestore.admin.v1.Field} request.field - * Required. The field to be updated. - * @param {google.protobuf.FieldMask} request.updateMask - * A mask, relative to the field. If specified, only configuration specified - * by this field_mask will be updated in the field. - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Promise} - The promise which resolves to an array. - * The first element of the array is an object representing - * a long running operation. Its `promise()` method returns a promise - * you can `await` for. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#long-running-operations | documentation } - * for more details and examples. - * @example - * region_tag:firestore_v1_generated_FirestoreAdmin_UpdateField_async - */ + /** + * Updates a field configuration. Currently, field updates apply only to + * single field index configuration. However, calls to + * {@link protos.google.firestore.admin.v1.FirestoreAdmin.UpdateField|FirestoreAdmin.UpdateField} + * should provide a field mask to avoid changing any configuration that the + * caller isn't aware of. The field mask should be specified as: `{ paths: + * "index_config" }`. + * + * This call returns a + * {@link protos.google.longrunning.Operation|google.longrunning.Operation} which may be + * used to track the status of the field update. The metadata for the + * operation will be the type + * {@link protos.google.firestore.admin.v1.FieldOperationMetadata|FieldOperationMetadata}. + * + * To configure the default field settings for the database, use + * the special `Field` with resource name: + * `projects/{project_id}/databases/{database_id}/collectionGroups/__default__/fields/*`. + * + * @param {Object} request + * The request object that will be sent. + * @param {google.firestore.admin.v1.Field} request.field + * Required. The field to be updated. + * @param {google.protobuf.FieldMask} request.updateMask + * A mask, relative to the field. If specified, only configuration specified + * by this field_mask will be updated in the field. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is an object representing + * a long running operation. Its `promise()` method returns a promise + * you can `await` for. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#long-running-operations | documentation } + * for more details and examples. + * @example + * region_tag:firestore_v1_generated_FirestoreAdmin_UpdateField_async + */ updateField( - request?: protos.google.firestore.admin.v1.IUpdateFieldRequest, - options?: CallOptions): - Promise<[ - LROperation, - protos.google.longrunning.IOperation|undefined, {}|undefined - ]>; + request?: protos.google.firestore.admin.v1.IUpdateFieldRequest, + options?: CallOptions + ): Promise< + [ + LROperation< + protos.google.firestore.admin.v1.IField, + protos.google.firestore.admin.v1.IFieldOperationMetadata + >, + protos.google.longrunning.IOperation | undefined, + {} | undefined, + ] + >; updateField( - request: protos.google.firestore.admin.v1.IUpdateFieldRequest, - options: CallOptions, - callback: Callback< - LROperation, - protos.google.longrunning.IOperation|null|undefined, - {}|null|undefined>): void; + request: protos.google.firestore.admin.v1.IUpdateFieldRequest, + options: CallOptions, + callback: Callback< + LROperation< + protos.google.firestore.admin.v1.IField, + protos.google.firestore.admin.v1.IFieldOperationMetadata + >, + protos.google.longrunning.IOperation | null | undefined, + {} | null | undefined + > + ): void; updateField( - request: protos.google.firestore.admin.v1.IUpdateFieldRequest, - callback: Callback< - LROperation, - protos.google.longrunning.IOperation|null|undefined, - {}|null|undefined>): void; + request: protos.google.firestore.admin.v1.IUpdateFieldRequest, + callback: Callback< + LROperation< + protos.google.firestore.admin.v1.IField, + protos.google.firestore.admin.v1.IFieldOperationMetadata + >, + protos.google.longrunning.IOperation | null | undefined, + {} | null | undefined + > + ): void; updateField( - request?: protos.google.firestore.admin.v1.IUpdateFieldRequest, - optionsOrCallback?: CallOptions|Callback< - LROperation, - protos.google.longrunning.IOperation|null|undefined, - {}|null|undefined>, - callback?: Callback< - LROperation, - protos.google.longrunning.IOperation|null|undefined, - {}|null|undefined>): - Promise<[ - LROperation, - protos.google.longrunning.IOperation|undefined, {}|undefined - ]>|void { + request?: protos.google.firestore.admin.v1.IUpdateFieldRequest, + optionsOrCallback?: + | CallOptions + | Callback< + LROperation< + protos.google.firestore.admin.v1.IField, + protos.google.firestore.admin.v1.IFieldOperationMetadata + >, + protos.google.longrunning.IOperation | null | undefined, + {} | null | undefined + >, + callback?: Callback< + LROperation< + protos.google.firestore.admin.v1.IField, + protos.google.firestore.admin.v1.IFieldOperationMetadata + >, + protos.google.longrunning.IOperation | null | undefined, + {} | null | undefined + > + ): Promise< + [ + LROperation< + protos.google.firestore.admin.v1.IField, + protos.google.firestore.admin.v1.IFieldOperationMetadata + >, + protos.google.longrunning.IOperation | undefined, + {} | undefined, + ] + > | void { request = request || {}; let options: CallOptions; if (typeof optionsOrCallback === 'function' && callback === undefined) { callback = optionsOrCallback; options = {}; - } - else { + } else { options = optionsOrCallback as CallOptions; } options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - options.otherArgs.headers[ - 'x-goog-request-params' - ] = this._gaxModule.routingHeader.fromParams({ - 'field.name': request.field!.name ?? '', + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + 'field.name': request.field!.name ?? '', + }); + this.initialize().catch(err => { + throw err; }); - this.initialize().catch(err => {throw err}); - const wrappedCallback: Callback< - LROperation, - protos.google.longrunning.IOperation|null|undefined, - {}|null|undefined>|undefined = callback + const wrappedCallback: + | Callback< + LROperation< + protos.google.firestore.admin.v1.IField, + protos.google.firestore.admin.v1.IFieldOperationMetadata + >, + protos.google.longrunning.IOperation | null | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, rawResponse, _) => { this._log.info('updateField response %j', rawResponse); callback!(error, response, rawResponse, _); // We verified callback above. } : undefined; this._log.info('updateField request %j', request); - return this.innerApiCalls.updateField(request, options, wrappedCallback) - ?.then(([response, rawResponse, _]: [ - LROperation, - protos.google.longrunning.IOperation|undefined, {}|undefined - ]) => { - this._log.info('updateField response %j', rawResponse); - return [response, rawResponse, _]; - }); + return this.innerApiCalls + .updateField(request, options, wrappedCallback) + ?.then( + ([response, rawResponse, _]: [ + LROperation< + protos.google.firestore.admin.v1.IField, + protos.google.firestore.admin.v1.IFieldOperationMetadata + >, + protos.google.longrunning.IOperation | undefined, + {} | undefined, + ]) => { + this._log.info('updateField response %j', rawResponse); + return [response, rawResponse, _]; + } + ); } -/** - * Check the status of the long running operation returned by `updateField()`. - * @param {String} name - * The operation name that will be passed. - * @returns {Promise} - The promise which resolves to an object. - * The decoded operation object has result and metadata field to get information from. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#long-running-operations | documentation } - * for more details and examples. - * @example - * region_tag:firestore_v1_generated_FirestoreAdmin_UpdateField_async - */ - async checkUpdateFieldProgress(name: string): Promise>{ + /** + * Check the status of the long running operation returned by `updateField()`. + * @param {String} name + * The operation name that will be passed. + * @returns {Promise} - The promise which resolves to an object. + * The decoded operation object has result and metadata field to get information from. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#long-running-operations | documentation } + * for more details and examples. + * @example + * region_tag:firestore_v1_generated_FirestoreAdmin_UpdateField_async + */ + async checkUpdateFieldProgress( + name: string + ): Promise< + LROperation< + protos.google.firestore.admin.v1.Field, + protos.google.firestore.admin.v1.FieldOperationMetadata + > + > { this._log.info('updateField long-running'); - const request = new this._gaxModule.operationsProtos.google.longrunning.GetOperationRequest({name}); + const request = + new this._gaxModule.operationsProtos.google.longrunning.GetOperationRequest( + {name} + ); const [operation] = await this.operationsClient.getOperation(request); - const decodeOperation = new this._gaxModule.Operation(operation, this.descriptors.longrunning.updateField, this._gaxModule.createDefaultBackoffSettings()); - return decodeOperation as LROperation; + const decodeOperation = new this._gaxModule.Operation( + operation, + this.descriptors.longrunning.updateField, + this._gaxModule.createDefaultBackoffSettings() + ); + return decodeOperation as LROperation< + protos.google.firestore.admin.v1.Field, + protos.google.firestore.admin.v1.FieldOperationMetadata + >; } -/** - * Exports a copy of all or a subset of documents from Google Cloud Firestore - * to another storage system, such as Google Cloud Storage. Recent updates to - * documents may not be reflected in the export. The export occurs in the - * background and its progress can be monitored and managed via the - * Operation resource that is created. The output of an export may only be - * used once the associated operation is done. If an export operation is - * cancelled before completion it may leave partial data behind in Google - * Cloud Storage. - * - * For more details on export behavior and output format, refer to: - * https://cloud.google.com/firestore/docs/manage-data/export-import - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.name - * Required. Database to export. Should be of the form: - * `projects/{project_id}/databases/{database_id}`. - * @param {string[]} request.collectionIds - * Which collection IDs to export. Unspecified means all collections. Each - * collection ID in this list must be unique. - * @param {string} request.outputUriPrefix - * The output URI. Currently only supports Google Cloud Storage URIs of the - * form: `gs://BUCKET_NAME[/NAMESPACE_PATH]`, where `BUCKET_NAME` is the name - * of the Google Cloud Storage bucket and `NAMESPACE_PATH` is an optional - * Google Cloud Storage namespace path. When - * choosing a name, be sure to consider Google Cloud Storage naming - * guidelines: https://cloud.google.com/storage/docs/naming. - * If the URI is a bucket (without a namespace path), a prefix will be - * generated based on the start time. - * @param {string[]} request.namespaceIds - * An empty list represents all namespaces. This is the preferred - * usage for databases that don't use namespaces. - * - * An empty string element represents the default namespace. This should be - * used if the database has data in non-default namespaces, but doesn't want - * to include them. Each namespace in this list must be unique. - * @param {google.protobuf.Timestamp} request.snapshotTime - * The timestamp that corresponds to the version of the database to be - * exported. The timestamp must be in the past, rounded to the minute and not - * older than - * {@link protos.google.firestore.admin.v1.Database.earliest_version_time|earliestVersionTime}. - * If specified, then the exported documents will represent a consistent view - * of the database at the provided time. Otherwise, there are no guarantees - * about the consistency of the exported documents. - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Promise} - The promise which resolves to an array. - * The first element of the array is an object representing - * a long running operation. Its `promise()` method returns a promise - * you can `await` for. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#long-running-operations | documentation } - * for more details and examples. - * @example - * region_tag:firestore_v1_generated_FirestoreAdmin_ExportDocuments_async - */ + /** + * Exports a copy of all or a subset of documents from Google Cloud Firestore + * to another storage system, such as Google Cloud Storage. Recent updates to + * documents may not be reflected in the export. The export occurs in the + * background and its progress can be monitored and managed via the + * Operation resource that is created. The output of an export may only be + * used once the associated operation is done. If an export operation is + * cancelled before completion it may leave partial data behind in Google + * Cloud Storage. + * + * For more details on export behavior and output format, refer to: + * https://cloud.google.com/firestore/docs/manage-data/export-import + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.name + * Required. Database to export. Should be of the form: + * `projects/{project_id}/databases/{database_id}`. + * @param {string[]} request.collectionIds + * Which collection IDs to export. Unspecified means all collections. Each + * collection ID in this list must be unique. + * @param {string} request.outputUriPrefix + * The output URI. Currently only supports Google Cloud Storage URIs of the + * form: `gs://BUCKET_NAME[/NAMESPACE_PATH]`, where `BUCKET_NAME` is the name + * of the Google Cloud Storage bucket and `NAMESPACE_PATH` is an optional + * Google Cloud Storage namespace path. When + * choosing a name, be sure to consider Google Cloud Storage naming + * guidelines: https://cloud.google.com/storage/docs/naming. + * If the URI is a bucket (without a namespace path), a prefix will be + * generated based on the start time. + * @param {string[]} request.namespaceIds + * An empty list represents all namespaces. This is the preferred + * usage for databases that don't use namespaces. + * + * An empty string element represents the default namespace. This should be + * used if the database has data in non-default namespaces, but doesn't want + * to include them. Each namespace in this list must be unique. + * @param {google.protobuf.Timestamp} request.snapshotTime + * The timestamp that corresponds to the version of the database to be + * exported. The timestamp must be in the past, rounded to the minute and not + * older than + * {@link protos.google.firestore.admin.v1.Database.earliest_version_time|earliestVersionTime}. + * If specified, then the exported documents will represent a consistent view + * of the database at the provided time. Otherwise, there are no guarantees + * about the consistency of the exported documents. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is an object representing + * a long running operation. Its `promise()` method returns a promise + * you can `await` for. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#long-running-operations | documentation } + * for more details and examples. + * @example + * region_tag:firestore_v1_generated_FirestoreAdmin_ExportDocuments_async + */ exportDocuments( - request?: protos.google.firestore.admin.v1.IExportDocumentsRequest, - options?: CallOptions): - Promise<[ - LROperation, - protos.google.longrunning.IOperation|undefined, {}|undefined - ]>; + request?: protos.google.firestore.admin.v1.IExportDocumentsRequest, + options?: CallOptions + ): Promise< + [ + LROperation< + protos.google.firestore.admin.v1.IExportDocumentsResponse, + protos.google.firestore.admin.v1.IExportDocumentsMetadata + >, + protos.google.longrunning.IOperation | undefined, + {} | undefined, + ] + >; exportDocuments( - request: protos.google.firestore.admin.v1.IExportDocumentsRequest, - options: CallOptions, - callback: Callback< - LROperation, - protos.google.longrunning.IOperation|null|undefined, - {}|null|undefined>): void; + request: protos.google.firestore.admin.v1.IExportDocumentsRequest, + options: CallOptions, + callback: Callback< + LROperation< + protos.google.firestore.admin.v1.IExportDocumentsResponse, + protos.google.firestore.admin.v1.IExportDocumentsMetadata + >, + protos.google.longrunning.IOperation | null | undefined, + {} | null | undefined + > + ): void; exportDocuments( - request: protos.google.firestore.admin.v1.IExportDocumentsRequest, - callback: Callback< - LROperation, - protos.google.longrunning.IOperation|null|undefined, - {}|null|undefined>): void; + request: protos.google.firestore.admin.v1.IExportDocumentsRequest, + callback: Callback< + LROperation< + protos.google.firestore.admin.v1.IExportDocumentsResponse, + protos.google.firestore.admin.v1.IExportDocumentsMetadata + >, + protos.google.longrunning.IOperation | null | undefined, + {} | null | undefined + > + ): void; exportDocuments( - request?: protos.google.firestore.admin.v1.IExportDocumentsRequest, - optionsOrCallback?: CallOptions|Callback< - LROperation, - protos.google.longrunning.IOperation|null|undefined, - {}|null|undefined>, - callback?: Callback< - LROperation, - protos.google.longrunning.IOperation|null|undefined, - {}|null|undefined>): - Promise<[ - LROperation, - protos.google.longrunning.IOperation|undefined, {}|undefined - ]>|void { + request?: protos.google.firestore.admin.v1.IExportDocumentsRequest, + optionsOrCallback?: + | CallOptions + | Callback< + LROperation< + protos.google.firestore.admin.v1.IExportDocumentsResponse, + protos.google.firestore.admin.v1.IExportDocumentsMetadata + >, + protos.google.longrunning.IOperation | null | undefined, + {} | null | undefined + >, + callback?: Callback< + LROperation< + protos.google.firestore.admin.v1.IExportDocumentsResponse, + protos.google.firestore.admin.v1.IExportDocumentsMetadata + >, + protos.google.longrunning.IOperation | null | undefined, + {} | null | undefined + > + ): Promise< + [ + LROperation< + protos.google.firestore.admin.v1.IExportDocumentsResponse, + protos.google.firestore.admin.v1.IExportDocumentsMetadata + >, + protos.google.longrunning.IOperation | undefined, + {} | undefined, + ] + > | void { request = request || {}; let options: CallOptions; if (typeof optionsOrCallback === 'function' && callback === undefined) { callback = optionsOrCallback; options = {}; - } - else { + } else { options = optionsOrCallback as CallOptions; } options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - options.otherArgs.headers[ - 'x-goog-request-params' - ] = this._gaxModule.routingHeader.fromParams({ - 'name': request.name ?? '', + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + name: request.name ?? '', + }); + this.initialize().catch(err => { + throw err; }); - this.initialize().catch(err => {throw err}); - const wrappedCallback: Callback< - LROperation, - protos.google.longrunning.IOperation|null|undefined, - {}|null|undefined>|undefined = callback + const wrappedCallback: + | Callback< + LROperation< + protos.google.firestore.admin.v1.IExportDocumentsResponse, + protos.google.firestore.admin.v1.IExportDocumentsMetadata + >, + protos.google.longrunning.IOperation | null | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, rawResponse, _) => { this._log.info('exportDocuments response %j', rawResponse); callback!(error, response, rawResponse, _); // We verified callback above. } : undefined; this._log.info('exportDocuments request %j', request); - return this.innerApiCalls.exportDocuments(request, options, wrappedCallback) - ?.then(([response, rawResponse, _]: [ - LROperation, - protos.google.longrunning.IOperation|undefined, {}|undefined - ]) => { - this._log.info('exportDocuments response %j', rawResponse); - return [response, rawResponse, _]; - }); + return this.innerApiCalls + .exportDocuments(request, options, wrappedCallback) + ?.then( + ([response, rawResponse, _]: [ + LROperation< + protos.google.firestore.admin.v1.IExportDocumentsResponse, + protos.google.firestore.admin.v1.IExportDocumentsMetadata + >, + protos.google.longrunning.IOperation | undefined, + {} | undefined, + ]) => { + this._log.info('exportDocuments response %j', rawResponse); + return [response, rawResponse, _]; + } + ); } -/** - * Check the status of the long running operation returned by `exportDocuments()`. - * @param {String} name - * The operation name that will be passed. - * @returns {Promise} - The promise which resolves to an object. - * The decoded operation object has result and metadata field to get information from. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#long-running-operations | documentation } - * for more details and examples. - * @example - * region_tag:firestore_v1_generated_FirestoreAdmin_ExportDocuments_async - */ - async checkExportDocumentsProgress(name: string): Promise>{ + /** + * Check the status of the long running operation returned by `exportDocuments()`. + * @param {String} name + * The operation name that will be passed. + * @returns {Promise} - The promise which resolves to an object. + * The decoded operation object has result and metadata field to get information from. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#long-running-operations | documentation } + * for more details and examples. + * @example + * region_tag:firestore_v1_generated_FirestoreAdmin_ExportDocuments_async + */ + async checkExportDocumentsProgress( + name: string + ): Promise< + LROperation< + protos.google.firestore.admin.v1.ExportDocumentsResponse, + protos.google.firestore.admin.v1.ExportDocumentsMetadata + > + > { this._log.info('exportDocuments long-running'); - const request = new this._gaxModule.operationsProtos.google.longrunning.GetOperationRequest({name}); + const request = + new this._gaxModule.operationsProtos.google.longrunning.GetOperationRequest( + {name} + ); const [operation] = await this.operationsClient.getOperation(request); - const decodeOperation = new this._gaxModule.Operation(operation, this.descriptors.longrunning.exportDocuments, this._gaxModule.createDefaultBackoffSettings()); - return decodeOperation as LROperation; + const decodeOperation = new this._gaxModule.Operation( + operation, + this.descriptors.longrunning.exportDocuments, + this._gaxModule.createDefaultBackoffSettings() + ); + return decodeOperation as LROperation< + protos.google.firestore.admin.v1.ExportDocumentsResponse, + protos.google.firestore.admin.v1.ExportDocumentsMetadata + >; } -/** - * Imports documents into Google Cloud Firestore. Existing documents with the - * same name are overwritten. The import occurs in the background and its - * progress can be monitored and managed via the Operation resource that is - * created. If an ImportDocuments operation is cancelled, it is possible - * that a subset of the data has already been imported to Cloud Firestore. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.name - * Required. Database to import into. Should be of the form: - * `projects/{project_id}/databases/{database_id}`. - * @param {string[]} request.collectionIds - * Which collection IDs to import. Unspecified means all collections included - * in the import. Each collection ID in this list must be unique. - * @param {string} request.inputUriPrefix - * Location of the exported files. - * This must match the output_uri_prefix of an ExportDocumentsResponse from - * an export that has completed successfully. - * See: - * {@link protos.google.firestore.admin.v1.ExportDocumentsResponse.output_uri_prefix|google.firestore.admin.v1.ExportDocumentsResponse.output_uri_prefix}. - * @param {string[]} request.namespaceIds - * An empty list represents all namespaces. This is the preferred - * usage for databases that don't use namespaces. - * - * An empty string element represents the default namespace. This should be - * used if the database has data in non-default namespaces, but doesn't want - * to include them. Each namespace in this list must be unique. - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Promise} - The promise which resolves to an array. - * The first element of the array is an object representing - * a long running operation. Its `promise()` method returns a promise - * you can `await` for. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#long-running-operations | documentation } - * for more details and examples. - * @example - * region_tag:firestore_v1_generated_FirestoreAdmin_ImportDocuments_async - */ + /** + * Imports documents into Google Cloud Firestore. Existing documents with the + * same name are overwritten. The import occurs in the background and its + * progress can be monitored and managed via the Operation resource that is + * created. If an ImportDocuments operation is cancelled, it is possible + * that a subset of the data has already been imported to Cloud Firestore. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.name + * Required. Database to import into. Should be of the form: + * `projects/{project_id}/databases/{database_id}`. + * @param {string[]} request.collectionIds + * Which collection IDs to import. Unspecified means all collections included + * in the import. Each collection ID in this list must be unique. + * @param {string} request.inputUriPrefix + * Location of the exported files. + * This must match the output_uri_prefix of an ExportDocumentsResponse from + * an export that has completed successfully. + * See: + * {@link protos.google.firestore.admin.v1.ExportDocumentsResponse.output_uri_prefix|google.firestore.admin.v1.ExportDocumentsResponse.output_uri_prefix}. + * @param {string[]} request.namespaceIds + * An empty list represents all namespaces. This is the preferred + * usage for databases that don't use namespaces. + * + * An empty string element represents the default namespace. This should be + * used if the database has data in non-default namespaces, but doesn't want + * to include them. Each namespace in this list must be unique. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is an object representing + * a long running operation. Its `promise()` method returns a promise + * you can `await` for. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#long-running-operations | documentation } + * for more details and examples. + * @example + * region_tag:firestore_v1_generated_FirestoreAdmin_ImportDocuments_async + */ importDocuments( - request?: protos.google.firestore.admin.v1.IImportDocumentsRequest, - options?: CallOptions): - Promise<[ - LROperation, - protos.google.longrunning.IOperation|undefined, {}|undefined - ]>; + request?: protos.google.firestore.admin.v1.IImportDocumentsRequest, + options?: CallOptions + ): Promise< + [ + LROperation< + protos.google.protobuf.IEmpty, + protos.google.firestore.admin.v1.IImportDocumentsMetadata + >, + protos.google.longrunning.IOperation | undefined, + {} | undefined, + ] + >; importDocuments( - request: protos.google.firestore.admin.v1.IImportDocumentsRequest, - options: CallOptions, - callback: Callback< - LROperation, - protos.google.longrunning.IOperation|null|undefined, - {}|null|undefined>): void; + request: protos.google.firestore.admin.v1.IImportDocumentsRequest, + options: CallOptions, + callback: Callback< + LROperation< + protos.google.protobuf.IEmpty, + protos.google.firestore.admin.v1.IImportDocumentsMetadata + >, + protos.google.longrunning.IOperation | null | undefined, + {} | null | undefined + > + ): void; importDocuments( - request: protos.google.firestore.admin.v1.IImportDocumentsRequest, - callback: Callback< - LROperation, - protos.google.longrunning.IOperation|null|undefined, - {}|null|undefined>): void; + request: protos.google.firestore.admin.v1.IImportDocumentsRequest, + callback: Callback< + LROperation< + protos.google.protobuf.IEmpty, + protos.google.firestore.admin.v1.IImportDocumentsMetadata + >, + protos.google.longrunning.IOperation | null | undefined, + {} | null | undefined + > + ): void; importDocuments( - request?: protos.google.firestore.admin.v1.IImportDocumentsRequest, - optionsOrCallback?: CallOptions|Callback< - LROperation, - protos.google.longrunning.IOperation|null|undefined, - {}|null|undefined>, - callback?: Callback< - LROperation, - protos.google.longrunning.IOperation|null|undefined, - {}|null|undefined>): - Promise<[ - LROperation, - protos.google.longrunning.IOperation|undefined, {}|undefined - ]>|void { + request?: protos.google.firestore.admin.v1.IImportDocumentsRequest, + optionsOrCallback?: + | CallOptions + | Callback< + LROperation< + protos.google.protobuf.IEmpty, + protos.google.firestore.admin.v1.IImportDocumentsMetadata + >, + protos.google.longrunning.IOperation | null | undefined, + {} | null | undefined + >, + callback?: Callback< + LROperation< + protos.google.protobuf.IEmpty, + protos.google.firestore.admin.v1.IImportDocumentsMetadata + >, + protos.google.longrunning.IOperation | null | undefined, + {} | null | undefined + > + ): Promise< + [ + LROperation< + protos.google.protobuf.IEmpty, + protos.google.firestore.admin.v1.IImportDocumentsMetadata + >, + protos.google.longrunning.IOperation | undefined, + {} | undefined, + ] + > | void { request = request || {}; let options: CallOptions; if (typeof optionsOrCallback === 'function' && callback === undefined) { callback = optionsOrCallback; options = {}; - } - else { + } else { options = optionsOrCallback as CallOptions; } options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - options.otherArgs.headers[ - 'x-goog-request-params' - ] = this._gaxModule.routingHeader.fromParams({ - 'name': request.name ?? '', + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + name: request.name ?? '', + }); + this.initialize().catch(err => { + throw err; }); - this.initialize().catch(err => {throw err}); - const wrappedCallback: Callback< - LROperation, - protos.google.longrunning.IOperation|null|undefined, - {}|null|undefined>|undefined = callback + const wrappedCallback: + | Callback< + LROperation< + protos.google.protobuf.IEmpty, + protos.google.firestore.admin.v1.IImportDocumentsMetadata + >, + protos.google.longrunning.IOperation | null | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, rawResponse, _) => { this._log.info('importDocuments response %j', rawResponse); callback!(error, response, rawResponse, _); // We verified callback above. } : undefined; this._log.info('importDocuments request %j', request); - return this.innerApiCalls.importDocuments(request, options, wrappedCallback) - ?.then(([response, rawResponse, _]: [ - LROperation, - protos.google.longrunning.IOperation|undefined, {}|undefined - ]) => { - this._log.info('importDocuments response %j', rawResponse); - return [response, rawResponse, _]; - }); + return this.innerApiCalls + .importDocuments(request, options, wrappedCallback) + ?.then( + ([response, rawResponse, _]: [ + LROperation< + protos.google.protobuf.IEmpty, + protos.google.firestore.admin.v1.IImportDocumentsMetadata + >, + protos.google.longrunning.IOperation | undefined, + {} | undefined, + ]) => { + this._log.info('importDocuments response %j', rawResponse); + return [response, rawResponse, _]; + } + ); } -/** - * Check the status of the long running operation returned by `importDocuments()`. - * @param {String} name - * The operation name that will be passed. - * @returns {Promise} - The promise which resolves to an object. - * The decoded operation object has result and metadata field to get information from. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#long-running-operations | documentation } - * for more details and examples. - * @example - * region_tag:firestore_v1_generated_FirestoreAdmin_ImportDocuments_async - */ - async checkImportDocumentsProgress(name: string): Promise>{ + /** + * Check the status of the long running operation returned by `importDocuments()`. + * @param {String} name + * The operation name that will be passed. + * @returns {Promise} - The promise which resolves to an object. + * The decoded operation object has result and metadata field to get information from. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#long-running-operations | documentation } + * for more details and examples. + * @example + * region_tag:firestore_v1_generated_FirestoreAdmin_ImportDocuments_async + */ + async checkImportDocumentsProgress( + name: string + ): Promise< + LROperation< + protos.google.protobuf.Empty, + protos.google.firestore.admin.v1.ImportDocumentsMetadata + > + > { this._log.info('importDocuments long-running'); - const request = new this._gaxModule.operationsProtos.google.longrunning.GetOperationRequest({name}); + const request = + new this._gaxModule.operationsProtos.google.longrunning.GetOperationRequest( + {name} + ); const [operation] = await this.operationsClient.getOperation(request); - const decodeOperation = new this._gaxModule.Operation(operation, this.descriptors.longrunning.importDocuments, this._gaxModule.createDefaultBackoffSettings()); - return decodeOperation as LROperation; + const decodeOperation = new this._gaxModule.Operation( + operation, + this.descriptors.longrunning.importDocuments, + this._gaxModule.createDefaultBackoffSettings() + ); + return decodeOperation as LROperation< + protos.google.protobuf.Empty, + protos.google.firestore.admin.v1.ImportDocumentsMetadata + >; } -/** - * Bulk deletes a subset of documents from Google Cloud Firestore. - * Documents created or updated after the underlying system starts to process - * the request will not be deleted. The bulk delete occurs in the background - * and its progress can be monitored and managed via the Operation resource - * that is created. - * - * For more details on bulk delete behavior, refer to: - * https://cloud.google.com/firestore/docs/manage-data/bulk-delete - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.name - * Required. Database to operate. Should be of the form: - * `projects/{project_id}/databases/{database_id}`. - * @param {string[]} [request.collectionIds] - * Optional. IDs of the collection groups to delete. Unspecified means all - * collection groups. - * - * Each collection group in this list must be unique. - * @param {string[]} [request.namespaceIds] - * Optional. Namespaces to delete. - * - * An empty list means all namespaces. This is the recommended - * usage for databases that don't use namespaces. - * - * An empty string element represents the default namespace. This should be - * used if the database has data in non-default namespaces, but doesn't want - * to delete from them. - * - * Each namespace in this list must be unique. - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Promise} - The promise which resolves to an array. - * The first element of the array is an object representing - * a long running operation. Its `promise()` method returns a promise - * you can `await` for. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#long-running-operations | documentation } - * for more details and examples. - * @example - * region_tag:firestore_v1_generated_FirestoreAdmin_BulkDeleteDocuments_async - */ + /** + * Bulk deletes a subset of documents from Google Cloud Firestore. + * Documents created or updated after the underlying system starts to process + * the request will not be deleted. The bulk delete occurs in the background + * and its progress can be monitored and managed via the Operation resource + * that is created. + * + * For more details on bulk delete behavior, refer to: + * https://cloud.google.com/firestore/docs/manage-data/bulk-delete + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.name + * Required. Database to operate. Should be of the form: + * `projects/{project_id}/databases/{database_id}`. + * @param {string[]} [request.collectionIds] + * Optional. IDs of the collection groups to delete. Unspecified means all + * collection groups. + * + * Each collection group in this list must be unique. + * @param {string[]} [request.namespaceIds] + * Optional. Namespaces to delete. + * + * An empty list means all namespaces. This is the recommended + * usage for databases that don't use namespaces. + * + * An empty string element represents the default namespace. This should be + * used if the database has data in non-default namespaces, but doesn't want + * to delete from them. + * + * Each namespace in this list must be unique. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is an object representing + * a long running operation. Its `promise()` method returns a promise + * you can `await` for. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#long-running-operations | documentation } + * for more details and examples. + * @example + * region_tag:firestore_v1_generated_FirestoreAdmin_BulkDeleteDocuments_async + */ bulkDeleteDocuments( - request?: protos.google.firestore.admin.v1.IBulkDeleteDocumentsRequest, - options?: CallOptions): - Promise<[ - LROperation, - protos.google.longrunning.IOperation|undefined, {}|undefined - ]>; + request?: protos.google.firestore.admin.v1.IBulkDeleteDocumentsRequest, + options?: CallOptions + ): Promise< + [ + LROperation< + protos.google.firestore.admin.v1.IBulkDeleteDocumentsResponse, + protos.google.firestore.admin.v1.IBulkDeleteDocumentsMetadata + >, + protos.google.longrunning.IOperation | undefined, + {} | undefined, + ] + >; bulkDeleteDocuments( - request: protos.google.firestore.admin.v1.IBulkDeleteDocumentsRequest, - options: CallOptions, - callback: Callback< - LROperation, - protos.google.longrunning.IOperation|null|undefined, - {}|null|undefined>): void; + request: protos.google.firestore.admin.v1.IBulkDeleteDocumentsRequest, + options: CallOptions, + callback: Callback< + LROperation< + protos.google.firestore.admin.v1.IBulkDeleteDocumentsResponse, + protos.google.firestore.admin.v1.IBulkDeleteDocumentsMetadata + >, + protos.google.longrunning.IOperation | null | undefined, + {} | null | undefined + > + ): void; bulkDeleteDocuments( - request: protos.google.firestore.admin.v1.IBulkDeleteDocumentsRequest, - callback: Callback< - LROperation, - protos.google.longrunning.IOperation|null|undefined, - {}|null|undefined>): void; + request: protos.google.firestore.admin.v1.IBulkDeleteDocumentsRequest, + callback: Callback< + LROperation< + protos.google.firestore.admin.v1.IBulkDeleteDocumentsResponse, + protos.google.firestore.admin.v1.IBulkDeleteDocumentsMetadata + >, + protos.google.longrunning.IOperation | null | undefined, + {} | null | undefined + > + ): void; bulkDeleteDocuments( - request?: protos.google.firestore.admin.v1.IBulkDeleteDocumentsRequest, - optionsOrCallback?: CallOptions|Callback< - LROperation, - protos.google.longrunning.IOperation|null|undefined, - {}|null|undefined>, - callback?: Callback< - LROperation, - protos.google.longrunning.IOperation|null|undefined, - {}|null|undefined>): - Promise<[ - LROperation, - protos.google.longrunning.IOperation|undefined, {}|undefined - ]>|void { + request?: protos.google.firestore.admin.v1.IBulkDeleteDocumentsRequest, + optionsOrCallback?: + | CallOptions + | Callback< + LROperation< + protos.google.firestore.admin.v1.IBulkDeleteDocumentsResponse, + protos.google.firestore.admin.v1.IBulkDeleteDocumentsMetadata + >, + protos.google.longrunning.IOperation | null | undefined, + {} | null | undefined + >, + callback?: Callback< + LROperation< + protos.google.firestore.admin.v1.IBulkDeleteDocumentsResponse, + protos.google.firestore.admin.v1.IBulkDeleteDocumentsMetadata + >, + protos.google.longrunning.IOperation | null | undefined, + {} | null | undefined + > + ): Promise< + [ + LROperation< + protos.google.firestore.admin.v1.IBulkDeleteDocumentsResponse, + protos.google.firestore.admin.v1.IBulkDeleteDocumentsMetadata + >, + protos.google.longrunning.IOperation | undefined, + {} | undefined, + ] + > | void { request = request || {}; let options: CallOptions; if (typeof optionsOrCallback === 'function' && callback === undefined) { callback = optionsOrCallback; options = {}; - } - else { + } else { options = optionsOrCallback as CallOptions; } options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - options.otherArgs.headers[ - 'x-goog-request-params' - ] = this._gaxModule.routingHeader.fromParams({ - 'name': request.name ?? '', + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + name: request.name ?? '', + }); + this.initialize().catch(err => { + throw err; }); - this.initialize().catch(err => {throw err}); - const wrappedCallback: Callback< - LROperation, - protos.google.longrunning.IOperation|null|undefined, - {}|null|undefined>|undefined = callback + const wrappedCallback: + | Callback< + LROperation< + protos.google.firestore.admin.v1.IBulkDeleteDocumentsResponse, + protos.google.firestore.admin.v1.IBulkDeleteDocumentsMetadata + >, + protos.google.longrunning.IOperation | null | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, rawResponse, _) => { this._log.info('bulkDeleteDocuments response %j', rawResponse); callback!(error, response, rawResponse, _); // We verified callback above. } : undefined; this._log.info('bulkDeleteDocuments request %j', request); - return this.innerApiCalls.bulkDeleteDocuments(request, options, wrappedCallback) - ?.then(([response, rawResponse, _]: [ - LROperation, - protos.google.longrunning.IOperation|undefined, {}|undefined - ]) => { - this._log.info('bulkDeleteDocuments response %j', rawResponse); - return [response, rawResponse, _]; - }); + return this.innerApiCalls + .bulkDeleteDocuments(request, options, wrappedCallback) + ?.then( + ([response, rawResponse, _]: [ + LROperation< + protos.google.firestore.admin.v1.IBulkDeleteDocumentsResponse, + protos.google.firestore.admin.v1.IBulkDeleteDocumentsMetadata + >, + protos.google.longrunning.IOperation | undefined, + {} | undefined, + ]) => { + this._log.info('bulkDeleteDocuments response %j', rawResponse); + return [response, rawResponse, _]; + } + ); } -/** - * Check the status of the long running operation returned by `bulkDeleteDocuments()`. - * @param {String} name - * The operation name that will be passed. - * @returns {Promise} - The promise which resolves to an object. - * The decoded operation object has result and metadata field to get information from. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#long-running-operations | documentation } - * for more details and examples. - * @example - * region_tag:firestore_v1_generated_FirestoreAdmin_BulkDeleteDocuments_async - */ - async checkBulkDeleteDocumentsProgress(name: string): Promise>{ + /** + * Check the status of the long running operation returned by `bulkDeleteDocuments()`. + * @param {String} name + * The operation name that will be passed. + * @returns {Promise} - The promise which resolves to an object. + * The decoded operation object has result and metadata field to get information from. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#long-running-operations | documentation } + * for more details and examples. + * @example + * region_tag:firestore_v1_generated_FirestoreAdmin_BulkDeleteDocuments_async + */ + async checkBulkDeleteDocumentsProgress( + name: string + ): Promise< + LROperation< + protos.google.firestore.admin.v1.BulkDeleteDocumentsResponse, + protos.google.firestore.admin.v1.BulkDeleteDocumentsMetadata + > + > { this._log.info('bulkDeleteDocuments long-running'); - const request = new this._gaxModule.operationsProtos.google.longrunning.GetOperationRequest({name}); + const request = + new this._gaxModule.operationsProtos.google.longrunning.GetOperationRequest( + {name} + ); const [operation] = await this.operationsClient.getOperation(request); - const decodeOperation = new this._gaxModule.Operation(operation, this.descriptors.longrunning.bulkDeleteDocuments, this._gaxModule.createDefaultBackoffSettings()); - return decodeOperation as LROperation; + const decodeOperation = new this._gaxModule.Operation( + operation, + this.descriptors.longrunning.bulkDeleteDocuments, + this._gaxModule.createDefaultBackoffSettings() + ); + return decodeOperation as LROperation< + protos.google.firestore.admin.v1.BulkDeleteDocumentsResponse, + protos.google.firestore.admin.v1.BulkDeleteDocumentsMetadata + >; } -/** - * Create a database. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.parent - * Required. A parent name of the form - * `projects/{project_id}` - * @param {google.firestore.admin.v1.Database} request.database - * Required. The Database to create. - * @param {string} request.databaseId - * Required. The ID to use for the database, which will become the final - * component of the database's resource name. - * - * This value should be 4-63 characters. Valid characters are /{@link protos.0-9|a-z}-/ - * with first character a letter and the last a letter or a number. Must not - * be UUID-like /[0-9a-f]{8}(-[0-9a-f]{4}){3}-[0-9a-f]{12}/. - * - * "(default)" database ID is also valid. - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Promise} - The promise which resolves to an array. - * The first element of the array is an object representing - * a long running operation. Its `promise()` method returns a promise - * you can `await` for. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#long-running-operations | documentation } - * for more details and examples. - * @example - * region_tag:firestore_v1_generated_FirestoreAdmin_CreateDatabase_async - */ + /** + * Create a database. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.parent + * Required. A parent name of the form + * `projects/{project_id}` + * @param {google.firestore.admin.v1.Database} request.database + * Required. The Database to create. + * @param {string} request.databaseId + * Required. The ID to use for the database, which will become the final + * component of the database's resource name. + * + * This value should be 4-63 characters. Valid characters are /{@link protos.0-9|a-z}-/ + * with first character a letter and the last a letter or a number. Must not + * be UUID-like /[0-9a-f]{8}(-[0-9a-f]{4}){3}-[0-9a-f]{12}/. + * + * "(default)" database ID is also valid. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is an object representing + * a long running operation. Its `promise()` method returns a promise + * you can `await` for. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#long-running-operations | documentation } + * for more details and examples. + * @example + * region_tag:firestore_v1_generated_FirestoreAdmin_CreateDatabase_async + */ createDatabase( - request?: protos.google.firestore.admin.v1.ICreateDatabaseRequest, - options?: CallOptions): - Promise<[ - LROperation, - protos.google.longrunning.IOperation|undefined, {}|undefined - ]>; + request?: protos.google.firestore.admin.v1.ICreateDatabaseRequest, + options?: CallOptions + ): Promise< + [ + LROperation< + protos.google.firestore.admin.v1.IDatabase, + protos.google.firestore.admin.v1.ICreateDatabaseMetadata + >, + protos.google.longrunning.IOperation | undefined, + {} | undefined, + ] + >; createDatabase( - request: protos.google.firestore.admin.v1.ICreateDatabaseRequest, - options: CallOptions, - callback: Callback< - LROperation, - protos.google.longrunning.IOperation|null|undefined, - {}|null|undefined>): void; + request: protos.google.firestore.admin.v1.ICreateDatabaseRequest, + options: CallOptions, + callback: Callback< + LROperation< + protos.google.firestore.admin.v1.IDatabase, + protos.google.firestore.admin.v1.ICreateDatabaseMetadata + >, + protos.google.longrunning.IOperation | null | undefined, + {} | null | undefined + > + ): void; createDatabase( - request: protos.google.firestore.admin.v1.ICreateDatabaseRequest, - callback: Callback< - LROperation, - protos.google.longrunning.IOperation|null|undefined, - {}|null|undefined>): void; + request: protos.google.firestore.admin.v1.ICreateDatabaseRequest, + callback: Callback< + LROperation< + protos.google.firestore.admin.v1.IDatabase, + protos.google.firestore.admin.v1.ICreateDatabaseMetadata + >, + protos.google.longrunning.IOperation | null | undefined, + {} | null | undefined + > + ): void; createDatabase( - request?: protos.google.firestore.admin.v1.ICreateDatabaseRequest, - optionsOrCallback?: CallOptions|Callback< - LROperation, - protos.google.longrunning.IOperation|null|undefined, - {}|null|undefined>, - callback?: Callback< - LROperation, - protos.google.longrunning.IOperation|null|undefined, - {}|null|undefined>): - Promise<[ - LROperation, - protos.google.longrunning.IOperation|undefined, {}|undefined - ]>|void { + request?: protos.google.firestore.admin.v1.ICreateDatabaseRequest, + optionsOrCallback?: + | CallOptions + | Callback< + LROperation< + protos.google.firestore.admin.v1.IDatabase, + protos.google.firestore.admin.v1.ICreateDatabaseMetadata + >, + protos.google.longrunning.IOperation | null | undefined, + {} | null | undefined + >, + callback?: Callback< + LROperation< + protos.google.firestore.admin.v1.IDatabase, + protos.google.firestore.admin.v1.ICreateDatabaseMetadata + >, + protos.google.longrunning.IOperation | null | undefined, + {} | null | undefined + > + ): Promise< + [ + LROperation< + protos.google.firestore.admin.v1.IDatabase, + protos.google.firestore.admin.v1.ICreateDatabaseMetadata + >, + protos.google.longrunning.IOperation | undefined, + {} | undefined, + ] + > | void { request = request || {}; let options: CallOptions; if (typeof optionsOrCallback === 'function' && callback === undefined) { callback = optionsOrCallback; options = {}; - } - else { + } else { options = optionsOrCallback as CallOptions; } options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - options.otherArgs.headers[ - 'x-goog-request-params' - ] = this._gaxModule.routingHeader.fromParams({ - 'parent': request.parent ?? '', + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + parent: request.parent ?? '', + }); + this.initialize().catch(err => { + throw err; }); - this.initialize().catch(err => {throw err}); - const wrappedCallback: Callback< - LROperation, - protos.google.longrunning.IOperation|null|undefined, - {}|null|undefined>|undefined = callback + const wrappedCallback: + | Callback< + LROperation< + protos.google.firestore.admin.v1.IDatabase, + protos.google.firestore.admin.v1.ICreateDatabaseMetadata + >, + protos.google.longrunning.IOperation | null | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, rawResponse, _) => { this._log.info('createDatabase response %j', rawResponse); callback!(error, response, rawResponse, _); // We verified callback above. } : undefined; this._log.info('createDatabase request %j', request); - return this.innerApiCalls.createDatabase(request, options, wrappedCallback) - ?.then(([response, rawResponse, _]: [ - LROperation, - protos.google.longrunning.IOperation|undefined, {}|undefined - ]) => { - this._log.info('createDatabase response %j', rawResponse); - return [response, rawResponse, _]; - }); + return this.innerApiCalls + .createDatabase(request, options, wrappedCallback) + ?.then( + ([response, rawResponse, _]: [ + LROperation< + protos.google.firestore.admin.v1.IDatabase, + protos.google.firestore.admin.v1.ICreateDatabaseMetadata + >, + protos.google.longrunning.IOperation | undefined, + {} | undefined, + ]) => { + this._log.info('createDatabase response %j', rawResponse); + return [response, rawResponse, _]; + } + ); } -/** - * Check the status of the long running operation returned by `createDatabase()`. - * @param {String} name - * The operation name that will be passed. - * @returns {Promise} - The promise which resolves to an object. - * The decoded operation object has result and metadata field to get information from. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#long-running-operations | documentation } - * for more details and examples. - * @example - * region_tag:firestore_v1_generated_FirestoreAdmin_CreateDatabase_async - */ - async checkCreateDatabaseProgress(name: string): Promise>{ + /** + * Check the status of the long running operation returned by `createDatabase()`. + * @param {String} name + * The operation name that will be passed. + * @returns {Promise} - The promise which resolves to an object. + * The decoded operation object has result and metadata field to get information from. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#long-running-operations | documentation } + * for more details and examples. + * @example + * region_tag:firestore_v1_generated_FirestoreAdmin_CreateDatabase_async + */ + async checkCreateDatabaseProgress( + name: string + ): Promise< + LROperation< + protos.google.firestore.admin.v1.Database, + protos.google.firestore.admin.v1.CreateDatabaseMetadata + > + > { this._log.info('createDatabase long-running'); - const request = new this._gaxModule.operationsProtos.google.longrunning.GetOperationRequest({name}); + const request = + new this._gaxModule.operationsProtos.google.longrunning.GetOperationRequest( + {name} + ); const [operation] = await this.operationsClient.getOperation(request); - const decodeOperation = new this._gaxModule.Operation(operation, this.descriptors.longrunning.createDatabase, this._gaxModule.createDefaultBackoffSettings()); - return decodeOperation as LROperation; + const decodeOperation = new this._gaxModule.Operation( + operation, + this.descriptors.longrunning.createDatabase, + this._gaxModule.createDefaultBackoffSettings() + ); + return decodeOperation as LROperation< + protos.google.firestore.admin.v1.Database, + protos.google.firestore.admin.v1.CreateDatabaseMetadata + >; } -/** - * Updates a database. - * - * @param {Object} request - * The request object that will be sent. - * @param {google.firestore.admin.v1.Database} request.database - * Required. The database to update. - * @param {google.protobuf.FieldMask} request.updateMask - * The list of fields to be updated. - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Promise} - The promise which resolves to an array. - * The first element of the array is an object representing - * a long running operation. Its `promise()` method returns a promise - * you can `await` for. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#long-running-operations | documentation } - * for more details and examples. - * @example - * region_tag:firestore_v1_generated_FirestoreAdmin_UpdateDatabase_async - */ + /** + * Updates a database. + * + * @param {Object} request + * The request object that will be sent. + * @param {google.firestore.admin.v1.Database} request.database + * Required. The database to update. + * @param {google.protobuf.FieldMask} request.updateMask + * The list of fields to be updated. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is an object representing + * a long running operation. Its `promise()` method returns a promise + * you can `await` for. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#long-running-operations | documentation } + * for more details and examples. + * @example + * region_tag:firestore_v1_generated_FirestoreAdmin_UpdateDatabase_async + */ updateDatabase( - request?: protos.google.firestore.admin.v1.IUpdateDatabaseRequest, - options?: CallOptions): - Promise<[ - LROperation, - protos.google.longrunning.IOperation|undefined, {}|undefined - ]>; + request?: protos.google.firestore.admin.v1.IUpdateDatabaseRequest, + options?: CallOptions + ): Promise< + [ + LROperation< + protos.google.firestore.admin.v1.IDatabase, + protos.google.firestore.admin.v1.IUpdateDatabaseMetadata + >, + protos.google.longrunning.IOperation | undefined, + {} | undefined, + ] + >; updateDatabase( - request: protos.google.firestore.admin.v1.IUpdateDatabaseRequest, - options: CallOptions, - callback: Callback< - LROperation, - protos.google.longrunning.IOperation|null|undefined, - {}|null|undefined>): void; + request: protos.google.firestore.admin.v1.IUpdateDatabaseRequest, + options: CallOptions, + callback: Callback< + LROperation< + protos.google.firestore.admin.v1.IDatabase, + protos.google.firestore.admin.v1.IUpdateDatabaseMetadata + >, + protos.google.longrunning.IOperation | null | undefined, + {} | null | undefined + > + ): void; updateDatabase( - request: protos.google.firestore.admin.v1.IUpdateDatabaseRequest, - callback: Callback< - LROperation, - protos.google.longrunning.IOperation|null|undefined, - {}|null|undefined>): void; + request: protos.google.firestore.admin.v1.IUpdateDatabaseRequest, + callback: Callback< + LROperation< + protos.google.firestore.admin.v1.IDatabase, + protos.google.firestore.admin.v1.IUpdateDatabaseMetadata + >, + protos.google.longrunning.IOperation | null | undefined, + {} | null | undefined + > + ): void; updateDatabase( - request?: protos.google.firestore.admin.v1.IUpdateDatabaseRequest, - optionsOrCallback?: CallOptions|Callback< - LROperation, - protos.google.longrunning.IOperation|null|undefined, - {}|null|undefined>, - callback?: Callback< - LROperation, - protos.google.longrunning.IOperation|null|undefined, - {}|null|undefined>): - Promise<[ - LROperation, - protos.google.longrunning.IOperation|undefined, {}|undefined - ]>|void { + request?: protos.google.firestore.admin.v1.IUpdateDatabaseRequest, + optionsOrCallback?: + | CallOptions + | Callback< + LROperation< + protos.google.firestore.admin.v1.IDatabase, + protos.google.firestore.admin.v1.IUpdateDatabaseMetadata + >, + protos.google.longrunning.IOperation | null | undefined, + {} | null | undefined + >, + callback?: Callback< + LROperation< + protos.google.firestore.admin.v1.IDatabase, + protos.google.firestore.admin.v1.IUpdateDatabaseMetadata + >, + protos.google.longrunning.IOperation | null | undefined, + {} | null | undefined + > + ): Promise< + [ + LROperation< + protos.google.firestore.admin.v1.IDatabase, + protos.google.firestore.admin.v1.IUpdateDatabaseMetadata + >, + protos.google.longrunning.IOperation | undefined, + {} | undefined, + ] + > | void { request = request || {}; let options: CallOptions; if (typeof optionsOrCallback === 'function' && callback === undefined) { callback = optionsOrCallback; options = {}; - } - else { + } else { options = optionsOrCallback as CallOptions; } options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - options.otherArgs.headers[ - 'x-goog-request-params' - ] = this._gaxModule.routingHeader.fromParams({ - 'database.name': request.database!.name ?? '', + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + 'database.name': request.database!.name ?? '', + }); + this.initialize().catch(err => { + throw err; }); - this.initialize().catch(err => {throw err}); - const wrappedCallback: Callback< - LROperation, - protos.google.longrunning.IOperation|null|undefined, - {}|null|undefined>|undefined = callback + const wrappedCallback: + | Callback< + LROperation< + protos.google.firestore.admin.v1.IDatabase, + protos.google.firestore.admin.v1.IUpdateDatabaseMetadata + >, + protos.google.longrunning.IOperation | null | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, rawResponse, _) => { this._log.info('updateDatabase response %j', rawResponse); callback!(error, response, rawResponse, _); // We verified callback above. } : undefined; this._log.info('updateDatabase request %j', request); - return this.innerApiCalls.updateDatabase(request, options, wrappedCallback) - ?.then(([response, rawResponse, _]: [ - LROperation, - protos.google.longrunning.IOperation|undefined, {}|undefined - ]) => { - this._log.info('updateDatabase response %j', rawResponse); - return [response, rawResponse, _]; - }); + return this.innerApiCalls + .updateDatabase(request, options, wrappedCallback) + ?.then( + ([response, rawResponse, _]: [ + LROperation< + protos.google.firestore.admin.v1.IDatabase, + protos.google.firestore.admin.v1.IUpdateDatabaseMetadata + >, + protos.google.longrunning.IOperation | undefined, + {} | undefined, + ]) => { + this._log.info('updateDatabase response %j', rawResponse); + return [response, rawResponse, _]; + } + ); } -/** - * Check the status of the long running operation returned by `updateDatabase()`. - * @param {String} name - * The operation name that will be passed. - * @returns {Promise} - The promise which resolves to an object. - * The decoded operation object has result and metadata field to get information from. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#long-running-operations | documentation } - * for more details and examples. - * @example - * region_tag:firestore_v1_generated_FirestoreAdmin_UpdateDatabase_async - */ - async checkUpdateDatabaseProgress(name: string): Promise>{ + /** + * Check the status of the long running operation returned by `updateDatabase()`. + * @param {String} name + * The operation name that will be passed. + * @returns {Promise} - The promise which resolves to an object. + * The decoded operation object has result and metadata field to get information from. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#long-running-operations | documentation } + * for more details and examples. + * @example + * region_tag:firestore_v1_generated_FirestoreAdmin_UpdateDatabase_async + */ + async checkUpdateDatabaseProgress( + name: string + ): Promise< + LROperation< + protos.google.firestore.admin.v1.Database, + protos.google.firestore.admin.v1.UpdateDatabaseMetadata + > + > { this._log.info('updateDatabase long-running'); - const request = new this._gaxModule.operationsProtos.google.longrunning.GetOperationRequest({name}); + const request = + new this._gaxModule.operationsProtos.google.longrunning.GetOperationRequest( + {name} + ); const [operation] = await this.operationsClient.getOperation(request); - const decodeOperation = new this._gaxModule.Operation(operation, this.descriptors.longrunning.updateDatabase, this._gaxModule.createDefaultBackoffSettings()); - return decodeOperation as LROperation; + const decodeOperation = new this._gaxModule.Operation( + operation, + this.descriptors.longrunning.updateDatabase, + this._gaxModule.createDefaultBackoffSettings() + ); + return decodeOperation as LROperation< + protos.google.firestore.admin.v1.Database, + protos.google.firestore.admin.v1.UpdateDatabaseMetadata + >; } -/** - * Deletes a database. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.name - * Required. A name of the form - * `projects/{project_id}/databases/{database_id}` - * @param {string} request.etag - * The current etag of the Database. - * If an etag is provided and does not match the current etag of the database, - * deletion will be blocked and a FAILED_PRECONDITION error will be returned. - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Promise} - The promise which resolves to an array. - * The first element of the array is an object representing - * a long running operation. Its `promise()` method returns a promise - * you can `await` for. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#long-running-operations | documentation } - * for more details and examples. - * @example - * region_tag:firestore_v1_generated_FirestoreAdmin_DeleteDatabase_async - */ + /** + * Deletes a database. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.name + * Required. A name of the form + * `projects/{project_id}/databases/{database_id}` + * @param {string} request.etag + * The current etag of the Database. + * If an etag is provided and does not match the current etag of the database, + * deletion will be blocked and a FAILED_PRECONDITION error will be returned. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is an object representing + * a long running operation. Its `promise()` method returns a promise + * you can `await` for. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#long-running-operations | documentation } + * for more details and examples. + * @example + * region_tag:firestore_v1_generated_FirestoreAdmin_DeleteDatabase_async + */ deleteDatabase( - request?: protos.google.firestore.admin.v1.IDeleteDatabaseRequest, - options?: CallOptions): - Promise<[ - LROperation, - protos.google.longrunning.IOperation|undefined, {}|undefined - ]>; + request?: protos.google.firestore.admin.v1.IDeleteDatabaseRequest, + options?: CallOptions + ): Promise< + [ + LROperation< + protos.google.firestore.admin.v1.IDatabase, + protos.google.firestore.admin.v1.IDeleteDatabaseMetadata + >, + protos.google.longrunning.IOperation | undefined, + {} | undefined, + ] + >; deleteDatabase( - request: protos.google.firestore.admin.v1.IDeleteDatabaseRequest, - options: CallOptions, - callback: Callback< - LROperation, - protos.google.longrunning.IOperation|null|undefined, - {}|null|undefined>): void; + request: protos.google.firestore.admin.v1.IDeleteDatabaseRequest, + options: CallOptions, + callback: Callback< + LROperation< + protos.google.firestore.admin.v1.IDatabase, + protos.google.firestore.admin.v1.IDeleteDatabaseMetadata + >, + protos.google.longrunning.IOperation | null | undefined, + {} | null | undefined + > + ): void; deleteDatabase( - request: protos.google.firestore.admin.v1.IDeleteDatabaseRequest, - callback: Callback< - LROperation, - protos.google.longrunning.IOperation|null|undefined, - {}|null|undefined>): void; + request: protos.google.firestore.admin.v1.IDeleteDatabaseRequest, + callback: Callback< + LROperation< + protos.google.firestore.admin.v1.IDatabase, + protos.google.firestore.admin.v1.IDeleteDatabaseMetadata + >, + protos.google.longrunning.IOperation | null | undefined, + {} | null | undefined + > + ): void; deleteDatabase( - request?: protos.google.firestore.admin.v1.IDeleteDatabaseRequest, - optionsOrCallback?: CallOptions|Callback< - LROperation, - protos.google.longrunning.IOperation|null|undefined, - {}|null|undefined>, - callback?: Callback< - LROperation, - protos.google.longrunning.IOperation|null|undefined, - {}|null|undefined>): - Promise<[ - LROperation, - protos.google.longrunning.IOperation|undefined, {}|undefined - ]>|void { + request?: protos.google.firestore.admin.v1.IDeleteDatabaseRequest, + optionsOrCallback?: + | CallOptions + | Callback< + LROperation< + protos.google.firestore.admin.v1.IDatabase, + protos.google.firestore.admin.v1.IDeleteDatabaseMetadata + >, + protos.google.longrunning.IOperation | null | undefined, + {} | null | undefined + >, + callback?: Callback< + LROperation< + protos.google.firestore.admin.v1.IDatabase, + protos.google.firestore.admin.v1.IDeleteDatabaseMetadata + >, + protos.google.longrunning.IOperation | null | undefined, + {} | null | undefined + > + ): Promise< + [ + LROperation< + protos.google.firestore.admin.v1.IDatabase, + protos.google.firestore.admin.v1.IDeleteDatabaseMetadata + >, + protos.google.longrunning.IOperation | undefined, + {} | undefined, + ] + > | void { request = request || {}; let options: CallOptions; if (typeof optionsOrCallback === 'function' && callback === undefined) { callback = optionsOrCallback; options = {}; - } - else { + } else { options = optionsOrCallback as CallOptions; } options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - options.otherArgs.headers[ - 'x-goog-request-params' - ] = this._gaxModule.routingHeader.fromParams({ - 'name': request.name ?? '', + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + name: request.name ?? '', + }); + this.initialize().catch(err => { + throw err; }); - this.initialize().catch(err => {throw err}); - const wrappedCallback: Callback< - LROperation, - protos.google.longrunning.IOperation|null|undefined, - {}|null|undefined>|undefined = callback + const wrappedCallback: + | Callback< + LROperation< + protos.google.firestore.admin.v1.IDatabase, + protos.google.firestore.admin.v1.IDeleteDatabaseMetadata + >, + protos.google.longrunning.IOperation | null | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, rawResponse, _) => { this._log.info('deleteDatabase response %j', rawResponse); callback!(error, response, rawResponse, _); // We verified callback above. } : undefined; this._log.info('deleteDatabase request %j', request); - return this.innerApiCalls.deleteDatabase(request, options, wrappedCallback) - ?.then(([response, rawResponse, _]: [ - LROperation, - protos.google.longrunning.IOperation|undefined, {}|undefined - ]) => { - this._log.info('deleteDatabase response %j', rawResponse); - return [response, rawResponse, _]; - }); + return this.innerApiCalls + .deleteDatabase(request, options, wrappedCallback) + ?.then( + ([response, rawResponse, _]: [ + LROperation< + protos.google.firestore.admin.v1.IDatabase, + protos.google.firestore.admin.v1.IDeleteDatabaseMetadata + >, + protos.google.longrunning.IOperation | undefined, + {} | undefined, + ]) => { + this._log.info('deleteDatabase response %j', rawResponse); + return [response, rawResponse, _]; + } + ); } -/** - * Check the status of the long running operation returned by `deleteDatabase()`. - * @param {String} name - * The operation name that will be passed. - * @returns {Promise} - The promise which resolves to an object. - * The decoded operation object has result and metadata field to get information from. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#long-running-operations | documentation } - * for more details and examples. - * @example - * region_tag:firestore_v1_generated_FirestoreAdmin_DeleteDatabase_async - */ - async checkDeleteDatabaseProgress(name: string): Promise>{ + /** + * Check the status of the long running operation returned by `deleteDatabase()`. + * @param {String} name + * The operation name that will be passed. + * @returns {Promise} - The promise which resolves to an object. + * The decoded operation object has result and metadata field to get information from. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#long-running-operations | documentation } + * for more details and examples. + * @example + * region_tag:firestore_v1_generated_FirestoreAdmin_DeleteDatabase_async + */ + async checkDeleteDatabaseProgress( + name: string + ): Promise< + LROperation< + protos.google.firestore.admin.v1.Database, + protos.google.firestore.admin.v1.DeleteDatabaseMetadata + > + > { this._log.info('deleteDatabase long-running'); - const request = new this._gaxModule.operationsProtos.google.longrunning.GetOperationRequest({name}); - const [operation] = await this.operationsClient.getOperation(request); - const decodeOperation = new this._gaxModule.Operation(operation, this.descriptors.longrunning.deleteDatabase, this._gaxModule.createDefaultBackoffSettings()); - return decodeOperation as LROperation; - } -/** - * Creates a new database by restoring from an existing backup. - * - * The new database must be in the same cloud region or multi-region location - * as the existing backup. This behaves similar to - * {@link protos.google.firestore.admin.v1.FirestoreAdmin.CreateDatabase|FirestoreAdmin.CreateDatabase} - * except instead of creating a new empty database, a new database is created - * with the database type, index configuration, and documents from an existing - * backup. - * - * The {@link protos.google.longrunning.Operation|long-running operation} can be used to - * track the progress of the restore, with the Operation's - * {@link protos.google.longrunning.Operation.metadata|metadata} field type being the - * {@link protos.google.firestore.admin.v1.RestoreDatabaseMetadata|RestoreDatabaseMetadata}. - * The {@link protos.google.longrunning.Operation.response|response} type is the - * {@link protos.google.firestore.admin.v1.Database|Database} if the restore was - * successful. The new database is not readable or writeable until the LRO has - * completed. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.parent - * Required. The project to restore the database in. Format is - * `projects/{project_id}`. - * @param {string} request.databaseId - * Required. The ID to use for the database, which will become the final - * component of the database's resource name. This database ID must not be - * associated with an existing database. - * - * This value should be 4-63 characters. Valid characters are /{@link protos.0-9|a-z}-/ - * with first character a letter and the last a letter or a number. Must not - * be UUID-like /[0-9a-f]{8}(-[0-9a-f]{4}){3}-[0-9a-f]{12}/. - * - * "(default)" database ID is also valid. - * @param {string} request.backup - * Required. Backup to restore from. Must be from the same project as the - * parent. - * - * The restored database will be created in the same location as the source - * backup. - * - * Format is: `projects/{project_id}/locations/{location}/backups/{backup}` - * @param {google.firestore.admin.v1.Database.EncryptionConfig} [request.encryptionConfig] - * Optional. Encryption configuration for the restored database. - * - * If this field is not specified, the restored database will use - * the same encryption configuration as the backup, namely - * {@link protos.google.firestore.admin.v1.Database.EncryptionConfig.use_source_encryption|use_source_encryption}. - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Promise} - The promise which resolves to an array. - * The first element of the array is an object representing - * a long running operation. Its `promise()` method returns a promise - * you can `await` for. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#long-running-operations | documentation } - * for more details and examples. - * @example - * region_tag:firestore_v1_generated_FirestoreAdmin_RestoreDatabase_async - */ + const request = + new this._gaxModule.operationsProtos.google.longrunning.GetOperationRequest( + {name} + ); + const [operation] = await this.operationsClient.getOperation(request); + const decodeOperation = new this._gaxModule.Operation( + operation, + this.descriptors.longrunning.deleteDatabase, + this._gaxModule.createDefaultBackoffSettings() + ); + return decodeOperation as LROperation< + protos.google.firestore.admin.v1.Database, + protos.google.firestore.admin.v1.DeleteDatabaseMetadata + >; + } + /** + * Creates a new database by restoring from an existing backup. + * + * The new database must be in the same cloud region or multi-region location + * as the existing backup. This behaves similar to + * {@link protos.google.firestore.admin.v1.FirestoreAdmin.CreateDatabase|FirestoreAdmin.CreateDatabase} + * except instead of creating a new empty database, a new database is created + * with the database type, index configuration, and documents from an existing + * backup. + * + * The {@link protos.google.longrunning.Operation|long-running operation} can be used to + * track the progress of the restore, with the Operation's + * {@link protos.google.longrunning.Operation.metadata|metadata} field type being the + * {@link protos.google.firestore.admin.v1.RestoreDatabaseMetadata|RestoreDatabaseMetadata}. + * The {@link protos.google.longrunning.Operation.response|response} type is the + * {@link protos.google.firestore.admin.v1.Database|Database} if the restore was + * successful. The new database is not readable or writeable until the LRO has + * completed. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.parent + * Required. The project to restore the database in. Format is + * `projects/{project_id}`. + * @param {string} request.databaseId + * Required. The ID to use for the database, which will become the final + * component of the database's resource name. This database ID must not be + * associated with an existing database. + * + * This value should be 4-63 characters. Valid characters are /{@link protos.0-9|a-z}-/ + * with first character a letter and the last a letter or a number. Must not + * be UUID-like /[0-9a-f]{8}(-[0-9a-f]{4}){3}-[0-9a-f]{12}/. + * + * "(default)" database ID is also valid. + * @param {string} request.backup + * Required. Backup to restore from. Must be from the same project as the + * parent. + * + * The restored database will be created in the same location as the source + * backup. + * + * Format is: `projects/{project_id}/locations/{location}/backups/{backup}` + * @param {google.firestore.admin.v1.Database.EncryptionConfig} [request.encryptionConfig] + * Optional. Encryption configuration for the restored database. + * + * If this field is not specified, the restored database will use + * the same encryption configuration as the backup, namely + * {@link protos.google.firestore.admin.v1.Database.EncryptionConfig.use_source_encryption|use_source_encryption}. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is an object representing + * a long running operation. Its `promise()` method returns a promise + * you can `await` for. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#long-running-operations | documentation } + * for more details and examples. + * @example + * region_tag:firestore_v1_generated_FirestoreAdmin_RestoreDatabase_async + */ restoreDatabase( - request?: protos.google.firestore.admin.v1.IRestoreDatabaseRequest, - options?: CallOptions): - Promise<[ - LROperation, - protos.google.longrunning.IOperation|undefined, {}|undefined - ]>; + request?: protos.google.firestore.admin.v1.IRestoreDatabaseRequest, + options?: CallOptions + ): Promise< + [ + LROperation< + protos.google.firestore.admin.v1.IDatabase, + protos.google.firestore.admin.v1.IRestoreDatabaseMetadata + >, + protos.google.longrunning.IOperation | undefined, + {} | undefined, + ] + >; restoreDatabase( - request: protos.google.firestore.admin.v1.IRestoreDatabaseRequest, - options: CallOptions, - callback: Callback< - LROperation, - protos.google.longrunning.IOperation|null|undefined, - {}|null|undefined>): void; + request: protos.google.firestore.admin.v1.IRestoreDatabaseRequest, + options: CallOptions, + callback: Callback< + LROperation< + protos.google.firestore.admin.v1.IDatabase, + protos.google.firestore.admin.v1.IRestoreDatabaseMetadata + >, + protos.google.longrunning.IOperation | null | undefined, + {} | null | undefined + > + ): void; restoreDatabase( - request: protos.google.firestore.admin.v1.IRestoreDatabaseRequest, - callback: Callback< - LROperation, - protos.google.longrunning.IOperation|null|undefined, - {}|null|undefined>): void; + request: protos.google.firestore.admin.v1.IRestoreDatabaseRequest, + callback: Callback< + LROperation< + protos.google.firestore.admin.v1.IDatabase, + protos.google.firestore.admin.v1.IRestoreDatabaseMetadata + >, + protos.google.longrunning.IOperation | null | undefined, + {} | null | undefined + > + ): void; restoreDatabase( - request?: protos.google.firestore.admin.v1.IRestoreDatabaseRequest, - optionsOrCallback?: CallOptions|Callback< - LROperation, - protos.google.longrunning.IOperation|null|undefined, - {}|null|undefined>, - callback?: Callback< - LROperation, - protos.google.longrunning.IOperation|null|undefined, - {}|null|undefined>): - Promise<[ - LROperation, - protos.google.longrunning.IOperation|undefined, {}|undefined - ]>|void { + request?: protos.google.firestore.admin.v1.IRestoreDatabaseRequest, + optionsOrCallback?: + | CallOptions + | Callback< + LROperation< + protos.google.firestore.admin.v1.IDatabase, + protos.google.firestore.admin.v1.IRestoreDatabaseMetadata + >, + protos.google.longrunning.IOperation | null | undefined, + {} | null | undefined + >, + callback?: Callback< + LROperation< + protos.google.firestore.admin.v1.IDatabase, + protos.google.firestore.admin.v1.IRestoreDatabaseMetadata + >, + protos.google.longrunning.IOperation | null | undefined, + {} | null | undefined + > + ): Promise< + [ + LROperation< + protos.google.firestore.admin.v1.IDatabase, + protos.google.firestore.admin.v1.IRestoreDatabaseMetadata + >, + protos.google.longrunning.IOperation | undefined, + {} | undefined, + ] + > | void { request = request || {}; let options: CallOptions; if (typeof optionsOrCallback === 'function' && callback === undefined) { callback = optionsOrCallback; options = {}; - } - else { + } else { options = optionsOrCallback as CallOptions; } options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - options.otherArgs.headers[ - 'x-goog-request-params' - ] = this._gaxModule.routingHeader.fromParams({ - 'parent': request.parent ?? '', + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + parent: request.parent ?? '', + }); + this.initialize().catch(err => { + throw err; }); - this.initialize().catch(err => {throw err}); - const wrappedCallback: Callback< - LROperation, - protos.google.longrunning.IOperation|null|undefined, - {}|null|undefined>|undefined = callback + const wrappedCallback: + | Callback< + LROperation< + protos.google.firestore.admin.v1.IDatabase, + protos.google.firestore.admin.v1.IRestoreDatabaseMetadata + >, + protos.google.longrunning.IOperation | null | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, rawResponse, _) => { this._log.info('restoreDatabase response %j', rawResponse); callback!(error, response, rawResponse, _); // We verified callback above. } : undefined; this._log.info('restoreDatabase request %j', request); - return this.innerApiCalls.restoreDatabase(request, options, wrappedCallback) - ?.then(([response, rawResponse, _]: [ - LROperation, - protos.google.longrunning.IOperation|undefined, {}|undefined - ]) => { - this._log.info('restoreDatabase response %j', rawResponse); - return [response, rawResponse, _]; - }); + return this.innerApiCalls + .restoreDatabase(request, options, wrappedCallback) + ?.then( + ([response, rawResponse, _]: [ + LROperation< + protos.google.firestore.admin.v1.IDatabase, + protos.google.firestore.admin.v1.IRestoreDatabaseMetadata + >, + protos.google.longrunning.IOperation | undefined, + {} | undefined, + ]) => { + this._log.info('restoreDatabase response %j', rawResponse); + return [response, rawResponse, _]; + } + ); } -/** - * Check the status of the long running operation returned by `restoreDatabase()`. - * @param {String} name - * The operation name that will be passed. - * @returns {Promise} - The promise which resolves to an object. - * The decoded operation object has result and metadata field to get information from. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#long-running-operations | documentation } - * for more details and examples. - * @example - * region_tag:firestore_v1_generated_FirestoreAdmin_RestoreDatabase_async - */ - async checkRestoreDatabaseProgress(name: string): Promise>{ + /** + * Check the status of the long running operation returned by `restoreDatabase()`. + * @param {String} name + * The operation name that will be passed. + * @returns {Promise} - The promise which resolves to an object. + * The decoded operation object has result and metadata field to get information from. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#long-running-operations | documentation } + * for more details and examples. + * @example + * region_tag:firestore_v1_generated_FirestoreAdmin_RestoreDatabase_async + */ + async checkRestoreDatabaseProgress( + name: string + ): Promise< + LROperation< + protos.google.firestore.admin.v1.Database, + protos.google.firestore.admin.v1.RestoreDatabaseMetadata + > + > { this._log.info('restoreDatabase long-running'); - const request = new this._gaxModule.operationsProtos.google.longrunning.GetOperationRequest({name}); + const request = + new this._gaxModule.operationsProtos.google.longrunning.GetOperationRequest( + {name} + ); const [operation] = await this.operationsClient.getOperation(request); - const decodeOperation = new this._gaxModule.Operation(operation, this.descriptors.longrunning.restoreDatabase, this._gaxModule.createDefaultBackoffSettings()); - return decodeOperation as LROperation; + const decodeOperation = new this._gaxModule.Operation( + operation, + this.descriptors.longrunning.restoreDatabase, + this._gaxModule.createDefaultBackoffSettings() + ); + return decodeOperation as LROperation< + protos.google.firestore.admin.v1.Database, + protos.google.firestore.admin.v1.RestoreDatabaseMetadata + >; } - /** - * Lists composite indexes. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.parent - * Required. A parent name of the form - * `projects/{project_id}/databases/{database_id}/collectionGroups/{collection_id}` - * @param {string} request.filter - * The filter to apply to list results. - * @param {number} request.pageSize - * The number of results to return. - * @param {string} request.pageToken - * A page token, returned from a previous call to - * {@link protos.google.firestore.admin.v1.FirestoreAdmin.ListIndexes|FirestoreAdmin.ListIndexes}, - * that may be used to get the next page of results. - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Promise} - The promise which resolves to an array. - * The first element of the array is Array of {@link protos.google.firestore.admin.v1.Index|Index}. - * The client library will perform auto-pagination by default: it will call the API as many - * times as needed and will merge results from all the pages into this array. - * Note that it can affect your quota. - * We recommend using `listIndexesAsync()` - * method described below for async iteration which you can stop as needed. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#auto-pagination | documentation } - * for more details and examples. - */ + /** + * Lists composite indexes. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.parent + * Required. A parent name of the form + * `projects/{project_id}/databases/{database_id}/collectionGroups/{collection_id}` + * @param {string} request.filter + * The filter to apply to list results. + * @param {number} request.pageSize + * The number of results to return. + * @param {string} request.pageToken + * A page token, returned from a previous call to + * {@link protos.google.firestore.admin.v1.FirestoreAdmin.ListIndexes|FirestoreAdmin.ListIndexes}, + * that may be used to get the next page of results. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is Array of {@link protos.google.firestore.admin.v1.Index|Index}. + * The client library will perform auto-pagination by default: it will call the API as many + * times as needed and will merge results from all the pages into this array. + * Note that it can affect your quota. + * We recommend using `listIndexesAsync()` + * method described below for async iteration which you can stop as needed. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#auto-pagination | documentation } + * for more details and examples. + */ listIndexes( - request?: protos.google.firestore.admin.v1.IListIndexesRequest, - options?: CallOptions): - Promise<[ - protos.google.firestore.admin.v1.IIndex[], - protos.google.firestore.admin.v1.IListIndexesRequest|null, - protos.google.firestore.admin.v1.IListIndexesResponse - ]>; + request?: protos.google.firestore.admin.v1.IListIndexesRequest, + options?: CallOptions + ): Promise< + [ + protos.google.firestore.admin.v1.IIndex[], + protos.google.firestore.admin.v1.IListIndexesRequest | null, + protos.google.firestore.admin.v1.IListIndexesResponse, + ] + >; listIndexes( - request: protos.google.firestore.admin.v1.IListIndexesRequest, - options: CallOptions, - callback: PaginationCallback< - protos.google.firestore.admin.v1.IListIndexesRequest, - protos.google.firestore.admin.v1.IListIndexesResponse|null|undefined, - protos.google.firestore.admin.v1.IIndex>): void; + request: protos.google.firestore.admin.v1.IListIndexesRequest, + options: CallOptions, + callback: PaginationCallback< + protos.google.firestore.admin.v1.IListIndexesRequest, + protos.google.firestore.admin.v1.IListIndexesResponse | null | undefined, + protos.google.firestore.admin.v1.IIndex + > + ): void; listIndexes( - request: protos.google.firestore.admin.v1.IListIndexesRequest, - callback: PaginationCallback< - protos.google.firestore.admin.v1.IListIndexesRequest, - protos.google.firestore.admin.v1.IListIndexesResponse|null|undefined, - protos.google.firestore.admin.v1.IIndex>): void; + request: protos.google.firestore.admin.v1.IListIndexesRequest, + callback: PaginationCallback< + protos.google.firestore.admin.v1.IListIndexesRequest, + protos.google.firestore.admin.v1.IListIndexesResponse | null | undefined, + protos.google.firestore.admin.v1.IIndex + > + ): void; listIndexes( - request?: protos.google.firestore.admin.v1.IListIndexesRequest, - optionsOrCallback?: CallOptions|PaginationCallback< - protos.google.firestore.admin.v1.IListIndexesRequest, - protos.google.firestore.admin.v1.IListIndexesResponse|null|undefined, - protos.google.firestore.admin.v1.IIndex>, - callback?: PaginationCallback< + request?: protos.google.firestore.admin.v1.IListIndexesRequest, + optionsOrCallback?: + | CallOptions + | PaginationCallback< protos.google.firestore.admin.v1.IListIndexesRequest, - protos.google.firestore.admin.v1.IListIndexesResponse|null|undefined, - protos.google.firestore.admin.v1.IIndex>): - Promise<[ - protos.google.firestore.admin.v1.IIndex[], - protos.google.firestore.admin.v1.IListIndexesRequest|null, - protos.google.firestore.admin.v1.IListIndexesResponse - ]>|void { + | protos.google.firestore.admin.v1.IListIndexesResponse + | null + | undefined, + protos.google.firestore.admin.v1.IIndex + >, + callback?: PaginationCallback< + protos.google.firestore.admin.v1.IListIndexesRequest, + protos.google.firestore.admin.v1.IListIndexesResponse | null | undefined, + protos.google.firestore.admin.v1.IIndex + > + ): Promise< + [ + protos.google.firestore.admin.v1.IIndex[], + protos.google.firestore.admin.v1.IListIndexesRequest | null, + protos.google.firestore.admin.v1.IListIndexesResponse, + ] + > | void { request = request || {}; let options: CallOptions; if (typeof optionsOrCallback === 'function' && callback === undefined) { callback = optionsOrCallback; options = {}; - } - else { + } else { options = optionsOrCallback as CallOptions; } options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - options.otherArgs.headers[ - 'x-goog-request-params' - ] = this._gaxModule.routingHeader.fromParams({ - 'parent': request.parent ?? '', + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + parent: request.parent ?? '', + }); + this.initialize().catch(err => { + throw err; }); - this.initialize().catch(err => {throw err}); - const wrappedCallback: PaginationCallback< - protos.google.firestore.admin.v1.IListIndexesRequest, - protos.google.firestore.admin.v1.IListIndexesResponse|null|undefined, - protos.google.firestore.admin.v1.IIndex>|undefined = callback + const wrappedCallback: + | PaginationCallback< + protos.google.firestore.admin.v1.IListIndexesRequest, + | protos.google.firestore.admin.v1.IListIndexesResponse + | null + | undefined, + protos.google.firestore.admin.v1.IIndex + > + | undefined = callback ? (error, values, nextPageRequest, rawResponse) => { this._log.info('listIndexes values %j', values); callback!(error, values, nextPageRequest, rawResponse); // We verified callback above. @@ -3536,58 +4793,61 @@ export class FirestoreAdminClient { this._log.info('listIndexes request %j', request); return this.innerApiCalls .listIndexes(request, options, wrappedCallback) - ?.then(([response, input, output]: [ - protos.google.firestore.admin.v1.IIndex[], - protos.google.firestore.admin.v1.IListIndexesRequest|null, - protos.google.firestore.admin.v1.IListIndexesResponse - ]) => { - this._log.info('listIndexes values %j', response); - return [response, input, output]; - }); + ?.then( + ([response, input, output]: [ + protos.google.firestore.admin.v1.IIndex[], + protos.google.firestore.admin.v1.IListIndexesRequest | null, + protos.google.firestore.admin.v1.IListIndexesResponse, + ]) => { + this._log.info('listIndexes values %j', response); + return [response, input, output]; + } + ); } -/** - * Equivalent to `listIndexes`, but returns a NodeJS Stream object. - * @param {Object} request - * The request object that will be sent. - * @param {string} request.parent - * Required. A parent name of the form - * `projects/{project_id}/databases/{database_id}/collectionGroups/{collection_id}` - * @param {string} request.filter - * The filter to apply to list results. - * @param {number} request.pageSize - * The number of results to return. - * @param {string} request.pageToken - * A page token, returned from a previous call to - * {@link protos.google.firestore.admin.v1.FirestoreAdmin.ListIndexes|FirestoreAdmin.ListIndexes}, - * that may be used to get the next page of results. - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Stream} - * An object stream which emits an object representing {@link protos.google.firestore.admin.v1.Index|Index} on 'data' event. - * The client library will perform auto-pagination by default: it will call the API as many - * times as needed. Note that it can affect your quota. - * We recommend using `listIndexesAsync()` - * method described below for async iteration which you can stop as needed. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#auto-pagination | documentation } - * for more details and examples. - */ + /** + * Equivalent to `listIndexes`, but returns a NodeJS Stream object. + * @param {Object} request + * The request object that will be sent. + * @param {string} request.parent + * Required. A parent name of the form + * `projects/{project_id}/databases/{database_id}/collectionGroups/{collection_id}` + * @param {string} request.filter + * The filter to apply to list results. + * @param {number} request.pageSize + * The number of results to return. + * @param {string} request.pageToken + * A page token, returned from a previous call to + * {@link protos.google.firestore.admin.v1.FirestoreAdmin.ListIndexes|FirestoreAdmin.ListIndexes}, + * that may be used to get the next page of results. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Stream} + * An object stream which emits an object representing {@link protos.google.firestore.admin.v1.Index|Index} on 'data' event. + * The client library will perform auto-pagination by default: it will call the API as many + * times as needed. Note that it can affect your quota. + * We recommend using `listIndexesAsync()` + * method described below for async iteration which you can stop as needed. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#auto-pagination | documentation } + * for more details and examples. + */ listIndexesStream( - request?: protos.google.firestore.admin.v1.IListIndexesRequest, - options?: CallOptions): - Transform{ + request?: protos.google.firestore.admin.v1.IListIndexesRequest, + options?: CallOptions + ): Transform { request = request || {}; options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - options.otherArgs.headers[ - 'x-goog-request-params' - ] = this._gaxModule.routingHeader.fromParams({ - 'parent': request.parent ?? '', - }); + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + parent: request.parent ?? '', + }); const defaultCallSettings = this._defaults['listIndexes']; const callSettings = defaultCallSettings.merge(options); - this.initialize().catch(err => {throw err}); + this.initialize().catch(err => { + throw err; + }); this._log.info('listIndexes stream %j', request); return this.descriptors.page.listIndexes.createStream( this.innerApiCalls.listIndexes as GaxCall, @@ -3596,51 +4856,52 @@ export class FirestoreAdminClient { ); } -/** - * Equivalent to `listIndexes`, but returns an iterable object. - * - * `for`-`await`-`of` syntax is used with the iterable to get response elements on-demand. - * @param {Object} request - * The request object that will be sent. - * @param {string} request.parent - * Required. A parent name of the form - * `projects/{project_id}/databases/{database_id}/collectionGroups/{collection_id}` - * @param {string} request.filter - * The filter to apply to list results. - * @param {number} request.pageSize - * The number of results to return. - * @param {string} request.pageToken - * A page token, returned from a previous call to - * {@link protos.google.firestore.admin.v1.FirestoreAdmin.ListIndexes|FirestoreAdmin.ListIndexes}, - * that may be used to get the next page of results. - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Object} - * An iterable Object that allows {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols | async iteration }. - * When you iterate the returned iterable, each element will be an object representing - * {@link protos.google.firestore.admin.v1.Index|Index}. The API will be called under the hood as needed, once per the page, - * so you can stop the iteration when you don't need more results. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#auto-pagination | documentation } - * for more details and examples. - * @example - * region_tag:firestore_v1_generated_FirestoreAdmin_ListIndexes_async - */ + /** + * Equivalent to `listIndexes`, but returns an iterable object. + * + * `for`-`await`-`of` syntax is used with the iterable to get response elements on-demand. + * @param {Object} request + * The request object that will be sent. + * @param {string} request.parent + * Required. A parent name of the form + * `projects/{project_id}/databases/{database_id}/collectionGroups/{collection_id}` + * @param {string} request.filter + * The filter to apply to list results. + * @param {number} request.pageSize + * The number of results to return. + * @param {string} request.pageToken + * A page token, returned from a previous call to + * {@link protos.google.firestore.admin.v1.FirestoreAdmin.ListIndexes|FirestoreAdmin.ListIndexes}, + * that may be used to get the next page of results. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Object} + * An iterable Object that allows {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols | async iteration }. + * When you iterate the returned iterable, each element will be an object representing + * {@link protos.google.firestore.admin.v1.Index|Index}. The API will be called under the hood as needed, once per the page, + * so you can stop the iteration when you don't need more results. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#auto-pagination | documentation } + * for more details and examples. + * @example + * region_tag:firestore_v1_generated_FirestoreAdmin_ListIndexes_async + */ listIndexesAsync( - request?: protos.google.firestore.admin.v1.IListIndexesRequest, - options?: CallOptions): - AsyncIterable{ + request?: protos.google.firestore.admin.v1.IListIndexesRequest, + options?: CallOptions + ): AsyncIterable { request = request || {}; options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - options.otherArgs.headers[ - 'x-goog-request-params' - ] = this._gaxModule.routingHeader.fromParams({ - 'parent': request.parent ?? '', - }); + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + parent: request.parent ?? '', + }); const defaultCallSettings = this._defaults['listIndexes']; const callSettings = defaultCallSettings.merge(options); - this.initialize().catch(err => {throw err}); + this.initialize().catch(err => { + throw err; + }); this._log.info('listIndexes iterate %j', request); return this.descriptors.page.listIndexes.asyncIterate( this.innerApiCalls['listIndexes'] as GaxCall, @@ -3648,106 +4909,125 @@ export class FirestoreAdminClient { callSettings ) as AsyncIterable; } - /** - * Lists the field configuration and metadata for this database. - * - * Currently, - * {@link protos.google.firestore.admin.v1.FirestoreAdmin.ListFields|FirestoreAdmin.ListFields} - * only supports listing fields that have been explicitly overridden. To issue - * this query, call - * {@link protos.google.firestore.admin.v1.FirestoreAdmin.ListFields|FirestoreAdmin.ListFields} - * with the filter set to `indexConfig.usesAncestorConfig:false` or - * `ttlConfig:*`. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.parent - * Required. A parent name of the form - * `projects/{project_id}/databases/{database_id}/collectionGroups/{collection_id}` - * @param {string} request.filter - * The filter to apply to list results. Currently, - * {@link protos.google.firestore.admin.v1.FirestoreAdmin.ListFields|FirestoreAdmin.ListFields} - * only supports listing fields that have been explicitly overridden. To issue - * this query, call - * {@link protos.google.firestore.admin.v1.FirestoreAdmin.ListFields|FirestoreAdmin.ListFields} - * with a filter that includes `indexConfig.usesAncestorConfig:false` or - * `ttlConfig:*`. - * @param {number} request.pageSize - * The number of results to return. - * @param {string} request.pageToken - * A page token, returned from a previous call to - * {@link protos.google.firestore.admin.v1.FirestoreAdmin.ListFields|FirestoreAdmin.ListFields}, - * that may be used to get the next page of results. - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Promise} - The promise which resolves to an array. - * The first element of the array is Array of {@link protos.google.firestore.admin.v1.Field|Field}. - * The client library will perform auto-pagination by default: it will call the API as many - * times as needed and will merge results from all the pages into this array. - * Note that it can affect your quota. - * We recommend using `listFieldsAsync()` - * method described below for async iteration which you can stop as needed. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#auto-pagination | documentation } - * for more details and examples. - */ + /** + * Lists the field configuration and metadata for this database. + * + * Currently, + * {@link protos.google.firestore.admin.v1.FirestoreAdmin.ListFields|FirestoreAdmin.ListFields} + * only supports listing fields that have been explicitly overridden. To issue + * this query, call + * {@link protos.google.firestore.admin.v1.FirestoreAdmin.ListFields|FirestoreAdmin.ListFields} + * with the filter set to `indexConfig.usesAncestorConfig:false` or + * `ttlConfig:*`. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.parent + * Required. A parent name of the form + * `projects/{project_id}/databases/{database_id}/collectionGroups/{collection_id}` + * @param {string} request.filter + * The filter to apply to list results. Currently, + * {@link protos.google.firestore.admin.v1.FirestoreAdmin.ListFields|FirestoreAdmin.ListFields} + * only supports listing fields that have been explicitly overridden. To issue + * this query, call + * {@link protos.google.firestore.admin.v1.FirestoreAdmin.ListFields|FirestoreAdmin.ListFields} + * with a filter that includes `indexConfig.usesAncestorConfig:false` or + * `ttlConfig:*`. + * @param {number} request.pageSize + * The number of results to return. + * @param {string} request.pageToken + * A page token, returned from a previous call to + * {@link protos.google.firestore.admin.v1.FirestoreAdmin.ListFields|FirestoreAdmin.ListFields}, + * that may be used to get the next page of results. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is Array of {@link protos.google.firestore.admin.v1.Field|Field}. + * The client library will perform auto-pagination by default: it will call the API as many + * times as needed and will merge results from all the pages into this array. + * Note that it can affect your quota. + * We recommend using `listFieldsAsync()` + * method described below for async iteration which you can stop as needed. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#auto-pagination | documentation } + * for more details and examples. + */ listFields( - request?: protos.google.firestore.admin.v1.IListFieldsRequest, - options?: CallOptions): - Promise<[ - protos.google.firestore.admin.v1.IField[], - protos.google.firestore.admin.v1.IListFieldsRequest|null, - protos.google.firestore.admin.v1.IListFieldsResponse - ]>; + request?: protos.google.firestore.admin.v1.IListFieldsRequest, + options?: CallOptions + ): Promise< + [ + protos.google.firestore.admin.v1.IField[], + protos.google.firestore.admin.v1.IListFieldsRequest | null, + protos.google.firestore.admin.v1.IListFieldsResponse, + ] + >; listFields( - request: protos.google.firestore.admin.v1.IListFieldsRequest, - options: CallOptions, - callback: PaginationCallback< - protos.google.firestore.admin.v1.IListFieldsRequest, - protos.google.firestore.admin.v1.IListFieldsResponse|null|undefined, - protos.google.firestore.admin.v1.IField>): void; + request: protos.google.firestore.admin.v1.IListFieldsRequest, + options: CallOptions, + callback: PaginationCallback< + protos.google.firestore.admin.v1.IListFieldsRequest, + protos.google.firestore.admin.v1.IListFieldsResponse | null | undefined, + protos.google.firestore.admin.v1.IField + > + ): void; listFields( - request: protos.google.firestore.admin.v1.IListFieldsRequest, - callback: PaginationCallback< - protos.google.firestore.admin.v1.IListFieldsRequest, - protos.google.firestore.admin.v1.IListFieldsResponse|null|undefined, - protos.google.firestore.admin.v1.IField>): void; + request: protos.google.firestore.admin.v1.IListFieldsRequest, + callback: PaginationCallback< + protos.google.firestore.admin.v1.IListFieldsRequest, + protos.google.firestore.admin.v1.IListFieldsResponse | null | undefined, + protos.google.firestore.admin.v1.IField + > + ): void; listFields( - request?: protos.google.firestore.admin.v1.IListFieldsRequest, - optionsOrCallback?: CallOptions|PaginationCallback< - protos.google.firestore.admin.v1.IListFieldsRequest, - protos.google.firestore.admin.v1.IListFieldsResponse|null|undefined, - protos.google.firestore.admin.v1.IField>, - callback?: PaginationCallback< + request?: protos.google.firestore.admin.v1.IListFieldsRequest, + optionsOrCallback?: + | CallOptions + | PaginationCallback< protos.google.firestore.admin.v1.IListFieldsRequest, - protos.google.firestore.admin.v1.IListFieldsResponse|null|undefined, - protos.google.firestore.admin.v1.IField>): - Promise<[ - protos.google.firestore.admin.v1.IField[], - protos.google.firestore.admin.v1.IListFieldsRequest|null, - protos.google.firestore.admin.v1.IListFieldsResponse - ]>|void { + | protos.google.firestore.admin.v1.IListFieldsResponse + | null + | undefined, + protos.google.firestore.admin.v1.IField + >, + callback?: PaginationCallback< + protos.google.firestore.admin.v1.IListFieldsRequest, + protos.google.firestore.admin.v1.IListFieldsResponse | null | undefined, + protos.google.firestore.admin.v1.IField + > + ): Promise< + [ + protos.google.firestore.admin.v1.IField[], + protos.google.firestore.admin.v1.IListFieldsRequest | null, + protos.google.firestore.admin.v1.IListFieldsResponse, + ] + > | void { request = request || {}; let options: CallOptions; if (typeof optionsOrCallback === 'function' && callback === undefined) { callback = optionsOrCallback; options = {}; - } - else { + } else { options = optionsOrCallback as CallOptions; } options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - options.otherArgs.headers[ - 'x-goog-request-params' - ] = this._gaxModule.routingHeader.fromParams({ - 'parent': request.parent ?? '', + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + parent: request.parent ?? '', + }); + this.initialize().catch(err => { + throw err; }); - this.initialize().catch(err => {throw err}); - const wrappedCallback: PaginationCallback< - protos.google.firestore.admin.v1.IListFieldsRequest, - protos.google.firestore.admin.v1.IListFieldsResponse|null|undefined, - protos.google.firestore.admin.v1.IField>|undefined = callback + const wrappedCallback: + | PaginationCallback< + protos.google.firestore.admin.v1.IListFieldsRequest, + | protos.google.firestore.admin.v1.IListFieldsResponse + | null + | undefined, + protos.google.firestore.admin.v1.IField + > + | undefined = callback ? (error, values, nextPageRequest, rawResponse) => { this._log.info('listFields values %j', values); callback!(error, values, nextPageRequest, rawResponse); // We verified callback above. @@ -3756,64 +5036,67 @@ export class FirestoreAdminClient { this._log.info('listFields request %j', request); return this.innerApiCalls .listFields(request, options, wrappedCallback) - ?.then(([response, input, output]: [ - protos.google.firestore.admin.v1.IField[], - protos.google.firestore.admin.v1.IListFieldsRequest|null, - protos.google.firestore.admin.v1.IListFieldsResponse - ]) => { - this._log.info('listFields values %j', response); - return [response, input, output]; - }); + ?.then( + ([response, input, output]: [ + protos.google.firestore.admin.v1.IField[], + protos.google.firestore.admin.v1.IListFieldsRequest | null, + protos.google.firestore.admin.v1.IListFieldsResponse, + ]) => { + this._log.info('listFields values %j', response); + return [response, input, output]; + } + ); } -/** - * Equivalent to `listFields`, but returns a NodeJS Stream object. - * @param {Object} request - * The request object that will be sent. - * @param {string} request.parent - * Required. A parent name of the form - * `projects/{project_id}/databases/{database_id}/collectionGroups/{collection_id}` - * @param {string} request.filter - * The filter to apply to list results. Currently, - * {@link protos.google.firestore.admin.v1.FirestoreAdmin.ListFields|FirestoreAdmin.ListFields} - * only supports listing fields that have been explicitly overridden. To issue - * this query, call - * {@link protos.google.firestore.admin.v1.FirestoreAdmin.ListFields|FirestoreAdmin.ListFields} - * with a filter that includes `indexConfig.usesAncestorConfig:false` or - * `ttlConfig:*`. - * @param {number} request.pageSize - * The number of results to return. - * @param {string} request.pageToken - * A page token, returned from a previous call to - * {@link protos.google.firestore.admin.v1.FirestoreAdmin.ListFields|FirestoreAdmin.ListFields}, - * that may be used to get the next page of results. - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Stream} - * An object stream which emits an object representing {@link protos.google.firestore.admin.v1.Field|Field} on 'data' event. - * The client library will perform auto-pagination by default: it will call the API as many - * times as needed. Note that it can affect your quota. - * We recommend using `listFieldsAsync()` - * method described below for async iteration which you can stop as needed. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#auto-pagination | documentation } - * for more details and examples. - */ + /** + * Equivalent to `listFields`, but returns a NodeJS Stream object. + * @param {Object} request + * The request object that will be sent. + * @param {string} request.parent + * Required. A parent name of the form + * `projects/{project_id}/databases/{database_id}/collectionGroups/{collection_id}` + * @param {string} request.filter + * The filter to apply to list results. Currently, + * {@link protos.google.firestore.admin.v1.FirestoreAdmin.ListFields|FirestoreAdmin.ListFields} + * only supports listing fields that have been explicitly overridden. To issue + * this query, call + * {@link protos.google.firestore.admin.v1.FirestoreAdmin.ListFields|FirestoreAdmin.ListFields} + * with a filter that includes `indexConfig.usesAncestorConfig:false` or + * `ttlConfig:*`. + * @param {number} request.pageSize + * The number of results to return. + * @param {string} request.pageToken + * A page token, returned from a previous call to + * {@link protos.google.firestore.admin.v1.FirestoreAdmin.ListFields|FirestoreAdmin.ListFields}, + * that may be used to get the next page of results. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Stream} + * An object stream which emits an object representing {@link protos.google.firestore.admin.v1.Field|Field} on 'data' event. + * The client library will perform auto-pagination by default: it will call the API as many + * times as needed. Note that it can affect your quota. + * We recommend using `listFieldsAsync()` + * method described below for async iteration which you can stop as needed. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#auto-pagination | documentation } + * for more details and examples. + */ listFieldsStream( - request?: protos.google.firestore.admin.v1.IListFieldsRequest, - options?: CallOptions): - Transform{ + request?: protos.google.firestore.admin.v1.IListFieldsRequest, + options?: CallOptions + ): Transform { request = request || {}; options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - options.otherArgs.headers[ - 'x-goog-request-params' - ] = this._gaxModule.routingHeader.fromParams({ - 'parent': request.parent ?? '', - }); + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + parent: request.parent ?? '', + }); const defaultCallSettings = this._defaults['listFields']; const callSettings = defaultCallSettings.merge(options); - this.initialize().catch(err => {throw err}); + this.initialize().catch(err => { + throw err; + }); this._log.info('listFields stream %j', request); return this.descriptors.page.listFields.createStream( this.innerApiCalls.listFields as GaxCall, @@ -3822,57 +5105,58 @@ export class FirestoreAdminClient { ); } -/** - * Equivalent to `listFields`, but returns an iterable object. - * - * `for`-`await`-`of` syntax is used with the iterable to get response elements on-demand. - * @param {Object} request - * The request object that will be sent. - * @param {string} request.parent - * Required. A parent name of the form - * `projects/{project_id}/databases/{database_id}/collectionGroups/{collection_id}` - * @param {string} request.filter - * The filter to apply to list results. Currently, - * {@link protos.google.firestore.admin.v1.FirestoreAdmin.ListFields|FirestoreAdmin.ListFields} - * only supports listing fields that have been explicitly overridden. To issue - * this query, call - * {@link protos.google.firestore.admin.v1.FirestoreAdmin.ListFields|FirestoreAdmin.ListFields} - * with a filter that includes `indexConfig.usesAncestorConfig:false` or - * `ttlConfig:*`. - * @param {number} request.pageSize - * The number of results to return. - * @param {string} request.pageToken - * A page token, returned from a previous call to - * {@link protos.google.firestore.admin.v1.FirestoreAdmin.ListFields|FirestoreAdmin.ListFields}, - * that may be used to get the next page of results. - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Object} - * An iterable Object that allows {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols | async iteration }. - * When you iterate the returned iterable, each element will be an object representing - * {@link protos.google.firestore.admin.v1.Field|Field}. The API will be called under the hood as needed, once per the page, - * so you can stop the iteration when you don't need more results. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#auto-pagination | documentation } - * for more details and examples. - * @example - * region_tag:firestore_v1_generated_FirestoreAdmin_ListFields_async - */ + /** + * Equivalent to `listFields`, but returns an iterable object. + * + * `for`-`await`-`of` syntax is used with the iterable to get response elements on-demand. + * @param {Object} request + * The request object that will be sent. + * @param {string} request.parent + * Required. A parent name of the form + * `projects/{project_id}/databases/{database_id}/collectionGroups/{collection_id}` + * @param {string} request.filter + * The filter to apply to list results. Currently, + * {@link protos.google.firestore.admin.v1.FirestoreAdmin.ListFields|FirestoreAdmin.ListFields} + * only supports listing fields that have been explicitly overridden. To issue + * this query, call + * {@link protos.google.firestore.admin.v1.FirestoreAdmin.ListFields|FirestoreAdmin.ListFields} + * with a filter that includes `indexConfig.usesAncestorConfig:false` or + * `ttlConfig:*`. + * @param {number} request.pageSize + * The number of results to return. + * @param {string} request.pageToken + * A page token, returned from a previous call to + * {@link protos.google.firestore.admin.v1.FirestoreAdmin.ListFields|FirestoreAdmin.ListFields}, + * that may be used to get the next page of results. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Object} + * An iterable Object that allows {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols | async iteration }. + * When you iterate the returned iterable, each element will be an object representing + * {@link protos.google.firestore.admin.v1.Field|Field}. The API will be called under the hood as needed, once per the page, + * so you can stop the iteration when you don't need more results. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#auto-pagination | documentation } + * for more details and examples. + * @example + * region_tag:firestore_v1_generated_FirestoreAdmin_ListFields_async + */ listFieldsAsync( - request?: protos.google.firestore.admin.v1.IListFieldsRequest, - options?: CallOptions): - AsyncIterable{ + request?: protos.google.firestore.admin.v1.IListFieldsRequest, + options?: CallOptions + ): AsyncIterable { request = request || {}; options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - options.otherArgs.headers[ - 'x-goog-request-params' - ] = this._gaxModule.routingHeader.fromParams({ - 'parent': request.parent ?? '', - }); + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + parent: request.parent ?? '', + }); const defaultCallSettings = this._defaults['listFields']; const callSettings = defaultCallSettings.merge(options); - this.initialize().catch(err => {throw err}); + this.initialize().catch(err => { + throw err; + }); this._log.info('listFields iterate %j', request); return this.descriptors.page.listFields.asyncIterate( this.innerApiCalls['listFields'] as GaxCall, @@ -3880,7 +5164,7 @@ export class FirestoreAdminClient { callSettings ) as AsyncIterable; } -/** + /** * Gets information about a location. * * @param {Object} request @@ -3920,7 +5204,7 @@ export class FirestoreAdminClient { return this.locationsClient.getLocation(request, options, callback); } -/** + /** * Lists information about the supported locations for this service. Returns an iterable object. * * `for`-`await`-`of` syntax is used with the iterable to get response elements on-demand. @@ -3958,7 +5242,7 @@ export class FirestoreAdminClient { return this.locationsClient.listLocationsAsync(request, options); } -/** + /** * Gets the latest state of a long-running operation. Clients can use this * method to poll the operation result at intervals as recommended by the API * service. @@ -4003,20 +5287,20 @@ export class FirestoreAdminClient { {} | null | undefined > ): Promise<[protos.google.longrunning.Operation]> { - let options: gax.CallOptions; - if (typeof optionsOrCallback === 'function' && callback === undefined) { - callback = optionsOrCallback; - options = {}; - } else { - options = optionsOrCallback as gax.CallOptions; - } - options = options || {}; - options.otherArgs = options.otherArgs || {}; - options.otherArgs.headers = options.otherArgs.headers || {}; - options.otherArgs.headers['x-goog-request-params'] = - this._gaxModule.routingHeader.fromParams({ - name: request.name ?? '', - }); + let options: gax.CallOptions; + if (typeof optionsOrCallback === 'function' && callback === undefined) { + callback = optionsOrCallback; + options = {}; + } else { + options = optionsOrCallback as gax.CallOptions; + } + options = options || {}; + options.otherArgs = options.otherArgs || {}; + options.otherArgs.headers = options.otherArgs.headers || {}; + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + name: request.name ?? '', + }); return this.operationsClient.getOperation(request, options, callback); } /** @@ -4053,13 +5337,13 @@ export class FirestoreAdminClient { request: protos.google.longrunning.ListOperationsRequest, options?: gax.CallOptions ): AsyncIterable { - options = options || {}; - options.otherArgs = options.otherArgs || {}; - options.otherArgs.headers = options.otherArgs.headers || {}; - options.otherArgs.headers['x-goog-request-params'] = - this._gaxModule.routingHeader.fromParams({ - name: request.name ?? '', - }); + options = options || {}; + options.otherArgs = options.otherArgs || {}; + options.otherArgs.headers = options.otherArgs.headers || {}; + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + name: request.name ?? '', + }); return this.operationsClient.listOperationsAsync(request, options); } /** @@ -4093,7 +5377,7 @@ export class FirestoreAdminClient { * await client.cancelOperation({name: ''}); * ``` */ - cancelOperation( + cancelOperation( request: protos.google.longrunning.CancelOperationRequest, optionsOrCallback?: | gax.CallOptions @@ -4108,20 +5392,20 @@ export class FirestoreAdminClient { {} | undefined | null > ): Promise { - let options: gax.CallOptions; - if (typeof optionsOrCallback === 'function' && callback === undefined) { - callback = optionsOrCallback; - options = {}; - } else { - options = optionsOrCallback as gax.CallOptions; - } - options = options || {}; - options.otherArgs = options.otherArgs || {}; - options.otherArgs.headers = options.otherArgs.headers || {}; - options.otherArgs.headers['x-goog-request-params'] = - this._gaxModule.routingHeader.fromParams({ - name: request.name ?? '', - }); + let options: gax.CallOptions; + if (typeof optionsOrCallback === 'function' && callback === undefined) { + callback = optionsOrCallback; + options = {}; + } else { + options = optionsOrCallback as gax.CallOptions; + } + options = options || {}; + options.otherArgs = options.otherArgs || {}; + options.otherArgs.headers = options.otherArgs.headers || {}; + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + name: request.name ?? '', + }); return this.operationsClient.cancelOperation(request, options, callback); } @@ -4165,20 +5449,20 @@ export class FirestoreAdminClient { {} | null | undefined > ): Promise { - let options: gax.CallOptions; - if (typeof optionsOrCallback === 'function' && callback === undefined) { - callback = optionsOrCallback; - options = {}; - } else { - options = optionsOrCallback as gax.CallOptions; - } - options = options || {}; - options.otherArgs = options.otherArgs || {}; - options.otherArgs.headers = options.otherArgs.headers || {}; - options.otherArgs.headers['x-goog-request-params'] = - this._gaxModule.routingHeader.fromParams({ - name: request.name ?? '', - }); + let options: gax.CallOptions; + if (typeof optionsOrCallback === 'function' && callback === undefined) { + callback = optionsOrCallback; + options = {}; + } else { + options = optionsOrCallback as gax.CallOptions; + } + options = options || {}; + options.otherArgs = options.otherArgs || {}; + options.otherArgs.headers = options.otherArgs.headers || {}; + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + name: request.name ?? '', + }); return this.operationsClient.deleteOperation(request, options, callback); } @@ -4194,7 +5478,7 @@ export class FirestoreAdminClient { * @param {string} backup * @returns {string} Resource name string. */ - backupPath(project:string,location:string,backup:string) { + backupPath(project: string, location: string, backup: string) { return this.pathTemplates.backupPathTemplate.render({ project: project, location: location, @@ -4243,7 +5527,11 @@ export class FirestoreAdminClient { * @param {string} backup_schedule * @returns {string} Resource name string. */ - backupSchedulePath(project:string,database:string,backupSchedule:string) { + backupSchedulePath( + project: string, + database: string, + backupSchedule: string + ) { return this.pathTemplates.backupSchedulePathTemplate.render({ project: project, database: database, @@ -4259,7 +5547,9 @@ export class FirestoreAdminClient { * @returns {string} A string representing the project. */ matchProjectFromBackupScheduleName(backupScheduleName: string) { - return this.pathTemplates.backupSchedulePathTemplate.match(backupScheduleName).project; + return this.pathTemplates.backupSchedulePathTemplate.match( + backupScheduleName + ).project; } /** @@ -4270,7 +5560,9 @@ export class FirestoreAdminClient { * @returns {string} A string representing the database. */ matchDatabaseFromBackupScheduleName(backupScheduleName: string) { - return this.pathTemplates.backupSchedulePathTemplate.match(backupScheduleName).database; + return this.pathTemplates.backupSchedulePathTemplate.match( + backupScheduleName + ).database; } /** @@ -4281,7 +5573,9 @@ export class FirestoreAdminClient { * @returns {string} A string representing the backup_schedule. */ matchBackupScheduleFromBackupScheduleName(backupScheduleName: string) { - return this.pathTemplates.backupSchedulePathTemplate.match(backupScheduleName).backup_schedule; + return this.pathTemplates.backupSchedulePathTemplate.match( + backupScheduleName + ).backup_schedule; } /** @@ -4292,7 +5586,7 @@ export class FirestoreAdminClient { * @param {string} collection * @returns {string} Resource name string. */ - collectionGroupPath(project:string,database:string,collection:string) { + collectionGroupPath(project: string, database: string, collection: string) { return this.pathTemplates.collectionGroupPathTemplate.render({ project: project, database: database, @@ -4308,7 +5602,9 @@ export class FirestoreAdminClient { * @returns {string} A string representing the project. */ matchProjectFromCollectionGroupName(collectionGroupName: string) { - return this.pathTemplates.collectionGroupPathTemplate.match(collectionGroupName).project; + return this.pathTemplates.collectionGroupPathTemplate.match( + collectionGroupName + ).project; } /** @@ -4319,7 +5615,9 @@ export class FirestoreAdminClient { * @returns {string} A string representing the database. */ matchDatabaseFromCollectionGroupName(collectionGroupName: string) { - return this.pathTemplates.collectionGroupPathTemplate.match(collectionGroupName).database; + return this.pathTemplates.collectionGroupPathTemplate.match( + collectionGroupName + ).database; } /** @@ -4330,7 +5628,9 @@ export class FirestoreAdminClient { * @returns {string} A string representing the collection. */ matchCollectionFromCollectionGroupName(collectionGroupName: string) { - return this.pathTemplates.collectionGroupPathTemplate.match(collectionGroupName).collection; + return this.pathTemplates.collectionGroupPathTemplate.match( + collectionGroupName + ).collection; } /** @@ -4340,7 +5640,7 @@ export class FirestoreAdminClient { * @param {string} database * @returns {string} Resource name string. */ - databasePath(project:string,database:string) { + databasePath(project: string, database: string) { return this.pathTemplates.databasePathTemplate.render({ project: project, database: database, @@ -4378,7 +5678,12 @@ export class FirestoreAdminClient { * @param {string} field * @returns {string} Resource name string. */ - fieldPath(project:string,database:string,collection:string,field:string) { + fieldPath( + project: string, + database: string, + collection: string, + field: string + ) { return this.pathTemplates.fieldPathTemplate.render({ project: project, database: database, @@ -4440,7 +5745,12 @@ export class FirestoreAdminClient { * @param {string} index * @returns {string} Resource name string. */ - indexPath(project:string,database:string,collection:string,index:string) { + indexPath( + project: string, + database: string, + collection: string, + index: string + ) { return this.pathTemplates.indexPathTemplate.render({ project: project, database: database, @@ -4500,7 +5810,7 @@ export class FirestoreAdminClient { * @param {string} location * @returns {string} Resource name string. */ - locationPath(project:string,location:string) { + locationPath(project: string, location: string) { return this.pathTemplates.locationPathTemplate.render({ project: project, location: location, @@ -4535,7 +5845,7 @@ export class FirestoreAdminClient { * @param {string} project * @returns {string} Resource name string. */ - projectPath(project:string) { + projectPath(project: string) { return this.pathTemplates.projectPathTemplate.render({ project: project, }); @@ -4560,7 +5870,7 @@ export class FirestoreAdminClient { * @param {string} user_creds * @returns {string} Resource name string. */ - userCredsPath(project:string,database:string,userCreds:string) { + userCredsPath(project: string, database: string, userCreds: string) { return this.pathTemplates.userCredsPathTemplate.render({ project: project, database: database, @@ -4576,7 +5886,8 @@ export class FirestoreAdminClient { * @returns {string} A string representing the project. */ matchProjectFromUserCredsName(userCredsName: string) { - return this.pathTemplates.userCredsPathTemplate.match(userCredsName).project; + return this.pathTemplates.userCredsPathTemplate.match(userCredsName) + .project; } /** @@ -4587,7 +5898,8 @@ export class FirestoreAdminClient { * @returns {string} A string representing the database. */ matchDatabaseFromUserCredsName(userCredsName: string) { - return this.pathTemplates.userCredsPathTemplate.match(userCredsName).database; + return this.pathTemplates.userCredsPathTemplate.match(userCredsName) + .database; } /** @@ -4598,7 +5910,8 @@ export class FirestoreAdminClient { * @returns {string} A string representing the user_creds. */ matchUserCredsFromUserCredsName(userCredsName: string) { - return this.pathTemplates.userCredsPathTemplate.match(userCredsName).user_creds; + return this.pathTemplates.userCredsPathTemplate.match(userCredsName) + .user_creds; } /** @@ -4613,10 +5926,12 @@ export class FirestoreAdminClient { this._log.info('ending gRPC channel'); this._terminated = true; stub.close(); - this.locationsClient.close().catch(err => {throw err}); + this.locationsClient.close().catch(err => { + throw err; + }); void this.operationsClient.close(); }); } return Promise.resolve(); } -} \ No newline at end of file +} diff --git a/dev/src/v1/firestore_client.ts b/dev/src/v1/firestore_client.ts index b3296bf05..f738fa10b 100644 --- a/dev/src/v1/firestore_client.ts +++ b/dev/src/v1/firestore_client.ts @@ -18,7 +18,16 @@ /* global window */ import type * as gax from 'google-gax'; -import type {Callback, CallOptions, Descriptors, ClientOptions, PaginationCallback, GaxCall, LocationsClient, LocationProtos} from 'google-gax'; +import type { + Callback, + CallOptions, + Descriptors, + ClientOptions, + PaginationCallback, + GaxCall, + LocationsClient, + LocationProtos, +} from 'google-gax'; import {Transform, PassThrough} from 'stream'; import * as protos from '../../protos/firestore_v1_proto_api'; import jsonProtos = require('../../protos/v1.json'); @@ -107,20 +116,41 @@ export class FirestoreClient { * const client = new FirestoreClient({fallback: true}, gax); * ``` */ - constructor(opts?: ClientOptions, gaxInstance?: typeof gax | typeof gax.fallback) { + constructor( + opts?: ClientOptions, + gaxInstance?: typeof gax | typeof gax.fallback + ) { // Ensure that options include all the required fields. const staticMembers = this.constructor as typeof FirestoreClient; - if (opts?.universe_domain && opts?.universeDomain && opts?.universe_domain !== opts?.universeDomain) { - throw new Error('Please set either universe_domain or universeDomain, but not both.'); + if ( + opts?.universe_domain && + opts?.universeDomain && + opts?.universe_domain !== opts?.universeDomain + ) { + throw new Error( + 'Please set either universe_domain or universeDomain, but not both.' + ); } - const universeDomainEnvVar = (typeof process === 'object' && typeof process.env === 'object') ? process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] : undefined; - this._universeDomain = opts?.universeDomain ?? opts?.universe_domain ?? universeDomainEnvVar ?? 'googleapis.com'; + const universeDomainEnvVar = + typeof process === 'object' && typeof process.env === 'object' + ? process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] + : undefined; + this._universeDomain = + opts?.universeDomain ?? + opts?.universe_domain ?? + universeDomainEnvVar ?? + 'googleapis.com'; this._servicePath = 'firestore.' + this._universeDomain; - const servicePath = opts?.servicePath || opts?.apiEndpoint || this._servicePath; - this._providedCustomServicePath = !!(opts?.servicePath || opts?.apiEndpoint); + const servicePath = + opts?.servicePath || opts?.apiEndpoint || this._servicePath; + this._providedCustomServicePath = !!( + opts?.servicePath || opts?.apiEndpoint + ); const port = opts?.port || staticMembers.port; const clientConfig = opts?.clientConfig ?? {}; - const fallback = opts?.fallback ?? (typeof window !== 'undefined' && typeof window?.fetch === 'function'); + const fallback = + opts?.fallback ?? + (typeof window !== 'undefined' && typeof window?.fetch === 'function'); opts = Object.assign({servicePath, port, clientConfig, fallback}, opts); // If scopes are unset in options and we're connecting to a non-default endpoint, set scopes just in case. @@ -143,7 +173,7 @@ export class FirestoreClient { this._opts = opts; // Save the auth object to the client, for use by other methods. - this.auth = (this._gaxGrpc.auth as gax.GoogleAuth); + this.auth = this._gaxGrpc.auth as gax.GoogleAuth; // Set useJWTAccessWithScope on the auth object. this.auth.useJWTAccessWithScope = true; @@ -159,13 +189,9 @@ export class FirestoreClient { this._gaxGrpc, opts ); - // Determine the client header string. - const clientHeader = [ - `gax/${this._gaxModule.version}`, - `gapic/${version}`, - ]; + const clientHeader = [`gax/${this._gaxModule.version}`, `gapic/${version}`]; if (typeof process === 'object' && 'versions' in process) { clientHeader.push(`gl-node/${process.versions.node}`); } else { @@ -186,29 +212,65 @@ export class FirestoreClient { // (e.g. 50 results at a time, with tokens to get subsequent // pages). Denote the keys used for pagination and results. this.descriptors.page = { - listDocuments: - new this._gaxModule.PageDescriptor('pageToken', 'nextPageToken', 'documents'), - partitionQuery: - new this._gaxModule.PageDescriptor('pageToken', 'nextPageToken', 'partitions'), - listCollectionIds: - new this._gaxModule.PageDescriptor('pageToken', 'nextPageToken', 'collectionIds') + listDocuments: new this._gaxModule.PageDescriptor( + 'pageToken', + 'nextPageToken', + 'documents' + ), + partitionQuery: new this._gaxModule.PageDescriptor( + 'pageToken', + 'nextPageToken', + 'partitions' + ), + listCollectionIds: new this._gaxModule.PageDescriptor( + 'pageToken', + 'nextPageToken', + 'collectionIds' + ), }; // Some of the methods on this service provide streaming responses. // Provide descriptors for these. this.descriptors.stream = { - batchGetDocuments: new this._gaxModule.StreamDescriptor(this._gaxModule.StreamType.SERVER_STREAMING, !!opts.fallback, !!opts.gaxServerStreamingRetries), - runQuery: new this._gaxModule.StreamDescriptor(this._gaxModule.StreamType.SERVER_STREAMING, !!opts.fallback, !!opts.gaxServerStreamingRetries), - executePipeline: new this._gaxModule.StreamDescriptor(this._gaxModule.StreamType.SERVER_STREAMING, !!opts.fallback, !!opts.gaxServerStreamingRetries), - runAggregationQuery: new this._gaxModule.StreamDescriptor(this._gaxModule.StreamType.SERVER_STREAMING, !!opts.fallback, !!opts.gaxServerStreamingRetries), - write: new this._gaxModule.StreamDescriptor(this._gaxModule.StreamType.BIDI_STREAMING, !!opts.fallback, !!opts.gaxServerStreamingRetries), - listen: new this._gaxModule.StreamDescriptor(this._gaxModule.StreamType.BIDI_STREAMING, !!opts.fallback, !!opts.gaxServerStreamingRetries) + batchGetDocuments: new this._gaxModule.StreamDescriptor( + this._gaxModule.StreamType.SERVER_STREAMING, + !!opts.fallback, + !!opts.gaxServerStreamingRetries + ), + runQuery: new this._gaxModule.StreamDescriptor( + this._gaxModule.StreamType.SERVER_STREAMING, + !!opts.fallback, + !!opts.gaxServerStreamingRetries + ), + executePipeline: new this._gaxModule.StreamDescriptor( + this._gaxModule.StreamType.SERVER_STREAMING, + !!opts.fallback, + !!opts.gaxServerStreamingRetries + ), + runAggregationQuery: new this._gaxModule.StreamDescriptor( + this._gaxModule.StreamType.SERVER_STREAMING, + !!opts.fallback, + !!opts.gaxServerStreamingRetries + ), + write: new this._gaxModule.StreamDescriptor( + this._gaxModule.StreamType.BIDI_STREAMING, + !!opts.fallback, + !!opts.gaxServerStreamingRetries + ), + listen: new this._gaxModule.StreamDescriptor( + this._gaxModule.StreamType.BIDI_STREAMING, + !!opts.fallback, + !!opts.gaxServerStreamingRetries + ), }; // Put together the default options sent with requests. this._defaults = this._gaxGrpc.constructSettings( - 'google.firestore.v1.Firestore', gapicConfig as gax.ClientConfig, - opts.clientConfig || {}, {'x-goog-api-client': clientHeader.join(' ')}); + 'google.firestore.v1.Firestore', + gapicConfig as gax.ClientConfig, + opts.clientConfig || {}, + {'x-goog-api-client': clientHeader.join(' ')} + ); // Set up a dictionary of "inner API calls"; the core implementation // of calling the API is handled in `google-gax`, with this code @@ -239,35 +301,63 @@ export class FirestoreClient { // Put together the "service stub" for // google.firestore.v1.Firestore. this.firestoreStub = this._gaxGrpc.createStub( - this._opts.fallback ? - (this._protos as protobuf.Root).lookupService('google.firestore.v1.Firestore') : - // eslint-disable-next-line @typescript-eslint/no-explicit-any + this._opts.fallback + ? (this._protos as protobuf.Root).lookupService( + 'google.firestore.v1.Firestore' + ) + : // eslint-disable-next-line @typescript-eslint/no-explicit-any (this._protos as any).google.firestore.v1.Firestore, - this._opts, this._providedCustomServicePath) as Promise<{[method: string]: Function}>; + this._opts, + this._providedCustomServicePath + ) as Promise<{[method: string]: Function}>; // Iterate over each of the methods that the service provides // and create an API call method for each. - const firestoreStubMethods = - ['getDocument', 'listDocuments', 'updateDocument', 'deleteDocument', 'batchGetDocuments', 'beginTransaction', 'commit', 'rollback', 'runQuery', 'executePipeline', 'runAggregationQuery', 'partitionQuery', 'write', 'listen', 'listCollectionIds', 'batchWrite', 'createDocument']; + const firestoreStubMethods = [ + 'getDocument', + 'listDocuments', + 'updateDocument', + 'deleteDocument', + 'batchGetDocuments', + 'beginTransaction', + 'commit', + 'rollback', + 'runQuery', + 'executePipeline', + 'runAggregationQuery', + 'partitionQuery', + 'write', + 'listen', + 'listCollectionIds', + 'batchWrite', + 'createDocument', + ]; for (const methodName of firestoreStubMethods) { const callPromise = this.firestoreStub.then( - stub => (...args: Array<{}>) => { - if (this._terminated) { - if (methodName in this.descriptors.stream) { - const stream = new PassThrough({objectMode: true}); - setImmediate(() => { - stream.emit('error', new this._gaxModule.GoogleError('The client has already been closed.')); - }); - return stream; + stub => + (...args: Array<{}>) => { + if (this._terminated) { + if (methodName in this.descriptors.stream) { + const stream = new PassThrough({objectMode: true}); + setImmediate(() => { + stream.emit( + 'error', + new this._gaxModule.GoogleError( + 'The client has already been closed.' + ) + ); + }); + return stream; + } + return Promise.reject('The client has already been closed.'); } - return Promise.reject('The client has already been closed.'); - } - const func = stub[methodName]; - return func.apply(stub, args); - }, - (err: Error|null|undefined) => () => { + const func = stub[methodName]; + return func.apply(stub, args); + }, + (err: Error | null | undefined) => () => { throw err; - }); + } + ); const descriptor = this.descriptors.page[methodName] || @@ -292,8 +382,14 @@ export class FirestoreClient { * @returns {string} The DNS address for this service. */ static get servicePath() { - if (typeof process === 'object' && typeof process.emitWarning === 'function') { - process.emitWarning('Static servicePath is deprecated, please use the instance method instead.', 'DeprecationWarning'); + if ( + typeof process === 'object' && + typeof process.emitWarning === 'function' + ) { + process.emitWarning( + 'Static servicePath is deprecated, please use the instance method instead.', + 'DeprecationWarning' + ); } return 'firestore.googleapis.com'; } @@ -304,8 +400,14 @@ export class FirestoreClient { * @returns {string} The DNS address for this service. */ static get apiEndpoint() { - if (typeof process === 'object' && typeof process.emitWarning === 'function') { - process.emitWarning('Static apiEndpoint is deprecated, please use the instance method instead.', 'DeprecationWarning'); + if ( + typeof process === 'object' && + typeof process.emitWarning === 'function' + ) { + process.emitWarning( + 'Static apiEndpoint is deprecated, please use the instance method instead.', + 'DeprecationWarning' + ); } return 'firestore.googleapis.com'; } @@ -338,7 +440,7 @@ export class FirestoreClient { static get scopes() { return [ 'https://www.googleapis.com/auth/cloud-platform', - 'https://www.googleapis.com/auth/datastore' + 'https://www.googleapis.com/auth/datastore', ]; } @@ -348,8 +450,9 @@ export class FirestoreClient { * Return the project ID used by this class. * @returns {Promise} A promise that resolves to string containing the project ID. */ - getProjectId(callback?: Callback): - Promise|void { + getProjectId( + callback?: Callback + ): Promise | void { if (callback) { this.auth.getProjectId(callback); return; @@ -360,1237 +463,1424 @@ export class FirestoreClient { // ------------------- // -- Service calls -- // ------------------- -/** - * Gets a single document. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.name - * Required. The resource name of the Document to get. In the format: - * `projects/{project_id}/databases/{database_id}/documents/{document_path}`. - * @param {google.firestore.v1.DocumentMask} request.mask - * The fields to return. If not set, returns all fields. - * - * If the document has a field that is not present in this mask, that field - * will not be returned in the response. - * @param {Buffer} request.transaction - * Reads the document in a transaction. - * @param {google.protobuf.Timestamp} request.readTime - * Reads the version of the document at the given time. - * - * This must be a microsecond precision timestamp within the past one hour, - * or if Point-in-Time Recovery is enabled, can additionally be a whole - * minute timestamp within the past 7 days. - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Promise} - The promise which resolves to an array. - * The first element of the array is an object representing {@link protos.google.firestore.v1.Document|Document}. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } - * for more details and examples. - * @example - * region_tag:firestore_v1_generated_Firestore_GetDocument_async - */ + /** + * Gets a single document. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.name + * Required. The resource name of the Document to get. In the format: + * `projects/{project_id}/databases/{database_id}/documents/{document_path}`. + * @param {google.firestore.v1.DocumentMask} request.mask + * The fields to return. If not set, returns all fields. + * + * If the document has a field that is not present in this mask, that field + * will not be returned in the response. + * @param {Buffer} request.transaction + * Reads the document in a transaction. + * @param {google.protobuf.Timestamp} request.readTime + * Reads the version of the document at the given time. + * + * This must be a microsecond precision timestamp within the past one hour, + * or if Point-in-Time Recovery is enabled, can additionally be a whole + * minute timestamp within the past 7 days. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is an object representing {@link protos.google.firestore.v1.Document|Document}. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } + * for more details and examples. + * @example + * region_tag:firestore_v1_generated_Firestore_GetDocument_async + */ getDocument( - request?: protos.google.firestore.v1.IGetDocumentRequest, - options?: CallOptions): - Promise<[ - protos.google.firestore.v1.IDocument, - protos.google.firestore.v1.IGetDocumentRequest|undefined, {}|undefined - ]>; + request?: protos.google.firestore.v1.IGetDocumentRequest, + options?: CallOptions + ): Promise< + [ + protos.google.firestore.v1.IDocument, + protos.google.firestore.v1.IGetDocumentRequest | undefined, + {} | undefined, + ] + >; getDocument( - request: protos.google.firestore.v1.IGetDocumentRequest, - options: CallOptions, - callback: Callback< - protos.google.firestore.v1.IDocument, - protos.google.firestore.v1.IGetDocumentRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.firestore.v1.IGetDocumentRequest, + options: CallOptions, + callback: Callback< + protos.google.firestore.v1.IDocument, + protos.google.firestore.v1.IGetDocumentRequest | null | undefined, + {} | null | undefined + > + ): void; getDocument( - request: protos.google.firestore.v1.IGetDocumentRequest, - callback: Callback< - protos.google.firestore.v1.IDocument, - protos.google.firestore.v1.IGetDocumentRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.firestore.v1.IGetDocumentRequest, + callback: Callback< + protos.google.firestore.v1.IDocument, + protos.google.firestore.v1.IGetDocumentRequest | null | undefined, + {} | null | undefined + > + ): void; getDocument( - request?: protos.google.firestore.v1.IGetDocumentRequest, - optionsOrCallback?: CallOptions|Callback< - protos.google.firestore.v1.IDocument, - protos.google.firestore.v1.IGetDocumentRequest|null|undefined, - {}|null|undefined>, - callback?: Callback< + request?: protos.google.firestore.v1.IGetDocumentRequest, + optionsOrCallback?: + | CallOptions + | Callback< protos.google.firestore.v1.IDocument, - protos.google.firestore.v1.IGetDocumentRequest|null|undefined, - {}|null|undefined>): - Promise<[ - protos.google.firestore.v1.IDocument, - protos.google.firestore.v1.IGetDocumentRequest|undefined, {}|undefined - ]>|void { + protos.google.firestore.v1.IGetDocumentRequest | null | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.firestore.v1.IDocument, + protos.google.firestore.v1.IGetDocumentRequest | null | undefined, + {} | null | undefined + > + ): Promise< + [ + protos.google.firestore.v1.IDocument, + protos.google.firestore.v1.IGetDocumentRequest | undefined, + {} | undefined, + ] + > | void { request = request || {}; let options: CallOptions; if (typeof optionsOrCallback === 'function' && callback === undefined) { callback = optionsOrCallback; options = {}; - } - else { + } else { options = optionsOrCallback as CallOptions; } options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - options.otherArgs.headers[ - 'x-goog-request-params' - ] = this._gaxModule.routingHeader.fromParams({ - 'name': request.name ?? '', + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + name: request.name ?? '', + }); + this.initialize().catch(err => { + throw err; }); - this.initialize().catch(err => {throw err}); this._log.info('getDocument request %j', request); - const wrappedCallback: Callback< - protos.google.firestore.v1.IDocument, - protos.google.firestore.v1.IGetDocumentRequest|null|undefined, - {}|null|undefined>|undefined = callback + const wrappedCallback: + | Callback< + protos.google.firestore.v1.IDocument, + protos.google.firestore.v1.IGetDocumentRequest | null | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, options, rawResponse) => { this._log.info('getDocument response %j', response); callback!(error, response, options, rawResponse); // We verified callback above. } : undefined; - return this.innerApiCalls.getDocument(request, options, wrappedCallback) - ?.then(([response, options, rawResponse]: [ - protos.google.firestore.v1.IDocument, - protos.google.firestore.v1.IGetDocumentRequest|undefined, - {}|undefined - ]) => { - this._log.info('getDocument response %j', response); - return [response, options, rawResponse]; - }); + return this.innerApiCalls + .getDocument(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.firestore.v1.IDocument, + protos.google.firestore.v1.IGetDocumentRequest | undefined, + {} | undefined, + ]) => { + this._log.info('getDocument response %j', response); + return [response, options, rawResponse]; + } + ); } -/** - * Updates or inserts a document. - * - * @param {Object} request - * The request object that will be sent. - * @param {google.firestore.v1.Document} request.document - * Required. The updated document. - * Creates the document if it does not already exist. - * @param {google.firestore.v1.DocumentMask} request.updateMask - * The fields to update. - * None of the field paths in the mask may contain a reserved name. - * - * If the document exists on the server and has fields not referenced in the - * mask, they are left unchanged. - * Fields referenced in the mask, but not present in the input document, are - * deleted from the document on the server. - * @param {google.firestore.v1.DocumentMask} request.mask - * The fields to return. If not set, returns all fields. - * - * If the document has a field that is not present in this mask, that field - * will not be returned in the response. - * @param {google.firestore.v1.Precondition} request.currentDocument - * An optional precondition on the document. - * The request will fail if this is set and not met by the target document. - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Promise} - The promise which resolves to an array. - * The first element of the array is an object representing {@link protos.google.firestore.v1.Document|Document}. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } - * for more details and examples. - * @example - * region_tag:firestore_v1_generated_Firestore_UpdateDocument_async - */ + /** + * Updates or inserts a document. + * + * @param {Object} request + * The request object that will be sent. + * @param {google.firestore.v1.Document} request.document + * Required. The updated document. + * Creates the document if it does not already exist. + * @param {google.firestore.v1.DocumentMask} request.updateMask + * The fields to update. + * None of the field paths in the mask may contain a reserved name. + * + * If the document exists on the server and has fields not referenced in the + * mask, they are left unchanged. + * Fields referenced in the mask, but not present in the input document, are + * deleted from the document on the server. + * @param {google.firestore.v1.DocumentMask} request.mask + * The fields to return. If not set, returns all fields. + * + * If the document has a field that is not present in this mask, that field + * will not be returned in the response. + * @param {google.firestore.v1.Precondition} request.currentDocument + * An optional precondition on the document. + * The request will fail if this is set and not met by the target document. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is an object representing {@link protos.google.firestore.v1.Document|Document}. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } + * for more details and examples. + * @example + * region_tag:firestore_v1_generated_Firestore_UpdateDocument_async + */ updateDocument( - request?: protos.google.firestore.v1.IUpdateDocumentRequest, - options?: CallOptions): - Promise<[ - protos.google.firestore.v1.IDocument, - protos.google.firestore.v1.IUpdateDocumentRequest|undefined, {}|undefined - ]>; + request?: protos.google.firestore.v1.IUpdateDocumentRequest, + options?: CallOptions + ): Promise< + [ + protos.google.firestore.v1.IDocument, + protos.google.firestore.v1.IUpdateDocumentRequest | undefined, + {} | undefined, + ] + >; updateDocument( - request: protos.google.firestore.v1.IUpdateDocumentRequest, - options: CallOptions, - callback: Callback< - protos.google.firestore.v1.IDocument, - protos.google.firestore.v1.IUpdateDocumentRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.firestore.v1.IUpdateDocumentRequest, + options: CallOptions, + callback: Callback< + protos.google.firestore.v1.IDocument, + protos.google.firestore.v1.IUpdateDocumentRequest | null | undefined, + {} | null | undefined + > + ): void; updateDocument( - request: protos.google.firestore.v1.IUpdateDocumentRequest, - callback: Callback< - protos.google.firestore.v1.IDocument, - protos.google.firestore.v1.IUpdateDocumentRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.firestore.v1.IUpdateDocumentRequest, + callback: Callback< + protos.google.firestore.v1.IDocument, + protos.google.firestore.v1.IUpdateDocumentRequest | null | undefined, + {} | null | undefined + > + ): void; updateDocument( - request?: protos.google.firestore.v1.IUpdateDocumentRequest, - optionsOrCallback?: CallOptions|Callback< - protos.google.firestore.v1.IDocument, - protos.google.firestore.v1.IUpdateDocumentRequest|null|undefined, - {}|null|undefined>, - callback?: Callback< + request?: protos.google.firestore.v1.IUpdateDocumentRequest, + optionsOrCallback?: + | CallOptions + | Callback< protos.google.firestore.v1.IDocument, - protos.google.firestore.v1.IUpdateDocumentRequest|null|undefined, - {}|null|undefined>): - Promise<[ - protos.google.firestore.v1.IDocument, - protos.google.firestore.v1.IUpdateDocumentRequest|undefined, {}|undefined - ]>|void { + protos.google.firestore.v1.IUpdateDocumentRequest | null | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.firestore.v1.IDocument, + protos.google.firestore.v1.IUpdateDocumentRequest | null | undefined, + {} | null | undefined + > + ): Promise< + [ + protos.google.firestore.v1.IDocument, + protos.google.firestore.v1.IUpdateDocumentRequest | undefined, + {} | undefined, + ] + > | void { request = request || {}; let options: CallOptions; if (typeof optionsOrCallback === 'function' && callback === undefined) { callback = optionsOrCallback; options = {}; - } - else { + } else { options = optionsOrCallback as CallOptions; } options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - options.otherArgs.headers[ - 'x-goog-request-params' - ] = this._gaxModule.routingHeader.fromParams({ - 'document.name': request.document!.name ?? '', + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + 'document.name': request.document!.name ?? '', + }); + this.initialize().catch(err => { + throw err; }); - this.initialize().catch(err => {throw err}); this._log.info('updateDocument request %j', request); - const wrappedCallback: Callback< - protos.google.firestore.v1.IDocument, - protos.google.firestore.v1.IUpdateDocumentRequest|null|undefined, - {}|null|undefined>|undefined = callback + const wrappedCallback: + | Callback< + protos.google.firestore.v1.IDocument, + protos.google.firestore.v1.IUpdateDocumentRequest | null | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, options, rawResponse) => { this._log.info('updateDocument response %j', response); callback!(error, response, options, rawResponse); // We verified callback above. } : undefined; - return this.innerApiCalls.updateDocument(request, options, wrappedCallback) - ?.then(([response, options, rawResponse]: [ - protos.google.firestore.v1.IDocument, - protos.google.firestore.v1.IUpdateDocumentRequest|undefined, - {}|undefined - ]) => { - this._log.info('updateDocument response %j', response); - return [response, options, rawResponse]; - }); + return this.innerApiCalls + .updateDocument(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.firestore.v1.IDocument, + protos.google.firestore.v1.IUpdateDocumentRequest | undefined, + {} | undefined, + ]) => { + this._log.info('updateDocument response %j', response); + return [response, options, rawResponse]; + } + ); } -/** - * Deletes a document. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.name - * Required. The resource name of the Document to delete. In the format: - * `projects/{project_id}/databases/{database_id}/documents/{document_path}`. - * @param {google.firestore.v1.Precondition} request.currentDocument - * An optional precondition on the document. - * The request will fail if this is set and not met by the target document. - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Promise} - The promise which resolves to an array. - * The first element of the array is an object representing {@link protos.google.protobuf.Empty|Empty}. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } - * for more details and examples. - * @example - * region_tag:firestore_v1_generated_Firestore_DeleteDocument_async - */ + /** + * Deletes a document. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.name + * Required. The resource name of the Document to delete. In the format: + * `projects/{project_id}/databases/{database_id}/documents/{document_path}`. + * @param {google.firestore.v1.Precondition} request.currentDocument + * An optional precondition on the document. + * The request will fail if this is set and not met by the target document. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is an object representing {@link protos.google.protobuf.Empty|Empty}. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } + * for more details and examples. + * @example + * region_tag:firestore_v1_generated_Firestore_DeleteDocument_async + */ deleteDocument( - request?: protos.google.firestore.v1.IDeleteDocumentRequest, - options?: CallOptions): - Promise<[ - protos.google.protobuf.IEmpty, - protos.google.firestore.v1.IDeleteDocumentRequest|undefined, {}|undefined - ]>; + request?: protos.google.firestore.v1.IDeleteDocumentRequest, + options?: CallOptions + ): Promise< + [ + protos.google.protobuf.IEmpty, + protos.google.firestore.v1.IDeleteDocumentRequest | undefined, + {} | undefined, + ] + >; deleteDocument( - request: protos.google.firestore.v1.IDeleteDocumentRequest, - options: CallOptions, - callback: Callback< - protos.google.protobuf.IEmpty, - protos.google.firestore.v1.IDeleteDocumentRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.firestore.v1.IDeleteDocumentRequest, + options: CallOptions, + callback: Callback< + protos.google.protobuf.IEmpty, + protos.google.firestore.v1.IDeleteDocumentRequest | null | undefined, + {} | null | undefined + > + ): void; deleteDocument( - request: protos.google.firestore.v1.IDeleteDocumentRequest, - callback: Callback< - protos.google.protobuf.IEmpty, - protos.google.firestore.v1.IDeleteDocumentRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.firestore.v1.IDeleteDocumentRequest, + callback: Callback< + protos.google.protobuf.IEmpty, + protos.google.firestore.v1.IDeleteDocumentRequest | null | undefined, + {} | null | undefined + > + ): void; deleteDocument( - request?: protos.google.firestore.v1.IDeleteDocumentRequest, - optionsOrCallback?: CallOptions|Callback< - protos.google.protobuf.IEmpty, - protos.google.firestore.v1.IDeleteDocumentRequest|null|undefined, - {}|null|undefined>, - callback?: Callback< + request?: protos.google.firestore.v1.IDeleteDocumentRequest, + optionsOrCallback?: + | CallOptions + | Callback< protos.google.protobuf.IEmpty, - protos.google.firestore.v1.IDeleteDocumentRequest|null|undefined, - {}|null|undefined>): - Promise<[ - protos.google.protobuf.IEmpty, - protos.google.firestore.v1.IDeleteDocumentRequest|undefined, {}|undefined - ]>|void { + protos.google.firestore.v1.IDeleteDocumentRequest | null | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.protobuf.IEmpty, + protos.google.firestore.v1.IDeleteDocumentRequest | null | undefined, + {} | null | undefined + > + ): Promise< + [ + protos.google.protobuf.IEmpty, + protos.google.firestore.v1.IDeleteDocumentRequest | undefined, + {} | undefined, + ] + > | void { request = request || {}; let options: CallOptions; if (typeof optionsOrCallback === 'function' && callback === undefined) { callback = optionsOrCallback; options = {}; - } - else { + } else { options = optionsOrCallback as CallOptions; } options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - options.otherArgs.headers[ - 'x-goog-request-params' - ] = this._gaxModule.routingHeader.fromParams({ - 'name': request.name ?? '', + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + name: request.name ?? '', + }); + this.initialize().catch(err => { + throw err; }); - this.initialize().catch(err => {throw err}); this._log.info('deleteDocument request %j', request); - const wrappedCallback: Callback< - protos.google.protobuf.IEmpty, - protos.google.firestore.v1.IDeleteDocumentRequest|null|undefined, - {}|null|undefined>|undefined = callback + const wrappedCallback: + | Callback< + protos.google.protobuf.IEmpty, + protos.google.firestore.v1.IDeleteDocumentRequest | null | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, options, rawResponse) => { this._log.info('deleteDocument response %j', response); callback!(error, response, options, rawResponse); // We verified callback above. } : undefined; - return this.innerApiCalls.deleteDocument(request, options, wrappedCallback) - ?.then(([response, options, rawResponse]: [ - protos.google.protobuf.IEmpty, - protos.google.firestore.v1.IDeleteDocumentRequest|undefined, - {}|undefined - ]) => { - this._log.info('deleteDocument response %j', response); - return [response, options, rawResponse]; - }); + return this.innerApiCalls + .deleteDocument(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.protobuf.IEmpty, + protos.google.firestore.v1.IDeleteDocumentRequest | undefined, + {} | undefined, + ]) => { + this._log.info('deleteDocument response %j', response); + return [response, options, rawResponse]; + } + ); } -/** - * Starts a new transaction. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.database - * Required. The database name. In the format: - * `projects/{project_id}/databases/{database_id}`. - * @param {google.firestore.v1.TransactionOptions} request.options - * The options for the transaction. - * Defaults to a read-write transaction. - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Promise} - The promise which resolves to an array. - * The first element of the array is an object representing {@link protos.google.firestore.v1.BeginTransactionResponse|BeginTransactionResponse}. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } - * for more details and examples. - * @example - * region_tag:firestore_v1_generated_Firestore_BeginTransaction_async - */ + /** + * Starts a new transaction. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.database + * Required. The database name. In the format: + * `projects/{project_id}/databases/{database_id}`. + * @param {google.firestore.v1.TransactionOptions} request.options + * The options for the transaction. + * Defaults to a read-write transaction. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is an object representing {@link protos.google.firestore.v1.BeginTransactionResponse|BeginTransactionResponse}. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } + * for more details and examples. + * @example + * region_tag:firestore_v1_generated_Firestore_BeginTransaction_async + */ beginTransaction( - request?: protos.google.firestore.v1.IBeginTransactionRequest, - options?: CallOptions): - Promise<[ - protos.google.firestore.v1.IBeginTransactionResponse, - protos.google.firestore.v1.IBeginTransactionRequest|undefined, {}|undefined - ]>; + request?: protos.google.firestore.v1.IBeginTransactionRequest, + options?: CallOptions + ): Promise< + [ + protos.google.firestore.v1.IBeginTransactionResponse, + protos.google.firestore.v1.IBeginTransactionRequest | undefined, + {} | undefined, + ] + >; beginTransaction( - request: protos.google.firestore.v1.IBeginTransactionRequest, - options: CallOptions, - callback: Callback< - protos.google.firestore.v1.IBeginTransactionResponse, - protos.google.firestore.v1.IBeginTransactionRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.firestore.v1.IBeginTransactionRequest, + options: CallOptions, + callback: Callback< + protos.google.firestore.v1.IBeginTransactionResponse, + protos.google.firestore.v1.IBeginTransactionRequest | null | undefined, + {} | null | undefined + > + ): void; beginTransaction( - request: protos.google.firestore.v1.IBeginTransactionRequest, - callback: Callback< - protos.google.firestore.v1.IBeginTransactionResponse, - protos.google.firestore.v1.IBeginTransactionRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.firestore.v1.IBeginTransactionRequest, + callback: Callback< + protos.google.firestore.v1.IBeginTransactionResponse, + protos.google.firestore.v1.IBeginTransactionRequest | null | undefined, + {} | null | undefined + > + ): void; beginTransaction( - request?: protos.google.firestore.v1.IBeginTransactionRequest, - optionsOrCallback?: CallOptions|Callback< - protos.google.firestore.v1.IBeginTransactionResponse, - protos.google.firestore.v1.IBeginTransactionRequest|null|undefined, - {}|null|undefined>, - callback?: Callback< + request?: protos.google.firestore.v1.IBeginTransactionRequest, + optionsOrCallback?: + | CallOptions + | Callback< protos.google.firestore.v1.IBeginTransactionResponse, - protos.google.firestore.v1.IBeginTransactionRequest|null|undefined, - {}|null|undefined>): - Promise<[ - protos.google.firestore.v1.IBeginTransactionResponse, - protos.google.firestore.v1.IBeginTransactionRequest|undefined, {}|undefined - ]>|void { + | protos.google.firestore.v1.IBeginTransactionRequest + | null + | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.firestore.v1.IBeginTransactionResponse, + protos.google.firestore.v1.IBeginTransactionRequest | null | undefined, + {} | null | undefined + > + ): Promise< + [ + protos.google.firestore.v1.IBeginTransactionResponse, + protos.google.firestore.v1.IBeginTransactionRequest | undefined, + {} | undefined, + ] + > | void { request = request || {}; let options: CallOptions; if (typeof optionsOrCallback === 'function' && callback === undefined) { callback = optionsOrCallback; options = {}; - } - else { + } else { options = optionsOrCallback as CallOptions; } options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - options.otherArgs.headers[ - 'x-goog-request-params' - ] = this._gaxModule.routingHeader.fromParams({ - 'database': request.database ?? '', + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + database: request.database ?? '', + }); + this.initialize().catch(err => { + throw err; }); - this.initialize().catch(err => {throw err}); this._log.info('beginTransaction request %j', request); - const wrappedCallback: Callback< - protos.google.firestore.v1.IBeginTransactionResponse, - protos.google.firestore.v1.IBeginTransactionRequest|null|undefined, - {}|null|undefined>|undefined = callback + const wrappedCallback: + | Callback< + protos.google.firestore.v1.IBeginTransactionResponse, + | protos.google.firestore.v1.IBeginTransactionRequest + | null + | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, options, rawResponse) => { this._log.info('beginTransaction response %j', response); callback!(error, response, options, rawResponse); // We verified callback above. } : undefined; - return this.innerApiCalls.beginTransaction(request, options, wrappedCallback) - ?.then(([response, options, rawResponse]: [ - protos.google.firestore.v1.IBeginTransactionResponse, - protos.google.firestore.v1.IBeginTransactionRequest|undefined, - {}|undefined - ]) => { - this._log.info('beginTransaction response %j', response); - return [response, options, rawResponse]; - }); + return this.innerApiCalls + .beginTransaction(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.firestore.v1.IBeginTransactionResponse, + protos.google.firestore.v1.IBeginTransactionRequest | undefined, + {} | undefined, + ]) => { + this._log.info('beginTransaction response %j', response); + return [response, options, rawResponse]; + } + ); } -/** - * Commits a transaction, while optionally updating documents. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.database - * Required. The database name. In the format: - * `projects/{project_id}/databases/{database_id}`. - * @param {number[]} request.writes - * The writes to apply. - * - * Always executed atomically and in order. - * @param {Buffer} request.transaction - * If set, applies all writes in this transaction, and commits it. - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Promise} - The promise which resolves to an array. - * The first element of the array is an object representing {@link protos.google.firestore.v1.CommitResponse|CommitResponse}. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } - * for more details and examples. - * @example - * region_tag:firestore_v1_generated_Firestore_Commit_async - */ + /** + * Commits a transaction, while optionally updating documents. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.database + * Required. The database name. In the format: + * `projects/{project_id}/databases/{database_id}`. + * @param {number[]} request.writes + * The writes to apply. + * + * Always executed atomically and in order. + * @param {Buffer} request.transaction + * If set, applies all writes in this transaction, and commits it. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is an object representing {@link protos.google.firestore.v1.CommitResponse|CommitResponse}. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } + * for more details and examples. + * @example + * region_tag:firestore_v1_generated_Firestore_Commit_async + */ commit( - request?: protos.google.firestore.v1.ICommitRequest, - options?: CallOptions): - Promise<[ - protos.google.firestore.v1.ICommitResponse, - protos.google.firestore.v1.ICommitRequest|undefined, {}|undefined - ]>; + request?: protos.google.firestore.v1.ICommitRequest, + options?: CallOptions + ): Promise< + [ + protos.google.firestore.v1.ICommitResponse, + protos.google.firestore.v1.ICommitRequest | undefined, + {} | undefined, + ] + >; commit( - request: protos.google.firestore.v1.ICommitRequest, - options: CallOptions, - callback: Callback< - protos.google.firestore.v1.ICommitResponse, - protos.google.firestore.v1.ICommitRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.firestore.v1.ICommitRequest, + options: CallOptions, + callback: Callback< + protos.google.firestore.v1.ICommitResponse, + protos.google.firestore.v1.ICommitRequest | null | undefined, + {} | null | undefined + > + ): void; commit( - request: protos.google.firestore.v1.ICommitRequest, - callback: Callback< - protos.google.firestore.v1.ICommitResponse, - protos.google.firestore.v1.ICommitRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.firestore.v1.ICommitRequest, + callback: Callback< + protos.google.firestore.v1.ICommitResponse, + protos.google.firestore.v1.ICommitRequest | null | undefined, + {} | null | undefined + > + ): void; commit( - request?: protos.google.firestore.v1.ICommitRequest, - optionsOrCallback?: CallOptions|Callback< - protos.google.firestore.v1.ICommitResponse, - protos.google.firestore.v1.ICommitRequest|null|undefined, - {}|null|undefined>, - callback?: Callback< + request?: protos.google.firestore.v1.ICommitRequest, + optionsOrCallback?: + | CallOptions + | Callback< protos.google.firestore.v1.ICommitResponse, - protos.google.firestore.v1.ICommitRequest|null|undefined, - {}|null|undefined>): - Promise<[ - protos.google.firestore.v1.ICommitResponse, - protos.google.firestore.v1.ICommitRequest|undefined, {}|undefined - ]>|void { + protos.google.firestore.v1.ICommitRequest | null | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.firestore.v1.ICommitResponse, + protos.google.firestore.v1.ICommitRequest | null | undefined, + {} | null | undefined + > + ): Promise< + [ + protos.google.firestore.v1.ICommitResponse, + protos.google.firestore.v1.ICommitRequest | undefined, + {} | undefined, + ] + > | void { request = request || {}; let options: CallOptions; if (typeof optionsOrCallback === 'function' && callback === undefined) { callback = optionsOrCallback; options = {}; - } - else { + } else { options = optionsOrCallback as CallOptions; } options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - options.otherArgs.headers[ - 'x-goog-request-params' - ] = this._gaxModule.routingHeader.fromParams({ - 'database': request.database ?? '', + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + database: request.database ?? '', + }); + this.initialize().catch(err => { + throw err; }); - this.initialize().catch(err => {throw err}); this._log.info('commit request %j', request); - const wrappedCallback: Callback< - protos.google.firestore.v1.ICommitResponse, - protos.google.firestore.v1.ICommitRequest|null|undefined, - {}|null|undefined>|undefined = callback + const wrappedCallback: + | Callback< + protos.google.firestore.v1.ICommitResponse, + protos.google.firestore.v1.ICommitRequest | null | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, options, rawResponse) => { this._log.info('commit response %j', response); callback!(error, response, options, rawResponse); // We verified callback above. } : undefined; - return this.innerApiCalls.commit(request, options, wrappedCallback) - ?.then(([response, options, rawResponse]: [ - protos.google.firestore.v1.ICommitResponse, - protos.google.firestore.v1.ICommitRequest|undefined, - {}|undefined - ]) => { - this._log.info('commit response %j', response); - return [response, options, rawResponse]; - }); + return this.innerApiCalls + .commit(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.firestore.v1.ICommitResponse, + protos.google.firestore.v1.ICommitRequest | undefined, + {} | undefined, + ]) => { + this._log.info('commit response %j', response); + return [response, options, rawResponse]; + } + ); } -/** - * Rolls back a transaction. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.database - * Required. The database name. In the format: - * `projects/{project_id}/databases/{database_id}`. - * @param {Buffer} request.transaction - * Required. The transaction to roll back. - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Promise} - The promise which resolves to an array. - * The first element of the array is an object representing {@link protos.google.protobuf.Empty|Empty}. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } - * for more details and examples. - * @example - * region_tag:firestore_v1_generated_Firestore_Rollback_async - */ + /** + * Rolls back a transaction. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.database + * Required. The database name. In the format: + * `projects/{project_id}/databases/{database_id}`. + * @param {Buffer} request.transaction + * Required. The transaction to roll back. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is an object representing {@link protos.google.protobuf.Empty|Empty}. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } + * for more details and examples. + * @example + * region_tag:firestore_v1_generated_Firestore_Rollback_async + */ rollback( - request?: protos.google.firestore.v1.IRollbackRequest, - options?: CallOptions): - Promise<[ - protos.google.protobuf.IEmpty, - protos.google.firestore.v1.IRollbackRequest|undefined, {}|undefined - ]>; + request?: protos.google.firestore.v1.IRollbackRequest, + options?: CallOptions + ): Promise< + [ + protos.google.protobuf.IEmpty, + protos.google.firestore.v1.IRollbackRequest | undefined, + {} | undefined, + ] + >; rollback( - request: protos.google.firestore.v1.IRollbackRequest, - options: CallOptions, - callback: Callback< - protos.google.protobuf.IEmpty, - protos.google.firestore.v1.IRollbackRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.firestore.v1.IRollbackRequest, + options: CallOptions, + callback: Callback< + protos.google.protobuf.IEmpty, + protos.google.firestore.v1.IRollbackRequest | null | undefined, + {} | null | undefined + > + ): void; rollback( - request: protos.google.firestore.v1.IRollbackRequest, - callback: Callback< - protos.google.protobuf.IEmpty, - protos.google.firestore.v1.IRollbackRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.firestore.v1.IRollbackRequest, + callback: Callback< + protos.google.protobuf.IEmpty, + protos.google.firestore.v1.IRollbackRequest | null | undefined, + {} | null | undefined + > + ): void; rollback( - request?: protos.google.firestore.v1.IRollbackRequest, - optionsOrCallback?: CallOptions|Callback< - protos.google.protobuf.IEmpty, - protos.google.firestore.v1.IRollbackRequest|null|undefined, - {}|null|undefined>, - callback?: Callback< + request?: protos.google.firestore.v1.IRollbackRequest, + optionsOrCallback?: + | CallOptions + | Callback< protos.google.protobuf.IEmpty, - protos.google.firestore.v1.IRollbackRequest|null|undefined, - {}|null|undefined>): - Promise<[ - protos.google.protobuf.IEmpty, - protos.google.firestore.v1.IRollbackRequest|undefined, {}|undefined - ]>|void { + protos.google.firestore.v1.IRollbackRequest | null | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.protobuf.IEmpty, + protos.google.firestore.v1.IRollbackRequest | null | undefined, + {} | null | undefined + > + ): Promise< + [ + protos.google.protobuf.IEmpty, + protos.google.firestore.v1.IRollbackRequest | undefined, + {} | undefined, + ] + > | void { request = request || {}; let options: CallOptions; if (typeof optionsOrCallback === 'function' && callback === undefined) { callback = optionsOrCallback; options = {}; - } - else { + } else { options = optionsOrCallback as CallOptions; } options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - options.otherArgs.headers[ - 'x-goog-request-params' - ] = this._gaxModule.routingHeader.fromParams({ - 'database': request.database ?? '', + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + database: request.database ?? '', + }); + this.initialize().catch(err => { + throw err; }); - this.initialize().catch(err => {throw err}); this._log.info('rollback request %j', request); - const wrappedCallback: Callback< - protos.google.protobuf.IEmpty, - protos.google.firestore.v1.IRollbackRequest|null|undefined, - {}|null|undefined>|undefined = callback + const wrappedCallback: + | Callback< + protos.google.protobuf.IEmpty, + protos.google.firestore.v1.IRollbackRequest | null | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, options, rawResponse) => { this._log.info('rollback response %j', response); callback!(error, response, options, rawResponse); // We verified callback above. } : undefined; - return this.innerApiCalls.rollback(request, options, wrappedCallback) - ?.then(([response, options, rawResponse]: [ - protos.google.protobuf.IEmpty, - protos.google.firestore.v1.IRollbackRequest|undefined, - {}|undefined - ]) => { - this._log.info('rollback response %j', response); - return [response, options, rawResponse]; - }); - } -/** - * Applies a batch of write operations. - * - * The BatchWrite method does not apply the write operations atomically - * and can apply them out of order. Method does not allow more than one write - * per document. Each write succeeds or fails independently. See the - * {@link protos.google.firestore.v1.BatchWriteResponse|BatchWriteResponse} for the - * success status of each write. - * - * If you require an atomically applied set of writes, use - * {@link protos.google.firestore.v1.Firestore.Commit|Commit} instead. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.database - * Required. The database name. In the format: - * `projects/{project_id}/databases/{database_id}`. - * @param {number[]} request.writes - * The writes to apply. - * - * Method does not apply writes atomically and does not guarantee ordering. - * Each write succeeds or fails independently. You cannot write to the same - * document more than once per request. - * @param {number[]} request.labels - * Labels associated with this batch write. - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Promise} - The promise which resolves to an array. - * The first element of the array is an object representing {@link protos.google.firestore.v1.BatchWriteResponse|BatchWriteResponse}. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } - * for more details and examples. - * @example - * region_tag:firestore_v1_generated_Firestore_BatchWrite_async - */ + return this.innerApiCalls + .rollback(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.protobuf.IEmpty, + protos.google.firestore.v1.IRollbackRequest | undefined, + {} | undefined, + ]) => { + this._log.info('rollback response %j', response); + return [response, options, rawResponse]; + } + ); + } + /** + * Applies a batch of write operations. + * + * The BatchWrite method does not apply the write operations atomically + * and can apply them out of order. Method does not allow more than one write + * per document. Each write succeeds or fails independently. See the + * {@link protos.google.firestore.v1.BatchWriteResponse|BatchWriteResponse} for the + * success status of each write. + * + * If you require an atomically applied set of writes, use + * {@link protos.google.firestore.v1.Firestore.Commit|Commit} instead. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.database + * Required. The database name. In the format: + * `projects/{project_id}/databases/{database_id}`. + * @param {number[]} request.writes + * The writes to apply. + * + * Method does not apply writes atomically and does not guarantee ordering. + * Each write succeeds or fails independently. You cannot write to the same + * document more than once per request. + * @param {number[]} request.labels + * Labels associated with this batch write. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is an object representing {@link protos.google.firestore.v1.BatchWriteResponse|BatchWriteResponse}. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } + * for more details and examples. + * @example + * region_tag:firestore_v1_generated_Firestore_BatchWrite_async + */ batchWrite( - request?: protos.google.firestore.v1.IBatchWriteRequest, - options?: CallOptions): - Promise<[ - protos.google.firestore.v1.IBatchWriteResponse, - protos.google.firestore.v1.IBatchWriteRequest|undefined, {}|undefined - ]>; + request?: protos.google.firestore.v1.IBatchWriteRequest, + options?: CallOptions + ): Promise< + [ + protos.google.firestore.v1.IBatchWriteResponse, + protos.google.firestore.v1.IBatchWriteRequest | undefined, + {} | undefined, + ] + >; batchWrite( - request: protos.google.firestore.v1.IBatchWriteRequest, - options: CallOptions, - callback: Callback< - protos.google.firestore.v1.IBatchWriteResponse, - protos.google.firestore.v1.IBatchWriteRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.firestore.v1.IBatchWriteRequest, + options: CallOptions, + callback: Callback< + protos.google.firestore.v1.IBatchWriteResponse, + protos.google.firestore.v1.IBatchWriteRequest | null | undefined, + {} | null | undefined + > + ): void; batchWrite( - request: protos.google.firestore.v1.IBatchWriteRequest, - callback: Callback< - protos.google.firestore.v1.IBatchWriteResponse, - protos.google.firestore.v1.IBatchWriteRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.firestore.v1.IBatchWriteRequest, + callback: Callback< + protos.google.firestore.v1.IBatchWriteResponse, + protos.google.firestore.v1.IBatchWriteRequest | null | undefined, + {} | null | undefined + > + ): void; batchWrite( - request?: protos.google.firestore.v1.IBatchWriteRequest, - optionsOrCallback?: CallOptions|Callback< - protos.google.firestore.v1.IBatchWriteResponse, - protos.google.firestore.v1.IBatchWriteRequest|null|undefined, - {}|null|undefined>, - callback?: Callback< + request?: protos.google.firestore.v1.IBatchWriteRequest, + optionsOrCallback?: + | CallOptions + | Callback< protos.google.firestore.v1.IBatchWriteResponse, - protos.google.firestore.v1.IBatchWriteRequest|null|undefined, - {}|null|undefined>): - Promise<[ - protos.google.firestore.v1.IBatchWriteResponse, - protos.google.firestore.v1.IBatchWriteRequest|undefined, {}|undefined - ]>|void { + protos.google.firestore.v1.IBatchWriteRequest | null | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.firestore.v1.IBatchWriteResponse, + protos.google.firestore.v1.IBatchWriteRequest | null | undefined, + {} | null | undefined + > + ): Promise< + [ + protos.google.firestore.v1.IBatchWriteResponse, + protos.google.firestore.v1.IBatchWriteRequest | undefined, + {} | undefined, + ] + > | void { request = request || {}; let options: CallOptions; if (typeof optionsOrCallback === 'function' && callback === undefined) { callback = optionsOrCallback; options = {}; - } - else { + } else { options = optionsOrCallback as CallOptions; } options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - options.otherArgs.headers[ - 'x-goog-request-params' - ] = this._gaxModule.routingHeader.fromParams({ - 'database': request.database ?? '', + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + database: request.database ?? '', + }); + this.initialize().catch(err => { + throw err; }); - this.initialize().catch(err => {throw err}); this._log.info('batchWrite request %j', request); - const wrappedCallback: Callback< - protos.google.firestore.v1.IBatchWriteResponse, - protos.google.firestore.v1.IBatchWriteRequest|null|undefined, - {}|null|undefined>|undefined = callback + const wrappedCallback: + | Callback< + protos.google.firestore.v1.IBatchWriteResponse, + protos.google.firestore.v1.IBatchWriteRequest | null | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, options, rawResponse) => { this._log.info('batchWrite response %j', response); callback!(error, response, options, rawResponse); // We verified callback above. } : undefined; - return this.innerApiCalls.batchWrite(request, options, wrappedCallback) - ?.then(([response, options, rawResponse]: [ - protos.google.firestore.v1.IBatchWriteResponse, - protos.google.firestore.v1.IBatchWriteRequest|undefined, - {}|undefined - ]) => { - this._log.info('batchWrite response %j', response); - return [response, options, rawResponse]; - }); + return this.innerApiCalls + .batchWrite(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.firestore.v1.IBatchWriteResponse, + protos.google.firestore.v1.IBatchWriteRequest | undefined, + {} | undefined, + ]) => { + this._log.info('batchWrite response %j', response); + return [response, options, rawResponse]; + } + ); } -/** - * Creates a new document. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.parent - * Required. The parent resource. For example: - * `projects/{project_id}/databases/{database_id}/documents` or - * `projects/{project_id}/databases/{database_id}/documents/chatrooms/{chatroom_id}` - * @param {string} request.collectionId - * Required. The collection ID, relative to `parent`, to list. For example: - * `chatrooms`. - * @param {string} request.documentId - * The client-assigned document ID to use for this document. - * - * Optional. If not specified, an ID will be assigned by the service. - * @param {google.firestore.v1.Document} request.document - * Required. The document to create. `name` must not be set. - * @param {google.firestore.v1.DocumentMask} request.mask - * The fields to return. If not set, returns all fields. - * - * If the document has a field that is not present in this mask, that field - * will not be returned in the response. - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Promise} - The promise which resolves to an array. - * The first element of the array is an object representing {@link protos.google.firestore.v1.Document|Document}. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } - * for more details and examples. - * @example - * region_tag:firestore_v1_generated_Firestore_CreateDocument_async - */ + /** + * Creates a new document. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.parent + * Required. The parent resource. For example: + * `projects/{project_id}/databases/{database_id}/documents` or + * `projects/{project_id}/databases/{database_id}/documents/chatrooms/{chatroom_id}` + * @param {string} request.collectionId + * Required. The collection ID, relative to `parent`, to list. For example: + * `chatrooms`. + * @param {string} request.documentId + * The client-assigned document ID to use for this document. + * + * Optional. If not specified, an ID will be assigned by the service. + * @param {google.firestore.v1.Document} request.document + * Required. The document to create. `name` must not be set. + * @param {google.firestore.v1.DocumentMask} request.mask + * The fields to return. If not set, returns all fields. + * + * If the document has a field that is not present in this mask, that field + * will not be returned in the response. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is an object representing {@link protos.google.firestore.v1.Document|Document}. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods | documentation } + * for more details and examples. + * @example + * region_tag:firestore_v1_generated_Firestore_CreateDocument_async + */ createDocument( - request?: protos.google.firestore.v1.ICreateDocumentRequest, - options?: CallOptions): - Promise<[ - protos.google.firestore.v1.IDocument, - protos.google.firestore.v1.ICreateDocumentRequest|undefined, {}|undefined - ]>; + request?: protos.google.firestore.v1.ICreateDocumentRequest, + options?: CallOptions + ): Promise< + [ + protos.google.firestore.v1.IDocument, + protos.google.firestore.v1.ICreateDocumentRequest | undefined, + {} | undefined, + ] + >; createDocument( - request: protos.google.firestore.v1.ICreateDocumentRequest, - options: CallOptions, - callback: Callback< - protos.google.firestore.v1.IDocument, - protos.google.firestore.v1.ICreateDocumentRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.firestore.v1.ICreateDocumentRequest, + options: CallOptions, + callback: Callback< + protos.google.firestore.v1.IDocument, + protos.google.firestore.v1.ICreateDocumentRequest | null | undefined, + {} | null | undefined + > + ): void; createDocument( - request: protos.google.firestore.v1.ICreateDocumentRequest, - callback: Callback< - protos.google.firestore.v1.IDocument, - protos.google.firestore.v1.ICreateDocumentRequest|null|undefined, - {}|null|undefined>): void; + request: protos.google.firestore.v1.ICreateDocumentRequest, + callback: Callback< + protos.google.firestore.v1.IDocument, + protos.google.firestore.v1.ICreateDocumentRequest | null | undefined, + {} | null | undefined + > + ): void; createDocument( - request?: protos.google.firestore.v1.ICreateDocumentRequest, - optionsOrCallback?: CallOptions|Callback< - protos.google.firestore.v1.IDocument, - protos.google.firestore.v1.ICreateDocumentRequest|null|undefined, - {}|null|undefined>, - callback?: Callback< + request?: protos.google.firestore.v1.ICreateDocumentRequest, + optionsOrCallback?: + | CallOptions + | Callback< protos.google.firestore.v1.IDocument, - protos.google.firestore.v1.ICreateDocumentRequest|null|undefined, - {}|null|undefined>): - Promise<[ - protos.google.firestore.v1.IDocument, - protos.google.firestore.v1.ICreateDocumentRequest|undefined, {}|undefined - ]>|void { + protos.google.firestore.v1.ICreateDocumentRequest | null | undefined, + {} | null | undefined + >, + callback?: Callback< + protos.google.firestore.v1.IDocument, + protos.google.firestore.v1.ICreateDocumentRequest | null | undefined, + {} | null | undefined + > + ): Promise< + [ + protos.google.firestore.v1.IDocument, + protos.google.firestore.v1.ICreateDocumentRequest | undefined, + {} | undefined, + ] + > | void { request = request || {}; let options: CallOptions; if (typeof optionsOrCallback === 'function' && callback === undefined) { callback = optionsOrCallback; options = {}; - } - else { + } else { options = optionsOrCallback as CallOptions; } options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - options.otherArgs.headers[ - 'x-goog-request-params' - ] = this._gaxModule.routingHeader.fromParams({ - 'parent': request.parent ?? '', - 'collection_id': request.collectionId ?? '', + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + parent: request.parent ?? '', + collection_id: request.collectionId ?? '', + }); + this.initialize().catch(err => { + throw err; }); - this.initialize().catch(err => {throw err}); this._log.info('createDocument request %j', request); - const wrappedCallback: Callback< - protos.google.firestore.v1.IDocument, - protos.google.firestore.v1.ICreateDocumentRequest|null|undefined, - {}|null|undefined>|undefined = callback + const wrappedCallback: + | Callback< + protos.google.firestore.v1.IDocument, + protos.google.firestore.v1.ICreateDocumentRequest | null | undefined, + {} | null | undefined + > + | undefined = callback ? (error, response, options, rawResponse) => { this._log.info('createDocument response %j', response); callback!(error, response, options, rawResponse); // We verified callback above. } : undefined; - return this.innerApiCalls.createDocument(request, options, wrappedCallback) - ?.then(([response, options, rawResponse]: [ - protos.google.firestore.v1.IDocument, - protos.google.firestore.v1.ICreateDocumentRequest|undefined, - {}|undefined - ]) => { - this._log.info('createDocument response %j', response); - return [response, options, rawResponse]; - }); + return this.innerApiCalls + .createDocument(request, options, wrappedCallback) + ?.then( + ([response, options, rawResponse]: [ + protos.google.firestore.v1.IDocument, + protos.google.firestore.v1.ICreateDocumentRequest | undefined, + {} | undefined, + ]) => { + this._log.info('createDocument response %j', response); + return [response, options, rawResponse]; + } + ); } -/** - * Gets multiple documents. - * - * Documents returned by this method are not guaranteed to be returned in the - * same order that they were requested. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.database - * Required. The database name. In the format: - * `projects/{project_id}/databases/{database_id}`. - * @param {string[]} request.documents - * The names of the documents to retrieve. In the format: - * `projects/{project_id}/databases/{database_id}/documents/{document_path}`. - * The request will fail if any of the document is not a child resource of the - * given `database`. Duplicate names will be elided. - * @param {google.firestore.v1.DocumentMask} request.mask - * The fields to return. If not set, returns all fields. - * - * If a document has a field that is not present in this mask, that field will - * not be returned in the response. - * @param {Buffer} request.transaction - * Reads documents in a transaction. - * @param {google.firestore.v1.TransactionOptions} request.newTransaction - * Starts a new transaction and reads the documents. - * Defaults to a read-only transaction. - * The new transaction ID will be returned as the first response in the - * stream. - * @param {google.protobuf.Timestamp} request.readTime - * Reads documents as they were at the given time. - * - * This must be a microsecond precision timestamp within the past one hour, - * or if Point-in-Time Recovery is enabled, can additionally be a whole - * minute timestamp within the past 7 days. - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Stream} - * An object stream which emits {@link protos.google.firestore.v1.BatchGetDocumentsResponse|BatchGetDocumentsResponse} on 'data' event. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#server-streaming | documentation } - * for more details and examples. - * @example - * region_tag:firestore_v1_generated_Firestore_BatchGetDocuments_async - */ + /** + * Gets multiple documents. + * + * Documents returned by this method are not guaranteed to be returned in the + * same order that they were requested. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.database + * Required. The database name. In the format: + * `projects/{project_id}/databases/{database_id}`. + * @param {string[]} request.documents + * The names of the documents to retrieve. In the format: + * `projects/{project_id}/databases/{database_id}/documents/{document_path}`. + * The request will fail if any of the document is not a child resource of the + * given `database`. Duplicate names will be elided. + * @param {google.firestore.v1.DocumentMask} request.mask + * The fields to return. If not set, returns all fields. + * + * If a document has a field that is not present in this mask, that field will + * not be returned in the response. + * @param {Buffer} request.transaction + * Reads documents in a transaction. + * @param {google.firestore.v1.TransactionOptions} request.newTransaction + * Starts a new transaction and reads the documents. + * Defaults to a read-only transaction. + * The new transaction ID will be returned as the first response in the + * stream. + * @param {google.protobuf.Timestamp} request.readTime + * Reads documents as they were at the given time. + * + * This must be a microsecond precision timestamp within the past one hour, + * or if Point-in-Time Recovery is enabled, can additionally be a whole + * minute timestamp within the past 7 days. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Stream} + * An object stream which emits {@link protos.google.firestore.v1.BatchGetDocumentsResponse|BatchGetDocumentsResponse} on 'data' event. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#server-streaming | documentation } + * for more details and examples. + * @example + * region_tag:firestore_v1_generated_Firestore_BatchGetDocuments_async + */ batchGetDocuments( - request?: protos.google.firestore.v1.IBatchGetDocumentsRequest, - options?: CallOptions): - gax.CancellableStream{ + request?: protos.google.firestore.v1.IBatchGetDocumentsRequest, + options?: CallOptions + ): gax.CancellableStream { request = request || {}; options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - options.otherArgs.headers[ - 'x-goog-request-params' - ] = this._gaxModule.routingHeader.fromParams({ - 'database': request.database ?? '', + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + database: request.database ?? '', + }); + this.initialize().catch(err => { + throw err; }); - this.initialize().catch(err => {throw err}); this._log.info('batchGetDocuments stream %j', options); return this.innerApiCalls.batchGetDocuments(request, options); } -/** - * Runs a query. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.parent - * Required. The parent resource name. In the format: - * `projects/{project_id}/databases/{database_id}/documents` or - * `projects/{project_id}/databases/{database_id}/documents/{document_path}`. - * For example: - * `projects/my-project/databases/my-database/documents` or - * `projects/my-project/databases/my-database/documents/chatrooms/my-chatroom` - * @param {google.firestore.v1.StructuredQuery} request.structuredQuery - * A structured query. - * @param {Buffer} request.transaction - * Run the query within an already active transaction. - * - * The value here is the opaque transaction ID to execute the query in. - * @param {google.firestore.v1.TransactionOptions} request.newTransaction - * Starts a new transaction and reads the documents. - * Defaults to a read-only transaction. - * The new transaction ID will be returned as the first response in the - * stream. - * @param {google.protobuf.Timestamp} request.readTime - * Reads documents as they were at the given time. - * - * This must be a microsecond precision timestamp within the past one hour, - * or if Point-in-Time Recovery is enabled, can additionally be a whole - * minute timestamp within the past 7 days. - * @param {google.firestore.v1.ExplainOptions} [request.explainOptions] - * Optional. Explain options for the query. If set, additional query - * statistics will be returned. If not, only query results will be returned. - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Stream} - * An object stream which emits {@link protos.google.firestore.v1.RunQueryResponse|RunQueryResponse} on 'data' event. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#server-streaming | documentation } - * for more details and examples. - * @example - * region_tag:firestore_v1_generated_Firestore_RunQuery_async - */ + /** + * Runs a query. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.parent + * Required. The parent resource name. In the format: + * `projects/{project_id}/databases/{database_id}/documents` or + * `projects/{project_id}/databases/{database_id}/documents/{document_path}`. + * For example: + * `projects/my-project/databases/my-database/documents` or + * `projects/my-project/databases/my-database/documents/chatrooms/my-chatroom` + * @param {google.firestore.v1.StructuredQuery} request.structuredQuery + * A structured query. + * @param {Buffer} request.transaction + * Run the query within an already active transaction. + * + * The value here is the opaque transaction ID to execute the query in. + * @param {google.firestore.v1.TransactionOptions} request.newTransaction + * Starts a new transaction and reads the documents. + * Defaults to a read-only transaction. + * The new transaction ID will be returned as the first response in the + * stream. + * @param {google.protobuf.Timestamp} request.readTime + * Reads documents as they were at the given time. + * + * This must be a microsecond precision timestamp within the past one hour, + * or if Point-in-Time Recovery is enabled, can additionally be a whole + * minute timestamp within the past 7 days. + * @param {google.firestore.v1.ExplainOptions} [request.explainOptions] + * Optional. Explain options for the query. If set, additional query + * statistics will be returned. If not, only query results will be returned. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Stream} + * An object stream which emits {@link protos.google.firestore.v1.RunQueryResponse|RunQueryResponse} on 'data' event. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#server-streaming | documentation } + * for more details and examples. + * @example + * region_tag:firestore_v1_generated_Firestore_RunQuery_async + */ runQuery( - request?: protos.google.firestore.v1.IRunQueryRequest, - options?: CallOptions): - gax.CancellableStream{ + request?: protos.google.firestore.v1.IRunQueryRequest, + options?: CallOptions + ): gax.CancellableStream { request = request || {}; options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - options.otherArgs.headers[ - 'x-goog-request-params' - ] = this._gaxModule.routingHeader.fromParams({ - 'parent': request.parent ?? '', + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + parent: request.parent ?? '', + }); + this.initialize().catch(err => { + throw err; }); - this.initialize().catch(err => {throw err}); this._log.info('runQuery stream %j', options); return this.innerApiCalls.runQuery(request, options); } -/** - * Executes a pipeline query. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.database - * Required. Database identifier, in the form - * `projects/{project}/databases/{database}`. - * @param {google.firestore.v1.StructuredPipeline} request.structuredPipeline - * A pipelined operation. - * @param {Buffer} request.transaction - * Run the query within an already active transaction. - * - * The value here is the opaque transaction ID to execute the query in. - * @param {google.firestore.v1.TransactionOptions} request.newTransaction - * Execute the pipeline in a new transaction. - * - * The identifier of the newly created transaction will be returned in the - * first response on the stream. This defaults to a read-only transaction. - * @param {google.protobuf.Timestamp} request.readTime - * Execute the pipeline in a snapshot transaction at the given time. - * - * This must be a microsecond precision timestamp within the past one hour, - * or if Point-in-Time Recovery is enabled, can additionally be a whole - * minute timestamp within the past 7 days. - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Stream} - * An object stream which emits {@link protos.google.firestore.v1.ExecutePipelineResponse|ExecutePipelineResponse} on 'data' event. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#server-streaming | documentation } - * for more details and examples. - * @example - * region_tag:firestore_v1_generated_Firestore_ExecutePipeline_async - */ + /** + * Executes a pipeline query. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.database + * Required. Database identifier, in the form + * `projects/{project}/databases/{database}`. + * @param {google.firestore.v1.StructuredPipeline} request.structuredPipeline + * A pipelined operation. + * @param {Buffer} request.transaction + * Run the query within an already active transaction. + * + * The value here is the opaque transaction ID to execute the query in. + * @param {google.firestore.v1.TransactionOptions} request.newTransaction + * Execute the pipeline in a new transaction. + * + * The identifier of the newly created transaction will be returned in the + * first response on the stream. This defaults to a read-only transaction. + * @param {google.protobuf.Timestamp} request.readTime + * Execute the pipeline in a snapshot transaction at the given time. + * + * This must be a microsecond precision timestamp within the past one hour, + * or if Point-in-Time Recovery is enabled, can additionally be a whole + * minute timestamp within the past 7 days. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Stream} + * An object stream which emits {@link protos.google.firestore.v1.ExecutePipelineResponse|ExecutePipelineResponse} on 'data' event. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#server-streaming | documentation } + * for more details and examples. + * @example + * region_tag:firestore_v1_generated_Firestore_ExecutePipeline_async + */ executePipeline( - request?: protos.google.firestore.v1.IExecutePipelineRequest, - options?: CallOptions): - gax.CancellableStream{ + request?: protos.google.firestore.v1.IExecutePipelineRequest, + options?: CallOptions + ): gax.CancellableStream { request = request || {}; options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - let routingParameter = {}; + const routingParameter = {}; { const fieldValue = request.database; if (fieldValue !== undefined && fieldValue !== null) { - const match = fieldValue.toString().match(RegExp('projects/(?[^/]+)(?:/.*)?')); + const match = fieldValue + .toString() + .match(RegExp('projects/(?[^/]+)(?:/.*)?')); if (match) { const parameterValue = match.groups?.['project_id'] ?? fieldValue; - Object.assign(routingParameter, { project_id: parameterValue }); + Object.assign(routingParameter, {project_id: parameterValue}); } } } { const fieldValue = request.database; if (fieldValue !== undefined && fieldValue !== null) { - const match = fieldValue.toString().match(RegExp('projects/[^/]+/databases/(?[^/]+)(?:/.*)?')); + const match = fieldValue + .toString() + .match( + RegExp('projects/[^/]+/databases/(?[^/]+)(?:/.*)?') + ); if (match) { const parameterValue = match.groups?.['database_id'] ?? fieldValue; - Object.assign(routingParameter, { database_id: parameterValue }); + Object.assign(routingParameter, {database_id: parameterValue}); } } } - options.otherArgs.headers[ - 'x-goog-request-params' - ] = this._gaxModule.routingHeader.fromParams( - routingParameter - ); - this.initialize().catch(err => {throw err}); + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams(routingParameter); + this.initialize().catch(err => { + throw err; + }); this._log.info('executePipeline stream %j', options); return this.innerApiCalls.executePipeline(request, options); } -/** - * Runs an aggregation query. - * - * Rather than producing {@link protos.google.firestore.v1.Document|Document} results like - * {@link protos.google.firestore.v1.Firestore.RunQuery|Firestore.RunQuery}, this API - * allows running an aggregation to produce a series of - * {@link protos.google.firestore.v1.AggregationResult|AggregationResult} server-side. - * - * High-Level Example: - * - * ``` - * -- Return the number of documents in table given a filter. - * SELECT COUNT(*) FROM ( SELECT * FROM k where a = true ); - * ``` - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.parent - * Required. The parent resource name. In the format: - * `projects/{project_id}/databases/{database_id}/documents` or - * `projects/{project_id}/databases/{database_id}/documents/{document_path}`. - * For example: - * `projects/my-project/databases/my-database/documents` or - * `projects/my-project/databases/my-database/documents/chatrooms/my-chatroom` - * @param {google.firestore.v1.StructuredAggregationQuery} request.structuredAggregationQuery - * An aggregation query. - * @param {Buffer} request.transaction - * Run the aggregation within an already active transaction. - * - * The value here is the opaque transaction ID to execute the query in. - * @param {google.firestore.v1.TransactionOptions} request.newTransaction - * Starts a new transaction as part of the query, defaulting to read-only. - * - * The new transaction ID will be returned as the first response in the - * stream. - * @param {google.protobuf.Timestamp} request.readTime - * Executes the query at the given timestamp. - * - * This must be a microsecond precision timestamp within the past one hour, - * or if Point-in-Time Recovery is enabled, can additionally be a whole - * minute timestamp within the past 7 days. - * @param {google.firestore.v1.ExplainOptions} [request.explainOptions] - * Optional. Explain options for the query. If set, additional query - * statistics will be returned. If not, only query results will be returned. - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Stream} - * An object stream which emits {@link protos.google.firestore.v1.RunAggregationQueryResponse|RunAggregationQueryResponse} on 'data' event. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#server-streaming | documentation } - * for more details and examples. - * @example - * region_tag:firestore_v1_generated_Firestore_RunAggregationQuery_async - */ + /** + * Runs an aggregation query. + * + * Rather than producing {@link protos.google.firestore.v1.Document|Document} results like + * {@link protos.google.firestore.v1.Firestore.RunQuery|Firestore.RunQuery}, this API + * allows running an aggregation to produce a series of + * {@link protos.google.firestore.v1.AggregationResult|AggregationResult} server-side. + * + * High-Level Example: + * + * ``` + * -- Return the number of documents in table given a filter. + * SELECT COUNT(*) FROM ( SELECT * FROM k where a = true ); + * ``` + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.parent + * Required. The parent resource name. In the format: + * `projects/{project_id}/databases/{database_id}/documents` or + * `projects/{project_id}/databases/{database_id}/documents/{document_path}`. + * For example: + * `projects/my-project/databases/my-database/documents` or + * `projects/my-project/databases/my-database/documents/chatrooms/my-chatroom` + * @param {google.firestore.v1.StructuredAggregationQuery} request.structuredAggregationQuery + * An aggregation query. + * @param {Buffer} request.transaction + * Run the aggregation within an already active transaction. + * + * The value here is the opaque transaction ID to execute the query in. + * @param {google.firestore.v1.TransactionOptions} request.newTransaction + * Starts a new transaction as part of the query, defaulting to read-only. + * + * The new transaction ID will be returned as the first response in the + * stream. + * @param {google.protobuf.Timestamp} request.readTime + * Executes the query at the given timestamp. + * + * This must be a microsecond precision timestamp within the past one hour, + * or if Point-in-Time Recovery is enabled, can additionally be a whole + * minute timestamp within the past 7 days. + * @param {google.firestore.v1.ExplainOptions} [request.explainOptions] + * Optional. Explain options for the query. If set, additional query + * statistics will be returned. If not, only query results will be returned. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Stream} + * An object stream which emits {@link protos.google.firestore.v1.RunAggregationQueryResponse|RunAggregationQueryResponse} on 'data' event. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#server-streaming | documentation } + * for more details and examples. + * @example + * region_tag:firestore_v1_generated_Firestore_RunAggregationQuery_async + */ runAggregationQuery( - request?: protos.google.firestore.v1.IRunAggregationQueryRequest, - options?: CallOptions): - gax.CancellableStream{ + request?: protos.google.firestore.v1.IRunAggregationQueryRequest, + options?: CallOptions + ): gax.CancellableStream { request = request || {}; options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - options.otherArgs.headers[ - 'x-goog-request-params' - ] = this._gaxModule.routingHeader.fromParams({ - 'parent': request.parent ?? '', + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + parent: request.parent ?? '', + }); + this.initialize().catch(err => { + throw err; }); - this.initialize().catch(err => {throw err}); this._log.info('runAggregationQuery stream %j', options); return this.innerApiCalls.runAggregationQuery(request, options); } -/** - * Streams batches of document updates and deletes, in order. This method is - * only available via gRPC or WebChannel (not REST). - * - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Stream} - * An object stream which is both readable and writable. It accepts objects - * representing {@link protos.google.firestore.v1.WriteRequest|WriteRequest} for write() method, and - * will emit objects representing {@link protos.google.firestore.v1.WriteResponse|WriteResponse} on 'data' event asynchronously. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#bi-directional-streaming | documentation } - * for more details and examples. - * @example - * region_tag:firestore_v1_generated_Firestore_Write_async - */ - write( - options?: CallOptions): - gax.CancellableStream { - this.initialize().catch(err => {throw err}); + /** + * Streams batches of document updates and deletes, in order. This method is + * only available via gRPC or WebChannel (not REST). + * + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Stream} + * An object stream which is both readable and writable. It accepts objects + * representing {@link protos.google.firestore.v1.WriteRequest|WriteRequest} for write() method, and + * will emit objects representing {@link protos.google.firestore.v1.WriteResponse|WriteResponse} on 'data' event asynchronously. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#bi-directional-streaming | documentation } + * for more details and examples. + * @example + * region_tag:firestore_v1_generated_Firestore_Write_async + */ + write(options?: CallOptions): gax.CancellableStream { + this.initialize().catch(err => { + throw err; + }); this._log.info('write stream %j', options); return this.innerApiCalls.write(null, options); } -/** - * Listens to changes. This method is only available via gRPC or WebChannel - * (not REST). - * - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Stream} - * An object stream which is both readable and writable. It accepts objects - * representing {@link protos.google.firestore.v1.ListenRequest|ListenRequest} for write() method, and - * will emit objects representing {@link protos.google.firestore.v1.ListenResponse|ListenResponse} on 'data' event asynchronously. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#bi-directional-streaming | documentation } - * for more details and examples. - * @example - * region_tag:firestore_v1_generated_Firestore_Listen_async - */ - listen( - options?: CallOptions): - gax.CancellableStream { - this.initialize().catch(err => {throw err}); + /** + * Listens to changes. This method is only available via gRPC or WebChannel + * (not REST). + * + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Stream} + * An object stream which is both readable and writable. It accepts objects + * representing {@link protos.google.firestore.v1.ListenRequest|ListenRequest} for write() method, and + * will emit objects representing {@link protos.google.firestore.v1.ListenResponse|ListenResponse} on 'data' event asynchronously. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#bi-directional-streaming | documentation } + * for more details and examples. + * @example + * region_tag:firestore_v1_generated_Firestore_Listen_async + */ + listen(options?: CallOptions): gax.CancellableStream { + this.initialize().catch(err => { + throw err; + }); this._log.info('listen stream %j', options); return this.innerApiCalls.listen(null, options); } - /** - * Lists documents. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.parent - * Required. The parent resource name. In the format: - * `projects/{project_id}/databases/{database_id}/documents` or - * `projects/{project_id}/databases/{database_id}/documents/{document_path}`. - * - * For example: - * `projects/my-project/databases/my-database/documents` or - * `projects/my-project/databases/my-database/documents/chatrooms/my-chatroom` - * @param {string} [request.collectionId] - * Optional. The collection ID, relative to `parent`, to list. - * - * For example: `chatrooms` or `messages`. - * - * This is optional, and when not provided, Firestore will list documents - * from all collections under the provided `parent`. - * @param {number} [request.pageSize] - * Optional. The maximum number of documents to return in a single response. - * - * Firestore may return fewer than this value. - * @param {string} [request.pageToken] - * Optional. A page token, received from a previous `ListDocuments` response. - * - * Provide this to retrieve the subsequent page. When paginating, all other - * parameters (with the exception of `page_size`) must match the values set - * in the request that generated the page token. - * @param {string} [request.orderBy] - * Optional. The optional ordering of the documents to return. - * - * For example: `priority desc, __name__ desc`. - * - * This mirrors the {@link protos.google.firestore.v1.StructuredQuery.order_by|`ORDER BY`} - * used in Firestore queries but in a string representation. When absent, - * documents are ordered based on `__name__ ASC`. - * @param {google.firestore.v1.DocumentMask} [request.mask] - * Optional. The fields to return. If not set, returns all fields. - * - * If a document has a field that is not present in this mask, that field - * will not be returned in the response. - * @param {Buffer} request.transaction - * Perform the read as part of an already active transaction. - * @param {google.protobuf.Timestamp} request.readTime - * Perform the read at the provided time. - * - * This must be a microsecond precision timestamp within the past one hour, - * or if Point-in-Time Recovery is enabled, can additionally be a whole - * minute timestamp within the past 7 days. - * @param {boolean} request.showMissing - * If the list should show missing documents. - * - * A document is missing if it does not exist, but there are sub-documents - * nested underneath it. When true, such missing documents will be returned - * with a key but will not have fields, - * {@link protos.google.firestore.v1.Document.create_time|`create_time`}, or - * {@link protos.google.firestore.v1.Document.update_time|`update_time`} set. - * - * Requests with `show_missing` may not specify `where` or `order_by`. - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Promise} - The promise which resolves to an array. - * The first element of the array is Array of {@link protos.google.firestore.v1.Document|Document}. - * The client library will perform auto-pagination by default: it will call the API as many - * times as needed and will merge results from all the pages into this array. - * Note that it can affect your quota. - * We recommend using `listDocumentsAsync()` - * method described below for async iteration which you can stop as needed. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#auto-pagination | documentation } - * for more details and examples. - */ + /** + * Lists documents. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.parent + * Required. The parent resource name. In the format: + * `projects/{project_id}/databases/{database_id}/documents` or + * `projects/{project_id}/databases/{database_id}/documents/{document_path}`. + * + * For example: + * `projects/my-project/databases/my-database/documents` or + * `projects/my-project/databases/my-database/documents/chatrooms/my-chatroom` + * @param {string} [request.collectionId] + * Optional. The collection ID, relative to `parent`, to list. + * + * For example: `chatrooms` or `messages`. + * + * This is optional, and when not provided, Firestore will list documents + * from all collections under the provided `parent`. + * @param {number} [request.pageSize] + * Optional. The maximum number of documents to return in a single response. + * + * Firestore may return fewer than this value. + * @param {string} [request.pageToken] + * Optional. A page token, received from a previous `ListDocuments` response. + * + * Provide this to retrieve the subsequent page. When paginating, all other + * parameters (with the exception of `page_size`) must match the values set + * in the request that generated the page token. + * @param {string} [request.orderBy] + * Optional. The optional ordering of the documents to return. + * + * For example: `priority desc, __name__ desc`. + * + * This mirrors the {@link protos.google.firestore.v1.StructuredQuery.order_by|`ORDER BY`} + * used in Firestore queries but in a string representation. When absent, + * documents are ordered based on `__name__ ASC`. + * @param {google.firestore.v1.DocumentMask} [request.mask] + * Optional. The fields to return. If not set, returns all fields. + * + * If a document has a field that is not present in this mask, that field + * will not be returned in the response. + * @param {Buffer} request.transaction + * Perform the read as part of an already active transaction. + * @param {google.protobuf.Timestamp} request.readTime + * Perform the read at the provided time. + * + * This must be a microsecond precision timestamp within the past one hour, + * or if Point-in-Time Recovery is enabled, can additionally be a whole + * minute timestamp within the past 7 days. + * @param {boolean} request.showMissing + * If the list should show missing documents. + * + * A document is missing if it does not exist, but there are sub-documents + * nested underneath it. When true, such missing documents will be returned + * with a key but will not have fields, + * {@link protos.google.firestore.v1.Document.create_time|`create_time`}, or + * {@link protos.google.firestore.v1.Document.update_time|`update_time`} set. + * + * Requests with `show_missing` may not specify `where` or `order_by`. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is Array of {@link protos.google.firestore.v1.Document|Document}. + * The client library will perform auto-pagination by default: it will call the API as many + * times as needed and will merge results from all the pages into this array. + * Note that it can affect your quota. + * We recommend using `listDocumentsAsync()` + * method described below for async iteration which you can stop as needed. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#auto-pagination | documentation } + * for more details and examples. + */ listDocuments( - request?: protos.google.firestore.v1.IListDocumentsRequest, - options?: CallOptions): - Promise<[ - protos.google.firestore.v1.IDocument[], - protos.google.firestore.v1.IListDocumentsRequest|null, - protos.google.firestore.v1.IListDocumentsResponse - ]>; + request?: protos.google.firestore.v1.IListDocumentsRequest, + options?: CallOptions + ): Promise< + [ + protos.google.firestore.v1.IDocument[], + protos.google.firestore.v1.IListDocumentsRequest | null, + protos.google.firestore.v1.IListDocumentsResponse, + ] + >; listDocuments( - request: protos.google.firestore.v1.IListDocumentsRequest, - options: CallOptions, - callback: PaginationCallback< - protos.google.firestore.v1.IListDocumentsRequest, - protos.google.firestore.v1.IListDocumentsResponse|null|undefined, - protos.google.firestore.v1.IDocument>): void; + request: protos.google.firestore.v1.IListDocumentsRequest, + options: CallOptions, + callback: PaginationCallback< + protos.google.firestore.v1.IListDocumentsRequest, + protos.google.firestore.v1.IListDocumentsResponse | null | undefined, + protos.google.firestore.v1.IDocument + > + ): void; listDocuments( - request: protos.google.firestore.v1.IListDocumentsRequest, - callback: PaginationCallback< - protos.google.firestore.v1.IListDocumentsRequest, - protos.google.firestore.v1.IListDocumentsResponse|null|undefined, - protos.google.firestore.v1.IDocument>): void; + request: protos.google.firestore.v1.IListDocumentsRequest, + callback: PaginationCallback< + protos.google.firestore.v1.IListDocumentsRequest, + protos.google.firestore.v1.IListDocumentsResponse | null | undefined, + protos.google.firestore.v1.IDocument + > + ): void; listDocuments( - request?: protos.google.firestore.v1.IListDocumentsRequest, - optionsOrCallback?: CallOptions|PaginationCallback< - protos.google.firestore.v1.IListDocumentsRequest, - protos.google.firestore.v1.IListDocumentsResponse|null|undefined, - protos.google.firestore.v1.IDocument>, - callback?: PaginationCallback< + request?: protos.google.firestore.v1.IListDocumentsRequest, + optionsOrCallback?: + | CallOptions + | PaginationCallback< protos.google.firestore.v1.IListDocumentsRequest, - protos.google.firestore.v1.IListDocumentsResponse|null|undefined, - protos.google.firestore.v1.IDocument>): - Promise<[ - protos.google.firestore.v1.IDocument[], - protos.google.firestore.v1.IListDocumentsRequest|null, - protos.google.firestore.v1.IListDocumentsResponse - ]>|void { + protos.google.firestore.v1.IListDocumentsResponse | null | undefined, + protos.google.firestore.v1.IDocument + >, + callback?: PaginationCallback< + protos.google.firestore.v1.IListDocumentsRequest, + protos.google.firestore.v1.IListDocumentsResponse | null | undefined, + protos.google.firestore.v1.IDocument + > + ): Promise< + [ + protos.google.firestore.v1.IDocument[], + protos.google.firestore.v1.IListDocumentsRequest | null, + protos.google.firestore.v1.IListDocumentsResponse, + ] + > | void { request = request || {}; let options: CallOptions; if (typeof optionsOrCallback === 'function' && callback === undefined) { callback = optionsOrCallback; options = {}; - } - else { + } else { options = optionsOrCallback as CallOptions; } options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - options.otherArgs.headers[ - 'x-goog-request-params' - ] = this._gaxModule.routingHeader.fromParams({ - 'parent': request.parent ?? '', - 'collection_id': request.collectionId ?? '', + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + parent: request.parent ?? '', + collection_id: request.collectionId ?? '', + }); + this.initialize().catch(err => { + throw err; }); - this.initialize().catch(err => {throw err}); - const wrappedCallback: PaginationCallback< - protos.google.firestore.v1.IListDocumentsRequest, - protos.google.firestore.v1.IListDocumentsResponse|null|undefined, - protos.google.firestore.v1.IDocument>|undefined = callback + const wrappedCallback: + | PaginationCallback< + protos.google.firestore.v1.IListDocumentsRequest, + protos.google.firestore.v1.IListDocumentsResponse | null | undefined, + protos.google.firestore.v1.IDocument + > + | undefined = callback ? (error, values, nextPageRequest, rawResponse) => { this._log.info('listDocuments values %j', values); callback!(error, values, nextPageRequest, rawResponse); // We verified callback above. @@ -1599,104 +1889,107 @@ export class FirestoreClient { this._log.info('listDocuments request %j', request); return this.innerApiCalls .listDocuments(request, options, wrappedCallback) - ?.then(([response, input, output]: [ - protos.google.firestore.v1.IDocument[], - protos.google.firestore.v1.IListDocumentsRequest|null, - protos.google.firestore.v1.IListDocumentsResponse - ]) => { - this._log.info('listDocuments values %j', response); - return [response, input, output]; - }); + ?.then( + ([response, input, output]: [ + protos.google.firestore.v1.IDocument[], + protos.google.firestore.v1.IListDocumentsRequest | null, + protos.google.firestore.v1.IListDocumentsResponse, + ]) => { + this._log.info('listDocuments values %j', response); + return [response, input, output]; + } + ); } -/** - * Equivalent to `listDocuments`, but returns a NodeJS Stream object. - * @param {Object} request - * The request object that will be sent. - * @param {string} request.parent - * Required. The parent resource name. In the format: - * `projects/{project_id}/databases/{database_id}/documents` or - * `projects/{project_id}/databases/{database_id}/documents/{document_path}`. - * - * For example: - * `projects/my-project/databases/my-database/documents` or - * `projects/my-project/databases/my-database/documents/chatrooms/my-chatroom` - * @param {string} [request.collectionId] - * Optional. The collection ID, relative to `parent`, to list. - * - * For example: `chatrooms` or `messages`. - * - * This is optional, and when not provided, Firestore will list documents - * from all collections under the provided `parent`. - * @param {number} [request.pageSize] - * Optional. The maximum number of documents to return in a single response. - * - * Firestore may return fewer than this value. - * @param {string} [request.pageToken] - * Optional. A page token, received from a previous `ListDocuments` response. - * - * Provide this to retrieve the subsequent page. When paginating, all other - * parameters (with the exception of `page_size`) must match the values set - * in the request that generated the page token. - * @param {string} [request.orderBy] - * Optional. The optional ordering of the documents to return. - * - * For example: `priority desc, __name__ desc`. - * - * This mirrors the {@link protos.google.firestore.v1.StructuredQuery.order_by|`ORDER BY`} - * used in Firestore queries but in a string representation. When absent, - * documents are ordered based on `__name__ ASC`. - * @param {google.firestore.v1.DocumentMask} [request.mask] - * Optional. The fields to return. If not set, returns all fields. - * - * If a document has a field that is not present in this mask, that field - * will not be returned in the response. - * @param {Buffer} request.transaction - * Perform the read as part of an already active transaction. - * @param {google.protobuf.Timestamp} request.readTime - * Perform the read at the provided time. - * - * This must be a microsecond precision timestamp within the past one hour, - * or if Point-in-Time Recovery is enabled, can additionally be a whole - * minute timestamp within the past 7 days. - * @param {boolean} request.showMissing - * If the list should show missing documents. - * - * A document is missing if it does not exist, but there are sub-documents - * nested underneath it. When true, such missing documents will be returned - * with a key but will not have fields, - * {@link protos.google.firestore.v1.Document.create_time|`create_time`}, or - * {@link protos.google.firestore.v1.Document.update_time|`update_time`} set. - * - * Requests with `show_missing` may not specify `where` or `order_by`. - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Stream} - * An object stream which emits an object representing {@link protos.google.firestore.v1.Document|Document} on 'data' event. - * The client library will perform auto-pagination by default: it will call the API as many - * times as needed. Note that it can affect your quota. - * We recommend using `listDocumentsAsync()` - * method described below for async iteration which you can stop as needed. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#auto-pagination | documentation } - * for more details and examples. - */ + /** + * Equivalent to `listDocuments`, but returns a NodeJS Stream object. + * @param {Object} request + * The request object that will be sent. + * @param {string} request.parent + * Required. The parent resource name. In the format: + * `projects/{project_id}/databases/{database_id}/documents` or + * `projects/{project_id}/databases/{database_id}/documents/{document_path}`. + * + * For example: + * `projects/my-project/databases/my-database/documents` or + * `projects/my-project/databases/my-database/documents/chatrooms/my-chatroom` + * @param {string} [request.collectionId] + * Optional. The collection ID, relative to `parent`, to list. + * + * For example: `chatrooms` or `messages`. + * + * This is optional, and when not provided, Firestore will list documents + * from all collections under the provided `parent`. + * @param {number} [request.pageSize] + * Optional. The maximum number of documents to return in a single response. + * + * Firestore may return fewer than this value. + * @param {string} [request.pageToken] + * Optional. A page token, received from a previous `ListDocuments` response. + * + * Provide this to retrieve the subsequent page. When paginating, all other + * parameters (with the exception of `page_size`) must match the values set + * in the request that generated the page token. + * @param {string} [request.orderBy] + * Optional. The optional ordering of the documents to return. + * + * For example: `priority desc, __name__ desc`. + * + * This mirrors the {@link protos.google.firestore.v1.StructuredQuery.order_by|`ORDER BY`} + * used in Firestore queries but in a string representation. When absent, + * documents are ordered based on `__name__ ASC`. + * @param {google.firestore.v1.DocumentMask} [request.mask] + * Optional. The fields to return. If not set, returns all fields. + * + * If a document has a field that is not present in this mask, that field + * will not be returned in the response. + * @param {Buffer} request.transaction + * Perform the read as part of an already active transaction. + * @param {google.protobuf.Timestamp} request.readTime + * Perform the read at the provided time. + * + * This must be a microsecond precision timestamp within the past one hour, + * or if Point-in-Time Recovery is enabled, can additionally be a whole + * minute timestamp within the past 7 days. + * @param {boolean} request.showMissing + * If the list should show missing documents. + * + * A document is missing if it does not exist, but there are sub-documents + * nested underneath it. When true, such missing documents will be returned + * with a key but will not have fields, + * {@link protos.google.firestore.v1.Document.create_time|`create_time`}, or + * {@link protos.google.firestore.v1.Document.update_time|`update_time`} set. + * + * Requests with `show_missing` may not specify `where` or `order_by`. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Stream} + * An object stream which emits an object representing {@link protos.google.firestore.v1.Document|Document} on 'data' event. + * The client library will perform auto-pagination by default: it will call the API as many + * times as needed. Note that it can affect your quota. + * We recommend using `listDocumentsAsync()` + * method described below for async iteration which you can stop as needed. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#auto-pagination | documentation } + * for more details and examples. + */ listDocumentsStream( - request?: protos.google.firestore.v1.IListDocumentsRequest, - options?: CallOptions): - Transform{ + request?: protos.google.firestore.v1.IListDocumentsRequest, + options?: CallOptions + ): Transform { request = request || {}; options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - options.otherArgs.headers[ - 'x-goog-request-params' - ] = this._gaxModule.routingHeader.fromParams({ - 'parent': request.parent ?? '', - 'collection_id': request.collectionId ?? '', - }); + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + parent: request.parent ?? '', + collection_id: request.collectionId ?? '', + }); const defaultCallSettings = this._defaults['listDocuments']; const callSettings = defaultCallSettings.merge(options); - this.initialize().catch(err => {throw err}); + this.initialize().catch(err => { + throw err; + }); this._log.info('listDocuments stream %j', request); return this.descriptors.page.listDocuments.createStream( this.innerApiCalls.listDocuments as GaxCall, @@ -1705,97 +1998,98 @@ export class FirestoreClient { ); } -/** - * Equivalent to `listDocuments`, but returns an iterable object. - * - * `for`-`await`-`of` syntax is used with the iterable to get response elements on-demand. - * @param {Object} request - * The request object that will be sent. - * @param {string} request.parent - * Required. The parent resource name. In the format: - * `projects/{project_id}/databases/{database_id}/documents` or - * `projects/{project_id}/databases/{database_id}/documents/{document_path}`. - * - * For example: - * `projects/my-project/databases/my-database/documents` or - * `projects/my-project/databases/my-database/documents/chatrooms/my-chatroom` - * @param {string} [request.collectionId] - * Optional. The collection ID, relative to `parent`, to list. - * - * For example: `chatrooms` or `messages`. - * - * This is optional, and when not provided, Firestore will list documents - * from all collections under the provided `parent`. - * @param {number} [request.pageSize] - * Optional. The maximum number of documents to return in a single response. - * - * Firestore may return fewer than this value. - * @param {string} [request.pageToken] - * Optional. A page token, received from a previous `ListDocuments` response. - * - * Provide this to retrieve the subsequent page. When paginating, all other - * parameters (with the exception of `page_size`) must match the values set - * in the request that generated the page token. - * @param {string} [request.orderBy] - * Optional. The optional ordering of the documents to return. - * - * For example: `priority desc, __name__ desc`. - * - * This mirrors the {@link protos.google.firestore.v1.StructuredQuery.order_by|`ORDER BY`} - * used in Firestore queries but in a string representation. When absent, - * documents are ordered based on `__name__ ASC`. - * @param {google.firestore.v1.DocumentMask} [request.mask] - * Optional. The fields to return. If not set, returns all fields. - * - * If a document has a field that is not present in this mask, that field - * will not be returned in the response. - * @param {Buffer} request.transaction - * Perform the read as part of an already active transaction. - * @param {google.protobuf.Timestamp} request.readTime - * Perform the read at the provided time. - * - * This must be a microsecond precision timestamp within the past one hour, - * or if Point-in-Time Recovery is enabled, can additionally be a whole - * minute timestamp within the past 7 days. - * @param {boolean} request.showMissing - * If the list should show missing documents. - * - * A document is missing if it does not exist, but there are sub-documents - * nested underneath it. When true, such missing documents will be returned - * with a key but will not have fields, - * {@link protos.google.firestore.v1.Document.create_time|`create_time`}, or - * {@link protos.google.firestore.v1.Document.update_time|`update_time`} set. - * - * Requests with `show_missing` may not specify `where` or `order_by`. - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Object} - * An iterable Object that allows {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols | async iteration }. - * When you iterate the returned iterable, each element will be an object representing - * {@link protos.google.firestore.v1.Document|Document}. The API will be called under the hood as needed, once per the page, - * so you can stop the iteration when you don't need more results. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#auto-pagination | documentation } - * for more details and examples. - * @example - * region_tag:firestore_v1_generated_Firestore_ListDocuments_async - */ + /** + * Equivalent to `listDocuments`, but returns an iterable object. + * + * `for`-`await`-`of` syntax is used with the iterable to get response elements on-demand. + * @param {Object} request + * The request object that will be sent. + * @param {string} request.parent + * Required. The parent resource name. In the format: + * `projects/{project_id}/databases/{database_id}/documents` or + * `projects/{project_id}/databases/{database_id}/documents/{document_path}`. + * + * For example: + * `projects/my-project/databases/my-database/documents` or + * `projects/my-project/databases/my-database/documents/chatrooms/my-chatroom` + * @param {string} [request.collectionId] + * Optional. The collection ID, relative to `parent`, to list. + * + * For example: `chatrooms` or `messages`. + * + * This is optional, and when not provided, Firestore will list documents + * from all collections under the provided `parent`. + * @param {number} [request.pageSize] + * Optional. The maximum number of documents to return in a single response. + * + * Firestore may return fewer than this value. + * @param {string} [request.pageToken] + * Optional. A page token, received from a previous `ListDocuments` response. + * + * Provide this to retrieve the subsequent page. When paginating, all other + * parameters (with the exception of `page_size`) must match the values set + * in the request that generated the page token. + * @param {string} [request.orderBy] + * Optional. The optional ordering of the documents to return. + * + * For example: `priority desc, __name__ desc`. + * + * This mirrors the {@link protos.google.firestore.v1.StructuredQuery.order_by|`ORDER BY`} + * used in Firestore queries but in a string representation. When absent, + * documents are ordered based on `__name__ ASC`. + * @param {google.firestore.v1.DocumentMask} [request.mask] + * Optional. The fields to return. If not set, returns all fields. + * + * If a document has a field that is not present in this mask, that field + * will not be returned in the response. + * @param {Buffer} request.transaction + * Perform the read as part of an already active transaction. + * @param {google.protobuf.Timestamp} request.readTime + * Perform the read at the provided time. + * + * This must be a microsecond precision timestamp within the past one hour, + * or if Point-in-Time Recovery is enabled, can additionally be a whole + * minute timestamp within the past 7 days. + * @param {boolean} request.showMissing + * If the list should show missing documents. + * + * A document is missing if it does not exist, but there are sub-documents + * nested underneath it. When true, such missing documents will be returned + * with a key but will not have fields, + * {@link protos.google.firestore.v1.Document.create_time|`create_time`}, or + * {@link protos.google.firestore.v1.Document.update_time|`update_time`} set. + * + * Requests with `show_missing` may not specify `where` or `order_by`. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Object} + * An iterable Object that allows {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols | async iteration }. + * When you iterate the returned iterable, each element will be an object representing + * {@link protos.google.firestore.v1.Document|Document}. The API will be called under the hood as needed, once per the page, + * so you can stop the iteration when you don't need more results. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#auto-pagination | documentation } + * for more details and examples. + * @example + * region_tag:firestore_v1_generated_Firestore_ListDocuments_async + */ listDocumentsAsync( - request?: protos.google.firestore.v1.IListDocumentsRequest, - options?: CallOptions): - AsyncIterable{ + request?: protos.google.firestore.v1.IListDocumentsRequest, + options?: CallOptions + ): AsyncIterable { request = request || {}; options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - options.otherArgs.headers[ - 'x-goog-request-params' - ] = this._gaxModule.routingHeader.fromParams({ - 'parent': request.parent ?? '', - 'collection_id': request.collectionId ?? '', - }); + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + parent: request.parent ?? '', + collection_id: request.collectionId ?? '', + }); const defaultCallSettings = this._defaults['listDocuments']; const callSettings = defaultCallSettings.merge(options); - this.initialize().catch(err => {throw err}); + this.initialize().catch(err => { + throw err; + }); this._log.info('listDocuments iterate %j', request); return this.descriptors.page.listDocuments.asyncIterate( this.innerApiCalls['listDocuments'] as GaxCall, @@ -1803,130 +2097,145 @@ export class FirestoreClient { callSettings ) as AsyncIterable; } - /** - * Partitions a query by returning partition cursors that can be used to run - * the query in parallel. The returned partition cursors are split points that - * can be used by RunQuery as starting/end points for the query results. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.parent - * Required. The parent resource name. In the format: - * `projects/{project_id}/databases/{database_id}/documents`. - * Document resource names are not supported; only database resource names - * can be specified. - * @param {google.firestore.v1.StructuredQuery} request.structuredQuery - * A structured query. - * Query must specify collection with all descendants and be ordered by name - * ascending. Other filters, order bys, limits, offsets, and start/end - * cursors are not supported. - * @param {number} request.partitionCount - * The desired maximum number of partition points. - * The partitions may be returned across multiple pages of results. - * The number must be positive. The actual number of partitions - * returned may be fewer. - * - * For example, this may be set to one fewer than the number of parallel - * queries to be run, or in running a data pipeline job, one fewer than the - * number of workers or compute instances available. - * @param {string} request.pageToken - * The `next_page_token` value returned from a previous call to - * PartitionQuery that may be used to get an additional set of results. - * There are no ordering guarantees between sets of results. Thus, using - * multiple sets of results will require merging the different result sets. - * - * For example, two subsequent calls using a page_token may return: - * - * * cursor B, cursor M, cursor Q - * * cursor A, cursor U, cursor W - * - * To obtain a complete result set ordered with respect to the results of the - * query supplied to PartitionQuery, the results sets should be merged: - * cursor A, cursor B, cursor M, cursor Q, cursor U, cursor W - * @param {number} request.pageSize - * The maximum number of partitions to return in this call, subject to - * `partition_count`. - * - * For example, if `partition_count` = 10 and `page_size` = 8, the first call - * to PartitionQuery will return up to 8 partitions and a `next_page_token` - * if more results exist. A second call to PartitionQuery will return up to - * 2 partitions, to complete the total of 10 specified in `partition_count`. - * @param {google.protobuf.Timestamp} request.readTime - * Reads documents as they were at the given time. - * - * This must be a microsecond precision timestamp within the past one hour, - * or if Point-in-Time Recovery is enabled, can additionally be a whole - * minute timestamp within the past 7 days. - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Promise} - The promise which resolves to an array. - * The first element of the array is Array of {@link protos.google.firestore.v1.Cursor|Cursor}. - * The client library will perform auto-pagination by default: it will call the API as many - * times as needed and will merge results from all the pages into this array. - * Note that it can affect your quota. - * We recommend using `partitionQueryAsync()` - * method described below for async iteration which you can stop as needed. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#auto-pagination | documentation } - * for more details and examples. - */ + /** + * Partitions a query by returning partition cursors that can be used to run + * the query in parallel. The returned partition cursors are split points that + * can be used by RunQuery as starting/end points for the query results. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.parent + * Required. The parent resource name. In the format: + * `projects/{project_id}/databases/{database_id}/documents`. + * Document resource names are not supported; only database resource names + * can be specified. + * @param {google.firestore.v1.StructuredQuery} request.structuredQuery + * A structured query. + * Query must specify collection with all descendants and be ordered by name + * ascending. Other filters, order bys, limits, offsets, and start/end + * cursors are not supported. + * @param {number} request.partitionCount + * The desired maximum number of partition points. + * The partitions may be returned across multiple pages of results. + * The number must be positive. The actual number of partitions + * returned may be fewer. + * + * For example, this may be set to one fewer than the number of parallel + * queries to be run, or in running a data pipeline job, one fewer than the + * number of workers or compute instances available. + * @param {string} request.pageToken + * The `next_page_token` value returned from a previous call to + * PartitionQuery that may be used to get an additional set of results. + * There are no ordering guarantees between sets of results. Thus, using + * multiple sets of results will require merging the different result sets. + * + * For example, two subsequent calls using a page_token may return: + * + * * cursor B, cursor M, cursor Q + * * cursor A, cursor U, cursor W + * + * To obtain a complete result set ordered with respect to the results of the + * query supplied to PartitionQuery, the results sets should be merged: + * cursor A, cursor B, cursor M, cursor Q, cursor U, cursor W + * @param {number} request.pageSize + * The maximum number of partitions to return in this call, subject to + * `partition_count`. + * + * For example, if `partition_count` = 10 and `page_size` = 8, the first call + * to PartitionQuery will return up to 8 partitions and a `next_page_token` + * if more results exist. A second call to PartitionQuery will return up to + * 2 partitions, to complete the total of 10 specified in `partition_count`. + * @param {google.protobuf.Timestamp} request.readTime + * Reads documents as they were at the given time. + * + * This must be a microsecond precision timestamp within the past one hour, + * or if Point-in-Time Recovery is enabled, can additionally be a whole + * minute timestamp within the past 7 days. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is Array of {@link protos.google.firestore.v1.Cursor|Cursor}. + * The client library will perform auto-pagination by default: it will call the API as many + * times as needed and will merge results from all the pages into this array. + * Note that it can affect your quota. + * We recommend using `partitionQueryAsync()` + * method described below for async iteration which you can stop as needed. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#auto-pagination | documentation } + * for more details and examples. + */ partitionQuery( - request?: protos.google.firestore.v1.IPartitionQueryRequest, - options?: CallOptions): - Promise<[ - protos.google.firestore.v1.ICursor[], - protos.google.firestore.v1.IPartitionQueryRequest|null, - protos.google.firestore.v1.IPartitionQueryResponse - ]>; + request?: protos.google.firestore.v1.IPartitionQueryRequest, + options?: CallOptions + ): Promise< + [ + protos.google.firestore.v1.ICursor[], + protos.google.firestore.v1.IPartitionQueryRequest | null, + protos.google.firestore.v1.IPartitionQueryResponse, + ] + >; partitionQuery( - request: protos.google.firestore.v1.IPartitionQueryRequest, - options: CallOptions, - callback: PaginationCallback< - protos.google.firestore.v1.IPartitionQueryRequest, - protos.google.firestore.v1.IPartitionQueryResponse|null|undefined, - protos.google.firestore.v1.ICursor>): void; + request: protos.google.firestore.v1.IPartitionQueryRequest, + options: CallOptions, + callback: PaginationCallback< + protos.google.firestore.v1.IPartitionQueryRequest, + protos.google.firestore.v1.IPartitionQueryResponse | null | undefined, + protos.google.firestore.v1.ICursor + > + ): void; partitionQuery( - request: protos.google.firestore.v1.IPartitionQueryRequest, - callback: PaginationCallback< - protos.google.firestore.v1.IPartitionQueryRequest, - protos.google.firestore.v1.IPartitionQueryResponse|null|undefined, - protos.google.firestore.v1.ICursor>): void; + request: protos.google.firestore.v1.IPartitionQueryRequest, + callback: PaginationCallback< + protos.google.firestore.v1.IPartitionQueryRequest, + protos.google.firestore.v1.IPartitionQueryResponse | null | undefined, + protos.google.firestore.v1.ICursor + > + ): void; partitionQuery( - request?: protos.google.firestore.v1.IPartitionQueryRequest, - optionsOrCallback?: CallOptions|PaginationCallback< + request?: protos.google.firestore.v1.IPartitionQueryRequest, + optionsOrCallback?: + | CallOptions + | PaginationCallback< protos.google.firestore.v1.IPartitionQueryRequest, - protos.google.firestore.v1.IPartitionQueryResponse|null|undefined, - protos.google.firestore.v1.ICursor>, - callback?: PaginationCallback< - protos.google.firestore.v1.IPartitionQueryRequest, - protos.google.firestore.v1.IPartitionQueryResponse|null|undefined, - protos.google.firestore.v1.ICursor>): - Promise<[ - protos.google.firestore.v1.ICursor[], - protos.google.firestore.v1.IPartitionQueryRequest|null, - protos.google.firestore.v1.IPartitionQueryResponse - ]>|void { + protos.google.firestore.v1.IPartitionQueryResponse | null | undefined, + protos.google.firestore.v1.ICursor + >, + callback?: PaginationCallback< + protos.google.firestore.v1.IPartitionQueryRequest, + protos.google.firestore.v1.IPartitionQueryResponse | null | undefined, + protos.google.firestore.v1.ICursor + > + ): Promise< + [ + protos.google.firestore.v1.ICursor[], + protos.google.firestore.v1.IPartitionQueryRequest | null, + protos.google.firestore.v1.IPartitionQueryResponse, + ] + > | void { request = request || {}; let options: CallOptions; if (typeof optionsOrCallback === 'function' && callback === undefined) { callback = optionsOrCallback; options = {}; - } - else { + } else { options = optionsOrCallback as CallOptions; } options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - options.otherArgs.headers[ - 'x-goog-request-params' - ] = this._gaxModule.routingHeader.fromParams({ - 'parent': request.parent ?? '', + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + parent: request.parent ?? '', + }); + this.initialize().catch(err => { + throw err; }); - this.initialize().catch(err => {throw err}); - const wrappedCallback: PaginationCallback< - protos.google.firestore.v1.IPartitionQueryRequest, - protos.google.firestore.v1.IPartitionQueryResponse|null|undefined, - protos.google.firestore.v1.ICursor>|undefined = callback + const wrappedCallback: + | PaginationCallback< + protos.google.firestore.v1.IPartitionQueryRequest, + protos.google.firestore.v1.IPartitionQueryResponse | null | undefined, + protos.google.firestore.v1.ICursor + > + | undefined = callback ? (error, values, nextPageRequest, rawResponse) => { this._log.info('partitionQuery values %j', values); callback!(error, values, nextPageRequest, rawResponse); // We verified callback above. @@ -1935,94 +2244,97 @@ export class FirestoreClient { this._log.info('partitionQuery request %j', request); return this.innerApiCalls .partitionQuery(request, options, wrappedCallback) - ?.then(([response, input, output]: [ - protos.google.firestore.v1.ICursor[], - protos.google.firestore.v1.IPartitionQueryRequest|null, - protos.google.firestore.v1.IPartitionQueryResponse - ]) => { - this._log.info('partitionQuery values %j', response); - return [response, input, output]; - }); + ?.then( + ([response, input, output]: [ + protos.google.firestore.v1.ICursor[], + protos.google.firestore.v1.IPartitionQueryRequest | null, + protos.google.firestore.v1.IPartitionQueryResponse, + ]) => { + this._log.info('partitionQuery values %j', response); + return [response, input, output]; + } + ); } -/** - * Equivalent to `partitionQuery`, but returns a NodeJS Stream object. - * @param {Object} request - * The request object that will be sent. - * @param {string} request.parent - * Required. The parent resource name. In the format: - * `projects/{project_id}/databases/{database_id}/documents`. - * Document resource names are not supported; only database resource names - * can be specified. - * @param {google.firestore.v1.StructuredQuery} request.structuredQuery - * A structured query. - * Query must specify collection with all descendants and be ordered by name - * ascending. Other filters, order bys, limits, offsets, and start/end - * cursors are not supported. - * @param {number} request.partitionCount - * The desired maximum number of partition points. - * The partitions may be returned across multiple pages of results. - * The number must be positive. The actual number of partitions - * returned may be fewer. - * - * For example, this may be set to one fewer than the number of parallel - * queries to be run, or in running a data pipeline job, one fewer than the - * number of workers or compute instances available. - * @param {string} request.pageToken - * The `next_page_token` value returned from a previous call to - * PartitionQuery that may be used to get an additional set of results. - * There are no ordering guarantees between sets of results. Thus, using - * multiple sets of results will require merging the different result sets. - * - * For example, two subsequent calls using a page_token may return: - * - * * cursor B, cursor M, cursor Q - * * cursor A, cursor U, cursor W - * - * To obtain a complete result set ordered with respect to the results of the - * query supplied to PartitionQuery, the results sets should be merged: - * cursor A, cursor B, cursor M, cursor Q, cursor U, cursor W - * @param {number} request.pageSize - * The maximum number of partitions to return in this call, subject to - * `partition_count`. - * - * For example, if `partition_count` = 10 and `page_size` = 8, the first call - * to PartitionQuery will return up to 8 partitions and a `next_page_token` - * if more results exist. A second call to PartitionQuery will return up to - * 2 partitions, to complete the total of 10 specified in `partition_count`. - * @param {google.protobuf.Timestamp} request.readTime - * Reads documents as they were at the given time. - * - * This must be a microsecond precision timestamp within the past one hour, - * or if Point-in-Time Recovery is enabled, can additionally be a whole - * minute timestamp within the past 7 days. - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Stream} - * An object stream which emits an object representing {@link protos.google.firestore.v1.Cursor|Cursor} on 'data' event. - * The client library will perform auto-pagination by default: it will call the API as many - * times as needed. Note that it can affect your quota. - * We recommend using `partitionQueryAsync()` - * method described below for async iteration which you can stop as needed. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#auto-pagination | documentation } - * for more details and examples. - */ + /** + * Equivalent to `partitionQuery`, but returns a NodeJS Stream object. + * @param {Object} request + * The request object that will be sent. + * @param {string} request.parent + * Required. The parent resource name. In the format: + * `projects/{project_id}/databases/{database_id}/documents`. + * Document resource names are not supported; only database resource names + * can be specified. + * @param {google.firestore.v1.StructuredQuery} request.structuredQuery + * A structured query. + * Query must specify collection with all descendants and be ordered by name + * ascending. Other filters, order bys, limits, offsets, and start/end + * cursors are not supported. + * @param {number} request.partitionCount + * The desired maximum number of partition points. + * The partitions may be returned across multiple pages of results. + * The number must be positive. The actual number of partitions + * returned may be fewer. + * + * For example, this may be set to one fewer than the number of parallel + * queries to be run, or in running a data pipeline job, one fewer than the + * number of workers or compute instances available. + * @param {string} request.pageToken + * The `next_page_token` value returned from a previous call to + * PartitionQuery that may be used to get an additional set of results. + * There are no ordering guarantees between sets of results. Thus, using + * multiple sets of results will require merging the different result sets. + * + * For example, two subsequent calls using a page_token may return: + * + * * cursor B, cursor M, cursor Q + * * cursor A, cursor U, cursor W + * + * To obtain a complete result set ordered with respect to the results of the + * query supplied to PartitionQuery, the results sets should be merged: + * cursor A, cursor B, cursor M, cursor Q, cursor U, cursor W + * @param {number} request.pageSize + * The maximum number of partitions to return in this call, subject to + * `partition_count`. + * + * For example, if `partition_count` = 10 and `page_size` = 8, the first call + * to PartitionQuery will return up to 8 partitions and a `next_page_token` + * if more results exist. A second call to PartitionQuery will return up to + * 2 partitions, to complete the total of 10 specified in `partition_count`. + * @param {google.protobuf.Timestamp} request.readTime + * Reads documents as they were at the given time. + * + * This must be a microsecond precision timestamp within the past one hour, + * or if Point-in-Time Recovery is enabled, can additionally be a whole + * minute timestamp within the past 7 days. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Stream} + * An object stream which emits an object representing {@link protos.google.firestore.v1.Cursor|Cursor} on 'data' event. + * The client library will perform auto-pagination by default: it will call the API as many + * times as needed. Note that it can affect your quota. + * We recommend using `partitionQueryAsync()` + * method described below for async iteration which you can stop as needed. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#auto-pagination | documentation } + * for more details and examples. + */ partitionQueryStream( - request?: protos.google.firestore.v1.IPartitionQueryRequest, - options?: CallOptions): - Transform{ + request?: protos.google.firestore.v1.IPartitionQueryRequest, + options?: CallOptions + ): Transform { request = request || {}; options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - options.otherArgs.headers[ - 'x-goog-request-params' - ] = this._gaxModule.routingHeader.fromParams({ - 'parent': request.parent ?? '', - }); + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + parent: request.parent ?? '', + }); const defaultCallSettings = this._defaults['partitionQuery']; const callSettings = defaultCallSettings.merge(options); - this.initialize().catch(err => {throw err}); + this.initialize().catch(err => { + throw err; + }); this._log.info('partitionQuery stream %j', request); return this.descriptors.page.partitionQuery.createStream( this.innerApiCalls.partitionQuery as GaxCall, @@ -2031,87 +2343,88 @@ export class FirestoreClient { ); } -/** - * Equivalent to `partitionQuery`, but returns an iterable object. - * - * `for`-`await`-`of` syntax is used with the iterable to get response elements on-demand. - * @param {Object} request - * The request object that will be sent. - * @param {string} request.parent - * Required. The parent resource name. In the format: - * `projects/{project_id}/databases/{database_id}/documents`. - * Document resource names are not supported; only database resource names - * can be specified. - * @param {google.firestore.v1.StructuredQuery} request.structuredQuery - * A structured query. - * Query must specify collection with all descendants and be ordered by name - * ascending. Other filters, order bys, limits, offsets, and start/end - * cursors are not supported. - * @param {number} request.partitionCount - * The desired maximum number of partition points. - * The partitions may be returned across multiple pages of results. - * The number must be positive. The actual number of partitions - * returned may be fewer. - * - * For example, this may be set to one fewer than the number of parallel - * queries to be run, or in running a data pipeline job, one fewer than the - * number of workers or compute instances available. - * @param {string} request.pageToken - * The `next_page_token` value returned from a previous call to - * PartitionQuery that may be used to get an additional set of results. - * There are no ordering guarantees between sets of results. Thus, using - * multiple sets of results will require merging the different result sets. - * - * For example, two subsequent calls using a page_token may return: - * - * * cursor B, cursor M, cursor Q - * * cursor A, cursor U, cursor W - * - * To obtain a complete result set ordered with respect to the results of the - * query supplied to PartitionQuery, the results sets should be merged: - * cursor A, cursor B, cursor M, cursor Q, cursor U, cursor W - * @param {number} request.pageSize - * The maximum number of partitions to return in this call, subject to - * `partition_count`. - * - * For example, if `partition_count` = 10 and `page_size` = 8, the first call - * to PartitionQuery will return up to 8 partitions and a `next_page_token` - * if more results exist. A second call to PartitionQuery will return up to - * 2 partitions, to complete the total of 10 specified in `partition_count`. - * @param {google.protobuf.Timestamp} request.readTime - * Reads documents as they were at the given time. - * - * This must be a microsecond precision timestamp within the past one hour, - * or if Point-in-Time Recovery is enabled, can additionally be a whole - * minute timestamp within the past 7 days. - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Object} - * An iterable Object that allows {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols | async iteration }. - * When you iterate the returned iterable, each element will be an object representing - * {@link protos.google.firestore.v1.Cursor|Cursor}. The API will be called under the hood as needed, once per the page, - * so you can stop the iteration when you don't need more results. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#auto-pagination | documentation } - * for more details and examples. - * @example - * region_tag:firestore_v1_generated_Firestore_PartitionQuery_async - */ + /** + * Equivalent to `partitionQuery`, but returns an iterable object. + * + * `for`-`await`-`of` syntax is used with the iterable to get response elements on-demand. + * @param {Object} request + * The request object that will be sent. + * @param {string} request.parent + * Required. The parent resource name. In the format: + * `projects/{project_id}/databases/{database_id}/documents`. + * Document resource names are not supported; only database resource names + * can be specified. + * @param {google.firestore.v1.StructuredQuery} request.structuredQuery + * A structured query. + * Query must specify collection with all descendants and be ordered by name + * ascending. Other filters, order bys, limits, offsets, and start/end + * cursors are not supported. + * @param {number} request.partitionCount + * The desired maximum number of partition points. + * The partitions may be returned across multiple pages of results. + * The number must be positive. The actual number of partitions + * returned may be fewer. + * + * For example, this may be set to one fewer than the number of parallel + * queries to be run, or in running a data pipeline job, one fewer than the + * number of workers or compute instances available. + * @param {string} request.pageToken + * The `next_page_token` value returned from a previous call to + * PartitionQuery that may be used to get an additional set of results. + * There are no ordering guarantees between sets of results. Thus, using + * multiple sets of results will require merging the different result sets. + * + * For example, two subsequent calls using a page_token may return: + * + * * cursor B, cursor M, cursor Q + * * cursor A, cursor U, cursor W + * + * To obtain a complete result set ordered with respect to the results of the + * query supplied to PartitionQuery, the results sets should be merged: + * cursor A, cursor B, cursor M, cursor Q, cursor U, cursor W + * @param {number} request.pageSize + * The maximum number of partitions to return in this call, subject to + * `partition_count`. + * + * For example, if `partition_count` = 10 and `page_size` = 8, the first call + * to PartitionQuery will return up to 8 partitions and a `next_page_token` + * if more results exist. A second call to PartitionQuery will return up to + * 2 partitions, to complete the total of 10 specified in `partition_count`. + * @param {google.protobuf.Timestamp} request.readTime + * Reads documents as they were at the given time. + * + * This must be a microsecond precision timestamp within the past one hour, + * or if Point-in-Time Recovery is enabled, can additionally be a whole + * minute timestamp within the past 7 days. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Object} + * An iterable Object that allows {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols | async iteration }. + * When you iterate the returned iterable, each element will be an object representing + * {@link protos.google.firestore.v1.Cursor|Cursor}. The API will be called under the hood as needed, once per the page, + * so you can stop the iteration when you don't need more results. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#auto-pagination | documentation } + * for more details and examples. + * @example + * region_tag:firestore_v1_generated_Firestore_PartitionQuery_async + */ partitionQueryAsync( - request?: protos.google.firestore.v1.IPartitionQueryRequest, - options?: CallOptions): - AsyncIterable{ + request?: protos.google.firestore.v1.IPartitionQueryRequest, + options?: CallOptions + ): AsyncIterable { request = request || {}; options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - options.otherArgs.headers[ - 'x-goog-request-params' - ] = this._gaxModule.routingHeader.fromParams({ - 'parent': request.parent ?? '', - }); + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + parent: request.parent ?? '', + }); const defaultCallSettings = this._defaults['partitionQuery']; const callSettings = defaultCallSettings.merge(options); - this.initialize().catch(err => {throw err}); + this.initialize().catch(err => { + throw err; + }); this._log.info('partitionQuery iterate %j', request); return this.descriptors.page.partitionQuery.asyncIterate( this.innerApiCalls['partitionQuery'] as GaxCall, @@ -2119,97 +2432,116 @@ export class FirestoreClient { callSettings ) as AsyncIterable; } - /** - * Lists all the collection IDs underneath a document. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.parent - * Required. The parent document. In the format: - * `projects/{project_id}/databases/{database_id}/documents/{document_path}`. - * For example: - * `projects/my-project/databases/my-database/documents/chatrooms/my-chatroom` - * @param {number} request.pageSize - * The maximum number of results to return. - * @param {string} request.pageToken - * A page token. Must be a value from - * {@link protos.google.firestore.v1.ListCollectionIdsResponse|ListCollectionIdsResponse}. - * @param {google.protobuf.Timestamp} request.readTime - * Reads documents as they were at the given time. - * - * This must be a microsecond precision timestamp within the past one hour, - * or if Point-in-Time Recovery is enabled, can additionally be a whole - * minute timestamp within the past 7 days. - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Promise} - The promise which resolves to an array. - * The first element of the array is Array of string. - * The client library will perform auto-pagination by default: it will call the API as many - * times as needed and will merge results from all the pages into this array. - * Note that it can affect your quota. - * We recommend using `listCollectionIdsAsync()` - * method described below for async iteration which you can stop as needed. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#auto-pagination | documentation } - * for more details and examples. - */ + /** + * Lists all the collection IDs underneath a document. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.parent + * Required. The parent document. In the format: + * `projects/{project_id}/databases/{database_id}/documents/{document_path}`. + * For example: + * `projects/my-project/databases/my-database/documents/chatrooms/my-chatroom` + * @param {number} request.pageSize + * The maximum number of results to return. + * @param {string} request.pageToken + * A page token. Must be a value from + * {@link protos.google.firestore.v1.ListCollectionIdsResponse|ListCollectionIdsResponse}. + * @param {google.protobuf.Timestamp} request.readTime + * Reads documents as they were at the given time. + * + * This must be a microsecond precision timestamp within the past one hour, + * or if Point-in-Time Recovery is enabled, can additionally be a whole + * minute timestamp within the past 7 days. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is Array of string. + * The client library will perform auto-pagination by default: it will call the API as many + * times as needed and will merge results from all the pages into this array. + * Note that it can affect your quota. + * We recommend using `listCollectionIdsAsync()` + * method described below for async iteration which you can stop as needed. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#auto-pagination | documentation } + * for more details and examples. + */ listCollectionIds( - request?: protos.google.firestore.v1.IListCollectionIdsRequest, - options?: CallOptions): - Promise<[ - string[], - protos.google.firestore.v1.IListCollectionIdsRequest|null, - protos.google.firestore.v1.IListCollectionIdsResponse - ]>; + request?: protos.google.firestore.v1.IListCollectionIdsRequest, + options?: CallOptions + ): Promise< + [ + string[], + protos.google.firestore.v1.IListCollectionIdsRequest | null, + protos.google.firestore.v1.IListCollectionIdsResponse, + ] + >; listCollectionIds( - request: protos.google.firestore.v1.IListCollectionIdsRequest, - options: CallOptions, - callback: PaginationCallback< - protos.google.firestore.v1.IListCollectionIdsRequest, - protos.google.firestore.v1.IListCollectionIdsResponse|null|undefined, - string>): void; + request: protos.google.firestore.v1.IListCollectionIdsRequest, + options: CallOptions, + callback: PaginationCallback< + protos.google.firestore.v1.IListCollectionIdsRequest, + protos.google.firestore.v1.IListCollectionIdsResponse | null | undefined, + string + > + ): void; listCollectionIds( - request: protos.google.firestore.v1.IListCollectionIdsRequest, - callback: PaginationCallback< - protos.google.firestore.v1.IListCollectionIdsRequest, - protos.google.firestore.v1.IListCollectionIdsResponse|null|undefined, - string>): void; + request: protos.google.firestore.v1.IListCollectionIdsRequest, + callback: PaginationCallback< + protos.google.firestore.v1.IListCollectionIdsRequest, + protos.google.firestore.v1.IListCollectionIdsResponse | null | undefined, + string + > + ): void; listCollectionIds( - request?: protos.google.firestore.v1.IListCollectionIdsRequest, - optionsOrCallback?: CallOptions|PaginationCallback< + request?: protos.google.firestore.v1.IListCollectionIdsRequest, + optionsOrCallback?: + | CallOptions + | PaginationCallback< protos.google.firestore.v1.IListCollectionIdsRequest, - protos.google.firestore.v1.IListCollectionIdsResponse|null|undefined, - string>, - callback?: PaginationCallback< - protos.google.firestore.v1.IListCollectionIdsRequest, - protos.google.firestore.v1.IListCollectionIdsResponse|null|undefined, - string>): - Promise<[ - string[], - protos.google.firestore.v1.IListCollectionIdsRequest|null, - protos.google.firestore.v1.IListCollectionIdsResponse - ]>|void { + | protos.google.firestore.v1.IListCollectionIdsResponse + | null + | undefined, + string + >, + callback?: PaginationCallback< + protos.google.firestore.v1.IListCollectionIdsRequest, + protos.google.firestore.v1.IListCollectionIdsResponse | null | undefined, + string + > + ): Promise< + [ + string[], + protos.google.firestore.v1.IListCollectionIdsRequest | null, + protos.google.firestore.v1.IListCollectionIdsResponse, + ] + > | void { request = request || {}; let options: CallOptions; if (typeof optionsOrCallback === 'function' && callback === undefined) { callback = optionsOrCallback; options = {}; - } - else { + } else { options = optionsOrCallback as CallOptions; } options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - options.otherArgs.headers[ - 'x-goog-request-params' - ] = this._gaxModule.routingHeader.fromParams({ - 'parent': request.parent ?? '', + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + parent: request.parent ?? '', + }); + this.initialize().catch(err => { + throw err; }); - this.initialize().catch(err => {throw err}); - const wrappedCallback: PaginationCallback< - protos.google.firestore.v1.IListCollectionIdsRequest, - protos.google.firestore.v1.IListCollectionIdsResponse|null|undefined, - string>|undefined = callback + const wrappedCallback: + | PaginationCallback< + protos.google.firestore.v1.IListCollectionIdsRequest, + | protos.google.firestore.v1.IListCollectionIdsResponse + | null + | undefined, + string + > + | undefined = callback ? (error, values, nextPageRequest, rawResponse) => { this._log.info('listCollectionIds values %j', values); callback!(error, values, nextPageRequest, rawResponse); // We verified callback above. @@ -2218,63 +2550,66 @@ export class FirestoreClient { this._log.info('listCollectionIds request %j', request); return this.innerApiCalls .listCollectionIds(request, options, wrappedCallback) - ?.then(([response, input, output]: [ - string[], - protos.google.firestore.v1.IListCollectionIdsRequest|null, - protos.google.firestore.v1.IListCollectionIdsResponse - ]) => { - this._log.info('listCollectionIds values %j', response); - return [response, input, output]; - }); + ?.then( + ([response, input, output]: [ + string[], + protos.google.firestore.v1.IListCollectionIdsRequest | null, + protos.google.firestore.v1.IListCollectionIdsResponse, + ]) => { + this._log.info('listCollectionIds values %j', response); + return [response, input, output]; + } + ); } -/** - * Equivalent to `listCollectionIds`, but returns a NodeJS Stream object. - * @param {Object} request - * The request object that will be sent. - * @param {string} request.parent - * Required. The parent document. In the format: - * `projects/{project_id}/databases/{database_id}/documents/{document_path}`. - * For example: - * `projects/my-project/databases/my-database/documents/chatrooms/my-chatroom` - * @param {number} request.pageSize - * The maximum number of results to return. - * @param {string} request.pageToken - * A page token. Must be a value from - * {@link protos.google.firestore.v1.ListCollectionIdsResponse|ListCollectionIdsResponse}. - * @param {google.protobuf.Timestamp} request.readTime - * Reads documents as they were at the given time. - * - * This must be a microsecond precision timestamp within the past one hour, - * or if Point-in-Time Recovery is enabled, can additionally be a whole - * minute timestamp within the past 7 days. - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Stream} - * An object stream which emits an object representing string on 'data' event. - * The client library will perform auto-pagination by default: it will call the API as many - * times as needed. Note that it can affect your quota. - * We recommend using `listCollectionIdsAsync()` - * method described below for async iteration which you can stop as needed. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#auto-pagination | documentation } - * for more details and examples. - */ + /** + * Equivalent to `listCollectionIds`, but returns a NodeJS Stream object. + * @param {Object} request + * The request object that will be sent. + * @param {string} request.parent + * Required. The parent document. In the format: + * `projects/{project_id}/databases/{database_id}/documents/{document_path}`. + * For example: + * `projects/my-project/databases/my-database/documents/chatrooms/my-chatroom` + * @param {number} request.pageSize + * The maximum number of results to return. + * @param {string} request.pageToken + * A page token. Must be a value from + * {@link protos.google.firestore.v1.ListCollectionIdsResponse|ListCollectionIdsResponse}. + * @param {google.protobuf.Timestamp} request.readTime + * Reads documents as they were at the given time. + * + * This must be a microsecond precision timestamp within the past one hour, + * or if Point-in-Time Recovery is enabled, can additionally be a whole + * minute timestamp within the past 7 days. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Stream} + * An object stream which emits an object representing string on 'data' event. + * The client library will perform auto-pagination by default: it will call the API as many + * times as needed. Note that it can affect your quota. + * We recommend using `listCollectionIdsAsync()` + * method described below for async iteration which you can stop as needed. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#auto-pagination | documentation } + * for more details and examples. + */ listCollectionIdsStream( - request?: protos.google.firestore.v1.IListCollectionIdsRequest, - options?: CallOptions): - Transform{ + request?: protos.google.firestore.v1.IListCollectionIdsRequest, + options?: CallOptions + ): Transform { request = request || {}; options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - options.otherArgs.headers[ - 'x-goog-request-params' - ] = this._gaxModule.routingHeader.fromParams({ - 'parent': request.parent ?? '', - }); + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + parent: request.parent ?? '', + }); const defaultCallSettings = this._defaults['listCollectionIds']; const callSettings = defaultCallSettings.merge(options); - this.initialize().catch(err => {throw err}); + this.initialize().catch(err => { + throw err; + }); this._log.info('listCollectionIds stream %j', request); return this.descriptors.page.listCollectionIds.createStream( this.innerApiCalls.listCollectionIds as GaxCall, @@ -2283,56 +2618,57 @@ export class FirestoreClient { ); } -/** - * Equivalent to `listCollectionIds`, but returns an iterable object. - * - * `for`-`await`-`of` syntax is used with the iterable to get response elements on-demand. - * @param {Object} request - * The request object that will be sent. - * @param {string} request.parent - * Required. The parent document. In the format: - * `projects/{project_id}/databases/{database_id}/documents/{document_path}`. - * For example: - * `projects/my-project/databases/my-database/documents/chatrooms/my-chatroom` - * @param {number} request.pageSize - * The maximum number of results to return. - * @param {string} request.pageToken - * A page token. Must be a value from - * {@link protos.google.firestore.v1.ListCollectionIdsResponse|ListCollectionIdsResponse}. - * @param {google.protobuf.Timestamp} request.readTime - * Reads documents as they were at the given time. - * - * This must be a microsecond precision timestamp within the past one hour, - * or if Point-in-Time Recovery is enabled, can additionally be a whole - * minute timestamp within the past 7 days. - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Object} - * An iterable Object that allows {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols | async iteration }. - * When you iterate the returned iterable, each element will be an object representing - * string. The API will be called under the hood as needed, once per the page, - * so you can stop the iteration when you don't need more results. - * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#auto-pagination | documentation } - * for more details and examples. - * @example - * region_tag:firestore_v1_generated_Firestore_ListCollectionIds_async - */ + /** + * Equivalent to `listCollectionIds`, but returns an iterable object. + * + * `for`-`await`-`of` syntax is used with the iterable to get response elements on-demand. + * @param {Object} request + * The request object that will be sent. + * @param {string} request.parent + * Required. The parent document. In the format: + * `projects/{project_id}/databases/{database_id}/documents/{document_path}`. + * For example: + * `projects/my-project/databases/my-database/documents/chatrooms/my-chatroom` + * @param {number} request.pageSize + * The maximum number of results to return. + * @param {string} request.pageToken + * A page token. Must be a value from + * {@link protos.google.firestore.v1.ListCollectionIdsResponse|ListCollectionIdsResponse}. + * @param {google.protobuf.Timestamp} request.readTime + * Reads documents as they were at the given time. + * + * This must be a microsecond precision timestamp within the past one hour, + * or if Point-in-Time Recovery is enabled, can additionally be a whole + * minute timestamp within the past 7 days. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Object} + * An iterable Object that allows {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols | async iteration }. + * When you iterate the returned iterable, each element will be an object representing + * string. The API will be called under the hood as needed, once per the page, + * so you can stop the iteration when you don't need more results. + * Please see the {@link https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#auto-pagination | documentation } + * for more details and examples. + * @example + * region_tag:firestore_v1_generated_Firestore_ListCollectionIds_async + */ listCollectionIdsAsync( - request?: protos.google.firestore.v1.IListCollectionIdsRequest, - options?: CallOptions): - AsyncIterable{ + request?: protos.google.firestore.v1.IListCollectionIdsRequest, + options?: CallOptions + ): AsyncIterable { request = request || {}; options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; - options.otherArgs.headers[ - 'x-goog-request-params' - ] = this._gaxModule.routingHeader.fromParams({ - 'parent': request.parent ?? '', - }); + options.otherArgs.headers['x-goog-request-params'] = + this._gaxModule.routingHeader.fromParams({ + parent: request.parent ?? '', + }); const defaultCallSettings = this._defaults['listCollectionIds']; const callSettings = defaultCallSettings.merge(options); - this.initialize().catch(err => {throw err}); + this.initialize().catch(err => { + throw err; + }); this._log.info('listCollectionIds iterate %j', request); return this.descriptors.page.listCollectionIds.asyncIterate( this.innerApiCalls['listCollectionIds'] as GaxCall, @@ -2340,7 +2676,7 @@ export class FirestoreClient { callSettings ) as AsyncIterable; } -/** + /** * Gets information about a location. * * @param {Object} request @@ -2380,7 +2716,7 @@ export class FirestoreClient { return this.locationsClient.getLocation(request, options, callback); } -/** + /** * Lists information about the supported locations for this service. Returns an iterable object. * * `for`-`await`-`of` syntax is used with the iterable to get response elements on-demand. @@ -2418,7 +2754,6 @@ export class FirestoreClient { return this.locationsClient.listLocationsAsync(request, options); } - /** * Terminate the gRPC channel and close the client. * @@ -2431,9 +2766,11 @@ export class FirestoreClient { this._log.info('ending gRPC channel'); this._terminated = true; stub.close(); - this.locationsClient.close().catch(err => {throw err}); + this.locationsClient.close().catch(err => { + throw err; + }); }); } return Promise.resolve(); } -} \ No newline at end of file +} diff --git a/dev/system-test/firestore.ts b/dev/system-test/firestore.ts index 622c43aae..932d94a97 100644 --- a/dev/system-test/firestore.ts +++ b/dev/system-test/firestore.ts @@ -805,6 +805,25 @@ describe('CollectionReference class', () => { expect(missingDocs.map(doc => doc.id)).to.have.members(['b']); }); + it('lists documents (more than the max page size)', async () => { + const batch = firestore.batch(); + const expectedResults = []; + for (let i = 0; i < 400; i++) { + const docRef = randomCol.doc(`${i}`.padStart(3, '0')); + batch.set(docRef, {id: i}); + expectedResults.push(docRef.id); + } + await batch.commit(); + + const documentRefs = await randomCol.listDocuments(); + + const actualDocIds = documentRefs + .map(dr => dr.id) + .sort((a, b) => a.localeCompare(b)); + + expect(actualDocIds).to.deep.equal(expectedResults); + }); + it('supports withConverter()', async () => { const ref = await firestore .collection('col') @@ -1198,11 +1217,13 @@ describe('DocumentReference class', () => { }); it('has listCollections() method', () => { - const collections = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j']; + const collections: string[] = []; const promises: Array> = []; - for (const collection of collections) { - promises.push(randomCol.doc(`doc/${collection}/doc`).create({})); + for (let i = 0; i < 400; i++) { + const collectionId = i.toString().padStart(3, '0'); + promises.push(randomCol.doc(`doc/${collectionId}/doc`).create({})); + collections.push(collectionId); } return Promise.all(promises) @@ -5032,6 +5053,26 @@ describe('Aggregation queries', () => { return Promise.all(sets); } + it('can run count within a transaction with readtime', async () => { + const doc = col.doc(); + const writeResult: WriteResult = await doc.create({some: 'data'}); + + const count = await firestore.runTransaction(t => t.get(col.count()), { + readOnly: true, + readTime: writeResult.writeTime, + }); + expect(count.data().count).to.equal(1); + + const countBefore = await firestore.runTransaction( + t => t.get(col.count()), + { + readOnly: true, + readTime: Timestamp.fromMillis(writeResult.writeTime.toMillis() - 1), + } + ); + expect(countBefore.data().count).to.equal(0); + }); + it('can run count query using aggregate api', async () => { const testDocs = { a: {author: 'authorA', title: 'titleA'}, diff --git a/dev/system-test/pipeline.ts b/dev/system-test/pipeline.ts index 1983e74ec..2a851b849 100644 --- a/dev/system-test/pipeline.ts +++ b/dev/system-test/pipeline.ts @@ -12,7 +12,7 @@ // See the License for the specific language governing permissions and // limitations under the License. -import {DocumentData} from '@google-cloud/firestore'; +import {DocumentData, Pipelines} from '@google-cloud/firestore'; import { BooleanExpr, @@ -107,7 +107,6 @@ import { PipelineResult, PipelineSnapshot, Pipeline, - FindNearestOptions, } from '../src/pipelines'; import { @@ -445,6 +444,186 @@ describe.only('Pipeline class', () => { }); }); + describe('pipeline explain', () => { + it('mode: analyze, format: text', async () => { + const ppl = firestore + .pipeline() + .collection(randomCol.path) + .sort(ascending('__name__')); + + const snapshot = await ppl.execute({ + explainOptions: { + mode: 'analyze', + outputFormat: 'text', + }, + }); + + expect(snapshot.explainStats).not.to.be.undefined; + expect(snapshot.explainStats!.text.length).to.be.greaterThan(0); + expect(snapshot.explainStats!.text.charAt(0)).not.to.equal('{'); + + expect(snapshot.explainStats!.rawData.type_url).to.equal( + 'type.googleapis.com/google.protobuf.StringValue' + ); + expect(snapshot.explainStats!.rawData.value).to.not.be.null; + expect(snapshot.explainStats!.rawData.value).to.not.be.undefined; + + expect(snapshot.results.length).to.equal(10); + expect(snapshot.pipeline).to.equal(ppl); + expectResults( + snapshot, + 'book1', + 'book10', + 'book2', + 'book3', + 'book4', + 'book5', + 'book6', + 'book7', + 'book8', + 'book9' + ); + }); + + it('mode: analyze, format: unspecified', async () => { + const ppl = firestore + .pipeline() + .collection(randomCol.path) + .sort(ascending('__name__')); + const snapshot = await ppl.execute({ + explainOptions: { + mode: 'analyze', + }, + }); + expect(snapshot.explainStats).not.to.be.undefined; + expect(snapshot.explainStats!.text.length).to.be.greaterThan(0); + expect(snapshot.explainStats!.text.charAt(0)).not.to.equal('{'); + + expect(snapshot.explainStats!.rawData.type_url).to.equal( + 'type.googleapis.com/google.protobuf.StringValue' + ); + expect(snapshot.explainStats!.rawData.value).to.not.be.null; + expect(snapshot.explainStats!.rawData.value).to.not.be.undefined; + + expect(snapshot.results.length).to.equal(10); + expect(snapshot.pipeline).to.equal(ppl); + expectResults( + snapshot, + 'book1', + 'book10', + 'book2', + 'book3', + 'book4', + 'book5', + 'book6', + 'book7', + 'book8', + 'book9' + ); + }); + + it('mode: analyze, format: json', async () => { + const ppl = firestore + .pipeline() + .collection(randomCol.path) + .sort(ascending('__name__')); + const snapshot = await ppl.execute({ + explainOptions: { + mode: 'analyze', + outputFormat: 'json', + }, + }); + expect(snapshot.explainStats).not.to.be.undefined; + expect(snapshot.explainStats!.text.length).to.be.greaterThan(0); + expect(snapshot.explainStats!.text.charAt(0)).to.equal('{'); + + expect(snapshot.explainStats!.rawData.type_url).to.equal( + 'type.googleapis.com/google.protobuf.StringValue' + ); + expect(snapshot.explainStats!.rawData.value).to.not.be.null; + expect(snapshot.explainStats!.rawData.value).to.not.be.undefined; + + expect(snapshot.explainStats!.json).not.to.be.null; + expect(typeof snapshot.explainStats!.json).to.be.equal('object'); + console.log(snapshot.explainStats!.json); + + expect(snapshot.results.length).to.equal(10); + expect(snapshot.pipeline).to.equal(ppl); + expectResults( + snapshot, + 'book1', + 'book10', + 'book2', + 'book3', + 'book4', + 'book5', + 'book6', + 'book7', + 'book8', + 'book9' + ); + }); + + it('mode: execute, format: text', async () => { + const ppl = firestore + .pipeline() + .collection(randomCol.path) + .sort(ascending('__name__')); + const snapshot = await ppl.execute({ + explainOptions: { + mode: 'execute', + outputFormat: 'text', + }, + }); + expect(snapshot.explainStats).to.be.undefined; + + expect(snapshot.results.length).to.equal(10); + expect(snapshot.pipeline).to.equal(ppl); + expectResults( + snapshot, + 'book1', + 'book10', + 'book2', + 'book3', + 'book4', + 'book5', + 'book6', + 'book7', + 'book8', + 'book9' + ); + }); + + it('mode: unspecified, format: text', async () => { + const ppl = firestore + .pipeline() + .collection(randomCol.path) + .sort(ascending('__name__')); + const snapshot = await ppl.execute({ + explainOptions: { + outputFormat: 'text', + }, + }); + expect(snapshot.explainStats).to.be.undefined; + + expect(snapshot.results.length).to.equal(10); + expect(snapshot.pipeline).to.equal(ppl); + expectResults( + snapshot, + 'book1', + 'book10', + 'book2', + 'book3', + 'book4', + 'book5', + 'book6', + 'book7', + 'book8', + 'book9' + ); + }); + }); + describe('pipeline sources', () => { it('supports CollectionReference as source', async () => { const snapshot = await firestore @@ -837,6 +1016,35 @@ describe.only('Pipeline class', () => { }); }); + it('supports aggregate options', async () => { + let snapshot = await firestore + .pipeline() + .collection(randomCol.path) + .aggregate({ + accumulators: [countAll().as('count')], + }) + .execute(); + expectResults(snapshot, {count: 10}); + + snapshot = await firestore + .pipeline() + .collection(randomCol.path) + .where(eq('genre', 'Science Fiction')) + .aggregate( + countAll().as('count'), + avg('rating').as('avgRating'), + maximum('rating').as('maxRating'), + sum('rating').as('sumRating') + ) + .execute(); + expectResults(snapshot, { + count: 2, + avgRating: 4.4, + maxRating: 4.6, + sumRating: 8.8, + }); + }); + it('rejects groups without accumulators', async () => { expect( firestore @@ -932,6 +1140,33 @@ describe.only('Pipeline class', () => { {genre: 'Southern Gothic', author: 'Harper Lee'} ); }); + + it('supports options', async () => { + const snapshot = await firestore + .pipeline() + .collection(randomCol.path) + .distinct('genre', 'author') + .sort({ + orderings: [ + field('genre').ascending(), + field('author').ascending(), + ], + }) + .execute(); + expectResults( + snapshot, + {genre: 'Dystopian', author: 'George Orwell'}, + {genre: 'Dystopian', author: 'Margaret Atwood'}, + {genre: 'Fantasy', author: 'J.R.R. Tolkien'}, + {genre: 'Magical Realism', author: 'Gabriel García Márquez'}, + {genre: 'Modernist', author: 'F. Scott Fitzgerald'}, + {genre: 'Psychological Thriller', author: 'Fyodor Dostoevsky'}, + {genre: 'Romance', author: 'Jane Austen'}, + {genre: 'Science Fiction', author: 'Douglas Adams'}, + {genre: 'Science Fiction', author: 'Frank Herbert'}, + {genre: 'Southern Gothic', author: 'Harper Lee'} + ); + }); }); describe('select stage', () => { @@ -962,6 +1197,24 @@ describe.only('Pipeline class', () => { {title: "The Handmaid's Tale", author: 'Margaret Atwood'} ); }); + + it('supports options', async () => { + const snapshot = await firestore + .pipeline() + .collection(randomCol.path) + .select({selections: ['title', field('author').as('auth0r')]}) + .sort(field('auth0r').ascending()) + .limit(2) + .execute(); + expectResults( + snapshot, + { + title: "The Hitchhiker's Guide to the Galaxy", + auth0r: 'Douglas Adams', + }, + {title: 'The Great Gatsby', auth0r: 'F. Scott Fitzgerald'} + ); + }); }); describe('addField stage', () => { @@ -993,38 +1246,211 @@ describe.only('Pipeline class', () => { }, { title: 'One Hundred Years of Solitude', - author: 'Gabriel García Márquez', - foo: 'bar', + author: 'Gabriel García Márquez', + foo: 'bar', + }, + {title: '1984', author: 'George Orwell', foo: 'bar'}, + { + title: 'To Kill a Mockingbird', + author: 'Harper Lee', + foo: 'bar', + }, + { + title: 'The Lord of the Rings', + author: 'J.R.R. Tolkien', + foo: 'bar', + }, + {title: 'Pride and Prejudice', author: 'Jane Austen', foo: 'bar'}, + { + title: "The Handmaid's Tale", + author: 'Margaret Atwood', + foo: 'bar', + } + ); + }); + + it('supports options', async () => { + const snapshot = await firestore + .pipeline() + .collection(randomCol.path) + .select('title', 'author') + .addFields({ + fields: [constant('bar').as('foo')], + }) + .sort(field('author').ascending()) + .execute(); + expectResults( + snapshot, + { + title: "The Hitchhiker's Guide to the Galaxy", + author: 'Douglas Adams', + foo: 'bar', + }, + { + title: 'The Great Gatsby', + author: 'F. Scott Fitzgerald', + foo: 'bar', + }, + {title: 'Dune', author: 'Frank Herbert', foo: 'bar'}, + { + title: 'Crime and Punishment', + author: 'Fyodor Dostoevsky', + foo: 'bar', + }, + { + title: 'One Hundred Years of Solitude', + author: 'Gabriel García Márquez', + foo: 'bar', + }, + {title: '1984', author: 'George Orwell', foo: 'bar'}, + { + title: 'To Kill a Mockingbird', + author: 'Harper Lee', + foo: 'bar', + }, + { + title: 'The Lord of the Rings', + author: 'J.R.R. Tolkien', + foo: 'bar', + }, + {title: 'Pride and Prejudice', author: 'Jane Austen', foo: 'bar'}, + { + title: "The Handmaid's Tale", + author: 'Margaret Atwood', + foo: 'bar', + } + ); + }); + }); + + describe('removeFields stage', () => { + it('can remove fields', async () => { + const snapshot = await firestore + .pipeline() + .collection(randomCol.path) + .select('title', 'author') + .sort(field('author').ascending()) + .removeFields(field('author')) + .sort(field('author').ascending()) + .execute(); + expectResults( + snapshot, + { + title: "The Hitchhiker's Guide to the Galaxy", + }, + { + title: 'The Great Gatsby', + }, + {title: 'Dune'}, + { + title: 'Crime and Punishment', + }, + { + title: 'One Hundred Years of Solitude', + }, + {title: '1984'}, + { + title: 'To Kill a Mockingbird', + }, + { + title: 'The Lord of the Rings', + }, + {title: 'Pride and Prejudice'}, + { + title: "The Handmaid's Tale", + } + ); + }); + + it('supports options', async () => { + const snapshot = await firestore + .pipeline() + .collection(randomCol.path) + .select('title', 'author', 'genre') + .sort(field('author').ascending()) + .removeFields({ + fields: [field('author'), 'genre'], + }) + .sort(field('author').ascending()) + .execute(); + expectResults( + snapshot, + { + title: "The Hitchhiker's Guide to the Galaxy", + }, + { + title: 'The Great Gatsby', + }, + {title: 'Dune'}, + { + title: 'Crime and Punishment', + }, + { + title: 'One Hundred Years of Solitude', + }, + {title: '1984'}, + { + title: 'To Kill a Mockingbird', + }, + { + title: 'The Lord of the Rings', + }, + {title: 'Pride and Prejudice'}, + { + title: "The Handmaid's Tale", + } + ); + }); + }); + + describe('findNearest stage', () => { + it('can find nearest', async () => { + const snapshot = await firestore + .pipeline() + .collection(randomCol.path) + .select('title', 'author') + .sort(field('author').ascending()) + .removeFields(field('author')) + .sort(field('author').ascending()) + .execute(); + expectResults( + snapshot, + { + title: "The Hitchhiker's Guide to the Galaxy", + }, + { + title: 'The Great Gatsby', + }, + {title: 'Dune'}, + { + title: 'Crime and Punishment', + }, + { + title: 'One Hundred Years of Solitude', }, - {title: '1984', author: 'George Orwell', foo: 'bar'}, + {title: '1984'}, { title: 'To Kill a Mockingbird', - author: 'Harper Lee', - foo: 'bar', }, { title: 'The Lord of the Rings', - author: 'J.R.R. Tolkien', - foo: 'bar', }, - {title: 'Pride and Prejudice', author: 'Jane Austen', foo: 'bar'}, + {title: 'Pride and Prejudice'}, { title: "The Handmaid's Tale", - author: 'Margaret Atwood', - foo: 'bar', } ); }); - }); - describe('removeFields stage', () => { - it('can remove fields', async () => { + it('supports options', async () => { const snapshot = await firestore .pipeline() .collection(randomCol.path) - .select('title', 'author') + .select('title', 'author', 'genre') .sort(field('author').ascending()) - .removeFields(field('author')) + .removeFields({ + fields: [field('author'), 'genre'], + }) .sort(field('author').ascending()) .execute(); expectResults( @@ -1071,6 +1497,7 @@ describe.only('Pipeline class', () => { .execute(); expectResults(snapshot, 'book10', 'book4'); }); + it('where with and (3 conditions)', async () => { const snapshot = await firestore .pipeline() @@ -1085,6 +1512,7 @@ describe.only('Pipeline class', () => { .execute(); expectResults(snapshot, 'book4'); }); + it('where with or', async () => { const snapshot = await firestore .pipeline() @@ -1129,6 +1557,20 @@ describe.only('Pipeline class', () => { {title: "The Handmaid's Tale"} ); }); + + it('supports options', async () => { + const snapshot = await firestore + .pipeline() + .collection(randomCol.path) + .where({ + condition: and( + gt('rating', 4.5), + eqAny('genre', ['Science Fiction', 'Romance', 'Fantasy']) + ), + }) + .execute(); + expectResults(snapshot, 'book10', 'book4'); + }); }); describe('sort, offset, and limit stages', () => { @@ -1148,6 +1590,25 @@ describe.only('Pipeline class', () => { {title: 'The Lord of the Rings', author: 'J.R.R. Tolkien'} ); }); + + it('sort, offset, and limit stages support options', async () => { + const snapshot = await firestore + .pipeline() + .collection(randomCol.path) + .sort({ + orderings: [field('author').ascending()], + }) + .offset({offset: 5}) + .limit({limit: 3}) + .select('title', 'author') + .execute(); + expectResults( + snapshot, + {title: '1984', author: 'George Orwell'}, + {title: 'To Kill a Mockingbird', author: 'Harper Lee'}, + {title: 'The Lord of the Rings', author: 'J.R.R. Tolkien'} + ); + }); }); describe('generic stage', () => { @@ -1275,6 +1736,37 @@ describe.only('Pipeline class', () => { } ); }); + + it('can perform FindNearest query', async () => { + const snapshot = await firestore + .pipeline() + .collection(randomCol) + .genericStage( + 'find_nearest', + [ + field('embedding'), + FieldValue.vector([10, 1, 2, 1, 1, 1, 1, 1, 1, 1]), + 'euclidean', + ], + { + distance_field: field('computedDistance'), + limit: 2, + } + ) + .select('title', 'computedDistance') + .execute(); + expectResults( + snapshot, + { + title: "The Hitchhiker's Guide to the Galaxy", + computedDistance: 1, + }, + { + title: 'One Hundred Years of Solitude', + computedDistance: 12.041594578792296, + } + ); + }); }); describe('replaceWith stage', () => { @@ -1311,6 +1803,20 @@ describe.only('Pipeline class', () => { baz: {title: "The Hitchhiker's Guide to the Galaxy"}, }); }); + + it('supports options', async () => { + const snapshot = await firestore + .pipeline() + .collection(randomCol.path) + .where(eq('title', "The Hitchhiker's Guide to the Galaxy")) + .replaceWith({map: 'awards'}) + .execute(); + expectResults(snapshot, { + hugo: true, + nebula: false, + others: {unknown: {year: 1980}}, + }); + }); }); describe('sample stage', () => { @@ -1381,6 +1887,38 @@ describe.only('Pipeline class', () => { 'book9' ); }); + + it('supports options', async () => { + const snapshot = await firestore + .pipeline() + .collection(randomCol.path) + .union({other: firestore.pipeline().collection(randomCol.path)}) + .sort(field(FieldPath.documentId()).ascending()) + .execute(); + expectResults( + snapshot, + 'book1', + 'book1', + 'book10', + 'book10', + 'book2', + 'book2', + 'book3', + 'book3', + 'book4', + 'book4', + 'book5', + 'book5', + 'book6', + 'book6', + 'book7', + 'book7', + 'book8', + 'book8', + 'book9', + 'book9' + ); + }); }); describe('unnest stage', () => { @@ -1451,6 +1989,78 @@ describe.only('Pipeline class', () => { } ); }); + + it('unnest with index field', async () => { + const snapshot = await firestore + .pipeline() + .collection(randomCol.path) + .where(eq('title', "The Hitchhiker's Guide to the Galaxy")) + .unnest(field('tags').as('tag'), 'tagsIndex') + .select( + 'title', + 'author', + 'genre', + 'published', + 'rating', + 'tags', + 'tag', + 'awards', + 'nestedField' + ) + .execute(); + expectResults( + snapshot, + { + title: "The Hitchhiker's Guide to the Galaxy", + author: 'Douglas Adams', + genre: 'Science Fiction', + published: 1979, + rating: 4.2, + tags: ['comedy', 'space', 'adventure'], + tag: 'comedy', + awards: { + hugo: true, + nebula: false, + others: {unknown: {year: 1980}}, + }, + nestedField: {'level.1': {'level.2': true}}, + tagsIndex: 0, + }, + { + title: "The Hitchhiker's Guide to the Galaxy", + author: 'Douglas Adams', + genre: 'Science Fiction', + published: 1979, + rating: 4.2, + tags: ['comedy', 'space', 'adventure'], + tag: 'space', + awards: { + hugo: true, + nebula: false, + others: {unknown: {year: 1980}}, + }, + nestedField: {'level.1': {'level.2': true}}, + tagsIndex: 1, + }, + { + title: "The Hitchhiker's Guide to the Galaxy", + author: 'Douglas Adams', + genre: 'Science Fiction', + published: 1979, + rating: 4.2, + tags: ['comedy', 'space', 'adventure'], + tag: 'adventure', + awards: { + hugo: true, + nebula: false, + others: {unknown: {year: 1980}}, + }, + nestedField: {'level.1': {'level.2': true}}, + tagsIndex: 2, + } + ); + }); + it('unnest an expr', async () => { const snapshot = await firestore .pipeline() @@ -1518,15 +2128,87 @@ describe.only('Pipeline class', () => { } ); }); + + it('supports options', async () => { + const snapshot = await firestore + .pipeline() + .collection(randomCol.path) + .where(eq('title', "The Hitchhiker's Guide to the Galaxy")) + .unnest({ + selectable: field('tags').as('tag'), + indexField: 'tagsIndex', + }) + .select( + 'title', + 'author', + 'genre', + 'published', + 'rating', + 'tags', + 'tag', + 'awards', + 'nestedField' + ) + .execute(); + expectResults( + snapshot, + { + title: "The Hitchhiker's Guide to the Galaxy", + author: 'Douglas Adams', + genre: 'Science Fiction', + published: 1979, + rating: 4.2, + tags: ['comedy', 'space', 'adventure'], + tag: 'comedy', + awards: { + hugo: true, + nebula: false, + others: {unknown: {year: 1980}}, + }, + nestedField: {'level.1': {'level.2': true}}, + tagsIndex: 0, + }, + { + title: "The Hitchhiker's Guide to the Galaxy", + author: 'Douglas Adams', + genre: 'Science Fiction', + published: 1979, + rating: 4.2, + tags: ['comedy', 'space', 'adventure'], + tag: 'space', + awards: { + hugo: true, + nebula: false, + others: {unknown: {year: 1980}}, + }, + nestedField: {'level.1': {'level.2': true}}, + tagsIndex: 1, + }, + { + title: "The Hitchhiker's Guide to the Galaxy", + author: 'Douglas Adams', + genre: 'Science Fiction', + published: 1979, + rating: 4.2, + tags: ['comedy', 'space', 'adventure'], + tag: 'adventure', + awards: { + hugo: true, + nebula: false, + others: {unknown: {year: 1980}}, + }, + nestedField: {'level.1': {'level.2': true}}, + tagsIndex: 2, + } + ); + }); }); describe('findNearest stage', () => { it('run pipeline with findNearest', async () => { - const measures: Array = [ - 'euclidean', - 'dot_product', - 'cosine', - ]; + const measures: Array< + Pipelines.FindNearestStageOptions['distanceMeasure'] + > = ['euclidean', 'dot_product', 'cosine']; for (const measure of measures) { const snapshot = await firestore .pipeline() @@ -2912,28 +3594,39 @@ describe.only('Pipeline class', () => { } ); }); -}); -/** - * @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. - */ + describe('stage options', () => { + describe('forceIndex', () => { + // SKIP: requires pre-existing index + it.skip('Collection Stage', async () => { + const snapshot = await firestore + .pipeline() + .collection({ + collection: randomCol, + forceIndex: 'unknown', + }) + .execute(); + expect(snapshot.results.length).to.equal(10); + }); + + // SKIP: requires pre-existing index + it.skip('CollectionGroup Stage', async () => { + const snapshot = await firestore + .pipeline() + .collectionGroup({ + collectionId: randomCol.id, + forceIndex: 'unknown', + }) + .execute(); + expect(snapshot.results.length).to.equal(10); + }); + }); + }); +}); // This is the Query integration tests from the lite API (no cache support) // with some additional test cases added for more complete coverage. -describe.only('Query to Pipeline', () => { +describe('Query to Pipeline', () => { async function execute(ppl: Pipeline): Promise { return ppl.execute(); } diff --git a/dev/test/collection.ts b/dev/test/collection.ts index c2d5b845e..f9b1e3b4b 100644 --- a/dev/test/collection.ts +++ b/dev/test/collection.ts @@ -156,7 +156,6 @@ describe('Collection interface', () => { parent: `${DATABASE_ROOT}/documents/a/b`, collectionId: 'c', showMissing: true, - pageSize: 65535, mask: {fieldPaths: []}, }); diff --git a/dev/test/document.ts b/dev/test/document.ts index bb33d8fd9..c29030a15 100644 --- a/dev/test/document.ts +++ b/dev/test/document.ts @@ -2223,7 +2223,6 @@ describe('listCollections() method', () => { listCollectionIds: request => { expect(request).to.deep.eq({ parent: `projects/${PROJECT_ID}/databases/(default)/documents/coll/doc`, - pageSize: 65535, }); return response(['second', 'first']); diff --git a/dev/test/gapic_firestore_admin_v1.ts b/dev/test/gapic_firestore_admin_v1.ts index 156f249f0..a1d856240 100644 --- a/dev/test/gapic_firestore_admin_v1.ts +++ b/dev/test/gapic_firestore_admin_v1.ts @@ -25,5123 +25,6387 @@ import * as firestoreadminModule from '../src/v1'; import {PassThrough} from 'stream'; -import {protobuf, LROperation, operationsProtos, LocationProtos} from 'google-gax'; +import { + protobuf, + LROperation, + operationsProtos, + LocationProtos, +} from 'google-gax'; // Dynamically loaded proto JSON is needed to get the type information // to fill in default values for request objects -const root = protobuf.Root.fromJSON(require('../protos/admin_v1.json')).resolveAll(); +const root = protobuf.Root.fromJSON( + require('../protos/admin_v1.json') +).resolveAll(); // eslint-disable-next-line @typescript-eslint/no-unused-vars function getTypeDefaultValue(typeName: string, fields: string[]) { - let type = root.lookupType(typeName) as protobuf.Type; - for (const field of fields.slice(0, -1)) { - type = type.fields[field]?.resolvedType as protobuf.Type; - } - return type.fields[fields[fields.length - 1]]?.defaultValue; + let type = root.lookupType(typeName) as protobuf.Type; + for (const field of fields.slice(0, -1)) { + type = type.fields[field]?.resolvedType as protobuf.Type; + } + return type.fields[fields[fields.length - 1]]?.defaultValue; } function generateSampleMessage(instance: T) { - const filledObject = (instance.constructor as typeof protobuf.Message) - .toObject(instance as protobuf.Message, {defaults: true}); - return (instance.constructor as typeof protobuf.Message).fromObject(filledObject) as T; + const filledObject = ( + instance.constructor as typeof protobuf.Message + ).toObject(instance as protobuf.Message, {defaults: true}); + return (instance.constructor as typeof protobuf.Message).fromObject( + filledObject + ) as T; } function stubSimpleCall(response?: ResponseType, error?: Error) { - return error ? sinon.stub().rejects(error) : sinon.stub().resolves([response]); + return error + ? sinon.stub().rejects(error) + : sinon.stub().resolves([response]); } -function stubSimpleCallWithCallback(response?: ResponseType, error?: Error) { - return error ? sinon.stub().callsArgWith(2, error) : sinon.stub().callsArgWith(2, null, response); +function stubSimpleCallWithCallback( + response?: ResponseType, + error?: Error +) { + return error + ? sinon.stub().callsArgWith(2, error) + : sinon.stub().callsArgWith(2, null, response); } -function stubLongRunningCall(response?: ResponseType, callError?: Error, lroError?: Error) { - const innerStub = lroError ? sinon.stub().rejects(lroError) : sinon.stub().resolves([response]); - const mockOperation = { - promise: innerStub, - }; - return callError ? sinon.stub().rejects(callError) : sinon.stub().resolves([mockOperation]); +function stubLongRunningCall( + response?: ResponseType, + callError?: Error, + lroError?: Error +) { + const innerStub = lroError + ? sinon.stub().rejects(lroError) + : sinon.stub().resolves([response]); + const mockOperation = { + promise: innerStub, + }; + return callError + ? sinon.stub().rejects(callError) + : sinon.stub().resolves([mockOperation]); } -function stubLongRunningCallWithCallback(response?: ResponseType, callError?: Error, lroError?: Error) { - const innerStub = lroError ? sinon.stub().rejects(lroError) : sinon.stub().resolves([response]); - const mockOperation = { - promise: innerStub, - }; - return callError ? sinon.stub().callsArgWith(2, callError) : sinon.stub().callsArgWith(2, null, mockOperation); +function stubLongRunningCallWithCallback( + response?: ResponseType, + callError?: Error, + lroError?: Error +) { + const innerStub = lroError + ? sinon.stub().rejects(lroError) + : sinon.stub().resolves([response]); + const mockOperation = { + promise: innerStub, + }; + return callError + ? sinon.stub().callsArgWith(2, callError) + : sinon.stub().callsArgWith(2, null, mockOperation); } -function stubPageStreamingCall(responses?: ResponseType[], error?: Error) { - const pagingStub = sinon.stub(); - if (responses) { - for (let i = 0; i < responses.length; ++i) { - pagingStub.onCall(i).callsArgWith(2, null, responses[i]); - } +function stubPageStreamingCall( + responses?: ResponseType[], + error?: Error +) { + const pagingStub = sinon.stub(); + if (responses) { + for (let i = 0; i < responses.length; ++i) { + pagingStub.onCall(i).callsArgWith(2, null, responses[i]); } - const transformStub = error ? sinon.stub().callsArgWith(2, error) : pagingStub; - const mockStream = new PassThrough({ - objectMode: true, - transform: transformStub, - }); - // trigger as many responses as needed - if (responses) { - for (let i = 0; i < responses.length; ++i) { - setImmediate(() => { mockStream.write({}); }); - } - setImmediate(() => { mockStream.end(); }); - } else { - setImmediate(() => { mockStream.write({}); }); - setImmediate(() => { mockStream.end(); }); + } + const transformStub = error + ? sinon.stub().callsArgWith(2, error) + : pagingStub; + const mockStream = new PassThrough({ + objectMode: true, + transform: transformStub, + }); + // trigger as many responses as needed + if (responses) { + for (let i = 0; i < responses.length; ++i) { + setImmediate(() => { + mockStream.write({}); + }); } - return sinon.stub().returns(mockStream); + setImmediate(() => { + mockStream.end(); + }); + } else { + setImmediate(() => { + mockStream.write({}); + }); + setImmediate(() => { + mockStream.end(); + }); + } + return sinon.stub().returns(mockStream); } -function stubAsyncIterationCall(responses?: ResponseType[], error?: Error) { - let counter = 0; - const asyncIterable = { - [Symbol.asyncIterator]() { - return { - async next() { - if (error) { - return Promise.reject(error); - } - if (counter >= responses!.length) { - return Promise.resolve({done: true, value: undefined}); - } - return Promise.resolve({done: false, value: responses![counter++]}); - } - }; - } - }; - return sinon.stub().returns(asyncIterable); +function stubAsyncIterationCall( + responses?: ResponseType[], + error?: Error +) { + let counter = 0; + const asyncIterable = { + [Symbol.asyncIterator]() { + return { + async next() { + if (error) { + return Promise.reject(error); + } + if (counter >= responses!.length) { + return Promise.resolve({done: true, value: undefined}); + } + return Promise.resolve({done: false, value: responses![counter++]}); + }, + }; + }, + }; + return sinon.stub().returns(asyncIterable); } describe('v1.FirestoreAdminClient', () => { - describe('Common methods', () => { - it('has apiEndpoint', () => { - const client = new firestoreadminModule.FirestoreAdminClient(); - const apiEndpoint = client.apiEndpoint; - assert.strictEqual(apiEndpoint, 'firestore.googleapis.com'); - }); - - it('has universeDomain', () => { - const client = new firestoreadminModule.FirestoreAdminClient(); - const universeDomain = client.universeDomain; - assert.strictEqual(universeDomain, "googleapis.com"); - }); - - if (typeof process === 'object' && typeof process.emitWarning === 'function') { - it('throws DeprecationWarning if static servicePath is used', () => { - const stub = sinon.stub(process, 'emitWarning'); - const servicePath = firestoreadminModule.FirestoreAdminClient.servicePath; - assert.strictEqual(servicePath, 'firestore.googleapis.com'); - assert(stub.called); - stub.restore(); - }); - - it('throws DeprecationWarning if static apiEndpoint is used', () => { - const stub = sinon.stub(process, 'emitWarning'); - const apiEndpoint = firestoreadminModule.FirestoreAdminClient.apiEndpoint; - assert.strictEqual(apiEndpoint, 'firestore.googleapis.com'); - assert(stub.called); - stub.restore(); - }); - } - it('sets apiEndpoint according to universe domain camelCase', () => { - const client = new firestoreadminModule.FirestoreAdminClient({universeDomain: 'example.com'}); - const servicePath = client.apiEndpoint; - assert.strictEqual(servicePath, 'firestore.example.com'); - }); - - it('sets apiEndpoint according to universe domain snakeCase', () => { - const client = new firestoreadminModule.FirestoreAdminClient({universe_domain: 'example.com'}); - const servicePath = client.apiEndpoint; - assert.strictEqual(servicePath, 'firestore.example.com'); - }); - - if (typeof process === 'object' && 'env' in process) { - describe('GOOGLE_CLOUD_UNIVERSE_DOMAIN environment variable', () => { - it('sets apiEndpoint from environment variable', () => { - const saved = process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN']; - process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] = 'example.com'; - const client = new firestoreadminModule.FirestoreAdminClient(); - const servicePath = client.apiEndpoint; - assert.strictEqual(servicePath, 'firestore.example.com'); - if (saved) { - process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] = saved; - } else { - delete process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN']; - } - }); - - it('value configured in code has priority over environment variable', () => { - const saved = process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN']; - process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] = 'example.com'; - const client = new firestoreadminModule.FirestoreAdminClient({universeDomain: 'configured.example.com'}); - const servicePath = client.apiEndpoint; - assert.strictEqual(servicePath, 'firestore.configured.example.com'); - if (saved) { - process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] = saved; - } else { - delete process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN']; - } - }); - }); - } - it('does not allow setting both universeDomain and universe_domain', () => { - assert.throws(() => { new firestoreadminModule.FirestoreAdminClient({universe_domain: 'example.com', universeDomain: 'example.net'}); }); - }); - - it('has port', () => { - const port = firestoreadminModule.FirestoreAdminClient.port; - assert(port); - assert(typeof port === 'number'); - }); - - it('should create a client with no option', () => { - const client = new firestoreadminModule.FirestoreAdminClient(); - assert(client); - }); - - it('should create a client with gRPC fallback', () => { - const client = new firestoreadminModule.FirestoreAdminClient({ - fallback: true, - }); - assert(client); - }); - - it('has initialize method and supports deferred initialization', async () => { - const client = new firestoreadminModule.FirestoreAdminClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - assert.strictEqual(client.firestoreAdminStub, undefined); - await client.initialize(); - assert(client.firestoreAdminStub); - }); - - it('has close method for the initialized client', done => { - const client = new firestoreadminModule.FirestoreAdminClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.initialize().catch(err => {throw err}); - assert(client.firestoreAdminStub); - client.close().then(() => { - done(); - }).catch(err => {throw err}); - }); - - it('has close method for the non-initialized client', done => { - const client = new firestoreadminModule.FirestoreAdminClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - assert.strictEqual(client.firestoreAdminStub, undefined); - client.close().then(() => { - done(); - }).catch(err => {throw err}); - }); - - it('has getProjectId method', async () => { - const fakeProjectId = 'fake-project-id'; - const client = new firestoreadminModule.FirestoreAdminClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.auth.getProjectId = sinon.stub().resolves(fakeProjectId); - const result = await client.getProjectId(); - assert.strictEqual(result, fakeProjectId); - assert((client.auth.getProjectId as SinonStub).calledWithExactly()); - }); - - it('has getProjectId method with callback', async () => { - const fakeProjectId = 'fake-project-id'; - const client = new firestoreadminModule.FirestoreAdminClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.auth.getProjectId = sinon.stub().callsArgWith(0, null, fakeProjectId); - const promise = new Promise((resolve, reject) => { - client.getProjectId((err?: Error|null, projectId?: string|null) => { - if (err) { - reject(err); - } else { - resolve(projectId); - } - }); - }); - const result = await promise; - assert.strictEqual(result, fakeProjectId); - }); + describe('Common methods', () => { + it('has apiEndpoint', () => { + const client = new firestoreadminModule.FirestoreAdminClient(); + const apiEndpoint = client.apiEndpoint; + assert.strictEqual(apiEndpoint, 'firestore.googleapis.com'); }); - describe('getIndex', () => { - it('invokes getIndex without error', async () => { - const client = new firestoreadminModule.FirestoreAdminClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.firestore.admin.v1.GetIndexRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.firestore.admin.v1.GetIndexRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.firestore.admin.v1.Index() - ); - client.innerApiCalls.getIndex = stubSimpleCall(expectedResponse); - const [response] = await client.getIndex(request); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.getIndex as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.getIndex as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes getIndex without error using callback', async () => { - const client = new firestoreadminModule.FirestoreAdminClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.firestore.admin.v1.GetIndexRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.firestore.admin.v1.GetIndexRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.firestore.admin.v1.Index() - ); - client.innerApiCalls.getIndex = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.getIndex( - request, - (err?: Error|null, result?: protos.google.firestore.admin.v1.IIndex|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.getIndex as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.getIndex as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes getIndex with error', async () => { - const client = new firestoreadminModule.FirestoreAdminClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.firestore.admin.v1.GetIndexRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.firestore.admin.v1.GetIndexRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.getIndex = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.getIndex(request), expectedError); - const actualRequest = (client.innerApiCalls.getIndex as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.getIndex as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes getIndex with closed client', async () => { - const client = new firestoreadminModule.FirestoreAdminClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.firestore.admin.v1.GetIndexRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.firestore.admin.v1.GetIndexRequest', ['name']); - request.name = defaultValue1; - const expectedError = new Error('The client has already been closed.'); - client.close().catch(err => {throw err}); - await assert.rejects(client.getIndex(request), expectedError); - }); + it('has universeDomain', () => { + const client = new firestoreadminModule.FirestoreAdminClient(); + const universeDomain = client.universeDomain; + assert.strictEqual(universeDomain, 'googleapis.com'); }); - describe('deleteIndex', () => { - it('invokes deleteIndex without error', async () => { - const client = new firestoreadminModule.FirestoreAdminClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.firestore.admin.v1.DeleteIndexRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.firestore.admin.v1.DeleteIndexRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.protobuf.Empty() - ); - client.innerApiCalls.deleteIndex = stubSimpleCall(expectedResponse); - const [response] = await client.deleteIndex(request); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.deleteIndex as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.deleteIndex as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes deleteIndex without error using callback', async () => { - const client = new firestoreadminModule.FirestoreAdminClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.firestore.admin.v1.DeleteIndexRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.firestore.admin.v1.DeleteIndexRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.protobuf.Empty() - ); - client.innerApiCalls.deleteIndex = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.deleteIndex( - request, - (err?: Error|null, result?: protos.google.protobuf.IEmpty|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.deleteIndex as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.deleteIndex as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes deleteIndex with error', async () => { - const client = new firestoreadminModule.FirestoreAdminClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.firestore.admin.v1.DeleteIndexRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.firestore.admin.v1.DeleteIndexRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.deleteIndex = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.deleteIndex(request), expectedError); - const actualRequest = (client.innerApiCalls.deleteIndex as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.deleteIndex as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes deleteIndex with closed client', async () => { - const client = new firestoreadminModule.FirestoreAdminClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.firestore.admin.v1.DeleteIndexRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.firestore.admin.v1.DeleteIndexRequest', ['name']); - request.name = defaultValue1; - const expectedError = new Error('The client has already been closed.'); - client.close().catch(err => {throw err}); - await assert.rejects(client.deleteIndex(request), expectedError); - }); + if ( + typeof process === 'object' && + typeof process.emitWarning === 'function' + ) { + it('throws DeprecationWarning if static servicePath is used', () => { + const stub = sinon.stub(process, 'emitWarning'); + const servicePath = + firestoreadminModule.FirestoreAdminClient.servicePath; + assert.strictEqual(servicePath, 'firestore.googleapis.com'); + assert(stub.called); + stub.restore(); + }); + + it('throws DeprecationWarning if static apiEndpoint is used', () => { + const stub = sinon.stub(process, 'emitWarning'); + const apiEndpoint = + firestoreadminModule.FirestoreAdminClient.apiEndpoint; + assert.strictEqual(apiEndpoint, 'firestore.googleapis.com'); + assert(stub.called); + stub.restore(); + }); + } + it('sets apiEndpoint according to universe domain camelCase', () => { + const client = new firestoreadminModule.FirestoreAdminClient({ + universeDomain: 'example.com', + }); + const servicePath = client.apiEndpoint; + assert.strictEqual(servicePath, 'firestore.example.com'); }); - describe('getField', () => { - it('invokes getField without error', async () => { - const client = new firestoreadminModule.FirestoreAdminClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.firestore.admin.v1.GetFieldRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.firestore.admin.v1.GetFieldRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.firestore.admin.v1.Field() - ); - client.innerApiCalls.getField = stubSimpleCall(expectedResponse); - const [response] = await client.getField(request); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.getField as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.getField as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes getField without error using callback', async () => { - const client = new firestoreadminModule.FirestoreAdminClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.firestore.admin.v1.GetFieldRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.firestore.admin.v1.GetFieldRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.firestore.admin.v1.Field() - ); - client.innerApiCalls.getField = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.getField( - request, - (err?: Error|null, result?: protos.google.firestore.admin.v1.IField|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.getField as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.getField as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes getField with error', async () => { - const client = new firestoreadminModule.FirestoreAdminClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.firestore.admin.v1.GetFieldRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.firestore.admin.v1.GetFieldRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.getField = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.getField(request), expectedError); - const actualRequest = (client.innerApiCalls.getField as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.getField as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes getField with closed client', async () => { - const client = new firestoreadminModule.FirestoreAdminClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.firestore.admin.v1.GetFieldRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.firestore.admin.v1.GetFieldRequest', ['name']); - request.name = defaultValue1; - const expectedError = new Error('The client has already been closed.'); - client.close().catch(err => {throw err}); - await assert.rejects(client.getField(request), expectedError); - }); + it('sets apiEndpoint according to universe domain snakeCase', () => { + const client = new firestoreadminModule.FirestoreAdminClient({ + universe_domain: 'example.com', + }); + const servicePath = client.apiEndpoint; + assert.strictEqual(servicePath, 'firestore.example.com'); }); - describe('getDatabase', () => { - it('invokes getDatabase without error', async () => { - const client = new firestoreadminModule.FirestoreAdminClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.firestore.admin.v1.GetDatabaseRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.firestore.admin.v1.GetDatabaseRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.firestore.admin.v1.Database() - ); - client.innerApiCalls.getDatabase = stubSimpleCall(expectedResponse); - const [response] = await client.getDatabase(request); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.getDatabase as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.getDatabase as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes getDatabase without error using callback', async () => { - const client = new firestoreadminModule.FirestoreAdminClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.firestore.admin.v1.GetDatabaseRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.firestore.admin.v1.GetDatabaseRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.firestore.admin.v1.Database() - ); - client.innerApiCalls.getDatabase = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.getDatabase( - request, - (err?: Error|null, result?: protos.google.firestore.admin.v1.IDatabase|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.getDatabase as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.getDatabase as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes getDatabase with error', async () => { - const client = new firestoreadminModule.FirestoreAdminClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.firestore.admin.v1.GetDatabaseRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.firestore.admin.v1.GetDatabaseRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.getDatabase = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.getDatabase(request), expectedError); - const actualRequest = (client.innerApiCalls.getDatabase as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.getDatabase as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes getDatabase with closed client', async () => { - const client = new firestoreadminModule.FirestoreAdminClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.firestore.admin.v1.GetDatabaseRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.firestore.admin.v1.GetDatabaseRequest', ['name']); - request.name = defaultValue1; - const expectedError = new Error('The client has already been closed.'); - client.close().catch(err => {throw err}); - await assert.rejects(client.getDatabase(request), expectedError); + if (typeof process === 'object' && 'env' in process) { + describe('GOOGLE_CLOUD_UNIVERSE_DOMAIN environment variable', () => { + it('sets apiEndpoint from environment variable', () => { + const saved = process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN']; + process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] = 'example.com'; + const client = new firestoreadminModule.FirestoreAdminClient(); + const servicePath = client.apiEndpoint; + assert.strictEqual(servicePath, 'firestore.example.com'); + if (saved) { + process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] = saved; + } else { + delete process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN']; + } + }); + + it('value configured in code has priority over environment variable', () => { + const saved = process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN']; + process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] = 'example.com'; + const client = new firestoreadminModule.FirestoreAdminClient({ + universeDomain: 'configured.example.com', + }); + const servicePath = client.apiEndpoint; + assert.strictEqual(servicePath, 'firestore.configured.example.com'); + if (saved) { + process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] = saved; + } else { + delete process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN']; + } + }); + }); + } + it('does not allow setting both universeDomain and universe_domain', () => { + assert.throws(() => { + new firestoreadminModule.FirestoreAdminClient({ + universe_domain: 'example.com', + universeDomain: 'example.net', }); + }); }); - describe('listDatabases', () => { - it('invokes listDatabases without error', async () => { - const client = new firestoreadminModule.FirestoreAdminClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.firestore.admin.v1.ListDatabasesRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.firestore.admin.v1.ListDatabasesRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.firestore.admin.v1.ListDatabasesResponse() - ); - client.innerApiCalls.listDatabases = stubSimpleCall(expectedResponse); - const [response] = await client.listDatabases(request); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.listDatabases as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.listDatabases as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes listDatabases without error using callback', async () => { - const client = new firestoreadminModule.FirestoreAdminClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.firestore.admin.v1.ListDatabasesRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.firestore.admin.v1.ListDatabasesRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.firestore.admin.v1.ListDatabasesResponse() - ); - client.innerApiCalls.listDatabases = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.listDatabases( - request, - (err?: Error|null, result?: protos.google.firestore.admin.v1.IListDatabasesResponse|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.listDatabases as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.listDatabases as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes listDatabases with error', async () => { - const client = new firestoreadminModule.FirestoreAdminClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.firestore.admin.v1.ListDatabasesRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.firestore.admin.v1.ListDatabasesRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.listDatabases = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.listDatabases(request), expectedError); - const actualRequest = (client.innerApiCalls.listDatabases as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.listDatabases as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes listDatabases with closed client', async () => { - const client = new firestoreadminModule.FirestoreAdminClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.firestore.admin.v1.ListDatabasesRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.firestore.admin.v1.ListDatabasesRequest', ['parent']); - request.parent = defaultValue1; - const expectedError = new Error('The client has already been closed.'); - client.close().catch(err => {throw err}); - await assert.rejects(client.listDatabases(request), expectedError); - }); + it('has port', () => { + const port = firestoreadminModule.FirestoreAdminClient.port; + assert(port); + assert(typeof port === 'number'); }); - describe('createUserCreds', () => { - it('invokes createUserCreds without error', async () => { - const client = new firestoreadminModule.FirestoreAdminClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.firestore.admin.v1.CreateUserCredsRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.firestore.admin.v1.CreateUserCredsRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.firestore.admin.v1.UserCreds() - ); - client.innerApiCalls.createUserCreds = stubSimpleCall(expectedResponse); - const [response] = await client.createUserCreds(request); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.createUserCreds as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.createUserCreds as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes createUserCreds without error using callback', async () => { - const client = new firestoreadminModule.FirestoreAdminClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.firestore.admin.v1.CreateUserCredsRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.firestore.admin.v1.CreateUserCredsRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.firestore.admin.v1.UserCreds() - ); - client.innerApiCalls.createUserCreds = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.createUserCreds( - request, - (err?: Error|null, result?: protos.google.firestore.admin.v1.IUserCreds|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.createUserCreds as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.createUserCreds as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('should create a client with no option', () => { + const client = new firestoreadminModule.FirestoreAdminClient(); + assert(client); + }); - it('invokes createUserCreds with error', async () => { - const client = new firestoreadminModule.FirestoreAdminClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.firestore.admin.v1.CreateUserCredsRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.firestore.admin.v1.CreateUserCredsRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.createUserCreds = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.createUserCreds(request), expectedError); - const actualRequest = (client.innerApiCalls.createUserCreds as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.createUserCreds as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('should create a client with gRPC fallback', () => { + const client = new firestoreadminModule.FirestoreAdminClient({ + fallback: true, + }); + assert(client); + }); - it('invokes createUserCreds with closed client', async () => { - const client = new firestoreadminModule.FirestoreAdminClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.firestore.admin.v1.CreateUserCredsRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.firestore.admin.v1.CreateUserCredsRequest', ['parent']); - request.parent = defaultValue1; - const expectedError = new Error('The client has already been closed.'); - client.close().catch(err => {throw err}); - await assert.rejects(client.createUserCreds(request), expectedError); - }); + it('has initialize method and supports deferred initialization', async () => { + const client = new firestoreadminModule.FirestoreAdminClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + assert.strictEqual(client.firestoreAdminStub, undefined); + await client.initialize(); + assert(client.firestoreAdminStub); }); - describe('getUserCreds', () => { - it('invokes getUserCreds without error', async () => { - const client = new firestoreadminModule.FirestoreAdminClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.firestore.admin.v1.GetUserCredsRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.firestore.admin.v1.GetUserCredsRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.firestore.admin.v1.UserCreds() - ); - client.innerApiCalls.getUserCreds = stubSimpleCall(expectedResponse); - const [response] = await client.getUserCreds(request); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.getUserCreds as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.getUserCreds as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + it('has close method for the initialized client', done => { + const client = new firestoreadminModule.FirestoreAdminClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + client.initialize().catch(err => { + throw err; + }); + assert(client.firestoreAdminStub); + client + .close() + .then(() => { + done(); + }) + .catch(err => { + throw err; }); + }); - it('invokes getUserCreds without error using callback', async () => { - const client = new firestoreadminModule.FirestoreAdminClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.firestore.admin.v1.GetUserCredsRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.firestore.admin.v1.GetUserCredsRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.firestore.admin.v1.UserCreds() - ); - client.innerApiCalls.getUserCreds = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.getUserCreds( - request, - (err?: Error|null, result?: protos.google.firestore.admin.v1.IUserCreds|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.getUserCreds as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.getUserCreds as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + it('has close method for the non-initialized client', done => { + const client = new firestoreadminModule.FirestoreAdminClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + assert.strictEqual(client.firestoreAdminStub, undefined); + client + .close() + .then(() => { + done(); + }) + .catch(err => { + throw err; }); + }); - it('invokes getUserCreds with error', async () => { - const client = new firestoreadminModule.FirestoreAdminClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.firestore.admin.v1.GetUserCredsRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.firestore.admin.v1.GetUserCredsRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.getUserCreds = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.getUserCreds(request), expectedError); - const actualRequest = (client.innerApiCalls.getUserCreds as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.getUserCreds as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('has getProjectId method', async () => { + const fakeProjectId = 'fake-project-id'; + const client = new firestoreadminModule.FirestoreAdminClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + client.auth.getProjectId = sinon.stub().resolves(fakeProjectId); + const result = await client.getProjectId(); + assert.strictEqual(result, fakeProjectId); + assert((client.auth.getProjectId as SinonStub).calledWithExactly()); + }); - it('invokes getUserCreds with closed client', async () => { - const client = new firestoreadminModule.FirestoreAdminClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.firestore.admin.v1.GetUserCredsRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.firestore.admin.v1.GetUserCredsRequest', ['name']); - request.name = defaultValue1; - const expectedError = new Error('The client has already been closed.'); - client.close().catch(err => {throw err}); - await assert.rejects(client.getUserCreds(request), expectedError); - }); + it('has getProjectId method with callback', async () => { + const fakeProjectId = 'fake-project-id'; + const client = new firestoreadminModule.FirestoreAdminClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + client.auth.getProjectId = sinon + .stub() + .callsArgWith(0, null, fakeProjectId); + const promise = new Promise((resolve, reject) => { + client.getProjectId((err?: Error | null, projectId?: string | null) => { + if (err) { + reject(err); + } else { + resolve(projectId); + } + }); + }); + const result = await promise; + assert.strictEqual(result, fakeProjectId); + }); + }); + + describe('getIndex', () => { + it('invokes getIndex without error', async () => { + const client = new firestoreadminModule.FirestoreAdminClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.firestore.admin.v1.GetIndexRequest() + ); + const defaultValue1 = getTypeDefaultValue( + '.google.firestore.admin.v1.GetIndexRequest', + ['name'] + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.firestore.admin.v1.Index() + ); + client.innerApiCalls.getIndex = stubSimpleCall(expectedResponse); + const [response] = await client.getIndex(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.getIndex as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.getIndex as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); }); - describe('listUserCreds', () => { - it('invokes listUserCreds without error', async () => { - const client = new firestoreadminModule.FirestoreAdminClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.firestore.admin.v1.ListUserCredsRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.firestore.admin.v1.ListUserCredsRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.firestore.admin.v1.ListUserCredsResponse() - ); - client.innerApiCalls.listUserCreds = stubSimpleCall(expectedResponse); - const [response] = await client.listUserCreds(request); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.listUserCreds as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.listUserCreds as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes getIndex without error using callback', async () => { + const client = new firestoreadminModule.FirestoreAdminClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.firestore.admin.v1.GetIndexRequest() + ); + const defaultValue1 = getTypeDefaultValue( + '.google.firestore.admin.v1.GetIndexRequest', + ['name'] + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.firestore.admin.v1.Index() + ); + client.innerApiCalls.getIndex = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.getIndex( + request, + ( + err?: Error | null, + result?: protos.google.firestore.admin.v1.IIndex | null + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + } + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.getIndex as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.getIndex as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes listUserCreds without error using callback', async () => { - const client = new firestoreadminModule.FirestoreAdminClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.firestore.admin.v1.ListUserCredsRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.firestore.admin.v1.ListUserCredsRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.firestore.admin.v1.ListUserCredsResponse() - ); - client.innerApiCalls.listUserCreds = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.listUserCreds( - request, - (err?: Error|null, result?: protos.google.firestore.admin.v1.IListUserCredsResponse|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.listUserCreds as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.listUserCreds as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes getIndex with error', async () => { + const client = new firestoreadminModule.FirestoreAdminClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.firestore.admin.v1.GetIndexRequest() + ); + const defaultValue1 = getTypeDefaultValue( + '.google.firestore.admin.v1.GetIndexRequest', + ['name'] + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.getIndex = stubSimpleCall(undefined, expectedError); + await assert.rejects(client.getIndex(request), expectedError); + const actualRequest = ( + client.innerApiCalls.getIndex as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.getIndex as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes listUserCreds with error', async () => { - const client = new firestoreadminModule.FirestoreAdminClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.firestore.admin.v1.ListUserCredsRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.firestore.admin.v1.ListUserCredsRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.listUserCreds = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.listUserCreds(request), expectedError); - const actualRequest = (client.innerApiCalls.listUserCreds as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.listUserCreds as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes getIndex with closed client', async () => { + const client = new firestoreadminModule.FirestoreAdminClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.firestore.admin.v1.GetIndexRequest() + ); + const defaultValue1 = getTypeDefaultValue( + '.google.firestore.admin.v1.GetIndexRequest', + ['name'] + ); + request.name = defaultValue1; + const expectedError = new Error('The client has already been closed.'); + client.close().catch(err => { + throw err; + }); + await assert.rejects(client.getIndex(request), expectedError); + }); + }); + + describe('deleteIndex', () => { + it('invokes deleteIndex without error', async () => { + const client = new firestoreadminModule.FirestoreAdminClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.firestore.admin.v1.DeleteIndexRequest() + ); + const defaultValue1 = getTypeDefaultValue( + '.google.firestore.admin.v1.DeleteIndexRequest', + ['name'] + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.protobuf.Empty() + ); + client.innerApiCalls.deleteIndex = stubSimpleCall(expectedResponse); + const [response] = await client.deleteIndex(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.deleteIndex as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.deleteIndex as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes listUserCreds with closed client', async () => { - const client = new firestoreadminModule.FirestoreAdminClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.firestore.admin.v1.ListUserCredsRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.firestore.admin.v1.ListUserCredsRequest', ['parent']); - request.parent = defaultValue1; - const expectedError = new Error('The client has already been closed.'); - client.close().catch(err => {throw err}); - await assert.rejects(client.listUserCreds(request), expectedError); - }); + it('invokes deleteIndex without error using callback', async () => { + const client = new firestoreadminModule.FirestoreAdminClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.firestore.admin.v1.DeleteIndexRequest() + ); + const defaultValue1 = getTypeDefaultValue( + '.google.firestore.admin.v1.DeleteIndexRequest', + ['name'] + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.protobuf.Empty() + ); + client.innerApiCalls.deleteIndex = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.deleteIndex( + request, + ( + err?: Error | null, + result?: protos.google.protobuf.IEmpty | null + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + } + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.deleteIndex as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.deleteIndex as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); }); - describe('enableUserCreds', () => { - it('invokes enableUserCreds without error', async () => { - const client = new firestoreadminModule.FirestoreAdminClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.firestore.admin.v1.EnableUserCredsRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.firestore.admin.v1.EnableUserCredsRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.firestore.admin.v1.UserCreds() - ); - client.innerApiCalls.enableUserCreds = stubSimpleCall(expectedResponse); - const [response] = await client.enableUserCreds(request); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.enableUserCreds as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.enableUserCreds as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes deleteIndex with error', async () => { + const client = new firestoreadminModule.FirestoreAdminClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.firestore.admin.v1.DeleteIndexRequest() + ); + const defaultValue1 = getTypeDefaultValue( + '.google.firestore.admin.v1.DeleteIndexRequest', + ['name'] + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.deleteIndex = stubSimpleCall( + undefined, + expectedError + ); + await assert.rejects(client.deleteIndex(request), expectedError); + const actualRequest = ( + client.innerApiCalls.deleteIndex as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.deleteIndex as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes enableUserCreds without error using callback', async () => { - const client = new firestoreadminModule.FirestoreAdminClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.firestore.admin.v1.EnableUserCredsRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.firestore.admin.v1.EnableUserCredsRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.firestore.admin.v1.UserCreds() - ); - client.innerApiCalls.enableUserCreds = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.enableUserCreds( - request, - (err?: Error|null, result?: protos.google.firestore.admin.v1.IUserCreds|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.enableUserCreds as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.enableUserCreds as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes deleteIndex with closed client', async () => { + const client = new firestoreadminModule.FirestoreAdminClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.firestore.admin.v1.DeleteIndexRequest() + ); + const defaultValue1 = getTypeDefaultValue( + '.google.firestore.admin.v1.DeleteIndexRequest', + ['name'] + ); + request.name = defaultValue1; + const expectedError = new Error('The client has already been closed.'); + client.close().catch(err => { + throw err; + }); + await assert.rejects(client.deleteIndex(request), expectedError); + }); + }); + + describe('getField', () => { + it('invokes getField without error', async () => { + const client = new firestoreadminModule.FirestoreAdminClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.firestore.admin.v1.GetFieldRequest() + ); + const defaultValue1 = getTypeDefaultValue( + '.google.firestore.admin.v1.GetFieldRequest', + ['name'] + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.firestore.admin.v1.Field() + ); + client.innerApiCalls.getField = stubSimpleCall(expectedResponse); + const [response] = await client.getField(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.getField as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.getField as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes enableUserCreds with error', async () => { - const client = new firestoreadminModule.FirestoreAdminClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.firestore.admin.v1.EnableUserCredsRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.firestore.admin.v1.EnableUserCredsRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.enableUserCreds = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.enableUserCreds(request), expectedError); - const actualRequest = (client.innerApiCalls.enableUserCreds as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.enableUserCreds as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes getField without error using callback', async () => { + const client = new firestoreadminModule.FirestoreAdminClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.firestore.admin.v1.GetFieldRequest() + ); + const defaultValue1 = getTypeDefaultValue( + '.google.firestore.admin.v1.GetFieldRequest', + ['name'] + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.firestore.admin.v1.Field() + ); + client.innerApiCalls.getField = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.getField( + request, + ( + err?: Error | null, + result?: protos.google.firestore.admin.v1.IField | null + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + } + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.getField as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.getField as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes enableUserCreds with closed client', async () => { - const client = new firestoreadminModule.FirestoreAdminClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.firestore.admin.v1.EnableUserCredsRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.firestore.admin.v1.EnableUserCredsRequest', ['name']); - request.name = defaultValue1; - const expectedError = new Error('The client has already been closed.'); - client.close().catch(err => {throw err}); - await assert.rejects(client.enableUserCreds(request), expectedError); - }); + it('invokes getField with error', async () => { + const client = new firestoreadminModule.FirestoreAdminClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.firestore.admin.v1.GetFieldRequest() + ); + const defaultValue1 = getTypeDefaultValue( + '.google.firestore.admin.v1.GetFieldRequest', + ['name'] + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.getField = stubSimpleCall(undefined, expectedError); + await assert.rejects(client.getField(request), expectedError); + const actualRequest = ( + client.innerApiCalls.getField as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.getField as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); }); - describe('disableUserCreds', () => { - it('invokes disableUserCreds without error', async () => { - const client = new firestoreadminModule.FirestoreAdminClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.firestore.admin.v1.DisableUserCredsRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.firestore.admin.v1.DisableUserCredsRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.firestore.admin.v1.UserCreds() - ); - client.innerApiCalls.disableUserCreds = stubSimpleCall(expectedResponse); - const [response] = await client.disableUserCreds(request); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.disableUserCreds as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.disableUserCreds as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes getField with closed client', async () => { + const client = new firestoreadminModule.FirestoreAdminClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.firestore.admin.v1.GetFieldRequest() + ); + const defaultValue1 = getTypeDefaultValue( + '.google.firestore.admin.v1.GetFieldRequest', + ['name'] + ); + request.name = defaultValue1; + const expectedError = new Error('The client has already been closed.'); + client.close().catch(err => { + throw err; + }); + await assert.rejects(client.getField(request), expectedError); + }); + }); + + describe('getDatabase', () => { + it('invokes getDatabase without error', async () => { + const client = new firestoreadminModule.FirestoreAdminClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.firestore.admin.v1.GetDatabaseRequest() + ); + const defaultValue1 = getTypeDefaultValue( + '.google.firestore.admin.v1.GetDatabaseRequest', + ['name'] + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.firestore.admin.v1.Database() + ); + client.innerApiCalls.getDatabase = stubSimpleCall(expectedResponse); + const [response] = await client.getDatabase(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.getDatabase as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.getDatabase as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes disableUserCreds without error using callback', async () => { - const client = new firestoreadminModule.FirestoreAdminClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.firestore.admin.v1.DisableUserCredsRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.firestore.admin.v1.DisableUserCredsRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.firestore.admin.v1.UserCreds() - ); - client.innerApiCalls.disableUserCreds = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.disableUserCreds( - request, - (err?: Error|null, result?: protos.google.firestore.admin.v1.IUserCreds|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.disableUserCreds as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.disableUserCreds as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes getDatabase without error using callback', async () => { + const client = new firestoreadminModule.FirestoreAdminClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.firestore.admin.v1.GetDatabaseRequest() + ); + const defaultValue1 = getTypeDefaultValue( + '.google.firestore.admin.v1.GetDatabaseRequest', + ['name'] + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.firestore.admin.v1.Database() + ); + client.innerApiCalls.getDatabase = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.getDatabase( + request, + ( + err?: Error | null, + result?: protos.google.firestore.admin.v1.IDatabase | null + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + } + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.getDatabase as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.getDatabase as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes disableUserCreds with error', async () => { - const client = new firestoreadminModule.FirestoreAdminClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.firestore.admin.v1.DisableUserCredsRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.firestore.admin.v1.DisableUserCredsRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.disableUserCreds = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.disableUserCreds(request), expectedError); - const actualRequest = (client.innerApiCalls.disableUserCreds as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.disableUserCreds as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes getDatabase with error', async () => { + const client = new firestoreadminModule.FirestoreAdminClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.firestore.admin.v1.GetDatabaseRequest() + ); + const defaultValue1 = getTypeDefaultValue( + '.google.firestore.admin.v1.GetDatabaseRequest', + ['name'] + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.getDatabase = stubSimpleCall( + undefined, + expectedError + ); + await assert.rejects(client.getDatabase(request), expectedError); + const actualRequest = ( + client.innerApiCalls.getDatabase as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.getDatabase as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes disableUserCreds with closed client', async () => { - const client = new firestoreadminModule.FirestoreAdminClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.firestore.admin.v1.DisableUserCredsRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.firestore.admin.v1.DisableUserCredsRequest', ['name']); - request.name = defaultValue1; - const expectedError = new Error('The client has already been closed.'); - client.close().catch(err => {throw err}); - await assert.rejects(client.disableUserCreds(request), expectedError); - }); + it('invokes getDatabase with closed client', async () => { + const client = new firestoreadminModule.FirestoreAdminClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.firestore.admin.v1.GetDatabaseRequest() + ); + const defaultValue1 = getTypeDefaultValue( + '.google.firestore.admin.v1.GetDatabaseRequest', + ['name'] + ); + request.name = defaultValue1; + const expectedError = new Error('The client has already been closed.'); + client.close().catch(err => { + throw err; + }); + await assert.rejects(client.getDatabase(request), expectedError); + }); + }); + + describe('listDatabases', () => { + it('invokes listDatabases without error', async () => { + const client = new firestoreadminModule.FirestoreAdminClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.firestore.admin.v1.ListDatabasesRequest() + ); + const defaultValue1 = getTypeDefaultValue( + '.google.firestore.admin.v1.ListDatabasesRequest', + ['parent'] + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.firestore.admin.v1.ListDatabasesResponse() + ); + client.innerApiCalls.listDatabases = stubSimpleCall(expectedResponse); + const [response] = await client.listDatabases(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.listDatabases as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.listDatabases as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); }); - describe('resetUserPassword', () => { - it('invokes resetUserPassword without error', async () => { - const client = new firestoreadminModule.FirestoreAdminClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.firestore.admin.v1.ResetUserPasswordRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.firestore.admin.v1.ResetUserPasswordRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.firestore.admin.v1.UserCreds() - ); - client.innerApiCalls.resetUserPassword = stubSimpleCall(expectedResponse); - const [response] = await client.resetUserPassword(request); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.resetUserPassword as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.resetUserPassword as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes listDatabases without error using callback', async () => { + const client = new firestoreadminModule.FirestoreAdminClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.firestore.admin.v1.ListDatabasesRequest() + ); + const defaultValue1 = getTypeDefaultValue( + '.google.firestore.admin.v1.ListDatabasesRequest', + ['parent'] + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.firestore.admin.v1.ListDatabasesResponse() + ); + client.innerApiCalls.listDatabases = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.listDatabases( + request, + ( + err?: Error | null, + result?: protos.google.firestore.admin.v1.IListDatabasesResponse | null + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + } + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.listDatabases as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.listDatabases as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes resetUserPassword without error using callback', async () => { - const client = new firestoreadminModule.FirestoreAdminClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.firestore.admin.v1.ResetUserPasswordRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.firestore.admin.v1.ResetUserPasswordRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.firestore.admin.v1.UserCreds() - ); - client.innerApiCalls.resetUserPassword = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.resetUserPassword( - request, - (err?: Error|null, result?: protos.google.firestore.admin.v1.IUserCreds|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.resetUserPassword as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.resetUserPassword as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes listDatabases with error', async () => { + const client = new firestoreadminModule.FirestoreAdminClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.firestore.admin.v1.ListDatabasesRequest() + ); + const defaultValue1 = getTypeDefaultValue( + '.google.firestore.admin.v1.ListDatabasesRequest', + ['parent'] + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.listDatabases = stubSimpleCall( + undefined, + expectedError + ); + await assert.rejects(client.listDatabases(request), expectedError); + const actualRequest = ( + client.innerApiCalls.listDatabases as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.listDatabases as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes resetUserPassword with error', async () => { - const client = new firestoreadminModule.FirestoreAdminClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.firestore.admin.v1.ResetUserPasswordRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.firestore.admin.v1.ResetUserPasswordRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.resetUserPassword = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.resetUserPassword(request), expectedError); - const actualRequest = (client.innerApiCalls.resetUserPassword as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.resetUserPassword as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes listDatabases with closed client', async () => { + const client = new firestoreadminModule.FirestoreAdminClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.firestore.admin.v1.ListDatabasesRequest() + ); + const defaultValue1 = getTypeDefaultValue( + '.google.firestore.admin.v1.ListDatabasesRequest', + ['parent'] + ); + request.parent = defaultValue1; + const expectedError = new Error('The client has already been closed.'); + client.close().catch(err => { + throw err; + }); + await assert.rejects(client.listDatabases(request), expectedError); + }); + }); + + describe('createUserCreds', () => { + it('invokes createUserCreds without error', async () => { + const client = new firestoreadminModule.FirestoreAdminClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.firestore.admin.v1.CreateUserCredsRequest() + ); + const defaultValue1 = getTypeDefaultValue( + '.google.firestore.admin.v1.CreateUserCredsRequest', + ['parent'] + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.firestore.admin.v1.UserCreds() + ); + client.innerApiCalls.createUserCreds = stubSimpleCall(expectedResponse); + const [response] = await client.createUserCreds(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.createUserCreds as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.createUserCreds as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes resetUserPassword with closed client', async () => { - const client = new firestoreadminModule.FirestoreAdminClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.firestore.admin.v1.ResetUserPasswordRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.firestore.admin.v1.ResetUserPasswordRequest', ['name']); - request.name = defaultValue1; - const expectedError = new Error('The client has already been closed.'); - client.close().catch(err => {throw err}); - await assert.rejects(client.resetUserPassword(request), expectedError); - }); + it('invokes createUserCreds without error using callback', async () => { + const client = new firestoreadminModule.FirestoreAdminClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.firestore.admin.v1.CreateUserCredsRequest() + ); + const defaultValue1 = getTypeDefaultValue( + '.google.firestore.admin.v1.CreateUserCredsRequest', + ['parent'] + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.firestore.admin.v1.UserCreds() + ); + client.innerApiCalls.createUserCreds = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.createUserCreds( + request, + ( + err?: Error | null, + result?: protos.google.firestore.admin.v1.IUserCreds | null + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + } + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.createUserCreds as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.createUserCreds as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); }); - describe('deleteUserCreds', () => { - it('invokes deleteUserCreds without error', async () => { - const client = new firestoreadminModule.FirestoreAdminClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.firestore.admin.v1.DeleteUserCredsRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.firestore.admin.v1.DeleteUserCredsRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.protobuf.Empty() - ); - client.innerApiCalls.deleteUserCreds = stubSimpleCall(expectedResponse); - const [response] = await client.deleteUserCreds(request); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.deleteUserCreds as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.deleteUserCreds as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes createUserCreds with error', async () => { + const client = new firestoreadminModule.FirestoreAdminClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.firestore.admin.v1.CreateUserCredsRequest() + ); + const defaultValue1 = getTypeDefaultValue( + '.google.firestore.admin.v1.CreateUserCredsRequest', + ['parent'] + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.createUserCreds = stubSimpleCall( + undefined, + expectedError + ); + await assert.rejects(client.createUserCreds(request), expectedError); + const actualRequest = ( + client.innerApiCalls.createUserCreds as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.createUserCreds as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes deleteUserCreds without error using callback', async () => { - const client = new firestoreadminModule.FirestoreAdminClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.firestore.admin.v1.DeleteUserCredsRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.firestore.admin.v1.DeleteUserCredsRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.protobuf.Empty() - ); - client.innerApiCalls.deleteUserCreds = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.deleteUserCreds( - request, - (err?: Error|null, result?: protos.google.protobuf.IEmpty|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.deleteUserCreds as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.deleteUserCreds as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes createUserCreds with closed client', async () => { + const client = new firestoreadminModule.FirestoreAdminClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.firestore.admin.v1.CreateUserCredsRequest() + ); + const defaultValue1 = getTypeDefaultValue( + '.google.firestore.admin.v1.CreateUserCredsRequest', + ['parent'] + ); + request.parent = defaultValue1; + const expectedError = new Error('The client has already been closed.'); + client.close().catch(err => { + throw err; + }); + await assert.rejects(client.createUserCreds(request), expectedError); + }); + }); + + describe('getUserCreds', () => { + it('invokes getUserCreds without error', async () => { + const client = new firestoreadminModule.FirestoreAdminClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.firestore.admin.v1.GetUserCredsRequest() + ); + const defaultValue1 = getTypeDefaultValue( + '.google.firestore.admin.v1.GetUserCredsRequest', + ['name'] + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.firestore.admin.v1.UserCreds() + ); + client.innerApiCalls.getUserCreds = stubSimpleCall(expectedResponse); + const [response] = await client.getUserCreds(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.getUserCreds as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.getUserCreds as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes deleteUserCreds with error', async () => { - const client = new firestoreadminModule.FirestoreAdminClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.firestore.admin.v1.DeleteUserCredsRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.firestore.admin.v1.DeleteUserCredsRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.deleteUserCreds = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.deleteUserCreds(request), expectedError); - const actualRequest = (client.innerApiCalls.deleteUserCreds as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.deleteUserCreds as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes getUserCreds without error using callback', async () => { + const client = new firestoreadminModule.FirestoreAdminClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.firestore.admin.v1.GetUserCredsRequest() + ); + const defaultValue1 = getTypeDefaultValue( + '.google.firestore.admin.v1.GetUserCredsRequest', + ['name'] + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.firestore.admin.v1.UserCreds() + ); + client.innerApiCalls.getUserCreds = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.getUserCreds( + request, + ( + err?: Error | null, + result?: protos.google.firestore.admin.v1.IUserCreds | null + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + } + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.getUserCreds as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.getUserCreds as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes deleteUserCreds with closed client', async () => { - const client = new firestoreadminModule.FirestoreAdminClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.firestore.admin.v1.DeleteUserCredsRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.firestore.admin.v1.DeleteUserCredsRequest', ['name']); - request.name = defaultValue1; - const expectedError = new Error('The client has already been closed.'); - client.close().catch(err => {throw err}); - await assert.rejects(client.deleteUserCreds(request), expectedError); - }); + it('invokes getUserCreds with error', async () => { + const client = new firestoreadminModule.FirestoreAdminClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.firestore.admin.v1.GetUserCredsRequest() + ); + const defaultValue1 = getTypeDefaultValue( + '.google.firestore.admin.v1.GetUserCredsRequest', + ['name'] + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.getUserCreds = stubSimpleCall( + undefined, + expectedError + ); + await assert.rejects(client.getUserCreds(request), expectedError); + const actualRequest = ( + client.innerApiCalls.getUserCreds as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.getUserCreds as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); }); - describe('getBackup', () => { - it('invokes getBackup without error', async () => { - const client = new firestoreadminModule.FirestoreAdminClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.firestore.admin.v1.GetBackupRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.firestore.admin.v1.GetBackupRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.firestore.admin.v1.Backup() - ); - client.innerApiCalls.getBackup = stubSimpleCall(expectedResponse); - const [response] = await client.getBackup(request); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.getBackup as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.getBackup as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes getUserCreds with closed client', async () => { + const client = new firestoreadminModule.FirestoreAdminClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.firestore.admin.v1.GetUserCredsRequest() + ); + const defaultValue1 = getTypeDefaultValue( + '.google.firestore.admin.v1.GetUserCredsRequest', + ['name'] + ); + request.name = defaultValue1; + const expectedError = new Error('The client has already been closed.'); + client.close().catch(err => { + throw err; + }); + await assert.rejects(client.getUserCreds(request), expectedError); + }); + }); + + describe('listUserCreds', () => { + it('invokes listUserCreds without error', async () => { + const client = new firestoreadminModule.FirestoreAdminClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.firestore.admin.v1.ListUserCredsRequest() + ); + const defaultValue1 = getTypeDefaultValue( + '.google.firestore.admin.v1.ListUserCredsRequest', + ['parent'] + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.firestore.admin.v1.ListUserCredsResponse() + ); + client.innerApiCalls.listUserCreds = stubSimpleCall(expectedResponse); + const [response] = await client.listUserCreds(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.listUserCreds as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.listUserCreds as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes getBackup without error using callback', async () => { - const client = new firestoreadminModule.FirestoreAdminClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.firestore.admin.v1.GetBackupRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.firestore.admin.v1.GetBackupRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.firestore.admin.v1.Backup() - ); - client.innerApiCalls.getBackup = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.getBackup( - request, - (err?: Error|null, result?: protos.google.firestore.admin.v1.IBackup|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.getBackup as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.getBackup as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes listUserCreds without error using callback', async () => { + const client = new firestoreadminModule.FirestoreAdminClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.firestore.admin.v1.ListUserCredsRequest() + ); + const defaultValue1 = getTypeDefaultValue( + '.google.firestore.admin.v1.ListUserCredsRequest', + ['parent'] + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.firestore.admin.v1.ListUserCredsResponse() + ); + client.innerApiCalls.listUserCreds = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.listUserCreds( + request, + ( + err?: Error | null, + result?: protos.google.firestore.admin.v1.IListUserCredsResponse | null + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + } + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.listUserCreds as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.listUserCreds as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes getBackup with error', async () => { - const client = new firestoreadminModule.FirestoreAdminClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.firestore.admin.v1.GetBackupRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.firestore.admin.v1.GetBackupRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.getBackup = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.getBackup(request), expectedError); - const actualRequest = (client.innerApiCalls.getBackup as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.getBackup as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes listUserCreds with error', async () => { + const client = new firestoreadminModule.FirestoreAdminClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.firestore.admin.v1.ListUserCredsRequest() + ); + const defaultValue1 = getTypeDefaultValue( + '.google.firestore.admin.v1.ListUserCredsRequest', + ['parent'] + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.listUserCreds = stubSimpleCall( + undefined, + expectedError + ); + await assert.rejects(client.listUserCreds(request), expectedError); + const actualRequest = ( + client.innerApiCalls.listUserCreds as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.listUserCreds as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes getBackup with closed client', async () => { - const client = new firestoreadminModule.FirestoreAdminClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.firestore.admin.v1.GetBackupRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.firestore.admin.v1.GetBackupRequest', ['name']); - request.name = defaultValue1; - const expectedError = new Error('The client has already been closed.'); - client.close().catch(err => {throw err}); - await assert.rejects(client.getBackup(request), expectedError); - }); + it('invokes listUserCreds with closed client', async () => { + const client = new firestoreadminModule.FirestoreAdminClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.firestore.admin.v1.ListUserCredsRequest() + ); + const defaultValue1 = getTypeDefaultValue( + '.google.firestore.admin.v1.ListUserCredsRequest', + ['parent'] + ); + request.parent = defaultValue1; + const expectedError = new Error('The client has already been closed.'); + client.close().catch(err => { + throw err; + }); + await assert.rejects(client.listUserCreds(request), expectedError); + }); + }); + + describe('enableUserCreds', () => { + it('invokes enableUserCreds without error', async () => { + const client = new firestoreadminModule.FirestoreAdminClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.firestore.admin.v1.EnableUserCredsRequest() + ); + const defaultValue1 = getTypeDefaultValue( + '.google.firestore.admin.v1.EnableUserCredsRequest', + ['name'] + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.firestore.admin.v1.UserCreds() + ); + client.innerApiCalls.enableUserCreds = stubSimpleCall(expectedResponse); + const [response] = await client.enableUserCreds(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.enableUserCreds as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.enableUserCreds as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); }); - describe('listBackups', () => { - it('invokes listBackups without error', async () => { - const client = new firestoreadminModule.FirestoreAdminClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.firestore.admin.v1.ListBackupsRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.firestore.admin.v1.ListBackupsRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.firestore.admin.v1.ListBackupsResponse() - ); - client.innerApiCalls.listBackups = stubSimpleCall(expectedResponse); - const [response] = await client.listBackups(request); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.listBackups as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.listBackups as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes enableUserCreds without error using callback', async () => { + const client = new firestoreadminModule.FirestoreAdminClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.firestore.admin.v1.EnableUserCredsRequest() + ); + const defaultValue1 = getTypeDefaultValue( + '.google.firestore.admin.v1.EnableUserCredsRequest', + ['name'] + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.firestore.admin.v1.UserCreds() + ); + client.innerApiCalls.enableUserCreds = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.enableUserCreds( + request, + ( + err?: Error | null, + result?: protos.google.firestore.admin.v1.IUserCreds | null + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + } + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.enableUserCreds as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.enableUserCreds as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes listBackups without error using callback', async () => { - const client = new firestoreadminModule.FirestoreAdminClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.firestore.admin.v1.ListBackupsRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.firestore.admin.v1.ListBackupsRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.firestore.admin.v1.ListBackupsResponse() - ); - client.innerApiCalls.listBackups = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.listBackups( - request, - (err?: Error|null, result?: protos.google.firestore.admin.v1.IListBackupsResponse|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.listBackups as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.listBackups as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes enableUserCreds with error', async () => { + const client = new firestoreadminModule.FirestoreAdminClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.firestore.admin.v1.EnableUserCredsRequest() + ); + const defaultValue1 = getTypeDefaultValue( + '.google.firestore.admin.v1.EnableUserCredsRequest', + ['name'] + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.enableUserCreds = stubSimpleCall( + undefined, + expectedError + ); + await assert.rejects(client.enableUserCreds(request), expectedError); + const actualRequest = ( + client.innerApiCalls.enableUserCreds as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.enableUserCreds as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes listBackups with error', async () => { - const client = new firestoreadminModule.FirestoreAdminClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.firestore.admin.v1.ListBackupsRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.firestore.admin.v1.ListBackupsRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.listBackups = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.listBackups(request), expectedError); - const actualRequest = (client.innerApiCalls.listBackups as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.listBackups as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes enableUserCreds with closed client', async () => { + const client = new firestoreadminModule.FirestoreAdminClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.firestore.admin.v1.EnableUserCredsRequest() + ); + const defaultValue1 = getTypeDefaultValue( + '.google.firestore.admin.v1.EnableUserCredsRequest', + ['name'] + ); + request.name = defaultValue1; + const expectedError = new Error('The client has already been closed.'); + client.close().catch(err => { + throw err; + }); + await assert.rejects(client.enableUserCreds(request), expectedError); + }); + }); + + describe('disableUserCreds', () => { + it('invokes disableUserCreds without error', async () => { + const client = new firestoreadminModule.FirestoreAdminClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.firestore.admin.v1.DisableUserCredsRequest() + ); + const defaultValue1 = getTypeDefaultValue( + '.google.firestore.admin.v1.DisableUserCredsRequest', + ['name'] + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.firestore.admin.v1.UserCreds() + ); + client.innerApiCalls.disableUserCreds = stubSimpleCall(expectedResponse); + const [response] = await client.disableUserCreds(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.disableUserCreds as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.disableUserCreds as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes listBackups with closed client', async () => { - const client = new firestoreadminModule.FirestoreAdminClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.firestore.admin.v1.ListBackupsRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.firestore.admin.v1.ListBackupsRequest', ['parent']); - request.parent = defaultValue1; - const expectedError = new Error('The client has already been closed.'); - client.close().catch(err => {throw err}); - await assert.rejects(client.listBackups(request), expectedError); - }); + it('invokes disableUserCreds without error using callback', async () => { + const client = new firestoreadminModule.FirestoreAdminClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.firestore.admin.v1.DisableUserCredsRequest() + ); + const defaultValue1 = getTypeDefaultValue( + '.google.firestore.admin.v1.DisableUserCredsRequest', + ['name'] + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.firestore.admin.v1.UserCreds() + ); + client.innerApiCalls.disableUserCreds = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.disableUserCreds( + request, + ( + err?: Error | null, + result?: protos.google.firestore.admin.v1.IUserCreds | null + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + } + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.disableUserCreds as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.disableUserCreds as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); }); - describe('deleteBackup', () => { - it('invokes deleteBackup without error', async () => { - const client = new firestoreadminModule.FirestoreAdminClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.firestore.admin.v1.DeleteBackupRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.firestore.admin.v1.DeleteBackupRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.protobuf.Empty() - ); - client.innerApiCalls.deleteBackup = stubSimpleCall(expectedResponse); - const [response] = await client.deleteBackup(request); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.deleteBackup as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.deleteBackup as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes disableUserCreds with error', async () => { + const client = new firestoreadminModule.FirestoreAdminClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.firestore.admin.v1.DisableUserCredsRequest() + ); + const defaultValue1 = getTypeDefaultValue( + '.google.firestore.admin.v1.DisableUserCredsRequest', + ['name'] + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.disableUserCreds = stubSimpleCall( + undefined, + expectedError + ); + await assert.rejects(client.disableUserCreds(request), expectedError); + const actualRequest = ( + client.innerApiCalls.disableUserCreds as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.disableUserCreds as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes deleteBackup without error using callback', async () => { - const client = new firestoreadminModule.FirestoreAdminClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.firestore.admin.v1.DeleteBackupRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.firestore.admin.v1.DeleteBackupRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.protobuf.Empty() - ); - client.innerApiCalls.deleteBackup = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.deleteBackup( - request, - (err?: Error|null, result?: protos.google.protobuf.IEmpty|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.deleteBackup as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.deleteBackup as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes disableUserCreds with closed client', async () => { + const client = new firestoreadminModule.FirestoreAdminClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.firestore.admin.v1.DisableUserCredsRequest() + ); + const defaultValue1 = getTypeDefaultValue( + '.google.firestore.admin.v1.DisableUserCredsRequest', + ['name'] + ); + request.name = defaultValue1; + const expectedError = new Error('The client has already been closed.'); + client.close().catch(err => { + throw err; + }); + await assert.rejects(client.disableUserCreds(request), expectedError); + }); + }); + + describe('resetUserPassword', () => { + it('invokes resetUserPassword without error', async () => { + const client = new firestoreadminModule.FirestoreAdminClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.firestore.admin.v1.ResetUserPasswordRequest() + ); + const defaultValue1 = getTypeDefaultValue( + '.google.firestore.admin.v1.ResetUserPasswordRequest', + ['name'] + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.firestore.admin.v1.UserCreds() + ); + client.innerApiCalls.resetUserPassword = stubSimpleCall(expectedResponse); + const [response] = await client.resetUserPassword(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.resetUserPassword as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.resetUserPassword as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes deleteBackup with error', async () => { - const client = new firestoreadminModule.FirestoreAdminClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.firestore.admin.v1.DeleteBackupRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.firestore.admin.v1.DeleteBackupRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.deleteBackup = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.deleteBackup(request), expectedError); - const actualRequest = (client.innerApiCalls.deleteBackup as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.deleteBackup as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes resetUserPassword without error using callback', async () => { + const client = new firestoreadminModule.FirestoreAdminClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.firestore.admin.v1.ResetUserPasswordRequest() + ); + const defaultValue1 = getTypeDefaultValue( + '.google.firestore.admin.v1.ResetUserPasswordRequest', + ['name'] + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.firestore.admin.v1.UserCreds() + ); + client.innerApiCalls.resetUserPassword = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.resetUserPassword( + request, + ( + err?: Error | null, + result?: protos.google.firestore.admin.v1.IUserCreds | null + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + } + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.resetUserPassword as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.resetUserPassword as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes deleteBackup with closed client', async () => { - const client = new firestoreadminModule.FirestoreAdminClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.firestore.admin.v1.DeleteBackupRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.firestore.admin.v1.DeleteBackupRequest', ['name']); - request.name = defaultValue1; - const expectedError = new Error('The client has already been closed.'); - client.close().catch(err => {throw err}); - await assert.rejects(client.deleteBackup(request), expectedError); - }); + it('invokes resetUserPassword with error', async () => { + const client = new firestoreadminModule.FirestoreAdminClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.firestore.admin.v1.ResetUserPasswordRequest() + ); + const defaultValue1 = getTypeDefaultValue( + '.google.firestore.admin.v1.ResetUserPasswordRequest', + ['name'] + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.resetUserPassword = stubSimpleCall( + undefined, + expectedError + ); + await assert.rejects(client.resetUserPassword(request), expectedError); + const actualRequest = ( + client.innerApiCalls.resetUserPassword as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.resetUserPassword as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); }); - describe('createBackupSchedule', () => { - it('invokes createBackupSchedule without error', async () => { - const client = new firestoreadminModule.FirestoreAdminClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.firestore.admin.v1.CreateBackupScheduleRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.firestore.admin.v1.CreateBackupScheduleRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.firestore.admin.v1.BackupSchedule() - ); - client.innerApiCalls.createBackupSchedule = stubSimpleCall(expectedResponse); - const [response] = await client.createBackupSchedule(request); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.createBackupSchedule as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.createBackupSchedule as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes resetUserPassword with closed client', async () => { + const client = new firestoreadminModule.FirestoreAdminClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.firestore.admin.v1.ResetUserPasswordRequest() + ); + const defaultValue1 = getTypeDefaultValue( + '.google.firestore.admin.v1.ResetUserPasswordRequest', + ['name'] + ); + request.name = defaultValue1; + const expectedError = new Error('The client has already been closed.'); + client.close().catch(err => { + throw err; + }); + await assert.rejects(client.resetUserPassword(request), expectedError); + }); + }); + + describe('deleteUserCreds', () => { + it('invokes deleteUserCreds without error', async () => { + const client = new firestoreadminModule.FirestoreAdminClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.firestore.admin.v1.DeleteUserCredsRequest() + ); + const defaultValue1 = getTypeDefaultValue( + '.google.firestore.admin.v1.DeleteUserCredsRequest', + ['name'] + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.protobuf.Empty() + ); + client.innerApiCalls.deleteUserCreds = stubSimpleCall(expectedResponse); + const [response] = await client.deleteUserCreds(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.deleteUserCreds as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.deleteUserCreds as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes createBackupSchedule without error using callback', async () => { - const client = new firestoreadminModule.FirestoreAdminClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.firestore.admin.v1.CreateBackupScheduleRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.firestore.admin.v1.CreateBackupScheduleRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.firestore.admin.v1.BackupSchedule() - ); - client.innerApiCalls.createBackupSchedule = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.createBackupSchedule( - request, - (err?: Error|null, result?: protos.google.firestore.admin.v1.IBackupSchedule|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.createBackupSchedule as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.createBackupSchedule as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes deleteUserCreds without error using callback', async () => { + const client = new firestoreadminModule.FirestoreAdminClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.firestore.admin.v1.DeleteUserCredsRequest() + ); + const defaultValue1 = getTypeDefaultValue( + '.google.firestore.admin.v1.DeleteUserCredsRequest', + ['name'] + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.protobuf.Empty() + ); + client.innerApiCalls.deleteUserCreds = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.deleteUserCreds( + request, + ( + err?: Error | null, + result?: protos.google.protobuf.IEmpty | null + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + } + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.deleteUserCreds as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.deleteUserCreds as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes createBackupSchedule with error', async () => { - const client = new firestoreadminModule.FirestoreAdminClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.firestore.admin.v1.CreateBackupScheduleRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.firestore.admin.v1.CreateBackupScheduleRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.createBackupSchedule = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.createBackupSchedule(request), expectedError); - const actualRequest = (client.innerApiCalls.createBackupSchedule as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.createBackupSchedule as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes deleteUserCreds with error', async () => { + const client = new firestoreadminModule.FirestoreAdminClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.firestore.admin.v1.DeleteUserCredsRequest() + ); + const defaultValue1 = getTypeDefaultValue( + '.google.firestore.admin.v1.DeleteUserCredsRequest', + ['name'] + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.deleteUserCreds = stubSimpleCall( + undefined, + expectedError + ); + await assert.rejects(client.deleteUserCreds(request), expectedError); + const actualRequest = ( + client.innerApiCalls.deleteUserCreds as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.deleteUserCreds as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes createBackupSchedule with closed client', async () => { - const client = new firestoreadminModule.FirestoreAdminClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.firestore.admin.v1.CreateBackupScheduleRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.firestore.admin.v1.CreateBackupScheduleRequest', ['parent']); - request.parent = defaultValue1; - const expectedError = new Error('The client has already been closed.'); - client.close().catch(err => {throw err}); - await assert.rejects(client.createBackupSchedule(request), expectedError); - }); + it('invokes deleteUserCreds with closed client', async () => { + const client = new firestoreadminModule.FirestoreAdminClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.firestore.admin.v1.DeleteUserCredsRequest() + ); + const defaultValue1 = getTypeDefaultValue( + '.google.firestore.admin.v1.DeleteUserCredsRequest', + ['name'] + ); + request.name = defaultValue1; + const expectedError = new Error('The client has already been closed.'); + client.close().catch(err => { + throw err; + }); + await assert.rejects(client.deleteUserCreds(request), expectedError); + }); + }); + + describe('getBackup', () => { + it('invokes getBackup without error', async () => { + const client = new firestoreadminModule.FirestoreAdminClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.firestore.admin.v1.GetBackupRequest() + ); + const defaultValue1 = getTypeDefaultValue( + '.google.firestore.admin.v1.GetBackupRequest', + ['name'] + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.firestore.admin.v1.Backup() + ); + client.innerApiCalls.getBackup = stubSimpleCall(expectedResponse); + const [response] = await client.getBackup(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.getBackup as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.getBackup as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); }); - describe('getBackupSchedule', () => { - it('invokes getBackupSchedule without error', async () => { - const client = new firestoreadminModule.FirestoreAdminClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.firestore.admin.v1.GetBackupScheduleRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.firestore.admin.v1.GetBackupScheduleRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.firestore.admin.v1.BackupSchedule() - ); - client.innerApiCalls.getBackupSchedule = stubSimpleCall(expectedResponse); - const [response] = await client.getBackupSchedule(request); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.getBackupSchedule as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.getBackupSchedule as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes getBackup without error using callback', async () => { + const client = new firestoreadminModule.FirestoreAdminClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.firestore.admin.v1.GetBackupRequest() + ); + const defaultValue1 = getTypeDefaultValue( + '.google.firestore.admin.v1.GetBackupRequest', + ['name'] + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.firestore.admin.v1.Backup() + ); + client.innerApiCalls.getBackup = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.getBackup( + request, + ( + err?: Error | null, + result?: protos.google.firestore.admin.v1.IBackup | null + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + } + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.getBackup as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.getBackup as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes getBackupSchedule without error using callback', async () => { - const client = new firestoreadminModule.FirestoreAdminClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.firestore.admin.v1.GetBackupScheduleRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.firestore.admin.v1.GetBackupScheduleRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.firestore.admin.v1.BackupSchedule() - ); - client.innerApiCalls.getBackupSchedule = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.getBackupSchedule( - request, - (err?: Error|null, result?: protos.google.firestore.admin.v1.IBackupSchedule|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.getBackupSchedule as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.getBackupSchedule as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes getBackup with error', async () => { + const client = new firestoreadminModule.FirestoreAdminClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.firestore.admin.v1.GetBackupRequest() + ); + const defaultValue1 = getTypeDefaultValue( + '.google.firestore.admin.v1.GetBackupRequest', + ['name'] + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.getBackup = stubSimpleCall(undefined, expectedError); + await assert.rejects(client.getBackup(request), expectedError); + const actualRequest = ( + client.innerApiCalls.getBackup as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.getBackup as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes getBackupSchedule with error', async () => { - const client = new firestoreadminModule.FirestoreAdminClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.firestore.admin.v1.GetBackupScheduleRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.firestore.admin.v1.GetBackupScheduleRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.getBackupSchedule = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.getBackupSchedule(request), expectedError); - const actualRequest = (client.innerApiCalls.getBackupSchedule as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.getBackupSchedule as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes getBackup with closed client', async () => { + const client = new firestoreadminModule.FirestoreAdminClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.firestore.admin.v1.GetBackupRequest() + ); + const defaultValue1 = getTypeDefaultValue( + '.google.firestore.admin.v1.GetBackupRequest', + ['name'] + ); + request.name = defaultValue1; + const expectedError = new Error('The client has already been closed.'); + client.close().catch(err => { + throw err; + }); + await assert.rejects(client.getBackup(request), expectedError); + }); + }); + + describe('listBackups', () => { + it('invokes listBackups without error', async () => { + const client = new firestoreadminModule.FirestoreAdminClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.firestore.admin.v1.ListBackupsRequest() + ); + const defaultValue1 = getTypeDefaultValue( + '.google.firestore.admin.v1.ListBackupsRequest', + ['parent'] + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.firestore.admin.v1.ListBackupsResponse() + ); + client.innerApiCalls.listBackups = stubSimpleCall(expectedResponse); + const [response] = await client.listBackups(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.listBackups as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.listBackups as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes getBackupSchedule with closed client', async () => { - const client = new firestoreadminModule.FirestoreAdminClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.firestore.admin.v1.GetBackupScheduleRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.firestore.admin.v1.GetBackupScheduleRequest', ['name']); - request.name = defaultValue1; - const expectedError = new Error('The client has already been closed.'); - client.close().catch(err => {throw err}); - await assert.rejects(client.getBackupSchedule(request), expectedError); - }); + it('invokes listBackups without error using callback', async () => { + const client = new firestoreadminModule.FirestoreAdminClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.firestore.admin.v1.ListBackupsRequest() + ); + const defaultValue1 = getTypeDefaultValue( + '.google.firestore.admin.v1.ListBackupsRequest', + ['parent'] + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.firestore.admin.v1.ListBackupsResponse() + ); + client.innerApiCalls.listBackups = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.listBackups( + request, + ( + err?: Error | null, + result?: protos.google.firestore.admin.v1.IListBackupsResponse | null + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + } + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.listBackups as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.listBackups as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); }); - describe('listBackupSchedules', () => { - it('invokes listBackupSchedules without error', async () => { - const client = new firestoreadminModule.FirestoreAdminClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.firestore.admin.v1.ListBackupSchedulesRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.firestore.admin.v1.ListBackupSchedulesRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.firestore.admin.v1.ListBackupSchedulesResponse() - ); - client.innerApiCalls.listBackupSchedules = stubSimpleCall(expectedResponse); - const [response] = await client.listBackupSchedules(request); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.listBackupSchedules as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.listBackupSchedules as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes listBackups with error', async () => { + const client = new firestoreadminModule.FirestoreAdminClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.firestore.admin.v1.ListBackupsRequest() + ); + const defaultValue1 = getTypeDefaultValue( + '.google.firestore.admin.v1.ListBackupsRequest', + ['parent'] + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.listBackups = stubSimpleCall( + undefined, + expectedError + ); + await assert.rejects(client.listBackups(request), expectedError); + const actualRequest = ( + client.innerApiCalls.listBackups as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.listBackups as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes listBackupSchedules without error using callback', async () => { - const client = new firestoreadminModule.FirestoreAdminClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.firestore.admin.v1.ListBackupSchedulesRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.firestore.admin.v1.ListBackupSchedulesRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.firestore.admin.v1.ListBackupSchedulesResponse() - ); - client.innerApiCalls.listBackupSchedules = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.listBackupSchedules( - request, - (err?: Error|null, result?: protos.google.firestore.admin.v1.IListBackupSchedulesResponse|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.listBackupSchedules as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.listBackupSchedules as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes listBackups with closed client', async () => { + const client = new firestoreadminModule.FirestoreAdminClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.firestore.admin.v1.ListBackupsRequest() + ); + const defaultValue1 = getTypeDefaultValue( + '.google.firestore.admin.v1.ListBackupsRequest', + ['parent'] + ); + request.parent = defaultValue1; + const expectedError = new Error('The client has already been closed.'); + client.close().catch(err => { + throw err; + }); + await assert.rejects(client.listBackups(request), expectedError); + }); + }); + + describe('deleteBackup', () => { + it('invokes deleteBackup without error', async () => { + const client = new firestoreadminModule.FirestoreAdminClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.firestore.admin.v1.DeleteBackupRequest() + ); + const defaultValue1 = getTypeDefaultValue( + '.google.firestore.admin.v1.DeleteBackupRequest', + ['name'] + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.protobuf.Empty() + ); + client.innerApiCalls.deleteBackup = stubSimpleCall(expectedResponse); + const [response] = await client.deleteBackup(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.deleteBackup as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.deleteBackup as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes listBackupSchedules with error', async () => { - const client = new firestoreadminModule.FirestoreAdminClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.firestore.admin.v1.ListBackupSchedulesRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.firestore.admin.v1.ListBackupSchedulesRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.listBackupSchedules = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.listBackupSchedules(request), expectedError); - const actualRequest = (client.innerApiCalls.listBackupSchedules as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.listBackupSchedules as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes deleteBackup without error using callback', async () => { + const client = new firestoreadminModule.FirestoreAdminClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.firestore.admin.v1.DeleteBackupRequest() + ); + const defaultValue1 = getTypeDefaultValue( + '.google.firestore.admin.v1.DeleteBackupRequest', + ['name'] + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.protobuf.Empty() + ); + client.innerApiCalls.deleteBackup = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.deleteBackup( + request, + ( + err?: Error | null, + result?: protos.google.protobuf.IEmpty | null + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + } + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.deleteBackup as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.deleteBackup as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes listBackupSchedules with closed client', async () => { - const client = new firestoreadminModule.FirestoreAdminClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.firestore.admin.v1.ListBackupSchedulesRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.firestore.admin.v1.ListBackupSchedulesRequest', ['parent']); - request.parent = defaultValue1; - const expectedError = new Error('The client has already been closed.'); - client.close().catch(err => {throw err}); - await assert.rejects(client.listBackupSchedules(request), expectedError); - }); + it('invokes deleteBackup with error', async () => { + const client = new firestoreadminModule.FirestoreAdminClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.firestore.admin.v1.DeleteBackupRequest() + ); + const defaultValue1 = getTypeDefaultValue( + '.google.firestore.admin.v1.DeleteBackupRequest', + ['name'] + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.deleteBackup = stubSimpleCall( + undefined, + expectedError + ); + await assert.rejects(client.deleteBackup(request), expectedError); + const actualRequest = ( + client.innerApiCalls.deleteBackup as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.deleteBackup as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); }); - describe('updateBackupSchedule', () => { - it('invokes updateBackupSchedule without error', async () => { - const client = new firestoreadminModule.FirestoreAdminClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.firestore.admin.v1.UpdateBackupScheduleRequest() - ); - request.backupSchedule ??= {}; - const defaultValue1 = - getTypeDefaultValue('.google.firestore.admin.v1.UpdateBackupScheduleRequest', ['backupSchedule', 'name']); - request.backupSchedule.name = defaultValue1; - const expectedHeaderRequestParams = `backup_schedule.name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.firestore.admin.v1.BackupSchedule() - ); - client.innerApiCalls.updateBackupSchedule = stubSimpleCall(expectedResponse); - const [response] = await client.updateBackupSchedule(request); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.updateBackupSchedule as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.updateBackupSchedule as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes deleteBackup with closed client', async () => { + const client = new firestoreadminModule.FirestoreAdminClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.firestore.admin.v1.DeleteBackupRequest() + ); + const defaultValue1 = getTypeDefaultValue( + '.google.firestore.admin.v1.DeleteBackupRequest', + ['name'] + ); + request.name = defaultValue1; + const expectedError = new Error('The client has already been closed.'); + client.close().catch(err => { + throw err; + }); + await assert.rejects(client.deleteBackup(request), expectedError); + }); + }); + + describe('createBackupSchedule', () => { + it('invokes createBackupSchedule without error', async () => { + const client = new firestoreadminModule.FirestoreAdminClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.firestore.admin.v1.CreateBackupScheduleRequest() + ); + const defaultValue1 = getTypeDefaultValue( + '.google.firestore.admin.v1.CreateBackupScheduleRequest', + ['parent'] + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.firestore.admin.v1.BackupSchedule() + ); + client.innerApiCalls.createBackupSchedule = + stubSimpleCall(expectedResponse); + const [response] = await client.createBackupSchedule(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.createBackupSchedule as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.createBackupSchedule as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes updateBackupSchedule without error using callback', async () => { - const client = new firestoreadminModule.FirestoreAdminClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.firestore.admin.v1.UpdateBackupScheduleRequest() - ); - request.backupSchedule ??= {}; - const defaultValue1 = - getTypeDefaultValue('.google.firestore.admin.v1.UpdateBackupScheduleRequest', ['backupSchedule', 'name']); - request.backupSchedule.name = defaultValue1; - const expectedHeaderRequestParams = `backup_schedule.name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.firestore.admin.v1.BackupSchedule() - ); - client.innerApiCalls.updateBackupSchedule = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.updateBackupSchedule( - request, - (err?: Error|null, result?: protos.google.firestore.admin.v1.IBackupSchedule|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.updateBackupSchedule as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.updateBackupSchedule as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes createBackupSchedule without error using callback', async () => { + const client = new firestoreadminModule.FirestoreAdminClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.firestore.admin.v1.CreateBackupScheduleRequest() + ); + const defaultValue1 = getTypeDefaultValue( + '.google.firestore.admin.v1.CreateBackupScheduleRequest', + ['parent'] + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.firestore.admin.v1.BackupSchedule() + ); + client.innerApiCalls.createBackupSchedule = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.createBackupSchedule( + request, + ( + err?: Error | null, + result?: protos.google.firestore.admin.v1.IBackupSchedule | null + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + } + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.createBackupSchedule as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.createBackupSchedule as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes updateBackupSchedule with error', async () => { - const client = new firestoreadminModule.FirestoreAdminClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.firestore.admin.v1.UpdateBackupScheduleRequest() - ); - request.backupSchedule ??= {}; - const defaultValue1 = - getTypeDefaultValue('.google.firestore.admin.v1.UpdateBackupScheduleRequest', ['backupSchedule', 'name']); - request.backupSchedule.name = defaultValue1; - const expectedHeaderRequestParams = `backup_schedule.name=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.updateBackupSchedule = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.updateBackupSchedule(request), expectedError); - const actualRequest = (client.innerApiCalls.updateBackupSchedule as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.updateBackupSchedule as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes createBackupSchedule with error', async () => { + const client = new firestoreadminModule.FirestoreAdminClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.firestore.admin.v1.CreateBackupScheduleRequest() + ); + const defaultValue1 = getTypeDefaultValue( + '.google.firestore.admin.v1.CreateBackupScheduleRequest', + ['parent'] + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.createBackupSchedule = stubSimpleCall( + undefined, + expectedError + ); + await assert.rejects(client.createBackupSchedule(request), expectedError); + const actualRequest = ( + client.innerApiCalls.createBackupSchedule as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.createBackupSchedule as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes updateBackupSchedule with closed client', async () => { - const client = new firestoreadminModule.FirestoreAdminClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.firestore.admin.v1.UpdateBackupScheduleRequest() - ); - request.backupSchedule ??= {}; - const defaultValue1 = - getTypeDefaultValue('.google.firestore.admin.v1.UpdateBackupScheduleRequest', ['backupSchedule', 'name']); - request.backupSchedule.name = defaultValue1; - const expectedError = new Error('The client has already been closed.'); - client.close().catch(err => {throw err}); - await assert.rejects(client.updateBackupSchedule(request), expectedError); - }); + it('invokes createBackupSchedule with closed client', async () => { + const client = new firestoreadminModule.FirestoreAdminClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.firestore.admin.v1.CreateBackupScheduleRequest() + ); + const defaultValue1 = getTypeDefaultValue( + '.google.firestore.admin.v1.CreateBackupScheduleRequest', + ['parent'] + ); + request.parent = defaultValue1; + const expectedError = new Error('The client has already been closed.'); + client.close().catch(err => { + throw err; + }); + await assert.rejects(client.createBackupSchedule(request), expectedError); + }); + }); + + describe('getBackupSchedule', () => { + it('invokes getBackupSchedule without error', async () => { + const client = new firestoreadminModule.FirestoreAdminClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.firestore.admin.v1.GetBackupScheduleRequest() + ); + const defaultValue1 = getTypeDefaultValue( + '.google.firestore.admin.v1.GetBackupScheduleRequest', + ['name'] + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.firestore.admin.v1.BackupSchedule() + ); + client.innerApiCalls.getBackupSchedule = stubSimpleCall(expectedResponse); + const [response] = await client.getBackupSchedule(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.getBackupSchedule as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.getBackupSchedule as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); }); - describe('deleteBackupSchedule', () => { - it('invokes deleteBackupSchedule without error', async () => { - const client = new firestoreadminModule.FirestoreAdminClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.firestore.admin.v1.DeleteBackupScheduleRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.firestore.admin.v1.DeleteBackupScheduleRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.protobuf.Empty() - ); - client.innerApiCalls.deleteBackupSchedule = stubSimpleCall(expectedResponse); - const [response] = await client.deleteBackupSchedule(request); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.deleteBackupSchedule as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.deleteBackupSchedule as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes getBackupSchedule without error using callback', async () => { + const client = new firestoreadminModule.FirestoreAdminClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.firestore.admin.v1.GetBackupScheduleRequest() + ); + const defaultValue1 = getTypeDefaultValue( + '.google.firestore.admin.v1.GetBackupScheduleRequest', + ['name'] + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.firestore.admin.v1.BackupSchedule() + ); + client.innerApiCalls.getBackupSchedule = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.getBackupSchedule( + request, + ( + err?: Error | null, + result?: protos.google.firestore.admin.v1.IBackupSchedule | null + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + } + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.getBackupSchedule as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.getBackupSchedule as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes deleteBackupSchedule without error using callback', async () => { - const client = new firestoreadminModule.FirestoreAdminClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.firestore.admin.v1.DeleteBackupScheduleRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.firestore.admin.v1.DeleteBackupScheduleRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.protobuf.Empty() - ); - client.innerApiCalls.deleteBackupSchedule = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.deleteBackupSchedule( - request, - (err?: Error|null, result?: protos.google.protobuf.IEmpty|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.deleteBackupSchedule as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.deleteBackupSchedule as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes getBackupSchedule with error', async () => { + const client = new firestoreadminModule.FirestoreAdminClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.firestore.admin.v1.GetBackupScheduleRequest() + ); + const defaultValue1 = getTypeDefaultValue( + '.google.firestore.admin.v1.GetBackupScheduleRequest', + ['name'] + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.getBackupSchedule = stubSimpleCall( + undefined, + expectedError + ); + await assert.rejects(client.getBackupSchedule(request), expectedError); + const actualRequest = ( + client.innerApiCalls.getBackupSchedule as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.getBackupSchedule as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes deleteBackupSchedule with error', async () => { - const client = new firestoreadminModule.FirestoreAdminClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.firestore.admin.v1.DeleteBackupScheduleRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.firestore.admin.v1.DeleteBackupScheduleRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.deleteBackupSchedule = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.deleteBackupSchedule(request), expectedError); - const actualRequest = (client.innerApiCalls.deleteBackupSchedule as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.deleteBackupSchedule as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes getBackupSchedule with closed client', async () => { + const client = new firestoreadminModule.FirestoreAdminClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.firestore.admin.v1.GetBackupScheduleRequest() + ); + const defaultValue1 = getTypeDefaultValue( + '.google.firestore.admin.v1.GetBackupScheduleRequest', + ['name'] + ); + request.name = defaultValue1; + const expectedError = new Error('The client has already been closed.'); + client.close().catch(err => { + throw err; + }); + await assert.rejects(client.getBackupSchedule(request), expectedError); + }); + }); + + describe('listBackupSchedules', () => { + it('invokes listBackupSchedules without error', async () => { + const client = new firestoreadminModule.FirestoreAdminClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.firestore.admin.v1.ListBackupSchedulesRequest() + ); + const defaultValue1 = getTypeDefaultValue( + '.google.firestore.admin.v1.ListBackupSchedulesRequest', + ['parent'] + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.firestore.admin.v1.ListBackupSchedulesResponse() + ); + client.innerApiCalls.listBackupSchedules = + stubSimpleCall(expectedResponse); + const [response] = await client.listBackupSchedules(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.listBackupSchedules as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.listBackupSchedules as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes deleteBackupSchedule with closed client', async () => { - const client = new firestoreadminModule.FirestoreAdminClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.firestore.admin.v1.DeleteBackupScheduleRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.firestore.admin.v1.DeleteBackupScheduleRequest', ['name']); - request.name = defaultValue1; - const expectedError = new Error('The client has already been closed.'); - client.close().catch(err => {throw err}); - await assert.rejects(client.deleteBackupSchedule(request), expectedError); - }); + it('invokes listBackupSchedules without error using callback', async () => { + const client = new firestoreadminModule.FirestoreAdminClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.firestore.admin.v1.ListBackupSchedulesRequest() + ); + const defaultValue1 = getTypeDefaultValue( + '.google.firestore.admin.v1.ListBackupSchedulesRequest', + ['parent'] + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.firestore.admin.v1.ListBackupSchedulesResponse() + ); + client.innerApiCalls.listBackupSchedules = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.listBackupSchedules( + request, + ( + err?: Error | null, + result?: protos.google.firestore.admin.v1.IListBackupSchedulesResponse | null + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + } + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.listBackupSchedules as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.listBackupSchedules as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); }); - describe('createIndex', () => { - it('invokes createIndex without error', async () => { - const client = new firestoreadminModule.FirestoreAdminClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.firestore.admin.v1.CreateIndexRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.firestore.admin.v1.CreateIndexRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.longrunning.Operation() - ); - client.innerApiCalls.createIndex = stubLongRunningCall(expectedResponse); - const [operation] = await client.createIndex(request); - const [response] = await operation.promise(); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.createIndex as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.createIndex as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes listBackupSchedules with error', async () => { + const client = new firestoreadminModule.FirestoreAdminClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.firestore.admin.v1.ListBackupSchedulesRequest() + ); + const defaultValue1 = getTypeDefaultValue( + '.google.firestore.admin.v1.ListBackupSchedulesRequest', + ['parent'] + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.listBackupSchedules = stubSimpleCall( + undefined, + expectedError + ); + await assert.rejects(client.listBackupSchedules(request), expectedError); + const actualRequest = ( + client.innerApiCalls.listBackupSchedules as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.listBackupSchedules as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes createIndex without error using callback', async () => { - const client = new firestoreadminModule.FirestoreAdminClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.firestore.admin.v1.CreateIndexRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.firestore.admin.v1.CreateIndexRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.longrunning.Operation() - ); - client.innerApiCalls.createIndex = stubLongRunningCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.createIndex( - request, - (err?: Error|null, - result?: LROperation|null - ) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const operation = await promise as LROperation; - const [response] = await operation.promise(); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.createIndex as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.createIndex as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes listBackupSchedules with closed client', async () => { + const client = new firestoreadminModule.FirestoreAdminClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.firestore.admin.v1.ListBackupSchedulesRequest() + ); + const defaultValue1 = getTypeDefaultValue( + '.google.firestore.admin.v1.ListBackupSchedulesRequest', + ['parent'] + ); + request.parent = defaultValue1; + const expectedError = new Error('The client has already been closed.'); + client.close().catch(err => { + throw err; + }); + await assert.rejects(client.listBackupSchedules(request), expectedError); + }); + }); + + describe('updateBackupSchedule', () => { + it('invokes updateBackupSchedule without error', async () => { + const client = new firestoreadminModule.FirestoreAdminClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.firestore.admin.v1.UpdateBackupScheduleRequest() + ); + request.backupSchedule ??= {}; + const defaultValue1 = getTypeDefaultValue( + '.google.firestore.admin.v1.UpdateBackupScheduleRequest', + ['backupSchedule', 'name'] + ); + request.backupSchedule.name = defaultValue1; + const expectedHeaderRequestParams = `backup_schedule.name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.firestore.admin.v1.BackupSchedule() + ); + client.innerApiCalls.updateBackupSchedule = + stubSimpleCall(expectedResponse); + const [response] = await client.updateBackupSchedule(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.updateBackupSchedule as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.updateBackupSchedule as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes createIndex with call error', async () => { - const client = new firestoreadminModule.FirestoreAdminClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.firestore.admin.v1.CreateIndexRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.firestore.admin.v1.CreateIndexRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.createIndex = stubLongRunningCall(undefined, expectedError); - await assert.rejects(client.createIndex(request), expectedError); - const actualRequest = (client.innerApiCalls.createIndex as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.createIndex as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes updateBackupSchedule without error using callback', async () => { + const client = new firestoreadminModule.FirestoreAdminClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.firestore.admin.v1.UpdateBackupScheduleRequest() + ); + request.backupSchedule ??= {}; + const defaultValue1 = getTypeDefaultValue( + '.google.firestore.admin.v1.UpdateBackupScheduleRequest', + ['backupSchedule', 'name'] + ); + request.backupSchedule.name = defaultValue1; + const expectedHeaderRequestParams = `backup_schedule.name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.firestore.admin.v1.BackupSchedule() + ); + client.innerApiCalls.updateBackupSchedule = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.updateBackupSchedule( + request, + ( + err?: Error | null, + result?: protos.google.firestore.admin.v1.IBackupSchedule | null + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + } + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.updateBackupSchedule as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.updateBackupSchedule as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes createIndex with LRO error', async () => { - const client = new firestoreadminModule.FirestoreAdminClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.firestore.admin.v1.CreateIndexRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.firestore.admin.v1.CreateIndexRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.createIndex = stubLongRunningCall(undefined, undefined, expectedError); - const [operation] = await client.createIndex(request); - await assert.rejects(operation.promise(), expectedError); - const actualRequest = (client.innerApiCalls.createIndex as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.createIndex as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes updateBackupSchedule with error', async () => { + const client = new firestoreadminModule.FirestoreAdminClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.firestore.admin.v1.UpdateBackupScheduleRequest() + ); + request.backupSchedule ??= {}; + const defaultValue1 = getTypeDefaultValue( + '.google.firestore.admin.v1.UpdateBackupScheduleRequest', + ['backupSchedule', 'name'] + ); + request.backupSchedule.name = defaultValue1; + const expectedHeaderRequestParams = `backup_schedule.name=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.updateBackupSchedule = stubSimpleCall( + undefined, + expectedError + ); + await assert.rejects(client.updateBackupSchedule(request), expectedError); + const actualRequest = ( + client.innerApiCalls.updateBackupSchedule as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.updateBackupSchedule as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes checkCreateIndexProgress without error', async () => { - const client = new firestoreadminModule.FirestoreAdminClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const expectedResponse = generateSampleMessage( - new operationsProtos.google.longrunning.Operation() - ); - expectedResponse.name = 'test'; - expectedResponse.response = {type_url: 'url', value: Buffer.from('')}; - expectedResponse.metadata = {type_url: 'url', value: Buffer.from('')} - - client.operationsClient.getOperation = stubSimpleCall(expectedResponse); - const decodedOperation = await client.checkCreateIndexProgress(expectedResponse.name); - assert.deepStrictEqual(decodedOperation.name, expectedResponse.name); - assert(decodedOperation.metadata); - assert((client.operationsClient.getOperation as SinonStub).getCall(0)); - }); + it('invokes updateBackupSchedule with closed client', async () => { + const client = new firestoreadminModule.FirestoreAdminClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.firestore.admin.v1.UpdateBackupScheduleRequest() + ); + request.backupSchedule ??= {}; + const defaultValue1 = getTypeDefaultValue( + '.google.firestore.admin.v1.UpdateBackupScheduleRequest', + ['backupSchedule', 'name'] + ); + request.backupSchedule.name = defaultValue1; + const expectedError = new Error('The client has already been closed.'); + client.close().catch(err => { + throw err; + }); + await assert.rejects(client.updateBackupSchedule(request), expectedError); + }); + }); + + describe('deleteBackupSchedule', () => { + it('invokes deleteBackupSchedule without error', async () => { + const client = new firestoreadminModule.FirestoreAdminClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.firestore.admin.v1.DeleteBackupScheduleRequest() + ); + const defaultValue1 = getTypeDefaultValue( + '.google.firestore.admin.v1.DeleteBackupScheduleRequest', + ['name'] + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.protobuf.Empty() + ); + client.innerApiCalls.deleteBackupSchedule = + stubSimpleCall(expectedResponse); + const [response] = await client.deleteBackupSchedule(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.deleteBackupSchedule as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.deleteBackupSchedule as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes checkCreateIndexProgress with error', async () => { - const client = new firestoreadminModule.FirestoreAdminClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const expectedError = new Error('expected'); - - client.operationsClient.getOperation = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.checkCreateIndexProgress(''), expectedError); - assert((client.operationsClient.getOperation as SinonStub) - .getCall(0)); - }); + it('invokes deleteBackupSchedule without error using callback', async () => { + const client = new firestoreadminModule.FirestoreAdminClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.firestore.admin.v1.DeleteBackupScheduleRequest() + ); + const defaultValue1 = getTypeDefaultValue( + '.google.firestore.admin.v1.DeleteBackupScheduleRequest', + ['name'] + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.protobuf.Empty() + ); + client.innerApiCalls.deleteBackupSchedule = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.deleteBackupSchedule( + request, + ( + err?: Error | null, + result?: protos.google.protobuf.IEmpty | null + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + } + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.deleteBackupSchedule as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.deleteBackupSchedule as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); }); - describe('updateField', () => { - it('invokes updateField without error', async () => { - const client = new firestoreadminModule.FirestoreAdminClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.firestore.admin.v1.UpdateFieldRequest() - ); - request.field ??= {}; - const defaultValue1 = - getTypeDefaultValue('.google.firestore.admin.v1.UpdateFieldRequest', ['field', 'name']); - request.field.name = defaultValue1; - const expectedHeaderRequestParams = `field.name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.longrunning.Operation() - ); - client.innerApiCalls.updateField = stubLongRunningCall(expectedResponse); - const [operation] = await client.updateField(request); - const [response] = await operation.promise(); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.updateField as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.updateField as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes deleteBackupSchedule with error', async () => { + const client = new firestoreadminModule.FirestoreAdminClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.firestore.admin.v1.DeleteBackupScheduleRequest() + ); + const defaultValue1 = getTypeDefaultValue( + '.google.firestore.admin.v1.DeleteBackupScheduleRequest', + ['name'] + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.deleteBackupSchedule = stubSimpleCall( + undefined, + expectedError + ); + await assert.rejects(client.deleteBackupSchedule(request), expectedError); + const actualRequest = ( + client.innerApiCalls.deleteBackupSchedule as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.deleteBackupSchedule as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes updateField without error using callback', async () => { - const client = new firestoreadminModule.FirestoreAdminClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.firestore.admin.v1.UpdateFieldRequest() - ); - request.field ??= {}; - const defaultValue1 = - getTypeDefaultValue('.google.firestore.admin.v1.UpdateFieldRequest', ['field', 'name']); - request.field.name = defaultValue1; - const expectedHeaderRequestParams = `field.name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.longrunning.Operation() - ); - client.innerApiCalls.updateField = stubLongRunningCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.updateField( - request, - (err?: Error|null, - result?: LROperation|null - ) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const operation = await promise as LROperation; - const [response] = await operation.promise(); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.updateField as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.updateField as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes deleteBackupSchedule with closed client', async () => { + const client = new firestoreadminModule.FirestoreAdminClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.firestore.admin.v1.DeleteBackupScheduleRequest() + ); + const defaultValue1 = getTypeDefaultValue( + '.google.firestore.admin.v1.DeleteBackupScheduleRequest', + ['name'] + ); + request.name = defaultValue1; + const expectedError = new Error('The client has already been closed.'); + client.close().catch(err => { + throw err; + }); + await assert.rejects(client.deleteBackupSchedule(request), expectedError); + }); + }); + + describe('createIndex', () => { + it('invokes createIndex without error', async () => { + const client = new firestoreadminModule.FirestoreAdminClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.firestore.admin.v1.CreateIndexRequest() + ); + const defaultValue1 = getTypeDefaultValue( + '.google.firestore.admin.v1.CreateIndexRequest', + ['parent'] + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.longrunning.Operation() + ); + client.innerApiCalls.createIndex = stubLongRunningCall(expectedResponse); + const [operation] = await client.createIndex(request); + const [response] = await operation.promise(); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.createIndex as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.createIndex as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes updateField with call error', async () => { - const client = new firestoreadminModule.FirestoreAdminClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.firestore.admin.v1.UpdateFieldRequest() - ); - request.field ??= {}; - const defaultValue1 = - getTypeDefaultValue('.google.firestore.admin.v1.UpdateFieldRequest', ['field', 'name']); - request.field.name = defaultValue1; - const expectedHeaderRequestParams = `field.name=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.updateField = stubLongRunningCall(undefined, expectedError); - await assert.rejects(client.updateField(request), expectedError); - const actualRequest = (client.innerApiCalls.updateField as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.updateField as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes createIndex without error using callback', async () => { + const client = new firestoreadminModule.FirestoreAdminClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.firestore.admin.v1.CreateIndexRequest() + ); + const defaultValue1 = getTypeDefaultValue( + '.google.firestore.admin.v1.CreateIndexRequest', + ['parent'] + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.longrunning.Operation() + ); + client.innerApiCalls.createIndex = + stubLongRunningCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.createIndex( + request, + ( + err?: Error | null, + result?: LROperation< + protos.google.firestore.admin.v1.IIndex, + protos.google.firestore.admin.v1.IIndexOperationMetadata + > | null + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + } + ); + }); + const operation = (await promise) as LROperation< + protos.google.firestore.admin.v1.IIndex, + protos.google.firestore.admin.v1.IIndexOperationMetadata + >; + const [response] = await operation.promise(); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.createIndex as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.createIndex as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes updateField with LRO error', async () => { - const client = new firestoreadminModule.FirestoreAdminClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.firestore.admin.v1.UpdateFieldRequest() - ); - request.field ??= {}; - const defaultValue1 = - getTypeDefaultValue('.google.firestore.admin.v1.UpdateFieldRequest', ['field', 'name']); - request.field.name = defaultValue1; - const expectedHeaderRequestParams = `field.name=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.updateField = stubLongRunningCall(undefined, undefined, expectedError); - const [operation] = await client.updateField(request); - await assert.rejects(operation.promise(), expectedError); - const actualRequest = (client.innerApiCalls.updateField as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.updateField as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes createIndex with call error', async () => { + const client = new firestoreadminModule.FirestoreAdminClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.firestore.admin.v1.CreateIndexRequest() + ); + const defaultValue1 = getTypeDefaultValue( + '.google.firestore.admin.v1.CreateIndexRequest', + ['parent'] + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.createIndex = stubLongRunningCall( + undefined, + expectedError + ); + await assert.rejects(client.createIndex(request), expectedError); + const actualRequest = ( + client.innerApiCalls.createIndex as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.createIndex as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes checkUpdateFieldProgress without error', async () => { - const client = new firestoreadminModule.FirestoreAdminClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const expectedResponse = generateSampleMessage( - new operationsProtos.google.longrunning.Operation() - ); - expectedResponse.name = 'test'; - expectedResponse.response = {type_url: 'url', value: Buffer.from('')}; - expectedResponse.metadata = {type_url: 'url', value: Buffer.from('')} - - client.operationsClient.getOperation = stubSimpleCall(expectedResponse); - const decodedOperation = await client.checkUpdateFieldProgress(expectedResponse.name); - assert.deepStrictEqual(decodedOperation.name, expectedResponse.name); - assert(decodedOperation.metadata); - assert((client.operationsClient.getOperation as SinonStub).getCall(0)); - }); + it('invokes createIndex with LRO error', async () => { + const client = new firestoreadminModule.FirestoreAdminClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.firestore.admin.v1.CreateIndexRequest() + ); + const defaultValue1 = getTypeDefaultValue( + '.google.firestore.admin.v1.CreateIndexRequest', + ['parent'] + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.createIndex = stubLongRunningCall( + undefined, + undefined, + expectedError + ); + const [operation] = await client.createIndex(request); + await assert.rejects(operation.promise(), expectedError); + const actualRequest = ( + client.innerApiCalls.createIndex as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.createIndex as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes checkUpdateFieldProgress with error', async () => { - const client = new firestoreadminModule.FirestoreAdminClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const expectedError = new Error('expected'); - - client.operationsClient.getOperation = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.checkUpdateFieldProgress(''), expectedError); - assert((client.operationsClient.getOperation as SinonStub) - .getCall(0)); - }); + it('invokes checkCreateIndexProgress without error', async () => { + const client = new firestoreadminModule.FirestoreAdminClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const expectedResponse = generateSampleMessage( + new operationsProtos.google.longrunning.Operation() + ); + expectedResponse.name = 'test'; + expectedResponse.response = {type_url: 'url', value: Buffer.from('')}; + expectedResponse.metadata = {type_url: 'url', value: Buffer.from('')}; + + client.operationsClient.getOperation = stubSimpleCall(expectedResponse); + const decodedOperation = await client.checkCreateIndexProgress( + expectedResponse.name + ); + assert.deepStrictEqual(decodedOperation.name, expectedResponse.name); + assert(decodedOperation.metadata); + assert((client.operationsClient.getOperation as SinonStub).getCall(0)); }); - describe('exportDocuments', () => { - it('invokes exportDocuments without error', async () => { - const client = new firestoreadminModule.FirestoreAdminClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.firestore.admin.v1.ExportDocumentsRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.firestore.admin.v1.ExportDocumentsRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.longrunning.Operation() - ); - client.innerApiCalls.exportDocuments = stubLongRunningCall(expectedResponse); - const [operation] = await client.exportDocuments(request); - const [response] = await operation.promise(); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.exportDocuments as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.exportDocuments as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes checkCreateIndexProgress with error', async () => { + const client = new firestoreadminModule.FirestoreAdminClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const expectedError = new Error('expected'); + + client.operationsClient.getOperation = stubSimpleCall( + undefined, + expectedError + ); + await assert.rejects(client.checkCreateIndexProgress(''), expectedError); + assert((client.operationsClient.getOperation as SinonStub).getCall(0)); + }); + }); + + describe('updateField', () => { + it('invokes updateField without error', async () => { + const client = new firestoreadminModule.FirestoreAdminClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.firestore.admin.v1.UpdateFieldRequest() + ); + request.field ??= {}; + const defaultValue1 = getTypeDefaultValue( + '.google.firestore.admin.v1.UpdateFieldRequest', + ['field', 'name'] + ); + request.field.name = defaultValue1; + const expectedHeaderRequestParams = `field.name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.longrunning.Operation() + ); + client.innerApiCalls.updateField = stubLongRunningCall(expectedResponse); + const [operation] = await client.updateField(request); + const [response] = await operation.promise(); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.updateField as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.updateField as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes exportDocuments without error using callback', async () => { - const client = new firestoreadminModule.FirestoreAdminClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.firestore.admin.v1.ExportDocumentsRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.firestore.admin.v1.ExportDocumentsRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.longrunning.Operation() - ); - client.innerApiCalls.exportDocuments = stubLongRunningCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.exportDocuments( - request, - (err?: Error|null, - result?: LROperation|null - ) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const operation = await promise as LROperation; - const [response] = await operation.promise(); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.exportDocuments as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.exportDocuments as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes updateField without error using callback', async () => { + const client = new firestoreadminModule.FirestoreAdminClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.firestore.admin.v1.UpdateFieldRequest() + ); + request.field ??= {}; + const defaultValue1 = getTypeDefaultValue( + '.google.firestore.admin.v1.UpdateFieldRequest', + ['field', 'name'] + ); + request.field.name = defaultValue1; + const expectedHeaderRequestParams = `field.name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.longrunning.Operation() + ); + client.innerApiCalls.updateField = + stubLongRunningCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.updateField( + request, + ( + err?: Error | null, + result?: LROperation< + protos.google.firestore.admin.v1.IField, + protos.google.firestore.admin.v1.IFieldOperationMetadata + > | null + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + } + ); + }); + const operation = (await promise) as LROperation< + protos.google.firestore.admin.v1.IField, + protos.google.firestore.admin.v1.IFieldOperationMetadata + >; + const [response] = await operation.promise(); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.updateField as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.updateField as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes exportDocuments with call error', async () => { - const client = new firestoreadminModule.FirestoreAdminClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.firestore.admin.v1.ExportDocumentsRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.firestore.admin.v1.ExportDocumentsRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.exportDocuments = stubLongRunningCall(undefined, expectedError); - await assert.rejects(client.exportDocuments(request), expectedError); - const actualRequest = (client.innerApiCalls.exportDocuments as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.exportDocuments as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes updateField with call error', async () => { + const client = new firestoreadminModule.FirestoreAdminClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.firestore.admin.v1.UpdateFieldRequest() + ); + request.field ??= {}; + const defaultValue1 = getTypeDefaultValue( + '.google.firestore.admin.v1.UpdateFieldRequest', + ['field', 'name'] + ); + request.field.name = defaultValue1; + const expectedHeaderRequestParams = `field.name=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.updateField = stubLongRunningCall( + undefined, + expectedError + ); + await assert.rejects(client.updateField(request), expectedError); + const actualRequest = ( + client.innerApiCalls.updateField as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.updateField as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes exportDocuments with LRO error', async () => { - const client = new firestoreadminModule.FirestoreAdminClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.firestore.admin.v1.ExportDocumentsRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.firestore.admin.v1.ExportDocumentsRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.exportDocuments = stubLongRunningCall(undefined, undefined, expectedError); - const [operation] = await client.exportDocuments(request); - await assert.rejects(operation.promise(), expectedError); - const actualRequest = (client.innerApiCalls.exportDocuments as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.exportDocuments as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes updateField with LRO error', async () => { + const client = new firestoreadminModule.FirestoreAdminClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.firestore.admin.v1.UpdateFieldRequest() + ); + request.field ??= {}; + const defaultValue1 = getTypeDefaultValue( + '.google.firestore.admin.v1.UpdateFieldRequest', + ['field', 'name'] + ); + request.field.name = defaultValue1; + const expectedHeaderRequestParams = `field.name=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.updateField = stubLongRunningCall( + undefined, + undefined, + expectedError + ); + const [operation] = await client.updateField(request); + await assert.rejects(operation.promise(), expectedError); + const actualRequest = ( + client.innerApiCalls.updateField as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.updateField as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes checkExportDocumentsProgress without error', async () => { - const client = new firestoreadminModule.FirestoreAdminClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const expectedResponse = generateSampleMessage( - new operationsProtos.google.longrunning.Operation() - ); - expectedResponse.name = 'test'; - expectedResponse.response = {type_url: 'url', value: Buffer.from('')}; - expectedResponse.metadata = {type_url: 'url', value: Buffer.from('')} - - client.operationsClient.getOperation = stubSimpleCall(expectedResponse); - const decodedOperation = await client.checkExportDocumentsProgress(expectedResponse.name); - assert.deepStrictEqual(decodedOperation.name, expectedResponse.name); - assert(decodedOperation.metadata); - assert((client.operationsClient.getOperation as SinonStub).getCall(0)); - }); + it('invokes checkUpdateFieldProgress without error', async () => { + const client = new firestoreadminModule.FirestoreAdminClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const expectedResponse = generateSampleMessage( + new operationsProtos.google.longrunning.Operation() + ); + expectedResponse.name = 'test'; + expectedResponse.response = {type_url: 'url', value: Buffer.from('')}; + expectedResponse.metadata = {type_url: 'url', value: Buffer.from('')}; + + client.operationsClient.getOperation = stubSimpleCall(expectedResponse); + const decodedOperation = await client.checkUpdateFieldProgress( + expectedResponse.name + ); + assert.deepStrictEqual(decodedOperation.name, expectedResponse.name); + assert(decodedOperation.metadata); + assert((client.operationsClient.getOperation as SinonStub).getCall(0)); + }); - it('invokes checkExportDocumentsProgress with error', async () => { - const client = new firestoreadminModule.FirestoreAdminClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const expectedError = new Error('expected'); - - client.operationsClient.getOperation = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.checkExportDocumentsProgress(''), expectedError); - assert((client.operationsClient.getOperation as SinonStub) - .getCall(0)); - }); + it('invokes checkUpdateFieldProgress with error', async () => { + const client = new firestoreadminModule.FirestoreAdminClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const expectedError = new Error('expected'); + + client.operationsClient.getOperation = stubSimpleCall( + undefined, + expectedError + ); + await assert.rejects(client.checkUpdateFieldProgress(''), expectedError); + assert((client.operationsClient.getOperation as SinonStub).getCall(0)); + }); + }); + + describe('exportDocuments', () => { + it('invokes exportDocuments without error', async () => { + const client = new firestoreadminModule.FirestoreAdminClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.firestore.admin.v1.ExportDocumentsRequest() + ); + const defaultValue1 = getTypeDefaultValue( + '.google.firestore.admin.v1.ExportDocumentsRequest', + ['name'] + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.longrunning.Operation() + ); + client.innerApiCalls.exportDocuments = + stubLongRunningCall(expectedResponse); + const [operation] = await client.exportDocuments(request); + const [response] = await operation.promise(); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.exportDocuments as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.exportDocuments as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); }); - describe('importDocuments', () => { - it('invokes importDocuments without error', async () => { - const client = new firestoreadminModule.FirestoreAdminClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.firestore.admin.v1.ImportDocumentsRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.firestore.admin.v1.ImportDocumentsRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.longrunning.Operation() - ); - client.innerApiCalls.importDocuments = stubLongRunningCall(expectedResponse); - const [operation] = await client.importDocuments(request); - const [response] = await operation.promise(); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.importDocuments as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.importDocuments as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes exportDocuments without error using callback', async () => { + const client = new firestoreadminModule.FirestoreAdminClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.firestore.admin.v1.ExportDocumentsRequest() + ); + const defaultValue1 = getTypeDefaultValue( + '.google.firestore.admin.v1.ExportDocumentsRequest', + ['name'] + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.longrunning.Operation() + ); + client.innerApiCalls.exportDocuments = + stubLongRunningCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.exportDocuments( + request, + ( + err?: Error | null, + result?: LROperation< + protos.google.firestore.admin.v1.IExportDocumentsResponse, + protos.google.firestore.admin.v1.IExportDocumentsMetadata + > | null + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + } + ); + }); + const operation = (await promise) as LROperation< + protos.google.firestore.admin.v1.IExportDocumentsResponse, + protos.google.firestore.admin.v1.IExportDocumentsMetadata + >; + const [response] = await operation.promise(); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.exportDocuments as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.exportDocuments as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes importDocuments without error using callback', async () => { - const client = new firestoreadminModule.FirestoreAdminClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.firestore.admin.v1.ImportDocumentsRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.firestore.admin.v1.ImportDocumentsRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.longrunning.Operation() - ); - client.innerApiCalls.importDocuments = stubLongRunningCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.importDocuments( - request, - (err?: Error|null, - result?: LROperation|null - ) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const operation = await promise as LROperation; - const [response] = await operation.promise(); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.importDocuments as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.importDocuments as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes exportDocuments with call error', async () => { + const client = new firestoreadminModule.FirestoreAdminClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.firestore.admin.v1.ExportDocumentsRequest() + ); + const defaultValue1 = getTypeDefaultValue( + '.google.firestore.admin.v1.ExportDocumentsRequest', + ['name'] + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.exportDocuments = stubLongRunningCall( + undefined, + expectedError + ); + await assert.rejects(client.exportDocuments(request), expectedError); + const actualRequest = ( + client.innerApiCalls.exportDocuments as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.exportDocuments as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes importDocuments with call error', async () => { - const client = new firestoreadminModule.FirestoreAdminClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.firestore.admin.v1.ImportDocumentsRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.firestore.admin.v1.ImportDocumentsRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.importDocuments = stubLongRunningCall(undefined, expectedError); - await assert.rejects(client.importDocuments(request), expectedError); - const actualRequest = (client.innerApiCalls.importDocuments as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.importDocuments as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes exportDocuments with LRO error', async () => { + const client = new firestoreadminModule.FirestoreAdminClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.firestore.admin.v1.ExportDocumentsRequest() + ); + const defaultValue1 = getTypeDefaultValue( + '.google.firestore.admin.v1.ExportDocumentsRequest', + ['name'] + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.exportDocuments = stubLongRunningCall( + undefined, + undefined, + expectedError + ); + const [operation] = await client.exportDocuments(request); + await assert.rejects(operation.promise(), expectedError); + const actualRequest = ( + client.innerApiCalls.exportDocuments as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.exportDocuments as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes importDocuments with LRO error', async () => { - const client = new firestoreadminModule.FirestoreAdminClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.firestore.admin.v1.ImportDocumentsRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.firestore.admin.v1.ImportDocumentsRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.importDocuments = stubLongRunningCall(undefined, undefined, expectedError); - const [operation] = await client.importDocuments(request); - await assert.rejects(operation.promise(), expectedError); - const actualRequest = (client.innerApiCalls.importDocuments as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.importDocuments as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes checkExportDocumentsProgress without error', async () => { + const client = new firestoreadminModule.FirestoreAdminClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const expectedResponse = generateSampleMessage( + new operationsProtos.google.longrunning.Operation() + ); + expectedResponse.name = 'test'; + expectedResponse.response = {type_url: 'url', value: Buffer.from('')}; + expectedResponse.metadata = {type_url: 'url', value: Buffer.from('')}; + + client.operationsClient.getOperation = stubSimpleCall(expectedResponse); + const decodedOperation = await client.checkExportDocumentsProgress( + expectedResponse.name + ); + assert.deepStrictEqual(decodedOperation.name, expectedResponse.name); + assert(decodedOperation.metadata); + assert((client.operationsClient.getOperation as SinonStub).getCall(0)); + }); - it('invokes checkImportDocumentsProgress without error', async () => { - const client = new firestoreadminModule.FirestoreAdminClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const expectedResponse = generateSampleMessage( - new operationsProtos.google.longrunning.Operation() - ); - expectedResponse.name = 'test'; - expectedResponse.response = {type_url: 'url', value: Buffer.from('')}; - expectedResponse.metadata = {type_url: 'url', value: Buffer.from('')} - - client.operationsClient.getOperation = stubSimpleCall(expectedResponse); - const decodedOperation = await client.checkImportDocumentsProgress(expectedResponse.name); - assert.deepStrictEqual(decodedOperation.name, expectedResponse.name); - assert(decodedOperation.metadata); - assert((client.operationsClient.getOperation as SinonStub).getCall(0)); - }); + it('invokes checkExportDocumentsProgress with error', async () => { + const client = new firestoreadminModule.FirestoreAdminClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const expectedError = new Error('expected'); + + client.operationsClient.getOperation = stubSimpleCall( + undefined, + expectedError + ); + await assert.rejects( + client.checkExportDocumentsProgress(''), + expectedError + ); + assert((client.operationsClient.getOperation as SinonStub).getCall(0)); + }); + }); + + describe('importDocuments', () => { + it('invokes importDocuments without error', async () => { + const client = new firestoreadminModule.FirestoreAdminClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.firestore.admin.v1.ImportDocumentsRequest() + ); + const defaultValue1 = getTypeDefaultValue( + '.google.firestore.admin.v1.ImportDocumentsRequest', + ['name'] + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.longrunning.Operation() + ); + client.innerApiCalls.importDocuments = + stubLongRunningCall(expectedResponse); + const [operation] = await client.importDocuments(request); + const [response] = await operation.promise(); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.importDocuments as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.importDocuments as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes checkImportDocumentsProgress with error', async () => { - const client = new firestoreadminModule.FirestoreAdminClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const expectedError = new Error('expected'); - - client.operationsClient.getOperation = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.checkImportDocumentsProgress(''), expectedError); - assert((client.operationsClient.getOperation as SinonStub) - .getCall(0)); - }); + it('invokes importDocuments without error using callback', async () => { + const client = new firestoreadminModule.FirestoreAdminClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.firestore.admin.v1.ImportDocumentsRequest() + ); + const defaultValue1 = getTypeDefaultValue( + '.google.firestore.admin.v1.ImportDocumentsRequest', + ['name'] + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.longrunning.Operation() + ); + client.innerApiCalls.importDocuments = + stubLongRunningCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.importDocuments( + request, + ( + err?: Error | null, + result?: LROperation< + protos.google.protobuf.IEmpty, + protos.google.firestore.admin.v1.IImportDocumentsMetadata + > | null + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + } + ); + }); + const operation = (await promise) as LROperation< + protos.google.protobuf.IEmpty, + protos.google.firestore.admin.v1.IImportDocumentsMetadata + >; + const [response] = await operation.promise(); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.importDocuments as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.importDocuments as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); }); - describe('bulkDeleteDocuments', () => { - it('invokes bulkDeleteDocuments without error', async () => { - const client = new firestoreadminModule.FirestoreAdminClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.firestore.admin.v1.BulkDeleteDocumentsRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.firestore.admin.v1.BulkDeleteDocumentsRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.longrunning.Operation() - ); - client.innerApiCalls.bulkDeleteDocuments = stubLongRunningCall(expectedResponse); - const [operation] = await client.bulkDeleteDocuments(request); - const [response] = await operation.promise(); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.bulkDeleteDocuments as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.bulkDeleteDocuments as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes importDocuments with call error', async () => { + const client = new firestoreadminModule.FirestoreAdminClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.firestore.admin.v1.ImportDocumentsRequest() + ); + const defaultValue1 = getTypeDefaultValue( + '.google.firestore.admin.v1.ImportDocumentsRequest', + ['name'] + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.importDocuments = stubLongRunningCall( + undefined, + expectedError + ); + await assert.rejects(client.importDocuments(request), expectedError); + const actualRequest = ( + client.innerApiCalls.importDocuments as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.importDocuments as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes bulkDeleteDocuments without error using callback', async () => { - const client = new firestoreadminModule.FirestoreAdminClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.firestore.admin.v1.BulkDeleteDocumentsRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.firestore.admin.v1.BulkDeleteDocumentsRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.longrunning.Operation() - ); - client.innerApiCalls.bulkDeleteDocuments = stubLongRunningCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.bulkDeleteDocuments( - request, - (err?: Error|null, - result?: LROperation|null - ) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const operation = await promise as LROperation; - const [response] = await operation.promise(); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.bulkDeleteDocuments as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.bulkDeleteDocuments as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes importDocuments with LRO error', async () => { + const client = new firestoreadminModule.FirestoreAdminClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.firestore.admin.v1.ImportDocumentsRequest() + ); + const defaultValue1 = getTypeDefaultValue( + '.google.firestore.admin.v1.ImportDocumentsRequest', + ['name'] + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.importDocuments = stubLongRunningCall( + undefined, + undefined, + expectedError + ); + const [operation] = await client.importDocuments(request); + await assert.rejects(operation.promise(), expectedError); + const actualRequest = ( + client.innerApiCalls.importDocuments as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.importDocuments as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes bulkDeleteDocuments with call error', async () => { - const client = new firestoreadminModule.FirestoreAdminClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.firestore.admin.v1.BulkDeleteDocumentsRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.firestore.admin.v1.BulkDeleteDocumentsRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.bulkDeleteDocuments = stubLongRunningCall(undefined, expectedError); - await assert.rejects(client.bulkDeleteDocuments(request), expectedError); - const actualRequest = (client.innerApiCalls.bulkDeleteDocuments as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.bulkDeleteDocuments as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes checkImportDocumentsProgress without error', async () => { + const client = new firestoreadminModule.FirestoreAdminClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const expectedResponse = generateSampleMessage( + new operationsProtos.google.longrunning.Operation() + ); + expectedResponse.name = 'test'; + expectedResponse.response = {type_url: 'url', value: Buffer.from('')}; + expectedResponse.metadata = {type_url: 'url', value: Buffer.from('')}; + + client.operationsClient.getOperation = stubSimpleCall(expectedResponse); + const decodedOperation = await client.checkImportDocumentsProgress( + expectedResponse.name + ); + assert.deepStrictEqual(decodedOperation.name, expectedResponse.name); + assert(decodedOperation.metadata); + assert((client.operationsClient.getOperation as SinonStub).getCall(0)); + }); - it('invokes bulkDeleteDocuments with LRO error', async () => { - const client = new firestoreadminModule.FirestoreAdminClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.firestore.admin.v1.BulkDeleteDocumentsRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.firestore.admin.v1.BulkDeleteDocumentsRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.bulkDeleteDocuments = stubLongRunningCall(undefined, undefined, expectedError); - const [operation] = await client.bulkDeleteDocuments(request); - await assert.rejects(operation.promise(), expectedError); - const actualRequest = (client.innerApiCalls.bulkDeleteDocuments as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.bulkDeleteDocuments as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes checkImportDocumentsProgress with error', async () => { + const client = new firestoreadminModule.FirestoreAdminClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const expectedError = new Error('expected'); + + client.operationsClient.getOperation = stubSimpleCall( + undefined, + expectedError + ); + await assert.rejects( + client.checkImportDocumentsProgress(''), + expectedError + ); + assert((client.operationsClient.getOperation as SinonStub).getCall(0)); + }); + }); + + describe('bulkDeleteDocuments', () => { + it('invokes bulkDeleteDocuments without error', async () => { + const client = new firestoreadminModule.FirestoreAdminClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.firestore.admin.v1.BulkDeleteDocumentsRequest() + ); + const defaultValue1 = getTypeDefaultValue( + '.google.firestore.admin.v1.BulkDeleteDocumentsRequest', + ['name'] + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.longrunning.Operation() + ); + client.innerApiCalls.bulkDeleteDocuments = + stubLongRunningCall(expectedResponse); + const [operation] = await client.bulkDeleteDocuments(request); + const [response] = await operation.promise(); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.bulkDeleteDocuments as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.bulkDeleteDocuments as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes checkBulkDeleteDocumentsProgress without error', async () => { - const client = new firestoreadminModule.FirestoreAdminClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const expectedResponse = generateSampleMessage( - new operationsProtos.google.longrunning.Operation() - ); - expectedResponse.name = 'test'; - expectedResponse.response = {type_url: 'url', value: Buffer.from('')}; - expectedResponse.metadata = {type_url: 'url', value: Buffer.from('')} - - client.operationsClient.getOperation = stubSimpleCall(expectedResponse); - const decodedOperation = await client.checkBulkDeleteDocumentsProgress(expectedResponse.name); - assert.deepStrictEqual(decodedOperation.name, expectedResponse.name); - assert(decodedOperation.metadata); - assert((client.operationsClient.getOperation as SinonStub).getCall(0)); - }); + it('invokes bulkDeleteDocuments without error using callback', async () => { + const client = new firestoreadminModule.FirestoreAdminClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.firestore.admin.v1.BulkDeleteDocumentsRequest() + ); + const defaultValue1 = getTypeDefaultValue( + '.google.firestore.admin.v1.BulkDeleteDocumentsRequest', + ['name'] + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.longrunning.Operation() + ); + client.innerApiCalls.bulkDeleteDocuments = + stubLongRunningCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.bulkDeleteDocuments( + request, + ( + err?: Error | null, + result?: LROperation< + protos.google.firestore.admin.v1.IBulkDeleteDocumentsResponse, + protos.google.firestore.admin.v1.IBulkDeleteDocumentsMetadata + > | null + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + } + ); + }); + const operation = (await promise) as LROperation< + protos.google.firestore.admin.v1.IBulkDeleteDocumentsResponse, + protos.google.firestore.admin.v1.IBulkDeleteDocumentsMetadata + >; + const [response] = await operation.promise(); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.bulkDeleteDocuments as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.bulkDeleteDocuments as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes checkBulkDeleteDocumentsProgress with error', async () => { - const client = new firestoreadminModule.FirestoreAdminClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const expectedError = new Error('expected'); - - client.operationsClient.getOperation = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.checkBulkDeleteDocumentsProgress(''), expectedError); - assert((client.operationsClient.getOperation as SinonStub) - .getCall(0)); - }); + it('invokes bulkDeleteDocuments with call error', async () => { + const client = new firestoreadminModule.FirestoreAdminClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.firestore.admin.v1.BulkDeleteDocumentsRequest() + ); + const defaultValue1 = getTypeDefaultValue( + '.google.firestore.admin.v1.BulkDeleteDocumentsRequest', + ['name'] + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.bulkDeleteDocuments = stubLongRunningCall( + undefined, + expectedError + ); + await assert.rejects(client.bulkDeleteDocuments(request), expectedError); + const actualRequest = ( + client.innerApiCalls.bulkDeleteDocuments as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.bulkDeleteDocuments as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); }); - describe('createDatabase', () => { - it('invokes createDatabase without error', async () => { - const client = new firestoreadminModule.FirestoreAdminClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.firestore.admin.v1.CreateDatabaseRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.firestore.admin.v1.CreateDatabaseRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.longrunning.Operation() - ); - client.innerApiCalls.createDatabase = stubLongRunningCall(expectedResponse); - const [operation] = await client.createDatabase(request); - const [response] = await operation.promise(); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.createDatabase as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.createDatabase as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes bulkDeleteDocuments with LRO error', async () => { + const client = new firestoreadminModule.FirestoreAdminClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.firestore.admin.v1.BulkDeleteDocumentsRequest() + ); + const defaultValue1 = getTypeDefaultValue( + '.google.firestore.admin.v1.BulkDeleteDocumentsRequest', + ['name'] + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.bulkDeleteDocuments = stubLongRunningCall( + undefined, + undefined, + expectedError + ); + const [operation] = await client.bulkDeleteDocuments(request); + await assert.rejects(operation.promise(), expectedError); + const actualRequest = ( + client.innerApiCalls.bulkDeleteDocuments as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.bulkDeleteDocuments as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes createDatabase without error using callback', async () => { - const client = new firestoreadminModule.FirestoreAdminClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.firestore.admin.v1.CreateDatabaseRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.firestore.admin.v1.CreateDatabaseRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.longrunning.Operation() - ); - client.innerApiCalls.createDatabase = stubLongRunningCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.createDatabase( - request, - (err?: Error|null, - result?: LROperation|null - ) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const operation = await promise as LROperation; - const [response] = await operation.promise(); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.createDatabase as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.createDatabase as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes checkBulkDeleteDocumentsProgress without error', async () => { + const client = new firestoreadminModule.FirestoreAdminClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const expectedResponse = generateSampleMessage( + new operationsProtos.google.longrunning.Operation() + ); + expectedResponse.name = 'test'; + expectedResponse.response = {type_url: 'url', value: Buffer.from('')}; + expectedResponse.metadata = {type_url: 'url', value: Buffer.from('')}; + + client.operationsClient.getOperation = stubSimpleCall(expectedResponse); + const decodedOperation = await client.checkBulkDeleteDocumentsProgress( + expectedResponse.name + ); + assert.deepStrictEqual(decodedOperation.name, expectedResponse.name); + assert(decodedOperation.metadata); + assert((client.operationsClient.getOperation as SinonStub).getCall(0)); + }); - it('invokes createDatabase with call error', async () => { - const client = new firestoreadminModule.FirestoreAdminClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.firestore.admin.v1.CreateDatabaseRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.firestore.admin.v1.CreateDatabaseRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.createDatabase = stubLongRunningCall(undefined, expectedError); - await assert.rejects(client.createDatabase(request), expectedError); - const actualRequest = (client.innerApiCalls.createDatabase as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.createDatabase as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes checkBulkDeleteDocumentsProgress with error', async () => { + const client = new firestoreadminModule.FirestoreAdminClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const expectedError = new Error('expected'); + + client.operationsClient.getOperation = stubSimpleCall( + undefined, + expectedError + ); + await assert.rejects( + client.checkBulkDeleteDocumentsProgress(''), + expectedError + ); + assert((client.operationsClient.getOperation as SinonStub).getCall(0)); + }); + }); + + describe('createDatabase', () => { + it('invokes createDatabase without error', async () => { + const client = new firestoreadminModule.FirestoreAdminClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.firestore.admin.v1.CreateDatabaseRequest() + ); + const defaultValue1 = getTypeDefaultValue( + '.google.firestore.admin.v1.CreateDatabaseRequest', + ['parent'] + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.longrunning.Operation() + ); + client.innerApiCalls.createDatabase = + stubLongRunningCall(expectedResponse); + const [operation] = await client.createDatabase(request); + const [response] = await operation.promise(); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.createDatabase as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.createDatabase as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes createDatabase with LRO error', async () => { - const client = new firestoreadminModule.FirestoreAdminClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.firestore.admin.v1.CreateDatabaseRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.firestore.admin.v1.CreateDatabaseRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.createDatabase = stubLongRunningCall(undefined, undefined, expectedError); - const [operation] = await client.createDatabase(request); - await assert.rejects(operation.promise(), expectedError); - const actualRequest = (client.innerApiCalls.createDatabase as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.createDatabase as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes createDatabase without error using callback', async () => { + const client = new firestoreadminModule.FirestoreAdminClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.firestore.admin.v1.CreateDatabaseRequest() + ); + const defaultValue1 = getTypeDefaultValue( + '.google.firestore.admin.v1.CreateDatabaseRequest', + ['parent'] + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.longrunning.Operation() + ); + client.innerApiCalls.createDatabase = + stubLongRunningCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.createDatabase( + request, + ( + err?: Error | null, + result?: LROperation< + protos.google.firestore.admin.v1.IDatabase, + protos.google.firestore.admin.v1.ICreateDatabaseMetadata + > | null + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + } + ); + }); + const operation = (await promise) as LROperation< + protos.google.firestore.admin.v1.IDatabase, + protos.google.firestore.admin.v1.ICreateDatabaseMetadata + >; + const [response] = await operation.promise(); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.createDatabase as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.createDatabase as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes checkCreateDatabaseProgress without error', async () => { - const client = new firestoreadminModule.FirestoreAdminClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const expectedResponse = generateSampleMessage( - new operationsProtos.google.longrunning.Operation() - ); - expectedResponse.name = 'test'; - expectedResponse.response = {type_url: 'url', value: Buffer.from('')}; - expectedResponse.metadata = {type_url: 'url', value: Buffer.from('')} - - client.operationsClient.getOperation = stubSimpleCall(expectedResponse); - const decodedOperation = await client.checkCreateDatabaseProgress(expectedResponse.name); - assert.deepStrictEqual(decodedOperation.name, expectedResponse.name); - assert(decodedOperation.metadata); - assert((client.operationsClient.getOperation as SinonStub).getCall(0)); - }); + it('invokes createDatabase with call error', async () => { + const client = new firestoreadminModule.FirestoreAdminClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.firestore.admin.v1.CreateDatabaseRequest() + ); + const defaultValue1 = getTypeDefaultValue( + '.google.firestore.admin.v1.CreateDatabaseRequest', + ['parent'] + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.createDatabase = stubLongRunningCall( + undefined, + expectedError + ); + await assert.rejects(client.createDatabase(request), expectedError); + const actualRequest = ( + client.innerApiCalls.createDatabase as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.createDatabase as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes checkCreateDatabaseProgress with error', async () => { - const client = new firestoreadminModule.FirestoreAdminClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const expectedError = new Error('expected'); - - client.operationsClient.getOperation = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.checkCreateDatabaseProgress(''), expectedError); - assert((client.operationsClient.getOperation as SinonStub) - .getCall(0)); - }); + it('invokes createDatabase with LRO error', async () => { + const client = new firestoreadminModule.FirestoreAdminClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.firestore.admin.v1.CreateDatabaseRequest() + ); + const defaultValue1 = getTypeDefaultValue( + '.google.firestore.admin.v1.CreateDatabaseRequest', + ['parent'] + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.createDatabase = stubLongRunningCall( + undefined, + undefined, + expectedError + ); + const [operation] = await client.createDatabase(request); + await assert.rejects(operation.promise(), expectedError); + const actualRequest = ( + client.innerApiCalls.createDatabase as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.createDatabase as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); }); - describe('updateDatabase', () => { - it('invokes updateDatabase without error', async () => { - const client = new firestoreadminModule.FirestoreAdminClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.firestore.admin.v1.UpdateDatabaseRequest() - ); - request.database ??= {}; - const defaultValue1 = - getTypeDefaultValue('.google.firestore.admin.v1.UpdateDatabaseRequest', ['database', 'name']); - request.database.name = defaultValue1; - const expectedHeaderRequestParams = `database.name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.longrunning.Operation() - ); - client.innerApiCalls.updateDatabase = stubLongRunningCall(expectedResponse); - const [operation] = await client.updateDatabase(request); - const [response] = await operation.promise(); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.updateDatabase as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.updateDatabase as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes checkCreateDatabaseProgress without error', async () => { + const client = new firestoreadminModule.FirestoreAdminClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const expectedResponse = generateSampleMessage( + new operationsProtos.google.longrunning.Operation() + ); + expectedResponse.name = 'test'; + expectedResponse.response = {type_url: 'url', value: Buffer.from('')}; + expectedResponse.metadata = {type_url: 'url', value: Buffer.from('')}; + + client.operationsClient.getOperation = stubSimpleCall(expectedResponse); + const decodedOperation = await client.checkCreateDatabaseProgress( + expectedResponse.name + ); + assert.deepStrictEqual(decodedOperation.name, expectedResponse.name); + assert(decodedOperation.metadata); + assert((client.operationsClient.getOperation as SinonStub).getCall(0)); + }); - it('invokes updateDatabase without error using callback', async () => { - const client = new firestoreadminModule.FirestoreAdminClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.firestore.admin.v1.UpdateDatabaseRequest() - ); - request.database ??= {}; - const defaultValue1 = - getTypeDefaultValue('.google.firestore.admin.v1.UpdateDatabaseRequest', ['database', 'name']); - request.database.name = defaultValue1; - const expectedHeaderRequestParams = `database.name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.longrunning.Operation() - ); - client.innerApiCalls.updateDatabase = stubLongRunningCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.updateDatabase( - request, - (err?: Error|null, - result?: LROperation|null - ) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const operation = await promise as LROperation; - const [response] = await operation.promise(); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.updateDatabase as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.updateDatabase as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes checkCreateDatabaseProgress with error', async () => { + const client = new firestoreadminModule.FirestoreAdminClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const expectedError = new Error('expected'); + + client.operationsClient.getOperation = stubSimpleCall( + undefined, + expectedError + ); + await assert.rejects( + client.checkCreateDatabaseProgress(''), + expectedError + ); + assert((client.operationsClient.getOperation as SinonStub).getCall(0)); + }); + }); + + describe('updateDatabase', () => { + it('invokes updateDatabase without error', async () => { + const client = new firestoreadminModule.FirestoreAdminClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.firestore.admin.v1.UpdateDatabaseRequest() + ); + request.database ??= {}; + const defaultValue1 = getTypeDefaultValue( + '.google.firestore.admin.v1.UpdateDatabaseRequest', + ['database', 'name'] + ); + request.database.name = defaultValue1; + const expectedHeaderRequestParams = `database.name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.longrunning.Operation() + ); + client.innerApiCalls.updateDatabase = + stubLongRunningCall(expectedResponse); + const [operation] = await client.updateDatabase(request); + const [response] = await operation.promise(); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.updateDatabase as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.updateDatabase as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes updateDatabase with call error', async () => { - const client = new firestoreadminModule.FirestoreAdminClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.firestore.admin.v1.UpdateDatabaseRequest() - ); - request.database ??= {}; - const defaultValue1 = - getTypeDefaultValue('.google.firestore.admin.v1.UpdateDatabaseRequest', ['database', 'name']); - request.database.name = defaultValue1; - const expectedHeaderRequestParams = `database.name=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.updateDatabase = stubLongRunningCall(undefined, expectedError); - await assert.rejects(client.updateDatabase(request), expectedError); - const actualRequest = (client.innerApiCalls.updateDatabase as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.updateDatabase as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes updateDatabase without error using callback', async () => { + const client = new firestoreadminModule.FirestoreAdminClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.firestore.admin.v1.UpdateDatabaseRequest() + ); + request.database ??= {}; + const defaultValue1 = getTypeDefaultValue( + '.google.firestore.admin.v1.UpdateDatabaseRequest', + ['database', 'name'] + ); + request.database.name = defaultValue1; + const expectedHeaderRequestParams = `database.name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.longrunning.Operation() + ); + client.innerApiCalls.updateDatabase = + stubLongRunningCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.updateDatabase( + request, + ( + err?: Error | null, + result?: LROperation< + protos.google.firestore.admin.v1.IDatabase, + protos.google.firestore.admin.v1.IUpdateDatabaseMetadata + > | null + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + } + ); + }); + const operation = (await promise) as LROperation< + protos.google.firestore.admin.v1.IDatabase, + protos.google.firestore.admin.v1.IUpdateDatabaseMetadata + >; + const [response] = await operation.promise(); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.updateDatabase as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.updateDatabase as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes updateDatabase with LRO error', async () => { - const client = new firestoreadminModule.FirestoreAdminClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.firestore.admin.v1.UpdateDatabaseRequest() - ); - request.database ??= {}; - const defaultValue1 = - getTypeDefaultValue('.google.firestore.admin.v1.UpdateDatabaseRequest', ['database', 'name']); - request.database.name = defaultValue1; - const expectedHeaderRequestParams = `database.name=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.updateDatabase = stubLongRunningCall(undefined, undefined, expectedError); - const [operation] = await client.updateDatabase(request); - await assert.rejects(operation.promise(), expectedError); - const actualRequest = (client.innerApiCalls.updateDatabase as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.updateDatabase as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes updateDatabase with call error', async () => { + const client = new firestoreadminModule.FirestoreAdminClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.firestore.admin.v1.UpdateDatabaseRequest() + ); + request.database ??= {}; + const defaultValue1 = getTypeDefaultValue( + '.google.firestore.admin.v1.UpdateDatabaseRequest', + ['database', 'name'] + ); + request.database.name = defaultValue1; + const expectedHeaderRequestParams = `database.name=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.updateDatabase = stubLongRunningCall( + undefined, + expectedError + ); + await assert.rejects(client.updateDatabase(request), expectedError); + const actualRequest = ( + client.innerApiCalls.updateDatabase as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.updateDatabase as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes checkUpdateDatabaseProgress without error', async () => { - const client = new firestoreadminModule.FirestoreAdminClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const expectedResponse = generateSampleMessage( - new operationsProtos.google.longrunning.Operation() - ); - expectedResponse.name = 'test'; - expectedResponse.response = {type_url: 'url', value: Buffer.from('')}; - expectedResponse.metadata = {type_url: 'url', value: Buffer.from('')} - - client.operationsClient.getOperation = stubSimpleCall(expectedResponse); - const decodedOperation = await client.checkUpdateDatabaseProgress(expectedResponse.name); - assert.deepStrictEqual(decodedOperation.name, expectedResponse.name); - assert(decodedOperation.metadata); - assert((client.operationsClient.getOperation as SinonStub).getCall(0)); - }); + it('invokes updateDatabase with LRO error', async () => { + const client = new firestoreadminModule.FirestoreAdminClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.firestore.admin.v1.UpdateDatabaseRequest() + ); + request.database ??= {}; + const defaultValue1 = getTypeDefaultValue( + '.google.firestore.admin.v1.UpdateDatabaseRequest', + ['database', 'name'] + ); + request.database.name = defaultValue1; + const expectedHeaderRequestParams = `database.name=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.updateDatabase = stubLongRunningCall( + undefined, + undefined, + expectedError + ); + const [operation] = await client.updateDatabase(request); + await assert.rejects(operation.promise(), expectedError); + const actualRequest = ( + client.innerApiCalls.updateDatabase as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.updateDatabase as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes checkUpdateDatabaseProgress with error', async () => { - const client = new firestoreadminModule.FirestoreAdminClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const expectedError = new Error('expected'); - - client.operationsClient.getOperation = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.checkUpdateDatabaseProgress(''), expectedError); - assert((client.operationsClient.getOperation as SinonStub) - .getCall(0)); - }); + it('invokes checkUpdateDatabaseProgress without error', async () => { + const client = new firestoreadminModule.FirestoreAdminClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const expectedResponse = generateSampleMessage( + new operationsProtos.google.longrunning.Operation() + ); + expectedResponse.name = 'test'; + expectedResponse.response = {type_url: 'url', value: Buffer.from('')}; + expectedResponse.metadata = {type_url: 'url', value: Buffer.from('')}; + + client.operationsClient.getOperation = stubSimpleCall(expectedResponse); + const decodedOperation = await client.checkUpdateDatabaseProgress( + expectedResponse.name + ); + assert.deepStrictEqual(decodedOperation.name, expectedResponse.name); + assert(decodedOperation.metadata); + assert((client.operationsClient.getOperation as SinonStub).getCall(0)); }); - describe('deleteDatabase', () => { - it('invokes deleteDatabase without error', async () => { - const client = new firestoreadminModule.FirestoreAdminClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.firestore.admin.v1.DeleteDatabaseRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.firestore.admin.v1.DeleteDatabaseRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.longrunning.Operation() - ); - client.innerApiCalls.deleteDatabase = stubLongRunningCall(expectedResponse); - const [operation] = await client.deleteDatabase(request); - const [response] = await operation.promise(); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.deleteDatabase as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.deleteDatabase as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes checkUpdateDatabaseProgress with error', async () => { + const client = new firestoreadminModule.FirestoreAdminClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const expectedError = new Error('expected'); + + client.operationsClient.getOperation = stubSimpleCall( + undefined, + expectedError + ); + await assert.rejects( + client.checkUpdateDatabaseProgress(''), + expectedError + ); + assert((client.operationsClient.getOperation as SinonStub).getCall(0)); + }); + }); + + describe('deleteDatabase', () => { + it('invokes deleteDatabase without error', async () => { + const client = new firestoreadminModule.FirestoreAdminClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.firestore.admin.v1.DeleteDatabaseRequest() + ); + const defaultValue1 = getTypeDefaultValue( + '.google.firestore.admin.v1.DeleteDatabaseRequest', + ['name'] + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.longrunning.Operation() + ); + client.innerApiCalls.deleteDatabase = + stubLongRunningCall(expectedResponse); + const [operation] = await client.deleteDatabase(request); + const [response] = await operation.promise(); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.deleteDatabase as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.deleteDatabase as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes deleteDatabase without error using callback', async () => { - const client = new firestoreadminModule.FirestoreAdminClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.firestore.admin.v1.DeleteDatabaseRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.firestore.admin.v1.DeleteDatabaseRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.longrunning.Operation() - ); - client.innerApiCalls.deleteDatabase = stubLongRunningCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.deleteDatabase( - request, - (err?: Error|null, - result?: LROperation|null - ) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const operation = await promise as LROperation; - const [response] = await operation.promise(); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.deleteDatabase as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.deleteDatabase as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes deleteDatabase without error using callback', async () => { + const client = new firestoreadminModule.FirestoreAdminClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.firestore.admin.v1.DeleteDatabaseRequest() + ); + const defaultValue1 = getTypeDefaultValue( + '.google.firestore.admin.v1.DeleteDatabaseRequest', + ['name'] + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.longrunning.Operation() + ); + client.innerApiCalls.deleteDatabase = + stubLongRunningCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.deleteDatabase( + request, + ( + err?: Error | null, + result?: LROperation< + protos.google.firestore.admin.v1.IDatabase, + protos.google.firestore.admin.v1.IDeleteDatabaseMetadata + > | null + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + } + ); + }); + const operation = (await promise) as LROperation< + protos.google.firestore.admin.v1.IDatabase, + protos.google.firestore.admin.v1.IDeleteDatabaseMetadata + >; + const [response] = await operation.promise(); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.deleteDatabase as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.deleteDatabase as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes deleteDatabase with call error', async () => { - const client = new firestoreadminModule.FirestoreAdminClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.firestore.admin.v1.DeleteDatabaseRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.firestore.admin.v1.DeleteDatabaseRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.deleteDatabase = stubLongRunningCall(undefined, expectedError); - await assert.rejects(client.deleteDatabase(request), expectedError); - const actualRequest = (client.innerApiCalls.deleteDatabase as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.deleteDatabase as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes deleteDatabase with call error', async () => { + const client = new firestoreadminModule.FirestoreAdminClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.firestore.admin.v1.DeleteDatabaseRequest() + ); + const defaultValue1 = getTypeDefaultValue( + '.google.firestore.admin.v1.DeleteDatabaseRequest', + ['name'] + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.deleteDatabase = stubLongRunningCall( + undefined, + expectedError + ); + await assert.rejects(client.deleteDatabase(request), expectedError); + const actualRequest = ( + client.innerApiCalls.deleteDatabase as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.deleteDatabase as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes deleteDatabase with LRO error', async () => { - const client = new firestoreadminModule.FirestoreAdminClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.firestore.admin.v1.DeleteDatabaseRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.firestore.admin.v1.DeleteDatabaseRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.deleteDatabase = stubLongRunningCall(undefined, undefined, expectedError); - const [operation] = await client.deleteDatabase(request); - await assert.rejects(operation.promise(), expectedError); - const actualRequest = (client.innerApiCalls.deleteDatabase as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.deleteDatabase as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes deleteDatabase with LRO error', async () => { + const client = new firestoreadminModule.FirestoreAdminClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.firestore.admin.v1.DeleteDatabaseRequest() + ); + const defaultValue1 = getTypeDefaultValue( + '.google.firestore.admin.v1.DeleteDatabaseRequest', + ['name'] + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.deleteDatabase = stubLongRunningCall( + undefined, + undefined, + expectedError + ); + const [operation] = await client.deleteDatabase(request); + await assert.rejects(operation.promise(), expectedError); + const actualRequest = ( + client.innerApiCalls.deleteDatabase as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.deleteDatabase as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes checkDeleteDatabaseProgress without error', async () => { - const client = new firestoreadminModule.FirestoreAdminClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const expectedResponse = generateSampleMessage( - new operationsProtos.google.longrunning.Operation() - ); - expectedResponse.name = 'test'; - expectedResponse.response = {type_url: 'url', value: Buffer.from('')}; - expectedResponse.metadata = {type_url: 'url', value: Buffer.from('')} - - client.operationsClient.getOperation = stubSimpleCall(expectedResponse); - const decodedOperation = await client.checkDeleteDatabaseProgress(expectedResponse.name); - assert.deepStrictEqual(decodedOperation.name, expectedResponse.name); - assert(decodedOperation.metadata); - assert((client.operationsClient.getOperation as SinonStub).getCall(0)); - }); + it('invokes checkDeleteDatabaseProgress without error', async () => { + const client = new firestoreadminModule.FirestoreAdminClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const expectedResponse = generateSampleMessage( + new operationsProtos.google.longrunning.Operation() + ); + expectedResponse.name = 'test'; + expectedResponse.response = {type_url: 'url', value: Buffer.from('')}; + expectedResponse.metadata = {type_url: 'url', value: Buffer.from('')}; + + client.operationsClient.getOperation = stubSimpleCall(expectedResponse); + const decodedOperation = await client.checkDeleteDatabaseProgress( + expectedResponse.name + ); + assert.deepStrictEqual(decodedOperation.name, expectedResponse.name); + assert(decodedOperation.metadata); + assert((client.operationsClient.getOperation as SinonStub).getCall(0)); + }); - it('invokes checkDeleteDatabaseProgress with error', async () => { - const client = new firestoreadminModule.FirestoreAdminClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const expectedError = new Error('expected'); - - client.operationsClient.getOperation = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.checkDeleteDatabaseProgress(''), expectedError); - assert((client.operationsClient.getOperation as SinonStub) - .getCall(0)); - }); + it('invokes checkDeleteDatabaseProgress with error', async () => { + const client = new firestoreadminModule.FirestoreAdminClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const expectedError = new Error('expected'); + + client.operationsClient.getOperation = stubSimpleCall( + undefined, + expectedError + ); + await assert.rejects( + client.checkDeleteDatabaseProgress(''), + expectedError + ); + assert((client.operationsClient.getOperation as SinonStub).getCall(0)); + }); + }); + + describe('restoreDatabase', () => { + it('invokes restoreDatabase without error', async () => { + const client = new firestoreadminModule.FirestoreAdminClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.firestore.admin.v1.RestoreDatabaseRequest() + ); + const defaultValue1 = getTypeDefaultValue( + '.google.firestore.admin.v1.RestoreDatabaseRequest', + ['parent'] + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.longrunning.Operation() + ); + client.innerApiCalls.restoreDatabase = + stubLongRunningCall(expectedResponse); + const [operation] = await client.restoreDatabase(request); + const [response] = await operation.promise(); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.restoreDatabase as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.restoreDatabase as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); }); - describe('restoreDatabase', () => { - it('invokes restoreDatabase without error', async () => { - const client = new firestoreadminModule.FirestoreAdminClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.firestore.admin.v1.RestoreDatabaseRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.firestore.admin.v1.RestoreDatabaseRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.longrunning.Operation() - ); - client.innerApiCalls.restoreDatabase = stubLongRunningCall(expectedResponse); - const [operation] = await client.restoreDatabase(request); - const [response] = await operation.promise(); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.restoreDatabase as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.restoreDatabase as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes restoreDatabase without error using callback', async () => { + const client = new firestoreadminModule.FirestoreAdminClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.firestore.admin.v1.RestoreDatabaseRequest() + ); + const defaultValue1 = getTypeDefaultValue( + '.google.firestore.admin.v1.RestoreDatabaseRequest', + ['parent'] + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.longrunning.Operation() + ); + client.innerApiCalls.restoreDatabase = + stubLongRunningCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.restoreDatabase( + request, + ( + err?: Error | null, + result?: LROperation< + protos.google.firestore.admin.v1.IDatabase, + protos.google.firestore.admin.v1.IRestoreDatabaseMetadata + > | null + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + } + ); + }); + const operation = (await promise) as LROperation< + protos.google.firestore.admin.v1.IDatabase, + protos.google.firestore.admin.v1.IRestoreDatabaseMetadata + >; + const [response] = await operation.promise(); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.restoreDatabase as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.restoreDatabase as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes restoreDatabase without error using callback', async () => { - const client = new firestoreadminModule.FirestoreAdminClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.firestore.admin.v1.RestoreDatabaseRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.firestore.admin.v1.RestoreDatabaseRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.longrunning.Operation() - ); - client.innerApiCalls.restoreDatabase = stubLongRunningCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.restoreDatabase( - request, - (err?: Error|null, - result?: LROperation|null - ) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const operation = await promise as LROperation; - const [response] = await operation.promise(); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.restoreDatabase as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.restoreDatabase as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes restoreDatabase with call error', async () => { + const client = new firestoreadminModule.FirestoreAdminClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.firestore.admin.v1.RestoreDatabaseRequest() + ); + const defaultValue1 = getTypeDefaultValue( + '.google.firestore.admin.v1.RestoreDatabaseRequest', + ['parent'] + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.restoreDatabase = stubLongRunningCall( + undefined, + expectedError + ); + await assert.rejects(client.restoreDatabase(request), expectedError); + const actualRequest = ( + client.innerApiCalls.restoreDatabase as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.restoreDatabase as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes restoreDatabase with call error', async () => { - const client = new firestoreadminModule.FirestoreAdminClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.firestore.admin.v1.RestoreDatabaseRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.firestore.admin.v1.RestoreDatabaseRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.restoreDatabase = stubLongRunningCall(undefined, expectedError); - await assert.rejects(client.restoreDatabase(request), expectedError); - const actualRequest = (client.innerApiCalls.restoreDatabase as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.restoreDatabase as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes restoreDatabase with LRO error', async () => { + const client = new firestoreadminModule.FirestoreAdminClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.firestore.admin.v1.RestoreDatabaseRequest() + ); + const defaultValue1 = getTypeDefaultValue( + '.google.firestore.admin.v1.RestoreDatabaseRequest', + ['parent'] + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.restoreDatabase = stubLongRunningCall( + undefined, + undefined, + expectedError + ); + const [operation] = await client.restoreDatabase(request); + await assert.rejects(operation.promise(), expectedError); + const actualRequest = ( + client.innerApiCalls.restoreDatabase as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.restoreDatabase as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes restoreDatabase with LRO error', async () => { - const client = new firestoreadminModule.FirestoreAdminClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.firestore.admin.v1.RestoreDatabaseRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.firestore.admin.v1.RestoreDatabaseRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.restoreDatabase = stubLongRunningCall(undefined, undefined, expectedError); - const [operation] = await client.restoreDatabase(request); - await assert.rejects(operation.promise(), expectedError); - const actualRequest = (client.innerApiCalls.restoreDatabase as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.restoreDatabase as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes checkRestoreDatabaseProgress without error', async () => { + const client = new firestoreadminModule.FirestoreAdminClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const expectedResponse = generateSampleMessage( + new operationsProtos.google.longrunning.Operation() + ); + expectedResponse.name = 'test'; + expectedResponse.response = {type_url: 'url', value: Buffer.from('')}; + expectedResponse.metadata = {type_url: 'url', value: Buffer.from('')}; + + client.operationsClient.getOperation = stubSimpleCall(expectedResponse); + const decodedOperation = await client.checkRestoreDatabaseProgress( + expectedResponse.name + ); + assert.deepStrictEqual(decodedOperation.name, expectedResponse.name); + assert(decodedOperation.metadata); + assert((client.operationsClient.getOperation as SinonStub).getCall(0)); + }); - it('invokes checkRestoreDatabaseProgress without error', async () => { - const client = new firestoreadminModule.FirestoreAdminClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const expectedResponse = generateSampleMessage( - new operationsProtos.google.longrunning.Operation() - ); - expectedResponse.name = 'test'; - expectedResponse.response = {type_url: 'url', value: Buffer.from('')}; - expectedResponse.metadata = {type_url: 'url', value: Buffer.from('')} - - client.operationsClient.getOperation = stubSimpleCall(expectedResponse); - const decodedOperation = await client.checkRestoreDatabaseProgress(expectedResponse.name); - assert.deepStrictEqual(decodedOperation.name, expectedResponse.name); - assert(decodedOperation.metadata); - assert((client.operationsClient.getOperation as SinonStub).getCall(0)); - }); + it('invokes checkRestoreDatabaseProgress with error', async () => { + const client = new firestoreadminModule.FirestoreAdminClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const expectedError = new Error('expected'); + + client.operationsClient.getOperation = stubSimpleCall( + undefined, + expectedError + ); + await assert.rejects( + client.checkRestoreDatabaseProgress(''), + expectedError + ); + assert((client.operationsClient.getOperation as SinonStub).getCall(0)); + }); + }); + + describe('listIndexes', () => { + it('invokes listIndexes without error', async () => { + const client = new firestoreadminModule.FirestoreAdminClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.firestore.admin.v1.ListIndexesRequest() + ); + const defaultValue1 = getTypeDefaultValue( + '.google.firestore.admin.v1.ListIndexesRequest', + ['parent'] + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedResponse = [ + generateSampleMessage(new protos.google.firestore.admin.v1.Index()), + generateSampleMessage(new protos.google.firestore.admin.v1.Index()), + generateSampleMessage(new protos.google.firestore.admin.v1.Index()), + ]; + client.innerApiCalls.listIndexes = stubSimpleCall(expectedResponse); + const [response] = await client.listIndexes(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.listIndexes as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.listIndexes as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes checkRestoreDatabaseProgress with error', async () => { - const client = new firestoreadminModule.FirestoreAdminClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const expectedError = new Error('expected'); - - client.operationsClient.getOperation = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.checkRestoreDatabaseProgress(''), expectedError); - assert((client.operationsClient.getOperation as SinonStub) - .getCall(0)); - }); + it('invokes listIndexes without error using callback', async () => { + const client = new firestoreadminModule.FirestoreAdminClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.firestore.admin.v1.ListIndexesRequest() + ); + const defaultValue1 = getTypeDefaultValue( + '.google.firestore.admin.v1.ListIndexesRequest', + ['parent'] + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedResponse = [ + generateSampleMessage(new protos.google.firestore.admin.v1.Index()), + generateSampleMessage(new protos.google.firestore.admin.v1.Index()), + generateSampleMessage(new protos.google.firestore.admin.v1.Index()), + ]; + client.innerApiCalls.listIndexes = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.listIndexes( + request, + ( + err?: Error | null, + result?: protos.google.firestore.admin.v1.IIndex[] | null + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + } + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.listIndexes as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.listIndexes as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); }); - describe('listIndexes', () => { - it('invokes listIndexes without error', async () => { - const client = new firestoreadminModule.FirestoreAdminClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.firestore.admin.v1.ListIndexesRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.firestore.admin.v1.ListIndexesRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`;const expectedResponse = [ - generateSampleMessage(new protos.google.firestore.admin.v1.Index()), - generateSampleMessage(new protos.google.firestore.admin.v1.Index()), - generateSampleMessage(new protos.google.firestore.admin.v1.Index()), - ]; - client.innerApiCalls.listIndexes = stubSimpleCall(expectedResponse); - const [response] = await client.listIndexes(request); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.listIndexes as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.listIndexes as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes listIndexes with error', async () => { + const client = new firestoreadminModule.FirestoreAdminClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.firestore.admin.v1.ListIndexesRequest() + ); + const defaultValue1 = getTypeDefaultValue( + '.google.firestore.admin.v1.ListIndexesRequest', + ['parent'] + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.listIndexes = stubSimpleCall( + undefined, + expectedError + ); + await assert.rejects(client.listIndexes(request), expectedError); + const actualRequest = ( + client.innerApiCalls.listIndexes as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.listIndexes as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes listIndexes without error using callback', async () => { - const client = new firestoreadminModule.FirestoreAdminClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.firestore.admin.v1.ListIndexesRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.firestore.admin.v1.ListIndexesRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`;const expectedResponse = [ - generateSampleMessage(new protos.google.firestore.admin.v1.Index()), - generateSampleMessage(new protos.google.firestore.admin.v1.Index()), - generateSampleMessage(new protos.google.firestore.admin.v1.Index()), - ]; - client.innerApiCalls.listIndexes = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.listIndexes( - request, - (err?: Error|null, result?: protos.google.firestore.admin.v1.IIndex[]|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.listIndexes as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.listIndexes as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes listIndexesStream without error', async () => { + const client = new firestoreadminModule.FirestoreAdminClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.firestore.admin.v1.ListIndexesRequest() + ); + const defaultValue1 = getTypeDefaultValue( + '.google.firestore.admin.v1.ListIndexesRequest', + ['parent'] + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedResponse = [ + generateSampleMessage(new protos.google.firestore.admin.v1.Index()), + generateSampleMessage(new protos.google.firestore.admin.v1.Index()), + generateSampleMessage(new protos.google.firestore.admin.v1.Index()), + ]; + client.descriptors.page.listIndexes.createStream = + stubPageStreamingCall(expectedResponse); + const stream = client.listIndexesStream(request); + const promise = new Promise((resolve, reject) => { + const responses: protos.google.firestore.admin.v1.Index[] = []; + stream.on( + 'data', + (response: protos.google.firestore.admin.v1.Index) => { + responses.push(response); + } + ); + stream.on('end', () => { + resolve(responses); + }); + stream.on('error', (err: Error) => { + reject(err); + }); + }); + const responses = await promise; + assert.deepStrictEqual(responses, expectedResponse); + assert( + (client.descriptors.page.listIndexes.createStream as SinonStub) + .getCall(0) + .calledWith(client.innerApiCalls.listIndexes, request) + ); + assert( + (client.descriptors.page.listIndexes.createStream as SinonStub) + .getCall(0) + .args[2].otherArgs.headers[ + 'x-goog-request-params' + ].includes(expectedHeaderRequestParams) + ); + }); - it('invokes listIndexes with error', async () => { - const client = new firestoreadminModule.FirestoreAdminClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.firestore.admin.v1.ListIndexesRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.firestore.admin.v1.ListIndexesRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.listIndexes = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.listIndexes(request), expectedError); - const actualRequest = (client.innerApiCalls.listIndexes as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.listIndexes as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes listIndexesStream with error', async () => { + const client = new firestoreadminModule.FirestoreAdminClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.firestore.admin.v1.ListIndexesRequest() + ); + const defaultValue1 = getTypeDefaultValue( + '.google.firestore.admin.v1.ListIndexesRequest', + ['parent'] + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.descriptors.page.listIndexes.createStream = stubPageStreamingCall( + undefined, + expectedError + ); + const stream = client.listIndexesStream(request); + const promise = new Promise((resolve, reject) => { + const responses: protos.google.firestore.admin.v1.Index[] = []; + stream.on( + 'data', + (response: protos.google.firestore.admin.v1.Index) => { + responses.push(response); + } + ); + stream.on('end', () => { + resolve(responses); + }); + stream.on('error', (err: Error) => { + reject(err); + }); + }); + await assert.rejects(promise, expectedError); + assert( + (client.descriptors.page.listIndexes.createStream as SinonStub) + .getCall(0) + .calledWith(client.innerApiCalls.listIndexes, request) + ); + assert( + (client.descriptors.page.listIndexes.createStream as SinonStub) + .getCall(0) + .args[2].otherArgs.headers[ + 'x-goog-request-params' + ].includes(expectedHeaderRequestParams) + ); + }); - it('invokes listIndexesStream without error', async () => { - const client = new firestoreadminModule.FirestoreAdminClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.firestore.admin.v1.ListIndexesRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.firestore.admin.v1.ListIndexesRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedResponse = [ - generateSampleMessage(new protos.google.firestore.admin.v1.Index()), - generateSampleMessage(new protos.google.firestore.admin.v1.Index()), - generateSampleMessage(new protos.google.firestore.admin.v1.Index()), - ]; - client.descriptors.page.listIndexes.createStream = stubPageStreamingCall(expectedResponse); - const stream = client.listIndexesStream(request); - const promise = new Promise((resolve, reject) => { - const responses: protos.google.firestore.admin.v1.Index[] = []; - stream.on('data', (response: protos.google.firestore.admin.v1.Index) => { - responses.push(response); - }); - stream.on('end', () => { - resolve(responses); - }); - stream.on('error', (err: Error) => { - reject(err); - }); - }); - const responses = await promise; - assert.deepStrictEqual(responses, expectedResponse); - assert((client.descriptors.page.listIndexes.createStream as SinonStub) - .getCall(0).calledWith(client.innerApiCalls.listIndexes, request)); - assert( - (client.descriptors.page.listIndexes.createStream as SinonStub) - .getCall(0).args[2].otherArgs.headers['x-goog-request-params'].includes( - expectedHeaderRequestParams - ) - ); - }); + it('uses async iteration with listIndexes without error', async () => { + const client = new firestoreadminModule.FirestoreAdminClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.firestore.admin.v1.ListIndexesRequest() + ); + const defaultValue1 = getTypeDefaultValue( + '.google.firestore.admin.v1.ListIndexesRequest', + ['parent'] + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedResponse = [ + generateSampleMessage(new protos.google.firestore.admin.v1.Index()), + generateSampleMessage(new protos.google.firestore.admin.v1.Index()), + generateSampleMessage(new protos.google.firestore.admin.v1.Index()), + ]; + client.descriptors.page.listIndexes.asyncIterate = + stubAsyncIterationCall(expectedResponse); + const responses: protos.google.firestore.admin.v1.IIndex[] = []; + const iterable = client.listIndexesAsync(request); + for await (const resource of iterable) { + responses.push(resource!); + } + assert.deepStrictEqual(responses, expectedResponse); + assert.deepStrictEqual( + (client.descriptors.page.listIndexes.asyncIterate as SinonStub).getCall( + 0 + ).args[1], + request + ); + assert( + (client.descriptors.page.listIndexes.asyncIterate as SinonStub) + .getCall(0) + .args[2].otherArgs.headers[ + 'x-goog-request-params' + ].includes(expectedHeaderRequestParams) + ); + }); - it('invokes listIndexesStream with error', async () => { - const client = new firestoreadminModule.FirestoreAdminClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.firestore.admin.v1.ListIndexesRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.firestore.admin.v1.ListIndexesRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.descriptors.page.listIndexes.createStream = stubPageStreamingCall(undefined, expectedError); - const stream = client.listIndexesStream(request); - const promise = new Promise((resolve, reject) => { - const responses: protos.google.firestore.admin.v1.Index[] = []; - stream.on('data', (response: protos.google.firestore.admin.v1.Index) => { - responses.push(response); - }); - stream.on('end', () => { - resolve(responses); - }); - stream.on('error', (err: Error) => { - reject(err); - }); - }); - await assert.rejects(promise, expectedError); - assert((client.descriptors.page.listIndexes.createStream as SinonStub) - .getCall(0).calledWith(client.innerApiCalls.listIndexes, request)); - assert( - (client.descriptors.page.listIndexes.createStream as SinonStub) - .getCall(0).args[2].otherArgs.headers['x-goog-request-params'].includes( - expectedHeaderRequestParams - ) - ); - }); + it('uses async iteration with listIndexes with error', async () => { + const client = new firestoreadminModule.FirestoreAdminClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.firestore.admin.v1.ListIndexesRequest() + ); + const defaultValue1 = getTypeDefaultValue( + '.google.firestore.admin.v1.ListIndexesRequest', + ['parent'] + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.descriptors.page.listIndexes.asyncIterate = stubAsyncIterationCall( + undefined, + expectedError + ); + const iterable = client.listIndexesAsync(request); + await assert.rejects(async () => { + const responses: protos.google.firestore.admin.v1.IIndex[] = []; + for await (const resource of iterable) { + responses.push(resource!); + } + }); + assert.deepStrictEqual( + (client.descriptors.page.listIndexes.asyncIterate as SinonStub).getCall( + 0 + ).args[1], + request + ); + assert( + (client.descriptors.page.listIndexes.asyncIterate as SinonStub) + .getCall(0) + .args[2].otherArgs.headers[ + 'x-goog-request-params' + ].includes(expectedHeaderRequestParams) + ); + }); + }); + + describe('listFields', () => { + it('invokes listFields without error', async () => { + const client = new firestoreadminModule.FirestoreAdminClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.firestore.admin.v1.ListFieldsRequest() + ); + const defaultValue1 = getTypeDefaultValue( + '.google.firestore.admin.v1.ListFieldsRequest', + ['parent'] + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedResponse = [ + generateSampleMessage(new protos.google.firestore.admin.v1.Field()), + generateSampleMessage(new protos.google.firestore.admin.v1.Field()), + generateSampleMessage(new protos.google.firestore.admin.v1.Field()), + ]; + client.innerApiCalls.listFields = stubSimpleCall(expectedResponse); + const [response] = await client.listFields(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.listFields as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.listFields as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('uses async iteration with listIndexes without error', async () => { - const client = new firestoreadminModule.FirestoreAdminClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.firestore.admin.v1.ListIndexesRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.firestore.admin.v1.ListIndexesRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedResponse = [ - generateSampleMessage(new protos.google.firestore.admin.v1.Index()), - generateSampleMessage(new protos.google.firestore.admin.v1.Index()), - generateSampleMessage(new protos.google.firestore.admin.v1.Index()), - ]; - client.descriptors.page.listIndexes.asyncIterate = stubAsyncIterationCall(expectedResponse); - const responses: protos.google.firestore.admin.v1.IIndex[] = []; - const iterable = client.listIndexesAsync(request); - for await (const resource of iterable) { - responses.push(resource!); + it('invokes listFields without error using callback', async () => { + const client = new firestoreadminModule.FirestoreAdminClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.firestore.admin.v1.ListFieldsRequest() + ); + const defaultValue1 = getTypeDefaultValue( + '.google.firestore.admin.v1.ListFieldsRequest', + ['parent'] + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedResponse = [ + generateSampleMessage(new protos.google.firestore.admin.v1.Field()), + generateSampleMessage(new protos.google.firestore.admin.v1.Field()), + generateSampleMessage(new protos.google.firestore.admin.v1.Field()), + ]; + client.innerApiCalls.listFields = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.listFields( + request, + ( + err?: Error | null, + result?: protos.google.firestore.admin.v1.IField[] | null + ) => { + if (err) { + reject(err); + } else { + resolve(result); } - assert.deepStrictEqual(responses, expectedResponse); - assert.deepStrictEqual( - (client.descriptors.page.listIndexes.asyncIterate as SinonStub) - .getCall(0).args[1], request); - assert( - (client.descriptors.page.listIndexes.asyncIterate as SinonStub) - .getCall(0).args[2].otherArgs.headers['x-goog-request-params'].includes( - expectedHeaderRequestParams - ) - ); - }); - - it('uses async iteration with listIndexes with error', async () => { - const client = new firestoreadminModule.FirestoreAdminClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.firestore.admin.v1.ListIndexesRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.firestore.admin.v1.ListIndexesRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.descriptors.page.listIndexes.asyncIterate = stubAsyncIterationCall(undefined, expectedError); - const iterable = client.listIndexesAsync(request); - await assert.rejects(async () => { - const responses: protos.google.firestore.admin.v1.IIndex[] = []; - for await (const resource of iterable) { - responses.push(resource!); - } - }); - assert.deepStrictEqual( - (client.descriptors.page.listIndexes.asyncIterate as SinonStub) - .getCall(0).args[1], request); - assert( - (client.descriptors.page.listIndexes.asyncIterate as SinonStub) - .getCall(0).args[2].otherArgs.headers['x-goog-request-params'].includes( - expectedHeaderRequestParams - ) - ); - }); + } + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.listFields as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.listFields as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); }); - describe('listFields', () => { - it('invokes listFields without error', async () => { - const client = new firestoreadminModule.FirestoreAdminClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.firestore.admin.v1.ListFieldsRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.firestore.admin.v1.ListFieldsRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`;const expectedResponse = [ - generateSampleMessage(new protos.google.firestore.admin.v1.Field()), - generateSampleMessage(new protos.google.firestore.admin.v1.Field()), - generateSampleMessage(new protos.google.firestore.admin.v1.Field()), - ]; - client.innerApiCalls.listFields = stubSimpleCall(expectedResponse); - const [response] = await client.listFields(request); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.listFields as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.listFields as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes listFields without error using callback', async () => { - const client = new firestoreadminModule.FirestoreAdminClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.firestore.admin.v1.ListFieldsRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.firestore.admin.v1.ListFieldsRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`;const expectedResponse = [ - generateSampleMessage(new protos.google.firestore.admin.v1.Field()), - generateSampleMessage(new protos.google.firestore.admin.v1.Field()), - generateSampleMessage(new protos.google.firestore.admin.v1.Field()), - ]; - client.innerApiCalls.listFields = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.listFields( - request, - (err?: Error|null, result?: protos.google.firestore.admin.v1.IField[]|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.listFields as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.listFields as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes listFields with error', async () => { + const client = new firestoreadminModule.FirestoreAdminClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.firestore.admin.v1.ListFieldsRequest() + ); + const defaultValue1 = getTypeDefaultValue( + '.google.firestore.admin.v1.ListFieldsRequest', + ['parent'] + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.listFields = stubSimpleCall( + undefined, + expectedError + ); + await assert.rejects(client.listFields(request), expectedError); + const actualRequest = ( + client.innerApiCalls.listFields as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.listFields as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes listFields with error', async () => { - const client = new firestoreadminModule.FirestoreAdminClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.firestore.admin.v1.ListFieldsRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.firestore.admin.v1.ListFieldsRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.listFields = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.listFields(request), expectedError); - const actualRequest = (client.innerApiCalls.listFields as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.listFields as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes listFieldsStream without error', async () => { + const client = new firestoreadminModule.FirestoreAdminClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.firestore.admin.v1.ListFieldsRequest() + ); + const defaultValue1 = getTypeDefaultValue( + '.google.firestore.admin.v1.ListFieldsRequest', + ['parent'] + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedResponse = [ + generateSampleMessage(new protos.google.firestore.admin.v1.Field()), + generateSampleMessage(new protos.google.firestore.admin.v1.Field()), + generateSampleMessage(new protos.google.firestore.admin.v1.Field()), + ]; + client.descriptors.page.listFields.createStream = + stubPageStreamingCall(expectedResponse); + const stream = client.listFieldsStream(request); + const promise = new Promise((resolve, reject) => { + const responses: protos.google.firestore.admin.v1.Field[] = []; + stream.on( + 'data', + (response: protos.google.firestore.admin.v1.Field) => { + responses.push(response); + } + ); + stream.on('end', () => { + resolve(responses); + }); + stream.on('error', (err: Error) => { + reject(err); + }); + }); + const responses = await promise; + assert.deepStrictEqual(responses, expectedResponse); + assert( + (client.descriptors.page.listFields.createStream as SinonStub) + .getCall(0) + .calledWith(client.innerApiCalls.listFields, request) + ); + assert( + (client.descriptors.page.listFields.createStream as SinonStub) + .getCall(0) + .args[2].otherArgs.headers[ + 'x-goog-request-params' + ].includes(expectedHeaderRequestParams) + ); + }); - it('invokes listFieldsStream without error', async () => { - const client = new firestoreadminModule.FirestoreAdminClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.firestore.admin.v1.ListFieldsRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.firestore.admin.v1.ListFieldsRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedResponse = [ - generateSampleMessage(new protos.google.firestore.admin.v1.Field()), - generateSampleMessage(new protos.google.firestore.admin.v1.Field()), - generateSampleMessage(new protos.google.firestore.admin.v1.Field()), - ]; - client.descriptors.page.listFields.createStream = stubPageStreamingCall(expectedResponse); - const stream = client.listFieldsStream(request); - const promise = new Promise((resolve, reject) => { - const responses: protos.google.firestore.admin.v1.Field[] = []; - stream.on('data', (response: protos.google.firestore.admin.v1.Field) => { - responses.push(response); - }); - stream.on('end', () => { - resolve(responses); - }); - stream.on('error', (err: Error) => { - reject(err); - }); - }); - const responses = await promise; - assert.deepStrictEqual(responses, expectedResponse); - assert((client.descriptors.page.listFields.createStream as SinonStub) - .getCall(0).calledWith(client.innerApiCalls.listFields, request)); - assert( - (client.descriptors.page.listFields.createStream as SinonStub) - .getCall(0).args[2].otherArgs.headers['x-goog-request-params'].includes( - expectedHeaderRequestParams - ) - ); - }); + it('invokes listFieldsStream with error', async () => { + const client = new firestoreadminModule.FirestoreAdminClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.firestore.admin.v1.ListFieldsRequest() + ); + const defaultValue1 = getTypeDefaultValue( + '.google.firestore.admin.v1.ListFieldsRequest', + ['parent'] + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.descriptors.page.listFields.createStream = stubPageStreamingCall( + undefined, + expectedError + ); + const stream = client.listFieldsStream(request); + const promise = new Promise((resolve, reject) => { + const responses: protos.google.firestore.admin.v1.Field[] = []; + stream.on( + 'data', + (response: protos.google.firestore.admin.v1.Field) => { + responses.push(response); + } + ); + stream.on('end', () => { + resolve(responses); + }); + stream.on('error', (err: Error) => { + reject(err); + }); + }); + await assert.rejects(promise, expectedError); + assert( + (client.descriptors.page.listFields.createStream as SinonStub) + .getCall(0) + .calledWith(client.innerApiCalls.listFields, request) + ); + assert( + (client.descriptors.page.listFields.createStream as SinonStub) + .getCall(0) + .args[2].otherArgs.headers[ + 'x-goog-request-params' + ].includes(expectedHeaderRequestParams) + ); + }); - it('invokes listFieldsStream with error', async () => { - const client = new firestoreadminModule.FirestoreAdminClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.firestore.admin.v1.ListFieldsRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.firestore.admin.v1.ListFieldsRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.descriptors.page.listFields.createStream = stubPageStreamingCall(undefined, expectedError); - const stream = client.listFieldsStream(request); - const promise = new Promise((resolve, reject) => { - const responses: protos.google.firestore.admin.v1.Field[] = []; - stream.on('data', (response: protos.google.firestore.admin.v1.Field) => { - responses.push(response); - }); - stream.on('end', () => { - resolve(responses); - }); - stream.on('error', (err: Error) => { - reject(err); - }); - }); - await assert.rejects(promise, expectedError); - assert((client.descriptors.page.listFields.createStream as SinonStub) - .getCall(0).calledWith(client.innerApiCalls.listFields, request)); - assert( - (client.descriptors.page.listFields.createStream as SinonStub) - .getCall(0).args[2].otherArgs.headers['x-goog-request-params'].includes( - expectedHeaderRequestParams - ) - ); - }); + it('uses async iteration with listFields without error', async () => { + const client = new firestoreadminModule.FirestoreAdminClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.firestore.admin.v1.ListFieldsRequest() + ); + const defaultValue1 = getTypeDefaultValue( + '.google.firestore.admin.v1.ListFieldsRequest', + ['parent'] + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedResponse = [ + generateSampleMessage(new protos.google.firestore.admin.v1.Field()), + generateSampleMessage(new protos.google.firestore.admin.v1.Field()), + generateSampleMessage(new protos.google.firestore.admin.v1.Field()), + ]; + client.descriptors.page.listFields.asyncIterate = + stubAsyncIterationCall(expectedResponse); + const responses: protos.google.firestore.admin.v1.IField[] = []; + const iterable = client.listFieldsAsync(request); + for await (const resource of iterable) { + responses.push(resource!); + } + assert.deepStrictEqual(responses, expectedResponse); + assert.deepStrictEqual( + (client.descriptors.page.listFields.asyncIterate as SinonStub).getCall( + 0 + ).args[1], + request + ); + assert( + (client.descriptors.page.listFields.asyncIterate as SinonStub) + .getCall(0) + .args[2].otherArgs.headers[ + 'x-goog-request-params' + ].includes(expectedHeaderRequestParams) + ); + }); - it('uses async iteration with listFields without error', async () => { - const client = new firestoreadminModule.FirestoreAdminClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.firestore.admin.v1.ListFieldsRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.firestore.admin.v1.ListFieldsRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedResponse = [ - generateSampleMessage(new protos.google.firestore.admin.v1.Field()), - generateSampleMessage(new protos.google.firestore.admin.v1.Field()), - generateSampleMessage(new protos.google.firestore.admin.v1.Field()), - ]; - client.descriptors.page.listFields.asyncIterate = stubAsyncIterationCall(expectedResponse); - const responses: protos.google.firestore.admin.v1.IField[] = []; - const iterable = client.listFieldsAsync(request); - for await (const resource of iterable) { - responses.push(resource!); + it('uses async iteration with listFields with error', async () => { + const client = new firestoreadminModule.FirestoreAdminClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.firestore.admin.v1.ListFieldsRequest() + ); + const defaultValue1 = getTypeDefaultValue( + '.google.firestore.admin.v1.ListFieldsRequest', + ['parent'] + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.descriptors.page.listFields.asyncIterate = stubAsyncIterationCall( + undefined, + expectedError + ); + const iterable = client.listFieldsAsync(request); + await assert.rejects(async () => { + const responses: protos.google.firestore.admin.v1.IField[] = []; + for await (const resource of iterable) { + responses.push(resource!); + } + }); + assert.deepStrictEqual( + (client.descriptors.page.listFields.asyncIterate as SinonStub).getCall( + 0 + ).args[1], + request + ); + assert( + (client.descriptors.page.listFields.asyncIterate as SinonStub) + .getCall(0) + .args[2].otherArgs.headers[ + 'x-goog-request-params' + ].includes(expectedHeaderRequestParams) + ); + }); + }); + describe('getLocation', () => { + it('invokes getLocation without error', async () => { + const client = new firestoreadminModule.FirestoreAdminClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new LocationProtos.google.cloud.location.GetLocationRequest() + ); + request.name = ''; + const expectedHeaderRequestParams = 'name='; + const expectedOptions = { + otherArgs: { + headers: { + 'x-goog-request-params': expectedHeaderRequestParams, + }, + }, + }; + const expectedResponse = generateSampleMessage( + new LocationProtos.google.cloud.location.Location() + ); + client.locationsClient.getLocation = stubSimpleCall(expectedResponse); + const response = await client.getLocation(request, expectedOptions); + assert.deepStrictEqual(response, [expectedResponse]); + assert( + (client.locationsClient.getLocation as SinonStub) + .getCall(0) + .calledWith(request, expectedOptions, undefined) + ); + }); + it('invokes getLocation without error using callback', async () => { + const client = new firestoreadminModule.FirestoreAdminClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new LocationProtos.google.cloud.location.GetLocationRequest() + ); + request.name = ''; + const expectedHeaderRequestParams = 'name='; + const expectedOptions = { + otherArgs: { + headers: { + 'x-goog-request-params': expectedHeaderRequestParams, + }, + }, + }; + const expectedResponse = generateSampleMessage( + new LocationProtos.google.cloud.location.Location() + ); + client.locationsClient.getLocation = sinon + .stub() + .callsArgWith(2, null, expectedResponse); + const promise = new Promise((resolve, reject) => { + client.getLocation( + request, + expectedOptions, + ( + err?: Error | null, + result?: LocationProtos.google.cloud.location.ILocation | null + ) => { + if (err) { + reject(err); + } else { + resolve(result); } - assert.deepStrictEqual(responses, expectedResponse); - assert.deepStrictEqual( - (client.descriptors.page.listFields.asyncIterate as SinonStub) - .getCall(0).args[1], request); - assert( - (client.descriptors.page.listFields.asyncIterate as SinonStub) - .getCall(0).args[2].otherArgs.headers['x-goog-request-params'].includes( - expectedHeaderRequestParams - ) - ); - }); - - it('uses async iteration with listFields with error', async () => { - const client = new firestoreadminModule.FirestoreAdminClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.firestore.admin.v1.ListFieldsRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.firestore.admin.v1.ListFieldsRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.descriptors.page.listFields.asyncIterate = stubAsyncIterationCall(undefined, expectedError); - const iterable = client.listFieldsAsync(request); - await assert.rejects(async () => { - const responses: protos.google.firestore.admin.v1.IField[] = []; - for await (const resource of iterable) { - responses.push(resource!); - } - }); - assert.deepStrictEqual( - (client.descriptors.page.listFields.asyncIterate as SinonStub) - .getCall(0).args[1], request); - assert( - (client.descriptors.page.listFields.asyncIterate as SinonStub) - .getCall(0).args[2].otherArgs.headers['x-goog-request-params'].includes( - expectedHeaderRequestParams - ) - ); - }); + } + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + assert((client.locationsClient.getLocation as SinonStub).getCall(0)); }); - describe('getLocation', () => { - it('invokes getLocation without error', async () => { - const client = new firestoreadminModule.FirestoreAdminClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new LocationProtos.google.cloud.location.GetLocationRequest() - ); - request.name = ''; - const expectedHeaderRequestParams = 'name='; - const expectedOptions = { - otherArgs: { - headers: { - 'x-goog-request-params': expectedHeaderRequestParams, - }, - }, - }; - const expectedResponse = generateSampleMessage( - new LocationProtos.google.cloud.location.Location() - ); - client.locationsClient.getLocation = stubSimpleCall(expectedResponse); - const response = await client.getLocation(request, expectedOptions); - assert.deepStrictEqual(response, [expectedResponse]); - assert((client.locationsClient.getLocation as SinonStub) - .getCall(0).calledWith(request, expectedOptions, undefined)); - }); - it('invokes getLocation without error using callback', async () => { - const client = new firestoreadminModule.FirestoreAdminClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new LocationProtos.google.cloud.location.GetLocationRequest() - ); - request.name = ''; - const expectedHeaderRequestParams = 'name='; - const expectedOptions = { - otherArgs: { - headers: { - 'x-goog-request-params': expectedHeaderRequestParams, - }, - }, - }; - const expectedResponse = generateSampleMessage( - new LocationProtos.google.cloud.location.Location() - ); - client.locationsClient.getLocation = sinon.stub().callsArgWith(2, null, expectedResponse); - const promise = new Promise((resolve, reject) => { - client.getLocation( - request, - expectedOptions, - ( - err?: Error | null, - result?: LocationProtos.google.cloud.location.ILocation | null - ) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - assert((client.locationsClient.getLocation as SinonStub) - .getCall(0)); - }); - it('invokes getLocation with error', async () => { - const client = new firestoreadminModule.FirestoreAdminClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new LocationProtos.google.cloud.location.GetLocationRequest() - ); - request.name = ''; - const expectedHeaderRequestParams = 'name='; - const expectedOptions = { - otherArgs: { - headers: { - 'x-goog-request-params': expectedHeaderRequestParams, - }, - }, - }; - const expectedError = new Error('expected'); - client.locationsClient.getLocation = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.getLocation(request, expectedOptions), expectedError); - assert((client.locationsClient.getLocation as SinonStub) - .getCall(0).calledWith(request, expectedOptions, undefined)); - }); + it('invokes getLocation with error', async () => { + const client = new firestoreadminModule.FirestoreAdminClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new LocationProtos.google.cloud.location.GetLocationRequest() + ); + request.name = ''; + const expectedHeaderRequestParams = 'name='; + const expectedOptions = { + otherArgs: { + headers: { + 'x-goog-request-params': expectedHeaderRequestParams, + }, + }, + }; + const expectedError = new Error('expected'); + client.locationsClient.getLocation = stubSimpleCall( + undefined, + expectedError + ); + await assert.rejects( + client.getLocation(request, expectedOptions), + expectedError + ); + assert( + (client.locationsClient.getLocation as SinonStub) + .getCall(0) + .calledWith(request, expectedOptions, undefined) + ); + }); + }); + describe('listLocationsAsync', () => { + it('uses async iteration with listLocations without error', async () => { + const client = new firestoreadminModule.FirestoreAdminClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new LocationProtos.google.cloud.location.ListLocationsRequest() + ); + request.name = ''; + const expectedHeaderRequestParams = 'name='; + const expectedResponse = [ + generateSampleMessage( + new LocationProtos.google.cloud.location.Location() + ), + generateSampleMessage( + new LocationProtos.google.cloud.location.Location() + ), + generateSampleMessage( + new LocationProtos.google.cloud.location.Location() + ), + ]; + client.locationsClient.descriptors.page.listLocations.asyncIterate = + stubAsyncIterationCall(expectedResponse); + const responses: LocationProtos.google.cloud.location.ILocation[] = []; + const iterable = client.listLocationsAsync(request); + for await (const resource of iterable) { + responses.push(resource!); + } + assert.deepStrictEqual(responses, expectedResponse); + assert.deepStrictEqual( + ( + client.locationsClient.descriptors.page.listLocations + .asyncIterate as SinonStub + ).getCall(0).args[1], + request + ); + assert( + ( + client.locationsClient.descriptors.page.listLocations + .asyncIterate as SinonStub + ) + .getCall(0) + .args[2].otherArgs.headers['x-goog-request-params'].includes( + expectedHeaderRequestParams + ) + ); + }); + it('uses async iteration with listLocations with error', async () => { + const client = new firestoreadminModule.FirestoreAdminClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new LocationProtos.google.cloud.location.ListLocationsRequest() + ); + request.name = ''; + const expectedHeaderRequestParams = 'name='; + const expectedError = new Error('expected'); + client.locationsClient.descriptors.page.listLocations.asyncIterate = + stubAsyncIterationCall(undefined, expectedError); + const iterable = client.listLocationsAsync(request); + await assert.rejects(async () => { + const responses: LocationProtos.google.cloud.location.ILocation[] = []; + for await (const resource of iterable) { + responses.push(resource!); + } + }); + assert.deepStrictEqual( + ( + client.locationsClient.descriptors.page.listLocations + .asyncIterate as SinonStub + ).getCall(0).args[1], + request + ); + assert( + ( + client.locationsClient.descriptors.page.listLocations + .asyncIterate as SinonStub + ) + .getCall(0) + .args[2].otherArgs.headers['x-goog-request-params'].includes( + expectedHeaderRequestParams + ) + ); + }); + }); + describe('getOperation', () => { + it('invokes getOperation without error', async () => { + const client = new firestoreadminModule.FirestoreAdminClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new operationsProtos.google.longrunning.GetOperationRequest() + ); + const expectedResponse = generateSampleMessage( + new operationsProtos.google.longrunning.Operation() + ); + client.operationsClient.getOperation = stubSimpleCall(expectedResponse); + const response = await client.getOperation(request); + assert.deepStrictEqual(response, [expectedResponse]); + assert( + (client.operationsClient.getOperation as SinonStub) + .getCall(0) + .calledWith(request) + ); }); - describe('listLocationsAsync', () => { - it('uses async iteration with listLocations without error', async () => { - const client = new firestoreadminModule.FirestoreAdminClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new LocationProtos.google.cloud.location.ListLocationsRequest() - ); - request.name = ''; - const expectedHeaderRequestParams = 'name='; - const expectedResponse = [ - generateSampleMessage( - new LocationProtos.google.cloud.location.Location() - ), - generateSampleMessage( - new LocationProtos.google.cloud.location.Location() - ), - generateSampleMessage( - new LocationProtos.google.cloud.location.Location() - ), - ]; - client.locationsClient.descriptors.page.listLocations.asyncIterate = stubAsyncIterationCall(expectedResponse); - const responses: LocationProtos.google.cloud.location.ILocation[] = []; - const iterable = client.listLocationsAsync(request); - for await (const resource of iterable) { - responses.push(resource!); + it('invokes getOperation without error using callback', async () => { + const client = new firestoreadminModule.FirestoreAdminClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + const request = generateSampleMessage( + new operationsProtos.google.longrunning.GetOperationRequest() + ); + const expectedResponse = generateSampleMessage( + new operationsProtos.google.longrunning.Operation() + ); + client.operationsClient.getOperation = sinon + .stub() + .callsArgWith(2, null, expectedResponse); + const promise = new Promise((resolve, reject) => { + client.operationsClient + .getOperation( + request, + undefined, + ( + err?: Error | null, + result?: operationsProtos.google.longrunning.Operation | null + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } } - assert.deepStrictEqual(responses, expectedResponse); - assert.deepStrictEqual( - (client.locationsClient.descriptors.page.listLocations.asyncIterate as SinonStub) - .getCall(0).args[1], request); - assert( - (client.locationsClient.descriptors.page.listLocations.asyncIterate as SinonStub) - .getCall(0).args[2].otherArgs.headers['x-goog-request-params'].includes( - expectedHeaderRequestParams - ) - ); - }); - it('uses async iteration with listLocations with error', async () => { - const client = new firestoreadminModule.FirestoreAdminClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new LocationProtos.google.cloud.location.ListLocationsRequest() - ); - request.name = ''; - const expectedHeaderRequestParams = 'name='; - const expectedError = new Error('expected'); - client.locationsClient.descriptors.page.listLocations.asyncIterate = stubAsyncIterationCall(undefined, expectedError); - const iterable = client.listLocationsAsync(request); - await assert.rejects(async () => { - const responses: LocationProtos.google.cloud.location.ILocation[] = []; - for await (const resource of iterable) { - responses.push(resource!); - } - }); - assert.deepStrictEqual( - (client.locationsClient.descriptors.page.listLocations.asyncIterate as SinonStub) - .getCall(0).args[1], request); - assert( - (client.locationsClient.descriptors.page.listLocations.asyncIterate as SinonStub) - .getCall(0).args[2].otherArgs.headers['x-goog-request-params'].includes( - expectedHeaderRequestParams - ) - ); - }); + ) + .catch(err => { + throw err; + }); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + assert((client.operationsClient.getOperation as SinonStub).getCall(0)); }); - describe('getOperation', () => { - it('invokes getOperation without error', async () => { - const client = new firestoreadminModule.FirestoreAdminClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new operationsProtos.google.longrunning.GetOperationRequest() - ); - const expectedResponse = generateSampleMessage( - new operationsProtos.google.longrunning.Operation() - ); - client.operationsClient.getOperation = stubSimpleCall(expectedResponse); - const response = await client.getOperation(request); - assert.deepStrictEqual(response, [expectedResponse]); - assert((client.operationsClient.getOperation as SinonStub) - .getCall(0).calledWith(request) - ); - }); - it('invokes getOperation without error using callback', async () => { - const client = new firestoreadminModule.FirestoreAdminClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - const request = generateSampleMessage( - new operationsProtos.google.longrunning.GetOperationRequest() - ); - const expectedResponse = generateSampleMessage( - new operationsProtos.google.longrunning.Operation() - ); - client.operationsClient.getOperation = sinon.stub().callsArgWith(2, null, expectedResponse); - const promise = new Promise((resolve, reject) => { - client.operationsClient.getOperation( - request, - undefined, - ( - err?: Error | null, - result?: operationsProtos.google.longrunning.Operation | null - ) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }).catch(err => {throw err}); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - assert((client.operationsClient.getOperation as SinonStub) - .getCall(0)); - }); - it('invokes getOperation with error', async () => { - const client = new firestoreadminModule.FirestoreAdminClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - const request = generateSampleMessage( - new operationsProtos.google.longrunning.GetOperationRequest() - ); - const expectedError = new Error('expected'); - client.operationsClient.getOperation = stubSimpleCall(undefined, expectedError); - await assert.rejects(async () => {await client.getOperation(request)}, expectedError); - assert((client.operationsClient.getOperation as SinonStub) - .getCall(0).calledWith(request)); - }); + it('invokes getOperation with error', async () => { + const client = new firestoreadminModule.FirestoreAdminClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + const request = generateSampleMessage( + new operationsProtos.google.longrunning.GetOperationRequest() + ); + const expectedError = new Error('expected'); + client.operationsClient.getOperation = stubSimpleCall( + undefined, + expectedError + ); + await assert.rejects(async () => { + await client.getOperation(request); + }, expectedError); + assert( + (client.operationsClient.getOperation as SinonStub) + .getCall(0) + .calledWith(request) + ); }); - describe('cancelOperation', () => { - it('invokes cancelOperation without error', async () => { - const client = new firestoreadminModule.FirestoreAdminClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new operationsProtos.google.longrunning.CancelOperationRequest() - ); - const expectedResponse = generateSampleMessage( - new protos.google.protobuf.Empty() - ); - client.operationsClient.cancelOperation = stubSimpleCall(expectedResponse); - const response = await client.cancelOperation(request); - assert.deepStrictEqual(response, [expectedResponse]); - assert((client.operationsClient.cancelOperation as SinonStub) - .getCall(0).calledWith(request) - ); - }); - it('invokes cancelOperation without error using callback', async () => { - const client = new firestoreadminModule.FirestoreAdminClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - const request = generateSampleMessage( - new operationsProtos.google.longrunning.CancelOperationRequest() - ); - const expectedResponse = generateSampleMessage( - new protos.google.protobuf.Empty() - ); - client.operationsClient.cancelOperation = sinon.stub().callsArgWith(2, null, expectedResponse); - const promise = new Promise((resolve, reject) => { - client.operationsClient.cancelOperation( - request, - undefined, - ( - err?: Error | null, - result?: protos.google.protobuf.Empty | null - ) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }).catch(err => {throw err}); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - assert((client.operationsClient.cancelOperation as SinonStub) - .getCall(0)); - }); - it('invokes cancelOperation with error', async () => { - const client = new firestoreadminModule.FirestoreAdminClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - const request = generateSampleMessage( - new operationsProtos.google.longrunning.CancelOperationRequest() - ); - const expectedError = new Error('expected'); - client.operationsClient.cancelOperation = stubSimpleCall(undefined, expectedError); - await assert.rejects(async () => {await client.cancelOperation(request)}, expectedError); - assert((client.operationsClient.cancelOperation as SinonStub) - .getCall(0).calledWith(request)); - }); + }); + describe('cancelOperation', () => { + it('invokes cancelOperation without error', async () => { + const client = new firestoreadminModule.FirestoreAdminClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new operationsProtos.google.longrunning.CancelOperationRequest() + ); + const expectedResponse = generateSampleMessage( + new protos.google.protobuf.Empty() + ); + client.operationsClient.cancelOperation = + stubSimpleCall(expectedResponse); + const response = await client.cancelOperation(request); + assert.deepStrictEqual(response, [expectedResponse]); + assert( + (client.operationsClient.cancelOperation as SinonStub) + .getCall(0) + .calledWith(request) + ); }); - describe('deleteOperation', () => { - it('invokes deleteOperation without error', async () => { - const client = new firestoreadminModule.FirestoreAdminClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new operationsProtos.google.longrunning.DeleteOperationRequest() - ); - const expectedResponse = generateSampleMessage( - new protos.google.protobuf.Empty() - ); - client.operationsClient.deleteOperation = stubSimpleCall(expectedResponse); - const response = await client.deleteOperation(request); - assert.deepStrictEqual(response, [expectedResponse]); - assert((client.operationsClient.deleteOperation as SinonStub) - .getCall(0).calledWith(request) - ); - }); - it('invokes deleteOperation without error using callback', async () => { - const client = new firestoreadminModule.FirestoreAdminClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - const request = generateSampleMessage( - new operationsProtos.google.longrunning.DeleteOperationRequest() - ); - const expectedResponse = generateSampleMessage( - new protos.google.protobuf.Empty() - ); - client.operationsClient.deleteOperation = sinon.stub().callsArgWith(2, null, expectedResponse); - const promise = new Promise((resolve, reject) => { - client.operationsClient.deleteOperation( - request, - undefined, - ( - err?: Error | null, - result?: protos.google.protobuf.Empty | null - ) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }).catch(err => {throw err}); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - assert((client.operationsClient.deleteOperation as SinonStub) - .getCall(0)); - }); - it('invokes deleteOperation with error', async () => { - const client = new firestoreadminModule.FirestoreAdminClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - const request = generateSampleMessage( - new operationsProtos.google.longrunning.DeleteOperationRequest() - ); - const expectedError = new Error('expected'); - client.operationsClient.deleteOperation = stubSimpleCall(undefined, expectedError); - await assert.rejects(async () => {await client.deleteOperation(request)}, expectedError); - assert((client.operationsClient.deleteOperation as SinonStub) - .getCall(0).calledWith(request)); - }); + it('invokes cancelOperation without error using callback', async () => { + const client = new firestoreadminModule.FirestoreAdminClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + const request = generateSampleMessage( + new operationsProtos.google.longrunning.CancelOperationRequest() + ); + const expectedResponse = generateSampleMessage( + new protos.google.protobuf.Empty() + ); + client.operationsClient.cancelOperation = sinon + .stub() + .callsArgWith(2, null, expectedResponse); + const promise = new Promise((resolve, reject) => { + client.operationsClient + .cancelOperation( + request, + undefined, + ( + err?: Error | null, + result?: protos.google.protobuf.Empty | null + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + } + ) + .catch(err => { + throw err; + }); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + assert((client.operationsClient.cancelOperation as SinonStub).getCall(0)); + }); + it('invokes cancelOperation with error', async () => { + const client = new firestoreadminModule.FirestoreAdminClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + const request = generateSampleMessage( + new operationsProtos.google.longrunning.CancelOperationRequest() + ); + const expectedError = new Error('expected'); + client.operationsClient.cancelOperation = stubSimpleCall( + undefined, + expectedError + ); + await assert.rejects(async () => { + await client.cancelOperation(request); + }, expectedError); + assert( + (client.operationsClient.cancelOperation as SinonStub) + .getCall(0) + .calledWith(request) + ); }); - describe('listOperationsAsync', () => { - it('uses async iteration with listOperations without error', async () => { - const client = new firestoreadminModule.FirestoreAdminClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - const request = generateSampleMessage( - new operationsProtos.google.longrunning.ListOperationsRequest() - ); - const expectedResponse = [ - generateSampleMessage( - new operationsProtos.google.longrunning.ListOperationsResponse() - ), - generateSampleMessage( - new operationsProtos.google.longrunning.ListOperationsResponse() - ), - generateSampleMessage( - new operationsProtos.google.longrunning.ListOperationsResponse() - ), - ]; - client.operationsClient.descriptor.listOperations.asyncIterate = stubAsyncIterationCall(expectedResponse); - const responses: operationsProtos.google.longrunning.IOperation[] = []; - const iterable = client.operationsClient.listOperationsAsync(request); - for await (const resource of iterable) { - responses.push(resource!); + }); + describe('deleteOperation', () => { + it('invokes deleteOperation without error', async () => { + const client = new firestoreadminModule.FirestoreAdminClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new operationsProtos.google.longrunning.DeleteOperationRequest() + ); + const expectedResponse = generateSampleMessage( + new protos.google.protobuf.Empty() + ); + client.operationsClient.deleteOperation = + stubSimpleCall(expectedResponse); + const response = await client.deleteOperation(request); + assert.deepStrictEqual(response, [expectedResponse]); + assert( + (client.operationsClient.deleteOperation as SinonStub) + .getCall(0) + .calledWith(request) + ); + }); + it('invokes deleteOperation without error using callback', async () => { + const client = new firestoreadminModule.FirestoreAdminClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + const request = generateSampleMessage( + new operationsProtos.google.longrunning.DeleteOperationRequest() + ); + const expectedResponse = generateSampleMessage( + new protos.google.protobuf.Empty() + ); + client.operationsClient.deleteOperation = sinon + .stub() + .callsArgWith(2, null, expectedResponse); + const promise = new Promise((resolve, reject) => { + client.operationsClient + .deleteOperation( + request, + undefined, + ( + err?: Error | null, + result?: protos.google.protobuf.Empty | null + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } } - assert.deepStrictEqual(responses, expectedResponse); - assert.deepStrictEqual( - (client.operationsClient.descriptor.listOperations.asyncIterate as SinonStub) - .getCall(0).args[1], request); - }); - it('uses async iteration with listOperations with error', async () => { - const client = new firestoreadminModule.FirestoreAdminClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new operationsProtos.google.longrunning.ListOperationsRequest() - ); - const expectedError = new Error('expected'); - client.operationsClient.descriptor.listOperations.asyncIterate = stubAsyncIterationCall(undefined, expectedError); - const iterable = client.operationsClient.listOperationsAsync(request); - await assert.rejects(async () => { - const responses: operationsProtos.google.longrunning.IOperation[] = []; - for await (const resource of iterable) { - responses.push(resource!); - } - }); - assert.deepStrictEqual( - (client.operationsClient.descriptor.listOperations.asyncIterate as SinonStub) - .getCall(0).args[1], request); - }); + ) + .catch(err => { + throw err; + }); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + assert((client.operationsClient.deleteOperation as SinonStub).getCall(0)); + }); + it('invokes deleteOperation with error', async () => { + const client = new firestoreadminModule.FirestoreAdminClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + const request = generateSampleMessage( + new operationsProtos.google.longrunning.DeleteOperationRequest() + ); + const expectedError = new Error('expected'); + client.operationsClient.deleteOperation = stubSimpleCall( + undefined, + expectedError + ); + await assert.rejects(async () => { + await client.deleteOperation(request); + }, expectedError); + assert( + (client.operationsClient.deleteOperation as SinonStub) + .getCall(0) + .calledWith(request) + ); + }); + }); + describe('listOperationsAsync', () => { + it('uses async iteration with listOperations without error', async () => { + const client = new firestoreadminModule.FirestoreAdminClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + const request = generateSampleMessage( + new operationsProtos.google.longrunning.ListOperationsRequest() + ); + const expectedResponse = [ + generateSampleMessage( + new operationsProtos.google.longrunning.ListOperationsResponse() + ), + generateSampleMessage( + new operationsProtos.google.longrunning.ListOperationsResponse() + ), + generateSampleMessage( + new operationsProtos.google.longrunning.ListOperationsResponse() + ), + ]; + client.operationsClient.descriptor.listOperations.asyncIterate = + stubAsyncIterationCall(expectedResponse); + const responses: operationsProtos.google.longrunning.IOperation[] = []; + const iterable = client.operationsClient.listOperationsAsync(request); + for await (const resource of iterable) { + responses.push(resource!); + } + assert.deepStrictEqual(responses, expectedResponse); + assert.deepStrictEqual( + ( + client.operationsClient.descriptor.listOperations + .asyncIterate as SinonStub + ).getCall(0).args[1], + request + ); + }); + it('uses async iteration with listOperations with error', async () => { + const client = new firestoreadminModule.FirestoreAdminClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new operationsProtos.google.longrunning.ListOperationsRequest() + ); + const expectedError = new Error('expected'); + client.operationsClient.descriptor.listOperations.asyncIterate = + stubAsyncIterationCall(undefined, expectedError); + const iterable = client.operationsClient.listOperationsAsync(request); + await assert.rejects(async () => { + const responses: operationsProtos.google.longrunning.IOperation[] = []; + for await (const resource of iterable) { + responses.push(resource!); + } + }); + assert.deepStrictEqual( + ( + client.operationsClient.descriptor.listOperations + .asyncIterate as SinonStub + ).getCall(0).args[1], + request + ); + }); + }); + + describe('Path templates', () => { + describe('backup', async () => { + const fakePath = '/rendered/path/backup'; + const expectedParameters = { + project: 'projectValue', + location: 'locationValue', + backup: 'backupValue', + }; + const client = new firestoreadminModule.FirestoreAdminClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + client.pathTemplates.backupPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.backupPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('backupPath', () => { + const result = client.backupPath( + 'projectValue', + 'locationValue', + 'backupValue' + ); + assert.strictEqual(result, fakePath); + assert( + (client.pathTemplates.backupPathTemplate.render as SinonStub) + .getCall(-1) + .calledWith(expectedParameters) + ); + }); + + it('matchProjectFromBackupName', () => { + const result = client.matchProjectFromBackupName(fakePath); + assert.strictEqual(result, 'projectValue'); + assert( + (client.pathTemplates.backupPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath) + ); + }); + + it('matchLocationFromBackupName', () => { + const result = client.matchLocationFromBackupName(fakePath); + assert.strictEqual(result, 'locationValue'); + assert( + (client.pathTemplates.backupPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath) + ); + }); + + it('matchBackupFromBackupName', () => { + const result = client.matchBackupFromBackupName(fakePath); + assert.strictEqual(result, 'backupValue'); + assert( + (client.pathTemplates.backupPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath) + ); + }); }); - describe('Path templates', () => { - - describe('backup', async () => { - const fakePath = "/rendered/path/backup"; - const expectedParameters = { - project: "projectValue", - location: "locationValue", - backup: "backupValue", - }; - const client = new firestoreadminModule.FirestoreAdminClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - client.pathTemplates.backupPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.backupPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('backupPath', () => { - const result = client.backupPath("projectValue", "locationValue", "backupValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.backupPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchProjectFromBackupName', () => { - const result = client.matchProjectFromBackupName(fakePath); - assert.strictEqual(result, "projectValue"); - assert((client.pathTemplates.backupPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchLocationFromBackupName', () => { - const result = client.matchLocationFromBackupName(fakePath); - assert.strictEqual(result, "locationValue"); - assert((client.pathTemplates.backupPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchBackupFromBackupName', () => { - const result = client.matchBackupFromBackupName(fakePath); - assert.strictEqual(result, "backupValue"); - assert((client.pathTemplates.backupPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); - - describe('backupSchedule', async () => { - const fakePath = "/rendered/path/backupSchedule"; - const expectedParameters = { - project: "projectValue", - database: "databaseValue", - backup_schedule: "backupScheduleValue", - }; - const client = new firestoreadminModule.FirestoreAdminClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - client.pathTemplates.backupSchedulePathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.backupSchedulePathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('backupSchedulePath', () => { - const result = client.backupSchedulePath("projectValue", "databaseValue", "backupScheduleValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.backupSchedulePathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchProjectFromBackupScheduleName', () => { - const result = client.matchProjectFromBackupScheduleName(fakePath); - assert.strictEqual(result, "projectValue"); - assert((client.pathTemplates.backupSchedulePathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchDatabaseFromBackupScheduleName', () => { - const result = client.matchDatabaseFromBackupScheduleName(fakePath); - assert.strictEqual(result, "databaseValue"); - assert((client.pathTemplates.backupSchedulePathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchBackupScheduleFromBackupScheduleName', () => { - const result = client.matchBackupScheduleFromBackupScheduleName(fakePath); - assert.strictEqual(result, "backupScheduleValue"); - assert((client.pathTemplates.backupSchedulePathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + describe('backupSchedule', async () => { + const fakePath = '/rendered/path/backupSchedule'; + const expectedParameters = { + project: 'projectValue', + database: 'databaseValue', + backup_schedule: 'backupScheduleValue', + }; + const client = new firestoreadminModule.FirestoreAdminClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + client.pathTemplates.backupSchedulePathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.backupSchedulePathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('backupSchedulePath', () => { + const result = client.backupSchedulePath( + 'projectValue', + 'databaseValue', + 'backupScheduleValue' + ); + assert.strictEqual(result, fakePath); + assert( + (client.pathTemplates.backupSchedulePathTemplate.render as SinonStub) + .getCall(-1) + .calledWith(expectedParameters) + ); + }); + + it('matchProjectFromBackupScheduleName', () => { + const result = client.matchProjectFromBackupScheduleName(fakePath); + assert.strictEqual(result, 'projectValue'); + assert( + (client.pathTemplates.backupSchedulePathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath) + ); + }); + + it('matchDatabaseFromBackupScheduleName', () => { + const result = client.matchDatabaseFromBackupScheduleName(fakePath); + assert.strictEqual(result, 'databaseValue'); + assert( + (client.pathTemplates.backupSchedulePathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath) + ); + }); + + it('matchBackupScheduleFromBackupScheduleName', () => { + const result = + client.matchBackupScheduleFromBackupScheduleName(fakePath); + assert.strictEqual(result, 'backupScheduleValue'); + assert( + (client.pathTemplates.backupSchedulePathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath) + ); + }); + }); - describe('collectionGroup', async () => { - const fakePath = "/rendered/path/collectionGroup"; - const expectedParameters = { - project: "projectValue", - database: "databaseValue", - collection: "collectionValue", - }; - const client = new firestoreadminModule.FirestoreAdminClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - client.pathTemplates.collectionGroupPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.collectionGroupPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('collectionGroupPath', () => { - const result = client.collectionGroupPath("projectValue", "databaseValue", "collectionValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.collectionGroupPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchProjectFromCollectionGroupName', () => { - const result = client.matchProjectFromCollectionGroupName(fakePath); - assert.strictEqual(result, "projectValue"); - assert((client.pathTemplates.collectionGroupPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchDatabaseFromCollectionGroupName', () => { - const result = client.matchDatabaseFromCollectionGroupName(fakePath); - assert.strictEqual(result, "databaseValue"); - assert((client.pathTemplates.collectionGroupPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchCollectionFromCollectionGroupName', () => { - const result = client.matchCollectionFromCollectionGroupName(fakePath); - assert.strictEqual(result, "collectionValue"); - assert((client.pathTemplates.collectionGroupPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + describe('collectionGroup', async () => { + const fakePath = '/rendered/path/collectionGroup'; + const expectedParameters = { + project: 'projectValue', + database: 'databaseValue', + collection: 'collectionValue', + }; + const client = new firestoreadminModule.FirestoreAdminClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + client.pathTemplates.collectionGroupPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.collectionGroupPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('collectionGroupPath', () => { + const result = client.collectionGroupPath( + 'projectValue', + 'databaseValue', + 'collectionValue' + ); + assert.strictEqual(result, fakePath); + assert( + (client.pathTemplates.collectionGroupPathTemplate.render as SinonStub) + .getCall(-1) + .calledWith(expectedParameters) + ); + }); + + it('matchProjectFromCollectionGroupName', () => { + const result = client.matchProjectFromCollectionGroupName(fakePath); + assert.strictEqual(result, 'projectValue'); + assert( + (client.pathTemplates.collectionGroupPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath) + ); + }); + + it('matchDatabaseFromCollectionGroupName', () => { + const result = client.matchDatabaseFromCollectionGroupName(fakePath); + assert.strictEqual(result, 'databaseValue'); + assert( + (client.pathTemplates.collectionGroupPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath) + ); + }); + + it('matchCollectionFromCollectionGroupName', () => { + const result = client.matchCollectionFromCollectionGroupName(fakePath); + assert.strictEqual(result, 'collectionValue'); + assert( + (client.pathTemplates.collectionGroupPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath) + ); + }); + }); - describe('database', async () => { - const fakePath = "/rendered/path/database"; - const expectedParameters = { - project: "projectValue", - database: "databaseValue", - }; - const client = new firestoreadminModule.FirestoreAdminClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - client.pathTemplates.databasePathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.databasePathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('databasePath', () => { - const result = client.databasePath("projectValue", "databaseValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.databasePathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchProjectFromDatabaseName', () => { - const result = client.matchProjectFromDatabaseName(fakePath); - assert.strictEqual(result, "projectValue"); - assert((client.pathTemplates.databasePathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchDatabaseFromDatabaseName', () => { - const result = client.matchDatabaseFromDatabaseName(fakePath); - assert.strictEqual(result, "databaseValue"); - assert((client.pathTemplates.databasePathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + describe('database', async () => { + const fakePath = '/rendered/path/database'; + const expectedParameters = { + project: 'projectValue', + database: 'databaseValue', + }; + const client = new firestoreadminModule.FirestoreAdminClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + client.pathTemplates.databasePathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.databasePathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('databasePath', () => { + const result = client.databasePath('projectValue', 'databaseValue'); + assert.strictEqual(result, fakePath); + assert( + (client.pathTemplates.databasePathTemplate.render as SinonStub) + .getCall(-1) + .calledWith(expectedParameters) + ); + }); + + it('matchProjectFromDatabaseName', () => { + const result = client.matchProjectFromDatabaseName(fakePath); + assert.strictEqual(result, 'projectValue'); + assert( + (client.pathTemplates.databasePathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath) + ); + }); + + it('matchDatabaseFromDatabaseName', () => { + const result = client.matchDatabaseFromDatabaseName(fakePath); + assert.strictEqual(result, 'databaseValue'); + assert( + (client.pathTemplates.databasePathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath) + ); + }); + }); - describe('field', async () => { - const fakePath = "/rendered/path/field"; - const expectedParameters = { - project: "projectValue", - database: "databaseValue", - collection: "collectionValue", - field: "fieldValue", - }; - const client = new firestoreadminModule.FirestoreAdminClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - client.pathTemplates.fieldPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.fieldPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('fieldPath', () => { - const result = client.fieldPath("projectValue", "databaseValue", "collectionValue", "fieldValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.fieldPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchProjectFromFieldName', () => { - const result = client.matchProjectFromFieldName(fakePath); - assert.strictEqual(result, "projectValue"); - assert((client.pathTemplates.fieldPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchDatabaseFromFieldName', () => { - const result = client.matchDatabaseFromFieldName(fakePath); - assert.strictEqual(result, "databaseValue"); - assert((client.pathTemplates.fieldPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchCollectionFromFieldName', () => { - const result = client.matchCollectionFromFieldName(fakePath); - assert.strictEqual(result, "collectionValue"); - assert((client.pathTemplates.fieldPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchFieldFromFieldName', () => { - const result = client.matchFieldFromFieldName(fakePath); - assert.strictEqual(result, "fieldValue"); - assert((client.pathTemplates.fieldPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + describe('field', async () => { + const fakePath = '/rendered/path/field'; + const expectedParameters = { + project: 'projectValue', + database: 'databaseValue', + collection: 'collectionValue', + field: 'fieldValue', + }; + const client = new firestoreadminModule.FirestoreAdminClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + client.pathTemplates.fieldPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.fieldPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('fieldPath', () => { + const result = client.fieldPath( + 'projectValue', + 'databaseValue', + 'collectionValue', + 'fieldValue' + ); + assert.strictEqual(result, fakePath); + assert( + (client.pathTemplates.fieldPathTemplate.render as SinonStub) + .getCall(-1) + .calledWith(expectedParameters) + ); + }); + + it('matchProjectFromFieldName', () => { + const result = client.matchProjectFromFieldName(fakePath); + assert.strictEqual(result, 'projectValue'); + assert( + (client.pathTemplates.fieldPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath) + ); + }); + + it('matchDatabaseFromFieldName', () => { + const result = client.matchDatabaseFromFieldName(fakePath); + assert.strictEqual(result, 'databaseValue'); + assert( + (client.pathTemplates.fieldPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath) + ); + }); + + it('matchCollectionFromFieldName', () => { + const result = client.matchCollectionFromFieldName(fakePath); + assert.strictEqual(result, 'collectionValue'); + assert( + (client.pathTemplates.fieldPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath) + ); + }); + + it('matchFieldFromFieldName', () => { + const result = client.matchFieldFromFieldName(fakePath); + assert.strictEqual(result, 'fieldValue'); + assert( + (client.pathTemplates.fieldPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath) + ); + }); + }); - describe('index', async () => { - const fakePath = "/rendered/path/index"; - const expectedParameters = { - project: "projectValue", - database: "databaseValue", - collection: "collectionValue", - index: "indexValue", - }; - const client = new firestoreadminModule.FirestoreAdminClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - client.pathTemplates.indexPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.indexPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('indexPath', () => { - const result = client.indexPath("projectValue", "databaseValue", "collectionValue", "indexValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.indexPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchProjectFromIndexName', () => { - const result = client.matchProjectFromIndexName(fakePath); - assert.strictEqual(result, "projectValue"); - assert((client.pathTemplates.indexPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchDatabaseFromIndexName', () => { - const result = client.matchDatabaseFromIndexName(fakePath); - assert.strictEqual(result, "databaseValue"); - assert((client.pathTemplates.indexPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchCollectionFromIndexName', () => { - const result = client.matchCollectionFromIndexName(fakePath); - assert.strictEqual(result, "collectionValue"); - assert((client.pathTemplates.indexPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchIndexFromIndexName', () => { - const result = client.matchIndexFromIndexName(fakePath); - assert.strictEqual(result, "indexValue"); - assert((client.pathTemplates.indexPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + describe('index', async () => { + const fakePath = '/rendered/path/index'; + const expectedParameters = { + project: 'projectValue', + database: 'databaseValue', + collection: 'collectionValue', + index: 'indexValue', + }; + const client = new firestoreadminModule.FirestoreAdminClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + client.pathTemplates.indexPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.indexPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('indexPath', () => { + const result = client.indexPath( + 'projectValue', + 'databaseValue', + 'collectionValue', + 'indexValue' + ); + assert.strictEqual(result, fakePath); + assert( + (client.pathTemplates.indexPathTemplate.render as SinonStub) + .getCall(-1) + .calledWith(expectedParameters) + ); + }); + + it('matchProjectFromIndexName', () => { + const result = client.matchProjectFromIndexName(fakePath); + assert.strictEqual(result, 'projectValue'); + assert( + (client.pathTemplates.indexPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath) + ); + }); + + it('matchDatabaseFromIndexName', () => { + const result = client.matchDatabaseFromIndexName(fakePath); + assert.strictEqual(result, 'databaseValue'); + assert( + (client.pathTemplates.indexPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath) + ); + }); + + it('matchCollectionFromIndexName', () => { + const result = client.matchCollectionFromIndexName(fakePath); + assert.strictEqual(result, 'collectionValue'); + assert( + (client.pathTemplates.indexPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath) + ); + }); + + it('matchIndexFromIndexName', () => { + const result = client.matchIndexFromIndexName(fakePath); + assert.strictEqual(result, 'indexValue'); + assert( + (client.pathTemplates.indexPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath) + ); + }); + }); - describe('location', async () => { - const fakePath = "/rendered/path/location"; - const expectedParameters = { - project: "projectValue", - location: "locationValue", - }; - const client = new firestoreadminModule.FirestoreAdminClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - client.pathTemplates.locationPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.locationPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('locationPath', () => { - const result = client.locationPath("projectValue", "locationValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.locationPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchProjectFromLocationName', () => { - const result = client.matchProjectFromLocationName(fakePath); - assert.strictEqual(result, "projectValue"); - assert((client.pathTemplates.locationPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchLocationFromLocationName', () => { - const result = client.matchLocationFromLocationName(fakePath); - assert.strictEqual(result, "locationValue"); - assert((client.pathTemplates.locationPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + describe('location', async () => { + const fakePath = '/rendered/path/location'; + const expectedParameters = { + project: 'projectValue', + location: 'locationValue', + }; + const client = new firestoreadminModule.FirestoreAdminClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + client.pathTemplates.locationPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.locationPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('locationPath', () => { + const result = client.locationPath('projectValue', 'locationValue'); + assert.strictEqual(result, fakePath); + assert( + (client.pathTemplates.locationPathTemplate.render as SinonStub) + .getCall(-1) + .calledWith(expectedParameters) + ); + }); + + it('matchProjectFromLocationName', () => { + const result = client.matchProjectFromLocationName(fakePath); + assert.strictEqual(result, 'projectValue'); + assert( + (client.pathTemplates.locationPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath) + ); + }); + + it('matchLocationFromLocationName', () => { + const result = client.matchLocationFromLocationName(fakePath); + assert.strictEqual(result, 'locationValue'); + assert( + (client.pathTemplates.locationPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath) + ); + }); + }); - describe('project', async () => { - const fakePath = "/rendered/path/project"; - const expectedParameters = { - project: "projectValue", - }; - const client = new firestoreadminModule.FirestoreAdminClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - client.pathTemplates.projectPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.projectPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('projectPath', () => { - const result = client.projectPath("projectValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.projectPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchProjectFromProjectName', () => { - const result = client.matchProjectFromProjectName(fakePath); - assert.strictEqual(result, "projectValue"); - assert((client.pathTemplates.projectPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + describe('project', async () => { + const fakePath = '/rendered/path/project'; + const expectedParameters = { + project: 'projectValue', + }; + const client = new firestoreadminModule.FirestoreAdminClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + client.pathTemplates.projectPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.projectPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('projectPath', () => { + const result = client.projectPath('projectValue'); + assert.strictEqual(result, fakePath); + assert( + (client.pathTemplates.projectPathTemplate.render as SinonStub) + .getCall(-1) + .calledWith(expectedParameters) + ); + }); + + it('matchProjectFromProjectName', () => { + const result = client.matchProjectFromProjectName(fakePath); + assert.strictEqual(result, 'projectValue'); + assert( + (client.pathTemplates.projectPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath) + ); + }); + }); - describe('userCreds', async () => { - const fakePath = "/rendered/path/userCreds"; - const expectedParameters = { - project: "projectValue", - database: "databaseValue", - user_creds: "userCredsValue", - }; - const client = new firestoreadminModule.FirestoreAdminClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - client.pathTemplates.userCredsPathTemplate.render = - sinon.stub().returns(fakePath); - client.pathTemplates.userCredsPathTemplate.match = - sinon.stub().returns(expectedParameters); - - it('userCredsPath', () => { - const result = client.userCredsPath("projectValue", "databaseValue", "userCredsValue"); - assert.strictEqual(result, fakePath); - assert((client.pathTemplates.userCredsPathTemplate.render as SinonStub) - .getCall(-1).calledWith(expectedParameters)); - }); - - it('matchProjectFromUserCredsName', () => { - const result = client.matchProjectFromUserCredsName(fakePath); - assert.strictEqual(result, "projectValue"); - assert((client.pathTemplates.userCredsPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchDatabaseFromUserCredsName', () => { - const result = client.matchDatabaseFromUserCredsName(fakePath); - assert.strictEqual(result, "databaseValue"); - assert((client.pathTemplates.userCredsPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - - it('matchUserCredsFromUserCredsName', () => { - const result = client.matchUserCredsFromUserCredsName(fakePath); - assert.strictEqual(result, "userCredsValue"); - assert((client.pathTemplates.userCredsPathTemplate.match as SinonStub) - .getCall(-1).calledWith(fakePath)); - }); - }); + describe('userCreds', async () => { + const fakePath = '/rendered/path/userCreds'; + const expectedParameters = { + project: 'projectValue', + database: 'databaseValue', + user_creds: 'userCredsValue', + }; + const client = new firestoreadminModule.FirestoreAdminClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + client.pathTemplates.userCredsPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.userCredsPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('userCredsPath', () => { + const result = client.userCredsPath( + 'projectValue', + 'databaseValue', + 'userCredsValue' + ); + assert.strictEqual(result, fakePath); + assert( + (client.pathTemplates.userCredsPathTemplate.render as SinonStub) + .getCall(-1) + .calledWith(expectedParameters) + ); + }); + + it('matchProjectFromUserCredsName', () => { + const result = client.matchProjectFromUserCredsName(fakePath); + assert.strictEqual(result, 'projectValue'); + assert( + (client.pathTemplates.userCredsPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath) + ); + }); + + it('matchDatabaseFromUserCredsName', () => { + const result = client.matchDatabaseFromUserCredsName(fakePath); + assert.strictEqual(result, 'databaseValue'); + assert( + (client.pathTemplates.userCredsPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath) + ); + }); + + it('matchUserCredsFromUserCredsName', () => { + const result = client.matchUserCredsFromUserCredsName(fakePath); + assert.strictEqual(result, 'userCredsValue'); + assert( + (client.pathTemplates.userCredsPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath) + ); + }); }); + }); }); diff --git a/dev/test/gapic_firestore_v1.ts b/dev/test/gapic_firestore_v1.ts index 78879baf3..6b04e5603 100644 --- a/dev/test/gapic_firestore_v1.ts +++ b/dev/test/gapic_firestore_v1.ts @@ -33,2720 +33,3347 @@ const root = protobuf.Root.fromJSON(require('../protos/v1.json')).resolveAll(); // eslint-disable-next-line @typescript-eslint/no-unused-vars function getTypeDefaultValue(typeName: string, fields: string[]) { - let type = root.lookupType(typeName) as protobuf.Type; - for (const field of fields.slice(0, -1)) { - type = type.fields[field]?.resolvedType as protobuf.Type; - } - return type.fields[fields[fields.length - 1]]?.defaultValue; + let type = root.lookupType(typeName) as protobuf.Type; + for (const field of fields.slice(0, -1)) { + type = type.fields[field]?.resolvedType as protobuf.Type; + } + return type.fields[fields[fields.length - 1]]?.defaultValue; } function generateSampleMessage(instance: T) { - const filledObject = (instance.constructor as typeof protobuf.Message) - .toObject(instance as protobuf.Message, {defaults: true}); - return (instance.constructor as typeof protobuf.Message).fromObject(filledObject) as T; + const filledObject = ( + instance.constructor as typeof protobuf.Message + ).toObject(instance as protobuf.Message, {defaults: true}); + return (instance.constructor as typeof protobuf.Message).fromObject( + filledObject + ) as T; } function stubSimpleCall(response?: ResponseType, error?: Error) { - return error ? sinon.stub().rejects(error) : sinon.stub().resolves([response]); + return error + ? sinon.stub().rejects(error) + : sinon.stub().resolves([response]); } -function stubSimpleCallWithCallback(response?: ResponseType, error?: Error) { - return error ? sinon.stub().callsArgWith(2, error) : sinon.stub().callsArgWith(2, null, response); +function stubSimpleCallWithCallback( + response?: ResponseType, + error?: Error +) { + return error + ? sinon.stub().callsArgWith(2, error) + : sinon.stub().callsArgWith(2, null, response); } -function stubServerStreamingCall(response?: ResponseType, error?: Error) { - const transformStub = error ? sinon.stub().callsArgWith(2, error) : sinon.stub().callsArgWith(2, null, response); - const mockStream = new PassThrough({ - objectMode: true, - transform: transformStub, - }); - // write something to the stream to trigger transformStub and send the response back to the client - setImmediate(() => { mockStream.write({}); }); - setImmediate(() => { mockStream.end(); }); - return sinon.stub().returns(mockStream); +function stubServerStreamingCall( + response?: ResponseType, + error?: Error +) { + const transformStub = error + ? sinon.stub().callsArgWith(2, error) + : sinon.stub().callsArgWith(2, null, response); + const mockStream = new PassThrough({ + objectMode: true, + transform: transformStub, + }); + // write something to the stream to trigger transformStub and send the response back to the client + setImmediate(() => { + mockStream.write({}); + }); + setImmediate(() => { + mockStream.end(); + }); + return sinon.stub().returns(mockStream); } -function stubBidiStreamingCall(response?: ResponseType, error?: Error) { - const transformStub = error ? sinon.stub().callsArgWith(2, error) : sinon.stub().callsArgWith(2, null, response); - const mockStream = new PassThrough({ - objectMode: true, - transform: transformStub, - }); - return sinon.stub().returns(mockStream); +function stubBidiStreamingCall( + response?: ResponseType, + error?: Error +) { + const transformStub = error + ? sinon.stub().callsArgWith(2, error) + : sinon.stub().callsArgWith(2, null, response); + const mockStream = new PassThrough({ + objectMode: true, + transform: transformStub, + }); + return sinon.stub().returns(mockStream); } -function stubPageStreamingCall(responses?: ResponseType[], error?: Error) { - const pagingStub = sinon.stub(); - if (responses) { - for (let i = 0; i < responses.length; ++i) { - pagingStub.onCall(i).callsArgWith(2, null, responses[i]); - } +function stubPageStreamingCall( + responses?: ResponseType[], + error?: Error +) { + const pagingStub = sinon.stub(); + if (responses) { + for (let i = 0; i < responses.length; ++i) { + pagingStub.onCall(i).callsArgWith(2, null, responses[i]); } - const transformStub = error ? sinon.stub().callsArgWith(2, error) : pagingStub; - const mockStream = new PassThrough({ - objectMode: true, - transform: transformStub, - }); - // trigger as many responses as needed - if (responses) { - for (let i = 0; i < responses.length; ++i) { - setImmediate(() => { mockStream.write({}); }); - } - setImmediate(() => { mockStream.end(); }); - } else { - setImmediate(() => { mockStream.write({}); }); - setImmediate(() => { mockStream.end(); }); + } + const transformStub = error + ? sinon.stub().callsArgWith(2, error) + : pagingStub; + const mockStream = new PassThrough({ + objectMode: true, + transform: transformStub, + }); + // trigger as many responses as needed + if (responses) { + for (let i = 0; i < responses.length; ++i) { + setImmediate(() => { + mockStream.write({}); + }); } - return sinon.stub().returns(mockStream); + setImmediate(() => { + mockStream.end(); + }); + } else { + setImmediate(() => { + mockStream.write({}); + }); + setImmediate(() => { + mockStream.end(); + }); + } + return sinon.stub().returns(mockStream); } -function stubAsyncIterationCall(responses?: ResponseType[], error?: Error) { - let counter = 0; - const asyncIterable = { - [Symbol.asyncIterator]() { - return { - async next() { - if (error) { - return Promise.reject(error); - } - if (counter >= responses!.length) { - return Promise.resolve({done: true, value: undefined}); - } - return Promise.resolve({done: false, value: responses![counter++]}); - } - }; - } - }; - return sinon.stub().returns(asyncIterable); +function stubAsyncIterationCall( + responses?: ResponseType[], + error?: Error +) { + let counter = 0; + const asyncIterable = { + [Symbol.asyncIterator]() { + return { + async next() { + if (error) { + return Promise.reject(error); + } + if (counter >= responses!.length) { + return Promise.resolve({done: true, value: undefined}); + } + return Promise.resolve({done: false, value: responses![counter++]}); + }, + }; + }, + }; + return sinon.stub().returns(asyncIterable); } describe('v1.FirestoreClient', () => { - describe('Common methods', () => { - it('has apiEndpoint', () => { - const client = new firestoreModule.FirestoreClient(); - const apiEndpoint = client.apiEndpoint; - assert.strictEqual(apiEndpoint, 'firestore.googleapis.com'); - }); - - it('has universeDomain', () => { - const client = new firestoreModule.FirestoreClient(); - const universeDomain = client.universeDomain; - assert.strictEqual(universeDomain, "googleapis.com"); - }); - - if (typeof process === 'object' && typeof process.emitWarning === 'function') { - it('throws DeprecationWarning if static servicePath is used', () => { - const stub = sinon.stub(process, 'emitWarning'); - const servicePath = firestoreModule.FirestoreClient.servicePath; - assert.strictEqual(servicePath, 'firestore.googleapis.com'); - assert(stub.called); - stub.restore(); - }); - - it('throws DeprecationWarning if static apiEndpoint is used', () => { - const stub = sinon.stub(process, 'emitWarning'); - const apiEndpoint = firestoreModule.FirestoreClient.apiEndpoint; - assert.strictEqual(apiEndpoint, 'firestore.googleapis.com'); - assert(stub.called); - stub.restore(); - }); - } - it('sets apiEndpoint according to universe domain camelCase', () => { - const client = new firestoreModule.FirestoreClient({universeDomain: 'example.com'}); - const servicePath = client.apiEndpoint; - assert.strictEqual(servicePath, 'firestore.example.com'); - }); - - it('sets apiEndpoint according to universe domain snakeCase', () => { - const client = new firestoreModule.FirestoreClient({universe_domain: 'example.com'}); - const servicePath = client.apiEndpoint; - assert.strictEqual(servicePath, 'firestore.example.com'); - }); - - if (typeof process === 'object' && 'env' in process) { - describe('GOOGLE_CLOUD_UNIVERSE_DOMAIN environment variable', () => { - it('sets apiEndpoint from environment variable', () => { - const saved = process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN']; - process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] = 'example.com'; - const client = new firestoreModule.FirestoreClient(); - const servicePath = client.apiEndpoint; - assert.strictEqual(servicePath, 'firestore.example.com'); - if (saved) { - process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] = saved; - } else { - delete process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN']; - } - }); - - it('value configured in code has priority over environment variable', () => { - const saved = process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN']; - process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] = 'example.com'; - const client = new firestoreModule.FirestoreClient({universeDomain: 'configured.example.com'}); - const servicePath = client.apiEndpoint; - assert.strictEqual(servicePath, 'firestore.configured.example.com'); - if (saved) { - process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] = saved; - } else { - delete process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN']; - } - }); - }); - } - it('does not allow setting both universeDomain and universe_domain', () => { - assert.throws(() => { new firestoreModule.FirestoreClient({universe_domain: 'example.com', universeDomain: 'example.net'}); }); - }); - - it('has port', () => { - const port = firestoreModule.FirestoreClient.port; - assert(port); - assert(typeof port === 'number'); - }); - - it('should create a client with no option', () => { - const client = new firestoreModule.FirestoreClient(); - assert(client); - }); - - it('should create a client with gRPC fallback', () => { - const client = new firestoreModule.FirestoreClient({ - fallback: true, - }); - assert(client); - }); - - it('has initialize method and supports deferred initialization', async () => { - const client = new firestoreModule.FirestoreClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - assert.strictEqual(client.firestoreStub, undefined); - await client.initialize(); - assert(client.firestoreStub); - }); - - it('has close method for the initialized client', done => { - const client = new firestoreModule.FirestoreClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.initialize().catch(err => {throw err}); - assert(client.firestoreStub); - client.close().then(() => { - done(); - }).catch(err => {throw err}); - }); - - it('has close method for the non-initialized client', done => { - const client = new firestoreModule.FirestoreClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - assert.strictEqual(client.firestoreStub, undefined); - client.close().then(() => { - done(); - }).catch(err => {throw err}); - }); - - it('has getProjectId method', async () => { - const fakeProjectId = 'fake-project-id'; - const client = new firestoreModule.FirestoreClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.auth.getProjectId = sinon.stub().resolves(fakeProjectId); - const result = await client.getProjectId(); - assert.strictEqual(result, fakeProjectId); - assert((client.auth.getProjectId as SinonStub).calledWithExactly()); - }); - - it('has getProjectId method with callback', async () => { - const fakeProjectId = 'fake-project-id'; - const client = new firestoreModule.FirestoreClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.auth.getProjectId = sinon.stub().callsArgWith(0, null, fakeProjectId); - const promise = new Promise((resolve, reject) => { - client.getProjectId((err?: Error|null, projectId?: string|null) => { - if (err) { - reject(err); - } else { - resolve(projectId); - } - }); - }); - const result = await promise; - assert.strictEqual(result, fakeProjectId); - }); + describe('Common methods', () => { + it('has apiEndpoint', () => { + const client = new firestoreModule.FirestoreClient(); + const apiEndpoint = client.apiEndpoint; + assert.strictEqual(apiEndpoint, 'firestore.googleapis.com'); }); - describe('getDocument', () => { - it('invokes getDocument without error', async () => { - const client = new firestoreModule.FirestoreClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.firestore.v1.GetDocumentRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.firestore.v1.GetDocumentRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.firestore.v1.Document() - ); - client.innerApiCalls.getDocument = stubSimpleCall(expectedResponse); - const [response] = await client.getDocument(request); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.getDocument as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.getDocument as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes getDocument without error using callback', async () => { - const client = new firestoreModule.FirestoreClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.firestore.v1.GetDocumentRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.firestore.v1.GetDocumentRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.firestore.v1.Document() - ); - client.innerApiCalls.getDocument = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.getDocument( - request, - (err?: Error|null, result?: protos.google.firestore.v1.IDocument|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.getDocument as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.getDocument as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('has universeDomain', () => { + const client = new firestoreModule.FirestoreClient(); + const universeDomain = client.universeDomain; + assert.strictEqual(universeDomain, 'googleapis.com'); + }); - it('invokes getDocument with error', async () => { - const client = new firestoreModule.FirestoreClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.firestore.v1.GetDocumentRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.firestore.v1.GetDocumentRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.getDocument = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.getDocument(request), expectedError); - const actualRequest = (client.innerApiCalls.getDocument as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.getDocument as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + if ( + typeof process === 'object' && + typeof process.emitWarning === 'function' + ) { + it('throws DeprecationWarning if static servicePath is used', () => { + const stub = sinon.stub(process, 'emitWarning'); + const servicePath = firestoreModule.FirestoreClient.servicePath; + assert.strictEqual(servicePath, 'firestore.googleapis.com'); + assert(stub.called); + stub.restore(); + }); + + it('throws DeprecationWarning if static apiEndpoint is used', () => { + const stub = sinon.stub(process, 'emitWarning'); + const apiEndpoint = firestoreModule.FirestoreClient.apiEndpoint; + assert.strictEqual(apiEndpoint, 'firestore.googleapis.com'); + assert(stub.called); + stub.restore(); + }); + } + it('sets apiEndpoint according to universe domain camelCase', () => { + const client = new firestoreModule.FirestoreClient({ + universeDomain: 'example.com', + }); + const servicePath = client.apiEndpoint; + assert.strictEqual(servicePath, 'firestore.example.com'); + }); - it('invokes getDocument with closed client', async () => { - const client = new firestoreModule.FirestoreClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.firestore.v1.GetDocumentRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.firestore.v1.GetDocumentRequest', ['name']); - request.name = defaultValue1; - const expectedError = new Error('The client has already been closed.'); - client.close().catch(err => {throw err}); - await assert.rejects(client.getDocument(request), expectedError); - }); + it('sets apiEndpoint according to universe domain snakeCase', () => { + const client = new firestoreModule.FirestoreClient({ + universe_domain: 'example.com', + }); + const servicePath = client.apiEndpoint; + assert.strictEqual(servicePath, 'firestore.example.com'); }); - describe('updateDocument', () => { - it('invokes updateDocument without error', async () => { - const client = new firestoreModule.FirestoreClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.firestore.v1.UpdateDocumentRequest() - ); - request.document ??= {}; - const defaultValue1 = - getTypeDefaultValue('.google.firestore.v1.UpdateDocumentRequest', ['document', 'name']); - request.document.name = defaultValue1; - const expectedHeaderRequestParams = `document.name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.firestore.v1.Document() - ); - client.innerApiCalls.updateDocument = stubSimpleCall(expectedResponse); - const [response] = await client.updateDocument(request); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.updateDocument as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.updateDocument as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + if (typeof process === 'object' && 'env' in process) { + describe('GOOGLE_CLOUD_UNIVERSE_DOMAIN environment variable', () => { + it('sets apiEndpoint from environment variable', () => { + const saved = process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN']; + process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] = 'example.com'; + const client = new firestoreModule.FirestoreClient(); + const servicePath = client.apiEndpoint; + assert.strictEqual(servicePath, 'firestore.example.com'); + if (saved) { + process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] = saved; + } else { + delete process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN']; + } + }); + + it('value configured in code has priority over environment variable', () => { + const saved = process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN']; + process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] = 'example.com'; + const client = new firestoreModule.FirestoreClient({ + universeDomain: 'configured.example.com', + }); + const servicePath = client.apiEndpoint; + assert.strictEqual(servicePath, 'firestore.configured.example.com'); + if (saved) { + process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN'] = saved; + } else { + delete process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN']; + } + }); + }); + } + it('does not allow setting both universeDomain and universe_domain', () => { + assert.throws(() => { + new firestoreModule.FirestoreClient({ + universe_domain: 'example.com', + universeDomain: 'example.net', }); + }); + }); - it('invokes updateDocument without error using callback', async () => { - const client = new firestoreModule.FirestoreClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.firestore.v1.UpdateDocumentRequest() - ); - request.document ??= {}; - const defaultValue1 = - getTypeDefaultValue('.google.firestore.v1.UpdateDocumentRequest', ['document', 'name']); - request.document.name = defaultValue1; - const expectedHeaderRequestParams = `document.name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.firestore.v1.Document() - ); - client.innerApiCalls.updateDocument = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.updateDocument( - request, - (err?: Error|null, result?: protos.google.firestore.v1.IDocument|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.updateDocument as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.updateDocument as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('has port', () => { + const port = firestoreModule.FirestoreClient.port; + assert(port); + assert(typeof port === 'number'); + }); - it('invokes updateDocument with error', async () => { - const client = new firestoreModule.FirestoreClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.firestore.v1.UpdateDocumentRequest() - ); - request.document ??= {}; - const defaultValue1 = - getTypeDefaultValue('.google.firestore.v1.UpdateDocumentRequest', ['document', 'name']); - request.document.name = defaultValue1; - const expectedHeaderRequestParams = `document.name=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.updateDocument = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.updateDocument(request), expectedError); - const actualRequest = (client.innerApiCalls.updateDocument as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.updateDocument as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('should create a client with no option', () => { + const client = new firestoreModule.FirestoreClient(); + assert(client); + }); - it('invokes updateDocument with closed client', async () => { - const client = new firestoreModule.FirestoreClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.firestore.v1.UpdateDocumentRequest() - ); - request.document ??= {}; - const defaultValue1 = - getTypeDefaultValue('.google.firestore.v1.UpdateDocumentRequest', ['document', 'name']); - request.document.name = defaultValue1; - const expectedError = new Error('The client has already been closed.'); - client.close().catch(err => {throw err}); - await assert.rejects(client.updateDocument(request), expectedError); - }); + it('should create a client with gRPC fallback', () => { + const client = new firestoreModule.FirestoreClient({ + fallback: true, + }); + assert(client); }); - describe('deleteDocument', () => { - it('invokes deleteDocument without error', async () => { - const client = new firestoreModule.FirestoreClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.firestore.v1.DeleteDocumentRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.firestore.v1.DeleteDocumentRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.protobuf.Empty() - ); - client.innerApiCalls.deleteDocument = stubSimpleCall(expectedResponse); - const [response] = await client.deleteDocument(request); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.deleteDocument as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.deleteDocument as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('has initialize method and supports deferred initialization', async () => { + const client = new firestoreModule.FirestoreClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + assert.strictEqual(client.firestoreStub, undefined); + await client.initialize(); + assert(client.firestoreStub); + }); - it('invokes deleteDocument without error using callback', async () => { - const client = new firestoreModule.FirestoreClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.firestore.v1.DeleteDocumentRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.firestore.v1.DeleteDocumentRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.protobuf.Empty() - ); - client.innerApiCalls.deleteDocument = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.deleteDocument( - request, - (err?: Error|null, result?: protos.google.protobuf.IEmpty|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.deleteDocument as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.deleteDocument as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + it('has close method for the initialized client', done => { + const client = new firestoreModule.FirestoreClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + client.initialize().catch(err => { + throw err; + }); + assert(client.firestoreStub); + client + .close() + .then(() => { + done(); + }) + .catch(err => { + throw err; }); + }); - it('invokes deleteDocument with error', async () => { - const client = new firestoreModule.FirestoreClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.firestore.v1.DeleteDocumentRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.firestore.v1.DeleteDocumentRequest', ['name']); - request.name = defaultValue1; - const expectedHeaderRequestParams = `name=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.deleteDocument = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.deleteDocument(request), expectedError); - const actualRequest = (client.innerApiCalls.deleteDocument as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.deleteDocument as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + it('has close method for the non-initialized client', done => { + const client = new firestoreModule.FirestoreClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + assert.strictEqual(client.firestoreStub, undefined); + client + .close() + .then(() => { + done(); + }) + .catch(err => { + throw err; }); + }); - it('invokes deleteDocument with closed client', async () => { - const client = new firestoreModule.FirestoreClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.firestore.v1.DeleteDocumentRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.firestore.v1.DeleteDocumentRequest', ['name']); - request.name = defaultValue1; - const expectedError = new Error('The client has already been closed.'); - client.close().catch(err => {throw err}); - await assert.rejects(client.deleteDocument(request), expectedError); - }); + it('has getProjectId method', async () => { + const fakeProjectId = 'fake-project-id'; + const client = new firestoreModule.FirestoreClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + client.auth.getProjectId = sinon.stub().resolves(fakeProjectId); + const result = await client.getProjectId(); + assert.strictEqual(result, fakeProjectId); + assert((client.auth.getProjectId as SinonStub).calledWithExactly()); }); - describe('beginTransaction', () => { - it('invokes beginTransaction without error', async () => { - const client = new firestoreModule.FirestoreClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.firestore.v1.BeginTransactionRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.firestore.v1.BeginTransactionRequest', ['database']); - request.database = defaultValue1; - const expectedHeaderRequestParams = `database=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.firestore.v1.BeginTransactionResponse() - ); - client.innerApiCalls.beginTransaction = stubSimpleCall(expectedResponse); - const [response] = await client.beginTransaction(request); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.beginTransaction as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.beginTransaction as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('has getProjectId method with callback', async () => { + const fakeProjectId = 'fake-project-id'; + const client = new firestoreModule.FirestoreClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + client.auth.getProjectId = sinon + .stub() + .callsArgWith(0, null, fakeProjectId); + const promise = new Promise((resolve, reject) => { + client.getProjectId((err?: Error | null, projectId?: string | null) => { + if (err) { + reject(err); + } else { + resolve(projectId); + } + }); + }); + const result = await promise; + assert.strictEqual(result, fakeProjectId); + }); + }); + + describe('getDocument', () => { + it('invokes getDocument without error', async () => { + const client = new firestoreModule.FirestoreClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.firestore.v1.GetDocumentRequest() + ); + const defaultValue1 = getTypeDefaultValue( + '.google.firestore.v1.GetDocumentRequest', + ['name'] + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.firestore.v1.Document() + ); + client.innerApiCalls.getDocument = stubSimpleCall(expectedResponse); + const [response] = await client.getDocument(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.getDocument as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.getDocument as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes beginTransaction without error using callback', async () => { - const client = new firestoreModule.FirestoreClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.firestore.v1.BeginTransactionRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.firestore.v1.BeginTransactionRequest', ['database']); - request.database = defaultValue1; - const expectedHeaderRequestParams = `database=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.firestore.v1.BeginTransactionResponse() - ); - client.innerApiCalls.beginTransaction = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.beginTransaction( - request, - (err?: Error|null, result?: protos.google.firestore.v1.IBeginTransactionResponse|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.beginTransaction as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.beginTransaction as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes getDocument without error using callback', async () => { + const client = new firestoreModule.FirestoreClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.firestore.v1.GetDocumentRequest() + ); + const defaultValue1 = getTypeDefaultValue( + '.google.firestore.v1.GetDocumentRequest', + ['name'] + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.firestore.v1.Document() + ); + client.innerApiCalls.getDocument = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.getDocument( + request, + ( + err?: Error | null, + result?: protos.google.firestore.v1.IDocument | null + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + } + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.getDocument as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.getDocument as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes beginTransaction with error', async () => { - const client = new firestoreModule.FirestoreClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.firestore.v1.BeginTransactionRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.firestore.v1.BeginTransactionRequest', ['database']); - request.database = defaultValue1; - const expectedHeaderRequestParams = `database=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.beginTransaction = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.beginTransaction(request), expectedError); - const actualRequest = (client.innerApiCalls.beginTransaction as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.beginTransaction as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes getDocument with error', async () => { + const client = new firestoreModule.FirestoreClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.firestore.v1.GetDocumentRequest() + ); + const defaultValue1 = getTypeDefaultValue( + '.google.firestore.v1.GetDocumentRequest', + ['name'] + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.getDocument = stubSimpleCall( + undefined, + expectedError + ); + await assert.rejects(client.getDocument(request), expectedError); + const actualRequest = ( + client.innerApiCalls.getDocument as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.getDocument as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes beginTransaction with closed client', async () => { - const client = new firestoreModule.FirestoreClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.firestore.v1.BeginTransactionRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.firestore.v1.BeginTransactionRequest', ['database']); - request.database = defaultValue1; - const expectedError = new Error('The client has already been closed.'); - client.close().catch(err => {throw err}); - await assert.rejects(client.beginTransaction(request), expectedError); - }); + it('invokes getDocument with closed client', async () => { + const client = new firestoreModule.FirestoreClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.firestore.v1.GetDocumentRequest() + ); + const defaultValue1 = getTypeDefaultValue( + '.google.firestore.v1.GetDocumentRequest', + ['name'] + ); + request.name = defaultValue1; + const expectedError = new Error('The client has already been closed.'); + client.close().catch(err => { + throw err; + }); + await assert.rejects(client.getDocument(request), expectedError); + }); + }); + + describe('updateDocument', () => { + it('invokes updateDocument without error', async () => { + const client = new firestoreModule.FirestoreClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.firestore.v1.UpdateDocumentRequest() + ); + request.document ??= {}; + const defaultValue1 = getTypeDefaultValue( + '.google.firestore.v1.UpdateDocumentRequest', + ['document', 'name'] + ); + request.document.name = defaultValue1; + const expectedHeaderRequestParams = `document.name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.firestore.v1.Document() + ); + client.innerApiCalls.updateDocument = stubSimpleCall(expectedResponse); + const [response] = await client.updateDocument(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.updateDocument as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.updateDocument as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); }); - describe('commit', () => { - it('invokes commit without error', async () => { - const client = new firestoreModule.FirestoreClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.firestore.v1.CommitRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.firestore.v1.CommitRequest', ['database']); - request.database = defaultValue1; - const expectedHeaderRequestParams = `database=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.firestore.v1.CommitResponse() - ); - client.innerApiCalls.commit = stubSimpleCall(expectedResponse); - const [response] = await client.commit(request); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.commit as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.commit as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes updateDocument without error using callback', async () => { + const client = new firestoreModule.FirestoreClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.firestore.v1.UpdateDocumentRequest() + ); + request.document ??= {}; + const defaultValue1 = getTypeDefaultValue( + '.google.firestore.v1.UpdateDocumentRequest', + ['document', 'name'] + ); + request.document.name = defaultValue1; + const expectedHeaderRequestParams = `document.name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.firestore.v1.Document() + ); + client.innerApiCalls.updateDocument = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.updateDocument( + request, + ( + err?: Error | null, + result?: protos.google.firestore.v1.IDocument | null + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + } + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.updateDocument as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.updateDocument as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes commit without error using callback', async () => { - const client = new firestoreModule.FirestoreClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.firestore.v1.CommitRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.firestore.v1.CommitRequest', ['database']); - request.database = defaultValue1; - const expectedHeaderRequestParams = `database=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.firestore.v1.CommitResponse() - ); - client.innerApiCalls.commit = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.commit( - request, - (err?: Error|null, result?: protos.google.firestore.v1.ICommitResponse|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.commit as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.commit as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes updateDocument with error', async () => { + const client = new firestoreModule.FirestoreClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.firestore.v1.UpdateDocumentRequest() + ); + request.document ??= {}; + const defaultValue1 = getTypeDefaultValue( + '.google.firestore.v1.UpdateDocumentRequest', + ['document', 'name'] + ); + request.document.name = defaultValue1; + const expectedHeaderRequestParams = `document.name=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.updateDocument = stubSimpleCall( + undefined, + expectedError + ); + await assert.rejects(client.updateDocument(request), expectedError); + const actualRequest = ( + client.innerApiCalls.updateDocument as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.updateDocument as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes commit with error', async () => { - const client = new firestoreModule.FirestoreClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.firestore.v1.CommitRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.firestore.v1.CommitRequest', ['database']); - request.database = defaultValue1; - const expectedHeaderRequestParams = `database=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.commit = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.commit(request), expectedError); - const actualRequest = (client.innerApiCalls.commit as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.commit as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes updateDocument with closed client', async () => { + const client = new firestoreModule.FirestoreClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.firestore.v1.UpdateDocumentRequest() + ); + request.document ??= {}; + const defaultValue1 = getTypeDefaultValue( + '.google.firestore.v1.UpdateDocumentRequest', + ['document', 'name'] + ); + request.document.name = defaultValue1; + const expectedError = new Error('The client has already been closed.'); + client.close().catch(err => { + throw err; + }); + await assert.rejects(client.updateDocument(request), expectedError); + }); + }); + + describe('deleteDocument', () => { + it('invokes deleteDocument without error', async () => { + const client = new firestoreModule.FirestoreClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.firestore.v1.DeleteDocumentRequest() + ); + const defaultValue1 = getTypeDefaultValue( + '.google.firestore.v1.DeleteDocumentRequest', + ['name'] + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.protobuf.Empty() + ); + client.innerApiCalls.deleteDocument = stubSimpleCall(expectedResponse); + const [response] = await client.deleteDocument(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.deleteDocument as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.deleteDocument as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes commit with closed client', async () => { - const client = new firestoreModule.FirestoreClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.firestore.v1.CommitRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.firestore.v1.CommitRequest', ['database']); - request.database = defaultValue1; - const expectedError = new Error('The client has already been closed.'); - client.close().catch(err => {throw err}); - await assert.rejects(client.commit(request), expectedError); - }); + it('invokes deleteDocument without error using callback', async () => { + const client = new firestoreModule.FirestoreClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.firestore.v1.DeleteDocumentRequest() + ); + const defaultValue1 = getTypeDefaultValue( + '.google.firestore.v1.DeleteDocumentRequest', + ['name'] + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.protobuf.Empty() + ); + client.innerApiCalls.deleteDocument = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.deleteDocument( + request, + ( + err?: Error | null, + result?: protos.google.protobuf.IEmpty | null + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + } + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.deleteDocument as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.deleteDocument as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); }); - describe('rollback', () => { - it('invokes rollback without error', async () => { - const client = new firestoreModule.FirestoreClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.firestore.v1.RollbackRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.firestore.v1.RollbackRequest', ['database']); - request.database = defaultValue1; - const expectedHeaderRequestParams = `database=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.protobuf.Empty() - ); - client.innerApiCalls.rollback = stubSimpleCall(expectedResponse); - const [response] = await client.rollback(request); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.rollback as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.rollback as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes deleteDocument with error', async () => { + const client = new firestoreModule.FirestoreClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.firestore.v1.DeleteDocumentRequest() + ); + const defaultValue1 = getTypeDefaultValue( + '.google.firestore.v1.DeleteDocumentRequest', + ['name'] + ); + request.name = defaultValue1; + const expectedHeaderRequestParams = `name=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.deleteDocument = stubSimpleCall( + undefined, + expectedError + ); + await assert.rejects(client.deleteDocument(request), expectedError); + const actualRequest = ( + client.innerApiCalls.deleteDocument as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.deleteDocument as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes rollback without error using callback', async () => { - const client = new firestoreModule.FirestoreClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.firestore.v1.RollbackRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.firestore.v1.RollbackRequest', ['database']); - request.database = defaultValue1; - const expectedHeaderRequestParams = `database=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.protobuf.Empty() - ); - client.innerApiCalls.rollback = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.rollback( - request, - (err?: Error|null, result?: protos.google.protobuf.IEmpty|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.rollback as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.rollback as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes deleteDocument with closed client', async () => { + const client = new firestoreModule.FirestoreClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.firestore.v1.DeleteDocumentRequest() + ); + const defaultValue1 = getTypeDefaultValue( + '.google.firestore.v1.DeleteDocumentRequest', + ['name'] + ); + request.name = defaultValue1; + const expectedError = new Error('The client has already been closed.'); + client.close().catch(err => { + throw err; + }); + await assert.rejects(client.deleteDocument(request), expectedError); + }); + }); + + describe('beginTransaction', () => { + it('invokes beginTransaction without error', async () => { + const client = new firestoreModule.FirestoreClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.firestore.v1.BeginTransactionRequest() + ); + const defaultValue1 = getTypeDefaultValue( + '.google.firestore.v1.BeginTransactionRequest', + ['database'] + ); + request.database = defaultValue1; + const expectedHeaderRequestParams = `database=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.firestore.v1.BeginTransactionResponse() + ); + client.innerApiCalls.beginTransaction = stubSimpleCall(expectedResponse); + const [response] = await client.beginTransaction(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.beginTransaction as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.beginTransaction as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes rollback with error', async () => { - const client = new firestoreModule.FirestoreClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.firestore.v1.RollbackRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.firestore.v1.RollbackRequest', ['database']); - request.database = defaultValue1; - const expectedHeaderRequestParams = `database=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.rollback = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.rollback(request), expectedError); - const actualRequest = (client.innerApiCalls.rollback as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.rollback as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes beginTransaction without error using callback', async () => { + const client = new firestoreModule.FirestoreClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.firestore.v1.BeginTransactionRequest() + ); + const defaultValue1 = getTypeDefaultValue( + '.google.firestore.v1.BeginTransactionRequest', + ['database'] + ); + request.database = defaultValue1; + const expectedHeaderRequestParams = `database=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.firestore.v1.BeginTransactionResponse() + ); + client.innerApiCalls.beginTransaction = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.beginTransaction( + request, + ( + err?: Error | null, + result?: protos.google.firestore.v1.IBeginTransactionResponse | null + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + } + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.beginTransaction as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.beginTransaction as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes rollback with closed client', async () => { - const client = new firestoreModule.FirestoreClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.firestore.v1.RollbackRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.firestore.v1.RollbackRequest', ['database']); - request.database = defaultValue1; - const expectedError = new Error('The client has already been closed.'); - client.close().catch(err => {throw err}); - await assert.rejects(client.rollback(request), expectedError); - }); + it('invokes beginTransaction with error', async () => { + const client = new firestoreModule.FirestoreClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.firestore.v1.BeginTransactionRequest() + ); + const defaultValue1 = getTypeDefaultValue( + '.google.firestore.v1.BeginTransactionRequest', + ['database'] + ); + request.database = defaultValue1; + const expectedHeaderRequestParams = `database=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.beginTransaction = stubSimpleCall( + undefined, + expectedError + ); + await assert.rejects(client.beginTransaction(request), expectedError); + const actualRequest = ( + client.innerApiCalls.beginTransaction as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.beginTransaction as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); }); - describe('batchWrite', () => { - it('invokes batchWrite without error', async () => { - const client = new firestoreModule.FirestoreClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.firestore.v1.BatchWriteRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.firestore.v1.BatchWriteRequest', ['database']); - request.database = defaultValue1; - const expectedHeaderRequestParams = `database=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.firestore.v1.BatchWriteResponse() - ); - client.innerApiCalls.batchWrite = stubSimpleCall(expectedResponse); - const [response] = await client.batchWrite(request); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.batchWrite as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.batchWrite as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes beginTransaction with closed client', async () => { + const client = new firestoreModule.FirestoreClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.firestore.v1.BeginTransactionRequest() + ); + const defaultValue1 = getTypeDefaultValue( + '.google.firestore.v1.BeginTransactionRequest', + ['database'] + ); + request.database = defaultValue1; + const expectedError = new Error('The client has already been closed.'); + client.close().catch(err => { + throw err; + }); + await assert.rejects(client.beginTransaction(request), expectedError); + }); + }); + + describe('commit', () => { + it('invokes commit without error', async () => { + const client = new firestoreModule.FirestoreClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.firestore.v1.CommitRequest() + ); + const defaultValue1 = getTypeDefaultValue( + '.google.firestore.v1.CommitRequest', + ['database'] + ); + request.database = defaultValue1; + const expectedHeaderRequestParams = `database=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.firestore.v1.CommitResponse() + ); + client.innerApiCalls.commit = stubSimpleCall(expectedResponse); + const [response] = await client.commit(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = (client.innerApiCalls.commit as SinonStub).getCall( + 0 + ).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.commit as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes batchWrite without error using callback', async () => { - const client = new firestoreModule.FirestoreClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.firestore.v1.BatchWriteRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.firestore.v1.BatchWriteRequest', ['database']); - request.database = defaultValue1; - const expectedHeaderRequestParams = `database=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.firestore.v1.BatchWriteResponse() - ); - client.innerApiCalls.batchWrite = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.batchWrite( - request, - (err?: Error|null, result?: protos.google.firestore.v1.IBatchWriteResponse|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.batchWrite as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.batchWrite as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes commit without error using callback', async () => { + const client = new firestoreModule.FirestoreClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.firestore.v1.CommitRequest() + ); + const defaultValue1 = getTypeDefaultValue( + '.google.firestore.v1.CommitRequest', + ['database'] + ); + request.database = defaultValue1; + const expectedHeaderRequestParams = `database=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.firestore.v1.CommitResponse() + ); + client.innerApiCalls.commit = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.commit( + request, + ( + err?: Error | null, + result?: protos.google.firestore.v1.ICommitResponse | null + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + } + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = (client.innerApiCalls.commit as SinonStub).getCall( + 0 + ).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.commit as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes batchWrite with error', async () => { - const client = new firestoreModule.FirestoreClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.firestore.v1.BatchWriteRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.firestore.v1.BatchWriteRequest', ['database']); - request.database = defaultValue1; - const expectedHeaderRequestParams = `database=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.batchWrite = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.batchWrite(request), expectedError); - const actualRequest = (client.innerApiCalls.batchWrite as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.batchWrite as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes commit with error', async () => { + const client = new firestoreModule.FirestoreClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.firestore.v1.CommitRequest() + ); + const defaultValue1 = getTypeDefaultValue( + '.google.firestore.v1.CommitRequest', + ['database'] + ); + request.database = defaultValue1; + const expectedHeaderRequestParams = `database=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.commit = stubSimpleCall(undefined, expectedError); + await assert.rejects(client.commit(request), expectedError); + const actualRequest = (client.innerApiCalls.commit as SinonStub).getCall( + 0 + ).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.commit as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes batchWrite with closed client', async () => { - const client = new firestoreModule.FirestoreClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.firestore.v1.BatchWriteRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.firestore.v1.BatchWriteRequest', ['database']); - request.database = defaultValue1; - const expectedError = new Error('The client has already been closed.'); - client.close().catch(err => {throw err}); - await assert.rejects(client.batchWrite(request), expectedError); - }); + it('invokes commit with closed client', async () => { + const client = new firestoreModule.FirestoreClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.firestore.v1.CommitRequest() + ); + const defaultValue1 = getTypeDefaultValue( + '.google.firestore.v1.CommitRequest', + ['database'] + ); + request.database = defaultValue1; + const expectedError = new Error('The client has already been closed.'); + client.close().catch(err => { + throw err; + }); + await assert.rejects(client.commit(request), expectedError); + }); + }); + + describe('rollback', () => { + it('invokes rollback without error', async () => { + const client = new firestoreModule.FirestoreClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.firestore.v1.RollbackRequest() + ); + const defaultValue1 = getTypeDefaultValue( + '.google.firestore.v1.RollbackRequest', + ['database'] + ); + request.database = defaultValue1; + const expectedHeaderRequestParams = `database=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.protobuf.Empty() + ); + client.innerApiCalls.rollback = stubSimpleCall(expectedResponse); + const [response] = await client.rollback(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.rollback as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.rollback as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); }); - describe('createDocument', () => { - it('invokes createDocument without error', async () => { - const client = new firestoreModule.FirestoreClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.firestore.v1.CreateDocumentRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.firestore.v1.CreateDocumentRequest', ['parent']); - request.parent = defaultValue1; - const defaultValue2 = - getTypeDefaultValue('.google.firestore.v1.CreateDocumentRequest', ['collectionId']); - request.collectionId = defaultValue2; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }&collection_id=${defaultValue2 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.firestore.v1.Document() - ); - client.innerApiCalls.createDocument = stubSimpleCall(expectedResponse); - const [response] = await client.createDocument(request); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.createDocument as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.createDocument as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes rollback without error using callback', async () => { + const client = new firestoreModule.FirestoreClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.firestore.v1.RollbackRequest() + ); + const defaultValue1 = getTypeDefaultValue( + '.google.firestore.v1.RollbackRequest', + ['database'] + ); + request.database = defaultValue1; + const expectedHeaderRequestParams = `database=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.protobuf.Empty() + ); + client.innerApiCalls.rollback = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.rollback( + request, + ( + err?: Error | null, + result?: protos.google.protobuf.IEmpty | null + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + } + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.rollback as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.rollback as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes createDocument without error using callback', async () => { - const client = new firestoreModule.FirestoreClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.firestore.v1.CreateDocumentRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.firestore.v1.CreateDocumentRequest', ['parent']); - request.parent = defaultValue1; - const defaultValue2 = - getTypeDefaultValue('.google.firestore.v1.CreateDocumentRequest', ['collectionId']); - request.collectionId = defaultValue2; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }&collection_id=${defaultValue2 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.firestore.v1.Document() - ); - client.innerApiCalls.createDocument = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.createDocument( - request, - (err?: Error|null, result?: protos.google.firestore.v1.IDocument|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.createDocument as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.createDocument as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes rollback with error', async () => { + const client = new firestoreModule.FirestoreClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.firestore.v1.RollbackRequest() + ); + const defaultValue1 = getTypeDefaultValue( + '.google.firestore.v1.RollbackRequest', + ['database'] + ); + request.database = defaultValue1; + const expectedHeaderRequestParams = `database=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.rollback = stubSimpleCall(undefined, expectedError); + await assert.rejects(client.rollback(request), expectedError); + const actualRequest = ( + client.innerApiCalls.rollback as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.rollback as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes createDocument with error', async () => { - const client = new firestoreModule.FirestoreClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.firestore.v1.CreateDocumentRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.firestore.v1.CreateDocumentRequest', ['parent']); - request.parent = defaultValue1; - const defaultValue2 = - getTypeDefaultValue('.google.firestore.v1.CreateDocumentRequest', ['collectionId']); - request.collectionId = defaultValue2; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }&collection_id=${defaultValue2 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.createDocument = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.createDocument(request), expectedError); - const actualRequest = (client.innerApiCalls.createDocument as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.createDocument as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes rollback with closed client', async () => { + const client = new firestoreModule.FirestoreClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.firestore.v1.RollbackRequest() + ); + const defaultValue1 = getTypeDefaultValue( + '.google.firestore.v1.RollbackRequest', + ['database'] + ); + request.database = defaultValue1; + const expectedError = new Error('The client has already been closed.'); + client.close().catch(err => { + throw err; + }); + await assert.rejects(client.rollback(request), expectedError); + }); + }); + + describe('batchWrite', () => { + it('invokes batchWrite without error', async () => { + const client = new firestoreModule.FirestoreClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.firestore.v1.BatchWriteRequest() + ); + const defaultValue1 = getTypeDefaultValue( + '.google.firestore.v1.BatchWriteRequest', + ['database'] + ); + request.database = defaultValue1; + const expectedHeaderRequestParams = `database=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.firestore.v1.BatchWriteResponse() + ); + client.innerApiCalls.batchWrite = stubSimpleCall(expectedResponse); + const [response] = await client.batchWrite(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.batchWrite as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.batchWrite as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes createDocument with closed client', async () => { - const client = new firestoreModule.FirestoreClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.firestore.v1.CreateDocumentRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.firestore.v1.CreateDocumentRequest', ['parent']); - request.parent = defaultValue1; - const defaultValue2 = - getTypeDefaultValue('.google.firestore.v1.CreateDocumentRequest', ['collectionId']); - request.collectionId = defaultValue2; - const expectedError = new Error('The client has already been closed.'); - client.close().catch(err => {throw err}); - await assert.rejects(client.createDocument(request), expectedError); - }); + it('invokes batchWrite without error using callback', async () => { + const client = new firestoreModule.FirestoreClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.firestore.v1.BatchWriteRequest() + ); + const defaultValue1 = getTypeDefaultValue( + '.google.firestore.v1.BatchWriteRequest', + ['database'] + ); + request.database = defaultValue1; + const expectedHeaderRequestParams = `database=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.firestore.v1.BatchWriteResponse() + ); + client.innerApiCalls.batchWrite = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.batchWrite( + request, + ( + err?: Error | null, + result?: protos.google.firestore.v1.IBatchWriteResponse | null + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + } + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.batchWrite as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.batchWrite as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); }); - describe('batchGetDocuments', () => { - it('invokes batchGetDocuments without error', async () => { - const client = new firestoreModule.FirestoreClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.firestore.v1.BatchGetDocumentsRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.firestore.v1.BatchGetDocumentsRequest', ['database']); - request.database = defaultValue1; - const expectedHeaderRequestParams = `database=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.firestore.v1.BatchGetDocumentsResponse() - ); - client.innerApiCalls.batchGetDocuments = stubServerStreamingCall(expectedResponse); - const stream = client.batchGetDocuments(request); - const promise = new Promise((resolve, reject) => { - stream.on('data', (response: protos.google.firestore.v1.BatchGetDocumentsResponse) => { - resolve(response); - }); - stream.on('error', (err: Error) => { - reject(err); - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.batchGetDocuments as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.batchGetDocuments as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes batchWrite with error', async () => { + const client = new firestoreModule.FirestoreClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.firestore.v1.BatchWriteRequest() + ); + const defaultValue1 = getTypeDefaultValue( + '.google.firestore.v1.BatchWriteRequest', + ['database'] + ); + request.database = defaultValue1; + const expectedHeaderRequestParams = `database=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.batchWrite = stubSimpleCall( + undefined, + expectedError + ); + await assert.rejects(client.batchWrite(request), expectedError); + const actualRequest = ( + client.innerApiCalls.batchWrite as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.batchWrite as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes batchGetDocuments without error and gaxServerStreamingRetries enabled', async () => { - const client = new firestoreModule.FirestoreClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - gaxServerStreamingRetries: true - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.firestore.v1.BatchGetDocumentsRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.firestore.v1.BatchGetDocumentsRequest', ['database']); - request.database = defaultValue1; - const expectedHeaderRequestParams = `database=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.firestore.v1.BatchGetDocumentsResponse() - ); - client.innerApiCalls.batchGetDocuments = stubServerStreamingCall(expectedResponse); - const stream = client.batchGetDocuments(request); - const promise = new Promise((resolve, reject) => { - stream.on('data', (response: protos.google.firestore.v1.BatchGetDocumentsResponse) => { - resolve(response); - }); - stream.on('error', (err: Error) => { - reject(err); - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.batchGetDocuments as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.batchGetDocuments as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes batchWrite with closed client', async () => { + const client = new firestoreModule.FirestoreClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.firestore.v1.BatchWriteRequest() + ); + const defaultValue1 = getTypeDefaultValue( + '.google.firestore.v1.BatchWriteRequest', + ['database'] + ); + request.database = defaultValue1; + const expectedError = new Error('The client has already been closed.'); + client.close().catch(err => { + throw err; + }); + await assert.rejects(client.batchWrite(request), expectedError); + }); + }); + + describe('createDocument', () => { + it('invokes createDocument without error', async () => { + const client = new firestoreModule.FirestoreClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.firestore.v1.CreateDocumentRequest() + ); + const defaultValue1 = getTypeDefaultValue( + '.google.firestore.v1.CreateDocumentRequest', + ['parent'] + ); + request.parent = defaultValue1; + const defaultValue2 = getTypeDefaultValue( + '.google.firestore.v1.CreateDocumentRequest', + ['collectionId'] + ); + request.collectionId = defaultValue2; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}&collection_id=${defaultValue2 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.firestore.v1.Document() + ); + client.innerApiCalls.createDocument = stubSimpleCall(expectedResponse); + const [response] = await client.createDocument(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.createDocument as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.createDocument as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes batchGetDocuments with error', async () => { - const client = new firestoreModule.FirestoreClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.firestore.v1.BatchGetDocumentsRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.firestore.v1.BatchGetDocumentsRequest', ['database']); - request.database = defaultValue1; - const expectedHeaderRequestParams = `database=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.batchGetDocuments = stubServerStreamingCall(undefined, expectedError); - const stream = client.batchGetDocuments(request); - const promise = new Promise((resolve, reject) => { - stream.on('data', (response: protos.google.firestore.v1.BatchGetDocumentsResponse) => { - resolve(response); - }); - stream.on('error', (err: Error) => { - reject(err); - }); - }); - await assert.rejects(promise, expectedError); - const actualRequest = (client.innerApiCalls.batchGetDocuments as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.batchGetDocuments as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes createDocument without error using callback', async () => { + const client = new firestoreModule.FirestoreClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.firestore.v1.CreateDocumentRequest() + ); + const defaultValue1 = getTypeDefaultValue( + '.google.firestore.v1.CreateDocumentRequest', + ['parent'] + ); + request.parent = defaultValue1; + const defaultValue2 = getTypeDefaultValue( + '.google.firestore.v1.CreateDocumentRequest', + ['collectionId'] + ); + request.collectionId = defaultValue2; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}&collection_id=${defaultValue2 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.firestore.v1.Document() + ); + client.innerApiCalls.createDocument = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.createDocument( + request, + ( + err?: Error | null, + result?: protos.google.firestore.v1.IDocument | null + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + } + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.createDocument as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.createDocument as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes batchGetDocuments with closed client', async () => { - const client = new firestoreModule.FirestoreClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.firestore.v1.BatchGetDocumentsRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.firestore.v1.BatchGetDocumentsRequest', ['database']); - request.database = defaultValue1; - const expectedError = new Error('The client has already been closed.'); - client.close().catch(err => {throw err}); - const stream = client.batchGetDocuments(request, {retryRequestOptions: {noResponseRetries: 0}}); - const promise = new Promise((resolve, reject) => { - stream.on('data', (response: protos.google.firestore.v1.BatchGetDocumentsResponse) => { - resolve(response); - }); - stream.on('error', (err: Error) => { - reject(err); - }); - }); - await assert.rejects(promise, expectedError); - }); - it('should create a client with gaxServerStreamingRetries enabled', () => { - const client = new firestoreModule.FirestoreClient({ - gaxServerStreamingRetries: true, - }); - assert(client); - }); + it('invokes createDocument with error', async () => { + const client = new firestoreModule.FirestoreClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.firestore.v1.CreateDocumentRequest() + ); + const defaultValue1 = getTypeDefaultValue( + '.google.firestore.v1.CreateDocumentRequest', + ['parent'] + ); + request.parent = defaultValue1; + const defaultValue2 = getTypeDefaultValue( + '.google.firestore.v1.CreateDocumentRequest', + ['collectionId'] + ); + request.collectionId = defaultValue2; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}&collection_id=${defaultValue2 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.createDocument = stubSimpleCall( + undefined, + expectedError + ); + await assert.rejects(client.createDocument(request), expectedError); + const actualRequest = ( + client.innerApiCalls.createDocument as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.createDocument as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); }); - describe('runQuery', () => { - it('invokes runQuery without error', async () => { - const client = new firestoreModule.FirestoreClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.firestore.v1.RunQueryRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.firestore.v1.RunQueryRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.firestore.v1.RunQueryResponse() - ); - client.innerApiCalls.runQuery = stubServerStreamingCall(expectedResponse); - const stream = client.runQuery(request); - const promise = new Promise((resolve, reject) => { - stream.on('data', (response: protos.google.firestore.v1.RunQueryResponse) => { - resolve(response); - }); - stream.on('error', (err: Error) => { - reject(err); - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.runQuery as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.runQuery as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes createDocument with closed client', async () => { + const client = new firestoreModule.FirestoreClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.firestore.v1.CreateDocumentRequest() + ); + const defaultValue1 = getTypeDefaultValue( + '.google.firestore.v1.CreateDocumentRequest', + ['parent'] + ); + request.parent = defaultValue1; + const defaultValue2 = getTypeDefaultValue( + '.google.firestore.v1.CreateDocumentRequest', + ['collectionId'] + ); + request.collectionId = defaultValue2; + const expectedError = new Error('The client has already been closed.'); + client.close().catch(err => { + throw err; + }); + await assert.rejects(client.createDocument(request), expectedError); + }); + }); + + describe('batchGetDocuments', () => { + it('invokes batchGetDocuments without error', async () => { + const client = new firestoreModule.FirestoreClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.firestore.v1.BatchGetDocumentsRequest() + ); + const defaultValue1 = getTypeDefaultValue( + '.google.firestore.v1.BatchGetDocumentsRequest', + ['database'] + ); + request.database = defaultValue1; + const expectedHeaderRequestParams = `database=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.firestore.v1.BatchGetDocumentsResponse() + ); + client.innerApiCalls.batchGetDocuments = + stubServerStreamingCall(expectedResponse); + const stream = client.batchGetDocuments(request); + const promise = new Promise((resolve, reject) => { + stream.on( + 'data', + (response: protos.google.firestore.v1.BatchGetDocumentsResponse) => { + resolve(response); + } + ); + stream.on('error', (err: Error) => { + reject(err); + }); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.batchGetDocuments as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.batchGetDocuments as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes runQuery without error and gaxServerStreamingRetries enabled', async () => { - const client = new firestoreModule.FirestoreClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - gaxServerStreamingRetries: true - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.firestore.v1.RunQueryRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.firestore.v1.RunQueryRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.firestore.v1.RunQueryResponse() - ); - client.innerApiCalls.runQuery = stubServerStreamingCall(expectedResponse); - const stream = client.runQuery(request); - const promise = new Promise((resolve, reject) => { - stream.on('data', (response: protos.google.firestore.v1.RunQueryResponse) => { - resolve(response); - }); - stream.on('error', (err: Error) => { - reject(err); - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.runQuery as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.runQuery as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes batchGetDocuments without error and gaxServerStreamingRetries enabled', async () => { + const client = new firestoreModule.FirestoreClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + gaxServerStreamingRetries: true, + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.firestore.v1.BatchGetDocumentsRequest() + ); + const defaultValue1 = getTypeDefaultValue( + '.google.firestore.v1.BatchGetDocumentsRequest', + ['database'] + ); + request.database = defaultValue1; + const expectedHeaderRequestParams = `database=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.firestore.v1.BatchGetDocumentsResponse() + ); + client.innerApiCalls.batchGetDocuments = + stubServerStreamingCall(expectedResponse); + const stream = client.batchGetDocuments(request); + const promise = new Promise((resolve, reject) => { + stream.on( + 'data', + (response: protos.google.firestore.v1.BatchGetDocumentsResponse) => { + resolve(response); + } + ); + stream.on('error', (err: Error) => { + reject(err); + }); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.batchGetDocuments as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.batchGetDocuments as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes runQuery with error', async () => { - const client = new firestoreModule.FirestoreClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.firestore.v1.RunQueryRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.firestore.v1.RunQueryRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.runQuery = stubServerStreamingCall(undefined, expectedError); - const stream = client.runQuery(request); - const promise = new Promise((resolve, reject) => { - stream.on('data', (response: protos.google.firestore.v1.RunQueryResponse) => { - resolve(response); - }); - stream.on('error', (err: Error) => { - reject(err); - }); - }); - await assert.rejects(promise, expectedError); - const actualRequest = (client.innerApiCalls.runQuery as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.runQuery as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes batchGetDocuments with error', async () => { + const client = new firestoreModule.FirestoreClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.firestore.v1.BatchGetDocumentsRequest() + ); + const defaultValue1 = getTypeDefaultValue( + '.google.firestore.v1.BatchGetDocumentsRequest', + ['database'] + ); + request.database = defaultValue1; + const expectedHeaderRequestParams = `database=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.batchGetDocuments = stubServerStreamingCall( + undefined, + expectedError + ); + const stream = client.batchGetDocuments(request); + const promise = new Promise((resolve, reject) => { + stream.on( + 'data', + (response: protos.google.firestore.v1.BatchGetDocumentsResponse) => { + resolve(response); + } + ); + stream.on('error', (err: Error) => { + reject(err); + }); + }); + await assert.rejects(promise, expectedError); + const actualRequest = ( + client.innerApiCalls.batchGetDocuments as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.batchGetDocuments as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes runQuery with closed client', async () => { - const client = new firestoreModule.FirestoreClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.firestore.v1.RunQueryRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.firestore.v1.RunQueryRequest', ['parent']); - request.parent = defaultValue1; - const expectedError = new Error('The client has already been closed.'); - client.close().catch(err => {throw err}); - const stream = client.runQuery(request, {retryRequestOptions: {noResponseRetries: 0}}); - const promise = new Promise((resolve, reject) => { - stream.on('data', (response: protos.google.firestore.v1.RunQueryResponse) => { - resolve(response); - }); - stream.on('error', (err: Error) => { - reject(err); - }); - }); - await assert.rejects(promise, expectedError); - }); - it('should create a client with gaxServerStreamingRetries enabled', () => { - const client = new firestoreModule.FirestoreClient({ - gaxServerStreamingRetries: true, - }); - assert(client); - }); + it('invokes batchGetDocuments with closed client', async () => { + const client = new firestoreModule.FirestoreClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.firestore.v1.BatchGetDocumentsRequest() + ); + const defaultValue1 = getTypeDefaultValue( + '.google.firestore.v1.BatchGetDocumentsRequest', + ['database'] + ); + request.database = defaultValue1; + const expectedError = new Error('The client has already been closed.'); + client.close().catch(err => { + throw err; + }); + const stream = client.batchGetDocuments(request, { + retryRequestOptions: {noResponseRetries: 0}, + }); + const promise = new Promise((resolve, reject) => { + stream.on( + 'data', + (response: protos.google.firestore.v1.BatchGetDocumentsResponse) => { + resolve(response); + } + ); + stream.on('error', (err: Error) => { + reject(err); + }); + }); + await assert.rejects(promise, expectedError); + }); + it('should create a client with gaxServerStreamingRetries enabled', () => { + const client = new firestoreModule.FirestoreClient({ + gaxServerStreamingRetries: true, + }); + assert(client); + }); + }); + + describe('runQuery', () => { + it('invokes runQuery without error', async () => { + const client = new firestoreModule.FirestoreClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.firestore.v1.RunQueryRequest() + ); + const defaultValue1 = getTypeDefaultValue( + '.google.firestore.v1.RunQueryRequest', + ['parent'] + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.firestore.v1.RunQueryResponse() + ); + client.innerApiCalls.runQuery = stubServerStreamingCall(expectedResponse); + const stream = client.runQuery(request); + const promise = new Promise((resolve, reject) => { + stream.on( + 'data', + (response: protos.google.firestore.v1.RunQueryResponse) => { + resolve(response); + } + ); + stream.on('error', (err: Error) => { + reject(err); + }); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.runQuery as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.runQuery as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); }); - describe('executePipeline', () => { - it('invokes executePipeline without error', async () => { - const client = new firestoreModule.FirestoreClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.firestore.v1.ExecutePipelineRequest() - ); - // path template: projects/*/databases/{database_id=*}/** - request.database = 'projects/value/databases/value/value'; - const expectedHeaderRequestParams = 'database_id=value'; - const expectedResponse = generateSampleMessage( - new protos.google.firestore.v1.ExecutePipelineResponse() - ); - client.innerApiCalls.executePipeline = stubServerStreamingCall(expectedResponse); - const stream = client.executePipeline(request); - const promise = new Promise((resolve, reject) => { - stream.on('data', (response: protos.google.firestore.v1.ExecutePipelineResponse) => { - resolve(response); - }); - stream.on('error', (err: Error) => { - reject(err); - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.executePipeline as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.executePipeline as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes runQuery without error and gaxServerStreamingRetries enabled', async () => { + const client = new firestoreModule.FirestoreClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + gaxServerStreamingRetries: true, + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.firestore.v1.RunQueryRequest() + ); + const defaultValue1 = getTypeDefaultValue( + '.google.firestore.v1.RunQueryRequest', + ['parent'] + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.firestore.v1.RunQueryResponse() + ); + client.innerApiCalls.runQuery = stubServerStreamingCall(expectedResponse); + const stream = client.runQuery(request); + const promise = new Promise((resolve, reject) => { + stream.on( + 'data', + (response: protos.google.firestore.v1.RunQueryResponse) => { + resolve(response); + } + ); + stream.on('error', (err: Error) => { + reject(err); + }); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.runQuery as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.runQuery as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes executePipeline without error and gaxServerStreamingRetries enabled', async () => { - const client = new firestoreModule.FirestoreClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - gaxServerStreamingRetries: true - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.firestore.v1.ExecutePipelineRequest() - ); - // path template: projects/*/databases/{database_id=*}/** - request.database = 'projects/value/databases/value/value'; - const expectedHeaderRequestParams = 'database_id=value'; - const expectedResponse = generateSampleMessage( - new protos.google.firestore.v1.ExecutePipelineResponse() - ); - client.innerApiCalls.executePipeline = stubServerStreamingCall(expectedResponse); - const stream = client.executePipeline(request); - const promise = new Promise((resolve, reject) => { - stream.on('data', (response: protos.google.firestore.v1.ExecutePipelineResponse) => { - resolve(response); - }); - stream.on('error', (err: Error) => { - reject(err); - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.executePipeline as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.executePipeline as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes runQuery with error', async () => { + const client = new firestoreModule.FirestoreClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.firestore.v1.RunQueryRequest() + ); + const defaultValue1 = getTypeDefaultValue( + '.google.firestore.v1.RunQueryRequest', + ['parent'] + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.runQuery = stubServerStreamingCall( + undefined, + expectedError + ); + const stream = client.runQuery(request); + const promise = new Promise((resolve, reject) => { + stream.on( + 'data', + (response: protos.google.firestore.v1.RunQueryResponse) => { + resolve(response); + } + ); + stream.on('error', (err: Error) => { + reject(err); + }); + }); + await assert.rejects(promise, expectedError); + const actualRequest = ( + client.innerApiCalls.runQuery as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.runQuery as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes executePipeline with error', async () => { - const client = new firestoreModule.FirestoreClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.firestore.v1.ExecutePipelineRequest() - ); - // path template: projects/*/databases/{database_id=*}/** - request.database = 'projects/value/databases/value/value'; - const expectedHeaderRequestParams = 'database_id=value'; - const expectedError = new Error('expected'); - client.innerApiCalls.executePipeline = stubServerStreamingCall(undefined, expectedError); - const stream = client.executePipeline(request); - const promise = new Promise((resolve, reject) => { - stream.on('data', (response: protos.google.firestore.v1.ExecutePipelineResponse) => { - resolve(response); - }); - stream.on('error', (err: Error) => { - reject(err); - }); - }); - await assert.rejects(promise, expectedError); - const actualRequest = (client.innerApiCalls.executePipeline as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.executePipeline as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes runQuery with closed client', async () => { + const client = new firestoreModule.FirestoreClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.firestore.v1.RunQueryRequest() + ); + const defaultValue1 = getTypeDefaultValue( + '.google.firestore.v1.RunQueryRequest', + ['parent'] + ); + request.parent = defaultValue1; + const expectedError = new Error('The client has already been closed.'); + client.close().catch(err => { + throw err; + }); + const stream = client.runQuery(request, { + retryRequestOptions: {noResponseRetries: 0}, + }); + const promise = new Promise((resolve, reject) => { + stream.on( + 'data', + (response: protos.google.firestore.v1.RunQueryResponse) => { + resolve(response); + } + ); + stream.on('error', (err: Error) => { + reject(err); + }); + }); + await assert.rejects(promise, expectedError); + }); + it('should create a client with gaxServerStreamingRetries enabled', () => { + const client = new firestoreModule.FirestoreClient({ + gaxServerStreamingRetries: true, + }); + assert(client); + }); + }); + + describe('executePipeline', () => { + it('invokes executePipeline without error', async () => { + const client = new firestoreModule.FirestoreClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.firestore.v1.ExecutePipelineRequest() + ); + // path template: projects/*/databases/{database_id=*}/** + request.database = 'projects/value/databases/value/value'; + const expectedHeaderRequestParams = 'database_id=value'; + const expectedResponse = generateSampleMessage( + new protos.google.firestore.v1.ExecutePipelineResponse() + ); + client.innerApiCalls.executePipeline = + stubServerStreamingCall(expectedResponse); + const stream = client.executePipeline(request); + const promise = new Promise((resolve, reject) => { + stream.on( + 'data', + (response: protos.google.firestore.v1.ExecutePipelineResponse) => { + resolve(response); + } + ); + stream.on('error', (err: Error) => { + reject(err); + }); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.executePipeline as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.executePipeline as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes executePipeline with closed client', async () => { - const client = new firestoreModule.FirestoreClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.firestore.v1.ExecutePipelineRequest() - ); - // path template: projects/*/databases/{database_id=*}/** - request.database = 'projects/value/databases/value/value'; - const expectedError = new Error('The client has already been closed.'); - client.close().catch(err => {throw err}); - const stream = client.executePipeline(request, {retryRequestOptions: {noResponseRetries: 0}}); - const promise = new Promise((resolve, reject) => { - stream.on('data', (response: protos.google.firestore.v1.ExecutePipelineResponse) => { - resolve(response); - }); - stream.on('error', (err: Error) => { - reject(err); - }); - }); - await assert.rejects(promise, expectedError); - }); - it('should create a client with gaxServerStreamingRetries enabled', () => { - const client = new firestoreModule.FirestoreClient({ - gaxServerStreamingRetries: true, - }); - assert(client); - }); + it('invokes executePipeline without error and gaxServerStreamingRetries enabled', async () => { + const client = new firestoreModule.FirestoreClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + gaxServerStreamingRetries: true, + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.firestore.v1.ExecutePipelineRequest() + ); + // path template: projects/*/databases/{database_id=*}/** + request.database = 'projects/value/databases/value/value'; + const expectedHeaderRequestParams = 'database_id=value'; + const expectedResponse = generateSampleMessage( + new protos.google.firestore.v1.ExecutePipelineResponse() + ); + client.innerApiCalls.executePipeline = + stubServerStreamingCall(expectedResponse); + const stream = client.executePipeline(request); + const promise = new Promise((resolve, reject) => { + stream.on( + 'data', + (response: protos.google.firestore.v1.ExecutePipelineResponse) => { + resolve(response); + } + ); + stream.on('error', (err: Error) => { + reject(err); + }); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.executePipeline as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.executePipeline as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); }); - describe('runAggregationQuery', () => { - it('invokes runAggregationQuery without error', async () => { - const client = new firestoreModule.FirestoreClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.firestore.v1.RunAggregationQueryRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.firestore.v1.RunAggregationQueryRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.firestore.v1.RunAggregationQueryResponse() - ); - client.innerApiCalls.runAggregationQuery = stubServerStreamingCall(expectedResponse); - const stream = client.runAggregationQuery(request); - const promise = new Promise((resolve, reject) => { - stream.on('data', (response: protos.google.firestore.v1.RunAggregationQueryResponse) => { - resolve(response); - }); - stream.on('error', (err: Error) => { - reject(err); - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.runAggregationQuery as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.runAggregationQuery as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes executePipeline with error', async () => { + const client = new firestoreModule.FirestoreClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.firestore.v1.ExecutePipelineRequest() + ); + // path template: projects/*/databases/{database_id=*}/** + request.database = 'projects/value/databases/value/value'; + const expectedHeaderRequestParams = 'database_id=value'; + const expectedError = new Error('expected'); + client.innerApiCalls.executePipeline = stubServerStreamingCall( + undefined, + expectedError + ); + const stream = client.executePipeline(request); + const promise = new Promise((resolve, reject) => { + stream.on( + 'data', + (response: protos.google.firestore.v1.ExecutePipelineResponse) => { + resolve(response); + } + ); + stream.on('error', (err: Error) => { + reject(err); + }); + }); + await assert.rejects(promise, expectedError); + const actualRequest = ( + client.innerApiCalls.executePipeline as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.executePipeline as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes runAggregationQuery without error and gaxServerStreamingRetries enabled', async () => { - const client = new firestoreModule.FirestoreClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - gaxServerStreamingRetries: true - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.firestore.v1.RunAggregationQueryRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.firestore.v1.RunAggregationQueryRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedResponse = generateSampleMessage( - new protos.google.firestore.v1.RunAggregationQueryResponse() - ); - client.innerApiCalls.runAggregationQuery = stubServerStreamingCall(expectedResponse); - const stream = client.runAggregationQuery(request); - const promise = new Promise((resolve, reject) => { - stream.on('data', (response: protos.google.firestore.v1.RunAggregationQueryResponse) => { - resolve(response); - }); - stream.on('error', (err: Error) => { - reject(err); - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.runAggregationQuery as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.runAggregationQuery as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes executePipeline with closed client', async () => { + const client = new firestoreModule.FirestoreClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.firestore.v1.ExecutePipelineRequest() + ); + // path template: projects/*/databases/{database_id=*}/** + request.database = 'projects/value/databases/value/value'; + const expectedError = new Error('The client has already been closed.'); + client.close().catch(err => { + throw err; + }); + const stream = client.executePipeline(request, { + retryRequestOptions: {noResponseRetries: 0}, + }); + const promise = new Promise((resolve, reject) => { + stream.on( + 'data', + (response: protos.google.firestore.v1.ExecutePipelineResponse) => { + resolve(response); + } + ); + stream.on('error', (err: Error) => { + reject(err); + }); + }); + await assert.rejects(promise, expectedError); + }); + it('should create a client with gaxServerStreamingRetries enabled', () => { + const client = new firestoreModule.FirestoreClient({ + gaxServerStreamingRetries: true, + }); + assert(client); + }); + }); + + describe('runAggregationQuery', () => { + it('invokes runAggregationQuery without error', async () => { + const client = new firestoreModule.FirestoreClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.firestore.v1.RunAggregationQueryRequest() + ); + const defaultValue1 = getTypeDefaultValue( + '.google.firestore.v1.RunAggregationQueryRequest', + ['parent'] + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.firestore.v1.RunAggregationQueryResponse() + ); + client.innerApiCalls.runAggregationQuery = + stubServerStreamingCall(expectedResponse); + const stream = client.runAggregationQuery(request); + const promise = new Promise((resolve, reject) => { + stream.on( + 'data', + ( + response: protos.google.firestore.v1.RunAggregationQueryResponse + ) => { + resolve(response); + } + ); + stream.on('error', (err: Error) => { + reject(err); + }); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.runAggregationQuery as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.runAggregationQuery as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes runAggregationQuery with error', async () => { - const client = new firestoreModule.FirestoreClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.firestore.v1.RunAggregationQueryRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.firestore.v1.RunAggregationQueryRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.runAggregationQuery = stubServerStreamingCall(undefined, expectedError); - const stream = client.runAggregationQuery(request); - const promise = new Promise((resolve, reject) => { - stream.on('data', (response: protos.google.firestore.v1.RunAggregationQueryResponse) => { - resolve(response); - }); - stream.on('error', (err: Error) => { - reject(err); - }); - }); - await assert.rejects(promise, expectedError); - const actualRequest = (client.innerApiCalls.runAggregationQuery as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.runAggregationQuery as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes runAggregationQuery without error and gaxServerStreamingRetries enabled', async () => { + const client = new firestoreModule.FirestoreClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + gaxServerStreamingRetries: true, + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.firestore.v1.RunAggregationQueryRequest() + ); + const defaultValue1 = getTypeDefaultValue( + '.google.firestore.v1.RunAggregationQueryRequest', + ['parent'] + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedResponse = generateSampleMessage( + new protos.google.firestore.v1.RunAggregationQueryResponse() + ); + client.innerApiCalls.runAggregationQuery = + stubServerStreamingCall(expectedResponse); + const stream = client.runAggregationQuery(request); + const promise = new Promise((resolve, reject) => { + stream.on( + 'data', + ( + response: protos.google.firestore.v1.RunAggregationQueryResponse + ) => { + resolve(response); + } + ); + stream.on('error', (err: Error) => { + reject(err); + }); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.runAggregationQuery as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.runAggregationQuery as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes runAggregationQuery with closed client', async () => { - const client = new firestoreModule.FirestoreClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.firestore.v1.RunAggregationQueryRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.firestore.v1.RunAggregationQueryRequest', ['parent']); - request.parent = defaultValue1; - const expectedError = new Error('The client has already been closed.'); - client.close().catch(err => {throw err}); - const stream = client.runAggregationQuery(request, {retryRequestOptions: {noResponseRetries: 0}}); - const promise = new Promise((resolve, reject) => { - stream.on('data', (response: protos.google.firestore.v1.RunAggregationQueryResponse) => { - resolve(response); - }); - stream.on('error', (err: Error) => { - reject(err); - }); - }); - await assert.rejects(promise, expectedError); - }); - it('should create a client with gaxServerStreamingRetries enabled', () => { - const client = new firestoreModule.FirestoreClient({ - gaxServerStreamingRetries: true, - }); - assert(client); - }); + it('invokes runAggregationQuery with error', async () => { + const client = new firestoreModule.FirestoreClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.firestore.v1.RunAggregationQueryRequest() + ); + const defaultValue1 = getTypeDefaultValue( + '.google.firestore.v1.RunAggregationQueryRequest', + ['parent'] + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.runAggregationQuery = stubServerStreamingCall( + undefined, + expectedError + ); + const stream = client.runAggregationQuery(request); + const promise = new Promise((resolve, reject) => { + stream.on( + 'data', + ( + response: protos.google.firestore.v1.RunAggregationQueryResponse + ) => { + resolve(response); + } + ); + stream.on('error', (err: Error) => { + reject(err); + }); + }); + await assert.rejects(promise, expectedError); + const actualRequest = ( + client.innerApiCalls.runAggregationQuery as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.runAggregationQuery as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); }); - describe('write', () => { - it('invokes write without error', async () => { - const client = new firestoreModule.FirestoreClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.firestore.v1.WriteRequest() - ); - - const expectedResponse = generateSampleMessage( - new protos.google.firestore.v1.WriteResponse() - ); - client.innerApiCalls.write = stubBidiStreamingCall(expectedResponse); - const stream = client.write(); - const promise = new Promise((resolve, reject) => { - stream.on('data', (response: protos.google.firestore.v1.WriteResponse) => { - resolve(response); - }); - stream.on('error', (err: Error) => { - reject(err); - }); - stream.write(request); - stream.end(); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - assert((client.innerApiCalls.write as SinonStub) - .getCall(0).calledWith(null)); - assert.deepStrictEqual(((stream as unknown as PassThrough) - ._transform as SinonStub).getCall(0).args[0], request); - }); + it('invokes runAggregationQuery with closed client', async () => { + const client = new firestoreModule.FirestoreClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.firestore.v1.RunAggregationQueryRequest() + ); + const defaultValue1 = getTypeDefaultValue( + '.google.firestore.v1.RunAggregationQueryRequest', + ['parent'] + ); + request.parent = defaultValue1; + const expectedError = new Error('The client has already been closed.'); + client.close().catch(err => { + throw err; + }); + const stream = client.runAggregationQuery(request, { + retryRequestOptions: {noResponseRetries: 0}, + }); + const promise = new Promise((resolve, reject) => { + stream.on( + 'data', + ( + response: protos.google.firestore.v1.RunAggregationQueryResponse + ) => { + resolve(response); + } + ); + stream.on('error', (err: Error) => { + reject(err); + }); + }); + await assert.rejects(promise, expectedError); + }); + it('should create a client with gaxServerStreamingRetries enabled', () => { + const client = new firestoreModule.FirestoreClient({ + gaxServerStreamingRetries: true, + }); + assert(client); + }); + }); + + describe('write', () => { + it('invokes write without error', async () => { + const client = new firestoreModule.FirestoreClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.firestore.v1.WriteRequest() + ); + + const expectedResponse = generateSampleMessage( + new protos.google.firestore.v1.WriteResponse() + ); + client.innerApiCalls.write = stubBidiStreamingCall(expectedResponse); + const stream = client.write(); + const promise = new Promise((resolve, reject) => { + stream.on( + 'data', + (response: protos.google.firestore.v1.WriteResponse) => { + resolve(response); + } + ); + stream.on('error', (err: Error) => { + reject(err); + }); + stream.write(request); + stream.end(); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + assert( + (client.innerApiCalls.write as SinonStub).getCall(0).calledWith(null) + ); + assert.deepStrictEqual( + ((stream as unknown as PassThrough)._transform as SinonStub).getCall(0) + .args[0], + request + ); + }); - it('invokes write with error', async () => { - const client = new firestoreModule.FirestoreClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.firestore.v1.WriteRequest() - ); - const expectedError = new Error('expected'); - client.innerApiCalls.write = stubBidiStreamingCall(undefined, expectedError); - const stream = client.write(); - const promise = new Promise((resolve, reject) => { - stream.on('data', (response: protos.google.firestore.v1.WriteResponse) => { - resolve(response); - }); - stream.on('error', (err: Error) => { - reject(err); - }); - stream.write(request); - stream.end(); - }); - await assert.rejects(promise, expectedError); - assert((client.innerApiCalls.write as SinonStub) - .getCall(0).calledWith(null)); - assert.deepStrictEqual(((stream as unknown as PassThrough) - ._transform as SinonStub).getCall(0).args[0], request); - }); + it('invokes write with error', async () => { + const client = new firestoreModule.FirestoreClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.firestore.v1.WriteRequest() + ); + const expectedError = new Error('expected'); + client.innerApiCalls.write = stubBidiStreamingCall( + undefined, + expectedError + ); + const stream = client.write(); + const promise = new Promise((resolve, reject) => { + stream.on( + 'data', + (response: protos.google.firestore.v1.WriteResponse) => { + resolve(response); + } + ); + stream.on('error', (err: Error) => { + reject(err); + }); + stream.write(request); + stream.end(); + }); + await assert.rejects(promise, expectedError); + assert( + (client.innerApiCalls.write as SinonStub).getCall(0).calledWith(null) + ); + assert.deepStrictEqual( + ((stream as unknown as PassThrough)._transform as SinonStub).getCall(0) + .args[0], + request + ); + }); + }); + + describe('listen', () => { + it('invokes listen without error', async () => { + const client = new firestoreModule.FirestoreClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.firestore.v1.ListenRequest() + ); + + const expectedResponse = generateSampleMessage( + new protos.google.firestore.v1.ListenResponse() + ); + client.innerApiCalls.listen = stubBidiStreamingCall(expectedResponse); + const stream = client.listen(); + const promise = new Promise((resolve, reject) => { + stream.on( + 'data', + (response: protos.google.firestore.v1.ListenResponse) => { + resolve(response); + } + ); + stream.on('error', (err: Error) => { + reject(err); + }); + stream.write(request); + stream.end(); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + assert( + (client.innerApiCalls.listen as SinonStub).getCall(0).calledWith(null) + ); + assert.deepStrictEqual( + ((stream as unknown as PassThrough)._transform as SinonStub).getCall(0) + .args[0], + request + ); }); - describe('listen', () => { - it('invokes listen without error', async () => { - const client = new firestoreModule.FirestoreClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.firestore.v1.ListenRequest() - ); - - const expectedResponse = generateSampleMessage( - new protos.google.firestore.v1.ListenResponse() - ); - client.innerApiCalls.listen = stubBidiStreamingCall(expectedResponse); - const stream = client.listen(); - const promise = new Promise((resolve, reject) => { - stream.on('data', (response: protos.google.firestore.v1.ListenResponse) => { - resolve(response); - }); - stream.on('error', (err: Error) => { - reject(err); - }); - stream.write(request); - stream.end(); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - assert((client.innerApiCalls.listen as SinonStub) - .getCall(0).calledWith(null)); - assert.deepStrictEqual(((stream as unknown as PassThrough) - ._transform as SinonStub).getCall(0).args[0], request); - }); + it('invokes listen with error', async () => { + const client = new firestoreModule.FirestoreClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.firestore.v1.ListenRequest() + ); + const expectedError = new Error('expected'); + client.innerApiCalls.listen = stubBidiStreamingCall( + undefined, + expectedError + ); + const stream = client.listen(); + const promise = new Promise((resolve, reject) => { + stream.on( + 'data', + (response: protos.google.firestore.v1.ListenResponse) => { + resolve(response); + } + ); + stream.on('error', (err: Error) => { + reject(err); + }); + stream.write(request); + stream.end(); + }); + await assert.rejects(promise, expectedError); + assert( + (client.innerApiCalls.listen as SinonStub).getCall(0).calledWith(null) + ); + assert.deepStrictEqual( + ((stream as unknown as PassThrough)._transform as SinonStub).getCall(0) + .args[0], + request + ); + }); + }); + + describe('listDocuments', () => { + it('invokes listDocuments without error', async () => { + const client = new firestoreModule.FirestoreClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.firestore.v1.ListDocumentsRequest() + ); + const defaultValue1 = getTypeDefaultValue( + '.google.firestore.v1.ListDocumentsRequest', + ['parent'] + ); + request.parent = defaultValue1; + const defaultValue2 = getTypeDefaultValue( + '.google.firestore.v1.ListDocumentsRequest', + ['collectionId'] + ); + request.collectionId = defaultValue2; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}&collection_id=${defaultValue2 ?? ''}`; + const expectedResponse = [ + generateSampleMessage(new protos.google.firestore.v1.Document()), + generateSampleMessage(new protos.google.firestore.v1.Document()), + generateSampleMessage(new protos.google.firestore.v1.Document()), + ]; + client.innerApiCalls.listDocuments = stubSimpleCall(expectedResponse); + const [response] = await client.listDocuments(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.listDocuments as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.listDocuments as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes listen with error', async () => { - const client = new firestoreModule.FirestoreClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.firestore.v1.ListenRequest() - ); - const expectedError = new Error('expected'); - client.innerApiCalls.listen = stubBidiStreamingCall(undefined, expectedError); - const stream = client.listen(); - const promise = new Promise((resolve, reject) => { - stream.on('data', (response: protos.google.firestore.v1.ListenResponse) => { - resolve(response); - }); - stream.on('error', (err: Error) => { - reject(err); - }); - stream.write(request); - stream.end(); - }); - await assert.rejects(promise, expectedError); - assert((client.innerApiCalls.listen as SinonStub) - .getCall(0).calledWith(null)); - assert.deepStrictEqual(((stream as unknown as PassThrough) - ._transform as SinonStub).getCall(0).args[0], request); - }); + it('invokes listDocuments without error using callback', async () => { + const client = new firestoreModule.FirestoreClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.firestore.v1.ListDocumentsRequest() + ); + const defaultValue1 = getTypeDefaultValue( + '.google.firestore.v1.ListDocumentsRequest', + ['parent'] + ); + request.parent = defaultValue1; + const defaultValue2 = getTypeDefaultValue( + '.google.firestore.v1.ListDocumentsRequest', + ['collectionId'] + ); + request.collectionId = defaultValue2; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}&collection_id=${defaultValue2 ?? ''}`; + const expectedResponse = [ + generateSampleMessage(new protos.google.firestore.v1.Document()), + generateSampleMessage(new protos.google.firestore.v1.Document()), + generateSampleMessage(new protos.google.firestore.v1.Document()), + ]; + client.innerApiCalls.listDocuments = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.listDocuments( + request, + ( + err?: Error | null, + result?: protos.google.firestore.v1.IDocument[] | null + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + } + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.listDocuments as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.listDocuments as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); }); - describe('listDocuments', () => { - it('invokes listDocuments without error', async () => { - const client = new firestoreModule.FirestoreClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.firestore.v1.ListDocumentsRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.firestore.v1.ListDocumentsRequest', ['parent']); - request.parent = defaultValue1; - const defaultValue2 = - getTypeDefaultValue('.google.firestore.v1.ListDocumentsRequest', ['collectionId']); - request.collectionId = defaultValue2; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }&collection_id=${defaultValue2 ?? '' }`;const expectedResponse = [ - generateSampleMessage(new protos.google.firestore.v1.Document()), - generateSampleMessage(new protos.google.firestore.v1.Document()), - generateSampleMessage(new protos.google.firestore.v1.Document()), - ]; - client.innerApiCalls.listDocuments = stubSimpleCall(expectedResponse); - const [response] = await client.listDocuments(request); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.listDocuments as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.listDocuments as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes listDocuments with error', async () => { + const client = new firestoreModule.FirestoreClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.firestore.v1.ListDocumentsRequest() + ); + const defaultValue1 = getTypeDefaultValue( + '.google.firestore.v1.ListDocumentsRequest', + ['parent'] + ); + request.parent = defaultValue1; + const defaultValue2 = getTypeDefaultValue( + '.google.firestore.v1.ListDocumentsRequest', + ['collectionId'] + ); + request.collectionId = defaultValue2; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}&collection_id=${defaultValue2 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.listDocuments = stubSimpleCall( + undefined, + expectedError + ); + await assert.rejects(client.listDocuments(request), expectedError); + const actualRequest = ( + client.innerApiCalls.listDocuments as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.listDocuments as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes listDocuments without error using callback', async () => { - const client = new firestoreModule.FirestoreClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.firestore.v1.ListDocumentsRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.firestore.v1.ListDocumentsRequest', ['parent']); - request.parent = defaultValue1; - const defaultValue2 = - getTypeDefaultValue('.google.firestore.v1.ListDocumentsRequest', ['collectionId']); - request.collectionId = defaultValue2; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }&collection_id=${defaultValue2 ?? '' }`;const expectedResponse = [ - generateSampleMessage(new protos.google.firestore.v1.Document()), - generateSampleMessage(new protos.google.firestore.v1.Document()), - generateSampleMessage(new protos.google.firestore.v1.Document()), - ]; - client.innerApiCalls.listDocuments = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.listDocuments( - request, - (err?: Error|null, result?: protos.google.firestore.v1.IDocument[]|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.listDocuments as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.listDocuments as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes listDocumentsStream without error', async () => { + const client = new firestoreModule.FirestoreClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.firestore.v1.ListDocumentsRequest() + ); + const defaultValue1 = getTypeDefaultValue( + '.google.firestore.v1.ListDocumentsRequest', + ['parent'] + ); + request.parent = defaultValue1; + const defaultValue2 = getTypeDefaultValue( + '.google.firestore.v1.ListDocumentsRequest', + ['collectionId'] + ); + request.collectionId = defaultValue2; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}&collection_id=${defaultValue2 ?? ''}`; + const expectedResponse = [ + generateSampleMessage(new protos.google.firestore.v1.Document()), + generateSampleMessage(new protos.google.firestore.v1.Document()), + generateSampleMessage(new protos.google.firestore.v1.Document()), + ]; + client.descriptors.page.listDocuments.createStream = + stubPageStreamingCall(expectedResponse); + const stream = client.listDocumentsStream(request); + const promise = new Promise((resolve, reject) => { + const responses: protos.google.firestore.v1.Document[] = []; + stream.on('data', (response: protos.google.firestore.v1.Document) => { + responses.push(response); + }); + stream.on('end', () => { + resolve(responses); + }); + stream.on('error', (err: Error) => { + reject(err); + }); + }); + const responses = await promise; + assert.deepStrictEqual(responses, expectedResponse); + assert( + (client.descriptors.page.listDocuments.createStream as SinonStub) + .getCall(0) + .calledWith(client.innerApiCalls.listDocuments, request) + ); + assert( + (client.descriptors.page.listDocuments.createStream as SinonStub) + .getCall(0) + .args[2].otherArgs.headers[ + 'x-goog-request-params' + ].includes(expectedHeaderRequestParams) + ); + }); - it('invokes listDocuments with error', async () => { - const client = new firestoreModule.FirestoreClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.firestore.v1.ListDocumentsRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.firestore.v1.ListDocumentsRequest', ['parent']); - request.parent = defaultValue1; - const defaultValue2 = - getTypeDefaultValue('.google.firestore.v1.ListDocumentsRequest', ['collectionId']); - request.collectionId = defaultValue2; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }&collection_id=${defaultValue2 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.listDocuments = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.listDocuments(request), expectedError); - const actualRequest = (client.innerApiCalls.listDocuments as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.listDocuments as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes listDocumentsStream with error', async () => { + const client = new firestoreModule.FirestoreClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.firestore.v1.ListDocumentsRequest() + ); + const defaultValue1 = getTypeDefaultValue( + '.google.firestore.v1.ListDocumentsRequest', + ['parent'] + ); + request.parent = defaultValue1; + const defaultValue2 = getTypeDefaultValue( + '.google.firestore.v1.ListDocumentsRequest', + ['collectionId'] + ); + request.collectionId = defaultValue2; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}&collection_id=${defaultValue2 ?? ''}`; + const expectedError = new Error('expected'); + client.descriptors.page.listDocuments.createStream = + stubPageStreamingCall(undefined, expectedError); + const stream = client.listDocumentsStream(request); + const promise = new Promise((resolve, reject) => { + const responses: protos.google.firestore.v1.Document[] = []; + stream.on('data', (response: protos.google.firestore.v1.Document) => { + responses.push(response); + }); + stream.on('end', () => { + resolve(responses); + }); + stream.on('error', (err: Error) => { + reject(err); + }); + }); + await assert.rejects(promise, expectedError); + assert( + (client.descriptors.page.listDocuments.createStream as SinonStub) + .getCall(0) + .calledWith(client.innerApiCalls.listDocuments, request) + ); + assert( + (client.descriptors.page.listDocuments.createStream as SinonStub) + .getCall(0) + .args[2].otherArgs.headers[ + 'x-goog-request-params' + ].includes(expectedHeaderRequestParams) + ); + }); - it('invokes listDocumentsStream without error', async () => { - const client = new firestoreModule.FirestoreClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.firestore.v1.ListDocumentsRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.firestore.v1.ListDocumentsRequest', ['parent']); - request.parent = defaultValue1; - const defaultValue2 = - getTypeDefaultValue('.google.firestore.v1.ListDocumentsRequest', ['collectionId']); - request.collectionId = defaultValue2; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }&collection_id=${defaultValue2 ?? '' }`; - const expectedResponse = [ - generateSampleMessage(new protos.google.firestore.v1.Document()), - generateSampleMessage(new protos.google.firestore.v1.Document()), - generateSampleMessage(new protos.google.firestore.v1.Document()), - ]; - client.descriptors.page.listDocuments.createStream = stubPageStreamingCall(expectedResponse); - const stream = client.listDocumentsStream(request); - const promise = new Promise((resolve, reject) => { - const responses: protos.google.firestore.v1.Document[] = []; - stream.on('data', (response: protos.google.firestore.v1.Document) => { - responses.push(response); - }); - stream.on('end', () => { - resolve(responses); - }); - stream.on('error', (err: Error) => { - reject(err); - }); - }); - const responses = await promise; - assert.deepStrictEqual(responses, expectedResponse); - assert((client.descriptors.page.listDocuments.createStream as SinonStub) - .getCall(0).calledWith(client.innerApiCalls.listDocuments, request)); - assert( - (client.descriptors.page.listDocuments.createStream as SinonStub) - .getCall(0).args[2].otherArgs.headers['x-goog-request-params'].includes( - expectedHeaderRequestParams - ) - ); - }); + it('uses async iteration with listDocuments without error', async () => { + const client = new firestoreModule.FirestoreClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.firestore.v1.ListDocumentsRequest() + ); + const defaultValue1 = getTypeDefaultValue( + '.google.firestore.v1.ListDocumentsRequest', + ['parent'] + ); + request.parent = defaultValue1; + const defaultValue2 = getTypeDefaultValue( + '.google.firestore.v1.ListDocumentsRequest', + ['collectionId'] + ); + request.collectionId = defaultValue2; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}&collection_id=${defaultValue2 ?? ''}`; + const expectedResponse = [ + generateSampleMessage(new protos.google.firestore.v1.Document()), + generateSampleMessage(new protos.google.firestore.v1.Document()), + generateSampleMessage(new protos.google.firestore.v1.Document()), + ]; + client.descriptors.page.listDocuments.asyncIterate = + stubAsyncIterationCall(expectedResponse); + const responses: protos.google.firestore.v1.IDocument[] = []; + const iterable = client.listDocumentsAsync(request); + for await (const resource of iterable) { + responses.push(resource!); + } + assert.deepStrictEqual(responses, expectedResponse); + assert.deepStrictEqual( + ( + client.descriptors.page.listDocuments.asyncIterate as SinonStub + ).getCall(0).args[1], + request + ); + assert( + (client.descriptors.page.listDocuments.asyncIterate as SinonStub) + .getCall(0) + .args[2].otherArgs.headers[ + 'x-goog-request-params' + ].includes(expectedHeaderRequestParams) + ); + }); - it('invokes listDocumentsStream with error', async () => { - const client = new firestoreModule.FirestoreClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.firestore.v1.ListDocumentsRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.firestore.v1.ListDocumentsRequest', ['parent']); - request.parent = defaultValue1; - const defaultValue2 = - getTypeDefaultValue('.google.firestore.v1.ListDocumentsRequest', ['collectionId']); - request.collectionId = defaultValue2; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }&collection_id=${defaultValue2 ?? '' }`; - const expectedError = new Error('expected'); - client.descriptors.page.listDocuments.createStream = stubPageStreamingCall(undefined, expectedError); - const stream = client.listDocumentsStream(request); - const promise = new Promise((resolve, reject) => { - const responses: protos.google.firestore.v1.Document[] = []; - stream.on('data', (response: protos.google.firestore.v1.Document) => { - responses.push(response); - }); - stream.on('end', () => { - resolve(responses); - }); - stream.on('error', (err: Error) => { - reject(err); - }); - }); - await assert.rejects(promise, expectedError); - assert((client.descriptors.page.listDocuments.createStream as SinonStub) - .getCall(0).calledWith(client.innerApiCalls.listDocuments, request)); - assert( - (client.descriptors.page.listDocuments.createStream as SinonStub) - .getCall(0).args[2].otherArgs.headers['x-goog-request-params'].includes( - expectedHeaderRequestParams - ) - ); - }); + it('uses async iteration with listDocuments with error', async () => { + const client = new firestoreModule.FirestoreClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.firestore.v1.ListDocumentsRequest() + ); + const defaultValue1 = getTypeDefaultValue( + '.google.firestore.v1.ListDocumentsRequest', + ['parent'] + ); + request.parent = defaultValue1; + const defaultValue2 = getTypeDefaultValue( + '.google.firestore.v1.ListDocumentsRequest', + ['collectionId'] + ); + request.collectionId = defaultValue2; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}&collection_id=${defaultValue2 ?? ''}`; + const expectedError = new Error('expected'); + client.descriptors.page.listDocuments.asyncIterate = + stubAsyncIterationCall(undefined, expectedError); + const iterable = client.listDocumentsAsync(request); + await assert.rejects(async () => { + const responses: protos.google.firestore.v1.IDocument[] = []; + for await (const resource of iterable) { + responses.push(resource!); + } + }); + assert.deepStrictEqual( + ( + client.descriptors.page.listDocuments.asyncIterate as SinonStub + ).getCall(0).args[1], + request + ); + assert( + (client.descriptors.page.listDocuments.asyncIterate as SinonStub) + .getCall(0) + .args[2].otherArgs.headers[ + 'x-goog-request-params' + ].includes(expectedHeaderRequestParams) + ); + }); + }); + + describe('partitionQuery', () => { + it('invokes partitionQuery without error', async () => { + const client = new firestoreModule.FirestoreClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.firestore.v1.PartitionQueryRequest() + ); + const defaultValue1 = getTypeDefaultValue( + '.google.firestore.v1.PartitionQueryRequest', + ['parent'] + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedResponse = [ + generateSampleMessage(new protos.google.firestore.v1.Cursor()), + generateSampleMessage(new protos.google.firestore.v1.Cursor()), + generateSampleMessage(new protos.google.firestore.v1.Cursor()), + ]; + client.innerApiCalls.partitionQuery = stubSimpleCall(expectedResponse); + const [response] = await client.partitionQuery(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.partitionQuery as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.partitionQuery as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('uses async iteration with listDocuments without error', async () => { - const client = new firestoreModule.FirestoreClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.firestore.v1.ListDocumentsRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.firestore.v1.ListDocumentsRequest', ['parent']); - request.parent = defaultValue1; - const defaultValue2 = - getTypeDefaultValue('.google.firestore.v1.ListDocumentsRequest', ['collectionId']); - request.collectionId = defaultValue2; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }&collection_id=${defaultValue2 ?? '' }`; - const expectedResponse = [ - generateSampleMessage(new protos.google.firestore.v1.Document()), - generateSampleMessage(new protos.google.firestore.v1.Document()), - generateSampleMessage(new protos.google.firestore.v1.Document()), - ]; - client.descriptors.page.listDocuments.asyncIterate = stubAsyncIterationCall(expectedResponse); - const responses: protos.google.firestore.v1.IDocument[] = []; - const iterable = client.listDocumentsAsync(request); - for await (const resource of iterable) { - responses.push(resource!); + it('invokes partitionQuery without error using callback', async () => { + const client = new firestoreModule.FirestoreClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.firestore.v1.PartitionQueryRequest() + ); + const defaultValue1 = getTypeDefaultValue( + '.google.firestore.v1.PartitionQueryRequest', + ['parent'] + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedResponse = [ + generateSampleMessage(new protos.google.firestore.v1.Cursor()), + generateSampleMessage(new protos.google.firestore.v1.Cursor()), + generateSampleMessage(new protos.google.firestore.v1.Cursor()), + ]; + client.innerApiCalls.partitionQuery = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.partitionQuery( + request, + ( + err?: Error | null, + result?: protos.google.firestore.v1.ICursor[] | null + ) => { + if (err) { + reject(err); + } else { + resolve(result); } - assert.deepStrictEqual(responses, expectedResponse); - assert.deepStrictEqual( - (client.descriptors.page.listDocuments.asyncIterate as SinonStub) - .getCall(0).args[1], request); - assert( - (client.descriptors.page.listDocuments.asyncIterate as SinonStub) - .getCall(0).args[2].otherArgs.headers['x-goog-request-params'].includes( - expectedHeaderRequestParams - ) - ); - }); - - it('uses async iteration with listDocuments with error', async () => { - const client = new firestoreModule.FirestoreClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.firestore.v1.ListDocumentsRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.firestore.v1.ListDocumentsRequest', ['parent']); - request.parent = defaultValue1; - const defaultValue2 = - getTypeDefaultValue('.google.firestore.v1.ListDocumentsRequest', ['collectionId']); - request.collectionId = defaultValue2; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }&collection_id=${defaultValue2 ?? '' }`; - const expectedError = new Error('expected'); - client.descriptors.page.listDocuments.asyncIterate = stubAsyncIterationCall(undefined, expectedError); - const iterable = client.listDocumentsAsync(request); - await assert.rejects(async () => { - const responses: protos.google.firestore.v1.IDocument[] = []; - for await (const resource of iterable) { - responses.push(resource!); - } - }); - assert.deepStrictEqual( - (client.descriptors.page.listDocuments.asyncIterate as SinonStub) - .getCall(0).args[1], request); - assert( - (client.descriptors.page.listDocuments.asyncIterate as SinonStub) - .getCall(0).args[2].otherArgs.headers['x-goog-request-params'].includes( - expectedHeaderRequestParams - ) - ); - }); + } + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.partitionQuery as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.partitionQuery as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); }); - describe('partitionQuery', () => { - it('invokes partitionQuery without error', async () => { - const client = new firestoreModule.FirestoreClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.firestore.v1.PartitionQueryRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.firestore.v1.PartitionQueryRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`;const expectedResponse = [ - generateSampleMessage(new protos.google.firestore.v1.Cursor()), - generateSampleMessage(new protos.google.firestore.v1.Cursor()), - generateSampleMessage(new protos.google.firestore.v1.Cursor()), - ]; - client.innerApiCalls.partitionQuery = stubSimpleCall(expectedResponse); - const [response] = await client.partitionQuery(request); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.partitionQuery as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.partitionQuery as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes partitionQuery with error', async () => { + const client = new firestoreModule.FirestoreClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.firestore.v1.PartitionQueryRequest() + ); + const defaultValue1 = getTypeDefaultValue( + '.google.firestore.v1.PartitionQueryRequest', + ['parent'] + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.partitionQuery = stubSimpleCall( + undefined, + expectedError + ); + await assert.rejects(client.partitionQuery(request), expectedError); + const actualRequest = ( + client.innerApiCalls.partitionQuery as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.partitionQuery as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes partitionQuery without error using callback', async () => { - const client = new firestoreModule.FirestoreClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.firestore.v1.PartitionQueryRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.firestore.v1.PartitionQueryRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`;const expectedResponse = [ - generateSampleMessage(new protos.google.firestore.v1.Cursor()), - generateSampleMessage(new protos.google.firestore.v1.Cursor()), - generateSampleMessage(new protos.google.firestore.v1.Cursor()), - ]; - client.innerApiCalls.partitionQuery = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.partitionQuery( - request, - (err?: Error|null, result?: protos.google.firestore.v1.ICursor[]|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.partitionQuery as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.partitionQuery as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes partitionQueryStream without error', async () => { + const client = new firestoreModule.FirestoreClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.firestore.v1.PartitionQueryRequest() + ); + const defaultValue1 = getTypeDefaultValue( + '.google.firestore.v1.PartitionQueryRequest', + ['parent'] + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedResponse = [ + generateSampleMessage(new protos.google.firestore.v1.Cursor()), + generateSampleMessage(new protos.google.firestore.v1.Cursor()), + generateSampleMessage(new protos.google.firestore.v1.Cursor()), + ]; + client.descriptors.page.partitionQuery.createStream = + stubPageStreamingCall(expectedResponse); + const stream = client.partitionQueryStream(request); + const promise = new Promise((resolve, reject) => { + const responses: protos.google.firestore.v1.Cursor[] = []; + stream.on('data', (response: protos.google.firestore.v1.Cursor) => { + responses.push(response); + }); + stream.on('end', () => { + resolve(responses); + }); + stream.on('error', (err: Error) => { + reject(err); + }); + }); + const responses = await promise; + assert.deepStrictEqual(responses, expectedResponse); + assert( + (client.descriptors.page.partitionQuery.createStream as SinonStub) + .getCall(0) + .calledWith(client.innerApiCalls.partitionQuery, request) + ); + assert( + (client.descriptors.page.partitionQuery.createStream as SinonStub) + .getCall(0) + .args[2].otherArgs.headers[ + 'x-goog-request-params' + ].includes(expectedHeaderRequestParams) + ); + }); - it('invokes partitionQuery with error', async () => { - const client = new firestoreModule.FirestoreClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.firestore.v1.PartitionQueryRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.firestore.v1.PartitionQueryRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.partitionQuery = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.partitionQuery(request), expectedError); - const actualRequest = (client.innerApiCalls.partitionQuery as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.partitionQuery as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes partitionQueryStream with error', async () => { + const client = new firestoreModule.FirestoreClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.firestore.v1.PartitionQueryRequest() + ); + const defaultValue1 = getTypeDefaultValue( + '.google.firestore.v1.PartitionQueryRequest', + ['parent'] + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.descriptors.page.partitionQuery.createStream = + stubPageStreamingCall(undefined, expectedError); + const stream = client.partitionQueryStream(request); + const promise = new Promise((resolve, reject) => { + const responses: protos.google.firestore.v1.Cursor[] = []; + stream.on('data', (response: protos.google.firestore.v1.Cursor) => { + responses.push(response); + }); + stream.on('end', () => { + resolve(responses); + }); + stream.on('error', (err: Error) => { + reject(err); + }); + }); + await assert.rejects(promise, expectedError); + assert( + (client.descriptors.page.partitionQuery.createStream as SinonStub) + .getCall(0) + .calledWith(client.innerApiCalls.partitionQuery, request) + ); + assert( + (client.descriptors.page.partitionQuery.createStream as SinonStub) + .getCall(0) + .args[2].otherArgs.headers[ + 'x-goog-request-params' + ].includes(expectedHeaderRequestParams) + ); + }); - it('invokes partitionQueryStream without error', async () => { - const client = new firestoreModule.FirestoreClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.firestore.v1.PartitionQueryRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.firestore.v1.PartitionQueryRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedResponse = [ - generateSampleMessage(new protos.google.firestore.v1.Cursor()), - generateSampleMessage(new protos.google.firestore.v1.Cursor()), - generateSampleMessage(new protos.google.firestore.v1.Cursor()), - ]; - client.descriptors.page.partitionQuery.createStream = stubPageStreamingCall(expectedResponse); - const stream = client.partitionQueryStream(request); - const promise = new Promise((resolve, reject) => { - const responses: protos.google.firestore.v1.Cursor[] = []; - stream.on('data', (response: protos.google.firestore.v1.Cursor) => { - responses.push(response); - }); - stream.on('end', () => { - resolve(responses); - }); - stream.on('error', (err: Error) => { - reject(err); - }); - }); - const responses = await promise; - assert.deepStrictEqual(responses, expectedResponse); - assert((client.descriptors.page.partitionQuery.createStream as SinonStub) - .getCall(0).calledWith(client.innerApiCalls.partitionQuery, request)); - assert( - (client.descriptors.page.partitionQuery.createStream as SinonStub) - .getCall(0).args[2].otherArgs.headers['x-goog-request-params'].includes( - expectedHeaderRequestParams - ) - ); - }); + it('uses async iteration with partitionQuery without error', async () => { + const client = new firestoreModule.FirestoreClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.firestore.v1.PartitionQueryRequest() + ); + const defaultValue1 = getTypeDefaultValue( + '.google.firestore.v1.PartitionQueryRequest', + ['parent'] + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedResponse = [ + generateSampleMessage(new protos.google.firestore.v1.Cursor()), + generateSampleMessage(new protos.google.firestore.v1.Cursor()), + generateSampleMessage(new protos.google.firestore.v1.Cursor()), + ]; + client.descriptors.page.partitionQuery.asyncIterate = + stubAsyncIterationCall(expectedResponse); + const responses: protos.google.firestore.v1.ICursor[] = []; + const iterable = client.partitionQueryAsync(request); + for await (const resource of iterable) { + responses.push(resource!); + } + assert.deepStrictEqual(responses, expectedResponse); + assert.deepStrictEqual( + ( + client.descriptors.page.partitionQuery.asyncIterate as SinonStub + ).getCall(0).args[1], + request + ); + assert( + (client.descriptors.page.partitionQuery.asyncIterate as SinonStub) + .getCall(0) + .args[2].otherArgs.headers[ + 'x-goog-request-params' + ].includes(expectedHeaderRequestParams) + ); + }); - it('invokes partitionQueryStream with error', async () => { - const client = new firestoreModule.FirestoreClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.firestore.v1.PartitionQueryRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.firestore.v1.PartitionQueryRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.descriptors.page.partitionQuery.createStream = stubPageStreamingCall(undefined, expectedError); - const stream = client.partitionQueryStream(request); - const promise = new Promise((resolve, reject) => { - const responses: protos.google.firestore.v1.Cursor[] = []; - stream.on('data', (response: protos.google.firestore.v1.Cursor) => { - responses.push(response); - }); - stream.on('end', () => { - resolve(responses); - }); - stream.on('error', (err: Error) => { - reject(err); - }); - }); - await assert.rejects(promise, expectedError); - assert((client.descriptors.page.partitionQuery.createStream as SinonStub) - .getCall(0).calledWith(client.innerApiCalls.partitionQuery, request)); - assert( - (client.descriptors.page.partitionQuery.createStream as SinonStub) - .getCall(0).args[2].otherArgs.headers['x-goog-request-params'].includes( - expectedHeaderRequestParams - ) - ); - }); + it('uses async iteration with partitionQuery with error', async () => { + const client = new firestoreModule.FirestoreClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.firestore.v1.PartitionQueryRequest() + ); + const defaultValue1 = getTypeDefaultValue( + '.google.firestore.v1.PartitionQueryRequest', + ['parent'] + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.descriptors.page.partitionQuery.asyncIterate = + stubAsyncIterationCall(undefined, expectedError); + const iterable = client.partitionQueryAsync(request); + await assert.rejects(async () => { + const responses: protos.google.firestore.v1.ICursor[] = []; + for await (const resource of iterable) { + responses.push(resource!); + } + }); + assert.deepStrictEqual( + ( + client.descriptors.page.partitionQuery.asyncIterate as SinonStub + ).getCall(0).args[1], + request + ); + assert( + (client.descriptors.page.partitionQuery.asyncIterate as SinonStub) + .getCall(0) + .args[2].otherArgs.headers[ + 'x-goog-request-params' + ].includes(expectedHeaderRequestParams) + ); + }); + }); + + describe('listCollectionIds', () => { + it('invokes listCollectionIds without error', async () => { + const client = new firestoreModule.FirestoreClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.firestore.v1.ListCollectionIdsRequest() + ); + const defaultValue1 = getTypeDefaultValue( + '.google.firestore.v1.ListCollectionIdsRequest', + ['parent'] + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedResponse = [new String(), new String(), new String()]; + client.innerApiCalls.listCollectionIds = stubSimpleCall(expectedResponse); + const [response] = await client.listCollectionIds(request); + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.listCollectionIds as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.listCollectionIds as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('uses async iteration with partitionQuery without error', async () => { - const client = new firestoreModule.FirestoreClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.firestore.v1.PartitionQueryRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.firestore.v1.PartitionQueryRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedResponse = [ - generateSampleMessage(new protos.google.firestore.v1.Cursor()), - generateSampleMessage(new protos.google.firestore.v1.Cursor()), - generateSampleMessage(new protos.google.firestore.v1.Cursor()), - ]; - client.descriptors.page.partitionQuery.asyncIterate = stubAsyncIterationCall(expectedResponse); - const responses: protos.google.firestore.v1.ICursor[] = []; - const iterable = client.partitionQueryAsync(request); - for await (const resource of iterable) { - responses.push(resource!); + it('invokes listCollectionIds without error using callback', async () => { + const client = new firestoreModule.FirestoreClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.firestore.v1.ListCollectionIdsRequest() + ); + const defaultValue1 = getTypeDefaultValue( + '.google.firestore.v1.ListCollectionIdsRequest', + ['parent'] + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedResponse = [new String(), new String(), new String()]; + client.innerApiCalls.listCollectionIds = + stubSimpleCallWithCallback(expectedResponse); + const promise = new Promise((resolve, reject) => { + client.listCollectionIds( + request, + (err?: Error | null, result?: string[] | null) => { + if (err) { + reject(err); + } else { + resolve(result); } - assert.deepStrictEqual(responses, expectedResponse); - assert.deepStrictEqual( - (client.descriptors.page.partitionQuery.asyncIterate as SinonStub) - .getCall(0).args[1], request); - assert( - (client.descriptors.page.partitionQuery.asyncIterate as SinonStub) - .getCall(0).args[2].otherArgs.headers['x-goog-request-params'].includes( - expectedHeaderRequestParams - ) - ); - }); - - it('uses async iteration with partitionQuery with error', async () => { - const client = new firestoreModule.FirestoreClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.firestore.v1.PartitionQueryRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.firestore.v1.PartitionQueryRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.descriptors.page.partitionQuery.asyncIterate = stubAsyncIterationCall(undefined, expectedError); - const iterable = client.partitionQueryAsync(request); - await assert.rejects(async () => { - const responses: protos.google.firestore.v1.ICursor[] = []; - for await (const resource of iterable) { - responses.push(resource!); - } - }); - assert.deepStrictEqual( - (client.descriptors.page.partitionQuery.asyncIterate as SinonStub) - .getCall(0).args[1], request); - assert( - (client.descriptors.page.partitionQuery.asyncIterate as SinonStub) - .getCall(0).args[2].otherArgs.headers['x-goog-request-params'].includes( - expectedHeaderRequestParams - ) - ); - }); + } + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + const actualRequest = ( + client.innerApiCalls.listCollectionIds as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.listCollectionIds as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); }); - describe('listCollectionIds', () => { - it('invokes listCollectionIds without error', async () => { - const client = new firestoreModule.FirestoreClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.firestore.v1.ListCollectionIdsRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.firestore.v1.ListCollectionIdsRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`;const expectedResponse = [new String(), new String(), new String()]; - client.innerApiCalls.listCollectionIds = stubSimpleCall(expectedResponse); - const [response] = await client.listCollectionIds(request); - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.listCollectionIds as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.listCollectionIds as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes listCollectionIds without error using callback', async () => { - const client = new firestoreModule.FirestoreClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.firestore.v1.ListCollectionIdsRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.firestore.v1.ListCollectionIdsRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`;const expectedResponse = [new String(), new String(), new String()]; - client.innerApiCalls.listCollectionIds = stubSimpleCallWithCallback(expectedResponse); - const promise = new Promise((resolve, reject) => { - client.listCollectionIds( - request, - (err?: Error|null, result?: string[]|null) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - const actualRequest = (client.innerApiCalls.listCollectionIds as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.listCollectionIds as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); - - it('invokes listCollectionIds with error', async () => { - const client = new firestoreModule.FirestoreClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.firestore.v1.ListCollectionIdsRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.firestore.v1.ListCollectionIdsRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.innerApiCalls.listCollectionIds = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.listCollectionIds(request), expectedError); - const actualRequest = (client.innerApiCalls.listCollectionIds as SinonStub) - .getCall(0).args[0]; - assert.deepStrictEqual(actualRequest, request); - const actualHeaderRequestParams = (client.innerApiCalls.listCollectionIds as SinonStub) - .getCall(0).args[1].otherArgs.headers['x-goog-request-params']; - assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); - }); + it('invokes listCollectionIds with error', async () => { + const client = new firestoreModule.FirestoreClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.firestore.v1.ListCollectionIdsRequest() + ); + const defaultValue1 = getTypeDefaultValue( + '.google.firestore.v1.ListCollectionIdsRequest', + ['parent'] + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.innerApiCalls.listCollectionIds = stubSimpleCall( + undefined, + expectedError + ); + await assert.rejects(client.listCollectionIds(request), expectedError); + const actualRequest = ( + client.innerApiCalls.listCollectionIds as SinonStub + ).getCall(0).args[0]; + assert.deepStrictEqual(actualRequest, request); + const actualHeaderRequestParams = ( + client.innerApiCalls.listCollectionIds as SinonStub + ).getCall(0).args[1].otherArgs.headers['x-goog-request-params']; + assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams)); + }); - it('invokes listCollectionIdsStream without error', async () => { - const client = new firestoreModule.FirestoreClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.firestore.v1.ListCollectionIdsRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.firestore.v1.ListCollectionIdsRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedResponse = [new String(), new String(), new String()]; - client.descriptors.page.listCollectionIds.createStream = stubPageStreamingCall(expectedResponse); - const stream = client.listCollectionIdsStream(request); - const promise = new Promise((resolve, reject) => { - const responses: string[] = []; - stream.on('data', (response: string) => { - responses.push(response); - }); - stream.on('end', () => { - resolve(responses); - }); - stream.on('error', (err: Error) => { - reject(err); - }); - }); - const responses = await promise; - assert.deepStrictEqual(responses, expectedResponse); - assert((client.descriptors.page.listCollectionIds.createStream as SinonStub) - .getCall(0).calledWith(client.innerApiCalls.listCollectionIds, request)); - assert( - (client.descriptors.page.listCollectionIds.createStream as SinonStub) - .getCall(0).args[2].otherArgs.headers['x-goog-request-params'].includes( - expectedHeaderRequestParams - ) - ); - }); + it('invokes listCollectionIdsStream without error', async () => { + const client = new firestoreModule.FirestoreClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.firestore.v1.ListCollectionIdsRequest() + ); + const defaultValue1 = getTypeDefaultValue( + '.google.firestore.v1.ListCollectionIdsRequest', + ['parent'] + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedResponse = [new String(), new String(), new String()]; + client.descriptors.page.listCollectionIds.createStream = + stubPageStreamingCall(expectedResponse); + const stream = client.listCollectionIdsStream(request); + const promise = new Promise((resolve, reject) => { + const responses: string[] = []; + stream.on('data', (response: string) => { + responses.push(response); + }); + stream.on('end', () => { + resolve(responses); + }); + stream.on('error', (err: Error) => { + reject(err); + }); + }); + const responses = await promise; + assert.deepStrictEqual(responses, expectedResponse); + assert( + (client.descriptors.page.listCollectionIds.createStream as SinonStub) + .getCall(0) + .calledWith(client.innerApiCalls.listCollectionIds, request) + ); + assert( + (client.descriptors.page.listCollectionIds.createStream as SinonStub) + .getCall(0) + .args[2].otherArgs.headers[ + 'x-goog-request-params' + ].includes(expectedHeaderRequestParams) + ); + }); - it('invokes listCollectionIdsStream with error', async () => { - const client = new firestoreModule.FirestoreClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.firestore.v1.ListCollectionIdsRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.firestore.v1.ListCollectionIdsRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.descriptors.page.listCollectionIds.createStream = stubPageStreamingCall(undefined, expectedError); - const stream = client.listCollectionIdsStream(request); - const promise = new Promise((resolve, reject) => { - const responses: string[] = []; - stream.on('data', (response: string) => { - responses.push(response); - }); - stream.on('end', () => { - resolve(responses); - }); - stream.on('error', (err: Error) => { - reject(err); - }); - }); - await assert.rejects(promise, expectedError); - assert((client.descriptors.page.listCollectionIds.createStream as SinonStub) - .getCall(0).calledWith(client.innerApiCalls.listCollectionIds, request)); - assert( - (client.descriptors.page.listCollectionIds.createStream as SinonStub) - .getCall(0).args[2].otherArgs.headers['x-goog-request-params'].includes( - expectedHeaderRequestParams - ) - ); - }); + it('invokes listCollectionIdsStream with error', async () => { + const client = new firestoreModule.FirestoreClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.firestore.v1.ListCollectionIdsRequest() + ); + const defaultValue1 = getTypeDefaultValue( + '.google.firestore.v1.ListCollectionIdsRequest', + ['parent'] + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.descriptors.page.listCollectionIds.createStream = + stubPageStreamingCall(undefined, expectedError); + const stream = client.listCollectionIdsStream(request); + const promise = new Promise((resolve, reject) => { + const responses: string[] = []; + stream.on('data', (response: string) => { + responses.push(response); + }); + stream.on('end', () => { + resolve(responses); + }); + stream.on('error', (err: Error) => { + reject(err); + }); + }); + await assert.rejects(promise, expectedError); + assert( + (client.descriptors.page.listCollectionIds.createStream as SinonStub) + .getCall(0) + .calledWith(client.innerApiCalls.listCollectionIds, request) + ); + assert( + (client.descriptors.page.listCollectionIds.createStream as SinonStub) + .getCall(0) + .args[2].otherArgs.headers[ + 'x-goog-request-params' + ].includes(expectedHeaderRequestParams) + ); + }); - it('uses async iteration with listCollectionIds without error', async () => { - const client = new firestoreModule.FirestoreClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.firestore.v1.ListCollectionIdsRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.firestore.v1.ListCollectionIdsRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedResponse = [new String(), new String(), new String()]; - client.descriptors.page.listCollectionIds.asyncIterate = stubAsyncIterationCall(expectedResponse); - const responses: string[] = []; - const iterable = client.listCollectionIdsAsync(request); - for await (const resource of iterable) { - responses.push(resource!); - } - assert.deepStrictEqual(responses, expectedResponse); - assert.deepStrictEqual( - (client.descriptors.page.listCollectionIds.asyncIterate as SinonStub) - .getCall(0).args[1], request); - assert( - (client.descriptors.page.listCollectionIds.asyncIterate as SinonStub) - .getCall(0).args[2].otherArgs.headers['x-goog-request-params'].includes( - expectedHeaderRequestParams - ) - ); - }); + it('uses async iteration with listCollectionIds without error', async () => { + const client = new firestoreModule.FirestoreClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.firestore.v1.ListCollectionIdsRequest() + ); + const defaultValue1 = getTypeDefaultValue( + '.google.firestore.v1.ListCollectionIdsRequest', + ['parent'] + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedResponse = [new String(), new String(), new String()]; + client.descriptors.page.listCollectionIds.asyncIterate = + stubAsyncIterationCall(expectedResponse); + const responses: string[] = []; + const iterable = client.listCollectionIdsAsync(request); + for await (const resource of iterable) { + responses.push(resource!); + } + assert.deepStrictEqual(responses, expectedResponse); + assert.deepStrictEqual( + ( + client.descriptors.page.listCollectionIds.asyncIterate as SinonStub + ).getCall(0).args[1], + request + ); + assert( + (client.descriptors.page.listCollectionIds.asyncIterate as SinonStub) + .getCall(0) + .args[2].otherArgs.headers[ + 'x-goog-request-params' + ].includes(expectedHeaderRequestParams) + ); + }); - it('uses async iteration with listCollectionIds with error', async () => { - const client = new firestoreModule.FirestoreClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new protos.google.firestore.v1.ListCollectionIdsRequest() - ); - const defaultValue1 = - getTypeDefaultValue('.google.firestore.v1.ListCollectionIdsRequest', ['parent']); - request.parent = defaultValue1; - const expectedHeaderRequestParams = `parent=${defaultValue1 ?? '' }`; - const expectedError = new Error('expected'); - client.descriptors.page.listCollectionIds.asyncIterate = stubAsyncIterationCall(undefined, expectedError); - const iterable = client.listCollectionIdsAsync(request); - await assert.rejects(async () => { - const responses: string[] = []; - for await (const resource of iterable) { - responses.push(resource!); - } - }); - assert.deepStrictEqual( - (client.descriptors.page.listCollectionIds.asyncIterate as SinonStub) - .getCall(0).args[1], request); - assert( - (client.descriptors.page.listCollectionIds.asyncIterate as SinonStub) - .getCall(0).args[2].otherArgs.headers['x-goog-request-params'].includes( - expectedHeaderRequestParams - ) - ); - }); + it('uses async iteration with listCollectionIds with error', async () => { + const client = new firestoreModule.FirestoreClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new protos.google.firestore.v1.ListCollectionIdsRequest() + ); + const defaultValue1 = getTypeDefaultValue( + '.google.firestore.v1.ListCollectionIdsRequest', + ['parent'] + ); + request.parent = defaultValue1; + const expectedHeaderRequestParams = `parent=${defaultValue1 ?? ''}`; + const expectedError = new Error('expected'); + client.descriptors.page.listCollectionIds.asyncIterate = + stubAsyncIterationCall(undefined, expectedError); + const iterable = client.listCollectionIdsAsync(request); + await assert.rejects(async () => { + const responses: string[] = []; + for await (const resource of iterable) { + responses.push(resource!); + } + }); + assert.deepStrictEqual( + ( + client.descriptors.page.listCollectionIds.asyncIterate as SinonStub + ).getCall(0).args[1], + request + ); + assert( + (client.descriptors.page.listCollectionIds.asyncIterate as SinonStub) + .getCall(0) + .args[2].otherArgs.headers[ + 'x-goog-request-params' + ].includes(expectedHeaderRequestParams) + ); }); - describe('getLocation', () => { - it('invokes getLocation without error', async () => { - const client = new firestoreModule.FirestoreClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new LocationProtos.google.cloud.location.GetLocationRequest() - ); - request.name = ''; - const expectedHeaderRequestParams = 'name='; - const expectedOptions = { - otherArgs: { - headers: { - 'x-goog-request-params': expectedHeaderRequestParams, - }, - }, - }; - const expectedResponse = generateSampleMessage( - new LocationProtos.google.cloud.location.Location() - ); - client.locationsClient.getLocation = stubSimpleCall(expectedResponse); - const response = await client.getLocation(request, expectedOptions); - assert.deepStrictEqual(response, [expectedResponse]); - assert((client.locationsClient.getLocation as SinonStub) - .getCall(0).calledWith(request, expectedOptions, undefined)); - }); - it('invokes getLocation without error using callback', async () => { - const client = new firestoreModule.FirestoreClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new LocationProtos.google.cloud.location.GetLocationRequest() - ); - request.name = ''; - const expectedHeaderRequestParams = 'name='; - const expectedOptions = { - otherArgs: { - headers: { - 'x-goog-request-params': expectedHeaderRequestParams, - }, - }, - }; - const expectedResponse = generateSampleMessage( - new LocationProtos.google.cloud.location.Location() - ); - client.locationsClient.getLocation = sinon.stub().callsArgWith(2, null, expectedResponse); - const promise = new Promise((resolve, reject) => { - client.getLocation( - request, - expectedOptions, - ( - err?: Error | null, - result?: LocationProtos.google.cloud.location.ILocation | null - ) => { - if (err) { - reject(err); - } else { - resolve(result); - } - }); - }); - const response = await promise; - assert.deepStrictEqual(response, expectedResponse); - assert((client.locationsClient.getLocation as SinonStub) - .getCall(0)); - }); - it('invokes getLocation with error', async () => { - const client = new firestoreModule.FirestoreClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new LocationProtos.google.cloud.location.GetLocationRequest() - ); - request.name = ''; - const expectedHeaderRequestParams = 'name='; - const expectedOptions = { - otherArgs: { - headers: { - 'x-goog-request-params': expectedHeaderRequestParams, - }, - }, - }; - const expectedError = new Error('expected'); - client.locationsClient.getLocation = stubSimpleCall(undefined, expectedError); - await assert.rejects(client.getLocation(request, expectedOptions), expectedError); - assert((client.locationsClient.getLocation as SinonStub) - .getCall(0).calledWith(request, expectedOptions, undefined)); - }); + }); + describe('getLocation', () => { + it('invokes getLocation without error', async () => { + const client = new firestoreModule.FirestoreClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new LocationProtos.google.cloud.location.GetLocationRequest() + ); + request.name = ''; + const expectedHeaderRequestParams = 'name='; + const expectedOptions = { + otherArgs: { + headers: { + 'x-goog-request-params': expectedHeaderRequestParams, + }, + }, + }; + const expectedResponse = generateSampleMessage( + new LocationProtos.google.cloud.location.Location() + ); + client.locationsClient.getLocation = stubSimpleCall(expectedResponse); + const response = await client.getLocation(request, expectedOptions); + assert.deepStrictEqual(response, [expectedResponse]); + assert( + (client.locationsClient.getLocation as SinonStub) + .getCall(0) + .calledWith(request, expectedOptions, undefined) + ); }); - describe('listLocationsAsync', () => { - it('uses async iteration with listLocations without error', async () => { - const client = new firestoreModule.FirestoreClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new LocationProtos.google.cloud.location.ListLocationsRequest() - ); - request.name = ''; - const expectedHeaderRequestParams = 'name='; - const expectedResponse = [ - generateSampleMessage( - new LocationProtos.google.cloud.location.Location() - ), - generateSampleMessage( - new LocationProtos.google.cloud.location.Location() - ), - generateSampleMessage( - new LocationProtos.google.cloud.location.Location() - ), - ]; - client.locationsClient.descriptors.page.listLocations.asyncIterate = stubAsyncIterationCall(expectedResponse); - const responses: LocationProtos.google.cloud.location.ILocation[] = []; - const iterable = client.listLocationsAsync(request); - for await (const resource of iterable) { - responses.push(resource!); + it('invokes getLocation without error using callback', async () => { + const client = new firestoreModule.FirestoreClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new LocationProtos.google.cloud.location.GetLocationRequest() + ); + request.name = ''; + const expectedHeaderRequestParams = 'name='; + const expectedOptions = { + otherArgs: { + headers: { + 'x-goog-request-params': expectedHeaderRequestParams, + }, + }, + }; + const expectedResponse = generateSampleMessage( + new LocationProtos.google.cloud.location.Location() + ); + client.locationsClient.getLocation = sinon + .stub() + .callsArgWith(2, null, expectedResponse); + const promise = new Promise((resolve, reject) => { + client.getLocation( + request, + expectedOptions, + ( + err?: Error | null, + result?: LocationProtos.google.cloud.location.ILocation | null + ) => { + if (err) { + reject(err); + } else { + resolve(result); } - assert.deepStrictEqual(responses, expectedResponse); - assert.deepStrictEqual( - (client.locationsClient.descriptors.page.listLocations.asyncIterate as SinonStub) - .getCall(0).args[1], request); - assert( - (client.locationsClient.descriptors.page.listLocations.asyncIterate as SinonStub) - .getCall(0).args[2].otherArgs.headers['x-goog-request-params'].includes( - expectedHeaderRequestParams - ) - ); - }); - it('uses async iteration with listLocations with error', async () => { - const client = new firestoreModule.FirestoreClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - await client.initialize(); - const request = generateSampleMessage( - new LocationProtos.google.cloud.location.ListLocationsRequest() - ); - request.name = ''; - const expectedHeaderRequestParams = 'name='; - const expectedError = new Error('expected'); - client.locationsClient.descriptors.page.listLocations.asyncIterate = stubAsyncIterationCall(undefined, expectedError); - const iterable = client.listLocationsAsync(request); - await assert.rejects(async () => { - const responses: LocationProtos.google.cloud.location.ILocation[] = []; - for await (const resource of iterable) { - responses.push(resource!); - } - }); - assert.deepStrictEqual( - (client.locationsClient.descriptors.page.listLocations.asyncIterate as SinonStub) - .getCall(0).args[1], request); - assert( - (client.locationsClient.descriptors.page.listLocations.asyncIterate as SinonStub) - .getCall(0).args[2].otherArgs.headers['x-goog-request-params'].includes( - expectedHeaderRequestParams - ) - ); - }); + } + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + assert((client.locationsClient.getLocation as SinonStub).getCall(0)); + }); + it('invokes getLocation with error', async () => { + const client = new firestoreModule.FirestoreClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new LocationProtos.google.cloud.location.GetLocationRequest() + ); + request.name = ''; + const expectedHeaderRequestParams = 'name='; + const expectedOptions = { + otherArgs: { + headers: { + 'x-goog-request-params': expectedHeaderRequestParams, + }, + }, + }; + const expectedError = new Error('expected'); + client.locationsClient.getLocation = stubSimpleCall( + undefined, + expectedError + ); + await assert.rejects( + client.getLocation(request, expectedOptions), + expectedError + ); + assert( + (client.locationsClient.getLocation as SinonStub) + .getCall(0) + .calledWith(request, expectedOptions, undefined) + ); + }); + }); + describe('listLocationsAsync', () => { + it('uses async iteration with listLocations without error', async () => { + const client = new firestoreModule.FirestoreClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new LocationProtos.google.cloud.location.ListLocationsRequest() + ); + request.name = ''; + const expectedHeaderRequestParams = 'name='; + const expectedResponse = [ + generateSampleMessage( + new LocationProtos.google.cloud.location.Location() + ), + generateSampleMessage( + new LocationProtos.google.cloud.location.Location() + ), + generateSampleMessage( + new LocationProtos.google.cloud.location.Location() + ), + ]; + client.locationsClient.descriptors.page.listLocations.asyncIterate = + stubAsyncIterationCall(expectedResponse); + const responses: LocationProtos.google.cloud.location.ILocation[] = []; + const iterable = client.listLocationsAsync(request); + for await (const resource of iterable) { + responses.push(resource!); + } + assert.deepStrictEqual(responses, expectedResponse); + assert.deepStrictEqual( + ( + client.locationsClient.descriptors.page.listLocations + .asyncIterate as SinonStub + ).getCall(0).args[1], + request + ); + assert( + ( + client.locationsClient.descriptors.page.listLocations + .asyncIterate as SinonStub + ) + .getCall(0) + .args[2].otherArgs.headers['x-goog-request-params'].includes( + expectedHeaderRequestParams + ) + ); + }); + it('uses async iteration with listLocations with error', async () => { + const client = new firestoreModule.FirestoreClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + await client.initialize(); + const request = generateSampleMessage( + new LocationProtos.google.cloud.location.ListLocationsRequest() + ); + request.name = ''; + const expectedHeaderRequestParams = 'name='; + const expectedError = new Error('expected'); + client.locationsClient.descriptors.page.listLocations.asyncIterate = + stubAsyncIterationCall(undefined, expectedError); + const iterable = client.listLocationsAsync(request); + await assert.rejects(async () => { + const responses: LocationProtos.google.cloud.location.ILocation[] = []; + for await (const resource of iterable) { + responses.push(resource!); + } + }); + assert.deepStrictEqual( + ( + client.locationsClient.descriptors.page.listLocations + .asyncIterate as SinonStub + ).getCall(0).args[1], + request + ); + assert( + ( + client.locationsClient.descriptors.page.listLocations + .asyncIterate as SinonStub + ) + .getCall(0) + .args[2].otherArgs.headers['x-goog-request-params'].includes( + expectedHeaderRequestParams + ) + ); }); + }); }); diff --git a/dev/test/index.ts b/dev/test/index.ts index bd9b2cae6..7f162de9a 100644 --- a/dev/test/index.ts +++ b/dev/test/index.ts @@ -1064,7 +1064,6 @@ describe('listCollections() method', () => { listCollectionIds: request => { expect(request).to.deep.eq({ parent: `projects/${PROJECT_ID}/databases/(default)/documents`, - pageSize: 65535, }); return response(['first', 'second']); diff --git a/dev/test/options-util.ts b/dev/test/options-util.ts new file mode 100644 index 000000000..961314d50 --- /dev/null +++ b/dev/test/options-util.ts @@ -0,0 +1,227 @@ +/** + * @license + * Copyright 2025 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. + */ + +import {expect} from 'chai'; +import {Serializer} from '../src/serializer'; +import {createInstance} from './util/helpers'; +import {Firestore} from '../src'; +import {OptionsUtil} from '../src/pipelines/options-util'; + +describe('OptionsUtil', () => { + let db: Firestore | undefined; + beforeEach(async () => { + db = await createInstance(); + }); + + afterEach(async () => { + if (db) { + await db.terminate(); + db = undefined; + } + }); + + it('should support known options', () => { + const optionsUtil = new OptionsUtil({ + fooBar: { + serverName: 'foo_bar', + }, + }); + const proto = optionsUtil.getOptionsProto(new Serializer(db!), { + fooBar: 'recommended', + }); + + expect(proto).deep.equal({ + foo_bar: { + stringValue: 'recommended', + }, + }); + }); + + it('should support unknown options', () => { + const optionsUtil = new OptionsUtil({}); + const proto = optionsUtil.getOptionsProto( + new Serializer(db!), + {}, + {baz: 'foo'} + ); + + expect(proto).to.deep.equal({ + baz: { + stringValue: 'foo', + }, + }); + }); + + it('should support unknown nested options', () => { + const optionsUtil = new OptionsUtil({}); + const proto = optionsUtil.getOptionsProto( + new Serializer(db!), + {}, + {'foo.bar': 'baz'} + ); + + expect(proto).to.deep.equal({ + foo: { + mapValue: { + fields: { + bar: {stringValue: 'baz'}, + }, + }, + }, + }); + }); + + it('should support options override', () => { + const optionsUtil = new OptionsUtil({ + indexMode: { + serverName: 'index_mode', + }, + }); + const proto = optionsUtil.getOptionsProto( + new Serializer(db!), + { + indexMode: 'recommended', + }, + { + index_mode: 'baz', + } + ); + + expect(proto).to.deep.equal({ + index_mode: { + stringValue: 'baz', + }, + }); + }); + + it('should support options override of nested field', () => { + const optionsUtil = new OptionsUtil({ + foo: { + serverName: 'foo', + nestedOptions: { + bar: { + serverName: 'bar', + }, + waldo: { + serverName: 'waldo', + }, + }, + }, + }); + const proto = optionsUtil.getOptionsProto( + new Serializer(db!), + { + foo: {bar: 'yep', waldo: 'found'}, + }, + { + 'foo.bar': 123, + 'foo.baz': true, + } + ); + + expect(proto).to.deep.equal({ + foo: { + mapValue: { + fields: { + bar: { + integerValue: '123', + }, + waldo: { + stringValue: 'found', + }, + baz: { + booleanValue: true, + }, + }, + }, + }, + }); + }); + + it('will replace a nested object if given a new object', () => { + const optionsUtil = new OptionsUtil({ + foo: { + serverName: 'foo', + nestedOptions: { + bar: { + serverName: 'bar', + }, + waldo: { + serverName: 'waldo', + }, + }, + }, + }); + const proto = optionsUtil.getOptionsProto( + new Serializer(db!), + { + foo: {bar: 'yep', waldo: 'found'}, + }, + { + foo: { + bar: 123, + }, + } + ); + + expect(proto).to.deep.equal({ + foo: { + mapValue: { + fields: { + bar: { + integerValue: '123', + }, + }, + }, + }, + }); + }); + + it('will replace a top level property that is not an object if given a nested field with dot notation', () => { + const optionsUtil = new OptionsUtil({ + foo: { + serverName: 'foo', + }, + }); + + const proto = optionsUtil.getOptionsProto( + new Serializer(db!), + { + foo: 'bar', + }, + { + 'foo.bar': '123', + 'foo.waldo': true, + } + ); + + expect(proto).to.deep.equal({ + foo: { + mapValue: { + fields: { + bar: { + stringValue: '123', + }, + waldo: { + booleanValue: true, + }, + }, + }, + }, + }); + }); +}); diff --git a/dev/test/pipelines/pipeline.ts b/dev/test/pipelines/pipeline.ts new file mode 100644 index 000000000..a646fd0b5 --- /dev/null +++ b/dev/test/pipelines/pipeline.ts @@ -0,0 +1,433 @@ +/** + * @license + * Copyright 2025 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. + */ + +import {expect} from 'chai'; +import * as sinon from 'sinon'; +import {createInstance, stream} from '../util/helpers'; +import {google} from '../../protos/firestore_v1_proto_api'; +import {Timestamp, Pipelines, Firestore} from '../../src'; +import IExecutePipelineRequest = google.firestore.v1.IExecutePipelineRequest; +import IExecutePipelineResponse = google.firestore.v1.IExecutePipelineResponse; +import Pipeline = Pipelines.Pipeline; +import field = Pipelines.field; +import sum = Pipelines.sum; +import descending = Pipelines.descending; +import IValue = google.firestore.v1.IValue; + +const FIRST_CALL = 0; +const EXECUTE_PIPELINE_REQUEST = 0; + +describe('execute(Pipeline|PipelineOptions)', () => { + it('returns execution time with empty results', async () => { + const executeTime = Timestamp.now(); + const results: IExecutePipelineResponse[] = [ + { + executionTime: executeTime.toProto().timestampValue, + results: [], + }, + ]; + + const firestore = await createInstance({ + executePipeline: () => stream(...results), + }); + + const pipelineSnapshot = await firestore + .pipeline() + .collection('foo') + .execute(); + + expect(pipelineSnapshot.results.length).to.equal(0); + + expect(pipelineSnapshot.executionTime.toProto()).to.deep.equal( + executeTime.toProto() + ); + }); + + it('serializes the pipeline', async () => { + const spy = sinon.fake.returns(stream()); + const firestore = await createInstance({ + executePipeline: spy, + }); + + await firestore.pipeline().collection('foo').execute(); + + const executePipelineRequest: IExecutePipelineRequest = { + database: 'projects/test-project/databases/(default)', + structuredPipeline: { + options: {}, + pipeline: { + stages: [ + { + args: [ + { + referenceValue: '/foo', + }, + ], + name: 'collection', + options: {}, + }, + ], + }, + }, + }; + expect(spy.args[FIRST_CALL][EXECUTE_PIPELINE_REQUEST]).to.deep.equal( + executePipelineRequest + ); + }); + + it('serializes the pipeline options', async () => { + const spy = sinon.fake.returns(stream()); + const firestore = await createInstance({ + executePipeline: spy, + }); + + await firestore + .pipeline() + .collection('foo') + .execute({ + indexMode: 'recommended', + explainOptions: { + mode: 'analyze', + outputFormat: 'json', + }, + }); + + const executePipelineRequest: IExecutePipelineRequest = { + database: 'projects/test-project/databases/(default)', + structuredPipeline: { + options: { + index_mode: { + stringValue: 'recommended', + }, + explain_options: { + mapValue: { + fields: { + mode: { + stringValue: 'analyze', + }, + output_format: { + stringValue: 'json', + }, + }, + }, + }, + }, + pipeline: { + stages: [ + { + args: [ + { + referenceValue: '/foo', + }, + ], + name: 'collection', + options: {}, + }, + ], + }, + }, + }; + expect(spy.args[FIRST_CALL][EXECUTE_PIPELINE_REQUEST]).to.deep.equal( + executePipelineRequest + ); + }); + + it('serializes the pipeline generic options', async () => { + const spy = sinon.fake.returns(stream()); + const firestore = await createInstance({ + executePipeline: spy, + }); + + await firestore + .pipeline() + .collection('foo') + .execute({ + customOptions: { + foo: 'bar', + }, + }); + + const executePipelineRequest: IExecutePipelineRequest = { + database: 'projects/test-project/databases/(default)', + structuredPipeline: { + options: { + foo: { + stringValue: 'bar', + }, + }, + pipeline: { + stages: [ + { + args: [ + { + referenceValue: '/foo', + }, + ], + name: 'collection', + options: {}, + }, + ], + }, + }, + }; + expect(spy.args[FIRST_CALL][EXECUTE_PIPELINE_REQUEST]).to.deep.equal( + executePipelineRequest + ); + }); +}); + +describe('stage option serialization', () => { + // Default custom options + const customOptions: Record = { + foo: 'bar1', + }; + // Default expected serialized options + const expectedSerializedOptions: Record = { + foo: { + stringValue: 'bar1', + }, + }; + + const testDefinitions: Array<{ + name: string; + pipeline: (firestore: Firestore) => Pipeline; + stageIndex?: number; + expectedOptions?: Record; + }> = [ + { + name: 'collection stage', + pipeline: firestore => + firestore.pipeline().collection({ + collection: 'foo', + customOptions, + forceIndex: 'foo-index', + }), + expectedOptions: { + ...expectedSerializedOptions, + force_index: { + stringValue: 'foo-index', + }, + }, + }, + { + name: 'collection group stage', + pipeline: firestore => + firestore.pipeline().collectionGroup({ + collectionId: 'foo', + customOptions, + forceIndex: 'bar-index', + }), + expectedOptions: { + ...expectedSerializedOptions, + force_index: { + stringValue: 'bar-index', + }, + }, + }, + { + name: 'documents stage', + pipeline: firestore => + firestore.pipeline().documents({ + docs: ['foo/bar'], + customOptions, + }), + }, + { + name: 'database stage', + pipeline: firestore => + firestore.pipeline().database({ + customOptions, + }), + }, + { + name: 'distinct stage', + pipeline: firestore => + firestore + .pipeline() + .database() + .distinct({ + groups: ['foo'], + customOptions, + }), + stageIndex: 1, + }, + { + name: 'findNearest stage', + pipeline: firestore => + firestore + .pipeline() + .database() + .findNearest({ + field: 'foo', + vectorValue: [0], + distanceMeasure: 'euclidean', + customOptions, + }), + stageIndex: 1, + }, + { + name: 'select stage', + pipeline: firestore => + firestore + .pipeline() + .database() + .select({ + selections: ['foo'], + customOptions, + }), + stageIndex: 1, + }, + { + name: 'unnest stage', + pipeline: firestore => + firestore + .pipeline() + .database() + .unnest({ + selectable: field('foo'), + customOptions, + }), + stageIndex: 1, + }, + { + name: 'addFields stage', + pipeline: firestore => + firestore + .pipeline() + .database() + .addFields({ + fields: [field('foo')], + customOptions, + }), + stageIndex: 1, + }, + { + name: 'aggregate stage', + pipeline: firestore => + firestore + .pipeline() + .database() + .aggregate({ + accumulators: [sum('foo').as('fooSum')], + customOptions, + }), + stageIndex: 1, + }, + { + name: 'limit stage', + pipeline: firestore => + firestore.pipeline().database().limit({ + limit: 1, + customOptions, + }), + stageIndex: 1, + }, + { + name: 'offset stage', + pipeline: firestore => + firestore.pipeline().database().offset({ + offset: 1, + customOptions, + }), + stageIndex: 1, + }, + { + name: 'removeFields stage', + pipeline: firestore => + firestore + .pipeline() + .database() + .removeFields({ + fields: ['foo'], + customOptions, + }), + stageIndex: 1, + }, + { + name: 'replaceWith stage', + pipeline: firestore => + firestore.pipeline().database().replaceWith({ + map: 'foo', + customOptions, + }), + stageIndex: 1, + }, + { + name: 'sample stage', + pipeline: firestore => + firestore.pipeline().database().sample({ + documents: 100, + customOptions, + }), + stageIndex: 1, + }, + { + name: 'sample stage', + pipeline: firestore => + firestore + .pipeline() + .database() + .sort({ + orderings: [descending('foo')], + customOptions, + }), + stageIndex: 1, + }, + { + name: 'union stage', + pipeline: firestore => + firestore.pipeline().database().union({ + other: firestore.pipeline().database(), + customOptions, + }), + stageIndex: 1, + }, + { + name: 'where stage', + pipeline: firestore => + firestore + .pipeline() + .database() + .where({ + condition: field('foo').eq(1), + customOptions, + }), + stageIndex: 1, + }, + ]; + + testDefinitions.forEach(testDefinition => { + it(testDefinition.name, async () => { + const spy = sinon.fake.returns(stream()); + const firestore = await createInstance({ + executePipeline: spy, + }); + + await testDefinition.pipeline(firestore).execute(); + + const expectedOptions = testDefinition.expectedOptions + ? testDefinition.expectedOptions + : expectedSerializedOptions; + + expect( + spy.args[FIRST_CALL][EXECUTE_PIPELINE_REQUEST]['structuredPipeline'][ + 'pipeline' + ]['stages'][testDefinition.stageIndex ?? 0]['options'] + ).to.deep.equal(expectedOptions); + }); + }); +}); diff --git a/dev/test/structured-pipeline.ts b/dev/test/structured-pipeline.ts new file mode 100644 index 000000000..89b0af406 --- /dev/null +++ b/dev/test/structured-pipeline.ts @@ -0,0 +1,183 @@ +/** + * @license + * Copyright 2025 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. + */ + +import {expect} from 'chai'; +import * as sinon from 'sinon'; +import {ProtoSerializable, Serializer} from '../src/serializer'; +import {google} from '../protos/firestore_v1_proto_api'; +import IPipeline = google.firestore.v1.IPipeline; +import {StructuredPipeline} from '../src/pipelines/structured-pipeline'; +import {createInstance} from './util/helpers'; +import {Firestore} from '../src'; + +describe('StructuredPipeline', () => { + let db: Firestore | undefined; + beforeEach(async () => { + db = await createInstance(); + }); + + afterEach(async () => { + if (db) { + await db.terminate(); + db = undefined; + } + }); + + it('should serialize the pipeline argument', async () => { + const pipeline: ProtoSerializable = { + _toProto: sinon.fake.returns({} as IPipeline), + }; + const structuredPipeline = new StructuredPipeline(pipeline, {}, {}); + + const proto = structuredPipeline._toProto(new Serializer(db!)); + + expect(proto).to.deep.equal({ + pipeline: {}, + options: {}, + }); + + expect((pipeline._toProto as sinon.SinonSpy).calledOnce).to.be.true; + }); + + it('should support known options', () => { + const pipeline: ProtoSerializable = { + _toProto: sinon.fake.returns({} as IPipeline), + }; + const structuredPipeline = new StructuredPipeline( + pipeline, + { + indexMode: 'recommended', + explainOptions: { + mode: 'explain', + outputFormat: 'json', + }, + }, + {} + ); + + const proto = structuredPipeline._toProto(new Serializer(db!)); + + expect(proto).deep.equal({ + pipeline: {}, + options: { + index_mode: { + stringValue: 'recommended', + }, + explain_options: { + mapValue: { + fields: { + mode: { + stringValue: 'explain', + }, + output_format: { + stringValue: 'json', + }, + }, + }, + }, + }, + }); + + expect((pipeline._toProto as sinon.SinonSpy).calledOnce).to.be.true; + }); + + it('should support unknown options', () => { + const pipeline: ProtoSerializable = { + _toProto: sinon.fake.returns({} as IPipeline), + }; + const structuredPipeline = new StructuredPipeline( + pipeline, + {}, + { + foo_bar: 'baz', + } + ); + + const proto = structuredPipeline._toProto(new Serializer(db!)); + + console.log(JSON.stringify(proto)); + + expect(proto).to.deep.equal({ + pipeline: {}, + options: { + foo_bar: { + stringValue: 'baz', + }, + }, + }); + + expect((pipeline._toProto as sinon.SinonSpy).calledOnce).to.be.true; + }); + + it('should support unknown nested options', () => { + const pipeline: ProtoSerializable = { + _toProto: sinon.fake.returns({} as IPipeline), + }; + const structuredPipeline = new StructuredPipeline( + pipeline, + {}, + { + 'foo.bar': 'baz', + } + ); + + const proto = structuredPipeline._toProto(new Serializer(db!)); + + expect(proto).to.deep.equal({ + pipeline: {}, + options: { + foo: { + mapValue: { + fields: { + bar: {stringValue: 'baz'}, + }, + }, + }, + }, + }); + + expect((pipeline._toProto as sinon.SinonSpy).calledOnce).to.be.true; + }); + + it('should support options override', () => { + const pipeline: ProtoSerializable = { + _toProto: sinon.fake.returns({} as IPipeline), + }; + const structuredPipeline = new StructuredPipeline( + pipeline, + { + indexMode: 'recommended', + }, + { + index_mode: 'baz', + } + ); + + const proto = structuredPipeline._toProto(new Serializer(db!)); + + expect(proto).to.deep.equal({ + pipeline: {}, + options: { + index_mode: { + stringValue: 'baz', + }, + }, + }); + + expect((pipeline._toProto as sinon.SinonSpy).calledOnce).to.be.true; + }); +}); diff --git a/package.json b/package.json index d080af86e..708694ea3 100644 --- a/package.json +++ b/package.json @@ -1,7 +1,7 @@ { "name": "@google-cloud/firestore", "description": "Firestore Client Library for Node.js", - "version": "7.11.0", + "version": "7.11.1", "license": "Apache-2.0", "author": "Google Inc.", "engines": { diff --git a/samples/package.json b/samples/package.json index 9e5c3359c..43c769f2b 100644 --- a/samples/package.json +++ b/samples/package.json @@ -11,7 +11,7 @@ "test": "mocha --timeout 600000" }, "dependencies": { - "@google-cloud/firestore": "^7.11.0" + "@google-cloud/firestore": "^7.11.1" }, "devDependencies": { "chai": "^4.2.0", diff --git a/types/firestore.d.ts b/types/firestore.d.ts index 53133967d..9393f0181 100644 --- a/types/firestore.d.ts +++ b/types/firestore.d.ts @@ -136,6 +136,19 @@ declare namespace FirebaseFirestore { ? I : never; + /** + * Utility type to create an type that only allows one + * property of the Type param T to be set. + * + * type XorY = OneOf<{ x: unknown, y: unknown}> + * let a = { x: "foo" } // OK + * let b = { y: "foo" } // OK + * let c = { a: "foo", y: "foo" } // Not OK + */ + export type OneOf = { + [K in keyof T]: Pick & {[P in Exclude]?: undefined}; + }[keyof T]; + /** * Sets or disables the log function for all active Firestore instances. * @@ -9100,61 +9113,6 @@ declare namespace FirebaseFirestore { readonly direction: 'ascending' | 'descending'; } - /** - * @beta - */ - export interface Stage { - name: string; - } - - /** - * @beta - */ - export class Aggregate implements Stage { - name: string; - } - - /** - * @beta - */ - export class Where implements Stage { - name: string; - } - - /** - * @beta - */ - export type FindNearestOptions = { - field: Field | string; - vectorValue: VectorValue | number[]; - distanceMeasure: 'euclidean' | 'cosine' | 'dot_product'; - limit?: number; - distanceField?: string; - }; - - /** - * @beta - */ - export class FindNearest implements Stage { - name: string; - } - - /** - * @beta - */ - export class Replace implements Stage { - name: string; - } - - /** - * @beta - */ - export interface UnnestOptions { - field: Selectable | string; - alias: Field | string; - indexField?: string; - } - /** * Represents the source of a Firestore {@link Pipeline}. * @beta @@ -9168,6 +9126,12 @@ declare namespace FirebaseFirestore { */ collection(collectionPath: string | CollectionReference): Pipeline; + /** + * Returns all documents from the entire collection. The collection can be nested. + * @param options - Options defining how this CollectionStage is evaluated. + */ + collection(options: CollectionStageOptions): Pipeline; + /** * Specifies the source as a collection group. * @@ -9175,6 +9139,12 @@ declare namespace FirebaseFirestore { * @return A new Pipeline object with the collection group as the source. */ collectionGroup(collectionId: string): Pipeline; + /** + * Returns all documents from a collection ID regardless of the parent. + * @param options - Options defining how this CollectionGroupStage is evaluated. + */ + + collectionGroup(options: CollectionGroupStageOptions): Pipeline; /** * Specifies the source as a database. @@ -9183,6 +9153,12 @@ declare namespace FirebaseFirestore { */ database(): Pipeline; + /** + * Returns all documents from the entire database. + * @param options - Options defining how a DatabaseStage is evaluated. + */ + database(options: DatabaseStageOptions): Pipeline; + /** * Specifies the source as a set of documents. * @@ -9191,6 +9167,15 @@ declare namespace FirebaseFirestore { */ documents(docs: Array): Pipeline; + /** + * Set the pipeline's source to the documents specified by the given paths and DocumentReferences. + * + * @param options - Options defining how this DocumentsStage is evaluated. + * + * @throws {@FirestoreError} Thrown if any of the provided DocumentReferences target a different project or database than the pipeline. + */ + documents(options: DocumentsStageOptions): Pipeline; + /** * Convert the given Query into an equivalent Pipeline. * @@ -9272,6 +9257,33 @@ declare namespace FirebaseFirestore { * @return A new Pipeline object with this stage appended to the stage list. */ addFields(field: Selectable, ...additionalFields: Selectable[]): Pipeline; + /** + * Adds new fields to outputs from previous stages. + * + * This stage allows you to compute values on-the-fly based on existing data from previous + * stages or constants. You can use this to create new fields or overwrite existing ones (if there + * is name overlaps). + * + * The added fields are defined using {@link Selectable}s, which can be: + * + * - {@link Field}: References an existing document field. + * - {@link Expr}: Either a literal value (see {@link Constant}) or a computed value + * (see {@FunctionExpr}) with an assigned alias using {@link Expr#as}. + * + * Example: + * + * ```typescript + * firestore.pipeline().collection("books") + * .addFields( + * field("rating").as("bookRating"), // Rename 'rating' to 'bookRating' + * add(5, field("quantity")).as("totalCost") // Calculate 'totalCost' + * ); + * ``` + * + * @param options - An object that specifies required and optional parameters for the stage. + * @return A new Pipeline object with this stage appended to the stage list. + */ + addFields(options: AddFieldsStageOptions): Pipeline; /** * Remove fields from outputs of previous stages. @@ -9295,6 +9307,24 @@ declare namespace FirebaseFirestore { fieldValue: Field | string, ...additionalFields: Array ): Pipeline; + /** + * Remove fields from outputs of previous stages. + * + * Example: + * + * ```typescript + * firestore.pipeline().collection('books') + * // removes field 'rating' and 'cost' from the previous stage outputs. + * .removeFields( + * field('rating'), + * 'cost' + * ); + * ``` + * + * @param options - An object that specifies required and optional parameters for the stage. + * @return A new Pipeline object with this stage appended to the stage list. + */ + removeFields(options: RemoveFieldsStageOptions): Pipeline; /** * Selects or creates a set of fields from the outputs of previous stages. @@ -9333,6 +9363,37 @@ declare namespace FirebaseFirestore { selection: Selectable | string, ...additionalSelections: Array ): Pipeline; + /** + * Selects or creates a set of fields from the outputs of previous stages. + * + *

The selected fields are defined using {@link Selectable} expressions, which can be: + * + *

    + *
  • {@code string}: Name of an existing field
  • + *
  • {@link Field}: References an existing field.
  • + *
  • {@link Function}: Represents the result of a function with an assigned alias name using + * {@link Expr#as}
  • + *
+ * + *

If no selections are provided, the output of this stage is empty. Use {@link + * Pipeline#addFields} instead if only additions are + * desired. + * + *

Example: + * + * ```typescript + * db.pipeline().collection("books") + * .select( + * "firstName", + * field("lastName"), + * field("address").toUppercase().as("upperAddress"), + * ); + * ``` + * + * @param options - An object that specifies required and optional parameters for the stage. + * @return A new Pipeline object with this stage appended to the stage list. + */ + select(options: SelectStageOptions): Pipeline; /** * Filters the documents from previous stages to only include those matching the specified {@link @@ -9366,6 +9427,38 @@ declare namespace FirebaseFirestore { * @return A new Pipeline object with this stage appended to the stage list. */ where(condition: BooleanExpr): Pipeline; + /** + * Filters the documents from previous stages to only include those matching the specified {@link + * BooleanExpr}. + * + *

This stage allows you to apply conditions to the data, similar to a "WHERE" clause in SQL. + * You can filter documents based on their field values, using implementations of {@link + * BooleanExpr}, typically including but not limited to: + * + *

    + *
  • field comparators: {@link Function#eq}, {@link Function#lt} (less than), {@link + * Function#gt} (greater than), etc.
  • + *
  • logical operators: {@link Function#and}, {@link Function#or}, {@link Function#not}, etc.
  • + *
  • advanced functions: {@link Function#regexMatch}, {@link + * Function#arrayContains}, etc.
  • + *
+ * + *

Example: + * + * ```typescript + * firestore.pipeline().collection("books") + * .where( + * and( + * gt(field("rating"), 4.0), // Filter for ratings greater than 4.0 + * field("genre").eq("Science Fiction") // Equivalent to gt("genre", "Science Fiction") + * ) + * ); + * ``` + * + * @param options - An object that specifies required and optional parameters for the stage. + * @return A new Pipeline object with this stage appended to the stage list. + */ + where(options: WhereStageOptions): Pipeline; /** * Skips the first `offset` number of documents from the results of previous stages. @@ -9388,6 +9481,27 @@ declare namespace FirebaseFirestore { * @return A new Pipeline object with this stage appended to the stage list. */ offset(offset: number): Pipeline; + /** + * Skips the first `offset` number of documents from the results of previous stages. + * + *

This stage is useful for implementing pagination in your pipelines, allowing you to retrieve + * results in chunks. It is typically used in conjunction with {@link #limit} to control the + * size of each page. + * + *

Example: + * + * ```typescript + * // Retrieve the second page of 20 results + * firestore.pipeline().collection('books') + * .sort(field('published').descending()) + * .offset(20) // Skip the first 20 results + * .limit(20); // Take the next 20 results + * ``` + * + * @param options - An object that specifies required and optional parameters for the stage. + * @return A new Pipeline object with this stage appended to the stage list. + */ + offset(options: OffsetStageOptions): Pipeline; /** * Limits the maximum number of documents returned by previous stages to `limit`. @@ -9415,6 +9529,32 @@ declare namespace FirebaseFirestore { * @return A new Pipeline object with this stage appended to the stage list. */ limit(limit: number): Pipeline; + /** + * Limits the maximum number of documents returned by previous stages to `limit`. + * + *

This stage is particularly useful when you want to retrieve a controlled subset of data from + * a potentially large result set. It's often used for: + * + *

    + *
  • **Pagination:** In combination with {@link #offset} to retrieve specific pages of + * results.
  • + *
  • **Limiting Data Retrieval:** To prevent excessive data transfer and improve performance, + * especially when dealing with large collections.
  • + *
+ * + *

Example: + * + * ```typescript + * // Limit the results to the top 10 highest-rated books + * firestore.pipeline().collection('books') + * .sort(field('rating').descending()) + * .limit(10); + * ``` + * + * @param options - An object that specifies required and optional parameters for the stage. + * @return A new Pipeline object with this stage appended to the stage list. + */ + limit(options: LimitStageOptions): Pipeline; /** * Returns a set of distinct values from the inputs to this stage. @@ -9448,6 +9588,32 @@ declare namespace FirebaseFirestore { group: string | Selectable, ...additionalGroups: Array ): Pipeline; + /** + * Returns a set of distinct values from the inputs to this stage. + * + * This stage runs through the results from previous stages to include only results with + * unique combinations of {@link Expr} values ({@link Field}, {@link Function}, etc). + * + * The parameters to this stage are defined using {@link Selectable} expressions or strings: + * + * - {@code string}: Name of an existing field + * - {@link Field}: References an existing document field. + * - {@link ExprWithAlias}: Represents the result of a function with an assigned alias name + * using {@link Expr#as}. + * + * Example: + * + * ```typescript + * // Get a list of unique author names in uppercase and genre combinations. + * firestore.pipeline().collection("books") + * .distinct(toUppercase(field("author")).as("authorName"), field("genre"), "publishedAt") + * .select("authorName"); + * ``` + * + * @param options - An object that specifies required and optional parameters for the stage. + * @return A new {@code Pipeline} object with this stage appended to the stage list. + */ + distinct(options: DistinctStageOptions): Pipeline; /** * Performs aggregation operations on the documents from previous stages. @@ -9505,17 +9671,38 @@ declare namespace FirebaseFirestore { * }); * ``` * - * @param options An object that specifies the accumulators - * and optional grouping fields to perform. + * @param options - An object that specifies required and optional parameters for the stage. * @return A new {@code Pipeline} object with this stage appended to the stage * list. */ - aggregate(options: { - accumulators: AggregateWithAlias[]; - groups?: Array; - }): Pipeline; + aggregate(options: AggregateStageOptions): Pipeline; - findNearest(options: FindNearestOptions): Pipeline; + /** + * Performs a vector proximity search on the documents from the previous stage, returning the + * K-nearest documents based on the specified query `vectorValue` and `distanceMeasure`. The + * returned documents will be sorted in order from nearest to furthest from the query `vectorValue`. + * + *

Example: + * + * ```typescript + * // Find the 10 most similar books based on the book description. + * const bookDescription = "Lorem ipsum..."; + * const queryVector: number[] = ...; // compute embedding of `bookDescription` + * + * firestore.pipeline().collection("books") + * .findNearest({ + * field: 'embedding', + * vectorValue: queryVector, + * distanceMeasure: 'euclidean', + * limit: 10, // optional + * distanceField: 'computedDistance' // optional + * }); + * ``` + * + * @param options - An object that specifies required and optional parameters for the stage. + * @return A new {@code Pipeline} object with this stage appended to the stage list. + */ + findNearest(options: FindNearestStageOptions): Pipeline; /** * Fully overwrites all fields in a document with those coming from a nested map. @@ -9589,20 +9776,58 @@ declare namespace FirebaseFirestore { replaceWith(expr: Expr): Pipeline; /** - * Performs a pseudo-random sampling of the documents from the previous stage. + * Fully overwrites all fields in a document with those coming from a map. * - *

This stage will filter documents pseudo-randomly. The parameter specifies how number of - * documents to be returned. + *

This stage allows you to emit a map value as a document. Each key of the map becomes a field + * on the document that contains the corresponding value. * - *

Examples: + *

Example: * * ```typescript - * // Sample 25 books, if available. - * firestore.pipeline().collection('books') - * .sample(25); - * ``` + * // Input. + * // { + * // 'name': 'John Doe Jr.', + * // 'parents': { + * // 'father': 'John Doe Sr.', + * // 'mother': 'Jane Doe' + * // } + * // } * - * @param documents The number of documents to sample. + * // Emit parents as document. + * firestore.pipeline().collection('people').replaceWith(map({ + * foo: 'bar', + * info: { + * name: field('name') + * } + * })); + * + * // Output + * // { + * // 'father': 'John Doe Sr.', + * // 'mother': 'Jane Doe' + * // } + * ``` + * + * @param options - An object that specifies required and optional parameters for the stage. + * @return A new {@code Pipeline} object with this stage appended to the stage list. + */ + replaceWith(options: ReplaceWithStageOptions): Pipeline; + + /** + * Performs a pseudo-random sampling of the documents from the previous stage. + * + *

This stage will filter documents pseudo-randomly. The parameter specifies how number of + * documents to be returned. + * + *

Examples: + * + * ```typescript + * // Sample 25 books, if available. + * firestore.pipeline().collection('books') + * .sample(25); + * ``` + * + * @param documents The number of documents to sample. * @return A new {@code Pipeline} object with this stage appended to the stage list. */ sample(documents: number): Pipeline; @@ -9629,31 +9854,25 @@ declare namespace FirebaseFirestore { sample(options: {percentage: number} | {documents: number}): Pipeline; /** - * Sorts the documents from previous stages based on one or more {@link Ordering} criteria. + * Performs a pseudo-random sampling of the documents from the previous stage. * - *

This stage allows you to order the results of your pipeline. You can specify multiple {@link - * Ordering} instances to sort by multiple fields in ascending or descending order. If documents - * have the same value for a field used for sorting, the next specified ordering will be used. If - * all orderings result in equal comparison, the documents are considered equal and the order is - * unspecified. + *

This stage will filter documents pseudo-randomly. The 'options' parameter specifies how + * sampling will be performed. See {@code SampleOptions} for more information. * - *

Example: + *

Examples: * - * ```typescript - * // Sort books by rating in descending order, and then by title in ascending order for books - * // with the same rating + * // Sample 10 books, if available. * firestore.pipeline().collection("books") - * .sort( - * Ordering.of(field("rating")).descending(), - * Ordering.of(field("title")) // Ascending order is the default - * ); - * ``` + * .sample({ documents: 10 }); * - * @param ordering The first {@link Ordering} instance specifying the sorting criteria. - * @param additionalOrderings Optional additional {@link Ordering} instances specifying the additional sorting criteria. + * // Sample 50% of books. + * firestore.pipeline().collection("books") + * .sample({ percentage: 0.5 }); + * + * @param options - An object that specifies required and optional parameters for the stage. * @return A new {@code Pipeline} object with this stage appended to the stage list. */ - sort(ordering: Ordering, ...additionalOrderings: Ordering[]): Pipeline; + sample(options: SampleStageOptions): Pipeline; /** * Performs union of all documents from two pipelines, including duplicates. @@ -9674,6 +9893,25 @@ declare namespace FirebaseFirestore { * @return A new {@code Pipeline} object with this stage appended to the stage list. */ union(other: Pipeline): Pipeline; + /** + * Performs union of all documents from two pipelines, including duplicates. + * + *

This stage will pass through documents from previous stage, and also pass through documents + * from previous stage of the `other` {@code Pipeline} given in parameter. The order of documents + * emitted from this stage is undefined. + * + *

Example: + * + * ```typescript + * // Emit documents from books collection and magazines collection. + * firestore.pipeline().collection('books') + * .union(firestore.pipeline().collection('magazines')); + * ``` + * + * @param options - An object that specifies required and optional parameters for the stage. + * @return A new {@code Pipeline} object with this stage appended to the stage list. + */ + union(options: UnionStageOptions): Pipeline; /** * Produces a document for each element in an input array. @@ -9708,6 +9946,90 @@ declare namespace FirebaseFirestore { * @return A new {@code Pipeline} object with this stage appended to the stage list. */ unnest(selectable: Selectable, indexField?: string): Pipeline; + /** + * Produces a document for each element in an input array. + * + * For each previous stage document, this stage will emit zero or more augmented documents. The + * input array specified by the `selectable` parameter, will emit an augmented document for each input array element. The input array element will + * augment the previous stage document by setting the `alias` field with the array element value. + * + * When `selectable` evaluates to a non-array value (ex: number, null, absent), then the stage becomes a no-op for + * the current input document, returning it as is with the `alias` field absent. + * + * No documents are emitted when `selectable` evaluates to an empty array. + * + * Example: + * + * ```typescript + * // Input: + * // { "title": "The Hitchhiker's Guide to the Galaxy", "tags": [ "comedy", "space", "adventure" ], ... } + * + * // Emit a book document for each tag of the book. + * firestore.pipeline().collection("books") + * .unnest(field("tags").as('tag'), 'tagIndex'); + * + * // Output: + * // { "title": "The Hitchhiker's Guide to the Galaxy", "tag": "comedy", "tagIndex": 0, ... } + * // { "title": "The Hitchhiker's Guide to the Galaxy", "tag": "space", "tagIndex": 1, ... } + * // { "title": "The Hitchhiker's Guide to the Galaxy", "tag": "adventure", "tagIndex": 2, ... } + * ``` + * + * @param options - An object that specifies required and optional parameters for the stage. + * @return A new {@code Pipeline} object with this stage appended to the stage list. + */ + unnest(options: UnnestStageOptions): Pipeline; + + /** + * Sorts the documents from previous stages based on one or more {@link Ordering} criteria. + * + *

This stage allows you to order the results of your pipeline. You can specify multiple {@link + * Ordering} instances to sort by multiple fields in ascending or descending order. If documents + * have the same value for a field used for sorting, the next specified ordering will be used. If + * all orderings result in equal comparison, the documents are considered equal and the order is + * unspecified. + * + *

Example: + * + * ```typescript + * // Sort books by rating in descending order, and then by title in ascending order for books + * // with the same rating + * firestore.pipeline().collection("books") + * .sort( + * Ordering.of(field("rating")).descending(), + * Ordering.of(field("title")) // Ascending order is the default + * ); + * ``` + * + * @param ordering The first {@link Ordering} instance specifying the sorting criteria. + * @param additionalOrderings Optional additional {@link Ordering} instances specifying the additional sorting criteria. + * @return A new {@code Pipeline} object with this stage appended to the stage list. + */ + sort(ordering: Ordering, ...additionalOrderings: Ordering[]): Pipeline; + /** + * Sorts the documents from previous stages based on one or more {@link Ordering} criteria. + * + *

This stage allows you to order the results of your pipeline. You can specify multiple {@link + * Ordering} instances to sort by multiple fields in ascending or descending order. If documents + * have the same value for a field used for sorting, the next specified ordering will be used. If + * all orderings result in equal comparison, the documents are considered equal and the order is + * unspecified. + * + *

Example: + * + * ```typescript + * // Sort books by rating in descending order, and then by title in ascending order for books + * // with the same rating + * firestore.pipeline().collection("books") + * .sort( + * Ordering.of(field("rating")).descending(), + * Ordering.of(field("title")) // Ascending order is the default + * ); + * ``` + * + * @param options - An object that specifies required and optional parameters for the stage. + * @return A new {@code Pipeline} object with this stage appended to the stage list. + */ + sort(options: SortStageOptions): Pipeline; /** * Adds a generic stage to the pipeline. @@ -9730,6 +10052,7 @@ declare namespace FirebaseFirestore { * @return A new {@code Pipeline} object with this stage appended to the stage list. */ genericStage(name: string, params: any[]): Pipeline; + /** * Executes this pipeline and returns a Promise to represent the asynchronous operation. * @@ -9759,9 +10082,10 @@ declare namespace FirebaseFirestore { * .execute(); * ``` * + * @param pipelineOptions - Optionally specify pipeline execution behavior. * @return A Promise representing the asynchronous pipeline execution. */ - execute(): Promise; + execute(pipelineOptions?: PipelineOptions): Promise; /** * Executes this pipeline and streams the results as {@link PipelineResult}s. @@ -9781,6 +10105,372 @@ declare namespace FirebaseFirestore { */ stream(): NodeJS.ReadableStream; } + + /** + * Options defining how a Pipeline is evaluated. + */ + export type PipelineOptions = { + /** + * Pipeline to be evaluated. + */ + pipeline: Pipeline; + + /** + * Specify the index mode. + */ + indexMode?: 'recommended'; + + /** + * An escape hatch to set options not known at SDK build time. These values + * will be passed directly to the Firestore backend and not used by the SDK. + * + * The option name will be used as provided. And must match the name + * format used by the backend (hint: use a snake_case_name). + * + * Custom option values can be any type supported + * by Firestore (for example: string, boolean, number, map, …). Value types + * not known to the SDK will be rejected. + * + * Values specified in customOptions will take precedence over any options + * with the same name set by the SDK. + * + * Override the `example_option`: + * ``` + * execute({ + * pipeline: myPipeline, + * customOptions: { + * // Override `example_option`. This will not + * // merge with the existing `example_option` object. + * "example_option": { + * foo: "bar" + * } + * } + * } + * ``` + * + * `customOptions` supports dot notation, if you want to override + * a nested option. + * ``` + * execute({ + * pipeline: myPipeline, + * customOptions: { + * // Override `example_option.foo` and do not override + * // any other properties of `example_option`. + * "example_option.foo": "bar" + * } + * } + * ``` + */ + customOptions?: { + [name: string]: unknown; + }; + }; + + /** + * Options defining how a Stage is evaluated. + */ + export type StageOptions = { + /** + * An escape hatch to set options not known at SDK build time. These values + * will be passed directly to the Firestore backend and not used by the SDK. + * + * The option name will be used as provided. And must match the name + * format used by the backend (hint: use a snake_case_name). + * + * Custom option values can be any type supported + * by Firestore (for example: string, boolean, number, map, …). Value types + * not known to the SDK will be rejected. + * + * Values specified in customOptions will take precedence over any options + * with the same name set by the SDK. + * + * `customOptions` supports dot notation, if you want to override + * a nested option. + */ + customOptions?: { + [name: string]: unknown; + }; + }; + + /** + * Options defining how a CollectionStage is evaluated. See {@link PipelineSource.collection}. + */ + export type CollectionStageOptions = StageOptions & { + /** + * Name or reference to the collection that will be used as the Pipeline source. + */ + collection: string | CollectionReference; + + /** + * Force index + */ + forceIndex?: string; + }; + + /** + * Options defining how a CollectionGroupStage is evaluated. See {@link PipelineSource.collectionGroup}. + */ + export type CollectionGroupStageOptions = StageOptions & { + /** + * ID of the collection group to use as the Pipeline source. + */ + collectionId: string; + + /** + * Force index + */ + forceIndex?: string; + }; + + /** + * Options defining how a DatabaseStage is evaluated. See {@link PipelineSource.database}. + */ + export type DatabaseStageOptions = StageOptions & {}; + + /** + * Options defining how a DocumentsStage is evaluated. See {@link PipelineSource.documents}. + */ + export type DocumentsStageOptions = StageOptions & { + /** + * An array of paths and DocumentReferences specifying the individual documents that will be the source of this pipeline. + * The converters for these DocumentReferences will be ignored and not have an effect on this pipeline. + * There must be at least one document specified in the array. + */ + docs: Array; + }; + + /** + * Options defining how an AddFieldsStage is evaluated. See {@link Pipeline.addFields}. + */ + export type AddFieldsStageOptions = StageOptions & { + /** + * The fields to add to each document, specified as a {@link Selectable}. + * At least one field is required. + */ + fields: Selectable[]; + }; + + /** + * Options defining how a RemoveFieldsStage is evaluated. See {@link Pipeline.removeFields}. + */ + export type RemoveFieldsStageOptions = StageOptions & { + /** + * The fields to remove from each document. + */ + fields: Array; + }; + + /** + * Options defining how a SelectStage is evaluated. See {@link Pipeline.select}. + */ + export type SelectStageOptions = StageOptions & { + /** + * The fields to include in the output documents, specified as {@link Selectable} expression + * or as a string value indicating the field name. + */ + selections: Array; + }; + + /** + * Options defining how a WhereStage is evaluated. See {@link Pipeline.where}. + */ + export type WhereStageOptions = StageOptions & { + /** + * The {@link BooleanExpr} to apply as a filter for each input document to this stage. + */ + condition: BooleanExpr; + }; + + /** + * Options defining how an OffsetStage is evaluated. See {@link Pipeline.offset}. + */ + export type OffsetStageOptions = StageOptions & { + /** + * The number of documents to skip. + */ + offset: number; + }; + + /** + * Options defining how a LimitStage is evaluated. See {@link Pipeline.limit}. + */ + export type LimitStageOptions = StageOptions & { + /** + * The maximum number of documents to return. + */ + limit: number; + }; + + /** + * Options defining how a DistinctStage is evaluated. See {@link Pipeline.distinct}. + */ + export type DistinctStageOptions = StageOptions & { + /** + * The {@link Selectable} expressions or field names to consider when determining + * distinct value combinations (groups). + */ + groups: Array; + }; + + /** + * Options defining how an AggregateStage is evaluated. See {@link Pipeline.aggregate}. + */ + export type AggregateStageOptions = StageOptions & { + /** + * The {@link AggregateWithAlias} values specifying aggregate operations to + * perform on the input documents. + */ + accumulators: AggregateWithAlias[]; + + /** + * The {@link Selectable} expressions or field names to consider when determining + * distinct value combinations (groups), which will be aggregated over. + */ + groups?: Array; + }; + + /** + * Options defining how a FindNearestStage is evaluated. See {@link Pipeline.findNearest}. + */ + export type FindNearestStageOptions = StageOptions & { + /** + * Specifies the field on the source documents to which the vector distance will be computed against the query vector. + */ + field: Field | string; + /** + * Specifies the query vector value, to which the vector distance will be computed. + */ + vectorValue: VectorValue | number[]; + /** + * Specifies how the distance is computed. + */ + distanceMeasure: 'euclidean' | 'cosine' | 'dot_product'; + /** + * The maximum number of documents to return from the FindNearest stage. + */ + limit?: number; + /** + * If set, specifies the field on the output documents that will contain + * the computed vector distance for the document. If not set, the computed + * vector distance will not be returned. + */ + distanceField?: string; + }; + + /** + * Options defining how a ReplaceWithStage is evaluated. See {@link Pipeline.replaceWith}. + */ + export type ReplaceWithStageOptions = StageOptions & { + /** + * The name of a field that contains a map or an {@link Expr} that + * evaluates to a map. + */ + map: Expr | string; + }; + + /** + * Options defining how a SampleStage is evaluated. See {@link Pipeline.findNearest}. + */ + export type SampleStageOptions = StageOptions & + OneOf<{ + /** + * If set, specifies the sample rate as a percentage of the + * input documents. + * + * Cannot be set when `documents: number` is set. + */ + percentage: number; + /** + * If set, specifies the sample rate as a total number of + * documents to sample from the input documents. + * + * Cannot be set when `percentage: number` is set. + */ + documents: number; + }>; + + /** + * Options defining how a UnionStage is evaluated. See {@link Pipeline.union}. + */ + export type UnionStageOptions = StageOptions & { + /** + * Specifies the other Pipeline to union with. + */ + other: Pipeline; + }; + + /** + * Options defining how an UnnestStage is evaluated. See {@link Pipeline.findNearest}. + */ + export type UnnestStageOptions = StageOptions & { + /** + * Specifies the expression evaluating to an array of elements, which will be un-nested + * into the field specified by `selectable.alias`. + */ + selectable: Selectable; + /** + * If set, specifies the field on the output documents that will contain the + * offset (starting at zero) that the element is from the original array. + */ + indexField?: string; + }; + + /** + * Options defining how a SortStage is evaluated. See {@link Pipeline.sort}. + */ + export type SortStageOptions = StageOptions & { + /** + * Orderings specify how the input documents are sorted. + * One or more ordering are required. + */ + orderings: Ordering[]; + }; + + /** + * Type representing the possible explain stats values. + */ + export type ExplainStatsFieldValue = + | null + | string + | number + | boolean + | {[key: string]: ExplainStatsFieldValue} + | ExplainStatsFieldValue[]; + + /** + * A wrapper object to access explain stats if explain or analyze + * was enabled for the Pipeline query execution. + */ + export class ExplainStats { + /** + * When explain stats were requested with `outputFormat = 'json'`, this returns + * the explain stats object parsed from the JSON string returned from the Firestore + * backend. + * + * If explain stats were not requested with `outputFormat = 'json'`, the behavior + * of this method is not guaranteed and is expected to throw. + */ + get json(): {[key: string]: ExplainStatsFieldValue}; + + /** + * When explain stats were requested with `outputFormat = 'text'`, this returns + * the explain stats string verbatium as returned from the Firestore backend. + * + * If explain stats were requested with `outputFormat = 'json'`, this returns + * the explain stats as stringified JSON, which was returned from the Firestore backend. + */ + get text(): string; + + /** + * Returns the explain stats in an encoded proto format, as returned from the Firestore backend. + * The caller is responsible for unpacking this proto message. + */ + get rawData(): { + type_url?: string | null; + value?: Uint8Array | null; + }; + } + /** * TODO(docs) */ @@ -9798,10 +10488,16 @@ declare namespace FirebaseFirestore { * The time at which the pipeline producing this result is executed. * * @type {Timestamp} - * @readonly * */ get executionTime(): Timestamp; + + /** + * Return stats from query explain. + * + * If `explainOptions.mode` was set to `execute` or left unset, then this returns `undefined`. + */ + get explainStats(): ExplainStats | undefined; } /** From 731dfe6a9d9758413ada3965ecdb66dfd4af5d80 Mon Sep 17 00:00:00 2001 From: Mark Duckworth <1124037+MarkDuckworth@users.noreply.github.com> Date: Thu, 31 Jul 2025 12:13:33 -0600 Subject: [PATCH 42/60] Test error propagation for pipelines (#2390) * Separate pipelines API into a subpackages * Finish refactoring Pipelines to namespace of the main module export. Also include @google-cloud/firestore/pipelines as an alternative submodule import * Updated samples and added placeholder in readme partials, for pipelines * Update signatures of add and multiply to take exactly 2 args * PipelineOptions for execute * Every stage accepts a StageOptions object * Implement and test stage options * Preview protos * Update.sh script fixes * Update google-gax dependency to v5 * Fixed preview protos * Fixes for google-gax major version update * Code formatting * Implement explain result parsing and tests. * Replaced rawValue(): unknown with rawData(): IAny * Test error propagation for pipelines. * Test that explain stats are accessible in an error case. * Formatting --- dev/src/v1/firestore_client.ts | 5 +-- dev/system-test/pipeline.ts | 73 ++++++++++++++++++++++++++++++++++ 2 files changed, 74 insertions(+), 4 deletions(-) diff --git a/dev/src/v1/firestore_client.ts b/dev/src/v1/firestore_client.ts index 895901eb8..67c7e25e1 100644 --- a/dev/src/v1/firestore_client.ts +++ b/dev/src/v1/firestore_client.ts @@ -360,10 +360,7 @@ export class FirestoreClient { }, (err: Error | null | undefined) => { this._stubFailed = true; - this._log.error( - 'Failed to create the gax client stub.', - err - ); + this._log.error('Failed to create the gax client stub.', err); return () => { throw err; }; diff --git a/dev/system-test/pipeline.ts b/dev/system-test/pipeline.ts index 2a851b849..d145e17ef 100644 --- a/dev/system-test/pipeline.ts +++ b/dev/system-test/pipeline.ts @@ -127,6 +127,9 @@ import {itIf, verifyInstance} from '../test/util/helpers'; import {getTestDb, getTestRoot} from './firestore'; import {Firestore as InternalFirestore} from '../src'; +import {ServiceError} from 'google-gax'; + +import * as google from '../protos/firestore_v1_proto_api'; use(chaiAsPromised); @@ -1611,6 +1614,76 @@ describe.only('Pipeline class', () => { }); }); + describe('error handling', () => { + it('error properties are propagated from the firestore backend', async () => { + try { + await firestore + .pipeline() + .collection(randomCol.path) + .genericStage('select', [ + // incorrect parameter type + field('title'), + ]) + .execute(); + + expect.fail('expected pipeline.execute() to throw'); + } catch (e: unknown) { + expect(e instanceof Error).to.be.true; + const err = e as ServiceError; + expect(err['code']).to.equal(3); + expect(typeof err['message']).to.equal('string'); + expect(typeof err['details']).to.equal('string'); + expect(typeof err['stack']).to.equal('string'); + expect(err['metadata'] instanceof Object).to.be.true; + + expect(err['message']).to.equal( + `${err.code} INVALID_ARGUMENT: ${err.details}` + ); + } + }); + + it('can access explain stats in error condition', async () => { + try { + await firestore + .pipeline() + .collection(randomCol.path) + .sort(field('rating').ascending()) + .execute({ + explainOptions: { + mode: 'analyze', + }, + customOptions: { + memory_limit: 1, + }, + }); + + expect.fail('expected pipeline.execute() to throw'); + } catch (e: unknown) { + const err = e as {[k: string]: unknown}; + expect(err instanceof Error).to.be.true; + + expect(err['code']).to.equal(8); + expect(typeof err['message']).to.equal('string'); + expect(typeof err['details']).to.equal('string'); + expect(typeof err['stack']).to.equal('string'); + expect(err['metadata'] instanceof Object).to.be.true; + + expect(err['message']).to.equal( + `${err.code} RESOURCE_EXHAUSTED: ${err.details}` + ); + + expect('statusDetails' in err).to.be.true; + expect(Array.isArray(err['statusDetails'])).to.be.true; + const explainStatsAny = ( + err['statusDetails'] as Array + )[0] as google.google.protobuf.IAny; + expect(explainStatsAny['type_url']).to.equal( + 'type.googleapis.com/google.firestore.v1.ExplainStats' + ); + } + }); + }); + describe('generic stage', () => { it('can select fields', async () => { const snapshot = await firestore From 689a03dcf99fbd238282ba7042424bbce96f12fe Mon Sep 17 00:00:00 2001 From: Mark Duckworth <1124037+MarkDuckworth@users.noreply.github.com> Date: Tue, 21 Oct 2025 14:30:33 -0600 Subject: [PATCH 43/60] More expressions and API cleanup (#2393) --- .eslintrc.json | 16 +- dev/src/index.ts | 8 +- dev/src/path.ts | 12 +- dev/src/pipelines/expression.ts | 2027 ++++++-------- dev/src/pipelines/index.ts | 32 +- dev/src/pipelines/pipeline-options.ts | 86 - dev/src/pipelines/pipeline-util.ts | 51 +- dev/src/pipelines/pipelines.ts | 206 +- dev/src/pipelines/stage.ts | 54 +- dev/src/serializer.ts | 14 +- dev/system-test/pipeline.ts | 1168 +++++--- dev/test/path.ts | 54 + dev/test/pipelines/pipeline.ts | 50 +- dev/test/serializer.ts | 58 +- dev/test/watch.ts | 2 +- package.json | 10 +- samples/pipelines-quickstart.js | 2 + types/firestore.d.ts | 3713 +++++++++++-------------- 18 files changed, 3613 insertions(+), 3950 deletions(-) delete mode 100644 dev/src/pipelines/pipeline-options.ts diff --git a/.eslintrc.json b/.eslintrc.json index 21dba5c59..fb4048cea 100644 --- a/.eslintrc.json +++ b/.eslintrc.json @@ -3,7 +3,11 @@ "overrides": [ { "files": [ - "dev/src/*.ts" + "dev/src/**/*.ts" + ], + "excludedFiles": [ + "dev/src/v1/*.ts", + "dev/src/v1beta1/*.ts" ], "parser": "@typescript-eslint/parser", "rules": { @@ -18,7 +22,8 @@ "@typescript-eslint/no-unused-vars": [ "warn", { - "argsIgnorePattern": "^_$" // Ignore args that are underscore only + // Ignore args that are underscore only + "argsIgnorePattern": "^_$" } ] } @@ -40,6 +45,13 @@ "object": "it", "property": "only" } + ], + "@typescript-eslint/no-unused-vars": [ + "warn", + { + // Ignore args that are underscore only + "argsIgnorePattern": "^_$" + } ] } } diff --git a/dev/src/index.ts b/dev/src/index.ts index e50013c36..73095d4ed 100644 --- a/dev/src/index.ts +++ b/dev/src/index.ts @@ -949,7 +949,13 @@ export class Firestore implements firestore.Firestore { } /** - * TODO + * @beta + * Creates and returns a new PipelineSource, which allows specifying the source stage of a {@link Pipeline}. + * + * @example + * ``` + * let myPipeline: Pipeline = firestore.pipeline().collection('books'); + * ``` */ pipeline(): PipelineSource { return new PipelineSource(this); diff --git a/dev/src/path.ts b/dev/src/path.ts index 5b49887ba..a05d40c01 100644 --- a/dev/src/path.ts +++ b/dev/src/path.ts @@ -43,8 +43,7 @@ export const DEFAULT_DATABASE_ID = '(default)'; * @type {RegExp} */ const RESOURCE_PATH_RE = - // Note: [\s\S] matches all characters including newlines. - /^projects\/([^/]*)\/databases\/([^/]*)(?:\/documents\/)?([\s\S]*)$/; + /^projects\/([^/]+)\/databases\/([^/]+)(?:\/documents(?:\/([^/]+(?:\/[^/]+)*))?)?$/; /*! * A regular expression to verify whether a field name can be passed to the @@ -455,8 +454,13 @@ export class QualifiedResourcePath extends ResourcePath { if (elements) { const project = elements[1]; const database = elements[2]; - const path = elements[3]; - return new QualifiedResourcePath(project, database).append(path); + const root = new QualifiedResourcePath(project, database); + + if (!elements[3]) { + return root; + } else { + return root.append(elements[3]); + } } throw new Error(`Resource name '${absolutePath}' is not valid.`); diff --git a/dev/src/pipelines/expression.ts b/dev/src/pipelines/expression.ts index aebb76436..d8a322d8d 100644 --- a/dev/src/pipelines/expression.ts +++ b/dev/src/pipelines/expression.ts @@ -29,6 +29,7 @@ import {HasUserData, Serializer, validateUserInput} from '../serializer'; import {cast} from '../util'; /** + * @beta * Represents an expression that can be evaluated to a value within the execution of a {@link * Pipeline}. * @@ -46,6 +47,7 @@ export abstract class Expr implements firestore.Pipelines.Expr, HasUserData { abstract exprType: firestore.Pipelines.ExprType; /** + * @beta * @internal * @private * Indicates if this expression was created from a literal value passed @@ -54,6 +56,7 @@ export abstract class Expr implements firestore.Pipelines.Expr, HasUserData { _createdFromLiteral = false; /** + * @beta * @private * @internal */ @@ -61,12 +64,14 @@ export abstract class Expr implements firestore.Pipelines.Expr, HasUserData { _protoValueType = 'ProtoValue' as const; /** + * @beta * @private * @internal */ abstract _validateUserData(ignoreUndefinedProperties: boolean): void; /** + * @beta * Creates an expression that adds this expression to another expression. * * ```typescript @@ -90,6 +95,7 @@ export abstract class Expr implements firestore.Pipelines.Expr, HasUserData { } /** + * @beta * Creates an expression that subtracts another expression from this expression. * * ```typescript @@ -97,12 +103,13 @@ export abstract class Expr implements firestore.Pipelines.Expr, HasUserData { * field("price").subtract(field("discount")); * ``` * - * @param other The expression to subtract from this expression. + * @param subtrahend The expression to subtract from this expression. * @return A new `Expr` representing the subtraction operation. */ - subtract(other: firestore.Pipelines.Expr): FunctionExpr; + subtract(subtrahend: firestore.Pipelines.Expr): FunctionExpr; /** + * @beta * Creates an expression that subtracts a constant value from this expression. * * ```typescript @@ -110,15 +117,16 @@ export abstract class Expr implements firestore.Pipelines.Expr, HasUserData { * field("total").subtract(20); * ``` * - * @param other The constant value to subtract. + * @param subtrahend The constant value to subtract. * @return A new `Expr` representing the subtraction operation. */ - subtract(other: number): FunctionExpr; - subtract(other: number | firestore.Pipelines.Expr): FunctionExpr { - return new FunctionExpr('subtract', [this, valueToDefaultExpr(other)]); + subtract(subtrahend: number): FunctionExpr; + subtract(subtrahend: number | firestore.Pipelines.Expr): FunctionExpr { + return new FunctionExpr('subtract', [this, valueToDefaultExpr(subtrahend)]); } /** + * @beta * Creates an expression that multiplies this expression by another expression. * * ```typescript @@ -142,6 +150,7 @@ export abstract class Expr implements firestore.Pipelines.Expr, HasUserData { } /** + * @beta * Creates an expression that divides this expression by another expression. * * ```typescript @@ -149,12 +158,13 @@ export abstract class Expr implements firestore.Pipelines.Expr, HasUserData { * field("total").divide(field("count")); * ``` * - * @param other The expression to divide by. + * @param divisor The expression to divide by. * @return A new `Expr` representing the division operation. */ - divide(other: Expr): FunctionExpr; + divide(divisor: Expr): FunctionExpr; /** + * @beta * Creates an expression that divides this expression by a constant value. * * ```typescript @@ -162,15 +172,16 @@ export abstract class Expr implements firestore.Pipelines.Expr, HasUserData { * field("value").divide(10); * ``` * - * @param other The constant value to divide by. + * @param divisor The constant value to divide by. * @return A new `Expr` representing the division operation. */ - divide(other: number): FunctionExpr; - divide(other: number | Expr): FunctionExpr { - return new FunctionExpr('divide', [this, valueToDefaultExpr(other)]); + divide(divisor: number): FunctionExpr; + divide(divisor: number | Expr): FunctionExpr { + return new FunctionExpr('divide', [this, valueToDefaultExpr(divisor)]); } /** + * @beta * Creates an expression that calculates the modulo (remainder) of dividing this expression by another expression. * * ```typescript @@ -184,6 +195,7 @@ export abstract class Expr implements firestore.Pipelines.Expr, HasUserData { mod(expression: Expr): FunctionExpr; /** + * @beta * Creates an expression that calculates the modulo (remainder) of dividing this expression by a constant value. * * ```typescript @@ -200,6 +212,7 @@ export abstract class Expr implements firestore.Pipelines.Expr, HasUserData { } /** + * @beta * Creates an expression that checks if this expression is equal to another expression. * * ```typescript @@ -213,6 +226,7 @@ export abstract class Expr implements firestore.Pipelines.Expr, HasUserData { eq(expression: Expr): BooleanExpr; /** + * @beta * Creates an expression that checks if this expression is equal to a constant value. * * ```typescript @@ -229,6 +243,7 @@ export abstract class Expr implements firestore.Pipelines.Expr, HasUserData { } /** + * @beta * Creates an expression that checks if this expression is not equal to another expression. * * ```typescript @@ -242,6 +257,7 @@ export abstract class Expr implements firestore.Pipelines.Expr, HasUserData { neq(expression: Expr): BooleanExpr; /** + * @beta * Creates an expression that checks if this expression is not equal to a constant value. * * ```typescript @@ -258,6 +274,7 @@ export abstract class Expr implements firestore.Pipelines.Expr, HasUserData { } /** + * @beta * Creates an expression that checks if this expression is less than another expression. * * ```typescript @@ -271,6 +288,7 @@ export abstract class Expr implements firestore.Pipelines.Expr, HasUserData { lt(experession: Expr): BooleanExpr; /** + * @beta * Creates an expression that checks if this expression is less than a constant value. * * ```typescript @@ -287,6 +305,7 @@ export abstract class Expr implements firestore.Pipelines.Expr, HasUserData { } /** + * @beta * Creates an expression that checks if this expression is less than or equal to another * expression. * @@ -301,6 +320,7 @@ export abstract class Expr implements firestore.Pipelines.Expr, HasUserData { lte(expression: Expr): BooleanExpr; /** + * @beta * Creates an expression that checks if this expression is less than or equal to a constant value. * * ```typescript @@ -317,6 +337,7 @@ export abstract class Expr implements firestore.Pipelines.Expr, HasUserData { } /** + * @beta * Creates an expression that checks if this expression is greater than another expression. * * ```typescript @@ -330,6 +351,7 @@ export abstract class Expr implements firestore.Pipelines.Expr, HasUserData { gt(expression: Expr): BooleanExpr; /** + * @beta * Creates an expression that checks if this expression is greater than a constant value. * * ```typescript @@ -346,6 +368,7 @@ export abstract class Expr implements firestore.Pipelines.Expr, HasUserData { } /** + * @beta * Creates an expression that checks if this expression is greater than or equal to another * expression. * @@ -360,6 +383,7 @@ export abstract class Expr implements firestore.Pipelines.Expr, HasUserData { gte(expression: Expr): BooleanExpr; /** + * @beta * Creates an expression that checks if this expression is greater than or equal to a constant * value. * @@ -377,26 +401,7 @@ export abstract class Expr implements firestore.Pipelines.Expr, HasUserData { } /** - * Creates an expression that concatenates an array expression with one or more other arrays. - * - * ```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. - * @return A new `Expr` representing the concatenated array. - */ - arrayConcat( - secondArray: Expr | unknown[], - ...otherArrays: Array - ): FunctionExpr { - const elements = [secondArray, ...otherArrays]; - const exprValues = elements.map(value => valueToDefaultExpr(value)); - return new FunctionExpr('array_concat', [this, ...exprValues]); - } - - /** + * @beta * Creates an expression that checks if an array contains a specific element. * * ```typescript @@ -410,6 +415,7 @@ export abstract class Expr implements firestore.Pipelines.Expr, HasUserData { arrayContains(expression: Expr): BooleanExpr; /** + * @beta * Creates an expression that checks if an array contains a specific value. * * ```typescript @@ -429,6 +435,7 @@ export abstract class Expr implements firestore.Pipelines.Expr, HasUserData { } /** + * @beta * Creates an expression that checks if an array contains all the specified elements. * * ```typescript @@ -442,6 +449,7 @@ export abstract class Expr implements firestore.Pipelines.Expr, HasUserData { arrayContainsAll(values: Array): BooleanExpr; /** + * @beta * Creates an expression that checks if an array contains all the specified elements. * * ```typescript @@ -461,6 +469,7 @@ export abstract class Expr implements firestore.Pipelines.Expr, HasUserData { } /** + * @beta * Creates an expression that checks if an array contains any of the specified elements. * * ```typescript @@ -474,6 +483,7 @@ export abstract class Expr implements firestore.Pipelines.Expr, HasUserData { arrayContainsAny(values: Array): BooleanExpr; /** + * @beta * Creates an expression that checks if an array contains any of the specified elements. * * ```typescript @@ -494,6 +504,22 @@ export abstract class Expr implements firestore.Pipelines.Expr, HasUserData { } /** + * @beta + * Creates an expression that reverses an array. + * + * ```typescript + * // Reverse the value of the 'myArray' field. + * field("myArray").arrayReverse(); + * ``` + * + * @return A new {@code Expr} representing the reversed array. + */ + arrayReverse(): FunctionExpr { + return new FunctionExpr('array_reverse', [this]); + } + + /** + * @beta * Creates an expression that calculates the length of an array. * * ```typescript @@ -508,6 +534,7 @@ export abstract class Expr implements firestore.Pipelines.Expr, HasUserData { } /** + * @beta * Creates an expression that checks if this expression is equal to any of the provided values or * expressions. * @@ -522,6 +549,7 @@ export abstract class Expr implements firestore.Pipelines.Expr, HasUserData { eqAny(values: Array): BooleanExpr; /** + * @beta * Creates an expression that checks if this expression is equal to any of the provided values or * expressions. * @@ -542,6 +570,7 @@ export abstract class Expr implements firestore.Pipelines.Expr, HasUserData { } /** + * @beta * Creates an expression that checks if this expression is not equal to any of the provided values or * expressions. * @@ -556,6 +585,7 @@ export abstract class Expr implements firestore.Pipelines.Expr, HasUserData { notEqAny(values: Array): BooleanExpr; /** + * @beta * Creates an expression that checks if this expression is not equal to any of the values in the evaluated expression. * * ```typescript @@ -575,6 +605,7 @@ export abstract class Expr implements firestore.Pipelines.Expr, HasUserData { } /** + * @beta * Creates an expression that checks if this expression evaluates to 'NaN' (Not a Number). * * ```typescript @@ -589,6 +620,7 @@ export abstract class Expr implements firestore.Pipelines.Expr, HasUserData { } /** + * @beta * Creates an expression that checks if this expression evaluates to 'Null'. * * ```typescript @@ -603,6 +635,7 @@ export abstract class Expr implements firestore.Pipelines.Expr, HasUserData { } /** + * @beta * Creates an expression that checks if a field exists in the document. * * ```typescript @@ -617,6 +650,7 @@ export abstract class Expr implements firestore.Pipelines.Expr, HasUserData { } /** + * @beta * Creates an expression that calculates the character length of a string in UTF-8. * * ```typescript @@ -631,6 +665,7 @@ export abstract class Expr implements firestore.Pipelines.Expr, HasUserData { } /** + * @beta * Creates an expression that performs a case-sensitive string comparison. * * ```typescript @@ -644,6 +679,7 @@ export abstract class Expr implements firestore.Pipelines.Expr, HasUserData { like(pattern: string): FunctionExpr; /** + * @beta * Creates an expression that performs a case-sensitive string comparison. * * ```typescript @@ -660,6 +696,7 @@ export abstract class Expr implements firestore.Pipelines.Expr, HasUserData { } /** + * @beta * Creates an expression that checks if a string contains a specified regular expression as a * substring. * @@ -674,6 +711,7 @@ export abstract class Expr implements firestore.Pipelines.Expr, HasUserData { regexContains(pattern: string): BooleanExpr; /** + * @beta * Creates an expression that checks if a string contains a specified regular expression as a * substring. * @@ -694,6 +732,7 @@ export abstract class Expr implements firestore.Pipelines.Expr, HasUserData { } /** + * @beta * Creates an expression that checks if a string matches a specified regular expression. * * ```typescript @@ -707,6 +746,7 @@ export abstract class Expr implements firestore.Pipelines.Expr, HasUserData { regexMatch(pattern: string): BooleanExpr; /** + * @beta * Creates an expression that checks if a string matches a specified regular expression. * * ```typescript @@ -726,6 +766,7 @@ export abstract class Expr implements firestore.Pipelines.Expr, HasUserData { } /** + * @beta * Creates an expression that checks if a string contains a specified substring. * * ```typescript @@ -739,6 +780,7 @@ export abstract class Expr implements firestore.Pipelines.Expr, HasUserData { strContains(substring: string): BooleanExpr; /** + * @beta * Creates an expression that checks if a string contains the string represented by another expression. * * ```typescript @@ -758,6 +800,7 @@ export abstract class Expr implements firestore.Pipelines.Expr, HasUserData { } /** + * @beta * Creates an expression that checks if a string starts with a given prefix. * * ```typescript @@ -771,6 +814,7 @@ export abstract class Expr implements firestore.Pipelines.Expr, HasUserData { startsWith(prefix: string): BooleanExpr; /** + * @beta * Creates an expression that checks if a string starts with a given prefix (represented as an * expression). * @@ -791,6 +835,7 @@ export abstract class Expr implements firestore.Pipelines.Expr, HasUserData { } /** + * @beta * Creates an expression that checks if a string ends with a given postfix. * * ```typescript @@ -804,6 +849,7 @@ export abstract class Expr implements firestore.Pipelines.Expr, HasUserData { endsWith(suffix: string): BooleanExpr; /** + * @beta * Creates an expression that checks if a string ends with a given postfix (represented as an * expression). * @@ -824,6 +870,7 @@ export abstract class Expr implements firestore.Pipelines.Expr, HasUserData { } /** + * @beta * Creates an expression that converts a string to lowercase. * * ```typescript @@ -838,6 +885,7 @@ export abstract class Expr implements firestore.Pipelines.Expr, HasUserData { } /** + * @beta * Creates an expression that converts a string to uppercase. * * ```typescript @@ -852,6 +900,7 @@ export abstract class Expr implements firestore.Pipelines.Expr, HasUserData { } /** + * @beta * Creates an expression that removes leading and trailing whitespace from a string. * * ```typescript @@ -866,6 +915,7 @@ export abstract class Expr implements firestore.Pipelines.Expr, HasUserData { } /** + * @beta * Creates an expression that concatenates string expressions together. * * ```typescript @@ -887,6 +937,7 @@ export abstract class Expr implements firestore.Pipelines.Expr, HasUserData { } /** + * @beta * Creates an expression that reverses this string expression. * * ```typescript @@ -901,92 +952,67 @@ export abstract class Expr implements firestore.Pipelines.Expr, HasUserData { } /** - * Creates an expression that replaces the first occurrence of a substring within this string expression with another substring. - * - * ```typescript - * // Replace the first occurrence of "hello" with "hi" in the 'message' field - * field("message").replaceFirst("hello", "hi"); - * ``` - * - * @param find The substring to search for. - * @param replace The substring to replace the first occurrence of 'find' with. - * @return A new {@code Expr} representing the string with the first occurrence replaced. - */ - replaceFirst(find: string, replace: string): FunctionExpr; - - /** - * Creates an expression that replaces the first occurrence of a substring within this string expression with another substring, - * where the substring to find and the replacement substring are specified by expressions. + * @beta + * Creates an expression that calculates the length of this string expression in bytes. * * ```typescript - * // Replace the first occurrence of the value in 'findField' with the value in 'replaceField' in the 'message' field - * field("message").replaceFirst(field("findField"), field("replaceField")); + * // Calculate the length of the 'myString' field in bytes. + * field("myString").byteLength(); * ``` * - * @param find The expression representing the substring to search for. - * @param replace The expression representing the substring to replace the first occurrence of 'find' with. - * @return A new {@code Expr} representing the string with the first occurrence replaced. + * @return A new {@code Expr} representing the length of the string in bytes. */ - replaceFirst(find: Expr, replace: Expr): FunctionExpr; - replaceFirst(find: Expr | string, replace: Expr | string): FunctionExpr { - return new FunctionExpr('replace_first', [ - this, - valueToDefaultExpr(find), - valueToDefaultExpr(replace), - ]); + byteLength(): FunctionExpr { + return new FunctionExpr('byte_length', [this]); } /** - * Creates an expression that replaces all occurrences of a substring within this string expression with another substring. + * @beta + * Creates an expression that computes the ceiling of a numeric value. * * ```typescript - * // Replace all occurrences of "hello" with "hi" in the 'message' field - * field("message").replaceAll("hello", "hi"); + * // Compute the ceiling of the 'price' field. + * field("price").ceil(); * ``` * - * @param find The substring to search for. - * @param replace The substring to replace all occurrences of 'find' with. - * @return A new {@code Expr} representing the string with all occurrences replaced. + * @return A new {@code Expr} representing the ceiling of the numeric value. */ - replaceAll(find: string, replace: string): FunctionExpr; + ceil(): FunctionExpr { + return new FunctionExpr('ceil', [this]); + } /** - * Creates an expression that replaces all occurrences of a substring within this string expression with another substring, - * where the substring to find and the replacement substring are specified by expressions. + * @beta + * Creates an expression that computes the floor of a numeric value. * * ```typescript - * // Replace all occurrences of the value in 'findField' with the value in 'replaceField' in the 'message' field - * field("message").replaceAll(field("findField"), field("replaceField")); + * // Compute the floor of the 'price' field. + * field("price").floor(); * ``` * - * @param find The expression representing the substring to search for. - * @param replace The expression representing the substring to replace all occurrences of 'find' with. - * @return A new {@code Expr} representing the string with all occurrences replaced. + * @return A new {@code Expr} representing the floor of the numeric value. */ - replaceAll(find: Expr, replace: Expr): FunctionExpr; - replaceAll(find: Expr | string, replace: Expr | string): FunctionExpr { - return new FunctionExpr('replace_all', [ - this, - valueToDefaultExpr(find), - valueToDefaultExpr(replace), - ]); + floor(): FunctionExpr { + return new FunctionExpr('floor', [this]); } /** - * Creates an expression that calculates the length of this string expression in bytes. + * @beta + * Creates an expression that computes e to the power of this expression. * * ```typescript - * // Calculate the length of the 'myString' field in bytes. - * field("myString").byteLength(); + * // Compute e to the power of the 'value' field. + * field("value").exp(); * ``` * - * @return A new {@code Expr} representing the length of the string in bytes. + * @return A new {@code Expr} representing the exp of the numeric value. */ - byteLength(): FunctionExpr { - return new FunctionExpr('byte_length', [this]); + exp(): FunctionExpr { + return new FunctionExpr('exp', [this]); } /** + * @beta * Accesses a value from a map (object) field using the provided key. * * ```typescript @@ -1002,6 +1028,7 @@ export abstract class Expr implements firestore.Pipelines.Expr, HasUserData { } /** + * @beta * Creates an aggregation that counts the number of stage inputs with valid evaluations of the * expression or field. * @@ -1017,6 +1044,7 @@ export abstract class Expr implements firestore.Pipelines.Expr, HasUserData { } /** + * @beta * Creates an aggregation that calculates the sum of a numeric field across multiple stage inputs. * * ```typescript @@ -1031,6 +1059,7 @@ export abstract class Expr implements firestore.Pipelines.Expr, HasUserData { } /** + * @beta * Creates an aggregation that calculates the average (mean) of a numeric field across multiple * stage inputs. * @@ -1046,6 +1075,7 @@ export abstract class Expr implements firestore.Pipelines.Expr, HasUserData { } /** + * @beta * Creates an aggregation that finds the minimum value of a field across multiple stage inputs. * * ```typescript @@ -1056,10 +1086,11 @@ export abstract class Expr implements firestore.Pipelines.Expr, HasUserData { * @return A new `AggregateFunction` representing the 'min' aggregation. */ minimum(): AggregateFunction { - return new AggregateFunction('minimum', [this]); + return new AggregateFunction('min', [this]); } /** + * @beta * Creates an aggregation that finds the maximum value of a field across multiple stage inputs. * * ```typescript @@ -1070,10 +1101,26 @@ export abstract class Expr implements firestore.Pipelines.Expr, HasUserData { * @return A new `AggregateFunction` representing the 'max' aggregation. */ maximum(): AggregateFunction { - return new AggregateFunction('maximum', [this]); + return new AggregateFunction('max', [this]); + } + + /** + * @beta + * Creates an aggregation that counts the number of distinct values of the expression or field. + * + * ```typescript + * // Count the distinct number of products + * field("productId").countDistinct().as("distinctProducts"); + * ``` + * + * @return A new `AggregateFunction` representing the 'count_distinct' aggregation. + */ + countDistinct(): AggregateFunction { + return new AggregateFunction('count_distinct', [this]); } /** + * @beta * Creates an expression that returns the larger value between this expression and another expression, based on Firestore's value type ordering. * * ```typescript @@ -1090,13 +1137,11 @@ export abstract class Expr implements firestore.Pipelines.Expr, HasUserData { ...others: Array ): FunctionExpr { const values = [second, ...others]; - return new FunctionExpr('logical_maximum', [ - this, - ...values.map(valueToDefaultExpr), - ]); + return new FunctionExpr('max', [this, ...values.map(valueToDefaultExpr)]); } /** + * @beta * Creates an expression that returns the smaller value between this expression and another expression, based on Firestore's value type ordering. * * ```typescript @@ -1113,13 +1158,11 @@ export abstract class Expr implements firestore.Pipelines.Expr, HasUserData { ...others: Array ): FunctionExpr { const values = [second, ...others]; - return new FunctionExpr('logical_minimum', [ - this, - ...values.map(valueToDefaultExpr), - ]); + return new FunctionExpr('min', [this, ...values.map(valueToDefaultExpr)]); } /** + * @beta * Creates an expression that calculates the length (number of dimensions) of this Firestore Vector expression. * * ```typescript @@ -1134,6 +1177,7 @@ export abstract class Expr implements firestore.Pipelines.Expr, HasUserData { } /** + * @beta * Calculates the cosine distance between two vectors. * * ```typescript @@ -1146,6 +1190,7 @@ export abstract class Expr implements firestore.Pipelines.Expr, HasUserData { */ cosineDistance(vectorExpression: Expr): FunctionExpr; /** + * @beta * Calculates the Cosine distance between two vectors. * * ```typescript @@ -1162,6 +1207,7 @@ export abstract class Expr implements firestore.Pipelines.Expr, HasUserData { } /** + * @beta * Calculates the dot product between two vectors. * * ```typescript @@ -1175,6 +1221,7 @@ export abstract class Expr implements firestore.Pipelines.Expr, HasUserData { dotProduct(vectorExpression: Expr): FunctionExpr; /** + * @beta * Calculates the dot product between two vectors. * * ```typescript @@ -1191,6 +1238,7 @@ export abstract class Expr implements firestore.Pipelines.Expr, HasUserData { } /** + * @beta * Calculates the Euclidean distance between two vectors. * * ```typescript @@ -1204,6 +1252,7 @@ export abstract class Expr implements firestore.Pipelines.Expr, HasUserData { euclideanDistance(vectorExpression: Expr): FunctionExpr; /** + * @beta * Calculates the Euclidean distance between two vectors. * * ```typescript @@ -1222,6 +1271,7 @@ export abstract class Expr implements firestore.Pipelines.Expr, HasUserData { } /** + * @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. * @@ -1237,6 +1287,7 @@ export abstract class Expr implements firestore.Pipelines.Expr, HasUserData { } /** + * @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). * * ```typescript @@ -1251,6 +1302,7 @@ export abstract class Expr implements firestore.Pipelines.Expr, HasUserData { } /** + * @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. * @@ -1266,6 +1318,7 @@ export abstract class Expr implements firestore.Pipelines.Expr, HasUserData { } /** + * @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). * * ```typescript @@ -1280,6 +1333,7 @@ export abstract class Expr implements firestore.Pipelines.Expr, HasUserData { } /** + * @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. * @@ -1295,6 +1349,7 @@ export abstract class Expr implements firestore.Pipelines.Expr, HasUserData { } /** + * @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). * * ```typescript @@ -1309,6 +1364,7 @@ export abstract class Expr implements firestore.Pipelines.Expr, HasUserData { } /** + * @beta * Creates an expression that adds a specified amount of time to this timestamp expression. * * ```typescript @@ -1323,6 +1379,7 @@ export abstract class Expr implements firestore.Pipelines.Expr, HasUserData { timestampAdd(unit: Expr, amount: Expr): FunctionExpr; /** + * @beta * Creates an expression that adds a specified amount of time to this timestamp expression. * * ```typescript @@ -1357,6 +1414,7 @@ export abstract class Expr implements firestore.Pipelines.Expr, HasUserData { } /** + * @beta * Creates an expression that subtracts a specified amount of time from this timestamp expression. * * ```typescript @@ -1371,6 +1429,7 @@ export abstract class Expr implements firestore.Pipelines.Expr, HasUserData { timestampSub(unit: Expr, amount: Expr): FunctionExpr; /** + * @beta * Creates an expression that subtracts a specified amount of time from this timestamp expression. * * ```typescript @@ -1405,175 +1464,7 @@ export abstract class Expr implements firestore.Pipelines.Expr, HasUserData { } /** - * Creates an expression that applies a bitwise AND operation between this expression and a constant. - * - * ```typescript - * // Calculate the bitwise AND of 'field1' and 0xFF. - * field("field1").bitAnd(0xFF); - * ``` - * - * @param otherBits A constant representing bits. - * @return A new {@code Expr} representing the bitwise AND operation. - */ - bitAnd(otherBits: number | Buffer | Uint8Array): FunctionExpr; - /** - * Creates an expression that applies a bitwise AND operation between two expressions. - * - * ```typescript - * // Calculate the bitwise AND of 'field1' and 'field2'. - * field("field1").bitAnd(field("field2")); - * ``` - * - * @param bitsExpression An expression that returns bits when evaluated. - * @return A new {@code Expr} representing the bitwise AND operation. - */ - bitAnd(bitsExpression: Expr): FunctionExpr; - bitAnd(bitsOrExpression: number | Expr | Buffer | Uint8Array): FunctionExpr { - return new FunctionExpr('bit_and', [ - this, - valueToDefaultExpr(bitsOrExpression), - ]); - } - - /** - * Creates an expression that applies a bitwise OR operation between this expression and a constant. - * - * ```typescript - * // Calculate the bitwise OR of 'field1' and 0xFF. - * field("field1").bitOr(0xFF); - * ``` - * - * @param otherBits A constant representing bits. - * @return A new {@code Expr} representing the bitwise OR operation. - */ - bitOr(otherBits: number | Buffer | Uint8Array): FunctionExpr; - /** - * Creates an expression that applies a bitwise OR operation between two expressions. - * - * ```typescript - * // Calculate the bitwise OR of 'field1' and 'field2'. - * field("field1").bitOr(field("field2")); - * ``` - * - * @param bitsExpression An expression that returns bits when evaluated. - * @return A new {@code Expr} representing the bitwise OR operation. - */ - bitOr(bitsExpression: Expr): FunctionExpr; - bitOr(bitsOrExpression: number | Expr | Buffer | Uint8Array): FunctionExpr { - return new FunctionExpr('bit_or', [ - this, - valueToDefaultExpr(bitsOrExpression), - ]); - } - - /** - * Creates an expression that applies a bitwise XOR operation between this expression and a constant. - * - * ```typescript - * // Calculate the bitwise XOR of 'field1' and 0xFF. - * field("field1").bitXor(0xFF); - * ``` - * - * @param otherBits A constant representing bits. - * @return A new {@code Expr} representing the bitwise XOR operation. - */ - bitXor(otherBits: number | Buffer | Uint8Array): FunctionExpr; - /** - * Creates an expression that applies a bitwise XOR operation between two expressions. - * - * ```typescript - * // Calculate the bitwise XOR of 'field1' and 'field2'. - * field("field1").bitXor(field("field2")); - * ``` - * - * @param bitsExpression An expression that returns bits when evaluated. - * @return A new {@code Expr} representing the bitwise XOR operation. - */ - bitXor(bitsExpression: Expr): FunctionExpr; - bitXor(bitsOrExpression: number | Expr | Buffer | Uint8Array): FunctionExpr { - return new FunctionExpr('bit_xor', [ - this, - valueToDefaultExpr(bitsOrExpression), - ]); - } - - /** - * Creates an expression that applies a bitwise NOT operation to this expression. - * - * ```typescript - * // Calculate the bitwise NOT of 'field1'. - * field("field1").bitNot(); - * ``` - * - * @return A new {@code Expr} representing the bitwise NOT operation. - */ - bitNot(): FunctionExpr { - return new FunctionExpr('bit_not', [this]); - } - - /** - * Creates an expression that applies a bitwise left shift operation to this expression. - * - * ```typescript - * // Calculate the bitwise left shift of 'field1' by 2 bits. - * field("field1").bitLeftShift(2); - * ``` - * - * @param y The operand constant representing the number of bits to shift. - * @return A new {@code Expr} representing the bitwise left shift operation. - */ - bitLeftShift(y: number): FunctionExpr; - /** - * Creates an expression that applies a bitwise left shift operation to this expression. - * - * ```typescript - * // Calculate the bitwise left shift of 'field1' by 'field2' bits. - * field("field1").bitLeftShift(field("field2")); - * ``` - * - * @param numberExpr The operand expression representing the number of bits to shift. - * @return A new {@code Expr} representing the bitwise left shift operation. - */ - bitLeftShift(numberExpr: Expr): FunctionExpr; - bitLeftShift(numberExpr: number | Expr): FunctionExpr { - return new FunctionExpr('bit_left_shift', [ - this, - valueToDefaultExpr(numberExpr), - ]); - } - - /** - * Creates an expression that applies a bitwise right shift operation to this expression. - * - * ```typescript - * // Calculate the bitwise right shift of 'field1' by 2 bits. - * field("field1").bitRightShift(2); - * ``` - * - * @param right The operand constant representing the number of bits to shift. - * @return A new {@code Expr} representing the bitwise right shift operation. - */ - bitRightShift(y: number): FunctionExpr; - /** - * Creates an expression that applies a bitwise right shift operation to this expression. - * - * ```typescript - * // Calculate the bitwise right shift of 'field1' by 'field2' bits. - * field("field1").bitRightShift(field("field2")); - * ``` - * - * @param numberExpr The operand expression representing the number of bits to shift. - * @return A new {@code Expr} representing the bitwise right shift operation. - */ - bitRightShift(numberExpr: Expr): FunctionExpr; - bitRightShift(numberExpr: number | Expr): FunctionExpr { - return new FunctionExpr('bit_right_shift', [ - this, - valueToDefaultExpr(numberExpr), - ]); - } - - /** + * @beta * Creates an expression that returns the document ID from a path. * * ```typescript @@ -1588,23 +1479,25 @@ export abstract class Expr implements firestore.Pipelines.Expr, HasUserData { } /** + * @beta * Creates an expression that returns a substring of the results of this expression. * * @param position Index of the first character of the substring. * @param length Length of the substring. If not provided, the substring will * end at the end of the input. */ - substr(position: number, length?: number): FunctionExpr; + substring(position: number, length?: number): FunctionExpr; /** + * @beta * Creates an expression that returns a substring of the results of this expression. * * @param position An expression returning the index of the first character of the substring. * @param length An expression returning the length of the substring. If not provided the * substring will end at the end of the input. */ - substr(position: Expr, length?: Expr): FunctionExpr; - substr(position: Expr | number, length?: Expr | number): FunctionExpr { + substring(position: Expr, length?: Expr): FunctionExpr; + substring(position: Expr | number, length?: Expr | number): FunctionExpr { const positionExpr = valueToDefaultExpr(position); if (length === undefined) { return new FunctionExpr('substr', [this, positionExpr]); @@ -1618,40 +1511,43 @@ export abstract class Expr implements firestore.Pipelines.Expr, HasUserData { } /** + * @beta * Creates an expression that indexes into an array from the beginning or end - * and returns the element. If the offset exceeds the array length, an error is - * returned. A negative offset, starts from the end. + * and returns the element. If the index exceeds the array length, an error is + * returned. A negative index, starts from the end. * * ```typescript * // Return the value in the 'tags' field array at index `1`. - * field('tags').arrayOffset(1); + * field('tags').arrayGet(1); * ``` * - * @param offset The index of the element to return. - * @return A new Expr representing the 'arrayOffset' operation. + * @param index The index of the element to return. + * @return A new Expr representing the 'arrayGet' operation. */ - arrayOffset(offset: number): FunctionExpr; + arrayGet(index: number): FunctionExpr; /** + * @beta * Creates an expression that indexes into an array from the beginning or end - * and returns the element. If the offset exceeds the array length, an error is - * returned. A negative offset, starts from the end. + * and returns the element. If the index exceeds the array length, an error is + * returned. A negative index, starts from the end. * * ```typescript * // Return the value in the tags field array at index specified by field * // 'favoriteTag'. - * field('tags').arrayOffset(field('favoriteTag')); + * field('tags').arrayGet(field('favoriteTag')); * ``` * - * @param offsetExpr An Expr evaluating to the index of the element to return. - * @return A new Expr representing the 'arrayOffset' operation. + * @param indexExpr An Expr evaluating to the index of the element to return. + * @return A new Expr representing the 'arrayGet' operation. */ - arrayOffset(offsetExpr: Expr): FunctionExpr; - arrayOffset(offset: Expr | number): FunctionExpr { - return new FunctionExpr('array_offset', [this, valueToDefaultExpr(offset)]); + arrayGet(indexExpr: Expr): FunctionExpr; + arrayGet(index: Expr | number): FunctionExpr { + return new FunctionExpr('array_get', [this, valueToDefaultExpr(index)]); } /** + * @beta * Creates an expression that checks if a given expression produces an error. * * ```typescript @@ -1666,13 +1562,14 @@ export abstract class Expr implements firestore.Pipelines.Expr, HasUserData { } /** + * @beta * Creates an expression that returns the result of the `catchExpr` argument * if there is an error, else return the result of this expression. * * ```typescript * // Returns the first item in the title field arrays, or returns * // the entire title field if the array is empty or the field is another type. - * field("title").arrayOffset(0).ifError(field("title")); + * field("title").arrayGet(0).ifError(field("title")); * ``` * * @param catchExpr The catch expression that will be evaluated and @@ -1682,13 +1579,14 @@ export abstract class Expr implements firestore.Pipelines.Expr, HasUserData { ifError(catchExpr: Expr): FunctionExpr; /** + * @beta * Creates an expression that returns the `catch` argument if there is an * error, else return the result of this expression. * * ```typescript * // Returns the first item in the title field arrays, or returns * // "Default Title" - * field("title").arrayOffset(0).ifError("Default Title"); + * field("title").arrayGet(0).ifError("Default Title"); * ``` * * @param catchValue The value that will be returned if this expression @@ -1701,6 +1599,7 @@ export abstract class Expr implements firestore.Pipelines.Expr, HasUserData { } /** + * @beta * Creates an expression that returns `true` if the result of this expression * is absent. Otherwise, returns `false` even if the value is `null`. * @@ -1716,6 +1615,7 @@ export abstract class Expr implements firestore.Pipelines.Expr, HasUserData { } /** + * @beta * Creates an expression that checks if tbe result of an expression is not null. * * ```typescript @@ -1730,6 +1630,7 @@ export abstract class Expr implements firestore.Pipelines.Expr, HasUserData { } /** + * @beta * Creates an expression that checks if the results of this expression is NOT 'NaN' (Not a Number). * * ```typescript @@ -1744,6 +1645,7 @@ export abstract class Expr implements firestore.Pipelines.Expr, HasUserData { } /** + * @beta * Creates an expression that removes a key from the map produced by evaluating this expression. * * ``` @@ -1756,6 +1658,7 @@ export abstract class Expr implements firestore.Pipelines.Expr, HasUserData { */ mapRemove(key: string): FunctionExpr; /** + * @beta * Creates an expression that removes a key from the map produced by evaluating this expression. * * ``` @@ -1775,6 +1678,7 @@ export abstract class Expr implements firestore.Pipelines.Expr, HasUserData { } /** + * @beta * Creates an expression that merges multiple map values. * * ``` @@ -1804,6 +1708,164 @@ export abstract class Expr implements firestore.Pipelines.Expr, HasUserData { } /** + * @beta + * Creates an expression that returns the value of this expression raised to the power of another expression. + * + * ```typescript + * // Raise the value of the 'base' field to the power of the 'exponent' field. + * field("base").pow(field("exponent")); + * ``` + * + * @param exponent The expression to raise this expression to the power of. + * @return A new `Expr` representing the power operation. + */ + pow(exponent: Expr): FunctionExpr; + + /** + * @beta + * Creates an expression that returns the value of this expression raised to the power of a constant value. + * + * ```typescript + * // Raise the value of the 'base' field to the power of 2. + * field("base").pow(2); + * ``` + * + * @param exponent The constant value to raise this expression to the power of. + * @return A new `Expr` representing the power operation. + */ + pow(exponent: number): FunctionExpr; + pow(exponent: number | Expr): FunctionExpr { + return new FunctionExpr('pow', [this, valueToDefaultExpr(exponent)]); + } + + /** + * @beta + * Creates an expression that rounds a numeric value to the nearest whole number. + * + * ```typescript + * // Round the value of the 'price' field. + * field("price").round(); + * ``` + * + * @return A new `Expr` representing the rounded value. + */ + round(): FunctionExpr { + return new FunctionExpr('round', [this]); + } + + /** + * @beta + * Creates an expression that returns the collection ID from a path. + * + * ```typescript + * // Get the collection ID from a path. + * field("__path__").collectionId(); + * ``` + * + * @return A new {@code Expr} representing the collectionId operation. + */ + collectionId(): FunctionExpr { + return new FunctionExpr('collection_id', [this]); + } + + /** + * @beta + * Creates an expression that calculates the length of a string, array, map, vector, or bytes. + * + * ```typescript + * // Get the length of the 'name' field. + * field("name").length(); + * + * // Get the number of items in the 'cart' array. + * field("cart").length(); + * ``` + * + * @return A new `Expr` representing the length of the string, array, map, vector, or bytes. + */ + length(): FunctionExpr { + return new FunctionExpr('length', [this]); + } + + /** + * @beta + * Creates an expression that computes the natural logarithm of a numeric value. + * + * ```typescript + * // Compute the natural logarithm of the 'value' field. + * field("value").ln(); + * ``` + * + * @return A new {@code Expr} representing the natural logarithm of the numeric value. + */ + ln(): FunctionExpr { + return new FunctionExpr('ln', [this]); + } + + /** + * @beta + * Creates an expression that computes the logarithm of this expression to a given base. + * + * ```typescript + * // Compute the logarithm of the 'value' field with base 10. + * field("value").log(10); + * ``` + * + * @param base The base of the logarithm. + * @return A new {@code Expr} representing the logarithm of the numeric value. + */ + log(base: number): FunctionExpr; + + /** + * @beta + * Creates an expression that computes the logarithm of this expression to a given base. + * + * ```typescript + * // Compute the logarithm of the 'value' field with the base in the 'base' field. + * field("value").log(field("base")); + * ``` + * + * @param base The base of the logarithm. + * @return A new {@code Expr} representing the logarithm of the numeric value. + */ + log(base: Expr): FunctionExpr; + log(base: number | Expr): FunctionExpr { + return new FunctionExpr('log', [this, valueToDefaultExpr(base)]); + } + + /** + * @beta + * Creates an expression that computes the square root of a numeric value. + * + * ```typescript + * // Compute the square root of the 'value' field. + * field("value").sqrt(); + * ``` + * + * @return A new {@code Expr} representing the square root of the numeric value. + */ + sqrt(): FunctionExpr { + return new FunctionExpr('sqrt', [this]); + } + + /** + * @beta + * Creates an expression that reverses a string. + * + * ```typescript + * // Reverse the value of the 'myString' field. + * field("myString").strReverse(); + * ``` + * + * @return A new {@code Expr} representing the reversed string. + */ + strReverse(): FunctionExpr { + return new FunctionExpr('str_reverse', [this]); + } + + // TODO(new-expression): Add new expression method definitions above this line + + /** + * @beta * Creates an {@link Ordering} that sorts documents in ascending order based on this expression. * * ```typescript @@ -1819,6 +1881,7 @@ export abstract class Expr implements firestore.Pipelines.Expr, HasUserData { } /** + * @beta * Creates an {@link Ordering} that sorts documents in descending order based on this expression. * * ```typescript @@ -1834,6 +1897,7 @@ export abstract class Expr implements firestore.Pipelines.Expr, HasUserData { } /** + * @beta * Assigns an alias to this expression. * * Aliases are useful for renaming fields in the output of a stage or for giving meaningful @@ -1846,21 +1910,23 @@ export abstract class Expr implements firestore.Pipelines.Expr, HasUserData { * ``` * * @param name The alias to assign to this expression. - * @return A new {@link ExprWithAlias} that wraps this + * @return A new {@link AliasedExpr} that wraps this * expression and associates it with the provided alias. */ - as(name: string): ExprWithAlias { - return new ExprWithAlias(this, name); + as(name: string): AliasedExpr { + return new AliasedExpr(this, name); } } /** + * @beta * A class that represents an aggregate function. */ export class AggregateFunction implements AggregateFunction, HasUserData { exprType: firestore.Pipelines.ExprType = 'AggregateFunction'; /** + * @beta * @internal * @private * Indicates if this expression was created from a literal value passed @@ -1869,6 +1935,7 @@ export class AggregateFunction implements AggregateFunction, HasUserData { _createdFromLiteral = false; /** + * @beta * @private * @internal */ @@ -1884,6 +1951,7 @@ export class AggregateFunction implements AggregateFunction, HasUserData { ) {} /** + * @beta * Assigns an alias to this AggregateFunction. The alias specifies the name that * the aggregated value will have in the output document. * @@ -1894,14 +1962,15 @@ export class AggregateFunction implements AggregateFunction, HasUserData { * ``` * * @param name The alias to assign to this AggregateFunction. - * @return A new {@link AggregateWithAlias} that wraps this + * @return A new {@link AliasedAggregate} that wraps this * AggregateFunction and associates it with the provided alias. */ - as(name: string): AggregateWithAlias { - return new AggregateWithAlias(this, name); + as(name: string): AliasedAggregate { + return new AliasedAggregate(this, name); } /** + * @beta * @private * @internal */ @@ -1918,15 +1987,17 @@ export class AggregateFunction implements AggregateFunction, HasUserData { } /** + * @beta * An AggregateFunction with alias. */ -export class AggregateWithAlias implements AggregateWithAlias, HasUserData { +export class AliasedAggregate implements AliasedAggregate, HasUserData { constructor( readonly aggregate: AggregateFunction, readonly alias: string ) {} /** + * @beta * @internal * @private * Indicates if this expression was created from a literal value passed @@ -1935,6 +2006,7 @@ export class AggregateWithAlias implements AggregateWithAlias, HasUserData { _createdFromLiteral = false; /** + * @beta * @private * @internal */ @@ -1944,15 +2016,17 @@ export class AggregateWithAlias implements AggregateWithAlias, HasUserData { } /** + * @beta * TODO */ -export class ExprWithAlias +export class AliasedExpr implements firestore.Pipelines.Selectable, HasUserData { - exprType: firestore.Pipelines.ExprType = 'ExprWithAlias'; + exprType: firestore.Pipelines.ExprType = 'AliasedExpr'; selectable = true as const; /** + * @beta * @internal * @private * Indicates if this expression was created from a literal value passed @@ -1966,6 +2040,7 @@ export class ExprWithAlias ) {} /** + * @beta * @private * @internal */ @@ -1975,6 +2050,7 @@ export class ExprWithAlias } /** + * @beta * @internal */ class ListOfExprs extends Expr { @@ -1985,6 +2061,7 @@ class ListOfExprs extends Expr { } /** + * @beta * @private * @internal */ @@ -1997,6 +2074,7 @@ class ListOfExprs extends Expr { } /** + * @beta * @private * @internal */ @@ -2008,6 +2086,7 @@ class ListOfExprs extends Expr { } /** + * @beta * Represents a reference to a field in a Firestore document, or outputs of a {@link Pipeline} stage. * *

Field references are used to access document field values in expressions and to specify fields @@ -2028,6 +2107,7 @@ export class Field extends Expr implements firestore.Pipelines.Selectable { selectable = true as const; /** + * @beta * @internal * @private * @hideconstructor @@ -2050,6 +2130,7 @@ export class Field extends Expr implements firestore.Pipelines.Selectable { } /** + * @beta * @private * @internal */ @@ -2060,6 +2141,7 @@ export class Field extends Expr implements firestore.Pipelines.Selectable { } /** + * @beta * @private * @internal */ @@ -2067,6 +2149,7 @@ export class Field extends Expr implements firestore.Pipelines.Selectable { } /** + * @beta * Creates a {@code Field} instance representing the field at the given path. * * The path can be a simple field name (e.g., "name") or a dot-separated path to a nested field @@ -2095,6 +2178,7 @@ export function field(field: string | firestore.FieldPath): Field { } /** + * @beta * Represents a constant value that can be used in a Firestore pipeline expression. * * You can create a `Constant` instance using the static {@link #of} method: @@ -2113,6 +2197,7 @@ export class Constant extends Expr { private protoValue?: api.IValue; /** + * @beta * @private * @internal * @hideconstructor @@ -2123,6 +2208,7 @@ export class Constant extends Expr { } /** + * @beta * @private * @internal */ @@ -2133,6 +2219,7 @@ export class Constant extends Expr { } /** + * @beta * @private * @internal */ @@ -2145,6 +2232,7 @@ export class Constant extends Expr { } /** + * @beta * @private * @internal */ @@ -2158,6 +2246,7 @@ export class Constant extends Expr { } /** + * @beta * Creates a `Constant` instance for a number value. * * @param value The number value. @@ -2166,6 +2255,7 @@ export class Constant extends Expr { export function constant(value: number): Constant; /** + * @beta * Creates a `Constant` instance for a string value. * * @param value The string value. @@ -2174,6 +2264,7 @@ export function constant(value: number): Constant; export function constant(value: string): Constant; /** + * @beta * Creates a `Constant` instance for a boolean value. * * @param value The boolean value. @@ -2182,6 +2273,7 @@ export function constant(value: string): Constant; export function constant(value: boolean): Constant; /** + * @beta * Creates a `Constant` instance for a null value. * * @param value The null value. @@ -2190,6 +2282,7 @@ export function constant(value: boolean): Constant; export function constant(value: null): Constant; /** + * @beta * Creates a `Constant` instance for a GeoPoint value. * * @param value The GeoPoint value. @@ -2198,6 +2291,7 @@ export function constant(value: null): Constant; export function constant(value: firestore.GeoPoint): Constant; /** + * @beta * Creates a `Constant` instance for a Timestamp value. * * @param value The Timestamp value. @@ -2206,6 +2300,7 @@ export function constant(value: firestore.GeoPoint): Constant; export function constant(value: firestore.Timestamp): Constant; /** + * @beta * Creates a `Constant` instance for a Date value. * * @param value The Date value. @@ -2214,6 +2309,7 @@ export function constant(value: firestore.Timestamp): Constant; export function constant(value: Date): Constant; /** + * @beta * Creates a `Constant` instance for a Buffer | Uint8Array value. * * @param value The Buffer | Uint8Array value. @@ -2222,6 +2318,7 @@ export function constant(value: Date): Constant; export function constant(value: Buffer | Uint8Array): Constant; /** + * @beta * Creates a `Constant` instance for a DocumentReference value. * * @param value The DocumentReference value. @@ -2230,6 +2327,7 @@ export function constant(value: Buffer | Uint8Array): Constant; export function constant(value: firestore.DocumentReference): Constant; /** + * @beta * Creates a `Constant` instance for a Firestore proto value. * For internal use only. * @private @@ -2240,6 +2338,7 @@ export function constant(value: firestore.DocumentReference): Constant; export function constant(value: api.IValue): Constant; /** + * @beta * Creates a `Constant` instance for a VectorValue value. * * @param value The VectorValue value. @@ -2248,6 +2347,7 @@ export function constant(value: api.IValue): Constant; export function constant(value: firestore.VectorValue): Constant; /** + * @beta * @internal * @private * @param value @@ -2259,27 +2359,7 @@ export function constant(value: unknown): Constant { } /** - * Creates a `Constant` instance for a VectorValue value. - * - * ```typescript - * // Create a Constant instance for a vector value - * const vectorConstant = constantVector([1, 2, 3]); - * ``` - * - * @param value The VectorValue value. - * @return A new `Constant` instance. - */ -export function constantVector( - value: number[] | firestore.VectorValue -): Constant { - if (Array.isArray(value)) { - return constant(new VectorValue(value as number[])); - } else { - return constant(value); - } -} - -/** + * @beta * Internal only * @internal * @private @@ -2296,6 +2376,7 @@ export class MapValue extends Expr { } /** + * @beta * @private * @internal */ @@ -2307,6 +2388,7 @@ export class MapValue extends Expr { } /** + * @beta * This class defines the base class for Firestore {@link Pipeline} functions, which can be evaluated within pipeline * execution. * @@ -2324,6 +2406,7 @@ export class FunctionExpr extends Expr { } /** + * @beta * @private * @internal */ @@ -2337,6 +2420,7 @@ export class FunctionExpr extends Expr { } /** + * @beta * @private * @internal */ @@ -2348,6 +2432,7 @@ export class FunctionExpr extends Expr { } /** + * @beta * This class defines the base class for Firestore {@link Pipeline} functions, which can be evaluated within pipeline * execution. * @@ -2362,6 +2447,7 @@ class MapFunctionExpr extends FunctionExpr { } /** + * @beta * @private * @internal */ @@ -2371,7 +2457,7 @@ class MapFunctionExpr extends FunctionExpr { if (Object.prototype.hasOwnProperty.call(this.map, key)) { if (this.map[key]) { args.push(constant(key)._toProto(serializer)); - args.push(this.map[key]._toProto(serializer)); + args.push(this.map[key]!._toProto(serializer)); } } } @@ -2384,6 +2470,7 @@ class MapFunctionExpr extends FunctionExpr { } /** + * @beta * @private * @internal */ @@ -2397,6 +2484,7 @@ class MapFunctionExpr extends FunctionExpr { } /** + * @beta * This class defines the base class for Firestore {@link Pipeline} functions, which can be evaluated within pipeline * execution. * @@ -2411,6 +2499,7 @@ class ArrayFunctionExpr extends FunctionExpr { } /** + * @beta * @private * @internal */ @@ -2420,12 +2509,13 @@ class ArrayFunctionExpr extends FunctionExpr { name: this.name, args: this.values .filter(v => !!v) - .map(value => value._toProto(serializer)), + .map(value => value!._toProto(serializer)), }, }; } /** + * @beta * @private * @internal */ @@ -2439,12 +2529,20 @@ class ArrayFunctionExpr extends FunctionExpr { } /** - * An interface that represents a filter condition. + * @beta + * An expression that evaluates to a boolean value. + * + * This expression type is useful for filter conditions. + * */ -export class BooleanExpr extends FunctionExpr implements BooleanExpr { - filterable: true = true as const; +export class BooleanExpr + extends FunctionExpr + implements firestore.Pipelines.BooleanExpr +{ + returnType: 'boolean' = 'boolean' as const; /** + * @beta * Creates an aggregation that finds the count of input documents satisfying * this boolean expression. * @@ -2460,6 +2558,7 @@ export class BooleanExpr extends FunctionExpr implements BooleanExpr { } /** + * @beta * Creates an expression that negates this boolean expression. * * ```typescript @@ -2475,6 +2574,7 @@ export class BooleanExpr extends FunctionExpr implements BooleanExpr { } /** + * @beta * Creates an aggregation that counts the number of stage inputs where the provided * boolean expression evaluates to true. * @@ -2491,6 +2591,7 @@ export function countIf(booleanExpr: BooleanExpr): AggregateFunction { } /** + * @beta * Creates an expression that return a pseudo-random value of type double in the * range of [0, 1), inclusive of 0 and exclusive of 1. * @@ -2501,436 +2602,83 @@ export function rand(): FunctionExpr { } /** - * Creates an expression that applies a bitwise AND operation between a field and a constant. - * - * ```typescript - * // Calculate the bitwise AND of 'field1' and 0xFF. - * bitAnd("field1", 0xFF); - * ``` - * - * @param field The left operand field name. - * @param otherBits A constant representing bits. - * @return A new {@code Expr} representing the bitwise AND operation. - */ -export function bitAnd( - field: string, - otherBits: number | Buffer | Uint8Array -): FunctionExpr; -/** - * Creates an expression that applies a bitwise AND operation between a field and an expression. - * - * ```typescript - * // Calculate the bitwise AND of 'field1' and 'field2'. - * bitAnd("field1", field("field2")); - * ``` - * - * @param field The left operand field name. - * @param bitsExpression An expression that returns bits when evaluated. - * @return A new {@code Expr} representing the bitwise AND operation. - */ -export function bitAnd(field: string, bitsExpression: Expr): FunctionExpr; -/** - * Creates an expression that applies a bitwise AND operation between an expression and a constant. - * - * ```typescript - * // Calculate the bitwise AND of 'field1' and 0xFF. - * bitAnd(field("field1"), 0xFF); - * ``` - * - * @param bitsExpression An expression returning bits. - * @param otherBits A constant representing bits. - * @return A new {@code Expr} representing the bitwise AND operation. - */ -export function bitAnd( - bitsExpression: Expr, - otherBits: number | Buffer | Uint8Array -): FunctionExpr; -/** - * Creates an expression that applies a bitwise AND operation between two expressions. - * - * ```typescript - * // Calculate the bitwise AND of 'field1' and 'field2'. - * bitAnd(field("field1"), field("field2")); - * ``` - * - * @param bitsExpression An expression that returns bits when evaluated. - * @param otherBitsExpression An expression that returns bits when evaluated. - * @return A new {@code Expr} representing the bitwise AND operation. - */ -export function bitAnd( - bitsExpression: Expr, - otherBitsExpression: Expr -): FunctionExpr; -export function bitAnd( - bits: string | Expr, - bitsOrExpression: number | Expr | Buffer | Uint8Array -): FunctionExpr { - return fieldOrExpression(bits).bitAnd(valueToDefaultExpr(bitsOrExpression)); -} - -/** - * Creates an expression that applies a bitwise OR operation between a field and a constant. - * - * ```typescript - * // Calculate the bitwise OR of 'field1' and 0xFF. - * bitOr("field1", 0xFF); - * ``` - * - * @param field The left operand field name. - * @param otherBits A constant representing bits. - * @return A new {@code Expr} representing the bitwise OR operation. - */ -export function bitOr( - field: string, - otherBits: number | Buffer | Uint8Array -): FunctionExpr; -/** - * Creates an expression that applies a bitwise OR operation between a field and an expression. - * - * ```typescript - * // Calculate the bitwise OR of 'field1' and 'field2'. - * bitOr("field1", field("field2")); - * ``` - * - * @param field The left operand field name. - * @param bitsExpression An expression that returns bits when evaluated. - * @return A new {@code Expr} representing the bitwise OR operation. - */ -export function bitOr(field: string, bitsExpression: Expr): FunctionExpr; -/** - * Creates an expression that applies a bitwise OR operation between an expression and a constant. - * - * ```typescript - * // Calculate the bitwise OR of 'field1' and 0xFF. - * bitOr(field("field1"), 0xFF); - * ``` - * - * @param bitsExpression An expression returning bits. - * @param otherBits A constant representing bits. - * @return A new {@code Expr} representing the bitwise OR operation. - */ -export function bitOr( - bitsExpression: Expr, - otherBits: number | Buffer | Uint8Array -): FunctionExpr; -/** - * Creates an expression that applies a bitwise OR operation between two expressions. - * - * ```typescript - * // Calculate the bitwise OR of 'field1' and 'field2'. - * bitOr(field("field1"), field("field2")); - * ``` - * - * @param bitsExpression An expression that returns bits when evaluated. - * @param otherBitsExpression An expression that returns bits when evaluated. - * @return A new {@code Expr} representing the bitwise OR operation. - */ -export function bitOr( - bitsExpression: Expr, - otherBitsExpression: Expr -): FunctionExpr; -export function bitOr( - bits: string | Expr, - bitsOrExpression: number | Expr | Buffer | Uint8Array -): FunctionExpr { - return fieldOrExpression(bits).bitOr(valueToDefaultExpr(bitsOrExpression)); -} - -/** - * Creates an expression that applies a bitwise XOR operation between a field and a constant. - * - * ```typescript - * // Calculate the bitwise XOR of 'field1' and 0xFF. - * bitXor("field1", 0xFF); - * ``` - * - * @param field The left operand field name. - * @param otherBits A constant representing bits. - * @return A new {@code Expr} representing the bitwise XOR operation. - */ -export function bitXor( - field: string, - otherBits: number | Buffer | Uint8Array -): FunctionExpr; -/** - * Creates an expression that applies a bitwise XOR operation between a field and an expression. - * - * ```typescript - * // Calculate the bitwise XOR of 'field1' and 'field2'. - * bitXor("field1", field("field2")); - * ``` - * - * @param field The left operand field name. - * @param bitsExpression An expression that returns bits when evaluated. - * @return A new {@code Expr} representing the bitwise XOR operation. - */ -export function bitXor(field: string, bitsExpression: Expr): FunctionExpr; -/** - * Creates an expression that applies a bitwise XOR operation between an expression and a constant. - * - * ```typescript - * // Calculate the bitwise XOR of 'field1' and 0xFF. - * bitXor(field("field1"), 0xFF); - * ``` - * - * @param bitsExpression An expression returning bits. - * @param otherBits A constant representing bits. - * @return A new {@code Expr} representing the bitwise XOR operation. - */ -export function bitXor( - bitsExpression: Expr, - otherBits: number | Buffer | Uint8Array -): FunctionExpr; -/** - * Creates an expression that applies a bitwise XOR operation between two expressions. - * - * ```typescript - * // Calculate the bitwise XOR of 'field1' and 'field2'. - * bitXor(field("field1"), field("field2")); - * ``` - * - * @param bitsExpression An expression that returns bits when evaluated. - * @param otherBitsExpression An expression that returns bits when evaluated. - * @return A new {@code Expr} representing the bitwise XOR operation. - */ -export function bitXor( - bitsExpression: Expr, - otherBitsExpression: Expr -): FunctionExpr; -export function bitXor( - bits: string | Expr, - bitsOrExpression: number | Expr | Buffer | Uint8Array -): FunctionExpr { - return fieldOrExpression(bits).bitXor(valueToDefaultExpr(bitsOrExpression)); -} - -/** - * Creates an expression that applies a bitwise NOT operation to a field. - * - * ```typescript - * // Calculate the bitwise NOT of 'field1'. - * bitNot("field1"); - * ``` - * - * @param field The operand field name. - * @return A new {@code Expr} representing the bitwise NOT operation. - */ -export function bitNot(field: string): FunctionExpr; -/** - * Creates an expression that applies a bitwise NOT operation to an expression. - * - * ```typescript - * // Calculate the bitwise NOT of 'field1'. - * bitNot(field("field1")); - * ``` - * - * @param bitsValueExpression An expression that returns bits when evaluated. - * @return A new {@code Expr} representing the bitwise NOT operation. - */ -export function bitNot(bitsValueExpression: Expr): FunctionExpr; -export function bitNot(bits: string | Expr): FunctionExpr { - return fieldOrExpression(bits).bitNot(); -} - -/** - * Creates an expression that applies a bitwise left shift operation between a field and a constant. - * - * ```typescript - * // Calculate the bitwise left shift of 'field1' by 2 bits. - * bitLeftShift("field1", 2); - * ``` - * - * @param field The left operand field name. - * @param y The right operand constant representing the number of bits to shift. - * @return A new {@code Expr} representing the bitwise left shift operation. - */ -export function bitLeftShift(field: string, y: number): FunctionExpr; -/** - * Creates an expression that applies a bitwise left shift operation between a field and an expression. - * - * ```typescript - * // Calculate the bitwise left shift of 'field1' by 'field2' bits. - * bitLeftShift("field1", field("field2")); - * ``` - * - * @param field The left operand field name. - * @param numberExpr The right operand expression representing the number of bits to shift. - * @return A new {@code Expr} representing the bitwise left shift operation. - */ -export function bitLeftShift(field: string, numberExpr: Expr): FunctionExpr; -/** - * Creates an expression that applies a bitwise left shift operation between an expression and a constant. - * - * ```typescript - * // Calculate the bitwise left shift of 'field1' by 2 bits. - * bitLeftShift(field("field1"), 2); - * ``` - * - * @param xValue An expression returning bits. - * @param y The right operand constant representing the number of bits to shift. - * @return A new {@code Expr} representing the bitwise left shift operation. - */ -export function bitLeftShift(xValue: Expr, y: number): FunctionExpr; -/** - * Creates an expression that applies a bitwise left shift operation between two expressions. - * - * ```typescript - * // Calculate the bitwise left shift of 'field1' by 'field2' bits. - * bitLeftShift(field("field1"), field("field2")); - * ``` - * - * @param xValue An expression returning bits. - * @param numberExpr The right operand expression representing the number of bits to shift. - * @return A new {@code Expr} representing the bitwise left shift operation. - */ -export function bitLeftShift(xValue: Expr, numberExpr: Expr): FunctionExpr; -export function bitLeftShift( - xValue: string | Expr, - numberExpr: number | Expr -): FunctionExpr { - return fieldOrExpression(xValue).bitLeftShift(valueToDefaultExpr(numberExpr)); -} - -/** - * Creates an expression that applies a bitwise right shift operation between a field and a constant. - * - * ```typescript - * // Calculate the bitwise right shift of 'field1' by 2 bits. - * bitRightShift("field1", 2); - * ``` - * - * @param field The left operand field name. - * @param y The right operand constant representing the number of bits to shift. - * @return A new {@code Expr} representing the bitwise right shift operation. - */ -export function bitRightShift(field: string, y: number): FunctionExpr; -/** - * Creates an expression that applies a bitwise right shift operation between a field and an expression. - * - * ```typescript - * // Calculate the bitwise right shift of 'field1' by 'field2' bits. - * bitRightShift("field1", field("field2")); - * ``` - * - * @param field The left operand field name. - * @param numberExpr The right operand expression representing the number of bits to shift. - * @return A new {@code Expr} representing the bitwise right shift operation. - */ -export function bitRightShift(field: string, numberExpr: Expr): FunctionExpr; -/** - * Creates an expression that applies a bitwise right shift operation between an expression and a constant. - * - * ```typescript - * // Calculate the bitwise right shift of 'field1' by 2 bits. - * bitRightShift(field("field1"), 2); - * ``` - * - * @param xValue An expression returning bits. - * @param y The right operand constant representing the number of bits to shift. - * @return A new {@code Expr} representing the bitwise right shift operation. - */ -export function bitRightShift(xValue: Expr, y: number): FunctionExpr; -/** - * Creates an expression that applies a bitwise right shift operation between two expressions. - * - * ```typescript - * // Calculate the bitwise right shift of 'field1' by 'field2' bits. - * bitRightShift(field("field1"), field("field2")); - * ``` - * - * @param xValue An expression returning bits. - * @param numberExpr The right operand expression representing the number of bits to shift. - * @return A new {@code Expr} representing the bitwise right shift operation. - */ -export function bitRightShift(xValue: Expr, numberExpr: Expr): FunctionExpr; -export function bitRightShift( - xValue: string | Expr, - numberExpr: number | Expr -): FunctionExpr { - return fieldOrExpression(xValue).bitRightShift( - valueToDefaultExpr(numberExpr) - ); -} - -/** + * @beta * Creates an expression that indexes into an array from the beginning or end - * and return the element. If the offset exceeds the array length, an error is - * returned. A negative offset, starts from the end. + * and return the element. If the index exceeds the array length, an error is + * returned. A negative index, starts from the end. * * ```typescript * // Return the value in the tags field array at index 1. - * arrayOffset('tags', 1); + * arrayGet('tags', 1); * ``` * * @param arrayField The name of the array field. - * @param offset The index of the element to return. - * @return A new Expr representing the 'arrayOffset' operation. + * @param index The index of the element to return. + * @return A new Expr representing the 'arrayGet' operation. */ -export function arrayOffset(arrayField: string, offset: number): FunctionExpr; +export function arrayGet(arrayField: string, index: number): FunctionExpr; /** + * @beta * Creates an expression that indexes into an array from the beginning or end - * and return the element. If the offset exceeds the array length, an error is - * returned. A negative offset, starts from the end. + * and return the element. If the index exceeds the array length, an error is + * returned. A negative index, starts from the end. * * ```typescript * // Return the value in the tags field array at index specified by field * // 'favoriteTag'. - * arrayOffset('tags', field('favoriteTag')); + * arrayGet('tags', field('favoriteTag')); * ``` * * @param arrayField The name of the array field. - * @param offsetExpr An Expr evaluating to the index of the element to return. - * @return A new Expr representing the 'arrayOffset' operation. + * @param indexExpr An Expr evaluating to the index of the element to return. + * @return A new Expr representing the 'arrayGet' operation. */ -export function arrayOffset(arrayField: string, offsetExpr: Expr): FunctionExpr; +export function arrayGet(arrayField: string, indexExpr: Expr): FunctionExpr; /** + * @beta * Creates an expression that indexes into an array from the beginning or end - * and return the element. If the offset exceeds the array length, an error is - * returned. A negative offset, starts from the end. + * and return the element. If the index exceeds the array length, an error is + * returned. A negative index, starts from the end. * * ```typescript * // Return the value in the tags field array at index 1. - * arrayOffset(field('tags'), 1); + * arrayGet(field('tags'), 1); * ``` * * @param arrayExpression An Expr evaluating to an array. - * @param offset The index of the element to return. - * @return A new Expr representing the 'arrayOffset' operation. + * @param index The index of the element to return. + * @return A new Expr representing the 'arrayGet' operation. */ -export function arrayOffset( - arrayExpression: Expr, - offset: number -): FunctionExpr; +export function arrayGet(arrayExpression: Expr, index: number): FunctionExpr; /** + * @beta * Creates an expression that indexes into an array from the beginning or end - * and return the element. If the offset exceeds the array length, an error is - * returned. A negative offset, starts from the end. + * and return the element. If the index exceeds the array length, an error is + * returned. A negative index, starts from the end. * * ```typescript * // Return the value in the tags field array at index specified by field * // 'favoriteTag'. - * arrayOffset(field('tags'), field('favoriteTag')); + * arrayGet(field('tags'), field('favoriteTag')); * ``` * * @param arrayExpression An Expr evaluating to an array. - * @param offsetExpr An Expr evaluating to the index of the element to return. - * @return A new Expr representing the 'arrayOffset' operation. + * @param indexExpr An Expr evaluating to the index of the element to return. + * @return A new Expr representing the 'arrayGet' operation. */ -export function arrayOffset( - arrayExpression: Expr, - offsetExpr: Expr -): FunctionExpr; -export function arrayOffset( +export function arrayGet(arrayExpression: Expr, indexExpr: Expr): FunctionExpr; +export function arrayGet( array: Expr | string, - offset: Expr | number + index: Expr | number ): FunctionExpr { - return fieldOrExpression(array).arrayOffset(valueToDefaultExpr(offset)); + return fieldOrExpression(array).arrayGet(valueToDefaultExpr(index)); } /** + * @beta * Creates an expression that checks if a given expression produces an error. * * ```typescript @@ -2947,13 +2695,14 @@ export function isError(value: Expr): BooleanExpr { } /** + * @beta * Creates an expression that returns the `catch` argument if there is an * error, else return the result of the `try` argument evaluation. * * ```typescript * // Returns the first item in the title field arrays, or returns * // the entire title field if the array is empty or the field is another type. - * ifError(field("title").arrayOffset(0), field("title")); + * ifError(field("title").arrayGet(0), field("title")); * ``` * * @param tryExpr The try expression. @@ -2964,13 +2713,14 @@ export function isError(value: Expr): BooleanExpr { export function ifError(tryExpr: Expr, catchExpr: Expr): FunctionExpr; /** + * @beta * Creates an expression that returns the `catch` argument if there is an * error, else return the result of the `try` argument evaluation. * * ```typescript * // Returns the first item in the title field arrays, or returns * // "Default Title" - * ifError(field("title").arrayOffset(0), "Default Title"); + * ifError(field("title").arrayGet(0), "Default Title"); * ``` * * @param tryExpr The try expression. @@ -2985,6 +2735,7 @@ export function ifError(tryExpr: Expr, catchValue: unknown): FunctionExpr { } /** + * @beta * Creates an expression that returns `true` if a value is absent. Otherwise, * returns `false` even if the value is `null`. * @@ -2999,6 +2750,7 @@ export function ifError(tryExpr: Expr, catchValue: unknown): FunctionExpr { export function isAbsent(value: Expr): BooleanExpr; /** + * @beta * Creates an expression that returns `true` if a field is absent. Otherwise, * returns `false` even if the field value is `null`. * @@ -3016,6 +2768,7 @@ export function isAbsent(value: Expr | string): BooleanExpr { } /** + * @beta * Creates an expression that checks if an expression evaluates to 'NaN' (Not a Number). * * ```typescript @@ -3029,6 +2782,7 @@ export function isAbsent(value: Expr | string): BooleanExpr { export function isNull(value: Expr): BooleanExpr; /** + * @beta * Creates an expression that checks if a field's value evaluates to 'NaN' (Not a Number). * * ```typescript @@ -3045,6 +2799,7 @@ export function isNull(value: Expr | string): BooleanExpr { } /** + * @beta * Creates an expression that checks if tbe result of an expression is not null. * * ```typescript @@ -3058,6 +2813,7 @@ export function isNull(value: Expr | string): BooleanExpr { export function isNotNull(value: Expr): BooleanExpr; /** + * @beta * Creates an expression that checks if tbe value of a field is not null. * * ```typescript @@ -3074,6 +2830,7 @@ export function isNotNull(value: Expr | string): BooleanExpr { } /** + * @beta * Creates an expression that checks if the results of this expression is NOT 'NaN' (Not a Number). * * ```typescript @@ -3088,7 +2845,6 @@ export function isNotNan(value: Expr): BooleanExpr; /** * @beta - * * Creates an expression that checks if the results of this expression is NOT 'NaN' (Not a Number). * * ```typescript @@ -3106,7 +2862,6 @@ export function isNotNan(value: Expr | string): BooleanExpr { /** * @beta - * * Creates an expression that removes a key from the map at the specified field name. * * ``` @@ -3120,7 +2875,6 @@ export function isNotNan(value: Expr | string): BooleanExpr { export function mapRemove(mapField: string, key: string): FunctionExpr; /** * @beta - * * Creates an expression that removes a key from the map produced by evaluating an expression. * * ``` @@ -3134,7 +2888,6 @@ export function mapRemove(mapField: string, key: string): FunctionExpr; export function mapRemove(mapExpr: Expr, key: string): FunctionExpr; /** * @beta - * * Creates an expression that removes a key from the map at the specified field name. * * ``` @@ -3148,7 +2901,6 @@ export function mapRemove(mapExpr: Expr, key: string): FunctionExpr; export function mapRemove(mapField: string, keyExpr: Expr): FunctionExpr; /** * @beta - * * Creates an expression that removes a key from the map produced by evaluating an expression. * * ``` @@ -3170,7 +2922,6 @@ export function mapRemove( /** * @beta - * * Creates an expression that merges multiple map values. * * ``` @@ -3193,7 +2944,6 @@ export function mapMerge( /** * @beta - * * Creates an expression that merges multiple map values. * * ``` @@ -3226,23 +2976,6 @@ export function mapMerge( /** * @beta - * - * Creates an expression that returns the document ID from a path. - * - * ```typescript - * // Get the document ID from a path. - * documentId(myDocumentReference); - * ``` - * - * @return A new {@code Expr} representing the documentId operation. - */ -export function documentId( - documentPath: string | firestore.DocumentReference -): FunctionExpr; - -/** - * @beta - * * Creates an expression that returns the document ID from a path. * * ```typescript @@ -3252,25 +2985,19 @@ export function documentId( * * @return A new {@code Expr} representing the documentId operation. */ -export function documentId(documentPathExpr: Expr): FunctionExpr; - -export function documentId( - documentPath: Expr | string | firestore.DocumentReference -): FunctionExpr { - const documentPathExpr = valueToDefaultExpr(documentPath); +export function documentId(documentPathExpr: Expr): FunctionExpr { return documentPathExpr.documentId(); } /** * @beta - * * Creates an expression that returns a substring of a string or byte array. * * @param field The name of a field containing a string or byte array to compute the substring from. * @param position Index of the first character of the substring. * @param length Length of the substring. */ -export function substr( +export function substring( field: string, position: number, length?: number @@ -3278,14 +3005,13 @@ export function substr( /** * @beta - * * Creates an expression that returns a substring of a string or byte array. * * @param input An expression returning a string or byte array to compute the substring from. * @param position Index of the first character of the substring. * @param length Length of the substring. */ -export function substr( +export function substring( input: Expr, position: number, length?: number @@ -3293,14 +3019,13 @@ export function substr( /** * @beta - * * Creates an expression that returns a substring of a string or byte array. * * @param field The name of a field containing a string or byte array to compute the substring from. * @param position An expression that returns the index of the first character of the substring. * @param length An expression that returns the length of the substring. */ -export function substr( +export function substring( field: string, position: Expr, length?: Expr @@ -3308,20 +3033,19 @@ export function substr( /** * @beta - * * Creates an expression that returns a substring of a string or byte array. * * @param input An expression returning a string or byte array to compute the substring from. * @param position An expression that returns the index of the first character of the substring. * @param length An expression that returns the length of the substring. */ -export function substr( +export function substring( input: Expr, position: Expr, length?: Expr ): FunctionExpr; -export function substr( +export function substring( field: Expr | string, position: Expr | number, length?: Expr | number @@ -3330,12 +3054,11 @@ export function substr( const positionExpr = valueToDefaultExpr(position); const lengthExpr = length === undefined ? undefined : valueToDefaultExpr(length); - return fieldExpr.substr(positionExpr, lengthExpr); + return fieldExpr.substring(positionExpr, lengthExpr); } /** * @beta - * * Creates an expression that adds the result of two expressions together. * * ```typescript @@ -3351,7 +3074,6 @@ export function add(first: Expr, second: Expr | unknown): FunctionExpr; /** * @beta - * * Creates an expression that adds a field's value to the result of an expression. * * ```typescript @@ -3374,7 +3096,6 @@ export function add( /** * @beta - * * Creates an expression that subtracts two expressions. * * ```typescript @@ -3382,15 +3103,14 @@ export function add( * subtract(field("price"), field("discount")); * ``` * - * @param left The expression to subtract from. - * @param right The expression to subtract. + * @param minuend The expression to subtract from. + * @param subtrahend The expression to subtract. * @return A new {@code Expr} representing the subtraction operation. */ -export function subtract(left: Expr, right: Expr): FunctionExpr; +export function subtract(minuend: Expr, subtrahend: Expr): FunctionExpr; /** * @beta - * * Creates an expression that subtracts a constant value from an expression. * * ```typescript @@ -3398,15 +3118,14 @@ export function subtract(left: Expr, right: Expr): FunctionExpr; * subtract(field("value"), 2); * ``` * - * @param expression The expression to subtract from. - * @param value The constant value to subtract. + * @param minuend The expression to subtract from. + * @param subtrahend The constant value to subtract. * @return A new {@code Expr} representing the subtraction operation. */ -export function subtract(expression: Expr, value: unknown): FunctionExpr; +export function subtract(minuend: Expr, subtrahend: unknown): FunctionExpr; /** * @beta - * * Creates an expression that subtracts an expression from a field's value. * * ```typescript @@ -3414,15 +3133,17 @@ export function subtract(expression: Expr, value: unknown): FunctionExpr; * subtract("price", field("discount")); * ``` * - * @param fieldName The field name to subtract from. - * @param expression The expression to subtract. + * @param minuendFieldName The field name to subtract from. + * @param subtrahend The expression to subtract. * @return A new {@code Expr} representing the subtraction operation. */ -export function subtract(fieldName: string, expression: Expr): FunctionExpr; +export function subtract( + minuendFieldName: string, + subtrahend: Expr +): FunctionExpr; /** * @beta - * * Creates an expression that subtracts a constant value from a field's value. * * ```typescript @@ -3430,11 +3151,14 @@ export function subtract(fieldName: string, expression: Expr): FunctionExpr; * subtract("total", 20); * ``` * - * @param fieldName The field name to subtract from. - * @param value The constant value to subtract. + * @param minuendFieldName The field name to subtract from. + * @param subtrahend The constant value to subtract. * @return A new {@code Expr} representing the subtraction operation. */ -export function subtract(fieldName: string, value: unknown): FunctionExpr; +export function subtract( + minuendFieldName: string, + subtrahend: unknown +): FunctionExpr; export function subtract( left: Expr | string, right: Expr | unknown @@ -3446,7 +3170,6 @@ export function subtract( /** * @beta - * * Creates an expression that multiplies the result of two expressions together. * * ```typescript @@ -3462,7 +3185,6 @@ export function multiply(first: Expr, second: Expr | unknown): FunctionExpr; /** * @beta - * * Creates an expression that multiplies a field's value by the result of an expression. * * ```typescript @@ -3488,7 +3210,6 @@ export function multiply( /** * @beta - * * Creates an expression that divides two expressions. * * ```typescript @@ -3496,15 +3217,14 @@ export function multiply( * divide(field("total"), field("count")); * ``` * - * @param left The expression to be divided. - * @param right The expression to divide by. + * @param dividend The expression to be divided. + * @param divisort The expression to divide by. * @return A new {@code Expr} representing the division operation. */ -export function divide(left: Expr, right: Expr): FunctionExpr; +export function divide(dividend: Expr, divisort: Expr): FunctionExpr; /** * @beta - * * Creates an expression that divides an expression by a constant value. * * ```typescript @@ -3512,15 +3232,14 @@ export function divide(left: Expr, right: Expr): FunctionExpr; * divide(field("value"), 10); * ``` * - * @param expression The expression to be divided. - * @param value The constant value to divide by. + * @param dividend The expression to be divided. + * @param divisor The constant value to divide by. * @return A new {@code Expr} representing the division operation. */ -export function divide(expression: Expr, value: unknown): FunctionExpr; +export function divide(dividend: Expr, divisor: unknown): FunctionExpr; /** * @beta - * * Creates an expression that divides a field's value by an expression. * * ```typescript @@ -3528,15 +3247,14 @@ export function divide(expression: Expr, value: unknown): FunctionExpr; * divide("total", field("count")); * ``` * - * @param fieldName The field name to be divided. - * @param expressions The expression to divide by. + * @param dividend The field name to be divided. + * @param divisor The expression to divide by. * @return A new {@code Expr} representing the division operation. */ -export function divide(fieldName: string, expressions: Expr): FunctionExpr; +export function divide(dividend: string, divisor: Expr): FunctionExpr; /** * @beta - * * Creates an expression that divides a field's value by a constant value. * * ```typescript @@ -3544,23 +3262,22 @@ export function divide(fieldName: string, expressions: Expr): FunctionExpr; * divide("value", 10); * ``` * - * @param fieldName The field name to be divided. - * @param value The constant value to divide by. + * @param dividend The field name to be divided. + * @param divisor The constant value to divide by. * @return A new {@code Expr} representing the division operation. */ -export function divide(fieldName: string, value: unknown): FunctionExpr; +export function divide(dividend: string, divisor: unknown): FunctionExpr; export function divide( - left: Expr | string, - right: Expr | unknown + dividend: Expr | string, + divisor: Expr | unknown ): FunctionExpr { - const normalizedLeft = fieldOrExpression(left); - const normalizedRight = valueToDefaultExpr(right); + const normalizedLeft = fieldOrExpression(dividend); + const normalizedRight = valueToDefaultExpr(divisor); return normalizedLeft.divide(normalizedRight); } /** * @beta - * * Creates an expression that calculates the modulo (remainder) of dividing two expressions. * * ```typescript @@ -3576,7 +3293,6 @@ export function mod(left: Expr, right: Expr): FunctionExpr; /** * @beta - * * Creates an expression that calculates the modulo (remainder) of dividing an expression by a constant. * * ```typescript @@ -3592,7 +3308,6 @@ export function mod(expression: Expr, value: unknown): FunctionExpr; /** * @beta - * * Creates an expression that calculates the modulo (remainder) of dividing a field's value by an expression. * * ```typescript @@ -3608,7 +3323,6 @@ export function mod(fieldName: string, expression: Expr): FunctionExpr; /** * @beta - * * Creates an expression that calculates the modulo (remainder) of dividing a field's value by a constant. * * ```typescript @@ -3629,7 +3343,6 @@ export function mod(left: Expr | string, right: Expr | unknown): FunctionExpr { /** * @beta - * * Creates an expression that creates a Firestore map value from an input object. * * ```typescript @@ -3655,6 +3368,7 @@ export function map(elements: Record): FunctionExpr { } /** + * @beta * Internal use only * Converts a plainObject to a mapValue in the proto representation, * rather than a functionValue+map that is the result of the map(...) function. @@ -3678,7 +3392,6 @@ export function _mapValue(plainObject: Record): MapValue { /** * @beta - * * Creates an expression that creates a Firestore array value from an input array. * * ```typescript @@ -3699,7 +3412,6 @@ export function array(elements: unknown[]): FunctionExpr { /** * @beta - * * Creates an expression that checks if two expressions are equal. * * ```typescript @@ -3715,7 +3427,6 @@ export function eq(left: Expr, right: Expr): BooleanExpr; /** * @beta - * * Creates an expression that checks if an expression is equal to a constant value. * * ```typescript @@ -3731,7 +3442,6 @@ export function eq(expression: Expr, value: unknown): BooleanExpr; /** * @beta - * * Creates an expression that checks if a field's value is equal to an expression. * * ```typescript @@ -3747,7 +3457,6 @@ export function eq(fieldName: string, expression: Expr): BooleanExpr; /** * @beta - * * Creates an expression that checks if a field's value is equal to a constant value. * * ```typescript @@ -3768,7 +3477,6 @@ export function eq(left: Expr | string, right: unknown): BooleanExpr { /** * @beta - * * Creates an expression that checks if two expressions are not equal. * * ```typescript @@ -3784,7 +3492,6 @@ export function neq(left: Expr, right: Expr): BooleanExpr; /** * @beta - * * Creates an expression that checks if an expression is not equal to a constant value. * * ```typescript @@ -3800,7 +3507,6 @@ export function neq(expression: Expr, value: unknown): BooleanExpr; /** * @beta - * * Creates an expression that checks if a field's value is not equal to an expression. * * ```typescript @@ -3816,7 +3522,6 @@ export function neq(fieldName: string, expression: Expr): BooleanExpr; /** * @beta - * * Creates an expression that checks if a field's value is not equal to a constant value. * * ```typescript @@ -3837,7 +3542,6 @@ export function neq(left: Expr | string, right: unknown): BooleanExpr { /** * @beta - * * Creates an expression that checks if the first expression is less than the second expression. * * ```typescript @@ -3853,7 +3557,6 @@ export function lt(left: Expr, right: Expr): BooleanExpr; /** * @beta - * * Creates an expression that checks if an expression is less than a constant value. * * ```typescript @@ -3869,7 +3572,6 @@ export function lt(expression: Expr, value: unknown): BooleanExpr; /** * @beta - * * Creates an expression that checks if a field's value is less than an expression. * * ```typescript @@ -3885,7 +3587,6 @@ export function lt(fieldName: string, expression: Expr): BooleanExpr; /** * @beta - * * Creates an expression that checks if a field's value is less than a constant value. * * ```typescript @@ -3906,7 +3607,6 @@ export function lt(left: Expr | string, right: unknown): BooleanExpr { /** * @beta - * * Creates an expression that checks if the first expression is less than or equal to the second * expression. * @@ -3923,7 +3623,6 @@ export function lte(left: Expr, right: Expr): BooleanExpr; /** * @beta - * * Creates an expression that checks if an expression is less than or equal to a constant value. * * ```typescript @@ -3938,6 +3637,7 @@ export function lte(left: Expr, right: Expr): BooleanExpr; export function lte(expression: Expr, value: unknown): BooleanExpr; /** + * @beta * Creates an expression that checks if a field's value is less than or equal to an expression. * * ```typescript @@ -3953,7 +3653,6 @@ export function lte(fieldName: string, expression: Expr): BooleanExpr; /** * @beta - * * Creates an expression that checks if a field's value is less than or equal to a constant value. * * ```typescript @@ -3974,7 +3673,6 @@ export function lte(left: Expr | string, right: unknown): BooleanExpr { /** * @beta - * * Creates an expression that checks if the first expression is greater than the second * expression. * @@ -3991,7 +3689,6 @@ export function gt(left: Expr, right: Expr): BooleanExpr; /** * @beta - * * Creates an expression that checks if an expression is greater than a constant value. * * ```typescript @@ -4007,7 +3704,6 @@ export function gt(expression: Expr, value: unknown): BooleanExpr; /** * @beta - * * Creates an expression that checks if a field's value is greater than an expression. * * ```typescript @@ -4023,7 +3719,6 @@ export function gt(fieldName: string, expression: Expr): BooleanExpr; /** * @beta - * * Creates an expression that checks if a field's value is greater than a constant value. * * ```typescript @@ -4044,7 +3739,6 @@ export function gt(left: Expr | string, right: unknown): BooleanExpr { /** * @beta - * * Creates an expression that checks if the first expression is greater than or equal to the * second expression. * @@ -4061,7 +3755,6 @@ export function gte(left: Expr, right: Expr): BooleanExpr; /** * @beta - * * Creates an expression that checks if an expression is greater than or equal to a constant * value. * @@ -4078,7 +3771,6 @@ export function gte(expression: Expr, value: unknown): BooleanExpr; /** * @beta - * * Creates an expression that checks if a field's value is greater than or equal to an expression. * * ```typescript @@ -4094,7 +3786,6 @@ export function gte(fieldName: string, value: Expr): BooleanExpr; /** * @beta - * * Creates an expression that checks if a field's value is greater than or equal to a constant * value. * @@ -4116,61 +3807,6 @@ export function gte(left: Expr | string, right: unknown): BooleanExpr { /** * @beta - * - * Creates an expression that concatenates an array expression with other arrays. - * - * ```typescript - * // Combine the 'items' array with two new item arrays - * arrayConcat(field("items"), [field("newItems"), field("otherItems")]); - * ``` - * - * @param firstArray The first array expression to concatenate to. - * @param secondArray The second array expression or array literal to concatenate to. - * @param otherArrays Optional additional array expressions or array literals to concatenate. - * @return A new {@code Expr} representing the concatenated array. - */ -export function arrayConcat( - firstArray: Expr, - secondArray: Expr | unknown[], - ...otherArrays: Array -): FunctionExpr; - -/** - * @beta - * - * Creates an expression that concatenates a field's array value with other arrays. - * - * ```typescript - * // Combine the 'items' array with two new item arrays - * arrayConcat("items", [field("newItems"), field("otherItems")]); - * ``` - * - * @param firstArrayField The first array to concatenate to. - * @param secondArray The second array expression or array literal to concatenate to. - * @param otherArrays Optional additional array expressions or array literals to concatenate. - * @return A new {@code Expr} representing the concatenated array. - */ -export function arrayConcat( - firstArrayField: string, - secondArray: Expr | unknown[], - ...otherArrays: Array -): FunctionExpr; - -export function arrayConcat( - firstArray: Expr | string, - secondArray: Expr | unknown[], - ...otherArrays: Array -): FunctionExpr { - const exprValues = otherArrays.map(element => valueToDefaultExpr(element)); - return fieldOrExpression(firstArray).arrayConcat( - fieldOrExpression(secondArray), - ...exprValues - ); -} - -/** - * @beta - * * Creates an expression that checks if an array expression contains a specific element. * * ```typescript @@ -4186,7 +3822,6 @@ export function arrayContains(array: Expr, element: Expr): FunctionExpr; /** * @beta - * * Creates an expression that checks if an array expression contains a specific element. * * ```typescript @@ -4202,7 +3837,6 @@ export function arrayContains(array: Expr, element: unknown): FunctionExpr; /** * @beta - * * Creates an expression that checks if a field's array value contains a specific element. * * ```typescript @@ -4218,7 +3852,6 @@ export function arrayContains(fieldName: string, element: Expr): FunctionExpr; /** * @beta - * * Creates an expression that checks if a field's array value contains a specific value. * * ```typescript @@ -4242,7 +3875,6 @@ export function arrayContains( /** * @beta - * * Creates an expression that checks if an array expression contains any of the specified * elements. * @@ -4262,7 +3894,6 @@ export function arrayContainsAny( /** * @beta - * * Creates an expression that checks if a field's array value contains any of the specified * elements. * @@ -4283,7 +3914,6 @@ export function arrayContainsAny( /** * @beta - * * Creates an expression that checks if an array expression contains any of the specified * elements. * @@ -4300,7 +3930,6 @@ export function arrayContainsAny(array: Expr, values: Expr): BooleanExpr; /** * @beta - * * Creates an expression that checks if a field's array value contains any of the specified * elements. * @@ -4328,7 +3957,6 @@ export function arrayContainsAny( /** * @beta - * * Creates an expression that checks if an array expression contains all the specified elements. * * ```typescript @@ -4347,7 +3975,6 @@ export function arrayContainsAll( /** * @beta - * * Creates an expression that checks if a field's array value contains all the specified values or * expressions. * @@ -4367,7 +3994,6 @@ export function arrayContainsAll( /** * @beta - * * Creates an expression that checks if an array expression contains all the specified elements. * * ```typescript @@ -4386,7 +4012,6 @@ export function arrayContainsAll( /** * @beta - * * Creates an expression that checks if a field's array value contains all the specified values or * expressions. * @@ -4416,7 +4041,6 @@ export function arrayContainsAll( /** * @beta - * * Creates an expression that calculates the length of an array in a specified field. * * ```typescript @@ -4431,7 +4055,6 @@ export function arrayLength(fieldName: string): FunctionExpr; /** * @beta - * * Creates an expression that calculates the length of an array expression. * * ```typescript @@ -4449,7 +4072,6 @@ export function arrayLength(array: Expr | string): FunctionExpr { /** * @beta - * * Creates an expression that checks if an expression, when evaluated, is equal to any of the provided values or * expressions. * @@ -4469,7 +4091,6 @@ export function eqAny( /** * @beta - * * Creates an expression that checks if an expression is equal to any of the provided values. * * ```typescript @@ -4485,7 +4106,6 @@ export function eqAny(expression: Expr, arrayExpression: Expr): BooleanExpr; /** * @beta - * * Creates an expression that checks if a field's value is equal to any of the provided values or * expressions. * @@ -4505,7 +4125,6 @@ export function eqAny( /** * @beta - * * Creates an expression that checks if a field's value is equal to any of the provided values or * expressions. * @@ -4532,7 +4151,6 @@ export function eqAny( /** * @beta - * * Creates an expression that checks if an expression is not equal to any of the provided values * or expressions. * @@ -4552,7 +4170,6 @@ export function notEqAny( /** * @beta - * * Creates an expression that checks if a field's value is not equal to any of the provided values * or expressions. * @@ -4572,7 +4189,6 @@ export function notEqAny( /** * @beta - * * Creates an expression that checks if an expression is not equal to any of the provided values * or expressions. * @@ -4589,7 +4205,6 @@ export function notEqAny(element: Expr, arrayExpression: Expr): BooleanExpr; /** * @beta - * * Creates an expression that checks if a field's value is not equal to any of the values in the evaluated expression. * * ```typescript @@ -4616,7 +4231,6 @@ export function notEqAny( /** * @beta - * * Creates an expression that performs a logical 'XOR' (exclusive OR) operation on multiple BooleanExprs. * * ```typescript @@ -4643,7 +4257,6 @@ export function xor( /** * @beta - * * Creates a conditional expression that evaluates to a 'then' expression if a condition is true * and an 'else' expression if the condition is false. * @@ -4672,7 +4285,6 @@ export function cond( /** * @beta - * * Creates an expression that negates a filter condition. * * ```typescript @@ -4689,7 +4301,6 @@ export function not(booleanExpr: BooleanExpr): BooleanExpr { /** * @beta - * * Creates an expression that returns the largest value between multiple input * expressions or literal values. Based on Firestore's value type ordering. * @@ -4712,7 +4323,6 @@ export function logicalMaximum( /** * @beta - * * Creates an expression that returns the largest value between multiple input * expressions or literal values. Based on Firestore's value type ordering. * @@ -4746,7 +4356,6 @@ export function logicalMaximum( /** * @beta - * * Creates an expression that returns the smallest value between multiple input * expressions and literal values. Based on Firestore's value type ordering. * @@ -4769,7 +4378,6 @@ export function logicalMinimum( /** * @beta - * * Creates an expression that returns the smallest value between a field's value * and other input expressions or literal values. * Based on Firestore's value type ordering. @@ -4804,7 +4412,6 @@ export function logicalMinimum( /** * @beta - * * Creates an expression that checks if a field exists. * * ```typescript @@ -4819,7 +4426,6 @@ export function exists(value: Expr): BooleanExpr; /** * @beta - * * Creates an expression that checks if a field exists. * * ```typescript @@ -4837,7 +4443,6 @@ export function exists(valueOrField: Expr | string): BooleanExpr { /** * @beta - * * Creates an expression that checks if an expression evaluates to 'NaN' (Not a Number). * * ```typescript @@ -4852,7 +4457,6 @@ export function isNan(value: Expr): BooleanExpr; /** * @beta - * * Creates an expression that checks if a field's value evaluates to 'NaN' (Not a Number). * * ```typescript @@ -4870,7 +4474,6 @@ export function isNan(value: Expr | string): BooleanExpr { /** * @beta - * * Creates an expression that reverses a string. * * ```typescript @@ -4885,7 +4488,6 @@ export function reverse(stringExpression: Expr): FunctionExpr; /** * @beta - * * Creates an expression that reverses a string value in the specified field. * * ```typescript @@ -4903,189 +4505,162 @@ export function reverse(expr: Expr | string): FunctionExpr { /** * @beta - * - * Creates an expression that replaces the first occurrence of a substring within a string with another substring. + * Creates an expression that reverses an array. * * ```typescript - * // Replace the first occurrence of "hello" with "hi" in the 'message' field. - * replaceFirst(field("message"), "hello", "hi"); + * // Reverse the value of the 'myArray' field. + * arrayReverse("myArray"); * ``` * - * @param value The expression representing the string to perform the replacement on. - * @param find The substring to search for. - * @param replace The substring to replace the first occurrence of 'find' with. - * @return A new {@code Expr} representing the string with the first occurrence replaced. + * @param fieldName The name of the field to reverse. + * @return A new {@code Expr} representing the reversed array. */ -export function replaceFirst( - value: Expr, - find: string, - replace: string -): FunctionExpr; +export function arrayReverse(fieldName: string): FunctionExpr; /** * @beta - * - * Creates an expression that replaces the first occurrence of a substring within a string with another substring, - * where the substring to find and the replacement substring are specified by expressions. + * Creates an expression that reverses an array. * * ```typescript - * // Replace the first occurrence of the value in 'findField' with the value in 'replaceField' in the 'message' field. - * replaceFirst(field("message"), field("findField"), field("replaceField")); + * // Reverse the value of the 'myArray' field. + * arrayReverse(field("myArray")); * ``` * - * @param value The expression representing the string to perform the replacement on. - * @param find The expression representing the substring to search for. - * @param replace The expression representing the substring to replace the first occurrence of 'find' with. - * @return A new {@code Expr} representing the string with the first occurrence replaced. + * @param arrayExpression An expression evaluating to an array value, which will be reversed. + * @return A new {@code Expr} representing the reversed array. */ -export function replaceFirst( - value: Expr, - find: Expr, - replace: Expr -): FunctionExpr; +export function arrayReverse(arrayExpression: Expr): FunctionExpr; +export function arrayReverse(expr: Expr | string): FunctionExpr { + return fieldOrExpression(expr).arrayReverse(); +} /** * @beta - * - * Creates an expression that replaces the first occurrence of a substring within a string represented by a field with another substring. + * Creates an expression that calculates the byte length of a string in UTF-8, or just the length of a Blob. * * ```typescript - * // Replace the first occurrence of "hello" with "hi" in the 'message' field. - * replaceFirst("message", "hello", "hi"); + * // Calculate the length of the 'myString' field in bytes. + * byteLength(field("myString")); * ``` * - * @param fieldName The name of the field representing the string to perform the replacement on. - * @param find The substring to search for. - * @param replace The substring to replace the first occurrence of 'find' with. - * @return A new {@code Expr} representing the string with the first occurrence replaced. + * @param expr The expression representing the string. + * @return A new {@code Expr} representing the length of the string in bytes. */ -export function replaceFirst( - fieldName: string, - find: string, - replace: string -): FunctionExpr; -export function replaceFirst( - value: Expr | string, - find: Expr | string, - replace: Expr | string -): FunctionExpr { - const normalizedValue = fieldOrExpression(value); - const normalizedFind = valueToDefaultExpr(find); - const normalizedReplace = valueToDefaultExpr(replace); - return normalizedValue.replaceFirst(normalizedFind, normalizedReplace); -} +export function byteLength(expr: Expr): FunctionExpr; /** * @beta - * - * Creates an expression that replaces all occurrences of a substring within a string with another substring. + * Creates an expression that calculates the length of a string represented by a field in UTF-8 bytes, or just the length of a Blob. * * ```typescript - * // Replace all occurrences of "hello" with "hi" in the 'message' field. - * replaceAll(field("message"), "hello", "hi"); + * // Calculate the length of the 'myString' field in bytes. + * byteLength("myString"); * ``` * - * @param value The expression representing the string to perform the replacement on. - * @param find The substring to search for. - * @param replace The substring to replace all occurrences of 'find' with. - * @return A new {@code Expr} representing the string with all occurrences replaced. + * @param fieldName The name of the field containing the string. + * @return A new {@code Expr} representing the length of the string in bytes. */ -export function replaceAll( - value: Expr, - find: string, - replace: string -): FunctionExpr; +export function byteLength(fieldName: string): FunctionExpr; +export function byteLength(expr: Expr | string): FunctionExpr { + const normalizedExpr = fieldOrExpression(expr); + return normalizedExpr.byteLength(); +} /** * @beta - * - * Creates an expression that replaces all occurrences of a substring within a string with another substring, - * where the substring to find and the replacement substring are specified by expressions. + * Creates an expression that computes e to the power of the expression's result. * * ```typescript - * // Replace all occurrences of the value in 'findField' with the value in 'replaceField' in the 'message' field. - * replaceAll(field("message"), field("findField"), field("replaceField")); + * // Compute e to the power of 2. + * exp(constant(2)); * ``` * - * @param value The expression representing the string to perform the replacement on. - * @param find The expression representing the substring to search for. - * @param replace The expression representing the substring to replace all occurrences of 'find' with. - * @return A new {@code Expr} representing the string with all occurrences replaced. + * @return A new {@code Expr} representing the exp of the numeric value. */ -export function replaceAll( - value: Expr, - find: Expr, - replace: Expr -): FunctionExpr; +export function exp(expression: Expr): FunctionExpr; /** * @beta - * - * Creates an expression that replaces all occurrences of a substring within a string represented by a field with another substring. + * Creates an expression that computes e to the power of the expression's result. * * ```typescript - * // Replace all occurrences of "hello" with "hi" in the 'message' field. - * replaceAll("message", "hello", "hi"); + * // Compute e to the power of the 'value' field. + * exp('value'); * ``` * - * @param fieldName The name of the field representing the string to perform the replacement on. - * @param find The substring to search for. - * @param replace The substring to replace all occurrences of 'find' with. - * @return A new {@code Expr} representing the string with all occurrences replaced. + * @return A new {@code Expr} representing the exp of the numeric value. */ -export function replaceAll( - fieldName: string, - find: string, - replace: string -): FunctionExpr; -export function replaceAll( - value: Expr | string, - find: Expr | string, - replace: Expr | string -): FunctionExpr { - const normalizedValue = fieldOrExpression(value); - const normalizedFind = valueToDefaultExpr(find); - const normalizedReplace = valueToDefaultExpr(replace); - return normalizedValue.replaceAll(normalizedFind, normalizedReplace); +export function exp(fieldName: string): FunctionExpr; + +export function exp(expressionOrFieldName: Expr | string): FunctionExpr { + return fieldOrExpression(expressionOrFieldName).exp(); } /** * @beta - * - * Creates an expression that calculates the byte length of a string in UTF-8, or just the length of a Blob. + * Creates an expression that computes the ceiling of a numeric value. * * ```typescript - * // Calculate the length of the 'myString' field in bytes. - * byteLength(field("myString")); + * // Compute the ceiling of the 'price' field. + * ceil("price"); * ``` * - * @param expr The expression representing the string. - * @return A new {@code Expr} representing the length of the string in bytes. + * @param fieldName The name of the field to compute the ceiling of. + * @return A new {@code Expr} representing the ceiling of the numeric value. */ -export function byteLength(expr: Expr): FunctionExpr; +export function ceil(fieldName: string): FunctionExpr; /** * @beta - * - * Creates an expression that calculates the length of a string represented by a field in UTF-8 bytes, or just the length of a Blob. + * Creates an expression that computes the ceiling of a numeric value. * * ```typescript - * // Calculate the length of the 'myString' field in bytes. - * byteLength("myString"); + * // Compute the ceiling of the 'price' field. + * ceil(field("price")); * ``` * - * @param fieldName The name of the field containing the string. - * @return A new {@code Expr} representing the length of the string in bytes. + * @param expression An expression evaluating to a numeric value, which the ceiling will be computed for. + * @return A new {@code Expr} representing the ceiling of the numeric value. */ -export function byteLength(fieldName: string): FunctionExpr; -export function byteLength(expr: Expr | string): FunctionExpr { - const normalizedExpr = fieldOrExpression(expr); - return normalizedExpr.byteLength(); +export function ceil(expression: Expr): FunctionExpr; +export function ceil(expr: Expr | string): FunctionExpr { + return fieldOrExpression(expr).ceil(); +} + +/** + * @beta + * Creates an expression that computes the floor of a numeric value. + * + * @param expr The expression to compute the floor of. + * @return A new {@code Expr} representing the floor of the numeric value. + */ +export function floor(expr: Expr): FunctionExpr; + +/** + * @beta + * Creates an expression that computes the floor of a numeric value. + * + * @param fieldName The name of the field to compute the floor of. + * @return A new {@code Expr} representing the floor of the numeric value. + */ +export function floor(fieldName: string): FunctionExpr; +export function floor(expr: Expr | string): FunctionExpr { + return fieldOrExpression(expr).floor(); } /** * @beta + * Creates an aggregation that counts the number of distinct values of a field. * + * @param expr The expression or field to count distinct values of. + * @return A new `AggregateFunction` representing the 'count_distinct' aggregation. + */ +export function countDistinct(expr: Expr | string): AggregateFunction { + return fieldOrExpression(expr).countDistinct(); +} + +/** + * @beta * Creates an expression that calculates the character length of a string field in UTF8. * * ```typescript @@ -5100,7 +4675,6 @@ export function charLength(fieldName: string): FunctionExpr; /** * @beta - * * Creates an expression that calculates the character length of a string expression in UTF-8. * * ```typescript @@ -5119,7 +4693,6 @@ export function charLength(value: Expr | string): FunctionExpr { /** * @beta - * * Creates an expression that performs a case-sensitive wildcard string comparison against a * field. * @@ -5136,7 +4709,6 @@ export function like(fieldName: string, pattern: string): BooleanExpr; /** * @beta - * * Creates an expression that performs a case-sensitive wildcard string comparison against a * field. * @@ -5153,7 +4725,6 @@ export function like(fieldName: string, pattern: Expr): BooleanExpr; /** * @beta - * * Creates an expression that performs a case-sensitive wildcard string comparison. * * ```typescript @@ -5169,7 +4740,6 @@ export function like(stringExpression: Expr, pattern: string): BooleanExpr; /** * @beta - * * Creates an expression that performs a case-sensitive wildcard string comparison. * * ```typescript @@ -5193,7 +4763,6 @@ export function like( /** * @beta - * * Creates an expression that checks if a string field contains a specified regular expression as * a substring. * @@ -5210,7 +4779,6 @@ export function regexContains(fieldName: string, pattern: string): BooleanExpr; /** * @beta - * * Creates an expression that checks if a string field contains a specified regular expression as * a substring. * @@ -5227,7 +4795,6 @@ export function regexContains(fieldName: string, pattern: Expr): BooleanExpr; /** * @beta - * * Creates an expression that checks if a string expression contains a specified regular * expression as a substring. * @@ -5247,7 +4814,6 @@ export function regexContains( /** * @beta - * * Creates an expression that checks if a string expression contains a specified regular * expression as a substring. * @@ -5275,7 +4841,6 @@ export function regexContains( /** * @beta - * * Creates an expression that checks if a string field matches a specified regular expression. * * ```typescript @@ -5291,7 +4856,6 @@ export function regexMatch(fieldName: string, pattern: string): BooleanExpr; /** * @beta - * * Creates an expression that checks if a string field matches a specified regular expression. * * ```typescript @@ -5307,7 +4871,6 @@ export function regexMatch(fieldName: string, pattern: Expr): BooleanExpr; /** * @beta - * * Creates an expression that checks if a string expression matches a specified regular * expression. * @@ -5327,7 +4890,6 @@ export function regexMatch( /** * @beta - * * Creates an expression that checks if a string expression matches a specified regular * expression. * @@ -5352,7 +4914,6 @@ export function regexMatch( /** * @beta - * * Creates an expression that checks if a string field contains a specified substring. * * ```typescript @@ -5368,7 +4929,6 @@ export function strContains(fieldName: string, substring: string): BooleanExpr; /** * @beta - * * Creates an expression that checks if a string field contains a substring specified by an expression. * * ```typescript @@ -5384,7 +4944,6 @@ export function strContains(fieldName: string, substring: Expr): BooleanExpr; /** * @beta - * * Creates an expression that checks if a string expression contains a specified substring. * * ```typescript @@ -5403,7 +4962,6 @@ export function strContains( /** * @beta - * * Creates an expression that checks if a string expression contains a substring specified by another expression. * * ```typescript @@ -5430,7 +4988,6 @@ export function strContains( /** * @beta - * * Creates an expression that checks if a field's value starts with a given prefix. * * ```typescript @@ -5446,7 +5003,6 @@ export function startsWith(fieldName: string, prefix: string): BooleanExpr; /** * @beta - * * Creates an expression that checks if a field's value starts with a given prefix. * * ```typescript @@ -5462,7 +5018,6 @@ export function startsWith(fieldName: string, prefix: Expr): BooleanExpr; /** * @beta - * * Creates an expression that checks if a string expression starts with a given prefix. * * ```typescript @@ -5478,7 +5033,6 @@ export function startsWith(stringExpression: Expr, prefix: string): BooleanExpr; /** * @beta - * * Creates an expression that checks if a string expression starts with a given prefix. * * ```typescript @@ -5500,7 +5054,6 @@ export function startsWith( /** * @beta - * * Creates an expression that checks if a field's value ends with a given postfix. * * ```typescript @@ -5516,7 +5069,6 @@ export function endsWith(fieldName: string, suffix: string): BooleanExpr; /** * @beta - * * Creates an expression that checks if a field's value ends with a given postfix. * * ```typescript @@ -5532,7 +5084,6 @@ export function endsWith(fieldName: string, suffix: Expr): BooleanExpr; /** * @beta - * * Creates an expression that checks if a string expression ends with a given postfix. * * ```typescript @@ -5548,7 +5099,6 @@ export function endsWith(stringExpression: Expr, suffix: string): BooleanExpr; /** * @beta - * * Creates an expression that checks if a string expression ends with a given postfix. * * ```typescript @@ -5570,7 +5120,6 @@ export function endsWith( /** * @beta - * * Creates an expression that converts a string field to lowercase. * * ```typescript @@ -5585,7 +5134,6 @@ export function toLower(fieldName: string): FunctionExpr; /** * @beta - * * Creates an expression that converts a string expression to lowercase. * * ```typescript @@ -5603,7 +5151,6 @@ export function toLower(expr: Expr | string): FunctionExpr { /** * @beta - * * Creates an expression that converts a string field to uppercase. * * ```typescript @@ -5618,7 +5165,6 @@ export function toUpper(fieldName: string): FunctionExpr; /** * @beta - * * Creates an expression that converts a string expression to uppercase. * * ```typescript @@ -5636,7 +5182,6 @@ export function toUpper(expr: Expr | string): FunctionExpr { /** * @beta - * * Creates an expression that removes leading and trailing whitespace from a string field. * * ```typescript @@ -5651,7 +5196,6 @@ export function trim(fieldName: string): FunctionExpr; /** * @beta - * * Creates an expression that removes leading and trailing whitespace from a string expression. * * ```typescript @@ -5669,7 +5213,6 @@ export function trim(expr: Expr | string): FunctionExpr { /** * @beta - * * Creates an expression that concatenates string functions, fields or constants together. * * ```typescript @@ -5720,7 +5263,6 @@ export function strConcat( /** * @beta - * * Accesses a value from a map (object) field using the provided key. * * ```typescript @@ -5736,7 +5278,6 @@ export function mapGet(fieldName: string, subField: string): FunctionExpr; /** * @beta - * * Accesses a value from a map (object) expression using the provided key. * * ```typescript @@ -5758,7 +5299,6 @@ export function mapGet( /** * @beta - * * Creates an aggregation that counts the total number of stage inputs. * * ```typescript @@ -5774,7 +5314,6 @@ export function countAll(): AggregateFunction { /** * @beta - * * Creates an aggregation that counts the number of stage inputs with valid evaluations of the * provided expression. * @@ -5789,6 +5328,7 @@ export function countAll(): AggregateFunction { export function count(expression: Expr): AggregateFunction; /** + * @beta * Creates an aggregation that counts the number of stage inputs where the input field exists. * * ```typescript @@ -5806,7 +5346,6 @@ export function count(value: Expr | string): AggregateFunction { /** * @beta - * * Creates an aggregation that calculates the sum of values from an expression across multiple * stage inputs. * @@ -5822,7 +5361,6 @@ export function sum(expression: Expr): AggregateFunction; /** * @beta - * * Creates an aggregation that calculates the sum of a field's values across multiple stage * inputs. * @@ -5841,7 +5379,6 @@ export function sum(value: Expr | string): AggregateFunction { /** * @beta - * * Creates an aggregation that calculates the average (mean) of values from an expression across * multiple stage inputs. * @@ -5857,7 +5394,6 @@ export function avg(expression: Expr): AggregateFunction; /** * @beta - * * Creates an aggregation that calculates the average (mean) of a field's values across multiple * stage inputs. * @@ -5876,7 +5412,6 @@ export function avg(value: Expr | string): AggregateFunction { /** * @beta - * * Creates an aggregation that finds the minimum value of an expression across multiple stage * inputs. * @@ -5892,7 +5427,6 @@ export function minimum(expression: Expr): AggregateFunction; /** * @beta - * * Creates an aggregation that finds the minimum value of a field across multiple stage inputs. * * ```typescript @@ -5910,7 +5444,6 @@ export function minimum(value: Expr | string): AggregateFunction { /** * @beta - * * Creates an aggregation that finds the maximum value of an expression across multiple stage * inputs. * @@ -5926,7 +5459,6 @@ export function maximum(expression: Expr): AggregateFunction; /** * @beta - * * Creates an aggregation that finds the maximum value of a field across multiple stage inputs. * * ```typescript @@ -5944,7 +5476,6 @@ export function maximum(value: Expr | string): AggregateFunction { /** * @beta - * * Calculates the Cosine distance between a field's vector value and a literal vector value. * * ```typescript @@ -5963,7 +5494,6 @@ export function cosineDistance( /** * @beta - * * Calculates the Cosine distance between a field's vector value and a vector expression. * * ```typescript @@ -5982,7 +5512,6 @@ export function cosineDistance( /** * @beta - * * Calculates the Cosine distance between a vector expression and a vector literal. * * ```typescript @@ -5996,12 +5525,11 @@ export function cosineDistance( */ export function cosineDistance( vectorExpression: Expr, - vector: number[] | Expr + vector: number[] | VectorValue ): FunctionExpr; /** * @beta - * * Calculates the Cosine distance between two vector expressions. * * ```typescript @@ -6019,7 +5547,7 @@ export function cosineDistance( ): FunctionExpr; export function cosineDistance( expr: Expr | string, - other: Expr | number[] | VectorValue + other: Expr | number[] | firestore.VectorValue ): FunctionExpr { const expr1 = fieldOrExpression(expr); const expr2 = vectorToExpr(other); @@ -6028,7 +5556,6 @@ export function cosineDistance( /** * @beta - * * Calculates the dot product between a field's vector value and a double array. * * ```typescript @@ -6047,7 +5574,6 @@ export function dotProduct( /** * @beta - * * Calculates the dot product between a field's vector value and a vector expression. * * ```typescript @@ -6066,7 +5592,6 @@ export function dotProduct( /** * @beta - * * Calculates the dot product between a vector expression and a double array. * * ```typescript @@ -6085,7 +5610,6 @@ export function dotProduct( /** * @beta - * * Calculates the dot product between two vector expressions. * * ```typescript @@ -6112,7 +5636,6 @@ export function dotProduct( /** * @beta - * * Calculates the Euclidean distance between a field's vector value and a double array. * * ```typescript @@ -6131,7 +5654,6 @@ export function euclideanDistance( /** * @beta - * * Calculates the Euclidean distance between a field's vector value and a vector expression. * * ```typescript @@ -6150,7 +5672,6 @@ export function euclideanDistance( /** * @beta - * * Calculates the Euclidean distance between a vector expression and a double array. * * ```typescript @@ -6170,7 +5691,6 @@ export function euclideanDistance( /** * @beta - * * Calculates the Euclidean distance between two vector expressions. * * ```typescript @@ -6197,7 +5717,6 @@ export function euclideanDistance( /** * @beta - * * Creates an expression that calculates the length of a Firestore Vector. * * ```typescript @@ -6212,7 +5731,6 @@ export function vectorLength(vectorExpression: Expr): FunctionExpr; /** * @beta - * * Creates an expression that calculates the length of a Firestore Vector represented by a field. * * ```typescript @@ -6230,7 +5748,6 @@ export function vectorLength(expr: Expr | string): FunctionExpr { /** * @beta - * * Creates an expression that interprets an expression as the number of microseconds since the Unix epoch (1970-01-01 00:00:00 UTC) * and returns a timestamp. * @@ -6246,7 +5763,6 @@ export function unixMicrosToTimestamp(expr: Expr): FunctionExpr; /** * @beta - * * Creates an expression that interprets a field's value as the number of microseconds since the Unix epoch (1970-01-01 00:00:00 UTC) * and returns a timestamp. * @@ -6265,7 +5781,6 @@ export function unixMicrosToTimestamp(expr: Expr | string): FunctionExpr { /** * @beta - * * Creates an expression that converts a timestamp expression to the number of microseconds since the Unix epoch (1970-01-01 00:00:00 UTC). * * ```typescript @@ -6280,7 +5795,6 @@ export function timestampToUnixMicros(expr: Expr): FunctionExpr; /** * @beta - * * Creates an expression that converts a timestamp field to the number of microseconds since the Unix epoch (1970-01-01 00:00:00 UTC). * * ```typescript @@ -6298,7 +5812,6 @@ export function timestampToUnixMicros(expr: Expr | string): FunctionExpr { /** * @beta - * * Creates an expression that interprets an expression as the number of milliseconds since the Unix epoch (1970-01-01 00:00:00 UTC) * and returns a timestamp. * @@ -6314,7 +5827,6 @@ export function unixMillisToTimestamp(expr: Expr): FunctionExpr; /** * @beta - * * Creates an expression that interprets a field's value as the number of milliseconds since the Unix epoch (1970-01-01 00:00:00 UTC) * and returns a timestamp. * @@ -6334,7 +5846,6 @@ export function unixMillisToTimestamp(expr: Expr | string): FunctionExpr { /** * @beta - * * Creates an expression that converts a timestamp expression to the number of milliseconds since the Unix epoch (1970-01-01 00:00:00 UTC). * * ```typescript @@ -6349,7 +5860,6 @@ export function timestampToUnixMillis(expr: Expr): FunctionExpr; /** * @beta - * * Creates an expression that converts a timestamp field to the number of milliseconds since the Unix epoch (1970-01-01 00:00:00 UTC). * * ```typescript @@ -6368,7 +5878,6 @@ export function timestampToUnixMillis(expr: Expr | string): FunctionExpr { /** * @beta - * * Creates an expression that interprets an expression as the number of seconds since the Unix epoch (1970-01-01 00:00:00 UTC) * and returns a timestamp. * @@ -6384,7 +5893,6 @@ export function unixSecondsToTimestamp(expr: Expr): FunctionExpr; /** * @beta - * * Creates an expression that interprets a field's value as the number of seconds since the Unix epoch (1970-01-01 00:00:00 UTC) * and returns a timestamp. * @@ -6404,7 +5912,6 @@ export function unixSecondsToTimestamp(expr: Expr | string): FunctionExpr { /** * @beta - * * Creates an expression that converts a timestamp expression to the number of seconds since the Unix epoch (1970-01-01 00:00:00 UTC). * * ```typescript @@ -6419,7 +5926,6 @@ export function timestampToUnixSeconds(expr: Expr): FunctionExpr; /** * @beta - * * Creates an expression that converts a timestamp field to the number of seconds since the Unix epoch (1970-01-01 00:00:00 UTC). * * ```typescript @@ -6438,7 +5944,6 @@ export function timestampToUnixSeconds(expr: Expr | string): FunctionExpr { /** * @beta - * * Creates an expression that adds a specified amount of time to a timestamp. * * ```typescript @@ -6459,7 +5964,6 @@ export function timestampAdd( /** * @beta - * * Creates an expression that adds a specified amount of time to a timestamp. * * ```typescript @@ -6480,7 +5984,6 @@ export function timestampAdd( /** * @beta - * * Creates an expression that adds a specified amount of time to a timestamp represented by a field. * * ```typescript @@ -6518,7 +6021,6 @@ export function timestampAdd( /** * @beta - * * Creates an expression that subtracts a specified amount of time from a timestamp. * * ```typescript @@ -6539,7 +6041,6 @@ export function timestampSub( /** * @beta - * * Creates an expression that subtracts a specified amount of time from a timestamp. * * ```typescript @@ -6560,7 +6061,6 @@ export function timestampSub( /** * @beta - * * Creates an expression that subtracts a specified amount of time from a timestamp represented by a field. * * ```typescript @@ -6598,7 +6098,6 @@ export function timestampSub( /** * @beta - * * Creates an expression that performs a logical 'AND' operation on multiple filter conditions. * * ```typescript @@ -6622,7 +6121,6 @@ export function and( /** * @beta - * * Creates an expression that performs a logical 'OR' operation on multiple filter conditions. * * ```typescript @@ -6646,8 +6144,326 @@ export function or( /** * @beta + * Creates an expression that returns the value of the base expression raised to the power of the exponent expression. + * + * ```typescript + * // Raise the value of the 'base' field to the power of the 'exponent' field. + * pow(field("base"), field("exponent")); + * ``` + * + * @param base The expression to raise to the power of the exponent. + * @param exponent The expression to raise the base to the power of. + * @return A new `Expr` representing the power operation. + */ +export function pow(base: Expr, exponent: Expr): FunctionExpr; + +/** + * @beta + * Creates an expression that returns the value of the base expression raised to the power of the exponent. + * + * ```typescript + * // Raise the value of the 'base' field to the power of 2. + * pow(field("base"), 2); + * ``` + * + * @param base The expression to raise to the power of the exponent. + * @param exponent The constant value to raise the base to the power of. + * @return A new `Expr` representing the power operation. + */ +export function pow(base: Expr, exponent: number): FunctionExpr; + +/** + * @beta + * Creates an expression that returns the value of the base field raised to the power of the exponent expression. + * + * ```typescript + * // Raise the value of the 'base' field to the power of the 'exponent' field. + * pow("base", field("exponent")); + * ``` + * + * @param base The name of the field to raise to the power of the exponent. + * @param exponent The expression to raise the base to the power of. + * @return A new `Expr` representing the power operation. + */ +export function pow(base: string, exponent: Expr): FunctionExpr; + +/** + * @beta + * Creates an expression that returns the value of the base field raised to the power of the exponent. + * + * ```typescript + * // Raise the value of the 'base' field to the power of 2. + * pow("base", 2); + * ``` + * + * @param base The name of the field to raise to the power of the exponent. + * @param exponent The constant value to raise the base to the power of. + * @return A new `Expr` representing the power operation. + */ +export function pow(base: string, exponent: number): FunctionExpr; +export function pow( + base: Expr | string, + exponent: Expr | number +): FunctionExpr { + return fieldOrExpression(base).pow(exponent as number); +} + +/** + * @beta + * Creates an expression that rounds a numeric value to the nearest whole number. + * + * ```typescript + * // Round the value of the 'price' field. + * round("price"); + * ``` + * + * @param fieldName The name of the field to round. + * @return A new `Expr` representing the rounded value. + */ +export function round(fieldName: string): FunctionExpr; + +/** + * @beta + * Creates an expression that rounds a numeric value to the nearest whole number. + * + * ```typescript + * // Round the value of the 'price' field. + * round(field("price")); + * ``` + * + * @param expression An expression evaluating to a numeric value, which will be rounded. + * @return A new `Expr` representing the rounded value. + */ +export function round(expression: Expr): FunctionExpr; +export function round(expr: Expr | string): FunctionExpr { + return fieldOrExpression(expr).round(); +} + +/** + * @beta + * Creates an expression that returns the collection ID from a path. * - * Creates an {@link Ordering} that sorts documents in ascending order based on an expression. + * ```typescript + * // Get the collection ID from a path. + * collectionId("__name__"); + * ``` + * + * @param fieldName The name of the field to get the collection ID from. + * @return A new {@code Expr} representing the collectionId operation. + */ +export function collectionId(fieldName: string): FunctionExpr; + +/** + * @beta + * Creates an expression that returns the collection ID from a path. + * + * ```typescript + * // Get the collection ID from a path. + * collectionId(field("__name__")); + * ``` + * + * @param expression An expression evaluating to a path, which the collection ID will be extracted from. + * @return A new {@code Expr} representing the collectionId operation. + */ +export function collectionId(expression: Expr): FunctionExpr; +export function collectionId(expr: Expr | string): FunctionExpr { + return fieldOrExpression(expr).collectionId(); +} + +/** + * @beta + * Creates an expression that calculates the length of a string, array, map, vector, or bytes. + * + * ```typescript + * // Get the length of the 'name' field. + * length("name"); + * + * // Get the number of items in the 'cart' array. + * length("cart"); + * ``` + * + * @param fieldName The name of the field to calculate the length of. + * @return A new `Expr` representing the length of the string, array, map, vector, or bytes. + */ +export function length(fieldName: string): FunctionExpr; + +/** + * @beta + * Creates an expression that calculates the length of a string, array, map, vector, or bytes. + * + * ```typescript + * // Get the length of the 'name' field. + * length(field("name")); + * + * // Get the number of items in the 'cart' array. + * length(field("cart")); + * ``` + * + * @param expression An expression evaluating to a string, array, map, vector, or bytes, which the length will be calculated for. + * @return A new `Expr` representing the length of the string, array, map, vector, or bytes. + */ +export function length(expression: Expr): FunctionExpr; +export function length(expr: Expr | string): FunctionExpr { + return fieldOrExpression(expr).length(); +} + +/** + * @beta + * Creates an expression that computes the natural logarithm of a numeric value. + * + * ```typescript + * // Compute the natural logarithm of the 'value' field. + * ln("value"); + * ``` + * + * @param fieldName The name of the field to compute the natural logarithm of. + * @return A new `Expr` representing the natural logarithm of the numeric value. + */ +export function ln(fieldName: string): FunctionExpr; + +/** + * @beta + * Creates an expression that computes the natural logarithm of a numeric value. + * + * ```typescript + * // Compute the natural logarithm of the 'value' field. + * ln(field("value")); + * ``` + * + * @param expression An expression evaluating to a numeric value, which the natural logarithm will be computed for. + * @return A new `Expr` representing the natural logarithm of the numeric value. + */ +export function ln(expression: Expr): FunctionExpr; +export function ln(expr: Expr | string): FunctionExpr { + return fieldOrExpression(expr).ln(); +} + +/** + * @beta + * Creates an expression that computes the logarithm of an expression to a given base. + * + * ```typescript + * // Compute the logarithm of the 'value' field with base 10. + * log(field("value"), 10); + * ``` + * + * @param expression An expression evaluating to a numeric value, which the logarithm will be computed for. + * @param base The base of the logarithm. + * @return A new {@code Expr} representing the logarithm of the numeric value. + */ +export function log(expression: Expr, base: number): FunctionExpr; +/** + * @beta + * Creates an expression that computes the logarithm of an expression to a given base. + * + * ```typescript + * // Compute the logarithm of the 'value' field with the base in the 'base' field. + * log(field("value"), field("base")); + * ``` + * + * @param expression An expression evaluating to a numeric value, which the logarithm will be computed for. + * @param base The base of the logarithm. + * @return A new {@code Expr} representing the logarithm of the numeric value. + */ +export function log(expression: Expr, base: Expr): FunctionExpr; +/** + * @beta + * Creates an expression that computes the logarithm of a field to a given base. + * + * ```typescript + * // Compute the logarithm of the 'value' field with base 10. + * log("value", 10); + * ``` + * + * @param fieldName The name of the field to compute the logarithm of. + * @param base The base of the logarithm. + * @return A new {@code Expr} representing the logarithm of the numeric value. + */ +export function log(fieldName: string, base: number): FunctionExpr; +/** + * @beta + * Creates an expression that computes the logarithm of a field to a given base. + * + * ```typescript + * // Compute the logarithm of the 'value' field with the base in the 'base' field. + * log("value", field("base")); + * ``` + * + * @param fieldName The name of the field to compute the logarithm of. + * @param base The base of the logarithm. + * @return A new {@code Expr} representing the logarithm of the numeric value. + */ +export function log(fieldName: string, base: Expr): FunctionExpr; +export function log(expr: Expr | string, base: number | Expr): FunctionExpr { + return fieldOrExpression(expr).log(valueToDefaultExpr(base)); +} + +/** + * @beta + * Creates an expression that computes the square root of a numeric value. + * + * ```typescript + * // Compute the square root of the 'value' field. + * sqrt(field("value")); + * ``` + * + * @param expression An expression evaluating to a numeric value, which the square root will be computed for. + * @return A new {@code Expr} representing the square root of the numeric value. + */ +export function sqrt(expression: Expr): FunctionExpr; +/** + * @beta + * Creates an expression that computes the square root of a numeric value. + * + * ```typescript + * // Compute the square root of the 'value' field. + * sqrt("value"); + * ``` + * + * @param fieldName The name of the field to compute the square root of. + * @return A new {@code Expr} representing the square root of the numeric value. + */ +export function sqrt(fieldName: string): FunctionExpr; +export function sqrt(expr: Expr | string): FunctionExpr { + return fieldOrExpression(expr).sqrt(); +} + +/** + * @beta + * Creates an expression that reverses a string. + * + * ```typescript + * // Reverse the value of the 'myString' field. + * strReverse(field("myString")); + * ``` + * + * @param stringExpression An expression evaluating to a string value, which will be reversed. + * @return A new {@code Expr} representing the reversed string. + */ +export function strReverse(stringExpression: Expr): FunctionExpr; + +/** + * @beta + * Creates an expression that reverses a string value in the specified field. + * + * ```typescript + * // Reverse the value of the 'myString' field. + * strReverse("myString"); + * ``` + * + * @param field The name of the field representing the string to reverse. + * @return A new {@code Expr} representing the reversed string. + */ +export function strReverse(field: string): FunctionExpr; +export function strReverse(expr: Expr | string): FunctionExpr { + return fieldOrExpression(expr).strReverse(); +} + +// TODO(new-expression): Add new top-level expression function definitions above this line + +/** + * @beta + * Creates a {@link Field} instance representing the field at the given path. * * ```typescript * // Sort documents by the 'name' field in lowercase in ascending order @@ -6662,7 +6478,6 @@ export function ascending(expr: Expr): Ordering; /** * @beta - * * Creates an {@link Ordering} that sorts documents in ascending order based on a field. * * ```typescript @@ -6681,7 +6496,6 @@ export function ascending(field: Expr | string): Ordering { /** * @beta - * * Creates an {@link Ordering} that sorts documents in descending order based on an expression. * * ```typescript @@ -6697,7 +6511,6 @@ export function descending(expr: Expr): Ordering; /** * @beta - * * Creates an {@link Ordering} that sorts documents in descending order based on a field. * * ```typescript @@ -6716,7 +6529,6 @@ export function descending(field: Expr | string): Ordering { /** * @beta - * * Represents an ordering criterion for sorting documents in a Firestore pipeline. * * You create `Ordering` instances using the `ascending` and `descending` helper functions. @@ -6728,6 +6540,7 @@ export class Ordering implements HasUserData { ) {} /** + * @beta * @internal * @private * Indicates if this expression was created from a literal value passed @@ -6736,6 +6549,7 @@ export class Ordering implements HasUserData { _createdFromLiteral = false; /** + * @beta * @private * @internal */ @@ -6754,6 +6568,7 @@ export class Ordering implements HasUserData { _protoValueType: 'ProtoValue' = 'ProtoValue' as const; /** + * @beta * @private * @internal */ diff --git a/dev/src/pipelines/index.ts b/dev/src/pipelines/index.ts index fc7006e3c..23c7a5791 100644 --- a/dev/src/pipelines/index.ts +++ b/dev/src/pipelines/index.ts @@ -23,8 +23,12 @@ export { and, arrayContains, arrayContainsAny, + arrayReverse, avg, eq, + ceil, + exp, + floor, gt, like, lt, @@ -38,6 +42,7 @@ export { strConcat, subtract, cosineDistance, + countDistinct, dotProduct, euclideanDistance, mapGet, @@ -45,12 +50,11 @@ export { eqAny, map, array, - bitNot, field, xor, AggregateFunction, rand, - arrayOffset, + arrayGet, add, BooleanExpr, Expr, @@ -75,30 +79,23 @@ export { ifError, isError, isNan, - arrayConcat, - substr, + substring, documentId, isNull, arrayContainsAll, constant, - constantVector, Field, Constant, sum, maximum, descending, gte, - bitOr, - bitXor, - bitLeftShift, - bitRightShift, - bitAnd, multiply, cond, Ordering, - AggregateWithAlias, + AliasedAggregate, endsWith, - ExprWithAlias, + AliasedExpr, mapMerge, mapRemove, byteLength, @@ -106,8 +103,6 @@ export { logicalMinimum, notEqAny, countAll, - replaceAll, - replaceFirst, timestampAdd, timestampSub, timestampToUnixMicros, @@ -116,4 +111,13 @@ export { timestampToUnixMillis, unixSecondsToTimestamp, unixMillisToTimestamp, + pow, + collectionId, + length, + ln, + log, + round, + sqrt, + strReverse, + // TODO(new-expression): Add new expression exports above this line } from './expression'; diff --git a/dev/src/pipelines/pipeline-options.ts b/dev/src/pipelines/pipeline-options.ts deleted file mode 100644 index 3717a9dd3..000000000 --- a/dev/src/pipelines/pipeline-options.ts +++ /dev/null @@ -1,86 +0,0 @@ -// Copyright 2025 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. - -/** - * Options defining how a Pipeline is evaluated. - */ -export interface PipelineOptions { - /** - * Specify the index mode. - */ - indexMode?: 'recommended'; - - /** Options used to configure explain queries. */ - explainOptions?: { - /** - * The explain mode configures what explain data - * and query results are returned from the Pipeline query. - * - * `"execute"` - [DEFAULT] Execute the Pipeline and return results - * `"analyze"` - Plan the query and execute, returning both the planner - * information and the Pipeline query results. - */ - mode?: 'execute' | 'analyze'; - - /** - * Specifies the output format of the query planner information. - */ - outputFormat?: 'text' | 'json'; - }; - - /** - * An escape hatch to set options not known at SDK build time. These values - * will be passed directly to the Firestore backend and not used by the SDK. - * - * The option name will be used as provided. And must match the name - * format used by the backend (hint: use a snake_case_name). - * - * Custom option values can be any type supported - * by Firestore (for example: string, boolean, number, map, …). Value types - * not known to the SDK will be rejected. - * - * Values specified in customOptions will take precedence over any options - * with the same name set by the SDK. - * - * Override the `example_option`: - * ``` - * execute({ - * pipeline: myPipeline, - * customOptions: { - * // Override `example_option`. This will not - * // merge with the existing `example_option` object. - * "example_option": { - * foo: "bar" - * } - * } - * } - * ``` - * - * `customOptions` supports dot notation, if you want to override - * a nested option. - * ``` - * execute({ - * pipeline: myPipeline, - * customOptions: { - * // Override `example_option.foo` and do not override - * // any other properties of `example_option`. - * "example_option.foo": "bar" - * } - * } - * ``` - */ - customOptions?: { - [name: string]: unknown; - }; -} diff --git a/dev/src/pipelines/pipeline-util.ts b/dev/src/pipelines/pipeline-util.ts index c44d886bf..9e8dab455 100644 --- a/dev/src/pipelines/pipeline-util.ts +++ b/dev/src/pipelines/pipeline-util.ts @@ -22,6 +22,7 @@ import './expression'; import Firestore, { CollectionReference, DocumentReference, + FieldValue, Timestamp, VectorValue, } from '../index'; @@ -58,7 +59,6 @@ import { map, array, Constant, - constantVector, field, Ordering, gt, @@ -140,14 +140,23 @@ export class ExecutionUtil { return Date.now() - startTime >= totalTimeout; } - stream(pipeline: Pipeline): NodeJS.ReadableStream { - // TODO(pipeline) implement options for stream - const structuredPipeline = new StructuredPipeline(pipeline, {}, {}); - const responseStream = this._stream(structuredPipeline); + stream( + structuredPipeline: StructuredPipeline, + transactionOrReadTime?: Uint8Array | Timestamp | api.ITransactionOptions + ): NodeJS.ReadableStream { + const responseStream = this._stream( + structuredPipeline, + transactionOrReadTime + ); const transform = new Transform({ objectMode: true, - transform(chunk, encoding, callback) { - callback(undefined, chunk.result); + transform(chunk: Array, encoding, callback) { + chunk.forEach(item => { + if (item.result) { + this.push(item.result); + } + }); + callback(); }, }); @@ -183,9 +192,6 @@ export class ExecutionUtil { if (proto.executionTime) { output.executionTime = Timestamp.fromProto(proto.executionTime); } - if (proto.explainStats) { - console.log(proto.explainStats.data); - } callback(undefined, [output]); } else { let output: PipelineStreamElement[] = proto.results.map(result => { @@ -203,10 +209,19 @@ export class ExecutionUtil { QualifiedResourcePath.fromSlashSeparatedString(result.name) ) : undefined; + + if (!result.fields) { + logger( + '_stream', + null, + 'Unexpected state: `result.fields` was falsey. Using an empty map.' + ); + } + output.result = new PipelineResult( this._serializer, + result.fields || {}, ref, - result.fields || undefined, Timestamp.fromProto(proto.executionTime!), result.createTime ? Timestamp.fromProto(result.createTime!) @@ -573,10 +588,10 @@ export function isOrdering(val: unknown): val is firestore.Pipelines.Ordering { ); } -export function isAggregateWithAlias( +export function isAliasedAggregate( val: unknown -): val is firestore.Pipelines.AggregateWithAlias { - const candidate = val as firestore.Pipelines.AggregateWithAlias; +): val is firestore.Pipelines.AliasedAggregate { + const candidate = val as firestore.Pipelines.AliasedAggregate; return ( isString(candidate.alias) && candidate.aggregate instanceof AggregateFunction @@ -648,8 +663,12 @@ export function vectorToExpr( ): Expr { if (value instanceof Expr) { return value; - } else if (value instanceof VectorValue || Array.isArray(value)) { - const result = constantVector(value); + } else if (value instanceof VectorValue) { + const result = constant(value); + result._createdFromLiteral = true; + return result; + } else if (Array.isArray(value)) { + const result = constant(FieldValue.vector(value)); result._createdFromLiteral = true; return result; } else { diff --git a/dev/src/pipelines/pipelines.ts b/dev/src/pipelines/pipelines.ts index 8941071bc..f902a374b 100644 --- a/dev/src/pipelines/pipelines.ts +++ b/dev/src/pipelines/pipelines.ts @@ -25,7 +25,7 @@ import {validateFieldPath} from '../path'; import { ExecutionUtil, fieldOrExpression, - isAggregateWithAlias, + isAliasedAggregate, isBooleanExpr, isCollectionReference, isExpr, @@ -38,7 +38,6 @@ import { toField, vectorToExpr, } from './pipeline-util'; -import {PipelineOptions} from './pipeline-options'; import {DocumentReference} from '../reference/document-reference'; import {PipelineResponse} from '../reference/types'; import {HasUserData, hasUserData, Serializer} from '../serializer'; @@ -50,9 +49,9 @@ import {isOptionalEqual, isPlainObject} from '../util'; import { AggregateFunction, - AggregateWithAlias, + AliasedAggregate, Expr, - ExprWithAlias, + AliasedExpr, Field, BooleanExpr, Ordering, @@ -69,7 +68,7 @@ import { DocumentsSource, Where, FindNearest, - GenericStage, + RawStage, Limit, Offset, Select, @@ -105,20 +104,22 @@ import { Type as MessageType, ReflectionObject, } from 'protobufjs'; -import {logger} from '../logger'; /** + * @beta * Represents the source of a Firestore {@link Pipeline}. */ export class PipelineSource implements firestore.Pipelines.PipelineSource { constructor(private db: Firestore) {} /** + * @beta * Returns all documents from the entire collection. The collection can be nested. * @param collection - Name or reference to the collection that will be used as the Pipeline source. */ collection(collection: string | firestore.CollectionReference): Pipeline; /** + * @beta * Returns all documents from the entire collection. The collection can be nested. * @param options - Options defining how this CollectionStage is evaluated. */ @@ -159,12 +160,14 @@ export class PipelineSource implements firestore.Pipelines.PipelineSource { } /** + * @beta * Returns all documents from a collection ID regardless of the parent. * @param collectionId - ID of the collection group to use as the Pipeline source. */ collectionGroup(collectionId: string): Pipeline; /** + * @beta * Returns all documents from a collection ID regardless of the parent. * @param options - Options defining how this CollectionGroupStage is evaluated. */ @@ -185,10 +188,12 @@ export class PipelineSource implements firestore.Pipelines.PipelineSource { } /** + * @beta * Returns all documents from the entire database. */ database(): Pipeline; /** + * @beta * Returns all documents from the entire database. * @param options - Options defining how a DatabaseStage is evaluated. */ @@ -198,6 +203,7 @@ export class PipelineSource implements firestore.Pipelines.PipelineSource { } /** + * @beta * Set the pipeline's source to the documents specified by the given paths and DocumentReferences. * * @param docs An array of paths and DocumentReferences specifying the individual documents that will be the source of this pipeline. @@ -208,6 +214,7 @@ export class PipelineSource implements firestore.Pipelines.PipelineSource { documents(docs: Array): Pipeline; /** + * @beta * Set the pipeline's source to the documents specified by the given paths and DocumentReferences. * * @param options - Options defining how this DocumentsStage is evaluated. @@ -244,6 +251,7 @@ export class PipelineSource implements firestore.Pipelines.PipelineSource { } /** + * @beta * Convert the given Query into an equivalent Pipeline. * * @param query A Query to be converted into a Pipeline. @@ -286,6 +294,7 @@ export class PipelineSource implements firestore.Pipelines.PipelineSource { } /** + * @beta * The Pipeline class provides a flexible and expressive framework for building complex data * transformation and query pipelines for Firestore. * @@ -338,6 +347,7 @@ export class Pipeline implements firestore.Pipelines.Pipeline { } /** + * @beta * Adds new fields to outputs from previous stages. * * This stage allows you to compute values on-the-fly based on existing data from previous @@ -369,6 +379,7 @@ export class Pipeline implements firestore.Pipelines.Pipeline { ...additionalFields: firestore.Pipelines.Selectable[] ): Pipeline; /** + * @beta * Adds new fields to outputs from previous stages. * * This stage allows you to compute values on-the-fly based on existing data from previous @@ -419,6 +430,7 @@ export class Pipeline implements firestore.Pipelines.Pipeline { } /** + * @beta * Remove fields from outputs of previous stages. * * Example: @@ -441,6 +453,7 @@ export class Pipeline implements firestore.Pipelines.Pipeline { ...additionalFields: Array ): Pipeline; /** + * @beta * Remove fields from outputs of previous stages. * * Example: @@ -488,6 +501,7 @@ export class Pipeline implements firestore.Pipelines.Pipeline { } /** + * @beta * Selects or creates a set of fields from the outputs of previous stages. * *

The selected fields are defined using {@link Selectable} expressions, which can be: @@ -525,6 +539,7 @@ export class Pipeline implements firestore.Pipelines.Pipeline { ...additionalSelections: Array ): Pipeline; /** + * @beta * Selects or creates a set of fields from the outputs of previous stages. * *

The selected fields are defined using {@link Selectable} expressions, which can be: @@ -584,6 +599,7 @@ export class Pipeline implements firestore.Pipelines.Pipeline { } /** + * @beta * Filters the documents from previous stages to only include those matching the specified {@link * BooleanExpr}. * @@ -616,6 +632,7 @@ export class Pipeline implements firestore.Pipelines.Pipeline { */ where(condition: firestore.Pipelines.BooleanExpr): Pipeline; /** + * @beta * Filters the documents from previous stages to only include those matching the specified {@link * BooleanExpr}. * @@ -671,6 +688,7 @@ export class Pipeline implements firestore.Pipelines.Pipeline { } /** + * @beta * Skips the first `offset` number of documents from the results of previous stages. * *

This stage is useful for implementing pagination in your pipelines, allowing you to retrieve @@ -692,6 +710,7 @@ export class Pipeline implements firestore.Pipelines.Pipeline { */ offset(offset: number): Pipeline; /** + * @beta * Skips the first `offset` number of documents from the results of previous stages. * *

This stage is useful for implementing pagination in your pipelines, allowing you to retrieve @@ -729,6 +748,7 @@ export class Pipeline implements firestore.Pipelines.Pipeline { } /** + * @beta * Limits the maximum number of documents returned by previous stages to `limit`. * *

This stage is particularly useful when you want to retrieve a controlled subset of data from @@ -755,6 +775,7 @@ export class Pipeline implements firestore.Pipelines.Pipeline { */ limit(limit: number): Pipeline; /** + * @beta * Limits the maximum number of documents returned by previous stages to `limit`. * *

This stage is particularly useful when you want to retrieve a controlled subset of data from @@ -797,6 +818,7 @@ export class Pipeline implements firestore.Pipelines.Pipeline { } /** + * @beta * Returns a set of distinct values from the inputs to this stage. * * This stage runs through the results from previous stages to include only results with @@ -806,7 +828,7 @@ export class Pipeline implements firestore.Pipelines.Pipeline { * * - {@code string}: Name of an existing field * - {@link Field}: References an existing document field. - * - {@link ExprWithAlias}: Represents the result of a function with an assigned alias name + * - {@link AliasedExpr}: Represents the result of a function with an assigned alias name * using {@link Expr#as}. * * Example: @@ -829,6 +851,7 @@ export class Pipeline implements firestore.Pipelines.Pipeline { ...additionalGroups: Array ): Pipeline; /** + * @beta * Returns a set of distinct values from the inputs to this stage. * * This stage runs through the results from previous stages to include only results with @@ -838,7 +861,7 @@ export class Pipeline implements firestore.Pipelines.Pipeline { * * - {@code string}: Name of an existing field * - {@link Field}: References an existing document field. - * - {@link ExprWithAlias}: Represents the result of a function with an assigned alias name + * - {@link AliasedExpr}: Represents the result of a function with an assigned alias name * using {@link Expr#as}. * * Example: @@ -882,10 +905,11 @@ export class Pipeline implements firestore.Pipelines.Pipeline { } /** + * @beta * Performs aggregation operations on the documents from previous stages. * *

This stage allows you to calculate aggregate values over a set of documents. You define the - * aggregations to perform using {@link AggregateWithAlias} expressions which are typically results of + * aggregations to perform using {@link AliasedAggregate} expressions which are typically results of * calling {@link Expr#as} on {@link AggregateFunction} instances. * *

Example: @@ -899,17 +923,18 @@ export class Pipeline implements firestore.Pipelines.Pipeline { * ); * ``` * - * @param accumulator The first {@link AggregateWithAlias}, wrapping an {@link AggregateFunction} + * @param accumulator The first {@link AliasedAggregate}, wrapping an {@link AggregateFunction} * and providing a name for the accumulated results. - * @param additionalAccumulators Optional additional {@link AggregateWithAlias}, each wrapping an {@link AggregateFunction} + * @param additionalAccumulators Optional additional {@link AliasedAggregate}, each wrapping an {@link AggregateFunction} * and providing a name for the accumulated results. * @return A new Pipeline object with this stage appended to the stage list. */ aggregate( - accumulator: firestore.Pipelines.AggregateWithAlias, - ...additionalAccumulators: firestore.Pipelines.AggregateWithAlias[] + accumulator: firestore.Pipelines.AliasedAggregate, + ...additionalAccumulators: firestore.Pipelines.AliasedAggregate[] ): Pipeline; /** + * @beta * Performs optionally grouped aggregation operations on the documents from previous stages. * *

This stage allows you to calculate aggregate values over a set of documents, optionally @@ -921,7 +946,7 @@ export class Pipeline implements firestore.Pipelines.Pipeline { * If no grouping fields are provided, a single group containing all documents is used. Not * specifying groups is the same as putting the entire inputs into one group. *

  • **Accumulators:** One or more accumulation operations to perform within each group. These - * are defined using {@link AggregateWithAlias} expressions, which are typically created by + * are defined using {@link AliasedAggregate} expressions, which are typically created by * calling {@link Expr#as} on {@link AggregateFunction} instances. Each aggregation * calculates a value (e.g., sum, average, count) based on the documents within its group.
  • * @@ -944,22 +969,20 @@ export class Pipeline implements firestore.Pipelines.Pipeline { aggregate(options: firestore.Pipelines.AggregateStageOptions): Pipeline; aggregate( targetOrOptions: - | firestore.Pipelines.AggregateWithAlias + | firestore.Pipelines.AliasedAggregate | firestore.Pipelines.AggregateStageOptions, - ...rest: firestore.Pipelines.AggregateWithAlias[] + ...rest: firestore.Pipelines.AliasedAggregate[] ): Pipeline { - const options = isAggregateWithAlias(targetOrOptions) - ? {} - : targetOrOptions; + const options = isAliasedAggregate(targetOrOptions) ? {} : targetOrOptions; - const accumulators: Array = - isAggregateWithAlias(targetOrOptions) + const accumulators: Array = + isAliasedAggregate(targetOrOptions) ? [targetOrOptions, ...rest] : targetOrOptions.accumulators; const convertedAccumulators: Map = - aggregateWithAliasToMap(accumulators); + aliasedAggregateToMap(accumulators); const groups: Array = - isAggregateWithAlias(targetOrOptions) ? [] : targetOrOptions.groups ?? []; + isAliasedAggregate(targetOrOptions) ? [] : targetOrOptions.groups ?? []; const convertedGroups: Map = selectablesToMap(groups); this._validateUserData('aggregate', convertedGroups); @@ -973,6 +996,7 @@ export class Pipeline implements firestore.Pipelines.Pipeline { } /** + * @beta * Performs a vector proximity search on the documents from the previous stage, returning the * K-nearest documents based on the specified query `vectorValue` and `distanceMeasure`. The * returned documents will be sorted in order from nearest to furthest from the query `vectorValue`. @@ -1019,6 +1043,7 @@ export class Pipeline implements firestore.Pipelines.Pipeline { } /** + * @beta * Fully overwrites all fields in a document with those coming from a nested map. * *

    This stage allows you to emit a map value as a document. Each key of the map becomes a field @@ -1051,6 +1076,7 @@ export class Pipeline implements firestore.Pipelines.Pipeline { */ replaceWith(fieldName: string): Pipeline; /** + * @beta * Fully overwrites all fields in a document with those coming from a map. * *

    This stage allows you to emit a map value as a document. Each key of the map becomes a field @@ -1088,6 +1114,7 @@ export class Pipeline implements firestore.Pipelines.Pipeline { */ replaceWith(expr: firestore.Pipelines.Expr): Pipeline; /** + * @beta * Fully overwrites all fields in a document with those coming from a map. * *

    This stage allows you to emit a map value as a document. Each key of the map becomes a field @@ -1148,6 +1175,7 @@ export class Pipeline implements firestore.Pipelines.Pipeline { } /** + * @beta * Performs a pseudo-random sampling of the documents from the previous stage. * *

    This stage will filter documents pseudo-randomly. The parameter specifies how number of @@ -1167,6 +1195,7 @@ export class Pipeline implements firestore.Pipelines.Pipeline { sample(documents: number): Pipeline; /** + * @beta * Performs a pseudo-random sampling of the documents from the previous stage. * *

    This stage will filter documents pseudo-randomly. The 'options' parameter specifies how @@ -1214,6 +1243,7 @@ export class Pipeline implements firestore.Pipelines.Pipeline { } /** + * @beta * Performs union of all documents from two pipelines, including duplicates. * *

    This stage will pass through documents from previous stage, and also pass through documents @@ -1233,6 +1263,7 @@ export class Pipeline implements firestore.Pipelines.Pipeline { */ union(other: firestore.Pipelines.Pipeline): Pipeline; /** + * @beta * Performs union of all documents from two pipelines, including duplicates. * *

    This stage will pass through documents from previous stage, and also pass through documents @@ -1273,6 +1304,7 @@ export class Pipeline implements firestore.Pipelines.Pipeline { } /** + * @beta * Produces a document for each element in an input array. * * For each previous stage document, this stage will emit zero or more augmented documents. The @@ -1309,6 +1341,7 @@ export class Pipeline implements firestore.Pipelines.Pipeline { indexField?: string ): Pipeline; /** + * @beta * Produces a document for each element in an input array. * * For each previous stage document, this stage will emit zero or more augmented documents. The @@ -1375,6 +1408,7 @@ export class Pipeline implements firestore.Pipelines.Pipeline { } /** + * @beta * Sorts the documents from previous stages based on one or more {@link Ordering} criteria. * *

    This stage allows you to order the results of your pipeline. You can specify multiple {@link @@ -1404,6 +1438,7 @@ export class Pipeline implements firestore.Pipelines.Pipeline { ...additionalOrderings: firestore.Pipelines.Ordering[] ): Pipeline; /** + * @beta * Sorts the documents from previous stages based on one or more {@link Ordering} criteria. * *

    This stage allows you to order the results of your pipeline. You can specify multiple {@link @@ -1453,10 +1488,11 @@ export class Pipeline implements firestore.Pipelines.Pipeline { } /** - * Adds a generic stage to the pipeline. + * @beta + * Adds a raw stage to the pipeline. * *

    This method provides a flexible way to extend the pipeline's functionality by adding custom - * stages. Each generic stage is defined by a unique `name` and a set of `params` that control its + * stages. Each raw stage is defined by a unique `name` and a set of `params` that control its * behavior. * *

    Example (Assuming there is no 'where' stage available in SDK): @@ -1464,16 +1500,16 @@ export class Pipeline implements firestore.Pipelines.Pipeline { * ```typescript * // Assume we don't have a built-in 'where' stage * firestore.pipeline().collection('books') - * .genericStage('where', [field('published').lt(1900)]) // Custom 'where' stage + * .rawStage('where', [field('published').lt(1900)]) // Custom 'where' stage * .select('title', 'author'); * ``` * - * @param name - The unique name of the generic stage to add. - * @param params - A list of parameters to configure the generic stage's behavior. + * @param name - The unique name of the raw stage to add. + * @param params - A list of parameters to configure the raw stage's behavior. * @param options - An object of key value pairs that specifies optional parameters for the stage. * @return A new {@code Pipeline} object with this stage appended to the stage list. */ - genericStage( + rawStage( name: string, params: unknown[], options?: {[key: string]: Expr | unknown} @@ -1499,12 +1535,11 @@ export class Pipeline implements firestore.Pipelines.Pipeline { param._validateUserData(!!this.db._settings.ignoreUndefinedProperties); } }); - return this._addStage( - new GenericStage(name, expressionParams, options ?? {}) - ); + return this._addStage(new RawStage(name, expressionParams, options ?? {})); } /** + * @beta * Executes this pipeline and returns a Promise to represent the asynchronous operation. * *

    The returned Promise can be used to track the progress of the pipeline execution @@ -1533,11 +1568,13 @@ export class Pipeline implements firestore.Pipelines.Pipeline { * .execute(); * ``` * - * @param pipelineOptions - Optionally specify pipeline execution behavior. + * @param pipelineExecuteOptions - Optionally specify pipeline execution behavior. * @return A Promise representing the asynchronous pipeline execution. */ - execute(pipelineOptions?: PipelineOptions): Promise { - return this._execute(undefined, pipelineOptions).then(response => { + execute( + pipelineExecuteOptions?: firestore.Pipelines.PipelineExecuteOptions + ): Promise { + return this._execute(undefined, pipelineExecuteOptions).then(response => { const results = response.result || []; const executionTime = response.executionTime; const stats = response.explainStats; @@ -1548,18 +1585,22 @@ export class Pipeline implements firestore.Pipelines.Pipeline { _execute( transactionOrReadTime?: Uint8Array | Timestamp | api.ITransactionOptions, - pipelineOptions?: PipelineOptions + pipelineExecuteOptions?: firestore.Pipelines.PipelineExecuteOptions ): Promise { const util = new ExecutionUtil(this.db, this.db._serializer!); - const structuredPipeline = this._toStructuredPipeline(pipelineOptions); + const structuredPipeline = this._toStructuredPipeline( + pipelineExecuteOptions + ); return util ._getResponse(structuredPipeline, transactionOrReadTime) .then(result => result!); } - _toStructuredPipeline(pipelineOptions?: PipelineOptions): StructuredPipeline { - const structuredPipelineOptions = pipelineOptions ?? {}; - const optionsOverride = pipelineOptions?.customOptions ?? {}; + _toStructuredPipeline( + pipelineExecuteOptions?: firestore.Pipelines.PipelineExecuteOptions + ): StructuredPipeline { + const structuredPipelineOptions = pipelineExecuteOptions ?? {}; + const optionsOverride = pipelineExecuteOptions?.rawOptions ?? {}; return new StructuredPipeline( this, structuredPipelineOptions, @@ -1568,6 +1609,7 @@ export class Pipeline implements firestore.Pipelines.Pipeline { } /** + * @beta * Executes this pipeline and streams the results as {@link PipelineResult}s. * * @returns {Stream.} A stream of @@ -1585,7 +1627,9 @@ export class Pipeline implements firestore.Pipelines.Pipeline { */ stream(): NodeJS.ReadableStream { const util = new ExecutionUtil(this.db, this.db._serializer!); - return util.stream(this); + // TODO(pipelines) support options + const structuredPipeline = this._toStructuredPipeline(); + return util.stream(structuredPipeline, undefined); } _toProto(): api.IPipeline { @@ -1604,7 +1648,7 @@ export class Pipeline implements firestore.Pipelines.Pipeline { */ _validateUserData< T extends Map | HasUserData[] | HasUserData, - >(name: string, val: T): T { + >(_: string, val: T): T { const ignoreUndefinedProperties = !!this.db._settings.ignoreUndefinedProperties; if (hasUserData(val)) { @@ -1632,8 +1676,8 @@ function selectablesToMap( ); } else if (selectable instanceof Field) { result.set((selectable as Field).fieldName(), selectable); - } else if (selectable instanceof ExprWithAlias) { - const expr = selectable as ExprWithAlias; + } else if (selectable instanceof AliasedExpr) { + const expr = selectable as AliasedExpr; result.set(expr.alias, expr.expr as unknown as Expr); } else { throw new Error('unexpected selectable: ' + JSON.stringify(selectable)); @@ -1642,13 +1686,13 @@ function selectablesToMap( return result; } -function aggregateWithAliasToMap( - aggregateWithAliases: firestore.Pipelines.AggregateWithAlias[] +function aliasedAggregateToMap( + aliasedAggregatees: firestore.Pipelines.AliasedAggregate[] ): Map { - return aggregateWithAliases.reduce( + return aliasedAggregatees.reduce( ( map: Map, - selectable: firestore.Pipelines.AggregateWithAlias + selectable: firestore.Pipelines.AliasedAggregate ) => { map.set(selectable.alias, selectable.aggregate as AggregateFunction); return map; @@ -1658,6 +1702,7 @@ function aggregateWithAliasToMap( } /** + * @beta * A wrapper object to access explain stats if explain or analyze * was enabled for the Pipeline query execution. */ @@ -1729,29 +1774,7 @@ export class ExplainStats implements firestore.Pipelines.ExplainStats { } /** - * When explain stats were requested with `outputFormat = 'json'`, this returns - * the explain stats object parsed from the JSON string returned from the Firestore - * backend. - * - * If explain stats were not requested with `outputFormat = 'json'`, the behavior - * of this method is not guaranteed and is expected to throw. - */ - get json(): {[key: string]: firestore.Pipelines.ExplainStatsFieldValue} { - const value = this._decode(); - if (isString(value)) { - try { - return JSON.parse(value); - } catch (error: unknown) { - logger('json', null, 'Error parsing explain stats to JSON.', error); - } - } - - throw new Error( - "Unable to convert explain stats to an object, ensure you requested `explainOptions.outputFormat = 'json'`" - ); - } - - /** + * @beta * When explain stats were requested with `outputFormat = 'text'`, this returns * the explain stats string verbatium as returned from the Firestore backend. * @@ -1770,6 +1793,7 @@ export class ExplainStats implements firestore.Pipelines.ExplainStats { } /** + * @beta * Returns the explain stats in an encoded proto format, as returned from the Firestore backend. * The caller is responsible for unpacking this proto message. */ @@ -1782,6 +1806,7 @@ export class ExplainStats implements firestore.Pipelines.ExplainStats { } /** + * @beta * TODO(docs) */ export class PipelineSnapshot implements firestore.Pipelines.PipelineSnapshot { @@ -1803,6 +1828,7 @@ export class PipelineSnapshot implements firestore.Pipelines.PipelineSnapshot { } /** + * @beta * The Pipeline on which you called `execute()` in order to get this * `PipelineSnapshot`. */ @@ -1810,12 +1836,14 @@ export class PipelineSnapshot implements firestore.Pipelines.PipelineSnapshot { return this._pipeline; } - /** An array of all the results in the `PipelineSnapshot`. */ + /** + * @beta An array of all the results in the `PipelineSnapshot`. */ get results(): PipelineResult[] { return this._results; } /** + * @beta * The time at which the pipeline producing this result is executed. * * @type {Timestamp} @@ -1832,6 +1860,7 @@ export class PipelineSnapshot implements firestore.Pipelines.PipelineSnapshot { } /** + * @beta * Return stats from query explain. * * If `explainOptions.mode` was set to `execute` or left unset, then this returns `undefined`. @@ -1842,6 +1871,7 @@ export class PipelineSnapshot implements firestore.Pipelines.PipelineSnapshot { } /** + * @beta * A PipelineResult contains data read from a Firestore Pipeline. The data can be extracted with the * {@link #data()} or {@link #get(String)} methods. * @@ -1870,12 +1900,12 @@ export class PipelineResult implements firestore.Pipelines.PipelineResult { */ constructor( serializer: Serializer, - ref?: DocumentReference, /** * @internal * @private **/ - readonly _fieldsProto?: ApiMapValue, + readonly _fieldsProto: ApiMapValue, + ref?: DocumentReference, readTime?: Timestamp, createTime?: Timestamp, updateTime?: Timestamp @@ -1888,6 +1918,7 @@ export class PipelineResult implements firestore.Pipelines.PipelineResult { } /** + * @beta * The reference of the document, if it is a document; otherwise `undefined`. */ get ref(): DocumentReference | undefined { @@ -1895,6 +1926,7 @@ export class PipelineResult implements firestore.Pipelines.PipelineResult { } /** + * @beta * The ID of the document for which this PipelineResult contains data, if it is a document; otherwise `undefined`. * * @type {string} @@ -1906,6 +1938,7 @@ export class PipelineResult implements firestore.Pipelines.PipelineResult { } /** + * @beta * The time the document was created. Undefined if this result is not a document. * * @type {Timestamp|undefined} @@ -1916,6 +1949,7 @@ export class PipelineResult implements firestore.Pipelines.PipelineResult { } /** + * @beta * The time the document was last updated (at the time the snapshot was * generated). Undefined if this result is not a document. * @@ -1927,6 +1961,7 @@ export class PipelineResult implements firestore.Pipelines.PipelineResult { } /** + * @beta * The time at which the pipeline producing this result is executed. * * @type {Timestamp} @@ -1943,11 +1978,10 @@ export class PipelineResult implements firestore.Pipelines.PipelineResult { } /** - * Retrieves all fields in the result as an object. Returns 'undefined' if - * the document doesn't exist. + * @beta + * Retrieves all fields in the result as an object. * - * @returns {T|undefined} An object containing all fields in the document or - * 'undefined' if the document doesn't exist. + * @returns {T} An object containing all fields in the document. * * @example * ``` @@ -1959,13 +1993,9 @@ export class PipelineResult implements firestore.Pipelines.PipelineResult { * }); * ``` */ - data(): firestore.DocumentData | undefined { + data(): firestore.DocumentData { const fields = this._fieldsProto; - if (fields === undefined) { - return undefined; - } - const obj: firestore.DocumentData = {}; for (const prop of Object.keys(fields)) { obj[prop] = this._serializer.decodeValue(fields[prop]); @@ -1974,9 +2004,10 @@ export class PipelineResult implements firestore.Pipelines.PipelineResult { } /** + * @beta * Retrieves the field specified by `field`. * - * @param {string|FieldPath} field The field path + * @param {string|FieldPath} fieldPath The field path * (e.g. 'foo' or 'foo.bar') to a specific field. * @returns {*} The data at the specified field location or undefined if no * such field exists. @@ -1994,10 +2025,10 @@ export class PipelineResult implements firestore.Pipelines.PipelineResult { // We deliberately use `any` in the external API to not impose type-checking // on end users. // eslint-disable-next-line @typescript-eslint/no-explicit-any - get(field: string | FieldPath): any { - validateFieldPath('field', field); + get(fieldPath: string | FieldPath): any { + validateFieldPath('field', fieldPath); - const protoField = this.protoField(field); + const protoField = this.protoField(fieldPath); if (protoField === undefined) { return undefined; @@ -2038,6 +2069,7 @@ export class PipelineResult implements firestore.Pipelines.PipelineResult { } /** + * @beta * Returns true if the document's data and path in this `PipelineResult` is * equal to the provided value. * diff --git a/dev/src/pipelines/stage.ts b/dev/src/pipelines/stage.ts index 378cb7223..ff3588726 100644 --- a/dev/src/pipelines/stage.ts +++ b/dev/src/pipelines/stage.ts @@ -62,7 +62,7 @@ export class RemoveFields implements Stage { options: this.optionsUtil.getOptionsProto( serializer, this.options, - this.options.customOptions + this.options.rawOptions ), }; } @@ -94,7 +94,7 @@ export class Aggregate implements Stage { options: this.optionsUtil.getOptionsProto( serializer, this.options, - this.options.customOptions + this.options.rawOptions ), }; } @@ -108,7 +108,6 @@ export type InternalDistinctStageOptions = Omit< }; /** - * @beta */ export class Distinct implements Stage { name = 'distinct'; @@ -123,7 +122,7 @@ export class Distinct implements Stage { options: this.optionsUtil.getOptionsProto( serializer, this.options, - this.options.customOptions + this.options.rawOptions ), }; } @@ -137,7 +136,6 @@ export type InternalCollectionStageOptions = Omit< }; /** - * @beta */ export class CollectionSource implements Stage { name = 'collection'; @@ -163,7 +161,7 @@ export class CollectionSource implements Stage { options: this.optionsUtil.getOptionsProto( serializer, this.options, - this.options.customOptions + this.options.rawOptions ), }; } @@ -173,7 +171,6 @@ export type InternalCollectionGroupStageOptions = firestore.Pipelines.CollectionGroupStageOptions; /** - * @beta */ export class CollectionGroupSource implements Stage { name = 'collection_group'; @@ -195,7 +192,7 @@ export class CollectionGroupSource implements Stage { options: this.optionsUtil.getOptionsProto( serializer, this.options, - this.options.customOptions + this.options.rawOptions ), }; } @@ -205,7 +202,6 @@ export type InternalDatabaseStageOptions = firestore.Pipelines.DatabaseStageOptions; /** - * @beta */ export class DatabaseSource implements Stage { name = 'database'; @@ -219,7 +215,7 @@ export class DatabaseSource implements Stage { options: this.optionsUtil.getOptionsProto( serializer, this.options, - this.options.customOptions + this.options.rawOptions ), }; } @@ -233,7 +229,6 @@ export type InternalDocumentsStageOptions = Omit< }; /** - * @beta */ export class DocumentsSource implements Stage { name = 'documents'; @@ -251,7 +246,7 @@ export class DocumentsSource implements Stage { options: this.optionsUtil.getOptionsProto( serializer, this.options, - this.options.customOptions + this.options.rawOptions ), }; } @@ -265,7 +260,6 @@ export type InternalWhereStageOptions = Omit< }; /** - * @beta */ export class Where implements Stage { name = 'where'; @@ -280,7 +274,7 @@ export class Where implements Stage { options: this.optionsUtil.getOptionsProto( serializer, this.options, - this.options.customOptions + this.options.rawOptions ), }; } @@ -296,7 +290,6 @@ export type InternalFindNearestStageOptions = Omit< }; /** - * @beta */ export class FindNearest implements Stage { name = 'find_nearest'; @@ -322,7 +315,7 @@ export class FindNearest implements Stage { options: this.optionsUtil.getOptionsProto( serializer, this._options, - this._options.customOptions + this._options.rawOptions ), }; } @@ -337,7 +330,6 @@ export type InternalSampleStageOptions = Omit< }; /** - * @beta */ export class Sample implements Stage { name = 'sample'; @@ -355,7 +347,7 @@ export class Sample implements Stage { options: this.optionsUtil.getOptionsProto( serializer, this.options, - this.options.customOptions + this.options.rawOptions ), }; } @@ -364,7 +356,6 @@ export class Sample implements Stage { export type InternalUnionStageOptions = firestore.Pipelines.UnionStageOptions; /** - * @beta */ export class Union implements Stage { name = 'union'; @@ -379,7 +370,7 @@ export class Union implements Stage { options: this.optionsUtil.getOptionsProto( serializer, this.options, - this.options.customOptions + this.options.rawOptions ), }; } @@ -395,7 +386,6 @@ export type InternalUnnestStageOptions = Omit< }; /** - * @beta */ export class Unnest implements Stage { name = 'unnest'; @@ -417,7 +407,7 @@ export class Unnest implements Stage { options: this.optionsUtil.getOptionsProto( serializer, this.options, - this.options.customOptions + this.options.rawOptions ), }; } @@ -426,7 +416,6 @@ export class Unnest implements Stage { export type InternalLimitStageOptions = firestore.Pipelines.LimitStageOptions; /** - * @beta */ export class Limit implements Stage { name = 'limit'; @@ -441,7 +430,7 @@ export class Limit implements Stage { options: this.optionsUtil.getOptionsProto( serializer, this.options, - this.options.customOptions + this.options.rawOptions ), }; } @@ -450,7 +439,6 @@ export class Limit implements Stage { export type InternalOffsetStageOptions = firestore.Pipelines.OffsetStageOptions; /** - * @beta */ export class Offset implements Stage { name = 'offset'; @@ -465,7 +453,7 @@ export class Offset implements Stage { options: this.optionsUtil.getOptionsProto( serializer, this.options, - this.options.customOptions + this.options.rawOptions ), }; } @@ -479,7 +467,6 @@ export type InternalReplaceWithStageOptions = Omit< }; /** - * @beta */ export class ReplaceWith implements Stage { name = 'replace_with'; @@ -497,7 +484,7 @@ export class ReplaceWith implements Stage { options: this.optionsUtil.getOptionsProto( serializer, this.options, - this.options.customOptions + this.options.rawOptions ), }; } @@ -511,7 +498,6 @@ export type InternalSelectStageOptions = Omit< }; /** - * @beta */ export class Select implements Stage { name = 'select'; @@ -526,7 +512,7 @@ export class Select implements Stage { options: this.optionsUtil.getOptionsProto( serializer, this.options, - this.options.customOptions + this.options.rawOptions ), }; } @@ -555,7 +541,7 @@ export class AddFields implements Stage { options: this.optionsUtil.getOptionsProto( serializer, this.options, - this.options.customOptions + this.options.rawOptions ), }; } @@ -569,7 +555,6 @@ export type InternalSortStageOptions = Omit< }; /** - * @beta */ export class Sort implements Stage { name = 'sort'; @@ -584,16 +569,15 @@ export class Sort implements Stage { options: this.optionsUtil.getOptionsProto( serializer, this.options, - this.options.customOptions + this.options.rawOptions ), }; } } /** - * @beta */ -export class GenericStage implements Stage { +export class RawStage implements Stage { readonly optionsUtil = new OptionsUtil({}); /** diff --git a/dev/src/serializer.ts b/dev/src/serializer.ts index b92fadfcb..f6f12e25e 100644 --- a/dev/src/serializer.ts +++ b/dev/src/serializer.ts @@ -68,14 +68,14 @@ export interface Serializable { */ export class Serializer { private allowUndefined: boolean; - private createReference: (path: string) => DocumentReference; + private createDocumentReference: (path: string) => DocumentReference; private createInteger: (n: number | string) => number | BigInt; - constructor(firestore: Firestore) { + constructor(private firestore: Firestore) { // Instead of storing the `firestore` object, we store just a reference to // its `.doc()` method. This avoid a circular reference, which breaks // JSON.stringify(). - this.createReference = path => firestore.doc(path); + this.createDocumentReference = path => firestore.doc(path); this.createInteger = n => firestore._settings.useBigInt ? BigInt(n) : Number(n); this.allowUndefined = !!firestore._settings.ignoreUndefinedProperties; @@ -340,7 +340,13 @@ export class Serializer { const resourcePath = QualifiedResourcePath.fromSlashSeparatedString( proto.referenceValue! ); - return this.createReference(resourcePath.relativeName); + if (resourcePath.isDocument) { + return this.createDocumentReference(resourcePath.relativeName); + } else { + throw new Error( + `The SDK does not currently support decoding referenceValues for collections or partitions. Actual path value: '${proto.referenceValue!}'` + ); + } } case 'arrayValue': { const array: unknown[] = []; diff --git a/dev/system-test/pipeline.ts b/dev/system-test/pipeline.ts index d145e17ef..5c420266a 100644 --- a/dev/system-test/pipeline.ts +++ b/dev/system-test/pipeline.ts @@ -12,19 +12,24 @@ // See the License for the specific language governing permissions and // limitations under the License. -import {DocumentData, Pipelines} from '@google-cloud/firestore'; +import { + DocumentData, + DocumentReference, + Pipelines, +} from '@google-cloud/firestore'; import { BooleanExpr, - constantVector, map, array, - bitNot, field, + ceil, + floor, + exp, xor, AggregateFunction, rand, - arrayOffset, + arrayGet, timestampToUnixMicros, timestampToUnixSeconds, unixMicrosToTimestamp, @@ -32,7 +37,6 @@ import { timestampSub, timestampAdd, byteLength, - bitAnd, multiply, sum, maximum, @@ -58,25 +62,19 @@ import { ifError, isError, isNan, - arrayConcat, - substr, + substring, documentId, isNull, arrayContainsAll, - replaceFirst, - replaceAll, mapRemove, mapMerge, unixSecondsToTimestamp, unixMillisToTimestamp, - bitOr, - bitXor, - bitLeftShift, - bitRightShift, add, and, arrayContains, arrayContainsAny, + arrayReverse, avg, countAll, endsWith, @@ -107,6 +105,16 @@ import { PipelineResult, PipelineSnapshot, Pipeline, + countDistinct, + pow, + round, + collectionId, + length, + ln, + log, + sqrt, + strReverse, + // TODO(new-expression): add new expression imports above this line } from '../src/pipelines'; import { @@ -123,7 +131,7 @@ import {expect, use} from 'chai'; import * as chaiAsPromised from 'chai-as-promised'; import {afterEach, describe, it} from 'mocha'; -import {itIf, verifyInstance} from '../test/util/helpers'; +import {verifyInstance} from '../test/util/helpers'; import {getTestDb, getTestRoot} from './firestore'; import {Firestore as InternalFirestore} from '../src'; @@ -133,10 +141,9 @@ import * as google from '../protos/firestore_v1_proto_api'; use(chaiAsPromised); -const testUnsupportedFeatures: boolean | 'only' = false; const timestampDeltaMS = 3000; -describe.only('Pipeline class', () => { +describe('Pipeline class', () => { let firestore: Firestore; let randomCol: CollectionReference; let beginDocCreation = 0; @@ -448,47 +455,7 @@ describe.only('Pipeline class', () => { }); describe('pipeline explain', () => { - it('mode: analyze, format: text', async () => { - const ppl = firestore - .pipeline() - .collection(randomCol.path) - .sort(ascending('__name__')); - - const snapshot = await ppl.execute({ - explainOptions: { - mode: 'analyze', - outputFormat: 'text', - }, - }); - - expect(snapshot.explainStats).not.to.be.undefined; - expect(snapshot.explainStats!.text.length).to.be.greaterThan(0); - expect(snapshot.explainStats!.text.charAt(0)).not.to.equal('{'); - - expect(snapshot.explainStats!.rawData.type_url).to.equal( - 'type.googleapis.com/google.protobuf.StringValue' - ); - expect(snapshot.explainStats!.rawData.value).to.not.be.null; - expect(snapshot.explainStats!.rawData.value).to.not.be.undefined; - - expect(snapshot.results.length).to.equal(10); - expect(snapshot.pipeline).to.equal(ppl); - expectResults( - snapshot, - 'book1', - 'book10', - 'book2', - 'book3', - 'book4', - 'book5', - 'book6', - 'book7', - 'book8', - 'book9' - ); - }); - - it('mode: analyze, format: unspecified', async () => { + it('mode: analyze', async () => { const ppl = firestore .pipeline() .collection(randomCol.path) @@ -525,58 +492,13 @@ describe.only('Pipeline class', () => { ); }); - it('mode: analyze, format: json', async () => { - const ppl = firestore - .pipeline() - .collection(randomCol.path) - .sort(ascending('__name__')); - const snapshot = await ppl.execute({ - explainOptions: { - mode: 'analyze', - outputFormat: 'json', - }, - }); - expect(snapshot.explainStats).not.to.be.undefined; - expect(snapshot.explainStats!.text.length).to.be.greaterThan(0); - expect(snapshot.explainStats!.text.charAt(0)).to.equal('{'); - - expect(snapshot.explainStats!.rawData.type_url).to.equal( - 'type.googleapis.com/google.protobuf.StringValue' - ); - expect(snapshot.explainStats!.rawData.value).to.not.be.null; - expect(snapshot.explainStats!.rawData.value).to.not.be.undefined; - - expect(snapshot.explainStats!.json).not.to.be.null; - expect(typeof snapshot.explainStats!.json).to.be.equal('object'); - console.log(snapshot.explainStats!.json); - - expect(snapshot.results.length).to.equal(10); - expect(snapshot.pipeline).to.equal(ppl); - expectResults( - snapshot, - 'book1', - 'book10', - 'book2', - 'book3', - 'book4', - 'book5', - 'book6', - 'book7', - 'book8', - 'book9' - ); - }); - - it('mode: execute, format: text', async () => { + it('mode: unspecified', async () => { const ppl = firestore .pipeline() .collection(randomCol.path) .sort(ascending('__name__')); const snapshot = await ppl.execute({ - explainOptions: { - mode: 'execute', - outputFormat: 'text', - }, + explainOptions: {}, }); expect(snapshot.explainStats).to.be.undefined; @@ -597,14 +519,14 @@ describe.only('Pipeline class', () => { ); }); - it('mode: unspecified, format: text', async () => { + it('mode: undefined', async () => { const ppl = firestore .pipeline() .collection(randomCol.path) .sort(ascending('__name__')); const snapshot = await ppl.execute({ explainOptions: { - outputFormat: 'text', + mode: undefined, }, }); expect(snapshot.explainStats).to.be.undefined; @@ -670,30 +592,25 @@ describe.only('Pipeline class', () => { await db2.terminate(); }); - // Subcollections not currently supported in DBE - itIf(testUnsupportedFeatures)( - 'supports collection group as source', - async () => { - const randomSubCollectionId = Math.random().toString(16).slice(2); - const doc1 = await randomCol - .doc('book1') - .collection(randomSubCollectionId) - .add({order: 1}); - const doc2 = await randomCol - .doc('book2') - .collection(randomSubCollectionId) - .add({order: 2}); - const snapshot = await firestore - .pipeline() - .collectionGroup(randomSubCollectionId) - .sort(ascending('order')) - .execute(); - expectResults(snapshot, doc1.id, doc2.id); - } - ); + it('supports collection group as source', async () => { + const randomSubCollectionId = Math.random().toString(16).slice(2); + const doc1 = await randomCol + .doc('book1') + .collection(randomSubCollectionId) + .add({order: 1}); + const doc2 = await randomCol + .doc('book2') + .collection(randomSubCollectionId) + .add({order: 2}); + const snapshot = await firestore + .pipeline() + .collectionGroup(randomSubCollectionId) + .sort(ascending('order')) + .execute(); + expectResults(snapshot, doc1.id, doc2.id); + }); - // subcollections not currently supported in dbe - itIf(testUnsupportedFeatures)('supports database as source', async () => { + it('supports database as source', async () => { const randomId = Math.random().toString(16).slice(2); const doc1 = await randomCol.doc('book1').collection('sub').add({ order: 1, @@ -727,8 +644,7 @@ describe.only('Pipeline class', () => { constant(refDate).as('date'), constant(new Uint8Array([1, 2, 3, 4, 5, 6, 7, 0])).as('bytes'), constant(firestore.doc('foo/bar')).as('documentReference'), - constantVector(FieldValue.vector([1, 2, 3])).as('vectorValue'), - constantVector([1, 2, 3]).as('vectorValue2'), + constant(FieldValue.vector([1, 2, 3])).as('vectorValue'), map({ number: 1, string: 'a string', @@ -782,7 +698,6 @@ describe.only('Pipeline class', () => { bytes: new Uint8Array([1, 2, 3, 4, 5, 6, 7, 0]), documentReference: firestore.collection('foo').doc('bar'), vectorValue: FieldValue.vector([1, 2, 3]), - vectorValue2: FieldValue.vector([1, 2, 3]), map: { number: 1, string: 'a string', @@ -1119,6 +1034,15 @@ describe.only('Pipeline class', () => { .execute(); expectResults(snapshot, expectedResults); }); + + it('returns countDistinct accumulation', async () => { + const snapshot = await firestore + .pipeline() + .collection(randomCol.path) + .aggregate(countDistinct('genre').as('distinctGenres')) + .execute(); + expectResults(snapshot, {distinctGenres: 8}); + }); }); describe('distinct stage', () => { @@ -1620,7 +1544,7 @@ describe.only('Pipeline class', () => { await firestore .pipeline() .collection(randomCol.path) - .genericStage('select', [ + .rawStage('select', [ // incorrect parameter type field('title'), ]) @@ -1652,7 +1576,7 @@ describe.only('Pipeline class', () => { explainOptions: { mode: 'analyze', }, - customOptions: { + rawOptions: { memory_limit: 1, }, }); @@ -1684,12 +1608,12 @@ describe.only('Pipeline class', () => { }); }); - describe('generic stage', () => { + describe('raw stage', () => { it('can select fields', async () => { const snapshot = await firestore .pipeline() .collection(randomCol.path) - .genericStage('select', [ + .rawStage('select', [ { title: field('title'), metadata: { @@ -1715,7 +1639,7 @@ describe.only('Pipeline class', () => { .sort(field('author').ascending()) .limit(1) .select('title', 'author') - .genericStage('add_fields', [ + .rawStage('add_fields', [ { display: strConcat('title', ' - ', field('author')), }, @@ -1733,7 +1657,7 @@ describe.only('Pipeline class', () => { .pipeline() .collection(randomCol.path) .select('title', 'author') - .genericStage('where', [field('author').eq('Douglas Adams')]) + .rawStage('where', [field('author').eq('Douglas Adams')]) .execute(); expectResults(snapshot, { title: "The Hitchhiker's Guide to the Galaxy", @@ -1746,14 +1670,14 @@ describe.only('Pipeline class', () => { .pipeline() .collection(randomCol.path) .select('title', 'author') - .genericStage('sort', [ + .rawStage('sort', [ { direction: 'ascending', expression: field('author'), }, ]) - .genericStage('offset', [3]) - .genericStage('limit', [1]) + .rawStage('offset', [3]) + .rawStage('limit', [1]) .execute(); expectResults(snapshot, { author: 'Fyodor Dostoevsky', @@ -1766,10 +1690,7 @@ describe.only('Pipeline class', () => { .pipeline() .collection(randomCol.path) .select('title', 'author', 'rating') - .genericStage('aggregate', [ - {averageRating: field('rating').avg()}, - {}, - ]) + .rawStage('aggregate', [{averageRating: field('rating').avg()}, {}]) .execute(); expectResults(snapshot, { averageRating: 4.3100000000000005, @@ -1781,7 +1702,7 @@ describe.only('Pipeline class', () => { .pipeline() .collection(randomCol.path) .select('title', 'author', 'rating') - .genericStage('distinct', [{rating: field('rating')}]) + .rawStage('distinct', [{rating: field('rating')}]) .sort(field('rating').descending()) .execute(); expectResults( @@ -1814,7 +1735,7 @@ describe.only('Pipeline class', () => { const snapshot = await firestore .pipeline() .collection(randomCol) - .genericStage( + .rawStage( 'find_nearest', [ field('embedding'), @@ -2683,8 +2604,8 @@ describe.only('Pipeline class', () => { .select( isNull('rating').as('ratingIsNull'), isNan('rating').as('ratingIsNaN'), - isError(arrayOffset('title', 0)).as('isError'), - ifError(arrayOffset('title', 0), constant('was error')).as('ifError'), + isError(arrayGet('title', 0)).as('isError'), + ifError(arrayGet('title', 0), constant('was error')).as('ifError'), isAbsent('foo').as('isAbsent'), isNotNull('title').as('titleIsNotNull'), isNotNan('cost').as('costIsNotNan'), @@ -2712,8 +2633,8 @@ describe.only('Pipeline class', () => { .select( field('rating').isNull().as('ratingIsNull'), field('rating').isNan().as('ratingIsNaN'), - arrayOffset('title', 0).isError().as('isError'), - arrayOffset('title', 0).ifError(constant('was error')).as('ifError'), + arrayGet('title', 0).isError().as('isError'), + arrayGet('title', 0).ifError(constant('was error')).as('ifError'), field('foo').isAbsent().as('isAbsent'), field('title').isNotNull().as('titleIsNotNull'), field('cost').isNotNan().as('costIsNotNan') @@ -2754,19 +2675,19 @@ describe.only('Pipeline class', () => { }); it('testDistanceFunctions', async () => { - const sourceVector = [0.1, 0.1]; - const targetVector = [0.5, 0.8]; + const sourceVector = FieldValue.vector([0.1, 0.1]); + const targetVector = FieldValue.vector([0.5, 0.8]); let snapshot = await firestore .pipeline() .collection(randomCol.path) .select( - cosineDistance(constantVector(sourceVector), targetVector).as( + cosineDistance(constant(sourceVector), targetVector).as( 'cosineDistance' ), - dotProduct(constantVector(sourceVector), targetVector).as( + dotProduct(constant(sourceVector), targetVector).as( 'dotProductDistance' ), - euclideanDistance(constantVector(sourceVector), targetVector).as( + euclideanDistance(constant(sourceVector), targetVector).as( 'euclideanDistance' ) ) @@ -2783,13 +2704,13 @@ describe.only('Pipeline class', () => { .pipeline() .collection(randomCol.path) .select( - constantVector(sourceVector) + constant(sourceVector) .cosineDistance(targetVector) .as('cosineDistance'), - constantVector(sourceVector) + constant(sourceVector) .dotProduct(targetVector) .as('dotProductDistance'), - constantVector(sourceVector) + constant(sourceVector) .euclideanDistance(targetVector) .as('euclideanDistance') ) @@ -2808,7 +2729,11 @@ describe.only('Pipeline class', () => { .pipeline() .collection(randomCol.path) .limit(1) - .select(vectorLength(constantVector([1, 2, 3])).as('vectorLength')) + .select( + vectorLength(constant(FieldValue.vector([1, 2, 3]))).as( + 'vectorLength' + ) + ) .execute(); expectResults(snapshot, { vectorLength: 3, @@ -2948,28 +2873,6 @@ describe.only('Pipeline class', () => { }); }); - itIf(testUnsupportedFeatures)('testReplaceFirst', async () => { - const snapshot = await firestore - .pipeline() - .collection(randomCol.path) - .where(eq('title', 'The Lord of the Rings')) - .limit(1) - .select(replaceFirst('title', 'o', '0').as('newName')) - .execute(); - expectResults(snapshot, {newName: 'The L0rd of the Rings'}); - }); - - itIf(testUnsupportedFeatures)('testReplaceAll', async () => { - const snapshot = await firestore - .pipeline() - .collection(randomCol.path) - .where(eq('title', 'The Lord of the Rings')) - .limit(1) - .select(replaceAll('title', 'o', '0').as('newName')) - .execute(); - expectResults(snapshot, {newName: 'The L0rd 0f the Rings'}); - }); - it('supports Rand', async () => { const snapshot = await firestore .pipeline() @@ -3014,13 +2917,13 @@ describe.only('Pipeline class', () => { }); }); - it('supports arrayOffset', async () => { + it('supports arrayGet', async () => { let snapshot = await firestore .pipeline() .collection(randomCol.path) .sort(field('rating').descending()) .limit(3) - .select(arrayOffset('tags', 0).as('firstTag')) + .select(arrayGet('tags', 0).as('firstTag')) .execute(); const expectedResults = [ { @@ -3040,7 +2943,7 @@ describe.only('Pipeline class', () => { .collection(randomCol.path) .sort(field('rating').descending()) .limit(3) - .select(field('tags').arrayOffset(0).as('firstTag')) + .select(field('tags').arrayGet(0).as('firstTag')) .execute(); expectResults(snapshot, ...expectedResults); }); @@ -3236,309 +3139,604 @@ describe.only('Pipeline class', () => { falseField: false, }); }); - }); - describe('not yet implemented in backend', () => { - itIf(testUnsupportedFeatures)('supports Bit_and', async () => { + it('can reverse an array', async () => { const snapshot = await firestore .pipeline() .collection(randomCol.path) + .where(field('title').eq("The Hitchhiker's Guide to the Galaxy")) .limit(1) - .select(bitAnd(constant(5), 12).as('result')) + .select(field('tags').arrayReverse().as('reversedTags')) .execute(); expectResults(snapshot, { - result: 4, + reversedTags: ['adventure', 'space', 'comedy'], }); }); - itIf(testUnsupportedFeatures)('supports Bit_and', async () => { + it('can reverse an array with the top-level function', async () => { const snapshot = await firestore .pipeline() .collection(randomCol.path) + .where(field('title').eq("The Hitchhiker's Guide to the Galaxy")) .limit(1) - .select(constant(5).bitAnd(12).as('result')) + .select(arrayReverse('tags').as('reversedTags')) .execute(); expectResults(snapshot, { - result: 4, + reversedTags: ['adventure', 'space', 'comedy'], }); }); - itIf(testUnsupportedFeatures)('supports Bit_or', async () => { - let snapshot = await firestore + it('can compute the ceiling of a numeric value', async () => { + const snapshot = await firestore .pipeline() .collection(randomCol.path) + .where(field('title').eq("The Hitchhiker's Guide to the Galaxy")) .limit(1) - .select(bitOr(constant(5), 12).as('result')) + .select(field('rating').ceil().as('ceilingRating')) .execute(); expectResults(snapshot, { - result: 13, + ceilingRating: 5, }); - snapshot = await firestore + }); + + it('can compute the ceiling of a numeric value with the top-level function', async () => { + const snapshot = await firestore .pipeline() .collection(randomCol.path) + .where(field('title').eq("The Hitchhiker's Guide to the Galaxy")) .limit(1) - .select(constant(5).bitOr(12).as('result')) + .select(ceil('rating').as('ceilingRating')) .execute(); expectResults(snapshot, { - result: 13, + ceilingRating: 5, }); }); - itIf(testUnsupportedFeatures)('supports Bit_xor', async () => { - let snapshot = await firestore + it('can compute the floor of a numeric value', async () => { + const snapshot = await firestore .pipeline() .collection(randomCol.path) + .where(field('title').eq("The Hitchhiker's Guide to the Galaxy")) .limit(1) - .select(bitXor(constant(5), 12).as('result')) + .select(field('rating').floor().as('floorRating')) .execute(); expectResults(snapshot, { - result: 9, + floorRating: 4, }); - snapshot = await firestore + }); + + it('can compute the floor of a numeric value with the top-level function', async () => { + const snapshot = await firestore .pipeline() .collection(randomCol.path) + .where(field('title').eq("The Hitchhiker's Guide to the Galaxy")) .limit(1) - .select(constant(5).bitXor(12).as('result')) + .select(floor('rating').as('floorRating')) .execute(); expectResults(snapshot, { - result: 9, + floorRating: 4, }); }); - itIf(testUnsupportedFeatures)('supports Bit_not', async () => { - let snapshot = await firestore + it('can compute e to the power of a numeric value', async () => { + const snapshot = await firestore .pipeline() .collection(randomCol.path) + .where(field('title').eq('The Lord of the Rings')) .limit(1) - .select(bitNot(constant(Uint8Array.of(0xfd))).as('result')) + .select(field('rating').exp().as('expRating')) .execute(); expectResults(snapshot, { - result: Uint8Array.of(0x02), + expRating: 109.94717245212352, }); - snapshot = await firestore + }); + + it('can compute e to the power of a numeric value with the top-level function', async () => { + const snapshot = await firestore + .pipeline() + .collection(randomCol.path) + .where(field('title').eq('The Lord of the Rings')) + .limit(1) + .select(exp('rating').as('expRating')) + .execute(); + expect(snapshot.results[0].get('expRating')).to.be.approximately( + 109.94717245212351, + 0.000001 + ); + }); + + it('can compute the power of a numeric value', async () => { + const snapshot = await firestore + .pipeline() + .collection(randomCol.path) + .where(field('title').eq("The Hitchhiker's Guide to the Galaxy")) + .limit(1) + .select(field('rating').pow(2).as('powerRating')) + .execute(); + expect(snapshot.results[0].get('powerRating')).to.be.approximately( + 17.64, + 0.0001 + ); + }); + + it('can compute the power of a numeric value with the top-level function', async () => { + const snapshot = await firestore + .pipeline() + .collection(randomCol.path) + .where(field('title').eq("The Hitchhiker's Guide to the Galaxy")) + .limit(1) + .select(pow('rating', 2).as('powerRating')) + .execute(); + expect(snapshot.results[0].get('powerRating')).to.be.approximately( + 17.64, + 0.0001 + ); + }); + + it('can round a numeric value', async () => { + const snapshot = await firestore .pipeline() .collection(randomCol.path) + .where(field('title').eq("The Hitchhiker's Guide to the Galaxy")) .limit(1) - .select(constant(Uint8Array.of(0xfd)).bitNot().as('result')) + .select(field('rating').round().as('roundedRating')) .execute(); expectResults(snapshot, { - result: Uint8Array.of(0x02), + roundedRating: 4, }); }); - itIf(testUnsupportedFeatures)('supports Bit_left_shift', async () => { - let snapshot = await firestore + it('can round a numeric value with the top-level function', async () => { + const snapshot = await firestore .pipeline() .collection(randomCol.path) + .where(field('title').eq("The Hitchhiker's Guide to the Galaxy")) .limit(1) - .select(bitLeftShift(constant(Uint8Array.of(0x02)), 2).as('result')) + .select(round('rating').as('roundedRating')) .execute(); expectResults(snapshot, { - result: Uint8Array.of(0x04), + roundedRating: 4, }); - snapshot = await firestore + }); + + it('can round a numeric value away from zero for positive half-way values', async () => { + const snapshot = await firestore .pipeline() .collection(randomCol.path) + .where(field('title').eq("The Hitchhiker's Guide to the Galaxy")) .limit(1) - .select(constant(Uint8Array.of(0x02)).bitLeftShift(2).as('result')) + .addFields(constant(1.5).as('positiveHalf')) + .select(field('positiveHalf').round().as('roundedRating')) .execute(); expectResults(snapshot, { - result: Uint8Array.of(0x04), + roundedRating: 2, }); }); - itIf(testUnsupportedFeatures)('supports Bit_right_shift', async () => { - let snapshot = await firestore + it('can round a numeric value away from zero for negative half-way values', async () => { + const snapshot = await firestore .pipeline() .collection(randomCol.path) + .where(field('title').eq("The Hitchhiker's Guide to the Galaxy")) .limit(1) - .select(bitRightShift(constant(Uint8Array.of(0x02)), 2).as('result')) + .addFields(constant(-1.5).as('negativeHalf')) + .select(field('negativeHalf').round().as('roundedRating')) .execute(); expectResults(snapshot, { - result: Uint8Array.of(0x01), + roundedRating: -2, }); - snapshot = await firestore + }); + + it('can get the collectionId from a path', async () => { + const snapshot = await firestore .pipeline() .collection(randomCol.path) .limit(1) - .select(constant(Uint8Array.of(0x02)).bitRightShift(2).as('result')) + .select(field('__name__').collectionId().as('collectionId')) .execute(); expectResults(snapshot, { - result: Uint8Array.of(0x01), + collectionId: randomCol.id, }); }); - itIf(testUnsupportedFeatures)('supports Document_id', async () => { - let snapshot = await firestore + it('can get the collectionId from a path with the top-level function', async () => { + const snapshot = await firestore .pipeline() .collection(randomCol.path) - .sort(field('rating').descending()) .limit(1) - .select(documentId(field('__path__')).as('docId')) + .select(collectionId('__name__').as('collectionId')) .execute(); expectResults(snapshot, { - docId: 'book4', + collectionId: randomCol.id, }); - snapshot = await firestore + }); + + it('can compute the length of a string value', async () => { + const snapshot = await firestore .pipeline() .collection(randomCol.path) - .sort(field('rating').descending()) + .where(field('title').eq("The Hitchhiker's Guide to the Galaxy")) .limit(1) - .select(field('__path__').documentId().as('docId')) + .select(field('title').length().as('titleLength')) .execute(); expectResults(snapshot, { - docId: 'book4', + titleLength: 36, }); }); - itIf(testUnsupportedFeatures)('supports Substr', async () => { - let snapshot = await firestore + it('can compute the length of a string value with the top-level function', async () => { + const snapshot = await firestore .pipeline() .collection(randomCol.path) - .sort(field('rating').descending()) + .where(field('title').eq("The Hitchhiker's Guide to the Galaxy")) .limit(1) - .select(substr('title', 9, 2).as('of')) + .select(length('title').as('titleLength')) .execute(); expectResults(snapshot, { - of: 'of', + titleLength: 36, }); - snapshot = await firestore + }); + + it('can compute the length of an array value', async () => { + const snapshot = await firestore .pipeline() .collection(randomCol.path) - .sort(field('rating').descending()) + .where(field('title').eq("The Hitchhiker's Guide to the Galaxy")) .limit(1) - .select(field('title').substr(9, 2).as('of')) + .select(field('tags').length().as('tagsLength')) .execute(); expectResults(snapshot, { - of: 'of', + tagsLength: 3, }); }); - itIf(testUnsupportedFeatures)( - 'supports Substr without length', - async () => { - let snapshot = await firestore - .pipeline() - .collection(randomCol.path) - .sort(field('rating').descending()) - .limit(1) - .select(substr('title', 9).as('of')) - .execute(); - expectResults(snapshot, { - of: 'of the Rings', - }); - snapshot = await firestore - .pipeline() - .collection(randomCol.path) - .sort(field('rating').descending()) - .limit(1) - .select(field('title').substr(9).as('of')) - .execute(); - expectResults(snapshot, { - of: 'of the Rings', - }); - } - ); - - itIf(testUnsupportedFeatures)('arrayConcat works', async () => { + it('can compute the length of an array value with the top-level function', async () => { const snapshot = await firestore .pipeline() .collection(randomCol.path) - .select( - arrayConcat('tags', ['newTag1', 'newTag2'], field('tags'), [null]).as( - 'modifiedTags' - ) - ) + .where(field('title').eq("The Hitchhiker's Guide to the Galaxy")) .limit(1) + .select(length('tags').as('tagsLength')) .execute(); expectResults(snapshot, { - modifiedTags: [ - 'comedy', - 'space', - 'adventure', - 'newTag1', - 'newTag2', - 'comedy', - 'space', - 'adventure', - null, - ], + tagsLength: 3, }); }); - itIf(testUnsupportedFeatures)('testToLowercase', async () => { + it('can compute the length of a map value', async () => { const snapshot = await firestore .pipeline() .collection(randomCol.path) - .select(toLower('title').as('lowercaseTitle')) + .where(field('title').eq("The Hitchhiker's Guide to the Galaxy")) .limit(1) + .select(field('awards').length().as('awardsLength')) .execute(); expectResults(snapshot, { - lowercaseTitle: "the hitchhiker's guide to the galaxy", + awardsLength: 3, }); }); - itIf(testUnsupportedFeatures)('testToUppercase', async () => { + it('can compute the length of a vector value', async () => { const snapshot = await firestore .pipeline() .collection(randomCol.path) - .select(toUpper('author').as('uppercaseAuthor')) + .where(field('title').eq("The Hitchhiker's Guide to the Galaxy")) .limit(1) + .select(field('embedding').length().as('embeddingLength')) .execute(); - expectResults(snapshot, {uppercaseAuthor: 'DOUGLAS ADAMS'}); + expectResults(snapshot, { + embeddingLength: 10, + }); }); - itIf(testUnsupportedFeatures)('testTrim', async () => { + it('can compute the length of a bytes value', async () => { const snapshot = await firestore .pipeline() .collection(randomCol.path) - .addFields( - constant(" The Hitchhiker's Guide to the Galaxy ").as('spacedTitle') - ) - .select(trim('spacedTitle').as('trimmedTitle'), field('spacedTitle')) + .select(constant('12é').as('value')) .limit(1) + .select(field('value').byteLength().as('valueLength')) .execute(); expectResults(snapshot, { - spacedTitle: " The Hitchhiker's Guide to the Galaxy ", - trimmedTitle: "The Hitchhiker's Guide to the Galaxy", + valueLength: 4, }); }); - itIf(testUnsupportedFeatures)('test reverse', async () => { + it('can compute the natural logarithm of a numeric value', async () => { const snapshot = await firestore .pipeline() .collection(randomCol.path) - .where(eq('title', '1984')) + .where(field('title').eq("The Hitchhiker's Guide to the Galaxy")) .limit(1) - .select(reverse('title').as('reverseTitle')) + .select(field('rating').ln().as('lnRating')) .execute(); - expectResults(snapshot, {title: '4891'}); + expect(snapshot.results[0]!.data().lnRating).to.be.closeTo(1.435, 0.001); }); - }); - describe('pagination', () => { - /** - * Adds several books to the test collection. These - * additional books support pagination test scenarios - * that would otherwise not be possible with the original - * set of books. - * @param collectionReference - */ - async function addBooks( - collectionReference: CollectionReference - ): Promise { - await collectionReference.doc('book11').set({ - title: 'Jonathan Strange & Mr Norrell', - author: 'Susanna Clarke', - genre: 'Fantasy', - published: 2004, - rating: 4.6, - tags: ['historical fantasy', 'magic', 'alternate history', 'england'], - awards: {hugo: false, nebula: false}, + it('can compute the natural logarithm of a numeric value with the top-level function', async () => { + const snapshot = await firestore + .pipeline() + .collection(randomCol.path) + .where(field('title').eq("The Hitchhiker's Guide to the Galaxy")) + .limit(1) + .select(ln('rating').as('lnRating')) + .execute(); + expect(snapshot.results[0]!.data().lnRating).to.be.closeTo(1.435, 0.001); + }); + + it('can compute the natural logarithm of a numeric value with the top-level function', async () => { + const snapshot = await firestore + .pipeline() + .collection(randomCol.path) + .where(field('title').eq("The Hitchhiker's Guide to the Galaxy")) + .limit(1) + .select(ln('rating').as('lnRating')) + .execute(); + expectResults(snapshot, { + lnRating: 1.4350845252893227, }); - await collectionReference.doc('book12').set({ - title: 'The Master and Margarita', - author: 'Mikhail Bulgakov', + }); + + it('can compute the logarithm of a numeric value', async () => { + const snapshot = await firestore + .pipeline() + .collection(randomCol.path) + .where(field('title').eq("The Hitchhiker's Guide to the Galaxy")) + .limit(1) + .select(field('rating').log(10).as('logRating')) + .execute(); + expectResults(snapshot, { + logRating: 0.6232492903979004, + }); + }); + + it('can compute the logarithm of a numeric value with the top-level function', async () => { + const snapshot = await firestore + .pipeline() + .collection(randomCol.path) + .where(field('title').eq("The Hitchhiker's Guide to the Galaxy")) + .limit(1) + .select(log('rating', 10).as('logRating')) + .execute(); + expectResults(snapshot, { + logRating: 0.6232492903979004, + }); + }); + + it('can round a numeric value', async () => { + const snapshot = await firestore + .pipeline() + .collection(randomCol.path) + .where(field('title').eq("The Hitchhiker's Guide to the Galaxy")) + .limit(1) + .select(field('rating').round().as('roundedRating')) + .execute(); + expectResults(snapshot, { + roundedRating: 4, + }); + }); + + it('can round a numeric value with the top-level function', async () => { + const snapshot = await firestore + .pipeline() + .collection(randomCol.path) + .where(field('title').eq("The Hitchhiker's Guide to the Galaxy")) + .limit(1) + .select(round('rating').as('roundedRating')) + .execute(); + expectResults(snapshot, { + roundedRating: 4, + }); + }); + + it('can compute the square root of a numeric value', async () => { + const snapshot = await firestore + .pipeline() + .collection(randomCol.path) + .where(field('title').eq("The Hitchhiker's Guide to the Galaxy")) + .limit(1) + .select(field('rating').sqrt().as('sqrtRating')) + .execute(); + expectResults(snapshot, { + sqrtRating: 2.04939015319192, + }); + }); + + it('can compute the square root of a numeric value with the top-level function', async () => { + const snapshot = await firestore + .pipeline() + .collection(randomCol.path) + .where(field('title').eq("The Hitchhiker's Guide to the Galaxy")) + .limit(1) + .select(sqrt('rating').as('sqrtRating')) + .execute(); + expectResults(snapshot, { + sqrtRating: 2.04939015319192, + }); + }); + + it('can reverse a string', async () => { + const snapshot = await firestore + .pipeline() + .collection(randomCol.path) + .where(field('title').eq("The Hitchhiker's Guide to the Galaxy")) + .limit(1) + .select(field('title').strReverse().as('reversedTitle')) + .execute(); + expectResults(snapshot, { + reversedTitle: "yxalaG eht ot ediuG s'rekihhctiH ehT", + }); + }); + + it('can reverse a string with the top-level function', async () => { + const snapshot = await firestore + .pipeline() + .collection(randomCol.path) + .where(field('title').eq("The Hitchhiker's Guide to the Galaxy")) + .limit(1) + .select(strReverse('title').as('reversedTitle')) + .execute(); + expectResults(snapshot, { + reversedTitle: "yxalaG eht ot ediuG s'rekihhctiH ehT", + }); + }); + + it('supports Document_id', async () => { + let snapshot = await firestore + .pipeline() + .collection(randomCol.path) + .sort(field('rating').descending()) + .limit(1) + .select( + documentId(field('__name__')).as('docId'), + documentId(field('__path__')).as('noDocId') + ) + .execute(); + expectResults(snapshot, { + docId: 'book4', + noDocId: null, + }); + snapshot = await firestore + .pipeline() + .collection(randomCol.path) + .sort(field('rating').descending()) + .limit(1) + .select(field('__name__').documentId().as('docId')) + .execute(); + expectResults(snapshot, { + docId: 'book4', + }); + }); + + it('supports substring', async () => { + let snapshot = await firestore + .pipeline() + .collection(randomCol.path) + .sort(field('rating').descending()) + .limit(1) + .select(substring('title', 9, 2).as('of')) + .execute(); + expectResults(snapshot, { + of: 'of', + }); + snapshot = await firestore + .pipeline() + .collection(randomCol.path) + .sort(field('rating').descending()) + .limit(1) + .select(field('title').substring(9, 2).as('of')) + .execute(); + expectResults(snapshot, { + of: 'of', + }); + }); + + it('supports substring without length', async () => { + let snapshot = await firestore + .pipeline() + .collection(randomCol.path) + .sort(field('rating').descending()) + .limit(1) + .select(substring('title', 9).as('of')) + .execute(); + expectResults(snapshot, { + of: 'of the Rings', + }); + snapshot = await firestore + .pipeline() + .collection(randomCol.path) + .sort(field('rating').descending()) + .limit(1) + .select(field('title').substring(9).as('of')) + .execute(); + expectResults(snapshot, { + of: 'of the Rings', + }); + }); + + it('test toLower', async () => { + const snapshot = await firestore + .pipeline() + .collection(randomCol.path) + .sort(ascending('title')) + .select(toLower('author').as('lowercaseAuthor')) + .limit(1) + .execute(); + expectResults(snapshot, { + lowercaseAuthor: 'george orwell', + }); + }); + + it('test toUpper', async () => { + const snapshot = await firestore + .pipeline() + .collection(randomCol.path) + .sort(ascending('title')) + .select(toUpper('author').as('uppercaseAuthor')) + .limit(1) + .execute(); + expectResults(snapshot, {uppercaseAuthor: 'GEORGE ORWELL'}); + }); + + it('testTrim', async () => { + const snapshot = await firestore + .pipeline() + .collection(randomCol.path) + .addFields( + constant(" The Hitchhiker's Guide to the Galaxy ").as('spacedTitle') + ) + .select(trim('spacedTitle').as('trimmedTitle'), field('spacedTitle')) + .limit(1) + .execute(); + expectResults(snapshot, { + spacedTitle: " The Hitchhiker's Guide to the Galaxy ", + trimmedTitle: "The Hitchhiker's Guide to the Galaxy", + }); + }); + + it('test reverse', async () => { + const snapshot = await firestore + .pipeline() + .collection(randomCol.path) + .where(eq('title', '1984')) + .limit(1) + .select(reverse('title').as('reverseTitle')) + .execute(); + expectResults(snapshot, {reverseTitle: '4891'}); + }); + + // TODO(new-expression): Add new expression tests above this line + }); + + describe('pagination', () => { + let addedDocs: DocumentReference[] = []; + + /** + * Adds several books to the test collection. These + * additional books support pagination test scenarios + * that would otherwise not be possible with the original + * set of books. + * @param collectionReference + */ + async function addBooks( + collectionReference: CollectionReference + ): Promise { + let docRef = collectionReference.doc('book11'); + addedDocs.push(docRef); + await docRef.set({ + title: 'Jonathan Strange & Mr Norrell', + author: 'Susanna Clarke', + genre: 'Fantasy', + published: 2004, + rating: 4.6, + tags: ['historical fantasy', 'magic', 'alternate history', 'england'], + awards: {hugo: false, nebula: false}, + }); + docRef = collectionReference.doc('book12'); + addedDocs.push(collectionReference.doc('book12')); + await docRef.set({ + title: 'The Master and Margarita', + author: 'Mikhail Bulgakov', genre: 'Satire', published: 1967, // Though written much earlier rating: 4.6, @@ -3550,7 +3748,9 @@ describe.only('Pipeline class', () => { ], awards: {}, }); - await collectionReference.doc('book13').set({ + docRef = collectionReference.doc('book13'); + addedDocs.push(docRef); + await docRef.set({ title: 'A Long Way to a Small, Angry Planet', author: 'Becky Chambers', genre: 'Science Fiction', @@ -3561,111 +3761,113 @@ describe.only('Pipeline class', () => { }); } - // sort on __name__ is not working, see b/409358591 - itIf(testUnsupportedFeatures)( - 'supports pagination with filters', - async () => { - await addBooks(randomCol); - const pageSize = 2; - const pipeline = firestore - .pipeline() - .collection(randomCol.path) - .select('title', 'rating', '__name__') - .sort(field('rating').descending(), field('__name__').ascending()); + afterEach(async () => { + for (let i = 0; i < addedDocs.length; i++) { + await addedDocs[i].delete(); + } + addedDocs = []; + }); - let snapshot = await pipeline.limit(pageSize).execute(); - expectResults( - snapshot, - {title: 'The Lord of the Rings', rating: 4.7}, - {title: 'Jonathan Strange & Mr Norrell', rating: 4.6} - ); + it('supports pagination with filters', async () => { + await addBooks(randomCol); + const pageSize = 2; + const pipeline = firestore + .pipeline() + .collection(randomCol.path) + .select('title', 'rating', '__name__') + .sort(field('rating').descending(), field('__name__').ascending()); - const lastDoc = snapshot.results[snapshot.results.length - 1]; + let snapshot = await pipeline.limit(pageSize).execute(); - snapshot = await pipeline - .where( - or( - and( - field('rating').eq(lastDoc.get('rating')), - field('__path__').gt(lastDoc.ref?.id) - ), - field('rating').lt(lastDoc.get('rating')) - ) - ) - .limit(pageSize) - .execute(); - expectResults( - snapshot, - {title: 'Pride and Prejudice', rating: 4.5}, - {title: 'Crime and Punishment', rating: 4.3} - ); - } - ); + snapshot.results.forEach(r => console.log(JSON.stringify(r.data()))); - // sort on __name__ is not working, see b/409358591 - itIf(testUnsupportedFeatures)( - 'supports pagination with offsets', - async () => { - await addBooks(randomCol); + expectResults( + snapshot, + {title: 'The Lord of the Rings', rating: 4.7}, + {title: 'Dune', rating: 4.6} + ); - const secondFilterField = '__path__'; + const lastDoc = snapshot.results[snapshot.results.length - 1]; - const pipeline = firestore - .pipeline() - .collection(randomCol.path) - .select('title', 'rating', secondFilterField) - .sort( - field('rating').descending(), - field(secondFilterField).ascending() - ); + snapshot = await pipeline + .where( + or( + and( + field('rating').eq(lastDoc.get('rating')), + field('__name__').gt(lastDoc.ref) + ), + field('rating').lt(lastDoc.get('rating')) + ) + ) + .limit(pageSize) + .execute(); + expectResults( + snapshot, + {title: 'Jonathan Strange & Mr Norrell', rating: 4.6}, + {title: 'The Master and Margarita', rating: 4.6} + ); + }); - const pageSize = 2; - let currPage = 0; + it('supports pagination with offsets', async () => { + await addBooks(randomCol); - let snapshot = await pipeline - .offset(currPage++ * pageSize) - .limit(pageSize) - .execute(); + const secondFilterField = '__name__'; - expectResults( - snapshot, - { - title: 'The Lord of the Rings', - rating: 4.7, - }, - {title: 'Dune', rating: 4.6} + const pipeline = firestore + .pipeline() + .collection(randomCol.path) + .select('title', 'rating', secondFilterField) + .sort( + field('rating').descending(), + field(secondFilterField).ascending() ); - snapshot = await pipeline - .offset(currPage++ * pageSize) - .limit(pageSize) - .execute(); - expectResults( - snapshot, - { - title: 'Jonathan Strange & Mr Norrell', - rating: 4.6, - }, - {title: 'The Master and Margarita', rating: 4.6} - ); + const pageSize = 2; + let currPage = 0; - snapshot = await pipeline - .offset(currPage++ * pageSize) - .limit(pageSize) - .execute(); - expectResults( - snapshot, - { - title: 'A Long Way to a Small, Angry Planet', - rating: 4.6, - }, - { - title: 'Pride and Prejudice', - rating: 4.5, - } - ); - } - ); + let snapshot = await pipeline + .offset(currPage++ * pageSize) + .limit(pageSize) + .execute(); + + expectResults( + snapshot, + { + title: 'The Lord of the Rings', + rating: 4.7, + }, + {title: 'Dune', rating: 4.6} + ); + + snapshot = await pipeline + .offset(currPage++ * pageSize) + .limit(pageSize) + .execute(); + expectResults( + snapshot, + { + title: 'Jonathan Strange & Mr Norrell', + rating: 4.6, + }, + {title: 'The Master and Margarita', rating: 4.6} + ); + + snapshot = await pipeline + .offset(currPage++ * pageSize) + .limit(pageSize) + .execute(); + expectResults( + snapshot, + { + title: 'A Long Way to a Small, Angry Planet', + rating: 4.6, + }, + { + title: 'Pride and Prejudice', + rating: 4.5, + } + ); + }); }); describe('stage options', () => { @@ -3695,6 +3897,85 @@ describe.only('Pipeline class', () => { }); }); }); + + describe('stream', () => { + it('full results as expected', done => { + const ppl = firestore + .pipeline() + .collection(randomCol.path) + .sort(ascending('__name__')); + const snapshotStream = ppl.stream(); + + const expected = [ + 'book1', + 'book10', + 'book2', + 'book3', + 'book4', + 'book5', + 'book6', + 'book7', + 'book8', + 'book9', + ]; + + let received = 0; + snapshotStream + .on('data', d => { + expect(d).to.be.an.instanceOf(PipelineResult); + const rslt = d as PipelineResult; + expect(rslt.id).to.equal(expected.shift()); + ++received; + }) + .on('end', () => { + expect(received).to.equal(10); + done(); + }); + }); + + it('empty snapshot', done => { + const ppl = firestore.pipeline().collection(randomCol.path).limit(0); + const snapshotStream = ppl.stream(); + + let received = 0; + snapshotStream + .on('data', _ => { + ++received; + }) + .on('end', () => { + expect(received).to.equal(0); + done(); + }); + }); + + it('document transform', done => { + const ppl = firestore + .pipeline() + .collection(randomCol.path) + .sort(ascending('__name__')) + .limit(2) + .select('title'); + const snapshotStream = ppl.stream(); + + const expected = [ + {title: "The Hitchhiker's Guide to the Galaxy"}, + {title: 'Dune'}, + ]; + + let received = 0; + snapshotStream + .on('data', d => { + expect(d).to.be.an.instanceOf(PipelineResult); + const rslt = d as PipelineResult; + expect(rslt.data()).to.deep.equal(expected.shift()); + ++received; + }) + .on('end', () => { + expect(received).to.equal(2); + done(); + }); + }); + }); }); // This is the Query integration tests from the lite API (no cache support) @@ -4102,8 +4383,7 @@ describe('Query to Pipeline', () => { ); }); - // needs subcollection support - itIf(testUnsupportedFeatures)('supports collection groups', () => { + it('supports collection groups', () => { return testCollectionWithDocs({}, async (collRef, db) => { const collectionGroupId = `${collRef.id}group`; @@ -4123,27 +4403,23 @@ describe('Query to Pipeline', () => { }); }); - // needs subcollection support - itIf(testUnsupportedFeatures)( - 'supports query over collection path with special characters', - () => { - return testCollectionWithDocs({}, async (collRef, db) => { - const docWithSpecials = collRef.doc('so!@#$%^&*()_+special'); + it('supports query over collection path with special characters', () => { + return testCollectionWithDocs({}, async (collRef, db) => { + const docWithSpecials = collRef.doc('so!@#$%^&*()_+special'); - const collectionWithSpecials = docWithSpecials.collection( - 'so!@#$%^&*()_+special' - ); - await collectionWithSpecials.add({foo: 1}); - await collectionWithSpecials.add({foo: 2}); + const collectionWithSpecials = docWithSpecials.collection( + 'so!@#$%^&*()_+special' + ); + await collectionWithSpecials.add({foo: 1}); + await collectionWithSpecials.add({foo: 2}); - const snapshot = await execute( - db.pipeline().createFrom(collectionWithSpecials.orderBy('foo', 'asc')) - ); + const snapshot = await execute( + db.pipeline().createFrom(collectionWithSpecials.orderBy('foo', 'asc')) + ); - verifyResults(snapshot, {foo: 1}, {foo: 2}); - }); - } - ); + verifyResults(snapshot, {foo: 1}, {foo: 2}); + }); + }); it('supports multiple inequality on same field', () => { return testCollectionWithDocs( @@ -4356,7 +4632,7 @@ describe('Query to Pipeline', () => { ); }); - itIf(testUnsupportedFeatures)('supports not in', () => { + it('supports not in', () => { return testCollectionWithDocs( { 1: {foo: 1, bar: 2}, @@ -4364,7 +4640,9 @@ describe('Query to Pipeline', () => { 3: {foo: 3, bar: 10}, }, async (collRef, db) => { - const query1 = collRef.where('bar', 'not-in', [0, 10, 20]); + const query1 = collRef + .where('bar', 'not-in', [0, 10, 20]) + .orderBy('foo'); const snapshot = await execute(db.pipeline().createFrom(query1)); verifyResults(snapshot, {foo: 1, bar: 2}, {foo: 2, bar: 1}); } diff --git a/dev/test/path.ts b/dev/test/path.ts index aa7627dcb..6703cdc80 100644 --- a/dev/test/path.ts +++ b/dev/test/path.ts @@ -45,12 +45,46 @@ describe('ResourcePath', () => { }); it('parses strings', () => { + // parse reference to db root let path = QualifiedResourcePath.fromSlashSeparatedString(DATABASE_ROOT); expect(path.formattedName).to.equal(`${DATABASE_ROOT}/documents`); + expect(path.isCollection).to.equal(false); + expect(path.isDocument).to.equal(false); + + // parse reference to db root with `/documents` + path = QualifiedResourcePath.fromSlashSeparatedString( + `${DATABASE_ROOT}/documents` + ); + expect(path.formattedName).to.equal(`${DATABASE_ROOT}/documents`); + expect(path.isCollection).to.equal(false); + expect(path.isDocument).to.equal(false); + + // parse reference to collection path = QualifiedResourcePath.fromSlashSeparatedString( `${DATABASE_ROOT}/documents/foo` ); expect(path.formattedName).to.equal(`${DATABASE_ROOT}/documents/foo`); + expect(path.isCollection).to.equal(true); + expect(path.isDocument).to.equal(false); + + // parse reference to document + path = QualifiedResourcePath.fromSlashSeparatedString( + `${DATABASE_ROOT}/documents/foo/bar` + ); + expect(path.formattedName).to.equal(`${DATABASE_ROOT}/documents/foo/bar`); + expect(path.isCollection).to.equal(false); + expect(path.isDocument).to.equal(true); + + // parse reference to nested collection + path = QualifiedResourcePath.fromSlashSeparatedString( + `${DATABASE_ROOT}/documents/foo/bar/baz` + ); + expect(path.formattedName).to.equal( + `${DATABASE_ROOT}/documents/foo/bar/baz` + ); + expect(path.isCollection).to.equal(true); + expect(path.isDocument).to.equal(false); + expect(() => { path = QualifiedResourcePath.fromSlashSeparatedString( 'projects/project/databases' @@ -58,6 +92,26 @@ describe('ResourcePath', () => { }).to.throw("Resource name 'projects/project/databases' is not valid"); }); + it('does not parse invalid paths', () => { + const invalidPaths: string[] = [ + 'projects/PPP/databases/DDD/wrong', + 'projects/PPP/databases/DDD//', + 'projects/PPP/databases/DDD/documentsBAD', + 'projects/PPP/databases/DDD/documents//', + 'projects/PPP/databases/DDD/documents/ok//ok', + 'projects/PPP/databases//DDD/documents', + 'projects/PPP/databases/DDD/documents/', + 'projects/PPP/databases//documents', + 'projects//databases/DDD/documents', + ]; + + invalidPaths.forEach(invalidPath => { + expect(() => { + QualifiedResourcePath.fromSlashSeparatedString(invalidPath); + }).to.throw(`Resource name '${invalidPath}' is not valid`); + }); + }); + it('accepts newlines', () => { const path = QualifiedResourcePath.fromSlashSeparatedString( `${DATABASE_ROOT}/documents/foo\nbar` diff --git a/dev/test/pipelines/pipeline.ts b/dev/test/pipelines/pipeline.ts index a646fd0b5..69b9a3b84 100644 --- a/dev/test/pipelines/pipeline.ts +++ b/dev/test/pipelines/pipeline.ts @@ -31,7 +31,7 @@ import IValue = google.firestore.v1.IValue; const FIRST_CALL = 0; const EXECUTE_PIPELINE_REQUEST = 0; -describe('execute(Pipeline|PipelineOptions)', () => { +describe('execute(Pipeline|PipelineExecuteOptions)', () => { it('returns execution time with empty results', async () => { const executeTime = Timestamp.now(); const results: IExecutePipelineResponse[] = [ @@ -102,7 +102,6 @@ describe('execute(Pipeline|PipelineOptions)', () => { indexMode: 'recommended', explainOptions: { mode: 'analyze', - outputFormat: 'json', }, }); @@ -119,9 +118,6 @@ describe('execute(Pipeline|PipelineOptions)', () => { mode: { stringValue: 'analyze', }, - output_format: { - stringValue: 'json', - }, }, }, }, @@ -146,7 +142,7 @@ describe('execute(Pipeline|PipelineOptions)', () => { ); }); - it('serializes the pipeline generic options', async () => { + it('serializes the pipeline raw options', async () => { const spy = sinon.fake.returns(stream()); const firestore = await createInstance({ executePipeline: spy, @@ -156,7 +152,7 @@ describe('execute(Pipeline|PipelineOptions)', () => { .pipeline() .collection('foo') .execute({ - customOptions: { + rawOptions: { foo: 'bar', }, }); @@ -191,8 +187,8 @@ describe('execute(Pipeline|PipelineOptions)', () => { }); describe('stage option serialization', () => { - // Default custom options - const customOptions: Record = { + // Default rawOptions + const rawOptions: Record = { foo: 'bar1', }; // Default expected serialized options @@ -213,7 +209,7 @@ describe('stage option serialization', () => { pipeline: firestore => firestore.pipeline().collection({ collection: 'foo', - customOptions, + rawOptions, forceIndex: 'foo-index', }), expectedOptions: { @@ -228,7 +224,7 @@ describe('stage option serialization', () => { pipeline: firestore => firestore.pipeline().collectionGroup({ collectionId: 'foo', - customOptions, + rawOptions, forceIndex: 'bar-index', }), expectedOptions: { @@ -243,14 +239,14 @@ describe('stage option serialization', () => { pipeline: firestore => firestore.pipeline().documents({ docs: ['foo/bar'], - customOptions, + rawOptions, }), }, { name: 'database stage', pipeline: firestore => firestore.pipeline().database({ - customOptions, + rawOptions, }), }, { @@ -261,7 +257,7 @@ describe('stage option serialization', () => { .database() .distinct({ groups: ['foo'], - customOptions, + rawOptions, }), stageIndex: 1, }, @@ -275,7 +271,7 @@ describe('stage option serialization', () => { field: 'foo', vectorValue: [0], distanceMeasure: 'euclidean', - customOptions, + rawOptions, }), stageIndex: 1, }, @@ -287,7 +283,7 @@ describe('stage option serialization', () => { .database() .select({ selections: ['foo'], - customOptions, + rawOptions, }), stageIndex: 1, }, @@ -299,7 +295,7 @@ describe('stage option serialization', () => { .database() .unnest({ selectable: field('foo'), - customOptions, + rawOptions, }), stageIndex: 1, }, @@ -311,7 +307,7 @@ describe('stage option serialization', () => { .database() .addFields({ fields: [field('foo')], - customOptions, + rawOptions, }), stageIndex: 1, }, @@ -323,7 +319,7 @@ describe('stage option serialization', () => { .database() .aggregate({ accumulators: [sum('foo').as('fooSum')], - customOptions, + rawOptions, }), stageIndex: 1, }, @@ -332,7 +328,7 @@ describe('stage option serialization', () => { pipeline: firestore => firestore.pipeline().database().limit({ limit: 1, - customOptions, + rawOptions, }), stageIndex: 1, }, @@ -341,7 +337,7 @@ describe('stage option serialization', () => { pipeline: firestore => firestore.pipeline().database().offset({ offset: 1, - customOptions, + rawOptions, }), stageIndex: 1, }, @@ -353,7 +349,7 @@ describe('stage option serialization', () => { .database() .removeFields({ fields: ['foo'], - customOptions, + rawOptions, }), stageIndex: 1, }, @@ -362,7 +358,7 @@ describe('stage option serialization', () => { pipeline: firestore => firestore.pipeline().database().replaceWith({ map: 'foo', - customOptions, + rawOptions, }), stageIndex: 1, }, @@ -371,7 +367,7 @@ describe('stage option serialization', () => { pipeline: firestore => firestore.pipeline().database().sample({ documents: 100, - customOptions, + rawOptions, }), stageIndex: 1, }, @@ -383,7 +379,7 @@ describe('stage option serialization', () => { .database() .sort({ orderings: [descending('foo')], - customOptions, + rawOptions, }), stageIndex: 1, }, @@ -392,7 +388,7 @@ describe('stage option serialization', () => { pipeline: firestore => firestore.pipeline().database().union({ other: firestore.pipeline().database(), - customOptions, + rawOptions, }), stageIndex: 1, }, @@ -404,7 +400,7 @@ describe('stage option serialization', () => { .database() .where({ condition: field('foo').eq(1), - customOptions, + rawOptions, }), stageIndex: 1, }, diff --git a/dev/test/serializer.ts b/dev/test/serializer.ts index 14bf22825..5e85c7805 100644 --- a/dev/test/serializer.ts +++ b/dev/test/serializer.ts @@ -14,7 +14,10 @@ import {it} from 'mocha'; import {expect} from 'chai'; -import {validateUserInput} from '../src/serializer'; +import * as sinon from 'sinon'; +import {validateUserInput, Serializer} from '../src/serializer'; +import {DocumentReference, Firestore} from '../src'; +import {SinonStubbedInstance} from 'sinon'; describe('validateUserInput', () => { it('validates the depth of nested objects and arrays - 20', () => { @@ -244,3 +247,56 @@ describe('validateUserInput', () => { ).to.throw(/Input object is deeper than 20 levels/i); }); }); + +describe('serializer', () => { + const PROJECT_ID = 'test-project'; + const DATABASE_ROOT = `projects/${PROJECT_ID}/databases/(default)`; + + let serializer: Serializer | undefined; + let firestoreStub: SinonStubbedInstance | undefined; + + const mockResult = {}; + + beforeEach(() => { + firestoreStub = sinon.stub({ + doc: (_: string) => { + return mockResult; + }, + _settings: {}, + } as Firestore); + firestoreStub.doc.returns(mockResult as DocumentReference); + + serializer = new Serializer(firestoreStub); + }); + + describe('decodeValue', () => { + it('decodes reference to document', () => { + const result = serializer!.decodeValue({ + referenceValue: `${DATABASE_ROOT}/documents/foo/bar`, + }) as DocumentReference; + + expect(result).to.equal(mockResult); + expect(firestoreStub!.doc.calledOnceWith('foo/bar')).to.be.true; + }); + + it('throws when given a reference to collection', () => { + expect(() => { + serializer!.decodeValue({ + referenceValue: `${DATABASE_ROOT}/documents/foo`, + }) as DocumentReference; + }).to.throw( + 'The SDK does not currently support decoding referenceValues for collections or partitions.' + ); + }); + + it('throws when given a reference to db root', () => { + expect(() => { + serializer!.decodeValue({ + referenceValue: `${DATABASE_ROOT}/documents`, + }) as DocumentReference; + }).to.throw( + 'The SDK does not currently support decoding referenceValues for collections or partitions.' + ); + }); + }); +}); diff --git a/dev/test/watch.ts b/dev/test/watch.ts index 60583ed11..14ca07043 100644 --- a/dev/test/watch.ts +++ b/dev/test/watch.ts @@ -2425,7 +2425,7 @@ describe('DocumentReference watch', () => { streamHelper.write({ documentChange: { document: { - name: `projects/${PROJECT_ID}/databases/(default)/col/wrong`, + name: `projects/${PROJECT_ID}/databases/(default)/documents/col/wrong`, fields: {}, createTime: {seconds: 1, nanos: 2}, updateTime: {seconds: 3, nanos: 4}, diff --git a/package.json b/package.json index f327f91f3..064c9b5c1 100644 --- a/package.json +++ b/package.json @@ -71,11 +71,11 @@ "protobufjs": "^7.2.6" }, "devDependencies": { + "@google-cloud/cloud-rad": "^0.4.0", + "@google-cloud/opentelemetry-cloud-trace-exporter": "^2.0.0", "@google-cloud/promisify": "legacy-14", "@google-cloud/trace-agent": "^8.0.0", "@googleapis/cloudtrace": "^1.1.2", - "@google-cloud/cloud-rad": "^0.4.0", - "@google-cloud/opentelemetry-cloud-trace-exporter": "^2.0.0", "@opentelemetry/context-async-hooks": "^1.24.1", "@opentelemetry/sdk-trace-node": "^1.24.1", "@types/assert": "^1.4.0", @@ -96,7 +96,7 @@ "extend": "^3.0.2", "fs-extra": "10.1.0", "gapic-tools": "^0.4.0", - "gts": "^5.0.1", + "gts": "^5.3.1", "jsdoc": "^4.0.0", "jsdoc-fresh": "^3.0.0", "jsdoc-region-tag": "^3.0.0", @@ -104,11 +104,11 @@ "linkinator": "^3.0.0", "mkdirp": "^3.0.0", "mocha": "^9.2.2", + "nise": "6.0.0", + "path-to-regexp": "^6.0.0", "protobufjs-cli": "^1.1.2", "proxyquire": "^2.1.3", - "nise": "6.0.0", "sinon": "^18.0.0", - "path-to-regexp": "^6.0.0", "through2": "^4.0.0", "ts-node": "^10.0.0", "typescript": "^5.2.2" diff --git a/samples/pipelines-quickstart.js b/samples/pipelines-quickstart.js index 174a19a0c..aadec0992 100644 --- a/samples/pipelines-quickstart.js +++ b/samples/pipelines-quickstart.js @@ -14,6 +14,8 @@ 'use strict'; +/* eslint-disable n/no-missing-require */ + // [START firestore_pipelines_quickstart] const {Firestore} = require('@google-cloud/firestore'); const {field} = require('@google-cloud/firestore/pipelines'); diff --git a/types/firestore.d.ts b/types/firestore.d.ts index 9393f0181..b618c03a5 100644 --- a/types/firestore.d.ts +++ b/types/firestore.d.ts @@ -13,24 +13,21 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - // We deliberately use `any` in the external API to not impose type-checking // on end users. /* eslint-disable @typescript-eslint/no-explicit-any */ - // Declare a global (ambient) namespace // (used when not using import statement, but just script include). - declare namespace FirebaseFirestore { /** Alias for `any` but used where a Firestore field value would be provided. */ export type DocumentFieldValue = any; - /** * Document data (for use with `DocumentReference.set()`) consists of fields * mapped to values. */ - export type DocumentData = {[field: string]: DocumentFieldValue}; - + export type DocumentData = { + [field: string]: DocumentFieldValue; + }; /** * Similar to Typescript's `Partial`, but allows nested fields to be * omitted and FieldValues to be passed in as property values. @@ -40,9 +37,10 @@ declare namespace FirebaseFirestore { | (T extends Primitive ? T : T extends {} - ? {[K in keyof T]?: PartialWithFieldValue | FieldValue} + ? { + [K in keyof T]?: PartialWithFieldValue | FieldValue; + } : never); - /** * Allows FieldValues to be passed in as a property value while maintaining * type safety. @@ -52,9 +50,10 @@ declare namespace FirebaseFirestore { | (T extends Primitive ? T : T extends {} - ? {[K in keyof T]: WithFieldValue | FieldValue} + ? { + [K in keyof T]: WithFieldValue | FieldValue; + } : never); - /** * Update data (for use with [update]{@link DocumentReference#update}) * that contains paths mapped to values. Fields that contain dots reference @@ -72,12 +71,12 @@ declare namespace FirebaseFirestore { export type UpdateData = T extends Primitive ? T : T extends {} - ? {[K in keyof T]?: UpdateData | FieldValue} & NestedUpdateFields + ? { + [K in keyof T]?: UpdateData | FieldValue; + } & NestedUpdateFields : Partial; - /** Primitive types. */ export type Primitive = string | number | boolean | undefined | null; - /** * For each field (e.g. 'bar'), find all nested keys (e.g. {'bar.baz': T1, * 'bar.qux': T2}). Intersect them together to make a single map containing @@ -89,7 +88,6 @@ declare namespace FirebaseFirestore { [K in keyof T & string]: ChildUpdateFields; }[keyof T & string] // Also include the generated prefix-string keys. >; - /** * Helper for calculating the nested fields for a given type T1. This is needed * to distribute union types such as `undefined | {...}` (happens for optional @@ -103,12 +101,9 @@ declare namespace FirebaseFirestore { export type ChildUpdateFields = // Only allow nesting for map values V extends Record - ? // Recurse into the map and add the prefix in front of each key - // (e.g. Prefix 'bar.' to create: 'bar.baz' and 'bar.qux'. + ? // (e.g. Prefix 'bar.' to create: 'bar.baz' and 'bar.qux'. AddPrefixToKeys> - : // UpdateData is always a map of values. - never; - + : never; /** * Returns a new map where every key is prefixed with the outer key appended * to a dot. @@ -118,8 +113,9 @@ declare namespace FirebaseFirestore { T extends Record, > = // Remap K => Prefix.K. See https://www.typescriptlang.org/docs/handbook/2/mapped-types.html#key-remapping-via-as - {[K in keyof T & string as `${Prefix}.${K}`]+?: T[K]}; - + { + [K in keyof T & string as `${Prefix}.${K}`]+?: T[K]; + }; /** * Given a union type `U = T1 | T2 | ...`, returns an intersected type * `(T1 & T2 & ...)`. @@ -135,7 +131,6 @@ declare namespace FirebaseFirestore { ) extends (k: infer I) => void ? I : never; - /** * Utility type to create an type that only allows one * property of the Type param T to be set. @@ -146,9 +141,10 @@ declare namespace FirebaseFirestore { * let c = { a: "foo", y: "foo" } // Not OK */ export type OneOf = { - [K in keyof T]: Pick & {[P in Exclude]?: undefined}; + [K in keyof T]: Pick & { + [P in Exclude]?: undefined; + }; }[keyof T]; - /** * Sets or disables the log function for all active Firestore instances. * @@ -156,7 +152,6 @@ declare namespace FirebaseFirestore { * `null` to turn off logging. */ function setLogFunction(logger: ((msg: string) => void) | null): void; - /** * Converter used by `withConverter()` to transform user objects of type * `AppModelType` into Firestore data of type `DbModelType`. @@ -359,7 +354,6 @@ declare namespace FirebaseFirestore { toFirestore( modelObject: WithFieldValue ): WithFieldValue; - /** * Called by the Firestore SDK to convert a custom model object of type * `AppModelType` into a plain Javascript object (suitable for writing @@ -377,7 +371,6 @@ declare namespace FirebaseFirestore { modelObject: PartialWithFieldValue, options: SetOptions ): PartialWithFieldValue; - /** * Called by the Firestore SDK to convert Firestore data into an object of * type `AppModelType`. You can access your data by calling: @@ -393,7 +386,6 @@ declare namespace FirebaseFirestore { */ fromFirestore(snapshot: QueryDocumentSnapshot): AppModelType; } - /** * Settings used to directly configure a `Firestore` instance. */ @@ -406,18 +398,14 @@ declare namespace FirebaseFirestore { * Default Credentials} */ projectId?: string; - /** * The database name. If omitted, the default database will be used. */ databaseId?: string; - /** The hostname to connect to. */ host?: string; - /** The port to connect to. */ port?: number; - /** * Local file containing the Service Account credentials as downloaded from * the Google Developers Console. Can be omitted in environments that @@ -427,7 +415,6 @@ declare namespace FirebaseFirestore { * `private_key` of your service account. */ keyFilename?: string; - /** * The 'client_email' and 'private_key' properties of the service account * to use with your Firestore project. Can be omitted in environments that @@ -435,11 +422,12 @@ declare namespace FirebaseFirestore { * Default Credentials}. If your credentials are stored in a JSON file, you * can specify a `keyFilename` instead. */ - credentials?: {client_email?: string; private_key?: string}; - + credentials?: { + client_email?: string; + private_key?: string; + }; /** Whether to use SSL when connecting. */ ssl?: boolean; - /** * The maximum number of idle GRPC channels to keep. A smaller number of idle * channels reduces memory usage but increases request latency for clients @@ -447,7 +435,6 @@ declare namespace FirebaseFirestore { * when the client becomes idle. Defaults to 1. */ maxIdleChannels?: number; - /** * Whether to use `BigInt` for integer types when deserializing Firestore * Documents. Regardless of magnitude, all integer values are returned as @@ -455,7 +442,6 @@ declare namespace FirebaseFirestore { * numbers continue to use JavaScript's `number` type. */ useBigInt?: boolean; - /** * Whether to skip nested properties that are set to `undefined` during * object serialization. If set to `true`, these properties are skipped @@ -463,7 +449,6 @@ declare namespace FirebaseFirestore { * an exception when it encounters properties of type `undefined`. */ ignoreUndefinedProperties?: boolean; - /** * Whether to force the use of HTTP/1.1 REST transport until a method that requires gRPC * is called. When a method requires gRPC, this Firestore client will load dependent gRPC @@ -473,16 +458,13 @@ declare namespace FirebaseFirestore { * or `Query.onSnapshot()`. */ preferRest?: boolean; - /** * Settings related to telemetry collection by this client. * @beta */ openTelemetry?: FirestoreOpenTelemetryOptions; - [key: string]: any; // Accept other properties, such as GRPC settings. } - /** * Options to configure telemetry collection. * This is a 'beta' interface and may change in backwards incompatible ways. @@ -499,7 +481,6 @@ declare namespace FirebaseFirestore { */ tracerProvider?: any; } - /** Options to configure a read-only transaction. */ export interface ReadOnlyTransactionOptions { /** Set to true to indicate a read-only transaction. */ @@ -511,7 +492,6 @@ declare namespace FirebaseFirestore { */ readTime?: Timestamp; } - /** Options to configure a read-write transaction. */ export interface ReadWriteTransactionOptions { /** Set to false or omit to indicate a read-write transaction. */ @@ -521,7 +501,6 @@ declare namespace FirebaseFirestore { */ maxAttempts?: number; } - /** * `Firestore` represents a Firestore Database and is the entry point for all * Firestore operations. @@ -532,7 +511,6 @@ declare namespace FirebaseFirestore { * {@link https://firebase.google.com/docs/firestore/} */ public constructor(settings?: Settings); - /** * Specifies custom settings to be used to configure the `Firestore` * instance. Can only be invoked once and before any other Firestore @@ -546,12 +524,10 @@ declare namespace FirebaseFirestore { * operations. */ settings(settings: Settings): void; - /** * Returns the Database ID for this Firestore instance. */ get databaseId(): string; - /** * Gets a `CollectionReference` instance that refers to the collection at * the specified path. @@ -560,7 +536,6 @@ declare namespace FirebaseFirestore { * @return The `CollectionReference` instance. */ collection(collectionPath: string): CollectionReference; - /** * Gets a `DocumentReference` instance that refers to the document at the * specified path. @@ -569,7 +544,6 @@ declare namespace FirebaseFirestore { * @return The `DocumentReference` instance. */ doc(documentPath: string): DocumentReference; - /** * Creates and returns a new Query that includes all documents in the * database that are contained in a collection or subcollection with the @@ -581,7 +555,6 @@ declare namespace FirebaseFirestore { * @return The created `CollectionGroup`. */ collectionGroup(collectionId: string): CollectionGroup; - /** * Retrieves multiple documents from Firestore. * @@ -598,7 +571,6 @@ declare namespace FirebaseFirestore { getAll( ...documentRefsOrReadOptions: Array ): Promise>; - /** * Recursively deletes all documents and subcollections at and under the * specified level. @@ -638,14 +610,12 @@ declare namespace FirebaseFirestore { ref: CollectionReference | DocumentReference, bulkWriter?: BulkWriter ): Promise; - /** * Terminates the Firestore client and closes all open streams. * * @return A Promise that resolves when the client is terminated. */ terminate(): Promise; - /** * Fetches the root collections that are associated with this Firestore * database. @@ -653,7 +623,6 @@ declare namespace FirebaseFirestore { * @returns A Promise that resolves with an array of CollectionReferences. */ listCollections(): Promise>; - /** * Executes the given updateFunction and commits the changes applied within * the transaction. @@ -698,13 +667,11 @@ declare namespace FirebaseFirestore { | ReadWriteTransactionOptions | ReadOnlyTransactionOptions ): Promise; - /** * Creates a write batch, used for performing multiple writes as a single * atomic operation. */ batch(): WriteBatch; - /** * Creates a [BulkWriter]{@link BulkWriter}, used for performing * multiple writes in parallel. Gradually ramps up writes as specified @@ -716,7 +683,6 @@ declare namespace FirebaseFirestore { * behavior for the underlying BulkWriter. */ bulkWriter(options?: BulkWriterOptions): BulkWriter; - /** * Creates a new `BundleBuilder` instance to package selected Firestore data into * a bundle. @@ -737,13 +703,11 @@ declare namespace FirebaseFirestore { * // Save `bundleBuffer` to CDN or stream it to clients. */ bundle(bundleId?: string): BundleBuilder; - /** * TODO(pipelines) */ pipeline(): Pipelines.PipelineSource; } - /** * An immutable object representing a geo point in Firestore. The geo point * is represented as latitude/longitude pair. @@ -759,10 +723,8 @@ declare namespace FirebaseFirestore { * @param longitude The longitude as number between -180 and 180. */ constructor(latitude: number, longitude: number); - readonly latitude: number; readonly longitude: number; - /** * Returns true if this `GeoPoint` is equal to the provided one. * @@ -771,7 +733,6 @@ declare namespace FirebaseFirestore { */ isEqual(other: GeoPoint): boolean; } - /** * A reference to a transaction. * The `Transaction` object passed to a transaction's updateFunction provides @@ -780,7 +741,6 @@ declare namespace FirebaseFirestore { */ export class Transaction { private constructor(); - /** * Retrieves a query result. Holds a pessimistic lock on all returned * documents. @@ -791,7 +751,6 @@ declare namespace FirebaseFirestore { get( query: Query ): Promise>; - /** * Reads the document referenced by the provided `DocumentReference.` * Holds a pessimistic lock on the returned document. @@ -802,7 +761,6 @@ declare namespace FirebaseFirestore { get( documentRef: DocumentReference ): Promise>; - /** * Retrieves an aggregate query result. Holds a pessimistic lock on all * documents that were matched by the underlying query. @@ -823,7 +781,6 @@ declare namespace FirebaseFirestore { ): Promise< AggregateQuerySnapshot >; - /** * Retrieves multiple documents from Firestore. Holds a pessimistic lock on * all returned documents. @@ -843,7 +800,6 @@ declare namespace FirebaseFirestore { DocumentReference | ReadOptions > ): Promise>>; - /** * Create the document referred to by the provided `DocumentReference`. * The operation will fail the transaction if a document exists at the @@ -858,7 +814,6 @@ declare namespace FirebaseFirestore { documentRef: DocumentReference, data: WithFieldValue ): Transaction; - /** * Writes to the document referred to by the provided `DocumentReference`. * If the document does not exist yet, it will be created. If you pass @@ -887,7 +842,6 @@ declare namespace FirebaseFirestore { documentRef: DocumentReference, data: WithFieldValue ): Transaction; - /** * Updates fields in the document referred to by the provided * `DocumentReference`. The update will fail if applied to a document that @@ -908,7 +862,6 @@ declare namespace FirebaseFirestore { data: UpdateData, precondition?: Precondition ): Transaction; - /** * Updates fields in the document referred to by the provided * `DocumentReference`. The update will fail if applied to a document that @@ -935,7 +888,6 @@ declare namespace FirebaseFirestore { value: any, ...fieldsOrPrecondition: any[] ): Transaction; - /** * Deletes the document referred to by the provided `DocumentReference`. * @@ -947,7 +899,6 @@ declare namespace FirebaseFirestore { documentRef: DocumentReference, precondition?: Precondition ): Transaction; - /** * Executes this pipeline and returns a Promise to represent the asynchronous operation. * @@ -982,7 +933,6 @@ declare namespace FirebaseFirestore { */ execute(pipeline: Pipelines.Pipeline): Promise; } - /** * A Firestore BulkWriter than can be used to perform a large number of writes * in parallel. Writes to the same document will be executed sequentially. @@ -991,7 +941,6 @@ declare namespace FirebaseFirestore { */ export class BulkWriter { private constructor(); - /** * Create a document with the provided data. This single operation will fail * if a document exists at its location. @@ -1008,7 +957,6 @@ declare namespace FirebaseFirestore { documentRef: DocumentReference, data: WithFieldValue ): Promise; - /** * Delete a document from the database. * @@ -1029,7 +977,6 @@ declare namespace FirebaseFirestore { documentRef: DocumentReference, precondition?: Precondition ): Promise; - /** * Write to the document referred to by the provided * [DocumentReference]{@link DocumentReference}. If the document does not @@ -1063,7 +1010,6 @@ declare namespace FirebaseFirestore { documentRef: DocumentReference, data: WithFieldValue ): Promise; - /** * Update fields of the document referred to by the provided * [DocumentReference]{@link DocumentReference}. If the document doesn't yet @@ -1093,7 +1039,6 @@ declare namespace FirebaseFirestore { data: UpdateData, precondition?: Precondition ): Promise; - /** * Update fields of the document referred to by the provided * [DocumentReference]{@link DocumentReference}. If the document doesn't yet @@ -1126,7 +1071,6 @@ declare namespace FirebaseFirestore { value: any, ...fieldsOrPrecondition: any[] ): Promise; - /** * Attaches a listener that is run every time a BulkWriter operation * successfully completes. @@ -1140,7 +1084,6 @@ declare namespace FirebaseFirestore { result: WriteResult ) => void ): void; - /** * Attaches an error handler listener that is run every time a BulkWriter * operation fails. @@ -1156,7 +1099,6 @@ declare namespace FirebaseFirestore { onWriteError( shouldRetryCallback: (error: BulkWriterError) => boolean ): void; - /** * Commits all writes that have been enqueued up to this point in parallel. * @@ -1173,7 +1115,6 @@ declare namespace FirebaseFirestore { * up to this point have been committed. */ flush(): Promise; - /** * Commits all enqueued writes and marks the BulkWriter instance as closed. * @@ -1191,7 +1132,6 @@ declare namespace FirebaseFirestore { */ close(): Promise; } - /** * An options object to configure throttling on BulkWriter. */ @@ -1215,29 +1155,26 @@ declare namespace FirebaseFirestore { */ readonly throttling?: | boolean - | {initialOpsPerSecond?: number; maxOpsPerSecond?: number}; + | { + initialOpsPerSecond?: number; + maxOpsPerSecond?: number; + }; } - /** * The error thrown when a BulkWriter operation fails. */ export class BulkWriterError extends Error { /** The status code of the error. */ readonly code: GrpcStatus; - /** The error message of the error. */ readonly message: string; - /** The document reference the operation was performed on. */ readonly documentRef: DocumentReference; - /** The type of operation performed. */ readonly operationType: 'create' | 'set' | 'update' | 'delete'; - /** How many times this operation has been attempted unsuccessfully. */ readonly failedAttempts: number; } - /** * A write batch, used to perform multiple writes as a single atomic unit. * @@ -1251,7 +1188,6 @@ declare namespace FirebaseFirestore { */ export class WriteBatch { private constructor(); - /** * Create the document referred to by the provided `DocumentReference`. The * operation will fail the batch if a document exists at the specified @@ -1266,7 +1202,6 @@ declare namespace FirebaseFirestore { documentRef: DocumentReference, data: WithFieldValue ): WriteBatch; - /** * Write to the document referred to by the provided `DocumentReference`. * If the document does not exist yet, it will be created. If you pass @@ -1295,7 +1230,6 @@ declare namespace FirebaseFirestore { documentRef: DocumentReference, data: WithFieldValue ): WriteBatch; - /** * Update fields of the document referred to by the provided * `DocumentReference`. If the document doesn't yet exist, the update fails @@ -1316,7 +1250,6 @@ declare namespace FirebaseFirestore { data: UpdateData, precondition?: Precondition ): WriteBatch; - /** * Updates fields in the document referred to by the provided * `DocumentReference`. The update will fail if applied to a document that @@ -1343,7 +1276,6 @@ declare namespace FirebaseFirestore { value: any, ...fieldsOrPrecondition: any[] ): WriteBatch; - /** * Deletes the document referred to by the provided `DocumentReference`. * @@ -1355,7 +1287,6 @@ declare namespace FirebaseFirestore { documentRef: DocumentReference, precondition?: Precondition ): WriteBatch; - /** * Commits all of the writes in this write batch as a single atomic unit. * @@ -1364,7 +1295,6 @@ declare namespace FirebaseFirestore { */ commit(): Promise; } - /** * An options object that configures conditional behavior of `update()` and * `delete()` calls in `DocumentReference`, `WriteBatch`, and `Transaction`. @@ -1376,13 +1306,11 @@ declare namespace FirebaseFirestore { * If set, the last update time to enforce. */ readonly lastUpdateTime?: Timestamp; - /** * If set, enforces that the target document must or must not exist. */ readonly exists?: boolean; } - /** * An options object that configures the behavior of `set()` calls in * `DocumentReference`, `WriteBatch` and `Transaction`. These calls can be @@ -1406,7 +1334,6 @@ declare namespace FirebaseFirestore { | { readonly mergeFields?: Array; }; - /** * An options object that can be used to configure the behavior of `getAll()` * calls. By providing a `fieldMask`, these calls can be configured to only @@ -1423,19 +1350,16 @@ declare namespace FirebaseFirestore { */ readonly fieldMask?: (string | FieldPath)[]; } - /** * A WriteResult wraps the write time set by the Firestore servers on `sets()`, * `updates()`, and `creates()`. */ export class WriteResult { private constructor(); - /** * The write time as set by the Firestore servers. */ readonly writeTime: Timestamp; - /** * Returns true if this `WriteResult` is equal to the provided one. * @@ -1444,7 +1368,6 @@ declare namespace FirebaseFirestore { */ isEqual(other: WriteResult): boolean; } - /** * A `DocumentReference` refers to a document location in a Firestore database * and can be used to write, read, or listen to the location. The document at @@ -1456,27 +1379,22 @@ declare namespace FirebaseFirestore { DbModelType extends DocumentData = DocumentData, > { private constructor(); - /** The identifier of the document within its collection. */ readonly id: string; - /** * The `Firestore` for the Firestore database (useful for performing * transactions, etc.). */ readonly firestore: Firestore; - /** * A reference to the Collection to which this DocumentReference belongs. */ readonly parent: CollectionReference; - /** * A string representing the path of the referenced document (relative * to the root of the database). */ readonly path: string; - /** * Gets a `CollectionReference` instance that refers to the collection at * the specified path. @@ -1485,14 +1403,12 @@ declare namespace FirebaseFirestore { * @return The `CollectionReference` instance. */ collection(collectionPath: string): CollectionReference; - /** * Fetches the subcollections that are direct children of this document. * * @returns A Promise that resolves with an array of CollectionReferences. */ listCollections(): Promise>; - /** * Creates a document referred to by this `DocumentReference` with the * provided object values. The write fails if the document already exists @@ -1502,7 +1418,6 @@ declare namespace FirebaseFirestore { * @return A Promise resolved with the write time of this create. */ create(data: WithFieldValue): Promise; - /** * Writes to the document referred to by this `DocumentReference`. If the * document does not yet exist, it will be created. If you pass @@ -1526,7 +1441,6 @@ declare namespace FirebaseFirestore { options: SetOptions ): Promise; set(data: WithFieldValue): Promise; - /** * Updates fields in the document referred to by this `DocumentReference`. * The update will fail if applied to a document that does not exist. @@ -1544,7 +1458,6 @@ declare namespace FirebaseFirestore { data: UpdateData, precondition?: Precondition ): Promise; - /** * Updates fields in the document referred to by this `DocumentReference`. * The update will fail if applied to a document that does not exist. @@ -1568,7 +1481,6 @@ declare namespace FirebaseFirestore { value: any, ...moreFieldsOrPrecondition: any[] ): Promise; - /** * Deletes the document referred to by this `DocumentReference`. * @@ -1576,7 +1488,6 @@ declare namespace FirebaseFirestore { * @return A Promise resolved with the write time of this delete. */ delete(precondition?: Precondition): Promise; - /** * Reads the document referred to by this `DocumentReference`. * @@ -1584,7 +1495,6 @@ declare namespace FirebaseFirestore { * current document contents. */ get(): Promise>; - /** * Attaches a listener for DocumentSnapshot events. * @@ -1599,7 +1509,6 @@ declare namespace FirebaseFirestore { onNext: (snapshot: DocumentSnapshot) => void, onError?: (error: Error) => void ): () => void; - /** * Returns true if this `DocumentReference` is equal to the provided one. * @@ -1607,7 +1516,6 @@ declare namespace FirebaseFirestore { * @return true if this `DocumentReference` is equal to the provided one. */ isEqual(other: DocumentReference): boolean; - /** * Applies a custom data converter to this DocumentReference, allowing you * to use your own custom model objects with Firestore. When you call @@ -1626,7 +1534,6 @@ declare namespace FirebaseFirestore { converter: FirestoreDataConverter | null ): DocumentReference; } - /** * A `DocumentSnapshot` contains data read from a document in your Firestore * database. The data can be extracted with `.data()` or `.get()` to @@ -1641,35 +1548,28 @@ declare namespace FirebaseFirestore { DbModelType extends DocumentData = DocumentData, > { protected constructor(); - /** True if the document exists. */ readonly exists: boolean; - /** A `DocumentReference` to the document location. */ readonly ref: DocumentReference; - /** * The ID of the document for which this `DocumentSnapshot` contains data. */ readonly id: string; - /** * The time the document was created. Not set for documents that don't * exist. */ readonly createTime?: Timestamp; - /** * The time the document was last updated (at the time the snapshot was * generated). Not set for documents that don't exist. */ readonly updateTime?: Timestamp; - /** * The time this snapshot was read. */ readonly readTime: Timestamp; - /** * Retrieves all fields in the document as an Object. Returns 'undefined' if * the document doesn't exist. @@ -1677,7 +1577,6 @@ declare namespace FirebaseFirestore { * @return An Object containing all fields in the document. */ data(): AppModelType | undefined; - /** * Retrieves the field specified by `fieldPath`. * @@ -1686,7 +1585,6 @@ declare namespace FirebaseFirestore { * field exists in the document. */ get(fieldPath: string | FieldPath): any; - /** * Returns true if the document's data and path in this `DocumentSnapshot` * is equal to the provided one. @@ -1696,7 +1594,6 @@ declare namespace FirebaseFirestore { */ isEqual(other: DocumentSnapshot): boolean; } - /** * A `QueryDocumentSnapshot` contains data read from a document in your * Firestore database as part of a query. The document is guaranteed to exist @@ -1713,18 +1610,15 @@ declare namespace FirebaseFirestore { DbModelType extends DocumentData = DocumentData, > extends DocumentSnapshot { private constructor(); - /** * The time the document was created. */ readonly createTime: Timestamp; - /** * The time the document was last updated (at the time the snapshot was * generated). */ readonly updateTime: Timestamp; - /** * Retrieves all fields in the document as an Object. * @@ -1733,13 +1627,11 @@ declare namespace FirebaseFirestore { */ data(): AppModelType; } - /** * The direction of a `Query.orderBy()` clause is specified as 'desc' or 'asc' * (descending or ascending). */ export type OrderByDirection = 'desc' | 'asc'; - /** * Filter conditions in a `Query.where()` clause are specified using the * strings '<', '<=', '==', '!=', '>=', '>', 'array-contains', 'in', 'not-in', @@ -1756,7 +1648,6 @@ declare namespace FirebaseFirestore { | 'in' | 'not-in' | 'array-contains-any'; - /** * A `Query` refers to a Query which you can read or listen to. You can also * construct refined `Query` objects by adding filters and ordering. @@ -1766,13 +1657,11 @@ declare namespace FirebaseFirestore { DbModelType extends DocumentData = DocumentData, > { protected constructor(); - /** * The `Firestore` for the Firestore database (useful for performing * transactions, etc.). */ readonly firestore: Firestore; - /** * Creates and returns a new Query with the additional filter that documents * must contain the specified field and that its value should satisfy the @@ -1791,7 +1680,6 @@ declare namespace FirebaseFirestore { opStr: WhereFilterOp, value: any ): Query; - /** * Creates and returns a new [Query]{@link Query} with the additional filter * that documents should satisfy the relation constraint provided. Documents @@ -1804,7 +1692,6 @@ declare namespace FirebaseFirestore { * @returns {Query} The created Query. */ where(filter: Filter): Query; - /** * Creates and returns a new Query that's additionally sorted by the * specified field, optionally in descending order instead of ascending. @@ -1821,7 +1708,6 @@ declare namespace FirebaseFirestore { fieldPath: string | FieldPath, directionStr?: OrderByDirection ): Query; - /** * Creates and returns a new Query that only returns the first matching * documents. @@ -1833,7 +1719,6 @@ declare namespace FirebaseFirestore { * @return The created Query. */ limit(limit: number): Query; - /** * Creates and returns a new Query that only returns the last matching * documents. @@ -1848,7 +1733,6 @@ declare namespace FirebaseFirestore { * @return The created Query. */ limitToLast(limit: number): Query; - /** * Specifies the offset of the returned results. * @@ -1859,7 +1743,6 @@ declare namespace FirebaseFirestore { * @return The created Query. */ offset(offset: number): Query; - /** * Creates and returns a new Query instance that applies a field mask to * the result and returns only the specified subset of fields. You can @@ -1876,7 +1759,6 @@ declare namespace FirebaseFirestore { * @return The created Query. */ select(...field: (string | FieldPath)[]): Query; - /** * Creates and returns a new Query that starts at the provided document * (inclusive). The starting position is relative to the order of the query. @@ -1889,7 +1771,6 @@ declare namespace FirebaseFirestore { startAt( snapshot: DocumentSnapshot ): Query; - /** * Creates and returns a new Query that starts at the provided fields * relative to the order of the query. The order of the field values @@ -1900,7 +1781,6 @@ declare namespace FirebaseFirestore { * @return The created Query. */ startAt(...fieldValues: any[]): Query; - /** * Creates and returns a new Query that starts after the provided document * (exclusive). The starting position is relative to the order of the query. @@ -1913,7 +1793,6 @@ declare namespace FirebaseFirestore { startAfter( snapshot: DocumentSnapshot ): Query; - /** * Creates and returns a new Query that starts after the provided fields * relative to the order of the query. The order of the field values @@ -1924,7 +1803,6 @@ declare namespace FirebaseFirestore { * @return The created Query. */ startAfter(...fieldValues: any[]): Query; - /** * Creates and returns a new Query that ends before the provided document * (exclusive). The end position is relative to the order of the query. The @@ -1937,7 +1815,6 @@ declare namespace FirebaseFirestore { endBefore( snapshot: DocumentSnapshot ): Query; - /** * Creates and returns a new Query that ends before the provided fields * relative to the order of the query. The order of the field values @@ -1948,7 +1825,6 @@ declare namespace FirebaseFirestore { * @return The created Query. */ endBefore(...fieldValues: any[]): Query; - /** * Creates and returns a new Query that ends at the provided document * (inclusive). The end position is relative to the order of the query. The @@ -1961,7 +1837,6 @@ declare namespace FirebaseFirestore { endAt( snapshot: DocumentSnapshot ): Query; - /** * Creates and returns a new Query that ends at the provided fields * relative to the order of the query. The order of the field values @@ -1972,14 +1847,12 @@ declare namespace FirebaseFirestore { * @return The created Query. */ endAt(...fieldValues: any[]): Query; - /** * Executes the query and returns the results as a `QuerySnapshot`. * * @return A Promise that will be resolved with the results of the Query. */ get(): Promise>; - /** * Plans and optionally executes this query. Returns a Promise that will be * resolved with the planner information, statistics from the query execution (if any), @@ -1991,14 +1864,12 @@ declare namespace FirebaseFirestore { explain( options?: ExplainOptions ): Promise>>; - /** * Executes the query and returns the results as Node Stream. * * @return A stream of QueryDocumentSnapshot. */ stream(): NodeJS.ReadableStream; - /** * Plans and optionally executes this query, and streams the results as Node Stream * of `{document?: DocumentSnapshot, metrics?: ExplainMetrics}` objects. @@ -2030,7 +1901,6 @@ declare namespace FirebaseFirestore { * objects. */ explainStream(options?: ExplainOptions): NodeJS.ReadableStream; - /** * Attaches a listener for `QuerySnapshot `events. * @@ -2045,7 +1915,6 @@ declare namespace FirebaseFirestore { onNext: (snapshot: QuerySnapshot) => void, onError?: (error: Error) => void ): () => void; - /** * Returns a query that counts the documents in the result set of this * query. @@ -2064,11 +1933,12 @@ declare namespace FirebaseFirestore { * returned query. */ count(): AggregateQuery< - {count: AggregateField}, + { + count: AggregateField; + }, AppModelType, DbModelType >; - /** * Returns a query that can perform the given aggregations. * @@ -2102,7 +1972,6 @@ declare namespace FirebaseFirestore { aggregate( aggregateSpec: T ): AggregateQuery; - /** * Returns a query that can perform vector distance (similarity) search with given parameters. * @@ -2139,7 +2008,6 @@ declare namespace FirebaseFirestore { distanceMeasure: 'EUCLIDEAN' | 'COSINE' | 'DOT_PRODUCT'; } ): VectorQuery; - /** * Returns a query that can perform vector distance (similarity) search with given parameters. * @@ -2171,7 +2039,6 @@ declare namespace FirebaseFirestore { findNearest( options: VectorQueryOptions ): VectorQuery; - /** * Returns a query that can perform vector distance (similarity) search with given parameters. * @@ -2203,7 +2070,6 @@ declare namespace FirebaseFirestore { findNearest( options: VectorQueryOptions ): VectorQuery; - /** * Returns true if this `Query` is equal to the provided one. * @@ -2211,7 +2077,6 @@ declare namespace FirebaseFirestore { * @return true if this `Query` is equal to the provided one. */ isEqual(other: Query): boolean; - /** * Applies a custom data converter to this Query, allowing you to use your * own custom model objects with Firestore. When you call get() on the @@ -2229,7 +2094,6 @@ declare namespace FirebaseFirestore { converter: FirestoreDataConverter | null ): Query; } - /** * A `QuerySnapshot` contains zero or more `QueryDocumentSnapshot` objects * representing the results of a query. The documents can be accessed as an @@ -2242,32 +2106,25 @@ declare namespace FirebaseFirestore { DbModelType extends DocumentData = DocumentData, > { private constructor(); - /** * The query on which you called `get` or `onSnapshot` in order to get this * `QuerySnapshot`. */ readonly query: Query; - /** An array of all the documents in the QuerySnapshot. */ readonly docs: Array>; - /** The number of documents in the QuerySnapshot. */ readonly size: number; - /** True if there are no documents in the QuerySnapshot. */ readonly empty: boolean; - /** The time this query snapshot was obtained. */ readonly readTime: Timestamp; - /** * Returns an array of the documents changes since the last snapshot. If * this is the first snapshot, all documents will be in the list as added * changes. */ docChanges(): DocumentChange[]; - /** * Enumerates all of the documents in the QuerySnapshot. * @@ -2281,7 +2138,6 @@ declare namespace FirebaseFirestore { ) => void, thisArg?: any ): void; - /** * Returns true if the document data in this `QuerySnapshot` is equal to the * provided one. @@ -2291,7 +2147,6 @@ declare namespace FirebaseFirestore { */ isEqual(other: QuerySnapshot): boolean; } - /** * A `VectorQuerySnapshot` contains zero or more `QueryDocumentSnapshot` objects * representing the results of a query. The documents can be accessed as an @@ -2304,32 +2159,25 @@ declare namespace FirebaseFirestore { DbModelType extends DocumentData = DocumentData, > { private constructor(); - /** * The query on which you called `get` in order to get this * `VectorQuerySnapshot`. */ readonly query: VectorQuery; - /** An array of all the documents in the QuerySnapshot. */ readonly docs: Array>; - /** The number of documents in the QuerySnapshot. */ readonly size: number; - /** True if there are no documents in the QuerySnapshot. */ readonly empty: boolean; - /** The time this query snapshot was obtained. */ readonly readTime: Timestamp; - /** * Returns an array of the documents changes since the last snapshot. If * this is the first snapshot, all documents will be in the list as added * changes. */ docChanges(): DocumentChange[]; - /** * Enumerates all of the documents in the QuerySnapshot. * @@ -2343,7 +2191,6 @@ declare namespace FirebaseFirestore { ) => void, thisArg?: any ): void; - /** * Returns true if the document data in this `VectorQuerySnapshot` is equal to the * provided one. @@ -2353,12 +2200,10 @@ declare namespace FirebaseFirestore { */ isEqual(other: VectorQuerySnapshot): boolean; } - /** * The type of `DocumentChange` may be 'added', 'removed', or 'modified'. */ export type DocumentChangeType = 'added' | 'removed' | 'modified'; - /** * A `DocumentChange` represents a change to the documents matching a query. * It contains the document affected and the type of change that occurred. @@ -2369,17 +2214,14 @@ declare namespace FirebaseFirestore { > { /** The type of change ('added', 'modified', or 'removed'). */ readonly type: DocumentChangeType; - /** The document affected by this change. */ readonly doc: QueryDocumentSnapshot; - /** * The index of the changed document in the result set immediately prior to * this DocumentChange (i.e. supposing that all prior DocumentChange objects * have been applied). Is -1 for 'added' events. */ readonly oldIndex: number; - /** * The index of the changed document in the result set immediately after * this DocumentChange (i.e. supposing that all prior DocumentChange @@ -2387,7 +2229,6 @@ declare namespace FirebaseFirestore { * Is -1 for 'removed' events. */ readonly newIndex: number; - /** * Returns true if the data in this `DocumentChange` is equal to the * provided one. @@ -2397,7 +2238,6 @@ declare namespace FirebaseFirestore { */ isEqual(other: DocumentChange): boolean; } - /** * A `CollectionReference` object can be used for adding documents, getting * document references, and querying for documents (using the methods @@ -2408,22 +2248,18 @@ declare namespace FirebaseFirestore { DbModelType extends DocumentData = DocumentData, > extends Query { private constructor(); - /** The identifier of the collection. */ readonly id: string; - /** * A reference to the containing Document if this is a subcollection, else * null. */ readonly parent: DocumentReference | null; - /** * A string representing the path of the referenced collection (relative * to the root of the database). */ readonly path: string; - /** * Retrieves the list of documents in this collection. * @@ -2439,7 +2275,6 @@ declare namespace FirebaseFirestore { listDocuments(): Promise< Array> >; - /** * Get a `DocumentReference` for a randomly-named document within this * collection. An automatically-generated unique ID will be used as the @@ -2448,7 +2283,6 @@ declare namespace FirebaseFirestore { * @return The `DocumentReference` instance. */ doc(): DocumentReference; - /** * Get a `DocumentReference` for the document within the collection at the * specified path. @@ -2457,7 +2291,6 @@ declare namespace FirebaseFirestore { * @return The `DocumentReference` instance. */ doc(documentPath: string): DocumentReference; - /** * Add a new document to this collection with the specified data, assigning * it a document ID automatically. @@ -2470,7 +2303,6 @@ declare namespace FirebaseFirestore { add( data: WithFieldValue ): Promise>; - /** * Returns true if this `CollectionReference` is equal to the provided one. * @@ -2478,7 +2310,6 @@ declare namespace FirebaseFirestore { * @return true if this `CollectionReference` is equal to the provided one. */ isEqual(other: CollectionReference): boolean; - /** * Applies a custom data converter to this CollectionReference, allowing you * to use your own custom model objects with Firestore. When you call add() @@ -2497,7 +2328,6 @@ declare namespace FirebaseFirestore { converter: FirestoreDataConverter | null ): CollectionReference; } - /** * A `CollectionGroup` refers to all documents that are contained in a * collection or subcollection with a specific collection ID. @@ -2507,7 +2337,6 @@ declare namespace FirebaseFirestore { DbModelType extends DocumentData = DocumentData, > extends Query { private constructor(); - /** * Partitions a query by returning partition cursors that can be used to run * the query in parallel. The returned cursors are split points that can be @@ -2521,7 +2350,6 @@ declare namespace FirebaseFirestore { getPartitions( desiredPartitionCount: number ): AsyncIterable>; - /** * Applies a custom data converter to this `CollectionGroup`, allowing you * to use your own custom model objects with Firestore. When you call get() @@ -2575,7 +2403,6 @@ declare namespace FirebaseFirestore { converter: FirestoreDataConverter | null ): CollectionGroup; } - /** * A split point that can be used in a query as a starting and/or end point for * the query results. The cursors returned by {@link #startAt} and {@link @@ -2587,7 +2414,6 @@ declare namespace FirebaseFirestore { DbModelType extends DocumentData = DocumentData, > { private constructor(); - /** * The cursor that defines the first result for this partition or * `undefined` if this is the first partition. The cursor value must be @@ -2598,7 +2424,6 @@ declare namespace FirebaseFirestore { * `undefined` if this is the first partition. */ get startAt(): unknown[] | undefined; - /** * The cursor that defines the first result after this partition or * `undefined` if this is the last partition. The cursor value must be @@ -2609,7 +2434,6 @@ declare namespace FirebaseFirestore { * `undefined` if this is the last partition. */ get endBefore(): unknown[] | undefined; - /** * Returns a query that only returns the documents for this partition. * @@ -2618,12 +2442,10 @@ declare namespace FirebaseFirestore { */ toQuery(): Query; } - /** * Union type representing the aggregate type to be performed. */ export type AggregateType = 'count' | 'avg' | 'sum'; - /** * The union of all `AggregateField` types that are supported by Firestore. */ @@ -2631,20 +2453,16 @@ declare namespace FirebaseFirestore { | ReturnType | ReturnType | ReturnType; - /** * Represents an aggregation that can be performed by Firestore. */ // eslint-disable-next-line @typescript-eslint/no-unused-vars export class AggregateField { private constructor(); - /** A type string to uniquely identify instances of this class. */ readonly type = 'AggregateField'; - /** The kind of aggregation performed by this AggregateField. */ public readonly aggregateType: AggregateType; - /** * Compares this object with the given object for equality. * @@ -2656,20 +2474,17 @@ declare namespace FirebaseFirestore { * defined above, or `false` otherwise. */ isEqual(other: AggregateField): boolean; - /** * Create an AggregateField object that can be used to compute the count of * documents in the result set of a query. */ static count(): AggregateField; - /** * Create an AggregateField object that can be used to compute the average of * a specified field over a range of documents in the result set of a query. * @param field Specifies the field to average across the result set. */ static average(field: string | FieldPath): AggregateField; - /** * Create an AggregateField object that can be used to compute the sum of * a specified field over a range of documents in the result set of a query. @@ -2677,14 +2492,12 @@ declare namespace FirebaseFirestore { */ static sum(field: string | FieldPath): AggregateField; } - /** * A type whose property values are all `AggregateField` objects. */ export interface AggregateSpec { [field: string]: AggregateFieldType; } - /** * A type whose keys are taken from an `AggregateSpec`, and whose values are * the result of the aggregation performed by the corresponding @@ -2693,7 +2506,6 @@ declare namespace FirebaseFirestore { export type AggregateSpecData = { [P in keyof T]: T[P] extends AggregateField ? U : never; }; - /** * A query that calculates aggregations over an underlying query. */ @@ -2703,10 +2515,8 @@ declare namespace FirebaseFirestore { DbModelType extends DocumentData = DocumentData, > { private constructor(); - /** The query whose aggregations will be calculated by this object. */ readonly query: Query; - /** * Executes this query. * @@ -2715,7 +2525,6 @@ declare namespace FirebaseFirestore { get(): Promise< AggregateQuerySnapshot >; - /** * Plans and optionally executes this query. Returns a Promise that will be * resolved with the planner information, statistics from the query execution (if any), @@ -2731,7 +2540,6 @@ declare namespace FirebaseFirestore { AggregateQuerySnapshot > >; - /** * Compares this object with the given object for equality. * @@ -2748,7 +2556,6 @@ declare namespace FirebaseFirestore { other: AggregateQuery ): boolean; } - /** * The results of executing an aggregation query. */ @@ -2758,17 +2565,14 @@ declare namespace FirebaseFirestore { DbModelType extends DocumentData = DocumentData, > { private constructor(); - /** The query that was executed to produce this result. */ readonly query: AggregateQuery< AggregateSpecType, AppModelType, DbModelType >; - /** The time this snapshot was read. */ readonly readTime: Timestamp; - /** * Returns the results of the aggregations performed over the underlying * query. @@ -2781,7 +2585,6 @@ declare namespace FirebaseFirestore { * query. */ data(): AggregateSpecData; - /** * Compares this object with the given object for equality. * @@ -2801,7 +2604,6 @@ declare namespace FirebaseFirestore { > ): boolean; } - /** * A query that finds the document whose vector fields are closest to a certain vector. */ @@ -2810,17 +2612,14 @@ declare namespace FirebaseFirestore { DbModelType extends DocumentData = DocumentData, > { private constructor(); - /** The query whose results participants in the distance search. */ readonly query: Query; - /** * Executes this query. * * @return A promise that will be resolved with the results of the query. */ get(): Promise>; - /** * Compares this object with the given object for equality. * @@ -2835,31 +2634,26 @@ declare namespace FirebaseFirestore { */ isEqual(other: VectorQuery): boolean; } - /** * Represent a vector type in Firestore documents. */ export class VectorValue { private constructor(values: number[] | undefined); - /** * Returns a copy of the raw number array form of the vector. */ toArray(): number[]; - /** * Returns true if the two `VectorValue` has the same raw number arrays, returns false otherwise. */ isEqual(other: VectorValue): boolean; } - /** * Sentinel values that can be used when writing document fields with set(), * create() or update(). */ export class FieldValue { private constructor(); - /** * Returns a sentinel used with set(), create() or update() to include a * server-generated timestamp in the written data. @@ -2868,7 +2662,6 @@ declare namespace FirebaseFirestore { * update(). */ static serverTimestamp(): FieldValue; - /** * Returns a sentinel for use with update() or set() with {merge:true} to * mark a field for deletion. @@ -2876,7 +2669,6 @@ declare namespace FirebaseFirestore { * @return The FieldValue sentinel for use in a call to set() or update(). */ static delete(): FieldValue; - /** * Returns a special value that can be used with set(), create() or update() * that tells the server to increment the field's current value by the given @@ -2895,7 +2687,6 @@ declare namespace FirebaseFirestore { * update(). */ static increment(n: number): FieldValue; - /** * Returns a special value that can be used with set(), create() or update() * that tells the server to union the given elements with any array value @@ -2909,7 +2700,6 @@ declare namespace FirebaseFirestore { * update(). */ static arrayUnion(...elements: any[]): FieldValue; - /** * Returns a special value that can be used with set(), create() or update() * that tells the server to remove the given elements from any array value @@ -2922,12 +2712,10 @@ declare namespace FirebaseFirestore { * update(). */ static arrayRemove(...elements: any[]): FieldValue; - /** * @return A new `VectorValue` constructed with a copy of the given array of number. */ static vector(values?: number[]): VectorValue; - /** * Returns true if this `FieldValue` is equal to the provided one. * @@ -2936,7 +2724,6 @@ declare namespace FirebaseFirestore { */ isEqual(other: FieldValue): boolean; } - /** * A FieldPath refers to a field in a document. The path may consist of a * single field name (referring to a top-level field in the document), or a @@ -2950,13 +2737,11 @@ declare namespace FirebaseFirestore { * @param fieldNames A list of field names. */ constructor(...fieldNames: string[]); - /** * Returns a special sentinel FieldPath to refer to the ID of a document. * It can be used in queries to sort or filter by the document ID. */ static documentId(): FieldPath; - /** * Returns true if this `FieldPath` is equal to the provided one. * @@ -2965,7 +2750,6 @@ declare namespace FirebaseFirestore { */ isEqual(other: FieldPath): boolean; } - /** * A Timestamp represents a point in time independent of any time zone or * calendar, represented as seconds and fractions of seconds at nanosecond @@ -2984,7 +2768,6 @@ declare namespace FirebaseFirestore { * @return A new `Timestamp` representing the current date. */ static now(): Timestamp; - /** * Creates a new timestamp from the given date. * @@ -2993,7 +2776,6 @@ declare namespace FirebaseFirestore { * given date. */ static fromDate(date: Date): Timestamp; - /** * Creates a new timestamp from the given number of milliseconds. * @@ -3003,7 +2785,6 @@ declare namespace FirebaseFirestore { * given number of milliseconds. */ static fromMillis(milliseconds: number): Timestamp; - /** * Creates a new timestamp. * @@ -3016,15 +2797,12 @@ declare namespace FirebaseFirestore { * 0 to 999,999,999 inclusive. */ constructor(seconds: number, nanoseconds: number); - /** * The number of seconds of UTC time since Unix epoch 1970-01-01T00:00:00Z. */ readonly seconds: number; - /** The non-negative fractions of a second at nanosecond resolution. */ readonly nanoseconds: number; - /** * Returns a new `Date` corresponding to this timestamp. This may lose * precision. @@ -3033,7 +2811,6 @@ declare namespace FirebaseFirestore { * this `Timestamp`, with millisecond precision. */ toDate(): Date; - /** * Returns the number of milliseconds since Unix epoch 1970-01-01T00:00:00Z. * @@ -3041,7 +2818,6 @@ declare namespace FirebaseFirestore { * the number of milliseconds since Unix epoch 1970-01-01T00:00:00Z. */ toMillis(): number; - /** * Returns true if this `Timestamp` is equal to the provided one. * @@ -3049,7 +2825,6 @@ declare namespace FirebaseFirestore { * @return 'true' if this `Timestamp` is equal to the provided one. */ isEqual(other: Timestamp): boolean; - /** * Converts this object to a primitive `string`, which allows `Timestamp` objects to be compared * using the `>`, `<=`, `>=` and `>` operators. @@ -3058,14 +2833,12 @@ declare namespace FirebaseFirestore { */ valueOf(): string; } - /** * Builds a Firestore data bundle with results from the given document and query snapshots. */ export class BundleBuilder { /** The ID of this bundle. */ readonly bundleId: string; - /** * Adds a Firestore `DocumentSnapshot` to the bundle. Both the documents data and the document * read time will be included in the bundle. @@ -3076,7 +2849,6 @@ declare namespace FirebaseFirestore { add( documentSnapshot: DocumentSnapshot ): BundleBuilder; - /** * Adds a Firestore `QuerySnapshot` to the bundle. Both the documents in the query results and * the query read time will be included in the bundle. @@ -3089,13 +2861,11 @@ declare namespace FirebaseFirestore { queryName: string, querySnapshot: QuerySnapshot ): BundleBuilder; - /** * Builds the bundle and returns the result as a `Buffer` instance. */ build(): Buffer; } - /** * The v1beta1 Veneer client. This client provides access to to the underlying * Firestore v1beta1 RPCs. @@ -3104,7 +2874,6 @@ declare namespace FirebaseFirestore { export const v1beta1: { FirestoreClient: typeof import('./v1beta1/firestore_client').FirestoreClient; }; - /** * The v1 Veneer clients. These clients provide access to the Firestore Admin * API and the underlying Firestore v1 RPCs. @@ -3113,7 +2882,6 @@ declare namespace FirebaseFirestore { FirestoreClient: typeof import('./v1/firestore_client').FirestoreClient; FirestoreAdminClient: typeof import('./v1/firestore_admin_client').FirestoreAdminClient; }; - /** * Status codes returned by Firestore's gRPC calls. */ @@ -3136,7 +2904,6 @@ declare namespace FirebaseFirestore { DATA_LOSS = 15, UNAUTHENTICATED = 16, } - /** * A `Filter` represents a restriction on one or more field values and can * be used to refine the results of a {@link Query}. @@ -3177,7 +2944,6 @@ declare namespace FirebaseFirestore { opStr: WhereFilterOp, value: unknown ): Filter; - /** * Creates and returns a new [Filter]{@link Filter} that is a * disjunction of the given {@link Filter}s. A disjunction filter includes @@ -3208,7 +2974,6 @@ declare namespace FirebaseFirestore { * ``` */ static or(...filters: Filter[]): Filter; - /** * Creates and returns a new [Filter]{@link Filter} that is a * conjunction of the given {@link Filter}s. A conjunction filter includes @@ -3240,11 +3005,9 @@ declare namespace FirebaseFirestore { */ static and(...filters: Filter[]): Filter; } - type Duration = { /** Signed seconds of the span of time. */ seconds: number; - /** * Signed fractions of a second at nanosecond resolution of the span * of time. Durations less than one second are represented with a 0 @@ -3255,7 +3018,6 @@ declare namespace FirebaseFirestore { */ nanoseconds: number; }; - /** Options used to configure explain queries. */ export interface ExplainOptions { /** @@ -3265,7 +3027,6 @@ declare namespace FirebaseFirestore { */ readonly analyze?: boolean; } - /** * PlanSummary contains information about the planning stage of a query. */ @@ -3278,18 +3039,14 @@ declare namespace FirebaseFirestore { */ readonly indexesUsed: Record[]; } - /** ExecutionStats contains information about the execution of a query. */ export interface ExecutionStats { /** The number of query results. */ readonly resultsReturned: number; - /** The total execution time of the query. */ readonly executionDuration: Duration; - /** The number of read operations that occurred when executing the query. */ readonly readOperations: number; - /** * Contains additional statistics related to the query execution. * This should be inspected or logged, because the contents are intended to be @@ -3298,7 +3055,6 @@ declare namespace FirebaseFirestore { */ readonly debugStats: Record; } - /** * ExplainMetrics contains information about planning and execution of a query. */ @@ -3307,14 +3063,12 @@ declare namespace FirebaseFirestore { * Information about the query plan. */ readonly planSummary: PlanSummary; - /** * Information about the execution of the query, or null if the query was * not executed. */ readonly executionStats: ExecutionStats | null; } - /** * ExplainResults contains information about planning, execution, and results * of a query. @@ -3324,14 +3078,12 @@ declare namespace FirebaseFirestore { * Information about planning and execution of the query. */ readonly metrics: ExplainMetrics; - /** * The snapshot that contains the results of executing the query, or null * if the query was not executed. */ readonly snapshot: T | null; } - /** * Specifies the behavior of the {@link VectorQuery} generated by a call to {@link Query.findNearest}. */ @@ -3340,28 +3092,23 @@ declare namespace FirebaseFirestore { * A string or {@link FieldPath} specifying the vector field to search on. */ vectorField: string | FieldPath; - /** * The {@link VectorValue} used to measure the distance from `vectorField` values in the documents. */ queryVector: VectorValue | Array; - /** * Specifies the upper bound of documents to return, must be a positive integer with a maximum value of 1000. */ limit: number; - /** * Specifies what type of distance is calculated when performing the query. */ distanceMeasure: 'EUCLIDEAN' | 'COSINE' | 'DOT_PRODUCT'; - /** * Optionally specifies the name of a field that will be set on each returned DocumentSnapshot, * which will contain the computed distance for the document. */ distanceResultField?: string | FieldPath; - /** * Specifies a threshold for which no less similar documents will be returned. The behavior * of the specified `distanceMeasure` will affect the meaning of the distance threshold. @@ -3376,11 +3123,19 @@ declare namespace FirebaseFirestore { distanceThreshold?: number; } + /** + * @beta + */ export namespace Pipelines { /** * @beta + * Represents an expression that has been assigned an alias using the `.as()` method. + * + * This class wraps an existing {@link Expr} and associates it with a user-defined alias, + * allowing the expression's result to be referred to by a different name in the output + * of a Firestore pipeline query, particularly within `select()` operations. * - * An enumeration of the different types of expressions. + * @internal */ export type ExprType = | 'Field' @@ -3388,11 +3143,9 @@ declare namespace FirebaseFirestore { | 'Function' | 'AggregateFunction' | 'ListOfExprs' - | 'ExprWithAlias'; - + | 'AliasedExpr'; /** * @beta - * * Represents an expression that can be evaluated to a value within the execution of a {@link * Pipeline}. * @@ -3408,8 +3161,8 @@ declare namespace FirebaseFirestore { */ export abstract class Expr { abstract readonly exprType: ExprType; - /** + * @beta * Creates an expression that adds this expression to another expression. * * ```typescript @@ -3425,8 +3178,8 @@ declare namespace FirebaseFirestore { second: Expr | unknown, ...others: Array ): FunctionExpr; - /** + * @beta * Creates an expression that subtracts another expression from this expression. * * ```typescript @@ -3434,12 +3187,12 @@ declare namespace FirebaseFirestore { * field("price").subtract(field("discount")); * ``` * - * @param other The expression to subtract from this expression. + * @param subtrahend The expression to subtract from this expression. * @return A new `Expr` representing the subtraction operation. */ - subtract(other: Expr): FunctionExpr; - + subtract(subtrahend: Expr): FunctionExpr; /** + * @beta * Creates an expression that subtracts a constant value from this expression. * * ```typescript @@ -3447,12 +3200,12 @@ declare namespace FirebaseFirestore { * field("total").subtract(20); * ``` * - * @param other The constant value to subtract. + * @param subtrahend The constant value to subtract. * @return A new `Expr` representing the subtraction operation. */ - subtract(other: number): FunctionExpr; - + subtract(subtrahend: number): FunctionExpr; /** + * @beta * Creates an expression that multiplies this expression by another expression. * * ```typescript @@ -3468,8 +3221,8 @@ declare namespace FirebaseFirestore { second: Expr | number, ...others: Array ): FunctionExpr; - /** + * @beta * Creates an expression that divides this expression by another expression. * * ```typescript @@ -3477,12 +3230,12 @@ declare namespace FirebaseFirestore { * field("total").divide(field("count")); * ``` * - * @param other The expression to divide by. + * @param divisor The expression to divide by. * @return A new `Expr` representing the division operation. */ - divide(other: Expr): FunctionExpr; - + divide(divisor: Expr): FunctionExpr; /** + * @beta * Creates an expression that divides this expression by a constant value. * * ```typescript @@ -3490,13 +3243,12 @@ declare namespace FirebaseFirestore { * field("value").divide(10); * ``` * - * @param other The constant value to divide by. + * @param divisor The constant value to divide by. * @return A new `Expr` representing the division operation. */ - divide(other: number): FunctionExpr; - divide(other: number | Expr): FunctionExpr; - + divide(divisor: number): FunctionExpr; /** + * @beta * Creates an expression that calculates the modulo (remainder) of dividing this expression by another expression. * * ```typescript @@ -3508,8 +3260,8 @@ declare namespace FirebaseFirestore { * @return A new `Expr` representing the modulo operation. */ mod(expression: Expr): FunctionExpr; - /** + * @beta * Creates an expression that calculates the modulo (remainder) of dividing this expression by a constant value. * * ```typescript @@ -3523,19 +3275,23 @@ declare namespace FirebaseFirestore { mod(value: number): FunctionExpr; /** + * @beta * Creates an expression that checks if this expression is equal to another expression. * * ```typescript - * // Check if the 'age' field is equal to 21 - * field("age").eq(21); + * // Check if the 'age' field is equal to the value of another field named 'otherAge'. + * field("age").eq(field("otherAge")); + * + * // Check if the 'status' field is equal to a string literal. + * field("status").eq("active"); * ``` * * @param expression The expression to compare for equality. - * @return A new `Expr` representing the equality comparison. + * @return A new `BooleanExpr` representing the equality comparison. */ eq(expression: Expr): BooleanExpr; - /** + * @beta * Creates an expression that checks if this expression is equal to a constant value. * * ```typescript @@ -3549,6 +3305,7 @@ declare namespace FirebaseFirestore { eq(value: unknown): BooleanExpr; /** + * @beta * Creates an expression that checks if this expression is not equal to another expression. * * ```typescript @@ -3557,11 +3314,11 @@ declare namespace FirebaseFirestore { * ``` * * @param expression The expression to compare for inequality. - * @return A new `Expr` representing the inequality comparison. + * @return A new {@link BooleanExpr} representing the inequality comparison. */ neq(expression: Expr): BooleanExpr; - /** + * @beta * Creates an expression that checks if this expression is not equal to a constant value. * * ```typescript @@ -3575,6 +3332,7 @@ declare namespace FirebaseFirestore { neq(value: unknown): BooleanExpr; /** + * @beta * Creates an expression that checks if this expression is less than another expression. * * ```typescript @@ -3582,12 +3340,12 @@ declare namespace FirebaseFirestore { * field("age").lt(field('limit')); * ``` * - * @param experession The expression to compare for less than. - * @return A new `Expr` representing the less than comparison. + * @param expression The expression to compare against. + * @return A new `BooleanExpr` representing the less than comparison. */ - lt(experession: Expr): BooleanExpr; - + lt(expression: Expr): BooleanExpr; /** + * @beta * Creates an expression that checks if this expression is less than a constant value. * * ```typescript @@ -3601,20 +3359,20 @@ declare namespace FirebaseFirestore { lt(value: unknown): BooleanExpr; /** - * Creates an expression that checks if this expression is less than or equal to another - * expression. + * @beta + * Creates an expression that checks if the current expression's value is less than or equal to the value of another expression. * * ```typescript * // Check if the 'quantity' field is less than or equal to 20 * field("quantity").lte(constant(20)); * ``` * - * @param expression The expression to compare for less than or equal to. - * @return A new `Expr` representing the less than or equal to comparison. + * @param expression The expression to compare against. + * @return A new `BooleanExpr` representing the less than or equal to comparison. */ lte(expression: Expr): BooleanExpr; - /** + * @beta * Creates an expression that checks if this expression is less than or equal to a constant value. * * ```typescript @@ -3628,6 +3386,7 @@ declare namespace FirebaseFirestore { lte(value: unknown): BooleanExpr; /** + * @beta * Creates an expression that checks if this expression is greater than another expression. * * ```typescript @@ -3636,11 +3395,11 @@ declare namespace FirebaseFirestore { * ``` * * @param expression The expression to compare for greater than. - * @return A new `Expr` representing the greater than comparison. + * @return A new {@link BooleanExpr} representing the greater than comparison. */ gt(expression: Expr): BooleanExpr; - /** + * @beta * Creates an expression that checks if this expression is greater than a constant value. * * ```typescript @@ -3652,8 +3411,8 @@ declare namespace FirebaseFirestore { * @return A new `Expr` representing the greater than comparison. */ gt(value: unknown): BooleanExpr; - /** + * @beta * Creates an expression that checks if this expression is greater than or equal to another * expression. * @@ -3666,8 +3425,8 @@ declare namespace FirebaseFirestore { * @return A new `Expr` representing the greater than or equal to comparison. */ gte(expression: Expr): BooleanExpr; - /** + * @beta * Creates an expression that checks if this expression is greater than or equal to a constant * value. * @@ -3680,24 +3439,8 @@ declare namespace FirebaseFirestore { * @return A new `Expr` representing the greater than or equal to comparison. */ gte(value: unknown): BooleanExpr; - - /** - * Creates an expression that concatenates an array expression with one or more other arrays. - * - * ```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. - * @return A new `Expr` representing the concatenated array. - */ - arrayConcat( - secondArray: Expr | unknown[], - ...otherArrays: Array - ): FunctionExpr; - /** + * @beta * Creates an expression that checks if an array contains a specific element. * * ```typescript @@ -3709,8 +3452,8 @@ declare namespace FirebaseFirestore { * @return A new `Expr` representing the 'array_contains' comparison. */ arrayContains(expression: Expr): BooleanExpr; - /** + * @beta * Creates an expression that checks if an array contains a specific value. * * ```typescript @@ -3722,8 +3465,8 @@ declare namespace FirebaseFirestore { * @return A new `Expr` representing the 'array_contains' comparison. */ arrayContains(value: unknown): BooleanExpr; - /** + * @beta * Creates an expression that checks if an array contains all the specified elements. * * ```typescript @@ -3735,8 +3478,8 @@ declare namespace FirebaseFirestore { * @return A new `Expr` representing the 'array_contains_all' comparison. */ arrayContainsAll(values: Array): BooleanExpr; - /** + * @beta * Creates an expression that checks if an array contains all the specified elements. * * ```typescript @@ -3748,8 +3491,8 @@ declare namespace FirebaseFirestore { * @return A new `Expr` representing the 'array_contains_all' comparison. */ arrayContainsAll(arrayExpression: Expr): BooleanExpr; - /** + * @beta * Creates an expression that checks if an array contains any of the specified elements. * * ```typescript @@ -3761,8 +3504,8 @@ declare namespace FirebaseFirestore { * @return A new `Expr` representing the 'array_contains_any' comparison. */ arrayContainsAny(values: Array): BooleanExpr; - /** + * @beta * Creates an expression that checks if an array contains any of the specified elements. * * ```typescript @@ -3775,8 +3518,8 @@ declare namespace FirebaseFirestore { * @return A new `Expr` representing the 'array_contains_any' comparison. */ arrayContainsAny(arrayExpression: Expr): BooleanExpr; - /** + * @beta * Creates an expression that calculates the length of an array. * * ```typescript @@ -3789,25 +3532,26 @@ declare namespace FirebaseFirestore { arrayLength(): FunctionExpr; /** + * @beta * Creates an expression that checks if this expression is equal to any of the provided values or * expressions. * * ```typescript - * // Check if the 'category' field is either "Electronics" or value of field 'primaryType' - * field("category").eqAny("Electronics", field("primaryType")); + * // Check if the 'category' field is either "Electronics" or the value of field 'primaryType' + * field("category").eqAny(["Electronics", field("primaryType")]); * ``` * - * @param values The values or expressions to check against. - * @return A new `Expr` representing the 'IN' comparison. + * @param values An array of values or expressions to check against. + * @return A new `BooleanExpr` representing the 'IN' comparison. */ eqAny(values: Array): BooleanExpr; - /** + * @beta * Creates an expression that checks if this expression is equal to any of the provided values or * expressions. * * ```typescript - * // Check if the 'category' field is either "Electronics" or value of field 'primaryType' + * // Check if the 'category' field is either "Electronics" or the value of field 'primaryType' * field("category").eqAny(array(["Electronics", field("primaryType")])); * ``` * @@ -3815,8 +3559,8 @@ declare namespace FirebaseFirestore { * @return A new `Expr` representing the 'IN' comparison. */ eqAny(arrayExpression: Expr): BooleanExpr; - /** + * @beta * Creates an expression that checks if this expression is not equal to any of the provided values or * expressions. * @@ -3831,19 +3575,20 @@ declare namespace FirebaseFirestore { notEqAny(values: Array): BooleanExpr; /** - * Creates an expression that checks if this expression is not equal to any of the values in the evaluated expression. + * @beta + * Creates an expression that checks if the current expression's value is not equal to any of the values within the array produced by the `arrayExpression`. * * ```typescript - * // Check if the 'status' field is not equal to any value in the field 'rejectedStatuses' + * // Check if the 'status' field is not equal to any value in the array returned by the 'rejectedStatuses' field. * field("status").notEqAny(field('rejectedStatuses')); * ``` * - * @param arrayExpression The values or expressions to check against. - * @return A new `Expr` representing the 'NotEqAny' comparison. + * @param arrayExpression An `Expr` that evaluates to an array of values to compare against. + * @return A new `BooleanExpr` representing the result of the 'not equal to any' comparison. */ notEqAny(arrayExpression: Expr): BooleanExpr; - /** + * @beta * Creates an expression that checks if this expression evaluates to 'NaN' (Not a Number). * * ```typescript @@ -3856,18 +3601,20 @@ declare namespace FirebaseFirestore { isNan(): BooleanExpr; /** - * Creates an expression that checks if this expression evaluates to 'Null'. + * @beta + * Creates an expression that checks if this expression evaluates to `null`. * * ```typescript - * // Check if the result of a calculation is NaN - * field("value").isNull(); + * // Check if the 'status' field is null. + * field("status").isNull(); * ``` * - * @return A new `Expr` representing the 'isNull' check. + * @return A new `BooleanExpr` representing the `isNull` check. */ isNull(): BooleanExpr; /** + * @beta * Creates an expression that checks if a field exists in the document. * * ```typescript @@ -3875,11 +3622,11 @@ declare namespace FirebaseFirestore { * field("phoneNumber").exists(); * ``` * - * @return A new `Expr` representing the 'exists' check. + * @returns A new {@link BooleanExpr} representing the 'exists' check. */ exists(): BooleanExpr; - /** + * @beta * Creates an expression that calculates the character length of a string in UTF-8. * * ```typescript @@ -3892,6 +3639,7 @@ declare namespace FirebaseFirestore { charLength(): FunctionExpr; /** + * @beta * Creates an expression that performs a case-sensitive string comparison. * * ```typescript @@ -3899,25 +3647,26 @@ declare namespace FirebaseFirestore { * field("title").like("%guide%"); * ``` * - * @param pattern The pattern to search for. You can use "%" as a wildcard character. - * @return A new `Expr` representing the 'like' comparison. + * @param pattern The string pattern to search for. You can use "%" as a wildcard character within the pattern. + * @return A new {@link FunctionExpr} representing the 'like' comparison. */ like(pattern: string): FunctionExpr; /** + * @beta * Creates an expression that performs a case-sensitive string comparison. * * ```typescript - * // Check if the 'title' field contains the word "guide" (case-sensitive) - * field("title").like("%guide%"); + * // Check if the 'description' field matches a pattern from another field + * field("description").like(field("searchPattern")); * ``` * - * @param pattern The pattern to search for. You can use "%" as a wildcard character. - * @return A new `Expr` representing the 'like' comparison. + * @param pattern An {@link Expr} that evaluates to the string pattern to search for. You can use "%" as a wildcard character within the pattern. + * @return A new {@link FunctionExpr} representing the 'like' comparison. */ like(pattern: Expr): FunctionExpr; - /** + * @beta * Creates an expression that checks if a string contains a specified regular expression as a * substring. * @@ -3932,6 +3681,7 @@ declare namespace FirebaseFirestore { regexContains(pattern: string): BooleanExpr; /** + * @beta * Creates an expression that checks if a string contains a specified regular expression as a * substring. * @@ -3941,11 +3691,11 @@ declare namespace FirebaseFirestore { * ``` * * @param pattern The regular expression to use for the search. - * @return A new `Expr` representing the 'contains' comparison. + * @return A new {@link BooleanExpr} representing the 'contains' comparison. */ regexContains(pattern: Expr): BooleanExpr; - /** + * @beta * Creates an expression that checks if a string matches a specified regular expression. * * ```typescript @@ -3959,19 +3709,20 @@ declare namespace FirebaseFirestore { regexMatch(pattern: string): BooleanExpr; /** + * @beta * Creates an expression that checks if a string matches a specified regular expression. * * ```typescript - * // Check if the 'email' field matches a regular expression stored in field 'regex' - * field("email").regexMatch(field("regex")); + * // Check if the 'email' field matches a regular expression stored in another field. + * field("email").regexMatch(field("regexPattern")); * ``` * - * @param pattern The regular expression to use for the match. - * @return A new `Expr` representing the regular expression match. + * @param pattern An expression that evaluates to the regular expression string to use for the match. + * @return A new `BooleanExpr` representing the result of the regular expression match. */ regexMatch(pattern: Expr): BooleanExpr; - /** + * @beta * Creates an expression that checks if a string contains a specified substring. * * ```typescript @@ -3985,6 +3736,7 @@ declare namespace FirebaseFirestore { strContains(substring: string): BooleanExpr; /** + * @beta * Creates an expression that checks if a string contains the string represented by another expression. * * ```typescript @@ -3993,11 +3745,11 @@ declare namespace FirebaseFirestore { * ``` * * @param expr The expression representing the substring to search for. - * @return A new `Expr` representing the 'contains' comparison. + * @return A new {@link BooleanExpr} representing the 'contains' comparison. */ strContains(expr: Expr): BooleanExpr; - /** + * @beta * Creates an expression that checks if a string starts with a given prefix. * * ```typescript @@ -4011,20 +3763,21 @@ declare namespace FirebaseFirestore { startsWith(prefix: string): BooleanExpr; /** - * Creates an expression that checks if a string starts with a given prefix (represented as an - * expression). + * @beta + * Creates an expression that checks if the string value of the current expression starts with the string value of the given prefix expression. * * ```typescript * // Check if the 'fullName' field starts with the value of the 'firstName' field * field("fullName").startsWith(field("firstName")); * ``` * - * @param prefix The prefix expression to check for. - * @return A new `Expr` representing the 'starts with' comparison. + * @param prefix An expression whose string value will be used as the prefix to check against. + * @returns A new `BooleanExpr` representing the 'starts with' comparison result. */ startsWith(prefix: Expr): BooleanExpr; /** + * @beta * Creates an expression that checks if a string ends with a given postfix. * * ```typescript @@ -4033,11 +3786,11 @@ declare namespace FirebaseFirestore { * ``` * * @param suffix The postfix to check for. - * @return A new `Expr` representing the 'ends with' comparison. + * @return A new {@link BooleanExpr} representing the 'ends with' comparison. */ endsWith(suffix: string): BooleanExpr; - /** + * @beta * Creates an expression that checks if a string ends with a given postfix (represented as an * expression). * @@ -4050,8 +3803,8 @@ declare namespace FirebaseFirestore { * @return A new `Expr` representing the 'ends with' comparison. */ endsWith(suffix: Expr): BooleanExpr; - /** + * @beta * Creates an expression that converts a string to lowercase. * * ```typescript @@ -4062,8 +3815,8 @@ declare namespace FirebaseFirestore { * @return A new `Expr` representing the lowercase string. */ toLower(): FunctionExpr; - /** + * @beta * Creates an expression that converts a string to uppercase. * * ```typescript @@ -4074,8 +3827,8 @@ declare namespace FirebaseFirestore { * @return A new `Expr` representing the uppercase string. */ toUpper(): FunctionExpr; - /** + * @beta * Creates an expression that removes leading and trailing whitespace from a string. * * ```typescript @@ -4086,8 +3839,8 @@ declare namespace FirebaseFirestore { * @return A new `Expr` representing the trimmed string. */ trim(): FunctionExpr; - /** + * @beta * Creates an expression that concatenates string expressions together. * * ```typescript @@ -4103,8 +3856,8 @@ declare namespace FirebaseFirestore { secondString: Expr | string, ...otherStrings: Array ): FunctionExpr; - /** + * @beta * Creates an expression that reverses this string expression. * * ```typescript @@ -4115,78 +3868,64 @@ declare namespace FirebaseFirestore { * @return A new {@code Expr} representing the reversed string. */ reverse(): FunctionExpr; - /** - * Creates an expression that replaces the first occurrence of a substring within this string expression with another substring. + * @beta + * Creates an expression that calculates the length of this string expression in bytes. * * ```typescript - * // Replace the first occurrence of "hello" with "hi" in the 'message' field - * field("message").replaceFirst("hello", "hi"); + * // Calculate the length of the 'myString' field in bytes. + * field("myString").byteLength(); * ``` * - * @param find The substring to search for. - * @param replace The substring to replace the first occurrence of 'find' with. - * @return A new {@code Expr} representing the string with the first occurrence replaced. + * @return A new {@code Expr} representing the length of the string in bytes. */ - replaceFirst(find: string, replace: string): FunctionExpr; - + byteLength(): FunctionExpr; /** - * Creates an expression that replaces the first occurrence of a substring within this string expression with another substring, - * where the substring to find and the replacement substring are specified by expressions. + * @beta + * Creates an expression that computes the ceiling of a numeric value. * * ```typescript - * // Replace the first occurrence of the value in 'findField' with the value in 'replaceField' in the 'message' field - * field("message").replaceFirst(field("findField"), field("replaceField")); + * // Compute the ceiling of the 'price' field. + * field("price").ceil(); * ``` * - * @param find The expression representing the substring to search for. - * @param replace The expression representing the substring to replace the first occurrence of 'find' with. - * @return A new {@code Expr} representing the string with the first occurrence replaced. + * @return A new {@code Expr} representing the ceiling of the numeric value. */ - replaceFirst(find: Expr, replace: Expr): FunctionExpr; - + ceil(): FunctionExpr; /** - * Creates an expression that replaces all occurrences of a substring within this string expression with another substring. + * @beta + * Creates an expression that computes the floor of a numeric value. * * ```typescript - * // Replace all occurrences of "hello" with "hi" in the 'message' field - * field("message").replaceAll("hello", "hi"); + * // Compute the floor of the 'price' field. + * field("price").floor(); * ``` * - * @param find The substring to search for. - * @param replace The substring to replace all occurrences of 'find' with. - * @return A new {@code Expr} representing the string with all occurrences replaced. + * @return A new {@code Expr} representing the floor of the numeric value. */ - replaceAll(find: string, replace: string): FunctionExpr; + floor(): FunctionExpr; /** - * Creates an expression that replaces all occurrences of a substring within this string expression with another substring, - * where the substring to find and the replacement substring are specified by expressions. + * @beta + * Creates an expression that computes `e` (Euler's number) raised to the power of this expression's numeric value. * * ```typescript - * // Replace all occurrences of the value in 'findField' with the value in 'replaceField' in the 'message' field - * field("message").replaceAll(field("findField"), field("replaceField")); + * // Compute `e` to the power of the 'value' field. + * field("value").exp(); * ``` * - * @param find The expression representing the substring to search for. - * @param replace The expression representing the substring to replace all occurrences of 'find' with. - * @return A new {@code Expr} representing the string with all occurrences replaced. + * @return A new {@code FunctionExpr} representing `e` raised to the power of the numeric value. */ - replaceAll(find: Expr, replace: Expr): FunctionExpr; - + exp(): FunctionExpr; /** - * Creates an expression that calculates the length of this string expression in bytes. - * - * ```typescript - * // Calculate the length of the 'myString' field in bytes. - * field("myString").byteLength(); - * ``` + * @beta + * Creates an aggregation that counts the number of distinct values of the expression or field. * - * @return A new {@code Expr} representing the length of the string in bytes. + * @return A new `AggregateFunction` representing the 'count_distinct' aggregation. */ - byteLength(): FunctionExpr; - + countDistinct(): AggregateFunction; /** + * @beta * Accesses a value from a map (object) field using the provided key. * * ```typescript @@ -4198,8 +3937,8 @@ declare namespace FirebaseFirestore { * @return A new `Expr` representing the value associated with the given key in the map. */ mapGet(subfield: string): FunctionExpr; - /** + * @beta * Creates an aggregation that counts the number of stage inputs with valid evaluations of the * expression or field. * @@ -4211,8 +3950,8 @@ declare namespace FirebaseFirestore { * @return A new `AggregateFunction` representing the 'count' aggregation. */ count(): AggregateFunction; - /** + * @beta * Creates an aggregation that calculates the sum of a numeric field across multiple stage inputs. * * ```typescript @@ -4223,8 +3962,8 @@ declare namespace FirebaseFirestore { * @return A new `AggregateFunction` representing the 'sum' aggregation. */ sum(): AggregateFunction; - /** + * @beta * Creates an aggregation that calculates the average (mean) of a numeric field across multiple * stage inputs. * @@ -4236,8 +3975,8 @@ declare namespace FirebaseFirestore { * @return A new `AggregateFunction` representing the 'avg' aggregation. */ avg(): AggregateFunction; - /** + * @beta * Creates an aggregation that finds the minimum value of a field across multiple stage inputs. * * ```typescript @@ -4248,8 +3987,8 @@ declare namespace FirebaseFirestore { * @return A new `AggregateFunction` representing the 'min' aggregation. */ minimum(): AggregateFunction; - /** + * @beta * Creates an aggregation that finds the maximum value of a field across multiple stage inputs. * * ```typescript @@ -4260,8 +3999,8 @@ declare namespace FirebaseFirestore { * @return A new `AggregateFunction` representing the 'max' aggregation. */ maximum(): AggregateFunction; - /** + * @beta * Creates an expression that returns the larger value between this expression and another expression, based on Firestore's value type ordering. * * ```typescript @@ -4277,8 +4016,8 @@ declare namespace FirebaseFirestore { second: Expr | unknown, ...others: Array ): FunctionExpr; - /** + * @beta * Creates an expression that returns the smaller value between this expression and another expression, based on Firestore's value type ordering. * * ```typescript @@ -4294,8 +4033,8 @@ declare namespace FirebaseFirestore { second: Expr | unknown, ...others: Array ): FunctionExpr; - /** + * @beta * Creates an expression that calculates the length (number of dimensions) of this Firestore Vector expression. * * ```typescript @@ -4306,8 +4045,8 @@ declare namespace FirebaseFirestore { * @return A new {@code Expr} representing the length of the vector. */ vectorLength(): FunctionExpr; - /** + * @beta * Calculates the cosine distance between two vectors. * * ```typescript @@ -4319,72 +4058,87 @@ declare namespace FirebaseFirestore { * @return A new `Expr` representing the cosine distance between the two vectors. */ cosineDistance(vectorExpression: Expr): FunctionExpr; + /** + * @beta * Calculates the Cosine distance between two vectors. * * ```typescript - * // Calculate the Cosine distance between the 'location' field and a target location - * field("location").cosineDistance(new VectorValue([37.7749, -122.4194])); + * // Calculate the Cosine distance between the 'embedding' field and a target vector + * field("embedding").cosineDistance(FieldValue.vector([0.1, 0.2, 0.3])); + * + * // Calculate the Cosine distance using a plain number array + * field("embedding").cosineDistance([0.1, 0.2, 0.3]); * ``` * - * @param vector The other vector (as a VectorValue) to compare against. - * @return A new `Expr` representing the Cosine* distance between the two vectors. + * @param vector The other vector to compare against, provided as either a `VectorValue` object or a plain `number[]` array. + * @return A new `FunctionExpr` representing the Cosine distance between the two vectors. */ cosineDistance(vector: VectorValue | number[]): FunctionExpr; - /** - * Calculates the dot product between two vectors. + * @beta + * Calculates the dot product between the current expression (representing a vector) + * and another expression (representing a second vector). + * + * Both expressions are expected to resolve to an array of numbers (a vector) at runtime. * * ```typescript - * // Calculate the dot product between a feature vector and a target vector - * field("features").dotProduct([0.5, 0.8, 0.2]); + * // Calculate the dot product between the 'features' field and the 'targetVector' field. + * field("features").dotProduct(field("targetVector")); * ``` * - * @param vectorExpression The other vector (as an array of numbers) to calculate with. - * @return A new `Expr` representing the dot product between the two vectors. + * @param vectorExpression An {@link Expr} representing the second vector. + * @returns A new {@link FunctionExpr} representing the dot product of the two vectors. */ dotProduct(vectorExpression: Expr): FunctionExpr; /** + * @beta * Calculates the dot product between two vectors. * * ```typescript * // Calculate the dot product between a feature vector and a target vector - * field("features").dotProduct(new VectorValue([0.5, 0.8, 0.2])); + * field("features").dotProduct(FieldValue.vector([0.5, 0.8, 0.2])); * ``` * - * @param vector The other vector (as an array of numbers) to calculate with. + * @param vector The other vector to calculate the dot product with. This can be a `VectorValue` object or a plain array of numbers. * @return A new `Expr` representing the dot product between the two vectors. */ dotProduct(vector: VectorValue | number[]): FunctionExpr; /** - * Calculates the Euclidean distance between two vectors. + * @beta + * Calculates the Euclidean distance between the vector represented by this expression and another vector expression. * * ```typescript - * // Calculate the Euclidean distance between the 'location' field and a target location - * field("location").euclideanDistance([37.7749, -122.4194]); + * // Calculate the Euclidean distance between two different vector fields. + * field("vectorA").euclideanDistance(field("vectorB")); * ``` * - * @param vectorExpression The other vector (as an array of numbers) to calculate with. - * @return A new `Expr` representing the Euclidean distance between the two vectors. + * @param vectorExpression An {@link Expr} that evaluates to the second vector (an array of numbers) for the distance calculation. + * @return A new {@link FunctionExpr} representing the Euclidean distance between the two vectors. */ euclideanDistance(vectorExpression: Expr): FunctionExpr; - /** + * @beta * Calculates the Euclidean distance between two vectors. * + * The `vector` parameter can be either a `VectorValue` object or a `number[]` (array of numbers). + * * ```typescript - * // Calculate the Euclidean distance between the 'location' field and a target location - * field("location").euclideanDistance(new VectorValue([37.7749, -122.4194])); + * // Calculate the Euclidean distance between the 'location' field and a target location using a VectorValue. + * field("location").euclideanDistance(FieldValue.vector([37.7749, -122.4194])); + * + * // Calculate the Euclidean distance between the 'location' field and a target location using a number array. + * field("location").euclideanDistance([37.7749, -122.4194]); * ``` * - * @param vector The other vector (as a VectorValue) to compare against. + * @param vector The other vector (as a `VectorValue` or `number[]`) to compare against. * @return A new `Expr` representing the Euclidean distance between the two vectors. */ euclideanDistance(vector: VectorValue | number[]): FunctionExpr; - /** + * @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. * @@ -4396,8 +4150,8 @@ declare namespace FirebaseFirestore { * @return A new {@code Expr} representing the timestamp. */ unixMicrosToTimestamp(): FunctionExpr; - /** + * @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). * * ```typescript @@ -4408,8 +4162,8 @@ declare namespace FirebaseFirestore { * @return A new {@code Expr} representing the number of microseconds since epoch. */ timestampToUnixMicros(): FunctionExpr; - /** + * @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. * @@ -4421,8 +4175,8 @@ declare namespace FirebaseFirestore { * @return A new {@code Expr} representing the timestamp. */ unixMillisToTimestamp(): FunctionExpr; - /** + * @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). * * ```typescript @@ -4433,8 +4187,8 @@ declare namespace FirebaseFirestore { * @return A new {@code Expr} representing the number of milliseconds since epoch. */ timestampToUnixMillis(): FunctionExpr; - /** + * @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. * @@ -4446,8 +4200,8 @@ declare namespace FirebaseFirestore { * @return A new {@code Expr} representing the timestamp. */ unixSecondsToTimestamp(): FunctionExpr; - /** + * @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). * * ```typescript @@ -4458,8 +4212,8 @@ declare namespace FirebaseFirestore { * @return A new {@code Expr} representing the number of seconds since epoch. */ timestampToUnixSeconds(): FunctionExpr; - /** + * @beta * Creates an expression that adds a specified amount of time to this timestamp expression. * * ```typescript @@ -4472,8 +4226,8 @@ declare namespace FirebaseFirestore { * @return A new {@code Expr} representing the resulting timestamp. */ timestampAdd(unit: Expr, amount: Expr): FunctionExpr; - /** + * @beta * Creates an expression that adds a specified amount of time to this timestamp expression. * * ```typescript @@ -4495,8 +4249,8 @@ declare namespace FirebaseFirestore { | 'day', amount: number ): FunctionExpr; - /** + * @beta * Creates an expression that subtracts a specified amount of time from this timestamp expression. * * ```typescript @@ -4511,6 +4265,7 @@ declare namespace FirebaseFirestore { timestampSub(unit: Expr, amount: Expr): FunctionExpr; /** + * @beta * Creates an expression that subtracts a specified amount of time from this timestamp expression. * * ```typescript @@ -4518,9 +4273,9 @@ declare namespace FirebaseFirestore { * field("timestamp").timestampSub("day", 1); * ``` * - * @param unit The unit of time to subtract (e.g., "day", "hour"). + * @param unit The unit of time to subtract. Supported units are 'microsecond', 'millisecond', 'second', 'minute', 'hour', and 'day'. * @param amount The amount of time to subtract. - * @return A new {@code Expr} representing the resulting timestamp. + * @return A new {@code FunctionExpr} representing the resulting timestamp after subtraction. */ timestampSub( unit: @@ -4532,381 +4287,331 @@ declare namespace FirebaseFirestore { | 'day', amount: number ): FunctionExpr; - /** * @beta - * - * Creates an expression that applies a bitwise AND operation between this expression and a constant. + * Creates an expression that returns the document ID from a DocumentReference. * * ```typescript - * // Calculate the bitwise AND of 'field1' and 0xFF. - * field("field1").bitAnd(0xFF); + * // Get the document ID for the current document. + * field("__name__").documentId(); * ``` * - * @param otherBits A constant representing bits. - * @return A new {@code Expr} representing the bitwise AND operation. + * @return A new {@code Expr} representing the documentId operation. */ - bitAnd(otherBits: number | Buffer | Uint8Array): FunctionExpr; + documentId(): FunctionExpr; /** * @beta + * Creates an expression that returns a substring of the results of this expression. * - * Creates an expression that applies a bitwise AND operation between two expressions. - * - * ```typescript - * // Calculate the bitwise AND of 'field1' and 'field2'. - * field("field1").bitAnd(field("field2")); - * ``` - * - * @param bitsExpression An expression that returns bits when evaluated. - * @return A new {@code Expr} representing the bitwise AND operation. + * @param position Index of the first character of the substring. + * @param length Length of the substring. If not provided, the substring will + * end at the end of the input. */ - bitAnd(bitsExpression: Expr): FunctionExpr; - + substring(position: number, length?: number): FunctionExpr; /** * @beta + * Creates an expression that returns a substring of the results of this expression. * - * Creates an expression that applies a bitwise OR operation between this expression and a constant. - * - * ```typescript - * // Calculate the bitwise OR of 'field1' and 0xFF. - * field("field1").bitOr(0xFF); - * ``` - * - * @param otherBits A constant representing bits. - * @return A new {@code Expr} representing the bitwise OR operation. + * @param position An expression returning the index of the first character of the substring. + * @param length An expression returning the length of the substring. If not provided the + * substring will end at the end of the input. */ - bitOr(otherBits: number | Buffer | Uint8Array): FunctionExpr; + substring(position: Expr, length?: Expr): FunctionExpr; /** * @beta - * - * Creates an expression that applies a bitwise OR operation between two expressions. + * Creates an expression that indexes into an array from the beginning or end + * and returns the element. If the index exceeds the array length, an error is + * returned. A negative index, starts from the end. * * ```typescript - * // Calculate the bitwise OR of 'field1' and 'field2'. - * field("field1").bitOr(field("field2")); + * // Return the value in the 'tags' field array at index `1`. + * field('tags').arrayGet(1); * ``` * - * @param bitsExpression An expression that returns bits when evaluated. - * @return A new {@code Expr} representing the bitwise OR operation. + * @param index The index of the element to return. + * @return A new Expr representing the 'arrayGet' operation. */ - bitOr(bitsExpression: Expr): FunctionExpr; - + arrayGet(index: number): FunctionExpr; /** * @beta - * - * Creates an expression that applies a bitwise XOR operation between this expression and a constant. + * Creates an expression that indexes into an array from the beginning or end + * and returns the element. If the index exceeds the array length, an error is + * returned. A negative index, starts from the end. * * ```typescript - * // Calculate the bitwise XOR of 'field1' and 0xFF. - * field("field1").bitXor(0xFF); + * // Return the value in the tags field array at index specified by field + * // 'favoriteTag'. + * field('tags').arrayGet(field('favoriteTag')); * ``` * - * @param otherBits A constant representing bits. - * @return A new {@code Expr} representing the bitwise XOR operation. + * @param indexExpr An Expr evaluating to the index of the element to return. + * @return A new Expr representing the 'arrayGet' operation. */ - bitXor(otherBits: number | Buffer | Uint8Array): FunctionExpr; + arrayGet(indexExpr: Expr): FunctionExpr; /** * @beta - * - * Creates an expression that applies a bitwise XOR operation between two expressions. + * Creates an expression that checks if a given expression produces an error. * * ```typescript - * // Calculate the bitwise XOR of 'field1' and 'field2'. - * field("field1").bitXor(field("field2")); + * // Check if the result of a calculation is an error + * field("title").arrayContains(1).isError(); * ``` * - * @param bitsExpression An expression that returns bits when evaluated. - * @return A new {@code Expr} representing the bitwise XOR operation. + * @return A new {@code BooleanExpr} representing the 'isError' check. */ - bitXor(bitsExpression: Expr): FunctionExpr; - + isError(): BooleanExpr; /** * @beta - * - * Creates an expression that applies a bitwise NOT operation to this expression. + * Creates an expression that returns the result of the `catchExpr` argument + * if there is an error, else return the result of this expression. * * ```typescript - * // Calculate the bitwise NOT of 'field1'. - * field("field1").bitNot(); + * // Returns the first item in the title field arrays, or returns + * // the entire title field if the array is empty or the field is another type. + * field("title").arrayGet(0).ifError(field("title")); * ``` * - * @return A new {@code Expr} representing the bitwise NOT operation. + * @param catchExpr The catch expression that will be evaluated and + * returned if this expression produces an error. + * @return A new {@code Expr} representing the 'ifError' operation. */ - bitNot(): FunctionExpr; - + ifError(catchExpr: Expr): FunctionExpr; /** * @beta - * - * Creates an expression that applies a bitwise left shift operation to this expression. + * Creates an expression that returns the `catch` argument if there is an + * error, else return the result of this expression. * * ```typescript - * // Calculate the bitwise left shift of 'field1' by 2 bits. - * field("field1").bitLeftShift(2); + * // Returns the first item in the title field arrays, or returns + * // "Default Title" + * field("title").arrayGet(0).ifError("Default Title"); * ``` * - * @param y The operand constant representing the number of bits to shift. - * @return A new {@code Expr} representing the bitwise left shift operation. + * @param catchValue The value that will be returned if this expression + * produces an error. + * @return A new {@code Expr} representing the 'ifError' operation. */ - bitLeftShift(y: number): FunctionExpr; + ifError(catchValue: unknown): FunctionExpr; /** * @beta - * - * Creates an expression that applies a bitwise left shift operation to this expression. + * Creates an expression that returns `true` if the result of this expression + * is absent. Otherwise, returns `false` even if the value is `null`. * * ```typescript - * // Calculate the bitwise left shift of 'field1' by 'field2' bits. - * field("field1").bitLeftShift(field("field2")); + * // Check if the field `value` is absent. + * field("value").isAbsent(); * ``` * - * @param numberExpr The operand expression representing the number of bits to shift. - * @return A new {@code Expr} representing the bitwise left shift operation. + * @return A new {@code BooleanExpr} representing the 'isAbsent' check. */ - bitLeftShift(numberExpr: Expr): FunctionExpr; + isAbsent(): BooleanExpr; /** * @beta - * - * Creates an expression that applies a bitwise right shift operation to this expression. + * Creates an expression that checks if the result of an expression is not null. * * ```typescript - * // Calculate the bitwise right shift of 'field1' by 2 bits. - * field("field1").bitRightShift(2); + * // Check if the value of the 'name' field is not null + * field("name").isNotNull(); * ``` * - * @param right The operand constant representing the number of bits to shift. - * @return A new {@code Expr} representing the bitwise right shift operation. + * @return A new {@code BooleanExpr} representing the 'isNotNull' check. */ - bitRightShift(y: number): FunctionExpr; + isNotNull(): BooleanExpr; /** * @beta - * - * Creates an expression that applies a bitwise right shift operation to this expression. + * Creates an expression that checks if the results of this expression is NOT 'NaN' (Not a Number). * * ```typescript - * // Calculate the bitwise right shift of 'field1' by 'field2' bits. - * field("field1").bitRightShift(field("field2")); + * // Check if the result of a calculation is NOT NaN + * field("value").divide(0).isNotNan(); * ``` * - * @param numberExpr The operand expression representing the number of bits to shift. - * @return A new {@code Expr} representing the bitwise right shift operation. + * @return A new {@code Expr} representing the 'isNaN' check. */ - bitRightShift(numberExpr: Expr): FunctionExpr; + isNotNan(): BooleanExpr; /** * @beta - * - * Creates an expression that returns the document ID from a path. + * Creates an expression that removes a key from the map produced by evaluating this expression. * * ```typescript - * // Get the document ID from a path. - * field("__path__").documentId(); + * // Removes the key 'baz' from the input map. + * map({foo: 'bar', baz: true}).mapRemove('baz'); * ``` * - * @return A new {@code Expr} representing the documentId operation. + * @param key The name of the key to remove from the input map. + * @returns A new {@code FunctionExpr} representing the 'mapRemove' operation. */ - documentId(): FunctionExpr; + mapRemove(key: string): FunctionExpr; /** * @beta + * Creates an expression that removes a key from the map produced by evaluating this expression. * - * Creates an expression that returns a substring of the results of this expression. + * ```typescript + * // Removes the key 'baz' from the input map. + * map({foo: 'bar', baz: true}).mapRemove(constant('baz')); + * ``` * - * @param position Index of the first character of the substring. - * @param length Length of the substring. If not provided, the substring will - * end at the end of the input. + * @param keyExpr An expression that produces the name of the key to remove from the input map. + * @returns A new {@code FunctionExpr} representing the 'mapRemove' operation. */ - substr(position: number, length?: number): FunctionExpr; + mapRemove(keyExpr: Expr): FunctionExpr; /** * @beta + * Creates an expression that merges multiple map values. * - * Creates an expression that returns a substring of the results of this expression. - * - * @param position An expression returning the index of the first character of the substring. - * @param length An expression returning the length of the substring. If not provided the - * substring will end at the end of the input. - */ - substr(position: Expr, length?: Expr): FunctionExpr; - - /** - * @beta - * Creates an expression that indexes into an array from the beginning or end - * and returns the element. If the offset exceeds the array length, an error is - * returned. A negative offset, starts from the end. + * The first map in the merge operation is the expression on which `mapMerge` is called. * * ```typescript - * // Return the value in the 'tags' field array at index `1`. - * field('tags').arrayOffset(1); + * // Merges the map in the 'settings' field with a literal map and a map + * // conditionally returned by another expression. + * field('settings').mapMerge({ enabled: true }, cond(field('isAdmin'), { admin: true }, {})) * ``` * - * @param offset The index of the element to return. - * @return A new Expr representing the 'arrayOffset' operation. + * @param secondMap A required second map to merge. This can be a literal object + * or an expression that evaluates to a map. + * @param otherMaps Optional additional maps to merge. Each can be a literal + * object or an expression that evaluates to a map. + * + * @returns A new {@code FunctionExpr} representing the result of the map merge operation. */ - arrayOffset(offset: number): FunctionExpr; - + mapMerge( + secondMap: Record | Expr, + ...otherMaps: Array | Expr> + ): FunctionExpr; /** * @beta - * Creates an expression that indexes into an array from the beginning or end - * and returns the element. If the offset exceeds the array length, an error is - * returned. A negative offset, starts from the end. + * Creates an expression that returns the value of this expression raised to the power of another expression. * * ```typescript - * // Return the value in the tags field array at index specified by field - * // 'favoriteTag'. - * field('tags').arrayOffset(field('favoriteTag')); + * // Raise the value of the 'base' field to the power of the 'exponent' field. + * field("base").pow(field("exponent")); * ``` * - * @param offsetExpr An Expr evaluating to the index of the element to return. - * @return A new Expr representing the 'arrayOffset' operation. + * @param exponent The expression to raise this expression to the power of. + * @return A new `Expr` representing the power operation. */ - arrayOffset(offsetExpr: Expr): FunctionExpr; - + pow(exponent: Expr): FunctionExpr; /** * @beta - * - * Creates an expression that checks if a given expression produces an error. + * Creates an expression that returns the value of this expression raised to the power of a constant value. * * ```typescript - * // Check if the result of a calculation is an error - * field("title").arrayContains(1).isError(); + * // Raise the value of the 'base' field to the power of 2. + * field("base").pow(2); * ``` * - * @return A new {@code BooleanExpr} representing the 'isError' check. + * @param exponent The constant value to raise this expression to the power of. + * @return A new `Expr` representing the power operation. */ - isError(): BooleanExpr; - + pow(exponent: number): FunctionExpr; /** * @beta - * - * Creates an expression that returns the result of the `catchExpr` argument - * if there is an error, else return the result of this expression. + * Creates an expression that rounds a numeric value to the nearest whole number. * * ```typescript - * // Returns the first item in the title field arrays, or returns - * // the entire title field if the array is empty or the field is another type. - * field("title").arrayOffset(0).ifError(field("title")); + * // Round the value of the 'price' field. + * field("price").round(); * ``` * - * @param catchExpr The catch expression that will be evaluated and - * returned if this expression produces an error. - * @return A new {@code Expr} representing the 'ifError' operation. + * @return A new `Expr` representing the rounded value. */ - ifError(catchExpr: Expr): FunctionExpr; - + round(): FunctionExpr; /** * @beta - * - * Creates an expression that returns the `catch` argument if there is an - * error, else return the result of this expression. + * Creates an expression that returns the collection ID from a path. * * ```typescript - * // Returns the first item in the title field arrays, or returns - * // "Default Title" - * field("title").arrayOffset(0).ifError("Default Title"); + * // Get the collection ID from a path. + * field("__name__").collectionId(); * ``` * - * @param catchValue The value that will be returned if this expression - * produces an error. - * @return A new {@code Expr} representing the 'ifError' operation. + * @return A new {@code Expr} representing the collectionId operation. */ - ifError(catchValue: unknown): FunctionExpr; - + collectionId(): FunctionExpr; /** * @beta - * - * Creates an expression that returns `true` if the result of this expression - * is absent. Otherwise, returns `false` even if the value is `null`. + * Creates an expression that calculates the length of a string, array, map, vector, or bytes. * * ```typescript - * // Check if the field `value` is absent. - * field("value").isAbsent(); + * // Get the length of the 'name' field. + * field("name").length(); + * + * // Get the number of items in the 'cart' array. + * field("cart").length(); * ``` * - * @return A new {@code BooleanExpr} representing the 'isAbsent' check. + * @return A new `Expr` representing the length of the string, array, map, vector, or bytes. */ - isAbsent(): BooleanExpr; - + length(): FunctionExpr; /** * @beta - * - * Creates an expression that checks if tbe result of an expression is not null. + * Creates an expression that computes the natural logarithm of a numeric value. * * ```typescript - * // Check if the value of the 'name' field is not null - * field("name").isNotNull(); + * // Compute the natural logarithm of the 'value' field. + * field("value").ln(); * ``` * - * @return A new {@code BooleanExpr} representing the 'isNotNull' check. + * @return A new {@code Expr} representing the natural logarithm of the numeric value. */ - isNotNull(): BooleanExpr; - + ln(): FunctionExpr; /** * @beta - * - * Creates an expression that checks if the results of this expression is NOT 'NaN' (Not a Number). + * Creates an expression that computes the logarithm of this expression to a given base. * * ```typescript - * // Check if the result of a calculation is NOT NaN - * field("value").divide(0).isNotNan(); + * // Compute the logarithm of the 'value' field with base 10. + * field("value").log(10); * ``` * - * @return A new {@code Expr} representing the 'isNaN' check. + * @param base The base of the logarithm. + * @return A new {@code Expr} representing the logarithm of the numeric value. */ - isNotNan(): BooleanExpr; - + log(base: number): FunctionExpr; /** * @beta + * Creates an expression that computes the logarithm of this expression to a given base. * - * Creates an expression that removes a key from the map produced by evaluating this expression. - * - * ``` - * // Removes the key 'baz' from the input map. - * map({foo: 'bar', baz: true}).mapRemove('baz'); + * ```typescript + * // Compute the logarithm of the 'value' field with the base in the 'base' field. + * field("value").log(field("base")); * ``` * - * @param key The name of the key to remove from the input map. - * @returns A new {@code FirestoreFunction} representing the 'mapRemove' operation. + * @param base The base of the logarithm. + * @return A new {@code Expr} representing the logarithm of the numeric value. */ - mapRemove(key: string): FunctionExpr; + log(base: Expr): FunctionExpr; /** * @beta + * Creates an expression that computes the square root of a numeric value. * - * Creates an expression that removes a key from the map produced by evaluating this expression. - * - * ``` - * // Removes the key 'baz' from the input map. - * map({foo: 'bar', baz: true}).mapRemove(constant('baz')); + * ```typescript + * // Compute the square root of the 'value' field. + * field("value").sqrt(); * ``` * - * @param keyExpr An expression that produces the name of the key to remove from the input map. - * @returns A new {@code FirestoreFunction} representing the 'mapRemove' operation. + * @return A new {@code Expr} representing the square root of the numeric value. */ - mapRemove(keyExpr: Expr): FunctionExpr; - + sqrt(): FunctionExpr; /** * @beta + * Creates an expression that reverses a string. * - * Creates an expression that merges multiple map values. - * - * ``` - * // 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 }, cond(field('isAdmin'), { admin: true}, {}) + * ```typescript + * // Reverse the value of the 'myString' field. + * field("myString").strReverse(); * ``` * - * @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 {@code FirestoreFunction} representing the 'mapMerge' operation. + * @return A new {@code Expr} representing the reversed string. */ - mapMerge( - secondMap: Record | Expr, - ...otherMaps: Array | Expr> - ): FunctionExpr; - + strReverse(): FunctionExpr; + // TODO(new-expression): Add new expression method declarations above this line /** + * @beta * Creates an {@link Ordering} that sorts documents in ascending order based on this expression. * * ```typescript @@ -4918,8 +4623,8 @@ declare namespace FirebaseFirestore { * @return A new `Ordering` for ascending sorting. */ ascending(): Ordering; - /** + * @beta * Creates an {@link Ordering} that sorts documents in descending order based on this expression. * * ```typescript @@ -4931,8 +4636,8 @@ declare namespace FirebaseFirestore { * @return A new `Ordering` for descending sorting. */ descending(): Ordering; - /** + * @beta * Assigns an alias to this expression. * * Aliases are useful for renaming fields in the output of a stage or for giving meaningful @@ -4945,15 +4650,13 @@ declare namespace FirebaseFirestore { * ``` * * @param name The alias to assign to this expression. - * @return A new {@link ExprWithAlias} that wraps this + * @return A new {@link AliasedExpr} that wraps this * expression and associates it with the provided alias. */ - as(name: string): ExprWithAlias; + as(name: string): AliasedExpr; } - /** * @beta - * * An interface that represents a selectable expression. */ export interface Selectable { @@ -4964,14 +4667,27 @@ declare namespace FirebaseFirestore { /** * @beta - * - * A class that represents an aggregate function. + * Represents an aggregate function used within Firestore pipelines. + * Aggregate functions perform a calculation across a set of documents and return a single result, + * such as counting documents, summing numeric fields, or finding minimum/maximum values. */ export class AggregateFunction { + /** + * @beta + * @property exprType The type of the aggregate expression, indicating the specific aggregate function (e.g., COUNT, SUM, AVG). + */ exprType: ExprType; - constructor(name: string, params: Expr[]); /** + * @beta + * @private + * @internal + * @param name + * @param params + */ + constructor(name: string, params: Expr[]); + /** + * @beta * Assigns an alias to this AggregateFunction. The alias specifies the name that * the aggregated value will have in the output document. * @@ -4982,63 +4698,119 @@ declare namespace FirebaseFirestore { * ``` * * @param name The alias to assign to this AggregateFunction. - * @return A new {@link AggregateWithAlias} that wraps this + * @return A new {@link AliasedAggregate} that wraps this * AggregateFunction and associates it with the provided alias. */ - as(name: string): AggregateWithAlias; + as(name: string): AliasedAggregate; } /** * @beta - * - * An AggregateFunction with alias. + * Represents an {@link AggregateFunction} that has been assigned an alias. + * This class is used to associate an aggregate result with a name. */ - export class AggregateWithAlias { + export class AliasedAggregate { + /** + * @beta + * The underlying {@link AggregateFunction} that this aliased aggregate wraps. + */ readonly aggregate: AggregateFunction; + + /** + * @beta + * Specifies the name of the property that will contain the aggregate result in the output document. + */ readonly alias: string; } /** * @beta + * Represents an expression that has been assigned an alias using the `.as()` method. + * + * This class wraps an existing {@link Expr} and associates it with a user-defined alias, + * allowing the expression's result to be referred to by name in the output + * of a Firestore pipeline query. */ - export class ExprWithAlias implements Selectable { + export class AliasedExpr implements Selectable { + /** + * @beta + * @internal Specifies that the instance is an AliasedExpr. + */ exprType: ExprType; + + /** + * @beta + * Specifies that this class is selectable, meaning it contains an {@link Expr} and an alias, + * and can be provided to the Select stage of a pipeline. + */ selectable: true; + /** + * @beta + * The underlying expression that is being aliased. + */ readonly expr: Expr; + + /** + * @beta + * Specifies the name of the property that will contain the aggregate result in the output document. + */ readonly alias: string; } /** * @beta + * Represents a reference to a field within a Firestore document or an output from a {@link Pipeline} stage. * - * Represents a reference to a field in a Firestore document, or outputs of a {@link Pipeline} stage. + * This class extends {@link Expr}. It is a type of expression that can be evaluated + * within Firestore Pipelines. It also implements {@link Selectable}, + * meaning instances of `Field` can be used to specify fields for selection in the {@link Pipeline.select} stage. * - *

    Field references are used to access document field values in expressions and to specify fields - * for sorting, filtering, and projecting data in Firestore pipelines. - * - *

    You can create a `Field` instance using the static {@link #of} method: - * - * ```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"); - * ``` + * `Field` instances are fundamental for constructing expressions that access document field values, + * and for defining criteria for sorting, filtering, and projecting data in Firestore Pipelines. */ export class Field extends Expr implements Selectable { + /** + * @beta + * @internal Specifies that the instance is a Field. + */ readonly exprType: ExprType; + /** + * @beta + * Specifies that this class is selectable, meaning it contains an {@link Expr} and an alias, + * and can be provided to the Select stage of a pipeline. + */ selectable: true; - + /** + * @beta + * Returns the name of the field. + * + * @example + * ```typescript + * const name = field("price").fieldName(); + * console.log(name); // "price" + * ``` + * + * @returns The name of the field. + */ fieldName(): string; - + /** + * @beta + * Returns the alias of the field, which is the field-name itself. + * + * @returns The field name itself. + */ get alias(): string; - + /** + * @beta + * Self-referential getter that returns this. + * + * @returns This {@link Field} object. + */ get expr(): Expr; } - /** + * @beta * Creates a {@code Field} instance representing the field at the given path. * * The path can be a simple field name (e.g., "name") or a dot-separated path to a nested field @@ -5056,14 +4828,20 @@ declare namespace FirebaseFirestore { * @return A new {@code Field} instance representing the specified field. */ export function field(name: string): Field; + /** + * @beta + * Creates a new Field instance from a given FieldPath. + * + * @param path The FieldPath to convert into a Field. + * @returns A new {@link Field} instance representing the specified path. + */ export function field(path: FieldPath): Field; /** * @beta + * Represents a constant value that can be used as part of a Firestore pipeline expression. * - * Represents a constant value that can be used in a Firestore pipeline expression. - * - * You can create a `Constant` instance using the static {@link #of} method: + * Instances of `Constant` are typically created via the top-level `constant()` function. * * ```typescript * // Create a Constant instance for the number 10 @@ -5076,622 +4854,262 @@ declare namespace FirebaseFirestore { export class Constant extends Expr { readonly exprType: ExprType; } - /** + * @beta * Creates a `Constant` instance for a number value. * * @param value The number value. * @return A new `Constant` instance. */ export function constant(value: number): Constant; - /** + * @beta * Creates a `Constant` instance for a string value. * * @param value The string value. * @return A new `Constant` instance. */ export function constant(value: string): Constant; - /** + * @beta * Creates a `Constant` instance for a boolean value. * * @param value The boolean value. * @return A new `Constant` instance. */ export function constant(value: boolean): Constant; - /** + * @beta * Creates a `Constant` instance for a null value. * * @param value The null value. * @return A new `Constant` instance. */ export function constant(value: null): Constant; - /** + * @beta * Creates a `Constant` instance for a GeoPoint value. * * @param value The GeoPoint value. * @return A new `Constant` instance. */ export function constant(value: GeoPoint): Constant; - /** + * @beta * Creates a `Constant` instance for a Timestamp value. * * @param value The Timestamp value. * @return A new `Constant` instance. */ - export function constant(value: Timestamp): Constant; - - /** - * Creates a `Constant` instance for a Date value. - * - * @param value The Date value. - * @return A new `Constant` instance. - */ - export function constant(value: Date): Constant; - - /** - * Creates a `Constant` instance for a Buffer | Uint8Array value. - * - * @param value The Buffer | Uint8Array value. - * @return A new `Constant` instance. - */ - export function constant(value: Buffer | Uint8Array): Constant; - - /** - * Creates a `Constant` instance for a DocumentReference value. - * - * @param value The DocumentReference value. - * @return A new `Constant` instance. - */ - export function constant(value: DocumentReference): Constant; - - /** - * Creates a `Constant` instance for a VectorValue value. - * - * @param value The VectorValue value. - * @return A new `Constant` instance. - */ - export function constant(value: VectorValue): Constant; - - /** - * Creates a `Constant` instance for a VectorValue value. - * - * ```typescript - * // Create a Constant instance for a vector value - * const vectorConstant = constantVector([1, 2, 3]); - * ``` - * - * @param value The VectorValue value. - * @return A new `Constant` instance. - */ - export function constantVector(value: number[] | VectorValue): Constant; - - /** - * @beta - * - * This class defines the base class for Firestore {@link 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 and}, {@link eq}, - * or the methods on {@link Expr} ({@link Expr#eq}, {@link Expr#lt}, etc.) to construct new Function instances. - */ - export class FunctionExpr extends Expr { - readonly exprType: ExprType; - - constructor(name: string, params: Expr[]); - } - - /** - * @beta - * - * An interface that represents a filter condition. - */ - export class BooleanExpr extends FunctionExpr { - filterable: true; - - /** - * Creates an aggregation that finds the count of input documents satisfying - * this boolean expression. - * - * ```typescript - * // Find the count of documents with a score greater than 90 - * field("score").gt(90).countIf().as("highestScore"); - * ``` - * - * @return A new `AggregateFunction` representing the 'countIf' aggregation. - */ - countIf(): AggregateFunction; - - /** - * Creates an expression that negates this boolean expression. - * - * ```typescript - * // Find documents where the 'tags' field does not contain 'completed' - * field("tags").arrayContains("completed").not(); - * ``` - * - * @return A new {@code Expr} representing the negated filter condition. - */ - not(): BooleanExpr; - } - - /** - * @beta - * Creates an aggregation that counts the number of stage inputs where the provided - * boolean expression evaluates to true. - * - * ```typescript - * // Count the number of documents where 'is_active' field equals true - * countIf(field("is_active").eq(true)).as("numActiveDocuments"); - * ``` - * - * @param booleanExpr - The boolean expression to evaluate on each input. - * @returns A new `AggregateFunction` representing the 'countIf' aggregation. - */ - export function countIf(booleanExpr: BooleanExpr): AggregateFunction; - - /** - * @beta - * Creates an expression that return a pseudo-random value of type double in the - * range of [0, 1), inclusive of 0 and exclusive of 1. - * - * @returns A new `Expr` representing the 'rand' function. - */ - export function rand(): FunctionExpr; - - /** - * @beta - * - * Creates an expression that applies a bitwise AND operation between a field and a constant. - * - * ```typescript - * // Calculate the bitwise AND of 'field1' and 0xFF. - * bitAnd("field1", 0xFF); - * ``` - * - * @param field The left operand field name. - * @param otherBits A constant representing bits. - * @return A new {@code Expr} representing the bitwise AND operation. - */ - export function bitAnd( - field: string, - otherBits: number | Buffer | Uint8Array - ): FunctionExpr; - /** - * @beta - * - * Creates an expression that applies a bitwise AND operation between a field and an expression. - * - * ```typescript - * // Calculate the bitwise AND of 'field1' and 'field2'. - * bitAnd("field1", field("field2")); - * ``` - * - * @param field The left operand field name. - * @param bitsExpression An expression that returns bits when evaluated. - * @return A new {@code Expr} representing the bitwise AND operation. - */ - export function bitAnd(field: string, bitsExpression: Expr): FunctionExpr; - /** - * @beta - * - * Creates an expression that applies a bitwise AND operation between an expression and a constant. - * - * ```typescript - * // Calculate the bitwise AND of 'field1' and 0xFF. - * bitAnd(field("field1"), 0xFF); - * ``` - * - * @param bitsExpression An expression returning bits. - * @param otherBits A constant representing bits. - * @return A new {@code Expr} representing the bitwise AND operation. - */ - export function bitAnd( - bitsExpression: Expr, - otherBits: number | Buffer | Uint8Array - ): FunctionExpr; - /** - * @beta - * - * Creates an expression that applies a bitwise AND operation between two expressions. - * - * ```typescript - * // Calculate the bitwise AND of 'field1' and 'field2'. - * bitAnd(field("field1"), field("field2")); - * ``` - * - * @param bitsExpression An expression that returns bits when evaluated. - * @param otherBitsExpression An expression that returns bits when evaluated. - * @return A new {@code Expr} representing the bitwise AND operation. - */ - export function bitAnd( - bitsExpression: Expr, - otherBitsExpression: Expr - ): FunctionExpr; - - /** - * @beta - * - * Creates an expression that applies a bitwise OR operation between a field and a constant. - * - * ```typescript - * // Calculate the bitwise OR of 'field1' and 0xFF. - * bitOr("field1", 0xFF); - * ``` - * - * @param field The left operand field name. - * @param otherBits A constant representing bits. - * @return A new {@code Expr} representing the bitwise OR operation. - */ - export function bitOr( - field: string, - otherBits: number | Buffer | Uint8Array - ): FunctionExpr; - /** - * @beta - * - * Creates an expression that applies a bitwise OR operation between a field and an expression. - * - * ```typescript - * // Calculate the bitwise OR of 'field1' and 'field2'. - * bitOr("field1", field("field2")); - * ``` - * - * @param field The left operand field name. - * @param bitsExpression An expression that returns bits when evaluated. - * @return A new {@code Expr} representing the bitwise OR operation. - */ - export function bitOr(field: string, bitsExpression: Expr): FunctionExpr; - /** - * @beta - * - * Creates an expression that applies a bitwise OR operation between an expression and a constant. - * - * ```typescript - * // Calculate the bitwise OR of 'field1' and 0xFF. - * bitOr(field("field1"), 0xFF); - * ``` - * - * @param bitsExpression An expression returning bits. - * @param otherBits A constant representing bits. - * @return A new {@code Expr} representing the bitwise OR operation. - */ - export function bitOr( - bitsExpression: Expr, - otherBits: number | Buffer | Uint8Array - ): FunctionExpr; - /** - * @beta - * - * Creates an expression that applies a bitwise OR operation between two expressions. - * - * ```typescript - * // Calculate the bitwise OR of 'field1' and 'field2'. - * bitOr(field("field1"), field("field2")); - * ``` - * - * @param bitsExpression An expression that returns bits when evaluated. - * @param otherBitsExpression An expression that returns bits when evaluated. - * @return A new {@code Expr} representing the bitwise OR operation. - */ - export function bitOr( - bitsExpression: Expr, - otherBitsExpression: Expr - ): FunctionExpr; - - /** - * @beta - * - * Creates an expression that applies a bitwise XOR operation between a field and a constant. - * - * ```typescript - * // Calculate the bitwise XOR of 'field1' and 0xFF. - * bitXor("field1", 0xFF); - * ``` - * - * @param field The left operand field name. - * @param otherBits A constant representing bits. - * @return A new {@code Expr} representing the bitwise XOR operation. - */ - export function bitXor( - field: string, - otherBits: number | Buffer | Uint8Array - ): FunctionExpr; - /** - * @beta - * - * Creates an expression that applies a bitwise XOR operation between a field and an expression. - * - * ```typescript - * // Calculate the bitwise XOR of 'field1' and 'field2'. - * bitXor("field1", field("field2")); - * ``` - * - * @param field The left operand field name. - * @param bitsExpression An expression that returns bits when evaluated. - * @return A new {@code Expr} representing the bitwise XOR operation. - */ - export function bitXor(field: string, bitsExpression: Expr): FunctionExpr; - /** - * @beta - * - * Creates an expression that applies a bitwise XOR operation between an expression and a constant. - * - * ```typescript - * // Calculate the bitwise XOR of 'field1' and 0xFF. - * bitXor(field("field1"), 0xFF); - * ``` - * - * @param bitsExpression An expression returning bits. - * @param otherBits A constant representing bits. - * @return A new {@code Expr} representing the bitwise XOR operation. - */ - export function bitXor( - bitsExpression: Expr, - otherBits: number | Buffer | Uint8Array - ): FunctionExpr; - /** - * @beta - * - * Creates an expression that applies a bitwise XOR operation between two expressions. - * - * ```typescript - * // Calculate the bitwise XOR of 'field1' and 'field2'. - * bitXor(field("field1"), field("field2")); - * ``` - * - * @param bitsExpression An expression that returns bits when evaluated. - * @param otherBitsExpression An expression that returns bits when evaluated. - * @return A new {@code Expr} representing the bitwise XOR operation. - */ - export function bitXor( - bitsExpression: Expr, - otherBitsExpression: Expr - ): FunctionExpr; - - /** - * @beta - * - * Creates an expression that applies a bitwise NOT operation to a field. - * - * ```typescript - * // Calculate the bitwise NOT of 'field1'. - * bitNot("field1"); - * ``` - * - * @param field The operand field name. - * @return A new {@code Expr} representing the bitwise NOT operation. - */ - export function bitNot(field: string): FunctionExpr; - /** - * @beta - * - * Creates an expression that applies a bitwise NOT operation to an expression. - * - * ```typescript - * // Calculate the bitwise NOT of 'field1'. - * bitNot(field("field1")); - * ``` - * - * @param bitsValueExpression An expression that returns bits when evaluated. - * @return A new {@code Expr} representing the bitwise NOT operation. - */ - export function bitNot(bitsValueExpression: Expr): FunctionExpr; - + export function constant(value: Timestamp): Constant; /** * @beta + * Creates a `Constant` instance for a Date value. * - * Creates an expression that applies a bitwise left shift operation between a field and a constant. - * - * ```typescript - * // Calculate the bitwise left shift of 'field1' by 2 bits. - * bitLeftShift("field1", 2); - * ``` - * - * @param field The left operand field name. - * @param y The right operand constant representing the number of bits to shift. - * @return A new {@code Expr} representing the bitwise left shift operation. + * @param value The Date value. + * @return A new `Constant` instance. */ - export function bitLeftShift(field: string, y: number): FunctionExpr; + export function constant(value: Date): Constant; /** * @beta + * Creates a `Constant` instance for a Buffer | Uint8Array value. * - * Creates an expression that applies a bitwise left shift operation between a field and an expression. - * - * ```typescript - * // Calculate the bitwise left shift of 'field1' by 'field2' bits. - * bitLeftShift("field1", field("field2")); - * ``` - * - * @param field The left operand field name. - * @param numberExpr The right operand expression representing the number of bits to shift. - * @return A new {@code Expr} representing the bitwise left shift operation. + * @param value The Buffer | Uint8Array value. + * @return A new `Constant` instance. */ - export function bitLeftShift(field: string, numberExpr: Expr): FunctionExpr; + export function constant(value: Buffer | Uint8Array): Constant; /** * @beta + * Creates a `Constant` instance for a DocumentReference value. * - * Creates an expression that applies a bitwise left shift operation between an expression and a constant. - * - * ```typescript - * // Calculate the bitwise left shift of 'field1' by 2 bits. - * bitLeftShift(field("field1"), 2); - * ``` - * - * @param xValue An expression returning bits. - * @param y The right operand constant representing the number of bits to shift. - * @return A new {@code Expr} representing the bitwise left shift operation. + * @param value The DocumentReference value. + * @return A new `Constant` instance. */ - export function bitLeftShift(xValue: Expr, y: number): FunctionExpr; + export function constant(value: DocumentReference): Constant; /** * @beta + * Creates a `Constant` instance for a VectorValue value. * - * Creates an expression that applies a bitwise left shift operation between two expressions. - * - * ```typescript - * // Calculate the bitwise left shift of 'field1' by 'field2' bits. - * bitLeftShift(field("field1"), field("field2")); - * ``` - * - * @param xValue An expression returning bits. - * @param numberExpr The right operand expression representing the number of bits to shift. - * @return A new {@code Expr} representing the bitwise left shift operation. + * @param value The VectorValue value. + * @return A new `Constant` instance. */ - export function bitLeftShift(xValue: Expr, numberExpr: Expr): FunctionExpr; + export function constant(value: VectorValue): Constant; /** * @beta + * Represents an expression that encapsulates a function call within the Firestore Pipelines. * - * Creates an expression that applies a bitwise right shift operation between a field and a constant. + * `FunctionExpr` extends {@link Expr} and is used to build complex queries and transformations + * by applying various functions (e.g., `and`, `eq`, `ceil`) to fields or other expressions. + * + * You typically do not instantiate `FunctionExpr` directly. Instead, use the provided + * top-level functions (like {@link and}, {@link eq}, {@link ceil}) or methods available + * on {@link Expr} instances (e.g., {@link Expr#eq}, {@link Expr#lt}) to construct + * `FunctionExpr` instances. * * ```typescript - * // Calculate the bitwise right shift of 'field1' by 2 bits. - * bitRightShift("field1", 2); - * ``` + * // Example of creating a FunctionExpr indirectly using helper functions: + * const priceGreaterThan10 = field("price").gt(10); + * const combinedCondition = and(priceGreaterThan10, field("category").eq("books")); * - * @param field The left operand field name. - * @param y The right operand constant representing the number of bits to shift. - * @return A new {@code Expr} representing the bitwise right shift operation. + * // 'priceGreaterThan10' and 'combinedCondition' are instances of FunctionExpr. + * ``` */ - export function bitRightShift(field: string, y: number): FunctionExpr; + export class FunctionExpr extends Expr { + /** + * @beta + * @internal + * Indicates that this expression is a `FunctionExpr`. + */ + readonly exprType: ExprType; + /** + * @beta + * @private + * @internal + * + * Initializes a new `FunctionExpr` instance with the given function name and parameters. + * + * @param name The name of the function. + * @param params An array of `Expr` instances representing the parameters of the function. + */ + constructor(name: string, params: Expr[]); + } /** * @beta + * An expression that evaluates to a boolean value. * - * Creates an expression that applies a bitwise right shift operation between a field and an expression. - * - * ```typescript - * // Calculate the bitwise right shift of 'field1' by 'field2' bits. - * bitRightShift("field1", field("field2")); - * ``` + * This expression type is useful for filter conditions. * - * @param field The left operand field name. - * @param numberExpr The right operand expression representing the number of bits to shift. - * @return A new {@code Expr} representing the bitwise right shift operation. */ - export function bitRightShift( - field: string, - numberExpr: Expr - ): FunctionExpr; + export class BooleanExpr extends FunctionExpr { + /** + * @beta + * @internal + * @private + */ + returnType: 'boolean'; + /** + * @beta + * Creates an aggregation that finds the count of input documents satisfying + * this boolean expression. + * + * ```typescript + * // Find the count of documents with a score greater than 90 + * field("score").gt(90).countIf().as("highestScore"); + * ``` + * + * @return A new `AggregateFunction` representing the 'countIf' aggregation. + */ + countIf(): AggregateFunction; + /** + * @beta + * Creates an expression that negates this boolean expression. + * + * ```typescript + * // Find documents where the 'tags' field does not contain 'completed' + * field("tags").arrayContains("completed").not(); + * ``` + * + * @return A new {@code Expr} representing the negated filter condition. + */ + not(): BooleanExpr; + } /** * @beta - * - * Creates an expression that applies a bitwise right shift operation between an expression and a constant. + * Creates an aggregation that counts the number of stage inputs where the provided + * boolean expression evaluates to true. * * ```typescript - * // Calculate the bitwise right shift of 'field1' by 2 bits. - * bitRightShift(field("field1"), 2); + * // Count the number of documents where 'is_active' field equals true + * countIf(field("is_active").eq(true)).as("numActiveDocuments"); * ``` * - * @param xValue An expression returning bits. - * @param y The right operand constant representing the number of bits to shift. - * @return A new {@code Expr} representing the bitwise right shift operation. + * @param booleanExpr - The boolean expression to evaluate on each input. + * @returns A new `AggregateFunction` representing the 'countIf' aggregation. */ - export function bitRightShift(xValue: Expr, y: number): FunctionExpr; + export function countIf(booleanExpr: BooleanExpr): AggregateFunction; /** * @beta + * Creates an expression that return a pseudo-random value of type double in the + * range of [0, 1), inclusive of 0 and exclusive of 1. * - * Creates an expression that applies a bitwise right shift operation between two expressions. - * - * ```typescript - * // Calculate the bitwise right shift of 'field1' by 'field2' bits. - * bitRightShift(field("field1"), field("field2")); - * ``` - * - * @param xValue An expression returning bits. - * @param right The right operand expression representing the number of bits to shift. - * @return A new {@code Expr} representing the bitwise right shift operation. + * @returns A new `Expr` representing the 'rand' function. */ - export function bitRightShift(xValue: Expr, numberExpr: Expr): FunctionExpr; - + export function rand(): FunctionExpr; /** * @beta * Creates an expression that indexes into an array from the beginning or end - * and return the element. If the offset exceeds the array length, an error is - * returned. A negative offset, starts from the end. + * and return the element. If the index exceeds the array length, an error is + * returned. A negative index, starts from the end. * * ```typescript * // Return the value in the tags field array at index 1. - * arrayOffset('tags', 1); + * arrayGet('tags', 1); * ``` * * @param arrayField The name of the array field. - * @param offset The index of the element to return. - * @return A new Expr representing the 'arrayOffset' operation. + * @param index The index of the element to return. + * @return A new Expr representing the 'arrayGet' operation. */ - export function arrayOffset( - arrayField: string, - offset: number - ): FunctionExpr; - + export function arrayGet(arrayField: string, index: number): FunctionExpr; /** * @beta * Creates an expression that indexes into an array from the beginning or end - * and return the element. If the offset exceeds the array length, an error is - * returned. A negative offset, starts from the end. + * and return the element. If the index exceeds the array length, an error is + * returned. A negative index, starts from the end. * * ```typescript * // Return the value in the tags field array at index specified by field * // 'favoriteTag'. - * arrayOffset('tags', field('favoriteTag')); + * arrayGet('tags', field('favoriteTag')); * ``` * * @param arrayField The name of the array field. - * @param offsetExpr An Expr evaluating to the index of the element to return. - * @return A new Expr representing the 'arrayOffset' operation. + * @param indexExpr An Expr evaluating to the index of the element to return. + * @return A new Expr representing the 'arrayGet' operation. */ - export function arrayOffset( - arrayField: string, - offsetExpr: Expr - ): FunctionExpr; - + export function arrayGet(arrayField: string, indexExpr: Expr): FunctionExpr; /** * @beta * Creates an expression that indexes into an array from the beginning or end - * and return the element. If the offset exceeds the array length, an error is - * returned. A negative offset, starts from the end. + * and return the element. If the index exceeds the array length, an error is + * returned. A negative index, starts from the end. * * ```typescript * // Return the value in the tags field array at index 1. - * arrayOffset(field('tags'), 1); + * arrayGet(field('tags'), 1); * ``` * * @param arrayExpression An Expr evaluating to an array. - * @param offset The index of the element to return. - * @return A new Expr representing the 'arrayOffset' operation. + * @param index The index of the element to return. + * @return A new Expr representing the 'arrayGet' operation. */ - export function arrayOffset( + export function arrayGet( arrayExpression: Expr, - offset: number + index: number ): FunctionExpr; - /** * @beta * Creates an expression that indexes into an array from the beginning or end - * and return the element. If the offset exceeds the array length, an error is - * returned. A negative offset, starts from the end. + * and return the element. If the index exceeds the array length, an error is + * returned. A negative index, starts from the end. * * ```typescript * // Return the value in the tags field array at index specified by field * // 'favoriteTag'. - * arrayOffset(field('tags'), field('favoriteTag')); + * arrayGet(field('tags'), field('favoriteTag')); * ``` * * @param arrayExpression An Expr evaluating to an array. - * @param offsetExpr An Expr evaluating to the index of the element to return. - * @return A new Expr representing the 'arrayOffset' operation. + * @param indexExpr An Expr evaluating to the index of the element to return. + * @return A new Expr representing the 'arrayGet' operation. */ - export function arrayOffset( + export function arrayGet( arrayExpression: Expr, - offsetExpr: Expr + indexExpr: Expr ): FunctionExpr; - /** * @beta - * * Creates an expression that checks if a given expression produces an error. * * ```typescript @@ -5703,17 +5121,15 @@ declare namespace FirebaseFirestore { * @return A new {@code Expr} representing the 'isError' check. */ export function isError(value: Expr): BooleanExpr; - /** * @beta - * * Creates an expression that returns the `catch` argument if there is an * error, else return the result of the `try` argument evaluation. * * ```typescript * // Returns the first item in the title field arrays, or returns * // the entire title field if the array is empty or the field is another type. - * ifError(field("title").arrayOffset(0), field("title")); + * ifError(field("title").arrayGet(0), field("title")); * ``` * * @param tryExpr The try expression. @@ -5722,17 +5138,15 @@ declare namespace FirebaseFirestore { * @return A new {@code Expr} representing the 'ifError' operation. */ export function ifError(tryExpr: Expr, catchExpr: Expr): FunctionExpr; - /** * @beta - * * Creates an expression that returns the `catch` argument if there is an * error, else return the result of the `try` argument evaluation. * * ```typescript * // Returns the first item in the title field arrays, or returns * // "Default Title" - * ifError(field("title").arrayOffset(0), "Default Title"); + * ifError(field("title").arrayGet(0), "Default Title"); * ``` * * @param tryExpr The try expression. @@ -5741,10 +5155,8 @@ declare namespace FirebaseFirestore { * @return A new {@code Expr} representing the 'ifError' operation. */ export function ifError(tryExpr: Expr, catchValue: unknown): FunctionExpr; - /** * @beta - * * Creates an expression that returns `true` if a value is absent. Otherwise, * returns `false` even if the value is `null`. * @@ -5757,10 +5169,8 @@ declare namespace FirebaseFirestore { * @return A new {@code Expr} representing the 'isAbsent' check. */ export function isAbsent(value: Expr): BooleanExpr; - /** * @beta - * * Creates an expression that returns `true` if a field is absent. Otherwise, * returns `false` even if the field value is `null`. * @@ -5776,38 +5186,35 @@ declare namespace FirebaseFirestore { /** * @beta - * - * Creates an expression that checks if an expression evaluates to 'NaN' (Not a Number). + * Creates an expression that checks if an expression evaluates to 'null'. * * ```typescript - * // Check if the result of a calculation is NaN - * isNaN(field("value").divide(0)); + * // Check if the 'lastLogin' field is null + * isNull(field("lastLogin")); * ``` * - * @param value The expression to check. - * @return A new {@code Expr} representing the 'isNaN' check. + * @param value The expression to check for null. + * @return A new {@code BooleanExpr} representing the 'isNull' check. */ export function isNull(value: Expr): BooleanExpr; /** * @beta - * - * Creates an expression that checks if a field's value evaluates to 'NaN' (Not a Number). + * Creates an expression that checks if a field's value evaluates to 'null'. * * ```typescript - * // Check if the result of a calculation is NaN - * isNaN("value"); + * // Check if the 'endDate' field is null. + * isNull("endDate"); * ``` * * @param value The name of the field to check. - * @return A new {@code Expr} representing the 'isNaN' check. + * @return A new {@code BooleanExpr} representing the 'isNull' check. */ export function isNull(value: string): BooleanExpr; /** * @beta - * - * Creates an expression that checks if tbe result of an expression is not null. + * Creates an expression that checks if the result of an expression is not null. * * ```typescript * // Check if the value of the 'name' field is not null @@ -5815,14 +5222,13 @@ declare namespace FirebaseFirestore { * ``` * * @param value The expression to check. - * @return A new {@code Expr} representing the 'isNaN' check. + * @return A new {@code BooleanExpr} representing the 'not null' check. */ export function isNotNull(value: Expr): BooleanExpr; /** * @beta - * - * Creates an expression that checks if tbe value of a field is not null. + * Creates an expression that checks if the value of a field is not null. * * ```typescript * // Check if the value of the 'name' field is not null @@ -5830,43 +5236,39 @@ declare namespace FirebaseFirestore { * ``` * * @param value The name of the field to check. - * @return A new {@code Expr} representing the 'isNaN' check. + * @return A new {@code BooleanExpr} representing the 'not null' check. */ export function isNotNull(value: string): BooleanExpr; /** * @beta - * - * Creates an expression that checks if the results of this expression is NOT 'NaN' (Not a Number). + * Creates an expression that evaluates to `true` if the given expression's result is not `NaN` (Not a Number), and `false` otherwise. * * ```typescript * // Check if the result of a calculation is NOT NaN - * isNotNaN(field("value").divide(0)); + * isNotNan(field("value").divide(0)); * ``` * - * @param value The expression to check. - * @return A new {@code Expr} representing the 'isNotNaN' check. + * @param value The expression to check for `NaN`. + * @return A new {@code BooleanExpr} representing the result of the `isNotNaN` check. */ export function isNotNan(value: Expr): BooleanExpr; /** * @beta - * - * Creates an expression that checks if the results of this expression is NOT 'NaN' (Not a Number). + * Creates an expression that checks if a numeric value is not NaN (Not a Number). * * ```typescript - * // Check if the value of a field is NOT NaN - * isNotNaN("value"); + * // Check if the value of a field is not NaN + * isNotNan("value"); * ``` * * @param value The name of the field to check. - * @return A new {@code Expr} representing the 'isNotNaN' check. + * @return A new {@code BooleanExpr} representing the 'isNotNan' check. */ export function isNotNan(value: string): BooleanExpr; - /** * @beta - * * Creates an expression that removes a key from the map at the specified field name. * * ``` @@ -5878,52 +5280,57 @@ declare namespace FirebaseFirestore { * @param key The name of the key to remove from the input map. */ export function mapRemove(mapField: string, key: string): FunctionExpr; + /** * @beta + * Creates an expression that removes a key from the map produced by evaluating another expression. * - * Creates an expression that removes a key from the map produced by evaluating an expression. - * - * ``` + * ```typescript * // Removes the key 'baz' from the input map. * mapRemove(map({foo: 'bar', baz: true}), 'baz'); * ``` * - * @param mapExpr An expression return a map value. + * @param mapExpr An expression that evaluates to a map value. * @param key The name of the key to remove from the input map. + * @returns A new {@link FunctionExpr} representing the map with the specified key removed. */ export function mapRemove(mapExpr: Expr, key: string): FunctionExpr; + /** * @beta - * * Creates an expression that removes a key from the map at the specified field name. * - * ``` + * ```typescript * // Removes the key 'city' field from the map in the address field of the input document. * mapRemove('address', constant('city')); * ``` * * @param mapField The name of a field containing a map value. * @param keyExpr An expression that produces the name of the key to remove from the input map. + * @returns A new {@code FunctionExpr} representing the map after the key has been removed. */ export function mapRemove(mapField: string, keyExpr: Expr): FunctionExpr; + /** * @beta + * Creates an expression that removes a key from a map. * - * Creates an expression that removes a key from the map produced by evaluating an expression. + * The `mapRemove` function takes two expressions: + * 1. An expression that evaluates to a map. + * 2. An expression that evaluates to the string key to be removed from the map. * - * ``` + * ```typescript * // Removes the key 'baz' from the input map. * mapRemove(map({foo: 'bar', baz: true}), constant('baz')); * ``` * - * @param mapExpr An expression return a map value. - * @param keyExpr An expression that produces the name of the key to remove from the input map. + * @param mapExpr An expression that evaluates to a map value. + * @param keyExpr An expression that evaluates to the string key to remove from the map. + * @returns A new {@link FunctionExpr} representing the map with the specified key removed. */ export function mapRemove(mapExpr: Expr, keyExpr: Expr): FunctionExpr; - /** * @beta - * * Creates an expression that merges multiple map values. * * ``` @@ -5943,10 +5350,8 @@ declare namespace FirebaseFirestore { secondMap: Record | Expr, ...otherMaps: Array | Expr> ): FunctionExpr; - /** * @beta - * * Creates an expression that merges multiple map values. * * ``` @@ -5969,74 +5374,52 @@ declare namespace FirebaseFirestore { /** * @beta - * - * Creates an expression that returns the document ID from a path. - * - * ```typescript - * // Get the document ID from a path. - * documentId(myDocumentReference); - * ``` - * - * @return A new {@code Expr} representing the documentId operation. - */ - export function documentId( - documentPath: string | DocumentReference - ): FunctionExpr; - - /** - * @beta - * - * Creates an expression that returns the document ID from a path. + * Creates an expression that extracts the document ID from a document reference. * * ```typescript - * // Get the document ID from a path. - * documentId(field("__path__")); + * // Get the document ID from a document reference. + * documentId(field("__name__")); * ``` * - * @return A new {@code Expr} representing the documentId operation. + * @param documentPathExpr An expression evaluating to a document path. + * @return A new {@code FunctionExpr} representing the document ID as a string. */ export function documentId(documentPathExpr: Expr): FunctionExpr; - /** * @beta - * * Creates an expression that returns a substring of a string or byte array. * * @param field The name of a field containing a string or byte array to compute the substring from. * @param position Index of the first character of the substring. * @param length Length of the substring. */ - export function substr( + export function substring( field: string, position: number, length?: number ): FunctionExpr; - /** * @beta - * * Creates an expression that returns a substring of a string or byte array. * * @param input An expression returning a string or byte array to compute the substring from. * @param position Index of the first character of the substring. * @param length Length of the substring. */ - export function substr( + export function substring( input: Expr, position: number, length?: number ): FunctionExpr; - /** * @beta - * * Creates an expression that returns a substring of a string or byte array. * * @param field The name of a field containing a string or byte array to compute the substring from. * @param position An expression that returns the index of the first character of the substring. * @param length An expression that returns the length of the substring. */ - export function substr( + export function substring( field: string, position: Expr, length?: Expr @@ -6044,14 +5427,19 @@ declare namespace FirebaseFirestore { /** * @beta - * * Creates an expression that returns a substring of a string or byte array. * - * @param input An expression returning a string or byte array to compute the substring from. - * @param position An expression that returns the index of the first character of the substring. - * @param length An expression that returns the length of the substring. + * ```typescript + * // Get a substring of the 'myString' field from index 0 with length 5. + * substring(field("myString"), 0, 5); + * ``` + * + * @param input An expression returning a string or byte array from which to extract the substring. + * @param position An expression that returns the 0-based starting index of the substring. + * @param length Optional. An expression that returns the length of the substring. If omitted, the substring extends to the end of the input. + * @return A new {@code FunctionExpr} representing the substring operation. */ - export function substr( + export function substring( input: Expr, position: Expr, length?: Expr @@ -6059,18 +5447,22 @@ declare namespace FirebaseFirestore { /** * @beta + * Creates an expression that performs an addition operation on two or more numeric expressions or literal values. * - * Creates an expression that adds two expressions together. + * This function supports adding multiple values. For example, `add(a, b, c)` is equivalent to `add(add(a, b), c)`. * * ```typescript * // Add the value of the 'quantity' field and the 'reserve' field. * add(field("quantity"), field("reserve")); + * + * // Add three values: a field, a literal number, and another field. + * add(field("price"), 10, field("tax")); * ``` * - * @param first The first expression to add. - * @param second The second expression or literal to add. - * @param others Optional other expressions or literals to add. - * @return A new {@code Expr} representing the addition operation. + * @param first The initial numeric expression or literal value. + * @param second The second numeric expression or literal value to add. + * @param others Optional: Additional numeric expressions or literal values to add. + * @return A new {@code FunctionExpr} representing the sum of all provided arguments. */ export function add( first: Expr, @@ -6080,17 +5472,22 @@ declare namespace FirebaseFirestore { /** * @beta - * - * Creates an expression that adds a field's value to an expression. + * Creates an expression that computes the sum of a field's value and one or more other expressions or literals. * * ```typescript - * // Add the value of the 'quantity' field and the 'reserve' field. + * // Add the value of the 'quantity' field to the value of the 'reserve' field. * add("quantity", field("reserve")); + * + * // Add the value of the 'price' field to a literal number. + * add("price", 10); + * + * // Add the value of the 'total' field to the values of 'tax' and 'shipping' fields. + * add("total", field("tax"), field("shipping")); * ``` * - * @param fieldName The name of the field containing the value to add. - * @param second The second expression or literal to add. - * @param others Optional other expressions or literals to add. + * @param fieldName The name of the field whose value will be the first operand in the addition. + * @param second The second operand, which can be an {@code Expr} or a literal value. + * @param others Optional additional operands, each of which can be an {@code Expr} or a literal value. * @return A new {@code Expr} representing the addition operation. */ export function add( @@ -6098,10 +5495,8 @@ declare namespace FirebaseFirestore { second: Expr | unknown, ...others: Array ): FunctionExpr; - /** * @beta - * * Creates an expression that subtracts two expressions. * * ```typescript @@ -6109,31 +5504,28 @@ declare namespace FirebaseFirestore { * subtract(field("price"), field("discount")); * ``` * - * @param left The expression to subtract from. - * @param right The expression to subtract. + * @param minuend The expression to subtract from. + * @param subtrahend The expression to subtract. * @return A new {@code Expr} representing the subtraction operation. */ - export function subtract(left: Expr, right: Expr): FunctionExpr; + export function subtract(minuend: Expr, subtrahend: Expr): FunctionExpr; /** * @beta - * - * Creates an expression that subtracts a constant value from an expression. + * Creates an expression that subtracts one value from another. * * ```typescript * // Subtract the constant value 2 from the 'value' field * subtract(field("value"), 2); * ``` * - * @param expression The expression to subtract from. - * @param value The constant value to subtract. + * @param minuend The expression to subtract from. + * @param subtrahend The value to subtract. * @return A new {@code Expr} representing the subtraction operation. */ - export function subtract(expression: Expr, value: unknown): FunctionExpr; - + export function subtract(minuend: Expr, subtrahend: unknown): FunctionExpr; /** * @beta - * * Creates an expression that subtracts an expression from a field's value. * * ```typescript @@ -6141,42 +5533,50 @@ declare namespace FirebaseFirestore { * subtract("price", field("discount")); * ``` * - * @param fieldName The field name to subtract from. - * @param expression The expression to subtract. + * @param minuendFieldName The field name to subtract from. + * @param subtrahend The expression to subtract. * @return A new {@code Expr} representing the subtraction operation. */ - export function subtract(fieldName: string, expression: Expr): FunctionExpr; + export function subtract( + minuendFieldName: string, + subtrahend: Expr + ): FunctionExpr; /** * @beta + * Creates an expression that subtracts a value from a field's value. * - * Creates an expression that subtracts a constant value from a field's value. * * ```typescript * // Subtract 20 from the value of the 'total' field * subtract("total", 20); * ``` * - * @param fieldName The field name to subtract from. - * @param value The constant value to subtract. + * @param minuendFieldName The name of the field to subtract from. + * @param subtrahend The value to subtract. * @return A new {@code Expr} representing the subtraction operation. */ - export function subtract(fieldName: string, value: unknown): FunctionExpr; + export function subtract( + minuendFieldName: string, + subtrahend: unknown + ): FunctionExpr; /** * @beta - * - * Creates an expression that multiplies two expressions together. + * Creates an expression that multiplies two or more values together. * * ```typescript * // Multiply the 'quantity' field by the 'price' field * multiply(field("quantity"), field("price")); + * + * // Multiply three values together + * multiply(field("a"), 2, field("b")); * ``` * * @param first The first expression to multiply. * @param second The second expression or literal to multiply. * @param others Optional additional expressions or literals to multiply. - * @return A new {@code Expr} representing the multiplication operation. + * @return A new {@code FunctionExpr} representing the multiplication operation. */ export function multiply( first: Expr, @@ -6186,28 +5586,25 @@ declare namespace FirebaseFirestore { /** * @beta - * - * Creates an expression that multiplies a field's value by an expression. + * Creates an expression that multiplies a field's value by one or more other expressions or literal values. * * ```typescript * // Multiply the 'quantity' field by the 'price' field * multiply("quantity", field("price")); * ``` * - * @param fieldName The name of the field containing the value to add. - * @param second The second expression or literal to add. - * @param others Optional other expressions or literals to add. - * @return A new {@code Expr} representing the multiplication operation. + * @param fieldName The name of the field whose value will be the initial operand of the multiplication. + * @param second The second operand, which can be an {@link Expr} or a literal value, to be multiplied. + * @param others Optional additional operands ({@link Expr} or literal values) to be included in the multiplication. + * @return A new {@link FunctionExpr} representing the multiplication operation. */ export function multiply( fieldName: string, second: Expr | unknown, ...others: Array ): FunctionExpr; - /** * @beta - * * Creates an expression that divides two expressions. * * ```typescript @@ -6215,15 +5612,13 @@ declare namespace FirebaseFirestore { * divide(field("total"), field("count")); * ``` * - * @param left The expression to be divided. - * @param right The expression to divide by. + * @param dividend The expression to be divided. + * @param divisor The expression to divide by. * @return A new {@code Expr} representing the division operation. */ - export function divide(left: Expr, right: Expr): FunctionExpr; - + export function divide(dividend: Expr, divisor: Expr): FunctionExpr; /** * @beta - * * Creates an expression that divides an expression by a constant value. * * ```typescript @@ -6231,15 +5626,13 @@ declare namespace FirebaseFirestore { * divide(field("value"), 10); * ``` * - * @param expression The expression to be divided. - * @param value The constant value to divide by. + * @param dividend The expression to be divided. + * @param divisor The constant value to divide by. * @return A new {@code Expr} representing the division operation. */ - export function divide(expression: Expr, value: unknown): FunctionExpr; - + export function divide(dividend: Expr, divisor: unknown): FunctionExpr; /** * @beta - * * Creates an expression that divides a field's value by an expression. * * ```typescript @@ -6247,15 +5640,13 @@ declare namespace FirebaseFirestore { * divide("total", field("count")); * ``` * - * @param fieldName The field name to be divided. - * @param expressions The expression to divide by. + * @param dividend The field name to be divided. + * @param divisor The expression to divide by. * @return A new {@code Expr} representing the division operation. */ - export function divide(fieldName: string, expressions: Expr): FunctionExpr; - + export function divide(dividend: string, divisor: Expr): FunctionExpr; /** * @beta - * * Creates an expression that divides a field's value by a constant value. * * ```typescript @@ -6263,15 +5654,13 @@ declare namespace FirebaseFirestore { * divide("value", 10); * ``` * - * @param fieldName The field name to be divided. - * @param value The constant value to divide by. + * @param dividend The field name to be divided. + * @param divisor The constant value to divide by. * @return A new {@code Expr} representing the division operation. */ - export function divide(fieldName: string, value: unknown): FunctionExpr; - + export function divide(dividend: string, divisor: unknown): FunctionExpr; /** * @beta - * * Creates an expression that calculates the modulo (remainder) of dividing two expressions. * * ```typescript @@ -6284,10 +5673,8 @@ declare namespace FirebaseFirestore { * @return A new {@code Expr} representing the modulo operation. */ export function mod(left: Expr, right: Expr): FunctionExpr; - /** * @beta - * * Creates an expression that calculates the modulo (remainder) of dividing an expression by a constant. * * ```typescript @@ -6300,10 +5687,8 @@ declare namespace FirebaseFirestore { * @return A new {@code Expr} representing the modulo operation. */ export function mod(expression: Expr, value: unknown): FunctionExpr; - /** * @beta - * * Creates an expression that calculates the modulo (remainder) of dividing a field's value by an expression. * * ```typescript @@ -6316,10 +5701,8 @@ declare namespace FirebaseFirestore { * @return A new {@code Expr} representing the modulo operation. */ export function mod(fieldName: string, expression: Expr): FunctionExpr; - /** * @beta - * * Creates an expression that calculates the modulo (remainder) of dividing a field's value by a constant. * * ```typescript @@ -6335,23 +5718,24 @@ declare namespace FirebaseFirestore { /** * @beta - * - * Creates an expression that creates a Firestore map value from an input object. + * Creates an expression that constructs a Firestore map value from a given JavaScript object. + * The keys of the object become the field names in the Firestore map, and the values become the field values. + * Values can be literal values or other expressions (e.g., `Field.of()`). * * ```typescript - * // Create a map from the input object and reference the 'baz' field value from the input document. + * // Create a map from the input object, where 'foo' is a literal string and 'baz' references the value + * // of the 'baz' field from the document currently being processed by the pipeline. * map({foo: 'bar', baz: Field.of('baz')}).as('data'); * ``` * - * @param elements The input map to evaluate in the expression. - * @return A new {@code Expr} representing the map function. + * @param elements The JavaScript object literal whose properties will be used to create the Firestore map expression. + * @returns A new {@code FunctionExpr} representing the map function. */ export function map(elements: Record): FunctionExpr; - /** * @beta - * - * Creates an expression that creates a Firestore array value from an input array. + * Creates an expression that creates a Firestore array value from a given JavaScript array. + * Array values can be literals or other expressions (e.g., `Field.of()`). * * ```typescript * // Create an array value from the input array and reference the 'baz' field value from the input document. @@ -6365,7 +5749,6 @@ declare namespace FirebaseFirestore { /** * @beta - * * Creates an expression that checks if two expressions are equal. * * ```typescript @@ -6375,13 +5758,11 @@ declare namespace FirebaseFirestore { * * @param left The first expression to compare. * @param right The second expression to compare. - * @return A new `Expr` representing the equality comparison. + * @return A new `BooleanExpr` representing the equality comparison. */ export function eq(left: Expr, right: Expr): BooleanExpr; - /** * @beta - * * Creates an expression that checks if an expression is equal to a constant value. * * ```typescript @@ -6397,23 +5778,20 @@ declare namespace FirebaseFirestore { /** * @beta - * - * Creates an expression that checks if a field's value is equal to an expression. + * Creates an expression that checks if a field's value is equal to another expression. * * ```typescript * // Check if the 'age' field is equal to the 'limit' field * eq("age", field("limit")); * ``` * - * @param fieldName The field name to compare. - * @param expression The expression to compare to. - * @return A new `Expr` representing the equality comparison. + * @param fieldName The name of the field to compare. + * @param expression The expression to compare the field's value against. + * @return A new `BooleanExpr` representing the equality comparison. */ export function eq(fieldName: string, expression: Expr): BooleanExpr; - /** * @beta - * * Creates an expression that checks if a field's value is equal to a constant value. * * ```typescript @@ -6426,10 +5804,8 @@ declare namespace FirebaseFirestore { * @return A new `Expr` representing the equality comparison. */ export function eq(fieldName: string, value: unknown): BooleanExpr; - /** * @beta - * * Creates an expression that checks if two expressions are not equal. * * ```typescript @@ -6442,10 +5818,8 @@ declare namespace FirebaseFirestore { * @return A new `Expr` representing the inequality comparison. */ export function neq(left: Expr, right: Expr): BooleanExpr; - /** * @beta - * * Creates an expression that checks if an expression is not equal to a constant value. * * ```typescript @@ -6461,7 +5835,6 @@ declare namespace FirebaseFirestore { /** * @beta - * * Creates an expression that checks if a field's value is not equal to an expression. * * ```typescript @@ -6471,13 +5844,11 @@ declare namespace FirebaseFirestore { * * @param fieldName The field name to compare. * @param expression The expression to compare to. - * @return A new `Expr` representing the inequality comparison. + * @return A new {@link BooleanExpr} representing the inequality comparison. */ export function neq(fieldName: string, expression: Expr): BooleanExpr; - /** * @beta - * * Creates an expression that checks if a field's value is not equal to a constant value. * * ```typescript @@ -6490,10 +5861,8 @@ declare namespace FirebaseFirestore { * @return A new `Expr` representing the inequality comparison. */ export function neq(fieldName: string, value: unknown): BooleanExpr; - /** * @beta - * * Creates an expression that checks if the first expression is less than the second expression. * * ```typescript @@ -6506,10 +5875,8 @@ declare namespace FirebaseFirestore { * @return A new `Expr` representing the less than comparison. */ export function lt(left: Expr, right: Expr): BooleanExpr; - /** * @beta - * * Creates an expression that checks if an expression is less than a constant value. * * ```typescript @@ -6525,7 +5892,6 @@ declare namespace FirebaseFirestore { /** * @beta - * * Creates an expression that checks if a field's value is less than an expression. * * ```typescript @@ -6535,13 +5901,11 @@ declare namespace FirebaseFirestore { * * @param fieldName The field name to compare. * @param expression The expression to compare to. - * @return A new `Expr` representing the less than comparison. + * @return A new `BooleanExpr` representing the less than comparison. */ export function lt(fieldName: string, expression: Expr): BooleanExpr; - /** * @beta - * * Creates an expression that checks if a field's value is less than a constant value. * * ```typescript @@ -6554,10 +5918,8 @@ declare namespace FirebaseFirestore { * @return A new `Expr` representing the less than comparison. */ export function lt(fieldName: string, value: unknown): BooleanExpr; - /** * @beta - * * Creates an expression that checks if the first expression is less than or equal to the second * expression. * @@ -6574,37 +5936,35 @@ declare namespace FirebaseFirestore { /** * @beta - * - * Creates an expression that checks if an expression is less than or equal to a constant value. + * Creates an expression that checks if a given expression's value is less than or equal to a constant value. * * ```typescript * // Check if the 'quantity' field is less than or equal to 20 * lte(field("quantity"), 20); * ``` * - * @param expression The expression to compare. - * @param value The constant value to compare to. - * @return A new `Expr` representing the less than or equal to comparison. + * @param expression The {@link Expr} to compare. + * @param value The constant value to compare against. + * @return A new {@link BooleanExpr} representing the less than or equal to comparison. */ export function lte(expression: Expr, value: unknown): BooleanExpr; /** - * Creates an expression that checks if a field's value is less than or equal to an expression. + * @beta + * Creates an expression that checks if a field's value is less than or equal to another expression. * * ```typescript * // Check if the 'quantity' field is less than or equal to the 'limit' field * lte("quantity", field("limit")); * ``` * - * @param fieldName The field name to compare. - * @param expression The expression to compare to. - * @return A new `Expr` representing the less than or equal to comparison. + * @param fieldName The name of the field whose value will be compared. + * @param expression The expression to compare against the field's value. + * @return A new {@link BooleanExpr} representing the less than or equal to comparison. */ export function lte(fieldName: string, expression: Expr): BooleanExpr; - /** * @beta - * * Creates an expression that checks if a field's value is less than or equal to a constant value. * * ```typescript @@ -6617,10 +5977,8 @@ declare namespace FirebaseFirestore { * @return A new `Expr` representing the less than or equal to comparison. */ export function lte(fieldName: string, value: unknown): BooleanExpr; - /** * @beta - * * Creates an expression that checks if the first expression is greater than the second * expression. * @@ -6634,10 +5992,8 @@ declare namespace FirebaseFirestore { * @return A new `Expr` representing the greater than comparison. */ export function gt(left: Expr, right: Expr): BooleanExpr; - /** * @beta - * * Creates an expression that checks if an expression is greater than a constant value. * * ```typescript @@ -6653,23 +6009,20 @@ declare namespace FirebaseFirestore { /** * @beta - * - * Creates an expression that checks if a field's value is greater than an expression. + * Creates an expression that checks if a field's value is greater than another expression. * * ```typescript * // Check if the value of field 'age' is greater than the value of field 'limit' * gt("age", field("limit")); * ``` - * - * @param fieldName The field name to compare. - * @param expression The expression to compare to. - * @return A new `Expr` representing the greater than comparison. + * + * @param fieldName The name of the field to compare. + * @param expression The expression to compare against. + * @return A new {@link BooleanExpr} representing the greater than comparison. */ export function gt(fieldName: string, expression: Expr): BooleanExpr; - /** * @beta - * * Creates an expression that checks if a field's value is greater than a constant value. * * ```typescript @@ -6677,15 +6030,13 @@ declare namespace FirebaseFirestore { * gt("price", 100); * ``` * - * @param fieldName The field name to compare. + * @param fieldName The name of the field to compare. * @param value The constant value to compare to. - * @return A new `Expr` representing the greater than comparison. + * @return A new {@link BooleanExpr} representing the greater than comparison. */ export function gt(fieldName: string, value: unknown): BooleanExpr; - /** * @beta - * * Creates an expression that checks if the first expression is greater than or equal to the * second expression. * @@ -6699,10 +6050,8 @@ declare namespace FirebaseFirestore { * @return A new `Expr` representing the greater than or equal to comparison. */ export function gte(left: Expr, right: Expr): BooleanExpr; - /** * @beta - * * Creates an expression that checks if an expression is greater than or equal to a constant * value. * @@ -6716,10 +6065,8 @@ declare namespace FirebaseFirestore { * @return A new `Expr` representing the greater than or equal to comparison. */ export function gte(expression: Expr, value: unknown): BooleanExpr; - /** * @beta - * * Creates an expression that checks if a field's value is greater than or equal to an expression. * * ```typescript @@ -6732,10 +6079,8 @@ declare namespace FirebaseFirestore { * @return A new `Expr` representing the greater than or equal to comparison. */ export function gte(fieldName: string, value: Expr): BooleanExpr; - /** * @beta - * * Creates an expression that checks if a field's value is greater than or equal to a constant * value. * @@ -6749,52 +6094,8 @@ declare namespace FirebaseFirestore { * @return A new `Expr` representing the greater than or equal to comparison. */ export function gte(fieldName: string, value: unknown): BooleanExpr; - - /** - * @beta - * - * Creates an expression that concatenates an array expression with other arrays. - * - * ```typescript - * // Combine the 'items' array with two new item arrays - * arrayConcat(field("items"), [field("newItems"), field("otherItems")]); - * ``` - * - * @param firstArray The first array expression to concatenate to. - * @param secondArray The second array expression or array literal to concatenate to. - * @param otherArrays Optional additional array expressions or array literals to concatenate. - * @return A new {@code Expr} representing the concatenated array. - */ - export function arrayConcat( - firstArray: Expr, - secondArray: Expr | unknown[], - ...otherArrays: Array - ): FunctionExpr; - - /** - * @beta - * - * Creates an expression that concatenates a field's array value with other arrays. - * - * ```typescript - * // Combine the 'items' array with two new item arrays - * arrayConcat("items", [field("newItems"), field("otherItems")]); - * ``` - * - * @param firstArrayField The first array to concatenate to. - * @param secondArray The second array expression or array literal to concatenate to. - * @param otherArrays Optional additional array expressions or array literals to concatenate. - * @return A new {@code Expr} representing the concatenated array. - */ - export function arrayConcat( - firstArrayField: string, - secondArray: Expr | unknown[], - ...otherArrays: Array - ): FunctionExpr; - /** * @beta - * * Creates an expression that checks if an array expression contains a specific element. * * ```typescript @@ -6807,10 +6108,8 @@ declare namespace FirebaseFirestore { * @return A new {@code Expr} representing the 'array_contains' comparison. */ export function arrayContains(array: Expr, element: Expr): FunctionExpr; - /** * @beta - * * Creates an expression that checks if an array expression contains a specific element. * * ```typescript @@ -6823,10 +6122,8 @@ declare namespace FirebaseFirestore { * @return A new {@code Expr} representing the 'array_contains' comparison. */ export function arrayContains(array: Expr, element: unknown): FunctionExpr; - /** * @beta - * * Creates an expression that checks if a field's array value contains a specific element. * * ```typescript @@ -6842,10 +6139,8 @@ declare namespace FirebaseFirestore { fieldName: string, element: Expr ): FunctionExpr; - /** * @beta - * * Creates an expression that checks if a field's array value contains a specific value. * * ```typescript @@ -6861,10 +6156,8 @@ declare namespace FirebaseFirestore { fieldName: string, element: unknown ): BooleanExpr; - /** * @beta - * * Creates an expression that checks if an array expression contains any of the specified * elements. * @@ -6881,10 +6174,8 @@ declare namespace FirebaseFirestore { array: Expr, values: Array ): BooleanExpr; - /** * @beta - * * Creates an expression that checks if a field's array value contains any of the specified * elements. * @@ -6902,10 +6193,8 @@ declare namespace FirebaseFirestore { fieldName: string, values: Array ): BooleanExpr; - /** * @beta - * * Creates an expression that checks if an array expression contains any of the specified * elements. * @@ -6919,10 +6208,8 @@ declare namespace FirebaseFirestore { * @return A new {@code Expr} representing the 'array_contains_any' comparison. */ export function arrayContainsAny(array: Expr, values: Expr): BooleanExpr; - /** * @beta - * * Creates an expression that checks if a field's array value contains any of the specified * elements. * @@ -6940,10 +6227,8 @@ declare namespace FirebaseFirestore { fieldName: string, values: Expr ): BooleanExpr; - /** * @beta - * * Creates an expression that checks if an array expression contains all the specified elements. * * ```typescript @@ -6959,10 +6244,8 @@ declare namespace FirebaseFirestore { array: Expr, values: Array ): BooleanExpr; - /** * @beta - * * Creates an expression that checks if a field's array value contains all the specified values or * expressions. * @@ -6979,20 +6262,25 @@ declare namespace FirebaseFirestore { fieldName: string, values: Array ): BooleanExpr; - /** * @beta - * * Creates an expression that checks if an array expression contains all the specified elements. * + * The `array` parameter should be an expression that evaluates to an array. + * The `arrayExpression` parameter should be an expression that evaluates to an array of elements + * to check for within the `array`. + * * ```typescript - * // Check if the "tags" array contains all of the values: "SciFi", "Adventure", and the value from field "tag1" - * arrayContainsAll(field("tags"), [field("tag1"), constant("SciFi"), "Adventure"]); + * // Check if the "tags" array contains all elements from the "requiredTags" field. + * arrayContainsAll(field("tags"), field("requiredTags")); + * + * // Check if the "items" array contains all elements from a constant array. + * arrayContainsAll(field("items"), constant(["apple", "banana"])); * ``` * - * @param array The array expression to check. - * @param arrayExpression The elements to check for in the array. - * @return A new {@code Expr} representing the 'array_contains_all' comparison. + * @param array An expression evaluating to the array to check. + * @param arrayExpression An expression evaluating to an array of elements to check for. + * @return A new {@code BooleanExpr} representing the 'array_contains_all' comparison. */ export function arrayContainsAll( array: Expr, @@ -7001,27 +6289,23 @@ declare namespace FirebaseFirestore { /** * @beta - * - * Creates an expression that checks if a field's array value contains all the specified values or - * expressions. + * Creates an expression that checks if a field's array value contains all the elements specified by another expression. * * ```typescript - * // Check if the 'tags' array contains both of the values from field 'tag1', the value "SciFi", and "Adventure" - * arrayContainsAll("tags", [field("tag1"), "SciFi", "Adventure"]); + * // Check if the 'tags' array contains all values present in the 'requiredTags' field. + * arrayContainsAll("tags", field("requiredTags")); * ``` * - * @param fieldName The field name to check. - * @param arrayExpression The elements to check for in the array. - * @return A new {@code Expr} representing the 'array_contains_all' comparison. + * @param fieldName The name of the array field to check. + * @param arrayExpression An expression that evaluates to an array of values to check for. + * @return A new {@code BooleanExpr} representing the 'array_contains_all' comparison. */ export function arrayContainsAll( fieldName: string, arrayExpression: Expr ): BooleanExpr; - /** * @beta - * * Creates an expression that calculates the length of an array in a specified field. * * ```typescript @@ -7033,10 +6317,8 @@ declare namespace FirebaseFirestore { * @return A new {@code Expr} representing the length of the array. */ export function arrayLength(fieldName: string): FunctionExpr; - /** * @beta - * * Creates an expression that calculates the length of an array expression. * * ```typescript @@ -7048,10 +6330,8 @@ declare namespace FirebaseFirestore { * @return A new {@code Expr} representing the length of the array. */ export function arrayLength(array: Expr): FunctionExpr; - /** * @beta - * * Creates an expression that checks if an expression, when evaluated, is equal to any of the provided values or * expressions. * @@ -7068,10 +6348,8 @@ declare namespace FirebaseFirestore { expression: Expr, values: Array ): BooleanExpr; - /** * @beta - * * Creates an expression that checks if an expression is equal to any of the provided values. * * ```typescript @@ -7084,10 +6362,8 @@ declare namespace FirebaseFirestore { * @return A new {@code Expr} representing the 'IN' comparison. */ export function eqAny(expression: Expr, arrayExpression: Expr): BooleanExpr; - /** * @beta - * * Creates an expression that checks if a field's value is equal to any of the provided values or * expressions. * @@ -7107,27 +6383,26 @@ declare namespace FirebaseFirestore { /** * @beta + * Creates an expression that checks if a field's value is equal to any of the elements + * within the array that the provided expression evaluates to. * - * Creates an expression that checks if a field's value is equal to any of the provided values or - * expressions. + * This is equivalent to an 'IN' comparison in Firestore queries. * * ```typescript - * // Check if the 'category' field is either "Electronics" or value of field 'primaryType' - * eqAny("category", ["Electronics", field("primaryType")]); + * // Check if the 'category' field's value is present in the 'allowedCategories' array field. + * eqAny("category", field("allowedCategories")); * ``` * - * @param fieldName The field to compare. - * @param arrayExpression An expression that evaluates to an array, whose elements to check for equality to the input field. - * @return A new {@code Expr} representing the 'IN' comparison. + * @param fieldName The name of the field to compare. + * @param arrayExpression An expression that evaluates to an array. The function checks if the value of `fieldName` is equal to any element within this array. + * @return A new {@code BooleanExpr} representing the 'IN' comparison. */ export function eqAny( fieldName: string, arrayExpression: Expr ): BooleanExpr; - /** * @beta - * * Creates an expression that checks if an expression is not equal to any of the provided values * or expressions. * @@ -7144,10 +6419,8 @@ declare namespace FirebaseFirestore { element: Expr, values: Array ): BooleanExpr; - /** * @beta - * * Creates an expression that checks if a field's value is not equal to any of the provided values * or expressions. * @@ -7167,24 +6440,21 @@ declare namespace FirebaseFirestore { /** * @beta - * - * Creates an expression that checks if an expression is not equal to any of the provided values - * or expressions. + * Creates an expression that checks if a given element expression is not equal to any of the values + * contained within an array expression. This is equivalent to a "NOT IN" operation. * * ```typescript - * // Check if the 'status' field is neither "pending" nor the value of the field 'rejectedStatus' - * notEqAny(field("status"), ["pending", field("rejectedStatus")]); + * // Check if the 'status' field is not present in the array stored in the 'invalidStatuses' field. + * notEqAny(field("status"), field("invalidStatuses")); * ``` * - * @param element The expression to compare. - * @param arrayExpression The values to check against. - * @return A new {@code Expr} representing the 'NOT IN' comparison. + * @param element The expression representing the value to check. + * @param arrayExpression An expression that evaluates to an array of values to check against. + * @return A new {@code BooleanExpr} representing the 'NOT IN' comparison. */ export function notEqAny(element: Expr, arrayExpression: Expr): BooleanExpr; - /** * @beta - * * Creates an expression that checks if a field's value is not equal to any of the values in the evaluated expression. * * ```typescript @@ -7203,32 +6473,31 @@ declare namespace FirebaseFirestore { /** * @beta - * - * Creates an expression that performs a logical 'XOR' (exclusive OR) operation on multiple BooleanExpressions. + * Creates an expression that performs a logical 'XOR' (exclusive OR) operation on two or more Boolean expressions. + * The result is true if an odd number of the input expressions evaluate to true, and false otherwise. * * ```typescript - * // Check if only one of the conditions is true: 'age' greater than 18, 'city' is "London", + * // Check if exactly one of the conditions is true: 'age' greater than 18, 'city' is "London", * // or 'status' is "active". * const condition = xor( * gt("age", 18), * eq("city", "London"), - * eq("status", "active")); + * eq("status", "active") + * ); * ``` * - * @param first The first condition. - * @param second The second condition. - * @param additionalConditions Additional conditions to 'XOR' together. - * @return A new {@code Expr} representing the logical 'XOR' operation. + * @param first The first Boolean expression. + * @param second The second Boolean expression. + * @param additionalConditions Optional: Additional Boolean expressions to include in the XOR operation. + * @returns A new {@link BooleanExpr} representing the logical 'XOR' operation. */ export function xor( first: BooleanExpr, second: BooleanExpr, ...additionalConditions: BooleanExpr[] ): BooleanExpr; - /** * @beta - * * Creates a conditional expression that evaluates to a 'then' expression if a condition is true * and an 'else' expression if the condition is false. * @@ -7248,10 +6517,8 @@ declare namespace FirebaseFirestore { thenExpr: Expr, elseExpr: Expr ): FunctionExpr; - /** * @beta - * * Creates an expression that negates a filter condition. * * ```typescript @@ -7263,10 +6530,8 @@ declare namespace FirebaseFirestore { * @return A new {@code Expr} representing the negated filter condition. */ export function not(booleanExpr: BooleanExpr): BooleanExpr; - /** * @beta - * * Creates an expression that returns the largest value between multiple input * expressions or literal values. Based on Firestore's value type ordering. * @@ -7286,10 +6551,8 @@ declare namespace FirebaseFirestore { second: Expr | unknown, ...others: Array ): FunctionExpr; - /** * @beta - * * Creates an expression that returns the largest value between multiple input * expressions or literal values. Based on Firestore's value type ordering. * @@ -7309,10 +6572,8 @@ declare namespace FirebaseFirestore { second: Expr | unknown, ...others: Array ): FunctionExpr; - /** * @beta - * * Creates an expression that returns the smallest value between multiple input * expressions and literal values. Based on Firestore's value type ordering. * @@ -7332,10 +6593,8 @@ declare namespace FirebaseFirestore { second: Expr | unknown, ...others: Array ): FunctionExpr; - /** * @beta - * * Creates an expression that returns the smallest value between a field's value * and other input expressions or literal values. * Based on Firestore's value type ordering. @@ -7359,7 +6618,6 @@ declare namespace FirebaseFirestore { /** * @beta - * * Creates an expression that checks if a field exists. * * ```typescript @@ -7367,14 +6625,12 @@ declare namespace FirebaseFirestore { * exists(field("phoneNumber")); * ``` * - * @param value An expression evaluates to the name of the field to check. - * @return A new {@code Expr} representing the 'exists' check. + * @param value An expression representing the field to check for existence. + * @return A new {@code BooleanExpr} representing the 'exists' check. */ export function exists(value: Expr): BooleanExpr; - /** * @beta - * * Creates an expression that checks if a field exists. * * ```typescript @@ -7389,12 +6645,11 @@ declare namespace FirebaseFirestore { /** * @beta - * * Creates an expression that checks if an expression evaluates to 'NaN' (Not a Number). * * ```typescript * // Check if the result of a calculation is NaN - * isNaN(field("value").divide(0)); + * isNan(field("value").divide(0)); * ``` * * @param value The expression to check. @@ -7404,22 +6659,19 @@ declare namespace FirebaseFirestore { /** * @beta - * * Creates an expression that checks if a field's value evaluates to 'NaN' (Not a Number). * * ```typescript * // Check if the result of a calculation is NaN - * isNaN("value"); + * isNan("value"); * ``` * * @param fieldName The name of the field to check. - * @return A new {@code Expr} representing the 'isNaN' check. + * @return A new {@code BooleanExpr} representing the 'isNan' check. */ export function isNan(fieldName: string): BooleanExpr; - /** * @beta - * * Creates an expression that reverses a string. * * ```typescript @@ -7431,10 +6683,8 @@ declare namespace FirebaseFirestore { * @return A new {@code Expr} representing the reversed string. */ export function reverse(stringExpression: Expr): FunctionExpr; - /** * @beta - * * Creates an expression that reverses a string value in the specified field. * * ```typescript @@ -7446,138 +6696,106 @@ declare namespace FirebaseFirestore { * @return A new {@code Expr} representing the reversed string. */ export function reverse(field: string): FunctionExpr; - /** * @beta - * - * Creates an expression that replaces the first occurrence of a substring within a string with another substring. + * Creates an expression that reverses an array. * * ```typescript - * // Replace the first occurrence of "hello" with "hi" in the 'message' field. - * replaceFirst(field("message"), "hello", "hi"); + * // Reverse the value of the 'myArray' field. + * arrayReverse(field("myArray")); * ``` * - * @param value The expression representing the string to perform the replacement on. - * @param find The substring to search for. - * @param replace The substring to replace the first occurrence of 'find' with. - * @return A new {@code Expr} representing the string with the first occurrence replaced. + * @param arrayExpression An expression evaluating to an array value, which will be reversed. + * @return A new {@code Expr} representing the reversed array. */ - export function replaceFirst( - value: Expr, - find: string, - replace: string - ): FunctionExpr; - + export function arrayReverse(arrayExpression: Expr): FunctionExpr; /** * @beta - * - * Creates an expression that replaces the first occurrence of a substring within a string with another substring, - * where the substring to find and the replacement substring are specified by expressions. + * Creates an expression that reverses an array. * * ```typescript - * // Replace the first occurrence of the value in 'findField' with the value in 'replaceField' in the 'message' field. - * replaceFirst(field("message"), field("findField"), field("replaceField")); + * // Reverse the value of the 'myArray' field. + * arrayReverse("myArray"); * ``` * - * @param value The expression representing the string to perform the replacement on. - * @param find The expression representing the substring to search for. - * @param replace The expression representing the substring to replace the first occurrence of 'find' with. - * @return A new {@code Expr} representing the string with the first occurrence replaced. + * @param fieldName The name of the field to reverse. + * @return A new {@code Expr} representing the reversed array. */ - export function replaceFirst( - value: Expr, - find: Expr, - replace: Expr - ): FunctionExpr; - + export function arrayReverse(fieldName: string): FunctionExpr; /** * @beta - * - * Creates an expression that replaces the first occurrence of a substring within a string represented by a field with another substring. + * Creates an expression that computes the ceiling of a numeric value. * * ```typescript - * // Replace the first occurrence of "hello" with "hi" in the 'message' field. - * replaceFirst("message", "hello", "hi"); + * // Compute the ceiling of the 'price' field. + * ceil(field("price")); * ``` * - * @param fieldName The name of the field representing the string to perform the replacement on. - * @param find The substring to search for. - * @param replace The substring to replace the first occurrence of 'find' with. - * @return A new {@code Expr} representing the string with the first occurrence replaced. + * @param expression An expression evaluating to a numeric value, which the ceiling will be computed for. + * @return A new {@code Expr} representing the ceiling of the numeric value. */ - export function replaceFirst( - fieldName: string, - find: string, - replace: string - ): FunctionExpr; - + export function ceil(expression: Expr): FunctionExpr; /** * @beta - * - * Creates an expression that replaces all occurrences of a substring within a string with another substring. + * Creates an expression that computes the ceiling of a numeric value. * * ```typescript - * // Replace all occurrences of "hello" with "hi" in the 'message' field. - * replaceAll(field("message"), "hello", "hi"); + * // Compute the ceiling of the 'price' field. + * ceil("price"); * ``` * - * @param value The expression representing the string to perform the replacement on. - * @param find The substring to search for. - * @param replace The substring to replace all occurrences of 'find' with. - * @return A new {@code Expr} representing the string with all occurrences replaced. + * @param fieldName The name of the field to compute the ceiling of. + * @return A new {@code Expr} representing the ceiling of the numeric value. */ - export function replaceAll( - value: Expr, - find: string, - replace: string - ): FunctionExpr; + export function ceil(fieldName: string): FunctionExpr; /** * @beta + * Creates an expression that computes `e` (Euler's number) raised to the power of the given expression's result. * - * Creates an expression that replaces all occurrences of a substring within a string with another substring, - * where the substring to find and the replacement substring are specified by expressions. + * This function is equivalent to `Math.exp()` in JavaScript. * * ```typescript - * // Replace all occurrences of the value in 'findField' with the value in 'replaceField' in the 'message' field. - * replaceAll(field("message"), field("findField"), field("replaceField")); + * // Compute e to the power of 2. + * exp(constant(2)); * ``` * - * @param value The expression representing the string to perform the replacement on. - * @param find The expression representing the substring to search for. - * @param replace The expression representing the substring to replace all occurrences of 'find' with. - * @return A new {@code Expr} representing the string with all occurrences replaced. + * @param expression An expression evaluating to a numeric value, which will be used as the exponent for `e`. + * @returns A new {@link FunctionExpr} representing `e` raised to the power of the input expression's result. */ - export function replaceAll( - value: Expr, - find: Expr, - replace: Expr - ): FunctionExpr; + export function exp(expression: Expr): FunctionExpr; /** * @beta - * - * Creates an expression that replaces all occurrences of a substring within a string represented by a field with another substring. + * Creates an expression that computes 'e' (Euler's number) raised to the power of the specified field's numeric value. * * ```typescript - * // Replace all occurrences of "hello" with "hi" in the 'message' field. - * replaceAll("message", "hello", "hi"); + * // Compute 'e' to the power of the 'value' field. + * exp('value'); * ``` * - * @param fieldName The name of the field representing the string to perform the replacement on. - * @param find The substring to search for. - * @param replace The substring to replace all occurrences of 'find' with. - * @return A new {@code Expr} representing the string with all occurrences replaced. + * @param fieldName The name of the field whose numeric value will be used as the exponent. + * @return A new {@code FunctionExpr} representing 'e' raised to the power of the numeric value. */ - export function replaceAll( - fieldName: string, - find: string, - replace: string - ): FunctionExpr; - + export function exp(fieldName: string): FunctionExpr; + /** + * @beta + * Creates an aggregation that counts the number of distinct values of an evaluated expression. + * + * @param expression The expression to count distinct values of. + * @return A new `AggregateFunction` representing the 'count_distinct' aggregation. + */ + export function countDistinct(expression: Expr): AggregateFunction; /** * @beta + * Creates an aggregation that counts the number of distinct values of a field. * + * @param fieldName The field to count distinct values of. + * @return A new `AggregateFunction` representing the 'count_distinct' aggregation. + */ + export function countDistinct(fieldName: string): AggregateFunction; + /** + * @beta * Creates an expression that calculates the byte length of a string in UTF-8, or just the length of a Blob. * * ```typescript @@ -7589,10 +6807,8 @@ declare namespace FirebaseFirestore { * @return A new {@code Expr} representing the length of the string in bytes. */ export function byteLength(expr: Expr): FunctionExpr; - /** * @beta - * * Creates an expression that calculates the length of a string represented by a field in UTF-8 bytes, or just the length of a Blob. * * ```typescript @@ -7607,12 +6823,11 @@ declare namespace FirebaseFirestore { /** * @beta - * * Creates an expression that calculates the character length of a string field in UTF8. * * ```typescript * // Get the character length of the 'name' field in UTF-8. - * strLength("name"); + * charLength("name"); * ``` * * @param fieldName The name of the field containing the string. @@ -7622,22 +6837,19 @@ declare namespace FirebaseFirestore { /** * @beta - * * Creates an expression that calculates the character length of a string expression in UTF-8. * * ```typescript * // Get the character length of the 'name' field in UTF-8. - * strLength(field("name")); + * charLength(field("name")); * ``` * * @param stringExpression The expression representing the string to calculate the length of. * @return A new {@code Expr} representing the length of the string. */ export function charLength(stringExpression: Expr): FunctionExpr; - /** * @beta - * * Creates an expression that performs a case-sensitive wildcard string comparison against a * field. * @@ -7651,10 +6863,8 @@ declare namespace FirebaseFirestore { * @return A new {@code Expr} representing the 'like' comparison. */ export function like(fieldName: string, pattern: string): BooleanExpr; - /** * @beta - * * Creates an expression that performs a case-sensitive wildcard string comparison against a * field. * @@ -7671,7 +6881,6 @@ declare namespace FirebaseFirestore { /** * @beta - * * Creates an expression that performs a case-sensitive wildcard string comparison. * * ```typescript @@ -7681,13 +6890,11 @@ declare namespace FirebaseFirestore { * * @param stringExpression The expression representing the string to perform the comparison on. * @param pattern The pattern to search for. You can use "%" as a wildcard character. - * @return A new {@code Expr} representing the 'like' comparison. + * @return A new {@code BooleanExpr} representing the 'like' comparison. */ export function like(stringExpression: Expr, pattern: string): BooleanExpr; - /** * @beta - * * Creates an expression that performs a case-sensitive wildcard string comparison. * * ```typescript @@ -7700,10 +6907,8 @@ declare namespace FirebaseFirestore { * @return A new {@code Expr} representing the 'like' comparison. */ export function like(stringExpression: Expr, pattern: Expr): BooleanExpr; - /** * @beta - * * Creates an expression that checks if a string field contains a specified regular expression as * a substring. * @@ -7720,10 +6925,8 @@ declare namespace FirebaseFirestore { fieldName: string, pattern: string ): BooleanExpr; - /** * @beta - * * Creates an expression that checks if a string field contains a specified regular expression as * a substring. * @@ -7743,7 +6946,6 @@ declare namespace FirebaseFirestore { /** * @beta - * * Creates an expression that checks if a string expression contains a specified regular * expression as a substring. * @@ -7752,9 +6954,9 @@ declare namespace FirebaseFirestore { * regexContains(field("description"), "(?i)example"); * ``` * - * @param stringExpression The expression representing the string to perform the comparison on. - * @param pattern The regular expression to use for the search. - * @return A new {@code Expr} representing the 'contains' comparison. + * @param stringExpression The expression representing the string to perform the regex comparison on. + * @param pattern The regular expression string to search for within the `stringExpression`. + * @return A new {@code BooleanExpr} representing the result of the regex contains comparison. */ export function regexContains( stringExpression: Expr, @@ -7763,27 +6965,27 @@ declare namespace FirebaseFirestore { /** * @beta - * * Creates an expression that checks if a string expression contains a specified regular * expression as a substring. * * ```typescript - * // Check if the 'description' field contains "example" (case-insensitive) - * regexContains(field("description"), field("pattern")); + * // Check if the 'description' field contains a pattern from another field. + * regexContains(field("description"), field("searchPattern")); + * + * // Check if the 'productName' field contains "apple" or "orange". + * regexContains(field("productName"), "apple|orange"); * ``` * * @param stringExpression The expression representing the string to perform the comparison on. * @param pattern The regular expression to use for the search. - * @return A new {@code Expr} representing the 'contains' comparison. + * @return A new {@code BooleanExpr} representing the 'contains' comparison. */ export function regexContains( stringExpression: Expr, pattern: Expr ): BooleanExpr; - /** * @beta - * * Creates an expression that checks if a string field matches a specified regular expression. * * ```typescript @@ -7799,23 +7001,24 @@ declare namespace FirebaseFirestore { /** * @beta - * * Creates an expression that checks if a string field matches a specified regular expression. * + * The `pattern` parameter is an {@link Expr} that evaluates to the regular expression string. + * This allows for dynamic regex patterns, such as those stored in other fields. + * * ```typescript - * // Check if the 'email' field matches a valid email pattern - * regexMatch("email", field("pattern")); + * // Check if the 'email' field matches a regex pattern stored in the 'emailValidationRegex' field. + * regexMatch("email", field("emailValidationRegex")); * ``` * - * @param fieldName The name of the field containing the string. - * @param pattern The regular expression to use for the match. - * @return A new {@code Expr} representing the regular expression match. + * @param fieldName The name of the field containing the string value to be matched. + * @param pattern An {@link Expr} that evaluates to the regular expression string to use for the match. + * @return A new {@link BooleanExpr} representing the result of the regular expression match. */ export function regexMatch(fieldName: string, pattern: Expr): BooleanExpr; /** * @beta - * * Creates an expression that checks if a string expression matches a specified regular * expression. * @@ -7824,18 +7027,16 @@ declare namespace FirebaseFirestore { * regexMatch(field("email"), "[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,}"); * ``` * - * @param stringExpression The expression representing the string to match against. + * @param stringExpression An expression that evaluates to the string to match against. * @param pattern The regular expression to use for the match. - * @return A new {@code Expr} representing the regular expression match. + * @return A new {@link BooleanExpr} representing the result of the regular expression match. */ export function regexMatch( stringExpression: Expr, pattern: string ): BooleanExpr; - /** * @beta - * * Creates an expression that checks if a string expression matches a specified regular * expression. * @@ -7852,10 +7053,8 @@ declare namespace FirebaseFirestore { stringExpression: Expr, pattern: Expr ): BooleanExpr; - /** * @beta - * * Creates an expression that checks if a string field contains a specified substring. * * ```typescript @@ -7871,10 +7070,8 @@ declare namespace FirebaseFirestore { fieldName: string, substring: string ): BooleanExpr; - /** * @beta - * * Creates an expression that checks if a string field contains a substring specified by an expression. * * ```typescript @@ -7890,10 +7087,8 @@ declare namespace FirebaseFirestore { fieldName: string, substring: Expr ): BooleanExpr; - /** * @beta - * * Creates an expression that checks if a string expression contains a specified substring. * * ```typescript @@ -7909,10 +7104,8 @@ declare namespace FirebaseFirestore { stringExpression: Expr, substring: string ): BooleanExpr; - /** * @beta - * * Creates an expression that checks if a string expression contains a substring specified by another expression. * * ```typescript @@ -7928,10 +7121,8 @@ declare namespace FirebaseFirestore { stringExpression: Expr, substring: Expr ): BooleanExpr; - /** * @beta - * * Creates an expression that checks if a field's value starts with a given prefix. * * ```typescript @@ -7944,10 +7135,8 @@ declare namespace FirebaseFirestore { * @return A new {@code Expr} representing the 'starts with' comparison. */ export function startsWith(fieldName: string, prefix: string): BooleanExpr; - /** * @beta - * * Creates an expression that checks if a field's value starts with a given prefix. * * ```typescript @@ -7963,17 +7152,16 @@ declare namespace FirebaseFirestore { /** * @beta - * - * Creates an expression that checks if a string expression starts with a given prefix. + * Creates an expression that checks if a string value, represented by an expression, starts with a given prefix. * * ```typescript - * // Check if the result of concatenating 'firstName' and 'lastName' fields starts with "Mr." - * startsWith(field("fullName"), "Mr."); + * // Check if the 'name' field starts with "Mr." + * startsWith(field("name"), "Mr."); * ``` * - * @param stringExpression The expression to check. - * @param prefix The prefix to check for. - * @return A new {@code Expr} representing the 'starts with' comparison. + * @param stringExpression An expression that evaluates to a string, which will be checked for the prefix. + * @param prefix The string prefix to check for. + * @return A new {@code BooleanExpr} representing the 'starts with' comparison. */ export function startsWith( stringExpression: Expr, @@ -7982,17 +7170,16 @@ declare namespace FirebaseFirestore { /** * @beta - * - * Creates an expression that checks if a string expression starts with a given prefix. + * Creates an expression that checks if a string expression starts with a given prefix expression. * * ```typescript - * // Check if the result of concatenating 'firstName' and 'lastName' fields starts with "Mr." + * // Check if the 'fullName' field starts with the value of the 'prefix' field. * startsWith(field("fullName"), field("prefix")); * ``` * - * @param stringExpression The expression to check. - * @param prefix The prefix to check for. - * @return A new {@code Expr} representing the 'starts with' comparison. + * @param stringExpression The string expression to check. + * @param prefix The prefix expression to check for. + * @return A new {@code BooleanExpr} representing the 'starts with' comparison. */ export function startsWith( stringExpression: Expr, @@ -8001,8 +7188,7 @@ declare namespace FirebaseFirestore { /** * @beta - * - * Creates an expression that checks if a field's value ends with a given postfix. + * Creates an expression that checks if a field's value ends with a given suffix. * * ```typescript * // Check if the 'filename' field ends with ".txt" @@ -8010,14 +7196,12 @@ declare namespace FirebaseFirestore { * ``` * * @param fieldName The field name to check. - * @param suffix The postfix to check for. - * @return A new {@code Expr} representing the 'ends with' comparison. + * @param suffix The suffix to check for. + * @return A new {@link BooleanExpr} representing the 'ends with' comparison. */ export function endsWith(fieldName: string, suffix: string): BooleanExpr; - /** * @beta - * * Creates an expression that checks if a field's value ends with a given postfix. * * ```typescript @@ -8030,10 +7214,8 @@ declare namespace FirebaseFirestore { * @return A new {@code Expr} representing the 'ends with' comparison. */ export function endsWith(fieldName: string, suffix: Expr): BooleanExpr; - /** * @beta - * * Creates an expression that checks if a string expression ends with a given postfix. * * ```typescript @@ -8049,10 +7231,8 @@ declare namespace FirebaseFirestore { stringExpression: Expr, suffix: string ): BooleanExpr; - /** * @beta - * * Creates an expression that checks if a string expression ends with a given postfix. * * ```typescript @@ -8068,7 +7248,6 @@ declare namespace FirebaseFirestore { /** * @beta - * * Creates an expression that converts a string field to lowercase. * * ```typescript @@ -8083,7 +7262,6 @@ declare namespace FirebaseFirestore { /** * @beta - * * Creates an expression that converts a string expression to lowercase. * * ```typescript @@ -8095,10 +7273,8 @@ declare namespace FirebaseFirestore { * @return A new {@code Expr} representing the lowercase string. */ export function toLower(stringExpression: Expr): FunctionExpr; - /** * @beta - * * Creates an expression that converts a string field to uppercase. * * ```typescript @@ -8113,22 +7289,19 @@ declare namespace FirebaseFirestore { /** * @beta - * * Creates an expression that converts a string expression to uppercase. * * ```typescript * // Convert the 'title' field to uppercase - * toUppercase(field("title")); + * toUpper(field("title")); * ``` * * @param stringExpression The expression representing the string to convert to uppercase. - * @return A new {@code Expr} representing the uppercase string. + * @return A new {@code FunctionExpr} representing the uppercase string. */ export function toUpper(stringExpression: Expr): FunctionExpr; - /** * @beta - * * Creates an expression that removes leading and trailing whitespace from a string field. * * ```typescript @@ -8140,10 +7313,8 @@ declare namespace FirebaseFirestore { * @return A new {@code Expr} representing the trimmed string. */ export function trim(fieldName: string): FunctionExpr; - /** * @beta - * * Creates an expression that removes leading and trailing whitespace from a string expression. * * ```typescript @@ -8158,25 +7329,23 @@ declare namespace FirebaseFirestore { /** * @beta - * - * Creates an expression that concatenates string functions, fields or constants together. + * Creates an expression that concatenates multiple string values, which can be field names or other expressions that evaluate to strings, along with string literals. * * ```typescript - * // Combine the 'firstName', " ", and 'lastName' fields into a single string + * // Combine the 'firstName' field, a space, and the 'lastName' field into a single string. * strConcat("firstName", " ", field("lastName")); * ``` * - * @param fieldName The field name containing the initial string value. + * @param fieldName The name of the field to use as the initial string value for concatenation. * @param secondString An expression or string literal to concatenate. * @param otherStrings Optional additional expressions or literals (typically strings) to concatenate. - * @return A new {@code Expr} representing the concatenated string. + * @return A new {@code FunctionExpr} representing the concatenated string. */ export function strConcat( fieldName: string, secondString: Expr | string, ...otherStrings: Array ): FunctionExpr; - /** * @beta * Creates an expression that concatenates string expressions together. @@ -8196,10 +7365,8 @@ declare namespace FirebaseFirestore { secondString: Expr | string, ...otherStrings: Array ): FunctionExpr; - /** * @beta - * * Accesses a value from a map (object) field using the provided key. * * ```typescript @@ -8212,10 +7379,8 @@ declare namespace FirebaseFirestore { * @return A new {@code Expr} representing the value associated with the given key in the map. */ export function mapGet(fieldName: string, subField: string): FunctionExpr; - /** * @beta - * * Accesses a value from a map (object) expression using the provided key. * * ```typescript @@ -8228,10 +7393,8 @@ declare namespace FirebaseFirestore { * @return A new {@code Expr} representing the value associated with the given key in the map. */ export function mapGet(mapExpression: Expr, subField: string): FunctionExpr; - /** * @beta - * * Creates an aggregation that counts the total number of stage inputs. * * ```typescript @@ -8242,10 +7405,8 @@ declare namespace FirebaseFirestore { * @return A new {@code AggregateFunction} representing the 'countAll' aggregation. */ export function countAll(): AggregateFunction; - /** * @beta - * * Creates an aggregation that counts the number of stage inputs with valid evaluations of the * provided expression. * @@ -8258,8 +7419,8 @@ declare namespace FirebaseFirestore { * @return A new {@code AggregateFunction} representing the 'count' aggregation. */ export function count(expression: Expr): AggregateFunction; - /** + * @beta * Creates an aggregation that counts the number of stage inputs where the input field exists. * * ```typescript @@ -8271,10 +7432,8 @@ declare namespace FirebaseFirestore { * @return A new {@code AggregateFunction} representing the 'count' aggregation. */ export function count(fieldName: string): AggregateFunction; - /** * @beta - * * Creates an aggregation that calculates the sum of values from an expression across multiple * stage inputs. * @@ -8287,10 +7446,8 @@ declare namespace FirebaseFirestore { * @return A new {@code AggregateFunction} representing the 'sum' aggregation. */ export function sum(expression: Expr): AggregateFunction; - /** * @beta - * * Creates an aggregation that calculates the sum of a field's values across multiple stage * inputs. * @@ -8303,10 +7460,8 @@ declare namespace FirebaseFirestore { * @return A new {@code AggregateFunction} representing the 'sum' aggregation. */ export function sum(fieldName: string): AggregateFunction; - /** * @beta - * * Creates an aggregation that calculates the average (mean) of values from an expression across * multiple stage inputs. * @@ -8319,10 +7474,8 @@ declare namespace FirebaseFirestore { * @return A new {@code AggregateFunction} representing the 'avg' aggregation. */ export function avg(expression: Expr): AggregateFunction; - /** * @beta - * * Creates an aggregation that calculates the average (mean) of a field's values across multiple * stage inputs. * @@ -8335,10 +7488,8 @@ declare namespace FirebaseFirestore { * @return A new {@code AggregateFunction} representing the 'avg' aggregation. */ export function avg(fieldName: string): AggregateFunction; - /** * @beta - * * Creates an aggregation that finds the minimum value of an expression across multiple stage * inputs. * @@ -8351,10 +7502,8 @@ declare namespace FirebaseFirestore { * @return A new {@code AggregateFunction} representing the 'min' aggregation. */ export function minimum(expression: Expr): AggregateFunction; - /** * @beta - * * Creates an aggregation that finds the minimum value of a field across multiple stage inputs. * * ```typescript @@ -8366,10 +7515,8 @@ declare namespace FirebaseFirestore { * @return A new {@code AggregateFunction} representing the 'min' aggregation. */ export function minimum(fieldName: string): AggregateFunction; - /** * @beta - * * Creates an aggregation that finds the maximum value of an expression across multiple stage * inputs. * @@ -8382,10 +7529,8 @@ declare namespace FirebaseFirestore { * @return A new {@code AggregateFunction} representing the 'max' aggregation. */ export function maximum(expression: Expr): AggregateFunction; - /** * @beta - * * Creates an aggregation that finds the maximum value of a field across multiple stage inputs. * * ```typescript @@ -8397,10 +7542,8 @@ declare namespace FirebaseFirestore { * @return A new {@code AggregateFunction} representing the 'max' aggregation. */ export function maximum(fieldName: string): AggregateFunction; - /** * @beta - * * Calculates the Cosine distance between a field's vector value and a literal vector value. * * ```typescript @@ -8416,10 +7559,8 @@ declare namespace FirebaseFirestore { fieldName: string, vector: number[] | VectorValue ): FunctionExpr; - /** * @beta - * * Calculates the Cosine distance between a field's vector value and a vector expression. * * ```typescript @@ -8438,26 +7579,30 @@ declare namespace FirebaseFirestore { /** * @beta + * Creates an expression that computes the cosine distance between two vectors. * - * Calculates the Cosine distance between a vector expression and a vector literal. + * The second argument can be either a vector literal (an array of numbers) or another vector expression. * * ```typescript - * // Calculate the cosine distance between the 'location' field and a target location + * // Calculate the cosine distance between the 'location' field and a target location literal. * cosineDistance(field("location"), [37.7749, -122.4194]); * ``` * - * @param vectorExpression The first vector (represented as an Expr) to compare against. - * @param vector The other vector (as an array of doubles or VectorValue) to compare against. - * @return A new {@code Expr} representing the cosine distance between the two vectors. + * ```typescript + * // Calculate the cosine distance between two vector fields. + * cosineDistance(field("vector1"), field("vector2")); + * ``` + * + * @param vectorExpression The first vector, represented as an {@link Expr} (e.g., a field path). + * @param vector The second vector, which can be either a numeric array literal (`number[]`) or another {@link Expr}. + * @return A new {@link FunctionExpr} representing the cosine distance. */ export function cosineDistance( vectorExpression: Expr, vector: number[] | Expr ): FunctionExpr; - /** * @beta - * * Calculates the Cosine distance between two vector expressions. * * ```typescript @@ -8473,10 +7618,8 @@ declare namespace FirebaseFirestore { vectorExpression: Expr, otherVectorExpression: Expr ): FunctionExpr; - /** * @beta - * * Calculates the dot product between a field's vector value and a double array. * * ```typescript @@ -8495,11 +7638,10 @@ declare namespace FirebaseFirestore { /** * @beta - * * Calculates the dot product between a field's vector value and a vector expression. * * ```typescript - * // Calculate the dot product distance between two document vectors: 'docVector1' and 'docVector2' + * // Calculate the dot product of 'docVector1' with 'docVector2' * dotProduct("docVector1", field("docVector2")); * ``` * @@ -8514,8 +7656,7 @@ declare namespace FirebaseFirestore { /** * @beta - * - * Calculates the dot product between a vector expression and a double array. + * Calculates the dot product between a vector expression and another vector (either a number array or a VectorValue). * * ```typescript * // Calculate the dot product between a feature vector and a target vector @@ -8523,17 +7664,15 @@ declare namespace FirebaseFirestore { * ``` * * @param vectorExpression The first vector (represented as an Expr) to calculate with. - * @param vector The other vector (as an array of doubles or VectorValue) to calculate with. + * @param vector The other vector (as an array of numbers or VectorValue) to calculate with. * @return A new {@code Expr} representing the dot product between the two vectors. */ export function dotProduct( vectorExpression: Expr, vector: number[] | VectorValue ): FunctionExpr; - /** * @beta - * * Calculates the dot product between two vector expressions. * * ```typescript @@ -8552,8 +7691,8 @@ declare namespace FirebaseFirestore { /** * @beta - * - * Calculates the Euclidean distance between a field's vector value and a double array. + * Calculates the Euclidean distance between a field's vector value and another vector. + * The other vector can be provided as a double array or a {@link VectorValue}. * * ```typescript * // Calculate the Euclidean distance between the 'location' field and a target location @@ -8568,10 +7707,8 @@ declare namespace FirebaseFirestore { fieldName: string, vector: number[] | VectorValue ): FunctionExpr; - /** * @beta - * * Calculates the Euclidean distance between a field's vector value and a vector expression. * * ```typescript @@ -8587,10 +7724,8 @@ declare namespace FirebaseFirestore { fieldName: string, vectorExpression: Expr ): FunctionExpr; - /** * @beta - * * Calculates the Euclidean distance between a vector expression and a double array. * * ```typescript @@ -8607,10 +7742,8 @@ declare namespace FirebaseFirestore { vectorExpression: Expr, vector: number[] | VectorValue ): FunctionExpr; - /** * @beta - * * Calculates the Euclidean distance between two vector expressions. * * ```typescript @@ -8626,10 +7759,8 @@ declare namespace FirebaseFirestore { vectorExpression: Expr, otherVectorExpression: Expr ): FunctionExpr; - /** * @beta - * * Creates an expression that calculates the length of a Firestore Vector. * * ```typescript @@ -8644,8 +7775,7 @@ declare namespace FirebaseFirestore { /** * @beta - * - * Creates an expression that calculates the length of a Firestore Vector represented by a field. + * Creates an expression that calculates the length (dimension) of a Firestore Vector represented by a field. * * ```typescript * // Get the vector length (dimension) of the field 'embedding'. @@ -8653,13 +7783,11 @@ declare namespace FirebaseFirestore { * ``` * * @param fieldName The name of the field representing the Firestore Vector. - * @return A new {@code Expr} representing the length of the array. + * @return A new {@code FunctionExpr} representing the length (dimension) of the vector. */ export function vectorLength(fieldName: string): FunctionExpr; - /** * @beta - * * Creates an expression that interprets an expression as the number of microseconds since the Unix epoch (1970-01-01 00:00:00 UTC) * and returns a timestamp. * @@ -8672,10 +7800,8 @@ declare namespace FirebaseFirestore { * @return A new {@code Expr} representing the timestamp. */ export function unixMicrosToTimestamp(expr: Expr): FunctionExpr; - /** * @beta - * * Creates an expression that interprets a field's value as the number of microseconds since the Unix epoch (1970-01-01 00:00:00 UTC) * and returns a timestamp. * @@ -8688,10 +7814,8 @@ declare namespace FirebaseFirestore { * @return A new {@code Expr} representing the timestamp. */ export function unixMicrosToTimestamp(fieldName: string): FunctionExpr; - /** * @beta - * * Creates an expression that converts a timestamp expression to the number of microseconds since the Unix epoch (1970-01-01 00:00:00 UTC). * * ```typescript @@ -8703,10 +7827,8 @@ declare namespace FirebaseFirestore { * @return A new {@code Expr} representing the number of microseconds since epoch. */ export function timestampToUnixMicros(expr: Expr): FunctionExpr; - /** * @beta - * * Creates an expression that converts a timestamp field to the number of microseconds since the Unix epoch (1970-01-01 00:00:00 UTC). * * ```typescript @@ -8718,10 +7840,8 @@ declare namespace FirebaseFirestore { * @return A new {@code Expr} representing the number of microseconds since epoch. */ export function timestampToUnixMicros(fieldName: string): FunctionExpr; - /** * @beta - * * Creates an expression that interprets an expression as the number of milliseconds since the Unix epoch (1970-01-01 00:00:00 UTC) * and returns a timestamp. * @@ -8734,10 +7854,8 @@ declare namespace FirebaseFirestore { * @return A new {@code Expr} representing the timestamp. */ export function unixMillisToTimestamp(expr: Expr): FunctionExpr; - /** * @beta - * * Creates an expression that interprets a field's value as the number of milliseconds since the Unix epoch (1970-01-01 00:00:00 UTC) * and returns a timestamp. * @@ -8750,10 +7868,8 @@ declare namespace FirebaseFirestore { * @return A new {@code Expr} representing the timestamp. */ export function unixMillisToTimestamp(fieldName: string): FunctionExpr; - /** * @beta - * * Creates an expression that converts a timestamp expression to the number of milliseconds since the Unix epoch (1970-01-01 00:00:00 UTC). * * ```typescript @@ -8765,10 +7881,8 @@ declare namespace FirebaseFirestore { * @return A new {@code Expr} representing the number of milliseconds since epoch. */ export function timestampToUnixMillis(expr: Expr): FunctionExpr; - /** * @beta - * * Creates an expression that converts a timestamp field to the number of milliseconds since the Unix epoch (1970-01-01 00:00:00 UTC). * * ```typescript @@ -8780,10 +7894,8 @@ declare namespace FirebaseFirestore { * @return A new {@code Expr} representing the number of milliseconds since epoch. */ export function timestampToUnixMillis(fieldName: string): FunctionExpr; - /** * @beta - * * Creates an expression that interprets an expression as the number of seconds since the Unix epoch (1970-01-01 00:00:00 UTC) * and returns a timestamp. * @@ -8796,10 +7908,8 @@ declare namespace FirebaseFirestore { * @return A new {@code Expr} representing the timestamp. */ export function unixSecondsToTimestamp(expr: Expr): FunctionExpr; - /** * @beta - * * Creates an expression that interprets a field's value as the number of seconds since the Unix epoch (1970-01-01 00:00:00 UTC) * and returns a timestamp. * @@ -8812,10 +7922,8 @@ declare namespace FirebaseFirestore { * @return A new {@code Expr} representing the timestamp. */ export function unixSecondsToTimestamp(fieldName: string): FunctionExpr; - /** * @beta - * * Creates an expression that converts a timestamp expression to the number of seconds since the Unix epoch (1970-01-01 00:00:00 UTC). * * ```typescript @@ -8827,10 +7935,8 @@ declare namespace FirebaseFirestore { * @return A new {@code Expr} representing the number of seconds since epoch. */ export function timestampToUnixSeconds(expr: Expr): FunctionExpr; - /** * @beta - * * Creates an expression that converts a timestamp field to the number of seconds since the Unix epoch (1970-01-01 00:00:00 UTC). * * ```typescript @@ -8842,10 +7948,8 @@ declare namespace FirebaseFirestore { * @return A new {@code Expr} representing the number of seconds since epoch. */ export function timestampToUnixSeconds(fieldName: string): FunctionExpr; - /** * @beta - * * Creates an expression that adds a specified amount of time to a timestamp. * * ```typescript @@ -8866,7 +7970,6 @@ declare namespace FirebaseFirestore { /** * @beta - * * Creates an expression that adds a specified amount of time to a timestamp. * * ```typescript @@ -8875,7 +7978,7 @@ declare namespace FirebaseFirestore { * ``` * * @param timestamp The expression representing the timestamp. - * @param unit The unit of time to add (e.g., "day", "hour"). + * @param unit The unit of time to add: 'microsecond', 'millisecond', 'second', 'minute', 'hour', or 'day'. * @param amount The amount of time to add. * @return A new {@code Expr} representing the resulting timestamp. */ @@ -8890,10 +7993,8 @@ declare namespace FirebaseFirestore { | 'day', amount: number ): FunctionExpr; - /** * @beta - * * Creates an expression that adds a specified amount of time to a timestamp represented by a field. * * ```typescript @@ -8917,10 +8018,8 @@ declare namespace FirebaseFirestore { | 'day', amount: number ): FunctionExpr; - /** * @beta - * * Creates an expression that subtracts a specified amount of time from a timestamp. * * ```typescript @@ -8938,10 +8037,8 @@ declare namespace FirebaseFirestore { unit: Expr, amount: Expr ): FunctionExpr; - /** * @beta - * * Creates an expression that subtracts a specified amount of time from a timestamp. * * ```typescript @@ -8965,10 +8062,8 @@ declare namespace FirebaseFirestore { | 'day', amount: number ): FunctionExpr; - /** * @beta - * * Creates an expression that subtracts a specified amount of time from a timestamp represented by a field. * * ```typescript @@ -8992,10 +8087,8 @@ declare namespace FirebaseFirestore { | 'day', amount: number ): FunctionExpr; - /** * @beta - * * Creates an expression that performs a logical 'AND' operation on multiple filter conditions. * * ```typescript @@ -9014,10 +8107,8 @@ declare namespace FirebaseFirestore { second: BooleanExpr, ...more: BooleanExpr[] ): BooleanExpr; - /** * @beta - * * Creates an expression that performs a logical 'OR' operation on multiple filter conditions. * * ```typescript @@ -9036,10 +8127,283 @@ declare namespace FirebaseFirestore { second: BooleanExpr, ...more: BooleanExpr[] ): BooleanExpr; - /** * @beta + * Creates an expression that returns the value of the base expression raised to the power of the exponent expression. + * + * ```typescript + * // Raise the value of the 'base' field to the power of the 'exponent' field. + * pow(field("base"), field("exponent")); + * ``` + * + * @param base The expression to raise to the power of the exponent. + * @param exponent The expression to raise the base to the power of. + * @return A new `Expr` representing the power operation. + */ + export function pow(base: Expr, exponent: Expr): FunctionExpr; + /** + * @beta + * Creates an expression that returns the value of the base expression raised to the power of the exponent. + * + * ```typescript + * // Raise the value of the 'base' field to the power of 2. + * pow(field("base"), 2); + * ``` + * + * @param base The expression to raise to the power of the exponent. + * @param exponent The constant value to raise the base to the power of. + * @return A new `Expr` representing the power operation. + */ + export function pow(base: Expr, exponent: number): FunctionExpr; + /** + * @beta + * Creates an expression that returns the value of the base field raised to the power of the exponent expression. + * + * ```typescript + * // Raise the value of the 'base' field to the power of the 'exponent' field. + * pow("base", field("exponent")); + * ``` + * + * @param base The name of the field to raise to the power of the exponent. + * @param exponent The expression to raise the base to the power of. + * @return A new `Expr` representing the power operation. + */ + export function pow(base: string, exponent: Expr): FunctionExpr; + /** + * @beta + * Creates an expression that returns the value of the base field raised to the power of the exponent. + * + * ```typescript + * // Raise the value of the 'base' field to the power of 2. + * pow("base", 2); + * ``` + * + * @param base The name of the field to raise to the power of the exponent. + * @param exponent The constant value to raise the base to the power of. + * @return A new `Expr` representing the power operation. + */ + export function pow(base: string, exponent: number): FunctionExpr; + /** + * @beta + * Creates an expression that returns the collection ID from a path. + * + * ```typescript + * // Get the collection ID from a path. + * collectionId(field("__name__")); + * ``` + * + * @param expression An expression evaluating to a path, which the collection ID will be extracted from. + * @return A new {@code Expr} representing the collectionId operation. + */ + export function collectionId(expression: Expr): FunctionExpr; + /** + * @beta + * Creates an expression that returns the collection ID from a path. + * + * ```typescript + * // Get the collection ID from a path. + * collectionId("__name__"); + * ``` + * + * @param fieldName The name of the field to get the collection ID from. + * @return A new {@code Expr} representing the collectionId operation. + */ + export function collectionId(fieldName: string): FunctionExpr; + /** + * @beta + * Creates an expression that calculates the length of a string, array, map, vector, or bytes. + * + * ```typescript + * // Get the length of the 'name' field. + * length(field("name")); + * + * // Get the number of items in the 'cart' array. + * length(field("cart")); + * ``` + * + * @param expression An expression evaluating to a string, array, map, vector, or bytes, which the length will be calculated for. + * @return A new `Expr` representing the length of the string, array, map, vector, or bytes. + */ + export function length(expression: Expr): FunctionExpr; + /** + * @beta + * Creates an expression that calculates the length of a string, array, map, vector, or bytes. + * + * ```typescript + * // Get the length of the 'name' field. + * length("name"); + * + * // Get the number of items in the 'cart' array. + * length("cart"); + * ``` + * + * @param fieldName The name of the field to calculate the length of. + * @return A new `Expr` representing the length of the string, array, map, vector, or bytes. + */ + export function length(fieldName: string): FunctionExpr; + /** + * @beta + * Creates an expression that reverses a string. + * + * ```typescript + * // Reverse the value of the 'myString' field. + * strReverse(field("myString")); + * ``` + * + * @param stringExpression An expression evaluating to a string value, which will be reversed. + * @return A new {@code Expr} representing the reversed string. + */ + export function strReverse(stringExpression: Expr): FunctionExpr; + /** + * @beta + * Creates an expression that reverses a string value in the specified field. + * + * ```typescript + * // Reverse the value of the 'myString' field. + * strReverse("myString"); + * ``` + * + * @param field The name of the field representing the string to reverse. + * @return A new {@code Expr} representing the reversed string. + */ + export function strReverse(field: string): FunctionExpr; + // TODO(new-expression): Add new top-level expression function declarations above this line + /** + * @beta + * Creates an expression that computes the natural logarithm of a numeric value. + * + * ```typescript + * // Compute the natural logarithm of the 'value' field. + * ln(field("value")); + * ``` + * + * @param expression An expression evaluating to a numeric value, which the natural logarithm will be computed for. + * @return A new {@code Expr} representing the natural logarithm of the numeric value. + */ + export function ln(expression: Expr): FunctionExpr; + /** + * @beta + * Creates an expression that computes the natural logarithm of a numeric value. + * + * ```typescript + * // Compute the natural logarithm of the 'value' field. + * ln("value"); + * ``` + * + * @param fieldName The name of the field to compute the natural logarithm of. + * @return A new {@code Expr} representing the natural logarithm of the numeric value. + */ + export function ln(fieldName: string): FunctionExpr; + /** + * @beta + * Creates an expression that computes the logarithm of an expression to a given base. + * + * ```typescript + * // Compute the logarithm of the 'value' field with base 10. + * log(field("value"), 10); + * ``` + * + * @param expression An expression evaluating to a numeric value, which the logarithm will be computed for. + * @param base The base of the logarithm. + * @return A new {@code Expr} representing the logarithm of the numeric value. + */ + export function log(expression: Expr, base: number): FunctionExpr; + /** + * @beta + * Creates an expression that computes the logarithm of an expression to a given base. + * + * ```typescript + * // Compute the logarithm of the 'value' field with the base in the 'base' field. + * log(field("value"), field("base")); + * ``` + * + * @param expression An expression evaluating to a numeric value, which the logarithm will be computed for. + * @param base The base of the logarithm. + * @return A new {@code Expr} representing the logarithm of the numeric value. + */ + export function log(expression: Expr, base: Expr): FunctionExpr; + /** + * @beta + * Creates an expression that computes the logarithm of a field to a given base. + * + * ```typescript + * // Compute the logarithm of the 'value' field with base 10. + * log("value", 10); + * ``` + * + * @param fieldName The name of the field to compute the logarithm of. + * @param base The base of the logarithm. + * @return A new {@code Expr} representing the logarithm of the numeric value. + */ + export function log(fieldName: string, base: number): FunctionExpr; + /** + * @beta + * Creates an expression that computes the logarithm of a field to a given base. + * + * ```typescript + * // Compute the logarithm of the 'value' field with the base in the 'base' field. + * log("value", field("base")); + * ``` + * + * @param fieldName The name of the field to compute the logarithm of. + * @param base The base of the logarithm. + * @return A new {@code Expr} representing the logarithm of the numeric value. + */ + export function log(fieldName: string, base: Expr): FunctionExpr; + /** + * @beta + * Creates an expression that rounds a numeric value to the nearest whole number. + * + * ```typescript + * // Round the value of the 'price' field. + * round(field("price")); + * ``` + * + * @param expression An expression evaluating to a numeric value, which will be rounded. + * @return A new `Expr` representing the rounded value. + */ + export function round(expression: Expr): FunctionExpr; + /** + * @beta + * Creates an expression that rounds a numeric value to the nearest whole number. + * + * ```typescript + * // Round the value of the 'price' field. + * round("price"); + * ``` + * + * @param fieldName The name of the field to round. + * @return A new `Expr` representing the rounded value. + */ + export function round(fieldName: string): FunctionExpr; + /** + * @beta + * Creates an expression that computes the square root of a numeric value. + * + * ```typescript + * // Compute the square root of the 'value' field. + * sqrt(field("value")); + * ``` + * + * @param expression An expression evaluating to a numeric value, which the square root will be computed for. + * @return A new {@code Expr} representing the square root of the numeric value. + */ + export function sqrt(expression: Expr): FunctionExpr; + /** + * @beta + * Creates an expression that computes the square root of a numeric value. + * + * ```typescript + * // Compute the square root of the 'value' field. + * sqrt("value"); + * ``` * + * @param fieldName The name of the field to compute the square root of. + * @return A new {@code Expr} representing the square root of the numeric value. + */ + export function sqrt(fieldName: string): FunctionExpr; + /** + * @beta * Creates an {@link Ordering} that sorts documents in ascending order based on an expression. * * ```typescript @@ -9052,10 +8416,8 @@ declare namespace FirebaseFirestore { * @return A new `Ordering` for ascending sorting. */ export function ascending(expr: Expr): Ordering; - /** * @beta - * * Creates an {@link Ordering} that sorts documents in ascending order based on a field. * * ```typescript @@ -9068,10 +8430,8 @@ declare namespace FirebaseFirestore { * @return A new `Ordering` for ascending sorting. */ export function ascending(fieldName: string): Ordering; - /** * @beta - * * Creates an {@link Ordering} that sorts documents in descending order based on an expression. * * ```typescript @@ -9084,10 +8444,8 @@ declare namespace FirebaseFirestore { * @return A new `Ordering` for descending sorting. */ export function descending(expr: Expr): Ordering; - /** * @beta - * * Creates an {@link Ordering} that sorts documents in descending order based on a field. * * ```typescript @@ -9100,10 +8458,8 @@ declare namespace FirebaseFirestore { * @return A new `Ordering` for descending sorting. */ export function descending(fieldName: string): Ordering; - /** * @beta - * * Represents an ordering criterion for sorting documents in a Firestore pipeline. * * You create `Ordering` instances using the `ascending` and `descending` helper functions. @@ -9114,60 +8470,90 @@ declare namespace FirebaseFirestore { } /** - * Represents the source of a Firestore {@link Pipeline}. * @beta + * Provides the entry point for defining the data source of a Firestore {@link Pipeline}. + * + * Use the methods of this class (e.g., {@link PipelineSource#collection}, {@link PipelineSource#collectionGroup}, + * {@link PipelineSource#database}, or {@link PipelineSource#documents}) to specify the initial data + * for your pipeline, such as a collection, a collection group, the entire database, or a set of specific documents. */ export class PipelineSource { /** - * Specifies the source as a collection. + * @beta + * Specifies the source for a new pipeline as a Firestore collection. + * This method allows you to start a data pipeline by defining the collection + * from which documents will be read. + * + * @param collectionPath The path to the collection as a string (e.g., 'users/alovelace/chats') + * or a {@link CollectionReference} object. + * @returns A new {@link Pipeline} object configured to read from the specified collection. * - * @param collectionPath The path to the collection. - * @return A new Pipeline object with the collection as the source. + * @example + * ```typescript + * // Using a string path + * const pipeline1 = firestore.pipeline().collection('myCollection'); + * + * // Using a CollectionReference + * const collectionRef = firestore.collection('anotherCollection'); + * const pipeline2 = firestore.pipeline().collection(collectionRef); + * ``` */ collection(collectionPath: string | CollectionReference): Pipeline; - /** + * @beta * Returns all documents from the entire collection. The collection can be nested. * @param options - Options defining how this CollectionStage is evaluated. */ collection(options: CollectionStageOptions): Pipeline; - /** + * @beta * Specifies the source as a collection group. * * @param collectionId The ID of the collection group. * @return A new Pipeline object with the collection group as the source. */ collectionGroup(collectionId: string): Pipeline; + /** - * Returns all documents from a collection ID regardless of the parent. - * @param options - Options defining how this CollectionGroupStage is evaluated. + * @beta + * Creates a new {@link Pipeline} stage that queries all documents belonging to a collection + * with the ID specified in the provided `options`, regardless of the document's parent. + * + * A collection group query can be used to query collections that have the same ID but + * are located at different paths. + * + * ```typescript + * // Query all 'cities' collections regardless of their parent document. + * const citiesPipeline = firestore.collectionGroup({ collectionId: 'cities' }); + * ``` + * + * @param options Options defining how this CollectionGroupStage is evaluated, including the `collectionId`. + * @returns A new {@link Pipeline} instance representing the collection group stage. */ - collectionGroup(options: CollectionGroupStageOptions): Pipeline; - /** + * @beta * Specifies the source as a database. * * @return A new Pipeline object with the database as the source. */ database(): Pipeline; - /** + * @beta * Returns all documents from the entire database. * @param options - Options defining how a DatabaseStage is evaluated. */ database(options: DatabaseStageOptions): Pipeline; - /** + * @beta * Specifies the source as a set of documents. * * @param docs The document references. * @return A new Pipeline object with the documents as the source. */ documents(docs: Array): Pipeline; - /** + * @beta * Set the pipeline's source to the documents specified by the given paths and DocumentReferences. * * @param options - Options defining how this DocumentsStage is evaluated. @@ -9175,8 +8561,8 @@ declare namespace FirebaseFirestore { * @throws {@FirestoreError} Thrown if any of the provided DocumentReferences target a different project or database than the pipeline. */ documents(options: DocumentsStageOptions): Pipeline; - /** + * @beta * Convert the given Query into an equivalent Pipeline. * * @param query A Query to be converted into a Pipeline. @@ -9185,10 +8571,8 @@ declare namespace FirebaseFirestore { */ createFrom(query: Query): Pipeline; } - /** * @beta - * * The Pipeline class provides a flexible and expressive framework for building complex data * transformation and query pipelines for Firestore. * @@ -9230,6 +8614,7 @@ declare namespace FirebaseFirestore { */ export class Pipeline { /** + * @beta * Adds new fields to outputs from previous stages. * * This stage allows you to compute values on-the-fly based on existing data from previous @@ -9258,6 +8643,7 @@ declare namespace FirebaseFirestore { */ addFields(field: Selectable, ...additionalFields: Selectable[]): Pipeline; /** + * @beta * Adds new fields to outputs from previous stages. * * This stage allows you to compute values on-the-fly based on existing data from previous @@ -9284,8 +8670,8 @@ declare namespace FirebaseFirestore { * @return A new Pipeline object with this stage appended to the stage list. */ addFields(options: AddFieldsStageOptions): Pipeline; - /** + * @beta * Remove fields from outputs of previous stages. * * Example: @@ -9307,41 +8693,48 @@ declare namespace FirebaseFirestore { fieldValue: Field | string, ...additionalFields: Array ): Pipeline; + /** - * Remove fields from outputs of previous stages. + * @beta + * Creates a stage that removes specified fields from the outputs of previous stages in the pipeline. + * + * This is useful for reducing the data transferred, by excluding fields + * that are no longer needed after certain pipeline operations. * * Example: * * ```typescript * firestore.pipeline().collection('books') - * // removes field 'rating' and 'cost' from the previous stage outputs. - * .removeFields( - * field('rating'), - * 'cost' - * ); + * // Removes the 'rating' and 'cost' fields from the documents + * // processed by the preceding stages. + * .removeFields({ + * fields: [ + * field('rating'), + * 'cost' + * ] + * }); * ``` * - * @param options - An object that specifies required and optional parameters for the stage. - * @return A new Pipeline object with this stage appended to the stage list. + * @param options - An object containing the configuration for this stage. + * @param options.fields - An array of field names (strings) or {@link Expr} objects + * representing the fields to be removed from the output. + * @returns A new {@link Pipeline} object with this stage appended to the stage list. */ removeFields(options: RemoveFieldsStageOptions): Pipeline; /** + * @beta * Selects or creates a set of fields from the outputs of previous stages. * *

    The selected fields are defined using {@link Selectable} expressions, which can be: * *

      - *
    • {@code string}: Name of an existing field
    • - *
    • {@link Field}: References an existing field.
    • - *
    • {@link Function}: Represents the result of a function with an assigned alias name using - * {@link Expr#as}
    • + *
    • {@code string}: The name of an existing field.
    • + *
    • {@link Field}: A reference to an existing field.
    • + *
    • {@link Expr}: An expression (e.g., a {@link FunctionExpr}) that represents the result of an expression., + * The Expr must be aliased using {@link Expr#as}.
    • *
    * - *

    If no selections are provided, the output of this stage is empty. Use {@link - * Pipeline#addFields} instead if only additions are - * desired. - * *

    Example: * * ```typescript @@ -9353,8 +8746,8 @@ declare namespace FirebaseFirestore { * ); * ``` * - * @param selection The first field to include in the output documents, specified as {@link - * Selectable} expression or string value representing the field name. + * @param selection The first field to include in the output documents, specified as a {@link + * Selectable} expression or a string value representing the field name. * @param additionalSelections Optional additional fields to include in the output documents, specified as {@link * Selectable} expressions or {@code string} values representing field names. * @return A new Pipeline object with this stage appended to the stage list. @@ -9363,39 +8756,44 @@ declare namespace FirebaseFirestore { selection: Selectable | string, ...additionalSelections: Array ): Pipeline; + /** + * @beta * Selects or creates a set of fields from the outputs of previous stages. * *

    The selected fields are defined using {@link Selectable} expressions, which can be: * *

      - *
    • {@code string}: Name of an existing field
    • - *
    • {@link Field}: References an existing field.
    • - *
    • {@link Function}: Represents the result of a function with an assigned alias name using - * {@link Expr#as}
    • + *
    • {@code string}: The name of an existing field.
    • + *
    • {@link Field}: A reference to an existing field.
    • + *
    • {@link Expr}: An expression (e.g., a {@link FunctionExpr}) that represents the result of an expression., + * The Expr must be aliased using {@link Expr#as}.
    • *
    * - *

    If no selections are provided, the output of this stage is empty. Use {@link - * Pipeline#addFields} instead if only additions are - * desired. + * If no selections are provided within the `options` (i.e., the `fields` array is empty), + * the output of this stage will be an empty document. If the intention is to add new fields + * without replacing existing ones, consider using {@link Pipeline#addFields} instead. * - *

    Example: + * Example: * * ```typescript * db.pipeline().collection("books") - * .select( - * "firstName", - * field("lastName"), - * field("address").toUppercase().as("upperAddress"), - * ); + * .select({ + * fields: [ + * "firstName", + * field("lastName"), + * field("address").toUppercase().as("upperAddress"), + * ] + * }); * ``` * - * @param options - An object that specifies required and optional parameters for the stage. - * @return A new Pipeline object with this stage appended to the stage list. + * @param options An object of type {@link SelectStageOptions} that defines the selection criteria for this stage. + * It is expected to contain a `fields` property, which is an array of {@link Selectable} expressions. + * @return A new {@link Pipeline} object with this select stage appended to its list of stages. */ select(options: SelectStageOptions): Pipeline; - /** + * @beta * Filters the documents from previous stages to only include those matching the specified {@link * BooleanExpr}. * @@ -9428,6 +8826,7 @@ declare namespace FirebaseFirestore { */ where(condition: BooleanExpr): Pipeline; /** + * @beta * Filters the documents from previous stages to only include those matching the specified {@link * BooleanExpr}. * @@ -9447,20 +8846,20 @@ declare namespace FirebaseFirestore { * * ```typescript * firestore.pipeline().collection("books") - * .where( - * and( + * .where({ + * filter: and( * gt(field("rating"), 4.0), // Filter for ratings greater than 4.0 * field("genre").eq("Science Fiction") // Equivalent to gt("genre", "Science Fiction") * ) - * ); + * }); * ``` * - * @param options - An object that specifies required and optional parameters for the stage. + * @param options An object that specifies the filtering criteria. It is expected to contain a `filter` property of type {@link BooleanExpr}. * @return A new Pipeline object with this stage appended to the stage list. */ where(options: WhereStageOptions): Pipeline; - /** + * @beta * Skips the first `offset` number of documents from the results of previous stages. * *

    This stage is useful for implementing pagination in your pipelines, allowing you to retrieve @@ -9481,15 +8880,16 @@ declare namespace FirebaseFirestore { * @return A new Pipeline object with this stage appended to the stage list. */ offset(offset: number): Pipeline; + /** - * Skips the first `offset` number of documents from the results of previous stages. - * - *

    This stage is useful for implementing pagination in your pipelines, allowing you to retrieve - * results in chunks. It is typically used in conjunction with {@link #limit} to control the - * size of each page. + * @beta + * Skips a specified number of documents from the results of previous stages. * - *

    Example: + * This stage is useful for implementing pagination in your pipelines, enabling you to + * retrieve results in manageable chunks. It is commonly used alongside {@link Pipeline.limit} + * to define the size of each page. * + * Example: * ```typescript * // Retrieve the second page of 20 results * firestore.pipeline().collection('books') @@ -9498,12 +8898,13 @@ declare namespace FirebaseFirestore { * .limit(20); // Take the next 20 results * ``` * - * @param options - An object that specifies required and optional parameters for the stage. - * @return A new Pipeline object with this stage appended to the stage list. + * @param options An object containing the configuration for the offset stage, + * including the number of documents to skip. + * @returns A new `Pipeline` object with this stage appended to the stage list. */ offset(options: OffsetStageOptions): Pipeline; - /** + * @beta * Limits the maximum number of documents returned by previous stages to `limit`. * *

    This stage is particularly useful when you want to retrieve a controlled subset of data from @@ -9529,16 +8930,18 @@ declare namespace FirebaseFirestore { * @return A new Pipeline object with this stage appended to the stage list. */ limit(limit: number): Pipeline; + /** - * Limits the maximum number of documents returned by previous stages to `limit`. + * @beta + * Limits the maximum number of documents returned by previous stages. * *

    This stage is particularly useful when you want to retrieve a controlled subset of data from * a potentially large result set. It's often used for: * *

      - *
    • **Pagination:** In combination with {@link #offset} to retrieve specific pages of + *
    • Pagination: In combination with {@link #offset} to retrieve specific pages of * results.
    • - *
    • **Limiting Data Retrieval:** To prevent excessive data transfer and improve performance, + *
    • Limiting Data Retrieval: To prevent excessive data transfer and improve performance, * especially when dealing with large collections.
    • *
    * @@ -9548,15 +8951,15 @@ declare namespace FirebaseFirestore { * // Limit the results to the top 10 highest-rated books * firestore.pipeline().collection('books') * .sort(field('rating').descending()) - * .limit(10); + * .limit({ limit: 10 }); * ``` * - * @param options - An object that specifies required and optional parameters for the stage. - * @return A new Pipeline object with this stage appended to the stage list. + * @param options - An object that specifies the limit. It must contain a `limit` property, which is a number representing the maximum number of documents to return. + * @return A new {@link Pipeline} object with this stage appended to the stage list. */ limit(options: LimitStageOptions): Pipeline; - /** + * @beta * Returns a set of distinct values from the inputs to this stage. * * This stage runs through the results from previous stages to include only results with @@ -9566,7 +8969,7 @@ declare namespace FirebaseFirestore { * * - {@code string}: Name of an existing field * - {@link Field}: References an existing document field. - * - {@link ExprWithAlias}: Represents the result of a function with an assigned alias name + * - {@link AliasedExpr}: Represents the result of a function with an assigned alias name * using {@link Expr#as}. * * Example: @@ -9589,6 +8992,7 @@ declare namespace FirebaseFirestore { ...additionalGroups: Array ): Pipeline; /** + * @beta * Returns a set of distinct values from the inputs to this stage. * * This stage runs through the results from previous stages to include only results with @@ -9598,7 +9002,7 @@ declare namespace FirebaseFirestore { * * - {@code string}: Name of an existing field * - {@link Field}: References an existing document field. - * - {@link ExprWithAlias}: Represents the result of a function with an assigned alias name + * - {@link AliasedExpr}: Represents the result of a function with an assigned alias name * using {@link Expr#as}. * * Example: @@ -9614,12 +9018,12 @@ declare namespace FirebaseFirestore { * @return A new {@code Pipeline} object with this stage appended to the stage list. */ distinct(options: DistinctStageOptions): Pipeline; - /** + * @beta * Performs aggregation operations on the documents from previous stages. * *

    This stage allows you to calculate aggregate values over a set of documents. You define the - * aggregations to perform using {@link AggregateWithAlias} expressions which are typically results of + * aggregations to perform using {@link AliasedAggregate} expressions which are typically results of * calling {@link Expr#as} on {@link AggregateFunction} instances. * *

    Example: @@ -9633,17 +9037,18 @@ declare namespace FirebaseFirestore { * ); * ``` * - * @param accumulator The first {@link AggregateWithAlias}, wrapping an {@link AggregateFunction} + * @param accumulator The first {@link AliasedAggregate}, wrapping an {@link AggregateFunction} * and providing a name for the accumulated results. - * @param additionalAccumulators Optional additional {@link AggregateWithAlias}, each wrapping an {@link AggregateFunction} + * @param additionalAccumulators Optional additional {@link AliasedAggregate}, each wrapping an {@link AggregateFunction} * and providing a name for the accumulated results. * @return A new Pipeline object with this stage appended to the stage list. */ aggregate( - accumulator: AggregateWithAlias, - ...additionalAccumulators: AggregateWithAlias[] + accumulator: AliasedAggregate, + ...additionalAccumulators: AliasedAggregate[] ): Pipeline; /** + * @beta * Performs optionally grouped aggregation operations on the documents from previous stages. * *

    This stage allows you to calculate aggregate values over a set of documents, optionally @@ -9655,7 +9060,7 @@ declare namespace FirebaseFirestore { * If no grouping fields are provided, a single group containing all documents is used. Not * specifying groups is the same as putting the entire inputs into one group. *

  • **Accumulators:** One or more accumulation operations to perform within each group. These - * are defined using {@link AggregateWithAlias} expressions, which are typically created by + * are defined using {@link AliasedAggregate} expressions, which are typically created by * calling {@link Expr#as} on {@link AggregateFunction} instances. Each aggregation * calculates a value (e.g., sum, average, count) based on the documents within its group.
  • * @@ -9676,8 +9081,8 @@ declare namespace FirebaseFirestore { * list. */ aggregate(options: AggregateStageOptions): Pipeline; - /** + * @beta * Performs a vector proximity search on the documents from the previous stage, returning the * K-nearest documents based on the specified query `vectorValue` and `distanceMeasure`. The * returned documents will be sorted in order from nearest to furthest from the query `vectorValue`. @@ -9705,6 +9110,7 @@ declare namespace FirebaseFirestore { findNearest(options: FindNearestStageOptions): Pipeline; /** + * @beta * Fully overwrites all fields in a document with those coming from a nested map. * *

    This stage allows you to emit a map value as a document. Each key of the map becomes a field @@ -9732,94 +9138,105 @@ declare namespace FirebaseFirestore { * // } * ``` * - * @param fieldName The {@link Field} field containing the nested map. + * @param fieldName The name of the field containing the nested map. * @return A new {@code Pipeline} object with this stage appended to the stage list. */ replaceWith(fieldName: string): Pipeline; /** - * Fully overwrites all fields in a document with those coming from a map. + * @beta + * Fully replaces all fields in a document with the fields from a map expression. * - *

    This stage allows you to emit a map value as a document. Each key of the map becomes a field - * on the document that contains the corresponding value. + *

    This stage allows you to transform the current document into a new one + * by providing an {@link Expr} that evaluates to a map. Each key-value pair + * in the resulting map will become a field-value pair in the document. * *

    Example: * * ```typescript - * // Input. + * // Input document: * // { - * // 'name': 'John Doe Jr.', - * // 'parents': { - * // 'father': 'John Doe Sr.', - * // 'mother': 'Jane Doe' - * // } + * // 'firstName': 'John', + * // 'lastName': 'Doe', + * // 'age': 30 * // } * - * // Emit parents as document. - * firestore.pipeline().collection('people').replaceWith(map({ - * foo: 'bar', - * info: { - * name: field('name') - * } + * // Replace the document's fields with a new map. + * // The 'fullName' field will be created by concatenating 'firstName' and 'lastName'. + * // The 'status' field will be a new static value. + * firestore.pipeline().collection('users').replaceWith(map({ + * fullName: concat(field('firstName'), ' ', field('lastName')), + * status: 'active' * })); * - * // Output + * // Output document: * // { - * // 'father': 'John Doe Sr.', - * // 'mother': 'Jane Doe' + * // 'fullName': 'John Doe', + * // 'status': 'active' * // } * ``` * - * @param expr An {@link Expr} that when returned evaluates to a map. + * @param expr An {@link Expr} that evaluates to a map. The key-value pairs of this map will replace the document's fields. * @return A new {@code Pipeline} object with this stage appended to the stage list. */ replaceWith(expr: Expr): Pipeline; /** + * @beta * Fully overwrites all fields in a document with those coming from a map. * - *

    This stage allows you to emit a map value as a document. Each key of the map becomes a field - * on the document that contains the corresponding value. + *

    This stage allows you to transform the current document into a new one + * by defining its new structure using a map expression. Each key in the + * provided map expression becomes a field in the new document, with its + * corresponding value. Values within the map can be literal values or + * expressions that refer to fields from the input document. * *

    Example: * * ```typescript - * // Input. + * // Input document: * // { - * // 'name': 'John Doe Jr.', - * // 'parents': { - * // 'father': 'John Doe Sr.', - * // 'mother': 'Jane Doe' + * // 'productId': 'P123', + * // 'itemName': 'Laptop', + * // 'price': 1200, + * // 'details': { + * // 'weight': '2kg', + * // 'color': 'silver' * // } * // } * - * // Emit parents as document. - * firestore.pipeline().collection('people').replaceWith(map({ - * foo: 'bar', - * info: { - * name: field('name') - * } + * // Replace the document with a new structure, selecting and renaming fields, + * // and adding new literal values. + * firestore.pipeline().collection('products').replaceWith(map({ + * id: field('productId'), + * productName: field('itemName'), + * displayPrice: concat('$', field('price')), + * category: 'Electronics', + * weightInKg: field('details.weight') * })); * - * // Output + * // Output document: * // { - * // 'father': 'John Doe Sr.', - * // 'mother': 'Jane Doe' + * // 'id': 'P123', + * // 'productName': 'Laptop', + * // 'displayPrice': '$1200', + * // 'category': 'Electronics', + * // 'weightInKg': '2kg' * // } * ``` * - * @param options - An object that specifies required and optional parameters for the stage. + * @param options - An object that specifies the map expression to use for replacement. * @return A new {@code Pipeline} object with this stage appended to the stage list. */ replaceWith(options: ReplaceWithStageOptions): Pipeline; /** - * Performs a pseudo-random sampling of the documents from the previous stage. + * @beta + * Performs a pseudo-random sampling of documents from the previous stage in the pipeline. * - *

    This stage will filter documents pseudo-randomly. The parameter specifies how number of - * documents to be returned. + * This stage filters documents pseudo-randomly, returning a specified number of documents. * - *

    Examples: + * Examples: * * ```typescript * // Sample 25 books, if available. @@ -9827,33 +9244,12 @@ declare namespace FirebaseFirestore { * .sample(25); * ``` * - * @param documents The number of documents to sample. + * @param documents The maximum number of documents to sample. * @return A new {@code Pipeline} object with this stage appended to the stage list. */ sample(documents: number): Pipeline; - - /** - * Performs a pseudo-random sampling of the documents from the previous stage. - * - *

    This stage will filter documents pseudo-randomly. The 'options' parameter specifies how - * sampling will be performed. See {@code SampleOptions} for more information. - * - *

    Examples: - * - * // Sample 10 books, if available. - * firestore.pipeline().collection("books") - * .sample({ documents: 10 }); - * - * // Sample 50% of books. - * firestore.pipeline().collection("books") - * .sample({ percentage: 0.5 }); - * - * @param options The {@code SampleOptions} specifies how sampling is performed. - * @return A new {@code Pipeline} object with this stage appended to the stage list. - */ - sample(options: {percentage: number} | {documents: number}): Pipeline; - /** + * @beta * Performs a pseudo-random sampling of the documents from the previous stage. * *

    This stage will filter documents pseudo-randomly. The 'options' parameter specifies how @@ -9873,8 +9269,8 @@ declare namespace FirebaseFirestore { * @return A new {@code Pipeline} object with this stage appended to the stage list. */ sample(options: SampleStageOptions): Pipeline; - /** + * @beta * Performs union of all documents from two pipelines, including duplicates. * *

    This stage will pass through documents from previous stage, and also pass through documents @@ -9894,6 +9290,7 @@ declare namespace FirebaseFirestore { */ union(other: Pipeline): Pipeline; /** + * @beta * Performs union of all documents from two pipelines, including duplicates. * *

    This stage will pass through documents from previous stage, and also pass through documents @@ -9912,8 +9309,8 @@ declare namespace FirebaseFirestore { * @return A new {@code Pipeline} object with this stage appended to the stage list. */ union(options: UnionStageOptions): Pipeline; - /** + * @beta * Produces a document for each element in an input array. * * For each previous stage document, this stage will emit zero or more augmented documents. The @@ -9947,6 +9344,7 @@ declare namespace FirebaseFirestore { */ unnest(selectable: Selectable, indexField?: string): Pipeline; /** + * @beta * Produces a document for each element in an input array. * * For each previous stage document, this stage will emit zero or more augmented documents. The @@ -9978,8 +9376,8 @@ declare namespace FirebaseFirestore { * @return A new {@code Pipeline} object with this stage appended to the stage list. */ unnest(options: UnnestStageOptions): Pipeline; - /** + * @beta * Sorts the documents from previous stages based on one or more {@link Ordering} criteria. * *

    This stage allows you to order the results of your pipeline. You can specify multiple {@link @@ -10006,6 +9404,7 @@ declare namespace FirebaseFirestore { */ sort(ordering: Ordering, ...additionalOrderings: Ordering[]): Pipeline; /** + * @beta * Sorts the documents from previous stages based on one or more {@link Ordering} criteria. * *

    This stage allows you to order the results of your pipeline. You can specify multiple {@link @@ -10030,12 +9429,12 @@ declare namespace FirebaseFirestore { * @return A new {@code Pipeline} object with this stage appended to the stage list. */ sort(options: SortStageOptions): Pipeline; - /** - * Adds a generic stage to the pipeline. + * @beta + * Adds a raw stage to the pipeline. * *

    This method provides a flexible way to extend the pipeline's functionality by adding custom - * stages. Each generic stage is defined by a unique `name` and a set of `params` that control its + * stages. Each raw stage is defined by a unique `name` and a set of `params` that control its * behavior. * *

    Example (Assuming there is no "where" stage available in SDK): @@ -10043,17 +9442,17 @@ declare namespace FirebaseFirestore { * ```typescript * // Assume we don't have a built-in "where" stage * firestore.pipeline().collection("books") - * .genericStage("where", [Field.of("published").lt(1900)]) // Custom "where" stage + * .rawStage("where", [Field.of("published").lt(1900)]) // Custom "where" stage * .select("title", "author"); * ``` * - * @param name The unique name of the generic stage to add. - * @param params A list of parameters to configure the generic stage's behavior. + * @param name The unique name of the raw stage to add. + * @param params A list of parameters to configure the raw stage's behavior. * @return A new {@code Pipeline} object with this stage appended to the stage list. */ - genericStage(name: string, params: any[]): Pipeline; - + rawStage(name: string, params: any[]): Pipeline; /** + * @beta * Executes this pipeline and returns a Promise to represent the asynchronous operation. * *

    The returned Promise can be used to track the progress of the pipeline execution @@ -10082,16 +9481,18 @@ declare namespace FirebaseFirestore { * .execute(); * ``` * - * @param pipelineOptions - Optionally specify pipeline execution behavior. + * @param pipelineExecuteOptions - Optionally specify pipeline execution behavior. * @return A Promise representing the asynchronous pipeline execution. */ - execute(pipelineOptions?: PipelineOptions): Promise; + execute( + pipelineExecuteOptions?: PipelineExecuteOptions + ): Promise; /** + * @beta * Executes this pipeline and streams the results as {@link PipelineResult}s. * - * @returns {Stream.} A stream of - * PipelineResult. + * @returns {NodeJS.ReadableStream} A Node.js ReadableStream that emits {@link PipelineResult} objects. * * @example * ```typescript @@ -10099,28 +9500,47 @@ declare namespace FirebaseFirestore { * .where(gt(Field.of("rating"), 4.5)) * .select("title", "author", "rating") * .stream() - * .on('data', (pipelineResult) => {}) - * .on('end', () => {}); + * .on('data', (pipelineResult) => { + * console.log(pipelineResult); + * }) + * .on('end', () => { + * console.log('Stream ended.'); + * }); * ``` */ stream(): NodeJS.ReadableStream; } - /** + * @beta * Options defining how a Pipeline is evaluated. */ - export type PipelineOptions = { - /** - * Pipeline to be evaluated. - */ - pipeline: Pipeline; - + export type PipelineExecuteOptions = { /** - * Specify the index mode. + * @beta + * Specifies the index mode for the query. */ indexMode?: 'recommended'; - /** + * @beta Options used to configure explain queries. */ + explainOptions?: { + /** + * @beta + * The explain mode configures what explain data + * and query results are returned from the Pipeline query. + * + * `"execute"` - [DEFAULT] Execute the Pipeline and return results + * `"analyze"` - Plan the query and execute, returning both the planner + * information and the Pipeline query results. + */ + mode?: 'execute' | 'analyze'; + /** + * @beta + * Specifies the output format of the query planner information. + */ + outputFormat?: 'text' | 'json'; + }; + /** + * @beta * An escape hatch to set options not known at SDK build time. These values * will be passed directly to the Firestore backend and not used by the SDK. * @@ -10131,14 +9551,14 @@ declare namespace FirebaseFirestore { * by Firestore (for example: string, boolean, number, map, …). Value types * not known to the SDK will be rejected. * - * Values specified in customOptions will take precedence over any options + * Values specified in rawOptions will take precedence over any options * with the same name set by the SDK. * * Override the `example_option`: * ``` * execute({ * pipeline: myPipeline, - * customOptions: { + * rawOptions: { * // Override `example_option`. This will not * // merge with the existing `example_option` object. * "example_option": { @@ -10148,12 +9568,12 @@ declare namespace FirebaseFirestore { * } * ``` * - * `customOptions` supports dot notation, if you want to override + * `rawOptions` supports dot notation, if you want to override * a nested option. * ``` * execute({ * pipeline: myPipeline, - * customOptions: { + * rawOptions: { * // Override `example_option.foo` and do not override * // any other properties of `example_option`. * "example_option.foo": "bar" @@ -10161,219 +9581,264 @@ declare namespace FirebaseFirestore { * } * ``` */ - customOptions?: { + rawOptions?: { [name: string]: unknown; }; }; - /** + * @beta * Options defining how a Stage is evaluated. */ export type StageOptions = { /** + * @beta * An escape hatch to set options not known at SDK build time. These values * will be passed directly to the Firestore backend and not used by the SDK. * * The option name will be used as provided. And must match the name * format used by the backend (hint: use a snake_case_name). * - * Custom option values can be any type supported + * Raw option values can be any type supported * by Firestore (for example: string, boolean, number, map, …). Value types * not known to the SDK will be rejected. * - * Values specified in customOptions will take precedence over any options + * Values specified in rawOptions will take precedence over any options * with the same name set by the SDK. * - * `customOptions` supports dot notation, if you want to override + * `rawOptions` supports dot notation, if you want to override * a nested option. */ - customOptions?: { + rawOptions?: { [name: string]: unknown; }; }; - /** + * @beta * Options defining how a CollectionStage is evaluated. See {@link PipelineSource.collection}. */ export type CollectionStageOptions = StageOptions & { /** + * @beta * Name or reference to the collection that will be used as the Pipeline source. */ collection: string | CollectionReference; /** - * Force index + * @beta + * Specifies the name of an index to be used for a query, overriding the query optimizer's default choice. + * This can be useful for performance tuning in specific scenarios where the default index selection + * does not yield optimal performance. + * + * @remarks This property is optional. When provided, it should be the exact name of the index to force. */ forceIndex?: string; }; /** - * Options defining how a CollectionGroupStage is evaluated. See {@link PipelineSource.collectionGroup}. + * @beta + * Defines the configuration options for a {@link CollectionGroupStage} within a pipeline. + * This type extends {@link StageOptions} and provides specific settings for how a collection group + * is identified and processed during pipeline execution. + * + * @see {@link PipelineSource.collectionGroup} to create a collection group stage. */ export type CollectionGroupStageOptions = StageOptions & { /** + * @beta * ID of the collection group to use as the Pipeline source. */ collectionId: string; /** - * Force index + * @beta + * Specifies the name of an index to be used for a query, overriding the query optimizer's default choice. + * This can be useful for performance tuning in specific scenarios where the default index selection + * does not yield optimal performance. + * + * @remarks This property is optional. When provided, it should be the exact name of the index to force. */ forceIndex?: string; }; - /** + * @beta * Options defining how a DatabaseStage is evaluated. See {@link PipelineSource.database}. */ export type DatabaseStageOptions = StageOptions & {}; - /** + * @beta * Options defining how a DocumentsStage is evaluated. See {@link PipelineSource.documents}. */ export type DocumentsStageOptions = StageOptions & { /** + * @beta * An array of paths and DocumentReferences specifying the individual documents that will be the source of this pipeline. * The converters for these DocumentReferences will be ignored and not have an effect on this pipeline. * There must be at least one document specified in the array. */ docs: Array; }; - /** + * @beta * Options defining how an AddFieldsStage is evaluated. See {@link Pipeline.addFields}. */ export type AddFieldsStageOptions = StageOptions & { /** + * @beta * The fields to add to each document, specified as a {@link Selectable}. * At least one field is required. */ fields: Selectable[]; }; - /** + * @beta * Options defining how a RemoveFieldsStage is evaluated. See {@link Pipeline.removeFields}. */ export type RemoveFieldsStageOptions = StageOptions & { /** + * @beta * The fields to remove from each document. */ fields: Array; }; - /** + * @beta * Options defining how a SelectStage is evaluated. See {@link Pipeline.select}. */ export type SelectStageOptions = StageOptions & { /** + * @beta * The fields to include in the output documents, specified as {@link Selectable} expression * or as a string value indicating the field name. */ selections: Array; }; - /** + * @beta * Options defining how a WhereStage is evaluated. See {@link Pipeline.where}. */ export type WhereStageOptions = StageOptions & { /** + * @beta * The {@link BooleanExpr} to apply as a filter for each input document to this stage. */ condition: BooleanExpr; }; - /** + * @beta * Options defining how an OffsetStage is evaluated. See {@link Pipeline.offset}. */ export type OffsetStageOptions = StageOptions & { /** + * @beta * The number of documents to skip. */ offset: number; }; - /** + * @beta * Options defining how a LimitStage is evaluated. See {@link Pipeline.limit}. */ export type LimitStageOptions = StageOptions & { /** + * @beta * The maximum number of documents to return. */ limit: number; }; - /** + * @beta * Options defining how a DistinctStage is evaluated. See {@link Pipeline.distinct}. */ export type DistinctStageOptions = StageOptions & { /** + * @beta * The {@link Selectable} expressions or field names to consider when determining * distinct value combinations (groups). */ groups: Array; }; - /** + * @beta * Options defining how an AggregateStage is evaluated. See {@link Pipeline.aggregate}. */ export type AggregateStageOptions = StageOptions & { /** - * The {@link AggregateWithAlias} values specifying aggregate operations to + * @beta + * The {@link AliasedAggregate} values specifying aggregate operations to * perform on the input documents. */ - accumulators: AggregateWithAlias[]; - + accumulators: AliasedAggregate[]; /** + * @beta * The {@link Selectable} expressions or field names to consider when determining * distinct value combinations (groups), which will be aggregated over. */ groups?: Array; }; - /** + * @beta * Options defining how a FindNearestStage is evaluated. See {@link Pipeline.findNearest}. */ export type FindNearestStageOptions = StageOptions & { /** - * Specifies the field on the source documents to which the vector distance will be computed against the query vector. + * @beta + * Specifies the field to be used. This can be a string representing the field path + * (e.g., 'fieldName', 'nested.fieldName') or an object of type {@link Field} + * representing a more complex field expression. */ field: Field | string; /** + * @beta * Specifies the query vector value, to which the vector distance will be computed. */ vectorValue: VectorValue | number[]; /** - * Specifies how the distance is computed. + * @beta + * Specifies the method used to compute the distance between vectors. + * + * Possible values are: + * - `'euclidean'`: Euclidean distance. + * - `'cosine'`: Cosine similarity. + * - `'dot_product'`: Dot product. */ distanceMeasure: 'euclidean' | 'cosine' | 'dot_product'; /** + * @beta * The maximum number of documents to return from the FindNearest stage. */ limit?: number; /** + * @beta * If set, specifies the field on the output documents that will contain * the computed vector distance for the document. If not set, the computed * vector distance will not be returned. */ distanceField?: string; }; - /** + * @beta * Options defining how a ReplaceWithStage is evaluated. See {@link Pipeline.replaceWith}. */ export type ReplaceWithStageOptions = StageOptions & { /** + * @beta * The name of a field that contains a map or an {@link Expr} that * evaluates to a map. */ map: Expr | string; }; - /** - * Options defining how a SampleStage is evaluated. See {@link Pipeline.findNearest}. + * @beta + * Defines the options for evaluating a sample stage within a pipeline. + * This type combines common {@link StageOptions} with a specific configuration + * where only one of the defined sampling methods can be applied. + * + * See {@link Pipeline.sample} to create a sample stage.. */ export type SampleStageOptions = StageOptions & OneOf<{ /** + * @beta * If set, specifies the sample rate as a percentage of the * input documents. * @@ -10381,6 +9846,7 @@ declare namespace FirebaseFirestore { */ percentage: number; /** + * @beta * If set, specifies the sample rate as a total number of * documents to sample from the input documents. * @@ -10388,38 +9854,43 @@ declare namespace FirebaseFirestore { */ documents: number; }>; - /** + * @beta * Options defining how a UnionStage is evaluated. See {@link Pipeline.union}. */ export type UnionStageOptions = StageOptions & { /** + * @beta * Specifies the other Pipeline to union with. */ other: Pipeline; }; /** - * Options defining how an UnnestStage is evaluated. See {@link Pipeline.findNearest}. + * @beta + * Represents the specific options available for configuring an `UnnestStage` within a pipeline. */ export type UnnestStageOptions = StageOptions & { /** - * Specifies the expression evaluating to an array of elements, which will be un-nested - * into the field specified by `selectable.alias`. + * @beta + * A `Selectable` object that defines an array expression to be un-nested + * and the alias for the un-nested field. */ selectable: Selectable; /** + * @beta * If set, specifies the field on the output documents that will contain the * offset (starting at zero) that the element is from the original array. */ indexField?: string; }; - /** + * @beta * Options defining how a SortStage is evaluated. See {@link Pipeline.sort}. */ export type SortStageOptions = StageOptions & { /** + * @beta * Orderings specify how the input documents are sorted. * One or more ordering are required. */ @@ -10427,32 +9898,29 @@ declare namespace FirebaseFirestore { }; /** - * Type representing the possible explain stats values. + * @beta + * Represents a field value within the explain statistics, which can be a primitive type (null, string, number, boolean) + * or a recursively defined object where keys are strings and values are also `ExplainStatsFieldValue`. */ export type ExplainStatsFieldValue = | null | string | number | boolean - | {[key: string]: ExplainStatsFieldValue} + | { + [key: string]: ExplainStatsFieldValue; + } | ExplainStatsFieldValue[]; /** - * A wrapper object to access explain stats if explain or analyze - * was enabled for the Pipeline query execution. + * @beta + * Represents the explanation statistics for a {@link Pipeline} query execution. + * These statistics are available when the query is executed with explain or analyze + * options enabled, providing insights into the query's performance and execution plan. */ export class ExplainStats { /** - * When explain stats were requested with `outputFormat = 'json'`, this returns - * the explain stats object parsed from the JSON string returned from the Firestore - * backend. - * - * If explain stats were not requested with `outputFormat = 'json'`, the behavior - * of this method is not guaranteed and is expected to throw. - */ - get json(): {[key: string]: ExplainStatsFieldValue}; - - /** + * @beta * When explain stats were requested with `outputFormat = 'text'`, this returns * the explain stats string verbatium as returned from the Firestore backend. * @@ -10460,10 +9928,11 @@ declare namespace FirebaseFirestore { * the explain stats as stringified JSON, which was returned from the Firestore backend. */ get text(): string; - /** - * Returns the explain stats in an encoded proto format, as returned from the Firestore backend. - * The caller is responsible for unpacking this proto message. + * @beta + * Returns the explain stats as an encoded protocol buffer message, typically wrapped in a `google.protobuf.Any` format. + * This object includes a `type_url` field that identifies the specific type of the serialized message. + * The caller is responsible for deserializing and unpacking this proto message to access the explain stats. */ get rawData(): { type_url?: string | null; @@ -10472,27 +9941,46 @@ declare namespace FirebaseFirestore { } /** - * TODO(docs) + * @beta + * Represents the results of a Firestore pipeline execution. + * + * A `PipelineSnapshot` contains zero or more {@link PipelineResult} objects + * representing the documents returned by a pipeline query. It provides methods + * to iterate over the documents and access metadata about the query results. + * + * @example + * ```typescript + * const snapshot = await firestore + * .pipeline() + * .collection('myCollection') + * .where(field('value').gt(10)) + * .execute(); + * + * snapshot.results.forEach(doc => { + * console.log(doc.id, '=>', doc.data()); + * }); + * ``` */ export class PipelineSnapshot { /** + * @beta * The Pipeline on which you called `execute()` in order to get this * `PipelineSnapshot`. */ get pipeline(): Pipeline; - /** An array of all the results in the `PipelineSnapshot`. */ + /** + * @beta An array of all the results in the `PipelineSnapshot`. */ get results(): PipelineResult[]; /** - * The time at which the pipeline producing this result is executed. - * - * @type {Timestamp} - * + * @beta + * The time at which the pipeline producing this result was executed. */ get executionTime(): Timestamp; /** + * @beta * Return stats from query explain. * * If `explainOptions.mode` was set to `execute` or left unset, then this returns `undefined`. @@ -10502,7 +9990,6 @@ declare namespace FirebaseFirestore { /** * @beta - * * A PipelineResult contains data read from a Firestore Pipeline. The data can be extracted with the * {@link #data()} or {@link #get(String)} methods. * @@ -10513,29 +10000,24 @@ declare namespace FirebaseFirestore { readonly executionTime: Timestamp; readonly createTime: Timestamp | undefined; readonly updateTime: Timestamp | undefined; - /** + * @beta * The reference of the document, if it is a document; otherwise `undefined`. */ - // get ref(): DocumentReference | undefined; + get ref(): DocumentReference | undefined; /** - * The ID of the document for which this PipelineResult contains data, if it is a document; otherwise `undefined`. - * - * @type {string} - * @readonly - * + * @beta + * The ID of the document for which this PipelineResult contains data. + * Returns `undefined` if the PipelineResult does not represent a document. */ get id(): string | undefined; - get ref(): DocumentReference | undefined; - /** - * Retrieves all fields in the result as an object. Returns 'undefined' if - * the document doesn't exist. + * @beta + * Retrieves all fields of the document from the query result as a plain JavaScript object. * - * @returns {T|undefined} An object containing all fields in the document or - * 'undefined' if the document doesn't exist. + * @returns {DocumentData} An object containing all fields in the document. * * @example * ``` @@ -10547,12 +10029,12 @@ declare namespace FirebaseFirestore { * }); * ``` */ - data(): DocumentData | undefined; - + data(): DocumentData; /** + * @beta * Retrieves the field specified by `field`. * - * @param {string|FieldPath} field The field path + * @param {string|FieldPath} fieldPath The field path * (e.g. 'foo' or 'foo.bar') to a specific field. * @returns {*} The data at the specified field location or undefined if no * such field exists. @@ -10570,21 +10052,20 @@ declare namespace FirebaseFirestore { // We deliberately use `any` in the external API to not impose type-checking // on end users. // eslint-disable-next-line @typescript-eslint/no-explicit-any - get(field: string | FieldPath): any; + get(fieldPath: string | FieldPath): any; /** - * Returns true if the document's data and path in this `PipelineResult` is - * equal to the provided value. + * @beta + * Checks if this `PipelineResult` is equal to the provided `other` object. + * Equality is determined by comparing the document's data and path. * - * @param {*} other The value to compare against. - * @return {boolean} true if this `PipelineResult` is equal to the provided - * value. + * @param other The `PipelineResult` to compare against. + * @returns `true` if this `PipelineResult` is equal to the provided value; `false` otherwise. */ isEqual(other: PipelineResult): boolean; } } } - declare module '@google-cloud/firestore' { export = FirebaseFirestore; } From c5f20bc798f6e408a368b1d5f224bff831295ccb Mon Sep 17 00:00:00 2001 From: Mark Duckworth <1124037+MarkDuckworth@users.noreply.github.com> Date: Wed, 29 Oct 2025 14:13:43 -0600 Subject: [PATCH 44/60] API audit edits (#2441) --- dev/src/pipelines/expression.ts | 3509 +++++++++++++--------- dev/src/pipelines/index.ts | 50 +- dev/src/pipelines/pipeline-util.ts | 179 +- dev/src/pipelines/pipelines.ts | 188 +- dev/src/pipelines/stage.ts | 22 +- dev/src/pipelines/structured-pipeline.ts | 2 +- dev/src/reference/aggregate-query.ts | 4 +- dev/src/reference/vector-query.ts | 6 +- dev/src/transaction.ts | 7 +- dev/system-test/pipeline.ts | 775 +++-- dev/system-test/query.ts | 2 +- dev/test/pipelines/pipeline.ts | 2 +- dev/test/structured-pipeline.ts | 6 +- samples/pipelines-quickstart.js | 2 +- types/firestore.d.ts | 2831 +++++++++-------- 15 files changed, 4531 insertions(+), 3054 deletions(-) diff --git a/dev/src/pipelines/expression.ts b/dev/src/pipelines/expression.ts index d8a322d8d..df567b1b7 100644 --- a/dev/src/pipelines/expression.ts +++ b/dev/src/pipelines/expression.ts @@ -40,11 +40,13 @@ import {cast} from '../util'; * - **Literals:** Represent constant values (strings, numbers, booleans). * - **Function calls:** Apply functions to one or more expressions. * - * The `Expr` class provides a fluent API for building expressions. You can chain together + * The `Expression` class provides a fluent API for building expressions. You can chain together * method calls to create complex expressions. */ -export abstract class Expr implements firestore.Pipelines.Expr, HasUserData { - abstract exprType: firestore.Pipelines.ExprType; +export abstract class Expression + implements firestore.Pipelines.Expression, HasUserData +{ + abstract expressionType: firestore.Pipelines.ExpressionType; /** * @beta @@ -81,14 +83,14 @@ export abstract class Expr implements firestore.Pipelines.Expr, HasUserData { * * @param second The expression or literal to add to this expression. * @param others Optional additional expressions or literals to add to this expression. - * @return A new `Expr` representing the addition operation. + * @return A new `Expression` representing the addition operation. */ add( - second: firestore.Pipelines.Expr | unknown, - ...others: Array - ): FunctionExpr { + second: firestore.Pipelines.Expression | unknown, + ...others: Array + ): FunctionExpression { const values = [second, ...others]; - return new FunctionExpr('add', [ + return new FunctionExpression('add', [ this, ...values.map(value => valueToDefaultExpr(value)), ]); @@ -104,9 +106,9 @@ export abstract class Expr implements firestore.Pipelines.Expr, HasUserData { * ``` * * @param subtrahend The expression to subtract from this expression. - * @return A new `Expr` representing the subtraction operation. + * @return A new `Expression` representing the subtraction operation. */ - subtract(subtrahend: firestore.Pipelines.Expr): FunctionExpr; + subtract(subtrahend: firestore.Pipelines.Expression): FunctionExpression; /** * @beta @@ -118,11 +120,16 @@ export abstract class Expr implements firestore.Pipelines.Expr, HasUserData { * ``` * * @param subtrahend The constant value to subtract. - * @return A new `Expr` representing the subtraction operation. + * @return A new `Expression` representing the subtraction operation. */ - subtract(subtrahend: number): FunctionExpr; - subtract(subtrahend: number | firestore.Pipelines.Expr): FunctionExpr { - return new FunctionExpr('subtract', [this, valueToDefaultExpr(subtrahend)]); + subtract(subtrahend: number): FunctionExpression; + subtract( + subtrahend: number | firestore.Pipelines.Expression + ): FunctionExpression { + return new FunctionExpression('subtract', [ + this, + valueToDefaultExpr(subtrahend), + ]); } /** @@ -136,13 +143,13 @@ export abstract class Expr implements firestore.Pipelines.Expr, HasUserData { * * @param second The second expression or literal to multiply by. * @param others Optional additional expressions or literals to multiply by. - * @return A new `Expr` representing the multiplication operation. + * @return A new `Expression` representing the multiplication operation. */ multiply( - second: Expr | number, - ...others: Array - ): FunctionExpr { - return new FunctionExpr('multiply', [ + second: Expression | number, + ...others: Array + ): FunctionExpression { + return new FunctionExpression('multiply', [ this, valueToDefaultExpr(second), ...others.map(value => valueToDefaultExpr(value)), @@ -159,9 +166,9 @@ export abstract class Expr implements firestore.Pipelines.Expr, HasUserData { * ``` * * @param divisor The expression to divide by. - * @return A new `Expr` representing the division operation. + * @return A new `Expression` representing the division operation. */ - divide(divisor: Expr): FunctionExpr; + divide(divisor: Expression): FunctionExpression; /** * @beta @@ -173,11 +180,14 @@ export abstract class Expr implements firestore.Pipelines.Expr, HasUserData { * ``` * * @param divisor The constant value to divide by. - * @return A new `Expr` representing the division operation. + * @return A new `Expression` representing the division operation. */ - divide(divisor: number): FunctionExpr; - divide(divisor: number | Expr): FunctionExpr { - return new FunctionExpr('divide', [this, valueToDefaultExpr(divisor)]); + divide(divisor: number): FunctionExpression; + divide(divisor: number | Expression): FunctionExpression { + return new FunctionExpression('divide', [ + this, + valueToDefaultExpr(divisor), + ]); } /** @@ -190,9 +200,9 @@ export abstract class Expr implements firestore.Pipelines.Expr, HasUserData { * ``` * * @param expression The expression to divide by. - * @return A new `Expr` representing the modulo operation. + * @return A new `Expression` representing the modulo operation. */ - mod(expression: Expr): FunctionExpr; + mod(expression: Expression): FunctionExpression; /** * @beta @@ -204,11 +214,11 @@ export abstract class Expr implements firestore.Pipelines.Expr, HasUserData { * ``` * * @param value The constant value to divide by. - * @return A new `Expr` representing the modulo operation. + * @return A new `Expression` representing the modulo operation. */ - mod(value: number): FunctionExpr; - mod(other: number | Expr): FunctionExpr { - return new FunctionExpr('mod', [this, valueToDefaultExpr(other)]); + mod(value: number): FunctionExpression; + mod(other: number | Expression): FunctionExpression { + return new FunctionExpression('mod', [this, valueToDefaultExpr(other)]); } /** @@ -217,13 +227,13 @@ export abstract class Expr implements firestore.Pipelines.Expr, HasUserData { * * ```typescript * // Check if the 'age' field is equal to 21 - * field("age").eq(21); + * field("age").equal(21); * ``` * * @param expression The expression to compare for equality. - * @return A new `Expr` representing the equality comparison. + * @return A new `Expression` representing the equality comparison. */ - eq(expression: Expr): BooleanExpr; + equal(expression: Expression): BooleanExpression; /** * @beta @@ -231,15 +241,15 @@ export abstract class Expr implements firestore.Pipelines.Expr, HasUserData { * * ```typescript * // Check if the 'city' field is equal to "London" - * field("city").eq("London"); + * field("city").equal("London"); * ``` * * @param value The constant value to compare for equality. - * @return A new `Expr` representing the equality comparison. + * @return A new `Expression` representing the equality comparison. */ - eq(value: unknown): BooleanExpr; - eq(other: unknown): BooleanExpr { - return new BooleanExpr('eq', [this, valueToDefaultExpr(other)]); + equal(value: unknown): BooleanExpression; + equal(other: unknown): BooleanExpression { + return new BooleanExpression('equal', [this, valueToDefaultExpr(other)]); } /** @@ -248,13 +258,13 @@ export abstract class Expr implements firestore.Pipelines.Expr, HasUserData { * * ```typescript * // Check if the 'status' field is not equal to "completed" - * field("status").neq("completed"); + * field("status").notEqual("completed"); * ``` * * @param expression The expression to compare for inequality. - * @return A new `Expr` representing the inequality comparison. + * @return A new `Expression` representing the inequality comparison. */ - neq(expression: Expr): BooleanExpr; + notEqual(expression: Expression): BooleanExpression; /** * @beta @@ -262,15 +272,18 @@ export abstract class Expr implements firestore.Pipelines.Expr, HasUserData { * * ```typescript * // Check if the 'country' field is not equal to "USA" - * field("country").neq("USA"); + * field("country").notEqual("USA"); * ``` * * @param value The constant value to compare for inequality. - * @return A new `Expr` representing the inequality comparison. + * @return A new `Expression` representing the inequality comparison. */ - neq(value: unknown): BooleanExpr; - neq(other: unknown): BooleanExpr { - return new BooleanExpr('neq', [this, valueToDefaultExpr(other)]); + notEqual(value: unknown): BooleanExpression; + notEqual(other: unknown): BooleanExpression { + return new BooleanExpression('not_equal', [ + this, + valueToDefaultExpr(other), + ]); } /** @@ -279,13 +292,13 @@ export abstract class Expr implements firestore.Pipelines.Expr, HasUserData { * * ```typescript * // Check if the 'age' field is less than 'limit' - * field("age").lt(field('limit')); + * field("age").lessThan(field('limit')); * ``` * * @param experession The expression to compare for less than. - * @return A new `Expr` representing the less than comparison. + * @return A new `Expression` representing the less than comparison. */ - lt(experession: Expr): BooleanExpr; + lessThan(experession: Expression): BooleanExpression; /** * @beta @@ -293,15 +306,18 @@ export abstract class Expr implements firestore.Pipelines.Expr, HasUserData { * * ```typescript * // Check if the 'price' field is less than 50 - * field("price").lt(50); + * field("price").lessThan(50); * ``` * * @param value The constant value to compare for less than. - * @return A new `Expr` representing the less than comparison. + * @return A new `Expression` representing the less than comparison. */ - lt(value: unknown): BooleanExpr; - lt(other: unknown): BooleanExpr { - return new BooleanExpr('lt', [this, valueToDefaultExpr(other)]); + lessThan(value: unknown): BooleanExpression; + lessThan(other: unknown): BooleanExpression { + return new BooleanExpression('less_than', [ + this, + valueToDefaultExpr(other), + ]); } /** @@ -311,13 +327,13 @@ export abstract class Expr implements firestore.Pipelines.Expr, HasUserData { * * ```typescript * // Check if the 'quantity' field is less than or equal to 20 - * field("quantity").lte(constant(20)); + * field("quantity").lessThanOrEqual(constant(20)); * ``` * * @param expression The expression to compare for less than or equal to. - * @return A new `Expr` representing the less than or equal to comparison. + * @return A new `Expression` representing the less than or equal to comparison. */ - lte(expression: Expr): BooleanExpr; + lessThanOrEqual(expression: Expression): BooleanExpression; /** * @beta @@ -325,15 +341,18 @@ export abstract class Expr implements firestore.Pipelines.Expr, HasUserData { * * ```typescript * // Check if the 'score' field is less than or equal to 70 - * field("score").lte(70); + * field("score").lessThanOrEqual(70); * ``` * * @param value The constant value to compare for less than or equal to. - * @return A new `Expr` representing the less than or equal to comparison. + * @return A new `Expression` representing the less than or equal to comparison. */ - lte(value: unknown): BooleanExpr; - lte(other: unknown): BooleanExpr { - return new BooleanExpr('lte', [this, valueToDefaultExpr(other)]); + lessThanOrEqual(value: unknown): BooleanExpression; + lessThanOrEqual(other: unknown): BooleanExpression { + return new BooleanExpression('less_than_or_equal', [ + this, + valueToDefaultExpr(other), + ]); } /** @@ -342,13 +361,13 @@ export abstract class Expr implements firestore.Pipelines.Expr, HasUserData { * * ```typescript * // Check if the 'age' field is greater than the 'limit' field - * field("age").gt(field("limit")); + * field("age").greaterThan(field("limit")); * ``` * * @param expression The expression to compare for greater than. - * @return A new `Expr` representing the greater than comparison. + * @return A new `Expression` representing the greater than comparison. */ - gt(expression: Expr): BooleanExpr; + greaterThan(expression: Expression): BooleanExpression; /** * @beta @@ -356,15 +375,18 @@ export abstract class Expr implements firestore.Pipelines.Expr, HasUserData { * * ```typescript * // Check if the 'price' field is greater than 100 - * field("price").gt(100); + * field("price").greaterThan(100); * ``` * * @param value The constant value to compare for greater than. - * @return A new `Expr` representing the greater than comparison. + * @return A new `Expression` representing the greater than comparison. */ - gt(value: unknown): BooleanExpr; - gt(other: unknown): BooleanExpr { - return new BooleanExpr('gt', [this, valueToDefaultExpr(other)]); + greaterThan(value: unknown): BooleanExpression; + greaterThan(other: unknown): BooleanExpression { + return new BooleanExpression('greater_than', [ + this, + valueToDefaultExpr(other), + ]); } /** @@ -374,13 +396,13 @@ export abstract class Expr implements firestore.Pipelines.Expr, HasUserData { * * ```typescript * // Check if the 'quantity' field is greater than or equal to field 'requirement' plus 1 - * field("quantity").gte(field('requirement').add(1)); + * field("quantity").greaterThanOrEqual(field('requirement').add(1)); * ``` * * @param expression The expression to compare for greater than or equal to. - * @return A new `Expr` representing the greater than or equal to comparison. + * @return A new `Expression` representing the greater than or equal to comparison. */ - gte(expression: Expr): BooleanExpr; + greaterThanOrEqual(expression: Expression): BooleanExpression; /** * @beta @@ -389,15 +411,39 @@ export abstract class Expr implements firestore.Pipelines.Expr, HasUserData { * * ```typescript * // Check if the 'score' field is greater than or equal to 80 - * field("score").gte(80); + * field("score").greaterThanOrEqual(80); * ``` * * @param value The constant value to compare for greater than or equal to. - * @return A new `Expr` representing the greater than or equal to comparison. + * @return A new `Expression` representing the greater than or equal to comparison. */ - gte(value: unknown): BooleanExpr; - gte(other: unknown): BooleanExpr { - return new BooleanExpr('gte', [this, valueToDefaultExpr(other)]); + greaterThanOrEqual(value: unknown): BooleanExpression; + greaterThanOrEqual(other: unknown): BooleanExpression { + return new BooleanExpression('greater_than_or_equal', [ + this, + valueToDefaultExpr(other), + ]); + } + + /** + * @beta + * Creates an expression that concatenates an array expression with one or more other arrays. + * + * ```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. + * @return A new `Expr` representing the concatenated array. + */ + arrayConcat( + secondArray: Expression | unknown[], + ...otherArrays: Array + ): FunctionExpression { + const elements = [secondArray, ...otherArrays]; + const exprValues = elements.map(value => valueToDefaultExpr(value)); + return new FunctionExpression('array_concat', [this, ...exprValues]); } /** @@ -410,9 +456,9 @@ export abstract class Expr implements firestore.Pipelines.Expr, HasUserData { * ``` * * @param expression The element to search for in the array. - * @return A new `Expr` representing the 'array_contains' comparison. + * @return A new `Expression` representing the 'array_contains' comparison. */ - arrayContains(expression: Expr): BooleanExpr; + arrayContains(expression: Expression): BooleanExpression; /** * @beta @@ -424,11 +470,11 @@ export abstract class Expr implements firestore.Pipelines.Expr, HasUserData { * ``` * * @param value The element to search for in the array. - * @return A new `Expr` representing the 'array_contains' comparison. + * @return A new `Expression` representing the 'array_contains' comparison. */ - arrayContains(value: unknown): BooleanExpr; - arrayContains(element: unknown): BooleanExpr { - return new BooleanExpr('array_contains', [ + arrayContains(value: unknown): BooleanExpression; + arrayContains(element: unknown): BooleanExpression { + return new BooleanExpression('array_contains', [ this, valueToDefaultExpr(element), ]); @@ -444,9 +490,9 @@ export abstract class Expr implements firestore.Pipelines.Expr, HasUserData { * ``` * * @param values The elements to check for in the array. - * @return A new `Expr` representing the 'array_contains_all' comparison. + * @return A new `Expression` representing the 'array_contains_all' comparison. */ - arrayContainsAll(values: Array): BooleanExpr; + arrayContainsAll(values: Array): BooleanExpression; /** * @beta @@ -458,14 +504,14 @@ export abstract class Expr implements firestore.Pipelines.Expr, HasUserData { * ``` * * @param arrayExpression The elements to check for in the array. - * @return A new `Expr` representing the 'array_contains_all' comparison. + * @return A new `Expression` representing the 'array_contains_all' comparison. */ - arrayContainsAll(arrayExpression: Expr): BooleanExpr; - arrayContainsAll(values: unknown[] | Expr): BooleanExpr { + arrayContainsAll(arrayExpression: Expression): BooleanExpression; + arrayContainsAll(values: unknown[] | Expression): BooleanExpression { const normalizedExpr = Array.isArray(values) ? new ListOfExprs(values.map(valueToDefaultExpr)) - : cast(values); - return new BooleanExpr('array_contains_all', [this, normalizedExpr]); + : cast(values); + return new BooleanExpression('array_contains_all', [this, normalizedExpr]); } /** @@ -478,9 +524,9 @@ export abstract class Expr implements firestore.Pipelines.Expr, HasUserData { * ``` * * @param values The elements to check for in the array. - * @return A new `Expr` representing the 'array_contains_any' comparison. + * @return A new `Expression` representing the 'array_contains_any' comparison. */ - arrayContainsAny(values: Array): BooleanExpr; + arrayContainsAny(values: Array): BooleanExpression; /** * @beta @@ -493,14 +539,16 @@ export abstract class Expr implements firestore.Pipelines.Expr, HasUserData { * ``` * * @param arrayExpression The elements to check for in the array. - * @return A new `Expr` representing the 'array_contains_any' comparison. + * @return A new `Expression` representing the 'array_contains_any' comparison. */ - arrayContainsAny(arrayExpression: Expr): BooleanExpr; - arrayContainsAny(values: Array | Expr): BooleanExpr { + arrayContainsAny(arrayExpression: Expression): BooleanExpression; + arrayContainsAny( + values: Array | Expression + ): BooleanExpression { const normalizedExpr = Array.isArray(values) ? new ListOfExprs(values.map(valueToDefaultExpr)) - : cast(values); - return new BooleanExpr('array_contains_any', [this, normalizedExpr]); + : cast(values); + return new BooleanExpression('array_contains_any', [this, normalizedExpr]); } /** @@ -512,10 +560,10 @@ export abstract class Expr implements firestore.Pipelines.Expr, HasUserData { * field("myArray").arrayReverse(); * ``` * - * @return A new {@code Expr} representing the reversed array. + * @return A new {@code Expression} representing the reversed array. */ - arrayReverse(): FunctionExpr { - return new FunctionExpr('array_reverse', [this]); + arrayReverse(): FunctionExpression { + return new FunctionExpression('array_reverse', [this]); } /** @@ -527,10 +575,10 @@ export abstract class Expr implements firestore.Pipelines.Expr, HasUserData { * field("cart").arrayLength(); * ``` * - * @return A new `Expr` representing the length of the array. + * @return A new `Expression` representing the length of the array. */ - arrayLength(): FunctionExpr { - return new FunctionExpr('array_length', [this]); + arrayLength(): FunctionExpression { + return new FunctionExpression('array_length', [this]); } /** @@ -540,13 +588,13 @@ export abstract class Expr implements firestore.Pipelines.Expr, HasUserData { * * ```typescript * // Check if the 'category' field is either "Electronics" or value of field 'primaryType' - * field("category").eqAny("Electronics", field("primaryType")); + * field("category").equalAny("Electronics", field("primaryType")); * ``` * * @param values The values or expressions to check against. - * @return A new `Expr` representing the 'IN' comparison. + * @return A new `Expression` representing the 'IN' comparison. */ - eqAny(values: Array): BooleanExpr; + equalAny(values: Array): BooleanExpression; /** * @beta @@ -555,18 +603,18 @@ export abstract class Expr implements firestore.Pipelines.Expr, HasUserData { * * ```typescript * // Check if the 'category' field is either "Electronics" or value of field 'primaryType' - * field("category").eqAny(array(["Electronics", field("primaryType")])); + * field("category").equalAny(array(["Electronics", field("primaryType")])); * ``` * * @param arrayExpression An expression that evaluates to an array of values to check against. - * @return A new `Expr` representing the 'IN' comparison. + * @return A new `Expression` representing the 'IN' comparison. */ - eqAny(arrayExpression: Expr): BooleanExpr; - eqAny(others: unknown[] | Expr): BooleanExpr { + equalAny(arrayExpression: Expression): BooleanExpression; + equalAny(others: unknown[] | Expression): BooleanExpression { const exprOthers = Array.isArray(others) ? new ListOfExprs(others.map(valueToDefaultExpr)) - : cast(others); - return new BooleanExpr('eq_any', [this, exprOthers]); + : cast(others); + return new BooleanExpression('equal_any', [this, exprOthers]); } /** @@ -576,13 +624,13 @@ export abstract class Expr implements firestore.Pipelines.Expr, HasUserData { * * ```typescript * // Check if the 'status' field is neither "pending" nor the value of 'rejectedStatus' - * field("status").notEqAny(["pending", field("rejectedStatus")]); + * field("status").notEqualAny(["pending", field("rejectedStatus")]); * ``` * * @param values The values or expressions to check against. - * @return A new `Expr` representing the 'NotEqAny' comparison. + * @return A new `Expression` representing the 'NotEqAny' comparison. */ - notEqAny(values: Array): BooleanExpr; + notEqualAny(values: Array): BooleanExpression; /** * @beta @@ -590,48 +638,18 @@ export abstract class Expr implements firestore.Pipelines.Expr, HasUserData { * * ```typescript * // Check if the 'status' field is not equal to any value in the field 'rejectedStatuses' - * field("status").notEqAny(field('rejectedStatuses')); + * field("status").notEqualAny(field('rejectedStatuses')); * ``` * * @param arrayExpression The values or expressions to check against. - * @return A new `Expr` representing the 'NotEqAny' comparison. + * @return A new `Expression` representing the 'NotEqAny' comparison. */ - notEqAny(arrayExpression: Expr): BooleanExpr; - notEqAny(others: unknown[] | Expr): BooleanExpr { + notEqualAny(arrayExpression: Expression): BooleanExpression; + notEqualAny(others: unknown[] | Expression): BooleanExpression { const exprOthers = Array.isArray(others) ? new ListOfExprs(others.map(valueToDefaultExpr)) - : cast(others); - return new BooleanExpr('not_eq_any', [this, exprOthers]); - } - - /** - * @beta - * Creates an expression that checks if this expression evaluates to 'NaN' (Not a Number). - * - * ```typescript - * // Check if the result of a calculation is NaN - * field("value").divide(0).isNan(); - * ``` - * - * @return A new `Expr` representing the 'isNan' check. - */ - isNan(): BooleanExpr { - return new BooleanExpr('is_nan', [this]); - } - - /** - * @beta - * Creates an expression that checks if this expression evaluates to 'Null'. - * - * ```typescript - * // Check if the result of a calculation is NaN - * field("value").isNull(); - * ``` - * - * @return A new `Expr` representing the 'isNull' check. - */ - isNull(): BooleanExpr { - return new BooleanExpr('is_null', [this]); + : cast(others); + return new BooleanExpression('not_equal_any', [this, exprOthers]); } /** @@ -643,10 +661,10 @@ export abstract class Expr implements firestore.Pipelines.Expr, HasUserData { * field("phoneNumber").exists(); * ``` * - * @return A new `Expr` representing the 'exists' check. + * @return A new `Expression` representing the 'exists' check. */ - exists(): BooleanExpr { - return new BooleanExpr('exists', [this]); + exists(): BooleanExpression { + return new BooleanExpression('exists', [this]); } /** @@ -658,10 +676,10 @@ export abstract class Expr implements firestore.Pipelines.Expr, HasUserData { * field("name").charLength(); * ``` * - * @return A new `Expr` representing the length of the string. + * @return A new `Expression` representing the length of the string. */ - charLength(): FunctionExpr { - return new FunctionExpr('char_length', [this]); + charLength(): FunctionExpression { + return new FunctionExpression('char_length', [this]); } /** @@ -674,9 +692,9 @@ export abstract class Expr implements firestore.Pipelines.Expr, HasUserData { * ``` * * @param pattern The pattern to search for. You can use "%" as a wildcard character. - * @return A new `Expr` representing the 'like' comparison. + * @return A new `Expression` representing the 'like' comparison. */ - like(pattern: string): FunctionExpr; + like(pattern: string): FunctionExpression; /** * @beta @@ -688,11 +706,14 @@ export abstract class Expr implements firestore.Pipelines.Expr, HasUserData { * ``` * * @param pattern The pattern to search for. You can use "%" as a wildcard character. - * @return A new `Expr` representing the 'like' comparison. + * @return A new `Expression` representing the 'like' comparison. */ - like(pattern: Expr): FunctionExpr; - like(stringOrExpr: string | Expr): FunctionExpr { - return new BooleanExpr('like', [this, valueToDefaultExpr(stringOrExpr)]); + like(pattern: Expression): FunctionExpression; + like(stringOrExpr: string | Expression): FunctionExpression { + return new BooleanExpression('like', [ + this, + valueToDefaultExpr(stringOrExpr), + ]); } /** @@ -706,9 +727,9 @@ export abstract class Expr implements firestore.Pipelines.Expr, HasUserData { * ``` * * @param pattern The regular expression to use for the search. - * @return A new `Expr` representing the 'contains' comparison. + * @return A new `Expression` representing the 'contains' comparison. */ - regexContains(pattern: string): BooleanExpr; + regexContains(pattern: string): BooleanExpression; /** * @beta @@ -721,11 +742,11 @@ export abstract class Expr implements firestore.Pipelines.Expr, HasUserData { * ``` * * @param pattern The regular expression to use for the search. - * @return A new `Expr` representing the 'contains' comparison. + * @return A new `Expression` representing the 'contains' comparison. */ - regexContains(pattern: Expr): BooleanExpr; - regexContains(stringOrExpr: string | Expr): BooleanExpr { - return new BooleanExpr('regex_contains', [ + regexContains(pattern: Expression): BooleanExpression; + regexContains(stringOrExpr: string | Expression): BooleanExpression { + return new BooleanExpression('regex_contains', [ this, valueToDefaultExpr(stringOrExpr), ]); @@ -741,9 +762,9 @@ export abstract class Expr implements firestore.Pipelines.Expr, HasUserData { * ``` * * @param pattern The regular expression to use for the match. - * @return A new `Expr` representing the regular expression match. + * @return A new `Expression` representing the regular expression match. */ - regexMatch(pattern: string): BooleanExpr; + regexMatch(pattern: string): BooleanExpression; /** * @beta @@ -755,11 +776,11 @@ export abstract class Expr implements firestore.Pipelines.Expr, HasUserData { * ``` * * @param pattern The regular expression to use for the match. - * @return A new `Expr` representing the regular expression match. + * @return A new `Expression` representing the regular expression match. */ - regexMatch(pattern: Expr): BooleanExpr; - regexMatch(stringOrExpr: string | Expr): BooleanExpr { - return new BooleanExpr('regex_match', [ + regexMatch(pattern: Expression): BooleanExpression; + regexMatch(stringOrExpr: string | Expression): BooleanExpression { + return new BooleanExpression('regex_match', [ this, valueToDefaultExpr(stringOrExpr), ]); @@ -771,13 +792,13 @@ export abstract class Expr implements firestore.Pipelines.Expr, HasUserData { * * ```typescript * // Check if the 'description' field contains "example". - * field("description").strContains("example"); + * field("description").stringContains("example"); * ``` * * @param substring The substring to search for. - * @return A new `Expr` representing the 'contains' comparison. + * @return A new `Expression` representing the 'contains' comparison. */ - strContains(substring: string): BooleanExpr; + stringContains(substring: string): BooleanExpression; /** * @beta @@ -785,15 +806,15 @@ export abstract class Expr implements firestore.Pipelines.Expr, HasUserData { * * ```typescript * // Check if the 'description' field contains the value of the 'keyword' field. - * field("description").strContains(field("keyword")); + * field("description").stringContains(field("keyword")); * ``` * * @param expr The expression representing the substring to search for. - * @return A new `Expr` representing the 'contains' comparison. + * @return A new `Expression` representing the 'contains' comparison. */ - strContains(expr: Expr): BooleanExpr; - strContains(stringOrExpr: string | Expr): BooleanExpr { - return new BooleanExpr('str_contains', [ + stringContains(expr: Expression): BooleanExpression; + stringContains(stringOrExpr: string | Expression): BooleanExpression { + return new BooleanExpression('string_contains', [ this, valueToDefaultExpr(stringOrExpr), ]); @@ -809,9 +830,9 @@ export abstract class Expr implements firestore.Pipelines.Expr, HasUserData { * ``` * * @param prefix The prefix to check for. - * @return A new `Expr` representing the 'starts with' comparison. + * @return A new `Expression` representing the 'starts with' comparison. */ - startsWith(prefix: string): BooleanExpr; + startsWith(prefix: string): BooleanExpression; /** * @beta @@ -824,11 +845,11 @@ export abstract class Expr implements firestore.Pipelines.Expr, HasUserData { * ``` * * @param prefix The prefix expression to check for. - * @return A new `Expr` representing the 'starts with' comparison. + * @return A new `Expression` representing the 'starts with' comparison. */ - startsWith(prefix: Expr): BooleanExpr; - startsWith(stringOrExpr: string | Expr): BooleanExpr { - return new BooleanExpr('starts_with', [ + startsWith(prefix: Expression): BooleanExpression; + startsWith(stringOrExpr: string | Expression): BooleanExpression { + return new BooleanExpression('starts_with', [ this, valueToDefaultExpr(stringOrExpr), ]); @@ -844,9 +865,9 @@ export abstract class Expr implements firestore.Pipelines.Expr, HasUserData { * ``` * * @param suffix The postfix to check for. - * @return A new `Expr` representing the 'ends with' comparison. + * @return A new `Expression` representing the 'ends with' comparison. */ - endsWith(suffix: string): BooleanExpr; + endsWith(suffix: string): BooleanExpression; /** * @beta @@ -859,11 +880,11 @@ export abstract class Expr implements firestore.Pipelines.Expr, HasUserData { * ``` * * @param suffix The postfix expression to check for. - * @return A new `Expr` representing the 'ends with' comparison. + * @return A new `Expression` representing the 'ends with' comparison. */ - endsWith(suffix: Expr): BooleanExpr; - endsWith(stringOrExpr: string | Expr): BooleanExpr { - return new BooleanExpr('ends_with', [ + endsWith(suffix: Expression): BooleanExpression; + endsWith(stringOrExpr: string | Expression): BooleanExpression { + return new BooleanExpression('ends_with', [ this, valueToDefaultExpr(stringOrExpr), ]); @@ -878,10 +899,10 @@ export abstract class Expr implements firestore.Pipelines.Expr, HasUserData { * field("name").toLower(); * ``` * - * @return A new `Expr` representing the lowercase string. + * @return A new `Expression` representing the lowercase string. */ - toLower(): FunctionExpr { - return new FunctionExpr('to_lower', [this]); + toLower(): FunctionExpression { + return new FunctionExpression('to_lower', [this]); } /** @@ -893,10 +914,10 @@ export abstract class Expr implements firestore.Pipelines.Expr, HasUserData { * field("title").toUpper(); * ``` * - * @return A new `Expr` representing the uppercase string. + * @return A new `Expression` representing the uppercase string. */ - toUpper(): FunctionExpr { - return new FunctionExpr('to_upper', [this]); + toUpper(): FunctionExpression { + return new FunctionExpression('to_upper', [this]); } /** @@ -908,10 +929,10 @@ export abstract class Expr implements firestore.Pipelines.Expr, HasUserData { * field("userInput").trim(); * ``` * - * @return A new `Expr` representing the trimmed string. + * @return A new `Expression` representing the trimmed string. */ - trim(): FunctionExpr { - return new FunctionExpr('trim', [this]); + trim(): FunctionExpression { + return new FunctionExpression('trim', [this]); } /** @@ -920,35 +941,57 @@ export abstract class Expr implements firestore.Pipelines.Expr, HasUserData { * * ```typescript * // Combine the 'firstName', " ", and 'lastName' fields into a single string - * field("firstName").strConcat(constant(" "), field("lastName")); + * 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. - * @return A new `Expr` representing the concatenated string. + * @return A new `Expression` representing the concatenated string. */ - strConcat( - secondString: Expr | string, - ...otherStrings: Array - ): FunctionExpr { + stringConcat( + secondString: Expression | string, + ...otherStrings: Array + ): FunctionExpression { const elements = [secondString, ...otherStrings]; const exprs = elements.map(valueToDefaultExpr); - return new FunctionExpr('str_concat', [this, ...exprs]); + return new FunctionExpression('string_concat', [this, ...exprs]); } /** * @beta - * Creates an expression that reverses this string expression. + * Creates an expression that concatenates expression results together. + * + * ```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. + * @return A new `Expr` representing the concatenated value. + */ + concat( + second: Expression | unknown, + ...others: Array + ): FunctionExpression { + const elements = [second, ...others]; + const exprs = elements.map(valueToDefaultExpr); + return new FunctionExpression('concat', [this, ...exprs]); + } + + /** + * @beta + * Creates an expression that reverses this string or bytes expression. * * ```typescript * // Reverse the value of the 'myString' field. * field("myString").reverse(); * ``` * - * @return A new {@code Expr} representing the reversed string. + * @return A new {@code Expression} representing the reversed string or bytes. */ - reverse(): FunctionExpr { - return new FunctionExpr('reverse', [this]); + reverse(): FunctionExpression { + return new FunctionExpression('reverse', [this]); } /** @@ -960,10 +1003,10 @@ export abstract class Expr implements firestore.Pipelines.Expr, HasUserData { * field("myString").byteLength(); * ``` * - * @return A new {@code Expr} representing the length of the string in bytes. + * @return A new {@code Expression} representing the length of the string in bytes. */ - byteLength(): FunctionExpr { - return new FunctionExpr('byte_length', [this]); + byteLength(): FunctionExpression { + return new FunctionExpression('byte_length', [this]); } /** @@ -975,10 +1018,10 @@ export abstract class Expr implements firestore.Pipelines.Expr, HasUserData { * field("price").ceil(); * ``` * - * @return A new {@code Expr} representing the ceiling of the numeric value. + * @return A new {@code Expression} representing the ceiling of the numeric value. */ - ceil(): FunctionExpr { - return new FunctionExpr('ceil', [this]); + ceil(): FunctionExpression { + return new FunctionExpression('ceil', [this]); } /** @@ -990,10 +1033,25 @@ export abstract class Expr implements firestore.Pipelines.Expr, HasUserData { * field("price").floor(); * ``` * - * @return A new {@code Expr} representing the floor of the numeric value. + * @return A new {@code Expression} representing the floor of the numeric value. + */ + floor(): FunctionExpression { + return new FunctionExpression('floor', [this]); + } + + /** + * @beta + * Creates an expression that computes the absolute value of a numeric value. + * + * ```typescript + * // Compute the absolute value of the 'price' field. + * field("price").abs(); + * ``` + * + * @return A new {@code Expr} representing the absolute value of the numeric value. */ - floor(): FunctionExpr { - return new FunctionExpr('floor', [this]); + abs(): FunctionExpression { + return new FunctionExpression('abs', [this]); } /** @@ -1005,10 +1063,10 @@ export abstract class Expr implements firestore.Pipelines.Expr, HasUserData { * field("value").exp(); * ``` * - * @return A new {@code Expr} representing the exp of the numeric value. + * @return A new {@code Expression} representing the exp of the numeric value. */ - exp(): FunctionExpr { - return new FunctionExpr('exp', [this]); + exp(): FunctionExpression { + return new FunctionExpression('exp', [this]); } /** @@ -1021,10 +1079,10 @@ export abstract class Expr implements firestore.Pipelines.Expr, HasUserData { * ``` * * @param subfield The key to access in the map. - * @return A new `Expr` representing the value associated with the given key in the map. + * @return A new `Expression` representing the value associated with the given key in the map. */ - mapGet(subfield: string): FunctionExpr { - return new FunctionExpr('map_get', [this, constant(subfield)]); + mapGet(subfield: string): FunctionExpression { + return new FunctionExpression('map_get', [this, constant(subfield)]); } /** @@ -1065,13 +1123,13 @@ export abstract class Expr implements firestore.Pipelines.Expr, HasUserData { * * ```typescript * // Calculate the average age of users - * field("age").avg().as("averageAge"); + * field("age").average().as("averageAge"); * ``` * - * @return A new `AggregateFunction` representing the 'avg' aggregation. + * @return A new `AggregateFunction` representing the 'average' aggregation. */ - avg(): AggregateFunction { - return new AggregateFunction('avg', [this]); + average(): AggregateFunction { + return new AggregateFunction('average', [this]); } /** @@ -1086,7 +1144,7 @@ export abstract class Expr implements firestore.Pipelines.Expr, HasUserData { * @return A new `AggregateFunction` representing the 'min' aggregation. */ minimum(): AggregateFunction { - return new AggregateFunction('min', [this]); + return new AggregateFunction('minimum', [this]); } /** @@ -1101,7 +1159,7 @@ export abstract class Expr implements firestore.Pipelines.Expr, HasUserData { * @return A new `AggregateFunction` representing the 'max' aggregation. */ maximum(): AggregateFunction { - return new AggregateFunction('max', [this]); + return new AggregateFunction('maximum', [this]); } /** @@ -1130,14 +1188,17 @@ export abstract class Expr implements firestore.Pipelines.Expr, HasUserData { * * @param second The second expression or literal to compare with. * @param others Optional additional expressions or literals to compare with. - * @return A new {@code Expr} representing the logical max operation. + * @return A new {@code Expression} representing the logical max operation. */ logicalMaximum( - second: Expr | unknown, - ...others: Array - ): FunctionExpr { + second: Expression | unknown, + ...others: Array + ): FunctionExpression { const values = [second, ...others]; - return new FunctionExpr('max', [this, ...values.map(valueToDefaultExpr)]); + return new FunctionExpression('maximum', [ + this, + ...values.map(valueToDefaultExpr), + ]); } /** @@ -1151,14 +1212,17 @@ export abstract class Expr implements firestore.Pipelines.Expr, HasUserData { * * @param second The second expression or literal to compare with. * @param others Optional additional expressions or literals to compare with. - * @return A new {@code Expr} representing the logical min operation. + * @return A new {@code Expression} representing the logical min operation. */ logicalMinimum( - second: Expr | unknown, - ...others: Array - ): FunctionExpr { + second: Expression | unknown, + ...others: Array + ): FunctionExpression { const values = [second, ...others]; - return new FunctionExpr('min', [this, ...values.map(valueToDefaultExpr)]); + return new FunctionExpression('minimum', [ + this, + ...values.map(valueToDefaultExpr), + ]); } /** @@ -1170,10 +1234,10 @@ export abstract class Expr implements firestore.Pipelines.Expr, HasUserData { * field("embedding").vectorLength(); * ``` * - * @return A new {@code Expr} representing the length of the vector. + * @return A new {@code Expression} representing the length of the vector. */ - vectorLength(): FunctionExpr { - return new FunctionExpr('vector_length', [this]); + vectorLength(): FunctionExpression { + return new FunctionExpression('vector_length', [this]); } /** @@ -1185,10 +1249,10 @@ export abstract class Expr implements firestore.Pipelines.Expr, HasUserData { * field("userVector").cosineDistance(field("itemVector")); * ``` * - * @param vectorExpression The other vector (represented as an Expr) to compare against. - * @return A new `Expr` representing the cosine distance between the two vectors. + * @param vectorExpression The other vector (represented as an Expression) to compare against. + * @return A new `Expression` representing the cosine distance between the two vectors. */ - cosineDistance(vectorExpression: Expr): FunctionExpr; + cosineDistance(vectorExpression: Expression): FunctionExpression; /** * @beta * Calculates the Cosine distance between two vectors. @@ -1199,11 +1263,16 @@ export abstract class Expr implements firestore.Pipelines.Expr, HasUserData { * ``` * * @param vector The other vector (as a VectorValue) to compare against. - * @return A new `Expr` representing the Cosine* distance between the two vectors. + * @return A new `Expression` representing the Cosine* distance between the two vectors. */ - cosineDistance(vector: firestore.VectorValue | number[]): FunctionExpr; - cosineDistance(other: Expr | firestore.VectorValue | number[]): FunctionExpr { - return new FunctionExpr('cosine_distance', [this, vectorToExpr(other)]); + cosineDistance(vector: firestore.VectorValue | number[]): FunctionExpression; + cosineDistance( + other: Expression | firestore.VectorValue | number[] + ): FunctionExpression { + return new FunctionExpression('cosine_distance', [ + this, + vectorToExpr(other), + ]); } /** @@ -1216,9 +1285,9 @@ export abstract class Expr implements firestore.Pipelines.Expr, HasUserData { * ``` * * @param vectorExpression The other vector (as an array of numbers) to calculate with. - * @return A new `Expr` representing the dot product between the two vectors. + * @return A new `Expression` representing the dot product between the two vectors. */ - dotProduct(vectorExpression: Expr): FunctionExpr; + dotProduct(vectorExpression: Expression): FunctionExpression; /** * @beta @@ -1230,11 +1299,13 @@ export abstract class Expr implements firestore.Pipelines.Expr, HasUserData { * ``` * * @param vector The other vector (as an array of numbers) to calculate with. - * @return A new `Expr` representing the dot product between the two vectors. + * @return A new `Expression` representing the dot product between the two vectors. */ - dotProduct(vector: firestore.VectorValue | number[]): FunctionExpr; - dotProduct(other: Expr | firestore.VectorValue | number[]): FunctionExpr { - return new FunctionExpr('dot_product', [this, vectorToExpr(other)]); + dotProduct(vector: firestore.VectorValue | number[]): FunctionExpression; + dotProduct( + other: Expression | firestore.VectorValue | number[] + ): FunctionExpression { + return new FunctionExpression('dot_product', [this, vectorToExpr(other)]); } /** @@ -1247,9 +1318,9 @@ export abstract class Expr implements firestore.Pipelines.Expr, HasUserData { * ``` * * @param vectorExpression The other vector (as an array of numbers) to calculate with. - * @return A new `Expr` representing the Euclidean distance between the two vectors. + * @return A new `Expression` representing the Euclidean distance between the two vectors. */ - euclideanDistance(vectorExpression: Expr): FunctionExpr; + euclideanDistance(vectorExpression: Expression): FunctionExpression; /** * @beta @@ -1261,13 +1332,18 @@ export abstract class Expr implements firestore.Pipelines.Expr, HasUserData { * ``` * * @param vector The other vector (as a VectorValue) to compare against. - * @return A new `Expr` representing the Euclidean distance between the two vectors. + * @return A new `Expression` representing the Euclidean distance between the two vectors. */ - euclideanDistance(vector: firestore.VectorValue | number[]): FunctionExpr; euclideanDistance( - other: Expr | firestore.VectorValue | number[] - ): FunctionExpr { - return new FunctionExpr('euclidean_distance', [this, vectorToExpr(other)]); + vector: firestore.VectorValue | number[] + ): FunctionExpression; + euclideanDistance( + other: Expression | firestore.VectorValue | number[] + ): FunctionExpression { + return new FunctionExpression('euclidean_distance', [ + this, + vectorToExpr(other), + ]); } /** @@ -1280,10 +1356,10 @@ export abstract class Expr implements firestore.Pipelines.Expr, HasUserData { * field("microseconds").unixMicrosToTimestamp(); * ``` * - * @return A new {@code Expr} representing the timestamp. + * @return A new {@code Expression} representing the timestamp. */ - unixMicrosToTimestamp(): FunctionExpr { - return new FunctionExpr('unix_micros_to_timestamp', [this]); + unixMicrosToTimestamp(): FunctionExpression { + return new FunctionExpression('unix_micros_to_timestamp', [this]); } /** @@ -1295,10 +1371,10 @@ export abstract class Expr implements firestore.Pipelines.Expr, HasUserData { * field("timestamp").timestampToUnixMicros(); * ``` * - * @return A new {@code Expr} representing the number of microseconds since epoch. + * @return A new {@code Expression} representing the number of microseconds since epoch. */ - timestampToUnixMicros(): FunctionExpr { - return new FunctionExpr('timestamp_to_unix_micros', [this]); + timestampToUnixMicros(): FunctionExpression { + return new FunctionExpression('timestamp_to_unix_micros', [this]); } /** @@ -1311,10 +1387,10 @@ export abstract class Expr implements firestore.Pipelines.Expr, HasUserData { * field("milliseconds").unixMillisToTimestamp(); * ``` * - * @return A new {@code Expr} representing the timestamp. + * @return A new {@code Expression} representing the timestamp. */ - unixMillisToTimestamp(): FunctionExpr { - return new FunctionExpr('unix_millis_to_timestamp', [this]); + unixMillisToTimestamp(): FunctionExpression { + return new FunctionExpression('unix_millis_to_timestamp', [this]); } /** @@ -1326,10 +1402,10 @@ export abstract class Expr implements firestore.Pipelines.Expr, HasUserData { * field("timestamp").timestampToUnixMillis(); * ``` * - * @return A new {@code Expr} representing the number of milliseconds since epoch. + * @return A new {@code Expression} representing the number of milliseconds since epoch. */ - timestampToUnixMillis(): FunctionExpr { - return new FunctionExpr('timestamp_to_unix_millis', [this]); + timestampToUnixMillis(): FunctionExpression { + return new FunctionExpression('timestamp_to_unix_millis', [this]); } /** @@ -1342,10 +1418,10 @@ export abstract class Expr implements firestore.Pipelines.Expr, HasUserData { * field("seconds").unixSecondsToTimestamp(); * ``` * - * @return A new {@code Expr} representing the timestamp. + * @return A new {@code Expression} representing the timestamp. */ - unixSecondsToTimestamp(): FunctionExpr { - return new FunctionExpr('unix_seconds_to_timestamp', [this]); + unixSecondsToTimestamp(): FunctionExpression { + return new FunctionExpression('unix_seconds_to_timestamp', [this]); } /** @@ -1357,10 +1433,10 @@ export abstract class Expr implements firestore.Pipelines.Expr, HasUserData { * field("timestamp").timestampToUnixSeconds(); * ``` * - * @return A new {@code Expr} representing the number of seconds since epoch. + * @return A new {@code Expression} representing the number of seconds since epoch. */ - timestampToUnixSeconds(): FunctionExpr { - return new FunctionExpr('timestamp_to_unix_seconds', [this]); + timestampToUnixSeconds(): FunctionExpression { + return new FunctionExpression('timestamp_to_unix_seconds', [this]); } /** @@ -1374,9 +1450,9 @@ export abstract class Expr implements firestore.Pipelines.Expr, HasUserData { * * @param unit The expression evaluates to unit of time, must be one of 'microsecond', 'millisecond', 'second', 'minute', 'hour', 'day'. * @param amount The expression evaluates to amount of the unit. - * @return A new {@code Expr} representing the resulting timestamp. + * @return A new {@code Expression} representing the resulting timestamp. */ - timestampAdd(unit: Expr, amount: Expr): FunctionExpr; + timestampAdd(unit: Expression, amount: Expression): FunctionExpression; /** * @beta @@ -1389,24 +1465,24 @@ export abstract class Expr implements firestore.Pipelines.Expr, HasUserData { * * @param unit The unit of time to add (e.g., "day", "hour"). * @param amount The amount of time to add. - * @return A new {@code Expr} representing the resulting timestamp. + * @return A new {@code Expression} representing the resulting timestamp. */ timestampAdd( unit: 'microsecond' | 'millisecond' | 'second' | 'minute' | 'hour' | 'day', amount: number - ): FunctionExpr; + ): FunctionExpression; timestampAdd( unit: - | Expr + | Expression | 'microsecond' | 'millisecond' | 'second' | 'minute' | 'hour' | 'day', - amount: Expr | number - ): FunctionExpr { - return new FunctionExpr('timestamp_add', [ + amount: Expression | number + ): FunctionExpression { + return new FunctionExpression('timestamp_add', [ this, valueToDefaultExpr(unit), valueToDefaultExpr(amount), @@ -1419,14 +1495,14 @@ export abstract class Expr implements firestore.Pipelines.Expr, HasUserData { * * ```typescript * // Subtract some duration determined by field 'unit' and 'amount' from the 'timestamp' field. - * field("timestamp").timestampSub(field("unit"), field("amount")); + * field("timestamp").timestampSubtract(field("unit"), field("amount")); * ``` * * @param unit The expression evaluates to unit of time, must be one of 'microsecond', 'millisecond', 'second', 'minute', 'hour', 'day'. * @param amount The expression evaluates to amount of the unit. - * @return A new {@code Expr} representing the resulting timestamp. + * @return A new {@code Expression} representing the resulting timestamp. */ - timestampSub(unit: Expr, amount: Expr): FunctionExpr; + timestampSubtract(unit: Expression, amount: Expression): FunctionExpression; /** * @beta @@ -1434,29 +1510,29 @@ export abstract class Expr implements firestore.Pipelines.Expr, HasUserData { * * ```typescript * // Subtract 1 day from the 'timestamp' field. - * field("timestamp").timestampSub("day", 1); + * field("timestamp").timestampSubtract("day", 1); * ``` * * @param unit The unit of time to subtract (e.g., "day", "hour"). * @param amount The amount of time to subtract. - * @return A new {@code Expr} representing the resulting timestamp. + * @return A new {@code Expression} representing the resulting timestamp. */ - timestampSub( + timestampSubtract( unit: 'microsecond' | 'millisecond' | 'second' | 'minute' | 'hour' | 'day', amount: number - ): FunctionExpr; - timestampSub( + ): FunctionExpression; + timestampSubtract( unit: - | Expr + | Expression | 'microsecond' | 'millisecond' | 'second' | 'minute' | 'hour' | 'day', - amount: Expr | number - ): FunctionExpr { - return new FunctionExpr('timestamp_sub', [ + amount: Expression | number + ): FunctionExpression { + return new FunctionExpression('timestamp_subtract', [ this, valueToDefaultExpr(unit), valueToDefaultExpr(amount), @@ -1472,10 +1548,10 @@ export abstract class Expr implements firestore.Pipelines.Expr, HasUserData { * field("__path__").documentId(); * ``` * - * @return A new {@code Expr} representing the documentId operation. + * @return A new {@code Expression} representing the documentId operation. */ - documentId(): FunctionExpr { - return new FunctionExpr('document_id', [this]); + documentId(): FunctionExpression { + return new FunctionExpression('document_id', [this]); } /** @@ -1486,7 +1562,7 @@ export abstract class Expr implements firestore.Pipelines.Expr, HasUserData { * @param length Length of the substring. If not provided, the substring will * end at the end of the input. */ - substring(position: number, length?: number): FunctionExpr; + substring(position: number, length?: number): FunctionExpression; /** * @beta @@ -1496,13 +1572,16 @@ export abstract class Expr implements firestore.Pipelines.Expr, HasUserData { * @param length An expression returning the length of the substring. If not provided the * substring will end at the end of the input. */ - substring(position: Expr, length?: Expr): FunctionExpr; - substring(position: Expr | number, length?: Expr | number): FunctionExpr { + substring(position: Expression, length?: Expression): FunctionExpression; + substring( + position: Expression | number, + length?: Expression | number + ): FunctionExpression { const positionExpr = valueToDefaultExpr(position); if (length === undefined) { - return new FunctionExpr('substr', [this, positionExpr]); + return new FunctionExpression('substring', [this, positionExpr]); } else { - return new FunctionExpr('substr', [ + return new FunctionExpression('substring', [ this, positionExpr, valueToDefaultExpr(length), @@ -1522,9 +1601,9 @@ export abstract class Expr implements firestore.Pipelines.Expr, HasUserData { * ``` * * @param index The index of the element to return. - * @return A new Expr representing the 'arrayGet' operation. + * @return A new Expression representing the 'arrayGet' operation. */ - arrayGet(index: number): FunctionExpr; + arrayGet(index: number): FunctionExpression; /** * @beta @@ -1538,12 +1617,15 @@ export abstract class Expr implements firestore.Pipelines.Expr, HasUserData { * field('tags').arrayGet(field('favoriteTag')); * ``` * - * @param indexExpr An Expr evaluating to the index of the element to return. - * @return A new Expr representing the 'arrayGet' operation. + * @param indexExpr An Expression evaluating to the index of the element to return. + * @return A new Expression representing the 'arrayGet' operation. */ - arrayGet(indexExpr: Expr): FunctionExpr; - arrayGet(index: Expr | number): FunctionExpr { - return new FunctionExpr('array_get', [this, valueToDefaultExpr(index)]); + arrayGet(indexExpr: Expression): FunctionExpression; + arrayGet(index: Expression | number): FunctionExpression { + return new FunctionExpression('array_get', [ + this, + valueToDefaultExpr(index), + ]); } /** @@ -1555,10 +1637,10 @@ export abstract class Expr implements firestore.Pipelines.Expr, HasUserData { * field("title").arrayContains(1).isError(); * ``` * - * @return A new {@code BooleanExpr} representing the 'isError' check. + * @return A new {@code BooleanExpression} representing the 'isError' check. */ - isError(): BooleanExpr { - return new BooleanExpr('is_error', [this]); + isError(): BooleanExpression { + return new BooleanExpression('is_error', [this]); } /** @@ -1574,9 +1656,9 @@ export abstract class Expr implements firestore.Pipelines.Expr, HasUserData { * * @param catchExpr The catch expression that will be evaluated and * returned if this expression produces an error. - * @return A new {@code Expr} representing the 'ifError' operation. + * @return A new {@code Expression} representing the 'ifError' operation. */ - ifError(catchExpr: Expr): FunctionExpr; + ifError(catchExpr: Expression): FunctionExpression; /** * @beta @@ -1591,11 +1673,14 @@ export abstract class Expr implements firestore.Pipelines.Expr, HasUserData { * * @param catchValue The value that will be returned if this expression * produces an error. - * @return A new {@code Expr} representing the 'ifError' operation. + * @return A new {@code Expression} representing the 'ifError' operation. */ - ifError(catchValue: unknown): FunctionExpr; - ifError(catchValue: unknown): FunctionExpr { - return new FunctionExpr('if_error', [this, valueToDefaultExpr(catchValue)]); + ifError(catchValue: unknown): FunctionExpression; + ifError(catchValue: unknown): FunctionExpression { + return new FunctionExpression('if_error', [ + this, + valueToDefaultExpr(catchValue), + ]); } /** @@ -1608,40 +1693,10 @@ export abstract class Expr implements firestore.Pipelines.Expr, HasUserData { * field("value").isAbsent(); * ``` * - * @return A new {@code BooleanExpr} representing the 'isAbsent' check. + * @return A new {@code BooleanExpression} representing the 'isAbsent' check. */ - isAbsent(): BooleanExpr { - return new BooleanExpr('is_absent', [this]); - } - - /** - * @beta - * Creates an expression that checks if tbe result of an expression is not null. - * - * ```typescript - * // Check if the value of the 'name' field is not null - * field("name").isNotNull(); - * ``` - * - * @return A new {@code BooleanExpr} representing the 'isNotNull' check. - */ - isNotNull(): BooleanExpr { - return new BooleanExpr('is_not_null', [this]); - } - - /** - * @beta - * Creates an expression that checks if the results of this expression is NOT 'NaN' (Not a Number). - * - * ```typescript - * // Check if the result of a calculation is NOT NaN - * field("value").divide(0).isNotNan(); - * ``` - * - * @return A new {@code Expr} representing the 'isNan' check. - */ - isNotNan(): BooleanExpr { - return new BooleanExpr('is_not_nan', [this]); + isAbsent(): BooleanExpression { + return new BooleanExpression('is_absent', [this]); } /** @@ -1656,7 +1711,7 @@ export abstract class Expr implements firestore.Pipelines.Expr, HasUserData { * @param key The name of the key to remove from the input map. * @returns A new {@code FirestoreFunction} representing the 'mapRemove' operation. */ - mapRemove(key: string): FunctionExpr; + mapRemove(key: string): FunctionExpression; /** * @beta * Creates an expression that removes a key from the map produced by evaluating this expression. @@ -1669,9 +1724,9 @@ export abstract class Expr implements firestore.Pipelines.Expr, HasUserData { * @param keyExpr An expression that produces the name of the key to remove from the input map. * @returns A new {@code FirestoreFunction} representing the 'mapRemove' operation. */ - mapRemove(keyExpr: Expr): FunctionExpr; - mapRemove(stringExpr: Expr | string): FunctionExpr { - return new FunctionExpr('map_remove', [ + mapRemove(keyExpr: Expression): FunctionExpression; + mapRemove(stringExpr: Expression | string): FunctionExpression { + return new FunctionExpression('map_remove', [ this, valueToDefaultExpr(stringExpr), ]); @@ -1684,7 +1739,7 @@ export abstract class Expr implements firestore.Pipelines.Expr, HasUserData { * ``` * // 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 }, cond(field('isAdmin'), { admin: true}, {}) + * field('settings').mapMerge({ enabled: true }, conditional(field('isAdmin'), { admin: true}, {}) * ``` * * @param secondMap A required second map to merge. Represented as a literal or @@ -1695,12 +1750,12 @@ export abstract class Expr implements firestore.Pipelines.Expr, HasUserData { * @returns A new {@code FirestoreFunction} representing the 'mapMerge' operation. */ mapMerge( - secondMap: Record | Expr, - ...otherMaps: Array | Expr> - ): FunctionExpr { + secondMap: Record | Expression, + ...otherMaps: Array | Expression> + ): FunctionExpression { const secondMapExpr = valueToDefaultExpr(secondMap); const otherMapExprs = otherMaps.map(valueToDefaultExpr); - return new FunctionExpr('map_merge', [ + return new FunctionExpression('map_merge', [ this, secondMapExpr, ...otherMapExprs, @@ -1717,9 +1772,9 @@ export abstract class Expr implements firestore.Pipelines.Expr, HasUserData { * ``` * * @param exponent The expression to raise this expression to the power of. - * @return A new `Expr` representing the power operation. + * @return A new `Expression` representing the power operation. */ - pow(exponent: Expr): FunctionExpr; + pow(exponent: Expression): FunctionExpression; /** * @beta @@ -1731,11 +1786,11 @@ export abstract class Expr implements firestore.Pipelines.Expr, HasUserData { * ``` * * @param exponent The constant value to raise this expression to the power of. - * @return A new `Expr` representing the power operation. + * @return A new `Expression` representing the power operation. */ - pow(exponent: number): FunctionExpr; - pow(exponent: number | Expr): FunctionExpr { - return new FunctionExpr('pow', [this, valueToDefaultExpr(exponent)]); + pow(exponent: number): FunctionExpression; + pow(exponent: number | Expression): FunctionExpression { + return new FunctionExpression('pow', [this, valueToDefaultExpr(exponent)]); } /** @@ -1747,10 +1802,46 @@ export abstract class Expr implements firestore.Pipelines.Expr, HasUserData { * field("price").round(); * ``` * + * @return A new `Expression` representing the rounded value. + */ + round(): FunctionExpression; + /** + * @beta + * Creates an expression that rounds a numeric value to the specified number of decimal places. + * + * ```typescript + * // Round the value of the 'price' field to two decimal places. + * field("price").round(2); + * ``` + * + * @param decimalPlaces A constant specifying the rounding precision in decimal places. + * * @return A new `Expr` representing the rounded value. */ - round(): FunctionExpr { - return new FunctionExpr('round', [this]); + round(decimalPlaces: number): FunctionExpression; + /** + * @beta + * Creates an expression that rounds a numeric value to the specified number of decimal places. + * + * ```typescript + * // Round the value of the 'price' field to two decimal places. + * field("price").round(constant(2)); + * ``` + * + * @param decimalPlaces An expression specifying the rounding precision in decimal places. + * + * @return A new `Expr` representing the rounded value. + */ + round(decimalPlaces: Expression): FunctionExpression; + round(decimalPlaces?: number | Expression): FunctionExpression { + if (decimalPlaces === undefined) { + return new FunctionExpression('round', [this]); + } else { + return new FunctionExpression('round', [ + this, + valueToDefaultExpr(decimalPlaces), + ]); + } } /** @@ -1762,10 +1853,10 @@ export abstract class Expr implements firestore.Pipelines.Expr, HasUserData { * field("__path__").collectionId(); * ``` * - * @return A new {@code Expr} representing the collectionId operation. + * @return A new {@code Expression} representing the collectionId operation. */ - collectionId(): FunctionExpr { - return new FunctionExpr('collection_id', [this]); + collectionId(): FunctionExpression { + return new FunctionExpression('collection_id', [this]); } /** @@ -1780,10 +1871,10 @@ export abstract class Expr implements firestore.Pipelines.Expr, HasUserData { * field("cart").length(); * ``` * - * @return A new `Expr` representing the length of the string, array, map, vector, or bytes. + * @return A new `Expression` representing the length of the string, array, map, vector, or bytes. */ - length(): FunctionExpr { - return new FunctionExpr('length', [this]); + length(): FunctionExpression { + return new FunctionExpression('length', [this]); } /** @@ -1795,71 +1886,144 @@ export abstract class Expr implements firestore.Pipelines.Expr, HasUserData { * field("value").ln(); * ``` * - * @return A new {@code Expr} representing the natural logarithm of the numeric value. + * @return A new {@code Expression} representing the natural logarithm of the numeric value. */ - ln(): FunctionExpr { - return new FunctionExpr('ln', [this]); + ln(): FunctionExpression { + return new FunctionExpression('ln', [this]); } /** * @beta - * Creates an expression that computes the logarithm of this expression to a given base. + * Creates an expression that computes the square root of a numeric value. * * ```typescript - * // Compute the logarithm of the 'value' field with base 10. - * field("value").log(10); + * // Compute the square root of the 'value' field. + * field("value").sqrt(); * ``` * - * @param base The base of the logarithm. - * @return A new {@code Expr} representing the logarithm of the numeric value. + * @return A new {@code Expression} representing the square root of the numeric value. */ - log(base: number): FunctionExpr; + sqrt(): FunctionExpression { + return new FunctionExpression('sqrt', [this]); + } /** * @beta - * Creates an expression that computes the logarithm of this expression to a given base. + * Creates an expression that reverses a string. * * ```typescript - * // Compute the logarithm of the 'value' field with the base in the 'base' field. - * field("value").log(field("base")); + * // Reverse the value of the 'myString' field. + * field("myString").stringReverse(); * ``` * - * @param base The base of the logarithm. - * @return A new {@code Expr} representing the logarithm of the numeric value. + * @return A new {@code Expression} representing the reversed string. */ - log(base: Expr): FunctionExpr; - log(base: number | Expr): FunctionExpr { - return new FunctionExpr('log', [this, valueToDefaultExpr(base)]); + stringReverse(): FunctionExpression { + return new FunctionExpression('string_reverse', [this]); } /** * @beta - * Creates an expression that computes the square root of a numeric value. + * Creates an expression that returns the `elseValue` argument if this expression results in an absent value, else + * return the result of the this expression evaluation. * * ```typescript - * // Compute the square root of the 'value' field. - * field("value").sqrt(); + * // Returns the value of the optional field 'optional_field', or returns 'default_value' + * // if the field is absent. + * field("optional_field").ifAbsent("default_value") * ``` * - * @return A new {@code Expr} representing the square root of the numeric value. + * @param elseValue The value that will be returned if this Expression evaluates to an absent value. + * @return A new [Expression] representing the ifAbsent operation. */ - sqrt(): FunctionExpr { - return new FunctionExpr('sqrt', [this]); + ifAbsent(elseValue: unknown): Expression; + + /** + * @beta + * Creates an expression that returns the `elseValue` argument if this expression results in an absent value, else + * return the result of this expression evaluation. + * + * ```typescript + * // Returns the value of the optional field 'optional_field', or if that is + * // absent, then returns the value of the field ` + * field("optional_field").ifAbsent(field('default_field')) + * ``` + * + * @param elseExpression The Expression that will be evaluated if this Expression evaluates to an absent value. + * @return A new [Expression] representing the ifAbsent operation. + */ + ifAbsent(elseExpression: unknown): Expression; + + ifAbsent(elseValueOrExpression: Expression | unknown): Expression { + return new FunctionExpression('if_absent', [ + this, + valueToDefaultExpr(elseValueOrExpression), + ]); } /** * @beta - * Creates an expression that reverses a string. + * Creates an expression that joins the elements of an array into a string. * * ```typescript - * // Reverse the value of the 'myString' field. - * field("myString").strReverse(); + * // Join the elements of the 'tags' field with the delimiter from the 'separator' field. + * field("tags").join(field("separator")) * ``` * - * @return A new {@code Expr} representing the reversed string. + * @param delimiterExpression The expression that evaluates to the delimiter string. + * @return A new Expression representing the join operation. */ - strReverse(): FunctionExpr { - return new FunctionExpr('str_reverse', [this]); + join(delimiterExpression: Expression): Expression; + + /** + * @beta + * Creates an expression that joins the elements of an array field into a string. + * + * ```typescript + * // Join the elements of the 'tags' field with a comma and space. + * field("tags").join(", ") + * ``` + * + * @param delimiter The string to use as a delimiter. + * @return A new Expression representing the join operation. + */ + join(delimiter: string): Expression; + + join(delimeterValueOrExpression: string | Expression): Expression { + return new FunctionExpression('join', [ + this, + valueToDefaultExpr(delimeterValueOrExpression), + ]); + } + + /** + * @beta + * Creates an expression that computes the base-10 logarithm of a numeric value. + * + * ```typescript + * // Compute the base-10 logarithm of the 'value' field. + * field("value").log10(); + * ``` + * + * @return A new {@code Expr} representing the base-10 logarithm of the numeric value. + */ + log10(): FunctionExpression { + return new FunctionExpression('log10', [this]); + } + + /** + * @beta + * Creates an expression that computes the sum of the elements in an array. + * + * ```typescript + * // Compute the sum of the elements in the 'scores' field. + * field("scores").arraySum(); + * ``` + * + * @return A new {@code Expr} representing the sum of the elements in the array. + */ + arraySum(): FunctionExpression { + return new FunctionExpression('sum', [this]); } // TODO(new-expression): Add new expression method definitions above this line @@ -1910,11 +2074,11 @@ export abstract class Expr implements firestore.Pipelines.Expr, HasUserData { * ``` * * @param name The alias to assign to this expression. - * @return A new {@link AliasedExpr} that wraps this + * @return A new {@link AliasedExpression} that wraps this * expression and associates it with the provided alias. */ - as(name: string): AliasedExpr { - return new AliasedExpr(this, name); + as(name: string): AliasedExpression { + return new AliasedExpression(this, name); } } @@ -1923,7 +2087,7 @@ export abstract class Expr implements firestore.Pipelines.Expr, HasUserData { * A class that represents an aggregate function. */ export class AggregateFunction implements AggregateFunction, HasUserData { - exprType: firestore.Pipelines.ExprType = 'AggregateFunction'; + expressionType: firestore.Pipelines.ExpressionType = 'AggregateFunction'; /** * @beta @@ -1947,7 +2111,7 @@ export class AggregateFunction implements AggregateFunction, HasUserData { constructor( private name: string, - private params: Expr[] + private params: Expression[] ) {} /** @@ -1958,7 +2122,7 @@ export class AggregateFunction implements AggregateFunction, HasUserData { * ```typescript * // Calculate the average price of all items and assign it the alias "averagePrice". * firestore.pipeline().collection("items") - * .aggregate(field("price").avg().as("averagePrice")); + * .aggregate(field("price").average().as("averagePrice")); * ``` * * @param name The alias to assign to this AggregateFunction. @@ -1992,8 +2156,8 @@ export class AggregateFunction implements AggregateFunction, HasUserData { */ export class AliasedAggregate implements AliasedAggregate, HasUserData { constructor( - readonly aggregate: AggregateFunction, - readonly alias: string + readonly _aggregate: AggregateFunction, + readonly _alias: string ) {} /** @@ -2011,7 +2175,7 @@ export class AliasedAggregate implements AliasedAggregate, HasUserData { * @internal */ _validateUserData(ignoreUndefinedProperties: boolean): void { - this.aggregate._validateUserData(ignoreUndefinedProperties); + this._aggregate._validateUserData(ignoreUndefinedProperties); } } @@ -2019,10 +2183,10 @@ export class AliasedAggregate implements AliasedAggregate, HasUserData { * @beta * TODO */ -export class AliasedExpr +export class AliasedExpression implements firestore.Pipelines.Selectable, HasUserData { - exprType: firestore.Pipelines.ExprType = 'AliasedExpr'; + expressionType: firestore.Pipelines.ExpressionType = 'AliasedExpression'; selectable = true as const; /** @@ -2035,8 +2199,8 @@ export class AliasedExpr _createdFromLiteral = false; constructor( - readonly expr: Expr, - readonly alias: string + readonly _expr: Expression, + readonly _alias: string ) {} /** @@ -2045,7 +2209,7 @@ export class AliasedExpr * @internal */ _validateUserData(ignoreUndefinedProperties: boolean): void { - this.expr._validateUserData(ignoreUndefinedProperties); + this._expr._validateUserData(ignoreUndefinedProperties); } } @@ -2053,10 +2217,10 @@ export class AliasedExpr * @beta * @internal */ -class ListOfExprs extends Expr { - exprType: firestore.Pipelines.ExprType = 'ListOfExprs'; +class ListOfExprs extends Expression { + expressionType: firestore.Pipelines.ExpressionType = 'ListOfExprs'; - constructor(private exprs: Expr[]) { + constructor(private exprs: Expression[]) { super(); } @@ -2102,8 +2266,11 @@ class ListOfExprs extends Expr { * const cityField = field("address.city"); * ``` */ -export class Field extends Expr implements firestore.Pipelines.Selectable { - readonly exprType: firestore.Pipelines.ExprType = 'Field'; +export class Field + extends Expression + implements firestore.Pipelines.Selectable +{ + readonly expressionType: firestore.Pipelines.ExpressionType = 'Field'; selectable = true as const; /** @@ -2117,15 +2284,15 @@ export class Field extends Expr implements firestore.Pipelines.Selectable { super(); } - fieldName(): string { + get fieldName(): string { return this.fieldPath.formattedName; } - get alias(): string { - return this.fieldName(); + get _alias(): string { + return this.fieldName; } - get expr(): Expr { + get _expr(): Expression { return this; } @@ -2179,6 +2346,7 @@ export function field(field: string | firestore.FieldPath): Field { /** * @beta + * @internal * Represents a constant value that can be used in a Firestore pipeline expression. * * You can create a `Constant` instance using the static {@link #of} method: @@ -2191,8 +2359,8 @@ export function field(field: string | firestore.FieldPath): Field { * const hello = constant("hello"); * ``` */ -export class Constant extends Expr { - readonly exprType: firestore.Pipelines.ExprType = 'Constant'; +export class Constant extends Expression { + readonly expressionType: firestore.Pipelines.ExpressionType = 'Constant'; private protoValue?: api.IValue; @@ -2247,104 +2415,104 @@ export class Constant extends Expr { /** * @beta - * Creates a `Constant` instance for a number value. + * Creates an 'Expression' instance for a number value. * * @param value The number value. - * @return A new `Constant` instance. + * @return A new `Expression` instance. */ -export function constant(value: number): Constant; +export function constant(value: number): Expression; /** * @beta - * Creates a `Constant` instance for a string value. + * Creates an 'Expression' instance for a string value. * * @param value The string value. - * @return A new `Constant` instance. + * @return A new `Expression` instance. */ -export function constant(value: string): Constant; +export function constant(value: string): Expression; /** * @beta - * Creates a `Constant` instance for a boolean value. + * Creates an 'Expression' instance for a boolean value. * * @param value The boolean value. - * @return A new `Constant` instance. + * @return A new `Expression` instance. */ -export function constant(value: boolean): Constant; +export function constant(value: boolean): BooleanExpression; /** * @beta - * Creates a `Constant` instance for a null value. + * Creates an 'Expression' instance for a null value. * * @param value The null value. - * @return A new `Constant` instance. + * @return A new `Expression` instance. */ -export function constant(value: null): Constant; +export function constant(value: null): Expression; /** * @beta - * Creates a `Constant` instance for a GeoPoint value. + * Creates an 'Expression' instance for a GeoPoint value. * * @param value The GeoPoint value. - * @return A new `Constant` instance. + * @return A new `Expression` instance. */ -export function constant(value: firestore.GeoPoint): Constant; +export function constant(value: firestore.GeoPoint): Expression; /** * @beta - * Creates a `Constant` instance for a Timestamp value. + * Creates an 'Expression' instance for a Timestamp value. * * @param value The Timestamp value. - * @return A new `Constant` instance. + * @return A new `Expression` instance. */ -export function constant(value: firestore.Timestamp): Constant; +export function constant(value: firestore.Timestamp): Expression; /** * @beta - * Creates a `Constant` instance for a Date value. + * Creates an 'Expression' instance for a Date value. * * @param value The Date value. - * @return A new `Constant` instance. + * @return A new `Expression` instance. */ -export function constant(value: Date): Constant; +export function constant(value: Date): Expression; /** * @beta - * Creates a `Constant` instance for a Buffer | Uint8Array value. + * Creates an 'Expression' instance for a Buffer | Uint8Array value. * * @param value The Buffer | Uint8Array value. - * @return A new `Constant` instance. + * @return A new `Expression` instance. */ -export function constant(value: Buffer | Uint8Array): Constant; +export function constant(value: Buffer | Uint8Array): Expression; /** * @beta - * Creates a `Constant` instance for a DocumentReference value. + * Creates an 'Expression' instance for a DocumentReference value. * * @param value The DocumentReference value. - * @return A new `Constant` instance. + * @return A new `Expression` instance. */ -export function constant(value: firestore.DocumentReference): Constant; +export function constant(value: firestore.DocumentReference): Expression; /** * @beta - * Creates a `Constant` instance for a Firestore proto value. + * Creates an 'Expression' instance for a Firestore proto value. * For internal use only. * @private * @internal * @param value The Firestore proto value. - * @return A new `Constant` instance. + * @return A new `Expression` instance. */ -export function constant(value: api.IValue): Constant; +export function constant(value: api.IValue): Expression; /** * @beta - * Creates a `Constant` instance for a VectorValue value. + * Creates an 'Expression' instance for a VectorValue value. * * @param value The VectorValue value. - * @return A new `Constant` instance. + * @return A new `Expression` instance. */ -export function constant(value: firestore.VectorValue): Constant; +export function constant(value: firestore.VectorValue): Expression; /** * @beta @@ -2352,9 +2520,9 @@ export function constant(value: firestore.VectorValue): Constant; * @private * @param value */ -export function constant(value: unknown): Constant; +export function constant(value: unknown): Expression; -export function constant(value: unknown): Constant { +export function constant(value: unknown): Expression { return new Constant(value); } @@ -2364,12 +2532,12 @@ export function constant(value: unknown): Constant { * @internal * @private */ -export class MapValue extends Expr { - constructor(private plainObject: Map) { +export class MapValue extends Expression { + constructor(private plainObject: Map) { super(); } - exprType: firestore.Pipelines.ExprType = 'Constant'; + expressionType: firestore.Pipelines.ExpressionType = 'Constant'; _toProto(serializer: Serializer): api.IValue { return serializer.encodeValue(this.plainObject); @@ -2392,15 +2560,15 @@ export class MapValue extends Expr { * This class defines the base class for Firestore {@link 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 and}, {@link eq}, - * or the methods on {@link Expr} ({@link Expr#eq}, {@link Expr#lt}, etc.) to construct new Function instances. + * Typically, you would not use this class or its children directly. Use either the functions like {@link and}, {@link equal}, + * or the methods on {@link Expression} ({@link Expression#equal}, {@link Expression#lessThan}, etc.) to construct new Function instances. */ -export class FunctionExpr extends Expr { - readonly exprType: firestore.Pipelines.ExprType = 'Function'; +export class FunctionExpression extends Expression { + readonly expressionType: firestore.Pipelines.ExpressionType = 'Function'; constructor( protected name: string, - private params: Expr[] + private params: Expression[] ) { super(); } @@ -2414,7 +2582,7 @@ export class FunctionExpr extends Expr { return { functionValue: { name: this.name, - args: this.params.map(p => cast(p)._toProto(serializer)), + args: this.params.map(p => cast(p)._toProto(serializer)), }, }; } @@ -2436,13 +2604,13 @@ export class FunctionExpr extends Expr { * This class defines the base class for Firestore {@link 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 and}, {@link eq}, - * or the methods on {@link Expr} ({@link Expr#eq}, {@link Expr#lt}, etc.) to construct new Function instances. + * Typically, you would not use this class or its children directly. Use either the functions like {@link and}, {@link equal}, + * or the methods on {@link Expression} ({@link Expression#equal}, {@link Expression#lessThan}, etc.) to construct new Function instances. */ -class MapFunctionExpr extends FunctionExpr { - readonly exprType: firestore.Pipelines.ExprType = 'Function'; +class MapFunctionExpr extends FunctionExpression { + readonly expressionType: firestore.Pipelines.ExpressionType = 'Function'; - constructor(private map: Record) { + constructor(private map: Record) { super('map', []); } @@ -2488,13 +2656,13 @@ class MapFunctionExpr extends FunctionExpr { * This class defines the base class for Firestore {@link 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 and}, {@link eq}, - * or the methods on {@link Expr} ({@link Expr#eq}, {@link Expr#lt}, etc.) to construct new Function instances. + * Typically, you would not use this class or its children directly. Use either the functions like {@link and}, {@link equal}, + * or the methods on {@link Expression} ({@link Expression#equal}, {@link Expression#lessThan}, etc.) to construct new Function instances. */ -class ArrayFunctionExpr extends FunctionExpr { - readonly exprType: firestore.Pipelines.ExprType = 'Function'; +class ArrayFunctionExpr extends FunctionExpression { + readonly expressionType: firestore.Pipelines.ExpressionType = 'Function'; - constructor(private values: Array) { + constructor(private values: Array) { super('array', []); } @@ -2535,9 +2703,9 @@ class ArrayFunctionExpr extends FunctionExpr { * This expression type is useful for filter conditions. * */ -export class BooleanExpr - extends FunctionExpr - implements firestore.Pipelines.BooleanExpr +export class BooleanExpression + extends FunctionExpression + implements firestore.Pipelines.BooleanExpression { returnType: 'boolean' = 'boolean' as const; @@ -2548,7 +2716,7 @@ export class BooleanExpr * * ```typescript * // Find the count of documents with a score greater than 90 - * field("score").gt(90).countIf().as("highestScore"); + * field("score").greaterThan(90).countIf().as("highestScore"); * ``` * * @return A new `AggregateFunction` representing the 'countIf' aggregation. @@ -2566,10 +2734,49 @@ export class BooleanExpr * field("tags").arrayContains("completed").not(); * ``` * - * @return A new {@code Expr} representing the negated filter condition. + * @return A new {@code Expression} representing the negated filter condition. + */ + not(): BooleanExpression { + return new BooleanExpression('not', [this]); + } + + /** + * @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`. + * + * ```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. + * @return A new {@code Expr} representing the conditional expression. + */ + conditional(thenExpr: Expression, elseExpr: Expression): FunctionExpression { + return new FunctionExpression('conditional', [this, thenExpr, elseExpr]); + } + + /** + * @beta + * + * Creates an expression that returns the `catch` argument if there is an + * error, else return the result of this expression. + * + * ```typescript + * // Create an expression that protects against a divide by zero error + * // but always returns a boolean expression. + * constant(50).divide('length').gt(1).ifError(constant(false)); + * ``` + * + * @param catchValue The value that will be returned if this expression + * produces an error. + * @return A new {@code Expr} representing the 'ifError' operation. */ - not(): BooleanExpr { - return new BooleanExpr('not', [this]); + ifError(catchValue: BooleanExpression): BooleanExpression { + return new BooleanExpression('if_error', [this, catchValue]); } } @@ -2580,25 +2787,14 @@ export class BooleanExpr * * ```typescript * // Count the number of documents where 'is_active' field equals true - * countIf(field("is_active").eq(true)).as("numActiveDocuments"); + * countIf(field("is_active").equal(true)).as("numActiveDocuments"); * ``` * * @param booleanExpr - The boolean expression to evaluate on each input. * @returns A new `AggregateFunction` representing the 'countIf' aggregation. */ -export function countIf(booleanExpr: BooleanExpr): AggregateFunction { - return new AggregateFunction('count_if', [cast(booleanExpr)]); -} - -/** - * @beta - * Creates an expression that return a pseudo-random value of type double in the - * range of [0, 1), inclusive of 0 and exclusive of 1. - * - * @returns A new `Expr` representing the 'rand' function. - */ -export function rand(): FunctionExpr { - return new FunctionExpr('rand', []); +export function countIf(booleanExpr: BooleanExpression): AggregateFunction { + return new AggregateFunction('count_if', [cast(booleanExpr)]); } /** @@ -2614,9 +2810,9 @@ export function rand(): FunctionExpr { * * @param arrayField The name of the array field. * @param index The index of the element to return. - * @return A new Expr representing the 'arrayGet' operation. + * @return A new Expression representing the 'arrayGet' operation. */ -export function arrayGet(arrayField: string, index: number): FunctionExpr; +export function arrayGet(arrayField: string, index: number): FunctionExpression; /** * @beta @@ -2631,10 +2827,13 @@ export function arrayGet(arrayField: string, index: number): FunctionExpr; * ``` * * @param arrayField The name of the array field. - * @param indexExpr An Expr evaluating to the index of the element to return. - * @return A new Expr representing the 'arrayGet' operation. + * @param indexExpr An Expression evaluating to the index of the element to return. + * @return A new Expression representing the 'arrayGet' operation. */ -export function arrayGet(arrayField: string, indexExpr: Expr): FunctionExpr; +export function arrayGet( + arrayField: string, + indexExpr: Expression +): FunctionExpression; /** * @beta @@ -2647,11 +2846,14 @@ export function arrayGet(arrayField: string, indexExpr: Expr): FunctionExpr; * arrayGet(field('tags'), 1); * ``` * - * @param arrayExpression An Expr evaluating to an array. + * @param arrayExpression An Expression evaluating to an array. * @param index The index of the element to return. - * @return A new Expr representing the 'arrayGet' operation. + * @return A new Expression representing the 'arrayGet' operation. */ -export function arrayGet(arrayExpression: Expr, index: number): FunctionExpr; +export function arrayGet( + arrayExpression: Expression, + index: number +): FunctionExpression; /** * @beta @@ -2665,15 +2867,18 @@ export function arrayGet(arrayExpression: Expr, index: number): FunctionExpr; * arrayGet(field('tags'), field('favoriteTag')); * ``` * - * @param arrayExpression An Expr evaluating to an array. - * @param indexExpr An Expr evaluating to the index of the element to return. - * @return A new Expr representing the 'arrayGet' operation. + * @param arrayExpression An Expression evaluating to an array. + * @param indexExpr An Expression evaluating to the index of the element to return. + * @return A new Expression representing the 'arrayGet' operation. */ -export function arrayGet(arrayExpression: Expr, indexExpr: Expr): FunctionExpr; export function arrayGet( - array: Expr | string, - index: Expr | number -): FunctionExpr { + arrayExpression: Expression, + indexExpr: Expression +): FunctionExpression; +export function arrayGet( + array: Expression | string, + index: Expression | number +): FunctionExpression { return fieldOrExpression(array).arrayGet(valueToDefaultExpr(index)); } @@ -2687,13 +2892,37 @@ export function arrayGet( * ``` * * @param value The expression to check. - * @return A new {@code Expr} representing the 'isError' check. + * @return A new {@code Expression} representing the 'isError' check. */ -export function isError(value: Expr): BooleanExpr { - const expr: Expr = cast(value); +export function isError(value: Expression): BooleanExpression { + const expr: Expression = cast(value); return expr.isError(); } +/** + * @beta + * + * Creates an expression that returns the `catch` argument if there is an + * error, else return the result of the `try` argument evaluation. + * + * This overload is useful when a BooleanExpression is required. + * + * ```typescript + * // Create an expression that protects against a divide by zero error + * // but always returns a boolean expression. + * ifError(constant(50).divide('length').gt(1), constant(false)); + * ``` + * + * @param tryExpr The try expression. + * @param catchExpr The catch expression that will be evaluated and + * returned if the tryExpr produces an error. + * @return A new {@code Expr} representing the 'ifError' operation. + */ +export function ifError( + tryExpr: BooleanExpression, + catchExpr: BooleanExpression +): BooleanExpression; + /** * @beta * Creates an expression that returns the `catch` argument if there is an @@ -2708,9 +2937,12 @@ export function isError(value: Expr): BooleanExpr { * @param tryExpr The try expression. * @param catchExpr The catch expression that will be evaluated and * returned if the tryExpr produces an error. - * @return A new {@code Expr} representing the 'ifError' operation. + * @return A new {@code Expression} representing the 'ifError' operation. */ -export function ifError(tryExpr: Expr, catchExpr: Expr): FunctionExpr; +export function ifError( + tryExpr: Expression, + catchExpr: Expression +): FunctionExpression; /** * @beta @@ -2726,12 +2958,24 @@ export function ifError(tryExpr: Expr, catchExpr: Expr): FunctionExpr; * @param tryExpr The try expression. * @param catchValue The value that will be returned if the tryExpr produces an * error. - * @return A new {@code Expr} representing the 'ifError' operation. - */ -export function ifError(tryExpr: Expr, catchValue: unknown): FunctionExpr; -export function ifError(tryExpr: Expr, catchValue: unknown): FunctionExpr { - const expr: Expr = cast(tryExpr); - return expr.ifError(valueToDefaultExpr(catchValue)); + * @return A new {@code Expression} representing the 'ifError' operation. + */ +export function ifError( + tryExpr: Expression, + catchValue: unknown +): FunctionExpression; +export function ifError( + tryExpr: Expression, + catchValue: unknown +): FunctionExpression { + if ( + tryExpr instanceof BooleanExpression && + catchValue instanceof BooleanExpression + ) { + return tryExpr.ifError(catchValue); + } else { + return tryExpr.ifError(valueToDefaultExpr(catchValue)); + } } /** @@ -2745,9 +2989,9 @@ export function ifError(tryExpr: Expr, catchValue: unknown): FunctionExpr { * ``` * * @param value The expression to check. - * @return A new {@code Expr} representing the 'isAbsent' check. + * @return A new {@code Expression} representing the 'isAbsent' check. */ -export function isAbsent(value: Expr): BooleanExpr; +export function isAbsent(value: Expression): BooleanExpression; /** * @beta @@ -2760,106 +3004,13 @@ export function isAbsent(value: Expr): BooleanExpr; * ``` * * @param field The field to check. - * @return A new {@code Expr} representing the 'isAbsent' check. + * @return A new {@code Expression} representing the 'isAbsent' check. */ -export function isAbsent(field: string): BooleanExpr; -export function isAbsent(value: Expr | string): BooleanExpr { +export function isAbsent(field: string): BooleanExpression; +export function isAbsent(value: Expression | string): BooleanExpression { return fieldOrExpression(value).isAbsent(); } -/** - * @beta - * Creates an expression that checks if an expression evaluates to 'NaN' (Not a Number). - * - * ```typescript - * // Check if the result of a calculation is NaN - * isNull(field("value").divide(0)); - * ``` - * - * @param value The expression to check. - * @return A new {@code Expr} representing the 'isNull' check. - */ -export function isNull(value: Expr): BooleanExpr; - -/** - * @beta - * Creates an expression that checks if a field's value evaluates to 'NaN' (Not a Number). - * - * ```typescript - * // Check if the result of a calculation is NaN - * isNull("value"); - * ``` - * - * @param value The name of the field to check. - * @return A new {@code Expr} representing the 'isNull' check. - */ -export function isNull(value: string): BooleanExpr; -export function isNull(value: Expr | string): BooleanExpr { - return fieldOrExpression(value).isNull(); -} - -/** - * @beta - * Creates an expression that checks if tbe result of an expression is not null. - * - * ```typescript - * // Check if the value of the 'name' field is not null - * isNotNull(field("name")); - * ``` - * - * @param value The expression to check. - * @return A new {@code Expr} representing the 'isNotNull' check. - */ -export function isNotNull(value: Expr): BooleanExpr; - -/** - * @beta - * Creates an expression that checks if tbe value of a field is not null. - * - * ```typescript - * // Check if the value of the 'name' field is not null - * isNotNull("name"); - * ``` - * - * @param value The name of the field to check. - * @return A new {@code Expr} representing the 'isNotNull' check. - */ -export function isNotNull(value: string): BooleanExpr; -export function isNotNull(value: Expr | string): BooleanExpr { - return fieldOrExpression(value).isNotNull(); -} - -/** - * @beta - * Creates an expression that checks if the results of this expression is NOT 'NaN' (Not a Number). - * - * ```typescript - * // Check if the result of a calculation is NOT NaN - * isNotNaN(field("value").divide(0)); - * ``` - * - * @param value The expression to check. - * @return A new {@code Expr} representing the 'isNotNaN' check. - */ -export function isNotNan(value: Expr): BooleanExpr; - -/** - * @beta - * Creates an expression that checks if the results of this expression is NOT 'NaN' (Not a Number). - * - * ```typescript - * // Check if the value of a field is NOT NaN - * isNotNaN("value"); - * ``` - * - * @param value The name of the field to check. - * @return A new {@code Expr} representing the 'isNotNaN' check. - */ -export function isNotNan(value: string): BooleanExpr; -export function isNotNan(value: Expr | string): BooleanExpr { - return fieldOrExpression(value).isNotNan(); -} - /** * @beta * Creates an expression that removes a key from the map at the specified field name. @@ -2872,7 +3023,7 @@ export function isNotNan(value: Expr | string): BooleanExpr { * @param mapField The name of a field containing a map value. * @param key The name of the key to remove from the input map. */ -export function mapRemove(mapField: string, key: string): FunctionExpr; +export function mapRemove(mapField: string, key: string): FunctionExpression; /** * @beta * Creates an expression that removes a key from the map produced by evaluating an expression. @@ -2885,7 +3036,7 @@ export function mapRemove(mapField: string, key: string): FunctionExpr; * @param mapExpr An expression return a map value. * @param key The name of the key to remove from the input map. */ -export function mapRemove(mapExpr: Expr, key: string): FunctionExpr; +export function mapRemove(mapExpr: Expression, key: string): FunctionExpression; /** * @beta * Creates an expression that removes a key from the map at the specified field name. @@ -2898,7 +3049,10 @@ export function mapRemove(mapExpr: Expr, key: string): FunctionExpr; * @param mapField The name of a field containing a map value. * @param keyExpr An expression that produces the name of the key to remove from the input map. */ -export function mapRemove(mapField: string, keyExpr: Expr): FunctionExpr; +export function mapRemove( + mapField: string, + keyExpr: Expression +): FunctionExpression; /** * @beta * Creates an expression that removes a key from the map produced by evaluating an expression. @@ -2911,12 +3065,15 @@ export function mapRemove(mapField: string, keyExpr: Expr): FunctionExpr; * @param mapExpr An expression return a map value. * @param keyExpr An expression that produces the name of the key to remove from the input map. */ -export function mapRemove(mapExpr: Expr, keyExpr: Expr): FunctionExpr; +export function mapRemove( + mapExpr: Expression, + keyExpr: Expression +): FunctionExpression; export function mapRemove( - mapExpr: Expr | string, - stringExpr: Expr | string -): FunctionExpr { + mapExpr: Expression | string, + stringExpr: Expression | string +): FunctionExpression { return fieldOrExpression(mapExpr).mapRemove(valueToDefaultExpr(stringExpr)); } @@ -2927,7 +3084,7 @@ export function mapRemove( * ``` * // Merges the map in the settings field with, a map literal, and a map in * // that is conditionally returned by another expression - * mapMerge('settings', { enabled: true }, cond(field('isAdmin'), { admin: true}, {}) + * mapMerge('settings', { enabled: true }, conditional(field('isAdmin'), { admin: true}, {}) * ``` * * @param mapField Name of a field containing a map value that will be merged. @@ -2938,9 +3095,9 @@ export function mapRemove( */ export function mapMerge( mapField: string, - secondMap: Record | Expr, - ...otherMaps: Array | Expr> -): FunctionExpr; + secondMap: Record | Expression, + ...otherMaps: Array | Expression> +): FunctionExpression; /** * @beta @@ -2949,7 +3106,7 @@ export function mapMerge( * ``` * // Merges the map in the settings field with, a map literal, and a map in * // that is conditionally returned by another expression - * mapMerge(field('settings'), { enabled: true }, cond(field('isAdmin'), { admin: true}, {}) + * mapMerge(field('settings'), { enabled: true }, conditional(field('isAdmin'), { admin: true}, {}) * ``` * * @param firstMap An expression or literal map value that will be merged. @@ -2959,16 +3116,16 @@ export function mapMerge( * as a literal or an expression that returns a map. */ export function mapMerge( - firstMap: Record | Expr, - secondMap: Record | Expr, - ...otherMaps: Array | Expr> -): FunctionExpr; + firstMap: Record | Expression, + secondMap: Record | Expression, + ...otherMaps: Array | Expression> +): FunctionExpression; export function mapMerge( - firstMap: string | Record | Expr, - secondMap: Record | Expr, - ...otherMaps: Array | Expr> -): FunctionExpr { + firstMap: string | Record | Expression, + secondMap: Record | Expression, + ...otherMaps: Array | Expression> +): FunctionExpression { const secondMapExpr = valueToDefaultExpr(secondMap); const otherMapExprs = otherMaps.map(valueToDefaultExpr); return fieldOrExpression(firstMap).mapMerge(secondMapExpr, ...otherMapExprs); @@ -2976,16 +3133,36 @@ export function mapMerge( /** * @beta + * * Creates an expression that returns the document ID from a path. * * ```typescript * // Get the document ID from a path. - * documentId(field("__path__")); + * documentId(myDocumentReference); * ``` * * @return A new {@code Expr} representing the documentId operation. */ -export function documentId(documentPathExpr: Expr): FunctionExpr { +export function documentId( + documentPath: string | firestore.DocumentReference +): FunctionExpression; + +/** + * @beta + * Creates an expression that returns the document ID from a path. + * + * ```typescript + * // Get the document ID from a path. + * documentId(field("__path__")); + * ``` + * + * @return A new {@code Expression} representing the documentId operation. + */ +export function documentId(documentPathExpr: Expression): FunctionExpression; +export function documentId( + documentPath: Expression | string | firestore.DocumentReference +): FunctionExpression { + const documentPathExpr = valueToDefaultExpr(documentPath); return documentPathExpr.documentId(); } @@ -3001,7 +3178,7 @@ export function substring( field: string, position: number, length?: number -): FunctionExpr; +): FunctionExpression; /** * @beta @@ -3012,10 +3189,10 @@ export function substring( * @param length Length of the substring. */ export function substring( - input: Expr, + input: Expression, position: number, length?: number -): FunctionExpr; +): FunctionExpression; /** * @beta @@ -3027,9 +3204,9 @@ export function substring( */ export function substring( field: string, - position: Expr, - length?: Expr -): FunctionExpr; + position: Expression, + length?: Expression +): FunctionExpression; /** * @beta @@ -3040,16 +3217,16 @@ export function substring( * @param length An expression that returns the length of the substring. */ export function substring( - input: Expr, - position: Expr, - length?: Expr -): FunctionExpr; + input: Expression, + position: Expression, + length?: Expression +): FunctionExpression; export function substring( - field: Expr | string, - position: Expr | number, - length?: Expr | number -): FunctionExpr { + field: Expression | string, + position: Expression | number, + length?: Expression | number +): FunctionExpression { const fieldExpr = fieldOrExpression(field); const positionExpr = valueToDefaultExpr(position); const lengthExpr = @@ -3068,9 +3245,12 @@ export function substring( * * @param first The first expression to add. * @param second The second expression or literal to add. - * @return A new {@code Expr} representing the addition operation. + * @return A new {@code Expression} representing the addition operation. */ -export function add(first: Expr, second: Expr | unknown): FunctionExpr; +export function add( + first: Expression, + second: Expression | unknown +): FunctionExpression; /** * @beta @@ -3083,14 +3263,17 @@ export function add(first: Expr, second: Expr | unknown): FunctionExpr; * * @param fieldName The name of the field containing the value to add. * @param second The second expression or literal to add. - * @return A new {@code Expr} representing the addition operation. + * @return A new {@code Expression} representing the addition operation. */ -export function add(fieldName: string, second: Expr | unknown): FunctionExpr; +export function add( + fieldName: string, + second: Expression | unknown +): FunctionExpression; export function add( - first: Expr | string, - second: Expr | unknown -): FunctionExpr { + first: Expression | string, + second: Expression | unknown +): FunctionExpression { return fieldOrExpression(first).add(valueToDefaultExpr(second)); } @@ -3105,9 +3288,12 @@ export function add( * * @param minuend The expression to subtract from. * @param subtrahend The expression to subtract. - * @return A new {@code Expr} representing the subtraction operation. + * @return A new {@code Expression} representing the subtraction operation. */ -export function subtract(minuend: Expr, subtrahend: Expr): FunctionExpr; +export function subtract( + minuend: Expression, + subtrahend: Expression +): FunctionExpression; /** * @beta @@ -3120,9 +3306,12 @@ export function subtract(minuend: Expr, subtrahend: Expr): FunctionExpr; * * @param minuend The expression to subtract from. * @param subtrahend The constant value to subtract. - * @return A new {@code Expr} representing the subtraction operation. + * @return A new {@code Expression} representing the subtraction operation. */ -export function subtract(minuend: Expr, subtrahend: unknown): FunctionExpr; +export function subtract( + minuend: Expression, + subtrahend: unknown +): FunctionExpression; /** * @beta @@ -3135,12 +3324,12 @@ export function subtract(minuend: Expr, subtrahend: unknown): FunctionExpr; * * @param minuendFieldName The field name to subtract from. * @param subtrahend The expression to subtract. - * @return A new {@code Expr} representing the subtraction operation. + * @return A new {@code Expression} representing the subtraction operation. */ export function subtract( minuendFieldName: string, - subtrahend: Expr -): FunctionExpr; + subtrahend: Expression +): FunctionExpression; /** * @beta @@ -3153,16 +3342,16 @@ export function subtract( * * @param minuendFieldName The field name to subtract from. * @param subtrahend The constant value to subtract. - * @return A new {@code Expr} representing the subtraction operation. + * @return A new {@code Expression} representing the subtraction operation. */ export function subtract( minuendFieldName: string, subtrahend: unknown -): FunctionExpr; +): FunctionExpression; export function subtract( - left: Expr | string, - right: Expr | unknown -): FunctionExpr { + left: Expression | string, + right: Expression | unknown +): FunctionExpression { const normalizedLeft = fieldOrExpression(left); const normalizedRight = valueToDefaultExpr(right); return normalizedLeft.subtract(normalizedRight); @@ -3179,9 +3368,12 @@ export function subtract( * * @param first The first expression to multiply. * @param second The second expression or literal to multiply. - * @return A new {@code Expr} representing the multiplication operation. + * @return A new {@code Expression} representing the multiplication operation. */ -export function multiply(first: Expr, second: Expr | unknown): FunctionExpr; +export function multiply( + first: Expression, + second: Expression | unknown +): FunctionExpression; /** * @beta @@ -3194,17 +3386,17 @@ export function multiply(first: Expr, second: Expr | unknown): FunctionExpr; * * @param fieldName The name of the field containing the value to multiply. * @param second The second expression or literal to multiply. - * @return A new {@code Expr} representing the multiplication operation. + * @return A new {@code Expression} representing the multiplication operation. */ export function multiply( fieldName: string, - second: Expr | unknown -): FunctionExpr; + second: Expression | unknown +): FunctionExpression; export function multiply( - first: Expr | string, - second: Expr | unknown -): FunctionExpr { + first: Expression | string, + second: Expression | unknown +): FunctionExpression { return fieldOrExpression(first).multiply(valueToDefaultExpr(second)); } @@ -3219,9 +3411,12 @@ export function multiply( * * @param dividend The expression to be divided. * @param divisort The expression to divide by. - * @return A new {@code Expr} representing the division operation. + * @return A new {@code Expression} representing the division operation. */ -export function divide(dividend: Expr, divisort: Expr): FunctionExpr; +export function divide( + dividend: Expression, + divisort: Expression +): FunctionExpression; /** * @beta @@ -3234,9 +3429,12 @@ export function divide(dividend: Expr, divisort: Expr): FunctionExpr; * * @param dividend The expression to be divided. * @param divisor The constant value to divide by. - * @return A new {@code Expr} representing the division operation. + * @return A new {@code Expression} representing the division operation. */ -export function divide(dividend: Expr, divisor: unknown): FunctionExpr; +export function divide( + dividend: Expression, + divisor: unknown +): FunctionExpression; /** * @beta @@ -3249,9 +3447,12 @@ export function divide(dividend: Expr, divisor: unknown): FunctionExpr; * * @param dividend The field name to be divided. * @param divisor The expression to divide by. - * @return A new {@code Expr} representing the division operation. + * @return A new {@code Expression} representing the division operation. */ -export function divide(dividend: string, divisor: Expr): FunctionExpr; +export function divide( + dividend: string, + divisor: Expression +): FunctionExpression; /** * @beta @@ -3264,13 +3465,13 @@ export function divide(dividend: string, divisor: Expr): FunctionExpr; * * @param dividend The field name to be divided. * @param divisor The constant value to divide by. - * @return A new {@code Expr} representing the division operation. + * @return A new {@code Expression} representing the division operation. */ -export function divide(dividend: string, divisor: unknown): FunctionExpr; +export function divide(dividend: string, divisor: unknown): FunctionExpression; export function divide( - dividend: Expr | string, - divisor: Expr | unknown -): FunctionExpr { + dividend: Expression | string, + divisor: Expression | unknown +): FunctionExpression { const normalizedLeft = fieldOrExpression(dividend); const normalizedRight = valueToDefaultExpr(divisor); return normalizedLeft.divide(normalizedRight); @@ -3287,9 +3488,9 @@ export function divide( * * @param left The dividend expression. * @param right The divisor expression. - * @return A new {@code Expr} representing the modulo operation. + * @return A new {@code Expression} representing the modulo operation. */ -export function mod(left: Expr, right: Expr): FunctionExpr; +export function mod(left: Expression, right: Expression): FunctionExpression; /** * @beta @@ -3302,9 +3503,9 @@ export function mod(left: Expr, right: Expr): FunctionExpr; * * @param expression The dividend expression. * @param value The divisor constant. - * @return A new {@code Expr} representing the modulo operation. + * @return A new {@code Expression} representing the modulo operation. */ -export function mod(expression: Expr, value: unknown): FunctionExpr; +export function mod(expression: Expression, value: unknown): FunctionExpression; /** * @beta @@ -3317,9 +3518,12 @@ export function mod(expression: Expr, value: unknown): FunctionExpr; * * @param fieldName The dividend field name. * @param expression The divisor expression. - * @return A new {@code Expr} representing the modulo operation. + * @return A new {@code Expression} representing the modulo operation. */ -export function mod(fieldName: string, expression: Expr): FunctionExpr; +export function mod( + fieldName: string, + expression: Expression +): FunctionExpression; /** * @beta @@ -3332,10 +3536,13 @@ export function mod(fieldName: string, expression: Expr): FunctionExpr; * * @param fieldName The dividend field name. * @param value The divisor constant. - * @return A new {@code Expr} representing the modulo operation. + * @return A new {@code Expression} representing the modulo operation. */ -export function mod(fieldName: string, value: unknown): FunctionExpr; -export function mod(left: Expr | string, right: Expr | unknown): FunctionExpr { +export function mod(fieldName: string, value: unknown): FunctionExpression; +export function mod( + left: Expression | string, + right: Expression | unknown +): FunctionExpression { const normalizedLeft = fieldOrExpression(left); const normalizedRight = valueToDefaultExpr(right); return normalizedLeft.mod(normalizedRight); @@ -3351,10 +3558,10 @@ export function mod(left: Expr | string, right: Expr | unknown): FunctionExpr { * ``` * * @param elements The input map to evaluate in the expression. - * @return A new {@code Expr} representing the map function. + * @return A new {@code Expression} representing the map function. */ -export function map(elements: Record): FunctionExpr { - const result: Record = {}; +export function map(elements: Record): FunctionExpression { + const result: Record = {}; for (const key in elements) { if (Object.prototype.hasOwnProperty.call(elements, key)) { @@ -3380,7 +3587,7 @@ export function map(elements: Record): FunctionExpr { * @param plainObject */ export function _mapValue(plainObject: Record): MapValue { - const result: Map = new Map(); + const result: Map = new Map(); for (const key in plainObject) { if (Object.prototype.hasOwnProperty.call(plainObject, key)) { const value = plainObject[key]; @@ -3400,9 +3607,9 @@ export function _mapValue(plainObject: Record): MapValue { * ``` * * @param elements The input array to evaluate in the expression. - * @return A new {@code Expr} representing the array function. + * @return A new {@code Expression} representing the array function. */ -export function array(elements: unknown[]): FunctionExpr { +export function array(elements: unknown[]): FunctionExpression { return new ArrayFunctionExpr( elements.map(element => { return element !== undefined ? valueToDefaultExpr(element) : undefined; @@ -3416,14 +3623,14 @@ export function array(elements: unknown[]): FunctionExpr { * * ```typescript * // Check if the 'age' field is equal to an expression - * eq(field("age"), field("minAge").add(10)); + * equal(field("age"), field("minAge").add(10)); * ``` * * @param left The first expression to compare. * @param right The second expression to compare. - * @return A new `Expr` representing the equality comparison. + * @return A new `Expression` representing the equality comparison. */ -export function eq(left: Expr, right: Expr): BooleanExpr; +export function equal(left: Expression, right: Expression): BooleanExpression; /** * @beta @@ -3431,14 +3638,17 @@ export function eq(left: Expr, right: Expr): BooleanExpr; * * ```typescript * // Check if the 'age' field is equal to 21 - * eq(field("age"), 21); + * equal(field("age"), 21); * ``` * * @param expression The expression to compare. * @param value The constant value to compare to. - * @return A new `Expr` representing the equality comparison. + * @return A new `Expression` representing the equality comparison. */ -export function eq(expression: Expr, value: unknown): BooleanExpr; +export function equal( + expression: Expression, + value: unknown +): BooleanExpression; /** * @beta @@ -3446,14 +3656,17 @@ export function eq(expression: Expr, value: unknown): BooleanExpr; * * ```typescript * // Check if the 'age' field is equal to the 'limit' field - * eq("age", field("limit")); + * equal("age", field("limit")); * ``` * * @param fieldName The field name to compare. * @param expression The expression to compare to. - * @return A new `Expr` representing the equality comparison. + * @return A new `Expression` representing the equality comparison. */ -export function eq(fieldName: string, expression: Expr): BooleanExpr; +export function equal( + fieldName: string, + expression: Expression +): BooleanExpression; /** * @beta @@ -3461,18 +3674,21 @@ export function eq(fieldName: string, expression: Expr): BooleanExpr; * * ```typescript * // Check if the 'city' field is equal to string constant "London" - * eq("city", "London"); + * equal("city", "London"); * ``` * * @param fieldName The field name to compare. * @param value The constant value to compare to. - * @return A new `Expr` representing the equality comparison. + * @return A new `Expression` representing the equality comparison. */ -export function eq(fieldName: string, value: unknown): BooleanExpr; -export function eq(left: Expr | string, right: unknown): BooleanExpr { +export function equal(fieldName: string, value: unknown): BooleanExpression; +export function equal( + left: Expression | string, + right: unknown +): BooleanExpression { const leftExpr = fieldOrExpression(left); const rightExpr = valueToDefaultExpr(right); - return leftExpr.eq(rightExpr); + return leftExpr.equal(rightExpr); } /** @@ -3481,14 +3697,17 @@ export function eq(left: Expr | string, right: unknown): BooleanExpr { * * ```typescript * // Check if the 'status' field is not equal to field 'finalState' - * neq(field("status"), field("finalState")); + * notEqual(field("status"), field("finalState")); * ``` * * @param left The first expression to compare. * @param right The second expression to compare. - * @return A new `Expr` representing the inequality comparison. + * @return A new `Expression` representing the inequality comparison. */ -export function neq(left: Expr, right: Expr): BooleanExpr; +export function notEqual( + left: Expression, + right: Expression +): BooleanExpression; /** * @beta @@ -3496,14 +3715,17 @@ export function neq(left: Expr, right: Expr): BooleanExpr; * * ```typescript * // Check if the 'status' field is not equal to "completed" - * neq(field("status"), "completed"); + * notEqual(field("status"), "completed"); * ``` * * @param expression The expression to compare. * @param value The constant value to compare to. - * @return A new `Expr` representing the inequality comparison. + * @return A new `Expression` representing the inequality comparison. */ -export function neq(expression: Expr, value: unknown): BooleanExpr; +export function notEqual( + expression: Expression, + value: unknown +): BooleanExpression; /** * @beta @@ -3511,14 +3733,17 @@ export function neq(expression: Expr, value: unknown): BooleanExpr; * * ```typescript * // Check if the 'status' field is not equal to the value of 'expectedStatus' - * neq("status", field("expectedStatus")); + * notEqual("status", field("expectedStatus")); * ``` * * @param fieldName The field name to compare. * @param expression The expression to compare to. - * @return A new `Expr` representing the inequality comparison. + * @return A new `Expression` representing the inequality comparison. */ -export function neq(fieldName: string, expression: Expr): BooleanExpr; +export function notEqual( + fieldName: string, + expression: Expression +): BooleanExpression; /** * @beta @@ -3526,18 +3751,21 @@ export function neq(fieldName: string, expression: Expr): BooleanExpr; * * ```typescript * // Check if the 'country' field is not equal to "USA" - * neq("country", "USA"); + * notEqual("country", "USA"); * ``` * * @param fieldName The field name to compare. * @param value The constant value to compare to. - * @return A new `Expr` representing the inequality comparison. + * @return A new `Expression` representing the inequality comparison. */ -export function neq(fieldName: string, value: unknown): BooleanExpr; -export function neq(left: Expr | string, right: unknown): BooleanExpr { +export function notEqual(fieldName: string, value: unknown): BooleanExpression; +export function notEqual( + left: Expression | string, + right: unknown +): BooleanExpression { const leftExpr = fieldOrExpression(left); const rightExpr = valueToDefaultExpr(right); - return leftExpr.neq(rightExpr); + return leftExpr.notEqual(rightExpr); } /** @@ -3546,14 +3774,17 @@ export function neq(left: Expr | string, right: unknown): BooleanExpr { * * ```typescript * // Check if the 'age' field is less than 30 - * lt(field("age"), field("limit")); + * lessThan(field("age"), field("limit")); * ``` * * @param left The first expression to compare. * @param right The second expression to compare. - * @return A new `Expr` representing the less than comparison. + * @return A new `Expression` representing the less than comparison. */ -export function lt(left: Expr, right: Expr): BooleanExpr; +export function lessThan( + left: Expression, + right: Expression +): BooleanExpression; /** * @beta @@ -3561,14 +3792,17 @@ export function lt(left: Expr, right: Expr): BooleanExpr; * * ```typescript * // Check if the 'age' field is less than 30 - * lt(field("age"), 30); + * lessThan(field("age"), 30); * ``` * * @param expression The expression to compare. * @param value The constant value to compare to. - * @return A new `Expr` representing the less than comparison. + * @return A new `Expression` representing the less than comparison. */ -export function lt(expression: Expr, value: unknown): BooleanExpr; +export function lessThan( + expression: Expression, + value: unknown +): BooleanExpression; /** * @beta @@ -3576,14 +3810,17 @@ export function lt(expression: Expr, value: unknown): BooleanExpr; * * ```typescript * // Check if the 'age' field is less than the 'limit' field - * lt("age", field("limit")); + * lessThan("age", field("limit")); * ``` * * @param fieldName The field name to compare. * @param expression The expression to compare to. - * @return A new `Expr` representing the less than comparison. + * @return A new `Expression` representing the less than comparison. */ -export function lt(fieldName: string, expression: Expr): BooleanExpr; +export function lessThan( + fieldName: string, + expression: Expression +): BooleanExpression; /** * @beta @@ -3591,18 +3828,21 @@ export function lt(fieldName: string, expression: Expr): BooleanExpr; * * ```typescript * // Check if the 'price' field is less than 50 - * lt("price", 50); + * lessThan("price", 50); * ``` * * @param fieldName The field name to compare. * @param value The constant value to compare to. - * @return A new `Expr` representing the less than comparison. + * @return A new `Expression` representing the less than comparison. */ -export function lt(fieldName: string, value: unknown): BooleanExpr; -export function lt(left: Expr | string, right: unknown): BooleanExpr { +export function lessThan(fieldName: string, value: unknown): BooleanExpression; +export function lessThan( + left: Expression | string, + right: unknown +): BooleanExpression { const leftExpr = fieldOrExpression(left); const rightExpr = valueToDefaultExpr(right); - return leftExpr.lt(rightExpr); + return leftExpr.lessThan(rightExpr); } /** @@ -3612,14 +3852,17 @@ export function lt(left: Expr | string, right: unknown): BooleanExpr { * * ```typescript * // Check if the 'quantity' field is less than or equal to 20 - * lte(field("quantity"), field("limit")); + * lessThanOrEqual(field("quantity"), field("limit")); * ``` * * @param left The first expression to compare. * @param right The second expression to compare. - * @return A new `Expr` representing the less than or equal to comparison. + * @return A new `Expression` representing the less than or equal to comparison. */ -export function lte(left: Expr, right: Expr): BooleanExpr; +export function lessThanOrEqual( + left: Expression, + right: Expression +): BooleanExpression; /** * @beta @@ -3627,14 +3870,17 @@ export function lte(left: Expr, right: Expr): BooleanExpr; * * ```typescript * // Check if the 'quantity' field is less than or equal to 20 - * lte(field("quantity"), 20); + * lessThanOrEqual(field("quantity"), 20); * ``` * * @param expression The expression to compare. * @param value The constant value to compare to. - * @return A new `Expr` representing the less than or equal to comparison. + * @return A new `Expression` representing the less than or equal to comparison. */ -export function lte(expression: Expr, value: unknown): BooleanExpr; +export function lessThanOrEqual( + expression: Expression, + value: unknown +): BooleanExpression; /** * @beta @@ -3642,14 +3888,17 @@ export function lte(expression: Expr, value: unknown): BooleanExpr; * * ```typescript * // Check if the 'quantity' field is less than or equal to the 'limit' field - * lte("quantity", field("limit")); + * lessThanOrEqual("quantity", field("limit")); * ``` * * @param fieldName The field name to compare. * @param expression The expression to compare to. - * @return A new `Expr` representing the less than or equal to comparison. + * @return A new `Expression` representing the less than or equal to comparison. */ -export function lte(fieldName: string, expression: Expr): BooleanExpr; +export function lessThanOrEqual( + fieldName: string, + expression: Expression +): BooleanExpression; /** * @beta @@ -3657,18 +3906,24 @@ export function lte(fieldName: string, expression: Expr): BooleanExpr; * * ```typescript * // Check if the 'score' field is less than or equal to 70 - * lte("score", 70); + * lessThanOrEqual("score", 70); * ``` * * @param fieldName The field name to compare. * @param value The constant value to compare to. - * @return A new `Expr` representing the less than or equal to comparison. + * @return A new `Expression` representing the less than or equal to comparison. */ -export function lte(fieldName: string, value: unknown): BooleanExpr; -export function lte(left: Expr | string, right: unknown): BooleanExpr { +export function lessThanOrEqual( + fieldName: string, + value: unknown +): BooleanExpression; +export function lessThanOrEqual( + left: Expression | string, + right: unknown +): BooleanExpression { const leftExpr = fieldOrExpression(left); const rightExpr = valueToDefaultExpr(right); - return leftExpr.lte(rightExpr); + return leftExpr.lessThanOrEqual(rightExpr); } /** @@ -3678,14 +3933,17 @@ export function lte(left: Expr | string, right: unknown): BooleanExpr { * * ```typescript * // Check if the 'age' field is greater than 18 - * gt(field("age"), Constant(9).add(9)); + * greaterThan(field("age"), Constant(9).add(9)); * ``` * * @param left The first expression to compare. * @param right The second expression to compare. - * @return A new `Expr` representing the greater than comparison. + * @return A new `Expression` representing the greater than comparison. */ -export function gt(left: Expr, right: Expr): BooleanExpr; +export function greaterThan( + left: Expression, + right: Expression +): BooleanExpression; /** * @beta @@ -3693,14 +3951,17 @@ export function gt(left: Expr, right: Expr): BooleanExpr; * * ```typescript * // Check if the 'age' field is greater than 18 - * gt(field("age"), 18); + * greaterThan(field("age"), 18); * ``` * * @param expression The expression to compare. * @param value The constant value to compare to. - * @return A new `Expr` representing the greater than comparison. + * @return A new `Expression` representing the greater than comparison. */ -export function gt(expression: Expr, value: unknown): BooleanExpr; +export function greaterThan( + expression: Expression, + value: unknown +): BooleanExpression; /** * @beta @@ -3708,14 +3969,17 @@ export function gt(expression: Expr, value: unknown): BooleanExpr; * * ```typescript * // Check if the value of field 'age' is greater than the value of field 'limit' - * gt("age", field("limit")); + * greaterThan("age", field("limit")); * ``` * * @param fieldName The field name to compare. * @param expression The expression to compare to. - * @return A new `Expr` representing the greater than comparison. + * @return A new `Expression` representing the greater than comparison. */ -export function gt(fieldName: string, expression: Expr): BooleanExpr; +export function greaterThan( + fieldName: string, + expression: Expression +): BooleanExpression; /** * @beta @@ -3723,18 +3987,24 @@ export function gt(fieldName: string, expression: Expr): BooleanExpr; * * ```typescript * // Check if the 'price' field is greater than 100 - * gt("price", 100); + * greaterThan("price", 100); * ``` * * @param fieldName The field name to compare. * @param value The constant value to compare to. - * @return A new `Expr` representing the greater than comparison. + * @return A new `Expression` representing the greater than comparison. */ -export function gt(fieldName: string, value: unknown): BooleanExpr; -export function gt(left: Expr | string, right: unknown): BooleanExpr { +export function greaterThan( + fieldName: string, + value: unknown +): BooleanExpression; +export function greaterThan( + left: Expression | string, + right: unknown +): BooleanExpression { const leftExpr = fieldOrExpression(left); const rightExpr = valueToDefaultExpr(right); - return leftExpr.gt(rightExpr); + return leftExpr.greaterThan(rightExpr); } /** @@ -3744,14 +4014,17 @@ export function gt(left: Expr | string, right: unknown): BooleanExpr { * * ```typescript * // Check if the 'quantity' field is greater than or equal to the field "threshold" - * gte(field("quantity"), field("threshold")); + * greaterThanOrEqual(field("quantity"), field("threshold")); * ``` * * @param left The first expression to compare. * @param right The second expression to compare. - * @return A new `Expr` representing the greater than or equal to comparison. + * @return A new `Expression` representing the greater than or equal to comparison. */ -export function gte(left: Expr, right: Expr): BooleanExpr; +export function greaterThanOrEqual( + left: Expression, + right: Expression +): BooleanExpression; /** * @beta @@ -3760,14 +4033,17 @@ export function gte(left: Expr, right: Expr): BooleanExpr; * * ```typescript * // Check if the 'quantity' field is greater than or equal to 10 - * gte(field("quantity"), 10); + * greaterThanOrEqual(field("quantity"), 10); * ``` * * @param expression The expression to compare. * @param value The constant value to compare to. - * @return A new `Expr` representing the greater than or equal to comparison. + * @return A new `Expression` representing the greater than or equal to comparison. */ -export function gte(expression: Expr, value: unknown): BooleanExpr; +export function greaterThanOrEqual( + expression: Expression, + value: unknown +): BooleanExpression; /** * @beta @@ -3775,14 +4051,17 @@ export function gte(expression: Expr, value: unknown): BooleanExpr; * * ```typescript * // Check if the value of field 'age' is greater than or equal to the value of field 'limit' - * gte("age", field("limit")); + * greaterThanOrEqual("age", field("limit")); * ``` * * @param fieldName The field name to compare. * @param value The expression to compare to. - * @return A new `Expr` representing the greater than or equal to comparison. + * @return A new `Expression` representing the greater than or equal to comparison. */ -export function gte(fieldName: string, value: Expr): BooleanExpr; +export function greaterThanOrEqual( + fieldName: string, + value: Expression +): BooleanExpression; /** * @beta @@ -3791,18 +4070,78 @@ export function gte(fieldName: string, value: Expr): BooleanExpr; * * ```typescript * // Check if the 'score' field is greater than or equal to 80 - * gte("score", 80); + * greaterThanOrEqual("score", 80); * ``` * * @param fieldName The field name to compare. * @param value The constant value to compare to. - * @return A new `Expr` representing the greater than or equal to comparison. + * @return A new `Expression` representing the greater than or equal to comparison. */ -export function gte(fieldName: string, value: unknown): BooleanExpr; -export function gte(left: Expr | string, right: unknown): BooleanExpr { +export function greaterThanOrEqual( + fieldName: string, + value: unknown +): BooleanExpression; +export function greaterThanOrEqual( + left: Expression | string, + right: unknown +): BooleanExpression { const leftExpr = fieldOrExpression(left); const rightExpr = valueToDefaultExpr(right); - return leftExpr.gte(rightExpr); + return leftExpr.greaterThanOrEqual(rightExpr); +} + +/** + * @beta + * + * Creates an expression that concatenates an array expression with other arrays. + * + * ```typescript + * // Combine the 'items' array with two new item arrays + * arrayConcat(field("items"), [field("newItems"), field("otherItems")]); + * ``` + * + * @param firstArray The first array expression to concatenate to. + * @param secondArray The second array expression or array literal to concatenate to. + * @param otherArrays Optional additional array expressions or array literals to concatenate. + * @return A new {@code Expr} representing the concatenated array. + */ +export function arrayConcat( + firstArray: Expression, + secondArray: Expression | unknown[], + ...otherArrays: Array +): FunctionExpression; + +/** + * @beta + * + * Creates an expression that concatenates a field's array value with other arrays. + * + * ```typescript + * // Combine the 'items' array with two new item arrays + * arrayConcat("items", [field("newItems"), field("otherItems")]); + * ``` + * + * @param firstArrayField The first array to concatenate to. + * @param secondArray The second array expression or array literal to concatenate to. + * @param otherArrays Optional additional array expressions or array literals to concatenate. + * @return A new {@code Expr} representing the concatenated array. + */ +export function arrayConcat( + firstArrayField: string, + secondArray: Expression | unknown[], + ...otherArrays: Array +): FunctionExpression; + +export function arrayConcat( + firstArray: Expression | string, + secondArray: Expression | unknown[], + ...otherArrays: Array +): FunctionExpression { + const exprValues = otherArrays.map(element => valueToDefaultExpr(element)); + return fieldOrExpression(firstArray).arrayConcat( + fieldOrExpression(secondArray), + ...exprValues + ); } /** @@ -3816,9 +4155,12 @@ export function gte(left: Expr | string, right: unknown): BooleanExpr { * * @param array The array expression to check. * @param element The element to search for in the array. - * @return A new {@code Expr} representing the 'array_contains' comparison. + * @return A new {@code Expression} representing the 'array_contains' comparison. */ -export function arrayContains(array: Expr, element: Expr): FunctionExpr; +export function arrayContains( + array: Expression, + element: Expression +): FunctionExpression; /** * @beta @@ -3831,9 +4173,12 @@ export function arrayContains(array: Expr, element: Expr): FunctionExpr; * * @param array The array expression to check. * @param element The element to search for in the array. - * @return A new {@code Expr} representing the 'array_contains' comparison. + * @return A new {@code Expression} representing the 'array_contains' comparison. */ -export function arrayContains(array: Expr, element: unknown): FunctionExpr; +export function arrayContains( + array: Expression, + element: unknown +): FunctionExpression; /** * @beta @@ -3846,9 +4191,12 @@ export function arrayContains(array: Expr, element: unknown): FunctionExpr; * * @param fieldName The field name to check. * @param element The element to search for in the array. - * @return A new {@code Expr} representing the 'array_contains' comparison. + * @return A new {@code Expression} representing the 'array_contains' comparison. */ -export function arrayContains(fieldName: string, element: Expr): FunctionExpr; +export function arrayContains( + fieldName: string, + element: Expression +): FunctionExpression; /** * @beta @@ -3861,13 +4209,16 @@ export function arrayContains(fieldName: string, element: Expr): FunctionExpr; * * @param fieldName The field name to check. * @param element The element to search for in the array. - * @return A new {@code Expr} representing the 'array_contains' comparison. + * @return A new {@code Expression} representing the 'array_contains' comparison. */ -export function arrayContains(fieldName: string, element: unknown): BooleanExpr; export function arrayContains( - array: Expr | string, + fieldName: string, + element: unknown +): BooleanExpression; +export function arrayContains( + array: Expression | string, element: unknown -): BooleanExpr { +): BooleanExpression { const arrayExpr = fieldOrExpression(array); const elementExpr = valueToDefaultExpr(element); return arrayExpr.arrayContains(elementExpr); @@ -3885,12 +4236,12 @@ export function arrayContains( * * @param array The array expression to check. * @param values The elements to check for in the array. - * @return A new {@code Expr} representing the 'array_contains_any' comparison. + * @return A new {@code Expression} representing the 'array_contains_any' comparison. */ export function arrayContainsAny( - array: Expr, - values: Array -): BooleanExpr; + array: Expression, + values: Array +): BooleanExpression; /** * @beta @@ -3905,12 +4256,12 @@ export function arrayContainsAny( * * @param fieldName The field name to check. * @param values The elements to check for in the array. - * @return A new {@code Expr} representing the 'array_contains_any' comparison. + * @return A new {@code Expression} representing the 'array_contains_any' comparison. */ export function arrayContainsAny( fieldName: string, - values: Array -): BooleanExpr; + values: Array +): BooleanExpression; /** * @beta @@ -3924,9 +4275,12 @@ export function arrayContainsAny( * * @param array The array expression to check. * @param values An expression that evaluates to an array, whose elements to check for in the array. - * @return A new {@code Expr} representing the 'array_contains_any' comparison. + * @return A new {@code Expression} representing the 'array_contains_any' comparison. */ -export function arrayContainsAny(array: Expr, values: Expr): BooleanExpr; +export function arrayContainsAny( + array: Expression, + values: Expression +): BooleanExpression; /** * @beta @@ -3941,13 +4295,16 @@ export function arrayContainsAny(array: Expr, values: Expr): BooleanExpr; * * @param fieldName The field name to check. * @param values An expression that evaluates to an array, whose elements to check for in the array field. - * @return A new {@code Expr} representing the 'array_contains_any' comparison. + * @return A new {@code Expression} representing the 'array_contains_any' comparison. */ -export function arrayContainsAny(fieldName: string, values: Expr): BooleanExpr; export function arrayContainsAny( - array: Expr | string, - values: unknown[] | Expr -): BooleanExpr { + fieldName: string, + values: Expression +): BooleanExpression; +export function arrayContainsAny( + array: Expression | string, + values: unknown[] | Expression +): BooleanExpression { if (Array.isArray(values)) { return fieldOrExpression(array).arrayContainsAny(values); } else { @@ -3966,12 +4323,12 @@ export function arrayContainsAny( * * @param array The array expression to check. * @param values The elements to check for in the array. - * @return A new {@code Expr} representing the 'array_contains_all' comparison. + * @return A new {@code Expression} representing the 'array_contains_all' comparison. */ export function arrayContainsAll( - array: Expr, - values: Array -): BooleanExpr; + array: Expression, + values: Array +): BooleanExpression; /** * @beta @@ -3985,12 +4342,12 @@ export function arrayContainsAll( * * @param fieldName The field name to check. * @param values The elements to check for in the array. - * @return A new {@code Expr} representing the 'array_contains_all' comparison. + * @return A new {@code Expression} representing the 'array_contains_all' comparison. */ export function arrayContainsAll( fieldName: string, - values: Array -): BooleanExpr; + values: Array +): BooleanExpression; /** * @beta @@ -4003,12 +4360,12 @@ export function arrayContainsAll( * * @param array The array expression to check. * @param arrayExpression The elements to check for in the array. - * @return A new {@code Expr} representing the 'array_contains_all' comparison. + * @return A new {@code Expression} representing the 'array_contains_all' comparison. */ export function arrayContainsAll( - array: Expr, - arrayExpression: Expr -): BooleanExpr; + array: Expression, + arrayExpression: Expression +): BooleanExpression; /** * @beta @@ -4022,16 +4379,16 @@ export function arrayContainsAll( * * @param fieldName The field name to check. * @param arrayExpression The elements to check for in the array. - * @return A new {@code Expr} representing the 'array_contains_all' comparison. + * @return A new {@code Expression} representing the 'array_contains_all' comparison. */ export function arrayContainsAll( fieldName: string, - arrayExpression: Expr -): BooleanExpr; + arrayExpression: Expression +): BooleanExpression; export function arrayContainsAll( - array: Expr | string, - values: unknown[] | Expr -): BooleanExpr { + array: Expression | string, + values: unknown[] | Expression +): BooleanExpression { if (Array.isArray(values)) { return fieldOrExpression(array).arrayContainsAll(values); } else { @@ -4049,9 +4406,9 @@ export function arrayContainsAll( * ``` * * @param fieldName The name of the field containing an array to calculate the length of. - * @return A new {@code Expr} representing the length of the array. + * @return A new {@code Expression} representing the length of the array. */ -export function arrayLength(fieldName: string): FunctionExpr; +export function arrayLength(fieldName: string): FunctionExpression; /** * @beta @@ -4063,10 +4420,10 @@ export function arrayLength(fieldName: string): FunctionExpr; * ``` * * @param array The array expression to calculate the length of. - * @return A new {@code Expr} representing the length of the array. + * @return A new {@code Expression} representing the length of the array. */ -export function arrayLength(array: Expr): FunctionExpr; -export function arrayLength(array: Expr | string): FunctionExpr { +export function arrayLength(array: Expression): FunctionExpression; +export function arrayLength(array: Expression | string): FunctionExpression { return fieldOrExpression(array).arrayLength(); } @@ -4077,17 +4434,17 @@ export function arrayLength(array: Expr | string): FunctionExpr { * * ```typescript * // Check if the 'category' field is either "Electronics" or value of field 'primaryType' - * eqAny(field("category"), [constant("Electronics"), field("primaryType")]); + * equalAny(field("category"), [constant("Electronics"), field("primaryType")]); * ``` * * @param expression The expression whose results to compare. * @param values The values to check against. - * @return A new {@code Expr} representing the 'IN' comparison. + * @return A new {@code Expression} representing the 'IN' comparison. */ -export function eqAny( - expression: Expr, - values: Array -): BooleanExpr; +export function equalAny( + expression: Expression, + values: Array +): BooleanExpression; /** * @beta @@ -4095,14 +4452,17 @@ export function eqAny( * * ```typescript * // Check if the 'category' field is set to a value in the disabledCategories field - * eqAny(field("category"), field('disabledCategories')); + * equalAny(field("category"), field('disabledCategories')); * ``` * * @param expression The expression whose results to compare. * @param arrayExpression An expression that evaluates to an array, whose elements to check for equality to the input. - * @return A new {@code Expr} representing the 'IN' comparison. + * @return A new {@code Expression} representing the 'IN' comparison. */ -export function eqAny(expression: Expr, arrayExpression: Expr): BooleanExpr; +export function equalAny( + expression: Expression, + arrayExpression: Expression +): BooleanExpression; /** * @beta @@ -4111,17 +4471,17 @@ export function eqAny(expression: Expr, arrayExpression: Expr): BooleanExpr; * * ```typescript * // Check if the 'category' field is either "Electronics" or value of field 'primaryType' - * eqAny("category", [constant("Electronics"), field("primaryType")]); + * equalAny("category", [constant("Electronics"), field("primaryType")]); * ``` * * @param fieldName The field to compare. * @param values The values to check against. - * @return A new {@code Expr} representing the 'IN' comparison. + * @return A new {@code Expression} representing the 'IN' comparison. */ -export function eqAny( +export function equalAny( fieldName: string, - values: Array -): BooleanExpr; + values: Array +): BooleanExpression; /** * @beta @@ -4130,22 +4490,25 @@ export function eqAny( * * ```typescript * // Check if the 'category' field is either "Electronics" or value of field 'primaryType' - * eqAny("category", ["Electronics", field("primaryType")]); + * equalAny("category", ["Electronics", field("primaryType")]); * ``` * * @param fieldName The field to compare. * @param arrayExpression An expression that evaluates to an array, whose elements to check for equality to the input field. - * @return A new {@code Expr} representing the 'IN' comparison. + * @return A new {@code Expression} representing the 'IN' comparison. */ -export function eqAny(fieldName: string, arrayExpression: Expr): BooleanExpr; -export function eqAny( - element: Expr | string, - values: unknown[] | Expr -): BooleanExpr { +export function equalAny( + fieldName: string, + arrayExpression: Expression +): BooleanExpression; +export function equalAny( + element: Expression | string, + values: unknown[] | Expression +): BooleanExpression { if (Array.isArray(values)) { - return fieldOrExpression(element).eqAny(values); + return fieldOrExpression(element).equalAny(values); } else { - return fieldOrExpression(element).eqAny(values); + return fieldOrExpression(element).equalAny(values); } } @@ -4156,17 +4519,17 @@ export function eqAny( * * ```typescript * // Check if the 'status' field is neither "pending" nor the value of 'rejectedStatus' - * notEqAny(field("status"), ["pending", field("rejectedStatus")]); + * notEqualAny(field("status"), ["pending", field("rejectedStatus")]); * ``` * * @param element The expression to compare. * @param values The values to check against. - * @return A new {@code Expr} representing the 'NOT IN' comparison. + * @return A new {@code Expression} representing the 'NOT IN' comparison. */ -export function notEqAny( - element: Expr, - values: Array -): BooleanExpr; +export function notEqualAny( + element: Expression, + values: Array +): BooleanExpression; /** * @beta @@ -4175,17 +4538,17 @@ export function notEqAny( * * ```typescript * // Check if the 'status' field is neither "pending" nor the value of 'rejectedStatus' - * notEqAny("status", [constant("pending"), field("rejectedStatus")]); + * notEqualAny("status", [constant("pending"), field("rejectedStatus")]); * ``` * * @param fieldName The field name to compare. * @param values The values to check against. - * @return A new {@code Expr} representing the 'NOT IN' comparison. + * @return A new {@code Expression} representing the 'NOT IN' comparison. */ -export function notEqAny( +export function notEqualAny( fieldName: string, - values: Array -): BooleanExpr; + values: Array +): BooleanExpression; /** * @beta @@ -4194,14 +4557,17 @@ export function notEqAny( * * ```typescript * // Check if the 'status' field is neither "pending" nor the value of the field 'rejectedStatus' - * notEqAny(field("status"), ["pending", field("rejectedStatus")]); + * notEqualAny(field("status"), ["pending", field("rejectedStatus")]); * ``` * * @param element The expression to compare. * @param arrayExpression The values to check against. - * @return A new {@code Expr} representing the 'NOT IN' comparison. + * @return A new {@code Expression} representing the 'NOT IN' comparison. */ -export function notEqAny(element: Expr, arrayExpression: Expr): BooleanExpr; +export function notEqualAny( + element: Expression, + arrayExpression: Expression +): BooleanExpression; /** * @beta @@ -4209,23 +4575,26 @@ export function notEqAny(element: Expr, arrayExpression: Expr): BooleanExpr; * * ```typescript * // Check if the 'status' field is not equal to any value in the field 'rejectedStatuses' - * notEqAny("status", field("rejectedStatuses")); + * notEqualAny("status", field("rejectedStatuses")); * ``` * * @param fieldName The field name to compare. * @param arrayExpression The values to check against. - * @return A new {@code Expr} representing the 'NOT IN' comparison. + * @return A new {@code Expression} representing the 'NOT IN' comparison. */ -export function notEqAny(fieldName: string, arrayExpression: Expr): BooleanExpr; +export function notEqualAny( + fieldName: string, + arrayExpression: Expression +): BooleanExpression; -export function notEqAny( - element: Expr | string, - values: unknown[] | Expr -): BooleanExpr { +export function notEqualAny( + element: Expression | string, + values: unknown[] | Expression +): BooleanExpression { if (Array.isArray(values)) { - return fieldOrExpression(element).notEqAny(values); + return fieldOrExpression(element).notEqualAny(values); } else { - return fieldOrExpression(element).notEqAny(values); + return fieldOrExpression(element).notEqualAny(values); } } @@ -4237,22 +4606,22 @@ export function notEqAny( * // Check if only one of the conditions is true: 'age' greater than 18, 'city' is "London", * // or 'status' is "active". * const condition = xor( - * gt("age", 18), - * eq("city", "London"), - * eq("status", "active")); + * greaterThan("age", 18), + * equal("city", "London"), + * equal("status", "active")); * ``` * * @param first The first condition. * @param second The second condition. * @param additionalConditions Additional conditions to 'XOR' together. - * @return A new {@code Expr} representing the logical 'XOR' operation. + * @return A new {@code Expression} representing the logical 'XOR' operation. */ export function xor( - first: BooleanExpr, - second: BooleanExpr, - ...additionalConditions: BooleanExpr[] -): BooleanExpr { - return new BooleanExpr('xor', [first, second, ...additionalConditions]); + first: BooleanExpression, + second: BooleanExpression, + ...additionalConditions: BooleanExpression[] +): BooleanExpression { + return new BooleanExpression('xor', [first, second, ...additionalConditions]); } /** @@ -4262,24 +4631,24 @@ export function xor( * * ```typescript * // If 'age' is greater than 18, return "Adult"; otherwise, return "Minor". - * cond( - * gt("age", 18), constant("Adult"), constant("Minor")); + * conditional( + * greaterThan("age", 18), constant("Adult"), constant("Minor")); * ``` * * @param condition The condition to evaluate. * @param thenExpr The expression to evaluate if the condition is true. * @param elseExpr The expression to evaluate if the condition is false. - * @return A new {@code Expr} representing the conditional expression. - */ -export function cond( - condition: BooleanExpr, - thenExpr: Expr, - elseExpr: Expr -): FunctionExpr { - return new FunctionExpr('cond', [ + * @return A new {@code Expression} representing the conditional expression. + */ +export function conditional( + condition: BooleanExpression, + thenExpr: Expression, + elseExpr: Expression +): FunctionExpression { + return new FunctionExpression('conditional', [ condition, - cast(thenExpr), - cast(elseExpr), + cast(thenExpr), + cast(elseExpr), ]); } @@ -4289,13 +4658,13 @@ export function cond( * * ```typescript * // Find documents where the 'completed' field is NOT true - * not(eq("completed", true)); + * not(equal("completed", true)); * ``` * * @param booleanExpr The filter condition to negate. - * @return A new {@code Expr} representing the negated filter condition. + * @return A new {@code Expression} representing the negated filter condition. */ -export function not(booleanExpr: BooleanExpr): BooleanExpr { +export function not(booleanExpr: BooleanExpression): BooleanExpression { return booleanExpr.not(); } @@ -4313,13 +4682,13 @@ export function not(booleanExpr: BooleanExpr): BooleanExpr { * @param first The first operand expression. * @param second The second expression or literal. * @param others Optional additional expressions or literals. - * @return A new {@code Expr} representing the logical max operation. + * @return A new {@code Expression} representing the logical max operation. */ export function logicalMaximum( - first: Expr, - second: Expr | unknown, - ...others: Array -): FunctionExpr; + first: Expression, + second: Expression | unknown, + ...others: Array +): FunctionExpression; /** * @beta @@ -4335,19 +4704,19 @@ export function logicalMaximum( * @param fieldName The first operand field name. * @param second The second expression or literal. * @param others Optional additional expressions or literals. - * @return A new {@code Expr} representing the logical max operation. + * @return A new {@code Expression} representing the logical max operation. */ export function logicalMaximum( fieldName: string, - second: Expr | unknown, - ...others: Array -): FunctionExpr; + second: Expression | unknown, + ...others: Array +): FunctionExpression; export function logicalMaximum( - first: Expr | string, - second: Expr | unknown, - ...others: Array -): FunctionExpr { + first: Expression | string, + second: Expression | unknown, + ...others: Array +): FunctionExpression { return fieldOrExpression(first).logicalMaximum( valueToDefaultExpr(second), ...others.map(value => valueToDefaultExpr(value)) @@ -4368,13 +4737,13 @@ export function logicalMaximum( * @param first The first operand expression. * @param second The second expression or literal. * @param others Optional additional expressions or literals. - * @return A new {@code Expr} representing the logical min operation. + * @return A new {@code Expression} representing the logical min operation. */ export function logicalMinimum( - first: Expr, - second: Expr | unknown, - ...others: Array -): FunctionExpr; + first: Expression, + second: Expression | unknown, + ...others: Array +): FunctionExpression; /** * @beta @@ -4391,19 +4760,19 @@ export function logicalMinimum( * @param fieldName The first operand field name. * @param second The second expression or literal. * @param others Optional additional expressions or literals. - * @return A new {@code Expr} representing the logical min operation. + * @return A new {@code Expression} representing the logical min operation. */ export function logicalMinimum( fieldName: string, - second: Expr | unknown, - ...others: Array -): FunctionExpr; + second: Expression | unknown, + ...others: Array +): FunctionExpression; export function logicalMinimum( - first: Expr | string, - second: Expr | unknown, - ...others: Array -): FunctionExpr { + first: Expression | string, + second: Expression | unknown, + ...others: Array +): FunctionExpression { return fieldOrExpression(first).logicalMinimum( valueToDefaultExpr(second), ...others.map(value => valueToDefaultExpr(value)) @@ -4420,9 +4789,9 @@ export function logicalMinimum( * ``` * * @param value An expression evaluates to the name of the field to check. - * @return A new {@code Expr} representing the 'exists' check. + * @return A new {@code Expression} representing the 'exists' check. */ -export function exists(value: Expr): BooleanExpr; +export function exists(value: Expression): BooleanExpression; /** * @beta @@ -4434,44 +4803,13 @@ export function exists(value: Expr): BooleanExpr; * ``` * * @param fieldName The field name to check. - * @return A new {@code Expr} representing the 'exists' check. + * @return A new {@code Expression} representing the 'exists' check. */ -export function exists(fieldName: string): BooleanExpr; -export function exists(valueOrField: Expr | string): BooleanExpr { +export function exists(fieldName: string): BooleanExpression; +export function exists(valueOrField: Expression | string): BooleanExpression { return fieldOrExpression(valueOrField).exists(); } -/** - * @beta - * Creates an expression that checks if an expression evaluates to 'NaN' (Not a Number). - * - * ```typescript - * // Check if the result of a calculation is NaN - * isNan(field("value").divide(0)); - * ``` - * - * @param value The expression to check. - * @return A new {@code Expr} representing the 'isNan' check. - */ -export function isNan(value: Expr): BooleanExpr; - -/** - * @beta - * Creates an expression that checks if a field's value evaluates to 'NaN' (Not a Number). - * - * ```typescript - * // Check if the result of a calculation is NaN - * isNan("value"); - * ``` - * - * @param fieldName The name of the field to check. - * @return A new {@code Expr} representing the 'isNan' check. - */ -export function isNan(fieldName: string): BooleanExpr; -export function isNan(value: Expr | string): BooleanExpr { - return fieldOrExpression(value).isNan(); -} - /** * @beta * Creates an expression that reverses a string. @@ -4482,9 +4820,9 @@ export function isNan(value: Expr | string): BooleanExpr { * ``` * * @param stringExpression An expression evaluating to a string value, which will be reversed. - * @return A new {@code Expr} representing the reversed string. + * @return A new {@code Expression} representing the reversed string. */ -export function reverse(stringExpression: Expr): FunctionExpr; +export function reverse(stringExpression: Expression): FunctionExpression; /** * @beta @@ -4496,10 +4834,10 @@ export function reverse(stringExpression: Expr): FunctionExpr; * ``` * * @param field The name of the field representing the string to reverse. - * @return A new {@code Expr} representing the reversed string. + * @return A new {@code Expression} representing the reversed string. */ -export function reverse(field: string): FunctionExpr; -export function reverse(expr: Expr | string): FunctionExpr { +export function reverse(field: string): FunctionExpression; +export function reverse(expr: Expression | string): FunctionExpression { return fieldOrExpression(expr).reverse(); } @@ -4513,9 +4851,9 @@ export function reverse(expr: Expr | string): FunctionExpr { * ``` * * @param fieldName The name of the field to reverse. - * @return A new {@code Expr} representing the reversed array. + * @return A new {@code Expression} representing the reversed array. */ -export function arrayReverse(fieldName: string): FunctionExpr; +export function arrayReverse(fieldName: string): FunctionExpression; /** * @beta @@ -4527,10 +4865,10 @@ export function arrayReverse(fieldName: string): FunctionExpr; * ``` * * @param arrayExpression An expression evaluating to an array value, which will be reversed. - * @return A new {@code Expr} representing the reversed array. + * @return A new {@code Expression} representing the reversed array. */ -export function arrayReverse(arrayExpression: Expr): FunctionExpr; -export function arrayReverse(expr: Expr | string): FunctionExpr { +export function arrayReverse(arrayExpression: Expression): FunctionExpression; +export function arrayReverse(expr: Expression | string): FunctionExpression { return fieldOrExpression(expr).arrayReverse(); } @@ -4544,9 +4882,9 @@ export function arrayReverse(expr: Expr | string): FunctionExpr { * ``` * * @param expr The expression representing the string. - * @return A new {@code Expr} representing the length of the string in bytes. + * @return A new {@code Expression} representing the length of the string in bytes. */ -export function byteLength(expr: Expr): FunctionExpr; +export function byteLength(expr: Expression): FunctionExpression; /** * @beta @@ -4558,10 +4896,10 @@ export function byteLength(expr: Expr): FunctionExpr; * ``` * * @param fieldName The name of the field containing the string. - * @return A new {@code Expr} representing the length of the string in bytes. + * @return A new {@code Expression} representing the length of the string in bytes. */ -export function byteLength(fieldName: string): FunctionExpr; -export function byteLength(expr: Expr | string): FunctionExpr { +export function byteLength(fieldName: string): FunctionExpression; +export function byteLength(expr: Expression | string): FunctionExpression { const normalizedExpr = fieldOrExpression(expr); return normalizedExpr.byteLength(); } @@ -4575,9 +4913,9 @@ export function byteLength(expr: Expr | string): FunctionExpr { * exp(constant(2)); * ``` * - * @return A new {@code Expr} representing the exp of the numeric value. + * @return A new {@code Expression} representing the exp of the numeric value. */ -export function exp(expression: Expr): FunctionExpr; +export function exp(expression: Expression): FunctionExpression; /** * @beta @@ -4588,11 +4926,13 @@ export function exp(expression: Expr): FunctionExpr; * exp('value'); * ``` * - * @return A new {@code Expr} representing the exp of the numeric value. + * @return A new {@code Expression} representing the exp of the numeric value. */ -export function exp(fieldName: string): FunctionExpr; +export function exp(fieldName: string): FunctionExpression; -export function exp(expressionOrFieldName: Expr | string): FunctionExpr { +export function exp( + expressionOrFieldName: Expression | string +): FunctionExpression { return fieldOrExpression(expressionOrFieldName).exp(); } @@ -4606,9 +4946,9 @@ export function exp(expressionOrFieldName: Expr | string): FunctionExpr { * ``` * * @param fieldName The name of the field to compute the ceiling of. - * @return A new {@code Expr} representing the ceiling of the numeric value. + * @return A new {@code Expression} representing the ceiling of the numeric value. */ -export function ceil(fieldName: string): FunctionExpr; +export function ceil(fieldName: string): FunctionExpression; /** * @beta @@ -4620,10 +4960,10 @@ export function ceil(fieldName: string): FunctionExpr; * ``` * * @param expression An expression evaluating to a numeric value, which the ceiling will be computed for. - * @return A new {@code Expr} representing the ceiling of the numeric value. + * @return A new {@code Expression} representing the ceiling of the numeric value. */ -export function ceil(expression: Expr): FunctionExpr; -export function ceil(expr: Expr | string): FunctionExpr { +export function ceil(expression: Expression): FunctionExpression; +export function ceil(expr: Expression | string): FunctionExpression { return fieldOrExpression(expr).ceil(); } @@ -4632,19 +4972,19 @@ export function ceil(expr: Expr | string): FunctionExpr { * Creates an expression that computes the floor of a numeric value. * * @param expr The expression to compute the floor of. - * @return A new {@code Expr} representing the floor of the numeric value. + * @return A new {@code Expression} representing the floor of the numeric value. */ -export function floor(expr: Expr): FunctionExpr; +export function floor(expr: Expression): FunctionExpression; /** * @beta * Creates an expression that computes the floor of a numeric value. * * @param fieldName The name of the field to compute the floor of. - * @return A new {@code Expr} representing the floor of the numeric value. + * @return A new {@code Expression} representing the floor of the numeric value. */ -export function floor(fieldName: string): FunctionExpr; -export function floor(expr: Expr | string): FunctionExpr { +export function floor(fieldName: string): FunctionExpression; +export function floor(expr: Expression | string): FunctionExpression { return fieldOrExpression(expr).floor(); } @@ -4655,7 +4995,7 @@ export function floor(expr: Expr | string): FunctionExpr { * @param expr The expression or field to count distinct values of. * @return A new `AggregateFunction` representing the 'count_distinct' aggregation. */ -export function countDistinct(expr: Expr | string): AggregateFunction { +export function countDistinct(expr: Expression | string): AggregateFunction { return fieldOrExpression(expr).countDistinct(); } @@ -4669,9 +5009,9 @@ export function countDistinct(expr: Expr | string): AggregateFunction { * ``` * * @param fieldName The name of the field containing the string. - * @return A new {@code Expr} representing the length of the string. + * @return A new {@code Expression} representing the length of the string. */ -export function charLength(fieldName: string): FunctionExpr; +export function charLength(fieldName: string): FunctionExpression; /** * @beta @@ -4683,10 +5023,10 @@ export function charLength(fieldName: string): FunctionExpr; * ``` * * @param stringExpression The expression representing the string to calculate the length of. - * @return A new {@code Expr} representing the length of the string. + * @return A new {@code Expression} representing the length of the string. */ -export function charLength(stringExpression: Expr): FunctionExpr; -export function charLength(value: Expr | string): FunctionExpr { +export function charLength(stringExpression: Expression): FunctionExpression; +export function charLength(value: Expression | string): FunctionExpression { const valueExpr = fieldOrExpression(value); return valueExpr.charLength(); } @@ -4703,9 +5043,9 @@ export function charLength(value: Expr | string): FunctionExpr { * * @param fieldName The name of the field containing the string. * @param pattern The pattern to search for. You can use "%" as a wildcard character. - * @return A new {@code Expr} representing the 'like' comparison. + * @return A new {@code Expression} representing the 'like' comparison. */ -export function like(fieldName: string, pattern: string): BooleanExpr; +export function like(fieldName: string, pattern: string): BooleanExpression; /** * @beta @@ -4719,9 +5059,9 @@ export function like(fieldName: string, pattern: string): BooleanExpr; * * @param fieldName The name of the field containing the string. * @param pattern The pattern to search for. You can use "%" as a wildcard character. - * @return A new {@code Expr} representing the 'like' comparison. + * @return A new {@code Expression} representing the 'like' comparison. */ -export function like(fieldName: string, pattern: Expr): BooleanExpr; +export function like(fieldName: string, pattern: Expression): BooleanExpression; /** * @beta @@ -4734,9 +5074,12 @@ export function like(fieldName: string, pattern: Expr): BooleanExpr; * * @param stringExpression The expression representing the string to perform the comparison on. * @param pattern The pattern to search for. You can use "%" as a wildcard character. - * @return A new {@code Expr} representing the 'like' comparison. + * @return A new {@code Expression} representing the 'like' comparison. */ -export function like(stringExpression: Expr, pattern: string): BooleanExpr; +export function like( + stringExpression: Expression, + pattern: string +): BooleanExpression; /** * @beta @@ -4749,13 +5092,16 @@ export function like(stringExpression: Expr, pattern: string): BooleanExpr; * * @param stringExpression The expression representing the string to perform the comparison on. * @param pattern The pattern to search for. You can use "%" as a wildcard character. - * @return A new {@code Expr} representing the 'like' comparison. + * @return A new {@code Expression} representing the 'like' comparison. */ -export function like(stringExpression: Expr, pattern: Expr): BooleanExpr; export function like( - left: Expr | string, - pattern: Expr | string -): FunctionExpr { + stringExpression: Expression, + pattern: Expression +): BooleanExpression; +export function like( + left: Expression | string, + pattern: Expression | string +): FunctionExpression { const leftExpr = fieldOrExpression(left); const patternExpr = valueToDefaultExpr(pattern); return leftExpr.like(patternExpr); @@ -4773,9 +5119,12 @@ export function like( * * @param fieldName The name of the field containing the string. * @param pattern The regular expression to use for the search. - * @return A new {@code Expr} representing the 'contains' comparison. + * @return A new {@code Expression} representing the 'contains' comparison. */ -export function regexContains(fieldName: string, pattern: string): BooleanExpr; +export function regexContains( + fieldName: string, + pattern: string +): BooleanExpression; /** * @beta @@ -4789,9 +5138,12 @@ export function regexContains(fieldName: string, pattern: string): BooleanExpr; * * @param fieldName The name of the field containing the string. * @param pattern The regular expression to use for the search. - * @return A new {@code Expr} representing the 'contains' comparison. + * @return A new {@code Expression} representing the 'contains' comparison. */ -export function regexContains(fieldName: string, pattern: Expr): BooleanExpr; +export function regexContains( + fieldName: string, + pattern: Expression +): BooleanExpression; /** * @beta @@ -4805,12 +5157,12 @@ export function regexContains(fieldName: string, pattern: Expr): BooleanExpr; * * @param stringExpression The expression representing the string to perform the comparison on. * @param pattern The regular expression to use for the search. - * @return A new {@code Expr} representing the 'contains' comparison. + * @return A new {@code Expression} representing the 'contains' comparison. */ export function regexContains( - stringExpression: Expr, + stringExpression: Expression, pattern: string -): BooleanExpr; +): BooleanExpression; /** * @beta @@ -4824,16 +5176,16 @@ export function regexContains( * * @param stringExpression The expression representing the string to perform the comparison on. * @param pattern The regular expression to use for the search. - * @return A new {@code Expr} representing the 'contains' comparison. + * @return A new {@code Expression} representing the 'contains' comparison. */ export function regexContains( - stringExpression: Expr, - pattern: Expr -): BooleanExpr; + stringExpression: Expression, + pattern: Expression +): BooleanExpression; export function regexContains( - left: Expr | string, - pattern: Expr | string -): BooleanExpr { + left: Expression | string, + pattern: Expression | string +): BooleanExpression { const leftExpr = fieldOrExpression(left); const patternExpr = valueToDefaultExpr(pattern); return leftExpr.regexContains(patternExpr); @@ -4850,9 +5202,12 @@ export function regexContains( * * @param fieldName The name of the field containing the string. * @param pattern The regular expression to use for the match. - * @return A new {@code Expr} representing the regular expression match. + * @return A new {@code Expression} representing the regular expression match. */ -export function regexMatch(fieldName: string, pattern: string): BooleanExpr; +export function regexMatch( + fieldName: string, + pattern: string +): BooleanExpression; /** * @beta @@ -4865,9 +5220,12 @@ export function regexMatch(fieldName: string, pattern: string): BooleanExpr; * * @param fieldName The name of the field containing the string. * @param pattern The regular expression to use for the match. - * @return A new {@code Expr} representing the regular expression match. + * @return A new {@code Expression} representing the regular expression match. */ -export function regexMatch(fieldName: string, pattern: Expr): BooleanExpr; +export function regexMatch( + fieldName: string, + pattern: Expression +): BooleanExpression; /** * @beta @@ -4881,12 +5239,12 @@ export function regexMatch(fieldName: string, pattern: Expr): BooleanExpr; * * @param stringExpression The expression representing the string to match against. * @param pattern The regular expression to use for the match. - * @return A new {@code Expr} representing the regular expression match. + * @return A new {@code Expression} representing the regular expression match. */ export function regexMatch( - stringExpression: Expr, + stringExpression: Expression, pattern: string -): BooleanExpr; +): BooleanExpression; /** * @beta @@ -4900,13 +5258,16 @@ export function regexMatch( * * @param stringExpression The expression representing the string to match against. * @param pattern The regular expression to use for the match. - * @return A new {@code Expr} representing the regular expression match. + * @return A new {@code Expression} representing the regular expression match. */ -export function regexMatch(stringExpression: Expr, pattern: Expr): BooleanExpr; export function regexMatch( - left: Expr | string, - pattern: Expr | string -): BooleanExpr { + stringExpression: Expression, + pattern: Expression +): BooleanExpression; +export function regexMatch( + left: Expression | string, + pattern: Expression | string +): BooleanExpression { const leftExpr = fieldOrExpression(left); const patternExpr = valueToDefaultExpr(pattern); return leftExpr.regexMatch(patternExpr); @@ -4918,14 +5279,17 @@ export function regexMatch( * * ```typescript * // Check if the 'description' field contains "example". - * strContains("description", "example"); + * stringContains("description", "example"); * ``` * * @param fieldName The name of the field containing the string. * @param substring The substring to search for. - * @return A new {@code Expr} representing the 'contains' comparison. + * @return A new {@code Expression} representing the 'contains' comparison. */ -export function strContains(fieldName: string, substring: string): BooleanExpr; +export function stringContains( + fieldName: string, + substring: string +): BooleanExpression; /** * @beta @@ -4933,14 +5297,17 @@ export function strContains(fieldName: string, substring: string): BooleanExpr; * * ```typescript * // Check if the 'description' field contains the value of the 'keyword' field. - * strContains("description", field("keyword")); + * stringContains("description", field("keyword")); * ``` * * @param fieldName The name of the field containing the string. * @param substring The expression representing the substring to search for. - * @return A new {@code Expr} representing the 'contains' comparison. + * @return A new {@code Expression} representing the 'contains' comparison. */ -export function strContains(fieldName: string, substring: Expr): BooleanExpr; +export function stringContains( + fieldName: string, + substring: Expression +): BooleanExpression; /** * @beta @@ -4948,17 +5315,17 @@ export function strContains(fieldName: string, substring: Expr): BooleanExpr; * * ```typescript * // Check if the 'description' field contains "example". - * strContains(field("description"), "example"); + * stringContains(field("description"), "example"); * ``` * * @param stringExpression The expression representing the string to perform the comparison on. * @param substring The substring to search for. - * @return A new {@code Expr} representing the 'contains' comparison. + * @return A new {@code Expression} representing the 'contains' comparison. */ -export function strContains( - stringExpression: Expr, +export function stringContains( + stringExpression: Expression, substring: string -): BooleanExpr; +): BooleanExpression; /** * @beta @@ -4966,24 +5333,24 @@ export function strContains( * * ```typescript * // Check if the 'description' field contains the value of the 'keyword' field. - * strContains(field("description"), field("keyword")); + * stringContains(field("description"), field("keyword")); * ``` * * @param stringExpression The expression representing the string to perform the comparison on. * @param substring The expression representing the substring to search for. - * @return A new {@code Expr} representing the 'contains' comparison. - */ -export function strContains( - stringExpression: Expr, - substring: Expr -): BooleanExpr; -export function strContains( - left: Expr | string, - substring: Expr | string -): BooleanExpr { + * @return A new {@code Expression} representing the 'contains' comparison. + */ +export function stringContains( + stringExpression: Expression, + substring: Expression +): BooleanExpression; +export function stringContains( + left: Expression | string, + substring: Expression | string +): BooleanExpression { const leftExpr = fieldOrExpression(left); const substringExpr = valueToDefaultExpr(substring); - return leftExpr.strContains(substringExpr); + return leftExpr.stringContains(substringExpr); } /** @@ -4997,9 +5364,12 @@ export function strContains( * * @param fieldName The field name to check. * @param prefix The prefix to check for. - * @return A new {@code Expr} representing the 'starts with' comparison. + * @return A new {@code Expression} representing the 'starts with' comparison. */ -export function startsWith(fieldName: string, prefix: string): BooleanExpr; +export function startsWith( + fieldName: string, + prefix: string +): BooleanExpression; /** * @beta @@ -5012,9 +5382,12 @@ export function startsWith(fieldName: string, prefix: string): BooleanExpr; * * @param fieldName The field name to check. * @param prefix The expression representing the prefix. - * @return A new {@code Expr} representing the 'starts with' comparison. + * @return A new {@code Expression} representing the 'starts with' comparison. */ -export function startsWith(fieldName: string, prefix: Expr): BooleanExpr; +export function startsWith( + fieldName: string, + prefix: Expression +): BooleanExpression; /** * @beta @@ -5027,9 +5400,12 @@ export function startsWith(fieldName: string, prefix: Expr): BooleanExpr; * * @param stringExpression The expression to check. * @param prefix The prefix to check for. - * @return A new {@code Expr} representing the 'starts with' comparison. + * @return A new {@code Expression} representing the 'starts with' comparison. */ -export function startsWith(stringExpression: Expr, prefix: string): BooleanExpr; +export function startsWith( + stringExpression: Expression, + prefix: string +): BooleanExpression; /** * @beta @@ -5042,13 +5418,16 @@ export function startsWith(stringExpression: Expr, prefix: string): BooleanExpr; * * @param stringExpression The expression to check. * @param prefix The prefix to check for. - * @return A new {@code Expr} representing the 'starts with' comparison. + * @return A new {@code Expression} representing the 'starts with' comparison. */ -export function startsWith(stringExpression: Expr, prefix: Expr): BooleanExpr; export function startsWith( - expr: Expr | string, - prefix: Expr | string -): BooleanExpr { + stringExpression: Expression, + prefix: Expression +): BooleanExpression; +export function startsWith( + expr: Expression | string, + prefix: Expression | string +): BooleanExpression { return fieldOrExpression(expr).startsWith(valueToDefaultExpr(prefix)); } @@ -5063,9 +5442,9 @@ export function startsWith( * * @param fieldName The field name to check. * @param suffix The postfix to check for. - * @return A new {@code Expr} representing the 'ends with' comparison. + * @return A new {@code Expression} representing the 'ends with' comparison. */ -export function endsWith(fieldName: string, suffix: string): BooleanExpr; +export function endsWith(fieldName: string, suffix: string): BooleanExpression; /** * @beta @@ -5078,9 +5457,12 @@ export function endsWith(fieldName: string, suffix: string): BooleanExpr; * * @param fieldName The field name to check. * @param suffix The expression representing the postfix. - * @return A new {@code Expr} representing the 'ends with' comparison. + * @return A new {@code Expression} representing the 'ends with' comparison. */ -export function endsWith(fieldName: string, suffix: Expr): BooleanExpr; +export function endsWith( + fieldName: string, + suffix: Expression +): BooleanExpression; /** * @beta @@ -5093,9 +5475,12 @@ export function endsWith(fieldName: string, suffix: Expr): BooleanExpr; * * @param stringExpression The expression to check. * @param suffix The postfix to check for. - * @return A new {@code Expr} representing the 'ends with' comparison. + * @return A new {@code Expression} representing the 'ends with' comparison. */ -export function endsWith(stringExpression: Expr, suffix: string): BooleanExpr; +export function endsWith( + stringExpression: Expression, + suffix: string +): BooleanExpression; /** * @beta @@ -5108,13 +5493,16 @@ export function endsWith(stringExpression: Expr, suffix: string): BooleanExpr; * * @param stringExpression The expression to check. * @param suffix The postfix to check for. - * @return A new {@code Expr} representing the 'ends with' comparison. + * @return A new {@code Expression} representing the 'ends with' comparison. */ -export function endsWith(stringExpression: Expr, suffix: Expr): BooleanExpr; export function endsWith( - expr: Expr | string, - suffix: Expr | string -): BooleanExpr { + stringExpression: Expression, + suffix: Expression +): BooleanExpression; +export function endsWith( + expr: Expression | string, + suffix: Expression | string +): BooleanExpression { return fieldOrExpression(expr).endsWith(valueToDefaultExpr(suffix)); } @@ -5128,9 +5516,9 @@ export function endsWith( * ``` * * @param fieldName The name of the field containing the string. - * @return A new {@code Expr} representing the lowercase string. + * @return A new {@code Expression} representing the lowercase string. */ -export function toLower(fieldName: string): FunctionExpr; +export function toLower(fieldName: string): FunctionExpression; /** * @beta @@ -5142,10 +5530,10 @@ export function toLower(fieldName: string): FunctionExpr; * ``` * * @param stringExpression The expression representing the string to convert to lowercase. - * @return A new {@code Expr} representing the lowercase string. + * @return A new {@code Expression} representing the lowercase string. */ -export function toLower(stringExpression: Expr): FunctionExpr; -export function toLower(expr: Expr | string): FunctionExpr { +export function toLower(stringExpression: Expression): FunctionExpression; +export function toLower(expr: Expression | string): FunctionExpression { return fieldOrExpression(expr).toLower(); } @@ -5159,9 +5547,9 @@ export function toLower(expr: Expr | string): FunctionExpr { * ``` * * @param fieldName The name of the field containing the string. - * @return A new {@code Expr} representing the uppercase string. + * @return A new {@code Expression} representing the uppercase string. */ -export function toUpper(fieldName: string): FunctionExpr; +export function toUpper(fieldName: string): FunctionExpression; /** * @beta @@ -5173,10 +5561,10 @@ export function toUpper(fieldName: string): FunctionExpr; * ``` * * @param stringExpression The expression representing the string to convert to uppercase. - * @return A new {@code Expr} representing the uppercase string. + * @return A new {@code Expression} representing the uppercase string. */ -export function toUpper(stringExpression: Expr): FunctionExpr; -export function toUpper(expr: Expr | string): FunctionExpr { +export function toUpper(stringExpression: Expression): FunctionExpression; +export function toUpper(expr: Expression | string): FunctionExpression { return fieldOrExpression(expr).toUpper(); } @@ -5190,9 +5578,9 @@ export function toUpper(expr: Expr | string): FunctionExpr { * ``` * * @param fieldName The name of the field containing the string. - * @return A new {@code Expr} representing the trimmed string. + * @return A new {@code Expression} representing the trimmed string. */ -export function trim(fieldName: string): FunctionExpr; +export function trim(fieldName: string): FunctionExpression; /** * @beta @@ -5204,10 +5592,10 @@ export function trim(fieldName: string): FunctionExpr; * ``` * * @param stringExpression The expression representing the string to trim. - * @return A new {@code Expr} representing the trimmed string. + * @return A new {@code Expression} representing the trimmed string. */ -export function trim(stringExpression: Expr): FunctionExpr; -export function trim(expr: Expr | string): FunctionExpr { +export function trim(stringExpression: Expression): FunctionExpression; +export function trim(expr: Expression | string): FunctionExpression { return fieldOrExpression(expr).trim(); } @@ -5217,19 +5605,19 @@ export function trim(expr: Expr | string): FunctionExpr { * * ```typescript * // Combine the 'firstName', " ", and 'lastName' fields into a single string - * strConcat("firstName", " ", field("lastName")); + * stringConcat("firstName", " ", field("lastName")); * ``` * * @param fieldName The field name containing the initial string value. * @param secondString An expression or string literal to concatenate. * @param otherStrings Optional additional expressions or literals (typically strings) to concatenate. - * @return A new {@code Expr} representing the concatenated string. + * @return A new {@code Expression} representing the concatenated string. */ -export function strConcat( +export function stringConcat( fieldName: string, - secondString: Expr | string, - ...otherStrings: Array -): FunctionExpr; + secondString: Expression | string, + ...otherStrings: Array +): FunctionExpression; /** * @beta @@ -5237,25 +5625,25 @@ export function strConcat( * * ```typescript * // Combine the 'firstName', " ", and 'lastName' fields into a single string - * strConcat(field("firstName"), " ", field("lastName")); + * stringConcat(field("firstName"), " ", field("lastName")); * ``` * * @param firstString The initial string expression to concatenate to. * @param secondString An expression or string literal to concatenate. * @param otherStrings Optional additional expressions or literals (typically strings) to concatenate. - * @return A new {@code Expr} representing the concatenated string. - */ -export function strConcat( - firstString: Expr, - secondString: Expr | string, - ...otherStrings: Array -): FunctionExpr; -export function strConcat( - first: string | Expr, - second: string | Expr, - ...elements: Array -): FunctionExpr { - return fieldOrExpression(first).strConcat( + * @return A new {@code Expression} representing the concatenated string. + */ +export function stringConcat( + firstString: Expression, + secondString: Expression | string, + ...otherStrings: Array +): FunctionExpression; +export function stringConcat( + first: string | Expression, + second: string | Expression, + ...elements: Array +): FunctionExpression { + return fieldOrExpression(first).stringConcat( valueToDefaultExpr(second), ...elements.map(valueToDefaultExpr) ); @@ -5272,9 +5660,9 @@ export function strConcat( * * @param fieldName The field name of the map field. * @param subField The key to access in the map. - * @return A new {@code Expr} representing the value associated with the given key in the map. + * @return A new {@code Expression} representing the value associated with the given key in the map. */ -export function mapGet(fieldName: string, subField: string): FunctionExpr; +export function mapGet(fieldName: string, subField: string): FunctionExpression; /** * @beta @@ -5287,13 +5675,16 @@ export function mapGet(fieldName: string, subField: string): FunctionExpr; * * @param mapExpression The expression representing the map. * @param subField The key to access in the map. - * @return A new {@code Expr} representing the value associated with the given key in the map. + * @return A new {@code Expression} representing the value associated with the given key in the map. */ -export function mapGet(mapExpression: Expr, subField: string): FunctionExpr; export function mapGet( - fieldOrExpr: string | Expr, + mapExpression: Expression, subField: string -): FunctionExpr { +): FunctionExpression; +export function mapGet( + fieldOrExpr: string | Expression, + subField: string +): FunctionExpression { return fieldOrExpression(fieldOrExpr).mapGet(subField); } @@ -5319,13 +5710,13 @@ export function countAll(): AggregateFunction { * * ```typescript * // Count the number of items where the price is greater than 10 - * count(field("price").gt(10)).as("expensiveItemCount"); + * count(field("price").greaterThan(10)).as("expensiveItemCount"); * ``` * * @param expression The expression to count. * @return A new {@code AggregateFunction} representing the 'count' aggregation. */ -export function count(expression: Expr): AggregateFunction; +export function count(expression: Expression): AggregateFunction; /** * @beta @@ -5340,7 +5731,7 @@ export function count(expression: Expr): AggregateFunction; * @return A new {@code AggregateFunction} representing the 'count' aggregation. */ export function count(fieldName: string): AggregateFunction; -export function count(value: Expr | string): AggregateFunction { +export function count(value: Expression | string): AggregateFunction { return fieldOrExpression(value).count(); } @@ -5357,7 +5748,7 @@ export function count(value: Expr | string): AggregateFunction { * @param expression The expression to sum up. * @return A new {@code AggregateFunction} representing the 'sum' aggregation. */ -export function sum(expression: Expr): AggregateFunction; +export function sum(expression: Expression): AggregateFunction; /** * @beta @@ -5373,7 +5764,7 @@ export function sum(expression: Expr): AggregateFunction; * @return A new {@code AggregateFunction} representing the 'sum' aggregation. */ export function sum(fieldName: string): AggregateFunction; -export function sum(value: Expr | string): AggregateFunction { +export function sum(value: Expression | string): AggregateFunction { return fieldOrExpression(value).sum(); } @@ -5384,13 +5775,13 @@ export function sum(value: Expr | string): AggregateFunction { * * ```typescript * // Calculate the average age of users - * avg(field("age")).as("averageAge"); + * average(field("age")).as("averageAge"); * ``` * * @param expression The expression representing the values to average. - * @return A new {@code AggregateFunction} representing the 'avg' aggregation. + * @return A new {@code AggregateFunction} representing the 'average' aggregation. */ -export function avg(expression: Expr): AggregateFunction; +export function average(expression: Expression): AggregateFunction; /** * @beta @@ -5399,15 +5790,15 @@ export function avg(expression: Expr): AggregateFunction; * * ```typescript * // Calculate the average age of users - * avg("age").as("averageAge"); + * average("age").as("averageAge"); * ``` * * @param fieldName The name of the field containing numeric values to average. - * @return A new {@code AggregateFunction} representing the 'avg' aggregation. + * @return A new {@code AggregateFunction} representing the 'average' aggregation. */ -export function avg(fieldName: string): AggregateFunction; -export function avg(value: Expr | string): AggregateFunction { - return fieldOrExpression(value).avg(); +export function average(fieldName: string): AggregateFunction; +export function average(value: Expression | string): AggregateFunction { + return fieldOrExpression(value).average(); } /** @@ -5423,7 +5814,7 @@ export function avg(value: Expr | string): AggregateFunction { * @param expression The expression to find the minimum value of. * @return A new {@code AggregateFunction} representing the 'min' aggregation. */ -export function minimum(expression: Expr): AggregateFunction; +export function minimum(expression: Expression): AggregateFunction; /** * @beta @@ -5438,7 +5829,7 @@ export function minimum(expression: Expr): AggregateFunction; * @return A new {@code AggregateFunction} representing the 'min' aggregation. */ export function minimum(fieldName: string): AggregateFunction; -export function minimum(value: Expr | string): AggregateFunction { +export function minimum(value: Expression | string): AggregateFunction { return fieldOrExpression(value).minimum(); } @@ -5455,7 +5846,7 @@ export function minimum(value: Expr | string): AggregateFunction { * @param expression The expression to find the maximum value of. * @return A new {@code AggregateFunction} representing the 'max' aggregation. */ -export function maximum(expression: Expr): AggregateFunction; +export function maximum(expression: Expression): AggregateFunction; /** * @beta @@ -5470,7 +5861,7 @@ export function maximum(expression: Expr): AggregateFunction; * @return A new {@code AggregateFunction} representing the 'max' aggregation. */ export function maximum(fieldName: string): AggregateFunction; -export function maximum(value: Expr | string): AggregateFunction { +export function maximum(value: Expression | string): AggregateFunction { return fieldOrExpression(value).maximum(); } @@ -5485,12 +5876,12 @@ export function maximum(value: Expr | string): AggregateFunction { * * @param fieldName The name of the field containing the first vector. * @param vector The other vector (as an array of doubles) or {@link VectorValue} to compare against. - * @return A new {@code Expr} representing the Cosine distance between the two vectors. + * @return A new {@code Expression} representing the Cosine distance between the two vectors. */ export function cosineDistance( fieldName: string, vector: number[] | VectorValue -): FunctionExpr; +): FunctionExpression; /** * @beta @@ -5502,13 +5893,13 @@ export function cosineDistance( * ``` * * @param fieldName The name of the field containing the first vector. - * @param vectorExpression The other vector (represented as an Expr) to compare against. - * @return A new {@code Expr} representing the cosine distance between the two vectors. + * @param vectorExpression The other vector (represented as an Expression) to compare against. + * @return A new {@code Expression} representing the cosine distance between the two vectors. */ export function cosineDistance( fieldName: string, - vectorExpression: Expr -): FunctionExpr; + vectorExpression: Expression +): FunctionExpression; /** * @beta @@ -5519,14 +5910,14 @@ export function cosineDistance( * cosineDistance(field("location"), [37.7749, -122.4194]); * ``` * - * @param vectorExpression The first vector (represented as an Expr) to compare against. + * @param vectorExpression The first vector (represented as an Expression) to compare against. * @param vector The other vector (as an array of doubles or VectorValue) to compare against. - * @return A new {@code Expr} representing the cosine distance between the two vectors. + * @return A new {@code Expression} representing the cosine distance between the two vectors. */ export function cosineDistance( - vectorExpression: Expr, + vectorExpression: Expression, vector: number[] | VectorValue -): FunctionExpr; +): FunctionExpression; /** * @beta @@ -5537,18 +5928,18 @@ export function cosineDistance( * cosineDistance(field("userVector"), field("itemVector")); * ``` * - * @param vectorExpression The first vector (represented as an Expr) to compare against. - * @param otherVectorExpression The other vector (represented as an Expr) to compare against. - * @return A new {@code Expr} representing the cosine distance between the two vectors. + * @param vectorExpression The first vector (represented as an Expression) to compare against. + * @param otherVectorExpression The other vector (represented as an Expression) to compare against. + * @return A new {@code Expression} representing the cosine distance between the two vectors. */ export function cosineDistance( - vectorExpression: Expr, - otherVectorExpression: Expr -): FunctionExpr; + vectorExpression: Expression, + otherVectorExpression: Expression +): FunctionExpression; export function cosineDistance( - expr: Expr | string, - other: Expr | number[] | firestore.VectorValue -): FunctionExpr { + expr: Expression | string, + other: Expression | number[] | firestore.VectorValue +): FunctionExpression { const expr1 = fieldOrExpression(expr); const expr2 = vectorToExpr(other); return expr1.cosineDistance(expr2); @@ -5565,12 +5956,12 @@ export function cosineDistance( * * @param fieldName The name of the field containing the first vector. * @param vector The other vector (as an array of doubles or VectorValue) to calculate with. - * @return A new {@code Expr} representing the dot product between the two vectors. + * @return A new {@code Expression} representing the dot product between the two vectors. */ export function dotProduct( fieldName: string, vector: number[] | VectorValue -): FunctionExpr; +): FunctionExpression; /** * @beta @@ -5582,13 +5973,13 @@ export function dotProduct( * ``` * * @param fieldName The name of the field containing the first vector. - * @param vectorExpression The other vector (represented as an Expr) to calculate with. - * @return A new {@code Expr} representing the dot product between the two vectors. + * @param vectorExpression The other vector (represented as an Expression) to calculate with. + * @return A new {@code Expression} representing the dot product between the two vectors. */ export function dotProduct( fieldName: string, - vectorExpression: Expr -): FunctionExpr; + vectorExpression: Expression +): FunctionExpression; /** * @beta @@ -5599,14 +5990,14 @@ export function dotProduct( * dotProduct(field("features"), [0.5, 0.8, 0.2]); * ``` * - * @param vectorExpression The first vector (represented as an Expr) to calculate with. + * @param vectorExpression The first vector (represented as an Expression) to calculate with. * @param vector The other vector (as an array of doubles or VectorValue) to calculate with. - * @return A new {@code Expr} representing the dot product between the two vectors. + * @return A new {@code Expression} representing the dot product between the two vectors. */ export function dotProduct( - vectorExpression: Expr, + vectorExpression: Expression, vector: number[] | VectorValue -): FunctionExpr; +): FunctionExpression; /** * @beta @@ -5617,18 +6008,18 @@ export function dotProduct( * dotProduct(field("docVector1"), field("docVector2")); * ``` * - * @param vectorExpression The first vector (represented as an Expr) to calculate with. - * @param otherVectorExpression The other vector (represented as an Expr) to calculate with. - * @return A new {@code Expr} representing the dot product between the two vectors. + * @param vectorExpression The first vector (represented as an Expression) to calculate with. + * @param otherVectorExpression The other vector (represented as an Expression) to calculate with. + * @return A new {@code Expression} representing the dot product between the two vectors. */ export function dotProduct( - vectorExpression: Expr, - otherVectorExpression: Expr -): FunctionExpr; + vectorExpression: Expression, + otherVectorExpression: Expression +): FunctionExpression; export function dotProduct( - expr: Expr | string, - other: Expr | number[] | VectorValue -): FunctionExpr { + expr: Expression | string, + other: Expression | number[] | VectorValue +): FunctionExpression { const expr1 = fieldOrExpression(expr); const expr2 = vectorToExpr(other); return expr1.dotProduct(expr2); @@ -5645,12 +6036,12 @@ export function dotProduct( * * @param fieldName The name of the field containing the first vector. * @param vector The other vector (as an array of doubles or VectorValue) to compare against. - * @return A new {@code Expr} representing the Euclidean distance between the two vectors. + * @return A new {@code Expression} representing the Euclidean distance between the two vectors. */ export function euclideanDistance( fieldName: string, vector: number[] | VectorValue -): FunctionExpr; +): FunctionExpression; /** * @beta @@ -5662,13 +6053,13 @@ export function euclideanDistance( * ``` * * @param fieldName The name of the field containing the first vector. - * @param vectorExpression The other vector (represented as an Expr) to compare against. - * @return A new {@code Expr} representing the Euclidean distance between the two vectors. + * @param vectorExpression The other vector (represented as an Expression) to compare against. + * @return A new {@code Expression} representing the Euclidean distance between the two vectors. */ export function euclideanDistance( fieldName: string, - vectorExpression: Expr -): FunctionExpr; + vectorExpression: Expression +): FunctionExpression; /** * @beta @@ -5680,14 +6071,14 @@ export function euclideanDistance( * euclideanDistance(field("location"), [37.7749, -122.4194]); * ``` * - * @param vectorExpression The first vector (represented as an Expr) to compare against. + * @param vectorExpression The first vector (represented as an Expression) to compare against. * @param vector The other vector (as an array of doubles or VectorValue) to compare against. - * @return A new {@code Expr} representing the Euclidean distance between the two vectors. + * @return A new {@code Expression} representing the Euclidean distance between the two vectors. */ export function euclideanDistance( - vectorExpression: Expr, + vectorExpression: Expression, vector: number[] | VectorValue -): FunctionExpr; +): FunctionExpression; /** * @beta @@ -5698,18 +6089,18 @@ export function euclideanDistance( * euclideanDistance(field("pointA"), field("pointB")); * ``` * - * @param vectorExpression The first vector (represented as an Expr) to compare against. - * @param otherVectorExpression The other vector (represented as an Expr) to compare against. - * @return A new {@code Expr} representing the Euclidean distance between the two vectors. + * @param vectorExpression The first vector (represented as an Expression) to compare against. + * @param otherVectorExpression The other vector (represented as an Expression) to compare against. + * @return A new {@code Expression} representing the Euclidean distance between the two vectors. */ export function euclideanDistance( - vectorExpression: Expr, - otherVectorExpression: Expr -): FunctionExpr; + vectorExpression: Expression, + otherVectorExpression: Expression +): FunctionExpression; export function euclideanDistance( - expr: Expr | string, - other: Expr | number[] | VectorValue -): FunctionExpr { + expr: Expression | string, + other: Expression | number[] | VectorValue +): FunctionExpression { const expr1 = fieldOrExpression(expr); const expr2 = vectorToExpr(other); return expr1.euclideanDistance(expr2); @@ -5725,9 +6116,9 @@ export function euclideanDistance( * ``` * * @param vectorExpression The expression representing the Firestore Vector. - * @return A new {@code Expr} representing the length of the array. + * @return A new {@code Expression} representing the length of the array. */ -export function vectorLength(vectorExpression: Expr): FunctionExpr; +export function vectorLength(vectorExpression: Expression): FunctionExpression; /** * @beta @@ -5739,10 +6130,10 @@ export function vectorLength(vectorExpression: Expr): FunctionExpr; * ``` * * @param fieldName The name of the field representing the Firestore Vector. - * @return A new {@code Expr} representing the length of the array. + * @return A new {@code Expression} representing the length of the array. */ -export function vectorLength(fieldName: string): FunctionExpr; -export function vectorLength(expr: Expr | string): FunctionExpr { +export function vectorLength(fieldName: string): FunctionExpression; +export function vectorLength(expr: Expression | string): FunctionExpression { return fieldOrExpression(expr).vectorLength(); } @@ -5757,9 +6148,9 @@ export function vectorLength(expr: Expr | string): FunctionExpr { * ``` * * @param expr The expression representing the number of microseconds since epoch. - * @return A new {@code Expr} representing the timestamp. + * @return A new {@code Expression} representing the timestamp. */ -export function unixMicrosToTimestamp(expr: Expr): FunctionExpr; +export function unixMicrosToTimestamp(expr: Expression): FunctionExpression; /** * @beta @@ -5772,10 +6163,12 @@ export function unixMicrosToTimestamp(expr: Expr): FunctionExpr; * ``` * * @param fieldName The name of the field representing the number of microseconds since epoch. - * @return A new {@code Expr} representing the timestamp. + * @return A new {@code Expression} representing the timestamp. */ -export function unixMicrosToTimestamp(fieldName: string): FunctionExpr; -export function unixMicrosToTimestamp(expr: Expr | string): FunctionExpr { +export function unixMicrosToTimestamp(fieldName: string): FunctionExpression; +export function unixMicrosToTimestamp( + expr: Expression | string +): FunctionExpression { return fieldOrExpression(expr).unixMicrosToTimestamp(); } @@ -5789,9 +6182,9 @@ export function unixMicrosToTimestamp(expr: Expr | string): FunctionExpr { * ``` * * @param expr The expression representing the timestamp. - * @return A new {@code Expr} representing the number of microseconds since epoch. + * @return A new {@code Expression} representing the number of microseconds since epoch. */ -export function timestampToUnixMicros(expr: Expr): FunctionExpr; +export function timestampToUnixMicros(expr: Expression): FunctionExpression; /** * @beta @@ -5803,10 +6196,12 @@ export function timestampToUnixMicros(expr: Expr): FunctionExpr; * ``` * * @param fieldName The name of the field representing the timestamp. - * @return A new {@code Expr} representing the number of microseconds since epoch. + * @return A new {@code Expression} representing the number of microseconds since epoch. */ -export function timestampToUnixMicros(fieldName: string): FunctionExpr; -export function timestampToUnixMicros(expr: Expr | string): FunctionExpr { +export function timestampToUnixMicros(fieldName: string): FunctionExpression; +export function timestampToUnixMicros( + expr: Expression | string +): FunctionExpression { return fieldOrExpression(expr).timestampToUnixMicros(); } @@ -5821,9 +6216,9 @@ export function timestampToUnixMicros(expr: Expr | string): FunctionExpr { * ``` * * @param expr The expression representing the number of milliseconds since epoch. - * @return A new {@code Expr} representing the timestamp. + * @return A new {@code Expression} representing the timestamp. */ -export function unixMillisToTimestamp(expr: Expr): FunctionExpr; +export function unixMillisToTimestamp(expr: Expression): FunctionExpression; /** * @beta @@ -5836,10 +6231,12 @@ export function unixMillisToTimestamp(expr: Expr): FunctionExpr; * ``` * * @param fieldName The name of the field representing the number of milliseconds since epoch. - * @return A new {@code Expr} representing the timestamp. + * @return A new {@code Expression} representing the timestamp. */ -export function unixMillisToTimestamp(fieldName: string): FunctionExpr; -export function unixMillisToTimestamp(expr: Expr | string): FunctionExpr { +export function unixMillisToTimestamp(fieldName: string): FunctionExpression; +export function unixMillisToTimestamp( + expr: Expression | string +): FunctionExpression { const normalizedExpr = fieldOrExpression(expr); return normalizedExpr.unixMillisToTimestamp(); } @@ -5854,9 +6251,9 @@ export function unixMillisToTimestamp(expr: Expr | string): FunctionExpr { * ``` * * @param expr The expression representing the timestamp. - * @return A new {@code Expr} representing the number of milliseconds since epoch. + * @return A new {@code Expression} representing the number of milliseconds since epoch. */ -export function timestampToUnixMillis(expr: Expr): FunctionExpr; +export function timestampToUnixMillis(expr: Expression): FunctionExpression; /** * @beta @@ -5868,10 +6265,12 @@ export function timestampToUnixMillis(expr: Expr): FunctionExpr; * ``` * * @param fieldName The name of the field representing the timestamp. - * @return A new {@code Expr} representing the number of milliseconds since epoch. + * @return A new {@code Expression} representing the number of milliseconds since epoch. */ -export function timestampToUnixMillis(fieldName: string): FunctionExpr; -export function timestampToUnixMillis(expr: Expr | string): FunctionExpr { +export function timestampToUnixMillis(fieldName: string): FunctionExpression; +export function timestampToUnixMillis( + expr: Expression | string +): FunctionExpression { const normalizedExpr = fieldOrExpression(expr); return normalizedExpr.timestampToUnixMillis(); } @@ -5887,9 +6286,9 @@ export function timestampToUnixMillis(expr: Expr | string): FunctionExpr { * ``` * * @param expr The expression representing the number of seconds since epoch. - * @return A new {@code Expr} representing the timestamp. + * @return A new {@code Expression} representing the timestamp. */ -export function unixSecondsToTimestamp(expr: Expr): FunctionExpr; +export function unixSecondsToTimestamp(expr: Expression): FunctionExpression; /** * @beta @@ -5902,10 +6301,12 @@ export function unixSecondsToTimestamp(expr: Expr): FunctionExpr; * ``` * * @param fieldName The name of the field representing the number of seconds since epoch. - * @return A new {@code Expr} representing the timestamp. + * @return A new {@code Expression} representing the timestamp. */ -export function unixSecondsToTimestamp(fieldName: string): FunctionExpr; -export function unixSecondsToTimestamp(expr: Expr | string): FunctionExpr { +export function unixSecondsToTimestamp(fieldName: string): FunctionExpression; +export function unixSecondsToTimestamp( + expr: Expression | string +): FunctionExpression { const normalizedExpr = fieldOrExpression(expr); return normalizedExpr.unixSecondsToTimestamp(); } @@ -5920,9 +6321,9 @@ export function unixSecondsToTimestamp(expr: Expr | string): FunctionExpr { * ``` * * @param expr The expression representing the timestamp. - * @return A new {@code Expr} representing the number of seconds since epoch. + * @return A new {@code Expression} representing the number of seconds since epoch. */ -export function timestampToUnixSeconds(expr: Expr): FunctionExpr; +export function timestampToUnixSeconds(expr: Expression): FunctionExpression; /** * @beta @@ -5934,10 +6335,12 @@ export function timestampToUnixSeconds(expr: Expr): FunctionExpr; * ``` * * @param fieldName The name of the field representing the timestamp. - * @return A new {@code Expr} representing the number of seconds since epoch. + * @return A new {@code Expression} representing the number of seconds since epoch. */ -export function timestampToUnixSeconds(fieldName: string): FunctionExpr; -export function timestampToUnixSeconds(expr: Expr | string): FunctionExpr { +export function timestampToUnixSeconds(fieldName: string): FunctionExpression; +export function timestampToUnixSeconds( + expr: Expression | string +): FunctionExpression { const normalizedExpr = fieldOrExpression(expr); return normalizedExpr.timestampToUnixSeconds(); } @@ -5954,13 +6357,13 @@ export function timestampToUnixSeconds(expr: Expr | string): FunctionExpr { * @param timestamp The expression representing the timestamp. * @param unit The expression evaluates to unit of time, must be one of 'microsecond', 'millisecond', 'second', 'minute', 'hour', 'day'. * @param amount The expression evaluates to amount of the unit. - * @return A new {@code Expr} representing the resulting timestamp. + * @return A new {@code Expression} representing the resulting timestamp. */ export function timestampAdd( - timestamp: Expr, - unit: Expr, - amount: Expr -): FunctionExpr; + timestamp: Expression, + unit: Expression, + amount: Expression +): FunctionExpression; /** * @beta @@ -5974,13 +6377,13 @@ export function timestampAdd( * @param timestamp The expression representing the timestamp. * @param unit The unit of time to add (e.g., "day", "hour"). * @param amount The amount of time to add. - * @return A new {@code Expr} representing the resulting timestamp. + * @return A new {@code Expression} representing the resulting timestamp. */ export function timestampAdd( - timestamp: Expr, + timestamp: Expression, unit: 'microsecond' | 'millisecond' | 'second' | 'minute' | 'hour' | 'day', amount: number -): FunctionExpr; +): FunctionExpression; /** * @beta @@ -5994,25 +6397,25 @@ export function timestampAdd( * @param fieldName The name of the field representing the timestamp. * @param unit The unit of time to add (e.g., "day", "hour"). * @param amount The amount of time to add. - * @return A new {@code Expr} representing the resulting timestamp. + * @return A new {@code Expression} representing the resulting timestamp. */ export function timestampAdd( fieldName: string, unit: 'microsecond' | 'millisecond' | 'second' | 'minute' | 'hour' | 'day', amount: number -): FunctionExpr; +): FunctionExpression; export function timestampAdd( - timestamp: Expr | string, + timestamp: Expression | string, unit: - | Expr + | Expression | 'microsecond' | 'millisecond' | 'second' | 'minute' | 'hour' | 'day', - amount: Expr | number -): FunctionExpr { + amount: Expression | number +): FunctionExpression { const normalizedTimestamp = fieldOrExpression(timestamp); const normalizedUnit = valueToDefaultExpr(unit); const normalizedAmount = valueToDefaultExpr(amount); @@ -6025,19 +6428,19 @@ export function timestampAdd( * * ```typescript * // Subtract some duration determined by field 'unit' and 'amount' from the 'timestamp' field. - * timestampSub(field("timestamp"), field("unit"), field("amount")); + * timestampSubtract(field("timestamp"), field("unit"), field("amount")); * ``` * * @param timestamp The expression representing the timestamp. * @param unit The expression evaluates to unit of time, must be one of 'microsecond', 'millisecond', 'second', 'minute', 'hour', 'day'. * @param amount The expression evaluates to amount of the unit. - * @return A new {@code Expr} representing the resulting timestamp. + * @return A new {@code Expression} representing the resulting timestamp. */ -export function timestampSub( - timestamp: Expr, - unit: Expr, - amount: Expr -): FunctionExpr; +export function timestampSubtract( + timestamp: Expression, + unit: Expression, + amount: Expression +): FunctionExpression; /** * @beta @@ -6045,19 +6448,19 @@ export function timestampSub( * * ```typescript * // Subtract 1 day from the 'timestamp' field. - * timestampSub(field("timestamp"), "day", 1); + * timestampSubtract(field("timestamp"), "day", 1); * ``` * * @param timestamp The expression representing the timestamp. * @param unit The unit of time to subtract (e.g., "day", "hour"). * @param amount The amount of time to subtract. - * @return A new {@code Expr} representing the resulting timestamp. + * @return A new {@code Expression} representing the resulting timestamp. */ -export function timestampSub( - timestamp: Expr, +export function timestampSubtract( + timestamp: Expression, unit: 'microsecond' | 'millisecond' | 'second' | 'minute' | 'hour' | 'day', amount: number -): FunctionExpr; +): FunctionExpression; /** * @beta @@ -6065,35 +6468,54 @@ export function timestampSub( * * ```typescript * // Subtract 1 day from the 'timestamp' field. - * timestampSub("timestamp", "day", 1); + * timestampSubtract("timestamp", "day", 1); * ``` * * @param fieldName The name of the field representing the timestamp. * @param unit The unit of time to subtract (e.g., "day", "hour"). * @param amount The amount of time to subtract. - * @return A new {@code Expr} representing the resulting timestamp. + * @return A new {@code Expression} representing the resulting timestamp. */ -export function timestampSub( +export function timestampSubtract( fieldName: string, unit: 'microsecond' | 'millisecond' | 'second' | 'minute' | 'hour' | 'day', amount: number -): FunctionExpr; -export function timestampSub( - timestamp: Expr | string, +): FunctionExpression; +export function timestampSubtract( + timestamp: Expression | string, unit: - | Expr + | Expression | 'microsecond' | 'millisecond' | 'second' | 'minute' | 'hour' | 'day', - amount: Expr | number -): FunctionExpr { + amount: Expression | number +): FunctionExpression { const normalizedTimestamp = fieldOrExpression(timestamp); const normalizedUnit = valueToDefaultExpr(unit); const normalizedAmount = valueToDefaultExpr(amount); - return normalizedTimestamp.timestampSub(normalizedUnit, normalizedAmount); + return normalizedTimestamp.timestampSubtract( + normalizedUnit, + normalizedAmount + ); +} + +/** + * @beta + * + * Creates an expression that evaluates to the current server timestamp. + * + * ```typescript + * // Get the current server timestamp + * currentTimestamp() + * ``` + * + * @return A new Expression representing the current server timestamp. + */ +export function currentTimestamp(): FunctionExpression { + return new FunctionExpression('current_timestamp', []); } /** @@ -6103,20 +6525,20 @@ export function timestampSub( * ```typescript * // Check if the 'age' field is greater than 18 AND the 'city' field is "London" AND * // the 'status' field is "active" - * const condition = and(gt("age", 18), eq("city", "London"), eq("status", "active")); + * const condition = and(greaterThan("age", 18), equal("city", "London"), equal("status", "active")); * ``` * * @param first The first filter condition. * @param second The second filter condition. * @param more Additional filter conditions to 'AND' together. - * @return A new {@code Expr} representing the logical 'AND' operation. + * @return A new {@code Expression} representing the logical 'AND' operation. */ export function and( - first: BooleanExpr, - second: BooleanExpr, - ...more: BooleanExpr[] -): BooleanExpr { - return new BooleanExpr('and', [first, second, ...more]); + first: BooleanExpression, + second: BooleanExpression, + ...more: BooleanExpression[] +): BooleanExpression { + return new BooleanExpression('and', [first, second, ...more]); } /** @@ -6126,20 +6548,20 @@ export function and( * ```typescript * // Check if the 'age' field is greater than 18 OR the 'city' field is "London" OR * // the 'status' field is "active" - * const condition = or(gt("age", 18), eq("city", "London"), eq("status", "active")); + * const condition = or(greaterThan("age", 18), equal("city", "London"), equal("status", "active")); * ``` * * @param first The first filter condition. * @param second The second filter condition. * @param more Additional filter conditions to 'OR' together. - * @return A new {@code Expr} representing the logical 'OR' operation. + * @return A new {@code Expression} representing the logical 'OR' operation. */ export function or( - first: BooleanExpr, - second: BooleanExpr, - ...more: BooleanExpr[] -): BooleanExpr { - return new BooleanExpr('or', [first, second, ...more]); + first: BooleanExpression, + second: BooleanExpression, + ...more: BooleanExpression[] +): BooleanExpression { + return new BooleanExpression('or', [first, second, ...more]); } /** @@ -6153,9 +6575,9 @@ export function or( * * @param base The expression to raise to the power of the exponent. * @param exponent The expression to raise the base to the power of. - * @return A new `Expr` representing the power operation. + * @return A new `Expression` representing the power operation. */ -export function pow(base: Expr, exponent: Expr): FunctionExpr; +export function pow(base: Expression, exponent: Expression): FunctionExpression; /** * @beta @@ -6168,9 +6590,9 @@ export function pow(base: Expr, exponent: Expr): FunctionExpr; * * @param base The expression to raise to the power of the exponent. * @param exponent The constant value to raise the base to the power of. - * @return A new `Expr` representing the power operation. + * @return A new `Expression` representing the power operation. */ -export function pow(base: Expr, exponent: number): FunctionExpr; +export function pow(base: Expression, exponent: number): FunctionExpression; /** * @beta @@ -6183,9 +6605,9 @@ export function pow(base: Expr, exponent: number): FunctionExpr; * * @param base The name of the field to raise to the power of the exponent. * @param exponent The expression to raise the base to the power of. - * @return A new `Expr` representing the power operation. + * @return A new `Expression` representing the power operation. */ -export function pow(base: string, exponent: Expr): FunctionExpr; +export function pow(base: string, exponent: Expression): FunctionExpression; /** * @beta @@ -6198,13 +6620,13 @@ export function pow(base: string, exponent: Expr): FunctionExpr; * * @param base The name of the field to raise to the power of the exponent. * @param exponent The constant value to raise the base to the power of. - * @return A new `Expr` representing the power operation. + * @return A new `Expression` representing the power operation. */ -export function pow(base: string, exponent: number): FunctionExpr; +export function pow(base: string, exponent: number): FunctionExpression; export function pow( - base: Expr | string, - exponent: Expr | number -): FunctionExpr { + base: Expression | string, + exponent: Expression | number +): FunctionExpression { return fieldOrExpression(base).pow(exponent as number); } @@ -6218,9 +6640,9 @@ export function pow( * ``` * * @param fieldName The name of the field to round. - * @return A new `Expr` representing the rounded value. + * @return A new `Expression` representing the rounded value. */ -export function round(fieldName: string): FunctionExpr; +export function round(fieldName: string): FunctionExpression; /** * @beta @@ -6232,11 +6654,53 @@ export function round(fieldName: string): FunctionExpr; * ``` * * @param expression An expression evaluating to a numeric value, which will be rounded. + * @return A new `Expression` representing the rounded value. + */ +export function round(expression: Expression): FunctionExpression; +/** + * @beta + * Creates an expression that rounds a numeric value to the specified number of decimal places. + * + * ```typescript + * // Round the value of the 'price' field to two decimal places. + * round("price", 2); + * ``` + * + * @param fieldName The name of the field to round. + * @param decimalPlaces A constant or expression specifying the rounding precision in decimal places. + * @return A new `Expr` representing the rounded value. + */ +export function round( + fieldName: string, + decimalPlaces: number | Expression +): FunctionExpression; + +/** + * @beta + * Creates an expression that rounds a numeric value to the specified number of decimal places. + * + * ```typescript + * // Round the value of the 'price' field to two decimal places. + * round(field("price"), constant(2)); + * ``` + * + * @param expression An expression evaluating to a numeric value, which will be rounded. + * @param decimalPlaces A constant or expression specifying the rounding precision in decimal places. * @return A new `Expr` representing the rounded value. */ -export function round(expression: Expr): FunctionExpr; -export function round(expr: Expr | string): FunctionExpr { - return fieldOrExpression(expr).round(); +export function round( + expression: Expression, + decimalPlaces: number | Expression +): FunctionExpression; +export function round( + expr: Expression | string, + decimalPlaces?: number | Expression +): FunctionExpression { + if (decimalPlaces === undefined) { + return fieldOrExpression(expr).round(); + } else { + return fieldOrExpression(expr).round(valueToDefaultExpr(decimalPlaces)); + } } /** @@ -6249,9 +6713,9 @@ export function round(expr: Expr | string): FunctionExpr { * ``` * * @param fieldName The name of the field to get the collection ID from. - * @return A new {@code Expr} representing the collectionId operation. + * @return A new {@code Expression} representing the collectionId operation. */ -export function collectionId(fieldName: string): FunctionExpr; +export function collectionId(fieldName: string): FunctionExpression; /** * @beta @@ -6263,10 +6727,10 @@ export function collectionId(fieldName: string): FunctionExpr; * ``` * * @param expression An expression evaluating to a path, which the collection ID will be extracted from. - * @return A new {@code Expr} representing the collectionId operation. + * @return A new {@code Expression} representing the collectionId operation. */ -export function collectionId(expression: Expr): FunctionExpr; -export function collectionId(expr: Expr | string): FunctionExpr { +export function collectionId(expression: Expression): FunctionExpression; +export function collectionId(expr: Expression | string): FunctionExpression { return fieldOrExpression(expr).collectionId(); } @@ -6283,9 +6747,9 @@ export function collectionId(expr: Expr | string): FunctionExpr { * ``` * * @param fieldName The name of the field to calculate the length of. - * @return A new `Expr` representing the length of the string, array, map, vector, or bytes. + * @return A new `Expression` representing the length of the string, array, map, vector, or bytes. */ -export function length(fieldName: string): FunctionExpr; +export function length(fieldName: string): FunctionExpression; /** * @beta @@ -6300,10 +6764,10 @@ export function length(fieldName: string): FunctionExpr; * ``` * * @param expression An expression evaluating to a string, array, map, vector, or bytes, which the length will be calculated for. - * @return A new `Expr` representing the length of the string, array, map, vector, or bytes. + * @return A new `Expression` representing the length of the string, array, map, vector, or bytes. */ -export function length(expression: Expr): FunctionExpr; -export function length(expr: Expr | string): FunctionExpr { +export function length(expression: Expression): FunctionExpression; +export function length(expr: Expression | string): FunctionExpression { return fieldOrExpression(expr).length(); } @@ -6317,9 +6781,9 @@ export function length(expr: Expr | string): FunctionExpr { * ``` * * @param fieldName The name of the field to compute the natural logarithm of. - * @return A new `Expr` representing the natural logarithm of the numeric value. + * @return A new `Expression` representing the natural logarithm of the numeric value. */ -export function ln(fieldName: string): FunctionExpr; +export function ln(fieldName: string): FunctionExpression; /** * @beta @@ -6331,132 +6795,363 @@ export function ln(fieldName: string): FunctionExpr; * ``` * * @param expression An expression evaluating to a numeric value, which the natural logarithm will be computed for. - * @return A new `Expr` representing the natural logarithm of the numeric value. + * @return A new `Expression` representing the natural logarithm of the numeric value. */ -export function ln(expression: Expr): FunctionExpr; -export function ln(expr: Expr | string): FunctionExpr { +export function ln(expression: Expression): FunctionExpression; +export function ln(expr: Expression | string): FunctionExpression { return fieldOrExpression(expr).ln(); } /** * @beta - * Creates an expression that computes the logarithm of an expression to a given base. + * Creates an expression that computes the square root of a numeric value. + * + * ```typescript + * // Compute the square root of the 'value' field. + * sqrt(field("value")); + * ``` + * + * @param expression An expression evaluating to a numeric value, which the square root will be computed for. + * @return A new {@code Expression} representing the square root of the numeric value. + */ +export function sqrt(expression: Expression): FunctionExpression; +/** + * @beta + * Creates an expression that computes the square root of a numeric value. + * + * ```typescript + * // Compute the square root of the 'value' field. + * sqrt("value"); + * ``` + * + * @param fieldName The name of the field to compute the square root of. + * @return A new {@code Expression} representing the square root of the numeric value. + */ +export function sqrt(fieldName: string): FunctionExpression; +export function sqrt(expr: Expression | string): FunctionExpression { + return fieldOrExpression(expr).sqrt(); +} + +/** + * @beta + * Creates an expression that reverses a string. * * ```typescript - * // Compute the logarithm of the 'value' field with base 10. - * log(field("value"), 10); + * // Reverse the value of the 'myString' field. + * stringReverse(field("myString")); * ``` * - * @param expression An expression evaluating to a numeric value, which the logarithm will be computed for. - * @param base The base of the logarithm. - * @return A new {@code Expr} representing the logarithm of the numeric value. + * @param stringExpression An expression evaluating to a string value, which will be reversed. + * @return A new {@code Expression} representing the reversed string. */ -export function log(expression: Expr, base: number): FunctionExpr; +export function stringReverse(stringExpression: Expression): FunctionExpression; + /** * @beta - * Creates an expression that computes the logarithm of an expression to a given base. + * Creates an expression that reverses a string value in the specified field. * * ```typescript - * // Compute the logarithm of the 'value' field with the base in the 'base' field. - * log(field("value"), field("base")); + * // Reverse the value of the 'myString' field. + * stringReverse("myString"); * ``` * - * @param expression An expression evaluating to a numeric value, which the logarithm will be computed for. - * @param base The base of the logarithm. - * @return A new {@code Expr} representing the logarithm of the numeric value. + * @param field The name of the field representing the string to reverse. + * @return A new {@code Expression} representing the reversed string. */ -export function log(expression: Expr, base: Expr): FunctionExpr; +export function stringReverse(field: string): FunctionExpression; +export function stringReverse(expr: Expression | string): FunctionExpression { + return fieldOrExpression(expr).stringReverse(); +} + /** * @beta - * Creates an expression that computes the logarithm of a field to a given base. + * Creates an expression that concatenates strings, arrays, or blobs. Types cannot be mixed. * * ```typescript - * // Compute the logarithm of the 'value' field with base 10. - * log("value", 10); + * // Concatenate the 'firstName' and 'lastName' fields with a space in between. + * concat(field("firstName"), " ", field("lastName")) * ``` * - * @param fieldName The name of the field to compute the logarithm of. - * @param base The base of the logarithm. - * @return A new {@code Expr} representing the logarithm of the numeric value. + * @param first The first expressions to concatenate. + * @param second The second literal or expression to concatenate. + * @param others Additional literals or expressions to concatenate. + * @return A new `Expression` representing the concatenation. */ -export function log(fieldName: string, base: number): FunctionExpr; +export function concat( + first: Expression, + second: Expression | unknown, + ...others: Array +): FunctionExpression; + /** * @beta - * Creates an expression that computes the logarithm of a field to a given base. + * Creates an expression that concatenates strings, arrays, or blobs. Types cannot be mixed. * * ```typescript - * // Compute the logarithm of the 'value' field with the base in the 'base' field. - * log("value", field("base")); + * // Concatenate a field with a literal string. + * concat(field("firstName"), "Doe") * ``` * - * @param fieldName The name of the field to compute the logarithm of. - * @param base The base of the logarithm. - * @return A new {@code Expr} representing the logarithm of the numeric value. + * @param fieldName The name of a field to concatenate. + * @param second The second literal or expression to concatenate. + * @param others Additional literal or expressions to concatenate. + * @return A new `Expression` representing the concatenation. + */ +export function concat( + fieldName: string, + second: Expression | unknown, + ...others: Array +): FunctionExpression; + +export function concat( + fieldNameOrExpression: string | Expression, + second: Expression | unknown, + ...others: Array +): FunctionExpression { + return fieldOrExpression(fieldNameOrExpression).concat( + valueToDefaultExpr(second), + ...others.map(valueToDefaultExpr) + ); +} + +/** + * @beta + * Creates an expression that computes the absolute value of a numeric value. + * + * @param expr The expression to compute the absolute value of. + * @return A new {@code Expr} representing the absolute value of the numeric value. + */ +export function abs(expr: Expression): FunctionExpression; + +/** + * @beta + * Creates an expression that computes the absolute value of a numeric value. + * + * @param fieldName The field to compute the absolute value of. + * @return A new {@code Expr} representing the absolute value of the numeric value. */ -export function log(fieldName: string, base: Expr): FunctionExpr; -export function log(expr: Expr | string, base: number | Expr): FunctionExpr { - return fieldOrExpression(expr).log(valueToDefaultExpr(base)); +export function abs(fieldName: string): FunctionExpression; +export function abs(expr: Expression | string): FunctionExpression { + return fieldOrExpression(expr).abs(); } /** * @beta - * Creates an expression that computes the square root of a numeric value. + * Creates an expression that returns the `elseExpr` argument if `ifExpr` is absent, else return + * the result of the `ifExpr` argument evaluation. * * ```typescript - * // Compute the square root of the 'value' field. - * sqrt(field("value")); + * // Returns the value of the optional field 'optional_field', or returns 'default_value' + * // if the field is absent. + * ifAbsent(field("optional_field"), constant("default_value")) * ``` * - * @param expression An expression evaluating to a numeric value, which the square root will be computed for. - * @return A new {@code Expr} representing the square root of the numeric value. + * @param ifExpr The expression to check for absence. + * @param elseExpr The expression that will be evaluated and returned if [ifExpr] is absent. + * @return A new Expression representing the ifAbsent operation. */ -export function sqrt(expression: Expr): FunctionExpr; +export function ifAbsent(ifExpr: Expression, elseExpr: Expression): Expression; + /** * @beta - * Creates an expression that computes the square root of a numeric value. + * Creates an expression that returns the `elseValue` argument if `ifExpr` is absent, else + * return the result of the `ifExpr` argument evaluation. * * ```typescript - * // Compute the square root of the 'value' field. - * sqrt("value"); + * // Returns the value of the optional field 'optional_field', or returns 'default_value' + * // if the field is absent. + * ifAbsent(field("optional_field"), "default_value") * ``` * - * @param fieldName The name of the field to compute the square root of. - * @return A new {@code Expr} representing the square root of the numeric value. + * @param ifExpr The expression to check for absence. + * @param elseValue The value that will be returned if `ifExpr` evaluates to an absent value. + * @return A new [Expression] representing the ifAbsent operation. */ -export function sqrt(fieldName: string): FunctionExpr; -export function sqrt(expr: Expr | string): FunctionExpr { - return fieldOrExpression(expr).sqrt(); +export function ifAbsent(ifExpr: Expression, elseValue: unknown): Expression; + +/** + * @beta + * Creates an expression that returns the `elseExpr` argument if `ifFieldName` is absent, else + * return the value of the field. + * + * ```typescript + * // Returns the value of the optional field 'optional_field', or returns the value of + * // 'default_field' if 'optional_field' is absent. + * ifAbsent("optional_field", field("default_field")) + * ``` + * + * @param ifFieldName The field to check for absence. + * @param elseExpr The expression that will be evaluated and returned if `ifFieldName` is + * absent. + * @return A new Expression representing the ifAbsent operation. + */ +export function ifAbsent(ifFieldName: string, elseExpr: Expression): Expression; + +/** + * @beta + * Creates an expression that returns the `elseValue` argument if `ifFieldName` is absent, else + * return the value of the field. + * + * ```typescript + * // Returns the value of the optional field 'optional_field', or returns 'default_value' + * // if the field is absent. + * ifAbsent("optional_field", "default_value") + * ``` + * + * @param ifFieldName The field to check for absence. + * @param elseValue The value that will be returned if [ifFieldName] is absent. + * @return A new Expression representing the ifAbsent operation. + */ +export function ifAbsent( + ifFieldName: string | Expression, + elseValue: Expression | unknown +): Expression; +export function ifAbsent( + fieldNameOrExpression: string | Expression, + elseValue: Expression | unknown +): Expression { + return fieldOrExpression(fieldNameOrExpression).ifAbsent( + valueToDefaultExpr(elseValue) + ); } /** * @beta - * Creates an expression that reverses a string. + * Creates an expression that joins the elements of an array into a string. * * ```typescript - * // Reverse the value of the 'myString' field. - * strReverse(field("myString")); + * // Join the elements of the 'tags' field with a comma and space. + * join("tags", ", ") * ``` * - * @param stringExpression An expression evaluating to a string value, which will be reversed. - * @return A new {@code Expr} representing the reversed string. + * @param arrayFieldName The name of the field containing the array. + * @param delimiter The string to use as a delimiter. + * @return A new Expression representing the join operation. */ -export function strReverse(stringExpression: Expr): FunctionExpr; +export function join(arrayFieldName: string, delimiter: string): Expression; /** * @beta - * Creates an expression that reverses a string value in the specified field. + * Creates an expression that joins the elements of an array into a string. * * ```typescript - * // Reverse the value of the 'myString' field. - * strReverse("myString"); + * // Join an array of string using the delimiter from the 'separator' field. + * join(array(['foo', 'bar']), field("separator")) * ``` * - * @param field The name of the field representing the string to reverse. - * @return A new {@code Expr} representing the reversed string. + * @param arrayExpression An expression that evaluates to an array. + * @param delimiterExpression The expression that evaluates to the delimiter string. + * @return A new Expression representing the join operation. + */ +export function join( + arrayExpression: Expression, + delimiterExpression: Expression +): Expression; + +/** + * @beta + * Creates an expression that joins the elements of an array into a string. + * + * ```typescript + * // Join the elements of the 'tags' field with a comma and space. + * join(field("tags"), ", ") + * ``` + * + * @param arrayExpression An expression that evaluates to an array. + * @param delimiter The string to use as a delimiter. + * @return A new Expression representing the join operation. + */ +export function join( + arrayExpression: Expression, + delimiter: string +): Expression; + +/** + * @beta + * Creates an expression that joins the elements of an array into a string. + * + * ```typescript + * // Join the elements of the 'tags' field with the delimiter from the 'separator' field. + * join('tags', field("separator")) + * ``` + * + * @param arrayFieldName The name of the field containing the array. + * @param delimiterExpression The expression that evaluates to the delimiter string. + * @return A new Expression representing the join operation. + */ +export function join( + arrayFieldName: string, + delimiterExpression: Expression +): Expression; +export function join( + fieldNameOrExpression: string | Expression, + delimiterValueOrExpression: Expression | string +): Expression { + return fieldOrExpression(fieldNameOrExpression).join( + valueToDefaultExpr(delimiterValueOrExpression) + ); +} + +/** + * @beta + * Creates an expression that computes the base-10 logarithm of a numeric value. + * + * ```typescript + * // Compute the base-10 logarithm of the 'value' field. + * log10("value"); + * ``` + * + * @param fieldName The name of the field to compute the base-10 logarithm of. + * @return A new `Expr` representing the base-10 logarithm of the numeric value. + */ +export function log10(fieldName: string): FunctionExpression; + +/** + * @beta + * Creates an expression that computes the base-10 logarithm of a numeric value. + * + * ```typescript + * // Compute the base-10 logarithm of the 'value' field. + * log10(field("value")); + * ``` + * + * @param expression An expression evaluating to a numeric value, which the base-10 logarithm will be computed for. + * @return A new `Expr` representing the base-10 logarithm of the numeric value. + */ +export function log10(expression: Expression): FunctionExpression; +export function log10(expr: Expression | string): FunctionExpression { + return fieldOrExpression(expr).log10(); +} + +/** + * @beta + * Creates an expression that computes the sum of the elements in an array. + * + * ```typescript + * // Compute the sum of the elements in the 'scores' field. + * arraySum("scores"); + * ``` + * + * @param fieldName The name of the field to compute the sum of. + * @return A new `Expr` representing the sum of the elements in the array. + */ +export function arraySum(fieldName: string): FunctionExpression; + +/** + * @beta + * Creates an expression that computes the sum of the elements in an array. + * + * ```typescript + * // Compute the sum of the elements in the 'scores' field. + * arraySum(field("scores")); + * ``` + * + * @param expression An expression evaluating to a numeric array, which the sum will be computed for. + * @return A new `Expr` representing the sum of the elements in the array. */ -export function strReverse(field: string): FunctionExpr; -export function strReverse(expr: Expr | string): FunctionExpr { - return fieldOrExpression(expr).strReverse(); +export function arraySum(expression: Expression): FunctionExpression; +export function arraySum(expr: Expression | string): FunctionExpression { + return fieldOrExpression(expr).arraySum(); } // TODO(new-expression): Add new top-level expression function definitions above this line @@ -6474,7 +7169,7 @@ export function strReverse(expr: Expr | string): FunctionExpr { * @param expr The expression to create an ascending ordering for. * @return A new `Ordering` for ascending sorting. */ -export function ascending(expr: Expr): Ordering; +export function ascending(expr: Expression): Ordering; /** * @beta @@ -6490,7 +7185,7 @@ export function ascending(expr: Expr): Ordering; * @return A new `Ordering` for ascending sorting. */ export function ascending(fieldName: string): Ordering; -export function ascending(field: Expr | string): Ordering { +export function ascending(field: Expression | string): Ordering { return new Ordering(fieldOrExpression(field), 'ascending'); } @@ -6507,7 +7202,7 @@ export function ascending(field: Expr | string): Ordering { * @param expr The expression to create a descending ordering for. * @return A new `Ordering` for descending sorting. */ -export function descending(expr: Expr): Ordering; +export function descending(expr: Expression): Ordering; /** * @beta @@ -6523,7 +7218,7 @@ export function descending(expr: Expr): Ordering; * @return A new `Ordering` for descending sorting. */ export function descending(fieldName: string): Ordering; -export function descending(field: Expr | string): Ordering { +export function descending(field: Expression | string): Ordering { return new Ordering(fieldOrExpression(field), 'descending'); } @@ -6535,7 +7230,7 @@ export function descending(field: Expr | string): Ordering { */ export class Ordering implements HasUserData { constructor( - readonly expr: Expr, + readonly expr: Expression, readonly direction: 'ascending' | 'descending' ) {} @@ -6554,7 +7249,7 @@ export class Ordering implements HasUserData { * @internal */ _toProto(serializer: Serializer): api.IValue { - const expr = this.expr as Expr; + const expr = this.expr as Expression; return { mapValue: { fields: { @@ -6573,6 +7268,6 @@ export class Ordering implements HasUserData { * @internal */ _validateUserData(ignoreUndefinedProperties: boolean): void { - (this.expr as Expr)._validateUserData(ignoreUndefinedProperties); + (this.expr as Expression)._validateUserData(ignoreUndefinedProperties); } } diff --git a/dev/src/pipelines/index.ts b/dev/src/pipelines/index.ts index 23c7a5791..a7ccc9cec 100644 --- a/dev/src/pipelines/index.ts +++ b/dev/src/pipelines/index.ts @@ -24,46 +24,45 @@ export { arrayContains, arrayContainsAny, arrayReverse, - avg, - eq, + average, + equal, ceil, exp, floor, - gt, + greaterThan, like, - lt, - neq, + lessThan, + notEqual, ascending, not, or, regexContains, regexMatch, startsWith, - strConcat, + stringConcat, subtract, cosineDistance, countDistinct, dotProduct, euclideanDistance, mapGet, - lte, - eqAny, + lessThanOrEqual, + equalAny, map, array, field, xor, AggregateFunction, - rand, arrayGet, add, - BooleanExpr, - Expr, - FunctionExpr, + BooleanExpression, + Expression, + FunctionExpression, minimum, count, countIf, arrayLength, - strContains, + stringContains, charLength, divide, mod, @@ -72,16 +71,12 @@ export { toUpper, toLower, vectorLength, - isNotNan, exists, - isNotNull, isAbsent, ifError, isError, - isNan, substring, documentId, - isNull, arrayContainsAll, constant, Field, @@ -89,22 +84,22 @@ export { sum, maximum, descending, - gte, + greaterThanOrEqual, multiply, - cond, + conditional, Ordering, AliasedAggregate, endsWith, - AliasedExpr, + AliasedExpression, mapMerge, mapRemove, byteLength, logicalMaximum, logicalMinimum, - notEqAny, + notEqualAny, countAll, timestampAdd, - timestampSub, + timestampSubtract, timestampToUnixMicros, timestampToUnixSeconds, unixMicrosToTimestamp, @@ -115,9 +110,16 @@ export { collectionId, length, ln, - log, round, sqrt, - strReverse, + stringReverse, + abs, + arraySum, + ifAbsent, + log10, + concat, + join, + currentTimestamp, + arrayConcat, // TODO(new-expression): Add new expression exports above this line } from './expression'; diff --git a/dev/src/pipelines/pipeline-util.ts b/dev/src/pipelines/pipeline-util.ts index 9e8dab455..31455bd75 100644 --- a/dev/src/pipelines/pipeline-util.ts +++ b/dev/src/pipelines/pipeline-util.ts @@ -27,7 +27,7 @@ import Firestore, { VectorValue, } from '../index'; import {logger} from '../logger'; -import {QualifiedResourcePath} from '../path'; +import {FieldPath, QualifiedResourcePath} from '../path'; import {CompositeFilterInternal} from '../reference/composite-filter-internal'; import {NOOP_MESSAGE} from '../reference/constants'; import {FieldFilterInternal} from '../reference/field-filter-internal'; @@ -50,8 +50,8 @@ import { import api = protos.google.firestore.v1; import { - Expr, - BooleanExpr, + Expression, + BooleanExpression, and, or, field as createField, @@ -61,8 +61,8 @@ import { Constant, field, Ordering, - gt, - lt, + greaterThan, + lessThan, Field, AggregateFunction, } from './expression'; @@ -440,9 +440,9 @@ export function whereConditionsFromCursor( cursor: QueryCursor, orderings: Ordering[], position: 'before' | 'after' -): BooleanExpr { +): BooleanExpression { // The filterFunc is either greater than or less than - const filterFunc = position === 'before' ? lt : gt; + const filterFunc = position === 'before' ? lessThan : greaterThan; const cursors = cursor.values.map(value => Constant._fromProto(value)); const size = cursors.length; @@ -450,14 +450,17 @@ export function whereConditionsFromCursor( let value = cursors[size - 1]; // Add condition for last bound - let condition: BooleanExpr = filterFunc(field, value); + let condition: BooleanExpression = filterFunc(field, value); if ( (position === 'after' && cursor.before) || (position === 'before' && !cursor.before) ) { // When the cursor bound is inclusive, then the last bound // can be equal to the value, otherwise it's not equal - condition = or(condition, field.eq(value) as unknown as BooleanExpr); + condition = or( + condition, + field.equal(value) as unknown as BooleanExpression + ); } // Iterate backwards over the remaining bounds, adding @@ -467,11 +470,11 @@ export function whereConditionsFromCursor( value = cursors[i]; // For each field in the orderings, the condition is either - // a) lt|gt the cursor value, - // b) or equal the cursor value and lt|gt the cursor values for other fields + // a) lessThan|greaterThan the cursor value, + // b) or equal the cursor value and lessThan|greaterThan the cursor values for other fields condition = or( filterFunc(field, value), - and(field.eq(value) as unknown as BooleanExpr, condition) + and(field.equal(value) as unknown as BooleanExpression, condition) ); } @@ -491,53 +494,40 @@ export function reverseOrderings(orderings: Ordering[]): Ordering[] { export function toPipelineBooleanExpr( f: FilterInternal, serializer: Serializer -): BooleanExpr { +): BooleanExpression { if (f instanceof FieldFilterInternal) { const field = createField(f.field); - if (f.isNanChecking()) { - if (f.nanOp() === 'IS_NAN') { - return and(field.exists(), field.isNan()); - } else { - return and(field.exists(), field.isNotNan()); + + // Comparison filters + const value = isFirestoreValue(f.value) + ? f.value + : serializer.encodeValue(f.value); + switch (f.op) { + case 'LESS_THAN': + return and(field.exists(), field.lessThan(value)); + case 'LESS_THAN_OR_EQUAL': + return and(field.exists(), field.lessThanOrEqual(value)); + case 'GREATER_THAN': + return and(field.exists(), field.greaterThan(value)); + case 'GREATER_THAN_OR_EQUAL': + return and(field.exists(), field.greaterThanOrEqual(value)); + case 'EQUAL': + return and(field.exists(), field.equal(value)); + case 'NOT_EQUAL': + return and(field.exists(), field.notEqual(value)); + case 'ARRAY_CONTAINS': + return and(field.exists(), field.arrayContains(value)); + case 'IN': { + const values = value?.arrayValue?.values?.map(val => constant(val)); + return and(field.exists(), field.equalAny(values!)); } - } else if (f.isNullChecking()) { - if (f.nullOp() === 'IS_NULL') { - return and(field.exists(), field.isNull()); - } else { - return and(field.exists(), field.isNotNull()); + case 'ARRAY_CONTAINS_ANY': { + const values = value?.arrayValue?.values?.map(val => constant(val)); + return and(field.exists(), field.arrayContainsAny(values!)); } - } else { - // Comparison filters - const value = isFirestoreValue(f.value) - ? f.value - : serializer.encodeValue(f.value); - switch (f.op) { - case 'LESS_THAN': - return and(field.exists(), field.lt(value)); - case 'LESS_THAN_OR_EQUAL': - return and(field.exists(), field.lte(value)); - case 'GREATER_THAN': - return and(field.exists(), field.gt(value)); - case 'GREATER_THAN_OR_EQUAL': - return and(field.exists(), field.gte(value)); - case 'EQUAL': - return and(field.exists(), field.eq(value)); - case 'NOT_EQUAL': - return and(field.exists(), field.neq(value)); - case 'ARRAY_CONTAINS': - return and(field.exists(), field.arrayContains(value)); - case 'IN': { - const values = value?.arrayValue?.values?.map(val => constant(val)); - return and(field.exists(), field.eqAny(values!)); - } - case 'ARRAY_CONTAINS_ANY': { - const values = value?.arrayValue?.values?.map(val => constant(val)); - return and(field.exists(), field.arrayContainsAny(values!)); - } - case 'NOT_IN': { - const values = value?.arrayValue?.values?.map(val => constant(val)); - return and(field.exists(), field.notEqAny(values!)); - } + case 'NOT_IN': { + const values = value?.arrayValue?.values?.map(val => constant(val)); + return and(field.exists(), field.notEqualAny(values!)); } } } else if (f instanceof CompositeFilterInternal) { @@ -575,7 +565,9 @@ export function isSelectable( ): val is firestore.Pipelines.Selectable { const candidate = val as firestore.Pipelines.Selectable; return ( - candidate.selectable && isString(candidate.alias) && isExpr(candidate.expr) + candidate.selectable && + isString(candidate._alias) && + isExpr(candidate._expr) ); } @@ -593,19 +585,19 @@ export function isAliasedAggregate( ): val is firestore.Pipelines.AliasedAggregate { const candidate = val as firestore.Pipelines.AliasedAggregate; return ( - isString(candidate.alias) && - candidate.aggregate instanceof AggregateFunction + isString(candidate._alias) && + candidate._aggregate instanceof AggregateFunction ); } -export function isExpr(val: unknown): val is firestore.Pipelines.Expr { - return val instanceof Expr; +export function isExpr(val: unknown): val is firestore.Pipelines.Expression { + return val instanceof Expression; } export function isBooleanExpr( val: unknown -): val is firestore.Pipelines.BooleanExpr { - return val instanceof BooleanExpr; +): val is firestore.Pipelines.BooleanExpression { + return val instanceof BooleanExpression; } export function isField(val: unknown): val is firestore.Pipelines.Field { @@ -623,19 +615,19 @@ export function isCollectionReference( } /** - * Converts a value to an Expr, Returning either a Constant, MapFunction, + * 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 */ -export function valueToDefaultExpr(value: unknown): Expr { - let result: Expr | undefined; +export function valueToDefaultExpr(value: unknown): Expression { + let result: Expression | undefined; if (isFirestoreValue(value)) { return constant(value); } - if (value instanceof Expr) { + if (value instanceof Expression) { return value; } else if (isPlainObject(value)) { result = map(value as Record); @@ -651,7 +643,7 @@ export function valueToDefaultExpr(value: unknown): Expr { } /** - * Converts a value to an Expr, Returning either a Constant, MapFunction, + * Converts a value to an Expression, Returning either a Constant, MapFunction, * ArrayFunction, or the input itself (if it's already an expression). * * @private @@ -659,9 +651,9 @@ export function valueToDefaultExpr(value: unknown): Expr { * @param value */ export function vectorToExpr( - value: firestore.VectorValue | number[] | Expr -): Expr { - if (value instanceof Expr) { + value: firestore.VectorValue | number[] | Expression +): Expression { + if (value instanceof Expression) { return value; } else if (value instanceof VectorValue) { const result = constant(value); @@ -677,7 +669,7 @@ export function vectorToExpr( } /** - * Converts a value to an Expr, Returning either a Constant, MapFunction, + * 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. @@ -686,7 +678,7 @@ export function vectorToExpr( * @internal * @param value */ -export function fieldOrExpression(value: unknown): Expr { +export function fieldOrExpression(value: unknown): Expression { if (isString(value)) { const result = field(value); result._createdFromLiteral = true; @@ -725,3 +717,46 @@ export function fieldOrSelectable(value: string | Selectable): Selectable { return value; } } + +export function selectablesToMap( + selectables: (firestore.Pipelines.Selectable | string)[] +): Map { + const result = new Map(); + for (const selectable of selectables) { + let alias: string; + let expression: Expression; + if (typeof selectable === 'string') { + alias = selectable as string; + expression = new Field(FieldPath.fromArgument(selectable)); + } else { + alias = selectable._alias; + expression = selectable._expr as unknown as Expression; + } + + if (result.get(alias) !== undefined) { + throw new Error(`Duplicate alias or field '${alias}'`); + } + + result.set(alias, expression); + } + return result; +} + +export function aliasedAggregateToMap( + aliasedAggregatees: firestore.Pipelines.AliasedAggregate[] +): Map { + return aliasedAggregatees.reduce( + ( + map: Map, + selectable: firestore.Pipelines.AliasedAggregate + ) => { + if (map.get(selectable._alias) !== undefined) { + throw new Error(`Duplicate alias or field '${selectable._alias}'`); + } + + map.set(selectable._alias, selectable._aggregate as AggregateFunction); + return map; + }, + new Map() as Map + ); +} diff --git a/dev/src/pipelines/pipelines.ts b/dev/src/pipelines/pipelines.ts index f902a374b..c15fe95a9 100644 --- a/dev/src/pipelines/pipelines.ts +++ b/dev/src/pipelines/pipelines.ts @@ -24,6 +24,7 @@ import Firestore, { import {validateFieldPath} from '../path'; import { ExecutionUtil, + aliasedAggregateToMap, fieldOrExpression, isAliasedAggregate, isBooleanExpr, @@ -35,6 +36,7 @@ import { isPipeline, isSelectable, isString, + selectablesToMap, toField, vectorToExpr, } from './pipeline-util'; @@ -50,10 +52,9 @@ import {isOptionalEqual, isPlainObject} from '../util'; import { AggregateFunction, AliasedAggregate, - Expr, - AliasedExpr, + Expression, Field, - BooleanExpr, + BooleanExpression, Ordering, constant, _mapValue, @@ -250,16 +251,27 @@ export class PipelineSource implements firestore.Pipelines.PipelineSource { return new Pipeline(this.db, [new DocumentsSource(internalOptions)]); } + /** + * @beta + * Convert the given VectorQuery into an equivalent Pipeline. + * + * @param query A VectorQuery to be converted into a Pipeline. + * + * @throws {@FirestoreError} Thrown if the provided VectorQuer targets a different project or database than the Pipeline. + */ + createFrom(query: firestore.VectorQuery): Pipeline; + /** * @beta * Convert the given Query into an equivalent Pipeline. * * @param query A Query to be converted into a Pipeline. * - * @throws {@FirestoreError} Thrown if any of the provided DocumentReferences target a different project or database than the pipeline. + * @throws {@FirestoreError} Thrown if the provided VectorQuer targets a different project or database than the Pipeline. */ - createFrom(query: firestore.Query): Pipeline { - return (query as unknown as Query)._pipeline(); + createFrom(query: firestore.Query): Pipeline; + createFrom(query: firestore.Query | firestore.VectorQuery): Pipeline { + return (query as unknown as {_pipeline(): Pipeline})._pipeline(); } _validateReference( @@ -323,14 +335,14 @@ export class PipelineSource implements firestore.Pipelines.PipelineSource { * // Example 2: Filter documents where 'genre' is 'Science Fiction' and 'published' is after 1950 * const results2 = await db.pipeline() * .collection('books') - * .where(and(field('genre').eq('Science Fiction'), field('published').gt(1950))) + * .where(and(field('genre').equal('Science Fiction'), field('published').greaterThan(1950))) * .execute(); * * // Example 3: Calculate the average rating of books published after 1980 * const results3 = await db.pipeline() * .collection('books') - * .where(field('published').gt(1980)) - * .aggregate(avg(field('rating')).as('averageRating')) + * .where(field('published').greaterThan(1980)) + * .aggregate(average(field('rating')).as('averageRating')) * .execute(); * ``` */ @@ -357,8 +369,8 @@ export class Pipeline implements firestore.Pipelines.Pipeline { * The added fields are defined using {@link Selectable}s, which can be: * * - {@link Field}: References an existing document field. - * - {@link Expr}: Either a literal value (see {@link Constant}) or a computed value - * (see {@FunctionExpr}) with an assigned alias using {@link Expr#as}. + * - {@link Expression}: Either a literal value (see {@link Constant}) or a computed value + * (see {@FunctionExpression}) with an assigned alias using {@link Expression#as}. * * Example: * @@ -389,8 +401,8 @@ export class Pipeline implements firestore.Pipelines.Pipeline { * The added fields are defined using {@link Selectable}s, which can be: * * - {@link Field}: References an existing document field. - * - {@link Expr}: Either a literal value (see {@link Constant}) or a computed value - * (see {@FunctionExpr}) with an assigned alias using {@link Expr#as}. + * - {@link Expression}: Either a literal value (see {@link Constant}) or a computed value + * (see {@FunctionExpression}) with an assigned alias using {@link Expression#as}. * * Example: * @@ -418,7 +430,7 @@ export class Pipeline implements firestore.Pipelines.Pipeline { ) ? [fieldOrOptions, ...additionalFields] : fieldOrOptions.fields; - const normalizedFields: Map = selectablesToMap(fields); + const normalizedFields: Map = selectablesToMap(fields); this._validateUserData('select', normalizedFields); @@ -510,7 +522,7 @@ export class Pipeline implements firestore.Pipelines.Pipeline { *

  • {@code string}: Name of an existing field
  • *
  • {@link Field}: References an existing field.
  • *
  • {@link Function}: Represents the result of a function with an assigned alias name using - * {@link Expr#as}
  • + * {@link Expression#as} * * *

    If no selections are provided, the output of this stage is empty. Use {@link @@ -548,7 +560,7 @@ export class Pipeline implements firestore.Pipelines.Pipeline { *

  • {@code string}: Name of an existing field
  • *
  • {@link Field}: References an existing field.
  • *
  • {@link Function}: Represents the result of a function with an assigned alias name using - * {@link Expr#as}
  • + * {@link Expression#as} * * *

    If no selections are provided, the output of this stage is empty. Use {@link @@ -586,7 +598,7 @@ export class Pipeline implements firestore.Pipelines.Pipeline { isSelectable(selectionOrOptions) || isString(selectionOrOptions) ? [selectionOrOptions, ...additionalSelections] : selectionOrOptions.selections; - const normalizedSelections: Map = + const normalizedSelections: Map = selectablesToMap(selections); this._validateUserData('select', normalizedSelections); @@ -601,15 +613,15 @@ export class Pipeline implements firestore.Pipelines.Pipeline { /** * @beta * Filters the documents from previous stages to only include those matching the specified {@link - * BooleanExpr}. + * BooleanExpression}. * *

    This stage allows you to apply conditions to the data, similar to a "WHERE" clause in SQL. * You can filter documents based on their field values, using implementations of {@link - * BooleanExpr}, typically including but not limited to: + * BooleanExpression}, typically including but not limited to: * *

      - *
    • field comparators: {@link Function#eq}, {@link Function#lt} (less than), {@link - * Function#gt} (greater than), etc.
    • + *
    • field comparators: {@link Function#equal}, {@link Function#lessThan} (less than), {@link + * Function#greaterThan} (greater than), etc.
    • *
    • logical operators: {@link Function#and}, {@link Function#or}, {@link Function#not}, etc.
    • *
    • advanced functions: {@link Function#regexMatch}, {@link * Function#arrayContains}, etc.
    • @@ -621,28 +633,28 @@ export class Pipeline implements firestore.Pipelines.Pipeline { * firestore.pipeline().collection("books") * .where( * and( - * gt(field("rating"), 4.0), // Filter for ratings greater than 4.0 - * field("genre").eq("Science Fiction") // Equivalent to gt("genre", "Science Fiction") + * greaterThan(field("rating"), 4.0), // Filter for ratings greater than 4.0 + * field("genre").equal("Science Fiction") // Equivalent to greaterThan("genre", "Science Fiction") * ) * ); * ``` * - * @param condition The {@link BooleanExpr} to apply. + * @param condition The {@link BooleanExpression} to apply. * @return A new Pipeline object with this stage appended to the stage list. */ - where(condition: firestore.Pipelines.BooleanExpr): Pipeline; + where(condition: firestore.Pipelines.BooleanExpression): Pipeline; /** * @beta * Filters the documents from previous stages to only include those matching the specified {@link - * BooleanExpr}. + * BooleanExpression}. * *

      This stage allows you to apply conditions to the data, similar to a "WHERE" clause in SQL. * You can filter documents based on their field values, using implementations of {@link - * BooleanExpr}, typically including but not limited to: + * BooleanExpression}, typically including but not limited to: * *

        - *
      • field comparators: {@link Function#eq}, {@link Function#lt} (less than), {@link - * Function#gt} (greater than), etc.
      • + *
      • field comparators: {@link Function#equal}, {@link Function#lessThan} (less than), {@link + * Function#greaterThan} (greater than), etc.
      • *
      • logical operators: {@link Function#and}, {@link Function#or}, {@link Function#not}, etc.
      • *
      • advanced functions: {@link Function#regexMatch}, {@link * Function#arrayContains}, etc.
      • @@ -654,8 +666,8 @@ export class Pipeline implements firestore.Pipelines.Pipeline { * firestore.pipeline().collection("books") * .where( * and( - * gt(field("rating"), 4.0), // Filter for ratings greater than 4.0 - * field("genre").eq("Science Fiction") // Equivalent to gt("genre", "Science Fiction") + * greaterThan(field("rating"), 4.0), // Filter for ratings greater than 4.0 + * field("genre").equal("Science Fiction") // Equivalent to greaterThan("genre", "Science Fiction") * ) * ); * ``` @@ -666,17 +678,18 @@ export class Pipeline implements firestore.Pipelines.Pipeline { where(options: firestore.Pipelines.WhereStageOptions): Pipeline; where( conditionOrOptions: - | firestore.Pipelines.BooleanExpr + | firestore.Pipelines.BooleanExpression | firestore.Pipelines.WhereStageOptions ): Pipeline { const options = isBooleanExpr(conditionOrOptions) ? {} : conditionOrOptions; - const condition: firestore.Pipelines.BooleanExpr = isBooleanExpr( + const condition: firestore.Pipelines.BooleanExpression = isBooleanExpr( conditionOrOptions ) ? conditionOrOptions : conditionOrOptions.condition; - const convertedCondition: BooleanExpr = condition as BooleanExpr; + const convertedCondition: BooleanExpression = + condition as BooleanExpression; this._validateUserData('where', convertedCondition); const internalOptions: InternalWhereStageOptions = { @@ -822,14 +835,14 @@ export class Pipeline implements firestore.Pipelines.Pipeline { * Returns a set of distinct values from the inputs to this stage. * * This stage runs through the results from previous stages to include only results with - * unique combinations of {@link Expr} values ({@link Field}, {@link Function}, etc). + * unique combinations of {@link Expression} values ({@link Field}, {@link Function}, etc). * * The parameters to this stage are defined using {@link Selectable} expressions or strings: * * - {@code string}: Name of an existing field * - {@link Field}: References an existing document field. - * - {@link AliasedExpr}: Represents the result of a function with an assigned alias name - * using {@link Expr#as}. + * - {@link AliasedExpression}: Represents the result of a function with an assigned alias name + * using {@link Expression#as}. * * Example: * @@ -855,14 +868,14 @@ export class Pipeline implements firestore.Pipelines.Pipeline { * Returns a set of distinct values from the inputs to this stage. * * This stage runs through the results from previous stages to include only results with - * unique combinations of {@link Expr} values ({@link Field}, {@link Function}, etc). + * unique combinations of {@link Expression} values ({@link Field}, {@link Function}, etc). * * The parameters to this stage are defined using {@link Selectable} expressions or strings: * * - {@code string}: Name of an existing field * - {@link Field}: References an existing document field. - * - {@link AliasedExpr}: Represents the result of a function with an assigned alias name - * using {@link Expr#as}. + * - {@link AliasedExpression}: Represents the result of a function with an assigned alias name + * using {@link Expression#as}. * * Example: * @@ -893,7 +906,7 @@ export class Pipeline implements firestore.Pipelines.Pipeline { isString(groupOrOptions) || isSelectable(groupOrOptions) ? [groupOrOptions, ...additionalGroups] : groupOrOptions.groups; - const convertedGroups: Map = selectablesToMap(groups); + const convertedGroups: Map = selectablesToMap(groups); this._validateUserData('distinct', convertedGroups); const internalOptions: InternalDistinctStageOptions = { @@ -910,7 +923,7 @@ export class Pipeline implements firestore.Pipelines.Pipeline { * *

        This stage allows you to calculate aggregate values over a set of documents. You define the * aggregations to perform using {@link AliasedAggregate} expressions which are typically results of - * calling {@link Expr#as} on {@link AggregateFunction} instances. + * calling {@link Expression#as} on {@link AggregateFunction} instances. * *

        Example: * @@ -918,7 +931,7 @@ export class Pipeline implements firestore.Pipelines.Pipeline { * // Calculate the average rating and the total number of books * firestore.pipeline().collection("books") * .aggregate( - * field("rating").avg().as("averageRating"), + * field("rating").average().as("averageRating"), * countAll().as("totalBooks") * ); * ``` @@ -947,7 +960,7 @@ export class Pipeline implements firestore.Pipelines.Pipeline { * specifying groups is the same as putting the entire inputs into one group. *

      • **Accumulators:** One or more accumulation operations to perform within each group. These * are defined using {@link AliasedAggregate} expressions, which are typically created by - * calling {@link Expr#as} on {@link AggregateFunction} instances. Each aggregation + * calling {@link Expression#as} on {@link AggregateFunction} instances. Each aggregation * calculates a value (e.g., sum, average, count) based on the documents within its group.
      • *
      * @@ -957,7 +970,7 @@ export class Pipeline implements firestore.Pipelines.Pipeline { * // Calculate the average rating for each genre. * firestore.pipeline().collection("books") * .aggregate({ - * accumulators: [avg(field("rating")).as("avg_rating")] + * accumulators: [average(field("rating")).as("avg_rating")] * groups: ["genre"] * }); * ``` @@ -983,7 +996,7 @@ export class Pipeline implements firestore.Pipelines.Pipeline { aliasedAggregateToMap(accumulators); const groups: Array = isAliasedAggregate(targetOrOptions) ? [] : targetOrOptions.groups ?? []; - const convertedGroups: Map = selectablesToMap(groups); + const convertedGroups: Map = selectablesToMap(groups); this._validateUserData('aggregate', convertedGroups); const internalOptions: InternalAggregateStageOptions = { @@ -1109,10 +1122,10 @@ export class Pipeline implements firestore.Pipelines.Pipeline { * // } * ``` * - * @param expr An {@link Expr} that when returned evaluates to a map. + * @param expr An {@link Expression} that when returned evaluates to a map. * @return A new {@code Pipeline} object with this stage appended to the stage list. */ - replaceWith(expr: firestore.Pipelines.Expr): Pipeline; + replaceWith(expr: firestore.Pipelines.Expression): Pipeline; /** * @beta * Fully overwrites all fields in a document with those coming from a map. @@ -1153,14 +1166,14 @@ export class Pipeline implements firestore.Pipelines.Pipeline { replaceWith(options: firestore.Pipelines.ReplaceWithStageOptions): Pipeline; replaceWith( valueOrOptions: - | firestore.Pipelines.Expr + | firestore.Pipelines.Expression | string | firestore.Pipelines.ReplaceWithStageOptions ): Pipeline { const options = isString(valueOrOptions) || isExpr(valueOrOptions) ? {} : valueOrOptions; - const fieldNameOrExpr: string | firestore.Pipelines.Expr = + const fieldNameOrExpr: string | firestore.Pipelines.Expression = isString(valueOrOptions) || isExpr(valueOrOptions) ? valueOrOptions : valueOrOptions.map; @@ -1388,8 +1401,8 @@ export class Pipeline implements firestore.Pipelines.Pipeline { ) ? selectableOrOptions : selectableOrOptions.selectable; - const alias = selectable.alias; - const expr = selectable.expr as Expr; + const alias = selectable._alias; + const expr = selectable._expr as Expression; const indexFieldName = isSelectable(selectableOrOptions) ? indexField @@ -1500,7 +1513,7 @@ export class Pipeline implements firestore.Pipelines.Pipeline { * ```typescript * // Assume we don't have a built-in 'where' stage * firestore.pipeline().collection('books') - * .rawStage('where', [field('published').lt(1900)]) // Custom 'where' stage + * .rawStage('where', [field('published').lessThan(1900)]) // Custom 'where' stage * .select('title', 'author'); * ``` * @@ -1512,14 +1525,14 @@ export class Pipeline implements firestore.Pipelines.Pipeline { rawStage( name: string, params: unknown[], - options?: {[key: string]: Expr | unknown} + options?: {[key: string]: Expression | unknown} ): Pipeline { // Convert input values to Expressions. // We treat objects as mapValues and arrays as arrayValues, // this is unlike the default conversion for objects and arrays // passed to an expression. const expressionParams = params.map((value: unknown) => { - if (value instanceof Expr) { + if (value instanceof Expression) { return value; } else if (value instanceof AggregateFunction) { return value; @@ -1563,7 +1576,7 @@ export class Pipeline implements firestore.Pipelines.Pipeline { * * ```typescript * const futureResults = await firestore.pipeline().collection('books') - * .where(gt(field('rating'), 4.5)) + * .where(greaterThan(field('rating'), 4.5)) * .select('title', 'author', 'rating') * .execute(); * ``` @@ -1618,7 +1631,7 @@ export class Pipeline implements firestore.Pipelines.Pipeline { * @example * ```typescript * firestore.pipeline().collection('books') - * .where(gt(field('rating'), 4.5)) + * .where(greaterThan(field('rating'), 4.5)) * .select('title', 'author', 'rating') * .stream() * .on('data', (pipelineResult) => {}) @@ -1640,6 +1653,7 @@ export class Pipeline implements firestore.Pipelines.Pipeline { } /** + * @beta * Validates user data for each expression in the expressionMap. * @param name Name of the calling function. Used for error messages when invalid user data is encountered. * @param val @@ -1664,43 +1678,6 @@ export class Pipeline implements firestore.Pipelines.Pipeline { } } -function selectablesToMap( - selectables: (firestore.Pipelines.Selectable | string)[] -): Map { - const result = new Map(); - for (const selectable of selectables) { - if (typeof selectable === 'string') { - result.set( - selectable as string, - new Field(FieldPath.fromArgument(selectable)) - ); - } else if (selectable instanceof Field) { - result.set((selectable as Field).fieldName(), selectable); - } else if (selectable instanceof AliasedExpr) { - const expr = selectable as AliasedExpr; - result.set(expr.alias, expr.expr as unknown as Expr); - } else { - throw new Error('unexpected selectable: ' + JSON.stringify(selectable)); - } - } - return result; -} - -function aliasedAggregateToMap( - aliasedAggregatees: firestore.Pipelines.AliasedAggregate[] -): Map { - return aliasedAggregatees.reduce( - ( - map: Map, - selectable: firestore.Pipelines.AliasedAggregate - ) => { - map.set(selectable.alias, selectable.aggregate as AggregateFunction); - return map; - }, - new Map() as Map - ); -} - /** * @beta * A wrapper object to access explain stats if explain or analyze @@ -1710,6 +1687,7 @@ export class ExplainStats implements firestore.Pipelines.ExplainStats { private static protoRoot: ProtoRoot | undefined = undefined; /** + * @beta * @private * @internal */ @@ -1723,6 +1701,7 @@ export class ExplainStats implements firestore.Pipelines.ExplainStats { } /** + * @beta * @private * @internal * @hideconstructor @@ -1731,6 +1710,7 @@ export class ExplainStats implements firestore.Pipelines.ExplainStats { constructor(private readonly explainStatsData: google.protobuf.IAny) {} /** + * @beta * Decode an ExplainStats proto message into a value. * @private * @internal @@ -1886,6 +1866,7 @@ export class PipelineResult implements firestore.Pipelines.PipelineResult { public readonly _updateTime: Timestamp | undefined; /** + * @beta * @private * @internal * @@ -1901,6 +1882,7 @@ export class PipelineResult implements firestore.Pipelines.PipelineResult { constructor( serializer: Serializer, /** + * @beta * @internal * @private **/ @@ -1960,23 +1942,6 @@ export class PipelineResult implements firestore.Pipelines.PipelineResult { return this._updateTime; } - /** - * @beta - * The time at which the pipeline producing this result is executed. - * - * @type {Timestamp} - * @readonly - * - */ - get executionTime(): Timestamp { - if (this._executionTime === undefined) { - throw new Error( - "'executionTime' is expected to exist, but it is undefined" - ); - } - return this._executionTime; - } - /** * @beta * Retrieves all fields in the result as an object. @@ -2038,6 +2003,7 @@ export class PipelineResult implements firestore.Pipelines.PipelineResult { } /** + * @beta * Retrieves the field specified by 'fieldPath' in its Protobuf JS * representation. * diff --git a/dev/src/pipelines/stage.ts b/dev/src/pipelines/stage.ts index ff3588726..dff5bd461 100644 --- a/dev/src/pipelines/stage.ts +++ b/dev/src/pipelines/stage.ts @@ -21,8 +21,8 @@ import {ProtoSerializable, Serializer} from '../serializer'; import { AggregateFunction, - BooleanExpr, - Expr, + BooleanExpression, + Expression, Field, field, Ordering, @@ -72,7 +72,7 @@ export type InternalAggregateStageOptions = Omit< firestore.Pipelines.AggregateStageOptions, 'groups' | 'accumulators' > & { - groups: Map; + groups: Map; accumulators: Map; }; @@ -104,7 +104,7 @@ export type InternalDistinctStageOptions = Omit< firestore.Pipelines.DistinctStageOptions, 'groups' > & { - groups: Map; + groups: Map; }; /** @@ -256,7 +256,7 @@ export type InternalWhereStageOptions = Omit< firestore.Pipelines.WhereStageOptions, 'condition' > & { - condition: BooleanExpr; + condition: BooleanExpression; }; /** @@ -284,7 +284,7 @@ export type InternalFindNearestStageOptions = Omit< firestore.Pipelines.FindNearestStageOptions, 'vectorValue' | 'field' | 'distanceField' > & { - vectorValue: Expr; + vectorValue: Expression; field: Field; distanceField?: Field; }; @@ -381,7 +381,7 @@ export type InternalUnnestStageOptions = Omit< 'selectable' | 'indexField' > & { alias: string; - expr: Expr; + expr: Expression; indexField?: Field; }; @@ -463,7 +463,7 @@ export type InternalReplaceWithStageOptions = Omit< firestore.Pipelines.ReplaceWithStageOptions, 'map' > & { - map: Expr; + map: Expression; }; /** @@ -494,7 +494,7 @@ export type InternalSelectStageOptions = Omit< firestore.Pipelines.SelectStageOptions, 'selections' > & { - selections: Map; + selections: Map; }; /** @@ -522,7 +522,7 @@ export type InternalAddFieldsStageOptions = Omit< firestore.Pipelines.AddFieldsStageOptions, 'fields' > & { - fields: Map; + fields: Map; }; /** @@ -586,7 +586,7 @@ export class RawStage implements Stage { */ constructor( public name: string, - private params: Array, + private params: Array, private rawOptions: Record ) {} diff --git a/dev/src/pipelines/structured-pipeline.ts b/dev/src/pipelines/structured-pipeline.ts index 69e9192de..9c8f5e04a 100644 --- a/dev/src/pipelines/structured-pipeline.ts +++ b/dev/src/pipelines/structured-pipeline.ts @@ -25,7 +25,7 @@ export type StructuredPipelineOptions = { indexMode?: 'recommended'; explainOptions?: { mode?: 'execute' | 'explain' | 'analyze'; - outputFormat?: 'text' | 'json'; + outputFormat?: 'text'; }; }; diff --git a/dev/src/reference/aggregate-query.ts b/dev/src/reference/aggregate-query.ts index 8143a9c37..a4b62fd43 100644 --- a/dev/src/reference/aggregate-query.ts +++ b/dev/src/reference/aggregate-query.ts @@ -22,7 +22,7 @@ import * as deepEqual from 'fast-deep-equal'; import * as firestore from '@google-cloud/firestore'; import {Aggregate, AggregateSpec} from '../aggregate'; -import {avg, count, countAll, field, sum} from '../pipelines'; +import {average, count, countAll, field, sum} from '../pipelines'; import {Pipeline} from '../pipelines'; import {Timestamp} from '../timestamp'; import {mapToArray, requestTag, wrapError} from '../util'; @@ -363,7 +363,7 @@ export class AggregateQuery< } return count(field(aggregate._field)).as(clientAlias); } else if (aggregate.aggregateType === 'avg') { - return avg(field(aggregate._field!)).as(clientAlias); + return average(field(aggregate._field!)).as(clientAlias); } else if (aggregate.aggregateType === 'sum') { return sum(field(aggregate._field!)).as(clientAlias); } else { diff --git a/dev/src/reference/vector-query.ts b/dev/src/reference/vector-query.ts index 6f6abfff0..20ecfe1e5 100644 --- a/dev/src/reference/vector-query.ts +++ b/dev/src/reference/vector-query.ts @@ -140,7 +140,11 @@ export class VectorQuery< return result; } - toPipeline(): Pipeline { + /** + * @private + * @internal + */ + _toPipeline(): Pipeline { const options: firestore.Pipelines.FindNearestStageOptions = { field: field(this._options.vectorField), vectorValue: this._options.queryVector, diff --git a/dev/src/transaction.ts b/dev/src/transaction.ts index 3d754d8bf..61dc35cc6 100644 --- a/dev/src/transaction.ts +++ b/dev/src/transaction.ts @@ -313,7 +313,7 @@ export class Transaction implements firestore.Transaction { * const futureResults = await transaction * .execute( * firestore.pipeline().collection("books") - * .where(gt(field("rating"), 4.5)) + * .where(greaterThan(field("rating"), 4.5)) * .select("title", "author", "rating")); * ``` * @@ -330,8 +330,9 @@ export class Transaction implements firestore.Transaction { this.executePipelineFn ).then(results => { const executionTime = results.reduce((maxTime, result) => { - return result.executionTime.valueOf() > maxTime.valueOf() - ? result.executionTime + return result._executionTime && + result._executionTime?.valueOf() > maxTime.valueOf() + ? result._executionTime : maxTime; }, Timestamp.fromMillis(0)); diff --git a/dev/system-test/pipeline.ts b/dev/system-test/pipeline.ts index 5c420266a..73dd7417c 100644 --- a/dev/system-test/pipeline.ts +++ b/dev/system-test/pipeline.ts @@ -19,7 +19,7 @@ import { } from '@google-cloud/firestore'; import { - BooleanExpr, + BooleanExpression, map, array, field, @@ -28,25 +28,24 @@ import { exp, xor, AggregateFunction, - rand, arrayGet, timestampToUnixMicros, timestampToUnixSeconds, unixMicrosToTimestamp, timestampToUnixMillis, - timestampSub, + timestampSubtract, timestampAdd, byteLength, multiply, sum, maximum, descending, - FunctionExpr, + FunctionExpression, minimum, count, countIf, arrayLength, - strContains, + stringContains, charLength, divide, mod, @@ -55,16 +54,12 @@ import { toUpper, toLower, vectorLength, - isNotNan, exists, - isNotNull, isAbsent, ifError, isError, - isNan, substring, documentId, - isNull, arrayContainsAll, mapRemove, mapMerge, @@ -75,32 +70,32 @@ import { arrayContains, arrayContainsAny, arrayReverse, - avg, + average, countAll, endsWith, - eq, - gt, + equal, + greaterThan, like, - lt, - neq, + lessThan, + notEqual, ascending, not, or, regexContains, regexMatch, startsWith, - strConcat, + stringConcat, subtract, cosineDistance, dotProduct, euclideanDistance, mapGet, - lte, - eqAny, - notEqAny, + lessThanOrEqual, + equalAny, + notEqualAny, logicalMinimum, logicalMaximum, - cond, + conditional, constant, PipelineResult, PipelineSnapshot, @@ -111,9 +106,16 @@ import { collectionId, length, ln, - log, sqrt, - strReverse, + stringReverse, + abs, + log10, + concat, + ifAbsent, + join, + arraySum, + currentTimestamp, + arrayConcat, // TODO(new-expression): add new expression imports above this line } from '../src/pipelines'; @@ -137,13 +139,11 @@ import {getTestDb, getTestRoot} from './firestore'; import {Firestore as InternalFirestore} from '../src'; import {ServiceError} from 'google-gax'; -import * as google from '../protos/firestore_v1_proto_api'; - use(chaiAsPromised); const timestampDeltaMS = 3000; -describe('Pipeline class', () => { +describe.skip('Pipeline class', () => { let firestore: Firestore; let randomCol: CollectionReference; let beginDocCreation = 0; @@ -421,7 +421,7 @@ describe('Pipeline class', () => { const pipeline = firestore .pipeline() .collection(randomCol.path) - .aggregate(avg('rating').as('avgRating')); + .aggregate(average('rating').as('avgRating')); const snapshot = await pipeline.execute(); const end = new Date().valueOf(); @@ -439,7 +439,7 @@ describe('Pipeline class', () => { .pipeline() .collection(randomCol.path) .aggregate({ - accumulators: [avg('rating').as('avgRating')], + accumulators: [average('rating').as('avgRating')], groups: ['genre'], }); @@ -455,7 +455,47 @@ describe('Pipeline class', () => { }); describe('pipeline explain', () => { - it('mode: analyze', async () => { + it('mode: analyze, format: text', async () => { + const ppl = firestore + .pipeline() + .collection(randomCol.path) + .sort(ascending('__name__')); + + const snapshot = await ppl.execute({ + explainOptions: { + mode: 'analyze', + outputFormat: 'text', + }, + }); + + expect(snapshot.explainStats).not.to.be.undefined; + expect(snapshot.explainStats!.text.length).to.be.greaterThan(0); + expect(snapshot.explainStats!.text.charAt(0)).not.to.equal('{'); + + expect(snapshot.explainStats!.rawData.type_url).to.equal( + 'type.googleapis.com/google.protobuf.StringValue' + ); + expect(snapshot.explainStats!.rawData.value).to.not.be.null; + expect(snapshot.explainStats!.rawData.value).to.not.be.undefined; + + expect(snapshot.results.length).to.equal(10); + expect(snapshot.pipeline).to.equal(ppl); + expectResults( + snapshot, + 'book1', + 'book10', + 'book2', + 'book3', + 'book4', + 'book5', + 'book6', + 'book7', + 'book8', + 'book9' + ); + }); + + it('mode: analyze, format: unspecified', async () => { const ppl = firestore .pipeline() .collection(randomCol.path) @@ -492,13 +532,16 @@ describe('Pipeline class', () => { ); }); - it('mode: unspecified', async () => { + it('mode: execute, format: text', async () => { const ppl = firestore .pipeline() .collection(randomCol.path) .sort(ascending('__name__')); const snapshot = await ppl.execute({ - explainOptions: {}, + explainOptions: { + mode: 'execute', + outputFormat: 'text', + }, }); expect(snapshot.explainStats).to.be.undefined; @@ -519,7 +562,7 @@ describe('Pipeline class', () => { ); }); - it('mode: undefined', async () => { + it('mode: unspecified, format: text', async () => { const ppl = firestore .pipeline() .collection(randomCol.path) @@ -623,7 +666,7 @@ describe('Pipeline class', () => { const snapshot = await firestore .pipeline() .database() - .where(eq('randomId', randomId)) + .where(equal('randomId', randomId)) .sort(ascending('order')) .execute(); expectResults(snapshot, doc1.id, doc2.id); @@ -851,7 +894,7 @@ describe('Pipeline class', () => { ) .where( and( - eq('metadataArray', [ + equal('metadataArray', [ 1, 2, field('genre'), @@ -861,7 +904,7 @@ describe('Pipeline class', () => { published: field('published'), }, ]), - eq('metadata', { + equal('metadata', { genre: field('genre'), rating: multiply('rating', 10), nestedArray: [field('title')], @@ -918,10 +961,10 @@ describe('Pipeline class', () => { snapshot = await firestore .pipeline() .collection(randomCol.path) - .where(eq('genre', 'Science Fiction')) + .where(equal('genre', 'Science Fiction')) .aggregate( countAll().as('count'), - avg('rating').as('avgRating'), + average('rating').as('avgRating'), maximum('rating').as('maxRating'), sum('rating').as('sumRating') ) @@ -934,6 +977,27 @@ describe('Pipeline class', () => { }); }); + it('throws on duplicate aliases', async () => { + expect(() => + firestore + .pipeline() + .collection(randomCol.path) + .aggregate(countAll().as('count'), count('foo').as('count')) + ).to.throw("Duplicate alias or field 'count'"); + }); + + it('throws on duplicate group aliases', async () => { + expect(() => + firestore + .pipeline() + .collection(randomCol.path) + .aggregate({ + accumulators: [countAll().as('count')], + groups: ['bax', field('bar').as('bax')], + }) + ).to.throw("Duplicate alias or field 'bax'"); + }); + it('supports aggregate options', async () => { let snapshot = await firestore .pipeline() @@ -947,10 +1011,10 @@ describe('Pipeline class', () => { snapshot = await firestore .pipeline() .collection(randomCol.path) - .where(eq('genre', 'Science Fiction')) + .where(equal('genre', 'Science Fiction')) .aggregate( countAll().as('count'), - avg('rating').as('avgRating'), + average('rating').as('avgRating'), maximum('rating').as('maxRating'), sum('rating').as('sumRating') ) @@ -968,7 +1032,7 @@ describe('Pipeline class', () => { firestore .pipeline() .collection(randomCol.path) - .where(lt('published', 1900)) + .where(lessThan('published', 1900)) .aggregate({ accumulators: [], groups: ['genre'], @@ -981,12 +1045,12 @@ describe('Pipeline class', () => { const snapshot = await firestore .pipeline() .collection(randomCol.path) - .where(lt(field('published'), 1984)) + .where(lessThan(field('published'), 1984)) .aggregate({ - accumulators: [avg('rating').as('avgRating')], + accumulators: [average('rating').as('avgRating')], groups: ['genre'], }) - .where(gt('avgRating', 4.3)) + .where(greaterThan('avgRating', 4.3)) .sort(field('avgRating').descending()) .execute(); expectResults( @@ -1020,7 +1084,7 @@ describe('Pipeline class', () => { let snapshot = await firestore .pipeline() .collection(randomCol.path) - .aggregate(countIf(field('rating').gt(4.3)).as('count')) + .aggregate(countIf(field('rating').greaterThan(4.3)).as('count')) .execute(); const expectedResults = { count: 3, @@ -1030,7 +1094,7 @@ describe('Pipeline class', () => { snapshot = await firestore .pipeline() .collection(randomCol.path) - .aggregate(field('rating').gt(4.3).countIf().as('count')) + .aggregate(field('rating').greaterThan(4.3).countIf().as('count')) .execute(); expectResults(snapshot, expectedResults); }); @@ -1125,6 +1189,16 @@ describe('Pipeline class', () => { ); }); + it('throws on duplicate aliases', async () => { + expect(() => { + firestore + .pipeline() + .collection(randomCol.path) + .limit(1) + .select(constant(1).as('foo'), constant(2).as('foo')); + }).to.throw("Duplicate alias or field 'foo'"); + }); + it('supports options', async () => { const snapshot = await firestore .pipeline() @@ -1196,6 +1270,17 @@ describe('Pipeline class', () => { ); }); + it('throws on duplicate aliases', async () => { + expect(() => + firestore + .pipeline() + .collection(randomCol.path) + .select('title', 'author') + .addFields(constant('bar').as('foo'), constant('baz').as('foo')) + .sort(field('author').ascending()) + ).to.throw("Duplicate alias or field 'foo'"); + }); + it('supports options', async () => { const snapshot = await firestore .pipeline() @@ -1258,7 +1343,6 @@ describe('Pipeline class', () => { .select('title', 'author') .sort(field('author').ascending()) .removeFields(field('author')) - .sort(field('author').ascending()) .execute(); expectResults( snapshot, @@ -1298,7 +1382,6 @@ describe('Pipeline class', () => { .removeFields({ fields: [field('author'), 'genre'], }) - .sort(field('author').ascending()) .execute(); expectResults( snapshot, @@ -1338,7 +1421,6 @@ describe('Pipeline class', () => { .select('title', 'author') .sort(field('author').ascending()) .removeFields(field('author')) - .sort(field('author').ascending()) .execute(); expectResults( snapshot, @@ -1378,7 +1460,6 @@ describe('Pipeline class', () => { .removeFields({ fields: [field('author'), 'genre'], }) - .sort(field('author').ascending()) .execute(); expectResults( snapshot, @@ -1417,8 +1498,8 @@ describe('Pipeline class', () => { .collection(randomCol.path) .where( and( - gt('rating', 4.5), - eqAny('genre', ['Science Fiction', 'Romance', 'Fantasy']) + greaterThan('rating', 4.5), + equalAny('genre', ['Science Fiction', 'Romance', 'Fantasy']) ) ) .execute(); @@ -1431,9 +1512,9 @@ describe('Pipeline class', () => { .collection(randomCol.path) .where( and( - gt('rating', 4.5), - eqAny('genre', ['Science Fiction', 'Romance', 'Fantasy']), - lt('published', 1965) + greaterThan('rating', 4.5), + equalAny('genre', ['Science Fiction', 'Romance', 'Fantasy']), + lessThan('published', 1965) ) ) .execute(); @@ -1446,9 +1527,9 @@ describe('Pipeline class', () => { .collection(randomCol.path) .where( or( - eq('genre', 'Romance'), - eq('genre', 'Dystopian'), - eq('genre', 'Fantasy') + equal('genre', 'Romance'), + equal('genre', 'Dystopian'), + equal('genre', 'Fantasy') ) ) .sort(ascending('title')) @@ -1469,10 +1550,10 @@ describe('Pipeline class', () => { .collection(randomCol.path) .where( xor( - eq('genre', 'Romance'), - eq('genre', 'Dystopian'), - eq('genre', 'Fantasy'), - eq('published', 1949) + equal('genre', 'Romance'), + equal('genre', 'Dystopian'), + equal('genre', 'Fantasy'), + equal('published', 1949) ) ) .select('title') @@ -1491,8 +1572,8 @@ describe('Pipeline class', () => { .collection(randomCol.path) .where({ condition: and( - gt('rating', 4.5), - eqAny('genre', ['Science Fiction', 'Romance', 'Fantasy']) + greaterThan('rating', 4.5), + equalAny('genre', ['Science Fiction', 'Romance', 'Fantasy']) ), }) .execute(); @@ -1598,12 +1679,17 @@ describe('Pipeline class', () => { expect('statusDetails' in err).to.be.true; expect(Array.isArray(err['statusDetails'])).to.be.true; - const explainStatsAny = ( - err['statusDetails'] as Array - )[0] as google.google.protobuf.IAny; - expect(explainStatsAny['type_url']).to.equal( - 'type.googleapis.com/google.firestore.v1.ExplainStats' - ); + + const statusDetails = err['statusDetails'] as Array; + + const foundExplainStats = statusDetails.find(x => { + return ( + 'type_url' in x && + x['type_url'] === + 'type.googleapis.com/google.firestore.v1.ExplainStats' + ); + }); + expect(foundExplainStats).to.not.be.undefined; } }); }); @@ -1641,7 +1727,7 @@ describe('Pipeline class', () => { .select('title', 'author') .rawStage('add_fields', [ { - display: strConcat('title', ' - ', field('author')), + display: stringConcat('title', ' - ', field('author')), }, ]) .execute(); @@ -1657,7 +1743,7 @@ describe('Pipeline class', () => { .pipeline() .collection(randomCol.path) .select('title', 'author') - .rawStage('where', [field('author').eq('Douglas Adams')]) + .rawStage('where', [field('author').equal('Douglas Adams')]) .execute(); expectResults(snapshot, { title: "The Hitchhiker's Guide to the Galaxy", @@ -1690,7 +1776,10 @@ describe('Pipeline class', () => { .pipeline() .collection(randomCol.path) .select('title', 'author', 'rating') - .rawStage('aggregate', [{averageRating: field('rating').avg()}, {}]) + .rawStage('aggregate', [ + {averageRating: field('rating').average()}, + {}, + ]) .execute(); expectResults(snapshot, { averageRating: 4.3100000000000005, @@ -1768,7 +1857,7 @@ describe('Pipeline class', () => { const snapshot = await firestore .pipeline() .collection(randomCol.path) - .where(eq('title', "The Hitchhiker's Guide to the Galaxy")) + .where(equal('title', "The Hitchhiker's Guide to the Galaxy")) .replaceWith('awards') .execute(); expectResults(snapshot, { @@ -1778,11 +1867,11 @@ describe('Pipeline class', () => { }); }); - it('run pipeline with replaceWith Expr result', async () => { + it('run pipeline with replaceWith Expression result', async () => { const snapshot = await firestore .pipeline() .collection(randomCol.path) - .where(eq('title', "The Hitchhiker's Guide to the Galaxy")) + .where(equal('title', "The Hitchhiker's Guide to the Galaxy")) .replaceWith( map({ foo: 'bar', @@ -1802,7 +1891,7 @@ describe('Pipeline class', () => { const snapshot = await firestore .pipeline() .collection(randomCol.path) - .where(eq('title', "The Hitchhiker's Guide to the Galaxy")) + .where(equal('title', "The Hitchhiker's Guide to the Galaxy")) .replaceWith({map: 'awards'}) .execute(); expectResults(snapshot, { @@ -1920,7 +2009,7 @@ describe('Pipeline class', () => { const snapshot = await firestore .pipeline() .collection(randomCol.path) - .where(eq('title', "The Hitchhiker's Guide to the Galaxy")) + .where(equal('title', "The Hitchhiker's Guide to the Galaxy")) .unnest(field('tags').as('tag')) .select( 'title', @@ -1988,7 +2077,7 @@ describe('Pipeline class', () => { const snapshot = await firestore .pipeline() .collection(randomCol.path) - .where(eq('title', "The Hitchhiker's Guide to the Galaxy")) + .where(equal('title', "The Hitchhiker's Guide to the Galaxy")) .unnest(field('tags').as('tag'), 'tagsIndex') .select( 'title', @@ -1999,7 +2088,8 @@ describe('Pipeline class', () => { 'tags', 'tag', 'awards', - 'nestedField' + 'nestedField', + 'tagsIndex' ) .execute(); expectResults( @@ -2059,7 +2149,7 @@ describe('Pipeline class', () => { const snapshot = await firestore .pipeline() .collection(randomCol.path) - .where(eq('title', "The Hitchhiker's Guide to the Galaxy")) + .where(equal('title', "The Hitchhiker's Guide to the Galaxy")) .unnest(array([1, 2, 3]).as('copy')) .select( 'title', @@ -2127,7 +2217,7 @@ describe('Pipeline class', () => { const snapshot = await firestore .pipeline() .collection(randomCol.path) - .where(eq('title', "The Hitchhiker's Guide to the Galaxy")) + .where(equal('title', "The Hitchhiker's Guide to the Galaxy")) .unnest({ selectable: field('tags').as('tag'), indexField: 'tagsIndex', @@ -2141,7 +2231,8 @@ describe('Pipeline class', () => { 'tags', 'tag', 'awards', - 'nestedField' + 'nestedField', + 'tagsIndex' ) .execute(); expectResults( @@ -2301,34 +2392,38 @@ describe('Pipeline class', () => { ); }); - it('cond works', async () => { + it('conditional works', async () => { const snapshot = await firestore .pipeline() .collection(randomCol.path) .select( 'title', - cond( - lt(field('published'), 1960), + conditional( + lessThan(field('published'), 1960), constant(1960), field('published') - ).as('published-safe') + ).as('published-safe'), + field('rating') + .greaterThanOrEqual(4.5) + .conditional(constant('great'), constant('good')) + .as('rating') ) .sort(field('title').ascending()) .limit(3) .execute(); expectResults( snapshot, - {title: '1984', 'published-safe': 1960}, - {title: 'Crime and Punishment', 'published-safe': 1960}, - {title: 'Dune', 'published-safe': 1965} + {title: '1984', 'published-safe': 1960, rating: 'good'}, + {title: 'Crime and Punishment', 'published-safe': 1960, rating: 'good'}, + {title: 'Dune', 'published-safe': 1965, rating: 'great'} ); }); - it('eqAny works', async () => { + it('equalAny works', async () => { const snapshot = await firestore .pipeline() .collection(randomCol.path) - .where(eqAny('published', [1979, 1999, 1967])) + .where(equalAny('published', [1979, 1999, 1967])) .sort(descending('title')) .select('title') .execute(); @@ -2339,12 +2434,12 @@ describe('Pipeline class', () => { ); }); - it('notEqAny works', async () => { + it('notEqualAny works', async () => { const snapshot = await firestore .pipeline() .collection(randomCol.path) .where( - notEqAny( + notEqualAny( 'published', [1965, 1925, 1949, 1960, 1866, 1985, 1954, 1967, 1979] ) @@ -2396,7 +2491,7 @@ describe('Pipeline class', () => { .pipeline() .collection(randomCol.path) .select(arrayLength('tags').as('tagsCount')) - .where(eq('tagsCount', 3)) + .where(equal('tagsCount', 3)) .execute(); expect(snapshot.results.length).to.equal(10); }); @@ -2406,7 +2501,9 @@ describe('Pipeline class', () => { .pipeline() .collection(randomCol.path) .sort(ascending('author')) - .select(field('author').strConcat(' - ', field('title')).as('bookInfo')) + .select( + field('author').stringConcat(' - ', field('title')).as('bookInfo') + ) .limit(1) .execute(); expectResults(snapshot, { @@ -2450,7 +2547,7 @@ describe('Pipeline class', () => { const snapshot = await firestore .pipeline() .collection(randomCol.path) - .where(strContains('title', "'s")) + .where(stringContains('title', "'s")) .select('title') .sort(field('title').ascending()) .execute(); @@ -2466,7 +2563,7 @@ describe('Pipeline class', () => { .pipeline() .collection(randomCol.path) .select(charLength('title').as('titleLength'), field('title')) - .where(gt('titleLength', 20)) + .where(greaterThan('titleLength', 20)) .sort(field('title').ascending()) .execute(); @@ -2526,7 +2623,7 @@ describe('Pipeline class', () => { const snapshot = await firestore .pipeline() .collection(randomCol.path) - .where(eq('title', 'To Kill a Mockingbird')) + .where(equal('title', 'To Kill a Mockingbird')) .select( add(field('rating'), 1).as('ratingPlusOne'), subtract(field('published'), 1900).as('yearsSince1900'), @@ -2555,9 +2652,9 @@ describe('Pipeline class', () => { .collection(randomCol.path) .where( and( - gt('rating', 4.2), - lte(field('rating'), 4.5), - neq('genre', 'Science Fiction') + greaterThan('rating', 4.2), + lessThanOrEqual(field('rating'), 4.5), + notEqual('genre', 'Science Fiction') ) ) .select('rating', 'title') @@ -2580,8 +2677,8 @@ describe('Pipeline class', () => { .collection(randomCol.path) .where( or( - and(gt('rating', 4.5), eq('genre', 'Science Fiction')), - lt('published', 1900) + and(greaterThan('rating', 4.5), equal('genre', 'Science Fiction')), + lessThan('published', 1900) ) ) .select('title') @@ -2602,13 +2699,21 @@ describe('Pipeline class', () => { .sort(field('rating').descending()) .limit(1) .select( - isNull('rating').as('ratingIsNull'), - isNan('rating').as('ratingIsNaN'), - isError(arrayGet('title', 0)).as('isError'), - ifError(arrayGet('title', 0), constant('was error')).as('ifError'), + equal('rating', null).as('ratingIsNull'), + equal('rating', NaN).as('ratingIsNaN'), + isError(divide(constant(1), constant(0))).as('isError'), + ifError(divide(constant(1), constant(0)), constant('was error')).as( + 'ifError' + ), + ifError( + divide(constant(1), constant(0)).greaterThan(1), + constant(true) + ) + .not() + .as('ifErrorBooleanExpression'), isAbsent('foo').as('isAbsent'), - isNotNull('title').as('titleIsNotNull'), - isNotNan('cost').as('costIsNotNan'), + notEqual('title', null).as('titleIsNotNull'), + notEqual('cost', NaN).as('costIsNotNan'), exists('fooBarBaz').as('fooBarBazExists'), field('title').exists().as('titleExists') ) @@ -2618,6 +2723,7 @@ describe('Pipeline class', () => { ratingIsNaN: false, isError: true, ifError: 'was error', + ifErrorBooleanExpression: false, isAbsent: true, titleIsNotNull: true, costIsNotNan: false, @@ -2631,13 +2737,20 @@ describe('Pipeline class', () => { .sort(field('rating').descending()) .limit(1) .select( - field('rating').isNull().as('ratingIsNull'), - field('rating').isNan().as('ratingIsNaN'), - arrayGet('title', 0).isError().as('isError'), - arrayGet('title', 0).ifError(constant('was error')).as('ifError'), + field('rating').equal(null).as('ratingIsNull'), + field('rating').equal(NaN).as('ratingIsNaN'), + divide(constant(1), constant(0)).isError().as('isError'), + divide(constant(1), constant(0)) + .ifError(constant('was error')) + .as('ifError'), + divide(constant(1), constant(0)) + .greaterThan(1) + .ifError(constant(true)) + .not() + .as('ifErrorBooleanExpression'), field('foo').isAbsent().as('isAbsent'), - field('title').isNotNull().as('titleIsNotNull'), - field('cost').isNotNan().as('costIsNotNan') + field('title').notEqual(null).as('titleIsNotNull'), + field('cost').notEqual(NaN).as('costIsNotNan') ) .execute(); expectResults(snapshot, { @@ -2645,6 +2758,7 @@ describe('Pipeline class', () => { ratingIsNaN: false, isError: true, ifError: 'was error', + ifErrorBooleanExpression: false, isAbsent: true, titleIsNotNull: true, costIsNotNan: false, @@ -2661,7 +2775,7 @@ describe('Pipeline class', () => { field('awards').mapGet('others').as('others'), field('title') ) - .where(eq('hugoAward', true)) + .where(equal('hugoAward', true)) .execute(); expectResults( snapshot, @@ -2670,7 +2784,7 @@ describe('Pipeline class', () => { title: "The Hitchhiker's Guide to the Galaxy", others: {unknown: {year: 1980}}, }, - {hugoAward: true, title: 'Dune', others: null} + {hugoAward: true, title: 'Dune'} ); }); @@ -2744,7 +2858,7 @@ describe('Pipeline class', () => { const snapshot = await firestore .pipeline() .collection(randomCol.path) - .where(eq('awards.hugo', true)) + .where(equal('awards.hugo', true)) .sort(descending('title')) .select('title', 'awards.hugo') .execute(); @@ -2762,23 +2876,32 @@ describe('Pipeline class', () => { const snapshot = await firestore .pipeline() .collection(randomCol.path) - .where(eq('awards.hugo', true)) + .limit(1) + .replaceWith( + map({ + title: 'foo', + nested: { + level: { + '1': 'bar', + }, + 'level.1': { + 'level.2': 'baz', + }, + }, + }) + ) .select( 'title', - field('nestedField.level.1'), - mapGet('nestedField', 'level.1').mapGet('level.2').as('nested') + field('nested.level.1'), + mapGet('nested', 'level.1').mapGet('level.2').as('nested') ) - .sort(descending('title')) .execute(); - expectResults( - snapshot, - { - title: "The Hitchhiker's Guide to the Galaxy", - 'nestedField.level.`1`': null, - nested: true, - }, - {title: 'Dune', 'nestedField.level.`1`': null, nested: null} - ); + + expectResults(snapshot, { + title: 'foo', + 'nested.level.`1`': 'bar', + nested: 'baz', + }); }); describe('genericFunction', () => { @@ -2789,7 +2912,9 @@ describe('Pipeline class', () => { .sort(descending('rating')) .limit(1) .select( - new FunctionExpr('add', [field('rating'), constant(1)]).as('rating') + new FunctionExpression('add', [field('rating'), constant(1)]).as( + 'rating' + ) ) .execute(); expectResults(snapshot, { @@ -2802,9 +2927,9 @@ describe('Pipeline class', () => { .pipeline() .collection(randomCol.path) .where( - new BooleanExpr('and', [ - field('rating').gt(0), - field('title').charLength().lt(5), + new BooleanExpression('and', [ + field('rating').greaterThan(0), + field('title').charLength().lessThan(5), field('tags').arrayContains('propaganda'), ]) ) @@ -2820,7 +2945,7 @@ describe('Pipeline class', () => { .pipeline() .collection(randomCol.path) .where( - new BooleanExpr('array_contains_any', [ + new BooleanExpression('array_contains_any', [ field('tags'), array(['politics']), ]) @@ -2837,9 +2962,9 @@ describe('Pipeline class', () => { .pipeline() .collection(randomCol.path) .aggregate( - new AggregateFunction('count_if', [field('rating').gte(4.5)]).as( - 'countOfBest' - ) + new AggregateFunction('count_if', [ + field('rating').greaterThanOrEqual(4.5), + ]).as('countOfBest') ) .execute(); expectResults(snapshot, { @@ -2852,7 +2977,7 @@ describe('Pipeline class', () => { .pipeline() .collection(randomCol.path) .sort( - new FunctionExpr('char_length', [field('title')]).ascending(), + new FunctionExpression('char_length', [field('title')]).ascending(), descending('__name__') ) .limit(3) @@ -2873,20 +2998,6 @@ describe('Pipeline class', () => { }); }); - it('supports Rand', async () => { - const snapshot = await firestore - .pipeline() - .collection(randomCol.path) - .limit(10) - .select(rand().as('result')) - .execute(); - expect(snapshot.results.length).to.equal(10); - snapshot.results.forEach((d: PipelineResult) => { - expect(d.get('result')).to.be.lt(1); - expect(d.get('result')).to.be.gte(0); - }); - }); - it('supports array', async () => { const snapshot = await firestore .pipeline() @@ -3087,12 +3198,12 @@ describe('Pipeline class', () => { timestampAdd('timestamp', 'second', 10).as('plus10seconds'), timestampAdd('timestamp', 'microsecond', 10).as('plus10micros'), timestampAdd('timestamp', 'millisecond', 10).as('plus10millis'), - timestampSub('timestamp', 'day', 10).as('minus10days'), - timestampSub('timestamp', 'hour', 10).as('minus10hours'), - timestampSub('timestamp', 'minute', 10).as('minus10minutes'), - timestampSub('timestamp', 'second', 10).as('minus10seconds'), - timestampSub('timestamp', 'microsecond', 10).as('minus10micros'), - timestampSub('timestamp', 'millisecond', 10).as('minus10millis') + timestampSubtract('timestamp', 'day', 10).as('minus10days'), + timestampSubtract('timestamp', 'hour', 10).as('minus10hours'), + timestampSubtract('timestamp', 'minute', 10).as('minus10minutes'), + timestampSubtract('timestamp', 'second', 10).as('minus10seconds'), + timestampSubtract('timestamp', 'microsecond', 10).as('minus10micros'), + timestampSubtract('timestamp', 'millisecond', 10).as('minus10millis') ) .execute(); expectResults(snapshot, { @@ -3131,7 +3242,7 @@ describe('Pipeline class', () => { .collection(randomCol) .limit(1) .select(constant(true).as('trueField')) - .select('trueField', not(eq('trueField', true)).as('falseField')) + .select('trueField', not(equal('trueField', true)).as('falseField')) .execute(); expectResults(snapshot, { @@ -3144,7 +3255,7 @@ describe('Pipeline class', () => { const snapshot = await firestore .pipeline() .collection(randomCol.path) - .where(field('title').eq("The Hitchhiker's Guide to the Galaxy")) + .where(field('title').equal("The Hitchhiker's Guide to the Galaxy")) .limit(1) .select(field('tags').arrayReverse().as('reversedTags')) .execute(); @@ -3157,7 +3268,7 @@ describe('Pipeline class', () => { const snapshot = await firestore .pipeline() .collection(randomCol.path) - .where(field('title').eq("The Hitchhiker's Guide to the Galaxy")) + .where(field('title').equal("The Hitchhiker's Guide to the Galaxy")) .limit(1) .select(arrayReverse('tags').as('reversedTags')) .execute(); @@ -3170,7 +3281,7 @@ describe('Pipeline class', () => { const snapshot = await firestore .pipeline() .collection(randomCol.path) - .where(field('title').eq("The Hitchhiker's Guide to the Galaxy")) + .where(field('title').equal("The Hitchhiker's Guide to the Galaxy")) .limit(1) .select(field('rating').ceil().as('ceilingRating')) .execute(); @@ -3183,7 +3294,7 @@ describe('Pipeline class', () => { const snapshot = await firestore .pipeline() .collection(randomCol.path) - .where(field('title').eq("The Hitchhiker's Guide to the Galaxy")) + .where(field('title').equal("The Hitchhiker's Guide to the Galaxy")) .limit(1) .select(ceil('rating').as('ceilingRating')) .execute(); @@ -3196,7 +3307,7 @@ describe('Pipeline class', () => { const snapshot = await firestore .pipeline() .collection(randomCol.path) - .where(field('title').eq("The Hitchhiker's Guide to the Galaxy")) + .where(field('title').equal("The Hitchhiker's Guide to the Galaxy")) .limit(1) .select(field('rating').floor().as('floorRating')) .execute(); @@ -3209,7 +3320,7 @@ describe('Pipeline class', () => { const snapshot = await firestore .pipeline() .collection(randomCol.path) - .where(field('title').eq("The Hitchhiker's Guide to the Galaxy")) + .where(field('title').equal("The Hitchhiker's Guide to the Galaxy")) .limit(1) .select(floor('rating').as('floorRating')) .execute(); @@ -3222,20 +3333,21 @@ describe('Pipeline class', () => { const snapshot = await firestore .pipeline() .collection(randomCol.path) - .where(field('title').eq('The Lord of the Rings')) + .where(field('title').equal('The Lord of the Rings')) .limit(1) .select(field('rating').exp().as('expRating')) .execute(); - expectResults(snapshot, { - expRating: 109.94717245212352, - }); + expect(snapshot.results[0].get('expRating')).to.be.approximately( + 109.94717245212352, + 0.00001 + ); }); it('can compute e to the power of a numeric value with the top-level function', async () => { const snapshot = await firestore .pipeline() .collection(randomCol.path) - .where(field('title').eq('The Lord of the Rings')) + .where(field('title').equal('The Lord of the Rings')) .limit(1) .select(exp('rating').as('expRating')) .execute(); @@ -3249,7 +3361,7 @@ describe('Pipeline class', () => { const snapshot = await firestore .pipeline() .collection(randomCol.path) - .where(field('title').eq("The Hitchhiker's Guide to the Galaxy")) + .where(field('title').equal("The Hitchhiker's Guide to the Galaxy")) .limit(1) .select(field('rating').pow(2).as('powerRating')) .execute(); @@ -3263,7 +3375,7 @@ describe('Pipeline class', () => { const snapshot = await firestore .pipeline() .collection(randomCol.path) - .where(field('title').eq("The Hitchhiker's Guide to the Galaxy")) + .where(field('title').equal("The Hitchhiker's Guide to the Galaxy")) .limit(1) .select(pow('rating', 2).as('powerRating')) .execute(); @@ -3277,7 +3389,7 @@ describe('Pipeline class', () => { const snapshot = await firestore .pipeline() .collection(randomCol.path) - .where(field('title').eq("The Hitchhiker's Guide to the Galaxy")) + .where(field('title').equal("The Hitchhiker's Guide to the Galaxy")) .limit(1) .select(field('rating').round().as('roundedRating')) .execute(); @@ -3290,7 +3402,7 @@ describe('Pipeline class', () => { const snapshot = await firestore .pipeline() .collection(randomCol.path) - .where(field('title').eq("The Hitchhiker's Guide to the Galaxy")) + .where(field('title').equal("The Hitchhiker's Guide to the Galaxy")) .limit(1) .select(round('rating').as('roundedRating')) .execute(); @@ -3303,7 +3415,7 @@ describe('Pipeline class', () => { const snapshot = await firestore .pipeline() .collection(randomCol.path) - .where(field('title').eq("The Hitchhiker's Guide to the Galaxy")) + .where(field('title').equal("The Hitchhiker's Guide to the Galaxy")) .limit(1) .addFields(constant(1.5).as('positiveHalf')) .select(field('positiveHalf').round().as('roundedRating')) @@ -3317,7 +3429,7 @@ describe('Pipeline class', () => { const snapshot = await firestore .pipeline() .collection(randomCol.path) - .where(field('title').eq("The Hitchhiker's Guide to the Galaxy")) + .where(field('title').equal("The Hitchhiker's Guide to the Galaxy")) .limit(1) .addFields(constant(-1.5).as('negativeHalf')) .select(field('negativeHalf').round().as('roundedRating')) @@ -3327,6 +3439,31 @@ describe('Pipeline class', () => { }); }); + it('can round a numeric value to specified precision', async () => { + const snapshot = await firestore + .pipeline() + .collection(randomCol.path) + .limit(1) + .replaceWith( + map({ + foo: 4.123456, + }) + ) + .select( + field('foo').round(0).as('0'), + round('foo', 1).as('1'), + round('foo', constant(2)).as('2'), + round(field('foo'), 4).as('4') + ) + .execute(); + expectResults(snapshot, { + '0': 4, + '1': 4.1, + '2': 4.12, + '4': 4.1235, + }); + }); + it('can get the collectionId from a path', async () => { const snapshot = await firestore .pipeline() @@ -3355,7 +3492,7 @@ describe('Pipeline class', () => { const snapshot = await firestore .pipeline() .collection(randomCol.path) - .where(field('title').eq("The Hitchhiker's Guide to the Galaxy")) + .where(field('title').equal("The Hitchhiker's Guide to the Galaxy")) .limit(1) .select(field('title').length().as('titleLength')) .execute(); @@ -3368,7 +3505,7 @@ describe('Pipeline class', () => { const snapshot = await firestore .pipeline() .collection(randomCol.path) - .where(field('title').eq("The Hitchhiker's Guide to the Galaxy")) + .where(field('title').equal("The Hitchhiker's Guide to the Galaxy")) .limit(1) .select(length('title').as('titleLength')) .execute(); @@ -3381,7 +3518,7 @@ describe('Pipeline class', () => { const snapshot = await firestore .pipeline() .collection(randomCol.path) - .where(field('title').eq("The Hitchhiker's Guide to the Galaxy")) + .where(field('title').equal("The Hitchhiker's Guide to the Galaxy")) .limit(1) .select(field('tags').length().as('tagsLength')) .execute(); @@ -3394,7 +3531,7 @@ describe('Pipeline class', () => { const snapshot = await firestore .pipeline() .collection(randomCol.path) - .where(field('title').eq("The Hitchhiker's Guide to the Galaxy")) + .where(field('title').equal("The Hitchhiker's Guide to the Galaxy")) .limit(1) .select(length('tags').as('tagsLength')) .execute(); @@ -3407,7 +3544,7 @@ describe('Pipeline class', () => { const snapshot = await firestore .pipeline() .collection(randomCol.path) - .where(field('title').eq("The Hitchhiker's Guide to the Galaxy")) + .where(field('title').equal("The Hitchhiker's Guide to the Galaxy")) .limit(1) .select(field('awards').length().as('awardsLength')) .execute(); @@ -3420,7 +3557,7 @@ describe('Pipeline class', () => { const snapshot = await firestore .pipeline() .collection(randomCol.path) - .where(field('title').eq("The Hitchhiker's Guide to the Galaxy")) + .where(field('title').equal("The Hitchhiker's Guide to the Galaxy")) .limit(1) .select(field('embedding').length().as('embeddingLength')) .execute(); @@ -3446,7 +3583,7 @@ describe('Pipeline class', () => { const snapshot = await firestore .pipeline() .collection(randomCol.path) - .where(field('title').eq("The Hitchhiker's Guide to the Galaxy")) + .where(field('title').equal("The Hitchhiker's Guide to the Galaxy")) .limit(1) .select(field('rating').ln().as('lnRating')) .execute(); @@ -3457,7 +3594,7 @@ describe('Pipeline class', () => { const snapshot = await firestore .pipeline() .collection(randomCol.path) - .where(field('title').eq("The Hitchhiker's Guide to the Galaxy")) + .where(field('title').equal("The Hitchhiker's Guide to the Galaxy")) .limit(1) .select(ln('rating').as('lnRating')) .execute(); @@ -3468,7 +3605,7 @@ describe('Pipeline class', () => { const snapshot = await firestore .pipeline() .collection(randomCol.path) - .where(field('title').eq("The Hitchhiker's Guide to the Galaxy")) + .where(field('title').equal("The Hitchhiker's Guide to the Galaxy")) .limit(1) .select(ln('rating').as('lnRating')) .execute(); @@ -3477,37 +3614,11 @@ describe('Pipeline class', () => { }); }); - it('can compute the logarithm of a numeric value', async () => { - const snapshot = await firestore - .pipeline() - .collection(randomCol.path) - .where(field('title').eq("The Hitchhiker's Guide to the Galaxy")) - .limit(1) - .select(field('rating').log(10).as('logRating')) - .execute(); - expectResults(snapshot, { - logRating: 0.6232492903979004, - }); - }); - - it('can compute the logarithm of a numeric value with the top-level function', async () => { - const snapshot = await firestore - .pipeline() - .collection(randomCol.path) - .where(field('title').eq("The Hitchhiker's Guide to the Galaxy")) - .limit(1) - .select(log('rating', 10).as('logRating')) - .execute(); - expectResults(snapshot, { - logRating: 0.6232492903979004, - }); - }); - it('can round a numeric value', async () => { const snapshot = await firestore .pipeline() .collection(randomCol.path) - .where(field('title').eq("The Hitchhiker's Guide to the Galaxy")) + .where(field('title').equal("The Hitchhiker's Guide to the Galaxy")) .limit(1) .select(field('rating').round().as('roundedRating')) .execute(); @@ -3520,7 +3631,7 @@ describe('Pipeline class', () => { const snapshot = await firestore .pipeline() .collection(randomCol.path) - .where(field('title').eq("The Hitchhiker's Guide to the Galaxy")) + .where(field('title').equal("The Hitchhiker's Guide to the Galaxy")) .limit(1) .select(round('rating').as('roundedRating')) .execute(); @@ -3533,7 +3644,7 @@ describe('Pipeline class', () => { const snapshot = await firestore .pipeline() .collection(randomCol.path) - .where(field('title').eq("The Hitchhiker's Guide to the Galaxy")) + .where(field('title').equal("The Hitchhiker's Guide to the Galaxy")) .limit(1) .select(field('rating').sqrt().as('sqrtRating')) .execute(); @@ -3546,7 +3657,7 @@ describe('Pipeline class', () => { const snapshot = await firestore .pipeline() .collection(randomCol.path) - .where(field('title').eq("The Hitchhiker's Guide to the Galaxy")) + .where(field('title').equal("The Hitchhiker's Guide to the Galaxy")) .limit(1) .select(sqrt('rating').as('sqrtRating')) .execute(); @@ -3559,9 +3670,9 @@ describe('Pipeline class', () => { const snapshot = await firestore .pipeline() .collection(randomCol.path) - .where(field('title').eq("The Hitchhiker's Guide to the Galaxy")) + .where(field('title').equal("The Hitchhiker's Guide to the Galaxy")) .limit(1) - .select(field('title').strReverse().as('reversedTitle')) + .select(field('title').stringReverse().as('reversedTitle')) .execute(); expectResults(snapshot, { reversedTitle: "yxalaG eht ot ediuG s'rekihhctiH ehT", @@ -3572,9 +3683,9 @@ describe('Pipeline class', () => { const snapshot = await firestore .pipeline() .collection(randomCol.path) - .where(field('title').eq("The Hitchhiker's Guide to the Galaxy")) + .where(field('title').equal("The Hitchhiker's Guide to the Galaxy")) .limit(1) - .select(strReverse('title').as('reversedTitle')) + .select(stringReverse('title').as('reversedTitle')) .execute(); expectResults(snapshot, { reversedTitle: "yxalaG eht ot ediuG s'rekihhctiH ehT", @@ -3589,12 +3700,14 @@ describe('Pipeline class', () => { .limit(1) .select( documentId(field('__name__')).as('docId'), - documentId(field('__path__')).as('noDocId') + documentId(field('__path__')).as('noDocId'), + documentId(randomCol.doc('foo')).as('fromDocRef') ) .execute(); expectResults(snapshot, { docId: 'book4', noDocId: null, + fromDocRef: 'foo', }); snapshot = await firestore .pipeline() @@ -3654,6 +3767,33 @@ describe('Pipeline class', () => { }); }); + it('arrayConcat works', async () => { + const snapshot = await firestore + .pipeline() + .collection(randomCol.path) + .where(field('title').equal("The Hitchhiker's Guide to the Galaxy")) + .select( + arrayConcat('tags', ['newTag1', 'newTag2'], field('tags'), [null]).as( + 'modifiedTags' + ) + ) + .limit(1) + .execute(); + expectResults(snapshot, { + modifiedTags: [ + 'comedy', + 'space', + 'adventure', + 'newTag1', + 'newTag2', + 'comedy', + 'space', + 'adventure', + null, + ], + }); + }); + it('test toLower', async () => { const snapshot = await firestore .pipeline() @@ -3698,13 +3838,168 @@ describe('Pipeline class', () => { const snapshot = await firestore .pipeline() .collection(randomCol.path) - .where(eq('title', '1984')) + .where(equal('title', '1984')) .limit(1) .select(reverse('title').as('reverseTitle')) .execute(); expectResults(snapshot, {reverseTitle: '4891'}); }); + it('testAbs', async () => { + const snapshot = await firestore + .pipeline() + .collection(randomCol.path) + .limit(1) + .select( + constant(-10).as('neg10'), + constant(-22.22).as('neg22'), + constant(1).as('pos1') + ) + .select( + abs('neg10').as('10'), + abs(field('neg22')).as('22'), + field('pos1').as('1') + ) + .execute(); + expectResults(snapshot, { + '10': 10, + '22': 22.22, + '1': 1, + }); + }); + + it('can compute the base-10 logarithm of a numeric value', async () => { + const snapshot = await firestore + .pipeline() + .collection(randomCol.path) + .where(field('title').equal('The Lord of the Rings')) + .limit(1) + .select(field('rating').log10().as('log10Rating')) + .execute(); + expect(snapshot.results[0]!.data().log10Rating).to.be.closeTo( + 0.672, + 0.001 + ); + }); + + it('can compute the base-10 logarithm of a numeric value with the top-level function', async () => { + const snapshot = await firestore + .pipeline() + .collection(randomCol.path) + .where(field('title').equal('The Lord of the Rings')) + .limit(1) + .select(log10('rating').as('log10Rating')) + .execute(); + expect(snapshot.results[0]!.data().log10Rating).to.be.closeTo( + 0.672, + 0.001 + ); + }); + + it('can concat fields', async () => { + const snapshot = await firestore + .pipeline() + .collection(randomCol.path) + .addFields( + concat('author', ' ', field('title')).as('display'), + field('author').concat(': ', field('title')).as('display2') + ) + .where(equal('author', 'Douglas Adams')) + .select('display', 'display2') + .execute(); + expectResults(snapshot, { + display: "Douglas Adams The Hitchhiker's Guide to the Galaxy", + display2: "Douglas Adams: The Hitchhiker's Guide to the Galaxy", + }); + }); + + it('supports currentTimestamp', async () => { + const snapshot = await firestore + .pipeline() + .collection(randomCol.path) + .limit(1) + .addFields(currentTimestamp().as('now')) + .select('now') + .execute(); + const now = snapshot.results[0].get('now') as Timestamp; + expect(now).instanceof(Timestamp); + expect( + now.toDate().getUTCSeconds() - new Date().getUTCSeconds() + ).lessThan(5000); + }); + + it('supports ifAbsent', async () => { + const snapshot = await firestore + .pipeline() + .collection(randomCol.path) + .limit(1) + .replaceWith( + map({ + title: 'foo', + }) + ) + .select( + ifAbsent('title', 'default title').as('title'), + field('name').ifAbsent('default name').as('name'), + field('name').ifAbsent(field('title')).as('nameOrTitle') + ) + .execute(); + + expectResults(snapshot, { + title: 'foo', + name: 'default name', + nameOrTitle: 'foo', + }); + }); + + it('supports join', async () => { + const snapshot = await firestore + .pipeline() + .collection(randomCol.path) + .limit(1) + .replaceWith( + map({ + tags: ['foo', 'bar', 'baz'], + delimeter: '|', + }) + ) + .select(join('tags', ',').as('csv'), field('tags').join('|').as('or')) + .execute(); + + expectResults(snapshot, { + csv: 'foo,bar,baz', + or: 'foo|bar|baz', + }); + }); + + it('can compute the sum of the elements in an array', async () => { + const snapshot = await firestore + .pipeline() + .collection(randomCol.path) + .where(field('title').equal('The Lord of the Rings')) + .limit(1) + .addFields(array([150, 200]).as('sales')) + .select(field('sales').arraySum().as('totalSales')) + .execute(); + expectResults(snapshot, { + totalSales: 350, + }); + }); + + it('can compute the sum of the elements in an array with the top-level function', async () => { + const snapshot = await firestore + .pipeline() + .collection(randomCol.path) + .where(field('title').equal('The Lord of the Rings')) + .limit(1) + .addFields(array([150, 200]).as('sales')) + .select(arraySum('sales').as('totalSales')) + .execute(); + expectResults(snapshot, { + totalSales: 350, + }); + }); + // TODO(new-expression): Add new expression tests above this line }); @@ -3793,10 +4088,10 @@ describe('Pipeline class', () => { .where( or( and( - field('rating').eq(lastDoc.get('rating')), - field('__name__').gt(lastDoc.ref) + field('rating').equal(lastDoc.get('rating')), + field('__name__').greaterThan(lastDoc.ref) ), - field('rating').lt(lastDoc.get('rating')) + field('rating').lessThan(lastDoc.get('rating')) ) ) .limit(pageSize) @@ -3980,7 +4275,7 @@ describe('Pipeline class', () => { // This is the Query integration tests from the lite API (no cache support) // with some additional test cases added for more complete coverage. -describe('Query to Pipeline', () => { +describe.skip('Query to Pipeline', () => { async function execute(ppl: Pipeline): Promise { return ppl.execute(); } @@ -4497,7 +4792,7 @@ describe('Query to Pipeline', () => { }); }); - it('supports eq nan', () => { + it('supports equal nan', () => { return testCollectionWithDocs( { 1: {foo: 1, bar: NaN}, @@ -4506,13 +4801,16 @@ describe('Query to Pipeline', () => { }, async (collRef, db) => { const query1 = collRef.where('bar', '==', NaN); + const classicSnapshot = await query1.get(); + const classicData = classicSnapshot.docs.map(d => d.data()); + const snapshot = await execute(db.pipeline().createFrom(query1)); - verifyResults(snapshot, {foo: 1, bar: NaN}); + verifyResults(snapshot, ...classicData); } ); }); - it('supports neq nan', () => { + it('supports notEqual nan', () => { return testCollectionWithDocs( { 1: {foo: 1, bar: NaN}, @@ -4521,13 +4819,17 @@ describe('Query to Pipeline', () => { }, async (collRef, db) => { const query1 = collRef.where('bar', '!=', NaN); + + const classicSnapshot = await query1.get(); + const classicData = classicSnapshot.docs.map(d => d.data()); + const snapshot = await execute(db.pipeline().createFrom(query1)); - verifyResults(snapshot, {foo: 2, bar: 1}); + verifyResults(snapshot, ...classicData); } ); }); - it('supports eq null', () => { + it('supports equal null', () => { return testCollectionWithDocs( { 1: {foo: 1, bar: null}, @@ -4535,13 +4837,16 @@ describe('Query to Pipeline', () => { }, async (collRef, db) => { const query1 = collRef.where('bar', '==', null); + const classicSnapshot = await query1.get(); + const classicData = classicSnapshot.docs.map(d => d.data()); + const snapshot = await execute(db.pipeline().createFrom(query1)); - verifyResults(snapshot, {foo: 1, bar: null}); + verifyResults(snapshot, ...classicData); } ); }); - it('supports neq null', () => { + it('supports notEqual null', () => { return testCollectionWithDocs( { 1: {foo: 1, bar: null}, @@ -4549,13 +4854,15 @@ describe('Query to Pipeline', () => { }, async (collRef, db) => { const query1 = collRef.where('bar', '!=', null); + const classicSnapshot = await query1.get(); + const classicData = classicSnapshot.docs.map(d => d.data()); const snapshot = await execute(db.pipeline().createFrom(query1)); - verifyResults(snapshot, {foo: 2, bar: 1}); + verifyResults(snapshot, ...classicData); } ); }); - it('supports neq', () => { + it('supports notEqual', () => { return testCollectionWithDocs( { 1: {foo: 1, bar: 0}, diff --git a/dev/system-test/query.ts b/dev/system-test/query.ts index 877016419..a5acbce28 100644 --- a/dev/system-test/query.ts +++ b/dev/system-test/query.ts @@ -128,7 +128,7 @@ describe('Query class', () => { query: VectorQuery ): Promise { const queryResults = await query.get(); - const pipeline = query.toPipeline(); + const pipeline = query.query.firestore.pipeline().createFrom(query); const pipelineResults = await pipeline.execute(); expect(pipelineResults.results.map(r => r._fieldsProto)).to.deep.equal( diff --git a/dev/test/pipelines/pipeline.ts b/dev/test/pipelines/pipeline.ts index 69b9a3b84..b0106f57f 100644 --- a/dev/test/pipelines/pipeline.ts +++ b/dev/test/pipelines/pipeline.ts @@ -399,7 +399,7 @@ describe('stage option serialization', () => { .pipeline() .database() .where({ - condition: field('foo').eq(1), + condition: field('foo').equal(1), rawOptions, }), stageIndex: 1, diff --git a/dev/test/structured-pipeline.ts b/dev/test/structured-pipeline.ts index 89b0af406..80499a7f1 100644 --- a/dev/test/structured-pipeline.ts +++ b/dev/test/structured-pipeline.ts @@ -63,7 +63,7 @@ describe('StructuredPipeline', () => { indexMode: 'recommended', explainOptions: { mode: 'explain', - outputFormat: 'json', + outputFormat: 'text', }, }, {} @@ -84,7 +84,7 @@ describe('StructuredPipeline', () => { stringValue: 'explain', }, output_format: { - stringValue: 'json', + stringValue: 'text', }, }, }, @@ -109,8 +109,6 @@ describe('StructuredPipeline', () => { const proto = structuredPipeline._toProto(new Serializer(db!)); - console.log(JSON.stringify(proto)); - expect(proto).to.deep.equal({ pipeline: {}, options: { diff --git a/samples/pipelines-quickstart.js b/samples/pipelines-quickstart.js index aadec0992..552dca1bc 100644 --- a/samples/pipelines-quickstart.js +++ b/samples/pipelines-quickstart.js @@ -43,7 +43,7 @@ async function quickstartPipelines() { .pipeline() .collection('posts') .select('rating', field('title').toUpper().as('lowercaseTitle')) - .where(field('rating').gt(5)); + .where(field('rating').greaterThan(5)); // Execute the Pipeline against the Firestore server. const pipelineSnapshot = await myPipeline.execute(); diff --git a/types/firestore.d.ts b/types/firestore.d.ts index b618c03a5..a2195f6e0 100644 --- a/types/firestore.d.ts +++ b/types/firestore.d.ts @@ -925,7 +925,7 @@ declare namespace FirebaseFirestore { * const futureResults = await transaction * .execute( * firestore.pipeline().collection("books") - * .where(gt(Field.of("rating"), 4.5)) + * .where(greaterThan(Field.of("rating"), 4.5)) * .select("title", "author", "rating")); * ``` * @@ -3122,28 +3122,24 @@ declare namespace FirebaseFirestore { */ distanceThreshold?: number; } - - /** - * @beta - */ export namespace Pipelines { /** * @beta * Represents an expression that has been assigned an alias using the `.as()` method. * - * This class wraps an existing {@link Expr} and associates it with a user-defined alias, + * This class wraps an existing {@link Expression} and associates it with a user-defined alias, * allowing the expression's result to be referred to by a different name in the output * of a Firestore pipeline query, particularly within `select()` operations. * * @internal */ - export type ExprType = + export type ExpressionType = | 'Field' | 'Constant' | 'Function' | 'AggregateFunction' | 'ListOfExprs' - | 'AliasedExpr'; + | 'AliasedExpression'; /** * @beta * Represents an expression that can be evaluated to a value within the execution of a {@link @@ -3156,11 +3152,11 @@ declare namespace FirebaseFirestore { * - **Literals:** Represent constant values (strings, numbers, booleans). * - **Function calls:** Apply functions to one or more expressions. * - * The `Expr` class provides a fluent API for building expressions. You can chain together + * The `Expression` class provides a fluent API for building expressions. You can chain together * method calls to create complex expressions. */ - export abstract class Expr { - abstract readonly exprType: ExprType; + export abstract class Expression { + abstract readonly expressionType: ExpressionType; /** * @beta * Creates an expression that adds this expression to another expression. @@ -3172,12 +3168,12 @@ declare namespace FirebaseFirestore { * * @param second The expression or literal to add to this expression. * @param others Optional additional expressions or literals to add to this expression. - * @return A new `Expr` representing the addition operation. + * @return A new `Expression` representing the addition operation. */ add( - second: Expr | unknown, - ...others: Array - ): FunctionExpr; + second: Expression | unknown, + ...others: Array + ): FunctionExpression; /** * @beta * Creates an expression that subtracts another expression from this expression. @@ -3188,9 +3184,9 @@ declare namespace FirebaseFirestore { * ``` * * @param subtrahend The expression to subtract from this expression. - * @return A new `Expr` representing the subtraction operation. + * @return A new `Expression` representing the subtraction operation. */ - subtract(subtrahend: Expr): FunctionExpr; + subtract(subtrahend: Expression): FunctionExpression; /** * @beta * Creates an expression that subtracts a constant value from this expression. @@ -3201,9 +3197,9 @@ declare namespace FirebaseFirestore { * ``` * * @param subtrahend The constant value to subtract. - * @return A new `Expr` representing the subtraction operation. + * @return A new `Expression` representing the subtraction operation. */ - subtract(subtrahend: number): FunctionExpr; + subtract(subtrahend: number): FunctionExpression; /** * @beta * Creates an expression that multiplies this expression by another expression. @@ -3215,12 +3211,12 @@ declare namespace FirebaseFirestore { * * @param second The second expression or literal to multiply by. * @param others Optional additional expressions or literals to multiply by. - * @return A new `Expr` representing the multiplication operation. + * @return A new `Expression` representing the multiplication operation. */ multiply( - second: Expr | number, - ...others: Array - ): FunctionExpr; + second: Expression | number, + ...others: Array + ): FunctionExpression; /** * @beta * Creates an expression that divides this expression by another expression. @@ -3231,9 +3227,9 @@ declare namespace FirebaseFirestore { * ``` * * @param divisor The expression to divide by. - * @return A new `Expr` representing the division operation. + * @return A new `Expression` representing the division operation. */ - divide(divisor: Expr): FunctionExpr; + divide(divisor: Expression): FunctionExpression; /** * @beta * Creates an expression that divides this expression by a constant value. @@ -3244,9 +3240,9 @@ declare namespace FirebaseFirestore { * ``` * * @param divisor The constant value to divide by. - * @return A new `Expr` representing the division operation. + * @return A new `Expression` representing the division operation. */ - divide(divisor: number): FunctionExpr; + divide(divisor: number): FunctionExpression; /** * @beta * Creates an expression that calculates the modulo (remainder) of dividing this expression by another expression. @@ -3257,9 +3253,9 @@ declare namespace FirebaseFirestore { * ``` * * @param expression The expression to divide by. - * @return A new `Expr` representing the modulo operation. + * @return A new `Expression` representing the modulo operation. */ - mod(expression: Expr): FunctionExpr; + mod(expression: Expression): FunctionExpression; /** * @beta * Creates an expression that calculates the modulo (remainder) of dividing this expression by a constant value. @@ -3270,9 +3266,9 @@ declare namespace FirebaseFirestore { * ``` * * @param value The constant value to divide by. - * @return A new `Expr` representing the modulo operation. + * @return A new `Expression` representing the modulo operation. */ - mod(value: number): FunctionExpr; + mod(value: number): FunctionExpression; /** * @beta @@ -3280,29 +3276,29 @@ declare namespace FirebaseFirestore { * * ```typescript * // Check if the 'age' field is equal to the value of another field named 'otherAge'. - * field("age").eq(field("otherAge")); + * field("age").equal(field("otherAge")); * * // Check if the 'status' field is equal to a string literal. - * field("status").eq("active"); + * field("status").equal("active"); * ``` * * @param expression The expression to compare for equality. - * @return A new `BooleanExpr` representing the equality comparison. + * @return A new `BooleanExpression` representing the equality comparison. */ - eq(expression: Expr): BooleanExpr; + equal(expression: Expression): BooleanExpression; /** * @beta * Creates an expression that checks if this expression is equal to a constant value. * * ```typescript * // Check if the 'city' field is equal to "London" - * field("city").eq("London"); + * field("city").equal("London"); * ``` * * @param value The constant value to compare for equality. - * @return A new `Expr` representing the equality comparison. + * @return A new `Expression` representing the equality comparison. */ - eq(value: unknown): BooleanExpr; + equal(value: unknown): BooleanExpression; /** * @beta @@ -3310,26 +3306,26 @@ declare namespace FirebaseFirestore { * * ```typescript * // Check if the 'status' field is not equal to "completed" - * field("status").neq("completed"); + * field("status").notEqual("completed"); * ``` * * @param expression The expression to compare for inequality. - * @return A new {@link BooleanExpr} representing the inequality comparison. + * @return A new {@link BooleanExpression} representing the inequality comparison. */ - neq(expression: Expr): BooleanExpr; + notEqual(expression: Expression): BooleanExpression; /** * @beta * Creates an expression that checks if this expression is not equal to a constant value. * * ```typescript * // Check if the 'country' field is not equal to "USA" - * field("country").neq("USA"); + * field("country").notEqual("USA"); * ``` * * @param value The constant value to compare for inequality. - * @return A new `Expr` representing the inequality comparison. + * @return A new `Expression` representing the inequality comparison. */ - neq(value: unknown): BooleanExpr; + notEqual(value: unknown): BooleanExpression; /** * @beta @@ -3337,26 +3333,26 @@ declare namespace FirebaseFirestore { * * ```typescript * // Check if the 'age' field is less than 'limit' - * field("age").lt(field('limit')); + * field("age").lessThan(field('limit')); * ``` * * @param expression The expression to compare against. - * @return A new `BooleanExpr` representing the less than comparison. + * @return A new `BooleanExpression` representing the less than comparison. */ - lt(expression: Expr): BooleanExpr; + lessThan(expression: Expression): BooleanExpression; /** * @beta * Creates an expression that checks if this expression is less than a constant value. * * ```typescript * // Check if the 'price' field is less than 50 - * field("price").lt(50); + * field("price").lessThan(50); * ``` * * @param value The constant value to compare for less than. - * @return A new `Expr` representing the less than comparison. + * @return A new `Expression` representing the less than comparison. */ - lt(value: unknown): BooleanExpr; + lessThan(value: unknown): BooleanExpression; /** * @beta @@ -3364,26 +3360,26 @@ declare namespace FirebaseFirestore { * * ```typescript * // Check if the 'quantity' field is less than or equal to 20 - * field("quantity").lte(constant(20)); + * field("quantity").lessThanOrEqual(constant(20)); * ``` * * @param expression The expression to compare against. - * @return A new `BooleanExpr` representing the less than or equal to comparison. + * @return A new `BooleanExpression` representing the less than or equal to comparison. */ - lte(expression: Expr): BooleanExpr; + lessThanOrEqual(expression: Expression): BooleanExpression; /** * @beta * Creates an expression that checks if this expression is less than or equal to a constant value. * * ```typescript * // Check if the 'score' field is less than or equal to 70 - * field("score").lte(70); + * field("score").lessThanOrEqual(70); * ``` * * @param value The constant value to compare for less than or equal to. - * @return A new `Expr` representing the less than or equal to comparison. + * @return A new `Expression` representing the less than or equal to comparison. */ - lte(value: unknown): BooleanExpr; + lessThanOrEqual(value: unknown): BooleanExpression; /** * @beta @@ -3391,26 +3387,26 @@ declare namespace FirebaseFirestore { * * ```typescript * // Check if the 'age' field is greater than the 'limit' field - * field("age").gt(field("limit")); + * field("age").greaterThan(field("limit")); * ``` * * @param expression The expression to compare for greater than. - * @return A new {@link BooleanExpr} representing the greater than comparison. + * @return A new {@link BooleanExpression} representing the greater than comparison. */ - gt(expression: Expr): BooleanExpr; + greaterThan(expression: Expression): BooleanExpression; /** * @beta * Creates an expression that checks if this expression is greater than a constant value. * * ```typescript * // Check if the 'price' field is greater than 100 - * field("price").gt(100); + * field("price").greaterThan(100); * ``` * * @param value The constant value to compare for greater than. - * @return A new `Expr` representing the greater than comparison. + * @return A new `Expression` representing the greater than comparison. */ - gt(value: unknown): BooleanExpr; + greaterThan(value: unknown): BooleanExpression; /** * @beta * Creates an expression that checks if this expression is greater than or equal to another @@ -3418,13 +3414,13 @@ declare namespace FirebaseFirestore { * * ```typescript * // Check if the 'quantity' field is greater than or equal to field 'requirement' plus 1 - * field("quantity").gte(field('requirement').add(1)); + * field("quantity").greaterThanOrEqual(field('requirement').add(1)); * ``` * * @param expression The expression to compare for greater than or equal to. - * @return A new `Expr` representing the greater than or equal to comparison. + * @return A new `Expression` representing the greater than or equal to comparison. */ - gte(expression: Expr): BooleanExpr; + greaterThanOrEqual(expression: Expression): BooleanExpression; /** * @beta * Creates an expression that checks if this expression is greater than or equal to a constant @@ -3432,13 +3428,31 @@ declare namespace FirebaseFirestore { * * ```typescript * // Check if the 'score' field is greater than or equal to 80 - * field("score").gte(80); + * field("score").greaterThanOrEqual(80); * ``` * * @param value The constant value to compare for greater than or equal to. - * @return A new `Expr` representing the greater than or equal to comparison. + * @return A new `Expression` representing the greater than or equal to comparison. + */ + greaterThanOrEqual(value: unknown): BooleanExpression; + + /** + * @beta + * Creates an expression that concatenates an array expression with one or more other arrays. + * + * ```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. + * @return A new `Expr` representing the concatenated array. */ - gte(value: unknown): BooleanExpr; + arrayConcat( + secondArray: Expression | unknown[], + ...otherArrays: Array + ): FunctionExpression; + /** * @beta * Creates an expression that checks if an array contains a specific element. @@ -3449,9 +3463,9 @@ declare namespace FirebaseFirestore { * ``` * * @param expression The element to search for in the array. - * @return A new `Expr` representing the 'array_contains' comparison. + * @return A new `Expression` representing the 'array_contains' comparison. */ - arrayContains(expression: Expr): BooleanExpr; + arrayContains(expression: Expression): BooleanExpression; /** * @beta * Creates an expression that checks if an array contains a specific value. @@ -3462,9 +3476,9 @@ declare namespace FirebaseFirestore { * ``` * * @param value The element to search for in the array. - * @return A new `Expr` representing the 'array_contains' comparison. + * @return A new `Expression` representing the 'array_contains' comparison. */ - arrayContains(value: unknown): BooleanExpr; + arrayContains(value: unknown): BooleanExpression; /** * @beta * Creates an expression that checks if an array contains all the specified elements. @@ -3475,9 +3489,9 @@ declare namespace FirebaseFirestore { * ``` * * @param values The elements to check for in the array. - * @return A new `Expr` representing the 'array_contains_all' comparison. + * @return A new `Expression` representing the 'array_contains_all' comparison. */ - arrayContainsAll(values: Array): BooleanExpr; + arrayContainsAll(values: Array): BooleanExpression; /** * @beta * Creates an expression that checks if an array contains all the specified elements. @@ -3488,9 +3502,9 @@ declare namespace FirebaseFirestore { * ``` * * @param arrayExpression The elements to check for in the array. - * @return A new `Expr` representing the 'array_contains_all' comparison. + * @return A new `Expression` representing the 'array_contains_all' comparison. */ - arrayContainsAll(arrayExpression: Expr): BooleanExpr; + arrayContainsAll(arrayExpression: Expression): BooleanExpression; /** * @beta * Creates an expression that checks if an array contains any of the specified elements. @@ -3501,9 +3515,9 @@ declare namespace FirebaseFirestore { * ``` * * @param values The elements to check for in the array. - * @return A new `Expr` representing the 'array_contains_any' comparison. + * @return A new `Expression` representing the 'array_contains_any' comparison. */ - arrayContainsAny(values: Array): BooleanExpr; + arrayContainsAny(values: Array): BooleanExpression; /** * @beta * Creates an expression that checks if an array contains any of the specified elements. @@ -3515,9 +3529,9 @@ declare namespace FirebaseFirestore { * ``` * * @param arrayExpression The elements to check for in the array. - * @return A new `Expr` representing the 'array_contains_any' comparison. + * @return A new `Expression` representing the 'array_contains_any' comparison. */ - arrayContainsAny(arrayExpression: Expr): BooleanExpr; + arrayContainsAny(arrayExpression: Expression): BooleanExpression; /** * @beta * Creates an expression that calculates the length of an array. @@ -3527,9 +3541,9 @@ declare namespace FirebaseFirestore { * field("cart").arrayLength(); * ``` * - * @return A new `Expr` representing the length of the array. + * @return A new `Expression` representing the length of the array. */ - arrayLength(): FunctionExpr; + arrayLength(): FunctionExpression; /** * @beta @@ -3538,13 +3552,13 @@ declare namespace FirebaseFirestore { * * ```typescript * // Check if the 'category' field is either "Electronics" or the value of field 'primaryType' - * field("category").eqAny(["Electronics", field("primaryType")]); + * field("category").equalAny(["Electronics", field("primaryType")]); * ``` * * @param values An array of values or expressions to check against. - * @return A new `BooleanExpr` representing the 'IN' comparison. + * @return A new `BooleanExpression` representing the 'IN' comparison. */ - eqAny(values: Array): BooleanExpr; + equalAny(values: Array): BooleanExpression; /** * @beta * Creates an expression that checks if this expression is equal to any of the provided values or @@ -3552,13 +3566,13 @@ declare namespace FirebaseFirestore { * * ```typescript * // Check if the 'category' field is either "Electronics" or the value of field 'primaryType' - * field("category").eqAny(array(["Electronics", field("primaryType")])); + * field("category").equalAny(array(["Electronics", field("primaryType")])); * ``` * * @param arrayExpression An expression that evaluates to an array of values to check against. - * @return A new `Expr` representing the 'IN' comparison. + * @return A new `Expression` representing the 'IN' comparison. */ - eqAny(arrayExpression: Expr): BooleanExpr; + equalAny(arrayExpression: Expression): BooleanExpression; /** * @beta * Creates an expression that checks if this expression is not equal to any of the provided values or @@ -3566,13 +3580,13 @@ declare namespace FirebaseFirestore { * * ```typescript * // Check if the 'status' field is neither "pending" nor the value of 'rejectedStatus' - * field("status").notEqAny(["pending", field("rejectedStatus")]); + * field("status").notEqualAny(["pending", field("rejectedStatus")]); * ``` * * @param values The values or expressions to check against. - * @return A new `Expr` representing the 'NotEqAny' comparison. + * @return A new `Expression` representing the 'NotEqAny' comparison. */ - notEqAny(values: Array): BooleanExpr; + notEqualAny(values: Array): BooleanExpression; /** * @beta @@ -3580,38 +3594,13 @@ declare namespace FirebaseFirestore { * * ```typescript * // Check if the 'status' field is not equal to any value in the array returned by the 'rejectedStatuses' field. - * field("status").notEqAny(field('rejectedStatuses')); - * ``` - * - * @param arrayExpression An `Expr` that evaluates to an array of values to compare against. - * @return A new `BooleanExpr` representing the result of the 'not equal to any' comparison. - */ - notEqAny(arrayExpression: Expr): BooleanExpr; - /** - * @beta - * Creates an expression that checks if this expression evaluates to 'NaN' (Not a Number). - * - * ```typescript - * // Check if the result of a calculation is NaN - * field("value").divide(0).isNaN(); - * ``` - * - * @return A new `Expr` representing the 'isNaN' check. - */ - isNan(): BooleanExpr; - - /** - * @beta - * Creates an expression that checks if this expression evaluates to `null`. - * - * ```typescript - * // Check if the 'status' field is null. - * field("status").isNull(); + * field("status").notEqualAny(field('rejectedStatuses')); * ``` * - * @return A new `BooleanExpr` representing the `isNull` check. + * @param arrayExpression An `Expression` that evaluates to an array of values to compare against. + * @return A new `BooleanExpression` representing the result of the 'not equal to any' comparison. */ - isNull(): BooleanExpr; + notEqualAny(arrayExpression: Expression): BooleanExpression; /** * @beta @@ -3622,9 +3611,9 @@ declare namespace FirebaseFirestore { * field("phoneNumber").exists(); * ``` * - * @returns A new {@link BooleanExpr} representing the 'exists' check. + * @returns A new {@link BooleanExpression} representing the 'exists' check. */ - exists(): BooleanExpr; + exists(): BooleanExpression; /** * @beta * Creates an expression that calculates the character length of a string in UTF-8. @@ -3634,9 +3623,9 @@ declare namespace FirebaseFirestore { * field("name").charLength(); * ``` * - * @return A new `Expr` representing the length of the string. + * @return A new `Expression` representing the length of the string. */ - charLength(): FunctionExpr; + charLength(): FunctionExpression; /** * @beta @@ -3648,9 +3637,9 @@ declare namespace FirebaseFirestore { * ``` * * @param pattern The string pattern to search for. You can use "%" as a wildcard character within the pattern. - * @return A new {@link FunctionExpr} representing the 'like' comparison. + * @return A new {@link FunctionExpression} representing the 'like' comparison. */ - like(pattern: string): FunctionExpr; + like(pattern: string): FunctionExpression; /** * @beta @@ -3661,10 +3650,10 @@ declare namespace FirebaseFirestore { * field("description").like(field("searchPattern")); * ``` * - * @param pattern An {@link Expr} that evaluates to the string pattern to search for. You can use "%" as a wildcard character within the pattern. - * @return A new {@link FunctionExpr} representing the 'like' comparison. + * @param pattern An {@link Expression} that evaluates to the string pattern to search for. You can use "%" as a wildcard character within the pattern. + * @return A new {@link FunctionExpression} representing the 'like' comparison. */ - like(pattern: Expr): FunctionExpr; + like(pattern: Expression): FunctionExpression; /** * @beta * Creates an expression that checks if a string contains a specified regular expression as a @@ -3676,9 +3665,9 @@ declare namespace FirebaseFirestore { * ``` * * @param pattern The regular expression to use for the search. - * @return A new `Expr` representing the 'contains' comparison. + * @return A new `Expression` representing the 'contains' comparison. */ - regexContains(pattern: string): BooleanExpr; + regexContains(pattern: string): BooleanExpression; /** * @beta @@ -3691,9 +3680,9 @@ declare namespace FirebaseFirestore { * ``` * * @param pattern The regular expression to use for the search. - * @return A new {@link BooleanExpr} representing the 'contains' comparison. + * @return A new {@link BooleanExpression} representing the 'contains' comparison. */ - regexContains(pattern: Expr): BooleanExpr; + regexContains(pattern: Expression): BooleanExpression; /** * @beta * Creates an expression that checks if a string matches a specified regular expression. @@ -3704,9 +3693,9 @@ declare namespace FirebaseFirestore { * ``` * * @param pattern The regular expression to use for the match. - * @return A new `Expr` representing the regular expression match. + * @return A new `Expression` representing the regular expression match. */ - regexMatch(pattern: string): BooleanExpr; + regexMatch(pattern: string): BooleanExpression; /** * @beta @@ -3718,22 +3707,22 @@ declare namespace FirebaseFirestore { * ``` * * @param pattern An expression that evaluates to the regular expression string to use for the match. - * @return A new `BooleanExpr` representing the result of the regular expression match. + * @return A new `BooleanExpression` representing the result of the regular expression match. */ - regexMatch(pattern: Expr): BooleanExpr; + regexMatch(pattern: Expression): BooleanExpression; /** * @beta * Creates an expression that checks if a string contains a specified substring. * * ```typescript * // Check if the 'description' field contains "example". - * field("description").strContains("example"); + * field("description").stringContains("example"); * ``` * * @param substring The substring to search for. - * @return A new `Expr` representing the 'contains' comparison. + * @return A new `Expression` representing the 'contains' comparison. */ - strContains(substring: string): BooleanExpr; + stringContains(substring: string): BooleanExpression; /** * @beta @@ -3741,13 +3730,13 @@ declare namespace FirebaseFirestore { * * ```typescript * // Check if the 'description' field contains the value of the 'keyword' field. - * field("description").strContains(field("keyword")); + * field("description").stringContains(field("keyword")); * ``` * * @param expr The expression representing the substring to search for. - * @return A new {@link BooleanExpr} representing the 'contains' comparison. + * @return A new {@link BooleanExpression} representing the 'contains' comparison. */ - strContains(expr: Expr): BooleanExpr; + stringContains(expr: Expression): BooleanExpression; /** * @beta * Creates an expression that checks if a string starts with a given prefix. @@ -3758,9 +3747,9 @@ declare namespace FirebaseFirestore { * ``` * * @param prefix The prefix to check for. - * @return A new `Expr` representing the 'starts with' comparison. + * @return A new `Expression` representing the 'starts with' comparison. */ - startsWith(prefix: string): BooleanExpr; + startsWith(prefix: string): BooleanExpression; /** * @beta @@ -3772,9 +3761,9 @@ declare namespace FirebaseFirestore { * ``` * * @param prefix An expression whose string value will be used as the prefix to check against. - * @returns A new `BooleanExpr` representing the 'starts with' comparison result. + * @returns A new `BooleanExpression` representing the 'starts with' comparison result. */ - startsWith(prefix: Expr): BooleanExpr; + startsWith(prefix: Expression): BooleanExpression; /** * @beta @@ -3786,9 +3775,9 @@ declare namespace FirebaseFirestore { * ``` * * @param suffix The postfix to check for. - * @return A new {@link BooleanExpr} representing the 'ends with' comparison. + * @return A new {@link BooleanExpression} representing the 'ends with' comparison. */ - endsWith(suffix: string): BooleanExpr; + endsWith(suffix: string): BooleanExpression; /** * @beta * Creates an expression that checks if a string ends with a given postfix (represented as an @@ -3800,9 +3789,9 @@ declare namespace FirebaseFirestore { * ``` * * @param suffix The postfix expression to check for. - * @return A new `Expr` representing the 'ends with' comparison. + * @return A new `Expression` representing the 'ends with' comparison. */ - endsWith(suffix: Expr): BooleanExpr; + endsWith(suffix: Expression): BooleanExpression; /** * @beta * Creates an expression that converts a string to lowercase. @@ -3812,9 +3801,9 @@ declare namespace FirebaseFirestore { * field("name").toLower(); * ``` * - * @return A new `Expr` representing the lowercase string. + * @return A new `Expression` representing the lowercase string. */ - toLower(): FunctionExpr; + toLower(): FunctionExpression; /** * @beta * Creates an expression that converts a string to uppercase. @@ -3824,9 +3813,9 @@ declare namespace FirebaseFirestore { * field("title").toUpper(); * ``` * - * @return A new `Expr` representing the uppercase string. + * @return A new `Expression` representing the uppercase string. */ - toUpper(): FunctionExpr; + toUpper(): FunctionExpression; /** * @beta * Creates an expression that removes leading and trailing whitespace from a string. @@ -3836,38 +3825,38 @@ declare namespace FirebaseFirestore { * field("userInput").trim(); * ``` * - * @return A new `Expr` representing the trimmed string. + * @return A new `Expression` representing the trimmed string. */ - trim(): FunctionExpr; + trim(): FunctionExpression; /** * @beta * Creates an expression that concatenates string expressions together. * * ```typescript * // Combine the 'firstName', " ", and 'lastName' fields into a single string - * field("firstName").strConcat(constant(" "), field("lastName")); + * 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. - * @return A new `Expr` representing the concatenated string. + * @return A new `Expression` representing the concatenated string. */ - strConcat( - secondString: Expr | string, - ...otherStrings: Array - ): FunctionExpr; + stringConcat( + secondString: Expression | string, + ...otherStrings: Array + ): FunctionExpression; /** * @beta - * Creates an expression that reverses this string expression. + * Creates an expression that reverses this string or bytes expression. * * ```typescript * // Reverse the value of the 'myString' field. * field("myString").reverse(); * ``` * - * @return A new {@code Expr} representing the reversed string. + * @return A new {@code Expression} representing the reversed string or bytes. */ - reverse(): FunctionExpr; + reverse(): FunctionExpression; /** * @beta * Creates an expression that calculates the length of this string expression in bytes. @@ -3877,9 +3866,9 @@ declare namespace FirebaseFirestore { * field("myString").byteLength(); * ``` * - * @return A new {@code Expr} representing the length of the string in bytes. + * @return A new {@code Expression} representing the length of the string in bytes. */ - byteLength(): FunctionExpr; + byteLength(): FunctionExpression; /** * @beta * Creates an expression that computes the ceiling of a numeric value. @@ -3889,9 +3878,9 @@ declare namespace FirebaseFirestore { * field("price").ceil(); * ``` * - * @return A new {@code Expr} representing the ceiling of the numeric value. + * @return A new {@code Expression} representing the ceiling of the numeric value. */ - ceil(): FunctionExpr; + ceil(): FunctionExpression; /** * @beta * Creates an expression that computes the floor of a numeric value. @@ -3901,9 +3890,22 @@ declare namespace FirebaseFirestore { * field("price").floor(); * ``` * - * @return A new {@code Expr} representing the floor of the numeric value. + * @return A new {@code Expression} representing the floor of the numeric value. */ - floor(): FunctionExpr; + floor(): FunctionExpression; + + /** + * @beta + * Creates an expression that computes the absolute value of a numeric value. + * + * ```typescript + * // Compute the absolute value of the 'price' field. + * field("price").abs(); + * ``` + * + * @return A new {@code Expr} representing the absolute value of the numeric value. + */ + abs(): FunctionExpression; /** * @beta @@ -3914,9 +3916,9 @@ declare namespace FirebaseFirestore { * field("value").exp(); * ``` * - * @return A new {@code FunctionExpr} representing `e` raised to the power of the numeric value. + * @return A new {@code FunctionExpression} representing `e` raised to the power of the numeric value. */ - exp(): FunctionExpr; + exp(): FunctionExpression; /** * @beta * Creates an aggregation that counts the number of distinct values of the expression or field. @@ -3934,9 +3936,9 @@ declare namespace FirebaseFirestore { * ``` * * @param subfield The key to access in the map. - * @return A new `Expr` representing the value associated with the given key in the map. + * @return A new `Expression` representing the value associated with the given key in the map. */ - mapGet(subfield: string): FunctionExpr; + mapGet(subfield: string): FunctionExpression; /** * @beta * Creates an aggregation that counts the number of stage inputs with valid evaluations of the @@ -3969,12 +3971,12 @@ declare namespace FirebaseFirestore { * * ```typescript * // Calculate the average age of users - * field("age").avg().as("averageAge"); + * field("age").average().as("averageAge"); * ``` * - * @return A new `AggregateFunction` representing the 'avg' aggregation. + * @return A new `AggregateFunction` representing the 'average' aggregation. */ - avg(): AggregateFunction; + average(): AggregateFunction; /** * @beta * Creates an aggregation that finds the minimum value of a field across multiple stage inputs. @@ -4010,12 +4012,12 @@ declare namespace FirebaseFirestore { * * @param second The second expression or literal to compare with. * @param others Optional additional expressions or literals to compare with. - * @return A new {@code Expr} representing the logical max operation. + * @return A new {@code Expression} representing the logical max operation. */ logicalMaximum( - second: Expr | unknown, - ...others: Array - ): FunctionExpr; + second: Expression | unknown, + ...others: Array + ): FunctionExpression; /** * @beta * Creates an expression that returns the smaller value between this expression and another expression, based on Firestore's value type ordering. @@ -4027,12 +4029,12 @@ declare namespace FirebaseFirestore { * * @param second The second expression or literal to compare with. * @param others Optional additional expressions or literals to compare with. - * @return A new {@code Expr} representing the logical min operation. + * @return A new {@code Expression} representing the logical min operation. */ logicalMinimum( - second: Expr | unknown, - ...others: Array - ): FunctionExpr; + second: Expression | unknown, + ...others: Array + ): FunctionExpression; /** * @beta * Creates an expression that calculates the length (number of dimensions) of this Firestore Vector expression. @@ -4042,9 +4044,9 @@ declare namespace FirebaseFirestore { * field("embedding").vectorLength(); * ``` * - * @return A new {@code Expr} representing the length of the vector. + * @return A new {@code Expression} representing the length of the vector. */ - vectorLength(): FunctionExpr; + vectorLength(): FunctionExpression; /** * @beta * Calculates the cosine distance between two vectors. @@ -4054,10 +4056,10 @@ declare namespace FirebaseFirestore { * field("userVector").cosineDistance(field("itemVector")); * ``` * - * @param vectorExpression The other vector (represented as an Expr) to compare against. - * @return A new `Expr` representing the cosine distance between the two vectors. + * @param vectorExpression The other vector (represented as an Expression) to compare against. + * @return A new `Expression` representing the cosine distance between the two vectors. */ - cosineDistance(vectorExpression: Expr): FunctionExpr; + cosineDistance(vectorExpression: Expression): FunctionExpression; /** * @beta @@ -4072,9 +4074,9 @@ declare namespace FirebaseFirestore { * ``` * * @param vector The other vector to compare against, provided as either a `VectorValue` object or a plain `number[]` array. - * @return A new `FunctionExpr` representing the Cosine distance between the two vectors. + * @return A new `FunctionExpression` representing the Cosine distance between the two vectors. */ - cosineDistance(vector: VectorValue | number[]): FunctionExpr; + cosineDistance(vector: VectorValue | number[]): FunctionExpression; /** * @beta * Calculates the dot product between the current expression (representing a vector) @@ -4087,10 +4089,10 @@ declare namespace FirebaseFirestore { * field("features").dotProduct(field("targetVector")); * ``` * - * @param vectorExpression An {@link Expr} representing the second vector. - * @returns A new {@link FunctionExpr} representing the dot product of the two vectors. + * @param vectorExpression An {@link Expression} representing the second vector. + * @returns A new {@link FunctionExpression} representing the dot product of the two vectors. */ - dotProduct(vectorExpression: Expr): FunctionExpr; + dotProduct(vectorExpression: Expression): FunctionExpression; /** * @beta @@ -4102,9 +4104,9 @@ declare namespace FirebaseFirestore { * ``` * * @param vector The other vector to calculate the dot product with. This can be a `VectorValue` object or a plain array of numbers. - * @return A new `Expr` representing the dot product between the two vectors. + * @return A new `Expression` representing the dot product between the two vectors. */ - dotProduct(vector: VectorValue | number[]): FunctionExpr; + dotProduct(vector: VectorValue | number[]): FunctionExpression; /** * @beta @@ -4115,10 +4117,10 @@ declare namespace FirebaseFirestore { * field("vectorA").euclideanDistance(field("vectorB")); * ``` * - * @param vectorExpression An {@link Expr} that evaluates to the second vector (an array of numbers) for the distance calculation. - * @return A new {@link FunctionExpr} representing the Euclidean distance between the two vectors. + * @param vectorExpression An {@link Expression} that evaluates to the second vector (an array of numbers) for the distance calculation. + * @return A new {@link FunctionExpression} representing the Euclidean distance between the two vectors. */ - euclideanDistance(vectorExpression: Expr): FunctionExpr; + euclideanDistance(vectorExpression: Expression): FunctionExpression; /** * @beta * Calculates the Euclidean distance between two vectors. @@ -4134,9 +4136,9 @@ declare namespace FirebaseFirestore { * ``` * * @param vector The other vector (as a `VectorValue` or `number[]`) to compare against. - * @return A new `Expr` representing the Euclidean distance between the two vectors. + * @return A new `Expression` representing the Euclidean distance between the two vectors. */ - euclideanDistance(vector: VectorValue | number[]): FunctionExpr; + euclideanDistance(vector: VectorValue | number[]): FunctionExpression; /** * @beta * Creates an expression that interprets this expression as the number of microseconds since the Unix epoch (1970-01-01 00:00:00 UTC) @@ -4147,9 +4149,9 @@ declare namespace FirebaseFirestore { * field("microseconds").unixMicrosToTimestamp(); * ``` * - * @return A new {@code Expr} representing the timestamp. + * @return A new {@code Expression} representing the timestamp. */ - unixMicrosToTimestamp(): FunctionExpr; + unixMicrosToTimestamp(): FunctionExpression; /** * @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). @@ -4159,9 +4161,9 @@ declare namespace FirebaseFirestore { * field("timestamp").timestampToUnixMicros(); * ``` * - * @return A new {@code Expr} representing the number of microseconds since epoch. + * @return A new {@code Expression} representing the number of microseconds since epoch. */ - timestampToUnixMicros(): FunctionExpr; + timestampToUnixMicros(): FunctionExpression; /** * @beta * Creates an expression that interprets this expression as the number of milliseconds since the Unix epoch (1970-01-01 00:00:00 UTC) @@ -4172,9 +4174,9 @@ declare namespace FirebaseFirestore { * field("milliseconds").unixMillisToTimestamp(); * ``` * - * @return A new {@code Expr} representing the timestamp. + * @return A new {@code Expression} representing the timestamp. */ - unixMillisToTimestamp(): FunctionExpr; + unixMillisToTimestamp(): FunctionExpression; /** * @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). @@ -4184,9 +4186,9 @@ declare namespace FirebaseFirestore { * field("timestamp").timestampToUnixMillis(); * ``` * - * @return A new {@code Expr} representing the number of milliseconds since epoch. + * @return A new {@code Expression} representing the number of milliseconds since epoch. */ - timestampToUnixMillis(): FunctionExpr; + timestampToUnixMillis(): FunctionExpression; /** * @beta * Creates an expression that interprets this expression as the number of seconds since the Unix epoch (1970-01-01 00:00:00 UTC) @@ -4197,9 +4199,9 @@ declare namespace FirebaseFirestore { * field("seconds").unixSecondsToTimestamp(); * ``` * - * @return A new {@code Expr} representing the timestamp. + * @return A new {@code Expression} representing the timestamp. */ - unixSecondsToTimestamp(): FunctionExpr; + unixSecondsToTimestamp(): FunctionExpression; /** * @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). @@ -4209,9 +4211,9 @@ declare namespace FirebaseFirestore { * field("timestamp").timestampToUnixSeconds(); * ``` * - * @return A new {@code Expr} representing the number of seconds since epoch. + * @return A new {@code Expression} representing the number of seconds since epoch. */ - timestampToUnixSeconds(): FunctionExpr; + timestampToUnixSeconds(): FunctionExpression; /** * @beta * Creates an expression that adds a specified amount of time to this timestamp expression. @@ -4223,9 +4225,9 @@ declare namespace FirebaseFirestore { * * @param unit The expression evaluates to unit of time, must be one of 'microsecond', 'millisecond', 'second', 'minute', 'hour', 'day'. * @param amount The expression evaluates to amount of the unit. - * @return A new {@code Expr} representing the resulting timestamp. + * @return A new {@code Expression} representing the resulting timestamp. */ - timestampAdd(unit: Expr, amount: Expr): FunctionExpr; + timestampAdd(unit: Expression, amount: Expression): FunctionExpression; /** * @beta * Creates an expression that adds a specified amount of time to this timestamp expression. @@ -4237,7 +4239,7 @@ declare namespace FirebaseFirestore { * * @param unit The unit of time to add (e.g., "day", "hour"). * @param amount The amount of time to add. - * @return A new {@code Expr} representing the resulting timestamp. + * @return A new {@code Expression} representing the resulting timestamp. */ timestampAdd( unit: @@ -4248,21 +4250,24 @@ declare namespace FirebaseFirestore { | 'hour' | 'day', amount: number - ): FunctionExpr; + ): FunctionExpression; /** * @beta * Creates an expression that subtracts a specified amount of time from this timestamp expression. * * ```typescript * // Subtract some duration determined by field 'unit' and 'amount' from the 'timestamp' field. - * field("timestamp").timestampSub(field("unit"), field("amount")); + * field("timestamp").timestampSubtract(field("unit"), field("amount")); * ``` * * @param unit The expression evaluates to unit of time, must be one of 'microsecond', 'millisecond', 'second', 'minute', 'hour', 'day'. * @param amount The expression evaluates to amount of the unit. - * @return A new {@code Expr} representing the resulting timestamp. + * @return A new {@code Expression} representing the resulting timestamp. */ - timestampSub(unit: Expr, amount: Expr): FunctionExpr; + timestampSubtract( + unit: Expression, + amount: Expression + ): FunctionExpression; /** * @beta @@ -4270,14 +4275,14 @@ declare namespace FirebaseFirestore { * * ```typescript * // Subtract 1 day from the 'timestamp' field. - * field("timestamp").timestampSub("day", 1); + * field("timestamp").timestampSubtract("day", 1); * ``` * * @param unit The unit of time to subtract. Supported units are 'microsecond', 'millisecond', 'second', 'minute', 'hour', and 'day'. * @param amount The amount of time to subtract. - * @return A new {@code FunctionExpr} representing the resulting timestamp after subtraction. + * @return A new {@code FunctionExpression} representing the resulting timestamp after subtraction. */ - timestampSub( + timestampSubtract( unit: | 'microsecond' | 'millisecond' @@ -4286,7 +4291,7 @@ declare namespace FirebaseFirestore { | 'hour' | 'day', amount: number - ): FunctionExpr; + ): FunctionExpression; /** * @beta * Creates an expression that returns the document ID from a DocumentReference. @@ -4296,9 +4301,9 @@ declare namespace FirebaseFirestore { * field("__name__").documentId(); * ``` * - * @return A new {@code Expr} representing the documentId operation. + * @return A new {@code Expression} representing the documentId operation. */ - documentId(): FunctionExpr; + documentId(): FunctionExpression; /** * @beta * Creates an expression that returns a substring of the results of this expression. @@ -4307,7 +4312,7 @@ declare namespace FirebaseFirestore { * @param length Length of the substring. If not provided, the substring will * end at the end of the input. */ - substring(position: number, length?: number): FunctionExpr; + substring(position: number, length?: number): FunctionExpression; /** * @beta * Creates an expression that returns a substring of the results of this expression. @@ -4316,7 +4321,7 @@ declare namespace FirebaseFirestore { * @param length An expression returning the length of the substring. If not provided the * substring will end at the end of the input. */ - substring(position: Expr, length?: Expr): FunctionExpr; + substring(position: Expression, length?: Expression): FunctionExpression; /** * @beta * Creates an expression that indexes into an array from the beginning or end @@ -4329,9 +4334,9 @@ declare namespace FirebaseFirestore { * ``` * * @param index The index of the element to return. - * @return A new Expr representing the 'arrayGet' operation. + * @return A new Expression representing the 'arrayGet' operation. */ - arrayGet(index: number): FunctionExpr; + arrayGet(index: number): FunctionExpression; /** * @beta * Creates an expression that indexes into an array from the beginning or end @@ -4344,10 +4349,10 @@ declare namespace FirebaseFirestore { * field('tags').arrayGet(field('favoriteTag')); * ``` * - * @param indexExpr An Expr evaluating to the index of the element to return. - * @return A new Expr representing the 'arrayGet' operation. + * @param indexExpr An Expression evaluating to the index of the element to return. + * @return A new Expression representing the 'arrayGet' operation. */ - arrayGet(indexExpr: Expr): FunctionExpr; + arrayGet(indexExpr: Expression): FunctionExpression; /** * @beta * Creates an expression that checks if a given expression produces an error. @@ -4357,9 +4362,9 @@ declare namespace FirebaseFirestore { * field("title").arrayContains(1).isError(); * ``` * - * @return A new {@code BooleanExpr} representing the 'isError' check. + * @return A new {@code BooleanExpression} representing the 'isError' check. */ - isError(): BooleanExpr; + isError(): BooleanExpression; /** * @beta * Creates an expression that returns the result of the `catchExpr` argument @@ -4373,9 +4378,9 @@ declare namespace FirebaseFirestore { * * @param catchExpr The catch expression that will be evaluated and * returned if this expression produces an error. - * @return A new {@code Expr} representing the 'ifError' operation. + * @return A new {@code Expression} representing the 'ifError' operation. */ - ifError(catchExpr: Expr): FunctionExpr; + ifError(catchExpr: Expression): FunctionExpression; /** * @beta * Creates an expression that returns the `catch` argument if there is an @@ -4389,9 +4394,9 @@ declare namespace FirebaseFirestore { * * @param catchValue The value that will be returned if this expression * produces an error. - * @return A new {@code Expr} representing the 'ifError' operation. + * @return A new {@code Expression} representing the 'ifError' operation. */ - ifError(catchValue: unknown): FunctionExpr; + ifError(catchValue: unknown): FunctionExpression; /** * @beta * Creates an expression that returns `true` if the result of this expression @@ -4402,34 +4407,9 @@ declare namespace FirebaseFirestore { * field("value").isAbsent(); * ``` * - * @return A new {@code BooleanExpr} representing the 'isAbsent' check. + * @return A new {@code BooleanExpression} representing the 'isAbsent' check. */ - isAbsent(): BooleanExpr; - - /** - * @beta - * Creates an expression that checks if the result of an expression is not null. - * - * ```typescript - * // Check if the value of the 'name' field is not null - * field("name").isNotNull(); - * ``` - * - * @return A new {@code BooleanExpr} representing the 'isNotNull' check. - */ - isNotNull(): BooleanExpr; - /** - * @beta - * Creates an expression that checks if the results of this expression is NOT 'NaN' (Not a Number). - * - * ```typescript - * // Check if the result of a calculation is NOT NaN - * field("value").divide(0).isNotNan(); - * ``` - * - * @return A new {@code Expr} representing the 'isNaN' check. - */ - isNotNan(): BooleanExpr; + isAbsent(): BooleanExpression; /** * @beta @@ -4441,9 +4421,9 @@ declare namespace FirebaseFirestore { * ``` * * @param key The name of the key to remove from the input map. - * @returns A new {@code FunctionExpr} representing the 'mapRemove' operation. + * @returns A new {@code FunctionExpression} representing the 'mapRemove' operation. */ - mapRemove(key: string): FunctionExpr; + mapRemove(key: string): FunctionExpression; /** * @beta @@ -4455,9 +4435,9 @@ declare namespace FirebaseFirestore { * ``` * * @param keyExpr An expression that produces the name of the key to remove from the input map. - * @returns A new {@code FunctionExpr} representing the 'mapRemove' operation. + * @returns A new {@code FunctionExpression} representing the 'mapRemove' operation. */ - mapRemove(keyExpr: Expr): FunctionExpr; + mapRemove(keyExpr: Expression): FunctionExpression; /** * @beta @@ -4468,7 +4448,7 @@ declare namespace FirebaseFirestore { * ```typescript * // Merges the map in the 'settings' field with a literal map and a map * // conditionally returned by another expression. - * field('settings').mapMerge({ enabled: true }, cond(field('isAdmin'), { admin: true }, {})) + * field('settings').mapMerge({ enabled: true }, conditional(field('isAdmin'), { admin: true }, {})) * ``` * * @param secondMap A required second map to merge. This can be a literal object @@ -4476,12 +4456,12 @@ declare namespace FirebaseFirestore { * @param otherMaps Optional additional maps to merge. Each can be a literal * object or an expression that evaluates to a map. * - * @returns A new {@code FunctionExpr} representing the result of the map merge operation. + * @returns A new {@code FunctionExpression} representing the result of the map merge operation. */ mapMerge( - secondMap: Record | Expr, - ...otherMaps: Array | Expr> - ): FunctionExpr; + secondMap: Record | Expression, + ...otherMaps: Array | Expression> + ): FunctionExpression; /** * @beta * Creates an expression that returns the value of this expression raised to the power of another expression. @@ -4492,9 +4472,9 @@ declare namespace FirebaseFirestore { * ``` * * @param exponent The expression to raise this expression to the power of. - * @return A new `Expr` representing the power operation. + * @return A new `Expression` representing the power operation. */ - pow(exponent: Expr): FunctionExpr; + pow(exponent: Expression): FunctionExpression; /** * @beta * Creates an expression that returns the value of this expression raised to the power of a constant value. @@ -4505,9 +4485,9 @@ declare namespace FirebaseFirestore { * ``` * * @param exponent The constant value to raise this expression to the power of. - * @return A new `Expr` representing the power operation. + * @return A new `Expression` representing the power operation. */ - pow(exponent: number): FunctionExpr; + pow(exponent: number): FunctionExpression; /** * @beta * Creates an expression that rounds a numeric value to the nearest whole number. @@ -4517,9 +4497,49 @@ declare namespace FirebaseFirestore { * field("price").round(); * ``` * + * @return A new `Expression` representing the rounded value. + */ + round(): FunctionExpression; + /** + * @beta + * Creates an expression that rounds a numeric value to the nearest whole number. + * + * ```typescript + * // Round the value of the 'price' field. + * field("price").round(); + * ``` + * + * @return A new `Expression` representing the rounded value. + */ + round(): FunctionExpression; + /** + * @beta + * Creates an expression that rounds a numeric value to the specified number of decimal places. + * + * ```typescript + * // Round the value of the 'price' field to two decimal places. + * field("price").round(2); + * ``` + * + * @param decimalPlaces A constant specifying the rounding precision in decimal places. + * * @return A new `Expr` representing the rounded value. */ - round(): FunctionExpr; + round(decimalPlaces: number): FunctionExpression; + /** + * @beta + * Creates an expression that rounds a numeric value to the specified number of decimal places. + * + * ```typescript + * // Round the value of the 'price' field to two decimal places. + * field("price").round(constant(2)); + * ``` + * + * @param decimalPlaces An expression specifying the rounding precision in decimal places. + * + * @return A new `Expr` representing the rounded value. + */ + round(decimalPlaces: Expression): FunctionExpression; /** * @beta * Creates an expression that returns the collection ID from a path. @@ -4529,9 +4549,9 @@ declare namespace FirebaseFirestore { * field("__name__").collectionId(); * ``` * - * @return A new {@code Expr} representing the collectionId operation. + * @return A new {@code Expression} representing the collectionId operation. */ - collectionId(): FunctionExpr; + collectionId(): FunctionExpression; /** * @beta * Creates an expression that calculates the length of a string, array, map, vector, or bytes. @@ -4544,9 +4564,9 @@ declare namespace FirebaseFirestore { * field("cart").length(); * ``` * - * @return A new `Expr` representing the length of the string, array, map, vector, or bytes. + * @return A new `Expression` representing the length of the string, array, map, vector, or bytes. */ - length(): FunctionExpr; + length(): FunctionExpression; /** * @beta * Creates an expression that computes the natural logarithm of a numeric value. @@ -4556,59 +4576,123 @@ declare namespace FirebaseFirestore { * field("value").ln(); * ``` * - * @return A new {@code Expr} representing the natural logarithm of the numeric value. + * @return A new {@code Expression} representing the natural logarithm of the numeric value. */ - ln(): FunctionExpr; + ln(): FunctionExpression; /** * @beta - * Creates an expression that computes the logarithm of this expression to a given base. + * Creates an expression that computes the square root of a numeric value. * * ```typescript - * // Compute the logarithm of the 'value' field with base 10. - * field("value").log(10); + * // Compute the square root of the 'value' field. + * field("value").sqrt(); * ``` * - * @param base The base of the logarithm. - * @return A new {@code Expr} representing the logarithm of the numeric value. + * @return A new {@code Expression} representing the square root of the numeric value. */ - log(base: number): FunctionExpr; + sqrt(): FunctionExpression; /** * @beta - * Creates an expression that computes the logarithm of this expression to a given base. + * Creates an expression that reverses a string. * * ```typescript - * // Compute the logarithm of the 'value' field with the base in the 'base' field. - * field("value").log(field("base")); + * // Reverse the value of the 'myString' field. + * field("myString").stringReverse(); * ``` * - * @param base The base of the logarithm. - * @return A new {@code Expr} representing the logarithm of the numeric value. + * @return A new {@code Expression} representing the reversed string. */ - log(base: Expr): FunctionExpr; + stringReverse(): FunctionExpression; + /** * @beta - * Creates an expression that computes the square root of a numeric value. + * Creates an expression that returns the `elseValue` argument if this expression results in an absent value, else + * return the result of the this expression evaluation. * * ```typescript - * // Compute the square root of the 'value' field. - * field("value").sqrt(); + * // Returns the value of the optional field 'optional_field', or returns 'default_value' + * // if the field is absent. + * field("optional_field").ifAbsent("default_value") * ``` * - * @return A new {@code Expr} representing the square root of the numeric value. + * @param elseValue The value that will be returned if this Expression evaluates to an absent value. + * @return A new [Expression] representing the ifAbsent operation. */ - sqrt(): FunctionExpr; + ifAbsent(elseValue: unknown): Expression; + /** * @beta - * Creates an expression that reverses a string. + * Creates an expression that returns the `elseValue` argument if this expression results in an absent value, else + * return the result of this expression evaluation. * * ```typescript - * // Reverse the value of the 'myString' field. - * field("myString").strReverse(); + * // Returns the value of the optional field 'optional_field', or if that is + * // absent, then returns the value of the field ` + * field("optional_field").ifAbsent(field('default_field')) + * ``` + * + * @param elseExpression The Expression that will be evaluated if this Expression evaluates to an absent value. + * @return A new [Expression] representing the ifAbsent operation. + */ + ifAbsent(elseExpression: unknown): Expression; + + ifAbsent(elseValueOrExpression: Expression | unknown): Expression; + + /** + * @beta + * Creates an expression that joins the elements of an array into a string. + * + * ```typescript + * // Join the elements of the 'tags' field with the delimiter from the 'separator' field. + * field("tags").join(field("separator")) + * ``` + * + * @param delimiterExpression The expression that evaluates to the delimiter string. + * @return A new Expression representing the join operation. + */ + join(delimiterExpression: Expression): Expression; + + /** + * @beta + * Creates an expression that joins the elements of an array field into a string. + * + * ```typescript + * // Join the elements of the 'tags' field with a comma and space. + * field("tags").join(", ") + * ``` + * + * @param delimiter The string to use as a delimiter. + * @return A new Expression representing the join operation. + */ + join(delimiter: string): Expression; + + join(delimeterValueOrExpression: string | Expression): Expression; + + /** + * @beta + * Creates an expression that computes the base-10 logarithm of a numeric value. + * + * ```typescript + * // Compute the base-10 logarithm of the 'value' field. + * field("value").log10(); * ``` * - * @return A new {@code Expr} representing the reversed string. + * @return A new {@code Expr} representing the base-10 logarithm of the numeric value. */ - strReverse(): FunctionExpr; + log10(): FunctionExpression; + + /** + * @beta + * Creates an expression that computes the sum of the elements in an array. + * + * ```typescript + * // Compute the sum of the elements in the 'scores' field. + * field("scores").arraySum(); + * ``` + * + * @return A new {@code Expr} representing the sum of the elements in the array. + */ + arraySum(): FunctionExpression; // TODO(new-expression): Add new expression method declarations above this line /** * @beta @@ -4650,10 +4734,10 @@ declare namespace FirebaseFirestore { * ``` * * @param name The alias to assign to this expression. - * @return A new {@link AliasedExpr} that wraps this + * @return A new {@link AliasedExpression} that wraps this * expression and associates it with the provided alias. */ - as(name: string): AliasedExpr; + as(name: string): AliasedExpression; } /** * @beta @@ -4661,8 +4745,16 @@ declare namespace FirebaseFirestore { */ export interface Selectable { selectable: true; - readonly alias: string; - readonly expr: Expr; + /** + * @beta + * @internal + */ + readonly _alias: string; + /** + * @beta + * @internal + */ + readonly _expr: Expression; } /** @@ -4674,9 +4766,9 @@ declare namespace FirebaseFirestore { export class AggregateFunction { /** * @beta - * @property exprType The type of the aggregate expression, indicating the specific aggregate function (e.g., COUNT, SUM, AVG). + * @property expressionType The type of the aggregate expression, indicating the specific aggregate function (e.g., COUNT, SUM, AVG). */ - exprType: ExprType; + expressionType: ExpressionType; /** * @beta @@ -4685,7 +4777,7 @@ declare namespace FirebaseFirestore { * @param name * @param params */ - constructor(name: string, params: Expr[]); + constructor(name: string, params: Expression[]); /** * @beta * Assigns an alias to this AggregateFunction. The alias specifies the name that @@ -4694,7 +4786,7 @@ declare namespace FirebaseFirestore { * ```typescript * // Calculate the average price of all items and assign it the alias "averagePrice". * pipeline().collection("items") - * .aggregate(field("price").avg().as("averagePrice")); + * .aggregate(field("price").average().as("averagePrice")); * ``` * * @param name The alias to assign to this AggregateFunction. @@ -4713,71 +4805,76 @@ declare namespace FirebaseFirestore { /** * @beta * The underlying {@link AggregateFunction} that this aliased aggregate wraps. + * @internal */ - readonly aggregate: AggregateFunction; + readonly _aggregate: AggregateFunction; /** * @beta * Specifies the name of the property that will contain the aggregate result in the output document. + * @internal */ - readonly alias: string; + readonly _alias: string; } /** * @beta * Represents an expression that has been assigned an alias using the `.as()` method. * - * This class wraps an existing {@link Expr} and associates it with a user-defined alias, + * This class wraps an existing {@link Expression} and associates it with a user-defined alias, * allowing the expression's result to be referred to by name in the output * of a Firestore pipeline query. */ - export class AliasedExpr implements Selectable { + export class AliasedExpression implements Selectable { /** * @beta - * @internal Specifies that the instance is an AliasedExpr. + * @internal + * Specifies that the instance is an AliasedExpression. */ - exprType: ExprType; + expressionType: ExpressionType; /** * @beta - * Specifies that this class is selectable, meaning it contains an {@link Expr} and an alias, + * Specifies that this class is selectable, meaning it contains an {@link Expression} and an alias, * and can be provided to the Select stage of a pipeline. */ selectable: true; /** * @beta + * @internal * The underlying expression that is being aliased. */ - readonly expr: Expr; + readonly _expr: Expression; /** * @beta + * @internal * Specifies the name of the property that will contain the aggregate result in the output document. */ - readonly alias: string; + readonly _alias: string; } /** * @beta * Represents a reference to a field within a Firestore document or an output from a {@link Pipeline} stage. * - * This class extends {@link Expr}. It is a type of expression that can be evaluated + * This class extends {@link Expression}. It is a type of expression that can be evaluated * within Firestore Pipelines. It also implements {@link Selectable}, * meaning instances of `Field` can be used to specify fields for selection in the {@link Pipeline.select} stage. * * `Field` instances are fundamental for constructing expressions that access document field values, * and for defining criteria for sorting, filtering, and projecting data in Firestore Pipelines. */ - export class Field extends Expr implements Selectable { + export class Field extends Expression implements Selectable { /** * @beta * @internal Specifies that the instance is a Field. */ - readonly exprType: ExprType; + readonly expressionType: ExpressionType; /** * @beta - * Specifies that this class is selectable, meaning it contains an {@link Expr} and an alias, + * Specifies that this class is selectable, meaning it contains an {@link Expression} and an alias, * and can be provided to the Select stage of a pipeline. */ selectable: true; @@ -4787,27 +4884,29 @@ declare namespace FirebaseFirestore { * * @example * ```typescript - * const name = field("price").fieldName(); + * const name = field("price").fieldName; * console.log(name); // "price" * ``` * * @returns The name of the field. */ - fieldName(): string; + get fieldName(): string; /** * @beta + * @internal * Returns the alias of the field, which is the field-name itself. * * @returns The field name itself. */ - get alias(): string; + get _alias(): string; /** * @beta + * @internal * Self-referential getter that returns this. * * @returns This {@link Field} object. */ - get expr(): Expr; + get _expr(): Expression; } /** * @beta @@ -4839,6 +4938,7 @@ declare namespace FirebaseFirestore { /** * @beta + * @internal * Represents a constant value that can be used as part of a Firestore pipeline expression. * * Instances of `Constant` are typically created via the top-level `constant()` function. @@ -4851,128 +4951,128 @@ declare namespace FirebaseFirestore { * const hello = constant("hello"); * ``` */ - export class Constant extends Expr { - readonly exprType: ExprType; + export class Constant extends Expression { + readonly expressionType: ExpressionType; } /** * @beta - * Creates a `Constant` instance for a number value. + * Creates an `Expression` instance for a number value. * * @param value The number value. - * @return A new `Constant` instance. + * @return A new `Expression` instance. */ - export function constant(value: number): Constant; + export function constant(value: number): Expression; /** * @beta - * Creates a `Constant` instance for a string value. + * Creates an `Expression` instance for a string value. * * @param value The string value. - * @return A new `Constant` instance. + * @return A new `Expression` instance. */ - export function constant(value: string): Constant; + export function constant(value: string): Expression; /** * @beta - * Creates a `Constant` instance for a boolean value. + * Creates an `Expression` instance for a boolean value. * * @param value The boolean value. - * @return A new `Constant` instance. + * @return A new `Expression` instance. */ - export function constant(value: boolean): Constant; + export function constant(value: boolean): BooleanExpression; /** * @beta - * Creates a `Constant` instance for a null value. + * Creates an `Expression` instance for a null value. * * @param value The null value. - * @return A new `Constant` instance. + * @return A new `Expression` instance. */ - export function constant(value: null): Constant; + export function constant(value: null): Expression; /** * @beta - * Creates a `Constant` instance for a GeoPoint value. + * Creates an `Expression` instance for a GeoPoint value. * * @param value The GeoPoint value. - * @return A new `Constant` instance. + * @return A new `Expression` instance. */ - export function constant(value: GeoPoint): Constant; + export function constant(value: GeoPoint): Expression; /** * @beta - * Creates a `Constant` instance for a Timestamp value. + * Creates an `Expression` instance for a Timestamp value. * * @param value The Timestamp value. - * @return A new `Constant` instance. + * @return A new `Expression` instance. */ - export function constant(value: Timestamp): Constant; + export function constant(value: Timestamp): Expression; /** * @beta - * Creates a `Constant` instance for a Date value. + * Creates an `Expression` instance for a Date value. * * @param value The Date value. - * @return A new `Constant` instance. + * @return A new `Expression` instance. */ - export function constant(value: Date): Constant; + export function constant(value: Date): Expression; /** * @beta - * Creates a `Constant` instance for a Buffer | Uint8Array value. + * Creates an `Expression` instance for a Buffer | Uint8Array value. * * @param value The Buffer | Uint8Array value. - * @return A new `Constant` instance. + * @return A new `Expression` instance. */ - export function constant(value: Buffer | Uint8Array): Constant; + export function constant(value: Buffer | Uint8Array): Expression; /** * @beta - * Creates a `Constant` instance for a DocumentReference value. + * Creates an `Expression` instance for a DocumentReference value. * * @param value The DocumentReference value. - * @return A new `Constant` instance. + * @return A new `Expression` instance. */ - export function constant(value: DocumentReference): Constant; + export function constant(value: DocumentReference): Expression; /** * @beta - * Creates a `Constant` instance for a VectorValue value. + * Creates an `Expression` instance for a VectorValue value. * * @param value The VectorValue value. - * @return A new `Constant` instance. + * @return A new `Expression` instance. */ - export function constant(value: VectorValue): Constant; + export function constant(value: VectorValue): Expression; /** * @beta * Represents an expression that encapsulates a function call within the Firestore Pipelines. * - * `FunctionExpr` extends {@link Expr} and is used to build complex queries and transformations - * by applying various functions (e.g., `and`, `eq`, `ceil`) to fields or other expressions. + * `FunctionExpression` extends {@link Expression} and is used to build complex queries and transformations + * by applying various functions (e.g., `and`, `equal`, `ceil`) to fields or other expressions. * - * You typically do not instantiate `FunctionExpr` directly. Instead, use the provided - * top-level functions (like {@link and}, {@link eq}, {@link ceil}) or methods available - * on {@link Expr} instances (e.g., {@link Expr#eq}, {@link Expr#lt}) to construct - * `FunctionExpr` instances. + * You typically do not instantiate `FunctionExpression` directly. Instead, use the provided + * top-level functions (like {@link and}, {@link equal}, {@link ceil}) or methods available + * on {@link Expression} instances (e.g., {@link Expression#equal}, {@link Expression#lessThan}) to construct + * `FunctionExpression` instances. * * ```typescript - * // Example of creating a FunctionExpr indirectly using helper functions: - * const priceGreaterThan10 = field("price").gt(10); - * const combinedCondition = and(priceGreaterThan10, field("category").eq("books")); + * // Example of creating a FunctionExpression indirectly using helper functions: + * const priceGreaterThan10 = field("price").greaterThan(10); + * const combinedCondition = and(priceGreaterThan10, field("category").equal("books")); * - * // 'priceGreaterThan10' and 'combinedCondition' are instances of FunctionExpr. + * // 'priceGreaterThan10' and 'combinedCondition' are instances of FunctionExpression. * ``` */ - export class FunctionExpr extends Expr { + export class FunctionExpression extends Expression { /** * @beta * @internal - * Indicates that this expression is a `FunctionExpr`. + * Indicates that this expression is a `FunctionExpression`. */ - readonly exprType: ExprType; + readonly expressionType: ExpressionType; /** * @beta * @private * @internal * - * Initializes a new `FunctionExpr` instance with the given function name and parameters. + * Initializes a new `FunctionExpression` instance with the given function name and parameters. * * @param name The name of the function. - * @param params An array of `Expr` instances representing the parameters of the function. + * @param params An array of `Expression` instances representing the parameters of the function. */ - constructor(name: string, params: Expr[]); + constructor(name: string, params: Expression[]); } /** * @beta @@ -4981,7 +5081,7 @@ declare namespace FirebaseFirestore { * This expression type is useful for filter conditions. * */ - export class BooleanExpr extends FunctionExpr { + export class BooleanExpression extends FunctionExpression { /** * @beta * @internal @@ -4995,7 +5095,7 @@ declare namespace FirebaseFirestore { * * ```typescript * // Find the count of documents with a score greater than 90 - * field("score").gt(90).countIf().as("highestScore"); + * field("score").greaterThan(90).countIf().as("highestScore"); * ``` * * @return A new `AggregateFunction` representing the 'countIf' aggregation. @@ -5010,9 +5110,9 @@ declare namespace FirebaseFirestore { * field("tags").arrayContains("completed").not(); * ``` * - * @return A new {@code Expr} representing the negated filter condition. + * @return A new {@code Expression} representing the negated filter condition. */ - not(): BooleanExpr; + not(): BooleanExpression; } /** * @beta @@ -5021,21 +5121,13 @@ declare namespace FirebaseFirestore { * * ```typescript * // Count the number of documents where 'is_active' field equals true - * countIf(field("is_active").eq(true)).as("numActiveDocuments"); + * countIf(field("is_active").equal(true)).as("numActiveDocuments"); * ``` * * @param booleanExpr - The boolean expression to evaluate on each input. * @returns A new `AggregateFunction` representing the 'countIf' aggregation. */ - export function countIf(booleanExpr: BooleanExpr): AggregateFunction; - /** - * @beta - * Creates an expression that return a pseudo-random value of type double in the - * range of [0, 1), inclusive of 0 and exclusive of 1. - * - * @returns A new `Expr` representing the 'rand' function. - */ - export function rand(): FunctionExpr; + export function countIf(booleanExpr: BooleanExpression): AggregateFunction; /** * @beta * Creates an expression that indexes into an array from the beginning or end @@ -5049,9 +5141,12 @@ declare namespace FirebaseFirestore { * * @param arrayField The name of the array field. * @param index The index of the element to return. - * @return A new Expr representing the 'arrayGet' operation. + * @return A new Expression representing the 'arrayGet' operation. */ - export function arrayGet(arrayField: string, index: number): FunctionExpr; + export function arrayGet( + arrayField: string, + index: number + ): FunctionExpression; /** * @beta * Creates an expression that indexes into an array from the beginning or end @@ -5065,10 +5160,13 @@ declare namespace FirebaseFirestore { * ``` * * @param arrayField The name of the array field. - * @param indexExpr An Expr evaluating to the index of the element to return. - * @return A new Expr representing the 'arrayGet' operation. + * @param indexExpr An Expression evaluating to the index of the element to return. + * @return A new Expression representing the 'arrayGet' operation. */ - export function arrayGet(arrayField: string, indexExpr: Expr): FunctionExpr; + export function arrayGet( + arrayField: string, + indexExpr: Expression + ): FunctionExpression; /** * @beta * Creates an expression that indexes into an array from the beginning or end @@ -5080,14 +5178,14 @@ declare namespace FirebaseFirestore { * arrayGet(field('tags'), 1); * ``` * - * @param arrayExpression An Expr evaluating to an array. + * @param arrayExpression An Expression evaluating to an array. * @param index The index of the element to return. - * @return A new Expr representing the 'arrayGet' operation. + * @return A new Expression representing the 'arrayGet' operation. */ export function arrayGet( - arrayExpression: Expr, + arrayExpression: Expression, index: number - ): FunctionExpr; + ): FunctionExpression; /** * @beta * Creates an expression that indexes into an array from the beginning or end @@ -5100,14 +5198,14 @@ declare namespace FirebaseFirestore { * arrayGet(field('tags'), field('favoriteTag')); * ``` * - * @param arrayExpression An Expr evaluating to an array. - * @param indexExpr An Expr evaluating to the index of the element to return. - * @return A new Expr representing the 'arrayGet' operation. + * @param arrayExpression An Expression evaluating to an array. + * @param indexExpr An Expression evaluating to the index of the element to return. + * @return A new Expression representing the 'arrayGet' operation. */ export function arrayGet( - arrayExpression: Expr, - indexExpr: Expr - ): FunctionExpr; + arrayExpression: Expression, + indexExpr: Expression + ): FunctionExpression; /** * @beta * Creates an expression that checks if a given expression produces an error. @@ -5118,9 +5216,32 @@ declare namespace FirebaseFirestore { * ``` * * @param value The expression to check. - * @return A new {@code Expr} representing the 'isError' check. + * @return A new {@code Expression} representing the 'isError' check. + */ + export function isError(value: Expression): BooleanExpression; + /** + * @beta + * + * Creates an expression that returns the `catch` argument if there is an + * error, else return the result of the `try` argument evaluation. + * + * This overload is useful when a BooleanExpression is required. + * + * ```typescript + * // Create an expression that protects against a divide by zero error + * // but always returns a boolean expression. + * ifError(constant(50).divide('length').gt(1), constant(false)); + * ``` + * + * @param tryExpr The try expression. + * @param catchExpr The catch expression that will be evaluated and + * returned if the tryExpr produces an error. + * @return A new {@code Expr} representing the 'ifError' operation. */ - export function isError(value: Expr): BooleanExpr; + export function ifError( + tryExpr: BooleanExpression, + catchExpr: BooleanExpression + ): BooleanExpression; /** * @beta * Creates an expression that returns the `catch` argument if there is an @@ -5135,9 +5256,12 @@ declare namespace FirebaseFirestore { * @param tryExpr The try expression. * @param catchExpr The catch expression that will be evaluated and * returned if the tryExpr produces an error. - * @return A new {@code Expr} representing the 'ifError' operation. + * @return A new {@code Expression} representing the 'ifError' operation. */ - export function ifError(tryExpr: Expr, catchExpr: Expr): FunctionExpr; + export function ifError( + tryExpr: Expression, + catchExpr: Expression + ): FunctionExpression; /** * @beta * Creates an expression that returns the `catch` argument if there is an @@ -5152,9 +5276,12 @@ declare namespace FirebaseFirestore { * @param tryExpr The try expression. * @param catchValue The value that will be returned if the tryExpr produces an * error. - * @return A new {@code Expr} representing the 'ifError' operation. + * @return A new {@code Expression} representing the 'ifError' operation. */ - export function ifError(tryExpr: Expr, catchValue: unknown): FunctionExpr; + export function ifError( + tryExpr: Expression, + catchValue: unknown + ): FunctionExpression; /** * @beta * Creates an expression that returns `true` if a value is absent. Otherwise, @@ -5166,9 +5293,9 @@ declare namespace FirebaseFirestore { * ``` * * @param value The expression to check. - * @return A new {@code Expr} representing the 'isAbsent' check. + * @return A new {@code Expression} representing the 'isAbsent' check. */ - export function isAbsent(value: Expr): BooleanExpr; + export function isAbsent(value: Expression): BooleanExpression; /** * @beta * Creates an expression that returns `true` if a field is absent. Otherwise, @@ -5180,93 +5307,10 @@ declare namespace FirebaseFirestore { * ``` * * @param field The field to check. - * @return A new {@code Expr} representing the 'isAbsent' check. - */ - export function isAbsent(field: string): BooleanExpr; - - /** - * @beta - * Creates an expression that checks if an expression evaluates to 'null'. - * - * ```typescript - * // Check if the 'lastLogin' field is null - * isNull(field("lastLogin")); - * ``` - * - * @param value The expression to check for null. - * @return A new {@code BooleanExpr} representing the 'isNull' check. - */ - export function isNull(value: Expr): BooleanExpr; - - /** - * @beta - * Creates an expression that checks if a field's value evaluates to 'null'. - * - * ```typescript - * // Check if the 'endDate' field is null. - * isNull("endDate"); - * ``` - * - * @param value The name of the field to check. - * @return A new {@code BooleanExpr} representing the 'isNull' check. - */ - export function isNull(value: string): BooleanExpr; - - /** - * @beta - * Creates an expression that checks if the result of an expression is not null. - * - * ```typescript - * // Check if the value of the 'name' field is not null - * isNotNull(field("name")); - * ``` - * - * @param value The expression to check. - * @return A new {@code BooleanExpr} representing the 'not null' check. + * @return A new {@code Expression} representing the 'isAbsent' check. */ - export function isNotNull(value: Expr): BooleanExpr; + export function isAbsent(field: string): BooleanExpression; - /** - * @beta - * Creates an expression that checks if the value of a field is not null. - * - * ```typescript - * // Check if the value of the 'name' field is not null - * isNotNull("name"); - * ``` - * - * @param value The name of the field to check. - * @return A new {@code BooleanExpr} representing the 'not null' check. - */ - export function isNotNull(value: string): BooleanExpr; - - /** - * @beta - * Creates an expression that evaluates to `true` if the given expression's result is not `NaN` (Not a Number), and `false` otherwise. - * - * ```typescript - * // Check if the result of a calculation is NOT NaN - * isNotNan(field("value").divide(0)); - * ``` - * - * @param value The expression to check for `NaN`. - * @return A new {@code BooleanExpr} representing the result of the `isNotNaN` check. - */ - export function isNotNan(value: Expr): BooleanExpr; - - /** - * @beta - * Creates an expression that checks if a numeric value is not NaN (Not a Number). - * - * ```typescript - * // Check if the value of a field is not NaN - * isNotNan("value"); - * ``` - * - * @param value The name of the field to check. - * @return A new {@code BooleanExpr} representing the 'isNotNan' check. - */ - export function isNotNan(value: string): BooleanExpr; /** * @beta * Creates an expression that removes a key from the map at the specified field name. @@ -5279,7 +5323,10 @@ declare namespace FirebaseFirestore { * @param mapField The name of a field containing a map value. * @param key The name of the key to remove from the input map. */ - export function mapRemove(mapField: string, key: string): FunctionExpr; + export function mapRemove( + mapField: string, + key: string + ): FunctionExpression; /** * @beta @@ -5292,9 +5339,12 @@ declare namespace FirebaseFirestore { * * @param mapExpr An expression that evaluates to a map value. * @param key The name of the key to remove from the input map. - * @returns A new {@link FunctionExpr} representing the map with the specified key removed. + * @returns A new {@link FunctionExpression} representing the map with the specified key removed. */ - export function mapRemove(mapExpr: Expr, key: string): FunctionExpr; + export function mapRemove( + mapExpr: Expression, + key: string + ): FunctionExpression; /** * @beta @@ -5307,9 +5357,12 @@ declare namespace FirebaseFirestore { * * @param mapField The name of a field containing a map value. * @param keyExpr An expression that produces the name of the key to remove from the input map. - * @returns A new {@code FunctionExpr} representing the map after the key has been removed. + * @returns A new {@code FunctionExpression} representing the map after the key has been removed. */ - export function mapRemove(mapField: string, keyExpr: Expr): FunctionExpr; + export function mapRemove( + mapField: string, + keyExpr: Expression + ): FunctionExpression; /** * @beta @@ -5326,9 +5379,12 @@ declare namespace FirebaseFirestore { * * @param mapExpr An expression that evaluates to a map value. * @param keyExpr An expression that evaluates to the string key to remove from the map. - * @returns A new {@link FunctionExpr} representing the map with the specified key removed. + * @returns A new {@link FunctionExpression} representing the map with the specified key removed. */ - export function mapRemove(mapExpr: Expr, keyExpr: Expr): FunctionExpr; + export function mapRemove( + mapExpr: Expression, + keyExpr: Expression + ): FunctionExpression; /** * @beta * Creates an expression that merges multiple map values. @@ -5336,7 +5392,7 @@ declare namespace FirebaseFirestore { * ``` * // Merges the map in the settings field with, a map literal, and a map in * // that is conditionally returned by another expression - * mapMerge('settings', { enabled: true }, cond(field('isAdmin'), { admin: true}, {}) + * mapMerge('settings', { enabled: true }, conditional(field('isAdmin'), { admin: true}, {}) * ``` * * @param mapField Name of a field containing a map value that will be merged. @@ -5347,9 +5403,9 @@ declare namespace FirebaseFirestore { */ export function mapMerge( mapField: string, - secondMap: Record | Expr, - ...otherMaps: Array | Expr> - ): FunctionExpr; + secondMap: Record | Expression, + ...otherMaps: Array | Expression> + ): FunctionExpression; /** * @beta * Creates an expression that merges multiple map values. @@ -5357,7 +5413,7 @@ declare namespace FirebaseFirestore { * ``` * // Merges the map in the settings field with, a map literal, and a map in * // that is conditionally returned by another expression - * mapMerge(field('settings'), { enabled: true }, cond(field('isAdmin'), { admin: true}, {}) + * mapMerge(field('settings'), { enabled: true }, conditional(field('isAdmin'), { admin: true}, {}) * ``` * * @param firstMap An expression or literal map value that will be merged. @@ -5367,10 +5423,10 @@ declare namespace FirebaseFirestore { * as a literal or an expression that returns a map. */ export function mapMerge( - firstMap: Record | Expr, - secondMap: Record | Expr, - ...otherMaps: Array | Expr> - ): FunctionExpr; + firstMap: Record | Expression, + secondMap: Record | Expression, + ...otherMaps: Array | Expression> + ): FunctionExpression; /** * @beta @@ -5382,9 +5438,42 @@ declare namespace FirebaseFirestore { * ``` * * @param documentPathExpr An expression evaluating to a document path. - * @return A new {@code FunctionExpr} representing the document ID as a string. + * @return A new {@code FunctionExpression} representing the document ID as a string. + */ + export function documentId( + documentPathExpr: Expression + ): FunctionExpression; + + /** + * @beta + * + * Creates an expression that returns the document ID from a path. + * + * ```typescript + * // Get the document ID from a path. + * documentId(myDocumentReference); + * ``` + * + * @return A new {@code Expr} representing the documentId operation. */ - export function documentId(documentPathExpr: Expr): FunctionExpr; + export function documentId( + documentPath: string | DocumentReference + ): FunctionExpression; + + /** + * @beta + * Creates an expression that returns the document ID from a path. + * + * ```typescript + * // Get the document ID from a path. + * documentId(field("__path__")); + * ``` + * + * @return A new {@code Expression} representing the documentId operation. + */ + export function documentId( + documentPathExpr: Expression + ): FunctionExpression; /** * @beta * Creates an expression that returns a substring of a string or byte array. @@ -5397,7 +5486,7 @@ declare namespace FirebaseFirestore { field: string, position: number, length?: number - ): FunctionExpr; + ): FunctionExpression; /** * @beta * Creates an expression that returns a substring of a string or byte array. @@ -5407,10 +5496,10 @@ declare namespace FirebaseFirestore { * @param length Length of the substring. */ export function substring( - input: Expr, + input: Expression, position: number, length?: number - ): FunctionExpr; + ): FunctionExpression; /** * @beta * Creates an expression that returns a substring of a string or byte array. @@ -5421,9 +5510,9 @@ declare namespace FirebaseFirestore { */ export function substring( field: string, - position: Expr, - length?: Expr - ): FunctionExpr; + position: Expression, + length?: Expression + ): FunctionExpression; /** * @beta @@ -5437,13 +5526,13 @@ declare namespace FirebaseFirestore { * @param input An expression returning a string or byte array from which to extract the substring. * @param position An expression that returns the 0-based starting index of the substring. * @param length Optional. An expression that returns the length of the substring. If omitted, the substring extends to the end of the input. - * @return A new {@code FunctionExpr} representing the substring operation. + * @return A new {@code FunctionExpression} representing the substring operation. */ export function substring( - input: Expr, - position: Expr, - length?: Expr - ): FunctionExpr; + input: Expression, + position: Expression, + length?: Expression + ): FunctionExpression; /** * @beta @@ -5462,13 +5551,13 @@ declare namespace FirebaseFirestore { * @param first The initial numeric expression or literal value. * @param second The second numeric expression or literal value to add. * @param others Optional: Additional numeric expressions or literal values to add. - * @return A new {@code FunctionExpr} representing the sum of all provided arguments. + * @return A new {@code FunctionExpression} representing the sum of all provided arguments. */ export function add( - first: Expr, - second: Expr | unknown, - ...others: Array - ): FunctionExpr; + first: Expression, + second: Expression | unknown, + ...others: Array + ): FunctionExpression; /** * @beta @@ -5486,15 +5575,15 @@ declare namespace FirebaseFirestore { * ``` * * @param fieldName The name of the field whose value will be the first operand in the addition. - * @param second The second operand, which can be an {@code Expr} or a literal value. - * @param others Optional additional operands, each of which can be an {@code Expr} or a literal value. - * @return A new {@code Expr} representing the addition operation. + * @param second The second operand, which can be an {@code Expression} or a literal value. + * @param others Optional additional operands, each of which can be an {@code Expression} or a literal value. + * @return A new {@code Expression} representing the addition operation. */ export function add( fieldName: string, - second: Expr | unknown, - ...others: Array - ): FunctionExpr; + second: Expression | unknown, + ...others: Array + ): FunctionExpression; /** * @beta * Creates an expression that subtracts two expressions. @@ -5506,9 +5595,12 @@ declare namespace FirebaseFirestore { * * @param minuend The expression to subtract from. * @param subtrahend The expression to subtract. - * @return A new {@code Expr} representing the subtraction operation. + * @return A new {@code Expression} representing the subtraction operation. */ - export function subtract(minuend: Expr, subtrahend: Expr): FunctionExpr; + export function subtract( + minuend: Expression, + subtrahend: Expression + ): FunctionExpression; /** * @beta @@ -5521,9 +5613,12 @@ declare namespace FirebaseFirestore { * * @param minuend The expression to subtract from. * @param subtrahend The value to subtract. - * @return A new {@code Expr} representing the subtraction operation. + * @return A new {@code Expression} representing the subtraction operation. */ - export function subtract(minuend: Expr, subtrahend: unknown): FunctionExpr; + export function subtract( + minuend: Expression, + subtrahend: unknown + ): FunctionExpression; /** * @beta * Creates an expression that subtracts an expression from a field's value. @@ -5535,12 +5630,12 @@ declare namespace FirebaseFirestore { * * @param minuendFieldName The field name to subtract from. * @param subtrahend The expression to subtract. - * @return A new {@code Expr} representing the subtraction operation. + * @return A new {@code Expression} representing the subtraction operation. */ export function subtract( minuendFieldName: string, - subtrahend: Expr - ): FunctionExpr; + subtrahend: Expression + ): FunctionExpression; /** * @beta @@ -5554,12 +5649,12 @@ declare namespace FirebaseFirestore { * * @param minuendFieldName The name of the field to subtract from. * @param subtrahend The value to subtract. - * @return A new {@code Expr} representing the subtraction operation. + * @return A new {@code Expression} representing the subtraction operation. */ export function subtract( minuendFieldName: string, subtrahend: unknown - ): FunctionExpr; + ): FunctionExpression; /** * @beta @@ -5576,13 +5671,13 @@ declare namespace FirebaseFirestore { * @param first The first expression to multiply. * @param second The second expression or literal to multiply. * @param others Optional additional expressions or literals to multiply. - * @return A new {@code FunctionExpr} representing the multiplication operation. + * @return A new {@code FunctionExpression} representing the multiplication operation. */ export function multiply( - first: Expr, - second: Expr | unknown, - ...others: Array - ): FunctionExpr; + first: Expression, + second: Expression | unknown, + ...others: Array + ): FunctionExpression; /** * @beta @@ -5594,15 +5689,15 @@ declare namespace FirebaseFirestore { * ``` * * @param fieldName The name of the field whose value will be the initial operand of the multiplication. - * @param second The second operand, which can be an {@link Expr} or a literal value, to be multiplied. - * @param others Optional additional operands ({@link Expr} or literal values) to be included in the multiplication. - * @return A new {@link FunctionExpr} representing the multiplication operation. + * @param second The second operand, which can be an {@link Expression} or a literal value, to be multiplied. + * @param others Optional additional operands ({@link Expression} or literal values) to be included in the multiplication. + * @return A new {@link FunctionExpression} representing the multiplication operation. */ export function multiply( fieldName: string, - second: Expr | unknown, - ...others: Array - ): FunctionExpr; + second: Expression | unknown, + ...others: Array + ): FunctionExpression; /** * @beta * Creates an expression that divides two expressions. @@ -5614,9 +5709,12 @@ declare namespace FirebaseFirestore { * * @param dividend The expression to be divided. * @param divisor The expression to divide by. - * @return A new {@code Expr} representing the division operation. + * @return A new {@code Expression} representing the division operation. */ - export function divide(dividend: Expr, divisor: Expr): FunctionExpr; + export function divide( + dividend: Expression, + divisor: Expression + ): FunctionExpression; /** * @beta * Creates an expression that divides an expression by a constant value. @@ -5628,9 +5726,12 @@ declare namespace FirebaseFirestore { * * @param dividend The expression to be divided. * @param divisor The constant value to divide by. - * @return A new {@code Expr} representing the division operation. + * @return A new {@code Expression} representing the division operation. */ - export function divide(dividend: Expr, divisor: unknown): FunctionExpr; + export function divide( + dividend: Expression, + divisor: unknown + ): FunctionExpression; /** * @beta * Creates an expression that divides a field's value by an expression. @@ -5642,9 +5743,12 @@ declare namespace FirebaseFirestore { * * @param dividend The field name to be divided. * @param divisor The expression to divide by. - * @return A new {@code Expr} representing the division operation. + * @return A new {@code Expression} representing the division operation. */ - export function divide(dividend: string, divisor: Expr): FunctionExpr; + export function divide( + dividend: string, + divisor: Expression + ): FunctionExpression; /** * @beta * Creates an expression that divides a field's value by a constant value. @@ -5656,9 +5760,12 @@ declare namespace FirebaseFirestore { * * @param dividend The field name to be divided. * @param divisor The constant value to divide by. - * @return A new {@code Expr} representing the division operation. + * @return A new {@code Expression} representing the division operation. */ - export function divide(dividend: string, divisor: unknown): FunctionExpr; + export function divide( + dividend: string, + divisor: unknown + ): FunctionExpression; /** * @beta * Creates an expression that calculates the modulo (remainder) of dividing two expressions. @@ -5670,9 +5777,12 @@ declare namespace FirebaseFirestore { * * @param left The dividend expression. * @param right The divisor expression. - * @return A new {@code Expr} representing the modulo operation. + * @return A new {@code Expression} representing the modulo operation. */ - export function mod(left: Expr, right: Expr): FunctionExpr; + export function mod( + left: Expression, + right: Expression + ): FunctionExpression; /** * @beta * Creates an expression that calculates the modulo (remainder) of dividing an expression by a constant. @@ -5684,9 +5794,12 @@ declare namespace FirebaseFirestore { * * @param expression The dividend expression. * @param value The divisor constant. - * @return A new {@code Expr} representing the modulo operation. + * @return A new {@code Expression} representing the modulo operation. */ - export function mod(expression: Expr, value: unknown): FunctionExpr; + export function mod( + expression: Expression, + value: unknown + ): FunctionExpression; /** * @beta * Creates an expression that calculates the modulo (remainder) of dividing a field's value by an expression. @@ -5698,9 +5811,12 @@ declare namespace FirebaseFirestore { * * @param fieldName The dividend field name. * @param expression The divisor expression. - * @return A new {@code Expr} representing the modulo operation. + * @return A new {@code Expression} representing the modulo operation. */ - export function mod(fieldName: string, expression: Expr): FunctionExpr; + export function mod( + fieldName: string, + expression: Expression + ): FunctionExpression; /** * @beta * Creates an expression that calculates the modulo (remainder) of dividing a field's value by a constant. @@ -5712,9 +5828,9 @@ declare namespace FirebaseFirestore { * * @param fieldName The dividend field name. * @param value The divisor constant. - * @return A new {@code Expr} representing the modulo operation. + * @return A new {@code Expression} representing the modulo operation. */ - export function mod(fieldName: string, value: unknown): FunctionExpr; + export function mod(fieldName: string, value: unknown): FunctionExpression; /** * @beta @@ -5729,9 +5845,9 @@ declare namespace FirebaseFirestore { * ``` * * @param elements The JavaScript object literal whose properties will be used to create the Firestore map expression. - * @returns A new {@code FunctionExpr} representing the map function. + * @returns A new {@code FunctionExpression} representing the map function. */ - export function map(elements: Record): FunctionExpr; + export function map(elements: Record): FunctionExpression; /** * @beta * Creates an expression that creates a Firestore array value from a given JavaScript array. @@ -5743,9 +5859,9 @@ declare namespace FirebaseFirestore { * ``` * * @param elements The input array to evaluate in the expression. - * @return A new {@code Expr} representing the array function. + * @return A new {@code Expression} representing the array function. */ - export function array(elements: unknown[]): FunctionExpr; + export function array(elements: unknown[]): FunctionExpression; /** * @beta @@ -5753,28 +5869,34 @@ declare namespace FirebaseFirestore { * * ```typescript * // Check if the 'age' field is equal to an expression - * eq(field("age"), field("minAge").add(10)); + * equal(field("age"), field("minAge").add(10)); * ``` * * @param left The first expression to compare. * @param right The second expression to compare. - * @return A new `BooleanExpr` representing the equality comparison. + * @return A new `BooleanExpression` representing the equality comparison. */ - export function eq(left: Expr, right: Expr): BooleanExpr; + export function equal( + left: Expression, + right: Expression + ): BooleanExpression; /** * @beta * Creates an expression that checks if an expression is equal to a constant value. * * ```typescript * // Check if the 'age' field is equal to 21 - * eq(field("age"), 21); + * equal(field("age"), 21); * ``` * * @param expression The expression to compare. * @param value The constant value to compare to. - * @return A new `Expr` representing the equality comparison. + * @return A new `Expression` representing the equality comparison. */ - export function eq(expression: Expr, value: unknown): BooleanExpr; + export function equal( + expression: Expression, + value: unknown + ): BooleanExpression; /** * @beta @@ -5782,56 +5904,65 @@ declare namespace FirebaseFirestore { * * ```typescript * // Check if the 'age' field is equal to the 'limit' field - * eq("age", field("limit")); + * equal("age", field("limit")); * ``` * * @param fieldName The name of the field to compare. * @param expression The expression to compare the field's value against. - * @return A new `BooleanExpr` representing the equality comparison. + * @return A new `BooleanExpression` representing the equality comparison. */ - export function eq(fieldName: string, expression: Expr): BooleanExpr; + export function equal( + fieldName: string, + expression: Expression + ): BooleanExpression; /** * @beta * Creates an expression that checks if a field's value is equal to a constant value. * * ```typescript * // Check if the 'city' field is equal to string constant "London" - * eq("city", "London"); + * equal("city", "London"); * ``` * * @param fieldName The field name to compare. * @param value The constant value to compare to. - * @return A new `Expr` representing the equality comparison. + * @return A new `Expression` representing the equality comparison. */ - export function eq(fieldName: string, value: unknown): BooleanExpr; + export function equal(fieldName: string, value: unknown): BooleanExpression; /** * @beta * Creates an expression that checks if two expressions are not equal. * * ```typescript * // Check if the 'status' field is not equal to field 'finalState' - * neq(field("status"), field("finalState")); + * notEqual(field("status"), field("finalState")); * ``` * * @param left The first expression to compare. * @param right The second expression to compare. - * @return A new `Expr` representing the inequality comparison. + * @return A new `Expression` representing the inequality comparison. */ - export function neq(left: Expr, right: Expr): BooleanExpr; + export function notEqual( + left: Expression, + right: Expression + ): BooleanExpression; /** * @beta * Creates an expression that checks if an expression is not equal to a constant value. * * ```typescript * // Check if the 'status' field is not equal to "completed" - * neq(field("status"), "completed"); + * notEqual(field("status"), "completed"); * ``` * * @param expression The expression to compare. * @param value The constant value to compare to. - * @return A new `Expr` representing the inequality comparison. + * @return A new `Expression` representing the inequality comparison. */ - export function neq(expression: Expr, value: unknown): BooleanExpr; + export function notEqual( + expression: Expression, + value: unknown + ): BooleanExpression; /** * @beta @@ -5839,56 +5970,68 @@ declare namespace FirebaseFirestore { * * ```typescript * // Check if the 'status' field is not equal to the value of 'expectedStatus' - * neq("status", field("expectedStatus")); + * notEqual("status", field("expectedStatus")); * ``` * * @param fieldName The field name to compare. * @param expression The expression to compare to. - * @return A new {@link BooleanExpr} representing the inequality comparison. + * @return A new {@link BooleanExpression} representing the inequality comparison. */ - export function neq(fieldName: string, expression: Expr): BooleanExpr; + export function notEqual( + fieldName: string, + expression: Expression + ): BooleanExpression; /** * @beta * Creates an expression that checks if a field's value is not equal to a constant value. * * ```typescript * // Check if the 'country' field is not equal to "USA" - * neq("country", "USA"); + * notEqual("country", "USA"); * ``` * * @param fieldName The field name to compare. * @param value The constant value to compare to. - * @return A new `Expr` representing the inequality comparison. + * @return A new `Expression` representing the inequality comparison. */ - export function neq(fieldName: string, value: unknown): BooleanExpr; + export function notEqual( + fieldName: string, + value: unknown + ): BooleanExpression; /** * @beta * Creates an expression that checks if the first expression is less than the second expression. * * ```typescript * // Check if the 'age' field is less than 30 - * lt(field("age"), field("limit")); + * lessThan(field("age"), field("limit")); * ``` * * @param left The first expression to compare. * @param right The second expression to compare. - * @return A new `Expr` representing the less than comparison. + * @return A new `Expression` representing the less than comparison. */ - export function lt(left: Expr, right: Expr): BooleanExpr; + export function lessThan( + left: Expression, + right: Expression + ): BooleanExpression; /** * @beta * Creates an expression that checks if an expression is less than a constant value. * * ```typescript * // Check if the 'age' field is less than 30 - * lt(field("age"), 30); + * lessThan(field("age"), 30); * ``` * * @param expression The expression to compare. * @param value The constant value to compare to. - * @return A new `Expr` representing the less than comparison. + * @return A new `Expression` representing the less than comparison. */ - export function lt(expression: Expr, value: unknown): BooleanExpr; + export function lessThan( + expression: Expression, + value: unknown + ): BooleanExpression; /** * @beta @@ -5896,28 +6039,34 @@ declare namespace FirebaseFirestore { * * ```typescript * // Check if the 'age' field is less than the 'limit' field - * lt("age", field("limit")); + * lessThan("age", field("limit")); * ``` * * @param fieldName The field name to compare. * @param expression The expression to compare to. - * @return A new `BooleanExpr` representing the less than comparison. + * @return A new `BooleanExpression` representing the less than comparison. */ - export function lt(fieldName: string, expression: Expr): BooleanExpr; + export function lessThan( + fieldName: string, + expression: Expression + ): BooleanExpression; /** * @beta * Creates an expression that checks if a field's value is less than a constant value. * * ```typescript * // Check if the 'price' field is less than 50 - * lt("price", 50); + * lessThan("price", 50); * ``` * * @param fieldName The field name to compare. * @param value The constant value to compare to. - * @return A new `Expr` representing the less than comparison. + * @return A new `Expression` representing the less than comparison. */ - export function lt(fieldName: string, value: unknown): BooleanExpr; + export function lessThan( + fieldName: string, + value: unknown + ): BooleanExpression; /** * @beta * Creates an expression that checks if the first expression is less than or equal to the second @@ -5925,14 +6074,17 @@ declare namespace FirebaseFirestore { * * ```typescript * // Check if the 'quantity' field is less than or equal to 20 - * lte(field("quantity"), field("limit")); + * lessThanOrEqual(field("quantity"), field("limit")); * ``` * * @param left The first expression to compare. * @param right The second expression to compare. - * @return A new `Expr` representing the less than or equal to comparison. + * @return A new `Expression` representing the less than or equal to comparison. */ - export function lte(left: Expr, right: Expr): BooleanExpr; + export function lessThanOrEqual( + left: Expression, + right: Expression + ): BooleanExpression; /** * @beta @@ -5940,14 +6092,17 @@ declare namespace FirebaseFirestore { * * ```typescript * // Check if the 'quantity' field is less than or equal to 20 - * lte(field("quantity"), 20); + * lessThanOrEqual(field("quantity"), 20); * ``` * - * @param expression The {@link Expr} to compare. + * @param expression The {@link Expression} to compare. * @param value The constant value to compare against. - * @return A new {@link BooleanExpr} representing the less than or equal to comparison. + * @return A new {@link BooleanExpression} representing the less than or equal to comparison. */ - export function lte(expression: Expr, value: unknown): BooleanExpr; + export function lessThanOrEqual( + expression: Expression, + value: unknown + ): BooleanExpression; /** * @beta @@ -5955,28 +6110,34 @@ declare namespace FirebaseFirestore { * * ```typescript * // Check if the 'quantity' field is less than or equal to the 'limit' field - * lte("quantity", field("limit")); + * lessThanOrEqual("quantity", field("limit")); * ``` * * @param fieldName The name of the field whose value will be compared. * @param expression The expression to compare against the field's value. - * @return A new {@link BooleanExpr} representing the less than or equal to comparison. + * @return A new {@link BooleanExpression} representing the less than or equal to comparison. */ - export function lte(fieldName: string, expression: Expr): BooleanExpr; + export function lessThanOrEqual( + fieldName: string, + expression: Expression + ): BooleanExpression; /** * @beta * Creates an expression that checks if a field's value is less than or equal to a constant value. * * ```typescript * // Check if the 'score' field is less than or equal to 70 - * lte("score", 70); + * lessThanOrEqual("score", 70); * ``` * * @param fieldName The field name to compare. * @param value The constant value to compare to. - * @return A new `Expr` representing the less than or equal to comparison. + * @return A new `Expression` representing the less than or equal to comparison. */ - export function lte(fieldName: string, value: unknown): BooleanExpr; + export function lessThanOrEqual( + fieldName: string, + value: unknown + ): BooleanExpression; /** * @beta * Creates an expression that checks if the first expression is greater than the second @@ -5984,28 +6145,34 @@ declare namespace FirebaseFirestore { * * ```typescript * // Check if the 'age' field is greater than 18 - * gt(field("age"), Constant(9).add(9)); + * greaterThan(field("age"), constant(9).add(9)); * ``` * * @param left The first expression to compare. * @param right The second expression to compare. - * @return A new `Expr` representing the greater than comparison. + * @return A new `Expression` representing the greater than comparison. */ - export function gt(left: Expr, right: Expr): BooleanExpr; + export function greaterThan( + left: Expression, + right: Expression + ): BooleanExpression; /** * @beta * Creates an expression that checks if an expression is greater than a constant value. * * ```typescript * // Check if the 'age' field is greater than 18 - * gt(field("age"), 18); + * greaterThan(field("age"), 18); * ``` * * @param expression The expression to compare. * @param value The constant value to compare to. - * @return A new `Expr` representing the greater than comparison. + * @return A new `Expression` representing the greater than comparison. */ - export function gt(expression: Expr, value: unknown): BooleanExpr; + export function greaterThan( + expression: Expression, + value: unknown + ): BooleanExpression; /** * @beta @@ -6013,28 +6180,34 @@ declare namespace FirebaseFirestore { * * ```typescript * // Check if the value of field 'age' is greater than the value of field 'limit' - * gt("age", field("limit")); + * greaterThan("age", field("limit")); * ``` * * @param fieldName The name of the field to compare. * @param expression The expression to compare against. - * @return A new {@link BooleanExpr} representing the greater than comparison. + * @return A new {@link BooleanExpression} representing the greater than comparison. */ - export function gt(fieldName: string, expression: Expr): BooleanExpr; + export function greaterThan( + fieldName: string, + expression: Expression + ): BooleanExpression; /** * @beta * Creates an expression that checks if a field's value is greater than a constant value. * * ```typescript * // Check if the 'price' field is greater than 100 - * gt("price", 100); + * greaterThan("price", 100); * ``` * * @param fieldName The name of the field to compare. * @param value The constant value to compare to. - * @return A new {@link BooleanExpr} representing the greater than comparison. + * @return A new {@link BooleanExpression} representing the greater than comparison. */ - export function gt(fieldName: string, value: unknown): BooleanExpr; + export function greaterThan( + fieldName: string, + value: unknown + ): BooleanExpression; /** * @beta * Creates an expression that checks if the first expression is greater than or equal to the @@ -6042,14 +6215,17 @@ declare namespace FirebaseFirestore { * * ```typescript * // Check if the 'quantity' field is greater than or equal to the field "threshold" - * gte(field("quantity"), field("threshold")); + * greaterThanOrEqual(field("quantity"), field("threshold")); * ``` * * @param left The first expression to compare. * @param right The second expression to compare. - * @return A new `Expr` representing the greater than or equal to comparison. + * @return A new `Expression` representing the greater than or equal to comparison. */ - export function gte(left: Expr, right: Expr): BooleanExpr; + export function greaterThanOrEqual( + left: Expression, + right: Expression + ): BooleanExpression; /** * @beta * Creates an expression that checks if an expression is greater than or equal to a constant @@ -6057,28 +6233,34 @@ declare namespace FirebaseFirestore { * * ```typescript * // Check if the 'quantity' field is greater than or equal to 10 - * gte(field("quantity"), 10); + * greaterThanOrEqual(field("quantity"), 10); * ``` * * @param expression The expression to compare. * @param value The constant value to compare to. - * @return A new `Expr` representing the greater than or equal to comparison. + * @return A new `Expression` representing the greater than or equal to comparison. */ - export function gte(expression: Expr, value: unknown): BooleanExpr; + export function greaterThanOrEqual( + expression: Expression, + value: unknown + ): BooleanExpression; /** * @beta * Creates an expression that checks if a field's value is greater than or equal to an expression. * * ```typescript * // Check if the value of field 'age' is greater than or equal to the value of field 'limit' - * gte("age", field("limit")); + * greaterThanOrEqual("age", field("limit")); * ``` * * @param fieldName The field name to compare. * @param value The expression to compare to. - * @return A new `Expr` representing the greater than or equal to comparison. + * @return A new `Expression` representing the greater than or equal to comparison. */ - export function gte(fieldName: string, value: Expr): BooleanExpr; + export function greaterThanOrEqual( + fieldName: string, + value: Expression + ): BooleanExpression; /** * @beta * Creates an expression that checks if a field's value is greater than or equal to a constant @@ -6086,14 +6268,60 @@ declare namespace FirebaseFirestore { * * ```typescript * // Check if the 'score' field is greater than or equal to 80 - * gte("score", 80); + * greaterThanOrEqual("score", 80); * ``` * * @param fieldName The field name to compare. * @param value The constant value to compare to. - * @return A new `Expr` representing the greater than or equal to comparison. + * @return A new `Expression` representing the greater than or equal to comparison. */ - export function gte(fieldName: string, value: unknown): BooleanExpr; + export function greaterThanOrEqual( + fieldName: string, + value: unknown + ): BooleanExpression; + + /** + * @beta + * + * Creates an expression that concatenates an array expression with other arrays. + * + * ```typescript + * // Combine the 'items' array with two new item arrays + * arrayConcat(field("items"), [field("newItems"), field("otherItems")]); + * ``` + * + * @param firstArray The first array expression to concatenate to. + * @param secondArray The second array expression or array literal to concatenate to. + * @param otherArrays Optional additional array expressions or array literals to concatenate. + * @return A new {@code Expr} representing the concatenated array. + */ + export function arrayConcat( + firstArray: Expression, + secondArray: Expression | unknown[], + ...otherArrays: Array + ): FunctionExpression; + + /** + * @beta + * + * Creates an expression that concatenates a field's array value with other arrays. + * + * ```typescript + * // Combine the 'items' array with two new item arrays + * arrayConcat("items", [field("newItems"), field("otherItems")]); + * ``` + * + * @param firstArrayField The first array to concatenate to. + * @param secondArray The second array expression or array literal to concatenate to. + * @param otherArrays Optional additional array expressions or array literals to concatenate. + * @return A new {@code Expr} representing the concatenated array. + */ + export function arrayConcat( + firstArrayField: string, + secondArray: Expression | unknown[], + ...otherArrays: Array + ): FunctionExpression; + /** * @beta * Creates an expression that checks if an array expression contains a specific element. @@ -6105,9 +6333,12 @@ declare namespace FirebaseFirestore { * * @param array The array expression to check. * @param element The element to search for in the array. - * @return A new {@code Expr} representing the 'array_contains' comparison. + * @return A new {@code Expression} representing the 'array_contains' comparison. */ - export function arrayContains(array: Expr, element: Expr): FunctionExpr; + export function arrayContains( + array: Expression, + element: Expression + ): FunctionExpression; /** * @beta * Creates an expression that checks if an array expression contains a specific element. @@ -6119,9 +6350,12 @@ declare namespace FirebaseFirestore { * * @param array The array expression to check. * @param element The element to search for in the array. - * @return A new {@code Expr} representing the 'array_contains' comparison. + * @return A new {@code Expression} representing the 'array_contains' comparison. */ - export function arrayContains(array: Expr, element: unknown): FunctionExpr; + export function arrayContains( + array: Expression, + element: unknown + ): FunctionExpression; /** * @beta * Creates an expression that checks if a field's array value contains a specific element. @@ -6133,12 +6367,12 @@ declare namespace FirebaseFirestore { * * @param fieldName The field name to check. * @param element The element to search for in the array. - * @return A new {@code Expr} representing the 'array_contains' comparison. + * @return A new {@code Expression} representing the 'array_contains' comparison. */ export function arrayContains( fieldName: string, - element: Expr - ): FunctionExpr; + element: Expression + ): FunctionExpression; /** * @beta * Creates an expression that checks if a field's array value contains a specific value. @@ -6150,12 +6384,12 @@ declare namespace FirebaseFirestore { * * @param fieldName The field name to check. * @param element The element to search for in the array. - * @return A new {@code Expr} representing the 'array_contains' comparison. + * @return A new {@code Expression} representing the 'array_contains' comparison. */ export function arrayContains( fieldName: string, element: unknown - ): BooleanExpr; + ): BooleanExpression; /** * @beta * Creates an expression that checks if an array expression contains any of the specified @@ -6168,12 +6402,12 @@ declare namespace FirebaseFirestore { * * @param array The array expression to check. * @param values The elements to check for in the array. - * @return A new {@code Expr} representing the 'array_contains_any' comparison. + * @return A new {@code Expression} representing the 'array_contains_any' comparison. */ export function arrayContainsAny( - array: Expr, - values: Array - ): BooleanExpr; + array: Expression, + values: Array + ): BooleanExpression; /** * @beta * Creates an expression that checks if a field's array value contains any of the specified @@ -6187,12 +6421,12 @@ declare namespace FirebaseFirestore { * * @param fieldName The field name to check. * @param values The elements to check for in the array. - * @return A new {@code Expr} representing the 'array_contains_any' comparison. + * @return A new {@code Expression} representing the 'array_contains_any' comparison. */ export function arrayContainsAny( fieldName: string, - values: Array - ): BooleanExpr; + values: Array + ): BooleanExpression; /** * @beta * Creates an expression that checks if an array expression contains any of the specified @@ -6205,9 +6439,12 @@ declare namespace FirebaseFirestore { * * @param array The array expression to check. * @param values An expression that evaluates to an array, whose elements to check for in the array. - * @return A new {@code Expr} representing the 'array_contains_any' comparison. + * @return A new {@code Expression} representing the 'array_contains_any' comparison. */ - export function arrayContainsAny(array: Expr, values: Expr): BooleanExpr; + export function arrayContainsAny( + array: Expression, + values: Expression + ): BooleanExpression; /** * @beta * Creates an expression that checks if a field's array value contains any of the specified @@ -6221,12 +6458,12 @@ declare namespace FirebaseFirestore { * * @param fieldName The field name to check. * @param values An expression that evaluates to an array, whose elements to check for in the array field. - * @return A new {@code Expr} representing the 'array_contains_any' comparison. + * @return A new {@code Expression} representing the 'array_contains_any' comparison. */ export function arrayContainsAny( fieldName: string, - values: Expr - ): BooleanExpr; + values: Expression + ): BooleanExpression; /** * @beta * Creates an expression that checks if an array expression contains all the specified elements. @@ -6238,12 +6475,12 @@ declare namespace FirebaseFirestore { * * @param array The array expression to check. * @param values The elements to check for in the array. - * @return A new {@code Expr} representing the 'array_contains_all' comparison. + * @return A new {@code Expression} representing the 'array_contains_all' comparison. */ export function arrayContainsAll( - array: Expr, - values: Array - ): BooleanExpr; + array: Expression, + values: Array + ): BooleanExpression; /** * @beta * Creates an expression that checks if a field's array value contains all the specified values or @@ -6256,12 +6493,12 @@ declare namespace FirebaseFirestore { * * @param fieldName The field name to check. * @param values The elements to check for in the array. - * @return A new {@code Expr} representing the 'array_contains_all' comparison. + * @return A new {@code Expression} representing the 'array_contains_all' comparison. */ export function arrayContainsAll( fieldName: string, - values: Array - ): BooleanExpr; + values: Array + ): BooleanExpression; /** * @beta * Creates an expression that checks if an array expression contains all the specified elements. @@ -6280,12 +6517,12 @@ declare namespace FirebaseFirestore { * * @param array An expression evaluating to the array to check. * @param arrayExpression An expression evaluating to an array of elements to check for. - * @return A new {@code BooleanExpr} representing the 'array_contains_all' comparison. + * @return A new {@code BooleanExpression} representing the 'array_contains_all' comparison. */ export function arrayContainsAll( - array: Expr, - arrayExpression: Expr - ): BooleanExpr; + array: Expression, + arrayExpression: Expression + ): BooleanExpression; /** * @beta @@ -6298,12 +6535,12 @@ declare namespace FirebaseFirestore { * * @param fieldName The name of the array field to check. * @param arrayExpression An expression that evaluates to an array of values to check for. - * @return A new {@code BooleanExpr} representing the 'array_contains_all' comparison. + * @return A new {@code BooleanExpression} representing the 'array_contains_all' comparison. */ export function arrayContainsAll( fieldName: string, - arrayExpression: Expr - ): BooleanExpr; + arrayExpression: Expression + ): BooleanExpression; /** * @beta * Creates an expression that calculates the length of an array in a specified field. @@ -6314,9 +6551,9 @@ declare namespace FirebaseFirestore { * ``` * * @param fieldName The name of the field containing an array to calculate the length of. - * @return A new {@code Expr} representing the length of the array. + * @return A new {@code Expression} representing the length of the array. */ - export function arrayLength(fieldName: string): FunctionExpr; + export function arrayLength(fieldName: string): FunctionExpression; /** * @beta * Creates an expression that calculates the length of an array expression. @@ -6327,9 +6564,9 @@ declare namespace FirebaseFirestore { * ``` * * @param array The array expression to calculate the length of. - * @return A new {@code Expr} representing the length of the array. + * @return A new {@code Expression} representing the length of the array. */ - export function arrayLength(array: Expr): FunctionExpr; + export function arrayLength(array: Expression): FunctionExpression; /** * @beta * Creates an expression that checks if an expression, when evaluated, is equal to any of the provided values or @@ -6337,31 +6574,34 @@ declare namespace FirebaseFirestore { * * ```typescript * // Check if the 'category' field is either "Electronics" or value of field 'primaryType' - * eqAny(field("category"), [constant("Electronics"), field("primaryType")]); + * equalAny(field("category"), [constant("Electronics"), field("primaryType")]); * ``` * * @param expression The expression whose results to compare. * @param values The values to check against. - * @return A new {@code Expr} representing the 'IN' comparison. + * @return A new {@code Expression} representing the 'IN' comparison. */ - export function eqAny( - expression: Expr, - values: Array - ): BooleanExpr; + export function equalAny( + expression: Expression, + values: Array + ): BooleanExpression; /** * @beta * Creates an expression that checks if an expression is equal to any of the provided values. * * ```typescript * // Check if the 'category' field is set to a value in the disabledCategories field - * eqAny(field("category"), field('disabledCategories')); + * equalAny(field("category"), field('disabledCategories')); * ``` * * @param expression The expression whose results to compare. * @param arrayExpression An expression that evaluates to an array, whose elements to check for equality to the input. - * @return A new {@code Expr} representing the 'IN' comparison. + * @return A new {@code Expression} representing the 'IN' comparison. */ - export function eqAny(expression: Expr, arrayExpression: Expr): BooleanExpr; + export function equalAny( + expression: Expression, + arrayExpression: Expression + ): BooleanExpression; /** * @beta * Creates an expression that checks if a field's value is equal to any of the provided values or @@ -6369,17 +6609,17 @@ declare namespace FirebaseFirestore { * * ```typescript * // Check if the 'category' field is either "Electronics" or value of field 'primaryType' - * eqAny("category", [constant("Electronics"), field("primaryType")]); + * equalAny("category", [constant("Electronics"), field("primaryType")]); * ``` * * @param fieldName The field to compare. * @param values The values to check against. - * @return A new {@code Expr} representing the 'IN' comparison. + * @return A new {@code Expression} representing the 'IN' comparison. */ - export function eqAny( + export function equalAny( fieldName: string, - values: Array - ): BooleanExpr; + values: Array + ): BooleanExpression; /** * @beta @@ -6390,17 +6630,17 @@ declare namespace FirebaseFirestore { * * ```typescript * // Check if the 'category' field's value is present in the 'allowedCategories' array field. - * eqAny("category", field("allowedCategories")); + * equalAny("category", field("allowedCategories")); * ``` * * @param fieldName The name of the field to compare. * @param arrayExpression An expression that evaluates to an array. The function checks if the value of `fieldName` is equal to any element within this array. - * @return A new {@code BooleanExpr} representing the 'IN' comparison. + * @return A new {@code BooleanExpression} representing the 'IN' comparison. */ - export function eqAny( + export function equalAny( fieldName: string, - arrayExpression: Expr - ): BooleanExpr; + arrayExpression: Expression + ): BooleanExpression; /** * @beta * Creates an expression that checks if an expression is not equal to any of the provided values @@ -6408,17 +6648,17 @@ declare namespace FirebaseFirestore { * * ```typescript * // Check if the 'status' field is neither "pending" nor the value of 'rejectedStatus' - * notEqAny(field("status"), ["pending", field("rejectedStatus")]); + * notEqualAny(field("status"), ["pending", field("rejectedStatus")]); * ``` * * @param element The expression to compare. * @param values The values to check against. - * @return A new {@code Expr} representing the 'NOT IN' comparison. + * @return A new {@code Expression} representing the 'NOT IN' comparison. */ - export function notEqAny( - element: Expr, - values: Array - ): BooleanExpr; + export function notEqualAny( + element: Expression, + values: Array + ): BooleanExpression; /** * @beta * Creates an expression that checks if a field's value is not equal to any of the provided values @@ -6426,17 +6666,17 @@ declare namespace FirebaseFirestore { * * ```typescript * // Check if the 'status' field is neither "pending" nor the value of 'rejectedStatus' - * notEqAny("status", [constant("pending"), field("rejectedStatus")]); + * notEqualAny("status", [constant("pending"), field("rejectedStatus")]); * ``` * * @param fieldName The field name to compare. * @param values The values to check against. - * @return A new {@code Expr} representing the 'NOT IN' comparison. + * @return A new {@code Expression} representing the 'NOT IN' comparison. */ - export function notEqAny( + export function notEqualAny( fieldName: string, - values: Array - ): BooleanExpr; + values: Array + ): BooleanExpression; /** * @beta @@ -6445,31 +6685,34 @@ declare namespace FirebaseFirestore { * * ```typescript * // Check if the 'status' field is not present in the array stored in the 'invalidStatuses' field. - * notEqAny(field("status"), field("invalidStatuses")); + * notEqualAny(field("status"), field("invalidStatuses")); * ``` * * @param element The expression representing the value to check. * @param arrayExpression An expression that evaluates to an array of values to check against. - * @return A new {@code BooleanExpr} representing the 'NOT IN' comparison. + * @return A new {@code BooleanExpression} representing the 'NOT IN' comparison. */ - export function notEqAny(element: Expr, arrayExpression: Expr): BooleanExpr; + export function notEqualAny( + element: Expression, + arrayExpression: Expression + ): BooleanExpression; /** * @beta * Creates an expression that checks if a field's value is not equal to any of the values in the evaluated expression. * * ```typescript * // Check if the 'status' field is not equal to any value in the field 'rejectedStatuses' - * notEqAny("status", field("rejectedStatuses")); + * notEqualAny("status", field("rejectedStatuses")); * ``` * * @param fieldName The field name to compare. * @param arrayExpression The values to check against. - * @return A new {@code Expr} representing the 'NOT IN' comparison. + * @return A new {@code Expression} representing the 'NOT IN' comparison. */ - export function notEqAny( + export function notEqualAny( fieldName: string, - arrayExpression: Expr - ): BooleanExpr; + arrayExpression: Expression + ): BooleanExpression; /** * @beta @@ -6480,22 +6723,22 @@ declare namespace FirebaseFirestore { * // Check if exactly one of the conditions is true: 'age' greater than 18, 'city' is "London", * // or 'status' is "active". * const condition = xor( - * gt("age", 18), - * eq("city", "London"), - * eq("status", "active") + * greaterThan("age", 18), + * equal("city", "London"), + * equal("status", "active") * ); * ``` * * @param first The first Boolean expression. * @param second The second Boolean expression. * @param additionalConditions Optional: Additional Boolean expressions to include in the XOR operation. - * @returns A new {@link BooleanExpr} representing the logical 'XOR' operation. + * @returns A new {@link BooleanExpression} representing the logical 'XOR' operation. */ export function xor( - first: BooleanExpr, - second: BooleanExpr, - ...additionalConditions: BooleanExpr[] - ): BooleanExpr; + first: BooleanExpression, + second: BooleanExpression, + ...additionalConditions: BooleanExpression[] + ): BooleanExpression; /** * @beta * Creates a conditional expression that evaluates to a 'then' expression if a condition is true @@ -6503,33 +6746,33 @@ declare namespace FirebaseFirestore { * * ```typescript * // If 'age' is greater than 18, return "Adult"; otherwise, return "Minor". - * cond( - * gt("age", 18), constant("Adult"), constant("Minor")); + * conditional( + * greaterThan("age", 18), constant("Adult"), constant("Minor")); * ``` * * @param condition The condition to evaluate. * @param thenExpr The expression to evaluate if the condition is true. * @param elseExpr The expression to evaluate if the condition is false. - * @return A new {@code Expr} representing the conditional expression. + * @return A new {@code Expression} representing the conditional expression. */ - export function cond( - condition: BooleanExpr, - thenExpr: Expr, - elseExpr: Expr - ): FunctionExpr; + export function conditional( + condition: BooleanExpression, + thenExpr: Expression, + elseExpr: Expression + ): FunctionExpression; /** * @beta * Creates an expression that negates a filter condition. * * ```typescript * // Find documents where the 'completed' field is NOT true - * not(eq("completed", true)); + * not(equal("completed", true)); * ``` * * @param booleanExpr The filter condition to negate. - * @return A new {@code Expr} representing the negated filter condition. + * @return A new {@code Expression} representing the negated filter condition. */ - export function not(booleanExpr: BooleanExpr): BooleanExpr; + export function not(booleanExpr: BooleanExpression): BooleanExpression; /** * @beta * Creates an expression that returns the largest value between multiple input @@ -6544,13 +6787,13 @@ declare namespace FirebaseFirestore { * @param first The first operand expression. * @param second The second expression or literal. * @param others Optional additional expressions or literals. - * @return A new {@code Expr} representing the logical max operation. + * @return A new {@code Expression} representing the logical max operation. */ export function logicalMaximum( - first: Expr, - second: Expr | unknown, - ...others: Array - ): FunctionExpr; + first: Expression, + second: Expression | unknown, + ...others: Array + ): FunctionExpression; /** * @beta * Creates an expression that returns the largest value between multiple input @@ -6565,13 +6808,13 @@ declare namespace FirebaseFirestore { * @param fieldName The first operand field name. * @param second The second expression or literal. * @param others Optional additional expressions or literals. - * @return A new {@code Expr} representing the logical max operation. + * @return A new {@code Expression} representing the logical max operation. */ export function logicalMaximum( fieldName: string, - second: Expr | unknown, - ...others: Array - ): FunctionExpr; + second: Expression | unknown, + ...others: Array + ): FunctionExpression; /** * @beta * Creates an expression that returns the smallest value between multiple input @@ -6586,13 +6829,13 @@ declare namespace FirebaseFirestore { * @param first The first operand expression. * @param second The second expression or literal. * @param others Optional additional expressions or literals. - * @return A new {@code Expr} representing the logical min operation. + * @return A new {@code Expression} representing the logical min operation. */ export function logicalMinimum( - first: Expr, - second: Expr | unknown, - ...others: Array - ): FunctionExpr; + first: Expression, + second: Expression | unknown, + ...others: Array + ): FunctionExpression; /** * @beta * Creates an expression that returns the smallest value between a field's value @@ -6608,13 +6851,13 @@ declare namespace FirebaseFirestore { * @param fieldName The first operand field name. * @param second The second expression or literal. * @param others Optional additional expressions or literals. - * @return A new {@code Expr} representing the logical min operation. + * @return A new {@code Expression} representing the logical min operation. */ export function logicalMinimum( fieldName: string, - second: Expr | unknown, - ...others: Array - ): FunctionExpr; + second: Expression | unknown, + ...others: Array + ): FunctionExpression; /** * @beta @@ -6626,9 +6869,9 @@ declare namespace FirebaseFirestore { * ``` * * @param value An expression representing the field to check for existence. - * @return A new {@code BooleanExpr} representing the 'exists' check. + * @return A new {@code BooleanExpression} representing the 'exists' check. */ - export function exists(value: Expr): BooleanExpr; + export function exists(value: Expression): BooleanExpression; /** * @beta * Creates an expression that checks if a field exists. @@ -6639,37 +6882,10 @@ declare namespace FirebaseFirestore { * ``` * * @param fieldName The field name to check. - * @return A new {@code Expr} representing the 'exists' check. + * @return A new {@code Expression} representing the 'exists' check. */ - export function exists(fieldName: string): BooleanExpr; + export function exists(fieldName: string): BooleanExpression; - /** - * @beta - * Creates an expression that checks if an expression evaluates to 'NaN' (Not a Number). - * - * ```typescript - * // Check if the result of a calculation is NaN - * isNan(field("value").divide(0)); - * ``` - * - * @param value The expression to check. - * @return A new {@code Expr} representing the 'isNaN' check. - */ - export function isNan(value: Expr): BooleanExpr; - - /** - * @beta - * Creates an expression that checks if a field's value evaluates to 'NaN' (Not a Number). - * - * ```typescript - * // Check if the result of a calculation is NaN - * isNan("value"); - * ``` - * - * @param fieldName The name of the field to check. - * @return A new {@code BooleanExpr} representing the 'isNan' check. - */ - export function isNan(fieldName: string): BooleanExpr; /** * @beta * Creates an expression that reverses a string. @@ -6680,9 +6896,9 @@ declare namespace FirebaseFirestore { * ``` * * @param stringExpression An expression evaluating to a string value, which will be reversed. - * @return A new {@code Expr} representing the reversed string. + * @return A new {@code Expression} representing the reversed string. */ - export function reverse(stringExpression: Expr): FunctionExpr; + export function reverse(stringExpression: Expression): FunctionExpression; /** * @beta * Creates an expression that reverses a string value in the specified field. @@ -6693,9 +6909,9 @@ declare namespace FirebaseFirestore { * ``` * * @param field The name of the field representing the string to reverse. - * @return A new {@code Expr} representing the reversed string. + * @return A new {@code Expression} representing the reversed string. */ - export function reverse(field: string): FunctionExpr; + export function reverse(field: string): FunctionExpression; /** * @beta * Creates an expression that reverses an array. @@ -6706,9 +6922,11 @@ declare namespace FirebaseFirestore { * ``` * * @param arrayExpression An expression evaluating to an array value, which will be reversed. - * @return A new {@code Expr} representing the reversed array. + * @return A new {@code Expression} representing the reversed array. */ - export function arrayReverse(arrayExpression: Expr): FunctionExpr; + export function arrayReverse( + arrayExpression: Expression + ): FunctionExpression; /** * @beta * Creates an expression that reverses an array. @@ -6719,9 +6937,9 @@ declare namespace FirebaseFirestore { * ``` * * @param fieldName The name of the field to reverse. - * @return A new {@code Expr} representing the reversed array. + * @return A new {@code Expression} representing the reversed array. */ - export function arrayReverse(fieldName: string): FunctionExpr; + export function arrayReverse(fieldName: string): FunctionExpression; /** * @beta * Creates an expression that computes the ceiling of a numeric value. @@ -6732,9 +6950,9 @@ declare namespace FirebaseFirestore { * ``` * * @param expression An expression evaluating to a numeric value, which the ceiling will be computed for. - * @return A new {@code Expr} representing the ceiling of the numeric value. + * @return A new {@code Expression} representing the ceiling of the numeric value. */ - export function ceil(expression: Expr): FunctionExpr; + export function ceil(expression: Expression): FunctionExpression; /** * @beta * Creates an expression that computes the ceiling of a numeric value. @@ -6745,9 +6963,9 @@ declare namespace FirebaseFirestore { * ``` * * @param fieldName The name of the field to compute the ceiling of. - * @return A new {@code Expr} representing the ceiling of the numeric value. + * @return A new {@code Expression} representing the ceiling of the numeric value. */ - export function ceil(fieldName: string): FunctionExpr; + export function ceil(fieldName: string): FunctionExpression; /** * @beta @@ -6761,9 +6979,9 @@ declare namespace FirebaseFirestore { * ``` * * @param expression An expression evaluating to a numeric value, which will be used as the exponent for `e`. - * @returns A new {@link FunctionExpr} representing `e` raised to the power of the input expression's result. + * @returns A new {@link FunctionExpression} representing `e` raised to the power of the input expression's result. */ - export function exp(expression: Expr): FunctionExpr; + export function exp(expression: Expression): FunctionExpression; /** * @beta @@ -6775,9 +6993,9 @@ declare namespace FirebaseFirestore { * ``` * * @param fieldName The name of the field whose numeric value will be used as the exponent. - * @return A new {@code FunctionExpr} representing 'e' raised to the power of the numeric value. + * @return A new {@code FunctionExpression} representing 'e' raised to the power of the numeric value. */ - export function exp(fieldName: string): FunctionExpr; + export function exp(fieldName: string): FunctionExpression; /** * @beta * Creates an aggregation that counts the number of distinct values of an evaluated expression. @@ -6785,7 +7003,7 @@ declare namespace FirebaseFirestore { * @param expression The expression to count distinct values of. * @return A new `AggregateFunction` representing the 'count_distinct' aggregation. */ - export function countDistinct(expression: Expr): AggregateFunction; + export function countDistinct(expression: Expression): AggregateFunction; /** * @beta * Creates an aggregation that counts the number of distinct values of a field. @@ -6804,9 +7022,9 @@ declare namespace FirebaseFirestore { * ``` * * @param expr The expression representing the string. - * @return A new {@code Expr} representing the length of the string in bytes. + * @return A new {@code Expression} representing the length of the string in bytes. */ - export function byteLength(expr: Expr): FunctionExpr; + export function byteLength(expr: Expression): FunctionExpression; /** * @beta * Creates an expression that calculates the length of a string represented by a field in UTF-8 bytes, or just the length of a Blob. @@ -6817,9 +7035,9 @@ declare namespace FirebaseFirestore { * ``` * * @param fieldName The name of the field containing the string. - * @return A new {@code Expr} representing the length of the string in bytes. + * @return A new {@code Expression} representing the length of the string in bytes. */ - export function byteLength(fieldName: string): FunctionExpr; + export function byteLength(fieldName: string): FunctionExpression; /** * @beta @@ -6831,9 +7049,9 @@ declare namespace FirebaseFirestore { * ``` * * @param fieldName The name of the field containing the string. - * @return A new {@code Expr} representing the length of the string. + * @return A new {@code Expression} representing the length of the string. */ - export function charLength(fieldName: string): FunctionExpr; + export function charLength(fieldName: string): FunctionExpression; /** * @beta @@ -6845,9 +7063,11 @@ declare namespace FirebaseFirestore { * ``` * * @param stringExpression The expression representing the string to calculate the length of. - * @return A new {@code Expr} representing the length of the string. + * @return A new {@code Expression} representing the length of the string. */ - export function charLength(stringExpression: Expr): FunctionExpr; + export function charLength( + stringExpression: Expression + ): FunctionExpression; /** * @beta * Creates an expression that performs a case-sensitive wildcard string comparison against a @@ -6860,9 +7080,9 @@ declare namespace FirebaseFirestore { * * @param fieldName The name of the field containing the string. * @param pattern The pattern to search for. You can use "%" as a wildcard character. - * @return A new {@code Expr} representing the 'like' comparison. + * @return A new {@code Expression} representing the 'like' comparison. */ - export function like(fieldName: string, pattern: string): BooleanExpr; + export function like(fieldName: string, pattern: string): BooleanExpression; /** * @beta * Creates an expression that performs a case-sensitive wildcard string comparison against a @@ -6875,9 +7095,12 @@ declare namespace FirebaseFirestore { * * @param fieldName The name of the field containing the string. * @param pattern The pattern to search for. You can use "%" as a wildcard character. - * @return A new {@code Expr} representing the 'like' comparison. + * @return A new {@code Expression} representing the 'like' comparison. */ - export function like(fieldName: string, pattern: Expr): BooleanExpr; + export function like( + fieldName: string, + pattern: Expression + ): BooleanExpression; /** * @beta @@ -6890,9 +7113,12 @@ declare namespace FirebaseFirestore { * * @param stringExpression The expression representing the string to perform the comparison on. * @param pattern The pattern to search for. You can use "%" as a wildcard character. - * @return A new {@code BooleanExpr} representing the 'like' comparison. + * @return A new {@code BooleanExpression} representing the 'like' comparison. */ - export function like(stringExpression: Expr, pattern: string): BooleanExpr; + export function like( + stringExpression: Expression, + pattern: string + ): BooleanExpression; /** * @beta * Creates an expression that performs a case-sensitive wildcard string comparison. @@ -6904,9 +7130,12 @@ declare namespace FirebaseFirestore { * * @param stringExpression The expression representing the string to perform the comparison on. * @param pattern The pattern to search for. You can use "%" as a wildcard character. - * @return A new {@code Expr} representing the 'like' comparison. + * @return A new {@code Expression} representing the 'like' comparison. */ - export function like(stringExpression: Expr, pattern: Expr): BooleanExpr; + export function like( + stringExpression: Expression, + pattern: Expression + ): BooleanExpression; /** * @beta * Creates an expression that checks if a string field contains a specified regular expression as @@ -6919,12 +7148,12 @@ declare namespace FirebaseFirestore { * * @param fieldName The name of the field containing the string. * @param pattern The regular expression to use for the search. - * @return A new {@code Expr} representing the 'contains' comparison. + * @return A new {@code Expression} representing the 'contains' comparison. */ export function regexContains( fieldName: string, pattern: string - ): BooleanExpr; + ): BooleanExpression; /** * @beta * Creates an expression that checks if a string field contains a specified regular expression as @@ -6937,12 +7166,12 @@ declare namespace FirebaseFirestore { * * @param fieldName The name of the field containing the string. * @param pattern The regular expression to use for the search. - * @return A new {@code Expr} representing the 'contains' comparison. + * @return A new {@code Expression} representing the 'contains' comparison. */ export function regexContains( fieldName: string, - pattern: Expr - ): BooleanExpr; + pattern: Expression + ): BooleanExpression; /** * @beta @@ -6956,12 +7185,12 @@ declare namespace FirebaseFirestore { * * @param stringExpression The expression representing the string to perform the regex comparison on. * @param pattern The regular expression string to search for within the `stringExpression`. - * @return A new {@code BooleanExpr} representing the result of the regex contains comparison. + * @return A new {@code BooleanExpression} representing the result of the regex contains comparison. */ export function regexContains( - stringExpression: Expr, + stringExpression: Expression, pattern: string - ): BooleanExpr; + ): BooleanExpression; /** * @beta @@ -6978,12 +7207,12 @@ declare namespace FirebaseFirestore { * * @param stringExpression The expression representing the string to perform the comparison on. * @param pattern The regular expression to use for the search. - * @return A new {@code BooleanExpr} representing the 'contains' comparison. + * @return A new {@code BooleanExpression} representing the 'contains' comparison. */ export function regexContains( - stringExpression: Expr, - pattern: Expr - ): BooleanExpr; + stringExpression: Expression, + pattern: Expression + ): BooleanExpression; /** * @beta * Creates an expression that checks if a string field matches a specified regular expression. @@ -6995,15 +7224,18 @@ declare namespace FirebaseFirestore { * * @param fieldName The name of the field containing the string. * @param pattern The regular expression to use for the match. - * @return A new {@code Expr} representing the regular expression match. + * @return A new {@code Expression} representing the regular expression match. */ - export function regexMatch(fieldName: string, pattern: string): BooleanExpr; + export function regexMatch( + fieldName: string, + pattern: string + ): BooleanExpression; /** * @beta * Creates an expression that checks if a string field matches a specified regular expression. * - * The `pattern` parameter is an {@link Expr} that evaluates to the regular expression string. + * The `pattern` parameter is an {@link Expression} that evaluates to the regular expression string. * This allows for dynamic regex patterns, such as those stored in other fields. * * ```typescript @@ -7012,10 +7244,13 @@ declare namespace FirebaseFirestore { * ``` * * @param fieldName The name of the field containing the string value to be matched. - * @param pattern An {@link Expr} that evaluates to the regular expression string to use for the match. - * @return A new {@link BooleanExpr} representing the result of the regular expression match. + * @param pattern An {@link Expression} that evaluates to the regular expression string to use for the match. + * @return A new {@link BooleanExpression} representing the result of the regular expression match. */ - export function regexMatch(fieldName: string, pattern: Expr): BooleanExpr; + export function regexMatch( + fieldName: string, + pattern: Expression + ): BooleanExpression; /** * @beta @@ -7029,12 +7264,12 @@ declare namespace FirebaseFirestore { * * @param stringExpression An expression that evaluates to the string to match against. * @param pattern The regular expression to use for the match. - * @return A new {@link BooleanExpr} representing the result of the regular expression match. + * @return A new {@link BooleanExpression} representing the result of the regular expression match. */ export function regexMatch( - stringExpression: Expr, + stringExpression: Expression, pattern: string - ): BooleanExpr; + ): BooleanExpression; /** * @beta * Creates an expression that checks if a string expression matches a specified regular @@ -7047,80 +7282,80 @@ declare namespace FirebaseFirestore { * * @param stringExpression The expression representing the string to match against. * @param pattern The regular expression to use for the match. - * @return A new {@code Expr} representing the regular expression match. + * @return A new {@code Expression} representing the regular expression match. */ export function regexMatch( - stringExpression: Expr, - pattern: Expr - ): BooleanExpr; + stringExpression: Expression, + pattern: Expression + ): BooleanExpression; /** * @beta * Creates an expression that checks if a string field contains a specified substring. * * ```typescript * // Check if the 'description' field contains "example". - * strContains("description", "example"); + * stringContains("description", "example"); * ``` * * @param fieldName The name of the field containing the string. * @param substring The substring to search for. - * @return A new {@code Expr} representing the 'contains' comparison. + * @return A new {@code Expression} representing the 'contains' comparison. */ - export function strContains( + export function stringContains( fieldName: string, substring: string - ): BooleanExpr; + ): BooleanExpression; /** * @beta * Creates an expression that checks if a string field contains a substring specified by an expression. * * ```typescript * // Check if the 'description' field contains the value of the 'keyword' field. - * strContains("description", field("keyword")); + * stringContains("description", field("keyword")); * ``` * * @param fieldName The name of the field containing the string. * @param substring The expression representing the substring to search for. - * @return A new {@code Expr} representing the 'contains' comparison. + * @return A new {@code Expression} representing the 'contains' comparison. */ - export function strContains( + export function stringContains( fieldName: string, - substring: Expr - ): BooleanExpr; + substring: Expression + ): BooleanExpression; /** * @beta * Creates an expression that checks if a string expression contains a specified substring. * * ```typescript * // Check if the 'description' field contains "example". - * strContains(field("description"), "example"); + * stringContains(field("description"), "example"); * ``` * * @param stringExpression The expression representing the string to perform the comparison on. * @param substring The substring to search for. - * @return A new {@code Expr} representing the 'contains' comparison. + * @return A new {@code Expression} representing the 'contains' comparison. */ - export function strContains( - stringExpression: Expr, + export function stringContains( + stringExpression: Expression, substring: string - ): BooleanExpr; + ): BooleanExpression; /** * @beta * Creates an expression that checks if a string expression contains a substring specified by another expression. * * ```typescript * // Check if the 'description' field contains the value of the 'keyword' field. - * strContains(field("description"), field("keyword")); + * stringContains(field("description"), field("keyword")); * ``` * * @param stringExpression The expression representing the string to perform the comparison on. * @param substring The expression representing the substring to search for. - * @return A new {@code Expr} representing the 'contains' comparison. + * @return A new {@code Expression} representing the 'contains' comparison. */ - export function strContains( - stringExpression: Expr, - substring: Expr - ): BooleanExpr; + export function stringContains( + stringExpression: Expression, + substring: Expression + ): BooleanExpression; /** * @beta * Creates an expression that checks if a field's value starts with a given prefix. @@ -7132,9 +7367,12 @@ declare namespace FirebaseFirestore { * * @param fieldName The field name to check. * @param prefix The prefix to check for. - * @return A new {@code Expr} representing the 'starts with' comparison. + * @return A new {@code Expression} representing the 'starts with' comparison. */ - export function startsWith(fieldName: string, prefix: string): BooleanExpr; + export function startsWith( + fieldName: string, + prefix: string + ): BooleanExpression; /** * @beta * Creates an expression that checks if a field's value starts with a given prefix. @@ -7146,9 +7384,12 @@ declare namespace FirebaseFirestore { * * @param fieldName The field name to check. * @param prefix The expression representing the prefix. - * @return A new {@code Expr} representing the 'starts with' comparison. + * @return A new {@code Expression} representing the 'starts with' comparison. */ - export function startsWith(fieldName: string, prefix: Expr): BooleanExpr; + export function startsWith( + fieldName: string, + prefix: Expression + ): BooleanExpression; /** * @beta @@ -7161,12 +7402,12 @@ declare namespace FirebaseFirestore { * * @param stringExpression An expression that evaluates to a string, which will be checked for the prefix. * @param prefix The string prefix to check for. - * @return A new {@code BooleanExpr} representing the 'starts with' comparison. + * @return A new {@code BooleanExpression} representing the 'starts with' comparison. */ export function startsWith( - stringExpression: Expr, + stringExpression: Expression, prefix: string - ): BooleanExpr; + ): BooleanExpression; /** * @beta @@ -7179,12 +7420,12 @@ declare namespace FirebaseFirestore { * * @param stringExpression The string expression to check. * @param prefix The prefix expression to check for. - * @return A new {@code BooleanExpr} representing the 'starts with' comparison. + * @return A new {@code BooleanExpression} representing the 'starts with' comparison. */ export function startsWith( - stringExpression: Expr, - prefix: Expr - ): BooleanExpr; + stringExpression: Expression, + prefix: Expression + ): BooleanExpression; /** * @beta @@ -7197,9 +7438,12 @@ declare namespace FirebaseFirestore { * * @param fieldName The field name to check. * @param suffix The suffix to check for. - * @return A new {@link BooleanExpr} representing the 'ends with' comparison. + * @return A new {@link BooleanExpression} representing the 'ends with' comparison. */ - export function endsWith(fieldName: string, suffix: string): BooleanExpr; + export function endsWith( + fieldName: string, + suffix: string + ): BooleanExpression; /** * @beta * Creates an expression that checks if a field's value ends with a given postfix. @@ -7211,9 +7455,12 @@ declare namespace FirebaseFirestore { * * @param fieldName The field name to check. * @param suffix The expression representing the postfix. - * @return A new {@code Expr} representing the 'ends with' comparison. + * @return A new {@code Expression} representing the 'ends with' comparison. */ - export function endsWith(fieldName: string, suffix: Expr): BooleanExpr; + export function endsWith( + fieldName: string, + suffix: Expression + ): BooleanExpression; /** * @beta * Creates an expression that checks if a string expression ends with a given postfix. @@ -7225,12 +7472,12 @@ declare namespace FirebaseFirestore { * * @param stringExpression The expression to check. * @param suffix The postfix to check for. - * @return A new {@code Expr} representing the 'ends with' comparison. + * @return A new {@code Expression} representing the 'ends with' comparison. */ export function endsWith( - stringExpression: Expr, + stringExpression: Expression, suffix: string - ): BooleanExpr; + ): BooleanExpression; /** * @beta * Creates an expression that checks if a string expression ends with a given postfix. @@ -7242,9 +7489,12 @@ declare namespace FirebaseFirestore { * * @param stringExpression The expression to check. * @param suffix The postfix to check for. - * @return A new {@code Expr} representing the 'ends with' comparison. + * @return A new {@code Expression} representing the 'ends with' comparison. */ - export function endsWith(stringExpression: Expr, suffix: Expr): BooleanExpr; + export function endsWith( + stringExpression: Expression, + suffix: Expression + ): BooleanExpression; /** * @beta @@ -7256,9 +7506,9 @@ declare namespace FirebaseFirestore { * ``` * * @param fieldName The name of the field containing the string. - * @return A new {@code Expr} representing the lowercase string. + * @return A new {@code Expression} representing the lowercase string. */ - export function toLower(fieldName: string): FunctionExpr; + export function toLower(fieldName: string): FunctionExpression; /** * @beta @@ -7270,9 +7520,9 @@ declare namespace FirebaseFirestore { * ``` * * @param stringExpression The expression representing the string to convert to lowercase. - * @return A new {@code Expr} representing the lowercase string. + * @return A new {@code Expression} representing the lowercase string. */ - export function toLower(stringExpression: Expr): FunctionExpr; + export function toLower(stringExpression: Expression): FunctionExpression; /** * @beta * Creates an expression that converts a string field to uppercase. @@ -7283,9 +7533,9 @@ declare namespace FirebaseFirestore { * ``` * * @param fieldName The name of the field containing the string. - * @return A new {@code Expr} representing the uppercase string. + * @return A new {@code Expression} representing the uppercase string. */ - export function toUpper(fieldName: string): FunctionExpr; + export function toUpper(fieldName: string): FunctionExpression; /** * @beta @@ -7297,9 +7547,9 @@ declare namespace FirebaseFirestore { * ``` * * @param stringExpression The expression representing the string to convert to uppercase. - * @return A new {@code FunctionExpr} representing the uppercase string. + * @return A new {@code FunctionExpression} representing the uppercase string. */ - export function toUpper(stringExpression: Expr): FunctionExpr; + export function toUpper(stringExpression: Expression): FunctionExpression; /** * @beta * Creates an expression that removes leading and trailing whitespace from a string field. @@ -7310,9 +7560,9 @@ declare namespace FirebaseFirestore { * ``` * * @param fieldName The name of the field containing the string. - * @return A new {@code Expr} representing the trimmed string. + * @return A new {@code Expression} representing the trimmed string. */ - export function trim(fieldName: string): FunctionExpr; + export function trim(fieldName: string): FunctionExpression; /** * @beta * Creates an expression that removes leading and trailing whitespace from a string expression. @@ -7323,9 +7573,9 @@ declare namespace FirebaseFirestore { * ``` * * @param stringExpression The expression representing the string to trim. - * @return A new {@code Expr} representing the trimmed string. + * @return A new {@code Expression} representing the trimmed string. */ - export function trim(stringExpression: Expr): FunctionExpr; + export function trim(stringExpression: Expression): FunctionExpression; /** * @beta @@ -7333,38 +7583,38 @@ declare namespace FirebaseFirestore { * * ```typescript * // Combine the 'firstName' field, a space, and the 'lastName' field into a single string. - * strConcat("firstName", " ", field("lastName")); + * stringConcat("firstName", " ", field("lastName")); * ``` * * @param fieldName The name of the field to use as the initial string value for concatenation. * @param secondString An expression or string literal to concatenate. * @param otherStrings Optional additional expressions or literals (typically strings) to concatenate. - * @return A new {@code FunctionExpr} representing the concatenated string. + * @return A new {@code FunctionExpression} representing the concatenated string. */ - export function strConcat( + export function stringConcat( fieldName: string, - secondString: Expr | string, - ...otherStrings: Array - ): FunctionExpr; + secondString: Expression | string, + ...otherStrings: Array + ): FunctionExpression; /** * @beta * Creates an expression that concatenates string expressions together. * * ```typescript * // Combine the 'firstName', " ", and 'lastName' fields into a single string - * strConcat(field("firstName"), " ", field("lastName")); + * stringConcat(field("firstName"), " ", field("lastName")); * ``` * * @param firstString The initial string expression to concatenate to. * @param secondString An expression or string literal to concatenate. * @param otherStrings Optional additional expressions or literals (typically strings) to concatenate. - * @return A new {@code Expr} representing the concatenated string. + * @return A new {@code Expression} representing the concatenated string. */ - export function strConcat( - firstString: Expr, - secondString: Expr | string, - ...otherStrings: Array - ): FunctionExpr; + export function stringConcat( + firstString: Expression, + secondString: Expression | string, + ...otherStrings: Array + ): FunctionExpression; /** * @beta * Accesses a value from a map (object) field using the provided key. @@ -7376,9 +7626,12 @@ declare namespace FirebaseFirestore { * * @param fieldName The field name of the map field. * @param subField The key to access in the map. - * @return A new {@code Expr} representing the value associated with the given key in the map. + * @return A new {@code Expression} representing the value associated with the given key in the map. */ - export function mapGet(fieldName: string, subField: string): FunctionExpr; + export function mapGet( + fieldName: string, + subField: string + ): FunctionExpression; /** * @beta * Accesses a value from a map (object) expression using the provided key. @@ -7390,9 +7643,12 @@ declare namespace FirebaseFirestore { * * @param mapExpression The expression representing the map. * @param subField The key to access in the map. - * @return A new {@code Expr} representing the value associated with the given key in the map. + * @return A new {@code Expression} representing the value associated with the given key in the map. */ - export function mapGet(mapExpression: Expr, subField: string): FunctionExpr; + export function mapGet( + mapExpression: Expression, + subField: string + ): FunctionExpression; /** * @beta * Creates an aggregation that counts the total number of stage inputs. @@ -7412,13 +7668,13 @@ declare namespace FirebaseFirestore { * * ```typescript * // Count the number of items where the price is greater than 10 - * count(field("price").gt(10)).as("expensiveItemCount"); + * count(field("price").greaterThan(10)).as("expensiveItemCount"); * ``` * * @param expression The expression to count. * @return A new {@code AggregateFunction} representing the 'count' aggregation. */ - export function count(expression: Expr): AggregateFunction; + export function count(expression: Expression): AggregateFunction; /** * @beta * Creates an aggregation that counts the number of stage inputs where the input field exists. @@ -7445,7 +7701,7 @@ declare namespace FirebaseFirestore { * @param expression The expression to sum up. * @return A new {@code AggregateFunction} representing the 'sum' aggregation. */ - export function sum(expression: Expr): AggregateFunction; + export function sum(expression: Expression): AggregateFunction; /** * @beta * Creates an aggregation that calculates the sum of a field's values across multiple stage @@ -7467,13 +7723,13 @@ declare namespace FirebaseFirestore { * * ```typescript * // Calculate the average age of users - * avg(field("age")).as("averageAge"); + * average(field("age")).as("averageAge"); * ``` * * @param expression The expression representing the values to average. - * @return A new {@code AggregateFunction} representing the 'avg' aggregation. + * @return A new {@code AggregateFunction} representing the 'average' aggregation. */ - export function avg(expression: Expr): AggregateFunction; + export function average(expression: Expression): AggregateFunction; /** * @beta * Creates an aggregation that calculates the average (mean) of a field's values across multiple @@ -7481,13 +7737,13 @@ declare namespace FirebaseFirestore { * * ```typescript * // Calculate the average age of users - * avg("age").as("averageAge"); + * average("age").as("averageAge"); * ``` * * @param fieldName The name of the field containing numeric values to average. - * @return A new {@code AggregateFunction} representing the 'avg' aggregation. + * @return A new {@code AggregateFunction} representing the 'average' aggregation. */ - export function avg(fieldName: string): AggregateFunction; + export function average(fieldName: string): AggregateFunction; /** * @beta * Creates an aggregation that finds the minimum value of an expression across multiple stage @@ -7501,7 +7757,7 @@ declare namespace FirebaseFirestore { * @param expression The expression to find the minimum value of. * @return A new {@code AggregateFunction} representing the 'min' aggregation. */ - export function minimum(expression: Expr): AggregateFunction; + export function minimum(expression: Expression): AggregateFunction; /** * @beta * Creates an aggregation that finds the minimum value of a field across multiple stage inputs. @@ -7528,7 +7784,7 @@ declare namespace FirebaseFirestore { * @param expression The expression to find the maximum value of. * @return A new {@code AggregateFunction} representing the 'max' aggregation. */ - export function maximum(expression: Expr): AggregateFunction; + export function maximum(expression: Expression): AggregateFunction; /** * @beta * Creates an aggregation that finds the maximum value of a field across multiple stage inputs. @@ -7553,12 +7809,12 @@ declare namespace FirebaseFirestore { * * @param fieldName The name of the field containing the first vector. * @param vector The other vector (as an array of doubles) or {@link VectorValue} to compare against. - * @return A new {@code Expr} representing the Cosine distance between the two vectors. + * @return A new {@code Expression} representing the Cosine distance between the two vectors. */ export function cosineDistance( fieldName: string, vector: number[] | VectorValue - ): FunctionExpr; + ): FunctionExpression; /** * @beta * Calculates the Cosine distance between a field's vector value and a vector expression. @@ -7569,13 +7825,13 @@ declare namespace FirebaseFirestore { * ``` * * @param fieldName The name of the field containing the first vector. - * @param vectorExpression The other vector (represented as an Expr) to compare against. - * @return A new {@code Expr} representing the cosine distance between the two vectors. + * @param vectorExpression The other vector (represented as an Expression) to compare against. + * @return A new {@code Expression} representing the cosine distance between the two vectors. */ export function cosineDistance( fieldName: string, - vectorExpression: Expr - ): FunctionExpr; + vectorExpression: Expression + ): FunctionExpression; /** * @beta @@ -7593,14 +7849,14 @@ declare namespace FirebaseFirestore { * cosineDistance(field("vector1"), field("vector2")); * ``` * - * @param vectorExpression The first vector, represented as an {@link Expr} (e.g., a field path). - * @param vector The second vector, which can be either a numeric array literal (`number[]`) or another {@link Expr}. - * @return A new {@link FunctionExpr} representing the cosine distance. + * @param vectorExpression The first vector, represented as an {@link Expression} (e.g., a field path). + * @param vector The second vector, which can be either a numeric array literal (`number[]`) or another {@link Expression}. + * @return A new {@link FunctionExpression} representing the cosine distance. */ export function cosineDistance( - vectorExpression: Expr, - vector: number[] | Expr - ): FunctionExpr; + vectorExpression: Expression, + vector: number[] | Expression + ): FunctionExpression; /** * @beta * Calculates the Cosine distance between two vector expressions. @@ -7610,14 +7866,14 @@ declare namespace FirebaseFirestore { * cosineDistance(field("userVector"), field("itemVector")); * ``` * - * @param vectorExpression The first vector (represented as an Expr) to compare against. - * @param otherVectorExpression The other vector (represented as an Expr) to compare against. - * @return A new {@code Expr} representing the cosine distance between the two vectors. + * @param vectorExpression The first vector (represented as an Expression) to compare against. + * @param otherVectorExpression The other vector (represented as an Expression) to compare against. + * @return A new {@code Expression} representing the cosine distance between the two vectors. */ export function cosineDistance( - vectorExpression: Expr, - otherVectorExpression: Expr - ): FunctionExpr; + vectorExpression: Expression, + otherVectorExpression: Expression + ): FunctionExpression; /** * @beta * Calculates the dot product between a field's vector value and a double array. @@ -7629,12 +7885,12 @@ declare namespace FirebaseFirestore { * * @param fieldName The name of the field containing the first vector. * @param vector The other vector (as an array of doubles or VectorValue) to calculate with. - * @return A new {@code Expr} representing the dot product between the two vectors. + * @return A new {@code Expression} representing the dot product between the two vectors. */ export function dotProduct( fieldName: string, vector: number[] | VectorValue - ): FunctionExpr; + ): FunctionExpression; /** * @beta @@ -7646,13 +7902,13 @@ declare namespace FirebaseFirestore { * ``` * * @param fieldName The name of the field containing the first vector. - * @param vectorExpression The other vector (represented as an Expr) to calculate with. - * @return A new {@code Expr} representing the dot product between the two vectors. + * @param vectorExpression The other vector (represented as an Expression) to calculate with. + * @return A new {@code Expression} representing the dot product between the two vectors. */ export function dotProduct( fieldName: string, - vectorExpression: Expr - ): FunctionExpr; + vectorExpression: Expression + ): FunctionExpression; /** * @beta @@ -7663,14 +7919,14 @@ declare namespace FirebaseFirestore { * dotProduct(field("features"), [0.5, 0.8, 0.2]); * ``` * - * @param vectorExpression The first vector (represented as an Expr) to calculate with. + * @param vectorExpression The first vector (represented as an Expression) to calculate with. * @param vector The other vector (as an array of numbers or VectorValue) to calculate with. - * @return A new {@code Expr} representing the dot product between the two vectors. + * @return A new {@code Expression} representing the dot product between the two vectors. */ export function dotProduct( - vectorExpression: Expr, + vectorExpression: Expression, vector: number[] | VectorValue - ): FunctionExpr; + ): FunctionExpression; /** * @beta * Calculates the dot product between two vector expressions. @@ -7680,14 +7936,14 @@ declare namespace FirebaseFirestore { * dotProduct(field("docVector1"), field("docVector2")); * ``` * - * @param vectorExpression The first vector (represented as an Expr) to calculate with. - * @param otherVectorExpression The other vector (represented as an Expr) to calculate with. - * @return A new {@code Expr} representing the dot product between the two vectors. + * @param vectorExpression The first vector (represented as an Expression) to calculate with. + * @param otherVectorExpression The other vector (represented as an Expression) to calculate with. + * @return A new {@code Expression} representing the dot product between the two vectors. */ export function dotProduct( - vectorExpression: Expr, - otherVectorExpression: Expr - ): FunctionExpr; + vectorExpression: Expression, + otherVectorExpression: Expression + ): FunctionExpression; /** * @beta @@ -7701,12 +7957,12 @@ declare namespace FirebaseFirestore { * * @param fieldName The name of the field containing the first vector. * @param vector The other vector (as an array of doubles or VectorValue) to compare against. - * @return A new {@code Expr} representing the Euclidean distance between the two vectors. + * @return A new {@code Expression} representing the Euclidean distance between the two vectors. */ export function euclideanDistance( fieldName: string, vector: number[] | VectorValue - ): FunctionExpr; + ): FunctionExpression; /** * @beta * Calculates the Euclidean distance between a field's vector value and a vector expression. @@ -7717,13 +7973,13 @@ declare namespace FirebaseFirestore { * ``` * * @param fieldName The name of the field containing the first vector. - * @param vectorExpression The other vector (represented as an Expr) to compare against. - * @return A new {@code Expr} representing the Euclidean distance between the two vectors. + * @param vectorExpression The other vector (represented as an Expression) to compare against. + * @return A new {@code Expression} representing the Euclidean distance between the two vectors. */ export function euclideanDistance( fieldName: string, - vectorExpression: Expr - ): FunctionExpr; + vectorExpression: Expression + ): FunctionExpression; /** * @beta * Calculates the Euclidean distance between a vector expression and a double array. @@ -7734,14 +7990,14 @@ declare namespace FirebaseFirestore { * euclideanDistance(field("location"), [37.7749, -122.4194]); * ``` * - * @param vectorExpression The first vector (represented as an Expr) to compare against. + * @param vectorExpression The first vector (represented as an Expression) to compare against. * @param vector The other vector (as an array of doubles or VectorValue) to compare against. - * @return A new {@code Expr} representing the Euclidean distance between the two vectors. + * @return A new {@code Expression} representing the Euclidean distance between the two vectors. */ export function euclideanDistance( - vectorExpression: Expr, + vectorExpression: Expression, vector: number[] | VectorValue - ): FunctionExpr; + ): FunctionExpression; /** * @beta * Calculates the Euclidean distance between two vector expressions. @@ -7751,14 +8007,14 @@ declare namespace FirebaseFirestore { * euclideanDistance(field("pointA"), field("pointB")); * ``` * - * @param vectorExpression The first vector (represented as an Expr) to compare against. - * @param otherVectorExpression The other vector (represented as an Expr) to compare against. - * @return A new {@code Expr} representing the Euclidean distance between the two vectors. + * @param vectorExpression The first vector (represented as an Expression) to compare against. + * @param otherVectorExpression The other vector (represented as an Expression) to compare against. + * @return A new {@code Expression} representing the Euclidean distance between the two vectors. */ export function euclideanDistance( - vectorExpression: Expr, - otherVectorExpression: Expr - ): FunctionExpr; + vectorExpression: Expression, + otherVectorExpression: Expression + ): FunctionExpression; /** * @beta * Creates an expression that calculates the length of a Firestore Vector. @@ -7769,9 +8025,11 @@ declare namespace FirebaseFirestore { * ``` * * @param vectorExpression The expression representing the Firestore Vector. - * @return A new {@code Expr} representing the length of the array. + * @return A new {@code Expression} representing the length of the array. */ - export function vectorLength(vectorExpression: Expr): FunctionExpr; + export function vectorLength( + vectorExpression: Expression + ): FunctionExpression; /** * @beta @@ -7783,9 +8041,9 @@ declare namespace FirebaseFirestore { * ``` * * @param fieldName The name of the field representing the Firestore Vector. - * @return A new {@code FunctionExpr} representing the length (dimension) of the vector. + * @return A new {@code FunctionExpression} representing the length (dimension) of the vector. */ - export function vectorLength(fieldName: string): FunctionExpr; + export function vectorLength(fieldName: string): FunctionExpression; /** * @beta * Creates an expression that interprets an expression as the number of microseconds since the Unix epoch (1970-01-01 00:00:00 UTC) @@ -7797,9 +8055,9 @@ declare namespace FirebaseFirestore { * ``` * * @param expr The expression representing the number of microseconds since epoch. - * @return A new {@code Expr} representing the timestamp. + * @return A new {@code Expression} representing the timestamp. */ - export function unixMicrosToTimestamp(expr: Expr): FunctionExpr; + export function unixMicrosToTimestamp(expr: Expression): FunctionExpression; /** * @beta * Creates an expression that interprets a field's value as the number of microseconds since the Unix epoch (1970-01-01 00:00:00 UTC) @@ -7811,9 +8069,11 @@ declare namespace FirebaseFirestore { * ``` * * @param fieldName The name of the field representing the number of microseconds since epoch. - * @return A new {@code Expr} representing the timestamp. + * @return A new {@code Expression} representing the timestamp. */ - export function unixMicrosToTimestamp(fieldName: string): FunctionExpr; + export function unixMicrosToTimestamp( + fieldName: string + ): FunctionExpression; /** * @beta * Creates an expression that converts a timestamp expression to the number of microseconds since the Unix epoch (1970-01-01 00:00:00 UTC). @@ -7824,9 +8084,9 @@ declare namespace FirebaseFirestore { * ``` * * @param expr The expression representing the timestamp. - * @return A new {@code Expr} representing the number of microseconds since epoch. + * @return A new {@code Expression} representing the number of microseconds since epoch. */ - export function timestampToUnixMicros(expr: Expr): FunctionExpr; + export function timestampToUnixMicros(expr: Expression): FunctionExpression; /** * @beta * Creates an expression that converts a timestamp field to the number of microseconds since the Unix epoch (1970-01-01 00:00:00 UTC). @@ -7837,9 +8097,11 @@ declare namespace FirebaseFirestore { * ``` * * @param fieldName The name of the field representing the timestamp. - * @return A new {@code Expr} representing the number of microseconds since epoch. + * @return A new {@code Expression} representing the number of microseconds since epoch. */ - export function timestampToUnixMicros(fieldName: string): FunctionExpr; + export function timestampToUnixMicros( + fieldName: string + ): FunctionExpression; /** * @beta * Creates an expression that interprets an expression as the number of milliseconds since the Unix epoch (1970-01-01 00:00:00 UTC) @@ -7851,9 +8113,9 @@ declare namespace FirebaseFirestore { * ``` * * @param expr The expression representing the number of milliseconds since epoch. - * @return A new {@code Expr} representing the timestamp. + * @return A new {@code Expression} representing the timestamp. */ - export function unixMillisToTimestamp(expr: Expr): FunctionExpr; + export function unixMillisToTimestamp(expr: Expression): FunctionExpression; /** * @beta * Creates an expression that interprets a field's value as the number of milliseconds since the Unix epoch (1970-01-01 00:00:00 UTC) @@ -7865,9 +8127,11 @@ declare namespace FirebaseFirestore { * ``` * * @param fieldName The name of the field representing the number of milliseconds since epoch. - * @return A new {@code Expr} representing the timestamp. + * @return A new {@code Expression} representing the timestamp. */ - export function unixMillisToTimestamp(fieldName: string): FunctionExpr; + export function unixMillisToTimestamp( + fieldName: string + ): FunctionExpression; /** * @beta * Creates an expression that converts a timestamp expression to the number of milliseconds since the Unix epoch (1970-01-01 00:00:00 UTC). @@ -7878,9 +8142,9 @@ declare namespace FirebaseFirestore { * ``` * * @param expr The expression representing the timestamp. - * @return A new {@code Expr} representing the number of milliseconds since epoch. + * @return A new {@code Expression} representing the number of milliseconds since epoch. */ - export function timestampToUnixMillis(expr: Expr): FunctionExpr; + export function timestampToUnixMillis(expr: Expression): FunctionExpression; /** * @beta * Creates an expression that converts a timestamp field to the number of milliseconds since the Unix epoch (1970-01-01 00:00:00 UTC). @@ -7891,9 +8155,11 @@ declare namespace FirebaseFirestore { * ``` * * @param fieldName The name of the field representing the timestamp. - * @return A new {@code Expr} representing the number of milliseconds since epoch. + * @return A new {@code Expression} representing the number of milliseconds since epoch. */ - export function timestampToUnixMillis(fieldName: string): FunctionExpr; + export function timestampToUnixMillis( + fieldName: string + ): FunctionExpression; /** * @beta * Creates an expression that interprets an expression as the number of seconds since the Unix epoch (1970-01-01 00:00:00 UTC) @@ -7905,9 +8171,11 @@ declare namespace FirebaseFirestore { * ``` * * @param expr The expression representing the number of seconds since epoch. - * @return A new {@code Expr} representing the timestamp. + * @return A new {@code Expression} representing the timestamp. */ - export function unixSecondsToTimestamp(expr: Expr): FunctionExpr; + export function unixSecondsToTimestamp( + expr: Expression + ): FunctionExpression; /** * @beta * Creates an expression that interprets a field's value as the number of seconds since the Unix epoch (1970-01-01 00:00:00 UTC) @@ -7919,9 +8187,11 @@ declare namespace FirebaseFirestore { * ``` * * @param fieldName The name of the field representing the number of seconds since epoch. - * @return A new {@code Expr} representing the timestamp. + * @return A new {@code Expression} representing the timestamp. */ - export function unixSecondsToTimestamp(fieldName: string): FunctionExpr; + export function unixSecondsToTimestamp( + fieldName: string + ): FunctionExpression; /** * @beta * Creates an expression that converts a timestamp expression to the number of seconds since the Unix epoch (1970-01-01 00:00:00 UTC). @@ -7932,9 +8202,11 @@ declare namespace FirebaseFirestore { * ``` * * @param expr The expression representing the timestamp. - * @return A new {@code Expr} representing the number of seconds since epoch. + * @return A new {@code Expression} representing the number of seconds since epoch. */ - export function timestampToUnixSeconds(expr: Expr): FunctionExpr; + export function timestampToUnixSeconds( + expr: Expression + ): FunctionExpression; /** * @beta * Creates an expression that converts a timestamp field to the number of seconds since the Unix epoch (1970-01-01 00:00:00 UTC). @@ -7945,9 +8217,11 @@ declare namespace FirebaseFirestore { * ``` * * @param fieldName The name of the field representing the timestamp. - * @return A new {@code Expr} representing the number of seconds since epoch. + * @return A new {@code Expression} representing the number of seconds since epoch. */ - export function timestampToUnixSeconds(fieldName: string): FunctionExpr; + export function timestampToUnixSeconds( + fieldName: string + ): FunctionExpression; /** * @beta * Creates an expression that adds a specified amount of time to a timestamp. @@ -7960,13 +8234,13 @@ declare namespace FirebaseFirestore { * @param timestamp The expression representing the timestamp. * @param unit The expression evaluates to unit of time, must be one of 'microsecond', 'millisecond', 'second', 'minute', 'hour', 'day'. * @param amount The expression evaluates to amount of the unit. - * @return A new {@code Expr} representing the resulting timestamp. + * @return A new {@code Expression} representing the resulting timestamp. */ export function timestampAdd( - timestamp: Expr, - unit: Expr, - amount: Expr - ): FunctionExpr; + timestamp: Expression, + unit: Expression, + amount: Expression + ): FunctionExpression; /** * @beta @@ -7980,10 +8254,10 @@ declare namespace FirebaseFirestore { * @param timestamp The expression representing the timestamp. * @param unit The unit of time to add: 'microsecond', 'millisecond', 'second', 'minute', 'hour', or 'day'. * @param amount The amount of time to add. - * @return A new {@code Expr} representing the resulting timestamp. + * @return A new {@code Expression} representing the resulting timestamp. */ export function timestampAdd( - timestamp: Expr, + timestamp: Expression, unit: | 'microsecond' | 'millisecond' @@ -7992,7 +8266,7 @@ declare namespace FirebaseFirestore { | 'hour' | 'day', amount: number - ): FunctionExpr; + ): FunctionExpression; /** * @beta * Creates an expression that adds a specified amount of time to a timestamp represented by a field. @@ -8005,7 +8279,7 @@ declare namespace FirebaseFirestore { * @param fieldName The name of the field representing the timestamp. * @param unit The unit of time to add (e.g., "day", "hour"). * @param amount The amount of time to add. - * @return A new {@code Expr} representing the resulting timestamp. + * @return A new {@code Expression} representing the resulting timestamp. */ export function timestampAdd( fieldName: string, @@ -8017,42 +8291,42 @@ declare namespace FirebaseFirestore { | 'hour' | 'day', amount: number - ): FunctionExpr; + ): FunctionExpression; /** * @beta * Creates an expression that subtracts a specified amount of time from a timestamp. * * ```typescript * // Subtract some duration determined by field 'unit' and 'amount' from the 'timestamp' field. - * timestampSub(field("timestamp"), field("unit"), field("amount")); + * timestampSubtract(field("timestamp"), field("unit"), field("amount")); * ``` * * @param timestamp The expression representing the timestamp. * @param unit The expression evaluates to unit of time, must be one of 'microsecond', 'millisecond', 'second', 'minute', 'hour', 'day'. * @param amount The expression evaluates to amount of the unit. - * @return A new {@code Expr} representing the resulting timestamp. + * @return A new {@code Expression} representing the resulting timestamp. */ - export function timestampSub( - timestamp: Expr, - unit: Expr, - amount: Expr - ): FunctionExpr; + export function timestampSubtract( + timestamp: Expression, + unit: Expression, + amount: Expression + ): FunctionExpression; /** * @beta * Creates an expression that subtracts a specified amount of time from a timestamp. * * ```typescript * // Subtract 1 day from the 'timestamp' field. - * timestampSub(field("timestamp"), "day", 1); + * timestampSubtract(field("timestamp"), "day", 1); * ``` * * @param timestamp The expression representing the timestamp. * @param unit The unit of time to subtract (e.g., "day", "hour"). * @param amount The amount of time to subtract. - * @return A new {@code Expr} representing the resulting timestamp. + * @return A new {@code Expression} representing the resulting timestamp. */ - export function timestampSub( - timestamp: Expr, + export function timestampSubtract( + timestamp: Expression, unit: | 'microsecond' | 'millisecond' @@ -8061,22 +8335,22 @@ declare namespace FirebaseFirestore { | 'hour' | 'day', amount: number - ): FunctionExpr; + ): FunctionExpression; /** * @beta * Creates an expression that subtracts a specified amount of time from a timestamp represented by a field. * * ```typescript * // Subtract 1 day from the 'timestamp' field. - * timestampSub("timestamp", "day", 1); + * timestampSubtract("timestamp", "day", 1); * ``` * * @param fieldName The name of the field representing the timestamp. * @param unit The unit of time to subtract (e.g., "day", "hour"). * @param amount The amount of time to subtract. - * @return A new {@code Expr} representing the resulting timestamp. + * @return A new {@code Expression} representing the resulting timestamp. */ - export function timestampSub( + export function timestampSubtract( fieldName: string, unit: | 'microsecond' @@ -8086,7 +8360,22 @@ declare namespace FirebaseFirestore { | 'hour' | 'day', amount: number - ): FunctionExpr; + ): FunctionExpression; + + /** + * @beta + * + * Creates an expression that evaluates to the current server timestamp. + * + * ```typescript + * // Get the current server timestamp + * currentTimestamp() + * ``` + * + * @return A new Expression representing the current server timestamp. + */ + export function currentTimestamp(): FunctionExpression; + /** * @beta * Creates an expression that performs a logical 'AND' operation on multiple filter conditions. @@ -8094,19 +8383,19 @@ declare namespace FirebaseFirestore { * ```typescript * // Check if the 'age' field is greater than 18 AND the 'city' field is "London" AND * // the 'status' field is "active" - * const condition = and(gt("age", 18), eq("city", "London"), eq("status", "active")); + * const condition = and(greaterThan("age", 18), equal("city", "London"), equal("status", "active")); * ``` * * @param first The first filter condition. * @param second The second filter condition. * @param more Additional filter conditions to 'AND' together. - * @return A new {@code Expr} representing the logical 'AND' operation. + * @return A new {@code Expression} representing the logical 'AND' operation. */ export function and( - first: BooleanExpr, - second: BooleanExpr, - ...more: BooleanExpr[] - ): BooleanExpr; + first: BooleanExpression, + second: BooleanExpression, + ...more: BooleanExpression[] + ): BooleanExpression; /** * @beta * Creates an expression that performs a logical 'OR' operation on multiple filter conditions. @@ -8114,19 +8403,19 @@ declare namespace FirebaseFirestore { * ```typescript * // Check if the 'age' field is greater than 18 OR the 'city' field is "London" OR * // the 'status' field is "active" - * const condition = or(gt("age", 18), eq("city", "London"), eq("status", "active")); + * const condition = or(greaterThan("age", 18), equal("city", "London"), equal("status", "active")); * ``` * * @param first The first filter condition. * @param second The second filter condition. * @param more Additional filter conditions to 'OR' together. - * @return A new {@code Expr} representing the logical 'OR' operation. + * @return A new {@code Expression} representing the logical 'OR' operation. */ export function or( - first: BooleanExpr, - second: BooleanExpr, - ...more: BooleanExpr[] - ): BooleanExpr; + first: BooleanExpression, + second: BooleanExpression, + ...more: BooleanExpression[] + ): BooleanExpression; /** * @beta * Creates an expression that returns the value of the base expression raised to the power of the exponent expression. @@ -8138,9 +8427,12 @@ declare namespace FirebaseFirestore { * * @param base The expression to raise to the power of the exponent. * @param exponent The expression to raise the base to the power of. - * @return A new `Expr` representing the power operation. + * @return A new `Expression` representing the power operation. */ - export function pow(base: Expr, exponent: Expr): FunctionExpr; + export function pow( + base: Expression, + exponent: Expression + ): FunctionExpression; /** * @beta * Creates an expression that returns the value of the base expression raised to the power of the exponent. @@ -8152,9 +8444,9 @@ declare namespace FirebaseFirestore { * * @param base The expression to raise to the power of the exponent. * @param exponent The constant value to raise the base to the power of. - * @return A new `Expr` representing the power operation. + * @return A new `Expression` representing the power operation. */ - export function pow(base: Expr, exponent: number): FunctionExpr; + export function pow(base: Expression, exponent: number): FunctionExpression; /** * @beta * Creates an expression that returns the value of the base field raised to the power of the exponent expression. @@ -8166,9 +8458,9 @@ declare namespace FirebaseFirestore { * * @param base The name of the field to raise to the power of the exponent. * @param exponent The expression to raise the base to the power of. - * @return A new `Expr` representing the power operation. + * @return A new `Expression` representing the power operation. */ - export function pow(base: string, exponent: Expr): FunctionExpr; + export function pow(base: string, exponent: Expression): FunctionExpression; /** * @beta * Creates an expression that returns the value of the base field raised to the power of the exponent. @@ -8180,9 +8472,9 @@ declare namespace FirebaseFirestore { * * @param base The name of the field to raise to the power of the exponent. * @param exponent The constant value to raise the base to the power of. - * @return A new `Expr` representing the power operation. + * @return A new `Expression` representing the power operation. */ - export function pow(base: string, exponent: number): FunctionExpr; + export function pow(base: string, exponent: number): FunctionExpression; /** * @beta * Creates an expression that returns the collection ID from a path. @@ -8193,9 +8485,9 @@ declare namespace FirebaseFirestore { * ``` * * @param expression An expression evaluating to a path, which the collection ID will be extracted from. - * @return A new {@code Expr} representing the collectionId operation. + * @return A new {@code Expression} representing the collectionId operation. */ - export function collectionId(expression: Expr): FunctionExpr; + export function collectionId(expression: Expression): FunctionExpression; /** * @beta * Creates an expression that returns the collection ID from a path. @@ -8206,9 +8498,9 @@ declare namespace FirebaseFirestore { * ``` * * @param fieldName The name of the field to get the collection ID from. - * @return A new {@code Expr} representing the collectionId operation. + * @return A new {@code Expression} representing the collectionId operation. */ - export function collectionId(fieldName: string): FunctionExpr; + export function collectionId(fieldName: string): FunctionExpression; /** * @beta * Creates an expression that calculates the length of a string, array, map, vector, or bytes. @@ -8222,9 +8514,9 @@ declare namespace FirebaseFirestore { * ``` * * @param expression An expression evaluating to a string, array, map, vector, or bytes, which the length will be calculated for. - * @return A new `Expr` representing the length of the string, array, map, vector, or bytes. + * @return A new `Expression` representing the length of the string, array, map, vector, or bytes. */ - export function length(expression: Expr): FunctionExpr; + export function length(expression: Expression): FunctionExpression; /** * @beta * Creates an expression that calculates the length of a string, array, map, vector, or bytes. @@ -8238,118 +8530,260 @@ declare namespace FirebaseFirestore { * ``` * * @param fieldName The name of the field to calculate the length of. - * @return A new `Expr` representing the length of the string, array, map, vector, or bytes. + * @return A new `Expression` representing the length of the string, array, map, vector, or bytes. */ - export function length(fieldName: string): FunctionExpr; + export function length(fieldName: string): FunctionExpression; /** * @beta * Creates an expression that reverses a string. * * ```typescript * // Reverse the value of the 'myString' field. - * strReverse(field("myString")); + * stringReverse(field("myString")); * ``` * * @param stringExpression An expression evaluating to a string value, which will be reversed. - * @return A new {@code Expr} representing the reversed string. + * @return A new {@code Expression} representing the reversed string. */ - export function strReverse(stringExpression: Expr): FunctionExpr; + export function stringReverse( + stringExpression: Expression + ): FunctionExpression; /** * @beta * Creates an expression that reverses a string value in the specified field. * * ```typescript * // Reverse the value of the 'myString' field. - * strReverse("myString"); + * stringReverse("myString"); * ``` * * @param field The name of the field representing the string to reverse. - * @return A new {@code Expr} representing the reversed string. + * @return A new {@code Expression} representing the reversed string. */ - export function strReverse(field: string): FunctionExpr; - // TODO(new-expression): Add new top-level expression function declarations above this line + export function stringReverse(field: string): FunctionExpression; + /** * @beta - * Creates an expression that computes the natural logarithm of a numeric value. + * Creates an expression that concatenates strings, arrays, or blobs. Types cannot be mixed. * * ```typescript - * // Compute the natural logarithm of the 'value' field. - * ln(field("value")); + * // Concatenate the 'firstName' and 'lastName' fields with a space in between. + * concat(field("firstName"), " ", field("lastName")) * ``` * - * @param expression An expression evaluating to a numeric value, which the natural logarithm will be computed for. - * @return A new {@code Expr} representing the natural logarithm of the numeric value. + * @param first The first expressions to concatenate. + * @param second The second literal or expression to concatenate. + * @param others Additional literals or expressions to concatenate. + * @return A new `Expression` representing the concatenation. */ - export function ln(expression: Expr): FunctionExpr; + export function concat( + first: Expression, + second: Expression | unknown, + ...others: Array + ): FunctionExpression; + /** * @beta - * Creates an expression that computes the natural logarithm of a numeric value. + * Creates an expression that computes the absolute value of a numeric value. + * + * @param expr The expression to compute the absolute value of. + * @return A new {@code Expr} representing the absolute value of the numeric value. + */ + export function abs(expr: Expression): FunctionExpression; + + /** + * @beta + * Creates an expression that returns the `elseExpr` argument if `ifExpr` is absent, else return + * the result of the `ifExpr` argument evaluation. * * ```typescript - * // Compute the natural logarithm of the 'value' field. - * ln("value"); + * // Returns the value of the optional field 'optional_field', or returns 'default_value' + * // if the field is absent. + * ifAbsent(field("optional_field"), constant("default_value")) * ``` * - * @param fieldName The name of the field to compute the natural logarithm of. - * @return A new {@code Expr} representing the natural logarithm of the numeric value. + * @param ifExpr The expression to check for absence. + * @param elseExpr The expression that will be evaluated and returned if [ifExpr] is absent. + * @return A new Expression representing the ifAbsent operation. + */ + export function ifAbsent( + ifExpr: Expression, + elseExpr: Expression + ): Expression; + + /** + * @beta + * Creates an expression that returns the `elseValue` argument if `ifExpr` is absent, else + * return the result of the `ifExpr` argument evaluation. + * + * ```typescript + * // Returns the value of the optional field 'optional_field', or returns 'default_value' + * // if the field is absent. + * ifAbsent(field("optional_field"), "default_value") + * ``` + * + * @param ifExpr The expression to check for absence. + * @param elseValue The value that will be returned if `ifExpr` evaluates to an absent value. + * @return A new [Expression] representing the ifAbsent operation. + */ + export function ifAbsent( + ifExpr: Expression, + elseValue: unknown + ): Expression; + + /** + * @beta + * Creates an expression that returns the `elseExpr` argument if `ifFieldName` is absent, else + * return the value of the field. + * + * ```typescript + * // Returns the value of the optional field 'optional_field', or returns the value of + * // 'default_field' if 'optional_field' is absent. + * ifAbsent("optional_field", field("default_field")) + * ``` + * + * @param ifFieldName The field to check for absence. + * @param elseExpr The expression that will be evaluated and returned if `ifFieldName` is + * absent. + * @return A new Expression representing the ifAbsent operation. */ - export function ln(fieldName: string): FunctionExpr; + export function ifAbsent( + ifFieldName: string, + elseExpr: Expression + ): Expression; + /** * @beta - * Creates an expression that computes the logarithm of an expression to a given base. + * Creates an expression that joins the elements of an array into a string. * * ```typescript - * // Compute the logarithm of the 'value' field with base 10. - * log(field("value"), 10); + * // Join the elements of the 'tags' field with a comma and space. + * join("tags", ", ") * ``` * - * @param expression An expression evaluating to a numeric value, which the logarithm will be computed for. - * @param base The base of the logarithm. - * @return A new {@code Expr} representing the logarithm of the numeric value. + * @param arrayFieldName The name of the field containing the array. + * @param delimiter The string to use as a delimiter. + * @return A new Expression representing the join operation. */ - export function log(expression: Expr, base: number): FunctionExpr; + export function join(arrayFieldName: string, delimiter: string): Expression; + /** * @beta - * Creates an expression that computes the logarithm of an expression to a given base. + * Creates an expression that joins the elements of an array into a string. * * ```typescript - * // Compute the logarithm of the 'value' field with the base in the 'base' field. - * log(field("value"), field("base")); + * // Join an array of string using the delimiter from the 'separator' field. + * join(array(['foo', 'bar']), field("separator")) * ``` * - * @param expression An expression evaluating to a numeric value, which the logarithm will be computed for. - * @param base The base of the logarithm. - * @return A new {@code Expr} representing the logarithm of the numeric value. + * @param arrayExpression An expression that evaluates to an array. + * @param delimiterExpression The expression that evaluates to the delimiter string. + * @return A new Expression representing the join operation. */ - export function log(expression: Expr, base: Expr): FunctionExpr; + export function join( + arrayExpression: Expression, + delimiterExpression: Expression + ): Expression; + /** * @beta - * Creates an expression that computes the logarithm of a field to a given base. + * Creates an expression that joins the elements of an array into a string. * * ```typescript - * // Compute the logarithm of the 'value' field with base 10. - * log("value", 10); + * // Join the elements of the 'tags' field with a comma and space. + * join(field("tags"), ", ") * ``` * - * @param fieldName The name of the field to compute the logarithm of. - * @param base The base of the logarithm. - * @return A new {@code Expr} representing the logarithm of the numeric value. + * @param arrayExpression An expression that evaluates to an array. + * @param delimiter The string to use as a delimiter. + * @return A new Expression representing the join operation. */ - export function log(fieldName: string, base: number): FunctionExpr; + export function join( + arrayExpression: Expression, + delimiter: string + ): Expression; + /** * @beta - * Creates an expression that computes the logarithm of a field to a given base. + * Creates an expression that computes the base-10 logarithm of a numeric value. * * ```typescript - * // Compute the logarithm of the 'value' field with the base in the 'base' field. - * log("value", field("base")); + * // Compute the base-10 logarithm of the 'value' field. + * log10("value"); * ``` * - * @param fieldName The name of the field to compute the logarithm of. - * @param base The base of the logarithm. - * @return A new {@code Expr} representing the logarithm of the numeric value. + * @param fieldName The name of the field to compute the base-10 logarithm of. + * @return A new `Expr` representing the base-10 logarithm of the numeric value. */ - export function log(fieldName: string, base: Expr): FunctionExpr; + export function log10(fieldName: string): FunctionExpression; + + /** + * @beta + * Creates an expression that computes the base-10 logarithm of a numeric value. + * + * ```typescript + * // Compute the base-10 logarithm of the 'value' field. + * log10(field("value")); + * ``` + * + * @param expression An expression evaluating to a numeric value, which the base-10 logarithm will be computed for. + * @return A new `Expr` representing the base-10 logarithm of the numeric value. + */ + export function log10(expression: Expression): FunctionExpression; + + /** + * @beta + * Creates an expression that computes the sum of the elements in an array. + * + * ```typescript + * // Compute the sum of the elements in the 'scores' field. + * arraySum("scores"); + * ``` + * + * @param fieldName The name of the field to compute the sum of. + * @return A new `Expr` representing the sum of the elements in the array. + */ + export function arraySum(fieldName: string): FunctionExpression; + + /** + * @beta + * Creates an expression that computes the sum of the elements in an array. + * + * ```typescript + * // Compute the sum of the elements in the 'scores' field. + * arraySum(field("scores")); + * ``` + * + * @param expression An expression evaluating to a numeric array, which the sum will be computed for. + * @return A new `Expr` representing the sum of the elements in the array. + */ + export function arraySum(expression: Expression): FunctionExpression; + /** + * @beta + * Creates an expression that computes the natural logarithm of a numeric value. + * + * ```typescript + * // Compute the natural logarithm of the 'value' field. + * ln(field("value")); + * ``` + * + * @param expression An expression evaluating to a numeric value, which the natural logarithm will be computed for. + * @return A new {@code Expression} representing the natural logarithm of the numeric value. + */ + export function ln(expression: Expression): FunctionExpression; + /** + * @beta + * Creates an expression that computes the natural logarithm of a numeric value. + * + * ```typescript + * // Compute the natural logarithm of the 'value' field. + * ln("value"); + * ``` + * + * @param fieldName The name of the field to compute the natural logarithm of. + * @return A new {@code Expression} representing the natural logarithm of the numeric value. + */ + export function ln(fieldName: string): FunctionExpression; /** * @beta * Creates an expression that rounds a numeric value to the nearest whole number. @@ -8360,9 +8794,9 @@ declare namespace FirebaseFirestore { * ``` * * @param expression An expression evaluating to a numeric value, which will be rounded. - * @return A new `Expr` representing the rounded value. + * @return A new `Expression` representing the rounded value. */ - export function round(expression: Expr): FunctionExpr; + export function round(expression: Expression): FunctionExpression; /** * @beta * Creates an expression that rounds a numeric value to the nearest whole number. @@ -8373,9 +8807,44 @@ declare namespace FirebaseFirestore { * ``` * * @param fieldName The name of the field to round. + * @return A new `Expression` representing the rounded value. + */ + export function round(fieldName: string): FunctionExpression; + /** + * @beta + * Creates an expression that rounds a numeric value to the specified number of decimal places. + * + * ```typescript + * // Round the value of the 'price' field to two decimal places. + * round("price", 2); + * ``` + * + * @param fieldName The name of the field to round. + * @param decimalPlaces A constant or expression specifying the rounding precision in decimal places. * @return A new `Expr` representing the rounded value. */ - export function round(fieldName: string): FunctionExpr; + export function round( + fieldName: string, + decimalPlaces: number | Expression + ): FunctionExpression; + + /** + * @beta + * Creates an expression that rounds a numeric value to the specified number of decimal places. + * + * ```typescript + * // Round the value of the 'price' field to two decimal places. + * round(field("price"), constant(2)); + * ``` + * + * @param expression An expression evaluating to a numeric value, which will be rounded. + * @param decimalPlaces A constant or expression specifying the rounding precision in decimal places. + * @return A new `Expr` representing the rounded value. + */ + export function round( + expression: Expression, + decimalPlaces: number | Expression + ): FunctionExpression; /** * @beta * Creates an expression that computes the square root of a numeric value. @@ -8386,9 +8855,9 @@ declare namespace FirebaseFirestore { * ``` * * @param expression An expression evaluating to a numeric value, which the square root will be computed for. - * @return A new {@code Expr} representing the square root of the numeric value. + * @return A new {@code Expression} representing the square root of the numeric value. */ - export function sqrt(expression: Expr): FunctionExpr; + export function sqrt(expression: Expression): FunctionExpression; /** * @beta * Creates an expression that computes the square root of a numeric value. @@ -8399,9 +8868,10 @@ declare namespace FirebaseFirestore { * ``` * * @param fieldName The name of the field to compute the square root of. - * @return A new {@code Expr} representing the square root of the numeric value. + * @return A new {@code Expression} representing the square root of the numeric value. */ - export function sqrt(fieldName: string): FunctionExpr; + export function sqrt(fieldName: string): FunctionExpression; + // TODO(new-expression): Add new top-level expression function declarations above this line /** * @beta * Creates an {@link Ordering} that sorts documents in ascending order based on an expression. @@ -8415,7 +8885,7 @@ declare namespace FirebaseFirestore { * @param expr The expression to create an ascending ordering for. * @return A new `Ordering` for ascending sorting. */ - export function ascending(expr: Expr): Ordering; + export function ascending(expr: Expression): Ordering; /** * @beta * Creates an {@link Ordering} that sorts documents in ascending order based on a field. @@ -8443,7 +8913,7 @@ declare namespace FirebaseFirestore { * @param expr The expression to create a descending ordering for. * @return A new `Ordering` for descending sorting. */ - export function descending(expr: Expr): Ordering; + export function descending(expr: Expression): Ordering; /** * @beta * Creates an {@link Ordering} that sorts documents in descending order based on a field. @@ -8465,7 +8935,7 @@ declare namespace FirebaseFirestore { * You create `Ordering` instances using the `ascending` and `descending` helper functions. */ export class Ordering { - readonly expr: Expr; + readonly expr: Expression; readonly direction: 'ascending' | 'descending'; } @@ -8601,14 +9071,14 @@ declare namespace FirebaseFirestore { * // Example 2: Filter documents where 'genre' is "Science Fiction" and 'published' is after 1950 * const results2 = await db.pipeline() * .collection("books") - * .where(and(Field.of("genre").eq("Science Fiction"), Field.of("published").gt(1950))) + * .where(and(Field.of("genre").equal("Science Fiction"), Field.of("published").greaterThan(1950))) * .execute(); * * // Example 3: Calculate the average rating of books published after 1980 * const results3 = await db.pipeline() * .collection("books") - * .where(Field.of("published").gt(1980)) - * .aggregate(avg(Field.of("rating")).as("averageRating")) + * .where(Field.of("published").greaterThan(1980)) + * .aggregate(average(Field.of("rating")).as("averageRating")) * .execute(); * ``` */ @@ -8624,8 +9094,8 @@ declare namespace FirebaseFirestore { * The added fields are defined using {@link Selectable}s, which can be: * * - {@link Field}: References an existing document field. - * - {@link Expr}: Either a literal value (see {@link Constant}) or a computed value - * (see {@FunctionExpr}) with an assigned alias using {@link Expr#as}. + * - {@link Expression}: Either a literal value (see {@link Constant}) or a computed value + * (see {@FunctionExpression}) with an assigned alias using {@link Expression#as}. * * Example: * @@ -8653,8 +9123,8 @@ declare namespace FirebaseFirestore { * The added fields are defined using {@link Selectable}s, which can be: * * - {@link Field}: References an existing document field. - * - {@link Expr}: Either a literal value (see {@link Constant}) or a computed value - * (see {@FunctionExpr}) with an assigned alias using {@link Expr#as}. + * - {@link Expression}: Either a literal value (see {@link Constant}) or a computed value + * (see {@FunctionExpression}) with an assigned alias using {@link Expression#as}. * * Example: * @@ -8716,7 +9186,7 @@ declare namespace FirebaseFirestore { * ``` * * @param options - An object containing the configuration for this stage. - * @param options.fields - An array of field names (strings) or {@link Expr} objects + * @param options.fields - An array of field names (strings) or {@link Expression} objects * representing the fields to be removed from the output. * @returns A new {@link Pipeline} object with this stage appended to the stage list. */ @@ -8731,8 +9201,8 @@ declare namespace FirebaseFirestore { *
        *
      • {@code string}: The name of an existing field.
      • *
      • {@link Field}: A reference to an existing field.
      • - *
      • {@link Expr}: An expression (e.g., a {@link FunctionExpr}) that represents the result of an expression., - * The Expr must be aliased using {@link Expr#as}.
      • + *
      • {@link Expression}: An expression (e.g., a {@link FunctionExpression}) that represents the result of an expression., + * The Expression must be aliased using {@link Expression#as}.
      • *
      * *

      Example: @@ -8766,8 +9236,8 @@ declare namespace FirebaseFirestore { *

        *
      • {@code string}: The name of an existing field.
      • *
      • {@link Field}: A reference to an existing field.
      • - *
      • {@link Expr}: An expression (e.g., a {@link FunctionExpr}) that represents the result of an expression., - * The Expr must be aliased using {@link Expr#as}.
      • + *
      • {@link Expression}: An expression (e.g., a {@link FunctionExpression}) that represents the result of an expression., + * The Expression must be aliased using {@link Expression#as}.
      • *
      * * If no selections are provided within the `options` (i.e., the `fields` array is empty), @@ -8795,15 +9265,15 @@ declare namespace FirebaseFirestore { /** * @beta * Filters the documents from previous stages to only include those matching the specified {@link - * BooleanExpr}. + * BooleanExpression}. * *

      This stage allows you to apply conditions to the data, similar to a "WHERE" clause in SQL. * You can filter documents based on their field values, using implementations of {@link - * BooleanExpr}, typically including but not limited to: + * BooleanExpression}, typically including but not limited to: * *

        - *
      • field comparators: {@link Function#eq}, {@link Function#lt} (less than), {@link - * Function#gt} (greater than), etc.
      • + *
      • field comparators: {@link Function#equal}, {@link Function#lessThan} (less than), {@link + * Function#greaterThan} (greater than), etc.
      • *
      • logical operators: {@link Function#and}, {@link Function#or}, {@link Function#not}, etc.
      • *
      • advanced functions: {@link Function#regexMatch}, {@link * Function#arrayContains}, etc.
      • @@ -8815,28 +9285,28 @@ declare namespace FirebaseFirestore { * firestore.pipeline().collection("books") * .where( * and( - * gt(field("rating"), 4.0), // Filter for ratings greater than 4.0 - * field("genre").eq("Science Fiction") // Equivalent to gt("genre", "Science Fiction") + * greaterThan(field("rating"), 4.0), // Filter for ratings greater than 4.0 + * field("genre").equal("Science Fiction") // Equivalent to greaterThan("genre", "Science Fiction") * ) * ); * ``` * - * @param condition The {@link BooleanExpr} to apply. + * @param condition The {@link BooleanExpression} to apply. * @return A new Pipeline object with this stage appended to the stage list. */ - where(condition: BooleanExpr): Pipeline; + where(condition: BooleanExpression): Pipeline; /** * @beta * Filters the documents from previous stages to only include those matching the specified {@link - * BooleanExpr}. + * BooleanExpression}. * *

        This stage allows you to apply conditions to the data, similar to a "WHERE" clause in SQL. * You can filter documents based on their field values, using implementations of {@link - * BooleanExpr}, typically including but not limited to: + * BooleanExpression}, typically including but not limited to: * *

          - *
        • field comparators: {@link Function#eq}, {@link Function#lt} (less than), {@link - * Function#gt} (greater than), etc.
        • + *
        • field comparators: {@link Function#equal}, {@link Function#lessThan} (less than), {@link + * Function#greaterThan} (greater than), etc.
        • *
        • logical operators: {@link Function#and}, {@link Function#or}, {@link Function#not}, etc.
        • *
        • advanced functions: {@link Function#regexMatch}, {@link * Function#arrayContains}, etc.
        • @@ -8848,13 +9318,13 @@ declare namespace FirebaseFirestore { * firestore.pipeline().collection("books") * .where({ * filter: and( - * gt(field("rating"), 4.0), // Filter for ratings greater than 4.0 - * field("genre").eq("Science Fiction") // Equivalent to gt("genre", "Science Fiction") + * greaterThan(field("rating"), 4.0), // Filter for ratings greater than 4.0 + * field("genre").equal("Science Fiction") // Equivalent to greaterThan("genre", "Science Fiction") * ) * }); * ``` * - * @param options An object that specifies the filtering criteria. It is expected to contain a `filter` property of type {@link BooleanExpr}. + * @param options An object that specifies the filtering criteria. It is expected to contain a `filter` property of type {@link BooleanExpression}. * @return A new Pipeline object with this stage appended to the stage list. */ where(options: WhereStageOptions): Pipeline; @@ -8963,14 +9433,14 @@ declare namespace FirebaseFirestore { * Returns a set of distinct values from the inputs to this stage. * * This stage runs through the results from previous stages to include only results with - * unique combinations of {@link Expr} values ({@link Field}, {@link Function}, etc). + * unique combinations of {@link Expression} values ({@link Field}, {@link Function}, etc). * * The parameters to this stage are defined using {@link Selectable} expressions or strings: * * - {@code string}: Name of an existing field * - {@link Field}: References an existing document field. - * - {@link AliasedExpr}: Represents the result of a function with an assigned alias name - * using {@link Expr#as}. + * - {@link AliasedExpression}: Represents the result of a function with an assigned alias name + * using {@link Expression#as}. * * Example: * @@ -8996,14 +9466,14 @@ declare namespace FirebaseFirestore { * Returns a set of distinct values from the inputs to this stage. * * This stage runs through the results from previous stages to include only results with - * unique combinations of {@link Expr} values ({@link Field}, {@link Function}, etc). + * unique combinations of {@link Expression} values ({@link Field}, {@link Function}, etc). * * The parameters to this stage are defined using {@link Selectable} expressions or strings: * * - {@code string}: Name of an existing field * - {@link Field}: References an existing document field. - * - {@link AliasedExpr}: Represents the result of a function with an assigned alias name - * using {@link Expr#as}. + * - {@link AliasedExpression}: Represents the result of a function with an assigned alias name + * using {@link Expression#as}. * * Example: * @@ -9024,7 +9494,7 @@ declare namespace FirebaseFirestore { * *

          This stage allows you to calculate aggregate values over a set of documents. You define the * aggregations to perform using {@link AliasedAggregate} expressions which are typically results of - * calling {@link Expr#as} on {@link AggregateFunction} instances. + * calling {@link Expression#as} on {@link AggregateFunction} instances. * *

          Example: * @@ -9032,7 +9502,7 @@ declare namespace FirebaseFirestore { * // Calculate the average rating and the total number of books * firestore.pipeline().collection("books") * .aggregate( - * field("rating").avg().as("averageRating"), + * field("rating").average().as("averageRating"), * countAll().as("totalBooks") * ); * ``` @@ -9061,7 +9531,7 @@ declare namespace FirebaseFirestore { * specifying groups is the same as putting the entire inputs into one group. *

        • **Accumulators:** One or more accumulation operations to perform within each group. These * are defined using {@link AliasedAggregate} expressions, which are typically created by - * calling {@link Expr#as} on {@link AggregateFunction} instances. Each aggregation + * calling {@link Expression#as} on {@link AggregateFunction} instances. Each aggregation * calculates a value (e.g., sum, average, count) based on the documents within its group.
        • *
        * @@ -9071,7 +9541,7 @@ declare namespace FirebaseFirestore { * // Calculate the average rating for each genre. * firestore.pipeline().collection("books") * .aggregate({ - * accumulators: [avg(field("rating")).as("avg_rating")] + * accumulators: [average(field("rating")).as("avg_rating")] * groups: ["genre"] * }); * ``` @@ -9148,7 +9618,7 @@ declare namespace FirebaseFirestore { * Fully replaces all fields in a document with the fields from a map expression. * *

        This stage allows you to transform the current document into a new one - * by providing an {@link Expr} that evaluates to a map. Each key-value pair + * by providing an {@link Expression} that evaluates to a map. Each key-value pair * in the resulting map will become a field-value pair in the document. * *

        Example: @@ -9176,10 +9646,10 @@ declare namespace FirebaseFirestore { * // } * ``` * - * @param expr An {@link Expr} that evaluates to a map. The key-value pairs of this map will replace the document's fields. + * @param expr An {@link Expression} that evaluates to a map. The key-value pairs of this map will replace the document's fields. * @return A new {@code Pipeline} object with this stage appended to the stage list. */ - replaceWith(expr: Expr): Pipeline; + replaceWith(expr: Expression): Pipeline; /** * @beta @@ -9442,7 +9912,7 @@ declare namespace FirebaseFirestore { * ```typescript * // Assume we don't have a built-in "where" stage * firestore.pipeline().collection("books") - * .rawStage("where", [Field.of("published").lt(1900)]) // Custom "where" stage + * .rawStage("where", [Field.of("published").lessThan(1900)]) // Custom "where" stage * .select("title", "author"); * ``` * @@ -9476,7 +9946,7 @@ declare namespace FirebaseFirestore { * * ```typescript * const futureResults = await firestore.pipeline().collection("books") - * .where(gt(Field.of("rating"), 4.5)) + * .where(greaterThan(Field.of("rating"), 4.5)) * .select("title", "author", "rating") * .execute(); * ``` @@ -9497,7 +9967,7 @@ declare namespace FirebaseFirestore { * @example * ```typescript * firestore.pipeline().collection("books") - * .where(gt(Field.of("rating"), 4.5)) + * .where(greaterThan(Field.of("rating"), 4.5)) * .select("title", "author", "rating") * .stream() * .on('data', (pipelineResult) => { @@ -9537,7 +10007,7 @@ declare namespace FirebaseFirestore { * @beta * Specifies the output format of the query planner information. */ - outputFormat?: 'text' | 'json'; + outputFormat?: 'text'; }; /** * @beta @@ -9719,9 +10189,9 @@ declare namespace FirebaseFirestore { export type WhereStageOptions = StageOptions & { /** * @beta - * The {@link BooleanExpr} to apply as a filter for each input document to this stage. + * The {@link BooleanExpression} to apply as a filter for each input document to this stage. */ - condition: BooleanExpr; + condition: BooleanExpression; }; /** * @beta @@ -9822,10 +10292,10 @@ declare namespace FirebaseFirestore { export type ReplaceWithStageOptions = StageOptions & { /** * @beta - * The name of a field that contains a map or an {@link Expr} that + * The name of a field that contains a map or an {@link Expression} that * evaluates to a map. */ - map: Expr | string; + map: Expression | string; }; /** * @beta @@ -9953,7 +10423,7 @@ declare namespace FirebaseFirestore { * const snapshot = await firestore * .pipeline() * .collection('myCollection') - * .where(field('value').gt(10)) + * .where(field('value').greaterThan(10)) * .execute(); * * snapshot.results.forEach(doc => { @@ -9997,7 +10467,6 @@ declare namespace FirebaseFirestore { * value. */ export class PipelineResult { - readonly executionTime: Timestamp; readonly createTime: Timestamp | undefined; readonly updateTime: Timestamp | undefined; /** From e60cedf48320345c203f66f32c186f9b283507ea Mon Sep 17 00:00:00 2001 From: Mark Duckworth <1124037+MarkDuckworth@users.noreply.github.com> Date: Fri, 31 Oct 2025 13:15:21 -0600 Subject: [PATCH 45/60] add split, type, timestampTrunc, and fix trim --- api-report/firestore.api.md | 3610 +++++++++++++++++++++++++++---- dev/src/pipelines/expression.ts | 379 +++- dev/src/pipelines/index.ts | 3 + dev/system-test/pipeline.ts | 180 +- types/firestore.d.ts | 347 ++- 5 files changed, 4085 insertions(+), 434 deletions(-) diff --git a/api-report/firestore.api.md b/api-report/firestore.api.md index 2715c31f1..1b166c2a3 100644 --- a/api-report/firestore.api.md +++ b/api-report/firestore.api.md @@ -4,16 +4,46 @@ ```ts -import { DocumentData } from '@google-cloud/firestore'; import { Duplex } from 'stream'; import * as firestore from '@google-cloud/firestore'; import { google } from '../protos/firestore_v1_proto_api'; +import { google as google_2 } from '../../protos/firestore_v1_proto_api'; import { GoogleError } from 'google-gax'; import * as proto from '../protos/firestore_v1_proto_api'; import * as protos from '../../protos/firestore_v1_proto_api'; import { Readable } from 'stream'; import { Span as Span_2 } from '@opentelemetry/api'; +// Warning: (tsdoc-param-tag-missing-hyphen) The @param block should be followed by a parameter name and then a hyphen +// Warning: (tsdoc-undefined-tag) The TSDoc tag "@return" is not defined in this configuration +// Warning: (tsdoc-undefined-tag) The TSDoc tag "@code" is not defined in this configuration +// +// @beta +function abs(expr: Expression): FunctionExpression; + +// Warning: (tsdoc-param-tag-missing-hyphen) The @param block should be followed by a parameter name and then a hyphen +// Warning: (tsdoc-undefined-tag) The TSDoc tag "@return" is not defined in this configuration +// Warning: (tsdoc-undefined-tag) The TSDoc tag "@code" is not defined in this configuration +// +// @beta +function abs(fieldName: string): FunctionExpression; + +// Warning: (tsdoc-param-tag-missing-hyphen) The @param block should be followed by a parameter name and then a hyphen +// Warning: (tsdoc-param-tag-missing-hyphen) The @param block should be followed by a parameter name and then a hyphen +// Warning: (tsdoc-undefined-tag) The TSDoc tag "@return" is not defined in this configuration +// Warning: (tsdoc-undefined-tag) The TSDoc tag "@code" is not defined in this configuration +// +// @beta +function add(first: Expression, second: Expression | unknown): FunctionExpression; + +// Warning: (tsdoc-param-tag-missing-hyphen) The @param block should be followed by a parameter name and then a hyphen +// Warning: (tsdoc-param-tag-missing-hyphen) The @param block should be followed by a parameter name and then a hyphen +// Warning: (tsdoc-undefined-tag) The TSDoc tag "@return" is not defined in this configuration +// Warning: (tsdoc-undefined-tag) The TSDoc tag "@code" is not defined in this configuration +// +// @beta +function add(fieldName: string, second: Expression | unknown): FunctionExpression; + // @public export class Aggregate { constructor(alias: string, aggregateType: AggregateType, fieldPath?: (string | FieldPath) | undefined); @@ -47,6 +77,31 @@ export class AggregateField implements firestore.AggregateField { // @public export type AggregateFieldType = ReturnType | ReturnType | ReturnType; +// Warning: (ae-forgotten-export) The symbol "HasUserData" needs to be exported by the entry point index.d.ts +// +// @beta +class AggregateFunction implements AggregateFunction, HasUserData { + constructor(name: string, params: Expression[]); + // Warning: (tsdoc-param-tag-missing-hyphen) The @param block should be followed by a parameter name and then a hyphen + // Warning: (tsdoc-undefined-tag) The TSDoc tag "@return" is not defined in this configuration + as(name: string): AliasedAggregate; + // Warning: (tsdoc-undefined-tag) The TSDoc tag "@private" is not defined in this configuration + _createdFromLiteral: boolean; + // (undocumented) + expressionType: firestore.Pipelines.ExpressionType; + // (undocumented) + _protoValueType: "ProtoValue"; + // Warning: (tsdoc-undefined-tag) The TSDoc tag "@private" is not defined in this configuration + // Warning: (ae-forgotten-export) The symbol "Serializer" needs to be exported by the entry point index.d.ts + // + // (undocumented) + _toProto(serializer: Serializer): api.IValue; + // Warning: (tsdoc-undefined-tag) The TSDoc tag "@private" is not defined in this configuration + // + // (undocumented) + _validateUserData(ignoreUndefinedProperties: boolean): void; +} + // @public export class AggregateQuery implements firestore.AggregateQuery { // Warning: (tsdoc-param-tag-missing-hyphen) The @param block should be followed by a parameter name and then a hyphen @@ -73,6 +128,10 @@ export class AggregateQuery): boolean; + // Warning: (tsdoc-undefined-tag) The TSDoc tag "@private" is not defined in this configuration + // + // @internal (undocumented) + _pipeline(): Pipeline; get query(): Query; // Warning: (tsdoc-undefined-tag) The TSDoc tag "@private" is not defined in this configuration // Warning: (tsdoc-param-tag-missing-hyphen) The @param block should be followed by a parameter name and then a hyphen @@ -111,6 +170,284 @@ export interface AggregateSpec { // @public export type AggregateType = 'count' | 'avg' | 'sum'; +// @beta +class AliasedAggregate implements AliasedAggregate, HasUserData { + constructor(_aggregate: AggregateFunction, _alias: string); + // (undocumented) + readonly _aggregate: AggregateFunction; + // (undocumented) + readonly _alias: string; + // Warning: (tsdoc-undefined-tag) The TSDoc tag "@private" is not defined in this configuration + _createdFromLiteral: boolean; + // Warning: (tsdoc-undefined-tag) The TSDoc tag "@private" is not defined in this configuration + // + // (undocumented) + _validateUserData(ignoreUndefinedProperties: boolean): void; +} + +// @beta +class AliasedExpression implements firestore.Pipelines.Selectable, HasUserData { + constructor(_expr: Expression, _alias: string); + // (undocumented) + readonly _alias: string; + // Warning: (tsdoc-undefined-tag) The TSDoc tag "@private" is not defined in this configuration + _createdFromLiteral: boolean; + // (undocumented) + readonly _expr: Expression; + // (undocumented) + expressionType: firestore.Pipelines.ExpressionType; + // (undocumented) + selectable: true; + // Warning: (tsdoc-undefined-tag) The TSDoc tag "@private" is not defined in this configuration + // + // (undocumented) + _validateUserData(ignoreUndefinedProperties: boolean): void; +} + +// Warning: (tsdoc-param-tag-missing-hyphen) The @param block should be followed by a parameter name and then a hyphen +// Warning: (tsdoc-param-tag-missing-hyphen) The @param block should be followed by a parameter name and then a hyphen +// Warning: (tsdoc-param-tag-missing-hyphen) The @param block should be followed by a parameter name and then a hyphen +// Warning: (tsdoc-undefined-tag) The TSDoc tag "@return" is not defined in this configuration +// Warning: (tsdoc-undefined-tag) The TSDoc tag "@code" is not defined in this configuration +// +// @beta +function and(first: BooleanExpression, second: BooleanExpression, ...more: BooleanExpression[]): BooleanExpression; + +// Warning: (tsdoc-param-tag-missing-hyphen) The @param block should be followed by a parameter name and then a hyphen +// Warning: (tsdoc-undefined-tag) The TSDoc tag "@return" is not defined in this configuration +// Warning: (tsdoc-undefined-tag) The TSDoc tag "@code" is not defined in this configuration +// +// @beta +function array(elements: unknown[]): FunctionExpression; + +// Warning: (tsdoc-param-tag-missing-hyphen) The @param block should be followed by a parameter name and then a hyphen +// Warning: (tsdoc-param-tag-missing-hyphen) The @param block should be followed by a parameter name and then a hyphen +// Warning: (tsdoc-param-tag-missing-hyphen) The @param block should be followed by a parameter name and then a hyphen +// Warning: (tsdoc-undefined-tag) The TSDoc tag "@return" is not defined in this configuration +// Warning: (tsdoc-undefined-tag) The TSDoc tag "@code" is not defined in this configuration +// +// @beta +function arrayConcat(firstArray: Expression, secondArray: Expression | unknown[], ...otherArrays: Array): FunctionExpression; + +// Warning: (tsdoc-param-tag-missing-hyphen) The @param block should be followed by a parameter name and then a hyphen +// Warning: (tsdoc-param-tag-missing-hyphen) The @param block should be followed by a parameter name and then a hyphen +// Warning: (tsdoc-param-tag-missing-hyphen) The @param block should be followed by a parameter name and then a hyphen +// Warning: (tsdoc-undefined-tag) The TSDoc tag "@return" is not defined in this configuration +// Warning: (tsdoc-undefined-tag) The TSDoc tag "@code" is not defined in this configuration +// +// @beta +function arrayConcat(firstArrayField: string, secondArray: Expression | unknown[], ...otherArrays: Array): FunctionExpression; + +// Warning: (tsdoc-param-tag-missing-hyphen) The @param block should be followed by a parameter name and then a hyphen +// Warning: (tsdoc-param-tag-missing-hyphen) The @param block should be followed by a parameter name and then a hyphen +// Warning: (tsdoc-undefined-tag) The TSDoc tag "@return" is not defined in this configuration +// Warning: (tsdoc-undefined-tag) The TSDoc tag "@code" is not defined in this configuration +// +// @beta +function arrayContains(array: Expression, element: Expression): FunctionExpression; + +// Warning: (tsdoc-param-tag-missing-hyphen) The @param block should be followed by a parameter name and then a hyphen +// Warning: (tsdoc-param-tag-missing-hyphen) The @param block should be followed by a parameter name and then a hyphen +// Warning: (tsdoc-undefined-tag) The TSDoc tag "@return" is not defined in this configuration +// Warning: (tsdoc-undefined-tag) The TSDoc tag "@code" is not defined in this configuration +// +// @beta +function arrayContains(array: Expression, element: unknown): FunctionExpression; + +// Warning: (tsdoc-param-tag-missing-hyphen) The @param block should be followed by a parameter name and then a hyphen +// Warning: (tsdoc-param-tag-missing-hyphen) The @param block should be followed by a parameter name and then a hyphen +// Warning: (tsdoc-undefined-tag) The TSDoc tag "@return" is not defined in this configuration +// Warning: (tsdoc-undefined-tag) The TSDoc tag "@code" is not defined in this configuration +// +// @beta +function arrayContains(fieldName: string, element: Expression): FunctionExpression; + +// Warning: (tsdoc-param-tag-missing-hyphen) The @param block should be followed by a parameter name and then a hyphen +// Warning: (tsdoc-param-tag-missing-hyphen) The @param block should be followed by a parameter name and then a hyphen +// Warning: (tsdoc-undefined-tag) The TSDoc tag "@return" is not defined in this configuration +// Warning: (tsdoc-undefined-tag) The TSDoc tag "@code" is not defined in this configuration +// +// @beta +function arrayContains(fieldName: string, element: unknown): BooleanExpression; + +// Warning: (tsdoc-param-tag-missing-hyphen) The @param block should be followed by a parameter name and then a hyphen +// Warning: (tsdoc-param-tag-missing-hyphen) The @param block should be followed by a parameter name and then a hyphen +// Warning: (tsdoc-undefined-tag) The TSDoc tag "@return" is not defined in this configuration +// Warning: (tsdoc-undefined-tag) The TSDoc tag "@code" is not defined in this configuration +// +// @beta +function arrayContainsAll(array: Expression, values: Array): BooleanExpression; + +// Warning: (tsdoc-param-tag-missing-hyphen) The @param block should be followed by a parameter name and then a hyphen +// Warning: (tsdoc-param-tag-missing-hyphen) The @param block should be followed by a parameter name and then a hyphen +// Warning: (tsdoc-undefined-tag) The TSDoc tag "@return" is not defined in this configuration +// Warning: (tsdoc-undefined-tag) The TSDoc tag "@code" is not defined in this configuration +// +// @beta +function arrayContainsAll(fieldName: string, values: Array): BooleanExpression; + +// Warning: (tsdoc-param-tag-missing-hyphen) The @param block should be followed by a parameter name and then a hyphen +// Warning: (tsdoc-param-tag-missing-hyphen) The @param block should be followed by a parameter name and then a hyphen +// Warning: (tsdoc-undefined-tag) The TSDoc tag "@return" is not defined in this configuration +// Warning: (tsdoc-undefined-tag) The TSDoc tag "@code" is not defined in this configuration +// +// @beta +function arrayContainsAll(array: Expression, arrayExpression: Expression): BooleanExpression; + +// Warning: (tsdoc-param-tag-missing-hyphen) The @param block should be followed by a parameter name and then a hyphen +// Warning: (tsdoc-param-tag-missing-hyphen) The @param block should be followed by a parameter name and then a hyphen +// Warning: (tsdoc-undefined-tag) The TSDoc tag "@return" is not defined in this configuration +// Warning: (tsdoc-undefined-tag) The TSDoc tag "@code" is not defined in this configuration +// +// @beta +function arrayContainsAll(fieldName: string, arrayExpression: Expression): BooleanExpression; + +// Warning: (tsdoc-param-tag-missing-hyphen) The @param block should be followed by a parameter name and then a hyphen +// Warning: (tsdoc-param-tag-missing-hyphen) The @param block should be followed by a parameter name and then a hyphen +// Warning: (tsdoc-undefined-tag) The TSDoc tag "@return" is not defined in this configuration +// Warning: (tsdoc-undefined-tag) The TSDoc tag "@code" is not defined in this configuration +// +// @beta +function arrayContainsAny(array: Expression, values: Array): BooleanExpression; + +// Warning: (tsdoc-param-tag-missing-hyphen) The @param block should be followed by a parameter name and then a hyphen +// Warning: (tsdoc-param-tag-missing-hyphen) The @param block should be followed by a parameter name and then a hyphen +// Warning: (tsdoc-undefined-tag) The TSDoc tag "@return" is not defined in this configuration +// Warning: (tsdoc-undefined-tag) The TSDoc tag "@code" is not defined in this configuration +// +// @beta +function arrayContainsAny(fieldName: string, values: Array): BooleanExpression; + +// Warning: (tsdoc-param-tag-missing-hyphen) The @param block should be followed by a parameter name and then a hyphen +// Warning: (tsdoc-param-tag-missing-hyphen) The @param block should be followed by a parameter name and then a hyphen +// Warning: (tsdoc-undefined-tag) The TSDoc tag "@return" is not defined in this configuration +// Warning: (tsdoc-undefined-tag) The TSDoc tag "@code" is not defined in this configuration +// +// @beta +function arrayContainsAny(array: Expression, values: Expression): BooleanExpression; + +// Warning: (tsdoc-param-tag-missing-hyphen) The @param block should be followed by a parameter name and then a hyphen +// Warning: (tsdoc-param-tag-missing-hyphen) The @param block should be followed by a parameter name and then a hyphen +// Warning: (tsdoc-undefined-tag) The TSDoc tag "@return" is not defined in this configuration +// Warning: (tsdoc-undefined-tag) The TSDoc tag "@code" is not defined in this configuration +// +// @beta +function arrayContainsAny(fieldName: string, values: Expression): BooleanExpression; + +// Warning: (tsdoc-param-tag-missing-hyphen) The @param block should be followed by a parameter name and then a hyphen +// Warning: (tsdoc-param-tag-missing-hyphen) The @param block should be followed by a parameter name and then a hyphen +// Warning: (tsdoc-undefined-tag) The TSDoc tag "@return" is not defined in this configuration +// +// @beta +function arrayGet(arrayField: string, index: number): FunctionExpression; + +// Warning: (tsdoc-param-tag-missing-hyphen) The @param block should be followed by a parameter name and then a hyphen +// Warning: (tsdoc-param-tag-missing-hyphen) The @param block should be followed by a parameter name and then a hyphen +// Warning: (tsdoc-undefined-tag) The TSDoc tag "@return" is not defined in this configuration +// +// @beta +function arrayGet(arrayField: string, indexExpr: Expression): FunctionExpression; + +// Warning: (tsdoc-param-tag-missing-hyphen) The @param block should be followed by a parameter name and then a hyphen +// Warning: (tsdoc-param-tag-missing-hyphen) The @param block should be followed by a parameter name and then a hyphen +// Warning: (tsdoc-undefined-tag) The TSDoc tag "@return" is not defined in this configuration +// +// @beta +function arrayGet(arrayExpression: Expression, index: number): FunctionExpression; + +// Warning: (tsdoc-param-tag-missing-hyphen) The @param block should be followed by a parameter name and then a hyphen +// Warning: (tsdoc-param-tag-missing-hyphen) The @param block should be followed by a parameter name and then a hyphen +// Warning: (tsdoc-undefined-tag) The TSDoc tag "@return" is not defined in this configuration +// +// @beta +function arrayGet(arrayExpression: Expression, indexExpr: Expression): FunctionExpression; + +// Warning: (tsdoc-param-tag-missing-hyphen) The @param block should be followed by a parameter name and then a hyphen +// Warning: (tsdoc-undefined-tag) The TSDoc tag "@return" is not defined in this configuration +// Warning: (tsdoc-undefined-tag) The TSDoc tag "@code" is not defined in this configuration +// +// @beta +function arrayLength(fieldName: string): FunctionExpression; + +// Warning: (tsdoc-param-tag-missing-hyphen) The @param block should be followed by a parameter name and then a hyphen +// Warning: (tsdoc-undefined-tag) The TSDoc tag "@return" is not defined in this configuration +// Warning: (tsdoc-undefined-tag) The TSDoc tag "@code" is not defined in this configuration +// +// @beta +function arrayLength(array: Expression): FunctionExpression; + +// Warning: (tsdoc-param-tag-missing-hyphen) The @param block should be followed by a parameter name and then a hyphen +// Warning: (tsdoc-undefined-tag) The TSDoc tag "@return" is not defined in this configuration +// Warning: (tsdoc-undefined-tag) The TSDoc tag "@code" is not defined in this configuration +// +// @beta +function arrayReverse(fieldName: string): FunctionExpression; + +// Warning: (tsdoc-param-tag-missing-hyphen) The @param block should be followed by a parameter name and then a hyphen +// Warning: (tsdoc-undefined-tag) The TSDoc tag "@return" is not defined in this configuration +// Warning: (tsdoc-undefined-tag) The TSDoc tag "@code" is not defined in this configuration +// +// @beta +function arrayReverse(arrayExpression: Expression): FunctionExpression; + +// Warning: (tsdoc-param-tag-missing-hyphen) The @param block should be followed by a parameter name and then a hyphen +// Warning: (tsdoc-undefined-tag) The TSDoc tag "@return" is not defined in this configuration +// +// @beta +function arraySum(fieldName: string): FunctionExpression; + +// Warning: (tsdoc-param-tag-missing-hyphen) The @param block should be followed by a parameter name and then a hyphen +// Warning: (tsdoc-undefined-tag) The TSDoc tag "@return" is not defined in this configuration +// +// @beta +function arraySum(expression: Expression): FunctionExpression; + +// Warning: (tsdoc-param-tag-missing-hyphen) The @param block should be followed by a parameter name and then a hyphen +// Warning: (tsdoc-undefined-tag) The TSDoc tag "@return" is not defined in this configuration +// +// @beta +function ascending(expr: Expression): Ordering; + +// Warning: (tsdoc-param-tag-missing-hyphen) The @param block should be followed by a parameter name and then a hyphen +// Warning: (tsdoc-undefined-tag) The TSDoc tag "@return" is not defined in this configuration +// +// @beta +function ascending(fieldName: string): Ordering; + +// Warning: (tsdoc-param-tag-missing-hyphen) The @param block should be followed by a parameter name and then a hyphen +// Warning: (tsdoc-undefined-tag) The TSDoc tag "@return" is not defined in this configuration +// Warning: (tsdoc-undefined-tag) The TSDoc tag "@code" is not defined in this configuration +// +// @beta +function average(expression: Expression): AggregateFunction; + +// Warning: (tsdoc-param-tag-missing-hyphen) The @param block should be followed by a parameter name and then a hyphen +// Warning: (tsdoc-undefined-tag) The TSDoc tag "@return" is not defined in this configuration +// Warning: (tsdoc-undefined-tag) The TSDoc tag "@code" is not defined in this configuration +// +// @beta +function average(fieldName: string): AggregateFunction; + +// @beta +class BooleanExpression extends FunctionExpression implements firestore.Pipelines.BooleanExpression { + // Warning: (tsdoc-param-tag-missing-hyphen) The @param block should be followed by a parameter name and then a hyphen + // Warning: (tsdoc-param-tag-missing-hyphen) The @param block should be followed by a parameter name and then a hyphen + // Warning: (tsdoc-undefined-tag) The TSDoc tag "@return" is not defined in this configuration + // Warning: (tsdoc-undefined-tag) The TSDoc tag "@code" is not defined in this configuration + conditional(thenExpr: Expression, elseExpr: Expression): FunctionExpression; + // Warning: (tsdoc-undefined-tag) The TSDoc tag "@return" is not defined in this configuration + countIf(): AggregateFunction; + // Warning: (tsdoc-param-tag-missing-hyphen) The @param block should be followed by a parameter name and then a hyphen + // Warning: (tsdoc-undefined-tag) The TSDoc tag "@return" is not defined in this configuration + // Warning: (tsdoc-undefined-tag) The TSDoc tag "@code" is not defined in this configuration + ifError(catchValue: BooleanExpression): BooleanExpression; + // Warning: (tsdoc-undefined-tag) The TSDoc tag "@return" is not defined in this configuration + // Warning: (tsdoc-undefined-tag) The TSDoc tag "@code" is not defined in this configuration + not(): BooleanExpression; + // (undocumented) + returnType: 'boolean'; +} + // Warning: (tsdoc-undefined-tag) The TSDoc tag "@class" is not defined in this configuration // // @public @@ -229,6 +566,48 @@ export class BundleBuilder { readonly bundleId: string; } +// Warning: (tsdoc-param-tag-missing-hyphen) The @param block should be followed by a parameter name and then a hyphen +// Warning: (tsdoc-undefined-tag) The TSDoc tag "@return" is not defined in this configuration +// Warning: (tsdoc-undefined-tag) The TSDoc tag "@code" is not defined in this configuration +// +// @beta +function byteLength(expr: Expression): FunctionExpression; + +// Warning: (tsdoc-param-tag-missing-hyphen) The @param block should be followed by a parameter name and then a hyphen +// Warning: (tsdoc-undefined-tag) The TSDoc tag "@return" is not defined in this configuration +// Warning: (tsdoc-undefined-tag) The TSDoc tag "@code" is not defined in this configuration +// +// @beta +function byteLength(fieldName: string): FunctionExpression; + +// Warning: (tsdoc-param-tag-missing-hyphen) The @param block should be followed by a parameter name and then a hyphen +// Warning: (tsdoc-undefined-tag) The TSDoc tag "@return" is not defined in this configuration +// Warning: (tsdoc-undefined-tag) The TSDoc tag "@code" is not defined in this configuration +// +// @beta +function ceil(fieldName: string): FunctionExpression; + +// Warning: (tsdoc-param-tag-missing-hyphen) The @param block should be followed by a parameter name and then a hyphen +// Warning: (tsdoc-undefined-tag) The TSDoc tag "@return" is not defined in this configuration +// Warning: (tsdoc-undefined-tag) The TSDoc tag "@code" is not defined in this configuration +// +// @beta +function ceil(expression: Expression): FunctionExpression; + +// Warning: (tsdoc-param-tag-missing-hyphen) The @param block should be followed by a parameter name and then a hyphen +// Warning: (tsdoc-undefined-tag) The TSDoc tag "@return" is not defined in this configuration +// Warning: (tsdoc-undefined-tag) The TSDoc tag "@code" is not defined in this configuration +// +// @beta +function charLength(fieldName: string): FunctionExpression; + +// Warning: (tsdoc-param-tag-missing-hyphen) The @param block should be followed by a parameter name and then a hyphen +// Warning: (tsdoc-undefined-tag) The TSDoc tag "@return" is not defined in this configuration +// Warning: (tsdoc-undefined-tag) The TSDoc tag "@code" is not defined in this configuration +// +// @beta +function charLength(stringExpression: Expression): FunctionExpression; + // Warning: (tsdoc-undefined-tag) The TSDoc tag "@class" is not defined in this configuration // // @public @@ -246,11 +625,23 @@ export class CollectionGroup(converter: firestore.FirestoreDataConverter): CollectionGroup; + withConverter(converter: firestore.FirestoreDataConverter | null): CollectionGroup; } +// Warning: (tsdoc-param-tag-missing-hyphen) The @param block should be followed by a parameter name and then a hyphen +// Warning: (tsdoc-undefined-tag) The TSDoc tag "@return" is not defined in this configuration +// Warning: (tsdoc-undefined-tag) The TSDoc tag "@code" is not defined in this configuration +// +// @beta +function collectionId(fieldName: string): FunctionExpression; + +// Warning: (tsdoc-param-tag-missing-hyphen) The @param block should be followed by a parameter name and then a hyphen +// Warning: (tsdoc-undefined-tag) The TSDoc tag "@return" is not defined in this configuration +// Warning: (tsdoc-undefined-tag) The TSDoc tag "@code" is not defined in this configuration +// +// @beta +function collectionId(expression: Expression): FunctionExpression; + // Warning: (tsdoc-undefined-tag) The TSDoc tag "@class" is not defined in this configuration // Warning: (tsdoc-undefined-tag) The TSDoc tag "@extends" is not defined in this configuration // @@ -302,62 +693,304 @@ export class CollectionReference(converter: firestore.FirestoreDataConverter): CollectionReference; + // (undocumented) + withConverter(converter: null): CollectionReference; } -// @public (undocumented) -export const DEFAULT_MAX_IDLE_CHANNELS = 1; +// Warning: (tsdoc-param-tag-missing-hyphen) The @param block should be followed by a parameter name and then a hyphen +// Warning: (tsdoc-param-tag-missing-hyphen) The @param block should be followed by a parameter name and then a hyphen +// Warning: (tsdoc-param-tag-missing-hyphen) The @param block should be followed by a parameter name and then a hyphen +// Warning: (tsdoc-undefined-tag) The TSDoc tag "@return" is not defined in this configuration +// +// @beta +function concat(first: Expression, second: Expression | unknown, ...others: Array): FunctionExpression; -// Warning: (tsdoc-undefined-tag) The TSDoc tag "@private" is not defined in this configuration +// Warning: (tsdoc-param-tag-missing-hyphen) The @param block should be followed by a parameter name and then a hyphen +// Warning: (tsdoc-param-tag-missing-hyphen) The @param block should be followed by a parameter name and then a hyphen +// Warning: (tsdoc-param-tag-missing-hyphen) The @param block should be followed by a parameter name and then a hyphen +// Warning: (tsdoc-undefined-tag) The TSDoc tag "@return" is not defined in this configuration // -// @public -export const DEFAULT_MAX_TRANSACTION_ATTEMPTS = 5; +// @beta +function concat(fieldName: string, second: Expression | unknown, ...others: Array): FunctionExpression; -// Warning: (tsdoc-undefined-tag) The TSDoc tag "@class" is not defined in this configuration +// Warning: (tsdoc-param-tag-missing-hyphen) The @param block should be followed by a parameter name and then a hyphen +// Warning: (tsdoc-param-tag-missing-hyphen) The @param block should be followed by a parameter name and then a hyphen +// Warning: (tsdoc-param-tag-missing-hyphen) The @param block should be followed by a parameter name and then a hyphen +// Warning: (tsdoc-undefined-tag) The TSDoc tag "@return" is not defined in this configuration +// Warning: (tsdoc-undefined-tag) The TSDoc tag "@code" is not defined in this configuration // -// @public -export class DocumentChange implements firestore.DocumentChange { +// @beta +function conditional(condition: BooleanExpression, thenExpr: Expression, elseExpr: Expression): FunctionExpression; + +// @beta +class Constant extends Expression { // Warning: (tsdoc-undefined-tag) The TSDoc tag "@private" is not defined in this configuration + // Warning: (tsdoc-undefined-tag) The TSDoc tag "@hideconstructor" is not defined in this configuration // Warning: (tsdoc-param-tag-missing-hyphen) The @param block should be followed by a parameter name and then a hyphen - // Warning: (tsdoc-param-tag-with-invalid-type) The @param block should not include a JSDoc-style '{type}' - // Warning: (tsdoc-param-tag-missing-hyphen) The @param block should be followed by a parameter name and then a hyphen - // Warning: (tsdoc-param-tag-with-invalid-type) The @param block should not include a JSDoc-style '{type}' - // Warning: (tsdoc-param-tag-missing-hyphen) The @param block should be followed by a parameter name and then a hyphen - // Warning: (tsdoc-param-tag-with-invalid-type) The @param block should not include a JSDoc-style '{type}' - // Warning: (tsdoc-param-tag-missing-hyphen) The @param block should be followed by a parameter name and then a hyphen - // Warning: (tsdoc-param-tag-with-invalid-type) The @param block should not include a JSDoc-style '{type}' - constructor(type: DocumentChangeType, document: QueryDocumentSnapshot, oldIndex: number, newIndex: number); - // Warning: (tsdoc-escape-right-brace) The "}" character should be escaped using a backslash to avoid confusion with a TSDoc inline tag - // Warning: (tsdoc-malformed-inline-tag) Expecting a TSDoc tag starting with "{@" - // Warning: (tsdoc-undefined-tag) The TSDoc tag "@type" is not defined in this configuration - // Warning: (tsdoc-undefined-tag) The TSDoc tag "@name" is not defined in this configuration - get doc(): QueryDocumentSnapshot; - // Warning: (tsdoc-param-tag-missing-hyphen) The @param block should be followed by a parameter name and then a hyphen - // Warning: (tsdoc-param-tag-with-invalid-type) The @param block should not include a JSDoc-style '{type}' - // Warning: (tsdoc-undefined-tag) The TSDoc tag "@return" is not defined in this configuration - isEqual(other: firestore.DocumentChange): boolean; - // Warning: (tsdoc-escape-right-brace) The "}" character should be escaped using a backslash to avoid confusion with a TSDoc inline tag - // Warning: (tsdoc-malformed-inline-tag) Expecting a TSDoc tag starting with "{@" - // Warning: (tsdoc-undefined-tag) The TSDoc tag "@type" is not defined in this configuration - // Warning: (tsdoc-undefined-tag) The TSDoc tag "@name" is not defined in this configuration - get newIndex(): number; - // Warning: (tsdoc-escape-right-brace) The "}" character should be escaped using a backslash to avoid confusion with a TSDoc inline tag - // Warning: (tsdoc-malformed-inline-tag) Expecting a TSDoc tag starting with "{@" - // Warning: (tsdoc-undefined-tag) The TSDoc tag "@type" is not defined in this configuration - // Warning: (tsdoc-undefined-tag) The TSDoc tag "@name" is not defined in this configuration - get oldIndex(): number; - // Warning: (tsdoc-escape-right-brace) The "}" character should be escaped using a backslash to avoid confusion with a TSDoc inline tag - // Warning: (tsdoc-malformed-inline-tag) Expecting a TSDoc tag starting with "{@" - // Warning: (tsdoc-undefined-tag) The TSDoc tag "@type" is not defined in this configuration - // Warning: (tsdoc-undefined-tag) The TSDoc tag "@name" is not defined in this configuration - get type(): DocumentChangeType; -} - -// @public (undocumented) -export type DocumentChangeType = 'added' | 'removed' | 'modified'; - + constructor(value: unknown); + // (undocumented) + readonly expressionType: firestore.Pipelines.ExpressionType; + // Warning: (tsdoc-undefined-tag) The TSDoc tag "@private" is not defined in this configuration + // + // (undocumented) + static _fromProto(value: api.IValue): Constant; + // Warning: (tsdoc-undefined-tag) The TSDoc tag "@private" is not defined in this configuration + // + // (undocumented) + _toProto(serializer: Serializer): api.IValue; + // Warning: (tsdoc-undefined-tag) The TSDoc tag "@private" is not defined in this configuration + // + // (undocumented) + _validateUserData(ignoreUndefinedProperties: boolean): void; +} + +// Warning: (tsdoc-param-tag-missing-hyphen) The @param block should be followed by a parameter name and then a hyphen +// Warning: (tsdoc-undefined-tag) The TSDoc tag "@return" is not defined in this configuration +// +// @beta +function constant(value: number): Expression; + +// Warning: (tsdoc-param-tag-missing-hyphen) The @param block should be followed by a parameter name and then a hyphen +// Warning: (tsdoc-undefined-tag) The TSDoc tag "@return" is not defined in this configuration +// +// @beta +function constant(value: string): Expression; + +// Warning: (tsdoc-param-tag-missing-hyphen) The @param block should be followed by a parameter name and then a hyphen +// Warning: (tsdoc-undefined-tag) The TSDoc tag "@return" is not defined in this configuration +// +// @beta +function constant(value: boolean): BooleanExpression; + +// Warning: (tsdoc-param-tag-missing-hyphen) The @param block should be followed by a parameter name and then a hyphen +// Warning: (tsdoc-undefined-tag) The TSDoc tag "@return" is not defined in this configuration +// +// @beta +function constant(value: null): Expression; + +// Warning: (tsdoc-param-tag-missing-hyphen) The @param block should be followed by a parameter name and then a hyphen +// Warning: (tsdoc-undefined-tag) The TSDoc tag "@return" is not defined in this configuration +// +// @beta +function constant(value: firestore.GeoPoint): Expression; + +// Warning: (tsdoc-param-tag-missing-hyphen) The @param block should be followed by a parameter name and then a hyphen +// Warning: (tsdoc-undefined-tag) The TSDoc tag "@return" is not defined in this configuration +// +// @beta +function constant(value: firestore.Timestamp): Expression; + +// Warning: (tsdoc-param-tag-missing-hyphen) The @param block should be followed by a parameter name and then a hyphen +// Warning: (tsdoc-undefined-tag) The TSDoc tag "@return" is not defined in this configuration +// +// @beta +function constant(value: Date): Expression; + +// Warning: (tsdoc-param-tag-missing-hyphen) The @param block should be followed by a parameter name and then a hyphen +// Warning: (tsdoc-undefined-tag) The TSDoc tag "@return" is not defined in this configuration +// +// @beta +function constant(value: Buffer | Uint8Array): Expression; + +// Warning: (tsdoc-param-tag-missing-hyphen) The @param block should be followed by a parameter name and then a hyphen +// Warning: (tsdoc-undefined-tag) The TSDoc tag "@return" is not defined in this configuration +// +// @beta +function constant(value: firestore.DocumentReference): Expression; + +// Warning: (tsdoc-undefined-tag) The TSDoc tag "@private" is not defined in this configuration +// Warning: (tsdoc-param-tag-missing-hyphen) The @param block should be followed by a parameter name and then a hyphen +// Warning: (tsdoc-undefined-tag) The TSDoc tag "@return" is not defined in this configuration +// +// @beta +function constant(value: api.IValue): Expression; + +// Warning: (tsdoc-param-tag-missing-hyphen) The @param block should be followed by a parameter name and then a hyphen +// Warning: (tsdoc-undefined-tag) The TSDoc tag "@return" is not defined in this configuration +// +// @beta +function constant(value: firestore.VectorValue): Expression; + +// Warning: (tsdoc-undefined-tag) The TSDoc tag "@private" is not defined in this configuration +// Warning: (tsdoc-param-tag-missing-hyphen) The @param block should be followed by a parameter name and then a hyphen +// +// @beta (undocumented) +function constant(value: unknown): Expression; + +// Warning: (tsdoc-param-tag-missing-hyphen) The @param block should be followed by a parameter name and then a hyphen +// Warning: (tsdoc-param-tag-missing-hyphen) The @param block should be followed by a parameter name and then a hyphen +// Warning: (tsdoc-undefined-tag) The TSDoc tag "@return" is not defined in this configuration +// Warning: (tsdoc-undefined-tag) The TSDoc tag "@code" is not defined in this configuration +// +// @beta +function cosineDistance(fieldName: string, vector: number[] | VectorValue): FunctionExpression; + +// Warning: (tsdoc-param-tag-missing-hyphen) The @param block should be followed by a parameter name and then a hyphen +// Warning: (tsdoc-param-tag-missing-hyphen) The @param block should be followed by a parameter name and then a hyphen +// Warning: (tsdoc-undefined-tag) The TSDoc tag "@return" is not defined in this configuration +// Warning: (tsdoc-undefined-tag) The TSDoc tag "@code" is not defined in this configuration +// +// @beta +function cosineDistance(fieldName: string, vectorExpression: Expression): FunctionExpression; + +// Warning: (tsdoc-param-tag-missing-hyphen) The @param block should be followed by a parameter name and then a hyphen +// Warning: (tsdoc-param-tag-missing-hyphen) The @param block should be followed by a parameter name and then a hyphen +// Warning: (tsdoc-undefined-tag) The TSDoc tag "@return" is not defined in this configuration +// Warning: (tsdoc-undefined-tag) The TSDoc tag "@code" is not defined in this configuration +// +// @beta +function cosineDistance(vectorExpression: Expression, vector: number[] | VectorValue): FunctionExpression; + +// Warning: (tsdoc-param-tag-missing-hyphen) The @param block should be followed by a parameter name and then a hyphen +// Warning: (tsdoc-param-tag-missing-hyphen) The @param block should be followed by a parameter name and then a hyphen +// Warning: (tsdoc-undefined-tag) The TSDoc tag "@return" is not defined in this configuration +// Warning: (tsdoc-undefined-tag) The TSDoc tag "@code" is not defined in this configuration +// +// @beta +function cosineDistance(vectorExpression: Expression, otherVectorExpression: Expression): FunctionExpression; + +// Warning: (tsdoc-param-tag-missing-hyphen) The @param block should be followed by a parameter name and then a hyphen +// Warning: (tsdoc-undefined-tag) The TSDoc tag "@return" is not defined in this configuration +// Warning: (tsdoc-undefined-tag) The TSDoc tag "@code" is not defined in this configuration +// +// @beta +function count(expression: Expression): AggregateFunction; + +// Warning: (tsdoc-param-tag-missing-hyphen) The @param block should be followed by a parameter name and then a hyphen +// Warning: (tsdoc-undefined-tag) The TSDoc tag "@return" is not defined in this configuration +// Warning: (tsdoc-undefined-tag) The TSDoc tag "@code" is not defined in this configuration +// +// @beta +function count(fieldName: string): AggregateFunction; + +// Warning: (tsdoc-undefined-tag) The TSDoc tag "@return" is not defined in this configuration +// Warning: (tsdoc-undefined-tag) The TSDoc tag "@code" is not defined in this configuration +// +// @beta +function countAll(): AggregateFunction; + +// Warning: (tsdoc-param-tag-missing-hyphen) The @param block should be followed by a parameter name and then a hyphen +// Warning: (tsdoc-undefined-tag) The TSDoc tag "@return" is not defined in this configuration +// +// @beta +function countDistinct(expr: Expression | string): AggregateFunction; + +// @beta +function countIf(booleanExpr: BooleanExpression): AggregateFunction; + +// Warning: (tsdoc-undefined-tag) The TSDoc tag "@return" is not defined in this configuration +// +// @beta +function currentTimestamp(): FunctionExpression; + +// @public (undocumented) +export const DEFAULT_MAX_IDLE_CHANNELS = 1; + +// Warning: (tsdoc-undefined-tag) The TSDoc tag "@private" is not defined in this configuration +// +// @public +export const DEFAULT_MAX_TRANSACTION_ATTEMPTS = 5; + +// Warning: (tsdoc-param-tag-missing-hyphen) The @param block should be followed by a parameter name and then a hyphen +// Warning: (tsdoc-undefined-tag) The TSDoc tag "@return" is not defined in this configuration +// +// @beta +function descending(expr: Expression): Ordering; + +// Warning: (tsdoc-param-tag-missing-hyphen) The @param block should be followed by a parameter name and then a hyphen +// Warning: (tsdoc-undefined-tag) The TSDoc tag "@return" is not defined in this configuration +// +// @beta +function descending(fieldName: string): Ordering; + +// Warning: (tsdoc-param-tag-missing-hyphen) The @param block should be followed by a parameter name and then a hyphen +// Warning: (tsdoc-param-tag-missing-hyphen) The @param block should be followed by a parameter name and then a hyphen +// Warning: (tsdoc-undefined-tag) The TSDoc tag "@return" is not defined in this configuration +// Warning: (tsdoc-undefined-tag) The TSDoc tag "@code" is not defined in this configuration +// +// @beta +function divide(dividend: Expression, divisort: Expression): FunctionExpression; + +// Warning: (tsdoc-param-tag-missing-hyphen) The @param block should be followed by a parameter name and then a hyphen +// Warning: (tsdoc-param-tag-missing-hyphen) The @param block should be followed by a parameter name and then a hyphen +// Warning: (tsdoc-undefined-tag) The TSDoc tag "@return" is not defined in this configuration +// Warning: (tsdoc-undefined-tag) The TSDoc tag "@code" is not defined in this configuration +// +// @beta +function divide(dividend: Expression, divisor: unknown): FunctionExpression; + +// Warning: (tsdoc-param-tag-missing-hyphen) The @param block should be followed by a parameter name and then a hyphen +// Warning: (tsdoc-param-tag-missing-hyphen) The @param block should be followed by a parameter name and then a hyphen +// Warning: (tsdoc-undefined-tag) The TSDoc tag "@return" is not defined in this configuration +// Warning: (tsdoc-undefined-tag) The TSDoc tag "@code" is not defined in this configuration +// +// @beta +function divide(dividend: string, divisor: Expression): FunctionExpression; + +// Warning: (tsdoc-param-tag-missing-hyphen) The @param block should be followed by a parameter name and then a hyphen +// Warning: (tsdoc-param-tag-missing-hyphen) The @param block should be followed by a parameter name and then a hyphen +// Warning: (tsdoc-undefined-tag) The TSDoc tag "@return" is not defined in this configuration +// Warning: (tsdoc-undefined-tag) The TSDoc tag "@code" is not defined in this configuration +// +// @beta +function divide(dividend: string, divisor: unknown): FunctionExpression; + +// Warning: (tsdoc-undefined-tag) The TSDoc tag "@class" is not defined in this configuration +// +// @public +export class DocumentChange implements firestore.DocumentChange { + // Warning: (tsdoc-undefined-tag) The TSDoc tag "@private" is not defined in this configuration + // Warning: (tsdoc-param-tag-missing-hyphen) The @param block should be followed by a parameter name and then a hyphen + // Warning: (tsdoc-param-tag-with-invalid-type) The @param block should not include a JSDoc-style '{type}' + // Warning: (tsdoc-param-tag-missing-hyphen) The @param block should be followed by a parameter name and then a hyphen + // Warning: (tsdoc-param-tag-with-invalid-type) The @param block should not include a JSDoc-style '{type}' + // Warning: (tsdoc-param-tag-missing-hyphen) The @param block should be followed by a parameter name and then a hyphen + // Warning: (tsdoc-param-tag-with-invalid-type) The @param block should not include a JSDoc-style '{type}' + // Warning: (tsdoc-param-tag-missing-hyphen) The @param block should be followed by a parameter name and then a hyphen + // Warning: (tsdoc-param-tag-with-invalid-type) The @param block should not include a JSDoc-style '{type}' + constructor(type: DocumentChangeType, document: QueryDocumentSnapshot, oldIndex: number, newIndex: number); + // Warning: (tsdoc-escape-right-brace) The "}" character should be escaped using a backslash to avoid confusion with a TSDoc inline tag + // Warning: (tsdoc-malformed-inline-tag) Expecting a TSDoc tag starting with "{@" + // Warning: (tsdoc-undefined-tag) The TSDoc tag "@type" is not defined in this configuration + // Warning: (tsdoc-undefined-tag) The TSDoc tag "@name" is not defined in this configuration + get doc(): QueryDocumentSnapshot; + // Warning: (tsdoc-param-tag-missing-hyphen) The @param block should be followed by a parameter name and then a hyphen + // Warning: (tsdoc-param-tag-with-invalid-type) The @param block should not include a JSDoc-style '{type}' + // Warning: (tsdoc-undefined-tag) The TSDoc tag "@return" is not defined in this configuration + isEqual(other: firestore.DocumentChange): boolean; + // Warning: (tsdoc-escape-right-brace) The "}" character should be escaped using a backslash to avoid confusion with a TSDoc inline tag + // Warning: (tsdoc-malformed-inline-tag) Expecting a TSDoc tag starting with "{@" + // Warning: (tsdoc-undefined-tag) The TSDoc tag "@type" is not defined in this configuration + // Warning: (tsdoc-undefined-tag) The TSDoc tag "@name" is not defined in this configuration + get newIndex(): number; + // Warning: (tsdoc-escape-right-brace) The "}" character should be escaped using a backslash to avoid confusion with a TSDoc inline tag + // Warning: (tsdoc-malformed-inline-tag) Expecting a TSDoc tag starting with "{@" + // Warning: (tsdoc-undefined-tag) The TSDoc tag "@type" is not defined in this configuration + // Warning: (tsdoc-undefined-tag) The TSDoc tag "@name" is not defined in this configuration + get oldIndex(): number; + // Warning: (tsdoc-escape-right-brace) The "}" character should be escaped using a backslash to avoid confusion with a TSDoc inline tag + // Warning: (tsdoc-malformed-inline-tag) Expecting a TSDoc tag starting with "{@" + // Warning: (tsdoc-undefined-tag) The TSDoc tag "@type" is not defined in this configuration + // Warning: (tsdoc-undefined-tag) The TSDoc tag "@name" is not defined in this configuration + get type(): DocumentChangeType; +} + +// @public (undocumented) +export type DocumentChangeType = 'added' | 'removed' | 'modified'; + +// Warning: (tsdoc-undefined-tag) The TSDoc tag "@return" is not defined in this configuration +// Warning: (tsdoc-undefined-tag) The TSDoc tag "@code" is not defined in this configuration +// +// @beta +function documentId(documentPath: string | firestore.DocumentReference): FunctionExpression; + +// Warning: (tsdoc-undefined-tag) The TSDoc tag "@return" is not defined in this configuration +// Warning: (tsdoc-undefined-tag) The TSDoc tag "@code" is not defined in this configuration +// +// @beta +function documentId(documentPathExpr: Expression): FunctionExpression; + // Warning: (tsdoc-undefined-tag) The TSDoc tag "@class" is not defined in this configuration // Warning: (ae-forgotten-export) The symbol "Serializable" needs to be exported by the entry point index.d.ts // @@ -474,9 +1107,7 @@ export class DocumentReference | string | firestore.FieldPath, ...preconditionOrValues: Array): Promise; // (undocumented) - withConverter(converter: null): DocumentReference; - // (undocumented) - withConverter(converter: firestore.FirestoreDataConverter): DocumentReference; + withConverter(converter: firestore.FirestoreDataConverter | null): DocumentReference; } // Warning: (tsdoc-undefined-tag) The TSDoc tag "@class" is not defined in this configuration @@ -578,6 +1209,162 @@ export class DocumentSnapshot): BooleanExpression; + +// Warning: (tsdoc-param-tag-missing-hyphen) The @param block should be followed by a parameter name and then a hyphen +// Warning: (tsdoc-param-tag-missing-hyphen) The @param block should be followed by a parameter name and then a hyphen +// Warning: (tsdoc-undefined-tag) The TSDoc tag "@return" is not defined in this configuration +// Warning: (tsdoc-undefined-tag) The TSDoc tag "@code" is not defined in this configuration +// +// @beta +function equalAny(expression: Expression, arrayExpression: Expression): BooleanExpression; + +// Warning: (tsdoc-param-tag-missing-hyphen) The @param block should be followed by a parameter name and then a hyphen +// Warning: (tsdoc-param-tag-missing-hyphen) The @param block should be followed by a parameter name and then a hyphen +// Warning: (tsdoc-undefined-tag) The TSDoc tag "@return" is not defined in this configuration +// Warning: (tsdoc-undefined-tag) The TSDoc tag "@code" is not defined in this configuration +// +// @beta +function equalAny(fieldName: string, values: Array): BooleanExpression; + +// Warning: (tsdoc-param-tag-missing-hyphen) The @param block should be followed by a parameter name and then a hyphen +// Warning: (tsdoc-param-tag-missing-hyphen) The @param block should be followed by a parameter name and then a hyphen +// Warning: (tsdoc-undefined-tag) The TSDoc tag "@return" is not defined in this configuration +// Warning: (tsdoc-undefined-tag) The TSDoc tag "@code" is not defined in this configuration +// +// @beta +function equalAny(fieldName: string, arrayExpression: Expression): BooleanExpression; + +// Warning: (tsdoc-param-tag-missing-hyphen) The @param block should be followed by a parameter name and then a hyphen +// Warning: (tsdoc-param-tag-missing-hyphen) The @param block should be followed by a parameter name and then a hyphen +// Warning: (tsdoc-undefined-tag) The TSDoc tag "@return" is not defined in this configuration +// Warning: (tsdoc-undefined-tag) The TSDoc tag "@code" is not defined in this configuration +// +// @beta +function euclideanDistance(fieldName: string, vector: number[] | VectorValue): FunctionExpression; + +// Warning: (tsdoc-param-tag-missing-hyphen) The @param block should be followed by a parameter name and then a hyphen +// Warning: (tsdoc-param-tag-missing-hyphen) The @param block should be followed by a parameter name and then a hyphen +// Warning: (tsdoc-undefined-tag) The TSDoc tag "@return" is not defined in this configuration +// Warning: (tsdoc-undefined-tag) The TSDoc tag "@code" is not defined in this configuration +// +// @beta +function euclideanDistance(fieldName: string, vectorExpression: Expression): FunctionExpression; + +// Warning: (tsdoc-param-tag-missing-hyphen) The @param block should be followed by a parameter name and then a hyphen +// Warning: (tsdoc-param-tag-missing-hyphen) The @param block should be followed by a parameter name and then a hyphen +// Warning: (tsdoc-undefined-tag) The TSDoc tag "@return" is not defined in this configuration +// Warning: (tsdoc-undefined-tag) The TSDoc tag "@code" is not defined in this configuration +// +// @beta +function euclideanDistance(vectorExpression: Expression, vector: number[] | VectorValue): FunctionExpression; + +// Warning: (tsdoc-param-tag-missing-hyphen) The @param block should be followed by a parameter name and then a hyphen +// Warning: (tsdoc-param-tag-missing-hyphen) The @param block should be followed by a parameter name and then a hyphen +// Warning: (tsdoc-undefined-tag) The TSDoc tag "@return" is not defined in this configuration +// Warning: (tsdoc-undefined-tag) The TSDoc tag "@code" is not defined in this configuration +// +// @beta +function euclideanDistance(vectorExpression: Expression, otherVectorExpression: Expression): FunctionExpression; + // Warning: (tsdoc-undefined-tag) The TSDoc tag "@class" is not defined in this configuration // // @public @@ -591,7 +1378,6 @@ export class ExecutionStats implements firestore.ExecutionStats { // (undocumented) readonly executionDuration: firestore.Duration; // Warning: (tsdoc-undefined-tag) The TSDoc tag "@private" is not defined in this configuration - // Warning: (ae-forgotten-export) The symbol "Serializer" needs to be exported by the entry point index.d.ts // // @internal (undocumented) static _fromProto(stats: IExecutionStats | null | undefined, serializer: Serializer): ExecutionStats | null; @@ -601,6 +1387,32 @@ export class ExecutionStats implements firestore.ExecutionStats { readonly resultsReturned: number; } +// Warning: (tsdoc-param-tag-missing-hyphen) The @param block should be followed by a parameter name and then a hyphen +// Warning: (tsdoc-undefined-tag) The TSDoc tag "@return" is not defined in this configuration +// Warning: (tsdoc-undefined-tag) The TSDoc tag "@code" is not defined in this configuration +// +// @beta +function exists(value: Expression): BooleanExpression; + +// Warning: (tsdoc-param-tag-missing-hyphen) The @param block should be followed by a parameter name and then a hyphen +// Warning: (tsdoc-undefined-tag) The TSDoc tag "@return" is not defined in this configuration +// Warning: (tsdoc-undefined-tag) The TSDoc tag "@code" is not defined in this configuration +// +// @beta +function exists(fieldName: string): BooleanExpression; + +// Warning: (tsdoc-undefined-tag) The TSDoc tag "@return" is not defined in this configuration +// Warning: (tsdoc-undefined-tag) The TSDoc tag "@code" is not defined in this configuration +// +// @beta +function exp(expression: Expression): FunctionExpression; + +// Warning: (tsdoc-undefined-tag) The TSDoc tag "@return" is not defined in this configuration +// Warning: (tsdoc-undefined-tag) The TSDoc tag "@code" is not defined in this configuration +// +// @beta +function exp(fieldName: string): FunctionExpression; + // Warning: (tsdoc-undefined-tag) The TSDoc tag "@class" is not defined in this configuration // // @public @@ -633,11 +1445,435 @@ export class ExplainResults implements firestore.ExplainResults { readonly snapshot: T | null; } -// Warning: (tsdoc-undefined-tag) The TSDoc tag "@class" is not defined in this configuration -// Warning: (ae-forgotten-export) The symbol "Path" needs to be exported by the entry point index.d.ts -// -// @public -export class FieldPath extends Path implements firestore.FieldPath { +// @beta +abstract class Expression implements firestore.Pipelines.Expression, HasUserData { + // Warning: (tsdoc-undefined-tag) The TSDoc tag "@return" is not defined in this configuration + // Warning: (tsdoc-undefined-tag) The TSDoc tag "@code" is not defined in this configuration + abs(): FunctionExpression; + // Warning: (tsdoc-param-tag-missing-hyphen) The @param block should be followed by a parameter name and then a hyphen + // Warning: (tsdoc-param-tag-missing-hyphen) The @param block should be followed by a parameter name and then a hyphen + // Warning: (tsdoc-undefined-tag) The TSDoc tag "@return" is not defined in this configuration + add(second: firestore.Pipelines.Expression | unknown, ...others: Array): FunctionExpression; + // Warning: (tsdoc-param-tag-missing-hyphen) The @param block should be followed by a parameter name and then a hyphen + // Warning: (tsdoc-param-tag-missing-hyphen) The @param block should be followed by a parameter name and then a hyphen + // Warning: (tsdoc-undefined-tag) The TSDoc tag "@return" is not defined in this configuration + arrayConcat(secondArray: Expression | unknown[], ...otherArrays: Array): FunctionExpression; + // Warning: (tsdoc-param-tag-missing-hyphen) The @param block should be followed by a parameter name and then a hyphen + // Warning: (tsdoc-undefined-tag) The TSDoc tag "@return" is not defined in this configuration + arrayContains(expression: Expression): BooleanExpression; + // Warning: (tsdoc-param-tag-missing-hyphen) The @param block should be followed by a parameter name and then a hyphen + // Warning: (tsdoc-undefined-tag) The TSDoc tag "@return" is not defined in this configuration + arrayContains(value: unknown): BooleanExpression; + // Warning: (tsdoc-param-tag-missing-hyphen) The @param block should be followed by a parameter name and then a hyphen + // Warning: (tsdoc-undefined-tag) The TSDoc tag "@return" is not defined in this configuration + arrayContainsAll(values: Array): BooleanExpression; + // Warning: (tsdoc-param-tag-missing-hyphen) The @param block should be followed by a parameter name and then a hyphen + // Warning: (tsdoc-undefined-tag) The TSDoc tag "@return" is not defined in this configuration + arrayContainsAll(arrayExpression: Expression): BooleanExpression; + // Warning: (tsdoc-param-tag-missing-hyphen) The @param block should be followed by a parameter name and then a hyphen + // Warning: (tsdoc-undefined-tag) The TSDoc tag "@return" is not defined in this configuration + arrayContainsAny(values: Array): BooleanExpression; + // Warning: (tsdoc-param-tag-missing-hyphen) The @param block should be followed by a parameter name and then a hyphen + // Warning: (tsdoc-undefined-tag) The TSDoc tag "@return" is not defined in this configuration + arrayContainsAny(arrayExpression: Expression): BooleanExpression; + // Warning: (tsdoc-param-tag-missing-hyphen) The @param block should be followed by a parameter name and then a hyphen + // Warning: (tsdoc-undefined-tag) The TSDoc tag "@return" is not defined in this configuration + arrayGet(index: number): FunctionExpression; + // Warning: (tsdoc-param-tag-missing-hyphen) The @param block should be followed by a parameter name and then a hyphen + // Warning: (tsdoc-undefined-tag) The TSDoc tag "@return" is not defined in this configuration + arrayGet(indexExpr: Expression): FunctionExpression; + // Warning: (tsdoc-undefined-tag) The TSDoc tag "@return" is not defined in this configuration + arrayLength(): FunctionExpression; + // Warning: (tsdoc-undefined-tag) The TSDoc tag "@return" is not defined in this configuration + // Warning: (tsdoc-undefined-tag) The TSDoc tag "@code" is not defined in this configuration + arrayReverse(): FunctionExpression; + // Warning: (tsdoc-undefined-tag) The TSDoc tag "@return" is not defined in this configuration + // Warning: (tsdoc-undefined-tag) The TSDoc tag "@code" is not defined in this configuration + arraySum(): FunctionExpression; + // Warning: (tsdoc-param-tag-missing-hyphen) The @param block should be followed by a parameter name and then a hyphen + // Warning: (tsdoc-undefined-tag) The TSDoc tag "@return" is not defined in this configuration + as(name: string): AliasedExpression; + // Warning: (tsdoc-undefined-tag) The TSDoc tag "@return" is not defined in this configuration + ascending(): Ordering; + // Warning: (tsdoc-undefined-tag) The TSDoc tag "@return" is not defined in this configuration + average(): AggregateFunction; + // Warning: (tsdoc-undefined-tag) The TSDoc tag "@return" is not defined in this configuration + // Warning: (tsdoc-undefined-tag) The TSDoc tag "@code" is not defined in this configuration + byteLength(): FunctionExpression; + // Warning: (tsdoc-undefined-tag) The TSDoc tag "@return" is not defined in this configuration + // Warning: (tsdoc-undefined-tag) The TSDoc tag "@code" is not defined in this configuration + ceil(): FunctionExpression; + // Warning: (tsdoc-undefined-tag) The TSDoc tag "@return" is not defined in this configuration + charLength(): FunctionExpression; + // Warning: (tsdoc-undefined-tag) The TSDoc tag "@return" is not defined in this configuration + // Warning: (tsdoc-undefined-tag) The TSDoc tag "@code" is not defined in this configuration + collectionId(): FunctionExpression; + // Warning: (tsdoc-param-tag-missing-hyphen) The @param block should be followed by a parameter name and then a hyphen + // Warning: (tsdoc-param-tag-missing-hyphen) The @param block should be followed by a parameter name and then a hyphen + // Warning: (tsdoc-undefined-tag) The TSDoc tag "@return" is not defined in this configuration + concat(second: Expression | unknown, ...others: Array): FunctionExpression; + // Warning: (tsdoc-param-tag-missing-hyphen) The @param block should be followed by a parameter name and then a hyphen + // Warning: (tsdoc-undefined-tag) The TSDoc tag "@return" is not defined in this configuration + cosineDistance(vectorExpression: Expression): FunctionExpression; + // Warning: (tsdoc-param-tag-missing-hyphen) The @param block should be followed by a parameter name and then a hyphen + // Warning: (tsdoc-undefined-tag) The TSDoc tag "@return" is not defined in this configuration + cosineDistance(vector: firestore.VectorValue | number[]): FunctionExpression; + // Warning: (tsdoc-undefined-tag) The TSDoc tag "@return" is not defined in this configuration + count(): AggregateFunction; + // Warning: (tsdoc-undefined-tag) The TSDoc tag "@return" is not defined in this configuration + countDistinct(): AggregateFunction; + // Warning: (tsdoc-undefined-tag) The TSDoc tag "@private" is not defined in this configuration + _createdFromLiteral: boolean; + // Warning: (tsdoc-undefined-tag) The TSDoc tag "@return" is not defined in this configuration + descending(): Ordering; + // Warning: (tsdoc-param-tag-missing-hyphen) The @param block should be followed by a parameter name and then a hyphen + // Warning: (tsdoc-undefined-tag) The TSDoc tag "@return" is not defined in this configuration + divide(divisor: Expression): FunctionExpression; + // Warning: (tsdoc-param-tag-missing-hyphen) The @param block should be followed by a parameter name and then a hyphen + // Warning: (tsdoc-undefined-tag) The TSDoc tag "@return" is not defined in this configuration + divide(divisor: number): FunctionExpression; + // Warning: (tsdoc-undefined-tag) The TSDoc tag "@return" is not defined in this configuration + // Warning: (tsdoc-undefined-tag) The TSDoc tag "@code" is not defined in this configuration + documentId(): FunctionExpression; + // Warning: (tsdoc-param-tag-missing-hyphen) The @param block should be followed by a parameter name and then a hyphen + // Warning: (tsdoc-undefined-tag) The TSDoc tag "@return" is not defined in this configuration + dotProduct(vectorExpression: Expression): FunctionExpression; + // Warning: (tsdoc-param-tag-missing-hyphen) The @param block should be followed by a parameter name and then a hyphen + // Warning: (tsdoc-undefined-tag) The TSDoc tag "@return" is not defined in this configuration + dotProduct(vector: firestore.VectorValue | number[]): FunctionExpression; + // Warning: (tsdoc-param-tag-missing-hyphen) The @param block should be followed by a parameter name and then a hyphen + // Warning: (tsdoc-undefined-tag) The TSDoc tag "@return" is not defined in this configuration + endsWith(suffix: string): BooleanExpression; + // Warning: (tsdoc-param-tag-missing-hyphen) The @param block should be followed by a parameter name and then a hyphen + // Warning: (tsdoc-undefined-tag) The TSDoc tag "@return" is not defined in this configuration + endsWith(suffix: Expression): BooleanExpression; + // Warning: (tsdoc-param-tag-missing-hyphen) The @param block should be followed by a parameter name and then a hyphen + // Warning: (tsdoc-undefined-tag) The TSDoc tag "@return" is not defined in this configuration + equal(expression: Expression): BooleanExpression; + // Warning: (tsdoc-param-tag-missing-hyphen) The @param block should be followed by a parameter name and then a hyphen + // Warning: (tsdoc-undefined-tag) The TSDoc tag "@return" is not defined in this configuration + equal(value: unknown): BooleanExpression; + // Warning: (tsdoc-param-tag-missing-hyphen) The @param block should be followed by a parameter name and then a hyphen + // Warning: (tsdoc-undefined-tag) The TSDoc tag "@return" is not defined in this configuration + equalAny(values: Array): BooleanExpression; + // Warning: (tsdoc-param-tag-missing-hyphen) The @param block should be followed by a parameter name and then a hyphen + // Warning: (tsdoc-undefined-tag) The TSDoc tag "@return" is not defined in this configuration + equalAny(arrayExpression: Expression): BooleanExpression; + // Warning: (tsdoc-param-tag-missing-hyphen) The @param block should be followed by a parameter name and then a hyphen + // Warning: (tsdoc-undefined-tag) The TSDoc tag "@return" is not defined in this configuration + euclideanDistance(vectorExpression: Expression): FunctionExpression; + // Warning: (tsdoc-param-tag-missing-hyphen) The @param block should be followed by a parameter name and then a hyphen + // Warning: (tsdoc-undefined-tag) The TSDoc tag "@return" is not defined in this configuration + euclideanDistance(vector: firestore.VectorValue | number[]): FunctionExpression; + // Warning: (tsdoc-undefined-tag) The TSDoc tag "@return" is not defined in this configuration + exists(): BooleanExpression; + // Warning: (tsdoc-undefined-tag) The TSDoc tag "@return" is not defined in this configuration + // Warning: (tsdoc-undefined-tag) The TSDoc tag "@code" is not defined in this configuration + exp(): FunctionExpression; + // (undocumented) + abstract expressionType: firestore.Pipelines.ExpressionType; + // Warning: (tsdoc-undefined-tag) The TSDoc tag "@return" is not defined in this configuration + // Warning: (tsdoc-undefined-tag) The TSDoc tag "@code" is not defined in this configuration + floor(): FunctionExpression; + // Warning: (tsdoc-param-tag-missing-hyphen) The @param block should be followed by a parameter name and then a hyphen + // Warning: (tsdoc-undefined-tag) The TSDoc tag "@return" is not defined in this configuration + greaterThan(expression: Expression): BooleanExpression; + // Warning: (tsdoc-param-tag-missing-hyphen) The @param block should be followed by a parameter name and then a hyphen + // Warning: (tsdoc-undefined-tag) The TSDoc tag "@return" is not defined in this configuration + greaterThan(value: unknown): BooleanExpression; + // Warning: (tsdoc-param-tag-missing-hyphen) The @param block should be followed by a parameter name and then a hyphen + // Warning: (tsdoc-undefined-tag) The TSDoc tag "@return" is not defined in this configuration + greaterThanOrEqual(expression: Expression): BooleanExpression; + // Warning: (tsdoc-param-tag-missing-hyphen) The @param block should be followed by a parameter name and then a hyphen + // Warning: (tsdoc-undefined-tag) The TSDoc tag "@return" is not defined in this configuration + greaterThanOrEqual(value: unknown): BooleanExpression; + // Warning: (tsdoc-param-tag-missing-hyphen) The @param block should be followed by a parameter name and then a hyphen + // Warning: (tsdoc-undefined-tag) The TSDoc tag "@return" is not defined in this configuration + ifAbsent(elseValue: unknown): Expression; + // Warning: (tsdoc-param-tag-missing-hyphen) The @param block should be followed by a parameter name and then a hyphen + // Warning: (tsdoc-undefined-tag) The TSDoc tag "@return" is not defined in this configuration + ifAbsent(elseExpression: unknown): Expression; + // Warning: (tsdoc-param-tag-missing-hyphen) The @param block should be followed by a parameter name and then a hyphen + // Warning: (tsdoc-undefined-tag) The TSDoc tag "@return" is not defined in this configuration + // Warning: (tsdoc-undefined-tag) The TSDoc tag "@code" is not defined in this configuration + ifError(catchExpr: Expression): FunctionExpression; + // Warning: (tsdoc-param-tag-missing-hyphen) The @param block should be followed by a parameter name and then a hyphen + // Warning: (tsdoc-undefined-tag) The TSDoc tag "@return" is not defined in this configuration + // Warning: (tsdoc-undefined-tag) The TSDoc tag "@code" is not defined in this configuration + ifError(catchValue: unknown): FunctionExpression; + // Warning: (tsdoc-undefined-tag) The TSDoc tag "@return" is not defined in this configuration + // Warning: (tsdoc-undefined-tag) The TSDoc tag "@code" is not defined in this configuration + isAbsent(): BooleanExpression; + // Warning: (tsdoc-undefined-tag) The TSDoc tag "@return" is not defined in this configuration + // Warning: (tsdoc-undefined-tag) The TSDoc tag "@code" is not defined in this configuration + isError(): BooleanExpression; + // Warning: (tsdoc-param-tag-missing-hyphen) The @param block should be followed by a parameter name and then a hyphen + // Warning: (tsdoc-undefined-tag) The TSDoc tag "@return" is not defined in this configuration + join(delimiterExpression: Expression): Expression; + // Warning: (tsdoc-param-tag-missing-hyphen) The @param block should be followed by a parameter name and then a hyphen + // Warning: (tsdoc-undefined-tag) The TSDoc tag "@return" is not defined in this configuration + join(delimiter: string): Expression; + // Warning: (tsdoc-undefined-tag) The TSDoc tag "@return" is not defined in this configuration + length(): FunctionExpression; + // Warning: (tsdoc-param-tag-missing-hyphen) The @param block should be followed by a parameter name and then a hyphen + // Warning: (tsdoc-undefined-tag) The TSDoc tag "@return" is not defined in this configuration + lessThan(experession: Expression): BooleanExpression; + // Warning: (tsdoc-param-tag-missing-hyphen) The @param block should be followed by a parameter name and then a hyphen + // Warning: (tsdoc-undefined-tag) The TSDoc tag "@return" is not defined in this configuration + lessThan(value: unknown): BooleanExpression; + // Warning: (tsdoc-param-tag-missing-hyphen) The @param block should be followed by a parameter name and then a hyphen + // Warning: (tsdoc-undefined-tag) The TSDoc tag "@return" is not defined in this configuration + lessThanOrEqual(expression: Expression): BooleanExpression; + // Warning: (tsdoc-param-tag-missing-hyphen) The @param block should be followed by a parameter name and then a hyphen + // Warning: (tsdoc-undefined-tag) The TSDoc tag "@return" is not defined in this configuration + lessThanOrEqual(value: unknown): BooleanExpression; + // Warning: (tsdoc-param-tag-missing-hyphen) The @param block should be followed by a parameter name and then a hyphen + // Warning: (tsdoc-undefined-tag) The TSDoc tag "@return" is not defined in this configuration + like(pattern: string): FunctionExpression; + // Warning: (tsdoc-param-tag-missing-hyphen) The @param block should be followed by a parameter name and then a hyphen + // Warning: (tsdoc-undefined-tag) The TSDoc tag "@return" is not defined in this configuration + like(pattern: Expression): FunctionExpression; + // Warning: (tsdoc-undefined-tag) The TSDoc tag "@return" is not defined in this configuration + // Warning: (tsdoc-undefined-tag) The TSDoc tag "@code" is not defined in this configuration + ln(): FunctionExpression; + // Warning: (tsdoc-undefined-tag) The TSDoc tag "@return" is not defined in this configuration + // Warning: (tsdoc-undefined-tag) The TSDoc tag "@code" is not defined in this configuration + log10(): FunctionExpression; + // Warning: (tsdoc-param-tag-missing-hyphen) The @param block should be followed by a parameter name and then a hyphen + // Warning: (tsdoc-param-tag-missing-hyphen) The @param block should be followed by a parameter name and then a hyphen + // Warning: (tsdoc-undefined-tag) The TSDoc tag "@return" is not defined in this configuration + // Warning: (tsdoc-undefined-tag) The TSDoc tag "@code" is not defined in this configuration + logicalMaximum(second: Expression | unknown, ...others: Array): FunctionExpression; + // Warning: (tsdoc-param-tag-missing-hyphen) The @param block should be followed by a parameter name and then a hyphen + // Warning: (tsdoc-param-tag-missing-hyphen) The @param block should be followed by a parameter name and then a hyphen + // Warning: (tsdoc-undefined-tag) The TSDoc tag "@return" is not defined in this configuration + // Warning: (tsdoc-undefined-tag) The TSDoc tag "@code" is not defined in this configuration + logicalMinimum(second: Expression | unknown, ...others: Array): FunctionExpression; + // Warning: (tsdoc-param-tag-missing-hyphen) The @param block should be followed by a parameter name and then a hyphen + // Warning: (tsdoc-undefined-tag) The TSDoc tag "@return" is not defined in this configuration + mapGet(subfield: string): FunctionExpression; + // Warning: (tsdoc-param-tag-missing-hyphen) The @param block should be followed by a parameter name and then a hyphen + // Warning: (tsdoc-param-tag-missing-hyphen) The @param block should be followed by a parameter name and then a hyphen + // Warning: (tsdoc-undefined-tag) The TSDoc tag "@code" is not defined in this configuration + mapMerge(secondMap: Record | Expression, ...otherMaps: Array | Expression>): FunctionExpression; + // Warning: (tsdoc-param-tag-missing-hyphen) The @param block should be followed by a parameter name and then a hyphen + // Warning: (tsdoc-undefined-tag) The TSDoc tag "@code" is not defined in this configuration + mapRemove(key: string): FunctionExpression; + // Warning: (tsdoc-param-tag-missing-hyphen) The @param block should be followed by a parameter name and then a hyphen + // Warning: (tsdoc-undefined-tag) The TSDoc tag "@code" is not defined in this configuration + mapRemove(keyExpr: Expression): FunctionExpression; + // Warning: (tsdoc-undefined-tag) The TSDoc tag "@return" is not defined in this configuration + maximum(): AggregateFunction; + // Warning: (tsdoc-undefined-tag) The TSDoc tag "@return" is not defined in this configuration + minimum(): AggregateFunction; + // Warning: (tsdoc-param-tag-missing-hyphen) The @param block should be followed by a parameter name and then a hyphen + // Warning: (tsdoc-undefined-tag) The TSDoc tag "@return" is not defined in this configuration + mod(expression: Expression): FunctionExpression; + // Warning: (tsdoc-param-tag-missing-hyphen) The @param block should be followed by a parameter name and then a hyphen + // Warning: (tsdoc-undefined-tag) The TSDoc tag "@return" is not defined in this configuration + mod(value: number): FunctionExpression; + // Warning: (tsdoc-param-tag-missing-hyphen) The @param block should be followed by a parameter name and then a hyphen + // Warning: (tsdoc-param-tag-missing-hyphen) The @param block should be followed by a parameter name and then a hyphen + // Warning: (tsdoc-undefined-tag) The TSDoc tag "@return" is not defined in this configuration + multiply(second: Expression | number, ...others: Array): FunctionExpression; + // Warning: (tsdoc-param-tag-missing-hyphen) The @param block should be followed by a parameter name and then a hyphen + // Warning: (tsdoc-undefined-tag) The TSDoc tag "@return" is not defined in this configuration + notEqual(expression: Expression): BooleanExpression; + // Warning: (tsdoc-param-tag-missing-hyphen) The @param block should be followed by a parameter name and then a hyphen + // Warning: (tsdoc-undefined-tag) The TSDoc tag "@return" is not defined in this configuration + notEqual(value: unknown): BooleanExpression; + // Warning: (tsdoc-param-tag-missing-hyphen) The @param block should be followed by a parameter name and then a hyphen + // Warning: (tsdoc-undefined-tag) The TSDoc tag "@return" is not defined in this configuration + notEqualAny(values: Array): BooleanExpression; + // Warning: (tsdoc-param-tag-missing-hyphen) The @param block should be followed by a parameter name and then a hyphen + // Warning: (tsdoc-undefined-tag) The TSDoc tag "@return" is not defined in this configuration + notEqualAny(arrayExpression: Expression): BooleanExpression; + // Warning: (tsdoc-param-tag-missing-hyphen) The @param block should be followed by a parameter name and then a hyphen + // Warning: (tsdoc-undefined-tag) The TSDoc tag "@return" is not defined in this configuration + pow(exponent: Expression): FunctionExpression; + // Warning: (tsdoc-param-tag-missing-hyphen) The @param block should be followed by a parameter name and then a hyphen + // Warning: (tsdoc-undefined-tag) The TSDoc tag "@return" is not defined in this configuration + pow(exponent: number): FunctionExpression; + // (undocumented) + _protoValueType: "ProtoValue"; + // Warning: (tsdoc-param-tag-missing-hyphen) The @param block should be followed by a parameter name and then a hyphen + // Warning: (tsdoc-undefined-tag) The TSDoc tag "@return" is not defined in this configuration + regexContains(pattern: string): BooleanExpression; + // Warning: (tsdoc-param-tag-missing-hyphen) The @param block should be followed by a parameter name and then a hyphen + // Warning: (tsdoc-undefined-tag) The TSDoc tag "@return" is not defined in this configuration + regexContains(pattern: Expression): BooleanExpression; + // Warning: (tsdoc-param-tag-missing-hyphen) The @param block should be followed by a parameter name and then a hyphen + // Warning: (tsdoc-undefined-tag) The TSDoc tag "@return" is not defined in this configuration + regexMatch(pattern: string): BooleanExpression; + // Warning: (tsdoc-param-tag-missing-hyphen) The @param block should be followed by a parameter name and then a hyphen + // Warning: (tsdoc-undefined-tag) The TSDoc tag "@return" is not defined in this configuration + regexMatch(pattern: Expression): BooleanExpression; + // Warning: (tsdoc-undefined-tag) The TSDoc tag "@return" is not defined in this configuration + // Warning: (tsdoc-undefined-tag) The TSDoc tag "@code" is not defined in this configuration + reverse(): FunctionExpression; + // Warning: (tsdoc-undefined-tag) The TSDoc tag "@return" is not defined in this configuration + round(): FunctionExpression; + // Warning: (tsdoc-param-tag-missing-hyphen) The @param block should be followed by a parameter name and then a hyphen + // Warning: (tsdoc-undefined-tag) The TSDoc tag "@return" is not defined in this configuration + round(decimalPlaces: number): FunctionExpression; + // Warning: (tsdoc-param-tag-missing-hyphen) The @param block should be followed by a parameter name and then a hyphen + // Warning: (tsdoc-undefined-tag) The TSDoc tag "@return" is not defined in this configuration + round(decimalPlaces: Expression): FunctionExpression; + // Warning: (tsdoc-undefined-tag) The TSDoc tag "@return" is not defined in this configuration + // Warning: (tsdoc-undefined-tag) The TSDoc tag "@code" is not defined in this configuration + split(delimiter: string): FunctionExpression; + // Warning: (tsdoc-undefined-tag) The TSDoc tag "@return" is not defined in this configuration + // Warning: (tsdoc-undefined-tag) The TSDoc tag "@code" is not defined in this configuration + split(delimiter: Expression): FunctionExpression; + // Warning: (tsdoc-undefined-tag) The TSDoc tag "@return" is not defined in this configuration + // Warning: (tsdoc-undefined-tag) The TSDoc tag "@code" is not defined in this configuration + sqrt(): FunctionExpression; + // Warning: (tsdoc-param-tag-missing-hyphen) The @param block should be followed by a parameter name and then a hyphen + // Warning: (tsdoc-undefined-tag) The TSDoc tag "@return" is not defined in this configuration + startsWith(prefix: string): BooleanExpression; + // Warning: (tsdoc-param-tag-missing-hyphen) The @param block should be followed by a parameter name and then a hyphen + // Warning: (tsdoc-undefined-tag) The TSDoc tag "@return" is not defined in this configuration + startsWith(prefix: Expression): BooleanExpression; + // Warning: (tsdoc-param-tag-missing-hyphen) The @param block should be followed by a parameter name and then a hyphen + // Warning: (tsdoc-param-tag-missing-hyphen) The @param block should be followed by a parameter name and then a hyphen + // Warning: (tsdoc-undefined-tag) The TSDoc tag "@return" is not defined in this configuration + stringConcat(secondString: Expression | string, ...otherStrings: Array): FunctionExpression; + // Warning: (tsdoc-param-tag-missing-hyphen) The @param block should be followed by a parameter name and then a hyphen + // Warning: (tsdoc-undefined-tag) The TSDoc tag "@return" is not defined in this configuration + stringContains(substring: string): BooleanExpression; + // Warning: (tsdoc-param-tag-missing-hyphen) The @param block should be followed by a parameter name and then a hyphen + // Warning: (tsdoc-undefined-tag) The TSDoc tag "@return" is not defined in this configuration + stringContains(expr: Expression): BooleanExpression; + // Warning: (tsdoc-undefined-tag) The TSDoc tag "@return" is not defined in this configuration + // Warning: (tsdoc-undefined-tag) The TSDoc tag "@code" is not defined in this configuration + stringReverse(): FunctionExpression; + // Warning: (tsdoc-param-tag-missing-hyphen) The @param block should be followed by a parameter name and then a hyphen + // Warning: (tsdoc-param-tag-missing-hyphen) The @param block should be followed by a parameter name and then a hyphen + substring(position: number, length?: number): FunctionExpression; + // Warning: (tsdoc-param-tag-missing-hyphen) The @param block should be followed by a parameter name and then a hyphen + // Warning: (tsdoc-param-tag-missing-hyphen) The @param block should be followed by a parameter name and then a hyphen + substring(position: Expression, length?: Expression): FunctionExpression; + // Warning: (tsdoc-param-tag-missing-hyphen) The @param block should be followed by a parameter name and then a hyphen + // Warning: (tsdoc-undefined-tag) The TSDoc tag "@return" is not defined in this configuration + subtract(subtrahend: firestore.Pipelines.Expression): FunctionExpression; + // Warning: (tsdoc-param-tag-missing-hyphen) The @param block should be followed by a parameter name and then a hyphen + // Warning: (tsdoc-undefined-tag) The TSDoc tag "@return" is not defined in this configuration + subtract(subtrahend: number): FunctionExpression; + // Warning: (tsdoc-undefined-tag) The TSDoc tag "@return" is not defined in this configuration + sum(): AggregateFunction; + // Warning: (tsdoc-param-tag-missing-hyphen) The @param block should be followed by a parameter name and then a hyphen + // Warning: (tsdoc-param-tag-missing-hyphen) The @param block should be followed by a parameter name and then a hyphen + // Warning: (tsdoc-undefined-tag) The TSDoc tag "@return" is not defined in this configuration + // Warning: (tsdoc-undefined-tag) The TSDoc tag "@code" is not defined in this configuration + timestampAdd(unit: Expression, amount: Expression): FunctionExpression; + // Warning: (tsdoc-param-tag-missing-hyphen) The @param block should be followed by a parameter name and then a hyphen + // Warning: (tsdoc-param-tag-missing-hyphen) The @param block should be followed by a parameter name and then a hyphen + // Warning: (tsdoc-undefined-tag) The TSDoc tag "@return" is not defined in this configuration + // Warning: (tsdoc-undefined-tag) The TSDoc tag "@code" is not defined in this configuration + timestampAdd(unit: 'microsecond' | 'millisecond' | 'second' | 'minute' | 'hour' | 'day', amount: number): FunctionExpression; + // Warning: (tsdoc-param-tag-missing-hyphen) The @param block should be followed by a parameter name and then a hyphen + // Warning: (tsdoc-param-tag-missing-hyphen) The @param block should be followed by a parameter name and then a hyphen + // Warning: (tsdoc-undefined-tag) The TSDoc tag "@return" is not defined in this configuration + // Warning: (tsdoc-undefined-tag) The TSDoc tag "@code" is not defined in this configuration + timestampSubtract(unit: Expression, amount: Expression): FunctionExpression; + // Warning: (tsdoc-param-tag-missing-hyphen) The @param block should be followed by a parameter name and then a hyphen + // Warning: (tsdoc-param-tag-missing-hyphen) The @param block should be followed by a parameter name and then a hyphen + // Warning: (tsdoc-undefined-tag) The TSDoc tag "@return" is not defined in this configuration + // Warning: (tsdoc-undefined-tag) The TSDoc tag "@code" is not defined in this configuration + timestampSubtract(unit: 'microsecond' | 'millisecond' | 'second' | 'minute' | 'hour' | 'day', amount: number): FunctionExpression; + // Warning: (tsdoc-undefined-tag) The TSDoc tag "@return" is not defined in this configuration + // Warning: (tsdoc-undefined-tag) The TSDoc tag "@code" is not defined in this configuration + timestampToUnixMicros(): FunctionExpression; + // Warning: (tsdoc-undefined-tag) The TSDoc tag "@return" is not defined in this configuration + // Warning: (tsdoc-undefined-tag) The TSDoc tag "@code" is not defined in this configuration + timestampToUnixMillis(): FunctionExpression; + // Warning: (tsdoc-undefined-tag) The TSDoc tag "@return" is not defined in this configuration + // Warning: (tsdoc-undefined-tag) The TSDoc tag "@code" is not defined in this configuration + timestampToUnixSeconds(): FunctionExpression; + // Warning: (tsdoc-param-tag-missing-hyphen) The @param block should be followed by a parameter name and then a hyphen + // Warning: (tsdoc-param-tag-missing-hyphen) The @param block should be followed by a parameter name and then a hyphen + // Warning: (tsdoc-escape-right-brace) The "}" character should be escaped using a backslash to avoid confusion with a TSDoc inline tag + // Warning: (tsdoc-malformed-inline-tag) Expecting a TSDoc tag starting with "{@" + // Warning: (tsdoc-undefined-tag) The TSDoc tag "@return" is not defined in this configuration + timestampTruncate(granularity: firestore.Pipelines.TimeGranularity, timezone?: string | Expression): FunctionExpression; + // Warning: (tsdoc-param-tag-missing-hyphen) The @param block should be followed by a parameter name and then a hyphen + // Warning: (tsdoc-param-tag-missing-hyphen) The @param block should be followed by a parameter name and then a hyphen + // Warning: (tsdoc-escape-right-brace) The "}" character should be escaped using a backslash to avoid confusion with a TSDoc inline tag + // Warning: (tsdoc-malformed-inline-tag) Expecting a TSDoc tag starting with "{@" + // Warning: (tsdoc-undefined-tag) The TSDoc tag "@return" is not defined in this configuration + timestampTruncate(granularity: Expression, timezone?: string | Expression): FunctionExpression; + // Warning: (tsdoc-undefined-tag) The TSDoc tag "@return" is not defined in this configuration + toLower(): FunctionExpression; + // Warning: (tsdoc-undefined-tag) The TSDoc tag "@private" is not defined in this configuration + // + // (undocumented) + abstract _toProto(serializer: Serializer): api.IValue; + // Warning: (tsdoc-undefined-tag) The TSDoc tag "@return" is not defined in this configuration + toUpper(): FunctionExpression; + // Warning: (tsdoc-param-tag-missing-hyphen) The @param block should be followed by a parameter name and then a hyphen + // Warning: (tsdoc-undefined-tag) The TSDoc tag "@return" is not defined in this configuration + trim(valueToTrim?: string | Expression | Uint8Array | Buffer): FunctionExpression; + // Warning: (tsdoc-escape-right-brace) The "}" character should be escaped using a backslash to avoid confusion with a TSDoc inline tag + // Warning: (tsdoc-malformed-inline-tag) Expecting a TSDoc tag starting with "{@" + // Warning: (tsdoc-undefined-tag) The TSDoc tag "@return" is not defined in this configuration + type(): FunctionExpression; + // Warning: (tsdoc-undefined-tag) The TSDoc tag "@return" is not defined in this configuration + // Warning: (tsdoc-undefined-tag) The TSDoc tag "@code" is not defined in this configuration + unixMicrosToTimestamp(): FunctionExpression; + // Warning: (tsdoc-undefined-tag) The TSDoc tag "@return" is not defined in this configuration + // Warning: (tsdoc-undefined-tag) The TSDoc tag "@code" is not defined in this configuration + unixMillisToTimestamp(): FunctionExpression; + // Warning: (tsdoc-undefined-tag) The TSDoc tag "@return" is not defined in this configuration + // Warning: (tsdoc-undefined-tag) The TSDoc tag "@code" is not defined in this configuration + unixSecondsToTimestamp(): FunctionExpression; + // Warning: (tsdoc-undefined-tag) The TSDoc tag "@private" is not defined in this configuration + // + // (undocumented) + abstract _validateUserData(ignoreUndefinedProperties: boolean): void; + // Warning: (tsdoc-undefined-tag) The TSDoc tag "@return" is not defined in this configuration + // Warning: (tsdoc-undefined-tag) The TSDoc tag "@code" is not defined in this configuration + vectorLength(): FunctionExpression; +} + +// @beta +class Field extends Expression implements firestore.Pipelines.Selectable { + // Warning: (tsdoc-undefined-tag) The TSDoc tag "@private" is not defined in this configuration + // Warning: (tsdoc-undefined-tag) The TSDoc tag "@hideconstructor" is not defined in this configuration + // Warning: (tsdoc-param-tag-missing-hyphen) The @param block should be followed by a parameter name and then a hyphen + constructor(fieldPath: FieldPath); + // (undocumented) + get _alias(): string; + // (undocumented) + get _expr(): Expression; + // (undocumented) + readonly expressionType: firestore.Pipelines.ExpressionType; + // (undocumented) + get fieldName(): string; + // (undocumented) + selectable: true; + // Warning: (tsdoc-undefined-tag) The TSDoc tag "@private" is not defined in this configuration + // + // (undocumented) + _toProto(_: Serializer): api.IValue; + // Warning: (tsdoc-undefined-tag) The TSDoc tag "@private" is not defined in this configuration + // + // (undocumented) + _validateUserData(_: boolean): void; +} + +// Warning: (tsdoc-undefined-tag) The TSDoc tag "@code" is not defined in this configuration +// Warning: (tsdoc-param-tag-missing-hyphen) The @param block should be followed by a parameter name and then a hyphen +// Warning: (tsdoc-undefined-tag) The TSDoc tag "@return" is not defined in this configuration +// Warning: (tsdoc-undefined-tag) The TSDoc tag "@code" is not defined in this configuration +// +// @beta +function field(field: string | firestore.FieldPath): Field; + +// Warning: (tsdoc-undefined-tag) The TSDoc tag "@class" is not defined in this configuration +// Warning: (ae-forgotten-export) The symbol "Path" needs to be exported by the entry point index.d.ts +// +// @public +export class FieldPath extends Path implements firestore.FieldPath { // Warning: (tsdoc-param-tag-missing-hyphen) The @param block should be followed by a parameter name and then a hyphen // Warning: (tsdoc-param-tag-with-invalid-type) The @param block should not include a JSDoc-style '{type}' constructor(...segments: string[]); @@ -653,6 +1889,12 @@ export class FieldPath extends Path implements firestore.FieldPath { // Warning: (tsdoc-escape-right-brace) The "}" character should be escaped using a backslash to avoid confusion with a TSDoc inline tag // Warning: (tsdoc-malformed-inline-tag) Expecting a TSDoc tag starting with "{@" // + // @internal + static _emptyPath(): FieldPath; + // Warning: (tsdoc-undefined-tag) The TSDoc tag "@private" is not defined in this configuration + // Warning: (tsdoc-escape-right-brace) The "}" character should be escaped using a backslash to avoid confusion with a TSDoc inline tag + // Warning: (tsdoc-malformed-inline-tag) Expecting a TSDoc tag starting with "{@" + // // @internal @override get formattedName(): string; // Warning: (tsdoc-undefined-tag) The TSDoc tag "@private" is not defined in this configuration @@ -670,8 +1912,12 @@ export class FieldPath extends Path implements firestore.FieldPath { // Warning: (tsdoc-undefined-tag) The TSDoc tag "@return" is not defined in this configuration isEqual(other: FieldPath): boolean; // Warning: (tsdoc-undefined-tag) The TSDoc tag "@private" is not defined in this configuration - // Warning: (tsdoc-param-tag-missing-hyphen) The @param block should be followed by a parameter name and then a hyphen - // Warning: (tsdoc-param-tag-with-invalid-type) The @param block should not include a JSDoc-style '{type}' + // + // @internal + get _minNumSegments(): number; + // Warning: (tsdoc-undefined-tag) The TSDoc tag "@private" is not defined in this configuration + // Warning: (tsdoc-param-tag-missing-hyphen) The @param block should be followed by a parameter name and then a hyphen + // Warning: (tsdoc-param-tag-with-invalid-type) The @param block should not include a JSDoc-style '{type}' // Warning: (tsdoc-escape-right-brace) The "}" character should be escaped using a backslash to avoid confusion with a TSDoc inline tag // Warning: (tsdoc-malformed-inline-tag) Expecting a TSDoc tag starting with "{@" // @@ -728,263 +1974,1217 @@ export class FieldValue implements firestore.FieldValue { // @public export abstract class Filter { // Warning: (tsdoc-param-tag-missing-hyphen) The @param block should be followed by a parameter name and then a hyphen - // Warning: (tsdoc-param-tag-with-invalid-type) The @param block should not include a JSDoc-style '{type}' - // Warning: (tsdoc-escape-right-brace) The "}" character should be escaped using a backslash to avoid confusion with a TSDoc inline tag - // Warning: (tsdoc-malformed-inline-tag) Expecting a TSDoc tag starting with "{@" - static and(...filters: Filter[]): Filter; + // Warning: (tsdoc-param-tag-with-invalid-type) The @param block should not include a JSDoc-style '{type}' + // Warning: (tsdoc-escape-right-brace) The "}" character should be escaped using a backslash to avoid confusion with a TSDoc inline tag + // Warning: (tsdoc-malformed-inline-tag) Expecting a TSDoc tag starting with "{@" + static and(...filters: Filter[]): Filter; + // Warning: (tsdoc-param-tag-missing-hyphen) The @param block should be followed by a parameter name and then a hyphen + // Warning: (tsdoc-param-tag-with-invalid-type) The @param block should not include a JSDoc-style '{type}' + // Warning: (tsdoc-escape-right-brace) The "}" character should be escaped using a backslash to avoid confusion with a TSDoc inline tag + // Warning: (tsdoc-malformed-inline-tag) Expecting a TSDoc tag starting with "{@" + static or(...filters: Filter[]): Filter; + // Warning: (tsdoc-param-tag-missing-hyphen) The @param block should be followed by a parameter name and then a hyphen + // Warning: (tsdoc-param-tag-with-invalid-type) The @param block should not include a JSDoc-style '{type}' + // Warning: (tsdoc-param-tag-missing-hyphen) The @param block should be followed by a parameter name and then a hyphen + // Warning: (tsdoc-param-tag-with-invalid-type) The @param block should not include a JSDoc-style '{type}' + // Warning: (tsdoc-param-tag-missing-hyphen) The @param block should be followed by a parameter name and then a hyphen + // Warning: (tsdoc-param-tag-with-invalid-type) The @param block should not include a JSDoc-style '{type}' + // Warning: (tsdoc-escape-right-brace) The "}" character should be escaped using a backslash to avoid confusion with a TSDoc inline tag + // Warning: (tsdoc-malformed-inline-tag) Expecting a TSDoc tag starting with "{@" + static where(fieldPath: string | firestore.FieldPath, opStr: firestore.WhereFilterOp, value: unknown): Filter; +} + +// Warning: (tsdoc-undefined-tag) The TSDoc tag "@class" is not defined in this configuration +// +// @public +class Firestore implements firestore.Firestore { + // Warning: (tsdoc-param-tag-missing-hyphen) The @param block should be followed by a parameter name and then a hyphen + // Warning: (tsdoc-param-tag-with-invalid-type) The @param block should not include a JSDoc-style '{type}' + // Warning: (tsdoc-escape-right-brace) The "}" character should be escaped using a backslash to avoid confusion with a TSDoc inline tag + // Warning: (tsdoc-malformed-inline-tag) Expecting a TSDoc tag starting with "{@" + // Warning: (tsdoc-param-tag-with-invalid-name) The @param block should be followed by a valid parameter name: The identifier cannot non-word characters + // Warning: (tsdoc-param-tag-with-invalid-type) The @param block should not include a JSDoc-style '{type}' + // Warning: (tsdoc-escape-right-brace) The "}" character should be escaped using a backslash to avoid confusion with a TSDoc inline tag + // Warning: (tsdoc-malformed-inline-tag) Expecting a TSDoc tag starting with "{@" + // Warning: (tsdoc-param-tag-with-invalid-name) The @param block should be followed by a valid parameter name: The identifier cannot non-word characters + // Warning: (tsdoc-param-tag-with-invalid-type) The @param block should not include a JSDoc-style '{type}' + // Warning: (tsdoc-escape-right-brace) The "}" character should be escaped using a backslash to avoid confusion with a TSDoc inline tag + // Warning: (tsdoc-escape-right-brace) The "}" character should be escaped using a backslash to avoid confusion with a TSDoc inline tag + // Warning: (tsdoc-malformed-inline-tag) Expecting a TSDoc tag starting with "{@" + // Warning: (tsdoc-malformed-inline-tag) Expecting a TSDoc tag starting with "{@" + // Warning: (tsdoc-param-tag-with-invalid-name) The @param block should be followed by a valid parameter name: The identifier cannot non-word characters + // Warning: (tsdoc-param-tag-with-invalid-type) The @param block should not include a JSDoc-style '{type}' + // Warning: (tsdoc-escape-right-brace) The "}" character should be escaped using a backslash to avoid confusion with a TSDoc inline tag + // Warning: (tsdoc-malformed-inline-tag) Expecting a TSDoc tag starting with "{@" + // Warning: (tsdoc-param-tag-with-invalid-name) The @param block should be followed by a valid parameter name: The identifier cannot non-word characters + // Warning: (tsdoc-param-tag-with-invalid-type) The @param block should not include a JSDoc-style '{type}' + // Warning: (tsdoc-escape-right-brace) The "}" character should be escaped using a backslash to avoid confusion with a TSDoc inline tag + // Warning: (tsdoc-malformed-inline-tag) Expecting a TSDoc tag starting with "{@" + // Warning: (tsdoc-param-tag-with-invalid-name) The @param block should be followed by a valid parameter name: The identifier cannot non-word characters + // Warning: (tsdoc-param-tag-with-invalid-type) The @param block should not include a JSDoc-style '{type}' + // Warning: (tsdoc-escape-right-brace) The "}" character should be escaped using a backslash to avoid confusion with a TSDoc inline tag + // Warning: (tsdoc-malformed-inline-tag) Expecting a TSDoc tag starting with "{@" + // Warning: (tsdoc-param-tag-with-invalid-name) The @param block should be followed by a valid parameter name: The identifier cannot non-word characters + // Warning: (tsdoc-param-tag-with-invalid-type) The @param block should not include a JSDoc-style '{type}' + // Warning: (tsdoc-escape-right-brace) The "}" character should be escaped using a backslash to avoid confusion with a TSDoc inline tag + // Warning: (tsdoc-malformed-inline-tag) Expecting a TSDoc tag starting with "{@" + // Warning: (tsdoc-param-tag-with-invalid-name) The @param block should be followed by a valid parameter name: The identifier cannot non-word characters + // Warning: (tsdoc-param-tag-with-invalid-type) The @param block should not include a JSDoc-style '{type}' + // Warning: (tsdoc-escape-right-brace) The "}" character should be escaped using a backslash to avoid confusion with a TSDoc inline tag + // Warning: (tsdoc-malformed-inline-tag) Expecting a TSDoc tag starting with "{@" + // Warning: (tsdoc-param-tag-with-invalid-name) The @param block should be followed by a valid parameter name: The identifier cannot non-word characters + // Warning: (tsdoc-param-tag-with-invalid-type) The @param block should not include a JSDoc-style '{type}' + constructor(settings?: firestore.Settings); + // Warning: (tsdoc-escape-right-brace) The "}" character should be escaped using a backslash to avoid confusion with a TSDoc inline tag + // Warning: (tsdoc-malformed-inline-tag) Expecting a TSDoc tag starting with "{@" + batch(): WriteBatch; + // Warning: (tsdoc-param-tag-missing-hyphen) The @param block should be followed by a parameter name and then a hyphen + // Warning: (tsdoc-param-tag-with-invalid-type) The @param block should not include a JSDoc-style '{type}' + // Warning: (tsdoc-escape-right-brace) The "}" character should be escaped using a backslash to avoid confusion with a TSDoc inline tag + // Warning: (tsdoc-malformed-inline-tag) Expecting a TSDoc tag starting with "{@" + bulkWriter(options?: firestore.BulkWriterOptions): BulkWriter; + // Warning: (tsdoc-param-tag-with-invalid-name) The @param block should be followed by a valid parameter name: The identifier cannot non-word characters + bundle(name?: string): BundleBuilder; + // Warning: (tsdoc-param-tag-missing-hyphen) The @param block should be followed by a parameter name and then a hyphen + // Warning: (tsdoc-param-tag-with-invalid-type) The @param block should not include a JSDoc-style '{type}' + // Warning: (tsdoc-escape-right-brace) The "}" character should be escaped using a backslash to avoid confusion with a TSDoc inline tag + // Warning: (tsdoc-malformed-inline-tag) Expecting a TSDoc tag starting with "{@" + collection(collectionPath: string): CollectionReference; + // Warning: (tsdoc-param-tag-missing-hyphen) The @param block should be followed by a parameter name and then a hyphen + // Warning: (tsdoc-param-tag-with-invalid-type) The @param block should not include a JSDoc-style '{type}' + // Warning: (tsdoc-escape-right-brace) The "}" character should be escaped using a backslash to avoid confusion with a TSDoc inline tag + // Warning: (tsdoc-malformed-inline-tag) Expecting a TSDoc tag starting with "{@" + collectionGroup(collectionId: string): CollectionGroup; + get databaseId(): string; + // Warning: (tsdoc-undefined-tag) The TSDoc tag "@private" is not defined in this configuration + // + // @internal + _decrementBulkWritersCount(): void; + // Warning: (tsdoc-param-tag-missing-hyphen) The @param block should be followed by a parameter name and then a hyphen + // Warning: (tsdoc-param-tag-with-invalid-type) The @param block should not include a JSDoc-style '{type}' + // Warning: (tsdoc-escape-right-brace) The "}" character should be escaped using a backslash to avoid confusion with a TSDoc inline tag + // Warning: (tsdoc-malformed-inline-tag) Expecting a TSDoc tag starting with "{@" + doc(documentPath: string): DocumentReference; + // Warning: (tsdoc-undefined-tag) The TSDoc tag "@private" is not defined in this configuration + // + // @internal + get formattedName(): string; + // Warning: (tsdoc-param-tag-missing-hyphen) The @param block should be followed by a parameter name and then a hyphen + // Warning: (tsdoc-param-tag-with-invalid-type) The @param block should not include a JSDoc-style '{type}' + // Warning: (tsdoc-escape-right-brace) The "}" character should be escaped using a backslash to avoid confusion with a TSDoc inline tag + // Warning: (tsdoc-malformed-inline-tag) Expecting a TSDoc tag starting with "{@" + getAll(...documentRefsOrReadOptions: Array | firestore.ReadOptions>): Promise>>; + // Warning: (tsdoc-undefined-tag) The TSDoc tag "@private" is not defined in this configuration + // + // @internal + _incrementBulkWritersCount(): void; + // Warning: (tsdoc-undefined-tag) The TSDoc tag "@private" is not defined in this configuration + // Warning: (tsdoc-param-tag-missing-hyphen) The @param block should be followed by a parameter name and then a hyphen + // Warning: (tsdoc-undefined-tag) The TSDoc tag "@return" is not defined in this configuration + // + // @internal + initializeIfNeeded(requestTag: string): Promise; + // Warning: (tsdoc-escape-right-brace) The "}" character should be escaped using a backslash to avoid confusion with a TSDoc inline tag + // Warning: (tsdoc-malformed-inline-tag) Expecting a TSDoc tag starting with "{@" + listCollections(): Promise; + // @beta + pipeline(): PipelineSource; + // Warning: (tsdoc-undefined-tag) The TSDoc tag "@private" is not defined in this configuration + // + // @internal + get projectId(): string; + // Warning: (tsdoc-param-tag-missing-hyphen) The @param block should be followed by a parameter name and then a hyphen + // Warning: (tsdoc-param-tag-missing-hyphen) The @param block should be followed by a parameter name and then a hyphen + // Warning: (tsdoc-undefined-tag) The TSDoc tag "@return" is not defined in this configuration + recursiveDelete(ref: firestore.CollectionReference | firestore.DocumentReference, bulkWriter?: BulkWriter): Promise; + // Warning: (tsdoc-undefined-tag) The TSDoc tag "@private" is not defined in this configuration + // + // @internal + _recursiveDelete(ref: firestore.CollectionReference | firestore.DocumentReference, maxPendingOps: number, minPendingOps: number, bulkWriter?: BulkWriter): Promise; + // Warning: (tsdoc-undefined-tag) The TSDoc tag "@private" is not defined in this configuration + // + // @internal + registerListener(): void; + // Warning: (tsdoc-undefined-tag) The TSDoc tag "@private" is not defined in this configuration + // Warning: (tsdoc-param-tag-missing-hyphen) The @param block should be followed by a parameter name and then a hyphen + // Warning: (tsdoc-param-tag-missing-hyphen) The @param block should be followed by a parameter name and then a hyphen + // Warning: (tsdoc-param-tag-missing-hyphen) The @param block should be followed by a parameter name and then a hyphen + // Warning: (tsdoc-param-tag-missing-hyphen) The @param block should be followed by a parameter name and then a hyphen + // Warning: (ae-forgotten-export) The symbol "FirestoreUnaryMethod" needs to be exported by the entry point index.d.ts + // + // @internal + request(methodName: FirestoreUnaryMethod, request: Req, requestTag: string, retryCodes?: number[]): Promise; + // Warning: (tsdoc-undefined-tag) The TSDoc tag "@private" is not defined in this configuration + // Warning: (tsdoc-param-tag-missing-hyphen) The @param block should be followed by a parameter name and then a hyphen + // Warning: (tsdoc-param-tag-missing-hyphen) The @param block should be followed by a parameter name and then a hyphen + // Warning: (tsdoc-param-tag-missing-hyphen) The @param block should be followed by a parameter name and then a hyphen + // Warning: (tsdoc-param-tag-missing-hyphen) The @param block should be followed by a parameter name and then a hyphen + // Warning: (ae-forgotten-export) The symbol "FirestoreStreamingMethod" needs to be exported by the entry point index.d.ts + // + // @internal + requestStream(methodName: FirestoreStreamingMethod, bidrectional: boolean, request: {}, requestTag: string): Promise; + // Warning: (tsdoc-undefined-tag) The TSDoc tag "@template" is not defined in this configuration + // Warning: (tsdoc-param-tag-missing-hyphen) The @param block should be followed by a parameter name and then a hyphen + // Warning: (tsdoc-param-tag-with-invalid-type) The @param block should not include a JSDoc-style '{type}' + // Warning: (tsdoc-param-tag-missing-hyphen) The @param block should be followed by a parameter name and then a hyphen + // Warning: (tsdoc-param-tag-with-invalid-type) The @param block should not include a JSDoc-style '{type}' + // Warning: (tsdoc-escape-right-brace) The "}" character should be escaped using a backslash to avoid confusion with a TSDoc inline tag + // Warning: (tsdoc-malformed-inline-tag) Expecting a TSDoc tag starting with "{@" + runTransaction(updateFunction: (transaction: Transaction) => Promise, transactionOptions?: firestore.ReadWriteTransactionOptions | firestore.ReadOnlyTransactionOptions): Promise; + // Warning: (tsdoc-undefined-tag) The TSDoc tag "@private" is not defined in this configuration + // + // @internal + _serializer: Serializer | null; + // Warning: (tsdoc-param-tag-missing-hyphen) The @param block should be followed by a parameter name and then a hyphen + // Warning: (tsdoc-param-tag-with-invalid-type) The @param block should not include a JSDoc-style '{type}' + settings(settings: firestore.Settings): void; + // Warning: (tsdoc-undefined-tag) The TSDoc tag "@private" is not defined in this configuration + // + // @internal + _settings: firestore.Settings; + // Warning: (tsdoc-undefined-tag) The TSDoc tag "@private" is not defined in this configuration + // Warning: (tsdoc-param-tag-missing-hyphen) The @param block should be followed by a parameter name and then a hyphen + // Warning: (tsdoc-param-tag-missing-hyphen) The @param block should be followed by a parameter name and then a hyphen + // Warning: (tsdoc-param-tag-missing-hyphen) The @param block should be followed by a parameter name and then a hyphen + snapshot_(documentName: string, readTime?: google.protobuf.ITimestamp, encoding?: 'protobufJS'): DocumentSnapshot; + // Warning: (tsdoc-undefined-tag) The TSDoc tag "@private" is not defined in this configuration + // + // (undocumented) + snapshot_(documentName: string, readTime: string, encoding: 'json'): DocumentSnapshot; + // Warning: (tsdoc-undefined-tag) The TSDoc tag "@private" is not defined in this configuration + // + // (undocumented) + snapshot_(document: api.IDocument, readTime: google.protobuf.ITimestamp, encoding?: 'protobufJS'): QueryDocumentSnapshot; + // Warning: (tsdoc-undefined-tag) The TSDoc tag "@private" is not defined in this configuration + // + // (undocumented) + snapshot_(document: { + [k: string]: unknown; + }, readTime: string, encoding: 'json'): QueryDocumentSnapshot; + // Warning: (tsdoc-undefined-tag) The TSDoc tag "@return" is not defined in this configuration + terminate(): Promise; + // Warning: (tsdoc-undefined-tag) The TSDoc tag "@return" is not defined in this configuration + toJSON(): object; + // Warning: (tsdoc-undefined-tag) The TSDoc tag "@private" is not defined in this configuration + // Warning: (ae-forgotten-export) The symbol "TraceUtil" needs to be exported by the entry point index.d.ts + // + // @internal + _traceUtil: TraceUtil; + // Warning: (tsdoc-undefined-tag) The TSDoc tag "@private" is not defined in this configuration + // + // @internal + unregisterListener(): void; +} +export { Firestore } +export default Firestore; + +// Warning: (tsdoc-param-tag-missing-hyphen) The @param block should be followed by a parameter name and then a hyphen +// Warning: (tsdoc-undefined-tag) The TSDoc tag "@return" is not defined in this configuration +// Warning: (tsdoc-undefined-tag) The TSDoc tag "@code" is not defined in this configuration +// +// @beta +function floor(expr: Expression): FunctionExpression; + +// Warning: (tsdoc-param-tag-missing-hyphen) The @param block should be followed by a parameter name and then a hyphen +// Warning: (tsdoc-undefined-tag) The TSDoc tag "@return" is not defined in this configuration +// Warning: (tsdoc-undefined-tag) The TSDoc tag "@code" is not defined in this configuration +// +// @beta +function floor(fieldName: string): FunctionExpression; + +// @beta +class FunctionExpression extends Expression { + constructor(name: string, params: Expression[]); + // (undocumented) + readonly expressionType: firestore.Pipelines.ExpressionType; + // (undocumented) + protected name: string; + // Warning: (tsdoc-undefined-tag) The TSDoc tag "@private" is not defined in this configuration + // + // (undocumented) + _toProto(serializer: Serializer): api.IValue; + // Warning: (tsdoc-undefined-tag) The TSDoc tag "@private" is not defined in this configuration + // + // (undocumented) + _validateUserData(ignoreUndefinedProperties: boolean): void; +} + +// Warning: (tsdoc-undefined-tag) The TSDoc tag "@class" is not defined in this configuration +// +// @public +export class GeoPoint implements Serializable, firestore.GeoPoint { + // Warning: (tsdoc-param-tag-missing-hyphen) The @param block should be followed by a parameter name and then a hyphen + // Warning: (tsdoc-param-tag-with-invalid-type) The @param block should not include a JSDoc-style '{type}' + // Warning: (tsdoc-param-tag-missing-hyphen) The @param block should be followed by a parameter name and then a hyphen + // Warning: (tsdoc-param-tag-with-invalid-type) The @param block should not include a JSDoc-style '{type}' + constructor(latitude: number, longitude: number); + // Warning: (tsdoc-undefined-tag) The TSDoc tag "@private" is not defined in this configuration + // + // @internal + static fromProto(proto: google.type.ILatLng): GeoPoint; + // Warning: (tsdoc-param-tag-missing-hyphen) The @param block should be followed by a parameter name and then a hyphen + // Warning: (tsdoc-param-tag-with-invalid-type) The @param block should not include a JSDoc-style '{type}' + // Warning: (tsdoc-escape-right-brace) The "}" character should be escaped using a backslash to avoid confusion with a TSDoc inline tag + // Warning: (tsdoc-malformed-inline-tag) Expecting a TSDoc tag starting with "{@" + // Warning: (tsdoc-undefined-tag) The TSDoc tag "@return" is not defined in this configuration + isEqual(other: firestore.GeoPoint): boolean; + // Warning: (tsdoc-escape-right-brace) The "}" character should be escaped using a backslash to avoid confusion with a TSDoc inline tag + // Warning: (tsdoc-malformed-inline-tag) Expecting a TSDoc tag starting with "{@" + // Warning: (tsdoc-undefined-tag) The TSDoc tag "@type" is not defined in this configuration + // Warning: (tsdoc-undefined-tag) The TSDoc tag "@name" is not defined in this configuration + get latitude(): number; + // Warning: (tsdoc-escape-right-brace) The "}" character should be escaped using a backslash to avoid confusion with a TSDoc inline tag + // Warning: (tsdoc-malformed-inline-tag) Expecting a TSDoc tag starting with "{@" + // Warning: (tsdoc-undefined-tag) The TSDoc tag "@type" is not defined in this configuration + // Warning: (tsdoc-undefined-tag) The TSDoc tag "@name" is not defined in this configuration + get longitude(): number; + // Warning: (tsdoc-undefined-tag) The TSDoc tag "@private" is not defined in this configuration + // + // @internal + toProto(): api.IValue; +} + +// Warning: (tsdoc-param-tag-missing-hyphen) The @param block should be followed by a parameter name and then a hyphen +// Warning: (tsdoc-param-tag-missing-hyphen) The @param block should be followed by a parameter name and then a hyphen +// Warning: (tsdoc-undefined-tag) The TSDoc tag "@return" is not defined in this configuration +// +// @beta +function greaterThan(left: Expression, right: Expression): BooleanExpression; + +// Warning: (tsdoc-param-tag-missing-hyphen) The @param block should be followed by a parameter name and then a hyphen +// Warning: (tsdoc-param-tag-missing-hyphen) The @param block should be followed by a parameter name and then a hyphen +// Warning: (tsdoc-undefined-tag) The TSDoc tag "@return" is not defined in this configuration +// +// @beta +function greaterThan(expression: Expression, value: unknown): BooleanExpression; + +// Warning: (tsdoc-param-tag-missing-hyphen) The @param block should be followed by a parameter name and then a hyphen +// Warning: (tsdoc-param-tag-missing-hyphen) The @param block should be followed by a parameter name and then a hyphen +// Warning: (tsdoc-undefined-tag) The TSDoc tag "@return" is not defined in this configuration +// +// @beta +function greaterThan(fieldName: string, expression: Expression): BooleanExpression; + +// Warning: (tsdoc-param-tag-missing-hyphen) The @param block should be followed by a parameter name and then a hyphen +// Warning: (tsdoc-param-tag-missing-hyphen) The @param block should be followed by a parameter name and then a hyphen +// Warning: (tsdoc-undefined-tag) The TSDoc tag "@return" is not defined in this configuration +// +// @beta +function greaterThan(fieldName: string, value: unknown): BooleanExpression; + +// Warning: (tsdoc-param-tag-missing-hyphen) The @param block should be followed by a parameter name and then a hyphen +// Warning: (tsdoc-param-tag-missing-hyphen) The @param block should be followed by a parameter name and then a hyphen +// Warning: (tsdoc-undefined-tag) The TSDoc tag "@return" is not defined in this configuration +// +// @beta +function greaterThanOrEqual(left: Expression, right: Expression): BooleanExpression; + +// Warning: (tsdoc-param-tag-missing-hyphen) The @param block should be followed by a parameter name and then a hyphen +// Warning: (tsdoc-param-tag-missing-hyphen) The @param block should be followed by a parameter name and then a hyphen +// Warning: (tsdoc-undefined-tag) The TSDoc tag "@return" is not defined in this configuration +// +// @beta +function greaterThanOrEqual(expression: Expression, value: unknown): BooleanExpression; + +// Warning: (tsdoc-param-tag-missing-hyphen) The @param block should be followed by a parameter name and then a hyphen +// Warning: (tsdoc-param-tag-missing-hyphen) The @param block should be followed by a parameter name and then a hyphen +// Warning: (tsdoc-undefined-tag) The TSDoc tag "@return" is not defined in this configuration +// +// @beta +function greaterThanOrEqual(fieldName: string, value: Expression): BooleanExpression; + +// Warning: (tsdoc-param-tag-missing-hyphen) The @param block should be followed by a parameter name and then a hyphen +// Warning: (tsdoc-param-tag-missing-hyphen) The @param block should be followed by a parameter name and then a hyphen +// Warning: (tsdoc-undefined-tag) The TSDoc tag "@return" is not defined in this configuration +// +// @beta +function greaterThanOrEqual(fieldName: string, value: unknown): BooleanExpression; + +// Warning: (tsdoc-param-tag-missing-hyphen) The @param block should be followed by a parameter name and then a hyphen +// Warning: (tsdoc-param-tag-missing-hyphen) The @param block should be followed by a parameter name and then a hyphen +// Warning: (tsdoc-undefined-tag) The TSDoc tag "@return" is not defined in this configuration +// +// @beta +function ifAbsent(ifExpr: Expression, elseExpr: Expression): Expression; + +// Warning: (tsdoc-param-tag-missing-hyphen) The @param block should be followed by a parameter name and then a hyphen +// Warning: (tsdoc-param-tag-missing-hyphen) The @param block should be followed by a parameter name and then a hyphen +// Warning: (tsdoc-undefined-tag) The TSDoc tag "@return" is not defined in this configuration +// +// @beta +function ifAbsent(ifExpr: Expression, elseValue: unknown): Expression; + +// Warning: (tsdoc-param-tag-missing-hyphen) The @param block should be followed by a parameter name and then a hyphen +// Warning: (tsdoc-param-tag-missing-hyphen) The @param block should be followed by a parameter name and then a hyphen +// Warning: (tsdoc-undefined-tag) The TSDoc tag "@return" is not defined in this configuration +// +// @beta +function ifAbsent(ifFieldName: string, elseExpr: Expression): Expression; + +// Warning: (tsdoc-param-tag-missing-hyphen) The @param block should be followed by a parameter name and then a hyphen +// Warning: (tsdoc-param-tag-missing-hyphen) The @param block should be followed by a parameter name and then a hyphen +// Warning: (tsdoc-undefined-tag) The TSDoc tag "@return" is not defined in this configuration +// +// @beta +function ifAbsent(ifFieldName: string | Expression, elseValue: Expression | unknown): Expression; + +// Warning: (tsdoc-param-tag-missing-hyphen) The @param block should be followed by a parameter name and then a hyphen +// Warning: (tsdoc-param-tag-missing-hyphen) The @param block should be followed by a parameter name and then a hyphen +// Warning: (tsdoc-undefined-tag) The TSDoc tag "@return" is not defined in this configuration +// Warning: (tsdoc-undefined-tag) The TSDoc tag "@code" is not defined in this configuration +// +// @beta +function ifError(tryExpr: BooleanExpression, catchExpr: BooleanExpression): BooleanExpression; + +// Warning: (tsdoc-param-tag-missing-hyphen) The @param block should be followed by a parameter name and then a hyphen +// Warning: (tsdoc-param-tag-missing-hyphen) The @param block should be followed by a parameter name and then a hyphen +// Warning: (tsdoc-undefined-tag) The TSDoc tag "@return" is not defined in this configuration +// Warning: (tsdoc-undefined-tag) The TSDoc tag "@code" is not defined in this configuration +// +// @beta +function ifError(tryExpr: Expression, catchExpr: Expression): FunctionExpression; + +// Warning: (tsdoc-param-tag-missing-hyphen) The @param block should be followed by a parameter name and then a hyphen +// Warning: (tsdoc-param-tag-missing-hyphen) The @param block should be followed by a parameter name and then a hyphen +// Warning: (tsdoc-undefined-tag) The TSDoc tag "@return" is not defined in this configuration +// Warning: (tsdoc-undefined-tag) The TSDoc tag "@code" is not defined in this configuration +// +// @beta +function ifError(tryExpr: Expression, catchValue: unknown): FunctionExpression; + +// Warning: (tsdoc-param-tag-missing-hyphen) The @param block should be followed by a parameter name and then a hyphen +// Warning: (tsdoc-undefined-tag) The TSDoc tag "@return" is not defined in this configuration +// Warning: (tsdoc-undefined-tag) The TSDoc tag "@code" is not defined in this configuration +// +// @beta +function isAbsent(value: Expression): BooleanExpression; + +// Warning: (tsdoc-param-tag-missing-hyphen) The @param block should be followed by a parameter name and then a hyphen +// Warning: (tsdoc-undefined-tag) The TSDoc tag "@return" is not defined in this configuration +// Warning: (tsdoc-undefined-tag) The TSDoc tag "@code" is not defined in this configuration +// +// @beta +function isAbsent(field: string): BooleanExpression; + +// Warning: (tsdoc-param-tag-missing-hyphen) The @param block should be followed by a parameter name and then a hyphen +// Warning: (tsdoc-undefined-tag) The TSDoc tag "@return" is not defined in this configuration +// Warning: (tsdoc-undefined-tag) The TSDoc tag "@code" is not defined in this configuration +// +// @beta +function isError(value: Expression): BooleanExpression; + +// Warning: (tsdoc-param-tag-missing-hyphen) The @param block should be followed by a parameter name and then a hyphen +// Warning: (tsdoc-param-tag-missing-hyphen) The @param block should be followed by a parameter name and then a hyphen +// Warning: (tsdoc-undefined-tag) The TSDoc tag "@return" is not defined in this configuration +// +// @beta +function join(arrayFieldName: string, delimiter: string): Expression; + +// Warning: (tsdoc-param-tag-missing-hyphen) The @param block should be followed by a parameter name and then a hyphen +// Warning: (tsdoc-param-tag-missing-hyphen) The @param block should be followed by a parameter name and then a hyphen +// Warning: (tsdoc-undefined-tag) The TSDoc tag "@return" is not defined in this configuration +// +// @beta +function join(arrayExpression: Expression, delimiterExpression: Expression): Expression; + +// Warning: (tsdoc-param-tag-missing-hyphen) The @param block should be followed by a parameter name and then a hyphen +// Warning: (tsdoc-param-tag-missing-hyphen) The @param block should be followed by a parameter name and then a hyphen +// Warning: (tsdoc-undefined-tag) The TSDoc tag "@return" is not defined in this configuration +// +// @beta +function join(arrayExpression: Expression, delimiter: string): Expression; + +// Warning: (tsdoc-param-tag-missing-hyphen) The @param block should be followed by a parameter name and then a hyphen +// Warning: (tsdoc-param-tag-missing-hyphen) The @param block should be followed by a parameter name and then a hyphen +// Warning: (tsdoc-undefined-tag) The TSDoc tag "@return" is not defined in this configuration +// +// @beta +function join(arrayFieldName: string, delimiterExpression: Expression): Expression; + +// Warning: (tsdoc-param-tag-missing-hyphen) The @param block should be followed by a parameter name and then a hyphen +// Warning: (tsdoc-undefined-tag) The TSDoc tag "@return" is not defined in this configuration +// +// @beta +function length_2(fieldName: string): FunctionExpression; + +// Warning: (tsdoc-param-tag-missing-hyphen) The @param block should be followed by a parameter name and then a hyphen +// Warning: (tsdoc-undefined-tag) The TSDoc tag "@return" is not defined in this configuration +// +// @beta +function length_2(expression: Expression): FunctionExpression; + +// Warning: (tsdoc-param-tag-missing-hyphen) The @param block should be followed by a parameter name and then a hyphen +// Warning: (tsdoc-param-tag-missing-hyphen) The @param block should be followed by a parameter name and then a hyphen +// Warning: (tsdoc-undefined-tag) The TSDoc tag "@return" is not defined in this configuration +// +// @beta +function lessThan(left: Expression, right: Expression): BooleanExpression; + +// Warning: (tsdoc-param-tag-missing-hyphen) The @param block should be followed by a parameter name and then a hyphen +// Warning: (tsdoc-param-tag-missing-hyphen) The @param block should be followed by a parameter name and then a hyphen +// Warning: (tsdoc-undefined-tag) The TSDoc tag "@return" is not defined in this configuration +// +// @beta +function lessThan(expression: Expression, value: unknown): BooleanExpression; + +// Warning: (tsdoc-param-tag-missing-hyphen) The @param block should be followed by a parameter name and then a hyphen +// Warning: (tsdoc-param-tag-missing-hyphen) The @param block should be followed by a parameter name and then a hyphen +// Warning: (tsdoc-undefined-tag) The TSDoc tag "@return" is not defined in this configuration +// +// @beta +function lessThan(fieldName: string, expression: Expression): BooleanExpression; + +// Warning: (tsdoc-param-tag-missing-hyphen) The @param block should be followed by a parameter name and then a hyphen +// Warning: (tsdoc-param-tag-missing-hyphen) The @param block should be followed by a parameter name and then a hyphen +// Warning: (tsdoc-undefined-tag) The TSDoc tag "@return" is not defined in this configuration +// +// @beta +function lessThan(fieldName: string, value: unknown): BooleanExpression; + +// Warning: (tsdoc-param-tag-missing-hyphen) The @param block should be followed by a parameter name and then a hyphen +// Warning: (tsdoc-param-tag-missing-hyphen) The @param block should be followed by a parameter name and then a hyphen +// Warning: (tsdoc-undefined-tag) The TSDoc tag "@return" is not defined in this configuration +// +// @beta +function lessThanOrEqual(left: Expression, right: Expression): BooleanExpression; + +// Warning: (tsdoc-param-tag-missing-hyphen) The @param block should be followed by a parameter name and then a hyphen +// Warning: (tsdoc-param-tag-missing-hyphen) The @param block should be followed by a parameter name and then a hyphen +// Warning: (tsdoc-undefined-tag) The TSDoc tag "@return" is not defined in this configuration +// +// @beta +function lessThanOrEqual(expression: Expression, value: unknown): BooleanExpression; + +// Warning: (tsdoc-param-tag-missing-hyphen) The @param block should be followed by a parameter name and then a hyphen +// Warning: (tsdoc-param-tag-missing-hyphen) The @param block should be followed by a parameter name and then a hyphen +// Warning: (tsdoc-undefined-tag) The TSDoc tag "@return" is not defined in this configuration +// +// @beta +function lessThanOrEqual(fieldName: string, expression: Expression): BooleanExpression; + +// Warning: (tsdoc-param-tag-missing-hyphen) The @param block should be followed by a parameter name and then a hyphen +// Warning: (tsdoc-param-tag-missing-hyphen) The @param block should be followed by a parameter name and then a hyphen +// Warning: (tsdoc-undefined-tag) The TSDoc tag "@return" is not defined in this configuration +// +// @beta +function lessThanOrEqual(fieldName: string, value: unknown): BooleanExpression; + +// Warning: (tsdoc-param-tag-missing-hyphen) The @param block should be followed by a parameter name and then a hyphen +// Warning: (tsdoc-param-tag-missing-hyphen) The @param block should be followed by a parameter name and then a hyphen +// Warning: (tsdoc-undefined-tag) The TSDoc tag "@return" is not defined in this configuration +// Warning: (tsdoc-undefined-tag) The TSDoc tag "@code" is not defined in this configuration +// +// @beta +function like(fieldName: string, pattern: string): BooleanExpression; + +// Warning: (tsdoc-param-tag-missing-hyphen) The @param block should be followed by a parameter name and then a hyphen +// Warning: (tsdoc-param-tag-missing-hyphen) The @param block should be followed by a parameter name and then a hyphen +// Warning: (tsdoc-undefined-tag) The TSDoc tag "@return" is not defined in this configuration +// Warning: (tsdoc-undefined-tag) The TSDoc tag "@code" is not defined in this configuration +// +// @beta +function like(fieldName: string, pattern: Expression): BooleanExpression; + +// Warning: (tsdoc-param-tag-missing-hyphen) The @param block should be followed by a parameter name and then a hyphen +// Warning: (tsdoc-param-tag-missing-hyphen) The @param block should be followed by a parameter name and then a hyphen +// Warning: (tsdoc-undefined-tag) The TSDoc tag "@return" is not defined in this configuration +// Warning: (tsdoc-undefined-tag) The TSDoc tag "@code" is not defined in this configuration +// +// @beta +function like(stringExpression: Expression, pattern: string): BooleanExpression; + +// Warning: (tsdoc-param-tag-missing-hyphen) The @param block should be followed by a parameter name and then a hyphen +// Warning: (tsdoc-param-tag-missing-hyphen) The @param block should be followed by a parameter name and then a hyphen +// Warning: (tsdoc-undefined-tag) The TSDoc tag "@return" is not defined in this configuration +// Warning: (tsdoc-undefined-tag) The TSDoc tag "@code" is not defined in this configuration +// +// @beta +function like(stringExpression: Expression, pattern: Expression): BooleanExpression; + +// Warning: (tsdoc-param-tag-missing-hyphen) The @param block should be followed by a parameter name and then a hyphen +// Warning: (tsdoc-undefined-tag) The TSDoc tag "@return" is not defined in this configuration +// +// @beta +function ln(fieldName: string): FunctionExpression; + +// Warning: (tsdoc-param-tag-missing-hyphen) The @param block should be followed by a parameter name and then a hyphen +// Warning: (tsdoc-undefined-tag) The TSDoc tag "@return" is not defined in this configuration +// +// @beta +function ln(expression: Expression): FunctionExpression; + +// Warning: (tsdoc-param-tag-missing-hyphen) The @param block should be followed by a parameter name and then a hyphen +// Warning: (tsdoc-undefined-tag) The TSDoc tag "@return" is not defined in this configuration +// +// @beta +function log10(fieldName: string): FunctionExpression; + +// Warning: (tsdoc-param-tag-missing-hyphen) The @param block should be followed by a parameter name and then a hyphen +// Warning: (tsdoc-undefined-tag) The TSDoc tag "@return" is not defined in this configuration +// +// @beta +function log10(expression: Expression): FunctionExpression; + +// Warning: (tsdoc-param-tag-missing-hyphen) The @param block should be followed by a parameter name and then a hyphen +// Warning: (tsdoc-param-tag-missing-hyphen) The @param block should be followed by a parameter name and then a hyphen +// Warning: (tsdoc-param-tag-missing-hyphen) The @param block should be followed by a parameter name and then a hyphen +// Warning: (tsdoc-undefined-tag) The TSDoc tag "@return" is not defined in this configuration +// Warning: (tsdoc-undefined-tag) The TSDoc tag "@code" is not defined in this configuration +// +// @beta +function logicalMaximum(first: Expression, second: Expression | unknown, ...others: Array): FunctionExpression; + +// Warning: (tsdoc-param-tag-missing-hyphen) The @param block should be followed by a parameter name and then a hyphen +// Warning: (tsdoc-param-tag-missing-hyphen) The @param block should be followed by a parameter name and then a hyphen +// Warning: (tsdoc-param-tag-missing-hyphen) The @param block should be followed by a parameter name and then a hyphen +// Warning: (tsdoc-undefined-tag) The TSDoc tag "@return" is not defined in this configuration +// Warning: (tsdoc-undefined-tag) The TSDoc tag "@code" is not defined in this configuration +// +// @beta +function logicalMaximum(fieldName: string, second: Expression | unknown, ...others: Array): FunctionExpression; + +// Warning: (tsdoc-param-tag-missing-hyphen) The @param block should be followed by a parameter name and then a hyphen +// Warning: (tsdoc-param-tag-missing-hyphen) The @param block should be followed by a parameter name and then a hyphen +// Warning: (tsdoc-param-tag-missing-hyphen) The @param block should be followed by a parameter name and then a hyphen +// Warning: (tsdoc-undefined-tag) The TSDoc tag "@return" is not defined in this configuration +// Warning: (tsdoc-undefined-tag) The TSDoc tag "@code" is not defined in this configuration +// +// @beta +function logicalMinimum(first: Expression, second: Expression | unknown, ...others: Array): FunctionExpression; + +// Warning: (tsdoc-param-tag-missing-hyphen) The @param block should be followed by a parameter name and then a hyphen +// Warning: (tsdoc-param-tag-missing-hyphen) The @param block should be followed by a parameter name and then a hyphen +// Warning: (tsdoc-param-tag-missing-hyphen) The @param block should be followed by a parameter name and then a hyphen +// Warning: (tsdoc-undefined-tag) The TSDoc tag "@return" is not defined in this configuration +// Warning: (tsdoc-undefined-tag) The TSDoc tag "@code" is not defined in this configuration +// +// @beta +function logicalMinimum(fieldName: string, second: Expression | unknown, ...others: Array): FunctionExpression; + +// Warning: (tsdoc-param-tag-missing-hyphen) The @param block should be followed by a parameter name and then a hyphen +// Warning: (tsdoc-undefined-tag) The TSDoc tag "@return" is not defined in this configuration +// Warning: (tsdoc-undefined-tag) The TSDoc tag "@code" is not defined in this configuration +// +// @beta +function map(elements: Record): FunctionExpression; + +// Warning: (tsdoc-param-tag-missing-hyphen) The @param block should be followed by a parameter name and then a hyphen +// Warning: (tsdoc-param-tag-missing-hyphen) The @param block should be followed by a parameter name and then a hyphen +// Warning: (tsdoc-undefined-tag) The TSDoc tag "@return" is not defined in this configuration +// Warning: (tsdoc-undefined-tag) The TSDoc tag "@code" is not defined in this configuration +// +// @beta +function mapGet(fieldName: string, subField: string): FunctionExpression; + +// Warning: (tsdoc-param-tag-missing-hyphen) The @param block should be followed by a parameter name and then a hyphen +// Warning: (tsdoc-param-tag-missing-hyphen) The @param block should be followed by a parameter name and then a hyphen +// Warning: (tsdoc-undefined-tag) The TSDoc tag "@return" is not defined in this configuration +// Warning: (tsdoc-undefined-tag) The TSDoc tag "@code" is not defined in this configuration +// +// @beta +function mapGet(mapExpression: Expression, subField: string): FunctionExpression; + +// Warning: (tsdoc-param-tag-missing-hyphen) The @param block should be followed by a parameter name and then a hyphen +// Warning: (tsdoc-param-tag-missing-hyphen) The @param block should be followed by a parameter name and then a hyphen +// Warning: (tsdoc-param-tag-missing-hyphen) The @param block should be followed by a parameter name and then a hyphen +// +// @beta +function mapMerge(mapField: string, secondMap: Record | Expression, ...otherMaps: Array | Expression>): FunctionExpression; + +// Warning: (tsdoc-param-tag-missing-hyphen) The @param block should be followed by a parameter name and then a hyphen +// Warning: (tsdoc-param-tag-missing-hyphen) The @param block should be followed by a parameter name and then a hyphen +// Warning: (tsdoc-param-tag-missing-hyphen) The @param block should be followed by a parameter name and then a hyphen +// +// @beta +function mapMerge(firstMap: Record | Expression, secondMap: Record | Expression, ...otherMaps: Array | Expression>): FunctionExpression; + +// Warning: (tsdoc-param-tag-missing-hyphen) The @param block should be followed by a parameter name and then a hyphen +// Warning: (tsdoc-param-tag-missing-hyphen) The @param block should be followed by a parameter name and then a hyphen +// +// @beta +function mapRemove(mapField: string, key: string): FunctionExpression; + +// Warning: (tsdoc-param-tag-missing-hyphen) The @param block should be followed by a parameter name and then a hyphen +// Warning: (tsdoc-param-tag-missing-hyphen) The @param block should be followed by a parameter name and then a hyphen +// +// @beta +function mapRemove(mapExpr: Expression, key: string): FunctionExpression; + +// Warning: (tsdoc-param-tag-missing-hyphen) The @param block should be followed by a parameter name and then a hyphen +// Warning: (tsdoc-param-tag-missing-hyphen) The @param block should be followed by a parameter name and then a hyphen +// +// @beta +function mapRemove(mapField: string, keyExpr: Expression): FunctionExpression; + +// Warning: (tsdoc-param-tag-missing-hyphen) The @param block should be followed by a parameter name and then a hyphen +// Warning: (tsdoc-param-tag-missing-hyphen) The @param block should be followed by a parameter name and then a hyphen +// +// @beta +function mapRemove(mapExpr: Expression, keyExpr: Expression): FunctionExpression; + +// Warning: (tsdoc-undefined-tag) The TSDoc tag "@private" is not defined in this configuration +// +// @public +export const MAX_REQUEST_RETRIES = 5; + +// Warning: (tsdoc-param-tag-missing-hyphen) The @param block should be followed by a parameter name and then a hyphen +// Warning: (tsdoc-undefined-tag) The TSDoc tag "@return" is not defined in this configuration +// Warning: (tsdoc-undefined-tag) The TSDoc tag "@code" is not defined in this configuration +// +// @beta +function maximum(expression: Expression): AggregateFunction; + +// Warning: (tsdoc-param-tag-missing-hyphen) The @param block should be followed by a parameter name and then a hyphen +// Warning: (tsdoc-undefined-tag) The TSDoc tag "@return" is not defined in this configuration +// Warning: (tsdoc-undefined-tag) The TSDoc tag "@code" is not defined in this configuration +// +// @beta +function maximum(fieldName: string): AggregateFunction; + +// Warning: (tsdoc-param-tag-missing-hyphen) The @param block should be followed by a parameter name and then a hyphen +// Warning: (tsdoc-undefined-tag) The TSDoc tag "@return" is not defined in this configuration +// Warning: (tsdoc-undefined-tag) The TSDoc tag "@code" is not defined in this configuration +// +// @beta +function minimum(expression: Expression): AggregateFunction; + +// Warning: (tsdoc-param-tag-missing-hyphen) The @param block should be followed by a parameter name and then a hyphen +// Warning: (tsdoc-undefined-tag) The TSDoc tag "@return" is not defined in this configuration +// Warning: (tsdoc-undefined-tag) The TSDoc tag "@code" is not defined in this configuration +// +// @beta +function minimum(fieldName: string): AggregateFunction; + +// Warning: (tsdoc-param-tag-missing-hyphen) The @param block should be followed by a parameter name and then a hyphen +// Warning: (tsdoc-param-tag-missing-hyphen) The @param block should be followed by a parameter name and then a hyphen +// Warning: (tsdoc-undefined-tag) The TSDoc tag "@return" is not defined in this configuration +// Warning: (tsdoc-undefined-tag) The TSDoc tag "@code" is not defined in this configuration +// +// @beta +function mod(left: Expression, right: Expression): FunctionExpression; + +// Warning: (tsdoc-param-tag-missing-hyphen) The @param block should be followed by a parameter name and then a hyphen +// Warning: (tsdoc-param-tag-missing-hyphen) The @param block should be followed by a parameter name and then a hyphen +// Warning: (tsdoc-undefined-tag) The TSDoc tag "@return" is not defined in this configuration +// Warning: (tsdoc-undefined-tag) The TSDoc tag "@code" is not defined in this configuration +// +// @beta +function mod(expression: Expression, value: unknown): FunctionExpression; + +// Warning: (tsdoc-param-tag-missing-hyphen) The @param block should be followed by a parameter name and then a hyphen +// Warning: (tsdoc-param-tag-missing-hyphen) The @param block should be followed by a parameter name and then a hyphen +// Warning: (tsdoc-undefined-tag) The TSDoc tag "@return" is not defined in this configuration +// Warning: (tsdoc-undefined-tag) The TSDoc tag "@code" is not defined in this configuration +// +// @beta +function mod(fieldName: string, expression: Expression): FunctionExpression; + +// Warning: (tsdoc-param-tag-missing-hyphen) The @param block should be followed by a parameter name and then a hyphen +// Warning: (tsdoc-param-tag-missing-hyphen) The @param block should be followed by a parameter name and then a hyphen +// Warning: (tsdoc-undefined-tag) The TSDoc tag "@return" is not defined in this configuration +// Warning: (tsdoc-undefined-tag) The TSDoc tag "@code" is not defined in this configuration +// +// @beta +function mod(fieldName: string, value: unknown): FunctionExpression; + +// Warning: (tsdoc-param-tag-missing-hyphen) The @param block should be followed by a parameter name and then a hyphen +// Warning: (tsdoc-param-tag-missing-hyphen) The @param block should be followed by a parameter name and then a hyphen +// Warning: (tsdoc-undefined-tag) The TSDoc tag "@return" is not defined in this configuration +// Warning: (tsdoc-undefined-tag) The TSDoc tag "@code" is not defined in this configuration +// +// @beta +function multiply(first: Expression, second: Expression | unknown): FunctionExpression; + +// Warning: (tsdoc-param-tag-missing-hyphen) The @param block should be followed by a parameter name and then a hyphen +// Warning: (tsdoc-param-tag-missing-hyphen) The @param block should be followed by a parameter name and then a hyphen +// Warning: (tsdoc-undefined-tag) The TSDoc tag "@return" is not defined in this configuration +// Warning: (tsdoc-undefined-tag) The TSDoc tag "@code" is not defined in this configuration +// +// @beta +function multiply(fieldName: string, second: Expression | unknown): FunctionExpression; + +// Warning: (tsdoc-param-tag-missing-hyphen) The @param block should be followed by a parameter name and then a hyphen +// Warning: (tsdoc-undefined-tag) The TSDoc tag "@return" is not defined in this configuration +// Warning: (tsdoc-undefined-tag) The TSDoc tag "@code" is not defined in this configuration +// +// @beta +function not(booleanExpr: BooleanExpression): BooleanExpression; + +// Warning: (tsdoc-param-tag-missing-hyphen) The @param block should be followed by a parameter name and then a hyphen +// Warning: (tsdoc-param-tag-missing-hyphen) The @param block should be followed by a parameter name and then a hyphen +// Warning: (tsdoc-undefined-tag) The TSDoc tag "@return" is not defined in this configuration +// +// @beta +function notEqual(left: Expression, right: Expression): BooleanExpression; + +// Warning: (tsdoc-param-tag-missing-hyphen) The @param block should be followed by a parameter name and then a hyphen +// Warning: (tsdoc-param-tag-missing-hyphen) The @param block should be followed by a parameter name and then a hyphen +// Warning: (tsdoc-undefined-tag) The TSDoc tag "@return" is not defined in this configuration +// +// @beta +function notEqual(expression: Expression, value: unknown): BooleanExpression; + +// Warning: (tsdoc-param-tag-missing-hyphen) The @param block should be followed by a parameter name and then a hyphen +// Warning: (tsdoc-param-tag-missing-hyphen) The @param block should be followed by a parameter name and then a hyphen +// Warning: (tsdoc-undefined-tag) The TSDoc tag "@return" is not defined in this configuration +// +// @beta +function notEqual(fieldName: string, expression: Expression): BooleanExpression; + +// Warning: (tsdoc-param-tag-missing-hyphen) The @param block should be followed by a parameter name and then a hyphen +// Warning: (tsdoc-param-tag-missing-hyphen) The @param block should be followed by a parameter name and then a hyphen +// Warning: (tsdoc-undefined-tag) The TSDoc tag "@return" is not defined in this configuration +// +// @beta +function notEqual(fieldName: string, value: unknown): BooleanExpression; + +// Warning: (tsdoc-param-tag-missing-hyphen) The @param block should be followed by a parameter name and then a hyphen +// Warning: (tsdoc-param-tag-missing-hyphen) The @param block should be followed by a parameter name and then a hyphen +// Warning: (tsdoc-undefined-tag) The TSDoc tag "@return" is not defined in this configuration +// Warning: (tsdoc-undefined-tag) The TSDoc tag "@code" is not defined in this configuration +// +// @beta +function notEqualAny(element: Expression, values: Array): BooleanExpression; + +// Warning: (tsdoc-param-tag-missing-hyphen) The @param block should be followed by a parameter name and then a hyphen +// Warning: (tsdoc-param-tag-missing-hyphen) The @param block should be followed by a parameter name and then a hyphen +// Warning: (tsdoc-undefined-tag) The TSDoc tag "@return" is not defined in this configuration +// Warning: (tsdoc-undefined-tag) The TSDoc tag "@code" is not defined in this configuration +// +// @beta +function notEqualAny(fieldName: string, values: Array): BooleanExpression; + +// Warning: (tsdoc-param-tag-missing-hyphen) The @param block should be followed by a parameter name and then a hyphen +// Warning: (tsdoc-param-tag-missing-hyphen) The @param block should be followed by a parameter name and then a hyphen +// Warning: (tsdoc-undefined-tag) The TSDoc tag "@return" is not defined in this configuration +// Warning: (tsdoc-undefined-tag) The TSDoc tag "@code" is not defined in this configuration +// +// @beta +function notEqualAny(element: Expression, arrayExpression: Expression): BooleanExpression; + +// Warning: (tsdoc-param-tag-missing-hyphen) The @param block should be followed by a parameter name and then a hyphen +// Warning: (tsdoc-param-tag-missing-hyphen) The @param block should be followed by a parameter name and then a hyphen +// Warning: (tsdoc-undefined-tag) The TSDoc tag "@return" is not defined in this configuration +// Warning: (tsdoc-undefined-tag) The TSDoc tag "@code" is not defined in this configuration +// +// @beta +function notEqualAny(fieldName: string, arrayExpression: Expression): BooleanExpression; + +// Warning: (tsdoc-param-tag-missing-hyphen) The @param block should be followed by a parameter name and then a hyphen +// Warning: (tsdoc-param-tag-missing-hyphen) The @param block should be followed by a parameter name and then a hyphen +// Warning: (tsdoc-param-tag-missing-hyphen) The @param block should be followed by a parameter name and then a hyphen +// Warning: (tsdoc-undefined-tag) The TSDoc tag "@return" is not defined in this configuration +// Warning: (tsdoc-undefined-tag) The TSDoc tag "@code" is not defined in this configuration +// +// @beta +function or(first: BooleanExpression, second: BooleanExpression, ...more: BooleanExpression[]): BooleanExpression; + +// @beta +class Ordering implements HasUserData { + constructor(expr: Expression, direction: 'ascending' | 'descending'); + // Warning: (tsdoc-undefined-tag) The TSDoc tag "@private" is not defined in this configuration + _createdFromLiteral: boolean; + // (undocumented) + readonly direction: 'ascending' | 'descending'; + // (undocumented) + readonly expr: Expression; + // (undocumented) + _protoValueType: 'ProtoValue'; + // Warning: (tsdoc-undefined-tag) The TSDoc tag "@private" is not defined in this configuration + // + // (undocumented) + _toProto(serializer: Serializer): api.IValue; + // Warning: (tsdoc-undefined-tag) The TSDoc tag "@private" is not defined in this configuration + // + // (undocumented) + _validateUserData(ignoreUndefinedProperties: boolean): void; +} + +// @beta +class Pipeline implements firestore.Pipelines.Pipeline { + // Warning: (ae-forgotten-export) The symbol "Stage" needs to be exported by the entry point index.d.ts + constructor(db: Firestore, stages: Stage[]); + // Warning: (tsdoc-undefined-tag) The TSDoc tag "@FunctionExpression" is not defined in this configuration + // Warning: (tsdoc-param-tag-missing-hyphen) The @param block should be followed by a parameter name and then a hyphen + // Warning: (tsdoc-param-tag-missing-hyphen) The @param block should be followed by a parameter name and then a hyphen + // Warning: (tsdoc-undefined-tag) The TSDoc tag "@return" is not defined in this configuration + addFields(field: firestore.Pipelines.Selectable, ...additionalFields: firestore.Pipelines.Selectable[]): Pipeline; + // Warning: (tsdoc-undefined-tag) The TSDoc tag "@FunctionExpression" is not defined in this configuration + // Warning: (tsdoc-undefined-tag) The TSDoc tag "@return" is not defined in this configuration + addFields(options: firestore.Pipelines.AddFieldsStageOptions): Pipeline; + // Warning: (tsdoc-param-tag-missing-hyphen) The @param block should be followed by a parameter name and then a hyphen + // Warning: (tsdoc-param-tag-missing-hyphen) The @param block should be followed by a parameter name and then a hyphen + // Warning: (tsdoc-undefined-tag) The TSDoc tag "@return" is not defined in this configuration + aggregate(accumulator: firestore.Pipelines.AliasedAggregate, ...additionalAccumulators: firestore.Pipelines.AliasedAggregate[]): Pipeline; + // Warning: (tsdoc-undefined-tag) The TSDoc tag "@return" is not defined in this configuration + // Warning: (tsdoc-undefined-tag) The TSDoc tag "@code" is not defined in this configuration + aggregate(options: firestore.Pipelines.AggregateStageOptions): Pipeline; + // Warning: (tsdoc-undefined-tag) The TSDoc tag "@code" is not defined in this configuration + // Warning: (tsdoc-param-tag-missing-hyphen) The @param block should be followed by a parameter name and then a hyphen + // Warning: (tsdoc-param-tag-missing-hyphen) The @param block should be followed by a parameter name and then a hyphen + // Warning: (tsdoc-undefined-tag) The TSDoc tag "@return" is not defined in this configuration + // Warning: (tsdoc-undefined-tag) The TSDoc tag "@code" is not defined in this configuration + distinct(group: string | firestore.Pipelines.Selectable, ...additionalGroups: Array): Pipeline; + // Warning: (tsdoc-undefined-tag) The TSDoc tag "@code" is not defined in this configuration + // Warning: (tsdoc-undefined-tag) The TSDoc tag "@return" is not defined in this configuration + // Warning: (tsdoc-undefined-tag) The TSDoc tag "@code" is not defined in this configuration + distinct(options: firestore.Pipelines.DistinctStageOptions): Pipeline; + // Warning: (tsdoc-undefined-tag) The TSDoc tag "@return" is not defined in this configuration + execute(pipelineExecuteOptions?: firestore.Pipelines.PipelineExecuteOptions): Promise; + // Warning: (ae-forgotten-export) The symbol "PipelineResponse" needs to be exported by the entry point index.d.ts + // + // (undocumented) + _execute(transactionOrReadTime?: Uint8Array | Timestamp | api.ITransactionOptions, pipelineExecuteOptions?: firestore.Pipelines.PipelineExecuteOptions): Promise; + // Warning: (tsdoc-undefined-tag) The TSDoc tag "@return" is not defined in this configuration + // Warning: (tsdoc-undefined-tag) The TSDoc tag "@code" is not defined in this configuration + findNearest(options: firestore.Pipelines.FindNearestStageOptions): Pipeline; + // Warning: (tsdoc-param-tag-missing-hyphen) The @param block should be followed by a parameter name and then a hyphen + // Warning: (tsdoc-undefined-tag) The TSDoc tag "@return" is not defined in this configuration + limit(limit: number): Pipeline; + // Warning: (tsdoc-undefined-tag) The TSDoc tag "@return" is not defined in this configuration + limit(options: firestore.Pipelines.LimitStageOptions): Pipeline; + // Warning: (tsdoc-param-tag-missing-hyphen) The @param block should be followed by a parameter name and then a hyphen + // Warning: (tsdoc-undefined-tag) The TSDoc tag "@return" is not defined in this configuration + offset(offset: number): Pipeline; + // Warning: (tsdoc-undefined-tag) The TSDoc tag "@return" is not defined in this configuration + offset(options: firestore.Pipelines.OffsetStageOptions): Pipeline; + // Warning: (tsdoc-undefined-tag) The TSDoc tag "@return" is not defined in this configuration + // Warning: (tsdoc-undefined-tag) The TSDoc tag "@code" is not defined in this configuration + rawStage(name: string, params: unknown[], options?: { + [key: string]: Expression | unknown; + }): Pipeline; // Warning: (tsdoc-param-tag-missing-hyphen) The @param block should be followed by a parameter name and then a hyphen - // Warning: (tsdoc-param-tag-with-invalid-type) The @param block should not include a JSDoc-style '{type}' - // Warning: (tsdoc-escape-right-brace) The "}" character should be escaped using a backslash to avoid confusion with a TSDoc inline tag - // Warning: (tsdoc-malformed-inline-tag) Expecting a TSDoc tag starting with "{@" - static or(...filters: Filter[]): Filter; // Warning: (tsdoc-param-tag-missing-hyphen) The @param block should be followed by a parameter name and then a hyphen - // Warning: (tsdoc-param-tag-with-invalid-type) The @param block should not include a JSDoc-style '{type}' + // Warning: (tsdoc-undefined-tag) The TSDoc tag "@return" is not defined in this configuration + removeFields(fieldValue: firestore.Pipelines.Field | string, ...additionalFields: Array): Pipeline; + // Warning: (tsdoc-undefined-tag) The TSDoc tag "@return" is not defined in this configuration + removeFields(options: firestore.Pipelines.RemoveFieldsStageOptions): Pipeline; // Warning: (tsdoc-param-tag-missing-hyphen) The @param block should be followed by a parameter name and then a hyphen - // Warning: (tsdoc-param-tag-with-invalid-type) The @param block should not include a JSDoc-style '{type}' + // Warning: (tsdoc-undefined-tag) The TSDoc tag "@return" is not defined in this configuration + // Warning: (tsdoc-undefined-tag) The TSDoc tag "@code" is not defined in this configuration + replaceWith(fieldName: string): Pipeline; // Warning: (tsdoc-param-tag-missing-hyphen) The @param block should be followed by a parameter name and then a hyphen - // Warning: (tsdoc-param-tag-with-invalid-type) The @param block should not include a JSDoc-style '{type}' - // Warning: (tsdoc-escape-right-brace) The "}" character should be escaped using a backslash to avoid confusion with a TSDoc inline tag - // Warning: (tsdoc-malformed-inline-tag) Expecting a TSDoc tag starting with "{@" - static where(fieldPath: string | firestore.FieldPath, opStr: firestore.WhereFilterOp, value: unknown): Filter; -} - -// Warning: (tsdoc-undefined-tag) The TSDoc tag "@class" is not defined in this configuration -// -// @public -class Firestore implements firestore.Firestore { + // Warning: (tsdoc-undefined-tag) The TSDoc tag "@return" is not defined in this configuration + // Warning: (tsdoc-undefined-tag) The TSDoc tag "@code" is not defined in this configuration + replaceWith(expr: firestore.Pipelines.Expression): Pipeline; + // Warning: (tsdoc-undefined-tag) The TSDoc tag "@return" is not defined in this configuration + // Warning: (tsdoc-undefined-tag) The TSDoc tag "@code" is not defined in this configuration + replaceWith(options: firestore.Pipelines.ReplaceWithStageOptions): Pipeline; // Warning: (tsdoc-param-tag-missing-hyphen) The @param block should be followed by a parameter name and then a hyphen - // Warning: (tsdoc-param-tag-with-invalid-type) The @param block should not include a JSDoc-style '{type}' - // Warning: (tsdoc-escape-right-brace) The "}" character should be escaped using a backslash to avoid confusion with a TSDoc inline tag - // Warning: (tsdoc-malformed-inline-tag) Expecting a TSDoc tag starting with "{@" - // Warning: (tsdoc-param-tag-with-invalid-name) The @param block should be followed by a valid parameter name: The identifier cannot non-word characters - // Warning: (tsdoc-param-tag-with-invalid-type) The @param block should not include a JSDoc-style '{type}' - // Warning: (tsdoc-escape-right-brace) The "}" character should be escaped using a backslash to avoid confusion with a TSDoc inline tag - // Warning: (tsdoc-malformed-inline-tag) Expecting a TSDoc tag starting with "{@" - // Warning: (tsdoc-param-tag-with-invalid-name) The @param block should be followed by a valid parameter name: The identifier cannot non-word characters - // Warning: (tsdoc-param-tag-with-invalid-type) The @param block should not include a JSDoc-style '{type}' - // Warning: (tsdoc-escape-right-brace) The "}" character should be escaped using a backslash to avoid confusion with a TSDoc inline tag - // Warning: (tsdoc-escape-right-brace) The "}" character should be escaped using a backslash to avoid confusion with a TSDoc inline tag - // Warning: (tsdoc-malformed-inline-tag) Expecting a TSDoc tag starting with "{@" - // Warning: (tsdoc-malformed-inline-tag) Expecting a TSDoc tag starting with "{@" - // Warning: (tsdoc-param-tag-with-invalid-name) The @param block should be followed by a valid parameter name: The identifier cannot non-word characters - // Warning: (tsdoc-param-tag-with-invalid-type) The @param block should not include a JSDoc-style '{type}' - // Warning: (tsdoc-escape-right-brace) The "}" character should be escaped using a backslash to avoid confusion with a TSDoc inline tag - // Warning: (tsdoc-malformed-inline-tag) Expecting a TSDoc tag starting with "{@" - // Warning: (tsdoc-param-tag-with-invalid-name) The @param block should be followed by a valid parameter name: The identifier cannot non-word characters - // Warning: (tsdoc-param-tag-with-invalid-type) The @param block should not include a JSDoc-style '{type}' - // Warning: (tsdoc-escape-right-brace) The "}" character should be escaped using a backslash to avoid confusion with a TSDoc inline tag - // Warning: (tsdoc-malformed-inline-tag) Expecting a TSDoc tag starting with "{@" - // Warning: (tsdoc-param-tag-with-invalid-name) The @param block should be followed by a valid parameter name: The identifier cannot non-word characters - // Warning: (tsdoc-param-tag-with-invalid-type) The @param block should not include a JSDoc-style '{type}' - // Warning: (tsdoc-escape-right-brace) The "}" character should be escaped using a backslash to avoid confusion with a TSDoc inline tag - // Warning: (tsdoc-malformed-inline-tag) Expecting a TSDoc tag starting with "{@" - // Warning: (tsdoc-param-tag-with-invalid-name) The @param block should be followed by a valid parameter name: The identifier cannot non-word characters - // Warning: (tsdoc-param-tag-with-invalid-type) The @param block should not include a JSDoc-style '{type}' - // Warning: (tsdoc-escape-right-brace) The "}" character should be escaped using a backslash to avoid confusion with a TSDoc inline tag - // Warning: (tsdoc-malformed-inline-tag) Expecting a TSDoc tag starting with "{@" - // Warning: (tsdoc-param-tag-with-invalid-name) The @param block should be followed by a valid parameter name: The identifier cannot non-word characters - // Warning: (tsdoc-param-tag-with-invalid-type) The @param block should not include a JSDoc-style '{type}' - // Warning: (tsdoc-escape-right-brace) The "}" character should be escaped using a backslash to avoid confusion with a TSDoc inline tag - // Warning: (tsdoc-malformed-inline-tag) Expecting a TSDoc tag starting with "{@" - // Warning: (tsdoc-param-tag-with-invalid-name) The @param block should be followed by a valid parameter name: The identifier cannot non-word characters - // Warning: (tsdoc-param-tag-with-invalid-type) The @param block should not include a JSDoc-style '{type}' - constructor(settings?: firestore.Settings); + // Warning: (tsdoc-undefined-tag) The TSDoc tag "@return" is not defined in this configuration + // Warning: (tsdoc-undefined-tag) The TSDoc tag "@code" is not defined in this configuration + sample(documents: number): Pipeline; + // Warning: (tsdoc-undefined-tag) The TSDoc tag "@code" is not defined in this configuration // Warning: (tsdoc-escape-right-brace) The "}" character should be escaped using a backslash to avoid confusion with a TSDoc inline tag // Warning: (tsdoc-malformed-inline-tag) Expecting a TSDoc tag starting with "{@" - batch(): WriteBatch; - // Warning: (tsdoc-param-tag-missing-hyphen) The @param block should be followed by a parameter name and then a hyphen - // Warning: (tsdoc-param-tag-with-invalid-type) The @param block should not include a JSDoc-style '{type}' // Warning: (tsdoc-escape-right-brace) The "}" character should be escaped using a backslash to avoid confusion with a TSDoc inline tag // Warning: (tsdoc-malformed-inline-tag) Expecting a TSDoc tag starting with "{@" - bulkWriter(options?: firestore.BulkWriterOptions): BulkWriter; - // Warning: (tsdoc-param-tag-with-invalid-name) The @param block should be followed by a valid parameter name: The identifier cannot non-word characters - bundle(name?: string): BundleBuilder; + // Warning: (tsdoc-undefined-tag) The TSDoc tag "@return" is not defined in this configuration + // Warning: (tsdoc-undefined-tag) The TSDoc tag "@code" is not defined in this configuration + sample(options: firestore.Pipelines.SampleStageOptions): Pipeline; + // Warning: (tsdoc-undefined-tag) The TSDoc tag "@code" is not defined in this configuration // Warning: (tsdoc-param-tag-missing-hyphen) The @param block should be followed by a parameter name and then a hyphen - // Warning: (tsdoc-param-tag-with-invalid-type) The @param block should not include a JSDoc-style '{type}' - // Warning: (tsdoc-escape-right-brace) The "}" character should be escaped using a backslash to avoid confusion with a TSDoc inline tag - // Warning: (tsdoc-malformed-inline-tag) Expecting a TSDoc tag starting with "{@" - collection(collectionPath: string): CollectionReference; // Warning: (tsdoc-param-tag-missing-hyphen) The @param block should be followed by a parameter name and then a hyphen - // Warning: (tsdoc-param-tag-with-invalid-type) The @param block should not include a JSDoc-style '{type}' - // Warning: (tsdoc-escape-right-brace) The "}" character should be escaped using a backslash to avoid confusion with a TSDoc inline tag - // Warning: (tsdoc-malformed-inline-tag) Expecting a TSDoc tag starting with "{@" - collectionGroup(collectionId: string): CollectionGroup; - get databaseId(): string; - // Warning: (tsdoc-undefined-tag) The TSDoc tag "@private" is not defined in this configuration - // - // @internal - _decrementBulkWritersCount(): void; + // Warning: (tsdoc-undefined-tag) The TSDoc tag "@code" is not defined in this configuration + // Warning: (tsdoc-undefined-tag) The TSDoc tag "@return" is not defined in this configuration + select(selection: firestore.Pipelines.Selectable | string, ...additionalSelections: Array): Pipeline; + // Warning: (tsdoc-undefined-tag) The TSDoc tag "@code" is not defined in this configuration + // Warning: (tsdoc-undefined-tag) The TSDoc tag "@return" is not defined in this configuration + select(options: firestore.Pipelines.SelectStageOptions): Pipeline; // Warning: (tsdoc-param-tag-missing-hyphen) The @param block should be followed by a parameter name and then a hyphen - // Warning: (tsdoc-param-tag-with-invalid-type) The @param block should not include a JSDoc-style '{type}' - // Warning: (tsdoc-escape-right-brace) The "}" character should be escaped using a backslash to avoid confusion with a TSDoc inline tag - // Warning: (tsdoc-malformed-inline-tag) Expecting a TSDoc tag starting with "{@" - doc(documentPath: string): DocumentReference; - // Warning: (tsdoc-undefined-tag) The TSDoc tag "@private" is not defined in this configuration - // - // @internal - get formattedName(): string; // Warning: (tsdoc-param-tag-missing-hyphen) The @param block should be followed by a parameter name and then a hyphen - // Warning: (tsdoc-param-tag-with-invalid-type) The @param block should not include a JSDoc-style '{type}' + // Warning: (tsdoc-undefined-tag) The TSDoc tag "@return" is not defined in this configuration + // Warning: (tsdoc-undefined-tag) The TSDoc tag "@code" is not defined in this configuration + sort(ordering: firestore.Pipelines.Ordering, ...additionalOrderings: firestore.Pipelines.Ordering[]): Pipeline; + // Warning: (tsdoc-undefined-tag) The TSDoc tag "@return" is not defined in this configuration + // Warning: (tsdoc-undefined-tag) The TSDoc tag "@code" is not defined in this configuration + sort(options: firestore.Pipelines.SortStageOptions): Pipeline; // Warning: (tsdoc-escape-right-brace) The "}" character should be escaped using a backslash to avoid confusion with a TSDoc inline tag // Warning: (tsdoc-malformed-inline-tag) Expecting a TSDoc tag starting with "{@" - getAll(...documentRefsOrReadOptions: Array | firestore.ReadOptions>): Promise>>; - // Warning: (tsdoc-undefined-tag) The TSDoc tag "@private" is not defined in this configuration + stream(): NodeJS.ReadableStream; + // (undocumented) + _toProto(): api.IPipeline; + // Warning: (ae-forgotten-export) The symbol "StructuredPipeline" needs to be exported by the entry point index.d.ts // - // @internal - _incrementBulkWritersCount(): void; - // Warning: (tsdoc-undefined-tag) The TSDoc tag "@private" is not defined in this configuration + // (undocumented) + _toStructuredPipeline(pipelineExecuteOptions?: firestore.Pipelines.PipelineExecuteOptions): StructuredPipeline; + // Warning: (tsdoc-undefined-tag) The TSDoc tag "@code" is not defined in this configuration // Warning: (tsdoc-param-tag-missing-hyphen) The @param block should be followed by a parameter name and then a hyphen + // Warning: (tsdoc-undefined-tag) The TSDoc tag "@code" is not defined in this configuration // Warning: (tsdoc-undefined-tag) The TSDoc tag "@return" is not defined in this configuration - // - // @internal - initializeIfNeeded(requestTag: string): Promise; - // Warning: (tsdoc-escape-right-brace) The "}" character should be escaped using a backslash to avoid confusion with a TSDoc inline tag - // Warning: (tsdoc-malformed-inline-tag) Expecting a TSDoc tag starting with "{@" - listCollections(): Promise; - // Warning: (tsdoc-undefined-tag) The TSDoc tag "@private" is not defined in this configuration - // - // @internal - get projectId(): string; + // Warning: (tsdoc-undefined-tag) The TSDoc tag "@code" is not defined in this configuration + union(other: firestore.Pipelines.Pipeline): Pipeline; + // Warning: (tsdoc-undefined-tag) The TSDoc tag "@code" is not defined in this configuration + // Warning: (tsdoc-undefined-tag) The TSDoc tag "@return" is not defined in this configuration + // Warning: (tsdoc-undefined-tag) The TSDoc tag "@code" is not defined in this configuration + union(options: firestore.Pipelines.UnionStageOptions): Pipeline; // Warning: (tsdoc-param-tag-missing-hyphen) The @param block should be followed by a parameter name and then a hyphen // Warning: (tsdoc-param-tag-missing-hyphen) The @param block should be followed by a parameter name and then a hyphen // Warning: (tsdoc-undefined-tag) The TSDoc tag "@return" is not defined in this configuration - recursiveDelete(ref: firestore.CollectionReference | firestore.DocumentReference, bulkWriter?: BulkWriter): Promise; - // Warning: (tsdoc-undefined-tag) The TSDoc tag "@private" is not defined in this configuration - // - // @internal - _recursiveDelete(ref: firestore.CollectionReference | firestore.DocumentReference, maxPendingOps: number, minPendingOps: number, bulkWriter?: BulkWriter): Promise; - // Warning: (tsdoc-undefined-tag) The TSDoc tag "@private" is not defined in this configuration - // - // @internal - registerListener(): void; - // Warning: (tsdoc-undefined-tag) The TSDoc tag "@private" is not defined in this configuration - // Warning: (tsdoc-param-tag-missing-hyphen) The @param block should be followed by a parameter name and then a hyphen + // Warning: (tsdoc-undefined-tag) The TSDoc tag "@code" is not defined in this configuration + unnest(selectable: firestore.Pipelines.Selectable, indexField?: string): Pipeline; + // Warning: (tsdoc-undefined-tag) The TSDoc tag "@return" is not defined in this configuration + // Warning: (tsdoc-undefined-tag) The TSDoc tag "@code" is not defined in this configuration + unnest(options: firestore.Pipelines.UnnestStageOptions): Pipeline; // Warning: (tsdoc-param-tag-missing-hyphen) The @param block should be followed by a parameter name and then a hyphen // Warning: (tsdoc-param-tag-missing-hyphen) The @param block should be followed by a parameter name and then a hyphen + // Warning: (tsdoc-undefined-tag) The TSDoc tag "@return" is not defined in this configuration + // Warning: (tsdoc-undefined-tag) The TSDoc tag "@private" is not defined in this configuration + _validateUserData | HasUserData[] | HasUserData>(_: string, val: T): T; // Warning: (tsdoc-param-tag-missing-hyphen) The @param block should be followed by a parameter name and then a hyphen - // Warning: (ae-forgotten-export) The symbol "FirestoreUnaryMethod" needs to be exported by the entry point index.d.ts - // - // @internal - request(methodName: FirestoreUnaryMethod, request: Req, requestTag: string, retryCodes?: number[]): Promise; + // Warning: (tsdoc-undefined-tag) The TSDoc tag "@return" is not defined in this configuration + where(condition: firestore.Pipelines.BooleanExpression): Pipeline; + // Warning: (tsdoc-undefined-tag) The TSDoc tag "@return" is not defined in this configuration + where(options: firestore.Pipelines.WhereStageOptions): Pipeline; +} + +// @beta +class PipelineResult implements firestore.Pipelines.PipelineResult { // Warning: (tsdoc-undefined-tag) The TSDoc tag "@private" is not defined in this configuration // Warning: (tsdoc-param-tag-missing-hyphen) The @param block should be followed by a parameter name and then a hyphen // Warning: (tsdoc-param-tag-missing-hyphen) The @param block should be followed by a parameter name and then a hyphen // Warning: (tsdoc-param-tag-missing-hyphen) The @param block should be followed by a parameter name and then a hyphen // Warning: (tsdoc-param-tag-missing-hyphen) The @param block should be followed by a parameter name and then a hyphen - // Warning: (ae-forgotten-export) The symbol "FirestoreStreamingMethod" needs to be exported by the entry point index.d.ts - // - // @internal - requestStream(methodName: FirestoreStreamingMethod, bidrectional: boolean, request: {}, requestTag: string): Promise; - // Warning: (tsdoc-undefined-tag) The TSDoc tag "@template" is not defined in this configuration // Warning: (tsdoc-param-tag-missing-hyphen) The @param block should be followed by a parameter name and then a hyphen - // Warning: (tsdoc-param-tag-with-invalid-type) The @param block should not include a JSDoc-style '{type}' // Warning: (tsdoc-param-tag-missing-hyphen) The @param block should be followed by a parameter name and then a hyphen - // Warning: (tsdoc-param-tag-with-invalid-type) The @param block should not include a JSDoc-style '{type}' + constructor(serializer: Serializer, + _fieldsProto: ApiMapValue, ref?: DocumentReference, readTime?: Timestamp, createTime?: Timestamp, updateTime?: Timestamp); // Warning: (tsdoc-escape-right-brace) The "}" character should be escaped using a backslash to avoid confusion with a TSDoc inline tag // Warning: (tsdoc-malformed-inline-tag) Expecting a TSDoc tag starting with "{@" - runTransaction(updateFunction: (transaction: Transaction) => Promise, transactionOptions?: firestore.ReadWriteTransactionOptions | firestore.ReadOnlyTransactionOptions): Promise; - // Warning: (tsdoc-undefined-tag) The TSDoc tag "@private" is not defined in this configuration - // - // @internal - _serializer: Serializer | null; - // Warning: (tsdoc-param-tag-missing-hyphen) The @param block should be followed by a parameter name and then a hyphen - // Warning: (tsdoc-param-tag-with-invalid-type) The @param block should not include a JSDoc-style '{type}' - settings(settings: firestore.Settings): void; - // Warning: (tsdoc-undefined-tag) The TSDoc tag "@private" is not defined in this configuration - // - // @internal - _settings: firestore.Settings; - // Warning: (tsdoc-undefined-tag) The TSDoc tag "@private" is not defined in this configuration - // Warning: (tsdoc-param-tag-missing-hyphen) The @param block should be followed by a parameter name and then a hyphen - // Warning: (tsdoc-param-tag-missing-hyphen) The @param block should be followed by a parameter name and then a hyphen - // Warning: (tsdoc-param-tag-missing-hyphen) The @param block should be followed by a parameter name and then a hyphen - snapshot_(documentName: string, readTime?: google.protobuf.ITimestamp, encoding?: 'protobufJS'): DocumentSnapshot; - // Warning: (tsdoc-undefined-tag) The TSDoc tag "@private" is not defined in this configuration - // + // Warning: (tsdoc-undefined-tag) The TSDoc tag "@type" is not defined in this configuration + get createTime(): Timestamp | undefined; // (undocumented) - snapshot_(documentName: string, readTime: string, encoding: 'json'): DocumentSnapshot; - // Warning: (tsdoc-undefined-tag) The TSDoc tag "@private" is not defined in this configuration - // + readonly _createTime: Timestamp | undefined; + // Warning: (tsdoc-escape-right-brace) The "}" character should be escaped using a backslash to avoid confusion with a TSDoc inline tag + // Warning: (tsdoc-malformed-inline-tag) Expecting a TSDoc tag starting with "{@" + data(): firestore.DocumentData; // (undocumented) - snapshot_(document: api.IDocument, readTime: google.protobuf.ITimestamp, encoding?: 'protobufJS'): QueryDocumentSnapshot; + readonly _executionTime: Timestamp | undefined; // Warning: (tsdoc-undefined-tag) The TSDoc tag "@private" is not defined in this configuration // // (undocumented) - snapshot_(document: { - [k: string]: unknown; - }, readTime: string, encoding: 'json'): QueryDocumentSnapshot; - // Warning: (tsdoc-undefined-tag) The TSDoc tag "@return" is not defined in this configuration - terminate(): Promise; - // Warning: (tsdoc-undefined-tag) The TSDoc tag "@return" is not defined in this configuration - toJSON(): object; - // Warning: (tsdoc-undefined-tag) The TSDoc tag "@private" is not defined in this configuration - // Warning: (ae-forgotten-export) The symbol "TraceUtil" needs to be exported by the entry point index.d.ts - // - // @internal - _traceUtil: TraceUtil; - // Warning: (tsdoc-undefined-tag) The TSDoc tag "@private" is not defined in this configuration - // - // @internal - unregisterListener(): void; -} -export { Firestore } -export default Firestore; - -// Warning: (tsdoc-undefined-tag) The TSDoc tag "@class" is not defined in this configuration -// -// @public -export class GeoPoint implements Serializable, firestore.GeoPoint { - // Warning: (tsdoc-param-tag-missing-hyphen) The @param block should be followed by a parameter name and then a hyphen - // Warning: (tsdoc-param-tag-with-invalid-type) The @param block should not include a JSDoc-style '{type}' + readonly _fieldsProto: ApiMapValue; // Warning: (tsdoc-param-tag-missing-hyphen) The @param block should be followed by a parameter name and then a hyphen // Warning: (tsdoc-param-tag-with-invalid-type) The @param block should not include a JSDoc-style '{type}' - constructor(latitude: number, longitude: number); - // Warning: (tsdoc-undefined-tag) The TSDoc tag "@private" is not defined in this configuration - // - // @internal - static fromProto(proto: google.type.ILatLng): GeoPoint; + // Warning: (tsdoc-escape-right-brace) The "}" character should be escaped using a backslash to avoid confusion with a TSDoc inline tag + // Warning: (tsdoc-malformed-inline-tag) Expecting a TSDoc tag starting with "{@" + get(fieldPath: string | FieldPath): any; + // Warning: (tsdoc-escape-right-brace) The "}" character should be escaped using a backslash to avoid confusion with a TSDoc inline tag + // Warning: (tsdoc-malformed-inline-tag) Expecting a TSDoc tag starting with "{@" + // Warning: (tsdoc-undefined-tag) The TSDoc tag "@type" is not defined in this configuration + get id(): string | undefined; // Warning: (tsdoc-param-tag-missing-hyphen) The @param block should be followed by a parameter name and then a hyphen // Warning: (tsdoc-param-tag-with-invalid-type) The @param block should not include a JSDoc-style '{type}' // Warning: (tsdoc-escape-right-brace) The "}" character should be escaped using a backslash to avoid confusion with a TSDoc inline tag // Warning: (tsdoc-malformed-inline-tag) Expecting a TSDoc tag starting with "{@" // Warning: (tsdoc-undefined-tag) The TSDoc tag "@return" is not defined in this configuration - isEqual(other: firestore.GeoPoint): boolean; + isEqual(other: PipelineResult): boolean; + // Warning: (tsdoc-undefined-tag) The TSDoc tag "@private" is not defined in this configuration + // Warning: (tsdoc-param-tag-missing-hyphen) The @param block should be followed by a parameter name and then a hyphen + protoField(field: string | FieldPath): api.IValue | undefined; + get ref(): DocumentReference | undefined; // Warning: (tsdoc-escape-right-brace) The "}" character should be escaped using a backslash to avoid confusion with a TSDoc inline tag // Warning: (tsdoc-malformed-inline-tag) Expecting a TSDoc tag starting with "{@" // Warning: (tsdoc-undefined-tag) The TSDoc tag "@type" is not defined in this configuration - // Warning: (tsdoc-undefined-tag) The TSDoc tag "@name" is not defined in this configuration - get latitude(): number; + get updateTime(): Timestamp | undefined; + // (undocumented) + readonly _updateTime: Timestamp | undefined; +} + +declare namespace Pipelines { + export { + Pipeline, + PipelineResult, + PipelineSnapshot, + PipelineSource, + and, + arrayContains, + arrayContainsAny, + arrayReverse, + average, + equal, + ceil, + exp, + floor, + greaterThan, + like, + lessThan, + notEqual, + ascending, + not, + or, + regexContains, + regexMatch, + startsWith, + stringConcat, + subtract, + cosineDistance, + countDistinct, + dotProduct, + euclideanDistance, + mapGet, + lessThanOrEqual, + equalAny, + map, + array, + field, + xor, + AggregateFunction, + arrayGet, + add, + BooleanExpression, + Expression, + FunctionExpression, + minimum, + count, + countIf, + arrayLength, + stringContains, + charLength, + divide, + mod, + reverse, + trim, + toUpper, + toLower, + vectorLength, + exists, + isAbsent, + ifError, + isError, + substring, + documentId, + arrayContainsAll, + constant, + Field, + Constant, + sum, + maximum, + descending, + greaterThanOrEqual, + multiply, + conditional, + Ordering, + AliasedAggregate, + endsWith, + AliasedExpression, + mapMerge, + mapRemove, + byteLength, + logicalMaximum, + logicalMinimum, + notEqualAny, + countAll, + timestampAdd, + timestampSubtract, + timestampToUnixMicros, + timestampToUnixSeconds, + unixMicrosToTimestamp, + timestampToUnixMillis, + unixSecondsToTimestamp, + unixMillisToTimestamp, + pow, + collectionId, + length_2 as length, + ln, + round, + sqrt, + stringReverse, + abs, + arraySum, + ifAbsent, + log10, + concat, + join, + currentTimestamp, + arrayConcat, + type, + timestampTruncate, + split + } +} +export { Pipelines } + +// @beta +class PipelineSnapshot implements firestore.Pipelines.PipelineSnapshot { + // Warning: (ae-forgotten-export) The symbol "ExplainStats" needs to be exported by the entry point index.d.ts + constructor(pipeline: Pipeline, results: PipelineResult[], executionTime?: Timestamp, explainStats?: ExplainStats); // Warning: (tsdoc-escape-right-brace) The "}" character should be escaped using a backslash to avoid confusion with a TSDoc inline tag // Warning: (tsdoc-malformed-inline-tag) Expecting a TSDoc tag starting with "{@" // Warning: (tsdoc-undefined-tag) The TSDoc tag "@type" is not defined in this configuration - // Warning: (tsdoc-undefined-tag) The TSDoc tag "@name" is not defined in this configuration - get longitude(): number; + get executionTime(): Timestamp; + get explainStats(): ExplainStats | undefined; + get pipeline(): Pipeline; + get results(): PipelineResult[]; +} + +// @beta +class PipelineSource implements firestore.Pipelines.PipelineSource { + constructor(db: Firestore); + collection(collection: string | firestore.CollectionReference): Pipeline; + collection(options: firestore.Pipelines.CollectionStageOptions): Pipeline; + collectionGroup(collectionId: string): Pipeline; + collectionGroup(options: firestore.Pipelines.CollectionGroupStageOptions): Pipeline; + // Warning: (tsdoc-param-tag-missing-hyphen) The @param block should be followed by a parameter name and then a hyphen + // Warning: (tsdoc-undefined-tag) The TSDoc tag "@FirestoreError" is not defined in this configuration + createFrom(query: firestore.VectorQuery): Pipeline; + // Warning: (tsdoc-param-tag-missing-hyphen) The @param block should be followed by a parameter name and then a hyphen + // Warning: (tsdoc-undefined-tag) The TSDoc tag "@FirestoreError" is not defined in this configuration + createFrom(query: firestore.Query): Pipeline; + database(): Pipeline; + database(options: firestore.Pipelines.DatabaseStageOptions): Pipeline; + // Warning: (tsdoc-param-tag-missing-hyphen) The @param block should be followed by a parameter name and then a hyphen + // Warning: (tsdoc-undefined-tag) The TSDoc tag "@FirestoreError" is not defined in this configuration + documents(docs: Array): Pipeline; + // Warning: (tsdoc-undefined-tag) The TSDoc tag "@FirestoreError" is not defined in this configuration + documents(options: firestore.Pipelines.DocumentsStageOptions): Pipeline; + // (undocumented) + _validateReference(reference: firestore.CollectionReference | firestore.DocumentReference): reference is CollectionReference | DocumentReference; +} + +// Warning: (tsdoc-undefined-tag) The TSDoc tag "@class" is not defined in this configuration +// +// @public +export class PlanSummary implements firestore.PlanSummary { // Warning: (tsdoc-undefined-tag) The TSDoc tag "@private" is not defined in this configuration // // @internal - toProto(): api.IValue; + constructor(indexesUsed: Record[]); + // Warning: (tsdoc-undefined-tag) The TSDoc tag "@private" is not defined in this configuration + // + // @internal (undocumented) + static _fromProto(plan: IPlanSummary | null | undefined, serializer: Serializer): PlanSummary; + // (undocumented) + readonly indexesUsed: Record[]; } -// Warning: (tsdoc-undefined-tag) The TSDoc tag "@private" is not defined in this configuration +// Warning: (tsdoc-param-tag-missing-hyphen) The @param block should be followed by a parameter name and then a hyphen +// Warning: (tsdoc-param-tag-missing-hyphen) The @param block should be followed by a parameter name and then a hyphen +// Warning: (tsdoc-undefined-tag) The TSDoc tag "@return" is not defined in this configuration // -// @public -export const MAX_REQUEST_RETRIES = 5; +// @beta +function pow(base: Expression, exponent: Expression): FunctionExpression; -// Warning: (tsdoc-undefined-tag) The TSDoc tag "@class" is not defined in this configuration +// Warning: (tsdoc-param-tag-missing-hyphen) The @param block should be followed by a parameter name and then a hyphen +// Warning: (tsdoc-param-tag-missing-hyphen) The @param block should be followed by a parameter name and then a hyphen +// Warning: (tsdoc-undefined-tag) The TSDoc tag "@return" is not defined in this configuration +// +// @beta +function pow(base: Expression, exponent: number): FunctionExpression; + +// Warning: (tsdoc-param-tag-missing-hyphen) The @param block should be followed by a parameter name and then a hyphen +// Warning: (tsdoc-param-tag-missing-hyphen) The @param block should be followed by a parameter name and then a hyphen +// Warning: (tsdoc-undefined-tag) The TSDoc tag "@return" is not defined in this configuration +// +// @beta +function pow(base: string, exponent: Expression): FunctionExpression; + +// Warning: (tsdoc-param-tag-missing-hyphen) The @param block should be followed by a parameter name and then a hyphen +// Warning: (tsdoc-param-tag-missing-hyphen) The @param block should be followed by a parameter name and then a hyphen +// Warning: (tsdoc-undefined-tag) The TSDoc tag "@return" is not defined in this configuration // -// @public -export class PlanSummary implements firestore.PlanSummary { - // Warning: (tsdoc-undefined-tag) The TSDoc tag "@private" is not defined in this configuration - // - // @internal - constructor(indexesUsed: Record[]); - // Warning: (tsdoc-undefined-tag) The TSDoc tag "@private" is not defined in this configuration - // - // @internal (undocumented) - static _fromProto(plan: IPlanSummary | null | undefined, serializer: Serializer): PlanSummary; - // (undocumented) - readonly indexesUsed: Record[]; -} +// @beta +function pow(base: string, exponent: number): FunctionExpression; // Warning: (tsdoc-undefined-tag) The TSDoc tag "@class" is not defined in this configuration // @@ -1072,6 +3272,7 @@ export class Query; // (undocumented) - withConverter(converter: null): Query; - // (undocumented) - withConverter(converter: firestore.FirestoreDataConverter): Query; + withConverter(converter: firestore.FirestoreDataConverter | null): Query; +} + +// Warning: (tsdoc-undefined-tag) The TSDoc tag "@class" is not defined in this configuration +// Warning: (tsdoc-undefined-tag) The TSDoc tag "@extends" is not defined in this configuration +// +// @public +export class QueryDocumentSnapshot extends DocumentSnapshot implements firestore.QueryDocumentSnapshot { + // Warning: (tsdoc-escape-right-brace) The "}" character should be escaped using a backslash to avoid confusion with a TSDoc inline tag + // Warning: (tsdoc-malformed-inline-tag) Expecting a TSDoc tag starting with "{@" + // Warning: (tsdoc-undefined-tag) The TSDoc tag "@type" is not defined in this configuration + // Warning: (tsdoc-undefined-tag) The TSDoc tag "@name" is not defined in this configuration + // + // @override + get createTime(): Timestamp; + // Warning: (tsdoc-escape-right-brace) The "}" character should be escaped using a backslash to avoid confusion with a TSDoc inline tag + // Warning: (tsdoc-malformed-inline-tag) Expecting a TSDoc tag starting with "{@" + // + // @override + data(): AppModelType; + // Warning: (tsdoc-escape-right-brace) The "}" character should be escaped using a backslash to avoid confusion with a TSDoc inline tag + // Warning: (tsdoc-malformed-inline-tag) Expecting a TSDoc tag starting with "{@" + // Warning: (tsdoc-undefined-tag) The TSDoc tag "@type" is not defined in this configuration + // Warning: (tsdoc-undefined-tag) The TSDoc tag "@name" is not defined in this configuration + // + // @override + get updateTime(): Timestamp; +} + +// Warning: (tsdoc-undefined-tag) The TSDoc tag "@class" is not defined in this configuration +// +// @public +export class QueryPartition implements firestore.QueryPartition { + // Warning: (tsdoc-undefined-tag) The TSDoc tag "@private" is not defined in this configuration + constructor(_firestore: Firestore, _collectionId: string, _converter: firestore.FirestoreDataConverter, _startAt: api.IValue[] | undefined, _endBefore: api.IValue[] | undefined); + // Warning: (tsdoc-escape-right-brace) The "}" character should be escaped using a backslash to avoid confusion with a TSDoc inline tag + // Warning: (tsdoc-malformed-inline-tag) Expecting a TSDoc tag starting with "{@" + // Warning: (tsdoc-undefined-tag) The TSDoc tag "@type" is not defined in this configuration + // Warning: (tsdoc-escape-right-brace) The "}" character should be escaped using a backslash to avoid confusion with a TSDoc inline tag + // Warning: (tsdoc-malformed-inline-tag) Expecting a TSDoc tag starting with "{@" + // Warning: (tsdoc-undefined-tag) The TSDoc tag "@return" is not defined in this configuration + get endBefore(): unknown[] | undefined; + // Warning: (tsdoc-escape-right-brace) The "}" character should be escaped using a backslash to avoid confusion with a TSDoc inline tag + // Warning: (tsdoc-malformed-inline-tag) Expecting a TSDoc tag starting with "{@" + // Warning: (tsdoc-undefined-tag) The TSDoc tag "@type" is not defined in this configuration + // Warning: (tsdoc-escape-right-brace) The "}" character should be escaped using a backslash to avoid confusion with a TSDoc inline tag + // Warning: (tsdoc-malformed-inline-tag) Expecting a TSDoc tag starting with "{@" + // Warning: (tsdoc-undefined-tag) The TSDoc tag "@return" is not defined in this configuration + get startAt(): unknown[] | undefined; + // Warning: (tsdoc-escape-right-brace) The "}" character should be escaped using a backslash to avoid confusion with a TSDoc inline tag + // Warning: (tsdoc-malformed-inline-tag) Expecting a TSDoc tag starting with "{@" + // Warning: (tsdoc-undefined-tag) The TSDoc tag "@return" is not defined in this configuration + toQuery(): Query; +} + +// Warning: (tsdoc-undefined-tag) The TSDoc tag "@class" is not defined in this configuration +// +// @public +export class QuerySnapshot implements firestore.QuerySnapshot { + // Warning: (tsdoc-undefined-tag) The TSDoc tag "@private" is not defined in this configuration + // Warning: (tsdoc-param-tag-missing-hyphen) The @param block should be followed by a parameter name and then a hyphen + // Warning: (tsdoc-param-tag-missing-hyphen) The @param block should be followed by a parameter name and then a hyphen + // Warning: (tsdoc-param-tag-missing-hyphen) The @param block should be followed by a parameter name and then a hyphen + // Warning: (tsdoc-param-tag-missing-hyphen) The @param block should be followed by a parameter name and then a hyphen + // Warning: (tsdoc-param-tag-missing-hyphen) The @param block should be followed by a parameter name and then a hyphen + constructor(_query: Query, _readTime: Timestamp, _size: number, docs: () => Array>, changes: () => Array>); + // Warning: (tsdoc-escape-right-brace) The "}" character should be escaped using a backslash to avoid confusion with a TSDoc inline tag + // Warning: (tsdoc-malformed-inline-tag) Expecting a TSDoc tag starting with "{@" + // Warning: (tsdoc-undefined-tag) The TSDoc tag "@return" is not defined in this configuration + docChanges(): Array>; + // Warning: (tsdoc-escape-right-brace) The "}" character should be escaped using a backslash to avoid confusion with a TSDoc inline tag + // Warning: (tsdoc-malformed-inline-tag) Expecting a TSDoc tag starting with "{@" + // Warning: (tsdoc-undefined-tag) The TSDoc tag "@type" is not defined in this configuration + // Warning: (tsdoc-undefined-tag) The TSDoc tag "@name" is not defined in this configuration + get docs(): Array>; + // Warning: (tsdoc-escape-right-brace) The "}" character should be escaped using a backslash to avoid confusion with a TSDoc inline tag + // Warning: (tsdoc-malformed-inline-tag) Expecting a TSDoc tag starting with "{@" + // Warning: (tsdoc-undefined-tag) The TSDoc tag "@type" is not defined in this configuration + // Warning: (tsdoc-undefined-tag) The TSDoc tag "@name" is not defined in this configuration + get empty(): boolean; + // Warning: (tsdoc-param-tag-missing-hyphen) The @param block should be followed by a parameter name and then a hyphen + // Warning: (tsdoc-param-tag-with-invalid-type) The @param block should not include a JSDoc-style '{type}' + // Warning: (tsdoc-param-tag-missing-hyphen) The @param block should be followed by a parameter name and then a hyphen + // Warning: (tsdoc-param-tag-with-invalid-type) The @param block should not include a JSDoc-style '{type}' + forEach(callback: (result: firestore.QueryDocumentSnapshot) => void, thisArg?: unknown): void; + // Warning: (tsdoc-param-tag-missing-hyphen) The @param block should be followed by a parameter name and then a hyphen + // Warning: (tsdoc-param-tag-with-invalid-type) The @param block should not include a JSDoc-style '{type}' + // Warning: (tsdoc-escape-right-brace) The "}" character should be escaped using a backslash to avoid confusion with a TSDoc inline tag + // Warning: (tsdoc-malformed-inline-tag) Expecting a TSDoc tag starting with "{@" + // Warning: (tsdoc-undefined-tag) The TSDoc tag "@return" is not defined in this configuration + isEqual(other: firestore.QuerySnapshot): boolean; + // Warning: (tsdoc-escape-right-brace) The "}" character should be escaped using a backslash to avoid confusion with a TSDoc inline tag + // Warning: (tsdoc-malformed-inline-tag) Expecting a TSDoc tag starting with "{@" + // Warning: (tsdoc-undefined-tag) The TSDoc tag "@type" is not defined in this configuration + // Warning: (tsdoc-undefined-tag) The TSDoc tag "@name" is not defined in this configuration + get query(): Query; + // Warning: (tsdoc-escape-right-brace) The "}" character should be escaped using a backslash to avoid confusion with a TSDoc inline tag + // Warning: (tsdoc-malformed-inline-tag) Expecting a TSDoc tag starting with "{@" + // Warning: (tsdoc-undefined-tag) The TSDoc tag "@type" is not defined in this configuration + // Warning: (tsdoc-undefined-tag) The TSDoc tag "@name" is not defined in this configuration + get readTime(): Timestamp; + // Warning: (tsdoc-escape-right-brace) The "}" character should be escaped using a backslash to avoid confusion with a TSDoc inline tag + // Warning: (tsdoc-malformed-inline-tag) Expecting a TSDoc tag starting with "{@" + // Warning: (tsdoc-undefined-tag) The TSDoc tag "@type" is not defined in this configuration + // Warning: (tsdoc-undefined-tag) The TSDoc tag "@name" is not defined in this configuration + get size(): number; } -// Warning: (tsdoc-undefined-tag) The TSDoc tag "@class" is not defined in this configuration -// Warning: (tsdoc-undefined-tag) The TSDoc tag "@extends" is not defined in this configuration +// Warning: (tsdoc-param-tag-missing-hyphen) The @param block should be followed by a parameter name and then a hyphen +// Warning: (tsdoc-param-tag-missing-hyphen) The @param block should be followed by a parameter name and then a hyphen +// Warning: (tsdoc-undefined-tag) The TSDoc tag "@return" is not defined in this configuration +// Warning: (tsdoc-undefined-tag) The TSDoc tag "@code" is not defined in this configuration +// +// @beta +function regexContains(fieldName: string, pattern: string): BooleanExpression; + +// Warning: (tsdoc-param-tag-missing-hyphen) The @param block should be followed by a parameter name and then a hyphen +// Warning: (tsdoc-param-tag-missing-hyphen) The @param block should be followed by a parameter name and then a hyphen +// Warning: (tsdoc-undefined-tag) The TSDoc tag "@return" is not defined in this configuration +// Warning: (tsdoc-undefined-tag) The TSDoc tag "@code" is not defined in this configuration +// +// @beta +function regexContains(fieldName: string, pattern: Expression): BooleanExpression; + +// Warning: (tsdoc-param-tag-missing-hyphen) The @param block should be followed by a parameter name and then a hyphen +// Warning: (tsdoc-param-tag-missing-hyphen) The @param block should be followed by a parameter name and then a hyphen +// Warning: (tsdoc-undefined-tag) The TSDoc tag "@return" is not defined in this configuration +// Warning: (tsdoc-undefined-tag) The TSDoc tag "@code" is not defined in this configuration +// +// @beta +function regexContains(stringExpression: Expression, pattern: string): BooleanExpression; + +// Warning: (tsdoc-param-tag-missing-hyphen) The @param block should be followed by a parameter name and then a hyphen +// Warning: (tsdoc-param-tag-missing-hyphen) The @param block should be followed by a parameter name and then a hyphen +// Warning: (tsdoc-undefined-tag) The TSDoc tag "@return" is not defined in this configuration +// Warning: (tsdoc-undefined-tag) The TSDoc tag "@code" is not defined in this configuration +// +// @beta +function regexContains(stringExpression: Expression, pattern: Expression): BooleanExpression; + +// Warning: (tsdoc-param-tag-missing-hyphen) The @param block should be followed by a parameter name and then a hyphen +// Warning: (tsdoc-param-tag-missing-hyphen) The @param block should be followed by a parameter name and then a hyphen +// Warning: (tsdoc-undefined-tag) The TSDoc tag "@return" is not defined in this configuration +// Warning: (tsdoc-undefined-tag) The TSDoc tag "@code" is not defined in this configuration +// +// @beta +function regexMatch(fieldName: string, pattern: string): BooleanExpression; + +// Warning: (tsdoc-param-tag-missing-hyphen) The @param block should be followed by a parameter name and then a hyphen +// Warning: (tsdoc-param-tag-missing-hyphen) The @param block should be followed by a parameter name and then a hyphen +// Warning: (tsdoc-undefined-tag) The TSDoc tag "@return" is not defined in this configuration +// Warning: (tsdoc-undefined-tag) The TSDoc tag "@code" is not defined in this configuration +// +// @beta +function regexMatch(fieldName: string, pattern: Expression): BooleanExpression; + +// Warning: (tsdoc-param-tag-missing-hyphen) The @param block should be followed by a parameter name and then a hyphen +// Warning: (tsdoc-param-tag-missing-hyphen) The @param block should be followed by a parameter name and then a hyphen +// Warning: (tsdoc-undefined-tag) The TSDoc tag "@return" is not defined in this configuration +// Warning: (tsdoc-undefined-tag) The TSDoc tag "@code" is not defined in this configuration +// +// @beta +function regexMatch(stringExpression: Expression, pattern: string): BooleanExpression; + +// Warning: (tsdoc-param-tag-missing-hyphen) The @param block should be followed by a parameter name and then a hyphen +// Warning: (tsdoc-param-tag-missing-hyphen) The @param block should be followed by a parameter name and then a hyphen +// Warning: (tsdoc-undefined-tag) The TSDoc tag "@return" is not defined in this configuration +// Warning: (tsdoc-undefined-tag) The TSDoc tag "@code" is not defined in this configuration +// +// @beta +function regexMatch(stringExpression: Expression, pattern: Expression): BooleanExpression; + +// Warning: (tsdoc-param-tag-missing-hyphen) The @param block should be followed by a parameter name and then a hyphen +// Warning: (tsdoc-undefined-tag) The TSDoc tag "@return" is not defined in this configuration +// Warning: (tsdoc-undefined-tag) The TSDoc tag "@code" is not defined in this configuration +// +// @beta +function reverse(stringExpression: Expression): FunctionExpression; + +// Warning: (tsdoc-param-tag-missing-hyphen) The @param block should be followed by a parameter name and then a hyphen +// Warning: (tsdoc-undefined-tag) The TSDoc tag "@return" is not defined in this configuration +// Warning: (tsdoc-undefined-tag) The TSDoc tag "@code" is not defined in this configuration +// +// @beta +function reverse(field: string): FunctionExpression; + +// Warning: (tsdoc-param-tag-missing-hyphen) The @param block should be followed by a parameter name and then a hyphen +// Warning: (tsdoc-undefined-tag) The TSDoc tag "@return" is not defined in this configuration +// +// @beta +function round(fieldName: string): FunctionExpression; + +// Warning: (tsdoc-param-tag-missing-hyphen) The @param block should be followed by a parameter name and then a hyphen +// Warning: (tsdoc-undefined-tag) The TSDoc tag "@return" is not defined in this configuration +// +// @beta +function round(expression: Expression): FunctionExpression; + +// Warning: (tsdoc-param-tag-missing-hyphen) The @param block should be followed by a parameter name and then a hyphen +// Warning: (tsdoc-param-tag-missing-hyphen) The @param block should be followed by a parameter name and then a hyphen +// Warning: (tsdoc-undefined-tag) The TSDoc tag "@return" is not defined in this configuration +// +// @beta +function round(fieldName: string, decimalPlaces: number | Expression): FunctionExpression; + +// Warning: (tsdoc-param-tag-missing-hyphen) The @param block should be followed by a parameter name and then a hyphen +// Warning: (tsdoc-param-tag-missing-hyphen) The @param block should be followed by a parameter name and then a hyphen +// Warning: (tsdoc-undefined-tag) The TSDoc tag "@return" is not defined in this configuration +// +// @beta +function round(expression: Expression, decimalPlaces: number | Expression): FunctionExpression; + +// Warning: (tsdoc-param-tag-missing-hyphen) The @param block should be followed by a parameter name and then a hyphen +// +// @public +export function setLogFunction(logger: ((msg: string) => void) | null): void; + +// Warning: (tsdoc-param-tag-missing-hyphen) The @param block should be followed by a parameter name and then a hyphen +// Warning: (tsdoc-param-tag-missing-hyphen) The @param block should be followed by a parameter name and then a hyphen +// Warning: (tsdoc-undefined-tag) The TSDoc tag "@return" is not defined in this configuration +// Warning: (tsdoc-undefined-tag) The TSDoc tag "@code" is not defined in this configuration +// +// @beta +function split(fieldName: string, delimiter: string): FunctionExpression; + +// Warning: (tsdoc-param-tag-missing-hyphen) The @param block should be followed by a parameter name and then a hyphen +// Warning: (tsdoc-param-tag-missing-hyphen) The @param block should be followed by a parameter name and then a hyphen +// Warning: (tsdoc-undefined-tag) The TSDoc tag "@return" is not defined in this configuration +// Warning: (tsdoc-undefined-tag) The TSDoc tag "@code" is not defined in this configuration +// +// @beta +function split(fieldName: string, delimiter: Expression): FunctionExpression; + +// Warning: (tsdoc-param-tag-missing-hyphen) The @param block should be followed by a parameter name and then a hyphen +// Warning: (tsdoc-param-tag-missing-hyphen) The @param block should be followed by a parameter name and then a hyphen +// Warning: (tsdoc-undefined-tag) The TSDoc tag "@return" is not defined in this configuration +// Warning: (tsdoc-undefined-tag) The TSDoc tag "@code" is not defined in this configuration +// +// @beta +function split(expression: Expression, delimiter: string): FunctionExpression; + +// Warning: (tsdoc-param-tag-missing-hyphen) The @param block should be followed by a parameter name and then a hyphen +// Warning: (tsdoc-param-tag-missing-hyphen) The @param block should be followed by a parameter name and then a hyphen +// Warning: (tsdoc-undefined-tag) The TSDoc tag "@return" is not defined in this configuration +// Warning: (tsdoc-undefined-tag) The TSDoc tag "@code" is not defined in this configuration +// +// @beta +function split(expression: Expression, delimiter: Expression): FunctionExpression; + +// Warning: (tsdoc-param-tag-missing-hyphen) The @param block should be followed by a parameter name and then a hyphen +// Warning: (tsdoc-undefined-tag) The TSDoc tag "@return" is not defined in this configuration +// Warning: (tsdoc-undefined-tag) The TSDoc tag "@code" is not defined in this configuration +// +// @beta +function sqrt(expression: Expression): FunctionExpression; + +// Warning: (tsdoc-param-tag-missing-hyphen) The @param block should be followed by a parameter name and then a hyphen +// Warning: (tsdoc-undefined-tag) The TSDoc tag "@return" is not defined in this configuration +// Warning: (tsdoc-undefined-tag) The TSDoc tag "@code" is not defined in this configuration +// +// @beta +function sqrt(fieldName: string): FunctionExpression; + +// Warning: (tsdoc-param-tag-missing-hyphen) The @param block should be followed by a parameter name and then a hyphen +// Warning: (tsdoc-param-tag-missing-hyphen) The @param block should be followed by a parameter name and then a hyphen +// Warning: (tsdoc-undefined-tag) The TSDoc tag "@return" is not defined in this configuration +// Warning: (tsdoc-undefined-tag) The TSDoc tag "@code" is not defined in this configuration +// +// @beta +function startsWith(fieldName: string, prefix: string): BooleanExpression; + +// Warning: (tsdoc-param-tag-missing-hyphen) The @param block should be followed by a parameter name and then a hyphen +// Warning: (tsdoc-param-tag-missing-hyphen) The @param block should be followed by a parameter name and then a hyphen +// Warning: (tsdoc-undefined-tag) The TSDoc tag "@return" is not defined in this configuration +// Warning: (tsdoc-undefined-tag) The TSDoc tag "@code" is not defined in this configuration +// +// @beta +function startsWith(fieldName: string, prefix: Expression): BooleanExpression; + +// Warning: (tsdoc-param-tag-missing-hyphen) The @param block should be followed by a parameter name and then a hyphen +// Warning: (tsdoc-param-tag-missing-hyphen) The @param block should be followed by a parameter name and then a hyphen +// Warning: (tsdoc-undefined-tag) The TSDoc tag "@return" is not defined in this configuration +// Warning: (tsdoc-undefined-tag) The TSDoc tag "@code" is not defined in this configuration +// +// @beta +function startsWith(stringExpression: Expression, prefix: string): BooleanExpression; + +// Warning: (tsdoc-param-tag-missing-hyphen) The @param block should be followed by a parameter name and then a hyphen +// Warning: (tsdoc-param-tag-missing-hyphen) The @param block should be followed by a parameter name and then a hyphen +// Warning: (tsdoc-undefined-tag) The TSDoc tag "@return" is not defined in this configuration +// Warning: (tsdoc-undefined-tag) The TSDoc tag "@code" is not defined in this configuration +// +// @beta +function startsWith(stringExpression: Expression, prefix: Expression): BooleanExpression; + +// Warning: (tsdoc-param-tag-missing-hyphen) The @param block should be followed by a parameter name and then a hyphen +// Warning: (tsdoc-param-tag-missing-hyphen) The @param block should be followed by a parameter name and then a hyphen +// Warning: (tsdoc-param-tag-missing-hyphen) The @param block should be followed by a parameter name and then a hyphen +// Warning: (tsdoc-undefined-tag) The TSDoc tag "@return" is not defined in this configuration +// Warning: (tsdoc-undefined-tag) The TSDoc tag "@code" is not defined in this configuration +// +// @beta +function stringConcat(fieldName: string, secondString: Expression | string, ...otherStrings: Array): FunctionExpression; + +// Warning: (tsdoc-param-tag-missing-hyphen) The @param block should be followed by a parameter name and then a hyphen +// Warning: (tsdoc-param-tag-missing-hyphen) The @param block should be followed by a parameter name and then a hyphen +// Warning: (tsdoc-param-tag-missing-hyphen) The @param block should be followed by a parameter name and then a hyphen +// Warning: (tsdoc-undefined-tag) The TSDoc tag "@return" is not defined in this configuration +// Warning: (tsdoc-undefined-tag) The TSDoc tag "@code" is not defined in this configuration +// +// @beta +function stringConcat(firstString: Expression, secondString: Expression | string, ...otherStrings: Array): FunctionExpression; + +// Warning: (tsdoc-param-tag-missing-hyphen) The @param block should be followed by a parameter name and then a hyphen +// Warning: (tsdoc-param-tag-missing-hyphen) The @param block should be followed by a parameter name and then a hyphen +// Warning: (tsdoc-undefined-tag) The TSDoc tag "@return" is not defined in this configuration +// Warning: (tsdoc-undefined-tag) The TSDoc tag "@code" is not defined in this configuration +// +// @beta +function stringContains(fieldName: string, substring: string): BooleanExpression; + +// Warning: (tsdoc-param-tag-missing-hyphen) The @param block should be followed by a parameter name and then a hyphen +// Warning: (tsdoc-param-tag-missing-hyphen) The @param block should be followed by a parameter name and then a hyphen +// Warning: (tsdoc-undefined-tag) The TSDoc tag "@return" is not defined in this configuration +// Warning: (tsdoc-undefined-tag) The TSDoc tag "@code" is not defined in this configuration +// +// @beta +function stringContains(fieldName: string, substring: Expression): BooleanExpression; + +// Warning: (tsdoc-param-tag-missing-hyphen) The @param block should be followed by a parameter name and then a hyphen +// Warning: (tsdoc-param-tag-missing-hyphen) The @param block should be followed by a parameter name and then a hyphen +// Warning: (tsdoc-undefined-tag) The TSDoc tag "@return" is not defined in this configuration +// Warning: (tsdoc-undefined-tag) The TSDoc tag "@code" is not defined in this configuration +// +// @beta +function stringContains(stringExpression: Expression, substring: string): BooleanExpression; + +// Warning: (tsdoc-param-tag-missing-hyphen) The @param block should be followed by a parameter name and then a hyphen +// Warning: (tsdoc-param-tag-missing-hyphen) The @param block should be followed by a parameter name and then a hyphen +// Warning: (tsdoc-undefined-tag) The TSDoc tag "@return" is not defined in this configuration +// Warning: (tsdoc-undefined-tag) The TSDoc tag "@code" is not defined in this configuration +// +// @beta +function stringContains(stringExpression: Expression, substring: Expression): BooleanExpression; + +// Warning: (tsdoc-param-tag-missing-hyphen) The @param block should be followed by a parameter name and then a hyphen +// Warning: (tsdoc-undefined-tag) The TSDoc tag "@return" is not defined in this configuration +// Warning: (tsdoc-undefined-tag) The TSDoc tag "@code" is not defined in this configuration +// +// @beta +function stringReverse(stringExpression: Expression): FunctionExpression; + +// Warning: (tsdoc-param-tag-missing-hyphen) The @param block should be followed by a parameter name and then a hyphen +// Warning: (tsdoc-undefined-tag) The TSDoc tag "@return" is not defined in this configuration +// Warning: (tsdoc-undefined-tag) The TSDoc tag "@code" is not defined in this configuration +// +// @beta +function stringReverse(field: string): FunctionExpression; + +// Warning: (tsdoc-param-tag-missing-hyphen) The @param block should be followed by a parameter name and then a hyphen +// Warning: (tsdoc-param-tag-missing-hyphen) The @param block should be followed by a parameter name and then a hyphen +// Warning: (tsdoc-param-tag-missing-hyphen) The @param block should be followed by a parameter name and then a hyphen +// +// @beta +function substring(field: string, position: number, length?: number): FunctionExpression; + +// Warning: (tsdoc-param-tag-missing-hyphen) The @param block should be followed by a parameter name and then a hyphen +// Warning: (tsdoc-param-tag-missing-hyphen) The @param block should be followed by a parameter name and then a hyphen +// Warning: (tsdoc-param-tag-missing-hyphen) The @param block should be followed by a parameter name and then a hyphen +// +// @beta +function substring(input: Expression, position: number, length?: number): FunctionExpression; + +// Warning: (tsdoc-param-tag-missing-hyphen) The @param block should be followed by a parameter name and then a hyphen +// Warning: (tsdoc-param-tag-missing-hyphen) The @param block should be followed by a parameter name and then a hyphen +// Warning: (tsdoc-param-tag-missing-hyphen) The @param block should be followed by a parameter name and then a hyphen // -// @public -export class QueryDocumentSnapshot extends DocumentSnapshot implements firestore.QueryDocumentSnapshot { - // Warning: (tsdoc-escape-right-brace) The "}" character should be escaped using a backslash to avoid confusion with a TSDoc inline tag - // Warning: (tsdoc-malformed-inline-tag) Expecting a TSDoc tag starting with "{@" - // Warning: (tsdoc-undefined-tag) The TSDoc tag "@type" is not defined in this configuration - // Warning: (tsdoc-undefined-tag) The TSDoc tag "@name" is not defined in this configuration - // - // @override - get createTime(): Timestamp; - // Warning: (tsdoc-escape-right-brace) The "}" character should be escaped using a backslash to avoid confusion with a TSDoc inline tag - // Warning: (tsdoc-malformed-inline-tag) Expecting a TSDoc tag starting with "{@" - // - // @override - data(): AppModelType; - // Warning: (tsdoc-escape-right-brace) The "}" character should be escaped using a backslash to avoid confusion with a TSDoc inline tag - // Warning: (tsdoc-malformed-inline-tag) Expecting a TSDoc tag starting with "{@" - // Warning: (tsdoc-undefined-tag) The TSDoc tag "@type" is not defined in this configuration - // Warning: (tsdoc-undefined-tag) The TSDoc tag "@name" is not defined in this configuration - // - // @override - get updateTime(): Timestamp; -} +// @beta +function substring(field: string, position: Expression, length?: Expression): FunctionExpression; -// Warning: (tsdoc-undefined-tag) The TSDoc tag "@class" is not defined in this configuration +// Warning: (tsdoc-param-tag-missing-hyphen) The @param block should be followed by a parameter name and then a hyphen +// Warning: (tsdoc-param-tag-missing-hyphen) The @param block should be followed by a parameter name and then a hyphen +// Warning: (tsdoc-param-tag-missing-hyphen) The @param block should be followed by a parameter name and then a hyphen // -// @public -export class QueryPartition implements firestore.QueryPartition { - // Warning: (tsdoc-undefined-tag) The TSDoc tag "@private" is not defined in this configuration - constructor(_firestore: Firestore, _collectionId: string, _converter: firestore.FirestoreDataConverter, _startAt: api.IValue[] | undefined, _endBefore: api.IValue[] | undefined); - // Warning: (tsdoc-escape-right-brace) The "}" character should be escaped using a backslash to avoid confusion with a TSDoc inline tag - // Warning: (tsdoc-malformed-inline-tag) Expecting a TSDoc tag starting with "{@" - // Warning: (tsdoc-undefined-tag) The TSDoc tag "@type" is not defined in this configuration - // Warning: (tsdoc-escape-right-brace) The "}" character should be escaped using a backslash to avoid confusion with a TSDoc inline tag - // Warning: (tsdoc-malformed-inline-tag) Expecting a TSDoc tag starting with "{@" - // Warning: (tsdoc-undefined-tag) The TSDoc tag "@return" is not defined in this configuration - get endBefore(): unknown[] | undefined; - // Warning: (tsdoc-escape-right-brace) The "}" character should be escaped using a backslash to avoid confusion with a TSDoc inline tag - // Warning: (tsdoc-malformed-inline-tag) Expecting a TSDoc tag starting with "{@" - // Warning: (tsdoc-undefined-tag) The TSDoc tag "@type" is not defined in this configuration - // Warning: (tsdoc-escape-right-brace) The "}" character should be escaped using a backslash to avoid confusion with a TSDoc inline tag - // Warning: (tsdoc-malformed-inline-tag) Expecting a TSDoc tag starting with "{@" - // Warning: (tsdoc-undefined-tag) The TSDoc tag "@return" is not defined in this configuration - get startAt(): unknown[] | undefined; - // Warning: (tsdoc-escape-right-brace) The "}" character should be escaped using a backslash to avoid confusion with a TSDoc inline tag - // Warning: (tsdoc-malformed-inline-tag) Expecting a TSDoc tag starting with "{@" - // Warning: (tsdoc-undefined-tag) The TSDoc tag "@return" is not defined in this configuration - toQuery(): Query; -} +// @beta +function substring(input: Expression, position: Expression, length?: Expression): FunctionExpression; -// Warning: (tsdoc-undefined-tag) The TSDoc tag "@class" is not defined in this configuration +// Warning: (tsdoc-param-tag-missing-hyphen) The @param block should be followed by a parameter name and then a hyphen +// Warning: (tsdoc-param-tag-missing-hyphen) The @param block should be followed by a parameter name and then a hyphen +// Warning: (tsdoc-undefined-tag) The TSDoc tag "@return" is not defined in this configuration +// Warning: (tsdoc-undefined-tag) The TSDoc tag "@code" is not defined in this configuration // -// @public -export class QuerySnapshot implements firestore.QuerySnapshot { - // Warning: (tsdoc-undefined-tag) The TSDoc tag "@private" is not defined in this configuration - // Warning: (tsdoc-param-tag-missing-hyphen) The @param block should be followed by a parameter name and then a hyphen - // Warning: (tsdoc-param-tag-missing-hyphen) The @param block should be followed by a parameter name and then a hyphen - // Warning: (tsdoc-param-tag-missing-hyphen) The @param block should be followed by a parameter name and then a hyphen - // Warning: (tsdoc-param-tag-missing-hyphen) The @param block should be followed by a parameter name and then a hyphen - // Warning: (tsdoc-param-tag-missing-hyphen) The @param block should be followed by a parameter name and then a hyphen - constructor(_query: Query, _readTime: Timestamp, _size: number, docs: () => Array>, changes: () => Array>); - // Warning: (tsdoc-escape-right-brace) The "}" character should be escaped using a backslash to avoid confusion with a TSDoc inline tag - // Warning: (tsdoc-malformed-inline-tag) Expecting a TSDoc tag starting with "{@" - // Warning: (tsdoc-undefined-tag) The TSDoc tag "@return" is not defined in this configuration - docChanges(): Array>; - // Warning: (tsdoc-escape-right-brace) The "}" character should be escaped using a backslash to avoid confusion with a TSDoc inline tag - // Warning: (tsdoc-malformed-inline-tag) Expecting a TSDoc tag starting with "{@" - // Warning: (tsdoc-undefined-tag) The TSDoc tag "@type" is not defined in this configuration - // Warning: (tsdoc-undefined-tag) The TSDoc tag "@name" is not defined in this configuration - get docs(): Array>; - // Warning: (tsdoc-escape-right-brace) The "}" character should be escaped using a backslash to avoid confusion with a TSDoc inline tag - // Warning: (tsdoc-malformed-inline-tag) Expecting a TSDoc tag starting with "{@" - // Warning: (tsdoc-undefined-tag) The TSDoc tag "@type" is not defined in this configuration - // Warning: (tsdoc-undefined-tag) The TSDoc tag "@name" is not defined in this configuration - get empty(): boolean; - // Warning: (tsdoc-param-tag-missing-hyphen) The @param block should be followed by a parameter name and then a hyphen - // Warning: (tsdoc-param-tag-with-invalid-type) The @param block should not include a JSDoc-style '{type}' - // Warning: (tsdoc-param-tag-missing-hyphen) The @param block should be followed by a parameter name and then a hyphen - // Warning: (tsdoc-param-tag-with-invalid-type) The @param block should not include a JSDoc-style '{type}' - forEach(callback: (result: firestore.QueryDocumentSnapshot) => void, thisArg?: unknown): void; - // Warning: (tsdoc-param-tag-missing-hyphen) The @param block should be followed by a parameter name and then a hyphen - // Warning: (tsdoc-param-tag-with-invalid-type) The @param block should not include a JSDoc-style '{type}' - // Warning: (tsdoc-escape-right-brace) The "}" character should be escaped using a backslash to avoid confusion with a TSDoc inline tag - // Warning: (tsdoc-malformed-inline-tag) Expecting a TSDoc tag starting with "{@" - // Warning: (tsdoc-undefined-tag) The TSDoc tag "@return" is not defined in this configuration - isEqual(other: firestore.QuerySnapshot): boolean; - // Warning: (tsdoc-escape-right-brace) The "}" character should be escaped using a backslash to avoid confusion with a TSDoc inline tag - // Warning: (tsdoc-malformed-inline-tag) Expecting a TSDoc tag starting with "{@" - // Warning: (tsdoc-undefined-tag) The TSDoc tag "@type" is not defined in this configuration - // Warning: (tsdoc-undefined-tag) The TSDoc tag "@name" is not defined in this configuration - get query(): Query; - // Warning: (tsdoc-escape-right-brace) The "}" character should be escaped using a backslash to avoid confusion with a TSDoc inline tag - // Warning: (tsdoc-malformed-inline-tag) Expecting a TSDoc tag starting with "{@" - // Warning: (tsdoc-undefined-tag) The TSDoc tag "@type" is not defined in this configuration - // Warning: (tsdoc-undefined-tag) The TSDoc tag "@name" is not defined in this configuration - get readTime(): Timestamp; - // Warning: (tsdoc-escape-right-brace) The "}" character should be escaped using a backslash to avoid confusion with a TSDoc inline tag - // Warning: (tsdoc-malformed-inline-tag) Expecting a TSDoc tag starting with "{@" - // Warning: (tsdoc-undefined-tag) The TSDoc tag "@type" is not defined in this configuration - // Warning: (tsdoc-undefined-tag) The TSDoc tag "@name" is not defined in this configuration - get size(): number; -} +// @beta +function subtract(minuend: Expression, subtrahend: Expression): FunctionExpression; // Warning: (tsdoc-param-tag-missing-hyphen) The @param block should be followed by a parameter name and then a hyphen +// Warning: (tsdoc-param-tag-missing-hyphen) The @param block should be followed by a parameter name and then a hyphen +// Warning: (tsdoc-undefined-tag) The TSDoc tag "@return" is not defined in this configuration +// Warning: (tsdoc-undefined-tag) The TSDoc tag "@code" is not defined in this configuration // -// @public -export function setLogFunction(logger: ((msg: string) => void) | null): void; +// @beta +function subtract(minuend: Expression, subtrahend: unknown): FunctionExpression; + +// Warning: (tsdoc-param-tag-missing-hyphen) The @param block should be followed by a parameter name and then a hyphen +// Warning: (tsdoc-param-tag-missing-hyphen) The @param block should be followed by a parameter name and then a hyphen +// Warning: (tsdoc-undefined-tag) The TSDoc tag "@return" is not defined in this configuration +// Warning: (tsdoc-undefined-tag) The TSDoc tag "@code" is not defined in this configuration +// +// @beta +function subtract(minuendFieldName: string, subtrahend: Expression): FunctionExpression; + +// Warning: (tsdoc-param-tag-missing-hyphen) The @param block should be followed by a parameter name and then a hyphen +// Warning: (tsdoc-param-tag-missing-hyphen) The @param block should be followed by a parameter name and then a hyphen +// Warning: (tsdoc-undefined-tag) The TSDoc tag "@return" is not defined in this configuration +// Warning: (tsdoc-undefined-tag) The TSDoc tag "@code" is not defined in this configuration +// +// @beta +function subtract(minuendFieldName: string, subtrahend: unknown): FunctionExpression; + +// Warning: (tsdoc-param-tag-missing-hyphen) The @param block should be followed by a parameter name and then a hyphen +// Warning: (tsdoc-undefined-tag) The TSDoc tag "@return" is not defined in this configuration +// Warning: (tsdoc-undefined-tag) The TSDoc tag "@code" is not defined in this configuration +// +// @beta +function sum(expression: Expression): AggregateFunction; + +// Warning: (tsdoc-param-tag-missing-hyphen) The @param block should be followed by a parameter name and then a hyphen +// Warning: (tsdoc-undefined-tag) The TSDoc tag "@return" is not defined in this configuration +// Warning: (tsdoc-undefined-tag) The TSDoc tag "@code" is not defined in this configuration +// +// @beta +function sum(fieldName: string): AggregateFunction; // @public export class Timestamp implements firestore.Timestamp { @@ -1366,6 +3889,186 @@ export class Timestamp implements firestore.Timestamp { valueOf(): string; } +// Warning: (tsdoc-param-tag-missing-hyphen) The @param block should be followed by a parameter name and then a hyphen +// Warning: (tsdoc-param-tag-missing-hyphen) The @param block should be followed by a parameter name and then a hyphen +// Warning: (tsdoc-param-tag-missing-hyphen) The @param block should be followed by a parameter name and then a hyphen +// Warning: (tsdoc-undefined-tag) The TSDoc tag "@return" is not defined in this configuration +// Warning: (tsdoc-undefined-tag) The TSDoc tag "@code" is not defined in this configuration +// +// @beta +function timestampAdd(timestamp: Expression, unit: Expression, amount: Expression): FunctionExpression; + +// Warning: (tsdoc-param-tag-missing-hyphen) The @param block should be followed by a parameter name and then a hyphen +// Warning: (tsdoc-param-tag-missing-hyphen) The @param block should be followed by a parameter name and then a hyphen +// Warning: (tsdoc-param-tag-missing-hyphen) The @param block should be followed by a parameter name and then a hyphen +// Warning: (tsdoc-undefined-tag) The TSDoc tag "@return" is not defined in this configuration +// Warning: (tsdoc-undefined-tag) The TSDoc tag "@code" is not defined in this configuration +// +// @beta +function timestampAdd(timestamp: Expression, unit: 'microsecond' | 'millisecond' | 'second' | 'minute' | 'hour' | 'day', amount: number): FunctionExpression; + +// Warning: (tsdoc-param-tag-missing-hyphen) The @param block should be followed by a parameter name and then a hyphen +// Warning: (tsdoc-param-tag-missing-hyphen) The @param block should be followed by a parameter name and then a hyphen +// Warning: (tsdoc-param-tag-missing-hyphen) The @param block should be followed by a parameter name and then a hyphen +// Warning: (tsdoc-undefined-tag) The TSDoc tag "@return" is not defined in this configuration +// Warning: (tsdoc-undefined-tag) The TSDoc tag "@code" is not defined in this configuration +// +// @beta +function timestampAdd(fieldName: string, unit: 'microsecond' | 'millisecond' | 'second' | 'minute' | 'hour' | 'day', amount: number): FunctionExpression; + +// Warning: (tsdoc-param-tag-missing-hyphen) The @param block should be followed by a parameter name and then a hyphen +// Warning: (tsdoc-param-tag-missing-hyphen) The @param block should be followed by a parameter name and then a hyphen +// Warning: (tsdoc-param-tag-missing-hyphen) The @param block should be followed by a parameter name and then a hyphen +// Warning: (tsdoc-undefined-tag) The TSDoc tag "@return" is not defined in this configuration +// Warning: (tsdoc-undefined-tag) The TSDoc tag "@code" is not defined in this configuration +// +// @beta +function timestampSubtract(timestamp: Expression, unit: Expression, amount: Expression): FunctionExpression; + +// Warning: (tsdoc-param-tag-missing-hyphen) The @param block should be followed by a parameter name and then a hyphen +// Warning: (tsdoc-param-tag-missing-hyphen) The @param block should be followed by a parameter name and then a hyphen +// Warning: (tsdoc-param-tag-missing-hyphen) The @param block should be followed by a parameter name and then a hyphen +// Warning: (tsdoc-undefined-tag) The TSDoc tag "@return" is not defined in this configuration +// Warning: (tsdoc-undefined-tag) The TSDoc tag "@code" is not defined in this configuration +// +// @beta +function timestampSubtract(timestamp: Expression, unit: 'microsecond' | 'millisecond' | 'second' | 'minute' | 'hour' | 'day', amount: number): FunctionExpression; + +// Warning: (tsdoc-param-tag-missing-hyphen) The @param block should be followed by a parameter name and then a hyphen +// Warning: (tsdoc-param-tag-missing-hyphen) The @param block should be followed by a parameter name and then a hyphen +// Warning: (tsdoc-param-tag-missing-hyphen) The @param block should be followed by a parameter name and then a hyphen +// Warning: (tsdoc-undefined-tag) The TSDoc tag "@return" is not defined in this configuration +// Warning: (tsdoc-undefined-tag) The TSDoc tag "@code" is not defined in this configuration +// +// @beta +function timestampSubtract(fieldName: string, unit: 'microsecond' | 'millisecond' | 'second' | 'minute' | 'hour' | 'day', amount: number): FunctionExpression; + +// Warning: (tsdoc-param-tag-missing-hyphen) The @param block should be followed by a parameter name and then a hyphen +// Warning: (tsdoc-undefined-tag) The TSDoc tag "@return" is not defined in this configuration +// Warning: (tsdoc-undefined-tag) The TSDoc tag "@code" is not defined in this configuration +// +// @beta +function timestampToUnixMicros(expr: Expression): FunctionExpression; + +// Warning: (tsdoc-param-tag-missing-hyphen) The @param block should be followed by a parameter name and then a hyphen +// Warning: (tsdoc-undefined-tag) The TSDoc tag "@return" is not defined in this configuration +// Warning: (tsdoc-undefined-tag) The TSDoc tag "@code" is not defined in this configuration +// +// @beta +function timestampToUnixMicros(fieldName: string): FunctionExpression; + +// Warning: (tsdoc-param-tag-missing-hyphen) The @param block should be followed by a parameter name and then a hyphen +// Warning: (tsdoc-undefined-tag) The TSDoc tag "@return" is not defined in this configuration +// Warning: (tsdoc-undefined-tag) The TSDoc tag "@code" is not defined in this configuration +// +// @beta +function timestampToUnixMillis(expr: Expression): FunctionExpression; + +// Warning: (tsdoc-param-tag-missing-hyphen) The @param block should be followed by a parameter name and then a hyphen +// Warning: (tsdoc-undefined-tag) The TSDoc tag "@return" is not defined in this configuration +// Warning: (tsdoc-undefined-tag) The TSDoc tag "@code" is not defined in this configuration +// +// @beta +function timestampToUnixMillis(fieldName: string): FunctionExpression; + +// Warning: (tsdoc-param-tag-missing-hyphen) The @param block should be followed by a parameter name and then a hyphen +// Warning: (tsdoc-undefined-tag) The TSDoc tag "@return" is not defined in this configuration +// Warning: (tsdoc-undefined-tag) The TSDoc tag "@code" is not defined in this configuration +// +// @beta +function timestampToUnixSeconds(expr: Expression): FunctionExpression; + +// Warning: (tsdoc-param-tag-missing-hyphen) The @param block should be followed by a parameter name and then a hyphen +// Warning: (tsdoc-undefined-tag) The TSDoc tag "@return" is not defined in this configuration +// Warning: (tsdoc-undefined-tag) The TSDoc tag "@code" is not defined in this configuration +// +// @beta +function timestampToUnixSeconds(fieldName: string): FunctionExpression; + +// Warning: (tsdoc-param-tag-missing-hyphen) The @param block should be followed by a parameter name and then a hyphen +// Warning: (tsdoc-param-tag-missing-hyphen) The @param block should be followed by a parameter name and then a hyphen +// Warning: (tsdoc-param-tag-missing-hyphen) The @param block should be followed by a parameter name and then a hyphen +// Warning: (tsdoc-escape-right-brace) The "}" character should be escaped using a backslash to avoid confusion with a TSDoc inline tag +// Warning: (tsdoc-malformed-inline-tag) Expecting a TSDoc tag starting with "{@" +// Warning: (tsdoc-undefined-tag) The TSDoc tag "@return" is not defined in this configuration +// Warning: (ae-incompatible-release-tags) The symbol "timestampTruncate" is marked as @public, but its signature references "Expression" which is marked as @beta +// Warning: (ae-incompatible-release-tags) The symbol "timestampTruncate" is marked as @public, but its signature references "FunctionExpression" which is marked as @beta +// Warning: (ae-incompatible-release-tags) The symbol "timestampTruncate" is marked as @public, but its signature references "Expression" which is marked as @beta +// Warning: (ae-incompatible-release-tags) The symbol "timestampTruncate" is marked as @public, but its signature references "FunctionExpression" which is marked as @beta +// +// @public +function timestampTruncate(fieldName: string, granularity: firestore.Pipelines.TimeGranularity, timezone?: string | Expression): FunctionExpression; + +// Warning: (tsdoc-param-tag-missing-hyphen) The @param block should be followed by a parameter name and then a hyphen +// Warning: (tsdoc-param-tag-missing-hyphen) The @param block should be followed by a parameter name and then a hyphen +// Warning: (tsdoc-param-tag-missing-hyphen) The @param block should be followed by a parameter name and then a hyphen +// Warning: (tsdoc-escape-right-brace) The "}" character should be escaped using a backslash to avoid confusion with a TSDoc inline tag +// Warning: (tsdoc-malformed-inline-tag) Expecting a TSDoc tag starting with "{@" +// Warning: (tsdoc-undefined-tag) The TSDoc tag "@return" is not defined in this configuration +// Warning: (ae-incompatible-release-tags) The symbol "timestampTruncate" is marked as @public, but its signature references "Expression" which is marked as @beta +// Warning: (ae-incompatible-release-tags) The symbol "timestampTruncate" is marked as @public, but its signature references "FunctionExpression" which is marked as @beta +// Warning: (ae-incompatible-release-tags) The symbol "timestampTruncate" is marked as @public, but its signature references "Expression" which is marked as @beta +// Warning: (ae-incompatible-release-tags) The symbol "timestampTruncate" is marked as @public, but its signature references "FunctionExpression" which is marked as @beta +// +// @public +function timestampTruncate(fieldName: string, granularity: Expression, timezone?: string | Expression): FunctionExpression; + +// Warning: (tsdoc-param-tag-missing-hyphen) The @param block should be followed by a parameter name and then a hyphen +// Warning: (tsdoc-param-tag-missing-hyphen) The @param block should be followed by a parameter name and then a hyphen +// Warning: (tsdoc-param-tag-missing-hyphen) The @param block should be followed by a parameter name and then a hyphen +// Warning: (tsdoc-escape-right-brace) The "}" character should be escaped using a backslash to avoid confusion with a TSDoc inline tag +// Warning: (tsdoc-malformed-inline-tag) Expecting a TSDoc tag starting with "{@" +// Warning: (tsdoc-undefined-tag) The TSDoc tag "@return" is not defined in this configuration +// Warning: (ae-incompatible-release-tags) The symbol "timestampTruncate" is marked as @public, but its signature references "Expression" which is marked as @beta +// Warning: (ae-incompatible-release-tags) The symbol "timestampTruncate" is marked as @public, but its signature references "FunctionExpression" which is marked as @beta +// Warning: (ae-incompatible-release-tags) The symbol "timestampTruncate" is marked as @public, but its signature references "Expression" which is marked as @beta +// Warning: (ae-incompatible-release-tags) The symbol "timestampTruncate" is marked as @public, but its signature references "FunctionExpression" which is marked as @beta +// +// @public +function timestampTruncate(timestampExpression: Expression, granularity: firestore.Pipelines.TimeGranularity, timezone?: string | Expression): FunctionExpression; + +// Warning: (tsdoc-param-tag-missing-hyphen) The @param block should be followed by a parameter name and then a hyphen +// Warning: (tsdoc-param-tag-missing-hyphen) The @param block should be followed by a parameter name and then a hyphen +// Warning: (tsdoc-param-tag-missing-hyphen) The @param block should be followed by a parameter name and then a hyphen +// Warning: (tsdoc-escape-right-brace) The "}" character should be escaped using a backslash to avoid confusion with a TSDoc inline tag +// Warning: (tsdoc-malformed-inline-tag) Expecting a TSDoc tag starting with "{@" +// Warning: (tsdoc-undefined-tag) The TSDoc tag "@return" is not defined in this configuration +// Warning: (ae-incompatible-release-tags) The symbol "timestampTruncate" is marked as @public, but its signature references "Expression" which is marked as @beta +// Warning: (ae-incompatible-release-tags) The symbol "timestampTruncate" is marked as @public, but its signature references "FunctionExpression" which is marked as @beta +// Warning: (ae-incompatible-release-tags) The symbol "timestampTruncate" is marked as @public, but its signature references "Expression" which is marked as @beta +// Warning: (ae-incompatible-release-tags) The symbol "timestampTruncate" is marked as @public, but its signature references "FunctionExpression" which is marked as @beta +// +// @public +function timestampTruncate(timestampExpression: Expression, granularity: Expression, timezone?: string | Expression): FunctionExpression; + +// Warning: (tsdoc-param-tag-missing-hyphen) The @param block should be followed by a parameter name and then a hyphen +// Warning: (tsdoc-undefined-tag) The TSDoc tag "@return" is not defined in this configuration +// Warning: (tsdoc-undefined-tag) The TSDoc tag "@code" is not defined in this configuration +// +// @beta +function toLower(fieldName: string): FunctionExpression; + +// Warning: (tsdoc-param-tag-missing-hyphen) The @param block should be followed by a parameter name and then a hyphen +// Warning: (tsdoc-undefined-tag) The TSDoc tag "@return" is not defined in this configuration +// Warning: (tsdoc-undefined-tag) The TSDoc tag "@code" is not defined in this configuration +// +// @beta +function toLower(stringExpression: Expression): FunctionExpression; + +// Warning: (tsdoc-param-tag-missing-hyphen) The @param block should be followed by a parameter name and then a hyphen +// Warning: (tsdoc-undefined-tag) The TSDoc tag "@return" is not defined in this configuration +// Warning: (tsdoc-undefined-tag) The TSDoc tag "@code" is not defined in this configuration +// +// @beta +function toUpper(fieldName: string): FunctionExpression; + +// Warning: (tsdoc-param-tag-missing-hyphen) The @param block should be followed by a parameter name and then a hyphen +// Warning: (tsdoc-undefined-tag) The TSDoc tag "@return" is not defined in this configuration +// Warning: (tsdoc-undefined-tag) The TSDoc tag "@code" is not defined in this configuration +// +// @beta +function toUpper(stringExpression: Expression): FunctionExpression; + // Warning: (tsdoc-undefined-tag) The TSDoc tag "@class" is not defined in this configuration // // @public @@ -1401,6 +4104,10 @@ export class Transaction implements firestore.Transaction { // Warning: (tsdoc-escape-right-brace) The "}" character should be escaped using a backslash to avoid confusion with a TSDoc inline tag // Warning: (tsdoc-malformed-inline-tag) Expecting a TSDoc tag starting with "{@" delete(documentRef: DocumentReference, precondition?: firestore.Precondition): this; + // Warning: (tsdoc-undefined-tag) The TSDoc tag "@return" is not defined in this configuration + // Warning: (ae-incompatible-release-tags) The symbol "execute" is marked as @public, but its signature references "Pipeline" which is marked as @beta + // Warning: (ae-incompatible-release-tags) The symbol "execute" is marked as @public, but its signature references "PipelineSnapshot" which is marked as @beta + execute(pipeline: Pipeline): Promise; // Warning: (tsdoc-param-tag-missing-hyphen) The @param block should be followed by a parameter name and then a hyphen // Warning: (tsdoc-param-tag-with-invalid-type) The @param block should not include a JSDoc-style '{type}' // Warning: (tsdoc-escape-right-brace) The "}" character should be escaped using a backslash to avoid confusion with a TSDoc inline tag @@ -1451,6 +4158,92 @@ export class Transaction implements firestore.Transaction { update(documentRef: firestore.DocumentReference, dataOrField: firestore.UpdateData | string | firestore.FieldPath, ...preconditionOrValues: Array): Transaction; } +// Warning: (tsdoc-param-tag-missing-hyphen) The @param block should be followed by a parameter name and then a hyphen +// Warning: (tsdoc-param-tag-missing-hyphen) The @param block should be followed by a parameter name and then a hyphen +// Warning: (tsdoc-undefined-tag) The TSDoc tag "@return" is not defined in this configuration +// Warning: (tsdoc-undefined-tag) The TSDoc tag "@code" is not defined in this configuration +// +// @beta +function trim(fieldName: string, valueToTrim?: string | Expression): FunctionExpression; + +// Warning: (tsdoc-param-tag-missing-hyphen) The @param block should be followed by a parameter name and then a hyphen +// Warning: (tsdoc-param-tag-missing-hyphen) The @param block should be followed by a parameter name and then a hyphen +// Warning: (tsdoc-undefined-tag) The TSDoc tag "@return" is not defined in this configuration +// Warning: (tsdoc-undefined-tag) The TSDoc tag "@code" is not defined in this configuration +// +// @beta +function trim(stringExpression: Expression, valueToTrim?: string | Expression): FunctionExpression; + +// Warning: (tsdoc-escape-right-brace) The "}" character should be escaped using a backslash to avoid confusion with a TSDoc inline tag +// Warning: (tsdoc-malformed-inline-tag) Expecting a TSDoc tag starting with "{@" +// Warning: (tsdoc-undefined-tag) The TSDoc tag "@return" is not defined in this configuration +// +// @beta +function type(fieldName: string): FunctionExpression; + +// Warning: (tsdoc-escape-right-brace) The "}" character should be escaped using a backslash to avoid confusion with a TSDoc inline tag +// Warning: (tsdoc-malformed-inline-tag) Expecting a TSDoc tag starting with "{@" +// Warning: (tsdoc-undefined-tag) The TSDoc tag "@return" is not defined in this configuration +// +// @beta +function type(expression: Expression): FunctionExpression; + +// Warning: (tsdoc-param-tag-missing-hyphen) The @param block should be followed by a parameter name and then a hyphen +// Warning: (tsdoc-undefined-tag) The TSDoc tag "@return" is not defined in this configuration +// Warning: (tsdoc-undefined-tag) The TSDoc tag "@code" is not defined in this configuration +// +// @beta +function unixMicrosToTimestamp(expr: Expression): FunctionExpression; + +// Warning: (tsdoc-param-tag-missing-hyphen) The @param block should be followed by a parameter name and then a hyphen +// Warning: (tsdoc-undefined-tag) The TSDoc tag "@return" is not defined in this configuration +// Warning: (tsdoc-undefined-tag) The TSDoc tag "@code" is not defined in this configuration +// +// @beta +function unixMicrosToTimestamp(fieldName: string): FunctionExpression; + +// Warning: (tsdoc-param-tag-missing-hyphen) The @param block should be followed by a parameter name and then a hyphen +// Warning: (tsdoc-undefined-tag) The TSDoc tag "@return" is not defined in this configuration +// Warning: (tsdoc-undefined-tag) The TSDoc tag "@code" is not defined in this configuration +// +// @beta +function unixMillisToTimestamp(expr: Expression): FunctionExpression; + +// Warning: (tsdoc-param-tag-missing-hyphen) The @param block should be followed by a parameter name and then a hyphen +// Warning: (tsdoc-undefined-tag) The TSDoc tag "@return" is not defined in this configuration +// Warning: (tsdoc-undefined-tag) The TSDoc tag "@code" is not defined in this configuration +// +// @beta +function unixMillisToTimestamp(fieldName: string): FunctionExpression; + +// Warning: (tsdoc-param-tag-missing-hyphen) The @param block should be followed by a parameter name and then a hyphen +// Warning: (tsdoc-undefined-tag) The TSDoc tag "@return" is not defined in this configuration +// Warning: (tsdoc-undefined-tag) The TSDoc tag "@code" is not defined in this configuration +// +// @beta +function unixSecondsToTimestamp(expr: Expression): FunctionExpression; + +// Warning: (tsdoc-param-tag-missing-hyphen) The @param block should be followed by a parameter name and then a hyphen +// Warning: (tsdoc-undefined-tag) The TSDoc tag "@return" is not defined in this configuration +// Warning: (tsdoc-undefined-tag) The TSDoc tag "@code" is not defined in this configuration +// +// @beta +function unixSecondsToTimestamp(fieldName: string): FunctionExpression; + +// Warning: (tsdoc-param-tag-missing-hyphen) The @param block should be followed by a parameter name and then a hyphen +// Warning: (tsdoc-undefined-tag) The TSDoc tag "@return" is not defined in this configuration +// Warning: (tsdoc-undefined-tag) The TSDoc tag "@code" is not defined in this configuration +// +// @beta +function vectorLength(vectorExpression: Expression): FunctionExpression; + +// Warning: (tsdoc-param-tag-missing-hyphen) The @param block should be followed by a parameter name and then a hyphen +// Warning: (tsdoc-undefined-tag) The TSDoc tag "@return" is not defined in this configuration +// Warning: (tsdoc-undefined-tag) The TSDoc tag "@code" is not defined in this configuration +// +// @beta +function vectorLength(fieldName: string): FunctionExpression; + // @public export class VectorQuery implements firestore.VectorQuery { // Warning: (tsdoc-undefined-tag) The TSDoc tag "@private" is not defined in this configuration @@ -1482,6 +4275,10 @@ export class VectorQuery { + const results = await firestore + .pipeline() + .collection(randomCol) + .limit(1) + .replaceWith( + map({ + timestamp: new Timestamp( + Date.UTC(2025, 10, 30, 1, 2, 3) / 1000, + 456789, + ), + }), + ) + .select( + timestampTruncate('timestamp', 'year').as('trunc_year'), + timestampTruncate(field('timestamp'), 'month').as('trunc_month'), + timestampTruncate(field('timestamp'), constant('day')).as( + 'trunc_day', + ), + field('timestamp') + .timestampTruncate(constant('day'), 'MST') + .as('trunc_day_mst'), + field('timestamp').timestampTruncate('hour').as('trunc_hour'), + field('timestamp') + .timestampTruncate(constant('minute')) + .as('trunc_minute'), + field('timestamp').timestampTruncate('second').as('trunc_second'), + ) + .execute(); + + expectResults(results, { + trunc_year: new Timestamp(Date.UTC(2025, 0) / 1000, 0), + trunc_month: new Timestamp(Date.UTC(2025, 10) / 1000, 0), + trunc_day: new Timestamp(Date.UTC(2025, 10, 30) / 1000, 0), + trunc_day_mst: new Timestamp( + Date.UTC(2025, 10, 29) / 1000 + 7 * 3600, + 0, + ), + trunc_hour: new Timestamp(Date.UTC(2025, 10, 30, 1) / 1000, 0), + trunc_minute: new Timestamp(Date.UTC(2025, 10, 30, 1, 2) / 1000, 0), + trunc_second: new Timestamp( + Date.UTC(2025, 10, 30, 1, 2, 3) / 1000, + 0, + ), + }); + }); + + it('supports split', async () => { + const results = await firestore + .pipeline() + .collection(randomCol) + .limit(1) + .replaceWith( + map({ + csv: 'foo,bar,baz', + data: 'baz:bar:foo', + csvDelimeter: ',', + bytes: Uint8Array.from([0x01, 0x00, 0x02, 0x00, 0x03]), + }), + ) + .select( + split('csv', field('csvDelimeter')).as('csv'), + split(field('data'), ':').as('data'), + field('bytes') + .split(constant(Uint8Array.from([0x00]))) + .as('bytes'), + ) + .execute(); + + expectResults(results, { + csv: ['foo', 'bar', 'baz'], + data: ['baz', 'bar', 'foo'], + bytes: [ + Uint8Array.from([0x01]), + Uint8Array.from([0x02]), + Uint8Array.from([0x03]), + ], + }); + + void expect( + firestore + .pipeline() + .collection(randomCol) + .limit(1) + .replaceWith( + map({ + csv: 'foo,bar,baz', + }), + ) + .select( + field('csv') + .split(constant(Uint8Array.from([0x00]))) + .as('dontSplitStringAndBytes'), + ) + .execute(), + ).to.be.rejected; + }); + + it('supports type', async () => { + const result = await firestore + .pipeline() + .collection(randomCol) + .limit(1) + .replaceWith( + map({ + int: constant(1), + float: constant(1.1), + str: constant('a string'), + bool: constant(true), + null: constant(null), + geoPoint: constant(new GeoPoint(0.1, 0.2)), + timestamp: constant(new Timestamp(123456, 0)), + date: constant(new Date()), + bytes: constant(new Uint8Array([1, 2, 3, 4, 5, 6, 7, 0])), + docRef: constant(firestore.doc('foo/bar')), + vector: constant(FieldValue.vector([1, 2, 3])), + map: map({ + number: 1, + string: 'a string', + }), + array: array([1, 'a string']), + }), + ) + .select( + type('int').as('int'), + field('float').type().as('float'), + field('str').type().as('str'), + type('bool').as('bool'), + type('null').as('null'), + type('geoPoint').as('geoPoint'), + type('timestamp').as('timestamp'), + type('date').as('date'), + type('bytes').as('bytes'), + type('docRef').as('docRef'), + type('vector').as('vector'), + type('map').as('map'), + type('array').as('array'), + ) + .execute(); + + expectResults(result, { + int: 'int64', + float: 'float64', + str: 'string', + bool: 'boolean', + null: 'null', + geoPoint: 'geo_point', + timestamp: 'timestamp', + date: 'timestamp', + bytes: 'bytes', + docRef: 'reference', + vector: 'vector', + map: 'map', + array: 'array', + }); + }); // TODO(new-expression): Add new expression tests above this line }); diff --git a/types/firestore.d.ts b/types/firestore.d.ts index 51643b93f..17c36ba6f 100644 --- a/types/firestore.d.ts +++ b/types/firestore.d.ts @@ -3831,16 +3831,22 @@ declare namespace FirebaseFirestore { toUpper(): FunctionExpression; /** * @beta - * Creates an expression that removes leading and trailing whitespace from a string. + * Creates an expression that removes leading and trailing characters from a string or byte array. * * ```typescript * // Trim whitespace from the 'userInput' field * field("userInput").trim(); - * ``` * - * @return A new `Expression` representing the trimmed string. + * // 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. + * @return A new `Expr` representing the trimmed string or byte array. */ - trim(): FunctionExpression; + trim( + valueToTrim?: string | Expression | Uint8Array | Buffer, + ): FunctionExpression; /** * @beta * Creates an expression that concatenates string expressions together. @@ -4706,6 +4712,87 @@ declare namespace FirebaseFirestore { * @return A new {@code Expr} representing the sum of the elements in the array. */ arraySum(): FunctionExpression; + /** + * @beta + * Creates an expression that splits the result of this expression into an + * array of substrings based on the provided delimiter. + * + * @example + * ```typescript + * // Split the 'scoresCsv' field on delimiter ',' + * field('scoresCsv').split(',') + * ``` + * + * @return A new {@code Expression} representing the split function. + */ + split(delimiter: string): FunctionExpression; + + /** + * @beta + * Creates an expression that splits the result of this expression into an + * array of substrings based on the provided delimiter. + * + * @example + * ```typescript + * // Split the 'scores' field on delimiter ',' or ':' depending on the stored format + * field('scores').split(conditional(field('format').equal('csv'), constant(','), constant(':')) + * ``` + * + * @return A new {@code Expression} representing the split function. + */ + split(delimiter: Expression): FunctionExpression; + /** + * Creates an expression that truncates a timestamp to a specified granularity. + * + * @example + * ```typescript + * // Truncate the 'createdAt' timestamp to the beginning of the day. + * field('createdAt').timestampTruncate('day') + * ``` + * + * @param granularity The granularity to truncate to. + * @param timezone The timezone to use for truncation. Valid values are from + * the TZ database (e.g., "America/Los_Angeles") or in the format "Etc/GMT-1". + * @return A new {Expression} representing the truncated timestamp. + */ + timestampTruncate( + granularity: TimeGranularity, + timezone?: string | Expression, + ): FunctionExpression; + + /** + * Creates an expression that truncates a timestamp to a specified granularity. + * + * @example + * ```typescript + * // Truncate the 'createdAt' timestamp to the granularity specified in the field 'granularity'. + * field('createdAt').timestampTruncate(field('granularity')) + * ``` + * + * @param granularity The granularity to truncate to. + * @param timezone The timezone to use for truncation. Valid values are from + * the TZ database (e.g., "America/Los_Angeles") or in the format "Etc/GMT-1". + * @return A new {Expression} representing the truncated timestamp. + */ + timestampTruncate( + granularity: Expression, + timezone?: string | Expression, + ): FunctionExpression; + + /** + * @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() + * ``` + * + * @return A new {Expression} representing the data type. + */ + type(): FunctionExpression; + // TODO(new-expression): Add new expression method declarations above this line /** * @beta @@ -4752,6 +4839,32 @@ declare namespace FirebaseFirestore { */ as(name: string): AliasedExpression; } + + /** + * @beta + * Time granularity used for timestamp functions. + */ + export type TimeGranularity = + | 'microsecond' + | 'millisecond' + | 'second' + | 'minute' + | 'hour' + | 'day' + | 'week' + | 'week(monday)' + | 'week(tuesday)' + | 'week(wednesday)' + | 'week(thursday)' + | 'week(friday)' + | 'week(saturday)' + | 'week(sunday)' + | 'isoWeek' + | 'month' + | 'quarter' + | 'year' + | 'isoYear'; + /** * @beta * An interface that represents a selectable expression. @@ -7565,30 +7678,49 @@ declare namespace FirebaseFirestore { export function toUpper(stringExpression: Expression): FunctionExpression; /** * @beta - * Creates an expression that removes leading and trailing whitespace from a string field. + * + * Creates an expression that removes leading and trailing whitespace from a string or byte array. * * ```typescript * // Trim whitespace from the 'userInput' field * trim("userInput"); + * + * // Trim quotes from the 'userInput' field + * trim("userInput", '"'); * ``` * - * @param fieldName The name of the field containing the string. - * @return A new {@code Expression} representing the trimmed string. + * @param fieldName The name of the field containing the string or byte array. + * @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. + * @return A new {@code Expr} representing the trimmed string. */ - export function trim(fieldName: string): FunctionExpression; + export function trim( + fieldName: string, + valueToTrim?: string | Expression, + ): FunctionExpression; + /** * @beta - * Creates an expression that removes leading and trailing whitespace from a string expression. + * + * Creates an expression that removes leading and trailing characters from a string or byte array expression. * * ```typescript * // Trim whitespace from the 'userInput' field * trim(field("userInput")); + * + * // Trim quotes from the 'userInput' field + * trim(field("userInput"), '"'); * ``` * - * @param stringExpression The expression representing the string to trim. - * @return A new {@code Expression} representing the trimmed string. + * @param stringExpression The expression representing the string or byte array to 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. + * @return A new {@code Expr} representing the trimmed string or byte array. */ - export function trim(stringExpression: Expression): FunctionExpression; + export function trim( + stringExpression: Expression, + valueToTrim?: string | Expression, + ): FunctionExpression; /** * @beta @@ -8884,6 +9016,197 @@ declare namespace FirebaseFirestore { * @return A new {@code Expression} representing the square root of the numeric value. */ export function sqrt(fieldName: string): FunctionExpression; + /** + * @beta + * Creates an expression that splits the value of a field on the provided delimiter. + * + * @example + * ```typescript + * // Split the 'scoresCsv' field on delimiter ',' + * split('scoresCsv', ',') + * ``` + * + * @param fieldName Split the value in this field. + * @param delimiter Split on this delimiter. + * + * @return A new {@code Expression} representing the split function. + */ + export function split( + fieldName: string, + delimiter: string, + ): FunctionExpression; + + /** + * @beta + * Creates an expression that splits the value of a field on the provided delimiter. + * + * @example + * ```typescript + * // Split the 'scores' field on delimiter ',' or ':' depending on the stored format + * split('scores', conditional(field('format').equal('csv'), constant(','), constant(':')) + * ``` + * + * @param fieldName Split the value in this field. + * @param delimiter Split on this delimiter returned by evaluating this expression. + * + * @return A new {@code Expression} representing the split function. + */ + export function split( + fieldName: string, + delimiter: Expression, + ): FunctionExpression; + + /** + * @beta + * Creates an expression that splits a string into an array of substrings based on the provided delimiter. + * + * @example + * ```typescript + * // Split the 'scoresCsv' field on delimiter ',' + * split(field('scoresCsv'), ',') + * ``` + * + * @param expression Split the result of this expression. + * @param delimiter Split on this delimiter. + * + * @return A new {@code Expression} representing the split function. + */ + export function split( + expression: Expression, + delimiter: string, + ): FunctionExpression; + + /** + * @beta + * Creates an expression that splits a string into an array of substrings based on the provided delimiter. + * + * @example + * ```typescript + * // Split the 'scores' field on delimiter ',' or ':' depending on the stored format + * split(field('scores'), conditional(field('format').equal('csv'), constant(','), constant(':')) + * ``` + * + * @param expression Split the result of this expression. + * @param delimiter Split on this delimiter returned by evaluating this expression. + * + * @return A new {@code Expression} representing the split function. + */ + export function split( + expression: Expression, + delimiter: Expression, + ): FunctionExpression; + + /** + * Creates an expression that truncates a timestamp to a specified granularity. + * + * @example + * ```typescript + * // Truncate the 'createdAt' timestamp to the beginning of the day. + * field('createdAt').timestampTruncate('day') + * ``` + * + * @param fieldName Truncate the timestamp value contained in this field. + * @param granularity The granularity to truncate to. + * @param timezone The timezone to use for truncation. Valid values are from + * the TZ database (e.g., "America/Los_Angeles") or in the format "Etc/GMT-1". + * @return A new {Expression} representing the truncated timestamp. + */ + export function timestampTruncate( + fieldName: string, + granularity: TimeGranularity, + timezone?: string | Expression, + ): FunctionExpression; + + /** + * Creates an expression that truncates a timestamp to a specified granularity. + * + * @example + * ```typescript + * // Truncate the 'createdAt' timestamp to the granularity specified in the field 'granularity'. + * field('createdAt').timestampTruncate(field('granularity')) + * ``` + * + * @param fieldName Truncate the timestamp value contained in this field. + * @param granularity The granularity to truncate to. + * @param timezone The timezone to use for truncation. Valid values are from + * the TZ database (e.g., "America/Los_Angeles") or in the format "Etc/GMT-1". + * @return A new {Expression} representing the truncated timestamp. + */ + export function timestampTruncate( + fieldName: string, + granularity: Expression, + timezone?: string | Expression, + ): FunctionExpression; + + /** + * Creates an expression that truncates a timestamp to a specified granularity. + * + * @example + * ```typescript + * // Truncate the 'createdAt' timestamp to the beginning of the day. + * field('createdAt').timestampTruncate('day') + * ``` + * + * @param timestampExpression Truncate the timestamp value that is returned by this expression. + * @param granularity The granularity to truncate to. + * @param timezone The timezone to use for truncation. Valid values are from + * the TZ database (e.g., "America/Los_Angeles") or in the format "Etc/GMT-1". + * @return A new {Expression} representing the truncated timestamp. + */ + export function timestampTruncate( + timestampExpression: Expression, + granularity: TimeGranularity, + timezone?: string | Expression, + ): FunctionExpression; + + /** + * Creates an expression that truncates a timestamp to a specified granularity. + * + * @example + * ```typescript + * // Truncate the 'createdAt' timestamp to the granularity specified in the field 'granularity'. + * field('createdAt').timestampTruncate(field('granularity')) + * ``` + * + * @param timestampExpression Truncate the timestamp value that is returned by this expression. + * @param granularity The granularity to truncate to. + * @param timezone The timezone to use for truncation. Valid values are from + * the TZ database (e.g., "America/Los_Angeles") or in the format "Etc/GMT-1". + * @return A new {Expression} representing the truncated timestamp. + */ + export function timestampTruncate( + timestampExpression: Expression, + granularity: Expression, + timezone?: string | Expression, + ): FunctionExpression; + + /** + * @beta + * Creates an expression that returns the data type of the data in the specified field. + * + * @example + * ```typescript + * // Get the data type of the value in field 'title' + * type('title') + * ``` + * + * @return A new {Expression} representing the data type. + */ + export function type(fieldName: string): FunctionExpression; + /** + * @beta + * Creates an expression that returns the data type of an expression's result. + * + * @example + * ```typescript + * // Get the data type of a conditional expression + * type(conditional(exists('foo'), constant(1), constant(true))) + * ``` + * + * @return A new {Expression} representing the data type. + */ + export function type(expression: Expression): FunctionExpression; + // TODO(new-expression): Add new top-level expression function declarations above this line /** * @beta From 9e7d183d83f194e1ea45c109780b3928ce15a3a2 Mon Sep 17 00:00:00 2001 From: Mark Duckworth <1124037+MarkDuckworth@users.noreply.github.com> Date: Mon, 3 Nov 2025 16:12:28 -0700 Subject: [PATCH 46/60] Add pre-release version identifier --- package.json | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/package.json b/package.json index 6ae971484..5feb63b41 100644 --- a/package.json +++ b/package.json @@ -1,7 +1,7 @@ { "name": "@google-cloud/firestore", "description": "Firestore Client Library for Node.js", - "version": "8.0.0", + "version": "8.0.0-eap-pipelines.1", "license": "Apache-2.0", "author": "Google Inc.", "engines": { From 19bafde65033c54ba7bc62c2c47b6fd7ab9e6adf Mon Sep 17 00:00:00 2001 From: Owl Bot Date: Tue, 4 Nov 2025 17:52:42 +0000 Subject: [PATCH 47/60] =?UTF-8?q?=F0=9F=A6=89=20Updates=20from=20OwlBot=20?= =?UTF-8?q?post-processor?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit See https://github.com/googleapis/repo-automation-bots/blob/main/packages/owl-bot/README.md --- README.md | 3 ++- samples/README.md | 18 ++++++++++++++++++ 2 files changed, 20 insertions(+), 1 deletion(-) diff --git a/README.md b/README.md index e4a568405..2228739a1 100644 --- a/README.md +++ b/README.md @@ -97,7 +97,7 @@ async function quickstart() { quickstart(); ``` - +TODO (piplines) - cover Piplines getting started content ## Samples @@ -107,6 +107,7 @@ Samples are in the [`samples/`](https://github.com/googleapis/nodejs-firestore/t | Sample | Source Code | Try it | | --------------------------- | --------------------------------- | ------ | | Limit-to-last-query | [source code](https://github.com/googleapis/nodejs-firestore/blob/main/samples/limit-to-last-query.js) | [![Open in Cloud Shell][shell_img]](https://console.cloud.google.com/cloudshell/open?git_repo=https://github.com/googleapis/nodejs-firestore&page=editor&open_in_editor=samples/limit-to-last-query.js,samples/README.md) | +| Pipelines-quickstart | [source code](https://github.com/googleapis/nodejs-firestore/blob/main/samples/pipelines-quickstart.js) | [![Open in Cloud Shell][shell_img]](https://console.cloud.google.com/cloudshell/open?git_repo=https://github.com/googleapis/nodejs-firestore&page=editor&open_in_editor=samples/pipelines-quickstart.js,samples/README.md) | | Quickstart | [source code](https://github.com/googleapis/nodejs-firestore/blob/main/samples/quickstart.js) | [![Open in Cloud Shell][shell_img]](https://console.cloud.google.com/cloudshell/open?git_repo=https://github.com/googleapis/nodejs-firestore&page=editor&open_in_editor=samples/quickstart.js,samples/README.md) | | Solution-counters | [source code](https://github.com/googleapis/nodejs-firestore/blob/main/samples/solution-counters.js) | [![Open in Cloud Shell][shell_img]](https://console.cloud.google.com/cloudshell/open?git_repo=https://github.com/googleapis/nodejs-firestore&page=editor&open_in_editor=samples/solution-counters.js,samples/README.md) | diff --git a/samples/README.md b/samples/README.md index 3a6b9d555..36bf3ae3f 100644 --- a/samples/README.md +++ b/samples/README.md @@ -21,6 +21,7 @@ Applications that use Google's Server SDKs should not be used in end-user e * [Before you begin](#before-you-begin) * [Samples](#samples) * [Limit-to-last-query](#limit-to-last-query) + * [Pipelines-quickstart](#pipelines-quickstart) * [Quickstart](#quickstart) * [Solution-counters](#solution-counters) @@ -56,6 +57,23 @@ __Usage:__ +### Pipelines-quickstart + +View the [source code](https://github.com/googleapis/nodejs-firestore/blob/main/samples/pipelines-quickstart.js). + +[![Open in Cloud Shell][shell_img]](https://console.cloud.google.com/cloudshell/open?git_repo=https://github.com/googleapis/nodejs-firestore&page=editor&open_in_editor=samples/pipelines-quickstart.js,samples/README.md) + +__Usage:__ + + +`node samples/pipelines-quickstart.js` + + +----- + + + + ### Quickstart View the [source code](https://github.com/googleapis/nodejs-firestore/blob/main/samples/quickstart.js). From 3ed8a6f9d2151b07ce75d7853a9f79e59541c933 Mon Sep 17 00:00:00 2001 From: Mark Duckworth <1124037+MarkDuckworth@users.noreply.github.com> Date: Tue, 4 Nov 2025 11:00:57 -0700 Subject: [PATCH 48/60] fix copyright header year --- dev/system-test/pipeline.ts | 2 +- dev/system-test/query.ts | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/dev/system-test/pipeline.ts b/dev/system-test/pipeline.ts index 72c95d105..4280e296f 100644 --- a/dev/system-test/pipeline.ts +++ b/dev/system-test/pipeline.ts @@ -1,4 +1,4 @@ -// Copyright 2024 Google LLC +// Copyright 2025 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. diff --git a/dev/system-test/query.ts b/dev/system-test/query.ts index 99cc4cfff..51577d04c 100644 --- a/dev/system-test/query.ts +++ b/dev/system-test/query.ts @@ -1,4 +1,4 @@ -// Copyright 2024 Google LLC +// Copyright 2025 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. From 9c3e496200acbe17ba1223c4f67e0081d756d083 Mon Sep 17 00:00:00 2001 From: Mark Duckworth <1124037+MarkDuckworth@users.noreply.github.com> Date: Fri, 7 Nov 2025 16:26:43 -0700 Subject: [PATCH 49/60] update version number of pipelines prerelease: 8.1.0-eap-pipelines.2 --- package.json | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/package.json b/package.json index 5feb63b41..682bbf815 100644 --- a/package.json +++ b/package.json @@ -1,7 +1,7 @@ { "name": "@google-cloud/firestore", "description": "Firestore Client Library for Node.js", - "version": "8.0.0-eap-pipelines.1", + "version": "8.1.0-eap-pipelines.2", "license": "Apache-2.0", "author": "Google Inc.", "engines": { From 3a6e9525807c166dbbeea4a4b479696e2318cd7c Mon Sep 17 00:00:00 2001 From: Mark Duckworth <1124037+MarkDuckworth@users.noreply.github.com> Date: Fri, 7 Nov 2025 17:08:23 -0700 Subject: [PATCH 50/60] Add export ./build/src/path for backward compatible support for firebase-admin --- package.json | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/package.json b/package.json index 682bbf815..ce489c77f 100644 --- a/package.json +++ b/package.json @@ -122,6 +122,7 @@ "types": "./types/pipelines.d.ts", "default": "./build/src/pipelines/index.js" }, - "./package.json": "./package.json" + "./package.json": "./package.json", + "./build/src/path": "./build/src/path.js" } } From 67a373069020d604de1d1cc8d221e3a4ce660cfd Mon Sep 17 00:00:00 2001 From: Mark Duckworth <1124037+MarkDuckworth@users.noreply.github.com> Date: Fri, 12 Dec 2025 16:55:39 -0700 Subject: [PATCH 51/60] Update readme-partials to include samples for using the Pipelines API --- .readme-partials.yaml | 53 ++++++++++++++++++++++++++++++++++++++++++- 1 file changed, 52 insertions(+), 1 deletion(-) diff --git a/.readme-partials.yaml b/.readme-partials.yaml index af7282e76..80babd85b 100644 --- a/.readme-partials.yaml +++ b/.readme-partials.yaml @@ -10,4 +10,55 @@ introduction: |- **Note:** This Cloud Firestore Server SDK does not support Firestore databases created in [Datastore mode](https://cloud.google.com/datastore/docs/firestore-or-datastore#in_datastore_mode). To access these databases, use the [Datastore SDK](https://www.npmjs.com/package/@google-cloud/datastore). body: |- - TODO (piplines) - cover Piplines getting started content + + ### Using the Pipelines API + + ``` + const {Firestore} = require('@google-cloud/firestore'); + + // Require/import Pipelines from '@google-cloud/firestore/pipelines' + const {field} = require('@google-cloud/firestore/pipelines'); + + // Create a new client + const firestore = new Firestore({ + projectId: 'firestore-sdk-nightly', + databaseId: 'enterprise' + }); + + async function pipelinesQuickstart() { + // Obtain a collection reference. + const collection = firestore.collection('books'); + + // Enter new documents into the document. + await collection.add({ + "title": "Whispers of the Cobalt Sea", + "price": 12.99, + "author": "Elara Vance", + "yearPublished": 2023 + }); + await collection.add({ + "title": "The Antigravity Cat's Guide to Napping", + "price": 24.50, + "author": "Mittens the IV", + "yearPublished": 2026 + }); + console.log('Entered new documents into the collection.'); + + // Define a Pipeline query that selects books published this century, + // orders them by price, and computes a discounted price (20% off). + const pipeline = firestore.pipeline().collection('books') + .where(field('yearPublished').greaterThanOrEqual(2000)) + .sort(field('price').ascending()) + .select('title', 'author', field('price').multiply(0.8).as('discountedPrice')); + + // Execute the pipeline + const pipelineSnapshot = await pipeline.execute(); + console.log('Executed the Pipeline.'); + + console.log('Results:'); + pipelineSnapshot.results.forEach(pipelineResult=> { + console.log(pipelineResult.data()); + }); + } + pipelinesQuickstart(); + ``` From 73eaef6f992e9a2fae1c97eac9fa8528dc2ee3c4 Mon Sep 17 00:00:00 2001 From: Owl Bot Date: Sat, 13 Dec 2025 00:01:14 +0000 Subject: [PATCH 52/60] =?UTF-8?q?=F0=9F=A6=89=20Updates=20from=20OwlBot=20?= =?UTF-8?q?post-processor?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit See https://github.com/googleapis/repo-automation-bots/blob/main/packages/owl-bot/README.md --- README.md | 53 ++++++++++++++++++++++++++++++++++++++++++++++++++++- 1 file changed, 52 insertions(+), 1 deletion(-) diff --git a/README.md b/README.md index 2228739a1..f07ef6a49 100644 --- a/README.md +++ b/README.md @@ -97,7 +97,58 @@ async function quickstart() { quickstart(); ``` -TODO (piplines) - cover Piplines getting started content + +### Using the Pipelines API + +``` +const {Firestore} = require('@google-cloud/firestore'); + +// Require/import Pipelines from '@google-cloud/firestore/pipelines' +const {field} = require('@google-cloud/firestore/pipelines'); + +// Create a new client +const firestore = new Firestore({ + projectId: 'firestore-sdk-nightly', + databaseId: 'enterprise' +}); + +async function pipelinesQuickstart() { + // Obtain a collection reference. + const collection = firestore.collection('books'); + + // Enter new documents into the document. + await collection.add({ + "title": "Whispers of the Cobalt Sea", + "price": 12.99, + "author": "Elara Vance", + "yearPublished": 2023 + }); + await collection.add({ + "title": "The Antigravity Cat's Guide to Napping", + "price": 24.50, + "author": "Mittens the IV", + "yearPublished": 2026 + }); + console.log('Entered new documents into the collection.'); + + // Define a Pipeline query that selects books published this century, + // orders them by price, and computes a discounted price (20% off). + const pipeline = firestore.pipeline().collection('books') + .where(field('yearPublished').greaterThanOrEqual(2000)) + .sort(field('price').ascending()) + .select('title', 'author', field('price').multiply(0.8).as('discountedPrice')); + + // Execute the pipeline + const pipelineSnapshot = await pipeline.execute(); + console.log('Executed the Pipeline.'); + + console.log('Results:'); + pipelineSnapshot.results.forEach(pipelineResult=> { + console.log(pipelineResult.data()); + }); +} +pipelinesQuickstart(); +``` ## Samples From d36bb0c422cd0dce0a147b34f5aaf5817535958e Mon Sep 17 00:00:00 2001 From: Mark Duckworth <1124037+MarkDuckworth@users.noreply.github.com> Date: Fri, 12 Dec 2025 17:14:12 -0700 Subject: [PATCH 53/60] Tweaking the readme-partials to get syntax highlighting --- .readme-partials.yaml | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/.readme-partials.yaml b/.readme-partials.yaml index 80babd85b..60b13dae8 100644 --- a/.readme-partials.yaml +++ b/.readme-partials.yaml @@ -11,9 +11,10 @@ introduction: |- body: |- - ### Using the Pipelines API + ### Using the client library with Pipelines + + ```javascript - ``` const {Firestore} = require('@google-cloud/firestore'); // Require/import Pipelines from '@google-cloud/firestore/pipelines' @@ -61,4 +62,5 @@ body: |- }); } pipelinesQuickstart(); + ``` From f27a6a319633659bc626efd5c71959f269a57fff Mon Sep 17 00:00:00 2001 From: Owl Bot Date: Sat, 13 Dec 2025 00:19:25 +0000 Subject: [PATCH 54/60] =?UTF-8?q?=F0=9F=A6=89=20Updates=20from=20OwlBot=20?= =?UTF-8?q?post-processor?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit See https://github.com/googleapis/repo-automation-bots/blob/main/packages/owl-bot/README.md --- README.md | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/README.md b/README.md index f07ef6a49..70149ec5e 100644 --- a/README.md +++ b/README.md @@ -98,9 +98,10 @@ quickstart(); ``` -### Using the Pipelines API +### Using the client library with Pipelines + +```javascript -``` const {Firestore} = require('@google-cloud/firestore'); // Require/import Pipelines from '@google-cloud/firestore/pipelines' @@ -148,6 +149,7 @@ async function pipelinesQuickstart() { }); } pipelinesQuickstart(); + ``` From 0bcef581d928b0bc5167ba8642139c7d05108688 Mon Sep 17 00:00:00 2001 From: Mark Duckworth <1124037+MarkDuckworth@users.noreply.github.com> Date: Tue, 16 Dec 2025 15:31:20 -0700 Subject: [PATCH 55/60] Ignore lint errors in generated code --- .eslintrc.json | 13 +++++++++++++ package.json | 1 + 2 files changed, 14 insertions(+) diff --git a/.eslintrc.json b/.eslintrc.json index 11ab6f089..ed46c46a7 100644 --- a/.eslintrc.json +++ b/.eslintrc.json @@ -55,6 +55,19 @@ ], "@typescript-eslint/no-floating-promises": "warn" } + }, + { + "files": [ + "dev/src/v1/**/*.ts", + "dev/src/v1beta1/**/*.ts", + "dev/test/gapic_firestore_v1.ts", + "dev/test/gapic_firestore_admin_v1.ts", + "dev/test/gapic_firestore_admin_v1.ts" + ], + "rules": { + "@typescript-eslint/no-explicit-any": ["off"], + "@typescript-eslint/no-floating-promises": ["off"] + } } ] } diff --git a/package.json b/package.json index ce489c77f..36c5aa3b8 100644 --- a/package.json +++ b/package.json @@ -92,6 +92,7 @@ "chai-as-promised": "^7.1.2", "codecov": "^3.8.3", "duplexify": "^4.1.3", + "eslint-plugin-node": "^11.1.0", "execa": "^9.6.0", "extend": "^3.0.2", "fs-extra": "^11.3.0", From 8468a7ae6e767f1d42c1fa2b843c371d8ff79349 Mon Sep 17 00:00:00 2001 From: Mark Duckworth <1124037+MarkDuckworth@users.noreply.github.com> Date: Tue, 16 Dec 2025 15:33:12 -0700 Subject: [PATCH 56/60] Fixing and skipping tests when running against enterprise --- dev/src/reference/vector-query.ts | 2 +- dev/system-test/firestore.ts | 1081 ++++---- dev/system-test/pipeline.ts | 5 +- dev/system-test/query.ts | 3915 ++++++++++++++--------------- dev/system-test/tracing.ts | 14 +- dev/test/util/helpers.ts | 10 +- dev/test/util/mocha_extensions.ts | 88 + 7 files changed, 2688 insertions(+), 2427 deletions(-) create mode 100644 dev/test/util/mocha_extensions.ts diff --git a/dev/src/reference/vector-query.ts b/dev/src/reference/vector-query.ts index 11db786b2..56de19296 100644 --- a/dev/src/reference/vector-query.ts +++ b/dev/src/reference/vector-query.ts @@ -144,7 +144,7 @@ export class VectorQuery< * @private * @internal */ - _toPipeline(): Pipeline { + _pipeline(): Pipeline { const options: firestore.Pipelines.FindNearestStageOptions = { field: field(this._options.vectorField), vectorValue: this._options.queryVector, diff --git a/dev/system-test/firestore.ts b/dev/system-test/firestore.ts index bc2c6ab9c..7571316c7 100644 --- a/dev/system-test/firestore.ts +++ b/dev/system-test/firestore.ts @@ -24,6 +24,7 @@ import { } from '@google-cloud/firestore'; import {afterEach, before, beforeEach, describe, it} from 'mocha'; +import '../test/util/mocha_extensions'; import {expect, use} from 'chai'; import * as chaiAsPromised from 'chai-as-promised'; import * as extend from 'extend'; @@ -48,6 +49,7 @@ import {autoId, Deferred} from '../src/util'; import {TEST_BUNDLE_ID, verifyMetadata} from '../test/bundle'; import { bundleToElementArray, + isEnterprise, Post, postConverter, postConverterMerge, @@ -169,7 +171,7 @@ describe('Firestore class', () => { }); }); - it('can plan a query using default options', async () => { + it.skipEnterprise('can plan a query using default options', async () => { await randomCol.doc('doc1').set({foo: 1}); await randomCol.doc('doc2').set({foo: 2}); await randomCol.doc('doc3').set({foo: 1}); @@ -189,7 +191,7 @@ describe('Firestore class', () => { expect(explainResults.snapshot).to.be.null; }); - it('can plan a query', async () => { + it.skipEnterprise('can plan a query', async () => { await randomCol.doc('doc1').set({foo: 1}); await randomCol.doc('doc2').set({foo: 2}); await randomCol.doc('doc3').set({foo: 1}); @@ -211,7 +213,7 @@ describe('Firestore class', () => { expect(explainResults.snapshot).to.be.null; }); - it('can profile a query', async () => { + it.skipEnterprise('can profile a query', async () => { await randomCol.doc('doc1').set({foo: 1, bar: 0}); await randomCol.doc('doc2').set({foo: 2, bar: 1}); await randomCol.doc('doc3').set({foo: 1, bar: 2}); @@ -241,77 +243,83 @@ describe('Firestore class', () => { expect(explainResults.snapshot!.size).to.equal(2); }); - it('can profile a query that does not match any docs', async () => { - await randomCol.doc('doc1').set({foo: 1, bar: 0}); - await randomCol.doc('doc2').set({foo: 2, bar: 1}); - await randomCol.doc('doc3').set({foo: 1, bar: 2}); - const results = await randomCol.where('foo', '==', 12345).get(); - expect(results.empty).to.be.true; - expect(results.docs.length).to.equal(0); - expect(results.readTime.toMillis()).to.be.greaterThan(0); + it.skipEnterprise( + 'can profile a query that does not match any docs', + async () => { + await randomCol.doc('doc1').set({foo: 1, bar: 0}); + await randomCol.doc('doc2').set({foo: 2, bar: 1}); + await randomCol.doc('doc3').set({foo: 1, bar: 2}); + const results = await randomCol.where('foo', '==', 12345).get(); + expect(results.empty).to.be.true; + expect(results.docs.length).to.equal(0); + expect(results.readTime.toMillis()).to.be.greaterThan(0); - const explainResults = await randomCol - .where('foo', '==', 12345) - .explain({analyze: true}); + const explainResults = await randomCol + .where('foo', '==', 12345) + .explain({analyze: true}); - const metrics = explainResults.metrics; + const metrics = explainResults.metrics; - expect(metrics.planSummary).to.not.be.null; - expect(metrics.executionStats).to.not.be.null; - expect(explainResults.snapshot).to.not.be.null; + expect(metrics.planSummary).to.not.be.null; + expect(metrics.executionStats).to.not.be.null; + expect(explainResults.snapshot).to.not.be.null; - expect( - Object.keys(metrics.planSummary.indexesUsed).length, - ).to.be.greaterThan(0); + expect( + Object.keys(metrics.planSummary.indexesUsed).length, + ).to.be.greaterThan(0); - const stats = metrics.executionStats!; - expect(stats.readOperations).to.be.greaterThan(0); - expect(stats.resultsReturned).to.be.equal(0); - expect( - stats.executionDuration.nanoseconds > 0 || - stats.executionDuration.seconds > 0, - ).to.be.true; - expect(Object.keys(stats.debugStats).length).to.be.greaterThan(0); + const stats = metrics.executionStats!; + expect(stats.readOperations).to.be.greaterThan(0); + expect(stats.resultsReturned).to.be.equal(0); + expect( + stats.executionDuration.nanoseconds > 0 || + stats.executionDuration.seconds > 0, + ).to.be.true; + expect(Object.keys(stats.debugStats).length).to.be.greaterThan(0); - expect(explainResults.snapshot!.size).to.equal(0); - }); + expect(explainResults.snapshot!.size).to.equal(0); + }, + ); - it('can stream explain results with default options', async () => { - await randomCol.doc('doc1').set({foo: 1, bar: 0}); - await randomCol.doc('doc2').set({foo: 2, bar: 1}); - await randomCol.doc('doc3').set({foo: 1, bar: 2}); - let totalResponses = 0; - let totalDocuments = 0; - let metrics: ExplainMetrics | null = null; - const stream = randomCol.explainStream(); - const promise = new Promise((resolve, reject) => { - stream.on('data', data => { - ++totalResponses; - if (data.document) { - ++totalDocuments; - } - if (data.metrics) { - metrics = data.metrics; - } - }); - stream.on('end', () => { - expect(totalResponses).to.equal(1); - expect(totalDocuments).to.equal(0); - expect(metrics).to.not.be.null; - expect(metrics!.planSummary.indexesUsed.length).to.be.greaterThan(0); - expect(metrics!.executionStats).to.be.null; - resolve(true); - }); - stream.on('error', (error: Error) => { - reject(error); + it.skipEnterprise( + 'can stream explain results with default options', + async () => { + await randomCol.doc('doc1').set({foo: 1, bar: 0}); + await randomCol.doc('doc2').set({foo: 2, bar: 1}); + await randomCol.doc('doc3').set({foo: 1, bar: 2}); + let totalResponses = 0; + let totalDocuments = 0; + let metrics: ExplainMetrics | null = null; + const stream = randomCol.explainStream(); + const promise = new Promise((resolve, reject) => { + stream.on('data', data => { + ++totalResponses; + if (data.document) { + ++totalDocuments; + } + if (data.metrics) { + metrics = data.metrics; + } + }); + stream.on('end', () => { + expect(totalResponses).to.equal(1); + expect(totalDocuments).to.equal(0); + expect(metrics).to.not.be.null; + expect(metrics!.planSummary.indexesUsed.length).to.be.greaterThan(0); + expect(metrics!.executionStats).to.be.null; + resolve(true); + }); + stream.on('error', (error: Error) => { + reject(error); + }); }); - }); - const success: boolean = await promise; - expect(success).to.be.true; - }); + const success: boolean = await promise; + expect(success).to.be.true; + }, + ); - it('can stream explain results without analyze', async () => { + it.skipEnterprise('can stream explain results without analyze', async () => { await randomCol.doc('doc1').set({foo: 1, bar: 0}); await randomCol.doc('doc2').set({foo: 2, bar: 1}); await randomCol.doc('doc3').set({foo: 1, bar: 2}); @@ -346,7 +354,7 @@ describe('Firestore class', () => { expect(success).to.be.true; }); - it('can stream explain results with analyze', async () => { + it.skipEnterprise('can stream explain results with analyze', async () => { await randomCol.doc('doc1').set({foo: 1, bar: 0}); await randomCol.doc('doc2').set({foo: 2, bar: 1}); await randomCol.doc('doc3').set({foo: 1, bar: 2}); @@ -384,26 +392,29 @@ describe('Firestore class', () => { expect(success).to.be.true; }); - it('can plan an aggregate query using default options', async () => { - await randomCol.doc('doc1').set({foo: 1}); - await randomCol.doc('doc2').set({foo: 2}); - await randomCol.doc('doc3').set({foo: 1}); - const explainResults = await randomCol - .where('foo', '>', 0) - .count() - .explain(); + it.skipEnterprise( + 'can plan an aggregate query using default options', + async () => { + await randomCol.doc('doc1').set({foo: 1}); + await randomCol.doc('doc2').set({foo: 2}); + await randomCol.doc('doc3').set({foo: 1}); + const explainResults = await randomCol + .where('foo', '>', 0) + .count() + .explain(); - const metrics = explainResults.metrics; + const metrics = explainResults.metrics; - const plan = metrics.planSummary; - expect(plan).to.not.be.null; - expect(Object.keys(plan.indexesUsed).length).to.be.greaterThan(0); + const plan = metrics.planSummary; + expect(plan).to.not.be.null; + expect(Object.keys(plan.indexesUsed).length).to.be.greaterThan(0); - expect(metrics.executionStats).to.be.null; - expect(explainResults.snapshot).to.be.null; - }); + expect(metrics.executionStats).to.be.null; + expect(explainResults.snapshot).to.be.null; + }, + ); - it('can plan an aggregate query', async () => { + it.skipEnterprise('can plan an aggregate query', async () => { await randomCol.doc('doc1').set({foo: 1}); await randomCol.doc('doc2').set({foo: 2}); await randomCol.doc('doc3').set({foo: 1}); @@ -422,7 +433,7 @@ describe('Firestore class', () => { expect(explainResults.snapshot).to.be.null; }); - it('can profile an aggregate query', async () => { + it.skipEnterprise('can profile an aggregate query', async () => { await randomCol.doc('doc1').set({foo: 1}); await randomCol.doc('doc2').set({foo: 2}); await randomCol.doc('doc3').set({foo: 1}); @@ -451,7 +462,7 @@ describe('Firestore class', () => { expect(explainResults.snapshot!.data().count).to.equal(3); }); - it('can plan a vector query', async () => { + it.skipEnterprise('can plan a vector query', async () => { const indexTestHelper = new IndexTestHelper(firestore); const collectionReference = await indexTestHelper.createTestDocs([ @@ -483,7 +494,7 @@ describe('Firestore class', () => { expect(explainResults.snapshot).to.be.null; }); - it('can profile a vector query', async () => { + it.skipEnterprise('can profile a vector query', async () => { const indexTestHelper = new IndexTestHelper(firestore); const collectionReference = await indexTestHelper.createTestDocs([ @@ -610,128 +621,125 @@ describe('Firestore class', () => { // Skip partition query tests when running against the emulator because // partition queries are not supported by the emulator. -(process.env.FIRESTORE_EMULATOR_HOST === undefined ? describe : describe.skip)( - 'CollectionGroup class', - () => { - const desiredPartitionCount = 3; - const documentCount = 2 * 128 + 127; // Minimum partition size is 128. - - let firestore: Firestore; - let randomColl: CollectionReference; - let collectionGroup: CollectionGroup; +describe.skipEmulator.skipEnterprise('CollectionGroup class', () => { + const desiredPartitionCount = 3; + const documentCount = 2 * 128 + 127; // Minimum partition size is 128. - before(async () => { - randomColl = getTestRoot(); - firestore = randomColl.firestore; - collectionGroup = firestore.collectionGroup(randomColl.id); + let firestore: Firestore; + let randomColl: CollectionReference; + let collectionGroup: CollectionGroup; - const batch = firestore.batch(); - for (let i = 0; i < documentCount; ++i) { - batch.create(randomColl.doc(), {title: 'post', author: 'author'}); - } - await batch.commit(); - }); + before(async () => { + randomColl = getTestRoot(); + firestore = randomColl.firestore; + collectionGroup = firestore.collectionGroup(randomColl.id); - async function getPartitions( - collectionGroup: CollectionGroup, - desiredPartitionsCount: number, - ): Promise[]> { - const partitions: QueryPartition[] = []; - for await (const partition of collectionGroup.getPartitions( - desiredPartitionsCount, - )) { - partitions.push(partition); - } - return partitions; + const batch = firestore.batch(); + for (let i = 0; i < documentCount; ++i) { + batch.create(randomColl.doc(), {title: 'post', author: 'author'}); } + await batch.commit(); + }); - async function verifyPartitions( - partitions: QueryPartition[], - ): Promise[]> { - expect(partitions.length).to.not.be.greaterThan(desiredPartitionCount); + async function getPartitions( + collectionGroup: CollectionGroup, + desiredPartitionsCount: number, + ): Promise[]> { + const partitions: QueryPartition[] = []; + for await (const partition of collectionGroup.getPartitions( + desiredPartitionsCount, + )) { + partitions.push(partition); + } + return partitions; + } - expect(partitions[0].startAt).to.be.undefined; - for (let i = 0; i < partitions.length - 1; ++i) { - // The cursor value is a single DocumentReference - expect( - (partitions[i].endBefore![0] as DocumentReference).isEqual( - partitions[i + 1].startAt![0] as DocumentReference, - ), - ).to.be.true; - } - expect(partitions[partitions.length - 1].endBefore).to.be.undefined; + async function verifyPartitions( + partitions: QueryPartition[], + ): Promise[]> { + expect(partitions.length).to.not.be.greaterThan(desiredPartitionCount); - // Validate that we can use the partitions to read the original documents. - const documents: QueryDocumentSnapshot[] = []; - for (const partition of partitions) { - documents.push(...(await partition.toQuery().get()).docs); - } - expect(documents.length).to.equal(documentCount); + expect(partitions[0].startAt).to.be.undefined; + for (let i = 0; i < partitions.length - 1; ++i) { + // The cursor value is a single DocumentReference + expect( + (partitions[i].endBefore![0] as DocumentReference).isEqual( + partitions[i + 1].startAt![0] as DocumentReference, + ), + ).to.be.true; + } + expect(partitions[partitions.length - 1].endBefore).to.be.undefined; - return documents; + // Validate that we can use the partitions to read the original documents. + const documents: QueryDocumentSnapshot[] = []; + for (const partition of partitions) { + documents.push(...(await partition.toQuery().get()).docs); } + expect(documents.length).to.equal(documentCount); - it('partition query', async () => { - const partitions = await getPartitions( - collectionGroup, - desiredPartitionCount, - ); - await verifyPartitions(partitions); - }); + return documents; + } - it('partition query with manual cursors', async () => { - const partitions = await getPartitions( - collectionGroup, - desiredPartitionCount, - ); + it('partition query', async () => { + const partitions = await getPartitions( + collectionGroup, + desiredPartitionCount, + ); + await verifyPartitions(partitions); + }); - const documents: QueryDocumentSnapshot[] = []; - for (const partition of partitions) { - let partitionedQuery: Query = collectionGroup.orderBy( - FieldPath.documentId(), - ); - if (partition.startAt) { - partitionedQuery = partitionedQuery.startAt(...partition.startAt); - } - if (partition.endBefore) { - partitionedQuery = partitionedQuery.endBefore(...partition.endBefore); - } - documents.push(...(await partitionedQuery.get()).docs); + it('partition query with manual cursors', async () => { + const partitions = await getPartitions( + collectionGroup, + desiredPartitionCount, + ); + + const documents: QueryDocumentSnapshot[] = []; + for (const partition of partitions) { + let partitionedQuery: Query = collectionGroup.orderBy( + FieldPath.documentId(), + ); + if (partition.startAt) { + partitionedQuery = partitionedQuery.startAt(...partition.startAt); + } + if (partition.endBefore) { + partitionedQuery = partitionedQuery.endBefore(...partition.endBefore); } + documents.push(...(await partitionedQuery.get()).docs); + } - expect(documents.length).to.equal(documentCount); - }); + expect(documents.length).to.equal(documentCount); + }); - it('partition query with converter', async () => { - const collectionGroupWithConverter = - collectionGroup.withConverter(postConverter); - const partitions = await getPartitions( - collectionGroupWithConverter, - desiredPartitionCount, - ); - const documents = await verifyPartitions(partitions); + it('partition query with converter', async () => { + const collectionGroupWithConverter = + collectionGroup.withConverter(postConverter); + const partitions = await getPartitions( + collectionGroupWithConverter, + desiredPartitionCount, + ); + const documents = await verifyPartitions(partitions); - for (const document of documents) { - expect(document.data()).to.be.an.instanceOf(Post); - } - }); + for (const document of documents) { + expect(document.data()).to.be.an.instanceOf(Post); + } + }); - it('empty partition query', async () => { - const desiredPartitionCount = 3; + it('empty partition query', async () => { + const desiredPartitionCount = 3; - const collectionGroupId = randomColl.doc().id; - const collectionGroup = firestore.collectionGroup(collectionGroupId); - const partitions = await getPartitions( - collectionGroup, - desiredPartitionCount, - ); + const collectionGroupId = randomColl.doc().id; + const collectionGroup = firestore.collectionGroup(collectionGroupId); + const partitions = await getPartitions( + collectionGroup, + desiredPartitionCount, + ); - expect(partitions.length).to.equal(1); - expect(partitions[0].startAt).to.be.undefined; - expect(partitions[0].endBefore).to.be.undefined; - }); - }, -); + expect(partitions.length).to.equal(1); + expect(partitions[0].startAt).to.be.undefined; + expect(partitions[0].endBefore).to.be.undefined; + }); +}); describe('CollectionReference class', () => { let firestore: Firestore; @@ -782,7 +790,8 @@ describe('CollectionReference class', () => { }); }); - it('lists missing documents', async () => { + // showMissing is not supported in Enterprise + it.skipEnterprise('lists missing documents', async () => { const batch = firestore.batch(); batch.set(randomCol.doc('a'), {}); @@ -800,24 +809,28 @@ describe('CollectionReference class', () => { expect(missingDocs.map(doc => doc.id)).to.have.members(['b']); }); - it('lists documents (more than the max page size)', async () => { - const batch = firestore.batch(); - const expectedResults = []; - for (let i = 0; i < 400; i++) { - const docRef = randomCol.doc(`${i}`.padStart(3, '0')); - batch.set(docRef, {id: i}); - expectedResults.push(docRef.id); - } - await batch.commit(); + // showMissing is not supported in Enterprise + it.skipEnterprise( + 'lists documents (more than the max page size)', + async () => { + const batch = firestore.batch(); + const expectedResults = []; + for (let i = 0; i < 400; i++) { + const docRef = randomCol.doc(`${i}`.padStart(3, '0')); + batch.set(docRef, {id: i}); + expectedResults.push(docRef.id); + } + await batch.commit(); - const documentRefs = await randomCol.listDocuments(); + const documentRefs = await randomCol.listDocuments(); - const actualDocIds = documentRefs - .map(dr => dr.id) - .sort((a, b) => a.localeCompare(b)); + const actualDocIds = documentRefs + .map(dr => dr.id) + .sort((a, b) => a.localeCompare(b)); - expect(actualDocIds).to.deep.equal(expectedResults); - }); + expect(actualDocIds).to.deep.equal(expectedResults); + }, + ); it('supports withConverter()', async () => { const ref = await firestore @@ -1213,7 +1226,8 @@ describe('DocumentReference class', () => { }); }); - it('has listCollections() method', () => { + // TODO enterprise waiting on server fix + it.skipEnterprise('has listCollections() method', () => { const collections: string[] = []; const promises: Array> = []; @@ -2083,7 +2097,7 @@ describe('Query class', () => { expect( res.docs[2].get('embedding').isEqual(FieldValue.vector([20, 0])) || - res.docs[2].get('embedding').isEqual(FieldValue.vector([20, 0])), + res.docs[2].get('embedding').isEqual(FieldValue.vector([10, 0])), ).to.be.true; }); @@ -2805,29 +2819,70 @@ describe('Query class', () => { {zip: null}, ); - let res = await randomCol.where('zip', '!=', 98101).get(); - expectDocs( - res, - {zip: NaN}, - {zip: 91102}, - {zip: 98103}, - {zip: [98101]}, - {zip: ['98101', {zip: 98101}]}, - {zip: {zip: 98101}}, - ); + let res = await randomCol + .where('zip', '!=', 98101) + .orderBy('zip') + .orderBy(FieldPath.documentId()) + .get(); + if (isEnterprise()) { + expectDocs( + res, + {zip: null}, + {zip: NaN}, + {zip: 91102}, + {zip: 98103}, + {zip: [98101]}, + {zip: ['98101', {zip: 98101}]}, + {zip: {zip: 98101}}, + ); + } else { + expectDocs( + res, + {zip: NaN}, + {zip: 91102}, + {zip: 98103}, + {zip: [98101]}, + {zip: ['98101', {zip: 98101}]}, + {zip: {zip: 98101}}, + ); + } - res = await randomCol.where('zip', '!=', NaN).get(); - expectDocs( - res, - {zip: 91102}, - {zip: 98101}, - {zip: 98103}, - {zip: [98101]}, - {zip: ['98101', {zip: 98101}]}, - {zip: {zip: 98101}}, - ); + if (isEnterprise()) { + res = await randomCol + .where('zip', '!=', NaN) + .orderBy(FieldPath.documentId()) + .get(); + expectDocs( + res, + {zip: 91102}, + {zip: 98101}, + {zip: 98103}, + {zip: [98101]}, + {zip: ['98101', {zip: 98101}]}, + {zip: {zip: 98101}}, + {zip: null}, + ); + } else { + res = await randomCol.where('zip', '!=', NaN).get(); + expectDocs( + res, + {zip: 91102}, + {zip: 98101}, + {zip: 98103}, + {zip: [98101]}, + {zip: ['98101', {zip: 98101}]}, + {zip: {zip: 98101}}, + ); + } - res = await randomCol.where('zip', '!=', null).get(); + if (isEnterprise()) { + res = await randomCol + .where('zip', '!=', null) + .orderBy(FieldPath.documentId()) + .get(); + } else { + res = await randomCol.where('zip', '!=', null).get(); + } expectDocs( res, {zip: NaN}, @@ -2844,6 +2899,7 @@ describe('Query class', () => { const refs = await addDocs({count: 1}, {count: 2}, {count: 3}); const res = await randomCol .where(FieldPath.documentId(), '!=', refs[0].id) + .orderBy(FieldPath.documentId()) .get(); expectDocs(res, {count: 2}, {count: 3}); }); @@ -2857,28 +2913,74 @@ describe('Query class', () => { {zip: ['98101', {zip: 98101}]}, {zip: {zip: 98101}}, ); - let res = await randomCol.where('zip', 'not-in', [98101, 98103]).get(); - expectDocs( - res, - {zip: 91102}, - {zip: [98101]}, - {zip: ['98101', {zip: 98101}]}, - {zip: {zip: 98101}}, - ); + let res: QuerySnapshot | undefined; - res = await randomCol.where('zip', 'not-in', [NaN]).get(); + if (isEnterprise()) { + res = await randomCol + .where('zip', 'not-in', [98101, 98103]) + .orderBy(FieldPath.documentId()) + .get(); + } else { + res = await randomCol.where('zip', 'not-in', [98101, 98103]).get(); + } expectDocs( res, {zip: 91102}, - {zip: 98101}, - {zip: 98103}, {zip: [98101]}, {zip: ['98101', {zip: 98101}]}, {zip: {zip: 98101}}, ); - res = await randomCol.where('zip', 'not-in', [null]).get(); - expect(res.size).to.equal(0); + if (isEnterprise()) { + res = await randomCol + .where('zip', 'not-in', [NaN]) + .orderBy(FieldPath.documentId()) + .get(); + + expectDocs( + res, + {zip: 98101}, + {zip: 91102}, + {zip: 98103}, + {zip: [98101]}, + {zip: ['98101', {zip: 98101}]}, + {zip: {zip: 98101}}, + ); + } else { + res = await randomCol.where('zip', 'not-in', [NaN]).get(); + + expectDocs( + res, + {zip: 91102}, + {zip: 98101}, + {zip: 98103}, + {zip: [98101]}, + {zip: ['98101', {zip: 98101}]}, + {zip: {zip: 98101}}, + ); + } + + if (isEnterprise()) { + res = await randomCol + .where('zip', 'not-in', [null]) + .orderBy(FieldPath.documentId()) + .get(); + } else { + res = await randomCol.where('zip', 'not-in', [null]).get(); + } + if (isEnterprise()) { + expectDocs( + res, + {zip: 98101}, + {zip: 91102}, + {zip: 98103}, + {zip: [98101]}, + {zip: ['98101', {zip: 98101}]}, + {zip: {zip: 98101}}, + ); + } else { + expect(res.size).to.equal(0); + } }); it('supports not-in with document ID array', async () => { @@ -2898,7 +3000,10 @@ describe('Query class', () => { {zip: ['98101', {zip: 98101}]}, {zip: {zip: 98101}}, ); - const res = await randomCol.where('zip', 'in', [98101, 98103]).get(); + const res = await randomCol + .where('zip', 'in', [98101, 98103]) + .orderBy('zip') + .get(); expectDocs(res, {zip: 98101}, {zip: 98103}); }); @@ -2910,7 +3015,8 @@ describe('Query class', () => { expectDocs(res, {count: 1}, {count: 2}); }); - it('supports array-contains-any', async () => { + // TODO waiting fix for `The function array_contains(...) requires `Array` but got `LONG`.` + it.skipEnterprise('supports array-contains-any', async () => { await addDocs( {array: [42]}, {array: ['a', 42, 'c']}, @@ -3047,6 +3153,7 @@ describe('Query class', () => { expectDocs(res, {doc: 2}, {doc: 3}, {doc: 4}); }); + // TODO WHAT? it('can use offset() method with get()', async () => { await addDocs({foo: 'a'}, {foo: 'b'}); const res = await randomCol.orderBy('foo').offset(1).get(); @@ -3066,6 +3173,7 @@ describe('Query class', () => { expect(received).to.equal(1); }); + // TODO WHAT? it('can run offset(num), where num is larger than the collection size on get()', async () => { await addDocs({foo: 'a'}, {foo: 'b'}); const res = await randomCol.orderBy('foo').offset(3).get(); @@ -3108,14 +3216,19 @@ describe('Query class', () => { }); }); - it('supports pagination with where() clauses', () => { + // TODO wait for implicit sort order decision + it.skipEmulator('supports pagination with where() clauses', () => { const batch = firestore.batch(); for (let i = 0; i < 10; ++i) { batch.set(randomCol.doc('doc' + i), {val: i}); } - const query = randomCol.where('val', '>=', 1).limit(3); + let query = randomCol.where('val', '>=', 1).limit(3); + + if (isEnterprise()) { + query = query.orderBy('val').orderBy(FieldPath.documentId()); + } return batch .commit() @@ -3208,7 +3321,8 @@ describe('Query class', () => { expect(received).to.equal(2); }); - it('can query collection groups', async () => { + // TODO (enterprise) waiting on implicit sor order decision + it.skipEnterprise('can query collection groups', async () => { // Use `randomCol` to get a random collection group name to use but ensure // it starts with 'b' for predictable ordering. const collectionGroup = 'b' + randomCol.id; @@ -3234,6 +3348,7 @@ describe('Query class', () => { const querySnapshot = await firestore .collectionGroup(collectionGroup) + .orderBy(FieldPath.documentId()) .get(); expect(querySnapshot.docs.map(d => d.id)).to.deep.equal([ 'cg-doc1', @@ -3285,44 +3400,49 @@ describe('Query class', () => { expect(querySnapshot.docs.map(d => d.id)).to.deep.equal(['cg-doc2']); }); - it('can query collection groups with where filters on arbitrary documentId', async () => { - // Use `randomCol` to get a random collection group name to use but - // ensure it starts with 'b' for predictable ordering. - const collectionGroup = 'b' + randomCol.id; - - const docPaths = [ - `a/a/${collectionGroup}/cg-doc1`, - `a/b/a/b/${collectionGroup}/cg-doc2`, - `a/b/${collectionGroup}/cg-doc3`, - `a/b/c/d/${collectionGroup}/cg-doc4`, - `a/c/${collectionGroup}/cg-doc5`, - `${collectionGroup}/cg-doc6`, - 'a/b/nope/nope', - ]; - const batch = firestore.batch(); - for (const docPath of docPaths) { - batch.set(firestore.doc(docPath), {x: 1}); - } - await batch.commit(); + // TODO wait for implicit sort order decision + it.skipEnterprise( + 'can query collection groups with where filters on arbitrary documentId', + async () => { + // Use `randomCol` to get a random collection group name to use but + // ensure it starts with 'b' for predictable ordering. + const collectionGroup = 'b' + randomCol.id; + + const docPaths = [ + `a/a/${collectionGroup}/cg-doc1`, + `a/b/a/b/${collectionGroup}/cg-doc2`, + `a/b/${collectionGroup}/cg-doc3`, + `a/b/c/d/${collectionGroup}/cg-doc4`, + `a/c/${collectionGroup}/cg-doc5`, + `${collectionGroup}/cg-doc6`, + 'a/b/nope/nope', + ]; + const batch = firestore.batch(); + for (const docPath of docPaths) { + batch.set(firestore.doc(docPath), {x: 1}); + } + await batch.commit(); - let querySnapshot = await firestore - .collectionGroup(collectionGroup) - .where(FieldPath.documentId(), '>=', 'a/b') - .where(FieldPath.documentId(), '<=', 'a/b0') - .get(); - expect(querySnapshot.docs.map(d => d.id)).to.deep.equal([ - 'cg-doc2', - 'cg-doc3', - 'cg-doc4', - ]); + let querySnapshot = await firestore + .collectionGroup(collectionGroup) + .where(FieldPath.documentId(), '>=', 'a/b') + .where(FieldPath.documentId(), '<=', 'a/b0') + .orderBy(FieldPath.documentId()) + .get(); + expect(querySnapshot.docs.map(d => d.id)).to.deep.equal([ + 'cg-doc2', + 'cg-doc3', + 'cg-doc4', + ]); - querySnapshot = await firestore - .collectionGroup(collectionGroup) - .where(FieldPath.documentId(), '>', 'a/b') - .where(FieldPath.documentId(), '<', `a/b/${collectionGroup}/cg-doc3`) - .get(); - expect(querySnapshot.docs.map(d => d.id)).to.deep.equal(['cg-doc2']); - }); + querySnapshot = await firestore + .collectionGroup(collectionGroup) + .where(FieldPath.documentId(), '>', 'a/b') + .where(FieldPath.documentId(), '<', `a/b/${collectionGroup}/cg-doc3`) + .get(); + expect(querySnapshot.docs.map(d => d.id)).to.deep.equal(['cg-doc2']); + }, + ); it('can query large collections', async () => { // @grpc/grpc-js v0.4.1 failed to deliver the full set of query results for @@ -3352,6 +3472,7 @@ describe('Query class', () => { .where( Filter.or(Filter.where('a', '==', 1), Filter.where('b', '==', 1)), ) + .orderBy(FieldPath.documentId()) .get(), 'doc1', 'doc2', @@ -3368,6 +3489,7 @@ describe('Query class', () => { Filter.and(Filter.where('a', '==', 3), Filter.where('b', '==', 2)), ), ) + .orderBy(FieldPath.documentId()) .get(), 'doc1', 'doc3', @@ -3382,6 +3504,7 @@ describe('Query class', () => { Filter.or(Filter.where('b', '==', 0), Filter.where('b', '==', 3)), ), ) + .orderBy(FieldPath.documentId()) .get(), 'doc1', 'doc4', @@ -3396,6 +3519,7 @@ describe('Query class', () => { Filter.or(Filter.where('a', '==', 3), Filter.where('b', '==', 3)), ), ) + .orderBy(FieldPath.documentId()) .get(), 'doc3', ); @@ -3407,14 +3531,15 @@ describe('Query class', () => { Filter.or(Filter.where('a', '==', 2), Filter.where('b', '==', 1)), ) .limit(1) + .orderBy(FieldPath.documentId()) .get(), 'doc2', ); }); - // Skip this test if running against production because it results in a 'missing index' error. - // The Firestore Emulator, however, does serve these queries. - (process.env.FIRESTORE_EMULATOR_HOST === undefined ? it.skip : it)( + // TODO Enterprise - wait for implicit sort order decision + // Skip this test if running against standard production because it results in a 'missing index' error. + it.skipClassic.skipEnterprise( 'supports OR queries with composite indexes', async () => { const collection = await testCollectionWithDocs({ @@ -3431,10 +3556,11 @@ describe('Query class', () => { .where( Filter.or(Filter.where('a', '>', 2), Filter.where('b', '==', 1)), ) + .orderBy(FieldPath.documentId()) .get(), - 'doc5', 'doc2', 'doc3', + 'doc5', ); // Test with limits (implicit order by ASC): (a==1) || (b > 0) LIMIT 2 @@ -3444,6 +3570,7 @@ describe('Query class', () => { Filter.or(Filter.where('a', '==', 1), Filter.where('b', '>', 0)), ) .limit(2) + .orderBy(FieldPath.documentId()) .get(), 'doc1', 'doc2', @@ -3458,6 +3585,7 @@ describe('Query class', () => { ) .limitToLast(2) .orderBy('b') + .orderBy(FieldPath.documentId()) .get(), 'doc3', 'doc4', @@ -3471,6 +3599,7 @@ describe('Query class', () => { ) .limit(1) .orderBy('a') + .orderBy(FieldPath.documentId()) .get(), 'doc5', ); @@ -3483,6 +3612,7 @@ describe('Query class', () => { ) .limit(1) .orderBy('a', 'desc') + .orderBy(FieldPath.documentId()) .get(), 'doc2', ); @@ -3507,6 +3637,7 @@ describe('Query class', () => { .where( Filter.or(Filter.where('a', '==', 1), Filter.where('b', '==', 1)), ) + .orderBy(FieldPath.documentId()) .get(), 'doc1', 'doc2', @@ -3515,9 +3646,10 @@ describe('Query class', () => { ); }); - // Skip this test if running against production because it results in a 'missing index' error. - // The Firestore Emulator, however, does serve these queries. - (process.env.FIRESTORE_EMULATOR_HOST === undefined ? it.skip : it)( + // Skip this test if running against production standard DB because it results in a 'missing index' error. + // The Firestore Emulator and Enterprise-editions, however, do serve these queries. + // TODO Enterprise wait for implicit sort order decision + it.skipClassic.skipEnterprise( 'supports OR queries on documents with missing fields', async () => { const collection = await testCollectionWithDocs({ @@ -3537,6 +3669,7 @@ describe('Query class', () => { Filter.or(Filter.where('a', '==', 1), Filter.where('b', '==', 1)), ) .orderBy('a') + .orderBy(FieldPath.documentId()) .get(), 'doc1', 'doc4', @@ -3551,6 +3684,7 @@ describe('Query class', () => { Filter.or(Filter.where('a', '==', 1), Filter.where('b', '==', 1)), ) .orderBy('b') + .orderBy(FieldPath.documentId()) .get(), 'doc1', 'doc2', @@ -3559,33 +3693,61 @@ describe('Query class', () => { // Query: a>2 || b==1. // This query has an implicit 'order by a'. - // doc2 should not be included because it's missing the field 'a'. - expectDocs( - await collection - .where( - Filter.or(Filter.where('a', '>', 2), Filter.where('b', '==', 1)), - ) - .get(), - 'doc3', - ); + if (isEnterprise()) { + expectDocs( + await collection + .where( + Filter.or(Filter.where('a', '>', 2), Filter.where('b', '==', 1)), + ) + .orderBy('a') + .orderBy(FieldPath.documentId()) + .get(), + 'doc3', + ); + } else { + // Standard Ed: doc2 should not be included because it's missing the field 'a'. + expectDocs( + await collection + .where( + Filter.or(Filter.where('a', '>', 2), Filter.where('b', '==', 1)), + ) + .get(), + 'doc3', + ); + } // Query: a>1 || b==1 order by a order by b. - // doc6 should not be included because it's missing the field 'b'. - // doc2 should not be included because it's missing the field 'a'. - expectDocs( - await collection - .where( - Filter.or(Filter.where('a', '>', 1), Filter.where('b', '==', 1)), - ) - .orderBy('a') - .orderBy('b') - .get(), - 'doc3', - ); + if (isEnterprise()) { + expectDocs( + await collection + .where( + Filter.or(Filter.where('a', '>', 1), Filter.where('b', '==', 1)), + ) + .orderBy('a') + .orderBy('b') + .orderBy(FieldPath.documentId()) + .get(), + 'doc3', + ); + } else { + // doc6 should not be included because it's missing the field 'b'. + // doc2 should not be included because it's missing the field 'a'. + expectDocs( + await collection + .where( + Filter.or(Filter.where('a', '>', 1), Filter.where('b', '==', 1)), + ) + .orderBy('a') + .orderBy('b') + .get(), + 'doc3', + ); + } }, ); - it('supports OR queries with in', async () => { + // TODO Enterprise wait for implicit sort order decision + it.skipEnterprise('supports OR queries with in', async () => { const collection = await testCollectionWithDocs({ doc1: {a: 1, b: 0}, doc2: {b: 1}, @@ -3604,6 +3766,7 @@ describe('Query class', () => { Filter.where('b', 'in', [2, 3]), ), ) + .orderBy(FieldPath.documentId()) .get(), 'doc3', 'doc4', @@ -3612,19 +3775,18 @@ describe('Query class', () => { }); // Skip this test if running against production because it results in a 'missing index' error. - // The Firestore Emulator, however, does serve these queries. - (process.env.FIRESTORE_EMULATOR_HOST === undefined ? it.skip : it)( - 'supports OR queries with not-in', - async () => { - const collection = await testCollectionWithDocs({ - doc1: {a: 1, b: 0}, - doc2: {b: 1}, - doc3: {a: 3, b: 2}, - doc4: {a: 1, b: 3}, - doc5: {a: 1}, - doc6: {a: 2}, - }); + // TODO Enterprise wait for implicit sort order decision + it.skipClassic.skipEnterprise('supports OR queries with not-in', async () => { + const collection = await testCollectionWithDocs({ + doc1: {a: 1, b: 0}, + doc2: {b: 1}, + doc3: {a: 3, b: 2}, + doc4: {a: 1, b: 3}, + doc5: {a: 1}, + doc6: {a: 2}, + }); + if (isEnterprise()) { // a==2 || (b != 2 && b != 3) // Has implicit "orderBy b" expectDocs( @@ -3635,14 +3797,33 @@ describe('Query class', () => { Filter.where('b', 'not-in', [2, 3]), ), ) + .orderBy(FieldPath.documentId()) .get(), 'doc1', 'doc2', + 'doc5', + 'doc6', ); - }, - ); + } else { + // a==2 || (b != 2 && b != 3) + // Has implicit "orderBy b" + expectDocs( + await collection + .where( + Filter.or( + Filter.where('a', '==', 2), + Filter.where('b', 'not-in', [2, 3]), + ), + ) + .get(), + 'doc1', + 'doc2', + ); + } + }); - it('supports OR queries with array membership', async () => { + // TODO Enterprise wait for implicit sort order decision + it.skipEnterprise('supports OR queries with array membership', async () => { const collection = await testCollectionWithDocs({ doc1: {a: 1, b: [0]}, doc2: {b: [1]}, @@ -3661,6 +3842,7 @@ describe('Query class', () => { Filter.where('b', 'array-contains', 7), ), ) + .orderBy(FieldPath.documentId()) .get(), 'doc3', 'doc4', @@ -3677,6 +3859,7 @@ describe('Query class', () => { Filter.where('b', 'array-contains-any', [0, 3]), ), ) + .orderBy(FieldPath.documentId()) .get(), 'doc1', 'doc4', @@ -3958,111 +4141,135 @@ describe('Query class', () => { unsubscribe(); }); - it('snapshot listener sorts query by DocumentId same way as server', async () => { - const batch = firestore.batch(); - batch.set(randomCol.doc('A'), {a: 1}); - batch.set(randomCol.doc('a'), {a: 1}); - batch.set(randomCol.doc('Aa'), {a: 1}); - batch.set(randomCol.doc('7'), {a: 1}); - batch.set(randomCol.doc('12'), {a: 1}); - batch.set(randomCol.doc('__id7__'), {a: 1}); - batch.set(randomCol.doc('__id12__'), {a: 1}); - batch.set(randomCol.doc('__id-2__'), {a: 1}); - batch.set(randomCol.doc('__id1_'), {a: 1}); - batch.set(randomCol.doc('_id1__'), {a: 1}); - batch.set(randomCol.doc('__id'), {a: 1}); - // largest long number - batch.set(randomCol.doc('__id9223372036854775807__'), {a: 1}); - batch.set(randomCol.doc('__id9223372036854775806__'), {a: 1}); - // smallest long number - batch.set(randomCol.doc('__id-9223372036854775808__'), {a: 1}); - batch.set(randomCol.doc('__id-9223372036854775807__'), {a: 1}); - await batch.commit(); + it.skipEnterprise( + 'snapshot listener sorts query by DocumentId same way as server', + async () => { + const batch = firestore.batch(); + batch.set(randomCol.doc('A'), {a: 1}); + batch.set(randomCol.doc('a'), {a: 1}); + batch.set(randomCol.doc('Aa'), {a: 1}); + batch.set(randomCol.doc('7'), {a: 1}); + batch.set(randomCol.doc('12'), {a: 1}); + batch.set(randomCol.doc('__id7__'), {a: 1}); + batch.set(randomCol.doc('__id12__'), {a: 1}); + batch.set(randomCol.doc('__id-2__'), {a: 1}); + batch.set(randomCol.doc('__id1_'), {a: 1}); + batch.set(randomCol.doc('_id1__'), {a: 1}); + batch.set(randomCol.doc('__id'), {a: 1}); + // largest long number + batch.set(randomCol.doc('__id9223372036854775807__'), {a: 1}); + batch.set(randomCol.doc('__id9223372036854775806__'), {a: 1}); + // smallest long number + batch.set(randomCol.doc('__id-9223372036854775808__'), {a: 1}); + batch.set(randomCol.doc('__id-9223372036854775807__'), {a: 1}); + await batch.commit(); - const query = randomCol.orderBy(FieldPath.documentId()); - const expectedDocs = [ - '__id-9223372036854775808__', - '__id-9223372036854775807__', - '__id-2__', - '__id7__', - '__id12__', - '__id9223372036854775806__', - '__id9223372036854775807__', - '12', - '7', - 'A', - 'Aa', - '__id', - '__id1_', - '_id1__', - 'a', - ]; + const query = randomCol.orderBy(FieldPath.documentId()); + const expectedDocs = isEnterprise() + ? [ + '12', + '7', + 'A', + 'Aa', + '__id', + '__id-2__', + '__id-9223372036854775807__', + '__id-9223372036854775808__', + '__id12__', + '__id1_', + '__id7__', + '__id9223372036854775806__', + '__id9223372036854775807__', + '_id1__', + 'a', + ] + : [ + '__id-9223372036854775808__', + '__id-9223372036854775807__', + '__id-2__', + '__id7__', + '__id12__', + '__id9223372036854775806__', + '__id9223372036854775807__', + '12', + '7', + 'A', + 'Aa', + '__id', + '__id1_', + '_id1__', + 'a', + ]; - const getSnapshot = await query.get(); - expect(getSnapshot.docs.map(d => d.id)).to.deep.equal(expectedDocs); + const getSnapshot = await query.get(); + expect(getSnapshot.docs.map(d => d.id)).to.deep.equal(expectedDocs); - const unsubscribe = query.onSnapshot(snapshot => - currentDeferred.resolve(snapshot), - ); + const unsubscribe = query.onSnapshot(snapshot => + currentDeferred.resolve(snapshot), + ); - const watchSnapshot = await waitForSnapshot(); - // Compare the snapshot (including sort order) of a snapshot - snapshotsEqual(watchSnapshot, { - docs: getSnapshot.docs, - docChanges: getSnapshot.docChanges(), - }); - unsubscribe(); - }); + const watchSnapshot = await waitForSnapshot(); + // Compare the snapshot (including sort order) of a snapshot + snapshotsEqual(watchSnapshot, { + docs: getSnapshot.docs, + docChanges: getSnapshot.docChanges(), + }); + unsubscribe(); + }, + ); - it('snapshot listener sorts filtered query by DocumentId same way as server', async () => { - const batch = firestore.batch(); - batch.set(randomCol.doc('A'), {a: 1}); - batch.set(randomCol.doc('a'), {a: 1}); - batch.set(randomCol.doc('Aa'), {a: 1}); - batch.set(randomCol.doc('7'), {a: 1}); - batch.set(randomCol.doc('12'), {a: 1}); - batch.set(randomCol.doc('__id7__'), {a: 1}); - batch.set(randomCol.doc('__id12__'), {a: 1}); - batch.set(randomCol.doc('__id-2__'), {a: 1}); - batch.set(randomCol.doc('__id1_'), {a: 1}); - batch.set(randomCol.doc('_id1__'), {a: 1}); - batch.set(randomCol.doc('__id'), {a: 1}); - // largest long number - batch.set(randomCol.doc('__id9223372036854775807__'), {a: 1}); - batch.set(randomCol.doc('__id9223372036854775806__'), {a: 1}); - // smallest long number - batch.set(randomCol.doc('__id-9223372036854775808__'), {a: 1}); - batch.set(randomCol.doc('__id-9223372036854775807__'), {a: 1}); - await batch.commit(); + it.skipEnterprise( + 'snapshot listener sorts filtered query by DocumentId same way as server', + async () => { + const batch = firestore.batch(); + batch.set(randomCol.doc('A'), {a: 1}); + batch.set(randomCol.doc('a'), {a: 1}); + batch.set(randomCol.doc('Aa'), {a: 1}); + batch.set(randomCol.doc('7'), {a: 1}); + batch.set(randomCol.doc('12'), {a: 1}); + batch.set(randomCol.doc('__id7__'), {a: 1}); + batch.set(randomCol.doc('__id12__'), {a: 1}); + batch.set(randomCol.doc('__id-2__'), {a: 1}); + batch.set(randomCol.doc('__id1_'), {a: 1}); + batch.set(randomCol.doc('_id1__'), {a: 1}); + batch.set(randomCol.doc('__id'), {a: 1}); + // largest long number + batch.set(randomCol.doc('__id9223372036854775807__'), {a: 1}); + batch.set(randomCol.doc('__id9223372036854775806__'), {a: 1}); + // smallest long number + batch.set(randomCol.doc('__id-9223372036854775808__'), {a: 1}); + batch.set(randomCol.doc('__id-9223372036854775807__'), {a: 1}); + await batch.commit(); - const query = randomCol - .where(FieldPath.documentId(), '>', '__id7__') - .where(FieldPath.documentId(), '<=', 'A') - .orderBy(FieldPath.documentId()); - const expectedDocs = [ - '__id12__', - '__id9223372036854775806__', - '__id9223372036854775807__', - '12', - '7', - 'A', - ]; + const query = randomCol + .where(FieldPath.documentId(), '>', '__id7__') + .where(FieldPath.documentId(), '<=', 'A') + .orderBy(FieldPath.documentId()); + const expectedDocs = [ + '__id12__', + '__id9223372036854775806__', + '__id9223372036854775807__', + '12', + '7', + 'A', + ]; - const getSnapshot = await query.get(); - expect(getSnapshot.docs.map(d => d.id)).to.deep.equal(expectedDocs); + const getSnapshot = await query.get(); + expect(getSnapshot.docs.map(d => d.id)).to.deep.equal(expectedDocs); - const unsubscribe = query.onSnapshot(snapshot => - currentDeferred.resolve(snapshot), - ); + const unsubscribe = query.onSnapshot(snapshot => + currentDeferred.resolve(snapshot), + ); - const watchSnapshot = await waitForSnapshot(); - // Compare the snapshot (including sort order) of a snapshot - snapshotsEqual(watchSnapshot, { - docs: getSnapshot.docs, - docChanges: getSnapshot.docChanges(), - }); - unsubscribe(); - }); + const watchSnapshot = await waitForSnapshot(); + // Compare the snapshot (including sort order) of a snapshot + snapshotsEqual(watchSnapshot, { + docs: getSnapshot.docs, + docChanges: getSnapshot.docChanges(), + }); + unsubscribe(); + }, + ); it('SDK orders vector field same way as backend', async () => { // We validate that the SDK orders the vector field the same way as the backend @@ -5809,7 +6016,11 @@ describe('Aggregation queries', () => { totalRating: AggregateField.sum('rating'), }) .get(); - expect(snapshot.data().totalRating).to.equal(0); + if (isEnterprise()) { + expect(snapshot.data().totalRating).to.equal(null); + } else { + expect(snapshot.data().totalRating).to.equal(0); + } }); it('performs sum only on numeric fields', async () => { @@ -7341,12 +7552,12 @@ describe('BulkWriter class', () => { await batch.commit(); }); - it('on top-level collection', async () => { + it.skipEnterprise('on top-level collection', async () => { await firestore.recursiveDelete(randomCol); expect(await countCollectionChildren(randomCol)).to.equal(0); }); - it('on nested collection', async () => { + it.skipEnterprise('on nested collection', async () => { const coll = randomCol.doc('bob').collection('parentsCol'); await firestore.recursiveDelete(coll); @@ -7354,7 +7565,8 @@ describe('BulkWriter class', () => { expect(await countCollectionChildren(randomCol)).to.equal(2); }); - it('on nested document', async () => { + // TODO enterprise waiting on b/469490062 + it.skip('on nested document', async () => { const doc = randomCol.doc('bob/parentsCol/daniel'); await firestore.recursiveDelete(doc); @@ -7364,7 +7576,8 @@ describe('BulkWriter class', () => { expect(await countCollectionChildren(randomCol)).to.equal(3); }); - it('on leaf document', async () => { + // TODO enterprise b/469490062 + it.skipEnterprise('on leaf document', async () => { const doc = randomCol.doc('bob/parentsCol/daniel/childCol/ernie'); await firestore.recursiveDelete(doc); @@ -7373,7 +7586,8 @@ describe('BulkWriter class', () => { expect(await countCollectionChildren(randomCol)).to.equal(5); }); - it('does not affect other collections', async () => { + // TODO enterprise b/469490062 + it.skipEnterprise('does not affect other collections', async () => { // Add other nested collection that shouldn't be deleted. const collB = firestore.collection('doggos'); await collB.doc('doggo').set({name: 'goodboi'}); @@ -7440,7 +7654,11 @@ describe('Client initialization', () => { ], [ 'CollectionReference.listDocuments()', - randomColl => randomColl.listDocuments(), + + randomColl => { + if (process.env.RUN_ENTERPRISE_TESTS) return Promise.resolve(); + return randomColl.listDocuments(); + }, ], [ 'CollectionReference.onSnapshot()', @@ -7477,7 +7695,11 @@ describe('Client initialization', () => { ['DocumentReference.delete()', randomColl => randomColl.doc().delete()], [ 'DocumentReference.listCollections()', - randomColl => randomColl.doc().listCollections(), + randomColl => { + // TODO enterprise waiting on b/469490062, skip for now + if (isEnterprise()) return Promise.resolve(); + return randomColl.doc().listCollections(); + }, ], [ 'DocumentReference.onSnapshot()', @@ -7493,6 +7715,9 @@ describe('Client initialization', () => { [ 'CollectionGroup.getPartitions()', async randomColl => { + // Requires PartitionQuery support + if (process.env.RUN_ENTERPRISE_TESTS) return; + const partitions = randomColl.firestore .collectionGroup('id') .getPartitions(2); diff --git a/dev/system-test/pipeline.ts b/dev/system-test/pipeline.ts index 4280e296f..7fc052add 100644 --- a/dev/system-test/pipeline.ts +++ b/dev/system-test/pipeline.ts @@ -136,6 +136,7 @@ import {expect, use} from 'chai'; import * as chaiAsPromised from 'chai-as-promised'; import {afterEach, describe, it} from 'mocha'; +import '../test/util/mocha_extensions'; import {verifyInstance} from '../test/util/helpers'; import {getTestDb, getTestRoot} from './firestore'; @@ -147,7 +148,7 @@ use(chaiAsPromised); const timestampDeltaMS = 3000; // eslint-disable-next-line no-restricted-properties -(process.env.RUN_ENTERPRISE_TESTS ? describe.only : describe.skip)( +(process.env.RUN_ENTERPRISE_TESTS ? describe : describe.skip)( 'Pipeline class', () => { let firestore: Firestore; @@ -4483,7 +4484,7 @@ const timestampDeltaMS = 3000; // This is the Query integration tests from the lite API (no cache support) // with some additional test cases added for more complete coverage. // eslint-disable-next-line no-restricted-properties -(process.env.RUN_ENTERPRISE_TESTS ? describe.only : describe.skip)( +(process.env.RUN_ENTERPRISE_TESTS ? describe : describe.skip)( 'Query to Pipeline', () => { async function execute(ppl: Pipeline): Promise { diff --git a/dev/system-test/query.ts b/dev/system-test/query.ts index 51577d04c..39b8d40d1 100644 --- a/dev/system-test/query.ts +++ b/dev/system-test/query.ts @@ -20,6 +20,7 @@ import { import {expect} from 'chai'; import {afterEach, beforeEach, describe, it} from 'mocha'; +import '../test/util/mocha_extensions'; import { CollectionReference, DocumentReference, @@ -37,1017 +38,1011 @@ import {verifyInstance} from '../test/util/helpers'; import {DeferredPromise, getTestRoot} from './firestore'; import {IndexTestHelper} from './index_test_helper'; -(process.env.RUN_ENTERPRISE_TESTS ? describe : describe.skip)( - 'Query class', - () => { - interface PaginatedResults { - pages: number; - docs: QueryDocumentSnapshot[]; - } - - let firestore: Firestore; - let randomCol: CollectionReference; - - const paginateResults = ( - query: Query, - startAfter?: unknown, - ): Promise => { - return (startAfter ? query.startAfter(startAfter) : query) - .get() - .then(snapshot => { - if (snapshot.empty) { - return {pages: 0, docs: []}; - } else { - const docs = snapshot.docs; - return paginateResults(query, docs[docs.length - 1]).then( - nextPage => { - return { - pages: nextPage.pages + 1, - docs: docs.concat(nextPage.docs), - }; - }, - ); - } - }); - }; - - async function addDocs( - ...docs: DocumentData[] - ): Promise { - let id = 0; // Guarantees consistent ordering for the first documents - const refs: DocumentReference[] = []; - for (const doc of docs) { - const ref = randomCol.doc('doc' + id++); - await ref.set(doc); - refs.push(ref); - } - return refs; - } - - async function testCollectionWithDocs(docs: { - [id: string]: DocumentData; - }): Promise> { - for (const id in docs) { - const ref = randomCol.doc(id); - await ref.set(docs[id]); - } - return randomCol; - } - - function expectDocs(result: QuerySnapshot, ...docs: string[]): void; - function expectDocs(result: QuerySnapshot, ...data: DocumentData[]): void; - - function expectDocs( - result: QuerySnapshot, - ...data: DocumentData[] | string[] - ): void { - expect(result.size).to.equal(data.length); - - if (data.length > 0) { - if (typeof data[0] === 'string') { - const actualIds = result.docs.map(docSnapshot => docSnapshot.id); - expect(actualIds).to.deep.equal(data); +describe.skipClassic('Query class', () => { + interface PaginatedResults { + pages: number; + docs: QueryDocumentSnapshot[]; + } + + let firestore: Firestore; + let randomCol: CollectionReference; + + const paginateResults = ( + query: Query, + startAfter?: unknown, + ): Promise => { + return (startAfter ? query.startAfter(startAfter) : query) + .get() + .then(snapshot => { + if (snapshot.empty) { + return {pages: 0, docs: []}; } else { - result.forEach(doc => { - expect(doc.data()).to.deep.equal(data.shift()); - }); + const docs = snapshot.docs; + return paginateResults(query, docs[docs.length - 1]).then( + nextPage => { + return { + pages: nextPage.pages + 1, + docs: docs.concat(nextPage.docs), + }; + }, + ); } - } - } - - async function compareQueryAndPipeline( - query: Query, - ): Promise { - const queryResults = await query.get(); - const pipeline = query.firestore.pipeline().createFrom(query); - const pipelineResults = await pipeline.execute(); - - expect(pipelineResults.results.map(r => r._fieldsProto)).to.deep.equal( - queryResults.docs.map(s => s._fieldsProto), - ); - return queryResults; + }); + }; + + async function addDocs( + ...docs: DocumentData[] + ): Promise { + let id = 0; // Guarantees consistent ordering for the first documents + const refs: DocumentReference[] = []; + for (const doc of docs) { + const ref = randomCol.doc('doc' + id++); + await ref.set(doc); + refs.push(ref); } - - async function compareVectorQueryAndPipeline( - query: VectorQuery, - ): Promise { - const queryResults = await query.get(); - const pipeline = query.query.firestore.pipeline().createFrom(query); - const pipelineResults = await pipeline.execute(); - - expect(pipelineResults.results.map(r => r._fieldsProto)).to.deep.equal( - queryResults.docs.map(s => s._fieldsProto), - ); - return queryResults; + return refs; + } + + async function testCollectionWithDocs(docs: { + [id: string]: DocumentData; + }): Promise> { + for (const id in docs) { + const ref = randomCol.doc(id); + await ref.set(docs[id]); } - - beforeEach(() => { - randomCol = getTestRoot(); - firestore = randomCol.firestore; - }); - - afterEach(() => verifyInstance(firestore)); - - it('has firestore property', () => { - const ref = randomCol.limit(0); - expect(ref.firestore).to.be.an.instanceOf(Firestore); - }); - - it('has select() method', () => { - const ref = randomCol.doc('doc'); - return ref - .set({foo: 'bar', bar: 'foo'}) - .then(() => { - return randomCol.select('foo').get(); - }) - .then(res => { - expect(res.docs[0].data()).to.deep.equal({foo: 'bar'}); - }); - }); - - it('select() supports empty fields', () => { - const ref = randomCol.doc('doc'); - return ref - .set({foo: 'bar', bar: 'foo'}) - .then(() => { - return randomCol.select().get(); - }) - .then(res => { - expect(res.docs[0].ref.id).to.deep.equal('doc'); - expect(res.docs[0].data()).to.deep.equal({}); + return randomCol; + } + + function expectDocs(result: QuerySnapshot, ...docs: string[]): void; + function expectDocs(result: QuerySnapshot, ...data: DocumentData[]): void; + + function expectDocs( + result: QuerySnapshot, + ...data: DocumentData[] | string[] + ): void { + expect(result.size).to.equal(data.length); + + if (data.length > 0) { + if (typeof data[0] === 'string') { + const actualIds = result.docs.map(docSnapshot => docSnapshot.id); + expect(actualIds).to.deep.equal(data); + } else { + result.forEach(doc => { + expect(doc.data()).to.deep.equal(data.shift()); }); - }); + } + } + } - it('has where() method', () => { - const ref = randomCol.doc('doc'); - return ref - .set({foo: 'bar'}) - .then(() => { - return compareQueryAndPipeline(randomCol.where('foo', '==', 'bar')); - }) - .then(res => { - expect(res.docs[0].data()).to.deep.equal({foo: 'bar'}); - }); - }); + async function compareQueryAndPipeline(query: Query): Promise { + const queryResults = await query.get(); + const pipeline = query.firestore.pipeline().createFrom(query); + const pipelineResults = await pipeline.execute(); - it('supports NaN and Null', () => { - const ref = randomCol.doc('doc'); - return ref - .set({foo: NaN, bar: null}) - .then(() => { - return compareQueryAndPipeline( - randomCol.where('foo', '==', NaN).where('bar', '==', null), - ); - }) - .then(res => { - expect( - typeof res.docs[0].get('foo') === 'number' && - isNaN(res.docs[0].get('foo')), - ); - expect(res.docs[0].get('bar')).to.equal(null); - }); - }); + expect(pipelineResults.results.map(r => r._fieldsProto)).to.deep.equal( + queryResults.docs.map(s => s._fieldsProto), + ); + return queryResults; + } + + async function compareVectorQueryAndPipeline( + query: VectorQuery, + ): Promise { + const queryResults = await query.get(); + const pipeline = query.query.firestore.pipeline().createFrom(query); + const pipelineResults = await pipeline.execute(); + + expect(pipelineResults.results.map(r => r._fieldsProto)).to.deep.equal( + queryResults.docs.map(s => s._fieldsProto), + ); + return queryResults; + } + + beforeEach(() => { + randomCol = getTestRoot(); + firestore = randomCol.firestore; + }); + + afterEach(() => verifyInstance(firestore)); + + it('has firestore property', () => { + const ref = randomCol.limit(0); + expect(ref.firestore).to.be.an.instanceOf(Firestore); + }); + + it('has select() method', () => { + const ref = randomCol.doc('doc'); + return ref + .set({foo: 'bar', bar: 'foo'}) + .then(() => { + return randomCol.select('foo').get(); + }) + .then(res => { + expect(res.docs[0].data()).to.deep.equal({foo: 'bar'}); + }); + }); + + it('select() supports empty fields', () => { + const ref = randomCol.doc('doc'); + return ref + .set({foo: 'bar', bar: 'foo'}) + .then(() => { + return randomCol.select().get(); + }) + .then(res => { + expect(res.docs[0].ref.id).to.deep.equal('doc'); + expect(res.docs[0].data()).to.deep.equal({}); + }); + }); + + it('has where() method', () => { + const ref = randomCol.doc('doc'); + return ref + .set({foo: 'bar'}) + .then(() => { + return compareQueryAndPipeline(randomCol.where('foo', '==', 'bar')); + }) + .then(res => { + expect(res.docs[0].data()).to.deep.equal({foo: 'bar'}); + }); + }); + + it('supports NaN and Null', () => { + const ref = randomCol.doc('doc'); + return ref + .set({foo: NaN, bar: null}) + .then(() => { + return compareQueryAndPipeline( + randomCol.where('foo', '==', NaN).where('bar', '==', null), + ); + }) + .then(res => { + expect( + typeof res.docs[0].get('foo') === 'number' && + isNaN(res.docs[0].get('foo')), + ); + expect(res.docs[0].get('bar')).to.equal(null); + }); + }); + + it('supports array-contains', () => { + return Promise.all([ + randomCol.add({foo: ['bar']}), + randomCol.add({foo: []}), + ]) + .then(() => + compareQueryAndPipeline( + randomCol.where('foo', 'array-contains', 'bar'), + ), + ) + .then(res => { + expect(res.size).to.equal(1); + expect(res.docs[0].get('foo')).to.deep.equal(['bar']); + }); + }); + + it('supports findNearest by EUCLIDEAN distance', async () => { + const indexTestHelper = new IndexTestHelper(firestore); + + const collectionReference = await indexTestHelper.createTestDocs([ + {foo: 'bar'}, + {foo: 'xxx', embedding: FieldValue.vector([10, 10])}, + {foo: 'bar', embedding: FieldValue.vector([1, 1])}, + {foo: 'bar', embedding: FieldValue.vector([10, 0])}, + {foo: 'bar', embedding: FieldValue.vector([20, 0])}, + {foo: 'bar', embedding: FieldValue.vector([100, 100])}, + ]); + + const vectorQuery = indexTestHelper + .query(collectionReference) + .where('foo', '==', 'bar') + .findNearest('embedding', [10, 10], { + limit: 3, + distanceMeasure: 'EUCLIDEAN', + }); - it('supports array-contains', () => { - return Promise.all([ - randomCol.add({foo: ['bar']}), - randomCol.add({foo: []}), - ]) - .then(() => - compareQueryAndPipeline( - randomCol.where('foo', 'array-contains', 'bar'), - ), - ) - .then(res => { - expect(res.size).to.equal(1); - expect(res.docs[0].get('foo')).to.deep.equal(['bar']); - }); + const res = await compareVectorQueryAndPipeline(vectorQuery); + expect(res.size).to.equal(3); + expect(res.docs[0].get('embedding').isEqual(FieldValue.vector([10, 0]))).to + .be.true; + expect(res.docs[1].get('embedding').isEqual(FieldValue.vector([1, 1]))).to + .be.true; + expect(res.docs[2].get('embedding').isEqual(FieldValue.vector([20, 0]))).to + .be.true; + }); + + it('supports findNearest by COSINE distance', async () => { + const indexTestHelper = new IndexTestHelper(firestore); + + const collectionReference = await indexTestHelper.setTestDocs({ + '1': {foo: 'bar'}, + '2': {foo: 'xxx', embedding: FieldValue.vector([10, 10])}, + '3': {foo: 'bar', embedding: FieldValue.vector([1, 1])}, + '4': {foo: 'bar', embedding: FieldValue.vector([20, 0])}, + '5': {foo: 'bar', embedding: FieldValue.vector([10, 0])}, + '6': {foo: 'bar', embedding: FieldValue.vector([100, 100])}, }); - it('supports findNearest by EUCLIDEAN distance', async () => { - const indexTestHelper = new IndexTestHelper(firestore); + const vectorQuery = indexTestHelper + .query(collectionReference) + .where('foo', '==', 'bar') + .findNearest('embedding', [10, 10], { + limit: 3, + distanceMeasure: 'COSINE', + }); - const collectionReference = await indexTestHelper.createTestDocs([ - {foo: 'bar'}, - {foo: 'xxx', embedding: FieldValue.vector([10, 10])}, - {foo: 'bar', embedding: FieldValue.vector([1, 1])}, - {foo: 'bar', embedding: FieldValue.vector([10, 0])}, - {foo: 'bar', embedding: FieldValue.vector([20, 0])}, - {foo: 'bar', embedding: FieldValue.vector([100, 100])}, - ]); + const res = await compareVectorQueryAndPipeline(vectorQuery); - const vectorQuery = indexTestHelper - .query(collectionReference) - .where('foo', '==', 'bar') - .findNearest('embedding', [10, 10], { - limit: 3, - distanceMeasure: 'EUCLIDEAN', - }); + expect(res.size).to.equal(3); - const res = await compareVectorQueryAndPipeline(vectorQuery); - expect(res.size).to.equal(3); - expect(res.docs[0].get('embedding').isEqual(FieldValue.vector([10, 0]))) - .to.be.true; + if (res.docs[0].get('embedding').isEqual(FieldValue.vector([1, 1]))) { + expect( + res.docs[1].get('embedding').isEqual(FieldValue.vector([100, 100])), + ).to.be.true; + } else { + expect( + res.docs[0].get('embedding').isEqual(FieldValue.vector([100, 100])), + ).to.be.true; expect(res.docs[1].get('embedding').isEqual(FieldValue.vector([1, 1]))).to .be.true; - expect(res.docs[2].get('embedding').isEqual(FieldValue.vector([20, 0]))) - .to.be.true; - }); - - it('supports findNearest by COSINE distance', async () => { - const indexTestHelper = new IndexTestHelper(firestore); + } - const collectionReference = await indexTestHelper.setTestDocs({ - '1': {foo: 'bar'}, - '2': {foo: 'xxx', embedding: FieldValue.vector([10, 10])}, - '3': {foo: 'bar', embedding: FieldValue.vector([1, 1])}, - '4': {foo: 'bar', embedding: FieldValue.vector([20, 0])}, - '5': {foo: 'bar', embedding: FieldValue.vector([10, 0])}, - '6': {foo: 'bar', embedding: FieldValue.vector([100, 100])}, + expect( + res.docs[2].get('embedding').isEqual(FieldValue.vector([20, 0])) || + res.docs[2].get('embedding').isEqual(FieldValue.vector([10, 0])), + ).to.be.true; + }); + + it('supports findNearest by DOT_PRODUCT distance', async () => { + const indexTestHelper = new IndexTestHelper(firestore); + + const collectionReference = await indexTestHelper.createTestDocs([ + {foo: 'bar'}, + {foo: 'xxx', embedding: FieldValue.vector([10, 10])}, + {foo: 'bar', embedding: FieldValue.vector([1, 1])}, + {foo: 'bar', embedding: FieldValue.vector([10, 0])}, + {foo: 'bar', embedding: FieldValue.vector([20, 0])}, + {foo: 'bar', embedding: FieldValue.vector([100, 100])}, + ]); + + const vectorQuery = indexTestHelper + .query(collectionReference) + .where('foo', '==', 'bar') + .findNearest('embedding', [10, 10], { + limit: 3, + distanceMeasure: 'DOT_PRODUCT', }); - const vectorQuery = indexTestHelper - .query(collectionReference) - .where('foo', '==', 'bar') - .findNearest('embedding', [10, 10], { - limit: 3, - distanceMeasure: 'COSINE', - }); + const res = await compareVectorQueryAndPipeline(vectorQuery); + expect(res.size).to.equal(3); + expect(res.docs[0].get('embedding').isEqual(FieldValue.vector([100, 100]))) + .to.be.true; + expect(res.docs[1].get('embedding').isEqual(FieldValue.vector([20, 0]))).to + .be.true; + expect(res.docs[2].get('embedding').isEqual(FieldValue.vector([10, 0]))).to + .be.true; + }); + + it('findNearest works with converters', async () => { + const indexTestHelper = new IndexTestHelper(firestore); + + class FooDistance { + constructor( + readonly foo: string, + readonly embedding: Array, + ) {} + } - const res = await compareVectorQueryAndPipeline(vectorQuery); + const fooConverter = { + toFirestore(d: FooDistance): DocumentData { + return {title: d.foo, embedding: FieldValue.vector(d.embedding)}; + }, + fromFirestore(snapshot: QueryDocumentSnapshot): FooDistance { + const data = snapshot.data(); + return new FooDistance(data.foo, data.embedding.toArray()); + }, + }; - expect(res.size).to.equal(3); + const collectionRef = await indexTestHelper.createTestDocs([ + {foo: 'bar', embedding: FieldValue.vector([5, 5])}, + ]); + + const vectorQuery = indexTestHelper + .query(collectionRef) + .withConverter(fooConverter) + .where('foo', '==', 'bar') + .findNearest('embedding', [10, 10], { + limit: 3, + distanceMeasure: 'EUCLIDEAN', + }); - if (res.docs[0].get('embedding').isEqual(FieldValue.vector([1, 1]))) { - expect( - res.docs[1].get('embedding').isEqual(FieldValue.vector([100, 100])), - ).to.be.true; - } else { - expect( - res.docs[0].get('embedding').isEqual(FieldValue.vector([100, 100])), - ).to.be.true; - expect(res.docs[1].get('embedding').isEqual(FieldValue.vector([1, 1]))) - .to.be.true; - } + const res = await compareVectorQueryAndPipeline(vectorQuery); - expect( - res.docs[2].get('embedding').isEqual(FieldValue.vector([20, 0])) || - res.docs[2].get('embedding').isEqual(FieldValue.vector([20, 0])), - ).to.be.true; - }); + expect(res.size).to.equal(1); + expect(res.docs[0].data().foo).to.equal('bar'); + expect(res.docs[0].data().embedding).to.deep.equal([5, 5]); + }); - it('supports findNearest by DOT_PRODUCT distance', async () => { - const indexTestHelper = new IndexTestHelper(firestore); + it('supports findNearest skipping fields of wrong types', async () => { + const indexTestHelper = new IndexTestHelper(firestore); - const collectionReference = await indexTestHelper.createTestDocs([ - {foo: 'bar'}, - {foo: 'xxx', embedding: FieldValue.vector([10, 10])}, - {foo: 'bar', embedding: FieldValue.vector([1, 1])}, - {foo: 'bar', embedding: FieldValue.vector([10, 0])}, - {foo: 'bar', embedding: FieldValue.vector([20, 0])}, - {foo: 'bar', embedding: FieldValue.vector([100, 100])}, - ]); + const collectionRef = await indexTestHelper.createTestDocs([ + {foo: 'bar'}, - const vectorQuery = indexTestHelper - .query(collectionReference) - .where('foo', '==', 'bar') - .findNearest('embedding', [10, 10], { - limit: 3, - distanceMeasure: 'DOT_PRODUCT', - }); + // These documents are skipped because it is not really a vector value + {foo: 'bar', embedding: [10, 10]}, + {foo: 'bar', embedding: 'not actually a vector'}, + {foo: 'bar', embedding: null}, - const res = await compareVectorQueryAndPipeline(vectorQuery); - expect(res.size).to.equal(3); - expect( - res.docs[0].get('embedding').isEqual(FieldValue.vector([100, 100])), - ).to.be.true; - expect(res.docs[1].get('embedding').isEqual(FieldValue.vector([20, 0]))) - .to.be.true; - expect(res.docs[2].get('embedding').isEqual(FieldValue.vector([10, 0]))) - .to.be.true; - }); + // Actual vector values + {foo: 'bar', embedding: FieldValue.vector([9, 9])}, + {foo: 'bar', embedding: FieldValue.vector([50, 50])}, + {foo: 'bar', embedding: FieldValue.vector([100, 100])}, + ]); - it('findNearest works with converters', async () => { - const indexTestHelper = new IndexTestHelper(firestore); + const vectorQuery = indexTestHelper + .query(collectionRef) + .where('foo', '==', 'bar') + .findNearest('embedding', [10, 10], { + limit: 100, // Intentionally large to get all matches. + distanceMeasure: 'EUCLIDEAN', + }); - class FooDistance { - constructor( - readonly foo: string, - readonly embedding: Array, - ) {} - } + const res = await compareVectorQueryAndPipeline(vectorQuery); + expect(res.size).to.equal(3); + expect(res.docs[0].get('embedding').isEqual(FieldValue.vector([9, 9]))).to + .be.true; + expect(res.docs[1].get('embedding').isEqual(FieldValue.vector([50, 50]))).to + .be.true; + expect(res.docs[2].get('embedding').isEqual(FieldValue.vector([100, 100]))) + .to.be.true; + }); + + it('findNearest ignores mismatching dimensions', async () => { + const indexTestHelper = new IndexTestHelper(firestore); + + const collectionRef = await indexTestHelper.createTestDocs([ + {foo: 'bar'}, + + // Vectors with dimension mismatch + {foo: 'bar', embedding: FieldValue.vector([10])}, + + // Vectors with dimension match + {foo: 'bar', embedding: FieldValue.vector([9, 9])}, + {foo: 'bar', embedding: FieldValue.vector([50, 50])}, + ]); + + const vectorQuery = indexTestHelper + .query(collectionRef) + .where('foo', '==', 'bar') + .findNearest('embedding', [10, 10], { + limit: 3, + distanceMeasure: 'EUCLIDEAN', + }); - const fooConverter = { - toFirestore(d: FooDistance): DocumentData { - return {title: d.foo, embedding: FieldValue.vector(d.embedding)}; - }, - fromFirestore(snapshot: QueryDocumentSnapshot): FooDistance { - const data = snapshot.data(); - return new FooDistance(data.foo, data.embedding.toArray()); - }, - }; + const res = await compareVectorQueryAndPipeline(vectorQuery); + expect(res.size).to.equal(2); + expect(res.docs[0].get('embedding').isEqual(FieldValue.vector([9, 9]))).to + .be.true; + expect(res.docs[1].get('embedding').isEqual(FieldValue.vector([50, 50]))).to + .be.true; + }); + + it('supports findNearest on non-existent field', async () => { + const indexTestHelper = new IndexTestHelper(firestore); + + const collectionRef = await indexTestHelper.createTestDocs([ + {foo: 'bar'}, + {foo: 'bar', otherField: [10, 10]}, + {foo: 'bar', otherField: 'not actually a vector'}, + {foo: 'bar', otherField: null}, + ]); + + const vectorQuery = indexTestHelper + .query(collectionRef) + .where('foo', '==', 'bar') + .findNearest('embedding', [10, 10], { + limit: 3, + distanceMeasure: 'EUCLIDEAN', + }); - const collectionRef = await indexTestHelper.createTestDocs([ - {foo: 'bar', embedding: FieldValue.vector([5, 5])}, - ]); + const res = await compareVectorQueryAndPipeline(vectorQuery); - const vectorQuery = indexTestHelper - .query(collectionRef) - .withConverter(fooConverter) - .where('foo', '==', 'bar') - .findNearest('embedding', [10, 10], { - limit: 3, - distanceMeasure: 'EUCLIDEAN', - }); + expect(res.size).to.equal(0); + }); - const res = await compareVectorQueryAndPipeline(vectorQuery); + it('supports findNearest on vector nested in a map', async () => { + const indexTestHelper = new IndexTestHelper(firestore); - expect(res.size).to.equal(1); - expect(res.docs[0].data().foo).to.equal('bar'); - expect(res.docs[0].data().embedding).to.deep.equal([5, 5]); - }); + const collectionReference = await indexTestHelper.createTestDocs([ + {nested: {foo: 'bar'}}, + {nested: {foo: 'xxx', embedding: FieldValue.vector([10, 10])}}, + {nested: {foo: 'bar', embedding: FieldValue.vector([1, 1])}}, + {nested: {foo: 'bar', embedding: FieldValue.vector([10, 0])}}, + {nested: {foo: 'bar', embedding: FieldValue.vector([20, 0])}}, + {nested: {foo: 'bar', embedding: FieldValue.vector([100, 100])}}, + ]); - it('supports findNearest skipping fields of wrong types', async () => { - const indexTestHelper = new IndexTestHelper(firestore); + const vectorQuery = indexTestHelper + .query(collectionReference) + .findNearest('nested.embedding', [10, 10], { + limit: 3, + distanceMeasure: 'EUCLIDEAN', + }); - const collectionRef = await indexTestHelper.createTestDocs([ - {foo: 'bar'}, + const res = await compareVectorQueryAndPipeline(vectorQuery); + expect(res.size).to.equal(3); + expect( + res.docs[0].get('nested.embedding').isEqual(FieldValue.vector([10, 10])), + ).to.be.true; + expect( + res.docs[1].get('nested.embedding').isEqual(FieldValue.vector([10, 0])), + ).to.be.true; + expect( + res.docs[2].get('nested.embedding').isEqual(FieldValue.vector([1, 1])), + ).to.be.true; + }); + + it('supports findNearest with select to exclude vector data in response', async () => { + const indexTestHelper = new IndexTestHelper(firestore); + + const collectionReference = await indexTestHelper.createTestDocs([ + {foo: 1}, + {foo: 2, embedding: FieldValue.vector([10, 10])}, + {foo: 3, embedding: FieldValue.vector([1, 1])}, + {foo: 4, embedding: FieldValue.vector([10, 0])}, + {foo: 5, embedding: FieldValue.vector([20, 0])}, + {foo: 6, embedding: FieldValue.vector([100, 100])}, + ]); + + const vectorQuery = indexTestHelper + .query(collectionReference) + .where('foo', 'in', [1, 2, 3, 4, 5, 6]) + .select('foo') + .findNearest('embedding', [10, 10], { + limit: 10, + distanceMeasure: 'EUCLIDEAN', + }); - // These documents are skipped because it is not really a vector value - {foo: 'bar', embedding: [10, 10]}, - {foo: 'bar', embedding: 'not actually a vector'}, - {foo: 'bar', embedding: null}, + const res = await vectorQuery.get(); + expect(res.size).to.equal(5); + expect(res.docs[0].get('foo')).to.equal(2); + expect(res.docs[1].get('foo')).to.equal(4); + expect(res.docs[2].get('foo')).to.equal(3); + expect(res.docs[3].get('foo')).to.equal(5); + expect(res.docs[4].get('foo')).to.equal(6); + + res.docs.forEach(ds => expect(ds.get('embedding')).to.be.undefined); + }); + + it('supports findNearest limits', async () => { + const indexTestHelper = new IndexTestHelper(firestore); + + const embeddingVector = []; + const queryVector = []; + for (let i = 0; i < 2048; i++) { + embeddingVector.push(i + 1); + queryVector.push(i - 1); + } - // Actual vector values - {foo: 'bar', embedding: FieldValue.vector([9, 9])}, - {foo: 'bar', embedding: FieldValue.vector([50, 50])}, - {foo: 'bar', embedding: FieldValue.vector([100, 100])}, - ]); + const collectionReference = await indexTestHelper.createTestDocs([ + {embedding: FieldValue.vector(embeddingVector)}, + ]); - const vectorQuery = indexTestHelper - .query(collectionRef) - .where('foo', '==', 'bar') - .findNearest('embedding', [10, 10], { - limit: 100, // Intentionally large to get all matches. - distanceMeasure: 'EUCLIDEAN', - }); + const vectorQuery = indexTestHelper + .query(collectionReference) + .findNearest('embedding', queryVector, { + limit: 1000, + distanceMeasure: 'EUCLIDEAN', + }); - const res = await compareVectorQueryAndPipeline(vectorQuery); - expect(res.size).to.equal(3); - expect(res.docs[0].get('embedding').isEqual(FieldValue.vector([9, 9]))).to - .be.true; - expect(res.docs[1].get('embedding').isEqual(FieldValue.vector([50, 50]))) - .to.be.true; - expect( - res.docs[2].get('embedding').isEqual(FieldValue.vector([100, 100])), - ).to.be.true; - }); + const res = await compareVectorQueryAndPipeline(vectorQuery); + expect(res.size).to.equal(1); + expect( + (res.docs[0].get('embedding') as VectorValue).toArray(), + ).to.deep.equal(embeddingVector); + }); + + // TODO waiting on implicit sort order decision + it.skipEnterprise('supports !=', async () => { + await addDocs( + {zip: NaN}, + {zip: 91102}, + {zip: 98101}, + {zip: 98103}, + {zip: [98101]}, + {zip: ['98101', {zip: 98101}]}, + {zip: {zip: 98101}}, + {zip: null}, + ); - it('findNearest ignores mismatching dimensions', async () => { - const indexTestHelper = new IndexTestHelper(firestore); + let res = await compareQueryAndPipeline( + randomCol.where('zip', '!=', 98101), + ); + expectDocs( + res, + {zip: NaN}, + {zip: 91102}, + {zip: 98103}, + {zip: [98101]}, + {zip: ['98101', {zip: 98101}]}, + {zip: {zip: 98101}}, + ); - const collectionRef = await indexTestHelper.createTestDocs([ - {foo: 'bar'}, + res = await compareQueryAndPipeline(randomCol.where('zip', '!=', NaN)); + expectDocs( + res, + {zip: 91102}, + {zip: 98101}, + {zip: 98103}, + {zip: [98101]}, + {zip: ['98101', {zip: 98101}]}, + {zip: {zip: 98101}}, + ); - // Vectors with dimension mismatch - {foo: 'bar', embedding: FieldValue.vector([10])}, + res = await compareQueryAndPipeline(randomCol.where('zip', '!=', null)); + expectDocs( + res, + {zip: NaN}, + {zip: 91102}, + {zip: 98101}, + {zip: 98103}, + {zip: [98101]}, + {zip: ['98101', {zip: 98101}]}, + {zip: {zip: 98101}}, + ); + }); - // Vectors with dimension match - {foo: 'bar', embedding: FieldValue.vector([9, 9])}, - {foo: 'bar', embedding: FieldValue.vector([50, 50])}, - ]); + // TODO waiting on implicit sort order decision + it.skipEnterprise('supports != with document ID', async () => { + const refs = await addDocs({count: 1}, {count: 2}, {count: 3}); + const res = await compareQueryAndPipeline( + randomCol.where(FieldPath.documentId(), '!=', refs[0].id), + ); + expectDocs(res, {count: 2}, {count: 3}); + }); + + // TODO waiting on implicit sort order decision + it.skipEnterprise('supports not-in', async () => { + await addDocs( + {zip: 98101}, + {zip: 91102}, + {zip: 98103}, + {zip: [98101]}, + {zip: ['98101', {zip: 98101}]}, + {zip: {zip: 98101}}, + ); + let res = await compareQueryAndPipeline( + randomCol.where('zip', 'not-in', [98101, 98103]), + ); + expectDocs( + res, + {zip: 91102}, + {zip: [98101]}, + {zip: ['98101', {zip: 98101}]}, + {zip: {zip: 98101}}, + ); - const vectorQuery = indexTestHelper - .query(collectionRef) - .where('foo', '==', 'bar') - .findNearest('embedding', [10, 10], { - limit: 3, - distanceMeasure: 'EUCLIDEAN', - }); + res = await compareQueryAndPipeline( + randomCol.where('zip', 'not-in', [NaN]), + ); + expectDocs( + res, + {zip: 91102}, + {zip: 98101}, + {zip: 98103}, + {zip: [98101]}, + {zip: ['98101', {zip: 98101}]}, + {zip: {zip: 98101}}, + ); - const res = await compareVectorQueryAndPipeline(vectorQuery); - expect(res.size).to.equal(2); - expect(res.docs[0].get('embedding').isEqual(FieldValue.vector([9, 9]))).to - .be.true; - expect(res.docs[1].get('embedding').isEqual(FieldValue.vector([50, 50]))) - .to.be.true; - }); + res = await compareQueryAndPipeline( + randomCol.where('zip', 'not-in', [null]), + ); + expect(res.size).to.equal(0); + }); - it('supports findNearest on non-existent field', async () => { - const indexTestHelper = new IndexTestHelper(firestore); + it('supports not-in with document ID array', async () => { + const refs = await addDocs({count: 1}, {count: 2}, {count: 3}); + const res = await compareQueryAndPipeline( + randomCol.where(FieldPath.documentId(), 'not-in', [refs[0].id, refs[1]]), + ); + expectDocs(res, {count: 3}); + }); + + // TODO waiting on implicit sort order decision + it.skipEnterprise('supports "in"', async () => { + await addDocs( + {zip: 98101}, + {zip: 91102}, + {zip: 98103}, + {zip: [98101]}, + {zip: ['98101', {zip: 98101}]}, + {zip: {zip: 98101}}, + ); + const res = await compareQueryAndPipeline( + randomCol.where('zip', 'in', [98101, 98103]), + ); + expectDocs(res, {zip: 98101}, {zip: 98103}); + }); - const collectionRef = await indexTestHelper.createTestDocs([ - {foo: 'bar'}, - {foo: 'bar', otherField: [10, 10]}, - {foo: 'bar', otherField: 'not actually a vector'}, - {foo: 'bar', otherField: null}, - ]); + it('supports "in" with document ID array', async () => { + const refs = await addDocs({count: 1}, {count: 2}, {count: 3}); + const res = await compareQueryAndPipeline( + randomCol.where(FieldPath.documentId(), 'in', [refs[0].id, refs[1]]), + ); + expectDocs(res, {count: 1}, {count: 2}); + }); + + it('supports array-contains-any', async () => { + await addDocs( + {array: [42]}, + {array: ['a', 42, 'c']}, + {array: [41.999, '42', {a: [42]}]}, + {array: [42], array2: ['sigh']}, + {array: [43]}, + {array: [{a: 42}]}, + {array: 42}, + ); - const vectorQuery = indexTestHelper - .query(collectionRef) - .where('foo', '==', 'bar') - .findNearest('embedding', [10, 10], { - limit: 3, - distanceMeasure: 'EUCLIDEAN', - }); + const res = await compareQueryAndPipeline( + randomCol.where('array', 'array-contains-any', [42, 43]), + ); - const res = await compareVectorQueryAndPipeline(vectorQuery); + expectDocs( + res, + {array: [42]}, + {array: ['a', 42, 'c']}, + { + array: [42], + array2: ['sigh'], + }, + {array: [43]}, + ); + }); - expect(res.size).to.equal(0); - }); + it('can query by FieldPath.documentId()', () => { + const ref = randomCol.doc('foo'); - it('supports findNearest on vector nested in a map', async () => { - const indexTestHelper = new IndexTestHelper(firestore); + return ref + .set({}) + .then(() => { + return compareQueryAndPipeline( + randomCol.where(FieldPath.documentId(), '>=', 'bar'), + ); + }) + .then(res => { + expect(res.docs.length).to.equal(1); + }); + }); - const collectionReference = await indexTestHelper.createTestDocs([ - {nested: {foo: 'bar'}}, - {nested: {foo: 'xxx', embedding: FieldValue.vector([10, 10])}}, - {nested: {foo: 'bar', embedding: FieldValue.vector([1, 1])}}, - {nested: {foo: 'bar', embedding: FieldValue.vector([10, 0])}}, - {nested: {foo: 'bar', embedding: FieldValue.vector([20, 0])}}, - {nested: {foo: 'bar', embedding: FieldValue.vector([100, 100])}}, - ]); + it('has orderBy() method', async () => { + await addDocs({foo: 'a'}, {foo: 'b'}); - const vectorQuery = indexTestHelper - .query(collectionReference) - .findNearest('nested.embedding', [10, 10], { - limit: 3, - distanceMeasure: 'EUCLIDEAN', - }); + let res = await compareQueryAndPipeline(randomCol.orderBy('foo')); + expectDocs(res, {foo: 'a'}, {foo: 'b'}); - const res = await compareVectorQueryAndPipeline(vectorQuery); - expect(res.size).to.equal(3); - expect( - res.docs[0] - .get('nested.embedding') - .isEqual(FieldValue.vector([10, 10])), - ).to.be.true; - expect( - res.docs[1].get('nested.embedding').isEqual(FieldValue.vector([10, 0])), - ).to.be.true; - expect( - res.docs[2].get('nested.embedding').isEqual(FieldValue.vector([1, 1])), - ).to.be.true; - }); + res = await compareQueryAndPipeline(randomCol.orderBy('foo', 'desc')); + expectDocs(res, {foo: 'b'}, {foo: 'a'}); + }); - it('supports findNearest with select to exclude vector data in response', async () => { - const indexTestHelper = new IndexTestHelper(firestore); + it('can order by FieldPath.documentId()', () => { + const ref1 = randomCol.doc('doc1'); + const ref2 = randomCol.doc('doc2'); - const collectionReference = await indexTestHelper.createTestDocs([ - {foo: 1}, - {foo: 2, embedding: FieldValue.vector([10, 10])}, - {foo: 3, embedding: FieldValue.vector([1, 1])}, - {foo: 4, embedding: FieldValue.vector([10, 0])}, - {foo: 5, embedding: FieldValue.vector([20, 0])}, - {foo: 6, embedding: FieldValue.vector([100, 100])}, - ]); + return Promise.all([ref1.set({foo: 'a'}), ref2.set({foo: 'b'})]) + .then(() => { + return compareQueryAndPipeline( + randomCol.orderBy(FieldPath.documentId()), + ); + }) + .then(res => { + expect(res.docs[0].data()).to.deep.equal({foo: 'a'}); + expect(res.docs[1].data()).to.deep.equal({foo: 'b'}); + }); + }); - const vectorQuery = indexTestHelper - .query(collectionReference) - .where('foo', 'in', [1, 2, 3, 4, 5, 6]) - .select('foo') - .findNearest('embedding', [10, 10], { - limit: 10, - distanceMeasure: 'EUCLIDEAN', - }); + it('can run get() on empty collection', async () => { + return compareQueryAndPipeline(randomCol).then(res => { + return expect(res.empty); + }); + }); - const res = await vectorQuery.get(); - expect(res.size).to.equal(5); - expect(res.docs[0].get('foo')).to.equal(2); - expect(res.docs[1].get('foo')).to.equal(4); - expect(res.docs[2].get('foo')).to.equal(3); - expect(res.docs[3].get('foo')).to.equal(5); - expect(res.docs[4].get('foo')).to.equal(6); + it('can run stream() on empty collection', async () => { + let received = 0; + const stream = randomCol.stream(); - res.docs.forEach(ds => expect(ds.get('embedding')).to.be.undefined); - }); + for await (const doc of stream) { + expect(doc).to.be.an.instanceOf(QueryDocumentSnapshot); + ++received; + } - it('supports findNearest limits', async () => { - const indexTestHelper = new IndexTestHelper(firestore); + expect(received).to.equal(0); + }); - const embeddingVector = []; - const queryVector = []; - for (let i = 0; i < 2048; i++) { - embeddingVector.push(i + 1); - queryVector.push(i - 1); - } + it('has limit() method on get()', async () => { + await addDocs({foo: 'a'}, {foo: 'b'}); + const res = await compareQueryAndPipeline( + randomCol.orderBy('foo').limit(1), + ); + expectDocs(res, {foo: 'a'}); + }); - const collectionReference = await indexTestHelper.createTestDocs([ - {embedding: FieldValue.vector(embeddingVector)}, - ]); + it('has limit() method on stream()', async () => { + let received = 0; + await addDocs({foo: 'a'}, {foo: 'b'}); - const vectorQuery = indexTestHelper - .query(collectionReference) - .findNearest('embedding', queryVector, { - limit: 1000, - distanceMeasure: 'EUCLIDEAN', - }); + const stream = randomCol.orderBy('foo').limit(1).stream(); + for await (const doc of stream) { + expect(doc).to.be.an.instanceOf(QueryDocumentSnapshot); + ++received; + } - const res = await compareVectorQueryAndPipeline(vectorQuery); - expect(res.size).to.equal(1); - expect( - (res.docs[0].get('embedding') as VectorValue).toArray(), - ).to.deep.equal(embeddingVector); - }); + expect(received).to.equal(1); + }); - it('supports !=', async () => { - await addDocs( - {zip: NaN}, - {zip: 91102}, - {zip: 98101}, - {zip: 98103}, - {zip: [98101]}, - {zip: ['98101', {zip: 98101}]}, - {zip: {zip: 98101}}, - {zip: null}, - ); + it('can run limit(num), where num is larger than the collection size on get()', async () => { + await addDocs({foo: 'a'}, {foo: 'b'}); + const res = await compareQueryAndPipeline( + randomCol.orderBy('foo').limit(3), + ); + expectDocs(res, {foo: 'a'}, {foo: 'b'}); + }); - let res = await compareQueryAndPipeline( - randomCol.where('zip', '!=', 98101), - ); - expectDocs( - res, - {zip: NaN}, - {zip: 91102}, - {zip: 98103}, - {zip: [98101]}, - {zip: ['98101', {zip: 98101}]}, - {zip: {zip: 98101}}, - ); + it('can run limit(num), where num is larger than the collection size on stream()', async () => { + let received = 0; + await addDocs({foo: 'a'}, {foo: 'b'}); - res = await compareQueryAndPipeline(randomCol.where('zip', '!=', NaN)); - expectDocs( - res, - {zip: 91102}, - {zip: 98101}, - {zip: 98103}, - {zip: [98101]}, - {zip: ['98101', {zip: 98101}]}, - {zip: {zip: 98101}}, - ); + const stream = randomCol.orderBy('foo').limit(3).stream(); + for await (const doc of stream) { + expect(doc).to.be.an.instanceOf(QueryDocumentSnapshot); + ++received; + } - res = await compareQueryAndPipeline(randomCol.where('zip', '!=', null)); - expectDocs( - res, - {zip: NaN}, - {zip: 91102}, - {zip: 98101}, - {zip: 98103}, - {zip: [98101]}, - {zip: ['98101', {zip: 98101}]}, - {zip: {zip: 98101}}, - ); - }); + expect(received).to.equal(2); + }); + + it('has limitToLast() method', async () => { + await addDocs({doc: 1}, {doc: 2}, {doc: 3}); + // const res = await compareQueryAndPipeline(randomCol.orderBy('doc').limitToLast(2)); + const res = await randomCol.orderBy('doc').limitToLast(2).get(); + expectDocs(res, {doc: 2}, {doc: 3}); + }); + + it('limitToLast() supports Query cursors', async () => { + await addDocs({doc: 1}, {doc: 2}, {doc: 3}, {doc: 4}, {doc: 5}); + const res = await randomCol + .orderBy('doc') + .startAt(2) + .endAt(4) + .limitToLast(5) + .get(); + expectDocs(res, {doc: 2}, {doc: 3}, {doc: 4}); + }); + + it('can use offset() method with get()', async () => { + await addDocs({foo: 'a'}, {foo: 'b'}); + const res = await compareQueryAndPipeline( + randomCol.orderBy('foo').offset(1), + ); + expectDocs(res, {foo: 'b'}); + }); - it('supports != with document ID', async () => { - const refs = await addDocs({count: 1}, {count: 2}, {count: 3}); - const res = await compareQueryAndPipeline( - randomCol.where(FieldPath.documentId(), '!=', refs[0].id), - ); - expectDocs(res, {count: 2}, {count: 3}); - }); + it('can use offset() method with stream()', async () => { + let received = 0; + await addDocs({foo: 'a'}, {foo: 'b'}); - it('supports not-in', async () => { - await addDocs( - {zip: 98101}, - {zip: 91102}, - {zip: 98103}, - {zip: [98101]}, - {zip: ['98101', {zip: 98101}]}, - {zip: {zip: 98101}}, - ); - let res = await compareQueryAndPipeline( - randomCol.where('zip', 'not-in', [98101, 98103]), - ); - expectDocs( - res, - {zip: 91102}, - {zip: [98101]}, - {zip: ['98101', {zip: 98101}]}, - {zip: {zip: 98101}}, - ); + const stream = randomCol.orderBy('foo').offset(1).stream(); + for await (const doc of stream) { + expect(doc).to.be.an.instanceOf(QueryDocumentSnapshot); + ++received; + } - res = await compareQueryAndPipeline( - randomCol.where('zip', 'not-in', [NaN]), - ); - expectDocs( - res, - {zip: 91102}, - {zip: 98101}, - {zip: 98103}, - {zip: [98101]}, - {zip: ['98101', {zip: 98101}]}, - {zip: {zip: 98101}}, - ); + expect(received).to.equal(1); + }); - res = await compareQueryAndPipeline( - randomCol.where('zip', 'not-in', [null]), - ); - expect(res.size).to.equal(0); - }); + it('can run offset(num), where num is larger than the collection size on get()', async () => { + await addDocs({foo: 'a'}, {foo: 'b'}); + const res = await compareQueryAndPipeline( + randomCol.orderBy('foo').offset(3), + ); + expect(res.empty); + }); + + it('can run offset(num), where num is larger than the collection size on stream()', async () => { + let received = 0; + await addDocs({foo: 'a'}, {foo: 'b'}); + const stream = randomCol.orderBy('foo').offset(3).stream(); + for await (const doc of stream) { + expect(doc).to.be.an.instanceOf(QueryDocumentSnapshot); + ++received; + } + expect(received).to.equal(0); + }); - it('supports not-in with document ID array', async () => { - const refs = await addDocs({count: 1}, {count: 2}, {count: 3}); - const res = await compareQueryAndPipeline( - randomCol.where(FieldPath.documentId(), 'not-in', [ - refs[0].id, - refs[1], - ]), - ); - expectDocs(res, {count: 3}); - }); + it('supports Unicode in document names', async () => { + const collRef = randomCol.doc('доброеутро').collection('coll'); + await collRef.add({}); + const snapshot = await compareQueryAndPipeline(collRef); + expect(snapshot.size).to.equal(1); + }); - it('supports "in"', async () => { - await addDocs( - {zip: 98101}, - {zip: 91102}, - {zip: 98103}, - {zip: [98101]}, - {zip: ['98101', {zip: 98101}]}, - {zip: {zip: 98101}}, - ); - const res = await compareQueryAndPipeline( - randomCol.where('zip', 'in', [98101, 98103]), - ); - expectDocs(res, {zip: 98101}, {zip: 98103}); - }); + it('supports pagination', () => { + const batch = firestore.batch(); - it('supports "in" with document ID array', async () => { - const refs = await addDocs({count: 1}, {count: 2}, {count: 3}); - const res = await compareQueryAndPipeline( - randomCol.where(FieldPath.documentId(), 'in', [refs[0].id, refs[1]]), - ); - expectDocs(res, {count: 1}, {count: 2}); - }); + for (let i = 0; i < 10; ++i) { + batch.set(randomCol.doc('doc' + i), {val: i}); + } - it('supports array-contains-any', async () => { - await addDocs( - {array: [42]}, - {array: ['a', 42, 'c']}, - {array: [41.999, '42', {a: [42]}]}, - {array: [42], array2: ['sigh']}, - {array: [43]}, - {array: [{a: 42}]}, - {array: 42}, - ); + const query = randomCol.orderBy('val').limit(3); - const res = await compareQueryAndPipeline( - randomCol.where('array', 'array-contains-any', [42, 43]), - ); + return batch + .commit() + .then(() => paginateResults(query)) + .then(results => { + expect(results.pages).to.equal(4); + expect(results.docs).to.have.length(10); + }); + }); - expectDocs( - res, - {array: [42]}, - {array: ['a', 42, 'c']}, - { - array: [42], - array2: ['sigh'], - }, - {array: [43]}, - ); - }); + it('supports pagination with where() clauses', () => { + const batch = firestore.batch(); - it('can query by FieldPath.documentId()', () => { - const ref = randomCol.doc('foo'); + for (let i = 0; i < 10; ++i) { + batch.set(randomCol.doc('doc' + i), {val: i}); + } - return ref - .set({}) - .then(() => { - return compareQueryAndPipeline( - randomCol.where(FieldPath.documentId(), '>=', 'bar'), - ); - }) - .then(res => { - expect(res.docs.length).to.equal(1); - }); - }); + const query = randomCol.where('val', '>=', 1).limit(3); - it('has orderBy() method', async () => { - await addDocs({foo: 'a'}, {foo: 'b'}); + return batch + .commit() + .then(() => paginateResults(query)) + .then(results => { + expect(results.pages).to.equal(3); + expect(results.docs).to.have.length(9); + }); + }); - let res = await compareQueryAndPipeline(randomCol.orderBy('foo')); - expectDocs(res, {foo: 'a'}, {foo: 'b'}); + it('supports pagination with array-contains filter', () => { + const batch = firestore.batch(); - res = await compareQueryAndPipeline(randomCol.orderBy('foo', 'desc')); - expectDocs(res, {foo: 'b'}, {foo: 'a'}); - }); + for (let i = 0; i < 10; ++i) { + batch.set(randomCol.doc('doc' + i), {array: ['foo']}); + } - it('can order by FieldPath.documentId()', () => { - const ref1 = randomCol.doc('doc1'); - const ref2 = randomCol.doc('doc2'); + const query = randomCol.where('array', 'array-contains', 'foo').limit(3); - return Promise.all([ref1.set({foo: 'a'}), ref2.set({foo: 'b'})]) - .then(() => { - return compareQueryAndPipeline( - randomCol.orderBy(FieldPath.documentId()), - ); + return batch + .commit() + .then(() => paginateResults(query)) + .then(results => { + expect(results.pages).to.equal(4); + expect(results.docs).to.have.length(10); + }); + }); + + it('has startAt() method', async () => { + await addDocs({foo: 'a'}, {foo: 'b'}); + const res = await randomCol.orderBy('foo').startAt('b').get(); + expectDocs(res, {foo: 'b'}); + }); + + it('startAt() adds implicit order by for DocumentSnapshot', async () => { + const references = await addDocs({foo: 'a'}, {foo: 'b'}); + const docSnap = await references[1].get(); + const res = await randomCol.startAt(docSnap).get(); + expectDocs(res, {foo: 'b'}); + }); + + it('has startAfter() method', async () => { + await addDocs({foo: 'a'}, {foo: 'b'}); + const res = await randomCol.orderBy('foo').startAfter('a').get(); + expectDocs(res, {foo: 'b'}); + }); + + it('has endAt() method', async () => { + await addDocs({foo: 'a'}, {foo: 'b'}); + const res = await randomCol.orderBy('foo').endAt('b').get(); + expectDocs(res, {foo: 'a'}, {foo: 'b'}); + }); + + it('has endBefore() method', async () => { + await addDocs({foo: 'a'}, {foo: 'b'}); + const res = await randomCol.orderBy('foo').endBefore('b').get(); + expectDocs(res, {foo: 'a'}); + }); + + it('has stream() method', done => { + let received = 0; + const ref1 = randomCol.doc('doc1'); + const ref2 = randomCol.doc('doc2'); + + void Promise.all([ref1.set({foo: 'a'}), ref2.set({foo: 'b'})]).then(() => { + return randomCol + .stream() + .on('data', d => { + expect(d).to.be.an.instanceOf(DocumentSnapshot); + ++received; }) - .then(res => { - expect(res.docs[0].data()).to.deep.equal({foo: 'a'}); - expect(res.docs[1].data()).to.deep.equal({foo: 'b'}); + .on('end', () => { + expect(received).to.equal(2); + done(); }); }); + }); - it('can run get() on empty collection', async () => { - return compareQueryAndPipeline(randomCol).then(res => { - return expect(res.empty); - }); - }); - - it('can run stream() on empty collection', async () => { - let received = 0; - const stream = randomCol.stream(); + it('stream() supports readable[Symbol.asyncIterator]()', async () => { + let received = 0; + await randomCol.doc().set({foo: 'bar'}); + await randomCol.doc().set({foo: 'bar'}); - for await (const doc of stream) { - expect(doc).to.be.an.instanceOf(QueryDocumentSnapshot); - ++received; - } - - expect(received).to.equal(0); - }); + const stream = randomCol.stream(); + for await (const doc of stream) { + expect(doc).to.be.an.instanceOf(QueryDocumentSnapshot); + ++received; + } - it('has limit() method on get()', async () => { - await addDocs({foo: 'a'}, {foo: 'b'}); - const res = await compareQueryAndPipeline( - randomCol.orderBy('foo').limit(1), - ); - expectDocs(res, {foo: 'a'}); - }); + expect(received).to.equal(2); + }); + + it('can query collection groups', async () => { + // Use `randomCol` to get a random collection group name to use but ensure + // it starts with 'b' for predictable ordering. + const collectionGroup = 'b' + randomCol.id; + + const docPaths = [ + `abc/123/${collectionGroup}/cg-doc1`, + `abc/123/${collectionGroup}/cg-doc2`, + `${collectionGroup}/cg-doc3`, + `${collectionGroup}/cg-doc4`, + `def/456/${collectionGroup}/cg-doc5`, + `${collectionGroup}/virtual-doc/nested-coll/not-cg-doc`, + `x${collectionGroup}/not-cg-doc`, + `${collectionGroup}x/not-cg-doc`, + `abc/123/${collectionGroup}x/not-cg-doc`, + `abc/123/x${collectionGroup}/not-cg-doc`, + `abc/${collectionGroup}`, + ]; + const batch = firestore.batch(); + for (const docPath of docPaths) { + batch.set(firestore.doc(docPath), {x: 1}); + } + await batch.commit(); - it('has limit() method on stream()', async () => { - let received = 0; - await addDocs({foo: 'a'}, {foo: 'b'}); + const querySnapshot = await compareQueryAndPipeline( + firestore.collectionGroup(collectionGroup), + ); + expect(querySnapshot.docs.map(d => d.id)).to.deep.equal([ + 'cg-doc1', + 'cg-doc2', + 'cg-doc3', + 'cg-doc4', + 'cg-doc5', + ]); + }); + + // TODO wait for implicit sort order decision + it.skipEnterprise( + 'can query collection groups with startAt / endAt by arbitrary documentId', + async () => { + // Use `randomCol` to get a random collection group name to use but + // ensure it starts with 'b' for predictable ordering. + const collectionGroup = 'b' + randomCol.id; - const stream = randomCol.orderBy('foo').limit(1).stream(); - for await (const doc of stream) { - expect(doc).to.be.an.instanceOf(QueryDocumentSnapshot); - ++received; + const docPaths = [ + `a/a/${collectionGroup}/cg-doc1`, + `a/b/a/b/${collectionGroup}/cg-doc2`, + `a/b/${collectionGroup}/cg-doc3`, + `a/b/c/d/${collectionGroup}/cg-doc4`, + `a/c/${collectionGroup}/cg-doc5`, + `${collectionGroup}/cg-doc6`, + 'a/b/nope/nope', + ]; + const batch = firestore.batch(); + for (const docPath of docPaths) { + batch.set(firestore.doc(docPath), {x: 1}); } - - expect(received).to.equal(1); - }); - - it('can run limit(num), where num is larger than the collection size on get()', async () => { - await addDocs({foo: 'a'}, {foo: 'b'}); - const res = await compareQueryAndPipeline( - randomCol.orderBy('foo').limit(3), - ); - expectDocs(res, {foo: 'a'}, {foo: 'b'}); - }); - - it('can run limit(num), where num is larger than the collection size on stream()', async () => { - let received = 0; - await addDocs({foo: 'a'}, {foo: 'b'}); - - const stream = randomCol.orderBy('foo').limit(3).stream(); - for await (const doc of stream) { - expect(doc).to.be.an.instanceOf(QueryDocumentSnapshot); - ++received; - } - - expect(received).to.equal(2); - }); - - it('has limitToLast() method', async () => { - await addDocs({doc: 1}, {doc: 2}, {doc: 3}); - // const res = await compareQueryAndPipeline(randomCol.orderBy('doc').limitToLast(2)); - const res = await randomCol.orderBy('doc').limitToLast(2).get(); - expectDocs(res, {doc: 2}, {doc: 3}); - }); - - it('limitToLast() supports Query cursors', async () => { - await addDocs({doc: 1}, {doc: 2}, {doc: 3}, {doc: 4}, {doc: 5}); - const res = await randomCol - .orderBy('doc') - .startAt(2) - .endAt(4) - .limitToLast(5) - .get(); - expectDocs(res, {doc: 2}, {doc: 3}, {doc: 4}); - }); - - it('can use offset() method with get()', async () => { - await addDocs({foo: 'a'}, {foo: 'b'}); - const res = await compareQueryAndPipeline( - randomCol.orderBy('foo').offset(1), - ); - expectDocs(res, {foo: 'b'}); - }); - - it('can use offset() method with stream()', async () => { - let received = 0; - await addDocs({foo: 'a'}, {foo: 'b'}); - - const stream = randomCol.orderBy('foo').offset(1).stream(); - for await (const doc of stream) { - expect(doc).to.be.an.instanceOf(QueryDocumentSnapshot); - ++received; - } - - expect(received).to.equal(1); - }); - - it('can run offset(num), where num is larger than the collection size on get()', async () => { - await addDocs({foo: 'a'}, {foo: 'b'}); - const res = await compareQueryAndPipeline( - randomCol.orderBy('foo').offset(3), - ); - expect(res.empty); - }); - - it('can run offset(num), where num is larger than the collection size on stream()', async () => { - let received = 0; - await addDocs({foo: 'a'}, {foo: 'b'}); - const stream = randomCol.orderBy('foo').offset(3).stream(); - for await (const doc of stream) { - expect(doc).to.be.an.instanceOf(QueryDocumentSnapshot); - ++received; - } - expect(received).to.equal(0); - }); - - it('supports Unicode in document names', async () => { - const collRef = randomCol.doc('доброеутро').collection('coll'); - await collRef.add({}); - const snapshot = await compareQueryAndPipeline(collRef); - expect(snapshot.size).to.equal(1); - }); - - it('supports pagination', () => { - const batch = firestore.batch(); - - for (let i = 0; i < 10; ++i) { - batch.set(randomCol.doc('doc' + i), {val: i}); - } - - const query = randomCol.orderBy('val').limit(3); - - return batch - .commit() - .then(() => paginateResults(query)) - .then(results => { - expect(results.pages).to.equal(4); - expect(results.docs).to.have.length(10); - }); - }); - - it('supports pagination with where() clauses', () => { - const batch = firestore.batch(); - - for (let i = 0; i < 10; ++i) { - batch.set(randomCol.doc('doc' + i), {val: i}); - } - - const query = randomCol.where('val', '>=', 1).limit(3); - - return batch - .commit() - .then(() => paginateResults(query)) - .then(results => { - expect(results.pages).to.equal(3); - expect(results.docs).to.have.length(9); - }); - }); - - it('supports pagination with array-contains filter', () => { - const batch = firestore.batch(); - - for (let i = 0; i < 10; ++i) { - batch.set(randomCol.doc('doc' + i), {array: ['foo']}); - } - - const query = randomCol.where('array', 'array-contains', 'foo').limit(3); - - return batch - .commit() - .then(() => paginateResults(query)) - .then(results => { - expect(results.pages).to.equal(4); - expect(results.docs).to.have.length(10); - }); - }); - - it('has startAt() method', async () => { - await addDocs({foo: 'a'}, {foo: 'b'}); - const res = await randomCol.orderBy('foo').startAt('b').get(); - expectDocs(res, {foo: 'b'}); - }); - - it('startAt() adds implicit order by for DocumentSnapshot', async () => { - const references = await addDocs({foo: 'a'}, {foo: 'b'}); - const docSnap = await references[1].get(); - const res = await randomCol.startAt(docSnap).get(); - expectDocs(res, {foo: 'b'}); - }); - - it('has startAfter() method', async () => { - await addDocs({foo: 'a'}, {foo: 'b'}); - const res = await randomCol.orderBy('foo').startAfter('a').get(); - expectDocs(res, {foo: 'b'}); - }); - - it('has endAt() method', async () => { - await addDocs({foo: 'a'}, {foo: 'b'}); - const res = await randomCol.orderBy('foo').endAt('b').get(); - expectDocs(res, {foo: 'a'}, {foo: 'b'}); - }); - - it('has endBefore() method', async () => { - await addDocs({foo: 'a'}, {foo: 'b'}); - const res = await randomCol.orderBy('foo').endBefore('b').get(); - expectDocs(res, {foo: 'a'}); - }); - - it('has stream() method', done => { - let received = 0; - const ref1 = randomCol.doc('doc1'); - const ref2 = randomCol.doc('doc2'); - - void Promise.all([ref1.set({foo: 'a'}), ref2.set({foo: 'b'})]).then( - () => { - return randomCol - .stream() - .on('data', d => { - expect(d).to.be.an.instanceOf(DocumentSnapshot); - ++received; - }) - .on('end', () => { - expect(received).to.equal(2); - done(); - }); - }, - ); - }); - - it('stream() supports readable[Symbol.asyncIterator]()', async () => { - let received = 0; - await randomCol.doc().set({foo: 'bar'}); - await randomCol.doc().set({foo: 'bar'}); - - const stream = randomCol.stream(); - for await (const doc of stream) { - expect(doc).to.be.an.instanceOf(QueryDocumentSnapshot); - ++received; - } - - expect(received).to.equal(2); - }); - - it('can query collection groups', async () => { - // Use `randomCol` to get a random collection group name to use but ensure - // it starts with 'b' for predictable ordering. - const collectionGroup = 'b' + randomCol.id; - - const docPaths = [ - `abc/123/${collectionGroup}/cg-doc1`, - `abc/123/${collectionGroup}/cg-doc2`, - `${collectionGroup}/cg-doc3`, - `${collectionGroup}/cg-doc4`, - `def/456/${collectionGroup}/cg-doc5`, - `${collectionGroup}/virtual-doc/nested-coll/not-cg-doc`, - `x${collectionGroup}/not-cg-doc`, - `${collectionGroup}x/not-cg-doc`, - `abc/123/${collectionGroup}x/not-cg-doc`, - `abc/123/x${collectionGroup}/not-cg-doc`, - `abc/${collectionGroup}`, - ]; - const batch = firestore.batch(); - for (const docPath of docPaths) { - batch.set(firestore.doc(docPath), {x: 1}); - } - await batch.commit(); - - const querySnapshot = await compareQueryAndPipeline( - firestore.collectionGroup(collectionGroup), - ); - expect(querySnapshot.docs.map(d => d.id)).to.deep.equal([ - 'cg-doc1', - 'cg-doc2', - 'cg-doc3', - 'cg-doc4', - 'cg-doc5', - ]); - }); - - it('can query collection groups with startAt / endAt by arbitrary documentId', async () => { - // Use `randomCol` to get a random collection group name to use but - // ensure it starts with 'b' for predictable ordering. - const collectionGroup = 'b' + randomCol.id; - - const docPaths = [ - `a/a/${collectionGroup}/cg-doc1`, - `a/b/a/b/${collectionGroup}/cg-doc2`, - `a/b/${collectionGroup}/cg-doc3`, - `a/b/c/d/${collectionGroup}/cg-doc4`, - `a/c/${collectionGroup}/cg-doc5`, - `${collectionGroup}/cg-doc6`, - 'a/b/nope/nope', - ]; - const batch = firestore.batch(); - for (const docPath of docPaths) { - batch.set(firestore.doc(docPath), {x: 1}); - } - await batch.commit(); + await batch.commit(); let querySnapshot = await firestore .collectionGroup(collectionGroup) @@ -1068,63 +1063,145 @@ import {IndexTestHelper} from './index_test_helper'; .endBefore(`a/b/${collectionGroup}/cg-doc3`) .get(); expect(querySnapshot.docs.map(d => d.id)).to.deep.equal(['cg-doc2']); - }); + }, + ); + + it('can query collection groups with where filters on arbitrary documentId', async () => { + // Use `randomCol` to get a random collection group name to use but + // ensure it starts with 'b' for predictable ordering. + const collectionGroup = 'b' + randomCol.id; + + const docPaths = [ + `a/a/${collectionGroup}/cg-doc1`, + `a/b/a/b/${collectionGroup}/cg-doc2`, + `a/b/${collectionGroup}/cg-doc3`, + `a/b/c/d/${collectionGroup}/cg-doc4`, + `a/c/${collectionGroup}/cg-doc5`, + `${collectionGroup}/cg-doc6`, + 'a/b/nope/nope', + ]; + const batch = firestore.batch(); + for (const docPath of docPaths) { + batch.set(firestore.doc(docPath), {x: 1}); + } + await batch.commit(); - it('can query collection groups with where filters on arbitrary documentId', async () => { - // Use `randomCol` to get a random collection group name to use but - // ensure it starts with 'b' for predictable ordering. - const collectionGroup = 'b' + randomCol.id; + let querySnapshot = await compareQueryAndPipeline( + firestore + .collectionGroup(collectionGroup) + .where(FieldPath.documentId(), '>=', 'a/b') + .where(FieldPath.documentId(), '<=', 'a/b0'), + ); + expect(querySnapshot.docs.map(d => d.id)).to.deep.equal([ + 'cg-doc2', + 'cg-doc3', + 'cg-doc4', + ]); + + querySnapshot = await compareQueryAndPipeline( + firestore + .collectionGroup(collectionGroup) + .where(FieldPath.documentId(), '>', 'a/b') + .where(FieldPath.documentId(), '<', `a/b/${collectionGroup}/cg-doc3`), + ); + expect(querySnapshot.docs.map(d => d.id)).to.deep.equal(['cg-doc2']); + }); + + it('can query large collections', async () => { + // @grpc/grpc-js v0.4.1 failed to deliver the full set of query results for + // larger collections (https://github.com/grpc/grpc-node/issues/895); + const batch = firestore.batch(); + for (let i = 0; i < 100; ++i) { + batch.create(randomCol.doc(), {}); + } + await batch.commit(); + + const snapshot = await compareQueryAndPipeline(randomCol); + expect(snapshot.size).to.equal(100); + }); + + // TODO wait for implicit sort order decision + it.skipEnterprise('supports OR queries', async () => { + const collection = await testCollectionWithDocs({ + doc1: {a: 1, b: 0}, + doc2: {a: 2, b: 1}, + doc3: {a: 3, b: 2}, + doc4: {a: 1, b: 3}, + doc5: {a: 1, b: 1}, + }); - const docPaths = [ - `a/a/${collectionGroup}/cg-doc1`, - `a/b/a/b/${collectionGroup}/cg-doc2`, - `a/b/${collectionGroup}/cg-doc3`, - `a/b/c/d/${collectionGroup}/cg-doc4`, - `a/c/${collectionGroup}/cg-doc5`, - `${collectionGroup}/cg-doc6`, - 'a/b/nope/nope', - ]; - const batch = firestore.batch(); - for (const docPath of docPaths) { - batch.set(firestore.doc(docPath), {x: 1}); - } - await batch.commit(); + // Two equalities: a==1 || b==1. + expectDocs( + await compareQueryAndPipeline( + collection.where( + Filter.or(Filter.where('a', '==', 1), Filter.where('b', '==', 1)), + ), + ), + 'doc1', + 'doc2', + 'doc4', + 'doc5', + ); - let querySnapshot = await compareQueryAndPipeline( - firestore - .collectionGroup(collectionGroup) - .where(FieldPath.documentId(), '>=', 'a/b') - .where(FieldPath.documentId(), '<=', 'a/b0'), - ); - expect(querySnapshot.docs.map(d => d.id)).to.deep.equal([ - 'cg-doc2', - 'cg-doc3', - 'cg-doc4', - ]); + // (a==1 && b==0) || (a==3 && b==2) + expectDocs( + await compareQueryAndPipeline( + collection.where( + Filter.or( + Filter.and(Filter.where('a', '==', 1), Filter.where('b', '==', 0)), + Filter.and(Filter.where('a', '==', 3), Filter.where('b', '==', 2)), + ), + ), + ), + 'doc1', + 'doc3', + ); - querySnapshot = await compareQueryAndPipeline( - firestore - .collectionGroup(collectionGroup) - .where(FieldPath.documentId(), '>', 'a/b') - .where(FieldPath.documentId(), '<', `a/b/${collectionGroup}/cg-doc3`), - ); - expect(querySnapshot.docs.map(d => d.id)).to.deep.equal(['cg-doc2']); - }); + // a==1 && (b==0 || b==3). + expectDocs( + await compareQueryAndPipeline( + collection.where( + Filter.and( + Filter.where('a', '==', 1), + Filter.or(Filter.where('b', '==', 0), Filter.where('b', '==', 3)), + ), + ), + ), + 'doc1', + 'doc4', + ); - it('can query large collections', async () => { - // @grpc/grpc-js v0.4.1 failed to deliver the full set of query results for - // larger collections (https://github.com/grpc/grpc-node/issues/895); - const batch = firestore.batch(); - for (let i = 0; i < 100; ++i) { - batch.create(randomCol.doc(), {}); - } - await batch.commit(); + // (a==2 || b==2) && (a==3 || b==3) + expectDocs( + await compareQueryAndPipeline( + collection.where( + Filter.and( + Filter.or(Filter.where('a', '==', 2), Filter.where('b', '==', 2)), + Filter.or(Filter.where('a', '==', 3), Filter.where('b', '==', 3)), + ), + ), + ), + 'doc3', + ); - const snapshot = await compareQueryAndPipeline(randomCol); - expect(snapshot.size).to.equal(100); - }); + // Test with limits without orderBy (the __name__ ordering is the tie breaker). + expectDocs( + await compareQueryAndPipeline( + collection + .where( + Filter.or(Filter.where('a', '==', 2), Filter.where('b', '==', 1)), + ) + .limit(1), + ), + 'doc2', + ); + }); - it('supports OR queries', async () => { + // Skip this test if running against production because it results in a 'missing index' error. + // The Firestore Emulator, however, does serve these queries. + (process.env.FIRESTORE_EMULATOR_HOST === undefined ? it : it)( + 'supports OR queries with composite indexes', + async () => { const collection = await testCollectionWithDocs({ doc1: {a: 1, b: 0}, doc2: {a: 2, b: 1}, @@ -1133,173 +1210,105 @@ import {IndexTestHelper} from './index_test_helper'; doc5: {a: 1, b: 1}, }); - // Two equalities: a==1 || b==1. + // with one inequality: a>2 || b==1. expectDocs( await compareQueryAndPipeline( collection.where( - Filter.or(Filter.where('a', '==', 1), Filter.where('b', '==', 1)), + Filter.or(Filter.where('a', '>', 2), Filter.where('b', '==', 1)), ), ), - 'doc1', - 'doc2', - 'doc4', 'doc5', + 'doc2', + 'doc3', ); - // (a==1 && b==0) || (a==3 && b==2) + // Test with limits (implicit order by ASC): (a==1) || (b > 0) LIMIT 2 expectDocs( await compareQueryAndPipeline( - collection.where( - Filter.or( - Filter.and( - Filter.where('a', '==', 1), - Filter.where('b', '==', 0), - ), - Filter.and( - Filter.where('a', '==', 3), - Filter.where('b', '==', 2), - ), - ), - ), + collection + .where( + Filter.or(Filter.where('a', '==', 1), Filter.where('b', '>', 0)), + ) + .limit(2), ), 'doc1', - 'doc3', + 'doc2', ); - // a==1 && (b==0 || b==3). + // Test with limits (explicit order by): (a==1) || (b > 0) LIMIT_TO_LAST 2 + // Note: The public query API does not allow implicit ordering when limitToLast is used. expectDocs( await compareQueryAndPipeline( - collection.where( - Filter.and( - Filter.where('a', '==', 1), - Filter.or(Filter.where('b', '==', 0), Filter.where('b', '==', 3)), - ), - ), + collection + .where( + Filter.or(Filter.where('a', '==', 1), Filter.where('b', '>', 0)), + ) + .limitToLast(2) + .orderBy('b'), ), - 'doc1', + 'doc3', 'doc4', ); - // (a==2 || b==2) && (a==3 || b==3) + // Test with limits (explicit order by ASC): (a==2) || (b == 1) ORDER BY a LIMIT 1 expectDocs( await compareQueryAndPipeline( - collection.where( - Filter.and( - Filter.or(Filter.where('a', '==', 2), Filter.where('b', '==', 2)), - Filter.or(Filter.where('a', '==', 3), Filter.where('b', '==', 3)), - ), - ), + collection + .where( + Filter.or(Filter.where('a', '==', 2), Filter.where('b', '==', 1)), + ) + .limit(1) + .orderBy('a'), ), - 'doc3', + 'doc5', ); - // Test with limits without orderBy (the __name__ ordering is the tie breaker). + // Test with limits (explicit order by DESC): (a==2) || (b == 1) ORDER BY a LIMIT 1 expectDocs( await compareQueryAndPipeline( collection .where( Filter.or(Filter.where('a', '==', 2), Filter.where('b', '==', 1)), ) - .limit(1), + .limit(1) + .orderBy('a', 'desc'), ), 'doc2', ); + }, + ); + + it('supports OR queries on documents with missing fields', async () => { + const collection = await testCollectionWithDocs({ + doc1: {a: 1, b: 0}, + doc2: {b: 1}, + doc3: {a: 3, b: 2}, + doc4: {a: 1, b: 3}, + doc5: {a: 1}, + doc6: {a: 2}, }); - // Skip this test if running against production because it results in a 'missing index' error. - // The Firestore Emulator, however, does serve these queries. - (process.env.FIRESTORE_EMULATOR_HOST === undefined ? it : it)( - 'supports OR queries with composite indexes', - async () => { - const collection = await testCollectionWithDocs({ - doc1: {a: 1, b: 0}, - doc2: {a: 2, b: 1}, - doc3: {a: 3, b: 2}, - doc4: {a: 1, b: 3}, - doc5: {a: 1, b: 1}, - }); - - // with one inequality: a>2 || b==1. - expectDocs( - await compareQueryAndPipeline( - collection.where( - Filter.or(Filter.where('a', '>', 2), Filter.where('b', '==', 1)), - ), - ), - 'doc5', - 'doc2', - 'doc3', - ); - - // Test with limits (implicit order by ASC): (a==1) || (b > 0) LIMIT 2 - expectDocs( - await compareQueryAndPipeline( - collection - .where( - Filter.or( - Filter.where('a', '==', 1), - Filter.where('b', '>', 0), - ), - ) - .limit(2), - ), - 'doc1', - 'doc2', - ); - - // Test with limits (explicit order by): (a==1) || (b > 0) LIMIT_TO_LAST 2 - // Note: The public query API does not allow implicit ordering when limitToLast is used. - expectDocs( - await compareQueryAndPipeline( - collection - .where( - Filter.or( - Filter.where('a', '==', 1), - Filter.where('b', '>', 0), - ), - ) - .limitToLast(2) - .orderBy('b'), - ), - 'doc3', - 'doc4', - ); - - // Test with limits (explicit order by ASC): (a==2) || (b == 1) ORDER BY a LIMIT 1 - expectDocs( - await compareQueryAndPipeline( - collection - .where( - Filter.or( - Filter.where('a', '==', 2), - Filter.where('b', '==', 1), - ), - ) - .limit(1) - .orderBy('a'), - ), - 'doc5', - ); - - // Test with limits (explicit order by DESC): (a==2) || (b == 1) ORDER BY a LIMIT 1 - expectDocs( - await compareQueryAndPipeline( - collection - .where( - Filter.or( - Filter.where('a', '==', 2), - Filter.where('b', '==', 1), - ), - ) - .limit(1) - .orderBy('a', 'desc'), - ), - 'doc2', - ); - }, + // Query: a==1 || b==1 + // There's no explicit nor implicit orderBy. Documents with missing 'a' or missing 'b' should be + // allowed if the document matches at least one disjunction term. + expectDocs( + await compareQueryAndPipeline( + collection.where( + Filter.or(Filter.where('a', '==', 1), Filter.where('b', '==', 1)), + ), + ), + 'doc1', + 'doc2', + 'doc4', + 'doc5', ); + }); - it('supports OR queries on documents with missing fields', async () => { + // Skip this test if running against production because it results in a 'missing index' error. + // TODO Enterprise wait for implicit sort order decision + it.skipClassic.skipEnterprise( + 'supports OR queries on documents with missing fields', + async () => { const collection = await testCollectionWithDocs({ doc1: {a: 1, b: 0}, doc2: {b: 1}, @@ -1309,105 +1318,96 @@ import {IndexTestHelper} from './index_test_helper'; doc6: {a: 2}, }); - // Query: a==1 || b==1 - // There's no explicit nor implicit orderBy. Documents with missing 'a' or missing 'b' should be - // allowed if the document matches at least one disjunction term. + // Query: a==1 || b==1 order by a. + // doc2 should not be included because it's missing the field 'a', and we have "orderBy a". expectDocs( await compareQueryAndPipeline( - collection.where( - Filter.or(Filter.where('a', '==', 1), Filter.where('b', '==', 1)), - ), + collection + .where( + Filter.or(Filter.where('a', '==', 1), Filter.where('b', '==', 1)), + ) + .orderBy('a'), ), 'doc1', - 'doc2', 'doc4', 'doc5', ); - }); - - // Skip this test if running against production because it results in a 'missing index' error. - // The Firestore Emulator, however, does serve these queries. - (process.env.FIRESTORE_EMULATOR_HOST === undefined ? it : it)( - 'supports OR queries on documents with missing fields', - async () => { - const collection = await testCollectionWithDocs({ - doc1: {a: 1, b: 0}, - doc2: {b: 1}, - doc3: {a: 3, b: 2}, - doc4: {a: 1, b: 3}, - doc5: {a: 1}, - doc6: {a: 2}, - }); - - // Query: a==1 || b==1 order by a. - // doc2 should not be included because it's missing the field 'a', and we have "orderBy a". - expectDocs( - await compareQueryAndPipeline( - collection - .where( - Filter.or( - Filter.where('a', '==', 1), - Filter.where('b', '==', 1), - ), - ) - .orderBy('a'), - ), - 'doc1', - 'doc4', - 'doc5', - ); - // Query: a==1 || b==1 order by b. - // doc5 should not be included because it's missing the field 'b', and we have "orderBy b". - expectDocs( - await compareQueryAndPipeline( - collection - .where( - Filter.or( - Filter.where('a', '==', 1), - Filter.where('b', '==', 1), - ), - ) - .orderBy('b'), - ), - 'doc1', - 'doc2', - 'doc4', - ); + // Query: a==1 || b==1 order by b. + // doc5 should not be included because it's missing the field 'b', and we have "orderBy b". + expectDocs( + await compareQueryAndPipeline( + collection + .where( + Filter.or(Filter.where('a', '==', 1), Filter.where('b', '==', 1)), + ) + .orderBy('b'), + ), + 'doc1', + 'doc2', + 'doc4', + ); - // Query: a>2 || b==1. - // This query has an implicit 'order by a'. - // doc2 should not be included because it's missing the field 'a'. - expectDocs( - await compareQueryAndPipeline( - collection.where( - Filter.or(Filter.where('a', '>', 2), Filter.where('b', '==', 1)), - ), + // Query: a>2 || b==1. + // This query has an implicit 'order by a'. + // doc2 should not be included because it's missing the field 'a'. + expectDocs( + await compareQueryAndPipeline( + collection.where( + Filter.or(Filter.where('a', '>', 2), Filter.where('b', '==', 1)), ), - 'doc3', - ); + ), + 'doc3', + ); - // Query: a>1 || b==1 order by a order by b. - // doc6 should not be included because it's missing the field 'b'. - // doc2 should not be included because it's missing the field 'a'. - expectDocs( - await compareQueryAndPipeline( - collection - .where( - Filter.or( - Filter.where('a', '>', 1), - Filter.where('b', '==', 1), - ), - ) - .orderBy('a') - .orderBy('b'), - ), - 'doc3', - ); - }, + // Query: a>1 || b==1 order by a order by b. + // doc6 should not be included because it's missing the field 'b'. + // doc2 should not be included because it's missing the field 'a'. + expectDocs( + await compareQueryAndPipeline( + collection + .where( + Filter.or(Filter.where('a', '>', 1), Filter.where('b', '==', 1)), + ) + .orderBy('a') + .orderBy('b'), + ), + 'doc3', + ); + }, + ); + + it('supports OR queries with in', async () => { + const collection = await testCollectionWithDocs({ + doc1: {a: 1, b: 0}, + doc2: {b: 1}, + doc3: {a: 3, b: 2}, + doc4: {a: 1, b: 3}, + doc5: {a: 1}, + doc6: {a: 2}, + }); + + // Query: a==2 || b in [2, 3] + expectDocs( + await compareQueryAndPipeline( + collection.where( + Filter.or( + Filter.where('a', '==', 2), + Filter.where('b', 'in', [2, 3]), + ), + ), + ), + 'doc3', + 'doc4', + 'doc6', ); + }); - it('supports OR queries with in', async () => { + // Skip this test if running against production because it results in a 'missing index' error. + // The Firestore Emulator, however, does serve these queries. + (process.env.FIRESTORE_EMULATOR_HOST === undefined ? it : it)( + 'supports OR queries with not-in', + async () => { const collection = await testCollectionWithDocs({ doc1: {a: 1, b: 0}, doc2: {b: 1}, @@ -1417,633 +1417,617 @@ import {IndexTestHelper} from './index_test_helper'; doc6: {a: 2}, }); - // Query: a==2 || b in [2, 3] + // a==2 || (b != 2 && b != 3) + // Has implicit "orderBy b" expectDocs( await compareQueryAndPipeline( collection.where( Filter.or( Filter.where('a', '==', 2), - Filter.where('b', 'in', [2, 3]), + Filter.where('b', 'not-in', [2, 3]), ), ), ), - 'doc3', - 'doc4', - 'doc6', + 'doc1', + 'doc2', ); + }, + ); + + it('supports OR queries with array membership', async () => { + const collection = await testCollectionWithDocs({ + doc1: {a: 1, b: [0]}, + doc2: {b: [1]}, + doc3: {a: 3, b: [2, 7]}, + doc4: {a: 1, b: [3, 7]}, + doc5: {a: 1}, + doc6: {a: 2}, }); - // Skip this test if running against production because it results in a 'missing index' error. - // The Firestore Emulator, however, does serve these queries. - (process.env.FIRESTORE_EMULATOR_HOST === undefined ? it : it)( - 'supports OR queries with not-in', - async () => { - const collection = await testCollectionWithDocs({ - doc1: {a: 1, b: 0}, - doc2: {b: 1}, - doc3: {a: 3, b: 2}, - doc4: {a: 1, b: 3}, - doc5: {a: 1}, - doc6: {a: 2}, - }); - - // a==2 || (b != 2 && b != 3) - // Has implicit "orderBy b" - expectDocs( - await compareQueryAndPipeline( - collection.where( - Filter.or( - Filter.where('a', '==', 2), - Filter.where('b', 'not-in', [2, 3]), - ), - ), + // Query: a==2 || b array-contains 7 + expectDocs( + await compareQueryAndPipeline( + collection.where( + Filter.or( + Filter.where('a', '==', 2), + Filter.where('b', 'array-contains', 7), ), - 'doc1', - 'doc2', - ); - }, + ), + ), + 'doc3', + 'doc4', + 'doc6', ); - it('supports OR queries with array membership', async () => { - const collection = await testCollectionWithDocs({ - doc1: {a: 1, b: [0]}, - doc2: {b: [1]}, - doc3: {a: 3, b: [2, 7]}, - doc4: {a: 1, b: [3, 7]}, - doc5: {a: 1}, - doc6: {a: 2}, - }); - - // Query: a==2 || b array-contains 7 - expectDocs( - await compareQueryAndPipeline( - collection.where( - Filter.or( - Filter.where('a', '==', 2), - Filter.where('b', 'array-contains', 7), - ), + // a==2 || b array-contains-any [0, 3] + // Has implicit "orderBy b" + expectDocs( + await compareQueryAndPipeline( + collection.where( + Filter.or( + Filter.where('a', '==', 2), + Filter.where('b', 'array-contains-any', [0, 3]), ), ), - 'doc3', - 'doc4', - 'doc6', - ); + ), + 'doc1', + 'doc4', + 'doc6', + ); + }); - // a==2 || b array-contains-any [0, 3] - // Has implicit "orderBy b" - expectDocs( - await compareQueryAndPipeline( - collection.where( - Filter.or( - Filter.where('a', '==', 2), - Filter.where('b', 'array-contains-any', [0, 3]), - ), - ), - ), - 'doc1', - 'doc4', - 'doc6', - ); - }); + describe('watch', () => { + interface ExpectedChange { + type: string; + doc: DocumentSnapshot; + } - describe('watch', () => { - interface ExpectedChange { - type: string; - doc: DocumentSnapshot; - } + const currentDeferred = new DeferredPromise(); - const currentDeferred = new DeferredPromise(); - - const snapshot = (id: string, data: DocumentData) => { - const ref = randomCol.doc(id); - const fields = ref.firestore._serializer!.encodeFields(data); - return randomCol.firestore.snapshot_( - { - name: - 'projects/ignored/databases/(default)/documents/' + - ref._path.relativeName, - fields, - createTime: {seconds: 0, nanos: 0}, - updateTime: {seconds: 0, nanos: 0}, - }, - {seconds: 0, nanos: 0}, - ); - }; + const snapshot = (id: string, data: DocumentData) => { + const ref = randomCol.doc(id); + const fields = ref.firestore._serializer!.encodeFields(data); + return randomCol.firestore.snapshot_( + { + name: + 'projects/ignored/databases/(default)/documents/' + + ref._path.relativeName, + fields, + createTime: {seconds: 0, nanos: 0}, + updateTime: {seconds: 0, nanos: 0}, + }, + {seconds: 0, nanos: 0}, + ); + }; - const docChange = ( - type: string, - id: string, - data: DocumentData, - ): ExpectedChange => { - return { - type, - doc: snapshot(id, data), - }; + const docChange = ( + type: string, + id: string, + data: DocumentData, + ): ExpectedChange => { + return { + type, + doc: snapshot(id, data), }; + }; - const added = (id: string, data: DocumentData) => - docChange('added', id, data); - const modified = (id: string, data: DocumentData) => - docChange('modified', id, data); - const removed = (id: string, data: DocumentData) => - docChange('removed', id, data); - - function resetPromise() { - currentDeferred.promise = new Promise((resolve, reject) => { - currentDeferred.resolve = resolve; - currentDeferred.reject = reject; - }); - } + const added = (id: string, data: DocumentData) => + docChange('added', id, data); + const modified = (id: string, data: DocumentData) => + docChange('modified', id, data); + const removed = (id: string, data: DocumentData) => + docChange('removed', id, data); + + function resetPromise() { + currentDeferred.promise = new Promise((resolve, reject) => { + currentDeferred.resolve = resolve; + currentDeferred.reject = reject; + }); + } - function waitForSnapshot(): Promise { - return currentDeferred.promise!.then(snapshot => { - resetPromise(); - return snapshot; - }); - } + function waitForSnapshot(): Promise { + return currentDeferred.promise!.then(snapshot => { + resetPromise(); + return snapshot; + }); + } - function snapshotsEqual( - actual: QuerySnapshot, - expected: {docs: DocumentSnapshot[]; docChanges: ExpectedChange[]}, - ) { - let i; - expect(actual.size).to.equal(expected.docs.length); - for (i = 0; i < expected.docs.length && i < actual.size; i++) { - expect(actual.docs[i].ref.id).to.equal(expected.docs[i].ref.id); - expect(actual.docs[i].data()).to.deep.equal(expected.docs[i].data()); - } - const actualDocChanges = actual.docChanges(); - expect(actualDocChanges.length).to.equal(expected.docChanges.length); - for (i = 0; i < expected.docChanges.length; i++) { - expect(actualDocChanges[i].type).to.equal( - expected.docChanges[i].type, - ); - expect(actualDocChanges[i].doc.ref.id).to.equal( - expected.docChanges[i].doc.ref.id, - ); - expect(actualDocChanges[i].doc.data()).to.deep.equal( - expected.docChanges[i].doc.data(), - ); - expect(actualDocChanges[i].doc.readTime).to.exist; - expect(actualDocChanges[i].doc.createTime).to.exist; - expect(actualDocChanges[i].doc.updateTime).to.exist; - } - expect(actual.readTime).to.exist; + function snapshotsEqual( + actual: QuerySnapshot, + expected: {docs: DocumentSnapshot[]; docChanges: ExpectedChange[]}, + ) { + let i; + expect(actual.size).to.equal(expected.docs.length); + for (i = 0; i < expected.docs.length && i < actual.size; i++) { + expect(actual.docs[i].ref.id).to.equal(expected.docs[i].ref.id); + expect(actual.docs[i].data()).to.deep.equal(expected.docs[i].data()); } + const actualDocChanges = actual.docChanges(); + expect(actualDocChanges.length).to.equal(expected.docChanges.length); + for (i = 0; i < expected.docChanges.length; i++) { + expect(actualDocChanges[i].type).to.equal(expected.docChanges[i].type); + expect(actualDocChanges[i].doc.ref.id).to.equal( + expected.docChanges[i].doc.ref.id, + ); + expect(actualDocChanges[i].doc.data()).to.deep.equal( + expected.docChanges[i].doc.data(), + ); + expect(actualDocChanges[i].doc.readTime).to.exist; + expect(actualDocChanges[i].doc.createTime).to.exist; + expect(actualDocChanges[i].doc.updateTime).to.exist; + } + expect(actual.readTime).to.exist; + } - beforeEach(() => resetPromise()); + beforeEach(() => resetPromise()); - it('handles changing a doc', () => { - const ref1 = randomCol.doc('doc1'); - const ref2 = randomCol.doc('doc2'); + it('handles changing a doc', () => { + const ref1 = randomCol.doc('doc1'); + const ref2 = randomCol.doc('doc2'); - const unsubscribe = randomCol.onSnapshot( - snapshot => { - currentDeferred.resolve(snapshot); - }, - err => { - currentDeferred.reject!(err); - }, - ); + const unsubscribe = randomCol.onSnapshot( + snapshot => { + currentDeferred.resolve(snapshot); + }, + err => { + currentDeferred.reject!(err); + }, + ); - return waitForSnapshot() - .then(results => { - snapshotsEqual(results, {docs: [], docChanges: []}); - // Add a result. - return ref1.set({foo: 'a'}); - }) - .then(() => { - return waitForSnapshot(); - }) - .then(results => { - snapshotsEqual(results, { - docs: [snapshot('doc1', {foo: 'a'})], - docChanges: [added('doc1', {foo: 'a'})], - }); - // Add another result. - return ref2.set({foo: 'b'}); - }) - .then(() => { - return waitForSnapshot(); - }) - .then(results => { - snapshotsEqual(results, { - docs: [ - snapshot('doc1', {foo: 'a'}), - snapshot('doc2', {foo: 'b'}), - ], - docChanges: [added('doc2', {foo: 'b'})], - }); - // Change a result. - return ref2.set({bar: 'c'}); - }) - .then(() => { - return waitForSnapshot(); - }) - .then(results => { - snapshotsEqual(results, { - docs: [ - snapshot('doc1', {foo: 'a'}), - snapshot('doc2', {bar: 'c'}), - ], - docChanges: [modified('doc2', {bar: 'c'})], - }); - unsubscribe(); + return waitForSnapshot() + .then(results => { + snapshotsEqual(results, {docs: [], docChanges: []}); + // Add a result. + return ref1.set({foo: 'a'}); + }) + .then(() => { + return waitForSnapshot(); + }) + .then(results => { + snapshotsEqual(results, { + docs: [snapshot('doc1', {foo: 'a'})], + docChanges: [added('doc1', {foo: 'a'})], }); - }); + // Add another result. + return ref2.set({foo: 'b'}); + }) + .then(() => { + return waitForSnapshot(); + }) + .then(results => { + snapshotsEqual(results, { + docs: [snapshot('doc1', {foo: 'a'}), snapshot('doc2', {foo: 'b'})], + docChanges: [added('doc2', {foo: 'b'})], + }); + // Change a result. + return ref2.set({bar: 'c'}); + }) + .then(() => { + return waitForSnapshot(); + }) + .then(results => { + snapshotsEqual(results, { + docs: [snapshot('doc1', {foo: 'a'}), snapshot('doc2', {bar: 'c'})], + docChanges: [modified('doc2', {bar: 'c'})], + }); + unsubscribe(); + }); + }); - it("handles changing a doc so it doesn't match", () => { - const ref1 = randomCol.doc('doc1'); - const ref2 = randomCol.doc('doc2'); + it("handles changing a doc so it doesn't match", () => { + const ref1 = randomCol.doc('doc1'); + const ref2 = randomCol.doc('doc2'); - const query = randomCol.where('included', '==', 'yes'); - const unsubscribe = query.onSnapshot( - snapshot => { - currentDeferred.resolve(snapshot); - }, - err => { - currentDeferred.reject(err); - }, - ); + const query = randomCol.where('included', '==', 'yes'); + const unsubscribe = query.onSnapshot( + snapshot => { + currentDeferred.resolve(snapshot); + }, + err => { + currentDeferred.reject(err); + }, + ); - return waitForSnapshot() - .then(results => { - snapshotsEqual(results, {docs: [], docChanges: []}); - // Add a result. - return ref1.set({included: 'yes'}); - }) - .then(() => { - return waitForSnapshot(); - }) - .then(results => { - snapshotsEqual(results, { - docs: [snapshot('doc1', {included: 'yes'})], - docChanges: [added('doc1', {included: 'yes'})], - }); - // Add another result. - return ref2.set({included: 'yes'}); - }) - .then(() => { - return waitForSnapshot(); - }) - .then(results => { - snapshotsEqual(results, { - docs: [ - snapshot('doc1', {included: 'yes'}), - snapshot('doc2', {included: 'yes'}), - ], - docChanges: [added('doc2', {included: 'yes'})], - }); - // Change a result. - return ref2.set({included: 'no'}); - }) - .then(() => { - return waitForSnapshot(); - }) - .then(results => { - snapshotsEqual(results, { - docs: [snapshot('doc1', {included: 'yes'})], - docChanges: [removed('doc2', {included: 'yes'})], - }); - unsubscribe(); + return waitForSnapshot() + .then(results => { + snapshotsEqual(results, {docs: [], docChanges: []}); + // Add a result. + return ref1.set({included: 'yes'}); + }) + .then(() => { + return waitForSnapshot(); + }) + .then(results => { + snapshotsEqual(results, { + docs: [snapshot('doc1', {included: 'yes'})], + docChanges: [added('doc1', {included: 'yes'})], }); - }); + // Add another result. + return ref2.set({included: 'yes'}); + }) + .then(() => { + return waitForSnapshot(); + }) + .then(results => { + snapshotsEqual(results, { + docs: [ + snapshot('doc1', {included: 'yes'}), + snapshot('doc2', {included: 'yes'}), + ], + docChanges: [added('doc2', {included: 'yes'})], + }); + // Change a result. + return ref2.set({included: 'no'}); + }) + .then(() => { + return waitForSnapshot(); + }) + .then(results => { + snapshotsEqual(results, { + docs: [snapshot('doc1', {included: 'yes'})], + docChanges: [removed('doc2', {included: 'yes'})], + }); + unsubscribe(); + }); + }); - it('handles deleting a doc', () => { - const ref1 = randomCol.doc('doc1'); - const ref2 = randomCol.doc('doc2'); + it('handles deleting a doc', () => { + const ref1 = randomCol.doc('doc1'); + const ref2 = randomCol.doc('doc2'); - const unsubscribe = randomCol.onSnapshot( - snapshot => { - currentDeferred.resolve(snapshot); - }, - err => { - currentDeferred.reject(err); - }, - ); + const unsubscribe = randomCol.onSnapshot( + snapshot => { + currentDeferred.resolve(snapshot); + }, + err => { + currentDeferred.reject(err); + }, + ); - return waitForSnapshot() - .then(results => { - snapshotsEqual(results, {docs: [], docChanges: []}); - // Add a result. - return ref1.set({included: 'yes'}); - }) - .then(() => { - return waitForSnapshot(); - }) - .then(results => { - snapshotsEqual(results, { - docs: [snapshot('doc1', {included: 'yes'})], - docChanges: [added('doc1', {included: 'yes'})], - }); - // Add another result. - return ref2.set({included: 'yes'}); - }) - .then(() => { - return waitForSnapshot(); - }) - .then(results => { - snapshotsEqual(results, { - docs: [ - snapshot('doc1', {included: 'yes'}), - snapshot('doc2', {included: 'yes'}), - ], - docChanges: [added('doc2', {included: 'yes'})], - }); - // Delete a result. - return ref2.delete(); - }) - .then(() => { - return waitForSnapshot(); - }) - .then(results => { - snapshotsEqual(results, { - docs: [snapshot('doc1', {included: 'yes'})], - docChanges: [removed('doc2', {included: 'yes'})], - }); - unsubscribe(); + return waitForSnapshot() + .then(results => { + snapshotsEqual(results, {docs: [], docChanges: []}); + // Add a result. + return ref1.set({included: 'yes'}); + }) + .then(() => { + return waitForSnapshot(); + }) + .then(results => { + snapshotsEqual(results, { + docs: [snapshot('doc1', {included: 'yes'})], + docChanges: [added('doc1', {included: 'yes'})], }); - }); - - it('orders limitToLast() correctly', async () => { - const ref1 = randomCol.doc('doc1'); - const ref2 = randomCol.doc('doc2'); - const ref3 = randomCol.doc('doc3'); + // Add another result. + return ref2.set({included: 'yes'}); + }) + .then(() => { + return waitForSnapshot(); + }) + .then(results => { + snapshotsEqual(results, { + docs: [ + snapshot('doc1', {included: 'yes'}), + snapshot('doc2', {included: 'yes'}), + ], + docChanges: [added('doc2', {included: 'yes'})], + }); + // Delete a result. + return ref2.delete(); + }) + .then(() => { + return waitForSnapshot(); + }) + .then(results => { + snapshotsEqual(results, { + docs: [snapshot('doc1', {included: 'yes'})], + docChanges: [removed('doc2', {included: 'yes'})], + }); + unsubscribe(); + }); + }); - await ref1.set({doc: 1}); - await ref2.set({doc: 2}); - await ref3.set({doc: 3}); + it('orders limitToLast() correctly', async () => { + const ref1 = randomCol.doc('doc1'); + const ref2 = randomCol.doc('doc2'); + const ref3 = randomCol.doc('doc3'); - const unsubscribe = randomCol - .orderBy('doc') - .limitToLast(2) - .onSnapshot(snapshot => currentDeferred.resolve(snapshot)); + await ref1.set({doc: 1}); + await ref2.set({doc: 2}); + await ref3.set({doc: 3}); - const results = await waitForSnapshot(); - snapshotsEqual(results, { - docs: [snapshot('doc2', {doc: 2}), snapshot('doc3', {doc: 3})], - docChanges: [added('doc2', {doc: 2}), added('doc3', {doc: 3})], - }); + const unsubscribe = randomCol + .orderBy('doc') + .limitToLast(2) + .onSnapshot(snapshot => currentDeferred.resolve(snapshot)); - unsubscribe(); + const results = await waitForSnapshot(); + snapshotsEqual(results, { + docs: [snapshot('doc2', {doc: 2}), snapshot('doc3', {doc: 3})], + docChanges: [added('doc2', {doc: 2}), added('doc3', {doc: 3})], }); - it('SDK orders vector field same way as backend', async () => { - // We validate that the SDK orders the vector field the same way as the backend - // by comparing the sort order of vector fields from a Query.get() and - // Query.onSnapshot(). Query.onSnapshot() will return sort order of the SDK, - // and Query.get() will return sort order of the backend. - - // Test data in the order that we expect the backend to sort it. - const docsInOrder = [ - {embedding: [1, 2, 3, 4, 5, 6]}, - {embedding: [100]}, - {embedding: FieldValue.vector([Number.NEGATIVE_INFINITY])}, - {embedding: FieldValue.vector([-100])}, - {embedding: FieldValue.vector([100])}, - {embedding: FieldValue.vector([Number.POSITIVE_INFINITY])}, - {embedding: FieldValue.vector([1, 2])}, - {embedding: FieldValue.vector([2, 2])}, - {embedding: FieldValue.vector([1, 2, 3])}, - {embedding: FieldValue.vector([1, 2, 3, 4])}, - {embedding: FieldValue.vector([1, 2, 3, 4, 5])}, - {embedding: FieldValue.vector([1, 2, 100, 4, 4])}, - {embedding: FieldValue.vector([100, 2, 3, 4, 5])}, - {embedding: {HELLO: 'WORLD'}}, - {embedding: {hello: 'world'}}, - ]; - - const expectedSnapshots = []; - const expectedChanges = []; - - for (let i = 0; i < docsInOrder.length; i++) { - const dr = await randomCol.add(docsInOrder[i]); - expectedSnapshots.push(snapshot(dr.id, docsInOrder[i])); - expectedChanges.push(added(dr.id, docsInOrder[i])); - } + unsubscribe(); + }); - const orderedQuery = randomCol.orderBy('embedding'); + it('SDK orders vector field same way as backend', async () => { + // We validate that the SDK orders the vector field the same way as the backend + // by comparing the sort order of vector fields from a Query.get() and + // Query.onSnapshot(). Query.onSnapshot() will return sort order of the SDK, + // and Query.get() will return sort order of the backend. + + // Test data in the order that we expect the backend to sort it. + const docsInOrder = [ + {embedding: [1, 2, 3, 4, 5, 6]}, + {embedding: [100]}, + {embedding: FieldValue.vector([Number.NEGATIVE_INFINITY])}, + {embedding: FieldValue.vector([-100])}, + {embedding: FieldValue.vector([100])}, + {embedding: FieldValue.vector([Number.POSITIVE_INFINITY])}, + {embedding: FieldValue.vector([1, 2])}, + {embedding: FieldValue.vector([2, 2])}, + {embedding: FieldValue.vector([1, 2, 3])}, + {embedding: FieldValue.vector([1, 2, 3, 4])}, + {embedding: FieldValue.vector([1, 2, 3, 4, 5])}, + {embedding: FieldValue.vector([1, 2, 100, 4, 4])}, + {embedding: FieldValue.vector([100, 2, 3, 4, 5])}, + {embedding: {HELLO: 'WORLD'}}, + {embedding: {hello: 'world'}}, + ]; - const unsubscribe = orderedQuery.onSnapshot( - snapshot => { - currentDeferred.resolve(snapshot); - }, - err => { - currentDeferred.reject!(err); - }, - ); + const expectedSnapshots = []; + const expectedChanges = []; - const watchSnapshot = await waitForSnapshot(); - unsubscribe(); + for (let i = 0; i < docsInOrder.length; i++) { + const dr = await randomCol.add(docsInOrder[i]); + expectedSnapshots.push(snapshot(dr.id, docsInOrder[i])); + expectedChanges.push(added(dr.id, docsInOrder[i])); + } - const getSnapshot = await orderedQuery.get(); + const orderedQuery = randomCol.orderBy('embedding'); - // Compare the snapshot (including sort order) of a snapshot - // from Query.onSnapshot() to an actual snapshot from Query.get() - snapshotsEqual(watchSnapshot, { - docs: getSnapshot.docs, - docChanges: getSnapshot.docChanges(), - }); + const unsubscribe = orderedQuery.onSnapshot( + snapshot => { + currentDeferred.resolve(snapshot); + }, + err => { + currentDeferred.reject!(err); + }, + ); - // Compare the snapshot (including sort order) of a snapshot - // from Query.onSnapshot() to the expected sort order from - // the backend. - snapshotsEqual(watchSnapshot, { - docs: expectedSnapshots, - docChanges: expectedChanges, - }); - }); - }); + const watchSnapshot = await waitForSnapshot(); + unsubscribe(); - (process.env.FIRESTORE_EMULATOR_HOST === undefined - ? describe.skip - : describe)('multiple inequality', () => { - it('supports multiple inequality queries', async () => { - const collection = await testCollectionWithDocs({ - doc1: {key: 'a', sort: 0, v: 0}, - doc2: {key: 'b', sort: 3, v: 1}, - doc3: {key: 'c', sort: 1, v: 3}, - doc4: {key: 'd', sort: 2, v: 2}, - }); + const getSnapshot = await orderedQuery.get(); - // Multiple inequality fields - let results = await compareQueryAndPipeline( - collection - .where('key', '!=', 'a') - .where('sort', '<=', 2) - .where('v', '>', 2), - ); - expectDocs(results, 'doc3'); + // Compare the snapshot (including sort order) of a snapshot + // from Query.onSnapshot() to an actual snapshot from Query.get() + snapshotsEqual(watchSnapshot, { + docs: getSnapshot.docs, + docChanges: getSnapshot.docChanges(), + }); - // Duplicate inequality fields - results = await compareQueryAndPipeline( - collection - .where('key', '!=', 'a') - .where('sort', '<=', 2) - .where('sort', '>', 1), - ); - expectDocs(results, 'doc4'); + // Compare the snapshot (including sort order) of a snapshot + // from Query.onSnapshot() to the expected sort order from + // the backend. + snapshotsEqual(watchSnapshot, { + docs: expectedSnapshots, + docChanges: expectedChanges, + }); + }); + }); - // With multiple IN - results = await compareQueryAndPipeline( - collection - .where('key', '>=', 'a') - .where('sort', '<=', 2) - .where('v', 'in', [2, 3, 4]) - .where('sort', 'in', [2, 3]), - ); - expectDocs(results, 'doc4'); + (process.env.FIRESTORE_EMULATOR_HOST === undefined + ? describe.skip + : describe)('multiple inequality', () => { + it('supports multiple inequality queries', async () => { + const collection = await testCollectionWithDocs({ + doc1: {key: 'a', sort: 0, v: 0}, + doc2: {key: 'b', sort: 3, v: 1}, + doc3: {key: 'c', sort: 1, v: 3}, + doc4: {key: 'd', sort: 2, v: 2}, + }); - // With NOT-IN - results = await compareQueryAndPipeline( - collection - .where('key', '>=', 'a') - .where('sort', '<=', 2) - .where('v', 'not-in', [2, 4, 5]), - ); - expectDocs(results, 'doc1', 'doc3'); + // Multiple inequality fields + let results = await compareQueryAndPipeline( + collection + .where('key', '!=', 'a') + .where('sort', '<=', 2) + .where('v', '>', 2), + ); + expectDocs(results, 'doc3'); - // With orderby - results = await compareQueryAndPipeline( - collection - .where('key', '>=', 'a') - .where('sort', '<=', 2) - .orderBy('v', 'desc'), - ); - expectDocs(results, 'doc3', 'doc4', 'doc1'); + // Duplicate inequality fields + results = await compareQueryAndPipeline( + collection + .where('key', '!=', 'a') + .where('sort', '<=', 2) + .where('sort', '>', 1), + ); + expectDocs(results, 'doc4'); + + // With multiple IN + results = await compareQueryAndPipeline( + collection + .where('key', '>=', 'a') + .where('sort', '<=', 2) + .where('v', 'in', [2, 3, 4]) + .where('sort', 'in', [2, 3]), + ); + expectDocs(results, 'doc4'); + + // With NOT-IN + results = await compareQueryAndPipeline( + collection + .where('key', '>=', 'a') + .where('sort', '<=', 2) + .where('v', 'not-in', [2, 4, 5]), + ); + expectDocs(results, 'doc1', 'doc3'); + + // With orderby + results = await compareQueryAndPipeline( + collection + .where('key', '>=', 'a') + .where('sort', '<=', 2) + .orderBy('v', 'desc'), + ); + expectDocs(results, 'doc3', 'doc4', 'doc1'); - // With limit - results = await compareQueryAndPipeline( - collection - .where('key', '>=', 'a') - .where('sort', '<=', 2) - .orderBy('v', 'desc') - .limit(2), - ); - expectDocs(results, 'doc3', 'doc4'); + // With limit + results = await compareQueryAndPipeline( + collection + .where('key', '>=', 'a') + .where('sort', '<=', 2) + .orderBy('v', 'desc') + .limit(2), + ); + expectDocs(results, 'doc3', 'doc4'); - // With limitToLast - results = await compareQueryAndPipeline( - collection - .where('key', '>=', 'a') - .where('sort', '<=', 2) - .orderBy('v', 'desc') - .limitToLast(2), - ); - expectDocs(results, 'doc4', 'doc1'); + // With limitToLast + results = await compareQueryAndPipeline( + collection + .where('key', '>=', 'a') + .where('sort', '<=', 2) + .orderBy('v', 'desc') + .limitToLast(2), + ); + expectDocs(results, 'doc4', 'doc1'); + }); + + it('can use on special values', async () => { + const collection = await testCollectionWithDocs({ + doc1: {key: 'a', sort: 0, v: 0}, + doc2: {key: 'b', sort: NaN, v: 1}, + doc3: {key: 'c', sort: null, v: 3}, + doc4: {key: 'd', v: 0}, + doc5: {key: 'e', sort: 1}, + doc6: {key: 'f', sort: 1, v: 1}, }); - it('can use on special values', async () => { - const collection = await testCollectionWithDocs({ - doc1: {key: 'a', sort: 0, v: 0}, - doc2: {key: 'b', sort: NaN, v: 1}, - doc3: {key: 'c', sort: null, v: 3}, - doc4: {key: 'd', v: 0}, - doc5: {key: 'e', sort: 1}, - doc6: {key: 'f', sort: 1, v: 1}, - }); + let results = await compareQueryAndPipeline( + collection.where('key', '!=', 'a').where('sort', '<=', 2), + ); + expectDocs(results, 'doc5', 'doc6'); - let results = await compareQueryAndPipeline( - collection.where('key', '!=', 'a').where('sort', '<=', 2), - ); - expectDocs(results, 'doc5', 'doc6'); + results = await compareQueryAndPipeline( + collection + .where('key', '!=', 'a') + .where('sort', '<=', 2) + .where('v', '<=', 1), + ); + expectDocs(results, 'doc6'); + }); - results = await compareQueryAndPipeline( - collection - .where('key', '!=', 'a') - .where('sort', '<=', 2) - .where('v', '<=', 1), - ); - expectDocs(results, 'doc6'); + it('can use with array membership', async () => { + const collection = await testCollectionWithDocs({ + doc1: {key: 'a', sort: 0, v: [0]}, + doc2: {key: 'b', sort: 1, v: [0, 1, 3]}, + doc3: {key: 'c', sort: 1, v: []}, + doc4: {key: 'd', sort: 2, v: [1]}, + doc5: {key: 'e', sort: 3, v: [2, 4]}, + doc6: {key: 'f', sort: 4, v: [NaN]}, + doc7: {key: 'g', sort: 4, v: [null]}, }); - it('can use with array membership', async () => { - const collection = await testCollectionWithDocs({ - doc1: {key: 'a', sort: 0, v: [0]}, - doc2: {key: 'b', sort: 1, v: [0, 1, 3]}, - doc3: {key: 'c', sort: 1, v: []}, - doc4: {key: 'd', sort: 2, v: [1]}, - doc5: {key: 'e', sort: 3, v: [2, 4]}, - doc6: {key: 'f', sort: 4, v: [NaN]}, - doc7: {key: 'g', sort: 4, v: [null]}, - }); - - let results = await compareQueryAndPipeline( - collection - .where('key', '!=', 'a') - .where('sort', '>=', 1) - .where('v', 'array-contains', 0), - ); - expectDocs(results, 'doc2'); + let results = await compareQueryAndPipeline( + collection + .where('key', '!=', 'a') + .where('sort', '>=', 1) + .where('v', 'array-contains', 0), + ); + expectDocs(results, 'doc2'); - results = await compareQueryAndPipeline( - collection - .where('key', '!=', 'a') - .where('sort', '>=', 1) - .where('v', 'array-contains-any', [0, 1]), - ); - expectDocs(results, 'doc2', 'doc4'); - }); + results = await compareQueryAndPipeline( + collection + .where('key', '!=', 'a') + .where('sort', '>=', 1) + .where('v', 'array-contains-any', [0, 1]), + ); + expectDocs(results, 'doc2', 'doc4'); + }); - // Use cursor in following test cases to add implicit order by fields in the sdk and compare the - // result with the query fields normalized in the server. - it('can use with nested field', async () => { - // eslint-disable-next-line @typescript-eslint/no-explicit-any - const testData = (n?: number): any => { - n = n || 1; - return { - name: 'room ' + n, - metadata: { - createdAt: n, - }, - field: 'field ' + n, - 'field.dot': n, - 'field\\slash': n, - }; + // Use cursor in following test cases to add implicit order by fields in the sdk and compare the + // result with the query fields normalized in the server. + it('can use with nested field', async () => { + // eslint-disable-next-line @typescript-eslint/no-explicit-any + const testData = (n?: number): any => { + n = n || 1; + return { + name: 'room ' + n, + metadata: { + createdAt: n, + }, + field: 'field ' + n, + 'field.dot': n, + 'field\\slash': n, }; + }; - const collection = await testCollectionWithDocs({ - doc1: testData(400), - doc2: testData(200), - doc3: testData(100), - doc4: testData(300), - }); + const collection = await testCollectionWithDocs({ + doc1: testData(400), + doc2: testData(200), + doc3: testData(100), + doc4: testData(300), + }); - // ordered by: name asc, metadata.createdAt asc, __name__ asc - let query = collection - .where('metadata.createdAt', '<=', 500) - .where('metadata.createdAt', '>', 100) - .where('name', '!=', 'room 200') - .orderBy('name'); - let docSnap = await collection.doc('doc4').get(); - let queryWithCursor = query.startAt(docSnap); - expectDocs(await compareQueryAndPipeline(query), 'doc4', 'doc1'); - expectDocs(await queryWithCursor.get(), 'doc4', 'doc1'); - - // ordered by: name desc, field desc, field.dot desc, field\\slash desc, __name__ desc - query = collection - .where('field', '>=', 'field 100') - .where(new FieldPath('field.dot'), '!=', 300) - .where('field\\slash', '<', 400) - .orderBy('name', 'desc'); - docSnap = await collection.doc('doc2').get(); - queryWithCursor = query.startAt(docSnap); - expectDocs(await compareQueryAndPipeline(query), 'doc2', 'doc3'); - expectDocs(await queryWithCursor.get(), 'doc2', 'doc3'); + // ordered by: name asc, metadata.createdAt asc, __name__ asc + let query = collection + .where('metadata.createdAt', '<=', 500) + .where('metadata.createdAt', '>', 100) + .where('name', '!=', 'room 200') + .orderBy('name'); + let docSnap = await collection.doc('doc4').get(); + let queryWithCursor = query.startAt(docSnap); + expectDocs(await compareQueryAndPipeline(query), 'doc4', 'doc1'); + expectDocs(await queryWithCursor.get(), 'doc4', 'doc1'); + + // ordered by: name desc, field desc, field.dot desc, field\\slash desc, __name__ desc + query = collection + .where('field', '>=', 'field 100') + .where(new FieldPath('field.dot'), '!=', 300) + .where('field\\slash', '<', 400) + .orderBy('name', 'desc'); + docSnap = await collection.doc('doc2').get(); + queryWithCursor = query.startAt(docSnap); + expectDocs(await compareQueryAndPipeline(query), 'doc2', 'doc3'); + expectDocs(await queryWithCursor.get(), 'doc2', 'doc3'); + }); + + it('can use with nested composite filters', async () => { + const collection = await testCollectionWithDocs({ + doc1: {key: 'a', sort: 0, v: 5}, + doc2: {key: 'aa', sort: 4, v: 4}, + doc3: {key: 'c', sort: 3, v: 3}, + doc4: {key: 'b', sort: 2, v: 2}, + doc5: {key: 'b', sort: 2, v: 1}, + doc6: {key: 'b', sort: 0, v: 0}, }); - it('can use with nested composite filters', async () => { - const collection = await testCollectionWithDocs({ - doc1: {key: 'a', sort: 0, v: 5}, - doc2: {key: 'aa', sort: 4, v: 4}, - doc3: {key: 'c', sort: 3, v: 3}, - doc4: {key: 'b', sort: 2, v: 2}, - doc5: {key: 'b', sort: 2, v: 1}, - doc6: {key: 'b', sort: 0, v: 0}, - }); + // Implicitly ordered by: 'key' asc, 'sort' asc, 'v' asc, __name__ asc + let query = collection.where( + Filter.or( + Filter.and( + Filter.where('key', '==', 'b'), + Filter.where('sort', '<=', 2), + ), + Filter.and(Filter.where('key', '!=', 'b'), Filter.where('v', '>', 4)), + ), + ); + let docSnap = await collection.doc('doc1').get(); + let queryWithCursor = query.startAt(docSnap); + expectDocs( + await compareQueryAndPipeline(query), + 'doc1', + 'doc6', + 'doc5', + 'doc4', + ); + expectDocs(await queryWithCursor.get(), 'doc1', 'doc6', 'doc5', 'doc4'); - // Implicitly ordered by: 'key' asc, 'sort' asc, 'v' asc, __name__ asc - let query = collection.where( + // Ordered by: 'sort' desc, 'key' asc, 'v' asc, __name__ asc + query = collection + .where( Filter.or( Filter.and( Filter.where('key', '==', 'b'), @@ -2054,273 +2038,232 @@ import {IndexTestHelper} from './index_test_helper'; Filter.where('v', '>', 4), ), ), - ); - let docSnap = await collection.doc('doc1').get(); - let queryWithCursor = query.startAt(docSnap); - expectDocs( - await compareQueryAndPipeline(query), - 'doc1', - 'doc6', - 'doc5', - 'doc4', - ); - expectDocs(await queryWithCursor.get(), 'doc1', 'doc6', 'doc5', 'doc4'); + ) + .orderBy('sort', 'desc') + .orderBy('key'); + docSnap = await collection.doc('doc5').get(); + queryWithCursor = query.startAt(docSnap); + expectDocs( + await compareQueryAndPipeline(query), + 'doc5', + 'doc4', + 'doc1', + 'doc6', + ); + expectDocs(await queryWithCursor.get(), 'doc5', 'doc4', 'doc1', 'doc6'); - // Ordered by: 'sort' desc, 'key' asc, 'v' asc, __name__ asc - query = collection - .where( - Filter.or( - Filter.and( - Filter.where('key', '==', 'b'), - Filter.where('sort', '<=', 2), - ), - Filter.and( - Filter.where('key', '!=', 'b'), - Filter.where('v', '>', 4), - ), + // Implicitly ordered by: 'key' asc, 'sort' asc, 'v' asc, __name__ asc + query = collection.where( + Filter.and( + Filter.or( + Filter.and( + Filter.where('key', '==', 'b'), + Filter.where('sort', '<=', 4), ), - ) - .orderBy('sort', 'desc') - .orderBy('key'); - docSnap = await collection.doc('doc5').get(); - queryWithCursor = query.startAt(docSnap); - expectDocs( - await compareQueryAndPipeline(query), - 'doc5', - 'doc4', - 'doc1', - 'doc6', - ); - expectDocs(await queryWithCursor.get(), 'doc5', 'doc4', 'doc1', 'doc6'); - - // Implicitly ordered by: 'key' asc, 'sort' asc, 'v' asc, __name__ asc - query = collection.where( - Filter.and( - Filter.or( - Filter.and( - Filter.where('key', '==', 'b'), - Filter.where('sort', '<=', 4), - ), - Filter.and( - Filter.where('key', '!=', 'b'), - Filter.where('v', '>=', 4), - ), + Filter.and( + Filter.where('key', '!=', 'b'), + Filter.where('v', '>=', 4), ), - Filter.or( - Filter.and( - Filter.where('key', '>', 'b'), - Filter.where('sort', '>=', 1), - ), - Filter.and( - Filter.where('key', '<', 'b'), - Filter.where('v', '>', 0), - ), + ), + Filter.or( + Filter.and( + Filter.where('key', '>', 'b'), + Filter.where('sort', '>=', 1), + ), + Filter.and( + Filter.where('key', '<', 'b'), + Filter.where('v', '>', 0), ), ), - ); - docSnap = await collection.doc('doc1').get(); - queryWithCursor = query.startAt(docSnap); - expectDocs(await compareQueryAndPipeline(query), 'doc1', 'doc2'); - expectDocs(await queryWithCursor.get(), 'doc1', 'doc2'); - }); + ), + ); + docSnap = await collection.doc('doc1').get(); + queryWithCursor = query.startAt(docSnap); + expectDocs(await compareQueryAndPipeline(query), 'doc1', 'doc2'); + expectDocs(await queryWithCursor.get(), 'doc1', 'doc2'); + }); - it('inequality fields will be implicitly ordered lexicographically by the server', async () => { - const collection = await testCollectionWithDocs({ - doc1: {key: 'a', sort: 0, v: 5}, - doc2: {key: 'aa', sort: 4, v: 4}, - doc3: {key: 'b', sort: 3, v: 3}, - doc4: {key: 'b', sort: 2, v: 2}, - doc5: {key: 'b', sort: 2, v: 1}, - doc6: {key: 'b', sort: 0, v: 0}, - }); + it('inequality fields will be implicitly ordered lexicographically by the server', async () => { + const collection = await testCollectionWithDocs({ + doc1: {key: 'a', sort: 0, v: 5}, + doc2: {key: 'aa', sort: 4, v: 4}, + doc3: {key: 'b', sort: 3, v: 3}, + doc4: {key: 'b', sort: 2, v: 2}, + doc5: {key: 'b', sort: 2, v: 1}, + doc6: {key: 'b', sort: 0, v: 0}, + }); - const docSnap = await collection.doc('doc2').get(); + const docSnap = await collection.doc('doc2').get(); - // Implicitly ordered by: 'key' asc, 'sort' asc, __name__ asc - let query = collection - .where('key', '!=', 'a') - .where('sort', '>', 1) - .where('v', 'in', [1, 2, 3, 4]); - let queryWithCursor = query.startAt(docSnap); - expectDocs( - await compareQueryAndPipeline(query), - 'doc2', - 'doc4', - 'doc5', - 'doc3', - ); - expectDocs(await queryWithCursor.get(), 'doc2', 'doc4', 'doc5', 'doc3'); + // Implicitly ordered by: 'key' asc, 'sort' asc, __name__ asc + let query = collection + .where('key', '!=', 'a') + .where('sort', '>', 1) + .where('v', 'in', [1, 2, 3, 4]); + let queryWithCursor = query.startAt(docSnap); + expectDocs( + await compareQueryAndPipeline(query), + 'doc2', + 'doc4', + 'doc5', + 'doc3', + ); + expectDocs(await queryWithCursor.get(), 'doc2', 'doc4', 'doc5', 'doc3'); + + // Changing filters order will not effect implicit order. + // Implicitly ordered by: 'key' asc, 'sort' asc, __name__ asc + query = collection + .where('sort', '>', 1) + .where('key', '!=', 'a') + .where('v', 'in', [1, 2, 3, 4]); + queryWithCursor = query.startAt(docSnap); + expectDocs( + await compareQueryAndPipeline(query), + 'doc2', + 'doc4', + 'doc5', + 'doc3', + ); + expectDocs(await queryWithCursor.get(), 'doc2', 'doc4', 'doc5', 'doc3'); + }); - // Changing filters order will not effect implicit order. - // Implicitly ordered by: 'key' asc, 'sort' asc, __name__ asc - query = collection - .where('sort', '>', 1) - .where('key', '!=', 'a') - .where('v', 'in', [1, 2, 3, 4]); - queryWithCursor = query.startAt(docSnap); - expectDocs( - await compareQueryAndPipeline(query), - 'doc2', - 'doc4', - 'doc5', - 'doc3', - ); - expectDocs(await queryWithCursor.get(), 'doc2', 'doc4', 'doc5', 'doc3'); + it('can use multiple explicit order by field', async () => { + const collection = await testCollectionWithDocs({ + doc1: {key: 'a', sort: 5, v: 0}, + doc2: {key: 'aa', sort: 4, v: 0}, + doc3: {key: 'b', sort: 3, v: 1}, + doc4: {key: 'b', sort: 2, v: 1}, + doc5: {key: 'bb', sort: 1, v: 1}, + doc6: {key: 'c', sort: 0, v: 2}, }); - it('can use multiple explicit order by field', async () => { - const collection = await testCollectionWithDocs({ - doc1: {key: 'a', sort: 5, v: 0}, - doc2: {key: 'aa', sort: 4, v: 0}, - doc3: {key: 'b', sort: 3, v: 1}, - doc4: {key: 'b', sort: 2, v: 1}, - doc5: {key: 'bb', sort: 1, v: 1}, - doc6: {key: 'c', sort: 0, v: 2}, - }); - - let docSnap = await collection.doc('doc2').get(); - - // Ordered by: 'v' asc, 'key' asc, 'sort' asc, __name__ asc - let query = collection - .where('key', '>', 'a') - .where('sort', '>=', 1) - .orderBy('v'); - let queryWithCursor = query.startAt(docSnap); - expectDocs( - await compareQueryAndPipeline(query), - 'doc2', - 'doc4', - 'doc3', - 'doc5', - ); - expectDocs(await queryWithCursor.get(), 'doc2', 'doc4', 'doc3', 'doc5'); + let docSnap = await collection.doc('doc2').get(); - // Ordered by: 'v asc, 'sort' asc, 'key' asc, __name__ asc - query = collection - .where('key', '>', 'a') - .where('sort', '>=', 1) - .orderBy('v') - .orderBy('sort'); - queryWithCursor = query.startAt(docSnap); - expectDocs( - await compareQueryAndPipeline(query), - 'doc2', - 'doc5', - 'doc4', - 'doc3', - ); - expectDocs(await queryWithCursor.get(), 'doc2', 'doc5', 'doc4', 'doc3'); + // Ordered by: 'v' asc, 'key' asc, 'sort' asc, __name__ asc + let query = collection + .where('key', '>', 'a') + .where('sort', '>=', 1) + .orderBy('v'); + let queryWithCursor = query.startAt(docSnap); + expectDocs( + await compareQueryAndPipeline(query), + 'doc2', + 'doc4', + 'doc3', + 'doc5', + ); + expectDocs(await queryWithCursor.get(), 'doc2', 'doc4', 'doc3', 'doc5'); + + // Ordered by: 'v asc, 'sort' asc, 'key' asc, __name__ asc + query = collection + .where('key', '>', 'a') + .where('sort', '>=', 1) + .orderBy('v') + .orderBy('sort'); + queryWithCursor = query.startAt(docSnap); + expectDocs( + await compareQueryAndPipeline(query), + 'doc2', + 'doc5', + 'doc4', + 'doc3', + ); + expectDocs(await queryWithCursor.get(), 'doc2', 'doc5', 'doc4', 'doc3'); - docSnap = await collection.doc('doc5').get(); + docSnap = await collection.doc('doc5').get(); - // Implicit order by matches the direction of last explicit order by. - // Ordered by: 'v' desc, 'key' desc, 'sort' desc, __name__ desc - query = collection - .where('key', '>', 'a') - .where('sort', '>=', 1) - .orderBy('v', 'desc'); - queryWithCursor = query.startAt(docSnap); - expectDocs( - await compareQueryAndPipeline(query), - 'doc5', - 'doc3', - 'doc4', - 'doc2', - ); - expectDocs(await queryWithCursor.get(), 'doc5', 'doc3', 'doc4', 'doc2'); + // Implicit order by matches the direction of last explicit order by. + // Ordered by: 'v' desc, 'key' desc, 'sort' desc, __name__ desc + query = collection + .where('key', '>', 'a') + .where('sort', '>=', 1) + .orderBy('v', 'desc'); + queryWithCursor = query.startAt(docSnap); + expectDocs( + await compareQueryAndPipeline(query), + 'doc5', + 'doc3', + 'doc4', + 'doc2', + ); + expectDocs(await queryWithCursor.get(), 'doc5', 'doc3', 'doc4', 'doc2'); + + // Ordered by: 'v desc, 'sort' asc, 'key' asc, __name__ asc + query = collection + .where('key', '>', 'a') + .where('sort', '>=', 1) + .orderBy('v', 'desc') + .orderBy('sort'); + queryWithCursor = query.startAt(docSnap); + expectDocs( + await compareQueryAndPipeline(query), + 'doc5', + 'doc4', + 'doc3', + 'doc2', + ); + expectDocs(await queryWithCursor.get(), 'doc5', 'doc4', 'doc3', 'doc2'); + }); - // Ordered by: 'v desc, 'sort' asc, 'key' asc, __name__ asc - query = collection - .where('key', '>', 'a') - .where('sort', '>=', 1) - .orderBy('v', 'desc') - .orderBy('sort'); - queryWithCursor = query.startAt(docSnap); - expectDocs( - await compareQueryAndPipeline(query), - 'doc5', - 'doc4', - 'doc3', - 'doc2', - ); - expectDocs(await queryWithCursor.get(), 'doc5', 'doc4', 'doc3', 'doc2'); + it('can use in aggregate query', async () => { + const collection = await testCollectionWithDocs({ + doc1: {key: 'a', sort: 5, v: 0}, + doc2: {key: 'aa', sort: 4, v: 0}, + doc3: {key: 'b', sort: 3, v: 1}, + doc4: {key: 'b', sort: 2, v: 1}, + doc5: {key: 'bb', sort: 1, v: 1}, }); - it('can use in aggregate query', async () => { - const collection = await testCollectionWithDocs({ - doc1: {key: 'a', sort: 5, v: 0}, - doc2: {key: 'aa', sort: 4, v: 0}, - doc3: {key: 'b', sort: 3, v: 1}, - doc4: {key: 'b', sort: 2, v: 1}, - doc5: {key: 'bb', sort: 1, v: 1}, - }); + const results = await collection + .where('key', '>', 'a') + .where('sort', '>=', 1) + .orderBy('v') + .count() + .get(); + expect(results.data().count).to.be.equal(4); + //TODO(MIEQ): Add sum and average when they are public. + }); - const results = await collection - .where('key', '>', 'a') - .where('sort', '>=', 1) - .orderBy('v') - .count() - .get(); - expect(results.data().count).to.be.equal(4); - //TODO(MIEQ): Add sum and average when they are public. + it('can use document ID im multiple inequality query', async () => { + const collection = await testCollectionWithDocs({ + doc1: {key: 'a', sort: 5}, + doc2: {key: 'aa', sort: 4}, + doc3: {key: 'b', sort: 3}, + doc4: {key: 'b', sort: 2}, + doc5: {key: 'bb', sort: 1}, }); - it('can use document ID im multiple inequality query', async () => { - const collection = await testCollectionWithDocs({ - doc1: {key: 'a', sort: 5}, - doc2: {key: 'aa', sort: 4}, - doc3: {key: 'b', sort: 3}, - doc4: {key: 'b', sort: 2}, - doc5: {key: 'bb', sort: 1}, - }); - - const docSnap = await collection.doc('doc2').get(); - - // Document Key in inequality field will implicitly ordered to the last. - // Implicitly ordered by: 'key' asc, 'sort' asc, __name__ asc - let query = collection - .where('sort', '>=', 1) - .where('key', '!=', 'a') - .where(FieldPath.documentId(), '<', 'doc5'); - let queryWithCursor = query.startAt(docSnap); - expectDocs( - await compareQueryAndPipeline(query), - 'doc2', - 'doc4', - 'doc3', - ); - expectDocs(await queryWithCursor.get(), 'doc2', 'doc4', 'doc3'); - - // Changing filters order will not effect implicit order. - // Implicitly ordered by: 'key' asc, 'sort' asc, __name__ asc - query = collection - .where(FieldPath.documentId(), '<', 'doc5') - .where('sort', '>=', 1) - .where('key', '!=', 'a'); - queryWithCursor = query.startAt(docSnap); - expectDocs( - await compareQueryAndPipeline(query), - 'doc2', - 'doc4', - 'doc3', - ); - expectDocs(await queryWithCursor.get(), 'doc2', 'doc4', 'doc3'); - - // Ordered by: 'sort' desc,'key' desc, __name__ desc - query = collection - .where(FieldPath.documentId(), '<', 'doc5') - .where('sort', '>=', 1) - .where('key', '!=', 'a') - .orderBy('sort', 'desc'); - queryWithCursor = query.startAt(docSnap); - expectDocs( - await compareQueryAndPipeline(query), - 'doc2', - 'doc3', - 'doc4', - ); - expectDocs(await queryWithCursor.get(), 'doc2', 'doc3', 'doc4'); - }); + const docSnap = await collection.doc('doc2').get(); + + // Document Key in inequality field will implicitly ordered to the last. + // Implicitly ordered by: 'key' asc, 'sort' asc, __name__ asc + let query = collection + .where('sort', '>=', 1) + .where('key', '!=', 'a') + .where(FieldPath.documentId(), '<', 'doc5'); + let queryWithCursor = query.startAt(docSnap); + expectDocs(await compareQueryAndPipeline(query), 'doc2', 'doc4', 'doc3'); + expectDocs(await queryWithCursor.get(), 'doc2', 'doc4', 'doc3'); + + // Changing filters order will not effect implicit order. + // Implicitly ordered by: 'key' asc, 'sort' asc, __name__ asc + query = collection + .where(FieldPath.documentId(), '<', 'doc5') + .where('sort', '>=', 1) + .where('key', '!=', 'a'); + queryWithCursor = query.startAt(docSnap); + expectDocs(await compareQueryAndPipeline(query), 'doc2', 'doc4', 'doc3'); + expectDocs(await queryWithCursor.get(), 'doc2', 'doc4', 'doc3'); + + // Ordered by: 'sort' desc,'key' desc, __name__ desc + query = collection + .where(FieldPath.documentId(), '<', 'doc5') + .where('sort', '>=', 1) + .where('key', '!=', 'a') + .orderBy('sort', 'desc'); + queryWithCursor = query.startAt(docSnap); + expectDocs(await compareQueryAndPipeline(query), 'doc2', 'doc3', 'doc4'); + expectDocs(await queryWithCursor.get(), 'doc2', 'doc3', 'doc4'); }); - }, -); + }); +}); diff --git a/dev/system-test/tracing.ts b/dev/system-test/tracing.ts index 3b7a520bd..e5497c850 100644 --- a/dev/system-test/tracing.ts +++ b/dev/system-test/tracing.ts @@ -93,9 +93,11 @@ const REST_TEST_SUITE_TITLE = 'REST'; diag.setLogger(new DiagConsoleLogger(), DiagLogLevel.DEBUG); // Enable Firestore debug messages for local debugging. -setLogFunction((msg: string) => { - console.log(`LOG: ${msg}`); -}); +if (process.env.NODE_ENV === 'DEBUG') { + setLogFunction((msg: string) => { + console.log(`LOG: ${msg}`); + }); +} interface TestConfig { // In-Memory tests check trace correctness by inspecting traces in memory by @@ -869,7 +871,8 @@ describe('Tracing Tests', () => { ); }); - it('collection reference list documents', async () => { + // Enterprise: field mask is not supported + it.skipEnterprise('collection reference list documents', async () => { await runFirestoreOperationInRootSpan(() => firestore.collection('foo').listDocuments(), ); @@ -961,7 +964,8 @@ describe('Tracing Tests', () => { expectSpanHierarchy(SPAN_NAME_TEST_ROOT, SPAN_NAME_BATCH_COMMIT); }); - it('partition query', async () => { + // Service not implemented for Enterprise DB: PartitionQuery + it.skipEnterprise('partition query', async () => { await runFirestoreOperationInRootSpan(async () => { const query = firestore.collectionGroup('foo'); let numPartitions = 0; diff --git a/dev/test/util/helpers.ts b/dev/test/util/helpers.ts index fe1ed5199..b10c81c5d 100644 --- a/dev/test/util/helpers.ts +++ b/dev/test/util/helpers.ts @@ -468,9 +468,9 @@ export function isPreferRest(): boolean { ); } -export function itIf( - condition: boolean | 'only', -): Mocha.TestFunction | Mocha.PendingTestFunction { - // eslint-disable-next-line no-restricted-properties - return condition === 'only' ? it.only : condition ? it : it.skip; +/** + * Returns a value indicating whether the tests are running against an Enterprise edition DB + */ +export function isEnterprise(): boolean { + return !!process.env.RUN_ENTERPRISE_TESTS; } diff --git a/dev/test/util/mocha_extensions.ts b/dev/test/util/mocha_extensions.ts new file mode 100644 index 000000000..33e653231 --- /dev/null +++ b/dev/test/util/mocha_extensions.ts @@ -0,0 +1,88 @@ +/** + * @license + * Copyright 2025 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-disable no-restricted-properties */ + +import {describe, it} from 'mocha'; + +// Helper to make a type itselt (T) and optionally union that with (T['skip']) +type tOrSkipT = T | (T extends {skip: unknown} ? T['skip'] : T); + +interface ExtendMochaTypeWithHelpers { + // Declare helpers + skipEnterprise: tOrSkipT; + skipEmulator: tOrSkipT; + skipClassic: tOrSkipT; +} + +declare module 'mocha' { + type TestFunction = ExtendMochaTypeWithHelpers; + type PendingTestFunction = ExtendMochaTypeWithHelpers; + type SuiteFunction = ExtendMochaTypeWithHelpers; + type PendingSuiteFunction = ExtendMochaTypeWithHelpers; +} + +// Define helpers +export function mixinSkipImplementations(obj: unknown): void { + Object.defineProperty(obj, 'skipEnterprise', { + get(): unknown { + if (this === it.skip) { + return this; + } + if (this === describe.skip) { + return this; + } + if (process.env.RUN_ENTERPRISE_TESTS) { + return this.skip; + } + return this; + }, + }); + + Object.defineProperty(obj, 'skipEmulator', { + get(): unknown { + if (this === it.skip) { + return this; + } + if (this === describe.skip) { + return this; + } + if (process.env.FIRESTORE_EMULATOR_HOST) { + return this.skip; + } + return this; + }, + }); + + Object.defineProperty(obj, 'skipClassic', { + get(): unknown { + if (this === it.skip) { + return this; + } + if (this === describe.skip) { + return this; + } + if (!process.env.RUN_ENTERPRISE_TESTS) { + return this.skip; + } + return this; + }, + }); +} + +// TODO add mocha functions that must be extended +[it, it.skip, describe, describe.skip].forEach(mixinSkipImplementations); From c23f53d5077b8557a3355e8ba019fc48a61bac2f Mon Sep 17 00:00:00 2001 From: Mark Duckworth <1124037+MarkDuckworth@users.noreply.github.com> Date: Tue, 16 Dec 2025 17:53:16 -0700 Subject: [PATCH 57/60] fix mocha_extensions --- dev/test/util/mocha_extensions.ts | 39 +++++++++++++++++++++---------- 1 file changed, 27 insertions(+), 12 deletions(-) diff --git a/dev/test/util/mocha_extensions.ts b/dev/test/util/mocha_extensions.ts index 33e653231..15532ba95 100644 --- a/dev/test/util/mocha_extensions.ts +++ b/dev/test/util/mocha_extensions.ts @@ -22,18 +22,31 @@ import {describe, it} from 'mocha'; // Helper to make a type itselt (T) and optionally union that with (T['skip']) type tOrSkipT = T | (T extends {skip: unknown} ? T['skip'] : T); -interface ExtendMochaTypeWithHelpers { - // Declare helpers - skipEnterprise: tOrSkipT; - skipEmulator: tOrSkipT; - skipClassic: tOrSkipT; -} - declare module 'mocha' { - type TestFunction = ExtendMochaTypeWithHelpers; - type PendingTestFunction = ExtendMochaTypeWithHelpers; - type SuiteFunction = ExtendMochaTypeWithHelpers; - type PendingSuiteFunction = ExtendMochaTypeWithHelpers; + // eslint-disable-next-line @typescript-eslint/no-namespace + interface TestFunction { + skipEnterprise: tOrSkipT; + skipEmulator: tOrSkipT; + skipClassic: tOrSkipT; + } + + interface PendingTestFunction { + skipEnterprise: tOrSkipT; + skipEmulator: tOrSkipT; + skipClassic: tOrSkipT; + } + + interface SuiteFunction { + skipEnterprise: tOrSkipT; + skipEmulator: tOrSkipT; + skipClassic: tOrSkipT; + } + + interface PendingSuiteFunction { + skipEnterprise: tOrSkipT; + skipEmulator: tOrSkipT; + skipClassic: tOrSkipT; + } } // Define helpers @@ -85,4 +98,6 @@ export function mixinSkipImplementations(obj: unknown): void { } // TODO add mocha functions that must be extended -[it, it.skip, describe, describe.skip].forEach(mixinSkipImplementations); +[global.it, global.describe, it, it.skip, describe, describe.skip].forEach( + mixinSkipImplementations, +); From 24de65e1545bad885d83cd58a880c3a013675f0d Mon Sep 17 00:00:00 2001 From: Mark Duckworth <1124037+MarkDuckworth@users.noreply.github.com> Date: Thu, 18 Dec 2025 13:34:13 -0700 Subject: [PATCH 58/60] Improve TODO message on listCollections test --- dev/system-test/firestore.ts | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/dev/system-test/firestore.ts b/dev/system-test/firestore.ts index 7571316c7..6a6e7e190 100644 --- a/dev/system-test/firestore.ts +++ b/dev/system-test/firestore.ts @@ -1226,7 +1226,9 @@ describe('DocumentReference class', () => { }); }); - // TODO enterprise waiting on server fix + // TODO this test times out in the RPC because there is no index in the backend + // to support the query. The latency scales with the total number of collection + // groups in the database, regardless of which collection / parent is being listed. it.skipEnterprise('has listCollections() method', () => { const collections: string[] = []; const promises: Array> = []; From 3be33ea4932a2d736795fa5fca1eeb05c0f68431 Mon Sep 17 00:00:00 2001 From: Mark Duckworth <1124037+MarkDuckworth@users.noreply.github.com> Date: Mon, 29 Dec 2025 16:56:43 -0700 Subject: [PATCH 59/60] Port BooleanExpression subclasses from Web --- dev/src/pipelines/expression.ts | 250 +++++++++++++++++++++++++------- dev/system-test/pipeline.ts | 17 +-- types/firestore.d.ts | 131 ++++++++++++++--- 3 files changed, 317 insertions(+), 81 deletions(-) diff --git a/dev/src/pipelines/expression.ts b/dev/src/pipelines/expression.ts index 89066a155..e095cdd5d 100644 --- a/dev/src/pipelines/expression.ts +++ b/dev/src/pipelines/expression.ts @@ -97,6 +97,28 @@ export abstract class Expression ]); } + /** + * @beta + * Wraps the expression in a [BooleanExpression]. + * + * @return A [BooleanExpression] representing the same expression. + */ + asBoolean(): BooleanExpression { + if (this instanceof BooleanExpression) { + return this; + } else if (this instanceof Constant) { + return new BooleanConstant(this); + } else if (this instanceof Field) { + return new BooleanField(this); + } else if (this instanceof FunctionExpression) { + return new BooleanFunctionExpression(this); + } else { + throw new Error( + `Conversion of type ${typeof this} to BooleanExpression not supported.`, + ); + } + } + /** * @beta * Creates an expression that subtracts another expression from this expression. @@ -250,7 +272,10 @@ export abstract class Expression */ equal(value: unknown): BooleanExpression; equal(other: unknown): BooleanExpression { - return new BooleanExpression('equal', [this, valueToDefaultExpr(other)]); + return new FunctionExpression('equal', [ + this, + valueToDefaultExpr(other), + ]).asBoolean(); } /** @@ -281,10 +306,10 @@ export abstract class Expression */ notEqual(value: unknown): BooleanExpression; notEqual(other: unknown): BooleanExpression { - return new BooleanExpression('not_equal', [ + return new FunctionExpression('not_equal', [ this, valueToDefaultExpr(other), - ]); + ]).asBoolean(); } /** @@ -315,10 +340,10 @@ export abstract class Expression */ lessThan(value: unknown): BooleanExpression; lessThan(other: unknown): BooleanExpression { - return new BooleanExpression('less_than', [ + return new FunctionExpression('less_than', [ this, valueToDefaultExpr(other), - ]); + ]).asBoolean(); } /** @@ -350,10 +375,10 @@ export abstract class Expression */ lessThanOrEqual(value: unknown): BooleanExpression; lessThanOrEqual(other: unknown): BooleanExpression { - return new BooleanExpression('less_than_or_equal', [ + return new FunctionExpression('less_than_or_equal', [ this, valueToDefaultExpr(other), - ]); + ]).asBoolean(); } /** @@ -384,10 +409,10 @@ export abstract class Expression */ greaterThan(value: unknown): BooleanExpression; greaterThan(other: unknown): BooleanExpression { - return new BooleanExpression('greater_than', [ + return new FunctionExpression('greater_than', [ this, valueToDefaultExpr(other), - ]); + ]).asBoolean(); } /** @@ -420,10 +445,10 @@ export abstract class Expression */ greaterThanOrEqual(value: unknown): BooleanExpression; greaterThanOrEqual(other: unknown): BooleanExpression { - return new BooleanExpression('greater_than_or_equal', [ + return new FunctionExpression('greater_than_or_equal', [ this, valueToDefaultExpr(other), - ]); + ]).asBoolean(); } /** @@ -475,10 +500,10 @@ export abstract class Expression */ arrayContains(value: unknown): BooleanExpression; arrayContains(element: unknown): BooleanExpression { - return new BooleanExpression('array_contains', [ + return new FunctionExpression('array_contains', [ this, valueToDefaultExpr(element), - ]); + ]).asBoolean(); } /** @@ -512,7 +537,10 @@ export abstract class Expression const normalizedExpr = Array.isArray(values) ? new ListOfExprs(values.map(valueToDefaultExpr)) : cast(values); - return new BooleanExpression('array_contains_all', [this, normalizedExpr]); + return new FunctionExpression('array_contains_all', [ + this, + normalizedExpr, + ]).asBoolean(); } /** @@ -549,7 +577,10 @@ export abstract class Expression const normalizedExpr = Array.isArray(values) ? new ListOfExprs(values.map(valueToDefaultExpr)) : cast(values); - return new BooleanExpression('array_contains_any', [this, normalizedExpr]); + return new FunctionExpression('array_contains_any', [ + this, + normalizedExpr, + ]).asBoolean(); } /** @@ -615,7 +646,7 @@ export abstract class Expression const exprOthers = Array.isArray(others) ? new ListOfExprs(others.map(valueToDefaultExpr)) : cast(others); - return new BooleanExpression('equal_any', [this, exprOthers]); + return new FunctionExpression('equal_any', [this, exprOthers]).asBoolean(); } /** @@ -650,7 +681,10 @@ export abstract class Expression const exprOthers = Array.isArray(others) ? new ListOfExprs(others.map(valueToDefaultExpr)) : cast(others); - return new BooleanExpression('not_equal_any', [this, exprOthers]); + return new FunctionExpression('not_equal_any', [ + this, + exprOthers, + ]).asBoolean(); } /** @@ -665,7 +699,7 @@ export abstract class Expression * @return A new `Expression` representing the 'exists' check. */ exists(): BooleanExpression { - return new BooleanExpression('exists', [this]); + return new FunctionExpression('exists', [this]).asBoolean(); } /** @@ -695,7 +729,7 @@ export abstract class Expression * @param pattern The pattern to search for. You can use "%" as a wildcard character. * @return A new `Expression` representing the 'like' comparison. */ - like(pattern: string): FunctionExpression; + like(pattern: string): BooleanExpression; /** * @beta @@ -709,12 +743,12 @@ export abstract class Expression * @param pattern The pattern to search for. You can use "%" as a wildcard character. * @return A new `Expression` representing the 'like' comparison. */ - like(pattern: Expression): FunctionExpression; - like(stringOrExpr: string | Expression): FunctionExpression { - return new BooleanExpression('like', [ + like(pattern: Expression): BooleanExpression; + like(stringOrExpr: string | Expression): BooleanExpression { + return new FunctionExpression('like', [ this, valueToDefaultExpr(stringOrExpr), - ]); + ]).asBoolean(); } /** @@ -747,10 +781,10 @@ export abstract class Expression */ regexContains(pattern: Expression): BooleanExpression; regexContains(stringOrExpr: string | Expression): BooleanExpression { - return new BooleanExpression('regex_contains', [ + return new FunctionExpression('regex_contains', [ this, valueToDefaultExpr(stringOrExpr), - ]); + ]).asBoolean(); } /** @@ -781,10 +815,10 @@ export abstract class Expression */ regexMatch(pattern: Expression): BooleanExpression; regexMatch(stringOrExpr: string | Expression): BooleanExpression { - return new BooleanExpression('regex_match', [ + return new FunctionExpression('regex_match', [ this, valueToDefaultExpr(stringOrExpr), - ]); + ]).asBoolean(); } /** @@ -815,10 +849,10 @@ export abstract class Expression */ stringContains(expr: Expression): BooleanExpression; stringContains(stringOrExpr: string | Expression): BooleanExpression { - return new BooleanExpression('string_contains', [ + return new FunctionExpression('string_contains', [ this, valueToDefaultExpr(stringOrExpr), - ]); + ]).asBoolean(); } /** @@ -850,10 +884,10 @@ export abstract class Expression */ startsWith(prefix: Expression): BooleanExpression; startsWith(stringOrExpr: string | Expression): BooleanExpression { - return new BooleanExpression('starts_with', [ + return new FunctionExpression('starts_with', [ this, valueToDefaultExpr(stringOrExpr), - ]); + ]).asBoolean(); } /** @@ -885,10 +919,10 @@ export abstract class Expression */ endsWith(suffix: Expression): BooleanExpression; endsWith(stringOrExpr: string | Expression): BooleanExpression { - return new BooleanExpression('ends_with', [ + return new FunctionExpression('ends_with', [ this, valueToDefaultExpr(stringOrExpr), - ]); + ]).asBoolean(); } /** @@ -1651,7 +1685,7 @@ export abstract class Expression * @return A new {@code BooleanExpression} representing the 'isError' check. */ isError(): BooleanExpression { - return new BooleanExpression('is_error', [this]); + return new FunctionExpression('is_error', [this]).asBoolean(); } /** @@ -1707,7 +1741,7 @@ export abstract class Expression * @return A new {@code BooleanExpression} representing the 'isAbsent' check. */ isAbsent(): BooleanExpression { - return new BooleanExpression('is_absent', [this]); + return new FunctionExpression('is_absent', [this]).asBoolean(); } /** @@ -2642,7 +2676,16 @@ export function constant(value: firestore.VectorValue): Expression; export function constant(value: unknown): Expression; export function constant(value: unknown): Expression { - return new Constant(value); + return _constant(value); +} + +export function _constant(value: unknown): Constant | BooleanExpression { + const c = new Constant(value); + if (typeof value === 'boolean') { + return new BooleanConstant(c); + } else { + return c; + } } /** @@ -2686,7 +2729,7 @@ export class FunctionExpression extends Expression { readonly expressionType: firestore.Pipelines.ExpressionType = 'Function'; constructor( - protected name: string, + public _methodName: string, private params: Expression[], ) { super(); @@ -2700,7 +2743,7 @@ export class FunctionExpression extends Expression { _toProto(serializer: Serializer): api.IValue { return { functionValue: { - name: this.name, + name: this._methodName, args: this.params.map(p => cast(p)._toProto(serializer)), }, }; @@ -2750,7 +2793,7 @@ class MapFunctionExpr extends FunctionExpression { } return { functionValue: { - name: this.name, + name: this._methodName, args: args, }, }; @@ -2793,7 +2836,7 @@ class ArrayFunctionExpr extends FunctionExpression { _toProto(serializer: Serializer): api.IValue { return { functionValue: { - name: this.name, + name: this._methodName, args: this.values .filter(v => !!v) .map(value => value!._toProto(serializer)), @@ -2822,11 +2865,11 @@ class ArrayFunctionExpr extends FunctionExpression { * This expression type is useful for filter conditions. * */ -export class BooleanExpression - extends FunctionExpression +export abstract class BooleanExpression + extends Expression implements firestore.Pipelines.BooleanExpression { - returnType: 'boolean' = 'boolean' as const; + abstract get _expr(): Expression; /** * @beta @@ -2856,7 +2899,7 @@ export class BooleanExpression * @return A new {@code Expression} representing the negated filter condition. */ not(): BooleanExpression { - return new BooleanExpression('not', [this]); + return new FunctionExpression('not', [this]).asBoolean(); } /** @@ -2894,8 +2937,98 @@ export class BooleanExpression * produces an error. * @return A new {@code Expr} representing the 'ifError' operation. */ - ifError(catchValue: BooleanExpression): BooleanExpression { - return new BooleanExpression('if_error', [this, catchValue]); + ifError(catchValue: BooleanExpression): BooleanExpression; + + /** + * @beta + * + * Creates an expression that returns the `catch` argument if there is an + * error, else return the result of this expression. + * + * ```typescript + * // Create an expression that protects against a divide by zero error + * // but always returns a boolean expression. + * constant(50).divide('length').gt(1).ifError(false); + * ``` + * + * @param catchValue The value that will be returned if this expression + * produces an error. + * @return A new {@code Expr} representing the 'ifError' operation. + */ + ifError(catchValue: boolean): BooleanExpression; + + /** + * @beta + * + * Creates an expression that returns the `catch` argument if there is an + * error, else return the result of this expression. + * + * ```typescript + * // Create an expression that protects against a divide by zero error. + * constant(50).divide('length').gt(1).ifError(constant(0)); + * ``` + * + * @param catchValue The value that will be returned if this expression + * produces an error. + * @return A new {@code Expr} representing the 'ifError' operation. + */ + ifError(catchValue: Expression): FunctionExpression; + + /** + * @beta + * + * Creates an expression that returns the `catch` argument if there is an + * error, else return the result of this expression. + * + * ```typescript + * // Create an expression that protects against a divide by zero error. + * constant(50).divide('length').gt(1).ifError(0); + * ``` + * + * @param catchValue The value that will be returned if this expression + * produces an error. + * @return A new {@code Expr} representing the 'ifError' operation. + */ + ifError(catchValue: unknown): FunctionExpression; + ifError(catchValue: unknown): unknown { + const normalizedCatchValue = valueToDefaultExpr(catchValue); + const expr = new FunctionExpression('if_error', [ + this, + normalizedCatchValue, + ]); + + return normalizedCatchValue instanceof BooleanExpression + ? expr.asBoolean() + : expr; + } + + _toProto(serializer: Serializer): api.IValue { + return this._expr._toProto(serializer); + } + + _validateUserData(ignoreUndefinedProperties: boolean): void { + this._expr._validateUserData(ignoreUndefinedProperties); + } +} + +export class BooleanFunctionExpression extends BooleanExpression { + readonly expressionType: firestore.Pipelines.ExpressionType = 'Function'; + constructor(readonly _expr: FunctionExpression) { + super(); + } +} + +export class BooleanConstant extends BooleanExpression { + readonly expressionType: firestore.Pipelines.ExpressionType = 'Constant'; + constructor(readonly _expr: Constant) { + super(); + } +} + +export class BooleanField extends BooleanExpression { + readonly expressionType: firestore.Pipelines.ExpressionType = 'Field'; + constructor(readonly _expr: Field) { + super(); } } @@ -3044,6 +3177,7 @@ export function ifError( /** * @beta + * * Creates an expression that returns the `catch` argument if there is an * error, else return the result of the `try` argument evaluation. * @@ -3065,6 +3199,7 @@ export function ifError( /** * @beta + * * Creates an expression that returns the `catch` argument if there is an * error, else return the result of the `try` argument evaluation. * @@ -3083,15 +3218,16 @@ export function ifError( tryExpr: Expression, catchValue: unknown, ): FunctionExpression; + export function ifError( tryExpr: Expression, catchValue: unknown, -): FunctionExpression { +): FunctionExpression | BooleanExpression { if ( tryExpr instanceof BooleanExpression && catchValue instanceof BooleanExpression ) { - return tryExpr.ifError(catchValue); + return tryExpr.ifError(catchValue).asBoolean(); } else { return tryExpr.ifError(valueToDefaultExpr(catchValue)); } @@ -4279,7 +4415,7 @@ export function arrayConcat( export function arrayContains( array: Expression, element: Expression, -): FunctionExpression; +): BooleanExpression; /** * @beta @@ -4297,7 +4433,7 @@ export function arrayContains( export function arrayContains( array: Expression, element: unknown, -): FunctionExpression; +): BooleanExpression; /** * @beta @@ -4315,7 +4451,7 @@ export function arrayContains( export function arrayContains( fieldName: string, element: Expression, -): FunctionExpression; +): BooleanExpression; /** * @beta @@ -4740,7 +4876,11 @@ export function xor( second: BooleanExpression, ...additionalConditions: BooleanExpression[] ): BooleanExpression { - return new BooleanExpression('xor', [first, second, ...additionalConditions]); + return new FunctionExpression('xor', [ + first, + second, + ...additionalConditions, + ]).asBoolean(); } /** @@ -5220,7 +5360,7 @@ export function like( export function like( left: Expression | string, pattern: Expression | string, -): FunctionExpression { +): BooleanExpression { const leftExpr = fieldOrExpression(left); const patternExpr = valueToDefaultExpr(pattern); return leftExpr.like(patternExpr); @@ -6678,7 +6818,7 @@ export function and( second: BooleanExpression, ...more: BooleanExpression[] ): BooleanExpression { - return new BooleanExpression('and', [first, second, ...more]); + return new FunctionExpression('and', [first, second, ...more]).asBoolean(); } /** @@ -6701,7 +6841,7 @@ export function or( second: BooleanExpression, ...more: BooleanExpression[] ): BooleanExpression { - return new BooleanExpression('or', [first, second, ...more]); + return new FunctionExpression('or', [first, second, ...more]).asBoolean(); } /** diff --git a/dev/system-test/pipeline.ts b/dev/system-test/pipeline.ts index 7fc052add..0a9cb6179 100644 --- a/dev/system-test/pipeline.ts +++ b/dev/system-test/pipeline.ts @@ -19,7 +19,6 @@ import { } from '@google-cloud/firestore'; import { - BooleanExpression, map, array, field, @@ -1038,8 +1037,8 @@ const timestampDeltaMS = 3000; }); it('rejects groups without accumulators', async () => { - void expect( - firestore + void expect(async () => { + await firestore .pipeline() .collection(randomCol.path) .where(lessThan('published', 1900)) @@ -1047,8 +1046,8 @@ const timestampDeltaMS = 3000; accumulators: [], groups: ['genre'], }) - .execute(), - ).to.be.rejected; + .execute(); + }).to.throw; }); it('returns group and accumulate results', async () => { @@ -2944,11 +2943,11 @@ const timestampDeltaMS = 3000; .pipeline() .collection(randomCol.path) .where( - new BooleanExpression('and', [ + new FunctionExpression('and', [ field('rating').greaterThan(0), field('title').charLength().lessThan(5), field('tags').arrayContains('propaganda'), - ]), + ]).asBoolean(), ) .select('title') .execute(); @@ -2962,10 +2961,10 @@ const timestampDeltaMS = 3000; .pipeline() .collection(randomCol.path) .where( - new BooleanExpression('array_contains_any', [ + new FunctionExpression('array_contains_any', [ field('tags'), array(['politics']), - ]), + ]).asBoolean(), ) .select('title') .execute(); diff --git a/types/firestore.d.ts b/types/firestore.d.ts index acc44a2ee..512e91f15 100644 --- a/types/firestore.d.ts +++ b/types/firestore.d.ts @@ -3225,6 +3225,13 @@ declare namespace FirebaseFirestore { second: Expression | unknown, ...others: Array ): FunctionExpression; + /** + * @beta + * Wraps the expression in a [BooleanExpression]. + * + * @return A [BooleanExpression] representing the same expression. + */ + asBoolean(): BooleanExpression; /** * @beta * Creates an expression that subtracts another expression from this expression. @@ -3688,9 +3695,9 @@ declare namespace FirebaseFirestore { * ``` * * @param pattern The string pattern to search for. You can use "%" as a wildcard character within the pattern. - * @return A new {@link FunctionExpression} representing the 'like' comparison. + * @return A new {@link BooleanExpression} representing the 'like' comparison. */ - like(pattern: string): FunctionExpression; + like(pattern: string): BooleanExpression; /** * @beta @@ -3702,9 +3709,9 @@ declare namespace FirebaseFirestore { * ``` * * @param pattern An {@link Expression} that evaluates to the string pattern to search for. You can use "%" as a wildcard character within the pattern. - * @return A new {@link FunctionExpression} representing the 'like' comparison. + * @return A new {@link BooleanExpression} representing the 'like' comparison. */ - like(pattern: Expression): FunctionExpression; + like(pattern: Expression): BooleanExpression; /** * @beta * Creates an expression that checks if a string contains a specified regular expression as a @@ -3716,7 +3723,7 @@ declare namespace FirebaseFirestore { * ``` * * @param pattern The regular expression to use for the search. - * @return A new `Expression` representing the 'contains' comparison. + * @return A new `BooleanExpression` representing the 'contains' comparison. */ regexContains(pattern: string): BooleanExpression; @@ -5245,13 +5252,7 @@ declare namespace FirebaseFirestore { * This expression type is useful for filter conditions. * */ - export class BooleanExpression extends FunctionExpression { - /** - * @beta - * @internal - * @private - */ - returnType: 'boolean'; + export abstract class BooleanExpression extends Expression { /** * @beta * Creates an aggregation that finds the count of input documents satisfying @@ -5265,6 +5266,7 @@ declare namespace FirebaseFirestore { * @return A new `AggregateFunction` representing the 'countIf' aggregation. */ countIf(): AggregateFunction; + /** * @beta * Creates an expression that negates this boolean expression. @@ -5277,6 +5279,96 @@ declare namespace FirebaseFirestore { * @return A new {@code Expression} representing the negated filter condition. */ not(): BooleanExpression; + + /** + * @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`. + * + * ```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. + * @return A new {@code Expr} representing the conditional expression. + */ + conditional( + thenExpr: Expression, + elseExpr: Expression, + ): FunctionExpression; + + /** + * @beta + * + * Creates an expression that returns the `catch` argument if there is an + * error, else return the result of this expression. + * + * ```typescript + * // Create an expression that protects against a divide by zero error + * // but always returns a boolean expression. + * constant(50).divide('length').gt(1).ifError(constant(false)); + * ``` + * + * @param catchValue The value that will be returned if this expression + * produces an error. + * @return A new {@code Expr} representing the 'ifError' operation. + */ + ifError(catchValue: BooleanExpression): BooleanExpression; + + /** + * @beta + * + * Creates an expression that returns the `catch` argument if there is an + * error, else return the result of this expression. + * + * ```typescript + * // Create an expression that protects against a divide by zero error + * // but always returns a boolean expression. + * constant(50).divide('length').gt(1).ifError(false); + * ``` + * + * @param catchValue The value that will be returned if this expression + * produces an error. + * @return A new {@code Expr} representing the 'ifError' operation. + */ + ifError(catchValue: boolean): BooleanExpression; + + /** + * @beta + * + * Creates an expression that returns the `catch` argument if there is an + * error, else return the result of this expression. + * + * ```typescript + * // Create an expression that protects against a divide by zero error. + * constant(50).divide('length').gt(1).ifError(constant(0)); + * ``` + * + * @param catchValue The value that will be returned if this expression + * produces an error. + * @return A new {@code Expr} representing the 'ifError' operation. + */ + ifError(catchValue: Expression): FunctionExpression; + + /** + * @beta + * + * Creates an expression that returns the `catch` argument if there is an + * error, else return the result of this expression. + * + * ```typescript + * // Create an expression that protects against a divide by zero error. + * constant(50).divide('length').gt(1).ifError(0); + * ``` + * + * @param catchValue The value that will be returned if this expression + * produces an error. + * @return A new {@code Expr} representing the 'ifError' operation. + */ + ifError(catchValue: unknown): FunctionExpression; } /** * @beta @@ -5380,7 +5472,7 @@ declare namespace FirebaseFirestore { * ``` * * @param value The expression to check. - * @return A new {@code Expression} representing the 'isError' check. + * @return A new {@code BooleanExpression} representing the 'isError' check. */ export function isError(value: Expression): BooleanExpression; /** @@ -5400,14 +5492,16 @@ declare namespace FirebaseFirestore { * @param tryExpr The try expression. * @param catchExpr The catch expression that will be evaluated and * returned if the tryExpr produces an error. - * @return A new {@code Expr} representing the 'ifError' operation. + * @return A new {@code BooleanExpression} representing the 'ifError' operation. */ export function ifError( tryExpr: BooleanExpression, catchExpr: BooleanExpression, ): BooleanExpression; + /** * @beta + * * Creates an expression that returns the `catch` argument if there is an * error, else return the result of the `try` argument evaluation. * @@ -5426,8 +5520,10 @@ declare namespace FirebaseFirestore { tryExpr: Expression, catchExpr: Expression, ): FunctionExpression; + /** * @beta + * * Creates an expression that returns the `catch` argument if there is an * error, else return the result of the `try` argument evaluation. * @@ -5446,6 +5542,7 @@ declare namespace FirebaseFirestore { tryExpr: Expression, catchValue: unknown, ): FunctionExpression; + /** * @beta * Creates an expression that returns `true` if a value is absent. Otherwise, @@ -6502,7 +6599,7 @@ declare namespace FirebaseFirestore { export function arrayContains( array: Expression, element: Expression, - ): FunctionExpression; + ): BooleanExpression; /** * @beta * Creates an expression that checks if an array expression contains a specific element. @@ -6519,7 +6616,7 @@ declare namespace FirebaseFirestore { export function arrayContains( array: Expression, element: unknown, - ): FunctionExpression; + ): BooleanExpression; /** * @beta * Creates an expression that checks if a field's array value contains a specific element. @@ -6536,7 +6633,7 @@ declare namespace FirebaseFirestore { export function arrayContains( fieldName: string, element: Expression, - ): FunctionExpression; + ): BooleanExpression; /** * @beta * Creates an expression that checks if a field's array value contains a specific value. From 4f4abbeab7bf787044bc4c552f9551b107680a6d Mon Sep 17 00:00:00 2001 From: Mark Duckworth <1124037+MarkDuckworth@users.noreply.github.com> Date: Tue, 30 Dec 2025 15:43:05 -0700 Subject: [PATCH 60/60] Fixing failing CI tests: includes fixes for query to pipeline conversion --- dev/src/pipelines/pipeline-util.ts | 5 +- dev/src/reference/query.ts | 50 +- dev/system-test/firestore.ts | 513 +- dev/system-test/pipeline.ts | 8939 ++++++++++++++-------------- dev/system-test/query.ts | 468 +- dev/system-test/tracing.ts | 2 +- 6 files changed, 4909 insertions(+), 5068 deletions(-) diff --git a/dev/src/pipelines/pipeline-util.ts b/dev/src/pipelines/pipeline-util.ts index c316afe05..f49cbcb32 100644 --- a/dev/src/pipelines/pipeline-util.ts +++ b/dev/src/pipelines/pipeline-util.ts @@ -527,7 +527,10 @@ export function toPipelineBooleanExpr( } case 'NOT_IN': { const values = value?.arrayValue?.values?.map(val => constant(val)); - return and(field.exists(), field.notEqualAny(values!)); + // In Enterprise DB's NOT_IN will match a field that does not exist, + // therefore we do not want an existence filter for the NOT_IN conversion + // so the Query and Pipeline behavior are consistent in Enterprise. + return field.notEqualAny(values!); } } } else if (f instanceof CompositeFilterInternal) { diff --git a/dev/src/reference/query.ts b/dev/src/reference/query.ts index 04f0a4311..3f2f84238 100644 --- a/dev/src/reference/query.ts +++ b/dev/src/reference/query.ts @@ -773,9 +773,14 @@ export class Query< } // orders - const existsConditions = this.createImplicitOrderBy().map(fieldOrder => { - return field(fieldOrder.field).exists(); - }); + // Ignore inequality fields when creating implicit order-bys + // for generating existsConditions, because existence filters + // will have already been added in the call to `toPipelineBooleanExpr` + const existsConditions = this.createImplicitOrderBy(true).map( + fieldOrder => { + return field(fieldOrder.field).exists(); + }, + ); if (existsConditions.length > 1) { const [first, second, ...rest] = existsConditions; pipeline = pipeline.where(and(first, second, ...rest)); @@ -858,6 +863,11 @@ export class Query< } } + // offset + if (this._queryOptions.offset) { + pipeline = pipeline.offset(this._queryOptions.offset); + } + return pipeline; } @@ -921,7 +931,7 @@ export class Query< return this.createImplicitOrderBy(); } - private createImplicitOrderBy(): FieldOrder[] { + private createImplicitOrderBy(ignoreInequalityFields = false): FieldOrder[] { const fieldOrders = this._queryOptions.fieldOrders.slice(); const fieldsNormalized = new Set([ ...fieldOrders.map(item => item.field.toString()), @@ -933,21 +943,23 @@ export class Query< ? directionOperators.ASC : fieldOrders[fieldOrders.length - 1].direction; - /** - * Any inequality fields not explicitly ordered should be implicitly ordered in a - * lexicographical order. When there are multiple inequality filters on the same field, the - * field should be added only once. - * Note: getInequalityFilterFields function sorts the key field before - * other fields. However, we want the key field to be sorted last. - */ - const inequalityFields = this.getInequalityFilterFields(); - for (const field of inequalityFields) { - if ( - !fieldsNormalized.has(field.toString()) && - !field.isEqual(FieldPath.documentId()) - ) { - fieldOrders.push(new FieldOrder(field, lastDirection)); - fieldsNormalized.add(field.toString()); + if (!ignoreInequalityFields) { + /** + * Any inequality fields not explicitly ordered should be implicitly ordered in a + * lexicographical order. When there are multiple inequality filters on the same field, the + * field should be added only once. + * Note: getInequalityFilterFields function sorts the key field before + * other fields. However, we want the key field to be sorted last. + */ + const inequalityFields = this.getInequalityFilterFields(); + for (const field of inequalityFields) { + if ( + !fieldsNormalized.has(field.toString()) && + !field.isEqual(FieldPath.documentId()) + ) { + fieldOrders.push(new FieldOrder(field, lastDirection)); + fieldsNormalized.add(field.toString()); + } } } diff --git a/dev/system-test/firestore.ts b/dev/system-test/firestore.ts index 6a6e7e190..2ceca9626 100644 --- a/dev/system-test/firestore.ts +++ b/dev/system-test/firestore.ts @@ -1873,7 +1873,7 @@ describe('runs query on a large collection', () => { }); }); -describe('Query class', () => { +describe.skipEnterprise('Query class - Standard DB', () => { interface PaginatedResults { pages: number; docs: QueryDocumentSnapshot[]; @@ -2826,65 +2826,28 @@ describe('Query class', () => { .orderBy('zip') .orderBy(FieldPath.documentId()) .get(); - if (isEnterprise()) { - expectDocs( - res, - {zip: null}, - {zip: NaN}, - {zip: 91102}, - {zip: 98103}, - {zip: [98101]}, - {zip: ['98101', {zip: 98101}]}, - {zip: {zip: 98101}}, - ); - } else { - expectDocs( - res, - {zip: NaN}, - {zip: 91102}, - {zip: 98103}, - {zip: [98101]}, - {zip: ['98101', {zip: 98101}]}, - {zip: {zip: 98101}}, - ); - } + expectDocs( + res, + {zip: NaN}, + {zip: 91102}, + {zip: 98103}, + {zip: [98101]}, + {zip: ['98101', {zip: 98101}]}, + {zip: {zip: 98101}}, + ); - if (isEnterprise()) { - res = await randomCol - .where('zip', '!=', NaN) - .orderBy(FieldPath.documentId()) - .get(); - expectDocs( - res, - {zip: 91102}, - {zip: 98101}, - {zip: 98103}, - {zip: [98101]}, - {zip: ['98101', {zip: 98101}]}, - {zip: {zip: 98101}}, - {zip: null}, - ); - } else { - res = await randomCol.where('zip', '!=', NaN).get(); - expectDocs( - res, - {zip: 91102}, - {zip: 98101}, - {zip: 98103}, - {zip: [98101]}, - {zip: ['98101', {zip: 98101}]}, - {zip: {zip: 98101}}, - ); - } + res = await randomCol.where('zip', '!=', NaN).get(); + expectDocs( + res, + {zip: 91102}, + {zip: 98101}, + {zip: 98103}, + {zip: [98101]}, + {zip: ['98101', {zip: 98101}]}, + {zip: {zip: 98101}}, + ); - if (isEnterprise()) { - res = await randomCol - .where('zip', '!=', null) - .orderBy(FieldPath.documentId()) - .get(); - } else { - res = await randomCol.where('zip', '!=', null).get(); - } + res = await randomCol.where('zip', '!=', null).get(); expectDocs( res, {zip: NaN}, @@ -2915,16 +2878,7 @@ describe('Query class', () => { {zip: ['98101', {zip: 98101}]}, {zip: {zip: 98101}}, ); - let res: QuerySnapshot | undefined; - - if (isEnterprise()) { - res = await randomCol - .where('zip', 'not-in', [98101, 98103]) - .orderBy(FieldPath.documentId()) - .get(); - } else { - res = await randomCol.where('zip', 'not-in', [98101, 98103]).get(); - } + let res = await randomCol.where('zip', 'not-in', [98101, 98103]).get(); expectDocs( res, {zip: 91102}, @@ -2933,56 +2887,21 @@ describe('Query class', () => { {zip: {zip: 98101}}, ); - if (isEnterprise()) { - res = await randomCol - .where('zip', 'not-in', [NaN]) - .orderBy(FieldPath.documentId()) - .get(); + res = await randomCol.where('zip', 'not-in', [NaN]).get(); - expectDocs( - res, - {zip: 98101}, - {zip: 91102}, - {zip: 98103}, - {zip: [98101]}, - {zip: ['98101', {zip: 98101}]}, - {zip: {zip: 98101}}, - ); - } else { - res = await randomCol.where('zip', 'not-in', [NaN]).get(); + expectDocs( + res, + {zip: 91102}, + {zip: 98101}, + {zip: 98103}, + {zip: [98101]}, + {zip: ['98101', {zip: 98101}]}, + {zip: {zip: 98101}}, + ); - expectDocs( - res, - {zip: 91102}, - {zip: 98101}, - {zip: 98103}, - {zip: [98101]}, - {zip: ['98101', {zip: 98101}]}, - {zip: {zip: 98101}}, - ); - } + res = await randomCol.where('zip', 'not-in', [null]).get(); - if (isEnterprise()) { - res = await randomCol - .where('zip', 'not-in', [null]) - .orderBy(FieldPath.documentId()) - .get(); - } else { - res = await randomCol.where('zip', 'not-in', [null]).get(); - } - if (isEnterprise()) { - expectDocs( - res, - {zip: 98101}, - {zip: 91102}, - {zip: 98103}, - {zip: [98101]}, - {zip: ['98101', {zip: 98101}]}, - {zip: {zip: 98101}}, - ); - } else { - expect(res.size).to.equal(0); - } + expect(res.size).to.equal(0); }); it('supports not-in with document ID array', async () => { @@ -3017,8 +2936,7 @@ describe('Query class', () => { expectDocs(res, {count: 1}, {count: 2}); }); - // TODO waiting fix for `The function array_contains(...) requires `Array` but got `LONG`.` - it.skipEnterprise('supports array-contains-any', async () => { + it('supports array-contains-any', async () => { await addDocs( {array: [42]}, {array: ['a', 42, 'c']}, @@ -3155,7 +3073,6 @@ describe('Query class', () => { expectDocs(res, {doc: 2}, {doc: 3}, {doc: 4}); }); - // TODO WHAT? it('can use offset() method with get()', async () => { await addDocs({foo: 'a'}, {foo: 'b'}); const res = await randomCol.orderBy('foo').offset(1).get(); @@ -3175,7 +3092,6 @@ describe('Query class', () => { expect(received).to.equal(1); }); - // TODO WHAT? it('can run offset(num), where num is larger than the collection size on get()', async () => { await addDocs({foo: 'a'}, {foo: 'b'}); const res = await randomCol.orderBy('foo').offset(3).get(); @@ -3218,19 +3134,14 @@ describe('Query class', () => { }); }); - // TODO wait for implicit sort order decision - it.skipEmulator('supports pagination with where() clauses', () => { + it('supports pagination with where() clauses', () => { const batch = firestore.batch(); for (let i = 0; i < 10; ++i) { batch.set(randomCol.doc('doc' + i), {val: i}); } - let query = randomCol.where('val', '>=', 1).limit(3); - - if (isEnterprise()) { - query = query.orderBy('val').orderBy(FieldPath.documentId()); - } + const query = randomCol.where('val', '>=', 1).limit(3); return batch .commit() @@ -3323,8 +3234,7 @@ describe('Query class', () => { expect(received).to.equal(2); }); - // TODO (enterprise) waiting on implicit sor order decision - it.skipEnterprise('can query collection groups', async () => { + it('can query collection groups', async () => { // Use `randomCol` to get a random collection group name to use but ensure // it starts with 'b' for predictable ordering. const collectionGroup = 'b' + randomCol.id; @@ -3402,49 +3312,45 @@ describe('Query class', () => { expect(querySnapshot.docs.map(d => d.id)).to.deep.equal(['cg-doc2']); }); - // TODO wait for implicit sort order decision - it.skipEnterprise( - 'can query collection groups with where filters on arbitrary documentId', - async () => { - // Use `randomCol` to get a random collection group name to use but - // ensure it starts with 'b' for predictable ordering. - const collectionGroup = 'b' + randomCol.id; - - const docPaths = [ - `a/a/${collectionGroup}/cg-doc1`, - `a/b/a/b/${collectionGroup}/cg-doc2`, - `a/b/${collectionGroup}/cg-doc3`, - `a/b/c/d/${collectionGroup}/cg-doc4`, - `a/c/${collectionGroup}/cg-doc5`, - `${collectionGroup}/cg-doc6`, - 'a/b/nope/nope', - ]; - const batch = firestore.batch(); - for (const docPath of docPaths) { - batch.set(firestore.doc(docPath), {x: 1}); - } - await batch.commit(); + it('can query collection groups with where filters on arbitrary documentId', async () => { + // Use `randomCol` to get a random collection group name to use but + // ensure it starts with 'b' for predictable ordering. + const collectionGroup = 'b' + randomCol.id; - let querySnapshot = await firestore - .collectionGroup(collectionGroup) - .where(FieldPath.documentId(), '>=', 'a/b') - .where(FieldPath.documentId(), '<=', 'a/b0') - .orderBy(FieldPath.documentId()) - .get(); - expect(querySnapshot.docs.map(d => d.id)).to.deep.equal([ - 'cg-doc2', - 'cg-doc3', - 'cg-doc4', - ]); + const docPaths = [ + `a/a/${collectionGroup}/cg-doc1`, + `a/b/a/b/${collectionGroup}/cg-doc2`, + `a/b/${collectionGroup}/cg-doc3`, + `a/b/c/d/${collectionGroup}/cg-doc4`, + `a/c/${collectionGroup}/cg-doc5`, + `${collectionGroup}/cg-doc6`, + 'a/b/nope/nope', + ]; + const batch = firestore.batch(); + for (const docPath of docPaths) { + batch.set(firestore.doc(docPath), {x: 1}); + } + await batch.commit(); - querySnapshot = await firestore - .collectionGroup(collectionGroup) - .where(FieldPath.documentId(), '>', 'a/b') - .where(FieldPath.documentId(), '<', `a/b/${collectionGroup}/cg-doc3`) - .get(); - expect(querySnapshot.docs.map(d => d.id)).to.deep.equal(['cg-doc2']); - }, - ); + let querySnapshot = await firestore + .collectionGroup(collectionGroup) + .where(FieldPath.documentId(), '>=', 'a/b') + .where(FieldPath.documentId(), '<=', 'a/b0') + .orderBy(FieldPath.documentId()) + .get(); + expect(querySnapshot.docs.map(d => d.id)).to.deep.equal([ + 'cg-doc2', + 'cg-doc3', + 'cg-doc4', + ]); + + querySnapshot = await firestore + .collectionGroup(collectionGroup) + .where(FieldPath.documentId(), '>', 'a/b') + .where(FieldPath.documentId(), '<', `a/b/${collectionGroup}/cg-doc3`) + .get(); + expect(querySnapshot.docs.map(d => d.id)).to.deep.equal(['cg-doc2']); + }); it('can query large collections', async () => { // @grpc/grpc-js v0.4.1 failed to deliver the full set of query results for @@ -3541,85 +3447,76 @@ describe('Query class', () => { // TODO Enterprise - wait for implicit sort order decision // Skip this test if running against standard production because it results in a 'missing index' error. - it.skipClassic.skipEnterprise( - 'supports OR queries with composite indexes', - async () => { - const collection = await testCollectionWithDocs({ - doc1: {a: 1, b: 0}, - doc2: {a: 2, b: 1}, - doc3: {a: 3, b: 2}, - doc4: {a: 1, b: 3}, - doc5: {a: 1, b: 1}, - }); + it.skipClassic('supports OR queries with composite indexes', async () => { + const collection = await testCollectionWithDocs({ + doc1: {a: 1, b: 0}, + doc2: {a: 2, b: 1}, + doc3: {a: 3, b: 2}, + doc4: {a: 1, b: 3}, + doc5: {a: 1, b: 1}, + }); - // with one inequality: a>2 || b==1. - expectDocs( - await collection - .where( - Filter.or(Filter.where('a', '>', 2), Filter.where('b', '==', 1)), - ) - .orderBy(FieldPath.documentId()) - .get(), - 'doc2', - 'doc3', - 'doc5', - ); + // with one inequality: a>2 || b==1. + expectDocs( + await collection + .where(Filter.or(Filter.where('a', '>', 2), Filter.where('b', '==', 1))) + .orderBy(FieldPath.documentId()) + .get(), + 'doc2', + 'doc3', + 'doc5', + ); - // Test with limits (implicit order by ASC): (a==1) || (b > 0) LIMIT 2 - expectDocs( - await collection - .where( - Filter.or(Filter.where('a', '==', 1), Filter.where('b', '>', 0)), - ) - .limit(2) - .orderBy(FieldPath.documentId()) - .get(), - 'doc1', - 'doc2', - ); + // Test with limits (implicit order by ASC): (a==1) || (b > 0) LIMIT 2 + expectDocs( + await collection + .where(Filter.or(Filter.where('a', '==', 1), Filter.where('b', '>', 0))) + .limit(2) + .orderBy(FieldPath.documentId()) + .get(), + 'doc1', + 'doc2', + ); - // Test with limits (explicit order by): (a==1) || (b > 0) LIMIT_TO_LAST 2 - // Note: The public query API does not allow implicit ordering when limitToLast is used. - expectDocs( - await collection - .where( - Filter.or(Filter.where('a', '==', 1), Filter.where('b', '>', 0)), - ) - .limitToLast(2) - .orderBy('b') - .orderBy(FieldPath.documentId()) - .get(), - 'doc3', - 'doc4', - ); + // Test with limits (explicit order by): (a==1) || (b > 0) LIMIT_TO_LAST 2 + // Note: The public query API does not allow implicit ordering when limitToLast is used. + expectDocs( + await collection + .where(Filter.or(Filter.where('a', '==', 1), Filter.where('b', '>', 0))) + .limitToLast(2) + .orderBy('b') + .orderBy(FieldPath.documentId()) + .get(), + 'doc3', + 'doc4', + ); - // Test with limits (explicit order by ASC): (a==2) || (b == 1) ORDER BY a LIMIT 1 - expectDocs( - await collection - .where( - Filter.or(Filter.where('a', '==', 2), Filter.where('b', '==', 1)), - ) - .limit(1) - .orderBy('a') - .orderBy(FieldPath.documentId()) - .get(), - 'doc5', - ); + // Test with limits (explicit order by ASC): (a==2) || (b == 1) ORDER BY a LIMIT 1 + expectDocs( + await collection + .where( + Filter.or(Filter.where('a', '==', 2), Filter.where('b', '==', 1)), + ) + .limit(1) + .orderBy('a') + .orderBy(FieldPath.documentId()) + .get(), + 'doc5', + ); - // Test with limits (explicit order by DESC): (a==2) || (b == 1) ORDER BY a LIMIT 1 - expectDocs( - await collection - .where( - Filter.or(Filter.where('a', '==', 2), Filter.where('b', '==', 1)), - ) - .limit(1) - .orderBy('a', 'desc') - .orderBy(FieldPath.documentId()) - .get(), - 'doc2', - ); - }, - ); + // Test with limits (explicit order by DESC): (a==2) || (b == 1) ORDER BY a LIMIT 1 + expectDocs( + await collection + .where( + Filter.or(Filter.where('a', '==', 2), Filter.where('b', '==', 1)), + ) + .limit(1) + .orderBy('a', 'desc') + .orderBy(FieldPath.documentId()) + .get(), + 'doc2', + ); + }); it('supports OR queries on documents with missing fields', async () => { const collection = await testCollectionWithDocs({ @@ -3650,8 +3547,7 @@ describe('Query class', () => { // Skip this test if running against production standard DB because it results in a 'missing index' error. // The Firestore Emulator and Enterprise-editions, however, do serve these queries. - // TODO Enterprise wait for implicit sort order decision - it.skipClassic.skipEnterprise( + it.skipClassic( 'supports OR queries on documents with missing fields', async () => { const collection = await testCollectionWithDocs({ @@ -3695,61 +3591,33 @@ describe('Query class', () => { // Query: a>2 || b==1. // This query has an implicit 'order by a'. - if (isEnterprise()) { - expectDocs( - await collection - .where( - Filter.or(Filter.where('a', '>', 2), Filter.where('b', '==', 1)), - ) - .orderBy('a') - .orderBy(FieldPath.documentId()) - .get(), - 'doc3', - ); - } else { - // Standard Ed: doc2 should not be included because it's missing the field 'a'. - expectDocs( - await collection - .where( - Filter.or(Filter.where('a', '>', 2), Filter.where('b', '==', 1)), - ) - .get(), - 'doc3', - ); - } + // Standard Ed: doc2 should not be included because it's missing the field 'a'. + expectDocs( + await collection + .where( + Filter.or(Filter.where('a', '>', 2), Filter.where('b', '==', 1)), + ) + .get(), + 'doc3', + ); // Query: a>1 || b==1 order by a order by b. - if (isEnterprise()) { - expectDocs( - await collection - .where( - Filter.or(Filter.where('a', '>', 1), Filter.where('b', '==', 1)), - ) - .orderBy('a') - .orderBy('b') - .orderBy(FieldPath.documentId()) - .get(), - 'doc3', - ); - } else { - // doc6 should not be included because it's missing the field 'b'. - // doc2 should not be included because it's missing the field 'a'. - expectDocs( - await collection - .where( - Filter.or(Filter.where('a', '>', 1), Filter.where('b', '==', 1)), - ) - .orderBy('a') - .orderBy('b') - .get(), - 'doc3', - ); - } + // doc6 should not be included because it's missing the field 'b'. + // doc2 should not be included because it's missing the field 'a'. + expectDocs( + await collection + .where( + Filter.or(Filter.where('a', '>', 1), Filter.where('b', '==', 1)), + ) + .orderBy('a') + .orderBy('b') + .get(), + 'doc3', + ); }, ); - // TODO Enterprise wait for implicit sort order decision - it.skipEnterprise('supports OR queries with in', async () => { + it('supports OR queries with in', async () => { const collection = await testCollectionWithDocs({ doc1: {a: 1, b: 0}, doc2: {b: 1}, @@ -3777,8 +3645,7 @@ describe('Query class', () => { }); // Skip this test if running against production because it results in a 'missing index' error. - // TODO Enterprise wait for implicit sort order decision - it.skipClassic.skipEnterprise('supports OR queries with not-in', async () => { + it.skipClassic('supports OR queries with not-in', async () => { const collection = await testCollectionWithDocs({ doc1: {a: 1, b: 0}, doc2: {b: 1}, @@ -3787,45 +3654,23 @@ describe('Query class', () => { doc5: {a: 1}, doc6: {a: 2}, }); - - if (isEnterprise()) { - // a==2 || (b != 2 && b != 3) - // Has implicit "orderBy b" - expectDocs( - await collection - .where( - Filter.or( - Filter.where('a', '==', 2), - Filter.where('b', 'not-in', [2, 3]), - ), - ) - .orderBy(FieldPath.documentId()) - .get(), - 'doc1', - 'doc2', - 'doc5', - 'doc6', - ); - } else { - // a==2 || (b != 2 && b != 3) - // Has implicit "orderBy b" - expectDocs( - await collection - .where( - Filter.or( - Filter.where('a', '==', 2), - Filter.where('b', 'not-in', [2, 3]), - ), - ) - .get(), - 'doc1', - 'doc2', - ); - } + // a==2 || (b != 2 && b != 3) + // Has implicit "orderBy b" + expectDocs( + await collection + .where( + Filter.or( + Filter.where('a', '==', 2), + Filter.where('b', 'not-in', [2, 3]), + ), + ) + .get(), + 'doc1', + 'doc2', + ); }); - // TODO Enterprise wait for implicit sort order decision - it.skipEnterprise('supports OR queries with array membership', async () => { + it('supports OR queries with array membership', async () => { const collection = await testCollectionWithDocs({ doc1: {a: 1, b: [0]}, doc2: {b: [1]}, diff --git a/dev/system-test/pipeline.ts b/dev/system-test/pipeline.ts index 0a9cb6179..851ce1d6c 100644 --- a/dev/system-test/pipeline.ts +++ b/dev/system-test/pipeline.ts @@ -146,693 +146,643 @@ use(chaiAsPromised); const timestampDeltaMS = 3000; -// eslint-disable-next-line no-restricted-properties -(process.env.RUN_ENTERPRISE_TESTS ? describe : describe.skip)( - 'Pipeline class', - () => { - let firestore: Firestore; - let randomCol: CollectionReference; - let beginDocCreation = 0; - let endDocCreation = 0; - - async function testCollectionWithDocs(docs: { - [id: string]: DocumentData; - }): Promise> { - beginDocCreation = new Date().valueOf(); - for (const id in docs) { - const ref = randomCol.doc(id); - await ref.set(docs[id]); - } - endDocCreation = new Date().valueOf(); - return randomCol; +describe.skipClassic('Pipeline class', () => { + let firestore: Firestore; + let randomCol: CollectionReference; + let beginDocCreation = 0; + let endDocCreation = 0; + + async function testCollectionWithDocs(docs: { + [id: string]: DocumentData; + }): Promise> { + beginDocCreation = new Date().valueOf(); + for (const id in docs) { + const ref = randomCol.doc(id); + await ref.set(docs[id]); } - - function expectResults(result: PipelineSnapshot, ...docs: string[]): void; - function expectResults( - result: PipelineSnapshot, - ...data: DocumentData[] - ): void; - function expectResults( - result: PipelineSnapshot, - ...data: DocumentData[] | string[] - ): void { - if (data.length > 0) { - if (typeof data[0] === 'string') { - const actualIds = result.results.map(result => result.id); - expect(actualIds).to.deep.equal(data); - } else { - result.results.forEach(r => { - expect(r.data()).to.deep.equal(data.shift()); - }); - } + endDocCreation = new Date().valueOf(); + return randomCol; + } + + function expectResults(result: PipelineSnapshot, ...docs: string[]): void; + function expectResults( + result: PipelineSnapshot, + ...data: DocumentData[] + ): void; + function expectResults( + result: PipelineSnapshot, + ...data: DocumentData[] | string[] + ): void { + if (data.length > 0) { + if (typeof data[0] === 'string') { + const actualIds = result.results.map(result => result.id); + expect(actualIds).to.deep.equal(data); } else { - expect(result.results.length).to.equal(data.length); + result.results.forEach(r => { + expect(r.data()).to.deep.equal(data.shift()); + }); } + } else { + expect(result.results.length).to.equal(data.length); } - - async function setupBookDocs(): Promise> { - const bookDocs: {[id: string]: DocumentData} = { - book1: { - title: "The Hitchhiker's Guide to the Galaxy", - author: 'Douglas Adams', - genre: 'Science Fiction', - published: 1979, - rating: 4.2, - tags: ['comedy', 'space', 'adventure'], - awards: { - hugo: true, - nebula: false, - others: {unknown: {year: 1980}}, - }, - nestedField: {'level.1': {'level.2': true}}, - embedding: FieldValue.vector([10, 1, 1, 1, 1, 1, 1, 1, 1, 1]), - }, - book2: { - title: 'Pride and Prejudice', - author: 'Jane Austen', - genre: 'Romance', - published: 1813, - rating: 4.5, - tags: ['classic', 'social commentary', 'love'], - awards: {none: true}, - embedding: FieldValue.vector([1, 10, 1, 1, 1, 1, 1, 1, 1, 1]), - }, - book3: { - title: 'One Hundred Years of Solitude', - author: 'Gabriel García Márquez', - genre: 'Magical Realism', - published: 1967, - rating: 4.3, - tags: ['family', 'history', 'fantasy'], - awards: {nobel: true, nebula: false}, - embedding: FieldValue.vector([1, 1, 10, 1, 1, 1, 1, 1, 1, 1]), - }, - book4: { - title: 'The Lord of the Rings', - author: 'J.R.R. Tolkien', - genre: 'Fantasy', - published: 1954, - rating: 4.7, - tags: ['adventure', 'magic', 'epic'], - awards: {hugo: false, nebula: false}, - remarks: null, - cost: NaN, - embedding: FieldValue.vector([1, 1, 1, 10, 1, 1, 1, 1, 1, 1]), - }, - book5: { - title: "The Handmaid's Tale", - author: 'Margaret Atwood', - genre: 'Dystopian', - published: 1985, - rating: 4.1, - tags: ['feminism', 'totalitarianism', 'resistance'], - awards: {'arthur c. clarke': true, 'booker prize': false}, - embedding: FieldValue.vector([1, 1, 1, 1, 10, 1, 1, 1, 1, 1]), - }, - book6: { - title: 'Crime and Punishment', - author: 'Fyodor Dostoevsky', - genre: 'Psychological Thriller', - published: 1866, - rating: 4.3, - tags: ['philosophy', 'crime', 'redemption'], - awards: {none: true}, - embedding: FieldValue.vector([1, 1, 1, 1, 1, 10, 1, 1, 1, 1]), - }, - book7: { - title: 'To Kill a Mockingbird', - author: 'Harper Lee', - genre: 'Southern Gothic', - published: 1960, - rating: 4.2, - tags: ['racism', 'injustice', 'coming-of-age'], - awards: {pulitzer: true}, - embedding: FieldValue.vector([1, 1, 1, 1, 1, 1, 10, 1, 1, 1]), - }, - book8: { - title: '1984', - author: 'George Orwell', - genre: 'Dystopian', - published: 1949, - rating: 4.2, - tags: ['surveillance', 'totalitarianism', 'propaganda'], - awards: {prometheus: true}, - embedding: FieldValue.vector([1, 1, 1, 1, 1, 1, 1, 10, 1, 1]), - }, - book9: { - title: 'The Great Gatsby', - author: 'F. Scott Fitzgerald', - genre: 'Modernist', - published: 1925, - rating: 4.0, - tags: ['wealth', 'american dream', 'love'], - awards: {none: true}, - embedding: FieldValue.vector([1, 1, 1, 1, 1, 1, 1, 1, 10, 1]), - }, - book10: { - title: 'Dune', - author: 'Frank Herbert', - genre: 'Science Fiction', - published: 1965, - rating: 4.6, - tags: ['politics', 'desert', 'ecology'], - awards: {hugo: true, nebula: true}, - embedding: FieldValue.vector([1, 1, 1, 1, 1, 1, 1, 1, 1, 10]), + } + + async function setupBookDocs(): Promise> { + const bookDocs: {[id: string]: DocumentData} = { + book1: { + title: "The Hitchhiker's Guide to the Galaxy", + author: 'Douglas Adams', + genre: 'Science Fiction', + published: 1979, + rating: 4.2, + tags: ['comedy', 'space', 'adventure'], + awards: { + hugo: true, + nebula: false, + others: {unknown: {year: 1980}}, }, - }; - return testCollectionWithDocs(bookDocs); - } + nestedField: {'level.1': {'level.2': true}}, + embedding: FieldValue.vector([10, 1, 1, 1, 1, 1, 1, 1, 1, 1]), + }, + book2: { + title: 'Pride and Prejudice', + author: 'Jane Austen', + genre: 'Romance', + published: 1813, + rating: 4.5, + tags: ['classic', 'social commentary', 'love'], + awards: {none: true}, + embedding: FieldValue.vector([1, 10, 1, 1, 1, 1, 1, 1, 1, 1]), + }, + book3: { + title: 'One Hundred Years of Solitude', + author: 'Gabriel García Márquez', + genre: 'Magical Realism', + published: 1967, + rating: 4.3, + tags: ['family', 'history', 'fantasy'], + awards: {nobel: true, nebula: false}, + embedding: FieldValue.vector([1, 1, 10, 1, 1, 1, 1, 1, 1, 1]), + }, + book4: { + title: 'The Lord of the Rings', + author: 'J.R.R. Tolkien', + genre: 'Fantasy', + published: 1954, + rating: 4.7, + tags: ['adventure', 'magic', 'epic'], + awards: {hugo: false, nebula: false}, + remarks: null, + cost: NaN, + embedding: FieldValue.vector([1, 1, 1, 10, 1, 1, 1, 1, 1, 1]), + }, + book5: { + title: "The Handmaid's Tale", + author: 'Margaret Atwood', + genre: 'Dystopian', + published: 1985, + rating: 4.1, + tags: ['feminism', 'totalitarianism', 'resistance'], + awards: {'arthur c. clarke': true, 'booker prize': false}, + embedding: FieldValue.vector([1, 1, 1, 1, 10, 1, 1, 1, 1, 1]), + }, + book6: { + title: 'Crime and Punishment', + author: 'Fyodor Dostoevsky', + genre: 'Psychological Thriller', + published: 1866, + rating: 4.3, + tags: ['philosophy', 'crime', 'redemption'], + awards: {none: true}, + embedding: FieldValue.vector([1, 1, 1, 1, 1, 10, 1, 1, 1, 1]), + }, + book7: { + title: 'To Kill a Mockingbird', + author: 'Harper Lee', + genre: 'Southern Gothic', + published: 1960, + rating: 4.2, + tags: ['racism', 'injustice', 'coming-of-age'], + awards: {pulitzer: true}, + embedding: FieldValue.vector([1, 1, 1, 1, 1, 1, 10, 1, 1, 1]), + }, + book8: { + title: '1984', + author: 'George Orwell', + genre: 'Dystopian', + published: 1949, + rating: 4.2, + tags: ['surveillance', 'totalitarianism', 'propaganda'], + awards: {prometheus: true}, + embedding: FieldValue.vector([1, 1, 1, 1, 1, 1, 1, 10, 1, 1]), + }, + book9: { + title: 'The Great Gatsby', + author: 'F. Scott Fitzgerald', + genre: 'Modernist', + published: 1925, + rating: 4.0, + tags: ['wealth', 'american dream', 'love'], + awards: {none: true}, + embedding: FieldValue.vector([1, 1, 1, 1, 1, 1, 1, 1, 10, 1]), + }, + book10: { + title: 'Dune', + author: 'Frank Herbert', + genre: 'Science Fiction', + published: 1965, + rating: 4.6, + tags: ['politics', 'desert', 'ecology'], + awards: {hugo: true, nebula: true}, + embedding: FieldValue.vector([1, 1, 1, 1, 1, 1, 1, 1, 1, 10]), + }, + }; + return testCollectionWithDocs(bookDocs); + } + + before(async () => { + randomCol = getTestRoot(); + await setupBookDocs(); + firestore = randomCol.firestore; + }); + + afterEach(() => verifyInstance(firestore as unknown as InternalFirestore)); + + describe('pipeline results', () => { + it('empty snapshot as expected', async () => { + const snapshot = await firestore + .pipeline() + .collection(randomCol.path) + .limit(0) + .execute(); + expect(snapshot.results.length).to.equal(0); + }); - before(async () => { - randomCol = getTestRoot(); - await setupBookDocs(); - firestore = randomCol.firestore; + it('full snapshot as expected', async () => { + const ppl = firestore + .pipeline() + .collection(randomCol.path) + .sort(ascending('__name__')); + const snapshot = await ppl.execute(); + expect(snapshot.results.length).to.equal(10); + expect(snapshot.pipeline).to.equal(ppl); + expectResults( + snapshot, + 'book1', + 'book10', + 'book2', + 'book3', + 'book4', + 'book5', + 'book6', + 'book7', + 'book8', + 'book9', + ); }); - afterEach(() => verifyInstance(firestore as unknown as InternalFirestore)); + it('result equals works', async () => { + const ppl = firestore + .pipeline() + .collection(randomCol.path) + .sort(ascending('title')) + .limit(1); + const snapshot1 = await ppl.execute(); + const snapshot2 = await ppl.execute(); + expect(snapshot1.results.length).to.equal(1); + expect(snapshot2.results.length).to.equal(1); + expect(snapshot1.results[0].isEqual(snapshot2.results[0])).to.be.true; + }); - describe('pipeline results', () => { - it('empty snapshot as expected', async () => { - const snapshot = await firestore - .pipeline() - .collection(randomCol.path) - .limit(0) - .execute(); - expect(snapshot.results.length).to.equal(0); - }); + it('returns execution time', async () => { + const start = new Date().valueOf(); + const pipeline = firestore.pipeline().collection(randomCol.path); - it('full snapshot as expected', async () => { - const ppl = firestore - .pipeline() - .collection(randomCol.path) - .sort(ascending('__name__')); - const snapshot = await ppl.execute(); - expect(snapshot.results.length).to.equal(10); - expect(snapshot.pipeline).to.equal(ppl); - expectResults( - snapshot, - 'book1', - 'book10', - 'book2', - 'book3', - 'book4', - 'book5', - 'book6', - 'book7', - 'book8', - 'book9', - ); - }); + const snapshot = await pipeline.execute(); + const end = new Date().valueOf(); - it('result equals works', async () => { - const ppl = firestore - .pipeline() - .collection(randomCol.path) - .sort(ascending('title')) - .limit(1); - const snapshot1 = await ppl.execute(); - const snapshot2 = await ppl.execute(); - expect(snapshot1.results.length).to.equal(1); - expect(snapshot2.results.length).to.equal(1); - expect(snapshot1.results[0].isEqual(snapshot2.results[0])).to.be.true; - }); + expect(snapshot.executionTime.toDate().valueOf()).to.approximately( + (start + end) / 2, + timestampDeltaMS, + ); + }); - it('returns execution time', async () => { - const start = new Date().valueOf(); - const pipeline = firestore.pipeline().collection(randomCol.path); + it('returns execution time for an empty query', async () => { + const start = new Date().valueOf(); + const pipeline = firestore.pipeline().collection(randomCol.path).limit(0); - const snapshot = await pipeline.execute(); - const end = new Date().valueOf(); + const snapshot = await pipeline.execute(); + const end = new Date().valueOf(); - expect(snapshot.executionTime.toDate().valueOf()).to.approximately( - (start + end) / 2, - timestampDeltaMS, - ); - }); + expect(snapshot.results.length).to.equal(0); - it('returns execution time for an empty query', async () => { - const start = new Date().valueOf(); - const pipeline = firestore - .pipeline() - .collection(randomCol.path) - .limit(0); + expect(snapshot.executionTime.toDate().valueOf()).to.approximately( + (start + end) / 2, + timestampDeltaMS, + ); + }); - const snapshot = await pipeline.execute(); - const end = new Date().valueOf(); + it('returns create and update time for each document', async () => { + const pipeline = firestore.pipeline().collection(randomCol.path); - expect(snapshot.results.length).to.equal(0); + let snapshot = await pipeline.execute(); + expect(snapshot.results.length).to.equal(10); + snapshot.results.forEach(doc => { + expect(doc.createTime).to.not.be.null; + expect(doc.updateTime).to.not.be.null; - expect(snapshot.executionTime.toDate().valueOf()).to.approximately( - (start + end) / 2, + expect(doc.createTime!.toDate().valueOf()).to.approximately( + (beginDocCreation + endDocCreation) / 2, timestampDeltaMS, ); + expect(doc.updateTime!.toDate().valueOf()).to.approximately( + (beginDocCreation + endDocCreation) / 2, + timestampDeltaMS, + ); + expect(doc.createTime?.valueOf()).to.equal(doc.updateTime?.valueOf()); }); - it('returns create and update time for each document', async () => { - const pipeline = firestore.pipeline().collection(randomCol.path); - - let snapshot = await pipeline.execute(); - expect(snapshot.results.length).to.equal(10); - snapshot.results.forEach(doc => { - expect(doc.createTime).to.not.be.null; - expect(doc.updateTime).to.not.be.null; - - expect(doc.createTime!.toDate().valueOf()).to.approximately( - (beginDocCreation + endDocCreation) / 2, - timestampDeltaMS, - ); - expect(doc.updateTime!.toDate().valueOf()).to.approximately( - (beginDocCreation + endDocCreation) / 2, - timestampDeltaMS, - ); - expect(doc.createTime?.valueOf()).to.equal(doc.updateTime?.valueOf()); - }); - - const wb = firestore.batch(); - snapshot.results.forEach(doc => { - wb.update(doc.ref!, {newField: 'value'}); - }); - await wb.commit(); - - snapshot = await pipeline.execute(); - expect(snapshot.results.length).to.equal(10); - snapshot.results.forEach(doc => { - expect(doc.createTime).to.not.be.null; - expect(doc.updateTime).to.not.be.null; - expect(doc.createTime!.toDate().valueOf()).to.be.lessThan( - doc.updateTime!.toDate().valueOf(), - ); - }); + const wb = firestore.batch(); + snapshot.results.forEach(doc => { + wb.update(doc.ref!, {newField: 'value'}); }); + await wb.commit(); - it('returns execution time for an aggregate query', async () => { - const start = new Date().valueOf(); - const pipeline = firestore - .pipeline() - .collection(randomCol.path) - .aggregate(average('rating').as('avgRating')); - - const snapshot = await pipeline.execute(); - const end = new Date().valueOf(); - - expect(snapshot.results.length).to.equal(1); - - expect(snapshot.executionTime.toDate().valueOf()).to.approximately( - (start + end) / 2, - timestampDeltaMS, + snapshot = await pipeline.execute(); + expect(snapshot.results.length).to.equal(10); + snapshot.results.forEach(doc => { + expect(doc.createTime).to.not.be.null; + expect(doc.updateTime).to.not.be.null; + expect(doc.createTime!.toDate().valueOf()).to.be.lessThan( + doc.updateTime!.toDate().valueOf(), ); }); + }); - it('returns undefined create and update time for each result in an aggregate query', async () => { - const pipeline = firestore - .pipeline() - .collection(randomCol.path) - .aggregate({ - accumulators: [average('rating').as('avgRating')], - groups: ['genre'], - }); + it('returns execution time for an aggregate query', async () => { + const start = new Date().valueOf(); + const pipeline = firestore + .pipeline() + .collection(randomCol.path) + .aggregate(average('rating').as('avgRating')); - const snapshot = await pipeline.execute(); + const snapshot = await pipeline.execute(); + const end = new Date().valueOf(); - expect(snapshot.results.length).to.equal(8); + expect(snapshot.results.length).to.equal(1); - snapshot.results.forEach(doc => { - expect(doc.updateTime).to.be.undefined; - expect(doc.createTime).to.be.undefined; - }); - }); + expect(snapshot.executionTime.toDate().valueOf()).to.approximately( + (start + end) / 2, + timestampDeltaMS, + ); }); - describe('pipeline explain', () => { - it('mode: analyze, format: text', async () => { - const ppl = firestore - .pipeline() - .collection(randomCol.path) - .sort(ascending('__name__')); - - const snapshot = await ppl.execute({ - explainOptions: { - mode: 'analyze', - outputFormat: 'text', - }, + it('returns undefined create and update time for each result in an aggregate query', async () => { + const pipeline = firestore + .pipeline() + .collection(randomCol.path) + .aggregate({ + accumulators: [average('rating').as('avgRating')], + groups: ['genre'], }); - expect(snapshot.explainStats).not.to.be.undefined; - expect(snapshot.explainStats!.text.length).to.be.greaterThan(0); - expect(snapshot.explainStats!.text.charAt(0)).not.to.equal('{'); + const snapshot = await pipeline.execute(); - expect(snapshot.explainStats!.rawData.type_url).to.equal( - 'type.googleapis.com/google.protobuf.StringValue', - ); - expect(snapshot.explainStats!.rawData.value).to.not.be.null; - expect(snapshot.explainStats!.rawData.value).to.not.be.undefined; + expect(snapshot.results.length).to.equal(8); - expect(snapshot.results.length).to.equal(10); - expect(snapshot.pipeline).to.equal(ppl); - expectResults( - snapshot, - 'book1', - 'book10', - 'book2', - 'book3', - 'book4', - 'book5', - 'book6', - 'book7', - 'book8', - 'book9', - ); + snapshot.results.forEach(doc => { + expect(doc.updateTime).to.be.undefined; + expect(doc.createTime).to.be.undefined; }); - - it('mode: analyze, format: unspecified', async () => { - const ppl = firestore - .pipeline() - .collection(randomCol.path) - .sort(ascending('__name__')); - const snapshot = await ppl.execute({ - explainOptions: { - mode: 'analyze', - }, - }); - expect(snapshot.explainStats).not.to.be.undefined; - expect(snapshot.explainStats!.text.length).to.be.greaterThan(0); - expect(snapshot.explainStats!.text.charAt(0)).not.to.equal('{'); - - expect(snapshot.explainStats!.rawData.type_url).to.equal( - 'type.googleapis.com/google.protobuf.StringValue', - ); - expect(snapshot.explainStats!.rawData.value).to.not.be.null; - expect(snapshot.explainStats!.rawData.value).to.not.be.undefined; - - expect(snapshot.results.length).to.equal(10); - expect(snapshot.pipeline).to.equal(ppl); - expectResults( - snapshot, - 'book1', - 'book10', - 'book2', - 'book3', - 'book4', - 'book5', - 'book6', - 'book7', - 'book8', - 'book9', - ); + }); + }); + + describe('pipeline explain', () => { + it('mode: analyze, format: text', async () => { + const ppl = firestore + .pipeline() + .collection(randomCol.path) + .sort(ascending('__name__')); + + const snapshot = await ppl.execute({ + explainOptions: { + mode: 'analyze', + outputFormat: 'text', + }, }); - it('mode: execute, format: text', async () => { - const ppl = firestore - .pipeline() - .collection(randomCol.path) - .sort(ascending('__name__')); - const snapshot = await ppl.execute({ - explainOptions: { - mode: 'execute', - outputFormat: 'text', - }, - }); - expect(snapshot.explainStats).to.be.undefined; + expect(snapshot.explainStats).not.to.be.undefined; + expect(snapshot.explainStats!.text.length).to.be.greaterThan(0); + expect(snapshot.explainStats!.text.charAt(0)).not.to.equal('{'); - expect(snapshot.results.length).to.equal(10); - expect(snapshot.pipeline).to.equal(ppl); - expectResults( - snapshot, - 'book1', - 'book10', - 'book2', - 'book3', - 'book4', - 'book5', - 'book6', - 'book7', - 'book8', - 'book9', - ); + expect(snapshot.explainStats!.rawData.type_url).to.equal( + 'type.googleapis.com/google.protobuf.StringValue', + ); + expect(snapshot.explainStats!.rawData.value).to.not.be.null; + expect(snapshot.explainStats!.rawData.value).to.not.be.undefined; + + expect(snapshot.results.length).to.equal(10); + expect(snapshot.pipeline).to.equal(ppl); + expectResults( + snapshot, + 'book1', + 'book10', + 'book2', + 'book3', + 'book4', + 'book5', + 'book6', + 'book7', + 'book8', + 'book9', + ); + }); + + it('mode: analyze, format: unspecified', async () => { + const ppl = firestore + .pipeline() + .collection(randomCol.path) + .sort(ascending('__name__')); + const snapshot = await ppl.execute({ + explainOptions: { + mode: 'analyze', + }, }); + expect(snapshot.explainStats).not.to.be.undefined; + expect(snapshot.explainStats!.text.length).to.be.greaterThan(0); + expect(snapshot.explainStats!.text.charAt(0)).not.to.equal('{'); - it('mode: unspecified, format: text', async () => { - const ppl = firestore - .pipeline() - .collection(randomCol.path) - .sort(ascending('__name__')); - const snapshot = await ppl.execute({ - explainOptions: { - mode: undefined, - }, - }); - expect(snapshot.explainStats).to.be.undefined; + expect(snapshot.explainStats!.rawData.type_url).to.equal( + 'type.googleapis.com/google.protobuf.StringValue', + ); + expect(snapshot.explainStats!.rawData.value).to.not.be.null; + expect(snapshot.explainStats!.rawData.value).to.not.be.undefined; + + expect(snapshot.results.length).to.equal(10); + expect(snapshot.pipeline).to.equal(ppl); + expectResults( + snapshot, + 'book1', + 'book10', + 'book2', + 'book3', + 'book4', + 'book5', + 'book6', + 'book7', + 'book8', + 'book9', + ); + }); - expect(snapshot.results.length).to.equal(10); - expect(snapshot.pipeline).to.equal(ppl); - expectResults( - snapshot, - 'book1', - 'book10', - 'book2', - 'book3', - 'book4', - 'book5', - 'book6', - 'book7', - 'book8', - 'book9', - ); + it('mode: execute, format: text', async () => { + const ppl = firestore + .pipeline() + .collection(randomCol.path) + .sort(ascending('__name__')); + const snapshot = await ppl.execute({ + explainOptions: { + mode: 'execute', + outputFormat: 'text', + }, }); + expect(snapshot.explainStats).to.be.undefined; + + expect(snapshot.results.length).to.equal(10); + expect(snapshot.pipeline).to.equal(ppl); + expectResults( + snapshot, + 'book1', + 'book10', + 'book2', + 'book3', + 'book4', + 'book5', + 'book6', + 'book7', + 'book8', + 'book9', + ); }); - describe('pipeline sources', () => { - it('supports CollectionReference as source', async () => { - const snapshot = await firestore - .pipeline() - .collection(randomCol) - .execute(); - expect(snapshot.results.length).to.equal(10); + it('mode: unspecified, format: text', async () => { + const ppl = firestore + .pipeline() + .collection(randomCol.path) + .sort(ascending('__name__')); + const snapshot = await ppl.execute({ + explainOptions: { + mode: undefined, + }, }); + expect(snapshot.explainStats).to.be.undefined; + + expect(snapshot.results.length).to.equal(10); + expect(snapshot.pipeline).to.equal(ppl); + expectResults( + snapshot, + 'book1', + 'book10', + 'book2', + 'book3', + 'book4', + 'book5', + 'book6', + 'book7', + 'book8', + 'book9', + ); + }); + }); + + describe('pipeline sources', () => { + it('supports CollectionReference as source', async () => { + const snapshot = await firestore + .pipeline() + .collection(randomCol) + .execute(); + expect(snapshot.results.length).to.equal(10); + }); - it('supports list of documents as source', async () => { - const collName = randomCol.id; - - const snapshot = await firestore - .pipeline() - .documents([ - `${collName}/book1`, - randomCol.doc('book2'), - randomCol.doc('book3').path, - ]) - .execute(); - expect(snapshot.results.length).to.equal(3); - }); + it('supports list of documents as source', async () => { + const collName = randomCol.id; + + const snapshot = await firestore + .pipeline() + .documents([ + `${collName}/book1`, + randomCol.doc('book2'), + randomCol.doc('book3').path, + ]) + .execute(); + expect(snapshot.results.length).to.equal(3); + }); - it('reject CollectionReference for another DB', async () => { - const db2 = getTestDb({databaseId: 'notDefault', projectId: 'random'}); + it('reject CollectionReference for another DB', async () => { + const db2 = getTestDb({databaseId: 'notDefault', projectId: 'random'}); - expect(() => { - firestore.pipeline().collection(db2.collection('foo')); - }).to.throw(/Invalid CollectionReference/); + expect(() => { + firestore.pipeline().collection(db2.collection('foo')); + }).to.throw(/Invalid CollectionReference/); - await db2.terminate(); - }); + await db2.terminate(); + }); - it('reject DocumentReference for another DB', async () => { - const db2 = getTestDb({databaseId: 'notDefault', projectId: 'random'}); + it('reject DocumentReference for another DB', async () => { + const db2 = getTestDb({databaseId: 'notDefault', projectId: 'random'}); - expect(() => { - firestore.pipeline().documents([db2.doc('foo/bar')]); - }).to.throw(/Invalid DocumentReference/); - - await db2.terminate(); - }); - - it('supports collection group as source', async () => { - const randomSubCollectionId = Math.random().toString(16).slice(2); - const doc1 = await randomCol - .doc('book1') - .collection(randomSubCollectionId) - .add({order: 1}); - const doc2 = await randomCol - .doc('book2') - .collection(randomSubCollectionId) - .add({order: 2}); - const snapshot = await firestore - .pipeline() - .collectionGroup(randomSubCollectionId) - .sort(ascending('order')) - .execute(); - expectResults(snapshot, doc1.id, doc2.id); - }); + expect(() => { + firestore.pipeline().documents([db2.doc('foo/bar')]); + }).to.throw(/Invalid DocumentReference/); - it('supports database as source', async () => { - const randomId = Math.random().toString(16).slice(2); - const doc1 = await randomCol.doc('book1').collection('sub').add({ - order: 1, - randomId, - }); - const doc2 = await randomCol.doc('book2').collection('sub').add({ - order: 2, - randomId, - }); - const snapshot = await firestore - .pipeline() - .database() - .where(equal('randomId', randomId)) - .sort(ascending('order')) - .execute(); - expectResults(snapshot, doc1.id, doc2.id); - }); - }); - - describe('supported data types', () => { - it('accepts and returns all data types', async () => { - const refDate = new Date(); - const refTimestamp = Timestamp.now(); - const constants = [ - constant(1).as('number'), - constant('a string').as('string'), - constant(true).as('boolean'), - constant(null).as('null'), - constant(new GeoPoint(0.1, 0.2)).as('geoPoint'), - constant(refTimestamp).as('timestamp'), - constant(refDate).as('date'), - constant(new Uint8Array([1, 2, 3, 4, 5, 6, 7, 0])).as('bytes'), - constant(firestore.doc('foo/bar')).as('documentReference'), - constant(FieldValue.vector([1, 2, 3])).as('vectorValue'), - map({ - number: 1, - string: 'a string', - boolean: true, - null: null, - geoPoint: new GeoPoint(0.1, 0.2), - timestamp: refTimestamp, - date: refDate, - uint8Array: new Uint8Array([1, 2, 3, 4, 5, 6, 7, 0]), - documentReference: firestore.doc('foo/bar'), - vectorValue: FieldValue.vector([1, 2, 3]), - map: { - number: 2, - string: 'b string', - }, - array: [1, 'c string'], - }).as('map'), - array([ - 1, - 'a string', - true, - null, - new GeoPoint(0.1, 0.2), - refTimestamp, - refDate, - new Uint8Array([1, 2, 3, 4, 5, 6, 7, 0]), - firestore.doc('foo/bar'), - FieldValue.vector([1, 2, 3]), - { - number: 2, - string: 'b string', - }, - ]).as('array'), - ]; + await db2.terminate(); + }); - const snapshots = await firestore - .pipeline() - .collection(randomCol.path) - .limit(1) - .select(constants[0], ...constants.slice(1)) - .execute(); + it('supports collection group as source', async () => { + const randomSubCollectionId = Math.random().toString(16).slice(2); + const doc1 = await randomCol + .doc('book1') + .collection(randomSubCollectionId) + .add({order: 1}); + const doc2 = await randomCol + .doc('book2') + .collection(randomSubCollectionId) + .add({order: 2}); + const snapshot = await firestore + .pipeline() + .collectionGroup(randomSubCollectionId) + .sort(ascending('order')) + .execute(); + expectResults(snapshot, doc1.id, doc2.id); + }); - expectResults(snapshots, { + it('supports database as source', async () => { + const randomId = Math.random().toString(16).slice(2); + const doc1 = await randomCol.doc('book1').collection('sub').add({ + order: 1, + randomId, + }); + const doc2 = await randomCol.doc('book2').collection('sub').add({ + order: 2, + randomId, + }); + const snapshot = await firestore + .pipeline() + .database() + .where(equal('randomId', randomId)) + .sort(ascending('order')) + .execute(); + expectResults(snapshot, doc1.id, doc2.id); + }); + }); + + describe('supported data types', () => { + it('accepts and returns all data types', async () => { + const refDate = new Date(); + const refTimestamp = Timestamp.now(); + const constants = [ + constant(1).as('number'), + constant('a string').as('string'), + constant(true).as('boolean'), + constant(null).as('null'), + constant(new GeoPoint(0.1, 0.2)).as('geoPoint'), + constant(refTimestamp).as('timestamp'), + constant(refDate).as('date'), + constant(new Uint8Array([1, 2, 3, 4, 5, 6, 7, 0])).as('bytes'), + constant(firestore.doc('foo/bar')).as('documentReference'), + constant(FieldValue.vector([1, 2, 3])).as('vectorValue'), + map({ number: 1, string: 'a string', boolean: true, null: null, geoPoint: new GeoPoint(0.1, 0.2), timestamp: refTimestamp, - date: Timestamp.fromDate(refDate), - bytes: new Uint8Array([1, 2, 3, 4, 5, 6, 7, 0]), - documentReference: firestore.collection('foo').doc('bar'), + date: refDate, + uint8Array: new Uint8Array([1, 2, 3, 4, 5, 6, 7, 0]), + documentReference: firestore.doc('foo/bar'), vectorValue: FieldValue.vector([1, 2, 3]), map: { - number: 1, - string: 'a string', - boolean: true, - null: null, - geoPoint: new GeoPoint(0.1, 0.2), - timestamp: refTimestamp, - date: Timestamp.fromDate(refDate), - uint8Array: new Uint8Array([1, 2, 3, 4, 5, 6, 7, 0]), - documentReference: firestore.collection('foo').doc('bar'), - vectorValue: FieldValue.vector([1, 2, 3]), - map: { - number: 2, - string: 'b string', - }, - array: [1, 'c string'], + number: 2, + string: 'b string', }, - array: [ - 1, - 'a string', - true, - null, - new GeoPoint(0.1, 0.2), - refTimestamp, - Timestamp.fromDate(refDate), - new Uint8Array([1, 2, 3, 4, 5, 6, 7, 0]), - firestore.collection('foo').doc('bar'), - FieldValue.vector([1, 2, 3]), - { - number: 2, - string: 'b string', - }, - ], - }); - }); - - it('throws on undefined in a map', async () => { - try { - await firestore - .pipeline() - .collection(randomCol.path) - .limit(1) - .select( - map({ - number: 1, - bad: undefined, - }).as('foo'), - ) - .execute(); - expect.fail('The statement above was expected to throw.'); - } catch (e: unknown) { - const error = e as Error; - console.log(error.message); - expect(error.message).to.contain( - 'Value for argument "value" is not a valid map value. Cannot use "undefined" as a Firestore value (found in field "bad").', - ); - } - }); - - it('throws on undefined in an array', async () => { - try { - await firestore - .pipeline() - .collection(randomCol.path) - .limit(1) - .select(array([1, undefined]).as('foo')) - .execute(); - expect.fail('The statement above was expected to throw.'); - } catch (e: unknown) { - const error = e as Error; - console.log(error.message); - expect(error.message).to.contain( - 'Value for argument "value" is not a valid array value. Cannot use "undefined" as a Firestore value', - ); - } + array: [1, 'c string'], + }).as('map'), + array([ + 1, + 'a string', + true, + null, + new GeoPoint(0.1, 0.2), + refTimestamp, + refDate, + new Uint8Array([1, 2, 3, 4, 5, 6, 7, 0]), + firestore.doc('foo/bar'), + FieldValue.vector([1, 2, 3]), + { + number: 2, + string: 'b string', + }, + ]).as('array'), + ]; + + const snapshots = await firestore + .pipeline() + .collection(randomCol.path) + .limit(1) + .select(constants[0], ...constants.slice(1)) + .execute(); + + expectResults(snapshots, { + number: 1, + string: 'a string', + boolean: true, + null: null, + geoPoint: new GeoPoint(0.1, 0.2), + timestamp: refTimestamp, + date: Timestamp.fromDate(refDate), + bytes: new Uint8Array([1, 2, 3, 4, 5, 6, 7, 0]), + documentReference: firestore.collection('foo').doc('bar'), + vectorValue: FieldValue.vector([1, 2, 3]), + map: { + number: 1, + string: 'a string', + boolean: true, + null: null, + geoPoint: new GeoPoint(0.1, 0.2), + timestamp: refTimestamp, + date: Timestamp.fromDate(refDate), + uint8Array: new Uint8Array([1, 2, 3, 4, 5, 6, 7, 0]), + documentReference: firestore.collection('foo').doc('bar'), + vectorValue: FieldValue.vector([1, 2, 3]), + map: { + number: 2, + string: 'b string', + }, + array: [1, 'c string'], + }, + array: [ + 1, + 'a string', + true, + null, + new GeoPoint(0.1, 0.2), + refTimestamp, + Timestamp.fromDate(refDate), + new Uint8Array([1, 2, 3, 4, 5, 6, 7, 0]), + firestore.collection('foo').doc('bar'), + FieldValue.vector([1, 2, 3]), + { + number: 2, + string: 'b string', + }, + ], }); + }); - it('ignores undefined in a map if ignoreUndefinedProperties is true', async () => { - const customFirestore = getTestDb({ - ignoreUndefinedProperties: true, - }); - - const snapshot = await customFirestore + it('throws on undefined in a map', async () => { + try { + await firestore .pipeline() .collection(randomCol.path) .limit(1) @@ -843,46 +793,111 @@ const timestampDeltaMS = 3000; }).as('foo'), ) .execute(); + expect.fail('The statement above was expected to throw.'); + } catch (e: unknown) { + const error = e as Error; + console.log(error.message); + expect(error.message).to.contain( + 'Value for argument "value" is not a valid map value. Cannot use "undefined" as a Firestore value (found in field "bad").', + ); + } + }); - const data = snapshot.results[0].data(); - expect(data).to.deep.equal({foo: {number: 1}}); - await customFirestore.terminate(); - }); - - it('ignores undefined in an array if ignoreUndefinedProperties is true', async () => { - const customFirestore = getTestDb({ - ignoreUndefinedProperties: true, - }); - - const snapshot = await customFirestore + it('throws on undefined in an array', async () => { + try { + await firestore .pipeline() .collection(randomCol.path) .limit(1) - .select(array([1, undefined, 3]).as('foo')) + .select(array([1, undefined]).as('foo')) .execute(); + expect.fail('The statement above was expected to throw.'); + } catch (e: unknown) { + const error = e as Error; + console.log(error.message); + expect(error.message).to.contain( + 'Value for argument "value" is not a valid array value. Cannot use "undefined" as a Firestore value', + ); + } + }); - const data = snapshot.results[0].data(); - expect(data).to.deep.equal({foo: [1, 3]}); - await customFirestore.terminate(); + it('ignores undefined in a map if ignoreUndefinedProperties is true', async () => { + const customFirestore = getTestDb({ + ignoreUndefinedProperties: true, }); - it('converts arrays and plain objects to functionValues if the customer intent is unspecified', async () => { - const snapshot = await firestore - .pipeline() - .collection(randomCol.path) - .sort(field('rating').descending()) - .limit(1) - .select( - 'title', - 'author', - 'genre', - 'rating', - 'published', - 'tags', - 'awards', - ) - .addFields( - array([ + const snapshot = await customFirestore + .pipeline() + .collection(randomCol.path) + .limit(1) + .select( + map({ + number: 1, + bad: undefined, + }).as('foo'), + ) + .execute(); + + const data = snapshot.results[0].data(); + expect(data).to.deep.equal({foo: {number: 1}}); + await customFirestore.terminate(); + }); + + it('ignores undefined in an array if ignoreUndefinedProperties is true', async () => { + const customFirestore = getTestDb({ + ignoreUndefinedProperties: true, + }); + + const snapshot = await customFirestore + .pipeline() + .collection(randomCol.path) + .limit(1) + .select(array([1, undefined, 3]).as('foo')) + .execute(); + + const data = snapshot.results[0].data(); + expect(data).to.deep.equal({foo: [1, 3]}); + await customFirestore.terminate(); + }); + + it('converts arrays and plain objects to functionValues if the customer intent is unspecified', async () => { + const snapshot = await firestore + .pipeline() + .collection(randomCol.path) + .sort(field('rating').descending()) + .limit(1) + .select( + 'title', + 'author', + 'genre', + 'rating', + 'published', + 'tags', + 'awards', + ) + .addFields( + array([ + 1, + 2, + field('genre'), + multiply('rating', 10), + [field('title')], + { + published: field('published'), + }, + ]).as('metadataArray'), + map({ + genre: field('genre'), + rating: multiply('rating', 10), + nestedArray: [field('title')], + nestedMap: { + published: field('published'), + }, + }).as('metadata'), + ) + .where( + and( + equal('metadataArray', [ 1, 2, field('genre'), @@ -891,4324 +906,4264 @@ const timestampDeltaMS = 3000; { published: field('published'), }, - ]).as('metadataArray'), - map({ + ]), + equal('metadata', { genre: field('genre'), rating: multiply('rating', 10), nestedArray: [field('title')], nestedMap: { published: field('published'), }, - }).as('metadata'), - ) - .where( - and( - equal('metadataArray', [ - 1, - 2, - field('genre'), - multiply('rating', 10), - [field('title')], - { - published: field('published'), - }, - ]), - equal('metadata', { - genre: field('genre'), - rating: multiply('rating', 10), - nestedArray: [field('title')], - nestedMap: { - published: field('published'), - }, - }), - ), - ) - .execute(); - - expect(snapshot.results.length).to.equal(1); - - expectResults(snapshot, { - title: 'The Lord of the Rings', - author: 'J.R.R. Tolkien', + }), + ), + ) + .execute(); + + expect(snapshot.results.length).to.equal(1); + + expectResults(snapshot, { + title: 'The Lord of the Rings', + author: 'J.R.R. Tolkien', + genre: 'Fantasy', + published: 1954, + rating: 4.7, + tags: ['adventure', 'magic', 'epic'], + awards: {hugo: false, nebula: false}, + metadataArray: [ + 1, + 2, + 'Fantasy', + 47, + ['The Lord of the Rings'], + { + published: 1954, + }, + ], + metadata: { genre: 'Fantasy', - published: 1954, - rating: 4.7, - tags: ['adventure', 'magic', 'epic'], - awards: {hugo: false, nebula: false}, - metadataArray: [ - 1, - 2, - 'Fantasy', - 47, - ['The Lord of the Rings'], - { - published: 1954, - }, - ], - metadata: { - genre: 'Fantasy', - rating: 47, - nestedArray: ['The Lord of the Rings'], - nestedMap: { - published: 1954, - }, + rating: 47, + nestedArray: ['The Lord of the Rings'], + nestedMap: { + published: 1954, }, - }); + }, }); }); + }); - describe('stages', () => { - describe('aggregate stage', () => { - it('supports aggregate', async () => { - let snapshot = await firestore - .pipeline() - .collection(randomCol.path) - .aggregate(countAll().as('count')) - .execute(); - expectResults(snapshot, {count: 10}); - - snapshot = await firestore - .pipeline() - .collection(randomCol.path) - .where(equal('genre', 'Science Fiction')) - .aggregate( - countAll().as('count'), - average('rating').as('avgRating'), - maximum('rating').as('maxRating'), - sum('rating').as('sumRating'), - ) - .execute(); - expectResults(snapshot, { - count: 2, - avgRating: 4.4, - maxRating: 4.6, - sumRating: 8.8, - }); - }); + describe('stages', () => { + describe('aggregate stage', () => { + it('supports aggregate', async () => { + let snapshot = await firestore + .pipeline() + .collection(randomCol.path) + .aggregate(countAll().as('count')) + .execute(); + expectResults(snapshot, {count: 10}); - it('throws on duplicate aliases', async () => { - expect(() => - firestore - .pipeline() - .collection(randomCol.path) - .aggregate(countAll().as('count'), count('foo').as('count')), - ).to.throw("Duplicate alias or field 'count'"); + snapshot = await firestore + .pipeline() + .collection(randomCol.path) + .where(equal('genre', 'Science Fiction')) + .aggregate( + countAll().as('count'), + average('rating').as('avgRating'), + maximum('rating').as('maxRating'), + sum('rating').as('sumRating'), + ) + .execute(); + expectResults(snapshot, { + count: 2, + avgRating: 4.4, + maxRating: 4.6, + sumRating: 8.8, }); + }); - it('throws on duplicate group aliases', async () => { - expect(() => - firestore - .pipeline() - .collection(randomCol.path) - .aggregate({ - accumulators: [countAll().as('count')], - groups: ['bax', field('bar').as('bax')], - }), - ).to.throw("Duplicate alias or field 'bax'"); - }); + it('throws on duplicate aliases', async () => { + expect(() => + firestore + .pipeline() + .collection(randomCol.path) + .aggregate(countAll().as('count'), count('foo').as('count')), + ).to.throw("Duplicate alias or field 'count'"); + }); - it('supports aggregate options', async () => { - let snapshot = await firestore + it('throws on duplicate group aliases', async () => { + expect(() => + firestore .pipeline() .collection(randomCol.path) .aggregate({ accumulators: [countAll().as('count')], - }) - .execute(); - expectResults(snapshot, {count: 10}); + groups: ['bax', field('bar').as('bax')], + }), + ).to.throw("Duplicate alias or field 'bax'"); + }); - snapshot = await firestore - .pipeline() - .collection(randomCol.path) - .where(equal('genre', 'Science Fiction')) - .aggregate( - countAll().as('count'), - average('rating').as('avgRating'), - maximum('rating').as('maxRating'), - sum('rating').as('sumRating'), - ) - .execute(); - expectResults(snapshot, { - count: 2, - avgRating: 4.4, - maxRating: 4.6, - sumRating: 8.8, - }); - }); + it('supports aggregate options', async () => { + let snapshot = await firestore + .pipeline() + .collection(randomCol.path) + .aggregate({ + accumulators: [countAll().as('count')], + }) + .execute(); + expectResults(snapshot, {count: 10}); - it('rejects groups without accumulators', async () => { - void expect(async () => { - await firestore - .pipeline() - .collection(randomCol.path) - .where(lessThan('published', 1900)) - .aggregate({ - accumulators: [], - groups: ['genre'], - }) - .execute(); - }).to.throw; + snapshot = await firestore + .pipeline() + .collection(randomCol.path) + .where(equal('genre', 'Science Fiction')) + .aggregate( + countAll().as('count'), + average('rating').as('avgRating'), + maximum('rating').as('maxRating'), + sum('rating').as('sumRating'), + ) + .execute(); + expectResults(snapshot, { + count: 2, + avgRating: 4.4, + maxRating: 4.6, + sumRating: 8.8, }); + }); - it('returns group and accumulate results', async () => { - const snapshot = await firestore + it('rejects groups without accumulators', async () => { + void expect(async () => { + await firestore .pipeline() .collection(randomCol.path) - .where(lessThan(field('published'), 1984)) + .where(lessThan('published', 1900)) .aggregate({ - accumulators: [average('rating').as('avgRating')], + accumulators: [], groups: ['genre'], }) - .where(greaterThan('avgRating', 4.3)) - .sort(field('avgRating').descending()) - .execute(); - expectResults( - snapshot, - {avgRating: 4.7, genre: 'Fantasy'}, - {avgRating: 4.5, genre: 'Romance'}, - {avgRating: 4.4, genre: 'Science Fiction'}, - ); - }); - - it('returns min, max, count, and countAll accumulations', async () => { - const snapshot = await firestore - .pipeline() - .collection(randomCol.path) - .aggregate( - count('cost').as('booksWithCost'), - countAll().as('count'), - maximum('rating').as('maxRating'), - minimum('published').as('minPublished'), - ) - .execute(); - expectResults(snapshot, { - booksWithCost: 1, - count: 10, - maxRating: 4.7, - minPublished: 1813, - }); - }); - - it('returns countif accumulation', async () => { - let snapshot = await firestore - .pipeline() - .collection(randomCol.path) - .aggregate(countIf(field('rating').greaterThan(4.3)).as('count')) .execute(); - const expectedResults = { - count: 3, - }; - expectResults(snapshot, expectedResults); + }).to.throw; + }); - snapshot = await firestore - .pipeline() - .collection(randomCol.path) - .aggregate(field('rating').greaterThan(4.3).countIf().as('count')) - .execute(); - expectResults(snapshot, expectedResults); - }); + it('returns group and accumulate results', async () => { + const snapshot = await firestore + .pipeline() + .collection(randomCol.path) + .where(lessThan(field('published'), 1984)) + .aggregate({ + accumulators: [average('rating').as('avgRating')], + groups: ['genre'], + }) + .where(greaterThan('avgRating', 4.3)) + .sort(field('avgRating').descending()) + .execute(); + expectResults( + snapshot, + {avgRating: 4.7, genre: 'Fantasy'}, + {avgRating: 4.5, genre: 'Romance'}, + {avgRating: 4.4, genre: 'Science Fiction'}, + ); + }); - it('returns countDistinct accumulation', async () => { - const snapshot = await firestore - .pipeline() - .collection(randomCol.path) - .aggregate(countDistinct('genre').as('distinctGenres')) - .execute(); - expectResults(snapshot, {distinctGenres: 8}); + it('returns min, max, count, and countAll accumulations', async () => { + const snapshot = await firestore + .pipeline() + .collection(randomCol.path) + .aggregate( + count('cost').as('booksWithCost'), + countAll().as('count'), + maximum('rating').as('maxRating'), + minimum('published').as('minPublished'), + ) + .execute(); + expectResults(snapshot, { + booksWithCost: 1, + count: 10, + maxRating: 4.7, + minPublished: 1813, }); }); - describe('distinct stage', () => { - it('returns distinct values as expected', async () => { - const snapshot = await firestore - .pipeline() - .collection(randomCol.path) - .distinct('genre', 'author') - .sort(field('genre').ascending(), field('author').ascending()) - .execute(); - expectResults( - snapshot, - {genre: 'Dystopian', author: 'George Orwell'}, - {genre: 'Dystopian', author: 'Margaret Atwood'}, - {genre: 'Fantasy', author: 'J.R.R. Tolkien'}, - {genre: 'Magical Realism', author: 'Gabriel García Márquez'}, - {genre: 'Modernist', author: 'F. Scott Fitzgerald'}, - {genre: 'Psychological Thriller', author: 'Fyodor Dostoevsky'}, - {genre: 'Romance', author: 'Jane Austen'}, - {genre: 'Science Fiction', author: 'Douglas Adams'}, - {genre: 'Science Fiction', author: 'Frank Herbert'}, - {genre: 'Southern Gothic', author: 'Harper Lee'}, - ); - }); + it('returns countif accumulation', async () => { + let snapshot = await firestore + .pipeline() + .collection(randomCol.path) + .aggregate(countIf(field('rating').greaterThan(4.3)).as('count')) + .execute(); + const expectedResults = { + count: 3, + }; + expectResults(snapshot, expectedResults); - it('supports options', async () => { - const snapshot = await firestore - .pipeline() - .collection(randomCol.path) - .distinct('genre', 'author') - .sort({ - orderings: [ - field('genre').ascending(), - field('author').ascending(), - ], - }) - .execute(); - expectResults( - snapshot, - {genre: 'Dystopian', author: 'George Orwell'}, - {genre: 'Dystopian', author: 'Margaret Atwood'}, - {genre: 'Fantasy', author: 'J.R.R. Tolkien'}, - {genre: 'Magical Realism', author: 'Gabriel García Márquez'}, - {genre: 'Modernist', author: 'F. Scott Fitzgerald'}, - {genre: 'Psychological Thriller', author: 'Fyodor Dostoevsky'}, - {genre: 'Romance', author: 'Jane Austen'}, - {genre: 'Science Fiction', author: 'Douglas Adams'}, - {genre: 'Science Fiction', author: 'Frank Herbert'}, - {genre: 'Southern Gothic', author: 'Harper Lee'}, - ); - }); + snapshot = await firestore + .pipeline() + .collection(randomCol.path) + .aggregate(field('rating').greaterThan(4.3).countIf().as('count')) + .execute(); + expectResults(snapshot, expectedResults); }); - describe('select stage', () => { - it('can select fields', async () => { - const snapshot = await firestore - .pipeline() - .collection(randomCol.path) - .select('title', 'author') - .sort(field('author').ascending()) - .execute(); - expectResults( - snapshot, - { - title: "The Hitchhiker's Guide to the Galaxy", - author: 'Douglas Adams', - }, - {title: 'The Great Gatsby', author: 'F. Scott Fitzgerald'}, - {title: 'Dune', author: 'Frank Herbert'}, - {title: 'Crime and Punishment', author: 'Fyodor Dostoevsky'}, - { - title: 'One Hundred Years of Solitude', - author: 'Gabriel García Márquez', - }, - {title: '1984', author: 'George Orwell'}, - {title: 'To Kill a Mockingbird', author: 'Harper Lee'}, - {title: 'The Lord of the Rings', author: 'J.R.R. Tolkien'}, - {title: 'Pride and Prejudice', author: 'Jane Austen'}, - {title: "The Handmaid's Tale", author: 'Margaret Atwood'}, - ); - }); + it('returns countDistinct accumulation', async () => { + const snapshot = await firestore + .pipeline() + .collection(randomCol.path) + .aggregate(countDistinct('genre').as('distinctGenres')) + .execute(); + expectResults(snapshot, {distinctGenres: 8}); + }); + }); - it('throws on duplicate aliases', async () => { - expect(() => { - firestore - .pipeline() - .collection(randomCol.path) - .limit(1) - .select(constant(1).as('foo'), constant(2).as('foo')); - }).to.throw("Duplicate alias or field 'foo'"); - }); + describe('distinct stage', () => { + it('returns distinct values as expected', async () => { + const snapshot = await firestore + .pipeline() + .collection(randomCol.path) + .distinct('genre', 'author') + .sort(field('genre').ascending(), field('author').ascending()) + .execute(); + expectResults( + snapshot, + {genre: 'Dystopian', author: 'George Orwell'}, + {genre: 'Dystopian', author: 'Margaret Atwood'}, + {genre: 'Fantasy', author: 'J.R.R. Tolkien'}, + {genre: 'Magical Realism', author: 'Gabriel García Márquez'}, + {genre: 'Modernist', author: 'F. Scott Fitzgerald'}, + {genre: 'Psychological Thriller', author: 'Fyodor Dostoevsky'}, + {genre: 'Romance', author: 'Jane Austen'}, + {genre: 'Science Fiction', author: 'Douglas Adams'}, + {genre: 'Science Fiction', author: 'Frank Herbert'}, + {genre: 'Southern Gothic', author: 'Harper Lee'}, + ); + }); - it('supports options', async () => { - const snapshot = await firestore - .pipeline() - .collection(randomCol.path) - .select({selections: ['title', field('author').as('auth0r')]}) - .sort(field('auth0r').ascending()) - .limit(2) - .execute(); - expectResults( - snapshot, - { - title: "The Hitchhiker's Guide to the Galaxy", - auth0r: 'Douglas Adams', - }, - {title: 'The Great Gatsby', auth0r: 'F. Scott Fitzgerald'}, - ); - }); - }); - - describe('addField stage', () => { - it('can add fields', async () => { - const snapshot = await firestore - .pipeline() - .collection(randomCol.path) - .select('title', 'author') - .addFields(constant('bar').as('foo')) - .sort(field('author').ascending()) - .execute(); - expectResults( - snapshot, - { - title: "The Hitchhiker's Guide to the Galaxy", - author: 'Douglas Adams', - foo: 'bar', - }, - { - title: 'The Great Gatsby', - author: 'F. Scott Fitzgerald', - foo: 'bar', - }, - {title: 'Dune', author: 'Frank Herbert', foo: 'bar'}, - { - title: 'Crime and Punishment', - author: 'Fyodor Dostoevsky', - foo: 'bar', - }, - { - title: 'One Hundred Years of Solitude', - author: 'Gabriel García Márquez', - foo: 'bar', - }, - {title: '1984', author: 'George Orwell', foo: 'bar'}, - { - title: 'To Kill a Mockingbird', - author: 'Harper Lee', - foo: 'bar', - }, - { - title: 'The Lord of the Rings', - author: 'J.R.R. Tolkien', - foo: 'bar', - }, - {title: 'Pride and Prejudice', author: 'Jane Austen', foo: 'bar'}, - { - title: "The Handmaid's Tale", - author: 'Margaret Atwood', - foo: 'bar', - }, - ); - }); - - it('throws on duplicate aliases', async () => { - expect(() => - firestore - .pipeline() - .collection(randomCol.path) - .select('title', 'author') - .addFields(constant('bar').as('foo'), constant('baz').as('foo')) - .sort(field('author').ascending()), - ).to.throw("Duplicate alias or field 'foo'"); - }); - - it('supports options', async () => { - const snapshot = await firestore - .pipeline() - .collection(randomCol.path) - .select('title', 'author') - .addFields({ - fields: [constant('bar').as('foo')], - }) - .sort(field('author').ascending()) - .execute(); - expectResults( - snapshot, - { - title: "The Hitchhiker's Guide to the Galaxy", - author: 'Douglas Adams', - foo: 'bar', - }, - { - title: 'The Great Gatsby', - author: 'F. Scott Fitzgerald', - foo: 'bar', - }, - {title: 'Dune', author: 'Frank Herbert', foo: 'bar'}, - { - title: 'Crime and Punishment', - author: 'Fyodor Dostoevsky', - foo: 'bar', - }, - { - title: 'One Hundred Years of Solitude', - author: 'Gabriel García Márquez', - foo: 'bar', - }, - {title: '1984', author: 'George Orwell', foo: 'bar'}, - { - title: 'To Kill a Mockingbird', - author: 'Harper Lee', - foo: 'bar', - }, - { - title: 'The Lord of the Rings', - author: 'J.R.R. Tolkien', - foo: 'bar', - }, - {title: 'Pride and Prejudice', author: 'Jane Austen', foo: 'bar'}, - { - title: "The Handmaid's Tale", - author: 'Margaret Atwood', - foo: 'bar', - }, - ); - }); - }); - - describe('removeFields stage', () => { - it('can remove fields', async () => { - const snapshot = await firestore - .pipeline() - .collection(randomCol.path) - .select('title', 'author') - .sort(field('author').ascending()) - .removeFields(field('author')) - .execute(); - expectResults( - snapshot, - { - title: "The Hitchhiker's Guide to the Galaxy", - }, - { - title: 'The Great Gatsby', - }, - {title: 'Dune'}, - { - title: 'Crime and Punishment', - }, - { - title: 'One Hundred Years of Solitude', - }, - {title: '1984'}, - { - title: 'To Kill a Mockingbird', - }, - { - title: 'The Lord of the Rings', - }, - {title: 'Pride and Prejudice'}, - { - title: "The Handmaid's Tale", - }, - ); - }); - - it('supports options', async () => { - const snapshot = await firestore - .pipeline() - .collection(randomCol.path) - .select('title', 'author', 'genre') - .sort(field('author').ascending()) - .removeFields({ - fields: [field('author'), 'genre'], - }) - .execute(); - expectResults( - snapshot, - { - title: "The Hitchhiker's Guide to the Galaxy", - }, - { - title: 'The Great Gatsby', - }, - {title: 'Dune'}, - { - title: 'Crime and Punishment', - }, - { - title: 'One Hundred Years of Solitude', - }, - {title: '1984'}, - { - title: 'To Kill a Mockingbird', - }, - { - title: 'The Lord of the Rings', - }, - {title: 'Pride and Prejudice'}, - { - title: "The Handmaid's Tale", - }, - ); - }); - }); - - describe('findNearest stage', () => { - it('can find nearest', async () => { - const snapshot = await firestore - .pipeline() - .collection(randomCol.path) - .select('title', 'author') - .sort(field('author').ascending()) - .removeFields(field('author')) - .execute(); - expectResults( - snapshot, - { - title: "The Hitchhiker's Guide to the Galaxy", - }, - { - title: 'The Great Gatsby', - }, - {title: 'Dune'}, - { - title: 'Crime and Punishment', - }, - { - title: 'One Hundred Years of Solitude', - }, - {title: '1984'}, - { - title: 'To Kill a Mockingbird', - }, - { - title: 'The Lord of the Rings', - }, - {title: 'Pride and Prejudice'}, - { - title: "The Handmaid's Tale", - }, - ); - }); - - it('supports options', async () => { - const snapshot = await firestore - .pipeline() - .collection(randomCol.path) - .select('title', 'author', 'genre') - .sort(field('author').ascending()) - .removeFields({ - fields: [field('author'), 'genre'], - }) - .execute(); - expectResults( - snapshot, - { - title: "The Hitchhiker's Guide to the Galaxy", - }, - { - title: 'The Great Gatsby', - }, - {title: 'Dune'}, - { - title: 'Crime and Punishment', - }, - { - title: 'One Hundred Years of Solitude', - }, - {title: '1984'}, - { - title: 'To Kill a Mockingbird', - }, - { - title: 'The Lord of the Rings', - }, - {title: 'Pride and Prejudice'}, - { - title: "The Handmaid's Tale", - }, - ); - }); - }); - - describe('where stage', () => { - it('where with and (2 conditions)', async () => { - const snapshot = await firestore - .pipeline() - .collection(randomCol.path) - .where( - and( - greaterThan('rating', 4.5), - equalAny('genre', ['Science Fiction', 'Romance', 'Fantasy']), - ), - ) - .execute(); - expectResults(snapshot, 'book10', 'book4'); - }); - - it('where with and (3 conditions)', async () => { - const snapshot = await firestore - .pipeline() - .collection(randomCol.path) - .where( - and( - greaterThan('rating', 4.5), - equalAny('genre', ['Science Fiction', 'Romance', 'Fantasy']), - lessThan('published', 1965), - ), - ) - .execute(); - expectResults(snapshot, 'book4'); - }); - - it('where with or', async () => { - const snapshot = await firestore - .pipeline() - .collection(randomCol.path) - .where( - or( - equal('genre', 'Romance'), - equal('genre', 'Dystopian'), - equal('genre', 'Fantasy'), - ), - ) - .sort(ascending('title')) - .select('title') - .execute(); - expectResults( - snapshot, - {title: '1984'}, - {title: 'Pride and Prejudice'}, - {title: "The Handmaid's Tale"}, - {title: 'The Lord of the Rings'}, - ); - }); - - it('where with xor', async () => { - const snapshot = await firestore - .pipeline() - .collection(randomCol.path) - .where( - xor( - equal('genre', 'Romance'), - equal('genre', 'Dystopian'), - equal('genre', 'Fantasy'), - equal('published', 1949), - ), - ) - .select('title') - .execute(); - expectResults( - snapshot, - {title: 'Pride and Prejudice'}, - {title: 'The Lord of the Rings'}, - {title: "The Handmaid's Tale"}, - ); - }); - - it('supports options', async () => { - const snapshot = await firestore - .pipeline() - .collection(randomCol.path) - .where({ - condition: and( - greaterThan('rating', 4.5), - equalAny('genre', ['Science Fiction', 'Romance', 'Fantasy']), - ), - }) - .execute(); - expectResults(snapshot, 'book10', 'book4'); - }); - }); - - describe('sort, offset, and limit stages', () => { - it('supports sort, offset, and limits', async () => { - const snapshot = await firestore - .pipeline() - .collection(randomCol.path) - .sort(field('author').ascending()) - .offset(5) - .limit(3) - .select('title', 'author') - .execute(); - expectResults( - snapshot, - {title: '1984', author: 'George Orwell'}, - {title: 'To Kill a Mockingbird', author: 'Harper Lee'}, - {title: 'The Lord of the Rings', author: 'J.R.R. Tolkien'}, - ); - }); - - it('sort, offset, and limit stages support options', async () => { - const snapshot = await firestore - .pipeline() - .collection(randomCol.path) - .sort({ - orderings: [field('author').ascending()], - }) - .offset({offset: 5}) - .limit({limit: 3}) - .select('title', 'author') - .execute(); - expectResults( - snapshot, - {title: '1984', author: 'George Orwell'}, - {title: 'To Kill a Mockingbird', author: 'Harper Lee'}, - {title: 'The Lord of the Rings', author: 'J.R.R. Tolkien'}, - ); - }); - }); - - describe('error handling', () => { - it('error properties are propagated from the firestore backend', async () => { - try { - await firestore - .pipeline() - .collection(randomCol.path) - .rawStage('select', [ - // incorrect parameter type - field('title'), - ]) - .execute(); - - expect.fail('expected pipeline.execute() to throw'); - } catch (e: unknown) { - expect(e instanceof Error).to.be.true; - const err = e as ServiceError; - expect(err['code']).to.equal(3); - expect(typeof err['message']).to.equal('string'); - expect(typeof err['details']).to.equal('string'); - expect(typeof err['stack']).to.equal('string'); - expect(err['metadata'] instanceof Object).to.be.true; - - expect(err['message']).to.equal( - `${err.code} INVALID_ARGUMENT: ${err.details}`, - ); - } - }); - - it('can access explain stats in error condition', async () => { - try { - await firestore - .pipeline() - .collection(randomCol.path) - .sort(field('rating').ascending()) - .execute({ - explainOptions: { - mode: 'analyze', - }, - rawOptions: { - memory_limit: 1, - }, - }); - - expect.fail('expected pipeline.execute() to throw'); - } catch (e: unknown) { - const err = e as {[k: string]: unknown}; - expect(err instanceof Error).to.be.true; - - expect(err['code']).to.equal(8); - expect(typeof err['message']).to.equal('string'); - expect(typeof err['details']).to.equal('string'); - expect(typeof err['stack']).to.equal('string'); - expect(err['metadata'] instanceof Object).to.be.true; - - expect(err['message']).to.equal( - `${err.code} RESOURCE_EXHAUSTED: ${err.details}`, - ); - - expect('statusDetails' in err).to.be.true; - expect(Array.isArray(err['statusDetails'])).to.be.true; - - const statusDetails = err['statusDetails'] as Array; - - const foundExplainStats = statusDetails.find(x => { - return ( - 'type_url' in x && - x['type_url'] === - 'type.googleapis.com/google.firestore.v1.ExplainStats' - ); - }); - expect(foundExplainStats).to.not.be.undefined; - } - }); - }); - - describe('raw stage', () => { - it('can select fields', async () => { - const snapshot = await firestore - .pipeline() - .collection(randomCol.path) - .rawStage('select', [ - { - title: field('title'), - metadata: { - author: field('author'), - }, - }, - ]) - .sort(field('author').ascending()) - .limit(1) - .execute(); - expectResults(snapshot, { - metadata: { - author: 'Frank Herbert', - }, - title: 'Dune', - }); - }); - - it('can add fields', async () => { - const snapshot = await firestore - .pipeline() - .collection(randomCol.path) - .sort(field('author').ascending()) - .limit(1) - .select('title', 'author') - .rawStage('add_fields', [ - { - display: stringConcat('title', ' - ', field('author')), - }, - ]) - .execute(); - expectResults(snapshot, { - title: "The Hitchhiker's Guide to the Galaxy", - author: 'Douglas Adams', - display: "The Hitchhiker's Guide to the Galaxy - Douglas Adams", - }); - }); - - it('can filter with where', async () => { - const snapshot = await firestore - .pipeline() - .collection(randomCol.path) - .select('title', 'author') - .rawStage('where', [field('author').equal('Douglas Adams')]) - .execute(); - expectResults(snapshot, { - title: "The Hitchhiker's Guide to the Galaxy", - author: 'Douglas Adams', - }); - }); - - it('can limit, offset, and sort', async () => { - const snapshot = await firestore - .pipeline() - .collection(randomCol.path) - .select('title', 'author') - .rawStage('sort', [ - { - direction: 'ascending', - expression: field('author'), - }, - ]) - .rawStage('offset', [3]) - .rawStage('limit', [1]) - .execute(); - expectResults(snapshot, { - author: 'Fyodor Dostoevsky', - title: 'Crime and Punishment', - }); - }); - - it('can perform aggregate query', async () => { - const snapshot = await firestore - .pipeline() - .collection(randomCol.path) - .select('title', 'author', 'rating') - .rawStage('aggregate', [ - {averageRating: field('rating').average()}, - {}, - ]) - .execute(); - expectResults(snapshot, { - averageRating: 4.3100000000000005, - }); - }); - - it('can perform distinct query', async () => { - const snapshot = await firestore - .pipeline() - .collection(randomCol.path) - .select('title', 'author', 'rating') - .rawStage('distinct', [{rating: field('rating')}]) - .sort(field('rating').descending()) - .execute(); - expectResults( - snapshot, - { - rating: 4.7, - }, - { - rating: 4.6, - }, - { - rating: 4.5, - }, - { - rating: 4.3, - }, - { - rating: 4.2, - }, - { - rating: 4.1, - }, - { - rating: 4.0, - }, - ); - }); - - it('can perform FindNearest query', async () => { - const snapshot = await firestore - .pipeline() - .collection(randomCol) - .rawStage( - 'find_nearest', - [ - field('embedding'), - FieldValue.vector([10, 1, 2, 1, 1, 1, 1, 1, 1, 1]), - 'euclidean', - ], - { - distance_field: field('computedDistance'), - limit: 2, - }, - ) - .select('title', 'computedDistance') - .execute(); - expectResults( - snapshot, - { - title: "The Hitchhiker's Guide to the Galaxy", - computedDistance: 1, - }, - { - title: 'One Hundred Years of Solitude', - computedDistance: 12.041594578792296, - }, - ); - }); - }); - - describe('replaceWith stage', () => { - it('run pipeline with replaceWith field name', async () => { - const snapshot = await firestore - .pipeline() - .collection(randomCol.path) - .where(equal('title', "The Hitchhiker's Guide to the Galaxy")) - .replaceWith('awards') - .execute(); - expectResults(snapshot, { - hugo: true, - nebula: false, - others: {unknown: {year: 1980}}, - }); - }); - - it('run pipeline with replaceWith Expression result', async () => { - const snapshot = await firestore - .pipeline() - .collection(randomCol.path) - .where(equal('title', "The Hitchhiker's Guide to the Galaxy")) - .replaceWith( - map({ - foo: 'bar', - baz: { - title: field('title'), - }, - }), - ) - .execute(); - expectResults(snapshot, { - foo: 'bar', - baz: {title: "The Hitchhiker's Guide to the Galaxy"}, - }); - }); - - it('supports options', async () => { - const snapshot = await firestore - .pipeline() - .collection(randomCol.path) - .where(equal('title', "The Hitchhiker's Guide to the Galaxy")) - .replaceWith({map: 'awards'}) - .execute(); - expectResults(snapshot, { - hugo: true, - nebula: false, - others: {unknown: {year: 1980}}, - }); - }); - }); - - describe('sample stage', () => { - it('run pipeline with sample limit of 3', async () => { - const snapshot = await firestore - .pipeline() - .collection(randomCol.path) - .sample(3) - .execute(); - expect(snapshot.results.length).to.equal(3); - }); - - it('run pipeline with sample limit of {documents: 3}', async () => { - const snapshot = await firestore - .pipeline() - .collection(randomCol.path) - .sample({documents: 3}) - .execute(); - expect(snapshot.results.length).to.equal(3); - }); - - it('run pipeline with sample limit of {percentage: 0.6}', async () => { - let avgSize = 0; - const numIterations = 30; - for (let i = 0; i < numIterations; i++) { - const snapshot = await firestore - .pipeline() - .collection(randomCol.path) - .sample({percentage: 0.6}) - .execute(); - - avgSize += snapshot.results.length; - } - avgSize /= numIterations; - expect(avgSize).to.be.closeTo(6, 1); - }); - }); - - describe('union stage', () => { - it('run pipeline with union', async () => { - const snapshot = await firestore - .pipeline() - .collection(randomCol.path) - .union(firestore.pipeline().collection(randomCol.path)) - .sort(field(FieldPath.documentId()).ascending()) - .execute(); - expectResults( - snapshot, - 'book1', - 'book1', - 'book10', - 'book10', - 'book2', - 'book2', - 'book3', - 'book3', - 'book4', - 'book4', - 'book5', - 'book5', - 'book6', - 'book6', - 'book7', - 'book7', - 'book8', - 'book8', - 'book9', - 'book9', - ); - }); - - it('supports options', async () => { - const snapshot = await firestore - .pipeline() - .collection(randomCol.path) - .union({other: firestore.pipeline().collection(randomCol.path)}) - .sort(field(FieldPath.documentId()).ascending()) - .execute(); - expectResults( - snapshot, - 'book1', - 'book1', - 'book10', - 'book10', - 'book2', - 'book2', - 'book3', - 'book3', - 'book4', - 'book4', - 'book5', - 'book5', - 'book6', - 'book6', - 'book7', - 'book7', - 'book8', - 'book8', - 'book9', - 'book9', - ); - }); - }); - - describe('unnest stage', () => { - it('run pipeline with unnest', async () => { - const snapshot = await firestore - .pipeline() - .collection(randomCol.path) - .where(equal('title', "The Hitchhiker's Guide to the Galaxy")) - .unnest(field('tags').as('tag')) - .select( - 'title', - 'author', - 'genre', - 'published', - 'rating', - 'tags', - 'tag', - 'awards', - 'nestedField', - ) - .execute(); - expectResults( - snapshot, - { - title: "The Hitchhiker's Guide to the Galaxy", - author: 'Douglas Adams', - genre: 'Science Fiction', - published: 1979, - rating: 4.2, - tags: ['comedy', 'space', 'adventure'], - tag: 'comedy', - awards: { - hugo: true, - nebula: false, - others: {unknown: {year: 1980}}, - }, - nestedField: {'level.1': {'level.2': true}}, - }, - { - title: "The Hitchhiker's Guide to the Galaxy", - author: 'Douglas Adams', - genre: 'Science Fiction', - published: 1979, - rating: 4.2, - tags: ['comedy', 'space', 'adventure'], - tag: 'space', - awards: { - hugo: true, - nebula: false, - others: {unknown: {year: 1980}}, - }, - nestedField: {'level.1': {'level.2': true}}, - }, - { - title: "The Hitchhiker's Guide to the Galaxy", - author: 'Douglas Adams', - genre: 'Science Fiction', - published: 1979, - rating: 4.2, - tags: ['comedy', 'space', 'adventure'], - tag: 'adventure', - awards: { - hugo: true, - nebula: false, - others: {unknown: {year: 1980}}, - }, - nestedField: {'level.1': {'level.2': true}}, - }, - ); - }); - - it('unnest with index field', async () => { - const snapshot = await firestore - .pipeline() - .collection(randomCol.path) - .where(equal('title', "The Hitchhiker's Guide to the Galaxy")) - .unnest(field('tags').as('tag'), 'tagsIndex') - .select( - 'title', - 'author', - 'genre', - 'published', - 'rating', - 'tags', - 'tag', - 'awards', - 'nestedField', - 'tagsIndex', - ) - .execute(); - expectResults( - snapshot, - { - title: "The Hitchhiker's Guide to the Galaxy", - author: 'Douglas Adams', - genre: 'Science Fiction', - published: 1979, - rating: 4.2, - tags: ['comedy', 'space', 'adventure'], - tag: 'comedy', - awards: { - hugo: true, - nebula: false, - others: {unknown: {year: 1980}}, - }, - nestedField: {'level.1': {'level.2': true}}, - tagsIndex: 0, - }, - { - title: "The Hitchhiker's Guide to the Galaxy", - author: 'Douglas Adams', - genre: 'Science Fiction', - published: 1979, - rating: 4.2, - tags: ['comedy', 'space', 'adventure'], - tag: 'space', - awards: { - hugo: true, - nebula: false, - others: {unknown: {year: 1980}}, - }, - nestedField: {'level.1': {'level.2': true}}, - tagsIndex: 1, - }, - { - title: "The Hitchhiker's Guide to the Galaxy", - author: 'Douglas Adams', - genre: 'Science Fiction', - published: 1979, - rating: 4.2, - tags: ['comedy', 'space', 'adventure'], - tag: 'adventure', - awards: { - hugo: true, - nebula: false, - others: {unknown: {year: 1980}}, - }, - nestedField: {'level.1': {'level.2': true}}, - tagsIndex: 2, - }, - ); - }); - - it('unnest an expr', async () => { - const snapshot = await firestore - .pipeline() - .collection(randomCol.path) - .where(equal('title', "The Hitchhiker's Guide to the Galaxy")) - .unnest(array([1, 2, 3]).as('copy')) - .select( - 'title', - 'author', - 'genre', - 'published', - 'rating', - 'tags', - 'copy', - 'awards', - 'nestedField', - ) - .execute(); - expectResults( - snapshot, - { - title: "The Hitchhiker's Guide to the Galaxy", - author: 'Douglas Adams', - genre: 'Science Fiction', - published: 1979, - rating: 4.2, - tags: ['comedy', 'space', 'adventure'], - copy: 1, - awards: { - hugo: true, - nebula: false, - others: {unknown: {year: 1980}}, - }, - nestedField: {'level.1': {'level.2': true}}, - }, - { - title: "The Hitchhiker's Guide to the Galaxy", - author: 'Douglas Adams', - genre: 'Science Fiction', - published: 1979, - rating: 4.2, - tags: ['comedy', 'space', 'adventure'], - copy: 2, - awards: { - hugo: true, - nebula: false, - others: {unknown: {year: 1980}}, - }, - nestedField: {'level.1': {'level.2': true}}, - }, - { - title: "The Hitchhiker's Guide to the Galaxy", - author: 'Douglas Adams', - genre: 'Science Fiction', - published: 1979, - rating: 4.2, - tags: ['comedy', 'space', 'adventure'], - copy: 3, - awards: { - hugo: true, - nebula: false, - others: {unknown: {year: 1980}}, - }, - nestedField: {'level.1': {'level.2': true}}, - }, - ); - }); - - it('supports options', async () => { - const snapshot = await firestore - .pipeline() - .collection(randomCol.path) - .where(equal('title', "The Hitchhiker's Guide to the Galaxy")) - .unnest({ - selectable: field('tags').as('tag'), - indexField: 'tagsIndex', - }) - .select( - 'title', - 'author', - 'genre', - 'published', - 'rating', - 'tags', - 'tag', - 'awards', - 'nestedField', - 'tagsIndex', - ) - .execute(); - expectResults( - snapshot, - { - title: "The Hitchhiker's Guide to the Galaxy", - author: 'Douglas Adams', - genre: 'Science Fiction', - published: 1979, - rating: 4.2, - tags: ['comedy', 'space', 'adventure'], - tag: 'comedy', - awards: { - hugo: true, - nebula: false, - others: {unknown: {year: 1980}}, - }, - nestedField: {'level.1': {'level.2': true}}, - tagsIndex: 0, - }, - { - title: "The Hitchhiker's Guide to the Galaxy", - author: 'Douglas Adams', - genre: 'Science Fiction', - published: 1979, - rating: 4.2, - tags: ['comedy', 'space', 'adventure'], - tag: 'space', - awards: { - hugo: true, - nebula: false, - others: {unknown: {year: 1980}}, - }, - nestedField: {'level.1': {'level.2': true}}, - tagsIndex: 1, - }, - { - title: "The Hitchhiker's Guide to the Galaxy", - author: 'Douglas Adams', - genre: 'Science Fiction', - published: 1979, - rating: 4.2, - tags: ['comedy', 'space', 'adventure'], - tag: 'adventure', - awards: { - hugo: true, - nebula: false, - others: {unknown: {year: 1980}}, - }, - nestedField: {'level.1': {'level.2': true}}, - tagsIndex: 2, - }, - ); - }); - }); - - describe('findNearest stage', () => { - it('run pipeline with findNearest', async () => { - const measures: Array< - Pipelines.FindNearestStageOptions['distanceMeasure'] - > = ['euclidean', 'dot_product', 'cosine']; - for (const measure of measures) { - const snapshot = await firestore - .pipeline() - .collection(randomCol) - .findNearest({ - field: 'embedding', - vectorValue: FieldValue.vector([10, 1, 3, 1, 2, 1, 1, 1, 1, 1]), - limit: 3, - distanceMeasure: measure, - }) - .select('title') - .execute(); - expectResults( - snapshot, - { - title: "The Hitchhiker's Guide to the Galaxy", - }, - { - title: 'One Hundred Years of Solitude', - }, - { - title: "The Handmaid's Tale", - }, - ); - } - }); - - it('optionally returns the computed distance', async () => { - const snapshot = await firestore - .pipeline() - .collection(randomCol) - .findNearest({ - field: 'embedding', - vectorValue: FieldValue.vector([10, 1, 2, 1, 1, 1, 1, 1, 1, 1]), - limit: 2, - distanceMeasure: 'euclidean', - distanceField: 'computedDistance', - }) - .select('title', 'computedDistance') - .execute(); - expectResults( - snapshot, - { - title: "The Hitchhiker's Guide to the Galaxy", - computedDistance: 1, - }, - { - title: 'One Hundred Years of Solitude', - computedDistance: 12.041594578792296, - }, - ); - }); - }); - }); - - describe('function expressions', () => { - it('logical max works', async () => { - const snapshot = await firestore - .pipeline() - .collection(randomCol.path) - .select( - 'title', - logicalMaximum(constant(1960), field('published'), 1961).as( - 'published-safe', - ), - ) - .sort(field('title').ascending()) - .limit(3) - .execute(); - expectResults( - snapshot, - {title: '1984', 'published-safe': 1961}, - {title: 'Crime and Punishment', 'published-safe': 1961}, - {title: 'Dune', 'published-safe': 1965}, - ); - }); - - it('logical min works', async () => { - const snapshot = await firestore - .pipeline() - .collection(randomCol.path) - .select( - 'title', - logicalMinimum(constant(1960), field('published'), 1961).as( - 'published-safe', - ), - ) - .sort(field('title').ascending()) - .limit(3) - .execute(); - expectResults( - snapshot, - {title: '1984', 'published-safe': 1949}, - {title: 'Crime and Punishment', 'published-safe': 1866}, - {title: 'Dune', 'published-safe': 1960}, - ); - }); - - it('conditional works', async () => { - const snapshot = await firestore - .pipeline() - .collection(randomCol.path) - .select( - 'title', - conditional( - lessThan(field('published'), 1960), - constant(1960), - field('published'), - ).as('published-safe'), - field('rating') - .greaterThanOrEqual(4.5) - .conditional(constant('great'), constant('good')) - .as('rating'), - ) - .sort(field('title').ascending()) - .limit(3) - .execute(); - expectResults( - snapshot, - {title: '1984', 'published-safe': 1960, rating: 'good'}, - { - title: 'Crime and Punishment', - 'published-safe': 1960, - rating: 'good', - }, - {title: 'Dune', 'published-safe': 1965, rating: 'great'}, - ); - }); - - it('equalAny works', async () => { - const snapshot = await firestore - .pipeline() - .collection(randomCol.path) - .where(equalAny('published', [1979, 1999, 1967])) - .sort(descending('title')) - .select('title') - .execute(); - expectResults( - snapshot, - {title: "The Hitchhiker's Guide to the Galaxy"}, - {title: 'One Hundred Years of Solitude'}, - ); - }); - - it('notEqualAny works', async () => { - const snapshot = await firestore - .pipeline() - .collection(randomCol.path) - .where( - notEqualAny( - 'published', - [1965, 1925, 1949, 1960, 1866, 1985, 1954, 1967, 1979], - ), - ) - .select('title') - .execute(); - expectResults(snapshot, {title: 'Pride and Prejudice'}); - }); - - it('arrayContains works', async () => { - const snapshot = await firestore - .pipeline() - .collection(randomCol.path) - .where(arrayContains('tags', 'comedy')) - .select('title') - .execute(); - expectResults(snapshot, { - title: "The Hitchhiker's Guide to the Galaxy", - }); - }); - - it('arrayContainsAny works', async () => { - const snapshot = await firestore - .pipeline() - .collection(randomCol.path) - .where(arrayContainsAny('tags', ['comedy', 'classic'])) - .sort(descending('title')) - .select('title') - .execute(); - expectResults( - snapshot, - {title: "The Hitchhiker's Guide to the Galaxy"}, - {title: 'Pride and Prejudice'}, - ); - }); - - it('arrayContainsAll works', async () => { - const snapshot = await firestore - .pipeline() - .collection(randomCol.path) - .where(arrayContainsAll('tags', ['adventure', 'magic'])) - .select('title') - .execute(); - expectResults(snapshot, {title: 'The Lord of the Rings'}); - }); - - it('arrayLength works', async () => { - const snapshot = await firestore - .pipeline() - .collection(randomCol.path) - .select(arrayLength('tags').as('tagsCount')) - .where(equal('tagsCount', 3)) - .execute(); - expect(snapshot.results.length).to.equal(10); - }); - - it('testStrConcat', async () => { - const snapshot = await firestore - .pipeline() - .collection(randomCol.path) - .sort(ascending('author')) - .select( - field('author').stringConcat(' - ', field('title')).as('bookInfo'), - ) - .limit(1) - .execute(); - expectResults(snapshot, { - bookInfo: "Douglas Adams - The Hitchhiker's Guide to the Galaxy", - }); - }); - - it('testStartsWith', async () => { - const snapshot = await firestore - .pipeline() - .collection(randomCol.path) - .where(startsWith('title', 'The')) - .select('title') - .sort(field('title').ascending()) - .execute(); - expectResults( - snapshot, - {title: 'The Great Gatsby'}, - {title: "The Handmaid's Tale"}, - {title: "The Hitchhiker's Guide to the Galaxy"}, - {title: 'The Lord of the Rings'}, - ); - }); - - it('testEndsWith', async () => { - const snapshot = await firestore - .pipeline() - .collection(randomCol.path) - .where(endsWith('title', 'y')) - .select('title') - .sort(field('title').descending()) - .execute(); - expectResults( - snapshot, - {title: "The Hitchhiker's Guide to the Galaxy"}, - {title: 'The Great Gatsby'}, - ); - }); - - it('testStrContains', async () => { - const snapshot = await firestore - .pipeline() - .collection(randomCol.path) - .where(stringContains('title', "'s")) - .select('title') - .sort(field('title').ascending()) - .execute(); - expectResults( - snapshot, - {title: "The Handmaid's Tale"}, - {title: "The Hitchhiker's Guide to the Galaxy"}, - ); - }); - - it('testLength', async () => { - const snapshot = await firestore - .pipeline() - .collection(randomCol.path) - .select(charLength('title').as('titleLength'), field('title')) - .where(greaterThan('titleLength', 20)) - .sort(field('title').ascending()) - .execute(); - - expectResults( - snapshot, - - { - titleLength: 29, - title: 'One Hundred Years of Solitude', - }, - { - titleLength: 36, - title: "The Hitchhiker's Guide to the Galaxy", - }, - { - titleLength: 21, - title: 'The Lord of the Rings', - }, - { - titleLength: 21, - title: 'To Kill a Mockingbird', - }, - ); - }); - - it('testLike', async () => { - const snapshot = await firestore - .pipeline() - .collection(randomCol.path) - .where(like('title', '%Guide%')) - .select('title') - .execute(); - expectResults(snapshot, { - title: "The Hitchhiker's Guide to the Galaxy", - }); - }); - - it('testRegexContains', async () => { - const snapshot = await firestore - .pipeline() - .collection(randomCol.path) - .where(regexContains('title', '(?i)(the|of)')) - .execute(); - expect(snapshot.results.length).to.equal(5); - }); - - it('testRegexMatches', async () => { - const snapshot = await firestore - .pipeline() - .collection(randomCol.path) - .where(regexMatch('title', '.*(?i)(the|of).*')) - .execute(); - expect(snapshot.results.length).to.equal(5); - }); - - it('testArithmeticOperations', async () => { - const snapshot = await firestore - .pipeline() - .collection(randomCol.path) - .where(equal('title', 'To Kill a Mockingbird')) - .select( - add(field('rating'), 1).as('ratingPlusOne'), - subtract(field('published'), 1900).as('yearsSince1900'), - field('rating').multiply(10).as('ratingTimesTen'), - divide('rating', 2).as('ratingDividedByTwo'), - multiply('rating', 20).as('ratingTimes20'), - add('rating', 3).as('ratingPlus3'), - mod('rating', 2).as('ratingMod2'), - ) - .limit(1) - .execute(); - expectResults(snapshot, { - ratingPlusOne: 5.2, - yearsSince1900: 60, - ratingTimesTen: 42, - ratingDividedByTwo: 2.1, - ratingTimes20: 84, - ratingPlus3: 7.2, - ratingMod2: 0.20000000000000018, - }); - }); - - it('testComparisonOperators', async () => { - const snapshot = await firestore - .pipeline() - .collection(randomCol.path) - .where( - and( - greaterThan('rating', 4.2), - lessThanOrEqual(field('rating'), 4.5), - notEqual('genre', 'Science Fiction'), - ), - ) - .select('rating', 'title') - .sort(field('title').ascending()) - .execute(); - expectResults( - snapshot, - {rating: 4.3, title: 'Crime and Punishment'}, - { - rating: 4.3, - title: 'One Hundred Years of Solitude', - }, - {rating: 4.5, title: 'Pride and Prejudice'}, - ); - }); - - it('testLogicalOperators', async () => { + it('supports options', async () => { const snapshot = await firestore .pipeline() .collection(randomCol.path) - .where( - or( - and( - greaterThan('rating', 4.5), - equal('genre', 'Science Fiction'), - ), - lessThan('published', 1900), - ), - ) - .select('title') - .sort(field('title').ascending()) + .distinct('genre', 'author') + .sort({ + orderings: [ + field('genre').ascending(), + field('author').ascending(), + ], + }) .execute(); expectResults( snapshot, - {title: 'Crime and Punishment'}, - {title: 'Dune'}, - {title: 'Pride and Prejudice'}, + {genre: 'Dystopian', author: 'George Orwell'}, + {genre: 'Dystopian', author: 'Margaret Atwood'}, + {genre: 'Fantasy', author: 'J.R.R. Tolkien'}, + {genre: 'Magical Realism', author: 'Gabriel García Márquez'}, + {genre: 'Modernist', author: 'F. Scott Fitzgerald'}, + {genre: 'Psychological Thriller', author: 'Fyodor Dostoevsky'}, + {genre: 'Romance', author: 'Jane Austen'}, + {genre: 'Science Fiction', author: 'Douglas Adams'}, + {genre: 'Science Fiction', author: 'Frank Herbert'}, + {genre: 'Southern Gothic', author: 'Harper Lee'}, ); }); + }); - it('testChecks', async () => { - let snapshot = await firestore - .pipeline() - .collection(randomCol.path) - .sort(field('rating').descending()) - .limit(1) - .select( - equal('rating', null).as('ratingIsNull'), - equal('rating', NaN).as('ratingIsNaN'), - isError(divide(constant(1), constant(0))).as('isError'), - ifError(divide(constant(1), constant(0)), constant('was error')).as( - 'ifError', - ), - ifError( - divide(constant(1), constant(0)).greaterThan(1), - constant(true), - ) - .not() - .as('ifErrorBooleanExpression'), - isAbsent('foo').as('isAbsent'), - notEqual('title', null).as('titleIsNotNull'), - notEqual('cost', NaN).as('costIsNotNan'), - exists('fooBarBaz').as('fooBarBazExists'), - field('title').exists().as('titleExists'), - ) - .execute(); - expectResults(snapshot, { - ratingIsNull: false, - ratingIsNaN: false, - isError: true, - ifError: 'was error', - ifErrorBooleanExpression: false, - isAbsent: true, - titleIsNotNull: true, - costIsNotNan: false, - fooBarBazExists: false, - titleExists: true, - }); - - snapshot = await firestore - .pipeline() - .collection(randomCol.path) - .sort(field('rating').descending()) - .limit(1) - .select( - field('rating').equal(null).as('ratingIsNull'), - field('rating').equal(NaN).as('ratingIsNaN'), - divide(constant(1), constant(0)).isError().as('isError'), - divide(constant(1), constant(0)) - .ifError(constant('was error')) - .as('ifError'), - divide(constant(1), constant(0)) - .greaterThan(1) - .ifError(constant(true)) - .not() - .as('ifErrorBooleanExpression'), - field('foo').isAbsent().as('isAbsent'), - field('title').notEqual(null).as('titleIsNotNull'), - field('cost').notEqual(NaN).as('costIsNotNan'), - ) - .execute(); - expectResults(snapshot, { - ratingIsNull: false, - ratingIsNaN: false, - isError: true, - ifError: 'was error', - ifErrorBooleanExpression: false, - isAbsent: true, - titleIsNotNull: true, - costIsNotNan: false, - }); - }); - - it('testMapGet', async () => { + describe('select stage', () => { + it('can select fields', async () => { const snapshot = await firestore .pipeline() .collection(randomCol.path) - .sort(field('published').descending()) - .select( - field('awards').mapGet('hugo').as('hugoAward'), - field('awards').mapGet('others').as('others'), - field('title'), - ) - .where(equal('hugoAward', true)) + .select('title', 'author') + .sort(field('author').ascending()) .execute(); expectResults( snapshot, { - hugoAward: true, title: "The Hitchhiker's Guide to the Galaxy", - others: {unknown: {year: 1980}}, + author: 'Douglas Adams', }, - {hugoAward: true, title: 'Dune'}, - ); - }); - - it('testDistanceFunctions', async () => { - const sourceVector = FieldValue.vector([0.1, 0.1]); - const targetVector = FieldValue.vector([0.5, 0.8]); - let snapshot = await firestore - .pipeline() - .collection(randomCol.path) - .select( - cosineDistance(constant(sourceVector), targetVector).as( - 'cosineDistance', - ), - dotProduct(constant(sourceVector), targetVector).as( - 'dotProductDistance', - ), - euclideanDistance(constant(sourceVector), targetVector).as( - 'euclideanDistance', - ), - ) - .limit(1) - .execute(); - - expectResults(snapshot, { - cosineDistance: 0.02560880430538015, - dotProductDistance: 0.13, - euclideanDistance: 0.806225774829855, - }); - - snapshot = await firestore - .pipeline() - .collection(randomCol.path) - .select( - constant(sourceVector) - .cosineDistance(targetVector) - .as('cosineDistance'), - constant(sourceVector) - .dotProduct(targetVector) - .as('dotProductDistance'), - constant(sourceVector) - .euclideanDistance(targetVector) - .as('euclideanDistance'), - ) - .limit(1) - .execute(); - - expectResults(snapshot, { - cosineDistance: 0.02560880430538015, - dotProductDistance: 0.13, - euclideanDistance: 0.806225774829855, - }); - }); - - it('testVectorLength', async () => { - const snapshot = await firestore - .pipeline() - .collection(randomCol.path) - .limit(1) - .select( - vectorLength(constant(FieldValue.vector([1, 2, 3]))).as( - 'vectorLength', - ), - ) - .execute(); - expectResults(snapshot, { - vectorLength: 3, - }); - }); - - it('testNestedFields', async () => { - const snapshot = await firestore - .pipeline() - .collection(randomCol.path) - .where(equal('awards.hugo', true)) - .sort(descending('title')) - .select('title', 'awards.hugo') - .execute(); - expectResults( - snapshot, + {title: 'The Great Gatsby', author: 'F. Scott Fitzgerald'}, + {title: 'Dune', author: 'Frank Herbert'}, + {title: 'Crime and Punishment', author: 'Fyodor Dostoevsky'}, { - title: "The Hitchhiker's Guide to the Galaxy", - 'awards.hugo': true, + title: 'One Hundred Years of Solitude', + author: 'Gabriel García Márquez', }, - {title: 'Dune', 'awards.hugo': true}, + {title: '1984', author: 'George Orwell'}, + {title: 'To Kill a Mockingbird', author: 'Harper Lee'}, + {title: 'The Lord of the Rings', author: 'J.R.R. Tolkien'}, + {title: 'Pride and Prejudice', author: 'Jane Austen'}, + {title: "The Handmaid's Tale", author: 'Margaret Atwood'}, ); }); - it('test mapGet with field name including . notation', async () => { - const snapshot = await firestore - .pipeline() - .collection(randomCol.path) - .limit(1) - .replaceWith( - map({ - title: 'foo', - nested: { - level: { - '1': 'bar', - }, - 'level.1': { - 'level.2': 'baz', - }, - }, - }), - ) - .select( - 'title', - field('nested.level.1'), - mapGet('nested', 'level.1').mapGet('level.2').as('nested'), - ) - .execute(); - - expectResults(snapshot, { - title: 'foo', - 'nested.level.`1`': 'bar', - nested: 'baz', - }); - }); - - describe('genericFunction', () => { - it('add selectable', async () => { - const snapshot = await firestore - .pipeline() - .collection(randomCol.path) - .sort(descending('rating')) - .limit(1) - .select( - new FunctionExpression('add', [field('rating'), constant(1)]).as( - 'rating', - ), - ) - .execute(); - expectResults(snapshot, { - rating: 5.7, - }); - }); - - it('and (variadic) selectable', async () => { - const snapshot = await firestore - .pipeline() - .collection(randomCol.path) - .where( - new FunctionExpression('and', [ - field('rating').greaterThan(0), - field('title').charLength().lessThan(5), - field('tags').arrayContains('propaganda'), - ]).asBoolean(), - ) - .select('title') - .execute(); - expectResults(snapshot, { - title: '1984', - }); - }); - - it('array contains any', async () => { - const snapshot = await firestore - .pipeline() - .collection(randomCol.path) - .where( - new FunctionExpression('array_contains_any', [ - field('tags'), - array(['politics']), - ]).asBoolean(), - ) - .select('title') - .execute(); - expectResults(snapshot, { - title: 'Dune', - }); - }); - - it('countif aggregate', async () => { - const snapshot = await firestore - .pipeline() - .collection(randomCol.path) - .aggregate( - new AggregateFunction('count_if', [ - field('rating').greaterThanOrEqual(4.5), - ]).as('countOfBest'), - ) - .execute(); - expectResults(snapshot, { - countOfBest: 3, - }); - }); - - it('sort by char_len', async () => { - const snapshot = await firestore - .pipeline() - .collection(randomCol.path) - .sort( - new FunctionExpression('char_length', [ - field('title'), - ]).ascending(), - descending('__name__'), - ) - .limit(3) - .select('title') - .execute(); - expectResults( - snapshot, - { - title: '1984', - }, - { - title: 'Dune', - }, - { - title: 'The Great Gatsby', - }, - ); - }); - }); - - it('supports array', async () => { - const snapshot = await firestore - .pipeline() - .collection(randomCol.path) - .sort(field('rating').descending()) - .limit(1) - .select(array([1, 2, 3, 4]).as('metadata')) - .execute(); - expect(snapshot.results.length).to.equal(1); - expectResults(snapshot, { - metadata: [1, 2, 3, 4], - }); - }); - - it('evaluates expression in array', async () => { - const snapshot = await firestore - .pipeline() - .collection(randomCol.path) - .sort(field('rating').descending()) - .limit(1) - .select( - array([1, 2, field('genre'), multiply('rating', 10)]).as( - 'metadata', - ), - ) - .execute(); - expect(snapshot.results.length).to.equal(1); - expectResults(snapshot, { - metadata: [1, 2, 'Fantasy', 47], - }); - }); - - it('supports arrayGet', async () => { - let snapshot = await firestore - .pipeline() - .collection(randomCol.path) - .sort(field('rating').descending()) - .limit(3) - .select(arrayGet('tags', 0).as('firstTag')) - .execute(); - const expectedResults = [ - { - firstTag: 'adventure', - }, - { - firstTag: 'politics', - }, - { - firstTag: 'classic', - }, - ]; - expectResults(snapshot, ...expectedResults); - - snapshot = await firestore - .pipeline() - .collection(randomCol.path) - .sort(field('rating').descending()) - .limit(3) - .select(field('tags').arrayGet(0).as('firstTag')) - .execute(); - expectResults(snapshot, ...expectedResults); - }); - - it('supports map', async () => { - const snapshot = await firestore - .pipeline() - .collection(randomCol.path) - .sort(field('rating').descending()) - .limit(1) - .select( - map({ - foo: 'bar', - }).as('metadata'), - ) - .execute(); - - expect(snapshot.results.length).to.equal(1); - expectResults(snapshot, { - metadata: { - foo: 'bar', - }, - }); - }); - - it('evaluates expression in map', async () => { - const snapshot = await firestore - .pipeline() - .collection(randomCol.path) - .sort(field('rating').descending()) - .limit(1) - .select( - map({ - genre: field('genre'), - rating: field('rating').multiply(10), - }).as('metadata'), - ) - .execute(); - - expect(snapshot.results.length).to.equal(1); - expectResults(snapshot, { - metadata: { - genre: 'Fantasy', - rating: 47, - }, - }); - }); - - it('supports mapRemove', async () => { - let snapshot = await firestore - .pipeline() - .collection(randomCol.path) - .sort(field('rating').descending()) - .limit(1) - .select(mapRemove('awards', 'hugo').as('awards')) - .execute(); - expectResults(snapshot, { - awards: {nebula: false}, - }); - snapshot = await firestore - .pipeline() - .collection(randomCol.path) - .sort(field('rating').descending()) - .limit(1) - .select(field('awards').mapRemove('hugo').as('awards')) - .execute(); - expectResults(snapshot, { - awards: {nebula: false}, - }); - }); - - it('supports mapMerge', async () => { - let snapshot = await firestore + it('throws on duplicate aliases', async () => { + expect(() => { + firestore + .pipeline() + .collection(randomCol.path) + .limit(1) + .select(constant(1).as('foo'), constant(2).as('foo')); + }).to.throw("Duplicate alias or field 'foo'"); + }); + + it('supports options', async () => { + const snapshot = await firestore .pipeline() .collection(randomCol.path) - .sort(field('rating').descending()) - .limit(1) - .select(mapMerge('awards', {fakeAward: true}).as('awards')) + .select({selections: ['title', field('author').as('auth0r')]}) + .sort(field('auth0r').ascending()) + .limit(2) .execute(); - expectResults(snapshot, { - awards: {nebula: false, hugo: false, fakeAward: true}, - }); - snapshot = await firestore + expectResults( + snapshot, + { + title: "The Hitchhiker's Guide to the Galaxy", + auth0r: 'Douglas Adams', + }, + {title: 'The Great Gatsby', auth0r: 'F. Scott Fitzgerald'}, + ); + }); + }); + + describe('addField stage', () => { + it('can add fields', async () => { + const snapshot = await firestore .pipeline() .collection(randomCol.path) - .sort(field('rating').descending()) - .limit(1) - .select(field('awards').mapMerge({fakeAward: true}).as('awards')) + .select('title', 'author') + .addFields(constant('bar').as('foo')) + .sort(field('author').ascending()) .execute(); - expectResults(snapshot, { - awards: {nebula: false, hugo: false, fakeAward: true}, - }); + expectResults( + snapshot, + { + title: "The Hitchhiker's Guide to the Galaxy", + author: 'Douglas Adams', + foo: 'bar', + }, + { + title: 'The Great Gatsby', + author: 'F. Scott Fitzgerald', + foo: 'bar', + }, + {title: 'Dune', author: 'Frank Herbert', foo: 'bar'}, + { + title: 'Crime and Punishment', + author: 'Fyodor Dostoevsky', + foo: 'bar', + }, + { + title: 'One Hundred Years of Solitude', + author: 'Gabriel García Márquez', + foo: 'bar', + }, + {title: '1984', author: 'George Orwell', foo: 'bar'}, + { + title: 'To Kill a Mockingbird', + author: 'Harper Lee', + foo: 'bar', + }, + { + title: 'The Lord of the Rings', + author: 'J.R.R. Tolkien', + foo: 'bar', + }, + {title: 'Pride and Prejudice', author: 'Jane Austen', foo: 'bar'}, + { + title: "The Handmaid's Tale", + author: 'Margaret Atwood', + foo: 'bar', + }, + ); + }); + + it('throws on duplicate aliases', async () => { + expect(() => + firestore + .pipeline() + .collection(randomCol.path) + .select('title', 'author') + .addFields(constant('bar').as('foo'), constant('baz').as('foo')) + .sort(field('author').ascending()), + ).to.throw("Duplicate alias or field 'foo'"); }); - it('supports timestamp conversions', async () => { + it('supports options', async () => { const snapshot = await firestore .pipeline() .collection(randomCol.path) - .limit(1) - .select( - unixSecondsToTimestamp(constant(1741380235)).as( - 'unixSecondsToTimestamp', - ), - unixMillisToTimestamp(constant(1741380235123)).as( - 'unixMillisToTimestamp', - ), - unixMicrosToTimestamp(constant(1741380235123456)).as( - 'unixMicrosToTimestamp', - ), - timestampToUnixSeconds( - constant(new Timestamp(1741380235, 123456789)), - ).as('timestampToUnixSeconds'), - timestampToUnixMicros( - constant(new Timestamp(1741380235, 123456789)), - ).as('timestampToUnixMicros'), - timestampToUnixMillis( - constant(new Timestamp(1741380235, 123456789)), - ).as('timestampToUnixMillis'), - ) + .select('title', 'author') + .addFields({ + fields: [constant('bar').as('foo')], + }) + .sort(field('author').ascending()) .execute(); - expectResults(snapshot, { - unixMicrosToTimestamp: new Timestamp(1741380235, 123456000), - unixMillisToTimestamp: new Timestamp(1741380235, 123000000), - unixSecondsToTimestamp: new Timestamp(1741380235, 0), - timestampToUnixSeconds: 1741380235, - timestampToUnixMicros: 1741380235123456, - timestampToUnixMillis: 1741380235123, - }); + expectResults( + snapshot, + { + title: "The Hitchhiker's Guide to the Galaxy", + author: 'Douglas Adams', + foo: 'bar', + }, + { + title: 'The Great Gatsby', + author: 'F. Scott Fitzgerald', + foo: 'bar', + }, + {title: 'Dune', author: 'Frank Herbert', foo: 'bar'}, + { + title: 'Crime and Punishment', + author: 'Fyodor Dostoevsky', + foo: 'bar', + }, + { + title: 'One Hundred Years of Solitude', + author: 'Gabriel García Márquez', + foo: 'bar', + }, + {title: '1984', author: 'George Orwell', foo: 'bar'}, + { + title: 'To Kill a Mockingbird', + author: 'Harper Lee', + foo: 'bar', + }, + { + title: 'The Lord of the Rings', + author: 'J.R.R. Tolkien', + foo: 'bar', + }, + {title: 'Pride and Prejudice', author: 'Jane Austen', foo: 'bar'}, + { + title: "The Handmaid's Tale", + author: 'Margaret Atwood', + foo: 'bar', + }, + ); }); + }); - it('supports timestamp math', async () => { + describe('removeFields stage', () => { + it('can remove fields', async () => { const snapshot = await firestore .pipeline() .collection(randomCol.path) - .limit(1) - .select(constant(new Timestamp(1741380235, 0)).as('timestamp')) - .select( - timestampAdd('timestamp', 'day', 10).as('plus10days'), - timestampAdd('timestamp', 'hour', 10).as('plus10hours'), - timestampAdd('timestamp', 'minute', 10).as('plus10minutes'), - timestampAdd('timestamp', 'second', 10).as('plus10seconds'), - timestampAdd('timestamp', 'microsecond', 10).as('plus10micros'), - timestampAdd('timestamp', 'millisecond', 10).as('plus10millis'), - timestampSubtract('timestamp', 'day', 10).as('minus10days'), - timestampSubtract('timestamp', 'hour', 10).as('minus10hours'), - timestampSubtract('timestamp', 'minute', 10).as('minus10minutes'), - timestampSubtract('timestamp', 'second', 10).as('minus10seconds'), - timestampSubtract('timestamp', 'microsecond', 10).as( - 'minus10micros', - ), - timestampSubtract('timestamp', 'millisecond', 10).as( - 'minus10millis', - ), - ) + .select('title', 'author') + .sort(field('author').ascending()) + .removeFields(field('author')) .execute(); - expectResults(snapshot, { - plus10days: new Timestamp(1742244235, 0), - plus10hours: new Timestamp(1741416235, 0), - plus10minutes: new Timestamp(1741380835, 0), - plus10seconds: new Timestamp(1741380245, 0), - plus10micros: new Timestamp(1741380235, 10000), - plus10millis: new Timestamp(1741380235, 10000000), - minus10days: new Timestamp(1740516235, 0), - minus10hours: new Timestamp(1741344235, 0), - minus10minutes: new Timestamp(1741379635, 0), - minus10seconds: new Timestamp(1741380225, 0), - minus10micros: new Timestamp(1741380234, 999990000), - minus10millis: new Timestamp(1741380234, 990000000), - }); + expectResults( + snapshot, + { + title: "The Hitchhiker's Guide to the Galaxy", + }, + { + title: 'The Great Gatsby', + }, + {title: 'Dune'}, + { + title: 'Crime and Punishment', + }, + { + title: 'One Hundred Years of Solitude', + }, + {title: '1984'}, + { + title: 'To Kill a Mockingbird', + }, + { + title: 'The Lord of the Rings', + }, + {title: 'Pride and Prejudice'}, + { + title: "The Handmaid's Tale", + }, + ); }); - it('supports byteLength', async () => { + it('supports options', async () => { const snapshot = await firestore .pipeline() - .collection(randomCol) - .limit(1) - .select( - constant(new Uint8Array([1, 2, 3, 4, 5, 6, 7, 0])).as('bytes'), - ) - .select(byteLength('bytes').as('byteLength')) + .collection(randomCol.path) + .select('title', 'author', 'genre') + .sort(field('author').ascending()) + .removeFields({ + fields: [field('author'), 'genre'], + }) .execute(); - - expectResults(snapshot, { - byteLength: 8, - }); + expectResults( + snapshot, + { + title: "The Hitchhiker's Guide to the Galaxy", + }, + { + title: 'The Great Gatsby', + }, + {title: 'Dune'}, + { + title: 'Crime and Punishment', + }, + { + title: 'One Hundred Years of Solitude', + }, + {title: '1984'}, + { + title: 'To Kill a Mockingbird', + }, + { + title: 'The Lord of the Rings', + }, + {title: 'Pride and Prejudice'}, + { + title: "The Handmaid's Tale", + }, + ); }); + }); - it('supports not', async () => { + describe('findNearest stage', () => { + it('can find nearest', async () => { const snapshot = await firestore .pipeline() - .collection(randomCol) - .limit(1) - .select(constant(true).as('trueField')) - .select('trueField', not(equal('trueField', true)).as('falseField')) + .collection(randomCol.path) + .select('title', 'author') + .sort(field('author').ascending()) + .removeFields(field('author')) .execute(); - - expectResults(snapshot, { - trueField: true, - falseField: false, - }); + expectResults( + snapshot, + { + title: "The Hitchhiker's Guide to the Galaxy", + }, + { + title: 'The Great Gatsby', + }, + {title: 'Dune'}, + { + title: 'Crime and Punishment', + }, + { + title: 'One Hundred Years of Solitude', + }, + {title: '1984'}, + { + title: 'To Kill a Mockingbird', + }, + { + title: 'The Lord of the Rings', + }, + {title: 'Pride and Prejudice'}, + { + title: "The Handmaid's Tale", + }, + ); }); - it('can reverse an array', async () => { + it('supports options', async () => { const snapshot = await firestore .pipeline() .collection(randomCol.path) - .where(field('title').equal("The Hitchhiker's Guide to the Galaxy")) - .limit(1) - .select(field('tags').arrayReverse().as('reversedTags')) + .select('title', 'author', 'genre') + .sort(field('author').ascending()) + .removeFields({ + fields: [field('author'), 'genre'], + }) .execute(); - expectResults(snapshot, { - reversedTags: ['adventure', 'space', 'comedy'], - }); + expectResults( + snapshot, + { + title: "The Hitchhiker's Guide to the Galaxy", + }, + { + title: 'The Great Gatsby', + }, + {title: 'Dune'}, + { + title: 'Crime and Punishment', + }, + { + title: 'One Hundred Years of Solitude', + }, + {title: '1984'}, + { + title: 'To Kill a Mockingbird', + }, + { + title: 'The Lord of the Rings', + }, + {title: 'Pride and Prejudice'}, + { + title: "The Handmaid's Tale", + }, + ); }); + }); - it('can reverse an array with the top-level function', async () => { + describe('where stage', () => { + it('where with and (2 conditions)', async () => { const snapshot = await firestore .pipeline() .collection(randomCol.path) - .where(field('title').equal("The Hitchhiker's Guide to the Galaxy")) - .limit(1) - .select(arrayReverse('tags').as('reversedTags')) + .where( + and( + greaterThan('rating', 4.5), + equalAny('genre', ['Science Fiction', 'Romance', 'Fantasy']), + ), + ) .execute(); - expectResults(snapshot, { - reversedTags: ['adventure', 'space', 'comedy'], - }); + expectResults(snapshot, 'book10', 'book4'); }); - it('can compute the ceiling of a numeric value', async () => { + it('where with and (3 conditions)', async () => { const snapshot = await firestore .pipeline() .collection(randomCol.path) - .where(field('title').equal("The Hitchhiker's Guide to the Galaxy")) - .limit(1) - .select(field('rating').ceil().as('ceilingRating')) + .where( + and( + greaterThan('rating', 4.5), + equalAny('genre', ['Science Fiction', 'Romance', 'Fantasy']), + lessThan('published', 1965), + ), + ) .execute(); - expectResults(snapshot, { - ceilingRating: 5, - }); + expectResults(snapshot, 'book4'); }); - it('can compute the ceiling of a numeric value with the top-level function', async () => { + it('where with or', async () => { const snapshot = await firestore .pipeline() .collection(randomCol.path) - .where(field('title').equal("The Hitchhiker's Guide to the Galaxy")) - .limit(1) - .select(ceil('rating').as('ceilingRating')) + .where( + or( + equal('genre', 'Romance'), + equal('genre', 'Dystopian'), + equal('genre', 'Fantasy'), + ), + ) + .sort(ascending('title')) + .select('title') .execute(); - expectResults(snapshot, { - ceilingRating: 5, - }); + expectResults( + snapshot, + {title: '1984'}, + {title: 'Pride and Prejudice'}, + {title: "The Handmaid's Tale"}, + {title: 'The Lord of the Rings'}, + ); }); - it('can compute the floor of a numeric value', async () => { + it('where with xor', async () => { const snapshot = await firestore .pipeline() .collection(randomCol.path) - .where(field('title').equal("The Hitchhiker's Guide to the Galaxy")) - .limit(1) - .select(field('rating').floor().as('floorRating')) + .where( + xor( + equal('genre', 'Romance'), + equal('genre', 'Dystopian'), + equal('genre', 'Fantasy'), + equal('published', 1949), + ), + ) + .select('title') .execute(); - expectResults(snapshot, { - floorRating: 4, - }); + expectResults( + snapshot, + {title: 'Pride and Prejudice'}, + {title: 'The Lord of the Rings'}, + {title: "The Handmaid's Tale"}, + ); }); - it('can compute the floor of a numeric value with the top-level function', async () => { + it('supports options', async () => { const snapshot = await firestore .pipeline() .collection(randomCol.path) - .where(field('title').equal("The Hitchhiker's Guide to the Galaxy")) - .limit(1) - .select(floor('rating').as('floorRating')) + .where({ + condition: and( + greaterThan('rating', 4.5), + equalAny('genre', ['Science Fiction', 'Romance', 'Fantasy']), + ), + }) .execute(); - expectResults(snapshot, { - floorRating: 4, - }); + expectResults(snapshot, 'book10', 'book4'); }); + }); - it('can compute e to the power of a numeric value', async () => { + describe('sort, offset, and limit stages', () => { + it('supports sort, offset, and limits', async () => { const snapshot = await firestore .pipeline() .collection(randomCol.path) - .where(field('title').equal('The Lord of the Rings')) - .limit(1) - .select(field('rating').exp().as('expRating')) + .sort(field('author').ascending()) + .offset(5) + .limit(3) + .select('title', 'author') .execute(); - expect(snapshot.results[0].get('expRating')).to.be.approximately( - 109.94717245212352, - 0.00001, + expectResults( + snapshot, + {title: '1984', author: 'George Orwell'}, + {title: 'To Kill a Mockingbird', author: 'Harper Lee'}, + {title: 'The Lord of the Rings', author: 'J.R.R. Tolkien'}, ); }); - it('can compute e to the power of a numeric value with the top-level function', async () => { + it('sort, offset, and limit stages support options', async () => { const snapshot = await firestore .pipeline() .collection(randomCol.path) - .where(field('title').equal('The Lord of the Rings')) - .limit(1) - .select(exp('rating').as('expRating')) + .sort({ + orderings: [field('author').ascending()], + }) + .offset({offset: 5}) + .limit({limit: 3}) + .select('title', 'author') .execute(); - expect(snapshot.results[0].get('expRating')).to.be.approximately( - 109.94717245212351, - 0.000001, + expectResults( + snapshot, + {title: '1984', author: 'George Orwell'}, + {title: 'To Kill a Mockingbird', author: 'Harper Lee'}, + {title: 'The Lord of the Rings', author: 'J.R.R. Tolkien'}, ); }); + }); + + describe('error handling', () => { + it('error properties are propagated from the firestore backend', async () => { + try { + await firestore + .pipeline() + .collection(randomCol.path) + .rawStage('select', [ + // incorrect parameter type + field('title'), + ]) + .execute(); + + expect.fail('expected pipeline.execute() to throw'); + } catch (e: unknown) { + expect(e instanceof Error).to.be.true; + const err = e as ServiceError; + expect(err['code']).to.equal(3); + expect(typeof err['message']).to.equal('string'); + expect(typeof err['details']).to.equal('string'); + expect(typeof err['stack']).to.equal('string'); + expect(err['metadata'] instanceof Object).to.be.true; + + expect(err['message']).to.equal( + `${err.code} INVALID_ARGUMENT: ${err.details}`, + ); + } + }); + + it('can access explain stats in error condition', async () => { + try { + await firestore + .pipeline() + .collection(randomCol.path) + .sort(field('rating').ascending()) + .execute({ + explainOptions: { + mode: 'analyze', + }, + rawOptions: { + memory_limit: 1, + }, + }); + + expect.fail('expected pipeline.execute() to throw'); + } catch (e: unknown) { + const err = e as {[k: string]: unknown}; + expect(err instanceof Error).to.be.true; + + expect(err['code']).to.equal(8); + expect(typeof err['message']).to.equal('string'); + expect(typeof err['details']).to.equal('string'); + expect(typeof err['stack']).to.equal('string'); + expect(err['metadata'] instanceof Object).to.be.true; + + expect(err['message']).to.equal( + `${err.code} RESOURCE_EXHAUSTED: ${err.details}`, + ); + + expect('statusDetails' in err).to.be.true; + expect(Array.isArray(err['statusDetails'])).to.be.true; + + const statusDetails = err['statusDetails'] as Array; + + const foundExplainStats = statusDetails.find(x => { + return ( + 'type_url' in x && + x['type_url'] === + 'type.googleapis.com/google.firestore.v1.ExplainStats' + ); + }); + expect(foundExplainStats).to.not.be.undefined; + } + }); + }); - it('can compute the power of a numeric value', async () => { + describe('raw stage', () => { + it('can select fields', async () => { const snapshot = await firestore .pipeline() .collection(randomCol.path) - .where(field('title').equal("The Hitchhiker's Guide to the Galaxy")) + .rawStage('select', [ + { + title: field('title'), + metadata: { + author: field('author'), + }, + }, + ]) + .sort(field('author').ascending()) .limit(1) - .select(field('rating').pow(2).as('powerRating')) .execute(); - expect(snapshot.results[0].get('powerRating')).to.be.approximately( - 17.64, - 0.0001, - ); + expectResults(snapshot, { + metadata: { + author: 'Frank Herbert', + }, + title: 'Dune', + }); }); - it('can compute the power of a numeric value with the top-level function', async () => { + it('can add fields', async () => { const snapshot = await firestore .pipeline() .collection(randomCol.path) - .where(field('title').equal("The Hitchhiker's Guide to the Galaxy")) + .sort(field('author').ascending()) .limit(1) - .select(pow('rating', 2).as('powerRating')) + .select('title', 'author') + .rawStage('add_fields', [ + { + display: stringConcat('title', ' - ', field('author')), + }, + ]) .execute(); - expect(snapshot.results[0].get('powerRating')).to.be.approximately( - 17.64, - 0.0001, - ); + expectResults(snapshot, { + title: "The Hitchhiker's Guide to the Galaxy", + author: 'Douglas Adams', + display: "The Hitchhiker's Guide to the Galaxy - Douglas Adams", + }); }); - it('can round a numeric value', async () => { + it('can filter with where', async () => { const snapshot = await firestore .pipeline() .collection(randomCol.path) - .where(field('title').equal("The Hitchhiker's Guide to the Galaxy")) - .limit(1) - .select(field('rating').round().as('roundedRating')) + .select('title', 'author') + .rawStage('where', [field('author').equal('Douglas Adams')]) .execute(); expectResults(snapshot, { - roundedRating: 4, + title: "The Hitchhiker's Guide to the Galaxy", + author: 'Douglas Adams', }); }); - it('can round a numeric value with the top-level function', async () => { + it('can limit, offset, and sort', async () => { const snapshot = await firestore .pipeline() .collection(randomCol.path) - .where(field('title').equal("The Hitchhiker's Guide to the Galaxy")) - .limit(1) - .select(round('rating').as('roundedRating')) + .select('title', 'author') + .rawStage('sort', [ + { + direction: 'ascending', + expression: field('author'), + }, + ]) + .rawStage('offset', [3]) + .rawStage('limit', [1]) .execute(); expectResults(snapshot, { - roundedRating: 4, + author: 'Fyodor Dostoevsky', + title: 'Crime and Punishment', }); }); - it('can round a numeric value away from zero for positive half-way values', async () => { + it('can perform aggregate query', async () => { const snapshot = await firestore .pipeline() .collection(randomCol.path) - .where(field('title').equal("The Hitchhiker's Guide to the Galaxy")) - .limit(1) - .addFields(constant(1.5).as('positiveHalf')) - .select(field('positiveHalf').round().as('roundedRating')) + .select('title', 'author', 'rating') + .rawStage('aggregate', [ + {averageRating: field('rating').average()}, + {}, + ]) .execute(); expectResults(snapshot, { - roundedRating: 2, + averageRating: 4.3100000000000005, }); }); - it('can round a numeric value away from zero for negative half-way values', async () => { + it('can perform distinct query', async () => { const snapshot = await firestore .pipeline() .collection(randomCol.path) - .where(field('title').equal("The Hitchhiker's Guide to the Galaxy")) - .limit(1) - .addFields(constant(-1.5).as('negativeHalf')) - .select(field('negativeHalf').round().as('roundedRating')) + .select('title', 'author', 'rating') + .rawStage('distinct', [{rating: field('rating')}]) + .sort(field('rating').descending()) .execute(); - expectResults(snapshot, { - roundedRating: -2, - }); + expectResults( + snapshot, + { + rating: 4.7, + }, + { + rating: 4.6, + }, + { + rating: 4.5, + }, + { + rating: 4.3, + }, + { + rating: 4.2, + }, + { + rating: 4.1, + }, + { + rating: 4.0, + }, + ); }); - it('can round a numeric value to specified precision', async () => { + it('can perform FindNearest query', async () => { const snapshot = await firestore .pipeline() - .collection(randomCol.path) - .limit(1) - .replaceWith( - map({ - foo: 4.123456, - }), - ) - .select( - field('foo').round(0).as('0'), - round('foo', 1).as('1'), - round('foo', constant(2)).as('2'), - round(field('foo'), 4).as('4'), + .collection(randomCol) + .rawStage( + 'find_nearest', + [ + field('embedding'), + FieldValue.vector([10, 1, 2, 1, 1, 1, 1, 1, 1, 1]), + 'euclidean', + ], + { + distance_field: field('computedDistance'), + limit: 2, + }, ) + .select('title', 'computedDistance') .execute(); - expectResults(snapshot, { - '0': 4, - '1': 4.1, - '2': 4.12, - '4': 4.1235, - }); + expectResults( + snapshot, + { + title: "The Hitchhiker's Guide to the Galaxy", + computedDistance: 1, + }, + { + title: 'One Hundred Years of Solitude', + computedDistance: 12.041594578792296, + }, + ); }); + }); - it('can get the collectionId from a path', async () => { + describe('replaceWith stage', () => { + it('run pipeline with replaceWith field name', async () => { const snapshot = await firestore .pipeline() .collection(randomCol.path) - .limit(1) - .select(field('__name__').collectionId().as('collectionId')) + .where(equal('title', "The Hitchhiker's Guide to the Galaxy")) + .replaceWith('awards') .execute(); expectResults(snapshot, { - collectionId: randomCol.id, + hugo: true, + nebula: false, + others: {unknown: {year: 1980}}, }); }); - it('can get the collectionId from a path with the top-level function', async () => { + it('run pipeline with replaceWith Expression result', async () => { const snapshot = await firestore .pipeline() .collection(randomCol.path) - .limit(1) - .select(collectionId('__name__').as('collectionId')) + .where(equal('title', "The Hitchhiker's Guide to the Galaxy")) + .replaceWith( + map({ + foo: 'bar', + baz: { + title: field('title'), + }, + }), + ) .execute(); expectResults(snapshot, { - collectionId: randomCol.id, + foo: 'bar', + baz: {title: "The Hitchhiker's Guide to the Galaxy"}, }); }); - it('can compute the length of a string value', async () => { + it('supports options', async () => { const snapshot = await firestore .pipeline() .collection(randomCol.path) - .where(field('title').equal("The Hitchhiker's Guide to the Galaxy")) - .limit(1) - .select(field('title').length().as('titleLength')) + .where(equal('title', "The Hitchhiker's Guide to the Galaxy")) + .replaceWith({map: 'awards'}) .execute(); expectResults(snapshot, { - titleLength: 36, + hugo: true, + nebula: false, + others: {unknown: {year: 1980}}, }); }); + }); - it('can compute the length of a string value with the top-level function', async () => { + describe('sample stage', () => { + it('run pipeline with sample limit of 3', async () => { const snapshot = await firestore .pipeline() .collection(randomCol.path) - .where(field('title').equal("The Hitchhiker's Guide to the Galaxy")) - .limit(1) - .select(length('title').as('titleLength')) + .sample(3) .execute(); - expectResults(snapshot, { - titleLength: 36, - }); + expect(snapshot.results.length).to.equal(3); }); - it('can compute the length of an array value', async () => { + it('run pipeline with sample limit of {documents: 3}', async () => { const snapshot = await firestore .pipeline() .collection(randomCol.path) - .where(field('title').equal("The Hitchhiker's Guide to the Galaxy")) - .limit(1) - .select(field('tags').length().as('tagsLength')) + .sample({documents: 3}) .execute(); - expectResults(snapshot, { - tagsLength: 3, - }); + expect(snapshot.results.length).to.equal(3); + }); + + it('run pipeline with sample limit of {percentage: 0.6}', async () => { + let avgSize = 0; + const numIterations = 30; + for (let i = 0; i < numIterations; i++) { + const snapshot = await firestore + .pipeline() + .collection(randomCol.path) + .sample({percentage: 0.6}) + .execute(); + + avgSize += snapshot.results.length; + } + avgSize /= numIterations; + expect(avgSize).to.be.closeTo(6, 1); }); + }); - it('can compute the length of an array value with the top-level function', async () => { + describe('union stage', () => { + it('run pipeline with union', async () => { const snapshot = await firestore .pipeline() .collection(randomCol.path) - .where(field('title').equal("The Hitchhiker's Guide to the Galaxy")) - .limit(1) - .select(length('tags').as('tagsLength')) + .union(firestore.pipeline().collection(randomCol.path)) + .sort(field(FieldPath.documentId()).ascending()) .execute(); - expectResults(snapshot, { - tagsLength: 3, - }); + expectResults( + snapshot, + 'book1', + 'book1', + 'book10', + 'book10', + 'book2', + 'book2', + 'book3', + 'book3', + 'book4', + 'book4', + 'book5', + 'book5', + 'book6', + 'book6', + 'book7', + 'book7', + 'book8', + 'book8', + 'book9', + 'book9', + ); }); - it('can compute the length of a map value', async () => { + it('supports options', async () => { const snapshot = await firestore .pipeline() .collection(randomCol.path) - .where(field('title').equal("The Hitchhiker's Guide to the Galaxy")) - .limit(1) - .select(field('awards').length().as('awardsLength')) + .union({other: firestore.pipeline().collection(randomCol.path)}) + .sort(field(FieldPath.documentId()).ascending()) .execute(); - expectResults(snapshot, { - awardsLength: 3, - }); + expectResults( + snapshot, + 'book1', + 'book1', + 'book10', + 'book10', + 'book2', + 'book2', + 'book3', + 'book3', + 'book4', + 'book4', + 'book5', + 'book5', + 'book6', + 'book6', + 'book7', + 'book7', + 'book8', + 'book8', + 'book9', + 'book9', + ); }); + }); - it('can compute the length of a vector value', async () => { + describe('unnest stage', () => { + it('run pipeline with unnest', async () => { const snapshot = await firestore .pipeline() .collection(randomCol.path) - .where(field('title').equal("The Hitchhiker's Guide to the Galaxy")) - .limit(1) - .select(field('embedding').length().as('embeddingLength')) + .where(equal('title', "The Hitchhiker's Guide to the Galaxy")) + .unnest(field('tags').as('tag')) + .select( + 'title', + 'author', + 'genre', + 'published', + 'rating', + 'tags', + 'tag', + 'awards', + 'nestedField', + ) .execute(); - expectResults(snapshot, { - embeddingLength: 10, - }); + expectResults( + snapshot, + { + title: "The Hitchhiker's Guide to the Galaxy", + author: 'Douglas Adams', + genre: 'Science Fiction', + published: 1979, + rating: 4.2, + tags: ['comedy', 'space', 'adventure'], + tag: 'comedy', + awards: { + hugo: true, + nebula: false, + others: {unknown: {year: 1980}}, + }, + nestedField: {'level.1': {'level.2': true}}, + }, + { + title: "The Hitchhiker's Guide to the Galaxy", + author: 'Douglas Adams', + genre: 'Science Fiction', + published: 1979, + rating: 4.2, + tags: ['comedy', 'space', 'adventure'], + tag: 'space', + awards: { + hugo: true, + nebula: false, + others: {unknown: {year: 1980}}, + }, + nestedField: {'level.1': {'level.2': true}}, + }, + { + title: "The Hitchhiker's Guide to the Galaxy", + author: 'Douglas Adams', + genre: 'Science Fiction', + published: 1979, + rating: 4.2, + tags: ['comedy', 'space', 'adventure'], + tag: 'adventure', + awards: { + hugo: true, + nebula: false, + others: {unknown: {year: 1980}}, + }, + nestedField: {'level.1': {'level.2': true}}, + }, + ); }); - it('can compute the length of a bytes value', async () => { + it('unnest with index field', async () => { const snapshot = await firestore .pipeline() .collection(randomCol.path) - .select(constant('12é').as('value')) - .limit(1) - .select(field('value').byteLength().as('valueLength')) + .where(equal('title', "The Hitchhiker's Guide to the Galaxy")) + .unnest(field('tags').as('tag'), 'tagsIndex') + .select( + 'title', + 'author', + 'genre', + 'published', + 'rating', + 'tags', + 'tag', + 'awards', + 'nestedField', + 'tagsIndex', + ) .execute(); - expectResults(snapshot, { - valueLength: 4, - }); + expectResults( + snapshot, + { + title: "The Hitchhiker's Guide to the Galaxy", + author: 'Douglas Adams', + genre: 'Science Fiction', + published: 1979, + rating: 4.2, + tags: ['comedy', 'space', 'adventure'], + tag: 'comedy', + awards: { + hugo: true, + nebula: false, + others: {unknown: {year: 1980}}, + }, + nestedField: {'level.1': {'level.2': true}}, + tagsIndex: 0, + }, + { + title: "The Hitchhiker's Guide to the Galaxy", + author: 'Douglas Adams', + genre: 'Science Fiction', + published: 1979, + rating: 4.2, + tags: ['comedy', 'space', 'adventure'], + tag: 'space', + awards: { + hugo: true, + nebula: false, + others: {unknown: {year: 1980}}, + }, + nestedField: {'level.1': {'level.2': true}}, + tagsIndex: 1, + }, + { + title: "The Hitchhiker's Guide to the Galaxy", + author: 'Douglas Adams', + genre: 'Science Fiction', + published: 1979, + rating: 4.2, + tags: ['comedy', 'space', 'adventure'], + tag: 'adventure', + awards: { + hugo: true, + nebula: false, + others: {unknown: {year: 1980}}, + }, + nestedField: {'level.1': {'level.2': true}}, + tagsIndex: 2, + }, + ); }); - it('can compute the natural logarithm of a numeric value', async () => { + it('unnest an expr', async () => { const snapshot = await firestore .pipeline() .collection(randomCol.path) - .where(field('title').equal("The Hitchhiker's Guide to the Galaxy")) - .limit(1) - .select(field('rating').ln().as('lnRating')) + .where(equal('title', "The Hitchhiker's Guide to the Galaxy")) + .unnest(array([1, 2, 3]).as('copy')) + .select( + 'title', + 'author', + 'genre', + 'published', + 'rating', + 'tags', + 'copy', + 'awards', + 'nestedField', + ) .execute(); - expect(snapshot.results[0]!.data().lnRating).to.be.closeTo( - 1.435, - 0.001, + expectResults( + snapshot, + { + title: "The Hitchhiker's Guide to the Galaxy", + author: 'Douglas Adams', + genre: 'Science Fiction', + published: 1979, + rating: 4.2, + tags: ['comedy', 'space', 'adventure'], + copy: 1, + awards: { + hugo: true, + nebula: false, + others: {unknown: {year: 1980}}, + }, + nestedField: {'level.1': {'level.2': true}}, + }, + { + title: "The Hitchhiker's Guide to the Galaxy", + author: 'Douglas Adams', + genre: 'Science Fiction', + published: 1979, + rating: 4.2, + tags: ['comedy', 'space', 'adventure'], + copy: 2, + awards: { + hugo: true, + nebula: false, + others: {unknown: {year: 1980}}, + }, + nestedField: {'level.1': {'level.2': true}}, + }, + { + title: "The Hitchhiker's Guide to the Galaxy", + author: 'Douglas Adams', + genre: 'Science Fiction', + published: 1979, + rating: 4.2, + tags: ['comedy', 'space', 'adventure'], + copy: 3, + awards: { + hugo: true, + nebula: false, + others: {unknown: {year: 1980}}, + }, + nestedField: {'level.1': {'level.2': true}}, + }, ); }); - it('can compute the natural logarithm of a numeric value with the top-level function', async () => { + it('supports options', async () => { const snapshot = await firestore .pipeline() .collection(randomCol.path) - .where(field('title').equal("The Hitchhiker's Guide to the Galaxy")) - .limit(1) - .select(ln('rating').as('lnRating')) + .where(equal('title', "The Hitchhiker's Guide to the Galaxy")) + .unnest({ + selectable: field('tags').as('tag'), + indexField: 'tagsIndex', + }) + .select( + 'title', + 'author', + 'genre', + 'published', + 'rating', + 'tags', + 'tag', + 'awards', + 'nestedField', + 'tagsIndex', + ) .execute(); - expect(snapshot.results[0]!.data().lnRating).to.be.closeTo( - 1.435, - 0.001, + expectResults( + snapshot, + { + title: "The Hitchhiker's Guide to the Galaxy", + author: 'Douglas Adams', + genre: 'Science Fiction', + published: 1979, + rating: 4.2, + tags: ['comedy', 'space', 'adventure'], + tag: 'comedy', + awards: { + hugo: true, + nebula: false, + others: {unknown: {year: 1980}}, + }, + nestedField: {'level.1': {'level.2': true}}, + tagsIndex: 0, + }, + { + title: "The Hitchhiker's Guide to the Galaxy", + author: 'Douglas Adams', + genre: 'Science Fiction', + published: 1979, + rating: 4.2, + tags: ['comedy', 'space', 'adventure'], + tag: 'space', + awards: { + hugo: true, + nebula: false, + others: {unknown: {year: 1980}}, + }, + nestedField: {'level.1': {'level.2': true}}, + tagsIndex: 1, + }, + { + title: "The Hitchhiker's Guide to the Galaxy", + author: 'Douglas Adams', + genre: 'Science Fiction', + published: 1979, + rating: 4.2, + tags: ['comedy', 'space', 'adventure'], + tag: 'adventure', + awards: { + hugo: true, + nebula: false, + others: {unknown: {year: 1980}}, + }, + nestedField: {'level.1': {'level.2': true}}, + tagsIndex: 2, + }, ); }); + }); - it('can compute the natural logarithm of a numeric value with the top-level function', async () => { - const snapshot = await firestore - .pipeline() - .collection(randomCol.path) - .where(field('title').equal("The Hitchhiker's Guide to the Galaxy")) - .limit(1) - .select(ln('rating').as('lnRating')) - .execute(); - expectResults(snapshot, { - lnRating: 1.4350845252893227, - }); + describe('findNearest stage', () => { + it('run pipeline with findNearest', async () => { + const measures: Array< + Pipelines.FindNearestStageOptions['distanceMeasure'] + > = ['euclidean', 'dot_product', 'cosine']; + for (const measure of measures) { + const snapshot = await firestore + .pipeline() + .collection(randomCol) + .findNearest({ + field: 'embedding', + vectorValue: FieldValue.vector([10, 1, 3, 1, 2, 1, 1, 1, 1, 1]), + limit: 3, + distanceMeasure: measure, + }) + .select('title') + .execute(); + expectResults( + snapshot, + { + title: "The Hitchhiker's Guide to the Galaxy", + }, + { + title: 'One Hundred Years of Solitude', + }, + { + title: "The Handmaid's Tale", + }, + ); + } }); - it('can round a numeric value', async () => { + it('optionally returns the computed distance', async () => { const snapshot = await firestore .pipeline() - .collection(randomCol.path) - .where(field('title').equal("The Hitchhiker's Guide to the Galaxy")) - .limit(1) - .select(field('rating').round().as('roundedRating')) + .collection(randomCol) + .findNearest({ + field: 'embedding', + vectorValue: FieldValue.vector([10, 1, 2, 1, 1, 1, 1, 1, 1, 1]), + limit: 2, + distanceMeasure: 'euclidean', + distanceField: 'computedDistance', + }) + .select('title', 'computedDistance') .execute(); - expectResults(snapshot, { - roundedRating: 4, - }); + expectResults( + snapshot, + { + title: "The Hitchhiker's Guide to the Galaxy", + computedDistance: 1, + }, + { + title: 'One Hundred Years of Solitude', + computedDistance: 12.041594578792296, + }, + ); }); + }); + }); + + describe('function expressions', () => { + it('logical max works', async () => { + const snapshot = await firestore + .pipeline() + .collection(randomCol.path) + .select( + 'title', + logicalMaximum(constant(1960), field('published'), 1961).as( + 'published-safe', + ), + ) + .sort(field('title').ascending()) + .limit(3) + .execute(); + expectResults( + snapshot, + {title: '1984', 'published-safe': 1961}, + {title: 'Crime and Punishment', 'published-safe': 1961}, + {title: 'Dune', 'published-safe': 1965}, + ); + }); - it('can round a numeric value with the top-level function', async () => { - const snapshot = await firestore - .pipeline() - .collection(randomCol.path) - .where(field('title').equal("The Hitchhiker's Guide to the Galaxy")) - .limit(1) - .select(round('rating').as('roundedRating')) - .execute(); - expectResults(snapshot, { - roundedRating: 4, - }); + it('logical min works', async () => { + const snapshot = await firestore + .pipeline() + .collection(randomCol.path) + .select( + 'title', + logicalMinimum(constant(1960), field('published'), 1961).as( + 'published-safe', + ), + ) + .sort(field('title').ascending()) + .limit(3) + .execute(); + expectResults( + snapshot, + {title: '1984', 'published-safe': 1949}, + {title: 'Crime and Punishment', 'published-safe': 1866}, + {title: 'Dune', 'published-safe': 1960}, + ); + }); + + it('conditional works', async () => { + const snapshot = await firestore + .pipeline() + .collection(randomCol.path) + .select( + 'title', + conditional( + lessThan(field('published'), 1960), + constant(1960), + field('published'), + ).as('published-safe'), + field('rating') + .greaterThanOrEqual(4.5) + .conditional(constant('great'), constant('good')) + .as('rating'), + ) + .sort(field('title').ascending()) + .limit(3) + .execute(); + expectResults( + snapshot, + {title: '1984', 'published-safe': 1960, rating: 'good'}, + { + title: 'Crime and Punishment', + 'published-safe': 1960, + rating: 'good', + }, + {title: 'Dune', 'published-safe': 1965, rating: 'great'}, + ); + }); + + it('equalAny works', async () => { + const snapshot = await firestore + .pipeline() + .collection(randomCol.path) + .where(equalAny('published', [1979, 1999, 1967])) + .sort(descending('title')) + .select('title') + .execute(); + expectResults( + snapshot, + {title: "The Hitchhiker's Guide to the Galaxy"}, + {title: 'One Hundred Years of Solitude'}, + ); + }); + + it('notEqualAny works', async () => { + const snapshot = await firestore + .pipeline() + .collection(randomCol.path) + .where( + notEqualAny( + 'published', + [1965, 1925, 1949, 1960, 1866, 1985, 1954, 1967, 1979], + ), + ) + .select('title') + .execute(); + expectResults(snapshot, {title: 'Pride and Prejudice'}); + }); + + it('arrayContains works', async () => { + const snapshot = await firestore + .pipeline() + .collection(randomCol.path) + .where(arrayContains('tags', 'comedy')) + .select('title') + .execute(); + expectResults(snapshot, { + title: "The Hitchhiker's Guide to the Galaxy", }); + }); - it('can compute the square root of a numeric value', async () => { - const snapshot = await firestore - .pipeline() - .collection(randomCol.path) - .where(field('title').equal("The Hitchhiker's Guide to the Galaxy")) - .limit(1) - .select(field('rating').sqrt().as('sqrtRating')) - .execute(); - expectResults(snapshot, { - sqrtRating: 2.04939015319192, - }); + it('arrayContainsAny works', async () => { + const snapshot = await firestore + .pipeline() + .collection(randomCol.path) + .where(arrayContainsAny('tags', ['comedy', 'classic'])) + .sort(descending('title')) + .select('title') + .execute(); + expectResults( + snapshot, + {title: "The Hitchhiker's Guide to the Galaxy"}, + {title: 'Pride and Prejudice'}, + ); + }); + + it('arrayContainsAll works', async () => { + const snapshot = await firestore + .pipeline() + .collection(randomCol.path) + .where(arrayContainsAll('tags', ['adventure', 'magic'])) + .select('title') + .execute(); + expectResults(snapshot, {title: 'The Lord of the Rings'}); + }); + + it('arrayLength works', async () => { + const snapshot = await firestore + .pipeline() + .collection(randomCol.path) + .select(arrayLength('tags').as('tagsCount')) + .where(equal('tagsCount', 3)) + .execute(); + expect(snapshot.results.length).to.equal(10); + }); + + it('testStrConcat', async () => { + const snapshot = await firestore + .pipeline() + .collection(randomCol.path) + .sort(ascending('author')) + .select( + field('author').stringConcat(' - ', field('title')).as('bookInfo'), + ) + .limit(1) + .execute(); + expectResults(snapshot, { + bookInfo: "Douglas Adams - The Hitchhiker's Guide to the Galaxy", }); + }); - it('can compute the square root of a numeric value with the top-level function', async () => { - const snapshot = await firestore - .pipeline() - .collection(randomCol.path) - .where(field('title').equal("The Hitchhiker's Guide to the Galaxy")) - .limit(1) - .select(sqrt('rating').as('sqrtRating')) - .execute(); - expectResults(snapshot, { - sqrtRating: 2.04939015319192, - }); + it('testStartsWith', async () => { + const snapshot = await firestore + .pipeline() + .collection(randomCol.path) + .where(startsWith('title', 'The')) + .select('title') + .sort(field('title').ascending()) + .execute(); + expectResults( + snapshot, + {title: 'The Great Gatsby'}, + {title: "The Handmaid's Tale"}, + {title: "The Hitchhiker's Guide to the Galaxy"}, + {title: 'The Lord of the Rings'}, + ); + }); + + it('testEndsWith', async () => { + const snapshot = await firestore + .pipeline() + .collection(randomCol.path) + .where(endsWith('title', 'y')) + .select('title') + .sort(field('title').descending()) + .execute(); + expectResults( + snapshot, + {title: "The Hitchhiker's Guide to the Galaxy"}, + {title: 'The Great Gatsby'}, + ); + }); + + it('testStrContains', async () => { + const snapshot = await firestore + .pipeline() + .collection(randomCol.path) + .where(stringContains('title', "'s")) + .select('title') + .sort(field('title').ascending()) + .execute(); + expectResults( + snapshot, + {title: "The Handmaid's Tale"}, + {title: "The Hitchhiker's Guide to the Galaxy"}, + ); + }); + + it('testLength', async () => { + const snapshot = await firestore + .pipeline() + .collection(randomCol.path) + .select(charLength('title').as('titleLength'), field('title')) + .where(greaterThan('titleLength', 20)) + .sort(field('title').ascending()) + .execute(); + + expectResults( + snapshot, + + { + titleLength: 29, + title: 'One Hundred Years of Solitude', + }, + { + titleLength: 36, + title: "The Hitchhiker's Guide to the Galaxy", + }, + { + titleLength: 21, + title: 'The Lord of the Rings', + }, + { + titleLength: 21, + title: 'To Kill a Mockingbird', + }, + ); + }); + + it('testLike', async () => { + const snapshot = await firestore + .pipeline() + .collection(randomCol.path) + .where(like('title', '%Guide%')) + .select('title') + .execute(); + expectResults(snapshot, { + title: "The Hitchhiker's Guide to the Galaxy", + }); + }); + + it('testRegexContains', async () => { + const snapshot = await firestore + .pipeline() + .collection(randomCol.path) + .where(regexContains('title', '(?i)(the|of)')) + .execute(); + expect(snapshot.results.length).to.equal(5); + }); + + it('testRegexMatches', async () => { + const snapshot = await firestore + .pipeline() + .collection(randomCol.path) + .where(regexMatch('title', '.*(?i)(the|of).*')) + .execute(); + expect(snapshot.results.length).to.equal(5); + }); + + it('testArithmeticOperations', async () => { + const snapshot = await firestore + .pipeline() + .collection(randomCol.path) + .where(equal('title', 'To Kill a Mockingbird')) + .select( + add(field('rating'), 1).as('ratingPlusOne'), + subtract(field('published'), 1900).as('yearsSince1900'), + field('rating').multiply(10).as('ratingTimesTen'), + divide('rating', 2).as('ratingDividedByTwo'), + multiply('rating', 20).as('ratingTimes20'), + add('rating', 3).as('ratingPlus3'), + mod('rating', 2).as('ratingMod2'), + ) + .limit(1) + .execute(); + expectResults(snapshot, { + ratingPlusOne: 5.2, + yearsSince1900: 60, + ratingTimesTen: 42, + ratingDividedByTwo: 2.1, + ratingTimes20: 84, + ratingPlus3: 7.2, + ratingMod2: 0.20000000000000018, }); + }); - it('can reverse a string', async () => { - const snapshot = await firestore - .pipeline() - .collection(randomCol.path) - .where(field('title').equal("The Hitchhiker's Guide to the Galaxy")) - .limit(1) - .select(field('title').stringReverse().as('reversedTitle')) - .execute(); - expectResults(snapshot, { - reversedTitle: "yxalaG eht ot ediuG s'rekihhctiH ehT", - }); + it('testComparisonOperators', async () => { + const snapshot = await firestore + .pipeline() + .collection(randomCol.path) + .where( + and( + greaterThan('rating', 4.2), + lessThanOrEqual(field('rating'), 4.5), + notEqual('genre', 'Science Fiction'), + ), + ) + .select('rating', 'title') + .sort(field('title').ascending()) + .execute(); + expectResults( + snapshot, + {rating: 4.3, title: 'Crime and Punishment'}, + { + rating: 4.3, + title: 'One Hundred Years of Solitude', + }, + {rating: 4.5, title: 'Pride and Prejudice'}, + ); + }); + + it('testLogicalOperators', async () => { + const snapshot = await firestore + .pipeline() + .collection(randomCol.path) + .where( + or( + and(greaterThan('rating', 4.5), equal('genre', 'Science Fiction')), + lessThan('published', 1900), + ), + ) + .select('title') + .sort(field('title').ascending()) + .execute(); + expectResults( + snapshot, + {title: 'Crime and Punishment'}, + {title: 'Dune'}, + {title: 'Pride and Prejudice'}, + ); + }); + + it('testChecks', async () => { + let snapshot = await firestore + .pipeline() + .collection(randomCol.path) + .sort(field('rating').descending()) + .limit(1) + .select( + equal('rating', null).as('ratingIsNull'), + equal('rating', NaN).as('ratingIsNaN'), + isError(divide(constant(1), constant(0))).as('isError'), + ifError(divide(constant(1), constant(0)), constant('was error')).as( + 'ifError', + ), + ifError( + divide(constant(1), constant(0)).greaterThan(1), + constant(true), + ) + .not() + .as('ifErrorBooleanExpression'), + isAbsent('foo').as('isAbsent'), + notEqual('title', null).as('titleIsNotNull'), + notEqual('cost', NaN).as('costIsNotNan'), + exists('fooBarBaz').as('fooBarBazExists'), + field('title').exists().as('titleExists'), + ) + .execute(); + expectResults(snapshot, { + ratingIsNull: false, + ratingIsNaN: false, + isError: true, + ifError: 'was error', + ifErrorBooleanExpression: false, + isAbsent: true, + titleIsNotNull: true, + costIsNotNan: false, + fooBarBazExists: false, + titleExists: true, + }); + + snapshot = await firestore + .pipeline() + .collection(randomCol.path) + .sort(field('rating').descending()) + .limit(1) + .select( + field('rating').equal(null).as('ratingIsNull'), + field('rating').equal(NaN).as('ratingIsNaN'), + divide(constant(1), constant(0)).isError().as('isError'), + divide(constant(1), constant(0)) + .ifError(constant('was error')) + .as('ifError'), + divide(constant(1), constant(0)) + .greaterThan(1) + .ifError(constant(true)) + .not() + .as('ifErrorBooleanExpression'), + field('foo').isAbsent().as('isAbsent'), + field('title').notEqual(null).as('titleIsNotNull'), + field('cost').notEqual(NaN).as('costIsNotNan'), + ) + .execute(); + expectResults(snapshot, { + ratingIsNull: false, + ratingIsNaN: false, + isError: true, + ifError: 'was error', + ifErrorBooleanExpression: false, + isAbsent: true, + titleIsNotNull: true, + costIsNotNan: false, + }); + }); + + it('testMapGet', async () => { + const snapshot = await firestore + .pipeline() + .collection(randomCol.path) + .sort(field('published').descending()) + .select( + field('awards').mapGet('hugo').as('hugoAward'), + field('awards').mapGet('others').as('others'), + field('title'), + ) + .where(equal('hugoAward', true)) + .execute(); + expectResults( + snapshot, + { + hugoAward: true, + title: "The Hitchhiker's Guide to the Galaxy", + others: {unknown: {year: 1980}}, + }, + {hugoAward: true, title: 'Dune'}, + ); + }); + + it('testDistanceFunctions', async () => { + const sourceVector = FieldValue.vector([0.1, 0.1]); + const targetVector = FieldValue.vector([0.5, 0.8]); + let snapshot = await firestore + .pipeline() + .collection(randomCol.path) + .select( + cosineDistance(constant(sourceVector), targetVector).as( + 'cosineDistance', + ), + dotProduct(constant(sourceVector), targetVector).as( + 'dotProductDistance', + ), + euclideanDistance(constant(sourceVector), targetVector).as( + 'euclideanDistance', + ), + ) + .limit(1) + .execute(); + + expectResults(snapshot, { + cosineDistance: 0.02560880430538015, + dotProductDistance: 0.13, + euclideanDistance: 0.806225774829855, + }); + + snapshot = await firestore + .pipeline() + .collection(randomCol.path) + .select( + constant(sourceVector) + .cosineDistance(targetVector) + .as('cosineDistance'), + constant(sourceVector) + .dotProduct(targetVector) + .as('dotProductDistance'), + constant(sourceVector) + .euclideanDistance(targetVector) + .as('euclideanDistance'), + ) + .limit(1) + .execute(); + + expectResults(snapshot, { + cosineDistance: 0.02560880430538015, + dotProductDistance: 0.13, + euclideanDistance: 0.806225774829855, }); + }); + + it('testVectorLength', async () => { + const snapshot = await firestore + .pipeline() + .collection(randomCol.path) + .limit(1) + .select( + vectorLength(constant(FieldValue.vector([1, 2, 3]))).as( + 'vectorLength', + ), + ) + .execute(); + expectResults(snapshot, { + vectorLength: 3, + }); + }); + + it('testNestedFields', async () => { + const snapshot = await firestore + .pipeline() + .collection(randomCol.path) + .where(equal('awards.hugo', true)) + .sort(descending('title')) + .select('title', 'awards.hugo') + .execute(); + expectResults( + snapshot, + { + title: "The Hitchhiker's Guide to the Galaxy", + 'awards.hugo': true, + }, + {title: 'Dune', 'awards.hugo': true}, + ); + }); - it('can reverse a string with the top-level function', async () => { - const snapshot = await firestore - .pipeline() - .collection(randomCol.path) - .where(field('title').equal("The Hitchhiker's Guide to the Galaxy")) - .limit(1) - .select(stringReverse('title').as('reversedTitle')) - .execute(); - expectResults(snapshot, { - reversedTitle: "yxalaG eht ot ediuG s'rekihhctiH ehT", - }); + it('test mapGet with field name including . notation', async () => { + const snapshot = await firestore + .pipeline() + .collection(randomCol.path) + .limit(1) + .replaceWith( + map({ + title: 'foo', + nested: { + level: { + '1': 'bar', + }, + 'level.1': { + 'level.2': 'baz', + }, + }, + }), + ) + .select( + 'title', + field('nested.level.1'), + mapGet('nested', 'level.1').mapGet('level.2').as('nested'), + ) + .execute(); + + expectResults(snapshot, { + title: 'foo', + 'nested.level.`1`': 'bar', + nested: 'baz', }); + }); - it('supports Document_id', async () => { - let snapshot = await firestore + describe('genericFunction', () => { + it('add selectable', async () => { + const snapshot = await firestore .pipeline() .collection(randomCol.path) - .sort(field('rating').descending()) + .sort(descending('rating')) .limit(1) .select( - documentId(field('__name__')).as('docId'), - documentId(field('__path__')).as('noDocId'), - documentId(randomCol.doc('foo')).as('fromDocRef'), + new FunctionExpression('add', [field('rating'), constant(1)]).as( + 'rating', + ), ) .execute(); expectResults(snapshot, { - docId: 'book4', - noDocId: null, - fromDocRef: 'foo', - }); - snapshot = await firestore - .pipeline() - .collection(randomCol.path) - .sort(field('rating').descending()) - .limit(1) - .select(field('__name__').documentId().as('docId')) - .execute(); - expectResults(snapshot, { - docId: 'book4', + rating: 5.7, }); }); - it('supports substring', async () => { - let snapshot = await firestore - .pipeline() - .collection(randomCol.path) - .sort(field('rating').descending()) - .limit(1) - .select(substring('title', 9, 2).as('of')) - .execute(); - expectResults(snapshot, { - of: 'of', - }); - snapshot = await firestore + it('and (variadic) selectable', async () => { + const snapshot = await firestore .pipeline() .collection(randomCol.path) - .sort(field('rating').descending()) - .limit(1) - .select(field('title').substring(9, 2).as('of')) + .where( + new FunctionExpression('and', [ + field('rating').greaterThan(0), + field('title').charLength().lessThan(5), + field('tags').arrayContains('propaganda'), + ]).asBoolean(), + ) + .select('title') .execute(); expectResults(snapshot, { - of: 'of', + title: '1984', }); }); - it('supports substring without length', async () => { - let snapshot = await firestore - .pipeline() - .collection(randomCol.path) - .sort(field('rating').descending()) - .limit(1) - .select(substring('title', 9).as('of')) - .execute(); - expectResults(snapshot, { - of: 'of the Rings', - }); - snapshot = await firestore + it('array contains any', async () => { + const snapshot = await firestore .pipeline() .collection(randomCol.path) - .sort(field('rating').descending()) - .limit(1) - .select(field('title').substring(9).as('of')) + .where( + new FunctionExpression('array_contains_any', [ + field('tags'), + array(['politics']), + ]).asBoolean(), + ) + .select('title') .execute(); expectResults(snapshot, { - of: 'of the Rings', + title: 'Dune', }); }); - it('arrayConcat works', async () => { + it('countif aggregate', async () => { const snapshot = await firestore .pipeline() .collection(randomCol.path) - .where(field('title').equal("The Hitchhiker's Guide to the Galaxy")) - .select( - arrayConcat('tags', ['newTag1', 'newTag2'], field('tags'), [ - null, - ]).as('modifiedTags'), + .aggregate( + new AggregateFunction('count_if', [ + field('rating').greaterThanOrEqual(4.5), + ]).as('countOfBest'), ) - .limit(1) .execute(); expectResults(snapshot, { - modifiedTags: [ - 'comedy', - 'space', - 'adventure', - 'newTag1', - 'newTag2', - 'comedy', - 'space', - 'adventure', - null, - ], + countOfBest: 3, }); }); - it('test toLower', async () => { + it('sort by char_len', async () => { const snapshot = await firestore .pipeline() .collection(randomCol.path) - .sort(ascending('title')) - .select(toLower('author').as('lowercaseAuthor')) - .limit(1) + .sort( + new FunctionExpression('char_length', [field('title')]).ascending(), + descending('__name__'), + ) + .limit(3) + .select('title') .execute(); - expectResults(snapshot, { - lowercaseAuthor: 'george orwell', - }); + expectResults( + snapshot, + { + title: '1984', + }, + { + title: 'Dune', + }, + { + title: 'The Great Gatsby', + }, + ); }); + }); - it('test toUpper', async () => { - const snapshot = await firestore - .pipeline() - .collection(randomCol.path) - .sort(ascending('title')) - .select(toUpper('author').as('uppercaseAuthor')) - .limit(1) - .execute(); - expectResults(snapshot, {uppercaseAuthor: 'GEORGE ORWELL'}); + it('supports array', async () => { + const snapshot = await firestore + .pipeline() + .collection(randomCol.path) + .sort(field('rating').descending()) + .limit(1) + .select(array([1, 2, 3, 4]).as('metadata')) + .execute(); + expect(snapshot.results.length).to.equal(1); + expectResults(snapshot, { + metadata: [1, 2, 3, 4], }); + }); - it('testTrim', async () => { - const snapshot = await firestore - .pipeline() - .collection(randomCol.path) - .replaceWith( - map({ - spacedTitle: " The Hitchhiker's Guide to the Galaxy ", - userNameWithQuotes: '"alice"', - bytes: Uint8Array.from([0x00, 0x01, 0x02, 0x00, 0x00]), - }), - ) - .select( - trim('spacedTitle').as('trimmedTitle'), - field('spacedTitle'), - field('userNameWithQuotes').trim('"').as('userName'), - field('bytes') - .trim(Uint8Array.from([0x00])) - .as('bytes'), - ) - .limit(1) - .execute(); - expectResults(snapshot, { - spacedTitle: " The Hitchhiker's Guide to the Galaxy ", - trimmedTitle: "The Hitchhiker's Guide to the Galaxy", - userName: 'alice', - bytes: Uint8Array.from([0x01, 0x02]), - }); + it('evaluates expression in array', async () => { + const snapshot = await firestore + .pipeline() + .collection(randomCol.path) + .sort(field('rating').descending()) + .limit(1) + .select( + array([1, 2, field('genre'), multiply('rating', 10)]).as('metadata'), + ) + .execute(); + expect(snapshot.results.length).to.equal(1); + expectResults(snapshot, { + metadata: [1, 2, 'Fantasy', 47], }); + }); - it('test reverse', async () => { - const snapshot = await firestore - .pipeline() - .collection(randomCol.path) - .where(equal('title', '1984')) - .limit(1) - .select(reverse('title').as('reverseTitle')) - .execute(); - expectResults(snapshot, {reverseTitle: '4891'}); + it('supports arrayGet', async () => { + let snapshot = await firestore + .pipeline() + .collection(randomCol.path) + .sort(field('rating').descending()) + .limit(3) + .select(arrayGet('tags', 0).as('firstTag')) + .execute(); + const expectedResults = [ + { + firstTag: 'adventure', + }, + { + firstTag: 'politics', + }, + { + firstTag: 'classic', + }, + ]; + expectResults(snapshot, ...expectedResults); + + snapshot = await firestore + .pipeline() + .collection(randomCol.path) + .sort(field('rating').descending()) + .limit(3) + .select(field('tags').arrayGet(0).as('firstTag')) + .execute(); + expectResults(snapshot, ...expectedResults); + }); + + it('supports map', async () => { + const snapshot = await firestore + .pipeline() + .collection(randomCol.path) + .sort(field('rating').descending()) + .limit(1) + .select( + map({ + foo: 'bar', + }).as('metadata'), + ) + .execute(); + + expect(snapshot.results.length).to.equal(1); + expectResults(snapshot, { + metadata: { + foo: 'bar', + }, }); + }); - it('testAbs', async () => { - const snapshot = await firestore - .pipeline() - .collection(randomCol.path) - .limit(1) - .select( - constant(-10).as('neg10'), - constant(-22.22).as('neg22'), - constant(1).as('pos1'), - ) - .select( - abs('neg10').as('10'), - abs(field('neg22')).as('22'), - field('pos1').as('1'), - ) - .execute(); - expectResults(snapshot, { - '10': 10, - '22': 22.22, - '1': 1, - }); + it('evaluates expression in map', async () => { + const snapshot = await firestore + .pipeline() + .collection(randomCol.path) + .sort(field('rating').descending()) + .limit(1) + .select( + map({ + genre: field('genre'), + rating: field('rating').multiply(10), + }).as('metadata'), + ) + .execute(); + + expect(snapshot.results.length).to.equal(1); + expectResults(snapshot, { + metadata: { + genre: 'Fantasy', + rating: 47, + }, }); + }); - it('can compute the base-10 logarithm of a numeric value', async () => { - const snapshot = await firestore - .pipeline() - .collection(randomCol.path) - .where(field('title').equal('The Lord of the Rings')) - .limit(1) - .select(field('rating').log10().as('log10Rating')) - .execute(); - expect(snapshot.results[0]!.data().log10Rating).to.be.closeTo( - 0.672, - 0.001, - ); + it('supports mapRemove', async () => { + let snapshot = await firestore + .pipeline() + .collection(randomCol.path) + .sort(field('rating').descending()) + .limit(1) + .select(mapRemove('awards', 'hugo').as('awards')) + .execute(); + expectResults(snapshot, { + awards: {nebula: false}, + }); + snapshot = await firestore + .pipeline() + .collection(randomCol.path) + .sort(field('rating').descending()) + .limit(1) + .select(field('awards').mapRemove('hugo').as('awards')) + .execute(); + expectResults(snapshot, { + awards: {nebula: false}, }); + }); - it('can compute the base-10 logarithm of a numeric value with the top-level function', async () => { - const snapshot = await firestore - .pipeline() - .collection(randomCol.path) - .where(field('title').equal('The Lord of the Rings')) - .limit(1) - .select(log10('rating').as('log10Rating')) - .execute(); - expect(snapshot.results[0]!.data().log10Rating).to.be.closeTo( - 0.672, - 0.001, - ); + it('supports mapMerge', async () => { + let snapshot = await firestore + .pipeline() + .collection(randomCol.path) + .sort(field('rating').descending()) + .limit(1) + .select(mapMerge('awards', {fakeAward: true}).as('awards')) + .execute(); + expectResults(snapshot, { + awards: {nebula: false, hugo: false, fakeAward: true}, + }); + snapshot = await firestore + .pipeline() + .collection(randomCol.path) + .sort(field('rating').descending()) + .limit(1) + .select(field('awards').mapMerge({fakeAward: true}).as('awards')) + .execute(); + expectResults(snapshot, { + awards: {nebula: false, hugo: false, fakeAward: true}, }); + }); - it('can concat fields', async () => { - const snapshot = await firestore - .pipeline() - .collection(randomCol.path) - .addFields( - concat('author', ' ', field('title')).as('display'), - field('author').concat(': ', field('title')).as('display2'), - ) - .where(equal('author', 'Douglas Adams')) - .select('display', 'display2') - .execute(); - expectResults(snapshot, { - display: "Douglas Adams The Hitchhiker's Guide to the Galaxy", - display2: "Douglas Adams: The Hitchhiker's Guide to the Galaxy", - }); + it('supports timestamp conversions', async () => { + const snapshot = await firestore + .pipeline() + .collection(randomCol.path) + .limit(1) + .select( + unixSecondsToTimestamp(constant(1741380235)).as( + 'unixSecondsToTimestamp', + ), + unixMillisToTimestamp(constant(1741380235123)).as( + 'unixMillisToTimestamp', + ), + unixMicrosToTimestamp(constant(1741380235123456)).as( + 'unixMicrosToTimestamp', + ), + timestampToUnixSeconds( + constant(new Timestamp(1741380235, 123456789)), + ).as('timestampToUnixSeconds'), + timestampToUnixMicros( + constant(new Timestamp(1741380235, 123456789)), + ).as('timestampToUnixMicros'), + timestampToUnixMillis( + constant(new Timestamp(1741380235, 123456789)), + ).as('timestampToUnixMillis'), + ) + .execute(); + expectResults(snapshot, { + unixMicrosToTimestamp: new Timestamp(1741380235, 123456000), + unixMillisToTimestamp: new Timestamp(1741380235, 123000000), + unixSecondsToTimestamp: new Timestamp(1741380235, 0), + timestampToUnixSeconds: 1741380235, + timestampToUnixMicros: 1741380235123456, + timestampToUnixMillis: 1741380235123, }); + }); - it('supports currentTimestamp', async () => { - const snapshot = await firestore - .pipeline() - .collection(randomCol.path) - .limit(1) - .addFields(currentTimestamp().as('now')) - .select('now') - .execute(); - const now = snapshot.results[0].get('now') as Timestamp; - expect(now).instanceof(Timestamp); - expect( - now.toDate().getUTCSeconds() - new Date().getUTCSeconds(), - ).lessThan(5000); + it('supports timestamp math', async () => { + const snapshot = await firestore + .pipeline() + .collection(randomCol.path) + .limit(1) + .select(constant(new Timestamp(1741380235, 0)).as('timestamp')) + .select( + timestampAdd('timestamp', 'day', 10).as('plus10days'), + timestampAdd('timestamp', 'hour', 10).as('plus10hours'), + timestampAdd('timestamp', 'minute', 10).as('plus10minutes'), + timestampAdd('timestamp', 'second', 10).as('plus10seconds'), + timestampAdd('timestamp', 'microsecond', 10).as('plus10micros'), + timestampAdd('timestamp', 'millisecond', 10).as('plus10millis'), + timestampSubtract('timestamp', 'day', 10).as('minus10days'), + timestampSubtract('timestamp', 'hour', 10).as('minus10hours'), + timestampSubtract('timestamp', 'minute', 10).as('minus10minutes'), + timestampSubtract('timestamp', 'second', 10).as('minus10seconds'), + timestampSubtract('timestamp', 'microsecond', 10).as('minus10micros'), + timestampSubtract('timestamp', 'millisecond', 10).as('minus10millis'), + ) + .execute(); + expectResults(snapshot, { + plus10days: new Timestamp(1742244235, 0), + plus10hours: new Timestamp(1741416235, 0), + plus10minutes: new Timestamp(1741380835, 0), + plus10seconds: new Timestamp(1741380245, 0), + plus10micros: new Timestamp(1741380235, 10000), + plus10millis: new Timestamp(1741380235, 10000000), + minus10days: new Timestamp(1740516235, 0), + minus10hours: new Timestamp(1741344235, 0), + minus10minutes: new Timestamp(1741379635, 0), + minus10seconds: new Timestamp(1741380225, 0), + minus10micros: new Timestamp(1741380234, 999990000), + minus10millis: new Timestamp(1741380234, 990000000), }); + }); - it('supports ifAbsent', async () => { - const snapshot = await firestore - .pipeline() - .collection(randomCol.path) - .limit(1) - .replaceWith( - map({ - title: 'foo', - }), - ) - .select( - ifAbsent('title', 'default title').as('title'), - field('name').ifAbsent('default name').as('name'), - field('name').ifAbsent(field('title')).as('nameOrTitle'), - ) - .execute(); + it('supports byteLength', async () => { + const snapshot = await firestore + .pipeline() + .collection(randomCol) + .limit(1) + .select(constant(new Uint8Array([1, 2, 3, 4, 5, 6, 7, 0])).as('bytes')) + .select(byteLength('bytes').as('byteLength')) + .execute(); - expectResults(snapshot, { - title: 'foo', - name: 'default name', - nameOrTitle: 'foo', - }); + expectResults(snapshot, { + byteLength: 8, }); + }); - it('supports join', async () => { - const snapshot = await firestore - .pipeline() - .collection(randomCol.path) - .limit(1) - .replaceWith( - map({ - tags: ['foo', 'bar', 'baz'], - delimeter: '|', - }), - ) - .select(join('tags', ',').as('csv'), field('tags').join('|').as('or')) - .execute(); + it('supports not', async () => { + const snapshot = await firestore + .pipeline() + .collection(randomCol) + .limit(1) + .select(constant(true).as('trueField')) + .select('trueField', not(equal('trueField', true)).as('falseField')) + .execute(); - expectResults(snapshot, { - csv: 'foo,bar,baz', - or: 'foo|bar|baz', - }); + expectResults(snapshot, { + trueField: true, + falseField: false, }); + }); - it('can compute the sum of the elements in an array', async () => { - const snapshot = await firestore - .pipeline() - .collection(randomCol.path) - .where(field('title').equal('The Lord of the Rings')) - .limit(1) - .addFields(array([150, 200]).as('sales')) - .select(field('sales').arraySum().as('totalSales')) - .execute(); - expectResults(snapshot, { - totalSales: 350, - }); + it('can reverse an array', async () => { + const snapshot = await firestore + .pipeline() + .collection(randomCol.path) + .where(field('title').equal("The Hitchhiker's Guide to the Galaxy")) + .limit(1) + .select(field('tags').arrayReverse().as('reversedTags')) + .execute(); + expectResults(snapshot, { + reversedTags: ['adventure', 'space', 'comedy'], }); + }); - it('can compute the sum of the elements in an array with the top-level function', async () => { - const snapshot = await firestore - .pipeline() - .collection(randomCol.path) - .where(field('title').equal('The Lord of the Rings')) - .limit(1) - .addFields(array([150, 200]).as('sales')) - .select(arraySum('sales').as('totalSales')) - .execute(); - expectResults(snapshot, { - totalSales: 350, - }); + it('can reverse an array with the top-level function', async () => { + const snapshot = await firestore + .pipeline() + .collection(randomCol.path) + .where(field('title').equal("The Hitchhiker's Guide to the Galaxy")) + .limit(1) + .select(arrayReverse('tags').as('reversedTags')) + .execute(); + expectResults(snapshot, { + reversedTags: ['adventure', 'space', 'comedy'], }); - it('truncate timestamp', async () => { - const results = await firestore - .pipeline() - .collection(randomCol) - .limit(1) - .replaceWith( - map({ - timestamp: new Timestamp( - Date.UTC(2025, 10, 30, 1, 2, 3) / 1000, - 456789, - ), - }), - ) - .select( - timestampTruncate('timestamp', 'year').as('trunc_year'), - timestampTruncate(field('timestamp'), 'month').as('trunc_month'), - timestampTruncate(field('timestamp'), constant('day')).as( - 'trunc_day', - ), - field('timestamp') - .timestampTruncate(constant('day'), 'MST') - .as('trunc_day_mst'), - field('timestamp').timestampTruncate('hour').as('trunc_hour'), - field('timestamp') - .timestampTruncate(constant('minute')) - .as('trunc_minute'), - field('timestamp').timestampTruncate('second').as('trunc_second'), - ) - .execute(); + }); - expectResults(results, { - trunc_year: new Timestamp(Date.UTC(2025, 0) / 1000, 0), - trunc_month: new Timestamp(Date.UTC(2025, 10) / 1000, 0), - trunc_day: new Timestamp(Date.UTC(2025, 10, 30) / 1000, 0), - trunc_day_mst: new Timestamp( - Date.UTC(2025, 10, 29) / 1000 + 7 * 3600, - 0, - ), - trunc_hour: new Timestamp(Date.UTC(2025, 10, 30, 1) / 1000, 0), - trunc_minute: new Timestamp(Date.UTC(2025, 10, 30, 1, 2) / 1000, 0), - trunc_second: new Timestamp( - Date.UTC(2025, 10, 30, 1, 2, 3) / 1000, - 0, - ), - }); + it('can compute the ceiling of a numeric value', async () => { + const snapshot = await firestore + .pipeline() + .collection(randomCol.path) + .where(field('title').equal("The Hitchhiker's Guide to the Galaxy")) + .limit(1) + .select(field('rating').ceil().as('ceilingRating')) + .execute(); + expectResults(snapshot, { + ceilingRating: 5, }); + }); - it('supports split', async () => { - const results = await firestore - .pipeline() - .collection(randomCol) - .limit(1) - .replaceWith( - map({ - csv: 'foo,bar,baz', - data: 'baz:bar:foo', - csvDelimeter: ',', - bytes: Uint8Array.from([0x01, 0x00, 0x02, 0x00, 0x03]), - }), - ) - .select( - split('csv', field('csvDelimeter')).as('csv'), - split(field('data'), ':').as('data'), - field('bytes') - .split(constant(Uint8Array.from([0x00]))) - .as('bytes'), - ) - .execute(); - - expectResults(results, { - csv: ['foo', 'bar', 'baz'], - data: ['baz', 'bar', 'foo'], - bytes: [ - Uint8Array.from([0x01]), - Uint8Array.from([0x02]), - Uint8Array.from([0x03]), - ], - }); + it('can compute the ceiling of a numeric value with the top-level function', async () => { + const snapshot = await firestore + .pipeline() + .collection(randomCol.path) + .where(field('title').equal("The Hitchhiker's Guide to the Galaxy")) + .limit(1) + .select(ceil('rating').as('ceilingRating')) + .execute(); + expectResults(snapshot, { + ceilingRating: 5, + }); + }); - void expect( - firestore - .pipeline() - .collection(randomCol) - .limit(1) - .replaceWith( - map({ - csv: 'foo,bar,baz', - }), - ) - .select( - field('csv') - .split(constant(Uint8Array.from([0x00]))) - .as('dontSplitStringAndBytes'), - ) - .execute(), - ).to.be.rejected; - }); - - it('supports type', async () => { - const result = await firestore - .pipeline() - .collection(randomCol) - .limit(1) - .replaceWith( - map({ - int: constant(1), - float: constant(1.1), - str: constant('a string'), - bool: constant(true), - null: constant(null), - geoPoint: constant(new GeoPoint(0.1, 0.2)), - timestamp: constant(new Timestamp(123456, 0)), - date: constant(new Date()), - bytes: constant(new Uint8Array([1, 2, 3, 4, 5, 6, 7, 0])), - docRef: constant(firestore.doc('foo/bar')), - vector: constant(FieldValue.vector([1, 2, 3])), - map: map({ - number: 1, - string: 'a string', - }), - array: array([1, 'a string']), - }), - ) - .select( - type('int').as('int'), - field('float').type().as('float'), - field('str').type().as('str'), - type('bool').as('bool'), - type('null').as('null'), - type('geoPoint').as('geoPoint'), - type('timestamp').as('timestamp'), - type('date').as('date'), - type('bytes').as('bytes'), - type('docRef').as('docRef'), - type('vector').as('vector'), - type('map').as('map'), - type('array').as('array'), - ) - .execute(); + it('can compute the floor of a numeric value', async () => { + const snapshot = await firestore + .pipeline() + .collection(randomCol.path) + .where(field('title').equal("The Hitchhiker's Guide to the Galaxy")) + .limit(1) + .select(field('rating').floor().as('floorRating')) + .execute(); + expectResults(snapshot, { + floorRating: 4, + }); + }); - expectResults(result, { - int: 'int64', - float: 'float64', - str: 'string', - bool: 'boolean', - null: 'null', - geoPoint: 'geo_point', - timestamp: 'timestamp', - date: 'timestamp', - bytes: 'bytes', - docRef: 'reference', - vector: 'vector', - map: 'map', - array: 'array', - }); + it('can compute the floor of a numeric value with the top-level function', async () => { + const snapshot = await firestore + .pipeline() + .collection(randomCol.path) + .where(field('title').equal("The Hitchhiker's Guide to the Galaxy")) + .limit(1) + .select(floor('rating').as('floorRating')) + .execute(); + expectResults(snapshot, { + floorRating: 4, }); + }); - // TODO(new-expression): Add new expression tests above this line + it('can compute e to the power of a numeric value', async () => { + const snapshot = await firestore + .pipeline() + .collection(randomCol.path) + .where(field('title').equal('The Lord of the Rings')) + .limit(1) + .select(field('rating').exp().as('expRating')) + .execute(); + expect(snapshot.results[0].get('expRating')).to.be.approximately( + 109.94717245212352, + 0.00001, + ); }); - describe('pagination', () => { - let addedDocs: DocumentReference[] = []; + it('can compute e to the power of a numeric value with the top-level function', async () => { + const snapshot = await firestore + .pipeline() + .collection(randomCol.path) + .where(field('title').equal('The Lord of the Rings')) + .limit(1) + .select(exp('rating').as('expRating')) + .execute(); + expect(snapshot.results[0].get('expRating')).to.be.approximately( + 109.94717245212351, + 0.000001, + ); + }); - /** - * Adds several books to the test collection. These - * additional books support pagination test scenarios - * that would otherwise not be possible with the original - * set of books. - * @param collectionReference - */ - async function addBooks( - collectionReference: CollectionReference, - ): Promise { - let docRef = collectionReference.doc('book11'); - addedDocs.push(docRef); - await docRef.set({ - title: 'Jonathan Strange & Mr Norrell', - author: 'Susanna Clarke', - genre: 'Fantasy', - published: 2004, - rating: 4.6, - tags: ['historical fantasy', 'magic', 'alternate history', 'england'], - awards: {hugo: false, nebula: false}, - }); - docRef = collectionReference.doc('book12'); - addedDocs.push(collectionReference.doc('book12')); - await docRef.set({ - title: 'The Master and Margarita', - author: 'Mikhail Bulgakov', - genre: 'Satire', - published: 1967, // Though written much earlier - rating: 4.6, - tags: [ - 'russian literature', - 'supernatural', - 'philosophy', - 'dark comedy', - ], - awards: {}, - }); - docRef = collectionReference.doc('book13'); - addedDocs.push(docRef); - await docRef.set({ - title: 'A Long Way to a Small, Angry Planet', - author: 'Becky Chambers', - genre: 'Science Fiction', - published: 2014, - rating: 4.6, - tags: [ - 'space opera', - 'found family', - 'character-driven', - 'optimistic', - ], - awards: {hugo: false, nebula: false, kitschies: true}, - }); - } + it('can compute the power of a numeric value', async () => { + const snapshot = await firestore + .pipeline() + .collection(randomCol.path) + .where(field('title').equal("The Hitchhiker's Guide to the Galaxy")) + .limit(1) + .select(field('rating').pow(2).as('powerRating')) + .execute(); + expect(snapshot.results[0].get('powerRating')).to.be.approximately( + 17.64, + 0.0001, + ); + }); - afterEach(async () => { - for (let i = 0; i < addedDocs.length; i++) { - await addedDocs[i].delete(); - } - addedDocs = []; + it('can compute the power of a numeric value with the top-level function', async () => { + const snapshot = await firestore + .pipeline() + .collection(randomCol.path) + .where(field('title').equal("The Hitchhiker's Guide to the Galaxy")) + .limit(1) + .select(pow('rating', 2).as('powerRating')) + .execute(); + expect(snapshot.results[0].get('powerRating')).to.be.approximately( + 17.64, + 0.0001, + ); + }); + + it('can round a numeric value', async () => { + const snapshot = await firestore + .pipeline() + .collection(randomCol.path) + .where(field('title').equal("The Hitchhiker's Guide to the Galaxy")) + .limit(1) + .select(field('rating').round().as('roundedRating')) + .execute(); + expectResults(snapshot, { + roundedRating: 4, }); + }); - it('supports pagination with filters', async () => { - await addBooks(randomCol); - const pageSize = 2; - const pipeline = firestore - .pipeline() - .collection(randomCol.path) - .select('title', 'rating', '__name__') - .sort(field('rating').descending(), field('__name__').ascending()); + it('can round a numeric value with the top-level function', async () => { + const snapshot = await firestore + .pipeline() + .collection(randomCol.path) + .where(field('title').equal("The Hitchhiker's Guide to the Galaxy")) + .limit(1) + .select(round('rating').as('roundedRating')) + .execute(); + expectResults(snapshot, { + roundedRating: 4, + }); + }); - let snapshot = await pipeline.limit(pageSize).execute(); + it('can round a numeric value away from zero for positive half-way values', async () => { + const snapshot = await firestore + .pipeline() + .collection(randomCol.path) + .where(field('title').equal("The Hitchhiker's Guide to the Galaxy")) + .limit(1) + .addFields(constant(1.5).as('positiveHalf')) + .select(field('positiveHalf').round().as('roundedRating')) + .execute(); + expectResults(snapshot, { + roundedRating: 2, + }); + }); - snapshot.results.forEach(r => console.log(JSON.stringify(r.data()))); + it('can round a numeric value away from zero for negative half-way values', async () => { + const snapshot = await firestore + .pipeline() + .collection(randomCol.path) + .where(field('title').equal("The Hitchhiker's Guide to the Galaxy")) + .limit(1) + .addFields(constant(-1.5).as('negativeHalf')) + .select(field('negativeHalf').round().as('roundedRating')) + .execute(); + expectResults(snapshot, { + roundedRating: -2, + }); + }); - expectResults( - snapshot, - {title: 'The Lord of the Rings', rating: 4.7}, - {title: 'Dune', rating: 4.6}, - ); + it('can round a numeric value to specified precision', async () => { + const snapshot = await firestore + .pipeline() + .collection(randomCol.path) + .limit(1) + .replaceWith( + map({ + foo: 4.123456, + }), + ) + .select( + field('foo').round(0).as('0'), + round('foo', 1).as('1'), + round('foo', constant(2)).as('2'), + round(field('foo'), 4).as('4'), + ) + .execute(); + expectResults(snapshot, { + '0': 4, + '1': 4.1, + '2': 4.12, + '4': 4.1235, + }); + }); - const lastDoc = snapshot.results[snapshot.results.length - 1]; + it('can get the collectionId from a path', async () => { + const snapshot = await firestore + .pipeline() + .collection(randomCol.path) + .limit(1) + .select(field('__name__').collectionId().as('collectionId')) + .execute(); + expectResults(snapshot, { + collectionId: randomCol.id, + }); + }); - snapshot = await pipeline - .where( - or( - and( - field('rating').equal(lastDoc.get('rating')), - field('__name__').greaterThan(lastDoc.ref), - ), - field('rating').lessThan(lastDoc.get('rating')), - ), - ) - .limit(pageSize) - .execute(); - expectResults( - snapshot, - {title: 'Jonathan Strange & Mr Norrell', rating: 4.6}, - {title: 'The Master and Margarita', rating: 4.6}, - ); + it('can get the collectionId from a path with the top-level function', async () => { + const snapshot = await firestore + .pipeline() + .collection(randomCol.path) + .limit(1) + .select(collectionId('__name__').as('collectionId')) + .execute(); + expectResults(snapshot, { + collectionId: randomCol.id, }); + }); - it('supports pagination with offsets', async () => { - await addBooks(randomCol); + it('can compute the length of a string value', async () => { + const snapshot = await firestore + .pipeline() + .collection(randomCol.path) + .where(field('title').equal("The Hitchhiker's Guide to the Galaxy")) + .limit(1) + .select(field('title').length().as('titleLength')) + .execute(); + expectResults(snapshot, { + titleLength: 36, + }); + }); - const secondFilterField = '__name__'; + it('can compute the length of a string value with the top-level function', async () => { + const snapshot = await firestore + .pipeline() + .collection(randomCol.path) + .where(field('title').equal("The Hitchhiker's Guide to the Galaxy")) + .limit(1) + .select(length('title').as('titleLength')) + .execute(); + expectResults(snapshot, { + titleLength: 36, + }); + }); - const pipeline = firestore - .pipeline() - .collection(randomCol.path) - .select('title', 'rating', secondFilterField) - .sort( - field('rating').descending(), - field(secondFilterField).ascending(), - ); + it('can compute the length of an array value', async () => { + const snapshot = await firestore + .pipeline() + .collection(randomCol.path) + .where(field('title').equal("The Hitchhiker's Guide to the Galaxy")) + .limit(1) + .select(field('tags').length().as('tagsLength')) + .execute(); + expectResults(snapshot, { + tagsLength: 3, + }); + }); - const pageSize = 2; - let currPage = 0; + it('can compute the length of an array value with the top-level function', async () => { + const snapshot = await firestore + .pipeline() + .collection(randomCol.path) + .where(field('title').equal("The Hitchhiker's Guide to the Galaxy")) + .limit(1) + .select(length('tags').as('tagsLength')) + .execute(); + expectResults(snapshot, { + tagsLength: 3, + }); + }); - let snapshot = await pipeline - .offset(currPage++ * pageSize) - .limit(pageSize) - .execute(); + it('can compute the length of a map value', async () => { + const snapshot = await firestore + .pipeline() + .collection(randomCol.path) + .where(field('title').equal("The Hitchhiker's Guide to the Galaxy")) + .limit(1) + .select(field('awards').length().as('awardsLength')) + .execute(); + expectResults(snapshot, { + awardsLength: 3, + }); + }); - expectResults( - snapshot, - { - title: 'The Lord of the Rings', - rating: 4.7, - }, - {title: 'Dune', rating: 4.6}, - ); + it('can compute the length of a vector value', async () => { + const snapshot = await firestore + .pipeline() + .collection(randomCol.path) + .where(field('title').equal("The Hitchhiker's Guide to the Galaxy")) + .limit(1) + .select(field('embedding').length().as('embeddingLength')) + .execute(); + expectResults(snapshot, { + embeddingLength: 10, + }); + }); - snapshot = await pipeline - .offset(currPage++ * pageSize) - .limit(pageSize) - .execute(); - expectResults( - snapshot, - { - title: 'Jonathan Strange & Mr Norrell', - rating: 4.6, - }, - {title: 'The Master and Margarita', rating: 4.6}, - ); + it('can compute the length of a bytes value', async () => { + const snapshot = await firestore + .pipeline() + .collection(randomCol.path) + .select(constant('12é').as('value')) + .limit(1) + .select(field('value').byteLength().as('valueLength')) + .execute(); + expectResults(snapshot, { + valueLength: 4, + }); + }); - snapshot = await pipeline - .offset(currPage++ * pageSize) - .limit(pageSize) - .execute(); - expectResults( - snapshot, - { - title: 'A Long Way to a Small, Angry Planet', - rating: 4.6, - }, - { - title: 'Pride and Prejudice', - rating: 4.5, - }, - ); + it('can compute the natural logarithm of a numeric value', async () => { + const snapshot = await firestore + .pipeline() + .collection(randomCol.path) + .where(field('title').equal("The Hitchhiker's Guide to the Galaxy")) + .limit(1) + .select(field('rating').ln().as('lnRating')) + .execute(); + expect(snapshot.results[0]!.data().lnRating).to.be.closeTo(1.435, 0.001); + }); + + it('can compute the natural logarithm of a numeric value with the top-level function', async () => { + const snapshot = await firestore + .pipeline() + .collection(randomCol.path) + .where(field('title').equal("The Hitchhiker's Guide to the Galaxy")) + .limit(1) + .select(ln('rating').as('lnRating')) + .execute(); + expect(snapshot.results[0]!.data().lnRating).to.be.closeTo(1.435, 0.001); + }); + + it('can compute the natural logarithm of a numeric value with the top-level function', async () => { + const snapshot = await firestore + .pipeline() + .collection(randomCol.path) + .where(field('title').equal("The Hitchhiker's Guide to the Galaxy")) + .limit(1) + .select(ln('rating').as('lnRating')) + .execute(); + expectResults(snapshot, { + lnRating: 1.4350845252893227, }); }); - describe('stage options', () => { - describe('forceIndex', () => { - // SKIP: requires pre-existing index - it.skip('Collection Stage', async () => { - const snapshot = await firestore - .pipeline() - .collection({ - collection: randomCol, - forceIndex: 'unknown', - }) - .execute(); - expect(snapshot.results.length).to.equal(10); - }); + it('can round a numeric value', async () => { + const snapshot = await firestore + .pipeline() + .collection(randomCol.path) + .where(field('title').equal("The Hitchhiker's Guide to the Galaxy")) + .limit(1) + .select(field('rating').round().as('roundedRating')) + .execute(); + expectResults(snapshot, { + roundedRating: 4, + }); + }); - // SKIP: requires pre-existing index - it.skip('CollectionGroup Stage', async () => { - const snapshot = await firestore - .pipeline() - .collectionGroup({ - collectionId: randomCol.id, - forceIndex: 'unknown', - }) - .execute(); - expect(snapshot.results.length).to.equal(10); - }); + it('can round a numeric value with the top-level function', async () => { + const snapshot = await firestore + .pipeline() + .collection(randomCol.path) + .where(field('title').equal("The Hitchhiker's Guide to the Galaxy")) + .limit(1) + .select(round('rating').as('roundedRating')) + .execute(); + expectResults(snapshot, { + roundedRating: 4, }); }); - describe('stream', () => { - it('full results as expected', done => { - const ppl = firestore - .pipeline() - .collection(randomCol.path) - .sort(ascending('__name__')); - const snapshotStream = ppl.stream(); + it('can compute the square root of a numeric value', async () => { + const snapshot = await firestore + .pipeline() + .collection(randomCol.path) + .where(field('title').equal("The Hitchhiker's Guide to the Galaxy")) + .limit(1) + .select(field('rating').sqrt().as('sqrtRating')) + .execute(); + expectResults(snapshot, { + sqrtRating: 2.04939015319192, + }); + }); - const expected = [ - 'book1', - 'book10', - 'book2', - 'book3', - 'book4', - 'book5', - 'book6', - 'book7', - 'book8', - 'book9', - ]; - - let received = 0; - snapshotStream - .on('data', d => { - expect(d).to.be.an.instanceOf(PipelineResult); - const rslt = d as PipelineResult; - expect(rslt.id).to.equal(expected.shift()); - ++received; - }) - .on('end', () => { - expect(received).to.equal(10); - done(); - }); + it('can compute the square root of a numeric value with the top-level function', async () => { + const snapshot = await firestore + .pipeline() + .collection(randomCol.path) + .where(field('title').equal("The Hitchhiker's Guide to the Galaxy")) + .limit(1) + .select(sqrt('rating').as('sqrtRating')) + .execute(); + expectResults(snapshot, { + sqrtRating: 2.04939015319192, }); + }); - it('empty snapshot', done => { - const ppl = firestore.pipeline().collection(randomCol.path).limit(0); - const snapshotStream = ppl.stream(); + it('can reverse a string', async () => { + const snapshot = await firestore + .pipeline() + .collection(randomCol.path) + .where(field('title').equal("The Hitchhiker's Guide to the Galaxy")) + .limit(1) + .select(field('title').stringReverse().as('reversedTitle')) + .execute(); + expectResults(snapshot, { + reversedTitle: "yxalaG eht ot ediuG s'rekihhctiH ehT", + }); + }); - let received = 0; - snapshotStream - .on('data', _ => { - ++received; - }) - .on('end', () => { - expect(received).to.equal(0); - done(); - }); + it('can reverse a string with the top-level function', async () => { + const snapshot = await firestore + .pipeline() + .collection(randomCol.path) + .where(field('title').equal("The Hitchhiker's Guide to the Galaxy")) + .limit(1) + .select(stringReverse('title').as('reversedTitle')) + .execute(); + expectResults(snapshot, { + reversedTitle: "yxalaG eht ot ediuG s'rekihhctiH ehT", }); + }); - it('document transform', done => { - const ppl = firestore - .pipeline() - .collection(randomCol.path) - .sort(ascending('__name__')) - .limit(2) - .select('title'); - const snapshotStream = ppl.stream(); + it('supports Document_id', async () => { + let snapshot = await firestore + .pipeline() + .collection(randomCol.path) + .sort(field('rating').descending()) + .limit(1) + .select( + documentId(field('__name__')).as('docId'), + documentId(field('__path__')).as('noDocId'), + documentId(randomCol.doc('foo')).as('fromDocRef'), + ) + .execute(); + expectResults(snapshot, { + docId: 'book4', + noDocId: null, + fromDocRef: 'foo', + }); + snapshot = await firestore + .pipeline() + .collection(randomCol.path) + .sort(field('rating').descending()) + .limit(1) + .select(field('__name__').documentId().as('docId')) + .execute(); + expectResults(snapshot, { + docId: 'book4', + }); + }); - const expected = [ - {title: "The Hitchhiker's Guide to the Galaxy"}, - {title: 'Dune'}, - ]; - - let received = 0; - snapshotStream - .on('data', d => { - expect(d).to.be.an.instanceOf(PipelineResult); - const rslt = d as PipelineResult; - expect(rslt.data()).to.deep.equal(expected.shift()); - ++received; - }) - .on('end', () => { - expect(received).to.equal(2); - done(); - }); + it('supports substring', async () => { + let snapshot = await firestore + .pipeline() + .collection(randomCol.path) + .sort(field('rating').descending()) + .limit(1) + .select(substring('title', 9, 2).as('of')) + .execute(); + expectResults(snapshot, { + of: 'of', + }); + snapshot = await firestore + .pipeline() + .collection(randomCol.path) + .sort(field('rating').descending()) + .limit(1) + .select(field('title').substring(9, 2).as('of')) + .execute(); + expectResults(snapshot, { + of: 'of', }); }); - }, -); -// This is the Query integration tests from the lite API (no cache support) -// with some additional test cases added for more complete coverage. -// eslint-disable-next-line no-restricted-properties -(process.env.RUN_ENTERPRISE_TESTS ? describe : describe.skip)( - 'Query to Pipeline', - () => { - async function execute(ppl: Pipeline): Promise { - return ppl.execute(); - } + it('supports substring without length', async () => { + let snapshot = await firestore + .pipeline() + .collection(randomCol.path) + .sort(field('rating').descending()) + .limit(1) + .select(substring('title', 9).as('of')) + .execute(); + expectResults(snapshot, { + of: 'of the Rings', + }); + snapshot = await firestore + .pipeline() + .collection(randomCol.path) + .sort(field('rating').descending()) + .limit(1) + .select(field('title').substring(9).as('of')) + .execute(); + expectResults(snapshot, { + of: 'of the Rings', + }); + }); - async function testCollectionWithDocs( - docs: { - [id: string]: DocumentData; - }, - callback: (collRef: CollectionReference, db: Firestore) => Promise, - ): Promise { - const randomCol = getTestRoot(); - const firestore = randomCol.firestore; - for (const id in docs) { - const ref = randomCol.doc(id); - await ref.set(docs[id]); - } + it('arrayConcat works', async () => { + const snapshot = await firestore + .pipeline() + .collection(randomCol.path) + .where(field('title').equal("The Hitchhiker's Guide to the Galaxy")) + .select( + arrayConcat('tags', ['newTag1', 'newTag2'], field('tags'), [null]).as( + 'modifiedTags', + ), + ) + .limit(1) + .execute(); + expectResults(snapshot, { + modifiedTags: [ + 'comedy', + 'space', + 'adventure', + 'newTag1', + 'newTag2', + 'comedy', + 'space', + 'adventure', + null, + ], + }); + }); - try { - await callback(randomCol, firestore); - } finally { - await firestore.terminate(); - } - } + it('test toLower', async () => { + const snapshot = await firestore + .pipeline() + .collection(randomCol.path) + .sort(ascending('title')) + .select(toLower('author').as('lowercaseAuthor')) + .limit(1) + .execute(); + expectResults(snapshot, { + lowercaseAuthor: 'george orwell', + }); + }); - function verifyResults( - actual: PipelineSnapshot, - ...expected: DocumentData[] - ): void { - const results = actual.results; - expect(results.length).to.equal(expected.length); + it('test toUpper', async () => { + const snapshot = await firestore + .pipeline() + .collection(randomCol.path) + .sort(ascending('title')) + .select(toUpper('author').as('uppercaseAuthor')) + .limit(1) + .execute(); + expectResults(snapshot, {uppercaseAuthor: 'GEORGE ORWELL'}); + }); - for (let i = 0; i < expected.length; ++i) { - expect(results[i].data()).to.deep.equal(expected[i]); - } - } + it('testTrim', async () => { + const snapshot = await firestore + .pipeline() + .collection(randomCol.path) + .replaceWith( + map({ + spacedTitle: " The Hitchhiker's Guide to the Galaxy ", + userNameWithQuotes: '"alice"', + bytes: Uint8Array.from([0x00, 0x01, 0x02, 0x00, 0x00]), + }), + ) + .select( + trim('spacedTitle').as('trimmedTitle'), + field('spacedTitle'), + field('userNameWithQuotes').trim('"').as('userName'), + field('bytes') + .trim(Uint8Array.from([0x00])) + .as('bytes'), + ) + .limit(1) + .execute(); + expectResults(snapshot, { + spacedTitle: " The Hitchhiker's Guide to the Galaxy ", + trimmedTitle: "The Hitchhiker's Guide to the Galaxy", + userName: 'alice', + bytes: Uint8Array.from([0x01, 0x02]), + }); + }); - it('supports default query', () => { - return testCollectionWithDocs({1: {foo: 1}}, async (collRef, db) => { - const snapshot = await execute(db.pipeline().createFrom(collRef)); - verifyResults(snapshot, {foo: 1}); + it('test reverse', async () => { + const snapshot = await firestore + .pipeline() + .collection(randomCol.path) + .where(equal('title', '1984')) + .limit(1) + .select(reverse('title').as('reverseTitle')) + .execute(); + expectResults(snapshot, {reverseTitle: '4891'}); + }); + + it('testAbs', async () => { + const snapshot = await firestore + .pipeline() + .collection(randomCol.path) + .limit(1) + .select( + constant(-10).as('neg10'), + constant(-22.22).as('neg22'), + constant(1).as('pos1'), + ) + .select( + abs('neg10').as('10'), + abs(field('neg22')).as('22'), + field('pos1').as('1'), + ) + .execute(); + expectResults(snapshot, { + '10': 10, + '22': 22.22, + '1': 1, }); }); - it('supports filtered query', () => { - return testCollectionWithDocs( - { - 1: {foo: 1}, - 2: {foo: 2}, - }, - async (collRef, db) => { - const query1 = collRef.where('foo', '==', 1); - const snapshot = await execute(db.pipeline().createFrom(query1)); - verifyResults(snapshot, {foo: 1}); - }, + it('can compute the base-10 logarithm of a numeric value', async () => { + const snapshot = await firestore + .pipeline() + .collection(randomCol.path) + .where(field('title').equal('The Lord of the Rings')) + .limit(1) + .select(field('rating').log10().as('log10Rating')) + .execute(); + expect(snapshot.results[0]!.data().log10Rating).to.be.closeTo( + 0.672, + 0.001, ); }); - it('supports filtered query (with FieldPath)', () => { - return testCollectionWithDocs( - { - 1: {foo: 1}, - 2: {foo: 2}, - }, - async (collRef, db) => { - const query1 = collRef.where(new FieldPath('foo'), '==', 1); - const snapshot = await execute(db.pipeline().createFrom(query1)); - verifyResults(snapshot, {foo: 1}); - }, + it('can compute the base-10 logarithm of a numeric value with the top-level function', async () => { + const snapshot = await firestore + .pipeline() + .collection(randomCol.path) + .where(field('title').equal('The Lord of the Rings')) + .limit(1) + .select(log10('rating').as('log10Rating')) + .execute(); + expect(snapshot.results[0]!.data().log10Rating).to.be.closeTo( + 0.672, + 0.001, ); }); - it('supports ordered query (with default order)', () => { - return testCollectionWithDocs( - { - 1: {foo: 1}, - 2: {foo: 2}, - }, - async (collRef, db) => { - const query1 = collRef.orderBy('foo'); - const snapshot = await execute(db.pipeline().createFrom(query1)); - verifyResults(snapshot, {foo: 1}, {foo: 2}); - }, - ); + it('can concat fields', async () => { + const snapshot = await firestore + .pipeline() + .collection(randomCol.path) + .addFields( + concat('author', ' ', field('title')).as('display'), + field('author').concat(': ', field('title')).as('display2'), + ) + .where(equal('author', 'Douglas Adams')) + .select('display', 'display2') + .execute(); + expectResults(snapshot, { + display: "Douglas Adams The Hitchhiker's Guide to the Galaxy", + display2: "Douglas Adams: The Hitchhiker's Guide to the Galaxy", + }); }); - it('supports ordered query (with asc)', () => { - return testCollectionWithDocs( - { - 1: {foo: 1}, - 2: {foo: 2}, - }, - async (collRef, db) => { - const query1 = collRef.orderBy('foo', 'asc'); - const snapshot = await execute(db.pipeline().createFrom(query1)); - verifyResults(snapshot, {foo: 1}, {foo: 2}); - }, - ); + it('supports currentTimestamp', async () => { + const snapshot = await firestore + .pipeline() + .collection(randomCol.path) + .limit(1) + .addFields(currentTimestamp().as('now')) + .select('now') + .execute(); + const now = snapshot.results[0].get('now') as Timestamp; + expect(now).instanceof(Timestamp); + expect( + now.toDate().getUTCSeconds() - new Date().getUTCSeconds(), + ).lessThan(5000); }); - it('supports ordered query (with desc)', () => { - return testCollectionWithDocs( - { - 1: {foo: 1}, - 2: {foo: 2}, - }, - async (collRef, db) => { - const query1 = collRef.orderBy('foo', 'desc'); - const snapshot = await execute(db.pipeline().createFrom(query1)); - verifyResults(snapshot, {foo: 2}, {foo: 1}); - }, - ); + it('supports ifAbsent', async () => { + const snapshot = await firestore + .pipeline() + .collection(randomCol.path) + .limit(1) + .replaceWith( + map({ + title: 'foo', + }), + ) + .select( + ifAbsent('title', 'default title').as('title'), + field('name').ifAbsent('default name').as('name'), + field('name').ifAbsent(field('title')).as('nameOrTitle'), + ) + .execute(); + + expectResults(snapshot, { + title: 'foo', + name: 'default name', + nameOrTitle: 'foo', + }); }); - it('supports limit query', () => { - return testCollectionWithDocs( - { - 1: {foo: 1}, - 2: {foo: 2}, - }, - async (collRef, db) => { - const query1 = collRef.orderBy('foo').limit(1); - const snapshot = await execute(db.pipeline().createFrom(query1)); - verifyResults(snapshot, {foo: 1}); - }, - ); + it('supports join', async () => { + const snapshot = await firestore + .pipeline() + .collection(randomCol.path) + .limit(1) + .replaceWith( + map({ + tags: ['foo', 'bar', 'baz'], + delimeter: '|', + }), + ) + .select(join('tags', ',').as('csv'), field('tags').join('|').as('or')) + .execute(); + + expectResults(snapshot, { + csv: 'foo,bar,baz', + or: 'foo|bar|baz', + }); }); - it('supports limitToLast query', () => { - return testCollectionWithDocs( - { - 1: {foo: 1}, - 2: {foo: 2}, - 3: {foo: 3}, - }, - async (collRef, db) => { - const query1 = collRef.orderBy('foo').limitToLast(2); - const snapshot = await execute(db.pipeline().createFrom(query1)); - verifyResults(snapshot, {foo: 2}, {foo: 3}); - }, - ); + it('can compute the sum of the elements in an array', async () => { + const snapshot = await firestore + .pipeline() + .collection(randomCol.path) + .where(field('title').equal('The Lord of the Rings')) + .limit(1) + .addFields(array([150, 200]).as('sales')) + .select(field('sales').arraySum().as('totalSales')) + .execute(); + expectResults(snapshot, { + totalSales: 350, + }); }); - it('supports startAt', () => { - return testCollectionWithDocs( - { - 1: {foo: 1}, - 2: {foo: 2}, - }, - async (collRef, db) => { - const query1 = collRef.orderBy('foo').startAt(2); - const snapshot = await execute(db.pipeline().createFrom(query1)); - verifyResults(snapshot, {foo: 2}); - }, - ); + it('can compute the sum of the elements in an array with the top-level function', async () => { + const snapshot = await firestore + .pipeline() + .collection(randomCol.path) + .where(field('title').equal('The Lord of the Rings')) + .limit(1) + .addFields(array([150, 200]).as('sales')) + .select(arraySum('sales').as('totalSales')) + .execute(); + expectResults(snapshot, { + totalSales: 350, + }); + }); + it('truncate timestamp', async () => { + const results = await firestore + .pipeline() + .collection(randomCol) + .limit(1) + .replaceWith( + map({ + timestamp: new Timestamp( + Date.UTC(2025, 10, 30, 1, 2, 3) / 1000, + 456789, + ), + }), + ) + .select( + timestampTruncate('timestamp', 'year').as('trunc_year'), + timestampTruncate(field('timestamp'), 'month').as('trunc_month'), + timestampTruncate(field('timestamp'), constant('day')).as( + 'trunc_day', + ), + field('timestamp') + .timestampTruncate(constant('day'), 'MST') + .as('trunc_day_mst'), + field('timestamp').timestampTruncate('hour').as('trunc_hour'), + field('timestamp') + .timestampTruncate(constant('minute')) + .as('trunc_minute'), + field('timestamp').timestampTruncate('second').as('trunc_second'), + ) + .execute(); + + expectResults(results, { + trunc_year: new Timestamp(Date.UTC(2025, 0) / 1000, 0), + trunc_month: new Timestamp(Date.UTC(2025, 10) / 1000, 0), + trunc_day: new Timestamp(Date.UTC(2025, 10, 30) / 1000, 0), + trunc_day_mst: new Timestamp( + Date.UTC(2025, 10, 29) / 1000 + 7 * 3600, + 0, + ), + trunc_hour: new Timestamp(Date.UTC(2025, 10, 30, 1) / 1000, 0), + trunc_minute: new Timestamp(Date.UTC(2025, 10, 30, 1, 2) / 1000, 0), + trunc_second: new Timestamp(Date.UTC(2025, 10, 30, 1, 2, 3) / 1000, 0), + }); }); - it('supports startAt with limitToLast', () => { - return testCollectionWithDocs( - { - 1: {foo: 1}, - 2: {foo: 2}, - 3: {foo: 3}, - 4: {foo: 4}, - 5: {foo: 5}, - }, - async (collRef, db) => { - const query1 = collRef.orderBy('foo').startAt(3).limitToLast(4); - const snapshot = await execute(db.pipeline().createFrom(query1)); - verifyResults(snapshot, {foo: 3}, {foo: 4}, {foo: 5}); - }, - ); + it('supports split', async () => { + const results = await firestore + .pipeline() + .collection(randomCol) + .limit(1) + .replaceWith( + map({ + csv: 'foo,bar,baz', + data: 'baz:bar:foo', + csvDelimeter: ',', + bytes: Uint8Array.from([0x01, 0x00, 0x02, 0x00, 0x03]), + }), + ) + .select( + split('csv', field('csvDelimeter')).as('csv'), + split(field('data'), ':').as('data'), + field('bytes') + .split(constant(Uint8Array.from([0x00]))) + .as('bytes'), + ) + .execute(); + + expectResults(results, { + csv: ['foo', 'bar', 'baz'], + data: ['baz', 'bar', 'foo'], + bytes: [ + Uint8Array.from([0x01]), + Uint8Array.from([0x02]), + Uint8Array.from([0x03]), + ], + }); + + void expect( + firestore + .pipeline() + .collection(randomCol) + .limit(1) + .replaceWith( + map({ + csv: 'foo,bar,baz', + }), + ) + .select( + field('csv') + .split(constant(Uint8Array.from([0x00]))) + .as('dontSplitStringAndBytes'), + ) + .execute(), + ).to.be.rejected; }); - it('supports endAt with limitToLast', () => { - return testCollectionWithDocs( - { - 1: {foo: 1}, - 2: {foo: 2}, - 3: {foo: 3}, - 4: {foo: 4}, - 5: {foo: 5}, - }, - async (collRef, db) => { - const query1 = collRef.orderBy('foo').endAt(3).limitToLast(2); - const snapshot = await execute(db.pipeline().createFrom(query1)); - verifyResults(snapshot, {foo: 2}, {foo: 3}); - }, - ); + it('supports type', async () => { + const result = await firestore + .pipeline() + .collection(randomCol) + .limit(1) + .replaceWith( + map({ + int: constant(1), + float: constant(1.1), + str: constant('a string'), + bool: constant(true), + null: constant(null), + geoPoint: constant(new GeoPoint(0.1, 0.2)), + timestamp: constant(new Timestamp(123456, 0)), + date: constant(new Date()), + bytes: constant(new Uint8Array([1, 2, 3, 4, 5, 6, 7, 0])), + docRef: constant(firestore.doc('foo/bar')), + vector: constant(FieldValue.vector([1, 2, 3])), + map: map({ + number: 1, + string: 'a string', + }), + array: array([1, 'a string']), + }), + ) + .select( + type('int').as('int'), + field('float').type().as('float'), + field('str').type().as('str'), + type('bool').as('bool'), + type('null').as('null'), + type('geoPoint').as('geoPoint'), + type('timestamp').as('timestamp'), + type('date').as('date'), + type('bytes').as('bytes'), + type('docRef').as('docRef'), + type('vector').as('vector'), + type('map').as('map'), + type('array').as('array'), + ) + .execute(); + + expectResults(result, { + int: 'int64', + float: 'float64', + str: 'string', + bool: 'boolean', + null: 'null', + geoPoint: 'geo_point', + timestamp: 'timestamp', + date: 'timestamp', + bytes: 'bytes', + docRef: 'reference', + vector: 'vector', + map: 'map', + array: 'array', + }); }); - it('supports startAfter (with DocumentSnapshot)', () => { - return testCollectionWithDocs( - { - 1: {id: 1, foo: 1, bar: 1, baz: 1}, - 2: {id: 2, foo: 1, bar: 1, baz: 2}, - 3: {id: 3, foo: 1, bar: 1, baz: 2}, - 4: {id: 4, foo: 1, bar: 2, baz: 1}, - 5: {id: 5, foo: 1, bar: 2, baz: 2}, - 6: {id: 6, foo: 1, bar: 2, baz: 2}, - 7: {id: 7, foo: 2, bar: 1, baz: 1}, - 8: {id: 8, foo: 2, bar: 1, baz: 2}, - 9: {id: 9, foo: 2, bar: 1, baz: 2}, - 10: {id: 10, foo: 2, bar: 2, baz: 1}, - 11: {id: 11, foo: 2, bar: 2, baz: 2}, - 12: {id: 12, foo: 2, bar: 2, baz: 2}, - }, - async (collRef, db) => { - let docRef = await collRef.doc('2').get(); - let query1 = collRef - .orderBy('foo') - .orderBy('bar') - .orderBy('baz') - .startAfter(docRef); - let snapshot = await execute(db.pipeline().createFrom(query1)); - verifyResults( - snapshot, - {id: 3, foo: 1, bar: 1, baz: 2}, - {id: 4, foo: 1, bar: 2, baz: 1}, - {id: 5, foo: 1, bar: 2, baz: 2}, - {id: 6, foo: 1, bar: 2, baz: 2}, - {id: 7, foo: 2, bar: 1, baz: 1}, - {id: 8, foo: 2, bar: 1, baz: 2}, - {id: 9, foo: 2, bar: 1, baz: 2}, - {id: 10, foo: 2, bar: 2, baz: 1}, - {id: 11, foo: 2, bar: 2, baz: 2}, - {id: 12, foo: 2, bar: 2, baz: 2}, - ); + // TODO(new-expression): Add new expression tests above this line + }); + + describe('pagination', () => { + let addedDocs: DocumentReference[] = []; + + /** + * Adds several books to the test collection. These + * additional books support pagination test scenarios + * that would otherwise not be possible with the original + * set of books. + * @param collectionReference + */ + async function addBooks( + collectionReference: CollectionReference, + ): Promise { + let docRef = collectionReference.doc('book11'); + addedDocs.push(docRef); + await docRef.set({ + title: 'Jonathan Strange & Mr Norrell', + author: 'Susanna Clarke', + genre: 'Fantasy', + published: 2004, + rating: 4.6, + tags: ['historical fantasy', 'magic', 'alternate history', 'england'], + awards: {hugo: false, nebula: false}, + }); + docRef = collectionReference.doc('book12'); + addedDocs.push(collectionReference.doc('book12')); + await docRef.set({ + title: 'The Master and Margarita', + author: 'Mikhail Bulgakov', + genre: 'Satire', + published: 1967, // Though written much earlier + rating: 4.6, + tags: [ + 'russian literature', + 'supernatural', + 'philosophy', + 'dark comedy', + ], + awards: {}, + }); + docRef = collectionReference.doc('book13'); + addedDocs.push(docRef); + await docRef.set({ + title: 'A Long Way to a Small, Angry Planet', + author: 'Becky Chambers', + genre: 'Science Fiction', + published: 2014, + rating: 4.6, + tags: ['space opera', 'found family', 'character-driven', 'optimistic'], + awards: {hugo: false, nebula: false, kitschies: true}, + }); + } - docRef = await collRef.doc('3').get(); - query1 = collRef - .orderBy('foo') - .orderBy('bar') - .orderBy('baz') - .startAfter(docRef); - snapshot = await execute(db.pipeline().createFrom(query1)); - verifyResults( - snapshot, - {id: 4, foo: 1, bar: 2, baz: 1}, - {id: 5, foo: 1, bar: 2, baz: 2}, - {id: 6, foo: 1, bar: 2, baz: 2}, - {id: 7, foo: 2, bar: 1, baz: 1}, - {id: 8, foo: 2, bar: 1, baz: 2}, - {id: 9, foo: 2, bar: 1, baz: 2}, - {id: 10, foo: 2, bar: 2, baz: 1}, - {id: 11, foo: 2, bar: 2, baz: 2}, - {id: 12, foo: 2, bar: 2, baz: 2}, - ); - }, - ); + afterEach(async () => { + for (let i = 0; i < addedDocs.length; i++) { + await addedDocs[i].delete(); + } + addedDocs = []; }); - it('supports startAt (with DocumentSnapshot)', () => { - return testCollectionWithDocs( - { - 1: {id: 1, foo: 1, bar: 1, baz: 1}, - 2: {id: 2, foo: 1, bar: 1, baz: 2}, - 3: {id: 3, foo: 1, bar: 1, baz: 2}, - 4: {id: 4, foo: 1, bar: 2, baz: 1}, - 5: {id: 5, foo: 1, bar: 2, baz: 2}, - 6: {id: 6, foo: 1, bar: 2, baz: 2}, - 7: {id: 7, foo: 2, bar: 1, baz: 1}, - 8: {id: 8, foo: 2, bar: 1, baz: 2}, - 9: {id: 9, foo: 2, bar: 1, baz: 2}, - 10: {id: 10, foo: 2, bar: 2, baz: 1}, - 11: {id: 11, foo: 2, bar: 2, baz: 2}, - 12: {id: 12, foo: 2, bar: 2, baz: 2}, - }, - async (collRef, db) => { - let docRef = await collRef.doc('2').get(); - let query1 = collRef - .orderBy('foo') - .orderBy('bar') - .orderBy('baz') - .startAt(docRef); - let snapshot = await execute(db.pipeline().createFrom(query1)); - verifyResults( - snapshot, - {id: 2, foo: 1, bar: 1, baz: 2}, - {id: 3, foo: 1, bar: 1, baz: 2}, - {id: 4, foo: 1, bar: 2, baz: 1}, - {id: 5, foo: 1, bar: 2, baz: 2}, - {id: 6, foo: 1, bar: 2, baz: 2}, - {id: 7, foo: 2, bar: 1, baz: 1}, - {id: 8, foo: 2, bar: 1, baz: 2}, - {id: 9, foo: 2, bar: 1, baz: 2}, - {id: 10, foo: 2, bar: 2, baz: 1}, - {id: 11, foo: 2, bar: 2, baz: 2}, - {id: 12, foo: 2, bar: 2, baz: 2}, - ); + it('supports pagination with filters', async () => { + await addBooks(randomCol); + const pageSize = 2; + const pipeline = firestore + .pipeline() + .collection(randomCol.path) + .select('title', 'rating', '__name__') + .sort(field('rating').descending(), field('__name__').ascending()); - docRef = await collRef.doc('3').get(); - query1 = collRef - .orderBy('foo') - .orderBy('bar') - .orderBy('baz') - .startAt(docRef); - snapshot = await execute(db.pipeline().createFrom(query1)); - verifyResults( - snapshot, - {id: 3, foo: 1, bar: 1, baz: 2}, - {id: 4, foo: 1, bar: 2, baz: 1}, - {id: 5, foo: 1, bar: 2, baz: 2}, - {id: 6, foo: 1, bar: 2, baz: 2}, - {id: 7, foo: 2, bar: 1, baz: 1}, - {id: 8, foo: 2, bar: 1, baz: 2}, - {id: 9, foo: 2, bar: 1, baz: 2}, - {id: 10, foo: 2, bar: 2, baz: 1}, - {id: 11, foo: 2, bar: 2, baz: 2}, - {id: 12, foo: 2, bar: 2, baz: 2}, - ); - }, + let snapshot = await pipeline.limit(pageSize).execute(); + + snapshot.results.forEach(r => console.log(JSON.stringify(r.data()))); + + expectResults( + snapshot, + {title: 'The Lord of the Rings', rating: 4.7}, + {title: 'Dune', rating: 4.6}, ); - }); - it('supports startAfter', () => { - return testCollectionWithDocs( - { - 1: {foo: 1}, - 2: {foo: 2}, - }, - async (collRef, db) => { - const query1 = collRef.orderBy('foo').startAfter(1); - const snapshot = await execute(db.pipeline().createFrom(query1)); - verifyResults(snapshot, {foo: 2}); - }, + const lastDoc = snapshot.results[snapshot.results.length - 1]; + + snapshot = await pipeline + .where( + or( + and( + field('rating').equal(lastDoc.get('rating')), + field('__name__').greaterThan(lastDoc.ref), + ), + field('rating').lessThan(lastDoc.get('rating')), + ), + ) + .limit(pageSize) + .execute(); + expectResults( + snapshot, + {title: 'Jonathan Strange & Mr Norrell', rating: 4.6}, + {title: 'The Master and Margarita', rating: 4.6}, ); }); - it('supports endAt', () => { - return testCollectionWithDocs( - { - 1: {foo: 1}, - 2: {foo: 2}, - }, - async (collRef, db) => { - const query1 = collRef.orderBy('foo').endAt(1); - const snapshot = await execute(db.pipeline().createFrom(query1)); - verifyResults(snapshot, {foo: 1}); - }, - ); - }); + it('supports pagination with offsets', async () => { + await addBooks(randomCol); + + const secondFilterField = '__name__'; + + const pipeline = firestore + .pipeline() + .collection(randomCol.path) + .select('title', 'rating', secondFilterField) + .sort( + field('rating').descending(), + field(secondFilterField).ascending(), + ); + + const pageSize = 2; + let currPage = 0; - it('supports endBefore', () => { - return testCollectionWithDocs( + let snapshot = await pipeline + .offset(currPage++ * pageSize) + .limit(pageSize) + .execute(); + + expectResults( + snapshot, { - 1: {foo: 1}, - 2: {foo: 2}, - }, - async (collRef, db) => { - const query1 = collRef.orderBy('foo').endBefore(2); - const snapshot = await execute(db.pipeline().createFrom(query1)); - verifyResults(snapshot, {foo: 1}); + title: 'The Lord of the Rings', + rating: 4.7, }, + {title: 'Dune', rating: 4.6}, ); - }); - it('supports pagination', () => { - return testCollectionWithDocs( + snapshot = await pipeline + .offset(currPage++ * pageSize) + .limit(pageSize) + .execute(); + expectResults( + snapshot, { - 1: {foo: 1}, - 2: {foo: 2}, - }, - async (collRef, db) => { - let query1 = collRef.orderBy('foo').limit(1); - const pipeline1 = db.pipeline().createFrom(query1); - let snapshot = await execute(pipeline1); - verifyResults(snapshot, {foo: 1}); - - // Pass the document snapshot from the previous snapshot - query1 = query1.startAfter(snapshot.results[0].get('foo')); - snapshot = await execute(db.pipeline().createFrom(query1)); - verifyResults(snapshot, {foo: 2}); + title: 'Jonathan Strange & Mr Norrell', + rating: 4.6, }, + {title: 'The Master and Margarita', rating: 4.6}, ); - }); - it('supports pagination on DocumentIds', () => { - return testCollectionWithDocs( + snapshot = await pipeline + .offset(currPage++ * pageSize) + .limit(pageSize) + .execute(); + expectResults( + snapshot, { - 1: {foo: 1}, - 2: {foo: 2}, + title: 'A Long Way to a Small, Angry Planet', + rating: 4.6, }, - async (collRef, db) => { - let query1 = collRef - .orderBy('foo') - .orderBy(FieldPath.documentId(), 'asc') - .limit(1); - const pipeline1 = db.pipeline().createFrom(query1); - let snapshot = await execute(pipeline1); - verifyResults(snapshot, {foo: 1}); - - // Pass the document snapshot from the previous snapshot - query1 = query1.startAfter( - snapshot.results[0].get('foo'), - snapshot.results[0].ref?.id, - ); - snapshot = await execute(db.pipeline().createFrom(query1)); - verifyResults(snapshot, {foo: 2}); + { + title: 'Pride and Prejudice', + rating: 4.5, }, ); }); + }); - it('supports collection groups', () => { - return testCollectionWithDocs({}, async (collRef, db) => { - const collectionGroupId = `${collRef.id}group`; + describe('stage options', () => { + describe('forceIndex', () => { + // SKIP: requires pre-existing index + it.skip('Collection Stage', async () => { + const snapshot = await firestore + .pipeline() + .collection({ + collection: randomCol, + forceIndex: 'unknown', + }) + .execute(); + expect(snapshot.results.length).to.equal(10); + }); - const fooDoc = collRef.firestore.doc( - `${collRef.id}/foo/${collectionGroupId}/doc1`, - ); - const barDoc = collRef.firestore.doc( - `${collRef.id}/bar/baz/boo/${collectionGroupId}/doc2`, - ); - await fooDoc.set({foo: 1}); - await barDoc.set({bar: 1}); + // SKIP: requires pre-existing index + it.skip('CollectionGroup Stage', async () => { + const snapshot = await firestore + .pipeline() + .collectionGroup({ + collectionId: randomCol.id, + forceIndex: 'unknown', + }) + .execute(); + expect(snapshot.results.length).to.equal(10); + }); + }); + }); + + describe('stream', () => { + it('full results as expected', done => { + const ppl = firestore + .pipeline() + .collection(randomCol.path) + .sort(ascending('__name__')); + const snapshotStream = ppl.stream(); + + const expected = [ + 'book1', + 'book10', + 'book2', + 'book3', + 'book4', + 'book5', + 'book6', + 'book7', + 'book8', + 'book9', + ]; + + let received = 0; + snapshotStream + .on('data', d => { + expect(d).to.be.an.instanceOf(PipelineResult); + const rslt = d as PipelineResult; + expect(rslt.id).to.equal(expected.shift()); + ++received; + }) + .on('end', () => { + expect(received).to.equal(10); + done(); + }); + }); - const query1 = collRef.firestore.collectionGroup(collectionGroupId); - const snapshot = await execute(db.pipeline().createFrom(query1)); + it('empty snapshot', done => { + const ppl = firestore.pipeline().collection(randomCol.path).limit(0); + const snapshotStream = ppl.stream(); - verifyResults(snapshot, {bar: 1}, {foo: 1}); - }); + let received = 0; + snapshotStream + .on('data', _ => { + ++received; + }) + .on('end', () => { + expect(received).to.equal(0); + done(); + }); }); - it('supports query over collection path with special characters', () => { - return testCollectionWithDocs({}, async (collRef, db) => { - const docWithSpecials = collRef.doc('so!@#$%^&*()_+special'); + it('document transform', done => { + const ppl = firestore + .pipeline() + .collection(randomCol.path) + .sort(ascending('__name__')) + .limit(2) + .select('title'); + const snapshotStream = ppl.stream(); + + const expected = [ + {title: "The Hitchhiker's Guide to the Galaxy"}, + {title: 'Dune'}, + ]; + + let received = 0; + snapshotStream + .on('data', d => { + expect(d).to.be.an.instanceOf(PipelineResult); + const rslt = d as PipelineResult; + expect(rslt.data()).to.deep.equal(expected.shift()); + ++received; + }) + .on('end', () => { + expect(received).to.equal(2); + done(); + }); + }); + }); +}); - const collectionWithSpecials = docWithSpecials.collection( - 'so!@#$%^&*()_+special', - ); - await collectionWithSpecials.add({foo: 1}); - await collectionWithSpecials.add({foo: 2}); +// This is the Query integration tests from the lite API (no cache support) +// with some additional test cases added for more complete coverage. +// eslint-disable-next-line no-restricted-properties +describe.skipClassic('Query to Pipeline', () => { + async function execute(ppl: Pipeline): Promise { + return ppl.execute(); + } - const snapshot = await execute( - db - .pipeline() - .createFrom(collectionWithSpecials.orderBy('foo', 'asc')), - ); + async function testCollectionWithDocs( + docs: { + [id: string]: DocumentData; + }, + callback: (collRef: CollectionReference, db: Firestore) => Promise, + ): Promise { + const randomCol = getTestRoot(); + const firestore = randomCol.firestore; + for (const id in docs) { + const ref = randomCol.doc(id); + await ref.set(docs[id]); + } - verifyResults(snapshot, {foo: 1}, {foo: 2}); - }); - }); + try { + await callback(randomCol, firestore); + } finally { + await firestore.terminate(); + } + } - it('supports multiple inequality on same field', () => { - return testCollectionWithDocs( - { - '01': {id: 1, foo: 1, bar: 1, baz: 1}, - '02': {id: 2, foo: 1, bar: 1, baz: 2}, - '03': {id: 3, foo: 1, bar: 1, baz: 2}, - '04': {id: 4, foo: 1, bar: 2, baz: 1}, - '05': {id: 5, foo: 1, bar: 2, baz: 2}, - '06': {id: 6, foo: 1, bar: 2, baz: 2}, - '07': {id: 7, foo: 2, bar: 1, baz: 1}, - '08': {id: 8, foo: 2, bar: 1, baz: 2}, - '09': {id: 9, foo: 2, bar: 1, baz: 2}, - '10': {id: 10, foo: 2, bar: 2, baz: 1}, - '11': {id: 11, foo: 2, bar: 2, baz: 2}, - '12': {id: 12, foo: 2, bar: 2, baz: 2}, - }, - async (collRef, db) => { - const query1 = collRef.where( - Filter.and( - Filter.where('id', '>', 2), - Filter.where('id', '<=', 10), - ), - ); - const snapshot = await execute(db.pipeline().createFrom(query1)); - verifyResults( - snapshot, - {id: 3, foo: 1, bar: 1, baz: 2}, - {id: 4, foo: 1, bar: 2, baz: 1}, - {id: 5, foo: 1, bar: 2, baz: 2}, - {id: 6, foo: 1, bar: 2, baz: 2}, - {id: 7, foo: 2, bar: 1, baz: 1}, - {id: 8, foo: 2, bar: 1, baz: 2}, - {id: 9, foo: 2, bar: 1, baz: 2}, - {id: 10, foo: 2, bar: 2, baz: 1}, - ); - }, - ); - }); + function verifyResults( + actual: PipelineSnapshot, + ...expected: DocumentData[] + ): void { + const results = actual.results; + expect(results.length).to.equal(expected.length); - it('supports multiple inequality on different fields', () => { - return testCollectionWithDocs( - { - '01': {id: 1, foo: 1, bar: 1, baz: 1}, - '02': {id: 2, foo: 1, bar: 1, baz: 2}, - '03': {id: 3, foo: 1, bar: 1, baz: 2}, - '04': {id: 4, foo: 1, bar: 2, baz: 1}, - '05': {id: 5, foo: 1, bar: 2, baz: 2}, - '06': {id: 6, foo: 1, bar: 2, baz: 2}, - '07': {id: 7, foo: 2, bar: 1, baz: 1}, - '08': {id: 8, foo: 2, bar: 1, baz: 2}, - '09': {id: 9, foo: 2, bar: 1, baz: 2}, - '10': {id: 10, foo: 2, bar: 2, baz: 1}, - '11': {id: 11, foo: 2, bar: 2, baz: 2}, - '12': {id: 12, foo: 2, bar: 2, baz: 2}, - }, - async (collRef, db) => { - const query1 = collRef.where( - Filter.and( - Filter.where('id', '>=', 2), - Filter.where('baz', '<', 2), - ), - ); - const snapshot = await execute(db.pipeline().createFrom(query1)); - verifyResults( - snapshot, - {id: 4, foo: 1, bar: 2, baz: 1}, - {id: 7, foo: 2, bar: 1, baz: 1}, - {id: 10, foo: 2, bar: 2, baz: 1}, - ); - }, - ); + for (let i = 0; i < expected.length; ++i) { + expect(results[i].data()).to.deep.equal(expected[i]); + } + } + + it('supports default query', () => { + return testCollectionWithDocs({1: {foo: 1}}, async (collRef, db) => { + const snapshot = await execute(db.pipeline().createFrom(collRef)); + verifyResults(snapshot, {foo: 1}); }); + }); - it('supports collectionGroup query', () => { - return testCollectionWithDocs({1: {foo: 1}}, async (collRef, db) => { - const snapshot = await execute( - db.pipeline().createFrom(db.collectionGroup(collRef.id)), - ); + it('supports filtered query', () => { + return testCollectionWithDocs( + { + 1: {foo: 1}, + 2: {foo: 2}, + }, + async (collRef, db) => { + const query1 = collRef.where('foo', '==', 1); + const snapshot = await execute(db.pipeline().createFrom(query1)); verifyResults(snapshot, {foo: 1}); - }); - }); + }, + ); + }); + + it('supports filtered query (with FieldPath)', () => { + return testCollectionWithDocs( + { + 1: {foo: 1}, + 2: {foo: 2}, + }, + async (collRef, db) => { + const query1 = collRef.where(new FieldPath('foo'), '==', 1); + const snapshot = await execute(db.pipeline().createFrom(query1)); + verifyResults(snapshot, {foo: 1}); + }, + ); + }); + + it('supports ordered query (with default order)', () => { + return testCollectionWithDocs( + { + 1: {foo: 1}, + 2: {foo: 2}, + }, + async (collRef, db) => { + const query1 = collRef.orderBy('foo'); + const snapshot = await execute(db.pipeline().createFrom(query1)); + verifyResults(snapshot, {foo: 1}, {foo: 2}); + }, + ); + }); + + it('supports ordered query (with asc)', () => { + return testCollectionWithDocs( + { + 1: {foo: 1}, + 2: {foo: 2}, + }, + async (collRef, db) => { + const query1 = collRef.orderBy('foo', 'asc'); + const snapshot = await execute(db.pipeline().createFrom(query1)); + verifyResults(snapshot, {foo: 1}, {foo: 2}); + }, + ); + }); + + it('supports ordered query (with desc)', () => { + return testCollectionWithDocs( + { + 1: {foo: 1}, + 2: {foo: 2}, + }, + async (collRef, db) => { + const query1 = collRef.orderBy('foo', 'desc'); + const snapshot = await execute(db.pipeline().createFrom(query1)); + verifyResults(snapshot, {foo: 2}, {foo: 1}); + }, + ); + }); + + it('supports limit query', () => { + return testCollectionWithDocs( + { + 1: {foo: 1}, + 2: {foo: 2}, + }, + async (collRef, db) => { + const query1 = collRef.orderBy('foo').limit(1); + const snapshot = await execute(db.pipeline().createFrom(query1)); + verifyResults(snapshot, {foo: 1}); + }, + ); + }); + + it('supports limitToLast query', () => { + return testCollectionWithDocs( + { + 1: {foo: 1}, + 2: {foo: 2}, + 3: {foo: 3}, + }, + async (collRef, db) => { + const query1 = collRef.orderBy('foo').limitToLast(2); + const snapshot = await execute(db.pipeline().createFrom(query1)); + verifyResults(snapshot, {foo: 2}, {foo: 3}); + }, + ); + }); + + it('supports startAt', () => { + return testCollectionWithDocs( + { + 1: {foo: 1}, + 2: {foo: 2}, + }, + async (collRef, db) => { + const query1 = collRef.orderBy('foo').startAt(2); + const snapshot = await execute(db.pipeline().createFrom(query1)); + verifyResults(snapshot, {foo: 2}); + }, + ); + }); + + it('supports startAt with limitToLast', () => { + return testCollectionWithDocs( + { + 1: {foo: 1}, + 2: {foo: 2}, + 3: {foo: 3}, + 4: {foo: 4}, + 5: {foo: 5}, + }, + async (collRef, db) => { + const query1 = collRef.orderBy('foo').startAt(3).limitToLast(4); + const snapshot = await execute(db.pipeline().createFrom(query1)); + verifyResults(snapshot, {foo: 3}, {foo: 4}, {foo: 5}); + }, + ); + }); + + it('supports endAt with limitToLast', () => { + return testCollectionWithDocs( + { + 1: {foo: 1}, + 2: {foo: 2}, + 3: {foo: 3}, + 4: {foo: 4}, + 5: {foo: 5}, + }, + async (collRef, db) => { + const query1 = collRef.orderBy('foo').endAt(3).limitToLast(2); + const snapshot = await execute(db.pipeline().createFrom(query1)); + verifyResults(snapshot, {foo: 2}, {foo: 3}); + }, + ); + }); + + it('supports startAfter (with DocumentSnapshot)', () => { + return testCollectionWithDocs( + { + 1: {id: 1, foo: 1, bar: 1, baz: 1}, + 2: {id: 2, foo: 1, bar: 1, baz: 2}, + 3: {id: 3, foo: 1, bar: 1, baz: 2}, + 4: {id: 4, foo: 1, bar: 2, baz: 1}, + 5: {id: 5, foo: 1, bar: 2, baz: 2}, + 6: {id: 6, foo: 1, bar: 2, baz: 2}, + 7: {id: 7, foo: 2, bar: 1, baz: 1}, + 8: {id: 8, foo: 2, bar: 1, baz: 2}, + 9: {id: 9, foo: 2, bar: 1, baz: 2}, + 10: {id: 10, foo: 2, bar: 2, baz: 1}, + 11: {id: 11, foo: 2, bar: 2, baz: 2}, + 12: {id: 12, foo: 2, bar: 2, baz: 2}, + }, + async (collRef, db) => { + let docRef = await collRef.doc('2').get(); + let query1 = collRef + .orderBy('foo') + .orderBy('bar') + .orderBy('baz') + .startAfter(docRef); + let snapshot = await execute(db.pipeline().createFrom(query1)); + verifyResults( + snapshot, + {id: 3, foo: 1, bar: 1, baz: 2}, + {id: 4, foo: 1, bar: 2, baz: 1}, + {id: 5, foo: 1, bar: 2, baz: 2}, + {id: 6, foo: 1, bar: 2, baz: 2}, + {id: 7, foo: 2, bar: 1, baz: 1}, + {id: 8, foo: 2, bar: 1, baz: 2}, + {id: 9, foo: 2, bar: 1, baz: 2}, + {id: 10, foo: 2, bar: 2, baz: 1}, + {id: 11, foo: 2, bar: 2, baz: 2}, + {id: 12, foo: 2, bar: 2, baz: 2}, + ); - it('supports equal nan', () => { - return testCollectionWithDocs( - { - 1: {foo: 1, bar: NaN}, - 2: {foo: 2, bar: 1}, - 3: {foo: 3, bar: 'bar'}, - }, - async (collRef, db) => { - const query1 = collRef.where('bar', '==', NaN); - const classicSnapshot = await query1.get(); - const classicData = classicSnapshot.docs.map(d => d.data()); + docRef = await collRef.doc('3').get(); + query1 = collRef + .orderBy('foo') + .orderBy('bar') + .orderBy('baz') + .startAfter(docRef); + snapshot = await execute(db.pipeline().createFrom(query1)); + verifyResults( + snapshot, + {id: 4, foo: 1, bar: 2, baz: 1}, + {id: 5, foo: 1, bar: 2, baz: 2}, + {id: 6, foo: 1, bar: 2, baz: 2}, + {id: 7, foo: 2, bar: 1, baz: 1}, + {id: 8, foo: 2, bar: 1, baz: 2}, + {id: 9, foo: 2, bar: 1, baz: 2}, + {id: 10, foo: 2, bar: 2, baz: 1}, + {id: 11, foo: 2, bar: 2, baz: 2}, + {id: 12, foo: 2, bar: 2, baz: 2}, + ); + }, + ); + }); + + it('supports startAt (with DocumentSnapshot)', () => { + return testCollectionWithDocs( + { + 1: {id: 1, foo: 1, bar: 1, baz: 1}, + 2: {id: 2, foo: 1, bar: 1, baz: 2}, + 3: {id: 3, foo: 1, bar: 1, baz: 2}, + 4: {id: 4, foo: 1, bar: 2, baz: 1}, + 5: {id: 5, foo: 1, bar: 2, baz: 2}, + 6: {id: 6, foo: 1, bar: 2, baz: 2}, + 7: {id: 7, foo: 2, bar: 1, baz: 1}, + 8: {id: 8, foo: 2, bar: 1, baz: 2}, + 9: {id: 9, foo: 2, bar: 1, baz: 2}, + 10: {id: 10, foo: 2, bar: 2, baz: 1}, + 11: {id: 11, foo: 2, bar: 2, baz: 2}, + 12: {id: 12, foo: 2, bar: 2, baz: 2}, + }, + async (collRef, db) => { + let docRef = await collRef.doc('2').get(); + let query1 = collRef + .orderBy('foo') + .orderBy('bar') + .orderBy('baz') + .startAt(docRef); + let snapshot = await execute(db.pipeline().createFrom(query1)); + verifyResults( + snapshot, + {id: 2, foo: 1, bar: 1, baz: 2}, + {id: 3, foo: 1, bar: 1, baz: 2}, + {id: 4, foo: 1, bar: 2, baz: 1}, + {id: 5, foo: 1, bar: 2, baz: 2}, + {id: 6, foo: 1, bar: 2, baz: 2}, + {id: 7, foo: 2, bar: 1, baz: 1}, + {id: 8, foo: 2, bar: 1, baz: 2}, + {id: 9, foo: 2, bar: 1, baz: 2}, + {id: 10, foo: 2, bar: 2, baz: 1}, + {id: 11, foo: 2, bar: 2, baz: 2}, + {id: 12, foo: 2, bar: 2, baz: 2}, + ); - const snapshot = await execute(db.pipeline().createFrom(query1)); - verifyResults(snapshot, ...classicData); - }, - ); - }); + docRef = await collRef.doc('3').get(); + query1 = collRef + .orderBy('foo') + .orderBy('bar') + .orderBy('baz') + .startAt(docRef); + snapshot = await execute(db.pipeline().createFrom(query1)); + verifyResults( + snapshot, + {id: 3, foo: 1, bar: 1, baz: 2}, + {id: 4, foo: 1, bar: 2, baz: 1}, + {id: 5, foo: 1, bar: 2, baz: 2}, + {id: 6, foo: 1, bar: 2, baz: 2}, + {id: 7, foo: 2, bar: 1, baz: 1}, + {id: 8, foo: 2, bar: 1, baz: 2}, + {id: 9, foo: 2, bar: 1, baz: 2}, + {id: 10, foo: 2, bar: 2, baz: 1}, + {id: 11, foo: 2, bar: 2, baz: 2}, + {id: 12, foo: 2, bar: 2, baz: 2}, + ); + }, + ); + }); + + it('supports startAfter', () => { + return testCollectionWithDocs( + { + 1: {foo: 1}, + 2: {foo: 2}, + }, + async (collRef, db) => { + const query1 = collRef.orderBy('foo').startAfter(1); + const snapshot = await execute(db.pipeline().createFrom(query1)); + verifyResults(snapshot, {foo: 2}); + }, + ); + }); + + it('supports endAt', () => { + return testCollectionWithDocs( + { + 1: {foo: 1}, + 2: {foo: 2}, + }, + async (collRef, db) => { + const query1 = collRef.orderBy('foo').endAt(1); + const snapshot = await execute(db.pipeline().createFrom(query1)); + verifyResults(snapshot, {foo: 1}); + }, + ); + }); + + it('supports endBefore', () => { + return testCollectionWithDocs( + { + 1: {foo: 1}, + 2: {foo: 2}, + }, + async (collRef, db) => { + const query1 = collRef.orderBy('foo').endBefore(2); + const snapshot = await execute(db.pipeline().createFrom(query1)); + verifyResults(snapshot, {foo: 1}); + }, + ); + }); + + it('supports pagination', () => { + return testCollectionWithDocs( + { + 1: {foo: 1}, + 2: {foo: 2}, + }, + async (collRef, db) => { + let query1 = collRef.orderBy('foo').limit(1); + const pipeline1 = db.pipeline().createFrom(query1); + let snapshot = await execute(pipeline1); + verifyResults(snapshot, {foo: 1}); - it('supports notEqual nan', () => { - return testCollectionWithDocs( - { - 1: {foo: 1, bar: NaN}, - 2: {foo: 2, bar: 1}, - 3: {foo: 3, bar: 'bar'}, - }, - async (collRef, db) => { - const query1 = collRef.where('bar', '!=', NaN); + // Pass the document snapshot from the previous snapshot + query1 = query1.startAfter(snapshot.results[0].get('foo')); + snapshot = await execute(db.pipeline().createFrom(query1)); + verifyResults(snapshot, {foo: 2}); + }, + ); + }); + + it('supports pagination on DocumentIds', () => { + return testCollectionWithDocs( + { + 1: {foo: 1}, + 2: {foo: 2}, + }, + async (collRef, db) => { + let query1 = collRef + .orderBy('foo') + .orderBy(FieldPath.documentId(), 'asc') + .limit(1); + const pipeline1 = db.pipeline().createFrom(query1); + let snapshot = await execute(pipeline1); + verifyResults(snapshot, {foo: 1}); + + // Pass the document snapshot from the previous snapshot + query1 = query1.startAfter( + snapshot.results[0].get('foo'), + snapshot.results[0].ref?.id, + ); + snapshot = await execute(db.pipeline().createFrom(query1)); + verifyResults(snapshot, {foo: 2}); + }, + ); + }); - const classicSnapshot = await query1.get(); - const classicData = classicSnapshot.docs.map(d => d.data()); + it('supports collection groups', () => { + return testCollectionWithDocs({}, async (collRef, db) => { + const collectionGroupId = `${collRef.id}group`; - const snapshot = await execute(db.pipeline().createFrom(query1)); - verifyResults(snapshot, ...classicData); - }, + const fooDoc = collRef.firestore.doc( + `${collRef.id}/foo/${collectionGroupId}/doc1`, ); - }); + const barDoc = collRef.firestore.doc( + `${collRef.id}/bar/baz/boo/${collectionGroupId}/doc2`, + ); + await fooDoc.set({foo: 1}); + await barDoc.set({bar: 1}); - it('supports equal null', () => { - return testCollectionWithDocs( - { - 1: {foo: 1, bar: null}, - 2: {foo: 2, bar: 1}, - }, - async (collRef, db) => { - const query1 = collRef.where('bar', '==', null); - const classicSnapshot = await query1.get(); - const classicData = classicSnapshot.docs.map(d => d.data()); + const query1 = collRef.firestore.collectionGroup(collectionGroupId); + const snapshot = await execute(db.pipeline().createFrom(query1)); - const snapshot = await execute(db.pipeline().createFrom(query1)); - verifyResults(snapshot, ...classicData); - }, - ); + verifyResults(snapshot, {bar: 1}, {foo: 1}); }); + }); - it('supports notEqual null', () => { - return testCollectionWithDocs( - { - 1: {foo: 1, bar: null}, - 2: {foo: 2, bar: 1}, - }, - async (collRef, db) => { - const query1 = collRef.where('bar', '!=', null); - const classicSnapshot = await query1.get(); - const classicData = classicSnapshot.docs.map(d => d.data()); - const snapshot = await execute(db.pipeline().createFrom(query1)); - verifyResults(snapshot, ...classicData); - }, - ); - }); + it('supports query over collection path with special characters', () => { + return testCollectionWithDocs({}, async (collRef, db) => { + const docWithSpecials = collRef.doc('so!@#$%^&*()_+special'); - it('supports notEqual', () => { - return testCollectionWithDocs( - { - 1: {foo: 1, bar: 0}, - 2: {foo: 2, bar: 1}, - }, - async (collRef, db) => { - const query1 = collRef.where('bar', '!=', 0); - const snapshot = await execute(db.pipeline().createFrom(query1)); - verifyResults(snapshot, {foo: 2, bar: 1}); - }, + const collectionWithSpecials = docWithSpecials.collection( + 'so!@#$%^&*()_+special', ); - }); + await collectionWithSpecials.add({foo: 1}); + await collectionWithSpecials.add({foo: 2}); - it('supports array contains', () => { - return testCollectionWithDocs( - { - 1: {foo: 1, bar: [0, 2, 4, 6]}, - 2: {foo: 2, bar: [1, 3, 5, 7]}, - }, - async (collRef, db) => { - const query1 = collRef.where('bar', 'array-contains', 4); - const snapshot = await execute(db.pipeline().createFrom(query1)); - verifyResults(snapshot, {foo: 1, bar: [0, 2, 4, 6]}); - }, + const snapshot = await execute( + db.pipeline().createFrom(collectionWithSpecials.orderBy('foo', 'asc')), ); - }); - it('supports array contains any', () => { - return testCollectionWithDocs( - { - 1: {foo: 1, bar: [0, 2, 4, 6]}, - 2: {foo: 2, bar: [1, 3, 5, 7]}, - 3: {foo: 3, bar: [10, 20, 30, 40]}, - }, - async (collRef, db) => { - const query1 = collRef.where('bar', 'array-contains-any', [4, 5]); - const snapshot = await execute(db.pipeline().createFrom(query1)); - verifyResults( - snapshot, - {foo: 1, bar: [0, 2, 4, 6]}, - {foo: 2, bar: [1, 3, 5, 7]}, - ); - }, - ); + verifyResults(snapshot, {foo: 1}, {foo: 2}); }); + }); + + it('supports multiple inequality on same field', () => { + return testCollectionWithDocs( + { + '01': {id: 1, foo: 1, bar: 1, baz: 1}, + '02': {id: 2, foo: 1, bar: 1, baz: 2}, + '03': {id: 3, foo: 1, bar: 1, baz: 2}, + '04': {id: 4, foo: 1, bar: 2, baz: 1}, + '05': {id: 5, foo: 1, bar: 2, baz: 2}, + '06': {id: 6, foo: 1, bar: 2, baz: 2}, + '07': {id: 7, foo: 2, bar: 1, baz: 1}, + '08': {id: 8, foo: 2, bar: 1, baz: 2}, + '09': {id: 9, foo: 2, bar: 1, baz: 2}, + '10': {id: 10, foo: 2, bar: 2, baz: 1}, + '11': {id: 11, foo: 2, bar: 2, baz: 2}, + '12': {id: 12, foo: 2, bar: 2, baz: 2}, + }, + async (collRef, db) => { + const query1 = collRef.where( + Filter.and(Filter.where('id', '>', 2), Filter.where('id', '<=', 10)), + ); + const snapshot = await execute(db.pipeline().createFrom(query1)); + verifyResults( + snapshot, + {id: 3, foo: 1, bar: 1, baz: 2}, + {id: 4, foo: 1, bar: 2, baz: 1}, + {id: 5, foo: 1, bar: 2, baz: 2}, + {id: 6, foo: 1, bar: 2, baz: 2}, + {id: 7, foo: 2, bar: 1, baz: 1}, + {id: 8, foo: 2, bar: 1, baz: 2}, + {id: 9, foo: 2, bar: 1, baz: 2}, + {id: 10, foo: 2, bar: 2, baz: 1}, + ); + }, + ); + }); + + it('supports multiple inequality on different fields', () => { + return testCollectionWithDocs( + { + '01': {id: 1, foo: 1, bar: 1, baz: 1}, + '02': {id: 2, foo: 1, bar: 1, baz: 2}, + '03': {id: 3, foo: 1, bar: 1, baz: 2}, + '04': {id: 4, foo: 1, bar: 2, baz: 1}, + '05': {id: 5, foo: 1, bar: 2, baz: 2}, + '06': {id: 6, foo: 1, bar: 2, baz: 2}, + '07': {id: 7, foo: 2, bar: 1, baz: 1}, + '08': {id: 8, foo: 2, bar: 1, baz: 2}, + '09': {id: 9, foo: 2, bar: 1, baz: 2}, + '10': {id: 10, foo: 2, bar: 2, baz: 1}, + '11': {id: 11, foo: 2, bar: 2, baz: 2}, + '12': {id: 12, foo: 2, bar: 2, baz: 2}, + }, + async (collRef, db) => { + const query1 = collRef.where( + Filter.and(Filter.where('id', '>=', 2), Filter.where('baz', '<', 2)), + ); + const snapshot = await execute(db.pipeline().createFrom(query1)); + verifyResults( + snapshot, + {id: 4, foo: 1, bar: 2, baz: 1}, + {id: 7, foo: 2, bar: 1, baz: 1}, + {id: 10, foo: 2, bar: 2, baz: 1}, + ); + }, + ); + }); - it('supports in', () => { - return testCollectionWithDocs( - { - 1: {foo: 1, bar: 2}, - 2: {foo: 2}, - 3: {foo: 3, bar: 10}, - }, - async (collRef, db) => { - const query1 = collRef.where('bar', 'in', [0, 10, 20]); - const snapshot = await execute(db.pipeline().createFrom(query1)); - verifyResults(snapshot, {foo: 3, bar: 10}); - }, + it('supports collectionGroup query', () => { + return testCollectionWithDocs({1: {foo: 1}}, async (collRef, db) => { + const snapshot = await execute( + db.pipeline().createFrom(db.collectionGroup(collRef.id)), ); + verifyResults(snapshot, {foo: 1}); }); + }); + + it('supports equal nan', () => { + return testCollectionWithDocs( + { + 1: {foo: 1, bar: NaN}, + 2: {foo: 2, bar: 1}, + 3: {foo: 3, bar: 'bar'}, + }, + async (collRef, db) => { + const query1 = collRef.where('bar', '==', NaN); + const classicSnapshot = await query1.get(); + const classicData = classicSnapshot.docs.map(d => d.data()); - it('supports in with 1', () => { - return testCollectionWithDocs( - { - 1: {foo: 1, bar: 2}, - 2: {foo: 2}, - 3: {foo: 3, bar: 10}, - }, - async (collRef, db) => { - const query1 = collRef.where('bar', 'in', [2]); - const snapshot = await execute(db.pipeline().createFrom(query1)); - verifyResults(snapshot, {foo: 1, bar: 2}); - }, - ); - }); + const snapshot = await execute(db.pipeline().createFrom(query1)); + verifyResults(snapshot, ...classicData); + }, + ); + }); + + it('supports notEqual nan', () => { + return testCollectionWithDocs( + { + 1: {foo: 1, bar: NaN}, + 2: {foo: 2, bar: 1}, + 3: {foo: 3, bar: 'bar'}, + }, + async (collRef, db) => { + const query1 = collRef.where('bar', '!=', NaN); - it('supports not in', () => { - return testCollectionWithDocs( - { - 1: {foo: 1, bar: 2}, - 2: {foo: 2, bar: 1}, - 3: {foo: 3, bar: 10}, - }, - async (collRef, db) => { - const query1 = collRef - .where('bar', 'not-in', [0, 10, 20]) - .orderBy('foo'); - const snapshot = await execute(db.pipeline().createFrom(query1)); - verifyResults(snapshot, {foo: 1, bar: 2}, {foo: 2, bar: 1}); - }, - ); - }); + const classicSnapshot = await query1.get(); + const classicData = classicSnapshot.docs.map(d => d.data()); - it('supports not in with 1', () => { - return testCollectionWithDocs( - { - 1: {foo: 1, bar: 2}, - 2: {foo: 2}, - 3: {foo: 3, bar: 10}, - }, - async (collRef, db) => { - const query1 = collRef.where('bar', 'not-in', [2]); - const snapshot = await execute(db.pipeline().createFrom(query1)); - verifyResults(snapshot, {foo: 3, bar: 10}); - }, - ); - }); + const snapshot = await execute(db.pipeline().createFrom(query1)); + verifyResults(snapshot, ...classicData); + }, + ); + }); + + it('supports equal null', () => { + return testCollectionWithDocs( + { + 1: {foo: 1, bar: null}, + 2: {foo: 2, bar: 1}, + }, + async (collRef, db) => { + const query1 = collRef.where('bar', '==', null); + const classicSnapshot = await query1.get(); + const classicData = classicSnapshot.docs.map(d => d.data()); - it('supports or operator', () => { - return testCollectionWithDocs( - { - 1: {foo: 1, bar: 2}, - 2: {foo: 2, bar: 0}, - 3: {foo: 3, bar: 10}, - }, - async (collRef, db) => { - const query1 = collRef - .where( - Filter.or( - Filter.where('bar', '==', 2), - Filter.where('foo', '==', 3), - ), - ) - .orderBy('foo'); - const snapshot = await execute(db.pipeline().createFrom(query1)); - verifyResults(snapshot, {foo: 1, bar: 2}, {foo: 3, bar: 10}); - }, - ); - }); - }, -); + const snapshot = await execute(db.pipeline().createFrom(query1)); + verifyResults(snapshot, ...classicData); + }, + ); + }); + + it('supports notEqual null', () => { + return testCollectionWithDocs( + { + 1: {foo: 1, bar: null}, + 2: {foo: 2, bar: 1}, + }, + async (collRef, db) => { + const query1 = collRef.where('bar', '!=', null); + const classicSnapshot = await query1.get(); + const classicData = classicSnapshot.docs.map(d => d.data()); + const snapshot = await execute(db.pipeline().createFrom(query1)); + verifyResults(snapshot, ...classicData); + }, + ); + }); + + it('supports notEqual', () => { + return testCollectionWithDocs( + { + 1: {foo: 1, bar: 0}, + 2: {foo: 2, bar: 1}, + }, + async (collRef, db) => { + const query1 = collRef.where('bar', '!=', 0); + const snapshot = await execute(db.pipeline().createFrom(query1)); + verifyResults(snapshot, {foo: 2, bar: 1}); + }, + ); + }); + + it('supports array contains', () => { + return testCollectionWithDocs( + { + 1: {foo: 1, bar: [0, 2, 4, 6]}, + 2: {foo: 2, bar: [1, 3, 5, 7]}, + }, + async (collRef, db) => { + const query1 = collRef.where('bar', 'array-contains', 4); + const snapshot = await execute(db.pipeline().createFrom(query1)); + verifyResults(snapshot, {foo: 1, bar: [0, 2, 4, 6]}); + }, + ); + }); + + it('supports array contains any', () => { + return testCollectionWithDocs( + { + 1: {foo: 1, bar: [0, 2, 4, 6]}, + 2: {foo: 2, bar: [1, 3, 5, 7]}, + 3: {foo: 3, bar: [10, 20, 30, 40]}, + }, + async (collRef, db) => { + const query1 = collRef.where('bar', 'array-contains-any', [4, 5]); + const snapshot = await execute(db.pipeline().createFrom(query1)); + verifyResults( + snapshot, + {foo: 1, bar: [0, 2, 4, 6]}, + {foo: 2, bar: [1, 3, 5, 7]}, + ); + }, + ); + }); + + it('supports in', () => { + return testCollectionWithDocs( + { + 1: {foo: 1, bar: 2}, + 2: {foo: 2}, + 3: {foo: 3, bar: 10}, + }, + async (collRef, db) => { + const query1 = collRef.where('bar', 'in', [0, 10, 20]); + const snapshot = await execute(db.pipeline().createFrom(query1)); + verifyResults(snapshot, {foo: 3, bar: 10}); + }, + ); + }); + + it('supports in with 1', () => { + return testCollectionWithDocs( + { + 1: {foo: 1, bar: 2}, + 2: {foo: 2}, + 3: {foo: 3, bar: 10}, + }, + async (collRef, db) => { + const query1 = collRef.where('bar', 'in', [2]); + const snapshot = await execute(db.pipeline().createFrom(query1)); + verifyResults(snapshot, {foo: 1, bar: 2}); + }, + ); + }); + + it('supports not in', () => { + return testCollectionWithDocs( + { + 1: {foo: 1, bar: 2}, + 2: {foo: 2, bar: 1}, + 3: {foo: 3, bar: 10}, + }, + async (collRef, db) => { + const query1 = collRef + .where('bar', 'not-in', [0, 10, 20]) + .orderBy('foo'); + const snapshot = await execute(db.pipeline().createFrom(query1)); + verifyResults(snapshot, {foo: 1, bar: 2}, {foo: 2, bar: 1}); + }, + ); + }); + + it('supports not in with 1', () => { + return testCollectionWithDocs( + { + 1: {foo: 1, bar: 2}, + 2: {foo: 2}, + 3: {foo: 3, bar: 10}, + }, + async (collRef, db) => { + const query1 = collRef.where('bar', 'not-in', [2]); + const snapshot = await execute(db.pipeline().createFrom(query1)); + verifyResults(snapshot, {foo: 2}, {foo: 3, bar: 10}); + }, + ); + }); + + it('supports or operator', () => { + return testCollectionWithDocs( + { + 1: {foo: 1, bar: 2}, + 2: {foo: 2, bar: 0}, + 3: {foo: 3, bar: 10}, + }, + async (collRef, db) => { + const query1 = collRef + .where( + Filter.or( + Filter.where('bar', '==', 2), + Filter.where('foo', '==', 3), + ), + ) + .orderBy('foo'); + const snapshot = await execute(db.pipeline().createFrom(query1)); + verifyResults(snapshot, {foo: 1, bar: 2}, {foo: 3, bar: 10}); + }, + ); + }); +}); diff --git a/dev/system-test/query.ts b/dev/system-test/query.ts index 39b8d40d1..7a0205d6f 100644 --- a/dev/system-test/query.ts +++ b/dev/system-test/query.ts @@ -33,12 +33,13 @@ import { QueryDocumentSnapshot, VectorQuery, VectorQuerySnapshot, + setLogFunction, } from '../src'; import {verifyInstance} from '../test/util/helpers'; import {DeferredPromise, getTestRoot} from './firestore'; import {IndexTestHelper} from './index_test_helper'; -describe.skipClassic('Query class', () => { +describe.skipClassic('Query and Pipeline Compare - Enterprise DB', () => { interface PaginatedResults { pages: number; docs: QueryDocumentSnapshot[]; @@ -602,8 +603,7 @@ describe.skipClassic('Query class', () => { expectDocs(res, {count: 2}, {count: 3}); }); - // TODO waiting on implicit sort order decision - it.skipEnterprise('supports not-in', async () => { + it('supports not-in', async () => { await addDocs( {zip: 98101}, {zip: 91102}, @@ -613,7 +613,9 @@ describe.skipClassic('Query class', () => { {zip: {zip: 98101}}, ); let res = await compareQueryAndPipeline( - randomCol.where('zip', 'not-in', [98101, 98103]), + randomCol + .where('zip', 'not-in', [98101, 98103]) + .orderBy(FieldPath.documentId()), ); expectDocs( res, @@ -624,7 +626,10 @@ describe.skipClassic('Query class', () => { ); res = await compareQueryAndPipeline( - randomCol.where('zip', 'not-in', [NaN]), + randomCol + .where('zip', 'not-in', [NaN]) + .orderBy('zip') + .orderBy(FieldPath.documentId()), ); expectDocs( res, @@ -637,9 +642,17 @@ describe.skipClassic('Query class', () => { ); res = await compareQueryAndPipeline( - randomCol.where('zip', 'not-in', [null]), + randomCol.where('zip', 'not-in', [null]).orderBy(FieldPath.documentId()), + ); + expectDocs( + res, + {zip: 98101}, + {zip: 91102}, + {zip: 98103}, + {zip: [98101]}, + {zip: ['98101', {zip: 98101}]}, + {zip: {zip: 98101}}, ); - expect(res.size).to.equal(0); }); it('supports not-in with document ID array', async () => { @@ -674,7 +687,8 @@ describe.skipClassic('Query class', () => { expectDocs(res, {count: 1}, {count: 2}); }); - it('supports array-contains-any', async () => { + // TODO waiting fix for `The function array_contains(...) requires `Array` but got `LONG`. + it.skipEnterprise('supports array-contains-any', async () => { await addDocs( {array: [42]}, {array: ['a', 42, 'c']}, @@ -821,6 +835,7 @@ describe.skipClassic('Query class', () => { }); it('can use offset() method with get()', async () => { + setLogFunction(console.log); await addDocs({foo: 'a'}, {foo: 'b'}); const res = await compareQueryAndPipeline( randomCol.orderBy('foo').offset(1), @@ -885,6 +900,7 @@ describe.skipClassic('Query class', () => { }); }); + // TODO (enterprise) waiting for implicit sort order support it('supports pagination with where() clauses', () => { const batch = firestore.batch(); @@ -892,7 +908,11 @@ describe.skipClassic('Query class', () => { batch.set(randomCol.doc('doc' + i), {val: i}); } - const query = randomCol.where('val', '>=', 1).limit(3); + const query = randomCol + .where('val', '>=', 1) + .limit(3) + .orderBy('val') + .orderBy(FieldPath.documentId()); return batch .commit() @@ -985,7 +1005,8 @@ describe.skipClassic('Query class', () => { expect(received).to.equal(2); }); - it('can query collection groups', async () => { + // TODO (enterprise) waiting on implicit sor order decision + it.skipEnterprise('can query collection groups', async () => { // Use `randomCol` to get a random collection group name to use but ensure // it starts with 'b' for predictable ordering. const collectionGroup = 'b' + randomCol.id; @@ -1021,7 +1042,7 @@ describe.skipClassic('Query class', () => { ]); }); - // TODO wait for implicit sort order decision + // TODO (enterprise) wait for implicit sort order support it.skipEnterprise( 'can query collection groups with startAt / endAt by arbitrary documentId', async () => { @@ -1066,46 +1087,50 @@ describe.skipClassic('Query class', () => { }, ); - it('can query collection groups with where filters on arbitrary documentId', async () => { - // Use `randomCol` to get a random collection group name to use but - // ensure it starts with 'b' for predictable ordering. - const collectionGroup = 'b' + randomCol.id; + // TODO (enterprise) wait for implicit sort order support + it.skipEnterprise( + 'can query collection groups with where filters on arbitrary documentId', + async () => { + // Use `randomCol` to get a random collection group name to use but + // ensure it starts with 'b' for predictable ordering. + const collectionGroup = 'b' + randomCol.id; - const docPaths = [ - `a/a/${collectionGroup}/cg-doc1`, - `a/b/a/b/${collectionGroup}/cg-doc2`, - `a/b/${collectionGroup}/cg-doc3`, - `a/b/c/d/${collectionGroup}/cg-doc4`, - `a/c/${collectionGroup}/cg-doc5`, - `${collectionGroup}/cg-doc6`, - 'a/b/nope/nope', - ]; - const batch = firestore.batch(); - for (const docPath of docPaths) { - batch.set(firestore.doc(docPath), {x: 1}); - } - await batch.commit(); + const docPaths = [ + `a/a/${collectionGroup}/cg-doc1`, + `a/b/a/b/${collectionGroup}/cg-doc2`, + `a/b/${collectionGroup}/cg-doc3`, + `a/b/c/d/${collectionGroup}/cg-doc4`, + `a/c/${collectionGroup}/cg-doc5`, + `${collectionGroup}/cg-doc6`, + 'a/b/nope/nope', + ]; + const batch = firestore.batch(); + for (const docPath of docPaths) { + batch.set(firestore.doc(docPath), {x: 1}); + } + await batch.commit(); - let querySnapshot = await compareQueryAndPipeline( - firestore - .collectionGroup(collectionGroup) - .where(FieldPath.documentId(), '>=', 'a/b') - .where(FieldPath.documentId(), '<=', 'a/b0'), - ); - expect(querySnapshot.docs.map(d => d.id)).to.deep.equal([ - 'cg-doc2', - 'cg-doc3', - 'cg-doc4', - ]); + let querySnapshot = await compareQueryAndPipeline( + firestore + .collectionGroup(collectionGroup) + .where(FieldPath.documentId(), '>=', 'a/b') + .where(FieldPath.documentId(), '<=', 'a/b0'), + ); + expect(querySnapshot.docs.map(d => d.id)).to.deep.equal([ + 'cg-doc2', + 'cg-doc3', + 'cg-doc4', + ]); - querySnapshot = await compareQueryAndPipeline( - firestore - .collectionGroup(collectionGroup) - .where(FieldPath.documentId(), '>', 'a/b') - .where(FieldPath.documentId(), '<', `a/b/${collectionGroup}/cg-doc3`), - ); - expect(querySnapshot.docs.map(d => d.id)).to.deep.equal(['cg-doc2']); - }); + querySnapshot = await compareQueryAndPipeline( + firestore + .collectionGroup(collectionGroup) + .where(FieldPath.documentId(), '>', 'a/b') + .where(FieldPath.documentId(), '<', `a/b/${collectionGroup}/cg-doc3`), + ); + expect(querySnapshot.docs.map(d => d.id)).to.deep.equal(['cg-doc2']); + }, + ); it('can query large collections', async () => { // @grpc/grpc-js v0.4.1 failed to deliver the full set of query results for @@ -1120,7 +1145,7 @@ describe.skipClassic('Query class', () => { expect(snapshot.size).to.equal(100); }); - // TODO wait for implicit sort order decision + // TODO (enterprise) wait for implicit sort order support it.skipEnterprise('supports OR queries', async () => { const collection = await testCollectionWithDocs({ doc1: {a: 1, b: 0}, @@ -1199,84 +1224,82 @@ describe.skipClassic('Query class', () => { // Skip this test if running against production because it results in a 'missing index' error. // The Firestore Emulator, however, does serve these queries. - (process.env.FIRESTORE_EMULATOR_HOST === undefined ? it : it)( - 'supports OR queries with composite indexes', - async () => { - const collection = await testCollectionWithDocs({ - doc1: {a: 1, b: 0}, - doc2: {a: 2, b: 1}, - doc3: {a: 3, b: 2}, - doc4: {a: 1, b: 3}, - doc5: {a: 1, b: 1}, - }); + // TODO (enterprise) wait for implicit sort order support + it.skipEnterprise('supports OR queries with composite indexes', async () => { + const collection = await testCollectionWithDocs({ + doc1: {a: 1, b: 0}, + doc2: {a: 2, b: 1}, + doc3: {a: 3, b: 2}, + doc4: {a: 1, b: 3}, + doc5: {a: 1, b: 1}, + }); - // with one inequality: a>2 || b==1. - expectDocs( - await compareQueryAndPipeline( - collection.where( - Filter.or(Filter.where('a', '>', 2), Filter.where('b', '==', 1)), - ), + // with one inequality: a>2 || b==1. + expectDocs( + await compareQueryAndPipeline( + collection.where( + Filter.or(Filter.where('a', '>', 2), Filter.where('b', '==', 1)), ), - 'doc5', - 'doc2', - 'doc3', - ); + ), + 'doc5', + 'doc2', + 'doc3', + ); - // Test with limits (implicit order by ASC): (a==1) || (b > 0) LIMIT 2 - expectDocs( - await compareQueryAndPipeline( - collection - .where( - Filter.or(Filter.where('a', '==', 1), Filter.where('b', '>', 0)), - ) - .limit(2), - ), - 'doc1', - 'doc2', - ); + // Test with limits (implicit order by ASC): (a==1) || (b > 0) LIMIT 2 + expectDocs( + await compareQueryAndPipeline( + collection + .where( + Filter.or(Filter.where('a', '==', 1), Filter.where('b', '>', 0)), + ) + .limit(2), + ), + 'doc1', + 'doc2', + ); - // Test with limits (explicit order by): (a==1) || (b > 0) LIMIT_TO_LAST 2 - // Note: The public query API does not allow implicit ordering when limitToLast is used. - expectDocs( - await compareQueryAndPipeline( - collection - .where( - Filter.or(Filter.where('a', '==', 1), Filter.where('b', '>', 0)), - ) - .limitToLast(2) - .orderBy('b'), - ), - 'doc3', - 'doc4', - ); + // Test with limits (explicit order by): (a==1) || (b > 0) LIMIT_TO_LAST 2 + // Note: The public query API does not allow implicit ordering when limitToLast is used. + expectDocs( + await compareQueryAndPipeline( + collection + .where( + Filter.or(Filter.where('a', '==', 1), Filter.where('b', '>', 0)), + ) + .limitToLast(2) + .orderBy('b'), + ), + 'doc3', + 'doc4', + ); - // Test with limits (explicit order by ASC): (a==2) || (b == 1) ORDER BY a LIMIT 1 - expectDocs( - await compareQueryAndPipeline( - collection - .where( - Filter.or(Filter.where('a', '==', 2), Filter.where('b', '==', 1)), - ) - .limit(1) - .orderBy('a'), - ), - 'doc5', - ); + // Test with limits (explicit order by ASC): (a==2) || (b == 1) ORDER BY a LIMIT 1 + expectDocs( + await compareQueryAndPipeline( + collection + .where( + Filter.or(Filter.where('a', '==', 2), Filter.where('b', '==', 1)), + ) + .limit(1) + .orderBy('a'), + ), + 'doc5', + ); - // Test with limits (explicit order by DESC): (a==2) || (b == 1) ORDER BY a LIMIT 1 - expectDocs( - await compareQueryAndPipeline( - collection - .where( - Filter.or(Filter.where('a', '==', 2), Filter.where('b', '==', 1)), - ) - .limit(1) - .orderBy('a', 'desc'), - ), - 'doc2', - ); - }, - ); + // Test with limits (explicit order by DESC): (a==2) || (b == 1) ORDER BY a LIMIT 1 + expectDocs( + await compareQueryAndPipeline( + collection + .where( + Filter.or(Filter.where('a', '==', 2), Filter.where('b', '==', 1)), + ) + .limit(1) + .orderBy('a', 'desc'), + ), + 'doc2', + ); + }); it('supports OR queries on documents with missing fields', async () => { const collection = await testCollectionWithDocs({ @@ -1293,9 +1316,11 @@ describe.skipClassic('Query class', () => { // allowed if the document matches at least one disjunction term. expectDocs( await compareQueryAndPipeline( - collection.where( - Filter.or(Filter.where('a', '==', 1), Filter.where('b', '==', 1)), - ), + collection + .where( + Filter.or(Filter.where('a', '==', 1), Filter.where('b', '==', 1)), + ) + .orderBy(FieldPath.documentId()), ), 'doc1', 'doc2', @@ -1305,77 +1330,74 @@ describe.skipClassic('Query class', () => { }); // Skip this test if running against production because it results in a 'missing index' error. - // TODO Enterprise wait for implicit sort order decision - it.skipClassic.skipEnterprise( - 'supports OR queries on documents with missing fields', - async () => { - const collection = await testCollectionWithDocs({ - doc1: {a: 1, b: 0}, - doc2: {b: 1}, - doc3: {a: 3, b: 2}, - doc4: {a: 1, b: 3}, - doc5: {a: 1}, - doc6: {a: 2}, - }); + // TODO (enterprise) wait for implicit sort order support + it.skip('supports OR queries on documents with missing fields', async () => { + const collection = await testCollectionWithDocs({ + doc1: {a: 1, b: 0}, + doc2: {b: 1}, + doc3: {a: 3, b: 2}, + doc4: {a: 1, b: 3}, + doc5: {a: 1}, + doc6: {a: 2}, + }); - // Query: a==1 || b==1 order by a. - // doc2 should not be included because it's missing the field 'a', and we have "orderBy a". - expectDocs( - await compareQueryAndPipeline( - collection - .where( - Filter.or(Filter.where('a', '==', 1), Filter.where('b', '==', 1)), - ) - .orderBy('a'), - ), - 'doc1', - 'doc4', - 'doc5', - ); + // Query: a==1 || b==1 order by a. + // doc2 should not be included because it's missing the field 'a', and we have "orderBy a". + expectDocs( + await compareQueryAndPipeline( + collection + .where( + Filter.or(Filter.where('a', '==', 1), Filter.where('b', '==', 1)), + ) + .orderBy('a'), + ), + 'doc1', + 'doc4', + 'doc5', + ); - // Query: a==1 || b==1 order by b. - // doc5 should not be included because it's missing the field 'b', and we have "orderBy b". - expectDocs( - await compareQueryAndPipeline( - collection - .where( - Filter.or(Filter.where('a', '==', 1), Filter.where('b', '==', 1)), - ) - .orderBy('b'), - ), - 'doc1', - 'doc2', - 'doc4', - ); + // Query: a==1 || b==1 order by b. + // doc5 should not be included because it's missing the field 'b', and we have "orderBy b". + expectDocs( + await compareQueryAndPipeline( + collection + .where( + Filter.or(Filter.where('a', '==', 1), Filter.where('b', '==', 1)), + ) + .orderBy('b'), + ), + 'doc1', + 'doc2', + 'doc4', + ); - // Query: a>2 || b==1. - // This query has an implicit 'order by a'. - // doc2 should not be included because it's missing the field 'a'. - expectDocs( - await compareQueryAndPipeline( - collection.where( - Filter.or(Filter.where('a', '>', 2), Filter.where('b', '==', 1)), - ), + // Query: a>2 || b==1. + // This query has an implicit 'order by a'. + // doc2 should not be included because it's missing the field 'a'. + expectDocs( + await compareQueryAndPipeline( + collection.where( + Filter.or(Filter.where('a', '>', 2), Filter.where('b', '==', 1)), ), - 'doc3', - ); + ), + 'doc3', + ); - // Query: a>1 || b==1 order by a order by b. - // doc6 should not be included because it's missing the field 'b'. - // doc2 should not be included because it's missing the field 'a'. - expectDocs( - await compareQueryAndPipeline( - collection - .where( - Filter.or(Filter.where('a', '>', 1), Filter.where('b', '==', 1)), - ) - .orderBy('a') - .orderBy('b'), - ), - 'doc3', - ); - }, - ); + // Query: a>1 || b==1 order by a order by b. + // doc6 should not be included because it's missing the field 'b'. + // doc2 should not be included because it's missing the field 'a'. + expectDocs( + await compareQueryAndPipeline( + collection + .where( + Filter.or(Filter.where('a', '>', 1), Filter.where('b', '==', 1)), + ) + .orderBy('a') + .orderBy('b'), + ), + 'doc3', + ); + }); it('supports OR queries with in', async () => { const collection = await testCollectionWithDocs({ @@ -1390,12 +1412,14 @@ describe.skipClassic('Query class', () => { // Query: a==2 || b in [2, 3] expectDocs( await compareQueryAndPipeline( - collection.where( - Filter.or( - Filter.where('a', '==', 2), - Filter.where('b', 'in', [2, 3]), - ), - ), + collection + .where( + Filter.or( + Filter.where('a', '==', 2), + Filter.where('b', 'in', [2, 3]), + ), + ) + .orderBy(FieldPath.documentId()), ), 'doc3', 'doc4', @@ -1404,37 +1428,39 @@ describe.skipClassic('Query class', () => { }); // Skip this test if running against production because it results in a 'missing index' error. - // The Firestore Emulator, however, does serve these queries. - (process.env.FIRESTORE_EMULATOR_HOST === undefined ? it : it)( - 'supports OR queries with not-in', - async () => { - const collection = await testCollectionWithDocs({ - doc1: {a: 1, b: 0}, - doc2: {b: 1}, - doc3: {a: 3, b: 2}, - doc4: {a: 1, b: 3}, - doc5: {a: 1}, - doc6: {a: 2}, - }); + it('supports OR queries with not-in', async () => { + setLogFunction(console.log); + const collection = await testCollectionWithDocs({ + doc1: {a: 1, b: 0}, + doc2: {b: 1}, + doc3: {a: 3, b: 2}, + doc4: {a: 1, b: 3}, + doc5: {a: 1}, + doc6: {a: 2}, + }); - // a==2 || (b != 2 && b != 3) - // Has implicit "orderBy b" - expectDocs( - await compareQueryAndPipeline( - collection.where( + // a==2 || (b != 2 && b != 3) + // Has implicit "orderBy b" + expectDocs( + await compareQueryAndPipeline( + collection + .where( Filter.or( Filter.where('a', '==', 2), Filter.where('b', 'not-in', [2, 3]), ), - ), - ), - 'doc1', - 'doc2', - ); - }, - ); + ) + .orderBy(FieldPath.documentId()), + ), + 'doc1', + 'doc2', + 'doc5', + 'doc6', + ); + }); - it('supports OR queries with array membership', async () => { + // TODO (enterprise) wait for implicit sort order support + it.skipEnterprise('supports OR queries with array membership', async () => { const collection = await testCollectionWithDocs({ doc1: {a: 1, b: [0]}, doc2: {b: [1]}, diff --git a/dev/system-test/tracing.ts b/dev/system-test/tracing.ts index e5497c850..8f18613aa 100644 --- a/dev/system-test/tracing.ts +++ b/dev/system-test/tracing.ts @@ -156,7 +156,7 @@ class SpanData { } } -describe('Tracing Tests', () => { +describe.skipEnterprise('Tracing Tests', () => { let firestore: Firestore; let tracerProvider: NodeTracerProvider; let inMemorySpanExporter: InMemorySpanExporter;

    include:samples/generated/v1/firestore_admin.get_index.jsinclude:samples/generated/v1/firestore_admin.get_index.jsinclude:samples/generated/v1/firestore_admin.delete_index.jsinclude:samples/generated/v1/firestore_admin.delete_index.jsinclude:samples/generated/v1/firestore_admin.get_field.jsinclude:samples/generated/v1/firestore_admin.get_field.jsinclude:samples/generated/v1/firestore_admin.get_database.jsinclude:samples/generated/v1/firestore_admin.get_database.jsinclude:samples/generated/v1/firestore_admin.list_databases.jsinclude:samples/generated/v1/firestore_admin.list_databases.jsinclude:samples/generated/v1/firestore_admin.get_backup.jsinclude:samples/generated/v1/firestore_admin.create_user_creds.jsinclude:samples/generated/v1/firestore_admin.list_backups.jsinclude:samples/generated/v1/firestore_admin.get_user_creds.jsinclude:samples/generated/v1/firestore_admin.list_user_creds.jsinclude:samples/generated/v1/firestore_admin.enable_user_creds.jsinclude:samples/generated/v1/firestore_admin.disable_user_creds.jsinclude:samples/generated/v1/firestore_admin.reset_user_password.jsinclude:samples/generated/v1/firestore_admin.delete_user_creds.jsinclude:samples/generated/v1/firestore_admin.get_backup.jsinclude:samples/generated/v1/firestore_admin.list_backups.jsinclude:samples/generated/v1/firestore_admin.delete_backup.jsinclude:samples/generated/v1/firestore_admin.delete_backup.jsinclude:samples/generated/v1/firestore_admin.create_backup_schedule.jsinclude:samples/generated/v1/firestore_admin.create_backup_schedule.jsinclude:samples/generated/v1/firestore_admin.get_backup_schedule.jsinclude:samples/generated/v1/firestore_admin.get_backup_schedule.jsinclude:samples/generated/v1/firestore_admin.list_backup_schedules.jsinclude:samples/generated/v1/firestore_admin.list_backup_schedules.jsinclude:samples/generated/v1/firestore_admin.update_backup_schedule.jsinclude:samples/generated/v1/firestore_admin.update_backup_schedule.jsinclude:samples/generated/v1/firestore_admin.delete_backup_schedule.jsinclude:samples/generated/v1/firestore_admin.delete_backup_schedule.jsinclude:samples/generated/v1/firestore_admin.create_index.jsinclude:samples/generated/v1/firestore_admin.create_index.jsinclude:samples/generated/v1/firestore_admin.create_index.jsinclude:samples/generated/v1/firestore_admin.create_index.jsinclude:samples/generated/v1/firestore_admin.update_field.jsinclude:samples/generated/v1/firestore_admin.update_field.jsinclude:samples/generated/v1/firestore_admin.update_field.jsinclude:samples/generated/v1/firestore_admin.update_field.jsinclude:samples/generated/v1/firestore_admin.export_documents.jsinclude:samples/generated/v1/firestore_admin.export_documents.jsinclude:samples/generated/v1/firestore_admin.export_documents.jsinclude:samples/generated/v1/firestore_admin.export_documents.jsinclude:samples/generated/v1/firestore_admin.import_documents.jsinclude:samples/generated/v1/firestore_admin.import_documents.jsinclude:samples/generated/v1/firestore_admin.import_documents.jsinclude:samples/generated/v1/firestore_admin.import_documents.jsinclude:samples/generated/v1/firestore_admin.bulk_delete_documents.jsinclude:samples/generated/v1/firestore_admin.bulk_delete_documents.jsinclude:samples/generated/v1/firestore_admin.bulk_delete_documents.jsinclude:samples/generated/v1/firestore_admin.bulk_delete_documents.jsinclude:samples/generated/v1/firestore_admin.create_database.jsinclude:samples/generated/v1/firestore_admin.create_database.jsinclude:samples/generated/v1/firestore_admin.create_database.jsinclude:samples/generated/v1/firestore_admin.create_database.jsinclude:samples/generated/v1/firestore_admin.update_database.jsinclude:samples/generated/v1/firestore_admin.update_database.jsinclude:samples/generated/v1/firestore_admin.update_database.jsinclude:samples/generated/v1/firestore_admin.update_database.jsinclude:samples/generated/v1/firestore_admin.delete_database.jsinclude:samples/generated/v1/firestore_admin.delete_database.jsinclude:samples/generated/v1/firestore_admin.delete_database.jsinclude:samples/generated/v1/firestore_admin.restore_database.jsinclude:samples/generated/v1/firestore_admin.delete_database.jsinclude:samples/generated/v1/firestore_admin.restore_database.jsinclude:samples/generated/v1/firestore_admin.restore_database.jsinclude:samples/generated/v1/firestore_admin.restore_database.jsinclude:samples/generated/v1/firestore_admin.list_indexes.jsinclude:samples/generated/v1/firestore_admin.list_indexes.jsinclude:samples/generated/v1/firestore_admin.list_fields.jsinclude:samples/generated/v1/firestore_admin.list_fields.jsinclude:samples/generated/v1/firestore.get_document.jsinclude:samples/generated/v1/firestore.get_document.jsinclude:samples/generated/v1/firestore.update_document.jsinclude:samples/generated/v1/firestore.update_document.jsinclude:samples/generated/v1/firestore.delete_document.jsinclude:samples/generated/v1/firestore.delete_document.jsinclude:samples/generated/v1/firestore.begin_transaction.jsinclude:samples/generated/v1/firestore.begin_transaction.jsinclude:samples/generated/v1/firestore.commit.jsinclude:samples/generated/v1/firestore.commit.jsinclude:samples/generated/v1/firestore.rollback.jsinclude:samples/generated/v1/firestore.rollback.jsinclude:samples/generated/v1/firestore.batch_write.jsinclude:samples/generated/v1/firestore.batch_write.jsinclude:samples/generated/v1/firestore.create_document.jsinclude:samples/generated/v1/firestore.create_document.jsinclude:samples/generated/v1/firestore.batch_get_documents.jsinclude:samples/generated/v1/firestore.batch_get_documents.jsinclude:samples/generated/v1/firestore.run_query.jsinclude:samples/generated/v1/firestore.run_query.jsinclude:samples/generated/v1/firestore.execute_pipeline.jsinclude:samples/generated/v1/firestore.run_aggregation_query.jsinclude:samples/generated/v1/firestore.run_aggregation_query.jsinclude:samples/generated/v1/firestore.write.jsinclude:samples/generated/v1/firestore.write.jsinclude:samples/generated/v1/firestore.listen.jsinclude:samples/generated/v1/firestore.listen.jsinclude:samples/generated/v1/firestore.list_documents.jsinclude:samples/generated/v1/firestore.list_documents.jsinclude:samples/generated/v1/firestore.partition_query.jsinclude:samples/generated/v1/firestore.partition_query.jsinclude:samples/generated/v1/firestore.list_collection_ids.jsinclude:samples/generated/v1/firestore.list_collection_ids.jsinclude:samples/generated/v1/firestore_admin.get_index.jsinclude:samples/generated/v1/firestore_admin.get_index.jsinclude:samples/generated/v1/firestore_admin.delete_index.jsinclude:samples/generated/v1/firestore_admin.delete_index.jsinclude:samples/generated/v1/firestore_admin.get_field.jsinclude:samples/generated/v1/firestore_admin.get_field.jsinclude:samples/generated/v1/firestore_admin.get_database.jsinclude:samples/generated/v1/firestore_admin.get_database.jsinclude:samples/generated/v1/firestore_admin.list_databases.jsinclude:samples/generated/v1/firestore_admin.list_databases.jsinclude:samples/generated/v1/firestore_admin.create_user_creds.jsinclude:samples/generated/v1/firestore_admin.create_user_creds.jsinclude:samples/generated/v1/firestore_admin.get_user_creds.jsinclude:samples/generated/v1/firestore_admin.get_user_creds.jsinclude:samples/generated/v1/firestore_admin.list_user_creds.jsinclude:samples/generated/v1/firestore_admin.list_user_creds.jsinclude:samples/generated/v1/firestore_admin.enable_user_creds.jsinclude:samples/generated/v1/firestore_admin.enable_user_creds.jsinclude:samples/generated/v1/firestore_admin.disable_user_creds.jsinclude:samples/generated/v1/firestore_admin.disable_user_creds.jsinclude:samples/generated/v1/firestore_admin.reset_user_password.jsinclude:samples/generated/v1/firestore_admin.reset_user_password.jsinclude:samples/generated/v1/firestore_admin.delete_user_creds.jsinclude:samples/generated/v1/firestore_admin.delete_user_creds.jsinclude:samples/generated/v1/firestore_admin.get_backup.jsinclude:samples/generated/v1/firestore_admin.get_backup.jsinclude:samples/generated/v1/firestore_admin.list_backups.jsinclude:samples/generated/v1/firestore_admin.list_backups.jsinclude:samples/generated/v1/firestore_admin.delete_backup.jsinclude:samples/generated/v1/firestore_admin.delete_backup.jsinclude:samples/generated/v1/firestore_admin.create_backup_schedule.jsinclude:samples/generated/v1/firestore_admin.create_backup_schedule.jsinclude:samples/generated/v1/firestore_admin.get_backup_schedule.jsinclude:samples/generated/v1/firestore_admin.get_backup_schedule.jsinclude:samples/generated/v1/firestore_admin.list_backup_schedules.jsinclude:samples/generated/v1/firestore_admin.list_backup_schedules.jsinclude:samples/generated/v1/firestore_admin.update_backup_schedule.jsinclude:samples/generated/v1/firestore_admin.update_backup_schedule.jsinclude:samples/generated/v1/firestore_admin.delete_backup_schedule.jsinclude:samples/generated/v1/firestore_admin.delete_backup_schedule.jsinclude:samples/generated/v1/firestore_admin.create_index.jsinclude:samples/generated/v1/firestore_admin.create_index.jsinclude:samples/generated/v1/firestore_admin.create_index.jsinclude:samples/generated/v1/firestore_admin.create_index.jsinclude:samples/generated/v1/firestore_admin.update_field.jsinclude:samples/generated/v1/firestore_admin.update_field.jsinclude:samples/generated/v1/firestore_admin.update_field.jsinclude:samples/generated/v1/firestore_admin.update_field.jsinclude:samples/generated/v1/firestore_admin.export_documents.jsinclude:samples/generated/v1/firestore_admin.export_documents.jsinclude:samples/generated/v1/firestore_admin.export_documents.jsinclude:samples/generated/v1/firestore_admin.export_documents.jsinclude:samples/generated/v1/firestore_admin.import_documents.jsinclude:samples/generated/v1/firestore_admin.import_documents.jsinclude:samples/generated/v1/firestore_admin.import_documents.jsinclude:samples/generated/v1/firestore_admin.import_documents.jsinclude:samples/generated/v1/firestore_admin.bulk_delete_documents.jsinclude:samples/generated/v1/firestore_admin.bulk_delete_documents.jsinclude:samples/generated/v1/firestore_admin.bulk_delete_documents.jsinclude:samples/generated/v1/firestore_admin.bulk_delete_documents.jsinclude:samples/generated/v1/firestore_admin.create_database.jsinclude:samples/generated/v1/firestore_admin.create_database.jsinclude:samples/generated/v1/firestore_admin.create_database.jsinclude:samples/generated/v1/firestore_admin.create_database.jsinclude:samples/generated/v1/firestore_admin.update_database.jsinclude:samples/generated/v1/firestore_admin.update_database.jsinclude:samples/generated/v1/firestore_admin.update_database.jsinclude:samples/generated/v1/firestore_admin.update_database.jsinclude:samples/generated/v1/firestore_admin.delete_database.jsinclude:samples/generated/v1/firestore_admin.delete_database.jsinclude:samples/generated/v1/firestore_admin.delete_database.jsinclude:samples/generated/v1/firestore_admin.delete_database.jsinclude:samples/generated/v1/firestore_admin.restore_database.jsinclude:samples/generated/v1/firestore_admin.restore_database.jsinclude:samples/generated/v1/firestore_admin.restore_database.jsinclude:samples/generated/v1/firestore_admin.restore_database.jsinclude:samples/generated/v1/firestore_admin.list_indexes.jsinclude:samples/generated/v1/firestore_admin.list_indexes.jsinclude:samples/generated/v1/firestore_admin.list_fields.jsinclude:samples/generated/v1/firestore_admin.list_fields.jsinclude:samples/generated/v1/firestore.get_document.jsinclude:samples/generated/v1/firestore.get_document.jsinclude:samples/generated/v1/firestore.update_document.jsinclude:samples/generated/v1/firestore.update_document.jsinclude:samples/generated/v1/firestore.delete_document.jsinclude:samples/generated/v1/firestore.delete_document.jsinclude:samples/generated/v1/firestore.begin_transaction.jsinclude:samples/generated/v1/firestore.begin_transaction.jsinclude:samples/generated/v1/firestore.commit.jsinclude:samples/generated/v1/firestore.commit.jsinclude:samples/generated/v1/firestore.rollback.jsinclude:samples/generated/v1/firestore.rollback.jsinclude:samples/generated/v1/firestore.batch_write.jsinclude:samples/generated/v1/firestore.batch_write.jsinclude:samples/generated/v1/firestore.create_document.jsinclude:samples/generated/v1/firestore.create_document.jsinclude:samples/generated/v1/firestore.batch_get_documents.jsinclude:samples/generated/v1/firestore.batch_get_documents.jsinclude:samples/generated/v1/firestore.run_query.jsinclude:samples/generated/v1/firestore.run_query.jsinclude:samples/generated/v1/firestore.execute_pipeline.jsinclude:samples/generated/v1/firestore.execute_pipeline.jsinclude:samples/generated/v1/firestore.run_aggregation_query.jsinclude:samples/generated/v1/firestore.run_aggregation_query.jsinclude:samples/generated/v1/firestore.write.jsinclude:samples/generated/v1/firestore.write.jsinclude:samples/generated/v1/firestore.listen.jsinclude:samples/generated/v1/firestore.listen.jsinclude:samples/generated/v1/firestore.list_documents.jsinclude:samples/generated/v1/firestore.list_documents.jsinclude:samples/generated/v1/firestore.partition_query.jsinclude:samples/generated/v1/firestore.partition_query.jsinclude:samples/generated/v1/firestore.list_collection_ids.jsinclude:samples/generated/v1/firestore.list_collection_ids.js